merge trunk
[bpt/emacs.git] / src / image.c
CommitLineData
4ef0d4d0 1/* Functions for image support on window system.
32d72c2f 2
ab422c4d 3Copyright (C) 1989, 1992-2013 Free Software Foundation, Inc.
4ef0d4d0
KS
4
5This file is part of GNU Emacs.
6
9ec0b715 7GNU Emacs is free software: you can redistribute it and/or modify
4ef0d4d0 8it under the terms of the GNU General Public License as published by
9ec0b715
GM
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
4ef0d4d0
KS
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
9ec0b715 18along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
4ef0d4d0
KS
19
20#include <config.h>
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 70
9ecf6403
YM
71#define PIX_MASK_RETAIN 0
72#define PIX_MASK_DRAW 1
4ef0d4d0
KS
73#endif /* HAVE_X_WINDOWS */
74
4ef0d4d0 75#ifdef HAVE_NTGUI
a9e7a9d5
PE
76
77/* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
78#ifdef WINDOWSNT
0fda9b75 79# include "w32.h"
a9e7a9d5
PE
80#endif
81
4ef0d4d0
KS
82/* W32_TODO : Color tables on W32. */
83#undef COLOR_TABLE_SUPPORT
84
85typedef struct w32_bitmap_record Bitmap_Record;
5e617bc2 86#define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
4ef0d4d0 87#define NO_PIXMAP 0
4ef0d4d0 88
9ecf6403
YM
89#define PIX_MASK_RETAIN 0
90#define PIX_MASK_DRAW 1
4ef0d4d0 91
4ef0d4d0
KS
92#define x_defined_color w32_defined_color
93#define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
8b7d0a16 94
5be1c984
EZ
95/* Version of libpng that we were compiled with, or -1 if no PNG
96 support was compiled in. This is tested by w32-win.el to correctly
97 set up the alist used to search for PNG libraries. */
98Lisp_Object Qlibpng_version;
4ef0d4d0
KS
99#endif /* HAVE_NTGUI */
100
edfda783 101#ifdef HAVE_NS
edfda783
AR
102#undef COLOR_TABLE_SUPPORT
103
104typedef struct ns_bitmap_record Bitmap_Record;
105
5e617bc2 106#define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
edfda783
AR
107#define NO_PIXMAP 0
108
edfda783
AR
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
bad98418 157/* Use with images created by ns_image_for_XPM. */
edfda783
AR
158unsigned long
159XGetPixel (XImagePtr ximage, int x, int y)
160{
ed3751c8 161 return ns_get_pixel (ximage, x, y);
edfda783
AR
162}
163
bad98418
PE
164/* Use with images created by ns_image_for_XPM; alpha set to 1;
165 pixel is assumed to be in RGB form. */
edfda783
AR
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)
62aba0d4 189ptrdiff_t
0766b489 190x_bitmap_pixmap (FRAME_PTR f, ptrdiff_t id)
4ef0d4d0 191{
f6cfbd8f 192 /* HAVE_NTGUI needs the explicit cast here. */
62aba0d4 193 return (ptrdiff_t) 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 562static void x_build_heuristic_mask (struct frame *, struct image *,
36a305a7 563 Lisp_Object);
0fda9b75
DC
564#ifdef WINDOWSNT
565extern Lisp_Object Vlibrary_cache;
0855eb52 566#define CACHE_IMAGE_TYPE(type, status) \
0898ca10 567 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
84d358f0
JB
568#else
569#define CACHE_IMAGE_TYPE(type, status)
a9e7a9d5 570#endif
0855eb52
JB
571
572#define ADD_IMAGE_TYPE(type) \
573 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
4ef0d4d0
KS
574
575/* Define a new image type from TYPE. This adds a copy of TYPE to
0855eb52 576 image_types and caches the loading status of TYPE. */
4ef0d4d0 577
bb4d86b4 578static struct image_type *
d07ff9db 579define_image_type (struct image_type *type)
4ef0d4d0 580{
bb4d86b4
CY
581 struct image_type *p = NULL;
582 Lisp_Object target_type = *type->type;
578098f3 583 bool type_valid = 1;
0855eb52 584
4d7e6e51 585 block_input ();
bb4d86b4
CY
586
587 for (p = image_types; p; p = p->next)
588 if (EQ (*p->type, target_type))
589 goto done;
590
591 if (type->init)
0855eb52 592 {
a9e7a9d5 593#if defined HAVE_NTGUI && defined WINDOWSNT
bb4d86b4
CY
594 /* If we failed to load the library before, don't try again. */
595 Lisp_Object tested = Fassq (target_type, Vlibrary_cache);
596 if (CONSP (tested) && NILP (XCDR (tested)))
597 type_valid = 0;
598 else
599#endif
600 {
d07ff9db 601 type_valid = type->init ();
bb4d86b4
CY
602 CACHE_IMAGE_TYPE (target_type, type_valid ? Qt : Qnil);
603 }
604 }
09c01941 605
bb4d86b4 606 if (type_valid)
0855eb52
JB
607 {
608 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
609 The initialized data segment is read-only. */
09c01941 610 p = xmalloc (sizeof *p);
ae1d87e2 611 *p = *type;
0855eb52
JB
612 p->next = image_types;
613 image_types = p;
0855eb52
JB
614 }
615
bb4d86b4 616 done:
4d7e6e51 617 unblock_input ();
bb4d86b4 618 return p;
4ef0d4d0
KS
619}
620
621
578098f3 622/* Value is true if OBJECT is a valid Lisp image specification. A
4ef0d4d0
KS
623 valid image specification is a list whose car is the symbol
624 `image', and whose rest is a property list. The property list must
625 contain a value for key `:type'. That value must be the name of a
626 supported image type. The rest of the property list depends on the
627 image type. */
628
578098f3 629bool
d3da34e0 630valid_image_p (Lisp_Object object)
4ef0d4d0 631{
578098f3 632 bool valid_p = 0;
4ef0d4d0
KS
633
634 if (IMAGEP (object))
635 {
636 Lisp_Object tem;
637
638 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
639 if (EQ (XCAR (tem), QCtype))
640 {
641 tem = XCDR (tem);
642 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
643 {
644 struct image_type *type;
645 type = lookup_image_type (XCAR (tem));
646 if (type)
647 valid_p = type->valid_p (object);
648 }
649
650 break;
651 }
652 }
653
654 return valid_p;
655}
656
657
658/* Log error message with format string FORMAT and argument ARG.
659 Signaling an error, e.g. when an image cannot be loaded, is not a
660 good idea because this would interrupt redisplay, and the error
661 message display would lead to another redisplay. This function
662 therefore simply displays a message. */
663
664static void
675e2c69 665image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
4ef0d4d0
KS
666{
667 add_to_log (format, arg1, arg2);
668}
669
670
671\f
672/***********************************************************************
673 Image specifications
674 ***********************************************************************/
675
676enum image_value_type
677{
678 IMAGE_DONT_CHECK_VALUE_TYPE,
679 IMAGE_STRING_VALUE,
680 IMAGE_STRING_OR_NIL_VALUE,
681 IMAGE_SYMBOL_VALUE,
682 IMAGE_POSITIVE_INTEGER_VALUE,
c4a07a4c 683 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
4ef0d4d0
KS
684 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
685 IMAGE_ASCENT_VALUE,
686 IMAGE_INTEGER_VALUE,
687 IMAGE_FUNCTION_VALUE,
688 IMAGE_NUMBER_VALUE,
689 IMAGE_BOOL_VALUE
690};
691
692/* Structure used when parsing image specifications. */
693
694struct image_keyword
695{
696 /* Name of keyword. */
675e2c69 697 const char *name;
4ef0d4d0
KS
698
699 /* The type of value allowed. */
700 enum image_value_type type;
701
578098f3
PE
702 /* True means key must be present. */
703 bool mandatory_p;
4ef0d4d0
KS
704
705 /* Used to recognize duplicate keywords in a property list. */
706 int count;
707
708 /* The value that was found. */
709 Lisp_Object value;
710};
711
712
4ef0d4d0
KS
713/* Parse image spec SPEC according to KEYWORDS. A valid image spec
714 has the format (image KEYWORD VALUE ...). One of the keyword/
715 value pairs must be `:type TYPE'. KEYWORDS is a vector of
716 image_keywords structures of size NKEYWORDS describing other
578098f3 717 allowed keyword/value pairs. Value is true if SPEC is valid. */
4ef0d4d0 718
578098f3 719static bool
d3da34e0
JB
720parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
721 int nkeywords, Lisp_Object type)
4ef0d4d0
KS
722{
723 int i;
724 Lisp_Object plist;
725
726 if (!IMAGEP (spec))
727 return 0;
728
729 plist = XCDR (spec);
730 while (CONSP (plist))
731 {
732 Lisp_Object key, value;
733
734 /* First element of a pair must be a symbol. */
735 key = XCAR (plist);
736 plist = XCDR (plist);
737 if (!SYMBOLP (key))
738 return 0;
739
740 /* There must follow a value. */
741 if (!CONSP (plist))
742 return 0;
743 value = XCAR (plist);
744 plist = XCDR (plist);
745
746 /* Find key in KEYWORDS. Error if not found. */
747 for (i = 0; i < nkeywords; ++i)
42a5b22f 748 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
4ef0d4d0
KS
749 break;
750
751 if (i == nkeywords)
752 continue;
753
754 /* Record that we recognized the keyword. If a keywords
755 was found more than once, it's an error. */
756 keywords[i].value = value;
4ef0d4d0
KS
757 if (keywords[i].count > 1)
758 return 0;
d311d28c 759 ++keywords[i].count;
4ef0d4d0
KS
760
761 /* Check type of value against allowed type. */
762 switch (keywords[i].type)
763 {
764 case IMAGE_STRING_VALUE:
765 if (!STRINGP (value))
766 return 0;
767 break;
768
769 case IMAGE_STRING_OR_NIL_VALUE:
770 if (!STRINGP (value) && !NILP (value))
771 return 0;
772 break;
773
774 case IMAGE_SYMBOL_VALUE:
775 if (!SYMBOLP (value))
776 return 0;
777 break;
778
779 case IMAGE_POSITIVE_INTEGER_VALUE:
13464394 780 if (! RANGED_INTEGERP (1, value, INT_MAX))
4ef0d4d0
KS
781 return 0;
782 break;
783
c4a07a4c
PE
784 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
785 if (RANGED_INTEGERP (0, value, INT_MAX))
4ef0d4d0
KS
786 break;
787 if (CONSP (value)
c4a07a4c
PE
788 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
789 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
4ef0d4d0
KS
790 break;
791 return 0;
792
793 case IMAGE_ASCENT_VALUE:
794 if (SYMBOLP (value) && EQ (value, Qcenter))
795 break;
13464394 796 else if (RANGED_INTEGERP (0, value, 100))
4ef0d4d0
KS
797 break;
798 return 0;
799
800 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
13464394
PE
801 /* Unlike the other integer-related cases, this one does not
802 verify that VALUE fits in 'int'. This is because callers
803 want EMACS_INT. */
4ef0d4d0
KS
804 if (!INTEGERP (value) || XINT (value) < 0)
805 return 0;
806 break;
807
808 case IMAGE_DONT_CHECK_VALUE_TYPE:
809 break;
810
811 case IMAGE_FUNCTION_VALUE:
812 value = indirect_function (value);
ca105506 813 if (!NILP (Ffunctionp (value)))
4ef0d4d0
KS
814 break;
815 return 0;
816
817 case IMAGE_NUMBER_VALUE:
818 if (!INTEGERP (value) && !FLOATP (value))
819 return 0;
820 break;
821
822 case IMAGE_INTEGER_VALUE:
13464394 823 if (! TYPE_RANGED_INTEGERP (int, value))
4ef0d4d0
KS
824 return 0;
825 break;
826
827 case IMAGE_BOOL_VALUE:
828 if (!NILP (value) && !EQ (value, Qt))
829 return 0;
830 break;
831
832 default:
1088b922 833 emacs_abort ();
4ef0d4d0
KS
834 break;
835 }
836
837 if (EQ (key, QCtype) && !EQ (type, value))
838 return 0;
839 }
840
841 /* Check that all mandatory fields are present. */
842 for (i = 0; i < nkeywords; ++i)
843 if (keywords[i].mandatory_p && keywords[i].count == 0)
844 return 0;
845
846 return NILP (plist);
847}
848
849
850/* Return the value of KEY in image specification SPEC. Value is nil
578098f3
PE
851 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
852 was found in SPEC. */
4ef0d4d0
KS
853
854static Lisp_Object
578098f3 855image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
4ef0d4d0
KS
856{
857 Lisp_Object tail;
858
a54e2c05 859 eassert (valid_image_p (spec));
4ef0d4d0
KS
860
861 for (tail = XCDR (spec);
862 CONSP (tail) && CONSP (XCDR (tail));
863 tail = XCDR (XCDR (tail)))
864 {
865 if (EQ (XCAR (tail), key))
866 {
867 if (found)
868 *found = 1;
869 return XCAR (XCDR (tail));
870 }
871 }
872
873 if (found)
874 *found = 0;
875 return Qnil;
876}
877
878
879DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
880 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
881PIXELS non-nil means return the size in pixels, otherwise return the
882size in canonical character units.
883FRAME is the frame on which the image will be displayed. FRAME nil
884or omitted means use the selected frame. */)
5842a27b 885 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
4ef0d4d0
KS
886{
887 Lisp_Object size;
888
889 size = Qnil;
890 if (valid_image_p (spec))
891 {
7452b7bd 892 struct frame *f = decode_window_system_frame (frame);
13464394 893 ptrdiff_t id = lookup_image (f, spec);
4ef0d4d0
KS
894 struct image *img = IMAGE_FROM_ID (f, id);
895 int width = img->width + 2 * img->hmargin;
896 int height = img->height + 2 * img->vmargin;
897
898 if (NILP (pixels))
899 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
900 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
901 else
902 size = Fcons (make_number (width), make_number (height));
903 }
904 else
905 error ("Invalid image specification");
906
907 return size;
908}
909
910
911DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
912 doc: /* Return t if image SPEC has a mask bitmap.
913FRAME is the frame on which the image will be displayed. FRAME nil
914or omitted means use the selected frame. */)
5842a27b 915 (Lisp_Object spec, Lisp_Object frame)
4ef0d4d0
KS
916{
917 Lisp_Object mask;
918
919 mask = Qnil;
920 if (valid_image_p (spec))
921 {
7452b7bd 922 struct frame *f = decode_window_system_frame (frame);
13464394 923 ptrdiff_t id = lookup_image (f, spec);
4ef0d4d0
KS
924 struct image *img = IMAGE_FROM_ID (f, id);
925 if (img->mask)
926 mask = Qt;
927 }
928 else
929 error ("Invalid image specification");
930
931 return mask;
932}
933
1546c559
JL
934DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
935 doc: /* Return metadata for image SPEC.
6ac3c7bb
KS
936FRAME is the frame on which the image will be displayed. FRAME nil
937or omitted means use the selected frame. */)
5842a27b 938 (Lisp_Object spec, Lisp_Object frame)
6ac3c7bb
KS
939{
940 Lisp_Object ext;
941
942 ext = Qnil;
943 if (valid_image_p (spec))
944 {
7452b7bd 945 struct frame *f = decode_window_system_frame (frame);
13464394 946 ptrdiff_t id = lookup_image (f, spec);
6ac3c7bb 947 struct image *img = IMAGE_FROM_ID (f, id);
b50691aa 948 ext = img->lisp_data;
6ac3c7bb
KS
949 }
950
951 return ext;
952}
953
4ef0d4d0
KS
954\f
955/***********************************************************************
956 Image type independent image structures
957 ***********************************************************************/
958
11273115 959#define MAX_IMAGE_SIZE 10.0
4ef0d4d0
KS
960/* Allocate and return a new image structure for image specification
961 SPEC. SPEC has a hash value of HASH. */
962
963static struct image *
0de4bb68 964make_image (Lisp_Object spec, EMACS_UINT hash)
4ef0d4d0 965{
23f86fce 966 struct image *img = xzalloc (sizeof *img);
a2bc5bdd 967 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
4ef0d4d0 968
a54e2c05 969 eassert (valid_image_p (spec));
a2bc5bdd 970 img->dependencies = NILP (file) ? Qnil : list1 (file);
4ef0d4d0 971 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
a54e2c05 972 eassert (img->type != NULL);
4ef0d4d0 973 img->spec = spec;
b50691aa 974 img->lisp_data = Qnil;
4ef0d4d0
KS
975 img->ascent = DEFAULT_IMAGE_ASCENT;
976 img->hash = hash;
6ac3c7bb 977 img->corners[BOT_CORNER] = -1; /* Full image */
4ef0d4d0
KS
978 return img;
979}
980
981
982/* Free image IMG which was used on frame F, including its resources. */
983
984static void
d3da34e0 985free_image (struct frame *f, struct image *img)
4ef0d4d0
KS
986{
987 if (img)
988 {
354884c4 989 struct image_cache *c = FRAME_IMAGE_CACHE (f);
4ef0d4d0
KS
990
991 /* Remove IMG from the hash table of its cache. */
992 if (img->prev)
993 img->prev->next = img->next;
994 else
995 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
996
997 if (img->next)
998 img->next->prev = img->prev;
999
1000 c->images[img->id] = NULL;
1001
1002 /* Free resources, then free IMG. */
1003 img->type->free (f, img);
1004 xfree (img);
1005 }
1006}
1007
578098f3 1008/* Return true if the given widths and heights are valid for display. */
f1f25b99 1009
578098f3 1010static bool
d3da34e0 1011check_image_size (struct frame *f, int width, int height)
f1f25b99 1012{
7df4765a 1013 int w, h;
f1f25b99 1014
7df4765a 1015 if (width <= 0 || height <= 0)
f1f25b99
CY
1016 return 0;
1017
7df4765a 1018 if (INTEGERP (Vmax_image_size))
3f791afe
PE
1019 return (width <= XINT (Vmax_image_size)
1020 && height <= XINT (Vmax_image_size));
7df4765a
KS
1021 else if (FLOATP (Vmax_image_size))
1022 {
e5d76069
PE
1023 if (f != NULL)
1024 {
1025 w = FRAME_PIXEL_WIDTH (f);
1026 h = FRAME_PIXEL_HEIGHT (f);
1027 }
1028 else
1029 w = h = 1024; /* Arbitrary size for unknown frame. */
3f791afe
PE
1030 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1031 && height <= XFLOAT_DATA (Vmax_image_size) * h);
7df4765a
KS
1032 }
1033 else
1034 return 1;
f1f25b99 1035}
4ef0d4d0
KS
1036
1037/* Prepare image IMG for display on frame F. Must be called before
1038 drawing an image. */
1039
1040void
d3da34e0 1041prepare_image_for_display (struct frame *f, struct image *img)
4ef0d4d0 1042{
4ef0d4d0 1043 /* We're about to display IMG, so set its timestamp to `now'. */
e9a9ae03 1044 img->timestamp = current_emacs_time ();
4ef0d4d0
KS
1045
1046 /* If IMG doesn't have a pixmap yet, load it now, using the image
1047 type dependent loader function. */
1048 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
578098f3 1049 img->load_failed_p = ! img->type->load (f, img);
c7fea325 1050
4ef0d4d0
KS
1051}
1052
1053
1054/* Value is the number of pixels for the ascent of image IMG when
1055 drawn in face FACE. */
1056
1057int
d3da34e0 1058image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
4ef0d4d0 1059{
1938bc36 1060 int height;
4ef0d4d0
KS
1061 int ascent;
1062
1938bc36
KS
1063 if (slice->height == img->height)
1064 height = img->height + img->vmargin;
1065 else if (slice->y == 0)
1066 height = slice->height + img->vmargin;
1067 else
1068 height = slice->height;
1069
4ef0d4d0
KS
1070 if (img->ascent == CENTERED_IMAGE_ASCENT)
1071 {
1072 if (face->font)
1073 {
1074#ifdef HAVE_NTGUI
1075 /* W32 specific version. Why?. ++kfs */
5fc9fdeb
JR
1076 ascent = height / 2 - (FONT_DESCENT (face->font)
1077 - FONT_BASE (face->font)) / 2;
4ef0d4d0
KS
1078#else
1079 /* This expression is arranged so that if the image can't be
1080 exactly centered, it will be moved slightly up. This is
1081 because a typical font is `top-heavy' (due to the presence
1082 uppercase letters), so the image placement should err towards
1083 being top-heavy too. It also just generally looks better. */
5e617bc2
JB
1084 ascent = (height + FONT_BASE (face->font)
1085 - FONT_DESCENT (face->font) + 1) / 2;
4ef0d4d0
KS
1086#endif /* HAVE_NTGUI */
1087 }
1088 else
1089 ascent = height / 2;
1090 }
1091 else
13464394 1092 ascent = height * (img->ascent / 100.0);
4ef0d4d0
KS
1093
1094 return ascent;
1095}
1096
1097\f
1098/* Image background colors. */
1099
1100/* Find the "best" corner color of a bitmap.
1101 On W32, XIMG is assumed to a device context with the bitmap selected. */
1102
1103static RGB_PIXEL_COLOR
d3da34e0
JB
1104four_corners_best (XImagePtr_or_DC ximg, int *corners,
1105 unsigned long width, unsigned long height)
4ef0d4d0 1106{
f0c77cd1 1107 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
4ef0d4d0
KS
1108 int i, best_count;
1109
6ac3c7bb
KS
1110 if (corners && corners[BOT_CORNER] >= 0)
1111 {
1112 /* Get the colors at the corner_pixels of ximg. */
1113 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1114 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1115 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1116 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1117 }
1118 else
1119 {
1120 /* Get the colors at the corner_pixels of ximg. */
1121 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1122 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1123 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1124 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1125 }
4ef0d4d0
KS
1126 /* Choose the most frequently found color as background. */
1127 for (i = best_count = 0; i < 4; ++i)
1128 {
1129 int j, n;
1130
1131 for (j = n = 0; j < 4; ++j)
6ac3c7bb 1132 if (corner_pixels[i] == corner_pixels[j])
4ef0d4d0
KS
1133 ++n;
1134
1135 if (n > best_count)
6ac3c7bb 1136 best = corner_pixels[i], best_count = n;
4ef0d4d0
KS
1137 }
1138
1139 return best;
1140}
1141
1142/* Portability macros */
1143
1144#ifdef HAVE_NTGUI
1145
1146#define Destroy_Image(img_dc, prev) \
1147 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1148
1149#define Free_Pixmap(display, pixmap) \
1150 DeleteObject (pixmap)
1151
edfda783
AR
1152#elif defined (HAVE_NS)
1153
1154#define Destroy_Image(ximg, dummy) \
ed3751c8 1155 ns_release_object (ximg)
edfda783
AR
1156
1157#define Free_Pixmap(display, pixmap) \
ed3751c8 1158 ns_release_object (pixmap)
edfda783 1159
4ef0d4d0
KS
1160#else
1161
1162#define Destroy_Image(ximg, dummy) \
1163 XDestroyImage (ximg)
1164
1165#define Free_Pixmap(display, pixmap) \
1166 XFreePixmap (display, pixmap)
1167
edfda783 1168#endif /* !HAVE_NTGUI && !HAVE_NS */
4ef0d4d0
KS
1169
1170
1171/* Return the `background' field of IMG. If IMG doesn't have one yet,
1172 it is guessed heuristically. If non-zero, XIMG is an existing
1173 XImage object (or device context with the image selected on W32) to
1f026899 1174 use for the heuristic. */
4ef0d4d0
KS
1175
1176RGB_PIXEL_COLOR
d3da34e0 1177image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
4ef0d4d0
KS
1178{
1179 if (! img->background_valid)
1180 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1181 {
578098f3 1182 bool free_ximg = !ximg;
4ef0d4d0
KS
1183#ifdef HAVE_NTGUI
1184 HGDIOBJ prev;
1185#endif /* HAVE_NTGUI */
1186
1187 if (free_ximg)
1188 {
1189#ifndef HAVE_NTGUI
1190 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1191 0, 0, img->width, img->height, ~0, ZPixmap);
1192#else
1193 HDC frame_dc = get_frame_dc (f);
1194 ximg = CreateCompatibleDC (frame_dc);
1195 release_frame_dc (f, frame_dc);
1196 prev = SelectObject (ximg, img->pixmap);
1197#endif /* !HAVE_NTGUI */
1198 }
1199
6ac3c7bb 1200 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
4ef0d4d0
KS
1201
1202 if (free_ximg)
1203 Destroy_Image (ximg, prev);
1f026899 1204
4ef0d4d0
KS
1205 img->background_valid = 1;
1206 }
1207
1208 return img->background;
1209}
1210
1211/* Return the `background_transparent' field of IMG. If IMG doesn't
1212 have one yet, it is guessed heuristically. If non-zero, MASK is an
1213 existing XImage object to use for the heuristic. */
1214
1215int
d3da34e0 1216image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
4ef0d4d0
KS
1217{
1218 if (! img->background_transparent_valid)
1219 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1220 {
1221 if (img->mask)
1222 {
578098f3 1223 bool free_mask = !mask;
4ef0d4d0
KS
1224#ifdef HAVE_NTGUI
1225 HGDIOBJ prev;
1226#endif /* HAVE_NTGUI */
1227
1228 if (free_mask)
1229 {
1230#ifndef HAVE_NTGUI
1231 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1232 0, 0, img->width, img->height, ~0, ZPixmap);
1233#else
1234 HDC frame_dc = get_frame_dc (f);
1235 mask = CreateCompatibleDC (frame_dc);
1236 release_frame_dc (f, frame_dc);
1237 prev = SelectObject (mask, img->mask);
1238#endif /* HAVE_NTGUI */
1239 }
1240
1241 img->background_transparent
6ac3c7bb 1242 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
4ef0d4d0
KS
1243
1244 if (free_mask)
1245 Destroy_Image (mask, prev);
1246 }
1247 else
1248 img->background_transparent = 0;
1249
1250 img->background_transparent_valid = 1;
1251 }
1252
1253 return img->background_transparent;
1254}
1255
1256\f
1257/***********************************************************************
1258 Helper functions for X image types
1259 ***********************************************************************/
1260
578098f3
PE
1261/* Clear X resources of image IMG on frame F. PIXMAP_P means free the
1262 pixmap if any. MASK_P means clear the mask pixmap if any.
1263 COLORS_P means free colors allocated for the image, if any. */
4ef0d4d0
KS
1264
1265static void
578098f3
PE
1266x_clear_image_1 (struct frame *f, struct image *img, bool pixmap_p,
1267 bool mask_p, bool colors_p)
4ef0d4d0
KS
1268{
1269 if (pixmap_p && img->pixmap)
1270 {
1271 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1272 img->pixmap = NO_PIXMAP;
5a06864f 1273 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
4ef0d4d0
KS
1274 img->background_valid = 0;
1275 }
1276
1277 if (mask_p && img->mask)
1278 {
1279 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1280 img->mask = NO_PIXMAP;
1281 img->background_transparent_valid = 0;
1282 }
1283
1284 if (colors_p && img->ncolors)
1285 {
4ef0d4d0
KS
1286 /* W32_TODO: color table support. */
1287#ifdef HAVE_X_WINDOWS
1288 x_free_colors (f, img->colors, img->ncolors);
1289#endif /* HAVE_X_WINDOWS */
1290 xfree (img->colors);
1291 img->colors = NULL;
1292 img->ncolors = 0;
1293 }
c7fea325 1294
4ef0d4d0
KS
1295}
1296
1297/* Free X resources of image IMG which is used on frame F. */
1298
1299static void
d3da34e0 1300x_clear_image (struct frame *f, struct image *img)
4ef0d4d0 1301{
4d7e6e51 1302 block_input ();
4ef0d4d0 1303 x_clear_image_1 (f, img, 1, 1, 1);
4d7e6e51 1304 unblock_input ();
4ef0d4d0
KS
1305}
1306
1307
1308/* Allocate color COLOR_NAME for image IMG on frame F. If color
1309 cannot be allocated, use DFLT. Add a newly allocated color to
1310 IMG->colors, so that it can be freed again. Value is the pixel
1311 color. */
1312
1313static unsigned long
d3da34e0
JB
1314x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1315 unsigned long dflt)
4ef0d4d0
KS
1316{
1317 XColor color;
1318 unsigned long result;
1319
a54e2c05 1320 eassert (STRINGP (color_name));
4ef0d4d0 1321
3f791afe
PE
1322 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1323 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1324 INT_MAX))
4ef0d4d0
KS
1325 {
1326 /* This isn't called frequently so we get away with simply
1327 reallocating the color vector to the needed size, here. */
ddff3151 1328 ptrdiff_t ncolors = img->ncolors + 1;
38182d90 1329 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
ddff3151
PE
1330 img->colors[ncolors - 1] = color.pixel;
1331 img->ncolors = ncolors;
4ef0d4d0
KS
1332 result = color.pixel;
1333 }
1334 else
1335 result = dflt;
1336
1337 return result;
1338}
1339
1340
1341\f
1342/***********************************************************************
1343 Image Cache
1344 ***********************************************************************/
1345
f57e2426 1346static void cache_image (struct frame *f, struct image *img);
4ef0d4d0
KS
1347
1348/* Return a new, initialized image cache that is allocated from the
1349 heap. Call free_image_cache to free an image cache. */
1350
1351struct image_cache *
d3da34e0 1352make_image_cache (void)
4ef0d4d0 1353{
23f86fce 1354 struct image_cache *c = xzalloc (sizeof *c);
4ef0d4d0
KS
1355 int size;
1356
ddff3151 1357 size = 50;
23f86fce 1358 c->images = xmalloc (size * sizeof *c->images);
ddff3151 1359 c->size = size;
4ef0d4d0 1360 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
23f86fce 1361 c->buckets = xzalloc (size);
4ef0d4d0
KS
1362 return c;
1363}
1364
1365
d3c35d17
CY
1366/* Find an image matching SPEC in the cache, and return it. If no
1367 image is found, return NULL. */
1368static struct image *
0de4bb68 1369search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
483e7ae0 1370{
91be6b66 1371 struct image *img;
354884c4 1372 struct image_cache *c = FRAME_IMAGE_CACHE (f);
483e7ae0
CY
1373 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1374
8198352b
CY
1375 if (!c) return NULL;
1376
d3c35d17
CY
1377 /* If the image spec does not specify a background color, the cached
1378 image must have the same background color as the current frame.
cf26ebe8
CY
1379 The foreground color must also match, for the sake of monochrome
1380 images.
1381
1382 In fact, we could ignore the foreground color matching condition
1383 for color images, or if the image spec specifies :foreground;
1384 similarly we could ignore the background color matching condition
1385 for formats that don't use transparency (such as jpeg), or if the
1386 image spec specifies :background. However, the extra memory
1387 usage is probably negligible in practice, so we don't bother. */
d3c35d17 1388
483e7ae0 1389 for (img = c->buckets[i]; img; img = img->next)
d3c35d17
CY
1390 if (img->hash == hash
1391 && !NILP (Fequal (img->spec, spec))
c5b8e0ea
YM
1392 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1393 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
d3c35d17
CY
1394 break;
1395 return img;
1396}
1397
1398
1399/* Search frame F for an image with spec SPEC, and free it. */
1400
1401static void
d3da34e0 1402uncache_image (struct frame *f, Lisp_Object spec)
d3c35d17
CY
1403{
1404 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1405 if (img)
be3faa80
CY
1406 {
1407 free_image (f, img);
1408 /* As display glyphs may still be referring to the image ID, we
1409 must garbage the frame (Bug#6426). */
1410 SET_FRAME_GARBAGED (f);
1411 }
483e7ae0
CY
1412}
1413
1414
4ef0d4d0
KS
1415/* Free image cache of frame F. Be aware that X frames share images
1416 caches. */
1417
1418void
d3da34e0 1419free_image_cache (struct frame *f)
4ef0d4d0 1420{
354884c4 1421 struct image_cache *c = FRAME_IMAGE_CACHE (f);
4ef0d4d0
KS
1422 if (c)
1423 {
13464394 1424 ptrdiff_t i;
4ef0d4d0
KS
1425
1426 /* Cache should not be referenced by any frame when freed. */
a54e2c05 1427 eassert (c->refcount == 0);
4ef0d4d0
KS
1428
1429 for (i = 0; i < c->used; ++i)
1430 free_image (f, c->images[i]);
1431 xfree (c->images);
1432 xfree (c->buckets);
1433 xfree (c);
354884c4 1434 FRAME_IMAGE_CACHE (f) = NULL;
4ef0d4d0
KS
1435 }
1436}
1437
1438
a2bc5bdd
SM
1439/* Clear image cache of frame F. FILTER=t means free all images.
1440 FILTER=nil means clear only images that haven't been
1441 displayed for some time.
1442 Else, only free the images which have FILTER in their `dependencies'.
1443 Should be called from time to time to reduce the number of loaded images.
1444 If image-cache-eviction-delay is non-nil, this frees images in the cache
1445 which weren't displayed for at least that many seconds. */
4ef0d4d0 1446
ce0ad53d 1447static void
a2bc5bdd 1448clear_image_cache (struct frame *f, Lisp_Object filter)
4ef0d4d0 1449{
354884c4 1450 struct image_cache *c = FRAME_IMAGE_CACHE (f);
4ef0d4d0 1451
98fe5161 1452 if (c)
4ef0d4d0 1453 {
13464394 1454 ptrdiff_t i, nfreed = 0;
4ef0d4d0
KS
1455
1456 /* Block input so that we won't be interrupted by a SIGIO
1457 while being in an inconsistent state. */
4d7e6e51 1458 block_input ();
4ef0d4d0 1459
98fe5161
CY
1460 if (!NILP (filter))
1461 {
1462 /* Filter image cache. */
1463 for (i = 0; i < c->used; ++i)
1464 {
1465 struct image *img = c->images[i];
1466 if (img && (EQ (Qt, filter)
1467 || !NILP (Fmember (filter, img->dependencies))))
1468 {
1469 free_image (f, img);
1470 ++nfreed;
1471 }
1472 }
1473 }
1474 else if (INTEGERP (Vimage_cache_eviction_delay))
4ef0d4d0 1475 {
98fe5161 1476 /* Free cache based on timestamp. */
d35af63c
PE
1477 EMACS_TIME old, t;
1478 double delay;
13464394 1479 ptrdiff_t nimages = 0;
98fe5161
CY
1480
1481 for (i = 0; i < c->used; ++i)
1482 if (c->images[i])
1483 nimages++;
1484
1485 /* If the number of cached images has grown unusually large,
1486 decrease the cache eviction delay (Bug#6230). */
13464394 1487 delay = XINT (Vimage_cache_eviction_delay);
98fe5161 1488 if (nimages > 40)
13464394
PE
1489 delay = 1600 * delay / nimages / nimages;
1490 delay = max (delay, 1);
98fe5161 1491
e9a9ae03
PE
1492 t = current_emacs_time ();
1493 old = sub_emacs_time (t, EMACS_TIME_FROM_DOUBLE (delay));
98fe5161
CY
1494
1495 for (i = 0; i < c->used; ++i)
4ef0d4d0 1496 {
98fe5161 1497 struct image *img = c->images[i];
d35af63c 1498 if (img && EMACS_TIME_LT (img->timestamp, old))
98fe5161
CY
1499 {
1500 free_image (f, img);
1501 ++nfreed;
1502 }
4ef0d4d0
KS
1503 }
1504 }
1505
1506 /* We may be clearing the image cache because, for example,
1507 Emacs was iconified for a longer period of time. In that
1508 case, current matrices may still contain references to
1509 images freed above. So, clear these matrices. */
1510 if (nfreed)
1511 {
1512 Lisp_Object tail, frame;
1513
1514 FOR_EACH_FRAME (tail, frame)
1515 {
6ae141d6
PE
1516 struct frame *fr = XFRAME (frame);
1517 if (FRAME_IMAGE_CACHE (fr) == c)
1518 clear_current_matrices (fr);
4ef0d4d0
KS
1519 }
1520
1521 ++windows_or_buffers_changed;
1522 }
1523
4d7e6e51 1524 unblock_input ();
4ef0d4d0
KS
1525 }
1526}
1527
354884c4 1528void
a2bc5bdd 1529clear_image_caches (Lisp_Object filter)
354884c4
SM
1530{
1531 /* FIXME: We want to do
1532 * struct terminal *t;
1533 * for (t = terminal_list; t; t = t->next_terminal)
1534 * clear_image_cache (t, filter); */
1535 Lisp_Object tail, frame;
1536 FOR_EACH_FRAME (tail, frame)
1537 if (FRAME_WINDOW_P (XFRAME (frame)))
a2bc5bdd 1538 clear_image_cache (XFRAME (frame), filter);
354884c4 1539}
4ef0d4d0
KS
1540
1541DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1542 0, 1, 0,
a2bc5bdd
SM
1543 doc: /* Clear the image cache.
1544FILTER nil or a frame means clear all images in the selected frame.
1545FILTER t means clear the image caches of all frames.
1546Anything else, means only clear those images which refer to FILTER,
1547which is then usually a filename. */)
5842a27b 1548 (Lisp_Object filter)
4ef0d4d0 1549{
a2bc5bdd
SM
1550 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1551 clear_image_caches (filter);
4ef0d4d0 1552 else
7452b7bd 1553 clear_image_cache (decode_window_system_frame (filter), Qt);
4ef0d4d0
KS
1554
1555 return Qnil;
1556}
1557
1558
110683ad 1559DEFUN ("image-flush", Fimage_flush, Simage_flush,
483e7ae0 1560 1, 2, 0,
110683ad
CY
1561 doc: /* Fush the image with specification SPEC on frame FRAME.
1562This removes the image from the Emacs image cache. If SPEC specifies
1563an image file, the next redisplay of this image will read from the
1564current contents of that file.
1565
483e7ae0
CY
1566FRAME nil or omitted means use the selected frame.
1567FRAME t means refresh the image on all frames. */)
5842a27b 1568 (Lisp_Object spec, Lisp_Object frame)
483e7ae0
CY
1569{
1570 if (!valid_image_p (spec))
1571 error ("Invalid image specification");
1572
1573 if (EQ (frame, Qt))
1574 {
1575 Lisp_Object tail;
1576 FOR_EACH_FRAME (tail, frame)
1577 {
1578 struct frame *f = XFRAME (frame);
1579 if (FRAME_WINDOW_P (f))
1580 uncache_image (f, spec);
1581 }
1582 }
1583 else
7452b7bd 1584 uncache_image (decode_window_system_frame (frame), spec);
483e7ae0
CY
1585
1586 return Qnil;
1587}
1588
1589
4ef0d4d0
KS
1590/* Compute masks and transform image IMG on frame F, as specified
1591 by the image's specification, */
1592
1593static void
d3da34e0 1594postprocess_image (struct frame *f, struct image *img)
4ef0d4d0
KS
1595{
1596 /* Manipulation of the image's mask. */
1597 if (img->pixmap)
1598 {
1599 Lisp_Object conversion, spec;
1600 Lisp_Object mask;
1601
1602 spec = img->spec;
1603
1604 /* `:heuristic-mask t'
1605 `:mask heuristic'
1606 means build a mask heuristically.
1607 `:heuristic-mask (R G B)'
1608 `:mask (heuristic (R G B))'
1609 means build a mask from color (R G B) in the
1610 image.
1611 `:mask nil'
1612 means remove a mask, if any. */
1613
1614 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1615 if (!NILP (mask))
1616 x_build_heuristic_mask (f, img, mask);
1617 else
1618 {
578098f3 1619 bool found_p;
4ef0d4d0
KS
1620
1621 mask = image_spec_value (spec, QCmask, &found_p);
1622
1623 if (EQ (mask, Qheuristic))
1624 x_build_heuristic_mask (f, img, Qt);
1625 else if (CONSP (mask)
1626 && EQ (XCAR (mask), Qheuristic))
1627 {
1628 if (CONSP (XCDR (mask)))
1629 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1630 else
1631 x_build_heuristic_mask (f, img, XCDR (mask));
1632 }
1633 else if (NILP (mask) && found_p && img->mask)
1634 {
1635 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1636 img->mask = NO_PIXMAP;
1637 }
1638 }
1639
1640
1641 /* Should we apply an image transformation algorithm? */
1642 conversion = image_spec_value (spec, QCconversion, NULL);
1643 if (EQ (conversion, Qdisabled))
1644 x_disable_image (f, img);
1645 else if (EQ (conversion, Qlaplace))
1646 x_laplace (f, img);
1647 else if (EQ (conversion, Qemboss))
1648 x_emboss (f, img);
1649 else if (CONSP (conversion)
1650 && EQ (XCAR (conversion), Qedge_detection))
1651 {
1652 Lisp_Object tem;
1653 tem = XCDR (conversion);
1654 if (CONSP (tem))
1655 x_edge_detection (f, img,
1656 Fplist_get (tem, QCmatrix),
1657 Fplist_get (tem, QCcolor_adjustment));
1658 }
1659 }
1660}
1661
1662
1663/* Return the id of image with Lisp specification SPEC on frame F.
1664 SPEC must be a valid Lisp image specification (see valid_image_p). */
1665
13464394 1666ptrdiff_t
d3da34e0 1667lookup_image (struct frame *f, Lisp_Object spec)
4ef0d4d0 1668{
4ef0d4d0 1669 struct image *img;
0de4bb68 1670 EMACS_UINT hash;
4ef0d4d0
KS
1671
1672 /* F must be a window-system frame, and SPEC must be a valid image
1673 specification. */
a54e2c05
DA
1674 eassert (FRAME_WINDOW_P (f));
1675 eassert (valid_image_p (spec));
4ef0d4d0 1676
4ef0d4d0
KS
1677 /* Look up SPEC in the hash table of the image cache. */
1678 hash = sxhash (spec, 0);
d3c35d17 1679 img = search_image_cache (f, spec, hash);
f1f25b99
CY
1680 if (img && img->load_failed_p)
1681 {
1682 free_image (f, img);
1683 img = NULL;
1684 }
1685
4ef0d4d0
KS
1686 /* If not found, create a new image and cache it. */
1687 if (img == NULL)
1688 {
4d7e6e51 1689 block_input ();
4ef0d4d0
KS
1690 img = make_image (spec, hash);
1691 cache_image (f, img);
578098f3 1692 img->load_failed_p = ! img->type->load (f, img);
c5b8e0ea
YM
1693 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1694 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
4ef0d4d0
KS
1695
1696 /* If we can't load the image, and we don't have a width and
1697 height, use some arbitrary width and height so that we can
1698 draw a rectangle for it. */
1699 if (img->load_failed_p)
1700 {
1701 Lisp_Object value;
1702
1703 value = image_spec_value (spec, QCwidth, NULL);
1704 img->width = (INTEGERP (value)
1705 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1706 value = image_spec_value (spec, QCheight, NULL);
1707 img->height = (INTEGERP (value)
1708 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1709 }
1710 else
1711 {
1712 /* Handle image type independent image attributes
1713 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1714 `:background COLOR'. */
1715 Lisp_Object ascent, margin, relief, bg;
d311d28c 1716 int relief_bound;
4ef0d4d0
KS
1717
1718 ascent = image_spec_value (spec, QCascent, NULL);
1719 if (INTEGERP (ascent))
1720 img->ascent = XFASTINT (ascent);
1721 else if (EQ (ascent, Qcenter))
1722 img->ascent = CENTERED_IMAGE_ASCENT;
1723
1724 margin = image_spec_value (spec, QCmargin, NULL);
13464394 1725 if (INTEGERP (margin))
4ef0d4d0 1726 img->vmargin = img->hmargin = XFASTINT (margin);
13464394 1727 else if (CONSP (margin))
4ef0d4d0 1728 {
13464394
PE
1729 img->hmargin = XFASTINT (XCAR (margin));
1730 img->vmargin = XFASTINT (XCDR (margin));
4ef0d4d0
KS
1731 }
1732
1733 relief = image_spec_value (spec, QCrelief, NULL);
d311d28c
PE
1734 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1735 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
4ef0d4d0
KS
1736 {
1737 img->relief = XINT (relief);
1ea40aa2
EZ
1738 img->hmargin += eabs (img->relief);
1739 img->vmargin += eabs (img->relief);
4ef0d4d0
KS
1740 }
1741
1742 if (! img->background_valid)
1743 {
1744 bg = image_spec_value (img->spec, QCbackground, NULL);
1745 if (!NILP (bg))
1746 {
1747 img->background
1748 = x_alloc_image_color (f, img, bg,
1749 FRAME_BACKGROUND_PIXEL (f));
1750 img->background_valid = 1;
1751 }
1752 }
1753
1754 /* Do image transformations and compute masks, unless we
1755 don't have the image yet. */
1756 if (!EQ (*img->type->type, Qpostscript))
1757 postprocess_image (f, img);
1758 }
1759
4d7e6e51 1760 unblock_input ();
4ef0d4d0
KS
1761 }
1762
1763 /* We're using IMG, so set its timestamp to `now'. */
e9a9ae03 1764 img->timestamp = current_emacs_time ();
4ef0d4d0 1765
4ef0d4d0
KS
1766 /* Value is the image id. */
1767 return img->id;
1768}
1769
1770
1771/* Cache image IMG in the image cache of frame F. */
1772
1773static void
d3da34e0 1774cache_image (struct frame *f, struct image *img)
4ef0d4d0 1775{
354884c4 1776 struct image_cache *c = FRAME_IMAGE_CACHE (f);
13464394 1777 ptrdiff_t i;
4ef0d4d0
KS
1778
1779 /* Find a free slot in c->images. */
1780 for (i = 0; i < c->used; ++i)
1781 if (c->images[i] == NULL)
1782 break;
1783
1784 /* If no free slot found, maybe enlarge c->images. */
1785 if (i == c->used && c->used == c->size)
a69fbedb 1786 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
4ef0d4d0
KS
1787
1788 /* Add IMG to c->images, and assign IMG an id. */
1789 c->images[i] = img;
1790 img->id = i;
1791 if (i == c->used)
1792 ++c->used;
1793
1794 /* Add IMG to the cache's hash table. */
1795 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1796 img->next = c->buckets[i];
1797 if (img->next)
1798 img->next->prev = img;
1799 img->prev = NULL;
1800 c->buckets[i] = img;
1801}
1802
1803
1804/* Call FN on every image in the image cache of frame F. Used to mark
1805 Lisp Objects in the image cache. */
1806
354884c4
SM
1807/* Mark Lisp objects in image IMG. */
1808
1809static void
d3da34e0 1810mark_image (struct image *img)
354884c4
SM
1811{
1812 mark_object (img->spec);
a2bc5bdd 1813 mark_object (img->dependencies);
354884c4 1814
b50691aa
CY
1815 if (!NILP (img->lisp_data))
1816 mark_object (img->lisp_data);
354884c4
SM
1817}
1818
1819
4ef0d4d0 1820void
354884c4 1821mark_image_cache (struct image_cache *c)
4ef0d4d0 1822{
354884c4 1823 if (c)
4ef0d4d0 1824 {
13464394 1825 ptrdiff_t i;
354884c4
SM
1826 for (i = 0; i < c->used; ++i)
1827 if (c->images[i])
1828 mark_image (c->images[i]);
4ef0d4d0
KS
1829 }
1830}
1831
1832
1833\f
1834/***********************************************************************
9e2a2647 1835 X / NS / W32 support code
4ef0d4d0
KS
1836 ***********************************************************************/
1837
0fda9b75 1838#ifdef WINDOWSNT
4ef0d4d0
KS
1839
1840/* Macro for defining functions that will be loaded from image DLLs. */
dbdb9a7c 1841#define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
4ef0d4d0
KS
1842
1843/* Macro for loading those image functions from the library. */
1844#define LOAD_IMGLIB_FN(lib,func) { \
1845 fn_##func = (void *) GetProcAddress (lib, #func); \
1846 if (!fn_##func) return 0; \
1847 }
1848
0fda9b75 1849#endif /* WINDOWSNT */
4ef0d4d0 1850
578098f3 1851/* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
476371c4 1852 windowing system.
ca4aa935
PE
1853 WIDTH and HEIGHT must both be positive.
1854 If XIMG is null, assume it is a bitmap. */
578098f3 1855static bool
ca4aa935
PE
1856x_check_image_size (XImagePtr ximg, int width, int height)
1857{
476371c4 1858#ifdef HAVE_X_WINDOWS
ca4aa935
PE
1859 /* Respect Xlib's limits: it cannot deal with images that have more
1860 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
476371c4 1861 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
ca4aa935
PE
1862 enum
1863 {
1864 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1865 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1866 };
1867
1868 int bitmap_pad, depth, bytes_per_line;
1869 if (ximg)
1870 {
1871 bitmap_pad = ximg->bitmap_pad;
1872 depth = ximg->depth;
1873 bytes_per_line = ximg->bytes_per_line;
1874 }
1875 else
1876 {
1877 bitmap_pad = 8;
1878 depth = 1;
1879 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1880 }
1881 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1882 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
476371c4
PE
1883#else
1884 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1885 For now, assume that every image size is allowed on these systems. */
1886 return 1;
1887#endif
ca4aa935 1888}
4ef0d4d0
KS
1889
1890/* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1891 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1892 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1893 via xmalloc. Print error messages via image_error if an error
578098f3 1894 occurs. Value is true if successful.
4ef0d4d0
KS
1895
1896 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1897 should indicate the bit depth of the image. */
1898
578098f3 1899static bool
d3da34e0
JB
1900x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1901 XImagePtr *ximg, Pixmap *pixmap)
4ef0d4d0
KS
1902{
1903#ifdef HAVE_X_WINDOWS
1904 Display *display = FRAME_X_DISPLAY (f);
1905 Window window = FRAME_X_WINDOW (f);
1906 Screen *screen = FRAME_X_SCREEN (f);
1907
4d7e6e51 1908 eassert (input_blocked_p ());
4ef0d4d0
KS
1909
1910 if (depth <= 0)
1911 depth = DefaultDepthOfScreen (screen);
1912 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1913 depth, ZPixmap, 0, NULL, width, height,
1914 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1915 if (*ximg == NULL)
1916 {
1917 image_error ("Unable to allocate X image", Qnil, Qnil);
1918 return 0;
1919 }
1920
ca4aa935
PE
1921 if (! x_check_image_size (*ximg, width, height))
1922 {
1923 x_destroy_x_image (*ximg);
1924 *ximg = NULL;
1925 image_error ("Image too large (%dx%d)",
1926 make_number (width), make_number (height));
1927 return 0;
1928 }
1929
4ef0d4d0 1930 /* Allocate image raster. */
23f86fce 1931 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
4ef0d4d0
KS
1932
1933 /* Allocate a pixmap of the same size. */
1934 *pixmap = XCreatePixmap (display, window, width, height, depth);
1935 if (*pixmap == NO_PIXMAP)
1936 {
1937 x_destroy_x_image (*ximg);
1938 *ximg = NULL;
1939 image_error ("Unable to create X pixmap", Qnil, Qnil);
1940 return 0;
1941 }
1942
1943 return 1;
1944#endif /* HAVE_X_WINDOWS */
1945
1946#ifdef HAVE_NTGUI
1947
1948 BITMAPINFOHEADER *header;
1949 HDC hdc;
1950 int scanline_width_bits;
1951 int remainder;
1952 int palette_colors = 0;
1953
1954 if (depth == 0)
1955 depth = 24;
1956
1957 if (depth != 1 && depth != 4 && depth != 8
1958 && depth != 16 && depth != 24 && depth != 32)
1959 {
1960 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1961 return 0;
1962 }
1963
1964 scanline_width_bits = width * depth;
1965 remainder = scanline_width_bits % 32;
1966
1967 if (remainder)
1968 scanline_width_bits += 32 - remainder;
1969
1970 /* Bitmaps with a depth less than 16 need a palette. */
1971 /* BITMAPINFO structure already contains the first RGBQUAD. */
1972 if (depth < 16)
657d08d3 1973 palette_colors = 1 << (depth - 1);
4ef0d4d0
KS
1974
1975 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
4ef0d4d0 1976
72af86bd
AS
1977 header = &(*ximg)->info.bmiHeader;
1978 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
4ef0d4d0
KS
1979 header->biSize = sizeof (*header);
1980 header->biWidth = width;
1981 header->biHeight = -height; /* negative indicates a top-down bitmap. */
1982 header->biPlanes = 1;
1983 header->biBitCount = depth;
1984 header->biCompression = BI_RGB;
1985 header->biClrUsed = palette_colors;
1986
1987 /* TODO: fill in palette. */
1988 if (depth == 1)
1989 {
1990 (*ximg)->info.bmiColors[0].rgbBlue = 0;
1991 (*ximg)->info.bmiColors[0].rgbGreen = 0;
1992 (*ximg)->info.bmiColors[0].rgbRed = 0;
1993 (*ximg)->info.bmiColors[0].rgbReserved = 0;
1994 (*ximg)->info.bmiColors[1].rgbBlue = 255;
1995 (*ximg)->info.bmiColors[1].rgbGreen = 255;
1996 (*ximg)->info.bmiColors[1].rgbRed = 255;
1997 (*ximg)->info.bmiColors[1].rgbReserved = 0;
1998 }
1999
2000 hdc = get_frame_dc (f);
2001
2002 /* Create a DIBSection and raster array for the bitmap,
2003 and store its handle in *pixmap. */
2004 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2005 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2e09fef1
EZ
2006 /* casting avoids a GCC warning */
2007 (void **)&((*ximg)->data), NULL, 0);
4ef0d4d0
KS
2008
2009 /* Realize display palette and garbage all frames. */
2010 release_frame_dc (f, hdc);
2011
2012 if (*pixmap == NULL)
2013 {
5fc9fdeb 2014 DWORD err = GetLastError ();
4ef0d4d0
KS
2015 Lisp_Object errcode;
2016 /* All system errors are < 10000, so the following is safe. */
13464394 2017 XSETINT (errcode, err);
4ef0d4d0
KS
2018 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2019 x_destroy_x_image (*ximg);
2020 return 0;
2021 }
2022
2023 return 1;
2024
2025#endif /* HAVE_NTGUI */
2026
edfda783 2027#ifdef HAVE_NS
ed3751c8 2028 *pixmap = ns_image_for_XPM (width, height, depth);
edfda783
AR
2029 if (*pixmap == 0)
2030 {
2031 *ximg = NULL;
2032 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2033 return 0;
2034 }
2035 *ximg = *pixmap;
2036 return 1;
2037#endif
4ef0d4d0
KS
2038}
2039
2040
2041/* Destroy XImage XIMG. Free XIMG->data. */
2042
2043static void
d3da34e0 2044x_destroy_x_image (XImagePtr ximg)
4ef0d4d0 2045{
4d7e6e51 2046 eassert (input_blocked_p ());
4ef0d4d0
KS
2047 if (ximg)
2048 {
2049#ifdef HAVE_X_WINDOWS
2050 xfree (ximg->data);
2051 ximg->data = NULL;
2052 XDestroyImage (ximg);
2053#endif /* HAVE_X_WINDOWS */
2054#ifdef HAVE_NTGUI
2055 /* Data will be freed by DestroyObject. */
2056 ximg->data = NULL;
2057 xfree (ximg);
2058#endif /* HAVE_NTGUI */
edfda783 2059#ifdef HAVE_NS
ed3751c8 2060 ns_release_object (ximg);
edfda783 2061#endif /* HAVE_NS */
4ef0d4d0
KS
2062 }
2063}
2064
2065
2066/* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2067 are width and height of both the image and pixmap. */
2068
2069static void
d3da34e0 2070x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
4ef0d4d0
KS
2071{
2072#ifdef HAVE_X_WINDOWS
2073 GC gc;
2074
4d7e6e51 2075 eassert (input_blocked_p ());
4ef0d4d0
KS
2076 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2077 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2078 XFreeGC (FRAME_X_DISPLAY (f), gc);
2079#endif /* HAVE_X_WINDOWS */
2080
2081#ifdef HAVE_NTGUI
2082#if 0 /* I don't think this is necessary looking at where it is used. */
2083 HDC hdc = get_frame_dc (f);
2084 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2085 release_frame_dc (f, hdc);
2086#endif
2087#endif /* HAVE_NTGUI */
2088
edfda783 2089#ifdef HAVE_NS
a54e2c05 2090 eassert (ximg == pixmap);
ed3751c8 2091 ns_retain_object (ximg);
edfda783 2092#endif
4ef0d4d0
KS
2093}
2094
2095\f
2096/***********************************************************************
2097 File Handling
2098 ***********************************************************************/
2099
6678dc11 2100/* Find image file FILE. Look in data-directory/images, then
022af124
KH
2101 x-bitmap-file-path. Value is the encoded full name of the file
2102 found, or nil if not found. */
4ef0d4d0 2103
c640aa9b 2104Lisp_Object
d3da34e0 2105x_find_image_file (Lisp_Object file)
4ef0d4d0
KS
2106{
2107 Lisp_Object file_found, search_path;
4ef0d4d0
KS
2108 int fd;
2109
6678dc11
GM
2110 /* TODO I think this should use something like image-load-path
2111 instead. Unfortunately, that can contain non-string elements. */
2112 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2113 Vdata_directory),
2114 Vx_bitmap_file_path);
4ef0d4d0 2115
050b82f6 2116 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
4ef0d4d0
KS
2117 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2118
2119 if (fd == -1)
2120 file_found = Qnil;
2121 else
022af124
KH
2122 {
2123 file_found = ENCODE_FILE (file_found);
2124 close (fd);
2125 }
4ef0d4d0 2126
4ef0d4d0
KS
2127 return file_found;
2128}
2129
2130
2131/* Read FILE into memory. Value is a pointer to a buffer allocated
2132 with xmalloc holding FILE's contents. Value is null if an error
2133 occurred. *SIZE is set to the size of the file. */
2134
2135static unsigned char *
dd52fcea 2136slurp_file (char *file, ptrdiff_t *size)
4ef0d4d0 2137{
d6453ce4 2138 FILE *fp = fopen (file, "rb");
4ef0d4d0
KS
2139 unsigned char *buf = NULL;
2140 struct stat st;
2141
d6453ce4 2142 if (fp && fstat (fileno (fp), &st) == 0
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
0fda9b75 2900#ifdef HAVE_NTGUI
44b1dc2e
JR
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
a9e7a9d5 3011#if defined HAVE_NTGUI && defined WINDOWSNT
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
0fda9b75 3210#ifdef WINDOWSNT
4ef0d4d0
KS
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
0fda9b75 3236#endif /* WINDOWSNT */
4ef0d4d0 3237
a9e7a9d5 3238#if defined HAVE_NTGUI && !defined WINDOWSNT
0fda9b75
DC
3239/* Glue for code below */
3240#define fn_XpmReadFileToImage XpmReadFileToImage
3241#define fn_XpmCreateImageFromBuffer XpmCreateImageFromBuffer
3242#define fn_XImageFree XImageFree
3243#define fn_XpmFreeAttributes XpmFreeAttributes
2ae3a8a7 3244#endif /* HAVE_NTGUI && !WINDOWSNT */
4ef0d4d0 3245
578098f3 3246/* Value is true if COLOR_SYMBOLS is a valid color symbols list
4ef0d4d0
KS
3247 for XPM images. Such a list must consist of conses whose car and
3248 cdr are strings. */
3249
578098f3 3250static bool
d3da34e0 3251xpm_valid_color_symbols_p (Lisp_Object color_symbols)
4ef0d4d0
KS
3252{
3253 while (CONSP (color_symbols))
3254 {
3255 Lisp_Object sym = XCAR (color_symbols);
3256 if (!CONSP (sym)
3257 || !STRINGP (XCAR (sym))
3258 || !STRINGP (XCDR (sym)))
3259 break;
3260 color_symbols = XCDR (color_symbols);
3261 }
3262
3263 return NILP (color_symbols);
3264}
3265
3266
578098f3 3267/* Value is true if OBJECT is a valid XPM image specification. */
4ef0d4d0 3268
578098f3 3269static bool
d3da34e0 3270xpm_image_p (Lisp_Object object)
4ef0d4d0
KS
3271{
3272 struct image_keyword fmt[XPM_LAST];
72af86bd 3273 memcpy (fmt, xpm_format, sizeof fmt);
4ef0d4d0
KS
3274 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3275 /* Either `:file' or `:data' must be present. */
3276 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3277 /* Either no `:color-symbols' or it's a list of conses
3278 whose car and cdr are strings. */
3279 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3280 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3281}
3282
9e2a2647 3283#endif /* HAVE_XPM || HAVE_NS */
4ef0d4d0 3284
cd44d2eb 3285#if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
0766b489 3286ptrdiff_t
ef1b0ba7 3287x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
786a43d6
CY
3288{
3289 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
0766b489
PE
3290 ptrdiff_t id;
3291 int rc;
786a43d6
CY
3292 XpmAttributes attrs;
3293 Pixmap bitmap, mask;
3294
72af86bd 3295 memset (&attrs, 0, sizeof attrs);
786a43d6 3296
54188d8f
CY
3297 attrs.visual = FRAME_X_VISUAL (f);
3298 attrs.colormap = FRAME_X_COLORMAP (f);
3299 attrs.valuemask |= XpmVisual;
3300 attrs.valuemask |= XpmColormap;
3301
786a43d6 3302 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
f77fabaf 3303 (char **) bits, &bitmap, &mask, &attrs);
786a43d6 3304 if (rc != XpmSuccess)
fe45ad15
CY
3305 {
3306 XpmFreeAttributes (&attrs);
3307 return -1;
3308 }
786a43d6
CY
3309
3310 id = x_allocate_bitmap_record (f);
786a43d6
CY
3311 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3312 dpyinfo->bitmaps[id - 1].have_mask = 1;
3313 dpyinfo->bitmaps[id - 1].mask = mask;
3314 dpyinfo->bitmaps[id - 1].file = NULL;
3315 dpyinfo->bitmaps[id - 1].height = attrs.height;
3316 dpyinfo->bitmaps[id - 1].width = attrs.width;
3317 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3318 dpyinfo->bitmaps[id - 1].refcount = 1;
3319
3320 XpmFreeAttributes (&attrs);
3321 return id;
3322}
0d876a14 3323#endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
786a43d6 3324
4ef0d4d0 3325/* Load image IMG which will be displayed on frame F. Value is
578098f3 3326 true if successful. */
4ef0d4d0 3327
ea1aaa6f
ST
3328#ifdef HAVE_XPM
3329
578098f3 3330static bool
d3da34e0 3331xpm_load (struct frame *f, struct image *img)
4ef0d4d0
KS
3332{
3333 int rc;
3334 XpmAttributes attrs;
3335 Lisp_Object specified_file, color_symbols;
3336#ifdef HAVE_NTGUI
3337 HDC hdc;
3338 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3339#endif /* HAVE_NTGUI */
3340
3341 /* Configure the XPM lib. Use the visual of frame F. Allocate
3342 close colors. Return colors allocated. */
72af86bd 3343 memset (&attrs, 0, sizeof attrs);
4ef0d4d0
KS
3344
3345#ifndef HAVE_NTGUI
3346 attrs.visual = FRAME_X_VISUAL (f);
3347 attrs.colormap = FRAME_X_COLORMAP (f);
3348 attrs.valuemask |= XpmVisual;
3349 attrs.valuemask |= XpmColormap;
3350#endif /* HAVE_NTGUI */
3351
3352#ifdef ALLOC_XPM_COLORS
3353 /* Allocate colors with our own functions which handle
3354 failing color allocation more gracefully. */
3355 attrs.color_closure = f;
3356 attrs.alloc_color = xpm_alloc_color;
3357 attrs.free_colors = xpm_free_colors;
3358 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3359#else /* not ALLOC_XPM_COLORS */
3360 /* Let the XPM lib allocate colors. */
3361 attrs.valuemask |= XpmReturnAllocPixels;
3362#ifdef XpmAllocCloseColors
3363 attrs.alloc_close_colors = 1;
3364 attrs.valuemask |= XpmAllocCloseColors;
3365#else /* not XpmAllocCloseColors */
3366 attrs.closeness = 600;
3367 attrs.valuemask |= XpmCloseness;
3368#endif /* not XpmAllocCloseColors */
3369#endif /* ALLOC_XPM_COLORS */
3370
3371 /* If image specification contains symbolic color definitions, add
3372 these to `attrs'. */
3373 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3374 if (CONSP (color_symbols))
3375 {
3376 Lisp_Object tail;
3377 XpmColorSymbol *xpm_syms;
3378 int i, size;
3379
3380 attrs.valuemask |= XpmColorSymbols;
3381
3382 /* Count number of symbols. */
3383 attrs.numsymbols = 0;
3384 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3385 ++attrs.numsymbols;
3386
3387 /* Allocate an XpmColorSymbol array. */
3388 size = attrs.numsymbols * sizeof *xpm_syms;
38182d90 3389 xpm_syms = alloca (size);
72af86bd 3390 memset (xpm_syms, 0, size);
4ef0d4d0
KS
3391 attrs.colorsymbols = xpm_syms;
3392
3393 /* Fill the color symbol array. */
3394 for (tail = color_symbols, i = 0;
3395 CONSP (tail);
3396 ++i, tail = XCDR (tail))
3397 {
7574650a
AS
3398 Lisp_Object name;
3399 Lisp_Object color;
e22cffbc 3400 char *empty_string = (char *) "";
7574650a
AS
3401
3402 if (!CONSP (XCAR (tail)))
3403 {
e22cffbc
PE
3404 xpm_syms[i].name = empty_string;
3405 xpm_syms[i].value = empty_string;
7574650a
AS
3406 continue;
3407 }
3408 name = XCAR (XCAR (tail));
3409 color = XCDR (XCAR (tail));
3410 if (STRINGP (name))
3411 {
38182d90 3412 xpm_syms[i].name = alloca (SCHARS (name) + 1);
42a5b22f 3413 strcpy (xpm_syms[i].name, SSDATA (name));
7574650a
AS
3414 }
3415 else
e22cffbc 3416 xpm_syms[i].name = empty_string;
7574650a
AS
3417 if (STRINGP (color))
3418 {
38182d90 3419 xpm_syms[i].value = alloca (SCHARS (color) + 1);
42a5b22f 3420 strcpy (xpm_syms[i].value, SSDATA (color));
7574650a
AS
3421 }
3422 else
e22cffbc 3423 xpm_syms[i].value = empty_string;
4ef0d4d0
KS
3424 }
3425 }
3426
3427 /* Create a pixmap for the image, either from a file, or from a
3428 string buffer containing data in the same format as an XPM file. */
3429#ifdef ALLOC_XPM_COLORS
3430 xpm_init_color_cache (f, &attrs);
3431#endif
3432
3433 specified_file = image_spec_value (img->spec, QCfile, NULL);
3434
3435#ifdef HAVE_NTGUI
3436 {
3437 HDC frame_dc = get_frame_dc (f);
3438 hdc = CreateCompatibleDC (frame_dc);
3439 release_frame_dc (f, frame_dc);
3440 }
3441#endif /* HAVE_NTGUI */
3442
3443 if (STRINGP (specified_file))
3444 {
3445 Lisp_Object file = x_find_image_file (specified_file);
3446 if (!STRINGP (file))
3447 {
3448 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7574650a
AS
3449#ifdef ALLOC_XPM_COLORS
3450 xpm_free_color_cache ();
3451#endif
4ef0d4d0
KS
3452 return 0;
3453 }
3454
3455#ifdef HAVE_NTGUI
3456 /* XpmReadFileToPixmap is not available in the Windows port of
3457 libxpm. But XpmReadFileToImage almost does what we want. */
3458 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3459 &xpm_image, &xpm_mask,
3460 &attrs);
3461#else
3462 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
42a5b22f 3463 SSDATA (file), &img->pixmap, &img->mask,
4ef0d4d0
KS
3464 &attrs);
3465#endif /* HAVE_NTGUI */
3466 }
3467 else
3468 {
3469 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
7574650a
AS
3470 if (!STRINGP (buffer))
3471 {
3472 image_error ("Invalid image data `%s'", buffer, Qnil);
3473#ifdef ALLOC_XPM_COLORS
3474 xpm_free_color_cache ();
3475#endif
3476 return 0;
3477 }
4ef0d4d0
KS
3478#ifdef HAVE_NTGUI
3479 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3480 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3481 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3482 &xpm_image, &xpm_mask,
3483 &attrs);
3484#else
3485 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
42a5b22f 3486 SSDATA (buffer),
4ef0d4d0
KS
3487 &img->pixmap, &img->mask,
3488 &attrs);
3489#endif /* HAVE_NTGUI */
3490 }
3491
3492 if (rc == XpmSuccess)
3493 {
3494#if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3495 img->colors = colors_in_color_table (&img->ncolors);
3496#else /* not ALLOC_XPM_COLORS */
3497 int i;
3498
3499#ifdef HAVE_NTGUI
3500 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3501 plus some duplicate attributes. */
3502 if (xpm_image && xpm_image->bitmap)
3503 {
3504 img->pixmap = xpm_image->bitmap;
3505 /* XImageFree in libXpm frees XImage struct without destroying
3506 the bitmap, which is what we want. */
3507 fn_XImageFree (xpm_image);
3508 }
3509 if (xpm_mask && xpm_mask->bitmap)
3510 {
3511 /* The mask appears to be inverted compared with what we expect.
3512 TODO: invert our expectations. See other places where we
3513 have to invert bits because our idea of masks is backwards. */
3514 HGDIOBJ old_obj;
3515 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3516
3517 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3518 SelectObject (hdc, old_obj);
3519
3520 img->mask = xpm_mask->bitmap;
3521 fn_XImageFree (xpm_mask);
3522 DeleteDC (hdc);
3523 }
3524
3525 DeleteDC (hdc);
3526#endif /* HAVE_NTGUI */
3527
3528 /* Remember allocated colors. */
0065d054 3529 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
ddff3151 3530 img->ncolors = attrs.nalloc_pixels;
4ef0d4d0
KS
3531 for (i = 0; i < attrs.nalloc_pixels; ++i)
3532 {
3533 img->colors[i] = attrs.alloc_pixels[i];
3534#ifdef DEBUG_X_COLORS
3535 register_color (img->colors[i]);
3536#endif
3537 }
3538#endif /* not ALLOC_XPM_COLORS */
3539
3540 img->width = attrs.width;
3541 img->height = attrs.height;
a54e2c05 3542 eassert (img->width > 0 && img->height > 0);
4ef0d4d0
KS
3543
3544 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3545#ifdef HAVE_NTGUI
3546 fn_XpmFreeAttributes (&attrs);
3547#else
3548 XpmFreeAttributes (&attrs);
3549#endif /* HAVE_NTGUI */
3550 }
3551 else
3552 {
3553#ifdef HAVE_NTGUI
3554 DeleteDC (hdc);
3555#endif /* HAVE_NTGUI */
3556
3557 switch (rc)
3558 {
3559 case XpmOpenFailed:
3560 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3561 break;
3562
3563 case XpmFileInvalid:
3564 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3565 break;
3566
3567 case XpmNoMemory:
3568 image_error ("Out of memory (%s)", img->spec, Qnil);
3569 break;
3570
3571 case XpmColorFailed:
3572 image_error ("Color allocation error (%s)", img->spec, Qnil);
3573 break;
3574
3575 default:
3576 image_error ("Unknown error (%s)", img->spec, Qnil);
3577 break;
3578 }
3579 }
3580
3581#ifdef ALLOC_XPM_COLORS
3582 xpm_free_color_cache ();
3583#endif
3584 return rc == XpmSuccess;
3585}
3586
3587#endif /* HAVE_XPM */
3588
9e2a2647 3589#if defined (HAVE_NS) && !defined (HAVE_XPM)
ea1aaa6f 3590
9e2a2647 3591/* XPM support functions for NS where libxpm is not available.
ea1aaa6f
ST
3592 Only XPM version 3 (without any extensions) is supported. */
3593
f57e2426
J
3594static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3595 int, Lisp_Object);
3596static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3597 const unsigned char *, int);
f57e2426
J
3598static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3599 int, Lisp_Object);
3600static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3601 const unsigned char *, int);
ea1aaa6f
ST
3602
3603/* Tokens returned from xpm_scan. */
3604
3605enum xpm_token
3606{
3607 XPM_TK_IDENT = 256,
3608 XPM_TK_STRING,
3609 XPM_TK_EOF
3610};
3611
3612/* Scan an XPM data and return a character (< 256) or a token defined
3613 by enum xpm_token above. *S and END are the start (inclusive) and
3614 the end (exclusive) addresses of the data, respectively. Advance
3615 *S while scanning. If token is either XPM_TK_IDENT or
3616 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3617 length of the corresponding token, respectively. */
3618
3619static int
3d608a86
J
3620xpm_scan (const unsigned char **s,
3621 const unsigned char *end,
3622 const unsigned char **beg,
74ca2eb3 3623 ptrdiff_t *len)
ea1aaa6f
ST
3624{
3625 int c;
3626
3627 while (*s < end)
3628 {
3629 /* Skip white-space. */
620f13b0 3630 while (*s < end && (c = *(*s)++, c_isspace (c)))
9ecf6403 3631 ;
ea1aaa6f
ST
3632
3633 /* gnus-pointer.xpm uses '-' in its identifier.
9ecf6403 3634 sb-dir-plus.xpm uses '+' in its identifier. */
620f13b0 3635 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
9ecf6403
YM
3636 {
3637 *beg = *s - 1;
2ff0845e 3638 while (*s < end
620f13b0
PE
3639 && (c = **s, c_isalnum (c)
3640 || c == '_' || c == '-' || c == '+'))
9ecf6403
YM
3641 ++*s;
3642 *len = *s - *beg;
3643 return XPM_TK_IDENT;
3644 }
ea1aaa6f 3645 else if (c == '"')
9ecf6403
YM
3646 {
3647 *beg = *s;
3648 while (*s < end && **s != '"')
3649 ++*s;
3650 *len = *s - *beg;
3651 if (*s < end)
3652 ++*s;
3653 return XPM_TK_STRING;
3654 }
ea1aaa6f 3655 else if (c == '/')
9ecf6403
YM
3656 {
3657 if (*s < end && **s == '*')
3658 {
3659 /* C-style comment. */
3660 ++*s;
3661 do
3662 {
3663 while (*s < end && *(*s)++ != '*')
3664 ;
3665 }
3666 while (*s < end && **s != '/');
3667 if (*s < end)
3668 ++*s;
3669 }
3670 else
3671 return c;
3672 }
ea1aaa6f 3673 else
9ecf6403 3674 return c;
ea1aaa6f
ST
3675 }
3676
3677 return XPM_TK_EOF;
3678}
3679
bbe6f2aa 3680/* Functions for color table lookup in XPM data. A key is a string
ea1aaa6f
ST
3681 specifying the color of each pixel in XPM data. A value is either
3682 an integer that specifies a pixel color, Qt that specifies
3683 transparency, or Qnil for the unspecified color. If the length of
3684 the key string is one, a vector is used as a table. Otherwise, a
3685 hash table is used. */
3686
3687static Lisp_Object
3d608a86
J
3688xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3689 const unsigned char *,
3690 int,
3691 Lisp_Object),
3692 Lisp_Object (**get_func) (Lisp_Object,
3693 const unsigned char *,
3694 int))
ea1aaa6f
ST
3695{
3696 *put_func = xpm_put_color_table_v;
3697 *get_func = xpm_get_color_table_v;
3698 return Fmake_vector (make_number (256), Qnil);
3699}
3700
3701static void
3d608a86
J
3702xpm_put_color_table_v (Lisp_Object color_table,
3703 const unsigned char *chars_start,
3704 int chars_len,
3705 Lisp_Object color)
ea1aaa6f 3706{
28be1ada 3707 ASET (color_table, *chars_start, color);
ea1aaa6f
ST
3708}
3709
3710static Lisp_Object
3d608a86
J
3711xpm_get_color_table_v (Lisp_Object color_table,
3712 const unsigned char *chars_start,
3713 int chars_len)
ea1aaa6f 3714{
28be1ada 3715 return AREF (color_table, *chars_start);
ea1aaa6f
ST
3716}
3717
3718static Lisp_Object
3d608a86
J
3719xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3720 const unsigned char *,
3721 int,
3722 Lisp_Object),
3723 Lisp_Object (**get_func) (Lisp_Object,
3724 const unsigned char *,
3725 int))
ea1aaa6f
ST
3726{
3727 *put_func = xpm_put_color_table_h;
3728 *get_func = xpm_get_color_table_h;
4ab15c3e 3729 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
9ecf6403
YM
3730 make_float (DEFAULT_REHASH_SIZE),
3731 make_float (DEFAULT_REHASH_THRESHOLD),
a23c4171 3732 Qnil);
ea1aaa6f
ST
3733}
3734
3735static void
3d608a86
J
3736xpm_put_color_table_h (Lisp_Object color_table,
3737 const unsigned char *chars_start,
3738 int chars_len,
3739 Lisp_Object color)
ea1aaa6f
ST
3740{
3741 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
0de4bb68 3742 EMACS_UINT hash_code;
ea1aaa6f
ST
3743 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3744
3745 hash_lookup (table, chars, &hash_code);
3746 hash_put (table, chars, color, hash_code);
3747}
3748
3749static Lisp_Object
3d608a86
J
3750xpm_get_color_table_h (Lisp_Object color_table,
3751 const unsigned char *chars_start,
3752 int chars_len)
ea1aaa6f
ST
3753{
3754 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
d3411f89
PE
3755 ptrdiff_t i =
3756 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
ea1aaa6f
ST
3757
3758 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3759}
3760
3761enum xpm_color_key {
3762 XPM_COLOR_KEY_S,
3763 XPM_COLOR_KEY_M,
3764 XPM_COLOR_KEY_G4,
3765 XPM_COLOR_KEY_G,
3766 XPM_COLOR_KEY_C
3767};
3768
46accb8f 3769static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
ea1aaa6f
ST
3770
3771static int
3d608a86 3772xpm_str_to_color_key (const char *s)
ea1aaa6f
ST
3773{
3774 int i;
3775
3776 for (i = 0;
3777 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3778 i++)
3779 if (strcmp (xpm_color_key_strings[i], s) == 0)
3780 return i;
3781 return -1;
3782}
3783
578098f3 3784static bool
3d608a86
J
3785xpm_load_image (struct frame *f,
3786 struct image *img,
3787 const unsigned char *contents,
3788 const unsigned char *end)
ea1aaa6f 3789{
46accb8f 3790 const unsigned char *s = contents, *beg, *str;
ea1aaa6f
ST
3791 unsigned char buffer[BUFSIZ];
3792 int width, height, x, y;
3793 int num_colors, chars_per_pixel;
74ca2eb3
PE
3794 ptrdiff_t len;
3795 int LA1;
46accb8f
YM
3796 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3797 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
ea1aaa6f 3798 Lisp_Object frame, color_symbols, color_table;
578098f3
PE
3799 int best_key;
3800 bool have_mask = 0;
ea1aaa6f
ST
3801 XImagePtr ximg = NULL, mask_img = NULL;
3802
3803#define match() \
3804 LA1 = xpm_scan (&s, end, &beg, &len)
3805
9ecf6403
YM
3806#define expect(TOKEN) \
3807 if (LA1 != (TOKEN)) \
3808 goto failure; \
3809 else \
ea1aaa6f
ST
3810 match ()
3811
9ecf6403 3812#define expect_ident(IDENT) \
ea1aaa6f 3813 if (LA1 == XPM_TK_IDENT \
9ecf6403
YM
3814 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3815 match (); \
3816 else \
ea1aaa6f
ST
3817 goto failure
3818
3819 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3820 goto failure;
3821 s += 9;
ed3751c8 3822 match ();
ea1aaa6f
ST
3823 expect_ident ("static");
3824 expect_ident ("char");
3825 expect ('*');
3826 expect (XPM_TK_IDENT);
3827 expect ('[');
3828 expect (']');
3829 expect ('=');
3830 expect ('{');
3831 expect (XPM_TK_STRING);
3832 if (len >= BUFSIZ)
3833 goto failure;
3834 memcpy (buffer, beg, len);
3835 buffer[len] = '\0';
3836 if (sscanf (buffer, "%d %d %d %d", &width, &height,
9ecf6403 3837 &num_colors, &chars_per_pixel) != 4
ea1aaa6f
ST
3838 || width <= 0 || height <= 0
3839 || num_colors <= 0 || chars_per_pixel <= 0)
3840 goto failure;
de297941
YM
3841
3842 if (!check_image_size (f, width, height))
3843 {
10ea2b82 3844 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
de297941
YM
3845 goto failure;
3846 }
3847
ca4aa935
PE
3848 if (!x_create_x_image_and_pixmap (f, width, height, 0,
3849 &ximg, &img->pixmap)
3850#ifndef HAVE_NS
3851 || !x_create_x_image_and_pixmap (f, width, height, 1,
3852 &mask_img, &img->mask)
3853#endif
3854 )
3855 {
3856 image_error ("Image too large", Qnil, Qnil);
3857 goto failure;
3858 }
3859
ea1aaa6f
ST
3860 expect (',');
3861
3862 XSETFRAME (frame, f);
3863 if (!NILP (Fxw_display_color_p (frame)))
3864 best_key = XPM_COLOR_KEY_C;
3865 else if (!NILP (Fx_display_grayscale_p (frame)))
3866 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
9ecf6403 3867 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
ea1aaa6f
ST
3868 else
3869 best_key = XPM_COLOR_KEY_M;
3870
3871 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3872 if (chars_per_pixel == 1)
3873 color_table = xpm_make_color_table_v (&put_color_table,
9ecf6403 3874 &get_color_table);
ea1aaa6f
ST
3875 else
3876 color_table = xpm_make_color_table_h (&put_color_table,
9ecf6403 3877 &get_color_table);
ea1aaa6f
ST
3878
3879 while (num_colors-- > 0)
3880 {
25a48bd0 3881 char *color, *max_color;
ea1aaa6f
ST
3882 int key, next_key, max_key = 0;
3883 Lisp_Object symbol_color = Qnil, color_val;
3884 XColor cdef;
3885
3886 expect (XPM_TK_STRING);
3887 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
9ecf6403 3888 goto failure;
ea1aaa6f
ST
3889 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
3890 buffer[len - chars_per_pixel] = '\0';
3891
3892 str = strtok (buffer, " \t");
3893 if (str == NULL)
9ecf6403 3894 goto failure;
ea1aaa6f
ST
3895 key = xpm_str_to_color_key (str);
3896 if (key < 0)
9ecf6403 3897 goto failure;
ea1aaa6f 3898 do
9ecf6403
YM
3899 {
3900 color = strtok (NULL, " \t");
3901 if (color == NULL)
3902 goto failure;
ea1aaa6f 3903
9db94f82 3904 while ((str = strtok (NULL, " \t")) != NULL)
9ecf6403
YM
3905 {
3906 next_key = xpm_str_to_color_key (str);
3907 if (next_key >= 0)
3908 break;
3909 color[strlen (color)] = ' ';
3910 }
ea1aaa6f 3911
9ecf6403
YM
3912 if (key == XPM_COLOR_KEY_S)
3913 {
3914 if (NILP (symbol_color))
3915 symbol_color = build_string (color);
3916 }
3917 else if (max_key < key && key <= best_key)
3918 {
3919 max_key = key;
3920 max_color = color;
3921 }
3922 key = next_key;
3923 }
ea1aaa6f
ST
3924 while (str);
3925
3926 color_val = Qnil;
3927 if (!NILP (color_symbols) && !NILP (symbol_color))
9ecf6403
YM
3928 {
3929 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
3930
3931 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
9db94f82 3932 {
25a48bd0 3933 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
9db94f82 3934 color_val = Qt;
6045c4fd 3935 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
9db94f82
YM
3936 &cdef, 0))
3937 color_val = make_number (cdef.pixel);
3938 }
9ecf6403 3939 }
ea1aaa6f 3940 if (NILP (color_val) && max_key > 0)
9db94f82 3941 {
05131107 3942 if (xstrcasecmp (max_color, "None") == 0)
9db94f82
YM
3943 color_val = Qt;
3944 else if (x_defined_color (f, max_color, &cdef, 0))
3945 color_val = make_number (cdef.pixel);
3946 }
ea1aaa6f 3947 if (!NILP (color_val))
9ecf6403 3948 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
ea1aaa6f
ST
3949
3950 expect (',');
3951 }
3952
ea1aaa6f
ST
3953 for (y = 0; y < height; y++)
3954 {
3955 expect (XPM_TK_STRING);
3956 str = beg;
3957 if (len < width * chars_per_pixel)
9ecf6403 3958 goto failure;
ea1aaa6f 3959 for (x = 0; x < width; x++, str += chars_per_pixel)
9ecf6403
YM
3960 {
3961 Lisp_Object color_val =
3962 (*get_color_table) (color_table, str, chars_per_pixel);
3963
3964 XPutPixel (ximg, x, y,
3965 (INTEGERP (color_val) ? XINT (color_val)
3966 : FRAME_FOREGROUND_PIXEL (f)));
edfda783 3967#ifndef HAVE_NS
9ecf6403
YM
3968 XPutPixel (mask_img, x, y,
3969 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
3970 : (have_mask = 1, PIX_MASK_RETAIN)));
edfda783 3971#else
ed3751c8
JB
3972 if (EQ (color_val, Qt))
3973 ns_set_alpha (ximg, x, y, 0);
edfda783 3974#endif
9ecf6403 3975 }
ea1aaa6f 3976 if (y + 1 < height)
9ecf6403 3977 expect (',');
ea1aaa6f
ST
3978 }
3979
3980 img->width = width;
3981 img->height = height;
3982
0b8ac842
YM
3983 /* Maybe fill in the background field while we have ximg handy. */
3984 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
3985 IMAGE_BACKGROUND (img, f, ximg);
3986
ea1aaa6f
ST
3987 x_put_x_image (f, ximg, img->pixmap, width, height);
3988 x_destroy_x_image (ximg);
edfda783 3989#ifndef HAVE_NS
ea1aaa6f
ST
3990 if (have_mask)
3991 {
9ecf6403
YM
3992 /* Fill in the background_transparent field while we have the
3993 mask handy. */
3994 image_background_transparent (img, f, mask_img);
3995
ea1aaa6f
ST
3996 x_put_x_image (f, mask_img, img->mask, width, height);
3997 x_destroy_x_image (mask_img);
3998 }
3999 else
4000 {
4001 x_destroy_x_image (mask_img);
4002 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4003 img->mask = NO_PIXMAP;
4004 }
edfda783 4005#endif
ea1aaa6f
ST
4006 return 1;
4007
4008 failure:
4009 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
ea1aaa6f
ST
4010 x_destroy_x_image (ximg);
4011 x_destroy_x_image (mask_img);
4012 x_clear_image (f, img);
4013 return 0;
4014
4015#undef match
4016#undef expect
4017#undef expect_ident
4018}
4019
578098f3 4020static bool
3d608a86
J
4021xpm_load (struct frame *f,
4022 struct image *img)
ea1aaa6f 4023{
578098f3 4024 bool success_p = 0;
ea1aaa6f
ST
4025 Lisp_Object file_name;
4026
4027 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4028 file_name = image_spec_value (img->spec, QCfile, NULL);
4029 if (STRINGP (file_name))
4030 {
4031 Lisp_Object file;
4032 unsigned char *contents;
dd52fcea 4033 ptrdiff_t size;
ea1aaa6f
ST
4034
4035 file = x_find_image_file (file_name);
ea1aaa6f 4036 if (!STRINGP (file))
9ecf6403
YM
4037 {
4038 image_error ("Cannot find image file `%s'", file_name, Qnil);
9ecf6403
YM
4039 return 0;
4040 }
ea1aaa6f 4041
6045c4fd 4042 contents = slurp_file (SSDATA (file), &size);
ea1aaa6f 4043 if (contents == NULL)
9ecf6403
YM
4044 {
4045 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
9ecf6403
YM
4046 return 0;
4047 }
ea1aaa6f
ST
4048
4049 success_p = xpm_load_image (f, img, contents, contents + size);
4050 xfree (contents);
ea1aaa6f
ST
4051 }
4052 else
4053 {
4054 Lisp_Object data;
4055
4056 data = image_spec_value (img->spec, QCdata, NULL);
7574650a
AS
4057 if (!STRINGP (data))
4058 {
4059 image_error ("Invalid image data `%s'", data, Qnil);
4060 return 0;
4061 }
ea1aaa6f 4062 success_p = xpm_load_image (f, img, SDATA (data),
9ecf6403 4063 SDATA (data) + SBYTES (data));
ea1aaa6f
ST
4064 }
4065
4066 return success_p;
4067}
4068
9e2a2647 4069#endif /* HAVE_NS && !HAVE_XPM */
b0da69a7 4070
ea1aaa6f 4071
4ef0d4d0
KS
4072\f
4073/***********************************************************************
4074 Color table
4075 ***********************************************************************/
4076
4077#ifdef COLOR_TABLE_SUPPORT
4078
4079/* An entry in the color table mapping an RGB color to a pixel color. */
4080
4081struct ct_color
4082{
4083 int r, g, b;
4084 unsigned long pixel;
4085
4086 /* Next in color table collision list. */
4087 struct ct_color *next;
4088};
4089
4090/* The bucket vector size to use. Must be prime. */
4091
4092#define CT_SIZE 101
4093
4094/* Value is a hash of the RGB color given by R, G, and B. */
4095
4096#define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4097
4098/* The color hash table. */
4099
cd44d2eb 4100static struct ct_color **ct_table;
4ef0d4d0
KS
4101
4102/* Number of entries in the color table. */
4103
cd44d2eb 4104static int ct_colors_allocated;
ddff3151
PE
4105enum
4106{
4107 ct_colors_allocated_max =
4108 min (INT_MAX,
4109 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4110};
4ef0d4d0
KS
4111
4112/* Initialize the color table. */
4113
4114static void
d3da34e0 4115init_color_table (void)
4ef0d4d0
KS
4116{
4117 int size = CT_SIZE * sizeof (*ct_table);
23f86fce 4118 ct_table = xzalloc (size);
4ef0d4d0
KS
4119 ct_colors_allocated = 0;
4120}
4121
4122
4123/* Free memory associated with the color table. */
4124
4125static void
d3da34e0 4126free_color_table (void)
4ef0d4d0
KS
4127{
4128 int i;
4129 struct ct_color *p, *next;
4130
4131 for (i = 0; i < CT_SIZE; ++i)
4132 for (p = ct_table[i]; p; p = next)
4133 {
4134 next = p->next;
4135 xfree (p);
4136 }
4137
4138 xfree (ct_table);
4139 ct_table = NULL;
4140}
4141
4142
4143/* Value is a pixel color for RGB color R, G, B on frame F. If an
4144 entry for that color already is in the color table, return the
4145 pixel color of that entry. Otherwise, allocate a new color for R,
4146 G, B, and make an entry in the color table. */
4147
4148static unsigned long
d3da34e0 4149lookup_rgb_color (struct frame *f, int r, int g, int b)
4ef0d4d0
KS
4150{
4151 unsigned hash = CT_HASH_RGB (r, g, b);
4152 int i = hash % CT_SIZE;
4153 struct ct_color *p;
4154 Display_Info *dpyinfo;
4155
4156 /* Handle TrueColor visuals specially, which improves performance by
4157 two orders of magnitude. Freeing colors on TrueColor visuals is
4158 a nop, and pixel colors specify RGB values directly. See also
4159 the Xlib spec, chapter 3.1. */
4160 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4161 if (dpyinfo->red_bits > 0)
4162 {
4163 unsigned long pr, pg, pb;
4164
4165 /* Apply gamma-correction like normal color allocation does. */
4166 if (f->gamma)
4167 {
4168 XColor color;
4169 color.red = r, color.green = g, color.blue = b;
4170 gamma_correct (f, &color);
4171 r = color.red, g = color.green, b = color.blue;
4172 }
4173
4174 /* Scale down RGB values to the visual's bits per RGB, and shift
4175 them to the right position in the pixel color. Note that the
4176 original RGB values are 16-bit values, as usual in X. */
4177 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4178 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4179 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4180
4181 /* Assemble the pixel color. */
4182 return pr | pg | pb;
4183 }
1f026899 4184
4ef0d4d0
KS
4185 for (p = ct_table[i]; p; p = p->next)
4186 if (p->r == r && p->g == g && p->b == b)
4187 break;
4188
4189 if (p == NULL)
4190 {
4191
4192#ifdef HAVE_X_WINDOWS
4193 XColor color;
4194 Colormap cmap;
578098f3 4195 bool rc;
ddff3151
PE
4196#else
4197 COLORREF color;
4198#endif
4ef0d4d0 4199
ddff3151
PE
4200 if (ct_colors_allocated_max <= ct_colors_allocated)
4201 return FRAME_FOREGROUND_PIXEL (f);
4202
4203#ifdef HAVE_X_WINDOWS
4ef0d4d0
KS
4204 color.red = r;
4205 color.green = g;
4206 color.blue = b;
4207
4208 cmap = FRAME_X_COLORMAP (f);
4209 rc = x_alloc_nearest_color (f, cmap, &color);
4210 if (rc)
4211 {
4212 ++ct_colors_allocated;
23f86fce 4213 p = xmalloc (sizeof *p);
4ef0d4d0
KS
4214 p->r = r;
4215 p->g = g;
4216 p->b = b;
4217 p->pixel = color.pixel;
4218 p->next = ct_table[i];
4219 ct_table[i] = p;
4220 }
4221 else
4222 return FRAME_FOREGROUND_PIXEL (f);
4223
4224#else
4ef0d4d0
KS
4225#ifdef HAVE_NTGUI
4226 color = PALETTERGB (r, g, b);
4227#else
4228 color = RGB_TO_ULONG (r, g, b);
4229#endif /* HAVE_NTGUI */
4230 ++ct_colors_allocated;
23f86fce 4231 p = xmalloc (sizeof *p);
4ef0d4d0
KS
4232 p->r = r;
4233 p->g = g;
4234 p->b = b;
4235 p->pixel = color;
4236 p->next = ct_table[i];
4237 ct_table[i] = p;
4238#endif /* HAVE_X_WINDOWS */
4239
4240 }
4241
4242 return p->pixel;
4243}
4244
4245
4246/* Look up pixel color PIXEL which is used on frame F in the color
4247 table. If not already present, allocate it. Value is PIXEL. */
4248
4249static unsigned long
d3da34e0 4250lookup_pixel_color (struct frame *f, unsigned long pixel)
4ef0d4d0
KS
4251{
4252 int i = pixel % CT_SIZE;
4253 struct ct_color *p;
4254
4255 for (p = ct_table[i]; p; p = p->next)
4256 if (p->pixel == pixel)
4257 break;
4258
4259 if (p == NULL)
4260 {
4261 XColor color;
4262 Colormap cmap;
578098f3 4263 bool rc;
4ef0d4d0 4264
ddff3151
PE
4265 if (ct_colors_allocated_max <= ct_colors_allocated)
4266 return FRAME_FOREGROUND_PIXEL (f);
4267
4ef0d4d0
KS
4268#ifdef HAVE_X_WINDOWS
4269 cmap = FRAME_X_COLORMAP (f);
4270 color.pixel = pixel;
4271 x_query_color (f, &color);
4272 rc = x_alloc_nearest_color (f, cmap, &color);
4273#else
4d7e6e51 4274 block_input ();
4ef0d4d0
KS
4275 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4276 color.pixel = pixel;
4277 XQueryColor (NULL, cmap, &color);
4278 rc = x_alloc_nearest_color (f, cmap, &color);
4d7e6e51 4279 unblock_input ();
4ef0d4d0
KS
4280#endif /* HAVE_X_WINDOWS */
4281
4282 if (rc)
4283 {
4284 ++ct_colors_allocated;
4285
23f86fce 4286 p = xmalloc (sizeof *p);
4ef0d4d0
KS
4287 p->r = color.red;
4288 p->g = color.green;
4289 p->b = color.blue;
4290 p->pixel = pixel;
4291 p->next = ct_table[i];
4292 ct_table[i] = p;
4293 }
4294 else
4295 return FRAME_FOREGROUND_PIXEL (f);
4296 }
4297 return p->pixel;
4298}
4299
4300
4301/* Value is a vector of all pixel colors contained in the color table,
4302 allocated via xmalloc. Set *N to the number of colors. */
4303
4304static unsigned long *
d3da34e0 4305colors_in_color_table (int *n)
4ef0d4d0
KS
4306{
4307 int i, j;
4308 struct ct_color *p;
4309 unsigned long *colors;
4310
4311 if (ct_colors_allocated == 0)
4312 {
4313 *n = 0;
4314 colors = NULL;
4315 }
4316 else
4317 {
23f86fce 4318 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4ef0d4d0
KS
4319 *n = ct_colors_allocated;
4320
4321 for (i = j = 0; i < CT_SIZE; ++i)
4322 for (p = ct_table[i]; p; p = p->next)
4323 colors[j++] = p->pixel;
4324 }
4325
4326 return colors;
4327}
4328
4329#else /* COLOR_TABLE_SUPPORT */
4330
4331static unsigned long
7c3320d8 4332lookup_rgb_color (struct frame *f, int r, int g, int b)
4ef0d4d0
KS
4333{
4334 unsigned long pixel;
4335
4ef0d4d0
KS
4336#ifdef HAVE_NTGUI
4337 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4338#endif /* HAVE_NTGUI */
4339
edfda783
AR
4340#ifdef HAVE_NS
4341 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4342#endif /* HAVE_NS */
4ef0d4d0
KS
4343 return pixel;
4344}
4345
4346static void
7c3320d8 4347init_color_table (void)
4ef0d4d0
KS
4348{
4349}
4350#endif /* COLOR_TABLE_SUPPORT */
4351
4352\f
4353/***********************************************************************
4354 Algorithms
4355 ***********************************************************************/
4356
4ef0d4d0
KS
4357/* Edge detection matrices for different edge-detection
4358 strategies. */
4359
4360static int emboss_matrix[9] = {
4361 /* x - 1 x x + 1 */
4362 2, -1, 0, /* y - 1 */
4363 -1, 0, 1, /* y */
4364 0, 1, -2 /* y + 1 */
4365};
4366
4367static int laplace_matrix[9] = {
4368 /* x - 1 x x + 1 */
4369 1, 0, 0, /* y - 1 */
4370 0, 0, 0, /* y */
4371 0, 0, -1 /* y + 1 */
4372};
4373
4374/* Value is the intensity of the color whose red/green/blue values
4375 are R, G, and B. */
4376
4377#define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4378
4379
4380/* On frame F, return an array of XColor structures describing image
4381 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
578098f3 4382 means also fill the red/green/blue members of the XColor
4ef0d4d0
KS
4383 structures. Value is a pointer to the array of XColors structures,
4384 allocated with xmalloc; it must be freed by the caller. */
4385
4386static XColor *
578098f3 4387x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4ef0d4d0
KS
4388{
4389 int x, y;
4390 XColor *colors, *p;
4391 XImagePtr_or_DC ximg;
4392#ifdef HAVE_NTGUI
4393 HDC hdc;
4394 HGDIOBJ prev;
4395#endif /* HAVE_NTGUI */
4396
ddff3151
PE
4397 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width < img->height)
4398 memory_full (SIZE_MAX);
23f86fce 4399 colors = xmalloc (sizeof *colors * img->width * img->height);
4ef0d4d0
KS
4400
4401#ifndef HAVE_NTGUI
4402 /* Get the X image IMG->pixmap. */
4403 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4404 0, 0, img->width, img->height, ~0, ZPixmap);
4405#else
4406 /* Load the image into a memory device context. */
4407 hdc = get_frame_dc (f);
4408 ximg = CreateCompatibleDC (hdc);
4409 release_frame_dc (f, hdc);
4410 prev = SelectObject (ximg, img->pixmap);
4411#endif /* HAVE_NTGUI */
4412
4413 /* Fill the `pixel' members of the XColor array. I wished there
4414 were an easy and portable way to circumvent XGetPixel. */
4415 p = colors;
4416 for (y = 0; y < img->height; ++y)
4417 {
8b7d0a16 4418#if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
6045c4fd 4419 XColor *row = p;
4ef0d4d0 4420 for (x = 0; x < img->width; ++x, ++p)
8b7d0a16 4421 p->pixel = GET_PIXEL (ximg, x, y);
4ef0d4d0
KS
4422 if (rgb_p)
4423 x_query_colors (f, row, img->width);
4424
4425#else
4426
4427 for (x = 0; x < img->width; ++x, ++p)
4428 {
4429 /* W32_TODO: palette support needed here? */
4430 p->pixel = GET_PIXEL (ximg, x, y);
4431 if (rgb_p)
4432 {
4ef0d4d0
KS
4433 p->red = RED16_FROM_ULONG (p->pixel);
4434 p->green = GREEN16_FROM_ULONG (p->pixel);
4435 p->blue = BLUE16_FROM_ULONG (p->pixel);
4ef0d4d0
KS
4436 }
4437 }
4438#endif /* HAVE_X_WINDOWS */
4439 }
4440
4441 Destroy_Image (ximg, prev);
4442
4443 return colors;
4444}
4445
4446#ifdef HAVE_NTGUI
4447
4448/* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4449 created with CreateDIBSection, with the pointer to the bit values
4450 stored in ximg->data. */
4451
3046a84b 4452static void
7c3320d8 4453XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4ef0d4d0
KS
4454{
4455 int width = ximg->info.bmiHeader.biWidth;
4ef0d4d0
KS
4456 unsigned char * pixel;
4457
4458 /* True color images. */
4459 if (ximg->info.bmiHeader.biBitCount == 24)
4460 {
4461 int rowbytes = width * 3;
4462 /* Ensure scanlines are aligned on 4 byte boundaries. */
4463 if (rowbytes % 4)
4464 rowbytes += 4 - (rowbytes % 4);
4465
4466 pixel = ximg->data + y * rowbytes + x * 3;
4467 /* Windows bitmaps are in BGR order. */
4468 *pixel = GetBValue (color);
4469 *(pixel + 1) = GetGValue (color);
4470 *(pixel + 2) = GetRValue (color);
4471 }
4472 /* Monochrome images. */
4473 else if (ximg->info.bmiHeader.biBitCount == 1)
4474 {
4475 int rowbytes = width / 8;
4476 /* Ensure scanlines are aligned on 4 byte boundaries. */
4477 if (rowbytes % 4)
4478 rowbytes += 4 - (rowbytes % 4);
4479 pixel = ximg->data + y * rowbytes + x / 8;
4480 /* Filter out palette info. */
4481 if (color & 0x00ffffff)
4482 *pixel = *pixel | (1 << x % 8);
4483 else
4484 *pixel = *pixel & ~(1 << x % 8);
4485 }
4486 else
4487 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4488}
4489
4490#endif /* HAVE_NTGUI */
4491
4492/* Create IMG->pixmap from an array COLORS of XColor structures, whose
4493 RGB members are set. F is the frame on which this all happens.
4494 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4495
4496static void
d3da34e0 4497x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4ef0d4d0
KS
4498{
4499 int x, y;
edfda783 4500 XImagePtr oimg = NULL;
9d7112ed 4501 Pixmap pixmap;
4ef0d4d0
KS
4502 XColor *p;
4503
4504 init_color_table ();
4505
4506 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4507 &oimg, &pixmap);
4508 p = colors;
4509 for (y = 0; y < img->height; ++y)
4510 for (x = 0; x < img->width; ++x, ++p)
4511 {
4512 unsigned long pixel;
4513 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4514 XPutPixel (oimg, x, y, pixel);
4515 }
4516
4517 xfree (colors);
4518 x_clear_image_1 (f, img, 1, 0, 1);
4519
4520 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4521 x_destroy_x_image (oimg);
4522 img->pixmap = pixmap;
4523#ifdef COLOR_TABLE_SUPPORT
4524 img->colors = colors_in_color_table (&img->ncolors);
4525 free_color_table ();
4526#endif /* COLOR_TABLE_SUPPORT */
4527}
4528
4529
4530/* On frame F, perform edge-detection on image IMG.
4531
4532 MATRIX is a nine-element array specifying the transformation
4533 matrix. See emboss_matrix for an example.
4534
4535 COLOR_ADJUST is a color adjustment added to each pixel of the
4536 outgoing image. */
4537
4538static void
d3da34e0 4539x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4ef0d4d0
KS
4540{
4541 XColor *colors = x_to_xcolors (f, img, 1);
4542 XColor *new, *p;
4543 int x, y, i, sum;
4544
4545 for (i = sum = 0; i < 9; ++i)
1ea40aa2 4546 sum += eabs (matrix[i]);
4ef0d4d0
KS
4547
4548#define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4549
ddff3151
PE
4550 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width < img->height)
4551 memory_full (SIZE_MAX);
23f86fce 4552 new = xmalloc (sizeof *new * img->width * img->height);
4ef0d4d0
KS
4553
4554 for (y = 0; y < img->height; ++y)
4555 {
4556 p = COLOR (new, 0, y);
4557 p->red = p->green = p->blue = 0xffff/2;
4558 p = COLOR (new, img->width - 1, y);
4559 p->red = p->green = p->blue = 0xffff/2;
4560 }
4561
4562 for (x = 1; x < img->width - 1; ++x)
4563 {
4564 p = COLOR (new, x, 0);
4565 p->red = p->green = p->blue = 0xffff/2;
4566 p = COLOR (new, x, img->height - 1);
4567 p->red = p->green = p->blue = 0xffff/2;
4568 }
4569
4570 for (y = 1; y < img->height - 1; ++y)
4571 {
4572 p = COLOR (new, 1, y);
4573
4574 for (x = 1; x < img->width - 1; ++x, ++p)
4575 {
6ae141d6 4576 int r, g, b, yy, xx;
4ef0d4d0
KS
4577
4578 r = g = b = i = 0;
6ae141d6
PE
4579 for (yy = y - 1; yy < y + 2; ++yy)
4580 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4ef0d4d0
KS
4581 if (matrix[i])
4582 {
6ae141d6 4583 XColor *t = COLOR (colors, xx, yy);
4ef0d4d0
KS
4584 r += matrix[i] * t->red;
4585 g += matrix[i] * t->green;
4586 b += matrix[i] * t->blue;
4587 }
4588
4589 r = (r / sum + color_adjust) & 0xffff;
4590 g = (g / sum + color_adjust) & 0xffff;
4591 b = (b / sum + color_adjust) & 0xffff;
4592 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4593 }
4594 }
4595
4596 xfree (colors);
4597 x_from_xcolors (f, img, new);
4598
4599#undef COLOR
4600}
4601
4602
4603/* Perform the pre-defined `emboss' edge-detection on image IMG
4604 on frame F. */
4605
4606static void
d3da34e0 4607x_emboss (struct frame *f, struct image *img)
4ef0d4d0
KS
4608{
4609 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4610}
4611
4612
4613/* Transform image IMG which is used on frame F with a Laplace
4614 edge-detection algorithm. The result is an image that can be used
4615 to draw disabled buttons, for example. */
4616
4617static void
d3da34e0 4618x_laplace (struct frame *f, struct image *img)
4ef0d4d0
KS
4619{
4620 x_detect_edges (f, img, laplace_matrix, 45000);
4621}
4622
4623
4624/* Perform edge-detection on image IMG on frame F, with specified
4625 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4626
4627 MATRIX must be either
4628
4629 - a list of at least 9 numbers in row-major form
4630 - a vector of at least 9 numbers
4631
4632 COLOR_ADJUST nil means use a default; otherwise it must be a
4633 number. */
4634
4635static void
d3da34e0
JB
4636x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4637 Lisp_Object color_adjust)
4ef0d4d0
KS
4638{
4639 int i = 0;
4640 int trans[9];
4641
4642 if (CONSP (matrix))
4643 {
4644 for (i = 0;
4645 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4646 ++i, matrix = XCDR (matrix))
4647 trans[i] = XFLOATINT (XCAR (matrix));
4648 }
4649 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4650 {
4651 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4652 trans[i] = XFLOATINT (AREF (matrix, i));
4653 }
4654
4655 if (NILP (color_adjust))
4656 color_adjust = make_number (0xffff / 2);
4657
4658 if (i == 9 && NUMBERP (color_adjust))
77a765fd 4659 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4ef0d4d0
KS
4660}
4661
4662
4663/* Transform image IMG on frame F so that it looks disabled. */
4664
4665static void
d3da34e0 4666x_disable_image (struct frame *f, struct image *img)
4ef0d4d0
KS
4667{
4668 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4669#ifdef HAVE_NTGUI
4670 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4671#else
4672 int n_planes = dpyinfo->n_planes;
4673#endif /* HAVE_NTGUI */
4674
4675 if (n_planes >= 2)
4676 {
4677 /* Color (or grayscale). Convert to gray, and equalize. Just
4678 drawing such images with a stipple can look very odd, so
4679 we're using this method instead. */
4680 XColor *colors = x_to_xcolors (f, img, 1);
4681 XColor *p, *end;
4682 const int h = 15000;
4683 const int l = 30000;
4684
4685 for (p = colors, end = colors + img->width * img->height;
4686 p < end;
4687 ++p)
4688 {
4689 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4690 int i2 = (0xffff - h - l) * i / 0xffff + l;
4691 p->red = p->green = p->blue = i2;
4692 }
4693
4694 x_from_xcolors (f, img, colors);
4695 }
4696
4697 /* Draw a cross over the disabled image, if we must or if we
4698 should. */
4699 if (n_planes < 2 || cross_disabled_images)
4700 {
4701#ifndef HAVE_NTGUI
5afa3a81 4702#ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
edfda783 4703
4ef0d4d0 4704#define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4ef0d4d0 4705
6045c4fd
PE
4706 Display *dpy = FRAME_X_DISPLAY (f);
4707 GC gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4ef0d4d0
KS
4708 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4709 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4710 img->width - 1, img->height - 1);
4711 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4712 img->width - 1, 0);
4713 XFreeGC (dpy, gc);
4714
4715 if (img->mask)
4716 {
ae8279db 4717 gc = XCreateGC (dpy, img->mask, 0, NULL);
4ef0d4d0
KS
4718 XSetForeground (dpy, gc, MaskForeground (f));
4719 XDrawLine (dpy, img->mask, gc, 0, 0,
4720 img->width - 1, img->height - 1);
4721 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4722 img->width - 1, 0);
4723 XFreeGC (dpy, gc);
4724 }
edfda783 4725#endif /* !HAVE_NS */
4ef0d4d0
KS
4726#else
4727 HDC hdc, bmpdc;
4728 HGDIOBJ prev;
4729
4730 hdc = get_frame_dc (f);
4731 bmpdc = CreateCompatibleDC (hdc);
4732 release_frame_dc (f, hdc);
4733
4734 prev = SelectObject (bmpdc, img->pixmap);
4735
4736 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4737 MoveToEx (bmpdc, 0, 0, NULL);
4738 LineTo (bmpdc, img->width - 1, img->height - 1);
4739 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4740 LineTo (bmpdc, img->width - 1, 0);
4741
4742 if (img->mask)
4743 {
4744 SelectObject (bmpdc, img->mask);
4745 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4746 MoveToEx (bmpdc, 0, 0, NULL);
4747 LineTo (bmpdc, img->width - 1, img->height - 1);
4748 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4749 LineTo (bmpdc, img->width - 1, 0);
4750 }
4751 SelectObject (bmpdc, prev);
4752 DeleteDC (bmpdc);
4753#endif /* HAVE_NTGUI */
4754 }
4755}
4756
4757
4758/* Build a mask for image IMG which is used on frame F. FILE is the
4759 name of an image file, for error messages. HOW determines how to
4760 determine the background color of IMG. If it is a list '(R G B)',
4761 with R, G, and B being integers >= 0, take that as the color of the
4762 background. Otherwise, determine the background color of IMG
578098f3 4763 heuristically. */
4ef0d4d0 4764
578098f3 4765static void
d3da34e0 4766x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4ef0d4d0
KS
4767{
4768 XImagePtr_or_DC ximg;
4769#ifndef HAVE_NTGUI
4770 XImagePtr mask_img;
4771#else
4772 HDC frame_dc;
4773 HGDIOBJ prev;
4774 char *mask_img;
4775 int row_width;
4776#endif /* HAVE_NTGUI */
578098f3
PE
4777 int x, y;
4778 bool rc, use_img_background;
4ef0d4d0
KS
4779 unsigned long bg = 0;
4780
4781 if (img->mask)
4782 {
4783 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4784 img->mask = NO_PIXMAP;
4785 img->background_transparent_valid = 0;
4786 }
4787
4788#ifndef HAVE_NTGUI
edfda783 4789#ifndef HAVE_NS
4ef0d4d0
KS
4790 /* Create an image and pixmap serving as mask. */
4791 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4792 &mask_img, &img->mask);
4793 if (!rc)
578098f3 4794 return;
edfda783 4795#endif /* !HAVE_NS */
4ef0d4d0
KS
4796
4797 /* Get the X image of IMG->pixmap. */
4798 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4799 img->width, img->height,
4800 ~0, ZPixmap);
4801#else
4802 /* Create the bit array serving as mask. */
4803 row_width = (img->width + 7) / 8;
23f86fce 4804 mask_img = xzalloc (row_width * img->height);
4ef0d4d0
KS
4805
4806 /* Create a memory device context for IMG->pixmap. */
4807 frame_dc = get_frame_dc (f);
4808 ximg = CreateCompatibleDC (frame_dc);
4809 release_frame_dc (f, frame_dc);
4810 prev = SelectObject (ximg, img->pixmap);
4811#endif /* HAVE_NTGUI */
4812
4813 /* Determine the background color of ximg. If HOW is `(R G B)'
4814 take that as color. Otherwise, use the image's background color. */
4815 use_img_background = 1;
4816
4817 if (CONSP (how))
4818 {
4819 int rgb[3], i;
4820
4821 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4822 {
4823 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4824 how = XCDR (how);
4825 }
4826
4827 if (i == 3 && NILP (how))
4828 {
4829 char color_name[30];
4830 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4831 bg = (
4832#ifdef HAVE_NTGUI
4833 0x00ffffff & /* Filter out palette info. */
4834#endif /* HAVE_NTGUI */
4835 x_alloc_image_color (f, img, build_string (color_name), 0));
4836 use_img_background = 0;
4837 }
4838 }
4839
4840 if (use_img_background)
6ac3c7bb 4841 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4ef0d4d0
KS
4842
4843 /* Set all bits in mask_img to 1 whose color in ximg is different
4844 from the background color bg. */
4845#ifndef HAVE_NTGUI
4846 for (y = 0; y < img->height; ++y)
4847 for (x = 0; x < img->width; ++x)
edfda783 4848#ifndef HAVE_NS
4ef0d4d0 4849 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
9ecf6403 4850 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
edfda783
AR
4851#else
4852 if (XGetPixel (ximg, x, y) == bg)
ed3751c8 4853 ns_set_alpha (ximg, x, y, 0);
edfda783
AR
4854#endif /* HAVE_NS */
4855#ifndef HAVE_NS
4ef0d4d0
KS
4856 /* Fill in the background_transparent field while we have the mask handy. */
4857 image_background_transparent (img, f, mask_img);
4858
4859 /* Put mask_img into img->mask. */
4860 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4861 x_destroy_x_image (mask_img);
edfda783 4862#endif /* !HAVE_NS */
4ef0d4d0
KS
4863#else
4864 for (y = 0; y < img->height; ++y)
4865 for (x = 0; x < img->width; ++x)
4866 {
4867 COLORREF p = GetPixel (ximg, x, y);
4868 if (p != bg)
4869 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4870 }
4871
4872 /* Create the mask image. */
4873 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4874 mask_img);
4875 /* Fill in the background_transparent field while we have the mask handy. */
4876 SelectObject (ximg, img->mask);
4877 image_background_transparent (img, f, ximg);
4878
4879 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4880 xfree (mask_img);
4881#endif /* HAVE_NTGUI */
4882
4883 Destroy_Image (ximg, prev);
4ef0d4d0
KS
4884}
4885
4886\f
4887/***********************************************************************
4888 PBM (mono, gray, color)
4889 ***********************************************************************/
4890
578098f3
PE
4891static bool pbm_image_p (Lisp_Object object);
4892static bool pbm_load (struct frame *f, struct image *img);
4ef0d4d0
KS
4893
4894/* The symbol `pbm' identifying images of this type. */
4895
955cbe7b 4896static Lisp_Object Qpbm;
4ef0d4d0
KS
4897
4898/* Indices of image specification fields in gs_format, below. */
4899
4900enum pbm_keyword_index
4901{
4902 PBM_TYPE,
4903 PBM_FILE,
4904 PBM_DATA,
4905 PBM_ASCENT,
4906 PBM_MARGIN,
4907 PBM_RELIEF,
4908 PBM_ALGORITHM,
4909 PBM_HEURISTIC_MASK,
4910 PBM_MASK,
4911 PBM_FOREGROUND,
4912 PBM_BACKGROUND,
4913 PBM_LAST
4914};
4915
4916/* Vector of image_keyword structures describing the format
4917 of valid user-defined image specifications. */
4918
91433552 4919static const struct image_keyword pbm_format[PBM_LAST] =
4ef0d4d0
KS
4920{
4921 {":type", IMAGE_SYMBOL_VALUE, 1},
4922 {":file", IMAGE_STRING_VALUE, 0},
4923 {":data", IMAGE_STRING_VALUE, 0},
4924 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 4925 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
4926 {":relief", IMAGE_INTEGER_VALUE, 0},
4927 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4928 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4929 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4930 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4931 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4932};
4933
4934/* Structure describing the image type `pbm'. */
4935
4936static struct image_type pbm_type =
4937{
4938 &Qpbm,
4939 pbm_image_p,
4940 pbm_load,
4941 x_clear_image,
bb4d86b4 4942 NULL,
4ef0d4d0
KS
4943 NULL
4944};
4945
4946
578098f3 4947/* Return true if OBJECT is a valid PBM image specification. */
4ef0d4d0 4948
578098f3 4949static bool
d3da34e0 4950pbm_image_p (Lisp_Object object)
4ef0d4d0
KS
4951{
4952 struct image_keyword fmt[PBM_LAST];
4953
72af86bd 4954 memcpy (fmt, pbm_format, sizeof fmt);
4ef0d4d0
KS
4955
4956 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
4957 return 0;
4958
4959 /* Must specify either :data or :file. */
4960 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
4961}
4962
4963
4964/* Scan a decimal number from *S and return it. Advance *S while
4965 reading the number. END is the end of the string. Value is -1 at
4966 end of input. */
4967
4968static int
d3da34e0 4969pbm_scan_number (unsigned char **s, unsigned char *end)
4ef0d4d0
KS
4970{
4971 int c = 0, val = -1;
4972
4973 while (*s < end)
4974 {
4975 /* Skip white-space. */
620f13b0 4976 while (*s < end && (c = *(*s)++, c_isspace (c)))
4ef0d4d0
KS
4977 ;
4978
4979 if (c == '#')
4980 {
4981 /* Skip comment to end of line. */
4982 while (*s < end && (c = *(*s)++, c != '\n'))
4983 ;
4984 }
620f13b0 4985 else if (c_isdigit (c))
4ef0d4d0
KS
4986 {
4987 /* Read decimal number. */
4988 val = c - '0';
620f13b0 4989 while (*s < end && (c = *(*s)++, c_isdigit (c)))
4ef0d4d0
KS
4990 val = 10 * val + c - '0';
4991 break;
4992 }
4993 else
4994 break;
4995 }
4996
4997 return val;
4998}
4999
5000
4ef0d4d0
KS
5001/* Load PBM image IMG for use on frame F. */
5002
578098f3 5003static bool
d3da34e0 5004pbm_load (struct frame *f, struct image *img)
4ef0d4d0 5005{
578098f3
PE
5006 bool raw_p;
5007 int x, y;
4ef0d4d0
KS
5008 int width, height, max_color_idx = 0;
5009 XImagePtr ximg;
5010 Lisp_Object file, specified_file;
5011 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
4ef0d4d0
KS
5012 unsigned char *contents = NULL;
5013 unsigned char *end, *p;
dd52fcea 5014 ptrdiff_t size;
4ef0d4d0
KS
5015
5016 specified_file = image_spec_value (img->spec, QCfile, NULL);
4ef0d4d0
KS
5017
5018 if (STRINGP (specified_file))
5019 {
5020 file = x_find_image_file (specified_file);
5021 if (!STRINGP (file))
5022 {
5023 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
5024 return 0;
5025 }
5026
42a5b22f 5027 contents = slurp_file (SSDATA (file), &size);
4ef0d4d0
KS
5028 if (contents == NULL)
5029 {
5030 image_error ("Error reading `%s'", file, Qnil);
4ef0d4d0
KS
5031 return 0;
5032 }
5033
5034 p = contents;
5035 end = contents + size;
5036 }
5037 else
5038 {
5039 Lisp_Object data;
5040 data = image_spec_value (img->spec, QCdata, NULL);
7574650a
AS
5041 if (!STRINGP (data))
5042 {
5043 image_error ("Invalid image data `%s'", data, Qnil);
5044 return 0;
5045 }
4ef0d4d0
KS
5046 p = SDATA (data);
5047 end = p + SBYTES (data);
5048 }
5049
5050 /* Check magic number. */
5051 if (end - p < 2 || *p++ != 'P')
5052 {
5053 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5054 error:
5055 xfree (contents);
4ef0d4d0
KS
5056 return 0;
5057 }
5058
5059 switch (*p++)
5060 {
5061 case '1':
5062 raw_p = 0, type = PBM_MONO;
5063 break;
5064
5065 case '2':
5066 raw_p = 0, type = PBM_GRAY;
5067 break;
5068
5069 case '3':
5070 raw_p = 0, type = PBM_COLOR;
5071 break;
5072
5073 case '4':
5074 raw_p = 1, type = PBM_MONO;
5075 break;
5076
5077 case '5':
5078 raw_p = 1, type = PBM_GRAY;
5079 break;
5080
5081 case '6':
5082 raw_p = 1, type = PBM_COLOR;
5083 break;
5084
5085 default:
5086 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5087 goto error;
5088 }
5089
5090 /* Read width, height, maximum color-component. Characters
5091 starting with `#' up to the end of a line are ignored. */
5092 width = pbm_scan_number (&p, end);
5093 height = pbm_scan_number (&p, end);
5094
5095 if (type != PBM_MONO)
5096 {
5097 max_color_idx = pbm_scan_number (&p, end);
b9c89e11
JR
5098 if (max_color_idx > 65535 || max_color_idx < 0)
5099 {
5100 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5101 goto error;
5102 }
4ef0d4d0
KS
5103 }
5104
b9c89e11
JR
5105 if (!check_image_size (f, width, height))
5106 {
10ea2b82 5107 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
b9c89e11
JR
5108 goto error;
5109 }
4ef0d4d0
KS
5110
5111 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5112 &ximg, &img->pixmap))
5113 goto error;
5114
5115 /* Initialize the color hash table. */
5116 init_color_table ();
5117
5118 if (type == PBM_MONO)
5119 {
5120 int c = 0, g;
5121 struct image_keyword fmt[PBM_LAST];
5122 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5123 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5124
5125 /* Parse the image specification. */
72af86bd 5126 memcpy (fmt, pbm_format, sizeof fmt);
4ef0d4d0
KS
5127 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5128
5129 /* Get foreground and background colors, maybe allocate colors. */
5130 if (fmt[PBM_FOREGROUND].count
5131 && STRINGP (fmt[PBM_FOREGROUND].value))
5132 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5133 if (fmt[PBM_BACKGROUND].count
5134 && STRINGP (fmt[PBM_BACKGROUND].value))
5135 {
5136 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5137 img->background = bg;
5138 img->background_valid = 1;
5139 }
5140
5141 for (y = 0; y < height; ++y)
5142 for (x = 0; x < width; ++x)
5143 {
5144 if (raw_p)
5145 {
5146 if ((x & 7) == 0)
c295e710
CY
5147 {
5148 if (p >= end)
5149 {
5150 x_destroy_x_image (ximg);
5151 x_clear_image (f, img);
5152 image_error ("Invalid image size in image `%s'",
5153 img->spec, Qnil);
5154 goto error;
5155 }
5156 c = *p++;
5157 }
4ef0d4d0
KS
5158 g = c & 0x80;
5159 c <<= 1;
5160 }
5161 else
5162 g = pbm_scan_number (&p, end);
5163
5164 XPutPixel (ximg, x, y, g ? fg : bg);
5165 }
5166 }
5167 else
5168 {
b9c89e11
JR
5169 int expected_size = height * width;
5170 if (max_color_idx > 255)
5171 expected_size *= 2;
5172 if (type == PBM_COLOR)
5173 expected_size *= 3;
5174
5175 if (raw_p && p + expected_size > end)
39e653ea
CY
5176 {
5177 x_destroy_x_image (ximg);
fb0b0862 5178 x_clear_image (f, img);
39e653ea
CY
5179 image_error ("Invalid image size in image `%s'",
5180 img->spec, Qnil);
5181 goto error;
5182 }
5183
4ef0d4d0
KS
5184 for (y = 0; y < height; ++y)
5185 for (x = 0; x < width; ++x)
5186 {
5187 int r, g, b;
5188
b9c89e11
JR
5189 if (type == PBM_GRAY && raw_p)
5190 {
5191 r = g = b = *p++;
5192 if (max_color_idx > 255)
5193 r = g = b = r * 256 + *p++;
5194 }
5195 else if (type == PBM_GRAY)
5196 r = g = b = pbm_scan_number (&p, end);
4ef0d4d0
KS
5197 else if (raw_p)
5198 {
5199 r = *p++;
b9c89e11
JR
5200 if (max_color_idx > 255)
5201 r = r * 256 + *p++;
4ef0d4d0 5202 g = *p++;
b9c89e11
JR
5203 if (max_color_idx > 255)
5204 g = g * 256 + *p++;
4ef0d4d0 5205 b = *p++;
b9c89e11
JR
5206 if (max_color_idx > 255)
5207 b = b * 256 + *p++;
4ef0d4d0
KS
5208 }
5209 else
5210 {
5211 r = pbm_scan_number (&p, end);
5212 g = pbm_scan_number (&p, end);
5213 b = pbm_scan_number (&p, end);
5214 }
5215
5216 if (r < 0 || g < 0 || b < 0)
5217 {
5218 x_destroy_x_image (ximg);
5219 image_error ("Invalid pixel value in image `%s'",
5220 img->spec, Qnil);
5221 goto error;
5222 }
5223
5224 /* RGB values are now in the range 0..max_color_idx.
5225 Scale this to the range 0..0xffff supported by X. */
5226 r = (double) r * 65535 / max_color_idx;
5227 g = (double) g * 65535 / max_color_idx;
5228 b = (double) b * 65535 / max_color_idx;
5229 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5230 }
5231 }
5232
5233#ifdef COLOR_TABLE_SUPPORT
5234 /* Store in IMG->colors the colors allocated for the image, and
5235 free the color table. */
5236 img->colors = colors_in_color_table (&img->ncolors);
5237 free_color_table ();
5238#endif /* COLOR_TABLE_SUPPORT */
5239
5240 img->width = width;
5241 img->height = height;
5242
5243 /* Maybe fill in the background field while we have ximg handy. */
5244
5245 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
5246 /* Casting avoids a GCC warning. */
5247 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
5248
5249 /* Put the image into a pixmap. */
5250 x_put_x_image (f, ximg, img->pixmap, width, height);
5251 x_destroy_x_image (ximg);
5252
5253 /* X and W32 versions did it here, MAC version above. ++kfs
1f026899 5254 img->width = width;
4ef0d4d0
KS
5255 img->height = height; */
5256
4ef0d4d0
KS
5257 xfree (contents);
5258 return 1;
5259}
5260
5261\f
5262/***********************************************************************
5263 PNG
5264 ***********************************************************************/
5265
9e2a2647 5266#if defined (HAVE_PNG) || defined (HAVE_NS)
4ef0d4d0
KS
5267
5268/* Function prototypes. */
5269
578098f3
PE
5270static bool png_image_p (Lisp_Object object);
5271static bool png_load (struct frame *f, struct image *img);
4ef0d4d0
KS
5272
5273/* The symbol `png' identifying images of this type. */
5274
955cbe7b 5275static Lisp_Object Qpng;
4ef0d4d0
KS
5276
5277/* Indices of image specification fields in png_format, below. */
5278
5279enum png_keyword_index
5280{
5281 PNG_TYPE,
5282 PNG_DATA,
5283 PNG_FILE,
5284 PNG_ASCENT,
5285 PNG_MARGIN,
5286 PNG_RELIEF,
5287 PNG_ALGORITHM,
5288 PNG_HEURISTIC_MASK,
5289 PNG_MASK,
5290 PNG_BACKGROUND,
5291 PNG_LAST
5292};
5293
5294/* Vector of image_keyword structures describing the format
5295 of valid user-defined image specifications. */
5296
91433552 5297static const struct image_keyword png_format[PNG_LAST] =
4ef0d4d0
KS
5298{
5299 {":type", IMAGE_SYMBOL_VALUE, 1},
5300 {":data", IMAGE_STRING_VALUE, 0},
5301 {":file", IMAGE_STRING_VALUE, 0},
5302 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 5303 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
5304 {":relief", IMAGE_INTEGER_VALUE, 0},
5305 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5306 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5307 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5308 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5309};
5310
a9e7a9d5 5311#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 5312static bool init_png_functions (void);
bb4d86b4
CY
5313#else
5314#define init_png_functions NULL
5315#endif
5316
4ef0d4d0
KS
5317/* Structure describing the image type `png'. */
5318
5319static struct image_type png_type =
5320{
5321 &Qpng,
5322 png_image_p,
5323 png_load,
5324 x_clear_image,
bb4d86b4 5325 init_png_functions,
4ef0d4d0
KS
5326 NULL
5327};
5328
578098f3 5329/* Return true if OBJECT is a valid PNG image specification. */
4ef0d4d0 5330
578098f3 5331static bool
d3da34e0 5332png_image_p (Lisp_Object object)
4ef0d4d0
KS
5333{
5334 struct image_keyword fmt[PNG_LAST];
72af86bd 5335 memcpy (fmt, png_format, sizeof fmt);
4ef0d4d0
KS
5336
5337 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5338 return 0;
5339
5340 /* Must specify either the :data or :file keyword. */
5341 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5342}
5343
9e2a2647 5344#endif /* HAVE_PNG || HAVE_NS */
4ef0d4d0
KS
5345
5346
5347#ifdef HAVE_PNG
5348
0fda9b75 5349#ifdef WINDOWSNT
4ef0d4d0
KS
5350/* PNG library details. */
5351
14beddf4
CY
5352DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5353DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5354DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5355 png_error_ptr, png_error_ptr));
5356DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5357DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5358DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5359DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5360DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5361DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
850690cc
JB
5362 png_uint_32 *, png_uint_32 *,
5363 int *, int *, int *, int *, int *));
14beddf4
CY
5364DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5365DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5366DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5367DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5368DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
850690cc 5369 int, int, double));
14beddf4
CY
5370DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5371DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5372DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5373DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5374DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5375DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5376DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
4ef0d4d0 5377
7f9c5df9 5378#if (PNG_LIBPNG_VER >= 10500)
14beddf4
CY
5379DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int));
5380DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
7f9c5df9 5381#endif /* libpng version >= 1.5 */
4ef0d4d0 5382
578098f3 5383static bool
d07ff9db 5384init_png_functions (void)
4ef0d4d0
KS
5385{
5386 HMODULE library;
5387
d07ff9db 5388 if (!(library = w32_delayed_load (Qpng)))
4ef0d4d0
KS
5389 return 0;
5390
5391 LOAD_IMGLIB_FN (library, png_get_io_ptr);
285d07e2 5392 LOAD_IMGLIB_FN (library, png_sig_cmp);
4ef0d4d0
KS
5393 LOAD_IMGLIB_FN (library, png_create_read_struct);
5394 LOAD_IMGLIB_FN (library, png_create_info_struct);
5395 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5396 LOAD_IMGLIB_FN (library, png_set_read_fn);
4ef0d4d0
KS
5397 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5398 LOAD_IMGLIB_FN (library, png_read_info);
5399 LOAD_IMGLIB_FN (library, png_get_IHDR);
5400 LOAD_IMGLIB_FN (library, png_get_valid);
5401 LOAD_IMGLIB_FN (library, png_set_strip_16);
5402 LOAD_IMGLIB_FN (library, png_set_expand);
5403 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5404 LOAD_IMGLIB_FN (library, png_set_background);
5405 LOAD_IMGLIB_FN (library, png_get_bKGD);
5406 LOAD_IMGLIB_FN (library, png_read_update_info);
5407 LOAD_IMGLIB_FN (library, png_get_channels);
5408 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5409 LOAD_IMGLIB_FN (library, png_read_image);
5410 LOAD_IMGLIB_FN (library, png_read_end);
5411 LOAD_IMGLIB_FN (library, png_error);
7f9c5df9
CY
5412
5413#if (PNG_LIBPNG_VER >= 10500)
5414 LOAD_IMGLIB_FN (library, png_longjmp);
5415 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5416#endif /* libpng version >= 1.5 */
5417
4ef0d4d0
KS
5418 return 1;
5419}
5420#else
5421
5422#define fn_png_get_io_ptr png_get_io_ptr
285d07e2 5423#define fn_png_sig_cmp png_sig_cmp
4ef0d4d0
KS
5424#define fn_png_create_read_struct png_create_read_struct
5425#define fn_png_create_info_struct png_create_info_struct
5426#define fn_png_destroy_read_struct png_destroy_read_struct
5427#define fn_png_set_read_fn png_set_read_fn
4ef0d4d0
KS
5428#define fn_png_set_sig_bytes png_set_sig_bytes
5429#define fn_png_read_info png_read_info
5430#define fn_png_get_IHDR png_get_IHDR
5431#define fn_png_get_valid png_get_valid
5432#define fn_png_set_strip_16 png_set_strip_16
5433#define fn_png_set_expand png_set_expand
5434#define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5435#define fn_png_set_background png_set_background
5436#define fn_png_get_bKGD png_get_bKGD
5437#define fn_png_read_update_info png_read_update_info
5438#define fn_png_get_channels png_get_channels
5439#define fn_png_get_rowbytes png_get_rowbytes
5440#define fn_png_read_image png_read_image
5441#define fn_png_read_end png_read_end
5442#define fn_png_error png_error
5443
7f9c5df9
CY
5444#if (PNG_LIBPNG_VER >= 10500)
5445#define fn_png_longjmp png_longjmp
5446#define fn_png_set_longjmp_fn png_set_longjmp_fn
5447#endif /* libpng version >= 1.5 */
5448
0fda9b75 5449#endif /* WINDOWSNT */
4ef0d4d0 5450
0328b6de
PE
5451/* Possibly inefficient/inexact substitutes for _setjmp and _longjmp.
5452 Do not use sys_setjmp, as PNG supports only jmp_buf. The _longjmp
7105c8cb
EZ
5453 substitute may munge the signal mask, but that should be OK here.
5454 MinGW (MS-Windows) uses _setjmp and defines setjmp to _setjmp in
5455 the system header setjmp.h; don't mess up that. */
0328b6de 5456#ifndef HAVE__SETJMP
39a57ad0 5457# define _setjmp(j) setjmp (j)
0328b6de
PE
5458# define _longjmp longjmp
5459#endif
7f9c5df9
CY
5460
5461#if (PNG_LIBPNG_VER < 10500)
af26b72c 5462#define PNG_LONGJMP(ptr) (_longjmp ((ptr)->jmpbuf, 1))
7f9c5df9
CY
5463#define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5464#else
df61c790 5465/* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
c2e79cb4 5466#define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
7f9c5df9 5467#define PNG_JMPBUF(ptr) \
af26b72c 5468 (*fn_png_set_longjmp_fn ((ptr), _longjmp, sizeof (jmp_buf)))
7f9c5df9
CY
5469#endif
5470
4ef0d4d0
KS
5471/* Error and warning handlers installed when the PNG library
5472 is initialized. */
5473
845ca893 5474static _Noreturn void
d3da34e0 5475my_png_error (png_struct *png_ptr, const char *msg)
4ef0d4d0 5476{
a54e2c05 5477 eassert (png_ptr != NULL);
5be1c984
EZ
5478 /* Avoid compiler warning about deprecated direct access to
5479 png_ptr's fields in libpng versions 1.4.x. */
4ef0d4d0 5480 image_error ("PNG error: %s", build_string (msg), Qnil);
7f9c5df9 5481 PNG_LONGJMP (png_ptr);
4ef0d4d0
KS
5482}
5483
5484
5485static void
d3da34e0 5486my_png_warning (png_struct *png_ptr, const char *msg)
4ef0d4d0 5487{
a54e2c05 5488 eassert (png_ptr != NULL);
4ef0d4d0
KS
5489 image_error ("PNG warning: %s", build_string (msg), Qnil);
5490}
5491
5492/* Memory source for PNG decoding. */
5493
5494struct png_memory_storage
5495{
5496 unsigned char *bytes; /* The data */
3f791afe
PE
5497 ptrdiff_t len; /* How big is it? */
5498 ptrdiff_t index; /* Where are we? */
4ef0d4d0
KS
5499};
5500
5501
5502/* Function set as reader function when reading PNG image from memory.
5503 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5504 bytes from the input to DATA. */
5505
5506static void
d3da34e0 5507png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
4ef0d4d0
KS
5508{
5509 struct png_memory_storage *tbr
5510 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5511
5512 if (length > tbr->len - tbr->index)
5513 fn_png_error (png_ptr, "Read error");
5514
72af86bd 5515 memcpy (data, tbr->bytes + tbr->index, length);
4ef0d4d0
KS
5516 tbr->index = tbr->index + length;
5517}
5518
b0da69a7 5519
9a22a004
JB
5520/* Function set as reader function when reading PNG image from a file.
5521 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5522 bytes from the input to DATA. */
5523
5524static void
d3da34e0 5525png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
9a22a004
JB
5526{
5527 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5528
5529 if (fread (data, 1, length, fp) < length)
5530 fn_png_error (png_ptr, "Read error");
5531}
5532
5533
578098f3 5534/* Load PNG image IMG for use on frame F. Value is true if
4ef0d4d0
KS
5535 successful. */
5536
40bce90b
PE
5537struct png_load_context
5538{
0328b6de 5539 /* These are members so that longjmp doesn't munge local variables. */
40bce90b
PE
5540 png_struct *png_ptr;
5541 png_info *info_ptr;
5542 png_info *end_info;
5543 FILE *fp;
5544 png_byte *pixels;
5545 png_byte **rows;
5546};
5547
578098f3 5548static bool
40bce90b 5549png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
4ef0d4d0
KS
5550{
5551 Lisp_Object file, specified_file;
5552 Lisp_Object specified_data;
5adf60bc
PE
5553 int x, y;
5554 ptrdiff_t i;
4ef0d4d0 5555 XImagePtr ximg, mask_img = NULL;
40bce90b 5556 png_struct *png_ptr;
4ef0d4d0 5557 png_info *info_ptr = NULL, *end_info = NULL;
40bce90b 5558 FILE *fp = NULL;
4ef0d4d0 5559 png_byte sig[8];
40bce90b
PE
5560 png_byte *pixels = NULL;
5561 png_byte **rows = NULL;
4ef0d4d0
KS
5562 png_uint_32 width, height;
5563 int bit_depth, color_type, interlace_type;
5564 png_byte channels;
5565 png_uint_32 row_bytes;
578098f3 5566 bool transparent_p;
4ef0d4d0
KS
5567 struct png_memory_storage tbr; /* Data to be read */
5568
5569 /* Find out what file to load. */
5570 specified_file = image_spec_value (img->spec, QCfile, NULL);
5571 specified_data = image_spec_value (img->spec, QCdata, NULL);
4ef0d4d0
KS
5572
5573 if (NILP (specified_data))
5574 {
5575 file = x_find_image_file (specified_file);
5576 if (!STRINGP (file))
5577 {
5578 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
5579 return 0;
5580 }
5581
5582 /* Open the image file. */
42a5b22f 5583 fp = fopen (SSDATA (file), "rb");
4ef0d4d0
KS
5584 if (!fp)
5585 {
5586 image_error ("Cannot open image file `%s'", file, Qnil);
4ef0d4d0
KS
5587 return 0;
5588 }
5589
5590 /* Check PNG signature. */
5591 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
285d07e2 5592 || fn_png_sig_cmp (sig, 0, sizeof sig))
4ef0d4d0
KS
5593 {
5594 image_error ("Not a PNG file: `%s'", file, Qnil);
4ef0d4d0
KS
5595 fclose (fp);
5596 return 0;
5597 }
5598 }
5599 else
5600 {
7574650a
AS
5601 if (!STRINGP (specified_data))
5602 {
5603 image_error ("Invalid image data `%s'", specified_data, Qnil);
5604 return 0;
5605 }
5606
4ef0d4d0
KS
5607 /* Read from memory. */
5608 tbr.bytes = SDATA (specified_data);
5609 tbr.len = SBYTES (specified_data);
5610 tbr.index = 0;
5611
5612 /* Check PNG signature. */
5613 if (tbr.len < sizeof sig
285d07e2 5614 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
4ef0d4d0
KS
5615 {
5616 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
4ef0d4d0
KS
5617 return 0;
5618 }
5619
5620 /* Need to skip past the signature. */
5621 tbr.bytes += sizeof (sig);
5622 }
5623
df61c790
AS
5624 /* Initialize read and info structs for PNG lib. */
5625 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5626 NULL, my_png_error,
5627 my_png_warning);
40bce90b 5628 if (png_ptr)
4ef0d4d0 5629 {
40bce90b
PE
5630 info_ptr = fn_png_create_info_struct (png_ptr);
5631 end_info = fn_png_create_info_struct (png_ptr);
4ef0d4d0
KS
5632 }
5633
40bce90b
PE
5634 c->png_ptr = png_ptr;
5635 c->info_ptr = info_ptr;
5636 c->end_info = end_info;
5637 c->fp = fp;
5638 c->pixels = pixels;
5639 c->rows = rows;
5640
5641 if (! (info_ptr && end_info))
4ef0d4d0 5642 {
40bce90b
PE
5643 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5644 png_ptr = 0;
4ef0d4d0 5645 }
40bce90b 5646 if (! png_ptr)
4ef0d4d0 5647 {
4ef0d4d0 5648 if (fp) fclose (fp);
4ef0d4d0
KS
5649 return 0;
5650 }
5651
5652 /* Set error jump-back. We come back here when the PNG library
5653 detects an error. */
af26b72c 5654 if (_setjmp (PNG_JMPBUF (png_ptr)))
4ef0d4d0
KS
5655 {
5656 error:
40bce90b
PE
5657 if (c->png_ptr)
5658 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5659 xfree (c->pixels);
5660 xfree (c->rows);
5661 if (c->fp)
5662 fclose (c->fp);
4ef0d4d0
KS
5663 return 0;
5664 }
5665
40bce90b
PE
5666 /* Silence a bogus diagnostic; see GCC bug 54561. */
5667 IF_LINT (fp = c->fp);
5668
4ef0d4d0
KS
5669 /* Read image info. */
5670 if (!NILP (specified_data))
5671 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5672 else
9a22a004 5673 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
4ef0d4d0
KS
5674
5675 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5676 fn_png_read_info (png_ptr, info_ptr);
5677 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5678 &interlace_type, NULL, NULL);
5679
3f791afe
PE
5680 if (! (width <= INT_MAX && height <= INT_MAX
5681 && check_image_size (f, width, height)))
10ea2b82
JR
5682 {
5683 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5684 goto error;
5685 }
ca4aa935
PE
5686
5687 /* Create the X image and pixmap now, so that the work below can be
5688 omitted if the image is too large for X. */
5689 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5690 &img->pixmap))
5691 goto error;
5692
4ef0d4d0
KS
5693 /* If image contains simply transparency data, we prefer to
5694 construct a clipping mask. */
5695 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5696 transparent_p = 1;
5697 else
5698 transparent_p = 0;
5699
5700 /* This function is easier to write if we only have to handle
5701 one data format: RGB or RGBA with 8 bits per channel. Let's
5702 transform other formats into that format. */
5703
5704 /* Strip more than 8 bits per channel. */
5705 if (bit_depth == 16)
5706 fn_png_set_strip_16 (png_ptr);
5707
5708 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5709 if available. */
5710 fn_png_set_expand (png_ptr);
5711
5712 /* Convert grayscale images to RGB. */
5713 if (color_type == PNG_COLOR_TYPE_GRAY
5714 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5715 fn_png_set_gray_to_rgb (png_ptr);
5716
4ef0d4d0
KS
5717 /* Handle alpha channel by combining the image with a background
5718 color. Do this only if a real alpha channel is supplied. For
5719 simple transparency, we prefer a clipping mask. */
5720 if (!transparent_p)
5721 {
917ac1a9 5722 /* png_color_16 *image_bg; */
4ef0d4d0
KS
5723 Lisp_Object specified_bg
5724 = image_spec_value (img->spec, QCbackground, NULL);
c4f13f44 5725 int shift = (bit_depth == 16) ? 0 : 8;
4ef0d4d0
KS
5726
5727 if (STRINGP (specified_bg))
5728 /* The user specified `:background', use that. */
5729 {
4ef0d4d0 5730 XColor color;
42a5b22f 5731 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
4ef0d4d0
KS
5732 {
5733 png_color_16 user_bg;
5734
72af86bd 5735 memset (&user_bg, 0, sizeof user_bg);
c4f13f44
CY
5736 user_bg.red = color.red >> shift;
5737 user_bg.green = color.green >> shift;
5738 user_bg.blue = color.blue >> shift;
4ef0d4d0
KS
5739
5740 fn_png_set_background (png_ptr, &user_bg,
5741 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5742 }
5743 }
4ef0d4d0
KS
5744 else
5745 {
c4f13f44
CY
5746 /* We use the current frame background, ignoring any default
5747 background color set by the image. */
8b7d0a16 5748#if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4ef0d4d0
KS
5749 XColor color;
5750 png_color_16 frame_background;
5751
5752 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5753 x_query_color (f, &color);
5754
72af86bd 5755 memset (&frame_background, 0, sizeof frame_background);
c4f13f44
CY
5756 frame_background.red = color.red >> shift;
5757 frame_background.green = color.green >> shift;
5758 frame_background.blue = color.blue >> shift;
4ef0d4d0
KS
5759#endif /* HAVE_X_WINDOWS */
5760
4ef0d4d0
KS
5761 fn_png_set_background (png_ptr, &frame_background,
5762 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5763 }
5764 }
5765
5766 /* Update info structure. */
5767 fn_png_read_update_info (png_ptr, info_ptr);
5768
5769 /* Get number of channels. Valid values are 1 for grayscale images
5770 and images with a palette, 2 for grayscale images with transparency
5771 information (alpha channel), 3 for RGB images, and 4 for RGB
5772 images with alpha channel, i.e. RGBA. If conversions above were
5773 sufficient we should only have 3 or 4 channels here. */
5774 channels = fn_png_get_channels (png_ptr, info_ptr);
a54e2c05 5775 eassert (channels == 3 || channels == 4);
4ef0d4d0
KS
5776
5777 /* Number of bytes needed for one row of the image. */
5778 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5779
5780 /* Allocate memory for the image. */
3f791afe
PE
5781 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows < height
5782 || min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height < row_bytes)
5783 memory_full (SIZE_MAX);
40bce90b
PE
5784 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
5785 c->rows = rows = xmalloc (height * sizeof *rows);
4ef0d4d0
KS
5786 for (i = 0; i < height; ++i)
5787 rows[i] = pixels + i * row_bytes;
5788
5789 /* Read the entire image. */
5790 fn_png_read_image (png_ptr, rows);
5791 fn_png_read_end (png_ptr, info_ptr);
5792 if (fp)
5793 {
5794 fclose (fp);
40bce90b 5795 c->fp = NULL;
4ef0d4d0
KS
5796 }
5797
4ef0d4d0
KS
5798 /* Create an image and pixmap serving as mask if the PNG image
5799 contains an alpha channel. */
5800 if (channels == 4
5801 && !transparent_p
5802 && !x_create_x_image_and_pixmap (f, width, height, 1,
5803 &mask_img, &img->mask))
5804 {
5805 x_destroy_x_image (ximg);
5806 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5807 img->pixmap = NO_PIXMAP;
5808 goto error;
5809 }
5810
5811 /* Fill the X image and mask from PNG data. */
5812 init_color_table ();
5813
5814 for (y = 0; y < height; ++y)
5815 {
5816 png_byte *p = rows[y];
5817
5818 for (x = 0; x < width; ++x)
5819 {
13464394 5820 int r, g, b;
4ef0d4d0
KS
5821
5822 r = *p++ << 8;
5823 g = *p++ << 8;
5824 b = *p++ << 8;
5825 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5826 /* An alpha channel, aka mask channel, associates variable
5827 transparency with an image. Where other image formats
5828 support binary transparency---fully transparent or fully
5829 opaque---PNG allows up to 254 levels of partial transparency.
5830 The PNG library implements partial transparency by combining
5831 the image with a specified background color.
5832
5833 I'm not sure how to handle this here nicely: because the
5834 background on which the image is displayed may change, for
5835 real alpha channel support, it would be necessary to create
5836 a new image for each possible background.
5837
5838 What I'm doing now is that a mask is created if we have
5839 boolean transparency information. Otherwise I'm using
5840 the frame's background color to combine the image with. */
5841
5842 if (channels == 4)
5843 {
5844 if (mask_img)
9ecf6403 5845 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
4ef0d4d0
KS
5846 ++p;
5847 }
5848 }
5849 }
5850
5851 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5852 /* Set IMG's background color from the PNG image, unless the user
5853 overrode it. */
5854 {
5855 png_color_16 *bg;
5856 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5857 {
5858 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5859 img->background_valid = 1;
5860 }
5861 }
5862
5863#ifdef COLOR_TABLE_SUPPORT
5864 /* Remember colors allocated for this image. */
5865 img->colors = colors_in_color_table (&img->ncolors);
5866 free_color_table ();
5867#endif /* COLOR_TABLE_SUPPORT */
5868
5869 /* Clean up. */
40bce90b 5870 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
4ef0d4d0
KS
5871 xfree (rows);
5872 xfree (pixels);
5873
5874 img->width = width;
5875 img->height = height;
5876
2e09fef1
EZ
5877 /* Maybe fill in the background field while we have ximg handy.
5878 Casting avoids a GCC warning. */
5879 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
5880
5881 /* Put the image into the pixmap, then free the X image and its buffer. */
5882 x_put_x_image (f, ximg, img->pixmap, width, height);
5883 x_destroy_x_image (ximg);
5884
5885 /* Same for the mask. */
5886 if (mask_img)
5887 {
2e09fef1
EZ
5888 /* Fill in the background_transparent field while we have the
5889 mask handy. Casting avoids a GCC warning. */
5890 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
4ef0d4d0
KS
5891
5892 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5893 x_destroy_x_image (mask_img);
5894 }
5895
4ef0d4d0
KS
5896 return 1;
5897}
5898
578098f3 5899static bool
40bce90b
PE
5900png_load (struct frame *f, struct image *img)
5901{
5902 struct png_load_context c;
5903 return png_load_body (f, img, &c);
5904}
5905
4ef0d4d0
KS
5906#else /* HAVE_PNG */
5907
edfda783 5908#ifdef HAVE_NS
578098f3 5909static bool
edfda783
AR
5910png_load (struct frame *f, struct image *img)
5911{
5e617bc2
JB
5912 return ns_load_image (f, img,
5913 image_spec_value (img->spec, QCfile, NULL),
5914 image_spec_value (img->spec, QCdata, NULL));
edfda783
AR
5915}
5916#endif /* HAVE_NS */
5917
5918
4ef0d4d0
KS
5919#endif /* !HAVE_PNG */
5920
5921
5922\f
5923/***********************************************************************
5924 JPEG
5925 ***********************************************************************/
5926
9e2a2647 5927#if defined (HAVE_JPEG) || defined (HAVE_NS)
4ef0d4d0 5928
578098f3
PE
5929static bool jpeg_image_p (Lisp_Object object);
5930static bool jpeg_load (struct frame *f, struct image *img);
4ef0d4d0
KS
5931
5932/* The symbol `jpeg' identifying images of this type. */
5933
955cbe7b 5934static Lisp_Object Qjpeg;
4ef0d4d0
KS
5935
5936/* Indices of image specification fields in gs_format, below. */
5937
5938enum jpeg_keyword_index
5939{
5940 JPEG_TYPE,
5941 JPEG_DATA,
5942 JPEG_FILE,
5943 JPEG_ASCENT,
5944 JPEG_MARGIN,
5945 JPEG_RELIEF,
5946 JPEG_ALGORITHM,
5947 JPEG_HEURISTIC_MASK,
5948 JPEG_MASK,
5949 JPEG_BACKGROUND,
5950 JPEG_LAST
5951};
5952
5953/* Vector of image_keyword structures describing the format
5954 of valid user-defined image specifications. */
5955
91433552 5956static const struct image_keyword jpeg_format[JPEG_LAST] =
4ef0d4d0
KS
5957{
5958 {":type", IMAGE_SYMBOL_VALUE, 1},
5959 {":data", IMAGE_STRING_VALUE, 0},
5960 {":file", IMAGE_STRING_VALUE, 0},
5961 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 5962 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
5963 {":relief", IMAGE_INTEGER_VALUE, 0},
5964 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5965 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5966 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5967 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5968};
5969
a9e7a9d5 5970#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 5971static bool init_jpeg_functions (void);
bb4d86b4
CY
5972#else
5973#define init_jpeg_functions NULL
5974#endif
5975
4ef0d4d0
KS
5976/* Structure describing the image type `jpeg'. */
5977
5978static struct image_type jpeg_type =
5979{
5980 &Qjpeg,
5981 jpeg_image_p,
5982 jpeg_load,
5983 x_clear_image,
bb4d86b4 5984 init_jpeg_functions,
4ef0d4d0
KS
5985 NULL
5986};
5987
578098f3 5988/* Return true if OBJECT is a valid JPEG image specification. */
4ef0d4d0 5989
578098f3 5990static bool
d3da34e0 5991jpeg_image_p (Lisp_Object object)
4ef0d4d0
KS
5992{
5993 struct image_keyword fmt[JPEG_LAST];
5994
72af86bd 5995 memcpy (fmt, jpeg_format, sizeof fmt);
4ef0d4d0
KS
5996
5997 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
5998 return 0;
5999
6000 /* Must specify either the :data or :file keyword. */
6001 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6002}
6003
9e2a2647 6004#endif /* HAVE_JPEG || HAVE_NS */
4ef0d4d0
KS
6005
6006#ifdef HAVE_JPEG
6007
6008/* Work around a warning about HAVE_STDLIB_H being redefined in
6009 jconfig.h. */
6010#ifdef HAVE_STDLIB_H
4ef0d4d0
KS
6011#undef HAVE_STDLIB_H
6012#endif /* HAVE_STLIB_H */
6013
66354420 6014#if defined (HAVE_NTGUI) && !defined (__WIN32__)
28893db2
JB
6015/* In older releases of the jpeg library, jpeglib.h will define boolean
6016 differently depending on __WIN32__, so make sure it is defined. */
66354420
JR
6017#define __WIN32__ 1
6018#endif
6019
93aa5c81
DC
6020/* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6021 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6022 using the Windows boolean type instead of the jpeglib boolean type
6023 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6024 headers are included along with windows.h, so under Cygwin, jpeglib
6025 attempts to define a conflicting boolean type. Worse, forcing
6026 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6027 because it created an ABI incompatibility between the
6028 already-compiled jpeg library and the header interface definition.
6029
6030 The best we can do is to define jpeglib's boolean type to a
6031 different name. This name, jpeg_boolean, remains in effect through
6032 the rest of image.c.
6033*/
a9e7a9d5 6034#if defined CYGWIN && defined HAVE_NTGUI
0fda9b75 6035#define boolean jpeg_boolean
2ae3a8a7 6036#endif
4ef0d4d0
KS
6037#include <jpeglib.h>
6038#include <jerror.h>
4ef0d4d0 6039
0fda9b75 6040#ifdef WINDOWSNT
4ef0d4d0
KS
6041
6042/* JPEG library details. */
14beddf4
CY
6043DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6044DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6045DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6046DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6047DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6048DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6049DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6050DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
4ef0d4d0 6051
578098f3 6052static bool
d07ff9db 6053init_jpeg_functions (void)
4ef0d4d0
KS
6054{
6055 HMODULE library;
6056
d07ff9db 6057 if (!(library = w32_delayed_load (Qjpeg)))
4ef0d4d0
KS
6058 return 0;
6059
6060 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6061 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6062 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6063 LOAD_IMGLIB_FN (library, jpeg_read_header);
4ef0d4d0
KS
6064 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6065 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6066 LOAD_IMGLIB_FN (library, jpeg_std_error);
6067 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6068 return 1;
6069}
6070
6071/* Wrapper since we can't directly assign the function pointer
6072 to another function pointer that was declared more completely easily. */
6073static boolean
7c3320d8 6074jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
4ef0d4d0
KS
6075{
6076 return fn_jpeg_resync_to_restart (cinfo, desired);
6077}
6078
6079#else
6080
5e617bc2 6081#define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
4ef0d4d0
KS
6082#define fn_jpeg_start_decompress jpeg_start_decompress
6083#define fn_jpeg_finish_decompress jpeg_finish_decompress
6084#define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6085#define fn_jpeg_read_header jpeg_read_header
6086#define fn_jpeg_read_scanlines jpeg_read_scanlines
4ef0d4d0
KS
6087#define fn_jpeg_std_error jpeg_std_error
6088#define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6089
0fda9b75 6090#endif /* WINDOWSNT */
4ef0d4d0
KS
6091
6092struct my_jpeg_error_mgr
6093{
6094 struct jpeg_error_mgr pub;
0328b6de 6095 sys_jmp_buf setjmp_buffer;
40bce90b 6096
0328b6de 6097 /* The remaining members are so that longjmp doesn't munge local
40bce90b
PE
6098 variables. */
6099 struct jpeg_decompress_struct cinfo;
6100 enum
6101 {
6102 MY_JPEG_ERROR_EXIT,
6103 MY_JPEG_INVALID_IMAGE_SIZE,
6104 MY_JPEG_CANNOT_CREATE_X
6105 } failure_code;
5f0cb45a
PE
6106#ifdef lint
6107 FILE *fp;
6108#endif
4ef0d4d0
KS
6109};
6110
6111
845ca893 6112static _Noreturn void
d3da34e0 6113my_error_exit (j_common_ptr cinfo)
4ef0d4d0
KS
6114{
6115 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
40bce90b 6116 mgr->failure_code = MY_JPEG_ERROR_EXIT;
0328b6de 6117 sys_longjmp (mgr->setjmp_buffer, 1);
4ef0d4d0
KS
6118}
6119
6120
6121/* Init source method for JPEG data source manager. Called by
6122 jpeg_read_header() before any data is actually read. See
6123 libjpeg.doc from the JPEG lib distribution. */
6124
6125static void
d3da34e0 6126our_common_init_source (j_decompress_ptr cinfo)
b25a72ab
JB
6127{
6128}
6129
6130
6131/* Method to terminate data source. Called by
6132 jpeg_finish_decompress() after all data has been processed. */
6133
6134static void
d3da34e0 6135our_common_term_source (j_decompress_ptr cinfo)
4ef0d4d0
KS
6136{
6137}
6138
6139
6140/* Fill input buffer method for JPEG data source manager. Called
6141 whenever more data is needed. We read the whole image in one step,
6142 so this only adds a fake end of input marker at the end. */
6143
5a1539f3 6144static JOCTET our_memory_buffer[2];
aca946f3 6145
4ef0d4d0 6146static boolean
d3da34e0 6147our_memory_fill_input_buffer (j_decompress_ptr cinfo)
4ef0d4d0
KS
6148{
6149 /* Insert a fake EOI marker. */
6150 struct jpeg_source_mgr *src = cinfo->src;
4ef0d4d0 6151
5a1539f3
MB
6152 our_memory_buffer[0] = (JOCTET) 0xFF;
6153 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
4ef0d4d0 6154
5a1539f3 6155 src->next_input_byte = our_memory_buffer;
4ef0d4d0 6156 src->bytes_in_buffer = 2;
e0e30823 6157 return 1;
4ef0d4d0
KS
6158}
6159
6160
6161/* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6162 is the JPEG data source manager. */
6163
6164static void
d3da34e0 6165our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
4ef0d4d0
KS
6166{
6167 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6168
6169 if (src)
6170 {
6171 if (num_bytes > src->bytes_in_buffer)
6172 ERREXIT (cinfo, JERR_INPUT_EOF);
6173
6174 src->bytes_in_buffer -= num_bytes;
6175 src->next_input_byte += num_bytes;
6176 }
6177}
6178
6179
4ef0d4d0
KS
6180/* Set up the JPEG lib for reading an image from DATA which contains
6181 LEN bytes. CINFO is the decompression info structure created for
6182 reading the image. */
6183
6184static void
92547ff9 6185jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
4ef0d4d0
KS
6186{
6187 struct jpeg_source_mgr *src;
6188
6189 if (cinfo->src == NULL)
6190 {
6191 /* First time for this JPEG object? */
6192 cinfo->src = (struct jpeg_source_mgr *)
6193 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6194 sizeof (struct jpeg_source_mgr));
6195 src = (struct jpeg_source_mgr *) cinfo->src;
6196 src->next_input_byte = data;
6197 }
6198
6199 src = (struct jpeg_source_mgr *) cinfo->src;
b25a72ab
JB
6200 src->init_source = our_common_init_source;
6201 src->fill_input_buffer = our_memory_fill_input_buffer;
6202 src->skip_input_data = our_memory_skip_input_data;
4ef0d4d0 6203 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
b25a72ab 6204 src->term_source = our_common_term_source;
4ef0d4d0
KS
6205 src->bytes_in_buffer = len;
6206 src->next_input_byte = data;
6207}
6208
6209
b25a72ab
JB
6210struct jpeg_stdio_mgr
6211{
6212 struct jpeg_source_mgr mgr;
6213 boolean finished;
6214 FILE *file;
6215 JOCTET *buffer;
6216};
6217
6218
6219/* Size of buffer to read JPEG from file.
6220 Not too big, as we want to use alloc_small. */
6221#define JPEG_STDIO_BUFFER_SIZE 8192
6222
6223
6224/* Fill input buffer method for JPEG data source manager. Called
6225 whenever more data is needed. The data is read from a FILE *. */
6226
6227static boolean
d3da34e0 6228our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
b25a72ab
JB
6229{
6230 struct jpeg_stdio_mgr *src;
6231
6232 src = (struct jpeg_stdio_mgr *) cinfo->src;
6233 if (!src->finished)
6234 {
3f791afe 6235 ptrdiff_t bytes;
b25a72ab
JB
6236
6237 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6238 if (bytes > 0)
6239 src->mgr.bytes_in_buffer = bytes;
6240 else
6241 {
6242 WARNMS (cinfo, JWRN_JPEG_EOF);
6243 src->finished = 1;
6244 src->buffer[0] = (JOCTET) 0xFF;
6245 src->buffer[1] = (JOCTET) JPEG_EOI;
6246 src->mgr.bytes_in_buffer = 2;
6247 }
6248 src->mgr.next_input_byte = src->buffer;
6249 }
6250
6251 return 1;
6252}
6253
6254
6255/* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6256 is the JPEG data source manager. */
6257
6258static void
d3da34e0 6259our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
b25a72ab
JB
6260{
6261 struct jpeg_stdio_mgr *src;
6262 src = (struct jpeg_stdio_mgr *) cinfo->src;
6263
6264 while (num_bytes > 0 && !src->finished)
6265 {
6266 if (num_bytes <= src->mgr.bytes_in_buffer)
6267 {
6268 src->mgr.bytes_in_buffer -= num_bytes;
6269 src->mgr.next_input_byte += num_bytes;
6270 break;
6271 }
6272 else
6273 {
6274 num_bytes -= src->mgr.bytes_in_buffer;
6275 src->mgr.bytes_in_buffer = 0;
6276 src->mgr.next_input_byte = NULL;
6277
6278 our_stdio_fill_input_buffer (cinfo);
6279 }
6280 }
6281}
6282
6283
6284/* Set up the JPEG lib for reading an image from a FILE *.
6285 CINFO is the decompression info structure created for
6286 reading the image. */
6287
6288static void
d3da34e0 6289jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
b25a72ab
JB
6290{
6291 struct jpeg_stdio_mgr *src;
6292
6293 if (cinfo->src != NULL)
6294 src = (struct jpeg_stdio_mgr *) cinfo->src;
6295 else
6296 {
6297 /* First time for this JPEG object? */
6298 cinfo->src = (struct jpeg_source_mgr *)
6299 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6300 sizeof (struct jpeg_stdio_mgr));
6301 src = (struct jpeg_stdio_mgr *) cinfo->src;
6302 src->buffer = (JOCTET *)
6303 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6304 JPEG_STDIO_BUFFER_SIZE);
6305 }
6306
6307 src->file = fp;
6308 src->finished = 0;
6309 src->mgr.init_source = our_common_init_source;
6310 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6311 src->mgr.skip_input_data = our_stdio_skip_input_data;
6312 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6313 src->mgr.term_source = our_common_term_source;
6314 src->mgr.bytes_in_buffer = 0;
6315 src->mgr.next_input_byte = NULL;
6316}
6317
6318
4ef0d4d0
KS
6319/* Load image IMG for use on frame F. Patterned after example.c
6320 from the JPEG lib. */
6321
578098f3 6322static bool
40bce90b
PE
6323jpeg_load_body (struct frame *f, struct image *img,
6324 struct my_jpeg_error_mgr *mgr)
4ef0d4d0 6325{
4ef0d4d0
KS
6326 Lisp_Object file, specified_file;
6327 Lisp_Object specified_data;
40bce90b 6328 FILE *fp = NULL;
4ef0d4d0
KS
6329 JSAMPARRAY buffer;
6330 int row_stride, x, y;
6331 XImagePtr ximg = NULL;
4ef0d4d0
KS
6332 unsigned long *colors;
6333 int width, height;
4ef0d4d0
KS
6334
6335 /* Open the JPEG file. */
6336 specified_file = image_spec_value (img->spec, QCfile, NULL);
6337 specified_data = image_spec_value (img->spec, QCdata, NULL);
4ef0d4d0
KS
6338
6339 if (NILP (specified_data))
6340 {
6341 file = x_find_image_file (specified_file);
6342 if (!STRINGP (file))
6343 {
6344 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
6345 return 0;
6346 }
6347
42a5b22f 6348 fp = fopen (SSDATA (file), "rb");
4ef0d4d0
KS
6349 if (fp == NULL)
6350 {
6351 image_error ("Cannot open `%s'", file, Qnil);
4ef0d4d0
KS
6352 return 0;
6353 }
6354 }
7574650a
AS
6355 else if (!STRINGP (specified_data))
6356 {
6357 image_error ("Invalid image data `%s'", specified_data, Qnil);
6358 return 0;
6359 }
4ef0d4d0 6360
5f0cb45a
PE
6361 IF_LINT (mgr->fp = fp);
6362
4ef0d4d0 6363 /* Customize libjpeg's error handling to call my_error_exit when an
df61c790 6364 error is detected. This function will perform a longjmp. */
40bce90b
PE
6365 mgr->cinfo.err = fn_jpeg_std_error (&mgr->pub);
6366 mgr->pub.error_exit = my_error_exit;
0328b6de 6367 if (sys_setjmp (mgr->setjmp_buffer))
4ef0d4d0 6368 {
40bce90b 6369 switch (mgr->failure_code)
4ef0d4d0 6370 {
40bce90b
PE
6371 case MY_JPEG_ERROR_EXIT:
6372 {
6373 char buf[JMSG_LENGTH_MAX];
6374 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6375 image_error ("Error reading JPEG image `%s': %s", img->spec,
6376 build_string (buf));
6377 break;
6378 }
6379
6380 case MY_JPEG_INVALID_IMAGE_SIZE:
6381 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6382 break;
6383
6384 case MY_JPEG_CANNOT_CREATE_X:
6385 break;
4ef0d4d0
KS
6386 }
6387
6388 /* Close the input file and destroy the JPEG object. */
6389 if (fp)
40bce90b
PE
6390 fclose (fp);
6391 fn_jpeg_destroy_decompress (&mgr->cinfo);
4ef0d4d0
KS
6392
6393 /* If we already have an XImage, free that. */
6394 x_destroy_x_image (ximg);
6395
6396 /* Free pixmap and colors. */
6397 x_clear_image (f, img);
4ef0d4d0
KS
6398 return 0;
6399 }
6400
5f0cb45a
PE
6401 /* Silence a bogus diagnostic; see GCC bug 54561. */
6402 IF_LINT (fp = mgr->fp);
6403
4ef0d4d0
KS
6404 /* Create the JPEG decompression object. Let it read from fp.
6405 Read the JPEG image header. */
40bce90b 6406 fn_jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
4ef0d4d0
KS
6407
6408 if (NILP (specified_data))
40bce90b 6409 jpeg_file_src (&mgr->cinfo, fp);
4ef0d4d0 6410 else
40bce90b 6411 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
4ef0d4d0
KS
6412 SBYTES (specified_data));
6413
40bce90b 6414 fn_jpeg_read_header (&mgr->cinfo, 1);
4ef0d4d0
KS
6415
6416 /* Customize decompression so that color quantization will be used.
6417 Start decompression. */
40bce90b
PE
6418 mgr->cinfo.quantize_colors = 1;
6419 fn_jpeg_start_decompress (&mgr->cinfo);
6420 width = img->width = mgr->cinfo.output_width;
6421 height = img->height = mgr->cinfo.output_height;
4ef0d4d0 6422
f1f25b99
CY
6423 if (!check_image_size (f, width, height))
6424 {
40bce90b 6425 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
0328b6de 6426 sys_longjmp (mgr->setjmp_buffer, 1);
f1f25b99
CY
6427 }
6428
4ef0d4d0
KS
6429 /* Create X image and pixmap. */
6430 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
40bce90b
PE
6431 {
6432 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
0328b6de 6433 sys_longjmp (mgr->setjmp_buffer, 1);
40bce90b 6434 }
4ef0d4d0
KS
6435
6436 /* Allocate colors. When color quantization is used,
40bce90b
PE
6437 mgr->cinfo.actual_number_of_colors has been set with the number of
6438 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6439 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
4ef0d4d0
KS
6440 No more than 255 colors will be generated. */
6441 {
6442 int i, ir, ig, ib;
6443
40bce90b 6444 if (mgr->cinfo.out_color_components > 2)
4ef0d4d0 6445 ir = 0, ig = 1, ib = 2;
40bce90b 6446 else if (mgr->cinfo.out_color_components > 1)
4ef0d4d0
KS
6447 ir = 0, ig = 1, ib = 0;
6448 else
6449 ir = 0, ig = 0, ib = 0;
6450
6451 /* Use the color table mechanism because it handles colors that
6452 cannot be allocated nicely. Such colors will be replaced with
6453 a default color, and we don't have to care about which colors
6454 can be freed safely, and which can't. */
6455 init_color_table ();
40bce90b 6456 colors = alloca (mgr->cinfo.actual_number_of_colors * sizeof *colors);
4ef0d4d0 6457
40bce90b 6458 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
4ef0d4d0
KS
6459 {
6460 /* Multiply RGB values with 255 because X expects RGB values
6461 in the range 0..0xffff. */
40bce90b
PE
6462 int r = mgr->cinfo.colormap[ir][i] << 8;
6463 int g = mgr->cinfo.colormap[ig][i] << 8;
6464 int b = mgr->cinfo.colormap[ib][i] << 8;
4ef0d4d0
KS
6465 colors[i] = lookup_rgb_color (f, r, g, b);
6466 }
6467
6468#ifdef COLOR_TABLE_SUPPORT
6469 /* Remember those colors actually allocated. */
6470 img->colors = colors_in_color_table (&img->ncolors);
6471 free_color_table ();
6472#endif /* COLOR_TABLE_SUPPORT */
6473 }
6474
6475 /* Read pixels. */
40bce90b
PE
6476 row_stride = width * mgr->cinfo.output_components;
6477 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6478 JPOOL_IMAGE, row_stride, 1);
4ef0d4d0
KS
6479 for (y = 0; y < height; ++y)
6480 {
40bce90b
PE
6481 fn_jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6482 for (x = 0; x < mgr->cinfo.output_width; ++x)
4ef0d4d0
KS
6483 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6484 }
6485
6486 /* Clean up. */
40bce90b
PE
6487 fn_jpeg_finish_decompress (&mgr->cinfo);
6488 fn_jpeg_destroy_decompress (&mgr->cinfo);
4ef0d4d0 6489 if (fp)
40bce90b 6490 fclose (fp);
4ef0d4d0
KS
6491
6492 /* Maybe fill in the background field while we have ximg handy. */
6493 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
6494 /* Casting avoids a GCC warning. */
6495 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
6496
6497 /* Put the image into the pixmap. */
6498 x_put_x_image (f, ximg, img->pixmap, width, height);
6499 x_destroy_x_image (ximg);
4ef0d4d0
KS
6500 return 1;
6501}
6502
578098f3 6503static bool
40bce90b
PE
6504jpeg_load (struct frame *f, struct image *img)
6505{
6506 struct my_jpeg_error_mgr mgr;
6507 return jpeg_load_body (f, img, &mgr);
6508}
6509
4ef0d4d0
KS
6510#else /* HAVE_JPEG */
6511
edfda783 6512#ifdef HAVE_NS
578098f3 6513static bool
edfda783
AR
6514jpeg_load (struct frame *f, struct image *img)
6515{
ed3751c8
JB
6516 return ns_load_image (f, img,
6517 image_spec_value (img->spec, QCfile, NULL),
6518 image_spec_value (img->spec, QCdata, NULL));
edfda783
AR
6519}
6520#endif /* HAVE_NS */
6521
4ef0d4d0
KS
6522#endif /* !HAVE_JPEG */
6523
6524
6525\f
6526/***********************************************************************
6527 TIFF
6528 ***********************************************************************/
6529
9e2a2647 6530#if defined (HAVE_TIFF) || defined (HAVE_NS)
4ef0d4d0 6531
578098f3
PE
6532static bool tiff_image_p (Lisp_Object object);
6533static bool tiff_load (struct frame *f, struct image *img);
4ef0d4d0
KS
6534
6535/* The symbol `tiff' identifying images of this type. */
6536
955cbe7b 6537static Lisp_Object Qtiff;
4ef0d4d0
KS
6538
6539/* Indices of image specification fields in tiff_format, below. */
6540
6541enum tiff_keyword_index
6542{
6543 TIFF_TYPE,
6544 TIFF_DATA,
6545 TIFF_FILE,
6546 TIFF_ASCENT,
6547 TIFF_MARGIN,
6548 TIFF_RELIEF,
6549 TIFF_ALGORITHM,
6550 TIFF_HEURISTIC_MASK,
6551 TIFF_MASK,
6552 TIFF_BACKGROUND,
58279503 6553 TIFF_INDEX,
4ef0d4d0
KS
6554 TIFF_LAST
6555};
6556
6557/* Vector of image_keyword structures describing the format
6558 of valid user-defined image specifications. */
6559
91433552 6560static const struct image_keyword tiff_format[TIFF_LAST] =
4ef0d4d0
KS
6561{
6562 {":type", IMAGE_SYMBOL_VALUE, 1},
6563 {":data", IMAGE_STRING_VALUE, 0},
6564 {":file", IMAGE_STRING_VALUE, 0},
6565 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 6566 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
6567 {":relief", IMAGE_INTEGER_VALUE, 0},
6568 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6569 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6570 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
58279503
JR
6571 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6572 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
4ef0d4d0
KS
6573};
6574
33d4113c 6575#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 6576static bool init_tiff_functions (void);
bb4d86b4
CY
6577#else
6578#define init_tiff_functions NULL
6579#endif
6580
4ef0d4d0
KS
6581/* Structure describing the image type `tiff'. */
6582
6583static struct image_type tiff_type =
6584{
6585 &Qtiff,
6586 tiff_image_p,
6587 tiff_load,
6588 x_clear_image,
bb4d86b4 6589 init_tiff_functions,
4ef0d4d0
KS
6590 NULL
6591};
6592
578098f3 6593/* Return true if OBJECT is a valid TIFF image specification. */
4ef0d4d0 6594
578098f3 6595static bool
d3da34e0 6596tiff_image_p (Lisp_Object object)
4ef0d4d0
KS
6597{
6598 struct image_keyword fmt[TIFF_LAST];
72af86bd 6599 memcpy (fmt, tiff_format, sizeof fmt);
4ef0d4d0
KS
6600
6601 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6602 return 0;
6603
6604 /* Must specify either the :data or :file keyword. */
6605 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6606}
6607
9e2a2647 6608#endif /* HAVE_TIFF || HAVE_NS */
4ef0d4d0
KS
6609
6610#ifdef HAVE_TIFF
6611
6612#include <tiffio.h>
6613
0fda9b75 6614#ifdef WINDOWSNT
4ef0d4d0
KS
6615
6616/* TIFF library details. */
14beddf4
CY
6617DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6618DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6619DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6620DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
850690cc
JB
6621 TIFFReadWriteProc, TIFFReadWriteProc,
6622 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6623 TIFFMapFileProc, TIFFUnmapFileProc));
14beddf4
CY
6624DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6625DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6626DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6627DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
4ef0d4d0 6628
578098f3 6629static bool
d07ff9db 6630init_tiff_functions (void)
4ef0d4d0
KS
6631{
6632 HMODULE library;
6633
d07ff9db 6634 if (!(library = w32_delayed_load (Qtiff)))
4ef0d4d0
KS
6635 return 0;
6636
6637 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6638 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6639 LOAD_IMGLIB_FN (library, TIFFOpen);
6640 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6641 LOAD_IMGLIB_FN (library, TIFFGetField);
6642 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6643 LOAD_IMGLIB_FN (library, TIFFClose);
58279503 6644 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
4ef0d4d0
KS
6645 return 1;
6646}
6647
6648#else
6649
6650#define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6651#define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6652#define fn_TIFFOpen TIFFOpen
6653#define fn_TIFFClientOpen TIFFClientOpen
6654#define fn_TIFFGetField TIFFGetField
6655#define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6656#define fn_TIFFClose TIFFClose
58279503 6657#define fn_TIFFSetDirectory TIFFSetDirectory
0fda9b75 6658#endif /* WINDOWSNT */
4ef0d4d0
KS
6659
6660
6661/* Reading from a memory buffer for TIFF images Based on the PNG
6662 memory source, but we have to provide a lot of extra functions.
6663 Blah.
6664
6665 We really only need to implement read and seek, but I am not
6666 convinced that the TIFF library is smart enough not to destroy
6667 itself if we only hand it the function pointers we need to
6668 override. */
6669
6670typedef struct
6671{
6672 unsigned char *bytes;
3f791afe
PE
6673 ptrdiff_t len;
6674 ptrdiff_t index;
4ef0d4d0
KS
6675}
6676tiff_memory_source;
6677
3f791afe 6678static tsize_t
d3da34e0 6679tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
4ef0d4d0
KS
6680{
6681 tiff_memory_source *src = (tiff_memory_source *) data;
6682
3f791afe 6683 size = min (size, src->len - src->index);
72af86bd 6684 memcpy (buf, src->bytes + src->index, size);
4ef0d4d0
KS
6685 src->index += size;
6686 return size;
6687}
6688
3f791afe 6689static tsize_t
d3da34e0 6690tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
4ef0d4d0 6691{
3f791afe 6692 return -1;
4ef0d4d0
KS
6693}
6694
6695static toff_t
d3da34e0 6696tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
4ef0d4d0
KS
6697{
6698 tiff_memory_source *src = (tiff_memory_source *) data;
3f791afe 6699 ptrdiff_t idx;
4ef0d4d0
KS
6700
6701 switch (whence)
6702 {
6703 case SEEK_SET: /* Go from beginning of source. */
6704 idx = off;
6705 break;
6706
6707 case SEEK_END: /* Go from end of source. */
6708 idx = src->len + off;
6709 break;
6710
6711 case SEEK_CUR: /* Go from current position. */
6712 idx = src->index + off;
6713 break;
6714
6715 default: /* Invalid `whence'. */
6716 return -1;
6717 }
6718
6719 if (idx > src->len || idx < 0)
6720 return -1;
6721
6722 src->index = idx;
6723 return src->index;
6724}
6725
6726static int
d3da34e0 6727tiff_close_memory (thandle_t data)
4ef0d4d0
KS
6728{
6729 /* NOOP */
6730 return 0;
6731}
6732
6733static int
d3da34e0 6734tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
4ef0d4d0
KS
6735{
6736 /* It is already _IN_ memory. */
6737 return 0;
6738}
6739
6740static void
d3da34e0 6741tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
4ef0d4d0
KS
6742{
6743 /* We don't need to do this. */
6744}
6745
6746static toff_t
d3da34e0 6747tiff_size_of_memory (thandle_t data)
4ef0d4d0
KS
6748{
6749 return ((tiff_memory_source *) data)->len;
6750}
6751
b41c3a35
EZ
6752/* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6753 compiler error compiling tiff_handler, see Bugzilla bug #17406
6754 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6755 this function as external works around that problem. */
6756#if defined (__MINGW32__) && __GNUC__ == 3
6757# define MINGW_STATIC
6758#else
6759# define MINGW_STATIC static
6760#endif
4ef0d4d0 6761
b41c3a35
EZ
6762MINGW_STATIC void
6763tiff_handler (const char *, const char *, const char *, va_list)
13464394 6764 ATTRIBUTE_FORMAT_PRINTF (3, 0);
b41c3a35 6765MINGW_STATIC void
13464394
PE
6766tiff_handler (const char *log_format, const char *title,
6767 const char *format, va_list ap)
6768{
6769 /* doprnt is not suitable here, as TIFF handlers are called from
6770 libtiff and are passed arbitrary printf directives. Instead, use
6771 vsnprintf, taking care to be portable to nonstandard environments
6772 where vsnprintf returns -1 on buffer overflow. Since it's just a
6773 log entry, it's OK to truncate it. */
6774 char buf[4000];
6775 int len = vsnprintf (buf, sizeof buf, format, ap);
6776 add_to_log (log_format, build_string (title),
6777 make_string (buf, max (0, min (len, sizeof buf - 1))));
6778}
b41c3a35 6779#undef MINGW_STATIC
13464394 6780
5e2d4a30
PE
6781static void tiff_error_handler (const char *, const char *, va_list)
6782 ATTRIBUTE_FORMAT_PRINTF (2, 0);
4ef0d4d0 6783static void
d3da34e0 6784tiff_error_handler (const char *title, const char *format, va_list ap)
4ef0d4d0 6785{
13464394 6786 tiff_handler ("TIFF error: %s %s", title, format, ap);
4ef0d4d0
KS
6787}
6788
6789
5e2d4a30
PE
6790static void tiff_warning_handler (const char *, const char *, va_list)
6791 ATTRIBUTE_FORMAT_PRINTF (2, 0);
4ef0d4d0 6792static void
d3da34e0 6793tiff_warning_handler (const char *title, const char *format, va_list ap)
4ef0d4d0 6794{
13464394 6795 tiff_handler ("TIFF warning: %s %s", title, format, ap);
4ef0d4d0
KS
6796}
6797
6798
578098f3 6799/* Load TIFF image IMG for use on frame F. Value is true if
4ef0d4d0
KS
6800 successful. */
6801
578098f3 6802static bool
d3da34e0 6803tiff_load (struct frame *f, struct image *img)
4ef0d4d0
KS
6804{
6805 Lisp_Object file, specified_file;
6806 Lisp_Object specified_data;
6807 TIFF *tiff;
58279503 6808 int width, height, x, y, count;
4ef0d4d0 6809 uint32 *buf;
03d0a109 6810 int rc;
4ef0d4d0 6811 XImagePtr ximg;
4ef0d4d0 6812 tiff_memory_source memsrc;
58279503 6813 Lisp_Object image;
4ef0d4d0
KS
6814
6815 specified_file = image_spec_value (img->spec, QCfile, NULL);
6816 specified_data = image_spec_value (img->spec, QCdata, NULL);
4ef0d4d0 6817
5e2d4a30
PE
6818 fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6819 fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
4ef0d4d0
KS
6820
6821 if (NILP (specified_data))
6822 {
6823 /* Read from a file */
6824 file = x_find_image_file (specified_file);
6825 if (!STRINGP (file))
6826 {
6827 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
6828 return 0;
6829 }
6830
df61c790 6831 /* Try to open the image file. */
b19beacc 6832 tiff = fn_TIFFOpen (SSDATA (file), "r");
4ef0d4d0
KS
6833 if (tiff == NULL)
6834 {
6835 image_error ("Cannot open `%s'", file, Qnil);
4ef0d4d0
KS
6836 return 0;
6837 }
6838 }
6839 else
6840 {
7574650a
AS
6841 if (!STRINGP (specified_data))
6842 {
6843 image_error ("Invalid image data `%s'", specified_data, Qnil);
6844 return 0;
6845 }
6846
4ef0d4d0
KS
6847 /* Memory source! */
6848 memsrc.bytes = SDATA (specified_data);
6849 memsrc.len = SBYTES (specified_data);
6850 memsrc.index = 0;
6851
3082f617 6852 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
3f791afe
PE
6853 tiff_read_from_memory,
6854 tiff_write_from_memory,
df61c790
AS
6855 tiff_seek_in_memory,
6856 tiff_close_memory,
6857 tiff_size_of_memory,
6858 tiff_mmap_memory,
6859 tiff_unmap_memory);
4ef0d4d0
KS
6860
6861 if (!tiff)
6862 {
6863 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
4ef0d4d0
KS
6864 return 0;
6865 }
6866 }
6867
58279503
JR
6868 image = image_spec_value (img->spec, QCindex, NULL);
6869 if (INTEGERP (image))
6870 {
13464394
PE
6871 EMACS_INT ino = XFASTINT (image);
6872 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
6873 && fn_TIFFSetDirectory (tiff, ino)))
58279503
JR
6874 {
6875 image_error ("Invalid image number `%s' in image `%s'",
6876 image, img->spec);
6877 fn_TIFFClose (tiff);
58279503
JR
6878 return 0;
6879 }
6880 }
6881
4ef0d4d0
KS
6882 /* Get width and height of the image, and allocate a raster buffer
6883 of width x height 32-bit values. */
6884 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6885 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
f1f25b99
CY
6886
6887 if (!check_image_size (f, width, height))
6888 {
10ea2b82 6889 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
58279503 6890 fn_TIFFClose (tiff);
f1f25b99
CY
6891 return 0;
6892 }
6893
ca4aa935
PE
6894 /* Create the X image and pixmap. */
6895 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
6896 && x_create_x_image_and_pixmap (f, width, height, 0,
6897 &ximg, &img->pixmap)))
6898 {
6899 fn_TIFFClose (tiff);
6900 return 0;
6901 }
6902
23f86fce 6903 buf = xmalloc (sizeof *buf * width * height);
4ef0d4d0
KS
6904
6905 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
58279503
JR
6906
6907 /* Count the number of images in the file. */
03d0a109
PE
6908 for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
6909 continue;
58279503
JR
6910
6911 if (count > 1)
b50691aa
CY
6912 img->lisp_data = Fcons (Qcount,
6913 Fcons (make_number (count),
6914 img->lisp_data));
58279503 6915
4ef0d4d0
KS
6916 fn_TIFFClose (tiff);
6917 if (!rc)
6918 {
6919 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6920 xfree (buf);
4ef0d4d0
KS
6921 return 0;
6922 }
6923
4ef0d4d0
KS
6924 /* Initialize the color table. */
6925 init_color_table ();
6926
6927 /* Process the pixel raster. Origin is in the lower-left corner. */
6928 for (y = 0; y < height; ++y)
6929 {
6930 uint32 *row = buf + y * width;
6931
6932 for (x = 0; x < width; ++x)
6933 {
6934 uint32 abgr = row[x];
6935 int r = TIFFGetR (abgr) << 8;
6936 int g = TIFFGetG (abgr) << 8;
6937 int b = TIFFGetB (abgr) << 8;
6938 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6939 }
6940 }
6941
6942#ifdef COLOR_TABLE_SUPPORT
6943 /* Remember the colors allocated for the image. Free the color table. */
6944 img->colors = colors_in_color_table (&img->ncolors);
6945 free_color_table ();
6946#endif /* COLOR_TABLE_SUPPORT */
6947
6948 img->width = width;
6949 img->height = height;
6950
6951 /* Maybe fill in the background field while we have ximg handy. */
6952 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
6953 /* Casting avoids a GCC warning on W32. */
6954 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
6955
6956 /* Put the image into the pixmap, then free the X image and its buffer. */
6957 x_put_x_image (f, ximg, img->pixmap, width, height);
6958 x_destroy_x_image (ximg);
6959 xfree (buf);
6960
4ef0d4d0
KS
6961 return 1;
6962}
6963
6964#else /* HAVE_TIFF */
6965
edfda783 6966#ifdef HAVE_NS
578098f3 6967static bool
edfda783
AR
6968tiff_load (struct frame *f, struct image *img)
6969{
ed3751c8
JB
6970 return ns_load_image (f, img,
6971 image_spec_value (img->spec, QCfile, NULL),
6972 image_spec_value (img->spec, QCdata, NULL));
edfda783
AR
6973}
6974#endif /* HAVE_NS */
6975
4ef0d4d0
KS
6976#endif /* !HAVE_TIFF */
6977
6978
6979\f
6980/***********************************************************************
6981 GIF
6982 ***********************************************************************/
6983
9e2a2647 6984#if defined (HAVE_GIF) || defined (HAVE_NS)
4ef0d4d0 6985
578098f3
PE
6986static bool gif_image_p (Lisp_Object object);
6987static bool gif_load (struct frame *f, struct image *img);
f57e2426 6988static void gif_clear_image (struct frame *f, struct image *img);
4ef0d4d0
KS
6989
6990/* The symbol `gif' identifying images of this type. */
6991
955cbe7b 6992static Lisp_Object Qgif;
4ef0d4d0
KS
6993
6994/* Indices of image specification fields in gif_format, below. */
6995
6996enum gif_keyword_index
6997{
6998 GIF_TYPE,
6999 GIF_DATA,
7000 GIF_FILE,
7001 GIF_ASCENT,
7002 GIF_MARGIN,
7003 GIF_RELIEF,
7004 GIF_ALGORITHM,
7005 GIF_HEURISTIC_MASK,
7006 GIF_MASK,
7007 GIF_IMAGE,
7008 GIF_BACKGROUND,
7009 GIF_LAST
7010};
7011
7012/* Vector of image_keyword structures describing the format
7013 of valid user-defined image specifications. */
7014
91433552 7015static const struct image_keyword gif_format[GIF_LAST] =
4ef0d4d0
KS
7016{
7017 {":type", IMAGE_SYMBOL_VALUE, 1},
7018 {":data", IMAGE_STRING_VALUE, 0},
7019 {":file", IMAGE_STRING_VALUE, 0},
7020 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 7021 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ef0d4d0
KS
7022 {":relief", IMAGE_INTEGER_VALUE, 0},
7023 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7024 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7025 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
58279503 7026 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
4ef0d4d0
KS
7027 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7028};
7029
a9e7a9d5 7030#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 7031static bool init_gif_functions (void);
bb4d86b4
CY
7032#else
7033#define init_gif_functions NULL
7034#endif
7035
4ef0d4d0
KS
7036/* Structure describing the image type `gif'. */
7037
7038static struct image_type gif_type =
7039{
7040 &Qgif,
7041 gif_image_p,
7042 gif_load,
6ac3c7bb 7043 gif_clear_image,
bb4d86b4 7044 init_gif_functions,
4ef0d4d0
KS
7045 NULL
7046};
7047
6ac3c7bb
KS
7048/* Free X resources of GIF image IMG which is used on frame F. */
7049
7050static void
d3da34e0 7051gif_clear_image (struct frame *f, struct image *img)
6ac3c7bb 7052{
b50691aa 7053 img->lisp_data = Qnil;
6ac3c7bb
KS
7054 x_clear_image (f, img);
7055}
7056
578098f3 7057/* Return true if OBJECT is a valid GIF image specification. */
4ef0d4d0 7058
578098f3 7059static bool
d3da34e0 7060gif_image_p (Lisp_Object object)
4ef0d4d0
KS
7061{
7062 struct image_keyword fmt[GIF_LAST];
72af86bd 7063 memcpy (fmt, gif_format, sizeof fmt);
4ef0d4d0
KS
7064
7065 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7066 return 0;
7067
7068 /* Must specify either the :data or :file keyword. */
7069 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7070}
7071
9e2a2647 7072#endif /* HAVE_GIF */
4ef0d4d0
KS
7073
7074#ifdef HAVE_GIF
7075
9e2a2647 7076#if defined (HAVE_NTGUI)
2e09fef1
EZ
7077/* winuser.h might define DrawText to DrawTextA or DrawTextW.
7078 Undefine before redefining to avoid a preprocessor warning. */
7079#ifdef DrawText
7080#undef DrawText
7081#endif
4ef0d4d0
KS
7082/* avoid conflict with QuickdrawText.h */
7083#define DrawText gif_DrawText
7084#include <gif_lib.h>
7085#undef DrawText
7086
9e2a2647 7087#else /* HAVE_NTGUI */
4ef0d4d0
KS
7088
7089#include <gif_lib.h>
7090
9e2a2647 7091#endif /* HAVE_NTGUI */
4ef0d4d0
KS
7092
7093
0fda9b75 7094#ifdef WINDOWSNT
4ef0d4d0
KS
7095
7096/* GIF library details. */
14beddf4
CY
7097DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7098DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7099DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7100DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
4ef0d4d0 7101
578098f3 7102static bool
d07ff9db 7103init_gif_functions (void)
4ef0d4d0
KS
7104{
7105 HMODULE library;
7106
d07ff9db 7107 if (!(library = w32_delayed_load (Qgif)))
4ef0d4d0
KS
7108 return 0;
7109
7110 LOAD_IMGLIB_FN (library, DGifCloseFile);
7111 LOAD_IMGLIB_FN (library, DGifSlurp);
7112 LOAD_IMGLIB_FN (library, DGifOpen);
7113 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7114 return 1;
7115}
7116
7117#else
7118
7119#define fn_DGifCloseFile DGifCloseFile
7120#define fn_DGifSlurp DGifSlurp
7121#define fn_DGifOpen DGifOpen
7122#define fn_DGifOpenFileName DGifOpenFileName
7123
0fda9b75 7124#endif /* WINDOWSNT */
4ef0d4d0
KS
7125
7126/* Reading a GIF image from memory
7127 Based on the PNG memory stuff to a certain extent. */
7128
7129typedef struct
7130{
7131 unsigned char *bytes;
3f791afe
PE
7132 ptrdiff_t len;
7133 ptrdiff_t index;
4ef0d4d0
KS
7134}
7135gif_memory_source;
7136
7137/* Make the current memory source available to gif_read_from_memory.
7138 It's done this way because not all versions of libungif support
7139 a UserData field in the GifFileType structure. */
7140static gif_memory_source *current_gif_memory_src;
7141
7142static int
d3da34e0 7143gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
4ef0d4d0
KS
7144{
7145 gif_memory_source *src = current_gif_memory_src;
7146
7147 if (len > src->len - src->index)
7148 return -1;
7149
72af86bd 7150 memcpy (buf, src->bytes + src->index, len);
4ef0d4d0
KS
7151 src->index += len;
7152 return len;
7153}
7154
7155
578098f3 7156/* Load GIF image IMG for use on frame F. Value is true if
4ef0d4d0
KS
7157 successful. */
7158
91433552
DN
7159static const int interlace_start[] = {0, 4, 2, 1};
7160static const int interlace_increment[] = {8, 8, 4, 2};
aca946f3 7161
17c0c952
JD
7162#define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7163
578098f3 7164static bool
d3da34e0 7165gif_load (struct frame *f, struct image *img)
4ef0d4d0 7166{
60002bf5
CY
7167 Lisp_Object file;
7168 int rc, width, height, x, y, i, j;
4ef0d4d0
KS
7169 XImagePtr ximg;
7170 ColorMapObject *gif_color_map;
7171 unsigned long pixel_colors[256];
7172 GifFileType *gif;
4ef0d4d0 7173 gif_memory_source memsrc;
60002bf5
CY
7174 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7175 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7176 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7177 unsigned long bgcolor = 0;
13464394 7178 EMACS_INT idx;
4ef0d4d0
KS
7179
7180 if (NILP (specified_data))
7181 {
7182 file = x_find_image_file (specified_file);
7183 if (!STRINGP (file))
7184 {
7185 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4ef0d4d0
KS
7186 return 0;
7187 }
7188
df61c790 7189 /* Open the GIF file. */
2037898d 7190 gif = fn_DGifOpenFileName (SSDATA (file));
4ef0d4d0
KS
7191 if (gif == NULL)
7192 {
7193 image_error ("Cannot open `%s'", file, Qnil);
4ef0d4d0
KS
7194 return 0;
7195 }
7196 }
7197 else
7198 {
7574650a
AS
7199 if (!STRINGP (specified_data))
7200 {
7201 image_error ("Invalid image data `%s'", specified_data, Qnil);
7202 return 0;
7203 }
7204
4ef0d4d0
KS
7205 /* Read from memory! */
7206 current_gif_memory_src = &memsrc;
7207 memsrc.bytes = SDATA (specified_data);
7208 memsrc.len = SBYTES (specified_data);
7209 memsrc.index = 0;
7210
df61c790 7211 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
4ef0d4d0
KS
7212 if (!gif)
7213 {
7214 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
4ef0d4d0
KS
7215 return 0;
7216 }
7217 }
7218
f1f25b99
CY
7219 /* Before reading entire contents, check the declared image size. */
7220 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7221 {
10ea2b82 7222 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
f1f25b99 7223 fn_DGifCloseFile (gif);
f1f25b99
CY
7224 return 0;
7225 }
7226
4ef0d4d0
KS
7227 /* Read entire contents. */
7228 rc = fn_DGifSlurp (gif);
60002bf5 7229 if (rc == GIF_ERROR || gif->ImageCount <= 0)
4ef0d4d0
KS
7230 {
7231 image_error ("Error reading `%s'", img->spec, Qnil);
7232 fn_DGifCloseFile (gif);
4ef0d4d0
KS
7233 return 0;
7234 }
7235
60002bf5
CY
7236 /* Which sub-image are we to display? */
7237 {
33290528
PE
7238 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7239 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
60002bf5 7240 if (idx < 0 || idx >= gif->ImageCount)
17c0c952 7241 {
60002bf5 7242 image_error ("Invalid image number `%s' in image `%s'",
33290528 7243 image_number, img->spec);
60002bf5
CY
7244 fn_DGifCloseFile (gif);
7245 return 0;
17c0c952 7246 }
60002bf5 7247 }
17c0c952 7248
e013fb34
CY
7249 width = img->width = gif->SWidth;
7250 height = img->height = gif->SHeight;
0f4aca46 7251
e013fb34
CY
7252 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7253 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
8d903f4e
AS
7254 img->corners[BOT_CORNER]
7255 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7256 img->corners[RIGHT_CORNER]
7257 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
4ef0d4d0 7258
f1f25b99
CY
7259 if (!check_image_size (f, width, height))
7260 {
10ea2b82 7261 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
f1f25b99 7262 fn_DGifCloseFile (gif);
f1f25b99
CY
7263 return 0;
7264 }
7265
44aa9ee6
PE
7266 /* Check that the selected subimages fit. It's not clear whether
7267 the GIF spec requires this, but Emacs can crash if they don't fit. */
7268 for (j = 0; j <= idx; ++j)
7269 {
7270 struct SavedImage *subimage = gif->SavedImages + j;
7271 int subimg_width = subimage->ImageDesc.Width;
7272 int subimg_height = subimage->ImageDesc.Height;
7273 int subimg_top = subimage->ImageDesc.Top;
7274 int subimg_left = subimage->ImageDesc.Left;
7275 if (! (0 <= subimg_width && 0 <= subimg_height
7276 && 0 <= subimg_top && subimg_top <= height - subimg_height
7277 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7278 {
7279 image_error ("Subimage does not fit in image", Qnil, Qnil);
7280 fn_DGifCloseFile (gif);
7281 return 0;
7282 }
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 {
a9ebfa0b 7395 while (subimg_height <= row)
60002bf5 7396 {
a9ebfa0b 7397 lint_assume (pass < 3);
60002bf5 7398 row = interlace_start[++pass];
60002bf5
CY
7399 }
7400
e013fb34 7401 for (x = 0; x < subimg_width; x++)
60002bf5 7402 {
e013fb34 7403 int c = raster[y * subimg_width + x];
60002bf5 7404 if (transparency_color_index != c || disposal != 1)
e013fb34
CY
7405 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7406 pixel_colors[c]);
60002bf5
CY
7407 }
7408 }
7409 }
7410 else
7411 {
e013fb34
CY
7412 for (y = 0; y < subimg_height; ++y)
7413 for (x = 0; x < subimg_width; ++x)
60002bf5 7414 {
e013fb34 7415 int c = raster[y * subimg_width + x];
60002bf5 7416 if (transparency_color_index != c || disposal != 1)
e013fb34
CY
7417 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7418 pixel_colors[c]);
60002bf5
CY
7419 }
7420 }
4ef0d4d0
KS
7421 }
7422
60002bf5
CY
7423#ifdef COLOR_TABLE_SUPPORT
7424 img->colors = colors_in_color_table (&img->ncolors);
7425 free_color_table ();
7426#endif /* COLOR_TABLE_SUPPORT */
7427
1546c559
JL
7428 /* Save GIF image extension data for `image-metadata'.
7429 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
b50691aa 7430 img->lisp_data = Qnil;
60002bf5 7431 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
6ac3c7bb 7432 {
13464394 7433 int delay = 0;
60002bf5
CY
7434 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7435 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
6ac3c7bb 7436 /* Append (... FUNCTION "BYTES") */
1100a63c
CY
7437 {
7438 img->lisp_data
7439 = Fcons (make_number (ext->Function),
7440 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7441 img->lisp_data));
7442 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7443 && ext->ByteCount == 4)
7444 {
7445 delay = ext->Bytes[2] << CHAR_BIT;
7446 delay |= ext->Bytes[1];
7447 }
7448 }
b50691aa 7449 img->lisp_data = Fcons (Qextension_data,
1100a63c
CY
7450 Fcons (img->lisp_data, Qnil));
7451 if (delay)
7452 img->lisp_data
7453 = Fcons (Qdelay,
13464394 7454 Fcons (make_float (delay / 100.0),
1100a63c 7455 img->lisp_data));
6ac3c7bb 7456 }
1100a63c 7457
6ac3c7bb 7458 if (gif->ImageCount > 1)
b50691aa
CY
7459 img->lisp_data = Fcons (Qcount,
7460 Fcons (make_number (gif->ImageCount),
7461 img->lisp_data));
6ac3c7bb 7462
4ef0d4d0
KS
7463 fn_DGifCloseFile (gif);
7464
7465 /* Maybe fill in the background field while we have ximg handy. */
7466 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
7467 /* Casting avoids a GCC warning. */
7468 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
7469
7470 /* Put the image into the pixmap, then free the X image and its buffer. */
7471 x_put_x_image (f, ximg, img->pixmap, width, height);
7472 x_destroy_x_image (ximg);
7473
4ef0d4d0
KS
7474 return 1;
7475}
7476
2e09fef1 7477#else /* !HAVE_GIF */
4ef0d4d0 7478
edfda783 7479#ifdef HAVE_NS
578098f3 7480static bool
edfda783
AR
7481gif_load (struct frame *f, struct image *img)
7482{
ed3751c8
JB
7483 return ns_load_image (f, img,
7484 image_spec_value (img->spec, QCfile, NULL),
7485 image_spec_value (img->spec, QCdata, NULL));
edfda783
AR
7486}
7487#endif /* HAVE_NS */
7488
4ef0d4d0
KS
7489#endif /* HAVE_GIF */
7490
7491
3de25479 7492/***********************************************************************
a32d4040 7493 ImageMagick
4917006b 7494***********************************************************************/
3de25479 7495#if defined (HAVE_IMAGEMAGICK)
3de25479 7496
4b66faf3 7497static Lisp_Object Qimagemagick;
a32d4040 7498
578098f3
PE
7499static bool imagemagick_image_p (Lisp_Object);
7500static bool imagemagick_load (struct frame *, struct image *);
d66c4c7c
CY
7501static void imagemagick_clear_image (struct frame *, struct image *);
7502
a32d4040 7503/* Indices of image specification fields in imagemagick_format. */
3de25479
JV
7504
7505enum imagemagick_keyword_index
4917006b
JV
7506 {
7507 IMAGEMAGICK_TYPE,
7508 IMAGEMAGICK_DATA,
7509 IMAGEMAGICK_FILE,
7510 IMAGEMAGICK_ASCENT,
7511 IMAGEMAGICK_MARGIN,
7512 IMAGEMAGICK_RELIEF,
7513 IMAGEMAGICK_ALGORITHM,
7514 IMAGEMAGICK_HEURISTIC_MASK,
7515 IMAGEMAGICK_MASK,
7516 IMAGEMAGICK_BACKGROUND,
c7f514b5
JV
7517 IMAGEMAGICK_HEIGHT,
7518 IMAGEMAGICK_WIDTH,
7519 IMAGEMAGICK_ROTATION,
7520 IMAGEMAGICK_CROP,
4917006b
JV
7521 IMAGEMAGICK_LAST
7522 };
3de25479
JV
7523
7524/* Vector of image_keyword structures describing the format
7525 of valid user-defined image specifications. */
7526
7527static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
4917006b
JV
7528 {
7529 {":type", IMAGE_SYMBOL_VALUE, 1},
7530 {":data", IMAGE_STRING_VALUE, 0},
7531 {":file", IMAGE_STRING_VALUE, 0},
7532 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 7533 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4917006b
JV
7534 {":relief", IMAGE_INTEGER_VALUE, 0},
7535 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7536 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7537 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
c7f514b5 7538 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7574650a
AS
7539 {":height", IMAGE_INTEGER_VALUE, 0},
7540 {":width", IMAGE_INTEGER_VALUE, 0},
7541 {":rotation", IMAGE_NUMBER_VALUE, 0},
c7f514b5 7542 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
4917006b 7543 };
a32d4040 7544
33d4113c 7545#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 7546static bool init_imagemagick_functions (void);
bb4d86b4
CY
7547#else
7548#define init_imagemagick_functions NULL
7549#endif
7550
d66c4c7c
CY
7551/* Structure describing the image type for any image handled via
7552 ImageMagick. */
7553
7554static struct image_type imagemagick_type =
7555 {
7556 &Qimagemagick,
7557 imagemagick_image_p,
7558 imagemagick_load,
7559 imagemagick_clear_image,
bb4d86b4 7560 init_imagemagick_functions,
d66c4c7c
CY
7561 NULL
7562 };
7563
3de25479
JV
7564/* Free X resources of imagemagick image IMG which is used on frame F. */
7565
7566static void
4917006b
JV
7567imagemagick_clear_image (struct frame *f,
7568 struct image *img)
3de25479 7569{
3de25479
JV
7570 x_clear_image (f, img);
7571}
7572
578098f3 7573/* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
3de25479
JV
7574 this by calling parse_image_spec and supplying the keywords that
7575 identify the IMAGEMAGICK format. */
7576
578098f3 7577static bool
4917006b 7578imagemagick_image_p (Lisp_Object object)
3de25479
JV
7579{
7580 struct image_keyword fmt[IMAGEMAGICK_LAST];
dbfe4532 7581 memcpy (fmt, imagemagick_format, sizeof fmt);
3de25479
JV
7582
7583 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7584 return 0;
7585
7586 /* Must specify either the :data or :file keyword. */
7587 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7588}
7589
7590/* The GIF library also defines DrawRectangle, but its never used in Emacs.
c7015153 7591 Therefore rename the function so it doesn't collide with ImageMagick. */
3de25479
JV
7592#define DrawRectangle DrawRectangleGif
7593#include <wand/MagickWand.h>
7594
60737f02
PE
7595/* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7596 Emacs seems to work fine with the hidden version, so unhide it. */
7597#include <magick/version.h>
7598#if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7599extern WandExport void PixelGetMagickColor (const PixelWand *,
7600 MagickPixelPacket *);
7601#endif
7602
d1d7b339
JL
7603/* Log ImageMagick error message.
7604 Useful when a ImageMagick function returns the status `MagickFalse'. */
7605
7606static void
7607imagemagick_error (MagickWand *wand)
7608{
7609 char *description;
7610 ExceptionType severity;
7611
7612 description = MagickGetException (wand, &severity);
7613 image_error ("ImageMagick error: %s",
1130ecfc 7614 build_string (description),
d1d7b339
JL
7615 Qnil);
7616 description = (char *) MagickRelinquishMemory (description);
7617}
7618
d66c4c7c
CY
7619/* Helper function for imagemagick_load, which does the actual loading
7620 given contents and size, apart from frame and image structures,
7621 passed from imagemagick_load. Uses librimagemagick to do most of
7622 the image processing.
3de25479 7623
d66c4c7c
CY
7624 F is a pointer to the Emacs frame; IMG to the image structure to
7625 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
7626 be parsed; SIZE is the number of bytes of data; and FILENAME is
7627 either the file name or the image data.
3de25479 7628
578098f3 7629 Return true if successful. */
3de25479 7630
578098f3 7631static bool
d66c4c7c
CY
7632imagemagick_load_image (struct frame *f, struct image *img,
7633 unsigned char *contents, unsigned int size,
33290528 7634 char *filename)
3de25479 7635{
1b9b4cf4 7636 size_t width, height;
d66c4c7c 7637 MagickBooleanType status;
3de25479 7638 XImagePtr ximg;
1b9b4cf4
CY
7639 int x, y;
7640 MagickWand *image_wand;
7641 MagickWand *ping_wand;
3de25479 7642 PixelIterator *iterator;
1b9b4cf4 7643 PixelWand **pixels, *bg_wand = NULL;
3de25479 7644 MagickPixelPacket pixel;
4917006b 7645 Lisp_Object image;
7574650a 7646 Lisp_Object value;
33290528 7647 Lisp_Object crop;
13464394 7648 EMACS_INT ino;
4917006b
JV
7649 int desired_width, desired_height;
7650 double rotation;
7574650a 7651 int pixelwidth;
7574650a 7652
a32d4040
CY
7653 /* Handle image index for image types who can contain more than one image.
7654 Interface :index is same as for GIF. First we "ping" the image to see how
7655 many sub-images it contains. Pinging is faster than loading the image to
7656 find out things about it. */
f853f599 7657
a32d4040 7658 /* Initialize the imagemagick environment. */
f853f599 7659 MagickWandGenesis ();
3de25479
JV
7660 image = image_spec_value (img->spec, QCindex, NULL);
7661 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7574650a 7662 ping_wand = NewMagickWand ();
d1d7b339 7663 /* MagickSetResolution (ping_wand, 2, 2); (Bug#10112) */
fa4fdb5c 7664
1b9b4cf4
CY
7665 status = filename
7666 ? MagickPingImage (ping_wand, filename)
7667 : MagickPingImageBlob (ping_wand, contents, size);
7574650a 7668
d1d7b339
JL
7669 if (status == MagickFalse)
7670 {
7671 imagemagick_error (ping_wand);
7672 DestroyMagickWand (ping_wand);
7673 return 0;
7674 }
fa4fdb5c 7675
1b9b4cf4 7676 if (ino < 0 || ino >= MagickGetNumberImages (ping_wand))
7574650a
AS
7677 {
7678 image_error ("Invalid image number `%s' in image `%s'",
7679 image, img->spec);
7680 DestroyMagickWand (ping_wand);
7681 return 0;
f3700365 7682 }
431dab04 7683
5e617bc2 7684 if (MagickGetNumberImages (ping_wand) > 1)
b50691aa 7685 img->lisp_data =
d2a2d277 7686 Fcons (Qcount,
7574650a 7687 Fcons (make_number (MagickGetNumberImages (ping_wand)),
b50691aa 7688 img->lisp_data));
f3700365
JV
7689
7690 DestroyMagickWand (ping_wand);
f853f599 7691
d66c4c7c 7692 /* Now we know how many images are inside the file. If it's not a
1b9b4cf4 7693 bundle, the number is one. Load the image data. */
f3700365 7694
1b9b4cf4 7695 image_wand = NewMagickWand ();
f3700365 7696
1b9b4cf4
CY
7697 if ((filename
7698 ? MagickReadImage (image_wand, filename)
7699 : MagickReadImageBlob (image_wand, contents, size))
7700 == MagickFalse)
f3700365 7701 {
1b9b4cf4
CY
7702 imagemagick_error (image_wand);
7703 goto imagemagick_error;
f3700365 7704 }
f853f599 7705
1b9b4cf4
CY
7706 /* Retrieve the frame's background color, for use later. */
7707 {
7708 XColor bgcolor;
7709 Lisp_Object specified_bg;
7710
7711 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7712 if (!STRINGP (specified_bg)
7713 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
7714 {
7715#ifndef HAVE_NS
7716 bgcolor.pixel = FRAME_BACKGROUND_PIXEL (f);
7717 x_query_color (f, &bgcolor);
7718#else
7719 ns_query_color (FRAME_BACKGROUND_COLOR (f), &bgcolor, 1);
7720#endif
7721 }
7722
7723 bg_wand = NewPixelWand ();
7724 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
7725 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
7726 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
7727 }
7728
d2a2d277 7729 /* If width and/or height is set in the display spec assume we want
a32d4040 7730 to scale to those values. If either h or w is unspecified, the
f3700365 7731 unspecified should be calculated from the specified to preserve
549a73b9 7732 aspect ratio. */
3de25479
JV
7733 value = image_spec_value (img->spec, QCwidth, NULL);
7734 desired_width = (INTEGERP (value) ? XFASTINT (value) : -1);
7735 value = image_spec_value (img->spec, QCheight, NULL);
7736 desired_height = (INTEGERP (value) ? XFASTINT (value) : -1);
c7f514b5 7737
bdf6a35d
JV
7738 height = MagickGetImageHeight (image_wand);
7739 width = MagickGetImageWidth (image_wand);
7740
a32d4040
CY
7741 if (desired_width != -1 && desired_height == -1)
7742 /* w known, calculate h. */
7743 desired_height = (double) desired_width / width * height;
7744 if (desired_width == -1 && desired_height != -1)
7745 /* h known, calculate w. */
7746 desired_width = (double) desired_height / height * width;
7747 if (desired_width != -1 && desired_height != -1)
4917006b 7748 {
7574650a
AS
7749 status = MagickScaleImage (image_wand, desired_width, desired_height);
7750 if (status == MagickFalse)
7751 {
7752 image_error ("Imagemagick scale failed", Qnil, Qnil);
d1d7b339 7753 imagemagick_error (image_wand);
7574650a
AS
7754 goto imagemagick_error;
7755 }
3de25479 7756 }
3de25479 7757
f3700365 7758 /* crop behaves similar to image slicing in Emacs but is more memory
7574650a
AS
7759 efficient. */
7760 crop = image_spec_value (img->spec, QCcrop, NULL);
7761
13464394 7762 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7574650a 7763 {
a32d4040
CY
7764 /* After some testing, it seems MagickCropImage is the fastest crop
7765 function in ImageMagick. This crop function seems to do less copying
7766 than the alternatives, but it still reads the entire image into memory
13464394 7767 before cropping, which is apparently difficult to avoid when using
a32d4040 7768 imagemagick. */
13464394 7769 size_t crop_width = XINT (XCAR (crop));
7574650a 7770 crop = XCDR (crop);
13464394 7771 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7574650a 7772 {
13464394 7773 size_t crop_height = XINT (XCAR (crop));
7574650a 7774 crop = XCDR (crop);
13464394 7775 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7574650a 7776 {
13464394 7777 ssize_t crop_x = XINT (XCAR (crop));
7574650a 7778 crop = XCDR (crop);
13464394 7779 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7574650a 7780 {
13464394
PE
7781 ssize_t crop_y = XINT (XCAR (crop));
7782 MagickCropImage (image_wand, crop_width, crop_height,
7783 crop_x, crop_y);
7574650a
AS
7784 }
7785 }
7786 }
7787 }
7788
d2a2d277
JV
7789 /* Furthermore :rotation. we need background color and angle for
7790 rotation. */
3de25479 7791 /*
d2a2d277
JV
7792 TODO background handling for rotation specified_bg =
7793 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
549a73b9 7794 (specified_bg). */
4917006b
JV
7795 value = image_spec_value (img->spec, QCrotation, NULL);
7796 if (FLOATP (value))
7797 {
3de25479 7798 rotation = extract_float (value);
1b9b4cf4 7799 status = MagickRotateImage (image_wand, bg_wand, rotation);
4917006b
JV
7800 if (status == MagickFalse)
7801 {
7802 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
d1d7b339 7803 imagemagick_error (image_wand);
4917006b
JV
7804 goto imagemagick_error;
7805 }
3de25479 7806 }
7574650a 7807
1b9b4cf4
CY
7808 /* Set the canvas background color to the frame or specified
7809 background, and flatten the image. Note: as of ImageMagick
7810 6.6.0, SVG image transparency is not handled properly
7811 (e.g. etc/images/splash.svg shows a white background always). */
7812 {
7813 MagickWand *new_wand;
7814 MagickSetImageBackgroundColor (image_wand, bg_wand);
0e25d334 7815#ifdef HAVE_MAGICKMERGEIMAGELAYERS
1b9b4cf4 7816 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
0e25d334
CY
7817#else
7818 new_wand = MagickFlattenImages (image_wand);
7819#endif
1b9b4cf4
CY
7820 DestroyMagickWand (image_wand);
7821 image_wand = new_wand;
7822 }
7823
84ac6f9d
PE
7824 /* Finally we are done manipulating the image. Figure out the
7825 resulting width/height and transfer ownership to Emacs. */
7826 height = MagickGetImageHeight (image_wand);
7827 width = MagickGetImageWidth (image_wand);
7828
3f791afe
PE
7829 if (! (width <= INT_MAX && height <= INT_MAX
7830 && check_image_size (f, width, height)))
3de25479
JV
7831 {
7832 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7833 goto imagemagick_error;
7834 }
7574650a 7835
3de25479
JV
7836 /* We can now get a valid pixel buffer from the imagemagick file, if all
7837 went ok. */
3de25479
JV
7838
7839 init_color_table ();
af008560 7840
0e25d334
CY
7841#ifdef HAVE_MAGICKEXPORTIMAGEPIXELS
7842 if (imagemagick_render_type != 0)
7843 {
7844 /* Magicexportimage is normally faster than pixelpushing. This
7845 method is also well tested. Some aspects of this method are
7846 ad-hoc and needs to be more researched. */
7847 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
7848 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
7849 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7850 if (!x_create_x_image_and_pixmap (f, width, height, imagedepth,
7851 &ximg, &img->pixmap))
7852 {
7853#ifdef COLOR_TABLE_SUPPORT
7854 free_color_table ();
7855#endif
7856 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7857 goto imagemagick_error;
7858 }
7859
7860 /* Oddly, the below code doesn't seem to work:*/
7861 /* switch(ximg->bitmap_unit){ */
7862 /* case 8: */
7863 /* pixelwidth=CharPixel; */
7864 /* break; */
7865 /* case 16: */
7866 /* pixelwidth=ShortPixel; */
7867 /* break; */
7868 /* case 32: */
7869 /* pixelwidth=LongPixel; */
7870 /* break; */
7871 /* } */
7872 /*
7873 Here im just guessing the format of the bitmap.
7874 happens to work fine for:
7875 - bw djvu images
7876 on rgb display.
7877 seems about 3 times as fast as pixel pushing(not carefully measured)
7878 */
7879 pixelwidth = CharPixel; /*??? TODO figure out*/
7880 MagickExportImagePixels (image_wand, 0, 0, width, height,
7881 exportdepth, pixelwidth, ximg->data);
7882 }
7883 else
7884#endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
4917006b 7885 {
13464394
PE
7886 size_t image_height;
7887
4917006b 7888 /* Try to create a x pixmap to hold the imagemagick pixmap. */
d2a2d277
JV
7889 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7890 &ximg, &img->pixmap))
4917006b 7891 {
466cbae9
AS
7892#ifdef COLOR_TABLE_SUPPORT
7893 free_color_table ();
7894#endif
5e617bc2 7895 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
4917006b
JV
7896 goto imagemagick_error;
7897 }
7574650a 7898
53964682 7899 /* Copy imagemagick image to x with primitive yet robust pixel
4917006b 7900 pusher loop. This has been tested a lot with many different
549a73b9 7901 images. */
7574650a 7902
4917006b
JV
7903 /* Copy pixels from the imagemagick image structure to the x image map. */
7904 iterator = NewPixelIterator (image_wand);
7574650a 7905 if (iterator == (PixelIterator *) NULL)
4917006b 7906 {
466cbae9
AS
7907#ifdef COLOR_TABLE_SUPPORT
7908 free_color_table ();
7909#endif
7910 x_destroy_x_image (ximg);
d2a2d277
JV
7911 image_error ("Imagemagick pixel iterator creation failed",
7912 Qnil, Qnil);
3de25479 7913 goto imagemagick_error;
4917006b
JV
7914 }
7915
13464394
PE
7916 image_height = MagickGetImageHeight (image_wand);
7917 for (y = 0; y < image_height; y++)
4917006b
JV
7918 {
7919 pixels = PixelGetNextIteratorRow (iterator, &width);
7574650a 7920 if (pixels == (PixelWand **) NULL)
4917006b
JV
7921 break;
7922 for (x = 0; x < (long) width; x++)
7923 {
7924 PixelGetMagickColor (pixels[x], &pixel);
d2a2d277
JV
7925 XPutPixel (ximg, x, y,
7926 lookup_rgb_color (f,
7927 pixel.red,
7928 pixel.green,
7929 pixel.blue));
4917006b
JV
7930 }
7931 }
7932 DestroyPixelIterator (iterator);
3de25479 7933 }
3ed42149 7934
3de25479
JV
7935#ifdef COLOR_TABLE_SUPPORT
7936 /* Remember colors allocated for this image. */
7937 img->colors = colors_in_color_table (&img->ncolors);
7938 free_color_table ();
7939#endif /* COLOR_TABLE_SUPPORT */
7940
3de25479
JV
7941 img->width = width;
7942 img->height = height;
7943
3de25479
JV
7944 /* Put the image into the pixmap, then free the X image and its
7945 buffer. */
7946 x_put_x_image (f, ximg, img->pixmap, width, height);
3de25479
JV
7947 x_destroy_x_image (ximg);
7948
f3700365 7949 /* Final cleanup. image_wand should be the only resource left. */
3de25479 7950 DestroyMagickWand (image_wand);
1b9b4cf4
CY
7951 if (bg_wand) DestroyPixelWand (bg_wand);
7952
03d32f1b 7953 /* `MagickWandTerminus' terminates the imagemagick environment. */
f853f599 7954 MagickWandTerminus ();
3de25479
JV
7955
7956 return 1;
7957
7958 imagemagick_error:
466cbae9 7959 DestroyMagickWand (image_wand);
1b9b4cf4
CY
7960 if (bg_wand) DestroyPixelWand (bg_wand);
7961
f853f599 7962 MagickWandTerminus ();
3de25479
JV
7963 /* TODO more cleanup. */
7964 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
3de25479
JV
7965 return 0;
7966}
7967
4917006b 7968
578098f3 7969/* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
4917006b
JV
7970 successful. this function will go into the imagemagick_type structure, and
7971 the prototype thus needs to be compatible with that structure. */
7972
578098f3 7973static bool
d66c4c7c 7974imagemagick_load (struct frame *f, struct image *img)
4917006b 7975{
578098f3 7976 bool success_p = 0;
4917006b
JV
7977 Lisp_Object file_name;
7978
7979 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7980 file_name = image_spec_value (img->spec, QCfile, NULL);
7981 if (STRINGP (file_name))
7982 {
7983 Lisp_Object file;
4917006b
JV
7984
7985 file = x_find_image_file (file_name);
4917006b
JV
7986 if (!STRINGP (file))
7987 {
7988 image_error ("Cannot find image file `%s'", file_name, Qnil);
4917006b
JV
7989 return 0;
7990 }
33290528 7991 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
4917006b
JV
7992 }
7993 /* Else its not a file, its a lisp object. Load the image from a
7994 lisp object rather than a file. */
7995 else
7996 {
7997 Lisp_Object data;
7998
7999 data = image_spec_value (img->spec, QCdata, NULL);
7574650a
AS
8000 if (!STRINGP (data))
8001 {
8002 image_error ("Invalid image data `%s'", data, Qnil);
8003 return 0;
8004 }
d2a2d277
JV
8005 success_p = imagemagick_load_image (f, img, SDATA (data),
8006 SBYTES (data), NULL);
4917006b
JV
8007 }
8008
8009 return success_p;
8010}
8011
a7ca3326 8012DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
d66c4c7c
CY
8013 doc: /* Return a list of image types supported by ImageMagick.
8014Each entry in this list is a symbol named after an ImageMagick format
8015tag. See the ImageMagick manual for a list of ImageMagick formats and
8016their descriptions (http://www.imagemagick.org/script/formats.php).
dd605cc4 8017You can also try the shell command: `identify -list format'.
d66c4c7c
CY
8018
8019Note that ImageMagick recognizes many file-types that Emacs does not
32d72c2f
GM
8020recognize as images, such as C. See `imagemagick-types-enable'
8021and `imagemagick-types-inhibit'. */)
a8101f66 8022 (void)
3de25479
JV
8023{
8024 Lisp_Object typelist = Qnil;
1ab0dee5 8025 size_t numf = 0;
3de25479 8026 ExceptionInfo ex;
2277de02 8027 char **imtypes;
3f791afe 8028 size_t i;
3de25479 8029 Lisp_Object Qimagemagicktype;
2277de02
JD
8030
8031 GetExceptionInfo(&ex);
8032 imtypes = GetMagickList ("*", &numf, &ex);
8033 DestroyExceptionInfo(&ex);
8034
4917006b
JV
8035 for (i = 0; i < numf; i++)
8036 {
8037 Qimagemagicktype = intern (imtypes[i]);
f3700365
JV
8038 typelist = Fcons (Qimagemagicktype, typelist);
8039 }
d1d7b339 8040 return Fnreverse (typelist);
3de25479 8041}
7574650a 8042
3de25479
JV
8043#endif /* defined (HAVE_IMAGEMAGICK) */
8044
8045
4ef0d4d0 8046\f
4ab27a43
GM
8047/***********************************************************************
8048 SVG
8049 ***********************************************************************/
8050
8051#if defined (HAVE_RSVG)
8052
8053/* Function prototypes. */
8054
578098f3
PE
8055static bool svg_image_p (Lisp_Object object);
8056static bool svg_load (struct frame *f, struct image *img);
4ab27a43 8057
578098f3
PE
8058static bool svg_load_image (struct frame *, struct image *,
8059 unsigned char *, ptrdiff_t);
4ab27a43
GM
8060
8061/* The symbol `svg' identifying images of this type. */
8062
4b66faf3 8063static Lisp_Object Qsvg;
4ab27a43
GM
8064
8065/* Indices of image specification fields in svg_format, below. */
8066
8067enum svg_keyword_index
8068{
8069 SVG_TYPE,
8070 SVG_DATA,
8071 SVG_FILE,
8072 SVG_ASCENT,
8073 SVG_MARGIN,
8074 SVG_RELIEF,
8075 SVG_ALGORITHM,
8076 SVG_HEURISTIC_MASK,
8077 SVG_MASK,
8078 SVG_BACKGROUND,
8079 SVG_LAST
8080};
8081
8082/* Vector of image_keyword structures describing the format
8083 of valid user-defined image specifications. */
8084
91433552 8085static const struct image_keyword svg_format[SVG_LAST] =
4ab27a43
GM
8086{
8087 {":type", IMAGE_SYMBOL_VALUE, 1},
8088 {":data", IMAGE_STRING_VALUE, 0},
8089 {":file", IMAGE_STRING_VALUE, 0},
8090 {":ascent", IMAGE_ASCENT_VALUE, 0},
c4a07a4c 8091 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4ab27a43
GM
8092 {":relief", IMAGE_INTEGER_VALUE, 0},
8093 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8094 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8095 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8096 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8097};
8098
33d4113c 8099#if defined HAVE_NTGUI && defined WINDOWSNT
578098f3 8100static bool init_svg_functions (void);
bb4d86b4
CY
8101#else
8102#define init_svg_functions NULL
8103#endif
8104
4ab27a43
GM
8105/* Structure describing the image type `svg'. Its the same type of
8106 structure defined for all image formats, handled by emacs image
8107 functions. See struct image_type in dispextern.h. */
8108
8109static struct image_type svg_type =
8110{
4ab27a43 8111 &Qsvg,
4ab27a43 8112 svg_image_p,
4ab27a43 8113 svg_load,
4ab27a43 8114 x_clear_image,
bb4d86b4 8115 init_svg_functions,
c21e6151 8116 NULL
4ab27a43
GM
8117};
8118
8119
578098f3 8120/* Return true if OBJECT is a valid SVG image specification. Do
4ab27a43
GM
8121 this by calling parse_image_spec and supplying the keywords that
8122 identify the SVG format. */
8123
578098f3 8124static bool
d3da34e0 8125svg_image_p (Lisp_Object object)
4ab27a43
GM
8126{
8127 struct image_keyword fmt[SVG_LAST];
72af86bd 8128 memcpy (fmt, svg_format, sizeof fmt);
4ab27a43
GM
8129
8130 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8131 return 0;
8132
8133 /* Must specify either the :data or :file keyword. */
8134 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8135}
8136
8137#include <librsvg/rsvg.h>
8138
0fda9b75 8139#ifdef WINDOWSNT
5fc9fdeb
JR
8140
8141/* SVG library functions. */
40693bba 8142DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new, (void));
8143DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions, (RsvgHandle *, RsvgDimensionData *));
8144DEF_IMGLIB_FN (gboolean, rsvg_handle_write, (RsvgHandle *, const guchar *, gsize, GError **));
8145DEF_IMGLIB_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8146DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8147DEF_IMGLIB_FN (void *, rsvg_handle_set_size_callback, (RsvgHandle *, RsvgSizeFunc, gpointer, GDestroyNotify));
8148
8149DEF_IMGLIB_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8150DEF_IMGLIB_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8151DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8152DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8153DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8154DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8155DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8156DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8157
8158DEF_IMGLIB_FN (void, g_type_init, (void));
8159DEF_IMGLIB_FN (void, g_object_unref, (gpointer));
121ab1cd 8160DEF_IMGLIB_FN (void, g_error_free, (GError *));
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
0fda9b75 8218#endif /* !WINDOWSNT */
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;
42143acd 8576 in_width *= FRAME_RES_X (f);
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;
42143acd 8579 in_height *= FRAME_RES_Y (f);
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 8776}
0855eb52 8777
bb4d86b4 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 }
0855eb52
JB
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}