Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / src / image.c
blob7d6445527a98b47586e88bd27c1afdd6fc02a202
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 #ifdef HAVE_PNG
25 #if defined HAVE_LIBPNG_PNG_H
26 # include <libpng/png.h>
27 #else
28 # include <png.h>
29 #endif
30 #endif
32 #include <setjmp.h>
33 #include <c-ctype.h>
35 #include "lisp.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "dispextern.h"
39 #include "blockinput.h"
40 #include "systime.h"
41 #include <epaths.h>
42 #include "character.h"
43 #include "coding.h"
44 #include "termhooks.h"
45 #include "font.h"
47 #ifdef HAVE_SYS_STAT_H
48 #include <sys/stat.h>
49 #endif /* HAVE_SYS_STAT_H */
51 #ifdef HAVE_SYS_TYPES_H
52 #include <sys/types.h>
53 #endif /* HAVE_SYS_TYPES_H */
55 #ifdef HAVE_WINDOW_SYSTEM
56 #include TERM_HEADER
57 #endif /* HAVE_WINDOW_SYSTEM */
59 #ifdef HAVE_X_WINDOWS
60 #define COLOR_TABLE_SUPPORT 1
62 typedef struct x_bitmap_record Bitmap_Record;
63 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
64 #define NO_PIXMAP None
66 #define PIX_MASK_RETAIN 0
67 #define PIX_MASK_DRAW 1
68 #endif /* HAVE_X_WINDOWS */
70 #ifdef HAVE_NTGUI
72 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
73 #ifdef WINDOWSNT
74 # include "w32.h"
75 #endif
77 /* W32_TODO : Color tables on W32. */
78 #undef COLOR_TABLE_SUPPORT
80 typedef struct w32_bitmap_record Bitmap_Record;
81 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
82 #define NO_PIXMAP 0
84 #define PIX_MASK_RETAIN 0
85 #define PIX_MASK_DRAW 1
87 #define x_defined_color w32_defined_color
88 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
90 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
91 or -1 if no PNG/GIF support was compiled in. This is tested by
92 w32-win.el to correctly set up the alist used to search for the
93 respective image libraries. */
94 Lisp_Object Qlibpng_version, Qlibgif_version, Qlibjpeg_version;
96 #endif /* HAVE_NTGUI */
98 #ifdef HAVE_NS
99 #undef COLOR_TABLE_SUPPORT
101 typedef struct ns_bitmap_record Bitmap_Record;
103 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
104 #define NO_PIXMAP 0
106 #define PIX_MASK_RETAIN 0
107 #define PIX_MASK_DRAW 1
109 #define x_defined_color(f, name, color_def, alloc) \
110 ns_defined_color (f, name, color_def, alloc, 0)
111 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
112 #endif /* HAVE_NS */
115 /* The symbol `postscript' identifying images of this type. */
117 static Lisp_Object Qpostscript;
119 static void x_disable_image (struct frame *, struct image *);
120 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
121 Lisp_Object);
123 static void init_color_table (void);
124 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
125 #ifdef COLOR_TABLE_SUPPORT
126 static void free_color_table (void);
127 static unsigned long *colors_in_color_table (int *n);
128 #endif
130 static Lisp_Object QCmax_width, QCmax_height;
132 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
133 id, which is just an int that this section returns. Bitmaps are
134 reference counted so they can be shared among frames.
136 Bitmap indices are guaranteed to be > 0, so a negative number can
137 be used to indicate no bitmap.
139 If you use x_create_bitmap_from_data, then you must keep track of
140 the bitmaps yourself. That is, creating a bitmap from the same
141 data more than once will not be caught. */
143 #ifdef HAVE_NS
144 /* Use with images created by ns_image_for_XPM. */
145 static unsigned long
146 XGetPixel (XImagePtr ximage, int x, int y)
148 return ns_get_pixel (ximage, x, y);
151 /* Use with images created by ns_image_for_XPM; alpha set to 1;
152 pixel is assumed to be in RGB form. */
153 static void
154 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
156 ns_put_pixel (ximage, x, y, pixel);
158 #endif /* HAVE_NS */
161 /* Functions to access the contents of a bitmap, given an id. */
163 static int
164 x_bitmap_height (struct frame *f, ptrdiff_t id)
166 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
169 static int
170 x_bitmap_width (struct frame *f, ptrdiff_t id)
172 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
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 /* Free resources, then free IMG. */
1002 img->type->free (f, img);
1003 xfree (img);
1007 /* Return true if the given widths and heights are valid for display. */
1009 static bool
1010 check_image_size (struct frame *f, int width, int height)
1012 int w, h;
1014 if (width <= 0 || height <= 0)
1015 return 0;
1017 if (INTEGERP (Vmax_image_size))
1018 return (width <= XINT (Vmax_image_size)
1019 && height <= XINT (Vmax_image_size));
1020 else if (FLOATP (Vmax_image_size))
1022 if (f != NULL)
1024 w = FRAME_PIXEL_WIDTH (f);
1025 h = FRAME_PIXEL_HEIGHT (f);
1027 else
1028 w = h = 1024; /* Arbitrary size for unknown frame. */
1029 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1030 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1032 else
1033 return 1;
1036 /* Prepare image IMG for display on frame F. Must be called before
1037 drawing an image. */
1039 void
1040 prepare_image_for_display (struct frame *f, struct image *img)
1042 /* We're about to display IMG, so set its timestamp to `now'. */
1043 img->timestamp = current_timespec ();
1045 /* If IMG doesn't have a pixmap yet, load it now, using the image
1046 type dependent loader function. */
1047 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1048 img->load_failed_p = ! img->type->load (f, img);
1050 #ifdef HAVE_X_WINDOWS
1051 if (!img->load_failed_p)
1053 block_input ();
1054 image_sync_to_pixmaps (f, img);
1055 unblock_input ();
1057 #endif
1061 /* Value is the number of pixels for the ascent of image IMG when
1062 drawn in face FACE. */
1065 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1067 int height;
1068 int ascent;
1070 if (slice->height == img->height)
1071 height = img->height + img->vmargin;
1072 else if (slice->y == 0)
1073 height = slice->height + img->vmargin;
1074 else
1075 height = slice->height;
1077 if (img->ascent == CENTERED_IMAGE_ASCENT)
1079 if (face->font)
1081 #ifdef HAVE_NTGUI
1082 /* W32 specific version. Why?. ++kfs */
1083 ascent = height / 2 - (FONT_DESCENT (face->font)
1084 - FONT_BASE (face->font)) / 2;
1085 #else
1086 /* This expression is arranged so that if the image can't be
1087 exactly centered, it will be moved slightly up. This is
1088 because a typical font is `top-heavy' (due to the presence
1089 uppercase letters), so the image placement should err towards
1090 being top-heavy too. It also just generally looks better. */
1091 ascent = (height + FONT_BASE (face->font)
1092 - FONT_DESCENT (face->font) + 1) / 2;
1093 #endif /* HAVE_NTGUI */
1095 else
1096 ascent = height / 2;
1098 else
1099 ascent = height * (img->ascent / 100.0);
1101 return ascent;
1105 /* Image background colors. */
1107 /* Find the "best" corner color of a bitmap.
1108 On W32, XIMG is assumed to a device context with the bitmap selected. */
1110 static RGB_PIXEL_COLOR
1111 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1112 unsigned long width, unsigned long height)
1114 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1115 int i, best_count;
1117 if (corners && corners[BOT_CORNER] >= 0)
1119 /* Get the colors at the corner_pixels of ximg. */
1120 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1121 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1122 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1123 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1125 else
1127 /* Get the colors at the corner_pixels of ximg. */
1128 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1129 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1130 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1131 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1133 /* Choose the most frequently found color as background. */
1134 for (i = best_count = 0; i < 4; ++i)
1136 int j, n;
1138 for (j = n = 0; j < 4; ++j)
1139 if (corner_pixels[i] == corner_pixels[j])
1140 ++n;
1142 if (n > best_count)
1143 best = corner_pixels[i], best_count = n;
1146 return best;
1149 /* Portability macros */
1151 #ifdef HAVE_NTGUI
1153 #define Free_Pixmap(display, pixmap) \
1154 DeleteObject (pixmap)
1156 #elif defined (HAVE_NS)
1158 #define Free_Pixmap(display, pixmap) \
1159 ns_release_object (pixmap)
1161 #else
1163 #define Free_Pixmap(display, pixmap) \
1164 XFreePixmap (display, pixmap)
1166 #endif /* !HAVE_NTGUI && !HAVE_NS */
1169 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1170 it is guessed heuristically. If non-zero, XIMG is an existing
1171 XImage object (or device context with the image selected on W32) to
1172 use for the heuristic. */
1174 RGB_PIXEL_COLOR
1175 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1177 if (! img->background_valid)
1178 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1180 bool free_ximg = !ximg;
1181 #ifdef HAVE_NTGUI
1182 HGDIOBJ prev;
1183 #endif /* HAVE_NTGUI */
1185 if (free_ximg)
1186 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1188 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1190 if (free_ximg)
1191 image_unget_x_image_or_dc (img, 0, ximg, prev);
1193 img->background_valid = 1;
1196 return img->background;
1199 /* Return the `background_transparent' field of IMG. If IMG doesn't
1200 have one yet, it is guessed heuristically. If non-zero, MASK is an
1201 existing XImage object to use for the heuristic. */
1204 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1206 if (! img->background_transparent_valid)
1207 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1209 if (img->mask)
1211 bool free_mask = !mask;
1212 #ifdef HAVE_NTGUI
1213 HGDIOBJ prev;
1214 #endif /* HAVE_NTGUI */
1216 if (free_mask)
1217 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1219 img->background_transparent
1220 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1222 if (free_mask)
1223 image_unget_x_image_or_dc (img, 1, mask, prev);
1225 else
1226 img->background_transparent = 0;
1228 img->background_transparent_valid = 1;
1231 return img->background_transparent;
1235 /***********************************************************************
1236 Helper functions for X image types
1237 ***********************************************************************/
1239 /* Clear X resources of image IMG on frame F according to FLAGS.
1240 FLAGS is bitwise-or of the following masks:
1241 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1242 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1243 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1244 any. */
1246 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1247 #define CLEAR_IMAGE_MASK (1 << 1)
1248 #define CLEAR_IMAGE_COLORS (1 << 2)
1250 static void
1251 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1253 if (flags & CLEAR_IMAGE_PIXMAP)
1255 if (img->pixmap)
1257 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1258 img->pixmap = NO_PIXMAP;
1259 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1260 img->background_valid = 0;
1262 #ifdef HAVE_X_WINDOWS
1263 if (img->ximg)
1265 x_destroy_x_image (img->ximg);
1266 img->ximg = NULL;
1267 img->background_valid = 0;
1269 #endif
1272 if (flags & CLEAR_IMAGE_MASK)
1274 if (img->mask)
1276 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1277 img->mask = NO_PIXMAP;
1278 img->background_transparent_valid = 0;
1280 #ifdef HAVE_X_WINDOWS
1281 if (img->mask_img)
1283 x_destroy_x_image (img->mask_img);
1284 img->mask_img = NULL;
1285 img->background_transparent_valid = 0;
1287 #endif
1290 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1292 /* W32_TODO: color table support. */
1293 #ifdef HAVE_X_WINDOWS
1294 x_free_colors (f, img->colors, img->ncolors);
1295 #endif /* HAVE_X_WINDOWS */
1296 xfree (img->colors);
1297 img->colors = NULL;
1298 img->ncolors = 0;
1303 /* Free X resources of image IMG which is used on frame F. */
1305 static void
1306 x_clear_image (struct frame *f, struct image *img)
1308 block_input ();
1309 x_clear_image_1 (f, img,
1310 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1311 unblock_input ();
1315 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1316 cannot be allocated, use DFLT. Add a newly allocated color to
1317 IMG->colors, so that it can be freed again. Value is the pixel
1318 color. */
1320 static unsigned long
1321 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1322 unsigned long dflt)
1324 XColor color;
1325 unsigned long result;
1327 eassert (STRINGP (color_name));
1329 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1330 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1331 INT_MAX))
1333 /* This isn't called frequently so we get away with simply
1334 reallocating the color vector to the needed size, here. */
1335 ptrdiff_t ncolors = img->ncolors + 1;
1336 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1337 img->colors[ncolors - 1] = color.pixel;
1338 img->ncolors = ncolors;
1339 result = color.pixel;
1341 else
1342 result = dflt;
1344 return result;
1349 /***********************************************************************
1350 Image Cache
1351 ***********************************************************************/
1353 static void cache_image (struct frame *f, struct image *img);
1355 /* Return a new, initialized image cache that is allocated from the
1356 heap. Call free_image_cache to free an image cache. */
1358 struct image_cache *
1359 make_image_cache (void)
1361 struct image_cache *c = xmalloc (sizeof *c);
1363 c->size = 50;
1364 c->used = c->refcount = 0;
1365 c->images = xmalloc (c->size * sizeof *c->images);
1366 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1367 return c;
1371 /* Find an image matching SPEC in the cache, and return it. If no
1372 image is found, return NULL. */
1373 static struct image *
1374 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1376 struct image *img;
1377 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1378 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1380 if (!c) return NULL;
1382 /* If the image spec does not specify a background color, the cached
1383 image must have the same background color as the current frame.
1384 The foreground color must also match, for the sake of monochrome
1385 images.
1387 In fact, we could ignore the foreground color matching condition
1388 for color images, or if the image spec specifies :foreground;
1389 similarly we could ignore the background color matching condition
1390 for formats that don't use transparency (such as jpeg), or if the
1391 image spec specifies :background. However, the extra memory
1392 usage is probably negligible in practice, so we don't bother. */
1394 for (img = c->buckets[i]; img; img = img->next)
1395 if (img->hash == hash
1396 && !NILP (Fequal (img->spec, spec))
1397 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1398 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1399 break;
1400 return img;
1404 /* Search frame F for an image with spec SPEC, and free it. */
1406 static void
1407 uncache_image (struct frame *f, Lisp_Object spec)
1409 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1410 if (img)
1412 free_image (f, img);
1413 /* As display glyphs may still be referring to the image ID, we
1414 must garbage the frame (Bug#6426). */
1415 SET_FRAME_GARBAGED (f);
1420 /* Free image cache of frame F. Be aware that X frames share images
1421 caches. */
1423 void
1424 free_image_cache (struct frame *f)
1426 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1427 if (c)
1429 ptrdiff_t i;
1431 /* Cache should not be referenced by any frame when freed. */
1432 eassert (c->refcount == 0);
1434 for (i = 0; i < c->used; ++i)
1435 free_image (f, c->images[i]);
1436 xfree (c->images);
1437 xfree (c->buckets);
1438 xfree (c);
1439 FRAME_IMAGE_CACHE (f) = NULL;
1444 /* Clear image cache of frame F. FILTER=t means free all images.
1445 FILTER=nil means clear only images that haven't been
1446 displayed for some time.
1447 Else, only free the images which have FILTER in their `dependencies'.
1448 Should be called from time to time to reduce the number of loaded images.
1449 If image-cache-eviction-delay is non-nil, this frees images in the cache
1450 which weren't displayed for at least that many seconds. */
1452 static void
1453 clear_image_cache (struct frame *f, Lisp_Object filter)
1455 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1457 if (c)
1459 ptrdiff_t i, nfreed = 0;
1461 /* Block input so that we won't be interrupted by a SIGIO
1462 while being in an inconsistent state. */
1463 block_input ();
1465 if (!NILP (filter))
1467 /* Filter image cache. */
1468 for (i = 0; i < c->used; ++i)
1470 struct image *img = c->images[i];
1471 if (img && (EQ (Qt, filter)
1472 || !NILP (Fmember (filter, img->dependencies))))
1474 free_image (f, img);
1475 ++nfreed;
1479 else if (INTEGERP (Vimage_cache_eviction_delay))
1481 /* Free cache based on timestamp. */
1482 struct timespec old, t;
1483 double delay;
1484 ptrdiff_t nimages = 0;
1486 for (i = 0; i < c->used; ++i)
1487 if (c->images[i])
1488 nimages++;
1490 /* If the number of cached images has grown unusually large,
1491 decrease the cache eviction delay (Bug#6230). */
1492 delay = XINT (Vimage_cache_eviction_delay);
1493 if (nimages > 40)
1494 delay = 1600 * delay / nimages / nimages;
1495 delay = max (delay, 1);
1497 t = current_timespec ();
1498 old = timespec_sub (t, dtotimespec (delay));
1500 for (i = 0; i < c->used; ++i)
1502 struct image *img = c->images[i];
1503 if (img && timespec_cmp (img->timestamp, old) < 0)
1505 free_image (f, img);
1506 ++nfreed;
1511 /* We may be clearing the image cache because, for example,
1512 Emacs was iconified for a longer period of time. In that
1513 case, current matrices may still contain references to
1514 images freed above. So, clear these matrices. */
1515 if (nfreed)
1517 Lisp_Object tail, frame;
1519 FOR_EACH_FRAME (tail, frame)
1521 struct frame *fr = XFRAME (frame);
1522 if (FRAME_IMAGE_CACHE (fr) == c)
1523 clear_current_matrices (fr);
1526 windows_or_buffers_changed = 19;
1529 unblock_input ();
1533 void
1534 clear_image_caches (Lisp_Object filter)
1536 /* FIXME: We want to do
1537 * struct terminal *t;
1538 * for (t = terminal_list; t; t = t->next_terminal)
1539 * clear_image_cache (t, filter); */
1540 Lisp_Object tail, frame;
1541 FOR_EACH_FRAME (tail, frame)
1542 if (FRAME_WINDOW_P (XFRAME (frame)))
1543 clear_image_cache (XFRAME (frame), filter);
1546 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1547 0, 1, 0,
1548 doc: /* Clear the image cache.
1549 FILTER nil or a frame means clear all images in the selected frame.
1550 FILTER t means clear the image caches of all frames.
1551 Anything else, means only clear those images which refer to FILTER,
1552 which is then usually a filename. */)
1553 (Lisp_Object filter)
1555 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1556 clear_image_caches (filter);
1557 else
1558 clear_image_cache (decode_window_system_frame (filter), Qt);
1560 return Qnil;
1564 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1565 1, 2, 0,
1566 doc: /* Flush the image with specification SPEC on frame FRAME.
1567 This removes the image from the Emacs image cache. If SPEC specifies
1568 an image file, the next redisplay of this image will read from the
1569 current contents of that file.
1571 FRAME nil or omitted means use the selected frame.
1572 FRAME t means refresh the image on all frames. */)
1573 (Lisp_Object spec, Lisp_Object frame)
1575 if (!valid_image_p (spec))
1576 error ("Invalid image specification");
1578 if (EQ (frame, Qt))
1580 Lisp_Object tail;
1581 FOR_EACH_FRAME (tail, frame)
1583 struct frame *f = XFRAME (frame);
1584 if (FRAME_WINDOW_P (f))
1585 uncache_image (f, spec);
1588 else
1589 uncache_image (decode_window_system_frame (frame), spec);
1591 return Qnil;
1595 /* Compute masks and transform image IMG on frame F, as specified
1596 by the image's specification, */
1598 static void
1599 postprocess_image (struct frame *f, struct image *img)
1601 /* Manipulation of the image's mask. */
1602 if (img->pixmap)
1604 Lisp_Object conversion, spec;
1605 Lisp_Object mask;
1607 spec = img->spec;
1609 /* `:heuristic-mask t'
1610 `:mask heuristic'
1611 means build a mask heuristically.
1612 `:heuristic-mask (R G B)'
1613 `:mask (heuristic (R G B))'
1614 means build a mask from color (R G B) in the
1615 image.
1616 `:mask nil'
1617 means remove a mask, if any. */
1619 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1620 if (!NILP (mask))
1621 x_build_heuristic_mask (f, img, mask);
1622 else
1624 bool found_p;
1626 mask = image_spec_value (spec, QCmask, &found_p);
1628 if (EQ (mask, Qheuristic))
1629 x_build_heuristic_mask (f, img, Qt);
1630 else if (CONSP (mask)
1631 && EQ (XCAR (mask), Qheuristic))
1633 if (CONSP (XCDR (mask)))
1634 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1635 else
1636 x_build_heuristic_mask (f, img, XCDR (mask));
1638 else if (NILP (mask) && found_p && img->mask)
1639 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1643 /* Should we apply an image transformation algorithm? */
1644 conversion = image_spec_value (spec, QCconversion, NULL);
1645 if (EQ (conversion, Qdisabled))
1646 x_disable_image (f, img);
1647 else if (EQ (conversion, Qlaplace))
1648 x_laplace (f, img);
1649 else if (EQ (conversion, Qemboss))
1650 x_emboss (f, img);
1651 else if (CONSP (conversion)
1652 && EQ (XCAR (conversion), Qedge_detection))
1654 Lisp_Object tem;
1655 tem = XCDR (conversion);
1656 if (CONSP (tem))
1657 x_edge_detection (f, img,
1658 Fplist_get (tem, QCmatrix),
1659 Fplist_get (tem, QCcolor_adjustment));
1665 /* Return the id of image with Lisp specification SPEC on frame F.
1666 SPEC must be a valid Lisp image specification (see valid_image_p). */
1668 ptrdiff_t
1669 lookup_image (struct frame *f, Lisp_Object spec)
1671 struct image *img;
1672 EMACS_UINT hash;
1674 /* F must be a window-system frame, and SPEC must be a valid image
1675 specification. */
1676 eassert (FRAME_WINDOW_P (f));
1677 eassert (valid_image_p (spec));
1679 /* Look up SPEC in the hash table of the image cache. */
1680 hash = sxhash (spec, 0);
1681 img = search_image_cache (f, spec, hash);
1682 if (img && img->load_failed_p)
1684 free_image (f, img);
1685 img = NULL;
1688 /* If not found, create a new image and cache it. */
1689 if (img == NULL)
1691 block_input ();
1692 img = make_image (spec, hash);
1693 cache_image (f, img);
1694 img->load_failed_p = ! img->type->load (f, img);
1695 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1696 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1698 /* If we can't load the image, and we don't have a width and
1699 height, use some arbitrary width and height so that we can
1700 draw a rectangle for it. */
1701 if (img->load_failed_p)
1703 Lisp_Object value;
1705 value = image_spec_value (spec, QCwidth, NULL);
1706 img->width = (INTEGERP (value)
1707 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1708 value = image_spec_value (spec, QCheight, NULL);
1709 img->height = (INTEGERP (value)
1710 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1712 else
1714 /* Handle image type independent image attributes
1715 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1716 `:background COLOR'. */
1717 Lisp_Object ascent, margin, relief, bg;
1718 int relief_bound;
1720 ascent = image_spec_value (spec, QCascent, NULL);
1721 if (INTEGERP (ascent))
1722 img->ascent = XFASTINT (ascent);
1723 else if (EQ (ascent, Qcenter))
1724 img->ascent = CENTERED_IMAGE_ASCENT;
1726 margin = image_spec_value (spec, QCmargin, NULL);
1727 if (INTEGERP (margin))
1728 img->vmargin = img->hmargin = XFASTINT (margin);
1729 else if (CONSP (margin))
1731 img->hmargin = XFASTINT (XCAR (margin));
1732 img->vmargin = XFASTINT (XCDR (margin));
1735 relief = image_spec_value (spec, QCrelief, NULL);
1736 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1737 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1739 img->relief = XINT (relief);
1740 img->hmargin += eabs (img->relief);
1741 img->vmargin += eabs (img->relief);
1744 if (! img->background_valid)
1746 bg = image_spec_value (img->spec, QCbackground, NULL);
1747 if (!NILP (bg))
1749 img->background
1750 = x_alloc_image_color (f, img, bg,
1751 FRAME_BACKGROUND_PIXEL (f));
1752 img->background_valid = 1;
1756 /* Do image transformations and compute masks, unless we
1757 don't have the image yet. */
1758 if (!EQ (*img->type->type, Qpostscript))
1759 postprocess_image (f, img);
1762 unblock_input ();
1765 /* We're using IMG, so set its timestamp to `now'. */
1766 img->timestamp = current_timespec ();
1768 /* Value is the image id. */
1769 return img->id;
1773 /* Cache image IMG in the image cache of frame F. */
1775 static void
1776 cache_image (struct frame *f, struct image *img)
1778 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1779 ptrdiff_t i;
1781 /* Find a free slot in c->images. */
1782 for (i = 0; i < c->used; ++i)
1783 if (c->images[i] == NULL)
1784 break;
1786 /* If no free slot found, maybe enlarge c->images. */
1787 if (i == c->used && c->used == c->size)
1788 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1790 /* Add IMG to c->images, and assign IMG an id. */
1791 c->images[i] = img;
1792 img->id = i;
1793 if (i == c->used)
1794 ++c->used;
1796 /* Add IMG to the cache's hash table. */
1797 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1798 img->next = c->buckets[i];
1799 if (img->next)
1800 img->next->prev = img;
1801 img->prev = NULL;
1802 c->buckets[i] = img;
1806 /* Call FN on every image in the image cache of frame F. Used to mark
1807 Lisp Objects in the image cache. */
1809 /* Mark Lisp objects in image IMG. */
1811 static void
1812 mark_image (struct image *img)
1814 mark_object (img->spec);
1815 mark_object (img->dependencies);
1817 if (!NILP (img->lisp_data))
1818 mark_object (img->lisp_data);
1822 void
1823 mark_image_cache (struct image_cache *c)
1825 if (c)
1827 ptrdiff_t i;
1828 for (i = 0; i < c->used; ++i)
1829 if (c->images[i])
1830 mark_image (c->images[i]);
1836 /***********************************************************************
1837 X / NS / W32 support code
1838 ***********************************************************************/
1840 #ifdef WINDOWSNT
1842 /* Macro for defining functions that will be loaded from image DLLs. */
1843 #define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
1845 /* Macro for loading those image functions from the library. */
1846 #define LOAD_IMGLIB_FN(lib,func) { \
1847 fn_##func = (void *) GetProcAddress (lib, #func); \
1848 if (!fn_##func) return 0; \
1851 #endif /* WINDOWSNT */
1853 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1854 windowing system.
1855 WIDTH and HEIGHT must both be positive.
1856 If XIMG is null, assume it is a bitmap. */
1857 static bool
1858 x_check_image_size (XImagePtr ximg, int width, int height)
1860 #ifdef HAVE_X_WINDOWS
1861 /* Respect Xlib's limits: it cannot deal with images that have more
1862 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1863 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1864 enum
1866 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1867 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1870 int bitmap_pad, depth, bytes_per_line;
1871 if (ximg)
1873 bitmap_pad = ximg->bitmap_pad;
1874 depth = ximg->depth;
1875 bytes_per_line = ximg->bytes_per_line;
1877 else
1879 bitmap_pad = 8;
1880 depth = 1;
1881 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1883 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1884 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1885 #else
1886 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1887 For now, assume that every image size is allowed on these systems. */
1888 return 1;
1889 #endif
1892 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1893 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1894 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1895 via xmalloc. Print error messages via image_error if an error
1896 occurs. Value is true if successful.
1898 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1899 should indicate the bit depth of the image. */
1901 static bool
1902 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1903 XImagePtr *ximg, Pixmap *pixmap)
1905 #ifdef HAVE_X_WINDOWS
1906 Display *display = FRAME_X_DISPLAY (f);
1907 Window window = FRAME_X_WINDOW (f);
1908 Screen *screen = FRAME_X_SCREEN (f);
1910 eassert (input_blocked_p ());
1912 if (depth <= 0)
1913 depth = DefaultDepthOfScreen (screen);
1914 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1915 depth, ZPixmap, 0, NULL, width, height,
1916 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1917 if (*ximg == NULL)
1919 image_error ("Unable to allocate X image", Qnil, Qnil);
1920 return 0;
1923 if (! x_check_image_size (*ximg, width, height))
1925 x_destroy_x_image (*ximg);
1926 *ximg = NULL;
1927 image_error ("Image too large (%dx%d)",
1928 make_number (width), make_number (height));
1929 return 0;
1932 /* Allocate image raster. */
1933 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1935 /* Allocate a pixmap of the same size. */
1936 *pixmap = XCreatePixmap (display, window, width, height, depth);
1937 if (*pixmap == NO_PIXMAP)
1939 x_destroy_x_image (*ximg);
1940 *ximg = NULL;
1941 image_error ("Unable to create X pixmap", Qnil, Qnil);
1942 return 0;
1945 return 1;
1946 #endif /* HAVE_X_WINDOWS */
1948 #ifdef HAVE_NTGUI
1950 BITMAPINFOHEADER *header;
1951 HDC hdc;
1952 int scanline_width_bits;
1953 int remainder;
1954 int palette_colors = 0;
1956 if (depth == 0)
1957 depth = 24;
1959 if (depth != 1 && depth != 4 && depth != 8
1960 && depth != 16 && depth != 24 && depth != 32)
1962 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1963 return 0;
1966 scanline_width_bits = width * depth;
1967 remainder = scanline_width_bits % 32;
1969 if (remainder)
1970 scanline_width_bits += 32 - remainder;
1972 /* Bitmaps with a depth less than 16 need a palette. */
1973 /* BITMAPINFO structure already contains the first RGBQUAD. */
1974 if (depth < 16)
1975 palette_colors = 1 << (depth - 1);
1977 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1979 header = &(*ximg)->info.bmiHeader;
1980 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
1981 header->biSize = sizeof (*header);
1982 header->biWidth = width;
1983 header->biHeight = -height; /* negative indicates a top-down bitmap. */
1984 header->biPlanes = 1;
1985 header->biBitCount = depth;
1986 header->biCompression = BI_RGB;
1987 header->biClrUsed = palette_colors;
1989 /* TODO: fill in palette. */
1990 if (depth == 1)
1992 (*ximg)->info.bmiColors[0].rgbBlue = 0;
1993 (*ximg)->info.bmiColors[0].rgbGreen = 0;
1994 (*ximg)->info.bmiColors[0].rgbRed = 0;
1995 (*ximg)->info.bmiColors[0].rgbReserved = 0;
1996 (*ximg)->info.bmiColors[1].rgbBlue = 255;
1997 (*ximg)->info.bmiColors[1].rgbGreen = 255;
1998 (*ximg)->info.bmiColors[1].rgbRed = 255;
1999 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2002 hdc = get_frame_dc (f);
2004 /* Create a DIBSection and raster array for the bitmap,
2005 and store its handle in *pixmap. */
2006 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2007 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2008 /* casting avoids a GCC warning */
2009 (void **)&((*ximg)->data), NULL, 0);
2011 /* Realize display palette and garbage all frames. */
2012 release_frame_dc (f, hdc);
2014 if (*pixmap == NULL)
2016 DWORD err = GetLastError ();
2017 Lisp_Object errcode;
2018 /* All system errors are < 10000, so the following is safe. */
2019 XSETINT (errcode, err);
2020 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2021 x_destroy_x_image (*ximg);
2022 return 0;
2025 return 1;
2027 #endif /* HAVE_NTGUI */
2029 #ifdef HAVE_NS
2030 *pixmap = ns_image_for_XPM (width, height, depth);
2031 if (*pixmap == 0)
2033 *ximg = NULL;
2034 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2035 return 0;
2037 *ximg = *pixmap;
2038 return 1;
2039 #endif
2043 /* Destroy XImage XIMG. Free XIMG->data. */
2045 static void
2046 x_destroy_x_image (XImagePtr ximg)
2048 eassert (input_blocked_p ());
2049 if (ximg)
2051 #ifdef HAVE_X_WINDOWS
2052 xfree (ximg->data);
2053 ximg->data = NULL;
2054 XDestroyImage (ximg);
2055 #endif /* HAVE_X_WINDOWS */
2056 #ifdef HAVE_NTGUI
2057 /* Data will be freed by DestroyObject. */
2058 ximg->data = NULL;
2059 xfree (ximg);
2060 #endif /* HAVE_NTGUI */
2061 #ifdef HAVE_NS
2062 ns_release_object (ximg);
2063 #endif /* HAVE_NS */
2068 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2069 are width and height of both the image and pixmap. */
2071 static void
2072 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2074 #ifdef HAVE_X_WINDOWS
2075 GC gc;
2077 eassert (input_blocked_p ());
2078 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2079 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2080 XFreeGC (FRAME_X_DISPLAY (f), gc);
2081 #endif /* HAVE_X_WINDOWS */
2083 #ifdef HAVE_NTGUI
2084 #if 0 /* I don't think this is necessary looking at where it is used. */
2085 HDC hdc = get_frame_dc (f);
2086 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2087 release_frame_dc (f, hdc);
2088 #endif
2089 #endif /* HAVE_NTGUI */
2091 #ifdef HAVE_NS
2092 eassert (ximg == pixmap);
2093 ns_retain_object (ximg);
2094 #endif
2097 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2098 with image_put_x_image. */
2100 static bool
2101 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2102 int width, int height, int depth,
2103 XImagePtr *ximg, bool mask_p)
2105 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2107 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2108 !mask_p ? &img->pixmap : &img->mask);
2111 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2112 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2113 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2114 On the other platforms, it puts XIMG into the pixmap, then frees
2115 the X image and its buffer. */
2117 static void
2118 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2119 bool mask_p)
2121 #ifdef HAVE_X_WINDOWS
2122 if (!mask_p)
2124 eassert (img->ximg == NULL);
2125 img->ximg = ximg;
2127 else
2129 eassert (img->mask_img == NULL);
2130 img->mask_img = ximg;
2132 #else
2133 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2134 img->width, img->height);
2135 x_destroy_x_image (ximg);
2136 #endif
2139 #ifdef HAVE_X_WINDOWS
2140 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2141 the X images and their buffers. */
2143 static void
2144 image_sync_to_pixmaps (struct frame *f, struct image *img)
2146 if (img->ximg)
2148 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2149 x_destroy_x_image (img->ximg);
2150 img->ximg = NULL;
2152 if (img->mask_img)
2154 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2155 x_destroy_x_image (img->mask_img);
2156 img->mask_img = NULL;
2159 #endif
2161 #ifdef HAVE_NTGUI
2162 /* Create a memory device context for IMG on frame F. It stores the
2163 currently selected GDI object into *PREV for future restoration by
2164 image_unget_x_image_or_dc. */
2166 static XImagePtr_or_DC
2167 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2168 HGDIOBJ *prev)
2170 HDC frame_dc = get_frame_dc (f);
2171 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2173 release_frame_dc (f, frame_dc);
2174 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2176 return ximg;
2179 static void
2180 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2181 XImagePtr_or_DC ximg, HGDIOBJ prev)
2183 SelectObject (ximg, prev);
2184 DeleteDC (ximg);
2186 #else /* !HAVE_NTGUI */
2187 /* Get the X image for IMG on frame F. The resulting X image data
2188 should be treated as read-only at least on X. */
2190 static XImagePtr
2191 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2193 #ifdef HAVE_X_WINDOWS
2194 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2196 if (ximg_in_img)
2197 return ximg_in_img;
2198 else
2199 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2200 0, 0, img->width, img->height, ~0, ZPixmap);
2201 #elif defined (HAVE_NS)
2202 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2204 ns_retain_object (pixmap);
2205 return pixmap;
2206 #endif
2209 static void
2210 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2212 #ifdef HAVE_X_WINDOWS
2213 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2215 if (ximg_in_img)
2216 eassert (ximg == ximg_in_img);
2217 else
2218 XDestroyImage (ximg);
2219 #elif defined (HAVE_NS)
2220 ns_release_object (ximg);
2221 #endif
2223 #endif /* !HAVE_NTGUI */
2226 /***********************************************************************
2227 File Handling
2228 ***********************************************************************/
2230 /* Find image file FILE. Look in data-directory/images, then
2231 x-bitmap-file-path. Value is the encoded full name of the file
2232 found, or nil if not found. */
2234 Lisp_Object
2235 x_find_image_file (Lisp_Object file)
2237 Lisp_Object file_found, search_path;
2238 int fd;
2240 /* TODO I think this should use something like image-load-path
2241 instead. Unfortunately, that can contain non-string elements. */
2242 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2243 Vdata_directory),
2244 Vx_bitmap_file_path);
2246 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2247 fd = openp (search_path, file, Qnil, &file_found, Qnil, false);
2249 if (fd == -1)
2250 file_found = Qnil;
2251 else
2253 file_found = ENCODE_FILE (file_found);
2254 if (fd != -2)
2255 emacs_close (fd);
2258 return file_found;
2262 /* Read FILE into memory. Value is a pointer to a buffer allocated
2263 with xmalloc holding FILE's contents. Value is null if an error
2264 occurred. *SIZE is set to the size of the file. */
2266 static unsigned char *
2267 slurp_file (char *file, ptrdiff_t *size)
2269 FILE *fp = emacs_fopen (file, "rb");
2270 unsigned char *buf = NULL;
2271 struct stat st;
2273 if (fp)
2275 ptrdiff_t count = SPECPDL_INDEX ();
2276 record_unwind_protect_ptr (fclose_unwind, fp);
2278 if (fstat (fileno (fp), &st) == 0
2279 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2281 /* Report an error if we read past the purported EOF.
2282 This can happen if the file grows as we read it. */
2283 ptrdiff_t buflen = st.st_size;
2284 buf = xmalloc (buflen + 1);
2285 if (fread (buf, 1, buflen + 1, fp) == buflen)
2286 *size = buflen;
2287 else
2289 xfree (buf);
2290 buf = NULL;
2294 unbind_to (count, Qnil);
2297 return buf;
2302 /***********************************************************************
2303 XBM images
2304 ***********************************************************************/
2306 static bool xbm_load (struct frame *f, struct image *img);
2307 static bool xbm_image_p (Lisp_Object object);
2308 static bool xbm_file_p (Lisp_Object);
2311 /* Indices of image specification fields in xbm_format, below. */
2313 enum xbm_keyword_index
2315 XBM_TYPE,
2316 XBM_FILE,
2317 XBM_WIDTH,
2318 XBM_HEIGHT,
2319 XBM_DATA,
2320 XBM_FOREGROUND,
2321 XBM_BACKGROUND,
2322 XBM_ASCENT,
2323 XBM_MARGIN,
2324 XBM_RELIEF,
2325 XBM_ALGORITHM,
2326 XBM_HEURISTIC_MASK,
2327 XBM_MASK,
2328 XBM_LAST
2331 /* Vector of image_keyword structures describing the format
2332 of valid XBM image specifications. */
2334 static const struct image_keyword xbm_format[XBM_LAST] =
2336 {":type", IMAGE_SYMBOL_VALUE, 1},
2337 {":file", IMAGE_STRING_VALUE, 0},
2338 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2339 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2340 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2341 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2342 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2343 {":ascent", IMAGE_ASCENT_VALUE, 0},
2344 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2345 {":relief", IMAGE_INTEGER_VALUE, 0},
2346 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2347 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2348 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2351 /* Structure describing the image type XBM. */
2353 static struct image_type xbm_type =
2355 &Qxbm,
2356 xbm_image_p,
2357 xbm_load,
2358 x_clear_image,
2359 NULL,
2360 NULL
2363 /* Tokens returned from xbm_scan. */
2365 enum xbm_token
2367 XBM_TK_IDENT = 256,
2368 XBM_TK_NUMBER
2372 /* Return true if OBJECT is a valid XBM-type image specification.
2373 A valid specification is a list starting with the symbol `image'
2374 The rest of the list is a property list which must contain an
2375 entry `:type xbm'.
2377 If the specification specifies a file to load, it must contain
2378 an entry `:file FILENAME' where FILENAME is a string.
2380 If the specification is for a bitmap loaded from memory it must
2381 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2382 WIDTH and HEIGHT are integers > 0. DATA may be:
2384 1. a string large enough to hold the bitmap data, i.e. it must
2385 have a size >= (WIDTH + 7) / 8 * HEIGHT
2387 2. a bool-vector of size >= WIDTH * HEIGHT
2389 3. a vector of strings or bool-vectors, one for each line of the
2390 bitmap.
2392 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2393 may not be specified in this case because they are defined in the
2394 XBM file.
2396 Both the file and data forms may contain the additional entries
2397 `:background COLOR' and `:foreground COLOR'. If not present,
2398 foreground and background of the frame on which the image is
2399 displayed is used. */
2401 static bool
2402 xbm_image_p (Lisp_Object object)
2404 struct image_keyword kw[XBM_LAST];
2406 memcpy (kw, xbm_format, sizeof kw);
2407 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2408 return 0;
2410 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2412 if (kw[XBM_FILE].count)
2414 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2415 return 0;
2417 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2419 /* In-memory XBM file. */
2420 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2421 return 0;
2423 else
2425 Lisp_Object data;
2426 int width, height;
2428 /* Entries for `:width', `:height' and `:data' must be present. */
2429 if (!kw[XBM_WIDTH].count
2430 || !kw[XBM_HEIGHT].count
2431 || !kw[XBM_DATA].count)
2432 return 0;
2434 data = kw[XBM_DATA].value;
2435 width = XFASTINT (kw[XBM_WIDTH].value);
2436 height = XFASTINT (kw[XBM_HEIGHT].value);
2438 /* Check type of data, and width and height against contents of
2439 data. */
2440 if (VECTORP (data))
2442 EMACS_INT i;
2444 /* Number of elements of the vector must be >= height. */
2445 if (ASIZE (data) < height)
2446 return 0;
2448 /* Each string or bool-vector in data must be large enough
2449 for one line of the image. */
2450 for (i = 0; i < height; ++i)
2452 Lisp_Object elt = AREF (data, i);
2454 if (STRINGP (elt))
2456 if (SCHARS (elt)
2457 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2458 return 0;
2460 else if (BOOL_VECTOR_P (elt))
2462 if (bool_vector_size (elt) < width)
2463 return 0;
2465 else
2466 return 0;
2469 else if (STRINGP (data))
2471 if (SCHARS (data)
2472 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2473 return 0;
2475 else if (BOOL_VECTOR_P (data))
2477 if (bool_vector_size (data) / height < width)
2478 return 0;
2480 else
2481 return 0;
2484 return 1;
2488 /* Scan a bitmap file. FP is the stream to read from. Value is
2489 either an enumerator from enum xbm_token, or a character for a
2490 single-character token, or 0 at end of file. If scanning an
2491 identifier, store the lexeme of the identifier in SVAL. If
2492 scanning a number, store its value in *IVAL. */
2494 static int
2495 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2497 unsigned int c;
2499 loop:
2501 /* Skip white space. */
2502 while (*s < end && (c = *(*s)++, c_isspace (c)))
2505 if (*s >= end)
2506 c = 0;
2507 else if (c_isdigit (c))
2509 int value = 0, digit;
2511 if (c == '0' && *s < end)
2513 c = *(*s)++;
2514 if (c == 'x' || c == 'X')
2516 while (*s < end)
2518 c = *(*s)++;
2519 if (c_isdigit (c))
2520 digit = c - '0';
2521 else if (c >= 'a' && c <= 'f')
2522 digit = c - 'a' + 10;
2523 else if (c >= 'A' && c <= 'F')
2524 digit = c - 'A' + 10;
2525 else
2526 break;
2527 value = 16 * value + digit;
2530 else if (c_isdigit (c))
2532 value = c - '0';
2533 while (*s < end
2534 && (c = *(*s)++, c_isdigit (c)))
2535 value = 8 * value + c - '0';
2538 else
2540 value = c - '0';
2541 while (*s < end
2542 && (c = *(*s)++, c_isdigit (c)))
2543 value = 10 * value + c - '0';
2546 if (*s < end)
2547 *s = *s - 1;
2548 *ival = value;
2549 c = XBM_TK_NUMBER;
2551 else if (c_isalpha (c) || c == '_')
2553 *sval++ = c;
2554 while (*s < end
2555 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2556 *sval++ = c;
2557 *sval = 0;
2558 if (*s < end)
2559 *s = *s - 1;
2560 c = XBM_TK_IDENT;
2562 else if (c == '/' && **s == '*')
2564 /* C-style comment. */
2565 ++*s;
2566 while (**s && (**s != '*' || *(*s + 1) != '/'))
2567 ++*s;
2568 if (**s)
2570 *s += 2;
2571 goto loop;
2575 return c;
2578 #ifdef HAVE_NTGUI
2580 /* Create a Windows bitmap from X bitmap data. */
2581 static HBITMAP
2582 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2584 static unsigned char swap_nibble[16]
2585 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2586 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2587 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2588 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2589 int i, j, w1, w2;
2590 unsigned char *bits, *p;
2591 HBITMAP bmp;
2593 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2594 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2595 bits = alloca (height * w2);
2596 memset (bits, 0, height * w2);
2597 for (i = 0; i < height; i++)
2599 p = bits + i*w2;
2600 for (j = 0; j < w1; j++)
2602 /* Bitswap XBM bytes to match how Windows does things. */
2603 unsigned char c = *data++;
2604 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2605 | (swap_nibble[(c>>4) & 0xf]));
2608 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2610 return bmp;
2613 static void
2614 convert_mono_to_color_image (struct frame *f, struct image *img,
2615 COLORREF foreground, COLORREF background)
2617 HDC hdc, old_img_dc, new_img_dc;
2618 HGDIOBJ old_prev, new_prev;
2619 HBITMAP new_pixmap;
2621 hdc = get_frame_dc (f);
2622 old_img_dc = CreateCompatibleDC (hdc);
2623 new_img_dc = CreateCompatibleDC (hdc);
2624 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2625 release_frame_dc (f, hdc);
2626 old_prev = SelectObject (old_img_dc, img->pixmap);
2627 new_prev = SelectObject (new_img_dc, new_pixmap);
2628 /* Windows convention for mono bitmaps is black = background,
2629 white = foreground. */
2630 SetTextColor (new_img_dc, background);
2631 SetBkColor (new_img_dc, foreground);
2633 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2634 0, 0, SRCCOPY);
2636 SelectObject (old_img_dc, old_prev);
2637 SelectObject (new_img_dc, new_prev);
2638 DeleteDC (old_img_dc);
2639 DeleteDC (new_img_dc);
2640 DeleteObject (img->pixmap);
2641 if (new_pixmap == 0)
2642 fprintf (stderr, "Failed to convert image to color.\n");
2643 else
2644 img->pixmap = new_pixmap;
2647 #define XBM_BIT_SHUFFLE(b) (~(b))
2649 #else
2651 #define XBM_BIT_SHUFFLE(b) (b)
2653 #endif /* HAVE_NTGUI */
2656 static void
2657 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2658 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2659 bool non_default_colors)
2661 #ifdef HAVE_NTGUI
2662 img->pixmap
2663 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2665 /* If colors were specified, transfer the bitmap to a color one. */
2666 if (non_default_colors)
2667 convert_mono_to_color_image (f, img, fg, bg);
2669 #elif defined (HAVE_NS)
2670 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2672 #else
2673 img->pixmap =
2674 (x_check_image_size (0, img->width, img->height)
2675 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2676 FRAME_X_WINDOW (f),
2677 data,
2678 img->width, img->height,
2679 fg, bg,
2680 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2681 : NO_PIXMAP);
2682 #endif /* !HAVE_NTGUI && !HAVE_NS */
2687 /* Replacement for XReadBitmapFileData which isn't available under old
2688 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2689 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2690 the image. Return in *DATA the bitmap data allocated with xmalloc.
2691 Value is true if successful. DATA null means just test if
2692 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2693 inhibit the call to image_error when the image size is invalid (the
2694 bitmap remains unread). */
2696 static bool
2697 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2698 int *width, int *height, char **data,
2699 bool inhibit_image_error)
2701 unsigned char *s = contents;
2702 char buffer[BUFSIZ];
2703 bool padding_p = 0;
2704 bool v10 = 0;
2705 int bytes_per_line, i, nbytes;
2706 char *p;
2707 int value;
2708 int LA1;
2710 #define match() \
2711 LA1 = xbm_scan (&s, end, buffer, &value)
2713 #define expect(TOKEN) \
2714 do \
2716 if (LA1 != (TOKEN)) \
2717 goto failure; \
2718 match (); \
2720 while (0)
2722 #define expect_ident(IDENT) \
2723 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2724 match (); \
2725 else \
2726 goto failure
2728 *width = *height = -1;
2729 if (data)
2730 *data = NULL;
2731 LA1 = xbm_scan (&s, end, buffer, &value);
2733 /* Parse defines for width, height and hot-spots. */
2734 while (LA1 == '#')
2736 match ();
2737 expect_ident ("define");
2738 expect (XBM_TK_IDENT);
2740 if (LA1 == XBM_TK_NUMBER)
2742 char *q = strrchr (buffer, '_');
2743 q = q ? q + 1 : buffer;
2744 if (strcmp (q, "width") == 0)
2745 *width = value;
2746 else if (strcmp (q, "height") == 0)
2747 *height = value;
2749 expect (XBM_TK_NUMBER);
2752 if (!check_image_size (f, *width, *height))
2754 if (!inhibit_image_error)
2755 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2756 goto failure;
2758 else if (data == NULL)
2759 goto success;
2761 /* Parse bits. Must start with `static'. */
2762 expect_ident ("static");
2763 if (LA1 == XBM_TK_IDENT)
2765 if (strcmp (buffer, "unsigned") == 0)
2767 match ();
2768 expect_ident ("char");
2770 else if (strcmp (buffer, "short") == 0)
2772 match ();
2773 v10 = 1;
2774 if (*width % 16 && *width % 16 < 9)
2775 padding_p = 1;
2777 else if (strcmp (buffer, "char") == 0)
2778 match ();
2779 else
2780 goto failure;
2782 else
2783 goto failure;
2785 expect (XBM_TK_IDENT);
2786 expect ('[');
2787 expect (']');
2788 expect ('=');
2789 expect ('{');
2791 if (! x_check_image_size (0, *width, *height))
2793 if (!inhibit_image_error)
2794 image_error ("Image too large (%dx%d)",
2795 make_number (*width), make_number (*height));
2796 goto failure;
2798 bytes_per_line = (*width + 7) / 8 + padding_p;
2799 nbytes = bytes_per_line * *height;
2800 p = *data = xmalloc (nbytes);
2802 if (v10)
2804 for (i = 0; i < nbytes; i += 2)
2806 int val = value;
2807 expect (XBM_TK_NUMBER);
2809 *p++ = XBM_BIT_SHUFFLE (val);
2810 if (!padding_p || ((i + 2) % bytes_per_line))
2811 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2813 if (LA1 == ',' || LA1 == '}')
2814 match ();
2815 else
2816 goto failure;
2819 else
2821 for (i = 0; i < nbytes; ++i)
2823 int val = value;
2824 expect (XBM_TK_NUMBER);
2826 *p++ = XBM_BIT_SHUFFLE (val);
2828 if (LA1 == ',' || LA1 == '}')
2829 match ();
2830 else
2831 goto failure;
2835 success:
2836 return 1;
2838 failure:
2840 if (data && *data)
2842 xfree (*data);
2843 *data = NULL;
2845 return 0;
2847 #undef match
2848 #undef expect
2849 #undef expect_ident
2853 /* Load XBM image IMG which will be displayed on frame F from buffer
2854 CONTENTS. END is the end of the buffer. Value is true if
2855 successful. */
2857 static bool
2858 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2859 unsigned char *end)
2861 bool rc;
2862 char *data;
2863 bool success_p = 0;
2865 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2866 &data, 0);
2867 if (rc)
2869 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2870 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2871 bool non_default_colors = 0;
2872 Lisp_Object value;
2874 eassert (img->width > 0 && img->height > 0);
2876 /* Get foreground and background colors, maybe allocate colors. */
2877 value = image_spec_value (img->spec, QCforeground, NULL);
2878 if (!NILP (value))
2880 foreground = x_alloc_image_color (f, img, value, foreground);
2881 non_default_colors = 1;
2883 value = image_spec_value (img->spec, QCbackground, NULL);
2884 if (!NILP (value))
2886 background = x_alloc_image_color (f, img, value, background);
2887 img->background = background;
2888 img->background_valid = 1;
2889 non_default_colors = 1;
2892 Create_Pixmap_From_Bitmap_Data (f, img, data,
2893 foreground, background,
2894 non_default_colors);
2895 xfree (data);
2897 if (img->pixmap == NO_PIXMAP)
2899 x_clear_image (f, img);
2900 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2902 else
2903 success_p = 1;
2905 else
2906 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2908 return success_p;
2912 /* Value is true if DATA looks like an in-memory XBM file. */
2914 static bool
2915 xbm_file_p (Lisp_Object data)
2917 int w, h;
2918 return (STRINGP (data)
2919 && xbm_read_bitmap_data (NULL, SDATA (data),
2920 (SDATA (data) + SBYTES (data)),
2921 &w, &h, NULL, 1));
2925 /* Fill image IMG which is used on frame F with pixmap data. Value is
2926 true if successful. */
2928 static bool
2929 xbm_load (struct frame *f, struct image *img)
2931 bool success_p = 0;
2932 Lisp_Object file_name;
2934 eassert (xbm_image_p (img->spec));
2936 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2937 file_name = image_spec_value (img->spec, QCfile, NULL);
2938 if (STRINGP (file_name))
2940 Lisp_Object file;
2941 unsigned char *contents;
2942 ptrdiff_t size;
2944 file = x_find_image_file (file_name);
2945 if (!STRINGP (file))
2947 image_error ("Cannot find image file `%s'", file_name, Qnil);
2948 return 0;
2951 contents = slurp_file (SSDATA (file), &size);
2952 if (contents == NULL)
2954 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2955 return 0;
2958 success_p = xbm_load_image (f, img, contents, contents + size);
2959 xfree (contents);
2961 else
2963 struct image_keyword fmt[XBM_LAST];
2964 Lisp_Object data;
2965 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2966 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2967 bool non_default_colors = 0;
2968 char *bits;
2969 bool parsed_p;
2970 bool in_memory_file_p = 0;
2972 /* See if data looks like an in-memory XBM file. */
2973 data = image_spec_value (img->spec, QCdata, NULL);
2974 in_memory_file_p = xbm_file_p (data);
2976 /* Parse the image specification. */
2977 memcpy (fmt, xbm_format, sizeof fmt);
2978 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2979 eassert (parsed_p);
2981 /* Get specified width, and height. */
2982 if (!in_memory_file_p)
2984 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2985 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2986 eassert (img->width > 0 && img->height > 0);
2987 if (!check_image_size (f, img->width, img->height))
2989 image_error ("Invalid image size (see `max-image-size')",
2990 Qnil, Qnil);
2991 return 0;
2995 /* Get foreground and background colors, maybe allocate colors. */
2996 if (fmt[XBM_FOREGROUND].count
2997 && STRINGP (fmt[XBM_FOREGROUND].value))
2999 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3000 foreground);
3001 non_default_colors = 1;
3004 if (fmt[XBM_BACKGROUND].count
3005 && STRINGP (fmt[XBM_BACKGROUND].value))
3007 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3008 background);
3009 non_default_colors = 1;
3012 if (in_memory_file_p)
3013 success_p = xbm_load_image (f, img, SDATA (data),
3014 (SDATA (data)
3015 + SBYTES (data)));
3016 else
3018 if (VECTORP (data))
3020 int i;
3021 char *p;
3022 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3024 p = bits = alloca (nbytes * img->height);
3025 for (i = 0; i < img->height; ++i, p += nbytes)
3027 Lisp_Object line = AREF (data, i);
3028 if (STRINGP (line))
3029 memcpy (p, SDATA (line), nbytes);
3030 else
3031 memcpy (p, bool_vector_data (line), nbytes);
3034 else if (STRINGP (data))
3035 bits = SSDATA (data);
3036 else
3037 bits = (char *) bool_vector_data (data);
3039 #ifdef HAVE_NTGUI
3041 char *invertedBits;
3042 int nbytes, i;
3043 /* Windows mono bitmaps are reversed compared with X. */
3044 invertedBits = bits;
3045 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
3046 * img->height;
3047 bits = alloca (nbytes);
3048 for (i = 0; i < nbytes; i++)
3049 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3051 #endif
3052 /* Create the pixmap. */
3054 if (x_check_image_size (0, img->width, img->height))
3055 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3056 foreground, background,
3057 non_default_colors);
3058 else
3059 img->pixmap = NO_PIXMAP;
3061 if (img->pixmap)
3062 success_p = 1;
3063 else
3065 image_error ("Unable to create pixmap for XBM image `%s'",
3066 img->spec, Qnil);
3067 x_clear_image (f, img);
3072 return success_p;
3077 /***********************************************************************
3078 XPM images
3079 ***********************************************************************/
3081 #if defined (HAVE_XPM) || defined (HAVE_NS)
3083 static bool xpm_image_p (Lisp_Object object);
3084 static bool xpm_load (struct frame *f, struct image *img);
3086 #endif /* HAVE_XPM || HAVE_NS */
3088 #ifdef HAVE_XPM
3089 #ifdef HAVE_NTGUI
3090 /* Indicate to xpm.h that we don't have Xlib. */
3091 #define FOR_MSW
3092 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3093 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3094 #define XColor xpm_XColor
3095 #define XImage xpm_XImage
3096 #define Display xpm_Display
3097 #define PIXEL_ALREADY_TYPEDEFED
3098 #include "X11/xpm.h"
3099 #undef FOR_MSW
3100 #undef XColor
3101 #undef XImage
3102 #undef Display
3103 #undef PIXEL_ALREADY_TYPEDEFED
3104 #else
3105 #include "X11/xpm.h"
3106 #endif /* HAVE_NTGUI */
3107 #endif /* HAVE_XPM */
3109 #if defined (HAVE_XPM) || defined (HAVE_NS)
3110 /* The symbol `xpm' identifying XPM-format images. */
3112 static Lisp_Object Qxpm;
3114 /* Indices of image specification fields in xpm_format, below. */
3116 enum xpm_keyword_index
3118 XPM_TYPE,
3119 XPM_FILE,
3120 XPM_DATA,
3121 XPM_ASCENT,
3122 XPM_MARGIN,
3123 XPM_RELIEF,
3124 XPM_ALGORITHM,
3125 XPM_HEURISTIC_MASK,
3126 XPM_MASK,
3127 XPM_COLOR_SYMBOLS,
3128 XPM_BACKGROUND,
3129 XPM_LAST
3132 /* Vector of image_keyword structures describing the format
3133 of valid XPM image specifications. */
3135 static const struct image_keyword xpm_format[XPM_LAST] =
3137 {":type", IMAGE_SYMBOL_VALUE, 1},
3138 {":file", IMAGE_STRING_VALUE, 0},
3139 {":data", IMAGE_STRING_VALUE, 0},
3140 {":ascent", IMAGE_ASCENT_VALUE, 0},
3141 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3142 {":relief", IMAGE_INTEGER_VALUE, 0},
3143 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3144 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3145 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3146 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3147 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3150 #if defined HAVE_NTGUI && defined WINDOWSNT
3151 static bool init_xpm_functions (void);
3152 #else
3153 #define init_xpm_functions NULL
3154 #endif
3156 /* Structure describing the image type XPM. */
3158 static struct image_type xpm_type =
3160 &Qxpm,
3161 xpm_image_p,
3162 xpm_load,
3163 x_clear_image,
3164 init_xpm_functions,
3165 NULL
3168 #ifdef HAVE_X_WINDOWS
3170 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3171 functions for allocating image colors. Our own functions handle
3172 color allocation failures more gracefully than the ones on the XPM
3173 lib. */
3175 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3176 #define ALLOC_XPM_COLORS
3177 #endif
3178 #endif /* HAVE_X_WINDOWS */
3180 #ifdef ALLOC_XPM_COLORS
3182 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3183 XColor *, int);
3185 /* An entry in a hash table used to cache color definitions of named
3186 colors. This cache is necessary to speed up XPM image loading in
3187 case we do color allocations ourselves. Without it, we would need
3188 a call to XParseColor per pixel in the image. */
3190 struct xpm_cached_color
3192 /* Next in collision chain. */
3193 struct xpm_cached_color *next;
3195 /* Color definition (RGB and pixel color). */
3196 XColor color;
3198 /* Color name. */
3199 char name[FLEXIBLE_ARRAY_MEMBER];
3202 /* The hash table used for the color cache, and its bucket vector
3203 size. */
3205 #define XPM_COLOR_CACHE_BUCKETS 1001
3206 static struct xpm_cached_color **xpm_color_cache;
3208 /* Initialize the color cache. */
3210 static void
3211 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3213 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3214 xpm_color_cache = xzalloc (nbytes);
3215 init_color_table ();
3217 if (attrs->valuemask & XpmColorSymbols)
3219 int i;
3220 XColor color;
3222 for (i = 0; i < attrs->numsymbols; ++i)
3223 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3224 attrs->colorsymbols[i].value, &color))
3226 color.pixel = lookup_rgb_color (f, color.red, color.green,
3227 color.blue);
3228 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3233 /* Free the color cache. */
3235 static void
3236 xpm_free_color_cache (void)
3238 struct xpm_cached_color *p, *next;
3239 int i;
3241 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3242 for (p = xpm_color_cache[i]; p; p = next)
3244 next = p->next;
3245 xfree (p);
3248 xfree (xpm_color_cache);
3249 xpm_color_cache = NULL;
3250 free_color_table ();
3253 /* Return the bucket index for color named COLOR_NAME in the color
3254 cache. */
3256 static int
3257 xpm_color_bucket (char *color_name)
3259 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3260 return hash % XPM_COLOR_CACHE_BUCKETS;
3264 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3265 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3266 entry added. */
3268 static struct xpm_cached_color *
3269 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3271 size_t nbytes;
3272 struct xpm_cached_color *p;
3274 if (bucket < 0)
3275 bucket = xpm_color_bucket (color_name);
3277 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3278 p = xmalloc (nbytes);
3279 strcpy (p->name, color_name);
3280 p->color = *color;
3281 p->next = xpm_color_cache[bucket];
3282 xpm_color_cache[bucket] = p;
3283 return p;
3286 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3287 return the cached definition in *COLOR. Otherwise, make a new
3288 entry in the cache and allocate the color. Value is false if color
3289 allocation failed. */
3291 static bool
3292 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3294 struct xpm_cached_color *p;
3295 int h = xpm_color_bucket (color_name);
3297 for (p = xpm_color_cache[h]; p; p = p->next)
3298 if (strcmp (p->name, color_name) == 0)
3299 break;
3301 if (p != NULL)
3302 *color = p->color;
3303 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3304 color_name, color))
3306 color->pixel = lookup_rgb_color (f, color->red, color->green,
3307 color->blue);
3308 p = xpm_cache_color (f, color_name, color, h);
3310 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3311 with transparency, and it's useful. */
3312 else if (strcmp ("opaque", color_name) == 0)
3314 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3315 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3316 p = xpm_cache_color (f, color_name, color, h);
3319 return p != NULL;
3323 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3324 CLOSURE is a pointer to the frame on which we allocate the
3325 color. Return in *COLOR the allocated color. Value is non-zero
3326 if successful. */
3328 static int
3329 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3330 void *closure)
3332 return xpm_lookup_color (closure, color_name, color);
3336 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3337 is a pointer to the frame on which we allocate the color. Value is
3338 non-zero if successful. */
3340 static int
3341 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3343 return 1;
3346 #endif /* ALLOC_XPM_COLORS */
3349 #ifdef WINDOWSNT
3351 /* XPM library details. */
3353 DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
3354 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3355 xpm_XImage **, XpmAttributes *));
3356 DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3357 xpm_XImage **, XpmAttributes *));
3358 DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
3360 static bool
3361 init_xpm_functions (void)
3363 HMODULE library;
3365 if (!(library = w32_delayed_load (Qxpm)))
3366 return 0;
3368 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3369 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3370 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3371 LOAD_IMGLIB_FN (library, XImageFree);
3372 return 1;
3375 #endif /* WINDOWSNT */
3377 #if defined HAVE_NTGUI && !defined WINDOWSNT
3378 /* Glue for code below */
3379 #define fn_XpmReadFileToImage XpmReadFileToImage
3380 #define fn_XpmCreateImageFromBuffer XpmCreateImageFromBuffer
3381 #define fn_XImageFree XImageFree
3382 #define fn_XpmFreeAttributes XpmFreeAttributes
3383 #endif /* HAVE_NTGUI && !WINDOWSNT */
3385 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3386 for XPM images. Such a list must consist of conses whose car and
3387 cdr are strings. */
3389 static bool
3390 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3392 while (CONSP (color_symbols))
3394 Lisp_Object sym = XCAR (color_symbols);
3395 if (!CONSP (sym)
3396 || !STRINGP (XCAR (sym))
3397 || !STRINGP (XCDR (sym)))
3398 break;
3399 color_symbols = XCDR (color_symbols);
3402 return NILP (color_symbols);
3406 /* Value is true if OBJECT is a valid XPM image specification. */
3408 static bool
3409 xpm_image_p (Lisp_Object object)
3411 struct image_keyword fmt[XPM_LAST];
3412 memcpy (fmt, xpm_format, sizeof fmt);
3413 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3414 /* Either `:file' or `:data' must be present. */
3415 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3416 /* Either no `:color-symbols' or it's a list of conses
3417 whose car and cdr are strings. */
3418 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3419 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3422 #endif /* HAVE_XPM || HAVE_NS */
3424 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3425 ptrdiff_t
3426 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3428 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3429 ptrdiff_t id;
3430 int rc;
3431 XpmAttributes attrs;
3432 Pixmap bitmap, mask;
3434 memset (&attrs, 0, sizeof attrs);
3436 attrs.visual = FRAME_X_VISUAL (f);
3437 attrs.colormap = FRAME_X_COLORMAP (f);
3438 attrs.valuemask |= XpmVisual;
3439 attrs.valuemask |= XpmColormap;
3441 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3442 (char **) bits, &bitmap, &mask, &attrs);
3443 if (rc != XpmSuccess)
3445 XpmFreeAttributes (&attrs);
3446 return -1;
3449 id = x_allocate_bitmap_record (f);
3450 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3451 dpyinfo->bitmaps[id - 1].have_mask = true;
3452 dpyinfo->bitmaps[id - 1].mask = mask;
3453 dpyinfo->bitmaps[id - 1].file = NULL;
3454 dpyinfo->bitmaps[id - 1].height = attrs.height;
3455 dpyinfo->bitmaps[id - 1].width = attrs.width;
3456 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3457 dpyinfo->bitmaps[id - 1].refcount = 1;
3459 XpmFreeAttributes (&attrs);
3460 return id;
3462 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3464 /* Load image IMG which will be displayed on frame F. Value is
3465 true if successful. */
3467 #ifdef HAVE_XPM
3469 static bool
3470 xpm_load (struct frame *f, struct image *img)
3472 int rc;
3473 XpmAttributes attrs;
3474 Lisp_Object specified_file, color_symbols;
3475 #ifdef HAVE_NTGUI
3476 HDC hdc;
3477 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3478 #endif /* HAVE_NTGUI */
3480 /* Configure the XPM lib. Use the visual of frame F. Allocate
3481 close colors. Return colors allocated. */
3482 memset (&attrs, 0, sizeof attrs);
3484 #ifndef HAVE_NTGUI
3485 attrs.visual = FRAME_X_VISUAL (f);
3486 attrs.colormap = FRAME_X_COLORMAP (f);
3487 attrs.valuemask |= XpmVisual;
3488 attrs.valuemask |= XpmColormap;
3489 #endif /* HAVE_NTGUI */
3491 #ifdef ALLOC_XPM_COLORS
3492 /* Allocate colors with our own functions which handle
3493 failing color allocation more gracefully. */
3494 attrs.color_closure = f;
3495 attrs.alloc_color = xpm_alloc_color;
3496 attrs.free_colors = xpm_free_colors;
3497 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3498 #else /* not ALLOC_XPM_COLORS */
3499 /* Let the XPM lib allocate colors. */
3500 attrs.valuemask |= XpmReturnAllocPixels;
3501 #ifdef XpmAllocCloseColors
3502 attrs.alloc_close_colors = 1;
3503 attrs.valuemask |= XpmAllocCloseColors;
3504 #else /* not XpmAllocCloseColors */
3505 attrs.closeness = 600;
3506 attrs.valuemask |= XpmCloseness;
3507 #endif /* not XpmAllocCloseColors */
3508 #endif /* ALLOC_XPM_COLORS */
3510 /* If image specification contains symbolic color definitions, add
3511 these to `attrs'. */
3512 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3513 if (CONSP (color_symbols))
3515 Lisp_Object tail;
3516 XpmColorSymbol *xpm_syms;
3517 int i, size;
3519 attrs.valuemask |= XpmColorSymbols;
3521 /* Count number of symbols. */
3522 attrs.numsymbols = 0;
3523 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3524 ++attrs.numsymbols;
3526 /* Allocate an XpmColorSymbol array. */
3527 size = attrs.numsymbols * sizeof *xpm_syms;
3528 xpm_syms = alloca (size);
3529 memset (xpm_syms, 0, size);
3530 attrs.colorsymbols = xpm_syms;
3532 /* Fill the color symbol array. */
3533 for (tail = color_symbols, i = 0;
3534 CONSP (tail);
3535 ++i, tail = XCDR (tail))
3537 Lisp_Object name;
3538 Lisp_Object color;
3539 char *empty_string = (char *) "";
3541 if (!CONSP (XCAR (tail)))
3543 xpm_syms[i].name = empty_string;
3544 xpm_syms[i].value = empty_string;
3545 continue;
3547 name = XCAR (XCAR (tail));
3548 color = XCDR (XCAR (tail));
3549 if (STRINGP (name))
3551 xpm_syms[i].name = alloca (SCHARS (name) + 1);
3552 strcpy (xpm_syms[i].name, SSDATA (name));
3554 else
3555 xpm_syms[i].name = empty_string;
3556 if (STRINGP (color))
3558 xpm_syms[i].value = alloca (SCHARS (color) + 1);
3559 strcpy (xpm_syms[i].value, SSDATA (color));
3561 else
3562 xpm_syms[i].value = empty_string;
3566 /* Create a pixmap for the image, either from a file, or from a
3567 string buffer containing data in the same format as an XPM file. */
3568 #ifdef ALLOC_XPM_COLORS
3569 xpm_init_color_cache (f, &attrs);
3570 #endif
3572 specified_file = image_spec_value (img->spec, QCfile, NULL);
3574 #ifdef HAVE_NTGUI
3576 HDC frame_dc = get_frame_dc (f);
3577 hdc = CreateCompatibleDC (frame_dc);
3578 release_frame_dc (f, frame_dc);
3580 #endif /* HAVE_NTGUI */
3582 if (STRINGP (specified_file))
3584 Lisp_Object file = x_find_image_file (specified_file);
3585 if (!STRINGP (file))
3587 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3588 #ifdef ALLOC_XPM_COLORS
3589 xpm_free_color_cache ();
3590 #endif
3591 return 0;
3594 #ifdef HAVE_NTGUI
3595 #ifdef WINDOWSNT
3596 /* FILE is encoded in UTF-8, but image libraries on Windows
3597 support neither UTF-8 nor UTF-16 encoded file names. So we
3598 need to re-encode it in ANSI. */
3599 file = ansi_encode_filename (file);
3600 #endif
3601 /* XpmReadFileToPixmap is not available in the Windows port of
3602 libxpm. But XpmReadFileToImage almost does what we want. */
3603 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3604 &xpm_image, &xpm_mask,
3605 &attrs);
3606 #else
3607 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3608 &img->ximg, &img->mask_img,
3609 &attrs);
3610 #endif /* HAVE_NTGUI */
3612 else
3614 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3615 if (!STRINGP (buffer))
3617 image_error ("Invalid image data `%s'", buffer, Qnil);
3618 #ifdef ALLOC_XPM_COLORS
3619 xpm_free_color_cache ();
3620 #endif
3621 return 0;
3623 #ifdef HAVE_NTGUI
3624 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3625 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3626 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3627 &xpm_image, &xpm_mask,
3628 &attrs);
3629 #else
3630 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3631 &img->ximg, &img->mask_img,
3632 &attrs);
3633 #endif /* HAVE_NTGUI */
3636 #ifdef HAVE_X_WINDOWS
3637 if (rc == XpmSuccess)
3639 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3640 img->ximg->width, img->ximg->height,
3641 img->ximg->depth);
3642 if (img->pixmap == NO_PIXMAP)
3644 x_clear_image (f, img);
3645 rc = XpmNoMemory;
3647 else if (img->mask_img)
3649 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3650 img->mask_img->width,
3651 img->mask_img->height,
3652 img->mask_img->depth);
3653 if (img->mask == NO_PIXMAP)
3655 x_clear_image (f, img);
3656 rc = XpmNoMemory;
3660 #endif
3662 if (rc == XpmSuccess)
3664 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3665 img->colors = colors_in_color_table (&img->ncolors);
3666 #else /* not ALLOC_XPM_COLORS */
3667 int i;
3669 #ifdef HAVE_NTGUI
3670 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3671 plus some duplicate attributes. */
3672 if (xpm_image && xpm_image->bitmap)
3674 img->pixmap = xpm_image->bitmap;
3675 /* XImageFree in libXpm frees XImage struct without destroying
3676 the bitmap, which is what we want. */
3677 fn_XImageFree (xpm_image);
3679 if (xpm_mask && xpm_mask->bitmap)
3681 /* The mask appears to be inverted compared with what we expect.
3682 TODO: invert our expectations. See other places where we
3683 have to invert bits because our idea of masks is backwards. */
3684 HGDIOBJ old_obj;
3685 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3687 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3688 SelectObject (hdc, old_obj);
3690 img->mask = xpm_mask->bitmap;
3691 fn_XImageFree (xpm_mask);
3692 DeleteDC (hdc);
3695 DeleteDC (hdc);
3696 #endif /* HAVE_NTGUI */
3698 /* Remember allocated colors. */
3699 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3700 img->ncolors = attrs.nalloc_pixels;
3701 for (i = 0; i < attrs.nalloc_pixels; ++i)
3703 img->colors[i] = attrs.alloc_pixels[i];
3704 #ifdef DEBUG_X_COLORS
3705 register_color (img->colors[i]);
3706 #endif
3708 #endif /* not ALLOC_XPM_COLORS */
3710 img->width = attrs.width;
3711 img->height = attrs.height;
3712 eassert (img->width > 0 && img->height > 0);
3714 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3715 #ifdef HAVE_NTGUI
3716 fn_XpmFreeAttributes (&attrs);
3717 #else
3718 XpmFreeAttributes (&attrs);
3719 #endif /* HAVE_NTGUI */
3721 #ifdef HAVE_X_WINDOWS
3722 /* Maybe fill in the background field while we have ximg handy. */
3723 IMAGE_BACKGROUND (img, f, img->ximg);
3724 if (img->mask_img)
3725 /* Fill in the background_transparent field while we have the
3726 mask handy. */
3727 image_background_transparent (img, f, img->mask_img);
3728 #endif
3730 else
3732 #ifdef HAVE_NTGUI
3733 DeleteDC (hdc);
3734 #endif /* HAVE_NTGUI */
3736 switch (rc)
3738 case XpmOpenFailed:
3739 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3740 break;
3742 case XpmFileInvalid:
3743 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3744 break;
3746 case XpmNoMemory:
3747 image_error ("Out of memory (%s)", img->spec, Qnil);
3748 break;
3750 case XpmColorFailed:
3751 image_error ("Color allocation error (%s)", img->spec, Qnil);
3752 break;
3754 default:
3755 image_error ("Unknown error (%s)", img->spec, Qnil);
3756 break;
3760 #ifdef ALLOC_XPM_COLORS
3761 xpm_free_color_cache ();
3762 #endif
3763 return rc == XpmSuccess;
3766 #endif /* HAVE_XPM */
3768 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3770 /* XPM support functions for NS where libxpm is not available.
3771 Only XPM version 3 (without any extensions) is supported. */
3773 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3774 int, Lisp_Object);
3775 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3776 const unsigned char *, int);
3777 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3778 int, Lisp_Object);
3779 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3780 const unsigned char *, int);
3782 /* Tokens returned from xpm_scan. */
3784 enum xpm_token
3786 XPM_TK_IDENT = 256,
3787 XPM_TK_STRING,
3788 XPM_TK_EOF
3791 /* Scan an XPM data and return a character (< 256) or a token defined
3792 by enum xpm_token above. *S and END are the start (inclusive) and
3793 the end (exclusive) addresses of the data, respectively. Advance
3794 *S while scanning. If token is either XPM_TK_IDENT or
3795 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3796 length of the corresponding token, respectively. */
3798 static int
3799 xpm_scan (const unsigned char **s,
3800 const unsigned char *end,
3801 const unsigned char **beg,
3802 ptrdiff_t *len)
3804 int c;
3806 while (*s < end)
3808 /* Skip white-space. */
3809 while (*s < end && (c = *(*s)++, c_isspace (c)))
3812 /* gnus-pointer.xpm uses '-' in its identifier.
3813 sb-dir-plus.xpm uses '+' in its identifier. */
3814 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3816 *beg = *s - 1;
3817 while (*s < end
3818 && (c = **s, c_isalnum (c)
3819 || c == '_' || c == '-' || c == '+'))
3820 ++*s;
3821 *len = *s - *beg;
3822 return XPM_TK_IDENT;
3824 else if (c == '"')
3826 *beg = *s;
3827 while (*s < end && **s != '"')
3828 ++*s;
3829 *len = *s - *beg;
3830 if (*s < end)
3831 ++*s;
3832 return XPM_TK_STRING;
3834 else if (c == '/')
3836 if (*s < end && **s == '*')
3838 /* C-style comment. */
3839 ++*s;
3842 while (*s < end && *(*s)++ != '*')
3845 while (*s < end && **s != '/');
3846 if (*s < end)
3847 ++*s;
3849 else
3850 return c;
3852 else
3853 return c;
3856 return XPM_TK_EOF;
3859 /* Functions for color table lookup in XPM data. A key is a string
3860 specifying the color of each pixel in XPM data. A value is either
3861 an integer that specifies a pixel color, Qt that specifies
3862 transparency, or Qnil for the unspecified color. If the length of
3863 the key string is one, a vector is used as a table. Otherwise, a
3864 hash table is used. */
3866 static Lisp_Object
3867 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3868 const unsigned char *,
3869 int,
3870 Lisp_Object),
3871 Lisp_Object (**get_func) (Lisp_Object,
3872 const unsigned char *,
3873 int))
3875 *put_func = xpm_put_color_table_v;
3876 *get_func = xpm_get_color_table_v;
3877 return Fmake_vector (make_number (256), Qnil);
3880 static void
3881 xpm_put_color_table_v (Lisp_Object color_table,
3882 const unsigned char *chars_start,
3883 int chars_len,
3884 Lisp_Object color)
3886 ASET (color_table, *chars_start, color);
3889 static Lisp_Object
3890 xpm_get_color_table_v (Lisp_Object color_table,
3891 const unsigned char *chars_start,
3892 int chars_len)
3894 return AREF (color_table, *chars_start);
3897 static Lisp_Object
3898 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3899 const unsigned char *,
3900 int,
3901 Lisp_Object),
3902 Lisp_Object (**get_func) (Lisp_Object,
3903 const unsigned char *,
3904 int))
3906 *put_func = xpm_put_color_table_h;
3907 *get_func = xpm_get_color_table_h;
3908 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
3909 make_float (DEFAULT_REHASH_SIZE),
3910 make_float (DEFAULT_REHASH_THRESHOLD),
3911 Qnil);
3914 static void
3915 xpm_put_color_table_h (Lisp_Object color_table,
3916 const unsigned char *chars_start,
3917 int chars_len,
3918 Lisp_Object color)
3920 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3921 EMACS_UINT hash_code;
3922 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3924 hash_lookup (table, chars, &hash_code);
3925 hash_put (table, chars, color, hash_code);
3928 static Lisp_Object
3929 xpm_get_color_table_h (Lisp_Object color_table,
3930 const unsigned char *chars_start,
3931 int chars_len)
3933 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3934 ptrdiff_t i =
3935 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
3937 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3940 enum xpm_color_key {
3941 XPM_COLOR_KEY_S,
3942 XPM_COLOR_KEY_M,
3943 XPM_COLOR_KEY_G4,
3944 XPM_COLOR_KEY_G,
3945 XPM_COLOR_KEY_C
3948 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3950 static int
3951 xpm_str_to_color_key (const char *s)
3953 int i;
3955 for (i = 0;
3956 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3957 i++)
3958 if (strcmp (xpm_color_key_strings[i], s) == 0)
3959 return i;
3960 return -1;
3963 static bool
3964 xpm_load_image (struct frame *f,
3965 struct image *img,
3966 const unsigned char *contents,
3967 const unsigned char *end)
3969 const unsigned char *s = contents, *beg, *str;
3970 unsigned char buffer[BUFSIZ];
3971 int width, height, x, y;
3972 int num_colors, chars_per_pixel;
3973 ptrdiff_t len;
3974 int LA1;
3975 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3976 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3977 Lisp_Object frame, color_symbols, color_table;
3978 int best_key;
3979 bool have_mask = false;
3980 XImagePtr ximg = NULL, mask_img = NULL;
3982 #define match() \
3983 LA1 = xpm_scan (&s, end, &beg, &len)
3985 #define expect(TOKEN) \
3986 do \
3988 if (LA1 != (TOKEN)) \
3989 goto failure; \
3990 match (); \
3992 while (0)
3994 #define expect_ident(IDENT) \
3995 if (LA1 == XPM_TK_IDENT \
3996 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3997 match (); \
3998 else \
3999 goto failure
4001 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4002 goto failure;
4003 s += 9;
4004 match ();
4005 expect_ident ("static");
4006 expect_ident ("char");
4007 expect ('*');
4008 expect (XPM_TK_IDENT);
4009 expect ('[');
4010 expect (']');
4011 expect ('=');
4012 expect ('{');
4013 expect (XPM_TK_STRING);
4014 if (len >= BUFSIZ)
4015 goto failure;
4016 memcpy (buffer, beg, len);
4017 buffer[len] = '\0';
4018 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4019 &num_colors, &chars_per_pixel) != 4
4020 || width <= 0 || height <= 0
4021 || num_colors <= 0 || chars_per_pixel <= 0)
4022 goto failure;
4024 if (!check_image_size (f, width, height))
4026 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
4027 goto failure;
4030 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4031 #ifndef HAVE_NS
4032 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4033 &mask_img, 1)
4034 #endif
4037 image_error ("Image too large", Qnil, Qnil);
4038 goto failure;
4041 expect (',');
4043 XSETFRAME (frame, f);
4044 if (!NILP (Fxw_display_color_p (frame)))
4045 best_key = XPM_COLOR_KEY_C;
4046 else if (!NILP (Fx_display_grayscale_p (frame)))
4047 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4048 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4049 else
4050 best_key = XPM_COLOR_KEY_M;
4052 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4053 if (chars_per_pixel == 1)
4054 color_table = xpm_make_color_table_v (&put_color_table,
4055 &get_color_table);
4056 else
4057 color_table = xpm_make_color_table_h (&put_color_table,
4058 &get_color_table);
4060 while (num_colors-- > 0)
4062 char *color, *max_color;
4063 int key, next_key, max_key = 0;
4064 Lisp_Object symbol_color = Qnil, color_val;
4065 XColor cdef;
4067 expect (XPM_TK_STRING);
4068 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4069 goto failure;
4070 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4071 buffer[len - chars_per_pixel] = '\0';
4073 str = strtok (buffer, " \t");
4074 if (str == NULL)
4075 goto failure;
4076 key = xpm_str_to_color_key (str);
4077 if (key < 0)
4078 goto failure;
4081 color = strtok (NULL, " \t");
4082 if (color == NULL)
4083 goto failure;
4085 while ((str = strtok (NULL, " \t")) != NULL)
4087 next_key = xpm_str_to_color_key (str);
4088 if (next_key >= 0)
4089 break;
4090 color[strlen (color)] = ' ';
4093 if (key == XPM_COLOR_KEY_S)
4095 if (NILP (symbol_color))
4096 symbol_color = build_string (color);
4098 else if (max_key < key && key <= best_key)
4100 max_key = key;
4101 max_color = color;
4103 key = next_key;
4105 while (str);
4107 color_val = Qnil;
4108 if (!NILP (color_symbols) && !NILP (symbol_color))
4110 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4112 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4114 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4115 color_val = Qt;
4116 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4117 &cdef, 0))
4118 color_val = make_number (cdef.pixel);
4121 if (NILP (color_val) && max_key > 0)
4123 if (xstrcasecmp (max_color, "None") == 0)
4124 color_val = Qt;
4125 else if (x_defined_color (f, max_color, &cdef, 0))
4126 color_val = make_number (cdef.pixel);
4128 if (!NILP (color_val))
4129 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4131 expect (',');
4134 for (y = 0; y < height; y++)
4136 expect (XPM_TK_STRING);
4137 str = beg;
4138 if (len < width * chars_per_pixel)
4139 goto failure;
4140 for (x = 0; x < width; x++, str += chars_per_pixel)
4142 Lisp_Object color_val =
4143 (*get_color_table) (color_table, str, chars_per_pixel);
4145 XPutPixel (ximg, x, y,
4146 (INTEGERP (color_val) ? XINT (color_val)
4147 : FRAME_FOREGROUND_PIXEL (f)));
4148 #ifndef HAVE_NS
4149 XPutPixel (mask_img, x, y,
4150 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4151 : (have_mask = true, PIX_MASK_RETAIN)));
4152 #else
4153 if (EQ (color_val, Qt))
4154 ns_set_alpha (ximg, x, y, 0);
4155 #endif
4157 if (y + 1 < height)
4158 expect (',');
4161 img->width = width;
4162 img->height = height;
4164 /* Maybe fill in the background field while we have ximg handy. */
4165 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4166 IMAGE_BACKGROUND (img, f, ximg);
4168 image_put_x_image (f, img, ximg, 0);
4169 #ifndef HAVE_NS
4170 if (have_mask)
4172 /* Fill in the background_transparent field while we have the
4173 mask handy. */
4174 image_background_transparent (img, f, mask_img);
4176 image_put_x_image (f, img, mask_img, 1);
4178 else
4180 x_destroy_x_image (mask_img);
4181 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4183 #endif
4184 return 1;
4186 failure:
4187 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4188 x_destroy_x_image (ximg);
4189 x_destroy_x_image (mask_img);
4190 x_clear_image (f, img);
4191 return 0;
4193 #undef match
4194 #undef expect
4195 #undef expect_ident
4198 static bool
4199 xpm_load (struct frame *f,
4200 struct image *img)
4202 bool success_p = 0;
4203 Lisp_Object file_name;
4205 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4206 file_name = image_spec_value (img->spec, QCfile, NULL);
4207 if (STRINGP (file_name))
4209 Lisp_Object file;
4210 unsigned char *contents;
4211 ptrdiff_t size;
4213 file = x_find_image_file (file_name);
4214 if (!STRINGP (file))
4216 image_error ("Cannot find image file `%s'", file_name, Qnil);
4217 return 0;
4220 contents = slurp_file (SSDATA (file), &size);
4221 if (contents == NULL)
4223 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4224 return 0;
4227 success_p = xpm_load_image (f, img, contents, contents + size);
4228 xfree (contents);
4230 else
4232 Lisp_Object data;
4234 data = image_spec_value (img->spec, QCdata, NULL);
4235 if (!STRINGP (data))
4237 image_error ("Invalid image data `%s'", data, Qnil);
4238 return 0;
4240 success_p = xpm_load_image (f, img, SDATA (data),
4241 SDATA (data) + SBYTES (data));
4244 return success_p;
4247 #endif /* HAVE_NS && !HAVE_XPM */
4251 /***********************************************************************
4252 Color table
4253 ***********************************************************************/
4255 #ifdef COLOR_TABLE_SUPPORT
4257 /* An entry in the color table mapping an RGB color to a pixel color. */
4259 struct ct_color
4261 int r, g, b;
4262 unsigned long pixel;
4264 /* Next in color table collision list. */
4265 struct ct_color *next;
4268 /* The bucket vector size to use. Must be prime. */
4270 #define CT_SIZE 101
4272 /* Value is a hash of the RGB color given by R, G, and B. */
4274 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4276 /* The color hash table. */
4278 static struct ct_color **ct_table;
4280 /* Number of entries in the color table. */
4282 static int ct_colors_allocated;
4283 enum
4285 ct_colors_allocated_max =
4286 min (INT_MAX,
4287 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4290 /* Initialize the color table. */
4292 static void
4293 init_color_table (void)
4295 int size = CT_SIZE * sizeof (*ct_table);
4296 ct_table = xzalloc (size);
4297 ct_colors_allocated = 0;
4301 /* Free memory associated with the color table. */
4303 static void
4304 free_color_table (void)
4306 int i;
4307 struct ct_color *p, *next;
4309 for (i = 0; i < CT_SIZE; ++i)
4310 for (p = ct_table[i]; p; p = next)
4312 next = p->next;
4313 xfree (p);
4316 xfree (ct_table);
4317 ct_table = NULL;
4321 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4322 entry for that color already is in the color table, return the
4323 pixel color of that entry. Otherwise, allocate a new color for R,
4324 G, B, and make an entry in the color table. */
4326 static unsigned long
4327 lookup_rgb_color (struct frame *f, int r, int g, int b)
4329 unsigned hash = CT_HASH_RGB (r, g, b);
4330 int i = hash % CT_SIZE;
4331 struct ct_color *p;
4332 Display_Info *dpyinfo;
4334 /* Handle TrueColor visuals specially, which improves performance by
4335 two orders of magnitude. Freeing colors on TrueColor visuals is
4336 a nop, and pixel colors specify RGB values directly. See also
4337 the Xlib spec, chapter 3.1. */
4338 dpyinfo = FRAME_DISPLAY_INFO (f);
4339 if (dpyinfo->red_bits > 0)
4341 unsigned long pr, pg, pb;
4343 /* Apply gamma-correction like normal color allocation does. */
4344 if (f->gamma)
4346 XColor color;
4347 color.red = r, color.green = g, color.blue = b;
4348 gamma_correct (f, &color);
4349 r = color.red, g = color.green, b = color.blue;
4352 /* Scale down RGB values to the visual's bits per RGB, and shift
4353 them to the right position in the pixel color. Note that the
4354 original RGB values are 16-bit values, as usual in X. */
4355 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4356 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4357 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4359 /* Assemble the pixel color. */
4360 return pr | pg | pb;
4363 for (p = ct_table[i]; p; p = p->next)
4364 if (p->r == r && p->g == g && p->b == b)
4365 break;
4367 if (p == NULL)
4370 #ifdef HAVE_X_WINDOWS
4371 XColor color;
4372 Colormap cmap;
4373 bool rc;
4374 #else
4375 COLORREF color;
4376 #endif
4378 if (ct_colors_allocated_max <= ct_colors_allocated)
4379 return FRAME_FOREGROUND_PIXEL (f);
4381 #ifdef HAVE_X_WINDOWS
4382 color.red = r;
4383 color.green = g;
4384 color.blue = b;
4386 cmap = FRAME_X_COLORMAP (f);
4387 rc = x_alloc_nearest_color (f, cmap, &color);
4388 if (rc)
4390 ++ct_colors_allocated;
4391 p = xmalloc (sizeof *p);
4392 p->r = r;
4393 p->g = g;
4394 p->b = b;
4395 p->pixel = color.pixel;
4396 p->next = ct_table[i];
4397 ct_table[i] = p;
4399 else
4400 return FRAME_FOREGROUND_PIXEL (f);
4402 #else
4403 #ifdef HAVE_NTGUI
4404 color = PALETTERGB (r, g, b);
4405 #else
4406 color = RGB_TO_ULONG (r, g, b);
4407 #endif /* HAVE_NTGUI */
4408 ++ct_colors_allocated;
4409 p = xmalloc (sizeof *p);
4410 p->r = r;
4411 p->g = g;
4412 p->b = b;
4413 p->pixel = color;
4414 p->next = ct_table[i];
4415 ct_table[i] = p;
4416 #endif /* HAVE_X_WINDOWS */
4420 return p->pixel;
4424 /* Look up pixel color PIXEL which is used on frame F in the color
4425 table. If not already present, allocate it. Value is PIXEL. */
4427 static unsigned long
4428 lookup_pixel_color (struct frame *f, unsigned long pixel)
4430 int i = pixel % CT_SIZE;
4431 struct ct_color *p;
4433 for (p = ct_table[i]; p; p = p->next)
4434 if (p->pixel == pixel)
4435 break;
4437 if (p == NULL)
4439 XColor color;
4440 Colormap cmap;
4441 bool rc;
4443 if (ct_colors_allocated_max <= ct_colors_allocated)
4444 return FRAME_FOREGROUND_PIXEL (f);
4446 #ifdef HAVE_X_WINDOWS
4447 cmap = FRAME_X_COLORMAP (f);
4448 color.pixel = pixel;
4449 x_query_color (f, &color);
4450 rc = x_alloc_nearest_color (f, cmap, &color);
4451 #else
4452 block_input ();
4453 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4454 color.pixel = pixel;
4455 XQueryColor (NULL, cmap, &color);
4456 rc = x_alloc_nearest_color (f, cmap, &color);
4457 unblock_input ();
4458 #endif /* HAVE_X_WINDOWS */
4460 if (rc)
4462 ++ct_colors_allocated;
4464 p = xmalloc (sizeof *p);
4465 p->r = color.red;
4466 p->g = color.green;
4467 p->b = color.blue;
4468 p->pixel = pixel;
4469 p->next = ct_table[i];
4470 ct_table[i] = p;
4472 else
4473 return FRAME_FOREGROUND_PIXEL (f);
4475 return p->pixel;
4479 /* Value is a vector of all pixel colors contained in the color table,
4480 allocated via xmalloc. Set *N to the number of colors. */
4482 static unsigned long *
4483 colors_in_color_table (int *n)
4485 int i, j;
4486 struct ct_color *p;
4487 unsigned long *colors;
4489 if (ct_colors_allocated == 0)
4491 *n = 0;
4492 colors = NULL;
4494 else
4496 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4497 *n = ct_colors_allocated;
4499 for (i = j = 0; i < CT_SIZE; ++i)
4500 for (p = ct_table[i]; p; p = p->next)
4501 colors[j++] = p->pixel;
4504 return colors;
4507 #else /* COLOR_TABLE_SUPPORT */
4509 static unsigned long
4510 lookup_rgb_color (struct frame *f, int r, int g, int b)
4512 unsigned long pixel;
4514 #ifdef HAVE_NTGUI
4515 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4516 #endif /* HAVE_NTGUI */
4518 #ifdef HAVE_NS
4519 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4520 #endif /* HAVE_NS */
4521 return pixel;
4524 static void
4525 init_color_table (void)
4528 #endif /* COLOR_TABLE_SUPPORT */
4531 /***********************************************************************
4532 Algorithms
4533 ***********************************************************************/
4535 /* Edge detection matrices for different edge-detection
4536 strategies. */
4538 static int emboss_matrix[9] = {
4539 /* x - 1 x x + 1 */
4540 2, -1, 0, /* y - 1 */
4541 -1, 0, 1, /* y */
4542 0, 1, -2 /* y + 1 */
4545 static int laplace_matrix[9] = {
4546 /* x - 1 x x + 1 */
4547 1, 0, 0, /* y - 1 */
4548 0, 0, 0, /* y */
4549 0, 0, -1 /* y + 1 */
4552 /* Value is the intensity of the color whose red/green/blue values
4553 are R, G, and B. */
4555 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4558 /* On frame F, return an array of XColor structures describing image
4559 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4560 means also fill the red/green/blue members of the XColor
4561 structures. Value is a pointer to the array of XColors structures,
4562 allocated with xmalloc; it must be freed by the caller. */
4564 static XColor *
4565 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4567 int x, y;
4568 XColor *colors, *p;
4569 XImagePtr_or_DC ximg;
4570 #ifdef HAVE_NTGUI
4571 HGDIOBJ prev;
4572 #endif /* HAVE_NTGUI */
4574 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width < img->height)
4575 memory_full (SIZE_MAX);
4576 colors = xmalloc (sizeof *colors * img->width * img->height);
4578 /* Get the X image or create a memory device context for IMG. */
4579 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4581 /* Fill the `pixel' members of the XColor array. I wished there
4582 were an easy and portable way to circumvent XGetPixel. */
4583 p = colors;
4584 for (y = 0; y < img->height; ++y)
4586 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4587 XColor *row = p;
4588 for (x = 0; x < img->width; ++x, ++p)
4589 p->pixel = GET_PIXEL (ximg, x, y);
4590 if (rgb_p)
4591 x_query_colors (f, row, img->width);
4593 #else
4595 for (x = 0; x < img->width; ++x, ++p)
4597 /* W32_TODO: palette support needed here? */
4598 p->pixel = GET_PIXEL (ximg, x, y);
4599 if (rgb_p)
4601 p->red = RED16_FROM_ULONG (p->pixel);
4602 p->green = GREEN16_FROM_ULONG (p->pixel);
4603 p->blue = BLUE16_FROM_ULONG (p->pixel);
4606 #endif /* HAVE_X_WINDOWS */
4609 image_unget_x_image_or_dc (img, 0, ximg, prev);
4611 return colors;
4614 #ifdef HAVE_NTGUI
4616 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4617 created with CreateDIBSection, with the pointer to the bit values
4618 stored in ximg->data. */
4620 static void
4621 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4623 int width = ximg->info.bmiHeader.biWidth;
4624 unsigned char * pixel;
4626 /* True color images. */
4627 if (ximg->info.bmiHeader.biBitCount == 24)
4629 int rowbytes = width * 3;
4630 /* Ensure scanlines are aligned on 4 byte boundaries. */
4631 if (rowbytes % 4)
4632 rowbytes += 4 - (rowbytes % 4);
4634 pixel = ximg->data + y * rowbytes + x * 3;
4635 /* Windows bitmaps are in BGR order. */
4636 *pixel = GetBValue (color);
4637 *(pixel + 1) = GetGValue (color);
4638 *(pixel + 2) = GetRValue (color);
4640 /* Monochrome images. */
4641 else if (ximg->info.bmiHeader.biBitCount == 1)
4643 int rowbytes = width / 8;
4644 /* Ensure scanlines are aligned on 4 byte boundaries. */
4645 if (rowbytes % 4)
4646 rowbytes += 4 - (rowbytes % 4);
4647 pixel = ximg->data + y * rowbytes + x / 8;
4648 /* Filter out palette info. */
4649 if (color & 0x00ffffff)
4650 *pixel = *pixel | (1 << x % 8);
4651 else
4652 *pixel = *pixel & ~(1 << x % 8);
4654 else
4655 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4658 #endif /* HAVE_NTGUI */
4660 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4661 RGB members are set. F is the frame on which this all happens.
4662 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4664 static void
4665 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4667 int x, y;
4668 XImagePtr oimg = NULL;
4669 XColor *p;
4671 init_color_table ();
4673 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4674 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4675 &oimg, 0);
4676 p = colors;
4677 for (y = 0; y < img->height; ++y)
4678 for (x = 0; x < img->width; ++x, ++p)
4680 unsigned long pixel;
4681 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4682 XPutPixel (oimg, x, y, pixel);
4685 xfree (colors);
4687 image_put_x_image (f, img, oimg, 0);
4688 #ifdef COLOR_TABLE_SUPPORT
4689 img->colors = colors_in_color_table (&img->ncolors);
4690 free_color_table ();
4691 #endif /* COLOR_TABLE_SUPPORT */
4695 /* On frame F, perform edge-detection on image IMG.
4697 MATRIX is a nine-element array specifying the transformation
4698 matrix. See emboss_matrix for an example.
4700 COLOR_ADJUST is a color adjustment added to each pixel of the
4701 outgoing image. */
4703 static void
4704 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4706 XColor *colors = x_to_xcolors (f, img, 1);
4707 XColor *new, *p;
4708 int x, y, i, sum;
4710 for (i = sum = 0; i < 9; ++i)
4711 sum += eabs (matrix[i]);
4713 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4715 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width < img->height)
4716 memory_full (SIZE_MAX);
4717 new = xmalloc (sizeof *new * img->width * img->height);
4719 for (y = 0; y < img->height; ++y)
4721 p = COLOR (new, 0, y);
4722 p->red = p->green = p->blue = 0xffff/2;
4723 p = COLOR (new, img->width - 1, y);
4724 p->red = p->green = p->blue = 0xffff/2;
4727 for (x = 1; x < img->width - 1; ++x)
4729 p = COLOR (new, x, 0);
4730 p->red = p->green = p->blue = 0xffff/2;
4731 p = COLOR (new, x, img->height - 1);
4732 p->red = p->green = p->blue = 0xffff/2;
4735 for (y = 1; y < img->height - 1; ++y)
4737 p = COLOR (new, 1, y);
4739 for (x = 1; x < img->width - 1; ++x, ++p)
4741 int r, g, b, yy, xx;
4743 r = g = b = i = 0;
4744 for (yy = y - 1; yy < y + 2; ++yy)
4745 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4746 if (matrix[i])
4748 XColor *t = COLOR (colors, xx, yy);
4749 r += matrix[i] * t->red;
4750 g += matrix[i] * t->green;
4751 b += matrix[i] * t->blue;
4754 r = (r / sum + color_adjust) & 0xffff;
4755 g = (g / sum + color_adjust) & 0xffff;
4756 b = (b / sum + color_adjust) & 0xffff;
4757 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4761 xfree (colors);
4762 x_from_xcolors (f, img, new);
4764 #undef COLOR
4768 /* Perform the pre-defined `emboss' edge-detection on image IMG
4769 on frame F. */
4771 static void
4772 x_emboss (struct frame *f, struct image *img)
4774 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4778 /* Transform image IMG which is used on frame F with a Laplace
4779 edge-detection algorithm. The result is an image that can be used
4780 to draw disabled buttons, for example. */
4782 static void
4783 x_laplace (struct frame *f, struct image *img)
4785 x_detect_edges (f, img, laplace_matrix, 45000);
4789 /* Perform edge-detection on image IMG on frame F, with specified
4790 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4792 MATRIX must be either
4794 - a list of at least 9 numbers in row-major form
4795 - a vector of at least 9 numbers
4797 COLOR_ADJUST nil means use a default; otherwise it must be a
4798 number. */
4800 static void
4801 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4802 Lisp_Object color_adjust)
4804 int i = 0;
4805 int trans[9];
4807 if (CONSP (matrix))
4809 for (i = 0;
4810 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4811 ++i, matrix = XCDR (matrix))
4812 trans[i] = XFLOATINT (XCAR (matrix));
4814 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4816 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4817 trans[i] = XFLOATINT (AREF (matrix, i));
4820 if (NILP (color_adjust))
4821 color_adjust = make_number (0xffff / 2);
4823 if (i == 9 && NUMBERP (color_adjust))
4824 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4828 /* Transform image IMG on frame F so that it looks disabled. */
4830 static void
4831 x_disable_image (struct frame *f, struct image *img)
4833 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4834 #ifdef HAVE_NTGUI
4835 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4836 #else
4837 int n_planes = dpyinfo->n_planes;
4838 #endif /* HAVE_NTGUI */
4840 if (n_planes >= 2)
4842 /* Color (or grayscale). Convert to gray, and equalize. Just
4843 drawing such images with a stipple can look very odd, so
4844 we're using this method instead. */
4845 XColor *colors = x_to_xcolors (f, img, 1);
4846 XColor *p, *end;
4847 const int h = 15000;
4848 const int l = 30000;
4850 for (p = colors, end = colors + img->width * img->height;
4851 p < end;
4852 ++p)
4854 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4855 int i2 = (0xffff - h - l) * i / 0xffff + l;
4856 p->red = p->green = p->blue = i2;
4859 x_from_xcolors (f, img, colors);
4862 /* Draw a cross over the disabled image, if we must or if we
4863 should. */
4864 if (n_planes < 2 || cross_disabled_images)
4866 #ifndef HAVE_NTGUI
4867 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4869 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4871 Display *dpy = FRAME_X_DISPLAY (f);
4872 GC gc;
4874 image_sync_to_pixmaps (f, img);
4875 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4876 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4877 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4878 img->width - 1, img->height - 1);
4879 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4880 img->width - 1, 0);
4881 XFreeGC (dpy, gc);
4883 if (img->mask)
4885 gc = XCreateGC (dpy, img->mask, 0, NULL);
4886 XSetForeground (dpy, gc, MaskForeground (f));
4887 XDrawLine (dpy, img->mask, gc, 0, 0,
4888 img->width - 1, img->height - 1);
4889 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4890 img->width - 1, 0);
4891 XFreeGC (dpy, gc);
4893 #endif /* !HAVE_NS */
4894 #else
4895 HDC hdc, bmpdc;
4896 HGDIOBJ prev;
4898 hdc = get_frame_dc (f);
4899 bmpdc = CreateCompatibleDC (hdc);
4900 release_frame_dc (f, hdc);
4902 prev = SelectObject (bmpdc, img->pixmap);
4904 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4905 MoveToEx (bmpdc, 0, 0, NULL);
4906 LineTo (bmpdc, img->width - 1, img->height - 1);
4907 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4908 LineTo (bmpdc, img->width - 1, 0);
4910 if (img->mask)
4912 SelectObject (bmpdc, img->mask);
4913 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4914 MoveToEx (bmpdc, 0, 0, NULL);
4915 LineTo (bmpdc, img->width - 1, img->height - 1);
4916 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4917 LineTo (bmpdc, img->width - 1, 0);
4919 SelectObject (bmpdc, prev);
4920 DeleteDC (bmpdc);
4921 #endif /* HAVE_NTGUI */
4926 /* Build a mask for image IMG which is used on frame F. FILE is the
4927 name of an image file, for error messages. HOW determines how to
4928 determine the background color of IMG. If it is a list '(R G B)',
4929 with R, G, and B being integers >= 0, take that as the color of the
4930 background. Otherwise, determine the background color of IMG
4931 heuristically. */
4933 static void
4934 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4936 XImagePtr_or_DC ximg;
4937 #ifndef HAVE_NTGUI
4938 XImagePtr mask_img;
4939 #else
4940 HGDIOBJ prev;
4941 char *mask_img;
4942 int row_width;
4943 #endif /* HAVE_NTGUI */
4944 int x, y;
4945 bool use_img_background;
4946 unsigned long bg = 0;
4948 if (img->mask)
4949 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4951 #ifndef HAVE_NTGUI
4952 #ifndef HAVE_NS
4953 /* Create an image and pixmap serving as mask. */
4954 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
4955 &mask_img, 1))
4956 return;
4957 #endif /* !HAVE_NS */
4958 #else
4959 /* Create the bit array serving as mask. */
4960 row_width = (img->width + 7) / 8;
4961 mask_img = xzalloc (row_width * img->height);
4962 #endif /* HAVE_NTGUI */
4964 /* Get the X image or create a memory device context for IMG. */
4965 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4967 /* Determine the background color of ximg. If HOW is `(R G B)'
4968 take that as color. Otherwise, use the image's background color. */
4969 use_img_background = 1;
4971 if (CONSP (how))
4973 int rgb[3], i;
4975 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4977 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4978 how = XCDR (how);
4981 if (i == 3 && NILP (how))
4983 char color_name[30];
4984 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4985 bg = (
4986 #ifdef HAVE_NTGUI
4987 0x00ffffff & /* Filter out palette info. */
4988 #endif /* HAVE_NTGUI */
4989 x_alloc_image_color (f, img, build_string (color_name), 0));
4990 use_img_background = 0;
4994 if (use_img_background)
4995 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4997 /* Set all bits in mask_img to 1 whose color in ximg is different
4998 from the background color bg. */
4999 #ifndef HAVE_NTGUI
5000 for (y = 0; y < img->height; ++y)
5001 for (x = 0; x < img->width; ++x)
5002 #ifndef HAVE_NS
5003 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5004 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5005 #else
5006 if (XGetPixel (ximg, x, y) == bg)
5007 ns_set_alpha (ximg, x, y, 0);
5008 #endif /* HAVE_NS */
5009 #ifndef HAVE_NS
5010 /* Fill in the background_transparent field while we have the mask handy. */
5011 image_background_transparent (img, f, mask_img);
5013 /* Put mask_img into the image. */
5014 image_put_x_image (f, img, mask_img, 1);
5015 #endif /* !HAVE_NS */
5016 #else
5017 for (y = 0; y < img->height; ++y)
5018 for (x = 0; x < img->width; ++x)
5020 COLORREF p = GetPixel (ximg, x, y);
5021 if (p != bg)
5022 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5025 /* Create the mask image. */
5026 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5027 mask_img);
5028 /* Fill in the background_transparent field while we have the mask handy. */
5029 SelectObject (ximg, img->mask);
5030 image_background_transparent (img, f, ximg);
5032 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5033 xfree (mask_img);
5034 #endif /* HAVE_NTGUI */
5036 image_unget_x_image_or_dc (img, 0, ximg, prev);
5040 /***********************************************************************
5041 PBM (mono, gray, color)
5042 ***********************************************************************/
5044 static bool pbm_image_p (Lisp_Object object);
5045 static bool pbm_load (struct frame *f, struct image *img);
5047 /* The symbol `pbm' identifying images of this type. */
5049 static Lisp_Object Qpbm;
5051 /* Indices of image specification fields in gs_format, below. */
5053 enum pbm_keyword_index
5055 PBM_TYPE,
5056 PBM_FILE,
5057 PBM_DATA,
5058 PBM_ASCENT,
5059 PBM_MARGIN,
5060 PBM_RELIEF,
5061 PBM_ALGORITHM,
5062 PBM_HEURISTIC_MASK,
5063 PBM_MASK,
5064 PBM_FOREGROUND,
5065 PBM_BACKGROUND,
5066 PBM_LAST
5069 /* Vector of image_keyword structures describing the format
5070 of valid user-defined image specifications. */
5072 static const struct image_keyword pbm_format[PBM_LAST] =
5074 {":type", IMAGE_SYMBOL_VALUE, 1},
5075 {":file", IMAGE_STRING_VALUE, 0},
5076 {":data", IMAGE_STRING_VALUE, 0},
5077 {":ascent", IMAGE_ASCENT_VALUE, 0},
5078 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5079 {":relief", IMAGE_INTEGER_VALUE, 0},
5080 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5081 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5082 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5083 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5084 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5087 /* Structure describing the image type `pbm'. */
5089 static struct image_type pbm_type =
5091 &Qpbm,
5092 pbm_image_p,
5093 pbm_load,
5094 x_clear_image,
5095 NULL,
5096 NULL
5100 /* Return true if OBJECT is a valid PBM image specification. */
5102 static bool
5103 pbm_image_p (Lisp_Object object)
5105 struct image_keyword fmt[PBM_LAST];
5107 memcpy (fmt, pbm_format, sizeof fmt);
5109 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5110 return 0;
5112 /* Must specify either :data or :file. */
5113 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5117 /* Get next char skipping comments in Netpbm header. Returns -1 at
5118 end of input. */
5120 static int
5121 pbm_next_char (unsigned char **s, unsigned char *end)
5123 int c = -1;
5125 while (*s < end && (c = *(*s)++, c == '#'))
5127 /* Skip to the next line break. */
5128 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5131 c = -1;
5134 return c;
5138 /* Scan a decimal number from *S and return it. Advance *S while
5139 reading the number. END is the end of the string. Value is -1 at
5140 end of input. */
5142 static int
5143 pbm_scan_number (unsigned char **s, unsigned char *end)
5145 int c = 0, val = -1;
5147 /* Skip white-space. */
5148 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5151 if (c_isdigit (c))
5153 /* Read decimal number. */
5154 val = c - '0';
5155 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5156 val = 10 * val + c - '0';
5159 return val;
5163 /* Load PBM image IMG for use on frame F. */
5165 static bool
5166 pbm_load (struct frame *f, struct image *img)
5168 bool raw_p;
5169 int x, y;
5170 int width, height, max_color_idx = 0;
5171 XImagePtr ximg;
5172 Lisp_Object file, specified_file;
5173 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5174 unsigned char *contents = NULL;
5175 unsigned char *end, *p;
5176 ptrdiff_t size;
5178 specified_file = image_spec_value (img->spec, QCfile, NULL);
5180 if (STRINGP (specified_file))
5182 file = x_find_image_file (specified_file);
5183 if (!STRINGP (file))
5185 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5186 return 0;
5189 contents = slurp_file (SSDATA (file), &size);
5190 if (contents == NULL)
5192 image_error ("Error reading `%s'", file, Qnil);
5193 return 0;
5196 p = contents;
5197 end = contents + size;
5199 else
5201 Lisp_Object data;
5202 data = image_spec_value (img->spec, QCdata, NULL);
5203 if (!STRINGP (data))
5205 image_error ("Invalid image data `%s'", data, Qnil);
5206 return 0;
5208 p = SDATA (data);
5209 end = p + SBYTES (data);
5212 /* Check magic number. */
5213 if (end - p < 2 || *p++ != 'P')
5215 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5216 error:
5217 xfree (contents);
5218 return 0;
5221 switch (*p++)
5223 case '1':
5224 raw_p = 0, type = PBM_MONO;
5225 break;
5227 case '2':
5228 raw_p = 0, type = PBM_GRAY;
5229 break;
5231 case '3':
5232 raw_p = 0, type = PBM_COLOR;
5233 break;
5235 case '4':
5236 raw_p = 1, type = PBM_MONO;
5237 break;
5239 case '5':
5240 raw_p = 1, type = PBM_GRAY;
5241 break;
5243 case '6':
5244 raw_p = 1, type = PBM_COLOR;
5245 break;
5247 default:
5248 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5249 goto error;
5252 /* Read width, height, maximum color-component. Characters
5253 starting with `#' up to the end of a line are ignored. */
5254 width = pbm_scan_number (&p, end);
5255 height = pbm_scan_number (&p, end);
5257 if (type != PBM_MONO)
5259 max_color_idx = pbm_scan_number (&p, end);
5260 if (max_color_idx > 65535 || max_color_idx < 0)
5262 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5263 goto error;
5267 if (!check_image_size (f, width, height))
5269 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5270 goto error;
5273 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5274 goto error;
5276 /* Initialize the color hash table. */
5277 init_color_table ();
5279 if (type == PBM_MONO)
5281 int c = 0, g;
5282 struct image_keyword fmt[PBM_LAST];
5283 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5284 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5286 /* Parse the image specification. */
5287 memcpy (fmt, pbm_format, sizeof fmt);
5288 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5290 /* Get foreground and background colors, maybe allocate colors. */
5291 if (fmt[PBM_FOREGROUND].count
5292 && STRINGP (fmt[PBM_FOREGROUND].value))
5293 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5294 if (fmt[PBM_BACKGROUND].count
5295 && STRINGP (fmt[PBM_BACKGROUND].value))
5297 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5298 img->background = bg;
5299 img->background_valid = 1;
5302 for (y = 0; y < height; ++y)
5303 for (x = 0; x < width; ++x)
5305 if (raw_p)
5307 if ((x & 7) == 0)
5309 if (p >= end)
5311 x_destroy_x_image (ximg);
5312 x_clear_image (f, img);
5313 image_error ("Invalid image size in image `%s'",
5314 img->spec, Qnil);
5315 goto error;
5317 c = *p++;
5319 g = c & 0x80;
5320 c <<= 1;
5322 else
5323 g = pbm_scan_number (&p, end);
5325 XPutPixel (ximg, x, y, g ? fg : bg);
5328 else
5330 int expected_size = height * width;
5331 if (max_color_idx > 255)
5332 expected_size *= 2;
5333 if (type == PBM_COLOR)
5334 expected_size *= 3;
5336 if (raw_p && p + expected_size > end)
5338 x_destroy_x_image (ximg);
5339 x_clear_image (f, img);
5340 image_error ("Invalid image size in image `%s'",
5341 img->spec, Qnil);
5342 goto error;
5345 for (y = 0; y < height; ++y)
5346 for (x = 0; x < width; ++x)
5348 int r, g, b;
5350 if (type == PBM_GRAY && raw_p)
5352 r = g = b = *p++;
5353 if (max_color_idx > 255)
5354 r = g = b = r * 256 + *p++;
5356 else if (type == PBM_GRAY)
5357 r = g = b = pbm_scan_number (&p, end);
5358 else if (raw_p)
5360 r = *p++;
5361 if (max_color_idx > 255)
5362 r = r * 256 + *p++;
5363 g = *p++;
5364 if (max_color_idx > 255)
5365 g = g * 256 + *p++;
5366 b = *p++;
5367 if (max_color_idx > 255)
5368 b = b * 256 + *p++;
5370 else
5372 r = pbm_scan_number (&p, end);
5373 g = pbm_scan_number (&p, end);
5374 b = pbm_scan_number (&p, end);
5377 if (r < 0 || g < 0 || b < 0)
5379 x_destroy_x_image (ximg);
5380 image_error ("Invalid pixel value in image `%s'",
5381 img->spec, Qnil);
5382 goto error;
5385 /* RGB values are now in the range 0..max_color_idx.
5386 Scale this to the range 0..0xffff supported by X. */
5387 r = (double) r * 65535 / max_color_idx;
5388 g = (double) g * 65535 / max_color_idx;
5389 b = (double) b * 65535 / max_color_idx;
5390 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5394 #ifdef COLOR_TABLE_SUPPORT
5395 /* Store in IMG->colors the colors allocated for the image, and
5396 free the color table. */
5397 img->colors = colors_in_color_table (&img->ncolors);
5398 free_color_table ();
5399 #endif /* COLOR_TABLE_SUPPORT */
5401 img->width = width;
5402 img->height = height;
5404 /* Maybe fill in the background field while we have ximg handy. */
5406 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5407 /* Casting avoids a GCC warning. */
5408 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5410 /* Put ximg into the image. */
5411 image_put_x_image (f, img, ximg, 0);
5413 /* X and W32 versions did it here, MAC version above. ++kfs
5414 img->width = width;
5415 img->height = height; */
5417 xfree (contents);
5418 return 1;
5422 /***********************************************************************
5424 ***********************************************************************/
5426 #if defined (HAVE_PNG) || defined (HAVE_NS)
5428 /* Function prototypes. */
5430 static bool png_image_p (Lisp_Object object);
5431 static bool png_load (struct frame *f, struct image *img);
5433 /* The symbol `png' identifying images of this type. */
5435 static Lisp_Object Qpng;
5437 /* Indices of image specification fields in png_format, below. */
5439 enum png_keyword_index
5441 PNG_TYPE,
5442 PNG_DATA,
5443 PNG_FILE,
5444 PNG_ASCENT,
5445 PNG_MARGIN,
5446 PNG_RELIEF,
5447 PNG_ALGORITHM,
5448 PNG_HEURISTIC_MASK,
5449 PNG_MASK,
5450 PNG_BACKGROUND,
5451 PNG_LAST
5454 /* Vector of image_keyword structures describing the format
5455 of valid user-defined image specifications. */
5457 static const struct image_keyword png_format[PNG_LAST] =
5459 {":type", IMAGE_SYMBOL_VALUE, 1},
5460 {":data", IMAGE_STRING_VALUE, 0},
5461 {":file", IMAGE_STRING_VALUE, 0},
5462 {":ascent", IMAGE_ASCENT_VALUE, 0},
5463 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5464 {":relief", IMAGE_INTEGER_VALUE, 0},
5465 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5466 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5467 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5468 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5471 #if defined HAVE_NTGUI && defined WINDOWSNT
5472 static bool init_png_functions (void);
5473 #else
5474 #define init_png_functions NULL
5475 #endif
5477 /* Structure describing the image type `png'. */
5479 static struct image_type png_type =
5481 &Qpng,
5482 png_image_p,
5483 png_load,
5484 x_clear_image,
5485 init_png_functions,
5486 NULL
5489 /* Return true if OBJECT is a valid PNG image specification. */
5491 static bool
5492 png_image_p (Lisp_Object object)
5494 struct image_keyword fmt[PNG_LAST];
5495 memcpy (fmt, png_format, sizeof fmt);
5497 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5498 return 0;
5500 /* Must specify either the :data or :file keyword. */
5501 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5504 #endif /* HAVE_PNG || HAVE_NS */
5507 #ifdef HAVE_PNG
5509 #ifdef WINDOWSNT
5510 /* PNG library details. */
5512 DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5513 DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5514 DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5515 png_error_ptr, png_error_ptr));
5516 DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5517 DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5518 DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5519 DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5520 DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5521 DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
5522 png_uint_32 *, png_uint_32 *,
5523 int *, int *, int *, int *, int *));
5524 DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5525 DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5526 DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5527 DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5528 DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
5529 int, int, double));
5530 DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5531 DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5532 DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5533 DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5534 DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5535 DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5536 DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
5538 #if (PNG_LIBPNG_VER >= 10500)
5539 DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5540 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
5541 #endif /* libpng version >= 1.5 */
5543 static bool
5544 init_png_functions (void)
5546 HMODULE library;
5548 if (!(library = w32_delayed_load (Qpng)))
5549 return 0;
5551 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5552 LOAD_IMGLIB_FN (library, png_sig_cmp);
5553 LOAD_IMGLIB_FN (library, png_create_read_struct);
5554 LOAD_IMGLIB_FN (library, png_create_info_struct);
5555 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5556 LOAD_IMGLIB_FN (library, png_set_read_fn);
5557 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5558 LOAD_IMGLIB_FN (library, png_read_info);
5559 LOAD_IMGLIB_FN (library, png_get_IHDR);
5560 LOAD_IMGLIB_FN (library, png_get_valid);
5561 LOAD_IMGLIB_FN (library, png_set_strip_16);
5562 LOAD_IMGLIB_FN (library, png_set_expand);
5563 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5564 LOAD_IMGLIB_FN (library, png_set_background);
5565 LOAD_IMGLIB_FN (library, png_get_bKGD);
5566 LOAD_IMGLIB_FN (library, png_read_update_info);
5567 LOAD_IMGLIB_FN (library, png_get_channels);
5568 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5569 LOAD_IMGLIB_FN (library, png_read_image);
5570 LOAD_IMGLIB_FN (library, png_read_end);
5571 LOAD_IMGLIB_FN (library, png_error);
5573 #if (PNG_LIBPNG_VER >= 10500)
5574 LOAD_IMGLIB_FN (library, png_longjmp);
5575 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5576 #endif /* libpng version >= 1.5 */
5578 return 1;
5580 #else
5582 #define fn_png_get_io_ptr png_get_io_ptr
5583 #define fn_png_sig_cmp png_sig_cmp
5584 #define fn_png_create_read_struct png_create_read_struct
5585 #define fn_png_create_info_struct png_create_info_struct
5586 #define fn_png_destroy_read_struct png_destroy_read_struct
5587 #define fn_png_set_read_fn png_set_read_fn
5588 #define fn_png_set_sig_bytes png_set_sig_bytes
5589 #define fn_png_read_info png_read_info
5590 #define fn_png_get_IHDR png_get_IHDR
5591 #define fn_png_get_valid png_get_valid
5592 #define fn_png_set_strip_16 png_set_strip_16
5593 #define fn_png_set_expand png_set_expand
5594 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5595 #define fn_png_set_background png_set_background
5596 #define fn_png_get_bKGD png_get_bKGD
5597 #define fn_png_read_update_info png_read_update_info
5598 #define fn_png_get_channels png_get_channels
5599 #define fn_png_get_rowbytes png_get_rowbytes
5600 #define fn_png_read_image png_read_image
5601 #define fn_png_read_end png_read_end
5602 #define fn_png_error png_error
5604 #if (PNG_LIBPNG_VER >= 10500)
5605 #define fn_png_longjmp png_longjmp
5606 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5607 #endif /* libpng version >= 1.5 */
5609 #endif /* WINDOWSNT */
5611 /* Possibly inefficient/inexact substitutes for _setjmp and _longjmp.
5612 Do not use sys_setjmp, as PNG supports only jmp_buf. The _longjmp
5613 substitute may munge the signal mask, but that should be OK here.
5614 MinGW (MS-Windows) uses _setjmp and defines setjmp to _setjmp in
5615 the system header setjmp.h; don't mess up that. */
5616 #ifndef HAVE__SETJMP
5617 # define _setjmp(j) setjmp (j)
5618 # define _longjmp longjmp
5619 #endif
5621 #if (PNG_LIBPNG_VER < 10500)
5622 #define PNG_LONGJMP(ptr) (_longjmp ((ptr)->jmpbuf, 1))
5623 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5624 #else
5625 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5626 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5627 #define PNG_JMPBUF(ptr) \
5628 (*fn_png_set_longjmp_fn ((ptr), _longjmp, sizeof (jmp_buf)))
5629 #endif
5631 /* Error and warning handlers installed when the PNG library
5632 is initialized. */
5634 static _Noreturn void
5635 my_png_error (png_struct *png_ptr, const char *msg)
5637 eassert (png_ptr != NULL);
5638 /* Avoid compiler warning about deprecated direct access to
5639 png_ptr's fields in libpng versions 1.4.x. */
5640 image_error ("PNG error: %s", build_string (msg), Qnil);
5641 PNG_LONGJMP (png_ptr);
5645 static void
5646 my_png_warning (png_struct *png_ptr, const char *msg)
5648 eassert (png_ptr != NULL);
5649 image_error ("PNG warning: %s", build_string (msg), Qnil);
5652 /* Memory source for PNG decoding. */
5654 struct png_memory_storage
5656 unsigned char *bytes; /* The data */
5657 ptrdiff_t len; /* How big is it? */
5658 ptrdiff_t index; /* Where are we? */
5662 /* Function set as reader function when reading PNG image from memory.
5663 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5664 bytes from the input to DATA. */
5666 static void
5667 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5669 struct png_memory_storage *tbr = fn_png_get_io_ptr (png_ptr);
5671 if (length > tbr->len - tbr->index)
5672 fn_png_error (png_ptr, "Read error");
5674 memcpy (data, tbr->bytes + tbr->index, length);
5675 tbr->index = tbr->index + length;
5679 /* Function set as reader function when reading PNG image from a file.
5680 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5681 bytes from the input to DATA. */
5683 static void
5684 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5686 FILE *fp = fn_png_get_io_ptr (png_ptr);
5688 if (fread (data, 1, length, fp) < length)
5689 fn_png_error (png_ptr, "Read error");
5693 /* Load PNG image IMG for use on frame F. Value is true if
5694 successful. */
5696 struct png_load_context
5698 /* These are members so that longjmp doesn't munge local variables. */
5699 png_struct *png_ptr;
5700 png_info *info_ptr;
5701 png_info *end_info;
5702 FILE *fp;
5703 png_byte *pixels;
5704 png_byte **rows;
5707 static bool
5708 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5710 Lisp_Object file, specified_file;
5711 Lisp_Object specified_data;
5712 int x, y;
5713 ptrdiff_t i;
5714 XImagePtr ximg, mask_img = NULL;
5715 png_struct *png_ptr;
5716 png_info *info_ptr = NULL, *end_info = NULL;
5717 FILE *fp = NULL;
5718 png_byte sig[8];
5719 png_byte *pixels = NULL;
5720 png_byte **rows = NULL;
5721 png_uint_32 width, height;
5722 int bit_depth, color_type, interlace_type;
5723 png_byte channels;
5724 png_uint_32 row_bytes;
5725 bool transparent_p;
5726 struct png_memory_storage tbr; /* Data to be read */
5728 /* Find out what file to load. */
5729 specified_file = image_spec_value (img->spec, QCfile, NULL);
5730 specified_data = image_spec_value (img->spec, QCdata, NULL);
5732 if (NILP (specified_data))
5734 file = x_find_image_file (specified_file);
5735 if (!STRINGP (file))
5737 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5738 return 0;
5741 /* Open the image file. */
5742 fp = emacs_fopen (SSDATA (file), "rb");
5743 if (!fp)
5745 image_error ("Cannot open image file `%s'", file, Qnil);
5746 return 0;
5749 /* Check PNG signature. */
5750 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5751 || fn_png_sig_cmp (sig, 0, sizeof sig))
5753 fclose (fp);
5754 image_error ("Not a PNG file: `%s'", file, Qnil);
5755 return 0;
5758 else
5760 if (!STRINGP (specified_data))
5762 image_error ("Invalid image data `%s'", specified_data, Qnil);
5763 return 0;
5766 /* Read from memory. */
5767 tbr.bytes = SDATA (specified_data);
5768 tbr.len = SBYTES (specified_data);
5769 tbr.index = 0;
5771 /* Check PNG signature. */
5772 if (tbr.len < sizeof sig
5773 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5775 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5776 return 0;
5779 /* Need to skip past the signature. */
5780 tbr.bytes += sizeof (sig);
5783 /* Initialize read and info structs for PNG lib. */
5784 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5785 NULL, my_png_error,
5786 my_png_warning);
5787 if (png_ptr)
5789 info_ptr = fn_png_create_info_struct (png_ptr);
5790 end_info = fn_png_create_info_struct (png_ptr);
5793 c->png_ptr = png_ptr;
5794 c->info_ptr = info_ptr;
5795 c->end_info = end_info;
5796 c->fp = fp;
5797 c->pixels = pixels;
5798 c->rows = rows;
5800 if (! (info_ptr && end_info))
5802 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5803 png_ptr = 0;
5805 if (! png_ptr)
5807 if (fp) fclose (fp);
5808 return 0;
5811 /* Set error jump-back. We come back here when the PNG library
5812 detects an error. */
5813 if (_setjmp (PNG_JMPBUF (png_ptr)))
5815 error:
5816 if (c->png_ptr)
5817 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5818 xfree (c->pixels);
5819 xfree (c->rows);
5820 if (c->fp)
5821 fclose (c->fp);
5822 return 0;
5825 /* Silence a bogus diagnostic; see GCC bug 54561. */
5826 IF_LINT (fp = c->fp);
5828 /* Read image info. */
5829 if (!NILP (specified_data))
5830 fn_png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
5831 else
5832 fn_png_set_read_fn (png_ptr, fp, png_read_from_file);
5834 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5835 fn_png_read_info (png_ptr, info_ptr);
5836 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5837 &interlace_type, NULL, NULL);
5839 if (! (width <= INT_MAX && height <= INT_MAX
5840 && check_image_size (f, width, height)))
5842 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5843 goto error;
5846 /* Create the X image and pixmap now, so that the work below can be
5847 omitted if the image is too large for X. */
5848 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5849 goto error;
5851 /* If image contains simply transparency data, we prefer to
5852 construct a clipping mask. */
5853 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5854 transparent_p = 1;
5855 else
5856 transparent_p = 0;
5858 /* This function is easier to write if we only have to handle
5859 one data format: RGB or RGBA with 8 bits per channel. Let's
5860 transform other formats into that format. */
5862 /* Strip more than 8 bits per channel. */
5863 if (bit_depth == 16)
5864 fn_png_set_strip_16 (png_ptr);
5866 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5867 if available. */
5868 fn_png_set_expand (png_ptr);
5870 /* Convert grayscale images to RGB. */
5871 if (color_type == PNG_COLOR_TYPE_GRAY
5872 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5873 fn_png_set_gray_to_rgb (png_ptr);
5875 /* Handle alpha channel by combining the image with a background
5876 color. Do this only if a real alpha channel is supplied. For
5877 simple transparency, we prefer a clipping mask. */
5878 if (!transparent_p)
5880 /* png_color_16 *image_bg; */
5881 Lisp_Object specified_bg
5882 = image_spec_value (img->spec, QCbackground, NULL);
5883 int shift = (bit_depth == 16) ? 0 : 8;
5885 if (STRINGP (specified_bg))
5886 /* The user specified `:background', use that. */
5888 XColor color;
5889 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
5891 png_color_16 user_bg;
5893 memset (&user_bg, 0, sizeof user_bg);
5894 user_bg.red = color.red >> shift;
5895 user_bg.green = color.green >> shift;
5896 user_bg.blue = color.blue >> shift;
5898 fn_png_set_background (png_ptr, &user_bg,
5899 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5902 else
5904 /* We use the current frame background, ignoring any default
5905 background color set by the image. */
5906 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5907 XColor color;
5908 png_color_16 frame_background;
5910 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5911 x_query_color (f, &color);
5913 memset (&frame_background, 0, sizeof frame_background);
5914 frame_background.red = color.red >> shift;
5915 frame_background.green = color.green >> shift;
5916 frame_background.blue = color.blue >> shift;
5917 #endif /* HAVE_X_WINDOWS */
5919 fn_png_set_background (png_ptr, &frame_background,
5920 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5924 /* Update info structure. */
5925 fn_png_read_update_info (png_ptr, info_ptr);
5927 /* Get number of channels. Valid values are 1 for grayscale images
5928 and images with a palette, 2 for grayscale images with transparency
5929 information (alpha channel), 3 for RGB images, and 4 for RGB
5930 images with alpha channel, i.e. RGBA. If conversions above were
5931 sufficient we should only have 3 or 4 channels here. */
5932 channels = fn_png_get_channels (png_ptr, info_ptr);
5933 eassert (channels == 3 || channels == 4);
5935 /* Number of bytes needed for one row of the image. */
5936 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5938 /* Allocate memory for the image. */
5939 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows < height
5940 || min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height < row_bytes)
5941 memory_full (SIZE_MAX);
5942 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
5943 c->rows = rows = xmalloc (height * sizeof *rows);
5944 for (i = 0; i < height; ++i)
5945 rows[i] = pixels + i * row_bytes;
5947 /* Read the entire image. */
5948 fn_png_read_image (png_ptr, rows);
5949 fn_png_read_end (png_ptr, info_ptr);
5950 if (fp)
5952 fclose (fp);
5953 c->fp = NULL;
5956 /* Create an image and pixmap serving as mask if the PNG image
5957 contains an alpha channel. */
5958 if (channels == 4
5959 && !transparent_p
5960 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
5961 &mask_img, 1))
5963 x_destroy_x_image (ximg);
5964 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
5965 goto error;
5968 /* Fill the X image and mask from PNG data. */
5969 init_color_table ();
5971 for (y = 0; y < height; ++y)
5973 png_byte *p = rows[y];
5975 for (x = 0; x < width; ++x)
5977 int r, g, b;
5979 r = *p++ << 8;
5980 g = *p++ << 8;
5981 b = *p++ << 8;
5982 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5983 /* An alpha channel, aka mask channel, associates variable
5984 transparency with an image. Where other image formats
5985 support binary transparency---fully transparent or fully
5986 opaque---PNG allows up to 254 levels of partial transparency.
5987 The PNG library implements partial transparency by combining
5988 the image with a specified background color.
5990 I'm not sure how to handle this here nicely: because the
5991 background on which the image is displayed may change, for
5992 real alpha channel support, it would be necessary to create
5993 a new image for each possible background.
5995 What I'm doing now is that a mask is created if we have
5996 boolean transparency information. Otherwise I'm using
5997 the frame's background color to combine the image with. */
5999 if (channels == 4)
6001 if (mask_img)
6002 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6003 ++p;
6008 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6009 /* Set IMG's background color from the PNG image, unless the user
6010 overrode it. */
6012 png_color_16 *bg;
6013 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6015 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6016 img->background_valid = 1;
6020 #ifdef COLOR_TABLE_SUPPORT
6021 /* Remember colors allocated for this image. */
6022 img->colors = colors_in_color_table (&img->ncolors);
6023 free_color_table ();
6024 #endif /* COLOR_TABLE_SUPPORT */
6026 /* Clean up. */
6027 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6028 xfree (rows);
6029 xfree (pixels);
6031 img->width = width;
6032 img->height = height;
6034 /* Maybe fill in the background field while we have ximg handy.
6035 Casting avoids a GCC warning. */
6036 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6038 /* Put ximg into the image. */
6039 image_put_x_image (f, img, ximg, 0);
6041 /* Same for the mask. */
6042 if (mask_img)
6044 /* Fill in the background_transparent field while we have the
6045 mask handy. Casting avoids a GCC warning. */
6046 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6048 image_put_x_image (f, img, mask_img, 1);
6051 return 1;
6054 static bool
6055 png_load (struct frame *f, struct image *img)
6057 struct png_load_context c;
6058 return png_load_body (f, img, &c);
6061 #else /* HAVE_PNG */
6063 #ifdef HAVE_NS
6064 static bool
6065 png_load (struct frame *f, struct image *img)
6067 return ns_load_image (f, img,
6068 image_spec_value (img->spec, QCfile, NULL),
6069 image_spec_value (img->spec, QCdata, NULL));
6071 #endif /* HAVE_NS */
6074 #endif /* !HAVE_PNG */
6078 /***********************************************************************
6079 JPEG
6080 ***********************************************************************/
6082 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6084 static bool jpeg_image_p (Lisp_Object object);
6085 static bool jpeg_load (struct frame *f, struct image *img);
6087 /* The symbol `jpeg' identifying images of this type. */
6089 static Lisp_Object Qjpeg;
6091 /* Indices of image specification fields in gs_format, below. */
6093 enum jpeg_keyword_index
6095 JPEG_TYPE,
6096 JPEG_DATA,
6097 JPEG_FILE,
6098 JPEG_ASCENT,
6099 JPEG_MARGIN,
6100 JPEG_RELIEF,
6101 JPEG_ALGORITHM,
6102 JPEG_HEURISTIC_MASK,
6103 JPEG_MASK,
6104 JPEG_BACKGROUND,
6105 JPEG_LAST
6108 /* Vector of image_keyword structures describing the format
6109 of valid user-defined image specifications. */
6111 static const struct image_keyword jpeg_format[JPEG_LAST] =
6113 {":type", IMAGE_SYMBOL_VALUE, 1},
6114 {":data", IMAGE_STRING_VALUE, 0},
6115 {":file", IMAGE_STRING_VALUE, 0},
6116 {":ascent", IMAGE_ASCENT_VALUE, 0},
6117 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6118 {":relief", IMAGE_INTEGER_VALUE, 0},
6119 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6120 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6121 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6122 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6125 #if defined HAVE_NTGUI && defined WINDOWSNT
6126 static bool init_jpeg_functions (void);
6127 #else
6128 #define init_jpeg_functions NULL
6129 #endif
6131 /* Structure describing the image type `jpeg'. */
6133 static struct image_type jpeg_type =
6135 &Qjpeg,
6136 jpeg_image_p,
6137 jpeg_load,
6138 x_clear_image,
6139 init_jpeg_functions,
6140 NULL
6143 /* Return true if OBJECT is a valid JPEG image specification. */
6145 static bool
6146 jpeg_image_p (Lisp_Object object)
6148 struct image_keyword fmt[JPEG_LAST];
6150 memcpy (fmt, jpeg_format, sizeof fmt);
6152 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6153 return 0;
6155 /* Must specify either the :data or :file keyword. */
6156 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6159 #endif /* HAVE_JPEG || HAVE_NS */
6161 #ifdef HAVE_JPEG
6163 /* Work around a warning about HAVE_STDLIB_H being redefined in
6164 jconfig.h. */
6165 #ifdef HAVE_STDLIB_H
6166 #undef HAVE_STDLIB_H
6167 #endif /* HAVE_STLIB_H */
6169 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6170 /* In older releases of the jpeg library, jpeglib.h will define boolean
6171 differently depending on __WIN32__, so make sure it is defined. */
6172 #define __WIN32__ 1
6173 #endif
6175 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6176 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6177 using the Windows boolean type instead of the jpeglib boolean type
6178 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6179 headers are included along with windows.h, so under Cygwin, jpeglib
6180 attempts to define a conflicting boolean type. Worse, forcing
6181 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6182 because it created an ABI incompatibility between the
6183 already-compiled jpeg library and the header interface definition.
6185 The best we can do is to define jpeglib's boolean type to a
6186 different name. This name, jpeg_boolean, remains in effect through
6187 the rest of image.c.
6189 #if defined CYGWIN && defined HAVE_NTGUI
6190 #define boolean jpeg_boolean
6191 #endif
6192 #include <jpeglib.h>
6193 #include <jerror.h>
6195 #ifdef WINDOWSNT
6197 /* JPEG library details. */
6198 DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6199 DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6200 DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6201 DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6202 DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6203 DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6204 DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6205 DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6207 static bool
6208 init_jpeg_functions (void)
6210 HMODULE library;
6212 if (!(library = w32_delayed_load (Qjpeg)))
6213 return 0;
6215 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6216 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6217 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6218 LOAD_IMGLIB_FN (library, jpeg_read_header);
6219 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6220 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6221 LOAD_IMGLIB_FN (library, jpeg_std_error);
6222 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6223 return 1;
6226 /* Wrapper since we can't directly assign the function pointer
6227 to another function pointer that was declared more completely easily. */
6228 static boolean
6229 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6231 return fn_jpeg_resync_to_restart (cinfo, desired);
6234 #else
6236 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
6237 #define fn_jpeg_start_decompress jpeg_start_decompress
6238 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6239 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6240 #define fn_jpeg_read_header jpeg_read_header
6241 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6242 #define fn_jpeg_std_error jpeg_std_error
6243 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6245 #endif /* WINDOWSNT */
6247 struct my_jpeg_error_mgr
6249 struct jpeg_error_mgr pub;
6250 sys_jmp_buf setjmp_buffer;
6252 /* The remaining members are so that longjmp doesn't munge local
6253 variables. */
6254 struct jpeg_decompress_struct cinfo;
6255 enum
6257 MY_JPEG_ERROR_EXIT,
6258 MY_JPEG_INVALID_IMAGE_SIZE,
6259 MY_JPEG_CANNOT_CREATE_X
6260 } failure_code;
6261 #ifdef lint
6262 FILE *fp;
6263 #endif
6267 static _Noreturn void
6268 my_error_exit (j_common_ptr cinfo)
6270 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6271 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6272 sys_longjmp (mgr->setjmp_buffer, 1);
6276 /* Init source method for JPEG data source manager. Called by
6277 jpeg_read_header() before any data is actually read. See
6278 libjpeg.doc from the JPEG lib distribution. */
6280 static void
6281 our_common_init_source (j_decompress_ptr cinfo)
6286 /* Method to terminate data source. Called by
6287 jpeg_finish_decompress() after all data has been processed. */
6289 static void
6290 our_common_term_source (j_decompress_ptr cinfo)
6295 /* Fill input buffer method for JPEG data source manager. Called
6296 whenever more data is needed. We read the whole image in one step,
6297 so this only adds a fake end of input marker at the end. */
6299 static JOCTET our_memory_buffer[2];
6301 static boolean
6302 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6304 /* Insert a fake EOI marker. */
6305 struct jpeg_source_mgr *src = cinfo->src;
6307 our_memory_buffer[0] = (JOCTET) 0xFF;
6308 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6310 src->next_input_byte = our_memory_buffer;
6311 src->bytes_in_buffer = 2;
6312 return 1;
6316 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6317 is the JPEG data source manager. */
6319 static void
6320 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6322 struct jpeg_source_mgr *src = cinfo->src;
6324 if (src)
6326 if (num_bytes > src->bytes_in_buffer)
6327 ERREXIT (cinfo, JERR_INPUT_EOF);
6329 src->bytes_in_buffer -= num_bytes;
6330 src->next_input_byte += num_bytes;
6335 /* Set up the JPEG lib for reading an image from DATA which contains
6336 LEN bytes. CINFO is the decompression info structure created for
6337 reading the image. */
6339 static void
6340 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6342 struct jpeg_source_mgr *src = cinfo->src;
6344 if (! src)
6346 /* First time for this JPEG object? */
6347 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6348 JPOOL_PERMANENT, sizeof *src);
6349 cinfo->src = src;
6350 src->next_input_byte = data;
6353 src->init_source = our_common_init_source;
6354 src->fill_input_buffer = our_memory_fill_input_buffer;
6355 src->skip_input_data = our_memory_skip_input_data;
6356 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6357 src->term_source = our_common_term_source;
6358 src->bytes_in_buffer = len;
6359 src->next_input_byte = data;
6363 struct jpeg_stdio_mgr
6365 struct jpeg_source_mgr mgr;
6366 boolean finished;
6367 FILE *file;
6368 JOCTET *buffer;
6372 /* Size of buffer to read JPEG from file.
6373 Not too big, as we want to use alloc_small. */
6374 #define JPEG_STDIO_BUFFER_SIZE 8192
6377 /* Fill input buffer method for JPEG data source manager. Called
6378 whenever more data is needed. The data is read from a FILE *. */
6380 static boolean
6381 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6383 struct jpeg_stdio_mgr *src;
6385 src = (struct jpeg_stdio_mgr *) cinfo->src;
6386 if (!src->finished)
6388 ptrdiff_t bytes;
6390 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6391 if (bytes > 0)
6392 src->mgr.bytes_in_buffer = bytes;
6393 else
6395 WARNMS (cinfo, JWRN_JPEG_EOF);
6396 src->finished = 1;
6397 src->buffer[0] = (JOCTET) 0xFF;
6398 src->buffer[1] = (JOCTET) JPEG_EOI;
6399 src->mgr.bytes_in_buffer = 2;
6401 src->mgr.next_input_byte = src->buffer;
6404 return 1;
6408 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6409 is the JPEG data source manager. */
6411 static void
6412 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6414 struct jpeg_stdio_mgr *src;
6415 src = (struct jpeg_stdio_mgr *) cinfo->src;
6417 while (num_bytes > 0 && !src->finished)
6419 if (num_bytes <= src->mgr.bytes_in_buffer)
6421 src->mgr.bytes_in_buffer -= num_bytes;
6422 src->mgr.next_input_byte += num_bytes;
6423 break;
6425 else
6427 num_bytes -= src->mgr.bytes_in_buffer;
6428 src->mgr.bytes_in_buffer = 0;
6429 src->mgr.next_input_byte = NULL;
6431 our_stdio_fill_input_buffer (cinfo);
6437 /* Set up the JPEG lib for reading an image from a FILE *.
6438 CINFO is the decompression info structure created for
6439 reading the image. */
6441 static void
6442 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6444 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6446 if (! src)
6448 /* First time for this JPEG object? */
6449 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6450 JPOOL_PERMANENT, sizeof *src);
6451 cinfo->src = (struct jpeg_source_mgr *) src;
6452 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6453 JPOOL_PERMANENT,
6454 JPEG_STDIO_BUFFER_SIZE);
6457 src->file = fp;
6458 src->finished = 0;
6459 src->mgr.init_source = our_common_init_source;
6460 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6461 src->mgr.skip_input_data = our_stdio_skip_input_data;
6462 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6463 src->mgr.term_source = our_common_term_source;
6464 src->mgr.bytes_in_buffer = 0;
6465 src->mgr.next_input_byte = NULL;
6469 /* Load image IMG for use on frame F. Patterned after example.c
6470 from the JPEG lib. */
6472 static bool
6473 jpeg_load_body (struct frame *f, struct image *img,
6474 struct my_jpeg_error_mgr *mgr)
6476 Lisp_Object file, specified_file;
6477 Lisp_Object specified_data;
6478 FILE *fp = NULL;
6479 JSAMPARRAY buffer;
6480 int row_stride, x, y;
6481 XImagePtr ximg = NULL;
6482 unsigned long *colors;
6483 int width, height;
6485 /* Open the JPEG file. */
6486 specified_file = image_spec_value (img->spec, QCfile, NULL);
6487 specified_data = image_spec_value (img->spec, QCdata, NULL);
6489 if (NILP (specified_data))
6491 file = x_find_image_file (specified_file);
6492 if (!STRINGP (file))
6494 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6495 return 0;
6498 fp = emacs_fopen (SSDATA (file), "rb");
6499 if (fp == NULL)
6501 image_error ("Cannot open `%s'", file, Qnil);
6502 return 0;
6505 else if (!STRINGP (specified_data))
6507 image_error ("Invalid image data `%s'", specified_data, Qnil);
6508 return 0;
6511 IF_LINT (mgr->fp = fp);
6513 /* Customize libjpeg's error handling to call my_error_exit when an
6514 error is detected. This function will perform a longjmp. */
6515 mgr->cinfo.err = fn_jpeg_std_error (&mgr->pub);
6516 mgr->pub.error_exit = my_error_exit;
6517 if (sys_setjmp (mgr->setjmp_buffer))
6519 switch (mgr->failure_code)
6521 case MY_JPEG_ERROR_EXIT:
6523 char buf[JMSG_LENGTH_MAX];
6524 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6525 image_error ("Error reading JPEG image `%s': %s", img->spec,
6526 build_string (buf));
6527 break;
6530 case MY_JPEG_INVALID_IMAGE_SIZE:
6531 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6532 break;
6534 case MY_JPEG_CANNOT_CREATE_X:
6535 break;
6538 /* Close the input file and destroy the JPEG object. */
6539 if (fp)
6540 fclose (fp);
6541 fn_jpeg_destroy_decompress (&mgr->cinfo);
6543 /* If we already have an XImage, free that. */
6544 x_destroy_x_image (ximg);
6546 /* Free pixmap and colors. */
6547 x_clear_image (f, img);
6548 return 0;
6551 /* Silence a bogus diagnostic; see GCC bug 54561. */
6552 IF_LINT (fp = mgr->fp);
6554 /* Create the JPEG decompression object. Let it read from fp.
6555 Read the JPEG image header. */
6556 fn_jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6558 if (NILP (specified_data))
6559 jpeg_file_src (&mgr->cinfo, fp);
6560 else
6561 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6562 SBYTES (specified_data));
6564 fn_jpeg_read_header (&mgr->cinfo, 1);
6566 /* Customize decompression so that color quantization will be used.
6567 Start decompression. */
6568 mgr->cinfo.quantize_colors = 1;
6569 fn_jpeg_start_decompress (&mgr->cinfo);
6570 width = img->width = mgr->cinfo.output_width;
6571 height = img->height = mgr->cinfo.output_height;
6573 if (!check_image_size (f, width, height))
6575 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6576 sys_longjmp (mgr->setjmp_buffer, 1);
6579 /* Create X image and pixmap. */
6580 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6582 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6583 sys_longjmp (mgr->setjmp_buffer, 1);
6586 /* Allocate colors. When color quantization is used,
6587 mgr->cinfo.actual_number_of_colors has been set with the number of
6588 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6589 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6590 No more than 255 colors will be generated. */
6592 int i, ir, ig, ib;
6594 if (mgr->cinfo.out_color_components > 2)
6595 ir = 0, ig = 1, ib = 2;
6596 else if (mgr->cinfo.out_color_components > 1)
6597 ir = 0, ig = 1, ib = 0;
6598 else
6599 ir = 0, ig = 0, ib = 0;
6601 /* Use the color table mechanism because it handles colors that
6602 cannot be allocated nicely. Such colors will be replaced with
6603 a default color, and we don't have to care about which colors
6604 can be freed safely, and which can't. */
6605 init_color_table ();
6606 colors = alloca (mgr->cinfo.actual_number_of_colors * sizeof *colors);
6608 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6610 /* Multiply RGB values with 255 because X expects RGB values
6611 in the range 0..0xffff. */
6612 int r = mgr->cinfo.colormap[ir][i] << 8;
6613 int g = mgr->cinfo.colormap[ig][i] << 8;
6614 int b = mgr->cinfo.colormap[ib][i] << 8;
6615 colors[i] = lookup_rgb_color (f, r, g, b);
6618 #ifdef COLOR_TABLE_SUPPORT
6619 /* Remember those colors actually allocated. */
6620 img->colors = colors_in_color_table (&img->ncolors);
6621 free_color_table ();
6622 #endif /* COLOR_TABLE_SUPPORT */
6625 /* Read pixels. */
6626 row_stride = width * mgr->cinfo.output_components;
6627 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6628 JPOOL_IMAGE, row_stride, 1);
6629 for (y = 0; y < height; ++y)
6631 fn_jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6632 for (x = 0; x < mgr->cinfo.output_width; ++x)
6633 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6636 /* Clean up. */
6637 fn_jpeg_finish_decompress (&mgr->cinfo);
6638 fn_jpeg_destroy_decompress (&mgr->cinfo);
6639 if (fp)
6640 fclose (fp);
6642 /* Maybe fill in the background field while we have ximg handy. */
6643 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6644 /* Casting avoids a GCC warning. */
6645 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6647 /* Put ximg into the image. */
6648 image_put_x_image (f, img, ximg, 0);
6649 return 1;
6652 static bool
6653 jpeg_load (struct frame *f, struct image *img)
6655 struct my_jpeg_error_mgr mgr;
6656 return jpeg_load_body (f, img, &mgr);
6659 #else /* HAVE_JPEG */
6661 #ifdef HAVE_NS
6662 static bool
6663 jpeg_load (struct frame *f, struct image *img)
6665 return ns_load_image (f, img,
6666 image_spec_value (img->spec, QCfile, NULL),
6667 image_spec_value (img->spec, QCdata, NULL));
6669 #endif /* HAVE_NS */
6671 #endif /* !HAVE_JPEG */
6675 /***********************************************************************
6676 TIFF
6677 ***********************************************************************/
6679 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6681 static bool tiff_image_p (Lisp_Object object);
6682 static bool tiff_load (struct frame *f, struct image *img);
6684 /* The symbol `tiff' identifying images of this type. */
6686 static Lisp_Object Qtiff;
6688 /* Indices of image specification fields in tiff_format, below. */
6690 enum tiff_keyword_index
6692 TIFF_TYPE,
6693 TIFF_DATA,
6694 TIFF_FILE,
6695 TIFF_ASCENT,
6696 TIFF_MARGIN,
6697 TIFF_RELIEF,
6698 TIFF_ALGORITHM,
6699 TIFF_HEURISTIC_MASK,
6700 TIFF_MASK,
6701 TIFF_BACKGROUND,
6702 TIFF_INDEX,
6703 TIFF_LAST
6706 /* Vector of image_keyword structures describing the format
6707 of valid user-defined image specifications. */
6709 static const struct image_keyword tiff_format[TIFF_LAST] =
6711 {":type", IMAGE_SYMBOL_VALUE, 1},
6712 {":data", IMAGE_STRING_VALUE, 0},
6713 {":file", IMAGE_STRING_VALUE, 0},
6714 {":ascent", IMAGE_ASCENT_VALUE, 0},
6715 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6716 {":relief", IMAGE_INTEGER_VALUE, 0},
6717 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6718 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6719 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6720 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6721 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6724 #if defined HAVE_NTGUI && defined WINDOWSNT
6725 static bool init_tiff_functions (void);
6726 #else
6727 #define init_tiff_functions NULL
6728 #endif
6730 /* Structure describing the image type `tiff'. */
6732 static struct image_type tiff_type =
6734 &Qtiff,
6735 tiff_image_p,
6736 tiff_load,
6737 x_clear_image,
6738 init_tiff_functions,
6739 NULL
6742 /* Return true if OBJECT is a valid TIFF image specification. */
6744 static bool
6745 tiff_image_p (Lisp_Object object)
6747 struct image_keyword fmt[TIFF_LAST];
6748 memcpy (fmt, tiff_format, sizeof fmt);
6750 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6751 return 0;
6753 /* Must specify either the :data or :file keyword. */
6754 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6757 #endif /* HAVE_TIFF || HAVE_NS */
6759 #ifdef HAVE_TIFF
6761 #include <tiffio.h>
6763 #ifdef WINDOWSNT
6765 /* TIFF library details. */
6766 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6767 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6768 DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6769 DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
6770 TIFFReadWriteProc, TIFFReadWriteProc,
6771 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6772 TIFFMapFileProc, TIFFUnmapFileProc));
6773 DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6774 DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6775 DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6776 DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6778 static bool
6779 init_tiff_functions (void)
6781 HMODULE library;
6783 if (!(library = w32_delayed_load (Qtiff)))
6784 return 0;
6786 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6787 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6788 LOAD_IMGLIB_FN (library, TIFFOpen);
6789 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6790 LOAD_IMGLIB_FN (library, TIFFGetField);
6791 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6792 LOAD_IMGLIB_FN (library, TIFFClose);
6793 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6794 return 1;
6797 #else
6799 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6800 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6801 #define fn_TIFFOpen TIFFOpen
6802 #define fn_TIFFClientOpen TIFFClientOpen
6803 #define fn_TIFFGetField TIFFGetField
6804 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6805 #define fn_TIFFClose TIFFClose
6806 #define fn_TIFFSetDirectory TIFFSetDirectory
6807 #endif /* WINDOWSNT */
6810 /* Reading from a memory buffer for TIFF images Based on the PNG
6811 memory source, but we have to provide a lot of extra functions.
6812 Blah.
6814 We really only need to implement read and seek, but I am not
6815 convinced that the TIFF library is smart enough not to destroy
6816 itself if we only hand it the function pointers we need to
6817 override. */
6819 typedef struct
6821 unsigned char *bytes;
6822 ptrdiff_t len;
6823 ptrdiff_t index;
6825 tiff_memory_source;
6827 static tsize_t
6828 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6830 tiff_memory_source *src = (tiff_memory_source *) data;
6832 size = min (size, src->len - src->index);
6833 memcpy (buf, src->bytes + src->index, size);
6834 src->index += size;
6835 return size;
6838 static tsize_t
6839 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6841 return -1;
6844 static toff_t
6845 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6847 tiff_memory_source *src = (tiff_memory_source *) data;
6848 ptrdiff_t idx;
6850 switch (whence)
6852 case SEEK_SET: /* Go from beginning of source. */
6853 idx = off;
6854 break;
6856 case SEEK_END: /* Go from end of source. */
6857 idx = src->len + off;
6858 break;
6860 case SEEK_CUR: /* Go from current position. */
6861 idx = src->index + off;
6862 break;
6864 default: /* Invalid `whence'. */
6865 return -1;
6868 if (idx > src->len || idx < 0)
6869 return -1;
6871 src->index = idx;
6872 return src->index;
6875 static int
6876 tiff_close_memory (thandle_t data)
6878 /* NOOP */
6879 return 0;
6882 static int
6883 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6885 /* It is already _IN_ memory. */
6886 return 0;
6889 static void
6890 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6892 /* We don't need to do this. */
6895 static toff_t
6896 tiff_size_of_memory (thandle_t data)
6898 return ((tiff_memory_source *) data)->len;
6901 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6902 compiler error compiling tiff_handler, see Bugzilla bug #17406
6903 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6904 this function as external works around that problem. */
6905 #if defined (__MINGW32__) && __GNUC__ == 3
6906 # define MINGW_STATIC
6907 #else
6908 # define MINGW_STATIC static
6909 #endif
6911 MINGW_STATIC void
6912 tiff_handler (const char *, const char *, const char *, va_list)
6913 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6914 MINGW_STATIC void
6915 tiff_handler (const char *log_format, const char *title,
6916 const char *format, va_list ap)
6918 /* doprnt is not suitable here, as TIFF handlers are called from
6919 libtiff and are passed arbitrary printf directives. Instead, use
6920 vsnprintf, taking care to be portable to nonstandard environments
6921 where vsnprintf returns -1 on buffer overflow. Since it's just a
6922 log entry, it's OK to truncate it. */
6923 char buf[4000];
6924 int len = vsnprintf (buf, sizeof buf, format, ap);
6925 add_to_log (log_format, build_string (title),
6926 make_string (buf, max (0, min (len, sizeof buf - 1))));
6928 #undef MINGW_STATIC
6930 static void tiff_error_handler (const char *, const char *, va_list)
6931 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6932 static void
6933 tiff_error_handler (const char *title, const char *format, va_list ap)
6935 tiff_handler ("TIFF error: %s %s", title, format, ap);
6939 static void tiff_warning_handler (const char *, const char *, va_list)
6940 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6941 static void
6942 tiff_warning_handler (const char *title, const char *format, va_list ap)
6944 tiff_handler ("TIFF warning: %s %s", title, format, ap);
6948 /* Load TIFF image IMG for use on frame F. Value is true if
6949 successful. */
6951 static bool
6952 tiff_load (struct frame *f, struct image *img)
6954 Lisp_Object file, specified_file;
6955 Lisp_Object specified_data;
6956 TIFF *tiff;
6957 int width, height, x, y, count;
6958 uint32 *buf;
6959 int rc;
6960 XImagePtr ximg;
6961 tiff_memory_source memsrc;
6962 Lisp_Object image;
6964 specified_file = image_spec_value (img->spec, QCfile, NULL);
6965 specified_data = image_spec_value (img->spec, QCdata, NULL);
6967 fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6968 fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
6970 if (NILP (specified_data))
6972 /* Read from a file */
6973 file = x_find_image_file (specified_file);
6974 if (!STRINGP (file))
6976 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6977 return 0;
6979 #ifdef WINDOWSNT
6980 file = ansi_encode_filename (file);
6981 #endif
6983 /* Try to open the image file. */
6984 tiff = fn_TIFFOpen (SSDATA (file), "r");
6985 if (tiff == NULL)
6987 image_error ("Cannot open `%s'", file, Qnil);
6988 return 0;
6991 else
6993 if (!STRINGP (specified_data))
6995 image_error ("Invalid image data `%s'", specified_data, Qnil);
6996 return 0;
6999 /* Memory source! */
7000 memsrc.bytes = SDATA (specified_data);
7001 memsrc.len = SBYTES (specified_data);
7002 memsrc.index = 0;
7004 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7005 tiff_read_from_memory,
7006 tiff_write_from_memory,
7007 tiff_seek_in_memory,
7008 tiff_close_memory,
7009 tiff_size_of_memory,
7010 tiff_mmap_memory,
7011 tiff_unmap_memory);
7013 if (!tiff)
7015 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7016 return 0;
7020 image = image_spec_value (img->spec, QCindex, NULL);
7021 if (INTEGERP (image))
7023 EMACS_INT ino = XFASTINT (image);
7024 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7025 && fn_TIFFSetDirectory (tiff, ino)))
7027 image_error ("Invalid image number `%s' in image `%s'",
7028 image, img->spec);
7029 fn_TIFFClose (tiff);
7030 return 0;
7034 /* Get width and height of the image, and allocate a raster buffer
7035 of width x height 32-bit values. */
7036 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7037 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7039 if (!check_image_size (f, width, height))
7041 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7042 fn_TIFFClose (tiff);
7043 return 0;
7046 /* Create the X image and pixmap. */
7047 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7048 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7049 &ximg, 0)))
7051 fn_TIFFClose (tiff);
7052 return 0;
7055 buf = xmalloc (sizeof *buf * width * height);
7057 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7059 /* Count the number of images in the file. */
7060 for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
7061 continue;
7063 if (count > 1)
7064 img->lisp_data = Fcons (Qcount,
7065 Fcons (make_number (count),
7066 img->lisp_data));
7068 fn_TIFFClose (tiff);
7069 if (!rc)
7071 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7072 xfree (buf);
7073 return 0;
7076 /* Initialize the color table. */
7077 init_color_table ();
7079 /* Process the pixel raster. Origin is in the lower-left corner. */
7080 for (y = 0; y < height; ++y)
7082 uint32 *row = buf + y * width;
7084 for (x = 0; x < width; ++x)
7086 uint32 abgr = row[x];
7087 int r = TIFFGetR (abgr) << 8;
7088 int g = TIFFGetG (abgr) << 8;
7089 int b = TIFFGetB (abgr) << 8;
7090 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7094 #ifdef COLOR_TABLE_SUPPORT
7095 /* Remember the colors allocated for the image. Free the color table. */
7096 img->colors = colors_in_color_table (&img->ncolors);
7097 free_color_table ();
7098 #endif /* COLOR_TABLE_SUPPORT */
7100 img->width = width;
7101 img->height = height;
7103 /* Maybe fill in the background field while we have ximg handy. */
7104 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7105 /* Casting avoids a GCC warning on W32. */
7106 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7108 /* Put ximg into the image. */
7109 image_put_x_image (f, img, ximg, 0);
7110 xfree (buf);
7112 return 1;
7115 #else /* HAVE_TIFF */
7117 #ifdef HAVE_NS
7118 static bool
7119 tiff_load (struct frame *f, struct image *img)
7121 return ns_load_image (f, img,
7122 image_spec_value (img->spec, QCfile, NULL),
7123 image_spec_value (img->spec, QCdata, NULL));
7125 #endif /* HAVE_NS */
7127 #endif /* !HAVE_TIFF */
7131 /***********************************************************************
7133 ***********************************************************************/
7135 #if defined (HAVE_GIF) || defined (HAVE_NS)
7137 static bool gif_image_p (Lisp_Object object);
7138 static bool gif_load (struct frame *f, struct image *img);
7139 static void gif_clear_image (struct frame *f, struct image *img);
7141 /* The symbol `gif' identifying images of this type. */
7143 static Lisp_Object Qgif;
7145 /* Indices of image specification fields in gif_format, below. */
7147 enum gif_keyword_index
7149 GIF_TYPE,
7150 GIF_DATA,
7151 GIF_FILE,
7152 GIF_ASCENT,
7153 GIF_MARGIN,
7154 GIF_RELIEF,
7155 GIF_ALGORITHM,
7156 GIF_HEURISTIC_MASK,
7157 GIF_MASK,
7158 GIF_IMAGE,
7159 GIF_BACKGROUND,
7160 GIF_LAST
7163 /* Vector of image_keyword structures describing the format
7164 of valid user-defined image specifications. */
7166 static const struct image_keyword gif_format[GIF_LAST] =
7168 {":type", IMAGE_SYMBOL_VALUE, 1},
7169 {":data", IMAGE_STRING_VALUE, 0},
7170 {":file", IMAGE_STRING_VALUE, 0},
7171 {":ascent", IMAGE_ASCENT_VALUE, 0},
7172 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7173 {":relief", IMAGE_INTEGER_VALUE, 0},
7174 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7175 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7176 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7177 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7178 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7181 #if defined HAVE_NTGUI && defined WINDOWSNT
7182 static bool init_gif_functions (void);
7183 #else
7184 #define init_gif_functions NULL
7185 #endif
7187 /* Structure describing the image type `gif'. */
7189 static struct image_type gif_type =
7191 &Qgif,
7192 gif_image_p,
7193 gif_load,
7194 gif_clear_image,
7195 init_gif_functions,
7196 NULL
7199 /* Free X resources of GIF image IMG which is used on frame F. */
7201 static void
7202 gif_clear_image (struct frame *f, struct image *img)
7204 img->lisp_data = Qnil;
7205 x_clear_image (f, img);
7208 /* Return true if OBJECT is a valid GIF image specification. */
7210 static bool
7211 gif_image_p (Lisp_Object object)
7213 struct image_keyword fmt[GIF_LAST];
7214 memcpy (fmt, gif_format, sizeof fmt);
7216 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7217 return 0;
7219 /* Must specify either the :data or :file keyword. */
7220 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7223 #endif /* HAVE_GIF */
7225 #ifdef HAVE_GIF
7227 #if defined (HAVE_NTGUI)
7229 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7230 Undefine before redefining to avoid a preprocessor warning. */
7231 #ifdef DrawText
7232 #undef DrawText
7233 #endif
7234 /* avoid conflict with QuickdrawText.h */
7235 #define DrawText gif_DrawText
7236 #include <gif_lib.h>
7237 #undef DrawText
7239 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7240 #ifndef GIFLIB_MINOR
7241 #define GIFLIB_MINOR 0
7242 #endif
7243 #ifndef GIFLIB_RELEASE
7244 #define GIFLIB_RELEASE 0
7245 #endif
7247 #else /* HAVE_NTGUI */
7249 #include <gif_lib.h>
7251 #endif /* HAVE_NTGUI */
7253 /* Giflib before 5.0 didn't define these macros. */
7254 #ifndef GIFLIB_MAJOR
7255 #define GIFLIB_MAJOR 4
7256 #endif
7258 #ifdef WINDOWSNT
7260 /* GIF library details. */
7261 DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7262 DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7263 #if GIFLIB_MAJOR < 5
7264 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7265 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
7266 #else
7267 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7268 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7269 DEF_IMGLIB_FN (char *, GifErrorString, (int));
7270 #endif
7272 static bool
7273 init_gif_functions (void)
7275 HMODULE library;
7277 if (!(library = w32_delayed_load (Qgif)))
7278 return 0;
7280 LOAD_IMGLIB_FN (library, DGifCloseFile);
7281 LOAD_IMGLIB_FN (library, DGifSlurp);
7282 LOAD_IMGLIB_FN (library, DGifOpen);
7283 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7284 #if GIFLIB_MAJOR >= 5
7285 LOAD_IMGLIB_FN (library, GifErrorString);
7286 #endif
7287 return 1;
7290 #else
7292 #define fn_DGifCloseFile DGifCloseFile
7293 #define fn_DGifSlurp DGifSlurp
7294 #define fn_DGifOpen DGifOpen
7295 #define fn_DGifOpenFileName DGifOpenFileName
7296 #if 5 <= GIFLIB_MAJOR
7297 # define fn_GifErrorString GifErrorString
7298 #endif
7300 #endif /* WINDOWSNT */
7302 /* Reading a GIF image from memory
7303 Based on the PNG memory stuff to a certain extent. */
7305 typedef struct
7307 unsigned char *bytes;
7308 ptrdiff_t len;
7309 ptrdiff_t index;
7311 gif_memory_source;
7313 /* Make the current memory source available to gif_read_from_memory.
7314 It's done this way because not all versions of libungif support
7315 a UserData field in the GifFileType structure. */
7316 static gif_memory_source *current_gif_memory_src;
7318 static int
7319 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7321 gif_memory_source *src = current_gif_memory_src;
7323 if (len > src->len - src->index)
7324 return -1;
7326 memcpy (buf, src->bytes + src->index, len);
7327 src->index += len;
7328 return len;
7332 /* Load GIF image IMG for use on frame F. Value is true if
7333 successful. */
7335 static const int interlace_start[] = {0, 4, 2, 1};
7336 static const int interlace_increment[] = {8, 8, 4, 2};
7338 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7340 static bool
7341 gif_load (struct frame *f, struct image *img)
7343 Lisp_Object file;
7344 int rc, width, height, x, y, i, j;
7345 XImagePtr ximg;
7346 ColorMapObject *gif_color_map;
7347 unsigned long pixel_colors[256];
7348 GifFileType *gif;
7349 gif_memory_source memsrc;
7350 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7351 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7352 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7353 unsigned long bgcolor = 0;
7354 EMACS_INT idx;
7355 #if GIFLIB_MAJOR >= 5
7356 int gif_err;
7357 #endif
7359 if (NILP (specified_data))
7361 file = x_find_image_file (specified_file);
7362 if (!STRINGP (file))
7364 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7365 return 0;
7367 #ifdef WINDOWSNT
7368 file = ansi_encode_filename (file);
7369 #endif
7371 /* Open the GIF file. */
7372 #if GIFLIB_MAJOR < 5
7373 gif = fn_DGifOpenFileName (SSDATA (file));
7374 if (gif == NULL)
7376 image_error ("Cannot open `%s'", file, Qnil);
7377 return 0;
7379 #else
7380 gif = fn_DGifOpenFileName (SSDATA (file), &gif_err);
7381 if (gif == NULL)
7383 image_error ("Cannot open `%s': %s",
7384 file, build_string (fn_GifErrorString (gif_err)));
7385 return 0;
7387 #endif
7389 else
7391 if (!STRINGP (specified_data))
7393 image_error ("Invalid image data `%s'", specified_data, Qnil);
7394 return 0;
7397 /* Read from memory! */
7398 current_gif_memory_src = &memsrc;
7399 memsrc.bytes = SDATA (specified_data);
7400 memsrc.len = SBYTES (specified_data);
7401 memsrc.index = 0;
7403 #if GIFLIB_MAJOR < 5
7404 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
7405 if (!gif)
7407 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7408 return 0;
7410 #else
7411 gif = fn_DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7412 if (!gif)
7414 image_error ("Cannot open memory source `%s': %s",
7415 img->spec, build_string (fn_GifErrorString (gif_err)));
7416 return 0;
7418 #endif
7421 /* Before reading entire contents, check the declared image size. */
7422 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7424 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7425 fn_DGifCloseFile (gif);
7426 return 0;
7429 /* Read entire contents. */
7430 rc = fn_DGifSlurp (gif);
7431 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7433 image_error ("Error reading `%s'", img->spec, Qnil);
7434 fn_DGifCloseFile (gif);
7435 return 0;
7438 /* Which sub-image are we to display? */
7440 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7441 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7442 if (idx < 0 || idx >= gif->ImageCount)
7444 image_error ("Invalid image number `%s' in image `%s'",
7445 image_number, img->spec);
7446 fn_DGifCloseFile (gif);
7447 return 0;
7451 width = img->width = gif->SWidth;
7452 height = img->height = gif->SHeight;
7454 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7455 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7456 img->corners[BOT_CORNER]
7457 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7458 img->corners[RIGHT_CORNER]
7459 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7461 if (!check_image_size (f, width, height))
7463 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7464 fn_DGifCloseFile (gif);
7465 return 0;
7468 /* Check that the selected subimages fit. It's not clear whether
7469 the GIF spec requires this, but Emacs can crash if they don't fit. */
7470 for (j = 0; j <= idx; ++j)
7472 struct SavedImage *subimage = gif->SavedImages + j;
7473 int subimg_width = subimage->ImageDesc.Width;
7474 int subimg_height = subimage->ImageDesc.Height;
7475 int subimg_top = subimage->ImageDesc.Top;
7476 int subimg_left = subimage->ImageDesc.Left;
7477 if (! (0 <= subimg_width && 0 <= subimg_height
7478 && 0 <= subimg_top && subimg_top <= height - subimg_height
7479 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7481 image_error ("Subimage does not fit in image", Qnil, Qnil);
7482 fn_DGifCloseFile (gif);
7483 return 0;
7487 /* Create the X image and pixmap. */
7488 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7490 fn_DGifCloseFile (gif);
7491 return 0;
7494 /* Clear the part of the screen image not covered by the image.
7495 Full animated GIF support requires more here (see the gif89 spec,
7496 disposal methods). Let's simply assume that the part not covered
7497 by a sub-image is in the frame's background color. */
7498 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7499 for (x = 0; x < width; ++x)
7500 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7502 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7503 for (x = 0; x < width; ++x)
7504 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7506 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7508 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7509 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7510 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7511 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7514 /* Read the GIF image into the X image. */
7516 /* FIXME: With the current implementation, loading an animated gif
7517 is quadratic in the number of animation frames, since each frame
7518 is a separate struct image. We must provide a way for a single
7519 gif_load call to construct and save all animation frames. */
7521 init_color_table ();
7522 if (STRINGP (specified_bg))
7523 bgcolor = x_alloc_image_color (f, img, specified_bg,
7524 FRAME_BACKGROUND_PIXEL (f));
7525 for (j = 0; j <= idx; ++j)
7527 /* We use a local variable `raster' here because RasterBits is a
7528 char *, which invites problems with bytes >= 0x80. */
7529 struct SavedImage *subimage = gif->SavedImages + j;
7530 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7531 int transparency_color_index = -1;
7532 int disposal = 0;
7533 int subimg_width = subimage->ImageDesc.Width;
7534 int subimg_height = subimage->ImageDesc.Height;
7535 int subimg_top = subimage->ImageDesc.Top;
7536 int subimg_left = subimage->ImageDesc.Left;
7538 /* Find the Graphic Control Extension block for this sub-image.
7539 Extract the disposal method and transparency color. */
7540 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7542 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7544 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7545 && extblock->ByteCount == 4
7546 && extblock->Bytes[0] & 1)
7548 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7549 to background". Treat any other value like 2. */
7550 disposal = (extblock->Bytes[0] >> 2) & 7;
7551 transparency_color_index = (unsigned char) extblock->Bytes[3];
7552 break;
7556 /* We can't "keep in place" the first subimage. */
7557 if (j == 0)
7558 disposal = 2;
7560 /* For disposal == 0, the spec says "No disposal specified. The
7561 decoder is not required to take any action." In practice, it
7562 seems we need to treat this like "keep in place", see e.g.
7563 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7564 if (disposal == 0)
7565 disposal = 1;
7567 /* Allocate subimage colors. */
7568 memset (pixel_colors, 0, sizeof pixel_colors);
7569 gif_color_map = subimage->ImageDesc.ColorMap;
7570 if (!gif_color_map)
7571 gif_color_map = gif->SColorMap;
7573 if (gif_color_map)
7574 for (i = 0; i < gif_color_map->ColorCount; ++i)
7576 if (transparency_color_index == i)
7577 pixel_colors[i] = STRINGP (specified_bg)
7578 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7579 else
7581 int r = gif_color_map->Colors[i].Red << 8;
7582 int g = gif_color_map->Colors[i].Green << 8;
7583 int b = gif_color_map->Colors[i].Blue << 8;
7584 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7588 /* Apply the pixel values. */
7589 if (gif->SavedImages[j].ImageDesc.Interlace)
7591 int row, pass;
7593 for (y = 0, row = interlace_start[0], pass = 0;
7594 y < subimg_height;
7595 y++, row += interlace_increment[pass])
7597 while (subimg_height <= row)
7598 row = interlace_start[++pass];
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, row + subimg_top,
7605 pixel_colors[c]);
7609 else
7611 for (y = 0; y < subimg_height; ++y)
7612 for (x = 0; x < subimg_width; ++x)
7614 int c = raster[y * subimg_width + x];
7615 if (transparency_color_index != c || disposal != 1)
7616 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7617 pixel_colors[c]);
7622 #ifdef COLOR_TABLE_SUPPORT
7623 img->colors = colors_in_color_table (&img->ncolors);
7624 free_color_table ();
7625 #endif /* COLOR_TABLE_SUPPORT */
7627 /* Save GIF image extension data for `image-metadata'.
7628 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7629 img->lisp_data = Qnil;
7630 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7632 int delay = 0;
7633 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7634 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7635 /* Append (... FUNCTION "BYTES") */
7637 img->lisp_data
7638 = Fcons (make_number (ext->Function),
7639 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7640 img->lisp_data));
7641 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7642 && ext->ByteCount == 4)
7644 delay = ext->Bytes[2] << CHAR_BIT;
7645 delay |= ext->Bytes[1];
7648 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7649 if (delay)
7650 img->lisp_data
7651 = Fcons (Qdelay,
7652 Fcons (make_float (delay / 100.0),
7653 img->lisp_data));
7656 if (gif->ImageCount > 1)
7657 img->lisp_data = Fcons (Qcount,
7658 Fcons (make_number (gif->ImageCount),
7659 img->lisp_data));
7661 fn_DGifCloseFile (gif);
7663 /* Maybe fill in the background field while we have ximg handy. */
7664 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7665 /* Casting avoids a GCC warning. */
7666 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7668 /* Put ximg into the image. */
7669 image_put_x_image (f, img, ximg, 0);
7671 return 1;
7674 #else /* !HAVE_GIF */
7676 #ifdef HAVE_NS
7677 static bool
7678 gif_load (struct frame *f, struct image *img)
7680 return ns_load_image (f, img,
7681 image_spec_value (img->spec, QCfile, NULL),
7682 image_spec_value (img->spec, QCdata, NULL));
7684 #endif /* HAVE_NS */
7686 #endif /* HAVE_GIF */
7689 #ifdef HAVE_IMAGEMAGICK
7691 /***********************************************************************
7692 ImageMagick
7693 ***********************************************************************/
7695 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
7696 safely rounded and clipped to int range. */
7698 static int
7699 scale_image_size (int size, size_t divisor, size_t multiplier)
7701 if (divisor != 0)
7703 double s = size;
7704 double scaled = s * multiplier / divisor + 0.5;
7705 if (scaled < INT_MAX)
7706 return scaled;
7708 return INT_MAX;
7711 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
7712 Use SPEC to deduce the size. Store the desired size into
7713 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
7714 static void
7715 compute_image_size (size_t width, size_t height,
7716 Lisp_Object spec,
7717 int *d_width, int *d_height)
7719 Lisp_Object value;
7720 int desired_width, desired_height;
7722 /* If width and/or height is set in the display spec assume we want
7723 to scale to those values. If either h or w is unspecified, the
7724 unspecified should be calculated from the specified to preserve
7725 aspect ratio. */
7726 value = image_spec_value (spec, QCwidth, NULL);
7727 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7728 value = image_spec_value (spec, QCheight, NULL);
7729 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7731 if (desired_width == -1)
7733 value = image_spec_value (spec, QCmax_width, NULL);
7734 if (NATNUMP (value))
7736 int max_width = min (XFASTINT (value), INT_MAX);
7737 if (max_width < width)
7739 /* The image is wider than :max-width. */
7740 desired_width = max_width;
7741 if (desired_height == -1)
7743 desired_height = scale_image_size (desired_width,
7744 width, height);
7745 value = image_spec_value (spec, QCmax_height, NULL);
7746 if (NATNUMP (value))
7748 int max_height = min (XFASTINT (value), INT_MAX);
7749 if (max_height < desired_height)
7751 desired_height = max_height;
7752 desired_width = scale_image_size (desired_height,
7753 height, width);
7761 if (desired_height == -1)
7763 value = image_spec_value (spec, QCmax_height, NULL);
7764 if (NATNUMP (value))
7766 int max_height = min (XFASTINT (value), INT_MAX);
7767 if (max_height < height)
7768 desired_height = max_height;
7772 if (desired_width != -1 && desired_height == -1)
7773 /* w known, calculate h. */
7774 desired_height = scale_image_size (desired_width, width, height);
7776 if (desired_width == -1 && desired_height != -1)
7777 /* h known, calculate w. */
7778 desired_width = scale_image_size (desired_height, height, width);
7780 *d_width = desired_width;
7781 *d_height = desired_height;
7784 static Lisp_Object Qimagemagick;
7786 static bool imagemagick_image_p (Lisp_Object);
7787 static bool imagemagick_load (struct frame *, struct image *);
7788 static void imagemagick_clear_image (struct frame *, struct image *);
7790 /* Indices of image specification fields in imagemagick_format. */
7792 enum imagemagick_keyword_index
7794 IMAGEMAGICK_TYPE,
7795 IMAGEMAGICK_DATA,
7796 IMAGEMAGICK_FILE,
7797 IMAGEMAGICK_ASCENT,
7798 IMAGEMAGICK_MARGIN,
7799 IMAGEMAGICK_RELIEF,
7800 IMAGEMAGICK_ALGORITHM,
7801 IMAGEMAGICK_HEURISTIC_MASK,
7802 IMAGEMAGICK_MASK,
7803 IMAGEMAGICK_BACKGROUND,
7804 IMAGEMAGICK_HEIGHT,
7805 IMAGEMAGICK_WIDTH,
7806 IMAGEMAGICK_MAX_HEIGHT,
7807 IMAGEMAGICK_MAX_WIDTH,
7808 IMAGEMAGICK_FORMAT,
7809 IMAGEMAGICK_ROTATION,
7810 IMAGEMAGICK_CROP,
7811 IMAGEMAGICK_LAST
7814 /* Vector of image_keyword structures describing the format
7815 of valid user-defined image specifications. */
7817 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7819 {":type", IMAGE_SYMBOL_VALUE, 1},
7820 {":data", IMAGE_STRING_VALUE, 0},
7821 {":file", IMAGE_STRING_VALUE, 0},
7822 {":ascent", IMAGE_ASCENT_VALUE, 0},
7823 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7824 {":relief", IMAGE_INTEGER_VALUE, 0},
7825 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7826 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7827 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7828 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7829 {":height", IMAGE_INTEGER_VALUE, 0},
7830 {":width", IMAGE_INTEGER_VALUE, 0},
7831 {":max-height", IMAGE_INTEGER_VALUE, 0},
7832 {":max-width", IMAGE_INTEGER_VALUE, 0},
7833 {":format", IMAGE_SYMBOL_VALUE, 0},
7834 {":rotation", IMAGE_NUMBER_VALUE, 0},
7835 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7838 #if defined HAVE_NTGUI && defined WINDOWSNT
7839 static bool init_imagemagick_functions (void);
7840 #else
7841 #define init_imagemagick_functions NULL
7842 #endif
7844 /* Structure describing the image type for any image handled via
7845 ImageMagick. */
7847 static struct image_type imagemagick_type =
7849 &Qimagemagick,
7850 imagemagick_image_p,
7851 imagemagick_load,
7852 imagemagick_clear_image,
7853 init_imagemagick_functions,
7854 NULL
7857 /* Free X resources of imagemagick image IMG which is used on frame F. */
7859 static void
7860 imagemagick_clear_image (struct frame *f,
7861 struct image *img)
7863 x_clear_image (f, img);
7866 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7867 this by calling parse_image_spec and supplying the keywords that
7868 identify the IMAGEMAGICK format. */
7870 static bool
7871 imagemagick_image_p (Lisp_Object object)
7873 struct image_keyword fmt[IMAGEMAGICK_LAST];
7874 memcpy (fmt, imagemagick_format, sizeof fmt);
7876 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7877 return 0;
7879 /* Must specify either the :data or :file keyword. */
7880 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7883 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7884 Therefore rename the function so it doesn't collide with ImageMagick. */
7885 #define DrawRectangle DrawRectangleGif
7886 #include <wand/MagickWand.h>
7888 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7889 Emacs seems to work fine with the hidden version, so unhide it. */
7890 #include <magick/version.h>
7891 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7892 extern WandExport void PixelGetMagickColor (const PixelWand *,
7893 MagickPixelPacket *);
7894 #endif
7896 /* Log ImageMagick error message.
7897 Useful when a ImageMagick function returns the status `MagickFalse'. */
7899 static void
7900 imagemagick_error (MagickWand *wand)
7902 char *description;
7903 ExceptionType severity;
7905 description = MagickGetException (wand, &severity);
7906 image_error ("ImageMagick error: %s",
7907 build_string (description),
7908 Qnil);
7909 description = (char *) MagickRelinquishMemory (description);
7912 /* Possibly give ImageMagick some extra help to determine the image
7913 type by supplying a "dummy" filename based on the Content-Type. */
7915 static char *
7916 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
7918 Lisp_Object symbol = intern ("image-format-suffixes");
7919 Lisp_Object val = find_symbol_value (symbol);
7920 Lisp_Object format;
7922 if (! CONSP (val))
7923 return NULL;
7925 format = image_spec_value (spec, intern (":format"), NULL);
7926 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
7927 if (! STRINGP (val))
7928 return NULL;
7930 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
7931 as ImageMagick would ignore the extra bytes anyway. */
7932 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
7933 return hint_buffer;
7936 /* Animated images (e.g., GIF89a) are composed from one "master image"
7937 (which is the first one, and then there's a number of images that
7938 follow. If following images have non-transparent colors, these are
7939 composed "on top" of the master image. So, in general, one has to
7940 compute ann the preceding images to be able to display a particular
7941 sub-image.
7943 Computing all the preceding images is too slow, so we maintain a
7944 cache of previously computed images. We have to maintain a cache
7945 separate from the image cache, because the images may be scaled
7946 before display. */
7948 struct animation_cache
7950 MagickWand *wand;
7951 int index;
7952 struct timespec update_time;
7953 struct animation_cache *next;
7954 char signature[FLEXIBLE_ARRAY_MEMBER];
7957 static struct animation_cache *animation_cache = NULL;
7959 static struct animation_cache *
7960 imagemagick_create_cache (char *signature)
7962 struct animation_cache *cache
7963 = xmalloc (offsetof (struct animation_cache, signature)
7964 + strlen (signature) + 1);
7965 cache->wand = 0;
7966 cache->index = 0;
7967 cache->next = 0;
7968 strcpy (cache->signature, signature);
7969 return cache;
7972 /* Discard cached images that haven't been used for a minute. */
7973 static void
7974 imagemagick_prune_animation_cache (void)
7976 struct animation_cache **pcache = &animation_cache;
7977 struct timespec old = timespec_sub (current_timespec (),
7978 make_timespec (60, 0));
7980 while (*pcache)
7982 struct animation_cache *cache = *pcache;
7983 if (timespec_cmp (old, cache->update_time) <= 0)
7984 pcache = &cache->next;
7985 else
7987 if (cache->wand)
7988 DestroyMagickWand (cache->wand);
7989 *pcache = cache->next;
7990 xfree (cache);
7995 static struct animation_cache *
7996 imagemagick_get_animation_cache (MagickWand *wand)
7998 char *signature = MagickGetImageSignature (wand);
7999 struct animation_cache *cache;
8000 struct animation_cache **pcache = &animation_cache;
8002 imagemagick_prune_animation_cache ();
8004 while (1)
8006 cache = *pcache;
8007 if (! cache)
8009 *pcache = cache = imagemagick_create_cache (signature);
8010 break;
8012 if (strcmp (signature, cache->signature) == 0)
8013 break;
8014 pcache = &cache->next;
8017 DestroyString (signature);
8018 cache->update_time = current_timespec ();
8019 return cache;
8022 static MagickWand *
8023 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8025 int i;
8026 MagickWand *composite_wand;
8027 size_t dest_width, dest_height;
8028 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8030 MagickSetIteratorIndex (super_wand, 0);
8032 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8034 composite_wand = MagickGetImage (super_wand);
8035 if (cache->wand)
8036 DestroyMagickWand (cache->wand);
8038 else
8039 composite_wand = cache->wand;
8041 dest_width = MagickGetImageWidth (composite_wand);
8042 dest_height = MagickGetImageHeight (composite_wand);
8044 for (i = max (1, cache->index + 1); i <= ino; i++)
8046 MagickWand *sub_wand;
8047 PixelIterator *source_iterator, *dest_iterator;
8048 PixelWand **source, **dest;
8049 size_t source_width, source_height;
8050 ssize_t source_left, source_top;
8051 MagickPixelPacket pixel;
8052 DisposeType dispose;
8053 ptrdiff_t lines = 0;
8055 MagickSetIteratorIndex (super_wand, i);
8056 sub_wand = MagickGetImage (super_wand);
8058 MagickGetImagePage (sub_wand, &source_width, &source_height,
8059 &source_left, &source_top);
8061 /* This flag says how to handle transparent pixels. */
8062 dispose = MagickGetImageDispose (sub_wand);
8064 source_iterator = NewPixelIterator (sub_wand);
8065 if (! source_iterator)
8067 DestroyMagickWand (composite_wand);
8068 DestroyMagickWand (sub_wand);
8069 cache->wand = NULL;
8070 image_error ("Imagemagick pixel iterator creation failed",
8071 Qnil, Qnil);
8072 return NULL;
8075 dest_iterator = NewPixelIterator (composite_wand);
8076 if (! dest_iterator)
8078 DestroyMagickWand (composite_wand);
8079 DestroyMagickWand (sub_wand);
8080 DestroyPixelIterator (source_iterator);
8081 cache->wand = NULL;
8082 image_error ("Imagemagick pixel iterator creation failed",
8083 Qnil, Qnil);
8084 return NULL;
8087 /* The sub-image may not start at origin, so move the destination
8088 iterator to where the sub-image should start. */
8089 if (source_top > 0)
8091 PixelSetIteratorRow (dest_iterator, source_top);
8092 lines = source_top;
8095 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8096 != NULL)
8098 ptrdiff_t x;
8100 /* Sanity check. This shouldn't happen, but apparently
8101 does in some pictures. */
8102 if (++lines >= dest_height)
8103 break;
8105 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8106 for (x = 0; x < source_width; x++)
8108 /* Sanity check. This shouldn't happen, but apparently
8109 also does in some pictures. */
8110 if (x + source_left > dest_width - 1)
8111 break;
8112 /* Normally we only copy over non-transparent pixels,
8113 but if the disposal method is "Background", then we
8114 copy over all pixels. */
8115 if (dispose == BackgroundDispose ||
8116 PixelGetAlpha (source[x]))
8118 PixelGetMagickColor (source[x], &pixel);
8119 PixelSetMagickColor (dest[x + source_left], &pixel);
8122 PixelSyncIterator (dest_iterator);
8125 DestroyPixelIterator (source_iterator);
8126 DestroyPixelIterator (dest_iterator);
8127 DestroyMagickWand (sub_wand);
8130 /* Cache a copy for the next iteration. The current wand will be
8131 destroyed by the caller. */
8132 cache->wand = CloneMagickWand (composite_wand);
8133 cache->index = ino;
8135 return composite_wand;
8139 /* Helper function for imagemagick_load, which does the actual loading
8140 given contents and size, apart from frame and image structures,
8141 passed from imagemagick_load. Uses librimagemagick to do most of
8142 the image processing.
8144 F is a pointer to the Emacs frame; IMG to the image structure to
8145 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8146 be parsed; SIZE is the number of bytes of data; and FILENAME is
8147 either the file name or the image data.
8149 Return true if successful. */
8151 static bool
8152 imagemagick_load_image (struct frame *f, struct image *img,
8153 unsigned char *contents, unsigned int size,
8154 char *filename)
8156 size_t width, height;
8157 MagickBooleanType status;
8158 XImagePtr ximg;
8159 int x, y;
8160 MagickWand *image_wand;
8161 PixelIterator *iterator;
8162 PixelWand **pixels, *bg_wand = NULL;
8163 MagickPixelPacket pixel;
8164 Lisp_Object image;
8165 Lisp_Object value;
8166 Lisp_Object crop;
8167 EMACS_INT ino;
8168 int desired_width, desired_height;
8169 double rotation;
8170 int pixelwidth;
8171 char hint_buffer[MaxTextExtent];
8172 char *filename_hint = NULL;
8174 /* Handle image index for image types who can contain more than one image.
8175 Interface :index is same as for GIF. First we "ping" the image to see how
8176 many sub-images it contains. Pinging is faster than loading the image to
8177 find out things about it. */
8179 /* Initialize the imagemagick environment. */
8180 MagickWandGenesis ();
8181 image = image_spec_value (img->spec, QCindex, NULL);
8182 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8183 image_wand = NewMagickWand ();
8185 if (filename)
8186 status = MagickReadImage (image_wand, filename);
8187 else
8189 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8190 MagickSetFilename (image_wand, filename_hint);
8191 status = MagickReadImageBlob (image_wand, contents, size);
8194 if (status == MagickFalse)
8196 imagemagick_error (image_wand);
8197 DestroyMagickWand (image_wand);
8198 return 0;
8201 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8203 image_error ("Invalid image number `%s' in image `%s'",
8204 image, img->spec);
8205 DestroyMagickWand (image_wand);
8206 return 0;
8209 if (MagickGetNumberImages (image_wand) > 1)
8210 img->lisp_data =
8211 Fcons (Qcount,
8212 Fcons (make_number (MagickGetNumberImages (image_wand)),
8213 img->lisp_data));
8215 /* If we have an animated image, get the new wand based on the
8216 "super-wand". */
8217 if (MagickGetNumberImages (image_wand) > 1)
8219 MagickWand *super_wand = image_wand;
8220 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8221 if (! image_wand)
8222 image_wand = super_wand;
8223 else
8224 DestroyMagickWand (super_wand);
8227 /* Retrieve the frame's background color, for use later. */
8229 XColor bgcolor;
8230 Lisp_Object specified_bg;
8232 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8233 if (!STRINGP (specified_bg)
8234 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8236 #ifndef HAVE_NS
8237 bgcolor.pixel = FRAME_BACKGROUND_PIXEL (f);
8238 x_query_color (f, &bgcolor);
8239 #else
8240 ns_query_color (FRAME_BACKGROUND_COLOR (f), &bgcolor, 1);
8241 #endif
8244 bg_wand = NewPixelWand ();
8245 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8246 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8247 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8250 compute_image_size (MagickGetImageWidth (image_wand),
8251 MagickGetImageHeight (image_wand),
8252 img->spec, &desired_width, &desired_height);
8254 if (desired_width != -1 && desired_height != -1)
8256 status = MagickScaleImage (image_wand, desired_width, desired_height);
8257 if (status == MagickFalse)
8259 image_error ("Imagemagick scale failed", Qnil, Qnil);
8260 imagemagick_error (image_wand);
8261 goto imagemagick_error;
8265 /* crop behaves similar to image slicing in Emacs but is more memory
8266 efficient. */
8267 crop = image_spec_value (img->spec, QCcrop, NULL);
8269 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8271 /* After some testing, it seems MagickCropImage is the fastest crop
8272 function in ImageMagick. This crop function seems to do less copying
8273 than the alternatives, but it still reads the entire image into memory
8274 before cropping, which is apparently difficult to avoid when using
8275 imagemagick. */
8276 size_t crop_width = XINT (XCAR (crop));
8277 crop = XCDR (crop);
8278 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8280 size_t crop_height = XINT (XCAR (crop));
8281 crop = XCDR (crop);
8282 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8284 ssize_t crop_x = XINT (XCAR (crop));
8285 crop = XCDR (crop);
8286 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8288 ssize_t crop_y = XINT (XCAR (crop));
8289 MagickCropImage (image_wand, crop_width, crop_height,
8290 crop_x, crop_y);
8296 /* Furthermore :rotation. we need background color and angle for
8297 rotation. */
8299 TODO background handling for rotation specified_bg =
8300 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8301 (specified_bg). */
8302 value = image_spec_value (img->spec, QCrotation, NULL);
8303 if (FLOATP (value))
8305 rotation = extract_float (value);
8306 status = MagickRotateImage (image_wand, bg_wand, rotation);
8307 if (status == MagickFalse)
8309 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
8310 imagemagick_error (image_wand);
8311 goto imagemagick_error;
8315 /* Set the canvas background color to the frame or specified
8316 background, and flatten the image. Note: as of ImageMagick
8317 6.6.0, SVG image transparency is not handled properly
8318 (e.g. etc/images/splash.svg shows a white background always). */
8320 MagickWand *new_wand;
8321 MagickSetImageBackgroundColor (image_wand, bg_wand);
8322 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8323 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8324 #else
8325 new_wand = MagickFlattenImages (image_wand);
8326 #endif
8327 DestroyMagickWand (image_wand);
8328 image_wand = new_wand;
8331 /* Finally we are done manipulating the image. Figure out the
8332 resulting width/height and transfer ownership to Emacs. */
8333 height = MagickGetImageHeight (image_wand);
8334 width = MagickGetImageWidth (image_wand);
8336 if (! (width <= INT_MAX && height <= INT_MAX
8337 && check_image_size (f, width, height)))
8339 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8340 goto imagemagick_error;
8343 /* We can now get a valid pixel buffer from the imagemagick file, if all
8344 went ok. */
8346 init_color_table ();
8348 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8349 if (imagemagick_render_type != 0)
8351 /* Magicexportimage is normally faster than pixelpushing. This
8352 method is also well tested. Some aspects of this method are
8353 ad-hoc and needs to be more researched. */
8354 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8355 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8356 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8357 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8358 &ximg, 0))
8360 #ifdef COLOR_TABLE_SUPPORT
8361 free_color_table ();
8362 #endif
8363 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8364 goto imagemagick_error;
8367 /* Oddly, the below code doesn't seem to work:*/
8368 /* switch(ximg->bitmap_unit){ */
8369 /* case 8: */
8370 /* pixelwidth=CharPixel; */
8371 /* break; */
8372 /* case 16: */
8373 /* pixelwidth=ShortPixel; */
8374 /* break; */
8375 /* case 32: */
8376 /* pixelwidth=LongPixel; */
8377 /* break; */
8378 /* } */
8380 Here im just guessing the format of the bitmap.
8381 happens to work fine for:
8382 - bw djvu images
8383 on rgb display.
8384 seems about 3 times as fast as pixel pushing(not carefully measured)
8386 pixelwidth = CharPixel; /*??? TODO figure out*/
8387 MagickExportImagePixels (image_wand, 0, 0, width, height,
8388 exportdepth, pixelwidth, ximg->data);
8390 else
8391 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8393 size_t image_height;
8395 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8396 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8397 &ximg, 0))
8399 #ifdef COLOR_TABLE_SUPPORT
8400 free_color_table ();
8401 #endif
8402 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8403 goto imagemagick_error;
8406 /* Copy imagemagick image to x with primitive yet robust pixel
8407 pusher loop. This has been tested a lot with many different
8408 images. */
8410 /* Copy pixels from the imagemagick image structure to the x image map. */
8411 iterator = NewPixelIterator (image_wand);
8412 if (! iterator)
8414 #ifdef COLOR_TABLE_SUPPORT
8415 free_color_table ();
8416 #endif
8417 x_destroy_x_image (ximg);
8418 image_error ("Imagemagick pixel iterator creation failed",
8419 Qnil, Qnil);
8420 goto imagemagick_error;
8423 image_height = MagickGetImageHeight (image_wand);
8424 for (y = 0; y < image_height; y++)
8426 pixels = PixelGetNextIteratorRow (iterator, &width);
8427 if (! pixels)
8428 break;
8429 for (x = 0; x < (long) width; x++)
8431 PixelGetMagickColor (pixels[x], &pixel);
8432 XPutPixel (ximg, x, y,
8433 lookup_rgb_color (f,
8434 pixel.red,
8435 pixel.green,
8436 pixel.blue));
8439 DestroyPixelIterator (iterator);
8442 #ifdef COLOR_TABLE_SUPPORT
8443 /* Remember colors allocated for this image. */
8444 img->colors = colors_in_color_table (&img->ncolors);
8445 free_color_table ();
8446 #endif /* COLOR_TABLE_SUPPORT */
8448 img->width = width;
8449 img->height = height;
8451 /* Put ximg into the image. */
8452 image_put_x_image (f, img, ximg, 0);
8454 /* Final cleanup. image_wand should be the only resource left. */
8455 DestroyMagickWand (image_wand);
8456 if (bg_wand) DestroyPixelWand (bg_wand);
8458 /* `MagickWandTerminus' terminates the imagemagick environment. */
8459 MagickWandTerminus ();
8461 return 1;
8463 imagemagick_error:
8464 DestroyMagickWand (image_wand);
8465 if (bg_wand) DestroyPixelWand (bg_wand);
8467 MagickWandTerminus ();
8468 /* TODO more cleanup. */
8469 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
8470 return 0;
8474 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8475 successful. this function will go into the imagemagick_type structure, and
8476 the prototype thus needs to be compatible with that structure. */
8478 static bool
8479 imagemagick_load (struct frame *f, struct image *img)
8481 bool success_p = 0;
8482 Lisp_Object file_name;
8484 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8485 file_name = image_spec_value (img->spec, QCfile, NULL);
8486 if (STRINGP (file_name))
8488 Lisp_Object file;
8490 file = x_find_image_file (file_name);
8491 if (!STRINGP (file))
8493 image_error ("Cannot find image file `%s'", file_name, Qnil);
8494 return 0;
8496 #ifdef WINDOWSNT
8497 file = ansi_encode_filename (file);
8498 #endif
8499 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8501 /* Else its not a file, its a lisp object. Load the image from a
8502 lisp object rather than a file. */
8503 else
8505 Lisp_Object data;
8507 data = image_spec_value (img->spec, QCdata, NULL);
8508 if (!STRINGP (data))
8510 image_error ("Invalid image data `%s'", data, Qnil);
8511 return 0;
8513 success_p = imagemagick_load_image (f, img, SDATA (data),
8514 SBYTES (data), NULL);
8517 return success_p;
8520 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8521 doc: /* Return a list of image types supported by ImageMagick.
8522 Each entry in this list is a symbol named after an ImageMagick format
8523 tag. See the ImageMagick manual for a list of ImageMagick formats and
8524 their descriptions (http://www.imagemagick.org/script/formats.php).
8525 You can also try the shell command: `identify -list format'.
8527 Note that ImageMagick recognizes many file-types that Emacs does not
8528 recognize as images, such as C. See `imagemagick-types-enable'
8529 and `imagemagick-types-inhibit'. */)
8530 (void)
8532 Lisp_Object typelist = Qnil;
8533 size_t numf = 0;
8534 ExceptionInfo ex;
8535 char **imtypes;
8536 size_t i;
8537 Lisp_Object Qimagemagicktype;
8539 GetExceptionInfo(&ex);
8540 imtypes = GetMagickList ("*", &numf, &ex);
8541 DestroyExceptionInfo(&ex);
8543 for (i = 0; i < numf; i++)
8545 Qimagemagicktype = intern (imtypes[i]);
8546 typelist = Fcons (Qimagemagicktype, typelist);
8548 return Fnreverse (typelist);
8551 #endif /* defined (HAVE_IMAGEMAGICK) */
8555 /***********************************************************************
8557 ***********************************************************************/
8559 #if defined (HAVE_RSVG)
8561 /* Function prototypes. */
8563 static bool svg_image_p (Lisp_Object object);
8564 static bool svg_load (struct frame *f, struct image *img);
8566 static bool svg_load_image (struct frame *, struct image *,
8567 unsigned char *, ptrdiff_t);
8569 /* The symbol `svg' identifying images of this type. */
8571 static Lisp_Object Qsvg;
8573 /* Indices of image specification fields in svg_format, below. */
8575 enum svg_keyword_index
8577 SVG_TYPE,
8578 SVG_DATA,
8579 SVG_FILE,
8580 SVG_ASCENT,
8581 SVG_MARGIN,
8582 SVG_RELIEF,
8583 SVG_ALGORITHM,
8584 SVG_HEURISTIC_MASK,
8585 SVG_MASK,
8586 SVG_BACKGROUND,
8587 SVG_LAST
8590 /* Vector of image_keyword structures describing the format
8591 of valid user-defined image specifications. */
8593 static const struct image_keyword svg_format[SVG_LAST] =
8595 {":type", IMAGE_SYMBOL_VALUE, 1},
8596 {":data", IMAGE_STRING_VALUE, 0},
8597 {":file", IMAGE_STRING_VALUE, 0},
8598 {":ascent", IMAGE_ASCENT_VALUE, 0},
8599 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8600 {":relief", IMAGE_INTEGER_VALUE, 0},
8601 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8602 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8603 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8604 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8607 #if defined HAVE_NTGUI && defined WINDOWSNT
8608 static bool init_svg_functions (void);
8609 #else
8610 #define init_svg_functions NULL
8611 #endif
8613 /* Structure describing the image type `svg'. Its the same type of
8614 structure defined for all image formats, handled by emacs image
8615 functions. See struct image_type in dispextern.h. */
8617 static struct image_type svg_type =
8619 &Qsvg,
8620 svg_image_p,
8621 svg_load,
8622 x_clear_image,
8623 init_svg_functions,
8624 NULL
8628 /* Return true if OBJECT is a valid SVG image specification. Do
8629 this by calling parse_image_spec and supplying the keywords that
8630 identify the SVG format. */
8632 static bool
8633 svg_image_p (Lisp_Object object)
8635 struct image_keyword fmt[SVG_LAST];
8636 memcpy (fmt, svg_format, sizeof fmt);
8638 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8639 return 0;
8641 /* Must specify either the :data or :file keyword. */
8642 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8645 #include <librsvg/rsvg.h>
8647 #ifdef WINDOWSNT
8649 /* SVG library functions. */
8650 DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new, (void));
8651 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions, (RsvgHandle *, RsvgDimensionData *));
8652 DEF_IMGLIB_FN (gboolean, rsvg_handle_write, (RsvgHandle *, const guchar *, gsize, GError **));
8653 DEF_IMGLIB_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8654 DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8655 DEF_IMGLIB_FN (void *, rsvg_handle_set_size_callback, (RsvgHandle *, RsvgSizeFunc, gpointer, GDestroyNotify));
8657 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8658 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8659 DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8660 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8661 DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8662 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8663 DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8664 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8666 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8667 DEF_IMGLIB_FN (void, g_type_init, (void));
8668 #endif
8669 DEF_IMGLIB_FN (void, g_object_unref, (gpointer));
8670 DEF_IMGLIB_FN (void, g_error_free, (GError *));
8672 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8674 static bool
8675 init_svg_functions (void)
8677 HMODULE library, gdklib, glib, gobject;
8679 if (!(glib = w32_delayed_load (Qglib))
8680 || !(gobject = w32_delayed_load (Qgobject))
8681 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
8682 || !(library = w32_delayed_load (Qsvg)))
8683 return 0;
8685 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8686 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8687 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8688 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8689 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8691 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8692 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8693 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8694 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8695 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8696 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8697 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8698 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8700 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8701 LOAD_IMGLIB_FN (gobject, g_type_init);
8702 #endif
8703 LOAD_IMGLIB_FN (gobject, g_object_unref);
8704 LOAD_IMGLIB_FN (glib, g_error_free);
8706 return 1;
8709 #else
8710 /* The following aliases for library functions allow dynamic loading
8711 to be used on some platforms. */
8712 #define fn_rsvg_handle_new rsvg_handle_new
8713 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8714 #define fn_rsvg_handle_write rsvg_handle_write
8715 #define fn_rsvg_handle_close rsvg_handle_close
8716 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8718 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8719 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8720 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8721 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8722 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8723 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8724 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8725 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8727 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8728 #define fn_g_type_init g_type_init
8729 #endif
8730 #define fn_g_object_unref g_object_unref
8731 #define fn_g_error_free g_error_free
8732 #endif /* !WINDOWSNT */
8734 /* Load SVG image IMG for use on frame F. Value is true if
8735 successful. */
8737 static bool
8738 svg_load (struct frame *f, struct image *img)
8740 bool success_p = 0;
8741 Lisp_Object file_name;
8743 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8744 file_name = image_spec_value (img->spec, QCfile, NULL);
8745 if (STRINGP (file_name))
8747 Lisp_Object file;
8748 unsigned char *contents;
8749 ptrdiff_t size;
8751 file = x_find_image_file (file_name);
8752 if (!STRINGP (file))
8754 image_error ("Cannot find image file `%s'", file_name, Qnil);
8755 return 0;
8758 /* Read the entire file into memory. */
8759 contents = slurp_file (SSDATA (file), &size);
8760 if (contents == NULL)
8762 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8763 return 0;
8765 /* If the file was slurped into memory properly, parse it. */
8766 success_p = svg_load_image (f, img, contents, size);
8767 xfree (contents);
8769 /* Else its not a file, its a lisp object. Load the image from a
8770 lisp object rather than a file. */
8771 else
8773 Lisp_Object data;
8775 data = image_spec_value (img->spec, QCdata, NULL);
8776 if (!STRINGP (data))
8778 image_error ("Invalid image data `%s'", data, Qnil);
8779 return 0;
8781 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8784 return success_p;
8787 /* svg_load_image is a helper function for svg_load, which does the
8788 actual loading given contents and size, apart from frame and image
8789 structures, passed from svg_load.
8791 Uses librsvg to do most of the image processing.
8793 Returns true when successful. */
8794 static bool
8795 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8796 struct image *img, /* Pointer to emacs image structure. */
8797 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8798 ptrdiff_t size) /* Size of data in bytes. */
8800 RsvgHandle *rsvg_handle;
8801 RsvgDimensionData dimension_data;
8802 GError *err = NULL;
8803 GdkPixbuf *pixbuf;
8804 int width;
8805 int height;
8806 const guint8 *pixels;
8807 int rowstride;
8808 XImagePtr ximg;
8809 Lisp_Object specified_bg;
8810 XColor background;
8811 int x;
8812 int y;
8814 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8815 /* g_type_init is a glib function that must be called prior to
8816 using gnome type library functions (obsolete since 2.36.0). */
8817 fn_g_type_init ();
8818 #endif
8820 /* Make a handle to a new rsvg object. */
8821 rsvg_handle = fn_rsvg_handle_new ();
8823 /* Parse the contents argument and fill in the rsvg_handle. */
8824 fn_rsvg_handle_write (rsvg_handle, contents, size, &err);
8825 if (err) goto rsvg_error;
8827 /* The parsing is complete, rsvg_handle is ready to used, close it
8828 for further writes. */
8829 fn_rsvg_handle_close (rsvg_handle, &err);
8830 if (err) goto rsvg_error;
8832 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8833 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8835 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8836 goto rsvg_error;
8839 /* We can now get a valid pixel buffer from the svg file, if all
8840 went ok. */
8841 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8842 if (!pixbuf) goto rsvg_error;
8843 fn_g_object_unref (rsvg_handle);
8845 /* Extract some meta data from the svg handle. */
8846 width = fn_gdk_pixbuf_get_width (pixbuf);
8847 height = fn_gdk_pixbuf_get_height (pixbuf);
8848 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8849 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8851 /* Validate the svg meta data. */
8852 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8853 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8854 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8855 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8857 /* Try to create a x pixmap to hold the svg pixmap. */
8858 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
8860 fn_g_object_unref (pixbuf);
8861 return 0;
8864 init_color_table ();
8866 /* Handle alpha channel by combining the image with a background
8867 color. */
8868 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8869 if (!STRINGP (specified_bg)
8870 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
8872 #ifndef HAVE_NS
8873 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8874 x_query_color (f, &background);
8875 #else
8876 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8877 #endif
8880 /* SVG pixmaps specify transparency in the last byte, so right
8881 shift 8 bits to get rid of it, since emacs doesn't support
8882 transparency. */
8883 background.red >>= 8;
8884 background.green >>= 8;
8885 background.blue >>= 8;
8887 /* This loop handles opacity values, since Emacs assumes
8888 non-transparent images. Each pixel must be "flattened" by
8889 calculating the resulting color, given the transparency of the
8890 pixel, and the image background color. */
8891 for (y = 0; y < height; ++y)
8893 for (x = 0; x < width; ++x)
8895 int red;
8896 int green;
8897 int blue;
8898 int opacity;
8900 red = *pixels++;
8901 green = *pixels++;
8902 blue = *pixels++;
8903 opacity = *pixels++;
8905 red = ((red * opacity)
8906 + (background.red * ((1 << 8) - opacity)));
8907 green = ((green * opacity)
8908 + (background.green * ((1 << 8) - opacity)));
8909 blue = ((blue * opacity)
8910 + (background.blue * ((1 << 8) - opacity)));
8912 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8915 pixels += rowstride - 4 * width;
8918 #ifdef COLOR_TABLE_SUPPORT
8919 /* Remember colors allocated for this image. */
8920 img->colors = colors_in_color_table (&img->ncolors);
8921 free_color_table ();
8922 #endif /* COLOR_TABLE_SUPPORT */
8924 fn_g_object_unref (pixbuf);
8926 img->width = width;
8927 img->height = height;
8929 /* Maybe fill in the background field while we have ximg handy.
8930 Casting avoids a GCC warning. */
8931 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8933 /* Put ximg into the image. */
8934 image_put_x_image (f, img, ximg, 0);
8936 return 1;
8938 rsvg_error:
8939 fn_g_object_unref (rsvg_handle);
8940 /* FIXME: Use error->message so the user knows what is the actual
8941 problem with the image. */
8942 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8943 fn_g_error_free (err);
8944 return 0;
8947 #endif /* defined (HAVE_RSVG) */
8952 /***********************************************************************
8953 Ghostscript
8954 ***********************************************************************/
8956 #ifdef HAVE_X_WINDOWS
8957 #define HAVE_GHOSTSCRIPT 1
8958 #endif /* HAVE_X_WINDOWS */
8960 #ifdef HAVE_GHOSTSCRIPT
8962 static bool gs_image_p (Lisp_Object object);
8963 static bool gs_load (struct frame *f, struct image *img);
8964 static void gs_clear_image (struct frame *f, struct image *img);
8966 /* Keyword symbols. */
8968 static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8970 /* Indices of image specification fields in gs_format, below. */
8972 enum gs_keyword_index
8974 GS_TYPE,
8975 GS_PT_WIDTH,
8976 GS_PT_HEIGHT,
8977 GS_FILE,
8978 GS_LOADER,
8979 GS_BOUNDING_BOX,
8980 GS_ASCENT,
8981 GS_MARGIN,
8982 GS_RELIEF,
8983 GS_ALGORITHM,
8984 GS_HEURISTIC_MASK,
8985 GS_MASK,
8986 GS_BACKGROUND,
8987 GS_LAST
8990 /* Vector of image_keyword structures describing the format
8991 of valid user-defined image specifications. */
8993 static const struct image_keyword gs_format[GS_LAST] =
8995 {":type", IMAGE_SYMBOL_VALUE, 1},
8996 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8997 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8998 {":file", IMAGE_STRING_VALUE, 1},
8999 {":loader", IMAGE_FUNCTION_VALUE, 0},
9000 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9001 {":ascent", IMAGE_ASCENT_VALUE, 0},
9002 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9003 {":relief", IMAGE_INTEGER_VALUE, 0},
9004 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9005 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9006 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9007 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9010 /* Structure describing the image type `ghostscript'. */
9012 static struct image_type gs_type =
9014 &Qpostscript,
9015 gs_image_p,
9016 gs_load,
9017 gs_clear_image,
9018 NULL,
9019 NULL
9023 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9025 static void
9026 gs_clear_image (struct frame *f, struct image *img)
9028 x_clear_image (f, img);
9032 /* Return true if OBJECT is a valid Ghostscript image
9033 specification. */
9035 static bool
9036 gs_image_p (Lisp_Object object)
9038 struct image_keyword fmt[GS_LAST];
9039 Lisp_Object tem;
9040 int i;
9042 memcpy (fmt, gs_format, sizeof fmt);
9044 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9045 return 0;
9047 /* Bounding box must be a list or vector containing 4 integers. */
9048 tem = fmt[GS_BOUNDING_BOX].value;
9049 if (CONSP (tem))
9051 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9052 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9053 return 0;
9054 if (!NILP (tem))
9055 return 0;
9057 else if (VECTORP (tem))
9059 if (ASIZE (tem) != 4)
9060 return 0;
9061 for (i = 0; i < 4; ++i)
9062 if (!INTEGERP (AREF (tem, i)))
9063 return 0;
9065 else
9066 return 0;
9068 return 1;
9072 /* Load Ghostscript image IMG for use on frame F. Value is true
9073 if successful. */
9075 static bool
9076 gs_load (struct frame *f, struct image *img)
9078 uprintmax_t printnum1, printnum2;
9079 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9080 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9081 Lisp_Object frame;
9082 double in_width, in_height;
9083 Lisp_Object pixel_colors = Qnil;
9085 /* Compute pixel size of pixmap needed from the given size in the
9086 image specification. Sizes in the specification are in pt. 1 pt
9087 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9088 info. */
9089 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9090 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9091 in_width *= FRAME_RES_X (f);
9092 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9093 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9094 in_height *= FRAME_RES_Y (f);
9096 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9097 && check_image_size (f, in_width, in_height)))
9099 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
9100 return 0;
9102 img->width = in_width;
9103 img->height = in_height;
9105 /* Create the pixmap. */
9106 eassert (img->pixmap == NO_PIXMAP);
9108 if (x_check_image_size (0, img->width, img->height))
9110 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9111 block_input ();
9112 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9113 img->width, img->height,
9114 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9115 unblock_input ();
9118 if (!img->pixmap)
9120 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
9121 return 0;
9124 /* Call the loader to fill the pixmap. It returns a process object
9125 if successful. We do not record_unwind_protect here because
9126 other places in redisplay like calling window scroll functions
9127 don't either. Let the Lisp loader use `unwind-protect' instead. */
9128 printnum1 = FRAME_X_WINDOW (f);
9129 printnum2 = img->pixmap;
9130 window_and_pixmap_id
9131 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9133 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9134 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9135 pixel_colors
9136 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9138 XSETFRAME (frame, f);
9139 loader = image_spec_value (img->spec, QCloader, NULL);
9140 if (NILP (loader))
9141 loader = intern ("gs-load-image");
9143 img->lisp_data = call6 (loader, frame, img->spec,
9144 make_number (img->width),
9145 make_number (img->height),
9146 window_and_pixmap_id,
9147 pixel_colors);
9148 return PROCESSP (img->lisp_data);
9152 /* Kill the Ghostscript process that was started to fill PIXMAP on
9153 frame F. Called from XTread_socket when receiving an event
9154 telling Emacs that Ghostscript has finished drawing. */
9156 void
9157 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9159 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9160 int class;
9161 ptrdiff_t i;
9162 struct image *img;
9164 /* Find the image containing PIXMAP. */
9165 for (i = 0; i < c->used; ++i)
9166 if (c->images[i]->pixmap == pixmap)
9167 break;
9169 /* Should someone in between have cleared the image cache, for
9170 instance, give up. */
9171 if (i == c->used)
9172 return;
9174 /* Kill the GS process. We should have found PIXMAP in the image
9175 cache and its image should contain a process object. */
9176 img = c->images[i];
9177 eassert (PROCESSP (img->lisp_data));
9178 Fkill_process (img->lisp_data, Qnil);
9179 img->lisp_data = Qnil;
9181 #if defined (HAVE_X_WINDOWS)
9183 /* On displays with a mutable colormap, figure out the colors
9184 allocated for the image by looking at the pixels of an XImage for
9185 img->pixmap. */
9186 class = FRAME_X_VISUAL (f)->class;
9187 if (class != StaticColor && class != StaticGray && class != TrueColor)
9189 XImagePtr ximg;
9191 block_input ();
9193 /* Try to get an XImage for img->pixmep. */
9194 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9195 0, 0, img->width, img->height, ~0, ZPixmap);
9196 if (ximg)
9198 int x, y;
9200 /* Initialize the color table. */
9201 init_color_table ();
9203 /* For each pixel of the image, look its color up in the
9204 color table. After having done so, the color table will
9205 contain an entry for each color used by the image. */
9206 for (y = 0; y < img->height; ++y)
9207 for (x = 0; x < img->width; ++x)
9209 unsigned long pixel = XGetPixel (ximg, x, y);
9210 lookup_pixel_color (f, pixel);
9213 /* Record colors in the image. Free color table and XImage. */
9214 #ifdef COLOR_TABLE_SUPPORT
9215 img->colors = colors_in_color_table (&img->ncolors);
9216 free_color_table ();
9217 #endif
9218 XDestroyImage (ximg);
9220 #if 0 /* This doesn't seem to be the case. If we free the colors
9221 here, we get a BadAccess later in x_clear_image when
9222 freeing the colors. */
9223 /* We have allocated colors once, but Ghostscript has also
9224 allocated colors on behalf of us. So, to get the
9225 reference counts right, free them once. */
9226 if (img->ncolors)
9227 x_free_colors (f, img->colors, img->ncolors);
9228 #endif
9230 else
9231 image_error ("Cannot get X image of `%s'; colors will not be freed",
9232 img->spec, Qnil);
9234 unblock_input ();
9236 #endif /* HAVE_X_WINDOWS */
9238 /* Now that we have the pixmap, compute mask and transform the
9239 image if requested. */
9240 block_input ();
9241 postprocess_image (f, img);
9242 unblock_input ();
9245 #endif /* HAVE_GHOSTSCRIPT */
9248 /***********************************************************************
9249 Tests
9250 ***********************************************************************/
9252 #ifdef GLYPH_DEBUG
9254 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9255 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9256 (Lisp_Object spec)
9258 return valid_image_p (spec) ? Qt : Qnil;
9262 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
9263 (Lisp_Object spec)
9265 ptrdiff_t id = -1;
9267 if (valid_image_p (spec))
9268 id = lookup_image (SELECTED_FRAME (), spec);
9270 debug_print (spec);
9271 return make_number (id);
9274 #endif /* GLYPH_DEBUG */
9277 /***********************************************************************
9278 Initialization
9279 ***********************************************************************/
9281 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9282 doc: /* Initialize image library implementing image type TYPE.
9283 Return non-nil if TYPE is a supported image type.
9285 If image libraries are loaded dynamically (currently only the case on
9286 MS-Windows), load the library for TYPE if it is not yet loaded, using
9287 the library file(s) specified by `dynamic-library-alist'. */)
9288 (Lisp_Object type)
9290 return lookup_image_type (type) ? Qt : Qnil;
9293 /* Look up image type TYPE, and return a pointer to its image_type
9294 structure. Return 0 if TYPE is not a known image type. */
9296 static struct image_type *
9297 lookup_image_type (Lisp_Object type)
9299 /* Types pbm and xbm are built-in and always available. */
9300 if (EQ (type, Qpbm))
9301 return define_image_type (&pbm_type);
9303 if (EQ (type, Qxbm))
9304 return define_image_type (&xbm_type);
9306 #if defined (HAVE_XPM) || defined (HAVE_NS)
9307 if (EQ (type, Qxpm))
9308 return define_image_type (&xpm_type);
9309 #endif
9311 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9312 if (EQ (type, Qjpeg))
9313 return define_image_type (&jpeg_type);
9314 #endif
9316 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9317 if (EQ (type, Qtiff))
9318 return define_image_type (&tiff_type);
9319 #endif
9321 #if defined (HAVE_GIF) || defined (HAVE_NS)
9322 if (EQ (type, Qgif))
9323 return define_image_type (&gif_type);
9324 #endif
9326 #if defined (HAVE_PNG) || defined (HAVE_NS)
9327 if (EQ (type, Qpng))
9328 return define_image_type (&png_type);
9329 #endif
9331 #if defined (HAVE_RSVG)
9332 if (EQ (type, Qsvg))
9333 return define_image_type (&svg_type);
9334 #endif
9336 #if defined (HAVE_IMAGEMAGICK)
9337 if (EQ (type, Qimagemagick))
9338 return define_image_type (&imagemagick_type);
9339 #endif
9341 #ifdef HAVE_GHOSTSCRIPT
9342 if (EQ (type, Qpostscript))
9343 return define_image_type (&gs_type);
9344 #endif
9346 return NULL;
9349 /* Reset image_types before dumping.
9350 Called from Fdump_emacs. */
9352 void
9353 reset_image_types (void)
9355 while (image_types)
9357 struct image_type *next = image_types->next;
9358 xfree (image_types);
9359 image_types = next;
9363 void
9364 syms_of_image (void)
9366 /* Initialize this only once; it will be reset before dumping. */
9367 image_types = NULL;
9369 /* Must be defined now because we're going to update it below, while
9370 defining the supported image types. */
9371 DEFVAR_LISP ("image-types", Vimage_types,
9372 doc: /* List of potentially supported image types.
9373 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9374 To check whether it is really supported, use `image-type-available-p'. */);
9375 Vimage_types = Qnil;
9377 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9378 doc: /* Maximum size of images.
9379 Emacs will not load an image into memory if its pixel width or
9380 pixel height exceeds this limit.
9382 If the value is an integer, it directly specifies the maximum
9383 image height and width, measured in pixels. If it is a floating
9384 point number, it specifies the maximum image height and width
9385 as a ratio to the frame height and width. If the value is
9386 non-numeric, there is no explicit limit on the size of images. */);
9387 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9389 DEFSYM (Qcount, "count");
9390 DEFSYM (Qextension_data, "extension-data");
9391 DEFSYM (Qdelay, "delay");
9393 DEFSYM (QCascent, ":ascent");
9394 DEFSYM (QCmargin, ":margin");
9395 DEFSYM (QCrelief, ":relief");
9396 DEFSYM (QCconversion, ":conversion");
9397 DEFSYM (QCcolor_symbols, ":color-symbols");
9398 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9399 DEFSYM (QCindex, ":index");
9400 DEFSYM (QCgeometry, ":geometry");
9401 DEFSYM (QCcrop, ":crop");
9402 DEFSYM (QCrotation, ":rotation");
9403 DEFSYM (QCmatrix, ":matrix");
9404 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9405 DEFSYM (QCmask, ":mask");
9407 DEFSYM (Qlaplace, "laplace");
9408 DEFSYM (Qemboss, "emboss");
9409 DEFSYM (Qedge_detection, "edge-detection");
9410 DEFSYM (Qheuristic, "heuristic");
9412 DEFSYM (Qpostscript, "postscript");
9413 DEFSYM (QCmax_width, ":max-width");
9414 DEFSYM (QCmax_height, ":max-height");
9415 #ifdef HAVE_GHOSTSCRIPT
9416 ADD_IMAGE_TYPE (Qpostscript);
9417 DEFSYM (QCloader, ":loader");
9418 DEFSYM (QCbounding_box, ":bounding-box");
9419 DEFSYM (QCpt_width, ":pt-width");
9420 DEFSYM (QCpt_height, ":pt-height");
9421 #endif /* HAVE_GHOSTSCRIPT */
9423 #ifdef HAVE_NTGUI
9424 DEFSYM (Qlibpng_version, "libpng-version");
9425 Fset (Qlibpng_version,
9426 #if HAVE_PNG
9427 make_number (PNG_LIBPNG_VER)
9428 #else
9429 make_number (-1)
9430 #endif
9432 DEFSYM (Qlibgif_version, "libgif-version");
9433 Fset (Qlibgif_version,
9434 #ifdef HAVE_GIF
9435 make_number (GIFLIB_MAJOR * 10000
9436 + GIFLIB_MINOR * 100
9437 + GIFLIB_RELEASE)
9438 #else
9439 make_number (-1)
9440 #endif
9442 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9443 Fset (Qlibjpeg_version,
9444 #if HAVE_JPEG
9445 make_number (JPEG_LIB_VERSION)
9446 #else
9447 make_number (-1)
9448 #endif
9450 #endif
9452 DEFSYM (Qpbm, "pbm");
9453 ADD_IMAGE_TYPE (Qpbm);
9455 DEFSYM (Qxbm, "xbm");
9456 ADD_IMAGE_TYPE (Qxbm);
9458 #if defined (HAVE_XPM) || defined (HAVE_NS)
9459 DEFSYM (Qxpm, "xpm");
9460 ADD_IMAGE_TYPE (Qxpm);
9461 #endif
9463 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9464 DEFSYM (Qjpeg, "jpeg");
9465 ADD_IMAGE_TYPE (Qjpeg);
9466 #endif
9468 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9469 DEFSYM (Qtiff, "tiff");
9470 ADD_IMAGE_TYPE (Qtiff);
9471 #endif
9473 #if defined (HAVE_GIF) || defined (HAVE_NS)
9474 DEFSYM (Qgif, "gif");
9475 ADD_IMAGE_TYPE (Qgif);
9476 #endif
9478 #if defined (HAVE_PNG) || defined (HAVE_NS)
9479 DEFSYM (Qpng, "png");
9480 ADD_IMAGE_TYPE (Qpng);
9481 #endif
9483 #if defined (HAVE_IMAGEMAGICK)
9484 DEFSYM (Qimagemagick, "imagemagick");
9485 ADD_IMAGE_TYPE (Qimagemagick);
9486 #endif
9488 #if defined (HAVE_RSVG)
9489 DEFSYM (Qsvg, "svg");
9490 ADD_IMAGE_TYPE (Qsvg);
9491 #ifdef HAVE_NTGUI
9492 /* Other libraries used directly by svg code. */
9493 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9494 DEFSYM (Qglib, "glib");
9495 DEFSYM (Qgobject, "gobject");
9496 #endif /* HAVE_NTGUI */
9497 #endif /* HAVE_RSVG */
9499 defsubr (&Sinit_image_library);
9500 #ifdef HAVE_IMAGEMAGICK
9501 defsubr (&Simagemagick_types);
9502 #endif
9503 defsubr (&Sclear_image_cache);
9504 defsubr (&Simage_flush);
9505 defsubr (&Simage_size);
9506 defsubr (&Simage_mask_p);
9507 defsubr (&Simage_metadata);
9509 #ifdef GLYPH_DEBUG
9510 defsubr (&Simagep);
9511 defsubr (&Slookup_image);
9512 #endif
9514 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9515 doc: /* Non-nil means always draw a cross over disabled images.
9516 Disabled images are those having a `:conversion disabled' property.
9517 A cross is always drawn on black & white displays. */);
9518 cross_disabled_images = 0;
9520 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9521 doc: /* List of directories to search for window system bitmap files. */);
9522 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9524 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9525 doc: /* Maximum time after which images are removed from the cache.
9526 When an image has not been displayed this many seconds, Emacs
9527 automatically removes it from the image cache. If the cache contains
9528 a large number of images, the actual eviction time may be shorter.
9529 The value can also be nil, meaning the cache is never cleared.
9531 The function `clear-image-cache' disregards this variable. */);
9532 Vimage_cache_eviction_delay = make_number (300);
9533 #ifdef HAVE_IMAGEMAGICK
9534 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9535 doc: /* Integer indicating which ImageMagick rendering method to use.
9536 The options are:
9537 0 -- the default method (pixel pushing)
9538 1 -- a newer method ("MagickExportImagePixels") that may perform
9539 better (speed etc) in some cases, but has not been as thoroughly
9540 tested with Emacs as the default method. This method requires
9541 ImageMagick version 6.4.6 (approximately) or later.
9542 */);
9543 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9544 imagemagick_render_type = 0;
9545 #endif