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