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