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