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