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