In temp_output_buffer_show make sure window returned by display_buffer is live (Bug...
[emacs.git] / src / image.c
blobbcc0fcd78a33b1e09276e8401675c4e1ccc46be1
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2013 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
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.
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.
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/>. */
20 #include <config.h>
21 #include "sysstdio.h"
22 #include <unistd.h>
24 #ifdef HAVE_PNG
25 #if defined HAVE_LIBPNG_PNG_H
26 # include <libpng/png.h>
27 #else
28 # include <png.h>
29 #endif
30 #endif
32 #include <setjmp.h>
34 #include <c-ctype.h>
36 /* This makes the fields of a Display accessible, in Xlib header files. */
38 #define XLIB_ILLEGAL_ACCESS
40 #include "lisp.h"
41 #include "frame.h"
42 #include "window.h"
43 #include "dispextern.h"
44 #include "blockinput.h"
45 #include "systime.h"
46 #include <epaths.h>
47 #include "character.h"
48 #include "coding.h"
49 #include "termhooks.h"
50 #include "font.h"
52 #ifdef HAVE_SYS_STAT_H
53 #include <sys/stat.h>
54 #endif /* HAVE_SYS_STAT_H */
56 #ifdef HAVE_SYS_TYPES_H
57 #include <sys/types.h>
58 #endif /* HAVE_SYS_TYPES_H */
60 #ifdef HAVE_WINDOW_SYSTEM
61 #include TERM_HEADER
62 #endif /* HAVE_WINDOW_SYSTEM */
64 #ifdef HAVE_X_WINDOWS
65 #define COLOR_TABLE_SUPPORT 1
67 typedef struct x_bitmap_record Bitmap_Record;
68 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
69 #define NO_PIXMAP None
71 #define PIX_MASK_RETAIN 0
72 #define PIX_MASK_DRAW 1
73 #endif /* HAVE_X_WINDOWS */
75 #ifdef HAVE_NTGUI
77 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
78 #ifdef WINDOWSNT
79 # include "w32.h"
80 #endif
82 /* W32_TODO : Color tables on W32. */
83 #undef COLOR_TABLE_SUPPORT
85 typedef struct w32_bitmap_record Bitmap_Record;
86 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
87 #define NO_PIXMAP 0
89 #define PIX_MASK_RETAIN 0
90 #define PIX_MASK_DRAW 1
92 #define x_defined_color w32_defined_color
93 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
95 /* Version of libpng that we were compiled with, or -1 if no PNG
96 support was compiled in. This is tested by w32-win.el to correctly
97 set up the alist used to search for PNG libraries. */
98 Lisp_Object Qlibpng_version;
99 #endif /* HAVE_NTGUI */
101 #ifdef HAVE_NS
102 #undef COLOR_TABLE_SUPPORT
104 typedef struct ns_bitmap_record Bitmap_Record;
106 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
107 #define NO_PIXMAP 0
109 #define PIX_MASK_RETAIN 0
110 #define PIX_MASK_DRAW 1
112 #define x_defined_color(f, name, color_def, alloc) \
113 ns_defined_color (f, name, color_def, alloc, 0)
114 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
115 #endif /* HAVE_NS */
118 /* The symbol `postscript' identifying images of this type. */
120 static Lisp_Object Qpostscript;
122 static void x_disable_image (struct frame *, struct image *);
123 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
124 Lisp_Object);
126 static void init_color_table (void);
127 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
128 #ifdef COLOR_TABLE_SUPPORT
129 static void free_color_table (void);
130 static unsigned long *colors_in_color_table (int *n);
131 #endif
133 static Lisp_Object QCmax_width, QCmax_height;
135 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
136 id, which is just an int that this section returns. Bitmaps are
137 reference counted so they can be shared among frames.
139 Bitmap indices are guaranteed to be > 0, so a negative number can
140 be used to indicate no bitmap.
142 If you use x_create_bitmap_from_data, then you must keep track of
143 the bitmaps yourself. That is, creating a bitmap from the same
144 data more than once will not be caught. */
146 #ifdef HAVE_NS
147 /* Use with images created by ns_image_for_XPM. */
148 static unsigned long
149 XGetPixel (XImagePtr ximage, int x, int y)
151 return ns_get_pixel (ximage, x, y);
154 /* Use with images created by ns_image_for_XPM; alpha set to 1;
155 pixel is assumed to be in RGB form. */
156 static void
157 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
159 ns_put_pixel (ximage, x, y, pixel);
161 #endif /* HAVE_NS */
164 /* Functions to access the contents of a bitmap, given an id. */
167 x_bitmap_height (struct frame *f, ptrdiff_t id)
169 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
173 x_bitmap_width (struct frame *f, ptrdiff_t id)
175 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
178 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
179 ptrdiff_t
180 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
182 /* HAVE_NTGUI needs the explicit cast here. */
183 return (ptrdiff_t) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
185 #endif
187 #ifdef HAVE_X_WINDOWS
189 x_bitmap_mask (struct frame *f, ptrdiff_t id)
191 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
193 #endif
195 /* Allocate a new bitmap record. Returns index of new record. */
197 static ptrdiff_t
198 x_allocate_bitmap_record (struct frame *f)
200 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
201 ptrdiff_t i;
203 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
204 return ++dpyinfo->bitmaps_last;
206 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
207 if (dpyinfo->bitmaps[i].refcount == 0)
208 return i + 1;
210 dpyinfo->bitmaps =
211 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
212 10, -1, sizeof *dpyinfo->bitmaps);
213 return ++dpyinfo->bitmaps_last;
216 /* Add one reference to the reference count of the bitmap with id ID. */
218 void
219 x_reference_bitmap (struct frame *f, ptrdiff_t id)
221 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
224 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
226 ptrdiff_t
227 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
229 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
230 ptrdiff_t id;
232 #ifdef HAVE_X_WINDOWS
233 Pixmap bitmap;
234 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
235 bits, width, height);
236 if (! bitmap)
237 return -1;
238 #endif /* HAVE_X_WINDOWS */
240 #ifdef HAVE_NTGUI
241 Pixmap bitmap;
242 bitmap = CreateBitmap (width, height,
243 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
244 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
245 bits);
246 if (! bitmap)
247 return -1;
248 #endif /* HAVE_NTGUI */
250 #ifdef HAVE_NS
251 void *bitmap = ns_image_from_XBM (bits, width, height);
252 if (!bitmap)
253 return -1;
254 #endif
256 id = x_allocate_bitmap_record (f);
258 #ifdef HAVE_NS
259 dpyinfo->bitmaps[id - 1].img = bitmap;
260 dpyinfo->bitmaps[id - 1].depth = 1;
261 #endif
263 dpyinfo->bitmaps[id - 1].file = NULL;
264 dpyinfo->bitmaps[id - 1].height = height;
265 dpyinfo->bitmaps[id - 1].width = width;
266 dpyinfo->bitmaps[id - 1].refcount = 1;
268 #ifdef HAVE_X_WINDOWS
269 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
270 dpyinfo->bitmaps[id - 1].have_mask = 0;
271 dpyinfo->bitmaps[id - 1].depth = 1;
272 #endif /* HAVE_X_WINDOWS */
274 #ifdef HAVE_NTGUI
275 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
276 dpyinfo->bitmaps[id - 1].hinst = NULL;
277 dpyinfo->bitmaps[id - 1].depth = 1;
278 #endif /* HAVE_NTGUI */
280 return id;
283 /* Create bitmap from file FILE for frame F. */
285 ptrdiff_t
286 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
288 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
290 #ifdef HAVE_NTGUI
291 return -1; /* W32_TODO : bitmap support */
292 #endif /* HAVE_NTGUI */
294 #ifdef HAVE_NS
295 ptrdiff_t id;
296 void *bitmap = ns_image_from_file (file);
298 if (!bitmap)
299 return -1;
302 id = x_allocate_bitmap_record (f);
303 dpyinfo->bitmaps[id - 1].img = bitmap;
304 dpyinfo->bitmaps[id - 1].refcount = 1;
305 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
306 dpyinfo->bitmaps[id - 1].depth = 1;
307 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
308 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
309 return id;
310 #endif
312 #ifdef HAVE_X_WINDOWS
313 unsigned int width, height;
314 Pixmap bitmap;
315 int xhot, yhot, result;
316 ptrdiff_t id;
317 Lisp_Object found;
318 char *filename;
320 /* Look for an existing bitmap with the same name. */
321 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
323 if (dpyinfo->bitmaps[id].refcount
324 && dpyinfo->bitmaps[id].file
325 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
327 ++dpyinfo->bitmaps[id].refcount;
328 return id + 1;
332 /* Search bitmap-file-path for the file, if appropriate. */
333 if (openp (Vx_bitmap_file_path, file, Qnil, &found, make_number (R_OK)) < 0)
334 return -1;
336 filename = SSDATA (found);
338 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
339 filename, &width, &height, &bitmap, &xhot, &yhot);
340 if (result != BitmapSuccess)
341 return -1;
343 id = x_allocate_bitmap_record (f);
344 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
345 dpyinfo->bitmaps[id - 1].have_mask = 0;
346 dpyinfo->bitmaps[id - 1].refcount = 1;
347 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
348 dpyinfo->bitmaps[id - 1].depth = 1;
349 dpyinfo->bitmaps[id - 1].height = height;
350 dpyinfo->bitmaps[id - 1].width = width;
352 return id;
353 #endif /* HAVE_X_WINDOWS */
356 /* Free bitmap B. */
358 static void
359 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
361 #ifdef HAVE_X_WINDOWS
362 XFreePixmap (dpyinfo->display, bm->pixmap);
363 if (bm->have_mask)
364 XFreePixmap (dpyinfo->display, bm->mask);
365 #endif /* HAVE_X_WINDOWS */
367 #ifdef HAVE_NTGUI
368 DeleteObject (bm->pixmap);
369 #endif /* HAVE_NTGUI */
371 #ifdef HAVE_NS
372 ns_release_object (bm->img);
373 #endif
375 if (bm->file)
377 xfree (bm->file);
378 bm->file = NULL;
382 /* Remove reference to bitmap with id number ID. */
384 void
385 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
387 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
389 if (id > 0)
391 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
393 if (--bm->refcount == 0)
395 block_input ();
396 free_bitmap_record (dpyinfo, bm);
397 unblock_input ();
402 /* Free all the bitmaps for the display specified by DPYINFO. */
404 void
405 x_destroy_all_bitmaps (Display_Info *dpyinfo)
407 ptrdiff_t i;
408 Bitmap_Record *bm = dpyinfo->bitmaps;
410 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
411 if (bm->refcount > 0)
412 free_bitmap_record (dpyinfo, bm);
414 dpyinfo->bitmaps_last = 0;
417 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
418 XImagePtr *, Pixmap *);
419 static void x_destroy_x_image (XImagePtr ximg);
421 #ifdef HAVE_NTGUI
422 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
423 bool, HGDIOBJ *);
424 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
425 HGDIOBJ);
426 #else
427 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
428 static void image_unget_x_image (struct image *, bool, XImagePtr);
429 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
430 image_get_x_image (f, img, mask_p)
431 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
432 image_unget_x_image (img, mask_p, ximg)
433 #endif
435 #ifdef HAVE_X_WINDOWS
437 static void image_sync_to_pixmaps (struct frame *, struct image *);
439 /* Useful functions defined in the section
440 `Image type independent image structures' below. */
442 static unsigned long four_corners_best (XImagePtr ximg,
443 int *corners,
444 unsigned long width,
445 unsigned long height);
448 /* Create a mask of a bitmap. Note is this not a perfect mask.
449 It's nicer with some borders in this context */
451 void
452 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
454 Pixmap pixmap, mask;
455 XImagePtr ximg, mask_img;
456 unsigned long width, height;
457 bool result;
458 unsigned long bg;
459 unsigned long x, y, xp, xm, yp, ym;
460 GC gc;
462 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
464 if (!(id > 0))
465 return;
467 pixmap = x_bitmap_pixmap (f, id);
468 width = x_bitmap_width (f, id);
469 height = x_bitmap_height (f, id);
471 block_input ();
472 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
473 ~0, ZPixmap);
475 if (!ximg)
477 unblock_input ();
478 return;
481 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
483 unblock_input ();
484 if (!result)
486 XDestroyImage (ximg);
487 return;
490 bg = four_corners_best (ximg, NULL, width, height);
492 for (y = 0; y < ximg->height; ++y)
494 for (x = 0; x < ximg->width; ++x)
496 xp = x != ximg->width - 1 ? x + 1 : 0;
497 xm = x != 0 ? x - 1 : ximg->width - 1;
498 yp = y != ximg->height - 1 ? y + 1 : 0;
499 ym = y != 0 ? y - 1 : ximg->height - 1;
500 if (XGetPixel (ximg, x, y) == bg
501 && XGetPixel (ximg, x, yp) == bg
502 && XGetPixel (ximg, x, ym) == bg
503 && XGetPixel (ximg, xp, y) == bg
504 && XGetPixel (ximg, xp, yp) == bg
505 && XGetPixel (ximg, xp, ym) == bg
506 && XGetPixel (ximg, xm, y) == bg
507 && XGetPixel (ximg, xm, yp) == bg
508 && XGetPixel (ximg, xm, ym) == bg)
509 XPutPixel (mask_img, x, y, 0);
510 else
511 XPutPixel (mask_img, x, y, 1);
515 eassert (input_blocked_p ());
516 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
517 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
518 width, height);
519 XFreeGC (FRAME_X_DISPLAY (f), gc);
521 dpyinfo->bitmaps[id - 1].have_mask = 1;
522 dpyinfo->bitmaps[id - 1].mask = mask;
524 XDestroyImage (ximg);
525 x_destroy_x_image (mask_img);
528 #endif /* HAVE_X_WINDOWS */
531 /***********************************************************************
532 Image types
533 ***********************************************************************/
535 /* List of supported image types. Use define_image_type to add new
536 types. Use lookup_image_type to find a type for a given symbol. */
538 static struct image_type *image_types;
540 /* The symbol `xbm' which is used as the type symbol for XBM images. */
542 static Lisp_Object Qxbm;
544 /* Keywords. */
546 Lisp_Object QCascent, QCmargin, QCrelief;
547 Lisp_Object QCconversion;
548 static Lisp_Object QCheuristic_mask;
549 static Lisp_Object QCcolor_symbols;
550 static Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry;
551 static Lisp_Object QCcrop, QCrotation;
553 /* Other symbols. */
555 static Lisp_Object Qcount, Qextension_data, Qdelay;
556 static Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
558 /* Forward function prototypes. */
560 static struct image_type *lookup_image_type (Lisp_Object);
561 static void x_laplace (struct frame *, struct image *);
562 static void x_emboss (struct frame *, struct image *);
563 static void x_build_heuristic_mask (struct frame *, struct image *,
564 Lisp_Object);
565 #ifdef WINDOWSNT
566 #define CACHE_IMAGE_TYPE(type, status) \
567 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
568 #else
569 #define CACHE_IMAGE_TYPE(type, status)
570 #endif
572 #define ADD_IMAGE_TYPE(type) \
573 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
575 /* Define a new image type from TYPE. This adds a copy of TYPE to
576 image_types and caches the loading status of TYPE. */
578 static struct image_type *
579 define_image_type (struct image_type *type)
581 struct image_type *p = NULL;
582 Lisp_Object target_type = *type->type;
583 bool type_valid = 1;
585 block_input ();
587 for (p = image_types; p; p = p->next)
588 if (EQ (*p->type, target_type))
589 goto done;
591 if (type->init)
593 #if defined HAVE_NTGUI && defined WINDOWSNT
594 /* If we failed to load the library before, don't try again. */
595 Lisp_Object tested = Fassq (target_type, Vlibrary_cache);
596 if (CONSP (tested) && NILP (XCDR (tested)))
597 type_valid = 0;
598 else
599 #endif
601 type_valid = type->init ();
602 CACHE_IMAGE_TYPE (target_type, type_valid ? Qt : Qnil);
606 if (type_valid)
608 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
609 The initialized data segment is read-only. */
610 p = xmalloc (sizeof *p);
611 *p = *type;
612 p->next = image_types;
613 image_types = p;
616 done:
617 unblock_input ();
618 return p;
622 /* Value is true if OBJECT is a valid Lisp image specification. A
623 valid image specification is a list whose car is the symbol
624 `image', and whose rest is a property list. The property list must
625 contain a value for key `:type'. That value must be the name of a
626 supported image type. The rest of the property list depends on the
627 image type. */
629 bool
630 valid_image_p (Lisp_Object object)
632 bool valid_p = 0;
634 if (IMAGEP (object))
636 Lisp_Object tem;
638 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
639 if (EQ (XCAR (tem), QCtype))
641 tem = XCDR (tem);
642 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
644 struct image_type *type;
645 type = lookup_image_type (XCAR (tem));
646 if (type)
647 valid_p = type->valid_p (object);
650 break;
654 return valid_p;
658 /* Log error message with format string FORMAT and argument ARG.
659 Signaling an error, e.g. when an image cannot be loaded, is not a
660 good idea because this would interrupt redisplay, and the error
661 message display would lead to another redisplay. This function
662 therefore simply displays a message. */
664 static void
665 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
667 add_to_log (format, arg1, arg2);
672 /***********************************************************************
673 Image specifications
674 ***********************************************************************/
676 enum image_value_type
678 IMAGE_DONT_CHECK_VALUE_TYPE,
679 IMAGE_STRING_VALUE,
680 IMAGE_STRING_OR_NIL_VALUE,
681 IMAGE_SYMBOL_VALUE,
682 IMAGE_POSITIVE_INTEGER_VALUE,
683 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
684 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
685 IMAGE_ASCENT_VALUE,
686 IMAGE_INTEGER_VALUE,
687 IMAGE_FUNCTION_VALUE,
688 IMAGE_NUMBER_VALUE,
689 IMAGE_BOOL_VALUE
692 /* Structure used when parsing image specifications. */
694 struct image_keyword
696 /* Name of keyword. */
697 const char *name;
699 /* The type of value allowed. */
700 enum image_value_type type;
702 /* True means key must be present. */
703 bool mandatory_p;
705 /* Used to recognize duplicate keywords in a property list. */
706 int count;
708 /* The value that was found. */
709 Lisp_Object value;
713 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
714 has the format (image KEYWORD VALUE ...). One of the keyword/
715 value pairs must be `:type TYPE'. KEYWORDS is a vector of
716 image_keywords structures of size NKEYWORDS describing other
717 allowed keyword/value pairs. Value is true if SPEC is valid. */
719 static bool
720 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
721 int nkeywords, Lisp_Object type)
723 int i;
724 Lisp_Object plist;
726 if (!IMAGEP (spec))
727 return 0;
729 plist = XCDR (spec);
730 while (CONSP (plist))
732 Lisp_Object key, value;
734 /* First element of a pair must be a symbol. */
735 key = XCAR (plist);
736 plist = XCDR (plist);
737 if (!SYMBOLP (key))
738 return 0;
740 /* There must follow a value. */
741 if (!CONSP (plist))
742 return 0;
743 value = XCAR (plist);
744 plist = XCDR (plist);
746 /* Find key in KEYWORDS. Error if not found. */
747 for (i = 0; i < nkeywords; ++i)
748 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
749 break;
751 if (i == nkeywords)
752 continue;
754 /* Record that we recognized the keyword. If a keywords
755 was found more than once, it's an error. */
756 keywords[i].value = value;
757 if (keywords[i].count > 1)
758 return 0;
759 ++keywords[i].count;
761 /* Check type of value against allowed type. */
762 switch (keywords[i].type)
764 case IMAGE_STRING_VALUE:
765 if (!STRINGP (value))
766 return 0;
767 break;
769 case IMAGE_STRING_OR_NIL_VALUE:
770 if (!STRINGP (value) && !NILP (value))
771 return 0;
772 break;
774 case IMAGE_SYMBOL_VALUE:
775 if (!SYMBOLP (value))
776 return 0;
777 break;
779 case IMAGE_POSITIVE_INTEGER_VALUE:
780 if (! RANGED_INTEGERP (1, value, INT_MAX))
781 return 0;
782 break;
784 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
785 if (RANGED_INTEGERP (0, value, INT_MAX))
786 break;
787 if (CONSP (value)
788 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
789 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
790 break;
791 return 0;
793 case IMAGE_ASCENT_VALUE:
794 if (SYMBOLP (value) && EQ (value, Qcenter))
795 break;
796 else if (RANGED_INTEGERP (0, value, 100))
797 break;
798 return 0;
800 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
801 /* Unlike the other integer-related cases, this one does not
802 verify that VALUE fits in 'int'. This is because callers
803 want EMACS_INT. */
804 if (!INTEGERP (value) || XINT (value) < 0)
805 return 0;
806 break;
808 case IMAGE_DONT_CHECK_VALUE_TYPE:
809 break;
811 case IMAGE_FUNCTION_VALUE:
812 value = indirect_function (value);
813 if (!NILP (Ffunctionp (value)))
814 break;
815 return 0;
817 case IMAGE_NUMBER_VALUE:
818 if (!INTEGERP (value) && !FLOATP (value))
819 return 0;
820 break;
822 case IMAGE_INTEGER_VALUE:
823 if (! TYPE_RANGED_INTEGERP (int, value))
824 return 0;
825 break;
827 case IMAGE_BOOL_VALUE:
828 if (!NILP (value) && !EQ (value, Qt))
829 return 0;
830 break;
832 default:
833 emacs_abort ();
834 break;
837 if (EQ (key, QCtype) && !EQ (type, value))
838 return 0;
841 /* Check that all mandatory fields are present. */
842 for (i = 0; i < nkeywords; ++i)
843 if (keywords[i].mandatory_p && keywords[i].count == 0)
844 return 0;
846 return NILP (plist);
850 /* Return the value of KEY in image specification SPEC. Value is nil
851 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
852 was found in SPEC. */
854 static Lisp_Object
855 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
857 Lisp_Object tail;
859 eassert (valid_image_p (spec));
861 for (tail = XCDR (spec);
862 CONSP (tail) && CONSP (XCDR (tail));
863 tail = XCDR (XCDR (tail)))
865 if (EQ (XCAR (tail), key))
867 if (found)
868 *found = 1;
869 return XCAR (XCDR (tail));
873 if (found)
874 *found = 0;
875 return Qnil;
879 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
880 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
881 PIXELS non-nil means return the size in pixels, otherwise return the
882 size in canonical character units.
883 FRAME is the frame on which the image will be displayed. FRAME nil
884 or omitted means use the selected frame. */)
885 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
887 Lisp_Object size;
889 size = Qnil;
890 if (valid_image_p (spec))
892 struct frame *f = decode_window_system_frame (frame);
893 ptrdiff_t id = lookup_image (f, spec);
894 struct image *img = IMAGE_FROM_ID (f, id);
895 int width = img->width + 2 * img->hmargin;
896 int height = img->height + 2 * img->vmargin;
898 if (NILP (pixels))
899 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
900 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
901 else
902 size = Fcons (make_number (width), make_number (height));
904 else
905 error ("Invalid image specification");
907 return size;
911 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
912 doc: /* Return t if image SPEC has a mask bitmap.
913 FRAME is the frame on which the image will be displayed. FRAME nil
914 or omitted means use the selected frame. */)
915 (Lisp_Object spec, Lisp_Object frame)
917 Lisp_Object mask;
919 mask = Qnil;
920 if (valid_image_p (spec))
922 struct frame *f = decode_window_system_frame (frame);
923 ptrdiff_t id = lookup_image (f, spec);
924 struct image *img = IMAGE_FROM_ID (f, id);
925 if (img->mask)
926 mask = Qt;
928 else
929 error ("Invalid image specification");
931 return mask;
934 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
935 doc: /* Return metadata for image SPEC.
936 FRAME is the frame on which the image will be displayed. FRAME nil
937 or omitted means use the selected frame. */)
938 (Lisp_Object spec, Lisp_Object frame)
940 Lisp_Object ext;
942 ext = Qnil;
943 if (valid_image_p (spec))
945 struct frame *f = decode_window_system_frame (frame);
946 ptrdiff_t id = lookup_image (f, spec);
947 struct image *img = IMAGE_FROM_ID (f, id);
948 ext = img->lisp_data;
951 return ext;
955 /***********************************************************************
956 Image type independent image structures
957 ***********************************************************************/
959 #define MAX_IMAGE_SIZE 10.0
960 /* Allocate and return a new image structure for image specification
961 SPEC. SPEC has a hash value of HASH. */
963 static struct image *
964 make_image (Lisp_Object spec, EMACS_UINT hash)
966 struct image *img = xzalloc (sizeof *img);
967 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
969 eassert (valid_image_p (spec));
970 img->dependencies = NILP (file) ? Qnil : list1 (file);
971 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
972 eassert (img->type != NULL);
973 img->spec = spec;
974 img->lisp_data = Qnil;
975 img->ascent = DEFAULT_IMAGE_ASCENT;
976 img->hash = hash;
977 img->corners[BOT_CORNER] = -1; /* Full image */
978 return img;
982 /* Free image IMG which was used on frame F, including its resources. */
984 static void
985 free_image (struct frame *f, struct image *img)
987 if (img)
989 struct image_cache *c = FRAME_IMAGE_CACHE (f);
991 /* Remove IMG from the hash table of its cache. */
992 if (img->prev)
993 img->prev->next = img->next;
994 else
995 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
997 if (img->next)
998 img->next->prev = img->prev;
1000 c->images[img->id] = NULL;
1002 /* Free resources, then free IMG. */
1003 img->type->free (f, img);
1004 xfree (img);
1008 /* Return true if the given widths and heights are valid for display. */
1010 static bool
1011 check_image_size (struct frame *f, int width, int height)
1013 int w, h;
1015 if (width <= 0 || height <= 0)
1016 return 0;
1018 if (INTEGERP (Vmax_image_size))
1019 return (width <= XINT (Vmax_image_size)
1020 && height <= XINT (Vmax_image_size));
1021 else if (FLOATP (Vmax_image_size))
1023 if (f != NULL)
1025 w = FRAME_PIXEL_WIDTH (f);
1026 h = FRAME_PIXEL_HEIGHT (f);
1028 else
1029 w = h = 1024; /* Arbitrary size for unknown frame. */
1030 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1031 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1033 else
1034 return 1;
1037 /* Prepare image IMG for display on frame F. Must be called before
1038 drawing an image. */
1040 void
1041 prepare_image_for_display (struct frame *f, struct image *img)
1043 /* We're about to display IMG, so set its timestamp to `now'. */
1044 img->timestamp = current_timespec ();
1046 /* If IMG doesn't have a pixmap yet, load it now, using the image
1047 type dependent loader function. */
1048 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1049 img->load_failed_p = ! img->type->load (f, img);
1051 #ifdef HAVE_X_WINDOWS
1052 if (!img->load_failed_p)
1054 block_input ();
1055 image_sync_to_pixmaps (f, img);
1056 unblock_input ();
1058 #endif
1062 /* Value is the number of pixels for the ascent of image IMG when
1063 drawn in face FACE. */
1066 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1068 int height;
1069 int ascent;
1071 if (slice->height == img->height)
1072 height = img->height + img->vmargin;
1073 else if (slice->y == 0)
1074 height = slice->height + img->vmargin;
1075 else
1076 height = slice->height;
1078 if (img->ascent == CENTERED_IMAGE_ASCENT)
1080 if (face->font)
1082 #ifdef HAVE_NTGUI
1083 /* W32 specific version. Why?. ++kfs */
1084 ascent = height / 2 - (FONT_DESCENT (face->font)
1085 - FONT_BASE (face->font)) / 2;
1086 #else
1087 /* This expression is arranged so that if the image can't be
1088 exactly centered, it will be moved slightly up. This is
1089 because a typical font is `top-heavy' (due to the presence
1090 uppercase letters), so the image placement should err towards
1091 being top-heavy too. It also just generally looks better. */
1092 ascent = (height + FONT_BASE (face->font)
1093 - FONT_DESCENT (face->font) + 1) / 2;
1094 #endif /* HAVE_NTGUI */
1096 else
1097 ascent = height / 2;
1099 else
1100 ascent = height * (img->ascent / 100.0);
1102 return ascent;
1106 /* Image background colors. */
1108 /* Find the "best" corner color of a bitmap.
1109 On W32, XIMG is assumed to a device context with the bitmap selected. */
1111 static RGB_PIXEL_COLOR
1112 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1113 unsigned long width, unsigned long height)
1115 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1116 int i, best_count;
1118 if (corners && corners[BOT_CORNER] >= 0)
1120 /* Get the colors at the corner_pixels of ximg. */
1121 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1122 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1123 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1124 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1126 else
1128 /* Get the colors at the corner_pixels of ximg. */
1129 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1130 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1131 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1132 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1134 /* Choose the most frequently found color as background. */
1135 for (i = best_count = 0; i < 4; ++i)
1137 int j, n;
1139 for (j = n = 0; j < 4; ++j)
1140 if (corner_pixels[i] == corner_pixels[j])
1141 ++n;
1143 if (n > best_count)
1144 best = corner_pixels[i], best_count = n;
1147 return best;
1150 /* Portability macros */
1152 #ifdef HAVE_NTGUI
1154 #define Free_Pixmap(display, pixmap) \
1155 DeleteObject (pixmap)
1157 #elif defined (HAVE_NS)
1159 #define Free_Pixmap(display, pixmap) \
1160 ns_release_object (pixmap)
1162 #else
1164 #define Free_Pixmap(display, pixmap) \
1165 XFreePixmap (display, pixmap)
1167 #endif /* !HAVE_NTGUI && !HAVE_NS */
1170 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1171 it is guessed heuristically. If non-zero, XIMG is an existing
1172 XImage object (or device context with the image selected on W32) to
1173 use for the heuristic. */
1175 RGB_PIXEL_COLOR
1176 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1178 if (! img->background_valid)
1179 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1181 bool free_ximg = !ximg;
1182 #ifdef HAVE_NTGUI
1183 HGDIOBJ prev;
1184 #endif /* HAVE_NTGUI */
1186 if (free_ximg)
1187 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1189 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1191 if (free_ximg)
1192 image_unget_x_image_or_dc (img, 0, ximg, prev);
1194 img->background_valid = 1;
1197 return img->background;
1200 /* Return the `background_transparent' field of IMG. If IMG doesn't
1201 have one yet, it is guessed heuristically. If non-zero, MASK is an
1202 existing XImage object to use for the heuristic. */
1205 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1207 if (! img->background_transparent_valid)
1208 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1210 if (img->mask)
1212 bool free_mask = !mask;
1213 #ifdef HAVE_NTGUI
1214 HGDIOBJ prev;
1215 #endif /* HAVE_NTGUI */
1217 if (free_mask)
1218 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1220 img->background_transparent
1221 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1223 if (free_mask)
1224 image_unget_x_image_or_dc (img, 1, mask, prev);
1226 else
1227 img->background_transparent = 0;
1229 img->background_transparent_valid = 1;
1232 return img->background_transparent;
1236 /***********************************************************************
1237 Helper functions for X image types
1238 ***********************************************************************/
1240 /* Clear X resources of image IMG on frame F according to FLAGS.
1241 FLAGS is bitwise-or of the following masks:
1242 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1243 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1244 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1245 any. */
1247 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1248 #define CLEAR_IMAGE_MASK (1 << 1)
1249 #define CLEAR_IMAGE_COLORS (1 << 2)
1251 static void
1252 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1254 if (flags & CLEAR_IMAGE_PIXMAP)
1256 if (img->pixmap)
1258 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1259 img->pixmap = NO_PIXMAP;
1260 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1261 img->background_valid = 0;
1263 #ifdef HAVE_X_WINDOWS
1264 if (img->ximg)
1266 x_destroy_x_image (img->ximg);
1267 img->ximg = NULL;
1268 img->background_valid = 0;
1270 #endif
1273 if (flags & CLEAR_IMAGE_MASK)
1275 if (img->mask)
1277 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1278 img->mask = NO_PIXMAP;
1279 img->background_transparent_valid = 0;
1281 #ifdef HAVE_X_WINDOWS
1282 if (img->mask_img)
1284 x_destroy_x_image (img->mask_img);
1285 img->mask_img = NULL;
1286 img->background_transparent_valid = 0;
1288 #endif
1291 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1293 /* W32_TODO: color table support. */
1294 #ifdef HAVE_X_WINDOWS
1295 x_free_colors (f, img->colors, img->ncolors);
1296 #endif /* HAVE_X_WINDOWS */
1297 xfree (img->colors);
1298 img->colors = NULL;
1299 img->ncolors = 0;
1304 /* Free X resources of image IMG which is used on frame F. */
1306 static void
1307 x_clear_image (struct frame *f, struct image *img)
1309 block_input ();
1310 x_clear_image_1 (f, img,
1311 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1312 unblock_input ();
1316 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1317 cannot be allocated, use DFLT. Add a newly allocated color to
1318 IMG->colors, so that it can be freed again. Value is the pixel
1319 color. */
1321 static unsigned long
1322 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1323 unsigned long dflt)
1325 XColor color;
1326 unsigned long result;
1328 eassert (STRINGP (color_name));
1330 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1331 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1332 INT_MAX))
1334 /* This isn't called frequently so we get away with simply
1335 reallocating the color vector to the needed size, here. */
1336 ptrdiff_t ncolors = img->ncolors + 1;
1337 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1338 img->colors[ncolors - 1] = color.pixel;
1339 img->ncolors = ncolors;
1340 result = color.pixel;
1342 else
1343 result = dflt;
1345 return result;
1350 /***********************************************************************
1351 Image Cache
1352 ***********************************************************************/
1354 static void cache_image (struct frame *f, struct image *img);
1356 /* Return a new, initialized image cache that is allocated from the
1357 heap. Call free_image_cache to free an image cache. */
1359 struct image_cache *
1360 make_image_cache (void)
1362 struct image_cache *c = xmalloc (sizeof *c);
1364 c->size = 50;
1365 c->used = c->refcount = 0;
1366 c->images = xmalloc (c->size * sizeof *c->images);
1367 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1368 return c;
1372 /* Find an image matching SPEC in the cache, and return it. If no
1373 image is found, return NULL. */
1374 static struct image *
1375 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1377 struct image *img;
1378 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1379 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1381 if (!c) return NULL;
1383 /* If the image spec does not specify a background color, the cached
1384 image must have the same background color as the current frame.
1385 The foreground color must also match, for the sake of monochrome
1386 images.
1388 In fact, we could ignore the foreground color matching condition
1389 for color images, or if the image spec specifies :foreground;
1390 similarly we could ignore the background color matching condition
1391 for formats that don't use transparency (such as jpeg), or if the
1392 image spec specifies :background. However, the extra memory
1393 usage is probably negligible in practice, so we don't bother. */
1395 for (img = c->buckets[i]; img; img = img->next)
1396 if (img->hash == hash
1397 && !NILP (Fequal (img->spec, spec))
1398 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1399 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1400 break;
1401 return img;
1405 /* Search frame F for an image with spec SPEC, and free it. */
1407 static void
1408 uncache_image (struct frame *f, Lisp_Object spec)
1410 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1411 if (img)
1413 free_image (f, img);
1414 /* As display glyphs may still be referring to the image ID, we
1415 must garbage the frame (Bug#6426). */
1416 SET_FRAME_GARBAGED (f);
1421 /* Free image cache of frame F. Be aware that X frames share images
1422 caches. */
1424 void
1425 free_image_cache (struct frame *f)
1427 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1428 if (c)
1430 ptrdiff_t i;
1432 /* Cache should not be referenced by any frame when freed. */
1433 eassert (c->refcount == 0);
1435 for (i = 0; i < c->used; ++i)
1436 free_image (f, c->images[i]);
1437 xfree (c->images);
1438 xfree (c->buckets);
1439 xfree (c);
1440 FRAME_IMAGE_CACHE (f) = NULL;
1445 /* Clear image cache of frame F. FILTER=t means free all images.
1446 FILTER=nil means clear only images that haven't been
1447 displayed for some time.
1448 Else, only free the images which have FILTER in their `dependencies'.
1449 Should be called from time to time to reduce the number of loaded images.
1450 If image-cache-eviction-delay is non-nil, this frees images in the cache
1451 which weren't displayed for at least that many seconds. */
1453 static void
1454 clear_image_cache (struct frame *f, Lisp_Object filter)
1456 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1458 if (c)
1460 ptrdiff_t i, nfreed = 0;
1462 /* Block input so that we won't be interrupted by a SIGIO
1463 while being in an inconsistent state. */
1464 block_input ();
1466 if (!NILP (filter))
1468 /* Filter image cache. */
1469 for (i = 0; i < c->used; ++i)
1471 struct image *img = c->images[i];
1472 if (img && (EQ (Qt, filter)
1473 || !NILP (Fmember (filter, img->dependencies))))
1475 free_image (f, img);
1476 ++nfreed;
1480 else if (INTEGERP (Vimage_cache_eviction_delay))
1482 /* Free cache based on timestamp. */
1483 struct timespec old, t;
1484 double delay;
1485 ptrdiff_t nimages = 0;
1487 for (i = 0; i < c->used; ++i)
1488 if (c->images[i])
1489 nimages++;
1491 /* If the number of cached images has grown unusually large,
1492 decrease the cache eviction delay (Bug#6230). */
1493 delay = XINT (Vimage_cache_eviction_delay);
1494 if (nimages > 40)
1495 delay = 1600 * delay / nimages / nimages;
1496 delay = max (delay, 1);
1498 t = current_timespec ();
1499 old = timespec_sub (t, dtotimespec (delay));
1501 for (i = 0; i < c->used; ++i)
1503 struct image *img = c->images[i];
1504 if (img && timespec_cmp (img->timestamp, old) < 0)
1506 free_image (f, img);
1507 ++nfreed;
1512 /* We may be clearing the image cache because, for example,
1513 Emacs was iconified for a longer period of time. In that
1514 case, current matrices may still contain references to
1515 images freed above. So, clear these matrices. */
1516 if (nfreed)
1518 Lisp_Object tail, frame;
1520 FOR_EACH_FRAME (tail, frame)
1522 struct frame *fr = XFRAME (frame);
1523 if (FRAME_IMAGE_CACHE (fr) == c)
1524 clear_current_matrices (fr);
1527 ++windows_or_buffers_changed;
1530 unblock_input ();
1534 void
1535 clear_image_caches (Lisp_Object filter)
1537 /* FIXME: We want to do
1538 * struct terminal *t;
1539 * for (t = terminal_list; t; t = t->next_terminal)
1540 * clear_image_cache (t, filter); */
1541 Lisp_Object tail, frame;
1542 FOR_EACH_FRAME (tail, frame)
1543 if (FRAME_WINDOW_P (XFRAME (frame)))
1544 clear_image_cache (XFRAME (frame), filter);
1547 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1548 0, 1, 0,
1549 doc: /* Clear the image cache.
1550 FILTER nil or a frame means clear all images in the selected frame.
1551 FILTER t means clear the image caches of all frames.
1552 Anything else, means only clear those images which refer to FILTER,
1553 which is then usually a filename. */)
1554 (Lisp_Object filter)
1556 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1557 clear_image_caches (filter);
1558 else
1559 clear_image_cache (decode_window_system_frame (filter), Qt);
1561 return Qnil;
1565 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1566 1, 2, 0,
1567 doc: /* Flush the image with specification SPEC on frame FRAME.
1568 This removes the image from the Emacs image cache. If SPEC specifies
1569 an image file, the next redisplay of this image will read from the
1570 current contents of that file.
1572 FRAME nil or omitted means use the selected frame.
1573 FRAME t means refresh the image on all frames. */)
1574 (Lisp_Object spec, Lisp_Object frame)
1576 if (!valid_image_p (spec))
1577 error ("Invalid image specification");
1579 if (EQ (frame, Qt))
1581 Lisp_Object tail;
1582 FOR_EACH_FRAME (tail, frame)
1584 struct frame *f = XFRAME (frame);
1585 if (FRAME_WINDOW_P (f))
1586 uncache_image (f, spec);
1589 else
1590 uncache_image (decode_window_system_frame (frame), spec);
1592 return Qnil;
1596 /* Compute masks and transform image IMG on frame F, as specified
1597 by the image's specification, */
1599 static void
1600 postprocess_image (struct frame *f, struct image *img)
1602 /* Manipulation of the image's mask. */
1603 if (img->pixmap)
1605 Lisp_Object conversion, spec;
1606 Lisp_Object mask;
1608 spec = img->spec;
1610 /* `:heuristic-mask t'
1611 `:mask heuristic'
1612 means build a mask heuristically.
1613 `:heuristic-mask (R G B)'
1614 `:mask (heuristic (R G B))'
1615 means build a mask from color (R G B) in the
1616 image.
1617 `:mask nil'
1618 means remove a mask, if any. */
1620 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1621 if (!NILP (mask))
1622 x_build_heuristic_mask (f, img, mask);
1623 else
1625 bool found_p;
1627 mask = image_spec_value (spec, QCmask, &found_p);
1629 if (EQ (mask, Qheuristic))
1630 x_build_heuristic_mask (f, img, Qt);
1631 else if (CONSP (mask)
1632 && EQ (XCAR (mask), Qheuristic))
1634 if (CONSP (XCDR (mask)))
1635 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1636 else
1637 x_build_heuristic_mask (f, img, XCDR (mask));
1639 else if (NILP (mask) && found_p && img->mask)
1640 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1644 /* Should we apply an image transformation algorithm? */
1645 conversion = image_spec_value (spec, QCconversion, NULL);
1646 if (EQ (conversion, Qdisabled))
1647 x_disable_image (f, img);
1648 else if (EQ (conversion, Qlaplace))
1649 x_laplace (f, img);
1650 else if (EQ (conversion, Qemboss))
1651 x_emboss (f, img);
1652 else if (CONSP (conversion)
1653 && EQ (XCAR (conversion), Qedge_detection))
1655 Lisp_Object tem;
1656 tem = XCDR (conversion);
1657 if (CONSP (tem))
1658 x_edge_detection (f, img,
1659 Fplist_get (tem, QCmatrix),
1660 Fplist_get (tem, QCcolor_adjustment));
1666 /* Return the id of image with Lisp specification SPEC on frame F.
1667 SPEC must be a valid Lisp image specification (see valid_image_p). */
1669 ptrdiff_t
1670 lookup_image (struct frame *f, Lisp_Object spec)
1672 struct image *img;
1673 EMACS_UINT hash;
1675 /* F must be a window-system frame, and SPEC must be a valid image
1676 specification. */
1677 eassert (FRAME_WINDOW_P (f));
1678 eassert (valid_image_p (spec));
1680 /* Look up SPEC in the hash table of the image cache. */
1681 hash = sxhash (spec, 0);
1682 img = search_image_cache (f, spec, hash);
1683 if (img && img->load_failed_p)
1685 free_image (f, img);
1686 img = NULL;
1689 /* If not found, create a new image and cache it. */
1690 if (img == NULL)
1692 block_input ();
1693 img = make_image (spec, hash);
1694 cache_image (f, img);
1695 img->load_failed_p = ! img->type->load (f, img);
1696 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1697 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1699 /* If we can't load the image, and we don't have a width and
1700 height, use some arbitrary width and height so that we can
1701 draw a rectangle for it. */
1702 if (img->load_failed_p)
1704 Lisp_Object value;
1706 value = image_spec_value (spec, QCwidth, NULL);
1707 img->width = (INTEGERP (value)
1708 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1709 value = image_spec_value (spec, QCheight, NULL);
1710 img->height = (INTEGERP (value)
1711 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1713 else
1715 /* Handle image type independent image attributes
1716 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1717 `:background COLOR'. */
1718 Lisp_Object ascent, margin, relief, bg;
1719 int relief_bound;
1721 ascent = image_spec_value (spec, QCascent, NULL);
1722 if (INTEGERP (ascent))
1723 img->ascent = XFASTINT (ascent);
1724 else if (EQ (ascent, Qcenter))
1725 img->ascent = CENTERED_IMAGE_ASCENT;
1727 margin = image_spec_value (spec, QCmargin, NULL);
1728 if (INTEGERP (margin))
1729 img->vmargin = img->hmargin = XFASTINT (margin);
1730 else if (CONSP (margin))
1732 img->hmargin = XFASTINT (XCAR (margin));
1733 img->vmargin = XFASTINT (XCDR (margin));
1736 relief = image_spec_value (spec, QCrelief, NULL);
1737 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1738 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1740 img->relief = XINT (relief);
1741 img->hmargin += eabs (img->relief);
1742 img->vmargin += eabs (img->relief);
1745 if (! img->background_valid)
1747 bg = image_spec_value (img->spec, QCbackground, NULL);
1748 if (!NILP (bg))
1750 img->background
1751 = x_alloc_image_color (f, img, bg,
1752 FRAME_BACKGROUND_PIXEL (f));
1753 img->background_valid = 1;
1757 /* Do image transformations and compute masks, unless we
1758 don't have the image yet. */
1759 if (!EQ (*img->type->type, Qpostscript))
1760 postprocess_image (f, img);
1763 unblock_input ();
1766 /* We're using IMG, so set its timestamp to `now'. */
1767 img->timestamp = current_timespec ();
1769 /* Value is the image id. */
1770 return img->id;
1774 /* Cache image IMG in the image cache of frame F. */
1776 static void
1777 cache_image (struct frame *f, struct image *img)
1779 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1780 ptrdiff_t i;
1782 /* Find a free slot in c->images. */
1783 for (i = 0; i < c->used; ++i)
1784 if (c->images[i] == NULL)
1785 break;
1787 /* If no free slot found, maybe enlarge c->images. */
1788 if (i == c->used && c->used == c->size)
1789 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1791 /* Add IMG to c->images, and assign IMG an id. */
1792 c->images[i] = img;
1793 img->id = i;
1794 if (i == c->used)
1795 ++c->used;
1797 /* Add IMG to the cache's hash table. */
1798 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1799 img->next = c->buckets[i];
1800 if (img->next)
1801 img->next->prev = img;
1802 img->prev = NULL;
1803 c->buckets[i] = img;
1807 /* Call FN on every image in the image cache of frame F. Used to mark
1808 Lisp Objects in the image cache. */
1810 /* Mark Lisp objects in image IMG. */
1812 static void
1813 mark_image (struct image *img)
1815 mark_object (img->spec);
1816 mark_object (img->dependencies);
1818 if (!NILP (img->lisp_data))
1819 mark_object (img->lisp_data);
1823 void
1824 mark_image_cache (struct image_cache *c)
1826 if (c)
1828 ptrdiff_t i;
1829 for (i = 0; i < c->used; ++i)
1830 if (c->images[i])
1831 mark_image (c->images[i]);
1837 /***********************************************************************
1838 X / NS / W32 support code
1839 ***********************************************************************/
1841 #ifdef WINDOWSNT
1843 /* Macro for defining functions that will be loaded from image DLLs. */
1844 #define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
1846 /* Macro for loading those image functions from the library. */
1847 #define LOAD_IMGLIB_FN(lib,func) { \
1848 fn_##func = (void *) GetProcAddress (lib, #func); \
1849 if (!fn_##func) return 0; \
1852 #endif /* WINDOWSNT */
1854 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1855 windowing system.
1856 WIDTH and HEIGHT must both be positive.
1857 If XIMG is null, assume it is a bitmap. */
1858 static bool
1859 x_check_image_size (XImagePtr ximg, int width, int height)
1861 #ifdef HAVE_X_WINDOWS
1862 /* Respect Xlib's limits: it cannot deal with images that have more
1863 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1864 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1865 enum
1867 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1868 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1871 int bitmap_pad, depth, bytes_per_line;
1872 if (ximg)
1874 bitmap_pad = ximg->bitmap_pad;
1875 depth = ximg->depth;
1876 bytes_per_line = ximg->bytes_per_line;
1878 else
1880 bitmap_pad = 8;
1881 depth = 1;
1882 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1884 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1885 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1886 #else
1887 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1888 For now, assume that every image size is allowed on these systems. */
1889 return 1;
1890 #endif
1893 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1894 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1895 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1896 via xmalloc. Print error messages via image_error if an error
1897 occurs. Value is true if successful.
1899 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1900 should indicate the bit depth of the image. */
1902 static bool
1903 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1904 XImagePtr *ximg, Pixmap *pixmap)
1906 #ifdef HAVE_X_WINDOWS
1907 Display *display = FRAME_X_DISPLAY (f);
1908 Window window = FRAME_X_WINDOW (f);
1909 Screen *screen = FRAME_X_SCREEN (f);
1911 eassert (input_blocked_p ());
1913 if (depth <= 0)
1914 depth = DefaultDepthOfScreen (screen);
1915 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1916 depth, ZPixmap, 0, NULL, width, height,
1917 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1918 if (*ximg == NULL)
1920 image_error ("Unable to allocate X image", Qnil, Qnil);
1921 return 0;
1924 if (! x_check_image_size (*ximg, width, height))
1926 x_destroy_x_image (*ximg);
1927 *ximg = NULL;
1928 image_error ("Image too large (%dx%d)",
1929 make_number (width), make_number (height));
1930 return 0;
1933 /* Allocate image raster. */
1934 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1936 /* Allocate a pixmap of the same size. */
1937 *pixmap = XCreatePixmap (display, window, width, height, depth);
1938 if (*pixmap == NO_PIXMAP)
1940 x_destroy_x_image (*ximg);
1941 *ximg = NULL;
1942 image_error ("Unable to create X pixmap", Qnil, Qnil);
1943 return 0;
1946 return 1;
1947 #endif /* HAVE_X_WINDOWS */
1949 #ifdef HAVE_NTGUI
1951 BITMAPINFOHEADER *header;
1952 HDC hdc;
1953 int scanline_width_bits;
1954 int remainder;
1955 int palette_colors = 0;
1957 if (depth == 0)
1958 depth = 24;
1960 if (depth != 1 && depth != 4 && depth != 8
1961 && depth != 16 && depth != 24 && depth != 32)
1963 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1964 return 0;
1967 scanline_width_bits = width * depth;
1968 remainder = scanline_width_bits % 32;
1970 if (remainder)
1971 scanline_width_bits += 32 - remainder;
1973 /* Bitmaps with a depth less than 16 need a palette. */
1974 /* BITMAPINFO structure already contains the first RGBQUAD. */
1975 if (depth < 16)
1976 palette_colors = 1 << (depth - 1);
1978 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1980 header = &(*ximg)->info.bmiHeader;
1981 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
1982 header->biSize = sizeof (*header);
1983 header->biWidth = width;
1984 header->biHeight = -height; /* negative indicates a top-down bitmap. */
1985 header->biPlanes = 1;
1986 header->biBitCount = depth;
1987 header->biCompression = BI_RGB;
1988 header->biClrUsed = palette_colors;
1990 /* TODO: fill in palette. */
1991 if (depth == 1)
1993 (*ximg)->info.bmiColors[0].rgbBlue = 0;
1994 (*ximg)->info.bmiColors[0].rgbGreen = 0;
1995 (*ximg)->info.bmiColors[0].rgbRed = 0;
1996 (*ximg)->info.bmiColors[0].rgbReserved = 0;
1997 (*ximg)->info.bmiColors[1].rgbBlue = 255;
1998 (*ximg)->info.bmiColors[1].rgbGreen = 255;
1999 (*ximg)->info.bmiColors[1].rgbRed = 255;
2000 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2003 hdc = get_frame_dc (f);
2005 /* Create a DIBSection and raster array for the bitmap,
2006 and store its handle in *pixmap. */
2007 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2008 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2009 /* casting avoids a GCC warning */
2010 (void **)&((*ximg)->data), NULL, 0);
2012 /* Realize display palette and garbage all frames. */
2013 release_frame_dc (f, hdc);
2015 if (*pixmap == NULL)
2017 DWORD err = GetLastError ();
2018 Lisp_Object errcode;
2019 /* All system errors are < 10000, so the following is safe. */
2020 XSETINT (errcode, err);
2021 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2022 x_destroy_x_image (*ximg);
2023 return 0;
2026 return 1;
2028 #endif /* HAVE_NTGUI */
2030 #ifdef HAVE_NS
2031 *pixmap = ns_image_for_XPM (width, height, depth);
2032 if (*pixmap == 0)
2034 *ximg = NULL;
2035 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2036 return 0;
2038 *ximg = *pixmap;
2039 return 1;
2040 #endif
2044 /* Destroy XImage XIMG. Free XIMG->data. */
2046 static void
2047 x_destroy_x_image (XImagePtr ximg)
2049 eassert (input_blocked_p ());
2050 if (ximg)
2052 #ifdef HAVE_X_WINDOWS
2053 xfree (ximg->data);
2054 ximg->data = NULL;
2055 XDestroyImage (ximg);
2056 #endif /* HAVE_X_WINDOWS */
2057 #ifdef HAVE_NTGUI
2058 /* Data will be freed by DestroyObject. */
2059 ximg->data = NULL;
2060 xfree (ximg);
2061 #endif /* HAVE_NTGUI */
2062 #ifdef HAVE_NS
2063 ns_release_object (ximg);
2064 #endif /* HAVE_NS */
2069 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2070 are width and height of both the image and pixmap. */
2072 static void
2073 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2075 #ifdef HAVE_X_WINDOWS
2076 GC gc;
2078 eassert (input_blocked_p ());
2079 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2080 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2081 XFreeGC (FRAME_X_DISPLAY (f), gc);
2082 #endif /* HAVE_X_WINDOWS */
2084 #ifdef HAVE_NTGUI
2085 #if 0 /* I don't think this is necessary looking at where it is used. */
2086 HDC hdc = get_frame_dc (f);
2087 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2088 release_frame_dc (f, hdc);
2089 #endif
2090 #endif /* HAVE_NTGUI */
2092 #ifdef HAVE_NS
2093 eassert (ximg == pixmap);
2094 ns_retain_object (ximg);
2095 #endif
2098 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2099 with image_put_x_image. */
2101 static bool
2102 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2103 int width, int height, int depth,
2104 XImagePtr *ximg, bool mask_p)
2106 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2108 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2109 !mask_p ? &img->pixmap : &img->mask);
2112 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2113 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2114 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2115 On the other platforms, it puts XIMG into the pixmap, then frees
2116 the X image and its buffer. */
2118 static void
2119 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2120 bool mask_p)
2122 #ifdef HAVE_X_WINDOWS
2123 if (!mask_p)
2125 eassert (img->ximg == NULL);
2126 img->ximg = ximg;
2128 else
2130 eassert (img->mask_img == NULL);
2131 img->mask_img = ximg;
2133 #else
2134 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2135 img->width, img->height);
2136 x_destroy_x_image (ximg);
2137 #endif
2140 #ifdef HAVE_X_WINDOWS
2141 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2142 the X images and their buffers. */
2144 static void
2145 image_sync_to_pixmaps (struct frame *f, struct image *img)
2147 if (img->ximg)
2149 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2150 x_destroy_x_image (img->ximg);
2151 img->ximg = NULL;
2153 if (img->mask_img)
2155 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2156 x_destroy_x_image (img->mask_img);
2157 img->mask_img = NULL;
2160 #endif
2162 #ifdef HAVE_NTGUI
2163 /* Create a memory device context for IMG on frame F. It stores the
2164 currently selected GDI object into *PREV for future restoration by
2165 image_unget_x_image_or_dc. */
2167 static XImagePtr_or_DC
2168 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2169 HGDIOBJ *prev)
2171 HDC frame_dc = get_frame_dc (f);
2172 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2174 release_frame_dc (f, frame_dc);
2175 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2177 return ximg;
2180 static void
2181 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2182 XImagePtr_or_DC ximg, HGDIOBJ prev)
2184 SelectObject (ximg, prev);
2185 DeleteDC (ximg);
2187 #else /* !HAVE_NTGUI */
2188 /* Get the X image for IMG on frame F. The resulting X image data
2189 should be treated as read-only at least on X. */
2191 static XImagePtr
2192 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2194 #ifdef HAVE_X_WINDOWS
2195 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2197 if (ximg_in_img)
2198 return ximg_in_img;
2199 else
2200 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2201 0, 0, img->width, img->height, ~0, ZPixmap);
2202 #elif defined (HAVE_NS)
2203 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2205 ns_retain_object (pixmap);
2206 return pixmap;
2207 #endif
2210 static void
2211 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2213 #ifdef HAVE_X_WINDOWS
2214 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2216 if (ximg_in_img)
2217 eassert (ximg == ximg_in_img);
2218 else
2219 XDestroyImage (ximg);
2220 #elif defined (HAVE_NS)
2221 ns_release_object (ximg);
2222 #endif
2224 #endif /* !HAVE_NTGUI */
2227 /***********************************************************************
2228 File Handling
2229 ***********************************************************************/
2231 /* Find image file FILE. Look in data-directory/images, then
2232 x-bitmap-file-path. Value is the encoded full name of the file
2233 found, or nil if not found. */
2235 Lisp_Object
2236 x_find_image_file (Lisp_Object file)
2238 Lisp_Object file_found, search_path;
2239 int fd;
2241 /* TODO I think this should use something like image-load-path
2242 instead. Unfortunately, that can contain non-string elements. */
2243 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2244 Vdata_directory),
2245 Vx_bitmap_file_path);
2247 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2248 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2250 if (fd == -1)
2251 file_found = Qnil;
2252 else
2254 file_found = ENCODE_FILE (file_found);
2255 if (fd != -2)
2256 emacs_close (fd);
2259 return file_found;
2263 /* Read FILE into memory. Value is a pointer to a buffer allocated
2264 with xmalloc holding FILE's contents. Value is null if an error
2265 occurred. *SIZE is set to the size of the file. */
2267 static unsigned char *
2268 slurp_file (char *file, ptrdiff_t *size)
2270 FILE *fp = emacs_fopen (file, "rb");
2271 unsigned char *buf = NULL;
2272 struct stat st;
2274 if (fp)
2276 ptrdiff_t count = SPECPDL_INDEX ();
2277 record_unwind_protect_ptr (fclose_unwind, fp);
2279 if (fstat (fileno (fp), &st) == 0
2280 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2282 /* Report an error if we read past the purported EOF.
2283 This can happen if the file grows as we read it. */
2284 ptrdiff_t buflen = st.st_size;
2285 buf = xmalloc (buflen + 1);
2286 if (fread (buf, 1, buflen + 1, fp) == buflen)
2287 *size = buflen;
2288 else
2290 xfree (buf);
2291 buf = NULL;
2295 unbind_to (count, Qnil);
2298 return buf;
2303 /***********************************************************************
2304 XBM images
2305 ***********************************************************************/
2307 static bool xbm_load (struct frame *f, struct image *img);
2308 static bool xbm_image_p (Lisp_Object object);
2309 static bool xbm_file_p (Lisp_Object);
2312 /* Indices of image specification fields in xbm_format, below. */
2314 enum xbm_keyword_index
2316 XBM_TYPE,
2317 XBM_FILE,
2318 XBM_WIDTH,
2319 XBM_HEIGHT,
2320 XBM_DATA,
2321 XBM_FOREGROUND,
2322 XBM_BACKGROUND,
2323 XBM_ASCENT,
2324 XBM_MARGIN,
2325 XBM_RELIEF,
2326 XBM_ALGORITHM,
2327 XBM_HEURISTIC_MASK,
2328 XBM_MASK,
2329 XBM_LAST
2332 /* Vector of image_keyword structures describing the format
2333 of valid XBM image specifications. */
2335 static const struct image_keyword xbm_format[XBM_LAST] =
2337 {":type", IMAGE_SYMBOL_VALUE, 1},
2338 {":file", IMAGE_STRING_VALUE, 0},
2339 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2340 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2341 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2342 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2343 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2344 {":ascent", IMAGE_ASCENT_VALUE, 0},
2345 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2346 {":relief", IMAGE_INTEGER_VALUE, 0},
2347 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2348 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2349 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2352 /* Structure describing the image type XBM. */
2354 static struct image_type xbm_type =
2356 &Qxbm,
2357 xbm_image_p,
2358 xbm_load,
2359 x_clear_image,
2360 NULL,
2361 NULL
2364 /* Tokens returned from xbm_scan. */
2366 enum xbm_token
2368 XBM_TK_IDENT = 256,
2369 XBM_TK_NUMBER
2373 /* Return true if OBJECT is a valid XBM-type image specification.
2374 A valid specification is a list starting with the symbol `image'
2375 The rest of the list is a property list which must contain an
2376 entry `:type xbm'.
2378 If the specification specifies a file to load, it must contain
2379 an entry `:file FILENAME' where FILENAME is a string.
2381 If the specification is for a bitmap loaded from memory it must
2382 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2383 WIDTH and HEIGHT are integers > 0. DATA may be:
2385 1. a string large enough to hold the bitmap data, i.e. it must
2386 have a size >= (WIDTH + 7) / 8 * HEIGHT
2388 2. a bool-vector of size >= WIDTH * HEIGHT
2390 3. a vector of strings or bool-vectors, one for each line of the
2391 bitmap.
2393 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2394 may not be specified in this case because they are defined in the
2395 XBM file.
2397 Both the file and data forms may contain the additional entries
2398 `:background COLOR' and `:foreground COLOR'. If not present,
2399 foreground and background of the frame on which the image is
2400 displayed is used. */
2402 static bool
2403 xbm_image_p (Lisp_Object object)
2405 struct image_keyword kw[XBM_LAST];
2407 memcpy (kw, xbm_format, sizeof kw);
2408 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2409 return 0;
2411 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2413 if (kw[XBM_FILE].count)
2415 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2416 return 0;
2418 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2420 /* In-memory XBM file. */
2421 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2422 return 0;
2424 else
2426 Lisp_Object data;
2427 int width, height;
2429 /* Entries for `:width', `:height' and `:data' must be present. */
2430 if (!kw[XBM_WIDTH].count
2431 || !kw[XBM_HEIGHT].count
2432 || !kw[XBM_DATA].count)
2433 return 0;
2435 data = kw[XBM_DATA].value;
2436 width = XFASTINT (kw[XBM_WIDTH].value);
2437 height = XFASTINT (kw[XBM_HEIGHT].value);
2439 /* Check type of data, and width and height against contents of
2440 data. */
2441 if (VECTORP (data))
2443 EMACS_INT i;
2445 /* Number of elements of the vector must be >= height. */
2446 if (ASIZE (data) < height)
2447 return 0;
2449 /* Each string or bool-vector in data must be large enough
2450 for one line of the image. */
2451 for (i = 0; i < height; ++i)
2453 Lisp_Object elt = AREF (data, i);
2455 if (STRINGP (elt))
2457 if (SCHARS (elt)
2458 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2459 return 0;
2461 else if (BOOL_VECTOR_P (elt))
2463 if (XBOOL_VECTOR (elt)->size < width)
2464 return 0;
2466 else
2467 return 0;
2470 else if (STRINGP (data))
2472 if (SCHARS (data)
2473 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2474 return 0;
2476 else if (BOOL_VECTOR_P (data))
2478 if (XBOOL_VECTOR (data)->size / height < width)
2479 return 0;
2481 else
2482 return 0;
2485 return 1;
2489 /* Scan a bitmap file. FP is the stream to read from. Value is
2490 either an enumerator from enum xbm_token, or a character for a
2491 single-character token, or 0 at end of file. If scanning an
2492 identifier, store the lexeme of the identifier in SVAL. If
2493 scanning a number, store its value in *IVAL. */
2495 static int
2496 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2498 unsigned int c;
2500 loop:
2502 /* Skip white space. */
2503 while (*s < end && (c = *(*s)++, c_isspace (c)))
2506 if (*s >= end)
2507 c = 0;
2508 else if (c_isdigit (c))
2510 int value = 0, digit;
2512 if (c == '0' && *s < end)
2514 c = *(*s)++;
2515 if (c == 'x' || c == 'X')
2517 while (*s < end)
2519 c = *(*s)++;
2520 if (c_isdigit (c))
2521 digit = c - '0';
2522 else if (c >= 'a' && c <= 'f')
2523 digit = c - 'a' + 10;
2524 else if (c >= 'A' && c <= 'F')
2525 digit = c - 'A' + 10;
2526 else
2527 break;
2528 value = 16 * value + digit;
2531 else if (c_isdigit (c))
2533 value = c - '0';
2534 while (*s < end
2535 && (c = *(*s)++, c_isdigit (c)))
2536 value = 8 * value + c - '0';
2539 else
2541 value = c - '0';
2542 while (*s < end
2543 && (c = *(*s)++, c_isdigit (c)))
2544 value = 10 * value + c - '0';
2547 if (*s < end)
2548 *s = *s - 1;
2549 *ival = value;
2550 c = XBM_TK_NUMBER;
2552 else if (c_isalpha (c) || c == '_')
2554 *sval++ = c;
2555 while (*s < end
2556 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2557 *sval++ = c;
2558 *sval = 0;
2559 if (*s < end)
2560 *s = *s - 1;
2561 c = XBM_TK_IDENT;
2563 else if (c == '/' && **s == '*')
2565 /* C-style comment. */
2566 ++*s;
2567 while (**s && (**s != '*' || *(*s + 1) != '/'))
2568 ++*s;
2569 if (**s)
2571 *s += 2;
2572 goto loop;
2576 return c;
2579 #ifdef HAVE_NTGUI
2581 /* Create a Windows bitmap from X bitmap data. */
2582 static HBITMAP
2583 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2585 static unsigned char swap_nibble[16]
2586 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2587 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2588 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2589 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2590 int i, j, w1, w2;
2591 unsigned char *bits, *p;
2592 HBITMAP bmp;
2594 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2595 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2596 bits = alloca (height * w2);
2597 memset (bits, 0, height * w2);
2598 for (i = 0; i < height; i++)
2600 p = bits + i*w2;
2601 for (j = 0; j < w1; j++)
2603 /* Bitswap XBM bytes to match how Windows does things. */
2604 unsigned char c = *data++;
2605 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2606 | (swap_nibble[(c>>4) & 0xf]));
2609 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2611 return bmp;
2614 static void
2615 convert_mono_to_color_image (struct frame *f, struct image *img,
2616 COLORREF foreground, COLORREF background)
2618 HDC hdc, old_img_dc, new_img_dc;
2619 HGDIOBJ old_prev, new_prev;
2620 HBITMAP new_pixmap;
2622 hdc = get_frame_dc (f);
2623 old_img_dc = CreateCompatibleDC (hdc);
2624 new_img_dc = CreateCompatibleDC (hdc);
2625 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2626 release_frame_dc (f, hdc);
2627 old_prev = SelectObject (old_img_dc, img->pixmap);
2628 new_prev = SelectObject (new_img_dc, new_pixmap);
2629 /* Windows convention for mono bitmaps is black = background,
2630 white = foreground. */
2631 SetTextColor (new_img_dc, background);
2632 SetBkColor (new_img_dc, foreground);
2634 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2635 0, 0, SRCCOPY);
2637 SelectObject (old_img_dc, old_prev);
2638 SelectObject (new_img_dc, new_prev);
2639 DeleteDC (old_img_dc);
2640 DeleteDC (new_img_dc);
2641 DeleteObject (img->pixmap);
2642 if (new_pixmap == 0)
2643 fprintf (stderr, "Failed to convert image to color.\n");
2644 else
2645 img->pixmap = new_pixmap;
2648 #define XBM_BIT_SHUFFLE(b) (~(b))
2650 #else
2652 #define XBM_BIT_SHUFFLE(b) (b)
2654 #endif /* HAVE_NTGUI */
2657 static void
2658 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2659 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2660 bool non_default_colors)
2662 #ifdef HAVE_NTGUI
2663 img->pixmap
2664 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2666 /* If colors were specified, transfer the bitmap to a color one. */
2667 if (non_default_colors)
2668 convert_mono_to_color_image (f, img, fg, bg);
2670 #elif defined (HAVE_NS)
2671 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2673 #else
2674 img->pixmap =
2675 (x_check_image_size (0, img->width, img->height)
2676 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2677 FRAME_X_WINDOW (f),
2678 data,
2679 img->width, img->height,
2680 fg, bg,
2681 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2682 : NO_PIXMAP);
2683 #endif /* !HAVE_NTGUI && !HAVE_NS */
2688 /* Replacement for XReadBitmapFileData which isn't available under old
2689 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2690 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2691 the image. Return in *DATA the bitmap data allocated with xmalloc.
2692 Value is true if successful. DATA null means just test if
2693 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2694 inhibit the call to image_error when the image size is invalid (the
2695 bitmap remains unread). */
2697 static bool
2698 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2699 int *width, int *height, char **data,
2700 bool inhibit_image_error)
2702 unsigned char *s = contents;
2703 char buffer[BUFSIZ];
2704 bool padding_p = 0;
2705 bool v10 = 0;
2706 int bytes_per_line, i, nbytes;
2707 char *p;
2708 int value;
2709 int LA1;
2711 #define match() \
2712 LA1 = xbm_scan (&s, end, buffer, &value)
2714 #define expect(TOKEN) \
2715 do \
2717 if (LA1 != (TOKEN)) \
2718 goto failure; \
2719 match (); \
2721 while (0)
2723 #define expect_ident(IDENT) \
2724 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2725 match (); \
2726 else \
2727 goto failure
2729 *width = *height = -1;
2730 if (data)
2731 *data = NULL;
2732 LA1 = xbm_scan (&s, end, buffer, &value);
2734 /* Parse defines for width, height and hot-spots. */
2735 while (LA1 == '#')
2737 match ();
2738 expect_ident ("define");
2739 expect (XBM_TK_IDENT);
2741 if (LA1 == XBM_TK_NUMBER)
2743 char *q = strrchr (buffer, '_');
2744 q = q ? q + 1 : buffer;
2745 if (strcmp (q, "width") == 0)
2746 *width = value;
2747 else if (strcmp (q, "height") == 0)
2748 *height = value;
2750 expect (XBM_TK_NUMBER);
2753 if (!check_image_size (f, *width, *height))
2755 if (!inhibit_image_error)
2756 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2757 goto failure;
2759 else if (data == NULL)
2760 goto success;
2762 /* Parse bits. Must start with `static'. */
2763 expect_ident ("static");
2764 if (LA1 == XBM_TK_IDENT)
2766 if (strcmp (buffer, "unsigned") == 0)
2768 match ();
2769 expect_ident ("char");
2771 else if (strcmp (buffer, "short") == 0)
2773 match ();
2774 v10 = 1;
2775 if (*width % 16 && *width % 16 < 9)
2776 padding_p = 1;
2778 else if (strcmp (buffer, "char") == 0)
2779 match ();
2780 else
2781 goto failure;
2783 else
2784 goto failure;
2786 expect (XBM_TK_IDENT);
2787 expect ('[');
2788 expect (']');
2789 expect ('=');
2790 expect ('{');
2792 if (! x_check_image_size (0, *width, *height))
2794 if (!inhibit_image_error)
2795 image_error ("Image too large (%dx%d)",
2796 make_number (*width), make_number (*height));
2797 goto failure;
2799 bytes_per_line = (*width + 7) / 8 + padding_p;
2800 nbytes = bytes_per_line * *height;
2801 p = *data = xmalloc (nbytes);
2803 if (v10)
2805 for (i = 0; i < nbytes; i += 2)
2807 int val = value;
2808 expect (XBM_TK_NUMBER);
2810 *p++ = XBM_BIT_SHUFFLE (val);
2811 if (!padding_p || ((i + 2) % bytes_per_line))
2812 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2814 if (LA1 == ',' || LA1 == '}')
2815 match ();
2816 else
2817 goto failure;
2820 else
2822 for (i = 0; i < nbytes; ++i)
2824 int val = value;
2825 expect (XBM_TK_NUMBER);
2827 *p++ = XBM_BIT_SHUFFLE (val);
2829 if (LA1 == ',' || LA1 == '}')
2830 match ();
2831 else
2832 goto failure;
2836 success:
2837 return 1;
2839 failure:
2841 if (data && *data)
2843 xfree (*data);
2844 *data = NULL;
2846 return 0;
2848 #undef match
2849 #undef expect
2850 #undef expect_ident
2854 /* Load XBM image IMG which will be displayed on frame F from buffer
2855 CONTENTS. END is the end of the buffer. Value is true if
2856 successful. */
2858 static bool
2859 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2860 unsigned char *end)
2862 bool rc;
2863 char *data;
2864 bool success_p = 0;
2866 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2867 &data, 0);
2868 if (rc)
2870 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2871 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2872 bool non_default_colors = 0;
2873 Lisp_Object value;
2875 eassert (img->width > 0 && img->height > 0);
2877 /* Get foreground and background colors, maybe allocate colors. */
2878 value = image_spec_value (img->spec, QCforeground, NULL);
2879 if (!NILP (value))
2881 foreground = x_alloc_image_color (f, img, value, foreground);
2882 non_default_colors = 1;
2884 value = image_spec_value (img->spec, QCbackground, NULL);
2885 if (!NILP (value))
2887 background = x_alloc_image_color (f, img, value, background);
2888 img->background = background;
2889 img->background_valid = 1;
2890 non_default_colors = 1;
2893 Create_Pixmap_From_Bitmap_Data (f, img, data,
2894 foreground, background,
2895 non_default_colors);
2896 xfree (data);
2898 if (img->pixmap == NO_PIXMAP)
2900 x_clear_image (f, img);
2901 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2903 else
2904 success_p = 1;
2906 else
2907 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2909 return success_p;
2913 /* Value is true if DATA looks like an in-memory XBM file. */
2915 static bool
2916 xbm_file_p (Lisp_Object data)
2918 int w, h;
2919 return (STRINGP (data)
2920 && xbm_read_bitmap_data (NULL, SDATA (data),
2921 (SDATA (data) + SBYTES (data)),
2922 &w, &h, NULL, 1));
2926 /* Fill image IMG which is used on frame F with pixmap data. Value is
2927 true if successful. */
2929 static bool
2930 xbm_load (struct frame *f, struct image *img)
2932 bool success_p = 0;
2933 Lisp_Object file_name;
2935 eassert (xbm_image_p (img->spec));
2937 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2938 file_name = image_spec_value (img->spec, QCfile, NULL);
2939 if (STRINGP (file_name))
2941 Lisp_Object file;
2942 unsigned char *contents;
2943 ptrdiff_t size;
2945 file = x_find_image_file (file_name);
2946 if (!STRINGP (file))
2948 image_error ("Cannot find image file `%s'", file_name, Qnil);
2949 return 0;
2952 contents = slurp_file (SSDATA (file), &size);
2953 if (contents == NULL)
2955 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2956 return 0;
2959 success_p = xbm_load_image (f, img, contents, contents + size);
2960 xfree (contents);
2962 else
2964 struct image_keyword fmt[XBM_LAST];
2965 Lisp_Object data;
2966 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2967 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2968 bool non_default_colors = 0;
2969 char *bits;
2970 bool parsed_p;
2971 bool in_memory_file_p = 0;
2973 /* See if data looks like an in-memory XBM file. */
2974 data = image_spec_value (img->spec, QCdata, NULL);
2975 in_memory_file_p = xbm_file_p (data);
2977 /* Parse the image specification. */
2978 memcpy (fmt, xbm_format, sizeof fmt);
2979 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2980 eassert (parsed_p);
2982 /* Get specified width, and height. */
2983 if (!in_memory_file_p)
2985 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2986 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2987 eassert (img->width > 0 && img->height > 0);
2988 if (!check_image_size (f, img->width, img->height))
2990 image_error ("Invalid image size (see `max-image-size')",
2991 Qnil, Qnil);
2992 return 0;
2996 /* Get foreground and background colors, maybe allocate colors. */
2997 if (fmt[XBM_FOREGROUND].count
2998 && STRINGP (fmt[XBM_FOREGROUND].value))
3000 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3001 foreground);
3002 non_default_colors = 1;
3005 if (fmt[XBM_BACKGROUND].count
3006 && STRINGP (fmt[XBM_BACKGROUND].value))
3008 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3009 background);
3010 non_default_colors = 1;
3013 if (in_memory_file_p)
3014 success_p = xbm_load_image (f, img, SDATA (data),
3015 (SDATA (data)
3016 + SBYTES (data)));
3017 else
3019 if (VECTORP (data))
3021 int i;
3022 char *p;
3023 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3025 p = bits = alloca (nbytes * img->height);
3026 for (i = 0; i < img->height; ++i, p += nbytes)
3028 Lisp_Object line = AREF (data, i);
3029 if (STRINGP (line))
3030 memcpy (p, SDATA (line), nbytes);
3031 else
3032 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
3035 else if (STRINGP (data))
3036 bits = SSDATA (data);
3037 else
3038 bits = (char *) XBOOL_VECTOR (data)->data;
3040 #ifdef HAVE_NTGUI
3042 char *invertedBits;
3043 int nbytes, i;
3044 /* Windows mono bitmaps are reversed compared with X. */
3045 invertedBits = bits;
3046 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
3047 * img->height;
3048 bits = alloca (nbytes);
3049 for (i = 0; i < nbytes; i++)
3050 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3052 #endif
3053 /* Create the pixmap. */
3055 if (x_check_image_size (0, img->width, img->height))
3056 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3057 foreground, background,
3058 non_default_colors);
3059 else
3060 img->pixmap = NO_PIXMAP;
3062 if (img->pixmap)
3063 success_p = 1;
3064 else
3066 image_error ("Unable to create pixmap for XBM image `%s'",
3067 img->spec, Qnil);
3068 x_clear_image (f, img);
3073 return success_p;
3078 /***********************************************************************
3079 XPM images
3080 ***********************************************************************/
3082 #if defined (HAVE_XPM) || defined (HAVE_NS)
3084 static bool xpm_image_p (Lisp_Object object);
3085 static bool xpm_load (struct frame *f, struct image *img);
3087 #endif /* HAVE_XPM || HAVE_NS */
3089 #ifdef HAVE_XPM
3090 #ifdef HAVE_NTGUI
3091 /* Indicate to xpm.h that we don't have Xlib. */
3092 #define FOR_MSW
3093 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3094 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3095 #define XColor xpm_XColor
3096 #define XImage xpm_XImage
3097 #define Display xpm_Display
3098 #define PIXEL_ALREADY_TYPEDEFED
3099 #include "X11/xpm.h"
3100 #undef FOR_MSW
3101 #undef XColor
3102 #undef XImage
3103 #undef Display
3104 #undef PIXEL_ALREADY_TYPEDEFED
3105 #else
3106 #include "X11/xpm.h"
3107 #endif /* HAVE_NTGUI */
3108 #endif /* HAVE_XPM */
3110 #if defined (HAVE_XPM) || defined (HAVE_NS)
3111 /* The symbol `xpm' identifying XPM-format images. */
3113 static Lisp_Object Qxpm;
3115 /* Indices of image specification fields in xpm_format, below. */
3117 enum xpm_keyword_index
3119 XPM_TYPE,
3120 XPM_FILE,
3121 XPM_DATA,
3122 XPM_ASCENT,
3123 XPM_MARGIN,
3124 XPM_RELIEF,
3125 XPM_ALGORITHM,
3126 XPM_HEURISTIC_MASK,
3127 XPM_MASK,
3128 XPM_COLOR_SYMBOLS,
3129 XPM_BACKGROUND,
3130 XPM_LAST
3133 /* Vector of image_keyword structures describing the format
3134 of valid XPM image specifications. */
3136 static const struct image_keyword xpm_format[XPM_LAST] =
3138 {":type", IMAGE_SYMBOL_VALUE, 1},
3139 {":file", IMAGE_STRING_VALUE, 0},
3140 {":data", IMAGE_STRING_VALUE, 0},
3141 {":ascent", IMAGE_ASCENT_VALUE, 0},
3142 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3143 {":relief", IMAGE_INTEGER_VALUE, 0},
3144 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3145 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3146 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3147 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3148 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3151 #if defined HAVE_NTGUI && defined WINDOWSNT
3152 static bool init_xpm_functions (void);
3153 #else
3154 #define init_xpm_functions NULL
3155 #endif
3157 /* Structure describing the image type XPM. */
3159 static struct image_type xpm_type =
3161 &Qxpm,
3162 xpm_image_p,
3163 xpm_load,
3164 x_clear_image,
3165 init_xpm_functions,
3166 NULL
3169 #ifdef HAVE_X_WINDOWS
3171 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3172 functions for allocating image colors. Our own functions handle
3173 color allocation failures more gracefully than the ones on the XPM
3174 lib. */
3176 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3177 #define ALLOC_XPM_COLORS
3178 #endif
3179 #endif /* HAVE_X_WINDOWS */
3181 #ifdef ALLOC_XPM_COLORS
3183 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3184 XColor *, int);
3186 /* An entry in a hash table used to cache color definitions of named
3187 colors. This cache is necessary to speed up XPM image loading in
3188 case we do color allocations ourselves. Without it, we would need
3189 a call to XParseColor per pixel in the image. */
3191 struct xpm_cached_color
3193 /* Next in collision chain. */
3194 struct xpm_cached_color *next;
3196 /* Color definition (RGB and pixel color). */
3197 XColor color;
3199 /* Color name. */
3200 char name[FLEXIBLE_ARRAY_MEMBER];
3203 /* The hash table used for the color cache, and its bucket vector
3204 size. */
3206 #define XPM_COLOR_CACHE_BUCKETS 1001
3207 static struct xpm_cached_color **xpm_color_cache;
3209 /* Initialize the color cache. */
3211 static void
3212 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3214 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3215 xpm_color_cache = xzalloc (nbytes);
3216 init_color_table ();
3218 if (attrs->valuemask & XpmColorSymbols)
3220 int i;
3221 XColor color;
3223 for (i = 0; i < attrs->numsymbols; ++i)
3224 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3225 attrs->colorsymbols[i].value, &color))
3227 color.pixel = lookup_rgb_color (f, color.red, color.green,
3228 color.blue);
3229 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3234 /* Free the color cache. */
3236 static void
3237 xpm_free_color_cache (void)
3239 struct xpm_cached_color *p, *next;
3240 int i;
3242 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3243 for (p = xpm_color_cache[i]; p; p = next)
3245 next = p->next;
3246 xfree (p);
3249 xfree (xpm_color_cache);
3250 xpm_color_cache = NULL;
3251 free_color_table ();
3254 /* Return the bucket index for color named COLOR_NAME in the color
3255 cache. */
3257 static int
3258 xpm_color_bucket (char *color_name)
3260 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3261 return hash % XPM_COLOR_CACHE_BUCKETS;
3265 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3266 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3267 entry added. */
3269 static struct xpm_cached_color *
3270 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3272 size_t nbytes;
3273 struct xpm_cached_color *p;
3275 if (bucket < 0)
3276 bucket = xpm_color_bucket (color_name);
3278 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3279 p = xmalloc (nbytes);
3280 strcpy (p->name, color_name);
3281 p->color = *color;
3282 p->next = xpm_color_cache[bucket];
3283 xpm_color_cache[bucket] = p;
3284 return p;
3287 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3288 return the cached definition in *COLOR. Otherwise, make a new
3289 entry in the cache and allocate the color. Value is false if color
3290 allocation failed. */
3292 static bool
3293 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3295 struct xpm_cached_color *p;
3296 int h = xpm_color_bucket (color_name);
3298 for (p = xpm_color_cache[h]; p; p = p->next)
3299 if (strcmp (p->name, color_name) == 0)
3300 break;
3302 if (p != NULL)
3303 *color = p->color;
3304 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3305 color_name, color))
3307 color->pixel = lookup_rgb_color (f, color->red, color->green,
3308 color->blue);
3309 p = xpm_cache_color (f, color_name, color, h);
3311 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3312 with transparency, and it's useful. */
3313 else if (strcmp ("opaque", color_name) == 0)
3315 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3316 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3317 p = xpm_cache_color (f, color_name, color, h);
3320 return p != NULL;
3324 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3325 CLOSURE is a pointer to the frame on which we allocate the
3326 color. Return in *COLOR the allocated color. Value is non-zero
3327 if successful. */
3329 static int
3330 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3331 void *closure)
3333 return xpm_lookup_color (closure, color_name, color);
3337 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3338 is a pointer to the frame on which we allocate the color. Value is
3339 non-zero if successful. */
3341 static int
3342 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3344 return 1;
3347 #endif /* ALLOC_XPM_COLORS */
3350 #ifdef WINDOWSNT
3352 /* XPM library details. */
3354 DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
3355 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3356 xpm_XImage **, XpmAttributes *));
3357 DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3358 xpm_XImage **, XpmAttributes *));
3359 DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
3361 static bool
3362 init_xpm_functions (void)
3364 HMODULE library;
3366 if (!(library = w32_delayed_load (Qxpm)))
3367 return 0;
3369 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3370 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3371 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3372 LOAD_IMGLIB_FN (library, XImageFree);
3373 return 1;
3376 #endif /* WINDOWSNT */
3378 #if defined HAVE_NTGUI && !defined WINDOWSNT
3379 /* Glue for code below */
3380 #define fn_XpmReadFileToImage XpmReadFileToImage
3381 #define fn_XpmCreateImageFromBuffer XpmCreateImageFromBuffer
3382 #define fn_XImageFree XImageFree
3383 #define fn_XpmFreeAttributes XpmFreeAttributes
3384 #endif /* HAVE_NTGUI && !WINDOWSNT */
3386 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3387 for XPM images. Such a list must consist of conses whose car and
3388 cdr are strings. */
3390 static bool
3391 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3393 while (CONSP (color_symbols))
3395 Lisp_Object sym = XCAR (color_symbols);
3396 if (!CONSP (sym)
3397 || !STRINGP (XCAR (sym))
3398 || !STRINGP (XCDR (sym)))
3399 break;
3400 color_symbols = XCDR (color_symbols);
3403 return NILP (color_symbols);
3407 /* Value is true if OBJECT is a valid XPM image specification. */
3409 static bool
3410 xpm_image_p (Lisp_Object object)
3412 struct image_keyword fmt[XPM_LAST];
3413 memcpy (fmt, xpm_format, sizeof fmt);
3414 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3415 /* Either `:file' or `:data' must be present. */
3416 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3417 /* Either no `:color-symbols' or it's a list of conses
3418 whose car and cdr are strings. */
3419 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3420 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3423 #endif /* HAVE_XPM || HAVE_NS */
3425 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3426 ptrdiff_t
3427 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3429 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3430 ptrdiff_t id;
3431 int rc;
3432 XpmAttributes attrs;
3433 Pixmap bitmap, mask;
3435 memset (&attrs, 0, sizeof attrs);
3437 attrs.visual = FRAME_X_VISUAL (f);
3438 attrs.colormap = FRAME_X_COLORMAP (f);
3439 attrs.valuemask |= XpmVisual;
3440 attrs.valuemask |= XpmColormap;
3442 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3443 (char **) bits, &bitmap, &mask, &attrs);
3444 if (rc != XpmSuccess)
3446 XpmFreeAttributes (&attrs);
3447 return -1;
3450 id = x_allocate_bitmap_record (f);
3451 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3452 dpyinfo->bitmaps[id - 1].have_mask = 1;
3453 dpyinfo->bitmaps[id - 1].mask = mask;
3454 dpyinfo->bitmaps[id - 1].file = NULL;
3455 dpyinfo->bitmaps[id - 1].height = attrs.height;
3456 dpyinfo->bitmaps[id - 1].width = attrs.width;
3457 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3458 dpyinfo->bitmaps[id - 1].refcount = 1;
3460 XpmFreeAttributes (&attrs);
3461 return id;
3463 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3465 /* Load image IMG which will be displayed on frame F. Value is
3466 true if successful. */
3468 #ifdef HAVE_XPM
3470 static bool
3471 xpm_load (struct frame *f, struct image *img)
3473 int rc;
3474 XpmAttributes attrs;
3475 Lisp_Object specified_file, color_symbols;
3476 #ifdef HAVE_NTGUI
3477 HDC hdc;
3478 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3479 #endif /* HAVE_NTGUI */
3481 /* Configure the XPM lib. Use the visual of frame F. Allocate
3482 close colors. Return colors allocated. */
3483 memset (&attrs, 0, sizeof attrs);
3485 #ifndef HAVE_NTGUI
3486 attrs.visual = FRAME_X_VISUAL (f);
3487 attrs.colormap = FRAME_X_COLORMAP (f);
3488 attrs.valuemask |= XpmVisual;
3489 attrs.valuemask |= XpmColormap;
3490 #endif /* HAVE_NTGUI */
3492 #ifdef ALLOC_XPM_COLORS
3493 /* Allocate colors with our own functions which handle
3494 failing color allocation more gracefully. */
3495 attrs.color_closure = f;
3496 attrs.alloc_color = xpm_alloc_color;
3497 attrs.free_colors = xpm_free_colors;
3498 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3499 #else /* not ALLOC_XPM_COLORS */
3500 /* Let the XPM lib allocate colors. */
3501 attrs.valuemask |= XpmReturnAllocPixels;
3502 #ifdef XpmAllocCloseColors
3503 attrs.alloc_close_colors = 1;
3504 attrs.valuemask |= XpmAllocCloseColors;
3505 #else /* not XpmAllocCloseColors */
3506 attrs.closeness = 600;
3507 attrs.valuemask |= XpmCloseness;
3508 #endif /* not XpmAllocCloseColors */
3509 #endif /* ALLOC_XPM_COLORS */
3511 /* If image specification contains symbolic color definitions, add
3512 these to `attrs'. */
3513 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3514 if (CONSP (color_symbols))
3516 Lisp_Object tail;
3517 XpmColorSymbol *xpm_syms;
3518 int i, size;
3520 attrs.valuemask |= XpmColorSymbols;
3522 /* Count number of symbols. */
3523 attrs.numsymbols = 0;
3524 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3525 ++attrs.numsymbols;
3527 /* Allocate an XpmColorSymbol array. */
3528 size = attrs.numsymbols * sizeof *xpm_syms;
3529 xpm_syms = alloca (size);
3530 memset (xpm_syms, 0, size);
3531 attrs.colorsymbols = xpm_syms;
3533 /* Fill the color symbol array. */
3534 for (tail = color_symbols, i = 0;
3535 CONSP (tail);
3536 ++i, tail = XCDR (tail))
3538 Lisp_Object name;
3539 Lisp_Object color;
3540 char *empty_string = (char *) "";
3542 if (!CONSP (XCAR (tail)))
3544 xpm_syms[i].name = empty_string;
3545 xpm_syms[i].value = empty_string;
3546 continue;
3548 name = XCAR (XCAR (tail));
3549 color = XCDR (XCAR (tail));
3550 if (STRINGP (name))
3552 xpm_syms[i].name = alloca (SCHARS (name) + 1);
3553 strcpy (xpm_syms[i].name, SSDATA (name));
3555 else
3556 xpm_syms[i].name = empty_string;
3557 if (STRINGP (color))
3559 xpm_syms[i].value = alloca (SCHARS (color) + 1);
3560 strcpy (xpm_syms[i].value, SSDATA (color));
3562 else
3563 xpm_syms[i].value = empty_string;
3567 /* Create a pixmap for the image, either from a file, or from a
3568 string buffer containing data in the same format as an XPM file. */
3569 #ifdef ALLOC_XPM_COLORS
3570 xpm_init_color_cache (f, &attrs);
3571 #endif
3573 specified_file = image_spec_value (img->spec, QCfile, NULL);
3575 #ifdef HAVE_NTGUI
3577 HDC frame_dc = get_frame_dc (f);
3578 hdc = CreateCompatibleDC (frame_dc);
3579 release_frame_dc (f, frame_dc);
3581 #endif /* HAVE_NTGUI */
3583 if (STRINGP (specified_file))
3585 Lisp_Object file = x_find_image_file (specified_file);
3586 if (!STRINGP (file))
3588 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3589 #ifdef ALLOC_XPM_COLORS
3590 xpm_free_color_cache ();
3591 #endif
3592 return 0;
3595 #ifdef HAVE_NTGUI
3596 /* XpmReadFileToPixmap is not available in the Windows port of
3597 libxpm. But XpmReadFileToImage almost does what we want. */
3598 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3599 &xpm_image, &xpm_mask,
3600 &attrs);
3601 #else
3602 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3603 &img->ximg, &img->mask_img,
3604 &attrs);
3605 #endif /* HAVE_NTGUI */
3607 else
3609 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3610 if (!STRINGP (buffer))
3612 image_error ("Invalid image data `%s'", buffer, Qnil);
3613 #ifdef ALLOC_XPM_COLORS
3614 xpm_free_color_cache ();
3615 #endif
3616 return 0;
3618 #ifdef HAVE_NTGUI
3619 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3620 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3621 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3622 &xpm_image, &xpm_mask,
3623 &attrs);
3624 #else
3625 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3626 &img->ximg, &img->mask_img,
3627 &attrs);
3628 #endif /* HAVE_NTGUI */
3631 #ifdef HAVE_X_WINDOWS
3632 if (rc == XpmSuccess)
3634 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3635 img->ximg->width, img->ximg->height,
3636 img->ximg->depth);
3637 if (img->pixmap == NO_PIXMAP)
3639 x_clear_image (f, img);
3640 rc = XpmNoMemory;
3642 else if (img->mask_img)
3644 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3645 img->mask_img->width,
3646 img->mask_img->height,
3647 img->mask_img->depth);
3648 if (img->mask == NO_PIXMAP)
3650 x_clear_image (f, img);
3651 rc = XpmNoMemory;
3655 #endif
3657 if (rc == XpmSuccess)
3659 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3660 img->colors = colors_in_color_table (&img->ncolors);
3661 #else /* not ALLOC_XPM_COLORS */
3662 int i;
3664 #ifdef HAVE_NTGUI
3665 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3666 plus some duplicate attributes. */
3667 if (xpm_image && xpm_image->bitmap)
3669 img->pixmap = xpm_image->bitmap;
3670 /* XImageFree in libXpm frees XImage struct without destroying
3671 the bitmap, which is what we want. */
3672 fn_XImageFree (xpm_image);
3674 if (xpm_mask && xpm_mask->bitmap)
3676 /* The mask appears to be inverted compared with what we expect.
3677 TODO: invert our expectations. See other places where we
3678 have to invert bits because our idea of masks is backwards. */
3679 HGDIOBJ old_obj;
3680 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3682 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3683 SelectObject (hdc, old_obj);
3685 img->mask = xpm_mask->bitmap;
3686 fn_XImageFree (xpm_mask);
3687 DeleteDC (hdc);
3690 DeleteDC (hdc);
3691 #endif /* HAVE_NTGUI */
3693 /* Remember allocated colors. */
3694 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3695 img->ncolors = attrs.nalloc_pixels;
3696 for (i = 0; i < attrs.nalloc_pixels; ++i)
3698 img->colors[i] = attrs.alloc_pixels[i];
3699 #ifdef DEBUG_X_COLORS
3700 register_color (img->colors[i]);
3701 #endif
3703 #endif /* not ALLOC_XPM_COLORS */
3705 img->width = attrs.width;
3706 img->height = attrs.height;
3707 eassert (img->width > 0 && img->height > 0);
3709 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3710 #ifdef HAVE_NTGUI
3711 fn_XpmFreeAttributes (&attrs);
3712 #else
3713 XpmFreeAttributes (&attrs);
3714 #endif /* HAVE_NTGUI */
3716 #ifdef HAVE_X_WINDOWS
3717 /* Maybe fill in the background field while we have ximg handy. */
3718 IMAGE_BACKGROUND (img, f, img->ximg);
3719 if (img->mask_img)
3720 /* Fill in the background_transparent field while we have the
3721 mask handy. */
3722 image_background_transparent (img, f, img->mask_img);
3723 #endif
3725 else
3727 #ifdef HAVE_NTGUI
3728 DeleteDC (hdc);
3729 #endif /* HAVE_NTGUI */
3731 switch (rc)
3733 case XpmOpenFailed:
3734 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3735 break;
3737 case XpmFileInvalid:
3738 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3739 break;
3741 case XpmNoMemory:
3742 image_error ("Out of memory (%s)", img->spec, Qnil);
3743 break;
3745 case XpmColorFailed:
3746 image_error ("Color allocation error (%s)", img->spec, Qnil);
3747 break;
3749 default:
3750 image_error ("Unknown error (%s)", img->spec, Qnil);
3751 break;
3755 #ifdef ALLOC_XPM_COLORS
3756 xpm_free_color_cache ();
3757 #endif
3758 return rc == XpmSuccess;
3761 #endif /* HAVE_XPM */
3763 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3765 /* XPM support functions for NS where libxpm is not available.
3766 Only XPM version 3 (without any extensions) is supported. */
3768 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3769 int, Lisp_Object);
3770 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3771 const unsigned char *, int);
3772 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3773 int, Lisp_Object);
3774 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3775 const unsigned char *, int);
3777 /* Tokens returned from xpm_scan. */
3779 enum xpm_token
3781 XPM_TK_IDENT = 256,
3782 XPM_TK_STRING,
3783 XPM_TK_EOF
3786 /* Scan an XPM data and return a character (< 256) or a token defined
3787 by enum xpm_token above. *S and END are the start (inclusive) and
3788 the end (exclusive) addresses of the data, respectively. Advance
3789 *S while scanning. If token is either XPM_TK_IDENT or
3790 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3791 length of the corresponding token, respectively. */
3793 static int
3794 xpm_scan (const unsigned char **s,
3795 const unsigned char *end,
3796 const unsigned char **beg,
3797 ptrdiff_t *len)
3799 int c;
3801 while (*s < end)
3803 /* Skip white-space. */
3804 while (*s < end && (c = *(*s)++, c_isspace (c)))
3807 /* gnus-pointer.xpm uses '-' in its identifier.
3808 sb-dir-plus.xpm uses '+' in its identifier. */
3809 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3811 *beg = *s - 1;
3812 while (*s < end
3813 && (c = **s, c_isalnum (c)
3814 || c == '_' || c == '-' || c == '+'))
3815 ++*s;
3816 *len = *s - *beg;
3817 return XPM_TK_IDENT;
3819 else if (c == '"')
3821 *beg = *s;
3822 while (*s < end && **s != '"')
3823 ++*s;
3824 *len = *s - *beg;
3825 if (*s < end)
3826 ++*s;
3827 return XPM_TK_STRING;
3829 else if (c == '/')
3831 if (*s < end && **s == '*')
3833 /* C-style comment. */
3834 ++*s;
3837 while (*s < end && *(*s)++ != '*')
3840 while (*s < end && **s != '/');
3841 if (*s < end)
3842 ++*s;
3844 else
3845 return c;
3847 else
3848 return c;
3851 return XPM_TK_EOF;
3854 /* Functions for color table lookup in XPM data. A key is a string
3855 specifying the color of each pixel in XPM data. A value is either
3856 an integer that specifies a pixel color, Qt that specifies
3857 transparency, or Qnil for the unspecified color. If the length of
3858 the key string is one, a vector is used as a table. Otherwise, a
3859 hash table is used. */
3861 static Lisp_Object
3862 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3863 const unsigned char *,
3864 int,
3865 Lisp_Object),
3866 Lisp_Object (**get_func) (Lisp_Object,
3867 const unsigned char *,
3868 int))
3870 *put_func = xpm_put_color_table_v;
3871 *get_func = xpm_get_color_table_v;
3872 return Fmake_vector (make_number (256), Qnil);
3875 static void
3876 xpm_put_color_table_v (Lisp_Object color_table,
3877 const unsigned char *chars_start,
3878 int chars_len,
3879 Lisp_Object color)
3881 ASET (color_table, *chars_start, color);
3884 static Lisp_Object
3885 xpm_get_color_table_v (Lisp_Object color_table,
3886 const unsigned char *chars_start,
3887 int chars_len)
3889 return AREF (color_table, *chars_start);
3892 static Lisp_Object
3893 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3894 const unsigned char *,
3895 int,
3896 Lisp_Object),
3897 Lisp_Object (**get_func) (Lisp_Object,
3898 const unsigned char *,
3899 int))
3901 *put_func = xpm_put_color_table_h;
3902 *get_func = xpm_get_color_table_h;
3903 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
3904 make_float (DEFAULT_REHASH_SIZE),
3905 make_float (DEFAULT_REHASH_THRESHOLD),
3906 Qnil);
3909 static void
3910 xpm_put_color_table_h (Lisp_Object color_table,
3911 const unsigned char *chars_start,
3912 int chars_len,
3913 Lisp_Object color)
3915 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3916 EMACS_UINT hash_code;
3917 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3919 hash_lookup (table, chars, &hash_code);
3920 hash_put (table, chars, color, hash_code);
3923 static Lisp_Object
3924 xpm_get_color_table_h (Lisp_Object color_table,
3925 const unsigned char *chars_start,
3926 int chars_len)
3928 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3929 ptrdiff_t i =
3930 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
3932 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3935 enum xpm_color_key {
3936 XPM_COLOR_KEY_S,
3937 XPM_COLOR_KEY_M,
3938 XPM_COLOR_KEY_G4,
3939 XPM_COLOR_KEY_G,
3940 XPM_COLOR_KEY_C
3943 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3945 static int
3946 xpm_str_to_color_key (const char *s)
3948 int i;
3950 for (i = 0;
3951 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3952 i++)
3953 if (strcmp (xpm_color_key_strings[i], s) == 0)
3954 return i;
3955 return -1;
3958 static bool
3959 xpm_load_image (struct frame *f,
3960 struct image *img,
3961 const unsigned char *contents,
3962 const unsigned char *end)
3964 const unsigned char *s = contents, *beg, *str;
3965 unsigned char buffer[BUFSIZ];
3966 int width, height, x, y;
3967 int num_colors, chars_per_pixel;
3968 ptrdiff_t len;
3969 int LA1;
3970 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3971 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3972 Lisp_Object frame, color_symbols, color_table;
3973 int best_key;
3974 bool have_mask = 0;
3975 XImagePtr ximg = NULL, mask_img = NULL;
3977 #define match() \
3978 LA1 = xpm_scan (&s, end, &beg, &len)
3980 #define expect(TOKEN) \
3981 do \
3983 if (LA1 != (TOKEN)) \
3984 goto failure; \
3985 match (); \
3987 while (0)
3989 #define expect_ident(IDENT) \
3990 if (LA1 == XPM_TK_IDENT \
3991 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3992 match (); \
3993 else \
3994 goto failure
3996 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3997 goto failure;
3998 s += 9;
3999 match ();
4000 expect_ident ("static");
4001 expect_ident ("char");
4002 expect ('*');
4003 expect (XPM_TK_IDENT);
4004 expect ('[');
4005 expect (']');
4006 expect ('=');
4007 expect ('{');
4008 expect (XPM_TK_STRING);
4009 if (len >= BUFSIZ)
4010 goto failure;
4011 memcpy (buffer, beg, len);
4012 buffer[len] = '\0';
4013 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4014 &num_colors, &chars_per_pixel) != 4
4015 || width <= 0 || height <= 0
4016 || num_colors <= 0 || chars_per_pixel <= 0)
4017 goto failure;
4019 if (!check_image_size (f, width, height))
4021 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
4022 goto failure;
4025 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4026 #ifndef HAVE_NS
4027 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4028 &mask_img, 1)
4029 #endif
4032 image_error ("Image too large", Qnil, Qnil);
4033 goto failure;
4036 expect (',');
4038 XSETFRAME (frame, f);
4039 if (!NILP (Fxw_display_color_p (frame)))
4040 best_key = XPM_COLOR_KEY_C;
4041 else if (!NILP (Fx_display_grayscale_p (frame)))
4042 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4043 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4044 else
4045 best_key = XPM_COLOR_KEY_M;
4047 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4048 if (chars_per_pixel == 1)
4049 color_table = xpm_make_color_table_v (&put_color_table,
4050 &get_color_table);
4051 else
4052 color_table = xpm_make_color_table_h (&put_color_table,
4053 &get_color_table);
4055 while (num_colors-- > 0)
4057 char *color, *max_color;
4058 int key, next_key, max_key = 0;
4059 Lisp_Object symbol_color = Qnil, color_val;
4060 XColor cdef;
4062 expect (XPM_TK_STRING);
4063 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4064 goto failure;
4065 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4066 buffer[len - chars_per_pixel] = '\0';
4068 str = strtok (buffer, " \t");
4069 if (str == NULL)
4070 goto failure;
4071 key = xpm_str_to_color_key (str);
4072 if (key < 0)
4073 goto failure;
4076 color = strtok (NULL, " \t");
4077 if (color == NULL)
4078 goto failure;
4080 while ((str = strtok (NULL, " \t")) != NULL)
4082 next_key = xpm_str_to_color_key (str);
4083 if (next_key >= 0)
4084 break;
4085 color[strlen (color)] = ' ';
4088 if (key == XPM_COLOR_KEY_S)
4090 if (NILP (symbol_color))
4091 symbol_color = build_string (color);
4093 else if (max_key < key && key <= best_key)
4095 max_key = key;
4096 max_color = color;
4098 key = next_key;
4100 while (str);
4102 color_val = Qnil;
4103 if (!NILP (color_symbols) && !NILP (symbol_color))
4105 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4107 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4109 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4110 color_val = Qt;
4111 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4112 &cdef, 0))
4113 color_val = make_number (cdef.pixel);
4116 if (NILP (color_val) && max_key > 0)
4118 if (xstrcasecmp (max_color, "None") == 0)
4119 color_val = Qt;
4120 else if (x_defined_color (f, max_color, &cdef, 0))
4121 color_val = make_number (cdef.pixel);
4123 if (!NILP (color_val))
4124 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4126 expect (',');
4129 for (y = 0; y < height; y++)
4131 expect (XPM_TK_STRING);
4132 str = beg;
4133 if (len < width * chars_per_pixel)
4134 goto failure;
4135 for (x = 0; x < width; x++, str += chars_per_pixel)
4137 Lisp_Object color_val =
4138 (*get_color_table) (color_table, str, chars_per_pixel);
4140 XPutPixel (ximg, x, y,
4141 (INTEGERP (color_val) ? XINT (color_val)
4142 : FRAME_FOREGROUND_PIXEL (f)));
4143 #ifndef HAVE_NS
4144 XPutPixel (mask_img, x, y,
4145 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4146 : (have_mask = 1, PIX_MASK_RETAIN)));
4147 #else
4148 if (EQ (color_val, Qt))
4149 ns_set_alpha (ximg, x, y, 0);
4150 #endif
4152 if (y + 1 < height)
4153 expect (',');
4156 img->width = width;
4157 img->height = height;
4159 /* Maybe fill in the background field while we have ximg handy. */
4160 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4161 IMAGE_BACKGROUND (img, f, ximg);
4163 image_put_x_image (f, img, ximg, 0);
4164 #ifndef HAVE_NS
4165 if (have_mask)
4167 /* Fill in the background_transparent field while we have the
4168 mask handy. */
4169 image_background_transparent (img, f, mask_img);
4171 image_put_x_image (f, img, mask_img, 1);
4173 else
4175 x_destroy_x_image (mask_img);
4176 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4178 #endif
4179 return 1;
4181 failure:
4182 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4183 x_destroy_x_image (ximg);
4184 x_destroy_x_image (mask_img);
4185 x_clear_image (f, img);
4186 return 0;
4188 #undef match
4189 #undef expect
4190 #undef expect_ident
4193 static bool
4194 xpm_load (struct frame *f,
4195 struct image *img)
4197 bool success_p = 0;
4198 Lisp_Object file_name;
4200 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4201 file_name = image_spec_value (img->spec, QCfile, NULL);
4202 if (STRINGP (file_name))
4204 Lisp_Object file;
4205 unsigned char *contents;
4206 ptrdiff_t size;
4208 file = x_find_image_file (file_name);
4209 if (!STRINGP (file))
4211 image_error ("Cannot find image file `%s'", file_name, Qnil);
4212 return 0;
4215 contents = slurp_file (SSDATA (file), &size);
4216 if (contents == NULL)
4218 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4219 return 0;
4222 success_p = xpm_load_image (f, img, contents, contents + size);
4223 xfree (contents);
4225 else
4227 Lisp_Object data;
4229 data = image_spec_value (img->spec, QCdata, NULL);
4230 if (!STRINGP (data))
4232 image_error ("Invalid image data `%s'", data, Qnil);
4233 return 0;
4235 success_p = xpm_load_image (f, img, SDATA (data),
4236 SDATA (data) + SBYTES (data));
4239 return success_p;
4242 #endif /* HAVE_NS && !HAVE_XPM */
4246 /***********************************************************************
4247 Color table
4248 ***********************************************************************/
4250 #ifdef COLOR_TABLE_SUPPORT
4252 /* An entry in the color table mapping an RGB color to a pixel color. */
4254 struct ct_color
4256 int r, g, b;
4257 unsigned long pixel;
4259 /* Next in color table collision list. */
4260 struct ct_color *next;
4263 /* The bucket vector size to use. Must be prime. */
4265 #define CT_SIZE 101
4267 /* Value is a hash of the RGB color given by R, G, and B. */
4269 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4271 /* The color hash table. */
4273 static struct ct_color **ct_table;
4275 /* Number of entries in the color table. */
4277 static int ct_colors_allocated;
4278 enum
4280 ct_colors_allocated_max =
4281 min (INT_MAX,
4282 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4285 /* Initialize the color table. */
4287 static void
4288 init_color_table (void)
4290 int size = CT_SIZE * sizeof (*ct_table);
4291 ct_table = xzalloc (size);
4292 ct_colors_allocated = 0;
4296 /* Free memory associated with the color table. */
4298 static void
4299 free_color_table (void)
4301 int i;
4302 struct ct_color *p, *next;
4304 for (i = 0; i < CT_SIZE; ++i)
4305 for (p = ct_table[i]; p; p = next)
4307 next = p->next;
4308 xfree (p);
4311 xfree (ct_table);
4312 ct_table = NULL;
4316 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4317 entry for that color already is in the color table, return the
4318 pixel color of that entry. Otherwise, allocate a new color for R,
4319 G, B, and make an entry in the color table. */
4321 static unsigned long
4322 lookup_rgb_color (struct frame *f, int r, int g, int b)
4324 unsigned hash = CT_HASH_RGB (r, g, b);
4325 int i = hash % CT_SIZE;
4326 struct ct_color *p;
4327 Display_Info *dpyinfo;
4329 /* Handle TrueColor visuals specially, which improves performance by
4330 two orders of magnitude. Freeing colors on TrueColor visuals is
4331 a nop, and pixel colors specify RGB values directly. See also
4332 the Xlib spec, chapter 3.1. */
4333 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4334 if (dpyinfo->red_bits > 0)
4336 unsigned long pr, pg, pb;
4338 /* Apply gamma-correction like normal color allocation does. */
4339 if (f->gamma)
4341 XColor color;
4342 color.red = r, color.green = g, color.blue = b;
4343 gamma_correct (f, &color);
4344 r = color.red, g = color.green, b = color.blue;
4347 /* Scale down RGB values to the visual's bits per RGB, and shift
4348 them to the right position in the pixel color. Note that the
4349 original RGB values are 16-bit values, as usual in X. */
4350 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4351 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4352 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4354 /* Assemble the pixel color. */
4355 return pr | pg | pb;
4358 for (p = ct_table[i]; p; p = p->next)
4359 if (p->r == r && p->g == g && p->b == b)
4360 break;
4362 if (p == NULL)
4365 #ifdef HAVE_X_WINDOWS
4366 XColor color;
4367 Colormap cmap;
4368 bool rc;
4369 #else
4370 COLORREF color;
4371 #endif
4373 if (ct_colors_allocated_max <= ct_colors_allocated)
4374 return FRAME_FOREGROUND_PIXEL (f);
4376 #ifdef HAVE_X_WINDOWS
4377 color.red = r;
4378 color.green = g;
4379 color.blue = b;
4381 cmap = FRAME_X_COLORMAP (f);
4382 rc = x_alloc_nearest_color (f, cmap, &color);
4383 if (rc)
4385 ++ct_colors_allocated;
4386 p = xmalloc (sizeof *p);
4387 p->r = r;
4388 p->g = g;
4389 p->b = b;
4390 p->pixel = color.pixel;
4391 p->next = ct_table[i];
4392 ct_table[i] = p;
4394 else
4395 return FRAME_FOREGROUND_PIXEL (f);
4397 #else
4398 #ifdef HAVE_NTGUI
4399 color = PALETTERGB (r, g, b);
4400 #else
4401 color = RGB_TO_ULONG (r, g, b);
4402 #endif /* HAVE_NTGUI */
4403 ++ct_colors_allocated;
4404 p = xmalloc (sizeof *p);
4405 p->r = r;
4406 p->g = g;
4407 p->b = b;
4408 p->pixel = color;
4409 p->next = ct_table[i];
4410 ct_table[i] = p;
4411 #endif /* HAVE_X_WINDOWS */
4415 return p->pixel;
4419 /* Look up pixel color PIXEL which is used on frame F in the color
4420 table. If not already present, allocate it. Value is PIXEL. */
4422 static unsigned long
4423 lookup_pixel_color (struct frame *f, unsigned long pixel)
4425 int i = pixel % CT_SIZE;
4426 struct ct_color *p;
4428 for (p = ct_table[i]; p; p = p->next)
4429 if (p->pixel == pixel)
4430 break;
4432 if (p == NULL)
4434 XColor color;
4435 Colormap cmap;
4436 bool rc;
4438 if (ct_colors_allocated_max <= ct_colors_allocated)
4439 return FRAME_FOREGROUND_PIXEL (f);
4441 #ifdef HAVE_X_WINDOWS
4442 cmap = FRAME_X_COLORMAP (f);
4443 color.pixel = pixel;
4444 x_query_color (f, &color);
4445 rc = x_alloc_nearest_color (f, cmap, &color);
4446 #else
4447 block_input ();
4448 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4449 color.pixel = pixel;
4450 XQueryColor (NULL, cmap, &color);
4451 rc = x_alloc_nearest_color (f, cmap, &color);
4452 unblock_input ();
4453 #endif /* HAVE_X_WINDOWS */
4455 if (rc)
4457 ++ct_colors_allocated;
4459 p = xmalloc (sizeof *p);
4460 p->r = color.red;
4461 p->g = color.green;
4462 p->b = color.blue;
4463 p->pixel = pixel;
4464 p->next = ct_table[i];
4465 ct_table[i] = p;
4467 else
4468 return FRAME_FOREGROUND_PIXEL (f);
4470 return p->pixel;
4474 /* Value is a vector of all pixel colors contained in the color table,
4475 allocated via xmalloc. Set *N to the number of colors. */
4477 static unsigned long *
4478 colors_in_color_table (int *n)
4480 int i, j;
4481 struct ct_color *p;
4482 unsigned long *colors;
4484 if (ct_colors_allocated == 0)
4486 *n = 0;
4487 colors = NULL;
4489 else
4491 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4492 *n = ct_colors_allocated;
4494 for (i = j = 0; i < CT_SIZE; ++i)
4495 for (p = ct_table[i]; p; p = p->next)
4496 colors[j++] = p->pixel;
4499 return colors;
4502 #else /* COLOR_TABLE_SUPPORT */
4504 static unsigned long
4505 lookup_rgb_color (struct frame *f, int r, int g, int b)
4507 unsigned long pixel;
4509 #ifdef HAVE_NTGUI
4510 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4511 #endif /* HAVE_NTGUI */
4513 #ifdef HAVE_NS
4514 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4515 #endif /* HAVE_NS */
4516 return pixel;
4519 static void
4520 init_color_table (void)
4523 #endif /* COLOR_TABLE_SUPPORT */
4526 /***********************************************************************
4527 Algorithms
4528 ***********************************************************************/
4530 /* Edge detection matrices for different edge-detection
4531 strategies. */
4533 static int emboss_matrix[9] = {
4534 /* x - 1 x x + 1 */
4535 2, -1, 0, /* y - 1 */
4536 -1, 0, 1, /* y */
4537 0, 1, -2 /* y + 1 */
4540 static int laplace_matrix[9] = {
4541 /* x - 1 x x + 1 */
4542 1, 0, 0, /* y - 1 */
4543 0, 0, 0, /* y */
4544 0, 0, -1 /* y + 1 */
4547 /* Value is the intensity of the color whose red/green/blue values
4548 are R, G, and B. */
4550 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4553 /* On frame F, return an array of XColor structures describing image
4554 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4555 means also fill the red/green/blue members of the XColor
4556 structures. Value is a pointer to the array of XColors structures,
4557 allocated with xmalloc; it must be freed by the caller. */
4559 static XColor *
4560 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4562 int x, y;
4563 XColor *colors, *p;
4564 XImagePtr_or_DC ximg;
4565 #ifdef HAVE_NTGUI
4566 HGDIOBJ prev;
4567 #endif /* HAVE_NTGUI */
4569 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width < img->height)
4570 memory_full (SIZE_MAX);
4571 colors = xmalloc (sizeof *colors * img->width * img->height);
4573 /* Get the X image or create a memory device context for IMG. */
4574 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4576 /* Fill the `pixel' members of the XColor array. I wished there
4577 were an easy and portable way to circumvent XGetPixel. */
4578 p = colors;
4579 for (y = 0; y < img->height; ++y)
4581 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4582 XColor *row = p;
4583 for (x = 0; x < img->width; ++x, ++p)
4584 p->pixel = GET_PIXEL (ximg, x, y);
4585 if (rgb_p)
4586 x_query_colors (f, row, img->width);
4588 #else
4590 for (x = 0; x < img->width; ++x, ++p)
4592 /* W32_TODO: palette support needed here? */
4593 p->pixel = GET_PIXEL (ximg, x, y);
4594 if (rgb_p)
4596 p->red = RED16_FROM_ULONG (p->pixel);
4597 p->green = GREEN16_FROM_ULONG (p->pixel);
4598 p->blue = BLUE16_FROM_ULONG (p->pixel);
4601 #endif /* HAVE_X_WINDOWS */
4604 image_unget_x_image_or_dc (img, 0, ximg, prev);
4606 return colors;
4609 #ifdef HAVE_NTGUI
4611 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4612 created with CreateDIBSection, with the pointer to the bit values
4613 stored in ximg->data. */
4615 static void
4616 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4618 int width = ximg->info.bmiHeader.biWidth;
4619 unsigned char * pixel;
4621 /* True color images. */
4622 if (ximg->info.bmiHeader.biBitCount == 24)
4624 int rowbytes = width * 3;
4625 /* Ensure scanlines are aligned on 4 byte boundaries. */
4626 if (rowbytes % 4)
4627 rowbytes += 4 - (rowbytes % 4);
4629 pixel = ximg->data + y * rowbytes + x * 3;
4630 /* Windows bitmaps are in BGR order. */
4631 *pixel = GetBValue (color);
4632 *(pixel + 1) = GetGValue (color);
4633 *(pixel + 2) = GetRValue (color);
4635 /* Monochrome images. */
4636 else if (ximg->info.bmiHeader.biBitCount == 1)
4638 int rowbytes = width / 8;
4639 /* Ensure scanlines are aligned on 4 byte boundaries. */
4640 if (rowbytes % 4)
4641 rowbytes += 4 - (rowbytes % 4);
4642 pixel = ximg->data + y * rowbytes + x / 8;
4643 /* Filter out palette info. */
4644 if (color & 0x00ffffff)
4645 *pixel = *pixel | (1 << x % 8);
4646 else
4647 *pixel = *pixel & ~(1 << x % 8);
4649 else
4650 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4653 #endif /* HAVE_NTGUI */
4655 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4656 RGB members are set. F is the frame on which this all happens.
4657 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4659 static void
4660 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4662 int x, y;
4663 XImagePtr oimg = NULL;
4664 XColor *p;
4666 init_color_table ();
4668 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4669 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4670 &oimg, 0);
4671 p = colors;
4672 for (y = 0; y < img->height; ++y)
4673 for (x = 0; x < img->width; ++x, ++p)
4675 unsigned long pixel;
4676 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4677 XPutPixel (oimg, x, y, pixel);
4680 xfree (colors);
4682 image_put_x_image (f, img, oimg, 0);
4683 #ifdef COLOR_TABLE_SUPPORT
4684 img->colors = colors_in_color_table (&img->ncolors);
4685 free_color_table ();
4686 #endif /* COLOR_TABLE_SUPPORT */
4690 /* On frame F, perform edge-detection on image IMG.
4692 MATRIX is a nine-element array specifying the transformation
4693 matrix. See emboss_matrix for an example.
4695 COLOR_ADJUST is a color adjustment added to each pixel of the
4696 outgoing image. */
4698 static void
4699 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4701 XColor *colors = x_to_xcolors (f, img, 1);
4702 XColor *new, *p;
4703 int x, y, i, sum;
4705 for (i = sum = 0; i < 9; ++i)
4706 sum += eabs (matrix[i]);
4708 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4710 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width < img->height)
4711 memory_full (SIZE_MAX);
4712 new = xmalloc (sizeof *new * img->width * img->height);
4714 for (y = 0; y < img->height; ++y)
4716 p = COLOR (new, 0, y);
4717 p->red = p->green = p->blue = 0xffff/2;
4718 p = COLOR (new, img->width - 1, y);
4719 p->red = p->green = p->blue = 0xffff/2;
4722 for (x = 1; x < img->width - 1; ++x)
4724 p = COLOR (new, x, 0);
4725 p->red = p->green = p->blue = 0xffff/2;
4726 p = COLOR (new, x, img->height - 1);
4727 p->red = p->green = p->blue = 0xffff/2;
4730 for (y = 1; y < img->height - 1; ++y)
4732 p = COLOR (new, 1, y);
4734 for (x = 1; x < img->width - 1; ++x, ++p)
4736 int r, g, b, yy, xx;
4738 r = g = b = i = 0;
4739 for (yy = y - 1; yy < y + 2; ++yy)
4740 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4741 if (matrix[i])
4743 XColor *t = COLOR (colors, xx, yy);
4744 r += matrix[i] * t->red;
4745 g += matrix[i] * t->green;
4746 b += matrix[i] * t->blue;
4749 r = (r / sum + color_adjust) & 0xffff;
4750 g = (g / sum + color_adjust) & 0xffff;
4751 b = (b / sum + color_adjust) & 0xffff;
4752 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4756 xfree (colors);
4757 x_from_xcolors (f, img, new);
4759 #undef COLOR
4763 /* Perform the pre-defined `emboss' edge-detection on image IMG
4764 on frame F. */
4766 static void
4767 x_emboss (struct frame *f, struct image *img)
4769 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4773 /* Transform image IMG which is used on frame F with a Laplace
4774 edge-detection algorithm. The result is an image that can be used
4775 to draw disabled buttons, for example. */
4777 static void
4778 x_laplace (struct frame *f, struct image *img)
4780 x_detect_edges (f, img, laplace_matrix, 45000);
4784 /* Perform edge-detection on image IMG on frame F, with specified
4785 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4787 MATRIX must be either
4789 - a list of at least 9 numbers in row-major form
4790 - a vector of at least 9 numbers
4792 COLOR_ADJUST nil means use a default; otherwise it must be a
4793 number. */
4795 static void
4796 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4797 Lisp_Object color_adjust)
4799 int i = 0;
4800 int trans[9];
4802 if (CONSP (matrix))
4804 for (i = 0;
4805 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4806 ++i, matrix = XCDR (matrix))
4807 trans[i] = XFLOATINT (XCAR (matrix));
4809 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4811 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4812 trans[i] = XFLOATINT (AREF (matrix, i));
4815 if (NILP (color_adjust))
4816 color_adjust = make_number (0xffff / 2);
4818 if (i == 9 && NUMBERP (color_adjust))
4819 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4823 /* Transform image IMG on frame F so that it looks disabled. */
4825 static void
4826 x_disable_image (struct frame *f, struct image *img)
4828 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4829 #ifdef HAVE_NTGUI
4830 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4831 #else
4832 int n_planes = dpyinfo->n_planes;
4833 #endif /* HAVE_NTGUI */
4835 if (n_planes >= 2)
4837 /* Color (or grayscale). Convert to gray, and equalize. Just
4838 drawing such images with a stipple can look very odd, so
4839 we're using this method instead. */
4840 XColor *colors = x_to_xcolors (f, img, 1);
4841 XColor *p, *end;
4842 const int h = 15000;
4843 const int l = 30000;
4845 for (p = colors, end = colors + img->width * img->height;
4846 p < end;
4847 ++p)
4849 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4850 int i2 = (0xffff - h - l) * i / 0xffff + l;
4851 p->red = p->green = p->blue = i2;
4854 x_from_xcolors (f, img, colors);
4857 /* Draw a cross over the disabled image, if we must or if we
4858 should. */
4859 if (n_planes < 2 || cross_disabled_images)
4861 #ifndef HAVE_NTGUI
4862 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4864 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4866 Display *dpy = FRAME_X_DISPLAY (f);
4867 GC gc;
4869 image_sync_to_pixmaps (f, img);
4870 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4871 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4872 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4873 img->width - 1, img->height - 1);
4874 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4875 img->width - 1, 0);
4876 XFreeGC (dpy, gc);
4878 if (img->mask)
4880 gc = XCreateGC (dpy, img->mask, 0, NULL);
4881 XSetForeground (dpy, gc, MaskForeground (f));
4882 XDrawLine (dpy, img->mask, gc, 0, 0,
4883 img->width - 1, img->height - 1);
4884 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4885 img->width - 1, 0);
4886 XFreeGC (dpy, gc);
4888 #endif /* !HAVE_NS */
4889 #else
4890 HDC hdc, bmpdc;
4891 HGDIOBJ prev;
4893 hdc = get_frame_dc (f);
4894 bmpdc = CreateCompatibleDC (hdc);
4895 release_frame_dc (f, hdc);
4897 prev = SelectObject (bmpdc, img->pixmap);
4899 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4900 MoveToEx (bmpdc, 0, 0, NULL);
4901 LineTo (bmpdc, img->width - 1, img->height - 1);
4902 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4903 LineTo (bmpdc, img->width - 1, 0);
4905 if (img->mask)
4907 SelectObject (bmpdc, img->mask);
4908 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4909 MoveToEx (bmpdc, 0, 0, NULL);
4910 LineTo (bmpdc, img->width - 1, img->height - 1);
4911 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4912 LineTo (bmpdc, img->width - 1, 0);
4914 SelectObject (bmpdc, prev);
4915 DeleteDC (bmpdc);
4916 #endif /* HAVE_NTGUI */
4921 /* Build a mask for image IMG which is used on frame F. FILE is the
4922 name of an image file, for error messages. HOW determines how to
4923 determine the background color of IMG. If it is a list '(R G B)',
4924 with R, G, and B being integers >= 0, take that as the color of the
4925 background. Otherwise, determine the background color of IMG
4926 heuristically. */
4928 static void
4929 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4931 XImagePtr_or_DC ximg;
4932 #ifndef HAVE_NTGUI
4933 XImagePtr mask_img;
4934 #else
4935 HGDIOBJ prev;
4936 char *mask_img;
4937 int row_width;
4938 #endif /* HAVE_NTGUI */
4939 int x, y;
4940 bool use_img_background;
4941 unsigned long bg = 0;
4943 if (img->mask)
4944 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4946 #ifndef HAVE_NTGUI
4947 #ifndef HAVE_NS
4948 /* Create an image and pixmap serving as mask. */
4949 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
4950 &mask_img, 1))
4951 return;
4952 #endif /* !HAVE_NS */
4953 #else
4954 /* Create the bit array serving as mask. */
4955 row_width = (img->width + 7) / 8;
4956 mask_img = xzalloc (row_width * img->height);
4957 #endif /* HAVE_NTGUI */
4959 /* Get the X image or create a memory device context for IMG. */
4960 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4962 /* Determine the background color of ximg. If HOW is `(R G B)'
4963 take that as color. Otherwise, use the image's background color. */
4964 use_img_background = 1;
4966 if (CONSP (how))
4968 int rgb[3], i;
4970 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4972 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4973 how = XCDR (how);
4976 if (i == 3 && NILP (how))
4978 char color_name[30];
4979 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4980 bg = (
4981 #ifdef HAVE_NTGUI
4982 0x00ffffff & /* Filter out palette info. */
4983 #endif /* HAVE_NTGUI */
4984 x_alloc_image_color (f, img, build_string (color_name), 0));
4985 use_img_background = 0;
4989 if (use_img_background)
4990 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4992 /* Set all bits in mask_img to 1 whose color in ximg is different
4993 from the background color bg. */
4994 #ifndef HAVE_NTGUI
4995 for (y = 0; y < img->height; ++y)
4996 for (x = 0; x < img->width; ++x)
4997 #ifndef HAVE_NS
4998 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4999 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5000 #else
5001 if (XGetPixel (ximg, x, y) == bg)
5002 ns_set_alpha (ximg, x, y, 0);
5003 #endif /* HAVE_NS */
5004 #ifndef HAVE_NS
5005 /* Fill in the background_transparent field while we have the mask handy. */
5006 image_background_transparent (img, f, mask_img);
5008 /* Put mask_img into the image. */
5009 image_put_x_image (f, img, mask_img, 1);
5010 #endif /* !HAVE_NS */
5011 #else
5012 for (y = 0; y < img->height; ++y)
5013 for (x = 0; x < img->width; ++x)
5015 COLORREF p = GetPixel (ximg, x, y);
5016 if (p != bg)
5017 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5020 /* Create the mask image. */
5021 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5022 mask_img);
5023 /* Fill in the background_transparent field while we have the mask handy. */
5024 SelectObject (ximg, img->mask);
5025 image_background_transparent (img, f, ximg);
5027 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5028 xfree (mask_img);
5029 #endif /* HAVE_NTGUI */
5031 image_unget_x_image_or_dc (img, 0, ximg, prev);
5035 /***********************************************************************
5036 PBM (mono, gray, color)
5037 ***********************************************************************/
5039 static bool pbm_image_p (Lisp_Object object);
5040 static bool pbm_load (struct frame *f, struct image *img);
5042 /* The symbol `pbm' identifying images of this type. */
5044 static Lisp_Object Qpbm;
5046 /* Indices of image specification fields in gs_format, below. */
5048 enum pbm_keyword_index
5050 PBM_TYPE,
5051 PBM_FILE,
5052 PBM_DATA,
5053 PBM_ASCENT,
5054 PBM_MARGIN,
5055 PBM_RELIEF,
5056 PBM_ALGORITHM,
5057 PBM_HEURISTIC_MASK,
5058 PBM_MASK,
5059 PBM_FOREGROUND,
5060 PBM_BACKGROUND,
5061 PBM_LAST
5064 /* Vector of image_keyword structures describing the format
5065 of valid user-defined image specifications. */
5067 static const struct image_keyword pbm_format[PBM_LAST] =
5069 {":type", IMAGE_SYMBOL_VALUE, 1},
5070 {":file", IMAGE_STRING_VALUE, 0},
5071 {":data", IMAGE_STRING_VALUE, 0},
5072 {":ascent", IMAGE_ASCENT_VALUE, 0},
5073 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5074 {":relief", IMAGE_INTEGER_VALUE, 0},
5075 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5076 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5077 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5078 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5079 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5082 /* Structure describing the image type `pbm'. */
5084 static struct image_type pbm_type =
5086 &Qpbm,
5087 pbm_image_p,
5088 pbm_load,
5089 x_clear_image,
5090 NULL,
5091 NULL
5095 /* Return true if OBJECT is a valid PBM image specification. */
5097 static bool
5098 pbm_image_p (Lisp_Object object)
5100 struct image_keyword fmt[PBM_LAST];
5102 memcpy (fmt, pbm_format, sizeof fmt);
5104 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5105 return 0;
5107 /* Must specify either :data or :file. */
5108 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5112 /* Scan a decimal number from *S and return it. Advance *S while
5113 reading the number. END is the end of the string. Value is -1 at
5114 end of input. */
5116 static int
5117 pbm_scan_number (unsigned char **s, unsigned char *end)
5119 int c = 0, val = -1;
5121 while (*s < end)
5123 /* Skip white-space. */
5124 while (*s < end && (c = *(*s)++, c_isspace (c)))
5127 if (c == '#')
5129 /* Skip comment to end of line. */
5130 while (*s < end && (c = *(*s)++, c != '\n'))
5133 else if (c_isdigit (c))
5135 /* Read decimal number. */
5136 val = c - '0';
5137 while (*s < end && (c = *(*s)++, c_isdigit (c)))
5138 val = 10 * val + c - '0';
5139 break;
5141 else
5142 break;
5145 return val;
5149 /* Load PBM image IMG for use on frame F. */
5151 static bool
5152 pbm_load (struct frame *f, struct image *img)
5154 bool raw_p;
5155 int x, y;
5156 int width, height, max_color_idx = 0;
5157 XImagePtr ximg;
5158 Lisp_Object file, specified_file;
5159 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5160 unsigned char *contents = NULL;
5161 unsigned char *end, *p;
5162 ptrdiff_t size;
5164 specified_file = image_spec_value (img->spec, QCfile, NULL);
5166 if (STRINGP (specified_file))
5168 file = x_find_image_file (specified_file);
5169 if (!STRINGP (file))
5171 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5172 return 0;
5175 contents = slurp_file (SSDATA (file), &size);
5176 if (contents == NULL)
5178 image_error ("Error reading `%s'", file, Qnil);
5179 return 0;
5182 p = contents;
5183 end = contents + size;
5185 else
5187 Lisp_Object data;
5188 data = image_spec_value (img->spec, QCdata, NULL);
5189 if (!STRINGP (data))
5191 image_error ("Invalid image data `%s'", data, Qnil);
5192 return 0;
5194 p = SDATA (data);
5195 end = p + SBYTES (data);
5198 /* Check magic number. */
5199 if (end - p < 2 || *p++ != 'P')
5201 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5202 error:
5203 xfree (contents);
5204 return 0;
5207 switch (*p++)
5209 case '1':
5210 raw_p = 0, type = PBM_MONO;
5211 break;
5213 case '2':
5214 raw_p = 0, type = PBM_GRAY;
5215 break;
5217 case '3':
5218 raw_p = 0, type = PBM_COLOR;
5219 break;
5221 case '4':
5222 raw_p = 1, type = PBM_MONO;
5223 break;
5225 case '5':
5226 raw_p = 1, type = PBM_GRAY;
5227 break;
5229 case '6':
5230 raw_p = 1, type = PBM_COLOR;
5231 break;
5233 default:
5234 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5235 goto error;
5238 /* Read width, height, maximum color-component. Characters
5239 starting with `#' up to the end of a line are ignored. */
5240 width = pbm_scan_number (&p, end);
5241 height = pbm_scan_number (&p, end);
5243 if (type != PBM_MONO)
5245 max_color_idx = pbm_scan_number (&p, end);
5246 if (max_color_idx > 65535 || max_color_idx < 0)
5248 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5249 goto error;
5253 if (!check_image_size (f, width, height))
5255 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5256 goto error;
5259 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5260 goto error;
5262 /* Initialize the color hash table. */
5263 init_color_table ();
5265 if (type == PBM_MONO)
5267 int c = 0, g;
5268 struct image_keyword fmt[PBM_LAST];
5269 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5270 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5272 /* Parse the image specification. */
5273 memcpy (fmt, pbm_format, sizeof fmt);
5274 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5276 /* Get foreground and background colors, maybe allocate colors. */
5277 if (fmt[PBM_FOREGROUND].count
5278 && STRINGP (fmt[PBM_FOREGROUND].value))
5279 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5280 if (fmt[PBM_BACKGROUND].count
5281 && STRINGP (fmt[PBM_BACKGROUND].value))
5283 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5284 img->background = bg;
5285 img->background_valid = 1;
5288 for (y = 0; y < height; ++y)
5289 for (x = 0; x < width; ++x)
5291 if (raw_p)
5293 if ((x & 7) == 0)
5295 if (p >= end)
5297 x_destroy_x_image (ximg);
5298 x_clear_image (f, img);
5299 image_error ("Invalid image size in image `%s'",
5300 img->spec, Qnil);
5301 goto error;
5303 c = *p++;
5305 g = c & 0x80;
5306 c <<= 1;
5308 else
5309 g = pbm_scan_number (&p, end);
5311 XPutPixel (ximg, x, y, g ? fg : bg);
5314 else
5316 int expected_size = height * width;
5317 if (max_color_idx > 255)
5318 expected_size *= 2;
5319 if (type == PBM_COLOR)
5320 expected_size *= 3;
5322 if (raw_p && p + expected_size > end)
5324 x_destroy_x_image (ximg);
5325 x_clear_image (f, img);
5326 image_error ("Invalid image size in image `%s'",
5327 img->spec, Qnil);
5328 goto error;
5331 for (y = 0; y < height; ++y)
5332 for (x = 0; x < width; ++x)
5334 int r, g, b;
5336 if (type == PBM_GRAY && raw_p)
5338 r = g = b = *p++;
5339 if (max_color_idx > 255)
5340 r = g = b = r * 256 + *p++;
5342 else if (type == PBM_GRAY)
5343 r = g = b = pbm_scan_number (&p, end);
5344 else if (raw_p)
5346 r = *p++;
5347 if (max_color_idx > 255)
5348 r = r * 256 + *p++;
5349 g = *p++;
5350 if (max_color_idx > 255)
5351 g = g * 256 + *p++;
5352 b = *p++;
5353 if (max_color_idx > 255)
5354 b = b * 256 + *p++;
5356 else
5358 r = pbm_scan_number (&p, end);
5359 g = pbm_scan_number (&p, end);
5360 b = pbm_scan_number (&p, end);
5363 if (r < 0 || g < 0 || b < 0)
5365 x_destroy_x_image (ximg);
5366 image_error ("Invalid pixel value in image `%s'",
5367 img->spec, Qnil);
5368 goto error;
5371 /* RGB values are now in the range 0..max_color_idx.
5372 Scale this to the range 0..0xffff supported by X. */
5373 r = (double) r * 65535 / max_color_idx;
5374 g = (double) g * 65535 / max_color_idx;
5375 b = (double) b * 65535 / max_color_idx;
5376 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5380 #ifdef COLOR_TABLE_SUPPORT
5381 /* Store in IMG->colors the colors allocated for the image, and
5382 free the color table. */
5383 img->colors = colors_in_color_table (&img->ncolors);
5384 free_color_table ();
5385 #endif /* COLOR_TABLE_SUPPORT */
5387 img->width = width;
5388 img->height = height;
5390 /* Maybe fill in the background field while we have ximg handy. */
5392 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5393 /* Casting avoids a GCC warning. */
5394 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5396 /* Put ximg into the image. */
5397 image_put_x_image (f, img, ximg, 0);
5399 /* X and W32 versions did it here, MAC version above. ++kfs
5400 img->width = width;
5401 img->height = height; */
5403 xfree (contents);
5404 return 1;
5408 /***********************************************************************
5410 ***********************************************************************/
5412 #if defined (HAVE_PNG) || defined (HAVE_NS)
5414 /* Function prototypes. */
5416 static bool png_image_p (Lisp_Object object);
5417 static bool png_load (struct frame *f, struct image *img);
5419 /* The symbol `png' identifying images of this type. */
5421 static Lisp_Object Qpng;
5423 /* Indices of image specification fields in png_format, below. */
5425 enum png_keyword_index
5427 PNG_TYPE,
5428 PNG_DATA,
5429 PNG_FILE,
5430 PNG_ASCENT,
5431 PNG_MARGIN,
5432 PNG_RELIEF,
5433 PNG_ALGORITHM,
5434 PNG_HEURISTIC_MASK,
5435 PNG_MASK,
5436 PNG_BACKGROUND,
5437 PNG_LAST
5440 /* Vector of image_keyword structures describing the format
5441 of valid user-defined image specifications. */
5443 static const struct image_keyword png_format[PNG_LAST] =
5445 {":type", IMAGE_SYMBOL_VALUE, 1},
5446 {":data", IMAGE_STRING_VALUE, 0},
5447 {":file", IMAGE_STRING_VALUE, 0},
5448 {":ascent", IMAGE_ASCENT_VALUE, 0},
5449 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5450 {":relief", IMAGE_INTEGER_VALUE, 0},
5451 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5452 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5453 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5454 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5457 #if defined HAVE_NTGUI && defined WINDOWSNT
5458 static bool init_png_functions (void);
5459 #else
5460 #define init_png_functions NULL
5461 #endif
5463 /* Structure describing the image type `png'. */
5465 static struct image_type png_type =
5467 &Qpng,
5468 png_image_p,
5469 png_load,
5470 x_clear_image,
5471 init_png_functions,
5472 NULL
5475 /* Return true if OBJECT is a valid PNG image specification. */
5477 static bool
5478 png_image_p (Lisp_Object object)
5480 struct image_keyword fmt[PNG_LAST];
5481 memcpy (fmt, png_format, sizeof fmt);
5483 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5484 return 0;
5486 /* Must specify either the :data or :file keyword. */
5487 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5490 #endif /* HAVE_PNG || HAVE_NS */
5493 #ifdef HAVE_PNG
5495 #ifdef WINDOWSNT
5496 /* PNG library details. */
5498 DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5499 DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5500 DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5501 png_error_ptr, png_error_ptr));
5502 DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5503 DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5504 DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5505 DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5506 DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5507 DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
5508 png_uint_32 *, png_uint_32 *,
5509 int *, int *, int *, int *, int *));
5510 DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5511 DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5512 DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5513 DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5514 DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
5515 int, int, double));
5516 DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5517 DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5518 DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5519 DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5520 DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5521 DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5522 DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
5524 #if (PNG_LIBPNG_VER >= 10500)
5525 DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int));
5526 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
5527 #endif /* libpng version >= 1.5 */
5529 static bool
5530 init_png_functions (void)
5532 HMODULE library;
5534 if (!(library = w32_delayed_load (Qpng)))
5535 return 0;
5537 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5538 LOAD_IMGLIB_FN (library, png_sig_cmp);
5539 LOAD_IMGLIB_FN (library, png_create_read_struct);
5540 LOAD_IMGLIB_FN (library, png_create_info_struct);
5541 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5542 LOAD_IMGLIB_FN (library, png_set_read_fn);
5543 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5544 LOAD_IMGLIB_FN (library, png_read_info);
5545 LOAD_IMGLIB_FN (library, png_get_IHDR);
5546 LOAD_IMGLIB_FN (library, png_get_valid);
5547 LOAD_IMGLIB_FN (library, png_set_strip_16);
5548 LOAD_IMGLIB_FN (library, png_set_expand);
5549 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5550 LOAD_IMGLIB_FN (library, png_set_background);
5551 LOAD_IMGLIB_FN (library, png_get_bKGD);
5552 LOAD_IMGLIB_FN (library, png_read_update_info);
5553 LOAD_IMGLIB_FN (library, png_get_channels);
5554 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5555 LOAD_IMGLIB_FN (library, png_read_image);
5556 LOAD_IMGLIB_FN (library, png_read_end);
5557 LOAD_IMGLIB_FN (library, png_error);
5559 #if (PNG_LIBPNG_VER >= 10500)
5560 LOAD_IMGLIB_FN (library, png_longjmp);
5561 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5562 #endif /* libpng version >= 1.5 */
5564 return 1;
5566 #else
5568 #define fn_png_get_io_ptr png_get_io_ptr
5569 #define fn_png_sig_cmp png_sig_cmp
5570 #define fn_png_create_read_struct png_create_read_struct
5571 #define fn_png_create_info_struct png_create_info_struct
5572 #define fn_png_destroy_read_struct png_destroy_read_struct
5573 #define fn_png_set_read_fn png_set_read_fn
5574 #define fn_png_set_sig_bytes png_set_sig_bytes
5575 #define fn_png_read_info png_read_info
5576 #define fn_png_get_IHDR png_get_IHDR
5577 #define fn_png_get_valid png_get_valid
5578 #define fn_png_set_strip_16 png_set_strip_16
5579 #define fn_png_set_expand png_set_expand
5580 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5581 #define fn_png_set_background png_set_background
5582 #define fn_png_get_bKGD png_get_bKGD
5583 #define fn_png_read_update_info png_read_update_info
5584 #define fn_png_get_channels png_get_channels
5585 #define fn_png_get_rowbytes png_get_rowbytes
5586 #define fn_png_read_image png_read_image
5587 #define fn_png_read_end png_read_end
5588 #define fn_png_error png_error
5590 #if (PNG_LIBPNG_VER >= 10500)
5591 #define fn_png_longjmp png_longjmp
5592 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5593 #endif /* libpng version >= 1.5 */
5595 #endif /* WINDOWSNT */
5597 /* Possibly inefficient/inexact substitutes for _setjmp and _longjmp.
5598 Do not use sys_setjmp, as PNG supports only jmp_buf. The _longjmp
5599 substitute may munge the signal mask, but that should be OK here.
5600 MinGW (MS-Windows) uses _setjmp and defines setjmp to _setjmp in
5601 the system header setjmp.h; don't mess up that. */
5602 #ifndef HAVE__SETJMP
5603 # define _setjmp(j) setjmp (j)
5604 # define _longjmp longjmp
5605 #endif
5607 #if (PNG_LIBPNG_VER < 10500)
5608 #define PNG_LONGJMP(ptr) (_longjmp ((ptr)->jmpbuf, 1))
5609 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5610 #else
5611 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5612 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5613 #define PNG_JMPBUF(ptr) \
5614 (*fn_png_set_longjmp_fn ((ptr), _longjmp, sizeof (jmp_buf)))
5615 #endif
5617 /* Error and warning handlers installed when the PNG library
5618 is initialized. */
5620 static _Noreturn void
5621 my_png_error (png_struct *png_ptr, const char *msg)
5623 eassert (png_ptr != NULL);
5624 /* Avoid compiler warning about deprecated direct access to
5625 png_ptr's fields in libpng versions 1.4.x. */
5626 image_error ("PNG error: %s", build_string (msg), Qnil);
5627 PNG_LONGJMP (png_ptr);
5631 static void
5632 my_png_warning (png_struct *png_ptr, const char *msg)
5634 eassert (png_ptr != NULL);
5635 image_error ("PNG warning: %s", build_string (msg), Qnil);
5638 /* Memory source for PNG decoding. */
5640 struct png_memory_storage
5642 unsigned char *bytes; /* The data */
5643 ptrdiff_t len; /* How big is it? */
5644 ptrdiff_t index; /* Where are we? */
5648 /* Function set as reader function when reading PNG image from memory.
5649 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5650 bytes from the input to DATA. */
5652 static void
5653 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5655 struct png_memory_storage *tbr = fn_png_get_io_ptr (png_ptr);
5657 if (length > tbr->len - tbr->index)
5658 fn_png_error (png_ptr, "Read error");
5660 memcpy (data, tbr->bytes + tbr->index, length);
5661 tbr->index = tbr->index + length;
5665 /* Function set as reader function when reading PNG image from a file.
5666 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5667 bytes from the input to DATA. */
5669 static void
5670 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5672 FILE *fp = fn_png_get_io_ptr (png_ptr);
5674 if (fread (data, 1, length, fp) < length)
5675 fn_png_error (png_ptr, "Read error");
5679 /* Load PNG image IMG for use on frame F. Value is true if
5680 successful. */
5682 struct png_load_context
5684 /* These are members so that longjmp doesn't munge local variables. */
5685 png_struct *png_ptr;
5686 png_info *info_ptr;
5687 png_info *end_info;
5688 FILE *fp;
5689 png_byte *pixels;
5690 png_byte **rows;
5693 static bool
5694 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5696 Lisp_Object file, specified_file;
5697 Lisp_Object specified_data;
5698 int x, y;
5699 ptrdiff_t i;
5700 XImagePtr ximg, mask_img = NULL;
5701 png_struct *png_ptr;
5702 png_info *info_ptr = NULL, *end_info = NULL;
5703 FILE *fp = NULL;
5704 png_byte sig[8];
5705 png_byte *pixels = NULL;
5706 png_byte **rows = NULL;
5707 png_uint_32 width, height;
5708 int bit_depth, color_type, interlace_type;
5709 png_byte channels;
5710 png_uint_32 row_bytes;
5711 bool transparent_p;
5712 struct png_memory_storage tbr; /* Data to be read */
5714 /* Find out what file to load. */
5715 specified_file = image_spec_value (img->spec, QCfile, NULL);
5716 specified_data = image_spec_value (img->spec, QCdata, NULL);
5718 if (NILP (specified_data))
5720 file = x_find_image_file (specified_file);
5721 if (!STRINGP (file))
5723 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5724 return 0;
5727 /* Open the image file. */
5728 fp = emacs_fopen (SSDATA (file), "rb");
5729 if (!fp)
5731 image_error ("Cannot open image file `%s'", file, Qnil);
5732 return 0;
5735 /* Check PNG signature. */
5736 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5737 || fn_png_sig_cmp (sig, 0, sizeof sig))
5739 fclose (fp);
5740 image_error ("Not a PNG file: `%s'", file, Qnil);
5741 return 0;
5744 else
5746 if (!STRINGP (specified_data))
5748 image_error ("Invalid image data `%s'", specified_data, Qnil);
5749 return 0;
5752 /* Read from memory. */
5753 tbr.bytes = SDATA (specified_data);
5754 tbr.len = SBYTES (specified_data);
5755 tbr.index = 0;
5757 /* Check PNG signature. */
5758 if (tbr.len < sizeof sig
5759 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5761 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5762 return 0;
5765 /* Need to skip past the signature. */
5766 tbr.bytes += sizeof (sig);
5769 /* Initialize read and info structs for PNG lib. */
5770 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5771 NULL, my_png_error,
5772 my_png_warning);
5773 if (png_ptr)
5775 info_ptr = fn_png_create_info_struct (png_ptr);
5776 end_info = fn_png_create_info_struct (png_ptr);
5779 c->png_ptr = png_ptr;
5780 c->info_ptr = info_ptr;
5781 c->end_info = end_info;
5782 c->fp = fp;
5783 c->pixels = pixels;
5784 c->rows = rows;
5786 if (! (info_ptr && end_info))
5788 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5789 png_ptr = 0;
5791 if (! png_ptr)
5793 if (fp) fclose (fp);
5794 return 0;
5797 /* Set error jump-back. We come back here when the PNG library
5798 detects an error. */
5799 if (_setjmp (PNG_JMPBUF (png_ptr)))
5801 error:
5802 if (c->png_ptr)
5803 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5804 xfree (c->pixels);
5805 xfree (c->rows);
5806 if (c->fp)
5807 fclose (c->fp);
5808 return 0;
5811 /* Silence a bogus diagnostic; see GCC bug 54561. */
5812 IF_LINT (fp = c->fp);
5814 /* Read image info. */
5815 if (!NILP (specified_data))
5816 fn_png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
5817 else
5818 fn_png_set_read_fn (png_ptr, fp, png_read_from_file);
5820 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5821 fn_png_read_info (png_ptr, info_ptr);
5822 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5823 &interlace_type, NULL, NULL);
5825 if (! (width <= INT_MAX && height <= INT_MAX
5826 && check_image_size (f, width, height)))
5828 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5829 goto error;
5832 /* Create the X image and pixmap now, so that the work below can be
5833 omitted if the image is too large for X. */
5834 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5835 goto error;
5837 /* If image contains simply transparency data, we prefer to
5838 construct a clipping mask. */
5839 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5840 transparent_p = 1;
5841 else
5842 transparent_p = 0;
5844 /* This function is easier to write if we only have to handle
5845 one data format: RGB or RGBA with 8 bits per channel. Let's
5846 transform other formats into that format. */
5848 /* Strip more than 8 bits per channel. */
5849 if (bit_depth == 16)
5850 fn_png_set_strip_16 (png_ptr);
5852 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5853 if available. */
5854 fn_png_set_expand (png_ptr);
5856 /* Convert grayscale images to RGB. */
5857 if (color_type == PNG_COLOR_TYPE_GRAY
5858 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5859 fn_png_set_gray_to_rgb (png_ptr);
5861 /* Handle alpha channel by combining the image with a background
5862 color. Do this only if a real alpha channel is supplied. For
5863 simple transparency, we prefer a clipping mask. */
5864 if (!transparent_p)
5866 /* png_color_16 *image_bg; */
5867 Lisp_Object specified_bg
5868 = image_spec_value (img->spec, QCbackground, NULL);
5869 int shift = (bit_depth == 16) ? 0 : 8;
5871 if (STRINGP (specified_bg))
5872 /* The user specified `:background', use that. */
5874 XColor color;
5875 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
5877 png_color_16 user_bg;
5879 memset (&user_bg, 0, sizeof user_bg);
5880 user_bg.red = color.red >> shift;
5881 user_bg.green = color.green >> shift;
5882 user_bg.blue = color.blue >> shift;
5884 fn_png_set_background (png_ptr, &user_bg,
5885 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5888 else
5890 /* We use the current frame background, ignoring any default
5891 background color set by the image. */
5892 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5893 XColor color;
5894 png_color_16 frame_background;
5896 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5897 x_query_color (f, &color);
5899 memset (&frame_background, 0, sizeof frame_background);
5900 frame_background.red = color.red >> shift;
5901 frame_background.green = color.green >> shift;
5902 frame_background.blue = color.blue >> shift;
5903 #endif /* HAVE_X_WINDOWS */
5905 fn_png_set_background (png_ptr, &frame_background,
5906 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5910 /* Update info structure. */
5911 fn_png_read_update_info (png_ptr, info_ptr);
5913 /* Get number of channels. Valid values are 1 for grayscale images
5914 and images with a palette, 2 for grayscale images with transparency
5915 information (alpha channel), 3 for RGB images, and 4 for RGB
5916 images with alpha channel, i.e. RGBA. If conversions above were
5917 sufficient we should only have 3 or 4 channels here. */
5918 channels = fn_png_get_channels (png_ptr, info_ptr);
5919 eassert (channels == 3 || channels == 4);
5921 /* Number of bytes needed for one row of the image. */
5922 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5924 /* Allocate memory for the image. */
5925 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows < height
5926 || min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height < row_bytes)
5927 memory_full (SIZE_MAX);
5928 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
5929 c->rows = rows = xmalloc (height * sizeof *rows);
5930 for (i = 0; i < height; ++i)
5931 rows[i] = pixels + i * row_bytes;
5933 /* Read the entire image. */
5934 fn_png_read_image (png_ptr, rows);
5935 fn_png_read_end (png_ptr, info_ptr);
5936 if (fp)
5938 fclose (fp);
5939 c->fp = NULL;
5942 /* Create an image and pixmap serving as mask if the PNG image
5943 contains an alpha channel. */
5944 if (channels == 4
5945 && !transparent_p
5946 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
5947 &mask_img, 1))
5949 x_destroy_x_image (ximg);
5950 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
5951 goto error;
5954 /* Fill the X image and mask from PNG data. */
5955 init_color_table ();
5957 for (y = 0; y < height; ++y)
5959 png_byte *p = rows[y];
5961 for (x = 0; x < width; ++x)
5963 int r, g, b;
5965 r = *p++ << 8;
5966 g = *p++ << 8;
5967 b = *p++ << 8;
5968 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5969 /* An alpha channel, aka mask channel, associates variable
5970 transparency with an image. Where other image formats
5971 support binary transparency---fully transparent or fully
5972 opaque---PNG allows up to 254 levels of partial transparency.
5973 The PNG library implements partial transparency by combining
5974 the image with a specified background color.
5976 I'm not sure how to handle this here nicely: because the
5977 background on which the image is displayed may change, for
5978 real alpha channel support, it would be necessary to create
5979 a new image for each possible background.
5981 What I'm doing now is that a mask is created if we have
5982 boolean transparency information. Otherwise I'm using
5983 the frame's background color to combine the image with. */
5985 if (channels == 4)
5987 if (mask_img)
5988 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5989 ++p;
5994 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5995 /* Set IMG's background color from the PNG image, unless the user
5996 overrode it. */
5998 png_color_16 *bg;
5999 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6001 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6002 img->background_valid = 1;
6006 #ifdef COLOR_TABLE_SUPPORT
6007 /* Remember colors allocated for this image. */
6008 img->colors = colors_in_color_table (&img->ncolors);
6009 free_color_table ();
6010 #endif /* COLOR_TABLE_SUPPORT */
6012 /* Clean up. */
6013 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6014 xfree (rows);
6015 xfree (pixels);
6017 img->width = width;
6018 img->height = height;
6020 /* Maybe fill in the background field while we have ximg handy.
6021 Casting avoids a GCC warning. */
6022 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6024 /* Put ximg into the image. */
6025 image_put_x_image (f, img, ximg, 0);
6027 /* Same for the mask. */
6028 if (mask_img)
6030 /* Fill in the background_transparent field while we have the
6031 mask handy. Casting avoids a GCC warning. */
6032 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6034 image_put_x_image (f, img, mask_img, 1);
6037 return 1;
6040 static bool
6041 png_load (struct frame *f, struct image *img)
6043 struct png_load_context c;
6044 return png_load_body (f, img, &c);
6047 #else /* HAVE_PNG */
6049 #ifdef HAVE_NS
6050 static bool
6051 png_load (struct frame *f, struct image *img)
6053 return ns_load_image (f, img,
6054 image_spec_value (img->spec, QCfile, NULL),
6055 image_spec_value (img->spec, QCdata, NULL));
6057 #endif /* HAVE_NS */
6060 #endif /* !HAVE_PNG */
6064 /***********************************************************************
6065 JPEG
6066 ***********************************************************************/
6068 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6070 static bool jpeg_image_p (Lisp_Object object);
6071 static bool jpeg_load (struct frame *f, struct image *img);
6073 /* The symbol `jpeg' identifying images of this type. */
6075 static Lisp_Object Qjpeg;
6077 /* Indices of image specification fields in gs_format, below. */
6079 enum jpeg_keyword_index
6081 JPEG_TYPE,
6082 JPEG_DATA,
6083 JPEG_FILE,
6084 JPEG_ASCENT,
6085 JPEG_MARGIN,
6086 JPEG_RELIEF,
6087 JPEG_ALGORITHM,
6088 JPEG_HEURISTIC_MASK,
6089 JPEG_MASK,
6090 JPEG_BACKGROUND,
6091 JPEG_LAST
6094 /* Vector of image_keyword structures describing the format
6095 of valid user-defined image specifications. */
6097 static const struct image_keyword jpeg_format[JPEG_LAST] =
6099 {":type", IMAGE_SYMBOL_VALUE, 1},
6100 {":data", IMAGE_STRING_VALUE, 0},
6101 {":file", IMAGE_STRING_VALUE, 0},
6102 {":ascent", IMAGE_ASCENT_VALUE, 0},
6103 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6104 {":relief", IMAGE_INTEGER_VALUE, 0},
6105 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6106 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6107 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6108 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6111 #if defined HAVE_NTGUI && defined WINDOWSNT
6112 static bool init_jpeg_functions (void);
6113 #else
6114 #define init_jpeg_functions NULL
6115 #endif
6117 /* Structure describing the image type `jpeg'. */
6119 static struct image_type jpeg_type =
6121 &Qjpeg,
6122 jpeg_image_p,
6123 jpeg_load,
6124 x_clear_image,
6125 init_jpeg_functions,
6126 NULL
6129 /* Return true if OBJECT is a valid JPEG image specification. */
6131 static bool
6132 jpeg_image_p (Lisp_Object object)
6134 struct image_keyword fmt[JPEG_LAST];
6136 memcpy (fmt, jpeg_format, sizeof fmt);
6138 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6139 return 0;
6141 /* Must specify either the :data or :file keyword. */
6142 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6145 #endif /* HAVE_JPEG || HAVE_NS */
6147 #ifdef HAVE_JPEG
6149 /* Work around a warning about HAVE_STDLIB_H being redefined in
6150 jconfig.h. */
6151 #ifdef HAVE_STDLIB_H
6152 #undef HAVE_STDLIB_H
6153 #endif /* HAVE_STLIB_H */
6155 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6156 /* In older releases of the jpeg library, jpeglib.h will define boolean
6157 differently depending on __WIN32__, so make sure it is defined. */
6158 #define __WIN32__ 1
6159 #endif
6161 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6162 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6163 using the Windows boolean type instead of the jpeglib boolean type
6164 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6165 headers are included along with windows.h, so under Cygwin, jpeglib
6166 attempts to define a conflicting boolean type. Worse, forcing
6167 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6168 because it created an ABI incompatibility between the
6169 already-compiled jpeg library and the header interface definition.
6171 The best we can do is to define jpeglib's boolean type to a
6172 different name. This name, jpeg_boolean, remains in effect through
6173 the rest of image.c.
6175 #if defined CYGWIN && defined HAVE_NTGUI
6176 #define boolean jpeg_boolean
6177 #endif
6178 #include <jpeglib.h>
6179 #include <jerror.h>
6181 #ifdef WINDOWSNT
6183 /* JPEG library details. */
6184 DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6185 DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6186 DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6187 DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6188 DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6189 DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6190 DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6191 DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6193 static bool
6194 init_jpeg_functions (void)
6196 HMODULE library;
6198 if (!(library = w32_delayed_load (Qjpeg)))
6199 return 0;
6201 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6202 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6203 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6204 LOAD_IMGLIB_FN (library, jpeg_read_header);
6205 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6206 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6207 LOAD_IMGLIB_FN (library, jpeg_std_error);
6208 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6209 return 1;
6212 /* Wrapper since we can't directly assign the function pointer
6213 to another function pointer that was declared more completely easily. */
6214 static boolean
6215 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6217 return fn_jpeg_resync_to_restart (cinfo, desired);
6220 #else
6222 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
6223 #define fn_jpeg_start_decompress jpeg_start_decompress
6224 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6225 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6226 #define fn_jpeg_read_header jpeg_read_header
6227 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6228 #define fn_jpeg_std_error jpeg_std_error
6229 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6231 #endif /* WINDOWSNT */
6233 struct my_jpeg_error_mgr
6235 struct jpeg_error_mgr pub;
6236 sys_jmp_buf setjmp_buffer;
6238 /* The remaining members are so that longjmp doesn't munge local
6239 variables. */
6240 struct jpeg_decompress_struct cinfo;
6241 enum
6243 MY_JPEG_ERROR_EXIT,
6244 MY_JPEG_INVALID_IMAGE_SIZE,
6245 MY_JPEG_CANNOT_CREATE_X
6246 } failure_code;
6247 #ifdef lint
6248 FILE *fp;
6249 #endif
6253 static _Noreturn void
6254 my_error_exit (j_common_ptr cinfo)
6256 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6257 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6258 sys_longjmp (mgr->setjmp_buffer, 1);
6262 /* Init source method for JPEG data source manager. Called by
6263 jpeg_read_header() before any data is actually read. See
6264 libjpeg.doc from the JPEG lib distribution. */
6266 static void
6267 our_common_init_source (j_decompress_ptr cinfo)
6272 /* Method to terminate data source. Called by
6273 jpeg_finish_decompress() after all data has been processed. */
6275 static void
6276 our_common_term_source (j_decompress_ptr cinfo)
6281 /* Fill input buffer method for JPEG data source manager. Called
6282 whenever more data is needed. We read the whole image in one step,
6283 so this only adds a fake end of input marker at the end. */
6285 static JOCTET our_memory_buffer[2];
6287 static boolean
6288 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6290 /* Insert a fake EOI marker. */
6291 struct jpeg_source_mgr *src = cinfo->src;
6293 our_memory_buffer[0] = (JOCTET) 0xFF;
6294 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6296 src->next_input_byte = our_memory_buffer;
6297 src->bytes_in_buffer = 2;
6298 return 1;
6302 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6303 is the JPEG data source manager. */
6305 static void
6306 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6308 struct jpeg_source_mgr *src = cinfo->src;
6310 if (src)
6312 if (num_bytes > src->bytes_in_buffer)
6313 ERREXIT (cinfo, JERR_INPUT_EOF);
6315 src->bytes_in_buffer -= num_bytes;
6316 src->next_input_byte += num_bytes;
6321 /* Set up the JPEG lib for reading an image from DATA which contains
6322 LEN bytes. CINFO is the decompression info structure created for
6323 reading the image. */
6325 static void
6326 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6328 struct jpeg_source_mgr *src = cinfo->src;
6330 if (! src)
6332 /* First time for this JPEG object? */
6333 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6334 JPOOL_PERMANENT, sizeof *src);
6335 cinfo->src = src;
6336 src->next_input_byte = data;
6339 src->init_source = our_common_init_source;
6340 src->fill_input_buffer = our_memory_fill_input_buffer;
6341 src->skip_input_data = our_memory_skip_input_data;
6342 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6343 src->term_source = our_common_term_source;
6344 src->bytes_in_buffer = len;
6345 src->next_input_byte = data;
6349 struct jpeg_stdio_mgr
6351 struct jpeg_source_mgr mgr;
6352 boolean finished;
6353 FILE *file;
6354 JOCTET *buffer;
6358 /* Size of buffer to read JPEG from file.
6359 Not too big, as we want to use alloc_small. */
6360 #define JPEG_STDIO_BUFFER_SIZE 8192
6363 /* Fill input buffer method for JPEG data source manager. Called
6364 whenever more data is needed. The data is read from a FILE *. */
6366 static boolean
6367 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6369 struct jpeg_stdio_mgr *src;
6371 src = (struct jpeg_stdio_mgr *) cinfo->src;
6372 if (!src->finished)
6374 ptrdiff_t bytes;
6376 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6377 if (bytes > 0)
6378 src->mgr.bytes_in_buffer = bytes;
6379 else
6381 WARNMS (cinfo, JWRN_JPEG_EOF);
6382 src->finished = 1;
6383 src->buffer[0] = (JOCTET) 0xFF;
6384 src->buffer[1] = (JOCTET) JPEG_EOI;
6385 src->mgr.bytes_in_buffer = 2;
6387 src->mgr.next_input_byte = src->buffer;
6390 return 1;
6394 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6395 is the JPEG data source manager. */
6397 static void
6398 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6400 struct jpeg_stdio_mgr *src;
6401 src = (struct jpeg_stdio_mgr *) cinfo->src;
6403 while (num_bytes > 0 && !src->finished)
6405 if (num_bytes <= src->mgr.bytes_in_buffer)
6407 src->mgr.bytes_in_buffer -= num_bytes;
6408 src->mgr.next_input_byte += num_bytes;
6409 break;
6411 else
6413 num_bytes -= src->mgr.bytes_in_buffer;
6414 src->mgr.bytes_in_buffer = 0;
6415 src->mgr.next_input_byte = NULL;
6417 our_stdio_fill_input_buffer (cinfo);
6423 /* Set up the JPEG lib for reading an image from a FILE *.
6424 CINFO is the decompression info structure created for
6425 reading the image. */
6427 static void
6428 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6430 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6432 if (! src)
6434 /* First time for this JPEG object? */
6435 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6436 JPOOL_PERMANENT, sizeof *src);
6437 cinfo->src = (struct jpeg_source_mgr *) src;
6438 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6439 JPOOL_PERMANENT,
6440 JPEG_STDIO_BUFFER_SIZE);
6443 src->file = fp;
6444 src->finished = 0;
6445 src->mgr.init_source = our_common_init_source;
6446 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6447 src->mgr.skip_input_data = our_stdio_skip_input_data;
6448 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6449 src->mgr.term_source = our_common_term_source;
6450 src->mgr.bytes_in_buffer = 0;
6451 src->mgr.next_input_byte = NULL;
6455 /* Load image IMG for use on frame F. Patterned after example.c
6456 from the JPEG lib. */
6458 static bool
6459 jpeg_load_body (struct frame *f, struct image *img,
6460 struct my_jpeg_error_mgr *mgr)
6462 Lisp_Object file, specified_file;
6463 Lisp_Object specified_data;
6464 FILE *fp = NULL;
6465 JSAMPARRAY buffer;
6466 int row_stride, x, y;
6467 XImagePtr ximg = NULL;
6468 unsigned long *colors;
6469 int width, height;
6471 /* Open the JPEG file. */
6472 specified_file = image_spec_value (img->spec, QCfile, NULL);
6473 specified_data = image_spec_value (img->spec, QCdata, NULL);
6475 if (NILP (specified_data))
6477 file = x_find_image_file (specified_file);
6478 if (!STRINGP (file))
6480 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6481 return 0;
6484 fp = emacs_fopen (SSDATA (file), "rb");
6485 if (fp == NULL)
6487 image_error ("Cannot open `%s'", file, Qnil);
6488 return 0;
6491 else if (!STRINGP (specified_data))
6493 image_error ("Invalid image data `%s'", specified_data, Qnil);
6494 return 0;
6497 IF_LINT (mgr->fp = fp);
6499 /* Customize libjpeg's error handling to call my_error_exit when an
6500 error is detected. This function will perform a longjmp. */
6501 mgr->cinfo.err = fn_jpeg_std_error (&mgr->pub);
6502 mgr->pub.error_exit = my_error_exit;
6503 if (sys_setjmp (mgr->setjmp_buffer))
6505 switch (mgr->failure_code)
6507 case MY_JPEG_ERROR_EXIT:
6509 char buf[JMSG_LENGTH_MAX];
6510 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6511 image_error ("Error reading JPEG image `%s': %s", img->spec,
6512 build_string (buf));
6513 break;
6516 case MY_JPEG_INVALID_IMAGE_SIZE:
6517 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6518 break;
6520 case MY_JPEG_CANNOT_CREATE_X:
6521 break;
6524 /* Close the input file and destroy the JPEG object. */
6525 if (fp)
6526 fclose (fp);
6527 fn_jpeg_destroy_decompress (&mgr->cinfo);
6529 /* If we already have an XImage, free that. */
6530 x_destroy_x_image (ximg);
6532 /* Free pixmap and colors. */
6533 x_clear_image (f, img);
6534 return 0;
6537 /* Silence a bogus diagnostic; see GCC bug 54561. */
6538 IF_LINT (fp = mgr->fp);
6540 /* Create the JPEG decompression object. Let it read from fp.
6541 Read the JPEG image header. */
6542 fn_jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6544 if (NILP (specified_data))
6545 jpeg_file_src (&mgr->cinfo, fp);
6546 else
6547 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6548 SBYTES (specified_data));
6550 fn_jpeg_read_header (&mgr->cinfo, 1);
6552 /* Customize decompression so that color quantization will be used.
6553 Start decompression. */
6554 mgr->cinfo.quantize_colors = 1;
6555 fn_jpeg_start_decompress (&mgr->cinfo);
6556 width = img->width = mgr->cinfo.output_width;
6557 height = img->height = mgr->cinfo.output_height;
6559 if (!check_image_size (f, width, height))
6561 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6562 sys_longjmp (mgr->setjmp_buffer, 1);
6565 /* Create X image and pixmap. */
6566 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6568 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6569 sys_longjmp (mgr->setjmp_buffer, 1);
6572 /* Allocate colors. When color quantization is used,
6573 mgr->cinfo.actual_number_of_colors has been set with the number of
6574 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6575 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6576 No more than 255 colors will be generated. */
6578 int i, ir, ig, ib;
6580 if (mgr->cinfo.out_color_components > 2)
6581 ir = 0, ig = 1, ib = 2;
6582 else if (mgr->cinfo.out_color_components > 1)
6583 ir = 0, ig = 1, ib = 0;
6584 else
6585 ir = 0, ig = 0, ib = 0;
6587 /* Use the color table mechanism because it handles colors that
6588 cannot be allocated nicely. Such colors will be replaced with
6589 a default color, and we don't have to care about which colors
6590 can be freed safely, and which can't. */
6591 init_color_table ();
6592 colors = alloca (mgr->cinfo.actual_number_of_colors * sizeof *colors);
6594 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6596 /* Multiply RGB values with 255 because X expects RGB values
6597 in the range 0..0xffff. */
6598 int r = mgr->cinfo.colormap[ir][i] << 8;
6599 int g = mgr->cinfo.colormap[ig][i] << 8;
6600 int b = mgr->cinfo.colormap[ib][i] << 8;
6601 colors[i] = lookup_rgb_color (f, r, g, b);
6604 #ifdef COLOR_TABLE_SUPPORT
6605 /* Remember those colors actually allocated. */
6606 img->colors = colors_in_color_table (&img->ncolors);
6607 free_color_table ();
6608 #endif /* COLOR_TABLE_SUPPORT */
6611 /* Read pixels. */
6612 row_stride = width * mgr->cinfo.output_components;
6613 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6614 JPOOL_IMAGE, row_stride, 1);
6615 for (y = 0; y < height; ++y)
6617 fn_jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6618 for (x = 0; x < mgr->cinfo.output_width; ++x)
6619 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6622 /* Clean up. */
6623 fn_jpeg_finish_decompress (&mgr->cinfo);
6624 fn_jpeg_destroy_decompress (&mgr->cinfo);
6625 if (fp)
6626 fclose (fp);
6628 /* Maybe fill in the background field while we have ximg handy. */
6629 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6630 /* Casting avoids a GCC warning. */
6631 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6633 /* Put ximg into the image. */
6634 image_put_x_image (f, img, ximg, 0);
6635 return 1;
6638 static bool
6639 jpeg_load (struct frame *f, struct image *img)
6641 struct my_jpeg_error_mgr mgr;
6642 return jpeg_load_body (f, img, &mgr);
6645 #else /* HAVE_JPEG */
6647 #ifdef HAVE_NS
6648 static bool
6649 jpeg_load (struct frame *f, struct image *img)
6651 return ns_load_image (f, img,
6652 image_spec_value (img->spec, QCfile, NULL),
6653 image_spec_value (img->spec, QCdata, NULL));
6655 #endif /* HAVE_NS */
6657 #endif /* !HAVE_JPEG */
6661 /***********************************************************************
6662 TIFF
6663 ***********************************************************************/
6665 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6667 static bool tiff_image_p (Lisp_Object object);
6668 static bool tiff_load (struct frame *f, struct image *img);
6670 /* The symbol `tiff' identifying images of this type. */
6672 static Lisp_Object Qtiff;
6674 /* Indices of image specification fields in tiff_format, below. */
6676 enum tiff_keyword_index
6678 TIFF_TYPE,
6679 TIFF_DATA,
6680 TIFF_FILE,
6681 TIFF_ASCENT,
6682 TIFF_MARGIN,
6683 TIFF_RELIEF,
6684 TIFF_ALGORITHM,
6685 TIFF_HEURISTIC_MASK,
6686 TIFF_MASK,
6687 TIFF_BACKGROUND,
6688 TIFF_INDEX,
6689 TIFF_LAST
6692 /* Vector of image_keyword structures describing the format
6693 of valid user-defined image specifications. */
6695 static const struct image_keyword tiff_format[TIFF_LAST] =
6697 {":type", IMAGE_SYMBOL_VALUE, 1},
6698 {":data", IMAGE_STRING_VALUE, 0},
6699 {":file", IMAGE_STRING_VALUE, 0},
6700 {":ascent", IMAGE_ASCENT_VALUE, 0},
6701 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6702 {":relief", IMAGE_INTEGER_VALUE, 0},
6703 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6704 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6705 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6706 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6707 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6710 #if defined HAVE_NTGUI && defined WINDOWSNT
6711 static bool init_tiff_functions (void);
6712 #else
6713 #define init_tiff_functions NULL
6714 #endif
6716 /* Structure describing the image type `tiff'. */
6718 static struct image_type tiff_type =
6720 &Qtiff,
6721 tiff_image_p,
6722 tiff_load,
6723 x_clear_image,
6724 init_tiff_functions,
6725 NULL
6728 /* Return true if OBJECT is a valid TIFF image specification. */
6730 static bool
6731 tiff_image_p (Lisp_Object object)
6733 struct image_keyword fmt[TIFF_LAST];
6734 memcpy (fmt, tiff_format, sizeof fmt);
6736 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6737 return 0;
6739 /* Must specify either the :data or :file keyword. */
6740 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6743 #endif /* HAVE_TIFF || HAVE_NS */
6745 #ifdef HAVE_TIFF
6747 #include <tiffio.h>
6749 #ifdef WINDOWSNT
6751 /* TIFF library details. */
6752 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6753 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6754 DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6755 DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
6756 TIFFReadWriteProc, TIFFReadWriteProc,
6757 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6758 TIFFMapFileProc, TIFFUnmapFileProc));
6759 DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6760 DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6761 DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6762 DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6764 static bool
6765 init_tiff_functions (void)
6767 HMODULE library;
6769 if (!(library = w32_delayed_load (Qtiff)))
6770 return 0;
6772 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6773 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6774 LOAD_IMGLIB_FN (library, TIFFOpen);
6775 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6776 LOAD_IMGLIB_FN (library, TIFFGetField);
6777 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6778 LOAD_IMGLIB_FN (library, TIFFClose);
6779 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6780 return 1;
6783 #else
6785 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6786 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6787 #define fn_TIFFOpen TIFFOpen
6788 #define fn_TIFFClientOpen TIFFClientOpen
6789 #define fn_TIFFGetField TIFFGetField
6790 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6791 #define fn_TIFFClose TIFFClose
6792 #define fn_TIFFSetDirectory TIFFSetDirectory
6793 #endif /* WINDOWSNT */
6796 /* Reading from a memory buffer for TIFF images Based on the PNG
6797 memory source, but we have to provide a lot of extra functions.
6798 Blah.
6800 We really only need to implement read and seek, but I am not
6801 convinced that the TIFF library is smart enough not to destroy
6802 itself if we only hand it the function pointers we need to
6803 override. */
6805 typedef struct
6807 unsigned char *bytes;
6808 ptrdiff_t len;
6809 ptrdiff_t index;
6811 tiff_memory_source;
6813 static tsize_t
6814 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6816 tiff_memory_source *src = (tiff_memory_source *) data;
6818 size = min (size, src->len - src->index);
6819 memcpy (buf, src->bytes + src->index, size);
6820 src->index += size;
6821 return size;
6824 static tsize_t
6825 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6827 return -1;
6830 static toff_t
6831 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6833 tiff_memory_source *src = (tiff_memory_source *) data;
6834 ptrdiff_t idx;
6836 switch (whence)
6838 case SEEK_SET: /* Go from beginning of source. */
6839 idx = off;
6840 break;
6842 case SEEK_END: /* Go from end of source. */
6843 idx = src->len + off;
6844 break;
6846 case SEEK_CUR: /* Go from current position. */
6847 idx = src->index + off;
6848 break;
6850 default: /* Invalid `whence'. */
6851 return -1;
6854 if (idx > src->len || idx < 0)
6855 return -1;
6857 src->index = idx;
6858 return src->index;
6861 static int
6862 tiff_close_memory (thandle_t data)
6864 /* NOOP */
6865 return 0;
6868 static int
6869 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6871 /* It is already _IN_ memory. */
6872 return 0;
6875 static void
6876 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6878 /* We don't need to do this. */
6881 static toff_t
6882 tiff_size_of_memory (thandle_t data)
6884 return ((tiff_memory_source *) data)->len;
6887 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6888 compiler error compiling tiff_handler, see Bugzilla bug #17406
6889 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6890 this function as external works around that problem. */
6891 #if defined (__MINGW32__) && __GNUC__ == 3
6892 # define MINGW_STATIC
6893 #else
6894 # define MINGW_STATIC static
6895 #endif
6897 MINGW_STATIC void
6898 tiff_handler (const char *, const char *, const char *, va_list)
6899 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6900 MINGW_STATIC void
6901 tiff_handler (const char *log_format, const char *title,
6902 const char *format, va_list ap)
6904 /* doprnt is not suitable here, as TIFF handlers are called from
6905 libtiff and are passed arbitrary printf directives. Instead, use
6906 vsnprintf, taking care to be portable to nonstandard environments
6907 where vsnprintf returns -1 on buffer overflow. Since it's just a
6908 log entry, it's OK to truncate it. */
6909 char buf[4000];
6910 int len = vsnprintf (buf, sizeof buf, format, ap);
6911 add_to_log (log_format, build_string (title),
6912 make_string (buf, max (0, min (len, sizeof buf - 1))));
6914 #undef MINGW_STATIC
6916 static void tiff_error_handler (const char *, const char *, va_list)
6917 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6918 static void
6919 tiff_error_handler (const char *title, const char *format, va_list ap)
6921 tiff_handler ("TIFF error: %s %s", title, format, ap);
6925 static void tiff_warning_handler (const char *, const char *, va_list)
6926 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6927 static void
6928 tiff_warning_handler (const char *title, const char *format, va_list ap)
6930 tiff_handler ("TIFF warning: %s %s", title, format, ap);
6934 /* Load TIFF image IMG for use on frame F. Value is true if
6935 successful. */
6937 static bool
6938 tiff_load (struct frame *f, struct image *img)
6940 Lisp_Object file, specified_file;
6941 Lisp_Object specified_data;
6942 TIFF *tiff;
6943 int width, height, x, y, count;
6944 uint32 *buf;
6945 int rc;
6946 XImagePtr ximg;
6947 tiff_memory_source memsrc;
6948 Lisp_Object image;
6950 specified_file = image_spec_value (img->spec, QCfile, NULL);
6951 specified_data = image_spec_value (img->spec, QCdata, NULL);
6953 fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6954 fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
6956 if (NILP (specified_data))
6958 /* Read from a file */
6959 file = x_find_image_file (specified_file);
6960 if (!STRINGP (file))
6962 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6963 return 0;
6966 /* Try to open the image file. */
6967 tiff = fn_TIFFOpen (SSDATA (file), "r");
6968 if (tiff == NULL)
6970 image_error ("Cannot open `%s'", file, Qnil);
6971 return 0;
6974 else
6976 if (!STRINGP (specified_data))
6978 image_error ("Invalid image data `%s'", specified_data, Qnil);
6979 return 0;
6982 /* Memory source! */
6983 memsrc.bytes = SDATA (specified_data);
6984 memsrc.len = SBYTES (specified_data);
6985 memsrc.index = 0;
6987 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
6988 tiff_read_from_memory,
6989 tiff_write_from_memory,
6990 tiff_seek_in_memory,
6991 tiff_close_memory,
6992 tiff_size_of_memory,
6993 tiff_mmap_memory,
6994 tiff_unmap_memory);
6996 if (!tiff)
6998 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6999 return 0;
7003 image = image_spec_value (img->spec, QCindex, NULL);
7004 if (INTEGERP (image))
7006 EMACS_INT ino = XFASTINT (image);
7007 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7008 && fn_TIFFSetDirectory (tiff, ino)))
7010 image_error ("Invalid image number `%s' in image `%s'",
7011 image, img->spec);
7012 fn_TIFFClose (tiff);
7013 return 0;
7017 /* Get width and height of the image, and allocate a raster buffer
7018 of width x height 32-bit values. */
7019 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7020 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7022 if (!check_image_size (f, width, height))
7024 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7025 fn_TIFFClose (tiff);
7026 return 0;
7029 /* Create the X image and pixmap. */
7030 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7031 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7032 &ximg, 0)))
7034 fn_TIFFClose (tiff);
7035 return 0;
7038 buf = xmalloc (sizeof *buf * width * height);
7040 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7042 /* Count the number of images in the file. */
7043 for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
7044 continue;
7046 if (count > 1)
7047 img->lisp_data = Fcons (Qcount,
7048 Fcons (make_number (count),
7049 img->lisp_data));
7051 fn_TIFFClose (tiff);
7052 if (!rc)
7054 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7055 xfree (buf);
7056 return 0;
7059 /* Initialize the color table. */
7060 init_color_table ();
7062 /* Process the pixel raster. Origin is in the lower-left corner. */
7063 for (y = 0; y < height; ++y)
7065 uint32 *row = buf + y * width;
7067 for (x = 0; x < width; ++x)
7069 uint32 abgr = row[x];
7070 int r = TIFFGetR (abgr) << 8;
7071 int g = TIFFGetG (abgr) << 8;
7072 int b = TIFFGetB (abgr) << 8;
7073 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7077 #ifdef COLOR_TABLE_SUPPORT
7078 /* Remember the colors allocated for the image. Free the color table. */
7079 img->colors = colors_in_color_table (&img->ncolors);
7080 free_color_table ();
7081 #endif /* COLOR_TABLE_SUPPORT */
7083 img->width = width;
7084 img->height = height;
7086 /* Maybe fill in the background field while we have ximg handy. */
7087 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7088 /* Casting avoids a GCC warning on W32. */
7089 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7091 /* Put ximg into the image. */
7092 image_put_x_image (f, img, ximg, 0);
7093 xfree (buf);
7095 return 1;
7098 #else /* HAVE_TIFF */
7100 #ifdef HAVE_NS
7101 static bool
7102 tiff_load (struct frame *f, struct image *img)
7104 return ns_load_image (f, img,
7105 image_spec_value (img->spec, QCfile, NULL),
7106 image_spec_value (img->spec, QCdata, NULL));
7108 #endif /* HAVE_NS */
7110 #endif /* !HAVE_TIFF */
7114 /***********************************************************************
7116 ***********************************************************************/
7118 #if defined (HAVE_GIF) || defined (HAVE_NS)
7120 static bool gif_image_p (Lisp_Object object);
7121 static bool gif_load (struct frame *f, struct image *img);
7122 static void gif_clear_image (struct frame *f, struct image *img);
7124 /* The symbol `gif' identifying images of this type. */
7126 static Lisp_Object Qgif;
7128 /* Indices of image specification fields in gif_format, below. */
7130 enum gif_keyword_index
7132 GIF_TYPE,
7133 GIF_DATA,
7134 GIF_FILE,
7135 GIF_ASCENT,
7136 GIF_MARGIN,
7137 GIF_RELIEF,
7138 GIF_ALGORITHM,
7139 GIF_HEURISTIC_MASK,
7140 GIF_MASK,
7141 GIF_IMAGE,
7142 GIF_BACKGROUND,
7143 GIF_LAST
7146 /* Vector of image_keyword structures describing the format
7147 of valid user-defined image specifications. */
7149 static const struct image_keyword gif_format[GIF_LAST] =
7151 {":type", IMAGE_SYMBOL_VALUE, 1},
7152 {":data", IMAGE_STRING_VALUE, 0},
7153 {":file", IMAGE_STRING_VALUE, 0},
7154 {":ascent", IMAGE_ASCENT_VALUE, 0},
7155 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7156 {":relief", IMAGE_INTEGER_VALUE, 0},
7157 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7158 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7159 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7160 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7161 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7164 #if defined HAVE_NTGUI && defined WINDOWSNT
7165 static bool init_gif_functions (void);
7166 #else
7167 #define init_gif_functions NULL
7168 #endif
7170 /* Structure describing the image type `gif'. */
7172 static struct image_type gif_type =
7174 &Qgif,
7175 gif_image_p,
7176 gif_load,
7177 gif_clear_image,
7178 init_gif_functions,
7179 NULL
7182 /* Free X resources of GIF image IMG which is used on frame F. */
7184 static void
7185 gif_clear_image (struct frame *f, struct image *img)
7187 img->lisp_data = Qnil;
7188 x_clear_image (f, img);
7191 /* Return true if OBJECT is a valid GIF image specification. */
7193 static bool
7194 gif_image_p (Lisp_Object object)
7196 struct image_keyword fmt[GIF_LAST];
7197 memcpy (fmt, gif_format, sizeof fmt);
7199 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7200 return 0;
7202 /* Must specify either the :data or :file keyword. */
7203 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7206 #endif /* HAVE_GIF */
7208 #ifdef HAVE_GIF
7210 #if defined (HAVE_NTGUI)
7211 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7212 Undefine before redefining to avoid a preprocessor warning. */
7213 #ifdef DrawText
7214 #undef DrawText
7215 #endif
7216 /* avoid conflict with QuickdrawText.h */
7217 #define DrawText gif_DrawText
7218 #include <gif_lib.h>
7219 #undef DrawText
7221 #else /* HAVE_NTGUI */
7223 #include <gif_lib.h>
7225 #endif /* HAVE_NTGUI */
7228 #ifdef WINDOWSNT
7230 /* GIF library details. */
7231 DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7232 DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7233 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7234 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
7236 static bool
7237 init_gif_functions (void)
7239 HMODULE library;
7241 if (!(library = w32_delayed_load (Qgif)))
7242 return 0;
7244 LOAD_IMGLIB_FN (library, DGifCloseFile);
7245 LOAD_IMGLIB_FN (library, DGifSlurp);
7246 LOAD_IMGLIB_FN (library, DGifOpen);
7247 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7248 return 1;
7251 #else
7253 #define fn_DGifCloseFile DGifCloseFile
7254 #define fn_DGifSlurp DGifSlurp
7255 #define fn_DGifOpen DGifOpen
7256 #define fn_DGifOpenFileName DGifOpenFileName
7258 #endif /* WINDOWSNT */
7260 /* Reading a GIF image from memory
7261 Based on the PNG memory stuff to a certain extent. */
7263 typedef struct
7265 unsigned char *bytes;
7266 ptrdiff_t len;
7267 ptrdiff_t index;
7269 gif_memory_source;
7271 /* Make the current memory source available to gif_read_from_memory.
7272 It's done this way because not all versions of libungif support
7273 a UserData field in the GifFileType structure. */
7274 static gif_memory_source *current_gif_memory_src;
7276 static int
7277 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7279 gif_memory_source *src = current_gif_memory_src;
7281 if (len > src->len - src->index)
7282 return -1;
7284 memcpy (buf, src->bytes + src->index, len);
7285 src->index += len;
7286 return len;
7290 /* Load GIF image IMG for use on frame F. Value is true if
7291 successful. */
7293 static const int interlace_start[] = {0, 4, 2, 1};
7294 static const int interlace_increment[] = {8, 8, 4, 2};
7296 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7298 static bool
7299 gif_load (struct frame *f, struct image *img)
7301 Lisp_Object file;
7302 int rc, width, height, x, y, i, j;
7303 XImagePtr ximg;
7304 ColorMapObject *gif_color_map;
7305 unsigned long pixel_colors[256];
7306 GifFileType *gif;
7307 gif_memory_source memsrc;
7308 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7309 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7310 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7311 unsigned long bgcolor = 0;
7312 EMACS_INT idx;
7314 if (NILP (specified_data))
7316 file = x_find_image_file (specified_file);
7317 if (!STRINGP (file))
7319 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7320 return 0;
7323 /* Open the GIF file. */
7324 gif = fn_DGifOpenFileName (SSDATA (file));
7325 if (gif == NULL)
7327 image_error ("Cannot open `%s'", file, Qnil);
7328 return 0;
7331 else
7333 if (!STRINGP (specified_data))
7335 image_error ("Invalid image data `%s'", specified_data, Qnil);
7336 return 0;
7339 /* Read from memory! */
7340 current_gif_memory_src = &memsrc;
7341 memsrc.bytes = SDATA (specified_data);
7342 memsrc.len = SBYTES (specified_data);
7343 memsrc.index = 0;
7345 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
7346 if (!gif)
7348 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7349 return 0;
7353 /* Before reading entire contents, check the declared image size. */
7354 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7356 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7357 fn_DGifCloseFile (gif);
7358 return 0;
7361 /* Read entire contents. */
7362 rc = fn_DGifSlurp (gif);
7363 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7365 image_error ("Error reading `%s'", img->spec, Qnil);
7366 fn_DGifCloseFile (gif);
7367 return 0;
7370 /* Which sub-image are we to display? */
7372 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7373 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7374 if (idx < 0 || idx >= gif->ImageCount)
7376 image_error ("Invalid image number `%s' in image `%s'",
7377 image_number, img->spec);
7378 fn_DGifCloseFile (gif);
7379 return 0;
7383 width = img->width = gif->SWidth;
7384 height = img->height = gif->SHeight;
7386 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7387 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7388 img->corners[BOT_CORNER]
7389 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7390 img->corners[RIGHT_CORNER]
7391 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7393 if (!check_image_size (f, width, height))
7395 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7396 fn_DGifCloseFile (gif);
7397 return 0;
7400 /* Check that the selected subimages fit. It's not clear whether
7401 the GIF spec requires this, but Emacs can crash if they don't fit. */
7402 for (j = 0; j <= idx; ++j)
7404 struct SavedImage *subimage = gif->SavedImages + j;
7405 int subimg_width = subimage->ImageDesc.Width;
7406 int subimg_height = subimage->ImageDesc.Height;
7407 int subimg_top = subimage->ImageDesc.Top;
7408 int subimg_left = subimage->ImageDesc.Left;
7409 if (! (0 <= subimg_width && 0 <= subimg_height
7410 && 0 <= subimg_top && subimg_top <= height - subimg_height
7411 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7413 image_error ("Subimage does not fit in image", Qnil, Qnil);
7414 fn_DGifCloseFile (gif);
7415 return 0;
7419 /* Create the X image and pixmap. */
7420 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7422 fn_DGifCloseFile (gif);
7423 return 0;
7426 /* Clear the part of the screen image not covered by the image.
7427 Full animated GIF support requires more here (see the gif89 spec,
7428 disposal methods). Let's simply assume that the part not covered
7429 by a sub-image is in the frame's background color. */
7430 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7431 for (x = 0; x < width; ++x)
7432 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7434 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7435 for (x = 0; x < width; ++x)
7436 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7438 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7440 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7441 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7442 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7443 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7446 /* Read the GIF image into the X image. */
7448 /* FIXME: With the current implementation, loading an animated gif
7449 is quadratic in the number of animation frames, since each frame
7450 is a separate struct image. We must provide a way for a single
7451 gif_load call to construct and save all animation frames. */
7453 init_color_table ();
7454 if (STRINGP (specified_bg))
7455 bgcolor = x_alloc_image_color (f, img, specified_bg,
7456 FRAME_BACKGROUND_PIXEL (f));
7457 for (j = 0; j <= idx; ++j)
7459 /* We use a local variable `raster' here because RasterBits is a
7460 char *, which invites problems with bytes >= 0x80. */
7461 struct SavedImage *subimage = gif->SavedImages + j;
7462 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7463 int transparency_color_index = -1;
7464 int disposal = 0;
7465 int subimg_width = subimage->ImageDesc.Width;
7466 int subimg_height = subimage->ImageDesc.Height;
7467 int subimg_top = subimage->ImageDesc.Top;
7468 int subimg_left = subimage->ImageDesc.Left;
7470 /* Find the Graphic Control Extension block for this sub-image.
7471 Extract the disposal method and transparency color. */
7472 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7474 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7476 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7477 && extblock->ByteCount == 4
7478 && extblock->Bytes[0] & 1)
7480 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7481 to background". Treat any other value like 2. */
7482 disposal = (extblock->Bytes[0] >> 2) & 7;
7483 transparency_color_index = (unsigned char) extblock->Bytes[3];
7484 break;
7488 /* We can't "keep in place" the first subimage. */
7489 if (j == 0)
7490 disposal = 2;
7492 /* For disposal == 0, the spec says "No disposal specified. The
7493 decoder is not required to take any action." In practice, it
7494 seems we need to treat this like "keep in place", see e.g.
7495 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7496 if (disposal == 0)
7497 disposal = 1;
7499 /* Allocate subimage colors. */
7500 memset (pixel_colors, 0, sizeof pixel_colors);
7501 gif_color_map = subimage->ImageDesc.ColorMap;
7502 if (!gif_color_map)
7503 gif_color_map = gif->SColorMap;
7505 if (gif_color_map)
7506 for (i = 0; i < gif_color_map->ColorCount; ++i)
7508 if (transparency_color_index == i)
7509 pixel_colors[i] = STRINGP (specified_bg)
7510 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7511 else
7513 int r = gif_color_map->Colors[i].Red << 8;
7514 int g = gif_color_map->Colors[i].Green << 8;
7515 int b = gif_color_map->Colors[i].Blue << 8;
7516 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7520 /* Apply the pixel values. */
7521 if (gif->SavedImages[j].ImageDesc.Interlace)
7523 int row, pass;
7525 for (y = 0, row = interlace_start[0], pass = 0;
7526 y < subimg_height;
7527 y++, row += interlace_increment[pass])
7529 while (subimg_height <= row)
7531 lint_assume (pass < 3);
7532 row = interlace_start[++pass];
7535 for (x = 0; x < subimg_width; x++)
7537 int c = raster[y * subimg_width + x];
7538 if (transparency_color_index != c || disposal != 1)
7539 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7540 pixel_colors[c]);
7544 else
7546 for (y = 0; y < subimg_height; ++y)
7547 for (x = 0; x < subimg_width; ++x)
7549 int c = raster[y * subimg_width + x];
7550 if (transparency_color_index != c || disposal != 1)
7551 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7552 pixel_colors[c]);
7557 #ifdef COLOR_TABLE_SUPPORT
7558 img->colors = colors_in_color_table (&img->ncolors);
7559 free_color_table ();
7560 #endif /* COLOR_TABLE_SUPPORT */
7562 /* Save GIF image extension data for `image-metadata'.
7563 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7564 img->lisp_data = Qnil;
7565 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7567 int delay = 0;
7568 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7569 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7570 /* Append (... FUNCTION "BYTES") */
7572 img->lisp_data
7573 = Fcons (make_number (ext->Function),
7574 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7575 img->lisp_data));
7576 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7577 && ext->ByteCount == 4)
7579 delay = ext->Bytes[2] << CHAR_BIT;
7580 delay |= ext->Bytes[1];
7583 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7584 if (delay)
7585 img->lisp_data
7586 = Fcons (Qdelay,
7587 Fcons (make_float (delay / 100.0),
7588 img->lisp_data));
7591 if (gif->ImageCount > 1)
7592 img->lisp_data = Fcons (Qcount,
7593 Fcons (make_number (gif->ImageCount),
7594 img->lisp_data));
7596 fn_DGifCloseFile (gif);
7598 /* Maybe fill in the background field while we have ximg handy. */
7599 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7600 /* Casting avoids a GCC warning. */
7601 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7603 /* Put ximg into the image. */
7604 image_put_x_image (f, img, ximg, 0);
7606 return 1;
7609 #else /* !HAVE_GIF */
7611 #ifdef HAVE_NS
7612 static bool
7613 gif_load (struct frame *f, struct image *img)
7615 return ns_load_image (f, img,
7616 image_spec_value (img->spec, QCfile, NULL),
7617 image_spec_value (img->spec, QCdata, NULL));
7619 #endif /* HAVE_NS */
7621 #endif /* HAVE_GIF */
7624 #ifdef HAVE_IMAGEMAGICK
7626 /***********************************************************************
7627 ImageMagick
7628 ***********************************************************************/
7630 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
7631 safely rounded and clipped to int range. */
7633 static int
7634 scale_image_size (int size, size_t divisor, size_t multiplier)
7636 if (divisor != 0)
7638 double s = size;
7639 double scaled = s * multiplier / divisor + 0.5;
7640 if (scaled < INT_MAX)
7641 return scaled;
7643 return INT_MAX;
7646 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
7647 Use SPEC to deduce the size. Store the desired size into
7648 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
7649 static void
7650 compute_image_size (size_t width, size_t height,
7651 Lisp_Object spec,
7652 int *d_width, int *d_height)
7654 Lisp_Object value;
7655 int desired_width, desired_height;
7657 /* If width and/or height is set in the display spec assume we want
7658 to scale to those values. If either h or w is unspecified, the
7659 unspecified should be calculated from the specified to preserve
7660 aspect ratio. */
7661 value = image_spec_value (spec, QCwidth, NULL);
7662 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7663 value = image_spec_value (spec, QCheight, NULL);
7664 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7666 if (desired_width == -1)
7668 value = image_spec_value (spec, QCmax_width, NULL);
7669 if (NATNUMP (value))
7671 int max_width = min (XFASTINT (value), INT_MAX);
7672 if (max_width < width)
7674 /* The image is wider than :max-width. */
7675 desired_width = max_width;
7676 if (desired_height == -1)
7678 desired_height = scale_image_size (desired_width,
7679 width, height);
7680 value = image_spec_value (spec, QCmax_height, NULL);
7681 if (NATNUMP (value))
7683 int max_height = min (XFASTINT (value), INT_MAX);
7684 if (max_height < desired_height)
7686 desired_height = max_height;
7687 desired_width = scale_image_size (desired_height,
7688 height, width);
7696 if (desired_height == -1)
7698 value = image_spec_value (spec, QCmax_height, NULL);
7699 if (NATNUMP (value))
7701 int max_height = min (XFASTINT (value), INT_MAX);
7702 if (max_height < height)
7703 desired_height = max_height;
7707 if (desired_width != -1 && desired_height == -1)
7708 /* w known, calculate h. */
7709 desired_height = scale_image_size (desired_width, width, height);
7711 if (desired_width == -1 && desired_height != -1)
7712 /* h known, calculate w. */
7713 desired_width = scale_image_size (desired_height, height, width);
7715 *d_width = desired_width;
7716 *d_height = desired_height;
7719 static Lisp_Object Qimagemagick;
7721 static bool imagemagick_image_p (Lisp_Object);
7722 static bool imagemagick_load (struct frame *, struct image *);
7723 static void imagemagick_clear_image (struct frame *, struct image *);
7725 /* Indices of image specification fields in imagemagick_format. */
7727 enum imagemagick_keyword_index
7729 IMAGEMAGICK_TYPE,
7730 IMAGEMAGICK_DATA,
7731 IMAGEMAGICK_FILE,
7732 IMAGEMAGICK_ASCENT,
7733 IMAGEMAGICK_MARGIN,
7734 IMAGEMAGICK_RELIEF,
7735 IMAGEMAGICK_ALGORITHM,
7736 IMAGEMAGICK_HEURISTIC_MASK,
7737 IMAGEMAGICK_MASK,
7738 IMAGEMAGICK_BACKGROUND,
7739 IMAGEMAGICK_HEIGHT,
7740 IMAGEMAGICK_WIDTH,
7741 IMAGEMAGICK_MAX_HEIGHT,
7742 IMAGEMAGICK_MAX_WIDTH,
7743 IMAGEMAGICK_FORMAT,
7744 IMAGEMAGICK_ROTATION,
7745 IMAGEMAGICK_CROP,
7746 IMAGEMAGICK_LAST
7749 /* Vector of image_keyword structures describing the format
7750 of valid user-defined image specifications. */
7752 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7754 {":type", IMAGE_SYMBOL_VALUE, 1},
7755 {":data", IMAGE_STRING_VALUE, 0},
7756 {":file", IMAGE_STRING_VALUE, 0},
7757 {":ascent", IMAGE_ASCENT_VALUE, 0},
7758 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7759 {":relief", IMAGE_INTEGER_VALUE, 0},
7760 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7761 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7762 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7763 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7764 {":height", IMAGE_INTEGER_VALUE, 0},
7765 {":width", IMAGE_INTEGER_VALUE, 0},
7766 {":max-height", IMAGE_INTEGER_VALUE, 0},
7767 {":max-width", IMAGE_INTEGER_VALUE, 0},
7768 {":format", IMAGE_SYMBOL_VALUE, 0},
7769 {":rotation", IMAGE_NUMBER_VALUE, 0},
7770 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7773 #if defined HAVE_NTGUI && defined WINDOWSNT
7774 static bool init_imagemagick_functions (void);
7775 #else
7776 #define init_imagemagick_functions NULL
7777 #endif
7779 /* Structure describing the image type for any image handled via
7780 ImageMagick. */
7782 static struct image_type imagemagick_type =
7784 &Qimagemagick,
7785 imagemagick_image_p,
7786 imagemagick_load,
7787 imagemagick_clear_image,
7788 init_imagemagick_functions,
7789 NULL
7792 /* Free X resources of imagemagick image IMG which is used on frame F. */
7794 static void
7795 imagemagick_clear_image (struct frame *f,
7796 struct image *img)
7798 x_clear_image (f, img);
7801 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7802 this by calling parse_image_spec and supplying the keywords that
7803 identify the IMAGEMAGICK format. */
7805 static bool
7806 imagemagick_image_p (Lisp_Object object)
7808 struct image_keyword fmt[IMAGEMAGICK_LAST];
7809 memcpy (fmt, imagemagick_format, sizeof fmt);
7811 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7812 return 0;
7814 /* Must specify either the :data or :file keyword. */
7815 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7818 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7819 Therefore rename the function so it doesn't collide with ImageMagick. */
7820 #define DrawRectangle DrawRectangleGif
7821 #include <wand/MagickWand.h>
7823 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7824 Emacs seems to work fine with the hidden version, so unhide it. */
7825 #include <magick/version.h>
7826 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7827 extern WandExport void PixelGetMagickColor (const PixelWand *,
7828 MagickPixelPacket *);
7829 #endif
7831 /* Log ImageMagick error message.
7832 Useful when a ImageMagick function returns the status `MagickFalse'. */
7834 static void
7835 imagemagick_error (MagickWand *wand)
7837 char *description;
7838 ExceptionType severity;
7840 description = MagickGetException (wand, &severity);
7841 image_error ("ImageMagick error: %s",
7842 build_string (description),
7843 Qnil);
7844 description = (char *) MagickRelinquishMemory (description);
7847 /* Possibly give ImageMagick some extra help to determine the image
7848 type by supplying a "dummy" filename based on the Content-Type. */
7850 static char *
7851 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
7853 Lisp_Object symbol = intern ("image-format-suffixes");
7854 Lisp_Object val = find_symbol_value (symbol);
7855 Lisp_Object format;
7857 if (! CONSP (val))
7858 return NULL;
7860 format = image_spec_value (spec, intern (":format"), NULL);
7861 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
7862 if (! STRINGP (val))
7863 return NULL;
7865 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
7866 as ImageMagick would ignore the extra bytes anyway. */
7867 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
7868 return hint_buffer;
7871 /* Animated images (e.g., GIF89a) are composed from one "master image"
7872 (which is the first one, and then there's a number of images that
7873 follow. If following images have non-transparent colors, these are
7874 composed "on top" of the master image. So, in general, one has to
7875 compute ann the preceding images to be able to display a particular
7876 sub-image.
7878 Computing all the preceding images is too slow, so we maintain a
7879 cache of previously computed images. We have to maintain a cache
7880 separate from the image cache, because the images may be scaled
7881 before display. */
7883 struct animation_cache
7885 MagickWand *wand;
7886 int index;
7887 struct timespec update_time;
7888 struct animation_cache *next;
7889 char signature[FLEXIBLE_ARRAY_MEMBER];
7892 static struct animation_cache *animation_cache = NULL;
7894 static struct animation_cache *
7895 imagemagick_create_cache (char *signature)
7897 struct animation_cache *cache
7898 = xmalloc (offsetof (struct animation_cache, signature)
7899 + strlen (signature) + 1);
7900 cache->wand = 0;
7901 cache->index = 0;
7902 cache->next = 0;
7903 strcpy (cache->signature, signature);
7904 return cache;
7907 /* Discard cached images that haven't been used for a minute. */
7908 static void
7909 imagemagick_prune_animation_cache (void)
7911 struct animation_cache **pcache = &animation_cache;
7912 struct timespec old = timespec_sub (current_timespec (),
7913 make_timespec (60, 0));
7915 while (*pcache)
7917 struct animation_cache *cache = *pcache;
7918 if (timespec_cmp (old, cache->update_time) <= 0)
7919 pcache = &cache->next;
7920 else
7922 if (cache->wand)
7923 DestroyMagickWand (cache->wand);
7924 *pcache = cache->next;
7925 xfree (cache);
7930 static struct animation_cache *
7931 imagemagick_get_animation_cache (MagickWand *wand)
7933 char *signature = MagickGetImageSignature (wand);
7934 struct animation_cache *cache;
7935 struct animation_cache **pcache = &animation_cache;
7937 imagemagick_prune_animation_cache ();
7939 while (1)
7941 cache = *pcache;
7942 if (! cache)
7944 *pcache = cache = imagemagick_create_cache (signature);
7945 break;
7947 if (strcmp (signature, cache->signature) == 0)
7948 break;
7949 pcache = &cache->next;
7952 DestroyString (signature);
7953 cache->update_time = current_timespec ();
7954 return cache;
7957 static MagickWand *
7958 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
7960 int i;
7961 MagickWand *composite_wand;
7962 size_t dest_width, dest_height;
7963 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
7965 MagickSetIteratorIndex (super_wand, 0);
7967 if (ino == 0 || cache->wand == NULL || cache->index > ino)
7969 composite_wand = MagickGetImage (super_wand);
7970 if (cache->wand)
7971 DestroyMagickWand (cache->wand);
7973 else
7974 composite_wand = cache->wand;
7976 dest_width = MagickGetImageWidth (composite_wand);
7977 dest_height = MagickGetImageHeight (composite_wand);
7979 for (i = max (1, cache->index + 1); i <= ino; i++)
7981 MagickWand *sub_wand;
7982 PixelIterator *source_iterator, *dest_iterator;
7983 PixelWand **source, **dest;
7984 size_t source_width, source_height;
7985 ssize_t source_left, source_top;
7986 MagickPixelPacket pixel;
7987 DisposeType dispose;
7988 ptrdiff_t lines = 0;
7990 MagickSetIteratorIndex (super_wand, i);
7991 sub_wand = MagickGetImage (super_wand);
7993 MagickGetImagePage (sub_wand, &source_width, &source_height,
7994 &source_left, &source_top);
7996 /* This flag says how to handle transparent pixels. */
7997 dispose = MagickGetImageDispose (sub_wand);
7999 source_iterator = NewPixelIterator (sub_wand);
8000 if (! source_iterator)
8002 DestroyMagickWand (composite_wand);
8003 DestroyMagickWand (sub_wand);
8004 cache->wand = NULL;
8005 image_error ("Imagemagick pixel iterator creation failed",
8006 Qnil, Qnil);
8007 return NULL;
8010 dest_iterator = NewPixelIterator (composite_wand);
8011 if (! dest_iterator)
8013 DestroyMagickWand (composite_wand);
8014 DestroyMagickWand (sub_wand);
8015 DestroyPixelIterator (source_iterator);
8016 cache->wand = NULL;
8017 image_error ("Imagemagick pixel iterator creation failed",
8018 Qnil, Qnil);
8019 return NULL;
8022 /* The sub-image may not start at origin, so move the destination
8023 iterator to where the sub-image should start. */
8024 if (source_top > 0)
8026 PixelSetIteratorRow (dest_iterator, source_top);
8027 lines = source_top;
8030 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8031 != NULL)
8033 ptrdiff_t x;
8035 /* Sanity check. This shouldn't happen, but apparently
8036 does in some pictures. */
8037 if (++lines >= dest_height)
8038 break;
8040 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8041 for (x = 0; x < source_width; x++)
8043 /* Sanity check. This shouldn't happen, but apparently
8044 also does in some pictures. */
8045 if (x + source_left > dest_width)
8046 break;
8047 /* Normally we only copy over non-transparent pixels,
8048 but if the disposal method is "Background", then we
8049 copy over all pixels. */
8050 if (dispose == BackgroundDispose ||
8051 PixelGetAlpha (source[x]))
8053 PixelGetMagickColor (source[x], &pixel);
8054 PixelSetMagickColor (dest[x + source_left], &pixel);
8057 PixelSyncIterator (dest_iterator);
8060 DestroyPixelIterator (source_iterator);
8061 DestroyPixelIterator (dest_iterator);
8062 DestroyMagickWand (sub_wand);
8065 /* Cache a copy for the next iteration. The current wand will be
8066 destroyed by the caller. */
8067 cache->wand = CloneMagickWand (composite_wand);
8068 cache->index = ino;
8070 return composite_wand;
8074 /* Helper function for imagemagick_load, which does the actual loading
8075 given contents and size, apart from frame and image structures,
8076 passed from imagemagick_load. Uses librimagemagick to do most of
8077 the image processing.
8079 F is a pointer to the Emacs frame; IMG to the image structure to
8080 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8081 be parsed; SIZE is the number of bytes of data; and FILENAME is
8082 either the file name or the image data.
8084 Return true if successful. */
8086 static bool
8087 imagemagick_load_image (struct frame *f, struct image *img,
8088 unsigned char *contents, unsigned int size,
8089 char *filename)
8091 size_t width, height;
8092 MagickBooleanType status;
8093 XImagePtr ximg;
8094 int x, y;
8095 MagickWand *image_wand;
8096 PixelIterator *iterator;
8097 PixelWand **pixels, *bg_wand = NULL;
8098 MagickPixelPacket pixel;
8099 Lisp_Object image;
8100 Lisp_Object value;
8101 Lisp_Object crop;
8102 EMACS_INT ino;
8103 int desired_width, desired_height;
8104 double rotation;
8105 int pixelwidth;
8106 char hint_buffer[MaxTextExtent];
8107 char *filename_hint = NULL;
8109 /* Handle image index for image types who can contain more than one image.
8110 Interface :index is same as for GIF. First we "ping" the image to see how
8111 many sub-images it contains. Pinging is faster than loading the image to
8112 find out things about it. */
8114 /* Initialize the imagemagick environment. */
8115 MagickWandGenesis ();
8116 image = image_spec_value (img->spec, QCindex, NULL);
8117 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8118 image_wand = NewMagickWand ();
8120 if (filename)
8121 status = MagickReadImage (image_wand, filename);
8122 else
8124 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8125 MagickSetFilename (image_wand, filename_hint);
8126 status = MagickReadImageBlob (image_wand, contents, size);
8129 if (status == MagickFalse)
8131 imagemagick_error (image_wand);
8132 DestroyMagickWand (image_wand);
8133 return 0;
8136 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8138 image_error ("Invalid image number `%s' in image `%s'",
8139 image, img->spec);
8140 DestroyMagickWand (image_wand);
8141 return 0;
8144 if (MagickGetNumberImages (image_wand) > 1)
8145 img->lisp_data =
8146 Fcons (Qcount,
8147 Fcons (make_number (MagickGetNumberImages (image_wand)),
8148 img->lisp_data));
8150 /* If we have an animated image, get the new wand based on the
8151 "super-wand". */
8152 if (MagickGetNumberImages (image_wand) > 1)
8154 MagickWand *super_wand = image_wand;
8155 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8156 if (! image_wand)
8157 image_wand = super_wand;
8158 else
8159 DestroyMagickWand (super_wand);
8162 /* Retrieve the frame's background color, for use later. */
8164 XColor bgcolor;
8165 Lisp_Object specified_bg;
8167 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8168 if (!STRINGP (specified_bg)
8169 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8171 #ifndef HAVE_NS
8172 bgcolor.pixel = FRAME_BACKGROUND_PIXEL (f);
8173 x_query_color (f, &bgcolor);
8174 #else
8175 ns_query_color (FRAME_BACKGROUND_COLOR (f), &bgcolor, 1);
8176 #endif
8179 bg_wand = NewPixelWand ();
8180 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8181 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8182 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8185 compute_image_size (MagickGetImageWidth (image_wand),
8186 MagickGetImageHeight (image_wand),
8187 img->spec, &desired_width, &desired_height);
8189 if (desired_width != -1 && desired_height != -1)
8191 status = MagickScaleImage (image_wand, desired_width, desired_height);
8192 if (status == MagickFalse)
8194 image_error ("Imagemagick scale failed", Qnil, Qnil);
8195 imagemagick_error (image_wand);
8196 goto imagemagick_error;
8200 /* crop behaves similar to image slicing in Emacs but is more memory
8201 efficient. */
8202 crop = image_spec_value (img->spec, QCcrop, NULL);
8204 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8206 /* After some testing, it seems MagickCropImage is the fastest crop
8207 function in ImageMagick. This crop function seems to do less copying
8208 than the alternatives, but it still reads the entire image into memory
8209 before cropping, which is apparently difficult to avoid when using
8210 imagemagick. */
8211 size_t crop_width = XINT (XCAR (crop));
8212 crop = XCDR (crop);
8213 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8215 size_t crop_height = XINT (XCAR (crop));
8216 crop = XCDR (crop);
8217 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8219 ssize_t crop_x = XINT (XCAR (crop));
8220 crop = XCDR (crop);
8221 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8223 ssize_t crop_y = XINT (XCAR (crop));
8224 MagickCropImage (image_wand, crop_width, crop_height,
8225 crop_x, crop_y);
8231 /* Furthermore :rotation. we need background color and angle for
8232 rotation. */
8234 TODO background handling for rotation specified_bg =
8235 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8236 (specified_bg). */
8237 value = image_spec_value (img->spec, QCrotation, NULL);
8238 if (FLOATP (value))
8240 rotation = extract_float (value);
8241 status = MagickRotateImage (image_wand, bg_wand, rotation);
8242 if (status == MagickFalse)
8244 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
8245 imagemagick_error (image_wand);
8246 goto imagemagick_error;
8250 /* Set the canvas background color to the frame or specified
8251 background, and flatten the image. Note: as of ImageMagick
8252 6.6.0, SVG image transparency is not handled properly
8253 (e.g. etc/images/splash.svg shows a white background always). */
8255 MagickWand *new_wand;
8256 MagickSetImageBackgroundColor (image_wand, bg_wand);
8257 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8258 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8259 #else
8260 new_wand = MagickFlattenImages (image_wand);
8261 #endif
8262 DestroyMagickWand (image_wand);
8263 image_wand = new_wand;
8266 /* Finally we are done manipulating the image. Figure out the
8267 resulting width/height and transfer ownership to Emacs. */
8268 height = MagickGetImageHeight (image_wand);
8269 width = MagickGetImageWidth (image_wand);
8271 if (! (width <= INT_MAX && height <= INT_MAX
8272 && check_image_size (f, width, height)))
8274 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8275 goto imagemagick_error;
8278 /* We can now get a valid pixel buffer from the imagemagick file, if all
8279 went ok. */
8281 init_color_table ();
8283 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8284 if (imagemagick_render_type != 0)
8286 /* Magicexportimage is normally faster than pixelpushing. This
8287 method is also well tested. Some aspects of this method are
8288 ad-hoc and needs to be more researched. */
8289 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8290 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8291 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8292 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8293 &ximg, 0))
8295 #ifdef COLOR_TABLE_SUPPORT
8296 free_color_table ();
8297 #endif
8298 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8299 goto imagemagick_error;
8302 /* Oddly, the below code doesn't seem to work:*/
8303 /* switch(ximg->bitmap_unit){ */
8304 /* case 8: */
8305 /* pixelwidth=CharPixel; */
8306 /* break; */
8307 /* case 16: */
8308 /* pixelwidth=ShortPixel; */
8309 /* break; */
8310 /* case 32: */
8311 /* pixelwidth=LongPixel; */
8312 /* break; */
8313 /* } */
8315 Here im just guessing the format of the bitmap.
8316 happens to work fine for:
8317 - bw djvu images
8318 on rgb display.
8319 seems about 3 times as fast as pixel pushing(not carefully measured)
8321 pixelwidth = CharPixel; /*??? TODO figure out*/
8322 MagickExportImagePixels (image_wand, 0, 0, width, height,
8323 exportdepth, pixelwidth, ximg->data);
8325 else
8326 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8328 size_t image_height;
8330 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8331 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8332 &ximg, 0))
8334 #ifdef COLOR_TABLE_SUPPORT
8335 free_color_table ();
8336 #endif
8337 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8338 goto imagemagick_error;
8341 /* Copy imagemagick image to x with primitive yet robust pixel
8342 pusher loop. This has been tested a lot with many different
8343 images. */
8345 /* Copy pixels from the imagemagick image structure to the x image map. */
8346 iterator = NewPixelIterator (image_wand);
8347 if (! iterator)
8349 #ifdef COLOR_TABLE_SUPPORT
8350 free_color_table ();
8351 #endif
8352 x_destroy_x_image (ximg);
8353 image_error ("Imagemagick pixel iterator creation failed",
8354 Qnil, Qnil);
8355 goto imagemagick_error;
8358 image_height = MagickGetImageHeight (image_wand);
8359 for (y = 0; y < image_height; y++)
8361 pixels = PixelGetNextIteratorRow (iterator, &width);
8362 if (! pixels)
8363 break;
8364 for (x = 0; x < (long) width; x++)
8366 PixelGetMagickColor (pixels[x], &pixel);
8367 XPutPixel (ximg, x, y,
8368 lookup_rgb_color (f,
8369 pixel.red,
8370 pixel.green,
8371 pixel.blue));
8374 DestroyPixelIterator (iterator);
8377 #ifdef COLOR_TABLE_SUPPORT
8378 /* Remember colors allocated for this image. */
8379 img->colors = colors_in_color_table (&img->ncolors);
8380 free_color_table ();
8381 #endif /* COLOR_TABLE_SUPPORT */
8383 img->width = width;
8384 img->height = height;
8386 /* Put ximg into the image. */
8387 image_put_x_image (f, img, ximg, 0);
8389 /* Final cleanup. image_wand should be the only resource left. */
8390 DestroyMagickWand (image_wand);
8391 if (bg_wand) DestroyPixelWand (bg_wand);
8393 /* `MagickWandTerminus' terminates the imagemagick environment. */
8394 MagickWandTerminus ();
8396 return 1;
8398 imagemagick_error:
8399 DestroyMagickWand (image_wand);
8400 if (bg_wand) DestroyPixelWand (bg_wand);
8402 MagickWandTerminus ();
8403 /* TODO more cleanup. */
8404 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
8405 return 0;
8409 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8410 successful. this function will go into the imagemagick_type structure, and
8411 the prototype thus needs to be compatible with that structure. */
8413 static bool
8414 imagemagick_load (struct frame *f, struct image *img)
8416 bool success_p = 0;
8417 Lisp_Object file_name;
8419 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8420 file_name = image_spec_value (img->spec, QCfile, NULL);
8421 if (STRINGP (file_name))
8423 Lisp_Object file;
8425 file = x_find_image_file (file_name);
8426 if (!STRINGP (file))
8428 image_error ("Cannot find image file `%s'", file_name, Qnil);
8429 return 0;
8431 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8433 /* Else its not a file, its a lisp object. Load the image from a
8434 lisp object rather than a file. */
8435 else
8437 Lisp_Object data;
8439 data = image_spec_value (img->spec, QCdata, NULL);
8440 if (!STRINGP (data))
8442 image_error ("Invalid image data `%s'", data, Qnil);
8443 return 0;
8445 success_p = imagemagick_load_image (f, img, SDATA (data),
8446 SBYTES (data), NULL);
8449 return success_p;
8452 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8453 doc: /* Return a list of image types supported by ImageMagick.
8454 Each entry in this list is a symbol named after an ImageMagick format
8455 tag. See the ImageMagick manual for a list of ImageMagick formats and
8456 their descriptions (http://www.imagemagick.org/script/formats.php).
8457 You can also try the shell command: `identify -list format'.
8459 Note that ImageMagick recognizes many file-types that Emacs does not
8460 recognize as images, such as C. See `imagemagick-types-enable'
8461 and `imagemagick-types-inhibit'. */)
8462 (void)
8464 Lisp_Object typelist = Qnil;
8465 size_t numf = 0;
8466 ExceptionInfo ex;
8467 char **imtypes;
8468 size_t i;
8469 Lisp_Object Qimagemagicktype;
8471 GetExceptionInfo(&ex);
8472 imtypes = GetMagickList ("*", &numf, &ex);
8473 DestroyExceptionInfo(&ex);
8475 for (i = 0; i < numf; i++)
8477 Qimagemagicktype = intern (imtypes[i]);
8478 typelist = Fcons (Qimagemagicktype, typelist);
8480 return Fnreverse (typelist);
8483 #endif /* defined (HAVE_IMAGEMAGICK) */
8487 /***********************************************************************
8489 ***********************************************************************/
8491 #if defined (HAVE_RSVG)
8493 /* Function prototypes. */
8495 static bool svg_image_p (Lisp_Object object);
8496 static bool svg_load (struct frame *f, struct image *img);
8498 static bool svg_load_image (struct frame *, struct image *,
8499 unsigned char *, ptrdiff_t);
8501 /* The symbol `svg' identifying images of this type. */
8503 static Lisp_Object Qsvg;
8505 /* Indices of image specification fields in svg_format, below. */
8507 enum svg_keyword_index
8509 SVG_TYPE,
8510 SVG_DATA,
8511 SVG_FILE,
8512 SVG_ASCENT,
8513 SVG_MARGIN,
8514 SVG_RELIEF,
8515 SVG_ALGORITHM,
8516 SVG_HEURISTIC_MASK,
8517 SVG_MASK,
8518 SVG_BACKGROUND,
8519 SVG_LAST
8522 /* Vector of image_keyword structures describing the format
8523 of valid user-defined image specifications. */
8525 static const struct image_keyword svg_format[SVG_LAST] =
8527 {":type", IMAGE_SYMBOL_VALUE, 1},
8528 {":data", IMAGE_STRING_VALUE, 0},
8529 {":file", IMAGE_STRING_VALUE, 0},
8530 {":ascent", IMAGE_ASCENT_VALUE, 0},
8531 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8532 {":relief", IMAGE_INTEGER_VALUE, 0},
8533 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8534 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8535 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8536 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8539 #if defined HAVE_NTGUI && defined WINDOWSNT
8540 static bool init_svg_functions (void);
8541 #else
8542 #define init_svg_functions NULL
8543 #endif
8545 /* Structure describing the image type `svg'. Its the same type of
8546 structure defined for all image formats, handled by emacs image
8547 functions. See struct image_type in dispextern.h. */
8549 static struct image_type svg_type =
8551 &Qsvg,
8552 svg_image_p,
8553 svg_load,
8554 x_clear_image,
8555 init_svg_functions,
8556 NULL
8560 /* Return true if OBJECT is a valid SVG image specification. Do
8561 this by calling parse_image_spec and supplying the keywords that
8562 identify the SVG format. */
8564 static bool
8565 svg_image_p (Lisp_Object object)
8567 struct image_keyword fmt[SVG_LAST];
8568 memcpy (fmt, svg_format, sizeof fmt);
8570 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8571 return 0;
8573 /* Must specify either the :data or :file keyword. */
8574 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8577 #include <librsvg/rsvg.h>
8579 #ifdef WINDOWSNT
8581 /* SVG library functions. */
8582 DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new, (void));
8583 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions, (RsvgHandle *, RsvgDimensionData *));
8584 DEF_IMGLIB_FN (gboolean, rsvg_handle_write, (RsvgHandle *, const guchar *, gsize, GError **));
8585 DEF_IMGLIB_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8586 DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8587 DEF_IMGLIB_FN (void *, rsvg_handle_set_size_callback, (RsvgHandle *, RsvgSizeFunc, gpointer, GDestroyNotify));
8589 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8590 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8591 DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8592 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8593 DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8594 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8595 DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8596 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8598 DEF_IMGLIB_FN (void, g_type_init, (void));
8599 DEF_IMGLIB_FN (void, g_object_unref, (gpointer));
8600 DEF_IMGLIB_FN (void, g_error_free, (GError *));
8602 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8604 static bool
8605 init_svg_functions (void)
8607 HMODULE library, gdklib, glib, gobject;
8609 if (!(glib = w32_delayed_load (Qglib))
8610 || !(gobject = w32_delayed_load (Qgobject))
8611 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
8612 || !(library = w32_delayed_load (Qsvg)))
8613 return 0;
8615 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8616 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8617 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8618 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8619 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8621 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8622 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8623 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8624 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8625 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8626 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8627 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8628 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8630 LOAD_IMGLIB_FN (gobject, g_type_init);
8631 LOAD_IMGLIB_FN (gobject, g_object_unref);
8632 LOAD_IMGLIB_FN (glib, g_error_free);
8634 return 1;
8637 #else
8638 /* The following aliases for library functions allow dynamic loading
8639 to be used on some platforms. */
8640 #define fn_rsvg_handle_new rsvg_handle_new
8641 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8642 #define fn_rsvg_handle_write rsvg_handle_write
8643 #define fn_rsvg_handle_close rsvg_handle_close
8644 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8646 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8647 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8648 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8649 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8650 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8651 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8652 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8653 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8655 #define fn_g_type_init g_type_init
8656 #define fn_g_object_unref g_object_unref
8657 #define fn_g_error_free g_error_free
8658 #endif /* !WINDOWSNT */
8660 /* Load SVG image IMG for use on frame F. Value is true if
8661 successful. */
8663 static bool
8664 svg_load (struct frame *f, struct image *img)
8666 bool success_p = 0;
8667 Lisp_Object file_name;
8669 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8670 file_name = image_spec_value (img->spec, QCfile, NULL);
8671 if (STRINGP (file_name))
8673 Lisp_Object file;
8674 unsigned char *contents;
8675 ptrdiff_t size;
8677 file = x_find_image_file (file_name);
8678 if (!STRINGP (file))
8680 image_error ("Cannot find image file `%s'", file_name, Qnil);
8681 return 0;
8684 /* Read the entire file into memory. */
8685 contents = slurp_file (SSDATA (file), &size);
8686 if (contents == NULL)
8688 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8689 return 0;
8691 /* If the file was slurped into memory properly, parse it. */
8692 success_p = svg_load_image (f, img, contents, size);
8693 xfree (contents);
8695 /* Else its not a file, its a lisp object. Load the image from a
8696 lisp object rather than a file. */
8697 else
8699 Lisp_Object data;
8701 data = image_spec_value (img->spec, QCdata, NULL);
8702 if (!STRINGP (data))
8704 image_error ("Invalid image data `%s'", data, Qnil);
8705 return 0;
8707 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8710 return success_p;
8713 /* svg_load_image is a helper function for svg_load, which does the
8714 actual loading given contents and size, apart from frame and image
8715 structures, passed from svg_load.
8717 Uses librsvg to do most of the image processing.
8719 Returns true when successful. */
8720 static bool
8721 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8722 struct image *img, /* Pointer to emacs image structure. */
8723 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8724 ptrdiff_t size) /* Size of data in bytes. */
8726 RsvgHandle *rsvg_handle;
8727 RsvgDimensionData dimension_data;
8728 GError *err = NULL;
8729 GdkPixbuf *pixbuf;
8730 int width;
8731 int height;
8732 const guint8 *pixels;
8733 int rowstride;
8734 XImagePtr ximg;
8735 Lisp_Object specified_bg;
8736 XColor background;
8737 int x;
8738 int y;
8740 /* g_type_init is a glib function that must be called prior to using
8741 gnome type library functions. */
8742 fn_g_type_init ();
8743 /* Make a handle to a new rsvg object. */
8744 rsvg_handle = fn_rsvg_handle_new ();
8746 /* Parse the contents argument and fill in the rsvg_handle. */
8747 fn_rsvg_handle_write (rsvg_handle, contents, size, &err);
8748 if (err) goto rsvg_error;
8750 /* The parsing is complete, rsvg_handle is ready to used, close it
8751 for further writes. */
8752 fn_rsvg_handle_close (rsvg_handle, &err);
8753 if (err) goto rsvg_error;
8755 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8756 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8758 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8759 goto rsvg_error;
8762 /* We can now get a valid pixel buffer from the svg file, if all
8763 went ok. */
8764 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8765 if (!pixbuf) goto rsvg_error;
8766 fn_g_object_unref (rsvg_handle);
8768 /* Extract some meta data from the svg handle. */
8769 width = fn_gdk_pixbuf_get_width (pixbuf);
8770 height = fn_gdk_pixbuf_get_height (pixbuf);
8771 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8772 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8774 /* Validate the svg meta data. */
8775 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8776 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8777 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8778 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8780 /* Try to create a x pixmap to hold the svg pixmap. */
8781 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
8783 fn_g_object_unref (pixbuf);
8784 return 0;
8787 init_color_table ();
8789 /* Handle alpha channel by combining the image with a background
8790 color. */
8791 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8792 if (!STRINGP (specified_bg)
8793 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
8795 #ifndef HAVE_NS
8796 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8797 x_query_color (f, &background);
8798 #else
8799 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8800 #endif
8803 /* SVG pixmaps specify transparency in the last byte, so right
8804 shift 8 bits to get rid of it, since emacs doesn't support
8805 transparency. */
8806 background.red >>= 8;
8807 background.green >>= 8;
8808 background.blue >>= 8;
8810 /* This loop handles opacity values, since Emacs assumes
8811 non-transparent images. Each pixel must be "flattened" by
8812 calculating the resulting color, given the transparency of the
8813 pixel, and the image background color. */
8814 for (y = 0; y < height; ++y)
8816 for (x = 0; x < width; ++x)
8818 int red;
8819 int green;
8820 int blue;
8821 int opacity;
8823 red = *pixels++;
8824 green = *pixels++;
8825 blue = *pixels++;
8826 opacity = *pixels++;
8828 red = ((red * opacity)
8829 + (background.red * ((1 << 8) - opacity)));
8830 green = ((green * opacity)
8831 + (background.green * ((1 << 8) - opacity)));
8832 blue = ((blue * opacity)
8833 + (background.blue * ((1 << 8) - opacity)));
8835 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8838 pixels += rowstride - 4 * width;
8841 #ifdef COLOR_TABLE_SUPPORT
8842 /* Remember colors allocated for this image. */
8843 img->colors = colors_in_color_table (&img->ncolors);
8844 free_color_table ();
8845 #endif /* COLOR_TABLE_SUPPORT */
8847 fn_g_object_unref (pixbuf);
8849 img->width = width;
8850 img->height = height;
8852 /* Maybe fill in the background field while we have ximg handy.
8853 Casting avoids a GCC warning. */
8854 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8856 /* Put ximg into the image. */
8857 image_put_x_image (f, img, ximg, 0);
8859 return 1;
8861 rsvg_error:
8862 fn_g_object_unref (rsvg_handle);
8863 /* FIXME: Use error->message so the user knows what is the actual
8864 problem with the image. */
8865 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8866 fn_g_error_free (err);
8867 return 0;
8870 #endif /* defined (HAVE_RSVG) */
8875 /***********************************************************************
8876 Ghostscript
8877 ***********************************************************************/
8879 #ifdef HAVE_X_WINDOWS
8880 #define HAVE_GHOSTSCRIPT 1
8881 #endif /* HAVE_X_WINDOWS */
8883 #ifdef HAVE_GHOSTSCRIPT
8885 static bool gs_image_p (Lisp_Object object);
8886 static bool gs_load (struct frame *f, struct image *img);
8887 static void gs_clear_image (struct frame *f, struct image *img);
8889 /* Keyword symbols. */
8891 static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8893 /* Indices of image specification fields in gs_format, below. */
8895 enum gs_keyword_index
8897 GS_TYPE,
8898 GS_PT_WIDTH,
8899 GS_PT_HEIGHT,
8900 GS_FILE,
8901 GS_LOADER,
8902 GS_BOUNDING_BOX,
8903 GS_ASCENT,
8904 GS_MARGIN,
8905 GS_RELIEF,
8906 GS_ALGORITHM,
8907 GS_HEURISTIC_MASK,
8908 GS_MASK,
8909 GS_BACKGROUND,
8910 GS_LAST
8913 /* Vector of image_keyword structures describing the format
8914 of valid user-defined image specifications. */
8916 static const struct image_keyword gs_format[GS_LAST] =
8918 {":type", IMAGE_SYMBOL_VALUE, 1},
8919 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8920 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8921 {":file", IMAGE_STRING_VALUE, 1},
8922 {":loader", IMAGE_FUNCTION_VALUE, 0},
8923 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8924 {":ascent", IMAGE_ASCENT_VALUE, 0},
8925 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8926 {":relief", IMAGE_INTEGER_VALUE, 0},
8927 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8928 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8929 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8930 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8933 /* Structure describing the image type `ghostscript'. */
8935 static struct image_type gs_type =
8937 &Qpostscript,
8938 gs_image_p,
8939 gs_load,
8940 gs_clear_image,
8941 NULL,
8942 NULL
8946 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8948 static void
8949 gs_clear_image (struct frame *f, struct image *img)
8951 x_clear_image (f, img);
8955 /* Return true if OBJECT is a valid Ghostscript image
8956 specification. */
8958 static bool
8959 gs_image_p (Lisp_Object object)
8961 struct image_keyword fmt[GS_LAST];
8962 Lisp_Object tem;
8963 int i;
8965 memcpy (fmt, gs_format, sizeof fmt);
8967 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8968 return 0;
8970 /* Bounding box must be a list or vector containing 4 integers. */
8971 tem = fmt[GS_BOUNDING_BOX].value;
8972 if (CONSP (tem))
8974 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8975 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8976 return 0;
8977 if (!NILP (tem))
8978 return 0;
8980 else if (VECTORP (tem))
8982 if (ASIZE (tem) != 4)
8983 return 0;
8984 for (i = 0; i < 4; ++i)
8985 if (!INTEGERP (AREF (tem, i)))
8986 return 0;
8988 else
8989 return 0;
8991 return 1;
8995 /* Load Ghostscript image IMG for use on frame F. Value is true
8996 if successful. */
8998 static bool
8999 gs_load (struct frame *f, struct image *img)
9001 uprintmax_t printnum1, printnum2;
9002 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9003 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9004 Lisp_Object frame;
9005 double in_width, in_height;
9006 Lisp_Object pixel_colors = Qnil;
9008 /* Compute pixel size of pixmap needed from the given size in the
9009 image specification. Sizes in the specification are in pt. 1 pt
9010 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9011 info. */
9012 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9013 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9014 in_width *= FRAME_RES_X (f);
9015 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9016 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9017 in_height *= FRAME_RES_Y (f);
9019 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9020 && check_image_size (f, in_width, in_height)))
9022 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
9023 return 0;
9025 img->width = in_width;
9026 img->height = in_height;
9028 /* Create the pixmap. */
9029 eassert (img->pixmap == NO_PIXMAP);
9031 if (x_check_image_size (0, img->width, img->height))
9033 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9034 block_input ();
9035 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9036 img->width, img->height,
9037 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9038 unblock_input ();
9041 if (!img->pixmap)
9043 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
9044 return 0;
9047 /* Call the loader to fill the pixmap. It returns a process object
9048 if successful. We do not record_unwind_protect here because
9049 other places in redisplay like calling window scroll functions
9050 don't either. Let the Lisp loader use `unwind-protect' instead. */
9051 printnum1 = FRAME_X_WINDOW (f);
9052 printnum2 = img->pixmap;
9053 window_and_pixmap_id
9054 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9056 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9057 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9058 pixel_colors
9059 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9061 XSETFRAME (frame, f);
9062 loader = image_spec_value (img->spec, QCloader, NULL);
9063 if (NILP (loader))
9064 loader = intern ("gs-load-image");
9066 img->lisp_data = call6 (loader, frame, img->spec,
9067 make_number (img->width),
9068 make_number (img->height),
9069 window_and_pixmap_id,
9070 pixel_colors);
9071 return PROCESSP (img->lisp_data);
9075 /* Kill the Ghostscript process that was started to fill PIXMAP on
9076 frame F. Called from XTread_socket when receiving an event
9077 telling Emacs that Ghostscript has finished drawing. */
9079 void
9080 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9082 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9083 int class;
9084 ptrdiff_t i;
9085 struct image *img;
9087 /* Find the image containing PIXMAP. */
9088 for (i = 0; i < c->used; ++i)
9089 if (c->images[i]->pixmap == pixmap)
9090 break;
9092 /* Should someone in between have cleared the image cache, for
9093 instance, give up. */
9094 if (i == c->used)
9095 return;
9097 /* Kill the GS process. We should have found PIXMAP in the image
9098 cache and its image should contain a process object. */
9099 img = c->images[i];
9100 eassert (PROCESSP (img->lisp_data));
9101 Fkill_process (img->lisp_data, Qnil);
9102 img->lisp_data = Qnil;
9104 #if defined (HAVE_X_WINDOWS)
9106 /* On displays with a mutable colormap, figure out the colors
9107 allocated for the image by looking at the pixels of an XImage for
9108 img->pixmap. */
9109 class = FRAME_X_VISUAL (f)->class;
9110 if (class != StaticColor && class != StaticGray && class != TrueColor)
9112 XImagePtr ximg;
9114 block_input ();
9116 /* Try to get an XImage for img->pixmep. */
9117 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9118 0, 0, img->width, img->height, ~0, ZPixmap);
9119 if (ximg)
9121 int x, y;
9123 /* Initialize the color table. */
9124 init_color_table ();
9126 /* For each pixel of the image, look its color up in the
9127 color table. After having done so, the color table will
9128 contain an entry for each color used by the image. */
9129 for (y = 0; y < img->height; ++y)
9130 for (x = 0; x < img->width; ++x)
9132 unsigned long pixel = XGetPixel (ximg, x, y);
9133 lookup_pixel_color (f, pixel);
9136 /* Record colors in the image. Free color table and XImage. */
9137 #ifdef COLOR_TABLE_SUPPORT
9138 img->colors = colors_in_color_table (&img->ncolors);
9139 free_color_table ();
9140 #endif
9141 XDestroyImage (ximg);
9143 #if 0 /* This doesn't seem to be the case. If we free the colors
9144 here, we get a BadAccess later in x_clear_image when
9145 freeing the colors. */
9146 /* We have allocated colors once, but Ghostscript has also
9147 allocated colors on behalf of us. So, to get the
9148 reference counts right, free them once. */
9149 if (img->ncolors)
9150 x_free_colors (f, img->colors, img->ncolors);
9151 #endif
9153 else
9154 image_error ("Cannot get X image of `%s'; colors will not be freed",
9155 img->spec, Qnil);
9157 unblock_input ();
9159 #endif /* HAVE_X_WINDOWS */
9161 /* Now that we have the pixmap, compute mask and transform the
9162 image if requested. */
9163 block_input ();
9164 postprocess_image (f, img);
9165 unblock_input ();
9168 #endif /* HAVE_GHOSTSCRIPT */
9171 /***********************************************************************
9172 Tests
9173 ***********************************************************************/
9175 #ifdef GLYPH_DEBUG
9177 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9178 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9179 (Lisp_Object spec)
9181 return valid_image_p (spec) ? Qt : Qnil;
9185 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
9186 (Lisp_Object spec)
9188 ptrdiff_t id = -1;
9190 if (valid_image_p (spec))
9191 id = lookup_image (SELECTED_FRAME (), spec);
9193 debug_print (spec);
9194 return make_number (id);
9197 #endif /* GLYPH_DEBUG */
9200 /***********************************************************************
9201 Initialization
9202 ***********************************************************************/
9204 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9205 doc: /* Initialize image library implementing image type TYPE.
9206 Return non-nil if TYPE is a supported image type.
9208 If image libraries are loaded dynamically (currently only the case on
9209 MS-Windows), load the library for TYPE if it is not yet loaded, using
9210 the library file(s) specified by `dynamic-library-alist'. */)
9211 (Lisp_Object type)
9213 return lookup_image_type (type) ? Qt : Qnil;
9216 /* Look up image type TYPE, and return a pointer to its image_type
9217 structure. Return 0 if TYPE is not a known image type. */
9219 static struct image_type *
9220 lookup_image_type (Lisp_Object type)
9222 /* Types pbm and xbm are built-in and always available. */
9223 if (EQ (type, Qpbm))
9224 return define_image_type (&pbm_type);
9226 if (EQ (type, Qxbm))
9227 return define_image_type (&xbm_type);
9229 #if defined (HAVE_XPM) || defined (HAVE_NS)
9230 if (EQ (type, Qxpm))
9231 return define_image_type (&xpm_type);
9232 #endif
9234 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9235 if (EQ (type, Qjpeg))
9236 return define_image_type (&jpeg_type);
9237 #endif
9239 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9240 if (EQ (type, Qtiff))
9241 return define_image_type (&tiff_type);
9242 #endif
9244 #if defined (HAVE_GIF) || defined (HAVE_NS)
9245 if (EQ (type, Qgif))
9246 return define_image_type (&gif_type);
9247 #endif
9249 #if defined (HAVE_PNG) || defined (HAVE_NS)
9250 if (EQ (type, Qpng))
9251 return define_image_type (&png_type);
9252 #endif
9254 #if defined (HAVE_RSVG)
9255 if (EQ (type, Qsvg))
9256 return define_image_type (&svg_type);
9257 #endif
9259 #if defined (HAVE_IMAGEMAGICK)
9260 if (EQ (type, Qimagemagick))
9261 return define_image_type (&imagemagick_type);
9262 #endif
9264 #ifdef HAVE_GHOSTSCRIPT
9265 if (EQ (type, Qpostscript))
9266 return define_image_type (&gs_type);
9267 #endif
9269 return NULL;
9272 /* Reset image_types before dumping.
9273 Called from Fdump_emacs. */
9275 void
9276 reset_image_types (void)
9278 while (image_types)
9280 struct image_type *next = image_types->next;
9281 xfree (image_types);
9282 image_types = next;
9286 void
9287 syms_of_image (void)
9289 /* Initialize this only once; it will be reset before dumping. */
9290 image_types = NULL;
9292 /* Must be defined now because we're going to update it below, while
9293 defining the supported image types. */
9294 DEFVAR_LISP ("image-types", Vimage_types,
9295 doc: /* List of potentially supported image types.
9296 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9297 To check whether it is really supported, use `image-type-available-p'. */);
9298 Vimage_types = Qnil;
9300 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9301 doc: /* Maximum size of images.
9302 Emacs will not load an image into memory if its pixel width or
9303 pixel height exceeds this limit.
9305 If the value is an integer, it directly specifies the maximum
9306 image height and width, measured in pixels. If it is a floating
9307 point number, it specifies the maximum image height and width
9308 as a ratio to the frame height and width. If the value is
9309 non-numeric, there is no explicit limit on the size of images. */);
9310 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9312 DEFSYM (Qcount, "count");
9313 DEFSYM (Qextension_data, "extension-data");
9314 DEFSYM (Qdelay, "delay");
9316 DEFSYM (QCascent, ":ascent");
9317 DEFSYM (QCmargin, ":margin");
9318 DEFSYM (QCrelief, ":relief");
9319 DEFSYM (QCconversion, ":conversion");
9320 DEFSYM (QCcolor_symbols, ":color-symbols");
9321 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9322 DEFSYM (QCindex, ":index");
9323 DEFSYM (QCgeometry, ":geometry");
9324 DEFSYM (QCcrop, ":crop");
9325 DEFSYM (QCrotation, ":rotation");
9326 DEFSYM (QCmatrix, ":matrix");
9327 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9328 DEFSYM (QCmask, ":mask");
9330 DEFSYM (Qlaplace, "laplace");
9331 DEFSYM (Qemboss, "emboss");
9332 DEFSYM (Qedge_detection, "edge-detection");
9333 DEFSYM (Qheuristic, "heuristic");
9335 DEFSYM (Qpostscript, "postscript");
9336 DEFSYM (QCmax_width, ":max-width");
9337 DEFSYM (QCmax_height, ":max-height");
9338 #ifdef HAVE_GHOSTSCRIPT
9339 ADD_IMAGE_TYPE (Qpostscript);
9340 DEFSYM (QCloader, ":loader");
9341 DEFSYM (QCbounding_box, ":bounding-box");
9342 DEFSYM (QCpt_width, ":pt-width");
9343 DEFSYM (QCpt_height, ":pt-height");
9344 #endif /* HAVE_GHOSTSCRIPT */
9346 #ifdef HAVE_NTGUI
9347 DEFSYM (Qlibpng_version, "libpng-version");
9348 Fset (Qlibpng_version,
9349 #if HAVE_PNG
9350 make_number (PNG_LIBPNG_VER)
9351 #else
9352 make_number (-1)
9353 #endif
9355 #endif
9357 DEFSYM (Qpbm, "pbm");
9358 ADD_IMAGE_TYPE (Qpbm);
9360 DEFSYM (Qxbm, "xbm");
9361 ADD_IMAGE_TYPE (Qxbm);
9363 #if defined (HAVE_XPM) || defined (HAVE_NS)
9364 DEFSYM (Qxpm, "xpm");
9365 ADD_IMAGE_TYPE (Qxpm);
9366 #endif
9368 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9369 DEFSYM (Qjpeg, "jpeg");
9370 ADD_IMAGE_TYPE (Qjpeg);
9371 #endif
9373 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9374 DEFSYM (Qtiff, "tiff");
9375 ADD_IMAGE_TYPE (Qtiff);
9376 #endif
9378 #if defined (HAVE_GIF) || defined (HAVE_NS)
9379 DEFSYM (Qgif, "gif");
9380 ADD_IMAGE_TYPE (Qgif);
9381 #endif
9383 #if defined (HAVE_PNG) || defined (HAVE_NS)
9384 DEFSYM (Qpng, "png");
9385 ADD_IMAGE_TYPE (Qpng);
9386 #endif
9388 #if defined (HAVE_IMAGEMAGICK)
9389 DEFSYM (Qimagemagick, "imagemagick");
9390 ADD_IMAGE_TYPE (Qimagemagick);
9391 #endif
9393 #if defined (HAVE_RSVG)
9394 DEFSYM (Qsvg, "svg");
9395 ADD_IMAGE_TYPE (Qsvg);
9396 #ifdef HAVE_NTGUI
9397 /* Other libraries used directly by svg code. */
9398 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9399 DEFSYM (Qglib, "glib");
9400 DEFSYM (Qgobject, "gobject");
9401 #endif /* HAVE_NTGUI */
9402 #endif /* HAVE_RSVG */
9404 defsubr (&Sinit_image_library);
9405 #ifdef HAVE_IMAGEMAGICK
9406 defsubr (&Simagemagick_types);
9407 #endif
9408 defsubr (&Sclear_image_cache);
9409 defsubr (&Simage_flush);
9410 defsubr (&Simage_size);
9411 defsubr (&Simage_mask_p);
9412 defsubr (&Simage_metadata);
9414 #ifdef GLYPH_DEBUG
9415 defsubr (&Simagep);
9416 defsubr (&Slookup_image);
9417 #endif
9419 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9420 doc: /* Non-nil means always draw a cross over disabled images.
9421 Disabled images are those having a `:conversion disabled' property.
9422 A cross is always drawn on black & white displays. */);
9423 cross_disabled_images = 0;
9425 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9426 doc: /* List of directories to search for window system bitmap files. */);
9427 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS);
9429 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9430 doc: /* Maximum time after which images are removed from the cache.
9431 When an image has not been displayed this many seconds, Emacs
9432 automatically removes it from the image cache. If the cache contains
9433 a large number of images, the actual eviction time may be shorter.
9434 The value can also be nil, meaning the cache is never cleared.
9436 The function `clear-image-cache' disregards this variable. */);
9437 Vimage_cache_eviction_delay = make_number (300);
9438 #ifdef HAVE_IMAGEMAGICK
9439 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9440 doc: /* Integer indicating which ImageMagick rendering method to use.
9441 The options are:
9442 0 -- the default method (pixel pushing)
9443 1 -- a newer method ("MagickExportImagePixels") that may perform
9444 better (speed etc) in some cases, but has not been as thoroughly
9445 tested with Emacs as the default method. This method requires
9446 ImageMagick version 6.4.6 (approximately) or later.
9447 */);
9448 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9449 imagemagick_render_type = 0;
9450 #endif