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