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