Reference `tramp-theme' in GNU ELPA.
[emacs.git] / src / image.c
blobaf65fdec7dc766a0c3b58b931715390091cb9403
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
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>
33 #include <c-ctype.h>
35 #include "lisp.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "buffer.h"
39 #include "dispextern.h"
40 #include "blockinput.h"
41 #include "systime.h"
42 #include <epaths.h>
43 #include "coding.h"
44 #include "termhooks.h"
45 #include "font.h"
47 #ifdef HAVE_SYS_STAT_H
48 #include <sys/stat.h>
49 #endif /* HAVE_SYS_STAT_H */
51 #ifdef HAVE_SYS_TYPES_H
52 #include <sys/types.h>
53 #endif /* HAVE_SYS_TYPES_H */
55 #ifdef HAVE_WINDOW_SYSTEM
56 #include TERM_HEADER
57 #endif /* HAVE_WINDOW_SYSTEM */
59 #ifdef HAVE_X_WINDOWS
60 typedef struct x_bitmap_record Bitmap_Record;
61 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
62 #define NO_PIXMAP None
64 #define PIX_MASK_RETAIN 0
65 #define PIX_MASK_DRAW 1
66 #endif /* HAVE_X_WINDOWS */
68 #ifdef HAVE_NTGUI
70 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
71 #ifdef WINDOWSNT
72 # include "w32.h"
73 #endif
75 typedef struct w32_bitmap_record Bitmap_Record;
76 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
77 #define NO_PIXMAP 0
79 #define PIX_MASK_RETAIN 0
80 #define PIX_MASK_DRAW 1
82 #define x_defined_color w32_defined_color
83 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
85 #endif /* HAVE_NTGUI */
87 #ifdef HAVE_NS
88 typedef struct ns_bitmap_record Bitmap_Record;
90 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
91 #define NO_PIXMAP 0
93 #define PIX_MASK_RETAIN 0
94 #define PIX_MASK_DRAW 1
96 #define x_defined_color(f, name, color_def, alloc) \
97 ns_defined_color (f, name, color_def, alloc, 0)
98 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
99 #endif /* HAVE_NS */
101 #if (defined HAVE_X_WINDOWS \
102 && ! (defined HAVE_NTGUI || defined USE_CAIRO || defined HAVE_NS))
103 /* W32_TODO : Color tables on W32. */
104 # define COLOR_TABLE_SUPPORT 1
105 #endif
107 static void x_disable_image (struct frame *, struct image *);
108 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
109 Lisp_Object);
111 static void init_color_table (void);
112 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
113 #ifdef COLOR_TABLE_SUPPORT
114 static void free_color_table (void);
115 static unsigned long *colors_in_color_table (int *n);
116 #endif
118 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
119 id, which is just an int that this section returns. Bitmaps are
120 reference counted so they can be shared among frames.
122 Bitmap indices are guaranteed to be > 0, so a negative number can
123 be used to indicate no bitmap.
125 If you use x_create_bitmap_from_data, then you must keep track of
126 the bitmaps yourself. That is, creating a bitmap from the same
127 data more than once will not be caught. */
129 #ifdef HAVE_NS
130 /* Use with images created by ns_image_for_XPM. */
131 static unsigned long
132 XGetPixel (XImagePtr ximage, int x, int y)
134 return ns_get_pixel (ximage, x, y);
137 /* Use with images created by ns_image_for_XPM; alpha set to 1;
138 pixel is assumed to be in RGB form. */
139 static void
140 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
142 ns_put_pixel (ximage, x, y, pixel);
144 #endif /* HAVE_NS */
147 /* Functions to access the contents of a bitmap, given an id. */
149 #ifdef HAVE_X_WINDOWS
150 static int
151 x_bitmap_height (struct frame *f, ptrdiff_t id)
153 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
156 static int
157 x_bitmap_width (struct frame *f, ptrdiff_t id)
159 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
161 #endif
163 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
164 ptrdiff_t
165 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
167 /* HAVE_NTGUI needs the explicit cast here. */
168 return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
170 #endif
172 #ifdef HAVE_X_WINDOWS
174 x_bitmap_mask (struct frame *f, ptrdiff_t id)
176 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
178 #endif
180 /* Allocate a new bitmap record. Returns index of new record. */
182 static ptrdiff_t
183 x_allocate_bitmap_record (struct frame *f)
185 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
186 ptrdiff_t i;
188 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
189 return ++dpyinfo->bitmaps_last;
191 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
192 if (dpyinfo->bitmaps[i].refcount == 0)
193 return i + 1;
195 dpyinfo->bitmaps =
196 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
197 10, -1, sizeof *dpyinfo->bitmaps);
198 return ++dpyinfo->bitmaps_last;
201 /* Add one reference to the reference count of the bitmap with id ID. */
203 void
204 x_reference_bitmap (struct frame *f, ptrdiff_t id)
206 ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
209 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
211 ptrdiff_t
212 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
214 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
215 ptrdiff_t id;
217 #ifdef HAVE_X_WINDOWS
218 Pixmap bitmap;
219 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
220 bits, width, height);
221 if (! bitmap)
222 return -1;
223 #endif /* HAVE_X_WINDOWS */
225 #ifdef HAVE_NTGUI
226 Pixmap bitmap;
227 bitmap = CreateBitmap (width, height,
228 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
229 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
230 bits);
231 if (! bitmap)
232 return -1;
233 #endif /* HAVE_NTGUI */
235 #ifdef HAVE_NS
236 void *bitmap = ns_image_from_XBM (bits, width, height, 0, 0);
237 if (!bitmap)
238 return -1;
239 #endif
241 id = x_allocate_bitmap_record (f);
243 #ifdef HAVE_NS
244 dpyinfo->bitmaps[id - 1].img = bitmap;
245 dpyinfo->bitmaps[id - 1].depth = 1;
246 #endif
248 dpyinfo->bitmaps[id - 1].file = NULL;
249 dpyinfo->bitmaps[id - 1].height = height;
250 dpyinfo->bitmaps[id - 1].width = width;
251 dpyinfo->bitmaps[id - 1].refcount = 1;
253 #ifdef HAVE_X_WINDOWS
254 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
255 dpyinfo->bitmaps[id - 1].have_mask = false;
256 dpyinfo->bitmaps[id - 1].depth = 1;
257 #endif /* HAVE_X_WINDOWS */
259 #ifdef HAVE_NTGUI
260 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
261 dpyinfo->bitmaps[id - 1].hinst = NULL;
262 dpyinfo->bitmaps[id - 1].depth = 1;
263 #endif /* HAVE_NTGUI */
265 return id;
268 /* Create bitmap from file FILE for frame F. */
270 ptrdiff_t
271 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
273 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
275 #ifdef HAVE_NTGUI
276 return -1; /* W32_TODO : bitmap support */
277 #endif /* HAVE_NTGUI */
279 #ifdef HAVE_NS
280 ptrdiff_t id;
281 void *bitmap = ns_image_from_file (file);
283 if (!bitmap)
284 return -1;
287 id = x_allocate_bitmap_record (f);
288 dpyinfo->bitmaps[id - 1].img = bitmap;
289 dpyinfo->bitmaps[id - 1].refcount = 1;
290 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
291 dpyinfo->bitmaps[id - 1].depth = 1;
292 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
293 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
294 return id;
295 #endif
297 #ifdef HAVE_X_WINDOWS
298 unsigned int width, height;
299 Pixmap bitmap;
300 int xhot, yhot, result;
301 ptrdiff_t id;
302 Lisp_Object found;
303 char *filename;
305 /* Look for an existing bitmap with the same name. */
306 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
308 if (dpyinfo->bitmaps[id].refcount
309 && dpyinfo->bitmaps[id].file
310 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
312 ++dpyinfo->bitmaps[id].refcount;
313 return id + 1;
317 /* Search bitmap-file-path for the file, if appropriate. */
318 if (openp (Vx_bitmap_file_path, file, Qnil, &found,
319 make_number (R_OK), false)
320 < 0)
321 return -1;
323 filename = SSDATA (found);
325 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
326 filename, &width, &height, &bitmap, &xhot, &yhot);
327 if (result != BitmapSuccess)
328 return -1;
330 id = x_allocate_bitmap_record (f);
331 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
332 dpyinfo->bitmaps[id - 1].have_mask = false;
333 dpyinfo->bitmaps[id - 1].refcount = 1;
334 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
335 dpyinfo->bitmaps[id - 1].depth = 1;
336 dpyinfo->bitmaps[id - 1].height = height;
337 dpyinfo->bitmaps[id - 1].width = width;
339 return id;
340 #endif /* HAVE_X_WINDOWS */
343 /* Free bitmap B. */
345 static void
346 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
348 #ifdef HAVE_X_WINDOWS
349 XFreePixmap (dpyinfo->display, bm->pixmap);
350 if (bm->have_mask)
351 XFreePixmap (dpyinfo->display, bm->mask);
352 #endif /* HAVE_X_WINDOWS */
354 #ifdef HAVE_NTGUI
355 DeleteObject (bm->pixmap);
356 #endif /* HAVE_NTGUI */
358 #ifdef HAVE_NS
359 ns_release_object (bm->img);
360 #endif
362 if (bm->file)
364 xfree (bm->file);
365 bm->file = NULL;
369 /* Remove reference to bitmap with id number ID. */
371 void
372 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
374 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
376 if (id > 0)
378 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
380 if (--bm->refcount == 0)
382 block_input ();
383 free_bitmap_record (dpyinfo, bm);
384 unblock_input ();
389 /* Free all the bitmaps for the display specified by DPYINFO. */
391 void
392 x_destroy_all_bitmaps (Display_Info *dpyinfo)
394 ptrdiff_t i;
395 Bitmap_Record *bm = dpyinfo->bitmaps;
397 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
398 if (bm->refcount > 0)
399 free_bitmap_record (dpyinfo, bm);
401 dpyinfo->bitmaps_last = 0;
404 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
405 XImagePtr *, Pixmap *);
406 static void x_destroy_x_image (XImagePtr ximg);
408 #ifdef HAVE_NTGUI
409 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
410 bool, HGDIOBJ *);
411 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
412 HGDIOBJ);
413 #else
414 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
415 static void image_unget_x_image (struct image *, bool, XImagePtr);
416 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
417 image_get_x_image (f, img, mask_p)
418 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
419 image_unget_x_image (img, mask_p, ximg)
420 #endif
422 #ifdef HAVE_X_WINDOWS
424 static void image_sync_to_pixmaps (struct frame *, struct image *);
426 /* Useful functions defined in the section
427 `Image type independent image structures' below. */
429 static unsigned long four_corners_best (XImagePtr ximg,
430 int *corners,
431 unsigned long width,
432 unsigned long height);
435 /* Create a mask of a bitmap. Note is this not a perfect mask.
436 It's nicer with some borders in this context */
438 void
439 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
441 Pixmap pixmap, mask;
442 XImagePtr ximg, mask_img;
443 unsigned long width, height;
444 bool result;
445 unsigned long bg;
446 unsigned long x, y, xp, xm, yp, ym;
447 GC gc;
449 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
451 if (!(id > 0))
452 return;
454 pixmap = x_bitmap_pixmap (f, id);
455 width = x_bitmap_width (f, id);
456 height = x_bitmap_height (f, id);
458 block_input ();
459 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
460 ~0, ZPixmap);
462 if (!ximg)
464 unblock_input ();
465 return;
468 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
470 unblock_input ();
471 if (!result)
473 XDestroyImage (ximg);
474 return;
477 bg = four_corners_best (ximg, NULL, width, height);
479 for (y = 0; y < ximg->height; ++y)
481 for (x = 0; x < ximg->width; ++x)
483 xp = x != ximg->width - 1 ? x + 1 : 0;
484 xm = x != 0 ? x - 1 : ximg->width - 1;
485 yp = y != ximg->height - 1 ? y + 1 : 0;
486 ym = y != 0 ? y - 1 : ximg->height - 1;
487 if (XGetPixel (ximg, x, y) == bg
488 && XGetPixel (ximg, x, yp) == bg
489 && XGetPixel (ximg, x, ym) == bg
490 && XGetPixel (ximg, xp, y) == bg
491 && XGetPixel (ximg, xp, yp) == bg
492 && XGetPixel (ximg, xp, ym) == bg
493 && XGetPixel (ximg, xm, y) == bg
494 && XGetPixel (ximg, xm, yp) == bg
495 && XGetPixel (ximg, xm, ym) == bg)
496 XPutPixel (mask_img, x, y, 0);
497 else
498 XPutPixel (mask_img, x, y, 1);
502 eassert (input_blocked_p ());
503 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
504 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
505 width, height);
506 XFreeGC (FRAME_X_DISPLAY (f), gc);
508 dpyinfo->bitmaps[id - 1].have_mask = true;
509 dpyinfo->bitmaps[id - 1].mask = mask;
511 XDestroyImage (ximg);
512 x_destroy_x_image (mask_img);
515 #endif /* HAVE_X_WINDOWS */
517 /***********************************************************************
518 Image types
519 ***********************************************************************/
521 /* List of supported image types. Use define_image_type to add new
522 types. Use lookup_image_type to find a type for a given symbol. */
524 static struct image_type *image_types;
526 /* Forward function prototypes. */
528 static struct image_type *lookup_image_type (Lisp_Object);
529 static void x_laplace (struct frame *, struct image *);
530 static void x_emboss (struct frame *, struct image *);
531 static void x_build_heuristic_mask (struct frame *, struct image *,
532 Lisp_Object);
533 #ifdef WINDOWSNT
534 #define CACHE_IMAGE_TYPE(type, status) \
535 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
536 #else
537 #define CACHE_IMAGE_TYPE(type, status)
538 #endif
540 #define ADD_IMAGE_TYPE(type) \
541 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
543 /* Define a new image type from TYPE. This adds a copy of TYPE to
544 image_types and caches the loading status of TYPE. */
546 static struct image_type *
547 define_image_type (struct image_type *type)
549 struct image_type *p = NULL;
550 int new_type = type->type;
551 bool type_valid = true;
553 block_input ();
555 for (p = image_types; p; p = p->next)
556 if (p->type == new_type)
557 goto done;
559 if (type->init)
561 #if defined HAVE_NTGUI && defined WINDOWSNT
562 /* If we failed to load the library before, don't try again. */
563 Lisp_Object tested = Fassq (builtin_lisp_symbol (new_type),
564 Vlibrary_cache);
565 if (CONSP (tested) && NILP (XCDR (tested)))
566 type_valid = false;
567 else
568 #endif
570 type_valid = type->init ();
571 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type),
572 type_valid ? Qt : Qnil);
576 if (type_valid)
578 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
579 The initialized data segment is read-only. */
580 p = xmalloc (sizeof *p);
581 *p = *type;
582 p->next = image_types;
583 image_types = p;
586 done:
587 unblock_input ();
588 return p;
592 /* Value is true if OBJECT is a valid Lisp image specification. A
593 valid image specification is a list whose car is the symbol
594 `image', and whose rest is a property list. The property list must
595 contain a value for key `:type'. That value must be the name of a
596 supported image type. The rest of the property list depends on the
597 image type. */
599 bool
600 valid_image_p (Lisp_Object object)
602 bool valid_p = 0;
604 if (IMAGEP (object))
606 Lisp_Object tem;
608 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
609 if (EQ (XCAR (tem), QCtype))
611 tem = XCDR (tem);
612 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
614 struct image_type *type;
615 type = lookup_image_type (XCAR (tem));
616 if (type)
617 valid_p = type->valid_p (object);
620 break;
624 return valid_p;
628 /* Log error message with format string FORMAT and trailing arguments.
629 Signaling an error, e.g. when an image cannot be loaded, is not a
630 good idea because this would interrupt redisplay, and the error
631 message display would lead to another redisplay. This function
632 therefore simply displays a message. */
634 static void
635 image_error (const char *format, ...)
637 va_list ap;
638 va_start (ap, format);
639 vadd_to_log (format, ap);
640 va_end (ap);
643 static void
644 image_size_error (void)
646 image_error ("Invalid image size (see `max-image-size')");
650 /***********************************************************************
651 Image specifications
652 ***********************************************************************/
654 enum image_value_type
656 IMAGE_DONT_CHECK_VALUE_TYPE,
657 IMAGE_STRING_VALUE,
658 IMAGE_STRING_OR_NIL_VALUE,
659 IMAGE_SYMBOL_VALUE,
660 IMAGE_POSITIVE_INTEGER_VALUE,
661 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
662 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
663 IMAGE_ASCENT_VALUE,
664 IMAGE_INTEGER_VALUE,
665 IMAGE_FUNCTION_VALUE,
666 IMAGE_NUMBER_VALUE,
667 IMAGE_BOOL_VALUE
670 /* Structure used when parsing image specifications. */
672 struct image_keyword
674 /* Name of keyword. */
675 const char *name;
677 /* The type of value allowed. */
678 enum image_value_type type;
680 /* True means key must be present. */
681 bool mandatory_p;
683 /* Used to recognize duplicate keywords in a property list. */
684 int count;
686 /* The value that was found. */
687 Lisp_Object value;
691 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
692 has the format (image KEYWORD VALUE ...). One of the keyword/
693 value pairs must be `:type TYPE'. KEYWORDS is a vector of
694 image_keywords structures of size NKEYWORDS describing other
695 allowed keyword/value pairs. Value is true if SPEC is valid. */
697 static bool
698 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
699 int nkeywords, Lisp_Object type)
701 int i;
702 Lisp_Object plist;
704 if (!IMAGEP (spec))
705 return 0;
707 plist = XCDR (spec);
708 while (CONSP (plist))
710 Lisp_Object key, value;
712 /* First element of a pair must be a symbol. */
713 key = XCAR (plist);
714 plist = XCDR (plist);
715 if (!SYMBOLP (key))
716 return 0;
718 /* There must follow a value. */
719 if (!CONSP (plist))
720 return 0;
721 value = XCAR (plist);
722 plist = XCDR (plist);
724 /* Find key in KEYWORDS. Error if not found. */
725 for (i = 0; i < nkeywords; ++i)
726 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
727 break;
729 if (i == nkeywords)
730 continue;
732 /* Record that we recognized the keyword. If a keywords
733 was found more than once, it's an error. */
734 keywords[i].value = value;
735 if (keywords[i].count > 1)
736 return 0;
737 ++keywords[i].count;
739 /* Check type of value against allowed type. */
740 switch (keywords[i].type)
742 case IMAGE_STRING_VALUE:
743 if (!STRINGP (value))
744 return 0;
745 break;
747 case IMAGE_STRING_OR_NIL_VALUE:
748 if (!STRINGP (value) && !NILP (value))
749 return 0;
750 break;
752 case IMAGE_SYMBOL_VALUE:
753 if (!SYMBOLP (value))
754 return 0;
755 break;
757 case IMAGE_POSITIVE_INTEGER_VALUE:
758 if (! RANGED_INTEGERP (1, value, INT_MAX))
759 return 0;
760 break;
762 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
763 if (RANGED_INTEGERP (0, value, INT_MAX))
764 break;
765 if (CONSP (value)
766 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
767 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
768 break;
769 return 0;
771 case IMAGE_ASCENT_VALUE:
772 if (SYMBOLP (value) && EQ (value, Qcenter))
773 break;
774 else if (RANGED_INTEGERP (0, value, 100))
775 break;
776 return 0;
778 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
779 /* Unlike the other integer-related cases, this one does not
780 verify that VALUE fits in 'int'. This is because callers
781 want EMACS_INT. */
782 if (!INTEGERP (value) || XINT (value) < 0)
783 return 0;
784 break;
786 case IMAGE_DONT_CHECK_VALUE_TYPE:
787 break;
789 case IMAGE_FUNCTION_VALUE:
790 value = indirect_function (value);
791 if (!NILP (Ffunctionp (value)))
792 break;
793 return 0;
795 case IMAGE_NUMBER_VALUE:
796 if (! NUMBERP (value))
797 return 0;
798 break;
800 case IMAGE_INTEGER_VALUE:
801 if (! TYPE_RANGED_INTEGERP (int, value))
802 return 0;
803 break;
805 case IMAGE_BOOL_VALUE:
806 if (!NILP (value) && !EQ (value, Qt))
807 return 0;
808 break;
810 default:
811 emacs_abort ();
812 break;
815 if (EQ (key, QCtype) && !EQ (type, value))
816 return 0;
819 /* Check that all mandatory fields are present. */
820 for (i = 0; i < nkeywords; ++i)
821 if (keywords[i].mandatory_p && keywords[i].count == 0)
822 return 0;
824 return NILP (plist);
828 /* Return the value of KEY in image specification SPEC. Value is nil
829 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
830 was found in SPEC. */
832 static Lisp_Object
833 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
835 Lisp_Object tail;
837 eassert (valid_image_p (spec));
839 for (tail = XCDR (spec);
840 CONSP (tail) && CONSP (XCDR (tail));
841 tail = XCDR (XCDR (tail)))
843 if (EQ (XCAR (tail), key))
845 if (found)
846 *found = 1;
847 return XCAR (XCDR (tail));
851 if (found)
852 *found = 0;
853 return Qnil;
857 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
858 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
859 PIXELS non-nil means return the size in pixels, otherwise return the
860 size in canonical character units.
861 FRAME is the frame on which the image will be displayed. FRAME nil
862 or omitted means use the selected frame. */)
863 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
865 Lisp_Object size;
867 size = Qnil;
868 if (valid_image_p (spec))
870 struct frame *f = decode_window_system_frame (frame);
871 ptrdiff_t id = lookup_image (f, spec);
872 struct image *img = IMAGE_FROM_ID (f, id);
873 int width = img->width + 2 * img->hmargin;
874 int height = img->height + 2 * img->vmargin;
876 if (NILP (pixels))
877 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
878 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
879 else
880 size = Fcons (make_number (width), make_number (height));
882 else
883 error ("Invalid image specification");
885 return size;
889 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
890 doc: /* Return t if image SPEC has a mask bitmap.
891 FRAME is the frame on which the image will be displayed. FRAME nil
892 or omitted means use the selected frame. */)
893 (Lisp_Object spec, Lisp_Object frame)
895 Lisp_Object mask;
897 mask = Qnil;
898 if (valid_image_p (spec))
900 struct frame *f = decode_window_system_frame (frame);
901 ptrdiff_t id = lookup_image (f, spec);
902 struct image *img = IMAGE_FROM_ID (f, id);
903 if (img->mask)
904 mask = Qt;
906 else
907 error ("Invalid image specification");
909 return mask;
912 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
913 doc: /* Return metadata for image SPEC.
914 FRAME is the frame on which the image will be displayed. FRAME nil
915 or omitted means use the selected frame. */)
916 (Lisp_Object spec, Lisp_Object frame)
918 Lisp_Object ext;
920 ext = Qnil;
921 if (valid_image_p (spec))
923 struct frame *f = decode_window_system_frame (frame);
924 ptrdiff_t id = lookup_image (f, spec);
925 struct image *img = IMAGE_FROM_ID (f, id);
926 ext = img->lisp_data;
929 return ext;
933 /***********************************************************************
934 Image type independent image structures
935 ***********************************************************************/
937 #define MAX_IMAGE_SIZE 10.0
938 /* Allocate and return a new image structure for image specification
939 SPEC. SPEC has a hash value of HASH. */
941 static struct image *
942 make_image (Lisp_Object spec, EMACS_UINT hash)
944 struct image *img = xzalloc (sizeof *img);
945 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
947 eassert (valid_image_p (spec));
948 img->dependencies = NILP (file) ? Qnil : list1 (file);
949 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
950 eassert (img->type != NULL);
951 img->spec = spec;
952 img->lisp_data = Qnil;
953 img->ascent = DEFAULT_IMAGE_ASCENT;
954 img->hash = hash;
955 img->corners[BOT_CORNER] = -1; /* Full image */
956 return img;
960 /* Free image IMG which was used on frame F, including its resources. */
962 static void
963 free_image (struct frame *f, struct image *img)
965 if (img)
967 struct image_cache *c = FRAME_IMAGE_CACHE (f);
969 /* Remove IMG from the hash table of its cache. */
970 if (img->prev)
971 img->prev->next = img->next;
972 else
973 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
975 if (img->next)
976 img->next->prev = img->prev;
978 c->images[img->id] = NULL;
980 /* Windows NT redefines 'free', but in this file, we need to
981 avoid the redefinition. */
982 #ifdef WINDOWSNT
983 #undef free
984 #endif
985 /* Free resources, then free IMG. */
986 img->type->free (f, img);
987 xfree (img);
991 /* Return true if the given widths and heights are valid for display. */
993 static bool
994 check_image_size (struct frame *f, int width, int height)
996 int w, h;
998 if (width <= 0 || height <= 0)
999 return 0;
1001 if (INTEGERP (Vmax_image_size))
1002 return (width <= XINT (Vmax_image_size)
1003 && height <= XINT (Vmax_image_size));
1004 else if (FLOATP (Vmax_image_size))
1006 if (f != NULL)
1008 w = FRAME_PIXEL_WIDTH (f);
1009 h = FRAME_PIXEL_HEIGHT (f);
1011 else
1012 w = h = 1024; /* Arbitrary size for unknown frame. */
1013 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1014 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1016 else
1017 return 1;
1020 /* Prepare image IMG for display on frame F. Must be called before
1021 drawing an image. */
1023 void
1024 prepare_image_for_display (struct frame *f, struct image *img)
1026 /* We're about to display IMG, so set its timestamp to `now'. */
1027 img->timestamp = current_timespec ();
1029 #ifndef USE_CAIRO
1030 /* If IMG doesn't have a pixmap yet, load it now, using the image
1031 type dependent loader function. */
1032 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1033 img->load_failed_p = ! img->type->load (f, img);
1035 #ifdef HAVE_X_WINDOWS
1036 if (!img->load_failed_p)
1038 block_input ();
1039 image_sync_to_pixmaps (f, img);
1040 unblock_input ();
1042 #endif
1043 #endif
1047 /* Value is the number of pixels for the ascent of image IMG when
1048 drawn in face FACE. */
1051 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1053 int height;
1054 int ascent;
1056 if (slice->height == img->height)
1057 height = img->height + img->vmargin;
1058 else if (slice->y == 0)
1059 height = slice->height + img->vmargin;
1060 else
1061 height = slice->height;
1063 if (img->ascent == CENTERED_IMAGE_ASCENT)
1065 if (face->font)
1067 #ifdef HAVE_NTGUI
1068 /* W32 specific version. Why?. ++kfs */
1069 ascent = height / 2 - (FONT_DESCENT (face->font)
1070 - FONT_BASE (face->font)) / 2;
1071 #else
1072 /* This expression is arranged so that if the image can't be
1073 exactly centered, it will be moved slightly up. This is
1074 because a typical font is `top-heavy' (due to the presence
1075 uppercase letters), so the image placement should err towards
1076 being top-heavy too. It also just generally looks better. */
1077 ascent = (height + FONT_BASE (face->font)
1078 - FONT_DESCENT (face->font) + 1) / 2;
1079 #endif /* HAVE_NTGUI */
1081 else
1082 ascent = height / 2;
1084 else
1085 ascent = height * (img->ascent / 100.0);
1087 return ascent;
1090 #ifdef USE_CAIRO
1091 static uint32_t
1092 xcolor_to_argb32 (XColor xc)
1094 return (0xff << 24) | ((xc.red / 256) << 16)
1095 | ((xc.green / 256) << 8) | (xc.blue / 256);
1098 static uint32_t
1099 get_spec_bg_or_alpha_as_argb (struct image *img,
1100 struct frame *f)
1102 uint32_t bgcolor = 0;
1103 XColor xbgcolor;
1104 Lisp_Object bg = image_spec_value (img->spec, QCbackground, NULL);
1106 if (STRINGP (bg) && x_parse_color (f, SSDATA (bg), &xbgcolor))
1107 bgcolor = xcolor_to_argb32 (xbgcolor);
1109 return bgcolor;
1112 static void
1113 create_cairo_image_surface (struct image *img,
1114 unsigned char *data,
1115 int width,
1116 int height)
1118 cairo_surface_t *surface;
1119 cairo_format_t format = CAIRO_FORMAT_ARGB32;
1120 int stride = cairo_format_stride_for_width (format, width);
1121 surface = cairo_image_surface_create_for_data (data,
1122 format,
1123 width,
1124 height,
1125 stride);
1126 img->width = width;
1127 img->height = height;
1128 img->cr_data = surface;
1129 img->cr_data2 = data;
1130 img->pixmap = 0;
1132 #endif
1136 /* Image background colors. */
1138 /* Find the "best" corner color of a bitmap.
1139 On W32, XIMG is assumed to a device context with the bitmap selected. */
1141 static RGB_PIXEL_COLOR
1142 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1143 unsigned long width, unsigned long height)
1145 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1146 int i, best_count;
1148 if (corners && corners[BOT_CORNER] >= 0)
1150 /* Get the colors at the corner_pixels of ximg. */
1151 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1152 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1153 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1154 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1156 else
1158 /* Get the colors at the corner_pixels of ximg. */
1159 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1160 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1161 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1162 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1164 /* Choose the most frequently found color as background. */
1165 for (i = best_count = 0; i < 4; ++i)
1167 int j, n;
1169 for (j = n = 0; j < 4; ++j)
1170 if (corner_pixels[i] == corner_pixels[j])
1171 ++n;
1173 if (n > best_count)
1174 best = corner_pixels[i], best_count = n;
1177 return best;
1180 /* Portability macros */
1182 #ifdef HAVE_NTGUI
1184 #define Free_Pixmap(display, pixmap) \
1185 DeleteObject (pixmap)
1187 #elif defined (HAVE_NS)
1189 #define Free_Pixmap(display, pixmap) \
1190 ns_release_object (pixmap)
1192 #else
1194 #define Free_Pixmap(display, pixmap) \
1195 XFreePixmap (display, pixmap)
1197 #endif /* !HAVE_NTGUI && !HAVE_NS */
1200 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1201 it is guessed heuristically. If non-zero, XIMG is an existing
1202 XImage object (or device context with the image selected on W32) to
1203 use for the heuristic. */
1205 RGB_PIXEL_COLOR
1206 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1208 if (! img->background_valid)
1209 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1211 bool free_ximg = !ximg;
1212 #ifdef HAVE_NTGUI
1213 HGDIOBJ prev;
1214 #endif /* HAVE_NTGUI */
1216 if (free_ximg)
1217 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1219 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1221 if (free_ximg)
1222 image_unget_x_image_or_dc (img, 0, ximg, prev);
1224 img->background_valid = 1;
1227 return img->background;
1230 /* Return the `background_transparent' field of IMG. If IMG doesn't
1231 have one yet, it is guessed heuristically. If non-zero, MASK is an
1232 existing XImage object to use for the heuristic. */
1235 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1237 if (! img->background_transparent_valid)
1238 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1240 if (img->mask)
1242 bool free_mask = !mask;
1243 #ifdef HAVE_NTGUI
1244 HGDIOBJ prev;
1245 #endif /* HAVE_NTGUI */
1247 if (free_mask)
1248 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1250 img->background_transparent
1251 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1253 if (free_mask)
1254 image_unget_x_image_or_dc (img, 1, mask, prev);
1256 else
1257 img->background_transparent = 0;
1259 img->background_transparent_valid = 1;
1262 return img->background_transparent;
1265 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1266 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1268 /* Store F's background color into *BGCOLOR. */
1269 static void
1270 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1272 #ifndef HAVE_NS
1273 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1274 x_query_color (f, bgcolor);
1275 #else
1276 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1277 #endif
1280 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1282 /***********************************************************************
1283 Helper functions for X image types
1284 ***********************************************************************/
1286 /* Clear X resources of image IMG on frame F according to FLAGS.
1287 FLAGS is bitwise-or of the following masks:
1288 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1289 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1290 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1291 any. */
1293 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1294 #define CLEAR_IMAGE_MASK (1 << 1)
1295 #define CLEAR_IMAGE_COLORS (1 << 2)
1297 static void
1298 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1300 if (flags & CLEAR_IMAGE_PIXMAP)
1302 if (img->pixmap)
1304 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1305 img->pixmap = NO_PIXMAP;
1306 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1307 img->background_valid = 0;
1309 #ifdef HAVE_X_WINDOWS
1310 if (img->ximg)
1312 x_destroy_x_image (img->ximg);
1313 img->ximg = NULL;
1314 img->background_valid = 0;
1316 #endif
1319 if (flags & CLEAR_IMAGE_MASK)
1321 if (img->mask)
1323 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1324 img->mask = NO_PIXMAP;
1325 img->background_transparent_valid = 0;
1327 #ifdef HAVE_X_WINDOWS
1328 if (img->mask_img)
1330 x_destroy_x_image (img->mask_img);
1331 img->mask_img = NULL;
1332 img->background_transparent_valid = 0;
1334 #endif
1337 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1339 /* W32_TODO: color table support. */
1340 #ifdef HAVE_X_WINDOWS
1341 x_free_colors (f, img->colors, img->ncolors);
1342 #endif /* HAVE_X_WINDOWS */
1343 xfree (img->colors);
1344 img->colors = NULL;
1345 img->ncolors = 0;
1350 /* Free X resources of image IMG which is used on frame F. */
1352 static void
1353 x_clear_image (struct frame *f, struct image *img)
1355 block_input ();
1356 #ifdef USE_CAIRO
1357 if (img->cr_data)
1358 cairo_surface_destroy ((cairo_surface_t *)img->cr_data);
1359 if (img->cr_data2) xfree (img->cr_data2);
1360 #endif
1361 x_clear_image_1 (f, img,
1362 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1363 unblock_input ();
1367 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1368 cannot be allocated, use DFLT. Add a newly allocated color to
1369 IMG->colors, so that it can be freed again. Value is the pixel
1370 color. */
1372 static unsigned long
1373 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1374 unsigned long dflt)
1376 XColor color;
1377 unsigned long result;
1379 eassert (STRINGP (color_name));
1381 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1382 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1383 INT_MAX))
1385 /* This isn't called frequently so we get away with simply
1386 reallocating the color vector to the needed size, here. */
1387 ptrdiff_t ncolors = img->ncolors + 1;
1388 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1389 img->colors[ncolors - 1] = color.pixel;
1390 img->ncolors = ncolors;
1391 result = color.pixel;
1393 else
1394 result = dflt;
1396 return result;
1401 /***********************************************************************
1402 Image Cache
1403 ***********************************************************************/
1405 static void cache_image (struct frame *f, struct image *img);
1407 /* Return a new, initialized image cache that is allocated from the
1408 heap. Call free_image_cache to free an image cache. */
1410 struct image_cache *
1411 make_image_cache (void)
1413 struct image_cache *c = xmalloc (sizeof *c);
1415 c->size = 50;
1416 c->used = c->refcount = 0;
1417 c->images = xmalloc (c->size * sizeof *c->images);
1418 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1419 return c;
1423 /* Find an image matching SPEC in the cache, and return it. If no
1424 image is found, return NULL. */
1425 static struct image *
1426 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1428 struct image *img;
1429 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1430 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1432 if (!c) return NULL;
1434 /* If the image spec does not specify a background color, the cached
1435 image must have the same background color as the current frame.
1436 The foreground color must also match, for the sake of monochrome
1437 images.
1439 In fact, we could ignore the foreground color matching condition
1440 for color images, or if the image spec specifies :foreground;
1441 similarly we could ignore the background color matching condition
1442 for formats that don't use transparency (such as jpeg), or if the
1443 image spec specifies :background. However, the extra memory
1444 usage is probably negligible in practice, so we don't bother. */
1446 for (img = c->buckets[i]; img; img = img->next)
1447 if (img->hash == hash
1448 && !NILP (Fequal (img->spec, spec))
1449 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1450 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1451 break;
1452 return img;
1456 /* Search frame F for an image with spec SPEC, and free it. */
1458 static void
1459 uncache_image (struct frame *f, Lisp_Object spec)
1461 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1462 if (img)
1464 free_image (f, img);
1465 /* As display glyphs may still be referring to the image ID, we
1466 must garbage the frame (Bug#6426). */
1467 SET_FRAME_GARBAGED (f);
1472 /* Free image cache of frame F. Be aware that X frames share images
1473 caches. */
1475 void
1476 free_image_cache (struct frame *f)
1478 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1479 if (c)
1481 ptrdiff_t i;
1483 /* Cache should not be referenced by any frame when freed. */
1484 eassert (c->refcount == 0);
1486 for (i = 0; i < c->used; ++i)
1487 free_image (f, c->images[i]);
1488 xfree (c->images);
1489 xfree (c->buckets);
1490 xfree (c);
1491 FRAME_IMAGE_CACHE (f) = NULL;
1496 /* Clear image cache of frame F. FILTER=t means free all images.
1497 FILTER=nil means clear only images that haven't been
1498 displayed for some time.
1499 Else, only free the images which have FILTER in their `dependencies'.
1500 Should be called from time to time to reduce the number of loaded images.
1501 If image-cache-eviction-delay is non-nil, this frees images in the cache
1502 which weren't displayed for at least that many seconds. */
1504 static void
1505 clear_image_cache (struct frame *f, Lisp_Object filter)
1507 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1509 if (c)
1511 ptrdiff_t i, nfreed = 0;
1513 /* Block input so that we won't be interrupted by a SIGIO
1514 while being in an inconsistent state. */
1515 block_input ();
1517 if (!NILP (filter))
1519 /* Filter image cache. */
1520 for (i = 0; i < c->used; ++i)
1522 struct image *img = c->images[i];
1523 if (img && (EQ (Qt, filter)
1524 || !NILP (Fmember (filter, img->dependencies))))
1526 free_image (f, img);
1527 ++nfreed;
1531 else if (INTEGERP (Vimage_cache_eviction_delay))
1533 /* Free cache based on timestamp. */
1534 struct timespec old, t;
1535 double delay;
1536 ptrdiff_t nimages = 0;
1538 for (i = 0; i < c->used; ++i)
1539 if (c->images[i])
1540 nimages++;
1542 /* If the number of cached images has grown unusually large,
1543 decrease the cache eviction delay (Bug#6230). */
1544 delay = XINT (Vimage_cache_eviction_delay);
1545 if (nimages > 40)
1546 delay = 1600 * delay / nimages / nimages;
1547 delay = max (delay, 1);
1549 t = current_timespec ();
1550 old = timespec_sub (t, dtotimespec (delay));
1552 for (i = 0; i < c->used; ++i)
1554 struct image *img = c->images[i];
1555 if (img && timespec_cmp (img->timestamp, old) < 0)
1557 free_image (f, img);
1558 ++nfreed;
1563 /* We may be clearing the image cache because, for example,
1564 Emacs was iconified for a longer period of time. In that
1565 case, current matrices may still contain references to
1566 images freed above. So, clear these matrices. */
1567 if (nfreed)
1569 Lisp_Object tail, frame;
1571 FOR_EACH_FRAME (tail, frame)
1573 struct frame *fr = XFRAME (frame);
1574 if (FRAME_IMAGE_CACHE (fr) == c)
1575 clear_current_matrices (fr);
1578 windows_or_buffers_changed = 19;
1581 unblock_input ();
1585 void
1586 clear_image_caches (Lisp_Object filter)
1588 /* FIXME: We want to do
1589 * struct terminal *t;
1590 * for (t = terminal_list; t; t = t->next_terminal)
1591 * clear_image_cache (t, filter); */
1592 Lisp_Object tail, frame;
1593 FOR_EACH_FRAME (tail, frame)
1594 if (FRAME_WINDOW_P (XFRAME (frame)))
1595 clear_image_cache (XFRAME (frame), filter);
1598 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1599 0, 1, 0,
1600 doc: /* Clear the image cache.
1601 FILTER nil or a frame means clear all images in the selected frame.
1602 FILTER t means clear the image caches of all frames.
1603 Anything else, means only clear those images which refer to FILTER,
1604 which is then usually a filename. */)
1605 (Lisp_Object filter)
1607 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1608 clear_image_caches (filter);
1609 else
1610 clear_image_cache (decode_window_system_frame (filter), Qt);
1612 return Qnil;
1616 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1617 1, 2, 0,
1618 doc: /* Flush the image with specification SPEC on frame FRAME.
1619 This removes the image from the Emacs image cache. If SPEC specifies
1620 an image file, the next redisplay of this image will read from the
1621 current contents of that file.
1623 FRAME nil or omitted means use the selected frame.
1624 FRAME t means refresh the image on all frames. */)
1625 (Lisp_Object spec, Lisp_Object frame)
1627 if (!valid_image_p (spec))
1628 error ("Invalid image specification");
1630 if (EQ (frame, Qt))
1632 Lisp_Object tail;
1633 FOR_EACH_FRAME (tail, frame)
1635 struct frame *f = XFRAME (frame);
1636 if (FRAME_WINDOW_P (f))
1637 uncache_image (f, spec);
1640 else
1641 uncache_image (decode_window_system_frame (frame), spec);
1643 return Qnil;
1647 /* Compute masks and transform image IMG on frame F, as specified
1648 by the image's specification, */
1650 static void
1651 postprocess_image (struct frame *f, struct image *img)
1653 /* Manipulation of the image's mask. */
1654 if (img->pixmap)
1656 Lisp_Object conversion, spec;
1657 Lisp_Object mask;
1659 spec = img->spec;
1661 /* `:heuristic-mask t'
1662 `:mask heuristic'
1663 means build a mask heuristically.
1664 `:heuristic-mask (R G B)'
1665 `:mask (heuristic (R G B))'
1666 means build a mask from color (R G B) in the
1667 image.
1668 `:mask nil'
1669 means remove a mask, if any. */
1671 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1672 if (!NILP (mask))
1673 x_build_heuristic_mask (f, img, mask);
1674 else
1676 bool found_p;
1678 mask = image_spec_value (spec, QCmask, &found_p);
1680 if (EQ (mask, Qheuristic))
1681 x_build_heuristic_mask (f, img, Qt);
1682 else if (CONSP (mask)
1683 && EQ (XCAR (mask), Qheuristic))
1685 if (CONSP (XCDR (mask)))
1686 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1687 else
1688 x_build_heuristic_mask (f, img, XCDR (mask));
1690 else if (NILP (mask) && found_p && img->mask)
1691 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1695 /* Should we apply an image transformation algorithm? */
1696 conversion = image_spec_value (spec, QCconversion, NULL);
1697 if (EQ (conversion, Qdisabled))
1698 x_disable_image (f, img);
1699 else if (EQ (conversion, Qlaplace))
1700 x_laplace (f, img);
1701 else if (EQ (conversion, Qemboss))
1702 x_emboss (f, img);
1703 else if (CONSP (conversion)
1704 && EQ (XCAR (conversion), Qedge_detection))
1706 Lisp_Object tem;
1707 tem = XCDR (conversion);
1708 if (CONSP (tem))
1709 x_edge_detection (f, img,
1710 Fplist_get (tem, QCmatrix),
1711 Fplist_get (tem, QCcolor_adjustment));
1717 /* Return the id of image with Lisp specification SPEC on frame F.
1718 SPEC must be a valid Lisp image specification (see valid_image_p). */
1720 ptrdiff_t
1721 lookup_image (struct frame *f, Lisp_Object spec)
1723 struct image *img;
1724 EMACS_UINT hash;
1726 /* F must be a window-system frame, and SPEC must be a valid image
1727 specification. */
1728 eassert (FRAME_WINDOW_P (f));
1729 eassert (valid_image_p (spec));
1731 /* Look up SPEC in the hash table of the image cache. */
1732 hash = sxhash (spec, 0);
1733 img = search_image_cache (f, spec, hash);
1734 if (img && img->load_failed_p)
1736 free_image (f, img);
1737 img = NULL;
1740 /* If not found, create a new image and cache it. */
1741 if (img == NULL)
1743 block_input ();
1744 img = make_image (spec, hash);
1745 cache_image (f, img);
1746 img->load_failed_p = ! img->type->load (f, img);
1747 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1748 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1750 /* If we can't load the image, and we don't have a width and
1751 height, use some arbitrary width and height so that we can
1752 draw a rectangle for it. */
1753 if (img->load_failed_p)
1755 Lisp_Object value;
1757 value = image_spec_value (spec, QCwidth, NULL);
1758 img->width = (INTEGERP (value)
1759 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1760 value = image_spec_value (spec, QCheight, NULL);
1761 img->height = (INTEGERP (value)
1762 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1764 else
1766 /* Handle image type independent image attributes
1767 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1768 `:background COLOR'. */
1769 Lisp_Object ascent, margin, relief, bg;
1770 int relief_bound;
1772 ascent = image_spec_value (spec, QCascent, NULL);
1773 if (INTEGERP (ascent))
1774 img->ascent = XFASTINT (ascent);
1775 else if (EQ (ascent, Qcenter))
1776 img->ascent = CENTERED_IMAGE_ASCENT;
1778 margin = image_spec_value (spec, QCmargin, NULL);
1779 if (INTEGERP (margin))
1780 img->vmargin = img->hmargin = XFASTINT (margin);
1781 else if (CONSP (margin))
1783 img->hmargin = XFASTINT (XCAR (margin));
1784 img->vmargin = XFASTINT (XCDR (margin));
1787 relief = image_spec_value (spec, QCrelief, NULL);
1788 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1789 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1791 img->relief = XINT (relief);
1792 img->hmargin += eabs (img->relief);
1793 img->vmargin += eabs (img->relief);
1796 if (! img->background_valid)
1798 bg = image_spec_value (img->spec, QCbackground, NULL);
1799 if (!NILP (bg))
1801 img->background
1802 = x_alloc_image_color (f, img, bg,
1803 FRAME_BACKGROUND_PIXEL (f));
1804 img->background_valid = 1;
1808 /* Do image transformations and compute masks, unless we
1809 don't have the image yet. */
1810 if (!EQ (builtin_lisp_symbol (img->type->type), Qpostscript))
1811 postprocess_image (f, img);
1814 unblock_input ();
1817 /* We're using IMG, so set its timestamp to `now'. */
1818 img->timestamp = current_timespec ();
1820 /* Value is the image id. */
1821 return img->id;
1825 /* Cache image IMG in the image cache of frame F. */
1827 static void
1828 cache_image (struct frame *f, struct image *img)
1830 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1831 ptrdiff_t i;
1833 /* Find a free slot in c->images. */
1834 for (i = 0; i < c->used; ++i)
1835 if (c->images[i] == NULL)
1836 break;
1838 /* If no free slot found, maybe enlarge c->images. */
1839 if (i == c->used && c->used == c->size)
1840 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1842 /* Add IMG to c->images, and assign IMG an id. */
1843 c->images[i] = img;
1844 img->id = i;
1845 if (i == c->used)
1846 ++c->used;
1848 /* Add IMG to the cache's hash table. */
1849 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1850 img->next = c->buckets[i];
1851 if (img->next)
1852 img->next->prev = img;
1853 img->prev = NULL;
1854 c->buckets[i] = img;
1858 /* Call FN on every image in the image cache of frame F. Used to mark
1859 Lisp Objects in the image cache. */
1861 /* Mark Lisp objects in image IMG. */
1863 static void
1864 mark_image (struct image *img)
1866 mark_object (img->spec);
1867 mark_object (img->dependencies);
1869 if (!NILP (img->lisp_data))
1870 mark_object (img->lisp_data);
1874 void
1875 mark_image_cache (struct image_cache *c)
1877 if (c)
1879 ptrdiff_t i;
1880 for (i = 0; i < c->used; ++i)
1881 if (c->images[i])
1882 mark_image (c->images[i]);
1888 /***********************************************************************
1889 X / NS / W32 support code
1890 ***********************************************************************/
1892 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1893 windowing system.
1894 WIDTH and HEIGHT must both be positive.
1895 If XIMG is null, assume it is a bitmap. */
1896 static bool
1897 x_check_image_size (XImagePtr ximg, int width, int height)
1899 #ifdef HAVE_X_WINDOWS
1900 /* Respect Xlib's limits: it cannot deal with images that have more
1901 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1902 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1903 enum
1905 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1906 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1909 int bitmap_pad, depth, bytes_per_line;
1910 if (ximg)
1912 bitmap_pad = ximg->bitmap_pad;
1913 depth = ximg->depth;
1914 bytes_per_line = ximg->bytes_per_line;
1916 else
1918 bitmap_pad = 8;
1919 depth = 1;
1920 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1922 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1923 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1924 #else
1925 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1926 For now, assume that every image size is allowed on these systems. */
1927 return 1;
1928 #endif
1931 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1932 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1933 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1934 via xmalloc. Print error messages via image_error if an error
1935 occurs. Value is true if successful.
1937 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1938 should indicate the bit depth of the image. */
1940 static bool
1941 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1942 XImagePtr *ximg, Pixmap *pixmap)
1944 #ifdef HAVE_X_WINDOWS
1945 Display *display = FRAME_X_DISPLAY (f);
1946 Window window = FRAME_X_WINDOW (f);
1947 Screen *screen = FRAME_X_SCREEN (f);
1949 eassert (input_blocked_p ());
1951 if (depth <= 0)
1952 depth = DefaultDepthOfScreen (screen);
1953 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1954 depth, ZPixmap, 0, NULL, width, height,
1955 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1956 if (*ximg == NULL)
1958 image_error ("Unable to allocate X image");
1959 return 0;
1962 if (! x_check_image_size (*ximg, width, height))
1964 x_destroy_x_image (*ximg);
1965 *ximg = NULL;
1966 image_error ("Image too large (%dx%d)",
1967 make_number (width), make_number (height));
1968 return 0;
1971 /* Allocate image raster. */
1972 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1974 /* Allocate a pixmap of the same size. */
1975 *pixmap = XCreatePixmap (display, window, width, height, depth);
1976 if (*pixmap == NO_PIXMAP)
1978 x_destroy_x_image (*ximg);
1979 *ximg = NULL;
1980 image_error ("Unable to create X pixmap");
1981 return 0;
1984 return 1;
1985 #endif /* HAVE_X_WINDOWS */
1987 #ifdef HAVE_NTGUI
1989 BITMAPINFOHEADER *header;
1990 HDC hdc;
1991 int scanline_width_bits;
1992 int remainder;
1993 int palette_colors = 0;
1995 if (depth == 0)
1996 depth = 24;
1998 if (depth != 1 && depth != 4 && depth != 8
1999 && depth != 16 && depth != 24 && depth != 32)
2001 image_error ("Invalid image bit depth specified");
2002 return 0;
2005 scanline_width_bits = width * depth;
2006 remainder = scanline_width_bits % 32;
2008 if (remainder)
2009 scanline_width_bits += 32 - remainder;
2011 /* Bitmaps with a depth less than 16 need a palette. */
2012 /* BITMAPINFO structure already contains the first RGBQUAD. */
2013 if (depth < 16)
2014 palette_colors = 1 << (depth - 1);
2016 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2018 header = &(*ximg)->info.bmiHeader;
2019 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2020 header->biSize = sizeof (*header);
2021 header->biWidth = width;
2022 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2023 header->biPlanes = 1;
2024 header->biBitCount = depth;
2025 header->biCompression = BI_RGB;
2026 header->biClrUsed = palette_colors;
2028 /* TODO: fill in palette. */
2029 if (depth == 1)
2031 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2032 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2033 (*ximg)->info.bmiColors[0].rgbRed = 0;
2034 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2035 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2036 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2037 (*ximg)->info.bmiColors[1].rgbRed = 255;
2038 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2041 hdc = get_frame_dc (f);
2043 /* Create a DIBSection and raster array for the bitmap,
2044 and store its handle in *pixmap. */
2045 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2046 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2047 /* casting avoids a GCC warning */
2048 (void **)&((*ximg)->data), NULL, 0);
2050 /* Realize display palette and garbage all frames. */
2051 release_frame_dc (f, hdc);
2053 if (*pixmap == NULL)
2055 DWORD err = GetLastError ();
2056 Lisp_Object errcode;
2057 /* All system errors are < 10000, so the following is safe. */
2058 XSETINT (errcode, err);
2059 image_error ("Unable to create bitmap, error code %d", errcode);
2060 x_destroy_x_image (*ximg);
2061 *ximg = NULL;
2062 return 0;
2065 return 1;
2067 #endif /* HAVE_NTGUI */
2069 #ifdef HAVE_NS
2070 *pixmap = ns_image_for_XPM (width, height, depth);
2071 if (*pixmap == 0)
2073 *ximg = NULL;
2074 image_error ("Unable to allocate NSImage for XPM pixmap");
2075 return 0;
2077 *ximg = *pixmap;
2078 return 1;
2079 #endif
2083 /* Destroy XImage XIMG. Free XIMG->data. */
2085 static void
2086 x_destroy_x_image (XImagePtr ximg)
2088 eassert (input_blocked_p ());
2089 if (ximg)
2091 #ifdef HAVE_X_WINDOWS
2092 xfree (ximg->data);
2093 ximg->data = NULL;
2094 XDestroyImage (ximg);
2095 #endif /* HAVE_X_WINDOWS */
2096 #ifdef HAVE_NTGUI
2097 /* Data will be freed by DestroyObject. */
2098 ximg->data = NULL;
2099 xfree (ximg);
2100 #endif /* HAVE_NTGUI */
2101 #ifdef HAVE_NS
2102 ns_release_object (ximg);
2103 #endif /* HAVE_NS */
2108 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2109 are width and height of both the image and pixmap. */
2111 static void
2112 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2114 #ifdef HAVE_X_WINDOWS
2115 GC gc;
2117 eassert (input_blocked_p ());
2118 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2119 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2120 XFreeGC (FRAME_X_DISPLAY (f), gc);
2121 #endif /* HAVE_X_WINDOWS */
2123 #ifdef HAVE_NTGUI
2124 #if 0 /* I don't think this is necessary looking at where it is used. */
2125 HDC hdc = get_frame_dc (f);
2126 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2127 release_frame_dc (f, hdc);
2128 #endif
2129 #endif /* HAVE_NTGUI */
2131 #ifdef HAVE_NS
2132 eassert (ximg == pixmap);
2133 ns_retain_object (ximg);
2134 #endif
2137 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2138 with image_put_x_image. */
2140 static bool
2141 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2142 int width, int height, int depth,
2143 XImagePtr *ximg, bool mask_p)
2145 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2147 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2148 !mask_p ? &img->pixmap : &img->mask);
2151 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2152 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2153 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2154 On the other platforms, it puts XIMG into the pixmap, then frees
2155 the X image and its buffer. */
2157 static void
2158 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2159 bool mask_p)
2161 #ifdef HAVE_X_WINDOWS
2162 if (!mask_p)
2164 eassert (img->ximg == NULL);
2165 img->ximg = ximg;
2167 else
2169 eassert (img->mask_img == NULL);
2170 img->mask_img = ximg;
2172 #else
2173 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2174 img->width, img->height);
2175 x_destroy_x_image (ximg);
2176 #endif
2179 #ifdef HAVE_X_WINDOWS
2180 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2181 the X images and their buffers. */
2183 static void
2184 image_sync_to_pixmaps (struct frame *f, struct image *img)
2186 if (img->ximg)
2188 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2189 x_destroy_x_image (img->ximg);
2190 img->ximg = NULL;
2192 if (img->mask_img)
2194 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2195 x_destroy_x_image (img->mask_img);
2196 img->mask_img = NULL;
2199 #endif
2201 #ifdef HAVE_NTGUI
2202 /* Create a memory device context for IMG on frame F. It stores the
2203 currently selected GDI object into *PREV for future restoration by
2204 image_unget_x_image_or_dc. */
2206 static XImagePtr_or_DC
2207 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2208 HGDIOBJ *prev)
2210 HDC frame_dc = get_frame_dc (f);
2211 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2213 release_frame_dc (f, frame_dc);
2214 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2216 return ximg;
2219 static void
2220 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2221 XImagePtr_or_DC ximg, HGDIOBJ prev)
2223 SelectObject (ximg, prev);
2224 DeleteDC (ximg);
2226 #else /* !HAVE_NTGUI */
2227 /* Get the X image for IMG on frame F. The resulting X image data
2228 should be treated as read-only at least on X. */
2230 static XImagePtr
2231 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2233 #ifdef HAVE_X_WINDOWS
2234 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2236 if (ximg_in_img)
2237 return ximg_in_img;
2238 else
2239 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2240 0, 0, img->width, img->height, ~0, ZPixmap);
2241 #elif defined (HAVE_NS)
2242 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2244 ns_retain_object (pixmap);
2245 return pixmap;
2246 #endif
2249 static void
2250 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2252 #ifdef HAVE_X_WINDOWS
2253 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2255 if (ximg_in_img)
2256 eassert (ximg == ximg_in_img);
2257 else
2258 XDestroyImage (ximg);
2259 #elif defined (HAVE_NS)
2260 ns_release_object (ximg);
2261 #endif
2263 #endif /* !HAVE_NTGUI */
2266 /***********************************************************************
2267 File Handling
2268 ***********************************************************************/
2270 /* Find image file FILE. Look in data-directory/images, then
2271 x-bitmap-file-path. Value is the full name of the file
2272 found, or nil if not found. If PFD is nonnull store into *PFD a
2273 readable file descriptor for the file, opened in binary mode. If
2274 PFD is null, do not open the file. */
2276 static Lisp_Object
2277 x_find_image_fd (Lisp_Object file, int *pfd)
2279 Lisp_Object file_found, search_path;
2280 int fd;
2282 /* TODO I think this should use something like image-load-path
2283 instead. Unfortunately, that can contain non-string elements. */
2284 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2285 Vdata_directory),
2286 Vx_bitmap_file_path);
2288 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2289 fd = openp (search_path, file, Qnil, &file_found,
2290 pfd ? Qt : make_number (R_OK), false);
2291 if (fd >= 0 || fd == -2)
2293 file_found = ENCODE_FILE (file_found);
2294 if (fd == -2)
2296 /* The file exists locally, but has a file handler. (This
2297 happens, e.g., under Auto Image File Mode.) 'openp'
2298 didn't open the file, so we should, because the caller
2299 expects that. */
2300 fd = emacs_open (SSDATA (file_found), O_RDONLY | O_BINARY, 0);
2303 else /* fd < 0, but not -2 */
2304 return Qnil;
2305 if (pfd)
2306 *pfd = fd;
2307 return file_found;
2310 /* Find image file FILE. Look in data-directory/images, then
2311 x-bitmap-file-path. Value is the encoded full name of the file
2312 found, or nil if not found. */
2314 Lisp_Object
2315 x_find_image_file (Lisp_Object file)
2317 return x_find_image_fd (file, 0);
2320 /* Read FILE into memory. Value is a pointer to a buffer allocated
2321 with xmalloc holding FILE's contents. Value is null if an error
2322 occurred. FD is a file descriptor open for reading FILE. Set
2323 *SIZE to the size of the file. */
2325 static unsigned char *
2326 slurp_file (int fd, ptrdiff_t *size)
2328 FILE *fp = fdopen (fd, "rb");
2330 unsigned char *buf = NULL;
2331 struct stat st;
2333 if (fp)
2335 ptrdiff_t count = SPECPDL_INDEX ();
2336 record_unwind_protect_ptr (fclose_unwind, fp);
2338 if (fstat (fileno (fp), &st) == 0
2339 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2341 /* Report an error if we read past the purported EOF.
2342 This can happen if the file grows as we read it. */
2343 ptrdiff_t buflen = st.st_size;
2344 buf = xmalloc (buflen + 1);
2345 if (fread (buf, 1, buflen + 1, fp) == buflen)
2346 *size = buflen;
2347 else
2349 xfree (buf);
2350 buf = NULL;
2354 unbind_to (count, Qnil);
2357 return buf;
2362 /***********************************************************************
2363 XBM images
2364 ***********************************************************************/
2366 static bool xbm_load (struct frame *f, struct image *img);
2367 static bool xbm_image_p (Lisp_Object object);
2368 static bool xbm_file_p (Lisp_Object);
2371 /* Indices of image specification fields in xbm_format, below. */
2373 enum xbm_keyword_index
2375 XBM_TYPE,
2376 XBM_FILE,
2377 XBM_WIDTH,
2378 XBM_HEIGHT,
2379 XBM_DATA,
2380 XBM_FOREGROUND,
2381 XBM_BACKGROUND,
2382 XBM_ASCENT,
2383 XBM_MARGIN,
2384 XBM_RELIEF,
2385 XBM_ALGORITHM,
2386 XBM_HEURISTIC_MASK,
2387 XBM_MASK,
2388 XBM_LAST
2391 /* Vector of image_keyword structures describing the format
2392 of valid XBM image specifications. */
2394 static const struct image_keyword xbm_format[XBM_LAST] =
2396 {":type", IMAGE_SYMBOL_VALUE, 1},
2397 {":file", IMAGE_STRING_VALUE, 0},
2398 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2399 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2400 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2401 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2402 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2403 {":ascent", IMAGE_ASCENT_VALUE, 0},
2404 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2405 {":relief", IMAGE_INTEGER_VALUE, 0},
2406 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2407 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2408 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2411 /* Structure describing the image type XBM. */
2413 static struct image_type xbm_type =
2415 SYMBOL_INDEX (Qxbm),
2416 xbm_image_p,
2417 xbm_load,
2418 x_clear_image,
2419 NULL,
2420 NULL
2423 /* Tokens returned from xbm_scan. */
2425 enum xbm_token
2427 XBM_TK_IDENT = 256,
2428 XBM_TK_NUMBER
2432 /* Return true if OBJECT is a valid XBM-type image specification.
2433 A valid specification is a list starting with the symbol `image'
2434 The rest of the list is a property list which must contain an
2435 entry `:type xbm'.
2437 If the specification specifies a file to load, it must contain
2438 an entry `:file FILENAME' where FILENAME is a string.
2440 If the specification is for a bitmap loaded from memory it must
2441 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2442 WIDTH and HEIGHT are integers > 0. DATA may be:
2444 1. a string large enough to hold the bitmap data, i.e. it must
2445 have a size >= (WIDTH + 7) / 8 * HEIGHT
2447 2. a bool-vector of size >= WIDTH * HEIGHT
2449 3. a vector of strings or bool-vectors, one for each line of the
2450 bitmap.
2452 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2453 may not be specified in this case because they are defined in the
2454 XBM file.
2456 Both the file and data forms may contain the additional entries
2457 `:background COLOR' and `:foreground COLOR'. If not present,
2458 foreground and background of the frame on which the image is
2459 displayed is used. */
2461 static bool
2462 xbm_image_p (Lisp_Object object)
2464 struct image_keyword kw[XBM_LAST];
2466 memcpy (kw, xbm_format, sizeof kw);
2467 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2468 return 0;
2470 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2472 if (kw[XBM_FILE].count)
2474 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2475 return 0;
2477 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2479 /* In-memory XBM file. */
2480 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2481 return 0;
2483 else
2485 Lisp_Object data;
2486 int width, height;
2488 /* Entries for `:width', `:height' and `:data' must be present. */
2489 if (!kw[XBM_WIDTH].count
2490 || !kw[XBM_HEIGHT].count
2491 || !kw[XBM_DATA].count)
2492 return 0;
2494 data = kw[XBM_DATA].value;
2495 width = XFASTINT (kw[XBM_WIDTH].value);
2496 height = XFASTINT (kw[XBM_HEIGHT].value);
2498 /* Check type of data, and width and height against contents of
2499 data. */
2500 if (VECTORP (data))
2502 EMACS_INT i;
2504 /* Number of elements of the vector must be >= height. */
2505 if (ASIZE (data) < height)
2506 return 0;
2508 /* Each string or bool-vector in data must be large enough
2509 for one line of the image. */
2510 for (i = 0; i < height; ++i)
2512 Lisp_Object elt = AREF (data, i);
2514 if (STRINGP (elt))
2516 if (SCHARS (elt)
2517 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2518 return 0;
2520 else if (BOOL_VECTOR_P (elt))
2522 if (bool_vector_size (elt) < width)
2523 return 0;
2525 else
2526 return 0;
2529 else if (STRINGP (data))
2531 if (SCHARS (data)
2532 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2533 return 0;
2535 else if (BOOL_VECTOR_P (data))
2537 if (bool_vector_size (data) / height < width)
2538 return 0;
2540 else
2541 return 0;
2544 return 1;
2548 /* Scan a bitmap file. FP is the stream to read from. Value is
2549 either an enumerator from enum xbm_token, or a character for a
2550 single-character token, or 0 at end of file. If scanning an
2551 identifier, store the lexeme of the identifier in SVAL. If
2552 scanning a number, store its value in *IVAL. */
2554 static int
2555 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2557 unsigned int c;
2559 loop:
2561 /* Skip white space. */
2562 while (*s < end && (c = *(*s)++, c_isspace (c)))
2565 if (*s >= end)
2566 c = 0;
2567 else if (c_isdigit (c))
2569 int value = 0, digit;
2571 if (c == '0' && *s < end)
2573 c = *(*s)++;
2574 if (c == 'x' || c == 'X')
2576 while (*s < end)
2578 c = *(*s)++;
2579 if (c_isdigit (c))
2580 digit = c - '0';
2581 else if (c >= 'a' && c <= 'f')
2582 digit = c - 'a' + 10;
2583 else if (c >= 'A' && c <= 'F')
2584 digit = c - 'A' + 10;
2585 else
2586 break;
2587 value = 16 * value + digit;
2590 else if (c_isdigit (c))
2592 value = c - '0';
2593 while (*s < end
2594 && (c = *(*s)++, c_isdigit (c)))
2595 value = 8 * value + c - '0';
2598 else
2600 value = c - '0';
2601 while (*s < end
2602 && (c = *(*s)++, c_isdigit (c)))
2603 value = 10 * value + c - '0';
2606 if (*s < end)
2607 *s = *s - 1;
2608 *ival = value;
2609 c = XBM_TK_NUMBER;
2611 else if (c_isalpha (c) || c == '_')
2613 *sval++ = c;
2614 while (*s < end
2615 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2616 *sval++ = c;
2617 *sval = 0;
2618 if (*s < end)
2619 *s = *s - 1;
2620 c = XBM_TK_IDENT;
2622 else if (c == '/' && **s == '*')
2624 /* C-style comment. */
2625 ++*s;
2626 while (**s && (**s != '*' || *(*s + 1) != '/'))
2627 ++*s;
2628 if (**s)
2630 *s += 2;
2631 goto loop;
2635 return c;
2638 #ifdef HAVE_NTGUI
2640 /* Create a Windows bitmap from X bitmap data. */
2641 static HBITMAP
2642 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2644 static unsigned char swap_nibble[16]
2645 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2646 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2647 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2648 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2649 int i, j, w1, w2;
2650 unsigned char *bits, *p;
2651 HBITMAP bmp;
2653 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2654 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2655 bits = alloca (height * w2);
2656 memset (bits, 0, height * w2);
2657 for (i = 0; i < height; i++)
2659 p = bits + i*w2;
2660 for (j = 0; j < w1; j++)
2662 /* Bitswap XBM bytes to match how Windows does things. */
2663 unsigned char c = *data++;
2664 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2665 | (swap_nibble[(c>>4) & 0xf]));
2668 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2670 return bmp;
2673 static void
2674 convert_mono_to_color_image (struct frame *f, struct image *img,
2675 COLORREF foreground, COLORREF background)
2677 HDC hdc, old_img_dc, new_img_dc;
2678 HGDIOBJ old_prev, new_prev;
2679 HBITMAP new_pixmap;
2681 hdc = get_frame_dc (f);
2682 old_img_dc = CreateCompatibleDC (hdc);
2683 new_img_dc = CreateCompatibleDC (hdc);
2684 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2685 release_frame_dc (f, hdc);
2686 old_prev = SelectObject (old_img_dc, img->pixmap);
2687 new_prev = SelectObject (new_img_dc, new_pixmap);
2688 /* Windows convention for mono bitmaps is black = background,
2689 white = foreground. */
2690 SetTextColor (new_img_dc, background);
2691 SetBkColor (new_img_dc, foreground);
2693 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2694 0, 0, SRCCOPY);
2696 SelectObject (old_img_dc, old_prev);
2697 SelectObject (new_img_dc, new_prev);
2698 DeleteDC (old_img_dc);
2699 DeleteDC (new_img_dc);
2700 DeleteObject (img->pixmap);
2701 if (new_pixmap == 0)
2702 fprintf (stderr, "Failed to convert image to color.\n");
2703 else
2704 img->pixmap = new_pixmap;
2707 #define XBM_BIT_SHUFFLE(b) (~(b))
2709 #else
2711 #define XBM_BIT_SHUFFLE(b) (b)
2713 #endif /* HAVE_NTGUI */
2716 static void
2717 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2718 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2719 bool non_default_colors)
2721 #ifdef HAVE_NTGUI
2722 img->pixmap
2723 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2725 /* If colors were specified, transfer the bitmap to a color one. */
2726 if (non_default_colors)
2727 convert_mono_to_color_image (f, img, fg, bg);
2729 #elif defined (HAVE_NS)
2730 img->pixmap = ns_image_from_XBM (data, img->width, img->height, fg, bg);
2732 #else
2733 img->pixmap =
2734 (x_check_image_size (0, img->width, img->height)
2735 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2736 FRAME_X_WINDOW (f),
2737 data,
2738 img->width, img->height,
2739 fg, bg,
2740 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2741 : NO_PIXMAP);
2742 #endif /* !HAVE_NTGUI && !HAVE_NS */
2747 /* Replacement for XReadBitmapFileData which isn't available under old
2748 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2749 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2750 the image. Return in *DATA the bitmap data allocated with xmalloc.
2751 Value is true if successful. DATA null means just test if
2752 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2753 inhibit the call to image_error when the image size is invalid (the
2754 bitmap remains unread). */
2756 static bool
2757 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2758 int *width, int *height, char **data,
2759 bool inhibit_image_error)
2761 unsigned char *s = contents;
2762 char buffer[BUFSIZ];
2763 bool padding_p = 0;
2764 bool v10 = 0;
2765 int bytes_per_line, i, nbytes;
2766 char *p;
2767 int value;
2768 int LA1;
2770 #define match() \
2771 LA1 = xbm_scan (&s, end, buffer, &value)
2773 #define expect(TOKEN) \
2774 do \
2776 if (LA1 != (TOKEN)) \
2777 goto failure; \
2778 match (); \
2780 while (0)
2782 #define expect_ident(IDENT) \
2783 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2784 match (); \
2785 else \
2786 goto failure
2788 *width = *height = -1;
2789 if (data)
2790 *data = NULL;
2791 LA1 = xbm_scan (&s, end, buffer, &value);
2793 /* Parse defines for width, height and hot-spots. */
2794 while (LA1 == '#')
2796 match ();
2797 expect_ident ("define");
2798 expect (XBM_TK_IDENT);
2800 if (LA1 == XBM_TK_NUMBER)
2802 char *q = strrchr (buffer, '_');
2803 q = q ? q + 1 : buffer;
2804 if (strcmp (q, "width") == 0)
2805 *width = value;
2806 else if (strcmp (q, "height") == 0)
2807 *height = value;
2809 expect (XBM_TK_NUMBER);
2812 if (!check_image_size (f, *width, *height))
2814 if (!inhibit_image_error)
2815 image_size_error ();
2816 goto failure;
2818 else if (data == NULL)
2819 goto success;
2821 /* Parse bits. Must start with `static'. */
2822 expect_ident ("static");
2823 if (LA1 == XBM_TK_IDENT)
2825 if (strcmp (buffer, "unsigned") == 0)
2827 match ();
2828 expect_ident ("char");
2830 else if (strcmp (buffer, "short") == 0)
2832 match ();
2833 v10 = 1;
2834 if (*width % 16 && *width % 16 < 9)
2835 padding_p = 1;
2837 else if (strcmp (buffer, "char") == 0)
2838 match ();
2839 else
2840 goto failure;
2842 else
2843 goto failure;
2845 expect (XBM_TK_IDENT);
2846 expect ('[');
2847 expect (']');
2848 expect ('=');
2849 expect ('{');
2851 if (! x_check_image_size (0, *width, *height))
2853 if (!inhibit_image_error)
2854 image_error ("Image too large (%dx%d)",
2855 make_number (*width), make_number (*height));
2856 goto failure;
2858 bytes_per_line = (*width + 7) / 8 + padding_p;
2859 nbytes = bytes_per_line * *height;
2860 p = *data = xmalloc (nbytes);
2862 if (v10)
2864 for (i = 0; i < nbytes; i += 2)
2866 int val = value;
2867 expect (XBM_TK_NUMBER);
2869 *p++ = XBM_BIT_SHUFFLE (val);
2870 if (!padding_p || ((i + 2) % bytes_per_line))
2871 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2873 if (LA1 == ',' || LA1 == '}')
2874 match ();
2875 else
2876 goto failure;
2879 else
2881 for (i = 0; i < nbytes; ++i)
2883 int val = value;
2884 expect (XBM_TK_NUMBER);
2886 *p++ = XBM_BIT_SHUFFLE (val);
2888 if (LA1 == ',' || LA1 == '}')
2889 match ();
2890 else
2891 goto failure;
2895 success:
2896 return 1;
2898 failure:
2900 if (data && *data)
2902 xfree (*data);
2903 *data = NULL;
2905 return 0;
2907 #undef match
2908 #undef expect
2909 #undef expect_ident
2913 /* Load XBM image IMG which will be displayed on frame F from buffer
2914 CONTENTS. END is the end of the buffer. Value is true if
2915 successful. */
2917 static bool
2918 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2919 unsigned char *end)
2921 bool rc;
2922 char *data;
2923 bool success_p = 0;
2925 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2926 &data, 0);
2927 if (rc)
2929 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2930 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2931 bool non_default_colors = 0;
2932 Lisp_Object value;
2934 eassert (img->width > 0 && img->height > 0);
2936 /* Get foreground and background colors, maybe allocate colors. */
2937 value = image_spec_value (img->spec, QCforeground, NULL);
2938 if (!NILP (value))
2940 foreground = x_alloc_image_color (f, img, value, foreground);
2941 non_default_colors = 1;
2943 value = image_spec_value (img->spec, QCbackground, NULL);
2944 if (!NILP (value))
2946 background = x_alloc_image_color (f, img, value, background);
2947 img->background = background;
2948 img->background_valid = 1;
2949 non_default_colors = 1;
2952 Create_Pixmap_From_Bitmap_Data (f, img, data,
2953 foreground, background,
2954 non_default_colors);
2955 xfree (data);
2957 if (img->pixmap == NO_PIXMAP)
2959 x_clear_image (f, img);
2960 image_error ("Unable to create X pixmap for `%s'", img->spec);
2962 else
2963 success_p = 1;
2965 else
2966 image_error ("Error loading XBM image `%s'", img->spec);
2968 return success_p;
2972 /* Value is true if DATA looks like an in-memory XBM file. */
2974 static bool
2975 xbm_file_p (Lisp_Object data)
2977 int w, h;
2978 return (STRINGP (data)
2979 && xbm_read_bitmap_data (NULL, SDATA (data),
2980 (SDATA (data) + SBYTES (data)),
2981 &w, &h, NULL, 1));
2985 /* Fill image IMG which is used on frame F with pixmap data. Value is
2986 true if successful. */
2988 static bool
2989 xbm_load (struct frame *f, struct image *img)
2991 bool success_p = 0;
2992 Lisp_Object file_name;
2994 eassert (xbm_image_p (img->spec));
2996 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2997 file_name = image_spec_value (img->spec, QCfile, NULL);
2998 if (STRINGP (file_name))
3000 int fd;
3001 Lisp_Object file = x_find_image_fd (file_name, &fd);
3002 if (!STRINGP (file))
3004 image_error ("Cannot find image file `%s'", file_name);
3005 return 0;
3008 ptrdiff_t size;
3009 unsigned char *contents = slurp_file (fd, &size);
3010 if (contents == NULL)
3012 image_error ("Error loading XBM image `%s'", file);
3013 return 0;
3016 success_p = xbm_load_image (f, img, contents, contents + size);
3017 xfree (contents);
3019 else
3021 struct image_keyword fmt[XBM_LAST];
3022 Lisp_Object data;
3023 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3024 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3025 bool non_default_colors = 0;
3026 char *bits;
3027 bool parsed_p;
3028 bool in_memory_file_p = 0;
3030 /* See if data looks like an in-memory XBM file. */
3031 data = image_spec_value (img->spec, QCdata, NULL);
3032 in_memory_file_p = xbm_file_p (data);
3034 /* Parse the image specification. */
3035 memcpy (fmt, xbm_format, sizeof fmt);
3036 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3037 eassert (parsed_p);
3039 /* Get specified width, and height. */
3040 if (!in_memory_file_p)
3042 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3043 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3044 eassert (img->width > 0 && img->height > 0);
3045 if (!check_image_size (f, img->width, img->height))
3047 image_size_error ();
3048 return 0;
3052 /* Get foreground and background colors, maybe allocate colors. */
3053 if (fmt[XBM_FOREGROUND].count
3054 && STRINGP (fmt[XBM_FOREGROUND].value))
3056 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3057 foreground);
3058 non_default_colors = 1;
3061 if (fmt[XBM_BACKGROUND].count
3062 && STRINGP (fmt[XBM_BACKGROUND].value))
3064 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3065 background);
3066 non_default_colors = 1;
3069 if (in_memory_file_p)
3070 success_p = xbm_load_image (f, img, SDATA (data),
3071 (SDATA (data)
3072 + SBYTES (data)));
3073 else
3075 USE_SAFE_ALLOCA;
3077 if (VECTORP (data))
3079 int i;
3080 char *p;
3081 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3083 SAFE_NALLOCA (bits, nbytes, img->height);
3084 p = bits;
3085 for (i = 0; i < img->height; ++i, p += nbytes)
3087 Lisp_Object line = AREF (data, i);
3088 if (STRINGP (line))
3089 memcpy (p, SDATA (line), nbytes);
3090 else
3091 memcpy (p, bool_vector_data (line), nbytes);
3094 else if (STRINGP (data))
3095 bits = SSDATA (data);
3096 else
3097 bits = (char *) bool_vector_data (data);
3099 #ifdef HAVE_NTGUI
3101 char *invertedBits;
3102 int nbytes, i;
3103 /* Windows mono bitmaps are reversed compared with X. */
3104 invertedBits = bits;
3105 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3106 SAFE_NALLOCA (bits, nbytes, img->height);
3107 for (i = 0; i < nbytes; i++)
3108 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3110 #endif
3111 /* Create the pixmap. */
3113 if (x_check_image_size (0, img->width, img->height))
3114 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3115 foreground, background,
3116 non_default_colors);
3117 else
3118 img->pixmap = NO_PIXMAP;
3120 if (img->pixmap)
3121 success_p = 1;
3122 else
3124 image_error ("Unable to create pixmap for XBM image `%s'",
3125 img->spec);
3126 x_clear_image (f, img);
3129 SAFE_FREE ();
3133 return success_p;
3138 /***********************************************************************
3139 XPM images
3140 ***********************************************************************/
3142 #if defined (HAVE_XPM) || defined (HAVE_NS)
3144 static bool xpm_image_p (Lisp_Object object);
3145 static bool xpm_load (struct frame *f, struct image *img);
3147 #endif /* HAVE_XPM || HAVE_NS */
3149 #ifdef HAVE_XPM
3150 #ifdef HAVE_NTGUI
3151 /* Indicate to xpm.h that we don't have Xlib. */
3152 #define FOR_MSW
3153 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3154 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3155 #define XColor xpm_XColor
3156 #define XImage xpm_XImage
3157 #define Display xpm_Display
3158 #define PIXEL_ALREADY_TYPEDEFED
3159 #include "X11/xpm.h"
3160 #undef FOR_MSW
3161 #undef XColor
3162 #undef XImage
3163 #undef Display
3164 #undef PIXEL_ALREADY_TYPEDEFED
3165 #else
3166 #include "X11/xpm.h"
3167 #endif /* HAVE_NTGUI */
3168 #endif /* HAVE_XPM */
3170 #if defined (HAVE_XPM) || defined (HAVE_NS)
3172 /* Indices of image specification fields in xpm_format, below. */
3174 enum xpm_keyword_index
3176 XPM_TYPE,
3177 XPM_FILE,
3178 XPM_DATA,
3179 XPM_ASCENT,
3180 XPM_MARGIN,
3181 XPM_RELIEF,
3182 XPM_ALGORITHM,
3183 XPM_HEURISTIC_MASK,
3184 XPM_MASK,
3185 XPM_COLOR_SYMBOLS,
3186 XPM_BACKGROUND,
3187 XPM_LAST
3190 /* Vector of image_keyword structures describing the format
3191 of valid XPM image specifications. */
3193 static const struct image_keyword xpm_format[XPM_LAST] =
3195 {":type", IMAGE_SYMBOL_VALUE, 1},
3196 {":file", IMAGE_STRING_VALUE, 0},
3197 {":data", IMAGE_STRING_VALUE, 0},
3198 {":ascent", IMAGE_ASCENT_VALUE, 0},
3199 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3200 {":relief", IMAGE_INTEGER_VALUE, 0},
3201 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3202 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3203 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3204 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3205 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3208 #if defined HAVE_NTGUI && defined WINDOWSNT
3209 static bool init_xpm_functions (void);
3210 #else
3211 #define init_xpm_functions NULL
3212 #endif
3214 /* Structure describing the image type XPM. */
3216 static struct image_type xpm_type =
3218 SYMBOL_INDEX (Qxpm),
3219 xpm_image_p,
3220 xpm_load,
3221 x_clear_image,
3222 init_xpm_functions,
3223 NULL
3226 #ifdef HAVE_X_WINDOWS
3228 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3229 functions for allocating image colors. Our own functions handle
3230 color allocation failures more gracefully than the ones on the XPM
3231 lib. */
3233 #ifndef USE_CAIRO
3234 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3235 #define ALLOC_XPM_COLORS
3236 #endif
3237 #endif /* USE_CAIRO */
3238 #endif /* HAVE_X_WINDOWS */
3240 #ifdef ALLOC_XPM_COLORS
3242 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3243 XColor *, int);
3245 /* An entry in a hash table used to cache color definitions of named
3246 colors. This cache is necessary to speed up XPM image loading in
3247 case we do color allocations ourselves. Without it, we would need
3248 a call to XParseColor per pixel in the image.
3250 FIXME Now that we're using x_parse_color and its cache, reevaluate
3251 the need for this caching layer. */
3253 struct xpm_cached_color
3255 /* Next in collision chain. */
3256 struct xpm_cached_color *next;
3258 /* Color definition (RGB and pixel color). */
3259 XColor color;
3261 /* Color name. */
3262 char name[FLEXIBLE_ARRAY_MEMBER];
3265 /* The hash table used for the color cache, and its bucket vector
3266 size. */
3268 #define XPM_COLOR_CACHE_BUCKETS 1001
3269 static struct xpm_cached_color **xpm_color_cache;
3271 /* Initialize the color cache. */
3273 static void
3274 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3276 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3277 xpm_color_cache = xzalloc (nbytes);
3278 init_color_table ();
3280 if (attrs->valuemask & XpmColorSymbols)
3282 int i;
3283 XColor color;
3285 for (i = 0; i < attrs->numsymbols; ++i)
3286 if (x_parse_color (f, attrs->colorsymbols[i].value, &color))
3288 color.pixel = lookup_rgb_color (f, color.red, color.green,
3289 color.blue);
3290 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3295 /* Free the color cache. */
3297 static void
3298 xpm_free_color_cache (void)
3300 struct xpm_cached_color *p, *next;
3301 int i;
3303 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3304 for (p = xpm_color_cache[i]; p; p = next)
3306 next = p->next;
3307 xfree (p);
3310 xfree (xpm_color_cache);
3311 xpm_color_cache = NULL;
3312 free_color_table ();
3315 /* Return the bucket index for color named COLOR_NAME in the color
3316 cache. */
3318 static int
3319 xpm_color_bucket (char *color_name)
3321 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3322 return hash % XPM_COLOR_CACHE_BUCKETS;
3326 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3327 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3328 entry added. */
3330 static struct xpm_cached_color *
3331 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3333 size_t nbytes;
3334 struct xpm_cached_color *p;
3336 if (bucket < 0)
3337 bucket = xpm_color_bucket (color_name);
3339 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3340 p = xmalloc (nbytes);
3341 strcpy (p->name, color_name);
3342 p->color = *color;
3343 p->next = xpm_color_cache[bucket];
3344 xpm_color_cache[bucket] = p;
3345 return p;
3348 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3349 return the cached definition in *COLOR. Otherwise, make a new
3350 entry in the cache and allocate the color. Value is false if color
3351 allocation failed. */
3353 static bool
3354 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3356 struct xpm_cached_color *p;
3357 int h = xpm_color_bucket (color_name);
3359 for (p = xpm_color_cache[h]; p; p = p->next)
3360 if (strcmp (p->name, color_name) == 0)
3361 break;
3363 if (p != NULL)
3364 *color = p->color;
3365 else if (x_parse_color (f, color_name, color))
3367 color->pixel = lookup_rgb_color (f, color->red, color->green,
3368 color->blue);
3369 p = xpm_cache_color (f, color_name, color, h);
3371 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3372 with transparency, and it's useful. */
3373 else if (strcmp ("opaque", color_name) == 0)
3375 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3376 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3377 p = xpm_cache_color (f, color_name, color, h);
3380 return p != NULL;
3384 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3385 CLOSURE is a pointer to the frame on which we allocate the
3386 color. Return in *COLOR the allocated color. Value is non-zero
3387 if successful. */
3389 static int
3390 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3391 void *closure)
3393 return xpm_lookup_color (closure, color_name, color);
3397 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3398 is a pointer to the frame on which we allocate the color. Value is
3399 non-zero if successful. */
3401 static int
3402 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3404 return 1;
3407 #endif /* ALLOC_XPM_COLORS */
3410 #ifdef WINDOWSNT
3412 /* XPM library details. */
3414 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3415 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3416 (Display *, char *, xpm_XImage **,
3417 xpm_XImage **, XpmAttributes *));
3418 DEF_DLL_FN (int, XpmReadFileToImage,
3419 (Display *, char *, xpm_XImage **,
3420 xpm_XImage **, XpmAttributes *));
3421 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3423 static bool
3424 init_xpm_functions (void)
3426 HMODULE library;
3428 if (!(library = w32_delayed_load (Qxpm)))
3429 return 0;
3431 LOAD_DLL_FN (library, XpmFreeAttributes);
3432 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3433 LOAD_DLL_FN (library, XpmReadFileToImage);
3434 LOAD_DLL_FN (library, XImageFree);
3435 return 1;
3438 # undef XImageFree
3439 # undef XpmCreateImageFromBuffer
3440 # undef XpmFreeAttributes
3441 # undef XpmReadFileToImage
3443 # define XImageFree fn_XImageFree
3444 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3445 # define XpmFreeAttributes fn_XpmFreeAttributes
3446 # define XpmReadFileToImage fn_XpmReadFileToImage
3448 #endif /* WINDOWSNT */
3450 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3451 for XPM images. Such a list must consist of conses whose car and
3452 cdr are strings. */
3454 static bool
3455 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3457 while (CONSP (color_symbols))
3459 Lisp_Object sym = XCAR (color_symbols);
3460 if (!CONSP (sym)
3461 || !STRINGP (XCAR (sym))
3462 || !STRINGP (XCDR (sym)))
3463 break;
3464 color_symbols = XCDR (color_symbols);
3467 return NILP (color_symbols);
3471 /* Value is true if OBJECT is a valid XPM image specification. */
3473 static bool
3474 xpm_image_p (Lisp_Object object)
3476 struct image_keyword fmt[XPM_LAST];
3477 memcpy (fmt, xpm_format, sizeof fmt);
3478 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3479 /* Either `:file' or `:data' must be present. */
3480 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3481 /* Either no `:color-symbols' or it's a list of conses
3482 whose car and cdr are strings. */
3483 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3484 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3487 #endif /* HAVE_XPM || HAVE_NS */
3489 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3490 ptrdiff_t
3491 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3493 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3494 ptrdiff_t id;
3495 int rc;
3496 XpmAttributes attrs;
3497 Pixmap bitmap, mask;
3499 memset (&attrs, 0, sizeof attrs);
3501 attrs.visual = FRAME_X_VISUAL (f);
3502 attrs.colormap = FRAME_X_COLORMAP (f);
3503 attrs.valuemask |= XpmVisual;
3504 attrs.valuemask |= XpmColormap;
3506 #ifdef ALLOC_XPM_COLORS
3507 attrs.color_closure = f;
3508 attrs.alloc_color = xpm_alloc_color;
3509 attrs.free_colors = xpm_free_colors;
3510 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3511 xpm_init_color_cache (f, &attrs);
3512 #endif
3514 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3515 (char **) bits, &bitmap, &mask, &attrs);
3516 if (rc != XpmSuccess)
3518 XpmFreeAttributes (&attrs);
3519 return -1;
3522 id = x_allocate_bitmap_record (f);
3523 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3524 dpyinfo->bitmaps[id - 1].have_mask = true;
3525 dpyinfo->bitmaps[id - 1].mask = mask;
3526 dpyinfo->bitmaps[id - 1].file = NULL;
3527 dpyinfo->bitmaps[id - 1].height = attrs.height;
3528 dpyinfo->bitmaps[id - 1].width = attrs.width;
3529 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3530 dpyinfo->bitmaps[id - 1].refcount = 1;
3532 #ifdef ALLOC_XPM_COLORS
3533 xpm_free_color_cache ();
3534 #endif
3535 XpmFreeAttributes (&attrs);
3536 return id;
3538 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3540 /* Load image IMG which will be displayed on frame F. Value is
3541 true if successful. */
3543 #ifdef HAVE_XPM
3545 static bool
3546 xpm_load (struct frame *f, struct image *img)
3548 int rc;
3549 XpmAttributes attrs;
3550 Lisp_Object specified_file, color_symbols;
3551 USE_SAFE_ALLOCA;
3553 #ifdef HAVE_NTGUI
3554 HDC hdc;
3555 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3556 #endif /* HAVE_NTGUI */
3558 /* Configure the XPM lib. Use the visual of frame F. Allocate
3559 close colors. Return colors allocated. */
3560 memset (&attrs, 0, sizeof attrs);
3562 #ifndef HAVE_NTGUI
3563 attrs.visual = FRAME_X_VISUAL (f);
3564 attrs.colormap = FRAME_X_COLORMAP (f);
3565 attrs.valuemask |= XpmVisual;
3566 attrs.valuemask |= XpmColormap;
3567 #endif /* HAVE_NTGUI */
3569 #ifdef ALLOC_XPM_COLORS
3570 /* Allocate colors with our own functions which handle
3571 failing color allocation more gracefully. */
3572 attrs.color_closure = f;
3573 attrs.alloc_color = xpm_alloc_color;
3574 attrs.free_colors = xpm_free_colors;
3575 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3576 #else /* not ALLOC_XPM_COLORS */
3577 /* Let the XPM lib allocate colors. */
3578 attrs.valuemask |= XpmReturnAllocPixels;
3579 #ifdef XpmAllocCloseColors
3580 attrs.alloc_close_colors = 1;
3581 attrs.valuemask |= XpmAllocCloseColors;
3582 #else /* not XpmAllocCloseColors */
3583 attrs.closeness = 600;
3584 attrs.valuemask |= XpmCloseness;
3585 #endif /* not XpmAllocCloseColors */
3586 #endif /* ALLOC_XPM_COLORS */
3588 /* If image specification contains symbolic color definitions, add
3589 these to `attrs'. */
3590 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3591 if (CONSP (color_symbols))
3593 Lisp_Object tail;
3594 XpmColorSymbol *xpm_syms;
3595 ptrdiff_t i, size;
3597 attrs.valuemask |= XpmColorSymbols;
3599 /* Count number of symbols. */
3600 attrs.numsymbols = 0;
3601 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3602 ++attrs.numsymbols;
3604 /* Allocate an XpmColorSymbol array. */
3605 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3606 size = attrs.numsymbols * sizeof *xpm_syms;
3607 memset (xpm_syms, 0, size);
3608 attrs.colorsymbols = xpm_syms;
3610 /* Fill the color symbol array. */
3611 for (tail = color_symbols, i = 0;
3612 CONSP (tail);
3613 ++i, tail = XCDR (tail))
3615 Lisp_Object name;
3616 Lisp_Object color;
3617 char *empty_string = (char *) "";
3619 if (!CONSP (XCAR (tail)))
3621 xpm_syms[i].name = empty_string;
3622 xpm_syms[i].value = empty_string;
3623 continue;
3625 name = XCAR (XCAR (tail));
3626 color = XCDR (XCAR (tail));
3627 if (STRINGP (name))
3628 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3629 else
3630 xpm_syms[i].name = empty_string;
3631 if (STRINGP (color))
3632 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3633 else
3634 xpm_syms[i].value = empty_string;
3638 /* Create a pixmap for the image, either from a file, or from a
3639 string buffer containing data in the same format as an XPM file. */
3640 #ifdef ALLOC_XPM_COLORS
3641 xpm_init_color_cache (f, &attrs);
3642 #endif
3644 specified_file = image_spec_value (img->spec, QCfile, NULL);
3646 #ifdef HAVE_NTGUI
3648 HDC frame_dc = get_frame_dc (f);
3649 hdc = CreateCompatibleDC (frame_dc);
3650 release_frame_dc (f, frame_dc);
3652 #endif /* HAVE_NTGUI */
3654 if (STRINGP (specified_file))
3656 Lisp_Object file = x_find_image_file (specified_file);
3657 if (!STRINGP (file))
3659 image_error ("Cannot find image file `%s'", specified_file);
3660 #ifdef ALLOC_XPM_COLORS
3661 xpm_free_color_cache ();
3662 #endif
3663 SAFE_FREE ();
3664 return 0;
3667 file = ENCODE_FILE (file);
3668 #ifdef HAVE_NTGUI
3669 #ifdef WINDOWSNT
3670 /* FILE is encoded in UTF-8, but image libraries on Windows
3671 support neither UTF-8 nor UTF-16 encoded file names. So we
3672 need to re-encode it in ANSI. */
3673 file = ansi_encode_filename (file);
3674 #endif
3675 /* XpmReadFileToPixmap is not available in the Windows port of
3676 libxpm. But XpmReadFileToImage almost does what we want. */
3677 rc = XpmReadFileToImage (&hdc, SDATA (file),
3678 &xpm_image, &xpm_mask,
3679 &attrs);
3680 #else
3681 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3682 &img->ximg, &img->mask_img,
3683 &attrs);
3684 #endif /* HAVE_NTGUI */
3686 else
3688 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3689 if (!STRINGP (buffer))
3691 image_error ("Invalid image data `%s'", buffer);
3692 #ifdef ALLOC_XPM_COLORS
3693 xpm_free_color_cache ();
3694 #endif
3695 SAFE_FREE ();
3696 return 0;
3698 #ifdef HAVE_NTGUI
3699 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3700 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3701 rc = XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3702 &xpm_image, &xpm_mask,
3703 &attrs);
3704 #else
3705 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3706 &img->ximg, &img->mask_img,
3707 &attrs);
3708 #endif /* HAVE_NTGUI */
3711 #ifdef USE_CAIRO
3712 // Load very specific Xpm:s.
3713 if (rc == XpmSuccess
3714 && img->ximg->format == ZPixmap
3715 && img->ximg->bits_per_pixel == 32
3716 && (! img->mask_img || img->mask_img->bits_per_pixel == 1))
3718 int width = img->ximg->width;
3719 int height = img->ximg->height;
3720 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
3721 int i;
3722 uint32_t *od = (uint32_t *)data;
3723 uint32_t *id = (uint32_t *)img->ximg->data;
3724 char *mid = img->mask_img ? img->mask_img->data : 0;
3725 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
3727 for (i = 0; i < height; ++i)
3729 int k;
3730 for (k = 0; k < width; ++k)
3732 int idx = i * img->ximg->bytes_per_line/4 + k;
3733 int maskidx = mid ? i * img->mask_img->bytes_per_line + k/8 : 0;
3734 int mask = mid ? mid[maskidx] & (1 << (k % 8)) : 1;
3736 if (mask) od[idx] = id[idx] + 0xff000000; // ff => full alpha
3737 else od[idx] = bgcolor;
3741 create_cairo_image_surface (img, data, width, height);
3743 else
3745 rc = XpmFileInvalid;
3746 x_clear_image (f, img);
3748 #else
3749 #ifdef HAVE_X_WINDOWS
3750 if (rc == XpmSuccess)
3752 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3753 img->ximg->width, img->ximg->height,
3754 img->ximg->depth);
3755 if (img->pixmap == NO_PIXMAP)
3757 x_clear_image (f, img);
3758 rc = XpmNoMemory;
3760 else if (img->mask_img)
3762 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3763 img->mask_img->width,
3764 img->mask_img->height,
3765 img->mask_img->depth);
3766 if (img->mask == NO_PIXMAP)
3768 x_clear_image (f, img);
3769 rc = XpmNoMemory;
3773 #endif
3774 #endif /* ! USE_CAIRO */
3776 if (rc == XpmSuccess)
3778 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3779 img->colors = colors_in_color_table (&img->ncolors);
3780 #else /* not ALLOC_XPM_COLORS */
3781 int i;
3783 #ifdef HAVE_NTGUI
3784 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3785 plus some duplicate attributes. */
3786 if (xpm_image && xpm_image->bitmap)
3788 img->pixmap = xpm_image->bitmap;
3789 /* XImageFree in libXpm frees XImage struct without destroying
3790 the bitmap, which is what we want. */
3791 XImageFree (xpm_image);
3793 if (xpm_mask && xpm_mask->bitmap)
3795 /* The mask appears to be inverted compared with what we expect.
3796 TODO: invert our expectations. See other places where we
3797 have to invert bits because our idea of masks is backwards. */
3798 HGDIOBJ old_obj;
3799 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3801 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3802 SelectObject (hdc, old_obj);
3804 img->mask = xpm_mask->bitmap;
3805 XImageFree (xpm_mask);
3806 DeleteDC (hdc);
3809 DeleteDC (hdc);
3810 #endif /* HAVE_NTGUI */
3812 /* Remember allocated colors. */
3813 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3814 img->ncolors = attrs.nalloc_pixels;
3815 for (i = 0; i < attrs.nalloc_pixels; ++i)
3817 img->colors[i] = attrs.alloc_pixels[i];
3818 #ifdef DEBUG_X_COLORS
3819 register_color (img->colors[i]);
3820 #endif
3822 #endif /* not ALLOC_XPM_COLORS */
3824 img->width = attrs.width;
3825 img->height = attrs.height;
3826 eassert (img->width > 0 && img->height > 0);
3828 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3829 XpmFreeAttributes (&attrs);
3831 #ifdef HAVE_X_WINDOWS
3832 /* Maybe fill in the background field while we have ximg handy. */
3833 IMAGE_BACKGROUND (img, f, img->ximg);
3834 if (img->mask_img)
3835 /* Fill in the background_transparent field while we have the
3836 mask handy. */
3837 image_background_transparent (img, f, img->mask_img);
3838 #endif
3840 else
3842 #ifdef HAVE_NTGUI
3843 DeleteDC (hdc);
3844 #endif /* HAVE_NTGUI */
3846 switch (rc)
3848 case XpmOpenFailed:
3849 image_error ("Error opening XPM file (%s)", img->spec);
3850 break;
3852 case XpmFileInvalid:
3853 image_error ("Invalid XPM file (%s)", img->spec);
3854 break;
3856 case XpmNoMemory:
3857 image_error ("Out of memory (%s)", img->spec);
3858 break;
3860 case XpmColorFailed:
3861 image_error ("Color allocation error (%s)", img->spec);
3862 break;
3864 default:
3865 image_error ("Unknown error (%s)", img->spec);
3866 break;
3870 #ifdef ALLOC_XPM_COLORS
3871 xpm_free_color_cache ();
3872 #endif
3873 SAFE_FREE ();
3874 return rc == XpmSuccess;
3877 #endif /* HAVE_XPM */
3879 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3881 /* XPM support functions for NS where libxpm is not available.
3882 Only XPM version 3 (without any extensions) is supported. */
3884 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3885 int, Lisp_Object);
3886 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3887 const unsigned char *, int);
3888 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3889 int, Lisp_Object);
3890 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3891 const unsigned char *, int);
3893 /* Tokens returned from xpm_scan. */
3895 enum xpm_token
3897 XPM_TK_IDENT = 256,
3898 XPM_TK_STRING,
3899 XPM_TK_EOF
3902 /* Scan an XPM data and return a character (< 256) or a token defined
3903 by enum xpm_token above. *S and END are the start (inclusive) and
3904 the end (exclusive) addresses of the data, respectively. Advance
3905 *S while scanning. If token is either XPM_TK_IDENT or
3906 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3907 length of the corresponding token, respectively. */
3909 static int
3910 xpm_scan (const unsigned char **s,
3911 const unsigned char *end,
3912 const unsigned char **beg,
3913 ptrdiff_t *len)
3915 int c;
3917 while (*s < end)
3919 /* Skip white-space. */
3920 while (*s < end && (c = *(*s)++, c_isspace (c)))
3923 /* gnus-pointer.xpm uses '-' in its identifier.
3924 sb-dir-plus.xpm uses '+' in its identifier. */
3925 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3927 *beg = *s - 1;
3928 while (*s < end
3929 && (c = **s, c_isalnum (c)
3930 || c == '_' || c == '-' || c == '+'))
3931 ++*s;
3932 *len = *s - *beg;
3933 return XPM_TK_IDENT;
3935 else if (c == '"')
3937 *beg = *s;
3938 while (*s < end && **s != '"')
3939 ++*s;
3940 *len = *s - *beg;
3941 if (*s < end)
3942 ++*s;
3943 return XPM_TK_STRING;
3945 else if (c == '/')
3947 if (*s < end && **s == '*')
3949 /* C-style comment. */
3950 ++*s;
3953 while (*s < end && *(*s)++ != '*')
3956 while (*s < end && **s != '/');
3957 if (*s < end)
3958 ++*s;
3960 else
3961 return c;
3963 else
3964 return c;
3967 return XPM_TK_EOF;
3970 /* Functions for color table lookup in XPM data. A key is a string
3971 specifying the color of each pixel in XPM data. A value is either
3972 an integer that specifies a pixel color, Qt that specifies
3973 transparency, or Qnil for the unspecified color. If the length of
3974 the key string is one, a vector is used as a table. Otherwise, a
3975 hash table is used. */
3977 static Lisp_Object
3978 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3979 const unsigned char *,
3980 int,
3981 Lisp_Object),
3982 Lisp_Object (**get_func) (Lisp_Object,
3983 const unsigned char *,
3984 int))
3986 *put_func = xpm_put_color_table_v;
3987 *get_func = xpm_get_color_table_v;
3988 return Fmake_vector (make_number (256), Qnil);
3991 static void
3992 xpm_put_color_table_v (Lisp_Object color_table,
3993 const unsigned char *chars_start,
3994 int chars_len,
3995 Lisp_Object color)
3997 ASET (color_table, *chars_start, color);
4000 static Lisp_Object
4001 xpm_get_color_table_v (Lisp_Object color_table,
4002 const unsigned char *chars_start,
4003 int chars_len)
4005 return AREF (color_table, *chars_start);
4008 static Lisp_Object
4009 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
4010 const unsigned char *,
4011 int,
4012 Lisp_Object),
4013 Lisp_Object (**get_func) (Lisp_Object,
4014 const unsigned char *,
4015 int))
4017 *put_func = xpm_put_color_table_h;
4018 *get_func = xpm_get_color_table_h;
4019 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
4020 make_float (DEFAULT_REHASH_SIZE),
4021 make_float (DEFAULT_REHASH_THRESHOLD),
4022 Qnil);
4025 static void
4026 xpm_put_color_table_h (Lisp_Object color_table,
4027 const unsigned char *chars_start,
4028 int chars_len,
4029 Lisp_Object color)
4031 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4032 EMACS_UINT hash_code;
4033 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4035 hash_lookup (table, chars, &hash_code);
4036 hash_put (table, chars, color, hash_code);
4039 static Lisp_Object
4040 xpm_get_color_table_h (Lisp_Object color_table,
4041 const unsigned char *chars_start,
4042 int chars_len)
4044 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4045 ptrdiff_t i =
4046 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
4048 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4051 enum xpm_color_key {
4052 XPM_COLOR_KEY_S,
4053 XPM_COLOR_KEY_M,
4054 XPM_COLOR_KEY_G4,
4055 XPM_COLOR_KEY_G,
4056 XPM_COLOR_KEY_C
4059 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4061 static int
4062 xpm_str_to_color_key (const char *s)
4064 int i;
4066 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
4067 if (strcmp (xpm_color_key_strings[i], s) == 0)
4068 return i;
4069 return -1;
4072 static bool
4073 xpm_load_image (struct frame *f,
4074 struct image *img,
4075 const unsigned char *contents,
4076 const unsigned char *end)
4078 const unsigned char *s = contents, *beg, *str;
4079 unsigned char buffer[BUFSIZ];
4080 int width, height, x, y;
4081 int num_colors, chars_per_pixel;
4082 ptrdiff_t len;
4083 int LA1;
4084 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4085 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
4086 Lisp_Object frame, color_symbols, color_table;
4087 int best_key;
4088 bool have_mask = false;
4089 XImagePtr ximg = NULL, mask_img = NULL;
4091 #define match() \
4092 LA1 = xpm_scan (&s, end, &beg, &len)
4094 #define expect(TOKEN) \
4095 do \
4097 if (LA1 != (TOKEN)) \
4098 goto failure; \
4099 match (); \
4101 while (0)
4103 #define expect_ident(IDENT) \
4104 if (LA1 == XPM_TK_IDENT \
4105 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4106 match (); \
4107 else \
4108 goto failure
4110 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4111 goto failure;
4112 s += 9;
4113 match ();
4114 expect_ident ("static");
4115 expect_ident ("char");
4116 expect ('*');
4117 expect (XPM_TK_IDENT);
4118 expect ('[');
4119 expect (']');
4120 expect ('=');
4121 expect ('{');
4122 expect (XPM_TK_STRING);
4123 if (len >= BUFSIZ)
4124 goto failure;
4125 memcpy (buffer, beg, len);
4126 buffer[len] = '\0';
4127 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4128 &num_colors, &chars_per_pixel) != 4
4129 || width <= 0 || height <= 0
4130 || num_colors <= 0 || chars_per_pixel <= 0)
4131 goto failure;
4133 if (!check_image_size (f, width, height))
4135 image_size_error ();
4136 goto failure;
4139 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4140 #ifndef HAVE_NS
4141 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4142 &mask_img, 1)
4143 #endif
4146 image_error ("Image too large");
4147 goto failure;
4150 expect (',');
4152 XSETFRAME (frame, f);
4153 if (!NILP (Fxw_display_color_p (frame)))
4154 best_key = XPM_COLOR_KEY_C;
4155 else if (!NILP (Fx_display_grayscale_p (frame)))
4156 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4157 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4158 else
4159 best_key = XPM_COLOR_KEY_M;
4161 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4162 if (chars_per_pixel == 1)
4163 color_table = xpm_make_color_table_v (&put_color_table,
4164 &get_color_table);
4165 else
4166 color_table = xpm_make_color_table_h (&put_color_table,
4167 &get_color_table);
4169 while (num_colors-- > 0)
4171 char *color, *max_color;
4172 int key, next_key, max_key = 0;
4173 Lisp_Object symbol_color = Qnil, color_val;
4174 XColor cdef;
4176 expect (XPM_TK_STRING);
4177 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4178 goto failure;
4179 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4180 buffer[len - chars_per_pixel] = '\0';
4182 str = strtok (buffer, " \t");
4183 if (str == NULL)
4184 goto failure;
4185 key = xpm_str_to_color_key (str);
4186 if (key < 0)
4187 goto failure;
4190 color = strtok (NULL, " \t");
4191 if (color == NULL)
4192 goto failure;
4194 while ((str = strtok (NULL, " \t")) != NULL)
4196 next_key = xpm_str_to_color_key (str);
4197 if (next_key >= 0)
4198 break;
4199 color[strlen (color)] = ' ';
4202 if (key == XPM_COLOR_KEY_S)
4204 if (NILP (symbol_color))
4205 symbol_color = build_string (color);
4207 else if (max_key < key && key <= best_key)
4209 max_key = key;
4210 max_color = color;
4212 key = next_key;
4214 while (str);
4216 color_val = Qnil;
4217 if (!NILP (color_symbols) && !NILP (symbol_color))
4219 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4221 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4223 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4224 color_val = Qt;
4225 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4226 &cdef, 0))
4227 color_val = make_number (cdef.pixel);
4230 if (NILP (color_val) && max_key > 0)
4232 if (xstrcasecmp (max_color, "None") == 0)
4233 color_val = Qt;
4234 else if (x_defined_color (f, max_color, &cdef, 0))
4235 color_val = make_number (cdef.pixel);
4237 if (!NILP (color_val))
4238 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4240 expect (',');
4243 for (y = 0; y < height; y++)
4245 expect (XPM_TK_STRING);
4246 str = beg;
4247 if (len < width * chars_per_pixel)
4248 goto failure;
4249 for (x = 0; x < width; x++, str += chars_per_pixel)
4251 Lisp_Object color_val =
4252 (*get_color_table) (color_table, str, chars_per_pixel);
4254 XPutPixel (ximg, x, y,
4255 (INTEGERP (color_val) ? XINT (color_val)
4256 : FRAME_FOREGROUND_PIXEL (f)));
4257 #ifndef HAVE_NS
4258 XPutPixel (mask_img, x, y,
4259 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4260 : (have_mask = true, PIX_MASK_RETAIN)));
4261 #else
4262 if (EQ (color_val, Qt))
4263 ns_set_alpha (ximg, x, y, 0);
4264 #endif
4266 if (y + 1 < height)
4267 expect (',');
4270 img->width = width;
4271 img->height = height;
4273 /* Maybe fill in the background field while we have ximg handy. */
4274 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4275 IMAGE_BACKGROUND (img, f, ximg);
4277 image_put_x_image (f, img, ximg, 0);
4278 #ifndef HAVE_NS
4279 if (have_mask)
4281 /* Fill in the background_transparent field while we have the
4282 mask handy. */
4283 image_background_transparent (img, f, mask_img);
4285 image_put_x_image (f, img, mask_img, 1);
4287 else
4289 x_destroy_x_image (mask_img);
4290 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4292 #endif
4293 return 1;
4295 failure:
4296 image_error ("Invalid XPM file (%s)", img->spec);
4297 x_destroy_x_image (ximg);
4298 x_destroy_x_image (mask_img);
4299 x_clear_image (f, img);
4300 return 0;
4302 #undef match
4303 #undef expect
4304 #undef expect_ident
4307 static bool
4308 xpm_load (struct frame *f,
4309 struct image *img)
4311 bool success_p = 0;
4312 Lisp_Object file_name;
4314 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4315 file_name = image_spec_value (img->spec, QCfile, NULL);
4316 if (STRINGP (file_name))
4318 int fd;
4319 Lisp_Object file = x_find_image_fd (file_name, &fd);
4320 if (!STRINGP (file))
4322 image_error ("Cannot find image file `%s'", file_name);
4323 return 0;
4326 ptrdiff_t size;
4327 unsigned char *contents = slurp_file (fd, &size);
4328 if (contents == NULL)
4330 image_error ("Error loading XPM image `%s'", file);
4331 return 0;
4334 success_p = xpm_load_image (f, img, contents, contents + size);
4335 xfree (contents);
4337 else
4339 Lisp_Object data;
4341 data = image_spec_value (img->spec, QCdata, NULL);
4342 if (!STRINGP (data))
4344 image_error ("Invalid image data `%s'", data);
4345 return 0;
4347 success_p = xpm_load_image (f, img, SDATA (data),
4348 SDATA (data) + SBYTES (data));
4351 return success_p;
4354 #endif /* HAVE_NS && !HAVE_XPM */
4358 /***********************************************************************
4359 Color table
4360 ***********************************************************************/
4362 #ifdef COLOR_TABLE_SUPPORT
4364 /* An entry in the color table mapping an RGB color to a pixel color. */
4366 struct ct_color
4368 int r, g, b;
4369 unsigned long pixel;
4371 /* Next in color table collision list. */
4372 struct ct_color *next;
4375 /* The bucket vector size to use. Must be prime. */
4377 #define CT_SIZE 101
4379 /* Value is a hash of the RGB color given by R, G, and B. */
4381 static unsigned
4382 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4384 return (r << 16) ^ (g << 8) ^ b;
4387 /* The color hash table. */
4389 static struct ct_color **ct_table;
4391 /* Number of entries in the color table. */
4393 static int ct_colors_allocated;
4394 enum
4396 ct_colors_allocated_max =
4397 min (INT_MAX,
4398 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4401 /* Initialize the color table. */
4403 static void
4404 init_color_table (void)
4406 int size = CT_SIZE * sizeof (*ct_table);
4407 ct_table = xzalloc (size);
4408 ct_colors_allocated = 0;
4412 /* Free memory associated with the color table. */
4414 static void
4415 free_color_table (void)
4417 int i;
4418 struct ct_color *p, *next;
4420 for (i = 0; i < CT_SIZE; ++i)
4421 for (p = ct_table[i]; p; p = next)
4423 next = p->next;
4424 xfree (p);
4427 xfree (ct_table);
4428 ct_table = NULL;
4432 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4433 entry for that color already is in the color table, return the
4434 pixel color of that entry. Otherwise, allocate a new color for R,
4435 G, B, and make an entry in the color table. */
4437 static unsigned long
4438 lookup_rgb_color (struct frame *f, int r, int g, int b)
4440 unsigned hash = ct_hash_rgb (r, g, b);
4441 int i = hash % CT_SIZE;
4442 struct ct_color *p;
4443 Display_Info *dpyinfo;
4445 /* Handle TrueColor visuals specially, which improves performance by
4446 two orders of magnitude. Freeing colors on TrueColor visuals is
4447 a nop, and pixel colors specify RGB values directly. See also
4448 the Xlib spec, chapter 3.1. */
4449 dpyinfo = FRAME_DISPLAY_INFO (f);
4450 if (dpyinfo->red_bits > 0)
4452 /* Apply gamma-correction like normal color allocation does. */
4453 if (f->gamma)
4455 XColor color;
4456 color.red = r, color.green = g, color.blue = b;
4457 gamma_correct (f, &color);
4458 r = color.red, g = color.green, b = color.blue;
4461 return x_make_truecolor_pixel (dpyinfo, r, g, b);
4464 for (p = ct_table[i]; p; p = p->next)
4465 if (p->r == r && p->g == g && p->b == b)
4466 break;
4468 if (p == NULL)
4471 #ifdef HAVE_X_WINDOWS
4472 XColor color;
4473 Colormap cmap;
4474 bool rc;
4475 #else
4476 COLORREF color;
4477 #endif
4479 if (ct_colors_allocated_max <= ct_colors_allocated)
4480 return FRAME_FOREGROUND_PIXEL (f);
4482 #ifdef HAVE_X_WINDOWS
4483 color.red = r;
4484 color.green = g;
4485 color.blue = b;
4487 cmap = FRAME_X_COLORMAP (f);
4488 rc = x_alloc_nearest_color (f, cmap, &color);
4489 if (rc)
4491 ++ct_colors_allocated;
4492 p = xmalloc (sizeof *p);
4493 p->r = r;
4494 p->g = g;
4495 p->b = b;
4496 p->pixel = color.pixel;
4497 p->next = ct_table[i];
4498 ct_table[i] = p;
4500 else
4501 return FRAME_FOREGROUND_PIXEL (f);
4503 #else
4504 #ifdef HAVE_NTGUI
4505 color = PALETTERGB (r, g, b);
4506 #else
4507 color = RGB_TO_ULONG (r, g, b);
4508 #endif /* HAVE_NTGUI */
4509 ++ct_colors_allocated;
4510 p = xmalloc (sizeof *p);
4511 p->r = r;
4512 p->g = g;
4513 p->b = b;
4514 p->pixel = color;
4515 p->next = ct_table[i];
4516 ct_table[i] = p;
4517 #endif /* HAVE_X_WINDOWS */
4521 return p->pixel;
4525 /* Look up pixel color PIXEL which is used on frame F in the color
4526 table. If not already present, allocate it. Value is PIXEL. */
4528 static unsigned long
4529 lookup_pixel_color (struct frame *f, unsigned long pixel)
4531 int i = pixel % CT_SIZE;
4532 struct ct_color *p;
4534 for (p = ct_table[i]; p; p = p->next)
4535 if (p->pixel == pixel)
4536 break;
4538 if (p == NULL)
4540 XColor color;
4541 Colormap cmap;
4542 bool rc;
4544 if (ct_colors_allocated >= ct_colors_allocated_max)
4545 return FRAME_FOREGROUND_PIXEL (f);
4547 #ifdef HAVE_X_WINDOWS
4548 cmap = FRAME_X_COLORMAP (f);
4549 color.pixel = pixel;
4550 x_query_color (f, &color);
4551 rc = x_alloc_nearest_color (f, cmap, &color);
4552 #else
4553 block_input ();
4554 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4555 color.pixel = pixel;
4556 XQueryColor (NULL, cmap, &color);
4557 rc = x_alloc_nearest_color (f, cmap, &color);
4558 unblock_input ();
4559 #endif /* HAVE_X_WINDOWS */
4561 if (rc)
4563 ++ct_colors_allocated;
4565 p = xmalloc (sizeof *p);
4566 p->r = color.red;
4567 p->g = color.green;
4568 p->b = color.blue;
4569 p->pixel = pixel;
4570 p->next = ct_table[i];
4571 ct_table[i] = p;
4573 else
4574 return FRAME_FOREGROUND_PIXEL (f);
4576 return p->pixel;
4580 /* Value is a vector of all pixel colors contained in the color table,
4581 allocated via xmalloc. Set *N to the number of colors. */
4583 static unsigned long *
4584 colors_in_color_table (int *n)
4586 int i, j;
4587 struct ct_color *p;
4588 unsigned long *colors;
4590 if (ct_colors_allocated == 0)
4592 *n = 0;
4593 colors = NULL;
4595 else
4597 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4598 *n = ct_colors_allocated;
4600 for (i = j = 0; i < CT_SIZE; ++i)
4601 for (p = ct_table[i]; p; p = p->next)
4602 colors[j++] = p->pixel;
4605 return colors;
4608 #else /* COLOR_TABLE_SUPPORT */
4610 static unsigned long
4611 lookup_rgb_color (struct frame *f, int r, int g, int b)
4613 #ifdef HAVE_NTGUI
4614 return PALETTERGB (r >> 8, g >> 8, b >> 8);
4615 #elif defined HAVE_NS
4616 return RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4617 #else
4618 xsignal1 (Qfile_error,
4619 build_string ("This Emacs mishandles this image file type"));
4620 #endif
4623 static void
4624 init_color_table (void)
4627 #endif /* COLOR_TABLE_SUPPORT */
4630 /***********************************************************************
4631 Algorithms
4632 ***********************************************************************/
4634 /* Edge detection matrices for different edge-detection
4635 strategies. */
4637 static int emboss_matrix[9] = {
4638 /* x - 1 x x + 1 */
4639 2, -1, 0, /* y - 1 */
4640 -1, 0, 1, /* y */
4641 0, 1, -2 /* y + 1 */
4644 static int laplace_matrix[9] = {
4645 /* x - 1 x x + 1 */
4646 1, 0, 0, /* y - 1 */
4647 0, 0, 0, /* y */
4648 0, 0, -1 /* y + 1 */
4651 /* Value is the intensity of the color whose red/green/blue values
4652 are R, G, and B. */
4654 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4657 /* On frame F, return an array of XColor structures describing image
4658 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4659 means also fill the red/green/blue members of the XColor
4660 structures. Value is a pointer to the array of XColors structures,
4661 allocated with xmalloc; it must be freed by the caller. */
4663 static XColor *
4664 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4666 int x, y;
4667 XColor *colors, *p;
4668 XImagePtr_or_DC ximg;
4669 ptrdiff_t nbytes;
4670 #ifdef HAVE_NTGUI
4671 HGDIOBJ prev;
4672 #endif /* HAVE_NTGUI */
4674 if (INT_MULTIPLY_WRAPV (sizeof *colors, img->width, &nbytes)
4675 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes)
4676 || SIZE_MAX < nbytes)
4677 memory_full (SIZE_MAX);
4678 colors = xmalloc (nbytes);
4680 /* Get the X image or create a memory device context for IMG. */
4681 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4683 /* Fill the `pixel' members of the XColor array. I wished there
4684 were an easy and portable way to circumvent XGetPixel. */
4685 p = colors;
4686 for (y = 0; y < img->height; ++y)
4688 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4689 XColor *row = p;
4690 for (x = 0; x < img->width; ++x, ++p)
4691 p->pixel = GET_PIXEL (ximg, x, y);
4692 if (rgb_p)
4693 x_query_colors (f, row, img->width);
4695 #else
4697 for (x = 0; x < img->width; ++x, ++p)
4699 /* W32_TODO: palette support needed here? */
4700 p->pixel = GET_PIXEL (ximg, x, y);
4701 if (rgb_p)
4703 p->red = RED16_FROM_ULONG (p->pixel);
4704 p->green = GREEN16_FROM_ULONG (p->pixel);
4705 p->blue = BLUE16_FROM_ULONG (p->pixel);
4708 #endif /* HAVE_X_WINDOWS */
4711 image_unget_x_image_or_dc (img, 0, ximg, prev);
4713 return colors;
4716 #ifdef HAVE_NTGUI
4718 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4719 created with CreateDIBSection, with the pointer to the bit values
4720 stored in ximg->data. */
4722 static void
4723 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4725 int width = ximg->info.bmiHeader.biWidth;
4726 unsigned char * pixel;
4728 /* True color images. */
4729 if (ximg->info.bmiHeader.biBitCount == 24)
4731 int rowbytes = width * 3;
4732 /* Ensure scanlines are aligned on 4 byte boundaries. */
4733 if (rowbytes % 4)
4734 rowbytes += 4 - (rowbytes % 4);
4736 pixel = ximg->data + y * rowbytes + x * 3;
4737 /* Windows bitmaps are in BGR order. */
4738 *pixel = GetBValue (color);
4739 *(pixel + 1) = GetGValue (color);
4740 *(pixel + 2) = GetRValue (color);
4742 /* Monochrome images. */
4743 else if (ximg->info.bmiHeader.biBitCount == 1)
4745 int rowbytes = width / 8;
4746 /* Ensure scanlines are aligned on 4 byte boundaries. */
4747 if (rowbytes % 4)
4748 rowbytes += 4 - (rowbytes % 4);
4749 pixel = ximg->data + y * rowbytes + x / 8;
4750 /* Filter out palette info. */
4751 if (color & 0x00ffffff)
4752 *pixel = *pixel | (1 << x % 8);
4753 else
4754 *pixel = *pixel & ~(1 << x % 8);
4756 else
4757 image_error ("XPutPixel: palette image not supported");
4760 #endif /* HAVE_NTGUI */
4762 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4763 RGB members are set. F is the frame on which this all happens.
4764 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4766 static void
4767 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4769 int x, y;
4770 XImagePtr oimg = NULL;
4771 XColor *p;
4773 init_color_table ();
4775 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4776 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4777 &oimg, 0);
4778 p = colors;
4779 for (y = 0; y < img->height; ++y)
4780 for (x = 0; x < img->width; ++x, ++p)
4782 unsigned long pixel;
4783 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4784 XPutPixel (oimg, x, y, pixel);
4787 xfree (colors);
4789 image_put_x_image (f, img, oimg, 0);
4790 #ifdef COLOR_TABLE_SUPPORT
4791 img->colors = colors_in_color_table (&img->ncolors);
4792 free_color_table ();
4793 #endif /* COLOR_TABLE_SUPPORT */
4797 /* On frame F, perform edge-detection on image IMG.
4799 MATRIX is a nine-element array specifying the transformation
4800 matrix. See emboss_matrix for an example.
4802 COLOR_ADJUST is a color adjustment added to each pixel of the
4803 outgoing image. */
4805 static void
4806 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4808 XColor *colors = x_to_xcolors (f, img, 1);
4809 XColor *new, *p;
4810 int x, y, i, sum;
4811 ptrdiff_t nbytes;
4813 for (i = sum = 0; i < 9; ++i)
4814 sum += eabs (matrix[i]);
4816 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4818 if (INT_MULTIPLY_WRAPV (sizeof *new, img->width, &nbytes)
4819 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes))
4820 memory_full (SIZE_MAX);
4821 new = xmalloc (nbytes);
4823 for (y = 0; y < img->height; ++y)
4825 p = COLOR (new, 0, y);
4826 p->red = p->green = p->blue = 0xffff/2;
4827 p = COLOR (new, img->width - 1, y);
4828 p->red = p->green = p->blue = 0xffff/2;
4831 for (x = 1; x < img->width - 1; ++x)
4833 p = COLOR (new, x, 0);
4834 p->red = p->green = p->blue = 0xffff/2;
4835 p = COLOR (new, x, img->height - 1);
4836 p->red = p->green = p->blue = 0xffff/2;
4839 for (y = 1; y < img->height - 1; ++y)
4841 p = COLOR (new, 1, y);
4843 for (x = 1; x < img->width - 1; ++x, ++p)
4845 int r, g, b, yy, xx;
4847 r = g = b = i = 0;
4848 for (yy = y - 1; yy < y + 2; ++yy)
4849 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4850 if (matrix[i])
4852 XColor *t = COLOR (colors, xx, yy);
4853 r += matrix[i] * t->red;
4854 g += matrix[i] * t->green;
4855 b += matrix[i] * t->blue;
4858 r = (r / sum + color_adjust) & 0xffff;
4859 g = (g / sum + color_adjust) & 0xffff;
4860 b = (b / sum + color_adjust) & 0xffff;
4861 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4865 xfree (colors);
4866 x_from_xcolors (f, img, new);
4868 #undef COLOR
4872 /* Perform the pre-defined `emboss' edge-detection on image IMG
4873 on frame F. */
4875 static void
4876 x_emboss (struct frame *f, struct image *img)
4878 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4882 /* Transform image IMG which is used on frame F with a Laplace
4883 edge-detection algorithm. The result is an image that can be used
4884 to draw disabled buttons, for example. */
4886 static void
4887 x_laplace (struct frame *f, struct image *img)
4889 x_detect_edges (f, img, laplace_matrix, 45000);
4893 /* Perform edge-detection on image IMG on frame F, with specified
4894 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4896 MATRIX must be either
4898 - a list of at least 9 numbers in row-major form
4899 - a vector of at least 9 numbers
4901 COLOR_ADJUST nil means use a default; otherwise it must be a
4902 number. */
4904 static void
4905 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4906 Lisp_Object color_adjust)
4908 int i = 0;
4909 int trans[9];
4911 if (CONSP (matrix))
4913 for (i = 0;
4914 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4915 ++i, matrix = XCDR (matrix))
4916 trans[i] = XFLOATINT (XCAR (matrix));
4918 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4920 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4921 trans[i] = XFLOATINT (AREF (matrix, i));
4924 if (NILP (color_adjust))
4925 color_adjust = make_number (0xffff / 2);
4927 if (i == 9 && NUMBERP (color_adjust))
4928 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4932 /* Transform image IMG on frame F so that it looks disabled. */
4934 static void
4935 x_disable_image (struct frame *f, struct image *img)
4937 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4938 #ifdef HAVE_NTGUI
4939 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4940 #else
4941 int n_planes = dpyinfo->n_planes;
4942 #endif /* HAVE_NTGUI */
4944 if (n_planes >= 2)
4946 /* Color (or grayscale). Convert to gray, and equalize. Just
4947 drawing such images with a stipple can look very odd, so
4948 we're using this method instead. */
4949 XColor *colors = x_to_xcolors (f, img, 1);
4950 XColor *p, *end;
4951 const int h = 15000;
4952 const int l = 30000;
4954 for (p = colors, end = colors + img->width * img->height;
4955 p < end;
4956 ++p)
4958 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4959 int i2 = (0xffff - h - l) * i / 0xffff + l;
4960 p->red = p->green = p->blue = i2;
4963 x_from_xcolors (f, img, colors);
4966 /* Draw a cross over the disabled image, if we must or if we
4967 should. */
4968 if (n_planes < 2 || cross_disabled_images)
4970 #ifndef HAVE_NTGUI
4971 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4973 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4975 Display *dpy = FRAME_X_DISPLAY (f);
4976 GC gc;
4978 image_sync_to_pixmaps (f, img);
4979 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4980 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4981 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4982 img->width - 1, img->height - 1);
4983 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4984 img->width - 1, 0);
4985 XFreeGC (dpy, gc);
4987 if (img->mask)
4989 gc = XCreateGC (dpy, img->mask, 0, NULL);
4990 XSetForeground (dpy, gc, MaskForeground (f));
4991 XDrawLine (dpy, img->mask, gc, 0, 0,
4992 img->width - 1, img->height - 1);
4993 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4994 img->width - 1, 0);
4995 XFreeGC (dpy, gc);
4997 #endif /* !HAVE_NS */
4998 #else
4999 HDC hdc, bmpdc;
5000 HGDIOBJ prev;
5002 hdc = get_frame_dc (f);
5003 bmpdc = CreateCompatibleDC (hdc);
5004 release_frame_dc (f, hdc);
5006 prev = SelectObject (bmpdc, img->pixmap);
5008 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5009 MoveToEx (bmpdc, 0, 0, NULL);
5010 LineTo (bmpdc, img->width - 1, img->height - 1);
5011 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5012 LineTo (bmpdc, img->width - 1, 0);
5014 if (img->mask)
5016 SelectObject (bmpdc, img->mask);
5017 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5018 MoveToEx (bmpdc, 0, 0, NULL);
5019 LineTo (bmpdc, img->width - 1, img->height - 1);
5020 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5021 LineTo (bmpdc, img->width - 1, 0);
5023 SelectObject (bmpdc, prev);
5024 DeleteDC (bmpdc);
5025 #endif /* HAVE_NTGUI */
5030 /* Build a mask for image IMG which is used on frame F. FILE is the
5031 name of an image file, for error messages. HOW determines how to
5032 determine the background color of IMG. If it is a list '(R G B)',
5033 with R, G, and B being integers >= 0, take that as the color of the
5034 background. Otherwise, determine the background color of IMG
5035 heuristically. */
5037 static void
5038 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
5040 XImagePtr_or_DC ximg;
5041 #ifndef HAVE_NTGUI
5042 XImagePtr mask_img;
5043 #else
5044 HGDIOBJ prev;
5045 char *mask_img;
5046 int row_width;
5047 #endif /* HAVE_NTGUI */
5048 int x, y;
5049 bool use_img_background;
5050 unsigned long bg = 0;
5052 if (img->mask)
5053 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
5055 #ifndef HAVE_NTGUI
5056 #ifndef HAVE_NS
5057 /* Create an image and pixmap serving as mask. */
5058 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
5059 &mask_img, 1))
5060 return;
5061 #endif /* !HAVE_NS */
5062 #else
5063 /* Create the bit array serving as mask. */
5064 row_width = (img->width + 7) / 8;
5065 mask_img = xzalloc (row_width * img->height);
5066 #endif /* HAVE_NTGUI */
5068 /* Get the X image or create a memory device context for IMG. */
5069 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
5071 /* Determine the background color of ximg. If HOW is `(R G B)'
5072 take that as color. Otherwise, use the image's background color. */
5073 use_img_background = 1;
5075 if (CONSP (how))
5077 int rgb[3], i;
5079 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5081 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5082 how = XCDR (how);
5085 if (i == 3 && NILP (how))
5087 char color_name[30];
5088 sprintf (color_name, "#%04x%04x%04x",
5089 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
5090 bg = (
5091 #ifdef HAVE_NTGUI
5092 0x00ffffff & /* Filter out palette info. */
5093 #endif /* HAVE_NTGUI */
5094 x_alloc_image_color (f, img, build_string (color_name), 0));
5095 use_img_background = 0;
5099 if (use_img_background)
5100 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5102 /* Set all bits in mask_img to 1 whose color in ximg is different
5103 from the background color bg. */
5104 #ifndef HAVE_NTGUI
5105 for (y = 0; y < img->height; ++y)
5106 for (x = 0; x < img->width; ++x)
5107 #ifndef HAVE_NS
5108 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5109 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5110 #else
5111 if (XGetPixel (ximg, x, y) == bg)
5112 ns_set_alpha (ximg, x, y, 0);
5113 #endif /* HAVE_NS */
5114 #ifndef HAVE_NS
5115 /* Fill in the background_transparent field while we have the mask handy. */
5116 image_background_transparent (img, f, mask_img);
5118 /* Put mask_img into the image. */
5119 image_put_x_image (f, img, mask_img, 1);
5120 #endif /* !HAVE_NS */
5121 #else
5122 for (y = 0; y < img->height; ++y)
5123 for (x = 0; x < img->width; ++x)
5125 COLORREF p = GetPixel (ximg, x, y);
5126 if (p != bg)
5127 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5130 /* Create the mask image. */
5131 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5132 mask_img);
5133 /* Fill in the background_transparent field while we have the mask handy. */
5134 SelectObject (ximg, img->mask);
5135 image_background_transparent (img, f, ximg);
5137 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5138 xfree (mask_img);
5139 #endif /* HAVE_NTGUI */
5141 image_unget_x_image_or_dc (img, 0, ximg, prev);
5145 /***********************************************************************
5146 PBM (mono, gray, color)
5147 ***********************************************************************/
5149 static bool pbm_image_p (Lisp_Object object);
5150 static bool pbm_load (struct frame *f, struct image *img);
5152 /* Indices of image specification fields in gs_format, below. */
5154 enum pbm_keyword_index
5156 PBM_TYPE,
5157 PBM_FILE,
5158 PBM_DATA,
5159 PBM_ASCENT,
5160 PBM_MARGIN,
5161 PBM_RELIEF,
5162 PBM_ALGORITHM,
5163 PBM_HEURISTIC_MASK,
5164 PBM_MASK,
5165 PBM_FOREGROUND,
5166 PBM_BACKGROUND,
5167 PBM_LAST
5170 /* Vector of image_keyword structures describing the format
5171 of valid user-defined image specifications. */
5173 static const struct image_keyword pbm_format[PBM_LAST] =
5175 {":type", IMAGE_SYMBOL_VALUE, 1},
5176 {":file", IMAGE_STRING_VALUE, 0},
5177 {":data", IMAGE_STRING_VALUE, 0},
5178 {":ascent", IMAGE_ASCENT_VALUE, 0},
5179 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5180 {":relief", IMAGE_INTEGER_VALUE, 0},
5181 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5182 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5183 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5184 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5185 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5188 /* Structure describing the image type `pbm'. */
5190 static struct image_type pbm_type =
5192 SYMBOL_INDEX (Qpbm),
5193 pbm_image_p,
5194 pbm_load,
5195 x_clear_image,
5196 NULL,
5197 NULL
5201 /* Return true if OBJECT is a valid PBM image specification. */
5203 static bool
5204 pbm_image_p (Lisp_Object object)
5206 struct image_keyword fmt[PBM_LAST];
5208 memcpy (fmt, pbm_format, sizeof fmt);
5210 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5211 return 0;
5213 /* Must specify either :data or :file. */
5214 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5218 /* Get next char skipping comments in Netpbm header. Returns -1 at
5219 end of input. */
5221 static int
5222 pbm_next_char (unsigned char **s, unsigned char *end)
5224 int c = -1;
5226 while (*s < end && (c = *(*s)++, c == '#'))
5228 /* Skip to the next line break. */
5229 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5232 c = -1;
5235 return c;
5239 /* Scan a decimal number from *S and return it. Advance *S while
5240 reading the number. END is the end of the string. Value is -1 at
5241 end of input. */
5243 static int
5244 pbm_scan_number (unsigned char **s, unsigned char *end)
5246 int c = 0, val = -1;
5248 /* Skip white-space. */
5249 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5252 if (c_isdigit (c))
5254 /* Read decimal number. */
5255 val = c - '0';
5256 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5257 val = 10 * val + c - '0';
5260 return val;
5264 /* Load PBM image IMG for use on frame F. */
5266 static bool
5267 pbm_load (struct frame *f, struct image *img)
5269 bool raw_p;
5270 int x, y;
5271 int width, height, max_color_idx = 0;
5272 Lisp_Object specified_file;
5273 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5274 unsigned char *contents = NULL;
5275 unsigned char *end, *p;
5276 #ifdef USE_CAIRO
5277 unsigned char *data = 0;
5278 uint32_t *dataptr;
5279 #else
5280 XImagePtr ximg;
5281 #endif
5283 specified_file = image_spec_value (img->spec, QCfile, NULL);
5285 if (STRINGP (specified_file))
5287 int fd;
5288 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5289 if (!STRINGP (file))
5291 image_error ("Cannot find image file `%s'", specified_file);
5292 return 0;
5295 ptrdiff_t size;
5296 contents = slurp_file (fd, &size);
5297 if (contents == NULL)
5299 image_error ("Error reading `%s'", file);
5300 return 0;
5303 p = contents;
5304 end = contents + size;
5306 else
5308 Lisp_Object data;
5309 data = image_spec_value (img->spec, QCdata, NULL);
5310 if (!STRINGP (data))
5312 image_error ("Invalid image data `%s'", data);
5313 return 0;
5315 p = SDATA (data);
5316 end = p + SBYTES (data);
5319 /* Check magic number. */
5320 if (end - p < 2 || *p++ != 'P')
5322 image_error ("Not a PBM image: `%s'", img->spec);
5323 error:
5324 xfree (contents);
5325 img->pixmap = NO_PIXMAP;
5326 return 0;
5329 switch (*p++)
5331 case '1':
5332 raw_p = 0, type = PBM_MONO;
5333 break;
5335 case '2':
5336 raw_p = 0, type = PBM_GRAY;
5337 break;
5339 case '3':
5340 raw_p = 0, type = PBM_COLOR;
5341 break;
5343 case '4':
5344 raw_p = 1, type = PBM_MONO;
5345 break;
5347 case '5':
5348 raw_p = 1, type = PBM_GRAY;
5349 break;
5351 case '6':
5352 raw_p = 1, type = PBM_COLOR;
5353 break;
5355 default:
5356 image_error ("Not a PBM image: `%s'", img->spec);
5357 goto error;
5360 /* Read width, height, maximum color-component. Characters
5361 starting with `#' up to the end of a line are ignored. */
5362 width = pbm_scan_number (&p, end);
5363 height = pbm_scan_number (&p, end);
5365 #ifdef USE_CAIRO
5366 data = (unsigned char *) xmalloc (width * height * 4);
5367 dataptr = (uint32_t *) data;
5368 #endif
5370 if (type != PBM_MONO)
5372 max_color_idx = pbm_scan_number (&p, end);
5373 if (max_color_idx > 65535 || max_color_idx < 0)
5375 image_error ("Unsupported maximum PBM color value");
5376 goto error;
5380 if (!check_image_size (f, width, height))
5382 image_size_error ();
5383 goto error;
5386 #ifndef USE_CAIRO
5387 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5388 goto error;
5389 #endif
5391 /* Initialize the color hash table. */
5392 init_color_table ();
5394 if (type == PBM_MONO)
5396 int c = 0, g;
5397 struct image_keyword fmt[PBM_LAST];
5398 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5399 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5400 #ifdef USE_CAIRO
5401 XColor xfg, xbg;
5402 int fga32, bga32;
5403 #endif
5404 /* Parse the image specification. */
5405 memcpy (fmt, pbm_format, sizeof fmt);
5406 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5408 /* Get foreground and background colors, maybe allocate colors. */
5409 #ifdef USE_CAIRO
5410 if (! fmt[PBM_FOREGROUND].count
5411 || ! STRINGP (fmt[PBM_FOREGROUND].value)
5412 || ! x_defined_color (f, SSDATA (fmt[PBM_FOREGROUND].value), &xfg, 0))
5414 xfg.pixel = fg;
5415 x_query_color (f, &xfg);
5417 fga32 = xcolor_to_argb32 (xfg);
5419 if (! fmt[PBM_BACKGROUND].count
5420 || ! STRINGP (fmt[PBM_BACKGROUND].value)
5421 || ! x_defined_color (f, SSDATA (fmt[PBM_BACKGROUND].value), &xbg, 0))
5423 xbg.pixel = bg;
5424 x_query_color (f, &xbg);
5426 bga32 = xcolor_to_argb32 (xbg);
5427 #else
5428 if (fmt[PBM_FOREGROUND].count
5429 && STRINGP (fmt[PBM_FOREGROUND].value))
5430 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5431 if (fmt[PBM_BACKGROUND].count
5432 && STRINGP (fmt[PBM_BACKGROUND].value))
5434 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5435 img->background = bg;
5436 img->background_valid = 1;
5438 #endif
5440 for (y = 0; y < height; ++y)
5441 for (x = 0; x < width; ++x)
5443 if (raw_p)
5445 if ((x & 7) == 0)
5447 if (p >= end)
5449 #ifdef USE_CAIRO
5450 xfree (data);
5451 #else
5452 x_destroy_x_image (ximg);
5453 #endif
5454 x_clear_image (f, img);
5455 image_error ("Invalid image size in image `%s'",
5456 img->spec);
5457 goto error;
5459 c = *p++;
5461 g = c & 0x80;
5462 c <<= 1;
5464 else
5465 g = pbm_scan_number (&p, end);
5467 #ifdef USE_CAIRO
5468 *dataptr++ = g ? fga32 : bga32;
5469 #else
5470 XPutPixel (ximg, x, y, g ? fg : bg);
5471 #endif
5474 else
5476 int expected_size = height * width;
5477 if (max_color_idx > 255)
5478 expected_size *= 2;
5479 if (type == PBM_COLOR)
5480 expected_size *= 3;
5482 if (raw_p && p + expected_size > end)
5484 #ifdef USE_CAIRO
5485 xfree (data);
5486 #else
5487 x_destroy_x_image (ximg);
5488 #endif
5489 x_clear_image (f, img);
5490 image_error ("Invalid image size in image `%s'", img->spec);
5491 goto error;
5494 for (y = 0; y < height; ++y)
5495 for (x = 0; x < width; ++x)
5497 int r, g, b;
5499 if (type == PBM_GRAY && raw_p)
5501 r = g = b = *p++;
5502 if (max_color_idx > 255)
5503 r = g = b = r * 256 + *p++;
5505 else if (type == PBM_GRAY)
5506 r = g = b = pbm_scan_number (&p, end);
5507 else if (raw_p)
5509 r = *p++;
5510 if (max_color_idx > 255)
5511 r = r * 256 + *p++;
5512 g = *p++;
5513 if (max_color_idx > 255)
5514 g = g * 256 + *p++;
5515 b = *p++;
5516 if (max_color_idx > 255)
5517 b = b * 256 + *p++;
5519 else
5521 r = pbm_scan_number (&p, end);
5522 g = pbm_scan_number (&p, end);
5523 b = pbm_scan_number (&p, end);
5526 if (r < 0 || g < 0 || b < 0)
5528 #ifdef USE_CAIRO
5529 xfree (data);
5530 #else
5531 x_destroy_x_image (ximg);
5532 #endif
5533 image_error ("Invalid pixel value in image `%s'", img->spec);
5534 goto error;
5537 #ifdef USE_CAIRO
5538 r = (double) r * 255 / max_color_idx;
5539 g = (double) g * 255 / max_color_idx;
5540 b = (double) b * 255 / max_color_idx;
5541 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
5542 #else
5543 /* RGB values are now in the range 0..max_color_idx.
5544 Scale this to the range 0..0xffff supported by X. */
5545 r = (double) r * 65535 / max_color_idx;
5546 g = (double) g * 65535 / max_color_idx;
5547 b = (double) b * 65535 / max_color_idx;
5548 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5549 #endif
5553 #ifdef COLOR_TABLE_SUPPORT
5554 /* Store in IMG->colors the colors allocated for the image, and
5555 free the color table. */
5556 img->colors = colors_in_color_table (&img->ncolors);
5557 free_color_table ();
5558 #endif /* COLOR_TABLE_SUPPORT */
5560 img->width = width;
5561 img->height = height;
5563 /* Maybe fill in the background field while we have ximg handy. */
5565 #ifdef USE_CAIRO
5566 create_cairo_image_surface (img, data, width, height);
5567 #else
5568 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5569 /* Casting avoids a GCC warning. */
5570 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5572 /* Put ximg into the image. */
5573 image_put_x_image (f, img, ximg, 0);
5574 #endif
5576 /* X and W32 versions did it here, MAC version above. ++kfs
5577 img->width = width;
5578 img->height = height; */
5580 xfree (contents);
5581 return 1;
5585 /***********************************************************************
5587 ***********************************************************************/
5589 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5591 /* Function prototypes. */
5593 static bool png_image_p (Lisp_Object object);
5594 static bool png_load (struct frame *f, struct image *img);
5596 /* Indices of image specification fields in png_format, below. */
5598 enum png_keyword_index
5600 PNG_TYPE,
5601 PNG_DATA,
5602 PNG_FILE,
5603 PNG_ASCENT,
5604 PNG_MARGIN,
5605 PNG_RELIEF,
5606 PNG_ALGORITHM,
5607 PNG_HEURISTIC_MASK,
5608 PNG_MASK,
5609 PNG_BACKGROUND,
5610 PNG_LAST
5613 /* Vector of image_keyword structures describing the format
5614 of valid user-defined image specifications. */
5616 static const struct image_keyword png_format[PNG_LAST] =
5618 {":type", IMAGE_SYMBOL_VALUE, 1},
5619 {":data", IMAGE_STRING_VALUE, 0},
5620 {":file", IMAGE_STRING_VALUE, 0},
5621 {":ascent", IMAGE_ASCENT_VALUE, 0},
5622 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5623 {":relief", IMAGE_INTEGER_VALUE, 0},
5624 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5625 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5626 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5627 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5630 #if defined HAVE_NTGUI && defined WINDOWSNT
5631 static bool init_png_functions (void);
5632 #else
5633 #define init_png_functions NULL
5634 #endif
5636 /* Structure describing the image type `png'. */
5638 static struct image_type png_type =
5640 SYMBOL_INDEX (Qpng),
5641 png_image_p,
5642 png_load,
5643 x_clear_image,
5644 init_png_functions,
5645 NULL
5648 /* Return true if OBJECT is a valid PNG image specification. */
5650 static bool
5651 png_image_p (Lisp_Object object)
5653 struct image_keyword fmt[PNG_LAST];
5654 memcpy (fmt, png_format, sizeof fmt);
5656 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5657 return 0;
5659 /* Must specify either the :data or :file keyword. */
5660 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5663 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5666 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5668 # ifdef WINDOWSNT
5669 /* PNG library details. */
5671 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5672 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5673 DEF_DLL_FN (png_structp, png_create_read_struct,
5674 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5675 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5676 DEF_DLL_FN (void, png_destroy_read_struct,
5677 (png_structpp, png_infopp, png_infopp));
5678 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5679 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5680 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5681 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5682 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5683 int *, int *, int *, int *, int *));
5684 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5685 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5686 DEF_DLL_FN (void, png_set_expand, (png_structp));
5687 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5688 DEF_DLL_FN (void, png_set_background,
5689 (png_structp, png_color_16p, int, int, double));
5690 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5691 (png_structp, png_infop, png_color_16p *));
5692 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5693 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5694 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5695 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5696 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5697 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5699 # if (PNG_LIBPNG_VER >= 10500)
5700 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5701 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5702 (png_structp, png_longjmp_ptr, size_t));
5703 # endif /* libpng version >= 1.5 */
5705 static bool
5706 init_png_functions (void)
5708 HMODULE library;
5710 if (!(library = w32_delayed_load (Qpng)))
5711 return 0;
5713 LOAD_DLL_FN (library, png_get_io_ptr);
5714 LOAD_DLL_FN (library, png_sig_cmp);
5715 LOAD_DLL_FN (library, png_create_read_struct);
5716 LOAD_DLL_FN (library, png_create_info_struct);
5717 LOAD_DLL_FN (library, png_destroy_read_struct);
5718 LOAD_DLL_FN (library, png_set_read_fn);
5719 LOAD_DLL_FN (library, png_set_sig_bytes);
5720 LOAD_DLL_FN (library, png_read_info);
5721 LOAD_DLL_FN (library, png_get_IHDR);
5722 LOAD_DLL_FN (library, png_get_valid);
5723 LOAD_DLL_FN (library, png_set_strip_16);
5724 LOAD_DLL_FN (library, png_set_expand);
5725 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5726 LOAD_DLL_FN (library, png_set_background);
5727 LOAD_DLL_FN (library, png_get_bKGD);
5728 LOAD_DLL_FN (library, png_read_update_info);
5729 LOAD_DLL_FN (library, png_get_channels);
5730 LOAD_DLL_FN (library, png_get_rowbytes);
5731 LOAD_DLL_FN (library, png_read_image);
5732 LOAD_DLL_FN (library, png_read_end);
5733 LOAD_DLL_FN (library, png_error);
5735 # if (PNG_LIBPNG_VER >= 10500)
5736 LOAD_DLL_FN (library, png_longjmp);
5737 LOAD_DLL_FN (library, png_set_longjmp_fn);
5738 # endif /* libpng version >= 1.5 */
5740 return 1;
5743 # undef png_create_info_struct
5744 # undef png_create_read_struct
5745 # undef png_destroy_read_struct
5746 # undef png_error
5747 # undef png_get_bKGD
5748 # undef png_get_channels
5749 # undef png_get_IHDR
5750 # undef png_get_io_ptr
5751 # undef png_get_rowbytes
5752 # undef png_get_valid
5753 # undef png_longjmp
5754 # undef png_read_end
5755 # undef png_read_image
5756 # undef png_read_info
5757 # undef png_read_update_info
5758 # undef png_set_background
5759 # undef png_set_expand
5760 # undef png_set_gray_to_rgb
5761 # undef png_set_longjmp_fn
5762 # undef png_set_read_fn
5763 # undef png_set_sig_bytes
5764 # undef png_set_strip_16
5765 # undef png_sig_cmp
5767 # define png_create_info_struct fn_png_create_info_struct
5768 # define png_create_read_struct fn_png_create_read_struct
5769 # define png_destroy_read_struct fn_png_destroy_read_struct
5770 # define png_error fn_png_error
5771 # define png_get_bKGD fn_png_get_bKGD
5772 # define png_get_channels fn_png_get_channels
5773 # define png_get_IHDR fn_png_get_IHDR
5774 # define png_get_io_ptr fn_png_get_io_ptr
5775 # define png_get_rowbytes fn_png_get_rowbytes
5776 # define png_get_valid fn_png_get_valid
5777 # define png_longjmp fn_png_longjmp
5778 # define png_read_end fn_png_read_end
5779 # define png_read_image fn_png_read_image
5780 # define png_read_info fn_png_read_info
5781 # define png_read_update_info fn_png_read_update_info
5782 # define png_set_background fn_png_set_background
5783 # define png_set_expand fn_png_set_expand
5784 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5785 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5786 # define png_set_read_fn fn_png_set_read_fn
5787 # define png_set_sig_bytes fn_png_set_sig_bytes
5788 # define png_set_strip_16 fn_png_set_strip_16
5789 # define png_sig_cmp fn_png_sig_cmp
5791 # endif /* WINDOWSNT */
5793 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5794 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5795 Do not use sys_setjmp, as PNG supports only jmp_buf.
5796 It's OK if the longjmp substitute restores the signal mask. */
5797 # ifdef HAVE__SETJMP
5798 # define FAST_SETJMP(j) _setjmp (j)
5799 # define FAST_LONGJMP _longjmp
5800 # else
5801 # define FAST_SETJMP(j) setjmp (j)
5802 # define FAST_LONGJMP longjmp
5803 # endif
5805 # if PNG_LIBPNG_VER < 10500
5806 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5807 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5808 # else
5809 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5810 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5811 # define PNG_JMPBUF(ptr) \
5812 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5813 # endif
5815 /* Error and warning handlers installed when the PNG library
5816 is initialized. */
5818 static _Noreturn void
5819 my_png_error (png_struct *png_ptr, const char *msg)
5821 eassert (png_ptr != NULL);
5822 /* Avoid compiler warning about deprecated direct access to
5823 png_ptr's fields in libpng versions 1.4.x. */
5824 image_error ("PNG error: %s", build_string (msg));
5825 PNG_LONGJMP (png_ptr);
5829 static void
5830 my_png_warning (png_struct *png_ptr, const char *msg)
5832 eassert (png_ptr != NULL);
5833 image_error ("PNG warning: %s", build_string (msg));
5836 /* Memory source for PNG decoding. */
5838 struct png_memory_storage
5840 unsigned char *bytes; /* The data */
5841 ptrdiff_t len; /* How big is it? */
5842 ptrdiff_t index; /* Where are we? */
5846 /* Function set as reader function when reading PNG image from memory.
5847 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5848 bytes from the input to DATA. */
5850 static void
5851 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5853 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5855 if (length > tbr->len - tbr->index)
5856 png_error (png_ptr, "Read error");
5858 memcpy (data, tbr->bytes + tbr->index, length);
5859 tbr->index = tbr->index + length;
5863 /* Function set as reader function when reading PNG image from a file.
5864 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5865 bytes from the input to DATA. */
5867 static void
5868 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5870 FILE *fp = png_get_io_ptr (png_ptr);
5872 if (fread (data, 1, length, fp) < length)
5873 png_error (png_ptr, "Read error");
5877 /* Load PNG image IMG for use on frame F. Value is true if
5878 successful. */
5880 struct png_load_context
5882 /* These are members so that longjmp doesn't munge local variables. */
5883 png_struct *png_ptr;
5884 png_info *info_ptr;
5885 png_info *end_info;
5886 FILE *fp;
5887 png_byte *pixels;
5888 png_byte **rows;
5891 static bool
5892 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5894 Lisp_Object specified_file;
5895 Lisp_Object specified_data;
5896 int x, y;
5897 ptrdiff_t i;
5898 png_struct *png_ptr;
5899 png_info *info_ptr = NULL, *end_info = NULL;
5900 FILE *fp = NULL;
5901 png_byte sig[8];
5902 png_byte *pixels = NULL;
5903 png_byte **rows = NULL;
5904 png_uint_32 width, height;
5905 int bit_depth, color_type, interlace_type;
5906 png_byte channels;
5907 png_uint_32 row_bytes;
5908 bool transparent_p;
5909 struct png_memory_storage tbr; /* Data to be read */
5910 ptrdiff_t nbytes;
5912 #ifdef USE_CAIRO
5913 unsigned char *data = 0;
5914 uint32_t *dataptr;
5915 #else
5916 XImagePtr ximg, mask_img = NULL;
5917 #endif
5919 /* Find out what file to load. */
5920 specified_file = image_spec_value (img->spec, QCfile, NULL);
5921 specified_data = image_spec_value (img->spec, QCdata, NULL);
5922 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
5924 if (NILP (specified_data))
5926 int fd;
5927 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5928 if (!STRINGP (file))
5930 image_error ("Cannot find image file `%s'", specified_file);
5931 return 0;
5934 /* Open the image file. */
5935 fp = fdopen (fd, "rb");
5936 if (!fp)
5938 image_error ("Cannot open image file `%s'", file);
5939 return 0;
5942 /* Check PNG signature. */
5943 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5944 || png_sig_cmp (sig, 0, sizeof sig))
5946 fclose (fp);
5947 image_error ("Not a PNG file: `%s'", file);
5948 return 0;
5951 else
5953 if (!STRINGP (specified_data))
5955 image_error ("Invalid image data `%s'", specified_data);
5956 return 0;
5959 /* Read from memory. */
5960 tbr.bytes = SDATA (specified_data);
5961 tbr.len = SBYTES (specified_data);
5962 tbr.index = 0;
5964 /* Check PNG signature. */
5965 if (tbr.len < sizeof sig
5966 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5968 image_error ("Not a PNG image: `%s'", img->spec);
5969 return 0;
5972 /* Need to skip past the signature. */
5973 tbr.bytes += sizeof (sig);
5976 /* Initialize read and info structs for PNG lib. */
5977 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5978 NULL, my_png_error,
5979 my_png_warning);
5980 if (png_ptr)
5982 info_ptr = png_create_info_struct (png_ptr);
5983 end_info = png_create_info_struct (png_ptr);
5986 c->png_ptr = png_ptr;
5987 c->info_ptr = info_ptr;
5988 c->end_info = end_info;
5989 c->fp = fp;
5990 c->pixels = pixels;
5991 c->rows = rows;
5993 if (! (info_ptr && end_info))
5995 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5996 png_ptr = 0;
5998 if (! png_ptr)
6000 if (fp) fclose (fp);
6001 return 0;
6004 /* Set error jump-back. We come back here when the PNG library
6005 detects an error. */
6006 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
6008 error:
6009 if (c->png_ptr)
6010 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6011 xfree (c->pixels);
6012 xfree (c->rows);
6013 if (c->fp)
6014 fclose (c->fp);
6015 return 0;
6018 /* Silence a bogus diagnostic; see GCC bug 54561. */
6019 IF_LINT (fp = c->fp);
6020 IF_LINT (specified_data = specified_data_volatile);
6022 /* Read image info. */
6023 if (!NILP (specified_data))
6024 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
6025 else
6026 png_set_read_fn (png_ptr, fp, png_read_from_file);
6028 png_set_sig_bytes (png_ptr, sizeof sig);
6029 png_read_info (png_ptr, info_ptr);
6030 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6031 &interlace_type, NULL, NULL);
6033 if (! (width <= INT_MAX && height <= INT_MAX
6034 && check_image_size (f, width, height)))
6036 image_size_error ();
6037 goto error;
6040 #ifndef USE_CAIRO
6041 /* Create the X image and pixmap now, so that the work below can be
6042 omitted if the image is too large for X. */
6043 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6044 goto error;
6045 #endif
6047 /* If image contains simply transparency data, we prefer to
6048 construct a clipping mask. */
6049 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6050 transparent_p = 1;
6051 else
6052 transparent_p = 0;
6054 /* This function is easier to write if we only have to handle
6055 one data format: RGB or RGBA with 8 bits per channel. Let's
6056 transform other formats into that format. */
6058 /* Strip more than 8 bits per channel. */
6059 if (bit_depth == 16)
6060 png_set_strip_16 (png_ptr);
6062 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6063 if available. */
6064 png_set_expand (png_ptr);
6066 /* Convert grayscale images to RGB. */
6067 if (color_type == PNG_COLOR_TYPE_GRAY
6068 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6069 png_set_gray_to_rgb (png_ptr);
6071 /* Handle alpha channel by combining the image with a background
6072 color. Do this only if a real alpha channel is supplied. For
6073 simple transparency, we prefer a clipping mask. */
6074 if (!transparent_p)
6076 /* png_color_16 *image_bg; */
6077 Lisp_Object specified_bg
6078 = image_spec_value (img->spec, QCbackground, NULL);
6079 XColor color;
6081 /* If the user specified a color, try to use it; if not, use the
6082 current frame background, ignoring any default background
6083 color set by the image. */
6084 if (STRINGP (specified_bg)
6085 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
6086 : (x_query_frame_background_color (f, &color), true))
6087 /* The user specified `:background', use that. */
6089 int shift = bit_depth == 16 ? 0 : 8;
6090 png_color_16 bg = { 0 };
6091 bg.red = color.red >> shift;
6092 bg.green = color.green >> shift;
6093 bg.blue = color.blue >> shift;
6095 png_set_background (png_ptr, &bg,
6096 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6100 /* Update info structure. */
6101 png_read_update_info (png_ptr, info_ptr);
6103 /* Get number of channels. Valid values are 1 for grayscale images
6104 and images with a palette, 2 for grayscale images with transparency
6105 information (alpha channel), 3 for RGB images, and 4 for RGB
6106 images with alpha channel, i.e. RGBA. If conversions above were
6107 sufficient we should only have 3 or 4 channels here. */
6108 channels = png_get_channels (png_ptr, info_ptr);
6109 eassert (channels == 3 || channels == 4);
6111 /* Number of bytes needed for one row of the image. */
6112 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
6114 /* Allocate memory for the image. */
6115 if (INT_MULTIPLY_WRAPV (row_bytes, sizeof *pixels, &nbytes)
6116 || INT_MULTIPLY_WRAPV (nbytes, height, &nbytes))
6117 memory_full (SIZE_MAX);
6118 c->pixels = pixels = xmalloc (nbytes);
6119 c->rows = rows = xmalloc (height * sizeof *rows);
6120 for (i = 0; i < height; ++i)
6121 rows[i] = pixels + i * row_bytes;
6123 /* Read the entire image. */
6124 png_read_image (png_ptr, rows);
6125 png_read_end (png_ptr, info_ptr);
6126 if (fp)
6128 fclose (fp);
6129 c->fp = NULL;
6132 #ifdef USE_CAIRO
6133 data = (unsigned char *) xmalloc (width * height * 4);
6134 dataptr = (uint32_t *) data;
6135 #else
6136 /* Create an image and pixmap serving as mask if the PNG image
6137 contains an alpha channel. */
6138 if (channels == 4
6139 && !transparent_p
6140 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
6141 &mask_img, 1))
6143 x_destroy_x_image (ximg);
6144 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
6145 goto error;
6147 #endif
6149 /* Fill the X image and mask from PNG data. */
6150 init_color_table ();
6152 for (y = 0; y < height; ++y)
6154 png_byte *p = rows[y];
6156 for (x = 0; x < width; ++x)
6158 int r, g, b;
6160 #ifdef USE_CAIRO
6161 int a = 0xff;
6162 r = *p++;
6163 g = *p++;
6164 b = *p++;
6165 if (channels == 4) a = *p++;
6166 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
6167 #else
6168 r = *p++ << 8;
6169 g = *p++ << 8;
6170 b = *p++ << 8;
6171 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6172 /* An alpha channel, aka mask channel, associates variable
6173 transparency with an image. Where other image formats
6174 support binary transparency---fully transparent or fully
6175 opaque---PNG allows up to 254 levels of partial transparency.
6176 The PNG library implements partial transparency by combining
6177 the image with a specified background color.
6179 I'm not sure how to handle this here nicely: because the
6180 background on which the image is displayed may change, for
6181 real alpha channel support, it would be necessary to create
6182 a new image for each possible background.
6184 What I'm doing now is that a mask is created if we have
6185 boolean transparency information. Otherwise I'm using
6186 the frame's background color to combine the image with. */
6188 if (channels == 4)
6190 if (mask_img)
6191 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6192 ++p;
6194 #endif
6198 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6199 /* Set IMG's background color from the PNG image, unless the user
6200 overrode it. */
6202 png_color_16 *bg;
6203 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6205 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6206 img->background_valid = 1;
6210 # ifdef COLOR_TABLE_SUPPORT
6211 /* Remember colors allocated for this image. */
6212 img->colors = colors_in_color_table (&img->ncolors);
6213 free_color_table ();
6214 # endif /* COLOR_TABLE_SUPPORT */
6216 /* Clean up. */
6217 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6218 xfree (rows);
6219 xfree (pixels);
6221 img->width = width;
6222 img->height = height;
6224 #ifdef USE_CAIRO
6225 create_cairo_image_surface (img, data, width, height);
6226 #else
6227 /* Maybe fill in the background field while we have ximg handy.
6228 Casting avoids a GCC warning. */
6229 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6231 /* Put ximg into the image. */
6232 image_put_x_image (f, img, ximg, 0);
6234 /* Same for the mask. */
6235 if (mask_img)
6237 /* Fill in the background_transparent field while we have the
6238 mask handy. Casting avoids a GCC warning. */
6239 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6241 image_put_x_image (f, img, mask_img, 1);
6243 #endif
6245 return 1;
6248 static bool
6249 png_load (struct frame *f, struct image *img)
6251 struct png_load_context c;
6252 return png_load_body (f, img, &c);
6255 #elif defined HAVE_NS
6257 static bool
6258 png_load (struct frame *f, struct image *img)
6260 return ns_load_image (f, img,
6261 image_spec_value (img->spec, QCfile, NULL),
6262 image_spec_value (img->spec, QCdata, NULL));
6266 #endif /* HAVE_NS */
6270 /***********************************************************************
6271 JPEG
6272 ***********************************************************************/
6274 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6276 static bool jpeg_image_p (Lisp_Object object);
6277 static bool jpeg_load (struct frame *f, struct image *img);
6279 /* Indices of image specification fields in gs_format, below. */
6281 enum jpeg_keyword_index
6283 JPEG_TYPE,
6284 JPEG_DATA,
6285 JPEG_FILE,
6286 JPEG_ASCENT,
6287 JPEG_MARGIN,
6288 JPEG_RELIEF,
6289 JPEG_ALGORITHM,
6290 JPEG_HEURISTIC_MASK,
6291 JPEG_MASK,
6292 JPEG_BACKGROUND,
6293 JPEG_LAST
6296 /* Vector of image_keyword structures describing the format
6297 of valid user-defined image specifications. */
6299 static const struct image_keyword jpeg_format[JPEG_LAST] =
6301 {":type", IMAGE_SYMBOL_VALUE, 1},
6302 {":data", IMAGE_STRING_VALUE, 0},
6303 {":file", IMAGE_STRING_VALUE, 0},
6304 {":ascent", IMAGE_ASCENT_VALUE, 0},
6305 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6306 {":relief", IMAGE_INTEGER_VALUE, 0},
6307 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6308 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6309 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6310 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6313 #if defined HAVE_NTGUI && defined WINDOWSNT
6314 static bool init_jpeg_functions (void);
6315 #else
6316 #define init_jpeg_functions NULL
6317 #endif
6319 /* Structure describing the image type `jpeg'. */
6321 static struct image_type jpeg_type =
6323 SYMBOL_INDEX (Qjpeg),
6324 jpeg_image_p,
6325 jpeg_load,
6326 x_clear_image,
6327 init_jpeg_functions,
6328 NULL
6331 /* Return true if OBJECT is a valid JPEG image specification. */
6333 static bool
6334 jpeg_image_p (Lisp_Object object)
6336 struct image_keyword fmt[JPEG_LAST];
6338 memcpy (fmt, jpeg_format, sizeof fmt);
6340 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6341 return 0;
6343 /* Must specify either the :data or :file keyword. */
6344 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6347 #endif /* HAVE_JPEG || HAVE_NS */
6349 #ifdef HAVE_JPEG
6351 /* Work around a warning about HAVE_STDLIB_H being redefined in
6352 jconfig.h. */
6353 # ifdef HAVE_STDLIB_H
6354 # undef HAVE_STDLIB_H
6355 # endif
6357 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6358 /* In older releases of the jpeg library, jpeglib.h will define boolean
6359 differently depending on __WIN32__, so make sure it is defined. */
6360 # define __WIN32__ 1
6361 # endif
6363 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6364 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6365 using the Windows boolean type instead of the jpeglib boolean type
6366 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6367 headers are included along with windows.h, so under Cygwin, jpeglib
6368 attempts to define a conflicting boolean type. Worse, forcing
6369 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6370 because it created an ABI incompatibility between the
6371 already-compiled jpeg library and the header interface definition.
6373 The best we can do is to define jpeglib's boolean type to a
6374 different name. This name, jpeg_boolean, remains in effect through
6375 the rest of image.c.
6377 # if defined CYGWIN && defined HAVE_NTGUI
6378 # define boolean jpeg_boolean
6379 # endif
6380 # include <jpeglib.h>
6381 # include <jerror.h>
6383 # ifdef WINDOWSNT
6385 /* JPEG library details. */
6386 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6387 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6388 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6389 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6390 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6391 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6392 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6393 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6394 (struct jpeg_error_mgr *));
6395 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6397 static bool
6398 init_jpeg_functions (void)
6400 HMODULE library;
6402 if (!(library = w32_delayed_load (Qjpeg)))
6403 return 0;
6405 LOAD_DLL_FN (library, jpeg_finish_decompress);
6406 LOAD_DLL_FN (library, jpeg_read_scanlines);
6407 LOAD_DLL_FN (library, jpeg_start_decompress);
6408 LOAD_DLL_FN (library, jpeg_read_header);
6409 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6410 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6411 LOAD_DLL_FN (library, jpeg_std_error);
6412 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6413 return 1;
6416 # undef jpeg_CreateDecompress
6417 # undef jpeg_destroy_decompress
6418 # undef jpeg_finish_decompress
6419 # undef jpeg_read_header
6420 # undef jpeg_read_scanlines
6421 # undef jpeg_resync_to_restart
6422 # undef jpeg_start_decompress
6423 # undef jpeg_std_error
6425 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6426 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6427 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6428 # define jpeg_read_header fn_jpeg_read_header
6429 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6430 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6431 # define jpeg_start_decompress fn_jpeg_start_decompress
6432 # define jpeg_std_error fn_jpeg_std_error
6434 /* Wrapper since we can't directly assign the function pointer
6435 to another function pointer that was declared more completely easily. */
6436 static boolean
6437 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6439 return jpeg_resync_to_restart (cinfo, desired);
6441 # undef jpeg_resync_to_restart
6442 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6444 # endif /* WINDOWSNT */
6446 struct my_jpeg_error_mgr
6448 struct jpeg_error_mgr pub;
6449 sys_jmp_buf setjmp_buffer;
6451 /* The remaining members are so that longjmp doesn't munge local
6452 variables. */
6453 struct jpeg_decompress_struct cinfo;
6454 enum
6456 MY_JPEG_ERROR_EXIT,
6457 MY_JPEG_INVALID_IMAGE_SIZE,
6458 MY_JPEG_CANNOT_CREATE_X
6459 } failure_code;
6463 static _Noreturn void
6464 my_error_exit (j_common_ptr cinfo)
6466 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6467 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6468 sys_longjmp (mgr->setjmp_buffer, 1);
6472 /* Init source method for JPEG data source manager. Called by
6473 jpeg_read_header() before any data is actually read. See
6474 libjpeg.doc from the JPEG lib distribution. */
6476 static void
6477 our_common_init_source (j_decompress_ptr cinfo)
6482 /* Method to terminate data source. Called by
6483 jpeg_finish_decompress() after all data has been processed. */
6485 static void
6486 our_common_term_source (j_decompress_ptr cinfo)
6491 /* Fill input buffer method for JPEG data source manager. Called
6492 whenever more data is needed. We read the whole image in one step,
6493 so this only adds a fake end of input marker at the end. */
6495 static JOCTET our_memory_buffer[2];
6497 static boolean
6498 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6500 /* Insert a fake EOI marker. */
6501 struct jpeg_source_mgr *src = cinfo->src;
6503 our_memory_buffer[0] = (JOCTET) 0xFF;
6504 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6506 src->next_input_byte = our_memory_buffer;
6507 src->bytes_in_buffer = 2;
6508 return 1;
6512 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6513 is the JPEG data source manager. */
6515 static void
6516 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6518 struct jpeg_source_mgr *src = cinfo->src;
6520 if (src)
6522 if (num_bytes > src->bytes_in_buffer)
6523 ERREXIT (cinfo, JERR_INPUT_EOF);
6525 src->bytes_in_buffer -= num_bytes;
6526 src->next_input_byte += num_bytes;
6531 /* Set up the JPEG lib for reading an image from DATA which contains
6532 LEN bytes. CINFO is the decompression info structure created for
6533 reading the image. */
6535 static void
6536 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6538 struct jpeg_source_mgr *src = cinfo->src;
6540 if (! src)
6542 /* First time for this JPEG object? */
6543 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6544 JPOOL_PERMANENT, sizeof *src);
6545 cinfo->src = src;
6546 src->next_input_byte = data;
6549 src->init_source = our_common_init_source;
6550 src->fill_input_buffer = our_memory_fill_input_buffer;
6551 src->skip_input_data = our_memory_skip_input_data;
6552 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6553 src->term_source = our_common_term_source;
6554 src->bytes_in_buffer = len;
6555 src->next_input_byte = data;
6559 struct jpeg_stdio_mgr
6561 struct jpeg_source_mgr mgr;
6562 boolean finished;
6563 FILE *file;
6564 JOCTET *buffer;
6568 /* Size of buffer to read JPEG from file.
6569 Not too big, as we want to use alloc_small. */
6570 #define JPEG_STDIO_BUFFER_SIZE 8192
6573 /* Fill input buffer method for JPEG data source manager. Called
6574 whenever more data is needed. The data is read from a FILE *. */
6576 static boolean
6577 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6579 struct jpeg_stdio_mgr *src;
6581 src = (struct jpeg_stdio_mgr *) cinfo->src;
6582 if (!src->finished)
6584 ptrdiff_t bytes;
6586 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6587 if (bytes > 0)
6588 src->mgr.bytes_in_buffer = bytes;
6589 else
6591 WARNMS (cinfo, JWRN_JPEG_EOF);
6592 src->finished = 1;
6593 src->buffer[0] = (JOCTET) 0xFF;
6594 src->buffer[1] = (JOCTET) JPEG_EOI;
6595 src->mgr.bytes_in_buffer = 2;
6597 src->mgr.next_input_byte = src->buffer;
6600 return 1;
6604 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6605 is the JPEG data source manager. */
6607 static void
6608 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6610 struct jpeg_stdio_mgr *src;
6611 src = (struct jpeg_stdio_mgr *) cinfo->src;
6613 while (num_bytes > 0 && !src->finished)
6615 if (num_bytes <= src->mgr.bytes_in_buffer)
6617 src->mgr.bytes_in_buffer -= num_bytes;
6618 src->mgr.next_input_byte += num_bytes;
6619 break;
6621 else
6623 num_bytes -= src->mgr.bytes_in_buffer;
6624 src->mgr.bytes_in_buffer = 0;
6625 src->mgr.next_input_byte = NULL;
6627 our_stdio_fill_input_buffer (cinfo);
6633 /* Set up the JPEG lib for reading an image from a FILE *.
6634 CINFO is the decompression info structure created for
6635 reading the image. */
6637 static void
6638 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6640 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6642 if (! src)
6644 /* First time for this JPEG object? */
6645 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6646 JPOOL_PERMANENT, sizeof *src);
6647 cinfo->src = (struct jpeg_source_mgr *) src;
6648 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6649 JPOOL_PERMANENT,
6650 JPEG_STDIO_BUFFER_SIZE);
6653 src->file = fp;
6654 src->finished = 0;
6655 src->mgr.init_source = our_common_init_source;
6656 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6657 src->mgr.skip_input_data = our_stdio_skip_input_data;
6658 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6659 src->mgr.term_source = our_common_term_source;
6660 src->mgr.bytes_in_buffer = 0;
6661 src->mgr.next_input_byte = NULL;
6664 /* Load image IMG for use on frame F. Patterned after example.c
6665 from the JPEG lib. */
6667 static bool
6668 jpeg_load_body (struct frame *f, struct image *img,
6669 struct my_jpeg_error_mgr *mgr)
6671 Lisp_Object specified_file;
6672 Lisp_Object specified_data;
6673 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6674 FILE * IF_LINT (volatile) fp = NULL;
6675 JSAMPARRAY buffer;
6676 int row_stride, x, y;
6677 unsigned long *colors;
6678 int width, height;
6679 int i, ir, ig, ib;
6680 #ifndef USE_CAIRO
6681 XImagePtr ximg = NULL;
6682 #endif
6684 /* Open the JPEG file. */
6685 specified_file = image_spec_value (img->spec, QCfile, NULL);
6686 specified_data = image_spec_value (img->spec, QCdata, NULL);
6687 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
6689 if (NILP (specified_data))
6691 int fd;
6692 Lisp_Object file = x_find_image_fd (specified_file, &fd);
6693 if (!STRINGP (file))
6695 image_error ("Cannot find image file `%s'", specified_file);
6696 return 0;
6699 fp = fdopen (fd, "rb");
6700 if (fp == NULL)
6702 image_error ("Cannot open `%s'", file);
6703 return 0;
6706 else if (!STRINGP (specified_data))
6708 image_error ("Invalid image data `%s'", specified_data);
6709 return 0;
6712 /* Customize libjpeg's error handling to call my_error_exit when an
6713 error is detected. This function will perform a longjmp. */
6714 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6715 mgr->pub.error_exit = my_error_exit;
6716 if (sys_setjmp (mgr->setjmp_buffer))
6718 switch (mgr->failure_code)
6720 case MY_JPEG_ERROR_EXIT:
6722 char buf[JMSG_LENGTH_MAX];
6723 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6724 image_error ("Error reading JPEG image `%s': %s",
6725 img->spec, build_string (buf));
6726 break;
6729 case MY_JPEG_INVALID_IMAGE_SIZE:
6730 image_size_error ();
6731 break;
6733 case MY_JPEG_CANNOT_CREATE_X:
6734 break;
6737 /* Close the input file and destroy the JPEG object. */
6738 if (fp)
6739 fclose (fp);
6740 jpeg_destroy_decompress (&mgr->cinfo);
6742 /* If we already have an XImage, free that. */
6743 #ifndef USE_CAIRO
6744 x_destroy_x_image (ximg);
6745 #endif
6746 /* Free pixmap and colors. */
6747 x_clear_image (f, img);
6748 return 0;
6751 /* Silence a bogus diagnostic; see GCC bug 54561. */
6752 IF_LINT (specified_data = specified_data_volatile);
6754 /* Create the JPEG decompression object. Let it read from fp.
6755 Read the JPEG image header. */
6756 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6758 if (NILP (specified_data))
6759 jpeg_file_src (&mgr->cinfo, fp);
6760 else
6761 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6762 SBYTES (specified_data));
6764 jpeg_read_header (&mgr->cinfo, 1);
6766 /* Customize decompression so that color quantization will be used.
6767 Start decompression. */
6768 mgr->cinfo.quantize_colors = 1;
6769 jpeg_start_decompress (&mgr->cinfo);
6770 width = img->width = mgr->cinfo.output_width;
6771 height = img->height = mgr->cinfo.output_height;
6773 if (!check_image_size (f, width, height))
6775 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6776 sys_longjmp (mgr->setjmp_buffer, 1);
6779 #ifndef USE_CAIRO
6780 /* Create X image and pixmap. */
6781 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6783 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6784 sys_longjmp (mgr->setjmp_buffer, 1);
6786 #endif
6788 /* Allocate colors. When color quantization is used,
6789 mgr->cinfo.actual_number_of_colors has been set with the number of
6790 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6791 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6792 No more than 255 colors will be generated. */
6793 USE_SAFE_ALLOCA;
6795 if (mgr->cinfo.out_color_components > 2)
6796 ir = 0, ig = 1, ib = 2;
6797 else if (mgr->cinfo.out_color_components > 1)
6798 ir = 0, ig = 1, ib = 0;
6799 else
6800 ir = 0, ig = 0, ib = 0;
6802 #ifndef CAIRO
6803 /* Use the color table mechanism because it handles colors that
6804 cannot be allocated nicely. Such colors will be replaced with
6805 a default color, and we don't have to care about which colors
6806 can be freed safely, and which can't. */
6807 init_color_table ();
6808 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6810 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6812 /* Multiply RGB values with 255 because X expects RGB values
6813 in the range 0..0xffff. */
6814 int r = mgr->cinfo.colormap[ir][i] << 8;
6815 int g = mgr->cinfo.colormap[ig][i] << 8;
6816 int b = mgr->cinfo.colormap[ib][i] << 8;
6817 colors[i] = lookup_rgb_color (f, r, g, b);
6819 #endif
6821 #ifdef COLOR_TABLE_SUPPORT
6822 /* Remember those colors actually allocated. */
6823 img->colors = colors_in_color_table (&img->ncolors);
6824 free_color_table ();
6825 #endif /* COLOR_TABLE_SUPPORT */
6828 /* Read pixels. */
6829 row_stride = width * mgr->cinfo.output_components;
6830 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6831 JPOOL_IMAGE, row_stride, 1);
6832 #ifdef USE_CAIRO
6834 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
6835 uint32_t *dataptr = (uint32_t *) data;
6836 int r, g, b;
6838 for (y = 0; y < height; ++y)
6840 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6842 for (x = 0; x < width; ++x)
6844 i = buffer[0][x];
6845 r = mgr->cinfo.colormap[ir][i];
6846 g = mgr->cinfo.colormap[ig][i];
6847 b = mgr->cinfo.colormap[ib][i];
6848 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
6852 create_cairo_image_surface (img, data, width, height);
6854 #else
6855 for (y = 0; y < height; ++y)
6857 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6858 for (x = 0; x < mgr->cinfo.output_width; ++x)
6859 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6861 #endif
6863 /* Clean up. */
6864 jpeg_finish_decompress (&mgr->cinfo);
6865 jpeg_destroy_decompress (&mgr->cinfo);
6866 if (fp)
6867 fclose (fp);
6869 #ifndef USE_CAIRO
6870 /* Maybe fill in the background field while we have ximg handy. */
6871 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6872 /* Casting avoids a GCC warning. */
6873 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6875 /* Put ximg into the image. */
6876 image_put_x_image (f, img, ximg, 0);
6877 #endif
6878 SAFE_FREE ();
6879 return 1;
6882 static bool
6883 jpeg_load (struct frame *f, struct image *img)
6885 struct my_jpeg_error_mgr mgr;
6886 return jpeg_load_body (f, img, &mgr);
6889 #else /* HAVE_JPEG */
6891 #ifdef HAVE_NS
6892 static bool
6893 jpeg_load (struct frame *f, struct image *img)
6895 return ns_load_image (f, img,
6896 image_spec_value (img->spec, QCfile, NULL),
6897 image_spec_value (img->spec, QCdata, NULL));
6899 #endif /* HAVE_NS */
6901 #endif /* !HAVE_JPEG */
6905 /***********************************************************************
6906 TIFF
6907 ***********************************************************************/
6909 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6911 static bool tiff_image_p (Lisp_Object object);
6912 static bool tiff_load (struct frame *f, struct image *img);
6914 /* Indices of image specification fields in tiff_format, below. */
6916 enum tiff_keyword_index
6918 TIFF_TYPE,
6919 TIFF_DATA,
6920 TIFF_FILE,
6921 TIFF_ASCENT,
6922 TIFF_MARGIN,
6923 TIFF_RELIEF,
6924 TIFF_ALGORITHM,
6925 TIFF_HEURISTIC_MASK,
6926 TIFF_MASK,
6927 TIFF_BACKGROUND,
6928 TIFF_INDEX,
6929 TIFF_LAST
6932 /* Vector of image_keyword structures describing the format
6933 of valid user-defined image specifications. */
6935 static const struct image_keyword tiff_format[TIFF_LAST] =
6937 {":type", IMAGE_SYMBOL_VALUE, 1},
6938 {":data", IMAGE_STRING_VALUE, 0},
6939 {":file", IMAGE_STRING_VALUE, 0},
6940 {":ascent", IMAGE_ASCENT_VALUE, 0},
6941 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6942 {":relief", IMAGE_INTEGER_VALUE, 0},
6943 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6944 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6945 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6946 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6947 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6950 #if defined HAVE_NTGUI && defined WINDOWSNT
6951 static bool init_tiff_functions (void);
6952 #else
6953 #define init_tiff_functions NULL
6954 #endif
6956 /* Structure describing the image type `tiff'. */
6958 static struct image_type tiff_type =
6960 SYMBOL_INDEX (Qtiff),
6961 tiff_image_p,
6962 tiff_load,
6963 x_clear_image,
6964 init_tiff_functions,
6965 NULL
6968 /* Return true if OBJECT is a valid TIFF image specification. */
6970 static bool
6971 tiff_image_p (Lisp_Object object)
6973 struct image_keyword fmt[TIFF_LAST];
6974 memcpy (fmt, tiff_format, sizeof fmt);
6976 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6977 return 0;
6979 /* Must specify either the :data or :file keyword. */
6980 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6983 #endif /* HAVE_TIFF || HAVE_NS */
6985 #ifdef HAVE_TIFF
6987 # include <tiffio.h>
6989 # ifdef WINDOWSNT
6991 /* TIFF library details. */
6992 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6993 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6994 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
6995 DEF_DLL_FN (TIFF *, TIFFClientOpen,
6996 (const char *, const char *, thandle_t, TIFFReadWriteProc,
6997 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6998 TIFFMapFileProc, TIFFUnmapFileProc));
6999 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
7000 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
7001 DEF_DLL_FN (void, TIFFClose, (TIFF *));
7002 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
7004 static bool
7005 init_tiff_functions (void)
7007 HMODULE library;
7009 if (!(library = w32_delayed_load (Qtiff)))
7010 return 0;
7012 LOAD_DLL_FN (library, TIFFSetErrorHandler);
7013 LOAD_DLL_FN (library, TIFFSetWarningHandler);
7014 LOAD_DLL_FN (library, TIFFOpen);
7015 LOAD_DLL_FN (library, TIFFClientOpen);
7016 LOAD_DLL_FN (library, TIFFGetField);
7017 LOAD_DLL_FN (library, TIFFReadRGBAImage);
7018 LOAD_DLL_FN (library, TIFFClose);
7019 LOAD_DLL_FN (library, TIFFSetDirectory);
7020 return 1;
7023 # undef TIFFClientOpen
7024 # undef TIFFClose
7025 # undef TIFFGetField
7026 # undef TIFFOpen
7027 # undef TIFFReadRGBAImage
7028 # undef TIFFSetDirectory
7029 # undef TIFFSetErrorHandler
7030 # undef TIFFSetWarningHandler
7032 # define TIFFClientOpen fn_TIFFClientOpen
7033 # define TIFFClose fn_TIFFClose
7034 # define TIFFGetField fn_TIFFGetField
7035 # define TIFFOpen fn_TIFFOpen
7036 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7037 # define TIFFSetDirectory fn_TIFFSetDirectory
7038 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7039 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7041 # endif /* WINDOWSNT */
7044 /* Reading from a memory buffer for TIFF images Based on the PNG
7045 memory source, but we have to provide a lot of extra functions.
7046 Blah.
7048 We really only need to implement read and seek, but I am not
7049 convinced that the TIFF library is smart enough not to destroy
7050 itself if we only hand it the function pointers we need to
7051 override. */
7053 typedef struct
7055 unsigned char *bytes;
7056 ptrdiff_t len;
7057 ptrdiff_t index;
7059 tiff_memory_source;
7061 static tsize_t
7062 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7064 tiff_memory_source *src = (tiff_memory_source *) data;
7066 size = min (size, src->len - src->index);
7067 memcpy (buf, src->bytes + src->index, size);
7068 src->index += size;
7069 return size;
7072 static tsize_t
7073 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7075 return -1;
7078 static toff_t
7079 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
7081 tiff_memory_source *src = (tiff_memory_source *) data;
7082 ptrdiff_t idx;
7084 switch (whence)
7086 case SEEK_SET: /* Go from beginning of source. */
7087 idx = off;
7088 break;
7090 case SEEK_END: /* Go from end of source. */
7091 idx = src->len + off;
7092 break;
7094 case SEEK_CUR: /* Go from current position. */
7095 idx = src->index + off;
7096 break;
7098 default: /* Invalid `whence'. */
7099 return -1;
7102 if (idx > src->len || idx < 0)
7103 return -1;
7105 src->index = idx;
7106 return src->index;
7109 static int
7110 tiff_close_memory (thandle_t data)
7112 /* NOOP */
7113 return 0;
7116 static int
7117 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
7119 /* It is already _IN_ memory. */
7120 return 0;
7123 static void
7124 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
7126 /* We don't need to do this. */
7129 static toff_t
7130 tiff_size_of_memory (thandle_t data)
7132 return ((tiff_memory_source *) data)->len;
7135 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7136 compiler error compiling tiff_handler, see Bugzilla bug #17406
7137 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7138 this function as external works around that problem. */
7139 # if defined (__MINGW32__) && __GNUC__ == 3
7140 # define MINGW_STATIC
7141 # else
7142 # define MINGW_STATIC static
7143 # endif
7145 MINGW_STATIC void
7146 tiff_handler (const char *, const char *, const char *, va_list)
7147 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7148 MINGW_STATIC void
7149 tiff_handler (const char *log_format, const char *title,
7150 const char *format, va_list ap)
7152 /* doprnt is not suitable here, as TIFF handlers are called from
7153 libtiff and are passed arbitrary printf directives. Instead, use
7154 vsnprintf, taking care to be portable to nonstandard environments
7155 where vsnprintf returns -1 on buffer overflow. Since it's just a
7156 log entry, it's OK to truncate it. */
7157 char buf[4000];
7158 int len = vsnprintf (buf, sizeof buf, format, ap);
7159 add_to_log (log_format, build_string (title),
7160 make_string (buf, max (0, min (len, sizeof buf - 1))));
7162 # undef MINGW_STATIC
7164 static void tiff_error_handler (const char *, const char *, va_list)
7165 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7166 static void
7167 tiff_error_handler (const char *title, const char *format, va_list ap)
7169 tiff_handler ("TIFF error: %s %s", title, format, ap);
7173 static void tiff_warning_handler (const char *, const char *, va_list)
7174 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7175 static void
7176 tiff_warning_handler (const char *title, const char *format, va_list ap)
7178 tiff_handler ("TIFF warning: %s %s", title, format, ap);
7182 /* Load TIFF image IMG for use on frame F. Value is true if
7183 successful. */
7185 static bool
7186 tiff_load (struct frame *f, struct image *img)
7188 Lisp_Object specified_file;
7189 Lisp_Object specified_data;
7190 TIFF *tiff;
7191 int width, height, x, y, count;
7192 uint32 *buf;
7193 int rc;
7194 XImagePtr ximg;
7195 tiff_memory_source memsrc;
7196 Lisp_Object image;
7198 specified_file = image_spec_value (img->spec, QCfile, NULL);
7199 specified_data = image_spec_value (img->spec, QCdata, NULL);
7201 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
7202 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7204 if (NILP (specified_data))
7206 /* Read from a file */
7207 Lisp_Object file = x_find_image_file (specified_file);
7208 if (!STRINGP (file))
7210 image_error ("Cannot find image file `%s'", specified_file);
7211 return 0;
7214 Lisp_Object encoded_file = ENCODE_FILE (file);
7215 # ifdef WINDOWSNT
7216 encoded_file = ansi_encode_filename (encoded_file);
7217 # endif
7219 /* Try to open the image file. */
7220 tiff = TIFFOpen (SSDATA (encoded_file), "r");
7221 if (tiff == NULL)
7223 image_error ("Cannot open `%s'", file);
7224 return 0;
7227 else
7229 if (!STRINGP (specified_data))
7231 image_error ("Invalid image data `%s'", specified_data);
7232 return 0;
7235 /* Memory source! */
7236 memsrc.bytes = SDATA (specified_data);
7237 memsrc.len = SBYTES (specified_data);
7238 memsrc.index = 0;
7240 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7241 tiff_read_from_memory,
7242 tiff_write_from_memory,
7243 tiff_seek_in_memory,
7244 tiff_close_memory,
7245 tiff_size_of_memory,
7246 tiff_mmap_memory,
7247 tiff_unmap_memory);
7249 if (!tiff)
7251 image_error ("Cannot open memory source for `%s'", img->spec);
7252 return 0;
7256 image = image_spec_value (img->spec, QCindex, NULL);
7257 if (INTEGERP (image))
7259 EMACS_INT ino = XFASTINT (image);
7260 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7261 && TIFFSetDirectory (tiff, ino)))
7263 image_error ("Invalid image number `%s' in image `%s'",
7264 image, img->spec);
7265 TIFFClose (tiff);
7266 return 0;
7270 /* Get width and height of the image, and allocate a raster buffer
7271 of width x height 32-bit values. */
7272 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7273 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7275 if (!check_image_size (f, width, height))
7277 image_size_error ();
7278 TIFFClose (tiff);
7279 return 0;
7282 /* Create the X image and pixmap. */
7283 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7284 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7285 &ximg, 0)))
7287 TIFFClose (tiff);
7288 return 0;
7291 buf = xmalloc (sizeof *buf * width * height);
7293 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7295 /* Count the number of images in the file. */
7296 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7297 continue;
7299 if (count > 1)
7300 img->lisp_data = Fcons (Qcount,
7301 Fcons (make_number (count),
7302 img->lisp_data));
7304 TIFFClose (tiff);
7305 if (!rc)
7307 image_error ("Error reading TIFF image `%s'", img->spec);
7308 xfree (buf);
7309 return 0;
7312 #ifdef USE_CAIRO
7314 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
7315 uint32_t *dataptr = (uint32_t *) data;
7317 for (y = 0; y < height; ++y)
7319 uint32 *row = buf + (height - 1 - y) * width;
7320 for (x = 0; x < width; ++x)
7322 uint32 abgr = row[x];
7323 int r = TIFFGetR (abgr);
7324 int g = TIFFGetG (abgr);
7325 int b = TIFFGetB (abgr);
7326 int a = TIFFGetA (abgr);
7327 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
7331 create_cairo_image_surface (img, data, width, height);
7333 #else
7334 /* Initialize the color table. */
7335 init_color_table ();
7337 /* Process the pixel raster. Origin is in the lower-left corner. */
7338 for (y = 0; y < height; ++y)
7340 uint32 *row = buf + y * width;
7342 for (x = 0; x < width; ++x)
7344 uint32 abgr = row[x];
7345 int r = TIFFGetR (abgr) << 8;
7346 int g = TIFFGetG (abgr) << 8;
7347 int b = TIFFGetB (abgr) << 8;
7348 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7352 # ifdef COLOR_TABLE_SUPPORT
7353 /* Remember the colors allocated for the image. Free the color table. */
7354 img->colors = colors_in_color_table (&img->ncolors);
7355 free_color_table ();
7356 # endif /* COLOR_TABLE_SUPPORT */
7358 img->width = width;
7359 img->height = height;
7361 /* Maybe fill in the background field while we have ximg handy. */
7362 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7363 /* Casting avoids a GCC warning on W32. */
7364 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7366 /* Put ximg into the image. */
7367 image_put_x_image (f, img, ximg, 0);
7369 #endif /* ! USE_CAIRO */
7371 xfree (buf);
7372 return 1;
7375 #elif defined HAVE_NS
7377 static bool
7378 tiff_load (struct frame *f, struct image *img)
7380 return ns_load_image (f, img,
7381 image_spec_value (img->spec, QCfile, NULL),
7382 image_spec_value (img->spec, QCdata, NULL));
7385 #endif
7389 /***********************************************************************
7391 ***********************************************************************/
7393 #if defined (HAVE_GIF) || defined (HAVE_NS)
7395 static bool gif_image_p (Lisp_Object object);
7396 static bool gif_load (struct frame *f, struct image *img);
7397 static void gif_clear_image (struct frame *f, struct image *img);
7399 /* Indices of image specification fields in gif_format, below. */
7401 enum gif_keyword_index
7403 GIF_TYPE,
7404 GIF_DATA,
7405 GIF_FILE,
7406 GIF_ASCENT,
7407 GIF_MARGIN,
7408 GIF_RELIEF,
7409 GIF_ALGORITHM,
7410 GIF_HEURISTIC_MASK,
7411 GIF_MASK,
7412 GIF_IMAGE,
7413 GIF_BACKGROUND,
7414 GIF_LAST
7417 /* Vector of image_keyword structures describing the format
7418 of valid user-defined image specifications. */
7420 static const struct image_keyword gif_format[GIF_LAST] =
7422 {":type", IMAGE_SYMBOL_VALUE, 1},
7423 {":data", IMAGE_STRING_VALUE, 0},
7424 {":file", IMAGE_STRING_VALUE, 0},
7425 {":ascent", IMAGE_ASCENT_VALUE, 0},
7426 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7427 {":relief", IMAGE_INTEGER_VALUE, 0},
7428 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7429 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7430 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7431 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7432 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7435 #if defined HAVE_NTGUI && defined WINDOWSNT
7436 static bool init_gif_functions (void);
7437 #else
7438 #define init_gif_functions NULL
7439 #endif
7441 /* Structure describing the image type `gif'. */
7443 static struct image_type gif_type =
7445 SYMBOL_INDEX (Qgif),
7446 gif_image_p,
7447 gif_load,
7448 gif_clear_image,
7449 init_gif_functions,
7450 NULL
7453 /* Free X resources of GIF image IMG which is used on frame F. */
7455 static void
7456 gif_clear_image (struct frame *f, struct image *img)
7458 img->lisp_data = Qnil;
7459 x_clear_image (f, img);
7462 /* Return true if OBJECT is a valid GIF image specification. */
7464 static bool
7465 gif_image_p (Lisp_Object object)
7467 struct image_keyword fmt[GIF_LAST];
7468 memcpy (fmt, gif_format, sizeof fmt);
7470 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7471 return 0;
7473 /* Must specify either the :data or :file keyword. */
7474 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7477 #endif /* HAVE_GIF */
7479 #ifdef HAVE_GIF
7481 # ifdef HAVE_NTGUI
7483 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7484 Undefine before redefining to avoid a preprocessor warning. */
7485 # ifdef DrawText
7486 # undef DrawText
7487 # endif
7488 /* avoid conflict with QuickdrawText.h */
7489 # define DrawText gif_DrawText
7490 # include <gif_lib.h>
7491 # undef DrawText
7493 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7494 # ifndef GIFLIB_MINOR
7495 # define GIFLIB_MINOR 0
7496 # endif
7497 # ifndef GIFLIB_RELEASE
7498 # define GIFLIB_RELEASE 0
7499 # endif
7501 # else /* HAVE_NTGUI */
7503 # include <gif_lib.h>
7505 # endif /* HAVE_NTGUI */
7507 /* Giflib before 5.0 didn't define these macros. */
7508 # ifndef GIFLIB_MAJOR
7509 # define GIFLIB_MAJOR 4
7510 # endif
7512 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7513 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7514 earlier releases, where either it returns char * or GIFLIB_MINOR
7515 may be incorrect. */
7516 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7518 # ifdef WINDOWSNT
7520 /* GIF library details. */
7521 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7522 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7523 # else
7524 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7525 # endif
7526 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7527 # if GIFLIB_MAJOR < 5
7528 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7529 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7530 # else
7531 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7532 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7533 # endif
7534 # if HAVE_GIFERRORSTRING
7535 DEF_DLL_FN (char const *, GifErrorString, (int));
7536 # endif
7538 static bool
7539 init_gif_functions (void)
7541 HMODULE library;
7543 if (!(library = w32_delayed_load (Qgif)))
7544 return 0;
7546 LOAD_DLL_FN (library, DGifCloseFile);
7547 LOAD_DLL_FN (library, DGifSlurp);
7548 LOAD_DLL_FN (library, DGifOpen);
7549 LOAD_DLL_FN (library, DGifOpenFileName);
7550 # if HAVE_GIFERRORSTRING
7551 LOAD_DLL_FN (library, GifErrorString);
7552 # endif
7553 return 1;
7556 # undef DGifCloseFile
7557 # undef DGifOpen
7558 # undef DGifOpenFileName
7559 # undef DGifSlurp
7560 # undef GifErrorString
7562 # define DGifCloseFile fn_DGifCloseFile
7563 # define DGifOpen fn_DGifOpen
7564 # define DGifOpenFileName fn_DGifOpenFileName
7565 # define DGifSlurp fn_DGifSlurp
7566 # define GifErrorString fn_GifErrorString
7568 # endif /* WINDOWSNT */
7570 /* Reading a GIF image from memory
7571 Based on the PNG memory stuff to a certain extent. */
7573 typedef struct
7575 unsigned char *bytes;
7576 ptrdiff_t len;
7577 ptrdiff_t index;
7579 gif_memory_source;
7581 /* Make the current memory source available to gif_read_from_memory.
7582 It's done this way because not all versions of libungif support
7583 a UserData field in the GifFileType structure. */
7584 static gif_memory_source *current_gif_memory_src;
7586 static int
7587 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7589 gif_memory_source *src = current_gif_memory_src;
7591 if (len > src->len - src->index)
7592 return -1;
7594 memcpy (buf, src->bytes + src->index, len);
7595 src->index += len;
7596 return len;
7599 static int
7600 gif_close (GifFileType *gif, int *err)
7602 int retval;
7604 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7605 retval = DGifCloseFile (gif, err);
7606 #else
7607 retval = DGifCloseFile (gif);
7608 #if GIFLIB_MAJOR >= 5
7609 if (err)
7610 *err = gif->Error;
7611 #endif
7612 #endif
7613 return retval;
7616 /* Load GIF image IMG for use on frame F. Value is true if
7617 successful. */
7619 static const int interlace_start[] = {0, 4, 2, 1};
7620 static const int interlace_increment[] = {8, 8, 4, 2};
7622 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7624 static bool
7625 gif_load (struct frame *f, struct image *img)
7627 int rc, width, height, x, y, i, j;
7628 ColorMapObject *gif_color_map;
7629 GifFileType *gif;
7630 gif_memory_source memsrc;
7631 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7632 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7633 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7634 EMACS_INT idx;
7635 int gif_err;
7637 #ifdef USE_CAIRO
7638 unsigned char *data = 0;
7639 #else
7640 unsigned long pixel_colors[256];
7641 unsigned long bgcolor = 0;
7642 XImagePtr ximg;
7643 #endif
7645 if (NILP (specified_data))
7647 Lisp_Object file = x_find_image_file (specified_file);
7648 if (!STRINGP (file))
7650 image_error ("Cannot find image file `%s'", specified_file);
7651 return 0;
7654 Lisp_Object encoded_file = ENCODE_FILE (file);
7655 #ifdef WINDOWSNT
7656 encoded_file = ansi_encode_filename (encoded_file);
7657 #endif
7659 /* Open the GIF file. */
7660 #if GIFLIB_MAJOR < 5
7661 gif = DGifOpenFileName (SSDATA (encoded_file));
7662 #else
7663 gif = DGifOpenFileName (SSDATA (encoded_file), &gif_err);
7664 #endif
7665 if (gif == NULL)
7667 #if HAVE_GIFERRORSTRING
7668 image_error ("Cannot open `%s': %s",
7669 file, build_string (GifErrorString (gif_err)));
7670 #else
7671 image_error ("Cannot open `%s'", file);
7672 #endif
7673 return 0;
7676 else
7678 if (!STRINGP (specified_data))
7680 image_error ("Invalid image data `%s'", specified_data);
7681 return 0;
7684 /* Read from memory! */
7685 current_gif_memory_src = &memsrc;
7686 memsrc.bytes = SDATA (specified_data);
7687 memsrc.len = SBYTES (specified_data);
7688 memsrc.index = 0;
7690 #if GIFLIB_MAJOR < 5
7691 gif = DGifOpen (&memsrc, gif_read_from_memory);
7692 #else
7693 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7694 #endif
7695 if (!gif)
7697 #if HAVE_GIFERRORSTRING
7698 image_error ("Cannot open memory source `%s': %s",
7699 img->spec, build_string (GifErrorString (gif_err)));
7700 #else
7701 image_error ("Cannot open memory source `%s'", img->spec);
7702 #endif
7703 return 0;
7707 /* Before reading entire contents, check the declared image size. */
7708 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7710 image_size_error ();
7711 gif_close (gif, NULL);
7712 return 0;
7715 /* Read entire contents. */
7716 rc = DGifSlurp (gif);
7717 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7719 image_error ("Error reading `%s'", img->spec);
7720 gif_close (gif, NULL);
7721 return 0;
7724 /* Which sub-image are we to display? */
7726 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7727 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7728 if (idx < 0 || idx >= gif->ImageCount)
7730 image_error ("Invalid image number `%s' in image `%s'",
7731 image_number, img->spec);
7732 gif_close (gif, NULL);
7733 return 0;
7737 width = img->width = gif->SWidth;
7738 height = img->height = gif->SHeight;
7740 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7741 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7742 img->corners[BOT_CORNER]
7743 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7744 img->corners[RIGHT_CORNER]
7745 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7747 if (!check_image_size (f, width, height))
7749 image_size_error ();
7750 gif_close (gif, NULL);
7751 return 0;
7754 /* Check that the selected subimages fit. It's not clear whether
7755 the GIF spec requires this, but Emacs can crash if they don't fit. */
7756 for (j = 0; j <= idx; ++j)
7758 struct SavedImage *subimage = gif->SavedImages + j;
7759 int subimg_width = subimage->ImageDesc.Width;
7760 int subimg_height = subimage->ImageDesc.Height;
7761 int subimg_top = subimage->ImageDesc.Top;
7762 int subimg_left = subimage->ImageDesc.Left;
7763 if (! (subimg_width >= 0 && subimg_height >= 0
7764 && 0 <= subimg_top && subimg_top <= height - subimg_height
7765 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7767 image_error ("Subimage does not fit in image");
7768 gif_close (gif, NULL);
7769 return 0;
7773 #ifdef USE_CAIRO
7774 /* xzalloc so data is zero => transparent */
7775 data = (unsigned char *) xzalloc (width * height * 4);
7776 if (STRINGP (specified_bg))
7778 XColor color;
7779 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
7781 uint32_t *dataptr = (uint32_t *)data;
7782 int r = color.red/256;
7783 int g = color.green/256;
7784 int b = color.blue/256;
7786 for (y = 0; y < height; ++y)
7787 for (x = 0; x < width; ++x)
7788 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
7791 #else
7792 /* Create the X image and pixmap. */
7793 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7795 gif_close (gif, NULL);
7796 return 0;
7799 /* Clear the part of the screen image not covered by the image.
7800 Full animated GIF support requires more here (see the gif89 spec,
7801 disposal methods). Let's simply assume that the part not covered
7802 by a sub-image is in the frame's background color. */
7803 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7804 for (x = 0; x < width; ++x)
7805 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7807 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7808 for (x = 0; x < width; ++x)
7809 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7811 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7813 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7814 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7815 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7816 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7818 #endif
7820 /* Read the GIF image into the X image. */
7822 /* FIXME: With the current implementation, loading an animated gif
7823 is quadratic in the number of animation frames, since each frame
7824 is a separate struct image. We must provide a way for a single
7825 gif_load call to construct and save all animation frames. */
7827 init_color_table ();
7829 #ifndef USE_CAIRO
7830 if (STRINGP (specified_bg))
7831 bgcolor = x_alloc_image_color (f, img, specified_bg,
7832 FRAME_BACKGROUND_PIXEL (f));
7833 #endif
7835 for (j = 0; j <= idx; ++j)
7837 /* We use a local variable `raster' here because RasterBits is a
7838 char *, which invites problems with bytes >= 0x80. */
7839 struct SavedImage *subimage = gif->SavedImages + j;
7840 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7841 int transparency_color_index = -1;
7842 int disposal = 0;
7843 int subimg_width = subimage->ImageDesc.Width;
7844 int subimg_height = subimage->ImageDesc.Height;
7845 int subimg_top = subimage->ImageDesc.Top;
7846 int subimg_left = subimage->ImageDesc.Left;
7848 /* Find the Graphic Control Extension block for this sub-image.
7849 Extract the disposal method and transparency color. */
7850 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7852 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7854 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7855 && extblock->ByteCount == 4
7856 && extblock->Bytes[0] & 1)
7858 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7859 to background". Treat any other value like 2. */
7860 disposal = (extblock->Bytes[0] >> 2) & 7;
7861 transparency_color_index = (unsigned char) extblock->Bytes[3];
7862 break;
7866 /* We can't "keep in place" the first subimage. */
7867 if (j == 0)
7868 disposal = 2;
7870 /* For disposal == 0, the spec says "No disposal specified. The
7871 decoder is not required to take any action." In practice, it
7872 seems we need to treat this like "keep in place", see e.g.
7873 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7874 if (disposal == 0)
7875 disposal = 1;
7877 gif_color_map = subimage->ImageDesc.ColorMap;
7878 if (!gif_color_map)
7879 gif_color_map = gif->SColorMap;
7881 #ifndef USE_CAIRO
7882 /* Allocate subimage colors. */
7883 memset (pixel_colors, 0, sizeof pixel_colors);
7885 if (gif_color_map)
7886 for (i = 0; i < gif_color_map->ColorCount; ++i)
7888 if (transparency_color_index == i)
7889 pixel_colors[i] = STRINGP (specified_bg)
7890 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7891 else
7893 int r = gif_color_map->Colors[i].Red << 8;
7894 int g = gif_color_map->Colors[i].Green << 8;
7895 int b = gif_color_map->Colors[i].Blue << 8;
7896 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7899 #endif
7901 /* Apply the pixel values. */
7902 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7904 int row, pass;
7906 for (y = 0, row = interlace_start[0], pass = 0;
7907 y < subimg_height;
7908 y++, row += interlace_increment[pass])
7910 while (subimg_height <= row)
7911 row = interlace_start[++pass];
7913 for (x = 0; x < subimg_width; x++)
7915 int c = raster[y * subimg_width + x];
7916 if (transparency_color_index != c || disposal != 1)
7918 #ifdef USE_CAIRO
7919 uint32_t *dataptr =
7920 ((uint32_t*)data + ((row + subimg_top) * subimg_width
7921 + x + subimg_left));
7922 int r = gif_color_map->Colors[c].Red;
7923 int g = gif_color_map->Colors[c].Green;
7924 int b = gif_color_map->Colors[c].Blue;
7926 if (transparency_color_index != c)
7927 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7928 #else
7929 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7930 pixel_colors[c]);
7931 #endif
7936 else
7938 for (y = 0; y < subimg_height; ++y)
7939 for (x = 0; x < subimg_width; ++x)
7941 int c = raster[y * subimg_width + x];
7942 if (transparency_color_index != c || disposal != 1)
7944 #ifdef USE_CAIRO
7945 uint32_t *dataptr =
7946 ((uint32_t*)data + ((y + subimg_top) * subimg_width
7947 + x + subimg_left));
7948 int r = gif_color_map->Colors[c].Red;
7949 int g = gif_color_map->Colors[c].Green;
7950 int b = gif_color_map->Colors[c].Blue;
7951 if (transparency_color_index != c)
7952 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7953 #else
7954 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7955 pixel_colors[c]);
7956 #endif
7962 #ifdef COLOR_TABLE_SUPPORT
7963 img->colors = colors_in_color_table (&img->ncolors);
7964 free_color_table ();
7965 #endif /* COLOR_TABLE_SUPPORT */
7967 /* Save GIF image extension data for `image-metadata'.
7968 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7969 img->lisp_data = Qnil;
7970 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7972 int delay = 0;
7973 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7974 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7975 /* Append (... FUNCTION "BYTES") */
7977 img->lisp_data
7978 = Fcons (make_number (ext->Function),
7979 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7980 img->lisp_data));
7981 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7982 && ext->ByteCount == 4)
7984 delay = ext->Bytes[2] << CHAR_BIT;
7985 delay |= ext->Bytes[1];
7988 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7989 if (delay)
7990 img->lisp_data
7991 = Fcons (Qdelay,
7992 Fcons (make_float (delay / 100.0),
7993 img->lisp_data));
7996 if (gif->ImageCount > 1)
7997 img->lisp_data = Fcons (Qcount,
7998 Fcons (make_number (gif->ImageCount),
7999 img->lisp_data));
8001 if (gif_close (gif, &gif_err) == GIF_ERROR)
8003 #if HAVE_GIFERRORSTRING
8004 char const *error_text = GifErrorString (gif_err);
8006 if (error_text)
8007 image_error ("Error closing `%s': %s",
8008 img->spec, build_string (error_text));
8009 #else
8010 image_error ("Error closing `%s'", img->spec);
8011 #endif
8014 #ifdef USE_CAIRO
8015 create_cairo_image_surface (img, data, width, height);
8016 #else
8017 /* Maybe fill in the background field while we have ximg handy. */
8018 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8019 /* Casting avoids a GCC warning. */
8020 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8022 /* Put ximg into the image. */
8023 image_put_x_image (f, img, ximg, 0);
8024 #endif
8026 return 1;
8029 #else /* !HAVE_GIF */
8031 #ifdef HAVE_NS
8032 static bool
8033 gif_load (struct frame *f, struct image *img)
8035 return ns_load_image (f, img,
8036 image_spec_value (img->spec, QCfile, NULL),
8037 image_spec_value (img->spec, QCdata, NULL));
8039 #endif /* HAVE_NS */
8041 #endif /* HAVE_GIF */
8044 #ifdef HAVE_IMAGEMAGICK
8046 /***********************************************************************
8047 ImageMagick
8048 ***********************************************************************/
8050 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8051 safely rounded and clipped to int range. */
8053 static int
8054 scale_image_size (int size, size_t divisor, size_t multiplier)
8056 if (divisor != 0)
8058 double s = size;
8059 double scaled = s * multiplier / divisor + 0.5;
8060 if (scaled < INT_MAX)
8061 return scaled;
8063 return INT_MAX;
8066 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8067 Use SPEC to deduce the size. Store the desired size into
8068 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8069 static void
8070 compute_image_size (size_t width, size_t height,
8071 Lisp_Object spec,
8072 int *d_width, int *d_height)
8074 Lisp_Object value;
8075 int desired_width, desired_height;
8076 double scale = 1;
8078 /* If width and/or height is set in the display spec assume we want
8079 to scale to those values. If either h or w is unspecified, the
8080 unspecified should be calculated from the specified to preserve
8081 aspect ratio. */
8082 value = image_spec_value (spec, QCwidth, NULL);
8083 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8084 value = image_spec_value (spec, QCheight, NULL);
8085 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8087 value = image_spec_value (spec, QCscale, NULL);
8088 if (NUMBERP (value))
8089 scale = extract_float (value);
8090 width = width * scale;
8091 height = height * scale;
8093 if (desired_width == -1)
8095 value = image_spec_value (spec, QCmax_width, NULL);
8096 if (NATNUMP (value))
8098 int max_width = min (XFASTINT (value), INT_MAX);
8099 if (max_width < width)
8101 /* The image is wider than :max-width. */
8102 desired_width = max_width;
8103 if (desired_height == -1)
8105 desired_height = scale_image_size (desired_width,
8106 width, height);
8107 value = image_spec_value (spec, QCmax_height, NULL);
8108 if (NATNUMP (value))
8110 int max_height = min (XFASTINT (value), INT_MAX);
8111 if (max_height < desired_height)
8113 desired_height = max_height;
8114 desired_width = scale_image_size (desired_height,
8115 height, width);
8123 if (desired_height == -1)
8125 value = image_spec_value (spec, QCmax_height, NULL);
8126 if (NATNUMP (value))
8128 int max_height = min (XFASTINT (value), INT_MAX);
8129 if (max_height < height)
8130 desired_height = max_height;
8134 if (desired_width != -1 && desired_height == -1)
8135 /* w known, calculate h. */
8136 desired_height = scale_image_size (desired_width, width, height);
8138 if (desired_width == -1 && desired_height != -1)
8139 /* h known, calculate w. */
8140 desired_width = scale_image_size (desired_height, height, width);
8142 /* We have no width/height settings, so just apply the scale. */
8143 if (desired_width == -1 && desired_height == -1)
8145 desired_width = width;
8146 desired_height = height;
8149 *d_width = desired_width;
8150 *d_height = desired_height;
8153 static bool imagemagick_image_p (Lisp_Object);
8154 static bool imagemagick_load (struct frame *, struct image *);
8155 static void imagemagick_clear_image (struct frame *, struct image *);
8157 /* Indices of image specification fields in imagemagick_format. */
8159 enum imagemagick_keyword_index
8161 IMAGEMAGICK_TYPE,
8162 IMAGEMAGICK_DATA,
8163 IMAGEMAGICK_FILE,
8164 IMAGEMAGICK_ASCENT,
8165 IMAGEMAGICK_MARGIN,
8166 IMAGEMAGICK_RELIEF,
8167 IMAGEMAGICK_ALGORITHM,
8168 IMAGEMAGICK_HEURISTIC_MASK,
8169 IMAGEMAGICK_MASK,
8170 IMAGEMAGICK_BACKGROUND,
8171 IMAGEMAGICK_HEIGHT,
8172 IMAGEMAGICK_WIDTH,
8173 IMAGEMAGICK_MAX_HEIGHT,
8174 IMAGEMAGICK_MAX_WIDTH,
8175 IMAGEMAGICK_FORMAT,
8176 IMAGEMAGICK_ROTATION,
8177 IMAGEMAGICK_CROP,
8178 IMAGEMAGICK_LAST
8181 /* Vector of image_keyword structures describing the format
8182 of valid user-defined image specifications. */
8184 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
8186 {":type", IMAGE_SYMBOL_VALUE, 1},
8187 {":data", IMAGE_STRING_VALUE, 0},
8188 {":file", IMAGE_STRING_VALUE, 0},
8189 {":ascent", IMAGE_ASCENT_VALUE, 0},
8190 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8191 {":relief", IMAGE_INTEGER_VALUE, 0},
8192 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8193 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8194 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8195 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8196 {":height", IMAGE_INTEGER_VALUE, 0},
8197 {":width", IMAGE_INTEGER_VALUE, 0},
8198 {":max-height", IMAGE_INTEGER_VALUE, 0},
8199 {":max-width", IMAGE_INTEGER_VALUE, 0},
8200 {":format", IMAGE_SYMBOL_VALUE, 0},
8201 {":rotation", IMAGE_NUMBER_VALUE, 0},
8202 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8205 #if defined HAVE_NTGUI && defined WINDOWSNT
8206 static bool init_imagemagick_functions (void);
8207 #else
8208 #define init_imagemagick_functions NULL
8209 #endif
8211 /* Structure describing the image type for any image handled via
8212 ImageMagick. */
8214 static struct image_type imagemagick_type =
8216 SYMBOL_INDEX (Qimagemagick),
8217 imagemagick_image_p,
8218 imagemagick_load,
8219 imagemagick_clear_image,
8220 init_imagemagick_functions,
8221 NULL
8224 /* Free X resources of imagemagick image IMG which is used on frame F. */
8226 static void
8227 imagemagick_clear_image (struct frame *f,
8228 struct image *img)
8230 x_clear_image (f, img);
8233 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8234 this by calling parse_image_spec and supplying the keywords that
8235 identify the IMAGEMAGICK format. */
8237 static bool
8238 imagemagick_image_p (Lisp_Object object)
8240 struct image_keyword fmt[IMAGEMAGICK_LAST];
8241 memcpy (fmt, imagemagick_format, sizeof fmt);
8243 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
8244 return 0;
8246 /* Must specify either the :data or :file keyword. */
8247 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
8250 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8251 Therefore rename the function so it doesn't collide with ImageMagick. */
8252 #define DrawRectangle DrawRectangleGif
8253 #include <wand/MagickWand.h>
8255 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8256 Emacs seems to work fine with the hidden version, so unhide it. */
8257 #include <magick/version.h>
8258 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8259 extern WandExport void PixelGetMagickColor (const PixelWand *,
8260 MagickPixelPacket *);
8261 #endif
8263 /* Log ImageMagick error message.
8264 Useful when a ImageMagick function returns the status `MagickFalse'. */
8266 static void
8267 imagemagick_error (MagickWand *wand)
8269 char *description;
8270 ExceptionType severity;
8272 description = MagickGetException (wand, &severity);
8273 image_error ("ImageMagick error: %s", build_string (description));
8274 MagickRelinquishMemory (description);
8277 /* Possibly give ImageMagick some extra help to determine the image
8278 type by supplying a "dummy" filename based on the Content-Type. */
8280 static char *
8281 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
8283 Lisp_Object symbol = intern ("image-format-suffixes");
8284 Lisp_Object val = find_symbol_value (symbol);
8285 Lisp_Object format;
8287 if (! CONSP (val))
8288 return NULL;
8290 format = image_spec_value (spec, intern (":format"), NULL);
8291 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
8292 if (! STRINGP (val))
8293 return NULL;
8295 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8296 as ImageMagick would ignore the extra bytes anyway. */
8297 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
8298 return hint_buffer;
8301 /* Animated images (e.g., GIF89a) are composed from one "master image"
8302 (which is the first one, and then there's a number of images that
8303 follow. If following images have non-transparent colors, these are
8304 composed "on top" of the master image. So, in general, one has to
8305 compute ann the preceding images to be able to display a particular
8306 sub-image.
8308 Computing all the preceding images is too slow, so we maintain a
8309 cache of previously computed images. We have to maintain a cache
8310 separate from the image cache, because the images may be scaled
8311 before display. */
8313 struct animation_cache
8315 MagickWand *wand;
8316 int index;
8317 struct timespec update_time;
8318 struct animation_cache *next;
8319 char signature[FLEXIBLE_ARRAY_MEMBER];
8322 static struct animation_cache *animation_cache = NULL;
8324 static struct animation_cache *
8325 imagemagick_create_cache (char *signature)
8327 struct animation_cache *cache
8328 = xmalloc (offsetof (struct animation_cache, signature)
8329 + strlen (signature) + 1);
8330 cache->wand = 0;
8331 cache->index = 0;
8332 cache->next = 0;
8333 strcpy (cache->signature, signature);
8334 return cache;
8337 /* Discard cached images that haven't been used for a minute. */
8338 static void
8339 imagemagick_prune_animation_cache (void)
8341 struct animation_cache **pcache = &animation_cache;
8342 struct timespec old = timespec_sub (current_timespec (),
8343 make_timespec (60, 0));
8345 while (*pcache)
8347 struct animation_cache *cache = *pcache;
8348 if (timespec_cmp (old, cache->update_time) <= 0)
8349 pcache = &cache->next;
8350 else
8352 if (cache->wand)
8353 DestroyMagickWand (cache->wand);
8354 *pcache = cache->next;
8355 xfree (cache);
8360 static struct animation_cache *
8361 imagemagick_get_animation_cache (MagickWand *wand)
8363 char *signature = MagickGetImageSignature (wand);
8364 struct animation_cache *cache;
8365 struct animation_cache **pcache = &animation_cache;
8367 imagemagick_prune_animation_cache ();
8369 while (1)
8371 cache = *pcache;
8372 if (! cache)
8374 *pcache = cache = imagemagick_create_cache (signature);
8375 break;
8377 if (strcmp (signature, cache->signature) == 0)
8378 break;
8379 pcache = &cache->next;
8382 DestroyString (signature);
8383 cache->update_time = current_timespec ();
8384 return cache;
8387 static MagickWand *
8388 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8390 int i;
8391 MagickWand *composite_wand;
8392 size_t dest_width, dest_height;
8393 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8395 MagickSetIteratorIndex (super_wand, 0);
8397 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8399 composite_wand = MagickGetImage (super_wand);
8400 if (cache->wand)
8401 DestroyMagickWand (cache->wand);
8403 else
8404 composite_wand = cache->wand;
8406 dest_height = MagickGetImageHeight (composite_wand);
8408 for (i = max (1, cache->index + 1); i <= ino; i++)
8410 MagickWand *sub_wand;
8411 PixelIterator *source_iterator, *dest_iterator;
8412 PixelWand **source, **dest;
8413 size_t source_width, source_height;
8414 ssize_t source_left, source_top;
8415 MagickPixelPacket pixel;
8416 DisposeType dispose;
8417 ptrdiff_t lines = 0;
8419 MagickSetIteratorIndex (super_wand, i);
8420 sub_wand = MagickGetImage (super_wand);
8422 MagickGetImagePage (sub_wand, &source_width, &source_height,
8423 &source_left, &source_top);
8425 /* This flag says how to handle transparent pixels. */
8426 dispose = MagickGetImageDispose (sub_wand);
8428 source_iterator = NewPixelIterator (sub_wand);
8429 if (! source_iterator)
8431 DestroyMagickWand (composite_wand);
8432 DestroyMagickWand (sub_wand);
8433 cache->wand = NULL;
8434 image_error ("Imagemagick pixel iterator creation failed");
8435 return NULL;
8438 dest_iterator = NewPixelIterator (composite_wand);
8439 if (! dest_iterator)
8441 DestroyMagickWand (composite_wand);
8442 DestroyMagickWand (sub_wand);
8443 DestroyPixelIterator (source_iterator);
8444 cache->wand = NULL;
8445 image_error ("Imagemagick pixel iterator creation failed");
8446 return NULL;
8449 /* The sub-image may not start at origin, so move the destination
8450 iterator to where the sub-image should start. */
8451 if (source_top > 0)
8453 PixelSetIteratorRow (dest_iterator, source_top);
8454 lines = source_top;
8457 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8458 != NULL)
8460 ptrdiff_t x;
8462 /* Sanity check. This shouldn't happen, but apparently
8463 does in some pictures. */
8464 if (++lines >= dest_height)
8465 break;
8467 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8468 for (x = 0; x < source_width; x++)
8470 /* Sanity check. This shouldn't happen, but apparently
8471 also does in some pictures. */
8472 if (x + source_left >= dest_width)
8473 break;
8474 /* Normally we only copy over non-transparent pixels,
8475 but if the disposal method is "Background", then we
8476 copy over all pixels. */
8477 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8479 PixelGetMagickColor (source[x], &pixel);
8480 PixelSetMagickColor (dest[x + source_left], &pixel);
8483 PixelSyncIterator (dest_iterator);
8486 DestroyPixelIterator (source_iterator);
8487 DestroyPixelIterator (dest_iterator);
8488 DestroyMagickWand (sub_wand);
8491 /* Cache a copy for the next iteration. The current wand will be
8492 destroyed by the caller. */
8493 cache->wand = CloneMagickWand (composite_wand);
8494 cache->index = ino;
8496 return composite_wand;
8500 /* Helper function for imagemagick_load, which does the actual loading
8501 given contents and size, apart from frame and image structures,
8502 passed from imagemagick_load. Uses librimagemagick to do most of
8503 the image processing.
8505 F is a pointer to the Emacs frame; IMG to the image structure to
8506 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8507 be parsed; SIZE is the number of bytes of data; and FILENAME is
8508 either the file name or the image data.
8510 Return true if successful. */
8512 static bool
8513 imagemagick_load_image (struct frame *f, struct image *img,
8514 unsigned char *contents, unsigned int size,
8515 char *filename)
8517 int width, height;
8518 size_t image_width, image_height;
8519 MagickBooleanType status;
8520 XImagePtr ximg;
8521 int x, y;
8522 MagickWand *image_wand;
8523 PixelIterator *iterator;
8524 PixelWand **pixels, *bg_wand = NULL;
8525 MagickPixelPacket pixel;
8526 Lisp_Object image;
8527 Lisp_Object value;
8528 Lisp_Object crop;
8529 EMACS_INT ino;
8530 int desired_width, desired_height;
8531 double rotation;
8532 int pixelwidth;
8533 char hint_buffer[MaxTextExtent];
8534 char *filename_hint = NULL;
8536 /* Handle image index for image types who can contain more than one image.
8537 Interface :index is same as for GIF. First we "ping" the image to see how
8538 many sub-images it contains. Pinging is faster than loading the image to
8539 find out things about it. */
8541 /* Initialize the imagemagick environment. */
8542 MagickWandGenesis ();
8543 image = image_spec_value (img->spec, QCindex, NULL);
8544 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8545 image_wand = NewMagickWand ();
8547 if (filename)
8548 status = MagickReadImage (image_wand, filename);
8549 else
8551 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8552 MagickSetFilename (image_wand, filename_hint);
8553 status = MagickReadImageBlob (image_wand, contents, size);
8556 if (status == MagickFalse)
8558 imagemagick_error (image_wand);
8559 DestroyMagickWand (image_wand);
8560 return 0;
8563 #ifdef HAVE_MAGICKAUTOORIENTIMAGE
8564 /* If no :rotation is explicitly specified, apply the automatic
8565 rotation from EXIF. */
8566 if (NILP (image_spec_value (img->spec, QCrotation, NULL)))
8567 if (MagickAutoOrientImage (image_wand) == MagickFalse)
8569 image_error ("Error applying automatic orientation in image `%s'", img->spec);
8570 DestroyMagickWand (image_wand);
8571 return 0;
8573 #endif
8575 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8577 image_error ("Invalid image number `%s' in image `%s'", image, img->spec);
8578 DestroyMagickWand (image_wand);
8579 return 0;
8582 if (MagickGetImageDelay (image_wand) > 0)
8583 img->lisp_data =
8584 Fcons (Qdelay,
8585 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8586 img->lisp_data));
8588 if (MagickGetNumberImages (image_wand) > 1)
8589 img->lisp_data =
8590 Fcons (Qcount,
8591 Fcons (make_number (MagickGetNumberImages (image_wand)),
8592 img->lisp_data));
8594 /* If we have an animated image, get the new wand based on the
8595 "super-wand". */
8596 if (MagickGetNumberImages (image_wand) > 1)
8598 MagickWand *super_wand = image_wand;
8599 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8600 if (! image_wand)
8601 image_wand = super_wand;
8602 else
8603 DestroyMagickWand (super_wand);
8606 /* Retrieve the frame's background color, for use later. */
8608 XColor bgcolor;
8609 Lisp_Object specified_bg;
8611 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8612 if (!STRINGP (specified_bg)
8613 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8614 x_query_frame_background_color (f, &bgcolor);
8616 bg_wand = NewPixelWand ();
8617 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8618 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8619 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8622 compute_image_size (MagickGetImageWidth (image_wand),
8623 MagickGetImageHeight (image_wand),
8624 img->spec, &desired_width, &desired_height);
8626 if (desired_width != -1 && desired_height != -1)
8628 status = MagickScaleImage (image_wand, desired_width, desired_height);
8629 if (status == MagickFalse)
8631 image_error ("Imagemagick scale failed");
8632 imagemagick_error (image_wand);
8633 goto imagemagick_error;
8637 /* crop behaves similar to image slicing in Emacs but is more memory
8638 efficient. */
8639 crop = image_spec_value (img->spec, QCcrop, NULL);
8641 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8643 /* After some testing, it seems MagickCropImage is the fastest crop
8644 function in ImageMagick. This crop function seems to do less copying
8645 than the alternatives, but it still reads the entire image into memory
8646 before cropping, which is apparently difficult to avoid when using
8647 imagemagick. */
8648 size_t crop_width = XINT (XCAR (crop));
8649 crop = XCDR (crop);
8650 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8652 size_t crop_height = XINT (XCAR (crop));
8653 crop = XCDR (crop);
8654 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8656 ssize_t crop_x = XINT (XCAR (crop));
8657 crop = XCDR (crop);
8658 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8660 ssize_t crop_y = XINT (XCAR (crop));
8661 MagickCropImage (image_wand, crop_width, crop_height,
8662 crop_x, crop_y);
8668 /* Furthermore :rotation. we need background color and angle for
8669 rotation. */
8671 TODO background handling for rotation specified_bg =
8672 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8673 (specified_bg). */
8674 value = image_spec_value (img->spec, QCrotation, NULL);
8675 if (FLOATP (value))
8677 rotation = extract_float (value);
8678 status = MagickRotateImage (image_wand, bg_wand, rotation);
8679 if (status == MagickFalse)
8681 image_error ("Imagemagick image rotate failed");
8682 imagemagick_error (image_wand);
8683 goto imagemagick_error;
8687 /* Set the canvas background color to the frame or specified
8688 background, and flatten the image. Note: as of ImageMagick
8689 6.6.0, SVG image transparency is not handled properly
8690 (e.g. etc/images/splash.svg shows a white background always). */
8692 MagickWand *new_wand;
8693 MagickSetImageBackgroundColor (image_wand, bg_wand);
8694 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8695 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8696 #else
8697 new_wand = MagickFlattenImages (image_wand);
8698 #endif
8699 DestroyMagickWand (image_wand);
8700 image_wand = new_wand;
8703 /* Finally we are done manipulating the image. Figure out the
8704 resulting width/height and transfer ownership to Emacs. */
8705 image_height = MagickGetImageHeight (image_wand);
8706 image_width = MagickGetImageWidth (image_wand);
8708 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8709 && check_image_size (f, image_width, image_height)))
8711 image_size_error ();
8712 goto imagemagick_error;
8715 width = image_width;
8716 height = image_height;
8718 /* We can now get a valid pixel buffer from the imagemagick file, if all
8719 went ok. */
8721 init_color_table ();
8723 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8724 if (imagemagick_render_type != 0)
8726 /* Magicexportimage is normally faster than pixelpushing. This
8727 method is also well tested. Some aspects of this method are
8728 ad-hoc and needs to be more researched. */
8729 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8730 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8731 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8732 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8733 &ximg, 0))
8735 #ifdef COLOR_TABLE_SUPPORT
8736 free_color_table ();
8737 #endif
8738 image_error ("Imagemagick X bitmap allocation failure");
8739 goto imagemagick_error;
8742 /* Oddly, the below code doesn't seem to work:*/
8743 /* switch(ximg->bitmap_unit){ */
8744 /* case 8: */
8745 /* pixelwidth=CharPixel; */
8746 /* break; */
8747 /* case 16: */
8748 /* pixelwidth=ShortPixel; */
8749 /* break; */
8750 /* case 32: */
8751 /* pixelwidth=LongPixel; */
8752 /* break; */
8753 /* } */
8755 Here im just guessing the format of the bitmap.
8756 happens to work fine for:
8757 - bw djvu images
8758 on rgb display.
8759 seems about 3 times as fast as pixel pushing(not carefully measured)
8761 pixelwidth = CharPixel; /*??? TODO figure out*/
8762 MagickExportImagePixels (image_wand, 0, 0, width, height,
8763 exportdepth, pixelwidth, ximg->data);
8765 else
8766 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8768 size_t image_height;
8769 MagickRealType color_scale = 65535.0 / QuantumRange;
8771 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8772 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8773 &ximg, 0))
8775 #ifdef COLOR_TABLE_SUPPORT
8776 free_color_table ();
8777 #endif
8778 image_error ("Imagemagick X bitmap allocation failure");
8779 goto imagemagick_error;
8782 /* Copy imagemagick image to x with primitive yet robust pixel
8783 pusher loop. This has been tested a lot with many different
8784 images. */
8786 /* Copy pixels from the imagemagick image structure to the x image map. */
8787 iterator = NewPixelIterator (image_wand);
8788 if (! iterator)
8790 #ifdef COLOR_TABLE_SUPPORT
8791 free_color_table ();
8792 #endif
8793 x_destroy_x_image (ximg);
8794 image_error ("Imagemagick pixel iterator creation failed");
8795 goto imagemagick_error;
8798 image_height = MagickGetImageHeight (image_wand);
8799 for (y = 0; y < image_height; y++)
8801 size_t row_width;
8802 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8803 if (! pixels)
8804 break;
8805 int xlim = min (row_width, width);
8806 for (x = 0; x < xlim; x++)
8808 PixelGetMagickColor (pixels[x], &pixel);
8809 XPutPixel (ximg, x, y,
8810 lookup_rgb_color (f,
8811 color_scale * pixel.red,
8812 color_scale * pixel.green,
8813 color_scale * pixel.blue));
8816 DestroyPixelIterator (iterator);
8819 #ifdef COLOR_TABLE_SUPPORT
8820 /* Remember colors allocated for this image. */
8821 img->colors = colors_in_color_table (&img->ncolors);
8822 free_color_table ();
8823 #endif /* COLOR_TABLE_SUPPORT */
8825 img->width = width;
8826 img->height = height;
8828 /* Put ximg into the image. */
8829 image_put_x_image (f, img, ximg, 0);
8831 /* Final cleanup. image_wand should be the only resource left. */
8832 DestroyMagickWand (image_wand);
8833 if (bg_wand) DestroyPixelWand (bg_wand);
8835 /* `MagickWandTerminus' terminates the imagemagick environment. */
8836 MagickWandTerminus ();
8838 return 1;
8840 imagemagick_error:
8841 DestroyMagickWand (image_wand);
8842 if (bg_wand) DestroyPixelWand (bg_wand);
8844 MagickWandTerminus ();
8845 /* TODO more cleanup. */
8846 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec);
8847 return 0;
8851 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8852 successful. this function will go into the imagemagick_type structure, and
8853 the prototype thus needs to be compatible with that structure. */
8855 static bool
8856 imagemagick_load (struct frame *f, struct image *img)
8858 bool success_p = 0;
8859 Lisp_Object file_name;
8861 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8862 file_name = image_spec_value (img->spec, QCfile, NULL);
8863 if (STRINGP (file_name))
8865 Lisp_Object file = x_find_image_file (file_name);
8866 if (!STRINGP (file))
8868 image_error ("Cannot find image file `%s'", file_name);
8869 return 0;
8871 file = ENCODE_FILE (file);
8872 #ifdef WINDOWSNT
8873 file = ansi_encode_filename (file);
8874 #endif
8875 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8877 /* Else its not a file, its a lisp object. Load the image from a
8878 lisp object rather than a file. */
8879 else
8881 Lisp_Object data;
8883 data = image_spec_value (img->spec, QCdata, NULL);
8884 if (!STRINGP (data))
8886 image_error ("Invalid image data `%s'", data);
8887 return 0;
8889 success_p = imagemagick_load_image (f, img, SDATA (data),
8890 SBYTES (data), NULL);
8893 return success_p;
8896 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8897 doc: /* Return a list of image types supported by ImageMagick.
8898 Each entry in this list is a symbol named after an ImageMagick format
8899 tag. See the ImageMagick manual for a list of ImageMagick formats and
8900 their descriptions (http://www.imagemagick.org/script/formats.php).
8901 You can also try the shell command: `identify -list format'.
8903 Note that ImageMagick recognizes many file-types that Emacs does not
8904 recognize as images, such as C. See `imagemagick-types-enable'
8905 and `imagemagick-types-inhibit'. */)
8906 (void)
8908 Lisp_Object typelist = Qnil;
8909 size_t numf = 0;
8910 ExceptionInfo ex;
8911 char **imtypes;
8912 size_t i;
8914 GetExceptionInfo(&ex);
8915 imtypes = GetMagickList ("*", &numf, &ex);
8916 DestroyExceptionInfo(&ex);
8918 for (i = 0; i < numf; i++)
8920 Lisp_Object imagemagicktype = intern (imtypes[i]);
8921 typelist = Fcons (imagemagicktype, typelist);
8922 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8925 MagickRelinquishMemory (imtypes);
8926 return Fnreverse (typelist);
8929 #endif /* defined (HAVE_IMAGEMAGICK) */
8933 /***********************************************************************
8935 ***********************************************************************/
8937 #ifdef HAVE_RSVG
8939 /* Function prototypes. */
8941 static bool svg_image_p (Lisp_Object object);
8942 static bool svg_load (struct frame *f, struct image *img);
8944 static bool svg_load_image (struct frame *, struct image *,
8945 unsigned char *, ptrdiff_t, char *);
8947 /* Indices of image specification fields in svg_format, below. */
8949 enum svg_keyword_index
8951 SVG_TYPE,
8952 SVG_DATA,
8953 SVG_FILE,
8954 SVG_ASCENT,
8955 SVG_MARGIN,
8956 SVG_RELIEF,
8957 SVG_ALGORITHM,
8958 SVG_HEURISTIC_MASK,
8959 SVG_MASK,
8960 SVG_BACKGROUND,
8961 SVG_LAST
8964 /* Vector of image_keyword structures describing the format
8965 of valid user-defined image specifications. */
8967 static const struct image_keyword svg_format[SVG_LAST] =
8969 {":type", IMAGE_SYMBOL_VALUE, 1},
8970 {":data", IMAGE_STRING_VALUE, 0},
8971 {":file", IMAGE_STRING_VALUE, 0},
8972 {":ascent", IMAGE_ASCENT_VALUE, 0},
8973 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8974 {":relief", IMAGE_INTEGER_VALUE, 0},
8975 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8976 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8977 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8978 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8981 # if defined HAVE_NTGUI && defined WINDOWSNT
8982 static bool init_svg_functions (void);
8983 # else
8984 #define init_svg_functions NULL
8985 # endif
8987 /* Structure describing the image type `svg'. Its the same type of
8988 structure defined for all image formats, handled by emacs image
8989 functions. See struct image_type in dispextern.h. */
8991 static struct image_type svg_type =
8993 SYMBOL_INDEX (Qsvg),
8994 svg_image_p,
8995 svg_load,
8996 x_clear_image,
8997 init_svg_functions,
8998 NULL
9002 /* Return true if OBJECT is a valid SVG image specification. Do
9003 this by calling parse_image_spec and supplying the keywords that
9004 identify the SVG format. */
9006 static bool
9007 svg_image_p (Lisp_Object object)
9009 struct image_keyword fmt[SVG_LAST];
9010 memcpy (fmt, svg_format, sizeof fmt);
9012 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
9013 return 0;
9015 /* Must specify either the :data or :file keyword. */
9016 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
9019 # include <librsvg/rsvg.h>
9021 # ifdef WINDOWSNT
9023 /* SVG library functions. */
9024 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
9025 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
9026 (RsvgHandle *, RsvgDimensionData *));
9027 DEF_DLL_FN (gboolean, rsvg_handle_write,
9028 (RsvgHandle *, const guchar *, gsize, GError **));
9029 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
9030 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
9031 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
9033 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
9034 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
9035 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
9036 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
9037 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
9038 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
9039 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
9040 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
9042 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9043 DEF_DLL_FN (void, g_type_init, (void));
9044 # endif
9045 DEF_DLL_FN (void, g_object_unref, (gpointer));
9046 DEF_DLL_FN (void, g_clear_error, (GError **));
9048 static bool
9049 init_svg_functions (void)
9051 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
9053 if (!(glib = w32_delayed_load (Qglib))
9054 || !(gobject = w32_delayed_load (Qgobject))
9055 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
9056 || !(library = w32_delayed_load (Qsvg)))
9058 if (gdklib) FreeLibrary (gdklib);
9059 if (gobject) FreeLibrary (gobject);
9060 if (glib) FreeLibrary (glib);
9061 return 0;
9064 LOAD_DLL_FN (library, rsvg_handle_new);
9065 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
9066 LOAD_DLL_FN (library, rsvg_handle_write);
9067 LOAD_DLL_FN (library, rsvg_handle_close);
9068 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
9069 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
9071 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
9072 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
9073 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
9074 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
9075 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
9076 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
9077 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
9078 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
9080 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9081 LOAD_DLL_FN (gobject, g_type_init);
9082 # endif
9083 LOAD_DLL_FN (gobject, g_object_unref);
9084 LOAD_DLL_FN (glib, g_clear_error);
9086 return 1;
9089 /* The following aliases for library functions allow dynamic loading
9090 to be used on some platforms. */
9092 # undef gdk_pixbuf_get_bits_per_sample
9093 # undef gdk_pixbuf_get_colorspace
9094 # undef gdk_pixbuf_get_has_alpha
9095 # undef gdk_pixbuf_get_height
9096 # undef gdk_pixbuf_get_n_channels
9097 # undef gdk_pixbuf_get_pixels
9098 # undef gdk_pixbuf_get_rowstride
9099 # undef gdk_pixbuf_get_width
9100 # undef g_clear_error
9101 # undef g_object_unref
9102 # undef g_type_init
9103 # undef rsvg_handle_close
9104 # undef rsvg_handle_get_dimensions
9105 # undef rsvg_handle_get_pixbuf
9106 # undef rsvg_handle_new
9107 # undef rsvg_handle_set_base_uri
9108 # undef rsvg_handle_write
9110 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9111 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9112 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9113 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9114 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9115 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9116 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9117 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9118 # define g_clear_error fn_g_clear_error
9119 # define g_object_unref fn_g_object_unref
9120 # define g_type_init fn_g_type_init
9121 # define rsvg_handle_close fn_rsvg_handle_close
9122 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9123 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9124 # define rsvg_handle_new fn_rsvg_handle_new
9125 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9126 # define rsvg_handle_write fn_rsvg_handle_write
9128 # endif /* !WINDOWSNT */
9130 /* Load SVG image IMG for use on frame F. Value is true if
9131 successful. */
9133 static bool
9134 svg_load (struct frame *f, struct image *img)
9136 bool success_p = 0;
9137 Lisp_Object file_name;
9139 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9140 file_name = image_spec_value (img->spec, QCfile, NULL);
9141 if (STRINGP (file_name))
9143 int fd;
9144 Lisp_Object file = x_find_image_fd (file_name, &fd);
9145 if (!STRINGP (file))
9147 image_error ("Cannot find image file `%s'", file_name);
9148 return 0;
9151 /* Read the entire file into memory. */
9152 ptrdiff_t size;
9153 unsigned char *contents = slurp_file (fd, &size);
9154 if (contents == NULL)
9156 image_error ("Error loading SVG image `%s'", file);
9157 return 0;
9159 /* If the file was slurped into memory properly, parse it. */
9160 success_p = svg_load_image (f, img, contents, size,
9161 SSDATA (ENCODE_FILE (file)));
9162 xfree (contents);
9164 /* Else its not a file, its a lisp object. Load the image from a
9165 lisp object rather than a file. */
9166 else
9168 Lisp_Object data, original_filename;
9170 data = image_spec_value (img->spec, QCdata, NULL);
9171 if (!STRINGP (data))
9173 image_error ("Invalid image data `%s'", data);
9174 return 0;
9176 original_filename = BVAR (current_buffer, filename);
9177 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data),
9178 (NILP (original_filename) ? NULL
9179 : SSDATA (original_filename)));
9182 return success_p;
9185 /* svg_load_image is a helper function for svg_load, which does the
9186 actual loading given contents and size, apart from frame and image
9187 structures, passed from svg_load.
9189 Uses librsvg to do most of the image processing.
9191 Returns true when successful. */
9192 static bool
9193 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
9194 struct image *img, /* Pointer to emacs image structure. */
9195 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
9196 ptrdiff_t size, /* Size of data in bytes. */
9197 char *filename) /* Name of SVG file being loaded. */
9199 RsvgHandle *rsvg_handle;
9200 RsvgDimensionData dimension_data;
9201 GError *err = NULL;
9202 GdkPixbuf *pixbuf;
9203 int width;
9204 int height;
9205 const guint8 *pixels;
9206 int rowstride;
9208 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9209 /* g_type_init is a glib function that must be called prior to
9210 using gnome type library functions (obsolete since 2.36.0). */
9211 g_type_init ();
9212 #endif
9214 /* Make a handle to a new rsvg object. */
9215 rsvg_handle = rsvg_handle_new ();
9217 /* Set base_uri for properly handling referenced images (via 'href').
9218 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9219 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9220 if (filename)
9221 rsvg_handle_set_base_uri(rsvg_handle, filename);
9223 /* Parse the contents argument and fill in the rsvg_handle. */
9224 rsvg_handle_write (rsvg_handle, contents, size, &err);
9225 if (err) goto rsvg_error;
9227 /* The parsing is complete, rsvg_handle is ready to used, close it
9228 for further writes. */
9229 rsvg_handle_close (rsvg_handle, &err);
9230 if (err) goto rsvg_error;
9232 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
9233 if (! check_image_size (f, dimension_data.width, dimension_data.height))
9235 image_size_error ();
9236 goto rsvg_error;
9239 /* We can now get a valid pixel buffer from the svg file, if all
9240 went ok. */
9241 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
9242 if (!pixbuf) goto rsvg_error;
9243 g_object_unref (rsvg_handle);
9245 /* Extract some meta data from the svg handle. */
9246 width = gdk_pixbuf_get_width (pixbuf);
9247 height = gdk_pixbuf_get_height (pixbuf);
9248 pixels = gdk_pixbuf_get_pixels (pixbuf);
9249 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
9251 /* Validate the svg meta data. */
9252 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
9253 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
9254 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
9255 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
9257 #ifdef USE_CAIRO
9259 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
9260 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
9262 for (int y = 0; y < height; ++y)
9264 const guchar *iconptr = pixels + y * rowstride;
9265 uint32_t *dataptr = (uint32_t *) (data + y * rowstride);
9267 for (int x = 0; x < width; ++x)
9269 if (iconptr[3] == 0)
9270 *dataptr = bgcolor;
9271 else
9272 *dataptr = (iconptr[0] << 16)
9273 | (iconptr[1] << 8)
9274 | iconptr[2]
9275 | (iconptr[3] << 24);
9277 iconptr += 4;
9278 ++dataptr;
9282 create_cairo_image_surface (img, data, width, height);
9283 g_object_unref (pixbuf);
9285 #else
9286 /* Try to create a x pixmap to hold the svg pixmap. */
9287 XImagePtr ximg;
9288 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
9290 g_object_unref (pixbuf);
9291 return 0;
9294 init_color_table ();
9296 /* Handle alpha channel by combining the image with a background
9297 color. */
9298 XColor background;
9299 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
9300 if (!STRINGP (specified_bg)
9301 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
9302 x_query_frame_background_color (f, &background);
9304 /* SVG pixmaps specify transparency in the last byte, so right
9305 shift 8 bits to get rid of it, since emacs doesn't support
9306 transparency. */
9307 background.red >>= 8;
9308 background.green >>= 8;
9309 background.blue >>= 8;
9311 /* This loop handles opacity values, since Emacs assumes
9312 non-transparent images. Each pixel must be "flattened" by
9313 calculating the resulting color, given the transparency of the
9314 pixel, and the image background color. */
9315 for (int y = 0; y < height; ++y)
9317 for (int x = 0; x < width; ++x)
9319 int red;
9320 int green;
9321 int blue;
9322 int opacity;
9324 red = *pixels++;
9325 green = *pixels++;
9326 blue = *pixels++;
9327 opacity = *pixels++;
9329 red = ((red * opacity)
9330 + (background.red * ((1 << 8) - opacity)));
9331 green = ((green * opacity)
9332 + (background.green * ((1 << 8) - opacity)));
9333 blue = ((blue * opacity)
9334 + (background.blue * ((1 << 8) - opacity)));
9336 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9339 pixels += rowstride - 4 * width;
9342 #ifdef COLOR_TABLE_SUPPORT
9343 /* Remember colors allocated for this image. */
9344 img->colors = colors_in_color_table (&img->ncolors);
9345 free_color_table ();
9346 #endif /* COLOR_TABLE_SUPPORT */
9348 g_object_unref (pixbuf);
9350 img->width = width;
9351 img->height = height;
9353 /* Maybe fill in the background field while we have ximg handy.
9354 Casting avoids a GCC warning. */
9355 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9357 /* Put ximg into the image. */
9358 image_put_x_image (f, img, ximg, 0);
9359 #endif /* ! USE_CAIRO */
9361 return 1;
9363 rsvg_error:
9364 g_object_unref (rsvg_handle);
9365 /* FIXME: Use error->message so the user knows what is the actual
9366 problem with the image. */
9367 image_error ("Error parsing SVG image `%s'", img->spec);
9368 g_clear_error (&err);
9369 return 0;
9372 #endif /* defined (HAVE_RSVG) */
9377 /***********************************************************************
9378 Ghostscript
9379 ***********************************************************************/
9381 #ifdef HAVE_X_WINDOWS
9382 #define HAVE_GHOSTSCRIPT 1
9383 #endif /* HAVE_X_WINDOWS */
9385 #ifdef HAVE_GHOSTSCRIPT
9387 static bool gs_image_p (Lisp_Object object);
9388 static bool gs_load (struct frame *f, struct image *img);
9389 static void gs_clear_image (struct frame *f, struct image *img);
9391 /* Indices of image specification fields in gs_format, below. */
9393 enum gs_keyword_index
9395 GS_TYPE,
9396 GS_PT_WIDTH,
9397 GS_PT_HEIGHT,
9398 GS_FILE,
9399 GS_LOADER,
9400 GS_BOUNDING_BOX,
9401 GS_ASCENT,
9402 GS_MARGIN,
9403 GS_RELIEF,
9404 GS_ALGORITHM,
9405 GS_HEURISTIC_MASK,
9406 GS_MASK,
9407 GS_BACKGROUND,
9408 GS_LAST
9411 /* Vector of image_keyword structures describing the format
9412 of valid user-defined image specifications. */
9414 static const struct image_keyword gs_format[GS_LAST] =
9416 {":type", IMAGE_SYMBOL_VALUE, 1},
9417 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9418 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9419 {":file", IMAGE_STRING_VALUE, 1},
9420 {":loader", IMAGE_FUNCTION_VALUE, 0},
9421 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9422 {":ascent", IMAGE_ASCENT_VALUE, 0},
9423 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9424 {":relief", IMAGE_INTEGER_VALUE, 0},
9425 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9426 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9427 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9428 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9431 /* Structure describing the image type `ghostscript'. */
9433 static struct image_type gs_type =
9435 SYMBOL_INDEX (Qpostscript),
9436 gs_image_p,
9437 gs_load,
9438 gs_clear_image,
9439 NULL,
9440 NULL
9444 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9446 static void
9447 gs_clear_image (struct frame *f, struct image *img)
9449 x_clear_image (f, img);
9453 /* Return true if OBJECT is a valid Ghostscript image
9454 specification. */
9456 static bool
9457 gs_image_p (Lisp_Object object)
9459 struct image_keyword fmt[GS_LAST];
9460 Lisp_Object tem;
9461 int i;
9463 memcpy (fmt, gs_format, sizeof fmt);
9465 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9466 return 0;
9468 /* Bounding box must be a list or vector containing 4 integers. */
9469 tem = fmt[GS_BOUNDING_BOX].value;
9470 if (CONSP (tem))
9472 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9473 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9474 return 0;
9475 if (!NILP (tem))
9476 return 0;
9478 else if (VECTORP (tem))
9480 if (ASIZE (tem) != 4)
9481 return 0;
9482 for (i = 0; i < 4; ++i)
9483 if (!INTEGERP (AREF (tem, i)))
9484 return 0;
9486 else
9487 return 0;
9489 return 1;
9493 /* Load Ghostscript image IMG for use on frame F. Value is true
9494 if successful. */
9496 static bool
9497 gs_load (struct frame *f, struct image *img)
9499 uprintmax_t printnum1, printnum2;
9500 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9501 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9502 Lisp_Object frame;
9503 double in_width, in_height;
9504 Lisp_Object pixel_colors = Qnil;
9506 /* Compute pixel size of pixmap needed from the given size in the
9507 image specification. Sizes in the specification are in pt. 1 pt
9508 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9509 info. */
9510 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9511 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9512 in_width *= FRAME_RES_X (f);
9513 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9514 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9515 in_height *= FRAME_RES_Y (f);
9517 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9518 && check_image_size (f, in_width, in_height)))
9520 image_size_error ();
9521 return 0;
9523 img->width = in_width;
9524 img->height = in_height;
9526 /* Create the pixmap. */
9527 eassert (img->pixmap == NO_PIXMAP);
9529 if (x_check_image_size (0, img->width, img->height))
9531 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9532 block_input ();
9533 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9534 img->width, img->height,
9535 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9536 unblock_input ();
9539 if (!img->pixmap)
9541 image_error ("Unable to create pixmap for `%s'" , img->spec);
9542 return 0;
9545 /* Call the loader to fill the pixmap. It returns a process object
9546 if successful. We do not record_unwind_protect here because
9547 other places in redisplay like calling window scroll functions
9548 don't either. Let the Lisp loader use `unwind-protect' instead. */
9549 printnum1 = FRAME_X_WINDOW (f);
9550 printnum2 = img->pixmap;
9551 window_and_pixmap_id
9552 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9554 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9555 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9556 pixel_colors
9557 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9559 XSETFRAME (frame, f);
9560 loader = image_spec_value (img->spec, QCloader, NULL);
9561 if (NILP (loader))
9562 loader = intern ("gs-load-image");
9564 img->lisp_data = call6 (loader, frame, img->spec,
9565 make_number (img->width),
9566 make_number (img->height),
9567 window_and_pixmap_id,
9568 pixel_colors);
9569 return PROCESSP (img->lisp_data);
9573 /* Kill the Ghostscript process that was started to fill PIXMAP on
9574 frame F. Called from XTread_socket when receiving an event
9575 telling Emacs that Ghostscript has finished drawing. */
9577 void
9578 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9580 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9581 ptrdiff_t i;
9582 struct image *img;
9584 /* Find the image containing PIXMAP. */
9585 for (i = 0; i < c->used; ++i)
9586 if (c->images[i]->pixmap == pixmap)
9587 break;
9589 /* Should someone in between have cleared the image cache, for
9590 instance, give up. */
9591 if (i == c->used)
9592 return;
9594 /* Kill the GS process. We should have found PIXMAP in the image
9595 cache and its image should contain a process object. */
9596 img = c->images[i];
9597 eassert (PROCESSP (img->lisp_data));
9598 Fkill_process (img->lisp_data, Qnil);
9599 img->lisp_data = Qnil;
9601 #if defined (HAVE_X_WINDOWS)
9603 /* On displays with a mutable colormap, figure out the colors
9604 allocated for the image by looking at the pixels of an XImage for
9605 img->pixmap. */
9606 if (x_mutable_colormap (FRAME_X_VISUAL (f)))
9608 XImagePtr ximg;
9610 block_input ();
9612 /* Try to get an XImage for img->pixmep. */
9613 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9614 0, 0, img->width, img->height, ~0, ZPixmap);
9615 if (ximg)
9617 /* Initialize the color table. */
9618 init_color_table ();
9620 /* For each pixel of the image, look its color up in the
9621 color table. After having done so, the color table will
9622 contain an entry for each color used by the image. */
9623 #ifdef COLOR_TABLE_SUPPORT
9624 for (int y = 0; y < img->height; ++y)
9625 for (int x = 0; x < img->width; ++x)
9627 unsigned long pixel = XGetPixel (ximg, x, y);
9629 lookup_pixel_color (f, pixel);
9632 /* Record colors in the image. Free color table and XImage. */
9633 img->colors = colors_in_color_table (&img->ncolors);
9634 free_color_table ();
9635 #endif
9636 XDestroyImage (ximg);
9638 #if 0 /* This doesn't seem to be the case. If we free the colors
9639 here, we get a BadAccess later in x_clear_image when
9640 freeing the colors. */
9641 /* We have allocated colors once, but Ghostscript has also
9642 allocated colors on behalf of us. So, to get the
9643 reference counts right, free them once. */
9644 if (img->ncolors)
9645 x_free_colors (f, img->colors, img->ncolors);
9646 #endif
9648 else
9649 image_error ("Cannot get X image of `%s'; colors will not be freed",
9650 img->spec);
9652 unblock_input ();
9654 #endif /* HAVE_X_WINDOWS */
9656 /* Now that we have the pixmap, compute mask and transform the
9657 image if requested. */
9658 block_input ();
9659 postprocess_image (f, img);
9660 unblock_input ();
9663 #endif /* HAVE_GHOSTSCRIPT */
9666 /***********************************************************************
9667 Tests
9668 ***********************************************************************/
9670 #ifdef GLYPH_DEBUG
9672 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9673 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9674 (Lisp_Object spec)
9676 return valid_image_p (spec) ? Qt : Qnil;
9680 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0,
9681 doc: /* */)
9682 (Lisp_Object spec)
9684 ptrdiff_t id = -1;
9686 if (valid_image_p (spec))
9687 id = lookup_image (SELECTED_FRAME (), spec);
9689 debug_print (spec);
9690 return make_number (id);
9693 #endif /* GLYPH_DEBUG */
9696 /***********************************************************************
9697 Initialization
9698 ***********************************************************************/
9700 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9701 doc: /* Initialize image library implementing image type TYPE.
9702 Return non-nil if TYPE is a supported image type.
9704 If image libraries are loaded dynamically (currently only the case on
9705 MS-Windows), load the library for TYPE if it is not yet loaded, using
9706 the library file(s) specified by `dynamic-library-alist'. */)
9707 (Lisp_Object type)
9709 return lookup_image_type (type) ? Qt : Qnil;
9712 /* Look up image type TYPE, and return a pointer to its image_type
9713 structure. Return 0 if TYPE is not a known image type. */
9715 static struct image_type *
9716 lookup_image_type (Lisp_Object type)
9718 /* Types pbm and xbm are built-in and always available. */
9719 if (EQ (type, Qpbm))
9720 return define_image_type (&pbm_type);
9722 if (EQ (type, Qxbm))
9723 return define_image_type (&xbm_type);
9725 #if defined (HAVE_XPM) || defined (HAVE_NS)
9726 if (EQ (type, Qxpm))
9727 return define_image_type (&xpm_type);
9728 #endif
9730 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9731 if (EQ (type, Qjpeg))
9732 return define_image_type (&jpeg_type);
9733 #endif
9735 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9736 if (EQ (type, Qtiff))
9737 return define_image_type (&tiff_type);
9738 #endif
9740 #if defined (HAVE_GIF) || defined (HAVE_NS)
9741 if (EQ (type, Qgif))
9742 return define_image_type (&gif_type);
9743 #endif
9745 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9746 if (EQ (type, Qpng))
9747 return define_image_type (&png_type);
9748 #endif
9750 #if defined (HAVE_RSVG)
9751 if (EQ (type, Qsvg))
9752 return define_image_type (&svg_type);
9753 #endif
9755 #if defined (HAVE_IMAGEMAGICK)
9756 if (EQ (type, Qimagemagick))
9757 return define_image_type (&imagemagick_type);
9758 #endif
9760 #ifdef HAVE_GHOSTSCRIPT
9761 if (EQ (type, Qpostscript))
9762 return define_image_type (&gs_type);
9763 #endif
9765 return NULL;
9768 /* Reset image_types before dumping.
9769 Called from Fdump_emacs. */
9771 void
9772 reset_image_types (void)
9774 while (image_types)
9776 struct image_type *next = image_types->next;
9777 xfree (image_types);
9778 image_types = next;
9782 void
9783 syms_of_image (void)
9785 /* Initialize this only once; it will be reset before dumping. */
9786 image_types = NULL;
9788 /* Must be defined now because we're going to update it below, while
9789 defining the supported image types. */
9790 DEFVAR_LISP ("image-types", Vimage_types,
9791 doc: /* List of potentially supported image types.
9792 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9793 To check whether it is really supported, use `image-type-available-p'. */);
9794 Vimage_types = Qnil;
9796 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9797 doc: /* Maximum size of images.
9798 Emacs will not load an image into memory if its pixel width or
9799 pixel height exceeds this limit.
9801 If the value is an integer, it directly specifies the maximum
9802 image height and width, measured in pixels. If it is a floating
9803 point number, it specifies the maximum image height and width
9804 as a ratio to the frame height and width. If the value is
9805 non-numeric, there is no explicit limit on the size of images. */);
9806 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9808 /* Other symbols. */
9809 DEFSYM (Qcount, "count");
9810 DEFSYM (Qextension_data, "extension-data");
9811 DEFSYM (Qdelay, "delay");
9813 /* Keywords. */
9814 DEFSYM (QCascent, ":ascent");
9815 DEFSYM (QCmargin, ":margin");
9816 DEFSYM (QCrelief, ":relief");
9817 DEFSYM (QCconversion, ":conversion");
9818 DEFSYM (QCcolor_symbols, ":color-symbols");
9819 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9820 DEFSYM (QCindex, ":index");
9821 DEFSYM (QCcrop, ":crop");
9822 DEFSYM (QCrotation, ":rotation");
9823 DEFSYM (QCmatrix, ":matrix");
9824 DEFSYM (QCscale, ":scale");
9825 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9826 DEFSYM (QCmask, ":mask");
9828 /* Other symbols. */
9829 DEFSYM (Qlaplace, "laplace");
9830 DEFSYM (Qemboss, "emboss");
9831 DEFSYM (Qedge_detection, "edge-detection");
9832 DEFSYM (Qheuristic, "heuristic");
9834 DEFSYM (Qpostscript, "postscript");
9835 DEFSYM (QCmax_width, ":max-width");
9836 DEFSYM (QCmax_height, ":max-height");
9837 #ifdef HAVE_GHOSTSCRIPT
9838 ADD_IMAGE_TYPE (Qpostscript);
9839 DEFSYM (QCloader, ":loader");
9840 DEFSYM (QCpt_width, ":pt-width");
9841 DEFSYM (QCpt_height, ":pt-height");
9842 #endif /* HAVE_GHOSTSCRIPT */
9844 #ifdef HAVE_NTGUI
9845 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9846 or -1 if no PNG/GIF support was compiled in. This is tested by
9847 w32-win.el to correctly set up the alist used to search for the
9848 respective image libraries. */
9849 DEFSYM (Qlibpng_version, "libpng-version");
9850 Fset (Qlibpng_version,
9851 #if HAVE_PNG
9852 make_number (PNG_LIBPNG_VER)
9853 #else
9854 make_number (-1)
9855 #endif
9857 DEFSYM (Qlibgif_version, "libgif-version");
9858 Fset (Qlibgif_version,
9859 #ifdef HAVE_GIF
9860 make_number (GIFLIB_MAJOR * 10000
9861 + GIFLIB_MINOR * 100
9862 + GIFLIB_RELEASE)
9863 #else
9864 make_number (-1)
9865 #endif
9867 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9868 Fset (Qlibjpeg_version,
9869 #if HAVE_JPEG
9870 make_number (JPEG_LIB_VERSION)
9871 #else
9872 make_number (-1)
9873 #endif
9875 #endif
9877 DEFSYM (Qpbm, "pbm");
9878 ADD_IMAGE_TYPE (Qpbm);
9880 DEFSYM (Qxbm, "xbm");
9881 ADD_IMAGE_TYPE (Qxbm);
9883 #if defined (HAVE_XPM) || defined (HAVE_NS)
9884 DEFSYM (Qxpm, "xpm");
9885 ADD_IMAGE_TYPE (Qxpm);
9886 #endif
9888 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9889 DEFSYM (Qjpeg, "jpeg");
9890 ADD_IMAGE_TYPE (Qjpeg);
9891 #endif
9893 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9894 DEFSYM (Qtiff, "tiff");
9895 ADD_IMAGE_TYPE (Qtiff);
9896 #endif
9898 #if defined (HAVE_GIF) || defined (HAVE_NS)
9899 DEFSYM (Qgif, "gif");
9900 ADD_IMAGE_TYPE (Qgif);
9901 #endif
9903 #if defined (HAVE_PNG) || defined (HAVE_NS)
9904 DEFSYM (Qpng, "png");
9905 ADD_IMAGE_TYPE (Qpng);
9906 #endif
9908 #if defined (HAVE_IMAGEMAGICK)
9909 DEFSYM (Qimagemagick, "imagemagick");
9910 ADD_IMAGE_TYPE (Qimagemagick);
9911 #endif
9913 #if defined (HAVE_RSVG)
9914 DEFSYM (Qsvg, "svg");
9915 ADD_IMAGE_TYPE (Qsvg);
9916 #ifdef HAVE_NTGUI
9917 /* Other libraries used directly by svg code. */
9918 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9919 DEFSYM (Qglib, "glib");
9920 DEFSYM (Qgobject, "gobject");
9921 #endif /* HAVE_NTGUI */
9922 #endif /* HAVE_RSVG */
9924 defsubr (&Sinit_image_library);
9925 #ifdef HAVE_IMAGEMAGICK
9926 defsubr (&Simagemagick_types);
9927 #endif
9928 defsubr (&Sclear_image_cache);
9929 defsubr (&Simage_flush);
9930 defsubr (&Simage_size);
9931 defsubr (&Simage_mask_p);
9932 defsubr (&Simage_metadata);
9934 #ifdef GLYPH_DEBUG
9935 defsubr (&Simagep);
9936 defsubr (&Slookup_image);
9937 #endif
9939 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9940 doc: /* Non-nil means always draw a cross over disabled images.
9941 Disabled images are those having a `:conversion disabled' property.
9942 A cross is always drawn on black & white displays. */);
9943 cross_disabled_images = 0;
9945 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9946 doc: /* List of directories to search for window system bitmap files. */);
9947 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9949 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9950 doc: /* Maximum time after which images are removed from the cache.
9951 When an image has not been displayed this many seconds, Emacs
9952 automatically removes it from the image cache. If the cache contains
9953 a large number of images, the actual eviction time may be shorter.
9954 The value can also be nil, meaning the cache is never cleared.
9956 The function `clear-image-cache' disregards this variable. */);
9957 Vimage_cache_eviction_delay = make_number (300);
9958 #ifdef HAVE_IMAGEMAGICK
9959 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9960 doc: /* Integer indicating which ImageMagick rendering method to use.
9961 The options are:
9962 0 -- the default method (pixel pushing)
9963 1 -- a newer method ("MagickExportImagePixels") that may perform
9964 better (speed etc) in some cases, but has not been as thoroughly
9965 tested with Emacs as the default method. This method requires
9966 ImageMagick version 6.4.6 (approximately) or later.
9967 */);
9968 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9969 imagemagick_render_type = 0;
9970 #endif