Improve responsiveness while in 'replace-buffer-contents'
[emacs.git] / src / image.c
blob4d5a1bf5e66c792ad904bb86fabe1ce674ecf3d8
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2018 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 (at
10 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 <https://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <fcntl.h>
23 #include <unistd.h>
25 /* Include this before including <setjmp.h> to work around bugs with
26 older libpng; see Bug#17429. */
27 #if defined HAVE_PNG && !defined HAVE_NS
28 # include <png.h>
29 #endif
31 #include <setjmp.h>
33 #include <c-ctype.h>
34 #include <flexmember.h>
36 #include "lisp.h"
37 #include "frame.h"
38 #include "process.h"
39 #include "window.h"
40 #include "buffer.h"
41 #include "dispextern.h"
42 #include "blockinput.h"
43 #include "sysstdio.h"
44 #include "systime.h"
45 #include <epaths.h>
46 #include "coding.h"
47 #include "termhooks.h"
48 #include "font.h"
50 #ifdef HAVE_SYS_STAT_H
51 #include <sys/stat.h>
52 #endif /* HAVE_SYS_STAT_H */
54 #ifdef HAVE_SYS_TYPES_H
55 #include <sys/types.h>
56 #endif /* HAVE_SYS_TYPES_H */
58 #ifdef HAVE_WINDOW_SYSTEM
59 #include TERM_HEADER
60 #endif /* HAVE_WINDOW_SYSTEM */
62 /* Work around GCC bug 54561. */
63 #if GNUC_PREREQ (4, 3, 0)
64 # pragma GCC diagnostic ignored "-Wclobbered"
65 #endif
67 #ifdef HAVE_X_WINDOWS
68 typedef struct x_bitmap_record Bitmap_Record;
69 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
70 #define NO_PIXMAP None
72 #define PIX_MASK_RETAIN 0
73 #define PIX_MASK_DRAW 1
74 #endif /* HAVE_X_WINDOWS */
76 #ifdef HAVE_NTGUI
78 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
79 #ifdef WINDOWSNT
80 # include "w32.h"
81 #endif
83 typedef struct w32_bitmap_record Bitmap_Record;
84 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
85 #define NO_PIXMAP 0
87 #define PIX_MASK_RETAIN 0
88 #define PIX_MASK_DRAW 1
90 #define x_defined_color w32_defined_color
92 #endif /* HAVE_NTGUI */
94 #ifdef HAVE_NS
95 typedef struct ns_bitmap_record Bitmap_Record;
97 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
98 #define NO_PIXMAP 0
100 #define PIX_MASK_RETAIN 0
102 #define x_defined_color(f, name, color_def, alloc) \
103 ns_defined_color (f, name, color_def, alloc, 0)
104 #endif /* HAVE_NS */
106 #if (defined HAVE_X_WINDOWS \
107 && ! (defined HAVE_NTGUI || defined USE_CAIRO || defined HAVE_NS))
108 /* W32_TODO : Color tables on W32. */
109 # define COLOR_TABLE_SUPPORT 1
110 #endif
112 static void x_disable_image (struct frame *, struct image *);
113 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
114 Lisp_Object);
116 static void init_color_table (void);
117 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
118 #ifdef COLOR_TABLE_SUPPORT
119 static void free_color_table (void);
120 static unsigned long *colors_in_color_table (int *n);
121 #endif
123 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
124 id, which is just an int that this section returns. Bitmaps are
125 reference counted so they can be shared among frames.
127 Bitmap indices are guaranteed to be > 0, so a negative number can
128 be used to indicate no bitmap.
130 If you use x_create_bitmap_from_data, then you must keep track of
131 the bitmaps yourself. That is, creating a bitmap from the same
132 data more than once will not be caught. */
134 #ifdef HAVE_NS
135 /* Use with images created by ns_image_for_XPM. */
136 static unsigned long
137 XGetPixel (XImagePtr ximage, int x, int y)
139 return ns_get_pixel (ximage, x, y);
142 /* Use with images created by ns_image_for_XPM; alpha set to 1;
143 pixel is assumed to be in RGB form. */
144 static void
145 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
147 ns_put_pixel (ximage, x, y, pixel);
149 #endif /* HAVE_NS */
152 /* Functions to access the contents of a bitmap, given an id. */
154 #ifdef HAVE_X_WINDOWS
155 static int
156 x_bitmap_height (struct frame *f, ptrdiff_t id)
158 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
161 static int
162 x_bitmap_width (struct frame *f, ptrdiff_t id)
164 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
166 #endif
168 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
169 ptrdiff_t
170 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
172 /* HAVE_NTGUI needs the explicit cast here. */
173 return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
175 #endif
177 #ifdef HAVE_X_WINDOWS
179 x_bitmap_mask (struct frame *f, ptrdiff_t id)
181 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
183 #endif
185 /* Allocate a new bitmap record. Returns index of new record. */
187 static ptrdiff_t
188 x_allocate_bitmap_record (struct frame *f)
190 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
191 ptrdiff_t i;
193 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
194 return ++dpyinfo->bitmaps_last;
196 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
197 if (dpyinfo->bitmaps[i].refcount == 0)
198 return i + 1;
200 dpyinfo->bitmaps =
201 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
202 10, -1, sizeof *dpyinfo->bitmaps);
203 return ++dpyinfo->bitmaps_last;
206 /* Add one reference to the reference count of the bitmap with id ID. */
208 void
209 x_reference_bitmap (struct frame *f, ptrdiff_t id)
211 ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
214 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
216 ptrdiff_t
217 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
219 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
220 ptrdiff_t id;
222 #ifdef HAVE_X_WINDOWS
223 Pixmap bitmap;
224 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
225 bits, width, height);
226 if (! bitmap)
227 return -1;
228 #endif /* HAVE_X_WINDOWS */
230 #ifdef HAVE_NTGUI
231 Lisp_Object frame UNINIT; /* The value is not used. */
232 Pixmap bitmap;
233 bitmap = CreateBitmap (width, height,
234 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
235 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
236 bits);
237 if (! bitmap)
238 return -1;
239 #endif /* HAVE_NTGUI */
241 #ifdef HAVE_NS
242 void *bitmap = ns_image_from_XBM (bits, width, height, 0, 0);
243 if (!bitmap)
244 return -1;
245 #endif
247 id = x_allocate_bitmap_record (f);
249 #ifdef HAVE_NS
250 dpyinfo->bitmaps[id - 1].img = bitmap;
251 dpyinfo->bitmaps[id - 1].depth = 1;
252 #endif
254 dpyinfo->bitmaps[id - 1].file = NULL;
255 dpyinfo->bitmaps[id - 1].height = height;
256 dpyinfo->bitmaps[id - 1].width = width;
257 dpyinfo->bitmaps[id - 1].refcount = 1;
259 #ifdef HAVE_X_WINDOWS
260 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
261 dpyinfo->bitmaps[id - 1].have_mask = false;
262 dpyinfo->bitmaps[id - 1].depth = 1;
263 #endif /* HAVE_X_WINDOWS */
265 #ifdef HAVE_NTGUI
266 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
267 dpyinfo->bitmaps[id - 1].hinst = NULL;
268 dpyinfo->bitmaps[id - 1].depth = 1;
269 #endif /* HAVE_NTGUI */
271 return id;
274 /* Create bitmap from file FILE for frame F. */
276 ptrdiff_t
277 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
279 #ifdef HAVE_NTGUI
280 return -1; /* W32_TODO : bitmap support */
281 #else
282 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
283 #endif
285 #ifdef HAVE_NS
286 ptrdiff_t id;
287 void *bitmap = ns_image_from_file (file);
289 if (!bitmap)
290 return -1;
293 id = x_allocate_bitmap_record (f);
294 dpyinfo->bitmaps[id - 1].img = bitmap;
295 dpyinfo->bitmaps[id - 1].refcount = 1;
296 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
297 dpyinfo->bitmaps[id - 1].depth = 1;
298 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
299 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
300 return id;
301 #endif
303 #ifdef HAVE_X_WINDOWS
304 unsigned int width, height;
305 Pixmap bitmap;
306 int xhot, yhot, result;
307 ptrdiff_t id;
308 Lisp_Object found;
309 char *filename;
311 /* Look for an existing bitmap with the same name. */
312 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
314 if (dpyinfo->bitmaps[id].refcount
315 && dpyinfo->bitmaps[id].file
316 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
318 ++dpyinfo->bitmaps[id].refcount;
319 return id + 1;
323 /* Search bitmap-file-path for the file, if appropriate. */
324 if (openp (Vx_bitmap_file_path, file, Qnil, &found,
325 make_number (R_OK), false)
326 < 0)
327 return -1;
329 filename = SSDATA (found);
331 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
332 filename, &width, &height, &bitmap, &xhot, &yhot);
333 if (result != BitmapSuccess)
334 return -1;
336 id = x_allocate_bitmap_record (f);
337 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
338 dpyinfo->bitmaps[id - 1].have_mask = false;
339 dpyinfo->bitmaps[id - 1].refcount = 1;
340 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
341 dpyinfo->bitmaps[id - 1].depth = 1;
342 dpyinfo->bitmaps[id - 1].height = height;
343 dpyinfo->bitmaps[id - 1].width = width;
345 return id;
346 #endif /* HAVE_X_WINDOWS */
349 /* Free bitmap B. */
351 static void
352 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
354 #ifdef HAVE_X_WINDOWS
355 XFreePixmap (dpyinfo->display, bm->pixmap);
356 if (bm->have_mask)
357 XFreePixmap (dpyinfo->display, bm->mask);
358 #endif /* HAVE_X_WINDOWS */
360 #ifdef HAVE_NTGUI
361 DeleteObject (bm->pixmap);
362 #endif /* HAVE_NTGUI */
364 #ifdef HAVE_NS
365 ns_release_object (bm->img);
366 #endif
368 if (bm->file)
370 xfree (bm->file);
371 bm->file = NULL;
375 /* Remove reference to bitmap with id number ID. */
377 void
378 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
380 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
382 if (id > 0)
384 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
386 if (--bm->refcount == 0)
388 block_input ();
389 free_bitmap_record (dpyinfo, bm);
390 unblock_input ();
395 /* Free all the bitmaps for the display specified by DPYINFO. */
397 void
398 x_destroy_all_bitmaps (Display_Info *dpyinfo)
400 ptrdiff_t i;
401 Bitmap_Record *bm = dpyinfo->bitmaps;
403 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
404 if (bm->refcount > 0)
405 free_bitmap_record (dpyinfo, bm);
407 dpyinfo->bitmaps_last = 0;
410 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
411 XImagePtr *, Pixmap *);
412 static void x_destroy_x_image (XImagePtr ximg);
414 #ifdef HAVE_NTGUI
415 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
416 bool, HGDIOBJ *);
417 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
418 HGDIOBJ);
419 #else
420 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
421 static void image_unget_x_image (struct image *, bool, XImagePtr);
422 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
423 image_get_x_image (f, img, mask_p)
424 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
425 image_unget_x_image (img, mask_p, ximg)
426 #endif
428 #ifdef HAVE_X_WINDOWS
430 static void image_sync_to_pixmaps (struct frame *, struct image *);
432 /* Useful functions defined in the section
433 `Image type independent image structures' below. */
435 static unsigned long four_corners_best (XImagePtr ximg,
436 int *corners,
437 unsigned long width,
438 unsigned long height);
441 /* Create a mask of a bitmap. Note is this not a perfect mask.
442 It's nicer with some borders in this context */
444 void
445 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
447 Pixmap pixmap, mask;
448 XImagePtr ximg, mask_img;
449 unsigned long width, height;
450 bool result;
451 unsigned long bg;
452 unsigned long x, y, xp, xm, yp, ym;
453 GC gc;
455 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
457 if (!(id > 0))
458 return;
460 pixmap = x_bitmap_pixmap (f, id);
461 width = x_bitmap_width (f, id);
462 height = x_bitmap_height (f, id);
464 block_input ();
465 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
466 ~0, ZPixmap);
468 if (!ximg)
470 unblock_input ();
471 return;
474 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
476 unblock_input ();
477 if (!result)
479 XDestroyImage (ximg);
480 return;
483 bg = four_corners_best (ximg, NULL, width, height);
485 for (y = 0; y < ximg->height; ++y)
487 for (x = 0; x < ximg->width; ++x)
489 xp = x != ximg->width - 1 ? x + 1 : 0;
490 xm = x != 0 ? x - 1 : ximg->width - 1;
491 yp = y != ximg->height - 1 ? y + 1 : 0;
492 ym = y != 0 ? y - 1 : ximg->height - 1;
493 if (XGetPixel (ximg, x, y) == bg
494 && XGetPixel (ximg, x, yp) == bg
495 && XGetPixel (ximg, x, ym) == bg
496 && XGetPixel (ximg, xp, y) == bg
497 && XGetPixel (ximg, xp, yp) == bg
498 && XGetPixel (ximg, xp, ym) == bg
499 && XGetPixel (ximg, xm, y) == bg
500 && XGetPixel (ximg, xm, yp) == bg
501 && XGetPixel (ximg, xm, ym) == bg)
502 XPutPixel (mask_img, x, y, 0);
503 else
504 XPutPixel (mask_img, x, y, 1);
508 eassert (input_blocked_p ());
509 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
510 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
511 width, height);
512 XFreeGC (FRAME_X_DISPLAY (f), gc);
514 dpyinfo->bitmaps[id - 1].have_mask = true;
515 dpyinfo->bitmaps[id - 1].mask = mask;
517 XDestroyImage (ximg);
518 x_destroy_x_image (mask_img);
521 #endif /* HAVE_X_WINDOWS */
523 /***********************************************************************
524 Image types
525 ***********************************************************************/
527 /* List of supported image types. Use define_image_type to add new
528 types. Use lookup_image_type to find a type for a given symbol. */
530 static struct image_type *image_types;
532 /* Forward function prototypes. */
534 static struct image_type *lookup_image_type (Lisp_Object);
535 static void x_laplace (struct frame *, struct image *);
536 static void x_emboss (struct frame *, struct image *);
537 static void x_build_heuristic_mask (struct frame *, struct image *,
538 Lisp_Object);
539 #ifdef WINDOWSNT
540 #define CACHE_IMAGE_TYPE(type, status) \
541 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
542 #else
543 #define CACHE_IMAGE_TYPE(type, status)
544 #endif
546 #define ADD_IMAGE_TYPE(type) \
547 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
549 /* Define a new image type from TYPE. This adds a copy of TYPE to
550 image_types and caches the loading status of TYPE. */
552 static struct image_type *
553 define_image_type (struct image_type *type)
555 struct image_type *p = NULL;
556 int new_type = type->type;
557 bool type_valid = true;
559 block_input ();
561 for (p = image_types; p; p = p->next)
562 if (p->type == new_type)
563 goto done;
565 if (type->init)
567 #if defined HAVE_NTGUI && defined WINDOWSNT
568 /* If we failed to load the library before, don't try again. */
569 Lisp_Object tested = Fassq (builtin_lisp_symbol (new_type),
570 Vlibrary_cache);
571 if (CONSP (tested) && NILP (XCDR (tested)))
572 type_valid = false;
573 else
574 #endif
576 type_valid = type->init ();
577 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type),
578 type_valid ? Qt : Qnil);
582 if (type_valid)
584 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
585 The initialized data segment is read-only. */
586 p = xmalloc (sizeof *p);
587 *p = *type;
588 p->next = image_types;
589 image_types = p;
592 done:
593 unblock_input ();
594 return p;
598 /* Value is true if OBJECT is a valid Lisp image specification. A
599 valid image specification is a list whose car is the symbol
600 `image', and whose rest is a property list. The property list must
601 contain a value for key `:type'. That value must be the name of a
602 supported image type. The rest of the property list depends on the
603 image type. */
605 bool
606 valid_image_p (Lisp_Object object)
608 bool valid_p = 0;
610 if (IMAGEP (object))
612 Lisp_Object tem;
614 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
615 if (EQ (XCAR (tem), QCtype))
617 tem = XCDR (tem);
618 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
620 struct image_type *type;
621 type = lookup_image_type (XCAR (tem));
622 if (type)
623 valid_p = type->valid_p (object);
626 break;
630 return valid_p;
634 /* Log error message with format string FORMAT and trailing arguments.
635 Signaling an error, e.g. when an image cannot be loaded, is not a
636 good idea because this would interrupt redisplay, and the error
637 message display would lead to another redisplay. This function
638 therefore simply displays a message. */
640 static void
641 image_error (const char *format, ...)
643 va_list ap;
644 va_start (ap, format);
645 vadd_to_log (format, ap);
646 va_end (ap);
649 static void
650 image_size_error (void)
652 image_error ("Invalid image size (see `max-image-size')");
656 /***********************************************************************
657 Image specifications
658 ***********************************************************************/
660 enum image_value_type
662 IMAGE_DONT_CHECK_VALUE_TYPE,
663 IMAGE_STRING_VALUE,
664 IMAGE_STRING_OR_NIL_VALUE,
665 IMAGE_SYMBOL_VALUE,
666 IMAGE_POSITIVE_INTEGER_VALUE,
667 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
668 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
669 IMAGE_ASCENT_VALUE,
670 IMAGE_INTEGER_VALUE,
671 IMAGE_FUNCTION_VALUE,
672 IMAGE_NUMBER_VALUE,
673 IMAGE_BOOL_VALUE
676 /* Structure used when parsing image specifications. */
678 struct image_keyword
680 /* Name of keyword. */
681 const char *name;
683 /* The type of value allowed. */
684 enum image_value_type type;
686 /* True means key must be present. */
687 bool mandatory_p;
689 /* Used to recognize duplicate keywords in a property list. */
690 int count;
692 /* The value that was found. */
693 Lisp_Object value;
697 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
698 has the format (image KEYWORD VALUE ...). One of the keyword/
699 value pairs must be `:type TYPE'. KEYWORDS is a vector of
700 image_keywords structures of size NKEYWORDS describing other
701 allowed keyword/value pairs. Value is true if SPEC is valid. */
703 static bool
704 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
705 int nkeywords, Lisp_Object type)
707 int i;
708 Lisp_Object plist;
710 if (!IMAGEP (spec))
711 return 0;
713 plist = XCDR (spec);
714 while (CONSP (plist))
716 Lisp_Object key, value;
718 /* First element of a pair must be a symbol. */
719 key = XCAR (plist);
720 plist = XCDR (plist);
721 if (!SYMBOLP (key))
722 return 0;
724 /* There must follow a value. */
725 if (!CONSP (plist))
726 return 0;
727 value = XCAR (plist);
728 plist = XCDR (plist);
730 /* Find key in KEYWORDS. Error if not found. */
731 for (i = 0; i < nkeywords; ++i)
732 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
733 break;
735 if (i == nkeywords)
736 continue;
738 /* Record that we recognized the keyword. If a keywords
739 was found more than once, it's an error. */
740 keywords[i].value = value;
741 if (keywords[i].count > 1)
742 return 0;
743 ++keywords[i].count;
745 /* Check type of value against allowed type. */
746 switch (keywords[i].type)
748 case IMAGE_STRING_VALUE:
749 if (!STRINGP (value))
750 return 0;
751 break;
753 case IMAGE_STRING_OR_NIL_VALUE:
754 if (!STRINGP (value) && !NILP (value))
755 return 0;
756 break;
758 case IMAGE_SYMBOL_VALUE:
759 if (!SYMBOLP (value))
760 return 0;
761 break;
763 case IMAGE_POSITIVE_INTEGER_VALUE:
764 if (! RANGED_INTEGERP (1, value, INT_MAX))
765 return 0;
766 break;
768 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
769 if (RANGED_INTEGERP (0, value, INT_MAX))
770 break;
771 if (CONSP (value)
772 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
773 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
774 break;
775 return 0;
777 case IMAGE_ASCENT_VALUE:
778 if (SYMBOLP (value) && EQ (value, Qcenter))
779 break;
780 else if (RANGED_INTEGERP (0, value, 100))
781 break;
782 return 0;
784 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
785 /* Unlike the other integer-related cases, this one does not
786 verify that VALUE fits in 'int'. This is because callers
787 want EMACS_INT. */
788 if (!INTEGERP (value) || XINT (value) < 0)
789 return 0;
790 break;
792 case IMAGE_DONT_CHECK_VALUE_TYPE:
793 break;
795 case IMAGE_FUNCTION_VALUE:
796 value = indirect_function (value);
797 if (FUNCTIONP (value))
798 break;
799 return 0;
801 case IMAGE_NUMBER_VALUE:
802 if (! NUMBERP (value))
803 return 0;
804 break;
806 case IMAGE_INTEGER_VALUE:
807 if (! TYPE_RANGED_INTEGERP (int, value))
808 return 0;
809 break;
811 case IMAGE_BOOL_VALUE:
812 if (!NILP (value) && !EQ (value, Qt))
813 return 0;
814 break;
816 default:
817 emacs_abort ();
818 break;
821 if (EQ (key, QCtype) && !EQ (type, value))
822 return 0;
825 /* Check that all mandatory fields are present. */
826 for (i = 0; i < nkeywords; ++i)
827 if (keywords[i].mandatory_p && keywords[i].count == 0)
828 return 0;
830 return NILP (plist);
834 /* Return the value of KEY in image specification SPEC. Value is nil
835 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
836 was found in SPEC. */
838 static Lisp_Object
839 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
841 Lisp_Object tail;
843 eassert (valid_image_p (spec));
845 for (tail = XCDR (spec);
846 CONSP (tail) && CONSP (XCDR (tail));
847 tail = XCDR (XCDR (tail)))
849 if (EQ (XCAR (tail), key))
851 if (found)
852 *found = 1;
853 return XCAR (XCDR (tail));
857 if (found)
858 *found = 0;
859 return Qnil;
863 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
864 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
865 PIXELS non-nil means return the size in pixels, otherwise return the
866 size in canonical character units.
867 FRAME is the frame on which the image will be displayed. FRAME nil
868 or omitted means use the selected frame. */)
869 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
871 Lisp_Object size;
873 size = Qnil;
874 if (valid_image_p (spec))
876 struct frame *f = decode_window_system_frame (frame);
877 ptrdiff_t id = lookup_image (f, spec);
878 struct image *img = IMAGE_FROM_ID (f, id);
879 int width = img->width + 2 * img->hmargin;
880 int height = img->height + 2 * img->vmargin;
882 if (NILP (pixels))
883 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
884 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
885 else
886 size = Fcons (make_number (width), make_number (height));
888 else
889 error ("Invalid image specification");
891 return size;
895 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
896 doc: /* Return t if image SPEC has a mask bitmap.
897 FRAME is the frame on which the image will be displayed. FRAME nil
898 or omitted means use the selected frame. */)
899 (Lisp_Object spec, Lisp_Object frame)
901 Lisp_Object mask;
903 mask = Qnil;
904 if (valid_image_p (spec))
906 struct frame *f = decode_window_system_frame (frame);
907 ptrdiff_t id = lookup_image (f, spec);
908 struct image *img = IMAGE_FROM_ID (f, id);
909 if (img->mask)
910 mask = Qt;
912 else
913 error ("Invalid image specification");
915 return mask;
918 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
919 doc: /* Return metadata for image SPEC.
920 FRAME is the frame on which the image will be displayed. FRAME nil
921 or omitted means use the selected frame. */)
922 (Lisp_Object spec, Lisp_Object frame)
924 Lisp_Object ext;
926 ext = Qnil;
927 if (valid_image_p (spec))
929 struct frame *f = decode_window_system_frame (frame);
930 ptrdiff_t id = lookup_image (f, spec);
931 struct image *img = IMAGE_FROM_ID (f, id);
932 ext = img->lisp_data;
935 return ext;
939 /***********************************************************************
940 Image type independent image structures
941 ***********************************************************************/
943 #define MAX_IMAGE_SIZE 10.0
944 /* Allocate and return a new image structure for image specification
945 SPEC. SPEC has a hash value of HASH. */
947 static struct image *
948 make_image (Lisp_Object spec, EMACS_UINT hash)
950 struct image *img = xzalloc (sizeof *img);
951 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
953 eassert (valid_image_p (spec));
954 img->dependencies = NILP (file) ? Qnil : list1 (file);
955 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
956 eassert (img->type != NULL);
957 img->spec = spec;
958 img->lisp_data = Qnil;
959 img->ascent = DEFAULT_IMAGE_ASCENT;
960 img->hash = hash;
961 img->corners[BOT_CORNER] = -1; /* Full image */
962 return img;
966 /* Free image IMG which was used on frame F, including its resources. */
968 static void
969 free_image (struct frame *f, struct image *img)
971 if (img)
973 struct image_cache *c = FRAME_IMAGE_CACHE (f);
975 /* Remove IMG from the hash table of its cache. */
976 if (img->prev)
977 img->prev->next = img->next;
978 else
979 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
981 if (img->next)
982 img->next->prev = img->prev;
984 c->images[img->id] = NULL;
986 /* Windows NT redefines 'free', but in this file, we need to
987 avoid the redefinition. */
988 #ifdef WINDOWSNT
989 #undef free
990 #endif
991 /* Free resources, then free IMG. */
992 img->type->free (f, img);
993 xfree (img);
997 /* Return true if the given widths and heights are valid for display. */
999 static bool
1000 check_image_size (struct frame *f, int width, int height)
1002 int w, h;
1004 if (width <= 0 || height <= 0)
1005 return 0;
1007 if (INTEGERP (Vmax_image_size))
1008 return (width <= XINT (Vmax_image_size)
1009 && height <= XINT (Vmax_image_size));
1010 else if (FLOATP (Vmax_image_size))
1012 if (f != NULL)
1014 w = FRAME_PIXEL_WIDTH (f);
1015 h = FRAME_PIXEL_HEIGHT (f);
1017 else
1018 w = h = 1024; /* Arbitrary size for unknown frame. */
1019 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1020 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1022 else
1023 return 1;
1026 /* Prepare image IMG for display on frame F. Must be called before
1027 drawing an image. */
1029 void
1030 prepare_image_for_display (struct frame *f, struct image *img)
1032 /* We're about to display IMG, so set its timestamp to `now'. */
1033 img->timestamp = current_timespec ();
1035 #ifndef USE_CAIRO
1036 /* If IMG doesn't have a pixmap yet, load it now, using the image
1037 type dependent loader function. */
1038 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1039 img->load_failed_p = ! img->type->load (f, img);
1041 #ifdef HAVE_X_WINDOWS
1042 if (!img->load_failed_p)
1044 block_input ();
1045 image_sync_to_pixmaps (f, img);
1046 unblock_input ();
1048 #endif
1049 #endif
1053 /* Value is the number of pixels for the ascent of image IMG when
1054 drawn in face FACE. */
1057 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1059 int height;
1060 int ascent;
1062 if (slice->height == img->height)
1063 height = img->height + img->vmargin;
1064 else if (slice->y == 0)
1065 height = slice->height + img->vmargin;
1066 else
1067 height = slice->height;
1069 if (img->ascent == CENTERED_IMAGE_ASCENT)
1071 if (face->font)
1073 #ifdef HAVE_NTGUI
1074 /* W32 specific version. Why?. ++kfs */
1075 ascent = height / 2 - (FONT_DESCENT (face->font)
1076 - FONT_BASE (face->font)) / 2;
1077 #else
1078 /* This expression is arranged so that if the image can't be
1079 exactly centered, it will be moved slightly up. This is
1080 because a typical font is `top-heavy' (due to the presence
1081 uppercase letters), so the image placement should err towards
1082 being top-heavy too. It also just generally looks better. */
1083 ascent = (height + FONT_BASE (face->font)
1084 - FONT_DESCENT (face->font) + 1) / 2;
1085 #endif /* HAVE_NTGUI */
1087 else
1088 ascent = height / 2;
1090 else
1091 ascent = height * (img->ascent / 100.0);
1093 return ascent;
1096 #ifdef USE_CAIRO
1097 static uint32_t
1098 xcolor_to_argb32 (XColor xc)
1100 return ((0xffu << 24) | ((xc.red / 256) << 16)
1101 | ((xc.green / 256) << 8) | (xc.blue / 256));
1104 static uint32_t
1105 get_spec_bg_or_alpha_as_argb (struct image *img,
1106 struct frame *f)
1108 uint32_t bgcolor = 0;
1109 XColor xbgcolor;
1110 Lisp_Object bg = image_spec_value (img->spec, QCbackground, NULL);
1112 if (STRINGP (bg) && x_parse_color (f, SSDATA (bg), &xbgcolor))
1113 bgcolor = xcolor_to_argb32 (xbgcolor);
1115 return bgcolor;
1118 static void
1119 create_cairo_image_surface (struct image *img,
1120 unsigned char *data,
1121 int width,
1122 int height)
1124 cairo_surface_t *surface;
1125 cairo_format_t format = CAIRO_FORMAT_ARGB32;
1126 int stride = cairo_format_stride_for_width (format, width);
1127 surface = cairo_image_surface_create_for_data (data,
1128 format,
1129 width,
1130 height,
1131 stride);
1132 img->width = width;
1133 img->height = height;
1134 img->cr_data = surface;
1135 img->cr_data2 = data;
1136 img->pixmap = 0;
1138 #endif
1142 /* Image background colors. */
1144 /* Find the "best" corner color of a bitmap.
1145 On W32, XIMG is assumed to a device context with the bitmap selected. */
1147 static RGB_PIXEL_COLOR
1148 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1149 unsigned long width, unsigned long height)
1151 RGB_PIXEL_COLOR corner_pixels[4];
1152 RGB_PIXEL_COLOR best UNINIT;
1153 int i, best_count;
1155 if (corners && corners[BOT_CORNER] >= 0)
1157 /* Get the colors at the corner_pixels of ximg. */
1158 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1159 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1160 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1161 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1163 else
1165 /* Get the colors at the corner_pixels of ximg. */
1166 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1167 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1168 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1169 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1171 /* Choose the most frequently found color as background. */
1172 for (i = best_count = 0; i < 4; ++i)
1174 int j, n;
1176 for (j = n = 0; j < 4; ++j)
1177 if (corner_pixels[i] == corner_pixels[j])
1178 ++n;
1180 if (n > best_count)
1181 best = corner_pixels[i], best_count = n;
1184 return best;
1187 /* Portability macros */
1189 #ifdef HAVE_NTGUI
1191 #define Free_Pixmap(display, pixmap) \
1192 DeleteObject (pixmap)
1194 #elif defined (HAVE_NS)
1196 #define Free_Pixmap(display, pixmap) \
1197 ns_release_object (pixmap)
1199 #else
1201 #define Free_Pixmap(display, pixmap) \
1202 XFreePixmap (display, pixmap)
1204 #endif /* !HAVE_NTGUI && !HAVE_NS */
1207 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1208 it is guessed heuristically. If non-zero, XIMG is an existing
1209 XImage object (or device context with the image selected on W32) to
1210 use for the heuristic. */
1212 RGB_PIXEL_COLOR
1213 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1215 if (! img->background_valid)
1216 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1218 bool free_ximg = !ximg;
1219 #ifdef HAVE_NTGUI
1220 HGDIOBJ prev;
1221 #endif /* HAVE_NTGUI */
1223 if (free_ximg)
1224 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1226 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1228 if (free_ximg)
1229 image_unget_x_image_or_dc (img, 0, ximg, prev);
1231 img->background_valid = 1;
1234 return img->background;
1237 /* Return the `background_transparent' field of IMG. If IMG doesn't
1238 have one yet, it is guessed heuristically. If non-zero, MASK is an
1239 existing XImage object to use for the heuristic. */
1242 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1244 if (! img->background_transparent_valid)
1245 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1247 if (img->mask)
1249 bool free_mask = !mask;
1250 #ifdef HAVE_NTGUI
1251 HGDIOBJ prev;
1252 #endif /* HAVE_NTGUI */
1254 if (free_mask)
1255 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1257 img->background_transparent
1258 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1260 if (free_mask)
1261 image_unget_x_image_or_dc (img, 1, mask, prev);
1263 else
1264 img->background_transparent = 0;
1266 img->background_transparent_valid = 1;
1269 return img->background_transparent;
1272 #if defined (HAVE_PNG) || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1274 /* Store F's background color into *BGCOLOR. */
1275 static void
1276 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1278 #ifndef HAVE_NS
1279 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1280 x_query_color (f, bgcolor);
1281 #else
1282 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1283 #endif
1286 #endif /* HAVE_PNG || HAVE_IMAGEMAGICK || HAVE_RSVG */
1288 /***********************************************************************
1289 Helper functions for X image types
1290 ***********************************************************************/
1292 /* Clear X resources of image IMG on frame F according to FLAGS.
1293 FLAGS is bitwise-or of the following masks:
1294 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1295 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1296 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1297 any. */
1299 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1300 #define CLEAR_IMAGE_MASK (1 << 1)
1301 #define CLEAR_IMAGE_COLORS (1 << 2)
1303 static void
1304 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1306 if (flags & CLEAR_IMAGE_PIXMAP)
1308 if (img->pixmap)
1310 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1311 img->pixmap = NO_PIXMAP;
1312 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1313 img->background_valid = 0;
1315 #ifdef HAVE_X_WINDOWS
1316 if (img->ximg)
1318 x_destroy_x_image (img->ximg);
1319 img->ximg = NULL;
1320 img->background_valid = 0;
1322 #endif
1325 if (flags & CLEAR_IMAGE_MASK)
1327 if (img->mask)
1329 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1330 img->mask = NO_PIXMAP;
1331 img->background_transparent_valid = 0;
1333 #ifdef HAVE_X_WINDOWS
1334 if (img->mask_img)
1336 x_destroy_x_image (img->mask_img);
1337 img->mask_img = NULL;
1338 img->background_transparent_valid = 0;
1340 #endif
1343 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1345 /* W32_TODO: color table support. */
1346 #ifdef HAVE_X_WINDOWS
1347 x_free_colors (f, img->colors, img->ncolors);
1348 #endif /* HAVE_X_WINDOWS */
1349 xfree (img->colors);
1350 img->colors = NULL;
1351 img->ncolors = 0;
1356 /* Free X resources of image IMG which is used on frame F. */
1358 static void
1359 x_clear_image (struct frame *f, struct image *img)
1361 block_input ();
1362 #ifdef USE_CAIRO
1363 if (img->cr_data)
1364 cairo_surface_destroy ((cairo_surface_t *)img->cr_data);
1365 if (img->cr_data2) xfree (img->cr_data2);
1366 #endif
1367 x_clear_image_1 (f, img,
1368 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1369 unblock_input ();
1373 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1374 cannot be allocated, use DFLT. Add a newly allocated color to
1375 IMG->colors, so that it can be freed again. Value is the pixel
1376 color. */
1378 static unsigned long
1379 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1380 unsigned long dflt)
1382 XColor color;
1383 unsigned long result;
1385 eassert (STRINGP (color_name));
1387 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1388 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1389 INT_MAX))
1391 /* This isn't called frequently so we get away with simply
1392 reallocating the color vector to the needed size, here. */
1393 ptrdiff_t ncolors = img->ncolors + 1;
1394 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1395 img->colors[ncolors - 1] = color.pixel;
1396 img->ncolors = ncolors;
1397 result = color.pixel;
1399 else
1400 result = dflt;
1402 return result;
1407 /***********************************************************************
1408 Image Cache
1409 ***********************************************************************/
1411 static void cache_image (struct frame *f, struct image *img);
1413 /* Return a new, initialized image cache that is allocated from the
1414 heap. Call free_image_cache to free an image cache. */
1416 struct image_cache *
1417 make_image_cache (void)
1419 struct image_cache *c = xmalloc (sizeof *c);
1421 c->size = 50;
1422 c->used = c->refcount = 0;
1423 c->images = xmalloc (c->size * sizeof *c->images);
1424 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1425 return c;
1429 /* Find an image matching SPEC in the cache, and return it. If no
1430 image is found, return NULL. */
1431 static struct image *
1432 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1434 struct image *img;
1435 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1436 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1438 if (!c) return NULL;
1440 /* If the image spec does not specify a background color, the cached
1441 image must have the same background color as the current frame.
1442 The foreground color must also match, for the sake of monochrome
1443 images.
1445 In fact, we could ignore the foreground color matching condition
1446 for color images, or if the image spec specifies :foreground;
1447 similarly we could ignore the background color matching condition
1448 for formats that don't use transparency (such as jpeg), or if the
1449 image spec specifies :background. However, the extra memory
1450 usage is probably negligible in practice, so we don't bother. */
1452 for (img = c->buckets[i]; img; img = img->next)
1453 if (img->hash == hash
1454 && !NILP (Fequal (img->spec, spec))
1455 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1456 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1457 break;
1458 return img;
1462 /* Search frame F for an image with spec SPEC, and free it. */
1464 static void
1465 uncache_image (struct frame *f, Lisp_Object spec)
1467 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1468 if (img)
1470 free_image (f, img);
1471 /* As display glyphs may still be referring to the image ID, we
1472 must garbage the frame (Bug#6426). */
1473 SET_FRAME_GARBAGED (f);
1478 /* Free image cache of frame F. Be aware that X frames share images
1479 caches. */
1481 void
1482 free_image_cache (struct frame *f)
1484 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1485 if (c)
1487 ptrdiff_t i;
1489 /* Cache should not be referenced by any frame when freed. */
1490 eassert (c->refcount == 0);
1492 for (i = 0; i < c->used; ++i)
1493 free_image (f, c->images[i]);
1494 xfree (c->images);
1495 xfree (c->buckets);
1496 xfree (c);
1497 FRAME_IMAGE_CACHE (f) = NULL;
1502 /* Clear image cache of frame F. FILTER=t means free all images.
1503 FILTER=nil means clear only images that haven't been
1504 displayed for some time.
1505 Else, only free the images which have FILTER in their `dependencies'.
1506 Should be called from time to time to reduce the number of loaded images.
1507 If image-cache-eviction-delay is non-nil, this frees images in the cache
1508 which weren't displayed for at least that many seconds. */
1510 static void
1511 clear_image_cache (struct frame *f, Lisp_Object filter)
1513 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1515 if (c)
1517 ptrdiff_t i, nfreed = 0;
1519 /* Block input so that we won't be interrupted by a SIGIO
1520 while being in an inconsistent state. */
1521 block_input ();
1523 if (!NILP (filter))
1525 /* Filter image cache. */
1526 for (i = 0; i < c->used; ++i)
1528 struct image *img = c->images[i];
1529 if (img && (EQ (Qt, filter)
1530 || !NILP (Fmember (filter, img->dependencies))))
1532 free_image (f, img);
1533 ++nfreed;
1537 else if (INTEGERP (Vimage_cache_eviction_delay))
1539 /* Free cache based on timestamp. */
1540 struct timespec old, t;
1541 double delay;
1542 ptrdiff_t nimages = 0;
1544 for (i = 0; i < c->used; ++i)
1545 if (c->images[i])
1546 nimages++;
1548 /* If the number of cached images has grown unusually large,
1549 decrease the cache eviction delay (Bug#6230). */
1550 delay = XINT (Vimage_cache_eviction_delay);
1551 if (nimages > 40)
1552 delay = 1600 * delay / nimages / nimages;
1553 delay = max (delay, 1);
1555 t = current_timespec ();
1556 old = timespec_sub (t, dtotimespec (delay));
1558 for (i = 0; i < c->used; ++i)
1560 struct image *img = c->images[i];
1561 if (img && timespec_cmp (img->timestamp, old) < 0)
1563 free_image (f, img);
1564 ++nfreed;
1569 /* We may be clearing the image cache because, for example,
1570 Emacs was iconified for a longer period of time. In that
1571 case, current matrices may still contain references to
1572 images freed above. So, clear these matrices. */
1573 if (nfreed)
1575 Lisp_Object tail, frame;
1577 FOR_EACH_FRAME (tail, frame)
1579 struct frame *fr = XFRAME (frame);
1580 if (FRAME_IMAGE_CACHE (fr) == c)
1581 clear_current_matrices (fr);
1584 windows_or_buffers_changed = 19;
1587 unblock_input ();
1591 void
1592 clear_image_caches (Lisp_Object filter)
1594 /* FIXME: We want to do
1595 * struct terminal *t;
1596 * for (t = terminal_list; t; t = t->next_terminal)
1597 * clear_image_cache (t, filter); */
1598 Lisp_Object tail, frame;
1599 FOR_EACH_FRAME (tail, frame)
1600 if (FRAME_WINDOW_P (XFRAME (frame)))
1601 clear_image_cache (XFRAME (frame), filter);
1604 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1605 0, 1, 0,
1606 doc: /* Clear the image cache.
1607 FILTER nil or a frame means clear all images in the selected frame.
1608 FILTER t means clear the image caches of all frames.
1609 Anything else, means only clear those images which refer to FILTER,
1610 which is then usually a filename. */)
1611 (Lisp_Object filter)
1613 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1614 clear_image_caches (filter);
1615 else
1616 clear_image_cache (decode_window_system_frame (filter), Qt);
1618 return Qnil;
1622 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1623 1, 2, 0,
1624 doc: /* Flush the image with specification SPEC on frame FRAME.
1625 This removes the image from the Emacs image cache. If SPEC specifies
1626 an image file, the next redisplay of this image will read from the
1627 current contents of that file.
1629 FRAME nil or omitted means use the selected frame.
1630 FRAME t means refresh the image on all frames. */)
1631 (Lisp_Object spec, Lisp_Object frame)
1633 if (!valid_image_p (spec))
1634 error ("Invalid image specification");
1636 if (EQ (frame, Qt))
1638 Lisp_Object tail;
1639 FOR_EACH_FRAME (tail, frame)
1641 struct frame *f = XFRAME (frame);
1642 if (FRAME_WINDOW_P (f))
1643 uncache_image (f, spec);
1646 else
1647 uncache_image (decode_window_system_frame (frame), spec);
1649 return Qnil;
1653 /* Compute masks and transform image IMG on frame F, as specified
1654 by the image's specification, */
1656 static void
1657 postprocess_image (struct frame *f, struct image *img)
1659 /* Manipulation of the image's mask. */
1660 if (img->pixmap)
1662 Lisp_Object conversion, spec;
1663 Lisp_Object mask;
1665 spec = img->spec;
1667 /* `:heuristic-mask t'
1668 `:mask heuristic'
1669 means build a mask heuristically.
1670 `:heuristic-mask (R G B)'
1671 `:mask (heuristic (R G B))'
1672 means build a mask from color (R G B) in the
1673 image.
1674 `:mask nil'
1675 means remove a mask, if any. */
1677 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1678 if (!NILP (mask))
1679 x_build_heuristic_mask (f, img, mask);
1680 else
1682 bool found_p;
1684 mask = image_spec_value (spec, QCmask, &found_p);
1686 if (EQ (mask, Qheuristic))
1687 x_build_heuristic_mask (f, img, Qt);
1688 else if (CONSP (mask)
1689 && EQ (XCAR (mask), Qheuristic))
1691 if (CONSP (XCDR (mask)))
1692 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1693 else
1694 x_build_heuristic_mask (f, img, XCDR (mask));
1696 else if (NILP (mask) && found_p && img->mask)
1697 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1701 /* Should we apply an image transformation algorithm? */
1702 conversion = image_spec_value (spec, QCconversion, NULL);
1703 if (EQ (conversion, Qdisabled))
1704 x_disable_image (f, img);
1705 else if (EQ (conversion, Qlaplace))
1706 x_laplace (f, img);
1707 else if (EQ (conversion, Qemboss))
1708 x_emboss (f, img);
1709 else if (CONSP (conversion)
1710 && EQ (XCAR (conversion), Qedge_detection))
1712 Lisp_Object tem;
1713 tem = XCDR (conversion);
1714 if (CONSP (tem))
1715 x_edge_detection (f, img,
1716 Fplist_get (tem, QCmatrix),
1717 Fplist_get (tem, QCcolor_adjustment));
1723 /* Return the id of image with Lisp specification SPEC on frame F.
1724 SPEC must be a valid Lisp image specification (see valid_image_p). */
1726 ptrdiff_t
1727 lookup_image (struct frame *f, Lisp_Object spec)
1729 struct image *img;
1730 EMACS_UINT hash;
1732 /* F must be a window-system frame, and SPEC must be a valid image
1733 specification. */
1734 eassert (FRAME_WINDOW_P (f));
1735 eassert (valid_image_p (spec));
1737 /* Look up SPEC in the hash table of the image cache. */
1738 hash = sxhash (spec, 0);
1739 img = search_image_cache (f, spec, hash);
1740 if (img && img->load_failed_p)
1742 free_image (f, img);
1743 img = NULL;
1746 /* If not found, create a new image and cache it. */
1747 if (img == NULL)
1749 block_input ();
1750 img = make_image (spec, hash);
1751 cache_image (f, img);
1752 img->load_failed_p = ! img->type->load (f, img);
1753 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1754 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1756 /* If we can't load the image, and we don't have a width and
1757 height, use some arbitrary width and height so that we can
1758 draw a rectangle for it. */
1759 if (img->load_failed_p)
1761 Lisp_Object value;
1763 value = image_spec_value (spec, QCwidth, NULL);
1764 img->width = (INTEGERP (value)
1765 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1766 value = image_spec_value (spec, QCheight, NULL);
1767 img->height = (INTEGERP (value)
1768 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1770 else
1772 /* Handle image type independent image attributes
1773 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1774 `:background COLOR'. */
1775 Lisp_Object ascent, margin, relief, bg;
1776 int relief_bound;
1778 ascent = image_spec_value (spec, QCascent, NULL);
1779 if (INTEGERP (ascent))
1780 img->ascent = XFASTINT (ascent);
1781 else if (EQ (ascent, Qcenter))
1782 img->ascent = CENTERED_IMAGE_ASCENT;
1784 margin = image_spec_value (spec, QCmargin, NULL);
1785 if (INTEGERP (margin))
1786 img->vmargin = img->hmargin = XFASTINT (margin);
1787 else if (CONSP (margin))
1789 img->hmargin = XFASTINT (XCAR (margin));
1790 img->vmargin = XFASTINT (XCDR (margin));
1793 relief = image_spec_value (spec, QCrelief, NULL);
1794 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1795 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1797 img->relief = XINT (relief);
1798 img->hmargin += eabs (img->relief);
1799 img->vmargin += eabs (img->relief);
1802 if (! img->background_valid)
1804 bg = image_spec_value (img->spec, QCbackground, NULL);
1805 if (!NILP (bg))
1807 img->background
1808 = x_alloc_image_color (f, img, bg,
1809 FRAME_BACKGROUND_PIXEL (f));
1810 img->background_valid = 1;
1814 /* Do image transformations and compute masks, unless we
1815 don't have the image yet. */
1816 if (!EQ (builtin_lisp_symbol (img->type->type), Qpostscript))
1817 postprocess_image (f, img);
1820 unblock_input ();
1823 /* We're using IMG, so set its timestamp to `now'. */
1824 img->timestamp = current_timespec ();
1826 /* Value is the image id. */
1827 return img->id;
1831 /* Cache image IMG in the image cache of frame F. */
1833 static void
1834 cache_image (struct frame *f, struct image *img)
1836 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1837 ptrdiff_t i;
1839 if (!c)
1840 c = FRAME_IMAGE_CACHE (f) = make_image_cache ();
1842 /* Find a free slot in c->images. */
1843 for (i = 0; i < c->used; ++i)
1844 if (c->images[i] == NULL)
1845 break;
1847 /* If no free slot found, maybe enlarge c->images. */
1848 if (i == c->used && c->used == c->size)
1849 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1851 /* Add IMG to c->images, and assign IMG an id. */
1852 c->images[i] = img;
1853 img->id = i;
1854 if (i == c->used)
1855 ++c->used;
1857 /* Add IMG to the cache's hash table. */
1858 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1859 img->next = c->buckets[i];
1860 if (img->next)
1861 img->next->prev = img;
1862 img->prev = NULL;
1863 c->buckets[i] = img;
1867 /* Call FN on every image in the image cache of frame F. Used to mark
1868 Lisp Objects in the image cache. */
1870 /* Mark Lisp objects in image IMG. */
1872 static void
1873 mark_image (struct image *img)
1875 mark_object (img->spec);
1876 mark_object (img->dependencies);
1878 if (!NILP (img->lisp_data))
1879 mark_object (img->lisp_data);
1883 void
1884 mark_image_cache (struct image_cache *c)
1886 if (c)
1888 ptrdiff_t i;
1889 for (i = 0; i < c->used; ++i)
1890 if (c->images[i])
1891 mark_image (c->images[i]);
1897 /***********************************************************************
1898 X / NS / W32 support code
1899 ***********************************************************************/
1901 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1902 windowing system.
1903 WIDTH and HEIGHT must both be positive.
1904 If XIMG is null, assume it is a bitmap. */
1905 static bool
1906 x_check_image_size (XImagePtr ximg, int width, int height)
1908 #ifdef HAVE_X_WINDOWS
1909 /* Respect Xlib's limits: it cannot deal with images that have more
1910 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1911 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1912 enum
1914 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1915 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1918 int bitmap_pad, depth, bytes_per_line;
1919 if (ximg)
1921 bitmap_pad = ximg->bitmap_pad;
1922 depth = ximg->depth;
1923 bytes_per_line = ximg->bytes_per_line;
1925 else
1927 bitmap_pad = 8;
1928 depth = 1;
1929 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1931 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1932 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1933 #else
1934 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1935 For now, assume that every image size is allowed on these systems. */
1936 return 1;
1937 #endif
1940 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1941 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1942 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1943 via xmalloc. Print error messages via image_error if an error
1944 occurs. Value is true if successful.
1946 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1947 should indicate the bit depth of the image. */
1949 static bool
1950 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1951 XImagePtr *ximg, Pixmap *pixmap)
1953 #ifdef HAVE_X_WINDOWS
1954 Display *display = FRAME_X_DISPLAY (f);
1955 Drawable drawable = FRAME_X_DRAWABLE (f);
1956 Screen *screen = FRAME_X_SCREEN (f);
1958 eassert (input_blocked_p ());
1960 if (depth <= 0)
1961 depth = DefaultDepthOfScreen (screen);
1962 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1963 depth, ZPixmap, 0, NULL, width, height,
1964 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1965 if (*ximg == NULL)
1967 image_error ("Unable to allocate X image");
1968 return 0;
1971 if (! x_check_image_size (*ximg, width, height))
1973 x_destroy_x_image (*ximg);
1974 *ximg = NULL;
1975 image_error ("Image too large (%dx%d)",
1976 make_number (width), make_number (height));
1977 return 0;
1980 /* Allocate image raster. */
1981 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1983 /* Allocate a pixmap of the same size. */
1984 *pixmap = XCreatePixmap (display, drawable, width, height, depth);
1985 if (*pixmap == NO_PIXMAP)
1987 x_destroy_x_image (*ximg);
1988 *ximg = NULL;
1989 image_error ("Unable to create X pixmap");
1990 return 0;
1993 return 1;
1994 #endif /* HAVE_X_WINDOWS */
1996 #ifdef HAVE_NTGUI
1998 BITMAPINFOHEADER *header;
1999 HDC hdc;
2000 int scanline_width_bits;
2001 int remainder;
2002 int palette_colors = 0;
2004 if (depth == 0)
2005 depth = 24;
2007 if (depth != 1 && depth != 4 && depth != 8
2008 && depth != 16 && depth != 24 && depth != 32)
2010 image_error ("Invalid image bit depth specified");
2011 return 0;
2014 scanline_width_bits = width * depth;
2015 remainder = scanline_width_bits % 32;
2017 if (remainder)
2018 scanline_width_bits += 32 - remainder;
2020 /* Bitmaps with a depth less than 16 need a palette. */
2021 /* BITMAPINFO structure already contains the first RGBQUAD. */
2022 if (depth < 16)
2023 palette_colors = 1 << (depth - 1);
2025 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2027 header = &(*ximg)->info.bmiHeader;
2028 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2029 header->biSize = sizeof (*header);
2030 header->biWidth = width;
2031 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2032 header->biPlanes = 1;
2033 header->biBitCount = depth;
2034 header->biCompression = BI_RGB;
2035 header->biClrUsed = palette_colors;
2037 /* TODO: fill in palette. */
2038 if (depth == 1)
2040 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2041 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2042 (*ximg)->info.bmiColors[0].rgbRed = 0;
2043 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2044 /* bmiColors is a variable-length array declared by w32api
2045 headers as bmiColors[1], which triggers a warning under
2046 -Warray-bounds; shut that up. */
2047 # if GNUC_PREREQ (4, 4, 0)
2048 # pragma GCC push_options
2049 # pragma GCC diagnostic ignored "-Warray-bounds"
2050 # endif
2051 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2052 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2053 (*ximg)->info.bmiColors[1].rgbRed = 255;
2054 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2055 # if GNUC_PREREQ (4, 4, 0)
2056 # pragma GCC pop_options
2057 # endif
2060 hdc = get_frame_dc (f);
2062 /* Create a DIBSection and raster array for the bitmap,
2063 and store its handle in *pixmap. */
2064 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2065 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2066 /* casting avoids a GCC warning */
2067 (void **)&((*ximg)->data), NULL, 0);
2069 /* Realize display palette and garbage all frames. */
2070 release_frame_dc (f, hdc);
2072 if (*pixmap == NULL)
2074 DWORD err = GetLastError ();
2075 Lisp_Object errcode;
2076 /* All system errors are < 10000, so the following is safe. */
2077 XSETINT (errcode, err);
2078 image_error ("Unable to create bitmap, error code %d", errcode);
2079 x_destroy_x_image (*ximg);
2080 *ximg = NULL;
2081 return 0;
2084 return 1;
2086 #endif /* HAVE_NTGUI */
2088 #ifdef HAVE_NS
2089 *pixmap = ns_image_for_XPM (width, height, depth);
2090 if (*pixmap == 0)
2092 *ximg = NULL;
2093 image_error ("Unable to allocate NSImage for XPM pixmap");
2094 return 0;
2096 *ximg = *pixmap;
2097 return 1;
2098 #endif
2102 /* Destroy XImage XIMG. Free XIMG->data. */
2104 static void
2105 x_destroy_x_image (XImagePtr ximg)
2107 eassert (input_blocked_p ());
2108 if (ximg)
2110 #ifdef HAVE_X_WINDOWS
2111 xfree (ximg->data);
2112 ximg->data = NULL;
2113 XDestroyImage (ximg);
2114 #endif /* HAVE_X_WINDOWS */
2115 #ifdef HAVE_NTGUI
2116 /* Data will be freed by DestroyObject. */
2117 ximg->data = NULL;
2118 xfree (ximg);
2119 #endif /* HAVE_NTGUI */
2120 #ifdef HAVE_NS
2121 ns_release_object (ximg);
2122 #endif /* HAVE_NS */
2127 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2128 are width and height of both the image and pixmap. */
2130 static void
2131 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2133 #ifdef HAVE_X_WINDOWS
2134 GC gc;
2136 eassert (input_blocked_p ());
2137 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2138 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2139 XFreeGC (FRAME_X_DISPLAY (f), gc);
2140 #endif /* HAVE_X_WINDOWS */
2142 #ifdef HAVE_NTGUI
2143 #if 0 /* I don't think this is necessary looking at where it is used. */
2144 HDC hdc = get_frame_dc (f);
2145 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2146 release_frame_dc (f, hdc);
2147 #endif
2148 #endif /* HAVE_NTGUI */
2150 #ifdef HAVE_NS
2151 eassert (ximg == pixmap);
2152 ns_retain_object (ximg);
2153 #endif
2156 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2157 with image_put_x_image. */
2159 static bool
2160 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2161 int width, int height, int depth,
2162 XImagePtr *ximg, bool mask_p)
2164 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2166 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2167 !mask_p ? &img->pixmap : &img->mask);
2170 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2171 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2172 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2173 On the other platforms, it puts XIMG into the pixmap, then frees
2174 the X image and its buffer. */
2176 static void
2177 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2178 bool mask_p)
2180 #ifdef HAVE_X_WINDOWS
2181 if (!mask_p)
2183 eassert (img->ximg == NULL);
2184 img->ximg = ximg;
2186 else
2188 eassert (img->mask_img == NULL);
2189 img->mask_img = ximg;
2191 #else
2192 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2193 img->width, img->height);
2194 x_destroy_x_image (ximg);
2195 #endif
2198 #ifdef HAVE_X_WINDOWS
2199 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2200 the X images and their buffers. */
2202 static void
2203 image_sync_to_pixmaps (struct frame *f, struct image *img)
2205 if (img->ximg)
2207 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2208 x_destroy_x_image (img->ximg);
2209 img->ximg = NULL;
2211 if (img->mask_img)
2213 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2214 x_destroy_x_image (img->mask_img);
2215 img->mask_img = NULL;
2218 #endif
2220 #ifdef HAVE_NTGUI
2221 /* Create a memory device context for IMG on frame F. It stores the
2222 currently selected GDI object into *PREV for future restoration by
2223 image_unget_x_image_or_dc. */
2225 static XImagePtr_or_DC
2226 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2227 HGDIOBJ *prev)
2229 HDC frame_dc = get_frame_dc (f);
2230 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2232 release_frame_dc (f, frame_dc);
2233 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2235 return ximg;
2238 static void
2239 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2240 XImagePtr_or_DC ximg, HGDIOBJ prev)
2242 SelectObject (ximg, prev);
2243 DeleteDC (ximg);
2245 #else /* !HAVE_NTGUI */
2246 /* Get the X image for IMG on frame F. The resulting X image data
2247 should be treated as read-only at least on X. */
2249 static XImagePtr
2250 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2252 #ifdef HAVE_X_WINDOWS
2253 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2255 if (ximg_in_img)
2256 return ximg_in_img;
2257 else
2258 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2259 0, 0, img->width, img->height, ~0, ZPixmap);
2260 #elif defined (HAVE_NS)
2261 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2263 ns_retain_object (pixmap);
2264 return pixmap;
2265 #endif
2268 static void
2269 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2271 #ifdef HAVE_X_WINDOWS
2272 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2274 if (ximg_in_img)
2275 eassert (ximg == ximg_in_img);
2276 else
2277 XDestroyImage (ximg);
2278 #elif defined (HAVE_NS)
2279 ns_release_object (ximg);
2280 #endif
2282 #endif /* !HAVE_NTGUI */
2285 /***********************************************************************
2286 File Handling
2287 ***********************************************************************/
2289 /* Find image file FILE. Look in data-directory/images, then
2290 x-bitmap-file-path. Value is the full name of the file
2291 found, or nil if not found. If PFD is nonnull store into *PFD a
2292 readable file descriptor for the file, opened in binary mode. If
2293 PFD is null, do not open the file. */
2295 static Lisp_Object
2296 x_find_image_fd (Lisp_Object file, int *pfd)
2298 Lisp_Object file_found, search_path;
2299 int fd;
2301 /* TODO I think this should use something like image-load-path
2302 instead. Unfortunately, that can contain non-string elements. */
2303 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2304 Vdata_directory),
2305 Vx_bitmap_file_path);
2307 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2308 fd = openp (search_path, file, Qnil, &file_found,
2309 pfd ? Qt : make_number (R_OK), false);
2310 if (fd >= 0 || fd == -2)
2312 file_found = ENCODE_FILE (file_found);
2313 if (fd == -2)
2315 /* The file exists locally, but has a file handler. (This
2316 happens, e.g., under Auto Image File Mode.) 'openp'
2317 didn't open the file, so we should, because the caller
2318 expects that. */
2319 fd = emacs_open (SSDATA (file_found), O_RDONLY, 0);
2322 else /* fd < 0, but not -2 */
2323 return Qnil;
2324 if (pfd)
2325 *pfd = fd;
2326 return file_found;
2329 /* Find image file FILE. Look in data-directory/images, then
2330 x-bitmap-file-path. Value is the encoded full name of the file
2331 found, or nil if not found. */
2333 Lisp_Object
2334 x_find_image_file (Lisp_Object file)
2336 return x_find_image_fd (file, 0);
2339 /* Read FILE into memory. Value is a pointer to a buffer allocated
2340 with xmalloc holding FILE's contents. Value is null if an error
2341 occurred. FD is a file descriptor open for reading FILE. Set
2342 *SIZE to the size of the file. */
2344 static char *
2345 slurp_file (int fd, ptrdiff_t *size)
2347 FILE *fp = fdopen (fd, "rb");
2349 char *buf = NULL;
2350 struct stat st;
2352 if (fp)
2354 ptrdiff_t count = SPECPDL_INDEX ();
2355 record_unwind_protect_ptr (fclose_unwind, fp);
2357 if (fstat (fileno (fp), &st) == 0
2358 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2360 /* Report an error if we read past the purported EOF.
2361 This can happen if the file grows as we read it. */
2362 ptrdiff_t buflen = st.st_size;
2363 buf = xmalloc (buflen + 1);
2364 if (fread_unlocked (buf, 1, buflen + 1, fp) == buflen)
2365 *size = buflen;
2366 else
2368 xfree (buf);
2369 buf = NULL;
2373 unbind_to (count, Qnil);
2376 return buf;
2381 /***********************************************************************
2382 XBM images
2383 ***********************************************************************/
2385 static bool xbm_load (struct frame *f, struct image *img);
2386 static bool xbm_image_p (Lisp_Object object);
2387 static bool xbm_file_p (Lisp_Object);
2390 /* Indices of image specification fields in xbm_format, below. */
2392 enum xbm_keyword_index
2394 XBM_TYPE,
2395 XBM_FILE,
2396 XBM_WIDTH,
2397 XBM_HEIGHT,
2398 XBM_DATA,
2399 XBM_FOREGROUND,
2400 XBM_BACKGROUND,
2401 XBM_ASCENT,
2402 XBM_MARGIN,
2403 XBM_RELIEF,
2404 XBM_ALGORITHM,
2405 XBM_HEURISTIC_MASK,
2406 XBM_MASK,
2407 XBM_LAST
2410 /* Vector of image_keyword structures describing the format
2411 of valid XBM image specifications. */
2413 static const struct image_keyword xbm_format[XBM_LAST] =
2415 {":type", IMAGE_SYMBOL_VALUE, 1},
2416 {":file", IMAGE_STRING_VALUE, 0},
2417 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2418 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2419 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2420 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2421 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2422 {":ascent", IMAGE_ASCENT_VALUE, 0},
2423 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2424 {":relief", IMAGE_INTEGER_VALUE, 0},
2425 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2426 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2427 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2430 /* Structure describing the image type XBM. */
2432 static struct image_type xbm_type =
2434 SYMBOL_INDEX (Qxbm),
2435 xbm_image_p,
2436 xbm_load,
2437 x_clear_image,
2438 NULL,
2439 NULL
2442 /* Tokens returned from xbm_scan. */
2444 enum xbm_token
2446 XBM_TK_IDENT = 256,
2447 XBM_TK_NUMBER,
2448 XBM_TK_OVERFLOW
2452 /* Return true if OBJECT is a valid XBM-type image specification.
2453 A valid specification is a list starting with the symbol `image'
2454 The rest of the list is a property list which must contain an
2455 entry `:type xbm'.
2457 If the specification specifies a file to load, it must contain
2458 an entry `:file FILENAME' where FILENAME is a string.
2460 If the specification is for a bitmap loaded from memory it must
2461 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2462 WIDTH and HEIGHT are integers > 0. DATA may be:
2464 1. a string large enough to hold the bitmap data, i.e. it must
2465 have a size >= (WIDTH + 7) / 8 * HEIGHT
2467 2. a bool-vector of size >= WIDTH * HEIGHT
2469 3. a vector of strings or bool-vectors, one for each line of the
2470 bitmap.
2472 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2473 may not be specified in this case because they are defined in the
2474 XBM file.
2476 Both the file and data forms may contain the additional entries
2477 `:background COLOR' and `:foreground COLOR'. If not present,
2478 foreground and background of the frame on which the image is
2479 displayed is used. */
2481 static bool
2482 xbm_image_p (Lisp_Object object)
2484 struct image_keyword kw[XBM_LAST];
2486 memcpy (kw, xbm_format, sizeof kw);
2487 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2488 return 0;
2490 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2492 if (kw[XBM_FILE].count)
2494 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2495 return 0;
2497 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2499 /* In-memory XBM file. */
2500 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2501 return 0;
2503 else
2505 Lisp_Object data;
2506 int width, height;
2508 /* Entries for `:width', `:height' and `:data' must be present. */
2509 if (!kw[XBM_WIDTH].count
2510 || !kw[XBM_HEIGHT].count
2511 || !kw[XBM_DATA].count)
2512 return 0;
2514 data = kw[XBM_DATA].value;
2515 width = XFASTINT (kw[XBM_WIDTH].value);
2516 height = XFASTINT (kw[XBM_HEIGHT].value);
2518 /* Check type of data, and width and height against contents of
2519 data. */
2520 if (VECTORP (data))
2522 EMACS_INT i;
2524 /* Number of elements of the vector must be >= height. */
2525 if (ASIZE (data) < height)
2526 return 0;
2528 /* Each string or bool-vector in data must be large enough
2529 for one line of the image. */
2530 for (i = 0; i < height; ++i)
2532 Lisp_Object elt = AREF (data, i);
2534 if (STRINGP (elt))
2536 if (SCHARS (elt)
2537 < (width + CHAR_BIT - 1) / CHAR_BIT)
2538 return 0;
2540 else if (BOOL_VECTOR_P (elt))
2542 if (bool_vector_size (elt) < width)
2543 return 0;
2545 else
2546 return 0;
2549 else if (STRINGP (data))
2551 if (SCHARS (data)
2552 < (width + CHAR_BIT - 1) / CHAR_BIT * height)
2553 return 0;
2555 else if (BOOL_VECTOR_P (data))
2557 if (bool_vector_size (data) / height < width)
2558 return 0;
2560 else
2561 return 0;
2564 return 1;
2568 /* Scan a bitmap file. FP is the stream to read from. Value is
2569 either an enumerator from enum xbm_token, or a character for a
2570 single-character token, or 0 at end of file. If scanning an
2571 identifier, store the lexeme of the identifier in SVAL. If
2572 scanning a number, store its value in *IVAL. */
2574 static int
2575 xbm_scan (char **s, char *end, char *sval, int *ival)
2577 unsigned char c UNINIT;
2579 loop:
2581 /* Skip white space. */
2582 while (*s < end && (c = *(*s)++, c_isspace (c)))
2585 if (*s >= end)
2586 c = 0;
2587 else if (c_isdigit (c))
2589 int value = 0, digit;
2590 bool overflow = false;
2592 if (c == '0' && *s < end)
2594 c = *(*s)++;
2595 if (c == 'x' || c == 'X')
2597 while (*s < end)
2599 c = *(*s)++;
2600 digit = char_hexdigit (c);
2601 if (digit < 0)
2602 break;
2603 overflow |= INT_MULTIPLY_WRAPV (value, 16, &value);
2604 value += digit;
2607 else if ('0' <= c && c <= '7')
2609 value = c - '0';
2610 while (*s < end
2611 && (c = *(*s)++, '0' <= c && c <= '7'))
2613 overflow |= INT_MULTIPLY_WRAPV (value, 8, &value);
2614 value += c - '0';
2618 else
2620 value = c - '0';
2621 while (*s < end
2622 && (c = *(*s)++, c_isdigit (c)))
2624 overflow |= INT_MULTIPLY_WRAPV (value, 10, &value);
2625 overflow |= INT_ADD_WRAPV (value, c - '0', &value);
2629 if (*s < end)
2630 *s = *s - 1;
2631 *ival = value;
2632 return overflow ? XBM_TK_OVERFLOW : XBM_TK_NUMBER;
2634 else if (c_isalpha (c) || c == '_')
2636 *sval++ = c;
2637 while (*s < end
2638 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2639 *sval++ = c;
2640 *sval = 0;
2641 if (*s < end)
2642 *s = *s - 1;
2643 return XBM_TK_IDENT;
2645 else if (c == '/' && **s == '*')
2647 /* C-style comment. */
2648 ++*s;
2649 while (**s && (**s != '*' || *(*s + 1) != '/'))
2650 ++*s;
2651 if (**s)
2653 *s += 2;
2654 goto loop;
2658 return c;
2661 #ifdef HAVE_NTGUI
2663 /* Create a Windows bitmap from X bitmap data. */
2664 static HBITMAP
2665 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2667 static unsigned char swap_nibble[16]
2668 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2669 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2670 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2671 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2672 int i, j, w1, w2;
2673 unsigned char *bits, *p;
2674 HBITMAP bmp;
2676 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2677 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2678 bits = alloca (height * w2);
2679 memset (bits, 0, height * w2);
2680 for (i = 0; i < height; i++)
2682 p = bits + i*w2;
2683 for (j = 0; j < w1; j++)
2685 /* Bitswap XBM bytes to match how Windows does things. */
2686 unsigned char c = *data++;
2687 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2688 | (swap_nibble[(c>>4) & 0xf]));
2691 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2693 return bmp;
2696 static void
2697 convert_mono_to_color_image (struct frame *f, struct image *img,
2698 COLORREF foreground, COLORREF background)
2700 HDC hdc, old_img_dc, new_img_dc;
2701 HGDIOBJ old_prev, new_prev;
2702 HBITMAP new_pixmap;
2704 hdc = get_frame_dc (f);
2705 old_img_dc = CreateCompatibleDC (hdc);
2706 new_img_dc = CreateCompatibleDC (hdc);
2707 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2708 release_frame_dc (f, hdc);
2709 old_prev = SelectObject (old_img_dc, img->pixmap);
2710 new_prev = SelectObject (new_img_dc, new_pixmap);
2711 /* Windows convention for mono bitmaps is black = background,
2712 white = foreground. */
2713 SetTextColor (new_img_dc, background);
2714 SetBkColor (new_img_dc, foreground);
2716 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2717 0, 0, SRCCOPY);
2719 SelectObject (old_img_dc, old_prev);
2720 SelectObject (new_img_dc, new_prev);
2721 DeleteDC (old_img_dc);
2722 DeleteDC (new_img_dc);
2723 DeleteObject (img->pixmap);
2724 if (new_pixmap == 0)
2725 fprintf (stderr, "Failed to convert image to color.\n");
2726 else
2727 img->pixmap = new_pixmap;
2730 #define XBM_BIT_SHUFFLE(b) (~(b))
2732 #else
2734 #define XBM_BIT_SHUFFLE(b) (b)
2736 #endif /* HAVE_NTGUI */
2739 static void
2740 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2741 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2742 bool non_default_colors)
2744 #ifdef HAVE_NTGUI
2745 img->pixmap
2746 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2748 /* If colors were specified, transfer the bitmap to a color one. */
2749 if (non_default_colors)
2750 convert_mono_to_color_image (f, img, fg, bg);
2752 #elif defined (HAVE_NS)
2753 img->pixmap = ns_image_from_XBM (data, img->width, img->height, fg, bg);
2755 #else
2756 img->pixmap =
2757 (x_check_image_size (0, img->width, img->height)
2758 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2759 FRAME_X_DRAWABLE (f),
2760 data,
2761 img->width, img->height,
2762 fg, bg,
2763 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2764 : NO_PIXMAP);
2765 #endif /* !HAVE_NTGUI && !HAVE_NS */
2770 /* Replacement for XReadBitmapFileData which isn't available under old
2771 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2772 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2773 the image. Return in *DATA the bitmap data allocated with xmalloc.
2774 Value is true if successful. DATA null means just test if
2775 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2776 inhibit the call to image_error when the image size is invalid (the
2777 bitmap remains unread). */
2779 static bool
2780 xbm_read_bitmap_data (struct frame *f, char *contents, char *end,
2781 int *width, int *height, char **data,
2782 bool inhibit_image_error)
2784 char *s = contents;
2785 char buffer[BUFSIZ];
2786 bool padding_p = 0;
2787 bool v10 = 0;
2788 int bytes_per_line, i, nbytes;
2789 char *p;
2790 int value;
2791 int LA1;
2793 #define match() \
2794 LA1 = xbm_scan (&s, end, buffer, &value)
2796 #define expect(TOKEN) \
2797 do \
2799 if (LA1 != (TOKEN)) \
2800 goto failure; \
2801 match (); \
2803 while (0)
2805 #define expect_ident(IDENT) \
2806 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2807 match (); \
2808 else \
2809 goto failure
2811 *width = *height = -1;
2812 if (data)
2813 *data = NULL;
2814 LA1 = xbm_scan (&s, end, buffer, &value);
2816 /* Parse defines for width, height and hot-spots. */
2817 while (LA1 == '#')
2819 match ();
2820 expect_ident ("define");
2821 expect (XBM_TK_IDENT);
2823 if (LA1 == XBM_TK_NUMBER)
2825 char *q = strrchr (buffer, '_');
2826 q = q ? q + 1 : buffer;
2827 if (strcmp (q, "width") == 0)
2828 *width = value;
2829 else if (strcmp (q, "height") == 0)
2830 *height = value;
2832 expect (XBM_TK_NUMBER);
2835 if (!check_image_size (f, *width, *height))
2837 if (!inhibit_image_error)
2838 image_size_error ();
2839 goto failure;
2841 else if (data == NULL)
2842 goto success;
2844 /* Parse bits. Must start with `static'. */
2845 expect_ident ("static");
2846 if (LA1 == XBM_TK_IDENT)
2848 if (strcmp (buffer, "unsigned") == 0)
2850 match ();
2851 expect_ident ("char");
2853 else if (strcmp (buffer, "short") == 0)
2855 match ();
2856 v10 = 1;
2857 if (*width % 16 && *width % 16 < 9)
2858 padding_p = 1;
2860 else if (strcmp (buffer, "char") == 0)
2861 match ();
2862 else
2863 goto failure;
2865 else
2866 goto failure;
2868 expect (XBM_TK_IDENT);
2869 expect ('[');
2870 expect (']');
2871 expect ('=');
2872 expect ('{');
2874 if (! x_check_image_size (0, *width, *height))
2876 if (!inhibit_image_error)
2877 image_error ("Image too large (%dx%d)",
2878 make_number (*width), make_number (*height));
2879 goto failure;
2881 bytes_per_line = (*width + 7) / 8 + padding_p;
2882 nbytes = bytes_per_line * *height;
2883 p = *data = xmalloc (nbytes);
2885 if (v10)
2887 for (i = 0; i < nbytes; i += 2)
2889 int val = value;
2890 expect (XBM_TK_NUMBER);
2892 *p++ = XBM_BIT_SHUFFLE (val);
2893 if (!padding_p || ((i + 2) % bytes_per_line))
2894 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2896 if (LA1 == ',' || LA1 == '}')
2897 match ();
2898 else
2899 goto failure;
2902 else
2904 for (i = 0; i < nbytes; ++i)
2906 int val = value;
2907 expect (XBM_TK_NUMBER);
2909 *p++ = XBM_BIT_SHUFFLE (val);
2911 if (LA1 == ',' || LA1 == '}')
2912 match ();
2913 else
2914 goto failure;
2918 success:
2919 return 1;
2921 failure:
2923 if (data && *data)
2925 xfree (*data);
2926 *data = NULL;
2928 return 0;
2930 #undef match
2931 #undef expect
2932 #undef expect_ident
2936 /* Load XBM image IMG which will be displayed on frame F from buffer
2937 CONTENTS. END is the end of the buffer. Value is true if
2938 successful. */
2940 static bool
2941 xbm_load_image (struct frame *f, struct image *img, char *contents, char *end)
2943 bool rc;
2944 char *data;
2945 bool success_p = 0;
2947 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2948 &data, 0);
2949 if (rc)
2951 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2952 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2953 bool non_default_colors = 0;
2954 Lisp_Object value;
2956 eassert (img->width > 0 && img->height > 0);
2958 /* Get foreground and background colors, maybe allocate colors. */
2959 value = image_spec_value (img->spec, QCforeground, NULL);
2960 if (!NILP (value))
2962 foreground = x_alloc_image_color (f, img, value, foreground);
2963 non_default_colors = 1;
2965 value = image_spec_value (img->spec, QCbackground, NULL);
2966 if (!NILP (value))
2968 background = x_alloc_image_color (f, img, value, background);
2969 img->background = background;
2970 img->background_valid = 1;
2971 non_default_colors = 1;
2974 Create_Pixmap_From_Bitmap_Data (f, img, data,
2975 foreground, background,
2976 non_default_colors);
2977 xfree (data);
2979 if (img->pixmap == NO_PIXMAP)
2981 x_clear_image (f, img);
2982 image_error ("Unable to create X pixmap for `%s'", img->spec);
2984 else
2985 success_p = 1;
2987 else
2988 image_error ("Error loading XBM image `%s'", img->spec);
2990 return success_p;
2994 /* Value is true if DATA looks like an in-memory XBM file. */
2996 static bool
2997 xbm_file_p (Lisp_Object data)
2999 int w, h;
3000 return (STRINGP (data)
3001 && xbm_read_bitmap_data (NULL, SSDATA (data),
3002 SSDATA (data) + SBYTES (data),
3003 &w, &h, NULL, 1));
3007 /* Fill image IMG which is used on frame F with pixmap data. Value is
3008 true if successful. */
3010 static bool
3011 xbm_load (struct frame *f, struct image *img)
3013 bool success_p = 0;
3014 Lisp_Object file_name;
3016 eassert (xbm_image_p (img->spec));
3018 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3019 file_name = image_spec_value (img->spec, QCfile, NULL);
3020 if (STRINGP (file_name))
3022 int fd;
3023 Lisp_Object file = x_find_image_fd (file_name, &fd);
3024 if (!STRINGP (file))
3026 image_error ("Cannot find image file `%s'", file_name);
3027 return 0;
3030 ptrdiff_t size;
3031 char *contents = slurp_file (fd, &size);
3032 if (contents == NULL)
3034 image_error ("Error loading XBM image `%s'", file);
3035 return 0;
3038 success_p = xbm_load_image (f, img, contents, contents + size);
3039 xfree (contents);
3041 else
3043 struct image_keyword fmt[XBM_LAST];
3044 Lisp_Object data;
3045 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3046 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3047 bool non_default_colors = 0;
3048 char *bits;
3049 bool parsed_p;
3050 bool in_memory_file_p = 0;
3052 /* See if data looks like an in-memory XBM file. */
3053 data = image_spec_value (img->spec, QCdata, NULL);
3054 in_memory_file_p = xbm_file_p (data);
3056 /* Parse the image specification. */
3057 memcpy (fmt, xbm_format, sizeof fmt);
3058 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3059 eassert (parsed_p);
3061 /* Get specified width, and height. */
3062 if (!in_memory_file_p)
3064 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3065 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3066 eassert (img->width > 0 && img->height > 0);
3067 if (!check_image_size (f, img->width, img->height))
3069 image_size_error ();
3070 return 0;
3074 /* Get foreground and background colors, maybe allocate colors. */
3075 if (fmt[XBM_FOREGROUND].count
3076 && STRINGP (fmt[XBM_FOREGROUND].value))
3078 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3079 foreground);
3080 non_default_colors = 1;
3083 if (fmt[XBM_BACKGROUND].count
3084 && STRINGP (fmt[XBM_BACKGROUND].value))
3086 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3087 background);
3088 non_default_colors = 1;
3091 if (in_memory_file_p)
3092 success_p = xbm_load_image (f, img, SSDATA (data),
3093 SSDATA (data) + SBYTES (data));
3094 else
3096 USE_SAFE_ALLOCA;
3098 if (VECTORP (data))
3100 int i;
3101 char *p;
3102 int nbytes = (img->width + CHAR_BIT - 1) / CHAR_BIT;
3104 SAFE_NALLOCA (bits, nbytes, img->height);
3105 p = bits;
3106 for (i = 0; i < img->height; ++i, p += nbytes)
3108 Lisp_Object line = AREF (data, i);
3109 if (STRINGP (line))
3110 memcpy (p, SDATA (line), nbytes);
3111 else
3112 memcpy (p, bool_vector_data (line), nbytes);
3115 else if (STRINGP (data))
3116 bits = SSDATA (data);
3117 else
3118 bits = (char *) bool_vector_data (data);
3120 #ifdef HAVE_NTGUI
3122 char *invertedBits;
3123 int nbytes, i;
3124 /* Windows mono bitmaps are reversed compared with X. */
3125 invertedBits = bits;
3126 nbytes = (img->width + CHAR_BIT - 1) / CHAR_BIT * img->height;
3127 SAFE_NALLOCA (bits, 1, nbytes);
3128 for (i = 0; i < nbytes; i++)
3129 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3131 #endif
3132 /* Create the pixmap. */
3134 if (x_check_image_size (0, img->width, img->height))
3135 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3136 foreground, background,
3137 non_default_colors);
3138 else
3139 img->pixmap = NO_PIXMAP;
3141 if (img->pixmap)
3142 success_p = 1;
3143 else
3145 image_error ("Unable to create pixmap for XBM image `%s'",
3146 img->spec);
3147 x_clear_image (f, img);
3150 SAFE_FREE ();
3154 return success_p;
3159 /***********************************************************************
3160 XPM images
3161 ***********************************************************************/
3163 #if defined (HAVE_XPM) || defined (HAVE_NS)
3165 static bool xpm_image_p (Lisp_Object object);
3166 static bool xpm_load (struct frame *f, struct image *img);
3168 #endif /* HAVE_XPM || HAVE_NS */
3170 #ifdef HAVE_XPM
3171 #ifdef HAVE_NTGUI
3172 /* Indicate to xpm.h that we don't have Xlib. */
3173 #define FOR_MSW
3174 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3175 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3176 #define XColor xpm_XColor
3177 #define XImage xpm_XImage
3178 #define Display xpm_Display
3179 #ifdef CYGWIN
3180 #include "noX/xpm.h"
3181 #else /* not CYGWIN */
3182 #include "X11/xpm.h"
3183 #endif /* not CYGWIN */
3184 #undef FOR_MSW
3185 #undef XColor
3186 #undef XImage
3187 #undef Display
3188 #else /* not HAVE_NTGUI */
3189 #include "X11/xpm.h"
3190 #endif /* not HAVE_NTGUI */
3191 #endif /* HAVE_XPM */
3193 #if defined (HAVE_XPM) || defined (HAVE_NS)
3195 /* Indices of image specification fields in xpm_format, below. */
3197 enum xpm_keyword_index
3199 XPM_TYPE,
3200 XPM_FILE,
3201 XPM_DATA,
3202 XPM_ASCENT,
3203 XPM_MARGIN,
3204 XPM_RELIEF,
3205 XPM_ALGORITHM,
3206 XPM_HEURISTIC_MASK,
3207 XPM_MASK,
3208 XPM_COLOR_SYMBOLS,
3209 XPM_BACKGROUND,
3210 XPM_LAST
3213 /* Vector of image_keyword structures describing the format
3214 of valid XPM image specifications. */
3216 static const struct image_keyword xpm_format[XPM_LAST] =
3218 {":type", IMAGE_SYMBOL_VALUE, 1},
3219 {":file", IMAGE_STRING_VALUE, 0},
3220 {":data", IMAGE_STRING_VALUE, 0},
3221 {":ascent", IMAGE_ASCENT_VALUE, 0},
3222 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3223 {":relief", IMAGE_INTEGER_VALUE, 0},
3224 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3225 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3226 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3227 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3228 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3231 #if defined HAVE_NTGUI && defined WINDOWSNT
3232 static bool init_xpm_functions (void);
3233 #else
3234 #define init_xpm_functions NULL
3235 #endif
3237 /* Structure describing the image type XPM. */
3239 static struct image_type xpm_type =
3241 SYMBOL_INDEX (Qxpm),
3242 xpm_image_p,
3243 xpm_load,
3244 x_clear_image,
3245 init_xpm_functions,
3246 NULL
3249 #ifdef HAVE_X_WINDOWS
3251 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3252 functions for allocating image colors. Our own functions handle
3253 color allocation failures more gracefully than the ones on the XPM
3254 lib. */
3256 #ifndef USE_CAIRO
3257 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3258 #define ALLOC_XPM_COLORS
3259 #endif
3260 #endif /* USE_CAIRO */
3261 #endif /* HAVE_X_WINDOWS */
3263 #ifdef ALLOC_XPM_COLORS
3265 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3266 XColor *, int);
3268 /* An entry in a hash table used to cache color definitions of named
3269 colors. This cache is necessary to speed up XPM image loading in
3270 case we do color allocations ourselves. Without it, we would need
3271 a call to XParseColor per pixel in the image.
3273 FIXME Now that we're using x_parse_color and its cache, reevaluate
3274 the need for this caching layer. */
3276 struct xpm_cached_color
3278 /* Next in collision chain. */
3279 struct xpm_cached_color *next;
3281 /* Color definition (RGB and pixel color). */
3282 XColor color;
3284 /* Color name. */
3285 char name[FLEXIBLE_ARRAY_MEMBER];
3288 /* The hash table used for the color cache, and its bucket vector
3289 size. */
3291 #define XPM_COLOR_CACHE_BUCKETS 1001
3292 static struct xpm_cached_color **xpm_color_cache;
3294 /* Initialize the color cache. */
3296 static void
3297 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3299 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3300 xpm_color_cache = xzalloc (nbytes);
3301 init_color_table ();
3303 if (attrs->valuemask & XpmColorSymbols)
3305 int i;
3306 XColor color;
3308 for (i = 0; i < attrs->numsymbols; ++i)
3309 if (x_parse_color (f, attrs->colorsymbols[i].value, &color))
3311 color.pixel = lookup_rgb_color (f, color.red, color.green,
3312 color.blue);
3313 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3318 /* Free the color cache. */
3320 static void
3321 xpm_free_color_cache (void)
3323 struct xpm_cached_color *p, *next;
3324 int i;
3326 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3327 for (p = xpm_color_cache[i]; p; p = next)
3329 next = p->next;
3330 xfree (p);
3333 xfree (xpm_color_cache);
3334 xpm_color_cache = NULL;
3335 free_color_table ();
3338 /* Return the bucket index for color named COLOR_NAME in the color
3339 cache. */
3341 static int
3342 xpm_color_bucket (char *color_name)
3344 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3345 return hash % XPM_COLOR_CACHE_BUCKETS;
3349 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3350 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3351 entry added. */
3353 static struct xpm_cached_color *
3354 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3356 size_t nbytes;
3357 struct xpm_cached_color *p;
3359 if (bucket < 0)
3360 bucket = xpm_color_bucket (color_name);
3362 nbytes = FLEXSIZEOF (struct xpm_cached_color, name, strlen (color_name) + 1);
3363 p = xmalloc (nbytes);
3364 strcpy (p->name, color_name);
3365 p->color = *color;
3366 p->next = xpm_color_cache[bucket];
3367 xpm_color_cache[bucket] = p;
3368 return p;
3371 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3372 return the cached definition in *COLOR. Otherwise, make a new
3373 entry in the cache and allocate the color. Value is false if color
3374 allocation failed. */
3376 static bool
3377 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3379 struct xpm_cached_color *p;
3380 int h = xpm_color_bucket (color_name);
3382 for (p = xpm_color_cache[h]; p; p = p->next)
3383 if (strcmp (p->name, color_name) == 0)
3384 break;
3386 if (p != NULL)
3387 *color = p->color;
3388 else if (x_parse_color (f, color_name, color))
3390 color->pixel = lookup_rgb_color (f, color->red, color->green,
3391 color->blue);
3392 p = xpm_cache_color (f, color_name, color, h);
3394 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3395 with transparency, and it's useful. */
3396 else if (strcmp ("opaque", color_name) == 0)
3398 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3399 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3400 p = xpm_cache_color (f, color_name, color, h);
3403 return p != NULL;
3407 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3408 CLOSURE is a pointer to the frame on which we allocate the
3409 color. Return in *COLOR the allocated color. Value is non-zero
3410 if successful. */
3412 static int
3413 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3414 void *closure)
3416 return xpm_lookup_color (closure, color_name, color);
3420 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3421 is a pointer to the frame on which we allocate the color. Value is
3422 non-zero if successful. */
3424 static int
3425 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3427 return 1;
3430 #endif /* ALLOC_XPM_COLORS */
3433 #ifdef WINDOWSNT
3435 /* XPM library details. */
3437 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3438 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3439 (Display *, char *, xpm_XImage **,
3440 xpm_XImage **, XpmAttributes *));
3441 DEF_DLL_FN (int, XpmReadFileToImage,
3442 (Display *, char *, xpm_XImage **,
3443 xpm_XImage **, XpmAttributes *));
3444 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3446 static bool
3447 init_xpm_functions (void)
3449 HMODULE library;
3451 if (!(library = w32_delayed_load (Qxpm)))
3452 return 0;
3454 LOAD_DLL_FN (library, XpmFreeAttributes);
3455 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3456 LOAD_DLL_FN (library, XpmReadFileToImage);
3457 LOAD_DLL_FN (library, XImageFree);
3458 return 1;
3461 # undef XImageFree
3462 # undef XpmCreateImageFromBuffer
3463 # undef XpmFreeAttributes
3464 # undef XpmReadFileToImage
3466 # define XImageFree fn_XImageFree
3467 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3468 # define XpmFreeAttributes fn_XpmFreeAttributes
3469 # define XpmReadFileToImage fn_XpmReadFileToImage
3471 #endif /* WINDOWSNT */
3473 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3474 for XPM images. Such a list must consist of conses whose car and
3475 cdr are strings. */
3477 static bool
3478 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3480 while (CONSP (color_symbols))
3482 Lisp_Object sym = XCAR (color_symbols);
3483 if (!CONSP (sym)
3484 || !STRINGP (XCAR (sym))
3485 || !STRINGP (XCDR (sym)))
3486 break;
3487 color_symbols = XCDR (color_symbols);
3490 return NILP (color_symbols);
3494 /* Value is true if OBJECT is a valid XPM image specification. */
3496 static bool
3497 xpm_image_p (Lisp_Object object)
3499 struct image_keyword fmt[XPM_LAST];
3500 memcpy (fmt, xpm_format, sizeof fmt);
3501 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3502 /* Either `:file' or `:data' must be present. */
3503 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3504 /* Either no `:color-symbols' or it's a list of conses
3505 whose car and cdr are strings. */
3506 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3507 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3510 #endif /* HAVE_XPM || HAVE_NS */
3512 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3513 ptrdiff_t
3514 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3516 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3517 ptrdiff_t id;
3518 int rc;
3519 XpmAttributes attrs;
3520 Pixmap bitmap, mask;
3522 memset (&attrs, 0, sizeof attrs);
3524 attrs.visual = FRAME_X_VISUAL (f);
3525 attrs.colormap = FRAME_X_COLORMAP (f);
3526 attrs.valuemask |= XpmVisual;
3527 attrs.valuemask |= XpmColormap;
3529 #ifdef ALLOC_XPM_COLORS
3530 attrs.color_closure = f;
3531 attrs.alloc_color = xpm_alloc_color;
3532 attrs.free_colors = xpm_free_colors;
3533 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3534 xpm_init_color_cache (f, &attrs);
3535 #endif
3537 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
3538 (char **) bits, &bitmap, &mask, &attrs);
3539 if (rc != XpmSuccess)
3541 XpmFreeAttributes (&attrs);
3542 return -1;
3545 id = x_allocate_bitmap_record (f);
3546 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3547 dpyinfo->bitmaps[id - 1].have_mask = true;
3548 dpyinfo->bitmaps[id - 1].mask = mask;
3549 dpyinfo->bitmaps[id - 1].file = NULL;
3550 dpyinfo->bitmaps[id - 1].height = attrs.height;
3551 dpyinfo->bitmaps[id - 1].width = attrs.width;
3552 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3553 dpyinfo->bitmaps[id - 1].refcount = 1;
3555 #ifdef ALLOC_XPM_COLORS
3556 xpm_free_color_cache ();
3557 #endif
3558 XpmFreeAttributes (&attrs);
3559 return id;
3561 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3563 /* Load image IMG which will be displayed on frame F. Value is
3564 true if successful. */
3566 #ifdef HAVE_XPM
3568 static bool
3569 xpm_load (struct frame *f, struct image *img)
3571 int rc;
3572 XpmAttributes attrs;
3573 Lisp_Object specified_file, color_symbols;
3574 USE_SAFE_ALLOCA;
3576 #ifdef HAVE_NTGUI
3577 HDC hdc;
3578 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3579 #endif /* HAVE_NTGUI */
3581 /* Configure the XPM lib. Use the visual of frame F. Allocate
3582 close colors. Return colors allocated. */
3583 memset (&attrs, 0, sizeof attrs);
3585 #ifndef HAVE_NTGUI
3586 attrs.visual = FRAME_X_VISUAL (f);
3587 attrs.colormap = FRAME_X_COLORMAP (f);
3588 attrs.valuemask |= XpmVisual;
3589 attrs.valuemask |= XpmColormap;
3590 #endif /* HAVE_NTGUI */
3592 #ifdef ALLOC_XPM_COLORS
3593 /* Allocate colors with our own functions which handle
3594 failing color allocation more gracefully. */
3595 attrs.color_closure = f;
3596 attrs.alloc_color = xpm_alloc_color;
3597 attrs.free_colors = xpm_free_colors;
3598 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3599 #else /* not ALLOC_XPM_COLORS */
3600 /* Let the XPM lib allocate colors. */
3601 attrs.valuemask |= XpmReturnAllocPixels;
3602 #ifdef XpmAllocCloseColors
3603 attrs.alloc_close_colors = 1;
3604 attrs.valuemask |= XpmAllocCloseColors;
3605 #else /* not XpmAllocCloseColors */
3606 attrs.closeness = 600;
3607 attrs.valuemask |= XpmCloseness;
3608 #endif /* not XpmAllocCloseColors */
3609 #endif /* ALLOC_XPM_COLORS */
3611 /* If image specification contains symbolic color definitions, add
3612 these to `attrs'. */
3613 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3614 if (CONSP (color_symbols))
3616 Lisp_Object tail;
3617 XpmColorSymbol *xpm_syms;
3618 ptrdiff_t i, size;
3620 attrs.valuemask |= XpmColorSymbols;
3622 /* Count number of symbols. */
3623 attrs.numsymbols = 0;
3624 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3625 ++attrs.numsymbols;
3627 /* Allocate an XpmColorSymbol array. */
3628 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3629 size = attrs.numsymbols * sizeof *xpm_syms;
3630 memset (xpm_syms, 0, size);
3631 attrs.colorsymbols = xpm_syms;
3633 /* Fill the color symbol array. */
3634 for (tail = color_symbols, i = 0;
3635 CONSP (tail);
3636 ++i, tail = XCDR (tail))
3638 Lisp_Object name;
3639 Lisp_Object color;
3640 char *empty_string = (char *) "";
3642 if (!CONSP (XCAR (tail)))
3644 xpm_syms[i].name = empty_string;
3645 xpm_syms[i].value = empty_string;
3646 continue;
3648 name = XCAR (XCAR (tail));
3649 color = XCDR (XCAR (tail));
3650 if (STRINGP (name))
3651 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3652 else
3653 xpm_syms[i].name = empty_string;
3654 if (STRINGP (color))
3655 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3656 else
3657 xpm_syms[i].value = empty_string;
3661 /* Create a pixmap for the image, either from a file, or from a
3662 string buffer containing data in the same format as an XPM file. */
3663 #ifdef ALLOC_XPM_COLORS
3664 xpm_init_color_cache (f, &attrs);
3665 #endif
3667 specified_file = image_spec_value (img->spec, QCfile, NULL);
3669 #ifdef HAVE_NTGUI
3671 HDC frame_dc = get_frame_dc (f);
3672 hdc = CreateCompatibleDC (frame_dc);
3673 release_frame_dc (f, frame_dc);
3675 #endif /* HAVE_NTGUI */
3677 if (STRINGP (specified_file))
3679 Lisp_Object file = x_find_image_file (specified_file);
3680 if (!STRINGP (file))
3682 image_error ("Cannot find image file `%s'", specified_file);
3683 #ifdef ALLOC_XPM_COLORS
3684 xpm_free_color_cache ();
3685 #endif
3686 SAFE_FREE ();
3687 return 0;
3690 file = ENCODE_FILE (file);
3691 #ifdef HAVE_NTGUI
3692 #ifdef WINDOWSNT
3693 /* FILE is encoded in UTF-8, but image libraries on Windows
3694 support neither UTF-8 nor UTF-16 encoded file names. So we
3695 need to re-encode it in ANSI. */
3696 file = ansi_encode_filename (file);
3697 #endif
3698 /* XpmReadFileToPixmap is not available in the Windows port of
3699 libxpm. But XpmReadFileToImage almost does what we want. */
3700 rc = XpmReadFileToImage (&hdc, SSDATA (file),
3701 &xpm_image, &xpm_mask,
3702 &attrs);
3703 #else
3704 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3705 &img->ximg, &img->mask_img,
3706 &attrs);
3707 #endif /* HAVE_NTGUI */
3709 else
3711 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3712 if (!STRINGP (buffer))
3714 image_error ("Invalid image data `%s'", buffer);
3715 #ifdef ALLOC_XPM_COLORS
3716 xpm_free_color_cache ();
3717 #endif
3718 SAFE_FREE ();
3719 return 0;
3721 #ifdef HAVE_NTGUI
3722 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3723 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3724 rc = XpmCreateImageFromBuffer (&hdc, SSDATA (buffer),
3725 &xpm_image, &xpm_mask,
3726 &attrs);
3727 #else
3728 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3729 &img->ximg, &img->mask_img,
3730 &attrs);
3731 #endif /* HAVE_NTGUI */
3734 #ifdef USE_CAIRO
3735 /* Load very specific Xpm:s. */
3736 if (rc == XpmSuccess
3737 && img->ximg->format == ZPixmap
3738 && img->ximg->bits_per_pixel == 32
3739 && (! img->mask_img || img->mask_img->bits_per_pixel == 1))
3741 int width = img->ximg->width;
3742 int height = img->ximg->height;
3743 void *data = xmalloc (width * height * 4);
3744 int i;
3745 uint32_t *od = data;
3746 uint32_t *id = (uint32_t *) img->ximg->data;
3747 char *mid = img->mask_img ? img->mask_img->data : 0;
3748 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
3750 for (i = 0; i < height; ++i)
3752 int k;
3753 for (k = 0; k < width; ++k)
3755 int idx = i * img->ximg->bytes_per_line/4 + k;
3756 int maskidx = mid ? i * img->mask_img->bytes_per_line + k/8 : 0;
3757 int mask = mid ? mid[maskidx] & (1 << (k % 8)) : 1;
3759 if (mask) od[idx] = id[idx] + 0xff000000; /* ff => full alpha */
3760 else od[idx] = bgcolor;
3764 create_cairo_image_surface (img, data, width, height);
3766 else
3768 rc = XpmFileInvalid;
3769 x_clear_image (f, img);
3771 #else
3772 #ifdef HAVE_X_WINDOWS
3773 if (rc == XpmSuccess)
3775 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
3776 img->ximg->width, img->ximg->height,
3777 img->ximg->depth);
3778 if (img->pixmap == NO_PIXMAP)
3780 x_clear_image (f, img);
3781 rc = XpmNoMemory;
3783 else if (img->mask_img)
3785 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
3786 img->mask_img->width,
3787 img->mask_img->height,
3788 img->mask_img->depth);
3789 if (img->mask == NO_PIXMAP)
3791 x_clear_image (f, img);
3792 rc = XpmNoMemory;
3796 #endif
3797 #endif /* ! USE_CAIRO */
3799 if (rc == XpmSuccess)
3801 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3802 img->colors = colors_in_color_table (&img->ncolors);
3803 #else /* not ALLOC_XPM_COLORS */
3804 int i;
3806 #ifdef HAVE_NTGUI
3807 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3808 plus some duplicate attributes. */
3809 if (xpm_image && xpm_image->bitmap)
3811 img->pixmap = xpm_image->bitmap;
3812 /* XImageFree in libXpm frees XImage struct without destroying
3813 the bitmap, which is what we want. */
3814 XImageFree (xpm_image);
3816 if (xpm_mask && xpm_mask->bitmap)
3818 /* The mask appears to be inverted compared with what we expect.
3819 TODO: invert our expectations. See other places where we
3820 have to invert bits because our idea of masks is backwards. */
3821 HGDIOBJ old_obj;
3822 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3824 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3825 SelectObject (hdc, old_obj);
3827 img->mask = xpm_mask->bitmap;
3828 XImageFree (xpm_mask);
3829 DeleteDC (hdc);
3832 DeleteDC (hdc);
3833 #endif /* HAVE_NTGUI */
3835 /* Remember allocated colors. */
3836 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3837 img->ncolors = attrs.nalloc_pixels;
3838 for (i = 0; i < attrs.nalloc_pixels; ++i)
3840 img->colors[i] = attrs.alloc_pixels[i];
3841 #ifdef DEBUG_X_COLORS
3842 register_color (img->colors[i]);
3843 #endif
3845 #endif /* not ALLOC_XPM_COLORS */
3847 img->width = attrs.width;
3848 img->height = attrs.height;
3849 eassert (img->width > 0 && img->height > 0);
3851 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3852 XpmFreeAttributes (&attrs);
3854 #ifdef HAVE_X_WINDOWS
3855 /* Maybe fill in the background field while we have ximg handy. */
3856 IMAGE_BACKGROUND (img, f, img->ximg);
3857 if (img->mask_img)
3858 /* Fill in the background_transparent field while we have the
3859 mask handy. */
3860 image_background_transparent (img, f, img->mask_img);
3861 #endif
3863 else
3865 #ifdef HAVE_NTGUI
3866 DeleteDC (hdc);
3867 #endif /* HAVE_NTGUI */
3869 switch (rc)
3871 case XpmOpenFailed:
3872 image_error ("Error opening XPM file (%s)", img->spec);
3873 break;
3875 case XpmFileInvalid:
3876 image_error ("Invalid XPM file (%s)", img->spec);
3877 break;
3879 case XpmNoMemory:
3880 image_error ("Out of memory (%s)", img->spec);
3881 break;
3883 case XpmColorFailed:
3884 image_error ("Color allocation error (%s)", img->spec);
3885 break;
3887 default:
3888 image_error ("Unknown error (%s)", img->spec);
3889 break;
3893 #ifdef ALLOC_XPM_COLORS
3894 xpm_free_color_cache ();
3895 #endif
3896 SAFE_FREE ();
3897 return rc == XpmSuccess;
3900 #endif /* HAVE_XPM */
3902 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3904 /* XPM support functions for NS where libxpm is not available.
3905 Only XPM version 3 (without any extensions) is supported. */
3907 static void xpm_put_color_table_v (Lisp_Object, const char *,
3908 int, Lisp_Object);
3909 static Lisp_Object xpm_get_color_table_v (Lisp_Object, const char *, int);
3910 static void xpm_put_color_table_h (Lisp_Object, const char *,
3911 int, Lisp_Object);
3912 static Lisp_Object xpm_get_color_table_h (Lisp_Object, const char *, int);
3914 /* Tokens returned from xpm_scan. */
3916 enum xpm_token
3918 XPM_TK_IDENT = 256,
3919 XPM_TK_STRING,
3920 XPM_TK_EOF
3923 /* Scan an XPM data and return a character (< 256) or a token defined
3924 by enum xpm_token above. *S and END are the start (inclusive) and
3925 the end (exclusive) addresses of the data, respectively. Advance
3926 *S while scanning. If token is either XPM_TK_IDENT or
3927 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3928 length of the corresponding token, respectively. */
3930 static int
3931 xpm_scan (const char **s, const char *end, const char **beg, ptrdiff_t *len)
3933 unsigned char c;
3935 while (*s < end)
3937 /* Skip white-space. */
3938 while (*s < end && (c = *(*s)++, c_isspace (c)))
3941 /* gnus-pointer.xpm uses '-' in its identifier.
3942 sb-dir-plus.xpm uses '+' in its identifier. */
3943 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3945 *beg = *s - 1;
3946 while (*s < end
3947 && (c = **s, c_isalnum (c)
3948 || c == '_' || c == '-' || c == '+'))
3949 ++*s;
3950 *len = *s - *beg;
3951 return XPM_TK_IDENT;
3953 else if (c == '"')
3955 *beg = *s;
3956 while (*s < end && **s != '"')
3957 ++*s;
3958 *len = *s - *beg;
3959 if (*s < end)
3960 ++*s;
3961 return XPM_TK_STRING;
3963 else if (c == '/')
3965 if (*s < end && **s == '*')
3967 /* C-style comment. */
3968 ++*s;
3971 while (*s < end && *(*s)++ != '*')
3974 while (*s < end && **s != '/');
3975 if (*s < end)
3976 ++*s;
3978 else
3979 return c;
3981 else
3982 return c;
3985 return XPM_TK_EOF;
3988 /* Functions for color table lookup in XPM data. A key is a string
3989 specifying the color of each pixel in XPM data. A value is either
3990 an integer that specifies a pixel color, Qt that specifies
3991 transparency, or Qnil for the unspecified color. If the length of
3992 the key string is one, a vector is used as a table. Otherwise, a
3993 hash table is used. */
3995 static Lisp_Object
3996 xpm_make_color_table_v (void (**put_func) (Lisp_Object, const char *, int,
3997 Lisp_Object),
3998 Lisp_Object (**get_func) (Lisp_Object, const char *,
3999 int))
4001 *put_func = xpm_put_color_table_v;
4002 *get_func = xpm_get_color_table_v;
4003 return Fmake_vector (make_number (256), Qnil);
4006 static void
4007 xpm_put_color_table_v (Lisp_Object color_table,
4008 const char *chars_start,
4009 int chars_len,
4010 Lisp_Object color)
4012 unsigned char uc = *chars_start;
4013 ASET (color_table, uc, color);
4016 static Lisp_Object
4017 xpm_get_color_table_v (Lisp_Object color_table,
4018 const char *chars_start,
4019 int chars_len)
4021 unsigned char uc = *chars_start;
4022 return AREF (color_table, uc);
4025 static Lisp_Object
4026 xpm_make_color_table_h (void (**put_func) (Lisp_Object, const char *, int,
4027 Lisp_Object),
4028 Lisp_Object (**get_func) (Lisp_Object, const char *,
4029 int))
4031 *put_func = xpm_put_color_table_h;
4032 *get_func = xpm_get_color_table_h;
4033 return make_hash_table (hashtest_equal, DEFAULT_HASH_SIZE,
4034 DEFAULT_REHASH_SIZE, DEFAULT_REHASH_THRESHOLD,
4035 Qnil, false);
4038 static void
4039 xpm_put_color_table_h (Lisp_Object color_table,
4040 const char *chars_start,
4041 int chars_len,
4042 Lisp_Object color)
4044 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4045 EMACS_UINT hash_code;
4046 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4048 hash_lookup (table, chars, &hash_code);
4049 hash_put (table, chars, color, hash_code);
4052 static Lisp_Object
4053 xpm_get_color_table_h (Lisp_Object color_table,
4054 const char *chars_start,
4055 int chars_len)
4057 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4058 ptrdiff_t i =
4059 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
4061 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4064 enum xpm_color_key {
4065 XPM_COLOR_KEY_S,
4066 XPM_COLOR_KEY_M,
4067 XPM_COLOR_KEY_G4,
4068 XPM_COLOR_KEY_G,
4069 XPM_COLOR_KEY_C
4072 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4074 static int
4075 xpm_str_to_color_key (const char *s)
4077 int i;
4079 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
4080 if (strcmp (xpm_color_key_strings[i], s) == 0)
4081 return i;
4082 return -1;
4085 static bool
4086 xpm_load_image (struct frame *f,
4087 struct image *img,
4088 const char *contents,
4089 const char *end)
4091 const char *s = contents, *beg, *str;
4092 char buffer[BUFSIZ];
4093 int width, height, x, y;
4094 int num_colors, chars_per_pixel;
4095 ptrdiff_t len;
4096 int LA1;
4097 void (*put_color_table) (Lisp_Object, const char *, int, Lisp_Object);
4098 Lisp_Object (*get_color_table) (Lisp_Object, const char *, int);
4099 Lisp_Object frame, color_symbols, color_table;
4100 int best_key;
4101 #ifndef HAVE_NS
4102 bool have_mask = false;
4103 #endif
4104 XImagePtr ximg = NULL, mask_img = NULL;
4106 #define match() \
4107 LA1 = xpm_scan (&s, end, &beg, &len)
4109 #define expect(TOKEN) \
4110 do \
4112 if (LA1 != (TOKEN)) \
4113 goto failure; \
4114 match (); \
4116 while (0)
4118 #define expect_ident(IDENT) \
4119 if (LA1 == XPM_TK_IDENT \
4120 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4121 match (); \
4122 else \
4123 goto failure
4125 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4126 goto failure;
4127 s += 9;
4128 match ();
4129 expect_ident ("static");
4130 expect_ident ("char");
4131 expect ('*');
4132 expect (XPM_TK_IDENT);
4133 expect ('[');
4134 expect (']');
4135 expect ('=');
4136 expect ('{');
4137 expect (XPM_TK_STRING);
4138 if (len >= BUFSIZ)
4139 goto failure;
4140 memcpy (buffer, beg, len);
4141 buffer[len] = '\0';
4142 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4143 &num_colors, &chars_per_pixel) != 4
4144 || width <= 0 || height <= 0
4145 || num_colors <= 0 || chars_per_pixel <= 0)
4146 goto failure;
4148 if (!check_image_size (f, width, height))
4150 image_size_error ();
4151 goto failure;
4154 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4155 #ifndef HAVE_NS
4156 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4157 &mask_img, 1)
4158 #endif
4161 image_error ("Image too large");
4162 goto failure;
4165 expect (',');
4167 XSETFRAME (frame, f);
4168 if (!NILP (Fxw_display_color_p (frame)))
4169 best_key = XPM_COLOR_KEY_C;
4170 else if (!NILP (Fx_display_grayscale_p (frame)))
4171 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4172 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4173 else
4174 best_key = XPM_COLOR_KEY_M;
4176 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4177 if (chars_per_pixel == 1)
4178 color_table = xpm_make_color_table_v (&put_color_table,
4179 &get_color_table);
4180 else
4181 color_table = xpm_make_color_table_h (&put_color_table,
4182 &get_color_table);
4184 while (num_colors-- > 0)
4186 char *color, *max_color;
4187 int key, next_key, max_key = 0;
4188 Lisp_Object symbol_color = Qnil, color_val;
4189 XColor cdef;
4191 expect (XPM_TK_STRING);
4192 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4193 goto failure;
4194 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4195 buffer[len - chars_per_pixel] = '\0';
4197 str = strtok (buffer, " \t");
4198 if (str == NULL)
4199 goto failure;
4200 key = xpm_str_to_color_key (str);
4201 if (key < 0)
4202 goto failure;
4205 color = strtok (NULL, " \t");
4206 if (color == NULL)
4207 goto failure;
4209 while ((str = strtok (NULL, " \t")) != NULL)
4211 next_key = xpm_str_to_color_key (str);
4212 if (next_key >= 0)
4213 break;
4214 color[strlen (color)] = ' ';
4217 if (key == XPM_COLOR_KEY_S)
4219 if (NILP (symbol_color))
4220 symbol_color = build_string (color);
4222 else if (max_key < key && key <= best_key)
4224 max_key = key;
4225 max_color = color;
4227 key = next_key;
4229 while (str);
4231 color_val = Qnil;
4232 if (!NILP (color_symbols) && !NILP (symbol_color))
4234 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols, Qnil);
4236 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4238 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4239 color_val = Qt;
4240 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4241 &cdef, 0))
4242 color_val = make_number (cdef.pixel);
4245 if (NILP (color_val) && max_key > 0)
4247 if (xstrcasecmp (max_color, "None") == 0)
4248 color_val = Qt;
4249 else if (x_defined_color (f, max_color, &cdef, 0))
4250 color_val = make_number (cdef.pixel);
4252 if (!NILP (color_val))
4253 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4255 expect (',');
4258 for (y = 0; y < height; y++)
4260 expect (XPM_TK_STRING);
4261 str = beg;
4262 if (len < width * chars_per_pixel)
4263 goto failure;
4264 for (x = 0; x < width; x++, str += chars_per_pixel)
4266 Lisp_Object color_val =
4267 (*get_color_table) (color_table, str, chars_per_pixel);
4269 XPutPixel (ximg, x, y,
4270 (INTEGERP (color_val) ? XINT (color_val)
4271 : FRAME_FOREGROUND_PIXEL (f)));
4272 #ifndef HAVE_NS
4273 XPutPixel (mask_img, x, y,
4274 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4275 : (have_mask = true, PIX_MASK_RETAIN)));
4276 #else
4277 if (EQ (color_val, Qt))
4278 ns_set_alpha (ximg, x, y, 0);
4279 #endif
4281 if (y + 1 < height)
4282 expect (',');
4285 img->width = width;
4286 img->height = height;
4288 /* Maybe fill in the background field while we have ximg handy. */
4289 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4290 IMAGE_BACKGROUND (img, f, ximg);
4292 image_put_x_image (f, img, ximg, 0);
4293 #ifndef HAVE_NS
4294 if (have_mask)
4296 /* Fill in the background_transparent field while we have the
4297 mask handy. */
4298 image_background_transparent (img, f, mask_img);
4300 image_put_x_image (f, img, mask_img, 1);
4302 else
4304 x_destroy_x_image (mask_img);
4305 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4307 #endif
4308 return 1;
4310 failure:
4311 image_error ("Invalid XPM file (%s)", img->spec);
4312 x_destroy_x_image (ximg);
4313 x_destroy_x_image (mask_img);
4314 x_clear_image (f, img);
4315 return 0;
4317 #undef match
4318 #undef expect
4319 #undef expect_ident
4322 static bool
4323 xpm_load (struct frame *f,
4324 struct image *img)
4326 bool success_p = 0;
4327 Lisp_Object file_name;
4329 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4330 file_name = image_spec_value (img->spec, QCfile, NULL);
4331 if (STRINGP (file_name))
4333 int fd;
4334 Lisp_Object file = x_find_image_fd (file_name, &fd);
4335 if (!STRINGP (file))
4337 image_error ("Cannot find image file `%s'", file_name);
4338 return 0;
4341 ptrdiff_t size;
4342 char *contents = slurp_file (fd, &size);
4343 if (contents == NULL)
4345 image_error ("Error loading XPM image `%s'", file);
4346 return 0;
4349 success_p = xpm_load_image (f, img, contents, contents + size);
4350 xfree (contents);
4352 else
4354 Lisp_Object data;
4356 data = image_spec_value (img->spec, QCdata, NULL);
4357 if (!STRINGP (data))
4359 image_error ("Invalid image data `%s'", data);
4360 return 0;
4362 success_p = xpm_load_image (f, img, SSDATA (data),
4363 SSDATA (data) + SBYTES (data));
4366 return success_p;
4369 #endif /* HAVE_NS && !HAVE_XPM */
4373 /***********************************************************************
4374 Color table
4375 ***********************************************************************/
4377 #ifdef COLOR_TABLE_SUPPORT
4379 /* An entry in the color table mapping an RGB color to a pixel color. */
4381 struct ct_color
4383 int r, g, b;
4384 unsigned long pixel;
4386 /* Next in color table collision list. */
4387 struct ct_color *next;
4390 /* The bucket vector size to use. Must be prime. */
4392 #define CT_SIZE 101
4394 /* Value is a hash of the RGB color given by R, G, and B. */
4396 static unsigned
4397 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4399 return (r << 16) ^ (g << 8) ^ b;
4402 /* The color hash table. */
4404 static struct ct_color **ct_table;
4406 /* Number of entries in the color table. */
4408 static int ct_colors_allocated;
4409 enum
4411 ct_colors_allocated_max =
4412 min (INT_MAX,
4413 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4416 /* Initialize the color table. */
4418 static void
4419 init_color_table (void)
4421 int size = CT_SIZE * sizeof (*ct_table);
4422 ct_table = xzalloc (size);
4423 ct_colors_allocated = 0;
4427 /* Free memory associated with the color table. */
4429 static void
4430 free_color_table (void)
4432 int i;
4433 struct ct_color *p, *next;
4435 for (i = 0; i < CT_SIZE; ++i)
4436 for (p = ct_table[i]; p; p = next)
4438 next = p->next;
4439 xfree (p);
4442 xfree (ct_table);
4443 ct_table = NULL;
4447 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4448 entry for that color already is in the color table, return the
4449 pixel color of that entry. Otherwise, allocate a new color for R,
4450 G, B, and make an entry in the color table. */
4452 static unsigned long
4453 lookup_rgb_color (struct frame *f, int r, int g, int b)
4455 unsigned hash = ct_hash_rgb (r, g, b);
4456 int i = hash % CT_SIZE;
4457 struct ct_color *p;
4458 Display_Info *dpyinfo;
4460 /* Handle TrueColor visuals specially, which improves performance by
4461 two orders of magnitude. Freeing colors on TrueColor visuals is
4462 a nop, and pixel colors specify RGB values directly. See also
4463 the Xlib spec, chapter 3.1. */
4464 dpyinfo = FRAME_DISPLAY_INFO (f);
4465 if (dpyinfo->red_bits > 0)
4467 /* Apply gamma-correction like normal color allocation does. */
4468 if (f->gamma)
4470 XColor color;
4471 color.red = r, color.green = g, color.blue = b;
4472 gamma_correct (f, &color);
4473 r = color.red, g = color.green, b = color.blue;
4476 return x_make_truecolor_pixel (dpyinfo, r, g, b);
4479 for (p = ct_table[i]; p; p = p->next)
4480 if (p->r == r && p->g == g && p->b == b)
4481 break;
4483 if (p == NULL)
4486 #ifdef HAVE_X_WINDOWS
4487 XColor color;
4488 Colormap cmap;
4489 bool rc;
4490 #else
4491 COLORREF color;
4492 #endif
4494 if (ct_colors_allocated_max <= ct_colors_allocated)
4495 return FRAME_FOREGROUND_PIXEL (f);
4497 #ifdef HAVE_X_WINDOWS
4498 color.red = r;
4499 color.green = g;
4500 color.blue = b;
4502 cmap = FRAME_X_COLORMAP (f);
4503 rc = x_alloc_nearest_color (f, cmap, &color);
4504 if (rc)
4506 ++ct_colors_allocated;
4507 p = xmalloc (sizeof *p);
4508 p->r = r;
4509 p->g = g;
4510 p->b = b;
4511 p->pixel = color.pixel;
4512 p->next = ct_table[i];
4513 ct_table[i] = p;
4515 else
4516 return FRAME_FOREGROUND_PIXEL (f);
4518 #else
4519 #ifdef HAVE_NTGUI
4520 color = PALETTERGB (r, g, b);
4521 #else
4522 color = RGB_TO_ULONG (r, g, b);
4523 #endif /* HAVE_NTGUI */
4524 ++ct_colors_allocated;
4525 p = xmalloc (sizeof *p);
4526 p->r = r;
4527 p->g = g;
4528 p->b = b;
4529 p->pixel = color;
4530 p->next = ct_table[i];
4531 ct_table[i] = p;
4532 #endif /* HAVE_X_WINDOWS */
4536 return p->pixel;
4540 /* Look up pixel color PIXEL which is used on frame F in the color
4541 table. If not already present, allocate it. Value is PIXEL. */
4543 static unsigned long
4544 lookup_pixel_color (struct frame *f, unsigned long pixel)
4546 int i = pixel % CT_SIZE;
4547 struct ct_color *p;
4549 for (p = ct_table[i]; p; p = p->next)
4550 if (p->pixel == pixel)
4551 break;
4553 if (p == NULL)
4555 XColor color;
4556 Colormap cmap;
4557 bool rc;
4559 if (ct_colors_allocated >= ct_colors_allocated_max)
4560 return FRAME_FOREGROUND_PIXEL (f);
4562 #ifdef HAVE_X_WINDOWS
4563 cmap = FRAME_X_COLORMAP (f);
4564 color.pixel = pixel;
4565 x_query_color (f, &color);
4566 rc = x_alloc_nearest_color (f, cmap, &color);
4567 #else
4568 block_input ();
4569 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4570 color.pixel = pixel;
4571 XQueryColor (NULL, cmap, &color);
4572 rc = x_alloc_nearest_color (f, cmap, &color);
4573 unblock_input ();
4574 #endif /* HAVE_X_WINDOWS */
4576 if (rc)
4578 ++ct_colors_allocated;
4580 p = xmalloc (sizeof *p);
4581 p->r = color.red;
4582 p->g = color.green;
4583 p->b = color.blue;
4584 p->pixel = pixel;
4585 p->next = ct_table[i];
4586 ct_table[i] = p;
4588 else
4589 return FRAME_FOREGROUND_PIXEL (f);
4591 return p->pixel;
4595 /* Value is a vector of all pixel colors contained in the color table,
4596 allocated via xmalloc. Set *N to the number of colors. */
4598 static unsigned long *
4599 colors_in_color_table (int *n)
4601 int i, j;
4602 struct ct_color *p;
4603 unsigned long *colors;
4605 if (ct_colors_allocated == 0)
4607 *n = 0;
4608 colors = NULL;
4610 else
4612 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4613 *n = ct_colors_allocated;
4615 for (i = j = 0; i < CT_SIZE; ++i)
4616 for (p = ct_table[i]; p; p = p->next)
4617 colors[j++] = p->pixel;
4620 return colors;
4623 #else /* COLOR_TABLE_SUPPORT */
4625 static unsigned long
4626 lookup_rgb_color (struct frame *f, int r, int g, int b)
4628 #ifdef HAVE_NTGUI
4629 return PALETTERGB (r >> 8, g >> 8, b >> 8);
4630 #elif defined HAVE_NS
4631 return RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4632 #elif defined USE_CAIRO
4633 return (0xffu << 24) | (r << 16) | (g << 8) | b;
4634 #else
4635 xsignal1 (Qfile_error,
4636 build_string ("This Emacs mishandles this image file type"));
4637 #endif
4640 static void
4641 init_color_table (void)
4644 #endif /* COLOR_TABLE_SUPPORT */
4647 /***********************************************************************
4648 Algorithms
4649 ***********************************************************************/
4651 /* Edge detection matrices for different edge-detection
4652 strategies. */
4654 static int emboss_matrix[9] = {
4655 /* x - 1 x x + 1 */
4656 2, -1, 0, /* y - 1 */
4657 -1, 0, 1, /* y */
4658 0, 1, -2 /* y + 1 */
4661 static int laplace_matrix[9] = {
4662 /* x - 1 x x + 1 */
4663 1, 0, 0, /* y - 1 */
4664 0, 0, 0, /* y */
4665 0, 0, -1 /* y + 1 */
4668 /* Value is the intensity of the color whose red/green/blue values
4669 are R, G, and B. */
4671 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4674 /* On frame F, return an array of XColor structures describing image
4675 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4676 means also fill the red/green/blue members of the XColor
4677 structures. Value is a pointer to the array of XColors structures,
4678 allocated with xmalloc; it must be freed by the caller. */
4680 static XColor *
4681 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4683 int x, y;
4684 XColor *colors, *p;
4685 XImagePtr_or_DC ximg;
4686 ptrdiff_t nbytes;
4687 #ifdef HAVE_NTGUI
4688 HGDIOBJ prev;
4689 #endif /* HAVE_NTGUI */
4691 if (INT_MULTIPLY_WRAPV (sizeof *colors, img->width, &nbytes)
4692 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes)
4693 || SIZE_MAX < nbytes)
4694 memory_full (SIZE_MAX);
4695 colors = xmalloc (nbytes);
4697 /* Get the X image or create a memory device context for IMG. */
4698 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4700 /* Fill the `pixel' members of the XColor array. I wished there
4701 were an easy and portable way to circumvent XGetPixel. */
4702 p = colors;
4703 for (y = 0; y < img->height; ++y)
4705 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4706 XColor *row = p;
4707 for (x = 0; x < img->width; ++x, ++p)
4708 p->pixel = GET_PIXEL (ximg, x, y);
4709 if (rgb_p)
4710 x_query_colors (f, row, img->width);
4712 #else
4714 for (x = 0; x < img->width; ++x, ++p)
4716 /* W32_TODO: palette support needed here? */
4717 p->pixel = GET_PIXEL (ximg, x, y);
4718 if (rgb_p)
4720 p->red = RED16_FROM_ULONG (p->pixel);
4721 p->green = GREEN16_FROM_ULONG (p->pixel);
4722 p->blue = BLUE16_FROM_ULONG (p->pixel);
4725 #endif /* HAVE_X_WINDOWS */
4728 image_unget_x_image_or_dc (img, 0, ximg, prev);
4730 return colors;
4733 #ifdef HAVE_NTGUI
4735 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4736 created with CreateDIBSection, with the pointer to the bit values
4737 stored in ximg->data. */
4739 static void
4740 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4742 int width = ximg->info.bmiHeader.biWidth;
4743 unsigned char * pixel;
4745 /* True color images. */
4746 if (ximg->info.bmiHeader.biBitCount == 24)
4748 int rowbytes = width * 3;
4749 /* Ensure scanlines are aligned on 4 byte boundaries. */
4750 if (rowbytes % 4)
4751 rowbytes += 4 - (rowbytes % 4);
4753 pixel = ximg->data + y * rowbytes + x * 3;
4754 /* Windows bitmaps are in BGR order. */
4755 *pixel = GetBValue (color);
4756 *(pixel + 1) = GetGValue (color);
4757 *(pixel + 2) = GetRValue (color);
4759 /* Monochrome images. */
4760 else if (ximg->info.bmiHeader.biBitCount == 1)
4762 int rowbytes = width / 8;
4763 /* Ensure scanlines are aligned on 4 byte boundaries. */
4764 if (rowbytes % 4)
4765 rowbytes += 4 - (rowbytes % 4);
4766 pixel = ximg->data + y * rowbytes + x / 8;
4767 /* Filter out palette info. */
4768 if (color & 0x00ffffff)
4769 *pixel = *pixel | (1 << x % 8);
4770 else
4771 *pixel = *pixel & ~(1 << x % 8);
4773 else
4774 image_error ("XPutPixel: palette image not supported");
4777 #endif /* HAVE_NTGUI */
4779 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4780 RGB members are set. F is the frame on which this all happens.
4781 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4783 static void
4784 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4786 int x, y;
4787 XImagePtr oimg = NULL;
4788 XColor *p;
4790 init_color_table ();
4792 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4793 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4794 &oimg, 0);
4795 p = colors;
4796 for (y = 0; y < img->height; ++y)
4797 for (x = 0; x < img->width; ++x, ++p)
4799 unsigned long pixel;
4800 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4801 XPutPixel (oimg, x, y, pixel);
4804 xfree (colors);
4806 image_put_x_image (f, img, oimg, 0);
4807 #ifdef COLOR_TABLE_SUPPORT
4808 img->colors = colors_in_color_table (&img->ncolors);
4809 free_color_table ();
4810 #endif /* COLOR_TABLE_SUPPORT */
4814 /* On frame F, perform edge-detection on image IMG.
4816 MATRIX is a nine-element array specifying the transformation
4817 matrix. See emboss_matrix for an example.
4819 COLOR_ADJUST is a color adjustment added to each pixel of the
4820 outgoing image. */
4822 static void
4823 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4825 XColor *colors = x_to_xcolors (f, img, 1);
4826 XColor *new, *p;
4827 int x, y, i, sum;
4828 ptrdiff_t nbytes;
4830 for (i = sum = 0; i < 9; ++i)
4831 sum += eabs (matrix[i]);
4833 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4835 if (INT_MULTIPLY_WRAPV (sizeof *new, img->width, &nbytes)
4836 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes))
4837 memory_full (SIZE_MAX);
4838 new = xmalloc (nbytes);
4840 for (y = 0; y < img->height; ++y)
4842 p = COLOR (new, 0, y);
4843 p->red = p->green = p->blue = 0xffff/2;
4844 p = COLOR (new, img->width - 1, y);
4845 p->red = p->green = p->blue = 0xffff/2;
4848 for (x = 1; x < img->width - 1; ++x)
4850 p = COLOR (new, x, 0);
4851 p->red = p->green = p->blue = 0xffff/2;
4852 p = COLOR (new, x, img->height - 1);
4853 p->red = p->green = p->blue = 0xffff/2;
4856 for (y = 1; y < img->height - 1; ++y)
4858 p = COLOR (new, 1, y);
4860 for (x = 1; x < img->width - 1; ++x, ++p)
4862 int r, g, b, yy, xx;
4864 r = g = b = i = 0;
4865 for (yy = y - 1; yy < y + 2; ++yy)
4866 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4867 if (matrix[i])
4869 XColor *t = COLOR (colors, xx, yy);
4870 r += matrix[i] * t->red;
4871 g += matrix[i] * t->green;
4872 b += matrix[i] * t->blue;
4875 r = (r / sum + color_adjust) & 0xffff;
4876 g = (g / sum + color_adjust) & 0xffff;
4877 b = (b / sum + color_adjust) & 0xffff;
4878 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4882 xfree (colors);
4883 x_from_xcolors (f, img, new);
4885 #undef COLOR
4889 /* Perform the pre-defined `emboss' edge-detection on image IMG
4890 on frame F. */
4892 static void
4893 x_emboss (struct frame *f, struct image *img)
4895 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4899 /* Transform image IMG which is used on frame F with a Laplace
4900 edge-detection algorithm. The result is an image that can be used
4901 to draw disabled buttons, for example. */
4903 static void
4904 x_laplace (struct frame *f, struct image *img)
4906 x_detect_edges (f, img, laplace_matrix, 45000);
4910 /* Perform edge-detection on image IMG on frame F, with specified
4911 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4913 MATRIX must be either
4915 - a list of at least 9 numbers in row-major form
4916 - a vector of at least 9 numbers
4918 COLOR_ADJUST nil means use a default; otherwise it must be a
4919 number. */
4921 static void
4922 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4923 Lisp_Object color_adjust)
4925 int i = 0;
4926 int trans[9];
4928 if (CONSP (matrix))
4930 for (i = 0;
4931 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4932 ++i, matrix = XCDR (matrix))
4933 trans[i] = XFLOATINT (XCAR (matrix));
4935 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4937 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4938 trans[i] = XFLOATINT (AREF (matrix, i));
4941 if (NILP (color_adjust))
4942 color_adjust = make_number (0xffff / 2);
4944 if (i == 9 && NUMBERP (color_adjust))
4945 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4949 /* Transform image IMG on frame F so that it looks disabled. */
4951 static void
4952 x_disable_image (struct frame *f, struct image *img)
4954 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4955 #ifdef HAVE_NTGUI
4956 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4957 #else
4958 int n_planes = dpyinfo->n_planes;
4959 #endif /* HAVE_NTGUI */
4961 if (n_planes >= 2)
4963 /* Color (or grayscale). Convert to gray, and equalize. Just
4964 drawing such images with a stipple can look very odd, so
4965 we're using this method instead. */
4966 XColor *colors = x_to_xcolors (f, img, 1);
4967 XColor *p, *end;
4968 const int h = 15000;
4969 const int l = 30000;
4971 for (p = colors, end = colors + img->width * img->height;
4972 p < end;
4973 ++p)
4975 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4976 int i2 = (0xffff - h - l) * i / 0xffff + l;
4977 p->red = p->green = p->blue = i2;
4980 x_from_xcolors (f, img, colors);
4983 /* Draw a cross over the disabled image, if we must or if we
4984 should. */
4985 if (n_planes < 2 || cross_disabled_images)
4987 #ifndef HAVE_NTGUI
4988 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4990 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4992 Display *dpy = FRAME_X_DISPLAY (f);
4993 GC gc;
4995 image_sync_to_pixmaps (f, img);
4996 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4997 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4998 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4999 img->width - 1, img->height - 1);
5000 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
5001 img->width - 1, 0);
5002 XFreeGC (dpy, gc);
5004 if (img->mask)
5006 gc = XCreateGC (dpy, img->mask, 0, NULL);
5007 XSetForeground (dpy, gc, MaskForeground (f));
5008 XDrawLine (dpy, img->mask, gc, 0, 0,
5009 img->width - 1, img->height - 1);
5010 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
5011 img->width - 1, 0);
5012 XFreeGC (dpy, gc);
5014 #endif /* !HAVE_NS */
5015 #else
5016 HDC hdc, bmpdc;
5017 HGDIOBJ prev;
5019 hdc = get_frame_dc (f);
5020 bmpdc = CreateCompatibleDC (hdc);
5021 release_frame_dc (f, hdc);
5023 prev = SelectObject (bmpdc, img->pixmap);
5025 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5026 MoveToEx (bmpdc, 0, 0, NULL);
5027 LineTo (bmpdc, img->width - 1, img->height - 1);
5028 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5029 LineTo (bmpdc, img->width - 1, 0);
5031 if (img->mask)
5033 SelectObject (bmpdc, img->mask);
5034 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5035 MoveToEx (bmpdc, 0, 0, NULL);
5036 LineTo (bmpdc, img->width - 1, img->height - 1);
5037 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5038 LineTo (bmpdc, img->width - 1, 0);
5040 SelectObject (bmpdc, prev);
5041 DeleteDC (bmpdc);
5042 #endif /* HAVE_NTGUI */
5047 /* Build a mask for image IMG which is used on frame F. FILE is the
5048 name of an image file, for error messages. HOW determines how to
5049 determine the background color of IMG. If it is a list '(R G B)',
5050 with R, G, and B being integers >= 0, take that as the color of the
5051 background. Otherwise, determine the background color of IMG
5052 heuristically. */
5054 static void
5055 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
5057 XImagePtr_or_DC ximg;
5058 #ifdef HAVE_NTGUI
5059 HGDIOBJ prev;
5060 char *mask_img;
5061 int row_width;
5062 #elif !defined HAVE_NS
5063 XImagePtr mask_img;
5064 #endif
5065 int x, y;
5066 bool use_img_background;
5067 unsigned long bg = 0;
5069 if (img->mask)
5070 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
5072 #ifndef HAVE_NTGUI
5073 #ifndef HAVE_NS
5074 /* Create an image and pixmap serving as mask. */
5075 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
5076 &mask_img, 1))
5077 return;
5078 #endif /* !HAVE_NS */
5079 #else
5080 /* Create the bit array serving as mask. */
5081 row_width = (img->width + 7) / 8;
5082 mask_img = xzalloc (row_width * img->height);
5083 #endif /* HAVE_NTGUI */
5085 /* Get the X image or create a memory device context for IMG. */
5086 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
5088 /* Determine the background color of ximg. If HOW is `(R G B)'
5089 take that as color. Otherwise, use the image's background color. */
5090 use_img_background = 1;
5092 if (CONSP (how))
5094 int rgb[3], i;
5096 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5098 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5099 how = XCDR (how);
5102 if (i == 3 && NILP (how))
5104 char color_name[30];
5105 sprintf (color_name, "#%04x%04x%04x",
5106 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
5107 bg = (
5108 #ifdef HAVE_NTGUI
5109 0x00ffffff & /* Filter out palette info. */
5110 #endif /* HAVE_NTGUI */
5111 x_alloc_image_color (f, img, build_string (color_name), 0));
5112 use_img_background = 0;
5116 if (use_img_background)
5117 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5119 /* Set all bits in mask_img to 1 whose color in ximg is different
5120 from the background color bg. */
5121 #ifndef HAVE_NTGUI
5122 for (y = 0; y < img->height; ++y)
5123 for (x = 0; x < img->width; ++x)
5124 #ifndef HAVE_NS
5125 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5126 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5127 #else
5128 if (XGetPixel (ximg, x, y) == bg)
5129 ns_set_alpha (ximg, x, y, 0);
5130 #endif /* HAVE_NS */
5131 #ifndef HAVE_NS
5132 /* Fill in the background_transparent field while we have the mask handy. */
5133 image_background_transparent (img, f, mask_img);
5135 /* Put mask_img into the image. */
5136 image_put_x_image (f, img, mask_img, 1);
5137 #endif /* !HAVE_NS */
5138 #else
5139 for (y = 0; y < img->height; ++y)
5140 for (x = 0; x < img->width; ++x)
5142 COLORREF p = GetPixel (ximg, x, y);
5143 if (p != bg)
5144 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5147 /* Create the mask image. */
5148 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5149 mask_img);
5150 /* Fill in the background_transparent field while we have the mask handy. */
5151 SelectObject (ximg, img->mask);
5152 image_background_transparent (img, f, ximg);
5154 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5155 xfree (mask_img);
5156 #endif /* HAVE_NTGUI */
5158 image_unget_x_image_or_dc (img, 0, ximg, prev);
5162 /***********************************************************************
5163 PBM (mono, gray, color)
5164 ***********************************************************************/
5166 static bool pbm_image_p (Lisp_Object object);
5167 static bool pbm_load (struct frame *f, struct image *img);
5169 /* Indices of image specification fields in gs_format, below. */
5171 enum pbm_keyword_index
5173 PBM_TYPE,
5174 PBM_FILE,
5175 PBM_DATA,
5176 PBM_ASCENT,
5177 PBM_MARGIN,
5178 PBM_RELIEF,
5179 PBM_ALGORITHM,
5180 PBM_HEURISTIC_MASK,
5181 PBM_MASK,
5182 PBM_FOREGROUND,
5183 PBM_BACKGROUND,
5184 PBM_LAST
5187 /* Vector of image_keyword structures describing the format
5188 of valid user-defined image specifications. */
5190 static const struct image_keyword pbm_format[PBM_LAST] =
5192 {":type", IMAGE_SYMBOL_VALUE, 1},
5193 {":file", IMAGE_STRING_VALUE, 0},
5194 {":data", IMAGE_STRING_VALUE, 0},
5195 {":ascent", IMAGE_ASCENT_VALUE, 0},
5196 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5197 {":relief", IMAGE_INTEGER_VALUE, 0},
5198 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5199 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5200 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5201 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5202 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5205 /* Structure describing the image type `pbm'. */
5207 static struct image_type pbm_type =
5209 SYMBOL_INDEX (Qpbm),
5210 pbm_image_p,
5211 pbm_load,
5212 x_clear_image,
5213 NULL,
5214 NULL
5218 /* Return true if OBJECT is a valid PBM image specification. */
5220 static bool
5221 pbm_image_p (Lisp_Object object)
5223 struct image_keyword fmt[PBM_LAST];
5225 memcpy (fmt, pbm_format, sizeof fmt);
5227 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5228 return 0;
5230 /* Must specify either :data or :file. */
5231 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5235 /* Get next char skipping comments in Netpbm header. Returns -1 at
5236 end of input. */
5238 static int
5239 pbm_next_char (char **s, char *end)
5241 while (*s < end)
5243 unsigned char c = *(*s)++;
5244 if (c != '#')
5245 return c;
5246 while (*s < end)
5248 c = *(*s)++;
5249 if (c == '\n' || c == '\r')
5250 break;
5254 return -1;
5258 /* Scan a decimal number from *S and return it. Advance *S while
5259 reading the number. END is the end of the string. Value is -1 at
5260 end of input. */
5262 static int
5263 pbm_scan_number (char **s, char *end)
5265 int c = 0, val = -1;
5267 /* Skip white-space. */
5268 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5271 if (c_isdigit (c))
5273 /* Read decimal number. */
5274 val = c - '0';
5275 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5276 val = 10 * val + c - '0';
5279 return val;
5282 /* Scan an index from *S and return it. It is a one-byte unsigned
5283 index if !TWO_BYTE, and a two-byte big-endian unsigned index if
5284 TWO_BYTE. */
5286 static int
5287 pbm_scan_index (char **s, bool two_byte)
5289 char *p = *s;
5290 unsigned char c0 = *p++;
5291 int n = c0;
5292 if (two_byte)
5294 unsigned char c1 = *p++;
5295 n = (n << 8) + c1;
5297 *s = p;
5298 return n;
5302 /* Load PBM image IMG for use on frame F. */
5304 static bool
5305 pbm_load (struct frame *f, struct image *img)
5307 bool raw_p;
5308 int x, y;
5309 int width, height, max_color_idx = 0;
5310 Lisp_Object specified_file;
5311 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5312 char *contents = NULL;
5313 char *end, *p;
5314 #ifndef USE_CAIRO
5315 XImagePtr ximg;
5316 #endif
5318 specified_file = image_spec_value (img->spec, QCfile, NULL);
5320 if (STRINGP (specified_file))
5322 int fd;
5323 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5324 if (!STRINGP (file))
5326 image_error ("Cannot find image file `%s'", specified_file);
5327 return 0;
5330 ptrdiff_t size;
5331 contents = slurp_file (fd, &size);
5332 if (contents == NULL)
5334 image_error ("Error reading `%s'", file);
5335 return 0;
5338 p = contents;
5339 end = contents + size;
5341 else
5343 Lisp_Object data;
5344 data = image_spec_value (img->spec, QCdata, NULL);
5345 if (!STRINGP (data))
5347 image_error ("Invalid image data `%s'", data);
5348 return 0;
5350 p = SSDATA (data);
5351 end = p + SBYTES (data);
5354 /* Check magic number. */
5355 if (end - p < 2 || *p++ != 'P')
5357 image_error ("Not a PBM image: `%s'", img->spec);
5358 error:
5359 xfree (contents);
5360 img->pixmap = NO_PIXMAP;
5361 return 0;
5364 switch (*p++)
5366 case '1':
5367 raw_p = 0, type = PBM_MONO;
5368 break;
5370 case '2':
5371 raw_p = 0, type = PBM_GRAY;
5372 break;
5374 case '3':
5375 raw_p = 0, type = PBM_COLOR;
5376 break;
5378 case '4':
5379 raw_p = 1, type = PBM_MONO;
5380 break;
5382 case '5':
5383 raw_p = 1, type = PBM_GRAY;
5384 break;
5386 case '6':
5387 raw_p = 1, type = PBM_COLOR;
5388 break;
5390 default:
5391 image_error ("Not a PBM image: `%s'", img->spec);
5392 goto error;
5395 /* Read width, height, maximum color-component. Characters
5396 starting with `#' up to the end of a line are ignored. */
5397 width = pbm_scan_number (&p, end);
5398 height = pbm_scan_number (&p, end);
5400 #ifdef USE_CAIRO
5401 void *data = xmalloc (width * height * 4);
5402 uint32_t *dataptr = data;
5403 #endif
5405 if (type != PBM_MONO)
5407 max_color_idx = pbm_scan_number (&p, end);
5408 if (max_color_idx > 65535 || max_color_idx < 0)
5410 image_error ("Unsupported maximum PBM color value");
5411 goto error;
5415 if (!check_image_size (f, width, height))
5417 image_size_error ();
5418 goto error;
5421 #ifndef USE_CAIRO
5422 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5423 goto error;
5424 #endif
5426 /* Initialize the color hash table. */
5427 init_color_table ();
5429 if (type == PBM_MONO)
5431 unsigned char c = 0;
5432 int g;
5433 struct image_keyword fmt[PBM_LAST];
5434 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5435 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5436 #ifdef USE_CAIRO
5437 XColor xfg, xbg;
5438 int fga32, bga32;
5439 #endif
5440 /* Parse the image specification. */
5441 memcpy (fmt, pbm_format, sizeof fmt);
5442 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5444 /* Get foreground and background colors, maybe allocate colors. */
5445 #ifdef USE_CAIRO
5446 if (! fmt[PBM_FOREGROUND].count
5447 || ! STRINGP (fmt[PBM_FOREGROUND].value)
5448 || ! x_defined_color (f, SSDATA (fmt[PBM_FOREGROUND].value), &xfg, 0))
5450 xfg.pixel = fg;
5451 x_query_color (f, &xfg);
5453 fga32 = xcolor_to_argb32 (xfg);
5455 if (! fmt[PBM_BACKGROUND].count
5456 || ! STRINGP (fmt[PBM_BACKGROUND].value)
5457 || ! x_defined_color (f, SSDATA (fmt[PBM_BACKGROUND].value), &xbg, 0))
5459 xbg.pixel = bg;
5460 x_query_color (f, &xbg);
5462 bga32 = xcolor_to_argb32 (xbg);
5463 #else
5464 if (fmt[PBM_FOREGROUND].count
5465 && STRINGP (fmt[PBM_FOREGROUND].value))
5466 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5467 if (fmt[PBM_BACKGROUND].count
5468 && STRINGP (fmt[PBM_BACKGROUND].value))
5470 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5471 img->background = bg;
5472 img->background_valid = 1;
5474 #endif
5476 for (y = 0; y < height; ++y)
5477 for (x = 0; x < width; ++x)
5479 if (raw_p)
5481 if ((x & 7) == 0)
5483 if (p >= end)
5485 #ifdef USE_CAIRO
5486 xfree (data);
5487 #else
5488 x_destroy_x_image (ximg);
5489 #endif
5490 x_clear_image (f, img);
5491 image_error ("Invalid image size in image `%s'",
5492 img->spec);
5493 goto error;
5495 c = *p++;
5497 g = c & 0x80;
5498 c <<= 1;
5500 else
5502 int c = 0;
5503 /* Skip white-space and comments. */
5504 while ((c = pbm_next_char (&p, end)) != -1 && c_isspace (c))
5507 if (c == '0' || c == '1')
5508 g = c - '0';
5509 else
5510 g = 0;
5513 #ifdef USE_CAIRO
5514 *dataptr++ = g ? fga32 : bga32;
5515 #else
5516 XPutPixel (ximg, x, y, g ? fg : bg);
5517 #endif
5520 else
5522 int expected_size = height * width;
5523 bool two_byte = 255 < max_color_idx;
5524 if (two_byte)
5525 expected_size *= 2;
5526 if (type == PBM_COLOR)
5527 expected_size *= 3;
5529 if (raw_p && p + expected_size > end)
5531 #ifdef USE_CAIRO
5532 xfree (data);
5533 #else
5534 x_destroy_x_image (ximg);
5535 #endif
5536 x_clear_image (f, img);
5537 image_error ("Invalid image size in image `%s'", img->spec);
5538 goto error;
5541 for (y = 0; y < height; ++y)
5542 for (x = 0; x < width; ++x)
5544 int r, g, b;
5546 if (type == PBM_GRAY && raw_p)
5547 r = g = b = pbm_scan_index (&p, two_byte);
5548 else if (type == PBM_GRAY)
5549 r = g = b = pbm_scan_number (&p, end);
5550 else if (raw_p)
5552 r = pbm_scan_index (&p, two_byte);
5553 g = pbm_scan_index (&p, two_byte);
5554 b = pbm_scan_index (&p, two_byte);
5556 else
5558 r = pbm_scan_number (&p, end);
5559 g = pbm_scan_number (&p, end);
5560 b = pbm_scan_number (&p, end);
5563 if (r < 0 || g < 0 || b < 0)
5565 #ifdef USE_CAIRO
5566 xfree (data);
5567 #else
5568 x_destroy_x_image (ximg);
5569 #endif
5570 image_error ("Invalid pixel value in image `%s'", img->spec);
5571 goto error;
5574 #ifdef USE_CAIRO
5575 r = (double) r * 255 / max_color_idx;
5576 g = (double) g * 255 / max_color_idx;
5577 b = (double) b * 255 / max_color_idx;
5578 *dataptr++ = (0xffu << 24) | (r << 16) | (g << 8) | b;
5579 #else
5580 /* RGB values are now in the range 0..max_color_idx.
5581 Scale this to the range 0..0xffff supported by X. */
5582 r = (double) r * 65535 / max_color_idx;
5583 g = (double) g * 65535 / max_color_idx;
5584 b = (double) b * 65535 / max_color_idx;
5585 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5586 #endif
5590 #ifdef COLOR_TABLE_SUPPORT
5591 /* Store in IMG->colors the colors allocated for the image, and
5592 free the color table. */
5593 img->colors = colors_in_color_table (&img->ncolors);
5594 free_color_table ();
5595 #endif /* COLOR_TABLE_SUPPORT */
5597 img->width = width;
5598 img->height = height;
5600 /* Maybe fill in the background field while we have ximg handy. */
5602 #ifdef USE_CAIRO
5603 create_cairo_image_surface (img, data, width, height);
5604 #else
5605 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5606 /* Casting avoids a GCC warning. */
5607 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5609 /* Put ximg into the image. */
5610 image_put_x_image (f, img, ximg, 0);
5611 #endif
5613 /* X and W32 versions did it here, MAC version above. ++kfs
5614 img->width = width;
5615 img->height = height; */
5617 xfree (contents);
5618 return 1;
5622 /***********************************************************************
5624 ***********************************************************************/
5626 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5628 /* Function prototypes. */
5630 static bool png_image_p (Lisp_Object object);
5631 static bool png_load (struct frame *f, struct image *img);
5633 /* Indices of image specification fields in png_format, below. */
5635 enum png_keyword_index
5637 PNG_TYPE,
5638 PNG_DATA,
5639 PNG_FILE,
5640 PNG_ASCENT,
5641 PNG_MARGIN,
5642 PNG_RELIEF,
5643 PNG_ALGORITHM,
5644 PNG_HEURISTIC_MASK,
5645 PNG_MASK,
5646 PNG_BACKGROUND,
5647 PNG_LAST
5650 /* Vector of image_keyword structures describing the format
5651 of valid user-defined image specifications. */
5653 static const struct image_keyword png_format[PNG_LAST] =
5655 {":type", IMAGE_SYMBOL_VALUE, 1},
5656 {":data", IMAGE_STRING_VALUE, 0},
5657 {":file", IMAGE_STRING_VALUE, 0},
5658 {":ascent", IMAGE_ASCENT_VALUE, 0},
5659 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5660 {":relief", IMAGE_INTEGER_VALUE, 0},
5661 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5662 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5663 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5664 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5667 #if defined HAVE_NTGUI && defined WINDOWSNT
5668 static bool init_png_functions (void);
5669 #else
5670 #define init_png_functions NULL
5671 #endif
5673 /* Structure describing the image type `png'. */
5675 static struct image_type png_type =
5677 SYMBOL_INDEX (Qpng),
5678 png_image_p,
5679 png_load,
5680 x_clear_image,
5681 init_png_functions,
5682 NULL
5685 /* Return true if OBJECT is a valid PNG image specification. */
5687 static bool
5688 png_image_p (Lisp_Object object)
5690 struct image_keyword fmt[PNG_LAST];
5691 memcpy (fmt, png_format, sizeof fmt);
5693 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5694 return 0;
5696 /* Must specify either the :data or :file keyword. */
5697 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5700 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5703 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5705 # ifdef WINDOWSNT
5706 /* PNG library details. */
5708 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5709 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5710 DEF_DLL_FN (png_structp, png_create_read_struct,
5711 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5712 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5713 DEF_DLL_FN (void, png_destroy_read_struct,
5714 (png_structpp, png_infopp, png_infopp));
5715 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5716 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5717 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5718 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5719 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5720 int *, int *, int *, int *, int *));
5721 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5722 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5723 DEF_DLL_FN (void, png_set_expand, (png_structp));
5724 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5725 DEF_DLL_FN (void, png_set_background,
5726 (png_structp, png_color_16p, int, int, double));
5727 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5728 (png_structp, png_infop, png_color_16p *));
5729 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5730 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5731 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5732 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5733 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5734 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5736 # if (PNG_LIBPNG_VER >= 10500)
5737 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5738 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5739 (png_structp, png_longjmp_ptr, size_t));
5740 # endif /* libpng version >= 1.5 */
5742 static bool
5743 init_png_functions (void)
5745 HMODULE library;
5747 if (!(library = w32_delayed_load (Qpng)))
5748 return 0;
5750 LOAD_DLL_FN (library, png_get_io_ptr);
5751 LOAD_DLL_FN (library, png_sig_cmp);
5752 LOAD_DLL_FN (library, png_create_read_struct);
5753 LOAD_DLL_FN (library, png_create_info_struct);
5754 LOAD_DLL_FN (library, png_destroy_read_struct);
5755 LOAD_DLL_FN (library, png_set_read_fn);
5756 LOAD_DLL_FN (library, png_set_sig_bytes);
5757 LOAD_DLL_FN (library, png_read_info);
5758 LOAD_DLL_FN (library, png_get_IHDR);
5759 LOAD_DLL_FN (library, png_get_valid);
5760 LOAD_DLL_FN (library, png_set_strip_16);
5761 LOAD_DLL_FN (library, png_set_expand);
5762 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5763 LOAD_DLL_FN (library, png_set_background);
5764 LOAD_DLL_FN (library, png_get_bKGD);
5765 LOAD_DLL_FN (library, png_read_update_info);
5766 LOAD_DLL_FN (library, png_get_channels);
5767 LOAD_DLL_FN (library, png_get_rowbytes);
5768 LOAD_DLL_FN (library, png_read_image);
5769 LOAD_DLL_FN (library, png_read_end);
5770 LOAD_DLL_FN (library, png_error);
5772 # if (PNG_LIBPNG_VER >= 10500)
5773 LOAD_DLL_FN (library, png_longjmp);
5774 LOAD_DLL_FN (library, png_set_longjmp_fn);
5775 # endif /* libpng version >= 1.5 */
5777 return 1;
5780 # undef png_create_info_struct
5781 # undef png_create_read_struct
5782 # undef png_destroy_read_struct
5783 # undef png_error
5784 # undef png_get_bKGD
5785 # undef png_get_channels
5786 # undef png_get_IHDR
5787 # undef png_get_io_ptr
5788 # undef png_get_rowbytes
5789 # undef png_get_valid
5790 # undef png_longjmp
5791 # undef png_read_end
5792 # undef png_read_image
5793 # undef png_read_info
5794 # undef png_read_update_info
5795 # undef png_set_background
5796 # undef png_set_expand
5797 # undef png_set_gray_to_rgb
5798 # undef png_set_longjmp_fn
5799 # undef png_set_read_fn
5800 # undef png_set_sig_bytes
5801 # undef png_set_strip_16
5802 # undef png_sig_cmp
5804 # define png_create_info_struct fn_png_create_info_struct
5805 # define png_create_read_struct fn_png_create_read_struct
5806 # define png_destroy_read_struct fn_png_destroy_read_struct
5807 # define png_error fn_png_error
5808 # define png_get_bKGD fn_png_get_bKGD
5809 # define png_get_channels fn_png_get_channels
5810 # define png_get_IHDR fn_png_get_IHDR
5811 # define png_get_io_ptr fn_png_get_io_ptr
5812 # define png_get_rowbytes fn_png_get_rowbytes
5813 # define png_get_valid fn_png_get_valid
5814 # define png_longjmp fn_png_longjmp
5815 # define png_read_end fn_png_read_end
5816 # define png_read_image fn_png_read_image
5817 # define png_read_info fn_png_read_info
5818 # define png_read_update_info fn_png_read_update_info
5819 # define png_set_background fn_png_set_background
5820 # define png_set_expand fn_png_set_expand
5821 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5822 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5823 # define png_set_read_fn fn_png_set_read_fn
5824 # define png_set_sig_bytes fn_png_set_sig_bytes
5825 # define png_set_strip_16 fn_png_set_strip_16
5826 # define png_sig_cmp fn_png_sig_cmp
5828 # endif /* WINDOWSNT */
5830 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5831 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5832 Do not use sys_setjmp, as PNG supports only jmp_buf.
5833 It's OK if the longjmp substitute restores the signal mask. */
5834 # ifdef HAVE__SETJMP
5835 # define FAST_SETJMP(j) _setjmp (j)
5836 # define FAST_LONGJMP _longjmp
5837 # else
5838 # define FAST_SETJMP(j) setjmp (j)
5839 # define FAST_LONGJMP longjmp
5840 # endif
5842 # if PNG_LIBPNG_VER < 10500
5843 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5844 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5845 # else
5846 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5847 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5848 # define PNG_JMPBUF(ptr) \
5849 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5850 # endif
5852 /* Error and warning handlers installed when the PNG library
5853 is initialized. */
5855 static _Noreturn void
5856 my_png_error (png_struct *png_ptr, const char *msg)
5858 eassert (png_ptr != NULL);
5859 /* Avoid compiler warning about deprecated direct access to
5860 png_ptr's fields in libpng versions 1.4.x. */
5861 image_error ("PNG error: %s", build_string (msg));
5862 PNG_LONGJMP (png_ptr);
5866 static void
5867 my_png_warning (png_struct *png_ptr, const char *msg)
5869 eassert (png_ptr != NULL);
5870 image_error ("PNG warning: %s", build_string (msg));
5873 /* Memory source for PNG decoding. */
5875 struct png_memory_storage
5877 unsigned char *bytes; /* The data */
5878 ptrdiff_t len; /* How big is it? */
5879 ptrdiff_t index; /* Where are we? */
5883 /* Function set as reader function when reading PNG image from memory.
5884 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5885 bytes from the input to DATA. */
5887 static void
5888 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5890 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5892 if (length > tbr->len - tbr->index)
5893 png_error (png_ptr, "Read error");
5895 memcpy (data, tbr->bytes + tbr->index, length);
5896 tbr->index = tbr->index + length;
5900 /* Function set as reader function when reading PNG image from a file.
5901 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5902 bytes from the input to DATA. */
5904 static void
5905 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5907 FILE *fp = png_get_io_ptr (png_ptr);
5909 if (fread_unlocked (data, 1, length, fp) < length)
5910 png_error (png_ptr, "Read error");
5914 /* Load PNG image IMG for use on frame F. Value is true if
5915 successful. */
5917 struct png_load_context
5919 /* These are members so that longjmp doesn't munge local variables. */
5920 png_struct *png_ptr;
5921 png_info *info_ptr;
5922 png_info *end_info;
5923 FILE *fp;
5924 png_byte *pixels;
5925 png_byte **rows;
5928 static bool
5929 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5931 Lisp_Object specified_file, specified_data;
5932 FILE *fp = NULL;
5933 int x, y;
5934 ptrdiff_t i;
5935 png_struct *png_ptr;
5936 png_info *info_ptr = NULL, *end_info = NULL;
5937 png_byte sig[8];
5938 png_byte *pixels = NULL;
5939 png_byte **rows = NULL;
5940 png_uint_32 width, height;
5941 int bit_depth, color_type, interlace_type;
5942 png_byte channels;
5943 png_uint_32 row_bytes;
5944 bool transparent_p;
5945 struct png_memory_storage tbr; /* Data to be read */
5946 ptrdiff_t nbytes;
5948 #ifdef USE_CAIRO
5949 unsigned char *data = 0;
5950 uint32_t *dataptr;
5951 #else
5952 XImagePtr ximg, mask_img = NULL;
5953 #endif
5955 /* Find out what file to load. */
5956 specified_file = image_spec_value (img->spec, QCfile, NULL);
5957 specified_data = image_spec_value (img->spec, QCdata, NULL);
5959 if (NILP (specified_data))
5961 int fd;
5962 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5963 if (!STRINGP (file))
5965 image_error ("Cannot find image file `%s'", specified_file);
5966 return 0;
5969 /* Open the image file. */
5970 fp = fdopen (fd, "rb");
5971 if (!fp)
5973 image_error ("Cannot open image file `%s'", file);
5974 return 0;
5977 /* Check PNG signature. */
5978 if (fread_unlocked (sig, 1, sizeof sig, fp) != sizeof sig
5979 || png_sig_cmp (sig, 0, sizeof sig))
5981 fclose (fp);
5982 image_error ("Not a PNG file: `%s'", file);
5983 return 0;
5986 else
5988 if (!STRINGP (specified_data))
5990 image_error ("Invalid image data `%s'", specified_data);
5991 return 0;
5994 /* Read from memory. */
5995 tbr.bytes = SDATA (specified_data);
5996 tbr.len = SBYTES (specified_data);
5997 tbr.index = 0;
5999 /* Check PNG signature. */
6000 if (tbr.len < sizeof sig
6001 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
6003 image_error ("Not a PNG image: `%s'", img->spec);
6004 return 0;
6007 /* Need to skip past the signature. */
6008 tbr.bytes += sizeof (sig);
6011 /* Initialize read and info structs for PNG lib. */
6012 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
6013 NULL, my_png_error,
6014 my_png_warning);
6015 if (png_ptr)
6017 info_ptr = png_create_info_struct (png_ptr);
6018 end_info = png_create_info_struct (png_ptr);
6021 c->png_ptr = png_ptr;
6022 c->info_ptr = info_ptr;
6023 c->end_info = end_info;
6024 c->fp = fp;
6025 c->pixels = pixels;
6026 c->rows = rows;
6028 if (! (info_ptr && end_info))
6030 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6031 png_ptr = 0;
6033 if (! png_ptr)
6035 if (fp) fclose (fp);
6036 return 0;
6039 /* Set error jump-back. We come back here when the PNG library
6040 detects an error. */
6041 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
6043 error:
6044 if (c->png_ptr)
6045 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6046 xfree (c->pixels);
6047 xfree (c->rows);
6048 if (c->fp)
6049 fclose (c->fp);
6050 return 0;
6053 /* Read image info. */
6054 if (!NILP (specified_data))
6055 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
6056 else
6057 png_set_read_fn (png_ptr, fp, png_read_from_file);
6059 png_set_sig_bytes (png_ptr, sizeof sig);
6060 png_read_info (png_ptr, info_ptr);
6061 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6062 &interlace_type, NULL, NULL);
6064 if (! (width <= INT_MAX && height <= INT_MAX
6065 && check_image_size (f, width, height)))
6067 image_size_error ();
6068 goto error;
6071 #ifndef USE_CAIRO
6072 /* Create the X image and pixmap now, so that the work below can be
6073 omitted if the image is too large for X. */
6074 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6075 goto error;
6076 #endif
6078 /* If image contains simply transparency data, we prefer to
6079 construct a clipping mask. */
6080 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6081 transparent_p = 1;
6082 else
6083 transparent_p = 0;
6085 /* This function is easier to write if we only have to handle
6086 one data format: RGB or RGBA with 8 bits per channel. Let's
6087 transform other formats into that format. */
6089 /* Strip more than 8 bits per channel. */
6090 if (bit_depth == 16)
6091 png_set_strip_16 (png_ptr);
6093 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6094 if available. */
6095 png_set_expand (png_ptr);
6097 /* Convert grayscale images to RGB. */
6098 if (color_type == PNG_COLOR_TYPE_GRAY
6099 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6100 png_set_gray_to_rgb (png_ptr);
6102 /* Handle alpha channel by combining the image with a background
6103 color. Do this only if a real alpha channel is supplied. For
6104 simple transparency, we prefer a clipping mask. */
6105 if (!transparent_p)
6107 /* png_color_16 *image_bg; */
6108 Lisp_Object specified_bg
6109 = image_spec_value (img->spec, QCbackground, NULL);
6110 XColor color;
6112 /* If the user specified a color, try to use it; if not, use the
6113 current frame background, ignoring any default background
6114 color set by the image. */
6115 if (STRINGP (specified_bg)
6116 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
6117 : (x_query_frame_background_color (f, &color), true))
6118 /* The user specified `:background', use that. */
6120 int shift = bit_depth == 16 ? 0 : 8;
6121 png_color_16 bg = { 0 };
6122 bg.red = color.red >> shift;
6123 bg.green = color.green >> shift;
6124 bg.blue = color.blue >> shift;
6126 png_set_background (png_ptr, &bg,
6127 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6131 /* Update info structure. */
6132 png_read_update_info (png_ptr, info_ptr);
6134 /* Get number of channels. Valid values are 1 for grayscale images
6135 and images with a palette, 2 for grayscale images with transparency
6136 information (alpha channel), 3 for RGB images, and 4 for RGB
6137 images with alpha channel, i.e. RGBA. If conversions above were
6138 sufficient we should only have 3 or 4 channels here. */
6139 channels = png_get_channels (png_ptr, info_ptr);
6140 eassert (channels == 3 || channels == 4);
6142 /* Number of bytes needed for one row of the image. */
6143 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
6145 /* Allocate memory for the image. */
6146 if (INT_MULTIPLY_WRAPV (row_bytes, sizeof *pixels, &nbytes)
6147 || INT_MULTIPLY_WRAPV (nbytes, height, &nbytes))
6148 memory_full (SIZE_MAX);
6149 c->pixels = pixels = xmalloc (nbytes);
6150 c->rows = rows = xmalloc (height * sizeof *rows);
6151 for (i = 0; i < height; ++i)
6152 rows[i] = pixels + i * row_bytes;
6154 /* Read the entire image. */
6155 png_read_image (png_ptr, rows);
6156 png_read_end (png_ptr, info_ptr);
6157 if (fp)
6159 fclose (fp);
6160 c->fp = NULL;
6163 #ifdef USE_CAIRO
6164 data = (unsigned char *) xmalloc (width * height * 4);
6165 dataptr = (uint32_t *) data;
6166 #else
6167 /* Create an image and pixmap serving as mask if the PNG image
6168 contains an alpha channel. */
6169 if (channels == 4
6170 && !transparent_p
6171 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
6172 &mask_img, 1))
6174 x_destroy_x_image (ximg);
6175 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
6176 goto error;
6178 #endif
6180 /* Fill the X image and mask from PNG data. */
6181 init_color_table ();
6183 for (y = 0; y < height; ++y)
6185 png_byte *p = rows[y];
6187 for (x = 0; x < width; ++x)
6189 int r, g, b;
6191 #ifdef USE_CAIRO
6192 int a = 0xff;
6193 r = *p++;
6194 g = *p++;
6195 b = *p++;
6196 if (channels == 4) a = *p++;
6197 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
6198 #else
6199 r = *p++ << 8;
6200 g = *p++ << 8;
6201 b = *p++ << 8;
6202 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6203 /* An alpha channel, aka mask channel, associates variable
6204 transparency with an image. Where other image formats
6205 support binary transparency---fully transparent or fully
6206 opaque---PNG allows up to 254 levels of partial transparency.
6207 The PNG library implements partial transparency by combining
6208 the image with a specified background color.
6210 I'm not sure how to handle this here nicely: because the
6211 background on which the image is displayed may change, for
6212 real alpha channel support, it would be necessary to create
6213 a new image for each possible background.
6215 What I'm doing now is that a mask is created if we have
6216 boolean transparency information. Otherwise I'm using
6217 the frame's background color to combine the image with. */
6219 if (channels == 4)
6221 if (mask_img)
6222 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6223 ++p;
6225 #endif
6229 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6230 /* Set IMG's background color from the PNG image, unless the user
6231 overrode it. */
6233 png_color_16 *bg;
6234 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6236 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6237 img->background_valid = 1;
6241 # ifdef COLOR_TABLE_SUPPORT
6242 /* Remember colors allocated for this image. */
6243 img->colors = colors_in_color_table (&img->ncolors);
6244 free_color_table ();
6245 # endif /* COLOR_TABLE_SUPPORT */
6247 /* Clean up. */
6248 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6249 xfree (rows);
6250 xfree (pixels);
6252 img->width = width;
6253 img->height = height;
6255 #ifdef USE_CAIRO
6256 create_cairo_image_surface (img, data, width, height);
6257 #else
6258 /* Maybe fill in the background field while we have ximg handy.
6259 Casting avoids a GCC warning. */
6260 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6262 /* Put ximg into the image. */
6263 image_put_x_image (f, img, ximg, 0);
6265 /* Same for the mask. */
6266 if (mask_img)
6268 /* Fill in the background_transparent field while we have the
6269 mask handy. Casting avoids a GCC warning. */
6270 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6272 image_put_x_image (f, img, mask_img, 1);
6274 #endif
6276 return 1;
6279 static bool
6280 png_load (struct frame *f, struct image *img)
6282 struct png_load_context c;
6283 return png_load_body (f, img, &c);
6286 #elif defined HAVE_NS
6288 static bool
6289 png_load (struct frame *f, struct image *img)
6291 return ns_load_image (f, img,
6292 image_spec_value (img->spec, QCfile, NULL),
6293 image_spec_value (img->spec, QCdata, NULL));
6297 #endif /* HAVE_NS */
6301 /***********************************************************************
6302 JPEG
6303 ***********************************************************************/
6305 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6307 static bool jpeg_image_p (Lisp_Object object);
6308 static bool jpeg_load (struct frame *f, struct image *img);
6310 /* Indices of image specification fields in gs_format, below. */
6312 enum jpeg_keyword_index
6314 JPEG_TYPE,
6315 JPEG_DATA,
6316 JPEG_FILE,
6317 JPEG_ASCENT,
6318 JPEG_MARGIN,
6319 JPEG_RELIEF,
6320 JPEG_ALGORITHM,
6321 JPEG_HEURISTIC_MASK,
6322 JPEG_MASK,
6323 JPEG_BACKGROUND,
6324 JPEG_LAST
6327 /* Vector of image_keyword structures describing the format
6328 of valid user-defined image specifications. */
6330 static const struct image_keyword jpeg_format[JPEG_LAST] =
6332 {":type", IMAGE_SYMBOL_VALUE, 1},
6333 {":data", IMAGE_STRING_VALUE, 0},
6334 {":file", IMAGE_STRING_VALUE, 0},
6335 {":ascent", IMAGE_ASCENT_VALUE, 0},
6336 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6337 {":relief", IMAGE_INTEGER_VALUE, 0},
6338 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6339 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6340 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6341 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6344 #if defined HAVE_NTGUI && defined WINDOWSNT
6345 static bool init_jpeg_functions (void);
6346 #else
6347 #define init_jpeg_functions NULL
6348 #endif
6350 /* Structure describing the image type `jpeg'. */
6352 static struct image_type jpeg_type =
6354 SYMBOL_INDEX (Qjpeg),
6355 jpeg_image_p,
6356 jpeg_load,
6357 x_clear_image,
6358 init_jpeg_functions,
6359 NULL
6362 /* Return true if OBJECT is a valid JPEG image specification. */
6364 static bool
6365 jpeg_image_p (Lisp_Object object)
6367 struct image_keyword fmt[JPEG_LAST];
6369 memcpy (fmt, jpeg_format, sizeof fmt);
6371 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6372 return 0;
6374 /* Must specify either the :data or :file keyword. */
6375 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6378 #endif /* HAVE_JPEG || HAVE_NS */
6380 #ifdef HAVE_JPEG
6382 /* Work around a warning about HAVE_STDLIB_H being redefined in
6383 jconfig.h. */
6384 # ifdef HAVE_STDLIB_H
6385 # undef HAVE_STDLIB_H
6386 # endif
6388 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6389 /* In older releases of the jpeg library, jpeglib.h will define boolean
6390 differently depending on __WIN32__, so make sure it is defined. */
6391 # define __WIN32__ 1
6392 # endif
6394 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6395 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6396 using the Windows boolean type instead of the jpeglib boolean type
6397 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6398 headers are included along with windows.h, so under Cygwin, jpeglib
6399 attempts to define a conflicting boolean type. Worse, forcing
6400 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6401 because it created an ABI incompatibility between the
6402 already-compiled jpeg library and the header interface definition.
6404 The best we can do is to define jpeglib's boolean type to a
6405 different name. This name, jpeg_boolean, remains in effect through
6406 the rest of image.c.
6408 # if defined CYGWIN && defined HAVE_NTGUI
6409 # define boolean jpeg_boolean
6410 # endif
6411 # include <jpeglib.h>
6412 # include <jerror.h>
6414 # ifdef WINDOWSNT
6416 /* JPEG library details. */
6417 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6418 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6419 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6420 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6421 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6422 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6423 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6424 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6425 (struct jpeg_error_mgr *));
6426 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6428 static bool
6429 init_jpeg_functions (void)
6431 HMODULE library;
6433 if (!(library = w32_delayed_load (Qjpeg)))
6434 return 0;
6436 LOAD_DLL_FN (library, jpeg_finish_decompress);
6437 LOAD_DLL_FN (library, jpeg_read_scanlines);
6438 LOAD_DLL_FN (library, jpeg_start_decompress);
6439 LOAD_DLL_FN (library, jpeg_read_header);
6440 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6441 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6442 LOAD_DLL_FN (library, jpeg_std_error);
6443 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6444 return 1;
6447 # undef jpeg_CreateDecompress
6448 # undef jpeg_destroy_decompress
6449 # undef jpeg_finish_decompress
6450 # undef jpeg_read_header
6451 # undef jpeg_read_scanlines
6452 # undef jpeg_resync_to_restart
6453 # undef jpeg_start_decompress
6454 # undef jpeg_std_error
6456 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6457 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6458 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6459 # define jpeg_read_header fn_jpeg_read_header
6460 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6461 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6462 # define jpeg_start_decompress fn_jpeg_start_decompress
6463 # define jpeg_std_error fn_jpeg_std_error
6465 /* Wrapper since we can't directly assign the function pointer
6466 to another function pointer that was declared more completely easily. */
6467 static boolean
6468 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6470 return jpeg_resync_to_restart (cinfo, desired);
6472 # undef jpeg_resync_to_restart
6473 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6475 # endif /* WINDOWSNT */
6477 struct my_jpeg_error_mgr
6479 struct jpeg_error_mgr pub;
6480 sys_jmp_buf setjmp_buffer;
6482 /* The remaining members are so that longjmp doesn't munge local
6483 variables. */
6484 struct jpeg_decompress_struct cinfo;
6485 enum
6487 MY_JPEG_ERROR_EXIT,
6488 MY_JPEG_INVALID_IMAGE_SIZE,
6489 MY_JPEG_CANNOT_CREATE_X
6490 } failure_code;
6494 static _Noreturn void
6495 my_error_exit (j_common_ptr cinfo)
6497 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6498 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6499 sys_longjmp (mgr->setjmp_buffer, 1);
6503 /* Init source method for JPEG data source manager. Called by
6504 jpeg_read_header() before any data is actually read. See
6505 libjpeg.doc from the JPEG lib distribution. */
6507 static void
6508 our_common_init_source (j_decompress_ptr cinfo)
6513 /* Method to terminate data source. Called by
6514 jpeg_finish_decompress() after all data has been processed. */
6516 static void
6517 our_common_term_source (j_decompress_ptr cinfo)
6522 /* Fill input buffer method for JPEG data source manager. Called
6523 whenever more data is needed. We read the whole image in one step,
6524 so this only adds a fake end of input marker at the end. */
6526 static JOCTET our_memory_buffer[2];
6528 static boolean
6529 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6531 /* Insert a fake EOI marker. */
6532 struct jpeg_source_mgr *src = cinfo->src;
6534 our_memory_buffer[0] = (JOCTET) 0xFF;
6535 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6537 src->next_input_byte = our_memory_buffer;
6538 src->bytes_in_buffer = 2;
6539 return 1;
6543 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6544 is the JPEG data source manager. */
6546 static void
6547 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6549 struct jpeg_source_mgr *src = cinfo->src;
6551 if (src)
6553 if (num_bytes > src->bytes_in_buffer)
6554 ERREXIT (cinfo, JERR_INPUT_EOF);
6556 src->bytes_in_buffer -= num_bytes;
6557 src->next_input_byte += num_bytes;
6562 /* Set up the JPEG lib for reading an image from DATA which contains
6563 LEN bytes. CINFO is the decompression info structure created for
6564 reading the image. */
6566 static void
6567 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6569 struct jpeg_source_mgr *src = cinfo->src;
6571 if (! src)
6573 /* First time for this JPEG object? */
6574 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6575 JPOOL_PERMANENT, sizeof *src);
6576 cinfo->src = src;
6577 src->next_input_byte = data;
6580 src->init_source = our_common_init_source;
6581 src->fill_input_buffer = our_memory_fill_input_buffer;
6582 src->skip_input_data = our_memory_skip_input_data;
6583 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6584 src->term_source = our_common_term_source;
6585 src->bytes_in_buffer = len;
6586 src->next_input_byte = data;
6590 struct jpeg_stdio_mgr
6592 struct jpeg_source_mgr mgr;
6593 boolean finished;
6594 FILE *file;
6595 JOCTET *buffer;
6599 /* Size of buffer to read JPEG from file.
6600 Not too big, as we want to use alloc_small. */
6601 #define JPEG_STDIO_BUFFER_SIZE 8192
6604 /* Fill input buffer method for JPEG data source manager. Called
6605 whenever more data is needed. The data is read from a FILE *. */
6607 static boolean
6608 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6610 struct jpeg_stdio_mgr *src;
6612 src = (struct jpeg_stdio_mgr *) cinfo->src;
6613 if (!src->finished)
6615 ptrdiff_t bytes;
6617 bytes = fread_unlocked (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE,
6618 src->file);
6619 if (bytes > 0)
6620 src->mgr.bytes_in_buffer = bytes;
6621 else
6623 WARNMS (cinfo, JWRN_JPEG_EOF);
6624 src->finished = 1;
6625 src->buffer[0] = (JOCTET) 0xFF;
6626 src->buffer[1] = (JOCTET) JPEG_EOI;
6627 src->mgr.bytes_in_buffer = 2;
6629 src->mgr.next_input_byte = src->buffer;
6632 return 1;
6636 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6637 is the JPEG data source manager. */
6639 static void
6640 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6642 struct jpeg_stdio_mgr *src;
6643 src = (struct jpeg_stdio_mgr *) cinfo->src;
6645 while (num_bytes > 0 && !src->finished)
6647 if (num_bytes <= src->mgr.bytes_in_buffer)
6649 src->mgr.bytes_in_buffer -= num_bytes;
6650 src->mgr.next_input_byte += num_bytes;
6651 break;
6653 else
6655 num_bytes -= src->mgr.bytes_in_buffer;
6656 src->mgr.bytes_in_buffer = 0;
6657 src->mgr.next_input_byte = NULL;
6659 our_stdio_fill_input_buffer (cinfo);
6665 /* Set up the JPEG lib for reading an image from a FILE *.
6666 CINFO is the decompression info structure created for
6667 reading the image. */
6669 static void
6670 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6672 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6674 if (! src)
6676 /* First time for this JPEG object? */
6677 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6678 JPOOL_PERMANENT, sizeof *src);
6679 cinfo->src = (struct jpeg_source_mgr *) src;
6680 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6681 JPOOL_PERMANENT,
6682 JPEG_STDIO_BUFFER_SIZE);
6685 src->file = fp;
6686 src->finished = 0;
6687 src->mgr.init_source = our_common_init_source;
6688 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6689 src->mgr.skip_input_data = our_stdio_skip_input_data;
6690 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6691 src->mgr.term_source = our_common_term_source;
6692 src->mgr.bytes_in_buffer = 0;
6693 src->mgr.next_input_byte = NULL;
6696 /* Load image IMG for use on frame F. Patterned after example.c
6697 from the JPEG lib. */
6699 static bool
6700 jpeg_load_body (struct frame *f, struct image *img,
6701 struct my_jpeg_error_mgr *mgr)
6703 Lisp_Object specified_file, specified_data;
6704 FILE *volatile fp = NULL;
6705 JSAMPARRAY buffer;
6706 int row_stride, x, y;
6707 int width, height;
6708 int i, ir, ig, ib;
6709 #ifndef USE_CAIRO
6710 unsigned long *colors;
6711 XImagePtr ximg = NULL;
6712 #endif
6714 /* Open the JPEG file. */
6715 specified_file = image_spec_value (img->spec, QCfile, NULL);
6716 specified_data = image_spec_value (img->spec, QCdata, NULL);
6718 if (NILP (specified_data))
6720 int fd;
6721 Lisp_Object file = x_find_image_fd (specified_file, &fd);
6722 if (!STRINGP (file))
6724 image_error ("Cannot find image file `%s'", specified_file);
6725 return 0;
6728 fp = fdopen (fd, "rb");
6729 if (fp == NULL)
6731 image_error ("Cannot open `%s'", file);
6732 return 0;
6735 else if (!STRINGP (specified_data))
6737 image_error ("Invalid image data `%s'", specified_data);
6738 return 0;
6741 /* Customize libjpeg's error handling to call my_error_exit when an
6742 error is detected. This function will perform a longjmp. */
6743 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6744 mgr->pub.error_exit = my_error_exit;
6745 if (sys_setjmp (mgr->setjmp_buffer))
6747 switch (mgr->failure_code)
6749 case MY_JPEG_ERROR_EXIT:
6751 char buf[JMSG_LENGTH_MAX];
6752 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6753 image_error ("Error reading JPEG image `%s': %s",
6754 img->spec, build_string (buf));
6755 break;
6758 case MY_JPEG_INVALID_IMAGE_SIZE:
6759 image_size_error ();
6760 break;
6762 case MY_JPEG_CANNOT_CREATE_X:
6763 break;
6766 /* Close the input file and destroy the JPEG object. */
6767 if (fp)
6768 fclose (fp);
6769 jpeg_destroy_decompress (&mgr->cinfo);
6771 /* If we already have an XImage, free that. */
6772 #ifndef USE_CAIRO
6773 x_destroy_x_image (ximg);
6774 #endif
6775 /* Free pixmap and colors. */
6776 x_clear_image (f, img);
6777 return 0;
6780 /* Create the JPEG decompression object. Let it read from fp.
6781 Read the JPEG image header. */
6782 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6784 if (NILP (specified_data))
6785 jpeg_file_src (&mgr->cinfo, fp);
6786 else
6787 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6788 SBYTES (specified_data));
6790 jpeg_read_header (&mgr->cinfo, 1);
6792 /* Customize decompression so that color quantization will be used.
6793 Start decompression. */
6794 mgr->cinfo.quantize_colors = 1;
6795 jpeg_start_decompress (&mgr->cinfo);
6796 width = img->width = mgr->cinfo.output_width;
6797 height = img->height = mgr->cinfo.output_height;
6799 if (!check_image_size (f, width, height))
6801 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6802 sys_longjmp (mgr->setjmp_buffer, 1);
6805 #ifndef USE_CAIRO
6806 /* Create X image and pixmap. */
6807 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6809 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6810 sys_longjmp (mgr->setjmp_buffer, 1);
6812 #endif
6814 /* Allocate colors. When color quantization is used,
6815 mgr->cinfo.actual_number_of_colors has been set with the number of
6816 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6817 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6818 No more than 255 colors will be generated. */
6819 USE_SAFE_ALLOCA;
6821 if (mgr->cinfo.out_color_components > 2)
6822 ir = 0, ig = 1, ib = 2;
6823 else if (mgr->cinfo.out_color_components > 1)
6824 ir = 0, ig = 1, ib = 0;
6825 else
6826 ir = 0, ig = 0, ib = 0;
6828 #ifndef USE_CAIRO
6829 /* Use the color table mechanism because it handles colors that
6830 cannot be allocated nicely. Such colors will be replaced with
6831 a default color, and we don't have to care about which colors
6832 can be freed safely, and which can't. */
6833 init_color_table ();
6834 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6836 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6838 /* Multiply RGB values with 255 because X expects RGB values
6839 in the range 0..0xffff. */
6840 int r = mgr->cinfo.colormap[ir][i] << 8;
6841 int g = mgr->cinfo.colormap[ig][i] << 8;
6842 int b = mgr->cinfo.colormap[ib][i] << 8;
6843 colors[i] = lookup_rgb_color (f, r, g, b);
6845 #endif
6847 #ifdef COLOR_TABLE_SUPPORT
6848 /* Remember those colors actually allocated. */
6849 img->colors = colors_in_color_table (&img->ncolors);
6850 free_color_table ();
6851 #endif /* COLOR_TABLE_SUPPORT */
6854 /* Read pixels. */
6855 row_stride = width * mgr->cinfo.output_components;
6856 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6857 JPOOL_IMAGE, row_stride, 1);
6858 #ifdef USE_CAIRO
6860 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
6861 uint32_t *dataptr = (uint32_t *) data;
6862 int r, g, b;
6864 for (y = 0; y < height; ++y)
6866 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6868 for (x = 0; x < width; ++x)
6870 i = buffer[0][x];
6871 r = mgr->cinfo.colormap[ir][i];
6872 g = mgr->cinfo.colormap[ig][i];
6873 b = mgr->cinfo.colormap[ib][i];
6874 *dataptr++ = (0xffu << 24) | (r << 16) | (g << 8) | b;
6878 create_cairo_image_surface (img, data, width, height);
6880 #else
6881 for (y = 0; y < height; ++y)
6883 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6884 for (x = 0; x < mgr->cinfo.output_width; ++x)
6885 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6887 #endif
6889 /* Clean up. */
6890 jpeg_finish_decompress (&mgr->cinfo);
6891 jpeg_destroy_decompress (&mgr->cinfo);
6892 if (fp)
6893 fclose (fp);
6895 #ifndef USE_CAIRO
6896 /* Maybe fill in the background field while we have ximg handy. */
6897 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6898 /* Casting avoids a GCC warning. */
6899 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6901 /* Put ximg into the image. */
6902 image_put_x_image (f, img, ximg, 0);
6903 #endif
6904 SAFE_FREE ();
6905 return 1;
6908 static bool
6909 jpeg_load (struct frame *f, struct image *img)
6911 struct my_jpeg_error_mgr mgr;
6912 return jpeg_load_body (f, img, &mgr);
6915 #else /* HAVE_JPEG */
6917 #ifdef HAVE_NS
6918 static bool
6919 jpeg_load (struct frame *f, struct image *img)
6921 return ns_load_image (f, img,
6922 image_spec_value (img->spec, QCfile, NULL),
6923 image_spec_value (img->spec, QCdata, NULL));
6925 #endif /* HAVE_NS */
6927 #endif /* !HAVE_JPEG */
6931 /***********************************************************************
6932 TIFF
6933 ***********************************************************************/
6935 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6937 static bool tiff_image_p (Lisp_Object object);
6938 static bool tiff_load (struct frame *f, struct image *img);
6940 /* Indices of image specification fields in tiff_format, below. */
6942 enum tiff_keyword_index
6944 TIFF_TYPE,
6945 TIFF_DATA,
6946 TIFF_FILE,
6947 TIFF_ASCENT,
6948 TIFF_MARGIN,
6949 TIFF_RELIEF,
6950 TIFF_ALGORITHM,
6951 TIFF_HEURISTIC_MASK,
6952 TIFF_MASK,
6953 TIFF_BACKGROUND,
6954 TIFF_INDEX,
6955 TIFF_LAST
6958 /* Vector of image_keyword structures describing the format
6959 of valid user-defined image specifications. */
6961 static const struct image_keyword tiff_format[TIFF_LAST] =
6963 {":type", IMAGE_SYMBOL_VALUE, 1},
6964 {":data", IMAGE_STRING_VALUE, 0},
6965 {":file", IMAGE_STRING_VALUE, 0},
6966 {":ascent", IMAGE_ASCENT_VALUE, 0},
6967 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6968 {":relief", IMAGE_INTEGER_VALUE, 0},
6969 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6970 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6971 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6972 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6973 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6976 #if defined HAVE_NTGUI && defined WINDOWSNT
6977 static bool init_tiff_functions (void);
6978 #else
6979 #define init_tiff_functions NULL
6980 #endif
6982 /* Structure describing the image type `tiff'. */
6984 static struct image_type tiff_type =
6986 SYMBOL_INDEX (Qtiff),
6987 tiff_image_p,
6988 tiff_load,
6989 x_clear_image,
6990 init_tiff_functions,
6991 NULL
6994 /* Return true if OBJECT is a valid TIFF image specification. */
6996 static bool
6997 tiff_image_p (Lisp_Object object)
6999 struct image_keyword fmt[TIFF_LAST];
7000 memcpy (fmt, tiff_format, sizeof fmt);
7002 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
7003 return 0;
7005 /* Must specify either the :data or :file keyword. */
7006 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
7009 #endif /* HAVE_TIFF || HAVE_NS */
7011 #ifdef HAVE_TIFF
7013 # include <tiffio.h>
7015 # ifdef WINDOWSNT
7017 /* TIFF library details. */
7018 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
7019 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
7020 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
7021 DEF_DLL_FN (TIFF *, TIFFClientOpen,
7022 (const char *, const char *, thandle_t, TIFFReadWriteProc,
7023 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
7024 TIFFMapFileProc, TIFFUnmapFileProc));
7025 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
7026 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
7027 DEF_DLL_FN (void, TIFFClose, (TIFF *));
7028 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
7030 static bool
7031 init_tiff_functions (void)
7033 HMODULE library;
7035 if (!(library = w32_delayed_load (Qtiff)))
7036 return 0;
7038 LOAD_DLL_FN (library, TIFFSetErrorHandler);
7039 LOAD_DLL_FN (library, TIFFSetWarningHandler);
7040 LOAD_DLL_FN (library, TIFFOpen);
7041 LOAD_DLL_FN (library, TIFFClientOpen);
7042 LOAD_DLL_FN (library, TIFFGetField);
7043 LOAD_DLL_FN (library, TIFFReadRGBAImage);
7044 LOAD_DLL_FN (library, TIFFClose);
7045 LOAD_DLL_FN (library, TIFFSetDirectory);
7046 return 1;
7049 # undef TIFFClientOpen
7050 # undef TIFFClose
7051 # undef TIFFGetField
7052 # undef TIFFOpen
7053 # undef TIFFReadRGBAImage
7054 # undef TIFFSetDirectory
7055 # undef TIFFSetErrorHandler
7056 # undef TIFFSetWarningHandler
7058 # define TIFFClientOpen fn_TIFFClientOpen
7059 # define TIFFClose fn_TIFFClose
7060 # define TIFFGetField fn_TIFFGetField
7061 # define TIFFOpen fn_TIFFOpen
7062 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7063 # define TIFFSetDirectory fn_TIFFSetDirectory
7064 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7065 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7067 # endif /* WINDOWSNT */
7070 /* Reading from a memory buffer for TIFF images Based on the PNG
7071 memory source, but we have to provide a lot of extra functions.
7072 Blah.
7074 We really only need to implement read and seek, but I am not
7075 convinced that the TIFF library is smart enough not to destroy
7076 itself if we only hand it the function pointers we need to
7077 override. */
7079 typedef struct
7081 unsigned char *bytes;
7082 ptrdiff_t len;
7083 ptrdiff_t index;
7085 tiff_memory_source;
7087 static tsize_t
7088 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7090 tiff_memory_source *src = (tiff_memory_source *) data;
7092 size = min (size, src->len - src->index);
7093 memcpy (buf, src->bytes + src->index, size);
7094 src->index += size;
7095 return size;
7098 static tsize_t
7099 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7101 return -1;
7104 static toff_t
7105 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
7107 tiff_memory_source *src = (tiff_memory_source *) data;
7108 ptrdiff_t idx;
7110 switch (whence)
7112 case SEEK_SET: /* Go from beginning of source. */
7113 idx = off;
7114 break;
7116 case SEEK_END: /* Go from end of source. */
7117 idx = src->len + off;
7118 break;
7120 case SEEK_CUR: /* Go from current position. */
7121 idx = src->index + off;
7122 break;
7124 default: /* Invalid `whence'. */
7125 return -1;
7128 if (idx > src->len || idx < 0)
7129 return -1;
7131 src->index = idx;
7132 return src->index;
7135 static int
7136 tiff_close_memory (thandle_t data)
7138 /* NOOP */
7139 return 0;
7142 static int
7143 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
7145 /* It is already _IN_ memory. */
7146 return 0;
7149 static void
7150 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
7152 /* We don't need to do this. */
7155 static toff_t
7156 tiff_size_of_memory (thandle_t data)
7158 return ((tiff_memory_source *) data)->len;
7161 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7162 compiler error compiling tiff_handler, see Bugzilla bug #17406
7163 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7164 this function as external works around that problem. */
7165 # if defined (__MINGW32__) && __GNUC__ == 3
7166 # define MINGW_STATIC
7167 # else
7168 # define MINGW_STATIC static
7169 # endif
7171 MINGW_STATIC void
7172 tiff_handler (const char *, const char *, const char *, va_list)
7173 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7174 MINGW_STATIC void
7175 tiff_handler (const char *log_format, const char *title,
7176 const char *format, va_list ap)
7178 /* doprnt is not suitable here, as TIFF handlers are called from
7179 libtiff and are passed arbitrary printf directives. Instead, use
7180 vsnprintf, taking care to be portable to nonstandard environments
7181 where vsnprintf returns -1 on buffer overflow. Since it's just a
7182 log entry, it's OK to truncate it. */
7183 char buf[4000];
7184 int len = vsnprintf (buf, sizeof buf, format, ap);
7185 add_to_log (log_format, build_string (title),
7186 make_string (buf, max (0, min (len, sizeof buf - 1))));
7188 # undef MINGW_STATIC
7190 static void tiff_error_handler (const char *, const char *, va_list)
7191 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7192 static void
7193 tiff_error_handler (const char *title, const char *format, va_list ap)
7195 tiff_handler ("TIFF error: %s %s", title, format, ap);
7199 static void tiff_warning_handler (const char *, const char *, va_list)
7200 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7201 static void
7202 tiff_warning_handler (const char *title, const char *format, va_list ap)
7204 tiff_handler ("TIFF warning: %s %s", title, format, ap);
7208 /* Load TIFF image IMG for use on frame F. Value is true if
7209 successful. */
7211 static bool
7212 tiff_load (struct frame *f, struct image *img)
7214 Lisp_Object specified_file;
7215 Lisp_Object specified_data;
7216 TIFF *tiff;
7217 int width, height, x, y, count;
7218 uint32 *buf;
7219 int rc;
7220 XImagePtr ximg;
7221 tiff_memory_source memsrc;
7222 Lisp_Object image;
7224 specified_file = image_spec_value (img->spec, QCfile, NULL);
7225 specified_data = image_spec_value (img->spec, QCdata, NULL);
7227 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
7228 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7230 if (NILP (specified_data))
7232 /* Read from a file */
7233 Lisp_Object file = x_find_image_file (specified_file);
7234 if (!STRINGP (file))
7236 image_error ("Cannot find image file `%s'", specified_file);
7237 return 0;
7240 Lisp_Object encoded_file = ENCODE_FILE (file);
7241 # ifdef WINDOWSNT
7242 encoded_file = ansi_encode_filename (encoded_file);
7243 # endif
7245 /* Try to open the image file. */
7246 tiff = TIFFOpen (SSDATA (encoded_file), "r");
7247 if (tiff == NULL)
7249 image_error ("Cannot open `%s'", file);
7250 return 0;
7253 else
7255 if (!STRINGP (specified_data))
7257 image_error ("Invalid image data `%s'", specified_data);
7258 return 0;
7261 /* Memory source! */
7262 memsrc.bytes = SDATA (specified_data);
7263 memsrc.len = SBYTES (specified_data);
7264 memsrc.index = 0;
7266 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7267 tiff_read_from_memory,
7268 tiff_write_from_memory,
7269 tiff_seek_in_memory,
7270 tiff_close_memory,
7271 tiff_size_of_memory,
7272 tiff_mmap_memory,
7273 tiff_unmap_memory);
7275 if (!tiff)
7277 image_error ("Cannot open memory source for `%s'", img->spec);
7278 return 0;
7282 image = image_spec_value (img->spec, QCindex, NULL);
7283 if (INTEGERP (image))
7285 EMACS_INT ino = XFASTINT (image);
7286 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7287 && TIFFSetDirectory (tiff, ino)))
7289 image_error ("Invalid image number `%s' in image `%s'",
7290 image, img->spec);
7291 TIFFClose (tiff);
7292 return 0;
7296 /* Get width and height of the image, and allocate a raster buffer
7297 of width x height 32-bit values. */
7298 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7299 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7301 if (!check_image_size (f, width, height))
7303 image_size_error ();
7304 TIFFClose (tiff);
7305 return 0;
7308 /* Create the X image and pixmap. */
7309 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7310 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7311 &ximg, 0)))
7313 TIFFClose (tiff);
7314 return 0;
7317 buf = xmalloc (sizeof *buf * width * height);
7319 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7321 /* Count the number of images in the file. */
7322 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7323 continue;
7325 if (count > 1)
7326 img->lisp_data = Fcons (Qcount,
7327 Fcons (make_number (count),
7328 img->lisp_data));
7330 TIFFClose (tiff);
7331 if (!rc)
7333 image_error ("Error reading TIFF image `%s'", img->spec);
7334 xfree (buf);
7335 return 0;
7338 #ifdef USE_CAIRO
7340 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
7341 uint32_t *dataptr = (uint32_t *) data;
7343 for (y = 0; y < height; ++y)
7345 uint32 *row = buf + (height - 1 - y) * width;
7346 for (x = 0; x < width; ++x)
7348 uint32 abgr = row[x];
7349 int r = TIFFGetR (abgr);
7350 int g = TIFFGetG (abgr);
7351 int b = TIFFGetB (abgr);
7352 int a = TIFFGetA (abgr);
7353 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
7357 create_cairo_image_surface (img, data, width, height);
7359 #else
7360 /* Initialize the color table. */
7361 init_color_table ();
7363 /* Process the pixel raster. Origin is in the lower-left corner. */
7364 for (y = 0; y < height; ++y)
7366 uint32 *row = buf + y * width;
7368 for (x = 0; x < width; ++x)
7370 uint32 abgr = row[x];
7371 int r = TIFFGetR (abgr) << 8;
7372 int g = TIFFGetG (abgr) << 8;
7373 int b = TIFFGetB (abgr) << 8;
7374 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7378 # ifdef COLOR_TABLE_SUPPORT
7379 /* Remember the colors allocated for the image. Free the color table. */
7380 img->colors = colors_in_color_table (&img->ncolors);
7381 free_color_table ();
7382 # endif /* COLOR_TABLE_SUPPORT */
7384 img->width = width;
7385 img->height = height;
7387 /* Maybe fill in the background field while we have ximg handy. */
7388 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7389 /* Casting avoids a GCC warning on W32. */
7390 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7392 /* Put ximg into the image. */
7393 image_put_x_image (f, img, ximg, 0);
7395 #endif /* ! USE_CAIRO */
7397 xfree (buf);
7398 return 1;
7401 #elif defined HAVE_NS
7403 static bool
7404 tiff_load (struct frame *f, struct image *img)
7406 return ns_load_image (f, img,
7407 image_spec_value (img->spec, QCfile, NULL),
7408 image_spec_value (img->spec, QCdata, NULL));
7411 #endif
7415 /***********************************************************************
7417 ***********************************************************************/
7419 #if defined (HAVE_GIF) || defined (HAVE_NS)
7421 static bool gif_image_p (Lisp_Object object);
7422 static bool gif_load (struct frame *f, struct image *img);
7423 static void gif_clear_image (struct frame *f, struct image *img);
7425 /* Indices of image specification fields in gif_format, below. */
7427 enum gif_keyword_index
7429 GIF_TYPE,
7430 GIF_DATA,
7431 GIF_FILE,
7432 GIF_ASCENT,
7433 GIF_MARGIN,
7434 GIF_RELIEF,
7435 GIF_ALGORITHM,
7436 GIF_HEURISTIC_MASK,
7437 GIF_MASK,
7438 GIF_IMAGE,
7439 GIF_BACKGROUND,
7440 GIF_LAST
7443 /* Vector of image_keyword structures describing the format
7444 of valid user-defined image specifications. */
7446 static const struct image_keyword gif_format[GIF_LAST] =
7448 {":type", IMAGE_SYMBOL_VALUE, 1},
7449 {":data", IMAGE_STRING_VALUE, 0},
7450 {":file", IMAGE_STRING_VALUE, 0},
7451 {":ascent", IMAGE_ASCENT_VALUE, 0},
7452 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7453 {":relief", IMAGE_INTEGER_VALUE, 0},
7454 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7455 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7456 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7457 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7458 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7461 #if defined HAVE_NTGUI && defined WINDOWSNT
7462 static bool init_gif_functions (void);
7463 #else
7464 #define init_gif_functions NULL
7465 #endif
7467 /* Structure describing the image type `gif'. */
7469 static struct image_type gif_type =
7471 SYMBOL_INDEX (Qgif),
7472 gif_image_p,
7473 gif_load,
7474 gif_clear_image,
7475 init_gif_functions,
7476 NULL
7479 /* Free X resources of GIF image IMG which is used on frame F. */
7481 static void
7482 gif_clear_image (struct frame *f, struct image *img)
7484 img->lisp_data = Qnil;
7485 x_clear_image (f, img);
7488 /* Return true if OBJECT is a valid GIF image specification. */
7490 static bool
7491 gif_image_p (Lisp_Object object)
7493 struct image_keyword fmt[GIF_LAST];
7494 memcpy (fmt, gif_format, sizeof fmt);
7496 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7497 return 0;
7499 /* Must specify either the :data or :file keyword. */
7500 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7503 #endif /* HAVE_GIF */
7505 #ifdef HAVE_GIF
7507 # ifdef HAVE_NTGUI
7509 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7510 Undefine before redefining to avoid a preprocessor warning. */
7511 # ifdef DrawText
7512 # undef DrawText
7513 # endif
7514 /* avoid conflict with QuickdrawText.h */
7515 # define DrawText gif_DrawText
7516 # include <gif_lib.h>
7517 /* The bogus ifdef below, which is always true, is to avoid a compiler
7518 warning about DrawText being unused. */
7519 # ifdef DrawText
7520 # undef DrawText
7521 # endif
7523 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7524 # ifndef GIFLIB_MINOR
7525 # define GIFLIB_MINOR 0
7526 # endif
7527 # ifndef GIFLIB_RELEASE
7528 # define GIFLIB_RELEASE 0
7529 # endif
7531 # else /* HAVE_NTGUI */
7533 # include <gif_lib.h>
7535 # endif /* HAVE_NTGUI */
7537 /* Giflib before 5.0 didn't define these macros. */
7538 # ifndef GIFLIB_MAJOR
7539 # define GIFLIB_MAJOR 4
7540 # endif
7542 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7543 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7544 earlier releases, where either it returns char * or GIFLIB_MINOR
7545 may be incorrect. */
7546 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7548 # ifdef WINDOWSNT
7550 /* GIF library details. */
7551 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7552 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7553 # else
7554 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7555 # endif
7556 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7557 # if GIFLIB_MAJOR < 5
7558 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7559 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7560 # else
7561 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7562 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7563 # endif
7564 # if HAVE_GIFERRORSTRING
7565 DEF_DLL_FN (char const *, GifErrorString, (int));
7566 # endif
7568 static bool
7569 init_gif_functions (void)
7571 HMODULE library;
7573 if (!(library = w32_delayed_load (Qgif)))
7574 return 0;
7576 LOAD_DLL_FN (library, DGifCloseFile);
7577 LOAD_DLL_FN (library, DGifSlurp);
7578 LOAD_DLL_FN (library, DGifOpen);
7579 LOAD_DLL_FN (library, DGifOpenFileName);
7580 # if HAVE_GIFERRORSTRING
7581 LOAD_DLL_FN (library, GifErrorString);
7582 # endif
7583 return 1;
7586 # undef DGifCloseFile
7587 # undef DGifOpen
7588 # undef DGifOpenFileName
7589 # undef DGifSlurp
7590 # undef GifErrorString
7592 # define DGifCloseFile fn_DGifCloseFile
7593 # define DGifOpen fn_DGifOpen
7594 # define DGifOpenFileName fn_DGifOpenFileName
7595 # define DGifSlurp fn_DGifSlurp
7596 # define GifErrorString fn_GifErrorString
7598 # endif /* WINDOWSNT */
7600 /* Reading a GIF image from memory
7601 Based on the PNG memory stuff to a certain extent. */
7603 typedef struct
7605 unsigned char *bytes;
7606 ptrdiff_t len;
7607 ptrdiff_t index;
7609 gif_memory_source;
7611 /* Make the current memory source available to gif_read_from_memory.
7612 It's done this way because not all versions of libungif support
7613 a UserData field in the GifFileType structure. */
7614 static gif_memory_source *current_gif_memory_src;
7616 static int
7617 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7619 gif_memory_source *src = current_gif_memory_src;
7621 if (len > src->len - src->index)
7622 return -1;
7624 memcpy (buf, src->bytes + src->index, len);
7625 src->index += len;
7626 return len;
7629 static int
7630 gif_close (GifFileType *gif, int *err)
7632 int retval;
7634 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7635 retval = DGifCloseFile (gif, err);
7636 #else
7637 retval = DGifCloseFile (gif);
7638 #if GIFLIB_MAJOR >= 5
7639 if (err)
7640 *err = gif->Error;
7641 #endif
7642 #endif
7643 return retval;
7646 /* Load GIF image IMG for use on frame F. Value is true if
7647 successful. */
7649 static const int interlace_start[] = {0, 4, 2, 1};
7650 static const int interlace_increment[] = {8, 8, 4, 2};
7652 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7654 static bool
7655 gif_load (struct frame *f, struct image *img)
7657 int rc, width, height, x, y, i, j;
7658 ColorMapObject *gif_color_map;
7659 GifFileType *gif;
7660 gif_memory_source memsrc;
7661 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7662 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7663 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7664 EMACS_INT idx;
7665 int gif_err;
7667 if (NILP (specified_data))
7669 Lisp_Object file = x_find_image_file (specified_file);
7670 if (!STRINGP (file))
7672 image_error ("Cannot find image file `%s'", specified_file);
7673 return 0;
7676 Lisp_Object encoded_file = ENCODE_FILE (file);
7677 #ifdef WINDOWSNT
7678 encoded_file = ansi_encode_filename (encoded_file);
7679 #endif
7681 /* Open the GIF file. */
7682 #if GIFLIB_MAJOR < 5
7683 gif = DGifOpenFileName (SSDATA (encoded_file));
7684 #else
7685 gif = DGifOpenFileName (SSDATA (encoded_file), &gif_err);
7686 #endif
7687 if (gif == NULL)
7689 #if HAVE_GIFERRORSTRING
7690 image_error ("Cannot open `%s': %s",
7691 file, build_string (GifErrorString (gif_err)));
7692 #else
7693 image_error ("Cannot open `%s'", file);
7694 #endif
7695 return 0;
7698 else
7700 if (!STRINGP (specified_data))
7702 image_error ("Invalid image data `%s'", specified_data);
7703 return 0;
7706 /* Read from memory! */
7707 current_gif_memory_src = &memsrc;
7708 memsrc.bytes = SDATA (specified_data);
7709 memsrc.len = SBYTES (specified_data);
7710 memsrc.index = 0;
7712 #if GIFLIB_MAJOR < 5
7713 gif = DGifOpen (&memsrc, gif_read_from_memory);
7714 #else
7715 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7716 #endif
7717 if (!gif)
7719 #if HAVE_GIFERRORSTRING
7720 image_error ("Cannot open memory source `%s': %s",
7721 img->spec, build_string (GifErrorString (gif_err)));
7722 #else
7723 image_error ("Cannot open memory source `%s'", img->spec);
7724 #endif
7725 return 0;
7729 /* Before reading entire contents, check the declared image size. */
7730 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7732 image_size_error ();
7733 gif_close (gif, NULL);
7734 return 0;
7737 /* Read entire contents. */
7738 rc = DGifSlurp (gif);
7739 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7741 image_error ("Error reading `%s'", img->spec);
7742 gif_close (gif, NULL);
7743 return 0;
7746 /* Which sub-image are we to display? */
7748 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7749 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7750 if (idx < 0 || idx >= gif->ImageCount)
7752 image_error ("Invalid image number `%s' in image `%s'",
7753 image_number, img->spec);
7754 gif_close (gif, NULL);
7755 return 0;
7759 width = img->width = gif->SWidth;
7760 height = img->height = gif->SHeight;
7762 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7763 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7764 img->corners[BOT_CORNER]
7765 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7766 img->corners[RIGHT_CORNER]
7767 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7769 if (!check_image_size (f, width, height))
7771 image_size_error ();
7772 gif_close (gif, NULL);
7773 return 0;
7776 /* Check that the selected subimages fit. It's not clear whether
7777 the GIF spec requires this, but Emacs can crash if they don't fit. */
7778 for (j = 0; j <= idx; ++j)
7780 struct SavedImage *subimage = gif->SavedImages + j;
7781 int subimg_width = subimage->ImageDesc.Width;
7782 int subimg_height = subimage->ImageDesc.Height;
7783 int subimg_top = subimage->ImageDesc.Top;
7784 int subimg_left = subimage->ImageDesc.Left;
7785 if (! (subimg_width >= 0 && subimg_height >= 0
7786 && 0 <= subimg_top && subimg_top <= height - subimg_height
7787 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7789 image_error ("Subimage does not fit in image");
7790 gif_close (gif, NULL);
7791 return 0;
7795 #ifdef USE_CAIRO
7796 /* xzalloc so data is zero => transparent */
7797 void *data = xzalloc (width * height * 4);
7798 uint32_t *data32 = data;
7799 if (STRINGP (specified_bg))
7801 XColor color;
7802 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
7804 uint32_t *dataptr = data32;
7805 int r = color.red/256;
7806 int g = color.green/256;
7807 int b = color.blue/256;
7809 for (y = 0; y < height; ++y)
7810 for (x = 0; x < width; ++x)
7811 *dataptr++ = (0xffu << 24) | (r << 16) | (g << 8) | b;
7814 #else
7815 /* Create the X image and pixmap. */
7816 XImagePtr ximg;
7817 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7819 gif_close (gif, NULL);
7820 return 0;
7823 /* Clear the part of the screen image not covered by the image.
7824 Full animated GIF support requires more here (see the gif89 spec,
7825 disposal methods). Let's simply assume that the part not covered
7826 by a sub-image is in the frame's background color. */
7827 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7828 for (x = 0; x < width; ++x)
7829 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7831 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7832 for (x = 0; x < width; ++x)
7833 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7835 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7837 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7838 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7839 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7840 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7842 #endif
7844 /* Read the GIF image into the X image. */
7846 /* FIXME: With the current implementation, loading an animated gif
7847 is quadratic in the number of animation frames, since each frame
7848 is a separate struct image. We must provide a way for a single
7849 gif_load call to construct and save all animation frames. */
7851 init_color_table ();
7853 #ifndef USE_CAIRO
7854 unsigned long bgcolor UNINIT;
7855 if (STRINGP (specified_bg))
7856 bgcolor = x_alloc_image_color (f, img, specified_bg,
7857 FRAME_BACKGROUND_PIXEL (f));
7858 #endif
7860 for (j = 0; j <= idx; ++j)
7862 /* We use a local variable `raster' here because RasterBits is a
7863 char *, which invites problems with bytes >= 0x80. */
7864 struct SavedImage *subimage = gif->SavedImages + j;
7865 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7866 int transparency_color_index = -1;
7867 int disposal = 0;
7868 int subimg_width = subimage->ImageDesc.Width;
7869 int subimg_height = subimage->ImageDesc.Height;
7870 int subimg_top = subimage->ImageDesc.Top;
7871 int subimg_left = subimage->ImageDesc.Left;
7873 /* Find the Graphic Control Extension block for this sub-image.
7874 Extract the disposal method and transparency color. */
7875 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7877 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7879 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7880 && extblock->ByteCount == 4
7881 && extblock->Bytes[0] & 1)
7883 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7884 to background". Treat any other value like 2. */
7885 disposal = (extblock->Bytes[0] >> 2) & 7;
7886 transparency_color_index = (unsigned char) extblock->Bytes[3];
7887 break;
7891 /* We can't "keep in place" the first subimage. */
7892 if (j == 0)
7893 disposal = 2;
7895 /* For disposal == 0, the spec says "No disposal specified. The
7896 decoder is not required to take any action." In practice, it
7897 seems we need to treat this like "keep in place", see e.g.
7898 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7899 if (disposal == 0)
7900 disposal = 1;
7902 gif_color_map = subimage->ImageDesc.ColorMap;
7903 if (!gif_color_map)
7904 gif_color_map = gif->SColorMap;
7906 #ifndef USE_CAIRO
7907 /* Allocate subimage colors. */
7908 unsigned long pixel_colors[256] = { 0, };
7910 if (gif_color_map)
7911 for (i = 0; i < gif_color_map->ColorCount; ++i)
7913 if (transparency_color_index == i)
7914 pixel_colors[i] = STRINGP (specified_bg)
7915 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7916 else
7918 int r = gif_color_map->Colors[i].Red << 8;
7919 int g = gif_color_map->Colors[i].Green << 8;
7920 int b = gif_color_map->Colors[i].Blue << 8;
7921 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7924 #endif
7926 /* Apply the pixel values. */
7927 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7929 int row, pass;
7931 for (y = 0, row = interlace_start[0], pass = 0;
7932 y < subimg_height;
7933 y++, row += interlace_increment[pass])
7935 while (subimg_height <= row)
7936 row = interlace_start[++pass];
7938 for (x = 0; x < subimg_width; x++)
7940 int c = raster[y * subimg_width + x];
7941 if (transparency_color_index != c || disposal != 1)
7943 #ifdef USE_CAIRO
7944 uint32_t *dataptr =
7945 (data32 + ((row + subimg_top) * subimg_width
7946 + x + subimg_left));
7947 int r = gif_color_map->Colors[c].Red;
7948 int g = gif_color_map->Colors[c].Green;
7949 int b = gif_color_map->Colors[c].Blue;
7951 if (transparency_color_index != c)
7952 *dataptr = (0xffu << 24) | (r << 16) | (g << 8) | b;
7953 #else
7954 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7955 pixel_colors[c]);
7956 #endif
7961 else
7963 for (y = 0; y < subimg_height; ++y)
7964 for (x = 0; x < subimg_width; ++x)
7966 int c = raster[y * subimg_width + x];
7967 if (transparency_color_index != c || disposal != 1)
7969 #ifdef USE_CAIRO
7970 uint32_t *dataptr =
7971 (data32 + ((y + subimg_top) * subimg_width
7972 + x + subimg_left));
7973 int r = gif_color_map->Colors[c].Red;
7974 int g = gif_color_map->Colors[c].Green;
7975 int b = gif_color_map->Colors[c].Blue;
7976 if (transparency_color_index != c)
7977 *dataptr = (0xffu << 24) | (r << 16) | (g << 8) | b;
7978 #else
7979 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7980 pixel_colors[c]);
7981 #endif
7987 #ifdef COLOR_TABLE_SUPPORT
7988 img->colors = colors_in_color_table (&img->ncolors);
7989 free_color_table ();
7990 #endif /* COLOR_TABLE_SUPPORT */
7992 /* Save GIF image extension data for `image-metadata'.
7993 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7994 img->lisp_data = Qnil;
7995 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7997 int delay = 0;
7998 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7999 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
8000 /* Append (... FUNCTION "BYTES") */
8002 img->lisp_data
8003 = Fcons (make_number (ext->Function),
8004 Fcons (make_unibyte_string ((char *) ext->Bytes,
8005 ext->ByteCount),
8006 img->lisp_data));
8007 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
8008 && ext->ByteCount == 4)
8010 delay = ext->Bytes[2] << CHAR_BIT;
8011 delay |= ext->Bytes[1];
8014 img->lisp_data = list2 (Qextension_data, img->lisp_data);
8015 if (delay)
8016 img->lisp_data
8017 = Fcons (Qdelay,
8018 Fcons (make_float (delay / 100.0),
8019 img->lisp_data));
8022 if (gif->ImageCount > 1)
8023 img->lisp_data = Fcons (Qcount,
8024 Fcons (make_number (gif->ImageCount),
8025 img->lisp_data));
8027 if (gif_close (gif, &gif_err) == GIF_ERROR)
8029 #if HAVE_GIFERRORSTRING
8030 char const *error_text = GifErrorString (gif_err);
8032 if (error_text)
8033 image_error ("Error closing `%s': %s",
8034 img->spec, build_string (error_text));
8035 #else
8036 image_error ("Error closing `%s'", img->spec);
8037 #endif
8040 #ifdef USE_CAIRO
8041 create_cairo_image_surface (img, data, width, height);
8042 #else
8043 /* Maybe fill in the background field while we have ximg handy. */
8044 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8045 /* Casting avoids a GCC warning. */
8046 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8048 /* Put ximg into the image. */
8049 image_put_x_image (f, img, ximg, 0);
8050 #endif
8052 return 1;
8055 #else /* !HAVE_GIF */
8057 #ifdef HAVE_NS
8058 static bool
8059 gif_load (struct frame *f, struct image *img)
8061 return ns_load_image (f, img,
8062 image_spec_value (img->spec, QCfile, NULL),
8063 image_spec_value (img->spec, QCdata, NULL));
8065 #endif /* HAVE_NS */
8067 #endif /* HAVE_GIF */
8070 #ifdef HAVE_IMAGEMAGICK
8072 /***********************************************************************
8073 ImageMagick
8074 ***********************************************************************/
8076 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8077 safely rounded and clipped to int range. */
8079 static int
8080 scale_image_size (int size, size_t divisor, size_t multiplier)
8082 if (divisor != 0)
8084 double s = size;
8085 double scaled = s * multiplier / divisor + 0.5;
8086 if (scaled < INT_MAX)
8087 return scaled;
8089 return INT_MAX;
8092 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8093 Use SPEC to deduce the size. Store the desired size into
8094 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8095 static void
8096 compute_image_size (size_t width, size_t height,
8097 Lisp_Object spec,
8098 int *d_width, int *d_height)
8100 Lisp_Object value;
8101 int desired_width = -1, desired_height = -1, max_width = -1, max_height = -1;
8102 double scale = 1;
8104 value = image_spec_value (spec, QCscale, NULL);
8105 if (NUMBERP (value))
8106 scale = XFLOATINT (value);
8108 value = image_spec_value (spec, QCmax_width, NULL);
8109 if (NATNUMP (value))
8110 max_width = min (XFASTINT (value), INT_MAX);
8112 value = image_spec_value (spec, QCmax_height, NULL);
8113 if (NATNUMP (value))
8114 max_height = min (XFASTINT (value), INT_MAX);
8116 /* If width and/or height is set in the display spec assume we want
8117 to scale to those values. If either h or w is unspecified, the
8118 unspecified should be calculated from the specified to preserve
8119 aspect ratio. */
8120 value = image_spec_value (spec, QCwidth, NULL);
8121 if (NATNUMP (value))
8123 desired_width = min (XFASTINT (value) * scale, INT_MAX);
8124 /* :width overrides :max-width. */
8125 max_width = -1;
8128 value = image_spec_value (spec, QCheight, NULL);
8129 if (NATNUMP (value))
8131 desired_height = min (XFASTINT (value) * scale, INT_MAX);
8132 /* :height overrides :max-height. */
8133 max_height = -1;
8136 /* If we have both width/height set explicitly, we skip past all the
8137 aspect ratio-preserving computations below. */
8138 if (desired_width != -1 && desired_height != -1)
8139 goto out;
8141 width = width * scale;
8142 height = height * scale;
8144 if (desired_width != -1)
8145 /* Width known, calculate height. */
8146 desired_height = scale_image_size (desired_width, width, height);
8147 else if (desired_height != -1)
8148 /* Height known, calculate width. */
8149 desired_width = scale_image_size (desired_height, height, width);
8150 else
8152 desired_width = width;
8153 desired_height = height;
8156 if (max_width != -1 && desired_width > max_width)
8158 /* The image is wider than :max-width. */
8159 desired_width = max_width;
8160 desired_height = scale_image_size (desired_width, width, height);
8163 if (max_height != -1 && desired_height > max_height)
8165 /* The image is higher than :max-height. */
8166 desired_height = max_height;
8167 desired_width = scale_image_size (desired_height, height, width);
8170 out:
8171 *d_width = desired_width;
8172 *d_height = desired_height;
8175 static bool imagemagick_image_p (Lisp_Object);
8176 static bool imagemagick_load (struct frame *, struct image *);
8177 static void imagemagick_clear_image (struct frame *, struct image *);
8179 /* Indices of image specification fields in imagemagick_format. */
8181 enum imagemagick_keyword_index
8183 IMAGEMAGICK_TYPE,
8184 IMAGEMAGICK_DATA,
8185 IMAGEMAGICK_FILE,
8186 IMAGEMAGICK_ASCENT,
8187 IMAGEMAGICK_MARGIN,
8188 IMAGEMAGICK_RELIEF,
8189 IMAGEMAGICK_ALGORITHM,
8190 IMAGEMAGICK_HEURISTIC_MASK,
8191 IMAGEMAGICK_MASK,
8192 IMAGEMAGICK_BACKGROUND,
8193 IMAGEMAGICK_HEIGHT,
8194 IMAGEMAGICK_WIDTH,
8195 IMAGEMAGICK_MAX_HEIGHT,
8196 IMAGEMAGICK_MAX_WIDTH,
8197 IMAGEMAGICK_FORMAT,
8198 IMAGEMAGICK_ROTATION,
8199 IMAGEMAGICK_CROP,
8200 IMAGEMAGICK_LAST
8203 /* Vector of image_keyword structures describing the format
8204 of valid user-defined image specifications. */
8206 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
8208 {":type", IMAGE_SYMBOL_VALUE, 1},
8209 {":data", IMAGE_STRING_VALUE, 0},
8210 {":file", IMAGE_STRING_VALUE, 0},
8211 {":ascent", IMAGE_ASCENT_VALUE, 0},
8212 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8213 {":relief", IMAGE_INTEGER_VALUE, 0},
8214 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8215 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8216 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8217 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8218 {":height", IMAGE_INTEGER_VALUE, 0},
8219 {":width", IMAGE_INTEGER_VALUE, 0},
8220 {":max-height", IMAGE_INTEGER_VALUE, 0},
8221 {":max-width", IMAGE_INTEGER_VALUE, 0},
8222 {":format", IMAGE_SYMBOL_VALUE, 0},
8223 {":rotation", IMAGE_NUMBER_VALUE, 0},
8224 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8227 #if defined HAVE_NTGUI && defined WINDOWSNT
8228 static bool init_imagemagick_functions (void);
8229 #else
8230 #define init_imagemagick_functions NULL
8231 #endif
8233 /* Structure describing the image type for any image handled via
8234 ImageMagick. */
8236 static struct image_type imagemagick_type =
8238 SYMBOL_INDEX (Qimagemagick),
8239 imagemagick_image_p,
8240 imagemagick_load,
8241 imagemagick_clear_image,
8242 init_imagemagick_functions,
8243 NULL
8246 /* Free X resources of imagemagick image IMG which is used on frame F. */
8248 static void
8249 imagemagick_clear_image (struct frame *f,
8250 struct image *img)
8252 x_clear_image (f, img);
8255 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8256 this by calling parse_image_spec and supplying the keywords that
8257 identify the IMAGEMAGICK format. */
8259 static bool
8260 imagemagick_image_p (Lisp_Object object)
8262 struct image_keyword fmt[IMAGEMAGICK_LAST];
8263 memcpy (fmt, imagemagick_format, sizeof fmt);
8265 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
8266 return 0;
8268 /* Must specify either the :data or :file keyword. */
8269 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
8272 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8273 Therefore rename the function so it doesn't collide with ImageMagick. */
8274 #define DrawRectangle DrawRectangleGif
8275 #include <wand/MagickWand.h>
8277 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8278 Emacs seems to work fine with the hidden version, so unhide it. */
8279 #include <magick/version.h>
8280 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8281 extern WandExport void PixelGetMagickColor (const PixelWand *,
8282 MagickPixelPacket *);
8283 #endif
8285 /* Log ImageMagick error message.
8286 Useful when an ImageMagick function returns the status `MagickFalse'. */
8288 static void
8289 imagemagick_error (MagickWand *wand)
8291 char *description;
8292 ExceptionType severity;
8294 description = MagickGetException (wand, &severity);
8295 image_error ("ImageMagick error: %s", build_string (description));
8296 MagickRelinquishMemory (description);
8299 /* Possibly give ImageMagick some extra help to determine the image
8300 type by supplying a "dummy" filename based on the Content-Type. */
8302 static char *
8303 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
8305 Lisp_Object symbol = intern ("image-format-suffixes");
8306 Lisp_Object val = find_symbol_value (symbol);
8307 Lisp_Object format;
8309 if (! CONSP (val))
8310 return NULL;
8312 format = image_spec_value (spec, intern (":format"), NULL);
8313 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
8314 if (! STRINGP (val))
8315 return NULL;
8317 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8318 as ImageMagick would ignore the extra bytes anyway. */
8319 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
8320 return hint_buffer;
8323 /* Animated images (e.g., GIF89a) are composed from one "master image"
8324 (which is the first one, and then there's a number of images that
8325 follow. If following images have non-transparent colors, these are
8326 composed "on top" of the master image. So, in general, one has to
8327 compute ann the preceding images to be able to display a particular
8328 sub-image.
8330 Computing all the preceding images is too slow, so we maintain a
8331 cache of previously computed images. We have to maintain a cache
8332 separate from the image cache, because the images may be scaled
8333 before display. */
8335 struct animation_cache
8337 MagickWand *wand;
8338 int index;
8339 struct timespec update_time;
8340 struct animation_cache *next;
8341 char signature[FLEXIBLE_ARRAY_MEMBER];
8344 static struct animation_cache *animation_cache = NULL;
8346 static struct animation_cache *
8347 imagemagick_create_cache (char *signature)
8349 struct animation_cache *cache
8350 = xmalloc (FLEXSIZEOF (struct animation_cache, signature,
8351 strlen (signature) + 1));
8352 cache->wand = 0;
8353 cache->index = 0;
8354 cache->next = 0;
8355 strcpy (cache->signature, signature);
8356 return cache;
8359 /* Discard cached images that haven't been used for a minute. */
8360 static void
8361 imagemagick_prune_animation_cache (void)
8363 struct animation_cache **pcache = &animation_cache;
8364 struct timespec old = timespec_sub (current_timespec (),
8365 make_timespec (60, 0));
8367 while (*pcache)
8369 struct animation_cache *cache = *pcache;
8370 if (timespec_cmp (old, cache->update_time) <= 0)
8371 pcache = &cache->next;
8372 else
8374 if (cache->wand)
8375 DestroyMagickWand (cache->wand);
8376 *pcache = cache->next;
8377 xfree (cache);
8382 static struct animation_cache *
8383 imagemagick_get_animation_cache (MagickWand *wand)
8385 char *signature = MagickGetImageSignature (wand);
8386 struct animation_cache *cache;
8387 struct animation_cache **pcache = &animation_cache;
8389 imagemagick_prune_animation_cache ();
8391 while (1)
8393 cache = *pcache;
8394 if (! cache)
8396 *pcache = cache = imagemagick_create_cache (signature);
8397 break;
8399 if (strcmp (signature, cache->signature) == 0)
8400 break;
8401 pcache = &cache->next;
8404 DestroyString (signature);
8405 cache->update_time = current_timespec ();
8406 return cache;
8409 static MagickWand *
8410 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8412 int i;
8413 MagickWand *composite_wand;
8414 size_t dest_width, dest_height;
8415 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8417 MagickSetIteratorIndex (super_wand, 0);
8419 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8421 composite_wand = MagickGetImage (super_wand);
8422 if (cache->wand)
8423 DestroyMagickWand (cache->wand);
8425 else
8426 composite_wand = cache->wand;
8428 dest_height = MagickGetImageHeight (composite_wand);
8430 for (i = max (1, cache->index + 1); i <= ino; i++)
8432 MagickWand *sub_wand;
8433 PixelIterator *source_iterator, *dest_iterator;
8434 PixelWand **source, **dest;
8435 size_t source_width, source_height;
8436 ssize_t source_left, source_top;
8437 MagickPixelPacket pixel;
8438 DisposeType dispose;
8439 ptrdiff_t lines = 0;
8441 MagickSetIteratorIndex (super_wand, i);
8442 sub_wand = MagickGetImage (super_wand);
8444 MagickGetImagePage (sub_wand, &source_width, &source_height,
8445 &source_left, &source_top);
8447 /* This flag says how to handle transparent pixels. */
8448 dispose = MagickGetImageDispose (sub_wand);
8450 source_iterator = NewPixelIterator (sub_wand);
8451 if (! source_iterator)
8453 DestroyMagickWand (composite_wand);
8454 DestroyMagickWand (sub_wand);
8455 cache->wand = NULL;
8456 image_error ("Imagemagick pixel iterator creation failed");
8457 return NULL;
8460 dest_iterator = NewPixelIterator (composite_wand);
8461 if (! dest_iterator)
8463 DestroyMagickWand (composite_wand);
8464 DestroyMagickWand (sub_wand);
8465 DestroyPixelIterator (source_iterator);
8466 cache->wand = NULL;
8467 image_error ("Imagemagick pixel iterator creation failed");
8468 return NULL;
8471 /* The sub-image may not start at origin, so move the destination
8472 iterator to where the sub-image should start. */
8473 if (source_top > 0)
8475 PixelSetIteratorRow (dest_iterator, source_top);
8476 lines = source_top;
8479 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8480 != NULL)
8482 ptrdiff_t x;
8484 /* Sanity check. This shouldn't happen, but apparently
8485 does in some pictures. */
8486 if (++lines >= dest_height)
8487 break;
8489 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8490 for (x = 0; x < source_width; x++)
8492 /* Sanity check. This shouldn't happen, but apparently
8493 also does in some pictures. */
8494 if (x + source_left >= dest_width)
8495 break;
8496 /* Normally we only copy over non-transparent pixels,
8497 but if the disposal method is "Background", then we
8498 copy over all pixels. */
8499 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8501 PixelGetMagickColor (source[x], &pixel);
8502 PixelSetMagickColor (dest[x + source_left], &pixel);
8505 PixelSyncIterator (dest_iterator);
8508 DestroyPixelIterator (source_iterator);
8509 DestroyPixelIterator (dest_iterator);
8510 DestroyMagickWand (sub_wand);
8513 /* Cache a copy for the next iteration. The current wand will be
8514 destroyed by the caller. */
8515 cache->wand = CloneMagickWand (composite_wand);
8516 cache->index = ino;
8518 return composite_wand;
8522 /* Helper function for imagemagick_load, which does the actual loading
8523 given contents and size, apart from frame and image structures,
8524 passed from imagemagick_load. Uses librimagemagick to do most of
8525 the image processing.
8527 F is a pointer to the Emacs frame; IMG to the image structure to
8528 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8529 be parsed; SIZE is the number of bytes of data; and FILENAME is
8530 either the file name or the image data.
8532 Return true if successful. */
8534 static bool
8535 imagemagick_load_image (struct frame *f, struct image *img,
8536 unsigned char *contents, unsigned int size,
8537 char *filename)
8539 int width, height;
8540 size_t image_width, image_height;
8541 MagickBooleanType status;
8542 #ifndef USE_CAIRO
8543 XImagePtr ximg;
8544 #endif
8545 int x, y;
8546 MagickWand *image_wand;
8547 PixelIterator *iterator;
8548 PixelWand **pixels, *bg_wand = NULL;
8549 MagickPixelPacket pixel;
8550 Lisp_Object image;
8551 Lisp_Object value;
8552 Lisp_Object crop;
8553 EMACS_INT ino;
8554 int desired_width, desired_height;
8555 double rotation;
8556 char hint_buffer[MaxTextExtent];
8557 char *filename_hint = NULL;
8558 #ifdef USE_CAIRO
8559 void *data = NULL;
8560 #endif
8562 /* Initialize the ImageMagick environment. */
8563 static bool imagemagick_initialized;
8564 if (!imagemagick_initialized)
8566 imagemagick_initialized = true;
8567 MagickWandGenesis ();
8570 /* Handle image index for image types who can contain more than one image.
8571 Interface :index is same as for GIF. First we "ping" the image to see how
8572 many sub-images it contains. Pinging is faster than loading the image to
8573 find out things about it. */
8575 image = image_spec_value (img->spec, QCindex, NULL);
8576 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8577 image_wand = NewMagickWand ();
8579 if (filename)
8580 status = MagickReadImage (image_wand, filename);
8581 else
8583 Lisp_Object lwidth = image_spec_value (img->spec, QCwidth, NULL);
8584 Lisp_Object lheight = image_spec_value (img->spec, QCheight, NULL);
8586 if (NATNUMP (lwidth) && NATNUMP (lheight))
8588 MagickSetSize (image_wand, XFASTINT (lwidth), XFASTINT (lheight));
8589 MagickSetDepth (image_wand, 8);
8591 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8592 MagickSetFilename (image_wand, filename_hint);
8593 status = MagickReadImageBlob (image_wand, contents, size);
8596 if (status == MagickFalse)
8598 imagemagick_error (image_wand);
8599 DestroyMagickWand (image_wand);
8600 return 0;
8603 #ifdef HAVE_MAGICKAUTOORIENTIMAGE
8604 /* If no :rotation is explicitly specified, apply the automatic
8605 rotation from EXIF. */
8606 if (NILP (image_spec_value (img->spec, QCrotation, NULL)))
8607 if (MagickAutoOrientImage (image_wand) == MagickFalse)
8609 image_error ("Error applying automatic orientation in image `%s'", img->spec);
8610 DestroyMagickWand (image_wand);
8611 return 0;
8613 #endif
8615 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8617 image_error ("Invalid image number `%s' in image `%s'", image, img->spec);
8618 DestroyMagickWand (image_wand);
8619 return 0;
8622 if (MagickGetImageDelay (image_wand) > 0)
8623 img->lisp_data =
8624 Fcons (Qdelay,
8625 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8626 img->lisp_data));
8628 if (MagickGetNumberImages (image_wand) > 1)
8629 img->lisp_data =
8630 Fcons (Qcount,
8631 Fcons (make_number (MagickGetNumberImages (image_wand)),
8632 img->lisp_data));
8634 /* If we have an animated image, get the new wand based on the
8635 "super-wand". */
8636 if (MagickGetNumberImages (image_wand) > 1)
8638 MagickWand *super_wand = image_wand;
8639 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8640 if (! image_wand)
8641 image_wand = super_wand;
8642 else
8643 DestroyMagickWand (super_wand);
8646 /* Retrieve the frame's background color, for use later. */
8648 XColor bgcolor;
8649 Lisp_Object specified_bg;
8651 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8652 if (!STRINGP (specified_bg)
8653 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8654 x_query_frame_background_color (f, &bgcolor);
8656 bg_wand = NewPixelWand ();
8657 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8658 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8659 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8662 compute_image_size (MagickGetImageWidth (image_wand),
8663 MagickGetImageHeight (image_wand),
8664 img->spec, &desired_width, &desired_height);
8666 if (desired_width != -1 && desired_height != -1)
8668 status = MagickScaleImage (image_wand, desired_width, desired_height);
8669 if (status == MagickFalse)
8671 image_error ("Imagemagick scale failed");
8672 imagemagick_error (image_wand);
8673 goto imagemagick_error;
8677 /* crop behaves similar to image slicing in Emacs but is more memory
8678 efficient. */
8679 crop = image_spec_value (img->spec, QCcrop, NULL);
8681 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8683 /* After some testing, it seems MagickCropImage is the fastest crop
8684 function in ImageMagick. This crop function seems to do less copying
8685 than the alternatives, but it still reads the entire image into memory
8686 before cropping, which is apparently difficult to avoid when using
8687 imagemagick. */
8688 size_t crop_width = XINT (XCAR (crop));
8689 crop = XCDR (crop);
8690 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8692 size_t crop_height = XINT (XCAR (crop));
8693 crop = XCDR (crop);
8694 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8696 ssize_t crop_x = XINT (XCAR (crop));
8697 crop = XCDR (crop);
8698 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8700 ssize_t crop_y = XINT (XCAR (crop));
8701 MagickCropImage (image_wand, crop_width, crop_height,
8702 crop_x, crop_y);
8708 /* Furthermore :rotation. we need background color and angle for
8709 rotation. */
8711 TODO background handling for rotation specified_bg =
8712 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8713 (specified_bg). */
8714 value = image_spec_value (img->spec, QCrotation, NULL);
8715 if (FLOATP (value))
8717 rotation = XFLOAT_DATA (value);
8718 status = MagickRotateImage (image_wand, bg_wand, rotation);
8719 if (status == MagickFalse)
8721 image_error ("Imagemagick image rotate failed");
8722 imagemagick_error (image_wand);
8723 goto imagemagick_error;
8727 /* Set the canvas background color to the frame or specified
8728 background, and flatten the image. Note: as of ImageMagick
8729 6.6.0, SVG image transparency is not handled properly
8730 (e.g. etc/images/splash.svg shows a white background always). */
8732 MagickWand *new_wand;
8733 MagickSetImageBackgroundColor (image_wand, bg_wand);
8734 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8735 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8736 #else
8737 new_wand = MagickFlattenImages (image_wand);
8738 #endif
8739 DestroyMagickWand (image_wand);
8740 image_wand = new_wand;
8743 /* Finally we are done manipulating the image. Figure out the
8744 resulting width/height and transfer ownership to Emacs. */
8745 image_height = MagickGetImageHeight (image_wand);
8746 image_width = MagickGetImageWidth (image_wand);
8748 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8749 && check_image_size (f, image_width, image_height)))
8751 image_size_error ();
8752 goto imagemagick_error;
8755 width = image_width;
8756 height = image_height;
8758 /* We can now get a valid pixel buffer from the imagemagick file, if all
8759 went ok. */
8761 init_color_table ();
8763 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8764 if (imagemagick_render_type != 0)
8766 /* Magicexportimage is normally faster than pixelpushing. This
8767 method is also well tested. Some aspects of this method are
8768 ad-hoc and needs to be more researched. */
8769 void *dataptr;
8770 #ifdef USE_CAIRO
8771 data = xmalloc (width * height * 4);
8772 const char *exportdepth = "BGRA";
8773 dataptr = data;
8774 #else
8775 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8776 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8777 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8778 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8779 &ximg, 0))
8781 #ifdef COLOR_TABLE_SUPPORT
8782 free_color_table ();
8783 #endif
8784 image_error ("Imagemagick X bitmap allocation failure");
8785 goto imagemagick_error;
8787 dataptr = ximg->data;
8788 #endif /* not USE_CAIRO */
8790 /* Oddly, the below code doesn't seem to work:*/
8791 /* switch(ximg->bitmap_unit){ */
8792 /* case 8: */
8793 /* pixelwidth=CharPixel; */
8794 /* break; */
8795 /* case 16: */
8796 /* pixelwidth=ShortPixel; */
8797 /* break; */
8798 /* case 32: */
8799 /* pixelwidth=LongPixel; */
8800 /* break; */
8801 /* } */
8803 Here im just guessing the format of the bitmap.
8804 happens to work fine for:
8805 - bw djvu images
8806 on rgb display.
8807 seems about 3 times as fast as pixel pushing(not carefully measured)
8809 int pixelwidth = CharPixel; /*??? TODO figure out*/
8810 MagickExportImagePixels (image_wand, 0, 0, width, height,
8811 exportdepth, pixelwidth, dataptr);
8813 else
8814 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8816 size_t image_height;
8817 MagickRealType color_scale = 65535.0 / QuantumRange;
8818 #ifdef USE_CAIRO
8819 data = xmalloc (width * height * 4);
8820 color_scale /= 256;
8821 #else
8822 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8823 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8824 &ximg, 0))
8826 #ifdef COLOR_TABLE_SUPPORT
8827 free_color_table ();
8828 #endif
8829 image_error ("Imagemagick X bitmap allocation failure");
8830 goto imagemagick_error;
8832 #endif
8834 /* Copy imagemagick image to x with primitive yet robust pixel
8835 pusher loop. This has been tested a lot with many different
8836 images. */
8838 /* Copy pixels from the imagemagick image structure to the x image map. */
8839 iterator = NewPixelIterator (image_wand);
8840 if (! iterator)
8842 #ifdef COLOR_TABLE_SUPPORT
8843 free_color_table ();
8844 #endif
8845 #ifndef USE_CAIRO
8846 x_destroy_x_image (ximg);
8847 #endif
8848 image_error ("Imagemagick pixel iterator creation failed");
8849 goto imagemagick_error;
8852 image_height = MagickGetImageHeight (image_wand);
8853 for (y = 0; y < image_height; y++)
8855 size_t row_width;
8856 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8857 if (! pixels)
8858 break;
8859 int xlim = min (row_width, width);
8860 for (x = 0; x < xlim; x++)
8862 PixelGetMagickColor (pixels[x], &pixel);
8863 #ifdef USE_CAIRO
8864 ((uint32_t *)data)[width * y + x] =
8865 lookup_rgb_color (f,
8866 color_scale * pixel.red,
8867 color_scale * pixel.green,
8868 color_scale * pixel.blue);
8869 #else
8870 XPutPixel (ximg, x, y,
8871 lookup_rgb_color (f,
8872 color_scale * pixel.red,
8873 color_scale * pixel.green,
8874 color_scale * pixel.blue));
8875 #endif
8878 DestroyPixelIterator (iterator);
8881 #ifdef USE_CAIRO
8882 create_cairo_image_surface (img, data, width, height);
8883 #else
8884 #ifdef COLOR_TABLE_SUPPORT
8885 /* Remember colors allocated for this image. */
8886 img->colors = colors_in_color_table (&img->ncolors);
8887 free_color_table ();
8888 #endif /* COLOR_TABLE_SUPPORT */
8890 img->width = width;
8891 img->height = height;
8893 /* Put ximg into the image. */
8894 image_put_x_image (f, img, ximg, 0);
8895 #endif
8897 /* Final cleanup. image_wand should be the only resource left. */
8898 DestroyMagickWand (image_wand);
8899 if (bg_wand) DestroyPixelWand (bg_wand);
8901 /* Do not call MagickWandTerminus, to work around ImageMagick bug 825. See:
8902 https://github.com/ImageMagick/ImageMagick/issues/825
8903 Although this bug was introduced in ImageMagick 6.9.9-14 and
8904 fixed in 6.9.9-18, it's simpler to work around it in all versions. */
8906 return 1;
8908 imagemagick_error:
8909 DestroyMagickWand (image_wand);
8910 if (bg_wand) DestroyPixelWand (bg_wand);
8912 /* TODO more cleanup. */
8913 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec);
8914 return 0;
8918 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8919 successful. this function will go into the imagemagick_type structure, and
8920 the prototype thus needs to be compatible with that structure. */
8922 static bool
8923 imagemagick_load (struct frame *f, struct image *img)
8925 bool success_p = 0;
8926 Lisp_Object file_name;
8928 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8929 file_name = image_spec_value (img->spec, QCfile, NULL);
8930 if (STRINGP (file_name))
8932 Lisp_Object file = x_find_image_file (file_name);
8933 if (!STRINGP (file))
8935 image_error ("Cannot find image file `%s'", file_name);
8936 return 0;
8938 file = ENCODE_FILE (file);
8939 #ifdef WINDOWSNT
8940 file = ansi_encode_filename (file);
8941 #endif
8942 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8944 /* Else its not a file, its a lisp object. Load the image from a
8945 lisp object rather than a file. */
8946 else
8948 Lisp_Object data;
8950 data = image_spec_value (img->spec, QCdata, NULL);
8951 if (!STRINGP (data))
8953 image_error ("Invalid image data `%s'", data);
8954 return 0;
8956 success_p = imagemagick_load_image (f, img, SDATA (data),
8957 SBYTES (data), NULL);
8960 return success_p;
8963 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8964 doc: /* Return a list of image types supported by ImageMagick.
8965 Each entry in this list is a symbol named after an ImageMagick format
8966 tag. See the ImageMagick manual for a list of ImageMagick formats and
8967 their descriptions (http://www.imagemagick.org/script/formats.php).
8968 You can also try the shell command: `identify -list format'.
8970 Note that ImageMagick recognizes many file-types that Emacs does not
8971 recognize as images, such as C. See `imagemagick-enabled-types'
8972 and `imagemagick-types-inhibit'. */)
8973 (void)
8975 Lisp_Object typelist = Qnil;
8976 size_t numf = 0;
8977 ExceptionInfo *ex;
8978 char **imtypes;
8979 size_t i;
8981 ex = AcquireExceptionInfo ();
8982 imtypes = GetMagickList ("*", &numf, ex);
8983 DestroyExceptionInfo (ex);
8985 for (i = 0; i < numf; i++)
8987 Lisp_Object imagemagicktype = intern (imtypes[i]);
8988 typelist = Fcons (imagemagicktype, typelist);
8989 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8992 MagickRelinquishMemory (imtypes);
8993 return Fnreverse (typelist);
8996 #endif /* defined (HAVE_IMAGEMAGICK) */
9000 /***********************************************************************
9002 ***********************************************************************/
9004 #ifdef HAVE_RSVG
9006 /* Function prototypes. */
9008 static bool svg_image_p (Lisp_Object object);
9009 static bool svg_load (struct frame *f, struct image *img);
9011 static bool svg_load_image (struct frame *, struct image *,
9012 char *, ptrdiff_t, char *);
9014 /* Indices of image specification fields in svg_format, below. */
9016 enum svg_keyword_index
9018 SVG_TYPE,
9019 SVG_DATA,
9020 SVG_FILE,
9021 SVG_ASCENT,
9022 SVG_MARGIN,
9023 SVG_RELIEF,
9024 SVG_ALGORITHM,
9025 SVG_HEURISTIC_MASK,
9026 SVG_MASK,
9027 SVG_BACKGROUND,
9028 SVG_LAST
9031 /* Vector of image_keyword structures describing the format
9032 of valid user-defined image specifications. */
9034 static const struct image_keyword svg_format[SVG_LAST] =
9036 {":type", IMAGE_SYMBOL_VALUE, 1},
9037 {":data", IMAGE_STRING_VALUE, 0},
9038 {":file", IMAGE_STRING_VALUE, 0},
9039 {":ascent", IMAGE_ASCENT_VALUE, 0},
9040 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9041 {":relief", IMAGE_INTEGER_VALUE, 0},
9042 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9043 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9044 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9045 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9048 # if defined HAVE_NTGUI && defined WINDOWSNT
9049 static bool init_svg_functions (void);
9050 # else
9051 #define init_svg_functions NULL
9052 # endif
9054 /* Structure describing the image type `svg'. Its the same type of
9055 structure defined for all image formats, handled by emacs image
9056 functions. See struct image_type in dispextern.h. */
9058 static struct image_type svg_type =
9060 SYMBOL_INDEX (Qsvg),
9061 svg_image_p,
9062 svg_load,
9063 x_clear_image,
9064 init_svg_functions,
9065 NULL
9069 /* Return true if OBJECT is a valid SVG image specification. Do
9070 this by calling parse_image_spec and supplying the keywords that
9071 identify the SVG format. */
9073 static bool
9074 svg_image_p (Lisp_Object object)
9076 struct image_keyword fmt[SVG_LAST];
9077 memcpy (fmt, svg_format, sizeof fmt);
9079 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
9080 return 0;
9082 /* Must specify either the :data or :file keyword. */
9083 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
9086 /* Some versions of glib's gatomic.h define MemoryBarrier, but MinGW
9087 w32api 3.18 and later has its own definition. The following gross
9088 hack avoids the clash. */
9089 # ifdef WINDOWSNT
9090 # if (__W32API_MAJOR_VERSION + (__W32API_MINOR_VERSION >= 18)) >= 4
9091 # define W32_SAVE_MINGW_VERSION __MINGW_MAJOR_VERSION
9092 # undef __MINGW_MAJOR_VERSION
9093 # define __MINGW_MAJOR_VERSION 4
9094 # endif
9095 # endif
9097 # include <librsvg/rsvg.h>
9099 # ifdef WINDOWSNT
9101 /* Restore the original definition of __MINGW_MAJOR_VERSION. */
9102 # ifdef W32_SAVE_MINGW_VERSION
9103 # undef __MINGW_MAJOR_VERSION
9104 # define __MINGW_MAJOR_VERSION W32_SAVE_MINGW_VERSION
9105 # ifdef __MINGW_MAJOR_VERSION
9106 # undef W32_SAVE_MINGW_VERSION
9107 # endif
9108 # endif
9110 /* SVG library functions. */
9111 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
9112 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
9113 (RsvgHandle *, RsvgDimensionData *));
9114 DEF_DLL_FN (gboolean, rsvg_handle_write,
9115 (RsvgHandle *, const guchar *, gsize, GError **));
9116 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
9117 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
9118 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
9120 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
9121 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
9122 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
9123 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
9124 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
9125 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
9126 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
9127 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
9129 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9130 DEF_DLL_FN (void, g_type_init, (void));
9131 # endif
9132 DEF_DLL_FN (void, g_object_unref, (gpointer));
9133 DEF_DLL_FN (void, g_clear_error, (GError **));
9135 static bool
9136 init_svg_functions (void)
9138 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
9140 if (!(glib = w32_delayed_load (Qglib))
9141 || !(gobject = w32_delayed_load (Qgobject))
9142 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
9143 || !(library = w32_delayed_load (Qsvg)))
9145 if (gdklib) FreeLibrary (gdklib);
9146 if (gobject) FreeLibrary (gobject);
9147 if (glib) FreeLibrary (glib);
9148 return 0;
9151 LOAD_DLL_FN (library, rsvg_handle_new);
9152 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
9153 LOAD_DLL_FN (library, rsvg_handle_write);
9154 LOAD_DLL_FN (library, rsvg_handle_close);
9155 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
9156 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
9158 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
9159 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
9160 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
9161 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
9162 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
9163 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
9164 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
9165 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
9167 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9168 LOAD_DLL_FN (gobject, g_type_init);
9169 # endif
9170 LOAD_DLL_FN (gobject, g_object_unref);
9171 LOAD_DLL_FN (glib, g_clear_error);
9173 return 1;
9176 /* The following aliases for library functions allow dynamic loading
9177 to be used on some platforms. */
9179 # undef gdk_pixbuf_get_bits_per_sample
9180 # undef gdk_pixbuf_get_colorspace
9181 # undef gdk_pixbuf_get_has_alpha
9182 # undef gdk_pixbuf_get_height
9183 # undef gdk_pixbuf_get_n_channels
9184 # undef gdk_pixbuf_get_pixels
9185 # undef gdk_pixbuf_get_rowstride
9186 # undef gdk_pixbuf_get_width
9187 # undef g_clear_error
9188 # undef g_object_unref
9189 # undef g_type_init
9190 # undef rsvg_handle_close
9191 # undef rsvg_handle_get_dimensions
9192 # undef rsvg_handle_get_pixbuf
9193 # undef rsvg_handle_new
9194 # undef rsvg_handle_set_base_uri
9195 # undef rsvg_handle_write
9197 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9198 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9199 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9200 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9201 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9202 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9203 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9204 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9205 # define g_clear_error fn_g_clear_error
9206 # define g_object_unref fn_g_object_unref
9207 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9208 # define g_type_init fn_g_type_init
9209 # endif
9210 # define rsvg_handle_close fn_rsvg_handle_close
9211 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9212 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9213 # define rsvg_handle_new fn_rsvg_handle_new
9214 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9215 # define rsvg_handle_write fn_rsvg_handle_write
9217 # endif /* !WINDOWSNT */
9219 /* Load SVG image IMG for use on frame F. Value is true if
9220 successful. */
9222 static bool
9223 svg_load (struct frame *f, struct image *img)
9225 bool success_p = 0;
9226 Lisp_Object file_name;
9228 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9229 file_name = image_spec_value (img->spec, QCfile, NULL);
9230 if (STRINGP (file_name))
9232 int fd;
9233 Lisp_Object file = x_find_image_fd (file_name, &fd);
9234 if (!STRINGP (file))
9236 image_error ("Cannot find image file `%s'", file_name);
9237 return 0;
9240 /* Read the entire file into memory. */
9241 ptrdiff_t size;
9242 char *contents = slurp_file (fd, &size);
9243 if (contents == NULL)
9245 image_error ("Error loading SVG image `%s'", file);
9246 return 0;
9248 /* If the file was slurped into memory properly, parse it. */
9249 success_p = svg_load_image (f, img, contents, size,
9250 SSDATA (ENCODE_FILE (file)));
9251 xfree (contents);
9253 /* Else its not a file, its a lisp object. Load the image from a
9254 lisp object rather than a file. */
9255 else
9257 Lisp_Object data, original_filename;
9259 data = image_spec_value (img->spec, QCdata, NULL);
9260 if (!STRINGP (data))
9262 image_error ("Invalid image data `%s'", data);
9263 return 0;
9265 original_filename = BVAR (current_buffer, filename);
9266 success_p = svg_load_image (f, img, SSDATA (data), SBYTES (data),
9267 (NILP (original_filename) ? NULL
9268 : SSDATA (original_filename)));
9271 return success_p;
9274 /* Load frame F and image IMG. CONTENTS contains the SVG XML data to
9275 be parsed, SIZE is its size, and FILENAME is the name of the SVG
9276 file being loaded.
9278 Use librsvg to do most of the image processing.
9280 Return true when successful. */
9281 static bool
9282 svg_load_image (struct frame *f, struct image *img, char *contents,
9283 ptrdiff_t size, char *filename)
9285 RsvgHandle *rsvg_handle;
9286 RsvgDimensionData dimension_data;
9287 GError *err = NULL;
9288 GdkPixbuf *pixbuf;
9289 int width;
9290 int height;
9291 const guint8 *pixels;
9292 int rowstride;
9294 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9295 /* g_type_init is a glib function that must be called prior to
9296 using gnome type library functions (obsolete since 2.36.0). */
9297 g_type_init ();
9298 #endif
9300 /* Make a handle to a new rsvg object. */
9301 rsvg_handle = rsvg_handle_new ();
9303 /* Set base_uri for properly handling referenced images (via 'href').
9304 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9305 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9306 if (filename)
9307 rsvg_handle_set_base_uri(rsvg_handle, filename);
9309 /* Parse the contents argument and fill in the rsvg_handle. */
9310 rsvg_handle_write (rsvg_handle, (unsigned char *) contents, size, &err);
9311 if (err) goto rsvg_error;
9313 /* The parsing is complete, rsvg_handle is ready to used, close it
9314 for further writes. */
9315 rsvg_handle_close (rsvg_handle, &err);
9316 if (err) goto rsvg_error;
9318 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
9319 if (! check_image_size (f, dimension_data.width, dimension_data.height))
9321 image_size_error ();
9322 goto rsvg_error;
9325 /* We can now get a valid pixel buffer from the svg file, if all
9326 went ok. */
9327 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
9328 if (!pixbuf) goto rsvg_error;
9329 g_object_unref (rsvg_handle);
9331 /* Extract some meta data from the svg handle. */
9332 width = gdk_pixbuf_get_width (pixbuf);
9333 height = gdk_pixbuf_get_height (pixbuf);
9334 pixels = gdk_pixbuf_get_pixels (pixbuf);
9335 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
9337 /* Validate the svg meta data. */
9338 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
9339 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
9340 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
9341 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
9344 #ifdef USE_CAIRO
9345 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
9346 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
9348 for (int y = 0; y < height; ++y)
9350 const guchar *iconptr = pixels + y * rowstride;
9351 uint32_t *dataptr = (uint32_t *) (data + y * rowstride);
9353 for (int x = 0; x < width; ++x)
9355 if (iconptr[3] == 0)
9356 *dataptr = bgcolor;
9357 else
9358 *dataptr = (iconptr[0] << 16)
9359 | (iconptr[1] << 8)
9360 | iconptr[2]
9361 | (iconptr[3] << 24);
9363 iconptr += 4;
9364 ++dataptr;
9368 create_cairo_image_surface (img, data, width, height);
9369 g_object_unref (pixbuf);
9370 #else
9371 /* Try to create a x pixmap to hold the svg pixmap. */
9372 XImagePtr ximg;
9373 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
9375 g_object_unref (pixbuf);
9376 return 0;
9379 init_color_table ();
9381 /* Handle alpha channel by combining the image with a background
9382 color. */
9383 XColor background;
9384 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
9385 if (!STRINGP (specified_bg)
9386 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
9387 x_query_frame_background_color (f, &background);
9389 /* SVG pixmaps specify transparency in the last byte, so right
9390 shift 8 bits to get rid of it, since emacs doesn't support
9391 transparency. */
9392 background.red >>= 8;
9393 background.green >>= 8;
9394 background.blue >>= 8;
9396 /* This loop handles opacity values, since Emacs assumes
9397 non-transparent images. Each pixel must be "flattened" by
9398 calculating the resulting color, given the transparency of the
9399 pixel, and the image background color. */
9400 for (int y = 0; y < height; ++y)
9402 for (int x = 0; x < width; ++x)
9404 int red = *pixels++;
9405 int green = *pixels++;
9406 int blue = *pixels++;
9407 int opacity = *pixels++;
9409 red = ((red * opacity)
9410 + (background.red * ((1 << 8) - opacity)));
9411 green = ((green * opacity)
9412 + (background.green * ((1 << 8) - opacity)));
9413 blue = ((blue * opacity)
9414 + (background.blue * ((1 << 8) - opacity)));
9416 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9419 pixels += rowstride - 4 * width;
9422 #ifdef COLOR_TABLE_SUPPORT
9423 /* Remember colors allocated for this image. */
9424 img->colors = colors_in_color_table (&img->ncolors);
9425 free_color_table ();
9426 #endif /* COLOR_TABLE_SUPPORT */
9428 g_object_unref (pixbuf);
9430 img->width = width;
9431 img->height = height;
9433 /* Maybe fill in the background field while we have ximg handy.
9434 Casting avoids a GCC warning. */
9435 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9437 /* Put ximg into the image. */
9438 image_put_x_image (f, img, ximg, 0);
9439 #endif /* ! USE_CAIRO */
9442 return 1;
9444 rsvg_error:
9445 g_object_unref (rsvg_handle);
9446 /* FIXME: Use error->message so the user knows what is the actual
9447 problem with the image. */
9448 image_error ("Error parsing SVG image `%s'", img->spec);
9449 g_clear_error (&err);
9450 return 0;
9453 #endif /* defined (HAVE_RSVG) */
9458 /***********************************************************************
9459 Ghostscript
9460 ***********************************************************************/
9462 #ifdef HAVE_X_WINDOWS
9463 #define HAVE_GHOSTSCRIPT 1
9464 #endif /* HAVE_X_WINDOWS */
9466 #ifdef HAVE_GHOSTSCRIPT
9468 static bool gs_image_p (Lisp_Object object);
9469 static bool gs_load (struct frame *f, struct image *img);
9470 static void gs_clear_image (struct frame *f, struct image *img);
9472 /* Indices of image specification fields in gs_format, below. */
9474 enum gs_keyword_index
9476 GS_TYPE,
9477 GS_PT_WIDTH,
9478 GS_PT_HEIGHT,
9479 GS_FILE,
9480 GS_LOADER,
9481 GS_BOUNDING_BOX,
9482 GS_ASCENT,
9483 GS_MARGIN,
9484 GS_RELIEF,
9485 GS_ALGORITHM,
9486 GS_HEURISTIC_MASK,
9487 GS_MASK,
9488 GS_BACKGROUND,
9489 GS_LAST
9492 /* Vector of image_keyword structures describing the format
9493 of valid user-defined image specifications. */
9495 static const struct image_keyword gs_format[GS_LAST] =
9497 {":type", IMAGE_SYMBOL_VALUE, 1},
9498 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9499 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9500 {":file", IMAGE_STRING_VALUE, 1},
9501 {":loader", IMAGE_FUNCTION_VALUE, 0},
9502 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9503 {":ascent", IMAGE_ASCENT_VALUE, 0},
9504 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9505 {":relief", IMAGE_INTEGER_VALUE, 0},
9506 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9507 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9508 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9509 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9512 /* Structure describing the image type `ghostscript'. */
9514 static struct image_type gs_type =
9516 SYMBOL_INDEX (Qpostscript),
9517 gs_image_p,
9518 gs_load,
9519 gs_clear_image,
9520 NULL,
9521 NULL
9525 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9527 static void
9528 gs_clear_image (struct frame *f, struct image *img)
9530 x_clear_image (f, img);
9534 /* Return true if OBJECT is a valid Ghostscript image
9535 specification. */
9537 static bool
9538 gs_image_p (Lisp_Object object)
9540 struct image_keyword fmt[GS_LAST];
9541 Lisp_Object tem;
9542 int i;
9544 memcpy (fmt, gs_format, sizeof fmt);
9546 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9547 return 0;
9549 /* Bounding box must be a list or vector containing 4 integers. */
9550 tem = fmt[GS_BOUNDING_BOX].value;
9551 if (CONSP (tem))
9553 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9554 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9555 return 0;
9556 if (!NILP (tem))
9557 return 0;
9559 else if (VECTORP (tem))
9561 if (ASIZE (tem) != 4)
9562 return 0;
9563 for (i = 0; i < 4; ++i)
9564 if (!INTEGERP (AREF (tem, i)))
9565 return 0;
9567 else
9568 return 0;
9570 return 1;
9574 /* Load Ghostscript image IMG for use on frame F. Value is true
9575 if successful. */
9577 static bool
9578 gs_load (struct frame *f, struct image *img)
9580 uprintmax_t printnum1, printnum2;
9581 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9582 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9583 Lisp_Object frame;
9584 double in_width, in_height;
9585 Lisp_Object pixel_colors = Qnil;
9587 /* Compute pixel size of pixmap needed from the given size in the
9588 image specification. Sizes in the specification are in pt. 1 pt
9589 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9590 info. */
9591 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9592 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9593 in_width *= FRAME_RES_X (f);
9594 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9595 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9596 in_height *= FRAME_RES_Y (f);
9598 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9599 && check_image_size (f, in_width, in_height)))
9601 image_size_error ();
9602 return 0;
9604 img->width = in_width;
9605 img->height = in_height;
9607 /* Create the pixmap. */
9608 eassert (img->pixmap == NO_PIXMAP);
9610 if (x_check_image_size (0, img->width, img->height))
9612 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9613 block_input ();
9614 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
9615 img->width, img->height,
9616 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9617 unblock_input ();
9620 if (!img->pixmap)
9622 image_error ("Unable to create pixmap for `%s'" , img->spec);
9623 return 0;
9626 /* Call the loader to fill the pixmap. It returns a process object
9627 if successful. We do not record_unwind_protect here because
9628 other places in redisplay like calling window scroll functions
9629 don't either. Let the Lisp loader use `unwind-protect' instead. */
9630 printnum1 = FRAME_X_DRAWABLE (f);
9631 printnum2 = img->pixmap;
9632 window_and_pixmap_id
9633 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9635 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9636 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9637 pixel_colors
9638 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9640 XSETFRAME (frame, f);
9641 loader = image_spec_value (img->spec, QCloader, NULL);
9642 if (NILP (loader))
9643 loader = intern ("gs-load-image");
9645 img->lisp_data = call6 (loader, frame, img->spec,
9646 make_number (img->width),
9647 make_number (img->height),
9648 window_and_pixmap_id,
9649 pixel_colors);
9650 return PROCESSP (img->lisp_data);
9654 /* Kill the Ghostscript process that was started to fill PIXMAP on
9655 frame F. Called from XTread_socket when receiving an event
9656 telling Emacs that Ghostscript has finished drawing. */
9658 void
9659 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9661 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9662 ptrdiff_t i;
9663 struct image *img;
9665 /* Find the image containing PIXMAP. */
9666 for (i = 0; i < c->used; ++i)
9667 if (c->images[i]->pixmap == pixmap)
9668 break;
9670 /* Should someone in between have cleared the image cache, for
9671 instance, give up. */
9672 if (i == c->used)
9673 return;
9675 /* Kill the GS process. We should have found PIXMAP in the image
9676 cache and its image should contain a process object. */
9677 img = c->images[i];
9678 eassert (PROCESSP (img->lisp_data));
9679 Fkill_process (img->lisp_data, Qnil);
9680 img->lisp_data = Qnil;
9682 #if defined (HAVE_X_WINDOWS)
9684 /* On displays with a mutable colormap, figure out the colors
9685 allocated for the image by looking at the pixels of an XImage for
9686 img->pixmap. */
9687 if (x_mutable_colormap (FRAME_X_VISUAL (f)))
9689 XImagePtr ximg;
9691 block_input ();
9693 /* Try to get an XImage for img->pixmep. */
9694 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9695 0, 0, img->width, img->height, ~0, ZPixmap);
9696 if (ximg)
9698 /* Initialize the color table. */
9699 init_color_table ();
9701 /* For each pixel of the image, look its color up in the
9702 color table. After having done so, the color table will
9703 contain an entry for each color used by the image. */
9704 #ifdef COLOR_TABLE_SUPPORT
9705 for (int y = 0; y < img->height; ++y)
9706 for (int x = 0; x < img->width; ++x)
9708 unsigned long pixel = XGetPixel (ximg, x, y);
9710 lookup_pixel_color (f, pixel);
9713 /* Record colors in the image. Free color table and XImage. */
9714 img->colors = colors_in_color_table (&img->ncolors);
9715 free_color_table ();
9716 #endif
9717 XDestroyImage (ximg);
9719 #if 0 /* This doesn't seem to be the case. If we free the colors
9720 here, we get a BadAccess later in x_clear_image when
9721 freeing the colors. */
9722 /* We have allocated colors once, but Ghostscript has also
9723 allocated colors on behalf of us. So, to get the
9724 reference counts right, free them once. */
9725 if (img->ncolors)
9726 x_free_colors (f, img->colors, img->ncolors);
9727 #endif
9729 else
9730 image_error ("Cannot get X image of `%s'; colors will not be freed",
9731 img->spec);
9733 unblock_input ();
9735 #endif /* HAVE_X_WINDOWS */
9737 /* Now that we have the pixmap, compute mask and transform the
9738 image if requested. */
9739 block_input ();
9740 postprocess_image (f, img);
9741 unblock_input ();
9744 #endif /* HAVE_GHOSTSCRIPT */
9747 /***********************************************************************
9748 Tests
9749 ***********************************************************************/
9751 #ifdef GLYPH_DEBUG
9753 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9754 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9755 (Lisp_Object spec)
9757 return valid_image_p (spec) ? Qt : Qnil;
9761 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0,
9762 doc: /* */)
9763 (Lisp_Object spec)
9765 ptrdiff_t id = -1;
9767 if (valid_image_p (spec))
9768 id = lookup_image (SELECTED_FRAME (), spec);
9770 debug_print (spec);
9771 return make_number (id);
9774 #endif /* GLYPH_DEBUG */
9777 /***********************************************************************
9778 Initialization
9779 ***********************************************************************/
9781 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9782 doc: /* Initialize image library implementing image type TYPE.
9783 Return non-nil if TYPE is a supported image type.
9785 If image libraries are loaded dynamically (currently only the case on
9786 MS-Windows), load the library for TYPE if it is not yet loaded, using
9787 the library file(s) specified by `dynamic-library-alist'. */)
9788 (Lisp_Object type)
9790 return lookup_image_type (type) ? Qt : Qnil;
9793 /* Look up image type TYPE, and return a pointer to its image_type
9794 structure. Return 0 if TYPE is not a known image type. */
9796 static struct image_type *
9797 lookup_image_type (Lisp_Object type)
9799 /* Types pbm and xbm are built-in and always available. */
9800 if (EQ (type, Qpbm))
9801 return define_image_type (&pbm_type);
9803 if (EQ (type, Qxbm))
9804 return define_image_type (&xbm_type);
9806 #if defined (HAVE_XPM) || defined (HAVE_NS)
9807 if (EQ (type, Qxpm))
9808 return define_image_type (&xpm_type);
9809 #endif
9811 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9812 if (EQ (type, Qjpeg))
9813 return define_image_type (&jpeg_type);
9814 #endif
9816 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9817 if (EQ (type, Qtiff))
9818 return define_image_type (&tiff_type);
9819 #endif
9821 #if defined (HAVE_GIF) || defined (HAVE_NS)
9822 if (EQ (type, Qgif))
9823 return define_image_type (&gif_type);
9824 #endif
9826 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9827 if (EQ (type, Qpng))
9828 return define_image_type (&png_type);
9829 #endif
9831 #if defined (HAVE_RSVG)
9832 if (EQ (type, Qsvg))
9833 return define_image_type (&svg_type);
9834 #endif
9836 #if defined (HAVE_IMAGEMAGICK)
9837 if (EQ (type, Qimagemagick))
9838 return define_image_type (&imagemagick_type);
9839 #endif
9841 #ifdef HAVE_GHOSTSCRIPT
9842 if (EQ (type, Qpostscript))
9843 return define_image_type (&gs_type);
9844 #endif
9846 return NULL;
9849 #if !defined CANNOT_DUMP && defined HAVE_WINDOW_SYSTEM
9851 /* Reset image_types before dumping.
9852 Called from Fdump_emacs. */
9854 void
9855 reset_image_types (void)
9857 while (image_types)
9859 struct image_type *next = image_types->next;
9860 xfree (image_types);
9861 image_types = next;
9864 #endif
9866 void
9867 syms_of_image (void)
9869 /* Initialize this only once; it will be reset before dumping. */
9870 image_types = NULL;
9872 /* Must be defined now because we're going to update it below, while
9873 defining the supported image types. */
9874 DEFVAR_LISP ("image-types", Vimage_types,
9875 doc: /* List of potentially supported image types.
9876 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9877 To check whether it is really supported, use `image-type-available-p'. */);
9878 Vimage_types = Qnil;
9880 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9881 doc: /* Maximum size of images.
9882 Emacs will not load an image into memory if its pixel width or
9883 pixel height exceeds this limit.
9885 If the value is an integer, it directly specifies the maximum
9886 image height and width, measured in pixels. If it is a floating
9887 point number, it specifies the maximum image height and width
9888 as a ratio to the frame height and width. If the value is
9889 non-numeric, there is no explicit limit on the size of images. */);
9890 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9892 /* Other symbols. */
9893 DEFSYM (Qcount, "count");
9894 DEFSYM (Qextension_data, "extension-data");
9895 DEFSYM (Qdelay, "delay");
9897 /* Keywords. */
9898 DEFSYM (QCascent, ":ascent");
9899 DEFSYM (QCmargin, ":margin");
9900 DEFSYM (QCrelief, ":relief");
9901 DEFSYM (QCconversion, ":conversion");
9902 DEFSYM (QCcolor_symbols, ":color-symbols");
9903 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9904 DEFSYM (QCindex, ":index");
9905 DEFSYM (QCcrop, ":crop");
9906 DEFSYM (QCrotation, ":rotation");
9907 DEFSYM (QCmatrix, ":matrix");
9908 DEFSYM (QCscale, ":scale");
9909 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9910 DEFSYM (QCmask, ":mask");
9912 /* Other symbols. */
9913 DEFSYM (Qlaplace, "laplace");
9914 DEFSYM (Qemboss, "emboss");
9915 DEFSYM (Qedge_detection, "edge-detection");
9916 DEFSYM (Qheuristic, "heuristic");
9918 DEFSYM (Qpostscript, "postscript");
9919 DEFSYM (QCmax_width, ":max-width");
9920 DEFSYM (QCmax_height, ":max-height");
9921 #ifdef HAVE_GHOSTSCRIPT
9922 ADD_IMAGE_TYPE (Qpostscript);
9923 DEFSYM (QCloader, ":loader");
9924 DEFSYM (QCpt_width, ":pt-width");
9925 DEFSYM (QCpt_height, ":pt-height");
9926 #endif /* HAVE_GHOSTSCRIPT */
9928 #ifdef HAVE_NTGUI
9929 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9930 or -1 if no PNG/GIF support was compiled in. This is tested by
9931 w32-win.el to correctly set up the alist used to search for the
9932 respective image libraries. */
9933 DEFSYM (Qlibpng_version, "libpng-version");
9934 Fset (Qlibpng_version,
9935 #if HAVE_PNG
9936 make_number (PNG_LIBPNG_VER)
9937 #else
9938 make_number (-1)
9939 #endif
9941 DEFSYM (Qlibgif_version, "libgif-version");
9942 Fset (Qlibgif_version,
9943 #ifdef HAVE_GIF
9944 make_number (GIFLIB_MAJOR * 10000
9945 + GIFLIB_MINOR * 100
9946 + GIFLIB_RELEASE)
9947 #else
9948 make_number (-1)
9949 #endif
9951 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9952 Fset (Qlibjpeg_version,
9953 #if HAVE_JPEG
9954 make_number (JPEG_LIB_VERSION)
9955 #else
9956 make_number (-1)
9957 #endif
9959 #endif
9961 DEFSYM (Qpbm, "pbm");
9962 ADD_IMAGE_TYPE (Qpbm);
9964 DEFSYM (Qxbm, "xbm");
9965 ADD_IMAGE_TYPE (Qxbm);
9967 #if defined (HAVE_XPM) || defined (HAVE_NS)
9968 DEFSYM (Qxpm, "xpm");
9969 ADD_IMAGE_TYPE (Qxpm);
9970 #endif
9972 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9973 DEFSYM (Qjpeg, "jpeg");
9974 ADD_IMAGE_TYPE (Qjpeg);
9975 #endif
9977 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9978 DEFSYM (Qtiff, "tiff");
9979 ADD_IMAGE_TYPE (Qtiff);
9980 #endif
9982 #if defined (HAVE_GIF) || defined (HAVE_NS)
9983 DEFSYM (Qgif, "gif");
9984 ADD_IMAGE_TYPE (Qgif);
9985 #endif
9987 #if defined (HAVE_PNG) || defined (HAVE_NS)
9988 DEFSYM (Qpng, "png");
9989 ADD_IMAGE_TYPE (Qpng);
9990 #endif
9992 #if defined (HAVE_IMAGEMAGICK)
9993 DEFSYM (Qimagemagick, "imagemagick");
9994 ADD_IMAGE_TYPE (Qimagemagick);
9995 #endif
9997 #if defined (HAVE_RSVG)
9998 DEFSYM (Qsvg, "svg");
9999 ADD_IMAGE_TYPE (Qsvg);
10000 #ifdef HAVE_NTGUI
10001 /* Other libraries used directly by svg code. */
10002 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
10003 DEFSYM (Qglib, "glib");
10004 DEFSYM (Qgobject, "gobject");
10005 #endif /* HAVE_NTGUI */
10006 #endif /* HAVE_RSVG */
10008 defsubr (&Sinit_image_library);
10009 #ifdef HAVE_IMAGEMAGICK
10010 defsubr (&Simagemagick_types);
10011 #endif
10012 defsubr (&Sclear_image_cache);
10013 defsubr (&Simage_flush);
10014 defsubr (&Simage_size);
10015 defsubr (&Simage_mask_p);
10016 defsubr (&Simage_metadata);
10018 #ifdef GLYPH_DEBUG
10019 defsubr (&Simagep);
10020 defsubr (&Slookup_image);
10021 #endif
10023 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
10024 doc: /* Non-nil means always draw a cross over disabled images.
10025 Disabled images are those having a `:conversion disabled' property.
10026 A cross is always drawn on black & white displays. */);
10027 cross_disabled_images = 0;
10029 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
10030 doc: /* List of directories to search for window system bitmap files. */);
10031 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
10033 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
10034 doc: /* Maximum time after which images are removed from the cache.
10035 When an image has not been displayed this many seconds, Emacs
10036 automatically removes it from the image cache. If the cache contains
10037 a large number of images, the actual eviction time may be shorter.
10038 The value can also be nil, meaning the cache is never cleared.
10040 The function `clear-image-cache' disregards this variable. */);
10041 Vimage_cache_eviction_delay = make_number (300);
10042 #ifdef HAVE_IMAGEMAGICK
10043 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
10044 doc: /* Integer indicating which ImageMagick rendering method to use.
10045 The options are:
10046 0 -- the default method (pixel pushing)
10047 1 -- a newer method ("MagickExportImagePixels") that may perform
10048 better (speed etc) in some cases, but has not been as thoroughly
10049 tested with Emacs as the default method. This method requires
10050 ImageMagick version 6.4.6 (approximately) or later.
10051 */);
10052 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
10053 imagemagick_render_type = 0;
10054 #endif