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