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