src/w32heap.c (init_heap): Fix typos in comments (again).
[emacs.git] / src / image.c
blob304603e7382d8ebf70d6ebde135ff120aa0b1512
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2014 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 /* Include this before including <setjmp.h> to work around bugs with
25 older libpng; see Bug#17429. */
26 #if defined HAVE_PNG && !defined HAVE_NS
27 # include <png.h>
28 #endif
30 #include <setjmp.h>
31 #include <c-ctype.h>
33 #include "lisp.h"
34 #include "frame.h"
35 #include "window.h"
36 #include "dispextern.h"
37 #include "blockinput.h"
38 #include "systime.h"
39 #include <epaths.h>
40 #include "character.h"
41 #include "coding.h"
42 #include "termhooks.h"
43 #include "font.h"
45 #ifdef HAVE_SYS_STAT_H
46 #include <sys/stat.h>
47 #endif /* HAVE_SYS_STAT_H */
49 #ifdef HAVE_SYS_TYPES_H
50 #include <sys/types.h>
51 #endif /* HAVE_SYS_TYPES_H */
53 #ifdef HAVE_WINDOW_SYSTEM
54 #include TERM_HEADER
55 #endif /* HAVE_WINDOW_SYSTEM */
57 #ifdef HAVE_X_WINDOWS
58 #define COLOR_TABLE_SUPPORT 1
60 typedef struct x_bitmap_record Bitmap_Record;
61 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
62 #define NO_PIXMAP None
64 #define PIX_MASK_RETAIN 0
65 #define PIX_MASK_DRAW 1
66 #endif /* HAVE_X_WINDOWS */
68 #ifdef HAVE_NTGUI
70 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
71 #ifdef WINDOWSNT
72 # include "w32.h"
73 #endif
75 /* W32_TODO : Color tables on W32. */
76 #undef COLOR_TABLE_SUPPORT
78 typedef struct w32_bitmap_record Bitmap_Record;
79 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
80 #define NO_PIXMAP 0
82 #define PIX_MASK_RETAIN 0
83 #define PIX_MASK_DRAW 1
85 #define x_defined_color w32_defined_color
86 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
88 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
89 or -1 if no PNG/GIF support was compiled in. This is tested by
90 w32-win.el to correctly set up the alist used to search for the
91 respective image libraries. */
92 Lisp_Object Qlibpng_version, Qlibgif_version, Qlibjpeg_version;
94 #endif /* HAVE_NTGUI */
96 #ifdef HAVE_NS
97 #undef COLOR_TABLE_SUPPORT
99 typedef struct ns_bitmap_record Bitmap_Record;
101 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
102 #define NO_PIXMAP 0
104 #define PIX_MASK_RETAIN 0
105 #define PIX_MASK_DRAW 1
107 #define x_defined_color(f, name, color_def, alloc) \
108 ns_defined_color (f, name, color_def, alloc, 0)
109 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
110 #endif /* HAVE_NS */
113 /* The symbol `postscript' identifying images of this type. */
115 static Lisp_Object Qpostscript;
117 static void x_disable_image (struct frame *, struct image *);
118 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
119 Lisp_Object);
121 static void init_color_table (void);
122 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
123 #ifdef COLOR_TABLE_SUPPORT
124 static void free_color_table (void);
125 static unsigned long *colors_in_color_table (int *n);
126 #endif
128 static Lisp_Object QCmax_width, QCmax_height;
130 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
131 id, which is just an int that this section returns. Bitmaps are
132 reference counted so they can be shared among frames.
134 Bitmap indices are guaranteed to be > 0, so a negative number can
135 be used to indicate no bitmap.
137 If you use x_create_bitmap_from_data, then you must keep track of
138 the bitmaps yourself. That is, creating a bitmap from the same
139 data more than once will not be caught. */
141 #ifdef HAVE_NS
142 /* Use with images created by ns_image_for_XPM. */
143 static unsigned long
144 XGetPixel (XImagePtr ximage, int x, int y)
146 return ns_get_pixel (ximage, x, y);
149 /* Use with images created by ns_image_for_XPM; alpha set to 1;
150 pixel is assumed to be in RGB form. */
151 static void
152 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
154 ns_put_pixel (ximage, x, y, pixel);
156 #endif /* HAVE_NS */
159 /* Functions to access the contents of a bitmap, given an id. */
161 #ifdef HAVE_X_WINDOWS
162 static int
163 x_bitmap_height (struct frame *f, ptrdiff_t id)
165 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
168 static int
169 x_bitmap_width (struct frame *f, ptrdiff_t id)
171 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
173 #endif
175 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
176 ptrdiff_t
177 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
179 /* HAVE_NTGUI needs the explicit cast here. */
180 return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
182 #endif
184 #ifdef HAVE_X_WINDOWS
186 x_bitmap_mask (struct frame *f, ptrdiff_t id)
188 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
190 #endif
192 /* Allocate a new bitmap record. Returns index of new record. */
194 static ptrdiff_t
195 x_allocate_bitmap_record (struct frame *f)
197 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
198 ptrdiff_t i;
200 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
201 return ++dpyinfo->bitmaps_last;
203 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
204 if (dpyinfo->bitmaps[i].refcount == 0)
205 return i + 1;
207 dpyinfo->bitmaps =
208 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
209 10, -1, sizeof *dpyinfo->bitmaps);
210 return ++dpyinfo->bitmaps_last;
213 /* Add one reference to the reference count of the bitmap with id ID. */
215 void
216 x_reference_bitmap (struct frame *f, ptrdiff_t id)
218 ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
221 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
223 ptrdiff_t
224 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
226 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
227 ptrdiff_t id;
229 #ifdef HAVE_X_WINDOWS
230 Pixmap bitmap;
231 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
232 bits, width, height);
233 if (! bitmap)
234 return -1;
235 #endif /* HAVE_X_WINDOWS */
237 #ifdef HAVE_NTGUI
238 Pixmap bitmap;
239 bitmap = CreateBitmap (width, height,
240 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
241 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
242 bits);
243 if (! bitmap)
244 return -1;
245 #endif /* HAVE_NTGUI */
247 #ifdef HAVE_NS
248 void *bitmap = ns_image_from_XBM (bits, width, height);
249 if (!bitmap)
250 return -1;
251 #endif
253 id = x_allocate_bitmap_record (f);
255 #ifdef HAVE_NS
256 dpyinfo->bitmaps[id - 1].img = bitmap;
257 dpyinfo->bitmaps[id - 1].depth = 1;
258 #endif
260 dpyinfo->bitmaps[id - 1].file = NULL;
261 dpyinfo->bitmaps[id - 1].height = height;
262 dpyinfo->bitmaps[id - 1].width = width;
263 dpyinfo->bitmaps[id - 1].refcount = 1;
265 #ifdef HAVE_X_WINDOWS
266 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
267 dpyinfo->bitmaps[id - 1].have_mask = false;
268 dpyinfo->bitmaps[id - 1].depth = 1;
269 #endif /* HAVE_X_WINDOWS */
271 #ifdef HAVE_NTGUI
272 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
273 dpyinfo->bitmaps[id - 1].hinst = NULL;
274 dpyinfo->bitmaps[id - 1].depth = 1;
275 #endif /* HAVE_NTGUI */
277 return id;
280 /* Create bitmap from file FILE for frame F. */
282 ptrdiff_t
283 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
285 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
287 #ifdef HAVE_NTGUI
288 return -1; /* W32_TODO : bitmap support */
289 #endif /* HAVE_NTGUI */
291 #ifdef HAVE_NS
292 ptrdiff_t id;
293 void *bitmap = ns_image_from_file (file);
295 if (!bitmap)
296 return -1;
299 id = x_allocate_bitmap_record (f);
300 dpyinfo->bitmaps[id - 1].img = bitmap;
301 dpyinfo->bitmaps[id - 1].refcount = 1;
302 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
303 dpyinfo->bitmaps[id - 1].depth = 1;
304 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
305 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
306 return id;
307 #endif
309 #ifdef HAVE_X_WINDOWS
310 unsigned int width, height;
311 Pixmap bitmap;
312 int xhot, yhot, result;
313 ptrdiff_t id;
314 Lisp_Object found;
315 char *filename;
317 /* Look for an existing bitmap with the same name. */
318 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
320 if (dpyinfo->bitmaps[id].refcount
321 && dpyinfo->bitmaps[id].file
322 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
324 ++dpyinfo->bitmaps[id].refcount;
325 return id + 1;
329 /* Search bitmap-file-path for the file, if appropriate. */
330 if (openp (Vx_bitmap_file_path, file, Qnil, &found,
331 make_number (R_OK), false)
332 < 0)
333 return -1;
335 filename = SSDATA (found);
337 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
338 filename, &width, &height, &bitmap, &xhot, &yhot);
339 if (result != BitmapSuccess)
340 return -1;
342 id = x_allocate_bitmap_record (f);
343 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
344 dpyinfo->bitmaps[id - 1].have_mask = false;
345 dpyinfo->bitmaps[id - 1].refcount = 1;
346 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
347 dpyinfo->bitmaps[id - 1].depth = 1;
348 dpyinfo->bitmaps[id - 1].height = height;
349 dpyinfo->bitmaps[id - 1].width = width;
351 return id;
352 #endif /* HAVE_X_WINDOWS */
355 /* Free bitmap B. */
357 static void
358 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
360 #ifdef HAVE_X_WINDOWS
361 XFreePixmap (dpyinfo->display, bm->pixmap);
362 if (bm->have_mask)
363 XFreePixmap (dpyinfo->display, bm->mask);
364 #endif /* HAVE_X_WINDOWS */
366 #ifdef HAVE_NTGUI
367 DeleteObject (bm->pixmap);
368 #endif /* HAVE_NTGUI */
370 #ifdef HAVE_NS
371 ns_release_object (bm->img);
372 #endif
374 if (bm->file)
376 xfree (bm->file);
377 bm->file = NULL;
381 /* Remove reference to bitmap with id number ID. */
383 void
384 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
386 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
388 if (id > 0)
390 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
392 if (--bm->refcount == 0)
394 block_input ();
395 free_bitmap_record (dpyinfo, bm);
396 unblock_input ();
401 /* Free all the bitmaps for the display specified by DPYINFO. */
403 void
404 x_destroy_all_bitmaps (Display_Info *dpyinfo)
406 ptrdiff_t i;
407 Bitmap_Record *bm = dpyinfo->bitmaps;
409 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
410 if (bm->refcount > 0)
411 free_bitmap_record (dpyinfo, bm);
413 dpyinfo->bitmaps_last = 0;
416 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
417 XImagePtr *, Pixmap *);
418 static void x_destroy_x_image (XImagePtr ximg);
420 #ifdef HAVE_NTGUI
421 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
422 bool, HGDIOBJ *);
423 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
424 HGDIOBJ);
425 #else
426 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
427 static void image_unget_x_image (struct image *, bool, XImagePtr);
428 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
429 image_get_x_image (f, img, mask_p)
430 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
431 image_unget_x_image (img, mask_p, ximg)
432 #endif
434 #ifdef HAVE_X_WINDOWS
436 static void image_sync_to_pixmaps (struct frame *, struct image *);
438 /* Useful functions defined in the section
439 `Image type independent image structures' below. */
441 static unsigned long four_corners_best (XImagePtr ximg,
442 int *corners,
443 unsigned long width,
444 unsigned long height);
447 /* Create a mask of a bitmap. Note is this not a perfect mask.
448 It's nicer with some borders in this context */
450 void
451 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
453 Pixmap pixmap, mask;
454 XImagePtr ximg, mask_img;
455 unsigned long width, height;
456 bool result;
457 unsigned long bg;
458 unsigned long x, y, xp, xm, yp, ym;
459 GC gc;
461 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
463 if (!(id > 0))
464 return;
466 pixmap = x_bitmap_pixmap (f, id);
467 width = x_bitmap_width (f, id);
468 height = x_bitmap_height (f, id);
470 block_input ();
471 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
472 ~0, ZPixmap);
474 if (!ximg)
476 unblock_input ();
477 return;
480 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
482 unblock_input ();
483 if (!result)
485 XDestroyImage (ximg);
486 return;
489 bg = four_corners_best (ximg, NULL, width, height);
491 for (y = 0; y < ximg->height; ++y)
493 for (x = 0; x < ximg->width; ++x)
495 xp = x != ximg->width - 1 ? x + 1 : 0;
496 xm = x != 0 ? x - 1 : ximg->width - 1;
497 yp = y != ximg->height - 1 ? y + 1 : 0;
498 ym = y != 0 ? y - 1 : ximg->height - 1;
499 if (XGetPixel (ximg, x, y) == bg
500 && XGetPixel (ximg, x, yp) == bg
501 && XGetPixel (ximg, x, ym) == bg
502 && XGetPixel (ximg, xp, y) == bg
503 && XGetPixel (ximg, xp, yp) == bg
504 && XGetPixel (ximg, xp, ym) == bg
505 && XGetPixel (ximg, xm, y) == bg
506 && XGetPixel (ximg, xm, yp) == bg
507 && XGetPixel (ximg, xm, ym) == bg)
508 XPutPixel (mask_img, x, y, 0);
509 else
510 XPutPixel (mask_img, x, y, 1);
514 eassert (input_blocked_p ());
515 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
516 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
517 width, height);
518 XFreeGC (FRAME_X_DISPLAY (f), gc);
520 dpyinfo->bitmaps[id - 1].have_mask = true;
521 dpyinfo->bitmaps[id - 1].mask = mask;
523 XDestroyImage (ximg);
524 x_destroy_x_image (mask_img);
527 #endif /* HAVE_X_WINDOWS */
530 /***********************************************************************
531 Image types
532 ***********************************************************************/
534 /* List of supported image types. Use define_image_type to add new
535 types. Use lookup_image_type to find a type for a given symbol. */
537 static struct image_type *image_types;
539 /* The symbol `xbm' which is used as the type symbol for XBM images. */
541 static Lisp_Object Qxbm;
543 /* Keywords. */
545 Lisp_Object QCascent, QCmargin, QCrelief;
546 Lisp_Object QCconversion;
547 static Lisp_Object QCheuristic_mask;
548 static Lisp_Object QCcolor_symbols;
549 static Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry;
550 static Lisp_Object QCcrop, QCrotation;
552 /* Other symbols. */
554 static Lisp_Object Qcount, Qextension_data, Qdelay;
555 static Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
557 /* Forward function prototypes. */
559 static struct image_type *lookup_image_type (Lisp_Object);
560 static void x_laplace (struct frame *, struct image *);
561 static void x_emboss (struct frame *, struct image *);
562 static void x_build_heuristic_mask (struct frame *, struct image *,
563 Lisp_Object);
564 #ifdef WINDOWSNT
565 #define CACHE_IMAGE_TYPE(type, status) \
566 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
567 #else
568 #define CACHE_IMAGE_TYPE(type, status)
569 #endif
571 #define ADD_IMAGE_TYPE(type) \
572 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
574 /* Define a new image type from TYPE. This adds a copy of TYPE to
575 image_types and caches the loading status of TYPE. */
577 static struct image_type *
578 define_image_type (struct image_type *type)
580 struct image_type *p = NULL;
581 Lisp_Object target_type = *type->type;
582 bool type_valid = 1;
584 block_input ();
586 for (p = image_types; p; p = p->next)
587 if (EQ (*p->type, target_type))
588 goto done;
590 if (type->init)
592 #if defined HAVE_NTGUI && defined WINDOWSNT
593 /* If we failed to load the library before, don't try again. */
594 Lisp_Object tested = Fassq (target_type, Vlibrary_cache);
595 if (CONSP (tested) && NILP (XCDR (tested)))
596 type_valid = 0;
597 else
598 #endif
600 type_valid = type->init ();
601 CACHE_IMAGE_TYPE (target_type, type_valid ? Qt : Qnil);
605 if (type_valid)
607 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
608 The initialized data segment is read-only. */
609 p = xmalloc (sizeof *p);
610 *p = *type;
611 p->next = image_types;
612 image_types = p;
615 done:
616 unblock_input ();
617 return p;
621 /* Value is true if OBJECT is a valid Lisp image specification. A
622 valid image specification is a list whose car is the symbol
623 `image', and whose rest is a property list. The property list must
624 contain a value for key `:type'. That value must be the name of a
625 supported image type. The rest of the property list depends on the
626 image type. */
628 bool
629 valid_image_p (Lisp_Object object)
631 bool valid_p = 0;
633 if (IMAGEP (object))
635 Lisp_Object tem;
637 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
638 if (EQ (XCAR (tem), QCtype))
640 tem = XCDR (tem);
641 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
643 struct image_type *type;
644 type = lookup_image_type (XCAR (tem));
645 if (type)
646 valid_p = type->valid_p (object);
649 break;
653 return valid_p;
657 /* Log error message with format string FORMAT and argument ARG.
658 Signaling an error, e.g. when an image cannot be loaded, is not a
659 good idea because this would interrupt redisplay, and the error
660 message display would lead to another redisplay. This function
661 therefore simply displays a message. */
663 static void
664 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
666 add_to_log (format, arg1, arg2);
671 /***********************************************************************
672 Image specifications
673 ***********************************************************************/
675 enum image_value_type
677 IMAGE_DONT_CHECK_VALUE_TYPE,
678 IMAGE_STRING_VALUE,
679 IMAGE_STRING_OR_NIL_VALUE,
680 IMAGE_SYMBOL_VALUE,
681 IMAGE_POSITIVE_INTEGER_VALUE,
682 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
683 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
684 IMAGE_ASCENT_VALUE,
685 IMAGE_INTEGER_VALUE,
686 IMAGE_FUNCTION_VALUE,
687 IMAGE_NUMBER_VALUE,
688 IMAGE_BOOL_VALUE
691 /* Structure used when parsing image specifications. */
693 struct image_keyword
695 /* Name of keyword. */
696 const char *name;
698 /* The type of value allowed. */
699 enum image_value_type type;
701 /* True means key must be present. */
702 bool mandatory_p;
704 /* Used to recognize duplicate keywords in a property list. */
705 int count;
707 /* The value that was found. */
708 Lisp_Object value;
712 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
713 has the format (image KEYWORD VALUE ...). One of the keyword/
714 value pairs must be `:type TYPE'. KEYWORDS is a vector of
715 image_keywords structures of size NKEYWORDS describing other
716 allowed keyword/value pairs. Value is true if SPEC is valid. */
718 static bool
719 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
720 int nkeywords, Lisp_Object type)
722 int i;
723 Lisp_Object plist;
725 if (!IMAGEP (spec))
726 return 0;
728 plist = XCDR (spec);
729 while (CONSP (plist))
731 Lisp_Object key, value;
733 /* First element of a pair must be a symbol. */
734 key = XCAR (plist);
735 plist = XCDR (plist);
736 if (!SYMBOLP (key))
737 return 0;
739 /* There must follow a value. */
740 if (!CONSP (plist))
741 return 0;
742 value = XCAR (plist);
743 plist = XCDR (plist);
745 /* Find key in KEYWORDS. Error if not found. */
746 for (i = 0; i < nkeywords; ++i)
747 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
748 break;
750 if (i == nkeywords)
751 continue;
753 /* Record that we recognized the keyword. If a keywords
754 was found more than once, it's an error. */
755 keywords[i].value = value;
756 if (keywords[i].count > 1)
757 return 0;
758 ++keywords[i].count;
760 /* Check type of value against allowed type. */
761 switch (keywords[i].type)
763 case IMAGE_STRING_VALUE:
764 if (!STRINGP (value))
765 return 0;
766 break;
768 case IMAGE_STRING_OR_NIL_VALUE:
769 if (!STRINGP (value) && !NILP (value))
770 return 0;
771 break;
773 case IMAGE_SYMBOL_VALUE:
774 if (!SYMBOLP (value))
775 return 0;
776 break;
778 case IMAGE_POSITIVE_INTEGER_VALUE:
779 if (! RANGED_INTEGERP (1, value, INT_MAX))
780 return 0;
781 break;
783 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
784 if (RANGED_INTEGERP (0, value, INT_MAX))
785 break;
786 if (CONSP (value)
787 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
788 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
789 break;
790 return 0;
792 case IMAGE_ASCENT_VALUE:
793 if (SYMBOLP (value) && EQ (value, Qcenter))
794 break;
795 else if (RANGED_INTEGERP (0, value, 100))
796 break;
797 return 0;
799 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
800 /* Unlike the other integer-related cases, this one does not
801 verify that VALUE fits in 'int'. This is because callers
802 want EMACS_INT. */
803 if (!INTEGERP (value) || XINT (value) < 0)
804 return 0;
805 break;
807 case IMAGE_DONT_CHECK_VALUE_TYPE:
808 break;
810 case IMAGE_FUNCTION_VALUE:
811 value = indirect_function (value);
812 if (!NILP (Ffunctionp (value)))
813 break;
814 return 0;
816 case IMAGE_NUMBER_VALUE:
817 if (!INTEGERP (value) && !FLOATP (value))
818 return 0;
819 break;
821 case IMAGE_INTEGER_VALUE:
822 if (! TYPE_RANGED_INTEGERP (int, value))
823 return 0;
824 break;
826 case IMAGE_BOOL_VALUE:
827 if (!NILP (value) && !EQ (value, Qt))
828 return 0;
829 break;
831 default:
832 emacs_abort ();
833 break;
836 if (EQ (key, QCtype) && !EQ (type, value))
837 return 0;
840 /* Check that all mandatory fields are present. */
841 for (i = 0; i < nkeywords; ++i)
842 if (keywords[i].mandatory_p && keywords[i].count == 0)
843 return 0;
845 return NILP (plist);
849 /* Return the value of KEY in image specification SPEC. Value is nil
850 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
851 was found in SPEC. */
853 static Lisp_Object
854 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
856 Lisp_Object tail;
858 eassert (valid_image_p (spec));
860 for (tail = XCDR (spec);
861 CONSP (tail) && CONSP (XCDR (tail));
862 tail = XCDR (XCDR (tail)))
864 if (EQ (XCAR (tail), key))
866 if (found)
867 *found = 1;
868 return XCAR (XCDR (tail));
872 if (found)
873 *found = 0;
874 return Qnil;
878 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
879 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
880 PIXELS non-nil means return the size in pixels, otherwise return the
881 size in canonical character units.
882 FRAME is the frame on which the image will be displayed. FRAME nil
883 or omitted means use the selected frame. */)
884 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
886 Lisp_Object size;
888 size = Qnil;
889 if (valid_image_p (spec))
891 struct frame *f = decode_window_system_frame (frame);
892 ptrdiff_t id = lookup_image (f, spec);
893 struct image *img = IMAGE_FROM_ID (f, id);
894 int width = img->width + 2 * img->hmargin;
895 int height = img->height + 2 * img->vmargin;
897 if (NILP (pixels))
898 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
899 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
900 else
901 size = Fcons (make_number (width), make_number (height));
903 else
904 error ("Invalid image specification");
906 return size;
910 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
911 doc: /* Return t if image SPEC has a mask bitmap.
912 FRAME is the frame on which the image will be displayed. FRAME nil
913 or omitted means use the selected frame. */)
914 (Lisp_Object spec, Lisp_Object frame)
916 Lisp_Object mask;
918 mask = Qnil;
919 if (valid_image_p (spec))
921 struct frame *f = decode_window_system_frame (frame);
922 ptrdiff_t id = lookup_image (f, spec);
923 struct image *img = IMAGE_FROM_ID (f, id);
924 if (img->mask)
925 mask = Qt;
927 else
928 error ("Invalid image specification");
930 return mask;
933 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
934 doc: /* Return metadata for image SPEC.
935 FRAME is the frame on which the image will be displayed. FRAME nil
936 or omitted means use the selected frame. */)
937 (Lisp_Object spec, Lisp_Object frame)
939 Lisp_Object ext;
941 ext = Qnil;
942 if (valid_image_p (spec))
944 struct frame *f = decode_window_system_frame (frame);
945 ptrdiff_t id = lookup_image (f, spec);
946 struct image *img = IMAGE_FROM_ID (f, id);
947 ext = img->lisp_data;
950 return ext;
954 /***********************************************************************
955 Image type independent image structures
956 ***********************************************************************/
958 #define MAX_IMAGE_SIZE 10.0
959 /* Allocate and return a new image structure for image specification
960 SPEC. SPEC has a hash value of HASH. */
962 static struct image *
963 make_image (Lisp_Object spec, EMACS_UINT hash)
965 struct image *img = xzalloc (sizeof *img);
966 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
968 eassert (valid_image_p (spec));
969 img->dependencies = NILP (file) ? Qnil : list1 (file);
970 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
971 eassert (img->type != NULL);
972 img->spec = spec;
973 img->lisp_data = Qnil;
974 img->ascent = DEFAULT_IMAGE_ASCENT;
975 img->hash = hash;
976 img->corners[BOT_CORNER] = -1; /* Full image */
977 return img;
981 /* Free image IMG which was used on frame F, including its resources. */
983 static void
984 free_image (struct frame *f, struct image *img)
986 if (img)
988 struct image_cache *c = FRAME_IMAGE_CACHE (f);
990 /* Remove IMG from the hash table of its cache. */
991 if (img->prev)
992 img->prev->next = img->next;
993 else
994 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
996 if (img->next)
997 img->next->prev = img->prev;
999 c->images[img->id] = NULL;
1001 /* Windows NT redefines 'free', but in this file, we need to
1002 avoid the redefinition. */
1003 #ifdef WINDOWSNT
1004 #undef free
1005 #endif
1006 /* Free resources, then free IMG. */
1007 img->type->free (f, img);
1008 xfree (img);
1012 /* Return true if the given widths and heights are valid for display. */
1014 static bool
1015 check_image_size (struct frame *f, int width, int height)
1017 int w, h;
1019 if (width <= 0 || height <= 0)
1020 return 0;
1022 if (INTEGERP (Vmax_image_size))
1023 return (width <= XINT (Vmax_image_size)
1024 && height <= XINT (Vmax_image_size));
1025 else if (FLOATP (Vmax_image_size))
1027 if (f != NULL)
1029 w = FRAME_PIXEL_WIDTH (f);
1030 h = FRAME_PIXEL_HEIGHT (f);
1032 else
1033 w = h = 1024; /* Arbitrary size for unknown frame. */
1034 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1035 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1037 else
1038 return 1;
1041 /* Prepare image IMG for display on frame F. Must be called before
1042 drawing an image. */
1044 void
1045 prepare_image_for_display (struct frame *f, struct image *img)
1047 /* We're about to display IMG, so set its timestamp to `now'. */
1048 img->timestamp = current_timespec ();
1050 /* If IMG doesn't have a pixmap yet, load it now, using the image
1051 type dependent loader function. */
1052 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1053 img->load_failed_p = ! img->type->load (f, img);
1055 #ifdef HAVE_X_WINDOWS
1056 if (!img->load_failed_p)
1058 block_input ();
1059 image_sync_to_pixmaps (f, img);
1060 unblock_input ();
1062 #endif
1066 /* Value is the number of pixels for the ascent of image IMG when
1067 drawn in face FACE. */
1070 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1072 int height;
1073 int ascent;
1075 if (slice->height == img->height)
1076 height = img->height + img->vmargin;
1077 else if (slice->y == 0)
1078 height = slice->height + img->vmargin;
1079 else
1080 height = slice->height;
1082 if (img->ascent == CENTERED_IMAGE_ASCENT)
1084 if (face->font)
1086 #ifdef HAVE_NTGUI
1087 /* W32 specific version. Why?. ++kfs */
1088 ascent = height / 2 - (FONT_DESCENT (face->font)
1089 - FONT_BASE (face->font)) / 2;
1090 #else
1091 /* This expression is arranged so that if the image can't be
1092 exactly centered, it will be moved slightly up. This is
1093 because a typical font is `top-heavy' (due to the presence
1094 uppercase letters), so the image placement should err towards
1095 being top-heavy too. It also just generally looks better. */
1096 ascent = (height + FONT_BASE (face->font)
1097 - FONT_DESCENT (face->font) + 1) / 2;
1098 #endif /* HAVE_NTGUI */
1100 else
1101 ascent = height / 2;
1103 else
1104 ascent = height * (img->ascent / 100.0);
1106 return ascent;
1110 /* Image background colors. */
1112 /* Find the "best" corner color of a bitmap.
1113 On W32, XIMG is assumed to a device context with the bitmap selected. */
1115 static RGB_PIXEL_COLOR
1116 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1117 unsigned long width, unsigned long height)
1119 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1120 int i, best_count;
1122 if (corners && corners[BOT_CORNER] >= 0)
1124 /* Get the colors at the corner_pixels of ximg. */
1125 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1126 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1127 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1128 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1130 else
1132 /* Get the colors at the corner_pixels of ximg. */
1133 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1134 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1135 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1136 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1138 /* Choose the most frequently found color as background. */
1139 for (i = best_count = 0; i < 4; ++i)
1141 int j, n;
1143 for (j = n = 0; j < 4; ++j)
1144 if (corner_pixels[i] == corner_pixels[j])
1145 ++n;
1147 if (n > best_count)
1148 best = corner_pixels[i], best_count = n;
1151 return best;
1154 /* Portability macros */
1156 #ifdef HAVE_NTGUI
1158 #define Free_Pixmap(display, pixmap) \
1159 DeleteObject (pixmap)
1161 #elif defined (HAVE_NS)
1163 #define Free_Pixmap(display, pixmap) \
1164 ns_release_object (pixmap)
1166 #else
1168 #define Free_Pixmap(display, pixmap) \
1169 XFreePixmap (display, pixmap)
1171 #endif /* !HAVE_NTGUI && !HAVE_NS */
1174 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1175 it is guessed heuristically. If non-zero, XIMG is an existing
1176 XImage object (or device context with the image selected on W32) to
1177 use for the heuristic. */
1179 RGB_PIXEL_COLOR
1180 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1182 if (! img->background_valid)
1183 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1185 bool free_ximg = !ximg;
1186 #ifdef HAVE_NTGUI
1187 HGDIOBJ prev;
1188 #endif /* HAVE_NTGUI */
1190 if (free_ximg)
1191 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1193 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1195 if (free_ximg)
1196 image_unget_x_image_or_dc (img, 0, ximg, prev);
1198 img->background_valid = 1;
1201 return img->background;
1204 /* Return the `background_transparent' field of IMG. If IMG doesn't
1205 have one yet, it is guessed heuristically. If non-zero, MASK is an
1206 existing XImage object to use for the heuristic. */
1209 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1211 if (! img->background_transparent_valid)
1212 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1214 if (img->mask)
1216 bool free_mask = !mask;
1217 #ifdef HAVE_NTGUI
1218 HGDIOBJ prev;
1219 #endif /* HAVE_NTGUI */
1221 if (free_mask)
1222 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1224 img->background_transparent
1225 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1227 if (free_mask)
1228 image_unget_x_image_or_dc (img, 1, mask, prev);
1230 else
1231 img->background_transparent = 0;
1233 img->background_transparent_valid = 1;
1236 return img->background_transparent;
1239 /* Store F's background color into *BGCOLOR. */
1240 static void
1241 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1243 #ifndef HAVE_NS
1244 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1245 x_query_color (f, bgcolor);
1246 #else
1247 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1248 #endif
1252 /***********************************************************************
1253 Helper functions for X image types
1254 ***********************************************************************/
1256 /* Clear X resources of image IMG on frame F according to FLAGS.
1257 FLAGS is bitwise-or of the following masks:
1258 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1259 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1260 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1261 any. */
1263 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1264 #define CLEAR_IMAGE_MASK (1 << 1)
1265 #define CLEAR_IMAGE_COLORS (1 << 2)
1267 static void
1268 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1270 if (flags & CLEAR_IMAGE_PIXMAP)
1272 if (img->pixmap)
1274 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1275 img->pixmap = NO_PIXMAP;
1276 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1277 img->background_valid = 0;
1279 #ifdef HAVE_X_WINDOWS
1280 if (img->ximg)
1282 x_destroy_x_image (img->ximg);
1283 img->ximg = NULL;
1284 img->background_valid = 0;
1286 #endif
1289 if (flags & CLEAR_IMAGE_MASK)
1291 if (img->mask)
1293 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1294 img->mask = NO_PIXMAP;
1295 img->background_transparent_valid = 0;
1297 #ifdef HAVE_X_WINDOWS
1298 if (img->mask_img)
1300 x_destroy_x_image (img->mask_img);
1301 img->mask_img = NULL;
1302 img->background_transparent_valid = 0;
1304 #endif
1307 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1309 /* W32_TODO: color table support. */
1310 #ifdef HAVE_X_WINDOWS
1311 x_free_colors (f, img->colors, img->ncolors);
1312 #endif /* HAVE_X_WINDOWS */
1313 xfree (img->colors);
1314 img->colors = NULL;
1315 img->ncolors = 0;
1320 /* Free X resources of image IMG which is used on frame F. */
1322 static void
1323 x_clear_image (struct frame *f, struct image *img)
1325 block_input ();
1326 x_clear_image_1 (f, img,
1327 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1328 unblock_input ();
1332 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1333 cannot be allocated, use DFLT. Add a newly allocated color to
1334 IMG->colors, so that it can be freed again. Value is the pixel
1335 color. */
1337 static unsigned long
1338 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1339 unsigned long dflt)
1341 XColor color;
1342 unsigned long result;
1344 eassert (STRINGP (color_name));
1346 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1347 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1348 INT_MAX))
1350 /* This isn't called frequently so we get away with simply
1351 reallocating the color vector to the needed size, here. */
1352 ptrdiff_t ncolors = img->ncolors + 1;
1353 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1354 img->colors[ncolors - 1] = color.pixel;
1355 img->ncolors = ncolors;
1356 result = color.pixel;
1358 else
1359 result = dflt;
1361 return result;
1366 /***********************************************************************
1367 Image Cache
1368 ***********************************************************************/
1370 static void cache_image (struct frame *f, struct image *img);
1372 /* Return a new, initialized image cache that is allocated from the
1373 heap. Call free_image_cache to free an image cache. */
1375 struct image_cache *
1376 make_image_cache (void)
1378 struct image_cache *c = xmalloc (sizeof *c);
1380 c->size = 50;
1381 c->used = c->refcount = 0;
1382 c->images = xmalloc (c->size * sizeof *c->images);
1383 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1384 return c;
1388 /* Find an image matching SPEC in the cache, and return it. If no
1389 image is found, return NULL. */
1390 static struct image *
1391 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1393 struct image *img;
1394 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1395 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1397 if (!c) return NULL;
1399 /* If the image spec does not specify a background color, the cached
1400 image must have the same background color as the current frame.
1401 The foreground color must also match, for the sake of monochrome
1402 images.
1404 In fact, we could ignore the foreground color matching condition
1405 for color images, or if the image spec specifies :foreground;
1406 similarly we could ignore the background color matching condition
1407 for formats that don't use transparency (such as jpeg), or if the
1408 image spec specifies :background. However, the extra memory
1409 usage is probably negligible in practice, so we don't bother. */
1411 for (img = c->buckets[i]; img; img = img->next)
1412 if (img->hash == hash
1413 && !NILP (Fequal (img->spec, spec))
1414 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1415 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1416 break;
1417 return img;
1421 /* Search frame F for an image with spec SPEC, and free it. */
1423 static void
1424 uncache_image (struct frame *f, Lisp_Object spec)
1426 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1427 if (img)
1429 free_image (f, img);
1430 /* As display glyphs may still be referring to the image ID, we
1431 must garbage the frame (Bug#6426). */
1432 SET_FRAME_GARBAGED (f);
1437 /* Free image cache of frame F. Be aware that X frames share images
1438 caches. */
1440 void
1441 free_image_cache (struct frame *f)
1443 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1444 if (c)
1446 ptrdiff_t i;
1448 /* Cache should not be referenced by any frame when freed. */
1449 eassert (c->refcount == 0);
1451 for (i = 0; i < c->used; ++i)
1452 free_image (f, c->images[i]);
1453 xfree (c->images);
1454 xfree (c->buckets);
1455 xfree (c);
1456 FRAME_IMAGE_CACHE (f) = NULL;
1461 /* Clear image cache of frame F. FILTER=t means free all images.
1462 FILTER=nil means clear only images that haven't been
1463 displayed for some time.
1464 Else, only free the images which have FILTER in their `dependencies'.
1465 Should be called from time to time to reduce the number of loaded images.
1466 If image-cache-eviction-delay is non-nil, this frees images in the cache
1467 which weren't displayed for at least that many seconds. */
1469 static void
1470 clear_image_cache (struct frame *f, Lisp_Object filter)
1472 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1474 if (c)
1476 ptrdiff_t i, nfreed = 0;
1478 /* Block input so that we won't be interrupted by a SIGIO
1479 while being in an inconsistent state. */
1480 block_input ();
1482 if (!NILP (filter))
1484 /* Filter image cache. */
1485 for (i = 0; i < c->used; ++i)
1487 struct image *img = c->images[i];
1488 if (img && (EQ (Qt, filter)
1489 || !NILP (Fmember (filter, img->dependencies))))
1491 free_image (f, img);
1492 ++nfreed;
1496 else if (INTEGERP (Vimage_cache_eviction_delay))
1498 /* Free cache based on timestamp. */
1499 struct timespec old, t;
1500 double delay;
1501 ptrdiff_t nimages = 0;
1503 for (i = 0; i < c->used; ++i)
1504 if (c->images[i])
1505 nimages++;
1507 /* If the number of cached images has grown unusually large,
1508 decrease the cache eviction delay (Bug#6230). */
1509 delay = XINT (Vimage_cache_eviction_delay);
1510 if (nimages > 40)
1511 delay = 1600 * delay / nimages / nimages;
1512 delay = max (delay, 1);
1514 t = current_timespec ();
1515 old = timespec_sub (t, dtotimespec (delay));
1517 for (i = 0; i < c->used; ++i)
1519 struct image *img = c->images[i];
1520 if (img && timespec_cmp (img->timestamp, old) < 0)
1522 free_image (f, img);
1523 ++nfreed;
1528 /* We may be clearing the image cache because, for example,
1529 Emacs was iconified for a longer period of time. In that
1530 case, current matrices may still contain references to
1531 images freed above. So, clear these matrices. */
1532 if (nfreed)
1534 Lisp_Object tail, frame;
1536 FOR_EACH_FRAME (tail, frame)
1538 struct frame *fr = XFRAME (frame);
1539 if (FRAME_IMAGE_CACHE (fr) == c)
1540 clear_current_matrices (fr);
1543 windows_or_buffers_changed = 19;
1546 unblock_input ();
1550 void
1551 clear_image_caches (Lisp_Object filter)
1553 /* FIXME: We want to do
1554 * struct terminal *t;
1555 * for (t = terminal_list; t; t = t->next_terminal)
1556 * clear_image_cache (t, filter); */
1557 Lisp_Object tail, frame;
1558 FOR_EACH_FRAME (tail, frame)
1559 if (FRAME_WINDOW_P (XFRAME (frame)))
1560 clear_image_cache (XFRAME (frame), filter);
1563 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1564 0, 1, 0,
1565 doc: /* Clear the image cache.
1566 FILTER nil or a frame means clear all images in the selected frame.
1567 FILTER t means clear the image caches of all frames.
1568 Anything else, means only clear those images which refer to FILTER,
1569 which is then usually a filename. */)
1570 (Lisp_Object filter)
1572 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1573 clear_image_caches (filter);
1574 else
1575 clear_image_cache (decode_window_system_frame (filter), Qt);
1577 return Qnil;
1581 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1582 1, 2, 0,
1583 doc: /* Flush the image with specification SPEC on frame FRAME.
1584 This removes the image from the Emacs image cache. If SPEC specifies
1585 an image file, the next redisplay of this image will read from the
1586 current contents of that file.
1588 FRAME nil or omitted means use the selected frame.
1589 FRAME t means refresh the image on all frames. */)
1590 (Lisp_Object spec, Lisp_Object frame)
1592 if (!valid_image_p (spec))
1593 error ("Invalid image specification");
1595 if (EQ (frame, Qt))
1597 Lisp_Object tail;
1598 FOR_EACH_FRAME (tail, frame)
1600 struct frame *f = XFRAME (frame);
1601 if (FRAME_WINDOW_P (f))
1602 uncache_image (f, spec);
1605 else
1606 uncache_image (decode_window_system_frame (frame), spec);
1608 return Qnil;
1612 /* Compute masks and transform image IMG on frame F, as specified
1613 by the image's specification, */
1615 static void
1616 postprocess_image (struct frame *f, struct image *img)
1618 /* Manipulation of the image's mask. */
1619 if (img->pixmap)
1621 Lisp_Object conversion, spec;
1622 Lisp_Object mask;
1624 spec = img->spec;
1626 /* `:heuristic-mask t'
1627 `:mask heuristic'
1628 means build a mask heuristically.
1629 `:heuristic-mask (R G B)'
1630 `:mask (heuristic (R G B))'
1631 means build a mask from color (R G B) in the
1632 image.
1633 `:mask nil'
1634 means remove a mask, if any. */
1636 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1637 if (!NILP (mask))
1638 x_build_heuristic_mask (f, img, mask);
1639 else
1641 bool found_p;
1643 mask = image_spec_value (spec, QCmask, &found_p);
1645 if (EQ (mask, Qheuristic))
1646 x_build_heuristic_mask (f, img, Qt);
1647 else if (CONSP (mask)
1648 && EQ (XCAR (mask), Qheuristic))
1650 if (CONSP (XCDR (mask)))
1651 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1652 else
1653 x_build_heuristic_mask (f, img, XCDR (mask));
1655 else if (NILP (mask) && found_p && img->mask)
1656 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1660 /* Should we apply an image transformation algorithm? */
1661 conversion = image_spec_value (spec, QCconversion, NULL);
1662 if (EQ (conversion, Qdisabled))
1663 x_disable_image (f, img);
1664 else if (EQ (conversion, Qlaplace))
1665 x_laplace (f, img);
1666 else if (EQ (conversion, Qemboss))
1667 x_emboss (f, img);
1668 else if (CONSP (conversion)
1669 && EQ (XCAR (conversion), Qedge_detection))
1671 Lisp_Object tem;
1672 tem = XCDR (conversion);
1673 if (CONSP (tem))
1674 x_edge_detection (f, img,
1675 Fplist_get (tem, QCmatrix),
1676 Fplist_get (tem, QCcolor_adjustment));
1682 /* Return the id of image with Lisp specification SPEC on frame F.
1683 SPEC must be a valid Lisp image specification (see valid_image_p). */
1685 ptrdiff_t
1686 lookup_image (struct frame *f, Lisp_Object spec)
1688 struct image *img;
1689 EMACS_UINT hash;
1691 /* F must be a window-system frame, and SPEC must be a valid image
1692 specification. */
1693 eassert (FRAME_WINDOW_P (f));
1694 eassert (valid_image_p (spec));
1696 /* Look up SPEC in the hash table of the image cache. */
1697 hash = sxhash (spec, 0);
1698 img = search_image_cache (f, spec, hash);
1699 if (img && img->load_failed_p)
1701 free_image (f, img);
1702 img = NULL;
1705 /* If not found, create a new image and cache it. */
1706 if (img == NULL)
1708 block_input ();
1709 img = make_image (spec, hash);
1710 cache_image (f, img);
1711 img->load_failed_p = ! img->type->load (f, img);
1712 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1713 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1715 /* If we can't load the image, and we don't have a width and
1716 height, use some arbitrary width and height so that we can
1717 draw a rectangle for it. */
1718 if (img->load_failed_p)
1720 Lisp_Object value;
1722 value = image_spec_value (spec, QCwidth, NULL);
1723 img->width = (INTEGERP (value)
1724 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1725 value = image_spec_value (spec, QCheight, NULL);
1726 img->height = (INTEGERP (value)
1727 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1729 else
1731 /* Handle image type independent image attributes
1732 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1733 `:background COLOR'. */
1734 Lisp_Object ascent, margin, relief, bg;
1735 int relief_bound;
1737 ascent = image_spec_value (spec, QCascent, NULL);
1738 if (INTEGERP (ascent))
1739 img->ascent = XFASTINT (ascent);
1740 else if (EQ (ascent, Qcenter))
1741 img->ascent = CENTERED_IMAGE_ASCENT;
1743 margin = image_spec_value (spec, QCmargin, NULL);
1744 if (INTEGERP (margin))
1745 img->vmargin = img->hmargin = XFASTINT (margin);
1746 else if (CONSP (margin))
1748 img->hmargin = XFASTINT (XCAR (margin));
1749 img->vmargin = XFASTINT (XCDR (margin));
1752 relief = image_spec_value (spec, QCrelief, NULL);
1753 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1754 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1756 img->relief = XINT (relief);
1757 img->hmargin += eabs (img->relief);
1758 img->vmargin += eabs (img->relief);
1761 if (! img->background_valid)
1763 bg = image_spec_value (img->spec, QCbackground, NULL);
1764 if (!NILP (bg))
1766 img->background
1767 = x_alloc_image_color (f, img, bg,
1768 FRAME_BACKGROUND_PIXEL (f));
1769 img->background_valid = 1;
1773 /* Do image transformations and compute masks, unless we
1774 don't have the image yet. */
1775 if (!EQ (*img->type->type, Qpostscript))
1776 postprocess_image (f, img);
1779 unblock_input ();
1782 /* We're using IMG, so set its timestamp to `now'. */
1783 img->timestamp = current_timespec ();
1785 /* Value is the image id. */
1786 return img->id;
1790 /* Cache image IMG in the image cache of frame F. */
1792 static void
1793 cache_image (struct frame *f, struct image *img)
1795 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1796 ptrdiff_t i;
1798 /* Find a free slot in c->images. */
1799 for (i = 0; i < c->used; ++i)
1800 if (c->images[i] == NULL)
1801 break;
1803 /* If no free slot found, maybe enlarge c->images. */
1804 if (i == c->used && c->used == c->size)
1805 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1807 /* Add IMG to c->images, and assign IMG an id. */
1808 c->images[i] = img;
1809 img->id = i;
1810 if (i == c->used)
1811 ++c->used;
1813 /* Add IMG to the cache's hash table. */
1814 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1815 img->next = c->buckets[i];
1816 if (img->next)
1817 img->next->prev = img;
1818 img->prev = NULL;
1819 c->buckets[i] = img;
1823 /* Call FN on every image in the image cache of frame F. Used to mark
1824 Lisp Objects in the image cache. */
1826 /* Mark Lisp objects in image IMG. */
1828 static void
1829 mark_image (struct image *img)
1831 mark_object (img->spec);
1832 mark_object (img->dependencies);
1834 if (!NILP (img->lisp_data))
1835 mark_object (img->lisp_data);
1839 void
1840 mark_image_cache (struct image_cache *c)
1842 if (c)
1844 ptrdiff_t i;
1845 for (i = 0; i < c->used; ++i)
1846 if (c->images[i])
1847 mark_image (c->images[i]);
1853 /***********************************************************************
1854 X / NS / W32 support code
1855 ***********************************************************************/
1857 #ifdef WINDOWSNT
1859 /* Macro for defining functions that will be loaded from image DLLs. */
1860 #define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
1862 /* Macro for loading those image functions from the library. */
1863 #define LOAD_IMGLIB_FN(lib,func) { \
1864 fn_##func = (void *) GetProcAddress (lib, #func); \
1865 if (!fn_##func) return 0; \
1868 #endif /* WINDOWSNT */
1870 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1871 windowing system.
1872 WIDTH and HEIGHT must both be positive.
1873 If XIMG is null, assume it is a bitmap. */
1874 static bool
1875 x_check_image_size (XImagePtr ximg, int width, int height)
1877 #ifdef HAVE_X_WINDOWS
1878 /* Respect Xlib's limits: it cannot deal with images that have more
1879 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1880 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1881 enum
1883 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1884 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1887 int bitmap_pad, depth, bytes_per_line;
1888 if (ximg)
1890 bitmap_pad = ximg->bitmap_pad;
1891 depth = ximg->depth;
1892 bytes_per_line = ximg->bytes_per_line;
1894 else
1896 bitmap_pad = 8;
1897 depth = 1;
1898 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1900 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1901 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1902 #else
1903 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1904 For now, assume that every image size is allowed on these systems. */
1905 return 1;
1906 #endif
1909 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1910 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1911 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1912 via xmalloc. Print error messages via image_error if an error
1913 occurs. Value is true if successful.
1915 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1916 should indicate the bit depth of the image. */
1918 static bool
1919 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1920 XImagePtr *ximg, Pixmap *pixmap)
1922 #ifdef HAVE_X_WINDOWS
1923 Display *display = FRAME_X_DISPLAY (f);
1924 Window window = FRAME_X_WINDOW (f);
1925 Screen *screen = FRAME_X_SCREEN (f);
1927 eassert (input_blocked_p ());
1929 if (depth <= 0)
1930 depth = DefaultDepthOfScreen (screen);
1931 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1932 depth, ZPixmap, 0, NULL, width, height,
1933 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1934 if (*ximg == NULL)
1936 image_error ("Unable to allocate X image", Qnil, Qnil);
1937 return 0;
1940 if (! x_check_image_size (*ximg, width, height))
1942 x_destroy_x_image (*ximg);
1943 *ximg = NULL;
1944 image_error ("Image too large (%dx%d)",
1945 make_number (width), make_number (height));
1946 return 0;
1949 /* Allocate image raster. */
1950 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1952 /* Allocate a pixmap of the same size. */
1953 *pixmap = XCreatePixmap (display, window, width, height, depth);
1954 if (*pixmap == NO_PIXMAP)
1956 x_destroy_x_image (*ximg);
1957 *ximg = NULL;
1958 image_error ("Unable to create X pixmap", Qnil, Qnil);
1959 return 0;
1962 return 1;
1963 #endif /* HAVE_X_WINDOWS */
1965 #ifdef HAVE_NTGUI
1967 BITMAPINFOHEADER *header;
1968 HDC hdc;
1969 int scanline_width_bits;
1970 int remainder;
1971 int palette_colors = 0;
1973 if (depth == 0)
1974 depth = 24;
1976 if (depth != 1 && depth != 4 && depth != 8
1977 && depth != 16 && depth != 24 && depth != 32)
1979 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1980 return 0;
1983 scanline_width_bits = width * depth;
1984 remainder = scanline_width_bits % 32;
1986 if (remainder)
1987 scanline_width_bits += 32 - remainder;
1989 /* Bitmaps with a depth less than 16 need a palette. */
1990 /* BITMAPINFO structure already contains the first RGBQUAD. */
1991 if (depth < 16)
1992 palette_colors = 1 << (depth - 1);
1994 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1996 header = &(*ximg)->info.bmiHeader;
1997 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
1998 header->biSize = sizeof (*header);
1999 header->biWidth = width;
2000 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2001 header->biPlanes = 1;
2002 header->biBitCount = depth;
2003 header->biCompression = BI_RGB;
2004 header->biClrUsed = palette_colors;
2006 /* TODO: fill in palette. */
2007 if (depth == 1)
2009 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2010 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2011 (*ximg)->info.bmiColors[0].rgbRed = 0;
2012 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2013 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2014 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2015 (*ximg)->info.bmiColors[1].rgbRed = 255;
2016 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2019 hdc = get_frame_dc (f);
2021 /* Create a DIBSection and raster array for the bitmap,
2022 and store its handle in *pixmap. */
2023 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2024 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2025 /* casting avoids a GCC warning */
2026 (void **)&((*ximg)->data), NULL, 0);
2028 /* Realize display palette and garbage all frames. */
2029 release_frame_dc (f, hdc);
2031 if (*pixmap == NULL)
2033 DWORD err = GetLastError ();
2034 Lisp_Object errcode;
2035 /* All system errors are < 10000, so the following is safe. */
2036 XSETINT (errcode, err);
2037 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2038 x_destroy_x_image (*ximg);
2039 *ximg = NULL;
2040 return 0;
2043 return 1;
2045 #endif /* HAVE_NTGUI */
2047 #ifdef HAVE_NS
2048 *pixmap = ns_image_for_XPM (width, height, depth);
2049 if (*pixmap == 0)
2051 *ximg = NULL;
2052 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2053 return 0;
2055 *ximg = *pixmap;
2056 return 1;
2057 #endif
2061 /* Destroy XImage XIMG. Free XIMG->data. */
2063 static void
2064 x_destroy_x_image (XImagePtr ximg)
2066 eassert (input_blocked_p ());
2067 if (ximg)
2069 #ifdef HAVE_X_WINDOWS
2070 xfree (ximg->data);
2071 ximg->data = NULL;
2072 XDestroyImage (ximg);
2073 #endif /* HAVE_X_WINDOWS */
2074 #ifdef HAVE_NTGUI
2075 /* Data will be freed by DestroyObject. */
2076 ximg->data = NULL;
2077 xfree (ximg);
2078 #endif /* HAVE_NTGUI */
2079 #ifdef HAVE_NS
2080 ns_release_object (ximg);
2081 #endif /* HAVE_NS */
2086 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2087 are width and height of both the image and pixmap. */
2089 static void
2090 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2092 #ifdef HAVE_X_WINDOWS
2093 GC gc;
2095 eassert (input_blocked_p ());
2096 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2097 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2098 XFreeGC (FRAME_X_DISPLAY (f), gc);
2099 #endif /* HAVE_X_WINDOWS */
2101 #ifdef HAVE_NTGUI
2102 #if 0 /* I don't think this is necessary looking at where it is used. */
2103 HDC hdc = get_frame_dc (f);
2104 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2105 release_frame_dc (f, hdc);
2106 #endif
2107 #endif /* HAVE_NTGUI */
2109 #ifdef HAVE_NS
2110 eassert (ximg == pixmap);
2111 ns_retain_object (ximg);
2112 #endif
2115 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2116 with image_put_x_image. */
2118 static bool
2119 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2120 int width, int height, int depth,
2121 XImagePtr *ximg, bool mask_p)
2123 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2125 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2126 !mask_p ? &img->pixmap : &img->mask);
2129 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2130 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2131 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2132 On the other platforms, it puts XIMG into the pixmap, then frees
2133 the X image and its buffer. */
2135 static void
2136 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2137 bool mask_p)
2139 #ifdef HAVE_X_WINDOWS
2140 if (!mask_p)
2142 eassert (img->ximg == NULL);
2143 img->ximg = ximg;
2145 else
2147 eassert (img->mask_img == NULL);
2148 img->mask_img = ximg;
2150 #else
2151 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2152 img->width, img->height);
2153 x_destroy_x_image (ximg);
2154 #endif
2157 #ifdef HAVE_X_WINDOWS
2158 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2159 the X images and their buffers. */
2161 static void
2162 image_sync_to_pixmaps (struct frame *f, struct image *img)
2164 if (img->ximg)
2166 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2167 x_destroy_x_image (img->ximg);
2168 img->ximg = NULL;
2170 if (img->mask_img)
2172 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2173 x_destroy_x_image (img->mask_img);
2174 img->mask_img = NULL;
2177 #endif
2179 #ifdef HAVE_NTGUI
2180 /* Create a memory device context for IMG on frame F. It stores the
2181 currently selected GDI object into *PREV for future restoration by
2182 image_unget_x_image_or_dc. */
2184 static XImagePtr_or_DC
2185 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2186 HGDIOBJ *prev)
2188 HDC frame_dc = get_frame_dc (f);
2189 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2191 release_frame_dc (f, frame_dc);
2192 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2194 return ximg;
2197 static void
2198 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2199 XImagePtr_or_DC ximg, HGDIOBJ prev)
2201 SelectObject (ximg, prev);
2202 DeleteDC (ximg);
2204 #else /* !HAVE_NTGUI */
2205 /* Get the X image for IMG on frame F. The resulting X image data
2206 should be treated as read-only at least on X. */
2208 static XImagePtr
2209 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2211 #ifdef HAVE_X_WINDOWS
2212 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2214 if (ximg_in_img)
2215 return ximg_in_img;
2216 else
2217 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2218 0, 0, img->width, img->height, ~0, ZPixmap);
2219 #elif defined (HAVE_NS)
2220 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2222 ns_retain_object (pixmap);
2223 return pixmap;
2224 #endif
2227 static void
2228 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2230 #ifdef HAVE_X_WINDOWS
2231 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2233 if (ximg_in_img)
2234 eassert (ximg == ximg_in_img);
2235 else
2236 XDestroyImage (ximg);
2237 #elif defined (HAVE_NS)
2238 ns_release_object (ximg);
2239 #endif
2241 #endif /* !HAVE_NTGUI */
2244 /***********************************************************************
2245 File Handling
2246 ***********************************************************************/
2248 /* Find image file FILE. Look in data-directory/images, then
2249 x-bitmap-file-path. Value is the encoded full name of the file
2250 found, or nil if not found. */
2252 Lisp_Object
2253 x_find_image_file (Lisp_Object file)
2255 Lisp_Object file_found, search_path;
2256 int fd;
2258 /* TODO I think this should use something like image-load-path
2259 instead. Unfortunately, that can contain non-string elements. */
2260 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2261 Vdata_directory),
2262 Vx_bitmap_file_path);
2264 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2265 fd = openp (search_path, file, Qnil, &file_found, Qnil, false);
2267 if (fd == -1)
2268 file_found = Qnil;
2269 else
2271 file_found = ENCODE_FILE (file_found);
2272 if (fd != -2)
2273 emacs_close (fd);
2276 return file_found;
2280 /* Read FILE into memory. Value is a pointer to a buffer allocated
2281 with xmalloc holding FILE's contents. Value is null if an error
2282 occurred. *SIZE is set to the size of the file. */
2284 static unsigned char *
2285 slurp_file (char *file, ptrdiff_t *size)
2287 FILE *fp = emacs_fopen (file, "rb");
2288 unsigned char *buf = NULL;
2289 struct stat st;
2291 if (fp)
2293 ptrdiff_t count = SPECPDL_INDEX ();
2294 record_unwind_protect_ptr (fclose_unwind, fp);
2296 if (fstat (fileno (fp), &st) == 0
2297 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2299 /* Report an error if we read past the purported EOF.
2300 This can happen if the file grows as we read it. */
2301 ptrdiff_t buflen = st.st_size;
2302 buf = xmalloc (buflen + 1);
2303 if (fread (buf, 1, buflen + 1, fp) == buflen)
2304 *size = buflen;
2305 else
2307 xfree (buf);
2308 buf = NULL;
2312 unbind_to (count, Qnil);
2315 return buf;
2320 /***********************************************************************
2321 XBM images
2322 ***********************************************************************/
2324 static bool xbm_load (struct frame *f, struct image *img);
2325 static bool xbm_image_p (Lisp_Object object);
2326 static bool xbm_file_p (Lisp_Object);
2329 /* Indices of image specification fields in xbm_format, below. */
2331 enum xbm_keyword_index
2333 XBM_TYPE,
2334 XBM_FILE,
2335 XBM_WIDTH,
2336 XBM_HEIGHT,
2337 XBM_DATA,
2338 XBM_FOREGROUND,
2339 XBM_BACKGROUND,
2340 XBM_ASCENT,
2341 XBM_MARGIN,
2342 XBM_RELIEF,
2343 XBM_ALGORITHM,
2344 XBM_HEURISTIC_MASK,
2345 XBM_MASK,
2346 XBM_LAST
2349 /* Vector of image_keyword structures describing the format
2350 of valid XBM image specifications. */
2352 static const struct image_keyword xbm_format[XBM_LAST] =
2354 {":type", IMAGE_SYMBOL_VALUE, 1},
2355 {":file", IMAGE_STRING_VALUE, 0},
2356 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2357 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2358 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2359 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2360 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2361 {":ascent", IMAGE_ASCENT_VALUE, 0},
2362 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2363 {":relief", IMAGE_INTEGER_VALUE, 0},
2364 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2365 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2366 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2369 /* Structure describing the image type XBM. */
2371 static struct image_type xbm_type =
2373 &Qxbm,
2374 xbm_image_p,
2375 xbm_load,
2376 x_clear_image,
2377 NULL,
2378 NULL
2381 /* Tokens returned from xbm_scan. */
2383 enum xbm_token
2385 XBM_TK_IDENT = 256,
2386 XBM_TK_NUMBER
2390 /* Return true if OBJECT is a valid XBM-type image specification.
2391 A valid specification is a list starting with the symbol `image'
2392 The rest of the list is a property list which must contain an
2393 entry `:type xbm'.
2395 If the specification specifies a file to load, it must contain
2396 an entry `:file FILENAME' where FILENAME is a string.
2398 If the specification is for a bitmap loaded from memory it must
2399 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2400 WIDTH and HEIGHT are integers > 0. DATA may be:
2402 1. a string large enough to hold the bitmap data, i.e. it must
2403 have a size >= (WIDTH + 7) / 8 * HEIGHT
2405 2. a bool-vector of size >= WIDTH * HEIGHT
2407 3. a vector of strings or bool-vectors, one for each line of the
2408 bitmap.
2410 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2411 may not be specified in this case because they are defined in the
2412 XBM file.
2414 Both the file and data forms may contain the additional entries
2415 `:background COLOR' and `:foreground COLOR'. If not present,
2416 foreground and background of the frame on which the image is
2417 displayed is used. */
2419 static bool
2420 xbm_image_p (Lisp_Object object)
2422 struct image_keyword kw[XBM_LAST];
2424 memcpy (kw, xbm_format, sizeof kw);
2425 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2426 return 0;
2428 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2430 if (kw[XBM_FILE].count)
2432 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2433 return 0;
2435 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2437 /* In-memory XBM file. */
2438 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2439 return 0;
2441 else
2443 Lisp_Object data;
2444 int width, height;
2446 /* Entries for `:width', `:height' and `:data' must be present. */
2447 if (!kw[XBM_WIDTH].count
2448 || !kw[XBM_HEIGHT].count
2449 || !kw[XBM_DATA].count)
2450 return 0;
2452 data = kw[XBM_DATA].value;
2453 width = XFASTINT (kw[XBM_WIDTH].value);
2454 height = XFASTINT (kw[XBM_HEIGHT].value);
2456 /* Check type of data, and width and height against contents of
2457 data. */
2458 if (VECTORP (data))
2460 EMACS_INT i;
2462 /* Number of elements of the vector must be >= height. */
2463 if (ASIZE (data) < height)
2464 return 0;
2466 /* Each string or bool-vector in data must be large enough
2467 for one line of the image. */
2468 for (i = 0; i < height; ++i)
2470 Lisp_Object elt = AREF (data, i);
2472 if (STRINGP (elt))
2474 if (SCHARS (elt)
2475 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2476 return 0;
2478 else if (BOOL_VECTOR_P (elt))
2480 if (bool_vector_size (elt) < width)
2481 return 0;
2483 else
2484 return 0;
2487 else if (STRINGP (data))
2489 if (SCHARS (data)
2490 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2491 return 0;
2493 else if (BOOL_VECTOR_P (data))
2495 if (bool_vector_size (data) / height < width)
2496 return 0;
2498 else
2499 return 0;
2502 return 1;
2506 /* Scan a bitmap file. FP is the stream to read from. Value is
2507 either an enumerator from enum xbm_token, or a character for a
2508 single-character token, or 0 at end of file. If scanning an
2509 identifier, store the lexeme of the identifier in SVAL. If
2510 scanning a number, store its value in *IVAL. */
2512 static int
2513 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2515 unsigned int c;
2517 loop:
2519 /* Skip white space. */
2520 while (*s < end && (c = *(*s)++, c_isspace (c)))
2523 if (*s >= end)
2524 c = 0;
2525 else if (c_isdigit (c))
2527 int value = 0, digit;
2529 if (c == '0' && *s < end)
2531 c = *(*s)++;
2532 if (c == 'x' || c == 'X')
2534 while (*s < end)
2536 c = *(*s)++;
2537 if (c_isdigit (c))
2538 digit = c - '0';
2539 else if (c >= 'a' && c <= 'f')
2540 digit = c - 'a' + 10;
2541 else if (c >= 'A' && c <= 'F')
2542 digit = c - 'A' + 10;
2543 else
2544 break;
2545 value = 16 * value + digit;
2548 else if (c_isdigit (c))
2550 value = c - '0';
2551 while (*s < end
2552 && (c = *(*s)++, c_isdigit (c)))
2553 value = 8 * value + c - '0';
2556 else
2558 value = c - '0';
2559 while (*s < end
2560 && (c = *(*s)++, c_isdigit (c)))
2561 value = 10 * value + c - '0';
2564 if (*s < end)
2565 *s = *s - 1;
2566 *ival = value;
2567 c = XBM_TK_NUMBER;
2569 else if (c_isalpha (c) || c == '_')
2571 *sval++ = c;
2572 while (*s < end
2573 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2574 *sval++ = c;
2575 *sval = 0;
2576 if (*s < end)
2577 *s = *s - 1;
2578 c = XBM_TK_IDENT;
2580 else if (c == '/' && **s == '*')
2582 /* C-style comment. */
2583 ++*s;
2584 while (**s && (**s != '*' || *(*s + 1) != '/'))
2585 ++*s;
2586 if (**s)
2588 *s += 2;
2589 goto loop;
2593 return c;
2596 #ifdef HAVE_NTGUI
2598 /* Create a Windows bitmap from X bitmap data. */
2599 static HBITMAP
2600 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2602 static unsigned char swap_nibble[16]
2603 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2604 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2605 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2606 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2607 int i, j, w1, w2;
2608 unsigned char *bits, *p;
2609 HBITMAP bmp;
2611 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2612 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2613 bits = alloca (height * w2);
2614 memset (bits, 0, height * w2);
2615 for (i = 0; i < height; i++)
2617 p = bits + i*w2;
2618 for (j = 0; j < w1; j++)
2620 /* Bitswap XBM bytes to match how Windows does things. */
2621 unsigned char c = *data++;
2622 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2623 | (swap_nibble[(c>>4) & 0xf]));
2626 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2628 return bmp;
2631 static void
2632 convert_mono_to_color_image (struct frame *f, struct image *img,
2633 COLORREF foreground, COLORREF background)
2635 HDC hdc, old_img_dc, new_img_dc;
2636 HGDIOBJ old_prev, new_prev;
2637 HBITMAP new_pixmap;
2639 hdc = get_frame_dc (f);
2640 old_img_dc = CreateCompatibleDC (hdc);
2641 new_img_dc = CreateCompatibleDC (hdc);
2642 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2643 release_frame_dc (f, hdc);
2644 old_prev = SelectObject (old_img_dc, img->pixmap);
2645 new_prev = SelectObject (new_img_dc, new_pixmap);
2646 /* Windows convention for mono bitmaps is black = background,
2647 white = foreground. */
2648 SetTextColor (new_img_dc, background);
2649 SetBkColor (new_img_dc, foreground);
2651 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2652 0, 0, SRCCOPY);
2654 SelectObject (old_img_dc, old_prev);
2655 SelectObject (new_img_dc, new_prev);
2656 DeleteDC (old_img_dc);
2657 DeleteDC (new_img_dc);
2658 DeleteObject (img->pixmap);
2659 if (new_pixmap == 0)
2660 fprintf (stderr, "Failed to convert image to color.\n");
2661 else
2662 img->pixmap = new_pixmap;
2665 #define XBM_BIT_SHUFFLE(b) (~(b))
2667 #else
2669 #define XBM_BIT_SHUFFLE(b) (b)
2671 #endif /* HAVE_NTGUI */
2674 static void
2675 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2676 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2677 bool non_default_colors)
2679 #ifdef HAVE_NTGUI
2680 img->pixmap
2681 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2683 /* If colors were specified, transfer the bitmap to a color one. */
2684 if (non_default_colors)
2685 convert_mono_to_color_image (f, img, fg, bg);
2687 #elif defined (HAVE_NS)
2688 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2690 #else
2691 img->pixmap =
2692 (x_check_image_size (0, img->width, img->height)
2693 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2694 FRAME_X_WINDOW (f),
2695 data,
2696 img->width, img->height,
2697 fg, bg,
2698 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2699 : NO_PIXMAP);
2700 #endif /* !HAVE_NTGUI && !HAVE_NS */
2705 /* Replacement for XReadBitmapFileData which isn't available under old
2706 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2707 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2708 the image. Return in *DATA the bitmap data allocated with xmalloc.
2709 Value is true if successful. DATA null means just test if
2710 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2711 inhibit the call to image_error when the image size is invalid (the
2712 bitmap remains unread). */
2714 static bool
2715 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2716 int *width, int *height, char **data,
2717 bool inhibit_image_error)
2719 unsigned char *s = contents;
2720 char buffer[BUFSIZ];
2721 bool padding_p = 0;
2722 bool v10 = 0;
2723 int bytes_per_line, i, nbytes;
2724 char *p;
2725 int value;
2726 int LA1;
2728 #define match() \
2729 LA1 = xbm_scan (&s, end, buffer, &value)
2731 #define expect(TOKEN) \
2732 do \
2734 if (LA1 != (TOKEN)) \
2735 goto failure; \
2736 match (); \
2738 while (0)
2740 #define expect_ident(IDENT) \
2741 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2742 match (); \
2743 else \
2744 goto failure
2746 *width = *height = -1;
2747 if (data)
2748 *data = NULL;
2749 LA1 = xbm_scan (&s, end, buffer, &value);
2751 /* Parse defines for width, height and hot-spots. */
2752 while (LA1 == '#')
2754 match ();
2755 expect_ident ("define");
2756 expect (XBM_TK_IDENT);
2758 if (LA1 == XBM_TK_NUMBER)
2760 char *q = strrchr (buffer, '_');
2761 q = q ? q + 1 : buffer;
2762 if (strcmp (q, "width") == 0)
2763 *width = value;
2764 else if (strcmp (q, "height") == 0)
2765 *height = value;
2767 expect (XBM_TK_NUMBER);
2770 if (!check_image_size (f, *width, *height))
2772 if (!inhibit_image_error)
2773 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2774 goto failure;
2776 else if (data == NULL)
2777 goto success;
2779 /* Parse bits. Must start with `static'. */
2780 expect_ident ("static");
2781 if (LA1 == XBM_TK_IDENT)
2783 if (strcmp (buffer, "unsigned") == 0)
2785 match ();
2786 expect_ident ("char");
2788 else if (strcmp (buffer, "short") == 0)
2790 match ();
2791 v10 = 1;
2792 if (*width % 16 && *width % 16 < 9)
2793 padding_p = 1;
2795 else if (strcmp (buffer, "char") == 0)
2796 match ();
2797 else
2798 goto failure;
2800 else
2801 goto failure;
2803 expect (XBM_TK_IDENT);
2804 expect ('[');
2805 expect (']');
2806 expect ('=');
2807 expect ('{');
2809 if (! x_check_image_size (0, *width, *height))
2811 if (!inhibit_image_error)
2812 image_error ("Image too large (%dx%d)",
2813 make_number (*width), make_number (*height));
2814 goto failure;
2816 bytes_per_line = (*width + 7) / 8 + padding_p;
2817 nbytes = bytes_per_line * *height;
2818 p = *data = xmalloc (nbytes);
2820 if (v10)
2822 for (i = 0; i < nbytes; i += 2)
2824 int val = value;
2825 expect (XBM_TK_NUMBER);
2827 *p++ = XBM_BIT_SHUFFLE (val);
2828 if (!padding_p || ((i + 2) % bytes_per_line))
2829 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2831 if (LA1 == ',' || LA1 == '}')
2832 match ();
2833 else
2834 goto failure;
2837 else
2839 for (i = 0; i < nbytes; ++i)
2841 int val = value;
2842 expect (XBM_TK_NUMBER);
2844 *p++ = XBM_BIT_SHUFFLE (val);
2846 if (LA1 == ',' || LA1 == '}')
2847 match ();
2848 else
2849 goto failure;
2853 success:
2854 return 1;
2856 failure:
2858 if (data && *data)
2860 xfree (*data);
2861 *data = NULL;
2863 return 0;
2865 #undef match
2866 #undef expect
2867 #undef expect_ident
2871 /* Load XBM image IMG which will be displayed on frame F from buffer
2872 CONTENTS. END is the end of the buffer. Value is true if
2873 successful. */
2875 static bool
2876 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2877 unsigned char *end)
2879 bool rc;
2880 char *data;
2881 bool success_p = 0;
2883 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2884 &data, 0);
2885 if (rc)
2887 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2888 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2889 bool non_default_colors = 0;
2890 Lisp_Object value;
2892 eassert (img->width > 0 && img->height > 0);
2894 /* Get foreground and background colors, maybe allocate colors. */
2895 value = image_spec_value (img->spec, QCforeground, NULL);
2896 if (!NILP (value))
2898 foreground = x_alloc_image_color (f, img, value, foreground);
2899 non_default_colors = 1;
2901 value = image_spec_value (img->spec, QCbackground, NULL);
2902 if (!NILP (value))
2904 background = x_alloc_image_color (f, img, value, background);
2905 img->background = background;
2906 img->background_valid = 1;
2907 non_default_colors = 1;
2910 Create_Pixmap_From_Bitmap_Data (f, img, data,
2911 foreground, background,
2912 non_default_colors);
2913 xfree (data);
2915 if (img->pixmap == NO_PIXMAP)
2917 x_clear_image (f, img);
2918 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2920 else
2921 success_p = 1;
2923 else
2924 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2926 return success_p;
2930 /* Value is true if DATA looks like an in-memory XBM file. */
2932 static bool
2933 xbm_file_p (Lisp_Object data)
2935 int w, h;
2936 return (STRINGP (data)
2937 && xbm_read_bitmap_data (NULL, SDATA (data),
2938 (SDATA (data) + SBYTES (data)),
2939 &w, &h, NULL, 1));
2943 /* Fill image IMG which is used on frame F with pixmap data. Value is
2944 true if successful. */
2946 static bool
2947 xbm_load (struct frame *f, struct image *img)
2949 bool success_p = 0;
2950 Lisp_Object file_name;
2952 eassert (xbm_image_p (img->spec));
2954 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2955 file_name = image_spec_value (img->spec, QCfile, NULL);
2956 if (STRINGP (file_name))
2958 Lisp_Object file;
2959 unsigned char *contents;
2960 ptrdiff_t size;
2962 file = x_find_image_file (file_name);
2963 if (!STRINGP (file))
2965 image_error ("Cannot find image file `%s'", file_name, Qnil);
2966 return 0;
2969 contents = slurp_file (SSDATA (file), &size);
2970 if (contents == NULL)
2972 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2973 return 0;
2976 success_p = xbm_load_image (f, img, contents, contents + size);
2977 xfree (contents);
2979 else
2981 struct image_keyword fmt[XBM_LAST];
2982 Lisp_Object data;
2983 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2984 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2985 bool non_default_colors = 0;
2986 char *bits;
2987 bool parsed_p;
2988 bool in_memory_file_p = 0;
2990 /* See if data looks like an in-memory XBM file. */
2991 data = image_spec_value (img->spec, QCdata, NULL);
2992 in_memory_file_p = xbm_file_p (data);
2994 /* Parse the image specification. */
2995 memcpy (fmt, xbm_format, sizeof fmt);
2996 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2997 eassert (parsed_p);
2999 /* Get specified width, and height. */
3000 if (!in_memory_file_p)
3002 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3003 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3004 eassert (img->width > 0 && img->height > 0);
3005 if (!check_image_size (f, img->width, img->height))
3007 image_error ("Invalid image size (see `max-image-size')",
3008 Qnil, Qnil);
3009 return 0;
3013 /* Get foreground and background colors, maybe allocate colors. */
3014 if (fmt[XBM_FOREGROUND].count
3015 && STRINGP (fmt[XBM_FOREGROUND].value))
3017 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3018 foreground);
3019 non_default_colors = 1;
3022 if (fmt[XBM_BACKGROUND].count
3023 && STRINGP (fmt[XBM_BACKGROUND].value))
3025 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3026 background);
3027 non_default_colors = 1;
3030 if (in_memory_file_p)
3031 success_p = xbm_load_image (f, img, SDATA (data),
3032 (SDATA (data)
3033 + SBYTES (data)));
3034 else
3036 if (VECTORP (data))
3038 int i;
3039 char *p;
3040 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3042 p = bits = alloca (nbytes * img->height);
3043 for (i = 0; i < img->height; ++i, p += nbytes)
3045 Lisp_Object line = AREF (data, i);
3046 if (STRINGP (line))
3047 memcpy (p, SDATA (line), nbytes);
3048 else
3049 memcpy (p, bool_vector_data (line), nbytes);
3052 else if (STRINGP (data))
3053 bits = SSDATA (data);
3054 else
3055 bits = (char *) bool_vector_data (data);
3057 #ifdef HAVE_NTGUI
3059 char *invertedBits;
3060 int nbytes, i;
3061 /* Windows mono bitmaps are reversed compared with X. */
3062 invertedBits = bits;
3063 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
3064 * img->height;
3065 bits = alloca (nbytes);
3066 for (i = 0; i < nbytes; i++)
3067 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3069 #endif
3070 /* Create the pixmap. */
3072 if (x_check_image_size (0, img->width, img->height))
3073 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3074 foreground, background,
3075 non_default_colors);
3076 else
3077 img->pixmap = NO_PIXMAP;
3079 if (img->pixmap)
3080 success_p = 1;
3081 else
3083 image_error ("Unable to create pixmap for XBM image `%s'",
3084 img->spec, Qnil);
3085 x_clear_image (f, img);
3090 return success_p;
3095 /***********************************************************************
3096 XPM images
3097 ***********************************************************************/
3099 #if defined (HAVE_XPM) || defined (HAVE_NS)
3101 static bool xpm_image_p (Lisp_Object object);
3102 static bool xpm_load (struct frame *f, struct image *img);
3104 #endif /* HAVE_XPM || HAVE_NS */
3106 #ifdef HAVE_XPM
3107 #ifdef HAVE_NTGUI
3108 /* Indicate to xpm.h that we don't have Xlib. */
3109 #define FOR_MSW
3110 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3111 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3112 #define XColor xpm_XColor
3113 #define XImage xpm_XImage
3114 #define Display xpm_Display
3115 #define PIXEL_ALREADY_TYPEDEFED
3116 #include "X11/xpm.h"
3117 #undef FOR_MSW
3118 #undef XColor
3119 #undef XImage
3120 #undef Display
3121 #undef PIXEL_ALREADY_TYPEDEFED
3122 #else
3123 #include "X11/xpm.h"
3124 #endif /* HAVE_NTGUI */
3125 #endif /* HAVE_XPM */
3127 #if defined (HAVE_XPM) || defined (HAVE_NS)
3128 /* The symbol `xpm' identifying XPM-format images. */
3130 static Lisp_Object Qxpm;
3132 /* Indices of image specification fields in xpm_format, below. */
3134 enum xpm_keyword_index
3136 XPM_TYPE,
3137 XPM_FILE,
3138 XPM_DATA,
3139 XPM_ASCENT,
3140 XPM_MARGIN,
3141 XPM_RELIEF,
3142 XPM_ALGORITHM,
3143 XPM_HEURISTIC_MASK,
3144 XPM_MASK,
3145 XPM_COLOR_SYMBOLS,
3146 XPM_BACKGROUND,
3147 XPM_LAST
3150 /* Vector of image_keyword structures describing the format
3151 of valid XPM image specifications. */
3153 static const struct image_keyword xpm_format[XPM_LAST] =
3155 {":type", IMAGE_SYMBOL_VALUE, 1},
3156 {":file", IMAGE_STRING_VALUE, 0},
3157 {":data", IMAGE_STRING_VALUE, 0},
3158 {":ascent", IMAGE_ASCENT_VALUE, 0},
3159 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3160 {":relief", IMAGE_INTEGER_VALUE, 0},
3161 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3162 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3163 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3164 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3165 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3168 #if defined HAVE_NTGUI && defined WINDOWSNT
3169 static bool init_xpm_functions (void);
3170 #else
3171 #define init_xpm_functions NULL
3172 #endif
3174 /* Structure describing the image type XPM. */
3176 static struct image_type xpm_type =
3178 &Qxpm,
3179 xpm_image_p,
3180 xpm_load,
3181 x_clear_image,
3182 init_xpm_functions,
3183 NULL
3186 #ifdef HAVE_X_WINDOWS
3188 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3189 functions for allocating image colors. Our own functions handle
3190 color allocation failures more gracefully than the ones on the XPM
3191 lib. */
3193 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3194 #define ALLOC_XPM_COLORS
3195 #endif
3196 #endif /* HAVE_X_WINDOWS */
3198 #ifdef ALLOC_XPM_COLORS
3200 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3201 XColor *, int);
3203 /* An entry in a hash table used to cache color definitions of named
3204 colors. This cache is necessary to speed up XPM image loading in
3205 case we do color allocations ourselves. Without it, we would need
3206 a call to XParseColor per pixel in the image. */
3208 struct xpm_cached_color
3210 /* Next in collision chain. */
3211 struct xpm_cached_color *next;
3213 /* Color definition (RGB and pixel color). */
3214 XColor color;
3216 /* Color name. */
3217 char name[FLEXIBLE_ARRAY_MEMBER];
3220 /* The hash table used for the color cache, and its bucket vector
3221 size. */
3223 #define XPM_COLOR_CACHE_BUCKETS 1001
3224 static struct xpm_cached_color **xpm_color_cache;
3226 /* Initialize the color cache. */
3228 static void
3229 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3231 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3232 xpm_color_cache = xzalloc (nbytes);
3233 init_color_table ();
3235 if (attrs->valuemask & XpmColorSymbols)
3237 int i;
3238 XColor color;
3240 for (i = 0; i < attrs->numsymbols; ++i)
3241 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3242 attrs->colorsymbols[i].value, &color))
3244 color.pixel = lookup_rgb_color (f, color.red, color.green,
3245 color.blue);
3246 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3251 /* Free the color cache. */
3253 static void
3254 xpm_free_color_cache (void)
3256 struct xpm_cached_color *p, *next;
3257 int i;
3259 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3260 for (p = xpm_color_cache[i]; p; p = next)
3262 next = p->next;
3263 xfree (p);
3266 xfree (xpm_color_cache);
3267 xpm_color_cache = NULL;
3268 free_color_table ();
3271 /* Return the bucket index for color named COLOR_NAME in the color
3272 cache. */
3274 static int
3275 xpm_color_bucket (char *color_name)
3277 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3278 return hash % XPM_COLOR_CACHE_BUCKETS;
3282 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3283 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3284 entry added. */
3286 static struct xpm_cached_color *
3287 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3289 size_t nbytes;
3290 struct xpm_cached_color *p;
3292 if (bucket < 0)
3293 bucket = xpm_color_bucket (color_name);
3295 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3296 p = xmalloc (nbytes);
3297 strcpy (p->name, color_name);
3298 p->color = *color;
3299 p->next = xpm_color_cache[bucket];
3300 xpm_color_cache[bucket] = p;
3301 return p;
3304 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3305 return the cached definition in *COLOR. Otherwise, make a new
3306 entry in the cache and allocate the color. Value is false if color
3307 allocation failed. */
3309 static bool
3310 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3312 struct xpm_cached_color *p;
3313 int h = xpm_color_bucket (color_name);
3315 for (p = xpm_color_cache[h]; p; p = p->next)
3316 if (strcmp (p->name, color_name) == 0)
3317 break;
3319 if (p != NULL)
3320 *color = p->color;
3321 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3322 color_name, color))
3324 color->pixel = lookup_rgb_color (f, color->red, color->green,
3325 color->blue);
3326 p = xpm_cache_color (f, color_name, color, h);
3328 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3329 with transparency, and it's useful. */
3330 else if (strcmp ("opaque", color_name) == 0)
3332 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3333 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3334 p = xpm_cache_color (f, color_name, color, h);
3337 return p != NULL;
3341 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3342 CLOSURE is a pointer to the frame on which we allocate the
3343 color. Return in *COLOR the allocated color. Value is non-zero
3344 if successful. */
3346 static int
3347 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3348 void *closure)
3350 return xpm_lookup_color (closure, color_name, color);
3354 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3355 is a pointer to the frame on which we allocate the color. Value is
3356 non-zero if successful. */
3358 static int
3359 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3361 return 1;
3364 #endif /* ALLOC_XPM_COLORS */
3367 #ifdef WINDOWSNT
3369 /* XPM library details. */
3371 DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
3372 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3373 xpm_XImage **, XpmAttributes *));
3374 DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3375 xpm_XImage **, XpmAttributes *));
3376 DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
3378 static bool
3379 init_xpm_functions (void)
3381 HMODULE library;
3383 if (!(library = w32_delayed_load (Qxpm)))
3384 return 0;
3386 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3387 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3388 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3389 LOAD_IMGLIB_FN (library, XImageFree);
3390 return 1;
3393 #endif /* WINDOWSNT */
3395 #if defined HAVE_NTGUI && !defined WINDOWSNT
3396 /* Glue for code below */
3397 #define fn_XpmReadFileToImage XpmReadFileToImage
3398 #define fn_XpmCreateImageFromBuffer XpmCreateImageFromBuffer
3399 #define fn_XImageFree XImageFree
3400 #define fn_XpmFreeAttributes XpmFreeAttributes
3401 #endif /* HAVE_NTGUI && !WINDOWSNT */
3403 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3404 for XPM images. Such a list must consist of conses whose car and
3405 cdr are strings. */
3407 static bool
3408 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3410 while (CONSP (color_symbols))
3412 Lisp_Object sym = XCAR (color_symbols);
3413 if (!CONSP (sym)
3414 || !STRINGP (XCAR (sym))
3415 || !STRINGP (XCDR (sym)))
3416 break;
3417 color_symbols = XCDR (color_symbols);
3420 return NILP (color_symbols);
3424 /* Value is true if OBJECT is a valid XPM image specification. */
3426 static bool
3427 xpm_image_p (Lisp_Object object)
3429 struct image_keyword fmt[XPM_LAST];
3430 memcpy (fmt, xpm_format, sizeof fmt);
3431 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3432 /* Either `:file' or `:data' must be present. */
3433 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3434 /* Either no `:color-symbols' or it's a list of conses
3435 whose car and cdr are strings. */
3436 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3437 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3440 #endif /* HAVE_XPM || HAVE_NS */
3442 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3443 ptrdiff_t
3444 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3446 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3447 ptrdiff_t id;
3448 int rc;
3449 XpmAttributes attrs;
3450 Pixmap bitmap, mask;
3452 memset (&attrs, 0, sizeof attrs);
3454 attrs.visual = FRAME_X_VISUAL (f);
3455 attrs.colormap = FRAME_X_COLORMAP (f);
3456 attrs.valuemask |= XpmVisual;
3457 attrs.valuemask |= XpmColormap;
3459 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3460 (char **) bits, &bitmap, &mask, &attrs);
3461 if (rc != XpmSuccess)
3463 XpmFreeAttributes (&attrs);
3464 return -1;
3467 id = x_allocate_bitmap_record (f);
3468 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3469 dpyinfo->bitmaps[id - 1].have_mask = true;
3470 dpyinfo->bitmaps[id - 1].mask = mask;
3471 dpyinfo->bitmaps[id - 1].file = NULL;
3472 dpyinfo->bitmaps[id - 1].height = attrs.height;
3473 dpyinfo->bitmaps[id - 1].width = attrs.width;
3474 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3475 dpyinfo->bitmaps[id - 1].refcount = 1;
3477 XpmFreeAttributes (&attrs);
3478 return id;
3480 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3482 /* Load image IMG which will be displayed on frame F. Value is
3483 true if successful. */
3485 #ifdef HAVE_XPM
3487 static bool
3488 xpm_load (struct frame *f, struct image *img)
3490 int rc;
3491 XpmAttributes attrs;
3492 Lisp_Object specified_file, color_symbols;
3493 #ifdef HAVE_NTGUI
3494 HDC hdc;
3495 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3496 #endif /* HAVE_NTGUI */
3498 /* Configure the XPM lib. Use the visual of frame F. Allocate
3499 close colors. Return colors allocated. */
3500 memset (&attrs, 0, sizeof attrs);
3502 #ifndef HAVE_NTGUI
3503 attrs.visual = FRAME_X_VISUAL (f);
3504 attrs.colormap = FRAME_X_COLORMAP (f);
3505 attrs.valuemask |= XpmVisual;
3506 attrs.valuemask |= XpmColormap;
3507 #endif /* HAVE_NTGUI */
3509 #ifdef ALLOC_XPM_COLORS
3510 /* Allocate colors with our own functions which handle
3511 failing color allocation more gracefully. */
3512 attrs.color_closure = f;
3513 attrs.alloc_color = xpm_alloc_color;
3514 attrs.free_colors = xpm_free_colors;
3515 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3516 #else /* not ALLOC_XPM_COLORS */
3517 /* Let the XPM lib allocate colors. */
3518 attrs.valuemask |= XpmReturnAllocPixels;
3519 #ifdef XpmAllocCloseColors
3520 attrs.alloc_close_colors = 1;
3521 attrs.valuemask |= XpmAllocCloseColors;
3522 #else /* not XpmAllocCloseColors */
3523 attrs.closeness = 600;
3524 attrs.valuemask |= XpmCloseness;
3525 #endif /* not XpmAllocCloseColors */
3526 #endif /* ALLOC_XPM_COLORS */
3528 /* If image specification contains symbolic color definitions, add
3529 these to `attrs'. */
3530 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3531 if (CONSP (color_symbols))
3533 Lisp_Object tail;
3534 XpmColorSymbol *xpm_syms;
3535 int i, size;
3537 attrs.valuemask |= XpmColorSymbols;
3539 /* Count number of symbols. */
3540 attrs.numsymbols = 0;
3541 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3542 ++attrs.numsymbols;
3544 /* Allocate an XpmColorSymbol array. */
3545 size = attrs.numsymbols * sizeof *xpm_syms;
3546 xpm_syms = alloca (size);
3547 memset (xpm_syms, 0, size);
3548 attrs.colorsymbols = xpm_syms;
3550 /* Fill the color symbol array. */
3551 for (tail = color_symbols, i = 0;
3552 CONSP (tail);
3553 ++i, tail = XCDR (tail))
3555 Lisp_Object name;
3556 Lisp_Object color;
3557 char *empty_string = (char *) "";
3559 if (!CONSP (XCAR (tail)))
3561 xpm_syms[i].name = empty_string;
3562 xpm_syms[i].value = empty_string;
3563 continue;
3565 name = XCAR (XCAR (tail));
3566 color = XCDR (XCAR (tail));
3567 if (STRINGP (name))
3569 xpm_syms[i].name = alloca (SCHARS (name) + 1);
3570 strcpy (xpm_syms[i].name, SSDATA (name));
3572 else
3573 xpm_syms[i].name = empty_string;
3574 if (STRINGP (color))
3576 xpm_syms[i].value = alloca (SCHARS (color) + 1);
3577 strcpy (xpm_syms[i].value, SSDATA (color));
3579 else
3580 xpm_syms[i].value = empty_string;
3584 /* Create a pixmap for the image, either from a file, or from a
3585 string buffer containing data in the same format as an XPM file. */
3586 #ifdef ALLOC_XPM_COLORS
3587 xpm_init_color_cache (f, &attrs);
3588 #endif
3590 specified_file = image_spec_value (img->spec, QCfile, NULL);
3592 #ifdef HAVE_NTGUI
3594 HDC frame_dc = get_frame_dc (f);
3595 hdc = CreateCompatibleDC (frame_dc);
3596 release_frame_dc (f, frame_dc);
3598 #endif /* HAVE_NTGUI */
3600 if (STRINGP (specified_file))
3602 Lisp_Object file = x_find_image_file (specified_file);
3603 if (!STRINGP (file))
3605 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3606 #ifdef ALLOC_XPM_COLORS
3607 xpm_free_color_cache ();
3608 #endif
3609 return 0;
3612 #ifdef HAVE_NTGUI
3613 #ifdef WINDOWSNT
3614 /* FILE is encoded in UTF-8, but image libraries on Windows
3615 support neither UTF-8 nor UTF-16 encoded file names. So we
3616 need to re-encode it in ANSI. */
3617 file = ansi_encode_filename (file);
3618 #endif
3619 /* XpmReadFileToPixmap is not available in the Windows port of
3620 libxpm. But XpmReadFileToImage almost does what we want. */
3621 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3622 &xpm_image, &xpm_mask,
3623 &attrs);
3624 #else
3625 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3626 &img->ximg, &img->mask_img,
3627 &attrs);
3628 #endif /* HAVE_NTGUI */
3630 else
3632 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3633 if (!STRINGP (buffer))
3635 image_error ("Invalid image data `%s'", buffer, Qnil);
3636 #ifdef ALLOC_XPM_COLORS
3637 xpm_free_color_cache ();
3638 #endif
3639 return 0;
3641 #ifdef HAVE_NTGUI
3642 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3643 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3644 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3645 &xpm_image, &xpm_mask,
3646 &attrs);
3647 #else
3648 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3649 &img->ximg, &img->mask_img,
3650 &attrs);
3651 #endif /* HAVE_NTGUI */
3654 #ifdef HAVE_X_WINDOWS
3655 if (rc == XpmSuccess)
3657 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3658 img->ximg->width, img->ximg->height,
3659 img->ximg->depth);
3660 if (img->pixmap == NO_PIXMAP)
3662 x_clear_image (f, img);
3663 rc = XpmNoMemory;
3665 else if (img->mask_img)
3667 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3668 img->mask_img->width,
3669 img->mask_img->height,
3670 img->mask_img->depth);
3671 if (img->mask == NO_PIXMAP)
3673 x_clear_image (f, img);
3674 rc = XpmNoMemory;
3678 #endif
3680 if (rc == XpmSuccess)
3682 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3683 img->colors = colors_in_color_table (&img->ncolors);
3684 #else /* not ALLOC_XPM_COLORS */
3685 int i;
3687 #ifdef HAVE_NTGUI
3688 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3689 plus some duplicate attributes. */
3690 if (xpm_image && xpm_image->bitmap)
3692 img->pixmap = xpm_image->bitmap;
3693 /* XImageFree in libXpm frees XImage struct without destroying
3694 the bitmap, which is what we want. */
3695 fn_XImageFree (xpm_image);
3697 if (xpm_mask && xpm_mask->bitmap)
3699 /* The mask appears to be inverted compared with what we expect.
3700 TODO: invert our expectations. See other places where we
3701 have to invert bits because our idea of masks is backwards. */
3702 HGDIOBJ old_obj;
3703 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3705 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3706 SelectObject (hdc, old_obj);
3708 img->mask = xpm_mask->bitmap;
3709 fn_XImageFree (xpm_mask);
3710 DeleteDC (hdc);
3713 DeleteDC (hdc);
3714 #endif /* HAVE_NTGUI */
3716 /* Remember allocated colors. */
3717 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3718 img->ncolors = attrs.nalloc_pixels;
3719 for (i = 0; i < attrs.nalloc_pixels; ++i)
3721 img->colors[i] = attrs.alloc_pixels[i];
3722 #ifdef DEBUG_X_COLORS
3723 register_color (img->colors[i]);
3724 #endif
3726 #endif /* not ALLOC_XPM_COLORS */
3728 img->width = attrs.width;
3729 img->height = attrs.height;
3730 eassert (img->width > 0 && img->height > 0);
3732 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3733 #ifdef HAVE_NTGUI
3734 fn_XpmFreeAttributes (&attrs);
3735 #else
3736 XpmFreeAttributes (&attrs);
3737 #endif /* HAVE_NTGUI */
3739 #ifdef HAVE_X_WINDOWS
3740 /* Maybe fill in the background field while we have ximg handy. */
3741 IMAGE_BACKGROUND (img, f, img->ximg);
3742 if (img->mask_img)
3743 /* Fill in the background_transparent field while we have the
3744 mask handy. */
3745 image_background_transparent (img, f, img->mask_img);
3746 #endif
3748 else
3750 #ifdef HAVE_NTGUI
3751 DeleteDC (hdc);
3752 #endif /* HAVE_NTGUI */
3754 switch (rc)
3756 case XpmOpenFailed:
3757 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3758 break;
3760 case XpmFileInvalid:
3761 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3762 break;
3764 case XpmNoMemory:
3765 image_error ("Out of memory (%s)", img->spec, Qnil);
3766 break;
3768 case XpmColorFailed:
3769 image_error ("Color allocation error (%s)", img->spec, Qnil);
3770 break;
3772 default:
3773 image_error ("Unknown error (%s)", img->spec, Qnil);
3774 break;
3778 #ifdef ALLOC_XPM_COLORS
3779 xpm_free_color_cache ();
3780 #endif
3781 return rc == XpmSuccess;
3784 #endif /* HAVE_XPM */
3786 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3788 /* XPM support functions for NS where libxpm is not available.
3789 Only XPM version 3 (without any extensions) is supported. */
3791 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3792 int, Lisp_Object);
3793 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3794 const unsigned char *, int);
3795 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3796 int, Lisp_Object);
3797 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3798 const unsigned char *, int);
3800 /* Tokens returned from xpm_scan. */
3802 enum xpm_token
3804 XPM_TK_IDENT = 256,
3805 XPM_TK_STRING,
3806 XPM_TK_EOF
3809 /* Scan an XPM data and return a character (< 256) or a token defined
3810 by enum xpm_token above. *S and END are the start (inclusive) and
3811 the end (exclusive) addresses of the data, respectively. Advance
3812 *S while scanning. If token is either XPM_TK_IDENT or
3813 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3814 length of the corresponding token, respectively. */
3816 static int
3817 xpm_scan (const unsigned char **s,
3818 const unsigned char *end,
3819 const unsigned char **beg,
3820 ptrdiff_t *len)
3822 int c;
3824 while (*s < end)
3826 /* Skip white-space. */
3827 while (*s < end && (c = *(*s)++, c_isspace (c)))
3830 /* gnus-pointer.xpm uses '-' in its identifier.
3831 sb-dir-plus.xpm uses '+' in its identifier. */
3832 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3834 *beg = *s - 1;
3835 while (*s < end
3836 && (c = **s, c_isalnum (c)
3837 || c == '_' || c == '-' || c == '+'))
3838 ++*s;
3839 *len = *s - *beg;
3840 return XPM_TK_IDENT;
3842 else if (c == '"')
3844 *beg = *s;
3845 while (*s < end && **s != '"')
3846 ++*s;
3847 *len = *s - *beg;
3848 if (*s < end)
3849 ++*s;
3850 return XPM_TK_STRING;
3852 else if (c == '/')
3854 if (*s < end && **s == '*')
3856 /* C-style comment. */
3857 ++*s;
3860 while (*s < end && *(*s)++ != '*')
3863 while (*s < end && **s != '/');
3864 if (*s < end)
3865 ++*s;
3867 else
3868 return c;
3870 else
3871 return c;
3874 return XPM_TK_EOF;
3877 /* Functions for color table lookup in XPM data. A key is a string
3878 specifying the color of each pixel in XPM data. A value is either
3879 an integer that specifies a pixel color, Qt that specifies
3880 transparency, or Qnil for the unspecified color. If the length of
3881 the key string is one, a vector is used as a table. Otherwise, a
3882 hash table is used. */
3884 static Lisp_Object
3885 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3886 const unsigned char *,
3887 int,
3888 Lisp_Object),
3889 Lisp_Object (**get_func) (Lisp_Object,
3890 const unsigned char *,
3891 int))
3893 *put_func = xpm_put_color_table_v;
3894 *get_func = xpm_get_color_table_v;
3895 return Fmake_vector (make_number (256), Qnil);
3898 static void
3899 xpm_put_color_table_v (Lisp_Object color_table,
3900 const unsigned char *chars_start,
3901 int chars_len,
3902 Lisp_Object color)
3904 ASET (color_table, *chars_start, color);
3907 static Lisp_Object
3908 xpm_get_color_table_v (Lisp_Object color_table,
3909 const unsigned char *chars_start,
3910 int chars_len)
3912 return AREF (color_table, *chars_start);
3915 static Lisp_Object
3916 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3917 const unsigned char *,
3918 int,
3919 Lisp_Object),
3920 Lisp_Object (**get_func) (Lisp_Object,
3921 const unsigned char *,
3922 int))
3924 *put_func = xpm_put_color_table_h;
3925 *get_func = xpm_get_color_table_h;
3926 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
3927 make_float (DEFAULT_REHASH_SIZE),
3928 make_float (DEFAULT_REHASH_THRESHOLD),
3929 Qnil);
3932 static void
3933 xpm_put_color_table_h (Lisp_Object color_table,
3934 const unsigned char *chars_start,
3935 int chars_len,
3936 Lisp_Object color)
3938 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3939 EMACS_UINT hash_code;
3940 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3942 hash_lookup (table, chars, &hash_code);
3943 hash_put (table, chars, color, hash_code);
3946 static Lisp_Object
3947 xpm_get_color_table_h (Lisp_Object color_table,
3948 const unsigned char *chars_start,
3949 int chars_len)
3951 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3952 ptrdiff_t i =
3953 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
3955 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3958 enum xpm_color_key {
3959 XPM_COLOR_KEY_S,
3960 XPM_COLOR_KEY_M,
3961 XPM_COLOR_KEY_G4,
3962 XPM_COLOR_KEY_G,
3963 XPM_COLOR_KEY_C
3966 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3968 static int
3969 xpm_str_to_color_key (const char *s)
3971 int i;
3973 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
3974 if (strcmp (xpm_color_key_strings[i], s) == 0)
3975 return i;
3976 return -1;
3979 static bool
3980 xpm_load_image (struct frame *f,
3981 struct image *img,
3982 const unsigned char *contents,
3983 const unsigned char *end)
3985 const unsigned char *s = contents, *beg, *str;
3986 unsigned char buffer[BUFSIZ];
3987 int width, height, x, y;
3988 int num_colors, chars_per_pixel;
3989 ptrdiff_t len;
3990 int LA1;
3991 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3992 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3993 Lisp_Object frame, color_symbols, color_table;
3994 int best_key;
3995 bool have_mask = false;
3996 XImagePtr ximg = NULL, mask_img = NULL;
3998 #define match() \
3999 LA1 = xpm_scan (&s, end, &beg, &len)
4001 #define expect(TOKEN) \
4002 do \
4004 if (LA1 != (TOKEN)) \
4005 goto failure; \
4006 match (); \
4008 while (0)
4010 #define expect_ident(IDENT) \
4011 if (LA1 == XPM_TK_IDENT \
4012 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4013 match (); \
4014 else \
4015 goto failure
4017 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4018 goto failure;
4019 s += 9;
4020 match ();
4021 expect_ident ("static");
4022 expect_ident ("char");
4023 expect ('*');
4024 expect (XPM_TK_IDENT);
4025 expect ('[');
4026 expect (']');
4027 expect ('=');
4028 expect ('{');
4029 expect (XPM_TK_STRING);
4030 if (len >= BUFSIZ)
4031 goto failure;
4032 memcpy (buffer, beg, len);
4033 buffer[len] = '\0';
4034 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4035 &num_colors, &chars_per_pixel) != 4
4036 || width <= 0 || height <= 0
4037 || num_colors <= 0 || chars_per_pixel <= 0)
4038 goto failure;
4040 if (!check_image_size (f, width, height))
4042 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
4043 goto failure;
4046 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4047 #ifndef HAVE_NS
4048 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4049 &mask_img, 1)
4050 #endif
4053 image_error ("Image too large", Qnil, Qnil);
4054 goto failure;
4057 expect (',');
4059 XSETFRAME (frame, f);
4060 if (!NILP (Fxw_display_color_p (frame)))
4061 best_key = XPM_COLOR_KEY_C;
4062 else if (!NILP (Fx_display_grayscale_p (frame)))
4063 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4064 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4065 else
4066 best_key = XPM_COLOR_KEY_M;
4068 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4069 if (chars_per_pixel == 1)
4070 color_table = xpm_make_color_table_v (&put_color_table,
4071 &get_color_table);
4072 else
4073 color_table = xpm_make_color_table_h (&put_color_table,
4074 &get_color_table);
4076 while (num_colors-- > 0)
4078 char *color, *max_color;
4079 int key, next_key, max_key = 0;
4080 Lisp_Object symbol_color = Qnil, color_val;
4081 XColor cdef;
4083 expect (XPM_TK_STRING);
4084 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4085 goto failure;
4086 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4087 buffer[len - chars_per_pixel] = '\0';
4089 str = strtok (buffer, " \t");
4090 if (str == NULL)
4091 goto failure;
4092 key = xpm_str_to_color_key (str);
4093 if (key < 0)
4094 goto failure;
4097 color = strtok (NULL, " \t");
4098 if (color == NULL)
4099 goto failure;
4101 while ((str = strtok (NULL, " \t")) != NULL)
4103 next_key = xpm_str_to_color_key (str);
4104 if (next_key >= 0)
4105 break;
4106 color[strlen (color)] = ' ';
4109 if (key == XPM_COLOR_KEY_S)
4111 if (NILP (symbol_color))
4112 symbol_color = build_string (color);
4114 else if (max_key < key && key <= best_key)
4116 max_key = key;
4117 max_color = color;
4119 key = next_key;
4121 while (str);
4123 color_val = Qnil;
4124 if (!NILP (color_symbols) && !NILP (symbol_color))
4126 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4128 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4130 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4131 color_val = Qt;
4132 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4133 &cdef, 0))
4134 color_val = make_number (cdef.pixel);
4137 if (NILP (color_val) && max_key > 0)
4139 if (xstrcasecmp (max_color, "None") == 0)
4140 color_val = Qt;
4141 else if (x_defined_color (f, max_color, &cdef, 0))
4142 color_val = make_number (cdef.pixel);
4144 if (!NILP (color_val))
4145 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4147 expect (',');
4150 for (y = 0; y < height; y++)
4152 expect (XPM_TK_STRING);
4153 str = beg;
4154 if (len < width * chars_per_pixel)
4155 goto failure;
4156 for (x = 0; x < width; x++, str += chars_per_pixel)
4158 Lisp_Object color_val =
4159 (*get_color_table) (color_table, str, chars_per_pixel);
4161 XPutPixel (ximg, x, y,
4162 (INTEGERP (color_val) ? XINT (color_val)
4163 : FRAME_FOREGROUND_PIXEL (f)));
4164 #ifndef HAVE_NS
4165 XPutPixel (mask_img, x, y,
4166 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4167 : (have_mask = true, PIX_MASK_RETAIN)));
4168 #else
4169 if (EQ (color_val, Qt))
4170 ns_set_alpha (ximg, x, y, 0);
4171 #endif
4173 if (y + 1 < height)
4174 expect (',');
4177 img->width = width;
4178 img->height = height;
4180 /* Maybe fill in the background field while we have ximg handy. */
4181 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4182 IMAGE_BACKGROUND (img, f, ximg);
4184 image_put_x_image (f, img, ximg, 0);
4185 #ifndef HAVE_NS
4186 if (have_mask)
4188 /* Fill in the background_transparent field while we have the
4189 mask handy. */
4190 image_background_transparent (img, f, mask_img);
4192 image_put_x_image (f, img, mask_img, 1);
4194 else
4196 x_destroy_x_image (mask_img);
4197 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4199 #endif
4200 return 1;
4202 failure:
4203 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4204 x_destroy_x_image (ximg);
4205 x_destroy_x_image (mask_img);
4206 x_clear_image (f, img);
4207 return 0;
4209 #undef match
4210 #undef expect
4211 #undef expect_ident
4214 static bool
4215 xpm_load (struct frame *f,
4216 struct image *img)
4218 bool success_p = 0;
4219 Lisp_Object file_name;
4221 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4222 file_name = image_spec_value (img->spec, QCfile, NULL);
4223 if (STRINGP (file_name))
4225 Lisp_Object file;
4226 unsigned char *contents;
4227 ptrdiff_t size;
4229 file = x_find_image_file (file_name);
4230 if (!STRINGP (file))
4232 image_error ("Cannot find image file `%s'", file_name, Qnil);
4233 return 0;
4236 contents = slurp_file (SSDATA (file), &size);
4237 if (contents == NULL)
4239 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4240 return 0;
4243 success_p = xpm_load_image (f, img, contents, contents + size);
4244 xfree (contents);
4246 else
4248 Lisp_Object data;
4250 data = image_spec_value (img->spec, QCdata, NULL);
4251 if (!STRINGP (data))
4253 image_error ("Invalid image data `%s'", data, Qnil);
4254 return 0;
4256 success_p = xpm_load_image (f, img, SDATA (data),
4257 SDATA (data) + SBYTES (data));
4260 return success_p;
4263 #endif /* HAVE_NS && !HAVE_XPM */
4267 /***********************************************************************
4268 Color table
4269 ***********************************************************************/
4271 #ifdef COLOR_TABLE_SUPPORT
4273 /* An entry in the color table mapping an RGB color to a pixel color. */
4275 struct ct_color
4277 int r, g, b;
4278 unsigned long pixel;
4280 /* Next in color table collision list. */
4281 struct ct_color *next;
4284 /* The bucket vector size to use. Must be prime. */
4286 #define CT_SIZE 101
4288 /* Value is a hash of the RGB color given by R, G, and B. */
4290 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4292 /* The color hash table. */
4294 static struct ct_color **ct_table;
4296 /* Number of entries in the color table. */
4298 static int ct_colors_allocated;
4299 enum
4301 ct_colors_allocated_max =
4302 min (INT_MAX,
4303 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4306 /* Initialize the color table. */
4308 static void
4309 init_color_table (void)
4311 int size = CT_SIZE * sizeof (*ct_table);
4312 ct_table = xzalloc (size);
4313 ct_colors_allocated = 0;
4317 /* Free memory associated with the color table. */
4319 static void
4320 free_color_table (void)
4322 int i;
4323 struct ct_color *p, *next;
4325 for (i = 0; i < CT_SIZE; ++i)
4326 for (p = ct_table[i]; p; p = next)
4328 next = p->next;
4329 xfree (p);
4332 xfree (ct_table);
4333 ct_table = NULL;
4337 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4338 entry for that color already is in the color table, return the
4339 pixel color of that entry. Otherwise, allocate a new color for R,
4340 G, B, and make an entry in the color table. */
4342 static unsigned long
4343 lookup_rgb_color (struct frame *f, int r, int g, int b)
4345 unsigned hash = CT_HASH_RGB (r, g, b);
4346 int i = hash % CT_SIZE;
4347 struct ct_color *p;
4348 Display_Info *dpyinfo;
4350 /* Handle TrueColor visuals specially, which improves performance by
4351 two orders of magnitude. Freeing colors on TrueColor visuals is
4352 a nop, and pixel colors specify RGB values directly. See also
4353 the Xlib spec, chapter 3.1. */
4354 dpyinfo = FRAME_DISPLAY_INFO (f);
4355 if (dpyinfo->red_bits > 0)
4357 unsigned long pr, pg, pb;
4359 /* Apply gamma-correction like normal color allocation does. */
4360 if (f->gamma)
4362 XColor color;
4363 color.red = r, color.green = g, color.blue = b;
4364 gamma_correct (f, &color);
4365 r = color.red, g = color.green, b = color.blue;
4368 /* Scale down RGB values to the visual's bits per RGB, and shift
4369 them to the right position in the pixel color. Note that the
4370 original RGB values are 16-bit values, as usual in X. */
4371 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4372 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4373 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4375 /* Assemble the pixel color. */
4376 return pr | pg | pb;
4379 for (p = ct_table[i]; p; p = p->next)
4380 if (p->r == r && p->g == g && p->b == b)
4381 break;
4383 if (p == NULL)
4386 #ifdef HAVE_X_WINDOWS
4387 XColor color;
4388 Colormap cmap;
4389 bool rc;
4390 #else
4391 COLORREF color;
4392 #endif
4394 if (ct_colors_allocated_max <= ct_colors_allocated)
4395 return FRAME_FOREGROUND_PIXEL (f);
4397 #ifdef HAVE_X_WINDOWS
4398 color.red = r;
4399 color.green = g;
4400 color.blue = b;
4402 cmap = FRAME_X_COLORMAP (f);
4403 rc = x_alloc_nearest_color (f, cmap, &color);
4404 if (rc)
4406 ++ct_colors_allocated;
4407 p = xmalloc (sizeof *p);
4408 p->r = r;
4409 p->g = g;
4410 p->b = b;
4411 p->pixel = color.pixel;
4412 p->next = ct_table[i];
4413 ct_table[i] = p;
4415 else
4416 return FRAME_FOREGROUND_PIXEL (f);
4418 #else
4419 #ifdef HAVE_NTGUI
4420 color = PALETTERGB (r, g, b);
4421 #else
4422 color = RGB_TO_ULONG (r, g, b);
4423 #endif /* HAVE_NTGUI */
4424 ++ct_colors_allocated;
4425 p = xmalloc (sizeof *p);
4426 p->r = r;
4427 p->g = g;
4428 p->b = b;
4429 p->pixel = color;
4430 p->next = ct_table[i];
4431 ct_table[i] = p;
4432 #endif /* HAVE_X_WINDOWS */
4436 return p->pixel;
4440 /* Look up pixel color PIXEL which is used on frame F in the color
4441 table. If not already present, allocate it. Value is PIXEL. */
4443 static unsigned long
4444 lookup_pixel_color (struct frame *f, unsigned long pixel)
4446 int i = pixel % CT_SIZE;
4447 struct ct_color *p;
4449 for (p = ct_table[i]; p; p = p->next)
4450 if (p->pixel == pixel)
4451 break;
4453 if (p == NULL)
4455 XColor color;
4456 Colormap cmap;
4457 bool rc;
4459 if (ct_colors_allocated_max <= ct_colors_allocated)
4460 return FRAME_FOREGROUND_PIXEL (f);
4462 #ifdef HAVE_X_WINDOWS
4463 cmap = FRAME_X_COLORMAP (f);
4464 color.pixel = pixel;
4465 x_query_color (f, &color);
4466 rc = x_alloc_nearest_color (f, cmap, &color);
4467 #else
4468 block_input ();
4469 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4470 color.pixel = pixel;
4471 XQueryColor (NULL, cmap, &color);
4472 rc = x_alloc_nearest_color (f, cmap, &color);
4473 unblock_input ();
4474 #endif /* HAVE_X_WINDOWS */
4476 if (rc)
4478 ++ct_colors_allocated;
4480 p = xmalloc (sizeof *p);
4481 p->r = color.red;
4482 p->g = color.green;
4483 p->b = color.blue;
4484 p->pixel = pixel;
4485 p->next = ct_table[i];
4486 ct_table[i] = p;
4488 else
4489 return FRAME_FOREGROUND_PIXEL (f);
4491 return p->pixel;
4495 /* Value is a vector of all pixel colors contained in the color table,
4496 allocated via xmalloc. Set *N to the number of colors. */
4498 static unsigned long *
4499 colors_in_color_table (int *n)
4501 int i, j;
4502 struct ct_color *p;
4503 unsigned long *colors;
4505 if (ct_colors_allocated == 0)
4507 *n = 0;
4508 colors = NULL;
4510 else
4512 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4513 *n = ct_colors_allocated;
4515 for (i = j = 0; i < CT_SIZE; ++i)
4516 for (p = ct_table[i]; p; p = p->next)
4517 colors[j++] = p->pixel;
4520 return colors;
4523 #else /* COLOR_TABLE_SUPPORT */
4525 static unsigned long
4526 lookup_rgb_color (struct frame *f, int r, int g, int b)
4528 unsigned long pixel;
4530 #ifdef HAVE_NTGUI
4531 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4532 #endif /* HAVE_NTGUI */
4534 #ifdef HAVE_NS
4535 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4536 #endif /* HAVE_NS */
4537 return pixel;
4540 static void
4541 init_color_table (void)
4544 #endif /* COLOR_TABLE_SUPPORT */
4547 /***********************************************************************
4548 Algorithms
4549 ***********************************************************************/
4551 /* Edge detection matrices for different edge-detection
4552 strategies. */
4554 static int emboss_matrix[9] = {
4555 /* x - 1 x x + 1 */
4556 2, -1, 0, /* y - 1 */
4557 -1, 0, 1, /* y */
4558 0, 1, -2 /* y + 1 */
4561 static int laplace_matrix[9] = {
4562 /* x - 1 x x + 1 */
4563 1, 0, 0, /* y - 1 */
4564 0, 0, 0, /* y */
4565 0, 0, -1 /* y + 1 */
4568 /* Value is the intensity of the color whose red/green/blue values
4569 are R, G, and B. */
4571 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4574 /* On frame F, return an array of XColor structures describing image
4575 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4576 means also fill the red/green/blue members of the XColor
4577 structures. Value is a pointer to the array of XColors structures,
4578 allocated with xmalloc; it must be freed by the caller. */
4580 static XColor *
4581 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4583 int x, y;
4584 XColor *colors, *p;
4585 XImagePtr_or_DC ximg;
4586 #ifdef HAVE_NTGUI
4587 HGDIOBJ prev;
4588 #endif /* HAVE_NTGUI */
4590 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width < img->height)
4591 memory_full (SIZE_MAX);
4592 colors = xmalloc (sizeof *colors * img->width * img->height);
4594 /* Get the X image or create a memory device context for IMG. */
4595 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4597 /* Fill the `pixel' members of the XColor array. I wished there
4598 were an easy and portable way to circumvent XGetPixel. */
4599 p = colors;
4600 for (y = 0; y < img->height; ++y)
4602 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4603 XColor *row = p;
4604 for (x = 0; x < img->width; ++x, ++p)
4605 p->pixel = GET_PIXEL (ximg, x, y);
4606 if (rgb_p)
4607 x_query_colors (f, row, img->width);
4609 #else
4611 for (x = 0; x < img->width; ++x, ++p)
4613 /* W32_TODO: palette support needed here? */
4614 p->pixel = GET_PIXEL (ximg, x, y);
4615 if (rgb_p)
4617 p->red = RED16_FROM_ULONG (p->pixel);
4618 p->green = GREEN16_FROM_ULONG (p->pixel);
4619 p->blue = BLUE16_FROM_ULONG (p->pixel);
4622 #endif /* HAVE_X_WINDOWS */
4625 image_unget_x_image_or_dc (img, 0, ximg, prev);
4627 return colors;
4630 #ifdef HAVE_NTGUI
4632 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4633 created with CreateDIBSection, with the pointer to the bit values
4634 stored in ximg->data. */
4636 static void
4637 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4639 int width = ximg->info.bmiHeader.biWidth;
4640 unsigned char * pixel;
4642 /* True color images. */
4643 if (ximg->info.bmiHeader.biBitCount == 24)
4645 int rowbytes = width * 3;
4646 /* Ensure scanlines are aligned on 4 byte boundaries. */
4647 if (rowbytes % 4)
4648 rowbytes += 4 - (rowbytes % 4);
4650 pixel = ximg->data + y * rowbytes + x * 3;
4651 /* Windows bitmaps are in BGR order. */
4652 *pixel = GetBValue (color);
4653 *(pixel + 1) = GetGValue (color);
4654 *(pixel + 2) = GetRValue (color);
4656 /* Monochrome images. */
4657 else if (ximg->info.bmiHeader.biBitCount == 1)
4659 int rowbytes = width / 8;
4660 /* Ensure scanlines are aligned on 4 byte boundaries. */
4661 if (rowbytes % 4)
4662 rowbytes += 4 - (rowbytes % 4);
4663 pixel = ximg->data + y * rowbytes + x / 8;
4664 /* Filter out palette info. */
4665 if (color & 0x00ffffff)
4666 *pixel = *pixel | (1 << x % 8);
4667 else
4668 *pixel = *pixel & ~(1 << x % 8);
4670 else
4671 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4674 #endif /* HAVE_NTGUI */
4676 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4677 RGB members are set. F is the frame on which this all happens.
4678 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4680 static void
4681 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4683 int x, y;
4684 XImagePtr oimg = NULL;
4685 XColor *p;
4687 init_color_table ();
4689 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4690 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4691 &oimg, 0);
4692 p = colors;
4693 for (y = 0; y < img->height; ++y)
4694 for (x = 0; x < img->width; ++x, ++p)
4696 unsigned long pixel;
4697 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4698 XPutPixel (oimg, x, y, pixel);
4701 xfree (colors);
4703 image_put_x_image (f, img, oimg, 0);
4704 #ifdef COLOR_TABLE_SUPPORT
4705 img->colors = colors_in_color_table (&img->ncolors);
4706 free_color_table ();
4707 #endif /* COLOR_TABLE_SUPPORT */
4711 /* On frame F, perform edge-detection on image IMG.
4713 MATRIX is a nine-element array specifying the transformation
4714 matrix. See emboss_matrix for an example.
4716 COLOR_ADJUST is a color adjustment added to each pixel of the
4717 outgoing image. */
4719 static void
4720 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4722 XColor *colors = x_to_xcolors (f, img, 1);
4723 XColor *new, *p;
4724 int x, y, i, sum;
4726 for (i = sum = 0; i < 9; ++i)
4727 sum += eabs (matrix[i]);
4729 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4731 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width < img->height)
4732 memory_full (SIZE_MAX);
4733 new = xmalloc (sizeof *new * img->width * img->height);
4735 for (y = 0; y < img->height; ++y)
4737 p = COLOR (new, 0, y);
4738 p->red = p->green = p->blue = 0xffff/2;
4739 p = COLOR (new, img->width - 1, y);
4740 p->red = p->green = p->blue = 0xffff/2;
4743 for (x = 1; x < img->width - 1; ++x)
4745 p = COLOR (new, x, 0);
4746 p->red = p->green = p->blue = 0xffff/2;
4747 p = COLOR (new, x, img->height - 1);
4748 p->red = p->green = p->blue = 0xffff/2;
4751 for (y = 1; y < img->height - 1; ++y)
4753 p = COLOR (new, 1, y);
4755 for (x = 1; x < img->width - 1; ++x, ++p)
4757 int r, g, b, yy, xx;
4759 r = g = b = i = 0;
4760 for (yy = y - 1; yy < y + 2; ++yy)
4761 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4762 if (matrix[i])
4764 XColor *t = COLOR (colors, xx, yy);
4765 r += matrix[i] * t->red;
4766 g += matrix[i] * t->green;
4767 b += matrix[i] * t->blue;
4770 r = (r / sum + color_adjust) & 0xffff;
4771 g = (g / sum + color_adjust) & 0xffff;
4772 b = (b / sum + color_adjust) & 0xffff;
4773 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4777 xfree (colors);
4778 x_from_xcolors (f, img, new);
4780 #undef COLOR
4784 /* Perform the pre-defined `emboss' edge-detection on image IMG
4785 on frame F. */
4787 static void
4788 x_emboss (struct frame *f, struct image *img)
4790 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4794 /* Transform image IMG which is used on frame F with a Laplace
4795 edge-detection algorithm. The result is an image that can be used
4796 to draw disabled buttons, for example. */
4798 static void
4799 x_laplace (struct frame *f, struct image *img)
4801 x_detect_edges (f, img, laplace_matrix, 45000);
4805 /* Perform edge-detection on image IMG on frame F, with specified
4806 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4808 MATRIX must be either
4810 - a list of at least 9 numbers in row-major form
4811 - a vector of at least 9 numbers
4813 COLOR_ADJUST nil means use a default; otherwise it must be a
4814 number. */
4816 static void
4817 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4818 Lisp_Object color_adjust)
4820 int i = 0;
4821 int trans[9];
4823 if (CONSP (matrix))
4825 for (i = 0;
4826 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4827 ++i, matrix = XCDR (matrix))
4828 trans[i] = XFLOATINT (XCAR (matrix));
4830 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4832 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4833 trans[i] = XFLOATINT (AREF (matrix, i));
4836 if (NILP (color_adjust))
4837 color_adjust = make_number (0xffff / 2);
4839 if (i == 9 && NUMBERP (color_adjust))
4840 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4844 /* Transform image IMG on frame F so that it looks disabled. */
4846 static void
4847 x_disable_image (struct frame *f, struct image *img)
4849 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4850 #ifdef HAVE_NTGUI
4851 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4852 #else
4853 int n_planes = dpyinfo->n_planes;
4854 #endif /* HAVE_NTGUI */
4856 if (n_planes >= 2)
4858 /* Color (or grayscale). Convert to gray, and equalize. Just
4859 drawing such images with a stipple can look very odd, so
4860 we're using this method instead. */
4861 XColor *colors = x_to_xcolors (f, img, 1);
4862 XColor *p, *end;
4863 const int h = 15000;
4864 const int l = 30000;
4866 for (p = colors, end = colors + img->width * img->height;
4867 p < end;
4868 ++p)
4870 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4871 int i2 = (0xffff - h - l) * i / 0xffff + l;
4872 p->red = p->green = p->blue = i2;
4875 x_from_xcolors (f, img, colors);
4878 /* Draw a cross over the disabled image, if we must or if we
4879 should. */
4880 if (n_planes < 2 || cross_disabled_images)
4882 #ifndef HAVE_NTGUI
4883 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4885 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4887 Display *dpy = FRAME_X_DISPLAY (f);
4888 GC gc;
4890 image_sync_to_pixmaps (f, img);
4891 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4892 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4893 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4894 img->width - 1, img->height - 1);
4895 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4896 img->width - 1, 0);
4897 XFreeGC (dpy, gc);
4899 if (img->mask)
4901 gc = XCreateGC (dpy, img->mask, 0, NULL);
4902 XSetForeground (dpy, gc, MaskForeground (f));
4903 XDrawLine (dpy, img->mask, gc, 0, 0,
4904 img->width - 1, img->height - 1);
4905 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4906 img->width - 1, 0);
4907 XFreeGC (dpy, gc);
4909 #endif /* !HAVE_NS */
4910 #else
4911 HDC hdc, bmpdc;
4912 HGDIOBJ prev;
4914 hdc = get_frame_dc (f);
4915 bmpdc = CreateCompatibleDC (hdc);
4916 release_frame_dc (f, hdc);
4918 prev = SelectObject (bmpdc, img->pixmap);
4920 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4921 MoveToEx (bmpdc, 0, 0, NULL);
4922 LineTo (bmpdc, img->width - 1, img->height - 1);
4923 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4924 LineTo (bmpdc, img->width - 1, 0);
4926 if (img->mask)
4928 SelectObject (bmpdc, img->mask);
4929 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4930 MoveToEx (bmpdc, 0, 0, NULL);
4931 LineTo (bmpdc, img->width - 1, img->height - 1);
4932 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4933 LineTo (bmpdc, img->width - 1, 0);
4935 SelectObject (bmpdc, prev);
4936 DeleteDC (bmpdc);
4937 #endif /* HAVE_NTGUI */
4942 /* Build a mask for image IMG which is used on frame F. FILE is the
4943 name of an image file, for error messages. HOW determines how to
4944 determine the background color of IMG. If it is a list '(R G B)',
4945 with R, G, and B being integers >= 0, take that as the color of the
4946 background. Otherwise, determine the background color of IMG
4947 heuristically. */
4949 static void
4950 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4952 XImagePtr_or_DC ximg;
4953 #ifndef HAVE_NTGUI
4954 XImagePtr mask_img;
4955 #else
4956 HGDIOBJ prev;
4957 char *mask_img;
4958 int row_width;
4959 #endif /* HAVE_NTGUI */
4960 int x, y;
4961 bool use_img_background;
4962 unsigned long bg = 0;
4964 if (img->mask)
4965 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4967 #ifndef HAVE_NTGUI
4968 #ifndef HAVE_NS
4969 /* Create an image and pixmap serving as mask. */
4970 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
4971 &mask_img, 1))
4972 return;
4973 #endif /* !HAVE_NS */
4974 #else
4975 /* Create the bit array serving as mask. */
4976 row_width = (img->width + 7) / 8;
4977 mask_img = xzalloc (row_width * img->height);
4978 #endif /* HAVE_NTGUI */
4980 /* Get the X image or create a memory device context for IMG. */
4981 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4983 /* Determine the background color of ximg. If HOW is `(R G B)'
4984 take that as color. Otherwise, use the image's background color. */
4985 use_img_background = 1;
4987 if (CONSP (how))
4989 int rgb[3], i;
4991 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4993 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4994 how = XCDR (how);
4997 if (i == 3 && NILP (how))
4999 char color_name[30];
5000 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
5001 bg = (
5002 #ifdef HAVE_NTGUI
5003 0x00ffffff & /* Filter out palette info. */
5004 #endif /* HAVE_NTGUI */
5005 x_alloc_image_color (f, img, build_string (color_name), 0));
5006 use_img_background = 0;
5010 if (use_img_background)
5011 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5013 /* Set all bits in mask_img to 1 whose color in ximg is different
5014 from the background color bg. */
5015 #ifndef HAVE_NTGUI
5016 for (y = 0; y < img->height; ++y)
5017 for (x = 0; x < img->width; ++x)
5018 #ifndef HAVE_NS
5019 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5020 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5021 #else
5022 if (XGetPixel (ximg, x, y) == bg)
5023 ns_set_alpha (ximg, x, y, 0);
5024 #endif /* HAVE_NS */
5025 #ifndef HAVE_NS
5026 /* Fill in the background_transparent field while we have the mask handy. */
5027 image_background_transparent (img, f, mask_img);
5029 /* Put mask_img into the image. */
5030 image_put_x_image (f, img, mask_img, 1);
5031 #endif /* !HAVE_NS */
5032 #else
5033 for (y = 0; y < img->height; ++y)
5034 for (x = 0; x < img->width; ++x)
5036 COLORREF p = GetPixel (ximg, x, y);
5037 if (p != bg)
5038 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5041 /* Create the mask image. */
5042 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5043 mask_img);
5044 /* Fill in the background_transparent field while we have the mask handy. */
5045 SelectObject (ximg, img->mask);
5046 image_background_transparent (img, f, ximg);
5048 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5049 xfree (mask_img);
5050 #endif /* HAVE_NTGUI */
5052 image_unget_x_image_or_dc (img, 0, ximg, prev);
5056 /***********************************************************************
5057 PBM (mono, gray, color)
5058 ***********************************************************************/
5060 static bool pbm_image_p (Lisp_Object object);
5061 static bool pbm_load (struct frame *f, struct image *img);
5063 /* The symbol `pbm' identifying images of this type. */
5065 static Lisp_Object Qpbm;
5067 /* Indices of image specification fields in gs_format, below. */
5069 enum pbm_keyword_index
5071 PBM_TYPE,
5072 PBM_FILE,
5073 PBM_DATA,
5074 PBM_ASCENT,
5075 PBM_MARGIN,
5076 PBM_RELIEF,
5077 PBM_ALGORITHM,
5078 PBM_HEURISTIC_MASK,
5079 PBM_MASK,
5080 PBM_FOREGROUND,
5081 PBM_BACKGROUND,
5082 PBM_LAST
5085 /* Vector of image_keyword structures describing the format
5086 of valid user-defined image specifications. */
5088 static const struct image_keyword pbm_format[PBM_LAST] =
5090 {":type", IMAGE_SYMBOL_VALUE, 1},
5091 {":file", IMAGE_STRING_VALUE, 0},
5092 {":data", IMAGE_STRING_VALUE, 0},
5093 {":ascent", IMAGE_ASCENT_VALUE, 0},
5094 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5095 {":relief", IMAGE_INTEGER_VALUE, 0},
5096 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5097 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5098 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5099 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5100 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5103 /* Structure describing the image type `pbm'. */
5105 static struct image_type pbm_type =
5107 &Qpbm,
5108 pbm_image_p,
5109 pbm_load,
5110 x_clear_image,
5111 NULL,
5112 NULL
5116 /* Return true if OBJECT is a valid PBM image specification. */
5118 static bool
5119 pbm_image_p (Lisp_Object object)
5121 struct image_keyword fmt[PBM_LAST];
5123 memcpy (fmt, pbm_format, sizeof fmt);
5125 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5126 return 0;
5128 /* Must specify either :data or :file. */
5129 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5133 /* Get next char skipping comments in Netpbm header. Returns -1 at
5134 end of input. */
5136 static int
5137 pbm_next_char (unsigned char **s, unsigned char *end)
5139 int c = -1;
5141 while (*s < end && (c = *(*s)++, c == '#'))
5143 /* Skip to the next line break. */
5144 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5147 c = -1;
5150 return c;
5154 /* Scan a decimal number from *S and return it. Advance *S while
5155 reading the number. END is the end of the string. Value is -1 at
5156 end of input. */
5158 static int
5159 pbm_scan_number (unsigned char **s, unsigned char *end)
5161 int c = 0, val = -1;
5163 /* Skip white-space. */
5164 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5167 if (c_isdigit (c))
5169 /* Read decimal number. */
5170 val = c - '0';
5171 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5172 val = 10 * val + c - '0';
5175 return val;
5179 /* Load PBM image IMG for use on frame F. */
5181 static bool
5182 pbm_load (struct frame *f, struct image *img)
5184 bool raw_p;
5185 int x, y;
5186 int width, height, max_color_idx = 0;
5187 XImagePtr ximg;
5188 Lisp_Object file, specified_file;
5189 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5190 unsigned char *contents = NULL;
5191 unsigned char *end, *p;
5192 ptrdiff_t size;
5194 specified_file = image_spec_value (img->spec, QCfile, NULL);
5196 if (STRINGP (specified_file))
5198 file = x_find_image_file (specified_file);
5199 if (!STRINGP (file))
5201 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5202 return 0;
5205 contents = slurp_file (SSDATA (file), &size);
5206 if (contents == NULL)
5208 image_error ("Error reading `%s'", file, Qnil);
5209 return 0;
5212 p = contents;
5213 end = contents + size;
5215 else
5217 Lisp_Object data;
5218 data = image_spec_value (img->spec, QCdata, NULL);
5219 if (!STRINGP (data))
5221 image_error ("Invalid image data `%s'", data, Qnil);
5222 return 0;
5224 p = SDATA (data);
5225 end = p + SBYTES (data);
5228 /* Check magic number. */
5229 if (end - p < 2 || *p++ != 'P')
5231 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5232 error:
5233 xfree (contents);
5234 img->pixmap = NO_PIXMAP;
5235 return 0;
5238 switch (*p++)
5240 case '1':
5241 raw_p = 0, type = PBM_MONO;
5242 break;
5244 case '2':
5245 raw_p = 0, type = PBM_GRAY;
5246 break;
5248 case '3':
5249 raw_p = 0, type = PBM_COLOR;
5250 break;
5252 case '4':
5253 raw_p = 1, type = PBM_MONO;
5254 break;
5256 case '5':
5257 raw_p = 1, type = PBM_GRAY;
5258 break;
5260 case '6':
5261 raw_p = 1, type = PBM_COLOR;
5262 break;
5264 default:
5265 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5266 goto error;
5269 /* Read width, height, maximum color-component. Characters
5270 starting with `#' up to the end of a line are ignored. */
5271 width = pbm_scan_number (&p, end);
5272 height = pbm_scan_number (&p, end);
5274 if (type != PBM_MONO)
5276 max_color_idx = pbm_scan_number (&p, end);
5277 if (max_color_idx > 65535 || max_color_idx < 0)
5279 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5280 goto error;
5284 if (!check_image_size (f, width, height))
5286 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5287 goto error;
5290 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5291 goto error;
5293 /* Initialize the color hash table. */
5294 init_color_table ();
5296 if (type == PBM_MONO)
5298 int c = 0, g;
5299 struct image_keyword fmt[PBM_LAST];
5300 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5301 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5303 /* Parse the image specification. */
5304 memcpy (fmt, pbm_format, sizeof fmt);
5305 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5307 /* Get foreground and background colors, maybe allocate colors. */
5308 if (fmt[PBM_FOREGROUND].count
5309 && STRINGP (fmt[PBM_FOREGROUND].value))
5310 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5311 if (fmt[PBM_BACKGROUND].count
5312 && STRINGP (fmt[PBM_BACKGROUND].value))
5314 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5315 img->background = bg;
5316 img->background_valid = 1;
5319 for (y = 0; y < height; ++y)
5320 for (x = 0; x < width; ++x)
5322 if (raw_p)
5324 if ((x & 7) == 0)
5326 if (p >= end)
5328 x_destroy_x_image (ximg);
5329 x_clear_image (f, img);
5330 image_error ("Invalid image size in image `%s'",
5331 img->spec, Qnil);
5332 goto error;
5334 c = *p++;
5336 g = c & 0x80;
5337 c <<= 1;
5339 else
5340 g = pbm_scan_number (&p, end);
5342 XPutPixel (ximg, x, y, g ? fg : bg);
5345 else
5347 int expected_size = height * width;
5348 if (max_color_idx > 255)
5349 expected_size *= 2;
5350 if (type == PBM_COLOR)
5351 expected_size *= 3;
5353 if (raw_p && p + expected_size > end)
5355 x_destroy_x_image (ximg);
5356 x_clear_image (f, img);
5357 image_error ("Invalid image size in image `%s'",
5358 img->spec, Qnil);
5359 goto error;
5362 for (y = 0; y < height; ++y)
5363 for (x = 0; x < width; ++x)
5365 int r, g, b;
5367 if (type == PBM_GRAY && raw_p)
5369 r = g = b = *p++;
5370 if (max_color_idx > 255)
5371 r = g = b = r * 256 + *p++;
5373 else if (type == PBM_GRAY)
5374 r = g = b = pbm_scan_number (&p, end);
5375 else if (raw_p)
5377 r = *p++;
5378 if (max_color_idx > 255)
5379 r = r * 256 + *p++;
5380 g = *p++;
5381 if (max_color_idx > 255)
5382 g = g * 256 + *p++;
5383 b = *p++;
5384 if (max_color_idx > 255)
5385 b = b * 256 + *p++;
5387 else
5389 r = pbm_scan_number (&p, end);
5390 g = pbm_scan_number (&p, end);
5391 b = pbm_scan_number (&p, end);
5394 if (r < 0 || g < 0 || b < 0)
5396 x_destroy_x_image (ximg);
5397 image_error ("Invalid pixel value in image `%s'",
5398 img->spec, Qnil);
5399 goto error;
5402 /* RGB values are now in the range 0..max_color_idx.
5403 Scale this to the range 0..0xffff supported by X. */
5404 r = (double) r * 65535 / max_color_idx;
5405 g = (double) g * 65535 / max_color_idx;
5406 b = (double) b * 65535 / max_color_idx;
5407 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5411 #ifdef COLOR_TABLE_SUPPORT
5412 /* Store in IMG->colors the colors allocated for the image, and
5413 free the color table. */
5414 img->colors = colors_in_color_table (&img->ncolors);
5415 free_color_table ();
5416 #endif /* COLOR_TABLE_SUPPORT */
5418 img->width = width;
5419 img->height = height;
5421 /* Maybe fill in the background field while we have ximg handy. */
5423 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5424 /* Casting avoids a GCC warning. */
5425 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5427 /* Put ximg into the image. */
5428 image_put_x_image (f, img, ximg, 0);
5430 /* X and W32 versions did it here, MAC version above. ++kfs
5431 img->width = width;
5432 img->height = height; */
5434 xfree (contents);
5435 return 1;
5439 /***********************************************************************
5441 ***********************************************************************/
5443 #if defined (HAVE_PNG) || defined (HAVE_NS)
5445 /* Function prototypes. */
5447 static bool png_image_p (Lisp_Object object);
5448 static bool png_load (struct frame *f, struct image *img);
5450 /* The symbol `png' identifying images of this type. */
5452 static Lisp_Object Qpng;
5454 /* Indices of image specification fields in png_format, below. */
5456 enum png_keyword_index
5458 PNG_TYPE,
5459 PNG_DATA,
5460 PNG_FILE,
5461 PNG_ASCENT,
5462 PNG_MARGIN,
5463 PNG_RELIEF,
5464 PNG_ALGORITHM,
5465 PNG_HEURISTIC_MASK,
5466 PNG_MASK,
5467 PNG_BACKGROUND,
5468 PNG_LAST
5471 /* Vector of image_keyword structures describing the format
5472 of valid user-defined image specifications. */
5474 static const struct image_keyword png_format[PNG_LAST] =
5476 {":type", IMAGE_SYMBOL_VALUE, 1},
5477 {":data", IMAGE_STRING_VALUE, 0},
5478 {":file", IMAGE_STRING_VALUE, 0},
5479 {":ascent", IMAGE_ASCENT_VALUE, 0},
5480 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5481 {":relief", IMAGE_INTEGER_VALUE, 0},
5482 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5483 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5484 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5485 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5488 #if defined HAVE_NTGUI && defined WINDOWSNT
5489 static bool init_png_functions (void);
5490 #else
5491 #define init_png_functions NULL
5492 #endif
5494 /* Structure describing the image type `png'. */
5496 static struct image_type png_type =
5498 &Qpng,
5499 png_image_p,
5500 png_load,
5501 x_clear_image,
5502 init_png_functions,
5503 NULL
5506 /* Return true if OBJECT is a valid PNG image specification. */
5508 static bool
5509 png_image_p (Lisp_Object object)
5511 struct image_keyword fmt[PNG_LAST];
5512 memcpy (fmt, png_format, sizeof fmt);
5514 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5515 return 0;
5517 /* Must specify either the :data or :file keyword. */
5518 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5521 #endif /* HAVE_PNG || HAVE_NS */
5524 #if defined HAVE_PNG && !defined HAVE_NS
5526 #ifdef WINDOWSNT
5527 /* PNG library details. */
5529 DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5530 DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5531 DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5532 png_error_ptr, png_error_ptr));
5533 DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5534 DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5535 DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5536 DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5537 DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5538 DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
5539 png_uint_32 *, png_uint_32 *,
5540 int *, int *, int *, int *, int *));
5541 DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5542 DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5543 DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5544 DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5545 DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
5546 int, int, double));
5547 DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5548 DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5549 DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5550 DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5551 DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5552 DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5553 DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
5555 #if (PNG_LIBPNG_VER >= 10500)
5556 DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5557 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
5558 #endif /* libpng version >= 1.5 */
5560 static bool
5561 init_png_functions (void)
5563 HMODULE library;
5565 if (!(library = w32_delayed_load (Qpng)))
5566 return 0;
5568 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5569 LOAD_IMGLIB_FN (library, png_sig_cmp);
5570 LOAD_IMGLIB_FN (library, png_create_read_struct);
5571 LOAD_IMGLIB_FN (library, png_create_info_struct);
5572 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5573 LOAD_IMGLIB_FN (library, png_set_read_fn);
5574 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5575 LOAD_IMGLIB_FN (library, png_read_info);
5576 LOAD_IMGLIB_FN (library, png_get_IHDR);
5577 LOAD_IMGLIB_FN (library, png_get_valid);
5578 LOAD_IMGLIB_FN (library, png_set_strip_16);
5579 LOAD_IMGLIB_FN (library, png_set_expand);
5580 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5581 LOAD_IMGLIB_FN (library, png_set_background);
5582 LOAD_IMGLIB_FN (library, png_get_bKGD);
5583 LOAD_IMGLIB_FN (library, png_read_update_info);
5584 LOAD_IMGLIB_FN (library, png_get_channels);
5585 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5586 LOAD_IMGLIB_FN (library, png_read_image);
5587 LOAD_IMGLIB_FN (library, png_read_end);
5588 LOAD_IMGLIB_FN (library, png_error);
5590 #if (PNG_LIBPNG_VER >= 10500)
5591 LOAD_IMGLIB_FN (library, png_longjmp);
5592 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5593 #endif /* libpng version >= 1.5 */
5595 return 1;
5597 #else
5599 #define fn_png_get_io_ptr png_get_io_ptr
5600 #define fn_png_sig_cmp png_sig_cmp
5601 #define fn_png_create_read_struct png_create_read_struct
5602 #define fn_png_create_info_struct png_create_info_struct
5603 #define fn_png_destroy_read_struct png_destroy_read_struct
5604 #define fn_png_set_read_fn png_set_read_fn
5605 #define fn_png_set_sig_bytes png_set_sig_bytes
5606 #define fn_png_read_info png_read_info
5607 #define fn_png_get_IHDR png_get_IHDR
5608 #define fn_png_get_valid png_get_valid
5609 #define fn_png_set_strip_16 png_set_strip_16
5610 #define fn_png_set_expand png_set_expand
5611 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5612 #define fn_png_set_background png_set_background
5613 #define fn_png_get_bKGD png_get_bKGD
5614 #define fn_png_read_update_info png_read_update_info
5615 #define fn_png_get_channels png_get_channels
5616 #define fn_png_get_rowbytes png_get_rowbytes
5617 #define fn_png_read_image png_read_image
5618 #define fn_png_read_end png_read_end
5619 #define fn_png_error png_error
5621 #if (PNG_LIBPNG_VER >= 10500)
5622 #define fn_png_longjmp png_longjmp
5623 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5624 #endif /* libpng version >= 1.5 */
5626 #endif /* WINDOWSNT */
5628 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5629 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5630 Do not use sys_setjmp, as PNG supports only jmp_buf.
5631 It's OK if the longjmp substitute restores the signal mask. */
5632 #ifdef HAVE__SETJMP
5633 # define FAST_SETJMP(j) _setjmp (j)
5634 # define FAST_LONGJMP _longjmp
5635 #else
5636 # define FAST_SETJMP(j) setjmp (j)
5637 # define FAST_LONGJMP longjmp
5638 #endif
5640 #if PNG_LIBPNG_VER < 10500
5641 #define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5642 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5643 #else
5644 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5645 #define PNG_LONGJMP(ptr) fn_png_longjmp (ptr, 1)
5646 #define PNG_JMPBUF(ptr) \
5647 (*fn_png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5648 #endif
5650 /* Error and warning handlers installed when the PNG library
5651 is initialized. */
5653 static _Noreturn void
5654 my_png_error (png_struct *png_ptr, const char *msg)
5656 eassert (png_ptr != NULL);
5657 /* Avoid compiler warning about deprecated direct access to
5658 png_ptr's fields in libpng versions 1.4.x. */
5659 image_error ("PNG error: %s", build_string (msg), Qnil);
5660 PNG_LONGJMP (png_ptr);
5664 static void
5665 my_png_warning (png_struct *png_ptr, const char *msg)
5667 eassert (png_ptr != NULL);
5668 image_error ("PNG warning: %s", build_string (msg), Qnil);
5671 /* Memory source for PNG decoding. */
5673 struct png_memory_storage
5675 unsigned char *bytes; /* The data */
5676 ptrdiff_t len; /* How big is it? */
5677 ptrdiff_t index; /* Where are we? */
5681 /* Function set as reader function when reading PNG image from memory.
5682 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5683 bytes from the input to DATA. */
5685 static void
5686 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5688 struct png_memory_storage *tbr = fn_png_get_io_ptr (png_ptr);
5690 if (length > tbr->len - tbr->index)
5691 fn_png_error (png_ptr, "Read error");
5693 memcpy (data, tbr->bytes + tbr->index, length);
5694 tbr->index = tbr->index + length;
5698 /* Function set as reader function when reading PNG image from a file.
5699 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5700 bytes from the input to DATA. */
5702 static void
5703 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5705 FILE *fp = fn_png_get_io_ptr (png_ptr);
5707 if (fread (data, 1, length, fp) < length)
5708 fn_png_error (png_ptr, "Read error");
5712 /* Load PNG image IMG for use on frame F. Value is true if
5713 successful. */
5715 struct png_load_context
5717 /* These are members so that longjmp doesn't munge local variables. */
5718 png_struct *png_ptr;
5719 png_info *info_ptr;
5720 png_info *end_info;
5721 FILE *fp;
5722 png_byte *pixels;
5723 png_byte **rows;
5726 static bool
5727 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5729 Lisp_Object file, specified_file;
5730 Lisp_Object specified_data;
5731 int x, y;
5732 ptrdiff_t i;
5733 XImagePtr ximg, mask_img = NULL;
5734 png_struct *png_ptr;
5735 png_info *info_ptr = NULL, *end_info = NULL;
5736 FILE *fp = NULL;
5737 png_byte sig[8];
5738 png_byte *pixels = NULL;
5739 png_byte **rows = NULL;
5740 png_uint_32 width, height;
5741 int bit_depth, color_type, interlace_type;
5742 png_byte channels;
5743 png_uint_32 row_bytes;
5744 bool transparent_p;
5745 struct png_memory_storage tbr; /* Data to be read */
5747 /* Find out what file to load. */
5748 specified_file = image_spec_value (img->spec, QCfile, NULL);
5749 specified_data = image_spec_value (img->spec, QCdata, NULL);
5751 if (NILP (specified_data))
5753 file = x_find_image_file (specified_file);
5754 if (!STRINGP (file))
5756 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5757 return 0;
5760 /* Open the image file. */
5761 fp = emacs_fopen (SSDATA (file), "rb");
5762 if (!fp)
5764 image_error ("Cannot open image file `%s'", file, Qnil);
5765 return 0;
5768 /* Check PNG signature. */
5769 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5770 || fn_png_sig_cmp (sig, 0, sizeof sig))
5772 fclose (fp);
5773 image_error ("Not a PNG file: `%s'", file, Qnil);
5774 return 0;
5777 else
5779 if (!STRINGP (specified_data))
5781 image_error ("Invalid image data `%s'", specified_data, Qnil);
5782 return 0;
5785 /* Read from memory. */
5786 tbr.bytes = SDATA (specified_data);
5787 tbr.len = SBYTES (specified_data);
5788 tbr.index = 0;
5790 /* Check PNG signature. */
5791 if (tbr.len < sizeof sig
5792 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5794 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5795 return 0;
5798 /* Need to skip past the signature. */
5799 tbr.bytes += sizeof (sig);
5802 /* Initialize read and info structs for PNG lib. */
5803 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5804 NULL, my_png_error,
5805 my_png_warning);
5806 if (png_ptr)
5808 info_ptr = fn_png_create_info_struct (png_ptr);
5809 end_info = fn_png_create_info_struct (png_ptr);
5812 c->png_ptr = png_ptr;
5813 c->info_ptr = info_ptr;
5814 c->end_info = end_info;
5815 c->fp = fp;
5816 c->pixels = pixels;
5817 c->rows = rows;
5819 if (! (info_ptr && end_info))
5821 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5822 png_ptr = 0;
5824 if (! png_ptr)
5826 if (fp) fclose (fp);
5827 return 0;
5830 /* Set error jump-back. We come back here when the PNG library
5831 detects an error. */
5832 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
5834 error:
5835 if (c->png_ptr)
5836 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5837 xfree (c->pixels);
5838 xfree (c->rows);
5839 if (c->fp)
5840 fclose (c->fp);
5841 return 0;
5844 /* Silence a bogus diagnostic; see GCC bug 54561. */
5845 IF_LINT (fp = c->fp);
5847 /* Read image info. */
5848 if (!NILP (specified_data))
5849 fn_png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
5850 else
5851 fn_png_set_read_fn (png_ptr, fp, png_read_from_file);
5853 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5854 fn_png_read_info (png_ptr, info_ptr);
5855 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5856 &interlace_type, NULL, NULL);
5858 if (! (width <= INT_MAX && height <= INT_MAX
5859 && check_image_size (f, width, height)))
5861 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5862 goto error;
5865 /* Create the X image and pixmap now, so that the work below can be
5866 omitted if the image is too large for X. */
5867 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5868 goto error;
5870 /* If image contains simply transparency data, we prefer to
5871 construct a clipping mask. */
5872 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5873 transparent_p = 1;
5874 else
5875 transparent_p = 0;
5877 /* This function is easier to write if we only have to handle
5878 one data format: RGB or RGBA with 8 bits per channel. Let's
5879 transform other formats into that format. */
5881 /* Strip more than 8 bits per channel. */
5882 if (bit_depth == 16)
5883 fn_png_set_strip_16 (png_ptr);
5885 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5886 if available. */
5887 fn_png_set_expand (png_ptr);
5889 /* Convert grayscale images to RGB. */
5890 if (color_type == PNG_COLOR_TYPE_GRAY
5891 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5892 fn_png_set_gray_to_rgb (png_ptr);
5894 /* Handle alpha channel by combining the image with a background
5895 color. Do this only if a real alpha channel is supplied. For
5896 simple transparency, we prefer a clipping mask. */
5897 if (!transparent_p)
5899 /* png_color_16 *image_bg; */
5900 Lisp_Object specified_bg
5901 = image_spec_value (img->spec, QCbackground, NULL);
5902 XColor color;
5904 /* If the user specified a color, try to use it; if not, use the
5905 current frame background, ignoring any default background
5906 color set by the image. */
5907 if (STRINGP (specified_bg)
5908 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
5909 : (x_query_frame_background_color (f, &color), true))
5910 /* The user specified `:background', use that. */
5912 int shift = bit_depth == 16 ? 0 : 8;
5913 png_color_16 bg = { 0 };
5914 bg.red = color.red >> shift;
5915 bg.green = color.green >> shift;
5916 bg.blue = color.blue >> shift;
5918 fn_png_set_background (png_ptr, &bg,
5919 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5923 /* Update info structure. */
5924 fn_png_read_update_info (png_ptr, info_ptr);
5926 /* Get number of channels. Valid values are 1 for grayscale images
5927 and images with a palette, 2 for grayscale images with transparency
5928 information (alpha channel), 3 for RGB images, and 4 for RGB
5929 images with alpha channel, i.e. RGBA. If conversions above were
5930 sufficient we should only have 3 or 4 channels here. */
5931 channels = fn_png_get_channels (png_ptr, info_ptr);
5932 eassert (channels == 3 || channels == 4);
5934 /* Number of bytes needed for one row of the image. */
5935 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5937 /* Allocate memory for the image. */
5938 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows < height
5939 || min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height < row_bytes)
5940 memory_full (SIZE_MAX);
5941 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
5942 c->rows = rows = xmalloc (height * sizeof *rows);
5943 for (i = 0; i < height; ++i)
5944 rows[i] = pixels + i * row_bytes;
5946 /* Read the entire image. */
5947 fn_png_read_image (png_ptr, rows);
5948 fn_png_read_end (png_ptr, info_ptr);
5949 if (fp)
5951 fclose (fp);
5952 c->fp = NULL;
5955 /* Create an image and pixmap serving as mask if the PNG image
5956 contains an alpha channel. */
5957 if (channels == 4
5958 && !transparent_p
5959 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
5960 &mask_img, 1))
5962 x_destroy_x_image (ximg);
5963 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
5964 goto error;
5967 /* Fill the X image and mask from PNG data. */
5968 init_color_table ();
5970 for (y = 0; y < height; ++y)
5972 png_byte *p = rows[y];
5974 for (x = 0; x < width; ++x)
5976 int r, g, b;
5978 r = *p++ << 8;
5979 g = *p++ << 8;
5980 b = *p++ << 8;
5981 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5982 /* An alpha channel, aka mask channel, associates variable
5983 transparency with an image. Where other image formats
5984 support binary transparency---fully transparent or fully
5985 opaque---PNG allows up to 254 levels of partial transparency.
5986 The PNG library implements partial transparency by combining
5987 the image with a specified background color.
5989 I'm not sure how to handle this here nicely: because the
5990 background on which the image is displayed may change, for
5991 real alpha channel support, it would be necessary to create
5992 a new image for each possible background.
5994 What I'm doing now is that a mask is created if we have
5995 boolean transparency information. Otherwise I'm using
5996 the frame's background color to combine the image with. */
5998 if (channels == 4)
6000 if (mask_img)
6001 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6002 ++p;
6007 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6008 /* Set IMG's background color from the PNG image, unless the user
6009 overrode it. */
6011 png_color_16 *bg;
6012 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6014 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6015 img->background_valid = 1;
6019 #ifdef COLOR_TABLE_SUPPORT
6020 /* Remember colors allocated for this image. */
6021 img->colors = colors_in_color_table (&img->ncolors);
6022 free_color_table ();
6023 #endif /* COLOR_TABLE_SUPPORT */
6025 /* Clean up. */
6026 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6027 xfree (rows);
6028 xfree (pixels);
6030 img->width = width;
6031 img->height = height;
6033 /* Maybe fill in the background field while we have ximg handy.
6034 Casting avoids a GCC warning. */
6035 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6037 /* Put ximg into the image. */
6038 image_put_x_image (f, img, ximg, 0);
6040 /* Same for the mask. */
6041 if (mask_img)
6043 /* Fill in the background_transparent field while we have the
6044 mask handy. Casting avoids a GCC warning. */
6045 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6047 image_put_x_image (f, img, mask_img, 1);
6050 return 1;
6053 static bool
6054 png_load (struct frame *f, struct image *img)
6056 struct png_load_context c;
6057 return png_load_body (f, img, &c);
6060 #elif defined HAVE_NS
6062 static bool
6063 png_load (struct frame *f, struct image *img)
6065 return ns_load_image (f, img,
6066 image_spec_value (img->spec, QCfile, NULL),
6067 image_spec_value (img->spec, QCdata, NULL));
6070 #endif /* HAVE_NS */
6074 /***********************************************************************
6075 JPEG
6076 ***********************************************************************/
6078 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6080 static bool jpeg_image_p (Lisp_Object object);
6081 static bool jpeg_load (struct frame *f, struct image *img);
6083 /* The symbol `jpeg' identifying images of this type. */
6085 static Lisp_Object Qjpeg;
6087 /* Indices of image specification fields in gs_format, below. */
6089 enum jpeg_keyword_index
6091 JPEG_TYPE,
6092 JPEG_DATA,
6093 JPEG_FILE,
6094 JPEG_ASCENT,
6095 JPEG_MARGIN,
6096 JPEG_RELIEF,
6097 JPEG_ALGORITHM,
6098 JPEG_HEURISTIC_MASK,
6099 JPEG_MASK,
6100 JPEG_BACKGROUND,
6101 JPEG_LAST
6104 /* Vector of image_keyword structures describing the format
6105 of valid user-defined image specifications. */
6107 static const struct image_keyword jpeg_format[JPEG_LAST] =
6109 {":type", IMAGE_SYMBOL_VALUE, 1},
6110 {":data", IMAGE_STRING_VALUE, 0},
6111 {":file", IMAGE_STRING_VALUE, 0},
6112 {":ascent", IMAGE_ASCENT_VALUE, 0},
6113 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6114 {":relief", IMAGE_INTEGER_VALUE, 0},
6115 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6116 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6117 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6118 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6121 #if defined HAVE_NTGUI && defined WINDOWSNT
6122 static bool init_jpeg_functions (void);
6123 #else
6124 #define init_jpeg_functions NULL
6125 #endif
6127 /* Structure describing the image type `jpeg'. */
6129 static struct image_type jpeg_type =
6131 &Qjpeg,
6132 jpeg_image_p,
6133 jpeg_load,
6134 x_clear_image,
6135 init_jpeg_functions,
6136 NULL
6139 /* Return true if OBJECT is a valid JPEG image specification. */
6141 static bool
6142 jpeg_image_p (Lisp_Object object)
6144 struct image_keyword fmt[JPEG_LAST];
6146 memcpy (fmt, jpeg_format, sizeof fmt);
6148 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6149 return 0;
6151 /* Must specify either the :data or :file keyword. */
6152 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6155 #endif /* HAVE_JPEG || HAVE_NS */
6157 #ifdef HAVE_JPEG
6159 /* Work around a warning about HAVE_STDLIB_H being redefined in
6160 jconfig.h. */
6161 #ifdef HAVE_STDLIB_H
6162 #undef HAVE_STDLIB_H
6163 #endif /* HAVE_STLIB_H */
6165 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6166 /* In older releases of the jpeg library, jpeglib.h will define boolean
6167 differently depending on __WIN32__, so make sure it is defined. */
6168 #define __WIN32__ 1
6169 #endif
6171 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6172 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6173 using the Windows boolean type instead of the jpeglib boolean type
6174 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6175 headers are included along with windows.h, so under Cygwin, jpeglib
6176 attempts to define a conflicting boolean type. Worse, forcing
6177 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6178 because it created an ABI incompatibility between the
6179 already-compiled jpeg library and the header interface definition.
6181 The best we can do is to define jpeglib's boolean type to a
6182 different name. This name, jpeg_boolean, remains in effect through
6183 the rest of image.c.
6185 #if defined CYGWIN && defined HAVE_NTGUI
6186 #define boolean jpeg_boolean
6187 #endif
6188 #include <jpeglib.h>
6189 #include <jerror.h>
6191 #ifdef WINDOWSNT
6193 /* JPEG library details. */
6194 DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6195 DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6196 DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6197 DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6198 DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6199 DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6200 DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6201 DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6203 static bool
6204 init_jpeg_functions (void)
6206 HMODULE library;
6208 if (!(library = w32_delayed_load (Qjpeg)))
6209 return 0;
6211 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6212 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6213 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6214 LOAD_IMGLIB_FN (library, jpeg_read_header);
6215 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6216 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6217 LOAD_IMGLIB_FN (library, jpeg_std_error);
6218 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6219 return 1;
6222 /* Wrapper since we can't directly assign the function pointer
6223 to another function pointer that was declared more completely easily. */
6224 static boolean
6225 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6227 return fn_jpeg_resync_to_restart (cinfo, desired);
6230 #else
6232 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
6233 #define fn_jpeg_start_decompress jpeg_start_decompress
6234 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6235 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6236 #define fn_jpeg_read_header jpeg_read_header
6237 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6238 #define fn_jpeg_std_error jpeg_std_error
6239 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6241 #endif /* WINDOWSNT */
6243 struct my_jpeg_error_mgr
6245 struct jpeg_error_mgr pub;
6246 sys_jmp_buf setjmp_buffer;
6248 /* The remaining members are so that longjmp doesn't munge local
6249 variables. */
6250 struct jpeg_decompress_struct cinfo;
6251 enum
6253 MY_JPEG_ERROR_EXIT,
6254 MY_JPEG_INVALID_IMAGE_SIZE,
6255 MY_JPEG_CANNOT_CREATE_X
6256 } failure_code;
6260 static _Noreturn void
6261 my_error_exit (j_common_ptr cinfo)
6263 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6264 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6265 sys_longjmp (mgr->setjmp_buffer, 1);
6269 /* Init source method for JPEG data source manager. Called by
6270 jpeg_read_header() before any data is actually read. See
6271 libjpeg.doc from the JPEG lib distribution. */
6273 static void
6274 our_common_init_source (j_decompress_ptr cinfo)
6279 /* Method to terminate data source. Called by
6280 jpeg_finish_decompress() after all data has been processed. */
6282 static void
6283 our_common_term_source (j_decompress_ptr cinfo)
6288 /* Fill input buffer method for JPEG data source manager. Called
6289 whenever more data is needed. We read the whole image in one step,
6290 so this only adds a fake end of input marker at the end. */
6292 static JOCTET our_memory_buffer[2];
6294 static boolean
6295 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6297 /* Insert a fake EOI marker. */
6298 struct jpeg_source_mgr *src = cinfo->src;
6300 our_memory_buffer[0] = (JOCTET) 0xFF;
6301 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6303 src->next_input_byte = our_memory_buffer;
6304 src->bytes_in_buffer = 2;
6305 return 1;
6309 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6310 is the JPEG data source manager. */
6312 static void
6313 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6315 struct jpeg_source_mgr *src = cinfo->src;
6317 if (src)
6319 if (num_bytes > src->bytes_in_buffer)
6320 ERREXIT (cinfo, JERR_INPUT_EOF);
6322 src->bytes_in_buffer -= num_bytes;
6323 src->next_input_byte += num_bytes;
6328 /* Set up the JPEG lib for reading an image from DATA which contains
6329 LEN bytes. CINFO is the decompression info structure created for
6330 reading the image. */
6332 static void
6333 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6335 struct jpeg_source_mgr *src = cinfo->src;
6337 if (! src)
6339 /* First time for this JPEG object? */
6340 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6341 JPOOL_PERMANENT, sizeof *src);
6342 cinfo->src = src;
6343 src->next_input_byte = data;
6346 src->init_source = our_common_init_source;
6347 src->fill_input_buffer = our_memory_fill_input_buffer;
6348 src->skip_input_data = our_memory_skip_input_data;
6349 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6350 src->term_source = our_common_term_source;
6351 src->bytes_in_buffer = len;
6352 src->next_input_byte = data;
6356 struct jpeg_stdio_mgr
6358 struct jpeg_source_mgr mgr;
6359 boolean finished;
6360 FILE *file;
6361 JOCTET *buffer;
6365 /* Size of buffer to read JPEG from file.
6366 Not too big, as we want to use alloc_small. */
6367 #define JPEG_STDIO_BUFFER_SIZE 8192
6370 /* Fill input buffer method for JPEG data source manager. Called
6371 whenever more data is needed. The data is read from a FILE *. */
6373 static boolean
6374 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6376 struct jpeg_stdio_mgr *src;
6378 src = (struct jpeg_stdio_mgr *) cinfo->src;
6379 if (!src->finished)
6381 ptrdiff_t bytes;
6383 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6384 if (bytes > 0)
6385 src->mgr.bytes_in_buffer = bytes;
6386 else
6388 WARNMS (cinfo, JWRN_JPEG_EOF);
6389 src->finished = 1;
6390 src->buffer[0] = (JOCTET) 0xFF;
6391 src->buffer[1] = (JOCTET) JPEG_EOI;
6392 src->mgr.bytes_in_buffer = 2;
6394 src->mgr.next_input_byte = src->buffer;
6397 return 1;
6401 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6402 is the JPEG data source manager. */
6404 static void
6405 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6407 struct jpeg_stdio_mgr *src;
6408 src = (struct jpeg_stdio_mgr *) cinfo->src;
6410 while (num_bytes > 0 && !src->finished)
6412 if (num_bytes <= src->mgr.bytes_in_buffer)
6414 src->mgr.bytes_in_buffer -= num_bytes;
6415 src->mgr.next_input_byte += num_bytes;
6416 break;
6418 else
6420 num_bytes -= src->mgr.bytes_in_buffer;
6421 src->mgr.bytes_in_buffer = 0;
6422 src->mgr.next_input_byte = NULL;
6424 our_stdio_fill_input_buffer (cinfo);
6430 /* Set up the JPEG lib for reading an image from a FILE *.
6431 CINFO is the decompression info structure created for
6432 reading the image. */
6434 static void
6435 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6437 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6439 if (! src)
6441 /* First time for this JPEG object? */
6442 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6443 JPOOL_PERMANENT, sizeof *src);
6444 cinfo->src = (struct jpeg_source_mgr *) src;
6445 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6446 JPOOL_PERMANENT,
6447 JPEG_STDIO_BUFFER_SIZE);
6450 src->file = fp;
6451 src->finished = 0;
6452 src->mgr.init_source = our_common_init_source;
6453 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6454 src->mgr.skip_input_data = our_stdio_skip_input_data;
6455 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6456 src->mgr.term_source = our_common_term_source;
6457 src->mgr.bytes_in_buffer = 0;
6458 src->mgr.next_input_byte = NULL;
6461 /* Load image IMG for use on frame F. Patterned after example.c
6462 from the JPEG lib. */
6464 static bool
6465 jpeg_load_body (struct frame *f, struct image *img,
6466 struct my_jpeg_error_mgr *mgr)
6468 Lisp_Object file, specified_file;
6469 Lisp_Object specified_data;
6470 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6471 FILE * IF_LINT (volatile) fp = NULL;
6472 JSAMPARRAY buffer;
6473 int row_stride, x, y;
6474 XImagePtr ximg = NULL;
6475 unsigned long *colors;
6476 int width, height;
6478 /* Open the JPEG file. */
6479 specified_file = image_spec_value (img->spec, QCfile, NULL);
6480 specified_data = image_spec_value (img->spec, QCdata, NULL);
6482 if (NILP (specified_data))
6484 file = x_find_image_file (specified_file);
6485 if (!STRINGP (file))
6487 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6488 return 0;
6491 fp = emacs_fopen (SSDATA (file), "rb");
6492 if (fp == NULL)
6494 image_error ("Cannot open `%s'", file, Qnil);
6495 return 0;
6498 else if (!STRINGP (specified_data))
6500 image_error ("Invalid image data `%s'", specified_data, Qnil);
6501 return 0;
6504 /* Customize libjpeg's error handling to call my_error_exit when an
6505 error is detected. This function will perform a longjmp. */
6506 mgr->cinfo.err = fn_jpeg_std_error (&mgr->pub);
6507 mgr->pub.error_exit = my_error_exit;
6508 if (sys_setjmp (mgr->setjmp_buffer))
6510 switch (mgr->failure_code)
6512 case MY_JPEG_ERROR_EXIT:
6514 char buf[JMSG_LENGTH_MAX];
6515 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6516 image_error ("Error reading JPEG image `%s': %s", img->spec,
6517 build_string (buf));
6518 break;
6521 case MY_JPEG_INVALID_IMAGE_SIZE:
6522 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6523 break;
6525 case MY_JPEG_CANNOT_CREATE_X:
6526 break;
6529 /* Close the input file and destroy the JPEG object. */
6530 if (fp)
6531 fclose (fp);
6532 fn_jpeg_destroy_decompress (&mgr->cinfo);
6534 /* If we already have an XImage, free that. */
6535 x_destroy_x_image (ximg);
6537 /* Free pixmap and colors. */
6538 x_clear_image (f, img);
6539 return 0;
6542 /* Create the JPEG decompression object. Let it read from fp.
6543 Read the JPEG image header. */
6544 fn_jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6546 if (NILP (specified_data))
6547 jpeg_file_src (&mgr->cinfo, fp);
6548 else
6549 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6550 SBYTES (specified_data));
6552 fn_jpeg_read_header (&mgr->cinfo, 1);
6554 /* Customize decompression so that color quantization will be used.
6555 Start decompression. */
6556 mgr->cinfo.quantize_colors = 1;
6557 fn_jpeg_start_decompress (&mgr->cinfo);
6558 width = img->width = mgr->cinfo.output_width;
6559 height = img->height = mgr->cinfo.output_height;
6561 if (!check_image_size (f, width, height))
6563 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6564 sys_longjmp (mgr->setjmp_buffer, 1);
6567 /* Create X image and pixmap. */
6568 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6570 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6571 sys_longjmp (mgr->setjmp_buffer, 1);
6574 /* Allocate colors. When color quantization is used,
6575 mgr->cinfo.actual_number_of_colors has been set with the number of
6576 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6577 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6578 No more than 255 colors will be generated. */
6580 int i, ir, ig, ib;
6582 if (mgr->cinfo.out_color_components > 2)
6583 ir = 0, ig = 1, ib = 2;
6584 else if (mgr->cinfo.out_color_components > 1)
6585 ir = 0, ig = 1, ib = 0;
6586 else
6587 ir = 0, ig = 0, ib = 0;
6589 /* Use the color table mechanism because it handles colors that
6590 cannot be allocated nicely. Such colors will be replaced with
6591 a default color, and we don't have to care about which colors
6592 can be freed safely, and which can't. */
6593 init_color_table ();
6594 colors = alloca (mgr->cinfo.actual_number_of_colors * sizeof *colors);
6596 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6598 /* Multiply RGB values with 255 because X expects RGB values
6599 in the range 0..0xffff. */
6600 int r = mgr->cinfo.colormap[ir][i] << 8;
6601 int g = mgr->cinfo.colormap[ig][i] << 8;
6602 int b = mgr->cinfo.colormap[ib][i] << 8;
6603 colors[i] = lookup_rgb_color (f, r, g, b);
6606 #ifdef COLOR_TABLE_SUPPORT
6607 /* Remember those colors actually allocated. */
6608 img->colors = colors_in_color_table (&img->ncolors);
6609 free_color_table ();
6610 #endif /* COLOR_TABLE_SUPPORT */
6613 /* Read pixels. */
6614 row_stride = width * mgr->cinfo.output_components;
6615 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6616 JPOOL_IMAGE, row_stride, 1);
6617 for (y = 0; y < height; ++y)
6619 fn_jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6620 for (x = 0; x < mgr->cinfo.output_width; ++x)
6621 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6624 /* Clean up. */
6625 fn_jpeg_finish_decompress (&mgr->cinfo);
6626 fn_jpeg_destroy_decompress (&mgr->cinfo);
6627 if (fp)
6628 fclose (fp);
6630 /* Maybe fill in the background field while we have ximg handy. */
6631 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6632 /* Casting avoids a GCC warning. */
6633 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6635 /* Put ximg into the image. */
6636 image_put_x_image (f, img, ximg, 0);
6637 return 1;
6640 static bool
6641 jpeg_load (struct frame *f, struct image *img)
6643 struct my_jpeg_error_mgr mgr;
6644 return jpeg_load_body (f, img, &mgr);
6647 #else /* HAVE_JPEG */
6649 #ifdef HAVE_NS
6650 static bool
6651 jpeg_load (struct frame *f, struct image *img)
6653 return ns_load_image (f, img,
6654 image_spec_value (img->spec, QCfile, NULL),
6655 image_spec_value (img->spec, QCdata, NULL));
6657 #endif /* HAVE_NS */
6659 #endif /* !HAVE_JPEG */
6663 /***********************************************************************
6664 TIFF
6665 ***********************************************************************/
6667 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6669 static bool tiff_image_p (Lisp_Object object);
6670 static bool tiff_load (struct frame *f, struct image *img);
6672 /* The symbol `tiff' identifying images of this type. */
6674 static Lisp_Object Qtiff;
6676 /* Indices of image specification fields in tiff_format, below. */
6678 enum tiff_keyword_index
6680 TIFF_TYPE,
6681 TIFF_DATA,
6682 TIFF_FILE,
6683 TIFF_ASCENT,
6684 TIFF_MARGIN,
6685 TIFF_RELIEF,
6686 TIFF_ALGORITHM,
6687 TIFF_HEURISTIC_MASK,
6688 TIFF_MASK,
6689 TIFF_BACKGROUND,
6690 TIFF_INDEX,
6691 TIFF_LAST
6694 /* Vector of image_keyword structures describing the format
6695 of valid user-defined image specifications. */
6697 static const struct image_keyword tiff_format[TIFF_LAST] =
6699 {":type", IMAGE_SYMBOL_VALUE, 1},
6700 {":data", IMAGE_STRING_VALUE, 0},
6701 {":file", IMAGE_STRING_VALUE, 0},
6702 {":ascent", IMAGE_ASCENT_VALUE, 0},
6703 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6704 {":relief", IMAGE_INTEGER_VALUE, 0},
6705 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6706 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6707 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6708 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6709 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6712 #if defined HAVE_NTGUI && defined WINDOWSNT
6713 static bool init_tiff_functions (void);
6714 #else
6715 #define init_tiff_functions NULL
6716 #endif
6718 /* Structure describing the image type `tiff'. */
6720 static struct image_type tiff_type =
6722 &Qtiff,
6723 tiff_image_p,
6724 tiff_load,
6725 x_clear_image,
6726 init_tiff_functions,
6727 NULL
6730 /* Return true if OBJECT is a valid TIFF image specification. */
6732 static bool
6733 tiff_image_p (Lisp_Object object)
6735 struct image_keyword fmt[TIFF_LAST];
6736 memcpy (fmt, tiff_format, sizeof fmt);
6738 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6739 return 0;
6741 /* Must specify either the :data or :file keyword. */
6742 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6745 #endif /* HAVE_TIFF || HAVE_NS */
6747 #ifdef HAVE_TIFF
6749 #include <tiffio.h>
6751 #ifdef WINDOWSNT
6753 /* TIFF library details. */
6754 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6755 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6756 DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6757 DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
6758 TIFFReadWriteProc, TIFFReadWriteProc,
6759 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6760 TIFFMapFileProc, TIFFUnmapFileProc));
6761 DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6762 DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6763 DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6764 DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6766 static bool
6767 init_tiff_functions (void)
6769 HMODULE library;
6771 if (!(library = w32_delayed_load (Qtiff)))
6772 return 0;
6774 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6775 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6776 LOAD_IMGLIB_FN (library, TIFFOpen);
6777 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6778 LOAD_IMGLIB_FN (library, TIFFGetField);
6779 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6780 LOAD_IMGLIB_FN (library, TIFFClose);
6781 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6782 return 1;
6785 #else
6787 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6788 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6789 #define fn_TIFFOpen TIFFOpen
6790 #define fn_TIFFClientOpen TIFFClientOpen
6791 #define fn_TIFFGetField TIFFGetField
6792 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6793 #define fn_TIFFClose TIFFClose
6794 #define fn_TIFFSetDirectory TIFFSetDirectory
6795 #endif /* WINDOWSNT */
6798 /* Reading from a memory buffer for TIFF images Based on the PNG
6799 memory source, but we have to provide a lot of extra functions.
6800 Blah.
6802 We really only need to implement read and seek, but I am not
6803 convinced that the TIFF library is smart enough not to destroy
6804 itself if we only hand it the function pointers we need to
6805 override. */
6807 typedef struct
6809 unsigned char *bytes;
6810 ptrdiff_t len;
6811 ptrdiff_t index;
6813 tiff_memory_source;
6815 static tsize_t
6816 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6818 tiff_memory_source *src = (tiff_memory_source *) data;
6820 size = min (size, src->len - src->index);
6821 memcpy (buf, src->bytes + src->index, size);
6822 src->index += size;
6823 return size;
6826 static tsize_t
6827 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6829 return -1;
6832 static toff_t
6833 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6835 tiff_memory_source *src = (tiff_memory_source *) data;
6836 ptrdiff_t idx;
6838 switch (whence)
6840 case SEEK_SET: /* Go from beginning of source. */
6841 idx = off;
6842 break;
6844 case SEEK_END: /* Go from end of source. */
6845 idx = src->len + off;
6846 break;
6848 case SEEK_CUR: /* Go from current position. */
6849 idx = src->index + off;
6850 break;
6852 default: /* Invalid `whence'. */
6853 return -1;
6856 if (idx > src->len || idx < 0)
6857 return -1;
6859 src->index = idx;
6860 return src->index;
6863 static int
6864 tiff_close_memory (thandle_t data)
6866 /* NOOP */
6867 return 0;
6870 static int
6871 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6873 /* It is already _IN_ memory. */
6874 return 0;
6877 static void
6878 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6880 /* We don't need to do this. */
6883 static toff_t
6884 tiff_size_of_memory (thandle_t data)
6886 return ((tiff_memory_source *) data)->len;
6889 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6890 compiler error compiling tiff_handler, see Bugzilla bug #17406
6891 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6892 this function as external works around that problem. */
6893 #if defined (__MINGW32__) && __GNUC__ == 3
6894 # define MINGW_STATIC
6895 #else
6896 # define MINGW_STATIC static
6897 #endif
6899 MINGW_STATIC void
6900 tiff_handler (const char *, const char *, const char *, va_list)
6901 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6902 MINGW_STATIC void
6903 tiff_handler (const char *log_format, const char *title,
6904 const char *format, va_list ap)
6906 /* doprnt is not suitable here, as TIFF handlers are called from
6907 libtiff and are passed arbitrary printf directives. Instead, use
6908 vsnprintf, taking care to be portable to nonstandard environments
6909 where vsnprintf returns -1 on buffer overflow. Since it's just a
6910 log entry, it's OK to truncate it. */
6911 char buf[4000];
6912 int len = vsnprintf (buf, sizeof buf, format, ap);
6913 add_to_log (log_format, build_string (title),
6914 make_string (buf, max (0, min (len, sizeof buf - 1))));
6916 #undef MINGW_STATIC
6918 static void tiff_error_handler (const char *, const char *, va_list)
6919 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6920 static void
6921 tiff_error_handler (const char *title, const char *format, va_list ap)
6923 tiff_handler ("TIFF error: %s %s", title, format, ap);
6927 static void tiff_warning_handler (const char *, const char *, va_list)
6928 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6929 static void
6930 tiff_warning_handler (const char *title, const char *format, va_list ap)
6932 tiff_handler ("TIFF warning: %s %s", title, format, ap);
6936 /* Load TIFF image IMG for use on frame F. Value is true if
6937 successful. */
6939 static bool
6940 tiff_load (struct frame *f, struct image *img)
6942 Lisp_Object file, specified_file;
6943 Lisp_Object specified_data;
6944 TIFF *tiff;
6945 int width, height, x, y, count;
6946 uint32 *buf;
6947 int rc;
6948 XImagePtr ximg;
6949 tiff_memory_source memsrc;
6950 Lisp_Object image;
6952 specified_file = image_spec_value (img->spec, QCfile, NULL);
6953 specified_data = image_spec_value (img->spec, QCdata, NULL);
6955 fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6956 fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
6958 if (NILP (specified_data))
6960 /* Read from a file */
6961 file = x_find_image_file (specified_file);
6962 if (!STRINGP (file))
6964 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6965 return 0;
6967 #ifdef WINDOWSNT
6968 file = ansi_encode_filename (file);
6969 #endif
6971 /* Try to open the image file. */
6972 tiff = fn_TIFFOpen (SSDATA (file), "r");
6973 if (tiff == NULL)
6975 image_error ("Cannot open `%s'", file, Qnil);
6976 return 0;
6979 else
6981 if (!STRINGP (specified_data))
6983 image_error ("Invalid image data `%s'", specified_data, Qnil);
6984 return 0;
6987 /* Memory source! */
6988 memsrc.bytes = SDATA (specified_data);
6989 memsrc.len = SBYTES (specified_data);
6990 memsrc.index = 0;
6992 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
6993 tiff_read_from_memory,
6994 tiff_write_from_memory,
6995 tiff_seek_in_memory,
6996 tiff_close_memory,
6997 tiff_size_of_memory,
6998 tiff_mmap_memory,
6999 tiff_unmap_memory);
7001 if (!tiff)
7003 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7004 return 0;
7008 image = image_spec_value (img->spec, QCindex, NULL);
7009 if (INTEGERP (image))
7011 EMACS_INT ino = XFASTINT (image);
7012 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7013 && fn_TIFFSetDirectory (tiff, ino)))
7015 image_error ("Invalid image number `%s' in image `%s'",
7016 image, img->spec);
7017 fn_TIFFClose (tiff);
7018 return 0;
7022 /* Get width and height of the image, and allocate a raster buffer
7023 of width x height 32-bit values. */
7024 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7025 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7027 if (!check_image_size (f, width, height))
7029 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7030 fn_TIFFClose (tiff);
7031 return 0;
7034 /* Create the X image and pixmap. */
7035 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7036 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7037 &ximg, 0)))
7039 fn_TIFFClose (tiff);
7040 return 0;
7043 buf = xmalloc (sizeof *buf * width * height);
7045 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7047 /* Count the number of images in the file. */
7048 for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
7049 continue;
7051 if (count > 1)
7052 img->lisp_data = Fcons (Qcount,
7053 Fcons (make_number (count),
7054 img->lisp_data));
7056 fn_TIFFClose (tiff);
7057 if (!rc)
7059 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7060 xfree (buf);
7061 return 0;
7064 /* Initialize the color table. */
7065 init_color_table ();
7067 /* Process the pixel raster. Origin is in the lower-left corner. */
7068 for (y = 0; y < height; ++y)
7070 uint32 *row = buf + y * width;
7072 for (x = 0; x < width; ++x)
7074 uint32 abgr = row[x];
7075 int r = TIFFGetR (abgr) << 8;
7076 int g = TIFFGetG (abgr) << 8;
7077 int b = TIFFGetB (abgr) << 8;
7078 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7082 #ifdef COLOR_TABLE_SUPPORT
7083 /* Remember the colors allocated for the image. Free the color table. */
7084 img->colors = colors_in_color_table (&img->ncolors);
7085 free_color_table ();
7086 #endif /* COLOR_TABLE_SUPPORT */
7088 img->width = width;
7089 img->height = height;
7091 /* Maybe fill in the background field while we have ximg handy. */
7092 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7093 /* Casting avoids a GCC warning on W32. */
7094 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7096 /* Put ximg into the image. */
7097 image_put_x_image (f, img, ximg, 0);
7098 xfree (buf);
7100 return 1;
7103 #else /* HAVE_TIFF */
7105 #ifdef HAVE_NS
7106 static bool
7107 tiff_load (struct frame *f, struct image *img)
7109 return ns_load_image (f, img,
7110 image_spec_value (img->spec, QCfile, NULL),
7111 image_spec_value (img->spec, QCdata, NULL));
7113 #endif /* HAVE_NS */
7115 #endif /* !HAVE_TIFF */
7119 /***********************************************************************
7121 ***********************************************************************/
7123 #if defined (HAVE_GIF) || defined (HAVE_NS)
7125 static bool gif_image_p (Lisp_Object object);
7126 static bool gif_load (struct frame *f, struct image *img);
7127 static void gif_clear_image (struct frame *f, struct image *img);
7129 /* The symbol `gif' identifying images of this type. */
7131 static Lisp_Object Qgif;
7133 /* Indices of image specification fields in gif_format, below. */
7135 enum gif_keyword_index
7137 GIF_TYPE,
7138 GIF_DATA,
7139 GIF_FILE,
7140 GIF_ASCENT,
7141 GIF_MARGIN,
7142 GIF_RELIEF,
7143 GIF_ALGORITHM,
7144 GIF_HEURISTIC_MASK,
7145 GIF_MASK,
7146 GIF_IMAGE,
7147 GIF_BACKGROUND,
7148 GIF_LAST
7151 /* Vector of image_keyword structures describing the format
7152 of valid user-defined image specifications. */
7154 static const struct image_keyword gif_format[GIF_LAST] =
7156 {":type", IMAGE_SYMBOL_VALUE, 1},
7157 {":data", IMAGE_STRING_VALUE, 0},
7158 {":file", IMAGE_STRING_VALUE, 0},
7159 {":ascent", IMAGE_ASCENT_VALUE, 0},
7160 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7161 {":relief", IMAGE_INTEGER_VALUE, 0},
7162 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7163 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7164 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7165 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7166 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7169 #if defined HAVE_NTGUI && defined WINDOWSNT
7170 static bool init_gif_functions (void);
7171 #else
7172 #define init_gif_functions NULL
7173 #endif
7175 /* Structure describing the image type `gif'. */
7177 static struct image_type gif_type =
7179 &Qgif,
7180 gif_image_p,
7181 gif_load,
7182 gif_clear_image,
7183 init_gif_functions,
7184 NULL
7187 /* Free X resources of GIF image IMG which is used on frame F. */
7189 static void
7190 gif_clear_image (struct frame *f, struct image *img)
7192 img->lisp_data = Qnil;
7193 x_clear_image (f, img);
7196 /* Return true if OBJECT is a valid GIF image specification. */
7198 static bool
7199 gif_image_p (Lisp_Object object)
7201 struct image_keyword fmt[GIF_LAST];
7202 memcpy (fmt, gif_format, sizeof fmt);
7204 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7205 return 0;
7207 /* Must specify either the :data or :file keyword. */
7208 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7211 #endif /* HAVE_GIF */
7213 #ifdef HAVE_GIF
7215 #if defined (HAVE_NTGUI)
7217 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7218 Undefine before redefining to avoid a preprocessor warning. */
7219 #ifdef DrawText
7220 #undef DrawText
7221 #endif
7222 /* avoid conflict with QuickdrawText.h */
7223 #define DrawText gif_DrawText
7224 #include <gif_lib.h>
7225 #undef DrawText
7227 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7228 #ifndef GIFLIB_MINOR
7229 #define GIFLIB_MINOR 0
7230 #endif
7231 #ifndef GIFLIB_RELEASE
7232 #define GIFLIB_RELEASE 0
7233 #endif
7235 #else /* HAVE_NTGUI */
7237 #include <gif_lib.h>
7239 #endif /* HAVE_NTGUI */
7241 /* Giflib before 5.0 didn't define these macros. */
7242 #ifndef GIFLIB_MAJOR
7243 #define GIFLIB_MAJOR 4
7244 #endif
7246 #ifdef WINDOWSNT
7248 /* GIF library details. */
7249 DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7250 DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7251 #if GIFLIB_MAJOR < 5
7252 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7253 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
7254 #else
7255 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7256 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7257 DEF_IMGLIB_FN (char *, GifErrorString, (int));
7258 #endif
7260 static bool
7261 init_gif_functions (void)
7263 HMODULE library;
7265 if (!(library = w32_delayed_load (Qgif)))
7266 return 0;
7268 LOAD_IMGLIB_FN (library, DGifCloseFile);
7269 LOAD_IMGLIB_FN (library, DGifSlurp);
7270 LOAD_IMGLIB_FN (library, DGifOpen);
7271 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7272 #if GIFLIB_MAJOR >= 5
7273 LOAD_IMGLIB_FN (library, GifErrorString);
7274 #endif
7275 return 1;
7278 #else
7280 #define fn_DGifCloseFile DGifCloseFile
7281 #define fn_DGifSlurp DGifSlurp
7282 #define fn_DGifOpen DGifOpen
7283 #define fn_DGifOpenFileName DGifOpenFileName
7284 #if 5 <= GIFLIB_MAJOR
7285 # define fn_GifErrorString GifErrorString
7286 #endif
7288 #endif /* WINDOWSNT */
7290 /* Reading a GIF image from memory
7291 Based on the PNG memory stuff to a certain extent. */
7293 typedef struct
7295 unsigned char *bytes;
7296 ptrdiff_t len;
7297 ptrdiff_t index;
7299 gif_memory_source;
7301 /* Make the current memory source available to gif_read_from_memory.
7302 It's done this way because not all versions of libungif support
7303 a UserData field in the GifFileType structure. */
7304 static gif_memory_source *current_gif_memory_src;
7306 static int
7307 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7309 gif_memory_source *src = current_gif_memory_src;
7311 if (len > src->len - src->index)
7312 return -1;
7314 memcpy (buf, src->bytes + src->index, len);
7315 src->index += len;
7316 return len;
7320 /* Load GIF image IMG for use on frame F. Value is true if
7321 successful. */
7323 static const int interlace_start[] = {0, 4, 2, 1};
7324 static const int interlace_increment[] = {8, 8, 4, 2};
7326 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7328 static bool
7329 gif_load (struct frame *f, struct image *img)
7331 Lisp_Object file;
7332 int rc, width, height, x, y, i, j;
7333 XImagePtr ximg;
7334 ColorMapObject *gif_color_map;
7335 unsigned long pixel_colors[256];
7336 GifFileType *gif;
7337 gif_memory_source memsrc;
7338 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7339 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7340 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7341 unsigned long bgcolor = 0;
7342 EMACS_INT idx;
7343 #if GIFLIB_MAJOR >= 5
7344 int gif_err;
7345 #endif
7347 if (NILP (specified_data))
7349 file = x_find_image_file (specified_file);
7350 if (!STRINGP (file))
7352 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7353 return 0;
7355 #ifdef WINDOWSNT
7356 file = ansi_encode_filename (file);
7357 #endif
7359 /* Open the GIF file. */
7360 #if GIFLIB_MAJOR < 5
7361 gif = fn_DGifOpenFileName (SSDATA (file));
7362 if (gif == NULL)
7364 image_error ("Cannot open `%s'", file, Qnil);
7365 return 0;
7367 #else
7368 gif = fn_DGifOpenFileName (SSDATA (file), &gif_err);
7369 if (gif == NULL)
7371 image_error ("Cannot open `%s': %s",
7372 file, build_string (fn_GifErrorString (gif_err)));
7373 return 0;
7375 #endif
7377 else
7379 if (!STRINGP (specified_data))
7381 image_error ("Invalid image data `%s'", specified_data, Qnil);
7382 return 0;
7385 /* Read from memory! */
7386 current_gif_memory_src = &memsrc;
7387 memsrc.bytes = SDATA (specified_data);
7388 memsrc.len = SBYTES (specified_data);
7389 memsrc.index = 0;
7391 #if GIFLIB_MAJOR < 5
7392 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
7393 if (!gif)
7395 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7396 return 0;
7398 #else
7399 gif = fn_DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7400 if (!gif)
7402 image_error ("Cannot open memory source `%s': %s",
7403 img->spec, build_string (fn_GifErrorString (gif_err)));
7404 return 0;
7406 #endif
7409 /* Before reading entire contents, check the declared image size. */
7410 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7412 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7413 fn_DGifCloseFile (gif);
7414 return 0;
7417 /* Read entire contents. */
7418 rc = fn_DGifSlurp (gif);
7419 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7421 image_error ("Error reading `%s'", img->spec, Qnil);
7422 fn_DGifCloseFile (gif);
7423 return 0;
7426 /* Which sub-image are we to display? */
7428 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7429 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7430 if (idx < 0 || idx >= gif->ImageCount)
7432 image_error ("Invalid image number `%s' in image `%s'",
7433 image_number, img->spec);
7434 fn_DGifCloseFile (gif);
7435 return 0;
7439 width = img->width = gif->SWidth;
7440 height = img->height = gif->SHeight;
7442 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7443 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7444 img->corners[BOT_CORNER]
7445 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7446 img->corners[RIGHT_CORNER]
7447 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7449 if (!check_image_size (f, width, height))
7451 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7452 fn_DGifCloseFile (gif);
7453 return 0;
7456 /* Check that the selected subimages fit. It's not clear whether
7457 the GIF spec requires this, but Emacs can crash if they don't fit. */
7458 for (j = 0; j <= idx; ++j)
7460 struct SavedImage *subimage = gif->SavedImages + j;
7461 int subimg_width = subimage->ImageDesc.Width;
7462 int subimg_height = subimage->ImageDesc.Height;
7463 int subimg_top = subimage->ImageDesc.Top;
7464 int subimg_left = subimage->ImageDesc.Left;
7465 if (! (0 <= subimg_width && 0 <= subimg_height
7466 && 0 <= subimg_top && subimg_top <= height - subimg_height
7467 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7469 image_error ("Subimage does not fit in image", Qnil, Qnil);
7470 fn_DGifCloseFile (gif);
7471 return 0;
7475 /* Create the X image and pixmap. */
7476 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7478 fn_DGifCloseFile (gif);
7479 return 0;
7482 /* Clear the part of the screen image not covered by the image.
7483 Full animated GIF support requires more here (see the gif89 spec,
7484 disposal methods). Let's simply assume that the part not covered
7485 by a sub-image is in the frame's background color. */
7486 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7487 for (x = 0; x < width; ++x)
7488 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7490 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7491 for (x = 0; x < width; ++x)
7492 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7494 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7496 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7497 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7498 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7499 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7502 /* Read the GIF image into the X image. */
7504 /* FIXME: With the current implementation, loading an animated gif
7505 is quadratic in the number of animation frames, since each frame
7506 is a separate struct image. We must provide a way for a single
7507 gif_load call to construct and save all animation frames. */
7509 init_color_table ();
7510 if (STRINGP (specified_bg))
7511 bgcolor = x_alloc_image_color (f, img, specified_bg,
7512 FRAME_BACKGROUND_PIXEL (f));
7513 for (j = 0; j <= idx; ++j)
7515 /* We use a local variable `raster' here because RasterBits is a
7516 char *, which invites problems with bytes >= 0x80. */
7517 struct SavedImage *subimage = gif->SavedImages + j;
7518 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7519 int transparency_color_index = -1;
7520 int disposal = 0;
7521 int subimg_width = subimage->ImageDesc.Width;
7522 int subimg_height = subimage->ImageDesc.Height;
7523 int subimg_top = subimage->ImageDesc.Top;
7524 int subimg_left = subimage->ImageDesc.Left;
7526 /* Find the Graphic Control Extension block for this sub-image.
7527 Extract the disposal method and transparency color. */
7528 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7530 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7532 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7533 && extblock->ByteCount == 4
7534 && extblock->Bytes[0] & 1)
7536 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7537 to background". Treat any other value like 2. */
7538 disposal = (extblock->Bytes[0] >> 2) & 7;
7539 transparency_color_index = (unsigned char) extblock->Bytes[3];
7540 break;
7544 /* We can't "keep in place" the first subimage. */
7545 if (j == 0)
7546 disposal = 2;
7548 /* For disposal == 0, the spec says "No disposal specified. The
7549 decoder is not required to take any action." In practice, it
7550 seems we need to treat this like "keep in place", see e.g.
7551 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7552 if (disposal == 0)
7553 disposal = 1;
7555 /* Allocate subimage colors. */
7556 memset (pixel_colors, 0, sizeof pixel_colors);
7557 gif_color_map = subimage->ImageDesc.ColorMap;
7558 if (!gif_color_map)
7559 gif_color_map = gif->SColorMap;
7561 if (gif_color_map)
7562 for (i = 0; i < gif_color_map->ColorCount; ++i)
7564 if (transparency_color_index == i)
7565 pixel_colors[i] = STRINGP (specified_bg)
7566 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7567 else
7569 int r = gif_color_map->Colors[i].Red << 8;
7570 int g = gif_color_map->Colors[i].Green << 8;
7571 int b = gif_color_map->Colors[i].Blue << 8;
7572 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7576 /* Apply the pixel values. */
7577 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7579 int row, pass;
7581 for (y = 0, row = interlace_start[0], pass = 0;
7582 y < subimg_height;
7583 y++, row += interlace_increment[pass])
7585 while (subimg_height <= row)
7586 row = interlace_start[++pass];
7588 for (x = 0; x < subimg_width; x++)
7590 int c = raster[y * subimg_width + x];
7591 if (transparency_color_index != c || disposal != 1)
7592 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7593 pixel_colors[c]);
7597 else
7599 for (y = 0; y < subimg_height; ++y)
7600 for (x = 0; x < subimg_width; ++x)
7602 int c = raster[y * subimg_width + x];
7603 if (transparency_color_index != c || disposal != 1)
7604 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7605 pixel_colors[c]);
7610 #ifdef COLOR_TABLE_SUPPORT
7611 img->colors = colors_in_color_table (&img->ncolors);
7612 free_color_table ();
7613 #endif /* COLOR_TABLE_SUPPORT */
7615 /* Save GIF image extension data for `image-metadata'.
7616 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7617 img->lisp_data = Qnil;
7618 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7620 int delay = 0;
7621 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7622 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7623 /* Append (... FUNCTION "BYTES") */
7625 img->lisp_data
7626 = Fcons (make_number (ext->Function),
7627 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7628 img->lisp_data));
7629 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7630 && ext->ByteCount == 4)
7632 delay = ext->Bytes[2] << CHAR_BIT;
7633 delay |= ext->Bytes[1];
7636 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7637 if (delay)
7638 img->lisp_data
7639 = Fcons (Qdelay,
7640 Fcons (make_float (delay / 100.0),
7641 img->lisp_data));
7644 if (gif->ImageCount > 1)
7645 img->lisp_data = Fcons (Qcount,
7646 Fcons (make_number (gif->ImageCount),
7647 img->lisp_data));
7649 fn_DGifCloseFile (gif);
7651 /* Maybe fill in the background field while we have ximg handy. */
7652 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7653 /* Casting avoids a GCC warning. */
7654 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7656 /* Put ximg into the image. */
7657 image_put_x_image (f, img, ximg, 0);
7659 return 1;
7662 #else /* !HAVE_GIF */
7664 #ifdef HAVE_NS
7665 static bool
7666 gif_load (struct frame *f, struct image *img)
7668 return ns_load_image (f, img,
7669 image_spec_value (img->spec, QCfile, NULL),
7670 image_spec_value (img->spec, QCdata, NULL));
7672 #endif /* HAVE_NS */
7674 #endif /* HAVE_GIF */
7677 #ifdef HAVE_IMAGEMAGICK
7679 /***********************************************************************
7680 ImageMagick
7681 ***********************************************************************/
7683 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
7684 safely rounded and clipped to int range. */
7686 static int
7687 scale_image_size (int size, size_t divisor, size_t multiplier)
7689 if (divisor != 0)
7691 double s = size;
7692 double scaled = s * multiplier / divisor + 0.5;
7693 if (scaled < INT_MAX)
7694 return scaled;
7696 return INT_MAX;
7699 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
7700 Use SPEC to deduce the size. Store the desired size into
7701 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
7702 static void
7703 compute_image_size (size_t width, size_t height,
7704 Lisp_Object spec,
7705 int *d_width, int *d_height)
7707 Lisp_Object value;
7708 int desired_width, desired_height;
7710 /* If width and/or height is set in the display spec assume we want
7711 to scale to those values. If either h or w is unspecified, the
7712 unspecified should be calculated from the specified to preserve
7713 aspect ratio. */
7714 value = image_spec_value (spec, QCwidth, NULL);
7715 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7716 value = image_spec_value (spec, QCheight, NULL);
7717 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7719 if (desired_width == -1)
7721 value = image_spec_value (spec, QCmax_width, NULL);
7722 if (NATNUMP (value))
7724 int max_width = min (XFASTINT (value), INT_MAX);
7725 if (max_width < width)
7727 /* The image is wider than :max-width. */
7728 desired_width = max_width;
7729 if (desired_height == -1)
7731 desired_height = scale_image_size (desired_width,
7732 width, height);
7733 value = image_spec_value (spec, QCmax_height, NULL);
7734 if (NATNUMP (value))
7736 int max_height = min (XFASTINT (value), INT_MAX);
7737 if (max_height < desired_height)
7739 desired_height = max_height;
7740 desired_width = scale_image_size (desired_height,
7741 height, width);
7749 if (desired_height == -1)
7751 value = image_spec_value (spec, QCmax_height, NULL);
7752 if (NATNUMP (value))
7754 int max_height = min (XFASTINT (value), INT_MAX);
7755 if (max_height < height)
7756 desired_height = max_height;
7760 if (desired_width != -1 && desired_height == -1)
7761 /* w known, calculate h. */
7762 desired_height = scale_image_size (desired_width, width, height);
7764 if (desired_width == -1 && desired_height != -1)
7765 /* h known, calculate w. */
7766 desired_width = scale_image_size (desired_height, height, width);
7768 *d_width = desired_width;
7769 *d_height = desired_height;
7772 static Lisp_Object Qimagemagick;
7774 static bool imagemagick_image_p (Lisp_Object);
7775 static bool imagemagick_load (struct frame *, struct image *);
7776 static void imagemagick_clear_image (struct frame *, struct image *);
7778 /* Indices of image specification fields in imagemagick_format. */
7780 enum imagemagick_keyword_index
7782 IMAGEMAGICK_TYPE,
7783 IMAGEMAGICK_DATA,
7784 IMAGEMAGICK_FILE,
7785 IMAGEMAGICK_ASCENT,
7786 IMAGEMAGICK_MARGIN,
7787 IMAGEMAGICK_RELIEF,
7788 IMAGEMAGICK_ALGORITHM,
7789 IMAGEMAGICK_HEURISTIC_MASK,
7790 IMAGEMAGICK_MASK,
7791 IMAGEMAGICK_BACKGROUND,
7792 IMAGEMAGICK_HEIGHT,
7793 IMAGEMAGICK_WIDTH,
7794 IMAGEMAGICK_MAX_HEIGHT,
7795 IMAGEMAGICK_MAX_WIDTH,
7796 IMAGEMAGICK_FORMAT,
7797 IMAGEMAGICK_ROTATION,
7798 IMAGEMAGICK_CROP,
7799 IMAGEMAGICK_LAST
7802 /* Vector of image_keyword structures describing the format
7803 of valid user-defined image specifications. */
7805 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7807 {":type", IMAGE_SYMBOL_VALUE, 1},
7808 {":data", IMAGE_STRING_VALUE, 0},
7809 {":file", IMAGE_STRING_VALUE, 0},
7810 {":ascent", IMAGE_ASCENT_VALUE, 0},
7811 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7812 {":relief", IMAGE_INTEGER_VALUE, 0},
7813 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7814 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7815 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7816 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7817 {":height", IMAGE_INTEGER_VALUE, 0},
7818 {":width", IMAGE_INTEGER_VALUE, 0},
7819 {":max-height", IMAGE_INTEGER_VALUE, 0},
7820 {":max-width", IMAGE_INTEGER_VALUE, 0},
7821 {":format", IMAGE_SYMBOL_VALUE, 0},
7822 {":rotation", IMAGE_NUMBER_VALUE, 0},
7823 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7826 #if defined HAVE_NTGUI && defined WINDOWSNT
7827 static bool init_imagemagick_functions (void);
7828 #else
7829 #define init_imagemagick_functions NULL
7830 #endif
7832 /* Structure describing the image type for any image handled via
7833 ImageMagick. */
7835 static struct image_type imagemagick_type =
7837 &Qimagemagick,
7838 imagemagick_image_p,
7839 imagemagick_load,
7840 imagemagick_clear_image,
7841 init_imagemagick_functions,
7842 NULL
7845 /* Free X resources of imagemagick image IMG which is used on frame F. */
7847 static void
7848 imagemagick_clear_image (struct frame *f,
7849 struct image *img)
7851 x_clear_image (f, img);
7854 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7855 this by calling parse_image_spec and supplying the keywords that
7856 identify the IMAGEMAGICK format. */
7858 static bool
7859 imagemagick_image_p (Lisp_Object object)
7861 struct image_keyword fmt[IMAGEMAGICK_LAST];
7862 memcpy (fmt, imagemagick_format, sizeof fmt);
7864 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7865 return 0;
7867 /* Must specify either the :data or :file keyword. */
7868 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7871 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7872 Therefore rename the function so it doesn't collide with ImageMagick. */
7873 #define DrawRectangle DrawRectangleGif
7874 #include <wand/MagickWand.h>
7876 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7877 Emacs seems to work fine with the hidden version, so unhide it. */
7878 #include <magick/version.h>
7879 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7880 extern WandExport void PixelGetMagickColor (const PixelWand *,
7881 MagickPixelPacket *);
7882 #endif
7884 /* Log ImageMagick error message.
7885 Useful when a ImageMagick function returns the status `MagickFalse'. */
7887 static void
7888 imagemagick_error (MagickWand *wand)
7890 char *description;
7891 ExceptionType severity;
7893 description = MagickGetException (wand, &severity);
7894 image_error ("ImageMagick error: %s",
7895 build_string (description),
7896 Qnil);
7897 MagickRelinquishMemory (description);
7900 /* Possibly give ImageMagick some extra help to determine the image
7901 type by supplying a "dummy" filename based on the Content-Type. */
7903 static char *
7904 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
7906 Lisp_Object symbol = intern ("image-format-suffixes");
7907 Lisp_Object val = find_symbol_value (symbol);
7908 Lisp_Object format;
7910 if (! CONSP (val))
7911 return NULL;
7913 format = image_spec_value (spec, intern (":format"), NULL);
7914 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
7915 if (! STRINGP (val))
7916 return NULL;
7918 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
7919 as ImageMagick would ignore the extra bytes anyway. */
7920 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
7921 return hint_buffer;
7924 /* Animated images (e.g., GIF89a) are composed from one "master image"
7925 (which is the first one, and then there's a number of images that
7926 follow. If following images have non-transparent colors, these are
7927 composed "on top" of the master image. So, in general, one has to
7928 compute ann the preceding images to be able to display a particular
7929 sub-image.
7931 Computing all the preceding images is too slow, so we maintain a
7932 cache of previously computed images. We have to maintain a cache
7933 separate from the image cache, because the images may be scaled
7934 before display. */
7936 struct animation_cache
7938 MagickWand *wand;
7939 int index;
7940 struct timespec update_time;
7941 struct animation_cache *next;
7942 char signature[FLEXIBLE_ARRAY_MEMBER];
7945 static struct animation_cache *animation_cache = NULL;
7947 static struct animation_cache *
7948 imagemagick_create_cache (char *signature)
7950 struct animation_cache *cache
7951 = xmalloc (offsetof (struct animation_cache, signature)
7952 + strlen (signature) + 1);
7953 cache->wand = 0;
7954 cache->index = 0;
7955 cache->next = 0;
7956 strcpy (cache->signature, signature);
7957 return cache;
7960 /* Discard cached images that haven't been used for a minute. */
7961 static void
7962 imagemagick_prune_animation_cache (void)
7964 struct animation_cache **pcache = &animation_cache;
7965 struct timespec old = timespec_sub (current_timespec (),
7966 make_timespec (60, 0));
7968 while (*pcache)
7970 struct animation_cache *cache = *pcache;
7971 if (timespec_cmp (old, cache->update_time) <= 0)
7972 pcache = &cache->next;
7973 else
7975 if (cache->wand)
7976 DestroyMagickWand (cache->wand);
7977 *pcache = cache->next;
7978 xfree (cache);
7983 static struct animation_cache *
7984 imagemagick_get_animation_cache (MagickWand *wand)
7986 char *signature = MagickGetImageSignature (wand);
7987 struct animation_cache *cache;
7988 struct animation_cache **pcache = &animation_cache;
7990 imagemagick_prune_animation_cache ();
7992 while (1)
7994 cache = *pcache;
7995 if (! cache)
7997 *pcache = cache = imagemagick_create_cache (signature);
7998 break;
8000 if (strcmp (signature, cache->signature) == 0)
8001 break;
8002 pcache = &cache->next;
8005 DestroyString (signature);
8006 cache->update_time = current_timespec ();
8007 return cache;
8010 static MagickWand *
8011 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8013 int i;
8014 MagickWand *composite_wand;
8015 size_t dest_width, dest_height;
8016 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8018 MagickSetIteratorIndex (super_wand, 0);
8020 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8022 composite_wand = MagickGetImage (super_wand);
8023 if (cache->wand)
8024 DestroyMagickWand (cache->wand);
8026 else
8027 composite_wand = cache->wand;
8029 dest_width = MagickGetImageWidth (composite_wand);
8030 dest_height = MagickGetImageHeight (composite_wand);
8032 for (i = max (1, cache->index + 1); i <= ino; i++)
8034 MagickWand *sub_wand;
8035 PixelIterator *source_iterator, *dest_iterator;
8036 PixelWand **source, **dest;
8037 size_t source_width, source_height;
8038 ssize_t source_left, source_top;
8039 MagickPixelPacket pixel;
8040 DisposeType dispose;
8041 ptrdiff_t lines = 0;
8043 MagickSetIteratorIndex (super_wand, i);
8044 sub_wand = MagickGetImage (super_wand);
8046 MagickGetImagePage (sub_wand, &source_width, &source_height,
8047 &source_left, &source_top);
8049 /* This flag says how to handle transparent pixels. */
8050 dispose = MagickGetImageDispose (sub_wand);
8052 source_iterator = NewPixelIterator (sub_wand);
8053 if (! source_iterator)
8055 DestroyMagickWand (composite_wand);
8056 DestroyMagickWand (sub_wand);
8057 cache->wand = NULL;
8058 image_error ("Imagemagick pixel iterator creation failed",
8059 Qnil, Qnil);
8060 return NULL;
8063 dest_iterator = NewPixelIterator (composite_wand);
8064 if (! dest_iterator)
8066 DestroyMagickWand (composite_wand);
8067 DestroyMagickWand (sub_wand);
8068 DestroyPixelIterator (source_iterator);
8069 cache->wand = NULL;
8070 image_error ("Imagemagick pixel iterator creation failed",
8071 Qnil, Qnil);
8072 return NULL;
8075 /* The sub-image may not start at origin, so move the destination
8076 iterator to where the sub-image should start. */
8077 if (source_top > 0)
8079 PixelSetIteratorRow (dest_iterator, source_top);
8080 lines = source_top;
8083 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8084 != NULL)
8086 ptrdiff_t x;
8088 /* Sanity check. This shouldn't happen, but apparently
8089 does in some pictures. */
8090 if (++lines >= dest_height)
8091 break;
8093 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8094 for (x = 0; x < source_width; x++)
8096 /* Sanity check. This shouldn't happen, but apparently
8097 also does in some pictures. */
8098 if (x + source_left > dest_width - 1)
8099 break;
8100 /* Normally we only copy over non-transparent pixels,
8101 but if the disposal method is "Background", then we
8102 copy over all pixels. */
8103 if (dispose == BackgroundDispose ||
8104 PixelGetAlpha (source[x]))
8106 PixelGetMagickColor (source[x], &pixel);
8107 PixelSetMagickColor (dest[x + source_left], &pixel);
8110 PixelSyncIterator (dest_iterator);
8113 DestroyPixelIterator (source_iterator);
8114 DestroyPixelIterator (dest_iterator);
8115 DestroyMagickWand (sub_wand);
8118 /* Cache a copy for the next iteration. The current wand will be
8119 destroyed by the caller. */
8120 cache->wand = CloneMagickWand (composite_wand);
8121 cache->index = ino;
8123 return composite_wand;
8127 /* Helper function for imagemagick_load, which does the actual loading
8128 given contents and size, apart from frame and image structures,
8129 passed from imagemagick_load. Uses librimagemagick to do most of
8130 the image processing.
8132 F is a pointer to the Emacs frame; IMG to the image structure to
8133 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8134 be parsed; SIZE is the number of bytes of data; and FILENAME is
8135 either the file name or the image data.
8137 Return true if successful. */
8139 static bool
8140 imagemagick_load_image (struct frame *f, struct image *img,
8141 unsigned char *contents, unsigned int size,
8142 char *filename)
8144 size_t width, height;
8145 MagickBooleanType status;
8146 XImagePtr ximg;
8147 int x, y;
8148 MagickWand *image_wand;
8149 PixelIterator *iterator;
8150 PixelWand **pixels, *bg_wand = NULL;
8151 MagickPixelPacket pixel;
8152 Lisp_Object image;
8153 Lisp_Object value;
8154 Lisp_Object crop;
8155 EMACS_INT ino;
8156 int desired_width, desired_height;
8157 double rotation;
8158 int pixelwidth;
8159 char hint_buffer[MaxTextExtent];
8160 char *filename_hint = NULL;
8162 /* Handle image index for image types who can contain more than one image.
8163 Interface :index is same as for GIF. First we "ping" the image to see how
8164 many sub-images it contains. Pinging is faster than loading the image to
8165 find out things about it. */
8167 /* Initialize the imagemagick environment. */
8168 MagickWandGenesis ();
8169 image = image_spec_value (img->spec, QCindex, NULL);
8170 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8171 image_wand = NewMagickWand ();
8173 if (filename)
8174 status = MagickReadImage (image_wand, filename);
8175 else
8177 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8178 MagickSetFilename (image_wand, filename_hint);
8179 status = MagickReadImageBlob (image_wand, contents, size);
8182 if (status == MagickFalse)
8184 imagemagick_error (image_wand);
8185 DestroyMagickWand (image_wand);
8186 return 0;
8189 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8191 image_error ("Invalid image number `%s' in image `%s'",
8192 image, img->spec);
8193 DestroyMagickWand (image_wand);
8194 return 0;
8197 if (MagickGetNumberImages (image_wand) > 1)
8198 img->lisp_data =
8199 Fcons (Qcount,
8200 Fcons (make_number (MagickGetNumberImages (image_wand)),
8201 img->lisp_data));
8203 /* If we have an animated image, get the new wand based on the
8204 "super-wand". */
8205 if (MagickGetNumberImages (image_wand) > 1)
8207 MagickWand *super_wand = image_wand;
8208 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8209 if (! image_wand)
8210 image_wand = super_wand;
8211 else
8212 DestroyMagickWand (super_wand);
8215 /* Retrieve the frame's background color, for use later. */
8217 XColor bgcolor;
8218 Lisp_Object specified_bg;
8220 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8221 if (!STRINGP (specified_bg)
8222 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8223 x_query_frame_background_color (f, &bgcolor);
8225 bg_wand = NewPixelWand ();
8226 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8227 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8228 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8231 compute_image_size (MagickGetImageWidth (image_wand),
8232 MagickGetImageHeight (image_wand),
8233 img->spec, &desired_width, &desired_height);
8235 if (desired_width != -1 && desired_height != -1)
8237 status = MagickScaleImage (image_wand, desired_width, desired_height);
8238 if (status == MagickFalse)
8240 image_error ("Imagemagick scale failed", Qnil, Qnil);
8241 imagemagick_error (image_wand);
8242 goto imagemagick_error;
8246 /* crop behaves similar to image slicing in Emacs but is more memory
8247 efficient. */
8248 crop = image_spec_value (img->spec, QCcrop, NULL);
8250 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8252 /* After some testing, it seems MagickCropImage is the fastest crop
8253 function in ImageMagick. This crop function seems to do less copying
8254 than the alternatives, but it still reads the entire image into memory
8255 before cropping, which is apparently difficult to avoid when using
8256 imagemagick. */
8257 size_t crop_width = XINT (XCAR (crop));
8258 crop = XCDR (crop);
8259 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8261 size_t crop_height = XINT (XCAR (crop));
8262 crop = XCDR (crop);
8263 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8265 ssize_t crop_x = XINT (XCAR (crop));
8266 crop = XCDR (crop);
8267 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8269 ssize_t crop_y = XINT (XCAR (crop));
8270 MagickCropImage (image_wand, crop_width, crop_height,
8271 crop_x, crop_y);
8277 /* Furthermore :rotation. we need background color and angle for
8278 rotation. */
8280 TODO background handling for rotation specified_bg =
8281 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8282 (specified_bg). */
8283 value = image_spec_value (img->spec, QCrotation, NULL);
8284 if (FLOATP (value))
8286 rotation = extract_float (value);
8287 status = MagickRotateImage (image_wand, bg_wand, rotation);
8288 if (status == MagickFalse)
8290 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
8291 imagemagick_error (image_wand);
8292 goto imagemagick_error;
8296 /* Set the canvas background color to the frame or specified
8297 background, and flatten the image. Note: as of ImageMagick
8298 6.6.0, SVG image transparency is not handled properly
8299 (e.g. etc/images/splash.svg shows a white background always). */
8301 MagickWand *new_wand;
8302 MagickSetImageBackgroundColor (image_wand, bg_wand);
8303 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8304 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8305 #else
8306 new_wand = MagickFlattenImages (image_wand);
8307 #endif
8308 DestroyMagickWand (image_wand);
8309 image_wand = new_wand;
8312 /* Finally we are done manipulating the image. Figure out the
8313 resulting width/height and transfer ownership to Emacs. */
8314 height = MagickGetImageHeight (image_wand);
8315 width = MagickGetImageWidth (image_wand);
8317 if (! (width <= INT_MAX && height <= INT_MAX
8318 && check_image_size (f, width, height)))
8320 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8321 goto imagemagick_error;
8324 /* We can now get a valid pixel buffer from the imagemagick file, if all
8325 went ok. */
8327 init_color_table ();
8329 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8330 if (imagemagick_render_type != 0)
8332 /* Magicexportimage is normally faster than pixelpushing. This
8333 method is also well tested. Some aspects of this method are
8334 ad-hoc and needs to be more researched. */
8335 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8336 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8337 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8338 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8339 &ximg, 0))
8341 #ifdef COLOR_TABLE_SUPPORT
8342 free_color_table ();
8343 #endif
8344 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8345 goto imagemagick_error;
8348 /* Oddly, the below code doesn't seem to work:*/
8349 /* switch(ximg->bitmap_unit){ */
8350 /* case 8: */
8351 /* pixelwidth=CharPixel; */
8352 /* break; */
8353 /* case 16: */
8354 /* pixelwidth=ShortPixel; */
8355 /* break; */
8356 /* case 32: */
8357 /* pixelwidth=LongPixel; */
8358 /* break; */
8359 /* } */
8361 Here im just guessing the format of the bitmap.
8362 happens to work fine for:
8363 - bw djvu images
8364 on rgb display.
8365 seems about 3 times as fast as pixel pushing(not carefully measured)
8367 pixelwidth = CharPixel; /*??? TODO figure out*/
8368 MagickExportImagePixels (image_wand, 0, 0, width, height,
8369 exportdepth, pixelwidth, ximg->data);
8371 else
8372 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8374 size_t image_height;
8375 MagickRealType color_scale = 65535.0 / QuantumRange;
8377 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8378 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8379 &ximg, 0))
8381 #ifdef COLOR_TABLE_SUPPORT
8382 free_color_table ();
8383 #endif
8384 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8385 goto imagemagick_error;
8388 /* Copy imagemagick image to x with primitive yet robust pixel
8389 pusher loop. This has been tested a lot with many different
8390 images. */
8392 /* Copy pixels from the imagemagick image structure to the x image map. */
8393 iterator = NewPixelIterator (image_wand);
8394 if (! iterator)
8396 #ifdef COLOR_TABLE_SUPPORT
8397 free_color_table ();
8398 #endif
8399 x_destroy_x_image (ximg);
8400 image_error ("Imagemagick pixel iterator creation failed",
8401 Qnil, Qnil);
8402 goto imagemagick_error;
8405 image_height = MagickGetImageHeight (image_wand);
8406 for (y = 0; y < image_height; y++)
8408 pixels = PixelGetNextIteratorRow (iterator, &width);
8409 if (! pixels)
8410 break;
8411 for (x = 0; x < (long) width; x++)
8413 PixelGetMagickColor (pixels[x], &pixel);
8414 XPutPixel (ximg, x, y,
8415 lookup_rgb_color (f,
8416 color_scale * pixel.red,
8417 color_scale * pixel.green,
8418 color_scale * pixel.blue));
8421 DestroyPixelIterator (iterator);
8424 #ifdef COLOR_TABLE_SUPPORT
8425 /* Remember colors allocated for this image. */
8426 img->colors = colors_in_color_table (&img->ncolors);
8427 free_color_table ();
8428 #endif /* COLOR_TABLE_SUPPORT */
8430 img->width = width;
8431 img->height = height;
8433 /* Put ximg into the image. */
8434 image_put_x_image (f, img, ximg, 0);
8436 /* Final cleanup. image_wand should be the only resource left. */
8437 DestroyMagickWand (image_wand);
8438 if (bg_wand) DestroyPixelWand (bg_wand);
8440 /* `MagickWandTerminus' terminates the imagemagick environment. */
8441 MagickWandTerminus ();
8443 return 1;
8445 imagemagick_error:
8446 DestroyMagickWand (image_wand);
8447 if (bg_wand) DestroyPixelWand (bg_wand);
8449 MagickWandTerminus ();
8450 /* TODO more cleanup. */
8451 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
8452 return 0;
8456 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8457 successful. this function will go into the imagemagick_type structure, and
8458 the prototype thus needs to be compatible with that structure. */
8460 static bool
8461 imagemagick_load (struct frame *f, struct image *img)
8463 bool success_p = 0;
8464 Lisp_Object file_name;
8466 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8467 file_name = image_spec_value (img->spec, QCfile, NULL);
8468 if (STRINGP (file_name))
8470 Lisp_Object file;
8472 file = x_find_image_file (file_name);
8473 if (!STRINGP (file))
8475 image_error ("Cannot find image file `%s'", file_name, Qnil);
8476 return 0;
8478 #ifdef WINDOWSNT
8479 file = ansi_encode_filename (file);
8480 #endif
8481 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8483 /* Else its not a file, its a lisp object. Load the image from a
8484 lisp object rather than a file. */
8485 else
8487 Lisp_Object data;
8489 data = image_spec_value (img->spec, QCdata, NULL);
8490 if (!STRINGP (data))
8492 image_error ("Invalid image data `%s'", data, Qnil);
8493 return 0;
8495 success_p = imagemagick_load_image (f, img, SDATA (data),
8496 SBYTES (data), NULL);
8499 return success_p;
8502 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8503 doc: /* Return a list of image types supported by ImageMagick.
8504 Each entry in this list is a symbol named after an ImageMagick format
8505 tag. See the ImageMagick manual for a list of ImageMagick formats and
8506 their descriptions (http://www.imagemagick.org/script/formats.php).
8507 You can also try the shell command: `identify -list format'.
8509 Note that ImageMagick recognizes many file-types that Emacs does not
8510 recognize as images, such as C. See `imagemagick-types-enable'
8511 and `imagemagick-types-inhibit'. */)
8512 (void)
8514 Lisp_Object typelist = Qnil;
8515 size_t numf = 0;
8516 ExceptionInfo ex;
8517 char **imtypes;
8518 size_t i;
8519 Lisp_Object Qimagemagicktype;
8521 GetExceptionInfo(&ex);
8522 imtypes = GetMagickList ("*", &numf, &ex);
8523 DestroyExceptionInfo(&ex);
8525 for (i = 0; i < numf; i++)
8527 Qimagemagicktype = intern (imtypes[i]);
8528 typelist = Fcons (Qimagemagicktype, typelist);
8529 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8532 MagickRelinquishMemory (imtypes);
8533 return Fnreverse (typelist);
8536 #endif /* defined (HAVE_IMAGEMAGICK) */
8540 /***********************************************************************
8542 ***********************************************************************/
8544 #if defined (HAVE_RSVG)
8546 /* Function prototypes. */
8548 static bool svg_image_p (Lisp_Object object);
8549 static bool svg_load (struct frame *f, struct image *img);
8551 static bool svg_load_image (struct frame *, struct image *,
8552 unsigned char *, ptrdiff_t);
8554 /* The symbol `svg' identifying images of this type. */
8556 static Lisp_Object Qsvg;
8558 /* Indices of image specification fields in svg_format, below. */
8560 enum svg_keyword_index
8562 SVG_TYPE,
8563 SVG_DATA,
8564 SVG_FILE,
8565 SVG_ASCENT,
8566 SVG_MARGIN,
8567 SVG_RELIEF,
8568 SVG_ALGORITHM,
8569 SVG_HEURISTIC_MASK,
8570 SVG_MASK,
8571 SVG_BACKGROUND,
8572 SVG_LAST
8575 /* Vector of image_keyword structures describing the format
8576 of valid user-defined image specifications. */
8578 static const struct image_keyword svg_format[SVG_LAST] =
8580 {":type", IMAGE_SYMBOL_VALUE, 1},
8581 {":data", IMAGE_STRING_VALUE, 0},
8582 {":file", IMAGE_STRING_VALUE, 0},
8583 {":ascent", IMAGE_ASCENT_VALUE, 0},
8584 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8585 {":relief", IMAGE_INTEGER_VALUE, 0},
8586 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8587 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8588 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8589 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8592 #if defined HAVE_NTGUI && defined WINDOWSNT
8593 static bool init_svg_functions (void);
8594 #else
8595 #define init_svg_functions NULL
8596 #endif
8598 /* Structure describing the image type `svg'. Its the same type of
8599 structure defined for all image formats, handled by emacs image
8600 functions. See struct image_type in dispextern.h. */
8602 static struct image_type svg_type =
8604 &Qsvg,
8605 svg_image_p,
8606 svg_load,
8607 x_clear_image,
8608 init_svg_functions,
8609 NULL
8613 /* Return true if OBJECT is a valid SVG image specification. Do
8614 this by calling parse_image_spec and supplying the keywords that
8615 identify the SVG format. */
8617 static bool
8618 svg_image_p (Lisp_Object object)
8620 struct image_keyword fmt[SVG_LAST];
8621 memcpy (fmt, svg_format, sizeof fmt);
8623 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8624 return 0;
8626 /* Must specify either the :data or :file keyword. */
8627 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8630 #include <librsvg/rsvg.h>
8632 #ifdef WINDOWSNT
8634 /* SVG library functions. */
8635 DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new, (void));
8636 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions, (RsvgHandle *, RsvgDimensionData *));
8637 DEF_IMGLIB_FN (gboolean, rsvg_handle_write, (RsvgHandle *, const guchar *, gsize, GError **));
8638 DEF_IMGLIB_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8639 DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8641 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8642 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8643 DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8644 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8645 DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8646 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8647 DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8648 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8650 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8651 DEF_IMGLIB_FN (void, g_type_init, (void));
8652 #endif
8653 DEF_IMGLIB_FN (void, g_object_unref, (gpointer));
8654 DEF_IMGLIB_FN (void, g_error_free, (GError *));
8656 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8658 static bool
8659 init_svg_functions (void)
8661 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
8663 if (!(glib = w32_delayed_load (Qglib))
8664 || !(gobject = w32_delayed_load (Qgobject))
8665 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
8666 || !(library = w32_delayed_load (Qsvg)))
8668 if (gdklib) FreeLibrary (gdklib);
8669 if (gobject) FreeLibrary (gobject);
8670 if (glib) FreeLibrary (glib);
8671 return 0;
8674 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8675 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8676 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8677 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8678 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8680 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8681 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8682 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8683 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8684 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8685 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8686 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8687 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8689 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8690 LOAD_IMGLIB_FN (gobject, g_type_init);
8691 #endif
8692 LOAD_IMGLIB_FN (gobject, g_object_unref);
8693 LOAD_IMGLIB_FN (glib, g_error_free);
8695 return 1;
8698 #else
8699 /* The following aliases for library functions allow dynamic loading
8700 to be used on some platforms. */
8701 #define fn_rsvg_handle_new rsvg_handle_new
8702 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8703 #define fn_rsvg_handle_write rsvg_handle_write
8704 #define fn_rsvg_handle_close rsvg_handle_close
8705 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8707 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8708 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8709 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8710 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8711 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8712 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8713 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8714 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8716 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8717 #define fn_g_type_init g_type_init
8718 #endif
8719 #define fn_g_object_unref g_object_unref
8720 #define fn_g_error_free g_error_free
8721 #endif /* !WINDOWSNT */
8723 /* Load SVG image IMG for use on frame F. Value is true if
8724 successful. */
8726 static bool
8727 svg_load (struct frame *f, struct image *img)
8729 bool success_p = 0;
8730 Lisp_Object file_name;
8732 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8733 file_name = image_spec_value (img->spec, QCfile, NULL);
8734 if (STRINGP (file_name))
8736 Lisp_Object file;
8737 unsigned char *contents;
8738 ptrdiff_t size;
8740 file = x_find_image_file (file_name);
8741 if (!STRINGP (file))
8743 image_error ("Cannot find image file `%s'", file_name, Qnil);
8744 return 0;
8747 /* Read the entire file into memory. */
8748 contents = slurp_file (SSDATA (file), &size);
8749 if (contents == NULL)
8751 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8752 return 0;
8754 /* If the file was slurped into memory properly, parse it. */
8755 success_p = svg_load_image (f, img, contents, size);
8756 xfree (contents);
8758 /* Else its not a file, its a lisp object. Load the image from a
8759 lisp object rather than a file. */
8760 else
8762 Lisp_Object data;
8764 data = image_spec_value (img->spec, QCdata, NULL);
8765 if (!STRINGP (data))
8767 image_error ("Invalid image data `%s'", data, Qnil);
8768 return 0;
8770 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8773 return success_p;
8776 /* svg_load_image is a helper function for svg_load, which does the
8777 actual loading given contents and size, apart from frame and image
8778 structures, passed from svg_load.
8780 Uses librsvg to do most of the image processing.
8782 Returns true when successful. */
8783 static bool
8784 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8785 struct image *img, /* Pointer to emacs image structure. */
8786 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8787 ptrdiff_t size) /* Size of data in bytes. */
8789 RsvgHandle *rsvg_handle;
8790 RsvgDimensionData dimension_data;
8791 GError *err = NULL;
8792 GdkPixbuf *pixbuf;
8793 int width;
8794 int height;
8795 const guint8 *pixels;
8796 int rowstride;
8797 XImagePtr ximg;
8798 Lisp_Object specified_bg;
8799 XColor background;
8800 int x;
8801 int y;
8803 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8804 /* g_type_init is a glib function that must be called prior to
8805 using gnome type library functions (obsolete since 2.36.0). */
8806 fn_g_type_init ();
8807 #endif
8809 /* Make a handle to a new rsvg object. */
8810 rsvg_handle = fn_rsvg_handle_new ();
8812 /* Parse the contents argument and fill in the rsvg_handle. */
8813 fn_rsvg_handle_write (rsvg_handle, contents, size, &err);
8814 if (err) goto rsvg_error;
8816 /* The parsing is complete, rsvg_handle is ready to used, close it
8817 for further writes. */
8818 fn_rsvg_handle_close (rsvg_handle, &err);
8819 if (err) goto rsvg_error;
8821 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8822 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8824 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8825 goto rsvg_error;
8828 /* We can now get a valid pixel buffer from the svg file, if all
8829 went ok. */
8830 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8831 if (!pixbuf) goto rsvg_error;
8832 fn_g_object_unref (rsvg_handle);
8834 /* Extract some meta data from the svg handle. */
8835 width = fn_gdk_pixbuf_get_width (pixbuf);
8836 height = fn_gdk_pixbuf_get_height (pixbuf);
8837 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8838 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8840 /* Validate the svg meta data. */
8841 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8842 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8843 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8844 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8846 /* Try to create a x pixmap to hold the svg pixmap. */
8847 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
8849 fn_g_object_unref (pixbuf);
8850 return 0;
8853 init_color_table ();
8855 /* Handle alpha channel by combining the image with a background
8856 color. */
8857 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8858 if (!STRINGP (specified_bg)
8859 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
8860 x_query_frame_background_color (f, &background);
8862 /* SVG pixmaps specify transparency in the last byte, so right
8863 shift 8 bits to get rid of it, since emacs doesn't support
8864 transparency. */
8865 background.red >>= 8;
8866 background.green >>= 8;
8867 background.blue >>= 8;
8869 /* This loop handles opacity values, since Emacs assumes
8870 non-transparent images. Each pixel must be "flattened" by
8871 calculating the resulting color, given the transparency of the
8872 pixel, and the image background color. */
8873 for (y = 0; y < height; ++y)
8875 for (x = 0; x < width; ++x)
8877 int red;
8878 int green;
8879 int blue;
8880 int opacity;
8882 red = *pixels++;
8883 green = *pixels++;
8884 blue = *pixels++;
8885 opacity = *pixels++;
8887 red = ((red * opacity)
8888 + (background.red * ((1 << 8) - opacity)));
8889 green = ((green * opacity)
8890 + (background.green * ((1 << 8) - opacity)));
8891 blue = ((blue * opacity)
8892 + (background.blue * ((1 << 8) - opacity)));
8894 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8897 pixels += rowstride - 4 * width;
8900 #ifdef COLOR_TABLE_SUPPORT
8901 /* Remember colors allocated for this image. */
8902 img->colors = colors_in_color_table (&img->ncolors);
8903 free_color_table ();
8904 #endif /* COLOR_TABLE_SUPPORT */
8906 fn_g_object_unref (pixbuf);
8908 img->width = width;
8909 img->height = height;
8911 /* Maybe fill in the background field while we have ximg handy.
8912 Casting avoids a GCC warning. */
8913 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8915 /* Put ximg into the image. */
8916 image_put_x_image (f, img, ximg, 0);
8918 return 1;
8920 rsvg_error:
8921 fn_g_object_unref (rsvg_handle);
8922 /* FIXME: Use error->message so the user knows what is the actual
8923 problem with the image. */
8924 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8925 fn_g_error_free (err);
8926 return 0;
8929 #endif /* defined (HAVE_RSVG) */
8934 /***********************************************************************
8935 Ghostscript
8936 ***********************************************************************/
8938 #ifdef HAVE_X_WINDOWS
8939 #define HAVE_GHOSTSCRIPT 1
8940 #endif /* HAVE_X_WINDOWS */
8942 #ifdef HAVE_GHOSTSCRIPT
8944 static bool gs_image_p (Lisp_Object object);
8945 static bool gs_load (struct frame *f, struct image *img);
8946 static void gs_clear_image (struct frame *f, struct image *img);
8948 /* Keyword symbols. */
8950 static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8952 /* Indices of image specification fields in gs_format, below. */
8954 enum gs_keyword_index
8956 GS_TYPE,
8957 GS_PT_WIDTH,
8958 GS_PT_HEIGHT,
8959 GS_FILE,
8960 GS_LOADER,
8961 GS_BOUNDING_BOX,
8962 GS_ASCENT,
8963 GS_MARGIN,
8964 GS_RELIEF,
8965 GS_ALGORITHM,
8966 GS_HEURISTIC_MASK,
8967 GS_MASK,
8968 GS_BACKGROUND,
8969 GS_LAST
8972 /* Vector of image_keyword structures describing the format
8973 of valid user-defined image specifications. */
8975 static const struct image_keyword gs_format[GS_LAST] =
8977 {":type", IMAGE_SYMBOL_VALUE, 1},
8978 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8979 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8980 {":file", IMAGE_STRING_VALUE, 1},
8981 {":loader", IMAGE_FUNCTION_VALUE, 0},
8982 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8983 {":ascent", IMAGE_ASCENT_VALUE, 0},
8984 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8985 {":relief", IMAGE_INTEGER_VALUE, 0},
8986 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8987 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8988 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8989 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8992 /* Structure describing the image type `ghostscript'. */
8994 static struct image_type gs_type =
8996 &Qpostscript,
8997 gs_image_p,
8998 gs_load,
8999 gs_clear_image,
9000 NULL,
9001 NULL
9005 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9007 static void
9008 gs_clear_image (struct frame *f, struct image *img)
9010 x_clear_image (f, img);
9014 /* Return true if OBJECT is a valid Ghostscript image
9015 specification. */
9017 static bool
9018 gs_image_p (Lisp_Object object)
9020 struct image_keyword fmt[GS_LAST];
9021 Lisp_Object tem;
9022 int i;
9024 memcpy (fmt, gs_format, sizeof fmt);
9026 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9027 return 0;
9029 /* Bounding box must be a list or vector containing 4 integers. */
9030 tem = fmt[GS_BOUNDING_BOX].value;
9031 if (CONSP (tem))
9033 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9034 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9035 return 0;
9036 if (!NILP (tem))
9037 return 0;
9039 else if (VECTORP (tem))
9041 if (ASIZE (tem) != 4)
9042 return 0;
9043 for (i = 0; i < 4; ++i)
9044 if (!INTEGERP (AREF (tem, i)))
9045 return 0;
9047 else
9048 return 0;
9050 return 1;
9054 /* Load Ghostscript image IMG for use on frame F. Value is true
9055 if successful. */
9057 static bool
9058 gs_load (struct frame *f, struct image *img)
9060 uprintmax_t printnum1, printnum2;
9061 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9062 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9063 Lisp_Object frame;
9064 double in_width, in_height;
9065 Lisp_Object pixel_colors = Qnil;
9067 /* Compute pixel size of pixmap needed from the given size in the
9068 image specification. Sizes in the specification are in pt. 1 pt
9069 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9070 info. */
9071 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9072 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9073 in_width *= FRAME_RES_X (f);
9074 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9075 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9076 in_height *= FRAME_RES_Y (f);
9078 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9079 && check_image_size (f, in_width, in_height)))
9081 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
9082 return 0;
9084 img->width = in_width;
9085 img->height = in_height;
9087 /* Create the pixmap. */
9088 eassert (img->pixmap == NO_PIXMAP);
9090 if (x_check_image_size (0, img->width, img->height))
9092 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9093 block_input ();
9094 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9095 img->width, img->height,
9096 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9097 unblock_input ();
9100 if (!img->pixmap)
9102 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
9103 return 0;
9106 /* Call the loader to fill the pixmap. It returns a process object
9107 if successful. We do not record_unwind_protect here because
9108 other places in redisplay like calling window scroll functions
9109 don't either. Let the Lisp loader use `unwind-protect' instead. */
9110 printnum1 = FRAME_X_WINDOW (f);
9111 printnum2 = img->pixmap;
9112 window_and_pixmap_id
9113 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9115 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9116 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9117 pixel_colors
9118 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9120 XSETFRAME (frame, f);
9121 loader = image_spec_value (img->spec, QCloader, NULL);
9122 if (NILP (loader))
9123 loader = intern ("gs-load-image");
9125 img->lisp_data = call6 (loader, frame, img->spec,
9126 make_number (img->width),
9127 make_number (img->height),
9128 window_and_pixmap_id,
9129 pixel_colors);
9130 return PROCESSP (img->lisp_data);
9134 /* Kill the Ghostscript process that was started to fill PIXMAP on
9135 frame F. Called from XTread_socket when receiving an event
9136 telling Emacs that Ghostscript has finished drawing. */
9138 void
9139 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9141 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9142 int class;
9143 ptrdiff_t i;
9144 struct image *img;
9146 /* Find the image containing PIXMAP. */
9147 for (i = 0; i < c->used; ++i)
9148 if (c->images[i]->pixmap == pixmap)
9149 break;
9151 /* Should someone in between have cleared the image cache, for
9152 instance, give up. */
9153 if (i == c->used)
9154 return;
9156 /* Kill the GS process. We should have found PIXMAP in the image
9157 cache and its image should contain a process object. */
9158 img = c->images[i];
9159 eassert (PROCESSP (img->lisp_data));
9160 Fkill_process (img->lisp_data, Qnil);
9161 img->lisp_data = Qnil;
9163 #if defined (HAVE_X_WINDOWS)
9165 /* On displays with a mutable colormap, figure out the colors
9166 allocated for the image by looking at the pixels of an XImage for
9167 img->pixmap. */
9168 class = FRAME_X_VISUAL (f)->class;
9169 if (class != StaticColor && class != StaticGray && class != TrueColor)
9171 XImagePtr ximg;
9173 block_input ();
9175 /* Try to get an XImage for img->pixmep. */
9176 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9177 0, 0, img->width, img->height, ~0, ZPixmap);
9178 if (ximg)
9180 int x, y;
9182 /* Initialize the color table. */
9183 init_color_table ();
9185 /* For each pixel of the image, look its color up in the
9186 color table. After having done so, the color table will
9187 contain an entry for each color used by the image. */
9188 for (y = 0; y < img->height; ++y)
9189 for (x = 0; x < img->width; ++x)
9191 unsigned long pixel = XGetPixel (ximg, x, y);
9192 lookup_pixel_color (f, pixel);
9195 /* Record colors in the image. Free color table and XImage. */
9196 #ifdef COLOR_TABLE_SUPPORT
9197 img->colors = colors_in_color_table (&img->ncolors);
9198 free_color_table ();
9199 #endif
9200 XDestroyImage (ximg);
9202 #if 0 /* This doesn't seem to be the case. If we free the colors
9203 here, we get a BadAccess later in x_clear_image when
9204 freeing the colors. */
9205 /* We have allocated colors once, but Ghostscript has also
9206 allocated colors on behalf of us. So, to get the
9207 reference counts right, free them once. */
9208 if (img->ncolors)
9209 x_free_colors (f, img->colors, img->ncolors);
9210 #endif
9212 else
9213 image_error ("Cannot get X image of `%s'; colors will not be freed",
9214 img->spec, Qnil);
9216 unblock_input ();
9218 #endif /* HAVE_X_WINDOWS */
9220 /* Now that we have the pixmap, compute mask and transform the
9221 image if requested. */
9222 block_input ();
9223 postprocess_image (f, img);
9224 unblock_input ();
9227 #endif /* HAVE_GHOSTSCRIPT */
9230 /***********************************************************************
9231 Tests
9232 ***********************************************************************/
9234 #ifdef GLYPH_DEBUG
9236 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9237 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9238 (Lisp_Object spec)
9240 return valid_image_p (spec) ? Qt : Qnil;
9244 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
9245 (Lisp_Object spec)
9247 ptrdiff_t id = -1;
9249 if (valid_image_p (spec))
9250 id = lookup_image (SELECTED_FRAME (), spec);
9252 debug_print (spec);
9253 return make_number (id);
9256 #endif /* GLYPH_DEBUG */
9259 /***********************************************************************
9260 Initialization
9261 ***********************************************************************/
9263 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9264 doc: /* Initialize image library implementing image type TYPE.
9265 Return non-nil if TYPE is a supported image type.
9267 If image libraries are loaded dynamically (currently only the case on
9268 MS-Windows), load the library for TYPE if it is not yet loaded, using
9269 the library file(s) specified by `dynamic-library-alist'. */)
9270 (Lisp_Object type)
9272 return lookup_image_type (type) ? Qt : Qnil;
9275 /* Look up image type TYPE, and return a pointer to its image_type
9276 structure. Return 0 if TYPE is not a known image type. */
9278 static struct image_type *
9279 lookup_image_type (Lisp_Object type)
9281 /* Types pbm and xbm are built-in and always available. */
9282 if (EQ (type, Qpbm))
9283 return define_image_type (&pbm_type);
9285 if (EQ (type, Qxbm))
9286 return define_image_type (&xbm_type);
9288 #if defined (HAVE_XPM) || defined (HAVE_NS)
9289 if (EQ (type, Qxpm))
9290 return define_image_type (&xpm_type);
9291 #endif
9293 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9294 if (EQ (type, Qjpeg))
9295 return define_image_type (&jpeg_type);
9296 #endif
9298 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9299 if (EQ (type, Qtiff))
9300 return define_image_type (&tiff_type);
9301 #endif
9303 #if defined (HAVE_GIF) || defined (HAVE_NS)
9304 if (EQ (type, Qgif))
9305 return define_image_type (&gif_type);
9306 #endif
9308 #if defined (HAVE_PNG) || defined (HAVE_NS)
9309 if (EQ (type, Qpng))
9310 return define_image_type (&png_type);
9311 #endif
9313 #if defined (HAVE_RSVG)
9314 if (EQ (type, Qsvg))
9315 return define_image_type (&svg_type);
9316 #endif
9318 #if defined (HAVE_IMAGEMAGICK)
9319 if (EQ (type, Qimagemagick))
9320 return define_image_type (&imagemagick_type);
9321 #endif
9323 #ifdef HAVE_GHOSTSCRIPT
9324 if (EQ (type, Qpostscript))
9325 return define_image_type (&gs_type);
9326 #endif
9328 return NULL;
9331 /* Reset image_types before dumping.
9332 Called from Fdump_emacs. */
9334 void
9335 reset_image_types (void)
9337 while (image_types)
9339 struct image_type *next = image_types->next;
9340 xfree (image_types);
9341 image_types = next;
9345 void
9346 syms_of_image (void)
9348 /* Initialize this only once; it will be reset before dumping. */
9349 image_types = NULL;
9351 /* Must be defined now because we're going to update it below, while
9352 defining the supported image types. */
9353 DEFVAR_LISP ("image-types", Vimage_types,
9354 doc: /* List of potentially supported image types.
9355 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9356 To check whether it is really supported, use `image-type-available-p'. */);
9357 Vimage_types = Qnil;
9359 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9360 doc: /* Maximum size of images.
9361 Emacs will not load an image into memory if its pixel width or
9362 pixel height exceeds this limit.
9364 If the value is an integer, it directly specifies the maximum
9365 image height and width, measured in pixels. If it is a floating
9366 point number, it specifies the maximum image height and width
9367 as a ratio to the frame height and width. If the value is
9368 non-numeric, there is no explicit limit on the size of images. */);
9369 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9371 DEFSYM (Qcount, "count");
9372 DEFSYM (Qextension_data, "extension-data");
9373 DEFSYM (Qdelay, "delay");
9375 DEFSYM (QCascent, ":ascent");
9376 DEFSYM (QCmargin, ":margin");
9377 DEFSYM (QCrelief, ":relief");
9378 DEFSYM (QCconversion, ":conversion");
9379 DEFSYM (QCcolor_symbols, ":color-symbols");
9380 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9381 DEFSYM (QCindex, ":index");
9382 DEFSYM (QCgeometry, ":geometry");
9383 DEFSYM (QCcrop, ":crop");
9384 DEFSYM (QCrotation, ":rotation");
9385 DEFSYM (QCmatrix, ":matrix");
9386 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9387 DEFSYM (QCmask, ":mask");
9389 DEFSYM (Qlaplace, "laplace");
9390 DEFSYM (Qemboss, "emboss");
9391 DEFSYM (Qedge_detection, "edge-detection");
9392 DEFSYM (Qheuristic, "heuristic");
9394 DEFSYM (Qpostscript, "postscript");
9395 DEFSYM (QCmax_width, ":max-width");
9396 DEFSYM (QCmax_height, ":max-height");
9397 #ifdef HAVE_GHOSTSCRIPT
9398 ADD_IMAGE_TYPE (Qpostscript);
9399 DEFSYM (QCloader, ":loader");
9400 DEFSYM (QCbounding_box, ":bounding-box");
9401 DEFSYM (QCpt_width, ":pt-width");
9402 DEFSYM (QCpt_height, ":pt-height");
9403 #endif /* HAVE_GHOSTSCRIPT */
9405 #ifdef HAVE_NTGUI
9406 DEFSYM (Qlibpng_version, "libpng-version");
9407 Fset (Qlibpng_version,
9408 #if HAVE_PNG
9409 make_number (PNG_LIBPNG_VER)
9410 #else
9411 make_number (-1)
9412 #endif
9414 DEFSYM (Qlibgif_version, "libgif-version");
9415 Fset (Qlibgif_version,
9416 #ifdef HAVE_GIF
9417 make_number (GIFLIB_MAJOR * 10000
9418 + GIFLIB_MINOR * 100
9419 + GIFLIB_RELEASE)
9420 #else
9421 make_number (-1)
9422 #endif
9424 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9425 Fset (Qlibjpeg_version,
9426 #if HAVE_JPEG
9427 make_number (JPEG_LIB_VERSION)
9428 #else
9429 make_number (-1)
9430 #endif
9432 #endif
9434 DEFSYM (Qpbm, "pbm");
9435 ADD_IMAGE_TYPE (Qpbm);
9437 DEFSYM (Qxbm, "xbm");
9438 ADD_IMAGE_TYPE (Qxbm);
9440 #if defined (HAVE_XPM) || defined (HAVE_NS)
9441 DEFSYM (Qxpm, "xpm");
9442 ADD_IMAGE_TYPE (Qxpm);
9443 #endif
9445 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9446 DEFSYM (Qjpeg, "jpeg");
9447 ADD_IMAGE_TYPE (Qjpeg);
9448 #endif
9450 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9451 DEFSYM (Qtiff, "tiff");
9452 ADD_IMAGE_TYPE (Qtiff);
9453 #endif
9455 #if defined (HAVE_GIF) || defined (HAVE_NS)
9456 DEFSYM (Qgif, "gif");
9457 ADD_IMAGE_TYPE (Qgif);
9458 #endif
9460 #if defined (HAVE_PNG) || defined (HAVE_NS)
9461 DEFSYM (Qpng, "png");
9462 ADD_IMAGE_TYPE (Qpng);
9463 #endif
9465 #if defined (HAVE_IMAGEMAGICK)
9466 DEFSYM (Qimagemagick, "imagemagick");
9467 ADD_IMAGE_TYPE (Qimagemagick);
9468 #endif
9470 #if defined (HAVE_RSVG)
9471 DEFSYM (Qsvg, "svg");
9472 ADD_IMAGE_TYPE (Qsvg);
9473 #ifdef HAVE_NTGUI
9474 /* Other libraries used directly by svg code. */
9475 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9476 DEFSYM (Qglib, "glib");
9477 DEFSYM (Qgobject, "gobject");
9478 #endif /* HAVE_NTGUI */
9479 #endif /* HAVE_RSVG */
9481 defsubr (&Sinit_image_library);
9482 #ifdef HAVE_IMAGEMAGICK
9483 defsubr (&Simagemagick_types);
9484 #endif
9485 defsubr (&Sclear_image_cache);
9486 defsubr (&Simage_flush);
9487 defsubr (&Simage_size);
9488 defsubr (&Simage_mask_p);
9489 defsubr (&Simage_metadata);
9491 #ifdef GLYPH_DEBUG
9492 defsubr (&Simagep);
9493 defsubr (&Slookup_image);
9494 #endif
9496 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9497 doc: /* Non-nil means always draw a cross over disabled images.
9498 Disabled images are those having a `:conversion disabled' property.
9499 A cross is always drawn on black & white displays. */);
9500 cross_disabled_images = 0;
9502 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9503 doc: /* List of directories to search for window system bitmap files. */);
9504 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9506 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9507 doc: /* Maximum time after which images are removed from the cache.
9508 When an image has not been displayed this many seconds, Emacs
9509 automatically removes it from the image cache. If the cache contains
9510 a large number of images, the actual eviction time may be shorter.
9511 The value can also be nil, meaning the cache is never cleared.
9513 The function `clear-image-cache' disregards this variable. */);
9514 Vimage_cache_eviction_delay = make_number (300);
9515 #ifdef HAVE_IMAGEMAGICK
9516 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9517 doc: /* Integer indicating which ImageMagick rendering method to use.
9518 The options are:
9519 0 -- the default method (pixel pushing)
9520 1 -- a newer method ("MagickExportImagePixels") that may perform
9521 better (speed etc) in some cases, but has not been as thoroughly
9522 tested with Emacs as the default method. This method requires
9523 ImageMagick version 6.4.6 (approximately) or later.
9524 */);
9525 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9526 imagemagick_render_type = 0;
9527 #endif