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