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