Prefer list1 (X) to Fcons (X, Qnil) when building lists.
[bpt/emacs.git] / src / image.c
CommitLineData
4ef0d4d0 1/* Functions for image support on window system.
32d72c2f 2
ab422c4d 3Copyright (C) 1989, 1992-2013 Free Software Foundation, Inc.
4ef0d4d0
KS
4
5This file is part of GNU Emacs.
6
9ec0b715 7GNU Emacs is free software: you can redistribute it and/or modify
4ef0d4d0 8it under the terms of the GNU General Public License as published by
9ec0b715
GM
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
4ef0d4d0
KS
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
9ec0b715 18along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
4ef0d4d0
KS
19
20#include <config.h>
406af475 21#include "sysstdio.h"
4ef0d4d0 22#include <unistd.h>
4ef0d4d0 23
d7306fe6
DN
24#ifdef HAVE_PNG
25#if defined HAVE_LIBPNG_PNG_H
26# include <libpng/png.h>
27#else
28# include <png.h>
29#endif
285d07e2 30#endif
d7306fe6 31
c3417a74
DN
32#include <setjmp.h>
33
620f13b0
PE
34#include <c-ctype.h>
35
4ef0d4d0
KS
36/* This makes the fields of a Display accessible, in Xlib header files. */
37
38#define XLIB_ILLEGAL_ACCESS
39
40#include "lisp.h"
41#include "frame.h"
42#include "window.h"
43#include "dispextern.h"
44#include "blockinput.h"
45#include "systime.h"
46#include <epaths.h>
3dcc8b84 47#include "character.h"
022af124 48#include "coding.h"
6087292e 49#include "termhooks.h"
3dcc8b84 50#include "font.h"
4ef0d4d0 51
17a2cbbd 52#ifdef HAVE_SYS_STAT_H
4ef0d4d0 53#include <sys/stat.h>
17a2cbbd
DC
54#endif /* HAVE_SYS_STAT_H */
55
56#ifdef HAVE_SYS_TYPES_H
57#include <sys/types.h>
58#endif /* HAVE_SYS_TYPES_H */
59
60#ifdef HAVE_WINDOW_SYSTEM
61#include TERM_HEADER
62#endif /* HAVE_WINDOW_SYSTEM */
4ef0d4d0 63
17a2cbbd 64#ifdef HAVE_X_WINDOWS
4ef0d4d0
KS
65#define COLOR_TABLE_SUPPORT 1
66
67typedef struct x_bitmap_record Bitmap_Record;
5e617bc2 68#define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
4ef0d4d0 69#define NO_PIXMAP None
4ef0d4d0 70
9ecf6403
YM
71#define PIX_MASK_RETAIN 0
72#define PIX_MASK_DRAW 1
4ef0d4d0
KS
73#endif /* HAVE_X_WINDOWS */
74
4ef0d4d0 75#ifdef HAVE_NTGUI
a9e7a9d5
PE
76
77/* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
78#ifdef WINDOWSNT
0fda9b75 79# include "w32.h"
a9e7a9d5
PE
80#endif
81
4ef0d4d0
KS
82/* W32_TODO : Color tables on W32. */
83#undef COLOR_TABLE_SUPPORT
84
85typedef struct w32_bitmap_record Bitmap_Record;
5e617bc2 86#define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
4ef0d4d0 87#define NO_PIXMAP 0
4ef0d4d0 88
9ecf6403
YM
89#define PIX_MASK_RETAIN 0
90#define PIX_MASK_DRAW 1
4ef0d4d0 91
4ef0d4d0
KS
92#define x_defined_color w32_defined_color
93#define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
8b7d0a16 94
5be1c984
EZ
95/* Version of libpng that we were compiled with, or -1 if no PNG
96 support was compiled in. This is tested by w32-win.el to correctly
97 set up the alist used to search for PNG libraries. */
98Lisp_Object Qlibpng_version;
4ef0d4d0
KS
99#endif /* HAVE_NTGUI */
100
edfda783 101#ifdef HAVE_NS
edfda783
AR
102#undef COLOR_TABLE_SUPPORT
103
104typedef struct ns_bitmap_record Bitmap_Record;
105
5e617bc2 106#define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
edfda783
AR
107#define NO_PIXMAP 0
108
edfda783
AR
109#define PIX_MASK_RETAIN 0
110#define PIX_MASK_DRAW 1
111
edfda783
AR
112#define x_defined_color(f, name, color_def, alloc) \
113 ns_defined_color (f, name, color_def, alloc, 0)
9e50ff0c 114#define DefaultDepthOfScreen(screen) x_display_list->n_planes
edfda783
AR
115#endif /* HAVE_NS */
116
117
97ec208f
DN
118/* The symbol `postscript' identifying images of this type. */
119
955cbe7b 120static Lisp_Object Qpostscript;
4ef0d4d0 121
f57e2426
J
122static void x_disable_image (struct frame *, struct image *);
123static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
124 Lisp_Object);
4ef0d4d0 125
f57e2426
J
126static void init_color_table (void);
127static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
4ef0d4d0 128#ifdef COLOR_TABLE_SUPPORT
f57e2426
J
129static void free_color_table (void);
130static unsigned long *colors_in_color_table (int *n);
4ef0d4d0
KS
131#endif
132
9c90cc06 133static Lisp_Object QCmax_width, QCmax_height;
f3f9606c 134
4ef0d4d0
KS
135/* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
136 id, which is just an int that this section returns. Bitmaps are
137 reference counted so they can be shared among frames.
138
139 Bitmap indices are guaranteed to be > 0, so a negative number can
140 be used to indicate no bitmap.
141
142 If you use x_create_bitmap_from_data, then you must keep track of
143 the bitmaps yourself. That is, creating a bitmap from the same
144 data more than once will not be caught. */
145
edfda783 146#ifdef HAVE_NS
bad98418 147/* Use with images created by ns_image_for_XPM. */
edfda783
AR
148unsigned long
149XGetPixel (XImagePtr ximage, int x, int y)
150{
ed3751c8 151 return ns_get_pixel (ximage, x, y);
edfda783
AR
152}
153
bad98418
PE
154/* Use with images created by ns_image_for_XPM; alpha set to 1;
155 pixel is assumed to be in RGB form. */
edfda783
AR
156void
157XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
158{
ed3751c8 159 ns_put_pixel (ximage, x, y, pixel);
edfda783
AR
160}
161#endif /* HAVE_NS */
162
4ef0d4d0
KS
163
164/* Functions to access the contents of a bitmap, given an id. */
165
166int
0766b489 167x_bitmap_height (FRAME_PTR f, ptrdiff_t id)
4ef0d4d0
KS
168{
169 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
170}
171
172int
0766b489 173x_bitmap_width (FRAME_PTR f, ptrdiff_t id)
4ef0d4d0
KS
174{
175 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
176}
177
178#if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
62aba0d4 179ptrdiff_t
0766b489 180x_bitmap_pixmap (FRAME_PTR f, ptrdiff_t id)
4ef0d4d0 181{
f6cfbd8f 182 /* HAVE_NTGUI needs the explicit cast here. */
62aba0d4 183 return (ptrdiff_t) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
4ef0d4d0
KS
184}
185#endif
186
187#ifdef HAVE_X_WINDOWS
188int
0766b489 189x_bitmap_mask (FRAME_PTR f, ptrdiff_t id)
4ef0d4d0
KS
190{
191 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
192}
193#endif
194
195/* Allocate a new bitmap record. Returns index of new record. */
196
0766b489 197static ptrdiff_t
d3da34e0 198x_allocate_bitmap_record (FRAME_PTR f)
4ef0d4d0
KS
199{
200 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
0766b489 201 ptrdiff_t i;
4ef0d4d0 202
4ef0d4d0
KS
203 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
204 return ++dpyinfo->bitmaps_last;
205
206 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
207 if (dpyinfo->bitmaps[i].refcount == 0)
208 return i + 1;
209
a69fbedb
PE
210 dpyinfo->bitmaps =
211 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
212 10, -1, sizeof *dpyinfo->bitmaps);
4ef0d4d0
KS
213 return ++dpyinfo->bitmaps_last;
214}
215
216/* Add one reference to the reference count of the bitmap with id ID. */
217
218void
13464394 219x_reference_bitmap (FRAME_PTR f, ptrdiff_t id)
4ef0d4d0
KS
220{
221 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
222}
223
224/* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
225
0766b489 226ptrdiff_t
d3da34e0 227x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
4ef0d4d0
KS
228{
229 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
0766b489 230 ptrdiff_t id;
4ef0d4d0
KS
231
232#ifdef HAVE_X_WINDOWS
233 Pixmap bitmap;
234 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
235 bits, width, height);
236 if (! bitmap)
237 return -1;
238#endif /* HAVE_X_WINDOWS */
239
240#ifdef HAVE_NTGUI
241 Pixmap bitmap;
242 bitmap = CreateBitmap (width, height,
243 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
244 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
245 bits);
246 if (! bitmap)
247 return -1;
248#endif /* HAVE_NTGUI */
249
edfda783 250#ifdef HAVE_NS
ed3751c8 251 void *bitmap = ns_image_from_XBM (bits, width, height);
edfda783
AR
252 if (!bitmap)
253 return -1;
254#endif
255
4ef0d4d0 256 id = x_allocate_bitmap_record (f);
4ef0d4d0 257
edfda783
AR
258#ifdef HAVE_NS
259 dpyinfo->bitmaps[id - 1].img = bitmap;
260 dpyinfo->bitmaps[id - 1].depth = 1;
261#endif
262
4ef0d4d0
KS
263 dpyinfo->bitmaps[id - 1].file = NULL;
264 dpyinfo->bitmaps[id - 1].height = height;
265 dpyinfo->bitmaps[id - 1].width = width;
266 dpyinfo->bitmaps[id - 1].refcount = 1;
267
268#ifdef HAVE_X_WINDOWS
269 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
270 dpyinfo->bitmaps[id - 1].have_mask = 0;
271 dpyinfo->bitmaps[id - 1].depth = 1;
272#endif /* HAVE_X_WINDOWS */
273
274#ifdef HAVE_NTGUI
275 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
276 dpyinfo->bitmaps[id - 1].hinst = NULL;
277 dpyinfo->bitmaps[id - 1].depth = 1;
278#endif /* HAVE_NTGUI */
279
280 return id;
281}
282
283/* Create bitmap from file FILE for frame F. */
284
0766b489 285ptrdiff_t
d3da34e0 286x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
4ef0d4d0 287{
edfda783
AR
288 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
289
4ef0d4d0
KS
290#ifdef HAVE_NTGUI
291 return -1; /* W32_TODO : bitmap support */
292#endif /* HAVE_NTGUI */
293
edfda783 294#ifdef HAVE_NS
0766b489 295 ptrdiff_t id;
ed3751c8 296 void *bitmap = ns_image_from_file (file);
edfda783
AR
297
298 if (!bitmap)
299 return -1;
300
301
302 id = x_allocate_bitmap_record (f);
303 dpyinfo->bitmaps[id - 1].img = bitmap;
304 dpyinfo->bitmaps[id - 1].refcount = 1;
23f86fce 305 dpyinfo->bitmaps[id - 1].file = xmalloc (SBYTES (file) + 1);
edfda783 306 dpyinfo->bitmaps[id - 1].depth = 1;
ed3751c8
JB
307 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
308 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
6045c4fd 309 strcpy (dpyinfo->bitmaps[id - 1].file, SSDATA (file));
edfda783
AR
310 return id;
311#endif
312
4ef0d4d0 313#ifdef HAVE_X_WINDOWS
4ef0d4d0
KS
314 unsigned int width, height;
315 Pixmap bitmap;
0766b489
PE
316 int xhot, yhot, result;
317 ptrdiff_t id;
4ef0d4d0 318 Lisp_Object found;
4ef0d4d0
KS
319 char *filename;
320
321 /* Look for an existing bitmap with the same name. */
322 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
323 {
324 if (dpyinfo->bitmaps[id].refcount
325 && dpyinfo->bitmaps[id].file
51b59d79 326 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
4ef0d4d0
KS
327 {
328 ++dpyinfo->bitmaps[id].refcount;
329 return id + 1;
330 }
331 }
332
333 /* Search bitmap-file-path for the file, if appropriate. */
a773ed9a 334 if (openp (Vx_bitmap_file_path, file, Qnil, &found, make_number (R_OK)) < 0)
4ef0d4d0 335 return -1;
4ef0d4d0 336
51b59d79 337 filename = SSDATA (found);
4ef0d4d0
KS
338
339 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
340 filename, &width, &height, &bitmap, &xhot, &yhot);
341 if (result != BitmapSuccess)
342 return -1;
343
344 id = x_allocate_bitmap_record (f);
345 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
346 dpyinfo->bitmaps[id - 1].have_mask = 0;
347 dpyinfo->bitmaps[id - 1].refcount = 1;
23f86fce 348 dpyinfo->bitmaps[id - 1].file = xmalloc (SBYTES (file) + 1);
4ef0d4d0
KS
349 dpyinfo->bitmaps[id - 1].depth = 1;
350 dpyinfo->bitmaps[id - 1].height = height;
351 dpyinfo->bitmaps[id - 1].width = width;
42a5b22f 352 strcpy (dpyinfo->bitmaps[id - 1].file, SSDATA (file));
4ef0d4d0
KS
353
354 return id;
355#endif /* HAVE_X_WINDOWS */
356}
357
358/* Free bitmap B. */
359
360static void
d3da34e0 361free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
4ef0d4d0
KS
362{
363#ifdef HAVE_X_WINDOWS
364 XFreePixmap (dpyinfo->display, bm->pixmap);
365 if (bm->have_mask)
366 XFreePixmap (dpyinfo->display, bm->mask);
367#endif /* HAVE_X_WINDOWS */
368
369#ifdef HAVE_NTGUI
370 DeleteObject (bm->pixmap);
371#endif /* HAVE_NTGUI */
372
edfda783 373#ifdef HAVE_NS
ed3751c8 374 ns_release_object (bm->img);
edfda783
AR
375#endif
376
4ef0d4d0
KS
377 if (bm->file)
378 {
379 xfree (bm->file);
380 bm->file = NULL;
381 }
382}
383
384/* Remove reference to bitmap with id number ID. */
385
386void
0766b489 387x_destroy_bitmap (FRAME_PTR f, ptrdiff_t id)
4ef0d4d0
KS
388{
389 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
390
391 if (id > 0)
392 {
393 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
394
395 if (--bm->refcount == 0)
396 {
4d7e6e51 397 block_input ();
65342ae3 398 free_bitmap_record (dpyinfo, bm);
4d7e6e51 399 unblock_input ();
4ef0d4d0
KS
400 }
401 }
402}
403
404/* Free all the bitmaps for the display specified by DPYINFO. */
405
406void
d3da34e0 407x_destroy_all_bitmaps (Display_Info *dpyinfo)
4ef0d4d0 408{
0766b489 409 ptrdiff_t i;
4ef0d4d0
KS
410 Bitmap_Record *bm = dpyinfo->bitmaps;
411
412 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
413 if (bm->refcount > 0)
65342ae3 414 free_bitmap_record (dpyinfo, bm);
4ef0d4d0
KS
415
416 dpyinfo->bitmaps_last = 0;
417}
418
578098f3
PE
419static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
420 XImagePtr *, Pixmap *);
421static void x_destroy_x_image (XImagePtr ximg);
4ef0d4d0 422
547c9269
YM
423#ifdef HAVE_NTGUI
424static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
425 bool, HGDIOBJ *);
426static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
427 HGDIOBJ);
428#else
429static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
430static void image_unget_x_image (struct image *, bool, XImagePtr);
431#define image_get_x_image_or_dc(f, img, mask_p, dummy) \
432 image_get_x_image (f, img, mask_p)
433#define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
434 image_unget_x_image (img, mask_p, ximg)
435#endif
436
4ef0d4d0
KS
437#ifdef HAVE_X_WINDOWS
438
547c9269
YM
439static void image_sync_to_pixmaps (struct frame *, struct image *);
440
4ef0d4d0
KS
441/* Useful functions defined in the section
442 `Image type independent image structures' below. */
443
f57e2426
J
444static unsigned long four_corners_best (XImagePtr ximg,
445 int *corners,
446 unsigned long width,
447 unsigned long height);
4ef0d4d0 448
4ef0d4d0
KS
449
450/* Create a mask of a bitmap. Note is this not a perfect mask.
451 It's nicer with some borders in this context */
452
578098f3 453void
0766b489 454x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
4ef0d4d0
KS
455{
456 Pixmap pixmap, mask;
457 XImagePtr ximg, mask_img;
458 unsigned long width, height;
578098f3 459 bool result;
4ef0d4d0
KS
460 unsigned long bg;
461 unsigned long x, y, xp, xm, yp, ym;
462 GC gc;
463
464 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
465
466 if (!(id > 0))
578098f3 467 return;
4ef0d4d0
KS
468
469 pixmap = x_bitmap_pixmap (f, id);
470 width = x_bitmap_width (f, id);
471 height = x_bitmap_height (f, id);
472
4d7e6e51 473 block_input ();
4ef0d4d0
KS
474 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
475 ~0, ZPixmap);
476
477 if (!ximg)
478 {
4d7e6e51 479 unblock_input ();
578098f3 480 return;
4ef0d4d0
KS
481 }
482
483 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
484
4d7e6e51 485 unblock_input ();
4ef0d4d0
KS
486 if (!result)
487 {
488 XDestroyImage (ximg);
578098f3 489 return;
4ef0d4d0
KS
490 }
491
6ac3c7bb 492 bg = four_corners_best (ximg, NULL, width, height);
4ef0d4d0
KS
493
494 for (y = 0; y < ximg->height; ++y)
495 {
496 for (x = 0; x < ximg->width; ++x)
497 {
498 xp = x != ximg->width - 1 ? x + 1 : 0;
499 xm = x != 0 ? x - 1 : ximg->width - 1;
500 yp = y != ximg->height - 1 ? y + 1 : 0;
501 ym = y != 0 ? y - 1 : ximg->height - 1;
502 if (XGetPixel (ximg, x, y) == bg
503 && XGetPixel (ximg, x, yp) == bg
504 && XGetPixel (ximg, x, ym) == bg
505 && XGetPixel (ximg, xp, y) == bg
506 && XGetPixel (ximg, xp, yp) == bg
507 && XGetPixel (ximg, xp, ym) == bg
508 && XGetPixel (ximg, xm, y) == bg
509 && XGetPixel (ximg, xm, yp) == bg
510 && XGetPixel (ximg, xm, ym) == bg)
511 XPutPixel (mask_img, x, y, 0);
512 else
513 XPutPixel (mask_img, x, y, 1);
514 }
515 }
516
4d7e6e51 517 eassert (input_blocked_p ());
4ef0d4d0
KS
518 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
519 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
520 width, height);
521 XFreeGC (FRAME_X_DISPLAY (f), gc);
522
523 dpyinfo->bitmaps[id - 1].have_mask = 1;
524 dpyinfo->bitmaps[id - 1].mask = mask;
525
526 XDestroyImage (ximg);
527 x_destroy_x_image (mask_img);
4ef0d4d0
KS
528}
529
530#endif /* HAVE_X_WINDOWS */
531
532
533/***********************************************************************
534 Image types
535 ***********************************************************************/
536
4ef0d4d0
KS
537/* List of supported image types. Use define_image_type to add new
538 types. Use lookup_image_type to find a type for a given symbol. */
539
540static struct image_type *image_types;
541
542/* The symbol `xbm' which is used as the type symbol for XBM images. */
543
955cbe7b 544static Lisp_Object Qxbm;
4ef0d4d0
KS
545
546/* Keywords. */
547
955cbe7b 548Lisp_Object QCascent, QCmargin, QCrelief;
955cbe7b
PE
549Lisp_Object QCconversion;
550static Lisp_Object QCheuristic_mask;
551static Lisp_Object QCcolor_symbols;
552static Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry;
553static Lisp_Object QCcrop, QCrotation;
4ef0d4d0
KS
554
555/* Other symbols. */
556
1100a63c 557static Lisp_Object Qcount, Qextension_data, Qdelay;
955cbe7b 558static Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
4ef0d4d0 559
578098f3 560/* Forward function prototypes. */
4ef0d4d0 561
641cfd14 562static struct image_type *lookup_image_type (Lisp_Object);
f57e2426
J
563static void x_laplace (struct frame *, struct image *);
564static void x_emboss (struct frame *, struct image *);
578098f3 565static void x_build_heuristic_mask (struct frame *, struct image *,
36a305a7 566 Lisp_Object);
0fda9b75
DC
567#ifdef WINDOWSNT
568extern Lisp_Object Vlibrary_cache;
0855eb52 569#define CACHE_IMAGE_TYPE(type, status) \
0898ca10 570 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
84d358f0
JB
571#else
572#define CACHE_IMAGE_TYPE(type, status)
a9e7a9d5 573#endif
0855eb52
JB
574
575#define ADD_IMAGE_TYPE(type) \
576 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
4ef0d4d0
KS
577
578/* Define a new image type from TYPE. This adds a copy of TYPE to
0855eb52 579 image_types and caches the loading status of TYPE. */
4ef0d4d0 580
bb4d86b4 581static struct image_type *
d07ff9db 582define_image_type (struct image_type *type)
4ef0d4d0 583{
bb4d86b4
CY
584 struct image_type *p = NULL;
585 Lisp_Object target_type = *type->type;
578098f3 586 bool type_valid = 1;
0855eb52 587
4d7e6e51 588 block_input ();
bb4d86b4
CY
589
590 for (p = image_types; p; p = p->next)
591 if (EQ (*p->type, target_type))
592 goto done;
593
594 if (type->init)
0855eb52 595 {
a9e7a9d5 596#if defined HAVE_NTGUI && defined WINDOWSNT
bb4d86b4
CY
597 /* If we failed to load the library before, don't try again. */
598 Lisp_Object tested = Fassq (target_type, Vlibrary_cache);
599 if (CONSP (tested) && NILP (XCDR (tested)))
600 type_valid = 0;
601 else
602#endif
603 {
d07ff9db 604 type_valid = type->init ();
bb4d86b4
CY
605 CACHE_IMAGE_TYPE (target_type, type_valid ? Qt : Qnil);
606 }
607 }
09c01941 608
bb4d86b4 609 if (type_valid)
0855eb52
JB
610 {
611 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
612 The initialized data segment is read-only. */
09c01941 613 p = xmalloc (sizeof *p);
ae1d87e2 614 *p = *type;
0855eb52
JB
615 p->next = image_types;
616 image_types = p;
0855eb52
JB
617 }
618
bb4d86b4 619 done:
4d7e6e51 620 unblock_input ();
bb4d86b4 621 return p;
4ef0d4d0
KS
622}
623
624
578098f3 625/* Value is true if OBJECT is a valid Lisp image specification. A
4ef0d4d0
KS
626 valid image specification is a list whose car is the symbol
627 `image', and whose rest is a property list. The property list must
628 contain a value for key `:type'. That value must be the name of a
629 supported image type. The rest of the property list depends on the
630 image type. */
631
578098f3 632bool
d3da34e0 633valid_image_p (Lisp_Object object)
4ef0d4d0 634{
578098f3 635 bool valid_p = 0;
4ef0d4d0
KS
636
637 if (IMAGEP (object))
638 {
639 Lisp_Object tem;
640
641 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
642 if (EQ (XCAR (tem), QCtype))
643 {
644 tem = XCDR (tem);
645 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
646 {
647 struct image_type *type;
648 type = lookup_image_type (XCAR (tem));
649 if (type)
650 valid_p = type->valid_p (object);
651 }
652
653 break;
654 }
655 }
656
657 return valid_p;
658}
659
660
661/* Log error message with format string FORMAT and argument ARG.
662 Signaling an error, e.g. when an image cannot be loaded, is not a
663 good idea because this would interrupt redisplay, and the error
664 message display would lead to another redisplay. This function
665 therefore simply displays a message. */
666
667static void
675e2c69 668image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
4ef0d4d0
KS
669{
670 add_to_log (format, arg1, arg2);
671}
672
673
674\f
675/***********************************************************************
676 Image specifications
677 ***********************************************************************/
678
679enum image_value_type
680{
681 IMAGE_DONT_CHECK_VALUE_TYPE,
682 IMAGE_STRING_VALUE,
683 IMAGE_STRING_OR_NIL_VALUE,
684 IMAGE_SYMBOL_VALUE,
685 IMAGE_POSITIVE_INTEGER_VALUE,
c4a07a4c 686 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
4ef0d4d0
KS
687 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
688 IMAGE_ASCENT_VALUE,
689 IMAGE_INTEGER_VALUE,
690 IMAGE_FUNCTION_VALUE,
691 IMAGE_NUMBER_VALUE,
692 IMAGE_BOOL_VALUE
693};
694
695/* Structure used when parsing image specifications. */
696
697struct image_keyword
698{
699 /* Name of keyword. */
675e2c69 700 const char *name;
4ef0d4d0
KS
701
702 /* The type of value allowed. */
703 enum image_value_type type;
704
578098f3
PE
705 /* True means key must be present. */
706 bool mandatory_p;
4ef0d4d0
KS
707
708 /* Used to recognize duplicate keywords in a property list. */
709 int count;
710
711 /* The value that was found. */
712 Lisp_Object value;
713};
714
715
4ef0d4d0
KS
716/* Parse image spec SPEC according to KEYWORDS. A valid image spec
717 has the format (image KEYWORD VALUE ...). One of the keyword/
718 value pairs must be `:type TYPE'. KEYWORDS is a vector of
719 image_keywords structures of size NKEYWORDS describing other
578098f3 720 allowed keyword/value pairs. Value is true if SPEC is valid. */
4ef0d4d0 721
578098f3 722static bool
d3da34e0
JB
723parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
724 int nkeywords, Lisp_Object type)
4ef0d4d0
KS
725{
726 int i;
727 Lisp_Object plist;
728
729 if (!IMAGEP (spec))
730 return 0;
731
732 plist = XCDR (spec);
733 while (CONSP (plist))
734 {
735 Lisp_Object key, value;
736
737 /* First element of a pair must be a symbol. */
738 key = XCAR (plist);
739 plist = XCDR (plist);
740 if (!SYMBOLP (key))
741 return 0;
742
743 /* There must follow a value. */
744 if (!CONSP (plist))
745 return 0;
746 value = XCAR (plist);
747 plist = XCDR (plist);
748
749 /* Find key in KEYWORDS. Error if not found. */
750 for (i = 0; i < nkeywords; ++i)
42a5b22f 751 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
4ef0d4d0
KS
752 break;
753
754 if (i == nkeywords)
755 continue;
756
757 /* Record that we recognized the keyword. If a keywords
758 was found more than once, it's an error. */
759 keywords[i].value = value;
4ef0d4d0
KS
760 if (keywords[i].count > 1)
761 return 0;
d311d28c 762 ++keywords[i].count;
4ef0d4d0
KS
763
764 /* Check type of value against allowed type. */
765 switch (keywords[i].type)
766 {
767 case IMAGE_STRING_VALUE:
768 if (!STRINGP (value))
769 return 0;
770 break;
771
772 case IMAGE_STRING_OR_NIL_VALUE:
773 if (!STRINGP (value) && !NILP (value))
774 return 0;
775 break;
776
777 case IMAGE_SYMBOL_VALUE:
778 if (!SYMBOLP (value))
779 return 0;
780 break;
781
782 case IMAGE_POSITIVE_INTEGER_VALUE:
13464394 783 if (! RANGED_INTEGERP (1, value, INT_MAX))
4ef0d4d0
KS
784 return 0;
785 break;
786
c4a07a4c
PE
787 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
788 if (RANGED_INTEGERP (0, value, INT_MAX))
4ef0d4d0
KS
789 break;
790 if (CONSP (value)
c4a07a4c
PE
791 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
792 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
4ef0d4d0
KS
793 break;
794 return 0;
795
796 case IMAGE_ASCENT_VALUE:
797 if (SYMBOLP (value) && EQ (value, Qcenter))
798 break;
13464394 799 else if (RANGED_INTEGERP (0, value, 100))
4ef0d4d0
KS
800 break;
801 return 0;
802
803 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
13464394
PE
804 /* Unlike the other integer-related cases, this one does not
805 verify that VALUE fits in 'int'. This is because callers
806 want EMACS_INT. */
4ef0d4d0
KS
807 if (!INTEGERP (value) || XINT (value) < 0)
808 return 0;
809 break;
810
811 case IMAGE_DONT_CHECK_VALUE_TYPE:
812 break;
813
814 case IMAGE_FUNCTION_VALUE:
815 value = indirect_function (value);
ca105506 816 if (!NILP (Ffunctionp (value)))
4ef0d4d0
KS
817 break;
818 return 0;
819
820 case IMAGE_NUMBER_VALUE:
821 if (!INTEGERP (value) && !FLOATP (value))
822 return 0;
823 break;
824
825 case IMAGE_INTEGER_VALUE:
13464394 826 if (! TYPE_RANGED_INTEGERP (int, value))
4ef0d4d0
KS
827 return 0;
828 break;
829
830 case IMAGE_BOOL_VALUE:
831 if (!NILP (value) && !EQ (value, Qt))
832 return 0;
833 break;
834
835 default:
1088b922 836 emacs_abort ();
4ef0d4d0
KS
837 break;
838 }
839
840 if (EQ (key, QCtype) && !EQ (type, value))
841 return 0;
842 }
843
844 /* Check that all mandatory fields are present. */
845 for (i = 0; i < nkeywords; ++i)
846 if (keywords[i].mandatory_p && keywords[i].count == 0)
847 return 0;
848
849 return NILP (plist);
850}
851
852
853/* Return the value of KEY in image specification SPEC. Value is nil
578098f3
PE
854 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
855 was found in SPEC. */
4ef0d4d0
KS
856
857static Lisp_Object
578098f3 858image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
4ef0d4d0
KS
859{
860 Lisp_Object tail;
861
a54e2c05 862 eassert (valid_image_p (spec));
4ef0d4d0
KS
863
864 for (tail = XCDR (spec);
865 CONSP (tail) && CONSP (XCDR (tail));
866 tail = XCDR (XCDR (tail)))
867 {
868 if (EQ (XCAR (tail), key))
869 {
870 if (found)
871 *found = 1;
872 return XCAR (XCDR (tail));
873 }
874 }
875
876 if (found)
877 *found = 0;
878 return Qnil;
879}
880
881
882DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
883 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
884PIXELS non-nil means return the size in pixels, otherwise return the
885size in canonical character units.
886FRAME is the frame on which the image will be displayed. FRAME nil
887or omitted means use the selected frame. */)
5842a27b 888 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
4ef0d4d0
KS
889{
890 Lisp_Object size;
891
892 size = Qnil;
893 if (valid_image_p (spec))
894 {
7452b7bd 895 struct frame *f = decode_window_system_frame (frame);
13464394 896 ptrdiff_t id = lookup_image (f, spec);
4ef0d4d0
KS
897 struct image *img = IMAGE_FROM_ID (f, id);
898 int width = img->width + 2 * img->hmargin;
899 int height = img->height + 2 * img->vmargin;
900
901 if (NILP (pixels))
902 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
903 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
904 else
905 size = Fcons (make_number (width), make_number (height));
906 }
907 else
908 error ("Invalid image specification");
909
910 return size;
911}
912
913
914DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
915 doc: /* Return t if image SPEC has a mask bitmap.
916FRAME is the frame on which the image will be displayed. FRAME nil
917or omitted means use the selected frame. */)
5842a27b 918 (Lisp_Object spec, Lisp_Object frame)
4ef0d4d0
KS
919{
920 Lisp_Object mask;
921
922 mask = Qnil;
923 if (valid_image_p (spec))
924 {
7452b7bd 925 struct frame *f = decode_window_system_frame (frame);
13464394 926 ptrdiff_t id = lookup_image (f, spec);
4ef0d4d0
KS
927 struct image *img = IMAGE_FROM_ID (f, id);
928 if (img->mask)
929 mask = Qt;
930 }
931 else
932 error ("Invalid image specification");
933
934 return mask;
935}
936
1546c559
JL
937DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
938 doc: /* Return metadata for image SPEC.
6ac3c7bb
KS
939FRAME is the frame on which the image will be displayed. FRAME nil
940or omitted means use the selected frame. */)
5842a27b 941 (Lisp_Object spec, Lisp_Object frame)
6ac3c7bb
KS
942{
943 Lisp_Object ext;
944
945 ext = Qnil;
946 if (valid_image_p (spec))
947 {
7452b7bd 948 struct frame *f = decode_window_system_frame (frame);
13464394 949 ptrdiff_t id = lookup_image (f, spec);
6ac3c7bb 950 struct image *img = IMAGE_FROM_ID (f, id);
b50691aa 951 ext = img->lisp_data;
6ac3c7bb
KS
952 }
953
954 return ext;
955}
956
4ef0d4d0
KS
957\f
958/***********************************************************************
959 Image type independent image structures
960 ***********************************************************************/
961
11273115 962#define MAX_IMAGE_SIZE 10.0
4ef0d4d0
KS
963/* Allocate and return a new image structure for image specification
964 SPEC. SPEC has a hash value of HASH. */
965
966static struct image *
0de4bb68 967make_image (Lisp_Object spec, EMACS_UINT hash)
4ef0d4d0 968{
23f86fce 969 struct image *img = xzalloc (sizeof *img);
a2bc5bdd 970 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
4ef0d4d0 971
a54e2c05 972 eassert (valid_image_p (spec));
a2bc5bdd 973 img->dependencies = NILP (file) ? Qnil : list1 (file);
4ef0d4d0 974 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
a54e2c05 975 eassert (img->type != NULL);
4ef0d4d0 976 img->spec = spec;
b50691aa 977 img->lisp_data = Qnil;
4ef0d4d0
KS
978 img->ascent = DEFAULT_IMAGE_ASCENT;
979 img->hash = hash;
6ac3c7bb 980 img->corners[BOT_CORNER] = -1; /* Full image */
4ef0d4d0
KS
981 return img;
982}
983
984
985/* Free image IMG which was used on frame F, including its resources. */
986
987static void
d3da34e0 988free_image (struct frame *f, struct image *img)
4ef0d4d0
KS
989{
990 if (img)
991 {
354884c4 992 struct image_cache *c = FRAME_IMAGE_CACHE (f);
4ef0d4d0
KS
993
994 /* Remove IMG from the hash table of its cache. */
995 if (img->prev)
996 img->prev->next = img->next;
997 else
998 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
999
1000 if (img->next)
1001 img->next->prev = img->prev;
1002
1003 c->images[img->id] = NULL;
1004
1005 /* Free resources, then free IMG. */
1006 img->type->free (f, img);
1007 xfree (img);
1008 }
1009}
1010
578098f3 1011/* Return true if the given widths and heights are valid for display. */
f1f25b99 1012
578098f3 1013static bool
d3da34e0 1014check_image_size (struct frame *f, int width, int height)
f1f25b99 1015{
7df4765a 1016 int w, h;
f1f25b99 1017
7df4765a 1018 if (width <= 0 || height <= 0)
f1f25b99
CY
1019 return 0;
1020
7df4765a 1021 if (INTEGERP (Vmax_image_size))
3f791afe
PE
1022 return (width <= XINT (Vmax_image_size)
1023 && height <= XINT (Vmax_image_size));
7df4765a
KS
1024 else if (FLOATP (Vmax_image_size))
1025 {
e5d76069
PE
1026 if (f != NULL)
1027 {
1028 w = FRAME_PIXEL_WIDTH (f);
1029 h = FRAME_PIXEL_HEIGHT (f);
1030 }
1031 else
1032 w = h = 1024; /* Arbitrary size for unknown frame. */
3f791afe
PE
1033 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1034 && height <= XFLOAT_DATA (Vmax_image_size) * h);
7df4765a
KS
1035 }
1036 else
1037 return 1;
f1f25b99 1038}
4ef0d4d0
KS
1039
1040/* Prepare image IMG for display on frame F. Must be called before
1041 drawing an image. */
1042
1043void
d3da34e0 1044prepare_image_for_display (struct frame *f, struct image *img)
4ef0d4d0 1045{
4ef0d4d0 1046 /* We're about to display IMG, so set its timestamp to `now'. */
e9a9ae03 1047 img->timestamp = current_emacs_time ();
4ef0d4d0
KS
1048
1049 /* If IMG doesn't have a pixmap yet, load it now, using the image
1050 type dependent loader function. */
1051 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
578098f3 1052 img->load_failed_p = ! img->type->load (f, img);
c7fea325 1053
547c9269
YM
1054#ifdef HAVE_X_WINDOWS
1055 if (!img->load_failed_p)
1056 {
1057 block_input ();
1058 image_sync_to_pixmaps (f, img);
1059 unblock_input ();
1060 }
1061#endif
4ef0d4d0
KS
1062}
1063
1064
1065/* Value is the number of pixels for the ascent of image IMG when
1066 drawn in face FACE. */
1067
1068int
d3da34e0 1069image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
4ef0d4d0 1070{
1938bc36 1071 int height;
4ef0d4d0
KS
1072 int ascent;
1073
1938bc36
KS
1074 if (slice->height == img->height)
1075 height = img->height + img->vmargin;
1076 else if (slice->y == 0)
1077 height = slice->height + img->vmargin;
1078 else
1079 height = slice->height;
1080
4ef0d4d0
KS
1081 if (img->ascent == CENTERED_IMAGE_ASCENT)
1082 {
1083 if (face->font)
1084 {
1085#ifdef HAVE_NTGUI
1086 /* W32 specific version. Why?. ++kfs */
5fc9fdeb
JR
1087 ascent = height / 2 - (FONT_DESCENT (face->font)
1088 - FONT_BASE (face->font)) / 2;
4ef0d4d0
KS
1089#else
1090 /* This expression is arranged so that if the image can't be
1091 exactly centered, it will be moved slightly up. This is
1092 because a typical font is `top-heavy' (due to the presence
1093 uppercase letters), so the image placement should err towards
1094 being top-heavy too. It also just generally looks better. */
5e617bc2
JB
1095 ascent = (height + FONT_BASE (face->font)
1096 - FONT_DESCENT (face->font) + 1) / 2;
4ef0d4d0
KS
1097#endif /* HAVE_NTGUI */
1098 }
1099 else
1100 ascent = height / 2;
1101 }
1102 else
13464394 1103 ascent = height * (img->ascent / 100.0);
4ef0d4d0
KS
1104
1105 return ascent;
1106}
1107
1108\f
1109/* Image background colors. */
1110
1111/* Find the "best" corner color of a bitmap.
1112 On W32, XIMG is assumed to a device context with the bitmap selected. */
1113
1114static RGB_PIXEL_COLOR
d3da34e0
JB
1115four_corners_best (XImagePtr_or_DC ximg, int *corners,
1116 unsigned long width, unsigned long height)
4ef0d4d0 1117{
f0c77cd1 1118 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
4ef0d4d0
KS
1119 int i, best_count;
1120
6ac3c7bb
KS
1121 if (corners && corners[BOT_CORNER] >= 0)
1122 {
1123 /* Get the colors at the corner_pixels of ximg. */
1124 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1125 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1126 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1127 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1128 }
1129 else
1130 {
1131 /* Get the colors at the corner_pixels of ximg. */
1132 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1133 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1134 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1135 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1136 }
4ef0d4d0
KS
1137 /* Choose the most frequently found color as background. */
1138 for (i = best_count = 0; i < 4; ++i)
1139 {
1140 int j, n;
1141
1142 for (j = n = 0; j < 4; ++j)
6ac3c7bb 1143 if (corner_pixels[i] == corner_pixels[j])
4ef0d4d0
KS
1144 ++n;
1145
1146 if (n > best_count)
6ac3c7bb 1147 best = corner_pixels[i], best_count = n;
4ef0d4d0
KS
1148 }
1149
1150 return best;
1151}
1152
1153/* Portability macros */
1154
1155#ifdef HAVE_NTGUI
1156
4ef0d4d0
KS
1157#define Free_Pixmap(display, pixmap) \
1158 DeleteObject (pixmap)
1159
edfda783
AR
1160#elif defined (HAVE_NS)
1161
edfda783 1162#define Free_Pixmap(display, pixmap) \
ed3751c8 1163 ns_release_object (pixmap)
edfda783 1164
4ef0d4d0
KS
1165#else
1166
4ef0d4d0
KS
1167#define Free_Pixmap(display, pixmap) \
1168 XFreePixmap (display, pixmap)
1169
edfda783 1170#endif /* !HAVE_NTGUI && !HAVE_NS */
4ef0d4d0
KS
1171
1172
1173/* Return the `background' field of IMG. If IMG doesn't have one yet,
1174 it is guessed heuristically. If non-zero, XIMG is an existing
1175 XImage object (or device context with the image selected on W32) to
1f026899 1176 use for the heuristic. */
4ef0d4d0
KS
1177
1178RGB_PIXEL_COLOR
d3da34e0 1179image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
4ef0d4d0
KS
1180{
1181 if (! img->background_valid)
1182 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1183 {
578098f3 1184 bool free_ximg = !ximg;
4ef0d4d0
KS
1185#ifdef HAVE_NTGUI
1186 HGDIOBJ prev;
1187#endif /* HAVE_NTGUI */
1188
1189 if (free_ximg)
547c9269 1190 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4ef0d4d0 1191
6ac3c7bb 1192 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
4ef0d4d0
KS
1193
1194 if (free_ximg)
547c9269 1195 image_unget_x_image_or_dc (img, 0, ximg, prev);
1f026899 1196
4ef0d4d0
KS
1197 img->background_valid = 1;
1198 }
1199
1200 return img->background;
1201}
1202
1203/* Return the `background_transparent' field of IMG. If IMG doesn't
1204 have one yet, it is guessed heuristically. If non-zero, MASK is an
1205 existing XImage object to use for the heuristic. */
1206
1207int
d3da34e0 1208image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
4ef0d4d0
KS
1209{
1210 if (! img->background_transparent_valid)
1211 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1212 {
1213 if (img->mask)
1214 {
578098f3 1215 bool free_mask = !mask;
4ef0d4d0
KS
1216#ifdef HAVE_NTGUI
1217 HGDIOBJ prev;
1218#endif /* HAVE_NTGUI */
1219
1220 if (free_mask)
547c9269 1221 mask = image_get_x_image_or_dc (f, img, 1, &prev);
4ef0d4d0
KS
1222
1223 img->background_transparent
6ac3c7bb 1224 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
4ef0d4d0
KS
1225
1226 if (free_mask)
547c9269 1227 image_unget_x_image_or_dc (img, 1, mask, prev);
4ef0d4d0
KS
1228 }
1229 else
1230 img->background_transparent = 0;
1231
1232 img->background_transparent_valid = 1;
1233 }
1234
1235 return img->background_transparent;
1236}
1237
1238\f
1239/***********************************************************************
1240 Helper functions for X image types
1241 ***********************************************************************/
1242
547c9269
YM
1243/* Clear X resources of image IMG on frame F according to FLAGS.
1244 FLAGS is bitwise-or of the following masks:
1245 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1246 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1247 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1248 any. */
1249
1250#define CLEAR_IMAGE_PIXMAP (1 << 0)
1251#define CLEAR_IMAGE_MASK (1 << 1)
1252#define CLEAR_IMAGE_COLORS (1 << 2)
4ef0d4d0
KS
1253
1254static void
547c9269 1255x_clear_image_1 (struct frame *f, struct image *img, int flags)
4ef0d4d0 1256{
547c9269 1257 if (flags & CLEAR_IMAGE_PIXMAP)
4ef0d4d0 1258 {
547c9269
YM
1259 if (img->pixmap)
1260 {
1261 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1262 img->pixmap = NO_PIXMAP;
1263 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1264 img->background_valid = 0;
1265 }
1266#ifdef HAVE_X_WINDOWS
1267 if (img->ximg)
1268 {
1269 x_destroy_x_image (img->ximg);
1270 img->ximg = NULL;
1271 img->background_valid = 0;
1272 }
1273#endif
4ef0d4d0
KS
1274 }
1275
547c9269 1276 if (flags & CLEAR_IMAGE_MASK)
4ef0d4d0 1277 {
547c9269
YM
1278 if (img->mask)
1279 {
1280 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1281 img->mask = NO_PIXMAP;
1282 img->background_transparent_valid = 0;
1283 }
1284#ifdef HAVE_X_WINDOWS
1285 if (img->mask_img)
1286 {
1287 x_destroy_x_image (img->mask_img);
1288 img->mask_img = NULL;
1289 img->background_transparent_valid = 0;
1290 }
1291#endif
4ef0d4d0
KS
1292 }
1293
547c9269 1294 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
4ef0d4d0 1295 {
4ef0d4d0
KS
1296 /* W32_TODO: color table support. */
1297#ifdef HAVE_X_WINDOWS
1298 x_free_colors (f, img->colors, img->ncolors);
1299#endif /* HAVE_X_WINDOWS */
1300 xfree (img->colors);
1301 img->colors = NULL;
1302 img->ncolors = 0;
1303 }
c7fea325 1304
4ef0d4d0
KS
1305}
1306
1307/* Free X resources of image IMG which is used on frame F. */
1308
1309static void
d3da34e0 1310x_clear_image (struct frame *f, struct image *img)
4ef0d4d0 1311{
4d7e6e51 1312 block_input ();
547c9269
YM
1313 x_clear_image_1 (f, img,
1314 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
4d7e6e51 1315 unblock_input ();
4ef0d4d0
KS
1316}
1317
1318
1319/* Allocate color COLOR_NAME for image IMG on frame F. If color
1320 cannot be allocated, use DFLT. Add a newly allocated color to
1321 IMG->colors, so that it can be freed again. Value is the pixel
1322 color. */
1323
1324static unsigned long
d3da34e0
JB
1325x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1326 unsigned long dflt)
4ef0d4d0
KS
1327{
1328 XColor color;
1329 unsigned long result;
1330
a54e2c05 1331 eassert (STRINGP (color_name));
4ef0d4d0 1332
3f791afe
PE
1333 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1334 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1335 INT_MAX))
4ef0d4d0
KS
1336 {
1337 /* This isn't called frequently so we get away with simply
1338 reallocating the color vector to the needed size, here. */
ddff3151 1339 ptrdiff_t ncolors = img->ncolors + 1;
38182d90 1340 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
ddff3151
PE
1341 img->colors[ncolors - 1] = color.pixel;
1342 img->ncolors = ncolors;
4ef0d4d0
KS
1343 result = color.pixel;
1344 }
1345 else
1346 result = dflt;
1347
1348 return result;
1349}
1350
1351
1352\f
1353/***********************************************************************
1354 Image Cache
1355 ***********************************************************************/
1356
f57e2426 1357static void cache_image (struct frame *f, struct image *img);
4ef0d4d0
KS
1358
1359/* Return a new, initialized image cache that is allocated from the
1360 heap. Call free_image_cache to free an image cache. */
1361
1362struct image_cache *
d3da34e0 1363make_image_cache (void)
4ef0d4d0 1364{
23f86fce 1365 struct image_cache *c = xzalloc (sizeof *c);
4ef0d4d0
KS
1366 int size;
1367
ddff3151 1368 size = 50;
23f86fce 1369 c->images = xmalloc (size * sizeof *c->images);
ddff3151 1370 c->size = size;
4ef0d4d0 1371 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
23f86fce 1372 c->buckets = xzalloc (size);
4ef0d4d0
KS
1373 return c;
1374}
1375
1376
d3c35d17
CY
1377/* Find an image matching SPEC in the cache, and return it. If no
1378 image is found, return NULL. */
1379static struct image *
0de4bb68 1380search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
483e7ae0 1381{
91be6b66 1382 struct image *img;
354884c4 1383 struct image_cache *c = FRAME_IMAGE_CACHE (f);
483e7ae0
CY
1384 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1385
8198352b
CY
1386 if (!c) return NULL;
1387
d3c35d17
CY
1388 /* If the image spec does not specify a background color, the cached
1389 image must have the same background color as the current frame.
cf26ebe8
CY
1390 The foreground color must also match, for the sake of monochrome
1391 images.
1392
1393 In fact, we could ignore the foreground color matching condition
1394 for color images, or if the image spec specifies :foreground;
1395 similarly we could ignore the background color matching condition
1396 for formats that don't use transparency (such as jpeg), or if the
1397 image spec specifies :background. However, the extra memory
1398 usage is probably negligible in practice, so we don't bother. */
d3c35d17 1399
483e7ae0 1400 for (img = c->buckets[i]; img; img = img->next)
d3c35d17
CY
1401 if (img->hash == hash
1402 && !NILP (Fequal (img->spec, spec))
c5b8e0ea
YM
1403 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1404 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
d3c35d17
CY
1405 break;
1406 return img;
1407}
1408
1409
1410/* Search frame F for an image with spec SPEC, and free it. */
1411
1412static void
d3da34e0 1413uncache_image (struct frame *f, Lisp_Object spec)
d3c35d17
CY
1414{
1415 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1416 if (img)
be3faa80
CY
1417 {
1418 free_image (f, img);
1419 /* As display glyphs may still be referring to the image ID, we
1420 must garbage the frame (Bug#6426). */
1421 SET_FRAME_GARBAGED (f);
1422 }
483e7ae0
CY
1423}
1424
1425
4ef0d4d0
KS
1426/* Free image cache of frame F. Be aware that X frames share images
1427 caches. */
1428
1429void
d3da34e0 1430free_image_cache (struct frame *f)
4ef0d4d0 1431{
354884c4 1432 struct image_cache *c = FRAME_IMAGE_CACHE (f);
4ef0d4d0
KS
1433 if (c)
1434 {
13464394 1435 ptrdiff_t i;
4ef0d4d0
KS
1436
1437 /* Cache should not be referenced by any frame when freed. */
a54e2c05 1438 eassert (c->refcount == 0);
4ef0d4d0
KS
1439
1440 for (i = 0; i < c->used; ++i)
1441 free_image (f, c->images[i]);
1442 xfree (c->images);
1443 xfree (c->buckets);
1444 xfree (c);
354884c4 1445 FRAME_IMAGE_CACHE (f) = NULL;
4ef0d4d0
KS
1446 }
1447}
1448
1449
a2bc5bdd
SM
1450/* Clear image cache of frame F. FILTER=t means free all images.
1451 FILTER=nil means clear only images that haven't been
1452 displayed for some time.
1453 Else, only free the images which have FILTER in their `dependencies'.
1454 Should be called from time to time to reduce the number of loaded images.
1455 If image-cache-eviction-delay is non-nil, this frees images in the cache
1456 which weren't displayed for at least that many seconds. */
4ef0d4d0 1457
ce0ad53d 1458static void
a2bc5bdd 1459clear_image_cache (struct frame *f, Lisp_Object filter)
4ef0d4d0 1460{
354884c4 1461 struct image_cache *c = FRAME_IMAGE_CACHE (f);
4ef0d4d0 1462
98fe5161 1463 if (c)
4ef0d4d0 1464 {
13464394 1465 ptrdiff_t i, nfreed = 0;
4ef0d4d0
KS
1466
1467 /* Block input so that we won't be interrupted by a SIGIO
1468 while being in an inconsistent state. */
4d7e6e51 1469 block_input ();
4ef0d4d0 1470
98fe5161
CY
1471 if (!NILP (filter))
1472 {
1473 /* Filter image cache. */
1474 for (i = 0; i < c->used; ++i)
1475 {
1476 struct image *img = c->images[i];
1477 if (img && (EQ (Qt, filter)
1478 || !NILP (Fmember (filter, img->dependencies))))
1479 {
1480 free_image (f, img);
1481 ++nfreed;
1482 }
1483 }
1484 }
1485 else if (INTEGERP (Vimage_cache_eviction_delay))
4ef0d4d0 1486 {
98fe5161 1487 /* Free cache based on timestamp. */
d35af63c
PE
1488 EMACS_TIME old, t;
1489 double delay;
13464394 1490 ptrdiff_t nimages = 0;
98fe5161
CY
1491
1492 for (i = 0; i < c->used; ++i)
1493 if (c->images[i])
1494 nimages++;
1495
1496 /* If the number of cached images has grown unusually large,
1497 decrease the cache eviction delay (Bug#6230). */
13464394 1498 delay = XINT (Vimage_cache_eviction_delay);
98fe5161 1499 if (nimages > 40)
13464394
PE
1500 delay = 1600 * delay / nimages / nimages;
1501 delay = max (delay, 1);
98fe5161 1502
e9a9ae03
PE
1503 t = current_emacs_time ();
1504 old = sub_emacs_time (t, EMACS_TIME_FROM_DOUBLE (delay));
98fe5161
CY
1505
1506 for (i = 0; i < c->used; ++i)
4ef0d4d0 1507 {
98fe5161 1508 struct image *img = c->images[i];
d35af63c 1509 if (img && EMACS_TIME_LT (img->timestamp, old))
98fe5161
CY
1510 {
1511 free_image (f, img);
1512 ++nfreed;
1513 }
4ef0d4d0
KS
1514 }
1515 }
1516
1517 /* We may be clearing the image cache because, for example,
1518 Emacs was iconified for a longer period of time. In that
1519 case, current matrices may still contain references to
1520 images freed above. So, clear these matrices. */
1521 if (nfreed)
1522 {
1523 Lisp_Object tail, frame;
1524
1525 FOR_EACH_FRAME (tail, frame)
1526 {
6ae141d6
PE
1527 struct frame *fr = XFRAME (frame);
1528 if (FRAME_IMAGE_CACHE (fr) == c)
1529 clear_current_matrices (fr);
4ef0d4d0
KS
1530 }
1531
1532 ++windows_or_buffers_changed;
1533 }
1534
4d7e6e51 1535 unblock_input ();
4ef0d4d0
KS
1536 }
1537}
1538
354884c4 1539void
a2bc5bdd 1540clear_image_caches (Lisp_Object filter)
354884c4
SM
1541{
1542 /* FIXME: We want to do
1543 * struct terminal *t;
1544 * for (t = terminal_list; t; t = t->next_terminal)
1545 * clear_image_cache (t, filter); */
1546 Lisp_Object tail, frame;
1547 FOR_EACH_FRAME (tail, frame)
1548 if (FRAME_WINDOW_P (XFRAME (frame)))
a2bc5bdd 1549 clear_image_cache (XFRAME (frame), filter);
354884c4 1550}
4ef0d4d0
KS
1551
1552DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1553 0, 1, 0,
a2bc5bdd
SM
1554 doc: /* Clear the image cache.
1555FILTER nil or a frame means clear all images in the selected frame.
1556FILTER t means clear the image caches of all frames.
1557Anything else, means only clear those images which refer to FILTER,
1558which is then usually a filename. */)
5842a27b 1559 (Lisp_Object filter)
4ef0d4d0 1560{
a2bc5bdd
SM
1561 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1562 clear_image_caches (filter);
4ef0d4d0 1563 else
7452b7bd 1564 clear_image_cache (decode_window_system_frame (filter), Qt);
4ef0d4d0
KS
1565
1566 return Qnil;
1567}
1568
1569
110683ad 1570DEFUN ("image-flush", Fimage_flush, Simage_flush,
483e7ae0 1571 1, 2, 0,
110683ad
CY
1572 doc: /* Fush the image with specification SPEC on frame FRAME.
1573This removes the image from the Emacs image cache. If SPEC specifies
1574an image file, the next redisplay of this image will read from the
1575current contents of that file.
1576
483e7ae0
CY
1577FRAME nil or omitted means use the selected frame.
1578FRAME t means refresh the image on all frames. */)
5842a27b 1579 (Lisp_Object spec, Lisp_Object frame)
483e7ae0
CY
1580{
1581 if (!valid_image_p (spec))
1582 error ("Invalid image specification");
1583
1584 if (EQ (frame, Qt))
1585 {
1586 Lisp_Object tail;
1587 FOR_EACH_FRAME (tail, frame)
1588 {
1589 struct frame *f = XFRAME (frame);
1590 if (FRAME_WINDOW_P (f))
1591 uncache_image (f, spec);
1592 }
1593 }
1594 else
7452b7bd 1595 uncache_image (decode_window_system_frame (frame), spec);
483e7ae0
CY
1596
1597 return Qnil;
1598}
1599
1600
4ef0d4d0
KS
1601/* Compute masks and transform image IMG on frame F, as specified
1602 by the image's specification, */
1603
1604static void
d3da34e0 1605postprocess_image (struct frame *f, struct image *img)
4ef0d4d0
KS
1606{
1607 /* Manipulation of the image's mask. */
1608 if (img->pixmap)
1609 {
1610 Lisp_Object conversion, spec;
1611 Lisp_Object mask;
1612
1613 spec = img->spec;
1614
1615 /* `:heuristic-mask t'
1616 `:mask heuristic'
1617 means build a mask heuristically.
1618 `:heuristic-mask (R G B)'
1619 `:mask (heuristic (R G B))'
1620 means build a mask from color (R G B) in the
1621 image.
1622 `:mask nil'
1623 means remove a mask, if any. */
1624
1625 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1626 if (!NILP (mask))
1627 x_build_heuristic_mask (f, img, mask);
1628 else
1629 {
578098f3 1630 bool found_p;
4ef0d4d0
KS
1631
1632 mask = image_spec_value (spec, QCmask, &found_p);
1633
1634 if (EQ (mask, Qheuristic))
1635 x_build_heuristic_mask (f, img, Qt);
1636 else if (CONSP (mask)
1637 && EQ (XCAR (mask), Qheuristic))
1638 {
1639 if (CONSP (XCDR (mask)))
1640 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1641 else
1642 x_build_heuristic_mask (f, img, XCDR (mask));
1643 }
1644 else if (NILP (mask) && found_p && img->mask)
547c9269 1645 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4ef0d4d0
KS
1646 }
1647
1648
1649 /* Should we apply an image transformation algorithm? */
1650 conversion = image_spec_value (spec, QCconversion, NULL);
1651 if (EQ (conversion, Qdisabled))
1652 x_disable_image (f, img);
1653 else if (EQ (conversion, Qlaplace))
1654 x_laplace (f, img);
1655 else if (EQ (conversion, Qemboss))
1656 x_emboss (f, img);
1657 else if (CONSP (conversion)
1658 && EQ (XCAR (conversion), Qedge_detection))
1659 {
1660 Lisp_Object tem;
1661 tem = XCDR (conversion);
1662 if (CONSP (tem))
1663 x_edge_detection (f, img,
1664 Fplist_get (tem, QCmatrix),
1665 Fplist_get (tem, QCcolor_adjustment));
1666 }
1667 }
1668}
1669
1670
1671/* Return the id of image with Lisp specification SPEC on frame F.
1672 SPEC must be a valid Lisp image specification (see valid_image_p). */
1673
13464394 1674ptrdiff_t
d3da34e0 1675lookup_image (struct frame *f, Lisp_Object spec)
4ef0d4d0 1676{
4ef0d4d0 1677 struct image *img;
0de4bb68 1678 EMACS_UINT hash;
4ef0d4d0
KS
1679
1680 /* F must be a window-system frame, and SPEC must be a valid image
1681 specification. */
a54e2c05
DA
1682 eassert (FRAME_WINDOW_P (f));
1683 eassert (valid_image_p (spec));
4ef0d4d0 1684
4ef0d4d0
KS
1685 /* Look up SPEC in the hash table of the image cache. */
1686 hash = sxhash (spec, 0);
d3c35d17 1687 img = search_image_cache (f, spec, hash);
f1f25b99
CY
1688 if (img && img->load_failed_p)
1689 {
1690 free_image (f, img);
1691 img = NULL;
1692 }
1693
4ef0d4d0
KS
1694 /* If not found, create a new image and cache it. */
1695 if (img == NULL)
1696 {
4d7e6e51 1697 block_input ();
4ef0d4d0
KS
1698 img = make_image (spec, hash);
1699 cache_image (f, img);
578098f3 1700 img->load_failed_p = ! img->type->load (f, img);
c5b8e0ea
YM
1701 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1702 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
4ef0d4d0
KS
1703
1704 /* If we can't load the image, and we don't have a width and
1705 height, use some arbitrary width and height so that we can
1706 draw a rectangle for it. */
1707 if (img->load_failed_p)
1708 {
1709 Lisp_Object value;
1710
1711 value = image_spec_value (spec, QCwidth, NULL);
1712 img->width = (INTEGERP (value)
1713 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1714 value = image_spec_value (spec, QCheight, NULL);
1715 img->height = (INTEGERP (value)
1716 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1717 }
1718 else
1719 {
1720 /* Handle image type independent image attributes
1721 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1722 `:background COLOR'. */
1723 Lisp_Object ascent, margin, relief, bg;
d311d28c 1724 int relief_bound;
4ef0d4d0
KS
1725
1726 ascent = image_spec_value (spec, QCascent, NULL);
1727 if (INTEGERP (ascent))
1728 img->ascent = XFASTINT (ascent);
1729 else if (EQ (ascent, Qcenter))
1730 img->ascent = CENTERED_IMAGE_ASCENT;
1731
1732 margin = image_spec_value (spec, QCmargin, NULL);
13464394 1733 if (INTEGERP (margin))
4ef0d4d0 1734 img->vmargin = img->hmargin = XFASTINT (margin);
13464394 1735 else if (CONSP (margin))
4ef0d4d0 1736 {
13464394
PE
1737 img->hmargin = XFASTINT (XCAR (margin));
1738 img->vmargin = XFASTINT (XCDR (margin));
4ef0d4d0
KS
1739 }
1740
1741 relief = image_spec_value (spec, QCrelief, NULL);
d311d28c
PE
1742 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1743 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
4ef0d4d0
KS
1744 {
1745 img->relief = XINT (relief);
1ea40aa2
EZ
1746 img->hmargin += eabs (img->relief);
1747 img->vmargin += eabs (img->relief);
4ef0d4d0
KS
1748 }
1749
1750 if (! img->background_valid)
1751 {
1752 bg = image_spec_value (img->spec, QCbackground, NULL);
1753 if (!NILP (bg))
1754 {
1755 img->background
1756 = x_alloc_image_color (f, img, bg,
1757 FRAME_BACKGROUND_PIXEL (f));
1758 img->background_valid = 1;
1759 }
1760 }
1761
1762 /* Do image transformations and compute masks, unless we
1763 don't have the image yet. */
1764 if (!EQ (*img->type->type, Qpostscript))
1765 postprocess_image (f, img);
1766 }
1767
4d7e6e51 1768 unblock_input ();
4ef0d4d0
KS
1769 }
1770
1771 /* We're using IMG, so set its timestamp to `now'. */
e9a9ae03 1772 img->timestamp = current_emacs_time ();
4ef0d4d0 1773
4ef0d4d0
KS
1774 /* Value is the image id. */
1775 return img->id;
1776}
1777
1778
1779/* Cache image IMG in the image cache of frame F. */
1780
1781static void
d3da34e0 1782cache_image (struct frame *f, struct image *img)
4ef0d4d0 1783{
354884c4 1784 struct image_cache *c = FRAME_IMAGE_CACHE (f);
13464394 1785 ptrdiff_t i;
4ef0d4d0
KS
1786
1787 /* Find a free slot in c->images. */
1788 for (i = 0; i < c->used; ++i)
1789 if (c->images[i] == NULL)
1790 break;
1791
1792 /* If no free slot found, maybe enlarge c->images. */
1793 if (i == c->used && c->used == c->size)
a69fbedb 1794 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
4ef0d4d0
KS
1795
1796 /* Add IMG to c->images, and assign IMG an id. */
1797 c->images[i] = img;
1798 img->id = i;
1799 if (i == c->used)
1800 ++c->used;
1801
1802 /* Add IMG to the cache's hash table. */
1803 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1804 img->next = c->buckets[i];
1805 if (img->next)
1806 img->next->prev = img;
1807 img->prev = NULL;
1808 c->buckets[i] = img;
1809}
1810
1811
1812/* Call FN on every image in the image cache of frame F. Used to mark
1813 Lisp Objects in the image cache. */
1814
354884c4
SM
1815/* Mark Lisp objects in image IMG. */
1816
1817static void
d3da34e0 1818mark_image (struct image *img)
354884c4
SM
1819{
1820 mark_object (img->spec);
a2bc5bdd 1821 mark_object (img->dependencies);
354884c4 1822
b50691aa
CY
1823 if (!NILP (img->lisp_data))
1824 mark_object (img->lisp_data);
354884c4
SM
1825}
1826
1827
4ef0d4d0 1828void
354884c4 1829mark_image_cache (struct image_cache *c)
4ef0d4d0 1830{
354884c4 1831 if (c)
4ef0d4d0 1832 {
13464394 1833 ptrdiff_t i;
354884c4
SM
1834 for (i = 0; i < c->used; ++i)
1835 if (c->images[i])
1836 mark_image (c->images[i]);
4ef0d4d0
KS
1837 }
1838}
1839
1840
1841\f
1842/***********************************************************************
9e2a2647 1843 X / NS / W32 support code
4ef0d4d0
KS
1844 ***********************************************************************/
1845
0fda9b75 1846#ifdef WINDOWSNT
4ef0d4d0
KS
1847
1848/* Macro for defining functions that will be loaded from image DLLs. */
dbdb9a7c 1849#define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
4ef0d4d0
KS
1850
1851/* Macro for loading those image functions from the library. */
1852#define LOAD_IMGLIB_FN(lib,func) { \
1853 fn_##func = (void *) GetProcAddress (lib, #func); \
1854 if (!fn_##func) return 0; \
1855 }
1856
0fda9b75 1857#endif /* WINDOWSNT */
4ef0d4d0 1858
578098f3 1859/* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
476371c4 1860 windowing system.
ca4aa935
PE
1861 WIDTH and HEIGHT must both be positive.
1862 If XIMG is null, assume it is a bitmap. */
578098f3 1863static bool
ca4aa935
PE
1864x_check_image_size (XImagePtr ximg, int width, int height)
1865{
476371c4 1866#ifdef HAVE_X_WINDOWS
ca4aa935
PE
1867 /* Respect Xlib's limits: it cannot deal with images that have more
1868 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
476371c4 1869 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
ca4aa935
PE
1870 enum
1871 {
1872 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1873 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1874 };
1875
1876 int bitmap_pad, depth, bytes_per_line;
1877 if (ximg)
1878 {
1879 bitmap_pad = ximg->bitmap_pad;
1880 depth = ximg->depth;
1881 bytes_per_line = ximg->bytes_per_line;
1882 }
1883 else
1884 {
1885 bitmap_pad = 8;
1886 depth = 1;
1887 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1888 }
1889 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1890 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
476371c4
PE
1891#else
1892 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1893 For now, assume that every image size is allowed on these systems. */
1894 return 1;
1895#endif
ca4aa935 1896}
4ef0d4d0
KS
1897
1898/* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1899 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1900 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1901 via xmalloc. Print error messages via image_error if an error
578098f3 1902 occurs. Value is true if successful.
4ef0d4d0
KS
1903
1904 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1905 should indicate the bit depth of the image. */
1906
578098f3 1907static bool
d3da34e0
JB
1908x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1909 XImagePtr *ximg, Pixmap *pixmap)
4ef0d4d0
KS
1910{
1911#ifdef HAVE_X_WINDOWS
1912 Display *display = FRAME_X_DISPLAY (f);
1913 Window window = FRAME_X_WINDOW (f);
1914 Screen *screen = FRAME_X_SCREEN (f);
1915
4d7e6e51 1916 eassert (input_blocked_p ());
4ef0d4d0
KS
1917
1918 if (depth <= 0)
1919 depth = DefaultDepthOfScreen (screen);
1920 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1921 depth, ZPixmap, 0, NULL, width, height,
1922 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1923 if (*ximg == NULL)
1924 {
1925 image_error ("Unable to allocate X image", Qnil, Qnil);
1926 return 0;
1927 }
1928
ca4aa935
PE
1929 if (! x_check_image_size (*ximg, width, height))
1930 {
1931 x_destroy_x_image (*ximg);
1932 *ximg = NULL;
1933 image_error ("Image too large (%dx%d)",
1934 make_number (width), make_number (height));
1935 return 0;
1936 }
1937
4ef0d4d0 1938 /* Allocate image raster. */
23f86fce 1939 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
4ef0d4d0
KS
1940
1941 /* Allocate a pixmap of the same size. */
1942 *pixmap = XCreatePixmap (display, window, width, height, depth);
1943 if (*pixmap == NO_PIXMAP)
1944 {
1945 x_destroy_x_image (*ximg);
1946 *ximg = NULL;
1947 image_error ("Unable to create X pixmap", Qnil, Qnil);
1948 return 0;
1949 }
1950
1951 return 1;
1952#endif /* HAVE_X_WINDOWS */
1953
1954#ifdef HAVE_NTGUI
1955
1956 BITMAPINFOHEADER *header;
1957 HDC hdc;
1958 int scanline_width_bits;
1959 int remainder;
1960 int palette_colors = 0;
1961
1962 if (depth == 0)
1963 depth = 24;
1964
1965 if (depth != 1 && depth != 4 && depth != 8
1966 && depth != 16 && depth != 24 && depth != 32)
1967 {
1968 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1969 return 0;
1970 }
1971
1972 scanline_width_bits = width * depth;
1973 remainder = scanline_width_bits % 32;
1974
1975 if (remainder)
1976 scanline_width_bits += 32 - remainder;
1977
1978 /* Bitmaps with a depth less than 16 need a palette. */
1979 /* BITMAPINFO structure already contains the first RGBQUAD. */
1980 if (depth < 16)
657d08d3 1981 palette_colors = 1 << (depth - 1);
4ef0d4d0
KS
1982
1983 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
4ef0d4d0 1984
72af86bd
AS
1985 header = &(*ximg)->info.bmiHeader;
1986 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
4ef0d4d0
KS
1987 header->biSize = sizeof (*header);
1988 header->biWidth = width;
1989 header->biHeight = -height; /* negative indicates a top-down bitmap. */
1990 header->biPlanes = 1;
1991 header->biBitCount = depth;
1992 header->biCompression = BI_RGB;
1993 header->biClrUsed = palette_colors;
1994
1995 /* TODO: fill in palette. */
1996 if (depth == 1)
1997 {
1998 (*ximg)->info.bmiColors[0].rgbBlue = 0;
1999 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2000 (*ximg)->info.bmiColors[0].rgbRed = 0;
2001 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2002 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2003 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2004 (*ximg)->info.bmiColors[1].rgbRed = 255;
2005 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2006 }
2007
2008 hdc = get_frame_dc (f);
2009
2010 /* Create a DIBSection and raster array for the bitmap,
2011 and store its handle in *pixmap. */
2012 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2013 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2e09fef1
EZ
2014 /* casting avoids a GCC warning */
2015 (void **)&((*ximg)->data), NULL, 0);
4ef0d4d0
KS
2016
2017 /* Realize display palette and garbage all frames. */
2018 release_frame_dc (f, hdc);
2019
2020 if (*pixmap == NULL)
2021 {
5fc9fdeb 2022 DWORD err = GetLastError ();
4ef0d4d0
KS
2023 Lisp_Object errcode;
2024 /* All system errors are < 10000, so the following is safe. */
13464394 2025 XSETINT (errcode, err);
4ef0d4d0
KS
2026 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2027 x_destroy_x_image (*ximg);
2028 return 0;
2029 }
2030
2031 return 1;
2032
2033#endif /* HAVE_NTGUI */
2034
edfda783 2035#ifdef HAVE_NS
ed3751c8 2036 *pixmap = ns_image_for_XPM (width, height, depth);
edfda783
AR
2037 if (*pixmap == 0)
2038 {
2039 *ximg = NULL;
2040 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2041 return 0;
2042 }
2043 *ximg = *pixmap;
2044 return 1;
2045#endif
4ef0d4d0
KS
2046}
2047
2048
2049/* Destroy XImage XIMG. Free XIMG->data. */
2050
2051static void
d3da34e0 2052x_destroy_x_image (XImagePtr ximg)
4ef0d4d0 2053{
4d7e6e51 2054 eassert (input_blocked_p ());
4ef0d4d0
KS
2055 if (ximg)
2056 {
2057#ifdef HAVE_X_WINDOWS
2058 xfree (ximg->data);
2059 ximg->data = NULL;
2060 XDestroyImage (ximg);
2061#endif /* HAVE_X_WINDOWS */
2062#ifdef HAVE_NTGUI
2063 /* Data will be freed by DestroyObject. */
2064 ximg->data = NULL;
2065 xfree (ximg);
2066#endif /* HAVE_NTGUI */
edfda783 2067#ifdef HAVE_NS
ed3751c8 2068 ns_release_object (ximg);
edfda783 2069#endif /* HAVE_NS */
4ef0d4d0
KS
2070 }
2071}
2072
2073
2074/* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2075 are width and height of both the image and pixmap. */
2076
2077static void
d3da34e0 2078x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
4ef0d4d0
KS
2079{
2080#ifdef HAVE_X_WINDOWS
2081 GC gc;
2082
4d7e6e51 2083 eassert (input_blocked_p ());
4ef0d4d0
KS
2084 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2085 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2086 XFreeGC (FRAME_X_DISPLAY (f), gc);
2087#endif /* HAVE_X_WINDOWS */
2088
2089#ifdef HAVE_NTGUI
2090#if 0 /* I don't think this is necessary looking at where it is used. */
2091 HDC hdc = get_frame_dc (f);
2092 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2093 release_frame_dc (f, hdc);
2094#endif
2095#endif /* HAVE_NTGUI */
2096
edfda783 2097#ifdef HAVE_NS
a54e2c05 2098 eassert (ximg == pixmap);
ed3751c8 2099 ns_retain_object (ximg);
edfda783 2100#endif
4ef0d4d0
KS
2101}
2102
547c9269
YM
2103/* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2104 with image_put_x_image. */
2105
2106static bool
2107image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2108 int width, int height, int depth,
2109 XImagePtr *ximg, bool mask_p)
2110{
2111 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2112
2113 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2114 !mask_p ? &img->pixmap : &img->mask);
2115}
2116
2117/* Put X image XIMG into image IMG on frame F, as a mask if and only
2118 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2119 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2120 On the other platforms, it puts XIMG into the pixmap, then frees
2121 the X image and its buffer. */
2122
2123static void
2124image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2125 bool mask_p)
2126{
2127#ifdef HAVE_X_WINDOWS
2128 if (!mask_p)
2129 {
2130 eassert (img->ximg == NULL);
2131 img->ximg = ximg;
2132 }
2133 else
2134 {
2135 eassert (img->mask_img == NULL);
2136 img->mask_img = ximg;
2137 }
2138#else
2139 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2140 img->width, img->height);
2141 x_destroy_x_image (ximg);
2142#endif
2143}
2144
2145#ifdef HAVE_X_WINDOWS
2146/* Put the X images recorded in IMG on frame F into pixmaps, then free
2147 the X images and their buffers. */
2148
2149static void
2150image_sync_to_pixmaps (struct frame *f, struct image *img)
2151{
2152 if (img->ximg)
2153 {
2154 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2155 x_destroy_x_image (img->ximg);
2156 img->ximg = NULL;
2157 }
2158 if (img->mask_img)
2159 {
2160 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2161 x_destroy_x_image (img->mask_img);
2162 img->mask_img = NULL;
2163 }
2164}
2165#endif
2166
2167#ifdef HAVE_NTGUI
2168/* Create a memory device context for IMG on frame F. It stores the
2169 currently selected GDI object into *PREV for future restoration by
2170 image_unget_x_image_or_dc. */
2171
2172static XImagePtr_or_DC
2173image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2174 HGDIOBJ *prev)
2175{
2176 HDC frame_dc = get_frame_dc (f);
2177 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2178
2179 release_frame_dc (f, frame_dc);
2180 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
b8075603
YM
2181
2182 return ximg;
547c9269
YM
2183}
2184
b8075603
YM
2185static void
2186image_unget_x_image_or_dc (struct image *img, bool mask_p,
2187 XImagePtr_or_DC ximg, HGDIOBJ prev)
547c9269
YM
2188{
2189 SelectObject (ximg, prev);
2190 DeleteDC (ximg);
2191}
2192#else /* !HAVE_NTGUI */
2193/* Get the X image for IMG on frame F. The resulting X image data
2194 should be treated as read-only at least on X. */
2195
2196static XImagePtr
2197image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2198{
2199#ifdef HAVE_X_WINDOWS
2200 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2201
2202 if (ximg_in_img)
2203 return ximg_in_img;
2204 else
2205 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2206 0, 0, img->width, img->height, ~0, ZPixmap);
2207#elif defined (HAVE_NS)
2208 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2209
2210 ns_retain_object (pixmap);
2211 return pixmap;
2212#endif
2213}
2214
df03dc8a
YM
2215static void
2216image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
547c9269
YM
2217{
2218#ifdef HAVE_X_WINDOWS
2219 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2220
2221 if (ximg_in_img)
2222 eassert (ximg == ximg_in_img);
2223 else
2224 XDestroyImage (ximg);
2225#elif defined (HAVE_NS)
2226 ns_release_object (ximg);
2227#endif
2228}
2229#endif /* !HAVE_NTGUI */
2230
4ef0d4d0
KS
2231\f
2232/***********************************************************************
2233 File Handling
2234 ***********************************************************************/
2235
6678dc11 2236/* Find image file FILE. Look in data-directory/images, then
022af124
KH
2237 x-bitmap-file-path. Value is the encoded full name of the file
2238 found, or nil if not found. */
4ef0d4d0 2239
c640aa9b 2240Lisp_Object
d3da34e0 2241x_find_image_file (Lisp_Object file)
4ef0d4d0
KS
2242{
2243 Lisp_Object file_found, search_path;
4ef0d4d0
KS
2244 int fd;
2245
6678dc11
GM
2246 /* TODO I think this should use something like image-load-path
2247 instead. Unfortunately, that can contain non-string elements. */
2248 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2249 Vdata_directory),
2250 Vx_bitmap_file_path);
4ef0d4d0 2251
050b82f6 2252 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
4ef0d4d0
KS
2253 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2254
2255 if (fd == -1)
2256 file_found = Qnil;
2257 else
022af124
KH
2258 {
2259 file_found = ENCODE_FILE (file_found);
f6774c1a
AS
2260 if (fd != -2)
2261 emacs_close (fd);
022af124 2262 }
4ef0d4d0 2263
4ef0d4d0
KS
2264 return file_found;
2265}
2266
2267
2268/* Read FILE into memory. Value is a pointer to a buffer allocated
2269 with xmalloc holding FILE's contents. Value is null if an error
2270 occurred. *SIZE is set to the size of the file. */
2271
2272static unsigned char *
dd52fcea 2273slurp_file (char *file, ptrdiff_t *size)
4ef0d4d0 2274{
406af475 2275 FILE *fp = emacs_fopen (file, "rb");
4ef0d4d0
KS
2276 unsigned char *buf = NULL;
2277 struct stat st;
2278
d6453ce4 2279 if (fp && fstat (fileno (fp), &st) == 0
dd52fcea 2280 && 0 <= st.st_size && st.st_size <= min (PTRDIFF_MAX, SIZE_MAX)
23f86fce 2281 && (buf = xmalloc (st.st_size),
4ef0d4d0
KS
2282 fread (buf, 1, st.st_size, fp) == st.st_size))
2283 {
2284 *size = st.st_size;
2285 fclose (fp);
2286 }
2287 else
2288 {
2289 if (fp)
2290 fclose (fp);
2291 if (buf)
2292 {
2293 xfree (buf);
2294 buf = NULL;
2295 }
2296 }
2297
2298 return buf;
2299}
2300
2301
2302\f
4ef0d4d0
KS
2303/***********************************************************************
2304 XBM images
2305 ***********************************************************************/
2306
578098f3
PE
2307static bool xbm_load (struct frame *f, struct image *img);
2308static bool xbm_image_p (Lisp_Object object);
2309static bool xbm_file_p (Lisp_Object);
4ef0d4d0
KS
2310
2311
2312/* Indices of image specification fields in xbm_format, below. */
2313
2314enum xbm_keyword_index
2315{
2316 XBM_TYPE,
2317 XBM_FILE,
2318 XBM_WIDTH,
2319 XBM_HEIGHT,
2320 XBM_DATA,
2321 XBM_FOREGROUND,
2322 XBM_BACKGROUND,
2323 XBM_ASCENT,
2324 XBM_MARGIN,
2325 XBM_RELIEF,
2326 XBM_ALGORITHM,
2327 XBM_HEURISTIC_MASK,
2328 XBM_MASK,
2329 XBM_LAST
2330};
2331
2332/* Vector of image_keyword structures describing the format
2333 of valid XBM image specifications. */
2334
91433552 2335static const struct image_keyword xbm_format[XBM_LAST] =
4ef0d4d0
KS
2336{
2337 {":type", IMAGE_SYMBOL_VALUE, 1},
2338 {":file", IMAGE_STRING_VALUE, 0},
2339 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2340 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2341 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2342 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2343 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2344 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 2345 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
2346 {":relief", IMAGE_INTEGER_VALUE, 0},
2347 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2348 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2349 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2350};
2351
2352/* Structure describing the image type XBM. */
2353
2354static struct image_type xbm_type =
2355{
2356 &Qxbm,
2357 xbm_image_p,
2358 xbm_load,
2359 x_clear_image,
bb4d86b4 2360 NULL,
4ef0d4d0
KS
2361 NULL
2362};
2363
2364/* Tokens returned from xbm_scan. */
2365
2366enum xbm_token
2367{
2368 XBM_TK_IDENT = 256,
2369 XBM_TK_NUMBER
2370};
2371
2372
578098f3 2373/* Return true if OBJECT is a valid XBM-type image specification.
4ef0d4d0
KS
2374 A valid specification is a list starting with the symbol `image'
2375 The rest of the list is a property list which must contain an
578098f3 2376 entry `:type xbm'.
4ef0d4d0
KS
2377
2378 If the specification specifies a file to load, it must contain
2379 an entry `:file FILENAME' where FILENAME is a string.
2380
2381 If the specification is for a bitmap loaded from memory it must
2382 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2383 WIDTH and HEIGHT are integers > 0. DATA may be:
2384
2385 1. a string large enough to hold the bitmap data, i.e. it must
2386 have a size >= (WIDTH + 7) / 8 * HEIGHT
2387
2388 2. a bool-vector of size >= WIDTH * HEIGHT
2389
2390 3. a vector of strings or bool-vectors, one for each line of the
2391 bitmap.
2392
bbe6f2aa 2393 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
4ef0d4d0
KS
2394 may not be specified in this case because they are defined in the
2395 XBM file.
2396
2397 Both the file and data forms may contain the additional entries
2398 `:background COLOR' and `:foreground COLOR'. If not present,
2399 foreground and background of the frame on which the image is
2400 displayed is used. */
2401
578098f3 2402static bool
d3da34e0 2403xbm_image_p (Lisp_Object object)
4ef0d4d0
KS
2404{
2405 struct image_keyword kw[XBM_LAST];
2406
72af86bd 2407 memcpy (kw, xbm_format, sizeof kw);
4ef0d4d0
KS
2408 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2409 return 0;
2410
a54e2c05 2411 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
4ef0d4d0
KS
2412
2413 if (kw[XBM_FILE].count)
2414 {
2415 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2416 return 0;
2417 }
2418 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2419 {
2420 /* In-memory XBM file. */
2421 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2422 return 0;
2423 }
2424 else
2425 {
2426 Lisp_Object data;
13464394 2427 int width, height;
4ef0d4d0
KS
2428
2429 /* Entries for `:width', `:height' and `:data' must be present. */
2430 if (!kw[XBM_WIDTH].count
2431 || !kw[XBM_HEIGHT].count
2432 || !kw[XBM_DATA].count)
2433 return 0;
2434
2435 data = kw[XBM_DATA].value;
2436 width = XFASTINT (kw[XBM_WIDTH].value);
2437 height = XFASTINT (kw[XBM_HEIGHT].value);
2438
2439 /* Check type of data, and width and height against contents of
2440 data. */
2441 if (VECTORP (data))
2442 {
45aebb64 2443 EMACS_INT i;
4ef0d4d0
KS
2444
2445 /* Number of elements of the vector must be >= height. */
77b37c05 2446 if (ASIZE (data) < height)
4ef0d4d0
KS
2447 return 0;
2448
2449 /* Each string or bool-vector in data must be large enough
2450 for one line of the image. */
2451 for (i = 0; i < height; ++i)
2452 {
28be1ada 2453 Lisp_Object elt = AREF (data, i);
4ef0d4d0
KS
2454
2455 if (STRINGP (elt))
2456 {
2457 if (SCHARS (elt)
2458 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2459 return 0;
2460 }
2461 else if (BOOL_VECTOR_P (elt))
2462 {
2463 if (XBOOL_VECTOR (elt)->size < width)
2464 return 0;
2465 }
2466 else
2467 return 0;
2468 }
2469 }
2470 else if (STRINGP (data))
2471 {
2472 if (SCHARS (data)
2473 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2474 return 0;
2475 }
2476 else if (BOOL_VECTOR_P (data))
2477 {
ca4aa935 2478 if (XBOOL_VECTOR (data)->size / height < width)
4ef0d4d0
KS
2479 return 0;
2480 }
2481 else
2482 return 0;
2483 }
2484
2485 return 1;
2486}
2487
2488
2489/* Scan a bitmap file. FP is the stream to read from. Value is
2490 either an enumerator from enum xbm_token, or a character for a
2491 single-character token, or 0 at end of file. If scanning an
2492 identifier, store the lexeme of the identifier in SVAL. If
2493 scanning a number, store its value in *IVAL. */
2494
2495static int
d3da34e0 2496xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
4ef0d4d0
KS
2497{
2498 unsigned int c;
2499
2500 loop:
2501
2502 /* Skip white space. */
620f13b0 2503 while (*s < end && (c = *(*s)++, c_isspace (c)))
4ef0d4d0
KS
2504 ;
2505
2506 if (*s >= end)
2507 c = 0;
620f13b0 2508 else if (c_isdigit (c))
4ef0d4d0
KS
2509 {
2510 int value = 0, digit;
2511
2512 if (c == '0' && *s < end)
2513 {
2514 c = *(*s)++;
2515 if (c == 'x' || c == 'X')
2516 {
2517 while (*s < end)
2518 {
2519 c = *(*s)++;
620f13b0 2520 if (c_isdigit (c))
4ef0d4d0
KS
2521 digit = c - '0';
2522 else if (c >= 'a' && c <= 'f')
2523 digit = c - 'a' + 10;
2524 else if (c >= 'A' && c <= 'F')
2525 digit = c - 'A' + 10;
2526 else
2527 break;
2528 value = 16 * value + digit;
2529 }
2530 }
620f13b0 2531 else if (c_isdigit (c))
4ef0d4d0
KS
2532 {
2533 value = c - '0';
2534 while (*s < end
620f13b0 2535 && (c = *(*s)++, c_isdigit (c)))
4ef0d4d0
KS
2536 value = 8 * value + c - '0';
2537 }
2538 }
2539 else
2540 {
2541 value = c - '0';
2542 while (*s < end
620f13b0 2543 && (c = *(*s)++, c_isdigit (c)))
4ef0d4d0
KS
2544 value = 10 * value + c - '0';
2545 }
2546
2547 if (*s < end)
2548 *s = *s - 1;
2549 *ival = value;
2550 c = XBM_TK_NUMBER;
2551 }
620f13b0 2552 else if (c_isalpha (c) || c == '_')
4ef0d4d0
KS
2553 {
2554 *sval++ = c;
2555 while (*s < end
620f13b0 2556 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
4ef0d4d0
KS
2557 *sval++ = c;
2558 *sval = 0;
2559 if (*s < end)
2560 *s = *s - 1;
2561 c = XBM_TK_IDENT;
2562 }
2563 else if (c == '/' && **s == '*')
2564 {
2565 /* C-style comment. */
2566 ++*s;
2567 while (**s && (**s != '*' || *(*s + 1) != '/'))
2568 ++*s;
2569 if (**s)
2570 {
2571 *s += 2;
2572 goto loop;
2573 }
2574 }
2575
2576 return c;
2577}
2578
2579#ifdef HAVE_NTGUI
2580
2581/* Create a Windows bitmap from X bitmap data. */
2582static HBITMAP
2583w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2584{
2585 static unsigned char swap_nibble[16]
2586 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2587 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2588 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2589 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2590 int i, j, w1, w2;
2591 unsigned char *bits, *p;
2592 HBITMAP bmp;
2593
2594 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2595 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
38182d90 2596 bits = alloca (height * w2);
72af86bd 2597 memset (bits, 0, height * w2);
4ef0d4d0
KS
2598 for (i = 0; i < height; i++)
2599 {
2600 p = bits + i*w2;
2601 for (j = 0; j < w1; j++)
2602 {
2603 /* Bitswap XBM bytes to match how Windows does things. */
2604 unsigned char c = *data++;
2605 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2606 | (swap_nibble[(c>>4) & 0xf]));
2607 }
2608 }
2609 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2610
2611 return bmp;
2612}
2613
3046a84b 2614static void
7c3320d8
JB
2615convert_mono_to_color_image (struct frame *f, struct image *img,
2616 COLORREF foreground, COLORREF background)
4ef0d4d0
KS
2617{
2618 HDC hdc, old_img_dc, new_img_dc;
2619 HGDIOBJ old_prev, new_prev;
2620 HBITMAP new_pixmap;
2621
2622 hdc = get_frame_dc (f);
2623 old_img_dc = CreateCompatibleDC (hdc);
2624 new_img_dc = CreateCompatibleDC (hdc);
2625 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2626 release_frame_dc (f, hdc);
2627 old_prev = SelectObject (old_img_dc, img->pixmap);
2628 new_prev = SelectObject (new_img_dc, new_pixmap);
44b1dc2e
JR
2629 /* Windows convention for mono bitmaps is black = background,
2630 white = foreground. */
2386b1f1
JR
2631 SetTextColor (new_img_dc, background);
2632 SetBkColor (new_img_dc, foreground);
4ef0d4d0
KS
2633
2634 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2635 0, 0, SRCCOPY);
2636
2637 SelectObject (old_img_dc, old_prev);
2638 SelectObject (new_img_dc, new_prev);
2639 DeleteDC (old_img_dc);
2640 DeleteDC (new_img_dc);
2641 DeleteObject (img->pixmap);
2642 if (new_pixmap == 0)
2643 fprintf (stderr, "Failed to convert image to color.\n");
2644 else
2645 img->pixmap = new_pixmap;
2646}
2647
2648#define XBM_BIT_SHUFFLE(b) (~(b))
2649
2650#else
2651
2652#define XBM_BIT_SHUFFLE(b) (b)
2653
2654#endif /* HAVE_NTGUI */
2655
2656
2657static void
d3da34e0
JB
2658Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2659 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
578098f3 2660 bool non_default_colors)
4ef0d4d0
KS
2661{
2662#ifdef HAVE_NTGUI
2663 img->pixmap
2664 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2665
2666 /* If colors were specified, transfer the bitmap to a color one. */
2667 if (non_default_colors)
2668 convert_mono_to_color_image (f, img, fg, bg);
edfda783
AR
2669
2670#elif defined (HAVE_NS)
ed3751c8 2671 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
edfda783 2672
4ef0d4d0 2673#else
ca4aa935
PE
2674 img->pixmap =
2675 (x_check_image_size (0, img->width, img->height)
2676 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
4ef0d4d0
KS
2677 FRAME_X_WINDOW (f),
2678 data,
2679 img->width, img->height,
2680 fg, bg,
ca4aa935
PE
2681 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2682 : NO_PIXMAP);
edfda783 2683#endif /* !HAVE_NTGUI && !HAVE_NS */
4ef0d4d0
KS
2684}
2685
2686
2687
2688/* Replacement for XReadBitmapFileData which isn't available under old
2689 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2690 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2691 the image. Return in *DATA the bitmap data allocated with xmalloc.
578098f3
PE
2692 Value is true if successful. DATA null means just test if
2693 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2694 inhibit the call to image_error when the image size is invalid (the
2695 bitmap remains unread). */
4ef0d4d0 2696
578098f3 2697static bool
d3da34e0 2698xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
b8dc29e9 2699 int *width, int *height, char **data,
578098f3 2700 bool inhibit_image_error)
4ef0d4d0
KS
2701{
2702 unsigned char *s = contents;
2703 char buffer[BUFSIZ];
578098f3
PE
2704 bool padding_p = 0;
2705 bool v10 = 0;
ca4aa935 2706 int bytes_per_line, i, nbytes;
b8dc29e9 2707 char *p;
4ef0d4d0
KS
2708 int value;
2709 int LA1;
2710
2711#define match() \
2712 LA1 = xbm_scan (&s, end, buffer, &value)
2713
2714#define expect(TOKEN) \
2715 if (LA1 != (TOKEN)) \
2716 goto failure; \
2717 else \
2718 match ()
2719
2720#define expect_ident(IDENT) \
2721 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2722 match (); \
2723 else \
2724 goto failure
2725
2726 *width = *height = -1;
2727 if (data)
2728 *data = NULL;
2729 LA1 = xbm_scan (&s, end, buffer, &value);
2730
2731 /* Parse defines for width, height and hot-spots. */
2732 while (LA1 == '#')
2733 {
2734 match ();
2735 expect_ident ("define");
2736 expect (XBM_TK_IDENT);
2737
431feaf6 2738 if (LA1 == XBM_TK_NUMBER)
4ef0d4d0 2739 {
6ae141d6
PE
2740 char *q = strrchr (buffer, '_');
2741 q = q ? q + 1 : buffer;
2742 if (strcmp (q, "width") == 0)
4ef0d4d0 2743 *width = value;
6ae141d6 2744 else if (strcmp (q, "height") == 0)
4ef0d4d0
KS
2745 *height = value;
2746 }
2747 expect (XBM_TK_NUMBER);
2748 }
2749
f1f25b99 2750 if (!check_image_size (f, *width, *height))
10ea2b82 2751 {
ce959360
CY
2752 if (!inhibit_image_error)
2753 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
10ea2b82
JR
2754 goto failure;
2755 }
4ef0d4d0
KS
2756 else if (data == NULL)
2757 goto success;
2758
2759 /* Parse bits. Must start with `static'. */
2760 expect_ident ("static");
2761 if (LA1 == XBM_TK_IDENT)
2762 {
2763 if (strcmp (buffer, "unsigned") == 0)
2764 {
2765 match ();
2766 expect_ident ("char");
2767 }
2768 else if (strcmp (buffer, "short") == 0)
2769 {
2770 match ();
2771 v10 = 1;
2772 if (*width % 16 && *width % 16 < 9)
2773 padding_p = 1;
2774 }
2775 else if (strcmp (buffer, "char") == 0)
2776 match ();
2777 else
2778 goto failure;
2779 }
2780 else
2781 goto failure;
2782
2783 expect (XBM_TK_IDENT);
2784 expect ('[');
2785 expect (']');
2786 expect ('=');
2787 expect ('{');
2788
ca4aa935
PE
2789 if (! x_check_image_size (0, *width, *height))
2790 {
2791 if (!inhibit_image_error)
2792 image_error ("Image too large (%dx%d)",
2793 make_number (*width), make_number (*height));
2794 goto failure;
2795 }
4ef0d4d0
KS
2796 bytes_per_line = (*width + 7) / 8 + padding_p;
2797 nbytes = bytes_per_line * *height;
23f86fce 2798 p = *data = xmalloc (nbytes);
4ef0d4d0
KS
2799
2800 if (v10)
2801 {
2802 for (i = 0; i < nbytes; i += 2)
2803 {
2804 int val = value;
2805 expect (XBM_TK_NUMBER);
2806
2807 *p++ = XBM_BIT_SHUFFLE (val);
2808 if (!padding_p || ((i + 2) % bytes_per_line))
2809 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2810
2811 if (LA1 == ',' || LA1 == '}')
2812 match ();
2813 else
2814 goto failure;
2815 }
2816 }
2817 else
2818 {
2819 for (i = 0; i < nbytes; ++i)
2820 {
2821 int val = value;
2822 expect (XBM_TK_NUMBER);
2823
2824 *p++ = XBM_BIT_SHUFFLE (val);
2825
2826 if (LA1 == ',' || LA1 == '}')
2827 match ();
2828 else
2829 goto failure;
2830 }
2831 }
2832
2833 success:
2834 return 1;
2835
2836 failure:
2837
2838 if (data && *data)
2839 {
2840 xfree (*data);
2841 *data = NULL;
2842 }
2843 return 0;
2844
2845#undef match
2846#undef expect
2847#undef expect_ident
2848}
2849
2850
2851/* Load XBM image IMG which will be displayed on frame F from buffer
578098f3 2852 CONTENTS. END is the end of the buffer. Value is true if
4ef0d4d0
KS
2853 successful. */
2854
578098f3 2855static bool
d3da34e0
JB
2856xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2857 unsigned char *end)
4ef0d4d0 2858{
578098f3 2859 bool rc;
b8dc29e9 2860 char *data;
578098f3 2861 bool success_p = 0;
4ef0d4d0 2862
ce959360
CY
2863 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2864 &data, 0);
4ef0d4d0
KS
2865 if (rc)
2866 {
2867 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2868 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
578098f3 2869 bool non_default_colors = 0;
4ef0d4d0
KS
2870 Lisp_Object value;
2871
a54e2c05 2872 eassert (img->width > 0 && img->height > 0);
4ef0d4d0
KS
2873
2874 /* Get foreground and background colors, maybe allocate colors. */
2875 value = image_spec_value (img->spec, QCforeground, NULL);
2876 if (!NILP (value))
2877 {
2878 foreground = x_alloc_image_color (f, img, value, foreground);
2879 non_default_colors = 1;
2880 }
2881 value = image_spec_value (img->spec, QCbackground, NULL);
2882 if (!NILP (value))
2883 {
2884 background = x_alloc_image_color (f, img, value, background);
2885 img->background = background;
2886 img->background_valid = 1;
2887 non_default_colors = 1;
2888 }
2889
1f026899 2890 Create_Pixmap_From_Bitmap_Data (f, img, data,
4ef0d4d0
KS
2891 foreground, background,
2892 non_default_colors);
2893 xfree (data);
2894
2895 if (img->pixmap == NO_PIXMAP)
2896 {
2897 x_clear_image (f, img);
2898 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2899 }
2900 else
2901 success_p = 1;
2902 }
2903 else
2904 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2905
2906 return success_p;
2907}
2908
2909
578098f3 2910/* Value is true if DATA looks like an in-memory XBM file. */
4ef0d4d0 2911
578098f3 2912static bool
d3da34e0 2913xbm_file_p (Lisp_Object data)
4ef0d4d0
KS
2914{
2915 int w, h;
2916 return (STRINGP (data)
f1f25b99 2917 && xbm_read_bitmap_data (NULL, SDATA (data),
ce959360
CY
2918 (SDATA (data) + SBYTES (data)),
2919 &w, &h, NULL, 1));
4ef0d4d0
KS
2920}
2921
2922
2923/* Fill image IMG which is used on frame F with pixmap data. Value is
578098f3 2924 true if successful. */
4ef0d4d0 2925
578098f3 2926static bool
d3da34e0 2927xbm_load (struct frame *f, struct image *img)
4ef0d4d0 2928{
578098f3 2929 bool success_p = 0;
4ef0d4d0
KS
2930 Lisp_Object file_name;
2931
a54e2c05 2932 eassert (xbm_image_p (img->spec));
4ef0d4d0
KS
2933
2934 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2935 file_name = image_spec_value (img->spec, QCfile, NULL);
2936 if (STRINGP (file_name))
2937 {
2938 Lisp_Object file;
2939 unsigned char *contents;
dd52fcea 2940 ptrdiff_t size;
4ef0d4d0
KS
2941
2942 file = x_find_image_file (file_name);
4ef0d4d0
KS
2943 if (!STRINGP (file))
2944 {
2945 image_error ("Cannot find image file `%s'", file_name, Qnil);
4ef0d4d0
KS
2946 return 0;
2947 }
2948
42a5b22f 2949 contents = slurp_file (SSDATA (file), &size);
4ef0d4d0
KS
2950 if (contents == NULL)
2951 {
2952 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
4ef0d4d0
KS
2953 return 0;
2954 }
2955
2956 success_p = xbm_load_image (f, img, contents, contents + size);
d5a19415 2957 xfree (contents);
4ef0d4d0
KS
2958 }
2959 else
2960 {
2961 struct image_keyword fmt[XBM_LAST];
2962 Lisp_Object data;
2963 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2964 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
578098f3 2965 bool non_default_colors = 0;
4ef0d4d0 2966 char *bits;
578098f3
PE
2967 bool parsed_p;
2968 bool in_memory_file_p = 0;
4ef0d4d0
KS
2969
2970 /* See if data looks like an in-memory XBM file. */
2971 data = image_spec_value (img->spec, QCdata, NULL);
2972 in_memory_file_p = xbm_file_p (data);
2973
2974 /* Parse the image specification. */
72af86bd 2975 memcpy (fmt, xbm_format, sizeof fmt);
4ef0d4d0 2976 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
a54e2c05 2977 eassert (parsed_p);
4ef0d4d0
KS
2978
2979 /* Get specified width, and height. */
2980 if (!in_memory_file_p)
2981 {
2982 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2983 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
a54e2c05 2984 eassert (img->width > 0 && img->height > 0);
ca4aa935
PE
2985 if (!check_image_size (f, img->width, img->height))
2986 {
2987 image_error ("Invalid image size (see `max-image-size')",
2988 Qnil, Qnil);
2989 return 0;
2990 }
4ef0d4d0
KS
2991 }
2992
2993 /* Get foreground and background colors, maybe allocate colors. */
2994 if (fmt[XBM_FOREGROUND].count
2995 && STRINGP (fmt[XBM_FOREGROUND].value))
2996 {
2997 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2998 foreground);
2999 non_default_colors = 1;
3000 }
3001
3002 if (fmt[XBM_BACKGROUND].count
3003 && STRINGP (fmt[XBM_BACKGROUND].value))
3004 {
3005 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3006 background);
3007 non_default_colors = 1;
3008 }
3009
3010 if (in_memory_file_p)
3011 success_p = xbm_load_image (f, img, SDATA (data),
3012 (SDATA (data)
3013 + SBYTES (data)));
3014 else
3015 {
3016 if (VECTORP (data))
3017 {
3018 int i;
3019 char *p;
3020 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3021
38182d90 3022 p = bits = alloca (nbytes * img->height);
4ef0d4d0
KS
3023 for (i = 0; i < img->height; ++i, p += nbytes)
3024 {
28be1ada 3025 Lisp_Object line = AREF (data, i);
4ef0d4d0 3026 if (STRINGP (line))
72af86bd 3027 memcpy (p, SDATA (line), nbytes);
4ef0d4d0 3028 else
72af86bd 3029 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
4ef0d4d0
KS
3030 }
3031 }
3032 else if (STRINGP (data))
42a5b22f 3033 bits = SSDATA (data);
4ef0d4d0 3034 else
b8dc29e9 3035 bits = (char *) XBOOL_VECTOR (data)->data;
4ef0d4d0 3036
0fda9b75 3037#ifdef HAVE_NTGUI
44b1dc2e
JR
3038 {
3039 char *invertedBits;
3040 int nbytes, i;
3041 /* Windows mono bitmaps are reversed compared with X. */
3042 invertedBits = bits;
285d07e2 3043 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
44b1dc2e 3044 * img->height;
38182d90 3045 bits = alloca (nbytes);
44b1dc2e
JR
3046 for (i = 0; i < nbytes; i++)
3047 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3048 }
3049#endif
4ef0d4d0
KS
3050 /* Create the pixmap. */
3051
ca4aa935
PE
3052 if (x_check_image_size (0, img->width, img->height))
3053 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3054 foreground, background,
3055 non_default_colors);
3056 else
3057 img->pixmap = NO_PIXMAP;
3058
4ef0d4d0
KS
3059 if (img->pixmap)
3060 success_p = 1;
3061 else
3062 {
3063 image_error ("Unable to create pixmap for XBM image `%s'",
3064 img->spec, Qnil);
3065 x_clear_image (f, img);
3066 }
3067 }
3068 }
3069
3070 return success_p;
3071}
3072
3073
3074\f
3075/***********************************************************************
3076 XPM images
3077 ***********************************************************************/
3078
9e2a2647 3079#if defined (HAVE_XPM) || defined (HAVE_NS)
4ef0d4d0 3080
578098f3
PE
3081static bool xpm_image_p (Lisp_Object object);
3082static bool xpm_load (struct frame *f, struct image *img);
4ef0d4d0 3083
9e2a2647 3084#endif /* HAVE_XPM || HAVE_NS */
ea1aaa6f
ST
3085
3086#ifdef HAVE_XPM
4ef0d4d0
KS
3087#ifdef HAVE_NTGUI
3088/* Indicate to xpm.h that we don't have Xlib. */
3089#define FOR_MSW
3090/* simx.h in xpm defines XColor and XImage differently than Emacs. */
279d3293 3091/* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
4ef0d4d0
KS
3092#define XColor xpm_XColor
3093#define XImage xpm_XImage
279d3293 3094#define Display xpm_Display
4ef0d4d0
KS
3095#define PIXEL_ALREADY_TYPEDEFED
3096#include "X11/xpm.h"
3097#undef FOR_MSW
3098#undef XColor
3099#undef XImage
279d3293 3100#undef Display
4ef0d4d0
KS
3101#undef PIXEL_ALREADY_TYPEDEFED
3102#else
3103#include "X11/xpm.h"
3104#endif /* HAVE_NTGUI */
ea1aaa6f 3105#endif /* HAVE_XPM */
4ef0d4d0 3106
9e2a2647 3107#if defined (HAVE_XPM) || defined (HAVE_NS)
4ef0d4d0
KS
3108/* The symbol `xpm' identifying XPM-format images. */
3109
955cbe7b 3110static Lisp_Object Qxpm;
4ef0d4d0
KS
3111
3112/* Indices of image specification fields in xpm_format, below. */
3113
3114enum xpm_keyword_index
3115{
3116 XPM_TYPE,
3117 XPM_FILE,
3118 XPM_DATA,
3119 XPM_ASCENT,
3120 XPM_MARGIN,
3121 XPM_RELIEF,
3122 XPM_ALGORITHM,
3123 XPM_HEURISTIC_MASK,
3124 XPM_MASK,
3125 XPM_COLOR_SYMBOLS,
3126 XPM_BACKGROUND,
3127 XPM_LAST
3128};
3129
3130/* Vector of image_keyword structures describing the format
3131 of valid XPM image specifications. */
3132
91433552 3133static const struct image_keyword xpm_format[XPM_LAST] =
4ef0d4d0
KS
3134{
3135 {":type", IMAGE_SYMBOL_VALUE, 1},
3136 {":file", IMAGE_STRING_VALUE, 0},
3137 {":data", IMAGE_STRING_VALUE, 0},
3138 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 3139 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
3140 {":relief", IMAGE_INTEGER_VALUE, 0},
3141 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3142 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3143 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3144 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3145 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3146};
3147
a9e7a9d5 3148#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 3149static bool init_xpm_functions (void);
bb4d86b4
CY
3150#else
3151#define init_xpm_functions NULL
3152#endif
3153
4ef0d4d0
KS
3154/* Structure describing the image type XPM. */
3155
3156static struct image_type xpm_type =
3157{
3158 &Qxpm,
3159 xpm_image_p,
3160 xpm_load,
3161 x_clear_image,
bb4d86b4 3162 init_xpm_functions,
4ef0d4d0
KS
3163 NULL
3164};
3165
3166#ifdef HAVE_X_WINDOWS
3167
3168/* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3169 functions for allocating image colors. Our own functions handle
3170 color allocation failures more gracefully than the ones on the XPM
3171 lib. */
3172
3173#if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3174#define ALLOC_XPM_COLORS
3175#endif
3176#endif /* HAVE_X_WINDOWS */
3177
3178#ifdef ALLOC_XPM_COLORS
3179
f57e2426
J
3180static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3181 XColor *, int);
4ef0d4d0
KS
3182
3183/* An entry in a hash table used to cache color definitions of named
3184 colors. This cache is necessary to speed up XPM image loading in
3185 case we do color allocations ourselves. Without it, we would need
3186 a call to XParseColor per pixel in the image. */
3187
3188struct xpm_cached_color
3189{
3190 /* Next in collision chain. */
3191 struct xpm_cached_color *next;
3192
3193 /* Color definition (RGB and pixel color). */
3194 XColor color;
3195
3196 /* Color name. */
fbe9e0b9 3197 char name[FLEXIBLE_ARRAY_MEMBER];
4ef0d4d0
KS
3198};
3199
3200/* The hash table used for the color cache, and its bucket vector
3201 size. */
3202
3203#define XPM_COLOR_CACHE_BUCKETS 1001
cd44d2eb 3204static struct xpm_cached_color **xpm_color_cache;
4ef0d4d0
KS
3205
3206/* Initialize the color cache. */
3207
3208static void
d3da34e0 3209xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
4ef0d4d0
KS
3210{
3211 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
23f86fce 3212 xpm_color_cache = xzalloc (nbytes);
4ef0d4d0
KS
3213 init_color_table ();
3214
3215 if (attrs->valuemask & XpmColorSymbols)
3216 {
3217 int i;
3218 XColor color;
3219
3220 for (i = 0; i < attrs->numsymbols; ++i)
3221 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3222 attrs->colorsymbols[i].value, &color))
3223 {
3224 color.pixel = lookup_rgb_color (f, color.red, color.green,
3225 color.blue);
3226 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3227 }
3228 }
3229}
3230
3231/* Free the color cache. */
3232
3233static void
d3da34e0 3234xpm_free_color_cache (void)
4ef0d4d0
KS
3235{
3236 struct xpm_cached_color *p, *next;
3237 int i;
3238
3239 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3240 for (p = xpm_color_cache[i]; p; p = next)
3241 {
3242 next = p->next;
3243 xfree (p);
3244 }
3245
3246 xfree (xpm_color_cache);
3247 xpm_color_cache = NULL;
3248 free_color_table ();
3249}
3250
3251/* Return the bucket index for color named COLOR_NAME in the color
3252 cache. */
3253
3254static int
d3da34e0 3255xpm_color_bucket (char *color_name)
4ef0d4d0 3256{
3f791afe
PE
3257 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3258 return hash % XPM_COLOR_CACHE_BUCKETS;
4ef0d4d0
KS
3259}
3260
3261
3262/* On frame F, cache values COLOR for color with name COLOR_NAME.
3263 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3264 entry added. */
3265
3266static struct xpm_cached_color *
d3da34e0 3267xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
4ef0d4d0
KS
3268{
3269 size_t nbytes;
3270 struct xpm_cached_color *p;
3271
3272 if (bucket < 0)
3273 bucket = xpm_color_bucket (color_name);
3274
3f791afe 3275 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
23f86fce 3276 p = xmalloc (nbytes);
4ef0d4d0
KS
3277 strcpy (p->name, color_name);
3278 p->color = *color;
3279 p->next = xpm_color_cache[bucket];
3280 xpm_color_cache[bucket] = p;
3281 return p;
3282}
3283
3284/* Look up color COLOR_NAME for frame F in the color cache. If found,
3285 return the cached definition in *COLOR. Otherwise, make a new
578098f3 3286 entry in the cache and allocate the color. Value is false if color
4ef0d4d0
KS
3287 allocation failed. */
3288
578098f3 3289static bool
d3da34e0 3290xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
4ef0d4d0
KS
3291{
3292 struct xpm_cached_color *p;
3293 int h = xpm_color_bucket (color_name);
3294
3295 for (p = xpm_color_cache[h]; p; p = p->next)
3296 if (strcmp (p->name, color_name) == 0)
3297 break;
3298
3299 if (p != NULL)
3300 *color = p->color;
3301 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3302 color_name, color))
3303 {
3304 color->pixel = lookup_rgb_color (f, color->red, color->green,
3305 color->blue);
3306 p = xpm_cache_color (f, color_name, color, h);
3307 }
3308 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3309 with transparency, and it's useful. */
3310 else if (strcmp ("opaque", color_name) == 0)
3311 {
72af86bd 3312 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
4ef0d4d0
KS
3313 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3314 p = xpm_cache_color (f, color_name, color, h);
3315 }
3316
3317 return p != NULL;
3318}
3319
3320
3321/* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3322 CLOSURE is a pointer to the frame on which we allocate the
3323 color. Return in *COLOR the allocated color. Value is non-zero
3324 if successful. */
3325
3326static int
d3da34e0
JB
3327xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3328 void *closure)
4ef0d4d0
KS
3329{
3330 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3331}
3332
3333
3334/* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3335 is a pointer to the frame on which we allocate the color. Value is
3336 non-zero if successful. */
3337
3338static int
d3da34e0 3339xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
4ef0d4d0
KS
3340{
3341 return 1;
3342}
3343
3344#endif /* ALLOC_XPM_COLORS */
3345
3346
0fda9b75 3347#ifdef WINDOWSNT
4ef0d4d0
KS
3348
3349/* XPM library details. */
3350
14beddf4
CY
3351DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
3352DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
850690cc 3353 xpm_XImage **, XpmAttributes *));
14beddf4 3354DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
850690cc 3355 xpm_XImage **, XpmAttributes *));
14beddf4 3356DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
4ef0d4d0 3357
578098f3 3358static bool
d07ff9db 3359init_xpm_functions (void)
4ef0d4d0
KS
3360{
3361 HMODULE library;
3362
d07ff9db 3363 if (!(library = w32_delayed_load (Qxpm)))
4ef0d4d0
KS
3364 return 0;
3365
3366 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3367 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3368 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3369 LOAD_IMGLIB_FN (library, XImageFree);
3370 return 1;
3371}
3372
0fda9b75 3373#endif /* WINDOWSNT */
4ef0d4d0 3374
a9e7a9d5 3375#if defined HAVE_NTGUI && !defined WINDOWSNT
0fda9b75
DC
3376/* Glue for code below */
3377#define fn_XpmReadFileToImage XpmReadFileToImage
3378#define fn_XpmCreateImageFromBuffer XpmCreateImageFromBuffer
3379#define fn_XImageFree XImageFree
3380#define fn_XpmFreeAttributes XpmFreeAttributes
2ae3a8a7 3381#endif /* HAVE_NTGUI && !WINDOWSNT */
4ef0d4d0 3382
578098f3 3383/* Value is true if COLOR_SYMBOLS is a valid color symbols list
4ef0d4d0
KS
3384 for XPM images. Such a list must consist of conses whose car and
3385 cdr are strings. */
3386
578098f3 3387static bool
d3da34e0 3388xpm_valid_color_symbols_p (Lisp_Object color_symbols)
4ef0d4d0
KS
3389{
3390 while (CONSP (color_symbols))
3391 {
3392 Lisp_Object sym = XCAR (color_symbols);
3393 if (!CONSP (sym)
3394 || !STRINGP (XCAR (sym))
3395 || !STRINGP (XCDR (sym)))
3396 break;
3397 color_symbols = XCDR (color_symbols);
3398 }
3399
3400 return NILP (color_symbols);
3401}
3402
3403
578098f3 3404/* Value is true if OBJECT is a valid XPM image specification. */
4ef0d4d0 3405
578098f3 3406static bool
d3da34e0 3407xpm_image_p (Lisp_Object object)
4ef0d4d0
KS
3408{
3409 struct image_keyword fmt[XPM_LAST];
72af86bd 3410 memcpy (fmt, xpm_format, sizeof fmt);
4ef0d4d0
KS
3411 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3412 /* Either `:file' or `:data' must be present. */
3413 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3414 /* Either no `:color-symbols' or it's a list of conses
3415 whose car and cdr are strings. */
3416 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3417 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3418}
3419
9e2a2647 3420#endif /* HAVE_XPM || HAVE_NS */
4ef0d4d0 3421
cd44d2eb 3422#if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
0766b489 3423ptrdiff_t
ef1b0ba7 3424x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
786a43d6
CY
3425{
3426 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
0766b489
PE
3427 ptrdiff_t id;
3428 int rc;
786a43d6
CY
3429 XpmAttributes attrs;
3430 Pixmap bitmap, mask;
3431
72af86bd 3432 memset (&attrs, 0, sizeof attrs);
786a43d6 3433
54188d8f
CY
3434 attrs.visual = FRAME_X_VISUAL (f);
3435 attrs.colormap = FRAME_X_COLORMAP (f);
3436 attrs.valuemask |= XpmVisual;
3437 attrs.valuemask |= XpmColormap;
3438
786a43d6 3439 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
f77fabaf 3440 (char **) bits, &bitmap, &mask, &attrs);
786a43d6 3441 if (rc != XpmSuccess)
fe45ad15
CY
3442 {
3443 XpmFreeAttributes (&attrs);
3444 return -1;
3445 }
786a43d6
CY
3446
3447 id = x_allocate_bitmap_record (f);
786a43d6
CY
3448 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3449 dpyinfo->bitmaps[id - 1].have_mask = 1;
3450 dpyinfo->bitmaps[id - 1].mask = mask;
3451 dpyinfo->bitmaps[id - 1].file = NULL;
3452 dpyinfo->bitmaps[id - 1].height = attrs.height;
3453 dpyinfo->bitmaps[id - 1].width = attrs.width;
3454 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3455 dpyinfo->bitmaps[id - 1].refcount = 1;
3456
3457 XpmFreeAttributes (&attrs);
3458 return id;
3459}
0d876a14 3460#endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
786a43d6 3461
4ef0d4d0 3462/* Load image IMG which will be displayed on frame F. Value is
578098f3 3463 true if successful. */
4ef0d4d0 3464
ea1aaa6f
ST
3465#ifdef HAVE_XPM
3466
578098f3 3467static bool
d3da34e0 3468xpm_load (struct frame *f, struct image *img)
4ef0d4d0
KS
3469{
3470 int rc;
3471 XpmAttributes attrs;
3472 Lisp_Object specified_file, color_symbols;
3473#ifdef HAVE_NTGUI
3474 HDC hdc;
3475 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3476#endif /* HAVE_NTGUI */
3477
3478 /* Configure the XPM lib. Use the visual of frame F. Allocate
3479 close colors. Return colors allocated. */
72af86bd 3480 memset (&attrs, 0, sizeof attrs);
4ef0d4d0
KS
3481
3482#ifndef HAVE_NTGUI
3483 attrs.visual = FRAME_X_VISUAL (f);
3484 attrs.colormap = FRAME_X_COLORMAP (f);
3485 attrs.valuemask |= XpmVisual;
3486 attrs.valuemask |= XpmColormap;
3487#endif /* HAVE_NTGUI */
3488
3489#ifdef ALLOC_XPM_COLORS
3490 /* Allocate colors with our own functions which handle
3491 failing color allocation more gracefully. */
3492 attrs.color_closure = f;
3493 attrs.alloc_color = xpm_alloc_color;
3494 attrs.free_colors = xpm_free_colors;
3495 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3496#else /* not ALLOC_XPM_COLORS */
3497 /* Let the XPM lib allocate colors. */
3498 attrs.valuemask |= XpmReturnAllocPixels;
3499#ifdef XpmAllocCloseColors
3500 attrs.alloc_close_colors = 1;
3501 attrs.valuemask |= XpmAllocCloseColors;
3502#else /* not XpmAllocCloseColors */
3503 attrs.closeness = 600;
3504 attrs.valuemask |= XpmCloseness;
3505#endif /* not XpmAllocCloseColors */
3506#endif /* ALLOC_XPM_COLORS */
3507
3508 /* If image specification contains symbolic color definitions, add
3509 these to `attrs'. */
3510 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3511 if (CONSP (color_symbols))
3512 {
3513 Lisp_Object tail;
3514 XpmColorSymbol *xpm_syms;
3515 int i, size;
3516
3517 attrs.valuemask |= XpmColorSymbols;
3518
3519 /* Count number of symbols. */
3520 attrs.numsymbols = 0;
3521 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3522 ++attrs.numsymbols;
3523
3524 /* Allocate an XpmColorSymbol array. */
3525 size = attrs.numsymbols * sizeof *xpm_syms;
38182d90 3526 xpm_syms = alloca (size);
72af86bd 3527 memset (xpm_syms, 0, size);
4ef0d4d0
KS
3528 attrs.colorsymbols = xpm_syms;
3529
3530 /* Fill the color symbol array. */
3531 for (tail = color_symbols, i = 0;
3532 CONSP (tail);
3533 ++i, tail = XCDR (tail))
3534 {
7574650a
AS
3535 Lisp_Object name;
3536 Lisp_Object color;
e22cffbc 3537 char *empty_string = (char *) "";
7574650a
AS
3538
3539 if (!CONSP (XCAR (tail)))
3540 {
e22cffbc
PE
3541 xpm_syms[i].name = empty_string;
3542 xpm_syms[i].value = empty_string;
7574650a
AS
3543 continue;
3544 }
3545 name = XCAR (XCAR (tail));
3546 color = XCDR (XCAR (tail));
3547 if (STRINGP (name))
3548 {
38182d90 3549 xpm_syms[i].name = alloca (SCHARS (name) + 1);
42a5b22f 3550 strcpy (xpm_syms[i].name, SSDATA (name));
7574650a
AS
3551 }
3552 else
e22cffbc 3553 xpm_syms[i].name = empty_string;
7574650a
AS
3554 if (STRINGP (color))
3555 {
38182d90 3556 xpm_syms[i].value = alloca (SCHARS (color) + 1);
42a5b22f 3557 strcpy (xpm_syms[i].value, SSDATA (color));
7574650a
AS
3558 }
3559 else
e22cffbc 3560 xpm_syms[i].value = empty_string;
4ef0d4d0
KS
3561 }
3562 }
3563
3564 /* Create a pixmap for the image, either from a file, or from a
3565 string buffer containing data in the same format as an XPM file. */
3566#ifdef ALLOC_XPM_COLORS
3567 xpm_init_color_cache (f, &attrs);
3568#endif
3569
3570 specified_file = image_spec_value (img->spec, QCfile, NULL);
3571
3572#ifdef HAVE_NTGUI
3573 {
3574 HDC frame_dc = get_frame_dc (f);
3575 hdc = CreateCompatibleDC (frame_dc);
3576 release_frame_dc (f, frame_dc);
3577 }
3578#endif /* HAVE_NTGUI */
3579
3580 if (STRINGP (specified_file))
3581 {
3582 Lisp_Object file = x_find_image_file (specified_file);
3583 if (!STRINGP (file))
3584 {
3585 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7574650a
AS
3586#ifdef ALLOC_XPM_COLORS
3587 xpm_free_color_cache ();
3588#endif
4ef0d4d0
KS
3589 return 0;
3590 }
3591
3592#ifdef HAVE_NTGUI
3593 /* XpmReadFileToPixmap is not available in the Windows port of
3594 libxpm. But XpmReadFileToImage almost does what we want. */
3595 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3596 &xpm_image, &xpm_mask,
3597 &attrs);
3598#else
547c9269
YM
3599 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3600 &img->ximg, &img->mask_img,
3601 &attrs);
4ef0d4d0
KS
3602#endif /* HAVE_NTGUI */
3603 }
3604 else
3605 {
3606 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
7574650a
AS
3607 if (!STRINGP (buffer))
3608 {
3609 image_error ("Invalid image data `%s'", buffer, Qnil);
3610#ifdef ALLOC_XPM_COLORS
3611 xpm_free_color_cache ();
3612#endif
3613 return 0;
3614 }
4ef0d4d0
KS
3615#ifdef HAVE_NTGUI
3616 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3617 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3618 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3619 &xpm_image, &xpm_mask,
3620 &attrs);
3621#else
547c9269
YM
3622 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3623 &img->ximg, &img->mask_img,
3624 &attrs);
4ef0d4d0
KS
3625#endif /* HAVE_NTGUI */
3626 }
3627
547c9269
YM
3628#ifdef HAVE_X_WINDOWS
3629 if (rc == XpmSuccess)
3630 {
3631 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3632 img->ximg->width, img->ximg->height,
3633 img->ximg->depth);
3634 if (img->pixmap == NO_PIXMAP)
3635 {
3636 x_clear_image (f, img);
3637 rc = XpmNoMemory;
3638 }
3639 else if (img->mask_img)
3640 {
3641 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3642 img->mask_img->width,
3643 img->mask_img->height,
3644 img->mask_img->depth);
3645 if (img->mask == NO_PIXMAP)
3646 {
3647 x_clear_image (f, img);
3648 rc = XpmNoMemory;
3649 }
3650 }
3651 }
3652#endif
3653
4ef0d4d0
KS
3654 if (rc == XpmSuccess)
3655 {
3656#if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3657 img->colors = colors_in_color_table (&img->ncolors);
3658#else /* not ALLOC_XPM_COLORS */
3659 int i;
3660
3661#ifdef HAVE_NTGUI
3662 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3663 plus some duplicate attributes. */
3664 if (xpm_image && xpm_image->bitmap)
3665 {
3666 img->pixmap = xpm_image->bitmap;
3667 /* XImageFree in libXpm frees XImage struct without destroying
3668 the bitmap, which is what we want. */
3669 fn_XImageFree (xpm_image);
3670 }
3671 if (xpm_mask && xpm_mask->bitmap)
3672 {
3673 /* The mask appears to be inverted compared with what we expect.
3674 TODO: invert our expectations. See other places where we
3675 have to invert bits because our idea of masks is backwards. */
3676 HGDIOBJ old_obj;
3677 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3678
3679 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3680 SelectObject (hdc, old_obj);
3681
3682 img->mask = xpm_mask->bitmap;
3683 fn_XImageFree (xpm_mask);
3684 DeleteDC (hdc);
3685 }
3686
3687 DeleteDC (hdc);
3688#endif /* HAVE_NTGUI */
3689
3690 /* Remember allocated colors. */
0065d054 3691 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
ddff3151 3692 img->ncolors = attrs.nalloc_pixels;
4ef0d4d0
KS
3693 for (i = 0; i < attrs.nalloc_pixels; ++i)
3694 {
3695 img->colors[i] = attrs.alloc_pixels[i];
3696#ifdef DEBUG_X_COLORS
3697 register_color (img->colors[i]);
3698#endif
3699 }
3700#endif /* not ALLOC_XPM_COLORS */
3701
3702 img->width = attrs.width;
3703 img->height = attrs.height;
a54e2c05 3704 eassert (img->width > 0 && img->height > 0);
4ef0d4d0
KS
3705
3706 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3707#ifdef HAVE_NTGUI
3708 fn_XpmFreeAttributes (&attrs);
3709#else
3710 XpmFreeAttributes (&attrs);
3711#endif /* HAVE_NTGUI */
547c9269
YM
3712
3713#ifdef HAVE_X_WINDOWS
3714 /* Maybe fill in the background field while we have ximg handy. */
3715 IMAGE_BACKGROUND (img, f, img->ximg);
3716 if (img->mask_img)
3717 /* Fill in the background_transparent field while we have the
3718 mask handy. */
3719 image_background_transparent (img, f, img->mask_img);
3720#endif
4ef0d4d0
KS
3721 }
3722 else
3723 {
3724#ifdef HAVE_NTGUI
3725 DeleteDC (hdc);
3726#endif /* HAVE_NTGUI */
3727
3728 switch (rc)
3729 {
3730 case XpmOpenFailed:
3731 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3732 break;
3733
3734 case XpmFileInvalid:
3735 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3736 break;
3737
3738 case XpmNoMemory:
3739 image_error ("Out of memory (%s)", img->spec, Qnil);
3740 break;
3741
3742 case XpmColorFailed:
3743 image_error ("Color allocation error (%s)", img->spec, Qnil);
3744 break;
3745
3746 default:
3747 image_error ("Unknown error (%s)", img->spec, Qnil);
3748 break;
3749 }
3750 }
3751
3752#ifdef ALLOC_XPM_COLORS
3753 xpm_free_color_cache ();
3754#endif
3755 return rc == XpmSuccess;
3756}
3757
3758#endif /* HAVE_XPM */
3759
9e2a2647 3760#if defined (HAVE_NS) && !defined (HAVE_XPM)
ea1aaa6f 3761
9e2a2647 3762/* XPM support functions for NS where libxpm is not available.
ea1aaa6f
ST
3763 Only XPM version 3 (without any extensions) is supported. */
3764
f57e2426
J
3765static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3766 int, Lisp_Object);
3767static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3768 const unsigned char *, int);
f57e2426
J
3769static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3770 int, Lisp_Object);
3771static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3772 const unsigned char *, int);
ea1aaa6f
ST
3773
3774/* Tokens returned from xpm_scan. */
3775
3776enum xpm_token
3777{
3778 XPM_TK_IDENT = 256,
3779 XPM_TK_STRING,
3780 XPM_TK_EOF
3781};
3782
3783/* Scan an XPM data and return a character (< 256) or a token defined
3784 by enum xpm_token above. *S and END are the start (inclusive) and
3785 the end (exclusive) addresses of the data, respectively. Advance
3786 *S while scanning. If token is either XPM_TK_IDENT or
3787 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3788 length of the corresponding token, respectively. */
3789
3790static int
3d608a86
J
3791xpm_scan (const unsigned char **s,
3792 const unsigned char *end,
3793 const unsigned char **beg,
74ca2eb3 3794 ptrdiff_t *len)
ea1aaa6f
ST
3795{
3796 int c;
3797
3798 while (*s < end)
3799 {
3800 /* Skip white-space. */
620f13b0 3801 while (*s < end && (c = *(*s)++, c_isspace (c)))
9ecf6403 3802 ;
ea1aaa6f
ST
3803
3804 /* gnus-pointer.xpm uses '-' in its identifier.
9ecf6403 3805 sb-dir-plus.xpm uses '+' in its identifier. */
620f13b0 3806 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
9ecf6403
YM
3807 {
3808 *beg = *s - 1;
2ff0845e 3809 while (*s < end
620f13b0
PE
3810 && (c = **s, c_isalnum (c)
3811 || c == '_' || c == '-' || c == '+'))
9ecf6403
YM
3812 ++*s;
3813 *len = *s - *beg;
3814 return XPM_TK_IDENT;
3815 }
ea1aaa6f 3816 else if (c == '"')
9ecf6403
YM
3817 {
3818 *beg = *s;
3819 while (*s < end && **s != '"')
3820 ++*s;
3821 *len = *s - *beg;
3822 if (*s < end)
3823 ++*s;
3824 return XPM_TK_STRING;
3825 }
ea1aaa6f 3826 else if (c == '/')
9ecf6403
YM
3827 {
3828 if (*s < end && **s == '*')
3829 {
3830 /* C-style comment. */
3831 ++*s;
3832 do
3833 {
3834 while (*s < end && *(*s)++ != '*')
3835 ;
3836 }
3837 while (*s < end && **s != '/');
3838 if (*s < end)
3839 ++*s;
3840 }
3841 else
3842 return c;
3843 }
ea1aaa6f 3844 else
9ecf6403 3845 return c;
ea1aaa6f
ST
3846 }
3847
3848 return XPM_TK_EOF;
3849}
3850
bbe6f2aa 3851/* Functions for color table lookup in XPM data. A key is a string
ea1aaa6f
ST
3852 specifying the color of each pixel in XPM data. A value is either
3853 an integer that specifies a pixel color, Qt that specifies
3854 transparency, or Qnil for the unspecified color. If the length of
3855 the key string is one, a vector is used as a table. Otherwise, a
3856 hash table is used. */
3857
3858static Lisp_Object
3d608a86
J
3859xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3860 const unsigned char *,
3861 int,
3862 Lisp_Object),
3863 Lisp_Object (**get_func) (Lisp_Object,
3864 const unsigned char *,
3865 int))
ea1aaa6f
ST
3866{
3867 *put_func = xpm_put_color_table_v;
3868 *get_func = xpm_get_color_table_v;
3869 return Fmake_vector (make_number (256), Qnil);
3870}
3871
3872static void
3d608a86
J
3873xpm_put_color_table_v (Lisp_Object color_table,
3874 const unsigned char *chars_start,
3875 int chars_len,
3876 Lisp_Object color)
ea1aaa6f 3877{
28be1ada 3878 ASET (color_table, *chars_start, color);
ea1aaa6f
ST
3879}
3880
3881static Lisp_Object
3d608a86
J
3882xpm_get_color_table_v (Lisp_Object color_table,
3883 const unsigned char *chars_start,
3884 int chars_len)
ea1aaa6f 3885{
28be1ada 3886 return AREF (color_table, *chars_start);
ea1aaa6f
ST
3887}
3888
3889static Lisp_Object
3d608a86
J
3890xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3891 const unsigned char *,
3892 int,
3893 Lisp_Object),
3894 Lisp_Object (**get_func) (Lisp_Object,
3895 const unsigned char *,
3896 int))
ea1aaa6f
ST
3897{
3898 *put_func = xpm_put_color_table_h;
3899 *get_func = xpm_get_color_table_h;
4ab15c3e 3900 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
9ecf6403
YM
3901 make_float (DEFAULT_REHASH_SIZE),
3902 make_float (DEFAULT_REHASH_THRESHOLD),
a23c4171 3903 Qnil);
ea1aaa6f
ST
3904}
3905
3906static void
3d608a86
J
3907xpm_put_color_table_h (Lisp_Object color_table,
3908 const unsigned char *chars_start,
3909 int chars_len,
3910 Lisp_Object color)
ea1aaa6f
ST
3911{
3912 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
0de4bb68 3913 EMACS_UINT hash_code;
ea1aaa6f
ST
3914 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3915
3916 hash_lookup (table, chars, &hash_code);
3917 hash_put (table, chars, color, hash_code);
3918}
3919
3920static Lisp_Object
3d608a86
J
3921xpm_get_color_table_h (Lisp_Object color_table,
3922 const unsigned char *chars_start,
3923 int chars_len)
ea1aaa6f
ST
3924{
3925 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
d3411f89
PE
3926 ptrdiff_t i =
3927 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
ea1aaa6f
ST
3928
3929 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3930}
3931
3932enum xpm_color_key {
3933 XPM_COLOR_KEY_S,
3934 XPM_COLOR_KEY_M,
3935 XPM_COLOR_KEY_G4,
3936 XPM_COLOR_KEY_G,
3937 XPM_COLOR_KEY_C
3938};
3939
46accb8f 3940static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
ea1aaa6f
ST
3941
3942static int
3d608a86 3943xpm_str_to_color_key (const char *s)
ea1aaa6f
ST
3944{
3945 int i;
3946
3947 for (i = 0;
3948 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3949 i++)
3950 if (strcmp (xpm_color_key_strings[i], s) == 0)
3951 return i;
3952 return -1;
3953}
3954
578098f3 3955static bool
3d608a86
J
3956xpm_load_image (struct frame *f,
3957 struct image *img,
3958 const unsigned char *contents,
3959 const unsigned char *end)
ea1aaa6f 3960{
46accb8f 3961 const unsigned char *s = contents, *beg, *str;
ea1aaa6f
ST
3962 unsigned char buffer[BUFSIZ];
3963 int width, height, x, y;
3964 int num_colors, chars_per_pixel;
74ca2eb3
PE
3965 ptrdiff_t len;
3966 int LA1;
46accb8f
YM
3967 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3968 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
ea1aaa6f 3969 Lisp_Object frame, color_symbols, color_table;
578098f3
PE
3970 int best_key;
3971 bool have_mask = 0;
ea1aaa6f
ST
3972 XImagePtr ximg = NULL, mask_img = NULL;
3973
3974#define match() \
3975 LA1 = xpm_scan (&s, end, &beg, &len)
3976
9ecf6403
YM
3977#define expect(TOKEN) \
3978 if (LA1 != (TOKEN)) \
3979 goto failure; \
3980 else \
ea1aaa6f
ST
3981 match ()
3982
9ecf6403 3983#define expect_ident(IDENT) \
ea1aaa6f 3984 if (LA1 == XPM_TK_IDENT \
9ecf6403
YM
3985 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3986 match (); \
3987 else \
ea1aaa6f
ST
3988 goto failure
3989
3990 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3991 goto failure;
3992 s += 9;
ed3751c8 3993 match ();
ea1aaa6f
ST
3994 expect_ident ("static");
3995 expect_ident ("char");
3996 expect ('*');
3997 expect (XPM_TK_IDENT);
3998 expect ('[');
3999 expect (']');
4000 expect ('=');
4001 expect ('{');
4002 expect (XPM_TK_STRING);
4003 if (len >= BUFSIZ)
4004 goto failure;
4005 memcpy (buffer, beg, len);
4006 buffer[len] = '\0';
4007 if (sscanf (buffer, "%d %d %d %d", &width, &height,
9ecf6403 4008 &num_colors, &chars_per_pixel) != 4
ea1aaa6f
ST
4009 || width <= 0 || height <= 0
4010 || num_colors <= 0 || chars_per_pixel <= 0)
4011 goto failure;
de297941
YM
4012
4013 if (!check_image_size (f, width, height))
4014 {
10ea2b82 4015 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
de297941
YM
4016 goto failure;
4017 }
4018
547c9269 4019 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
ca4aa935 4020#ifndef HAVE_NS
547c9269
YM
4021 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4022 &mask_img, 1)
ca4aa935
PE
4023#endif
4024 )
4025 {
4026 image_error ("Image too large", Qnil, Qnil);
4027 goto failure;
4028 }
4029
ea1aaa6f
ST
4030 expect (',');
4031
4032 XSETFRAME (frame, f);
4033 if (!NILP (Fxw_display_color_p (frame)))
4034 best_key = XPM_COLOR_KEY_C;
4035 else if (!NILP (Fx_display_grayscale_p (frame)))
4036 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
9ecf6403 4037 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
ea1aaa6f
ST
4038 else
4039 best_key = XPM_COLOR_KEY_M;
4040
4041 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4042 if (chars_per_pixel == 1)
4043 color_table = xpm_make_color_table_v (&put_color_table,
9ecf6403 4044 &get_color_table);
ea1aaa6f
ST
4045 else
4046 color_table = xpm_make_color_table_h (&put_color_table,
9ecf6403 4047 &get_color_table);
ea1aaa6f
ST
4048
4049 while (num_colors-- > 0)
4050 {
25a48bd0 4051 char *color, *max_color;
ea1aaa6f
ST
4052 int key, next_key, max_key = 0;
4053 Lisp_Object symbol_color = Qnil, color_val;
4054 XColor cdef;
4055
4056 expect (XPM_TK_STRING);
4057 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
9ecf6403 4058 goto failure;
ea1aaa6f
ST
4059 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4060 buffer[len - chars_per_pixel] = '\0';
4061
4062 str = strtok (buffer, " \t");
4063 if (str == NULL)
9ecf6403 4064 goto failure;
ea1aaa6f
ST
4065 key = xpm_str_to_color_key (str);
4066 if (key < 0)
9ecf6403 4067 goto failure;
ea1aaa6f 4068 do
9ecf6403
YM
4069 {
4070 color = strtok (NULL, " \t");
4071 if (color == NULL)
4072 goto failure;
ea1aaa6f 4073
9db94f82 4074 while ((str = strtok (NULL, " \t")) != NULL)
9ecf6403
YM
4075 {
4076 next_key = xpm_str_to_color_key (str);
4077 if (next_key >= 0)
4078 break;
4079 color[strlen (color)] = ' ';
4080 }
ea1aaa6f 4081
9ecf6403
YM
4082 if (key == XPM_COLOR_KEY_S)
4083 {
4084 if (NILP (symbol_color))
4085 symbol_color = build_string (color);
4086 }
4087 else if (max_key < key && key <= best_key)
4088 {
4089 max_key = key;
4090 max_color = color;
4091 }
4092 key = next_key;
4093 }
ea1aaa6f
ST
4094 while (str);
4095
4096 color_val = Qnil;
4097 if (!NILP (color_symbols) && !NILP (symbol_color))
9ecf6403
YM
4098 {
4099 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4100
4101 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
9db94f82 4102 {
25a48bd0 4103 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
9db94f82 4104 color_val = Qt;
6045c4fd 4105 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
9db94f82
YM
4106 &cdef, 0))
4107 color_val = make_number (cdef.pixel);
4108 }
9ecf6403 4109 }
ea1aaa6f 4110 if (NILP (color_val) && max_key > 0)
9db94f82 4111 {
05131107 4112 if (xstrcasecmp (max_color, "None") == 0)
9db94f82
YM
4113 color_val = Qt;
4114 else if (x_defined_color (f, max_color, &cdef, 0))
4115 color_val = make_number (cdef.pixel);
4116 }
ea1aaa6f 4117 if (!NILP (color_val))
9ecf6403 4118 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
ea1aaa6f
ST
4119
4120 expect (',');
4121 }
4122
ea1aaa6f
ST
4123 for (y = 0; y < height; y++)
4124 {
4125 expect (XPM_TK_STRING);
4126 str = beg;
4127 if (len < width * chars_per_pixel)
9ecf6403 4128 goto failure;
ea1aaa6f 4129 for (x = 0; x < width; x++, str += chars_per_pixel)
9ecf6403
YM
4130 {
4131 Lisp_Object color_val =
4132 (*get_color_table) (color_table, str, chars_per_pixel);
4133
4134 XPutPixel (ximg, x, y,
4135 (INTEGERP (color_val) ? XINT (color_val)
4136 : FRAME_FOREGROUND_PIXEL (f)));
edfda783 4137#ifndef HAVE_NS
9ecf6403
YM
4138 XPutPixel (mask_img, x, y,
4139 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4140 : (have_mask = 1, PIX_MASK_RETAIN)));
edfda783 4141#else
ed3751c8
JB
4142 if (EQ (color_val, Qt))
4143 ns_set_alpha (ximg, x, y, 0);
edfda783 4144#endif
9ecf6403 4145 }
ea1aaa6f 4146 if (y + 1 < height)
9ecf6403 4147 expect (',');
ea1aaa6f
ST
4148 }
4149
4150 img->width = width;
4151 img->height = height;
4152
0b8ac842
YM
4153 /* Maybe fill in the background field while we have ximg handy. */
4154 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4155 IMAGE_BACKGROUND (img, f, ximg);
4156
547c9269 4157 image_put_x_image (f, img, ximg, 0);
edfda783 4158#ifndef HAVE_NS
ea1aaa6f
ST
4159 if (have_mask)
4160 {
9ecf6403
YM
4161 /* Fill in the background_transparent field while we have the
4162 mask handy. */
4163 image_background_transparent (img, f, mask_img);
4164
547c9269 4165 image_put_x_image (f, img, mask_img, 1);
ea1aaa6f
ST
4166 }
4167 else
4168 {
4169 x_destroy_x_image (mask_img);
547c9269 4170 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
ea1aaa6f 4171 }
edfda783 4172#endif
ea1aaa6f
ST
4173 return 1;
4174
4175 failure:
4176 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
ea1aaa6f
ST
4177 x_destroy_x_image (ximg);
4178 x_destroy_x_image (mask_img);
4179 x_clear_image (f, img);
4180 return 0;
4181
4182#undef match
4183#undef expect
4184#undef expect_ident
4185}
4186
578098f3 4187static bool
3d608a86
J
4188xpm_load (struct frame *f,
4189 struct image *img)
ea1aaa6f 4190{
578098f3 4191 bool success_p = 0;
ea1aaa6f
ST
4192 Lisp_Object file_name;
4193
4194 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4195 file_name = image_spec_value (img->spec, QCfile, NULL);
4196 if (STRINGP (file_name))
4197 {
4198 Lisp_Object file;
4199 unsigned char *contents;
dd52fcea 4200 ptrdiff_t size;
ea1aaa6f
ST
4201
4202 file = x_find_image_file (file_name);
ea1aaa6f 4203 if (!STRINGP (file))
9ecf6403
YM
4204 {
4205 image_error ("Cannot find image file `%s'", file_name, Qnil);
9ecf6403
YM
4206 return 0;
4207 }
ea1aaa6f 4208
6045c4fd 4209 contents = slurp_file (SSDATA (file), &size);
ea1aaa6f 4210 if (contents == NULL)
9ecf6403
YM
4211 {
4212 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
9ecf6403
YM
4213 return 0;
4214 }
ea1aaa6f
ST
4215
4216 success_p = xpm_load_image (f, img, contents, contents + size);
4217 xfree (contents);
ea1aaa6f
ST
4218 }
4219 else
4220 {
4221 Lisp_Object data;
4222
4223 data = image_spec_value (img->spec, QCdata, NULL);
7574650a
AS
4224 if (!STRINGP (data))
4225 {
4226 image_error ("Invalid image data `%s'", data, Qnil);
4227 return 0;
4228 }
ea1aaa6f 4229 success_p = xpm_load_image (f, img, SDATA (data),
9ecf6403 4230 SDATA (data) + SBYTES (data));
ea1aaa6f
ST
4231 }
4232
4233 return success_p;
4234}
4235
9e2a2647 4236#endif /* HAVE_NS && !HAVE_XPM */
b0da69a7 4237
ea1aaa6f 4238
4ef0d4d0
KS
4239\f
4240/***********************************************************************
4241 Color table
4242 ***********************************************************************/
4243
4244#ifdef COLOR_TABLE_SUPPORT
4245
4246/* An entry in the color table mapping an RGB color to a pixel color. */
4247
4248struct ct_color
4249{
4250 int r, g, b;
4251 unsigned long pixel;
4252
4253 /* Next in color table collision list. */
4254 struct ct_color *next;
4255};
4256
4257/* The bucket vector size to use. Must be prime. */
4258
4259#define CT_SIZE 101
4260
4261/* Value is a hash of the RGB color given by R, G, and B. */
4262
4263#define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4264
4265/* The color hash table. */
4266
cd44d2eb 4267static struct ct_color **ct_table;
4ef0d4d0
KS
4268
4269/* Number of entries in the color table. */
4270
cd44d2eb 4271static int ct_colors_allocated;
ddff3151
PE
4272enum
4273{
4274 ct_colors_allocated_max =
4275 min (INT_MAX,
4276 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4277};
4ef0d4d0
KS
4278
4279/* Initialize the color table. */
4280
4281static void
d3da34e0 4282init_color_table (void)
4ef0d4d0
KS
4283{
4284 int size = CT_SIZE * sizeof (*ct_table);
23f86fce 4285 ct_table = xzalloc (size);
4ef0d4d0
KS
4286 ct_colors_allocated = 0;
4287}
4288
4289
4290/* Free memory associated with the color table. */
4291
4292static void
d3da34e0 4293free_color_table (void)
4ef0d4d0
KS
4294{
4295 int i;
4296 struct ct_color *p, *next;
4297
4298 for (i = 0; i < CT_SIZE; ++i)
4299 for (p = ct_table[i]; p; p = next)
4300 {
4301 next = p->next;
4302 xfree (p);
4303 }
4304
4305 xfree (ct_table);
4306 ct_table = NULL;
4307}
4308
4309
4310/* Value is a pixel color for RGB color R, G, B on frame F. If an
4311 entry for that color already is in the color table, return the
4312 pixel color of that entry. Otherwise, allocate a new color for R,
4313 G, B, and make an entry in the color table. */
4314
4315static unsigned long
d3da34e0 4316lookup_rgb_color (struct frame *f, int r, int g, int b)
4ef0d4d0
KS
4317{
4318 unsigned hash = CT_HASH_RGB (r, g, b);
4319 int i = hash % CT_SIZE;
4320 struct ct_color *p;
4321 Display_Info *dpyinfo;
4322
4323 /* Handle TrueColor visuals specially, which improves performance by
4324 two orders of magnitude. Freeing colors on TrueColor visuals is
4325 a nop, and pixel colors specify RGB values directly. See also
4326 the Xlib spec, chapter 3.1. */
4327 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4328 if (dpyinfo->red_bits > 0)
4329 {
4330 unsigned long pr, pg, pb;
4331
4332 /* Apply gamma-correction like normal color allocation does. */
4333 if (f->gamma)
4334 {
4335 XColor color;
4336 color.red = r, color.green = g, color.blue = b;
4337 gamma_correct (f, &color);
4338 r = color.red, g = color.green, b = color.blue;
4339 }
4340
4341 /* Scale down RGB values to the visual's bits per RGB, and shift
4342 them to the right position in the pixel color. Note that the
4343 original RGB values are 16-bit values, as usual in X. */
4344 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4345 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4346 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4347
4348 /* Assemble the pixel color. */
4349 return pr | pg | pb;
4350 }
1f026899 4351
4ef0d4d0
KS
4352 for (p = ct_table[i]; p; p = p->next)
4353 if (p->r == r && p->g == g && p->b == b)
4354 break;
4355
4356 if (p == NULL)
4357 {
4358
4359#ifdef HAVE_X_WINDOWS
4360 XColor color;
4361 Colormap cmap;
578098f3 4362 bool rc;
ddff3151
PE
4363#else
4364 COLORREF color;
4365#endif
4ef0d4d0 4366
ddff3151
PE
4367 if (ct_colors_allocated_max <= ct_colors_allocated)
4368 return FRAME_FOREGROUND_PIXEL (f);
4369
4370#ifdef HAVE_X_WINDOWS
4ef0d4d0
KS
4371 color.red = r;
4372 color.green = g;
4373 color.blue = b;
4374
4375 cmap = FRAME_X_COLORMAP (f);
4376 rc = x_alloc_nearest_color (f, cmap, &color);
4377 if (rc)
4378 {
4379 ++ct_colors_allocated;
23f86fce 4380 p = xmalloc (sizeof *p);
4ef0d4d0
KS
4381 p->r = r;
4382 p->g = g;
4383 p->b = b;
4384 p->pixel = color.pixel;
4385 p->next = ct_table[i];
4386 ct_table[i] = p;
4387 }
4388 else
4389 return FRAME_FOREGROUND_PIXEL (f);
4390
4391#else
4ef0d4d0
KS
4392#ifdef HAVE_NTGUI
4393 color = PALETTERGB (r, g, b);
4394#else
4395 color = RGB_TO_ULONG (r, g, b);
4396#endif /* HAVE_NTGUI */
4397 ++ct_colors_allocated;
23f86fce 4398 p = xmalloc (sizeof *p);
4ef0d4d0
KS
4399 p->r = r;
4400 p->g = g;
4401 p->b = b;
4402 p->pixel = color;
4403 p->next = ct_table[i];
4404 ct_table[i] = p;
4405#endif /* HAVE_X_WINDOWS */
4406
4407 }
4408
4409 return p->pixel;
4410}
4411
4412
4413/* Look up pixel color PIXEL which is used on frame F in the color
4414 table. If not already present, allocate it. Value is PIXEL. */
4415
4416static unsigned long
d3da34e0 4417lookup_pixel_color (struct frame *f, unsigned long pixel)
4ef0d4d0
KS
4418{
4419 int i = pixel % CT_SIZE;
4420 struct ct_color *p;
4421
4422 for (p = ct_table[i]; p; p = p->next)
4423 if (p->pixel == pixel)
4424 break;
4425
4426 if (p == NULL)
4427 {
4428 XColor color;
4429 Colormap cmap;
578098f3 4430 bool rc;
4ef0d4d0 4431
ddff3151
PE
4432 if (ct_colors_allocated_max <= ct_colors_allocated)
4433 return FRAME_FOREGROUND_PIXEL (f);
4434
4ef0d4d0
KS
4435#ifdef HAVE_X_WINDOWS
4436 cmap = FRAME_X_COLORMAP (f);
4437 color.pixel = pixel;
4438 x_query_color (f, &color);
4439 rc = x_alloc_nearest_color (f, cmap, &color);
4440#else
4d7e6e51 4441 block_input ();
4ef0d4d0
KS
4442 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4443 color.pixel = pixel;
4444 XQueryColor (NULL, cmap, &color);
4445 rc = x_alloc_nearest_color (f, cmap, &color);
4d7e6e51 4446 unblock_input ();
4ef0d4d0
KS
4447#endif /* HAVE_X_WINDOWS */
4448
4449 if (rc)
4450 {
4451 ++ct_colors_allocated;
4452
23f86fce 4453 p = xmalloc (sizeof *p);
4ef0d4d0
KS
4454 p->r = color.red;
4455 p->g = color.green;
4456 p->b = color.blue;
4457 p->pixel = pixel;
4458 p->next = ct_table[i];
4459 ct_table[i] = p;
4460 }
4461 else
4462 return FRAME_FOREGROUND_PIXEL (f);
4463 }
4464 return p->pixel;
4465}
4466
4467
4468/* Value is a vector of all pixel colors contained in the color table,
4469 allocated via xmalloc. Set *N to the number of colors. */
4470
4471static unsigned long *
d3da34e0 4472colors_in_color_table (int *n)
4ef0d4d0
KS
4473{
4474 int i, j;
4475 struct ct_color *p;
4476 unsigned long *colors;
4477
4478 if (ct_colors_allocated == 0)
4479 {
4480 *n = 0;
4481 colors = NULL;
4482 }
4483 else
4484 {
23f86fce 4485 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4ef0d4d0
KS
4486 *n = ct_colors_allocated;
4487
4488 for (i = j = 0; i < CT_SIZE; ++i)
4489 for (p = ct_table[i]; p; p = p->next)
4490 colors[j++] = p->pixel;
4491 }
4492
4493 return colors;
4494}
4495
4496#else /* COLOR_TABLE_SUPPORT */
4497
4498static unsigned long
7c3320d8 4499lookup_rgb_color (struct frame *f, int r, int g, int b)
4ef0d4d0
KS
4500{
4501 unsigned long pixel;
4502
4ef0d4d0
KS
4503#ifdef HAVE_NTGUI
4504 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4505#endif /* HAVE_NTGUI */
4506
edfda783
AR
4507#ifdef HAVE_NS
4508 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4509#endif /* HAVE_NS */
4ef0d4d0
KS
4510 return pixel;
4511}
4512
4513static void
7c3320d8 4514init_color_table (void)
4ef0d4d0
KS
4515{
4516}
4517#endif /* COLOR_TABLE_SUPPORT */
4518
4519\f
4520/***********************************************************************
4521 Algorithms
4522 ***********************************************************************/
4523
4ef0d4d0
KS
4524/* Edge detection matrices for different edge-detection
4525 strategies. */
4526
4527static int emboss_matrix[9] = {
4528 /* x - 1 x x + 1 */
4529 2, -1, 0, /* y - 1 */
4530 -1, 0, 1, /* y */
4531 0, 1, -2 /* y + 1 */
4532};
4533
4534static int laplace_matrix[9] = {
4535 /* x - 1 x x + 1 */
4536 1, 0, 0, /* y - 1 */
4537 0, 0, 0, /* y */
4538 0, 0, -1 /* y + 1 */
4539};
4540
4541/* Value is the intensity of the color whose red/green/blue values
4542 are R, G, and B. */
4543
4544#define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4545
4546
4547/* On frame F, return an array of XColor structures describing image
4548 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
578098f3 4549 means also fill the red/green/blue members of the XColor
4ef0d4d0
KS
4550 structures. Value is a pointer to the array of XColors structures,
4551 allocated with xmalloc; it must be freed by the caller. */
4552
4553static XColor *
578098f3 4554x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4ef0d4d0
KS
4555{
4556 int x, y;
4557 XColor *colors, *p;
4558 XImagePtr_or_DC ximg;
4559#ifdef HAVE_NTGUI
4ef0d4d0
KS
4560 HGDIOBJ prev;
4561#endif /* HAVE_NTGUI */
4562
ddff3151
PE
4563 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width < img->height)
4564 memory_full (SIZE_MAX);
23f86fce 4565 colors = xmalloc (sizeof *colors * img->width * img->height);
4ef0d4d0 4566
547c9269
YM
4567 /* Get the X image or create a memory device context for IMG. */
4568 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4ef0d4d0
KS
4569
4570 /* Fill the `pixel' members of the XColor array. I wished there
4571 were an easy and portable way to circumvent XGetPixel. */
4572 p = colors;
4573 for (y = 0; y < img->height; ++y)
4574 {
8b7d0a16 4575#if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
6045c4fd 4576 XColor *row = p;
4ef0d4d0 4577 for (x = 0; x < img->width; ++x, ++p)
8b7d0a16 4578 p->pixel = GET_PIXEL (ximg, x, y);
4ef0d4d0
KS
4579 if (rgb_p)
4580 x_query_colors (f, row, img->width);
4581
4582#else
4583
4584 for (x = 0; x < img->width; ++x, ++p)
4585 {
4586 /* W32_TODO: palette support needed here? */
4587 p->pixel = GET_PIXEL (ximg, x, y);
4588 if (rgb_p)
4589 {
4ef0d4d0
KS
4590 p->red = RED16_FROM_ULONG (p->pixel);
4591 p->green = GREEN16_FROM_ULONG (p->pixel);
4592 p->blue = BLUE16_FROM_ULONG (p->pixel);
4ef0d4d0
KS
4593 }
4594 }
4595#endif /* HAVE_X_WINDOWS */
4596 }
4597
547c9269 4598 image_unget_x_image_or_dc (img, 0, ximg, prev);
4ef0d4d0
KS
4599
4600 return colors;
4601}
4602
4603#ifdef HAVE_NTGUI
4604
4605/* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4606 created with CreateDIBSection, with the pointer to the bit values
4607 stored in ximg->data. */
4608
3046a84b 4609static void
7c3320d8 4610XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4ef0d4d0
KS
4611{
4612 int width = ximg->info.bmiHeader.biWidth;
4ef0d4d0
KS
4613 unsigned char * pixel;
4614
4615 /* True color images. */
4616 if (ximg->info.bmiHeader.biBitCount == 24)
4617 {
4618 int rowbytes = width * 3;
4619 /* Ensure scanlines are aligned on 4 byte boundaries. */
4620 if (rowbytes % 4)
4621 rowbytes += 4 - (rowbytes % 4);
4622
4623 pixel = ximg->data + y * rowbytes + x * 3;
4624 /* Windows bitmaps are in BGR order. */
4625 *pixel = GetBValue (color);
4626 *(pixel + 1) = GetGValue (color);
4627 *(pixel + 2) = GetRValue (color);
4628 }
4629 /* Monochrome images. */
4630 else if (ximg->info.bmiHeader.biBitCount == 1)
4631 {
4632 int rowbytes = width / 8;
4633 /* Ensure scanlines are aligned on 4 byte boundaries. */
4634 if (rowbytes % 4)
4635 rowbytes += 4 - (rowbytes % 4);
4636 pixel = ximg->data + y * rowbytes + x / 8;
4637 /* Filter out palette info. */
4638 if (color & 0x00ffffff)
4639 *pixel = *pixel | (1 << x % 8);
4640 else
4641 *pixel = *pixel & ~(1 << x % 8);
4642 }
4643 else
4644 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4645}
4646
4647#endif /* HAVE_NTGUI */
4648
4649/* Create IMG->pixmap from an array COLORS of XColor structures, whose
4650 RGB members are set. F is the frame on which this all happens.
4651 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4652
4653static void
d3da34e0 4654x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4ef0d4d0
KS
4655{
4656 int x, y;
edfda783 4657 XImagePtr oimg = NULL;
4ef0d4d0
KS
4658 XColor *p;
4659
4660 init_color_table ();
4661
547c9269
YM
4662 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4663 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4664 &oimg, 0);
4ef0d4d0
KS
4665 p = colors;
4666 for (y = 0; y < img->height; ++y)
4667 for (x = 0; x < img->width; ++x, ++p)
4668 {
4669 unsigned long pixel;
4670 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4671 XPutPixel (oimg, x, y, pixel);
4672 }
4673
4674 xfree (colors);
4ef0d4d0 4675
547c9269 4676 image_put_x_image (f, img, oimg, 0);
4ef0d4d0
KS
4677#ifdef COLOR_TABLE_SUPPORT
4678 img->colors = colors_in_color_table (&img->ncolors);
4679 free_color_table ();
4680#endif /* COLOR_TABLE_SUPPORT */
4681}
4682
4683
4684/* On frame F, perform edge-detection on image IMG.
4685
4686 MATRIX is a nine-element array specifying the transformation
4687 matrix. See emboss_matrix for an example.
4688
4689 COLOR_ADJUST is a color adjustment added to each pixel of the
4690 outgoing image. */
4691
4692static void
d3da34e0 4693x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4ef0d4d0
KS
4694{
4695 XColor *colors = x_to_xcolors (f, img, 1);
4696 XColor *new, *p;
4697 int x, y, i, sum;
4698
4699 for (i = sum = 0; i < 9; ++i)
1ea40aa2 4700 sum += eabs (matrix[i]);
4ef0d4d0
KS
4701
4702#define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4703
ddff3151
PE
4704 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width < img->height)
4705 memory_full (SIZE_MAX);
23f86fce 4706 new = xmalloc (sizeof *new * img->width * img->height);
4ef0d4d0
KS
4707
4708 for (y = 0; y < img->height; ++y)
4709 {
4710 p = COLOR (new, 0, y);
4711 p->red = p->green = p->blue = 0xffff/2;
4712 p = COLOR (new, img->width - 1, y);
4713 p->red = p->green = p->blue = 0xffff/2;
4714 }
4715
4716 for (x = 1; x < img->width - 1; ++x)
4717 {
4718 p = COLOR (new, x, 0);
4719 p->red = p->green = p->blue = 0xffff/2;
4720 p = COLOR (new, x, img->height - 1);
4721 p->red = p->green = p->blue = 0xffff/2;
4722 }
4723
4724 for (y = 1; y < img->height - 1; ++y)
4725 {
4726 p = COLOR (new, 1, y);
4727
4728 for (x = 1; x < img->width - 1; ++x, ++p)
4729 {
6ae141d6 4730 int r, g, b, yy, xx;
4ef0d4d0
KS
4731
4732 r = g = b = i = 0;
6ae141d6
PE
4733 for (yy = y - 1; yy < y + 2; ++yy)
4734 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4ef0d4d0
KS
4735 if (matrix[i])
4736 {
6ae141d6 4737 XColor *t = COLOR (colors, xx, yy);
4ef0d4d0
KS
4738 r += matrix[i] * t->red;
4739 g += matrix[i] * t->green;
4740 b += matrix[i] * t->blue;
4741 }
4742
4743 r = (r / sum + color_adjust) & 0xffff;
4744 g = (g / sum + color_adjust) & 0xffff;
4745 b = (b / sum + color_adjust) & 0xffff;
4746 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4747 }
4748 }
4749
4750 xfree (colors);
4751 x_from_xcolors (f, img, new);
4752
4753#undef COLOR
4754}
4755
4756
4757/* Perform the pre-defined `emboss' edge-detection on image IMG
4758 on frame F. */
4759
4760static void
d3da34e0 4761x_emboss (struct frame *f, struct image *img)
4ef0d4d0
KS
4762{
4763 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4764}
4765
4766
4767/* Transform image IMG which is used on frame F with a Laplace
4768 edge-detection algorithm. The result is an image that can be used
4769 to draw disabled buttons, for example. */
4770
4771static void
d3da34e0 4772x_laplace (struct frame *f, struct image *img)
4ef0d4d0
KS
4773{
4774 x_detect_edges (f, img, laplace_matrix, 45000);
4775}
4776
4777
4778/* Perform edge-detection on image IMG on frame F, with specified
4779 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4780
4781 MATRIX must be either
4782
4783 - a list of at least 9 numbers in row-major form
4784 - a vector of at least 9 numbers
4785
4786 COLOR_ADJUST nil means use a default; otherwise it must be a
4787 number. */
4788
4789static void
d3da34e0
JB
4790x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4791 Lisp_Object color_adjust)
4ef0d4d0
KS
4792{
4793 int i = 0;
4794 int trans[9];
4795
4796 if (CONSP (matrix))
4797 {
4798 for (i = 0;
4799 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4800 ++i, matrix = XCDR (matrix))
4801 trans[i] = XFLOATINT (XCAR (matrix));
4802 }
4803 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4804 {
4805 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4806 trans[i] = XFLOATINT (AREF (matrix, i));
4807 }
4808
4809 if (NILP (color_adjust))
4810 color_adjust = make_number (0xffff / 2);
4811
4812 if (i == 9 && NUMBERP (color_adjust))
77a765fd 4813 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4ef0d4d0
KS
4814}
4815
4816
4817/* Transform image IMG on frame F so that it looks disabled. */
4818
4819static void
d3da34e0 4820x_disable_image (struct frame *f, struct image *img)
4ef0d4d0
KS
4821{
4822 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4823#ifdef HAVE_NTGUI
4824 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4825#else
4826 int n_planes = dpyinfo->n_planes;
4827#endif /* HAVE_NTGUI */
4828
4829 if (n_planes >= 2)
4830 {
4831 /* Color (or grayscale). Convert to gray, and equalize. Just
4832 drawing such images with a stipple can look very odd, so
4833 we're using this method instead. */
4834 XColor *colors = x_to_xcolors (f, img, 1);
4835 XColor *p, *end;
4836 const int h = 15000;
4837 const int l = 30000;
4838
4839 for (p = colors, end = colors + img->width * img->height;
4840 p < end;
4841 ++p)
4842 {
4843 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4844 int i2 = (0xffff - h - l) * i / 0xffff + l;
4845 p->red = p->green = p->blue = i2;
4846 }
4847
4848 x_from_xcolors (f, img, colors);
4849 }
4850
4851 /* Draw a cross over the disabled image, if we must or if we
4852 should. */
4853 if (n_planes < 2 || cross_disabled_images)
4854 {
4855#ifndef HAVE_NTGUI
5afa3a81 4856#ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
edfda783 4857
4ef0d4d0 4858#define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4ef0d4d0 4859
6045c4fd 4860 Display *dpy = FRAME_X_DISPLAY (f);
547c9269
YM
4861 GC gc;
4862
4863 image_sync_to_pixmaps (f, img);
4864 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4ef0d4d0
KS
4865 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4866 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4867 img->width - 1, img->height - 1);
4868 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4869 img->width - 1, 0);
4870 XFreeGC (dpy, gc);
4871
4872 if (img->mask)
4873 {
ae8279db 4874 gc = XCreateGC (dpy, img->mask, 0, NULL);
4ef0d4d0
KS
4875 XSetForeground (dpy, gc, MaskForeground (f));
4876 XDrawLine (dpy, img->mask, gc, 0, 0,
4877 img->width - 1, img->height - 1);
4878 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4879 img->width - 1, 0);
4880 XFreeGC (dpy, gc);
4881 }
edfda783 4882#endif /* !HAVE_NS */
4ef0d4d0
KS
4883#else
4884 HDC hdc, bmpdc;
4885 HGDIOBJ prev;
4886
4887 hdc = get_frame_dc (f);
4888 bmpdc = CreateCompatibleDC (hdc);
4889 release_frame_dc (f, hdc);
4890
4891 prev = SelectObject (bmpdc, img->pixmap);
4892
4893 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4894 MoveToEx (bmpdc, 0, 0, NULL);
4895 LineTo (bmpdc, img->width - 1, img->height - 1);
4896 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4897 LineTo (bmpdc, img->width - 1, 0);
4898
4899 if (img->mask)
4900 {
4901 SelectObject (bmpdc, img->mask);
4902 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4903 MoveToEx (bmpdc, 0, 0, NULL);
4904 LineTo (bmpdc, img->width - 1, img->height - 1);
4905 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4906 LineTo (bmpdc, img->width - 1, 0);
4907 }
4908 SelectObject (bmpdc, prev);
4909 DeleteDC (bmpdc);
4910#endif /* HAVE_NTGUI */
4911 }
4912}
4913
4914
4915/* Build a mask for image IMG which is used on frame F. FILE is the
4916 name of an image file, for error messages. HOW determines how to
4917 determine the background color of IMG. If it is a list '(R G B)',
4918 with R, G, and B being integers >= 0, take that as the color of the
4919 background. Otherwise, determine the background color of IMG
578098f3 4920 heuristically. */
4ef0d4d0 4921
578098f3 4922static void
d3da34e0 4923x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4ef0d4d0
KS
4924{
4925 XImagePtr_or_DC ximg;
4926#ifndef HAVE_NTGUI
4927 XImagePtr mask_img;
4928#else
4ef0d4d0
KS
4929 HGDIOBJ prev;
4930 char *mask_img;
4931 int row_width;
4932#endif /* HAVE_NTGUI */
578098f3
PE
4933 int x, y;
4934 bool rc, use_img_background;
4ef0d4d0
KS
4935 unsigned long bg = 0;
4936
4937 if (img->mask)
547c9269 4938 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4ef0d4d0
KS
4939
4940#ifndef HAVE_NTGUI
edfda783 4941#ifndef HAVE_NS
4ef0d4d0 4942 /* Create an image and pixmap serving as mask. */
547c9269
YM
4943 rc = image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
4944 &mask_img, 1);
4ef0d4d0 4945 if (!rc)
578098f3 4946 return;
edfda783 4947#endif /* !HAVE_NS */
4ef0d4d0
KS
4948#else
4949 /* Create the bit array serving as mask. */
4950 row_width = (img->width + 7) / 8;
23f86fce 4951 mask_img = xzalloc (row_width * img->height);
4ef0d4d0
KS
4952#endif /* HAVE_NTGUI */
4953
547c9269
YM
4954 /* Get the X image or create a memory device context for IMG. */
4955 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4956
4ef0d4d0
KS
4957 /* Determine the background color of ximg. If HOW is `(R G B)'
4958 take that as color. Otherwise, use the image's background color. */
4959 use_img_background = 1;
4960
4961 if (CONSP (how))
4962 {
4963 int rgb[3], i;
4964
4965 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4966 {
4967 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4968 how = XCDR (how);
4969 }
4970
4971 if (i == 3 && NILP (how))
4972 {
4973 char color_name[30];
4974 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4975 bg = (
4976#ifdef HAVE_NTGUI
4977 0x00ffffff & /* Filter out palette info. */
4978#endif /* HAVE_NTGUI */
4979 x_alloc_image_color (f, img, build_string (color_name), 0));
4980 use_img_background = 0;
4981 }
4982 }
4983
4984 if (use_img_background)
6ac3c7bb 4985 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4ef0d4d0
KS
4986
4987 /* Set all bits in mask_img to 1 whose color in ximg is different
4988 from the background color bg. */
4989#ifndef HAVE_NTGUI
4990 for (y = 0; y < img->height; ++y)
4991 for (x = 0; x < img->width; ++x)
edfda783 4992#ifndef HAVE_NS
4ef0d4d0 4993 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
9ecf6403 4994 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
edfda783
AR
4995#else
4996 if (XGetPixel (ximg, x, y) == bg)
ed3751c8 4997 ns_set_alpha (ximg, x, y, 0);
edfda783
AR
4998#endif /* HAVE_NS */
4999#ifndef HAVE_NS
4ef0d4d0
KS
5000 /* Fill in the background_transparent field while we have the mask handy. */
5001 image_background_transparent (img, f, mask_img);
5002
547c9269
YM
5003 /* Put mask_img into the image. */
5004 image_put_x_image (f, img, mask_img, 1);
edfda783 5005#endif /* !HAVE_NS */
4ef0d4d0
KS
5006#else
5007 for (y = 0; y < img->height; ++y)
5008 for (x = 0; x < img->width; ++x)
5009 {
5010 COLORREF p = GetPixel (ximg, x, y);
5011 if (p != bg)
5012 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5013 }
5014
5015 /* Create the mask image. */
5016 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5017 mask_img);
5018 /* Fill in the background_transparent field while we have the mask handy. */
5019 SelectObject (ximg, img->mask);
5020 image_background_transparent (img, f, ximg);
5021
5022 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5023 xfree (mask_img);
5024#endif /* HAVE_NTGUI */
5025
547c9269 5026 image_unget_x_image_or_dc (img, 0, ximg, prev);
4ef0d4d0
KS
5027}
5028
5029\f
5030/***********************************************************************
5031 PBM (mono, gray, color)
5032 ***********************************************************************/
5033
578098f3
PE
5034static bool pbm_image_p (Lisp_Object object);
5035static bool pbm_load (struct frame *f, struct image *img);
4ef0d4d0
KS
5036
5037/* The symbol `pbm' identifying images of this type. */
5038
955cbe7b 5039static Lisp_Object Qpbm;
4ef0d4d0
KS
5040
5041/* Indices of image specification fields in gs_format, below. */
5042
5043enum pbm_keyword_index
5044{
5045 PBM_TYPE,
5046 PBM_FILE,
5047 PBM_DATA,
5048 PBM_ASCENT,
5049 PBM_MARGIN,
5050 PBM_RELIEF,
5051 PBM_ALGORITHM,
5052 PBM_HEURISTIC_MASK,
5053 PBM_MASK,
5054 PBM_FOREGROUND,
5055 PBM_BACKGROUND,
5056 PBM_LAST
5057};
5058
5059/* Vector of image_keyword structures describing the format
5060 of valid user-defined image specifications. */
5061
91433552 5062static const struct image_keyword pbm_format[PBM_LAST] =
4ef0d4d0
KS
5063{
5064 {":type", IMAGE_SYMBOL_VALUE, 1},
5065 {":file", IMAGE_STRING_VALUE, 0},
5066 {":data", IMAGE_STRING_VALUE, 0},
5067 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 5068 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
5069 {":relief", IMAGE_INTEGER_VALUE, 0},
5070 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5071 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5072 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5073 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5074 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5075};
5076
5077/* Structure describing the image type `pbm'. */
5078
5079static struct image_type pbm_type =
5080{
5081 &Qpbm,
5082 pbm_image_p,
5083 pbm_load,
5084 x_clear_image,
bb4d86b4 5085 NULL,
4ef0d4d0
KS
5086 NULL
5087};
5088
5089
578098f3 5090/* Return true if OBJECT is a valid PBM image specification. */
4ef0d4d0 5091
578098f3 5092static bool
d3da34e0 5093pbm_image_p (Lisp_Object object)
4ef0d4d0
KS
5094{
5095 struct image_keyword fmt[PBM_LAST];
5096
72af86bd 5097 memcpy (fmt, pbm_format, sizeof fmt);
4ef0d4d0
KS
5098
5099 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5100 return 0;
5101
5102 /* Must specify either :data or :file. */
5103 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5104}
5105
5106
5107/* Scan a decimal number from *S and return it. Advance *S while
5108 reading the number. END is the end of the string. Value is -1 at
5109 end of input. */
5110
5111static int
d3da34e0 5112pbm_scan_number (unsigned char **s, unsigned char *end)
4ef0d4d0
KS
5113{
5114 int c = 0, val = -1;
5115
5116 while (*s < end)
5117 {
5118 /* Skip white-space. */
620f13b0 5119 while (*s < end && (c = *(*s)++, c_isspace (c)))
4ef0d4d0
KS
5120 ;
5121
5122 if (c == '#')
5123 {
5124 /* Skip comment to end of line. */
5125 while (*s < end && (c = *(*s)++, c != '\n'))
5126 ;
5127 }
620f13b0 5128 else if (c_isdigit (c))
4ef0d4d0
KS
5129 {
5130 /* Read decimal number. */
5131 val = c - '0';
620f13b0 5132 while (*s < end && (c = *(*s)++, c_isdigit (c)))
4ef0d4d0
KS
5133 val = 10 * val + c - '0';
5134 break;
5135 }
5136 else
5137 break;
5138 }
5139
5140 return val;
5141}
5142
5143
4ef0d4d0
KS
5144/* Load PBM image IMG for use on frame F. */
5145
578098f3 5146static bool
d3da34e0 5147pbm_load (struct frame *f, struct image *img)
4ef0d4d0 5148{
578098f3
PE
5149 bool raw_p;
5150 int x, y;
4ef0d4d0
KS
5151 int width, height, max_color_idx = 0;
5152 XImagePtr ximg;
5153 Lisp_Object file, specified_file;
5154 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
4ef0d4d0
KS
5155 unsigned char *contents = NULL;
5156 unsigned char *end, *p;
dd52fcea 5157 ptrdiff_t size;
4ef0d4d0
KS
5158
5159 specified_file = image_spec_value (img->spec, QCfile, NULL);
4ef0d4d0
KS
5160
5161 if (STRINGP (specified_file))
5162 {
5163 file = x_find_image_file (specified_file);
5164 if (!STRINGP (file))
5165 {
5166 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
5167 return 0;
5168 }
5169
42a5b22f 5170 contents = slurp_file (SSDATA (file), &size);
4ef0d4d0
KS
5171 if (contents == NULL)
5172 {
5173 image_error ("Error reading `%s'", file, Qnil);
4ef0d4d0
KS
5174 return 0;
5175 }
5176
5177 p = contents;
5178 end = contents + size;
5179 }
5180 else
5181 {
5182 Lisp_Object data;
5183 data = image_spec_value (img->spec, QCdata, NULL);
7574650a
AS
5184 if (!STRINGP (data))
5185 {
5186 image_error ("Invalid image data `%s'", data, Qnil);
5187 return 0;
5188 }
4ef0d4d0
KS
5189 p = SDATA (data);
5190 end = p + SBYTES (data);
5191 }
5192
5193 /* Check magic number. */
5194 if (end - p < 2 || *p++ != 'P')
5195 {
5196 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5197 error:
5198 xfree (contents);
4ef0d4d0
KS
5199 return 0;
5200 }
5201
5202 switch (*p++)
5203 {
5204 case '1':
5205 raw_p = 0, type = PBM_MONO;
5206 break;
5207
5208 case '2':
5209 raw_p = 0, type = PBM_GRAY;
5210 break;
5211
5212 case '3':
5213 raw_p = 0, type = PBM_COLOR;
5214 break;
5215
5216 case '4':
5217 raw_p = 1, type = PBM_MONO;
5218 break;
5219
5220 case '5':
5221 raw_p = 1, type = PBM_GRAY;
5222 break;
5223
5224 case '6':
5225 raw_p = 1, type = PBM_COLOR;
5226 break;
5227
5228 default:
5229 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5230 goto error;
5231 }
5232
5233 /* Read width, height, maximum color-component. Characters
5234 starting with `#' up to the end of a line are ignored. */
5235 width = pbm_scan_number (&p, end);
5236 height = pbm_scan_number (&p, end);
5237
5238 if (type != PBM_MONO)
5239 {
5240 max_color_idx = pbm_scan_number (&p, end);
b9c89e11
JR
5241 if (max_color_idx > 65535 || max_color_idx < 0)
5242 {
5243 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5244 goto error;
5245 }
4ef0d4d0
KS
5246 }
5247
b9c89e11
JR
5248 if (!check_image_size (f, width, height))
5249 {
10ea2b82 5250 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
b9c89e11
JR
5251 goto error;
5252 }
4ef0d4d0 5253
547c9269 5254 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
4ef0d4d0
KS
5255 goto error;
5256
5257 /* Initialize the color hash table. */
5258 init_color_table ();
5259
5260 if (type == PBM_MONO)
5261 {
5262 int c = 0, g;
5263 struct image_keyword fmt[PBM_LAST];
5264 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5265 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5266
5267 /* Parse the image specification. */
72af86bd 5268 memcpy (fmt, pbm_format, sizeof fmt);
4ef0d4d0
KS
5269 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5270
5271 /* Get foreground and background colors, maybe allocate colors. */
5272 if (fmt[PBM_FOREGROUND].count
5273 && STRINGP (fmt[PBM_FOREGROUND].value))
5274 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5275 if (fmt[PBM_BACKGROUND].count
5276 && STRINGP (fmt[PBM_BACKGROUND].value))
5277 {
5278 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5279 img->background = bg;
5280 img->background_valid = 1;
5281 }
5282
5283 for (y = 0; y < height; ++y)
5284 for (x = 0; x < width; ++x)
5285 {
5286 if (raw_p)
5287 {
5288 if ((x & 7) == 0)
c295e710
CY
5289 {
5290 if (p >= end)
5291 {
5292 x_destroy_x_image (ximg);
5293 x_clear_image (f, img);
5294 image_error ("Invalid image size in image `%s'",
5295 img->spec, Qnil);
5296 goto error;
5297 }
5298 c = *p++;
5299 }
4ef0d4d0
KS
5300 g = c & 0x80;
5301 c <<= 1;
5302 }
5303 else
5304 g = pbm_scan_number (&p, end);
5305
5306 XPutPixel (ximg, x, y, g ? fg : bg);
5307 }
5308 }
5309 else
5310 {
b9c89e11
JR
5311 int expected_size = height * width;
5312 if (max_color_idx > 255)
5313 expected_size *= 2;
5314 if (type == PBM_COLOR)
5315 expected_size *= 3;
5316
5317 if (raw_p && p + expected_size > end)
39e653ea
CY
5318 {
5319 x_destroy_x_image (ximg);
fb0b0862 5320 x_clear_image (f, img);
39e653ea
CY
5321 image_error ("Invalid image size in image `%s'",
5322 img->spec, Qnil);
5323 goto error;
5324 }
5325
4ef0d4d0
KS
5326 for (y = 0; y < height; ++y)
5327 for (x = 0; x < width; ++x)
5328 {
5329 int r, g, b;
5330
b9c89e11
JR
5331 if (type == PBM_GRAY && raw_p)
5332 {
5333 r = g = b = *p++;
5334 if (max_color_idx > 255)
5335 r = g = b = r * 256 + *p++;
5336 }
5337 else if (type == PBM_GRAY)
5338 r = g = b = pbm_scan_number (&p, end);
4ef0d4d0
KS
5339 else if (raw_p)
5340 {
5341 r = *p++;
b9c89e11
JR
5342 if (max_color_idx > 255)
5343 r = r * 256 + *p++;
4ef0d4d0 5344 g = *p++;
b9c89e11
JR
5345 if (max_color_idx > 255)
5346 g = g * 256 + *p++;
4ef0d4d0 5347 b = *p++;
b9c89e11
JR
5348 if (max_color_idx > 255)
5349 b = b * 256 + *p++;
4ef0d4d0
KS
5350 }
5351 else
5352 {
5353 r = pbm_scan_number (&p, end);
5354 g = pbm_scan_number (&p, end);
5355 b = pbm_scan_number (&p, end);
5356 }
5357
5358 if (r < 0 || g < 0 || b < 0)
5359 {
5360 x_destroy_x_image (ximg);
5361 image_error ("Invalid pixel value in image `%s'",
5362 img->spec, Qnil);
5363 goto error;
5364 }
5365
5366 /* RGB values are now in the range 0..max_color_idx.
5367 Scale this to the range 0..0xffff supported by X. */
5368 r = (double) r * 65535 / max_color_idx;
5369 g = (double) g * 65535 / max_color_idx;
5370 b = (double) b * 65535 / max_color_idx;
5371 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5372 }
5373 }
5374
5375#ifdef COLOR_TABLE_SUPPORT
5376 /* Store in IMG->colors the colors allocated for the image, and
5377 free the color table. */
5378 img->colors = colors_in_color_table (&img->ncolors);
5379 free_color_table ();
5380#endif /* COLOR_TABLE_SUPPORT */
5381
5382 img->width = width;
5383 img->height = height;
5384
5385 /* Maybe fill in the background field while we have ximg handy. */
5386
5387 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
5388 /* Casting avoids a GCC warning. */
5389 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0 5390
547c9269
YM
5391 /* Put ximg into the image. */
5392 image_put_x_image (f, img, ximg, 0);
4ef0d4d0
KS
5393
5394 /* X and W32 versions did it here, MAC version above. ++kfs
1f026899 5395 img->width = width;
4ef0d4d0
KS
5396 img->height = height; */
5397
4ef0d4d0
KS
5398 xfree (contents);
5399 return 1;
5400}
5401
5402\f
5403/***********************************************************************
5404 PNG
5405 ***********************************************************************/
5406
9e2a2647 5407#if defined (HAVE_PNG) || defined (HAVE_NS)
4ef0d4d0
KS
5408
5409/* Function prototypes. */
5410
578098f3
PE
5411static bool png_image_p (Lisp_Object object);
5412static bool png_load (struct frame *f, struct image *img);
4ef0d4d0
KS
5413
5414/* The symbol `png' identifying images of this type. */
5415
955cbe7b 5416static Lisp_Object Qpng;
4ef0d4d0
KS
5417
5418/* Indices of image specification fields in png_format, below. */
5419
5420enum png_keyword_index
5421{
5422 PNG_TYPE,
5423 PNG_DATA,
5424 PNG_FILE,
5425 PNG_ASCENT,
5426 PNG_MARGIN,
5427 PNG_RELIEF,
5428 PNG_ALGORITHM,
5429 PNG_HEURISTIC_MASK,
5430 PNG_MASK,
5431 PNG_BACKGROUND,
5432 PNG_LAST
5433};
5434
5435/* Vector of image_keyword structures describing the format
5436 of valid user-defined image specifications. */
5437
91433552 5438static const struct image_keyword png_format[PNG_LAST] =
4ef0d4d0
KS
5439{
5440 {":type", IMAGE_SYMBOL_VALUE, 1},
5441 {":data", IMAGE_STRING_VALUE, 0},
5442 {":file", IMAGE_STRING_VALUE, 0},
5443 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 5444 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
5445 {":relief", IMAGE_INTEGER_VALUE, 0},
5446 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5447 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5448 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5449 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5450};
5451
a9e7a9d5 5452#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 5453static bool init_png_functions (void);
bb4d86b4
CY
5454#else
5455#define init_png_functions NULL
5456#endif
5457
4ef0d4d0
KS
5458/* Structure describing the image type `png'. */
5459
5460static struct image_type png_type =
5461{
5462 &Qpng,
5463 png_image_p,
5464 png_load,
5465 x_clear_image,
bb4d86b4 5466 init_png_functions,
4ef0d4d0
KS
5467 NULL
5468};
5469
578098f3 5470/* Return true if OBJECT is a valid PNG image specification. */
4ef0d4d0 5471
578098f3 5472static bool
d3da34e0 5473png_image_p (Lisp_Object object)
4ef0d4d0
KS
5474{
5475 struct image_keyword fmt[PNG_LAST];
72af86bd 5476 memcpy (fmt, png_format, sizeof fmt);
4ef0d4d0
KS
5477
5478 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5479 return 0;
5480
5481 /* Must specify either the :data or :file keyword. */
5482 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5483}
5484
9e2a2647 5485#endif /* HAVE_PNG || HAVE_NS */
4ef0d4d0
KS
5486
5487
5488#ifdef HAVE_PNG
5489
0fda9b75 5490#ifdef WINDOWSNT
4ef0d4d0
KS
5491/* PNG library details. */
5492
14beddf4
CY
5493DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5494DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5495DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5496 png_error_ptr, png_error_ptr));
5497DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5498DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5499DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5500DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5501DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5502DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
850690cc
JB
5503 png_uint_32 *, png_uint_32 *,
5504 int *, int *, int *, int *, int *));
14beddf4
CY
5505DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5506DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5507DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5508DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5509DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
850690cc 5510 int, int, double));
14beddf4
CY
5511DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5512DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5513DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5514DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5515DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5516DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5517DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
4ef0d4d0 5518
7f9c5df9 5519#if (PNG_LIBPNG_VER >= 10500)
14beddf4
CY
5520DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int));
5521DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
7f9c5df9 5522#endif /* libpng version >= 1.5 */
4ef0d4d0 5523
578098f3 5524static bool
d07ff9db 5525init_png_functions (void)
4ef0d4d0
KS
5526{
5527 HMODULE library;
5528
d07ff9db 5529 if (!(library = w32_delayed_load (Qpng)))
4ef0d4d0
KS
5530 return 0;
5531
5532 LOAD_IMGLIB_FN (library, png_get_io_ptr);
285d07e2 5533 LOAD_IMGLIB_FN (library, png_sig_cmp);
4ef0d4d0
KS
5534 LOAD_IMGLIB_FN (library, png_create_read_struct);
5535 LOAD_IMGLIB_FN (library, png_create_info_struct);
5536 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5537 LOAD_IMGLIB_FN (library, png_set_read_fn);
4ef0d4d0
KS
5538 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5539 LOAD_IMGLIB_FN (library, png_read_info);
5540 LOAD_IMGLIB_FN (library, png_get_IHDR);
5541 LOAD_IMGLIB_FN (library, png_get_valid);
5542 LOAD_IMGLIB_FN (library, png_set_strip_16);
5543 LOAD_IMGLIB_FN (library, png_set_expand);
5544 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5545 LOAD_IMGLIB_FN (library, png_set_background);
5546 LOAD_IMGLIB_FN (library, png_get_bKGD);
5547 LOAD_IMGLIB_FN (library, png_read_update_info);
5548 LOAD_IMGLIB_FN (library, png_get_channels);
5549 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5550 LOAD_IMGLIB_FN (library, png_read_image);
5551 LOAD_IMGLIB_FN (library, png_read_end);
5552 LOAD_IMGLIB_FN (library, png_error);
7f9c5df9
CY
5553
5554#if (PNG_LIBPNG_VER >= 10500)
5555 LOAD_IMGLIB_FN (library, png_longjmp);
5556 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5557#endif /* libpng version >= 1.5 */
5558
4ef0d4d0
KS
5559 return 1;
5560}
5561#else
5562
5563#define fn_png_get_io_ptr png_get_io_ptr
285d07e2 5564#define fn_png_sig_cmp png_sig_cmp
4ef0d4d0
KS
5565#define fn_png_create_read_struct png_create_read_struct
5566#define fn_png_create_info_struct png_create_info_struct
5567#define fn_png_destroy_read_struct png_destroy_read_struct
5568#define fn_png_set_read_fn png_set_read_fn
4ef0d4d0
KS
5569#define fn_png_set_sig_bytes png_set_sig_bytes
5570#define fn_png_read_info png_read_info
5571#define fn_png_get_IHDR png_get_IHDR
5572#define fn_png_get_valid png_get_valid
5573#define fn_png_set_strip_16 png_set_strip_16
5574#define fn_png_set_expand png_set_expand
5575#define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5576#define fn_png_set_background png_set_background
5577#define fn_png_get_bKGD png_get_bKGD
5578#define fn_png_read_update_info png_read_update_info
5579#define fn_png_get_channels png_get_channels
5580#define fn_png_get_rowbytes png_get_rowbytes
5581#define fn_png_read_image png_read_image
5582#define fn_png_read_end png_read_end
5583#define fn_png_error png_error
5584
7f9c5df9
CY
5585#if (PNG_LIBPNG_VER >= 10500)
5586#define fn_png_longjmp png_longjmp
5587#define fn_png_set_longjmp_fn png_set_longjmp_fn
5588#endif /* libpng version >= 1.5 */
5589
0fda9b75 5590#endif /* WINDOWSNT */
4ef0d4d0 5591
0328b6de
PE
5592/* Possibly inefficient/inexact substitutes for _setjmp and _longjmp.
5593 Do not use sys_setjmp, as PNG supports only jmp_buf. The _longjmp
7105c8cb
EZ
5594 substitute may munge the signal mask, but that should be OK here.
5595 MinGW (MS-Windows) uses _setjmp and defines setjmp to _setjmp in
5596 the system header setjmp.h; don't mess up that. */
0328b6de 5597#ifndef HAVE__SETJMP
39a57ad0 5598# define _setjmp(j) setjmp (j)
0328b6de
PE
5599# define _longjmp longjmp
5600#endif
7f9c5df9
CY
5601
5602#if (PNG_LIBPNG_VER < 10500)
af26b72c 5603#define PNG_LONGJMP(ptr) (_longjmp ((ptr)->jmpbuf, 1))
7f9c5df9
CY
5604#define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5605#else
df61c790 5606/* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
c2e79cb4 5607#define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
7f9c5df9 5608#define PNG_JMPBUF(ptr) \
af26b72c 5609 (*fn_png_set_longjmp_fn ((ptr), _longjmp, sizeof (jmp_buf)))
7f9c5df9
CY
5610#endif
5611
4ef0d4d0
KS
5612/* Error and warning handlers installed when the PNG library
5613 is initialized. */
5614
845ca893 5615static _Noreturn void
d3da34e0 5616my_png_error (png_struct *png_ptr, const char *msg)
4ef0d4d0 5617{
a54e2c05 5618 eassert (png_ptr != NULL);
5be1c984
EZ
5619 /* Avoid compiler warning about deprecated direct access to
5620 png_ptr's fields in libpng versions 1.4.x. */
4ef0d4d0 5621 image_error ("PNG error: %s", build_string (msg), Qnil);
7f9c5df9 5622 PNG_LONGJMP (png_ptr);
4ef0d4d0
KS
5623}
5624
5625
5626static void
d3da34e0 5627my_png_warning (png_struct *png_ptr, const char *msg)
4ef0d4d0 5628{
a54e2c05 5629 eassert (png_ptr != NULL);
4ef0d4d0
KS
5630 image_error ("PNG warning: %s", build_string (msg), Qnil);
5631}
5632
5633/* Memory source for PNG decoding. */
5634
5635struct png_memory_storage
5636{
5637 unsigned char *bytes; /* The data */
3f791afe
PE
5638 ptrdiff_t len; /* How big is it? */
5639 ptrdiff_t index; /* Where are we? */
4ef0d4d0
KS
5640};
5641
5642
5643/* Function set as reader function when reading PNG image from memory.
5644 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5645 bytes from the input to DATA. */
5646
5647static void
d3da34e0 5648png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
4ef0d4d0
KS
5649{
5650 struct png_memory_storage *tbr
5651 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5652
5653 if (length > tbr->len - tbr->index)
5654 fn_png_error (png_ptr, "Read error");
5655
72af86bd 5656 memcpy (data, tbr->bytes + tbr->index, length);
4ef0d4d0
KS
5657 tbr->index = tbr->index + length;
5658}
5659
b0da69a7 5660
9a22a004
JB
5661/* Function set as reader function when reading PNG image from a file.
5662 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5663 bytes from the input to DATA. */
5664
5665static void
d3da34e0 5666png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
9a22a004
JB
5667{
5668 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5669
5670 if (fread (data, 1, length, fp) < length)
5671 fn_png_error (png_ptr, "Read error");
5672}
5673
5674
578098f3 5675/* Load PNG image IMG for use on frame F. Value is true if
4ef0d4d0
KS
5676 successful. */
5677
40bce90b
PE
5678struct png_load_context
5679{
0328b6de 5680 /* These are members so that longjmp doesn't munge local variables. */
40bce90b
PE
5681 png_struct *png_ptr;
5682 png_info *info_ptr;
5683 png_info *end_info;
5684 FILE *fp;
5685 png_byte *pixels;
5686 png_byte **rows;
5687};
5688
578098f3 5689static bool
40bce90b 5690png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
4ef0d4d0
KS
5691{
5692 Lisp_Object file, specified_file;
5693 Lisp_Object specified_data;
5adf60bc
PE
5694 int x, y;
5695 ptrdiff_t i;
4ef0d4d0 5696 XImagePtr ximg, mask_img = NULL;
40bce90b 5697 png_struct *png_ptr;
4ef0d4d0 5698 png_info *info_ptr = NULL, *end_info = NULL;
40bce90b 5699 FILE *fp = NULL;
4ef0d4d0 5700 png_byte sig[8];
40bce90b
PE
5701 png_byte *pixels = NULL;
5702 png_byte **rows = NULL;
4ef0d4d0
KS
5703 png_uint_32 width, height;
5704 int bit_depth, color_type, interlace_type;
5705 png_byte channels;
5706 png_uint_32 row_bytes;
578098f3 5707 bool transparent_p;
4ef0d4d0
KS
5708 struct png_memory_storage tbr; /* Data to be read */
5709
5710 /* Find out what file to load. */
5711 specified_file = image_spec_value (img->spec, QCfile, NULL);
5712 specified_data = image_spec_value (img->spec, QCdata, NULL);
4ef0d4d0
KS
5713
5714 if (NILP (specified_data))
5715 {
5716 file = x_find_image_file (specified_file);
5717 if (!STRINGP (file))
5718 {
5719 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
5720 return 0;
5721 }
5722
5723 /* Open the image file. */
406af475 5724 fp = emacs_fopen (SSDATA (file), "rb");
4ef0d4d0
KS
5725 if (!fp)
5726 {
5727 image_error ("Cannot open image file `%s'", file, Qnil);
4ef0d4d0
KS
5728 return 0;
5729 }
5730
5731 /* Check PNG signature. */
5732 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
285d07e2 5733 || fn_png_sig_cmp (sig, 0, sizeof sig))
4ef0d4d0
KS
5734 {
5735 image_error ("Not a PNG file: `%s'", file, Qnil);
4ef0d4d0
KS
5736 fclose (fp);
5737 return 0;
5738 }
5739 }
5740 else
5741 {
7574650a
AS
5742 if (!STRINGP (specified_data))
5743 {
5744 image_error ("Invalid image data `%s'", specified_data, Qnil);
5745 return 0;
5746 }
5747
4ef0d4d0
KS
5748 /* Read from memory. */
5749 tbr.bytes = SDATA (specified_data);
5750 tbr.len = SBYTES (specified_data);
5751 tbr.index = 0;
5752
5753 /* Check PNG signature. */
5754 if (tbr.len < sizeof sig
285d07e2 5755 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
4ef0d4d0
KS
5756 {
5757 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
4ef0d4d0
KS
5758 return 0;
5759 }
5760
5761 /* Need to skip past the signature. */
5762 tbr.bytes += sizeof (sig);
5763 }
5764
df61c790
AS
5765 /* Initialize read and info structs for PNG lib. */
5766 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5767 NULL, my_png_error,
5768 my_png_warning);
40bce90b 5769 if (png_ptr)
4ef0d4d0 5770 {
40bce90b
PE
5771 info_ptr = fn_png_create_info_struct (png_ptr);
5772 end_info = fn_png_create_info_struct (png_ptr);
4ef0d4d0
KS
5773 }
5774
40bce90b
PE
5775 c->png_ptr = png_ptr;
5776 c->info_ptr = info_ptr;
5777 c->end_info = end_info;
5778 c->fp = fp;
5779 c->pixels = pixels;
5780 c->rows = rows;
5781
5782 if (! (info_ptr && end_info))
4ef0d4d0 5783 {
40bce90b
PE
5784 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5785 png_ptr = 0;
4ef0d4d0 5786 }
40bce90b 5787 if (! png_ptr)
4ef0d4d0 5788 {
4ef0d4d0 5789 if (fp) fclose (fp);
4ef0d4d0
KS
5790 return 0;
5791 }
5792
5793 /* Set error jump-back. We come back here when the PNG library
5794 detects an error. */
af26b72c 5795 if (_setjmp (PNG_JMPBUF (png_ptr)))
4ef0d4d0
KS
5796 {
5797 error:
40bce90b
PE
5798 if (c->png_ptr)
5799 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5800 xfree (c->pixels);
5801 xfree (c->rows);
5802 if (c->fp)
5803 fclose (c->fp);
4ef0d4d0
KS
5804 return 0;
5805 }
5806
40bce90b
PE
5807 /* Silence a bogus diagnostic; see GCC bug 54561. */
5808 IF_LINT (fp = c->fp);
5809
4ef0d4d0
KS
5810 /* Read image info. */
5811 if (!NILP (specified_data))
5812 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5813 else
9a22a004 5814 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
4ef0d4d0
KS
5815
5816 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5817 fn_png_read_info (png_ptr, info_ptr);
5818 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5819 &interlace_type, NULL, NULL);
5820
3f791afe
PE
5821 if (! (width <= INT_MAX && height <= INT_MAX
5822 && check_image_size (f, width, height)))
10ea2b82
JR
5823 {
5824 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5825 goto error;
5826 }
ca4aa935
PE
5827
5828 /* Create the X image and pixmap now, so that the work below can be
5829 omitted if the image is too large for X. */
547c9269 5830 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
ca4aa935
PE
5831 goto error;
5832
4ef0d4d0
KS
5833 /* If image contains simply transparency data, we prefer to
5834 construct a clipping mask. */
5835 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5836 transparent_p = 1;
5837 else
5838 transparent_p = 0;
5839
5840 /* This function is easier to write if we only have to handle
5841 one data format: RGB or RGBA with 8 bits per channel. Let's
5842 transform other formats into that format. */
5843
5844 /* Strip more than 8 bits per channel. */
5845 if (bit_depth == 16)
5846 fn_png_set_strip_16 (png_ptr);
5847
5848 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5849 if available. */
5850 fn_png_set_expand (png_ptr);
5851
5852 /* Convert grayscale images to RGB. */
5853 if (color_type == PNG_COLOR_TYPE_GRAY
5854 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5855 fn_png_set_gray_to_rgb (png_ptr);
5856
4ef0d4d0
KS
5857 /* Handle alpha channel by combining the image with a background
5858 color. Do this only if a real alpha channel is supplied. For
5859 simple transparency, we prefer a clipping mask. */
5860 if (!transparent_p)
5861 {
917ac1a9 5862 /* png_color_16 *image_bg; */
4ef0d4d0
KS
5863 Lisp_Object specified_bg
5864 = image_spec_value (img->spec, QCbackground, NULL);
c4f13f44 5865 int shift = (bit_depth == 16) ? 0 : 8;
4ef0d4d0
KS
5866
5867 if (STRINGP (specified_bg))
5868 /* The user specified `:background', use that. */
5869 {
4ef0d4d0 5870 XColor color;
42a5b22f 5871 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
4ef0d4d0
KS
5872 {
5873 png_color_16 user_bg;
5874
72af86bd 5875 memset (&user_bg, 0, sizeof user_bg);
c4f13f44
CY
5876 user_bg.red = color.red >> shift;
5877 user_bg.green = color.green >> shift;
5878 user_bg.blue = color.blue >> shift;
4ef0d4d0
KS
5879
5880 fn_png_set_background (png_ptr, &user_bg,
5881 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5882 }
5883 }
4ef0d4d0
KS
5884 else
5885 {
c4f13f44
CY
5886 /* We use the current frame background, ignoring any default
5887 background color set by the image. */
8b7d0a16 5888#if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4ef0d4d0
KS
5889 XColor color;
5890 png_color_16 frame_background;
5891
5892 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5893 x_query_color (f, &color);
5894
72af86bd 5895 memset (&frame_background, 0, sizeof frame_background);
c4f13f44
CY
5896 frame_background.red = color.red >> shift;
5897 frame_background.green = color.green >> shift;
5898 frame_background.blue = color.blue >> shift;
4ef0d4d0
KS
5899#endif /* HAVE_X_WINDOWS */
5900
4ef0d4d0
KS
5901 fn_png_set_background (png_ptr, &frame_background,
5902 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5903 }
5904 }
5905
5906 /* Update info structure. */
5907 fn_png_read_update_info (png_ptr, info_ptr);
5908
5909 /* Get number of channels. Valid values are 1 for grayscale images
5910 and images with a palette, 2 for grayscale images with transparency
5911 information (alpha channel), 3 for RGB images, and 4 for RGB
5912 images with alpha channel, i.e. RGBA. If conversions above were
5913 sufficient we should only have 3 or 4 channels here. */
5914 channels = fn_png_get_channels (png_ptr, info_ptr);
a54e2c05 5915 eassert (channels == 3 || channels == 4);
4ef0d4d0
KS
5916
5917 /* Number of bytes needed for one row of the image. */
5918 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5919
5920 /* Allocate memory for the image. */
3f791afe
PE
5921 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows < height
5922 || min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height < row_bytes)
5923 memory_full (SIZE_MAX);
40bce90b
PE
5924 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
5925 c->rows = rows = xmalloc (height * sizeof *rows);
4ef0d4d0
KS
5926 for (i = 0; i < height; ++i)
5927 rows[i] = pixels + i * row_bytes;
5928
5929 /* Read the entire image. */
5930 fn_png_read_image (png_ptr, rows);
5931 fn_png_read_end (png_ptr, info_ptr);
5932 if (fp)
5933 {
5934 fclose (fp);
40bce90b 5935 c->fp = NULL;
4ef0d4d0
KS
5936 }
5937
4ef0d4d0
KS
5938 /* Create an image and pixmap serving as mask if the PNG image
5939 contains an alpha channel. */
5940 if (channels == 4
5941 && !transparent_p
547c9269
YM
5942 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
5943 &mask_img, 1))
4ef0d4d0
KS
5944 {
5945 x_destroy_x_image (ximg);
547c9269 5946 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
4ef0d4d0
KS
5947 goto error;
5948 }
5949
5950 /* Fill the X image and mask from PNG data. */
5951 init_color_table ();
5952
5953 for (y = 0; y < height; ++y)
5954 {
5955 png_byte *p = rows[y];
5956
5957 for (x = 0; x < width; ++x)
5958 {
13464394 5959 int r, g, b;
4ef0d4d0
KS
5960
5961 r = *p++ << 8;
5962 g = *p++ << 8;
5963 b = *p++ << 8;
5964 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5965 /* An alpha channel, aka mask channel, associates variable
5966 transparency with an image. Where other image formats
5967 support binary transparency---fully transparent or fully
5968 opaque---PNG allows up to 254 levels of partial transparency.
5969 The PNG library implements partial transparency by combining
5970 the image with a specified background color.
5971
5972 I'm not sure how to handle this here nicely: because the
5973 background on which the image is displayed may change, for
5974 real alpha channel support, it would be necessary to create
5975 a new image for each possible background.
5976
5977 What I'm doing now is that a mask is created if we have
5978 boolean transparency information. Otherwise I'm using
5979 the frame's background color to combine the image with. */
5980
5981 if (channels == 4)
5982 {
5983 if (mask_img)
9ecf6403 5984 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
4ef0d4d0
KS
5985 ++p;
5986 }
5987 }
5988 }
5989
5990 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5991 /* Set IMG's background color from the PNG image, unless the user
5992 overrode it. */
5993 {
5994 png_color_16 *bg;
5995 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5996 {
5997 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5998 img->background_valid = 1;
5999 }
6000 }
6001
6002#ifdef COLOR_TABLE_SUPPORT
6003 /* Remember colors allocated for this image. */
6004 img->colors = colors_in_color_table (&img->ncolors);
6005 free_color_table ();
6006#endif /* COLOR_TABLE_SUPPORT */
6007
6008 /* Clean up. */
40bce90b 6009 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
4ef0d4d0
KS
6010 xfree (rows);
6011 xfree (pixels);
6012
6013 img->width = width;
6014 img->height = height;
6015
2e09fef1
EZ
6016 /* Maybe fill in the background field while we have ximg handy.
6017 Casting avoids a GCC warning. */
6018 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0 6019
547c9269
YM
6020 /* Put ximg into the image. */
6021 image_put_x_image (f, img, ximg, 0);
4ef0d4d0
KS
6022
6023 /* Same for the mask. */
6024 if (mask_img)
6025 {
2e09fef1
EZ
6026 /* Fill in the background_transparent field while we have the
6027 mask handy. Casting avoids a GCC warning. */
6028 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
4ef0d4d0 6029
547c9269 6030 image_put_x_image (f, img, mask_img, 1);
4ef0d4d0
KS
6031 }
6032
4ef0d4d0
KS
6033 return 1;
6034}
6035
578098f3 6036static bool
40bce90b
PE
6037png_load (struct frame *f, struct image *img)
6038{
6039 struct png_load_context c;
6040 return png_load_body (f, img, &c);
6041}
6042
4ef0d4d0
KS
6043#else /* HAVE_PNG */
6044
edfda783 6045#ifdef HAVE_NS
578098f3 6046static bool
edfda783
AR
6047png_load (struct frame *f, struct image *img)
6048{
5e617bc2
JB
6049 return ns_load_image (f, img,
6050 image_spec_value (img->spec, QCfile, NULL),
6051 image_spec_value (img->spec, QCdata, NULL));
edfda783
AR
6052}
6053#endif /* HAVE_NS */
6054
6055
4ef0d4d0
KS
6056#endif /* !HAVE_PNG */
6057
6058
6059\f
6060/***********************************************************************
6061 JPEG
6062 ***********************************************************************/
6063
9e2a2647 6064#if defined (HAVE_JPEG) || defined (HAVE_NS)
4ef0d4d0 6065
578098f3
PE
6066static bool jpeg_image_p (Lisp_Object object);
6067static bool jpeg_load (struct frame *f, struct image *img);
4ef0d4d0
KS
6068
6069/* The symbol `jpeg' identifying images of this type. */
6070
955cbe7b 6071static Lisp_Object Qjpeg;
4ef0d4d0
KS
6072
6073/* Indices of image specification fields in gs_format, below. */
6074
6075enum jpeg_keyword_index
6076{
6077 JPEG_TYPE,
6078 JPEG_DATA,
6079 JPEG_FILE,
6080 JPEG_ASCENT,
6081 JPEG_MARGIN,
6082 JPEG_RELIEF,
6083 JPEG_ALGORITHM,
6084 JPEG_HEURISTIC_MASK,
6085 JPEG_MASK,
6086 JPEG_BACKGROUND,
6087 JPEG_LAST
6088};
6089
6090/* Vector of image_keyword structures describing the format
6091 of valid user-defined image specifications. */
6092
91433552 6093static const struct image_keyword jpeg_format[JPEG_LAST] =
4ef0d4d0
KS
6094{
6095 {":type", IMAGE_SYMBOL_VALUE, 1},
6096 {":data", IMAGE_STRING_VALUE, 0},
6097 {":file", IMAGE_STRING_VALUE, 0},
6098 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 6099 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
6100 {":relief", IMAGE_INTEGER_VALUE, 0},
6101 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6102 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6103 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6104 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6105};
6106
a9e7a9d5 6107#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 6108static bool init_jpeg_functions (void);
bb4d86b4
CY
6109#else
6110#define init_jpeg_functions NULL
6111#endif
6112
4ef0d4d0
KS
6113/* Structure describing the image type `jpeg'. */
6114
6115static struct image_type jpeg_type =
6116{
6117 &Qjpeg,
6118 jpeg_image_p,
6119 jpeg_load,
6120 x_clear_image,
bb4d86b4 6121 init_jpeg_functions,
4ef0d4d0
KS
6122 NULL
6123};
6124
578098f3 6125/* Return true if OBJECT is a valid JPEG image specification. */
4ef0d4d0 6126
578098f3 6127static bool
d3da34e0 6128jpeg_image_p (Lisp_Object object)
4ef0d4d0
KS
6129{
6130 struct image_keyword fmt[JPEG_LAST];
6131
72af86bd 6132 memcpy (fmt, jpeg_format, sizeof fmt);
4ef0d4d0
KS
6133
6134 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6135 return 0;
6136
6137 /* Must specify either the :data or :file keyword. */
6138 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6139}
6140
9e2a2647 6141#endif /* HAVE_JPEG || HAVE_NS */
4ef0d4d0
KS
6142
6143#ifdef HAVE_JPEG
6144
6145/* Work around a warning about HAVE_STDLIB_H being redefined in
6146 jconfig.h. */
6147#ifdef HAVE_STDLIB_H
4ef0d4d0
KS
6148#undef HAVE_STDLIB_H
6149#endif /* HAVE_STLIB_H */
6150
66354420 6151#if defined (HAVE_NTGUI) && !defined (__WIN32__)
28893db2
JB
6152/* In older releases of the jpeg library, jpeglib.h will define boolean
6153 differently depending on __WIN32__, so make sure it is defined. */
66354420
JR
6154#define __WIN32__ 1
6155#endif
6156
93aa5c81
DC
6157/* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6158 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6159 using the Windows boolean type instead of the jpeglib boolean type
6160 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6161 headers are included along with windows.h, so under Cygwin, jpeglib
6162 attempts to define a conflicting boolean type. Worse, forcing
6163 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6164 because it created an ABI incompatibility between the
6165 already-compiled jpeg library and the header interface definition.
6166
6167 The best we can do is to define jpeglib's boolean type to a
6168 different name. This name, jpeg_boolean, remains in effect through
6169 the rest of image.c.
6170*/
a9e7a9d5 6171#if defined CYGWIN && defined HAVE_NTGUI
0fda9b75 6172#define boolean jpeg_boolean
2ae3a8a7 6173#endif
4ef0d4d0
KS
6174#include <jpeglib.h>
6175#include <jerror.h>
4ef0d4d0 6176
0fda9b75 6177#ifdef WINDOWSNT
4ef0d4d0
KS
6178
6179/* JPEG library details. */
14beddf4
CY
6180DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6181DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6182DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6183DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6184DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6185DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6186DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6187DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
4ef0d4d0 6188
578098f3 6189static bool
d07ff9db 6190init_jpeg_functions (void)
4ef0d4d0
KS
6191{
6192 HMODULE library;
6193
d07ff9db 6194 if (!(library = w32_delayed_load (Qjpeg)))
4ef0d4d0
KS
6195 return 0;
6196
6197 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6198 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6199 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6200 LOAD_IMGLIB_FN (library, jpeg_read_header);
4ef0d4d0
KS
6201 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6202 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6203 LOAD_IMGLIB_FN (library, jpeg_std_error);
6204 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6205 return 1;
6206}
6207
6208/* Wrapper since we can't directly assign the function pointer
6209 to another function pointer that was declared more completely easily. */
6210static boolean
7c3320d8 6211jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
4ef0d4d0
KS
6212{
6213 return fn_jpeg_resync_to_restart (cinfo, desired);
6214}
6215
6216#else
6217
5e617bc2 6218#define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
4ef0d4d0
KS
6219#define fn_jpeg_start_decompress jpeg_start_decompress
6220#define fn_jpeg_finish_decompress jpeg_finish_decompress
6221#define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6222#define fn_jpeg_read_header jpeg_read_header
6223#define fn_jpeg_read_scanlines jpeg_read_scanlines
4ef0d4d0
KS
6224#define fn_jpeg_std_error jpeg_std_error
6225#define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6226
0fda9b75 6227#endif /* WINDOWSNT */
4ef0d4d0
KS
6228
6229struct my_jpeg_error_mgr
6230{
6231 struct jpeg_error_mgr pub;
0328b6de 6232 sys_jmp_buf setjmp_buffer;
40bce90b 6233
0328b6de 6234 /* The remaining members are so that longjmp doesn't munge local
40bce90b
PE
6235 variables. */
6236 struct jpeg_decompress_struct cinfo;
6237 enum
6238 {
6239 MY_JPEG_ERROR_EXIT,
6240 MY_JPEG_INVALID_IMAGE_SIZE,
6241 MY_JPEG_CANNOT_CREATE_X
6242 } failure_code;
5f0cb45a
PE
6243#ifdef lint
6244 FILE *fp;
6245#endif
4ef0d4d0
KS
6246};
6247
6248
845ca893 6249static _Noreturn void
d3da34e0 6250my_error_exit (j_common_ptr cinfo)
4ef0d4d0
KS
6251{
6252 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
40bce90b 6253 mgr->failure_code = MY_JPEG_ERROR_EXIT;
0328b6de 6254 sys_longjmp (mgr->setjmp_buffer, 1);
4ef0d4d0
KS
6255}
6256
6257
6258/* Init source method for JPEG data source manager. Called by
6259 jpeg_read_header() before any data is actually read. See
6260 libjpeg.doc from the JPEG lib distribution. */
6261
6262static void
d3da34e0 6263our_common_init_source (j_decompress_ptr cinfo)
b25a72ab
JB
6264{
6265}
6266
6267
6268/* Method to terminate data source. Called by
6269 jpeg_finish_decompress() after all data has been processed. */
6270
6271static void
d3da34e0 6272our_common_term_source (j_decompress_ptr cinfo)
4ef0d4d0
KS
6273{
6274}
6275
6276
6277/* Fill input buffer method for JPEG data source manager. Called
6278 whenever more data is needed. We read the whole image in one step,
6279 so this only adds a fake end of input marker at the end. */
6280
5a1539f3 6281static JOCTET our_memory_buffer[2];
aca946f3 6282
4ef0d4d0 6283static boolean
d3da34e0 6284our_memory_fill_input_buffer (j_decompress_ptr cinfo)
4ef0d4d0
KS
6285{
6286 /* Insert a fake EOI marker. */
6287 struct jpeg_source_mgr *src = cinfo->src;
4ef0d4d0 6288
5a1539f3
MB
6289 our_memory_buffer[0] = (JOCTET) 0xFF;
6290 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
4ef0d4d0 6291
5a1539f3 6292 src->next_input_byte = our_memory_buffer;
4ef0d4d0 6293 src->bytes_in_buffer = 2;
e0e30823 6294 return 1;
4ef0d4d0
KS
6295}
6296
6297
6298/* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6299 is the JPEG data source manager. */
6300
6301static void
d3da34e0 6302our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
4ef0d4d0
KS
6303{
6304 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6305
6306 if (src)
6307 {
6308 if (num_bytes > src->bytes_in_buffer)
6309 ERREXIT (cinfo, JERR_INPUT_EOF);
6310
6311 src->bytes_in_buffer -= num_bytes;
6312 src->next_input_byte += num_bytes;
6313 }
6314}
6315
6316
4ef0d4d0
KS
6317/* Set up the JPEG lib for reading an image from DATA which contains
6318 LEN bytes. CINFO is the decompression info structure created for
6319 reading the image. */
6320
6321static void
92547ff9 6322jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
4ef0d4d0
KS
6323{
6324 struct jpeg_source_mgr *src;
6325
6326 if (cinfo->src == NULL)
6327 {
6328 /* First time for this JPEG object? */
6329 cinfo->src = (struct jpeg_source_mgr *)
6330 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6331 sizeof (struct jpeg_source_mgr));
6332 src = (struct jpeg_source_mgr *) cinfo->src;
6333 src->next_input_byte = data;
6334 }
6335
6336 src = (struct jpeg_source_mgr *) cinfo->src;
b25a72ab
JB
6337 src->init_source = our_common_init_source;
6338 src->fill_input_buffer = our_memory_fill_input_buffer;
6339 src->skip_input_data = our_memory_skip_input_data;
4ef0d4d0 6340 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
b25a72ab 6341 src->term_source = our_common_term_source;
4ef0d4d0
KS
6342 src->bytes_in_buffer = len;
6343 src->next_input_byte = data;
6344}
6345
6346
b25a72ab
JB
6347struct jpeg_stdio_mgr
6348{
6349 struct jpeg_source_mgr mgr;
6350 boolean finished;
6351 FILE *file;
6352 JOCTET *buffer;
6353};
6354
6355
6356/* Size of buffer to read JPEG from file.
6357 Not too big, as we want to use alloc_small. */
6358#define JPEG_STDIO_BUFFER_SIZE 8192
6359
6360
6361/* Fill input buffer method for JPEG data source manager. Called
6362 whenever more data is needed. The data is read from a FILE *. */
6363
6364static boolean
d3da34e0 6365our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
b25a72ab
JB
6366{
6367 struct jpeg_stdio_mgr *src;
6368
6369 src = (struct jpeg_stdio_mgr *) cinfo->src;
6370 if (!src->finished)
6371 {
3f791afe 6372 ptrdiff_t bytes;
b25a72ab
JB
6373
6374 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6375 if (bytes > 0)
6376 src->mgr.bytes_in_buffer = bytes;
6377 else
6378 {
6379 WARNMS (cinfo, JWRN_JPEG_EOF);
6380 src->finished = 1;
6381 src->buffer[0] = (JOCTET) 0xFF;
6382 src->buffer[1] = (JOCTET) JPEG_EOI;
6383 src->mgr.bytes_in_buffer = 2;
6384 }
6385 src->mgr.next_input_byte = src->buffer;
6386 }
6387
6388 return 1;
6389}
6390
6391
6392/* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6393 is the JPEG data source manager. */
6394
6395static void
d3da34e0 6396our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
b25a72ab
JB
6397{
6398 struct jpeg_stdio_mgr *src;
6399 src = (struct jpeg_stdio_mgr *) cinfo->src;
6400
6401 while (num_bytes > 0 && !src->finished)
6402 {
6403 if (num_bytes <= src->mgr.bytes_in_buffer)
6404 {
6405 src->mgr.bytes_in_buffer -= num_bytes;
6406 src->mgr.next_input_byte += num_bytes;
6407 break;
6408 }
6409 else
6410 {
6411 num_bytes -= src->mgr.bytes_in_buffer;
6412 src->mgr.bytes_in_buffer = 0;
6413 src->mgr.next_input_byte = NULL;
6414
6415 our_stdio_fill_input_buffer (cinfo);
6416 }
6417 }
6418}
6419
6420
6421/* Set up the JPEG lib for reading an image from a FILE *.
6422 CINFO is the decompression info structure created for
6423 reading the image. */
6424
6425static void
d3da34e0 6426jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
b25a72ab
JB
6427{
6428 struct jpeg_stdio_mgr *src;
6429
6430 if (cinfo->src != NULL)
6431 src = (struct jpeg_stdio_mgr *) cinfo->src;
6432 else
6433 {
6434 /* First time for this JPEG object? */
6435 cinfo->src = (struct jpeg_source_mgr *)
6436 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6437 sizeof (struct jpeg_stdio_mgr));
6438 src = (struct jpeg_stdio_mgr *) cinfo->src;
6439 src->buffer = (JOCTET *)
6440 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6441 JPEG_STDIO_BUFFER_SIZE);
6442 }
6443
6444 src->file = fp;
6445 src->finished = 0;
6446 src->mgr.init_source = our_common_init_source;
6447 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6448 src->mgr.skip_input_data = our_stdio_skip_input_data;
6449 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6450 src->mgr.term_source = our_common_term_source;
6451 src->mgr.bytes_in_buffer = 0;
6452 src->mgr.next_input_byte = NULL;
6453}
6454
6455
4ef0d4d0
KS
6456/* Load image IMG for use on frame F. Patterned after example.c
6457 from the JPEG lib. */
6458
578098f3 6459static bool
40bce90b
PE
6460jpeg_load_body (struct frame *f, struct image *img,
6461 struct my_jpeg_error_mgr *mgr)
4ef0d4d0 6462{
4ef0d4d0
KS
6463 Lisp_Object file, specified_file;
6464 Lisp_Object specified_data;
40bce90b 6465 FILE *fp = NULL;
4ef0d4d0
KS
6466 JSAMPARRAY buffer;
6467 int row_stride, x, y;
6468 XImagePtr ximg = NULL;
4ef0d4d0
KS
6469 unsigned long *colors;
6470 int width, height;
4ef0d4d0
KS
6471
6472 /* Open the JPEG file. */
6473 specified_file = image_spec_value (img->spec, QCfile, NULL);
6474 specified_data = image_spec_value (img->spec, QCdata, NULL);
4ef0d4d0
KS
6475
6476 if (NILP (specified_data))
6477 {
6478 file = x_find_image_file (specified_file);
6479 if (!STRINGP (file))
6480 {
6481 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
6482 return 0;
6483 }
6484
406af475 6485 fp = emacs_fopen (SSDATA (file), "rb");
4ef0d4d0
KS
6486 if (fp == NULL)
6487 {
6488 image_error ("Cannot open `%s'", file, Qnil);
4ef0d4d0
KS
6489 return 0;
6490 }
6491 }
7574650a
AS
6492 else if (!STRINGP (specified_data))
6493 {
6494 image_error ("Invalid image data `%s'", specified_data, Qnil);
6495 return 0;
6496 }
4ef0d4d0 6497
5f0cb45a
PE
6498 IF_LINT (mgr->fp = fp);
6499
4ef0d4d0 6500 /* Customize libjpeg's error handling to call my_error_exit when an
df61c790 6501 error is detected. This function will perform a longjmp. */
40bce90b
PE
6502 mgr->cinfo.err = fn_jpeg_std_error (&mgr->pub);
6503 mgr->pub.error_exit = my_error_exit;
0328b6de 6504 if (sys_setjmp (mgr->setjmp_buffer))
4ef0d4d0 6505 {
40bce90b 6506 switch (mgr->failure_code)
4ef0d4d0 6507 {
40bce90b
PE
6508 case MY_JPEG_ERROR_EXIT:
6509 {
6510 char buf[JMSG_LENGTH_MAX];
6511 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6512 image_error ("Error reading JPEG image `%s': %s", img->spec,
6513 build_string (buf));
6514 break;
6515 }
6516
6517 case MY_JPEG_INVALID_IMAGE_SIZE:
6518 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6519 break;
6520
6521 case MY_JPEG_CANNOT_CREATE_X:
6522 break;
4ef0d4d0
KS
6523 }
6524
6525 /* Close the input file and destroy the JPEG object. */
6526 if (fp)
40bce90b
PE
6527 fclose (fp);
6528 fn_jpeg_destroy_decompress (&mgr->cinfo);
4ef0d4d0
KS
6529
6530 /* If we already have an XImage, free that. */
6531 x_destroy_x_image (ximg);
6532
6533 /* Free pixmap and colors. */
6534 x_clear_image (f, img);
4ef0d4d0
KS
6535 return 0;
6536 }
6537
5f0cb45a
PE
6538 /* Silence a bogus diagnostic; see GCC bug 54561. */
6539 IF_LINT (fp = mgr->fp);
6540
4ef0d4d0
KS
6541 /* Create the JPEG decompression object. Let it read from fp.
6542 Read the JPEG image header. */
40bce90b 6543 fn_jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
4ef0d4d0
KS
6544
6545 if (NILP (specified_data))
40bce90b 6546 jpeg_file_src (&mgr->cinfo, fp);
4ef0d4d0 6547 else
40bce90b 6548 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
4ef0d4d0
KS
6549 SBYTES (specified_data));
6550
40bce90b 6551 fn_jpeg_read_header (&mgr->cinfo, 1);
4ef0d4d0
KS
6552
6553 /* Customize decompression so that color quantization will be used.
6554 Start decompression. */
40bce90b
PE
6555 mgr->cinfo.quantize_colors = 1;
6556 fn_jpeg_start_decompress (&mgr->cinfo);
6557 width = img->width = mgr->cinfo.output_width;
6558 height = img->height = mgr->cinfo.output_height;
4ef0d4d0 6559
f1f25b99
CY
6560 if (!check_image_size (f, width, height))
6561 {
40bce90b 6562 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
0328b6de 6563 sys_longjmp (mgr->setjmp_buffer, 1);
f1f25b99
CY
6564 }
6565
4ef0d4d0 6566 /* Create X image and pixmap. */
547c9269 6567 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
40bce90b
PE
6568 {
6569 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
0328b6de 6570 sys_longjmp (mgr->setjmp_buffer, 1);
40bce90b 6571 }
4ef0d4d0
KS
6572
6573 /* Allocate colors. When color quantization is used,
40bce90b
PE
6574 mgr->cinfo.actual_number_of_colors has been set with the number of
6575 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6576 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
4ef0d4d0
KS
6577 No more than 255 colors will be generated. */
6578 {
6579 int i, ir, ig, ib;
6580
40bce90b 6581 if (mgr->cinfo.out_color_components > 2)
4ef0d4d0 6582 ir = 0, ig = 1, ib = 2;
40bce90b 6583 else if (mgr->cinfo.out_color_components > 1)
4ef0d4d0
KS
6584 ir = 0, ig = 1, ib = 0;
6585 else
6586 ir = 0, ig = 0, ib = 0;
6587
6588 /* Use the color table mechanism because it handles colors that
6589 cannot be allocated nicely. Such colors will be replaced with
6590 a default color, and we don't have to care about which colors
6591 can be freed safely, and which can't. */
6592 init_color_table ();
40bce90b 6593 colors = alloca (mgr->cinfo.actual_number_of_colors * sizeof *colors);
4ef0d4d0 6594
40bce90b 6595 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
4ef0d4d0
KS
6596 {
6597 /* Multiply RGB values with 255 because X expects RGB values
6598 in the range 0..0xffff. */
40bce90b
PE
6599 int r = mgr->cinfo.colormap[ir][i] << 8;
6600 int g = mgr->cinfo.colormap[ig][i] << 8;
6601 int b = mgr->cinfo.colormap[ib][i] << 8;
4ef0d4d0
KS
6602 colors[i] = lookup_rgb_color (f, r, g, b);
6603 }
6604
6605#ifdef COLOR_TABLE_SUPPORT
6606 /* Remember those colors actually allocated. */
6607 img->colors = colors_in_color_table (&img->ncolors);
6608 free_color_table ();
6609#endif /* COLOR_TABLE_SUPPORT */
6610 }
6611
6612 /* Read pixels. */
40bce90b
PE
6613 row_stride = width * mgr->cinfo.output_components;
6614 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6615 JPOOL_IMAGE, row_stride, 1);
4ef0d4d0
KS
6616 for (y = 0; y < height; ++y)
6617 {
40bce90b
PE
6618 fn_jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6619 for (x = 0; x < mgr->cinfo.output_width; ++x)
4ef0d4d0
KS
6620 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6621 }
6622
6623 /* Clean up. */
40bce90b
PE
6624 fn_jpeg_finish_decompress (&mgr->cinfo);
6625 fn_jpeg_destroy_decompress (&mgr->cinfo);
4ef0d4d0 6626 if (fp)
40bce90b 6627 fclose (fp);
4ef0d4d0
KS
6628
6629 /* Maybe fill in the background field while we have ximg handy. */
6630 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
6631 /* Casting avoids a GCC warning. */
6632 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0 6633
547c9269
YM
6634 /* Put ximg into the image. */
6635 image_put_x_image (f, img, ximg, 0);
4ef0d4d0
KS
6636 return 1;
6637}
6638
578098f3 6639static bool
40bce90b
PE
6640jpeg_load (struct frame *f, struct image *img)
6641{
6642 struct my_jpeg_error_mgr mgr;
6643 return jpeg_load_body (f, img, &mgr);
6644}
6645
4ef0d4d0
KS
6646#else /* HAVE_JPEG */
6647
edfda783 6648#ifdef HAVE_NS
578098f3 6649static bool
edfda783
AR
6650jpeg_load (struct frame *f, struct image *img)
6651{
ed3751c8
JB
6652 return ns_load_image (f, img,
6653 image_spec_value (img->spec, QCfile, NULL),
6654 image_spec_value (img->spec, QCdata, NULL));
edfda783
AR
6655}
6656#endif /* HAVE_NS */
6657
4ef0d4d0
KS
6658#endif /* !HAVE_JPEG */
6659
6660
6661\f
6662/***********************************************************************
6663 TIFF
6664 ***********************************************************************/
6665
9e2a2647 6666#if defined (HAVE_TIFF) || defined (HAVE_NS)
4ef0d4d0 6667
578098f3
PE
6668static bool tiff_image_p (Lisp_Object object);
6669static bool tiff_load (struct frame *f, struct image *img);
4ef0d4d0
KS
6670
6671/* The symbol `tiff' identifying images of this type. */
6672
955cbe7b 6673static Lisp_Object Qtiff;
4ef0d4d0
KS
6674
6675/* Indices of image specification fields in tiff_format, below. */
6676
6677enum tiff_keyword_index
6678{
6679 TIFF_TYPE,
6680 TIFF_DATA,
6681 TIFF_FILE,
6682 TIFF_ASCENT,
6683 TIFF_MARGIN,
6684 TIFF_RELIEF,
6685 TIFF_ALGORITHM,
6686 TIFF_HEURISTIC_MASK,
6687 TIFF_MASK,
6688 TIFF_BACKGROUND,
58279503 6689 TIFF_INDEX,
4ef0d4d0
KS
6690 TIFF_LAST
6691};
6692
6693/* Vector of image_keyword structures describing the format
6694 of valid user-defined image specifications. */
6695
91433552 6696static const struct image_keyword tiff_format[TIFF_LAST] =
4ef0d4d0
KS
6697{
6698 {":type", IMAGE_SYMBOL_VALUE, 1},
6699 {":data", IMAGE_STRING_VALUE, 0},
6700 {":file", IMAGE_STRING_VALUE, 0},
6701 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 6702 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
6703 {":relief", IMAGE_INTEGER_VALUE, 0},
6704 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6705 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6706 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
58279503
JR
6707 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6708 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
4ef0d4d0
KS
6709};
6710
33d4113c 6711#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 6712static bool init_tiff_functions (void);
bb4d86b4
CY
6713#else
6714#define init_tiff_functions NULL
6715#endif
6716
4ef0d4d0
KS
6717/* Structure describing the image type `tiff'. */
6718
6719static struct image_type tiff_type =
6720{
6721 &Qtiff,
6722 tiff_image_p,
6723 tiff_load,
6724 x_clear_image,
bb4d86b4 6725 init_tiff_functions,
4ef0d4d0
KS
6726 NULL
6727};
6728
578098f3 6729/* Return true if OBJECT is a valid TIFF image specification. */
4ef0d4d0 6730
578098f3 6731static bool
d3da34e0 6732tiff_image_p (Lisp_Object object)
4ef0d4d0
KS
6733{
6734 struct image_keyword fmt[TIFF_LAST];
72af86bd 6735 memcpy (fmt, tiff_format, sizeof fmt);
4ef0d4d0
KS
6736
6737 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6738 return 0;
6739
6740 /* Must specify either the :data or :file keyword. */
6741 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6742}
6743
9e2a2647 6744#endif /* HAVE_TIFF || HAVE_NS */
4ef0d4d0
KS
6745
6746#ifdef HAVE_TIFF
6747
6748#include <tiffio.h>
6749
0fda9b75 6750#ifdef WINDOWSNT
4ef0d4d0
KS
6751
6752/* TIFF library details. */
14beddf4
CY
6753DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6754DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6755DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6756DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
850690cc
JB
6757 TIFFReadWriteProc, TIFFReadWriteProc,
6758 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6759 TIFFMapFileProc, TIFFUnmapFileProc));
14beddf4
CY
6760DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6761DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6762DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6763DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
4ef0d4d0 6764
578098f3 6765static bool
d07ff9db 6766init_tiff_functions (void)
4ef0d4d0
KS
6767{
6768 HMODULE library;
6769
d07ff9db 6770 if (!(library = w32_delayed_load (Qtiff)))
4ef0d4d0
KS
6771 return 0;
6772
6773 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6774 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6775 LOAD_IMGLIB_FN (library, TIFFOpen);
6776 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6777 LOAD_IMGLIB_FN (library, TIFFGetField);
6778 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6779 LOAD_IMGLIB_FN (library, TIFFClose);
58279503 6780 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
4ef0d4d0
KS
6781 return 1;
6782}
6783
6784#else
6785
6786#define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6787#define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6788#define fn_TIFFOpen TIFFOpen
6789#define fn_TIFFClientOpen TIFFClientOpen
6790#define fn_TIFFGetField TIFFGetField
6791#define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6792#define fn_TIFFClose TIFFClose
58279503 6793#define fn_TIFFSetDirectory TIFFSetDirectory
0fda9b75 6794#endif /* WINDOWSNT */
4ef0d4d0
KS
6795
6796
6797/* Reading from a memory buffer for TIFF images Based on the PNG
6798 memory source, but we have to provide a lot of extra functions.
6799 Blah.
6800
6801 We really only need to implement read and seek, but I am not
6802 convinced that the TIFF library is smart enough not to destroy
6803 itself if we only hand it the function pointers we need to
6804 override. */
6805
6806typedef struct
6807{
6808 unsigned char *bytes;
3f791afe
PE
6809 ptrdiff_t len;
6810 ptrdiff_t index;
4ef0d4d0
KS
6811}
6812tiff_memory_source;
6813
3f791afe 6814static tsize_t
d3da34e0 6815tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
4ef0d4d0
KS
6816{
6817 tiff_memory_source *src = (tiff_memory_source *) data;
6818
3f791afe 6819 size = min (size, src->len - src->index);
72af86bd 6820 memcpy (buf, src->bytes + src->index, size);
4ef0d4d0
KS
6821 src->index += size;
6822 return size;
6823}
6824
3f791afe 6825static tsize_t
d3da34e0 6826tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
4ef0d4d0 6827{
3f791afe 6828 return -1;
4ef0d4d0
KS
6829}
6830
6831static toff_t
d3da34e0 6832tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
4ef0d4d0
KS
6833{
6834 tiff_memory_source *src = (tiff_memory_source *) data;
3f791afe 6835 ptrdiff_t idx;
4ef0d4d0
KS
6836
6837 switch (whence)
6838 {
6839 case SEEK_SET: /* Go from beginning of source. */
6840 idx = off;
6841 break;
6842
6843 case SEEK_END: /* Go from end of source. */
6844 idx = src->len + off;
6845 break;
6846
6847 case SEEK_CUR: /* Go from current position. */
6848 idx = src->index + off;
6849 break;
6850
6851 default: /* Invalid `whence'. */
6852 return -1;
6853 }
6854
6855 if (idx > src->len || idx < 0)
6856 return -1;
6857
6858 src->index = idx;
6859 return src->index;
6860}
6861
6862static int
d3da34e0 6863tiff_close_memory (thandle_t data)
4ef0d4d0
KS
6864{
6865 /* NOOP */
6866 return 0;
6867}
6868
6869static int
d3da34e0 6870tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
4ef0d4d0
KS
6871{
6872 /* It is already _IN_ memory. */
6873 return 0;
6874}
6875
6876static void
d3da34e0 6877tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
4ef0d4d0
KS
6878{
6879 /* We don't need to do this. */
6880}
6881
6882static toff_t
d3da34e0 6883tiff_size_of_memory (thandle_t data)
4ef0d4d0
KS
6884{
6885 return ((tiff_memory_source *) data)->len;
6886}
6887
b41c3a35
EZ
6888/* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6889 compiler error compiling tiff_handler, see Bugzilla bug #17406
6890 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6891 this function as external works around that problem. */
6892#if defined (__MINGW32__) && __GNUC__ == 3
6893# define MINGW_STATIC
6894#else
6895# define MINGW_STATIC static
6896#endif
4ef0d4d0 6897
b41c3a35
EZ
6898MINGW_STATIC void
6899tiff_handler (const char *, const char *, const char *, va_list)
13464394 6900 ATTRIBUTE_FORMAT_PRINTF (3, 0);
b41c3a35 6901MINGW_STATIC void
13464394
PE
6902tiff_handler (const char *log_format, const char *title,
6903 const char *format, va_list ap)
6904{
6905 /* doprnt is not suitable here, as TIFF handlers are called from
6906 libtiff and are passed arbitrary printf directives. Instead, use
6907 vsnprintf, taking care to be portable to nonstandard environments
6908 where vsnprintf returns -1 on buffer overflow. Since it's just a
6909 log entry, it's OK to truncate it. */
6910 char buf[4000];
6911 int len = vsnprintf (buf, sizeof buf, format, ap);
6912 add_to_log (log_format, build_string (title),
6913 make_string (buf, max (0, min (len, sizeof buf - 1))));
6914}
b41c3a35 6915#undef MINGW_STATIC
13464394 6916
5e2d4a30
PE
6917static void tiff_error_handler (const char *, const char *, va_list)
6918 ATTRIBUTE_FORMAT_PRINTF (2, 0);
4ef0d4d0 6919static void
d3da34e0 6920tiff_error_handler (const char *title, const char *format, va_list ap)
4ef0d4d0 6921{
13464394 6922 tiff_handler ("TIFF error: %s %s", title, format, ap);
4ef0d4d0
KS
6923}
6924
6925
5e2d4a30
PE
6926static void tiff_warning_handler (const char *, const char *, va_list)
6927 ATTRIBUTE_FORMAT_PRINTF (2, 0);
4ef0d4d0 6928static void
d3da34e0 6929tiff_warning_handler (const char *title, const char *format, va_list ap)
4ef0d4d0 6930{
13464394 6931 tiff_handler ("TIFF warning: %s %s", title, format, ap);
4ef0d4d0
KS
6932}
6933
6934
578098f3 6935/* Load TIFF image IMG for use on frame F. Value is true if
4ef0d4d0
KS
6936 successful. */
6937
578098f3 6938static bool
d3da34e0 6939tiff_load (struct frame *f, struct image *img)
4ef0d4d0
KS
6940{
6941 Lisp_Object file, specified_file;
6942 Lisp_Object specified_data;
6943 TIFF *tiff;
58279503 6944 int width, height, x, y, count;
4ef0d4d0 6945 uint32 *buf;
03d0a109 6946 int rc;
4ef0d4d0 6947 XImagePtr ximg;
4ef0d4d0 6948 tiff_memory_source memsrc;
58279503 6949 Lisp_Object image;
4ef0d4d0
KS
6950
6951 specified_file = image_spec_value (img->spec, QCfile, NULL);
6952 specified_data = image_spec_value (img->spec, QCdata, NULL);
4ef0d4d0 6953
5e2d4a30
PE
6954 fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6955 fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
4ef0d4d0
KS
6956
6957 if (NILP (specified_data))
6958 {
6959 /* Read from a file */
6960 file = x_find_image_file (specified_file);
6961 if (!STRINGP (file))
6962 {
6963 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
6964 return 0;
6965 }
6966
df61c790 6967 /* Try to open the image file. */
b19beacc 6968 tiff = fn_TIFFOpen (SSDATA (file), "r");
4ef0d4d0
KS
6969 if (tiff == NULL)
6970 {
6971 image_error ("Cannot open `%s'", file, Qnil);
4ef0d4d0
KS
6972 return 0;
6973 }
6974 }
6975 else
6976 {
7574650a
AS
6977 if (!STRINGP (specified_data))
6978 {
6979 image_error ("Invalid image data `%s'", specified_data, Qnil);
6980 return 0;
6981 }
6982
4ef0d4d0
KS
6983 /* Memory source! */
6984 memsrc.bytes = SDATA (specified_data);
6985 memsrc.len = SBYTES (specified_data);
6986 memsrc.index = 0;
6987
3082f617 6988 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
3f791afe
PE
6989 tiff_read_from_memory,
6990 tiff_write_from_memory,
df61c790
AS
6991 tiff_seek_in_memory,
6992 tiff_close_memory,
6993 tiff_size_of_memory,
6994 tiff_mmap_memory,
6995 tiff_unmap_memory);
4ef0d4d0
KS
6996
6997 if (!tiff)
6998 {
6999 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
4ef0d4d0
KS
7000 return 0;
7001 }
7002 }
7003
58279503
JR
7004 image = image_spec_value (img->spec, QCindex, NULL);
7005 if (INTEGERP (image))
7006 {
13464394
PE
7007 EMACS_INT ino = XFASTINT (image);
7008 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7009 && fn_TIFFSetDirectory (tiff, ino)))
58279503
JR
7010 {
7011 image_error ("Invalid image number `%s' in image `%s'",
7012 image, img->spec);
7013 fn_TIFFClose (tiff);
58279503
JR
7014 return 0;
7015 }
7016 }
7017
4ef0d4d0
KS
7018 /* Get width and height of the image, and allocate a raster buffer
7019 of width x height 32-bit values. */
7020 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7021 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
f1f25b99
CY
7022
7023 if (!check_image_size (f, width, height))
7024 {
10ea2b82 7025 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
58279503 7026 fn_TIFFClose (tiff);
f1f25b99
CY
7027 return 0;
7028 }
7029
ca4aa935
PE
7030 /* Create the X image and pixmap. */
7031 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
547c9269
YM
7032 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7033 &ximg, 0)))
ca4aa935
PE
7034 {
7035 fn_TIFFClose (tiff);
7036 return 0;
7037 }
7038
23f86fce 7039 buf = xmalloc (sizeof *buf * width * height);
4ef0d4d0
KS
7040
7041 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
58279503
JR
7042
7043 /* Count the number of images in the file. */
03d0a109
PE
7044 for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
7045 continue;
58279503
JR
7046
7047 if (count > 1)
b50691aa
CY
7048 img->lisp_data = Fcons (Qcount,
7049 Fcons (make_number (count),
7050 img->lisp_data));
58279503 7051
4ef0d4d0
KS
7052 fn_TIFFClose (tiff);
7053 if (!rc)
7054 {
7055 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7056 xfree (buf);
4ef0d4d0
KS
7057 return 0;
7058 }
7059
4ef0d4d0
KS
7060 /* Initialize the color table. */
7061 init_color_table ();
7062
7063 /* Process the pixel raster. Origin is in the lower-left corner. */
7064 for (y = 0; y < height; ++y)
7065 {
7066 uint32 *row = buf + y * width;
7067
7068 for (x = 0; x < width; ++x)
7069 {
7070 uint32 abgr = row[x];
7071 int r = TIFFGetR (abgr) << 8;
7072 int g = TIFFGetG (abgr) << 8;
7073 int b = TIFFGetB (abgr) << 8;
7074 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7075 }
7076 }
7077
7078#ifdef COLOR_TABLE_SUPPORT
7079 /* Remember the colors allocated for the image. Free the color table. */
7080 img->colors = colors_in_color_table (&img->ncolors);
7081 free_color_table ();
7082#endif /* COLOR_TABLE_SUPPORT */
7083
7084 img->width = width;
7085 img->height = height;
7086
7087 /* Maybe fill in the background field while we have ximg handy. */
7088 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
7089 /* Casting avoids a GCC warning on W32. */
7090 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0 7091
547c9269
YM
7092 /* Put ximg into the image. */
7093 image_put_x_image (f, img, ximg, 0);
4ef0d4d0
KS
7094 xfree (buf);
7095
4ef0d4d0
KS
7096 return 1;
7097}
7098
7099#else /* HAVE_TIFF */
7100
edfda783 7101#ifdef HAVE_NS
578098f3 7102static bool
edfda783
AR
7103tiff_load (struct frame *f, struct image *img)
7104{
ed3751c8
JB
7105 return ns_load_image (f, img,
7106 image_spec_value (img->spec, QCfile, NULL),
7107 image_spec_value (img->spec, QCdata, NULL));
edfda783
AR
7108}
7109#endif /* HAVE_NS */
7110
4ef0d4d0
KS
7111#endif /* !HAVE_TIFF */
7112
7113
7114\f
7115/***********************************************************************
7116 GIF
7117 ***********************************************************************/
7118
9e2a2647 7119#if defined (HAVE_GIF) || defined (HAVE_NS)
4ef0d4d0 7120
578098f3
PE
7121static bool gif_image_p (Lisp_Object object);
7122static bool gif_load (struct frame *f, struct image *img);
f57e2426 7123static void gif_clear_image (struct frame *f, struct image *img);
4ef0d4d0
KS
7124
7125/* The symbol `gif' identifying images of this type. */
7126
955cbe7b 7127static Lisp_Object Qgif;
4ef0d4d0
KS
7128
7129/* Indices of image specification fields in gif_format, below. */
7130
7131enum gif_keyword_index
7132{
7133 GIF_TYPE,
7134 GIF_DATA,
7135 GIF_FILE,
7136 GIF_ASCENT,
7137 GIF_MARGIN,
7138 GIF_RELIEF,
7139 GIF_ALGORITHM,
7140 GIF_HEURISTIC_MASK,
7141 GIF_MASK,
7142 GIF_IMAGE,
7143 GIF_BACKGROUND,
7144 GIF_LAST
7145};
7146
7147/* Vector of image_keyword structures describing the format
7148 of valid user-defined image specifications. */
7149
91433552 7150static const struct image_keyword gif_format[GIF_LAST] =
4ef0d4d0
KS
7151{
7152 {":type", IMAGE_SYMBOL_VALUE, 1},
7153 {":data", IMAGE_STRING_VALUE, 0},
7154 {":file", IMAGE_STRING_VALUE, 0},
7155 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 7156 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
7157 {":relief", IMAGE_INTEGER_VALUE, 0},
7158 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7159 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7160 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
58279503 7161 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
4ef0d4d0
KS
7162 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7163};
7164
a9e7a9d5 7165#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 7166static bool init_gif_functions (void);
bb4d86b4
CY
7167#else
7168#define init_gif_functions NULL
7169#endif
7170
4ef0d4d0
KS
7171/* Structure describing the image type `gif'. */
7172
7173static struct image_type gif_type =
7174{
7175 &Qgif,
7176 gif_image_p,
7177 gif_load,
6ac3c7bb 7178 gif_clear_image,
bb4d86b4 7179 init_gif_functions,
4ef0d4d0
KS
7180 NULL
7181};
7182
6ac3c7bb
KS
7183/* Free X resources of GIF image IMG which is used on frame F. */
7184
7185static void
d3da34e0 7186gif_clear_image (struct frame *f, struct image *img)
6ac3c7bb 7187{
b50691aa 7188 img->lisp_data = Qnil;
6ac3c7bb
KS
7189 x_clear_image (f, img);
7190}
7191
578098f3 7192/* Return true if OBJECT is a valid GIF image specification. */
4ef0d4d0 7193
578098f3 7194static bool
d3da34e0 7195gif_image_p (Lisp_Object object)
4ef0d4d0
KS
7196{
7197 struct image_keyword fmt[GIF_LAST];
72af86bd 7198 memcpy (fmt, gif_format, sizeof fmt);
4ef0d4d0
KS
7199
7200 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7201 return 0;
7202
7203 /* Must specify either the :data or :file keyword. */
7204 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7205}
7206
9e2a2647 7207#endif /* HAVE_GIF */
4ef0d4d0
KS
7208
7209#ifdef HAVE_GIF
7210
9e2a2647 7211#if defined (HAVE_NTGUI)
2e09fef1
EZ
7212/* winuser.h might define DrawText to DrawTextA or DrawTextW.
7213 Undefine before redefining to avoid a preprocessor warning. */
7214#ifdef DrawText
7215#undef DrawText
7216#endif
4ef0d4d0
KS
7217/* avoid conflict with QuickdrawText.h */
7218#define DrawText gif_DrawText
7219#include <gif_lib.h>
7220#undef DrawText
7221
9e2a2647 7222#else /* HAVE_NTGUI */
4ef0d4d0
KS
7223
7224#include <gif_lib.h>
7225
9e2a2647 7226#endif /* HAVE_NTGUI */
4ef0d4d0
KS
7227
7228
0fda9b75 7229#ifdef WINDOWSNT
4ef0d4d0
KS
7230
7231/* GIF library details. */
14beddf4
CY
7232DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7233DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7234DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7235DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
4ef0d4d0 7236
578098f3 7237static bool
d07ff9db 7238init_gif_functions (void)
4ef0d4d0
KS
7239{
7240 HMODULE library;
7241
d07ff9db 7242 if (!(library = w32_delayed_load (Qgif)))
4ef0d4d0
KS
7243 return 0;
7244
7245 LOAD_IMGLIB_FN (library, DGifCloseFile);
7246 LOAD_IMGLIB_FN (library, DGifSlurp);
7247 LOAD_IMGLIB_FN (library, DGifOpen);
7248 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7249 return 1;
7250}
7251
7252#else
7253
7254#define fn_DGifCloseFile DGifCloseFile
7255#define fn_DGifSlurp DGifSlurp
7256#define fn_DGifOpen DGifOpen
7257#define fn_DGifOpenFileName DGifOpenFileName
7258
0fda9b75 7259#endif /* WINDOWSNT */
4ef0d4d0
KS
7260
7261/* Reading a GIF image from memory
7262 Based on the PNG memory stuff to a certain extent. */
7263
7264typedef struct
7265{
7266 unsigned char *bytes;
3f791afe
PE
7267 ptrdiff_t len;
7268 ptrdiff_t index;
4ef0d4d0
KS
7269}
7270gif_memory_source;
7271
7272/* Make the current memory source available to gif_read_from_memory.
7273 It's done this way because not all versions of libungif support
7274 a UserData field in the GifFileType structure. */
7275static gif_memory_source *current_gif_memory_src;
7276
7277static int
d3da34e0 7278gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
4ef0d4d0
KS
7279{
7280 gif_memory_source *src = current_gif_memory_src;
7281
7282 if (len > src->len - src->index)
7283 return -1;
7284
72af86bd 7285 memcpy (buf, src->bytes + src->index, len);
4ef0d4d0
KS
7286 src->index += len;
7287 return len;
7288}
7289
7290
578098f3 7291/* Load GIF image IMG for use on frame F. Value is true if
4ef0d4d0
KS
7292 successful. */
7293
91433552
DN
7294static const int interlace_start[] = {0, 4, 2, 1};
7295static const int interlace_increment[] = {8, 8, 4, 2};
aca946f3 7296
17c0c952
JD
7297#define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7298
578098f3 7299static bool
d3da34e0 7300gif_load (struct frame *f, struct image *img)
4ef0d4d0 7301{
60002bf5
CY
7302 Lisp_Object file;
7303 int rc, width, height, x, y, i, j;
4ef0d4d0
KS
7304 XImagePtr ximg;
7305 ColorMapObject *gif_color_map;
7306 unsigned long pixel_colors[256];
7307 GifFileType *gif;
4ef0d4d0 7308 gif_memory_source memsrc;
60002bf5
CY
7309 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7310 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7311 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7312 unsigned long bgcolor = 0;
13464394 7313 EMACS_INT idx;
4ef0d4d0
KS
7314
7315 if (NILP (specified_data))
7316 {
7317 file = x_find_image_file (specified_file);
7318 if (!STRINGP (file))
7319 {
7320 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
7321 return 0;
7322 }
7323
df61c790 7324 /* Open the GIF file. */
2037898d 7325 gif = fn_DGifOpenFileName (SSDATA (file));
4ef0d4d0
KS
7326 if (gif == NULL)
7327 {
7328 image_error ("Cannot open `%s'", file, Qnil);
4ef0d4d0
KS
7329 return 0;
7330 }
7331 }
7332 else
7333 {
7574650a
AS
7334 if (!STRINGP (specified_data))
7335 {
7336 image_error ("Invalid image data `%s'", specified_data, Qnil);
7337 return 0;
7338 }
7339
4ef0d4d0
KS
7340 /* Read from memory! */
7341 current_gif_memory_src = &memsrc;
7342 memsrc.bytes = SDATA (specified_data);
7343 memsrc.len = SBYTES (specified_data);
7344 memsrc.index = 0;
7345
df61c790 7346 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
4ef0d4d0
KS
7347 if (!gif)
7348 {
7349 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
4ef0d4d0
KS
7350 return 0;
7351 }
7352 }
7353
f1f25b99
CY
7354 /* Before reading entire contents, check the declared image size. */
7355 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7356 {
10ea2b82 7357 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
f1f25b99 7358 fn_DGifCloseFile (gif);
f1f25b99
CY
7359 return 0;
7360 }
7361
4ef0d4d0
KS
7362 /* Read entire contents. */
7363 rc = fn_DGifSlurp (gif);
60002bf5 7364 if (rc == GIF_ERROR || gif->ImageCount <= 0)
4ef0d4d0
KS
7365 {
7366 image_error ("Error reading `%s'", img->spec, Qnil);
7367 fn_DGifCloseFile (gif);
4ef0d4d0
KS
7368 return 0;
7369 }
7370
60002bf5
CY
7371 /* Which sub-image are we to display? */
7372 {
33290528
PE
7373 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7374 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
60002bf5 7375 if (idx < 0 || idx >= gif->ImageCount)
17c0c952 7376 {
60002bf5 7377 image_error ("Invalid image number `%s' in image `%s'",
33290528 7378 image_number, img->spec);
60002bf5
CY
7379 fn_DGifCloseFile (gif);
7380 return 0;
17c0c952 7381 }
60002bf5 7382 }
17c0c952 7383
e013fb34
CY
7384 width = img->width = gif->SWidth;
7385 height = img->height = gif->SHeight;
0f4aca46 7386
e013fb34
CY
7387 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7388 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
8d903f4e
AS
7389 img->corners[BOT_CORNER]
7390 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7391 img->corners[RIGHT_CORNER]
7392 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
4ef0d4d0 7393
f1f25b99
CY
7394 if (!check_image_size (f, width, height))
7395 {
10ea2b82 7396 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
f1f25b99 7397 fn_DGifCloseFile (gif);
f1f25b99
CY
7398 return 0;
7399 }
7400
44aa9ee6
PE
7401 /* Check that the selected subimages fit. It's not clear whether
7402 the GIF spec requires this, but Emacs can crash if they don't fit. */
7403 for (j = 0; j <= idx; ++j)
7404 {
7405 struct SavedImage *subimage = gif->SavedImages + j;
7406 int subimg_width = subimage->ImageDesc.Width;
7407 int subimg_height = subimage->ImageDesc.Height;
7408 int subimg_top = subimage->ImageDesc.Top;
7409 int subimg_left = subimage->ImageDesc.Left;
7410 if (! (0 <= subimg_width && 0 <= subimg_height
7411 && 0 <= subimg_top && subimg_top <= height - subimg_height
7412 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7413 {
7414 image_error ("Subimage does not fit in image", Qnil, Qnil);
7415 fn_DGifCloseFile (gif);
7416 return 0;
7417 }
7418 }
7419
4ef0d4d0 7420 /* Create the X image and pixmap. */
547c9269 7421 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
4ef0d4d0
KS
7422 {
7423 fn_DGifCloseFile (gif);
4ef0d4d0
KS
7424 return 0;
7425 }
7426
60002bf5
CY
7427 /* Clear the part of the screen image not covered by the image.
7428 Full animated GIF support requires more here (see the gif89 spec,
7429 disposal methods). Let's simply assume that the part not covered
7430 by a sub-image is in the frame's background color. */
6ac3c7bb 7431 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
4ef0d4d0
KS
7432 for (x = 0; x < width; ++x)
7433 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7434
6ac3c7bb 7435 for (y = img->corners[BOT_CORNER]; y < height; ++y)
4ef0d4d0
KS
7436 for (x = 0; x < width; ++x)
7437 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7438
6ac3c7bb 7439 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
4ef0d4d0 7440 {
6ac3c7bb 7441 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
4ef0d4d0 7442 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
6ac3c7bb 7443 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
4ef0d4d0
KS
7444 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7445 }
7446
60002bf5 7447 /* Read the GIF image into the X image. */
4ef0d4d0 7448
60002bf5
CY
7449 /* FIXME: With the current implementation, loading an animated gif
7450 is quadratic in the number of animation frames, since each frame
7451 is a separate struct image. We must provide a way for a single
7452 gif_load call to construct and save all animation frames. */
4ef0d4d0 7453
60002bf5
CY
7454 init_color_table ();
7455 if (STRINGP (specified_bg))
7456 bgcolor = x_alloc_image_color (f, img, specified_bg,
7457 FRAME_BACKGROUND_PIXEL (f));
7458 for (j = 0; j <= idx; ++j)
7459 {
7460 /* We use a local variable `raster' here because RasterBits is a
7461 char *, which invites problems with bytes >= 0x80. */
7462 struct SavedImage *subimage = gif->SavedImages + j;
7463 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7464 int transparency_color_index = -1;
7465 int disposal = 0;
e013fb34
CY
7466 int subimg_width = subimage->ImageDesc.Width;
7467 int subimg_height = subimage->ImageDesc.Height;
7468 int subimg_top = subimage->ImageDesc.Top;
7469 int subimg_left = subimage->ImageDesc.Left;
60002bf5
CY
7470
7471 /* Find the Graphic Control Extension block for this sub-image.
7472 Extract the disposal method and transparency color. */
7473 for (i = 0; i < subimage->ExtensionBlockCount; i++)
4ef0d4d0 7474 {
60002bf5 7475 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
4ef0d4d0 7476
60002bf5
CY
7477 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7478 && extblock->ByteCount == 4
7479 && extblock->Bytes[0] & 1)
4ef0d4d0 7480 {
60002bf5
CY
7481 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7482 to background". Treat any other value like 2. */
7483 disposal = (extblock->Bytes[0] >> 2) & 7;
2547adb1 7484 transparency_color_index = (unsigned char) extblock->Bytes[3];
60002bf5 7485 break;
4ef0d4d0 7486 }
4ef0d4d0 7487 }
60002bf5
CY
7488
7489 /* We can't "keep in place" the first subimage. */
7490 if (j == 0)
7491 disposal = 2;
7492
e013fb34
CY
7493 /* For disposal == 0, the spec says "No disposal specified. The
7494 decoder is not required to take any action." In practice, it
7495 seems we need to treat this like "keep in place", see e.g.
7496 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7497 if (disposal == 0)
7498 disposal = 1;
7499
60002bf5
CY
7500 /* Allocate subimage colors. */
7501 memset (pixel_colors, 0, sizeof pixel_colors);
7502 gif_color_map = subimage->ImageDesc.ColorMap;
7503 if (!gif_color_map)
7504 gif_color_map = gif->SColorMap;
7505
7506 if (gif_color_map)
7507 for (i = 0; i < gif_color_map->ColorCount; ++i)
4ef0d4d0 7508 {
60002bf5
CY
7509 if (transparency_color_index == i)
7510 pixel_colors[i] = STRINGP (specified_bg)
7511 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7512 else
7513 {
7514 int r = gif_color_map->Colors[i].Red << 8;
7515 int g = gif_color_map->Colors[i].Green << 8;
7516 int b = gif_color_map->Colors[i].Blue << 8;
7517 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7518 }
4ef0d4d0 7519 }
60002bf5
CY
7520
7521 /* Apply the pixel values. */
7522 if (gif->SavedImages[j].ImageDesc.Interlace)
7523 {
7524 int row, pass;
7525
7526 for (y = 0, row = interlace_start[0], pass = 0;
e013fb34 7527 y < subimg_height;
60002bf5
CY
7528 y++, row += interlace_increment[pass])
7529 {
a9ebfa0b 7530 while (subimg_height <= row)
60002bf5 7531 {
a9ebfa0b 7532 lint_assume (pass < 3);
60002bf5 7533 row = interlace_start[++pass];
60002bf5
CY
7534 }
7535
e013fb34 7536 for (x = 0; x < subimg_width; x++)
60002bf5 7537 {
e013fb34 7538 int c = raster[y * subimg_width + x];
60002bf5 7539 if (transparency_color_index != c || disposal != 1)
e013fb34
CY
7540 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7541 pixel_colors[c]);
60002bf5
CY
7542 }
7543 }
7544 }
7545 else
7546 {
e013fb34
CY
7547 for (y = 0; y < subimg_height; ++y)
7548 for (x = 0; x < subimg_width; ++x)
60002bf5 7549 {
e013fb34 7550 int c = raster[y * subimg_width + x];
60002bf5 7551 if (transparency_color_index != c || disposal != 1)
e013fb34
CY
7552 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7553 pixel_colors[c]);
60002bf5
CY
7554 }
7555 }
4ef0d4d0
KS
7556 }
7557
60002bf5
CY
7558#ifdef COLOR_TABLE_SUPPORT
7559 img->colors = colors_in_color_table (&img->ncolors);
7560 free_color_table ();
7561#endif /* COLOR_TABLE_SUPPORT */
7562
1546c559
JL
7563 /* Save GIF image extension data for `image-metadata'.
7564 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
b50691aa 7565 img->lisp_data = Qnil;
60002bf5 7566 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
6ac3c7bb 7567 {
13464394 7568 int delay = 0;
60002bf5
CY
7569 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7570 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
6ac3c7bb 7571 /* Append (... FUNCTION "BYTES") */
1100a63c
CY
7572 {
7573 img->lisp_data
7574 = Fcons (make_number (ext->Function),
7575 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7576 img->lisp_data));
7577 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7578 && ext->ByteCount == 4)
7579 {
7580 delay = ext->Bytes[2] << CHAR_BIT;
7581 delay |= ext->Bytes[1];
7582 }
7583 }
6c6f1994 7584 img->lisp_data = list2 (Qextension_data, img->lisp_data);
1100a63c
CY
7585 if (delay)
7586 img->lisp_data
7587 = Fcons (Qdelay,
13464394 7588 Fcons (make_float (delay / 100.0),
1100a63c 7589 img->lisp_data));
6ac3c7bb 7590 }
1100a63c 7591
6ac3c7bb 7592 if (gif->ImageCount > 1)
b50691aa
CY
7593 img->lisp_data = Fcons (Qcount,
7594 Fcons (make_number (gif->ImageCount),
7595 img->lisp_data));
6ac3c7bb 7596
4ef0d4d0
KS
7597 fn_DGifCloseFile (gif);
7598
7599 /* Maybe fill in the background field while we have ximg handy. */
7600 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
7601 /* Casting avoids a GCC warning. */
7602 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0 7603
547c9269
YM
7604 /* Put ximg into the image. */
7605 image_put_x_image (f, img, ximg, 0);
4ef0d4d0 7606
4ef0d4d0
KS
7607 return 1;
7608}
7609
2e09fef1 7610#else /* !HAVE_GIF */
4ef0d4d0 7611
edfda783 7612#ifdef HAVE_NS
578098f3 7613static bool
edfda783
AR
7614gif_load (struct frame *f, struct image *img)
7615{
ed3751c8
JB
7616 return ns_load_image (f, img,
7617 image_spec_value (img->spec, QCfile, NULL),
7618 image_spec_value (img->spec, QCdata, NULL));
edfda783
AR
7619}
7620#endif /* HAVE_NS */
7621
4ef0d4d0
KS
7622#endif /* HAVE_GIF */
7623
7624
b9ed53d5
PE
7625#ifdef HAVE_IMAGEMAGICK
7626
7627/***********************************************************************
7628 ImageMagick
7629***********************************************************************/
7630
7631/* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
7632 safely rounded and clipped to int range. */
7633
7634static int
7635scale_image_size (int size, size_t divisor, size_t multiplier)
7636{
7637 if (divisor != 0)
7638 {
7639 double s = size;
7640 double scaled = s * multiplier / divisor + 0.5;
7641 if (scaled < INT_MAX)
7642 return scaled;
7643 }
7644 return INT_MAX;
7645}
7646
7647/* Compute the desired size of an image with native size WIDTH x HEIGHT.
7648 Use SPEC to deduce the size. Store the desired size into
7649 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
f3f9606c
LMI
7650static void
7651compute_image_size (size_t width, size_t height,
7652 Lisp_Object spec,
7653 int *d_width, int *d_height)
7654{
7655 Lisp_Object value;
7656 int desired_width, desired_height;
7657
7658 /* If width and/or height is set in the display spec assume we want
7659 to scale to those values. If either h or w is unspecified, the
7660 unspecified should be calculated from the specified to preserve
7661 aspect ratio. */
7662 value = image_spec_value (spec, QCwidth, NULL);
b9ed53d5 7663 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
f3f9606c 7664 value = image_spec_value (spec, QCheight, NULL);
b9ed53d5 7665 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
f3f9606c
LMI
7666
7667 if (desired_width == -1)
7668 {
7669 value = image_spec_value (spec, QCmax_width, NULL);
b9ed53d5 7670 if (NATNUMP (value))
f3f9606c 7671 {
b9ed53d5
PE
7672 int max_width = min (XFASTINT (value), INT_MAX);
7673 if (max_width < width)
f3f9606c 7674 {
b9ed53d5
PE
7675 /* The image is wider than :max-width. */
7676 desired_width = max_width;
7677 if (desired_height == -1)
f3f9606c 7678 {
b9ed53d5
PE
7679 desired_height = scale_image_size (desired_width,
7680 width, height);
7681 value = image_spec_value (spec, QCmax_height, NULL);
7682 if (NATNUMP (value))
f3f9606c 7683 {
b9ed53d5
PE
7684 int max_height = min (XFASTINT (value), INT_MAX);
7685 if (max_height < desired_height)
7686 {
7687 desired_height = max_height;
7688 desired_width = scale_image_size (desired_height,
7689 height, width);
7690 }
f3f9606c
LMI
7691 }
7692 }
f3f9606c
LMI
7693 }
7694 }
7695 }
7696
7697 if (desired_height == -1)
7698 {
7699 value = image_spec_value (spec, QCmax_height, NULL);
b9ed53d5
PE
7700 if (NATNUMP (value))
7701 {
7702 int max_height = min (XFASTINT (value), INT_MAX);
7703 if (max_height < height)
7704 desired_height = max_height;
7705 }
f3f9606c
LMI
7706 }
7707
7708 if (desired_width != -1 && desired_height == -1)
7709 /* w known, calculate h. */
b9ed53d5 7710 desired_height = scale_image_size (desired_width, width, height);
f3f9606c
LMI
7711
7712 if (desired_width == -1 && desired_height != -1)
7713 /* h known, calculate w. */
b9ed53d5 7714 desired_width = scale_image_size (desired_height, height, width);
f3f9606c
LMI
7715
7716 *d_width = desired_width;
7717 *d_height = desired_height;
7718}
7719
4b66faf3 7720static Lisp_Object Qimagemagick;
a32d4040 7721
578098f3
PE
7722static bool imagemagick_image_p (Lisp_Object);
7723static bool imagemagick_load (struct frame *, struct image *);
d66c4c7c
CY
7724static void imagemagick_clear_image (struct frame *, struct image *);
7725
a32d4040 7726/* Indices of image specification fields in imagemagick_format. */
3de25479
JV
7727
7728enum imagemagick_keyword_index
4917006b
JV
7729 {
7730 IMAGEMAGICK_TYPE,
7731 IMAGEMAGICK_DATA,
7732 IMAGEMAGICK_FILE,
7733 IMAGEMAGICK_ASCENT,
7734 IMAGEMAGICK_MARGIN,
7735 IMAGEMAGICK_RELIEF,
7736 IMAGEMAGICK_ALGORITHM,
7737 IMAGEMAGICK_HEURISTIC_MASK,
7738 IMAGEMAGICK_MASK,
7739 IMAGEMAGICK_BACKGROUND,
c7f514b5
JV
7740 IMAGEMAGICK_HEIGHT,
7741 IMAGEMAGICK_WIDTH,
f3f9606c
LMI
7742 IMAGEMAGICK_MAX_HEIGHT,
7743 IMAGEMAGICK_MAX_WIDTH,
c7f514b5
JV
7744 IMAGEMAGICK_ROTATION,
7745 IMAGEMAGICK_CROP,
4917006b
JV
7746 IMAGEMAGICK_LAST
7747 };
3de25479
JV
7748
7749/* Vector of image_keyword structures describing the format
7750 of valid user-defined image specifications. */
7751
7752static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
4917006b
JV
7753 {
7754 {":type", IMAGE_SYMBOL_VALUE, 1},
7755 {":data", IMAGE_STRING_VALUE, 0},
7756 {":file", IMAGE_STRING_VALUE, 0},
7757 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 7758 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4917006b
JV
7759 {":relief", IMAGE_INTEGER_VALUE, 0},
7760 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7761 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7762 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
c7f514b5 7763 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7574650a
AS
7764 {":height", IMAGE_INTEGER_VALUE, 0},
7765 {":width", IMAGE_INTEGER_VALUE, 0},
f3f9606c
LMI
7766 {":max-height", IMAGE_INTEGER_VALUE, 0},
7767 {":max-width", IMAGE_INTEGER_VALUE, 0},
7574650a 7768 {":rotation", IMAGE_NUMBER_VALUE, 0},
c7f514b5 7769 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
4917006b 7770 };
a32d4040 7771
33d4113c 7772#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 7773static bool init_imagemagick_functions (void);
bb4d86b4
CY
7774#else
7775#define init_imagemagick_functions NULL
7776#endif
7777
d66c4c7c
CY
7778/* Structure describing the image type for any image handled via
7779 ImageMagick. */
7780
7781static struct image_type imagemagick_type =
7782 {
7783 &Qimagemagick,
7784 imagemagick_image_p,
7785 imagemagick_load,
7786 imagemagick_clear_image,
bb4d86b4 7787 init_imagemagick_functions,
d66c4c7c
CY
7788 NULL
7789 };
7790
3de25479
JV
7791/* Free X resources of imagemagick image IMG which is used on frame F. */
7792
7793static void
4917006b
JV
7794imagemagick_clear_image (struct frame *f,
7795 struct image *img)
3de25479 7796{
3de25479
JV
7797 x_clear_image (f, img);
7798}
7799
578098f3 7800/* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
3de25479
JV
7801 this by calling parse_image_spec and supplying the keywords that
7802 identify the IMAGEMAGICK format. */
7803
578098f3 7804static bool
4917006b 7805imagemagick_image_p (Lisp_Object object)
3de25479
JV
7806{
7807 struct image_keyword fmt[IMAGEMAGICK_LAST];
dbfe4532 7808 memcpy (fmt, imagemagick_format, sizeof fmt);
3de25479
JV
7809
7810 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7811 return 0;
7812
7813 /* Must specify either the :data or :file keyword. */
7814 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7815}
7816
7817/* The GIF library also defines DrawRectangle, but its never used in Emacs.
c7015153 7818 Therefore rename the function so it doesn't collide with ImageMagick. */
3de25479
JV
7819#define DrawRectangle DrawRectangleGif
7820#include <wand/MagickWand.h>
7821
60737f02
PE
7822/* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7823 Emacs seems to work fine with the hidden version, so unhide it. */
7824#include <magick/version.h>
7825#if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7826extern WandExport void PixelGetMagickColor (const PixelWand *,
7827 MagickPixelPacket *);
7828#endif
7829
d1d7b339
JL
7830/* Log ImageMagick error message.
7831 Useful when a ImageMagick function returns the status `MagickFalse'. */
7832
7833static void
7834imagemagick_error (MagickWand *wand)
7835{
7836 char *description;
7837 ExceptionType severity;
7838
7839 description = MagickGetException (wand, &severity);
7840 image_error ("ImageMagick error: %s",
1130ecfc 7841 build_string (description),
d1d7b339
JL
7842 Qnil);
7843 description = (char *) MagickRelinquishMemory (description);
7844}
7845
d66c4c7c
CY
7846/* Helper function for imagemagick_load, which does the actual loading
7847 given contents and size, apart from frame and image structures,
7848 passed from imagemagick_load. Uses librimagemagick to do most of
7849 the image processing.
3de25479 7850
d66c4c7c
CY
7851 F is a pointer to the Emacs frame; IMG to the image structure to
7852 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
7853 be parsed; SIZE is the number of bytes of data; and FILENAME is
7854 either the file name or the image data.
3de25479 7855
578098f3 7856 Return true if successful. */
3de25479 7857
578098f3 7858static bool
d66c4c7c
CY
7859imagemagick_load_image (struct frame *f, struct image *img,
7860 unsigned char *contents, unsigned int size,
33290528 7861 char *filename)
3de25479 7862{
1b9b4cf4 7863 size_t width, height;
d66c4c7c 7864 MagickBooleanType status;
3de25479 7865 XImagePtr ximg;
1b9b4cf4
CY
7866 int x, y;
7867 MagickWand *image_wand;
7868 MagickWand *ping_wand;
3de25479 7869 PixelIterator *iterator;
1b9b4cf4 7870 PixelWand **pixels, *bg_wand = NULL;
3de25479 7871 MagickPixelPacket pixel;
4917006b 7872 Lisp_Object image;
7574650a 7873 Lisp_Object value;
33290528 7874 Lisp_Object crop;
13464394 7875 EMACS_INT ino;
4917006b
JV
7876 int desired_width, desired_height;
7877 double rotation;
7574650a 7878 int pixelwidth;
7574650a 7879
a32d4040
CY
7880 /* Handle image index for image types who can contain more than one image.
7881 Interface :index is same as for GIF. First we "ping" the image to see how
7882 many sub-images it contains. Pinging is faster than loading the image to
7883 find out things about it. */
f853f599 7884
a32d4040 7885 /* Initialize the imagemagick environment. */
f853f599 7886 MagickWandGenesis ();
3de25479
JV
7887 image = image_spec_value (img->spec, QCindex, NULL);
7888 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7574650a 7889 ping_wand = NewMagickWand ();
d1d7b339 7890 /* MagickSetResolution (ping_wand, 2, 2); (Bug#10112) */
fa4fdb5c 7891
1b9b4cf4
CY
7892 status = filename
7893 ? MagickPingImage (ping_wand, filename)
7894 : MagickPingImageBlob (ping_wand, contents, size);
7574650a 7895
d1d7b339
JL
7896 if (status == MagickFalse)
7897 {
7898 imagemagick_error (ping_wand);
7899 DestroyMagickWand (ping_wand);
7900 return 0;
7901 }
fa4fdb5c 7902
1b9b4cf4 7903 if (ino < 0 || ino >= MagickGetNumberImages (ping_wand))
7574650a
AS
7904 {
7905 image_error ("Invalid image number `%s' in image `%s'",
7906 image, img->spec);
7907 DestroyMagickWand (ping_wand);
7908 return 0;
f3700365 7909 }
431dab04 7910
5e617bc2 7911 if (MagickGetNumberImages (ping_wand) > 1)
b50691aa 7912 img->lisp_data =
d2a2d277 7913 Fcons (Qcount,
7574650a 7914 Fcons (make_number (MagickGetNumberImages (ping_wand)),
b50691aa 7915 img->lisp_data));
f3700365
JV
7916
7917 DestroyMagickWand (ping_wand);
f853f599 7918
d66c4c7c 7919 /* Now we know how many images are inside the file. If it's not a
1b9b4cf4 7920 bundle, the number is one. Load the image data. */
f3700365 7921
1b9b4cf4 7922 image_wand = NewMagickWand ();
f3700365 7923
1b9b4cf4
CY
7924 if ((filename
7925 ? MagickReadImage (image_wand, filename)
7926 : MagickReadImageBlob (image_wand, contents, size))
7927 == MagickFalse)
f3700365 7928 {
1b9b4cf4
CY
7929 imagemagick_error (image_wand);
7930 goto imagemagick_error;
f3700365 7931 }
f853f599 7932
1b9b4cf4
CY
7933 /* Retrieve the frame's background color, for use later. */
7934 {
7935 XColor bgcolor;
7936 Lisp_Object specified_bg;
7937
7938 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7939 if (!STRINGP (specified_bg)
7940 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
7941 {
7942#ifndef HAVE_NS
7943 bgcolor.pixel = FRAME_BACKGROUND_PIXEL (f);
7944 x_query_color (f, &bgcolor);
7945#else
7946 ns_query_color (FRAME_BACKGROUND_COLOR (f), &bgcolor, 1);
7947#endif
7948 }
7949
7950 bg_wand = NewPixelWand ();
7951 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
7952 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
7953 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
7954 }
7955
f3f9606c
LMI
7956 compute_image_size (MagickGetImageWidth (image_wand),
7957 MagickGetImageHeight (image_wand),
7958 img->spec, &desired_width, &desired_height);
bdf6a35d 7959
a32d4040 7960 if (desired_width != -1 && desired_height != -1)
4917006b 7961 {
7574650a
AS
7962 status = MagickScaleImage (image_wand, desired_width, desired_height);
7963 if (status == MagickFalse)
7964 {
7965 image_error ("Imagemagick scale failed", Qnil, Qnil);
d1d7b339 7966 imagemagick_error (image_wand);
7574650a
AS
7967 goto imagemagick_error;
7968 }
3de25479 7969 }
3de25479 7970
f3700365 7971 /* crop behaves similar to image slicing in Emacs but is more memory
7574650a
AS
7972 efficient. */
7973 crop = image_spec_value (img->spec, QCcrop, NULL);
7974
13464394 7975 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7574650a 7976 {
a32d4040
CY
7977 /* After some testing, it seems MagickCropImage is the fastest crop
7978 function in ImageMagick. This crop function seems to do less copying
7979 than the alternatives, but it still reads the entire image into memory
13464394 7980 before cropping, which is apparently difficult to avoid when using
a32d4040 7981 imagemagick. */
13464394 7982 size_t crop_width = XINT (XCAR (crop));
7574650a 7983 crop = XCDR (crop);
13464394 7984 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7574650a 7985 {
13464394 7986 size_t crop_height = XINT (XCAR (crop));
7574650a 7987 crop = XCDR (crop);
13464394 7988 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7574650a 7989 {
13464394 7990 ssize_t crop_x = XINT (XCAR (crop));
7574650a 7991 crop = XCDR (crop);
13464394 7992 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7574650a 7993 {
13464394
PE
7994 ssize_t crop_y = XINT (XCAR (crop));
7995 MagickCropImage (image_wand, crop_width, crop_height,
7996 crop_x, crop_y);
7574650a
AS
7997 }
7998 }
7999 }
8000 }
8001
d2a2d277
JV
8002 /* Furthermore :rotation. we need background color and angle for
8003 rotation. */
3de25479 8004 /*
d2a2d277
JV
8005 TODO background handling for rotation specified_bg =
8006 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
549a73b9 8007 (specified_bg). */
4917006b
JV
8008 value = image_spec_value (img->spec, QCrotation, NULL);
8009 if (FLOATP (value))
8010 {
3de25479 8011 rotation = extract_float (value);
1b9b4cf4 8012 status = MagickRotateImage (image_wand, bg_wand, rotation);
4917006b
JV
8013 if (status == MagickFalse)
8014 {
8015 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
d1d7b339 8016 imagemagick_error (image_wand);
4917006b
JV
8017 goto imagemagick_error;
8018 }
3de25479 8019 }
7574650a 8020
1b9b4cf4
CY
8021 /* Set the canvas background color to the frame or specified
8022 background, and flatten the image. Note: as of ImageMagick
8023 6.6.0, SVG image transparency is not handled properly
8024 (e.g. etc/images/splash.svg shows a white background always). */
8025 {
8026 MagickWand *new_wand;
8027 MagickSetImageBackgroundColor (image_wand, bg_wand);
0e25d334 8028#ifdef HAVE_MAGICKMERGEIMAGELAYERS
1b9b4cf4 8029 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
0e25d334
CY
8030#else
8031 new_wand = MagickFlattenImages (image_wand);
8032#endif
1b9b4cf4
CY
8033 DestroyMagickWand (image_wand);
8034 image_wand = new_wand;
8035 }
8036
84ac6f9d
PE
8037 /* Finally we are done manipulating the image. Figure out the
8038 resulting width/height and transfer ownership to Emacs. */
8039 height = MagickGetImageHeight (image_wand);
8040 width = MagickGetImageWidth (image_wand);
8041
3f791afe
PE
8042 if (! (width <= INT_MAX && height <= INT_MAX
8043 && check_image_size (f, width, height)))
3de25479
JV
8044 {
8045 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8046 goto imagemagick_error;
8047 }
7574650a 8048
3de25479
JV
8049 /* We can now get a valid pixel buffer from the imagemagick file, if all
8050 went ok. */
3de25479
JV
8051
8052 init_color_table ();
af008560 8053
cf7a0de6 8054#if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
0e25d334
CY
8055 if (imagemagick_render_type != 0)
8056 {
8057 /* Magicexportimage is normally faster than pixelpushing. This
8058 method is also well tested. Some aspects of this method are
8059 ad-hoc and needs to be more researched. */
8060 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8061 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8062 /* Try to create a x pixmap to hold the imagemagick pixmap. */
547c9269
YM
8063 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8064 &ximg, 0))
0e25d334
CY
8065 {
8066#ifdef COLOR_TABLE_SUPPORT
8067 free_color_table ();
8068#endif
8069 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8070 goto imagemagick_error;
8071 }
8072
8073 /* Oddly, the below code doesn't seem to work:*/
8074 /* switch(ximg->bitmap_unit){ */
8075 /* case 8: */
8076 /* pixelwidth=CharPixel; */
8077 /* break; */
8078 /* case 16: */
8079 /* pixelwidth=ShortPixel; */
8080 /* break; */
8081 /* case 32: */
8082 /* pixelwidth=LongPixel; */
8083 /* break; */
8084 /* } */
8085 /*
8086 Here im just guessing the format of the bitmap.
8087 happens to work fine for:
8088 - bw djvu images
8089 on rgb display.
8090 seems about 3 times as fast as pixel pushing(not carefully measured)
8091 */
8092 pixelwidth = CharPixel; /*??? TODO figure out*/
8093 MagickExportImagePixels (image_wand, 0, 0, width, height,
8094 exportdepth, pixelwidth, ximg->data);
8095 }
8096 else
8097#endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
4917006b 8098 {
13464394
PE
8099 size_t image_height;
8100
4917006b 8101 /* Try to create a x pixmap to hold the imagemagick pixmap. */
547c9269
YM
8102 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8103 &ximg, 0))
4917006b 8104 {
466cbae9
AS
8105#ifdef COLOR_TABLE_SUPPORT
8106 free_color_table ();
8107#endif
5e617bc2 8108 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
4917006b
JV
8109 goto imagemagick_error;
8110 }
7574650a 8111
53964682 8112 /* Copy imagemagick image to x with primitive yet robust pixel
4917006b 8113 pusher loop. This has been tested a lot with many different
549a73b9 8114 images. */
7574650a 8115
4917006b
JV
8116 /* Copy pixels from the imagemagick image structure to the x image map. */
8117 iterator = NewPixelIterator (image_wand);
7574650a 8118 if (iterator == (PixelIterator *) NULL)
4917006b 8119 {
466cbae9
AS
8120#ifdef COLOR_TABLE_SUPPORT
8121 free_color_table ();
8122#endif
8123 x_destroy_x_image (ximg);
d2a2d277
JV
8124 image_error ("Imagemagick pixel iterator creation failed",
8125 Qnil, Qnil);
3de25479 8126 goto imagemagick_error;
4917006b
JV
8127 }
8128
13464394
PE
8129 image_height = MagickGetImageHeight (image_wand);
8130 for (y = 0; y < image_height; y++)
4917006b
JV
8131 {
8132 pixels = PixelGetNextIteratorRow (iterator, &width);
7574650a 8133 if (pixels == (PixelWand **) NULL)
4917006b
JV
8134 break;
8135 for (x = 0; x < (long) width; x++)
8136 {
8137 PixelGetMagickColor (pixels[x], &pixel);
d2a2d277
JV
8138 XPutPixel (ximg, x, y,
8139 lookup_rgb_color (f,
8140 pixel.red,
8141 pixel.green,
8142 pixel.blue));
4917006b
JV
8143 }
8144 }
8145 DestroyPixelIterator (iterator);
3de25479 8146 }
3ed42149 8147
3de25479
JV
8148#ifdef COLOR_TABLE_SUPPORT
8149 /* Remember colors allocated for this image. */
8150 img->colors = colors_in_color_table (&img->ncolors);
8151 free_color_table ();
8152#endif /* COLOR_TABLE_SUPPORT */
8153
3de25479
JV
8154 img->width = width;
8155 img->height = height;
8156
547c9269
YM
8157 /* Put ximg into the image. */
8158 image_put_x_image (f, img, ximg, 0);
3de25479 8159
f3700365 8160 /* Final cleanup. image_wand should be the only resource left. */
3de25479 8161 DestroyMagickWand (image_wand);
1b9b4cf4
CY
8162 if (bg_wand) DestroyPixelWand (bg_wand);
8163
03d32f1b 8164 /* `MagickWandTerminus' terminates the imagemagick environment. */
f853f599 8165 MagickWandTerminus ();
3de25479
JV
8166
8167 return 1;
8168
8169 imagemagick_error:
466cbae9 8170 DestroyMagickWand (image_wand);
1b9b4cf4
CY
8171 if (bg_wand) DestroyPixelWand (bg_wand);
8172
f853f599 8173 MagickWandTerminus ();
3de25479
JV
8174 /* TODO more cleanup. */
8175 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
3de25479
JV
8176 return 0;
8177}
8178
4917006b 8179
578098f3 8180/* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
4917006b
JV
8181 successful. this function will go into the imagemagick_type structure, and
8182 the prototype thus needs to be compatible with that structure. */
8183
578098f3 8184static bool
d66c4c7c 8185imagemagick_load (struct frame *f, struct image *img)
4917006b 8186{
578098f3 8187 bool success_p = 0;
4917006b
JV
8188 Lisp_Object file_name;
8189
8190 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8191 file_name = image_spec_value (img->spec, QCfile, NULL);
8192 if (STRINGP (file_name))
8193 {
8194 Lisp_Object file;
4917006b
JV
8195
8196 file = x_find_image_file (file_name);
4917006b
JV
8197 if (!STRINGP (file))
8198 {
8199 image_error ("Cannot find image file `%s'", file_name, Qnil);
4917006b
JV
8200 return 0;
8201 }
33290528 8202 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
4917006b
JV
8203 }
8204 /* Else its not a file, its a lisp object. Load the image from a
8205 lisp object rather than a file. */
8206 else
8207 {
8208 Lisp_Object data;
8209
8210 data = image_spec_value (img->spec, QCdata, NULL);
7574650a
AS
8211 if (!STRINGP (data))
8212 {
8213 image_error ("Invalid image data `%s'", data, Qnil);
8214 return 0;
8215 }
d2a2d277
JV
8216 success_p = imagemagick_load_image (f, img, SDATA (data),
8217 SBYTES (data), NULL);
4917006b
JV
8218 }
8219
8220 return success_p;
8221}
8222
a7ca3326 8223DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
d66c4c7c
CY
8224 doc: /* Return a list of image types supported by ImageMagick.
8225Each entry in this list is a symbol named after an ImageMagick format
8226tag. See the ImageMagick manual for a list of ImageMagick formats and
8227their descriptions (http://www.imagemagick.org/script/formats.php).
dd605cc4 8228You can also try the shell command: `identify -list format'.
d66c4c7c
CY
8229
8230Note that ImageMagick recognizes many file-types that Emacs does not
32d72c2f
GM
8231recognize as images, such as C. See `imagemagick-types-enable'
8232and `imagemagick-types-inhibit'. */)
a8101f66 8233 (void)
3de25479
JV
8234{
8235 Lisp_Object typelist = Qnil;
1ab0dee5 8236 size_t numf = 0;
3de25479 8237 ExceptionInfo ex;
2277de02 8238 char **imtypes;
3f791afe 8239 size_t i;
3de25479 8240 Lisp_Object Qimagemagicktype;
2277de02
JD
8241
8242 GetExceptionInfo(&ex);
8243 imtypes = GetMagickList ("*", &numf, &ex);
8244 DestroyExceptionInfo(&ex);
8245
4917006b
JV
8246 for (i = 0; i < numf; i++)
8247 {
8248 Qimagemagicktype = intern (imtypes[i]);
f3700365
JV
8249 typelist = Fcons (Qimagemagicktype, typelist);
8250 }
d1d7b339 8251 return Fnreverse (typelist);
3de25479 8252}
7574650a 8253
3de25479
JV
8254#endif /* defined (HAVE_IMAGEMAGICK) */
8255
8256
4ef0d4d0 8257\f
4ab27a43
GM
8258/***********************************************************************
8259 SVG
8260 ***********************************************************************/
8261
8262#if defined (HAVE_RSVG)
8263
8264/* Function prototypes. */
8265
578098f3
PE
8266static bool svg_image_p (Lisp_Object object);
8267static bool svg_load (struct frame *f, struct image *img);
4ab27a43 8268
578098f3
PE
8269static bool svg_load_image (struct frame *, struct image *,
8270 unsigned char *, ptrdiff_t);
4ab27a43
GM
8271
8272/* The symbol `svg' identifying images of this type. */
8273
4b66faf3 8274static Lisp_Object Qsvg;
4ab27a43
GM
8275
8276/* Indices of image specification fields in svg_format, below. */
8277
8278enum svg_keyword_index
8279{
8280 SVG_TYPE,
8281 SVG_DATA,
8282 SVG_FILE,
8283 SVG_ASCENT,
8284 SVG_MARGIN,
8285 SVG_RELIEF,
8286 SVG_ALGORITHM,
8287 SVG_HEURISTIC_MASK,
8288 SVG_MASK,
8289 SVG_BACKGROUND,
8290 SVG_LAST
8291};
8292
8293/* Vector of image_keyword structures describing the format
8294 of valid user-defined image specifications. */
8295
91433552 8296static const struct image_keyword svg_format[SVG_LAST] =
4ab27a43
GM
8297{
8298 {":type", IMAGE_SYMBOL_VALUE, 1},
8299 {":data", IMAGE_STRING_VALUE, 0},
8300 {":file", IMAGE_STRING_VALUE, 0},
8301 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 8302 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ab27a43
GM
8303 {":relief", IMAGE_INTEGER_VALUE, 0},
8304 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8305 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8306 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8307 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8308};
8309
33d4113c 8310#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 8311static bool init_svg_functions (void);
bb4d86b4
CY
8312#else
8313#define init_svg_functions NULL
8314#endif
8315
4ab27a43
GM
8316/* Structure describing the image type `svg'. Its the same type of
8317 structure defined for all image formats, handled by emacs image
8318 functions. See struct image_type in dispextern.h. */
8319
8320static struct image_type svg_type =
8321{
4ab27a43 8322 &Qsvg,
4ab27a43 8323 svg_image_p,
4ab27a43 8324 svg_load,
4ab27a43 8325 x_clear_image,
bb4d86b4 8326 init_svg_functions,
c21e6151 8327 NULL
4ab27a43
GM
8328};
8329
8330
578098f3 8331/* Return true if OBJECT is a valid SVG image specification. Do
4ab27a43
GM
8332 this by calling parse_image_spec and supplying the keywords that
8333 identify the SVG format. */
8334
578098f3 8335static bool
d3da34e0 8336svg_image_p (Lisp_Object object)
4ab27a43
GM
8337{
8338 struct image_keyword fmt[SVG_LAST];
72af86bd 8339 memcpy (fmt, svg_format, sizeof fmt);
4ab27a43
GM
8340
8341 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8342 return 0;
8343
8344 /* Must specify either the :data or :file keyword. */
8345 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8346}
8347
8348#include <librsvg/rsvg.h>
8349
0fda9b75 8350#ifdef WINDOWSNT
5fc9fdeb
JR
8351
8352/* SVG library functions. */
40693bba 8353DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new, (void));
8354DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions, (RsvgHandle *, RsvgDimensionData *));
8355DEF_IMGLIB_FN (gboolean, rsvg_handle_write, (RsvgHandle *, const guchar *, gsize, GError **));
8356DEF_IMGLIB_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8357DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8358DEF_IMGLIB_FN (void *, rsvg_handle_set_size_callback, (RsvgHandle *, RsvgSizeFunc, gpointer, GDestroyNotify));
8359
8360DEF_IMGLIB_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8361DEF_IMGLIB_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8362DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8363DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8364DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8365DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8366DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8367DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8368
8369DEF_IMGLIB_FN (void, g_type_init, (void));
8370DEF_IMGLIB_FN (void, g_object_unref, (gpointer));
121ab1cd 8371DEF_IMGLIB_FN (void, g_error_free, (GError *));
5fc9fdeb 8372
df23bf08 8373Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
5fc9fdeb 8374
578098f3 8375static bool
d07ff9db 8376init_svg_functions (void)
5fc9fdeb 8377{
df23bf08 8378 HMODULE library, gdklib, glib, gobject;
5fc9fdeb 8379
d07ff9db
CY
8380 if (!(glib = w32_delayed_load (Qglib))
8381 || !(gobject = w32_delayed_load (Qgobject))
8382 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
8383 || !(library = w32_delayed_load (Qsvg)))
5fc9fdeb
JR
8384 return 0;
8385
8386 LOAD_IMGLIB_FN (library, rsvg_handle_new);
e025c9c2 8387 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
5fc9fdeb
JR
8388 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8389 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8390 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
5fc9fdeb
JR
8391
8392 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8393 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8394 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8395 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8396 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8397 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8398 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8399 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8400
df23bf08
JR
8401 LOAD_IMGLIB_FN (gobject, g_type_init);
8402 LOAD_IMGLIB_FN (gobject, g_object_unref);
5fc9fdeb 8403 LOAD_IMGLIB_FN (glib, g_error_free);
df23bf08 8404
5fc9fdeb
JR
8405 return 1;
8406}
4ab27a43 8407
5fc9fdeb
JR
8408#else
8409/* The following aliases for library functions allow dynamic loading
8410 to be used on some platforms. */
4ab27a43 8411#define fn_rsvg_handle_new rsvg_handle_new
e025c9c2 8412#define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
4ab27a43
GM
8413#define fn_rsvg_handle_write rsvg_handle_write
8414#define fn_rsvg_handle_close rsvg_handle_close
8415#define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
4ab27a43 8416
5fc9fdeb
JR
8417#define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8418#define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8419#define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8420#define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8421#define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8422#define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8423#define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
4ab27a43
GM
8424#define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8425
5fc9fdeb
JR
8426#define fn_g_type_init g_type_init
8427#define fn_g_object_unref g_object_unref
8428#define fn_g_error_free g_error_free
0fda9b75 8429#endif /* !WINDOWSNT */
4ab27a43 8430
578098f3
PE
8431/* Load SVG image IMG for use on frame F. Value is true if
8432 successful. */
4ab27a43 8433
578098f3 8434static bool
d3da34e0 8435svg_load (struct frame *f, struct image *img)
4ab27a43 8436{
578098f3 8437 bool success_p = 0;
4ab27a43
GM
8438 Lisp_Object file_name;
8439
8440 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8441 file_name = image_spec_value (img->spec, QCfile, NULL);
8442 if (STRINGP (file_name))
8443 {
8444 Lisp_Object file;
8445 unsigned char *contents;
dd52fcea 8446 ptrdiff_t size;
4ab27a43
GM
8447
8448 file = x_find_image_file (file_name);
4ab27a43 8449 if (!STRINGP (file))
c21e6151
YM
8450 {
8451 image_error ("Cannot find image file `%s'", file_name, Qnil);
c21e6151
YM
8452 return 0;
8453 }
8454
4ab27a43 8455 /* Read the entire file into memory. */
33290528 8456 contents = slurp_file (SSDATA (file), &size);
4ab27a43 8457 if (contents == NULL)
c21e6151
YM
8458 {
8459 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
c21e6151
YM
8460 return 0;
8461 }
4ab27a43 8462 /* If the file was slurped into memory properly, parse it. */
c21e6151 8463 success_p = svg_load_image (f, img, contents, size);
4ab27a43 8464 xfree (contents);
4ab27a43
GM
8465 }
8466 /* Else its not a file, its a lisp object. Load the image from a
8467 lisp object rather than a file. */
8468 else
8469 {
8470 Lisp_Object data;
8471
8472 data = image_spec_value (img->spec, QCdata, NULL);
7574650a
AS
8473 if (!STRINGP (data))
8474 {
8475 image_error ("Invalid image data `%s'", data, Qnil);
8476 return 0;
8477 }
4ab27a43
GM
8478 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8479 }
8480
8481 return success_p;
8482}
8483
bbe6f2aa
JB
8484/* svg_load_image is a helper function for svg_load, which does the
8485 actual loading given contents and size, apart from frame and image
8486 structures, passed from svg_load.
4ab27a43 8487
bbe6f2aa 8488 Uses librsvg to do most of the image processing.
c21e6151 8489
578098f3
PE
8490 Returns true when successful. */
8491static bool
d3da34e0
JB
8492svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8493 struct image *img, /* Pointer to emacs image structure. */
8494 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
dd52fcea 8495 ptrdiff_t size) /* Size of data in bytes. */
4ab27a43
GM
8496{
8497 RsvgHandle *rsvg_handle;
e025c9c2 8498 RsvgDimensionData dimension_data;
33290528 8499 GError *err = NULL;
4ab27a43
GM
8500 GdkPixbuf *pixbuf;
8501 int width;
8502 int height;
8503 const guint8 *pixels;
8504 int rowstride;
8505 XImagePtr ximg;
c21e6151 8506 Lisp_Object specified_bg;
4ab27a43
GM
8507 XColor background;
8508 int x;
8509 int y;
8510
8511 /* g_type_init is a glib function that must be called prior to using
8512 gnome type library functions. */
5fc9fdeb 8513 fn_g_type_init ();
4ab27a43 8514 /* Make a handle to a new rsvg object. */
df61c790 8515 rsvg_handle = fn_rsvg_handle_new ();
4ab27a43
GM
8516
8517 /* Parse the contents argument and fill in the rsvg_handle. */
33290528
PE
8518 fn_rsvg_handle_write (rsvg_handle, contents, size, &err);
8519 if (err) goto rsvg_error;
4ab27a43
GM
8520
8521 /* The parsing is complete, rsvg_handle is ready to used, close it
8522 for further writes. */
33290528
PE
8523 fn_rsvg_handle_close (rsvg_handle, &err);
8524 if (err) goto rsvg_error;
e025c9c2
CY
8525
8526 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8527 if (! check_image_size (f, dimension_data.width, dimension_data.height))
10ea2b82
JR
8528 {
8529 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8530 goto rsvg_error;
8531 }
b2996e57 8532
4ab27a43
GM
8533 /* We can now get a valid pixel buffer from the svg file, if all
8534 went ok. */
df61c790 8535 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
e025c9c2
CY
8536 if (!pixbuf) goto rsvg_error;
8537 fn_g_object_unref (rsvg_handle);
4ab27a43
GM
8538
8539 /* Extract some meta data from the svg handle. */
8540 width = fn_gdk_pixbuf_get_width (pixbuf);
8541 height = fn_gdk_pixbuf_get_height (pixbuf);
df61c790 8542 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
4ab27a43
GM
8543 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8544
8545 /* Validate the svg meta data. */
8546 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8547 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8548 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8549 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8550
8551 /* Try to create a x pixmap to hold the svg pixmap. */
547c9269 8552 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
c21e6151 8553 {
5fc9fdeb 8554 fn_g_object_unref (pixbuf);
c21e6151
YM
8555 return 0;
8556 }
4ab27a43
GM
8557
8558 init_color_table ();
8559
c21e6151
YM
8560 /* Handle alpha channel by combining the image with a background
8561 color. */
8562 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8d3c4e79 8563 if (!STRINGP (specified_bg)
33290528 8564 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
c21e6151 8565 {
d7e008d0 8566#ifndef HAVE_NS
c21e6151
YM
8567 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8568 x_query_color (f, &background);
d7e008d0 8569#else
ed3751c8 8570 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
d7e008d0 8571#endif
c21e6151 8572 }
4ab27a43 8573
8d3c4e79
CY
8574 /* SVG pixmaps specify transparency in the last byte, so right
8575 shift 8 bits to get rid of it, since emacs doesn't support
8576 transparency. */
8577 background.red >>= 8;
8578 background.green >>= 8;
8579 background.blue >>= 8;
8580
4ab27a43
GM
8581 /* This loop handles opacity values, since Emacs assumes
8582 non-transparent images. Each pixel must be "flattened" by
bbe6f2aa
JB
8583 calculating the resulting color, given the transparency of the
8584 pixel, and the image background color. */
4ab27a43
GM
8585 for (y = 0; y < height; ++y)
8586 {
8587 for (x = 0; x < width; ++x)
8588 {
13464394
PE
8589 int red;
8590 int green;
8591 int blue;
8592 int opacity;
4ab27a43
GM
8593
8594 red = *pixels++;
8595 green = *pixels++;
8596 blue = *pixels++;
8597 opacity = *pixels++;
8598
8599 red = ((red * opacity)
8600 + (background.red * ((1 << 8) - opacity)));
8601 green = ((green * opacity)
8602 + (background.green * ((1 << 8) - opacity)));
8603 blue = ((blue * opacity)
8604 + (background.blue * ((1 << 8) - opacity)));
8605
8606 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8607 }
8608
8609 pixels += rowstride - 4 * width;
8610 }
8611
8612#ifdef COLOR_TABLE_SUPPORT
8613 /* Remember colors allocated for this image. */
8614 img->colors = colors_in_color_table (&img->ncolors);
8615 free_color_table ();
8616#endif /* COLOR_TABLE_SUPPORT */
8617
5fc9fdeb 8618 fn_g_object_unref (pixbuf);
4ab27a43 8619
c21e6151
YM
8620 img->width = width;
8621 img->height = height;
8622
8623 /* Maybe fill in the background field while we have ximg handy.
8624 Casting avoids a GCC warning. */
8625 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8626
547c9269
YM
8627 /* Put ximg into the image. */
8628 image_put_x_image (f, img, ximg, 0);
4ab27a43 8629
4ab27a43
GM
8630 return 1;
8631
8632 rsvg_error:
e025c9c2 8633 fn_g_object_unref (rsvg_handle);
4ab27a43
GM
8634 /* FIXME: Use error->message so the user knows what is the actual
8635 problem with the image. */
8636 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
33290528 8637 fn_g_error_free (err);
4ab27a43
GM
8638 return 0;
8639}
8640
8641#endif /* defined (HAVE_RSVG) */
8642
8643
8644
4ef0d4d0
KS
8645\f
8646/***********************************************************************
8647 Ghostscript
8648 ***********************************************************************/
8649
8650#ifdef HAVE_X_WINDOWS
8651#define HAVE_GHOSTSCRIPT 1
8652#endif /* HAVE_X_WINDOWS */
8653
4ef0d4d0
KS
8654#ifdef HAVE_GHOSTSCRIPT
8655
578098f3
PE
8656static bool gs_image_p (Lisp_Object object);
8657static bool gs_load (struct frame *f, struct image *img);
f57e2426 8658static void gs_clear_image (struct frame *f, struct image *img);
4ef0d4d0
KS
8659
8660/* Keyword symbols. */
8661
955cbe7b 8662static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
4ef0d4d0
KS
8663
8664/* Indices of image specification fields in gs_format, below. */
8665
8666enum gs_keyword_index
8667{
8668 GS_TYPE,
8669 GS_PT_WIDTH,
8670 GS_PT_HEIGHT,
8671 GS_FILE,
8672 GS_LOADER,
8673 GS_BOUNDING_BOX,
8674 GS_ASCENT,
8675 GS_MARGIN,
8676 GS_RELIEF,
8677 GS_ALGORITHM,
8678 GS_HEURISTIC_MASK,
8679 GS_MASK,
8680 GS_BACKGROUND,
8681 GS_LAST
8682};
8683
8684/* Vector of image_keyword structures describing the format
8685 of valid user-defined image specifications. */
8686
91433552 8687static const struct image_keyword gs_format[GS_LAST] =
4ef0d4d0
KS
8688{
8689 {":type", IMAGE_SYMBOL_VALUE, 1},
8690 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8691 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8692 {":file", IMAGE_STRING_VALUE, 1},
8693 {":loader", IMAGE_FUNCTION_VALUE, 0},
8694 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8695 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 8696 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
8697 {":relief", IMAGE_INTEGER_VALUE, 0},
8698 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8699 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8700 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8701 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8702};
8703
8704/* Structure describing the image type `ghostscript'. */
8705
8706static struct image_type gs_type =
8707{
8708 &Qpostscript,
8709 gs_image_p,
8710 gs_load,
8711 gs_clear_image,
d07ff9db 8712 NULL,
4ef0d4d0
KS
8713 NULL
8714};
8715
8716
8717/* Free X resources of Ghostscript image IMG which is used on frame F. */
8718
8719static void
d3da34e0 8720gs_clear_image (struct frame *f, struct image *img)
4ef0d4d0 8721{
4ef0d4d0
KS
8722 x_clear_image (f, img);
8723}
8724
8725
578098f3 8726/* Return true if OBJECT is a valid Ghostscript image
4ef0d4d0
KS
8727 specification. */
8728
578098f3 8729static bool
d3da34e0 8730gs_image_p (Lisp_Object object)
4ef0d4d0
KS
8731{
8732 struct image_keyword fmt[GS_LAST];
8733 Lisp_Object tem;
8734 int i;
8735
72af86bd 8736 memcpy (fmt, gs_format, sizeof fmt);
4ef0d4d0
KS
8737
8738 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8739 return 0;
8740
8741 /* Bounding box must be a list or vector containing 4 integers. */
8742 tem = fmt[GS_BOUNDING_BOX].value;
8743 if (CONSP (tem))
8744 {
8745 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8746 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8747 return 0;
8748 if (!NILP (tem))
8749 return 0;
8750 }
8751 else if (VECTORP (tem))
8752 {
77b37c05 8753 if (ASIZE (tem) != 4)
4ef0d4d0
KS
8754 return 0;
8755 for (i = 0; i < 4; ++i)
28be1ada 8756 if (!INTEGERP (AREF (tem, i)))
4ef0d4d0
KS
8757 return 0;
8758 }
8759 else
8760 return 0;
8761
8762 return 1;
8763}
8764
8765
578098f3 8766/* Load Ghostscript image IMG for use on frame F. Value is true
4ef0d4d0
KS
8767 if successful. */
8768
578098f3 8769static bool
d3da34e0 8770gs_load (struct frame *f, struct image *img)
4ef0d4d0 8771{
13464394
PE
8772 uprintmax_t printnum1, printnum2;
8773 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
4ef0d4d0 8774 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
4ef0d4d0
KS
8775 Lisp_Object frame;
8776 double in_width, in_height;
8777 Lisp_Object pixel_colors = Qnil;
8778
8779 /* Compute pixel size of pixmap needed from the given size in the
8780 image specification. Sizes in the specification are in pt. 1 pt
8781 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8782 info. */
8783 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
7574650a 8784 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
42143acd 8785 in_width *= FRAME_RES_X (f);
4ef0d4d0 8786 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
7574650a 8787 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
42143acd 8788 in_height *= FRAME_RES_Y (f);
4ef0d4d0 8789
13464394
PE
8790 if (! (in_width <= INT_MAX && in_height <= INT_MAX
8791 && check_image_size (f, in_width, in_height)))
f1f25b99 8792 {
10ea2b82 8793 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
f1f25b99
CY
8794 return 0;
8795 }
13464394
PE
8796 img->width = in_width;
8797 img->height = in_height;
f1f25b99 8798
4ef0d4d0 8799 /* Create the pixmap. */
a54e2c05 8800 eassert (img->pixmap == NO_PIXMAP);
4ef0d4d0 8801
ca4aa935
PE
8802 if (x_check_image_size (0, img->width, img->height))
8803 {
8804 /* Only W32 version did BLOCK_INPUT here. ++kfs */
4d7e6e51 8805 block_input ();
ca4aa935
PE
8806 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8807 img->width, img->height,
8808 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
4d7e6e51 8809 unblock_input ();
ca4aa935 8810 }
4ef0d4d0
KS
8811
8812 if (!img->pixmap)
8813 {
8814 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8815 return 0;
8816 }
8817
8818 /* Call the loader to fill the pixmap. It returns a process object
8819 if successful. We do not record_unwind_protect here because
8820 other places in redisplay like calling window scroll functions
8821 don't either. Let the Lisp loader use `unwind-protect' instead. */
13464394
PE
8822 printnum1 = FRAME_X_WINDOW (f);
8823 printnum2 = img->pixmap;
620f13b0 8824 window_and_pixmap_id
a8290ec3 8825 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
4ef0d4d0 8826
13464394
PE
8827 printnum1 = FRAME_FOREGROUND_PIXEL (f);
8828 printnum2 = FRAME_BACKGROUND_PIXEL (f);
a8290ec3
DA
8829 pixel_colors
8830 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
4ef0d4d0
KS
8831
8832 XSETFRAME (frame, f);
8833 loader = image_spec_value (img->spec, QCloader, NULL);
8834 if (NILP (loader))
8835 loader = intern ("gs-load-image");
8836
b50691aa
CY
8837 img->lisp_data = call6 (loader, frame, img->spec,
8838 make_number (img->width),
8839 make_number (img->height),
8840 window_and_pixmap_id,
8841 pixel_colors);
8842 return PROCESSP (img->lisp_data);
4ef0d4d0
KS
8843}
8844
8845
8846/* Kill the Ghostscript process that was started to fill PIXMAP on
8847 frame F. Called from XTread_socket when receiving an event
8848 telling Emacs that Ghostscript has finished drawing. */
8849
8850void
d3da34e0 8851x_kill_gs_process (Pixmap pixmap, struct frame *f)
4ef0d4d0 8852{
354884c4 8853 struct image_cache *c = FRAME_IMAGE_CACHE (f);
13464394
PE
8854 int class;
8855 ptrdiff_t i;
4ef0d4d0
KS
8856 struct image *img;
8857
8858 /* Find the image containing PIXMAP. */
8859 for (i = 0; i < c->used; ++i)
8860 if (c->images[i]->pixmap == pixmap)
8861 break;
8862
8863 /* Should someone in between have cleared the image cache, for
8864 instance, give up. */
8865 if (i == c->used)
8866 return;
8867
8868 /* Kill the GS process. We should have found PIXMAP in the image
8869 cache and its image should contain a process object. */
8870 img = c->images[i];
a54e2c05 8871 eassert (PROCESSP (img->lisp_data));
b50691aa
CY
8872 Fkill_process (img->lisp_data, Qnil);
8873 img->lisp_data = Qnil;
4ef0d4d0
KS
8874
8875#if defined (HAVE_X_WINDOWS)
8876
8877 /* On displays with a mutable colormap, figure out the colors
8878 allocated for the image by looking at the pixels of an XImage for
8879 img->pixmap. */
8880 class = FRAME_X_VISUAL (f)->class;
8881 if (class != StaticColor && class != StaticGray && class != TrueColor)
8882 {
8883 XImagePtr ximg;
8884
4d7e6e51 8885 block_input ();
4ef0d4d0
KS
8886
8887 /* Try to get an XImage for img->pixmep. */
8888 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8889 0, 0, img->width, img->height, ~0, ZPixmap);
8890 if (ximg)
8891 {
8892 int x, y;
8893
8894 /* Initialize the color table. */
8895 init_color_table ();
8896
8897 /* For each pixel of the image, look its color up in the
8898 color table. After having done so, the color table will
8899 contain an entry for each color used by the image. */
8900 for (y = 0; y < img->height; ++y)
8901 for (x = 0; x < img->width; ++x)
8902 {
8903 unsigned long pixel = XGetPixel (ximg, x, y);
8904 lookup_pixel_color (f, pixel);
8905 }
8906
8907 /* Record colors in the image. Free color table and XImage. */
8908#ifdef COLOR_TABLE_SUPPORT
8909 img->colors = colors_in_color_table (&img->ncolors);
8910 free_color_table ();
8911#endif
8912 XDestroyImage (ximg);
8913
8914#if 0 /* This doesn't seem to be the case. If we free the colors
8915 here, we get a BadAccess later in x_clear_image when
8916 freeing the colors. */
8917 /* We have allocated colors once, but Ghostscript has also
8918 allocated colors on behalf of us. So, to get the
8919 reference counts right, free them once. */
8920 if (img->ncolors)
8921 x_free_colors (f, img->colors, img->ncolors);
8922#endif
8923 }
8924 else
8925 image_error ("Cannot get X image of `%s'; colors will not be freed",
8926 img->spec, Qnil);
8927
4d7e6e51 8928 unblock_input ();
4ef0d4d0
KS
8929 }
8930#endif /* HAVE_X_WINDOWS */
8931
8932 /* Now that we have the pixmap, compute mask and transform the
8933 image if requested. */
4d7e6e51 8934 block_input ();
4ef0d4d0 8935 postprocess_image (f, img);
4d7e6e51 8936 unblock_input ();
4ef0d4d0
KS
8937}
8938
8939#endif /* HAVE_GHOSTSCRIPT */
8940
8941\f
8942/***********************************************************************
8943 Tests
8944 ***********************************************************************/
8945
e509cfa6 8946#ifdef GLYPH_DEBUG
4ef0d4d0 8947
a7ca3326 8948DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
4ef0d4d0 8949 doc: /* Value is non-nil if SPEC is a valid image specification. */)
5842a27b 8950 (Lisp_Object spec)
4ef0d4d0
KS
8951{
8952 return valid_image_p (spec) ? Qt : Qnil;
8953}
8954
8955
a7ca3326 8956DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
5842a27b 8957 (Lisp_Object spec)
4ef0d4d0 8958{
13464394 8959 ptrdiff_t id = -1;
4ef0d4d0
KS
8960
8961 if (valid_image_p (spec))
8962 id = lookup_image (SELECTED_FRAME (), spec);
8963
8964 debug_print (spec);
8965 return make_number (id);
8966}
8967
e509cfa6 8968#endif /* GLYPH_DEBUG */
4ef0d4d0
KS
8969
8970
8971/***********************************************************************
8972 Initialization
8973 ***********************************************************************/
8974
d07ff9db 8975DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
0855eb52
JB
8976 doc: /* Initialize image library implementing image type TYPE.
8977Return non-nil if TYPE is a supported image type.
8978
d07ff9db
CY
8979If image libraries are loaded dynamically (currently only the case on
8980MS-Windows), load the library for TYPE if it is not yet loaded, using
8981the library file(s) specified by `dynamic-library-alist'. */)
8982 (Lisp_Object type)
0855eb52 8983{
d07ff9db 8984 return lookup_image_type (type) ? Qt : Qnil;
bb4d86b4 8985}
0855eb52 8986
bb4d86b4 8987/* Look up image type TYPE, and return a pointer to its image_type
d07ff9db 8988 structure. Return 0 if TYPE is not a known image type. */
bb4d86b4
CY
8989
8990static struct image_type *
d07ff9db 8991lookup_image_type (Lisp_Object type)
bb4d86b4 8992{
2f142cc5 8993 /* Types pbm and xbm are built-in and always available. */
bb4d86b4 8994 if (EQ (type, Qpbm))
d07ff9db 8995 return define_image_type (&pbm_type);
bb4d86b4
CY
8996
8997 if (EQ (type, Qxbm))
d07ff9db 8998 return define_image_type (&xbm_type);
2f142cc5 8999
9e2a2647 9000#if defined (HAVE_XPM) || defined (HAVE_NS)
0855eb52 9001 if (EQ (type, Qxpm))
d07ff9db 9002 return define_image_type (&xpm_type);
0855eb52
JB
9003#endif
9004
9e2a2647 9005#if defined (HAVE_JPEG) || defined (HAVE_NS)
0855eb52 9006 if (EQ (type, Qjpeg))
d07ff9db 9007 return define_image_type (&jpeg_type);
0855eb52
JB
9008#endif
9009
9e2a2647 9010#if defined (HAVE_TIFF) || defined (HAVE_NS)
0855eb52 9011 if (EQ (type, Qtiff))
d07ff9db 9012 return define_image_type (&tiff_type);
0855eb52
JB
9013#endif
9014
9e2a2647 9015#if defined (HAVE_GIF) || defined (HAVE_NS)
0855eb52 9016 if (EQ (type, Qgif))
d07ff9db 9017 return define_image_type (&gif_type);
0855eb52
JB
9018#endif
9019
9e2a2647 9020#if defined (HAVE_PNG) || defined (HAVE_NS)
0855eb52 9021 if (EQ (type, Qpng))
d07ff9db 9022 return define_image_type (&png_type);
0855eb52
JB
9023#endif
9024
4ab27a43
GM
9025#if defined (HAVE_RSVG)
9026 if (EQ (type, Qsvg))
d07ff9db 9027 return define_image_type (&svg_type);
4ab27a43 9028#endif
c21e6151 9029
3de25479 9030#if defined (HAVE_IMAGEMAGICK)
7574650a 9031 if (EQ (type, Qimagemagick))
d07ff9db 9032 return define_image_type (&imagemagick_type);
3de25479
JV
9033#endif
9034
0855eb52
JB
9035#ifdef HAVE_GHOSTSCRIPT
9036 if (EQ (type, Qpostscript))
d07ff9db 9037 return define_image_type (&gs_type);
0855eb52
JB
9038#endif
9039
bb4d86b4 9040 return NULL;
0855eb52
JB
9041}
9042
aa15c6bb
JB
9043/* Reset image_types before dumping.
9044 Called from Fdump_emacs. */
9045
9046void
9047reset_image_types (void)
9048{
9049 while (image_types)
9050 {
9051 struct image_type *next = image_types->next;
9052 xfree (image_types);
9053 image_types = next;
9054 }
0855eb52
JB
9055}
9056
4ef0d4d0 9057void
d3da34e0 9058syms_of_image (void)
4ef0d4d0 9059{
aa15c6bb 9060 /* Initialize this only once; it will be reset before dumping. */
6e6fc3fd
RS
9061 image_types = NULL;
9062
91af3942 9063 /* Must be defined now because we're going to update it below, while
0855eb52 9064 defining the supported image types. */
29208e82 9065 DEFVAR_LISP ("image-types", Vimage_types,
0855eb52 9066 doc: /* List of potentially supported image types.
bbe6f2aa 9067Each element of the list is a symbol for an image type, like 'jpeg or 'png.
0855eb52
JB
9068To check whether it is really supported, use `image-type-available-p'. */);
9069 Vimage_types = Qnil;
9070
29208e82 9071 DEFVAR_LISP ("max-image-size", Vmax_image_size,
7df4765a
KS
9072 doc: /* Maximum size of images.
9073Emacs will not load an image into memory if its pixel width or
9074pixel height exceeds this limit.
9075
9076If the value is an integer, it directly specifies the maximum
9077image height and width, measured in pixels. If it is a floating
9078point number, it specifies the maximum image height and width
9079as a ratio to the frame height and width. If the value is
9080non-numeric, there is no explicit limit on the size of images. */);
f1f25b99
CY
9081 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9082
1100a63c
CY
9083 DEFSYM (Qcount, "count");
9084 DEFSYM (Qextension_data, "extension-data");
9085 DEFSYM (Qdelay, "delay");
9086
9087 DEFSYM (QCascent, ":ascent");
9088 DEFSYM (QCmargin, ":margin");
9089 DEFSYM (QCrelief, ":relief");
9090 DEFSYM (QCconversion, ":conversion");
9091 DEFSYM (QCcolor_symbols, ":color-symbols");
9092 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9093 DEFSYM (QCindex, ":index");
9094 DEFSYM (QCgeometry, ":geometry");
9095 DEFSYM (QCcrop, ":crop");
9096 DEFSYM (QCrotation, ":rotation");
9097 DEFSYM (QCmatrix, ":matrix");
9098 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9099 DEFSYM (QCmask, ":mask");
9100
9101 DEFSYM (Qlaplace, "laplace");
9102 DEFSYM (Qemboss, "emboss");
9103 DEFSYM (Qedge_detection, "edge-detection");
9104 DEFSYM (Qheuristic, "heuristic");
9105
9106 DEFSYM (Qpostscript, "postscript");
f3f9606c
LMI
9107 DEFSYM (QCmax_width, ":max-width");
9108 DEFSYM (QCmax_height, ":max-height");
4ef0d4d0 9109#ifdef HAVE_GHOSTSCRIPT
5fc9fdeb 9110 ADD_IMAGE_TYPE (Qpostscript);
1100a63c
CY
9111 DEFSYM (QCloader, ":loader");
9112 DEFSYM (QCbounding_box, ":bounding-box");
9113 DEFSYM (QCpt_width, ":pt-width");
9114 DEFSYM (QCpt_height, ":pt-height");
4ef0d4d0
KS
9115#endif /* HAVE_GHOSTSCRIPT */
9116
5be1c984 9117#ifdef HAVE_NTGUI
1100a63c 9118 DEFSYM (Qlibpng_version, "libpng-version");
0514b4be 9119 Fset (Qlibpng_version,
5be1c984 9120#if HAVE_PNG
0514b4be 9121 make_number (PNG_LIBPNG_VER)
5be1c984 9122#else
0514b4be 9123 make_number (-1)
5be1c984 9124#endif
0514b4be 9125 );
5be1c984
EZ
9126#endif
9127
bb4d86b4
CY
9128 DEFSYM (Qpbm, "pbm");
9129 ADD_IMAGE_TYPE (Qpbm);
9130
9131 DEFSYM (Qxbm, "xbm");
9132 ADD_IMAGE_TYPE (Qxbm);
9133
9e2a2647 9134#if defined (HAVE_XPM) || defined (HAVE_NS)
1100a63c 9135 DEFSYM (Qxpm, "xpm");
5fc9fdeb 9136 ADD_IMAGE_TYPE (Qxpm);
4ef0d4d0
KS
9137#endif
9138
9e2a2647 9139#if defined (HAVE_JPEG) || defined (HAVE_NS)
1100a63c 9140 DEFSYM (Qjpeg, "jpeg");
5fc9fdeb 9141 ADD_IMAGE_TYPE (Qjpeg);
4ef0d4d0
KS
9142#endif
9143
9e2a2647 9144#if defined (HAVE_TIFF) || defined (HAVE_NS)
1100a63c 9145 DEFSYM (Qtiff, "tiff");
5fc9fdeb 9146 ADD_IMAGE_TYPE (Qtiff);
4ef0d4d0
KS
9147#endif
9148
9e2a2647 9149#if defined (HAVE_GIF) || defined (HAVE_NS)
1100a63c 9150 DEFSYM (Qgif, "gif");
5fc9fdeb 9151 ADD_IMAGE_TYPE (Qgif);
4ef0d4d0
KS
9152#endif
9153
9e2a2647 9154#if defined (HAVE_PNG) || defined (HAVE_NS)
1100a63c 9155 DEFSYM (Qpng, "png");
5fc9fdeb 9156 ADD_IMAGE_TYPE (Qpng);
4ef0d4d0
KS
9157#endif
9158
3de25479 9159#if defined (HAVE_IMAGEMAGICK)
1100a63c 9160 DEFSYM (Qimagemagick, "imagemagick");
3de25479
JV
9161 ADD_IMAGE_TYPE (Qimagemagick);
9162#endif
7574650a 9163
4ab27a43 9164#if defined (HAVE_RSVG)
1100a63c 9165 DEFSYM (Qsvg, "svg");
5fc9fdeb
JR
9166 ADD_IMAGE_TYPE (Qsvg);
9167#ifdef HAVE_NTGUI
df23bf08 9168 /* Other libraries used directly by svg code. */
1100a63c
CY
9169 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9170 DEFSYM (Qglib, "glib");
9171 DEFSYM (Qgobject, "gobject");
5fc9fdeb
JR
9172#endif /* HAVE_NTGUI */
9173#endif /* HAVE_RSVG */
4ab27a43 9174
0855eb52 9175 defsubr (&Sinit_image_library);
7574650a 9176#ifdef HAVE_IMAGEMAGICK
3de25479 9177 defsubr (&Simagemagick_types);
7574650a 9178#endif
4ef0d4d0 9179 defsubr (&Sclear_image_cache);
110683ad 9180 defsubr (&Simage_flush);
4ef0d4d0
KS
9181 defsubr (&Simage_size);
9182 defsubr (&Simage_mask_p);
1546c559 9183 defsubr (&Simage_metadata);
4ef0d4d0 9184
e509cfa6 9185#ifdef GLYPH_DEBUG
4ef0d4d0
KS
9186 defsubr (&Simagep);
9187 defsubr (&Slookup_image);
9188#endif
9189
29208e82 9190 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
4ef0d4d0 9191 doc: /* Non-nil means always draw a cross over disabled images.
3046a84b 9192Disabled images are those having a `:conversion disabled' property.
4ef0d4d0
KS
9193A cross is always drawn on black & white displays. */);
9194 cross_disabled_images = 0;
9195
29208e82 9196 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
4ef0d4d0
KS
9197 doc: /* List of directories to search for window system bitmap files. */);
9198 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
9199
29208e82 9200 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
98fe5161
CY
9201 doc: /* Maximum time after which images are removed from the cache.
9202When an image has not been displayed this many seconds, Emacs
9203automatically removes it from the image cache. If the cache contains
9204a large number of images, the actual eviction time may be shorter.
9205The value can also be nil, meaning the cache is never cleared.
9206
9207The function `clear-image-cache' disregards this variable. */);
9208 Vimage_cache_eviction_delay = make_number (300);
7574650a 9209#ifdef HAVE_IMAGEMAGICK
af008560
GM
9210 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9211 doc: /* Integer indicating which ImageMagick rendering method to use.
9212The options are:
9213 0 -- the default method (pixel pushing)
9214 1 -- a newer method ("MagickExportImagePixels") that may perform
9215 better (speed etc) in some cases, but has not been as thoroughly
9216 tested with Emacs as the default method. This method requires
9217 ImageMagick version 6.4.6 (approximately) or later.
9218*/);
9219 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9220 imagemagick_render_type = 0;
7574650a 9221#endif
4ef0d4d0 9222
4ef0d4d0 9223}