Subject: Restore correct Gnus newsgroup name after sending message
[emacs.git] / src / image.c
blob39677d2add91d9380918f2e77bf257ebcb565d2c
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2017 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 <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <unistd.h>
26 /* Include this before including <setjmp.h> to work around bugs with
27 older libpng; see Bug#17429. */
28 #if defined HAVE_PNG && !defined HAVE_NS
29 # include <png.h>
30 #endif
32 #include <setjmp.h>
34 #include <c-ctype.h>
35 #include <flexmember.h>
37 #include "lisp.h"
38 #include "frame.h"
39 #include "process.h"
40 #include "window.h"
41 #include "buffer.h"
42 #include "dispextern.h"
43 #include "blockinput.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_NS) \
1273 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1275 /* Store F's background color into *BGCOLOR. */
1276 static void
1277 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1279 #ifndef HAVE_NS
1280 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1281 x_query_color (f, bgcolor);
1282 #else
1283 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1284 #endif
1287 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1289 /***********************************************************************
1290 Helper functions for X image types
1291 ***********************************************************************/
1293 /* Clear X resources of image IMG on frame F according to FLAGS.
1294 FLAGS is bitwise-or of the following masks:
1295 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1296 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1297 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1298 any. */
1300 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1301 #define CLEAR_IMAGE_MASK (1 << 1)
1302 #define CLEAR_IMAGE_COLORS (1 << 2)
1304 static void
1305 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1307 if (flags & CLEAR_IMAGE_PIXMAP)
1309 if (img->pixmap)
1311 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1312 img->pixmap = NO_PIXMAP;
1313 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1314 img->background_valid = 0;
1316 #ifdef HAVE_X_WINDOWS
1317 if (img->ximg)
1319 x_destroy_x_image (img->ximg);
1320 img->ximg = NULL;
1321 img->background_valid = 0;
1323 #endif
1326 if (flags & CLEAR_IMAGE_MASK)
1328 if (img->mask)
1330 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1331 img->mask = NO_PIXMAP;
1332 img->background_transparent_valid = 0;
1334 #ifdef HAVE_X_WINDOWS
1335 if (img->mask_img)
1337 x_destroy_x_image (img->mask_img);
1338 img->mask_img = NULL;
1339 img->background_transparent_valid = 0;
1341 #endif
1344 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1346 /* W32_TODO: color table support. */
1347 #ifdef HAVE_X_WINDOWS
1348 x_free_colors (f, img->colors, img->ncolors);
1349 #endif /* HAVE_X_WINDOWS */
1350 xfree (img->colors);
1351 img->colors = NULL;
1352 img->ncolors = 0;
1357 /* Free X resources of image IMG which is used on frame F. */
1359 static void
1360 x_clear_image (struct frame *f, struct image *img)
1362 block_input ();
1363 #ifdef USE_CAIRO
1364 if (img->cr_data)
1365 cairo_surface_destroy ((cairo_surface_t *)img->cr_data);
1366 if (img->cr_data2) xfree (img->cr_data2);
1367 #endif
1368 x_clear_image_1 (f, img,
1369 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1370 unblock_input ();
1374 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1375 cannot be allocated, use DFLT. Add a newly allocated color to
1376 IMG->colors, so that it can be freed again. Value is the pixel
1377 color. */
1379 static unsigned long
1380 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1381 unsigned long dflt)
1383 XColor color;
1384 unsigned long result;
1386 eassert (STRINGP (color_name));
1388 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1389 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1390 INT_MAX))
1392 /* This isn't called frequently so we get away with simply
1393 reallocating the color vector to the needed size, here. */
1394 ptrdiff_t ncolors = img->ncolors + 1;
1395 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1396 img->colors[ncolors - 1] = color.pixel;
1397 img->ncolors = ncolors;
1398 result = color.pixel;
1400 else
1401 result = dflt;
1403 return result;
1408 /***********************************************************************
1409 Image Cache
1410 ***********************************************************************/
1412 static void cache_image (struct frame *f, struct image *img);
1414 /* Return a new, initialized image cache that is allocated from the
1415 heap. Call free_image_cache to free an image cache. */
1417 struct image_cache *
1418 make_image_cache (void)
1420 struct image_cache *c = xmalloc (sizeof *c);
1422 c->size = 50;
1423 c->used = c->refcount = 0;
1424 c->images = xmalloc (c->size * sizeof *c->images);
1425 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1426 return c;
1430 /* Find an image matching SPEC in the cache, and return it. If no
1431 image is found, return NULL. */
1432 static struct image *
1433 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1435 struct image *img;
1436 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1437 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1439 if (!c) return NULL;
1441 /* If the image spec does not specify a background color, the cached
1442 image must have the same background color as the current frame.
1443 The foreground color must also match, for the sake of monochrome
1444 images.
1446 In fact, we could ignore the foreground color matching condition
1447 for color images, or if the image spec specifies :foreground;
1448 similarly we could ignore the background color matching condition
1449 for formats that don't use transparency (such as jpeg), or if the
1450 image spec specifies :background. However, the extra memory
1451 usage is probably negligible in practice, so we don't bother. */
1453 for (img = c->buckets[i]; img; img = img->next)
1454 if (img->hash == hash
1455 && !NILP (Fequal (img->spec, spec))
1456 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1457 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1458 break;
1459 return img;
1463 /* Search frame F for an image with spec SPEC, and free it. */
1465 static void
1466 uncache_image (struct frame *f, Lisp_Object spec)
1468 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1469 if (img)
1471 free_image (f, img);
1472 /* As display glyphs may still be referring to the image ID, we
1473 must garbage the frame (Bug#6426). */
1474 SET_FRAME_GARBAGED (f);
1479 /* Free image cache of frame F. Be aware that X frames share images
1480 caches. */
1482 void
1483 free_image_cache (struct frame *f)
1485 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1486 if (c)
1488 ptrdiff_t i;
1490 /* Cache should not be referenced by any frame when freed. */
1491 eassert (c->refcount == 0);
1493 for (i = 0; i < c->used; ++i)
1494 free_image (f, c->images[i]);
1495 xfree (c->images);
1496 xfree (c->buckets);
1497 xfree (c);
1498 FRAME_IMAGE_CACHE (f) = NULL;
1503 /* Clear image cache of frame F. FILTER=t means free all images.
1504 FILTER=nil means clear only images that haven't been
1505 displayed for some time.
1506 Else, only free the images which have FILTER in their `dependencies'.
1507 Should be called from time to time to reduce the number of loaded images.
1508 If image-cache-eviction-delay is non-nil, this frees images in the cache
1509 which weren't displayed for at least that many seconds. */
1511 static void
1512 clear_image_cache (struct frame *f, Lisp_Object filter)
1514 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1516 if (c)
1518 ptrdiff_t i, nfreed = 0;
1520 /* Block input so that we won't be interrupted by a SIGIO
1521 while being in an inconsistent state. */
1522 block_input ();
1524 if (!NILP (filter))
1526 /* Filter image cache. */
1527 for (i = 0; i < c->used; ++i)
1529 struct image *img = c->images[i];
1530 if (img && (EQ (Qt, filter)
1531 || !NILP (Fmember (filter, img->dependencies))))
1533 free_image (f, img);
1534 ++nfreed;
1538 else if (INTEGERP (Vimage_cache_eviction_delay))
1540 /* Free cache based on timestamp. */
1541 struct timespec old, t;
1542 double delay;
1543 ptrdiff_t nimages = 0;
1545 for (i = 0; i < c->used; ++i)
1546 if (c->images[i])
1547 nimages++;
1549 /* If the number of cached images has grown unusually large,
1550 decrease the cache eviction delay (Bug#6230). */
1551 delay = XINT (Vimage_cache_eviction_delay);
1552 if (nimages > 40)
1553 delay = 1600 * delay / nimages / nimages;
1554 delay = max (delay, 1);
1556 t = current_timespec ();
1557 old = timespec_sub (t, dtotimespec (delay));
1559 for (i = 0; i < c->used; ++i)
1561 struct image *img = c->images[i];
1562 if (img && timespec_cmp (img->timestamp, old) < 0)
1564 free_image (f, img);
1565 ++nfreed;
1570 /* We may be clearing the image cache because, for example,
1571 Emacs was iconified for a longer period of time. In that
1572 case, current matrices may still contain references to
1573 images freed above. So, clear these matrices. */
1574 if (nfreed)
1576 Lisp_Object tail, frame;
1578 FOR_EACH_FRAME (tail, frame)
1580 struct frame *fr = XFRAME (frame);
1581 if (FRAME_IMAGE_CACHE (fr) == c)
1582 clear_current_matrices (fr);
1585 windows_or_buffers_changed = 19;
1588 unblock_input ();
1592 void
1593 clear_image_caches (Lisp_Object filter)
1595 /* FIXME: We want to do
1596 * struct terminal *t;
1597 * for (t = terminal_list; t; t = t->next_terminal)
1598 * clear_image_cache (t, filter); */
1599 Lisp_Object tail, frame;
1600 FOR_EACH_FRAME (tail, frame)
1601 if (FRAME_WINDOW_P (XFRAME (frame)))
1602 clear_image_cache (XFRAME (frame), filter);
1605 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1606 0, 1, 0,
1607 doc: /* Clear the image cache.
1608 FILTER nil or a frame means clear all images in the selected frame.
1609 FILTER t means clear the image caches of all frames.
1610 Anything else, means only clear those images which refer to FILTER,
1611 which is then usually a filename. */)
1612 (Lisp_Object filter)
1614 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1615 clear_image_caches (filter);
1616 else
1617 clear_image_cache (decode_window_system_frame (filter), Qt);
1619 return Qnil;
1623 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1624 1, 2, 0,
1625 doc: /* Flush the image with specification SPEC on frame FRAME.
1626 This removes the image from the Emacs image cache. If SPEC specifies
1627 an image file, the next redisplay of this image will read from the
1628 current contents of that file.
1630 FRAME nil or omitted means use the selected frame.
1631 FRAME t means refresh the image on all frames. */)
1632 (Lisp_Object spec, Lisp_Object frame)
1634 if (!valid_image_p (spec))
1635 error ("Invalid image specification");
1637 if (EQ (frame, Qt))
1639 Lisp_Object tail;
1640 FOR_EACH_FRAME (tail, frame)
1642 struct frame *f = XFRAME (frame);
1643 if (FRAME_WINDOW_P (f))
1644 uncache_image (f, spec);
1647 else
1648 uncache_image (decode_window_system_frame (frame), spec);
1650 return Qnil;
1654 /* Compute masks and transform image IMG on frame F, as specified
1655 by the image's specification, */
1657 static void
1658 postprocess_image (struct frame *f, struct image *img)
1660 /* Manipulation of the image's mask. */
1661 if (img->pixmap)
1663 Lisp_Object conversion, spec;
1664 Lisp_Object mask;
1666 spec = img->spec;
1668 /* `:heuristic-mask t'
1669 `:mask heuristic'
1670 means build a mask heuristically.
1671 `:heuristic-mask (R G B)'
1672 `:mask (heuristic (R G B))'
1673 means build a mask from color (R G B) in the
1674 image.
1675 `:mask nil'
1676 means remove a mask, if any. */
1678 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1679 if (!NILP (mask))
1680 x_build_heuristic_mask (f, img, mask);
1681 else
1683 bool found_p;
1685 mask = image_spec_value (spec, QCmask, &found_p);
1687 if (EQ (mask, Qheuristic))
1688 x_build_heuristic_mask (f, img, Qt);
1689 else if (CONSP (mask)
1690 && EQ (XCAR (mask), Qheuristic))
1692 if (CONSP (XCDR (mask)))
1693 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1694 else
1695 x_build_heuristic_mask (f, img, XCDR (mask));
1697 else if (NILP (mask) && found_p && img->mask)
1698 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1702 /* Should we apply an image transformation algorithm? */
1703 conversion = image_spec_value (spec, QCconversion, NULL);
1704 if (EQ (conversion, Qdisabled))
1705 x_disable_image (f, img);
1706 else if (EQ (conversion, Qlaplace))
1707 x_laplace (f, img);
1708 else if (EQ (conversion, Qemboss))
1709 x_emboss (f, img);
1710 else if (CONSP (conversion)
1711 && EQ (XCAR (conversion), Qedge_detection))
1713 Lisp_Object tem;
1714 tem = XCDR (conversion);
1715 if (CONSP (tem))
1716 x_edge_detection (f, img,
1717 Fplist_get (tem, QCmatrix),
1718 Fplist_get (tem, QCcolor_adjustment));
1724 /* Return the id of image with Lisp specification SPEC on frame F.
1725 SPEC must be a valid Lisp image specification (see valid_image_p). */
1727 ptrdiff_t
1728 lookup_image (struct frame *f, Lisp_Object spec)
1730 struct image *img;
1731 EMACS_UINT hash;
1733 /* F must be a window-system frame, and SPEC must be a valid image
1734 specification. */
1735 eassert (FRAME_WINDOW_P (f));
1736 eassert (valid_image_p (spec));
1738 /* Look up SPEC in the hash table of the image cache. */
1739 hash = sxhash (spec, 0);
1740 img = search_image_cache (f, spec, hash);
1741 if (img && img->load_failed_p)
1743 free_image (f, img);
1744 img = NULL;
1747 /* If not found, create a new image and cache it. */
1748 if (img == NULL)
1750 block_input ();
1751 img = make_image (spec, hash);
1752 cache_image (f, img);
1753 img->load_failed_p = ! img->type->load (f, img);
1754 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1755 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1757 /* If we can't load the image, and we don't have a width and
1758 height, use some arbitrary width and height so that we can
1759 draw a rectangle for it. */
1760 if (img->load_failed_p)
1762 Lisp_Object value;
1764 value = image_spec_value (spec, QCwidth, NULL);
1765 img->width = (INTEGERP (value)
1766 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1767 value = image_spec_value (spec, QCheight, NULL);
1768 img->height = (INTEGERP (value)
1769 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1771 else
1773 /* Handle image type independent image attributes
1774 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1775 `:background COLOR'. */
1776 Lisp_Object ascent, margin, relief, bg;
1777 int relief_bound;
1779 ascent = image_spec_value (spec, QCascent, NULL);
1780 if (INTEGERP (ascent))
1781 img->ascent = XFASTINT (ascent);
1782 else if (EQ (ascent, Qcenter))
1783 img->ascent = CENTERED_IMAGE_ASCENT;
1785 margin = image_spec_value (spec, QCmargin, NULL);
1786 if (INTEGERP (margin))
1787 img->vmargin = img->hmargin = XFASTINT (margin);
1788 else if (CONSP (margin))
1790 img->hmargin = XFASTINT (XCAR (margin));
1791 img->vmargin = XFASTINT (XCDR (margin));
1794 relief = image_spec_value (spec, QCrelief, NULL);
1795 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1796 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1798 img->relief = XINT (relief);
1799 img->hmargin += eabs (img->relief);
1800 img->vmargin += eabs (img->relief);
1803 if (! img->background_valid)
1805 bg = image_spec_value (img->spec, QCbackground, NULL);
1806 if (!NILP (bg))
1808 img->background
1809 = x_alloc_image_color (f, img, bg,
1810 FRAME_BACKGROUND_PIXEL (f));
1811 img->background_valid = 1;
1815 /* Do image transformations and compute masks, unless we
1816 don't have the image yet. */
1817 if (!EQ (builtin_lisp_symbol (img->type->type), Qpostscript))
1818 postprocess_image (f, img);
1821 unblock_input ();
1824 /* We're using IMG, so set its timestamp to `now'. */
1825 img->timestamp = current_timespec ();
1827 /* Value is the image id. */
1828 return img->id;
1832 /* Cache image IMG in the image cache of frame F. */
1834 static void
1835 cache_image (struct frame *f, struct image *img)
1837 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1838 ptrdiff_t i;
1840 if (!c)
1841 c = FRAME_IMAGE_CACHE (f) = make_image_cache ();
1843 /* Find a free slot in c->images. */
1844 for (i = 0; i < c->used; ++i)
1845 if (c->images[i] == NULL)
1846 break;
1848 /* If no free slot found, maybe enlarge c->images. */
1849 if (i == c->used && c->used == c->size)
1850 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1852 /* Add IMG to c->images, and assign IMG an id. */
1853 c->images[i] = img;
1854 img->id = i;
1855 if (i == c->used)
1856 ++c->used;
1858 /* Add IMG to the cache's hash table. */
1859 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1860 img->next = c->buckets[i];
1861 if (img->next)
1862 img->next->prev = img;
1863 img->prev = NULL;
1864 c->buckets[i] = img;
1868 /* Call FN on every image in the image cache of frame F. Used to mark
1869 Lisp Objects in the image cache. */
1871 /* Mark Lisp objects in image IMG. */
1873 static void
1874 mark_image (struct image *img)
1876 mark_object (img->spec);
1877 mark_object (img->dependencies);
1879 if (!NILP (img->lisp_data))
1880 mark_object (img->lisp_data);
1884 void
1885 mark_image_cache (struct image_cache *c)
1887 if (c)
1889 ptrdiff_t i;
1890 for (i = 0; i < c->used; ++i)
1891 if (c->images[i])
1892 mark_image (c->images[i]);
1898 /***********************************************************************
1899 X / NS / W32 support code
1900 ***********************************************************************/
1902 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1903 windowing system.
1904 WIDTH and HEIGHT must both be positive.
1905 If XIMG is null, assume it is a bitmap. */
1906 static bool
1907 x_check_image_size (XImagePtr ximg, int width, int height)
1909 #ifdef HAVE_X_WINDOWS
1910 /* Respect Xlib's limits: it cannot deal with images that have more
1911 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1912 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1913 enum
1915 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1916 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1919 int bitmap_pad, depth, bytes_per_line;
1920 if (ximg)
1922 bitmap_pad = ximg->bitmap_pad;
1923 depth = ximg->depth;
1924 bytes_per_line = ximg->bytes_per_line;
1926 else
1928 bitmap_pad = 8;
1929 depth = 1;
1930 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1932 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1933 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1934 #else
1935 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1936 For now, assume that every image size is allowed on these systems. */
1937 return 1;
1938 #endif
1941 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1942 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1943 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1944 via xmalloc. Print error messages via image_error if an error
1945 occurs. Value is true if successful.
1947 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1948 should indicate the bit depth of the image. */
1950 static bool
1951 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1952 XImagePtr *ximg, Pixmap *pixmap)
1954 #ifdef HAVE_X_WINDOWS
1955 Display *display = FRAME_X_DISPLAY (f);
1956 Drawable drawable = FRAME_X_DRAWABLE (f);
1957 Screen *screen = FRAME_X_SCREEN (f);
1959 eassert (input_blocked_p ());
1961 if (depth <= 0)
1962 depth = DefaultDepthOfScreen (screen);
1963 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1964 depth, ZPixmap, 0, NULL, width, height,
1965 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1966 if (*ximg == NULL)
1968 image_error ("Unable to allocate X image");
1969 return 0;
1972 if (! x_check_image_size (*ximg, width, height))
1974 x_destroy_x_image (*ximg);
1975 *ximg = NULL;
1976 image_error ("Image too large (%dx%d)",
1977 make_number (width), make_number (height));
1978 return 0;
1981 /* Allocate image raster. */
1982 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1984 /* Allocate a pixmap of the same size. */
1985 *pixmap = XCreatePixmap (display, drawable, width, height, depth);
1986 if (*pixmap == NO_PIXMAP)
1988 x_destroy_x_image (*ximg);
1989 *ximg = NULL;
1990 image_error ("Unable to create X pixmap");
1991 return 0;
1994 return 1;
1995 #endif /* HAVE_X_WINDOWS */
1997 #ifdef HAVE_NTGUI
1999 BITMAPINFOHEADER *header;
2000 HDC hdc;
2001 int scanline_width_bits;
2002 int remainder;
2003 int palette_colors = 0;
2005 if (depth == 0)
2006 depth = 24;
2008 if (depth != 1 && depth != 4 && depth != 8
2009 && depth != 16 && depth != 24 && depth != 32)
2011 image_error ("Invalid image bit depth specified");
2012 return 0;
2015 scanline_width_bits = width * depth;
2016 remainder = scanline_width_bits % 32;
2018 if (remainder)
2019 scanline_width_bits += 32 - remainder;
2021 /* Bitmaps with a depth less than 16 need a palette. */
2022 /* BITMAPINFO structure already contains the first RGBQUAD. */
2023 if (depth < 16)
2024 palette_colors = 1 << (depth - 1);
2026 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2028 header = &(*ximg)->info.bmiHeader;
2029 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2030 header->biSize = sizeof (*header);
2031 header->biWidth = width;
2032 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2033 header->biPlanes = 1;
2034 header->biBitCount = depth;
2035 header->biCompression = BI_RGB;
2036 header->biClrUsed = palette_colors;
2038 /* TODO: fill in palette. */
2039 if (depth == 1)
2041 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2042 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2043 (*ximg)->info.bmiColors[0].rgbRed = 0;
2044 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2045 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2046 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2047 (*ximg)->info.bmiColors[1].rgbRed = 255;
2048 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2051 hdc = get_frame_dc (f);
2053 /* Create a DIBSection and raster array for the bitmap,
2054 and store its handle in *pixmap. */
2055 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2056 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2057 /* casting avoids a GCC warning */
2058 (void **)&((*ximg)->data), NULL, 0);
2060 /* Realize display palette and garbage all frames. */
2061 release_frame_dc (f, hdc);
2063 if (*pixmap == NULL)
2065 DWORD err = GetLastError ();
2066 Lisp_Object errcode;
2067 /* All system errors are < 10000, so the following is safe. */
2068 XSETINT (errcode, err);
2069 image_error ("Unable to create bitmap, error code %d", errcode);
2070 x_destroy_x_image (*ximg);
2071 *ximg = NULL;
2072 return 0;
2075 return 1;
2077 #endif /* HAVE_NTGUI */
2079 #ifdef HAVE_NS
2080 *pixmap = ns_image_for_XPM (width, height, depth);
2081 if (*pixmap == 0)
2083 *ximg = NULL;
2084 image_error ("Unable to allocate NSImage for XPM pixmap");
2085 return 0;
2087 *ximg = *pixmap;
2088 return 1;
2089 #endif
2093 /* Destroy XImage XIMG. Free XIMG->data. */
2095 static void
2096 x_destroy_x_image (XImagePtr ximg)
2098 eassert (input_blocked_p ());
2099 if (ximg)
2101 #ifdef HAVE_X_WINDOWS
2102 xfree (ximg->data);
2103 ximg->data = NULL;
2104 XDestroyImage (ximg);
2105 #endif /* HAVE_X_WINDOWS */
2106 #ifdef HAVE_NTGUI
2107 /* Data will be freed by DestroyObject. */
2108 ximg->data = NULL;
2109 xfree (ximg);
2110 #endif /* HAVE_NTGUI */
2111 #ifdef HAVE_NS
2112 ns_release_object (ximg);
2113 #endif /* HAVE_NS */
2118 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2119 are width and height of both the image and pixmap. */
2121 static void
2122 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2124 #ifdef HAVE_X_WINDOWS
2125 GC gc;
2127 eassert (input_blocked_p ());
2128 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2129 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2130 XFreeGC (FRAME_X_DISPLAY (f), gc);
2131 #endif /* HAVE_X_WINDOWS */
2133 #ifdef HAVE_NTGUI
2134 #if 0 /* I don't think this is necessary looking at where it is used. */
2135 HDC hdc = get_frame_dc (f);
2136 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2137 release_frame_dc (f, hdc);
2138 #endif
2139 #endif /* HAVE_NTGUI */
2141 #ifdef HAVE_NS
2142 eassert (ximg == pixmap);
2143 ns_retain_object (ximg);
2144 #endif
2147 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2148 with image_put_x_image. */
2150 static bool
2151 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2152 int width, int height, int depth,
2153 XImagePtr *ximg, bool mask_p)
2155 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2157 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2158 !mask_p ? &img->pixmap : &img->mask);
2161 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2162 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2163 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2164 On the other platforms, it puts XIMG into the pixmap, then frees
2165 the X image and its buffer. */
2167 static void
2168 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2169 bool mask_p)
2171 #ifdef HAVE_X_WINDOWS
2172 if (!mask_p)
2174 eassert (img->ximg == NULL);
2175 img->ximg = ximg;
2177 else
2179 eassert (img->mask_img == NULL);
2180 img->mask_img = ximg;
2182 #else
2183 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2184 img->width, img->height);
2185 x_destroy_x_image (ximg);
2186 #endif
2189 #ifdef HAVE_X_WINDOWS
2190 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2191 the X images and their buffers. */
2193 static void
2194 image_sync_to_pixmaps (struct frame *f, struct image *img)
2196 if (img->ximg)
2198 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2199 x_destroy_x_image (img->ximg);
2200 img->ximg = NULL;
2202 if (img->mask_img)
2204 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2205 x_destroy_x_image (img->mask_img);
2206 img->mask_img = NULL;
2209 #endif
2211 #ifdef HAVE_NTGUI
2212 /* Create a memory device context for IMG on frame F. It stores the
2213 currently selected GDI object into *PREV for future restoration by
2214 image_unget_x_image_or_dc. */
2216 static XImagePtr_or_DC
2217 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2218 HGDIOBJ *prev)
2220 HDC frame_dc = get_frame_dc (f);
2221 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2223 release_frame_dc (f, frame_dc);
2224 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2226 return ximg;
2229 static void
2230 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2231 XImagePtr_or_DC ximg, HGDIOBJ prev)
2233 SelectObject (ximg, prev);
2234 DeleteDC (ximg);
2236 #else /* !HAVE_NTGUI */
2237 /* Get the X image for IMG on frame F. The resulting X image data
2238 should be treated as read-only at least on X. */
2240 static XImagePtr
2241 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2243 #ifdef HAVE_X_WINDOWS
2244 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2246 if (ximg_in_img)
2247 return ximg_in_img;
2248 else
2249 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2250 0, 0, img->width, img->height, ~0, ZPixmap);
2251 #elif defined (HAVE_NS)
2252 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2254 ns_retain_object (pixmap);
2255 return pixmap;
2256 #endif
2259 static void
2260 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2262 #ifdef HAVE_X_WINDOWS
2263 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2265 if (ximg_in_img)
2266 eassert (ximg == ximg_in_img);
2267 else
2268 XDestroyImage (ximg);
2269 #elif defined (HAVE_NS)
2270 ns_release_object (ximg);
2271 #endif
2273 #endif /* !HAVE_NTGUI */
2276 /***********************************************************************
2277 File Handling
2278 ***********************************************************************/
2280 /* Find image file FILE. Look in data-directory/images, then
2281 x-bitmap-file-path. Value is the full name of the file
2282 found, or nil if not found. If PFD is nonnull store into *PFD a
2283 readable file descriptor for the file, opened in binary mode. If
2284 PFD is null, do not open the file. */
2286 static Lisp_Object
2287 x_find_image_fd (Lisp_Object file, int *pfd)
2289 Lisp_Object file_found, search_path;
2290 int fd;
2292 /* TODO I think this should use something like image-load-path
2293 instead. Unfortunately, that can contain non-string elements. */
2294 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2295 Vdata_directory),
2296 Vx_bitmap_file_path);
2298 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2299 fd = openp (search_path, file, Qnil, &file_found,
2300 pfd ? Qt : make_number (R_OK), false);
2301 if (fd >= 0 || fd == -2)
2303 file_found = ENCODE_FILE (file_found);
2304 if (fd == -2)
2306 /* The file exists locally, but has a file handler. (This
2307 happens, e.g., under Auto Image File Mode.) 'openp'
2308 didn't open the file, so we should, because the caller
2309 expects that. */
2310 fd = emacs_open (SSDATA (file_found), O_RDONLY, 0);
2313 else /* fd < 0, but not -2 */
2314 return Qnil;
2315 if (pfd)
2316 *pfd = fd;
2317 return file_found;
2320 /* Find image file FILE. Look in data-directory/images, then
2321 x-bitmap-file-path. Value is the encoded full name of the file
2322 found, or nil if not found. */
2324 Lisp_Object
2325 x_find_image_file (Lisp_Object file)
2327 return x_find_image_fd (file, 0);
2330 /* Read FILE into memory. Value is a pointer to a buffer allocated
2331 with xmalloc holding FILE's contents. Value is null if an error
2332 occurred. FD is a file descriptor open for reading FILE. Set
2333 *SIZE to the size of the file. */
2335 static char *
2336 slurp_file (int fd, ptrdiff_t *size)
2338 FILE *fp = fdopen (fd, "rb");
2340 char *buf = NULL;
2341 struct stat st;
2343 if (fp)
2345 ptrdiff_t count = SPECPDL_INDEX ();
2346 record_unwind_protect_ptr (fclose_unwind, fp);
2348 if (fstat (fileno (fp), &st) == 0
2349 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2351 /* Report an error if we read past the purported EOF.
2352 This can happen if the file grows as we read it. */
2353 ptrdiff_t buflen = st.st_size;
2354 buf = xmalloc (buflen + 1);
2355 if (fread (buf, 1, buflen + 1, fp) == buflen)
2356 *size = buflen;
2357 else
2359 xfree (buf);
2360 buf = NULL;
2364 unbind_to (count, Qnil);
2367 return buf;
2372 /***********************************************************************
2373 XBM images
2374 ***********************************************************************/
2376 static bool xbm_load (struct frame *f, struct image *img);
2377 static bool xbm_image_p (Lisp_Object object);
2378 static bool xbm_file_p (Lisp_Object);
2381 /* Indices of image specification fields in xbm_format, below. */
2383 enum xbm_keyword_index
2385 XBM_TYPE,
2386 XBM_FILE,
2387 XBM_WIDTH,
2388 XBM_HEIGHT,
2389 XBM_DATA,
2390 XBM_FOREGROUND,
2391 XBM_BACKGROUND,
2392 XBM_ASCENT,
2393 XBM_MARGIN,
2394 XBM_RELIEF,
2395 XBM_ALGORITHM,
2396 XBM_HEURISTIC_MASK,
2397 XBM_MASK,
2398 XBM_LAST
2401 /* Vector of image_keyword structures describing the format
2402 of valid XBM image specifications. */
2404 static const struct image_keyword xbm_format[XBM_LAST] =
2406 {":type", IMAGE_SYMBOL_VALUE, 1},
2407 {":file", IMAGE_STRING_VALUE, 0},
2408 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2409 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2410 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2411 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2412 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2413 {":ascent", IMAGE_ASCENT_VALUE, 0},
2414 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2415 {":relief", IMAGE_INTEGER_VALUE, 0},
2416 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2417 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2418 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2421 /* Structure describing the image type XBM. */
2423 static struct image_type xbm_type =
2425 SYMBOL_INDEX (Qxbm),
2426 xbm_image_p,
2427 xbm_load,
2428 x_clear_image,
2429 NULL,
2430 NULL
2433 /* Tokens returned from xbm_scan. */
2435 enum xbm_token
2437 XBM_TK_IDENT = 256,
2438 XBM_TK_NUMBER
2442 /* Return true if OBJECT is a valid XBM-type image specification.
2443 A valid specification is a list starting with the symbol `image'
2444 The rest of the list is a property list which must contain an
2445 entry `:type xbm'.
2447 If the specification specifies a file to load, it must contain
2448 an entry `:file FILENAME' where FILENAME is a string.
2450 If the specification is for a bitmap loaded from memory it must
2451 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2452 WIDTH and HEIGHT are integers > 0. DATA may be:
2454 1. a string large enough to hold the bitmap data, i.e. it must
2455 have a size >= (WIDTH + 7) / 8 * HEIGHT
2457 2. a bool-vector of size >= WIDTH * HEIGHT
2459 3. a vector of strings or bool-vectors, one for each line of the
2460 bitmap.
2462 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2463 may not be specified in this case because they are defined in the
2464 XBM file.
2466 Both the file and data forms may contain the additional entries
2467 `:background COLOR' and `:foreground COLOR'. If not present,
2468 foreground and background of the frame on which the image is
2469 displayed is used. */
2471 static bool
2472 xbm_image_p (Lisp_Object object)
2474 struct image_keyword kw[XBM_LAST];
2476 memcpy (kw, xbm_format, sizeof kw);
2477 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2478 return 0;
2480 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2482 if (kw[XBM_FILE].count)
2484 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2485 return 0;
2487 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2489 /* In-memory XBM file. */
2490 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2491 return 0;
2493 else
2495 Lisp_Object data;
2496 int width, height;
2498 /* Entries for `:width', `:height' and `:data' must be present. */
2499 if (!kw[XBM_WIDTH].count
2500 || !kw[XBM_HEIGHT].count
2501 || !kw[XBM_DATA].count)
2502 return 0;
2504 data = kw[XBM_DATA].value;
2505 width = XFASTINT (kw[XBM_WIDTH].value);
2506 height = XFASTINT (kw[XBM_HEIGHT].value);
2508 /* Check type of data, and width and height against contents of
2509 data. */
2510 if (VECTORP (data))
2512 EMACS_INT i;
2514 /* Number of elements of the vector must be >= height. */
2515 if (ASIZE (data) < height)
2516 return 0;
2518 /* Each string or bool-vector in data must be large enough
2519 for one line of the image. */
2520 for (i = 0; i < height; ++i)
2522 Lisp_Object elt = AREF (data, i);
2524 if (STRINGP (elt))
2526 if (SCHARS (elt)
2527 < (width + CHAR_BIT - 1) / CHAR_BIT)
2528 return 0;
2530 else if (BOOL_VECTOR_P (elt))
2532 if (bool_vector_size (elt) < width)
2533 return 0;
2535 else
2536 return 0;
2539 else if (STRINGP (data))
2541 if (SCHARS (data)
2542 < (width + CHAR_BIT - 1) / CHAR_BIT * height)
2543 return 0;
2545 else if (BOOL_VECTOR_P (data))
2547 if (bool_vector_size (data) / height < width)
2548 return 0;
2550 else
2551 return 0;
2554 return 1;
2558 /* Scan a bitmap file. FP is the stream to read from. Value is
2559 either an enumerator from enum xbm_token, or a character for a
2560 single-character token, or 0 at end of file. If scanning an
2561 identifier, store the lexeme of the identifier in SVAL. If
2562 scanning a number, store its value in *IVAL. */
2564 static int
2565 xbm_scan (char **s, char *end, char *sval, int *ival)
2567 unsigned char c;
2569 loop:
2571 /* Skip white space. */
2572 while (*s < end && (c = *(*s)++, c_isspace (c)))
2575 if (*s >= end)
2576 c = 0;
2577 else if (c_isdigit (c))
2579 int value = 0, digit;
2581 if (c == '0' && *s < end)
2583 c = *(*s)++;
2584 if (c == 'x' || c == 'X')
2586 while (*s < end)
2588 c = *(*s)++;
2589 if (c_isdigit (c))
2590 digit = c - '0';
2591 else if (c >= 'a' && c <= 'f')
2592 digit = c - 'a' + 10;
2593 else if (c >= 'A' && c <= 'F')
2594 digit = c - 'A' + 10;
2595 else
2596 break;
2597 value = 16 * value + digit;
2600 else if (c_isdigit (c))
2602 value = c - '0';
2603 while (*s < end
2604 && (c = *(*s)++, c_isdigit (c)))
2605 value = 8 * value + c - '0';
2608 else
2610 value = c - '0';
2611 while (*s < end
2612 && (c = *(*s)++, c_isdigit (c)))
2613 value = 10 * value + c - '0';
2616 if (*s < end)
2617 *s = *s - 1;
2618 *ival = value;
2619 return XBM_TK_NUMBER;
2621 else if (c_isalpha (c) || c == '_')
2623 *sval++ = c;
2624 while (*s < end
2625 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2626 *sval++ = c;
2627 *sval = 0;
2628 if (*s < end)
2629 *s = *s - 1;
2630 return XBM_TK_IDENT;
2632 else if (c == '/' && **s == '*')
2634 /* C-style comment. */
2635 ++*s;
2636 while (**s && (**s != '*' || *(*s + 1) != '/'))
2637 ++*s;
2638 if (**s)
2640 *s += 2;
2641 goto loop;
2645 return c;
2648 #ifdef HAVE_NTGUI
2650 /* Create a Windows bitmap from X bitmap data. */
2651 static HBITMAP
2652 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2654 static unsigned char swap_nibble[16]
2655 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2656 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2657 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2658 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2659 int i, j, w1, w2;
2660 unsigned char *bits, *p;
2661 HBITMAP bmp;
2663 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2664 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2665 bits = alloca (height * w2);
2666 memset (bits, 0, height * w2);
2667 for (i = 0; i < height; i++)
2669 p = bits + i*w2;
2670 for (j = 0; j < w1; j++)
2672 /* Bitswap XBM bytes to match how Windows does things. */
2673 unsigned char c = *data++;
2674 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2675 | (swap_nibble[(c>>4) & 0xf]));
2678 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2680 return bmp;
2683 static void
2684 convert_mono_to_color_image (struct frame *f, struct image *img,
2685 COLORREF foreground, COLORREF background)
2687 HDC hdc, old_img_dc, new_img_dc;
2688 HGDIOBJ old_prev, new_prev;
2689 HBITMAP new_pixmap;
2691 hdc = get_frame_dc (f);
2692 old_img_dc = CreateCompatibleDC (hdc);
2693 new_img_dc = CreateCompatibleDC (hdc);
2694 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2695 release_frame_dc (f, hdc);
2696 old_prev = SelectObject (old_img_dc, img->pixmap);
2697 new_prev = SelectObject (new_img_dc, new_pixmap);
2698 /* Windows convention for mono bitmaps is black = background,
2699 white = foreground. */
2700 SetTextColor (new_img_dc, background);
2701 SetBkColor (new_img_dc, foreground);
2703 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2704 0, 0, SRCCOPY);
2706 SelectObject (old_img_dc, old_prev);
2707 SelectObject (new_img_dc, new_prev);
2708 DeleteDC (old_img_dc);
2709 DeleteDC (new_img_dc);
2710 DeleteObject (img->pixmap);
2711 if (new_pixmap == 0)
2712 fprintf (stderr, "Failed to convert image to color.\n");
2713 else
2714 img->pixmap = new_pixmap;
2717 #define XBM_BIT_SHUFFLE(b) (~(b))
2719 #else
2721 #define XBM_BIT_SHUFFLE(b) (b)
2723 #endif /* HAVE_NTGUI */
2726 static void
2727 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2728 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2729 bool non_default_colors)
2731 #ifdef HAVE_NTGUI
2732 img->pixmap
2733 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2735 /* If colors were specified, transfer the bitmap to a color one. */
2736 if (non_default_colors)
2737 convert_mono_to_color_image (f, img, fg, bg);
2739 #elif defined (HAVE_NS)
2740 img->pixmap = ns_image_from_XBM (data, img->width, img->height, fg, bg);
2742 #else
2743 img->pixmap =
2744 (x_check_image_size (0, img->width, img->height)
2745 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2746 FRAME_X_DRAWABLE (f),
2747 data,
2748 img->width, img->height,
2749 fg, bg,
2750 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2751 : NO_PIXMAP);
2752 #endif /* !HAVE_NTGUI && !HAVE_NS */
2757 /* Replacement for XReadBitmapFileData which isn't available under old
2758 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2759 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2760 the image. Return in *DATA the bitmap data allocated with xmalloc.
2761 Value is true if successful. DATA null means just test if
2762 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2763 inhibit the call to image_error when the image size is invalid (the
2764 bitmap remains unread). */
2766 static bool
2767 xbm_read_bitmap_data (struct frame *f, char *contents, char *end,
2768 int *width, int *height, char **data,
2769 bool inhibit_image_error)
2771 char *s = contents;
2772 char buffer[BUFSIZ];
2773 bool padding_p = 0;
2774 bool v10 = 0;
2775 int bytes_per_line, i, nbytes;
2776 char *p;
2777 int value;
2778 int LA1;
2780 #define match() \
2781 LA1 = xbm_scan (&s, end, buffer, &value)
2783 #define expect(TOKEN) \
2784 do \
2786 if (LA1 != (TOKEN)) \
2787 goto failure; \
2788 match (); \
2790 while (0)
2792 #define expect_ident(IDENT) \
2793 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2794 match (); \
2795 else \
2796 goto failure
2798 *width = *height = -1;
2799 if (data)
2800 *data = NULL;
2801 LA1 = xbm_scan (&s, end, buffer, &value);
2803 /* Parse defines for width, height and hot-spots. */
2804 while (LA1 == '#')
2806 match ();
2807 expect_ident ("define");
2808 expect (XBM_TK_IDENT);
2810 if (LA1 == XBM_TK_NUMBER)
2812 char *q = strrchr (buffer, '_');
2813 q = q ? q + 1 : buffer;
2814 if (strcmp (q, "width") == 0)
2815 *width = value;
2816 else if (strcmp (q, "height") == 0)
2817 *height = value;
2819 expect (XBM_TK_NUMBER);
2822 if (!check_image_size (f, *width, *height))
2824 if (!inhibit_image_error)
2825 image_size_error ();
2826 goto failure;
2828 else if (data == NULL)
2829 goto success;
2831 /* Parse bits. Must start with `static'. */
2832 expect_ident ("static");
2833 if (LA1 == XBM_TK_IDENT)
2835 if (strcmp (buffer, "unsigned") == 0)
2837 match ();
2838 expect_ident ("char");
2840 else if (strcmp (buffer, "short") == 0)
2842 match ();
2843 v10 = 1;
2844 if (*width % 16 && *width % 16 < 9)
2845 padding_p = 1;
2847 else if (strcmp (buffer, "char") == 0)
2848 match ();
2849 else
2850 goto failure;
2852 else
2853 goto failure;
2855 expect (XBM_TK_IDENT);
2856 expect ('[');
2857 expect (']');
2858 expect ('=');
2859 expect ('{');
2861 if (! x_check_image_size (0, *width, *height))
2863 if (!inhibit_image_error)
2864 image_error ("Image too large (%dx%d)",
2865 make_number (*width), make_number (*height));
2866 goto failure;
2868 bytes_per_line = (*width + 7) / 8 + padding_p;
2869 nbytes = bytes_per_line * *height;
2870 p = *data = xmalloc (nbytes);
2872 if (v10)
2874 for (i = 0; i < nbytes; i += 2)
2876 int val = value;
2877 expect (XBM_TK_NUMBER);
2879 *p++ = XBM_BIT_SHUFFLE (val);
2880 if (!padding_p || ((i + 2) % bytes_per_line))
2881 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2883 if (LA1 == ',' || LA1 == '}')
2884 match ();
2885 else
2886 goto failure;
2889 else
2891 for (i = 0; i < nbytes; ++i)
2893 int val = value;
2894 expect (XBM_TK_NUMBER);
2896 *p++ = XBM_BIT_SHUFFLE (val);
2898 if (LA1 == ',' || LA1 == '}')
2899 match ();
2900 else
2901 goto failure;
2905 success:
2906 return 1;
2908 failure:
2910 if (data && *data)
2912 xfree (*data);
2913 *data = NULL;
2915 return 0;
2917 #undef match
2918 #undef expect
2919 #undef expect_ident
2923 /* Load XBM image IMG which will be displayed on frame F from buffer
2924 CONTENTS. END is the end of the buffer. Value is true if
2925 successful. */
2927 static bool
2928 xbm_load_image (struct frame *f, struct image *img, char *contents, char *end)
2930 bool rc;
2931 char *data;
2932 bool success_p = 0;
2934 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2935 &data, 0);
2936 if (rc)
2938 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2939 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2940 bool non_default_colors = 0;
2941 Lisp_Object value;
2943 eassert (img->width > 0 && img->height > 0);
2945 /* Get foreground and background colors, maybe allocate colors. */
2946 value = image_spec_value (img->spec, QCforeground, NULL);
2947 if (!NILP (value))
2949 foreground = x_alloc_image_color (f, img, value, foreground);
2950 non_default_colors = 1;
2952 value = image_spec_value (img->spec, QCbackground, NULL);
2953 if (!NILP (value))
2955 background = x_alloc_image_color (f, img, value, background);
2956 img->background = background;
2957 img->background_valid = 1;
2958 non_default_colors = 1;
2961 Create_Pixmap_From_Bitmap_Data (f, img, data,
2962 foreground, background,
2963 non_default_colors);
2964 xfree (data);
2966 if (img->pixmap == NO_PIXMAP)
2968 x_clear_image (f, img);
2969 image_error ("Unable to create X pixmap for `%s'", img->spec);
2971 else
2972 success_p = 1;
2974 else
2975 image_error ("Error loading XBM image `%s'", img->spec);
2977 return success_p;
2981 /* Value is true if DATA looks like an in-memory XBM file. */
2983 static bool
2984 xbm_file_p (Lisp_Object data)
2986 int w, h;
2987 return (STRINGP (data)
2988 && xbm_read_bitmap_data (NULL, SSDATA (data),
2989 SSDATA (data) + SBYTES (data),
2990 &w, &h, NULL, 1));
2994 /* Fill image IMG which is used on frame F with pixmap data. Value is
2995 true if successful. */
2997 static bool
2998 xbm_load (struct frame *f, struct image *img)
3000 bool success_p = 0;
3001 Lisp_Object file_name;
3003 eassert (xbm_image_p (img->spec));
3005 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3006 file_name = image_spec_value (img->spec, QCfile, NULL);
3007 if (STRINGP (file_name))
3009 int fd;
3010 Lisp_Object file = x_find_image_fd (file_name, &fd);
3011 if (!STRINGP (file))
3013 image_error ("Cannot find image file `%s'", file_name);
3014 return 0;
3017 ptrdiff_t size;
3018 char *contents = slurp_file (fd, &size);
3019 if (contents == NULL)
3021 image_error ("Error loading XBM image `%s'", file);
3022 return 0;
3025 success_p = xbm_load_image (f, img, contents, contents + size);
3026 xfree (contents);
3028 else
3030 struct image_keyword fmt[XBM_LAST];
3031 Lisp_Object data;
3032 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3033 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3034 bool non_default_colors = 0;
3035 char *bits;
3036 bool parsed_p;
3037 bool in_memory_file_p = 0;
3039 /* See if data looks like an in-memory XBM file. */
3040 data = image_spec_value (img->spec, QCdata, NULL);
3041 in_memory_file_p = xbm_file_p (data);
3043 /* Parse the image specification. */
3044 memcpy (fmt, xbm_format, sizeof fmt);
3045 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3046 eassert (parsed_p);
3048 /* Get specified width, and height. */
3049 if (!in_memory_file_p)
3051 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3052 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3053 eassert (img->width > 0 && img->height > 0);
3054 if (!check_image_size (f, img->width, img->height))
3056 image_size_error ();
3057 return 0;
3061 /* Get foreground and background colors, maybe allocate colors. */
3062 if (fmt[XBM_FOREGROUND].count
3063 && STRINGP (fmt[XBM_FOREGROUND].value))
3065 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3066 foreground);
3067 non_default_colors = 1;
3070 if (fmt[XBM_BACKGROUND].count
3071 && STRINGP (fmt[XBM_BACKGROUND].value))
3073 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3074 background);
3075 non_default_colors = 1;
3078 if (in_memory_file_p)
3079 success_p = xbm_load_image (f, img, SSDATA (data),
3080 SSDATA (data) + SBYTES (data));
3081 else
3083 USE_SAFE_ALLOCA;
3085 if (VECTORP (data))
3087 int i;
3088 char *p;
3089 int nbytes = (img->width + CHAR_BIT - 1) / CHAR_BIT;
3091 SAFE_NALLOCA (bits, nbytes, img->height);
3092 p = bits;
3093 for (i = 0; i < img->height; ++i, p += nbytes)
3095 Lisp_Object line = AREF (data, i);
3096 if (STRINGP (line))
3097 memcpy (p, SDATA (line), nbytes);
3098 else
3099 memcpy (p, bool_vector_data (line), nbytes);
3102 else if (STRINGP (data))
3103 bits = SSDATA (data);
3104 else
3105 bits = (char *) bool_vector_data (data);
3107 #ifdef HAVE_NTGUI
3109 char *invertedBits;
3110 int nbytes, i;
3111 /* Windows mono bitmaps are reversed compared with X. */
3112 invertedBits = bits;
3113 nbytes = (img->width + CHAR_BIT - 1) / CHAR_BIT;
3114 SAFE_NALLOCA (bits, nbytes, img->height);
3115 for (i = 0; i < nbytes; i++)
3116 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3118 #endif
3119 /* Create the pixmap. */
3121 if (x_check_image_size (0, img->width, img->height))
3122 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3123 foreground, background,
3124 non_default_colors);
3125 else
3126 img->pixmap = NO_PIXMAP;
3128 if (img->pixmap)
3129 success_p = 1;
3130 else
3132 image_error ("Unable to create pixmap for XBM image `%s'",
3133 img->spec);
3134 x_clear_image (f, img);
3137 SAFE_FREE ();
3141 return success_p;
3146 /***********************************************************************
3147 XPM images
3148 ***********************************************************************/
3150 #if defined (HAVE_XPM) || defined (HAVE_NS)
3152 static bool xpm_image_p (Lisp_Object object);
3153 static bool xpm_load (struct frame *f, struct image *img);
3155 #endif /* HAVE_XPM || HAVE_NS */
3157 #ifdef HAVE_XPM
3158 #ifdef HAVE_NTGUI
3159 /* Indicate to xpm.h that we don't have Xlib. */
3160 #define FOR_MSW
3161 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3162 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3163 #define XColor xpm_XColor
3164 #define XImage xpm_XImage
3165 #define Display xpm_Display
3166 #ifdef CYGWIN
3167 #include "noX/xpm.h"
3168 #else /* not CYGWIN */
3169 #include "X11/xpm.h"
3170 #endif /* not CYGWIN */
3171 #undef FOR_MSW
3172 #undef XColor
3173 #undef XImage
3174 #undef Display
3175 #else /* not HAVE_NTGUI */
3176 #include "X11/xpm.h"
3177 #endif /* not HAVE_NTGUI */
3178 #endif /* HAVE_XPM */
3180 #if defined (HAVE_XPM) || defined (HAVE_NS)
3182 /* Indices of image specification fields in xpm_format, below. */
3184 enum xpm_keyword_index
3186 XPM_TYPE,
3187 XPM_FILE,
3188 XPM_DATA,
3189 XPM_ASCENT,
3190 XPM_MARGIN,
3191 XPM_RELIEF,
3192 XPM_ALGORITHM,
3193 XPM_HEURISTIC_MASK,
3194 XPM_MASK,
3195 XPM_COLOR_SYMBOLS,
3196 XPM_BACKGROUND,
3197 XPM_LAST
3200 /* Vector of image_keyword structures describing the format
3201 of valid XPM image specifications. */
3203 static const struct image_keyword xpm_format[XPM_LAST] =
3205 {":type", IMAGE_SYMBOL_VALUE, 1},
3206 {":file", IMAGE_STRING_VALUE, 0},
3207 {":data", IMAGE_STRING_VALUE, 0},
3208 {":ascent", IMAGE_ASCENT_VALUE, 0},
3209 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3210 {":relief", IMAGE_INTEGER_VALUE, 0},
3211 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3212 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3213 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3214 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3215 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3218 #if defined HAVE_NTGUI && defined WINDOWSNT
3219 static bool init_xpm_functions (void);
3220 #else
3221 #define init_xpm_functions NULL
3222 #endif
3224 /* Structure describing the image type XPM. */
3226 static struct image_type xpm_type =
3228 SYMBOL_INDEX (Qxpm),
3229 xpm_image_p,
3230 xpm_load,
3231 x_clear_image,
3232 init_xpm_functions,
3233 NULL
3236 #ifdef HAVE_X_WINDOWS
3238 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3239 functions for allocating image colors. Our own functions handle
3240 color allocation failures more gracefully than the ones on the XPM
3241 lib. */
3243 #ifndef USE_CAIRO
3244 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3245 #define ALLOC_XPM_COLORS
3246 #endif
3247 #endif /* USE_CAIRO */
3248 #endif /* HAVE_X_WINDOWS */
3250 #ifdef ALLOC_XPM_COLORS
3252 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3253 XColor *, int);
3255 /* An entry in a hash table used to cache color definitions of named
3256 colors. This cache is necessary to speed up XPM image loading in
3257 case we do color allocations ourselves. Without it, we would need
3258 a call to XParseColor per pixel in the image.
3260 FIXME Now that we're using x_parse_color and its cache, reevaluate
3261 the need for this caching layer. */
3263 struct xpm_cached_color
3265 /* Next in collision chain. */
3266 struct xpm_cached_color *next;
3268 /* Color definition (RGB and pixel color). */
3269 XColor color;
3271 /* Color name. */
3272 char name[FLEXIBLE_ARRAY_MEMBER];
3275 /* The hash table used for the color cache, and its bucket vector
3276 size. */
3278 #define XPM_COLOR_CACHE_BUCKETS 1001
3279 static struct xpm_cached_color **xpm_color_cache;
3281 /* Initialize the color cache. */
3283 static void
3284 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3286 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3287 xpm_color_cache = xzalloc (nbytes);
3288 init_color_table ();
3290 if (attrs->valuemask & XpmColorSymbols)
3292 int i;
3293 XColor color;
3295 for (i = 0; i < attrs->numsymbols; ++i)
3296 if (x_parse_color (f, attrs->colorsymbols[i].value, &color))
3298 color.pixel = lookup_rgb_color (f, color.red, color.green,
3299 color.blue);
3300 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3305 /* Free the color cache. */
3307 static void
3308 xpm_free_color_cache (void)
3310 struct xpm_cached_color *p, *next;
3311 int i;
3313 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3314 for (p = xpm_color_cache[i]; p; p = next)
3316 next = p->next;
3317 xfree (p);
3320 xfree (xpm_color_cache);
3321 xpm_color_cache = NULL;
3322 free_color_table ();
3325 /* Return the bucket index for color named COLOR_NAME in the color
3326 cache. */
3328 static int
3329 xpm_color_bucket (char *color_name)
3331 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3332 return hash % XPM_COLOR_CACHE_BUCKETS;
3336 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3337 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3338 entry added. */
3340 static struct xpm_cached_color *
3341 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3343 size_t nbytes;
3344 struct xpm_cached_color *p;
3346 if (bucket < 0)
3347 bucket = xpm_color_bucket (color_name);
3349 nbytes = FLEXSIZEOF (struct xpm_cached_color, name, strlen (color_name) + 1);
3350 p = xmalloc (nbytes);
3351 strcpy (p->name, color_name);
3352 p->color = *color;
3353 p->next = xpm_color_cache[bucket];
3354 xpm_color_cache[bucket] = p;
3355 return p;
3358 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3359 return the cached definition in *COLOR. Otherwise, make a new
3360 entry in the cache and allocate the color. Value is false if color
3361 allocation failed. */
3363 static bool
3364 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3366 struct xpm_cached_color *p;
3367 int h = xpm_color_bucket (color_name);
3369 for (p = xpm_color_cache[h]; p; p = p->next)
3370 if (strcmp (p->name, color_name) == 0)
3371 break;
3373 if (p != NULL)
3374 *color = p->color;
3375 else if (x_parse_color (f, color_name, color))
3377 color->pixel = lookup_rgb_color (f, color->red, color->green,
3378 color->blue);
3379 p = xpm_cache_color (f, color_name, color, h);
3381 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3382 with transparency, and it's useful. */
3383 else if (strcmp ("opaque", color_name) == 0)
3385 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3386 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3387 p = xpm_cache_color (f, color_name, color, h);
3390 return p != NULL;
3394 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3395 CLOSURE is a pointer to the frame on which we allocate the
3396 color. Return in *COLOR the allocated color. Value is non-zero
3397 if successful. */
3399 static int
3400 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3401 void *closure)
3403 return xpm_lookup_color (closure, color_name, color);
3407 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3408 is a pointer to the frame on which we allocate the color. Value is
3409 non-zero if successful. */
3411 static int
3412 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3414 return 1;
3417 #endif /* ALLOC_XPM_COLORS */
3420 #ifdef WINDOWSNT
3422 /* XPM library details. */
3424 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3425 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3426 (Display *, char *, xpm_XImage **,
3427 xpm_XImage **, XpmAttributes *));
3428 DEF_DLL_FN (int, XpmReadFileToImage,
3429 (Display *, char *, xpm_XImage **,
3430 xpm_XImage **, XpmAttributes *));
3431 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3433 static bool
3434 init_xpm_functions (void)
3436 HMODULE library;
3438 if (!(library = w32_delayed_load (Qxpm)))
3439 return 0;
3441 LOAD_DLL_FN (library, XpmFreeAttributes);
3442 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3443 LOAD_DLL_FN (library, XpmReadFileToImage);
3444 LOAD_DLL_FN (library, XImageFree);
3445 return 1;
3448 # undef XImageFree
3449 # undef XpmCreateImageFromBuffer
3450 # undef XpmFreeAttributes
3451 # undef XpmReadFileToImage
3453 # define XImageFree fn_XImageFree
3454 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3455 # define XpmFreeAttributes fn_XpmFreeAttributes
3456 # define XpmReadFileToImage fn_XpmReadFileToImage
3458 #endif /* WINDOWSNT */
3460 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3461 for XPM images. Such a list must consist of conses whose car and
3462 cdr are strings. */
3464 static bool
3465 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3467 while (CONSP (color_symbols))
3469 Lisp_Object sym = XCAR (color_symbols);
3470 if (!CONSP (sym)
3471 || !STRINGP (XCAR (sym))
3472 || !STRINGP (XCDR (sym)))
3473 break;
3474 color_symbols = XCDR (color_symbols);
3477 return NILP (color_symbols);
3481 /* Value is true if OBJECT is a valid XPM image specification. */
3483 static bool
3484 xpm_image_p (Lisp_Object object)
3486 struct image_keyword fmt[XPM_LAST];
3487 memcpy (fmt, xpm_format, sizeof fmt);
3488 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3489 /* Either `:file' or `:data' must be present. */
3490 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3491 /* Either no `:color-symbols' or it's a list of conses
3492 whose car and cdr are strings. */
3493 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3494 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3497 #endif /* HAVE_XPM || HAVE_NS */
3499 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3500 ptrdiff_t
3501 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3503 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3504 ptrdiff_t id;
3505 int rc;
3506 XpmAttributes attrs;
3507 Pixmap bitmap, mask;
3509 memset (&attrs, 0, sizeof attrs);
3511 attrs.visual = FRAME_X_VISUAL (f);
3512 attrs.colormap = FRAME_X_COLORMAP (f);
3513 attrs.valuemask |= XpmVisual;
3514 attrs.valuemask |= XpmColormap;
3516 #ifdef ALLOC_XPM_COLORS
3517 attrs.color_closure = f;
3518 attrs.alloc_color = xpm_alloc_color;
3519 attrs.free_colors = xpm_free_colors;
3520 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3521 xpm_init_color_cache (f, &attrs);
3522 #endif
3524 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
3525 (char **) bits, &bitmap, &mask, &attrs);
3526 if (rc != XpmSuccess)
3528 XpmFreeAttributes (&attrs);
3529 return -1;
3532 id = x_allocate_bitmap_record (f);
3533 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3534 dpyinfo->bitmaps[id - 1].have_mask = true;
3535 dpyinfo->bitmaps[id - 1].mask = mask;
3536 dpyinfo->bitmaps[id - 1].file = NULL;
3537 dpyinfo->bitmaps[id - 1].height = attrs.height;
3538 dpyinfo->bitmaps[id - 1].width = attrs.width;
3539 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3540 dpyinfo->bitmaps[id - 1].refcount = 1;
3542 #ifdef ALLOC_XPM_COLORS
3543 xpm_free_color_cache ();
3544 #endif
3545 XpmFreeAttributes (&attrs);
3546 return id;
3548 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3550 /* Load image IMG which will be displayed on frame F. Value is
3551 true if successful. */
3553 #ifdef HAVE_XPM
3555 static bool
3556 xpm_load (struct frame *f, struct image *img)
3558 int rc;
3559 XpmAttributes attrs;
3560 Lisp_Object specified_file, color_symbols;
3561 USE_SAFE_ALLOCA;
3563 #ifdef HAVE_NTGUI
3564 HDC hdc;
3565 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3566 #endif /* HAVE_NTGUI */
3568 /* Configure the XPM lib. Use the visual of frame F. Allocate
3569 close colors. Return colors allocated. */
3570 memset (&attrs, 0, sizeof attrs);
3572 #ifndef HAVE_NTGUI
3573 attrs.visual = FRAME_X_VISUAL (f);
3574 attrs.colormap = FRAME_X_COLORMAP (f);
3575 attrs.valuemask |= XpmVisual;
3576 attrs.valuemask |= XpmColormap;
3577 #endif /* HAVE_NTGUI */
3579 #ifdef ALLOC_XPM_COLORS
3580 /* Allocate colors with our own functions which handle
3581 failing color allocation more gracefully. */
3582 attrs.color_closure = f;
3583 attrs.alloc_color = xpm_alloc_color;
3584 attrs.free_colors = xpm_free_colors;
3585 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3586 #else /* not ALLOC_XPM_COLORS */
3587 /* Let the XPM lib allocate colors. */
3588 attrs.valuemask |= XpmReturnAllocPixels;
3589 #ifdef XpmAllocCloseColors
3590 attrs.alloc_close_colors = 1;
3591 attrs.valuemask |= XpmAllocCloseColors;
3592 #else /* not XpmAllocCloseColors */
3593 attrs.closeness = 600;
3594 attrs.valuemask |= XpmCloseness;
3595 #endif /* not XpmAllocCloseColors */
3596 #endif /* ALLOC_XPM_COLORS */
3598 /* If image specification contains symbolic color definitions, add
3599 these to `attrs'. */
3600 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3601 if (CONSP (color_symbols))
3603 Lisp_Object tail;
3604 XpmColorSymbol *xpm_syms;
3605 ptrdiff_t i, size;
3607 attrs.valuemask |= XpmColorSymbols;
3609 /* Count number of symbols. */
3610 attrs.numsymbols = 0;
3611 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3612 ++attrs.numsymbols;
3614 /* Allocate an XpmColorSymbol array. */
3615 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3616 size = attrs.numsymbols * sizeof *xpm_syms;
3617 memset (xpm_syms, 0, size);
3618 attrs.colorsymbols = xpm_syms;
3620 /* Fill the color symbol array. */
3621 for (tail = color_symbols, i = 0;
3622 CONSP (tail);
3623 ++i, tail = XCDR (tail))
3625 Lisp_Object name;
3626 Lisp_Object color;
3627 char *empty_string = (char *) "";
3629 if (!CONSP (XCAR (tail)))
3631 xpm_syms[i].name = empty_string;
3632 xpm_syms[i].value = empty_string;
3633 continue;
3635 name = XCAR (XCAR (tail));
3636 color = XCDR (XCAR (tail));
3637 if (STRINGP (name))
3638 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3639 else
3640 xpm_syms[i].name = empty_string;
3641 if (STRINGP (color))
3642 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3643 else
3644 xpm_syms[i].value = empty_string;
3648 /* Create a pixmap for the image, either from a file, or from a
3649 string buffer containing data in the same format as an XPM file. */
3650 #ifdef ALLOC_XPM_COLORS
3651 xpm_init_color_cache (f, &attrs);
3652 #endif
3654 specified_file = image_spec_value (img->spec, QCfile, NULL);
3656 #ifdef HAVE_NTGUI
3658 HDC frame_dc = get_frame_dc (f);
3659 hdc = CreateCompatibleDC (frame_dc);
3660 release_frame_dc (f, frame_dc);
3662 #endif /* HAVE_NTGUI */
3664 if (STRINGP (specified_file))
3666 Lisp_Object file = x_find_image_file (specified_file);
3667 if (!STRINGP (file))
3669 image_error ("Cannot find image file `%s'", specified_file);
3670 #ifdef ALLOC_XPM_COLORS
3671 xpm_free_color_cache ();
3672 #endif
3673 SAFE_FREE ();
3674 return 0;
3677 file = ENCODE_FILE (file);
3678 #ifdef HAVE_NTGUI
3679 #ifdef WINDOWSNT
3680 /* FILE is encoded in UTF-8, but image libraries on Windows
3681 support neither UTF-8 nor UTF-16 encoded file names. So we
3682 need to re-encode it in ANSI. */
3683 file = ansi_encode_filename (file);
3684 #endif
3685 /* XpmReadFileToPixmap is not available in the Windows port of
3686 libxpm. But XpmReadFileToImage almost does what we want. */
3687 rc = XpmReadFileToImage (&hdc, SSDATA (file),
3688 &xpm_image, &xpm_mask,
3689 &attrs);
3690 #else
3691 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3692 &img->ximg, &img->mask_img,
3693 &attrs);
3694 #endif /* HAVE_NTGUI */
3696 else
3698 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3699 if (!STRINGP (buffer))
3701 image_error ("Invalid image data `%s'", buffer);
3702 #ifdef ALLOC_XPM_COLORS
3703 xpm_free_color_cache ();
3704 #endif
3705 SAFE_FREE ();
3706 return 0;
3708 #ifdef HAVE_NTGUI
3709 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3710 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3711 rc = XpmCreateImageFromBuffer (&hdc, SSDATA (buffer),
3712 &xpm_image, &xpm_mask,
3713 &attrs);
3714 #else
3715 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3716 &img->ximg, &img->mask_img,
3717 &attrs);
3718 #endif /* HAVE_NTGUI */
3721 #ifdef USE_CAIRO
3722 /* Load very specific Xpm:s. */
3723 if (rc == XpmSuccess
3724 && img->ximg->format == ZPixmap
3725 && img->ximg->bits_per_pixel == 32
3726 && (! img->mask_img || img->mask_img->bits_per_pixel == 1))
3728 int width = img->ximg->width;
3729 int height = img->ximg->height;
3730 void *data = xmalloc (width * height * 4);
3731 int i;
3732 uint32_t *od = data;
3733 uint32_t *id = (uint32_t *) img->ximg->data;
3734 char *mid = img->mask_img ? img->mask_img->data : 0;
3735 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
3737 for (i = 0; i < height; ++i)
3739 int k;
3740 for (k = 0; k < width; ++k)
3742 int idx = i * img->ximg->bytes_per_line/4 + k;
3743 int maskidx = mid ? i * img->mask_img->bytes_per_line + k/8 : 0;
3744 int mask = mid ? mid[maskidx] & (1 << (k % 8)) : 1;
3746 if (mask) od[idx] = id[idx] + 0xff000000; /* ff => full alpha */
3747 else od[idx] = bgcolor;
3751 create_cairo_image_surface (img, data, width, height);
3753 else
3755 rc = XpmFileInvalid;
3756 x_clear_image (f, img);
3758 #else
3759 #ifdef HAVE_X_WINDOWS
3760 if (rc == XpmSuccess)
3762 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
3763 img->ximg->width, img->ximg->height,
3764 img->ximg->depth);
3765 if (img->pixmap == NO_PIXMAP)
3767 x_clear_image (f, img);
3768 rc = XpmNoMemory;
3770 else if (img->mask_img)
3772 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
3773 img->mask_img->width,
3774 img->mask_img->height,
3775 img->mask_img->depth);
3776 if (img->mask == NO_PIXMAP)
3778 x_clear_image (f, img);
3779 rc = XpmNoMemory;
3783 #endif
3784 #endif /* ! USE_CAIRO */
3786 if (rc == XpmSuccess)
3788 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3789 img->colors = colors_in_color_table (&img->ncolors);
3790 #else /* not ALLOC_XPM_COLORS */
3791 int i;
3793 #ifdef HAVE_NTGUI
3794 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3795 plus some duplicate attributes. */
3796 if (xpm_image && xpm_image->bitmap)
3798 img->pixmap = xpm_image->bitmap;
3799 /* XImageFree in libXpm frees XImage struct without destroying
3800 the bitmap, which is what we want. */
3801 XImageFree (xpm_image);
3803 if (xpm_mask && xpm_mask->bitmap)
3805 /* The mask appears to be inverted compared with what we expect.
3806 TODO: invert our expectations. See other places where we
3807 have to invert bits because our idea of masks is backwards. */
3808 HGDIOBJ old_obj;
3809 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3811 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3812 SelectObject (hdc, old_obj);
3814 img->mask = xpm_mask->bitmap;
3815 XImageFree (xpm_mask);
3816 DeleteDC (hdc);
3819 DeleteDC (hdc);
3820 #endif /* HAVE_NTGUI */
3822 /* Remember allocated colors. */
3823 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3824 img->ncolors = attrs.nalloc_pixels;
3825 for (i = 0; i < attrs.nalloc_pixels; ++i)
3827 img->colors[i] = attrs.alloc_pixels[i];
3828 #ifdef DEBUG_X_COLORS
3829 register_color (img->colors[i]);
3830 #endif
3832 #endif /* not ALLOC_XPM_COLORS */
3834 img->width = attrs.width;
3835 img->height = attrs.height;
3836 eassert (img->width > 0 && img->height > 0);
3838 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3839 XpmFreeAttributes (&attrs);
3841 #ifdef HAVE_X_WINDOWS
3842 /* Maybe fill in the background field while we have ximg handy. */
3843 IMAGE_BACKGROUND (img, f, img->ximg);
3844 if (img->mask_img)
3845 /* Fill in the background_transparent field while we have the
3846 mask handy. */
3847 image_background_transparent (img, f, img->mask_img);
3848 #endif
3850 else
3852 #ifdef HAVE_NTGUI
3853 DeleteDC (hdc);
3854 #endif /* HAVE_NTGUI */
3856 switch (rc)
3858 case XpmOpenFailed:
3859 image_error ("Error opening XPM file (%s)", img->spec);
3860 break;
3862 case XpmFileInvalid:
3863 image_error ("Invalid XPM file (%s)", img->spec);
3864 break;
3866 case XpmNoMemory:
3867 image_error ("Out of memory (%s)", img->spec);
3868 break;
3870 case XpmColorFailed:
3871 image_error ("Color allocation error (%s)", img->spec);
3872 break;
3874 default:
3875 image_error ("Unknown error (%s)", img->spec);
3876 break;
3880 #ifdef ALLOC_XPM_COLORS
3881 xpm_free_color_cache ();
3882 #endif
3883 SAFE_FREE ();
3884 return rc == XpmSuccess;
3887 #endif /* HAVE_XPM */
3889 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3891 /* XPM support functions for NS where libxpm is not available.
3892 Only XPM version 3 (without any extensions) is supported. */
3894 static void xpm_put_color_table_v (Lisp_Object, const char *,
3895 int, Lisp_Object);
3896 static Lisp_Object xpm_get_color_table_v (Lisp_Object, const char *, int);
3897 static void xpm_put_color_table_h (Lisp_Object, const char *,
3898 int, Lisp_Object);
3899 static Lisp_Object xpm_get_color_table_h (Lisp_Object, const char *, int);
3901 /* Tokens returned from xpm_scan. */
3903 enum xpm_token
3905 XPM_TK_IDENT = 256,
3906 XPM_TK_STRING,
3907 XPM_TK_EOF
3910 /* Scan an XPM data and return a character (< 256) or a token defined
3911 by enum xpm_token above. *S and END are the start (inclusive) and
3912 the end (exclusive) addresses of the data, respectively. Advance
3913 *S while scanning. If token is either XPM_TK_IDENT or
3914 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3915 length of the corresponding token, respectively. */
3917 static int
3918 xpm_scan (const char **s, const char *end, const char **beg, ptrdiff_t *len)
3920 unsigned char c;
3922 while (*s < end)
3924 /* Skip white-space. */
3925 while (*s < end && (c = *(*s)++, c_isspace (c)))
3928 /* gnus-pointer.xpm uses '-' in its identifier.
3929 sb-dir-plus.xpm uses '+' in its identifier. */
3930 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3932 *beg = *s - 1;
3933 while (*s < end
3934 && (c = **s, c_isalnum (c)
3935 || c == '_' || c == '-' || c == '+'))
3936 ++*s;
3937 *len = *s - *beg;
3938 return XPM_TK_IDENT;
3940 else if (c == '"')
3942 *beg = *s;
3943 while (*s < end && **s != '"')
3944 ++*s;
3945 *len = *s - *beg;
3946 if (*s < end)
3947 ++*s;
3948 return XPM_TK_STRING;
3950 else if (c == '/')
3952 if (*s < end && **s == '*')
3954 /* C-style comment. */
3955 ++*s;
3958 while (*s < end && *(*s)++ != '*')
3961 while (*s < end && **s != '/');
3962 if (*s < end)
3963 ++*s;
3965 else
3966 return c;
3968 else
3969 return c;
3972 return XPM_TK_EOF;
3975 /* Functions for color table lookup in XPM data. A key is a string
3976 specifying the color of each pixel in XPM data. A value is either
3977 an integer that specifies a pixel color, Qt that specifies
3978 transparency, or Qnil for the unspecified color. If the length of
3979 the key string is one, a vector is used as a table. Otherwise, a
3980 hash table is used. */
3982 static Lisp_Object
3983 xpm_make_color_table_v (void (**put_func) (Lisp_Object, const char *, int,
3984 Lisp_Object),
3985 Lisp_Object (**get_func) (Lisp_Object, const char *,
3986 int))
3988 *put_func = xpm_put_color_table_v;
3989 *get_func = xpm_get_color_table_v;
3990 return Fmake_vector (make_number (256), Qnil);
3993 static void
3994 xpm_put_color_table_v (Lisp_Object color_table,
3995 const char *chars_start,
3996 int chars_len,
3997 Lisp_Object color)
3999 unsigned char uc = *chars_start;
4000 ASET (color_table, uc, color);
4003 static Lisp_Object
4004 xpm_get_color_table_v (Lisp_Object color_table,
4005 const char *chars_start,
4006 int chars_len)
4008 unsigned char uc = *chars_start;
4009 return AREF (color_table, uc);
4012 static Lisp_Object
4013 xpm_make_color_table_h (void (**put_func) (Lisp_Object, const char *, int,
4014 Lisp_Object),
4015 Lisp_Object (**get_func) (Lisp_Object, const char *,
4016 int))
4018 *put_func = xpm_put_color_table_h;
4019 *get_func = xpm_get_color_table_h;
4020 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
4021 make_float (DEFAULT_REHASH_SIZE),
4022 make_float (DEFAULT_REHASH_THRESHOLD),
4023 Qnil);
4026 static void
4027 xpm_put_color_table_h (Lisp_Object color_table,
4028 const char *chars_start,
4029 int chars_len,
4030 Lisp_Object color)
4032 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4033 EMACS_UINT hash_code;
4034 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4036 hash_lookup (table, chars, &hash_code);
4037 hash_put (table, chars, color, hash_code);
4040 static Lisp_Object
4041 xpm_get_color_table_h (Lisp_Object color_table,
4042 const char *chars_start,
4043 int chars_len)
4045 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4046 ptrdiff_t i =
4047 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
4049 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4052 enum xpm_color_key {
4053 XPM_COLOR_KEY_S,
4054 XPM_COLOR_KEY_M,
4055 XPM_COLOR_KEY_G4,
4056 XPM_COLOR_KEY_G,
4057 XPM_COLOR_KEY_C
4060 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4062 static int
4063 xpm_str_to_color_key (const char *s)
4065 int i;
4067 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
4068 if (strcmp (xpm_color_key_strings[i], s) == 0)
4069 return i;
4070 return -1;
4073 static bool
4074 xpm_load_image (struct frame *f,
4075 struct image *img,
4076 const char *contents,
4077 const char *end)
4079 const char *s = contents, *beg, *str;
4080 char buffer[BUFSIZ];
4081 int width, height, x, y;
4082 int num_colors, chars_per_pixel;
4083 ptrdiff_t len;
4084 int LA1;
4085 void (*put_color_table) (Lisp_Object, const char *, int, Lisp_Object);
4086 Lisp_Object (*get_color_table) (Lisp_Object, const char *, int);
4087 Lisp_Object frame, color_symbols, color_table;
4088 int best_key;
4089 #ifndef HAVE_NS
4090 bool have_mask = false;
4091 #endif
4092 XImagePtr ximg = NULL, mask_img = NULL;
4094 #define match() \
4095 LA1 = xpm_scan (&s, end, &beg, &len)
4097 #define expect(TOKEN) \
4098 do \
4100 if (LA1 != (TOKEN)) \
4101 goto failure; \
4102 match (); \
4104 while (0)
4106 #define expect_ident(IDENT) \
4107 if (LA1 == XPM_TK_IDENT \
4108 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4109 match (); \
4110 else \
4111 goto failure
4113 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4114 goto failure;
4115 s += 9;
4116 match ();
4117 expect_ident ("static");
4118 expect_ident ("char");
4119 expect ('*');
4120 expect (XPM_TK_IDENT);
4121 expect ('[');
4122 expect (']');
4123 expect ('=');
4124 expect ('{');
4125 expect (XPM_TK_STRING);
4126 if (len >= BUFSIZ)
4127 goto failure;
4128 memcpy (buffer, beg, len);
4129 buffer[len] = '\0';
4130 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4131 &num_colors, &chars_per_pixel) != 4
4132 || width <= 0 || height <= 0
4133 || num_colors <= 0 || chars_per_pixel <= 0)
4134 goto failure;
4136 if (!check_image_size (f, width, height))
4138 image_size_error ();
4139 goto failure;
4142 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4143 #ifndef HAVE_NS
4144 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4145 &mask_img, 1)
4146 #endif
4149 image_error ("Image too large");
4150 goto failure;
4153 expect (',');
4155 XSETFRAME (frame, f);
4156 if (!NILP (Fxw_display_color_p (frame)))
4157 best_key = XPM_COLOR_KEY_C;
4158 else if (!NILP (Fx_display_grayscale_p (frame)))
4159 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4160 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4161 else
4162 best_key = XPM_COLOR_KEY_M;
4164 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4165 if (chars_per_pixel == 1)
4166 color_table = xpm_make_color_table_v (&put_color_table,
4167 &get_color_table);
4168 else
4169 color_table = xpm_make_color_table_h (&put_color_table,
4170 &get_color_table);
4172 while (num_colors-- > 0)
4174 char *color, *max_color;
4175 int key, next_key, max_key = 0;
4176 Lisp_Object symbol_color = Qnil, color_val;
4177 XColor cdef;
4179 expect (XPM_TK_STRING);
4180 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4181 goto failure;
4182 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4183 buffer[len - chars_per_pixel] = '\0';
4185 str = strtok (buffer, " \t");
4186 if (str == NULL)
4187 goto failure;
4188 key = xpm_str_to_color_key (str);
4189 if (key < 0)
4190 goto failure;
4193 color = strtok (NULL, " \t");
4194 if (color == NULL)
4195 goto failure;
4197 while ((str = strtok (NULL, " \t")) != NULL)
4199 next_key = xpm_str_to_color_key (str);
4200 if (next_key >= 0)
4201 break;
4202 color[strlen (color)] = ' ';
4205 if (key == XPM_COLOR_KEY_S)
4207 if (NILP (symbol_color))
4208 symbol_color = build_string (color);
4210 else if (max_key < key && key <= best_key)
4212 max_key = key;
4213 max_color = color;
4215 key = next_key;
4217 while (str);
4219 color_val = Qnil;
4220 if (!NILP (color_symbols) && !NILP (symbol_color))
4222 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4224 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4226 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4227 color_val = Qt;
4228 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4229 &cdef, 0))
4230 color_val = make_number (cdef.pixel);
4233 if (NILP (color_val) && max_key > 0)
4235 if (xstrcasecmp (max_color, "None") == 0)
4236 color_val = Qt;
4237 else if (x_defined_color (f, max_color, &cdef, 0))
4238 color_val = make_number (cdef.pixel);
4240 if (!NILP (color_val))
4241 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4243 expect (',');
4246 for (y = 0; y < height; y++)
4248 expect (XPM_TK_STRING);
4249 str = beg;
4250 if (len < width * chars_per_pixel)
4251 goto failure;
4252 for (x = 0; x < width; x++, str += chars_per_pixel)
4254 Lisp_Object color_val =
4255 (*get_color_table) (color_table, str, chars_per_pixel);
4257 XPutPixel (ximg, x, y,
4258 (INTEGERP (color_val) ? XINT (color_val)
4259 : FRAME_FOREGROUND_PIXEL (f)));
4260 #ifndef HAVE_NS
4261 XPutPixel (mask_img, x, y,
4262 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4263 : (have_mask = true, PIX_MASK_RETAIN)));
4264 #else
4265 if (EQ (color_val, Qt))
4266 ns_set_alpha (ximg, x, y, 0);
4267 #endif
4269 if (y + 1 < height)
4270 expect (',');
4273 img->width = width;
4274 img->height = height;
4276 /* Maybe fill in the background field while we have ximg handy. */
4277 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4278 IMAGE_BACKGROUND (img, f, ximg);
4280 image_put_x_image (f, img, ximg, 0);
4281 #ifndef HAVE_NS
4282 if (have_mask)
4284 /* Fill in the background_transparent field while we have the
4285 mask handy. */
4286 image_background_transparent (img, f, mask_img);
4288 image_put_x_image (f, img, mask_img, 1);
4290 else
4292 x_destroy_x_image (mask_img);
4293 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4295 #endif
4296 return 1;
4298 failure:
4299 image_error ("Invalid XPM file (%s)", img->spec);
4300 x_destroy_x_image (ximg);
4301 x_destroy_x_image (mask_img);
4302 x_clear_image (f, img);
4303 return 0;
4305 #undef match
4306 #undef expect
4307 #undef expect_ident
4310 static bool
4311 xpm_load (struct frame *f,
4312 struct image *img)
4314 bool success_p = 0;
4315 Lisp_Object file_name;
4317 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4318 file_name = image_spec_value (img->spec, QCfile, NULL);
4319 if (STRINGP (file_name))
4321 int fd;
4322 Lisp_Object file = x_find_image_fd (file_name, &fd);
4323 if (!STRINGP (file))
4325 image_error ("Cannot find image file `%s'", file_name);
4326 return 0;
4329 ptrdiff_t size;
4330 char *contents = slurp_file (fd, &size);
4331 if (contents == NULL)
4333 image_error ("Error loading XPM image `%s'", file);
4334 return 0;
4337 success_p = xpm_load_image (f, img, contents, contents + size);
4338 xfree (contents);
4340 else
4342 Lisp_Object data;
4344 data = image_spec_value (img->spec, QCdata, NULL);
4345 if (!STRINGP (data))
4347 image_error ("Invalid image data `%s'", data);
4348 return 0;
4350 success_p = xpm_load_image (f, img, SSDATA (data),
4351 SSDATA (data) + SBYTES (data));
4354 return success_p;
4357 #endif /* HAVE_NS && !HAVE_XPM */
4361 /***********************************************************************
4362 Color table
4363 ***********************************************************************/
4365 #ifdef COLOR_TABLE_SUPPORT
4367 /* An entry in the color table mapping an RGB color to a pixel color. */
4369 struct ct_color
4371 int r, g, b;
4372 unsigned long pixel;
4374 /* Next in color table collision list. */
4375 struct ct_color *next;
4378 /* The bucket vector size to use. Must be prime. */
4380 #define CT_SIZE 101
4382 /* Value is a hash of the RGB color given by R, G, and B. */
4384 static unsigned
4385 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4387 return (r << 16) ^ (g << 8) ^ b;
4390 /* The color hash table. */
4392 static struct ct_color **ct_table;
4394 /* Number of entries in the color table. */
4396 static int ct_colors_allocated;
4397 enum
4399 ct_colors_allocated_max =
4400 min (INT_MAX,
4401 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4404 /* Initialize the color table. */
4406 static void
4407 init_color_table (void)
4409 int size = CT_SIZE * sizeof (*ct_table);
4410 ct_table = xzalloc (size);
4411 ct_colors_allocated = 0;
4415 /* Free memory associated with the color table. */
4417 static void
4418 free_color_table (void)
4420 int i;
4421 struct ct_color *p, *next;
4423 for (i = 0; i < CT_SIZE; ++i)
4424 for (p = ct_table[i]; p; p = next)
4426 next = p->next;
4427 xfree (p);
4430 xfree (ct_table);
4431 ct_table = NULL;
4435 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4436 entry for that color already is in the color table, return the
4437 pixel color of that entry. Otherwise, allocate a new color for R,
4438 G, B, and make an entry in the color table. */
4440 static unsigned long
4441 lookup_rgb_color (struct frame *f, int r, int g, int b)
4443 unsigned hash = ct_hash_rgb (r, g, b);
4444 int i = hash % CT_SIZE;
4445 struct ct_color *p;
4446 Display_Info *dpyinfo;
4448 /* Handle TrueColor visuals specially, which improves performance by
4449 two orders of magnitude. Freeing colors on TrueColor visuals is
4450 a nop, and pixel colors specify RGB values directly. See also
4451 the Xlib spec, chapter 3.1. */
4452 dpyinfo = FRAME_DISPLAY_INFO (f);
4453 if (dpyinfo->red_bits > 0)
4455 /* Apply gamma-correction like normal color allocation does. */
4456 if (f->gamma)
4458 XColor color;
4459 color.red = r, color.green = g, color.blue = b;
4460 gamma_correct (f, &color);
4461 r = color.red, g = color.green, b = color.blue;
4464 return x_make_truecolor_pixel (dpyinfo, r, g, b);
4467 for (p = ct_table[i]; p; p = p->next)
4468 if (p->r == r && p->g == g && p->b == b)
4469 break;
4471 if (p == NULL)
4474 #ifdef HAVE_X_WINDOWS
4475 XColor color;
4476 Colormap cmap;
4477 bool rc;
4478 #else
4479 COLORREF color;
4480 #endif
4482 if (ct_colors_allocated_max <= ct_colors_allocated)
4483 return FRAME_FOREGROUND_PIXEL (f);
4485 #ifdef HAVE_X_WINDOWS
4486 color.red = r;
4487 color.green = g;
4488 color.blue = b;
4490 cmap = FRAME_X_COLORMAP (f);
4491 rc = x_alloc_nearest_color (f, cmap, &color);
4492 if (rc)
4494 ++ct_colors_allocated;
4495 p = xmalloc (sizeof *p);
4496 p->r = r;
4497 p->g = g;
4498 p->b = b;
4499 p->pixel = color.pixel;
4500 p->next = ct_table[i];
4501 ct_table[i] = p;
4503 else
4504 return FRAME_FOREGROUND_PIXEL (f);
4506 #else
4507 #ifdef HAVE_NTGUI
4508 color = PALETTERGB (r, g, b);
4509 #else
4510 color = RGB_TO_ULONG (r, g, b);
4511 #endif /* HAVE_NTGUI */
4512 ++ct_colors_allocated;
4513 p = xmalloc (sizeof *p);
4514 p->r = r;
4515 p->g = g;
4516 p->b = b;
4517 p->pixel = color;
4518 p->next = ct_table[i];
4519 ct_table[i] = p;
4520 #endif /* HAVE_X_WINDOWS */
4524 return p->pixel;
4528 /* Look up pixel color PIXEL which is used on frame F in the color
4529 table. If not already present, allocate it. Value is PIXEL. */
4531 static unsigned long
4532 lookup_pixel_color (struct frame *f, unsigned long pixel)
4534 int i = pixel % CT_SIZE;
4535 struct ct_color *p;
4537 for (p = ct_table[i]; p; p = p->next)
4538 if (p->pixel == pixel)
4539 break;
4541 if (p == NULL)
4543 XColor color;
4544 Colormap cmap;
4545 bool rc;
4547 if (ct_colors_allocated >= ct_colors_allocated_max)
4548 return FRAME_FOREGROUND_PIXEL (f);
4550 #ifdef HAVE_X_WINDOWS
4551 cmap = FRAME_X_COLORMAP (f);
4552 color.pixel = pixel;
4553 x_query_color (f, &color);
4554 rc = x_alloc_nearest_color (f, cmap, &color);
4555 #else
4556 block_input ();
4557 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4558 color.pixel = pixel;
4559 XQueryColor (NULL, cmap, &color);
4560 rc = x_alloc_nearest_color (f, cmap, &color);
4561 unblock_input ();
4562 #endif /* HAVE_X_WINDOWS */
4564 if (rc)
4566 ++ct_colors_allocated;
4568 p = xmalloc (sizeof *p);
4569 p->r = color.red;
4570 p->g = color.green;
4571 p->b = color.blue;
4572 p->pixel = pixel;
4573 p->next = ct_table[i];
4574 ct_table[i] = p;
4576 else
4577 return FRAME_FOREGROUND_PIXEL (f);
4579 return p->pixel;
4583 /* Value is a vector of all pixel colors contained in the color table,
4584 allocated via xmalloc. Set *N to the number of colors. */
4586 static unsigned long *
4587 colors_in_color_table (int *n)
4589 int i, j;
4590 struct ct_color *p;
4591 unsigned long *colors;
4593 if (ct_colors_allocated == 0)
4595 *n = 0;
4596 colors = NULL;
4598 else
4600 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4601 *n = ct_colors_allocated;
4603 for (i = j = 0; i < CT_SIZE; ++i)
4604 for (p = ct_table[i]; p; p = p->next)
4605 colors[j++] = p->pixel;
4608 return colors;
4611 #else /* COLOR_TABLE_SUPPORT */
4613 static unsigned long
4614 lookup_rgb_color (struct frame *f, int r, int g, int b)
4616 #ifdef HAVE_NTGUI
4617 return PALETTERGB (r >> 8, g >> 8, b >> 8);
4618 #elif defined HAVE_NS
4619 return RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4620 #else
4621 xsignal1 (Qfile_error,
4622 build_string ("This Emacs mishandles this image file type"));
4623 #endif
4626 static void
4627 init_color_table (void)
4630 #endif /* COLOR_TABLE_SUPPORT */
4633 /***********************************************************************
4634 Algorithms
4635 ***********************************************************************/
4637 /* Edge detection matrices for different edge-detection
4638 strategies. */
4640 static int emboss_matrix[9] = {
4641 /* x - 1 x x + 1 */
4642 2, -1, 0, /* y - 1 */
4643 -1, 0, 1, /* y */
4644 0, 1, -2 /* y + 1 */
4647 static int laplace_matrix[9] = {
4648 /* x - 1 x x + 1 */
4649 1, 0, 0, /* y - 1 */
4650 0, 0, 0, /* y */
4651 0, 0, -1 /* y + 1 */
4654 /* Value is the intensity of the color whose red/green/blue values
4655 are R, G, and B. */
4657 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4660 /* On frame F, return an array of XColor structures describing image
4661 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4662 means also fill the red/green/blue members of the XColor
4663 structures. Value is a pointer to the array of XColors structures,
4664 allocated with xmalloc; it must be freed by the caller. */
4666 static XColor *
4667 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4669 int x, y;
4670 XColor *colors, *p;
4671 XImagePtr_or_DC ximg;
4672 ptrdiff_t nbytes;
4673 #ifdef HAVE_NTGUI
4674 HGDIOBJ prev;
4675 #endif /* HAVE_NTGUI */
4677 if (INT_MULTIPLY_WRAPV (sizeof *colors, img->width, &nbytes)
4678 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes)
4679 || SIZE_MAX < nbytes)
4680 memory_full (SIZE_MAX);
4681 colors = xmalloc (nbytes);
4683 /* Get the X image or create a memory device context for IMG. */
4684 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4686 /* Fill the `pixel' members of the XColor array. I wished there
4687 were an easy and portable way to circumvent XGetPixel. */
4688 p = colors;
4689 for (y = 0; y < img->height; ++y)
4691 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4692 XColor *row = p;
4693 for (x = 0; x < img->width; ++x, ++p)
4694 p->pixel = GET_PIXEL (ximg, x, y);
4695 if (rgb_p)
4696 x_query_colors (f, row, img->width);
4698 #else
4700 for (x = 0; x < img->width; ++x, ++p)
4702 /* W32_TODO: palette support needed here? */
4703 p->pixel = GET_PIXEL (ximg, x, y);
4704 if (rgb_p)
4706 p->red = RED16_FROM_ULONG (p->pixel);
4707 p->green = GREEN16_FROM_ULONG (p->pixel);
4708 p->blue = BLUE16_FROM_ULONG (p->pixel);
4711 #endif /* HAVE_X_WINDOWS */
4714 image_unget_x_image_or_dc (img, 0, ximg, prev);
4716 return colors;
4719 #ifdef HAVE_NTGUI
4721 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4722 created with CreateDIBSection, with the pointer to the bit values
4723 stored in ximg->data. */
4725 static void
4726 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4728 int width = ximg->info.bmiHeader.biWidth;
4729 unsigned char * pixel;
4731 /* True color images. */
4732 if (ximg->info.bmiHeader.biBitCount == 24)
4734 int rowbytes = width * 3;
4735 /* Ensure scanlines are aligned on 4 byte boundaries. */
4736 if (rowbytes % 4)
4737 rowbytes += 4 - (rowbytes % 4);
4739 pixel = ximg->data + y * rowbytes + x * 3;
4740 /* Windows bitmaps are in BGR order. */
4741 *pixel = GetBValue (color);
4742 *(pixel + 1) = GetGValue (color);
4743 *(pixel + 2) = GetRValue (color);
4745 /* Monochrome images. */
4746 else if (ximg->info.bmiHeader.biBitCount == 1)
4748 int rowbytes = width / 8;
4749 /* Ensure scanlines are aligned on 4 byte boundaries. */
4750 if (rowbytes % 4)
4751 rowbytes += 4 - (rowbytes % 4);
4752 pixel = ximg->data + y * rowbytes + x / 8;
4753 /* Filter out palette info. */
4754 if (color & 0x00ffffff)
4755 *pixel = *pixel | (1 << x % 8);
4756 else
4757 *pixel = *pixel & ~(1 << x % 8);
4759 else
4760 image_error ("XPutPixel: palette image not supported");
4763 #endif /* HAVE_NTGUI */
4765 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4766 RGB members are set. F is the frame on which this all happens.
4767 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4769 static void
4770 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4772 int x, y;
4773 XImagePtr oimg = NULL;
4774 XColor *p;
4776 init_color_table ();
4778 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4779 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4780 &oimg, 0);
4781 p = colors;
4782 for (y = 0; y < img->height; ++y)
4783 for (x = 0; x < img->width; ++x, ++p)
4785 unsigned long pixel;
4786 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4787 XPutPixel (oimg, x, y, pixel);
4790 xfree (colors);
4792 image_put_x_image (f, img, oimg, 0);
4793 #ifdef COLOR_TABLE_SUPPORT
4794 img->colors = colors_in_color_table (&img->ncolors);
4795 free_color_table ();
4796 #endif /* COLOR_TABLE_SUPPORT */
4800 /* On frame F, perform edge-detection on image IMG.
4802 MATRIX is a nine-element array specifying the transformation
4803 matrix. See emboss_matrix for an example.
4805 COLOR_ADJUST is a color adjustment added to each pixel of the
4806 outgoing image. */
4808 static void
4809 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4811 XColor *colors = x_to_xcolors (f, img, 1);
4812 XColor *new, *p;
4813 int x, y, i, sum;
4814 ptrdiff_t nbytes;
4816 for (i = sum = 0; i < 9; ++i)
4817 sum += eabs (matrix[i]);
4819 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4821 if (INT_MULTIPLY_WRAPV (sizeof *new, img->width, &nbytes)
4822 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes))
4823 memory_full (SIZE_MAX);
4824 new = xmalloc (nbytes);
4826 for (y = 0; y < img->height; ++y)
4828 p = COLOR (new, 0, y);
4829 p->red = p->green = p->blue = 0xffff/2;
4830 p = COLOR (new, img->width - 1, y);
4831 p->red = p->green = p->blue = 0xffff/2;
4834 for (x = 1; x < img->width - 1; ++x)
4836 p = COLOR (new, x, 0);
4837 p->red = p->green = p->blue = 0xffff/2;
4838 p = COLOR (new, x, img->height - 1);
4839 p->red = p->green = p->blue = 0xffff/2;
4842 for (y = 1; y < img->height - 1; ++y)
4844 p = COLOR (new, 1, y);
4846 for (x = 1; x < img->width - 1; ++x, ++p)
4848 int r, g, b, yy, xx;
4850 r = g = b = i = 0;
4851 for (yy = y - 1; yy < y + 2; ++yy)
4852 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4853 if (matrix[i])
4855 XColor *t = COLOR (colors, xx, yy);
4856 r += matrix[i] * t->red;
4857 g += matrix[i] * t->green;
4858 b += matrix[i] * t->blue;
4861 r = (r / sum + color_adjust) & 0xffff;
4862 g = (g / sum + color_adjust) & 0xffff;
4863 b = (b / sum + color_adjust) & 0xffff;
4864 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4868 xfree (colors);
4869 x_from_xcolors (f, img, new);
4871 #undef COLOR
4875 /* Perform the pre-defined `emboss' edge-detection on image IMG
4876 on frame F. */
4878 static void
4879 x_emboss (struct frame *f, struct image *img)
4881 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4885 /* Transform image IMG which is used on frame F with a Laplace
4886 edge-detection algorithm. The result is an image that can be used
4887 to draw disabled buttons, for example. */
4889 static void
4890 x_laplace (struct frame *f, struct image *img)
4892 x_detect_edges (f, img, laplace_matrix, 45000);
4896 /* Perform edge-detection on image IMG on frame F, with specified
4897 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4899 MATRIX must be either
4901 - a list of at least 9 numbers in row-major form
4902 - a vector of at least 9 numbers
4904 COLOR_ADJUST nil means use a default; otherwise it must be a
4905 number. */
4907 static void
4908 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4909 Lisp_Object color_adjust)
4911 int i = 0;
4912 int trans[9];
4914 if (CONSP (matrix))
4916 for (i = 0;
4917 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4918 ++i, matrix = XCDR (matrix))
4919 trans[i] = XFLOATINT (XCAR (matrix));
4921 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4923 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4924 trans[i] = XFLOATINT (AREF (matrix, i));
4927 if (NILP (color_adjust))
4928 color_adjust = make_number (0xffff / 2);
4930 if (i == 9 && NUMBERP (color_adjust))
4931 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4935 /* Transform image IMG on frame F so that it looks disabled. */
4937 static void
4938 x_disable_image (struct frame *f, struct image *img)
4940 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4941 #ifdef HAVE_NTGUI
4942 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4943 #else
4944 int n_planes = dpyinfo->n_planes;
4945 #endif /* HAVE_NTGUI */
4947 if (n_planes >= 2)
4949 /* Color (or grayscale). Convert to gray, and equalize. Just
4950 drawing such images with a stipple can look very odd, so
4951 we're using this method instead. */
4952 XColor *colors = x_to_xcolors (f, img, 1);
4953 XColor *p, *end;
4954 const int h = 15000;
4955 const int l = 30000;
4957 for (p = colors, end = colors + img->width * img->height;
4958 p < end;
4959 ++p)
4961 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4962 int i2 = (0xffff - h - l) * i / 0xffff + l;
4963 p->red = p->green = p->blue = i2;
4966 x_from_xcolors (f, img, colors);
4969 /* Draw a cross over the disabled image, if we must or if we
4970 should. */
4971 if (n_planes < 2 || cross_disabled_images)
4973 #ifndef HAVE_NTGUI
4974 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4976 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4978 Display *dpy = FRAME_X_DISPLAY (f);
4979 GC gc;
4981 image_sync_to_pixmaps (f, img);
4982 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4983 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4984 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4985 img->width - 1, img->height - 1);
4986 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4987 img->width - 1, 0);
4988 XFreeGC (dpy, gc);
4990 if (img->mask)
4992 gc = XCreateGC (dpy, img->mask, 0, NULL);
4993 XSetForeground (dpy, gc, MaskForeground (f));
4994 XDrawLine (dpy, img->mask, gc, 0, 0,
4995 img->width - 1, img->height - 1);
4996 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4997 img->width - 1, 0);
4998 XFreeGC (dpy, gc);
5000 #endif /* !HAVE_NS */
5001 #else
5002 HDC hdc, bmpdc;
5003 HGDIOBJ prev;
5005 hdc = get_frame_dc (f);
5006 bmpdc = CreateCompatibleDC (hdc);
5007 release_frame_dc (f, hdc);
5009 prev = SelectObject (bmpdc, img->pixmap);
5011 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5012 MoveToEx (bmpdc, 0, 0, NULL);
5013 LineTo (bmpdc, img->width - 1, img->height - 1);
5014 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5015 LineTo (bmpdc, img->width - 1, 0);
5017 if (img->mask)
5019 SelectObject (bmpdc, img->mask);
5020 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5021 MoveToEx (bmpdc, 0, 0, NULL);
5022 LineTo (bmpdc, img->width - 1, img->height - 1);
5023 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5024 LineTo (bmpdc, img->width - 1, 0);
5026 SelectObject (bmpdc, prev);
5027 DeleteDC (bmpdc);
5028 #endif /* HAVE_NTGUI */
5033 /* Build a mask for image IMG which is used on frame F. FILE is the
5034 name of an image file, for error messages. HOW determines how to
5035 determine the background color of IMG. If it is a list '(R G B)',
5036 with R, G, and B being integers >= 0, take that as the color of the
5037 background. Otherwise, determine the background color of IMG
5038 heuristically. */
5040 static void
5041 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
5043 XImagePtr_or_DC ximg;
5044 #ifdef HAVE_NTGUI
5045 HGDIOBJ prev;
5046 char *mask_img;
5047 int row_width;
5048 #elif !defined HAVE_NS
5049 XImagePtr mask_img;
5050 #endif
5051 int x, y;
5052 bool use_img_background;
5053 unsigned long bg = 0;
5055 if (img->mask)
5056 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
5058 #ifndef HAVE_NTGUI
5059 #ifndef HAVE_NS
5060 /* Create an image and pixmap serving as mask. */
5061 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
5062 &mask_img, 1))
5063 return;
5064 #endif /* !HAVE_NS */
5065 #else
5066 /* Create the bit array serving as mask. */
5067 row_width = (img->width + 7) / 8;
5068 mask_img = xzalloc (row_width * img->height);
5069 #endif /* HAVE_NTGUI */
5071 /* Get the X image or create a memory device context for IMG. */
5072 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
5074 /* Determine the background color of ximg. If HOW is `(R G B)'
5075 take that as color. Otherwise, use the image's background color. */
5076 use_img_background = 1;
5078 if (CONSP (how))
5080 int rgb[3], i;
5082 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5084 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5085 how = XCDR (how);
5088 if (i == 3 && NILP (how))
5090 char color_name[30];
5091 sprintf (color_name, "#%04x%04x%04x",
5092 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
5093 bg = (
5094 #ifdef HAVE_NTGUI
5095 0x00ffffff & /* Filter out palette info. */
5096 #endif /* HAVE_NTGUI */
5097 x_alloc_image_color (f, img, build_string (color_name), 0));
5098 use_img_background = 0;
5102 if (use_img_background)
5103 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5105 /* Set all bits in mask_img to 1 whose color in ximg is different
5106 from the background color bg. */
5107 #ifndef HAVE_NTGUI
5108 for (y = 0; y < img->height; ++y)
5109 for (x = 0; x < img->width; ++x)
5110 #ifndef HAVE_NS
5111 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5112 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5113 #else
5114 if (XGetPixel (ximg, x, y) == bg)
5115 ns_set_alpha (ximg, x, y, 0);
5116 #endif /* HAVE_NS */
5117 #ifndef HAVE_NS
5118 /* Fill in the background_transparent field while we have the mask handy. */
5119 image_background_transparent (img, f, mask_img);
5121 /* Put mask_img into the image. */
5122 image_put_x_image (f, img, mask_img, 1);
5123 #endif /* !HAVE_NS */
5124 #else
5125 for (y = 0; y < img->height; ++y)
5126 for (x = 0; x < img->width; ++x)
5128 COLORREF p = GetPixel (ximg, x, y);
5129 if (p != bg)
5130 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5133 /* Create the mask image. */
5134 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5135 mask_img);
5136 /* Fill in the background_transparent field while we have the mask handy. */
5137 SelectObject (ximg, img->mask);
5138 image_background_transparent (img, f, ximg);
5140 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5141 xfree (mask_img);
5142 #endif /* HAVE_NTGUI */
5144 image_unget_x_image_or_dc (img, 0, ximg, prev);
5148 /***********************************************************************
5149 PBM (mono, gray, color)
5150 ***********************************************************************/
5152 static bool pbm_image_p (Lisp_Object object);
5153 static bool pbm_load (struct frame *f, struct image *img);
5155 /* Indices of image specification fields in gs_format, below. */
5157 enum pbm_keyword_index
5159 PBM_TYPE,
5160 PBM_FILE,
5161 PBM_DATA,
5162 PBM_ASCENT,
5163 PBM_MARGIN,
5164 PBM_RELIEF,
5165 PBM_ALGORITHM,
5166 PBM_HEURISTIC_MASK,
5167 PBM_MASK,
5168 PBM_FOREGROUND,
5169 PBM_BACKGROUND,
5170 PBM_LAST
5173 /* Vector of image_keyword structures describing the format
5174 of valid user-defined image specifications. */
5176 static const struct image_keyword pbm_format[PBM_LAST] =
5178 {":type", IMAGE_SYMBOL_VALUE, 1},
5179 {":file", IMAGE_STRING_VALUE, 0},
5180 {":data", IMAGE_STRING_VALUE, 0},
5181 {":ascent", IMAGE_ASCENT_VALUE, 0},
5182 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5183 {":relief", IMAGE_INTEGER_VALUE, 0},
5184 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5185 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5186 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5187 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5188 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5191 /* Structure describing the image type `pbm'. */
5193 static struct image_type pbm_type =
5195 SYMBOL_INDEX (Qpbm),
5196 pbm_image_p,
5197 pbm_load,
5198 x_clear_image,
5199 NULL,
5200 NULL
5204 /* Return true if OBJECT is a valid PBM image specification. */
5206 static bool
5207 pbm_image_p (Lisp_Object object)
5209 struct image_keyword fmt[PBM_LAST];
5211 memcpy (fmt, pbm_format, sizeof fmt);
5213 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5214 return 0;
5216 /* Must specify either :data or :file. */
5217 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5221 /* Get next char skipping comments in Netpbm header. Returns -1 at
5222 end of input. */
5224 static int
5225 pbm_next_char (char **s, char *end)
5227 while (*s < end)
5229 unsigned char c = *(*s)++;
5230 if (c != '#')
5231 return c;
5232 while (*s < end)
5234 c = *(*s)++;
5235 if (c == '\n' || c == '\r')
5236 break;
5240 return -1;
5244 /* Scan a decimal number from *S and return it. Advance *S while
5245 reading the number. END is the end of the string. Value is -1 at
5246 end of input. */
5248 static int
5249 pbm_scan_number (char **s, char *end)
5251 int c = 0, val = -1;
5253 /* Skip white-space. */
5254 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5257 if (c_isdigit (c))
5259 /* Read decimal number. */
5260 val = c - '0';
5261 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5262 val = 10 * val + c - '0';
5265 return val;
5269 /* Load PBM image IMG for use on frame F. */
5271 static bool
5272 pbm_load (struct frame *f, struct image *img)
5274 bool raw_p;
5275 int x, y;
5276 int width, height, max_color_idx = 0;
5277 Lisp_Object specified_file;
5278 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5279 char *contents = NULL;
5280 char *end, *p;
5281 #ifndef USE_CAIRO
5282 XImagePtr ximg;
5283 #endif
5285 specified_file = image_spec_value (img->spec, QCfile, NULL);
5287 if (STRINGP (specified_file))
5289 int fd;
5290 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5291 if (!STRINGP (file))
5293 image_error ("Cannot find image file `%s'", specified_file);
5294 return 0;
5297 ptrdiff_t size;
5298 contents = slurp_file (fd, &size);
5299 if (contents == NULL)
5301 image_error ("Error reading `%s'", file);
5302 return 0;
5305 p = contents;
5306 end = contents + size;
5308 else
5310 Lisp_Object data;
5311 data = image_spec_value (img->spec, QCdata, NULL);
5312 if (!STRINGP (data))
5314 image_error ("Invalid image data `%s'", data);
5315 return 0;
5317 p = SSDATA (data);
5318 end = p + SBYTES (data);
5321 /* Check magic number. */
5322 if (end - p < 2 || *p++ != 'P')
5324 image_error ("Not a PBM image: `%s'", img->spec);
5325 error:
5326 xfree (contents);
5327 img->pixmap = NO_PIXMAP;
5328 return 0;
5331 switch (*p++)
5333 case '1':
5334 raw_p = 0, type = PBM_MONO;
5335 break;
5337 case '2':
5338 raw_p = 0, type = PBM_GRAY;
5339 break;
5341 case '3':
5342 raw_p = 0, type = PBM_COLOR;
5343 break;
5345 case '4':
5346 raw_p = 1, type = PBM_MONO;
5347 break;
5349 case '5':
5350 raw_p = 1, type = PBM_GRAY;
5351 break;
5353 case '6':
5354 raw_p = 1, type = PBM_COLOR;
5355 break;
5357 default:
5358 image_error ("Not a PBM image: `%s'", img->spec);
5359 goto error;
5362 /* Read width, height, maximum color-component. Characters
5363 starting with `#' up to the end of a line are ignored. */
5364 width = pbm_scan_number (&p, end);
5365 height = pbm_scan_number (&p, end);
5367 #ifdef USE_CAIRO
5368 void *data = xmalloc (width * height * 4);
5369 uint32_t *dataptr = data;
5370 #endif
5372 if (type != PBM_MONO)
5374 max_color_idx = pbm_scan_number (&p, end);
5375 if (max_color_idx > 65535 || max_color_idx < 0)
5377 image_error ("Unsupported maximum PBM color value");
5378 goto error;
5382 if (!check_image_size (f, width, height))
5384 image_size_error ();
5385 goto error;
5388 #ifndef USE_CAIRO
5389 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5390 goto error;
5391 #endif
5393 /* Initialize the color hash table. */
5394 init_color_table ();
5396 if (type == PBM_MONO)
5398 unsigned char c = 0;
5399 int g;
5400 struct image_keyword fmt[PBM_LAST];
5401 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5402 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5403 #ifdef USE_CAIRO
5404 XColor xfg, xbg;
5405 int fga32, bga32;
5406 #endif
5407 /* Parse the image specification. */
5408 memcpy (fmt, pbm_format, sizeof fmt);
5409 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5411 /* Get foreground and background colors, maybe allocate colors. */
5412 #ifdef USE_CAIRO
5413 if (! fmt[PBM_FOREGROUND].count
5414 || ! STRINGP (fmt[PBM_FOREGROUND].value)
5415 || ! x_defined_color (f, SSDATA (fmt[PBM_FOREGROUND].value), &xfg, 0))
5417 xfg.pixel = fg;
5418 x_query_color (f, &xfg);
5420 fga32 = xcolor_to_argb32 (xfg);
5422 if (! fmt[PBM_BACKGROUND].count
5423 || ! STRINGP (fmt[PBM_BACKGROUND].value)
5424 || ! x_defined_color (f, SSDATA (fmt[PBM_BACKGROUND].value), &xbg, 0))
5426 xbg.pixel = bg;
5427 x_query_color (f, &xbg);
5429 bga32 = xcolor_to_argb32 (xbg);
5430 #else
5431 if (fmt[PBM_FOREGROUND].count
5432 && STRINGP (fmt[PBM_FOREGROUND].value))
5433 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5434 if (fmt[PBM_BACKGROUND].count
5435 && STRINGP (fmt[PBM_BACKGROUND].value))
5437 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5438 img->background = bg;
5439 img->background_valid = 1;
5441 #endif
5443 for (y = 0; y < height; ++y)
5444 for (x = 0; x < width; ++x)
5446 if (raw_p)
5448 if ((x & 7) == 0)
5450 if (p >= end)
5452 #ifdef USE_CAIRO
5453 xfree (data);
5454 #else
5455 x_destroy_x_image (ximg);
5456 #endif
5457 x_clear_image (f, img);
5458 image_error ("Invalid image size in image `%s'",
5459 img->spec);
5460 goto error;
5462 c = *p++;
5464 g = c & 0x80;
5465 c <<= 1;
5467 else
5468 g = pbm_scan_number (&p, end);
5470 #ifdef USE_CAIRO
5471 *dataptr++ = g ? fga32 : bga32;
5472 #else
5473 XPutPixel (ximg, x, y, g ? fg : bg);
5474 #endif
5477 else
5479 int expected_size = height * width;
5480 if (max_color_idx > 255)
5481 expected_size *= 2;
5482 if (type == PBM_COLOR)
5483 expected_size *= 3;
5485 if (raw_p && p + expected_size > end)
5487 #ifdef USE_CAIRO
5488 xfree (data);
5489 #else
5490 x_destroy_x_image (ximg);
5491 #endif
5492 x_clear_image (f, img);
5493 image_error ("Invalid image size in image `%s'", img->spec);
5494 goto error;
5497 for (y = 0; y < height; ++y)
5498 for (x = 0; x < width; ++x)
5500 int r, g, b;
5502 if (type == PBM_GRAY && raw_p)
5504 r = g = b = *p++;
5505 if (max_color_idx > 255)
5506 r = g = b = r * 256 + *p++;
5508 else if (type == PBM_GRAY)
5509 r = g = b = pbm_scan_number (&p, end);
5510 else if (raw_p)
5512 r = *p++;
5513 if (max_color_idx > 255)
5514 r = r * 256 + *p++;
5515 g = *p++;
5516 if (max_color_idx > 255)
5517 g = g * 256 + *p++;
5518 b = *p++;
5519 if (max_color_idx > 255)
5520 b = b * 256 + *p++;
5522 else
5524 r = pbm_scan_number (&p, end);
5525 g = pbm_scan_number (&p, end);
5526 b = pbm_scan_number (&p, end);
5529 if (r < 0 || g < 0 || b < 0)
5531 #ifdef USE_CAIRO
5532 xfree (data);
5533 #else
5534 x_destroy_x_image (ximg);
5535 #endif
5536 image_error ("Invalid pixel value in image `%s'", img->spec);
5537 goto error;
5540 #ifdef USE_CAIRO
5541 r = (double) r * 255 / max_color_idx;
5542 g = (double) g * 255 / max_color_idx;
5543 b = (double) b * 255 / max_color_idx;
5544 *dataptr++ = (0xffu << 24) | (r << 16) | (g << 8) | b;
5545 #else
5546 /* RGB values are now in the range 0..max_color_idx.
5547 Scale this to the range 0..0xffff supported by X. */
5548 r = (double) r * 65535 / max_color_idx;
5549 g = (double) g * 65535 / max_color_idx;
5550 b = (double) b * 65535 / max_color_idx;
5551 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5552 #endif
5556 #ifdef COLOR_TABLE_SUPPORT
5557 /* Store in IMG->colors the colors allocated for the image, and
5558 free the color table. */
5559 img->colors = colors_in_color_table (&img->ncolors);
5560 free_color_table ();
5561 #endif /* COLOR_TABLE_SUPPORT */
5563 img->width = width;
5564 img->height = height;
5566 /* Maybe fill in the background field while we have ximg handy. */
5568 #ifdef USE_CAIRO
5569 create_cairo_image_surface (img, data, width, height);
5570 #else
5571 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5572 /* Casting avoids a GCC warning. */
5573 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5575 /* Put ximg into the image. */
5576 image_put_x_image (f, img, ximg, 0);
5577 #endif
5579 /* X and W32 versions did it here, MAC version above. ++kfs
5580 img->width = width;
5581 img->height = height; */
5583 xfree (contents);
5584 return 1;
5588 /***********************************************************************
5590 ***********************************************************************/
5592 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5594 /* Function prototypes. */
5596 static bool png_image_p (Lisp_Object object);
5597 static bool png_load (struct frame *f, struct image *img);
5599 /* Indices of image specification fields in png_format, below. */
5601 enum png_keyword_index
5603 PNG_TYPE,
5604 PNG_DATA,
5605 PNG_FILE,
5606 PNG_ASCENT,
5607 PNG_MARGIN,
5608 PNG_RELIEF,
5609 PNG_ALGORITHM,
5610 PNG_HEURISTIC_MASK,
5611 PNG_MASK,
5612 PNG_BACKGROUND,
5613 PNG_LAST
5616 /* Vector of image_keyword structures describing the format
5617 of valid user-defined image specifications. */
5619 static const struct image_keyword png_format[PNG_LAST] =
5621 {":type", IMAGE_SYMBOL_VALUE, 1},
5622 {":data", IMAGE_STRING_VALUE, 0},
5623 {":file", IMAGE_STRING_VALUE, 0},
5624 {":ascent", IMAGE_ASCENT_VALUE, 0},
5625 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5626 {":relief", IMAGE_INTEGER_VALUE, 0},
5627 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5628 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5629 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5630 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5633 #if defined HAVE_NTGUI && defined WINDOWSNT
5634 static bool init_png_functions (void);
5635 #else
5636 #define init_png_functions NULL
5637 #endif
5639 /* Structure describing the image type `png'. */
5641 static struct image_type png_type =
5643 SYMBOL_INDEX (Qpng),
5644 png_image_p,
5645 png_load,
5646 x_clear_image,
5647 init_png_functions,
5648 NULL
5651 /* Return true if OBJECT is a valid PNG image specification. */
5653 static bool
5654 png_image_p (Lisp_Object object)
5656 struct image_keyword fmt[PNG_LAST];
5657 memcpy (fmt, png_format, sizeof fmt);
5659 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5660 return 0;
5662 /* Must specify either the :data or :file keyword. */
5663 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5666 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5669 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5671 # ifdef WINDOWSNT
5672 /* PNG library details. */
5674 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5675 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5676 DEF_DLL_FN (png_structp, png_create_read_struct,
5677 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5678 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5679 DEF_DLL_FN (void, png_destroy_read_struct,
5680 (png_structpp, png_infopp, png_infopp));
5681 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5682 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5683 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5684 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5685 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5686 int *, int *, int *, int *, int *));
5687 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5688 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5689 DEF_DLL_FN (void, png_set_expand, (png_structp));
5690 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5691 DEF_DLL_FN (void, png_set_background,
5692 (png_structp, png_color_16p, int, int, double));
5693 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5694 (png_structp, png_infop, png_color_16p *));
5695 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5696 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5697 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5698 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5699 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5700 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5702 # if (PNG_LIBPNG_VER >= 10500)
5703 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5704 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5705 (png_structp, png_longjmp_ptr, size_t));
5706 # endif /* libpng version >= 1.5 */
5708 static bool
5709 init_png_functions (void)
5711 HMODULE library;
5713 if (!(library = w32_delayed_load (Qpng)))
5714 return 0;
5716 LOAD_DLL_FN (library, png_get_io_ptr);
5717 LOAD_DLL_FN (library, png_sig_cmp);
5718 LOAD_DLL_FN (library, png_create_read_struct);
5719 LOAD_DLL_FN (library, png_create_info_struct);
5720 LOAD_DLL_FN (library, png_destroy_read_struct);
5721 LOAD_DLL_FN (library, png_set_read_fn);
5722 LOAD_DLL_FN (library, png_set_sig_bytes);
5723 LOAD_DLL_FN (library, png_read_info);
5724 LOAD_DLL_FN (library, png_get_IHDR);
5725 LOAD_DLL_FN (library, png_get_valid);
5726 LOAD_DLL_FN (library, png_set_strip_16);
5727 LOAD_DLL_FN (library, png_set_expand);
5728 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5729 LOAD_DLL_FN (library, png_set_background);
5730 LOAD_DLL_FN (library, png_get_bKGD);
5731 LOAD_DLL_FN (library, png_read_update_info);
5732 LOAD_DLL_FN (library, png_get_channels);
5733 LOAD_DLL_FN (library, png_get_rowbytes);
5734 LOAD_DLL_FN (library, png_read_image);
5735 LOAD_DLL_FN (library, png_read_end);
5736 LOAD_DLL_FN (library, png_error);
5738 # if (PNG_LIBPNG_VER >= 10500)
5739 LOAD_DLL_FN (library, png_longjmp);
5740 LOAD_DLL_FN (library, png_set_longjmp_fn);
5741 # endif /* libpng version >= 1.5 */
5743 return 1;
5746 # undef png_create_info_struct
5747 # undef png_create_read_struct
5748 # undef png_destroy_read_struct
5749 # undef png_error
5750 # undef png_get_bKGD
5751 # undef png_get_channels
5752 # undef png_get_IHDR
5753 # undef png_get_io_ptr
5754 # undef png_get_rowbytes
5755 # undef png_get_valid
5756 # undef png_longjmp
5757 # undef png_read_end
5758 # undef png_read_image
5759 # undef png_read_info
5760 # undef png_read_update_info
5761 # undef png_set_background
5762 # undef png_set_expand
5763 # undef png_set_gray_to_rgb
5764 # undef png_set_longjmp_fn
5765 # undef png_set_read_fn
5766 # undef png_set_sig_bytes
5767 # undef png_set_strip_16
5768 # undef png_sig_cmp
5770 # define png_create_info_struct fn_png_create_info_struct
5771 # define png_create_read_struct fn_png_create_read_struct
5772 # define png_destroy_read_struct fn_png_destroy_read_struct
5773 # define png_error fn_png_error
5774 # define png_get_bKGD fn_png_get_bKGD
5775 # define png_get_channels fn_png_get_channels
5776 # define png_get_IHDR fn_png_get_IHDR
5777 # define png_get_io_ptr fn_png_get_io_ptr
5778 # define png_get_rowbytes fn_png_get_rowbytes
5779 # define png_get_valid fn_png_get_valid
5780 # define png_longjmp fn_png_longjmp
5781 # define png_read_end fn_png_read_end
5782 # define png_read_image fn_png_read_image
5783 # define png_read_info fn_png_read_info
5784 # define png_read_update_info fn_png_read_update_info
5785 # define png_set_background fn_png_set_background
5786 # define png_set_expand fn_png_set_expand
5787 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5788 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5789 # define png_set_read_fn fn_png_set_read_fn
5790 # define png_set_sig_bytes fn_png_set_sig_bytes
5791 # define png_set_strip_16 fn_png_set_strip_16
5792 # define png_sig_cmp fn_png_sig_cmp
5794 # endif /* WINDOWSNT */
5796 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5797 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5798 Do not use sys_setjmp, as PNG supports only jmp_buf.
5799 It's OK if the longjmp substitute restores the signal mask. */
5800 # ifdef HAVE__SETJMP
5801 # define FAST_SETJMP(j) _setjmp (j)
5802 # define FAST_LONGJMP _longjmp
5803 # else
5804 # define FAST_SETJMP(j) setjmp (j)
5805 # define FAST_LONGJMP longjmp
5806 # endif
5808 # if PNG_LIBPNG_VER < 10500
5809 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5810 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5811 # else
5812 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5813 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5814 # define PNG_JMPBUF(ptr) \
5815 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5816 # endif
5818 /* Error and warning handlers installed when the PNG library
5819 is initialized. */
5821 static _Noreturn void
5822 my_png_error (png_struct *png_ptr, const char *msg)
5824 eassert (png_ptr != NULL);
5825 /* Avoid compiler warning about deprecated direct access to
5826 png_ptr's fields in libpng versions 1.4.x. */
5827 image_error ("PNG error: %s", build_string (msg));
5828 PNG_LONGJMP (png_ptr);
5832 static void
5833 my_png_warning (png_struct *png_ptr, const char *msg)
5835 eassert (png_ptr != NULL);
5836 image_error ("PNG warning: %s", build_string (msg));
5839 /* Memory source for PNG decoding. */
5841 struct png_memory_storage
5843 unsigned char *bytes; /* The data */
5844 ptrdiff_t len; /* How big is it? */
5845 ptrdiff_t index; /* Where are we? */
5849 /* Function set as reader function when reading PNG image from memory.
5850 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5851 bytes from the input to DATA. */
5853 static void
5854 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5856 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5858 if (length > tbr->len - tbr->index)
5859 png_error (png_ptr, "Read error");
5861 memcpy (data, tbr->bytes + tbr->index, length);
5862 tbr->index = tbr->index + length;
5866 /* Function set as reader function when reading PNG image from a file.
5867 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5868 bytes from the input to DATA. */
5870 static void
5871 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5873 FILE *fp = png_get_io_ptr (png_ptr);
5875 if (fread (data, 1, length, fp) < length)
5876 png_error (png_ptr, "Read error");
5880 /* Load PNG image IMG for use on frame F. Value is true if
5881 successful. */
5883 struct png_load_context
5885 /* These are members so that longjmp doesn't munge local variables. */
5886 png_struct *png_ptr;
5887 png_info *info_ptr;
5888 png_info *end_info;
5889 FILE *fp;
5890 png_byte *pixels;
5891 png_byte **rows;
5894 static bool
5895 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5897 Lisp_Object specified_file, specified_data;
5898 FILE *fp = NULL;
5899 int x, y;
5900 ptrdiff_t i;
5901 png_struct *png_ptr;
5902 png_info *info_ptr = NULL, *end_info = NULL;
5903 png_byte sig[8];
5904 png_byte *pixels = NULL;
5905 png_byte **rows = NULL;
5906 png_uint_32 width, height;
5907 int bit_depth, color_type, interlace_type;
5908 png_byte channels;
5909 png_uint_32 row_bytes;
5910 bool transparent_p;
5911 struct png_memory_storage tbr; /* Data to be read */
5912 ptrdiff_t nbytes;
5914 #ifdef USE_CAIRO
5915 unsigned char *data = 0;
5916 uint32_t *dataptr;
5917 #else
5918 XImagePtr ximg, mask_img = NULL;
5919 #endif
5921 /* Find out what file to load. */
5922 specified_file = image_spec_value (img->spec, QCfile, NULL);
5923 specified_data = image_spec_value (img->spec, QCdata, NULL);
5925 if (NILP (specified_data))
5927 int fd;
5928 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5929 if (!STRINGP (file))
5931 image_error ("Cannot find image file `%s'", specified_file);
5932 return 0;
5935 /* Open the image file. */
5936 fp = fdopen (fd, "rb");
5937 if (!fp)
5939 image_error ("Cannot open image file `%s'", file);
5940 return 0;
5943 /* Check PNG signature. */
5944 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5945 || png_sig_cmp (sig, 0, sizeof sig))
5947 fclose (fp);
5948 image_error ("Not a PNG file: `%s'", file);
5949 return 0;
5952 else
5954 if (!STRINGP (specified_data))
5956 image_error ("Invalid image data `%s'", specified_data);
5957 return 0;
5960 /* Read from memory. */
5961 tbr.bytes = SDATA (specified_data);
5962 tbr.len = SBYTES (specified_data);
5963 tbr.index = 0;
5965 /* Check PNG signature. */
5966 if (tbr.len < sizeof sig
5967 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5969 image_error ("Not a PNG image: `%s'", img->spec);
5970 return 0;
5973 /* Need to skip past the signature. */
5974 tbr.bytes += sizeof (sig);
5977 /* Initialize read and info structs for PNG lib. */
5978 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5979 NULL, my_png_error,
5980 my_png_warning);
5981 if (png_ptr)
5983 info_ptr = png_create_info_struct (png_ptr);
5984 end_info = png_create_info_struct (png_ptr);
5987 c->png_ptr = png_ptr;
5988 c->info_ptr = info_ptr;
5989 c->end_info = end_info;
5990 c->fp = fp;
5991 c->pixels = pixels;
5992 c->rows = rows;
5994 if (! (info_ptr && end_info))
5996 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5997 png_ptr = 0;
5999 if (! png_ptr)
6001 if (fp) fclose (fp);
6002 return 0;
6005 /* Set error jump-back. We come back here when the PNG library
6006 detects an error. */
6007 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
6009 error:
6010 if (c->png_ptr)
6011 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6012 xfree (c->pixels);
6013 xfree (c->rows);
6014 if (c->fp)
6015 fclose (c->fp);
6016 return 0;
6019 /* Read image info. */
6020 if (!NILP (specified_data))
6021 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
6022 else
6023 png_set_read_fn (png_ptr, fp, png_read_from_file);
6025 png_set_sig_bytes (png_ptr, sizeof sig);
6026 png_read_info (png_ptr, info_ptr);
6027 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6028 &interlace_type, NULL, NULL);
6030 if (! (width <= INT_MAX && height <= INT_MAX
6031 && check_image_size (f, width, height)))
6033 image_size_error ();
6034 goto error;
6037 #ifndef USE_CAIRO
6038 /* Create the X image and pixmap now, so that the work below can be
6039 omitted if the image is too large for X. */
6040 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6041 goto error;
6042 #endif
6044 /* If image contains simply transparency data, we prefer to
6045 construct a clipping mask. */
6046 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6047 transparent_p = 1;
6048 else
6049 transparent_p = 0;
6051 /* This function is easier to write if we only have to handle
6052 one data format: RGB or RGBA with 8 bits per channel. Let's
6053 transform other formats into that format. */
6055 /* Strip more than 8 bits per channel. */
6056 if (bit_depth == 16)
6057 png_set_strip_16 (png_ptr);
6059 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6060 if available. */
6061 png_set_expand (png_ptr);
6063 /* Convert grayscale images to RGB. */
6064 if (color_type == PNG_COLOR_TYPE_GRAY
6065 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6066 png_set_gray_to_rgb (png_ptr);
6068 /* Handle alpha channel by combining the image with a background
6069 color. Do this only if a real alpha channel is supplied. For
6070 simple transparency, we prefer a clipping mask. */
6071 if (!transparent_p)
6073 /* png_color_16 *image_bg; */
6074 Lisp_Object specified_bg
6075 = image_spec_value (img->spec, QCbackground, NULL);
6076 XColor color;
6078 /* If the user specified a color, try to use it; if not, use the
6079 current frame background, ignoring any default background
6080 color set by the image. */
6081 if (STRINGP (specified_bg)
6082 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
6083 : (x_query_frame_background_color (f, &color), true))
6084 /* The user specified `:background', use that. */
6086 int shift = bit_depth == 16 ? 0 : 8;
6087 png_color_16 bg = { 0 };
6088 bg.red = color.red >> shift;
6089 bg.green = color.green >> shift;
6090 bg.blue = color.blue >> shift;
6092 png_set_background (png_ptr, &bg,
6093 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6097 /* Update info structure. */
6098 png_read_update_info (png_ptr, info_ptr);
6100 /* Get number of channels. Valid values are 1 for grayscale images
6101 and images with a palette, 2 for grayscale images with transparency
6102 information (alpha channel), 3 for RGB images, and 4 for RGB
6103 images with alpha channel, i.e. RGBA. If conversions above were
6104 sufficient we should only have 3 or 4 channels here. */
6105 channels = png_get_channels (png_ptr, info_ptr);
6106 eassert (channels == 3 || channels == 4);
6108 /* Number of bytes needed for one row of the image. */
6109 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
6111 /* Allocate memory for the image. */
6112 if (INT_MULTIPLY_WRAPV (row_bytes, sizeof *pixels, &nbytes)
6113 || INT_MULTIPLY_WRAPV (nbytes, height, &nbytes))
6114 memory_full (SIZE_MAX);
6115 c->pixels = pixels = xmalloc (nbytes);
6116 c->rows = rows = xmalloc (height * sizeof *rows);
6117 for (i = 0; i < height; ++i)
6118 rows[i] = pixels + i * row_bytes;
6120 /* Read the entire image. */
6121 png_read_image (png_ptr, rows);
6122 png_read_end (png_ptr, info_ptr);
6123 if (fp)
6125 fclose (fp);
6126 c->fp = NULL;
6129 #ifdef USE_CAIRO
6130 data = (unsigned char *) xmalloc (width * height * 4);
6131 dataptr = (uint32_t *) data;
6132 #else
6133 /* Create an image and pixmap serving as mask if the PNG image
6134 contains an alpha channel. */
6135 if (channels == 4
6136 && !transparent_p
6137 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
6138 &mask_img, 1))
6140 x_destroy_x_image (ximg);
6141 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
6142 goto error;
6144 #endif
6146 /* Fill the X image and mask from PNG data. */
6147 init_color_table ();
6149 for (y = 0; y < height; ++y)
6151 png_byte *p = rows[y];
6153 for (x = 0; x < width; ++x)
6155 int r, g, b;
6157 #ifdef USE_CAIRO
6158 int a = 0xff;
6159 r = *p++;
6160 g = *p++;
6161 b = *p++;
6162 if (channels == 4) a = *p++;
6163 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
6164 #else
6165 r = *p++ << 8;
6166 g = *p++ << 8;
6167 b = *p++ << 8;
6168 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6169 /* An alpha channel, aka mask channel, associates variable
6170 transparency with an image. Where other image formats
6171 support binary transparency---fully transparent or fully
6172 opaque---PNG allows up to 254 levels of partial transparency.
6173 The PNG library implements partial transparency by combining
6174 the image with a specified background color.
6176 I'm not sure how to handle this here nicely: because the
6177 background on which the image is displayed may change, for
6178 real alpha channel support, it would be necessary to create
6179 a new image for each possible background.
6181 What I'm doing now is that a mask is created if we have
6182 boolean transparency information. Otherwise I'm using
6183 the frame's background color to combine the image with. */
6185 if (channels == 4)
6187 if (mask_img)
6188 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6189 ++p;
6191 #endif
6195 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6196 /* Set IMG's background color from the PNG image, unless the user
6197 overrode it. */
6199 png_color_16 *bg;
6200 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6202 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6203 img->background_valid = 1;
6207 # ifdef COLOR_TABLE_SUPPORT
6208 /* Remember colors allocated for this image. */
6209 img->colors = colors_in_color_table (&img->ncolors);
6210 free_color_table ();
6211 # endif /* COLOR_TABLE_SUPPORT */
6213 /* Clean up. */
6214 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6215 xfree (rows);
6216 xfree (pixels);
6218 img->width = width;
6219 img->height = height;
6221 #ifdef USE_CAIRO
6222 create_cairo_image_surface (img, data, width, height);
6223 #else
6224 /* Maybe fill in the background field while we have ximg handy.
6225 Casting avoids a GCC warning. */
6226 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6228 /* Put ximg into the image. */
6229 image_put_x_image (f, img, ximg, 0);
6231 /* Same for the mask. */
6232 if (mask_img)
6234 /* Fill in the background_transparent field while we have the
6235 mask handy. Casting avoids a GCC warning. */
6236 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6238 image_put_x_image (f, img, mask_img, 1);
6240 #endif
6242 return 1;
6245 static bool
6246 png_load (struct frame *f, struct image *img)
6248 struct png_load_context c;
6249 return png_load_body (f, img, &c);
6252 #elif defined HAVE_NS
6254 static bool
6255 png_load (struct frame *f, struct image *img)
6257 return ns_load_image (f, img,
6258 image_spec_value (img->spec, QCfile, NULL),
6259 image_spec_value (img->spec, QCdata, NULL));
6263 #endif /* HAVE_NS */
6267 /***********************************************************************
6268 JPEG
6269 ***********************************************************************/
6271 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6273 static bool jpeg_image_p (Lisp_Object object);
6274 static bool jpeg_load (struct frame *f, struct image *img);
6276 /* Indices of image specification fields in gs_format, below. */
6278 enum jpeg_keyword_index
6280 JPEG_TYPE,
6281 JPEG_DATA,
6282 JPEG_FILE,
6283 JPEG_ASCENT,
6284 JPEG_MARGIN,
6285 JPEG_RELIEF,
6286 JPEG_ALGORITHM,
6287 JPEG_HEURISTIC_MASK,
6288 JPEG_MASK,
6289 JPEG_BACKGROUND,
6290 JPEG_LAST
6293 /* Vector of image_keyword structures describing the format
6294 of valid user-defined image specifications. */
6296 static const struct image_keyword jpeg_format[JPEG_LAST] =
6298 {":type", IMAGE_SYMBOL_VALUE, 1},
6299 {":data", IMAGE_STRING_VALUE, 0},
6300 {":file", IMAGE_STRING_VALUE, 0},
6301 {":ascent", IMAGE_ASCENT_VALUE, 0},
6302 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6303 {":relief", IMAGE_INTEGER_VALUE, 0},
6304 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6305 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6306 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6307 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6310 #if defined HAVE_NTGUI && defined WINDOWSNT
6311 static bool init_jpeg_functions (void);
6312 #else
6313 #define init_jpeg_functions NULL
6314 #endif
6316 /* Structure describing the image type `jpeg'. */
6318 static struct image_type jpeg_type =
6320 SYMBOL_INDEX (Qjpeg),
6321 jpeg_image_p,
6322 jpeg_load,
6323 x_clear_image,
6324 init_jpeg_functions,
6325 NULL
6328 /* Return true if OBJECT is a valid JPEG image specification. */
6330 static bool
6331 jpeg_image_p (Lisp_Object object)
6333 struct image_keyword fmt[JPEG_LAST];
6335 memcpy (fmt, jpeg_format, sizeof fmt);
6337 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6338 return 0;
6340 /* Must specify either the :data or :file keyword. */
6341 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6344 #endif /* HAVE_JPEG || HAVE_NS */
6346 #ifdef HAVE_JPEG
6348 /* Work around a warning about HAVE_STDLIB_H being redefined in
6349 jconfig.h. */
6350 # ifdef HAVE_STDLIB_H
6351 # undef HAVE_STDLIB_H
6352 # endif
6354 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6355 /* In older releases of the jpeg library, jpeglib.h will define boolean
6356 differently depending on __WIN32__, so make sure it is defined. */
6357 # define __WIN32__ 1
6358 # endif
6360 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6361 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6362 using the Windows boolean type instead of the jpeglib boolean type
6363 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6364 headers are included along with windows.h, so under Cygwin, jpeglib
6365 attempts to define a conflicting boolean type. Worse, forcing
6366 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6367 because it created an ABI incompatibility between the
6368 already-compiled jpeg library and the header interface definition.
6370 The best we can do is to define jpeglib's boolean type to a
6371 different name. This name, jpeg_boolean, remains in effect through
6372 the rest of image.c.
6374 # if defined CYGWIN && defined HAVE_NTGUI
6375 # define boolean jpeg_boolean
6376 # endif
6377 # include <jpeglib.h>
6378 # include <jerror.h>
6380 # ifdef WINDOWSNT
6382 /* JPEG library details. */
6383 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6384 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6385 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6386 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6387 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6388 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6389 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6390 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6391 (struct jpeg_error_mgr *));
6392 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6394 static bool
6395 init_jpeg_functions (void)
6397 HMODULE library;
6399 if (!(library = w32_delayed_load (Qjpeg)))
6400 return 0;
6402 LOAD_DLL_FN (library, jpeg_finish_decompress);
6403 LOAD_DLL_FN (library, jpeg_read_scanlines);
6404 LOAD_DLL_FN (library, jpeg_start_decompress);
6405 LOAD_DLL_FN (library, jpeg_read_header);
6406 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6407 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6408 LOAD_DLL_FN (library, jpeg_std_error);
6409 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6410 return 1;
6413 # undef jpeg_CreateDecompress
6414 # undef jpeg_destroy_decompress
6415 # undef jpeg_finish_decompress
6416 # undef jpeg_read_header
6417 # undef jpeg_read_scanlines
6418 # undef jpeg_resync_to_restart
6419 # undef jpeg_start_decompress
6420 # undef jpeg_std_error
6422 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6423 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6424 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6425 # define jpeg_read_header fn_jpeg_read_header
6426 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6427 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6428 # define jpeg_start_decompress fn_jpeg_start_decompress
6429 # define jpeg_std_error fn_jpeg_std_error
6431 /* Wrapper since we can't directly assign the function pointer
6432 to another function pointer that was declared more completely easily. */
6433 static boolean
6434 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6436 return jpeg_resync_to_restart (cinfo, desired);
6438 # undef jpeg_resync_to_restart
6439 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6441 # endif /* WINDOWSNT */
6443 struct my_jpeg_error_mgr
6445 struct jpeg_error_mgr pub;
6446 sys_jmp_buf setjmp_buffer;
6448 /* The remaining members are so that longjmp doesn't munge local
6449 variables. */
6450 struct jpeg_decompress_struct cinfo;
6451 enum
6453 MY_JPEG_ERROR_EXIT,
6454 MY_JPEG_INVALID_IMAGE_SIZE,
6455 MY_JPEG_CANNOT_CREATE_X
6456 } failure_code;
6460 static _Noreturn void
6461 my_error_exit (j_common_ptr cinfo)
6463 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6464 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6465 sys_longjmp (mgr->setjmp_buffer, 1);
6469 /* Init source method for JPEG data source manager. Called by
6470 jpeg_read_header() before any data is actually read. See
6471 libjpeg.doc from the JPEG lib distribution. */
6473 static void
6474 our_common_init_source (j_decompress_ptr cinfo)
6479 /* Method to terminate data source. Called by
6480 jpeg_finish_decompress() after all data has been processed. */
6482 static void
6483 our_common_term_source (j_decompress_ptr cinfo)
6488 /* Fill input buffer method for JPEG data source manager. Called
6489 whenever more data is needed. We read the whole image in one step,
6490 so this only adds a fake end of input marker at the end. */
6492 static JOCTET our_memory_buffer[2];
6494 static boolean
6495 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6497 /* Insert a fake EOI marker. */
6498 struct jpeg_source_mgr *src = cinfo->src;
6500 our_memory_buffer[0] = (JOCTET) 0xFF;
6501 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6503 src->next_input_byte = our_memory_buffer;
6504 src->bytes_in_buffer = 2;
6505 return 1;
6509 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6510 is the JPEG data source manager. */
6512 static void
6513 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6515 struct jpeg_source_mgr *src = cinfo->src;
6517 if (src)
6519 if (num_bytes > src->bytes_in_buffer)
6520 ERREXIT (cinfo, JERR_INPUT_EOF);
6522 src->bytes_in_buffer -= num_bytes;
6523 src->next_input_byte += num_bytes;
6528 /* Set up the JPEG lib for reading an image from DATA which contains
6529 LEN bytes. CINFO is the decompression info structure created for
6530 reading the image. */
6532 static void
6533 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6535 struct jpeg_source_mgr *src = cinfo->src;
6537 if (! src)
6539 /* First time for this JPEG object? */
6540 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6541 JPOOL_PERMANENT, sizeof *src);
6542 cinfo->src = src;
6543 src->next_input_byte = data;
6546 src->init_source = our_common_init_source;
6547 src->fill_input_buffer = our_memory_fill_input_buffer;
6548 src->skip_input_data = our_memory_skip_input_data;
6549 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6550 src->term_source = our_common_term_source;
6551 src->bytes_in_buffer = len;
6552 src->next_input_byte = data;
6556 struct jpeg_stdio_mgr
6558 struct jpeg_source_mgr mgr;
6559 boolean finished;
6560 FILE *file;
6561 JOCTET *buffer;
6565 /* Size of buffer to read JPEG from file.
6566 Not too big, as we want to use alloc_small. */
6567 #define JPEG_STDIO_BUFFER_SIZE 8192
6570 /* Fill input buffer method for JPEG data source manager. Called
6571 whenever more data is needed. The data is read from a FILE *. */
6573 static boolean
6574 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6576 struct jpeg_stdio_mgr *src;
6578 src = (struct jpeg_stdio_mgr *) cinfo->src;
6579 if (!src->finished)
6581 ptrdiff_t bytes;
6583 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6584 if (bytes > 0)
6585 src->mgr.bytes_in_buffer = bytes;
6586 else
6588 WARNMS (cinfo, JWRN_JPEG_EOF);
6589 src->finished = 1;
6590 src->buffer[0] = (JOCTET) 0xFF;
6591 src->buffer[1] = (JOCTET) JPEG_EOI;
6592 src->mgr.bytes_in_buffer = 2;
6594 src->mgr.next_input_byte = src->buffer;
6597 return 1;
6601 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6602 is the JPEG data source manager. */
6604 static void
6605 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6607 struct jpeg_stdio_mgr *src;
6608 src = (struct jpeg_stdio_mgr *) cinfo->src;
6610 while (num_bytes > 0 && !src->finished)
6612 if (num_bytes <= src->mgr.bytes_in_buffer)
6614 src->mgr.bytes_in_buffer -= num_bytes;
6615 src->mgr.next_input_byte += num_bytes;
6616 break;
6618 else
6620 num_bytes -= src->mgr.bytes_in_buffer;
6621 src->mgr.bytes_in_buffer = 0;
6622 src->mgr.next_input_byte = NULL;
6624 our_stdio_fill_input_buffer (cinfo);
6630 /* Set up the JPEG lib for reading an image from a FILE *.
6631 CINFO is the decompression info structure created for
6632 reading the image. */
6634 static void
6635 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6637 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6639 if (! src)
6641 /* First time for this JPEG object? */
6642 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6643 JPOOL_PERMANENT, sizeof *src);
6644 cinfo->src = (struct jpeg_source_mgr *) src;
6645 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6646 JPOOL_PERMANENT,
6647 JPEG_STDIO_BUFFER_SIZE);
6650 src->file = fp;
6651 src->finished = 0;
6652 src->mgr.init_source = our_common_init_source;
6653 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6654 src->mgr.skip_input_data = our_stdio_skip_input_data;
6655 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6656 src->mgr.term_source = our_common_term_source;
6657 src->mgr.bytes_in_buffer = 0;
6658 src->mgr.next_input_byte = NULL;
6661 /* Load image IMG for use on frame F. Patterned after example.c
6662 from the JPEG lib. */
6664 static bool
6665 jpeg_load_body (struct frame *f, struct image *img,
6666 struct my_jpeg_error_mgr *mgr)
6668 Lisp_Object specified_file, specified_data;
6669 FILE *volatile fp = NULL;
6670 JSAMPARRAY buffer;
6671 int row_stride, x, y;
6672 unsigned long *colors;
6673 int width, height;
6674 int i, ir, ig, ib;
6675 #ifndef USE_CAIRO
6676 XImagePtr ximg = NULL;
6677 #endif
6679 /* Open the JPEG file. */
6680 specified_file = image_spec_value (img->spec, QCfile, NULL);
6681 specified_data = image_spec_value (img->spec, QCdata, NULL);
6683 if (NILP (specified_data))
6685 int fd;
6686 Lisp_Object file = x_find_image_fd (specified_file, &fd);
6687 if (!STRINGP (file))
6689 image_error ("Cannot find image file `%s'", specified_file);
6690 return 0;
6693 fp = fdopen (fd, "rb");
6694 if (fp == NULL)
6696 image_error ("Cannot open `%s'", file);
6697 return 0;
6700 else if (!STRINGP (specified_data))
6702 image_error ("Invalid image data `%s'", specified_data);
6703 return 0;
6706 /* Customize libjpeg's error handling to call my_error_exit when an
6707 error is detected. This function will perform a longjmp. */
6708 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6709 mgr->pub.error_exit = my_error_exit;
6710 if (sys_setjmp (mgr->setjmp_buffer))
6712 switch (mgr->failure_code)
6714 case MY_JPEG_ERROR_EXIT:
6716 char buf[JMSG_LENGTH_MAX];
6717 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6718 image_error ("Error reading JPEG image `%s': %s",
6719 img->spec, build_string (buf));
6720 break;
6723 case MY_JPEG_INVALID_IMAGE_SIZE:
6724 image_size_error ();
6725 break;
6727 case MY_JPEG_CANNOT_CREATE_X:
6728 break;
6731 /* Close the input file and destroy the JPEG object. */
6732 if (fp)
6733 fclose (fp);
6734 jpeg_destroy_decompress (&mgr->cinfo);
6736 /* If we already have an XImage, free that. */
6737 #ifndef USE_CAIRO
6738 x_destroy_x_image (ximg);
6739 #endif
6740 /* Free pixmap and colors. */
6741 x_clear_image (f, img);
6742 return 0;
6745 /* Create the JPEG decompression object. Let it read from fp.
6746 Read the JPEG image header. */
6747 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6749 if (NILP (specified_data))
6750 jpeg_file_src (&mgr->cinfo, fp);
6751 else
6752 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6753 SBYTES (specified_data));
6755 jpeg_read_header (&mgr->cinfo, 1);
6757 /* Customize decompression so that color quantization will be used.
6758 Start decompression. */
6759 mgr->cinfo.quantize_colors = 1;
6760 jpeg_start_decompress (&mgr->cinfo);
6761 width = img->width = mgr->cinfo.output_width;
6762 height = img->height = mgr->cinfo.output_height;
6764 if (!check_image_size (f, width, height))
6766 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6767 sys_longjmp (mgr->setjmp_buffer, 1);
6770 #ifndef USE_CAIRO
6771 /* Create X image and pixmap. */
6772 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6774 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6775 sys_longjmp (mgr->setjmp_buffer, 1);
6777 #endif
6779 /* Allocate colors. When color quantization is used,
6780 mgr->cinfo.actual_number_of_colors has been set with the number of
6781 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6782 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6783 No more than 255 colors will be generated. */
6784 USE_SAFE_ALLOCA;
6786 if (mgr->cinfo.out_color_components > 2)
6787 ir = 0, ig = 1, ib = 2;
6788 else if (mgr->cinfo.out_color_components > 1)
6789 ir = 0, ig = 1, ib = 0;
6790 else
6791 ir = 0, ig = 0, ib = 0;
6793 #ifndef CAIRO
6794 /* Use the color table mechanism because it handles colors that
6795 cannot be allocated nicely. Such colors will be replaced with
6796 a default color, and we don't have to care about which colors
6797 can be freed safely, and which can't. */
6798 init_color_table ();
6799 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6801 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6803 /* Multiply RGB values with 255 because X expects RGB values
6804 in the range 0..0xffff. */
6805 int r = mgr->cinfo.colormap[ir][i] << 8;
6806 int g = mgr->cinfo.colormap[ig][i] << 8;
6807 int b = mgr->cinfo.colormap[ib][i] << 8;
6808 colors[i] = lookup_rgb_color (f, r, g, b);
6810 #endif
6812 #ifdef COLOR_TABLE_SUPPORT
6813 /* Remember those colors actually allocated. */
6814 img->colors = colors_in_color_table (&img->ncolors);
6815 free_color_table ();
6816 #endif /* COLOR_TABLE_SUPPORT */
6819 /* Read pixels. */
6820 row_stride = width * mgr->cinfo.output_components;
6821 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6822 JPOOL_IMAGE, row_stride, 1);
6823 #ifdef USE_CAIRO
6825 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
6826 uint32_t *dataptr = (uint32_t *) data;
6827 int r, g, b;
6829 for (y = 0; y < height; ++y)
6831 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6833 for (x = 0; x < width; ++x)
6835 i = buffer[0][x];
6836 r = mgr->cinfo.colormap[ir][i];
6837 g = mgr->cinfo.colormap[ig][i];
6838 b = mgr->cinfo.colormap[ib][i];
6839 *dataptr++ = (0xffu << 24) | (r << 16) | (g << 8) | b;
6843 create_cairo_image_surface (img, data, width, height);
6845 #else
6846 for (y = 0; y < height; ++y)
6848 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6849 for (x = 0; x < mgr->cinfo.output_width; ++x)
6850 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6852 #endif
6854 /* Clean up. */
6855 jpeg_finish_decompress (&mgr->cinfo);
6856 jpeg_destroy_decompress (&mgr->cinfo);
6857 if (fp)
6858 fclose (fp);
6860 #ifndef USE_CAIRO
6861 /* Maybe fill in the background field while we have ximg handy. */
6862 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6863 /* Casting avoids a GCC warning. */
6864 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6866 /* Put ximg into the image. */
6867 image_put_x_image (f, img, ximg, 0);
6868 #endif
6869 SAFE_FREE ();
6870 return 1;
6873 static bool
6874 jpeg_load (struct frame *f, struct image *img)
6876 struct my_jpeg_error_mgr mgr;
6877 return jpeg_load_body (f, img, &mgr);
6880 #else /* HAVE_JPEG */
6882 #ifdef HAVE_NS
6883 static bool
6884 jpeg_load (struct frame *f, struct image *img)
6886 return ns_load_image (f, img,
6887 image_spec_value (img->spec, QCfile, NULL),
6888 image_spec_value (img->spec, QCdata, NULL));
6890 #endif /* HAVE_NS */
6892 #endif /* !HAVE_JPEG */
6896 /***********************************************************************
6897 TIFF
6898 ***********************************************************************/
6900 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6902 static bool tiff_image_p (Lisp_Object object);
6903 static bool tiff_load (struct frame *f, struct image *img);
6905 /* Indices of image specification fields in tiff_format, below. */
6907 enum tiff_keyword_index
6909 TIFF_TYPE,
6910 TIFF_DATA,
6911 TIFF_FILE,
6912 TIFF_ASCENT,
6913 TIFF_MARGIN,
6914 TIFF_RELIEF,
6915 TIFF_ALGORITHM,
6916 TIFF_HEURISTIC_MASK,
6917 TIFF_MASK,
6918 TIFF_BACKGROUND,
6919 TIFF_INDEX,
6920 TIFF_LAST
6923 /* Vector of image_keyword structures describing the format
6924 of valid user-defined image specifications. */
6926 static const struct image_keyword tiff_format[TIFF_LAST] =
6928 {":type", IMAGE_SYMBOL_VALUE, 1},
6929 {":data", IMAGE_STRING_VALUE, 0},
6930 {":file", IMAGE_STRING_VALUE, 0},
6931 {":ascent", IMAGE_ASCENT_VALUE, 0},
6932 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6933 {":relief", IMAGE_INTEGER_VALUE, 0},
6934 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6935 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6936 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6937 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6938 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6941 #if defined HAVE_NTGUI && defined WINDOWSNT
6942 static bool init_tiff_functions (void);
6943 #else
6944 #define init_tiff_functions NULL
6945 #endif
6947 /* Structure describing the image type `tiff'. */
6949 static struct image_type tiff_type =
6951 SYMBOL_INDEX (Qtiff),
6952 tiff_image_p,
6953 tiff_load,
6954 x_clear_image,
6955 init_tiff_functions,
6956 NULL
6959 /* Return true if OBJECT is a valid TIFF image specification. */
6961 static bool
6962 tiff_image_p (Lisp_Object object)
6964 struct image_keyword fmt[TIFF_LAST];
6965 memcpy (fmt, tiff_format, sizeof fmt);
6967 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6968 return 0;
6970 /* Must specify either the :data or :file keyword. */
6971 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6974 #endif /* HAVE_TIFF || HAVE_NS */
6976 #ifdef HAVE_TIFF
6978 # include <tiffio.h>
6980 # ifdef WINDOWSNT
6982 /* TIFF library details. */
6983 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6984 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6985 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
6986 DEF_DLL_FN (TIFF *, TIFFClientOpen,
6987 (const char *, const char *, thandle_t, TIFFReadWriteProc,
6988 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6989 TIFFMapFileProc, TIFFUnmapFileProc));
6990 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6991 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6992 DEF_DLL_FN (void, TIFFClose, (TIFF *));
6993 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6995 static bool
6996 init_tiff_functions (void)
6998 HMODULE library;
7000 if (!(library = w32_delayed_load (Qtiff)))
7001 return 0;
7003 LOAD_DLL_FN (library, TIFFSetErrorHandler);
7004 LOAD_DLL_FN (library, TIFFSetWarningHandler);
7005 LOAD_DLL_FN (library, TIFFOpen);
7006 LOAD_DLL_FN (library, TIFFClientOpen);
7007 LOAD_DLL_FN (library, TIFFGetField);
7008 LOAD_DLL_FN (library, TIFFReadRGBAImage);
7009 LOAD_DLL_FN (library, TIFFClose);
7010 LOAD_DLL_FN (library, TIFFSetDirectory);
7011 return 1;
7014 # undef TIFFClientOpen
7015 # undef TIFFClose
7016 # undef TIFFGetField
7017 # undef TIFFOpen
7018 # undef TIFFReadRGBAImage
7019 # undef TIFFSetDirectory
7020 # undef TIFFSetErrorHandler
7021 # undef TIFFSetWarningHandler
7023 # define TIFFClientOpen fn_TIFFClientOpen
7024 # define TIFFClose fn_TIFFClose
7025 # define TIFFGetField fn_TIFFGetField
7026 # define TIFFOpen fn_TIFFOpen
7027 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7028 # define TIFFSetDirectory fn_TIFFSetDirectory
7029 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7030 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7032 # endif /* WINDOWSNT */
7035 /* Reading from a memory buffer for TIFF images Based on the PNG
7036 memory source, but we have to provide a lot of extra functions.
7037 Blah.
7039 We really only need to implement read and seek, but I am not
7040 convinced that the TIFF library is smart enough not to destroy
7041 itself if we only hand it the function pointers we need to
7042 override. */
7044 typedef struct
7046 unsigned char *bytes;
7047 ptrdiff_t len;
7048 ptrdiff_t index;
7050 tiff_memory_source;
7052 static tsize_t
7053 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7055 tiff_memory_source *src = (tiff_memory_source *) data;
7057 size = min (size, src->len - src->index);
7058 memcpy (buf, src->bytes + src->index, size);
7059 src->index += size;
7060 return size;
7063 static tsize_t
7064 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7066 return -1;
7069 static toff_t
7070 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
7072 tiff_memory_source *src = (tiff_memory_source *) data;
7073 ptrdiff_t idx;
7075 switch (whence)
7077 case SEEK_SET: /* Go from beginning of source. */
7078 idx = off;
7079 break;
7081 case SEEK_END: /* Go from end of source. */
7082 idx = src->len + off;
7083 break;
7085 case SEEK_CUR: /* Go from current position. */
7086 idx = src->index + off;
7087 break;
7089 default: /* Invalid `whence'. */
7090 return -1;
7093 if (idx > src->len || idx < 0)
7094 return -1;
7096 src->index = idx;
7097 return src->index;
7100 static int
7101 tiff_close_memory (thandle_t data)
7103 /* NOOP */
7104 return 0;
7107 static int
7108 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
7110 /* It is already _IN_ memory. */
7111 return 0;
7114 static void
7115 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
7117 /* We don't need to do this. */
7120 static toff_t
7121 tiff_size_of_memory (thandle_t data)
7123 return ((tiff_memory_source *) data)->len;
7126 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7127 compiler error compiling tiff_handler, see Bugzilla bug #17406
7128 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7129 this function as external works around that problem. */
7130 # if defined (__MINGW32__) && __GNUC__ == 3
7131 # define MINGW_STATIC
7132 # else
7133 # define MINGW_STATIC static
7134 # endif
7136 MINGW_STATIC void
7137 tiff_handler (const char *, const char *, const char *, va_list)
7138 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7139 MINGW_STATIC void
7140 tiff_handler (const char *log_format, const char *title,
7141 const char *format, va_list ap)
7143 /* doprnt is not suitable here, as TIFF handlers are called from
7144 libtiff and are passed arbitrary printf directives. Instead, use
7145 vsnprintf, taking care to be portable to nonstandard environments
7146 where vsnprintf returns -1 on buffer overflow. Since it's just a
7147 log entry, it's OK to truncate it. */
7148 char buf[4000];
7149 int len = vsnprintf (buf, sizeof buf, format, ap);
7150 add_to_log (log_format, build_string (title),
7151 make_string (buf, max (0, min (len, sizeof buf - 1))));
7153 # undef MINGW_STATIC
7155 static void tiff_error_handler (const char *, const char *, va_list)
7156 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7157 static void
7158 tiff_error_handler (const char *title, const char *format, va_list ap)
7160 tiff_handler ("TIFF error: %s %s", title, format, ap);
7164 static void tiff_warning_handler (const char *, const char *, va_list)
7165 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7166 static void
7167 tiff_warning_handler (const char *title, const char *format, va_list ap)
7169 tiff_handler ("TIFF warning: %s %s", title, format, ap);
7173 /* Load TIFF image IMG for use on frame F. Value is true if
7174 successful. */
7176 static bool
7177 tiff_load (struct frame *f, struct image *img)
7179 Lisp_Object specified_file;
7180 Lisp_Object specified_data;
7181 TIFF *tiff;
7182 int width, height, x, y, count;
7183 uint32 *buf;
7184 int rc;
7185 XImagePtr ximg;
7186 tiff_memory_source memsrc;
7187 Lisp_Object image;
7189 specified_file = image_spec_value (img->spec, QCfile, NULL);
7190 specified_data = image_spec_value (img->spec, QCdata, NULL);
7192 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
7193 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7195 if (NILP (specified_data))
7197 /* Read from a file */
7198 Lisp_Object file = x_find_image_file (specified_file);
7199 if (!STRINGP (file))
7201 image_error ("Cannot find image file `%s'", specified_file);
7202 return 0;
7205 Lisp_Object encoded_file = ENCODE_FILE (file);
7206 # ifdef WINDOWSNT
7207 encoded_file = ansi_encode_filename (encoded_file);
7208 # endif
7210 /* Try to open the image file. */
7211 tiff = TIFFOpen (SSDATA (encoded_file), "r");
7212 if (tiff == NULL)
7214 image_error ("Cannot open `%s'", file);
7215 return 0;
7218 else
7220 if (!STRINGP (specified_data))
7222 image_error ("Invalid image data `%s'", specified_data);
7223 return 0;
7226 /* Memory source! */
7227 memsrc.bytes = SDATA (specified_data);
7228 memsrc.len = SBYTES (specified_data);
7229 memsrc.index = 0;
7231 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7232 tiff_read_from_memory,
7233 tiff_write_from_memory,
7234 tiff_seek_in_memory,
7235 tiff_close_memory,
7236 tiff_size_of_memory,
7237 tiff_mmap_memory,
7238 tiff_unmap_memory);
7240 if (!tiff)
7242 image_error ("Cannot open memory source for `%s'", img->spec);
7243 return 0;
7247 image = image_spec_value (img->spec, QCindex, NULL);
7248 if (INTEGERP (image))
7250 EMACS_INT ino = XFASTINT (image);
7251 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7252 && TIFFSetDirectory (tiff, ino)))
7254 image_error ("Invalid image number `%s' in image `%s'",
7255 image, img->spec);
7256 TIFFClose (tiff);
7257 return 0;
7261 /* Get width and height of the image, and allocate a raster buffer
7262 of width x height 32-bit values. */
7263 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7264 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7266 if (!check_image_size (f, width, height))
7268 image_size_error ();
7269 TIFFClose (tiff);
7270 return 0;
7273 /* Create the X image and pixmap. */
7274 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7275 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7276 &ximg, 0)))
7278 TIFFClose (tiff);
7279 return 0;
7282 buf = xmalloc (sizeof *buf * width * height);
7284 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7286 /* Count the number of images in the file. */
7287 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7288 continue;
7290 if (count > 1)
7291 img->lisp_data = Fcons (Qcount,
7292 Fcons (make_number (count),
7293 img->lisp_data));
7295 TIFFClose (tiff);
7296 if (!rc)
7298 image_error ("Error reading TIFF image `%s'", img->spec);
7299 xfree (buf);
7300 return 0;
7303 #ifdef USE_CAIRO
7305 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
7306 uint32_t *dataptr = (uint32_t *) data;
7308 for (y = 0; y < height; ++y)
7310 uint32 *row = buf + (height - 1 - y) * width;
7311 for (x = 0; x < width; ++x)
7313 uint32 abgr = row[x];
7314 int r = TIFFGetR (abgr);
7315 int g = TIFFGetG (abgr);
7316 int b = TIFFGetB (abgr);
7317 int a = TIFFGetA (abgr);
7318 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
7322 create_cairo_image_surface (img, data, width, height);
7324 #else
7325 /* Initialize the color table. */
7326 init_color_table ();
7328 /* Process the pixel raster. Origin is in the lower-left corner. */
7329 for (y = 0; y < height; ++y)
7331 uint32 *row = buf + y * width;
7333 for (x = 0; x < width; ++x)
7335 uint32 abgr = row[x];
7336 int r = TIFFGetR (abgr) << 8;
7337 int g = TIFFGetG (abgr) << 8;
7338 int b = TIFFGetB (abgr) << 8;
7339 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7343 # ifdef COLOR_TABLE_SUPPORT
7344 /* Remember the colors allocated for the image. Free the color table. */
7345 img->colors = colors_in_color_table (&img->ncolors);
7346 free_color_table ();
7347 # endif /* COLOR_TABLE_SUPPORT */
7349 img->width = width;
7350 img->height = height;
7352 /* Maybe fill in the background field while we have ximg handy. */
7353 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7354 /* Casting avoids a GCC warning on W32. */
7355 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7357 /* Put ximg into the image. */
7358 image_put_x_image (f, img, ximg, 0);
7360 #endif /* ! USE_CAIRO */
7362 xfree (buf);
7363 return 1;
7366 #elif defined HAVE_NS
7368 static bool
7369 tiff_load (struct frame *f, struct image *img)
7371 return ns_load_image (f, img,
7372 image_spec_value (img->spec, QCfile, NULL),
7373 image_spec_value (img->spec, QCdata, NULL));
7376 #endif
7380 /***********************************************************************
7382 ***********************************************************************/
7384 #if defined (HAVE_GIF) || defined (HAVE_NS)
7386 static bool gif_image_p (Lisp_Object object);
7387 static bool gif_load (struct frame *f, struct image *img);
7388 static void gif_clear_image (struct frame *f, struct image *img);
7390 /* Indices of image specification fields in gif_format, below. */
7392 enum gif_keyword_index
7394 GIF_TYPE,
7395 GIF_DATA,
7396 GIF_FILE,
7397 GIF_ASCENT,
7398 GIF_MARGIN,
7399 GIF_RELIEF,
7400 GIF_ALGORITHM,
7401 GIF_HEURISTIC_MASK,
7402 GIF_MASK,
7403 GIF_IMAGE,
7404 GIF_BACKGROUND,
7405 GIF_LAST
7408 /* Vector of image_keyword structures describing the format
7409 of valid user-defined image specifications. */
7411 static const struct image_keyword gif_format[GIF_LAST] =
7413 {":type", IMAGE_SYMBOL_VALUE, 1},
7414 {":data", IMAGE_STRING_VALUE, 0},
7415 {":file", IMAGE_STRING_VALUE, 0},
7416 {":ascent", IMAGE_ASCENT_VALUE, 0},
7417 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7418 {":relief", IMAGE_INTEGER_VALUE, 0},
7419 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7420 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7421 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7422 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7423 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7426 #if defined HAVE_NTGUI && defined WINDOWSNT
7427 static bool init_gif_functions (void);
7428 #else
7429 #define init_gif_functions NULL
7430 #endif
7432 /* Structure describing the image type `gif'. */
7434 static struct image_type gif_type =
7436 SYMBOL_INDEX (Qgif),
7437 gif_image_p,
7438 gif_load,
7439 gif_clear_image,
7440 init_gif_functions,
7441 NULL
7444 /* Free X resources of GIF image IMG which is used on frame F. */
7446 static void
7447 gif_clear_image (struct frame *f, struct image *img)
7449 img->lisp_data = Qnil;
7450 x_clear_image (f, img);
7453 /* Return true if OBJECT is a valid GIF image specification. */
7455 static bool
7456 gif_image_p (Lisp_Object object)
7458 struct image_keyword fmt[GIF_LAST];
7459 memcpy (fmt, gif_format, sizeof fmt);
7461 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7462 return 0;
7464 /* Must specify either the :data or :file keyword. */
7465 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7468 #endif /* HAVE_GIF */
7470 #ifdef HAVE_GIF
7472 # ifdef HAVE_NTGUI
7474 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7475 Undefine before redefining to avoid a preprocessor warning. */
7476 # ifdef DrawText
7477 # undef DrawText
7478 # endif
7479 /* avoid conflict with QuickdrawText.h */
7480 # define DrawText gif_DrawText
7481 # include <gif_lib.h>
7482 /* The bogus ifdef below, which is always true, is to avoid a compiler
7483 warning about DrawText being unused. */
7484 # ifdef DrawText
7485 # undef DrawText
7486 # endif
7488 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7489 # ifndef GIFLIB_MINOR
7490 # define GIFLIB_MINOR 0
7491 # endif
7492 # ifndef GIFLIB_RELEASE
7493 # define GIFLIB_RELEASE 0
7494 # endif
7496 # else /* HAVE_NTGUI */
7498 # include <gif_lib.h>
7500 # endif /* HAVE_NTGUI */
7502 /* Giflib before 5.0 didn't define these macros. */
7503 # ifndef GIFLIB_MAJOR
7504 # define GIFLIB_MAJOR 4
7505 # endif
7507 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7508 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7509 earlier releases, where either it returns char * or GIFLIB_MINOR
7510 may be incorrect. */
7511 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7513 # ifdef WINDOWSNT
7515 /* GIF library details. */
7516 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7517 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7518 # else
7519 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7520 # endif
7521 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7522 # if GIFLIB_MAJOR < 5
7523 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7524 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7525 # else
7526 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7527 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7528 # endif
7529 # if HAVE_GIFERRORSTRING
7530 DEF_DLL_FN (char const *, GifErrorString, (int));
7531 # endif
7533 static bool
7534 init_gif_functions (void)
7536 HMODULE library;
7538 if (!(library = w32_delayed_load (Qgif)))
7539 return 0;
7541 LOAD_DLL_FN (library, DGifCloseFile);
7542 LOAD_DLL_FN (library, DGifSlurp);
7543 LOAD_DLL_FN (library, DGifOpen);
7544 LOAD_DLL_FN (library, DGifOpenFileName);
7545 # if HAVE_GIFERRORSTRING
7546 LOAD_DLL_FN (library, GifErrorString);
7547 # endif
7548 return 1;
7551 # undef DGifCloseFile
7552 # undef DGifOpen
7553 # undef DGifOpenFileName
7554 # undef DGifSlurp
7555 # undef GifErrorString
7557 # define DGifCloseFile fn_DGifCloseFile
7558 # define DGifOpen fn_DGifOpen
7559 # define DGifOpenFileName fn_DGifOpenFileName
7560 # define DGifSlurp fn_DGifSlurp
7561 # define GifErrorString fn_GifErrorString
7563 # endif /* WINDOWSNT */
7565 /* Reading a GIF image from memory
7566 Based on the PNG memory stuff to a certain extent. */
7568 typedef struct
7570 unsigned char *bytes;
7571 ptrdiff_t len;
7572 ptrdiff_t index;
7574 gif_memory_source;
7576 /* Make the current memory source available to gif_read_from_memory.
7577 It's done this way because not all versions of libungif support
7578 a UserData field in the GifFileType structure. */
7579 static gif_memory_source *current_gif_memory_src;
7581 static int
7582 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7584 gif_memory_source *src = current_gif_memory_src;
7586 if (len > src->len - src->index)
7587 return -1;
7589 memcpy (buf, src->bytes + src->index, len);
7590 src->index += len;
7591 return len;
7594 static int
7595 gif_close (GifFileType *gif, int *err)
7597 int retval;
7599 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7600 retval = DGifCloseFile (gif, err);
7601 #else
7602 retval = DGifCloseFile (gif);
7603 #if GIFLIB_MAJOR >= 5
7604 if (err)
7605 *err = gif->Error;
7606 #endif
7607 #endif
7608 return retval;
7611 /* Load GIF image IMG for use on frame F. Value is true if
7612 successful. */
7614 static const int interlace_start[] = {0, 4, 2, 1};
7615 static const int interlace_increment[] = {8, 8, 4, 2};
7617 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7619 static bool
7620 gif_load (struct frame *f, struct image *img)
7622 int rc, width, height, x, y, i, j;
7623 ColorMapObject *gif_color_map;
7624 GifFileType *gif;
7625 gif_memory_source memsrc;
7626 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7627 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7628 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7629 EMACS_INT idx;
7630 int gif_err;
7632 if (NILP (specified_data))
7634 Lisp_Object file = x_find_image_file (specified_file);
7635 if (!STRINGP (file))
7637 image_error ("Cannot find image file `%s'", specified_file);
7638 return 0;
7641 Lisp_Object encoded_file = ENCODE_FILE (file);
7642 #ifdef WINDOWSNT
7643 encoded_file = ansi_encode_filename (encoded_file);
7644 #endif
7646 /* Open the GIF file. */
7647 #if GIFLIB_MAJOR < 5
7648 gif = DGifOpenFileName (SSDATA (encoded_file));
7649 #else
7650 gif = DGifOpenFileName (SSDATA (encoded_file), &gif_err);
7651 #endif
7652 if (gif == NULL)
7654 #if HAVE_GIFERRORSTRING
7655 image_error ("Cannot open `%s': %s",
7656 file, build_string (GifErrorString (gif_err)));
7657 #else
7658 image_error ("Cannot open `%s'", file);
7659 #endif
7660 return 0;
7663 else
7665 if (!STRINGP (specified_data))
7667 image_error ("Invalid image data `%s'", specified_data);
7668 return 0;
7671 /* Read from memory! */
7672 current_gif_memory_src = &memsrc;
7673 memsrc.bytes = SDATA (specified_data);
7674 memsrc.len = SBYTES (specified_data);
7675 memsrc.index = 0;
7677 #if GIFLIB_MAJOR < 5
7678 gif = DGifOpen (&memsrc, gif_read_from_memory);
7679 #else
7680 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7681 #endif
7682 if (!gif)
7684 #if HAVE_GIFERRORSTRING
7685 image_error ("Cannot open memory source `%s': %s",
7686 img->spec, build_string (GifErrorString (gif_err)));
7687 #else
7688 image_error ("Cannot open memory source `%s'", img->spec);
7689 #endif
7690 return 0;
7694 /* Before reading entire contents, check the declared image size. */
7695 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7697 image_size_error ();
7698 gif_close (gif, NULL);
7699 return 0;
7702 /* Read entire contents. */
7703 rc = DGifSlurp (gif);
7704 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7706 image_error ("Error reading `%s'", img->spec);
7707 gif_close (gif, NULL);
7708 return 0;
7711 /* Which sub-image are we to display? */
7713 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7714 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7715 if (idx < 0 || idx >= gif->ImageCount)
7717 image_error ("Invalid image number `%s' in image `%s'",
7718 image_number, img->spec);
7719 gif_close (gif, NULL);
7720 return 0;
7724 width = img->width = gif->SWidth;
7725 height = img->height = gif->SHeight;
7727 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7728 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7729 img->corners[BOT_CORNER]
7730 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7731 img->corners[RIGHT_CORNER]
7732 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7734 if (!check_image_size (f, width, height))
7736 image_size_error ();
7737 gif_close (gif, NULL);
7738 return 0;
7741 /* Check that the selected subimages fit. It's not clear whether
7742 the GIF spec requires this, but Emacs can crash if they don't fit. */
7743 for (j = 0; j <= idx; ++j)
7745 struct SavedImage *subimage = gif->SavedImages + j;
7746 int subimg_width = subimage->ImageDesc.Width;
7747 int subimg_height = subimage->ImageDesc.Height;
7748 int subimg_top = subimage->ImageDesc.Top;
7749 int subimg_left = subimage->ImageDesc.Left;
7750 if (! (subimg_width >= 0 && subimg_height >= 0
7751 && 0 <= subimg_top && subimg_top <= height - subimg_height
7752 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7754 image_error ("Subimage does not fit in image");
7755 gif_close (gif, NULL);
7756 return 0;
7760 #ifdef USE_CAIRO
7761 /* xzalloc so data is zero => transparent */
7762 void *data = xzalloc (width * height * 4);
7763 uint32_t *data32 = data;
7764 if (STRINGP (specified_bg))
7766 XColor color;
7767 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
7769 uint32_t *dataptr = data32;
7770 int r = color.red/256;
7771 int g = color.green/256;
7772 int b = color.blue/256;
7774 for (y = 0; y < height; ++y)
7775 for (x = 0; x < width; ++x)
7776 *dataptr++ = (0xffu << 24) | (r << 16) | (g << 8) | b;
7779 #else
7780 /* Create the X image and pixmap. */
7781 XImagePtr ximg;
7782 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7784 gif_close (gif, NULL);
7785 return 0;
7788 /* Clear the part of the screen image not covered by the image.
7789 Full animated GIF support requires more here (see the gif89 spec,
7790 disposal methods). Let's simply assume that the part not covered
7791 by a sub-image is in the frame's background color. */
7792 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7793 for (x = 0; x < width; ++x)
7794 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7796 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7797 for (x = 0; x < width; ++x)
7798 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7800 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7802 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7803 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7804 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7805 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7807 #endif
7809 /* Read the GIF image into the X image. */
7811 /* FIXME: With the current implementation, loading an animated gif
7812 is quadratic in the number of animation frames, since each frame
7813 is a separate struct image. We must provide a way for a single
7814 gif_load call to construct and save all animation frames. */
7816 init_color_table ();
7818 #ifndef USE_CAIRO
7819 unsigned long bgcolor;
7820 if (STRINGP (specified_bg))
7821 bgcolor = x_alloc_image_color (f, img, specified_bg,
7822 FRAME_BACKGROUND_PIXEL (f));
7823 #endif
7825 for (j = 0; j <= idx; ++j)
7827 /* We use a local variable `raster' here because RasterBits is a
7828 char *, which invites problems with bytes >= 0x80. */
7829 struct SavedImage *subimage = gif->SavedImages + j;
7830 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7831 int transparency_color_index = -1;
7832 int disposal = 0;
7833 int subimg_width = subimage->ImageDesc.Width;
7834 int subimg_height = subimage->ImageDesc.Height;
7835 int subimg_top = subimage->ImageDesc.Top;
7836 int subimg_left = subimage->ImageDesc.Left;
7838 /* Find the Graphic Control Extension block for this sub-image.
7839 Extract the disposal method and transparency color. */
7840 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7842 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7844 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7845 && extblock->ByteCount == 4
7846 && extblock->Bytes[0] & 1)
7848 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7849 to background". Treat any other value like 2. */
7850 disposal = (extblock->Bytes[0] >> 2) & 7;
7851 transparency_color_index = (unsigned char) extblock->Bytes[3];
7852 break;
7856 /* We can't "keep in place" the first subimage. */
7857 if (j == 0)
7858 disposal = 2;
7860 /* For disposal == 0, the spec says "No disposal specified. The
7861 decoder is not required to take any action." In practice, it
7862 seems we need to treat this like "keep in place", see e.g.
7863 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7864 if (disposal == 0)
7865 disposal = 1;
7867 gif_color_map = subimage->ImageDesc.ColorMap;
7868 if (!gif_color_map)
7869 gif_color_map = gif->SColorMap;
7871 #ifndef USE_CAIRO
7872 /* Allocate subimage colors. */
7873 unsigned long pixel_colors[256] = { 0, };
7875 if (gif_color_map)
7876 for (i = 0; i < gif_color_map->ColorCount; ++i)
7878 if (transparency_color_index == i)
7879 pixel_colors[i] = STRINGP (specified_bg)
7880 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7881 else
7883 int r = gif_color_map->Colors[i].Red << 8;
7884 int g = gif_color_map->Colors[i].Green << 8;
7885 int b = gif_color_map->Colors[i].Blue << 8;
7886 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7889 #endif
7891 /* Apply the pixel values. */
7892 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7894 int row, pass;
7896 for (y = 0, row = interlace_start[0], pass = 0;
7897 y < subimg_height;
7898 y++, row += interlace_increment[pass])
7900 while (subimg_height <= row)
7901 row = interlace_start[++pass];
7903 for (x = 0; x < subimg_width; x++)
7905 int c = raster[y * subimg_width + x];
7906 if (transparency_color_index != c || disposal != 1)
7908 #ifdef USE_CAIRO
7909 uint32_t *dataptr =
7910 (data32 + ((row + subimg_top) * subimg_width
7911 + x + subimg_left));
7912 int r = gif_color_map->Colors[c].Red;
7913 int g = gif_color_map->Colors[c].Green;
7914 int b = gif_color_map->Colors[c].Blue;
7916 if (transparency_color_index != c)
7917 *dataptr = (0xffu << 24) | (r << 16) | (g << 8) | b;
7918 #else
7919 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7920 pixel_colors[c]);
7921 #endif
7926 else
7928 for (y = 0; y < subimg_height; ++y)
7929 for (x = 0; x < subimg_width; ++x)
7931 int c = raster[y * subimg_width + x];
7932 if (transparency_color_index != c || disposal != 1)
7934 #ifdef USE_CAIRO
7935 uint32_t *dataptr =
7936 (data32 + ((y + subimg_top) * subimg_width
7937 + x + subimg_left));
7938 int r = gif_color_map->Colors[c].Red;
7939 int g = gif_color_map->Colors[c].Green;
7940 int b = gif_color_map->Colors[c].Blue;
7941 if (transparency_color_index != c)
7942 *dataptr = (0xffu << 24) | (r << 16) | (g << 8) | b;
7943 #else
7944 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7945 pixel_colors[c]);
7946 #endif
7952 #ifdef COLOR_TABLE_SUPPORT
7953 img->colors = colors_in_color_table (&img->ncolors);
7954 free_color_table ();
7955 #endif /* COLOR_TABLE_SUPPORT */
7957 /* Save GIF image extension data for `image-metadata'.
7958 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7959 img->lisp_data = Qnil;
7960 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7962 int delay = 0;
7963 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7964 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7965 /* Append (... FUNCTION "BYTES") */
7967 img->lisp_data
7968 = Fcons (make_number (ext->Function),
7969 Fcons (make_unibyte_string ((char *) ext->Bytes,
7970 ext->ByteCount),
7971 img->lisp_data));
7972 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7973 && ext->ByteCount == 4)
7975 delay = ext->Bytes[2] << CHAR_BIT;
7976 delay |= ext->Bytes[1];
7979 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7980 if (delay)
7981 img->lisp_data
7982 = Fcons (Qdelay,
7983 Fcons (make_float (delay / 100.0),
7984 img->lisp_data));
7987 if (gif->ImageCount > 1)
7988 img->lisp_data = Fcons (Qcount,
7989 Fcons (make_number (gif->ImageCount),
7990 img->lisp_data));
7992 if (gif_close (gif, &gif_err) == GIF_ERROR)
7994 #if HAVE_GIFERRORSTRING
7995 char const *error_text = GifErrorString (gif_err);
7997 if (error_text)
7998 image_error ("Error closing `%s': %s",
7999 img->spec, build_string (error_text));
8000 #else
8001 image_error ("Error closing `%s'", img->spec);
8002 #endif
8005 #ifdef USE_CAIRO
8006 create_cairo_image_surface (img, data, width, height);
8007 #else
8008 /* Maybe fill in the background field while we have ximg handy. */
8009 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8010 /* Casting avoids a GCC warning. */
8011 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8013 /* Put ximg into the image. */
8014 image_put_x_image (f, img, ximg, 0);
8015 #endif
8017 return 1;
8020 #else /* !HAVE_GIF */
8022 #ifdef HAVE_NS
8023 static bool
8024 gif_load (struct frame *f, struct image *img)
8026 return ns_load_image (f, img,
8027 image_spec_value (img->spec, QCfile, NULL),
8028 image_spec_value (img->spec, QCdata, NULL));
8030 #endif /* HAVE_NS */
8032 #endif /* HAVE_GIF */
8035 #ifdef HAVE_IMAGEMAGICK
8037 /***********************************************************************
8038 ImageMagick
8039 ***********************************************************************/
8041 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8042 safely rounded and clipped to int range. */
8044 static int
8045 scale_image_size (int size, size_t divisor, size_t multiplier)
8047 if (divisor != 0)
8049 double s = size;
8050 double scaled = s * multiplier / divisor + 0.5;
8051 if (scaled < INT_MAX)
8052 return scaled;
8054 return INT_MAX;
8057 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8058 Use SPEC to deduce the size. Store the desired size into
8059 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8060 static void
8061 compute_image_size (size_t width, size_t height,
8062 Lisp_Object spec,
8063 int *d_width, int *d_height)
8065 Lisp_Object value;
8066 int desired_width, desired_height;
8067 double scale = 1;
8069 value = image_spec_value (spec, QCscale, NULL);
8070 if (NUMBERP (value))
8071 scale = extract_float (value);
8073 /* If width and/or height is set in the display spec assume we want
8074 to scale to those values. If either h or w is unspecified, the
8075 unspecified should be calculated from the specified to preserve
8076 aspect ratio. */
8077 value = image_spec_value (spec, QCwidth, NULL);
8078 desired_width = NATNUMP (value) ?
8079 min (XFASTINT (value) * scale, INT_MAX) : -1;
8080 value = image_spec_value (spec, QCheight, NULL);
8081 desired_height = NATNUMP (value) ?
8082 min (XFASTINT (value) * scale, INT_MAX) : -1;
8084 width = width * scale;
8085 height = height * scale;
8087 if (desired_width == -1)
8089 value = image_spec_value (spec, QCmax_width, NULL);
8090 if (NATNUMP (value))
8092 int max_width = min (XFASTINT (value), INT_MAX);
8093 if (max_width < width)
8095 /* The image is wider than :max-width. */
8096 desired_width = max_width;
8097 if (desired_height == -1)
8099 desired_height = scale_image_size (desired_width,
8100 width, height);
8101 value = image_spec_value (spec, QCmax_height, NULL);
8102 if (NATNUMP (value))
8104 int max_height = min (XFASTINT (value), INT_MAX);
8105 if (max_height < desired_height)
8107 desired_height = max_height;
8108 desired_width = scale_image_size (desired_height,
8109 height, width);
8117 if (desired_height == -1)
8119 value = image_spec_value (spec, QCmax_height, NULL);
8120 if (NATNUMP (value))
8122 int max_height = min (XFASTINT (value), INT_MAX);
8123 if (max_height < height)
8124 desired_height = max_height;
8128 if (desired_width != -1 && desired_height == -1)
8129 /* w known, calculate h. */
8130 desired_height = scale_image_size (desired_width, width, height);
8132 if (desired_width == -1 && desired_height != -1)
8133 /* h known, calculate w. */
8134 desired_width = scale_image_size (desired_height, height, width);
8136 /* We have no width/height settings, so just apply the scale. */
8137 if (desired_width == -1 && desired_height == -1)
8139 desired_width = width;
8140 desired_height = height;
8143 *d_width = desired_width;
8144 *d_height = desired_height;
8147 static bool imagemagick_image_p (Lisp_Object);
8148 static bool imagemagick_load (struct frame *, struct image *);
8149 static void imagemagick_clear_image (struct frame *, struct image *);
8151 /* Indices of image specification fields in imagemagick_format. */
8153 enum imagemagick_keyword_index
8155 IMAGEMAGICK_TYPE,
8156 IMAGEMAGICK_DATA,
8157 IMAGEMAGICK_FILE,
8158 IMAGEMAGICK_ASCENT,
8159 IMAGEMAGICK_MARGIN,
8160 IMAGEMAGICK_RELIEF,
8161 IMAGEMAGICK_ALGORITHM,
8162 IMAGEMAGICK_HEURISTIC_MASK,
8163 IMAGEMAGICK_MASK,
8164 IMAGEMAGICK_BACKGROUND,
8165 IMAGEMAGICK_HEIGHT,
8166 IMAGEMAGICK_WIDTH,
8167 IMAGEMAGICK_MAX_HEIGHT,
8168 IMAGEMAGICK_MAX_WIDTH,
8169 IMAGEMAGICK_FORMAT,
8170 IMAGEMAGICK_ROTATION,
8171 IMAGEMAGICK_CROP,
8172 IMAGEMAGICK_LAST
8175 /* Vector of image_keyword structures describing the format
8176 of valid user-defined image specifications. */
8178 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
8180 {":type", IMAGE_SYMBOL_VALUE, 1},
8181 {":data", IMAGE_STRING_VALUE, 0},
8182 {":file", IMAGE_STRING_VALUE, 0},
8183 {":ascent", IMAGE_ASCENT_VALUE, 0},
8184 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8185 {":relief", IMAGE_INTEGER_VALUE, 0},
8186 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8187 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8188 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8189 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8190 {":height", IMAGE_INTEGER_VALUE, 0},
8191 {":width", IMAGE_INTEGER_VALUE, 0},
8192 {":max-height", IMAGE_INTEGER_VALUE, 0},
8193 {":max-width", IMAGE_INTEGER_VALUE, 0},
8194 {":format", IMAGE_SYMBOL_VALUE, 0},
8195 {":rotation", IMAGE_NUMBER_VALUE, 0},
8196 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8199 #if defined HAVE_NTGUI && defined WINDOWSNT
8200 static bool init_imagemagick_functions (void);
8201 #else
8202 #define init_imagemagick_functions NULL
8203 #endif
8205 /* Structure describing the image type for any image handled via
8206 ImageMagick. */
8208 static struct image_type imagemagick_type =
8210 SYMBOL_INDEX (Qimagemagick),
8211 imagemagick_image_p,
8212 imagemagick_load,
8213 imagemagick_clear_image,
8214 init_imagemagick_functions,
8215 NULL
8218 /* Free X resources of imagemagick image IMG which is used on frame F. */
8220 static void
8221 imagemagick_clear_image (struct frame *f,
8222 struct image *img)
8224 x_clear_image (f, img);
8227 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8228 this by calling parse_image_spec and supplying the keywords that
8229 identify the IMAGEMAGICK format. */
8231 static bool
8232 imagemagick_image_p (Lisp_Object object)
8234 struct image_keyword fmt[IMAGEMAGICK_LAST];
8235 memcpy (fmt, imagemagick_format, sizeof fmt);
8237 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
8238 return 0;
8240 /* Must specify either the :data or :file keyword. */
8241 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
8244 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8245 Therefore rename the function so it doesn't collide with ImageMagick. */
8246 #define DrawRectangle DrawRectangleGif
8247 #include <wand/MagickWand.h>
8249 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8250 Emacs seems to work fine with the hidden version, so unhide it. */
8251 #include <magick/version.h>
8252 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8253 extern WandExport void PixelGetMagickColor (const PixelWand *,
8254 MagickPixelPacket *);
8255 #endif
8257 /* Log ImageMagick error message.
8258 Useful when a ImageMagick function returns the status `MagickFalse'. */
8260 static void
8261 imagemagick_error (MagickWand *wand)
8263 char *description;
8264 ExceptionType severity;
8266 description = MagickGetException (wand, &severity);
8267 image_error ("ImageMagick error: %s", build_string (description));
8268 MagickRelinquishMemory (description);
8271 /* Possibly give ImageMagick some extra help to determine the image
8272 type by supplying a "dummy" filename based on the Content-Type. */
8274 static char *
8275 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
8277 Lisp_Object symbol = intern ("image-format-suffixes");
8278 Lisp_Object val = find_symbol_value (symbol);
8279 Lisp_Object format;
8281 if (! CONSP (val))
8282 return NULL;
8284 format = image_spec_value (spec, intern (":format"), NULL);
8285 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
8286 if (! STRINGP (val))
8287 return NULL;
8289 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8290 as ImageMagick would ignore the extra bytes anyway. */
8291 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
8292 return hint_buffer;
8295 /* Animated images (e.g., GIF89a) are composed from one "master image"
8296 (which is the first one, and then there's a number of images that
8297 follow. If following images have non-transparent colors, these are
8298 composed "on top" of the master image. So, in general, one has to
8299 compute ann the preceding images to be able to display a particular
8300 sub-image.
8302 Computing all the preceding images is too slow, so we maintain a
8303 cache of previously computed images. We have to maintain a cache
8304 separate from the image cache, because the images may be scaled
8305 before display. */
8307 struct animation_cache
8309 MagickWand *wand;
8310 int index;
8311 struct timespec update_time;
8312 struct animation_cache *next;
8313 char signature[FLEXIBLE_ARRAY_MEMBER];
8316 static struct animation_cache *animation_cache = NULL;
8318 static struct animation_cache *
8319 imagemagick_create_cache (char *signature)
8321 struct animation_cache *cache
8322 = xmalloc (FLEXSIZEOF (struct animation_cache, signature,
8323 strlen (signature) + 1));
8324 cache->wand = 0;
8325 cache->index = 0;
8326 cache->next = 0;
8327 strcpy (cache->signature, signature);
8328 return cache;
8331 /* Discard cached images that haven't been used for a minute. */
8332 static void
8333 imagemagick_prune_animation_cache (void)
8335 struct animation_cache **pcache = &animation_cache;
8336 struct timespec old = timespec_sub (current_timespec (),
8337 make_timespec (60, 0));
8339 while (*pcache)
8341 struct animation_cache *cache = *pcache;
8342 if (timespec_cmp (old, cache->update_time) <= 0)
8343 pcache = &cache->next;
8344 else
8346 if (cache->wand)
8347 DestroyMagickWand (cache->wand);
8348 *pcache = cache->next;
8349 xfree (cache);
8354 static struct animation_cache *
8355 imagemagick_get_animation_cache (MagickWand *wand)
8357 char *signature = MagickGetImageSignature (wand);
8358 struct animation_cache *cache;
8359 struct animation_cache **pcache = &animation_cache;
8361 imagemagick_prune_animation_cache ();
8363 while (1)
8365 cache = *pcache;
8366 if (! cache)
8368 *pcache = cache = imagemagick_create_cache (signature);
8369 break;
8371 if (strcmp (signature, cache->signature) == 0)
8372 break;
8373 pcache = &cache->next;
8376 DestroyString (signature);
8377 cache->update_time = current_timespec ();
8378 return cache;
8381 static MagickWand *
8382 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8384 int i;
8385 MagickWand *composite_wand;
8386 size_t dest_width, dest_height;
8387 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8389 MagickSetIteratorIndex (super_wand, 0);
8391 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8393 composite_wand = MagickGetImage (super_wand);
8394 if (cache->wand)
8395 DestroyMagickWand (cache->wand);
8397 else
8398 composite_wand = cache->wand;
8400 dest_height = MagickGetImageHeight (composite_wand);
8402 for (i = max (1, cache->index + 1); i <= ino; i++)
8404 MagickWand *sub_wand;
8405 PixelIterator *source_iterator, *dest_iterator;
8406 PixelWand **source, **dest;
8407 size_t source_width, source_height;
8408 ssize_t source_left, source_top;
8409 MagickPixelPacket pixel;
8410 DisposeType dispose;
8411 ptrdiff_t lines = 0;
8413 MagickSetIteratorIndex (super_wand, i);
8414 sub_wand = MagickGetImage (super_wand);
8416 MagickGetImagePage (sub_wand, &source_width, &source_height,
8417 &source_left, &source_top);
8419 /* This flag says how to handle transparent pixels. */
8420 dispose = MagickGetImageDispose (sub_wand);
8422 source_iterator = NewPixelIterator (sub_wand);
8423 if (! source_iterator)
8425 DestroyMagickWand (composite_wand);
8426 DestroyMagickWand (sub_wand);
8427 cache->wand = NULL;
8428 image_error ("Imagemagick pixel iterator creation failed");
8429 return NULL;
8432 dest_iterator = NewPixelIterator (composite_wand);
8433 if (! dest_iterator)
8435 DestroyMagickWand (composite_wand);
8436 DestroyMagickWand (sub_wand);
8437 DestroyPixelIterator (source_iterator);
8438 cache->wand = NULL;
8439 image_error ("Imagemagick pixel iterator creation failed");
8440 return NULL;
8443 /* The sub-image may not start at origin, so move the destination
8444 iterator to where the sub-image should start. */
8445 if (source_top > 0)
8447 PixelSetIteratorRow (dest_iterator, source_top);
8448 lines = source_top;
8451 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8452 != NULL)
8454 ptrdiff_t x;
8456 /* Sanity check. This shouldn't happen, but apparently
8457 does in some pictures. */
8458 if (++lines >= dest_height)
8459 break;
8461 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8462 for (x = 0; x < source_width; x++)
8464 /* Sanity check. This shouldn't happen, but apparently
8465 also does in some pictures. */
8466 if (x + source_left >= dest_width)
8467 break;
8468 /* Normally we only copy over non-transparent pixels,
8469 but if the disposal method is "Background", then we
8470 copy over all pixels. */
8471 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8473 PixelGetMagickColor (source[x], &pixel);
8474 PixelSetMagickColor (dest[x + source_left], &pixel);
8477 PixelSyncIterator (dest_iterator);
8480 DestroyPixelIterator (source_iterator);
8481 DestroyPixelIterator (dest_iterator);
8482 DestroyMagickWand (sub_wand);
8485 /* Cache a copy for the next iteration. The current wand will be
8486 destroyed by the caller. */
8487 cache->wand = CloneMagickWand (composite_wand);
8488 cache->index = ino;
8490 return composite_wand;
8494 /* Helper function for imagemagick_load, which does the actual loading
8495 given contents and size, apart from frame and image structures,
8496 passed from imagemagick_load. Uses librimagemagick to do most of
8497 the image processing.
8499 F is a pointer to the Emacs frame; IMG to the image structure to
8500 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8501 be parsed; SIZE is the number of bytes of data; and FILENAME is
8502 either the file name or the image data.
8504 Return true if successful. */
8506 static bool
8507 imagemagick_load_image (struct frame *f, struct image *img,
8508 unsigned char *contents, unsigned int size,
8509 char *filename)
8511 int width, height;
8512 size_t image_width, image_height;
8513 MagickBooleanType status;
8514 XImagePtr ximg;
8515 int x, y;
8516 MagickWand *image_wand;
8517 PixelIterator *iterator;
8518 PixelWand **pixels, *bg_wand = NULL;
8519 MagickPixelPacket pixel;
8520 Lisp_Object image;
8521 Lisp_Object value;
8522 Lisp_Object crop;
8523 EMACS_INT ino;
8524 int desired_width, desired_height;
8525 double rotation;
8526 char hint_buffer[MaxTextExtent];
8527 char *filename_hint = NULL;
8529 /* Handle image index for image types who can contain more than one image.
8530 Interface :index is same as for GIF. First we "ping" the image to see how
8531 many sub-images it contains. Pinging is faster than loading the image to
8532 find out things about it. */
8534 /* Initialize the imagemagick environment. */
8535 MagickWandGenesis ();
8536 image = image_spec_value (img->spec, QCindex, NULL);
8537 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8538 image_wand = NewMagickWand ();
8540 if (filename)
8541 status = MagickReadImage (image_wand, filename);
8542 else
8544 Lisp_Object lwidth = image_spec_value (img->spec, QCwidth, NULL);
8545 Lisp_Object lheight = image_spec_value (img->spec, QCheight, NULL);
8547 if (NATNUMP (lwidth) && NATNUMP (lheight))
8549 MagickSetSize (image_wand, XFASTINT (lwidth), XFASTINT (lheight));
8550 MagickSetDepth (image_wand, 8);
8552 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8553 MagickSetFilename (image_wand, filename_hint);
8554 status = MagickReadImageBlob (image_wand, contents, size);
8557 if (status == MagickFalse)
8559 imagemagick_error (image_wand);
8560 DestroyMagickWand (image_wand);
8561 return 0;
8564 #ifdef HAVE_MAGICKAUTOORIENTIMAGE
8565 /* If no :rotation is explicitly specified, apply the automatic
8566 rotation from EXIF. */
8567 if (NILP (image_spec_value (img->spec, QCrotation, NULL)))
8568 if (MagickAutoOrientImage (image_wand) == MagickFalse)
8570 image_error ("Error applying automatic orientation in image `%s'", img->spec);
8571 DestroyMagickWand (image_wand);
8572 return 0;
8574 #endif
8576 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8578 image_error ("Invalid image number `%s' in image `%s'", image, img->spec);
8579 DestroyMagickWand (image_wand);
8580 return 0;
8583 if (MagickGetImageDelay (image_wand) > 0)
8584 img->lisp_data =
8585 Fcons (Qdelay,
8586 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8587 img->lisp_data));
8589 if (MagickGetNumberImages (image_wand) > 1)
8590 img->lisp_data =
8591 Fcons (Qcount,
8592 Fcons (make_number (MagickGetNumberImages (image_wand)),
8593 img->lisp_data));
8595 /* If we have an animated image, get the new wand based on the
8596 "super-wand". */
8597 if (MagickGetNumberImages (image_wand) > 1)
8599 MagickWand *super_wand = image_wand;
8600 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8601 if (! image_wand)
8602 image_wand = super_wand;
8603 else
8604 DestroyMagickWand (super_wand);
8607 /* Retrieve the frame's background color, for use later. */
8609 XColor bgcolor;
8610 Lisp_Object specified_bg;
8612 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8613 if (!STRINGP (specified_bg)
8614 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8615 x_query_frame_background_color (f, &bgcolor);
8617 bg_wand = NewPixelWand ();
8618 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8619 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8620 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8623 compute_image_size (MagickGetImageWidth (image_wand),
8624 MagickGetImageHeight (image_wand),
8625 img->spec, &desired_width, &desired_height);
8627 if (desired_width != -1 && desired_height != -1)
8629 status = MagickScaleImage (image_wand, desired_width, desired_height);
8630 if (status == MagickFalse)
8632 image_error ("Imagemagick scale failed");
8633 imagemagick_error (image_wand);
8634 goto imagemagick_error;
8638 /* crop behaves similar to image slicing in Emacs but is more memory
8639 efficient. */
8640 crop = image_spec_value (img->spec, QCcrop, NULL);
8642 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8644 /* After some testing, it seems MagickCropImage is the fastest crop
8645 function in ImageMagick. This crop function seems to do less copying
8646 than the alternatives, but it still reads the entire image into memory
8647 before cropping, which is apparently difficult to avoid when using
8648 imagemagick. */
8649 size_t crop_width = XINT (XCAR (crop));
8650 crop = XCDR (crop);
8651 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8653 size_t crop_height = XINT (XCAR (crop));
8654 crop = XCDR (crop);
8655 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8657 ssize_t crop_x = XINT (XCAR (crop));
8658 crop = XCDR (crop);
8659 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8661 ssize_t crop_y = XINT (XCAR (crop));
8662 MagickCropImage (image_wand, crop_width, crop_height,
8663 crop_x, crop_y);
8669 /* Furthermore :rotation. we need background color and angle for
8670 rotation. */
8672 TODO background handling for rotation specified_bg =
8673 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8674 (specified_bg). */
8675 value = image_spec_value (img->spec, QCrotation, NULL);
8676 if (FLOATP (value))
8678 rotation = extract_float (value);
8679 status = MagickRotateImage (image_wand, bg_wand, rotation);
8680 if (status == MagickFalse)
8682 image_error ("Imagemagick image rotate failed");
8683 imagemagick_error (image_wand);
8684 goto imagemagick_error;
8688 /* Set the canvas background color to the frame or specified
8689 background, and flatten the image. Note: as of ImageMagick
8690 6.6.0, SVG image transparency is not handled properly
8691 (e.g. etc/images/splash.svg shows a white background always). */
8693 MagickWand *new_wand;
8694 MagickSetImageBackgroundColor (image_wand, bg_wand);
8695 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8696 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8697 #else
8698 new_wand = MagickFlattenImages (image_wand);
8699 #endif
8700 DestroyMagickWand (image_wand);
8701 image_wand = new_wand;
8704 /* Finally we are done manipulating the image. Figure out the
8705 resulting width/height and transfer ownership to Emacs. */
8706 image_height = MagickGetImageHeight (image_wand);
8707 image_width = MagickGetImageWidth (image_wand);
8709 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8710 && check_image_size (f, image_width, image_height)))
8712 image_size_error ();
8713 goto imagemagick_error;
8716 width = image_width;
8717 height = image_height;
8719 /* We can now get a valid pixel buffer from the imagemagick file, if all
8720 went ok. */
8722 init_color_table ();
8724 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8725 if (imagemagick_render_type != 0)
8727 /* Magicexportimage is normally faster than pixelpushing. This
8728 method is also well tested. Some aspects of this method are
8729 ad-hoc and needs to be more researched. */
8730 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8731 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8732 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8733 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8734 &ximg, 0))
8736 #ifdef COLOR_TABLE_SUPPORT
8737 free_color_table ();
8738 #endif
8739 image_error ("Imagemagick X bitmap allocation failure");
8740 goto imagemagick_error;
8743 /* Oddly, the below code doesn't seem to work:*/
8744 /* switch(ximg->bitmap_unit){ */
8745 /* case 8: */
8746 /* pixelwidth=CharPixel; */
8747 /* break; */
8748 /* case 16: */
8749 /* pixelwidth=ShortPixel; */
8750 /* break; */
8751 /* case 32: */
8752 /* pixelwidth=LongPixel; */
8753 /* break; */
8754 /* } */
8756 Here im just guessing the format of the bitmap.
8757 happens to work fine for:
8758 - bw djvu images
8759 on rgb display.
8760 seems about 3 times as fast as pixel pushing(not carefully measured)
8762 int pixelwidth = CharPixel; /*??? TODO figure out*/
8763 MagickExportImagePixels (image_wand, 0, 0, width, height,
8764 exportdepth, pixelwidth, ximg->data);
8766 else
8767 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8769 size_t image_height;
8770 MagickRealType color_scale = 65535.0 / QuantumRange;
8772 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8773 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8774 &ximg, 0))
8776 #ifdef COLOR_TABLE_SUPPORT
8777 free_color_table ();
8778 #endif
8779 image_error ("Imagemagick X bitmap allocation failure");
8780 goto imagemagick_error;
8783 /* Copy imagemagick image to x with primitive yet robust pixel
8784 pusher loop. This has been tested a lot with many different
8785 images. */
8787 /* Copy pixels from the imagemagick image structure to the x image map. */
8788 iterator = NewPixelIterator (image_wand);
8789 if (! iterator)
8791 #ifdef COLOR_TABLE_SUPPORT
8792 free_color_table ();
8793 #endif
8794 x_destroy_x_image (ximg);
8795 image_error ("Imagemagick pixel iterator creation failed");
8796 goto imagemagick_error;
8799 image_height = MagickGetImageHeight (image_wand);
8800 for (y = 0; y < image_height; y++)
8802 size_t row_width;
8803 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8804 if (! pixels)
8805 break;
8806 int xlim = min (row_width, width);
8807 for (x = 0; x < xlim; x++)
8809 PixelGetMagickColor (pixels[x], &pixel);
8810 XPutPixel (ximg, x, y,
8811 lookup_rgb_color (f,
8812 color_scale * pixel.red,
8813 color_scale * pixel.green,
8814 color_scale * pixel.blue));
8817 DestroyPixelIterator (iterator);
8820 #ifdef COLOR_TABLE_SUPPORT
8821 /* Remember colors allocated for this image. */
8822 img->colors = colors_in_color_table (&img->ncolors);
8823 free_color_table ();
8824 #endif /* COLOR_TABLE_SUPPORT */
8826 img->width = width;
8827 img->height = height;
8829 /* Put ximg into the image. */
8830 image_put_x_image (f, img, ximg, 0);
8832 /* Final cleanup. image_wand should be the only resource left. */
8833 DestroyMagickWand (image_wand);
8834 if (bg_wand) DestroyPixelWand (bg_wand);
8836 /* `MagickWandTerminus' terminates the imagemagick environment. */
8837 MagickWandTerminus ();
8839 return 1;
8841 imagemagick_error:
8842 DestroyMagickWand (image_wand);
8843 if (bg_wand) DestroyPixelWand (bg_wand);
8845 MagickWandTerminus ();
8846 /* TODO more cleanup. */
8847 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec);
8848 return 0;
8852 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8853 successful. this function will go into the imagemagick_type structure, and
8854 the prototype thus needs to be compatible with that structure. */
8856 static bool
8857 imagemagick_load (struct frame *f, struct image *img)
8859 bool success_p = 0;
8860 Lisp_Object file_name;
8862 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8863 file_name = image_spec_value (img->spec, QCfile, NULL);
8864 if (STRINGP (file_name))
8866 Lisp_Object file = x_find_image_file (file_name);
8867 if (!STRINGP (file))
8869 image_error ("Cannot find image file `%s'", file_name);
8870 return 0;
8872 file = ENCODE_FILE (file);
8873 #ifdef WINDOWSNT
8874 file = ansi_encode_filename (file);
8875 #endif
8876 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8878 /* Else its not a file, its a lisp object. Load the image from a
8879 lisp object rather than a file. */
8880 else
8882 Lisp_Object data;
8884 data = image_spec_value (img->spec, QCdata, NULL);
8885 if (!STRINGP (data))
8887 image_error ("Invalid image data `%s'", data);
8888 return 0;
8890 success_p = imagemagick_load_image (f, img, SDATA (data),
8891 SBYTES (data), NULL);
8894 return success_p;
8897 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8898 doc: /* Return a list of image types supported by ImageMagick.
8899 Each entry in this list is a symbol named after an ImageMagick format
8900 tag. See the ImageMagick manual for a list of ImageMagick formats and
8901 their descriptions (http://www.imagemagick.org/script/formats.php).
8902 You can also try the shell command: `identify -list format'.
8904 Note that ImageMagick recognizes many file-types that Emacs does not
8905 recognize as images, such as C. See `imagemagick-types-enable'
8906 and `imagemagick-types-inhibit'. */)
8907 (void)
8909 Lisp_Object typelist = Qnil;
8910 size_t numf = 0;
8911 ExceptionInfo *ex;
8912 char **imtypes;
8913 size_t i;
8915 ex = AcquireExceptionInfo ();
8916 imtypes = GetMagickList ("*", &numf, ex);
8917 DestroyExceptionInfo (ex);
8919 for (i = 0; i < numf; i++)
8921 Lisp_Object imagemagicktype = intern (imtypes[i]);
8922 typelist = Fcons (imagemagicktype, typelist);
8923 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8926 MagickRelinquishMemory (imtypes);
8927 return Fnreverse (typelist);
8930 #endif /* defined (HAVE_IMAGEMAGICK) */
8934 /***********************************************************************
8936 ***********************************************************************/
8938 #ifdef HAVE_RSVG
8940 /* Function prototypes. */
8942 static bool svg_image_p (Lisp_Object object);
8943 static bool svg_load (struct frame *f, struct image *img);
8945 static bool svg_load_image (struct frame *, struct image *,
8946 char *, ptrdiff_t, char *);
8948 /* Indices of image specification fields in svg_format, below. */
8950 enum svg_keyword_index
8952 SVG_TYPE,
8953 SVG_DATA,
8954 SVG_FILE,
8955 SVG_ASCENT,
8956 SVG_MARGIN,
8957 SVG_RELIEF,
8958 SVG_ALGORITHM,
8959 SVG_HEURISTIC_MASK,
8960 SVG_MASK,
8961 SVG_BACKGROUND,
8962 SVG_LAST
8965 /* Vector of image_keyword structures describing the format
8966 of valid user-defined image specifications. */
8968 static const struct image_keyword svg_format[SVG_LAST] =
8970 {":type", IMAGE_SYMBOL_VALUE, 1},
8971 {":data", IMAGE_STRING_VALUE, 0},
8972 {":file", IMAGE_STRING_VALUE, 0},
8973 {":ascent", IMAGE_ASCENT_VALUE, 0},
8974 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8975 {":relief", IMAGE_INTEGER_VALUE, 0},
8976 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8977 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8978 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8979 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8982 # if defined HAVE_NTGUI && defined WINDOWSNT
8983 static bool init_svg_functions (void);
8984 # else
8985 #define init_svg_functions NULL
8986 # endif
8988 /* Structure describing the image type `svg'. Its the same type of
8989 structure defined for all image formats, handled by emacs image
8990 functions. See struct image_type in dispextern.h. */
8992 static struct image_type svg_type =
8994 SYMBOL_INDEX (Qsvg),
8995 svg_image_p,
8996 svg_load,
8997 x_clear_image,
8998 init_svg_functions,
8999 NULL
9003 /* Return true if OBJECT is a valid SVG image specification. Do
9004 this by calling parse_image_spec and supplying the keywords that
9005 identify the SVG format. */
9007 static bool
9008 svg_image_p (Lisp_Object object)
9010 struct image_keyword fmt[SVG_LAST];
9011 memcpy (fmt, svg_format, sizeof fmt);
9013 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
9014 return 0;
9016 /* Must specify either the :data or :file keyword. */
9017 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
9020 /* Some versions of glib's gatomic.h define MemoryBarrier, but MinGW
9021 w32api 3.18 and later has its own definition. The following gross
9022 hack avoids the clash. */
9023 # ifdef WINDOWSNT
9024 # if (__W32API_MAJOR_VERSION + (__W32API_MINOR_VERSION >= 18)) >= 4
9025 # define W32_SAVE_MINGW_VERSION __MINGW_MAJOR_VERSION
9026 # undef __MINGW_MAJOR_VERSION
9027 # define __MINGW_MAJOR_VERSION 4
9028 # endif
9029 # endif
9031 # include <librsvg/rsvg.h>
9033 # ifdef WINDOWSNT
9035 /* Restore the original definition of __MINGW_MAJOR_VERSION. */
9036 # ifdef W32_SAVE_MINGW_VERSION
9037 # undef __MINGW_MAJOR_VERSION
9038 # define __MINGW_MAJOR_VERSION W32_SAVE_MINGW_VERSION
9039 # ifdef __MINGW_MAJOR_VERSION
9040 # undef W32_SAVE_MINGW_VERSION
9041 # endif
9042 # endif
9044 /* SVG library functions. */
9045 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
9046 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
9047 (RsvgHandle *, RsvgDimensionData *));
9048 DEF_DLL_FN (gboolean, rsvg_handle_write,
9049 (RsvgHandle *, const guchar *, gsize, GError **));
9050 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
9051 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
9052 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
9054 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
9055 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
9056 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
9057 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
9058 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
9059 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
9060 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
9061 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
9063 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9064 DEF_DLL_FN (void, g_type_init, (void));
9065 # endif
9066 DEF_DLL_FN (void, g_object_unref, (gpointer));
9067 DEF_DLL_FN (void, g_clear_error, (GError **));
9069 static bool
9070 init_svg_functions (void)
9072 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
9074 if (!(glib = w32_delayed_load (Qglib))
9075 || !(gobject = w32_delayed_load (Qgobject))
9076 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
9077 || !(library = w32_delayed_load (Qsvg)))
9079 if (gdklib) FreeLibrary (gdklib);
9080 if (gobject) FreeLibrary (gobject);
9081 if (glib) FreeLibrary (glib);
9082 return 0;
9085 LOAD_DLL_FN (library, rsvg_handle_new);
9086 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
9087 LOAD_DLL_FN (library, rsvg_handle_write);
9088 LOAD_DLL_FN (library, rsvg_handle_close);
9089 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
9090 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
9092 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
9093 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
9094 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
9095 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
9096 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
9097 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
9098 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
9099 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
9101 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9102 LOAD_DLL_FN (gobject, g_type_init);
9103 # endif
9104 LOAD_DLL_FN (gobject, g_object_unref);
9105 LOAD_DLL_FN (glib, g_clear_error);
9107 return 1;
9110 /* The following aliases for library functions allow dynamic loading
9111 to be used on some platforms. */
9113 # undef gdk_pixbuf_get_bits_per_sample
9114 # undef gdk_pixbuf_get_colorspace
9115 # undef gdk_pixbuf_get_has_alpha
9116 # undef gdk_pixbuf_get_height
9117 # undef gdk_pixbuf_get_n_channels
9118 # undef gdk_pixbuf_get_pixels
9119 # undef gdk_pixbuf_get_rowstride
9120 # undef gdk_pixbuf_get_width
9121 # undef g_clear_error
9122 # undef g_object_unref
9123 # undef g_type_init
9124 # undef rsvg_handle_close
9125 # undef rsvg_handle_get_dimensions
9126 # undef rsvg_handle_get_pixbuf
9127 # undef rsvg_handle_new
9128 # undef rsvg_handle_set_base_uri
9129 # undef rsvg_handle_write
9131 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9132 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9133 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9134 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9135 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9136 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9137 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9138 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9139 # define g_clear_error fn_g_clear_error
9140 # define g_object_unref fn_g_object_unref
9141 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9142 # define g_type_init fn_g_type_init
9143 # endif
9144 # define rsvg_handle_close fn_rsvg_handle_close
9145 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9146 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9147 # define rsvg_handle_new fn_rsvg_handle_new
9148 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9149 # define rsvg_handle_write fn_rsvg_handle_write
9151 # endif /* !WINDOWSNT */
9153 /* Load SVG image IMG for use on frame F. Value is true if
9154 successful. */
9156 static bool
9157 svg_load (struct frame *f, struct image *img)
9159 bool success_p = 0;
9160 Lisp_Object file_name;
9162 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9163 file_name = image_spec_value (img->spec, QCfile, NULL);
9164 if (STRINGP (file_name))
9166 int fd;
9167 Lisp_Object file = x_find_image_fd (file_name, &fd);
9168 if (!STRINGP (file))
9170 image_error ("Cannot find image file `%s'", file_name);
9171 return 0;
9174 /* Read the entire file into memory. */
9175 ptrdiff_t size;
9176 char *contents = slurp_file (fd, &size);
9177 if (contents == NULL)
9179 image_error ("Error loading SVG image `%s'", file);
9180 return 0;
9182 /* If the file was slurped into memory properly, parse it. */
9183 success_p = svg_load_image (f, img, contents, size,
9184 SSDATA (ENCODE_FILE (file)));
9185 xfree (contents);
9187 /* Else its not a file, its a lisp object. Load the image from a
9188 lisp object rather than a file. */
9189 else
9191 Lisp_Object data, original_filename;
9193 data = image_spec_value (img->spec, QCdata, NULL);
9194 if (!STRINGP (data))
9196 image_error ("Invalid image data `%s'", data);
9197 return 0;
9199 original_filename = BVAR (current_buffer, filename);
9200 success_p = svg_load_image (f, img, SSDATA (data), SBYTES (data),
9201 (NILP (original_filename) ? NULL
9202 : SSDATA (original_filename)));
9205 return success_p;
9208 /* Load frame F and image IMG. CONTENTS contains the SVG XML data to
9209 be parsed, SIZE is its size, and FILENAME is the name of the SVG
9210 file being loaded.
9212 Use librsvg to do most of the image processing.
9214 Return true when successful. */
9215 static bool
9216 svg_load_image (struct frame *f, struct image *img, char *contents,
9217 ptrdiff_t size, char *filename)
9219 RsvgHandle *rsvg_handle;
9220 RsvgDimensionData dimension_data;
9221 GError *err = NULL;
9222 GdkPixbuf *pixbuf;
9223 int width;
9224 int height;
9225 const guint8 *pixels;
9226 int rowstride;
9228 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9229 /* g_type_init is a glib function that must be called prior to
9230 using gnome type library functions (obsolete since 2.36.0). */
9231 g_type_init ();
9232 #endif
9234 /* Make a handle to a new rsvg object. */
9235 rsvg_handle = rsvg_handle_new ();
9237 /* Set base_uri for properly handling referenced images (via 'href').
9238 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9239 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9240 if (filename)
9241 rsvg_handle_set_base_uri(rsvg_handle, filename);
9243 /* Parse the contents argument and fill in the rsvg_handle. */
9244 rsvg_handle_write (rsvg_handle, (unsigned char *) contents, size, &err);
9245 if (err) goto rsvg_error;
9247 /* The parsing is complete, rsvg_handle is ready to used, close it
9248 for further writes. */
9249 rsvg_handle_close (rsvg_handle, &err);
9250 if (err) goto rsvg_error;
9252 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
9253 if (! check_image_size (f, dimension_data.width, dimension_data.height))
9255 image_size_error ();
9256 goto rsvg_error;
9259 /* We can now get a valid pixel buffer from the svg file, if all
9260 went ok. */
9261 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
9262 if (!pixbuf) goto rsvg_error;
9263 g_object_unref (rsvg_handle);
9265 /* Extract some meta data from the svg handle. */
9266 width = gdk_pixbuf_get_width (pixbuf);
9267 height = gdk_pixbuf_get_height (pixbuf);
9268 pixels = gdk_pixbuf_get_pixels (pixbuf);
9269 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
9271 /* Validate the svg meta data. */
9272 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
9273 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
9274 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
9275 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
9278 #ifdef USE_CAIRO
9279 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
9280 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
9282 for (int y = 0; y < height; ++y)
9284 const guchar *iconptr = pixels + y * rowstride;
9285 uint32_t *dataptr = (uint32_t *) (data + y * rowstride);
9287 for (int x = 0; x < width; ++x)
9289 if (iconptr[3] == 0)
9290 *dataptr = bgcolor;
9291 else
9292 *dataptr = (iconptr[0] << 16)
9293 | (iconptr[1] << 8)
9294 | iconptr[2]
9295 | (iconptr[3] << 24);
9297 iconptr += 4;
9298 ++dataptr;
9302 create_cairo_image_surface (img, data, width, height);
9303 g_object_unref (pixbuf);
9304 #else
9305 /* Try to create a x pixmap to hold the svg pixmap. */
9306 XImagePtr ximg;
9307 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
9309 g_object_unref (pixbuf);
9310 return 0;
9313 init_color_table ();
9315 /* Handle alpha channel by combining the image with a background
9316 color. */
9317 XColor background;
9318 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
9319 if (!STRINGP (specified_bg)
9320 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
9321 x_query_frame_background_color (f, &background);
9323 /* SVG pixmaps specify transparency in the last byte, so right
9324 shift 8 bits to get rid of it, since emacs doesn't support
9325 transparency. */
9326 background.red >>= 8;
9327 background.green >>= 8;
9328 background.blue >>= 8;
9330 /* This loop handles opacity values, since Emacs assumes
9331 non-transparent images. Each pixel must be "flattened" by
9332 calculating the resulting color, given the transparency of the
9333 pixel, and the image background color. */
9334 for (int y = 0; y < height; ++y)
9336 for (int x = 0; x < width; ++x)
9338 int red = *pixels++;
9339 int green = *pixels++;
9340 int blue = *pixels++;
9341 int opacity = *pixels++;
9343 red = ((red * opacity)
9344 + (background.red * ((1 << 8) - opacity)));
9345 green = ((green * opacity)
9346 + (background.green * ((1 << 8) - opacity)));
9347 blue = ((blue * opacity)
9348 + (background.blue * ((1 << 8) - opacity)));
9350 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9353 pixels += rowstride - 4 * width;
9356 #ifdef COLOR_TABLE_SUPPORT
9357 /* Remember colors allocated for this image. */
9358 img->colors = colors_in_color_table (&img->ncolors);
9359 free_color_table ();
9360 #endif /* COLOR_TABLE_SUPPORT */
9362 g_object_unref (pixbuf);
9364 img->width = width;
9365 img->height = height;
9367 /* Maybe fill in the background field while we have ximg handy.
9368 Casting avoids a GCC warning. */
9369 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9371 /* Put ximg into the image. */
9372 image_put_x_image (f, img, ximg, 0);
9373 #endif /* ! USE_CAIRO */
9376 return 1;
9378 rsvg_error:
9379 g_object_unref (rsvg_handle);
9380 /* FIXME: Use error->message so the user knows what is the actual
9381 problem with the image. */
9382 image_error ("Error parsing SVG image `%s'", img->spec);
9383 g_clear_error (&err);
9384 return 0;
9387 #endif /* defined (HAVE_RSVG) */
9392 /***********************************************************************
9393 Ghostscript
9394 ***********************************************************************/
9396 #ifdef HAVE_X_WINDOWS
9397 #define HAVE_GHOSTSCRIPT 1
9398 #endif /* HAVE_X_WINDOWS */
9400 #ifdef HAVE_GHOSTSCRIPT
9402 static bool gs_image_p (Lisp_Object object);
9403 static bool gs_load (struct frame *f, struct image *img);
9404 static void gs_clear_image (struct frame *f, struct image *img);
9406 /* Indices of image specification fields in gs_format, below. */
9408 enum gs_keyword_index
9410 GS_TYPE,
9411 GS_PT_WIDTH,
9412 GS_PT_HEIGHT,
9413 GS_FILE,
9414 GS_LOADER,
9415 GS_BOUNDING_BOX,
9416 GS_ASCENT,
9417 GS_MARGIN,
9418 GS_RELIEF,
9419 GS_ALGORITHM,
9420 GS_HEURISTIC_MASK,
9421 GS_MASK,
9422 GS_BACKGROUND,
9423 GS_LAST
9426 /* Vector of image_keyword structures describing the format
9427 of valid user-defined image specifications. */
9429 static const struct image_keyword gs_format[GS_LAST] =
9431 {":type", IMAGE_SYMBOL_VALUE, 1},
9432 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9433 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9434 {":file", IMAGE_STRING_VALUE, 1},
9435 {":loader", IMAGE_FUNCTION_VALUE, 0},
9436 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9437 {":ascent", IMAGE_ASCENT_VALUE, 0},
9438 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9439 {":relief", IMAGE_INTEGER_VALUE, 0},
9440 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9441 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9442 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9443 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9446 /* Structure describing the image type `ghostscript'. */
9448 static struct image_type gs_type =
9450 SYMBOL_INDEX (Qpostscript),
9451 gs_image_p,
9452 gs_load,
9453 gs_clear_image,
9454 NULL,
9455 NULL
9459 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9461 static void
9462 gs_clear_image (struct frame *f, struct image *img)
9464 x_clear_image (f, img);
9468 /* Return true if OBJECT is a valid Ghostscript image
9469 specification. */
9471 static bool
9472 gs_image_p (Lisp_Object object)
9474 struct image_keyword fmt[GS_LAST];
9475 Lisp_Object tem;
9476 int i;
9478 memcpy (fmt, gs_format, sizeof fmt);
9480 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9481 return 0;
9483 /* Bounding box must be a list or vector containing 4 integers. */
9484 tem = fmt[GS_BOUNDING_BOX].value;
9485 if (CONSP (tem))
9487 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9488 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9489 return 0;
9490 if (!NILP (tem))
9491 return 0;
9493 else if (VECTORP (tem))
9495 if (ASIZE (tem) != 4)
9496 return 0;
9497 for (i = 0; i < 4; ++i)
9498 if (!INTEGERP (AREF (tem, i)))
9499 return 0;
9501 else
9502 return 0;
9504 return 1;
9508 /* Load Ghostscript image IMG for use on frame F. Value is true
9509 if successful. */
9511 static bool
9512 gs_load (struct frame *f, struct image *img)
9514 uprintmax_t printnum1, printnum2;
9515 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9516 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9517 Lisp_Object frame;
9518 double in_width, in_height;
9519 Lisp_Object pixel_colors = Qnil;
9521 /* Compute pixel size of pixmap needed from the given size in the
9522 image specification. Sizes in the specification are in pt. 1 pt
9523 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9524 info. */
9525 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9526 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9527 in_width *= FRAME_RES_X (f);
9528 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9529 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9530 in_height *= FRAME_RES_Y (f);
9532 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9533 && check_image_size (f, in_width, in_height)))
9535 image_size_error ();
9536 return 0;
9538 img->width = in_width;
9539 img->height = in_height;
9541 /* Create the pixmap. */
9542 eassert (img->pixmap == NO_PIXMAP);
9544 if (x_check_image_size (0, img->width, img->height))
9546 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9547 block_input ();
9548 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
9549 img->width, img->height,
9550 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9551 unblock_input ();
9554 if (!img->pixmap)
9556 image_error ("Unable to create pixmap for `%s'" , img->spec);
9557 return 0;
9560 /* Call the loader to fill the pixmap. It returns a process object
9561 if successful. We do not record_unwind_protect here because
9562 other places in redisplay like calling window scroll functions
9563 don't either. Let the Lisp loader use `unwind-protect' instead. */
9564 printnum1 = FRAME_X_DRAWABLE (f);
9565 printnum2 = img->pixmap;
9566 window_and_pixmap_id
9567 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9569 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9570 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9571 pixel_colors
9572 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9574 XSETFRAME (frame, f);
9575 loader = image_spec_value (img->spec, QCloader, NULL);
9576 if (NILP (loader))
9577 loader = intern ("gs-load-image");
9579 img->lisp_data = call6 (loader, frame, img->spec,
9580 make_number (img->width),
9581 make_number (img->height),
9582 window_and_pixmap_id,
9583 pixel_colors);
9584 return PROCESSP (img->lisp_data);
9588 /* Kill the Ghostscript process that was started to fill PIXMAP on
9589 frame F. Called from XTread_socket when receiving an event
9590 telling Emacs that Ghostscript has finished drawing. */
9592 void
9593 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9595 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9596 ptrdiff_t i;
9597 struct image *img;
9599 /* Find the image containing PIXMAP. */
9600 for (i = 0; i < c->used; ++i)
9601 if (c->images[i]->pixmap == pixmap)
9602 break;
9604 /* Should someone in between have cleared the image cache, for
9605 instance, give up. */
9606 if (i == c->used)
9607 return;
9609 /* Kill the GS process. We should have found PIXMAP in the image
9610 cache and its image should contain a process object. */
9611 img = c->images[i];
9612 eassert (PROCESSP (img->lisp_data));
9613 Fkill_process (img->lisp_data, Qnil);
9614 img->lisp_data = Qnil;
9616 #if defined (HAVE_X_WINDOWS)
9618 /* On displays with a mutable colormap, figure out the colors
9619 allocated for the image by looking at the pixels of an XImage for
9620 img->pixmap. */
9621 if (x_mutable_colormap (FRAME_X_VISUAL (f)))
9623 XImagePtr ximg;
9625 block_input ();
9627 /* Try to get an XImage for img->pixmep. */
9628 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9629 0, 0, img->width, img->height, ~0, ZPixmap);
9630 if (ximg)
9632 /* Initialize the color table. */
9633 init_color_table ();
9635 /* For each pixel of the image, look its color up in the
9636 color table. After having done so, the color table will
9637 contain an entry for each color used by the image. */
9638 #ifdef COLOR_TABLE_SUPPORT
9639 for (int y = 0; y < img->height; ++y)
9640 for (int x = 0; x < img->width; ++x)
9642 unsigned long pixel = XGetPixel (ximg, x, y);
9644 lookup_pixel_color (f, pixel);
9647 /* Record colors in the image. Free color table and XImage. */
9648 img->colors = colors_in_color_table (&img->ncolors);
9649 free_color_table ();
9650 #endif
9651 XDestroyImage (ximg);
9653 #if 0 /* This doesn't seem to be the case. If we free the colors
9654 here, we get a BadAccess later in x_clear_image when
9655 freeing the colors. */
9656 /* We have allocated colors once, but Ghostscript has also
9657 allocated colors on behalf of us. So, to get the
9658 reference counts right, free them once. */
9659 if (img->ncolors)
9660 x_free_colors (f, img->colors, img->ncolors);
9661 #endif
9663 else
9664 image_error ("Cannot get X image of `%s'; colors will not be freed",
9665 img->spec);
9667 unblock_input ();
9669 #endif /* HAVE_X_WINDOWS */
9671 /* Now that we have the pixmap, compute mask and transform the
9672 image if requested. */
9673 block_input ();
9674 postprocess_image (f, img);
9675 unblock_input ();
9678 #endif /* HAVE_GHOSTSCRIPT */
9681 /***********************************************************************
9682 Tests
9683 ***********************************************************************/
9685 #ifdef GLYPH_DEBUG
9687 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9688 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9689 (Lisp_Object spec)
9691 return valid_image_p (spec) ? Qt : Qnil;
9695 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0,
9696 doc: /* */)
9697 (Lisp_Object spec)
9699 ptrdiff_t id = -1;
9701 if (valid_image_p (spec))
9702 id = lookup_image (SELECTED_FRAME (), spec);
9704 debug_print (spec);
9705 return make_number (id);
9708 #endif /* GLYPH_DEBUG */
9711 /***********************************************************************
9712 Initialization
9713 ***********************************************************************/
9715 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9716 doc: /* Initialize image library implementing image type TYPE.
9717 Return non-nil if TYPE is a supported image type.
9719 If image libraries are loaded dynamically (currently only the case on
9720 MS-Windows), load the library for TYPE if it is not yet loaded, using
9721 the library file(s) specified by `dynamic-library-alist'. */)
9722 (Lisp_Object type)
9724 return lookup_image_type (type) ? Qt : Qnil;
9727 /* Look up image type TYPE, and return a pointer to its image_type
9728 structure. Return 0 if TYPE is not a known image type. */
9730 static struct image_type *
9731 lookup_image_type (Lisp_Object type)
9733 /* Types pbm and xbm are built-in and always available. */
9734 if (EQ (type, Qpbm))
9735 return define_image_type (&pbm_type);
9737 if (EQ (type, Qxbm))
9738 return define_image_type (&xbm_type);
9740 #if defined (HAVE_XPM) || defined (HAVE_NS)
9741 if (EQ (type, Qxpm))
9742 return define_image_type (&xpm_type);
9743 #endif
9745 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9746 if (EQ (type, Qjpeg))
9747 return define_image_type (&jpeg_type);
9748 #endif
9750 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9751 if (EQ (type, Qtiff))
9752 return define_image_type (&tiff_type);
9753 #endif
9755 #if defined (HAVE_GIF) || defined (HAVE_NS)
9756 if (EQ (type, Qgif))
9757 return define_image_type (&gif_type);
9758 #endif
9760 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9761 if (EQ (type, Qpng))
9762 return define_image_type (&png_type);
9763 #endif
9765 #if defined (HAVE_RSVG)
9766 if (EQ (type, Qsvg))
9767 return define_image_type (&svg_type);
9768 #endif
9770 #if defined (HAVE_IMAGEMAGICK)
9771 if (EQ (type, Qimagemagick))
9772 return define_image_type (&imagemagick_type);
9773 #endif
9775 #ifdef HAVE_GHOSTSCRIPT
9776 if (EQ (type, Qpostscript))
9777 return define_image_type (&gs_type);
9778 #endif
9780 return NULL;
9783 #if !defined CANNOT_DUMP && defined HAVE_WINDOW_SYSTEM
9785 /* Reset image_types before dumping.
9786 Called from Fdump_emacs. */
9788 void
9789 reset_image_types (void)
9791 while (image_types)
9793 struct image_type *next = image_types->next;
9794 xfree (image_types);
9795 image_types = next;
9798 #endif
9800 void
9801 syms_of_image (void)
9803 /* Initialize this only once; it will be reset before dumping. */
9804 image_types = NULL;
9806 /* Must be defined now because we're going to update it below, while
9807 defining the supported image types. */
9808 DEFVAR_LISP ("image-types", Vimage_types,
9809 doc: /* List of potentially supported image types.
9810 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9811 To check whether it is really supported, use `image-type-available-p'. */);
9812 Vimage_types = Qnil;
9814 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9815 doc: /* Maximum size of images.
9816 Emacs will not load an image into memory if its pixel width or
9817 pixel height exceeds this limit.
9819 If the value is an integer, it directly specifies the maximum
9820 image height and width, measured in pixels. If it is a floating
9821 point number, it specifies the maximum image height and width
9822 as a ratio to the frame height and width. If the value is
9823 non-numeric, there is no explicit limit on the size of images. */);
9824 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9826 /* Other symbols. */
9827 DEFSYM (Qcount, "count");
9828 DEFSYM (Qextension_data, "extension-data");
9829 DEFSYM (Qdelay, "delay");
9831 /* Keywords. */
9832 DEFSYM (QCascent, ":ascent");
9833 DEFSYM (QCmargin, ":margin");
9834 DEFSYM (QCrelief, ":relief");
9835 DEFSYM (QCconversion, ":conversion");
9836 DEFSYM (QCcolor_symbols, ":color-symbols");
9837 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9838 DEFSYM (QCindex, ":index");
9839 DEFSYM (QCcrop, ":crop");
9840 DEFSYM (QCrotation, ":rotation");
9841 DEFSYM (QCmatrix, ":matrix");
9842 DEFSYM (QCscale, ":scale");
9843 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9844 DEFSYM (QCmask, ":mask");
9846 /* Other symbols. */
9847 DEFSYM (Qlaplace, "laplace");
9848 DEFSYM (Qemboss, "emboss");
9849 DEFSYM (Qedge_detection, "edge-detection");
9850 DEFSYM (Qheuristic, "heuristic");
9852 DEFSYM (Qpostscript, "postscript");
9853 DEFSYM (QCmax_width, ":max-width");
9854 DEFSYM (QCmax_height, ":max-height");
9855 #ifdef HAVE_GHOSTSCRIPT
9856 ADD_IMAGE_TYPE (Qpostscript);
9857 DEFSYM (QCloader, ":loader");
9858 DEFSYM (QCpt_width, ":pt-width");
9859 DEFSYM (QCpt_height, ":pt-height");
9860 #endif /* HAVE_GHOSTSCRIPT */
9862 #ifdef HAVE_NTGUI
9863 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9864 or -1 if no PNG/GIF support was compiled in. This is tested by
9865 w32-win.el to correctly set up the alist used to search for the
9866 respective image libraries. */
9867 DEFSYM (Qlibpng_version, "libpng-version");
9868 Fset (Qlibpng_version,
9869 #if HAVE_PNG
9870 make_number (PNG_LIBPNG_VER)
9871 #else
9872 make_number (-1)
9873 #endif
9875 DEFSYM (Qlibgif_version, "libgif-version");
9876 Fset (Qlibgif_version,
9877 #ifdef HAVE_GIF
9878 make_number (GIFLIB_MAJOR * 10000
9879 + GIFLIB_MINOR * 100
9880 + GIFLIB_RELEASE)
9881 #else
9882 make_number (-1)
9883 #endif
9885 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9886 Fset (Qlibjpeg_version,
9887 #if HAVE_JPEG
9888 make_number (JPEG_LIB_VERSION)
9889 #else
9890 make_number (-1)
9891 #endif
9893 #endif
9895 DEFSYM (Qpbm, "pbm");
9896 ADD_IMAGE_TYPE (Qpbm);
9898 DEFSYM (Qxbm, "xbm");
9899 ADD_IMAGE_TYPE (Qxbm);
9901 #if defined (HAVE_XPM) || defined (HAVE_NS)
9902 DEFSYM (Qxpm, "xpm");
9903 ADD_IMAGE_TYPE (Qxpm);
9904 #endif
9906 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9907 DEFSYM (Qjpeg, "jpeg");
9908 ADD_IMAGE_TYPE (Qjpeg);
9909 #endif
9911 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9912 DEFSYM (Qtiff, "tiff");
9913 ADD_IMAGE_TYPE (Qtiff);
9914 #endif
9916 #if defined (HAVE_GIF) || defined (HAVE_NS)
9917 DEFSYM (Qgif, "gif");
9918 ADD_IMAGE_TYPE (Qgif);
9919 #endif
9921 #if defined (HAVE_PNG) || defined (HAVE_NS)
9922 DEFSYM (Qpng, "png");
9923 ADD_IMAGE_TYPE (Qpng);
9924 #endif
9926 #if defined (HAVE_IMAGEMAGICK)
9927 DEFSYM (Qimagemagick, "imagemagick");
9928 ADD_IMAGE_TYPE (Qimagemagick);
9929 #endif
9931 #if defined (HAVE_RSVG)
9932 DEFSYM (Qsvg, "svg");
9933 ADD_IMAGE_TYPE (Qsvg);
9934 #ifdef HAVE_NTGUI
9935 /* Other libraries used directly by svg code. */
9936 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9937 DEFSYM (Qglib, "glib");
9938 DEFSYM (Qgobject, "gobject");
9939 #endif /* HAVE_NTGUI */
9940 #endif /* HAVE_RSVG */
9942 defsubr (&Sinit_image_library);
9943 #ifdef HAVE_IMAGEMAGICK
9944 defsubr (&Simagemagick_types);
9945 #endif
9946 defsubr (&Sclear_image_cache);
9947 defsubr (&Simage_flush);
9948 defsubr (&Simage_size);
9949 defsubr (&Simage_mask_p);
9950 defsubr (&Simage_metadata);
9952 #ifdef GLYPH_DEBUG
9953 defsubr (&Simagep);
9954 defsubr (&Slookup_image);
9955 #endif
9957 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9958 doc: /* Non-nil means always draw a cross over disabled images.
9959 Disabled images are those having a `:conversion disabled' property.
9960 A cross is always drawn on black & white displays. */);
9961 cross_disabled_images = 0;
9963 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9964 doc: /* List of directories to search for window system bitmap files. */);
9965 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9967 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9968 doc: /* Maximum time after which images are removed from the cache.
9969 When an image has not been displayed this many seconds, Emacs
9970 automatically removes it from the image cache. If the cache contains
9971 a large number of images, the actual eviction time may be shorter.
9972 The value can also be nil, meaning the cache is never cleared.
9974 The function `clear-image-cache' disregards this variable. */);
9975 Vimage_cache_eviction_delay = make_number (300);
9976 #ifdef HAVE_IMAGEMAGICK
9977 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9978 doc: /* Integer indicating which ImageMagick rendering method to use.
9979 The options are:
9980 0 -- the default method (pixel pushing)
9981 1 -- a newer method ("MagickExportImagePixels") that may perform
9982 better (speed etc) in some cases, but has not been as thoroughly
9983 tested with Emacs as the default method. This method requires
9984 ImageMagick version 6.4.6 (approximately) or later.
9985 */);
9986 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9987 imagemagick_render_type = 0;
9988 #endif