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