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