* admin/release-process: Improve wording.
[emacs.git] / src / image.c
blob544435eac0b1c2fea4cfe0aa1175a6d1e9efdb31
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2015 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 #define COLOR_TABLE_SUPPORT 1
62 typedef struct x_bitmap_record Bitmap_Record;
63 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
64 #define NO_PIXMAP None
66 #define PIX_MASK_RETAIN 0
67 #define PIX_MASK_DRAW 1
68 #endif /* HAVE_X_WINDOWS */
70 #ifdef HAVE_NTGUI
72 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
73 #ifdef WINDOWSNT
74 # include "w32.h"
75 #endif
77 /* W32_TODO : Color tables on W32. */
78 #undef COLOR_TABLE_SUPPORT
80 typedef struct w32_bitmap_record Bitmap_Record;
81 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
82 #define NO_PIXMAP 0
84 #define PIX_MASK_RETAIN 0
85 #define PIX_MASK_DRAW 1
87 #define x_defined_color w32_defined_color
88 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
90 #endif /* HAVE_NTGUI */
92 #ifdef USE_CAIRO
93 #undef COLOR_TABLE_SUPPORT
94 #endif
96 #ifdef HAVE_NS
97 #undef COLOR_TABLE_SUPPORT
99 typedef struct ns_bitmap_record Bitmap_Record;
101 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
102 #define NO_PIXMAP 0
104 #define PIX_MASK_RETAIN 0
105 #define PIX_MASK_DRAW 1
107 #define x_defined_color(f, name, color_def, alloc) \
108 ns_defined_color (f, name, color_def, alloc, 0)
109 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
110 #endif /* HAVE_NS */
112 static void x_disable_image (struct frame *, struct image *);
113 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
114 Lisp_Object);
116 static void init_color_table (void);
117 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
118 #ifdef COLOR_TABLE_SUPPORT
119 static void free_color_table (void);
120 static unsigned long *colors_in_color_table (int *n);
121 #endif
123 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
124 id, which is just an int that this section returns. Bitmaps are
125 reference counted so they can be shared among frames.
127 Bitmap indices are guaranteed to be > 0, so a negative number can
128 be used to indicate no bitmap.
130 If you use x_create_bitmap_from_data, then you must keep track of
131 the bitmaps yourself. That is, creating a bitmap from the same
132 data more than once will not be caught. */
134 #ifdef HAVE_NS
135 /* Use with images created by ns_image_for_XPM. */
136 static unsigned long
137 XGetPixel (XImagePtr ximage, int x, int y)
139 return ns_get_pixel (ximage, x, y);
142 /* Use with images created by ns_image_for_XPM; alpha set to 1;
143 pixel is assumed to be in RGB form. */
144 static void
145 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
147 ns_put_pixel (ximage, x, y, pixel);
149 #endif /* HAVE_NS */
152 /* Functions to access the contents of a bitmap, given an id. */
154 #ifdef HAVE_X_WINDOWS
155 static int
156 x_bitmap_height (struct frame *f, ptrdiff_t id)
158 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
161 static int
162 x_bitmap_width (struct frame *f, ptrdiff_t id)
164 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
166 #endif
168 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
169 ptrdiff_t
170 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
172 /* HAVE_NTGUI needs the explicit cast here. */
173 return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
175 #endif
177 #ifdef HAVE_X_WINDOWS
179 x_bitmap_mask (struct frame *f, ptrdiff_t id)
181 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
183 #endif
185 /* Allocate a new bitmap record. Returns index of new record. */
187 static ptrdiff_t
188 x_allocate_bitmap_record (struct frame *f)
190 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
191 ptrdiff_t i;
193 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
194 return ++dpyinfo->bitmaps_last;
196 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
197 if (dpyinfo->bitmaps[i].refcount == 0)
198 return i + 1;
200 dpyinfo->bitmaps =
201 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
202 10, -1, sizeof *dpyinfo->bitmaps);
203 return ++dpyinfo->bitmaps_last;
206 /* Add one reference to the reference count of the bitmap with id ID. */
208 void
209 x_reference_bitmap (struct frame *f, ptrdiff_t id)
211 ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
214 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
216 ptrdiff_t
217 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
219 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
220 ptrdiff_t id;
222 #ifdef HAVE_X_WINDOWS
223 Pixmap bitmap;
224 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
225 bits, width, height);
226 if (! bitmap)
227 return -1;
228 #endif /* HAVE_X_WINDOWS */
230 #ifdef HAVE_NTGUI
231 Pixmap bitmap;
232 bitmap = CreateBitmap (width, height,
233 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
234 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
235 bits);
236 if (! bitmap)
237 return -1;
238 #endif /* HAVE_NTGUI */
240 #ifdef HAVE_NS
241 void *bitmap = ns_image_from_XBM (bits, width, height, 0, 0);
242 if (!bitmap)
243 return -1;
244 #endif
246 id = x_allocate_bitmap_record (f);
248 #ifdef HAVE_NS
249 dpyinfo->bitmaps[id - 1].img = bitmap;
250 dpyinfo->bitmaps[id - 1].depth = 1;
251 #endif
253 dpyinfo->bitmaps[id - 1].file = NULL;
254 dpyinfo->bitmaps[id - 1].height = height;
255 dpyinfo->bitmaps[id - 1].width = width;
256 dpyinfo->bitmaps[id - 1].refcount = 1;
258 #ifdef HAVE_X_WINDOWS
259 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
260 dpyinfo->bitmaps[id - 1].have_mask = false;
261 dpyinfo->bitmaps[id - 1].depth = 1;
262 #endif /* HAVE_X_WINDOWS */
264 #ifdef HAVE_NTGUI
265 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
266 dpyinfo->bitmaps[id - 1].hinst = NULL;
267 dpyinfo->bitmaps[id - 1].depth = 1;
268 #endif /* HAVE_NTGUI */
270 return id;
273 /* Create bitmap from file FILE for frame F. */
275 ptrdiff_t
276 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
278 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
280 #ifdef HAVE_NTGUI
281 return -1; /* W32_TODO : bitmap support */
282 #endif /* HAVE_NTGUI */
284 #ifdef HAVE_NS
285 ptrdiff_t id;
286 void *bitmap = ns_image_from_file (file);
288 if (!bitmap)
289 return -1;
292 id = x_allocate_bitmap_record (f);
293 dpyinfo->bitmaps[id - 1].img = bitmap;
294 dpyinfo->bitmaps[id - 1].refcount = 1;
295 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
296 dpyinfo->bitmaps[id - 1].depth = 1;
297 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
298 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
299 return id;
300 #endif
302 #ifdef HAVE_X_WINDOWS
303 unsigned int width, height;
304 Pixmap bitmap;
305 int xhot, yhot, result;
306 ptrdiff_t id;
307 Lisp_Object found;
308 char *filename;
310 /* Look for an existing bitmap with the same name. */
311 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
313 if (dpyinfo->bitmaps[id].refcount
314 && dpyinfo->bitmaps[id].file
315 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
317 ++dpyinfo->bitmaps[id].refcount;
318 return id + 1;
322 /* Search bitmap-file-path for the file, if appropriate. */
323 if (openp (Vx_bitmap_file_path, file, Qnil, &found,
324 make_number (R_OK), false)
325 < 0)
326 return -1;
328 filename = SSDATA (found);
330 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
331 filename, &width, &height, &bitmap, &xhot, &yhot);
332 if (result != BitmapSuccess)
333 return -1;
335 id = x_allocate_bitmap_record (f);
336 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
337 dpyinfo->bitmaps[id - 1].have_mask = false;
338 dpyinfo->bitmaps[id - 1].refcount = 1;
339 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
340 dpyinfo->bitmaps[id - 1].depth = 1;
341 dpyinfo->bitmaps[id - 1].height = height;
342 dpyinfo->bitmaps[id - 1].width = width;
344 return id;
345 #endif /* HAVE_X_WINDOWS */
348 /* Free bitmap B. */
350 static void
351 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
353 #ifdef HAVE_X_WINDOWS
354 XFreePixmap (dpyinfo->display, bm->pixmap);
355 if (bm->have_mask)
356 XFreePixmap (dpyinfo->display, bm->mask);
357 #endif /* HAVE_X_WINDOWS */
359 #ifdef HAVE_NTGUI
360 DeleteObject (bm->pixmap);
361 #endif /* HAVE_NTGUI */
363 #ifdef HAVE_NS
364 ns_release_object (bm->img);
365 #endif
367 if (bm->file)
369 xfree (bm->file);
370 bm->file = NULL;
374 /* Remove reference to bitmap with id number ID. */
376 void
377 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
379 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
381 if (id > 0)
383 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
385 if (--bm->refcount == 0)
387 block_input ();
388 free_bitmap_record (dpyinfo, bm);
389 unblock_input ();
394 /* Free all the bitmaps for the display specified by DPYINFO. */
396 void
397 x_destroy_all_bitmaps (Display_Info *dpyinfo)
399 ptrdiff_t i;
400 Bitmap_Record *bm = dpyinfo->bitmaps;
402 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
403 if (bm->refcount > 0)
404 free_bitmap_record (dpyinfo, bm);
406 dpyinfo->bitmaps_last = 0;
409 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
410 XImagePtr *, Pixmap *);
411 static void x_destroy_x_image (XImagePtr ximg);
413 #ifdef HAVE_NTGUI
414 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
415 bool, HGDIOBJ *);
416 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
417 HGDIOBJ);
418 #else
419 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
420 static void image_unget_x_image (struct image *, bool, XImagePtr);
421 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
422 image_get_x_image (f, img, mask_p)
423 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
424 image_unget_x_image (img, mask_p, ximg)
425 #endif
427 #ifdef HAVE_X_WINDOWS
429 static void image_sync_to_pixmaps (struct frame *, struct image *);
431 /* Useful functions defined in the section
432 `Image type independent image structures' below. */
434 static unsigned long four_corners_best (XImagePtr ximg,
435 int *corners,
436 unsigned long width,
437 unsigned long height);
440 /* Create a mask of a bitmap. Note is this not a perfect mask.
441 It's nicer with some borders in this context */
443 void
444 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
446 Pixmap pixmap, mask;
447 XImagePtr ximg, mask_img;
448 unsigned long width, height;
449 bool result;
450 unsigned long bg;
451 unsigned long x, y, xp, xm, yp, ym;
452 GC gc;
454 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
456 if (!(id > 0))
457 return;
459 pixmap = x_bitmap_pixmap (f, id);
460 width = x_bitmap_width (f, id);
461 height = x_bitmap_height (f, id);
463 block_input ();
464 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
465 ~0, ZPixmap);
467 if (!ximg)
469 unblock_input ();
470 return;
473 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
475 unblock_input ();
476 if (!result)
478 XDestroyImage (ximg);
479 return;
482 bg = four_corners_best (ximg, NULL, width, height);
484 for (y = 0; y < ximg->height; ++y)
486 for (x = 0; x < ximg->width; ++x)
488 xp = x != ximg->width - 1 ? x + 1 : 0;
489 xm = x != 0 ? x - 1 : ximg->width - 1;
490 yp = y != ximg->height - 1 ? y + 1 : 0;
491 ym = y != 0 ? y - 1 : ximg->height - 1;
492 if (XGetPixel (ximg, x, y) == bg
493 && XGetPixel (ximg, x, yp) == bg
494 && XGetPixel (ximg, x, ym) == bg
495 && XGetPixel (ximg, xp, y) == bg
496 && XGetPixel (ximg, xp, yp) == bg
497 && XGetPixel (ximg, xp, ym) == bg
498 && XGetPixel (ximg, xm, y) == bg
499 && XGetPixel (ximg, xm, yp) == bg
500 && XGetPixel (ximg, xm, ym) == bg)
501 XPutPixel (mask_img, x, y, 0);
502 else
503 XPutPixel (mask_img, x, y, 1);
507 eassert (input_blocked_p ());
508 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
509 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
510 width, height);
511 XFreeGC (FRAME_X_DISPLAY (f), gc);
513 dpyinfo->bitmaps[id - 1].have_mask = true;
514 dpyinfo->bitmaps[id - 1].mask = mask;
516 XDestroyImage (ximg);
517 x_destroy_x_image (mask_img);
520 #endif /* HAVE_X_WINDOWS */
522 /***********************************************************************
523 Image types
524 ***********************************************************************/
526 /* List of supported image types. Use define_image_type to add new
527 types. Use lookup_image_type to find a type for a given symbol. */
529 static struct image_type *image_types;
531 /* Forward function prototypes. */
533 static struct image_type *lookup_image_type (Lisp_Object);
534 static void x_laplace (struct frame *, struct image *);
535 static void x_emboss (struct frame *, struct image *);
536 static void x_build_heuristic_mask (struct frame *, struct image *,
537 Lisp_Object);
538 #ifdef WINDOWSNT
539 #define CACHE_IMAGE_TYPE(type, status) \
540 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
541 #else
542 #define CACHE_IMAGE_TYPE(type, status)
543 #endif
545 #define ADD_IMAGE_TYPE(type) \
546 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
548 /* Define a new image type from TYPE. This adds a copy of TYPE to
549 image_types and caches the loading status of TYPE. */
551 static struct image_type *
552 define_image_type (struct image_type *type)
554 struct image_type *p = NULL;
555 int new_type = type->type;
556 bool type_valid = true;
558 block_input ();
560 for (p = image_types; p; p = p->next)
561 if (p->type == new_type)
562 goto done;
564 if (type->init)
566 #if defined HAVE_NTGUI && defined WINDOWSNT
567 /* If we failed to load the library before, don't try again. */
568 Lisp_Object tested = Fassq (builtin_lisp_symbol (new_type),
569 Vlibrary_cache);
570 if (CONSP (tested) && NILP (XCDR (tested)))
571 type_valid = false;
572 else
573 #endif
575 type_valid = type->init ();
576 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type),
577 type_valid ? Qt : Qnil);
581 if (type_valid)
583 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
584 The initialized data segment is read-only. */
585 p = xmalloc (sizeof *p);
586 *p = *type;
587 p->next = image_types;
588 image_types = p;
591 done:
592 unblock_input ();
593 return p;
597 /* Value is true if OBJECT is a valid Lisp image specification. A
598 valid image specification is a list whose car is the symbol
599 `image', and whose rest is a property list. The property list must
600 contain a value for key `:type'. That value must be the name of a
601 supported image type. The rest of the property list depends on the
602 image type. */
604 bool
605 valid_image_p (Lisp_Object object)
607 bool valid_p = 0;
609 if (IMAGEP (object))
611 Lisp_Object tem;
613 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
614 if (EQ (XCAR (tem), QCtype))
616 tem = XCDR (tem);
617 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
619 struct image_type *type;
620 type = lookup_image_type (XCAR (tem));
621 if (type)
622 valid_p = type->valid_p (object);
625 break;
629 return valid_p;
633 /* Log error message with format string FORMAT and trailing arguments.
634 Signaling an error, e.g. when an image cannot be loaded, is not a
635 good idea because this would interrupt redisplay, and the error
636 message display would lead to another redisplay. This function
637 therefore simply displays a message. */
639 static void
640 image_error (const char *format, ...)
642 va_list ap;
643 va_start (ap, format);
644 vadd_to_log (format, ap);
645 va_end (ap);
648 static void
649 image_size_error (void)
651 image_error ("Invalid image size (see `max-image-size')");
655 /***********************************************************************
656 Image specifications
657 ***********************************************************************/
659 enum image_value_type
661 IMAGE_DONT_CHECK_VALUE_TYPE,
662 IMAGE_STRING_VALUE,
663 IMAGE_STRING_OR_NIL_VALUE,
664 IMAGE_SYMBOL_VALUE,
665 IMAGE_POSITIVE_INTEGER_VALUE,
666 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
667 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
668 IMAGE_ASCENT_VALUE,
669 IMAGE_INTEGER_VALUE,
670 IMAGE_FUNCTION_VALUE,
671 IMAGE_NUMBER_VALUE,
672 IMAGE_BOOL_VALUE
675 /* Structure used when parsing image specifications. */
677 struct image_keyword
679 /* Name of keyword. */
680 const char *name;
682 /* The type of value allowed. */
683 enum image_value_type type;
685 /* True means key must be present. */
686 bool mandatory_p;
688 /* Used to recognize duplicate keywords in a property list. */
689 int count;
691 /* The value that was found. */
692 Lisp_Object value;
696 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
697 has the format (image KEYWORD VALUE ...). One of the keyword/
698 value pairs must be `:type TYPE'. KEYWORDS is a vector of
699 image_keywords structures of size NKEYWORDS describing other
700 allowed keyword/value pairs. Value is true if SPEC is valid. */
702 static bool
703 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
704 int nkeywords, Lisp_Object type)
706 int i;
707 Lisp_Object plist;
709 if (!IMAGEP (spec))
710 return 0;
712 plist = XCDR (spec);
713 while (CONSP (plist))
715 Lisp_Object key, value;
717 /* First element of a pair must be a symbol. */
718 key = XCAR (plist);
719 plist = XCDR (plist);
720 if (!SYMBOLP (key))
721 return 0;
723 /* There must follow a value. */
724 if (!CONSP (plist))
725 return 0;
726 value = XCAR (plist);
727 plist = XCDR (plist);
729 /* Find key in KEYWORDS. Error if not found. */
730 for (i = 0; i < nkeywords; ++i)
731 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
732 break;
734 if (i == nkeywords)
735 continue;
737 /* Record that we recognized the keyword. If a keywords
738 was found more than once, it's an error. */
739 keywords[i].value = value;
740 if (keywords[i].count > 1)
741 return 0;
742 ++keywords[i].count;
744 /* Check type of value against allowed type. */
745 switch (keywords[i].type)
747 case IMAGE_STRING_VALUE:
748 if (!STRINGP (value))
749 return 0;
750 break;
752 case IMAGE_STRING_OR_NIL_VALUE:
753 if (!STRINGP (value) && !NILP (value))
754 return 0;
755 break;
757 case IMAGE_SYMBOL_VALUE:
758 if (!SYMBOLP (value))
759 return 0;
760 break;
762 case IMAGE_POSITIVE_INTEGER_VALUE:
763 if (! RANGED_INTEGERP (1, value, INT_MAX))
764 return 0;
765 break;
767 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
768 if (RANGED_INTEGERP (0, value, INT_MAX))
769 break;
770 if (CONSP (value)
771 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
772 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
773 break;
774 return 0;
776 case IMAGE_ASCENT_VALUE:
777 if (SYMBOLP (value) && EQ (value, Qcenter))
778 break;
779 else if (RANGED_INTEGERP (0, value, 100))
780 break;
781 return 0;
783 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
784 /* Unlike the other integer-related cases, this one does not
785 verify that VALUE fits in 'int'. This is because callers
786 want EMACS_INT. */
787 if (!INTEGERP (value) || XINT (value) < 0)
788 return 0;
789 break;
791 case IMAGE_DONT_CHECK_VALUE_TYPE:
792 break;
794 case IMAGE_FUNCTION_VALUE:
795 value = indirect_function (value);
796 if (!NILP (Ffunctionp (value)))
797 break;
798 return 0;
800 case IMAGE_NUMBER_VALUE:
801 if (! NUMBERP (value))
802 return 0;
803 break;
805 case IMAGE_INTEGER_VALUE:
806 if (! TYPE_RANGED_INTEGERP (int, value))
807 return 0;
808 break;
810 case IMAGE_BOOL_VALUE:
811 if (!NILP (value) && !EQ (value, Qt))
812 return 0;
813 break;
815 default:
816 emacs_abort ();
817 break;
820 if (EQ (key, QCtype) && !EQ (type, value))
821 return 0;
824 /* Check that all mandatory fields are present. */
825 for (i = 0; i < nkeywords; ++i)
826 if (keywords[i].mandatory_p && keywords[i].count == 0)
827 return 0;
829 return NILP (plist);
833 /* Return the value of KEY in image specification SPEC. Value is nil
834 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
835 was found in SPEC. */
837 static Lisp_Object
838 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
840 Lisp_Object tail;
842 eassert (valid_image_p (spec));
844 for (tail = XCDR (spec);
845 CONSP (tail) && CONSP (XCDR (tail));
846 tail = XCDR (XCDR (tail)))
848 if (EQ (XCAR (tail), key))
850 if (found)
851 *found = 1;
852 return XCAR (XCDR (tail));
856 if (found)
857 *found = 0;
858 return Qnil;
862 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
863 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
864 PIXELS non-nil means return the size in pixels, otherwise return the
865 size in canonical character units.
866 FRAME is the frame on which the image will be displayed. FRAME nil
867 or omitted means use the selected frame. */)
868 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
870 Lisp_Object size;
872 size = Qnil;
873 if (valid_image_p (spec))
875 struct frame *f = decode_window_system_frame (frame);
876 ptrdiff_t id = lookup_image (f, spec);
877 struct image *img = IMAGE_FROM_ID (f, id);
878 int width = img->width + 2 * img->hmargin;
879 int height = img->height + 2 * img->vmargin;
881 if (NILP (pixels))
882 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
883 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
884 else
885 size = Fcons (make_number (width), make_number (height));
887 else
888 error ("Invalid image specification");
890 return size;
894 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
895 doc: /* Return t if image SPEC has a mask bitmap.
896 FRAME is the frame on which the image will be displayed. FRAME nil
897 or omitted means use the selected frame. */)
898 (Lisp_Object spec, Lisp_Object frame)
900 Lisp_Object mask;
902 mask = Qnil;
903 if (valid_image_p (spec))
905 struct frame *f = decode_window_system_frame (frame);
906 ptrdiff_t id = lookup_image (f, spec);
907 struct image *img = IMAGE_FROM_ID (f, id);
908 if (img->mask)
909 mask = Qt;
911 else
912 error ("Invalid image specification");
914 return mask;
917 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
918 doc: /* Return metadata for image SPEC.
919 FRAME is the frame on which the image will be displayed. FRAME nil
920 or omitted means use the selected frame. */)
921 (Lisp_Object spec, Lisp_Object frame)
923 Lisp_Object ext;
925 ext = Qnil;
926 if (valid_image_p (spec))
928 struct frame *f = decode_window_system_frame (frame);
929 ptrdiff_t id = lookup_image (f, spec);
930 struct image *img = IMAGE_FROM_ID (f, id);
931 ext = img->lisp_data;
934 return ext;
938 /***********************************************************************
939 Image type independent image structures
940 ***********************************************************************/
942 #define MAX_IMAGE_SIZE 10.0
943 /* Allocate and return a new image structure for image specification
944 SPEC. SPEC has a hash value of HASH. */
946 static struct image *
947 make_image (Lisp_Object spec, EMACS_UINT hash)
949 struct image *img = xzalloc (sizeof *img);
950 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
952 eassert (valid_image_p (spec));
953 img->dependencies = NILP (file) ? Qnil : list1 (file);
954 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
955 eassert (img->type != NULL);
956 img->spec = spec;
957 img->lisp_data = Qnil;
958 img->ascent = DEFAULT_IMAGE_ASCENT;
959 img->hash = hash;
960 img->corners[BOT_CORNER] = -1; /* Full image */
961 return img;
965 /* Free image IMG which was used on frame F, including its resources. */
967 static void
968 free_image (struct frame *f, struct image *img)
970 if (img)
972 struct image_cache *c = FRAME_IMAGE_CACHE (f);
974 /* Remove IMG from the hash table of its cache. */
975 if (img->prev)
976 img->prev->next = img->next;
977 else
978 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
980 if (img->next)
981 img->next->prev = img->prev;
983 c->images[img->id] = NULL;
985 /* Windows NT redefines 'free', but in this file, we need to
986 avoid the redefinition. */
987 #ifdef WINDOWSNT
988 #undef free
989 #endif
990 /* Free resources, then free IMG. */
991 img->type->free (f, img);
992 xfree (img);
996 /* Return true if the given widths and heights are valid for display. */
998 static bool
999 check_image_size (struct frame *f, int width, int height)
1001 int w, h;
1003 if (width <= 0 || height <= 0)
1004 return 0;
1006 if (INTEGERP (Vmax_image_size))
1007 return (width <= XINT (Vmax_image_size)
1008 && height <= XINT (Vmax_image_size));
1009 else if (FLOATP (Vmax_image_size))
1011 if (f != NULL)
1013 w = FRAME_PIXEL_WIDTH (f);
1014 h = FRAME_PIXEL_HEIGHT (f);
1016 else
1017 w = h = 1024; /* Arbitrary size for unknown frame. */
1018 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1019 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1021 else
1022 return 1;
1025 /* Prepare image IMG for display on frame F. Must be called before
1026 drawing an image. */
1028 void
1029 prepare_image_for_display (struct frame *f, struct image *img)
1031 /* We're about to display IMG, so set its timestamp to `now'. */
1032 img->timestamp = current_timespec ();
1034 #ifndef USE_CAIRO
1035 /* If IMG doesn't have a pixmap yet, load it now, using the image
1036 type dependent loader function. */
1037 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1038 img->load_failed_p = ! img->type->load (f, img);
1040 #ifdef HAVE_X_WINDOWS
1041 if (!img->load_failed_p)
1043 block_input ();
1044 image_sync_to_pixmaps (f, img);
1045 unblock_input ();
1047 #endif
1048 #endif
1052 /* Value is the number of pixels for the ascent of image IMG when
1053 drawn in face FACE. */
1056 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1058 int height;
1059 int ascent;
1061 if (slice->height == img->height)
1062 height = img->height + img->vmargin;
1063 else if (slice->y == 0)
1064 height = slice->height + img->vmargin;
1065 else
1066 height = slice->height;
1068 if (img->ascent == CENTERED_IMAGE_ASCENT)
1070 if (face->font)
1072 #ifdef HAVE_NTGUI
1073 /* W32 specific version. Why?. ++kfs */
1074 ascent = height / 2 - (FONT_DESCENT (face->font)
1075 - FONT_BASE (face->font)) / 2;
1076 #else
1077 /* This expression is arranged so that if the image can't be
1078 exactly centered, it will be moved slightly up. This is
1079 because a typical font is `top-heavy' (due to the presence
1080 uppercase letters), so the image placement should err towards
1081 being top-heavy too. It also just generally looks better. */
1082 ascent = (height + FONT_BASE (face->font)
1083 - FONT_DESCENT (face->font) + 1) / 2;
1084 #endif /* HAVE_NTGUI */
1086 else
1087 ascent = height / 2;
1089 else
1090 ascent = height * (img->ascent / 100.0);
1092 return ascent;
1095 #ifdef USE_CAIRO
1096 static uint32_t
1097 xcolor_to_argb32 (XColor xc)
1099 return (0xff << 24) | ((xc.red / 256) << 16)
1100 | ((xc.green / 256) << 8) | (xc.blue / 256);
1103 static uint32_t
1104 get_spec_bg_or_alpha_as_argb (struct image *img,
1105 struct frame *f)
1107 uint32_t bgcolor = 0;
1108 XColor xbgcolor;
1109 Lisp_Object bg = image_spec_value (img->spec, QCbackground, NULL);
1111 if (STRINGP (bg) && x_parse_color (f, SSDATA (bg), &xbgcolor))
1112 bgcolor = xcolor_to_argb32 (xbgcolor);
1114 return bgcolor;
1117 static void
1118 create_cairo_image_surface (struct image *img,
1119 unsigned char *data,
1120 int width,
1121 int height)
1123 cairo_surface_t *surface;
1124 cairo_format_t format = CAIRO_FORMAT_ARGB32;
1125 int stride = cairo_format_stride_for_width (format, width);
1126 surface = cairo_image_surface_create_for_data (data,
1127 format,
1128 width,
1129 height,
1130 stride);
1131 img->width = width;
1132 img->height = height;
1133 img->cr_data = surface;
1134 img->cr_data2 = data;
1135 img->pixmap = 0;
1137 #endif
1141 /* Image background colors. */
1143 /* Find the "best" corner color of a bitmap.
1144 On W32, XIMG is assumed to a device context with the bitmap selected. */
1146 static RGB_PIXEL_COLOR
1147 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1148 unsigned long width, unsigned long height)
1150 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1151 int i, best_count;
1153 if (corners && corners[BOT_CORNER] >= 0)
1155 /* Get the colors at the corner_pixels of ximg. */
1156 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1157 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1158 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1159 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1161 else
1163 /* Get the colors at the corner_pixels of ximg. */
1164 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1165 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1166 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1167 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1169 /* Choose the most frequently found color as background. */
1170 for (i = best_count = 0; i < 4; ++i)
1172 int j, n;
1174 for (j = n = 0; j < 4; ++j)
1175 if (corner_pixels[i] == corner_pixels[j])
1176 ++n;
1178 if (n > best_count)
1179 best = corner_pixels[i], best_count = n;
1182 return best;
1185 /* Portability macros */
1187 #ifdef HAVE_NTGUI
1189 #define Free_Pixmap(display, pixmap) \
1190 DeleteObject (pixmap)
1192 #elif defined (HAVE_NS)
1194 #define Free_Pixmap(display, pixmap) \
1195 ns_release_object (pixmap)
1197 #else
1199 #define Free_Pixmap(display, pixmap) \
1200 XFreePixmap (display, pixmap)
1202 #endif /* !HAVE_NTGUI && !HAVE_NS */
1205 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1206 it is guessed heuristically. If non-zero, XIMG is an existing
1207 XImage object (or device context with the image selected on W32) to
1208 use for the heuristic. */
1210 RGB_PIXEL_COLOR
1211 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1213 if (! img->background_valid)
1214 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1216 bool free_ximg = !ximg;
1217 #ifdef HAVE_NTGUI
1218 HGDIOBJ prev;
1219 #endif /* HAVE_NTGUI */
1221 if (free_ximg)
1222 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1224 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1226 if (free_ximg)
1227 image_unget_x_image_or_dc (img, 0, ximg, prev);
1229 img->background_valid = 1;
1232 return img->background;
1235 /* Return the `background_transparent' field of IMG. If IMG doesn't
1236 have one yet, it is guessed heuristically. If non-zero, MASK is an
1237 existing XImage object to use for the heuristic. */
1240 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1242 if (! img->background_transparent_valid)
1243 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1245 if (img->mask)
1247 bool free_mask = !mask;
1248 #ifdef HAVE_NTGUI
1249 HGDIOBJ prev;
1250 #endif /* HAVE_NTGUI */
1252 if (free_mask)
1253 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1255 img->background_transparent
1256 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1258 if (free_mask)
1259 image_unget_x_image_or_dc (img, 1, mask, prev);
1261 else
1262 img->background_transparent = 0;
1264 img->background_transparent_valid = 1;
1267 return img->background_transparent;
1270 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1271 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1273 /* Store F's background color into *BGCOLOR. */
1274 static void
1275 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1277 #ifndef HAVE_NS
1278 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1279 x_query_color (f, bgcolor);
1280 #else
1281 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1282 #endif
1285 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1287 /***********************************************************************
1288 Helper functions for X image types
1289 ***********************************************************************/
1291 /* Clear X resources of image IMG on frame F according to FLAGS.
1292 FLAGS is bitwise-or of the following masks:
1293 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1294 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1295 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1296 any. */
1298 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1299 #define CLEAR_IMAGE_MASK (1 << 1)
1300 #define CLEAR_IMAGE_COLORS (1 << 2)
1302 static void
1303 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1305 if (flags & CLEAR_IMAGE_PIXMAP)
1307 if (img->pixmap)
1309 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1310 img->pixmap = NO_PIXMAP;
1311 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1312 img->background_valid = 0;
1314 #ifdef HAVE_X_WINDOWS
1315 if (img->ximg)
1317 x_destroy_x_image (img->ximg);
1318 img->ximg = NULL;
1319 img->background_valid = 0;
1321 #endif
1324 if (flags & CLEAR_IMAGE_MASK)
1326 if (img->mask)
1328 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1329 img->mask = NO_PIXMAP;
1330 img->background_transparent_valid = 0;
1332 #ifdef HAVE_X_WINDOWS
1333 if (img->mask_img)
1335 x_destroy_x_image (img->mask_img);
1336 img->mask_img = NULL;
1337 img->background_transparent_valid = 0;
1339 #endif
1342 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1344 /* W32_TODO: color table support. */
1345 #ifdef HAVE_X_WINDOWS
1346 x_free_colors (f, img->colors, img->ncolors);
1347 #endif /* HAVE_X_WINDOWS */
1348 xfree (img->colors);
1349 img->colors = NULL;
1350 img->ncolors = 0;
1355 /* Free X resources of image IMG which is used on frame F. */
1357 static void
1358 x_clear_image (struct frame *f, struct image *img)
1360 block_input ();
1361 #ifdef USE_CAIRO
1362 if (img->cr_data)
1363 cairo_surface_destroy ((cairo_surface_t *)img->cr_data);
1364 if (img->cr_data2) xfree (img->cr_data2);
1365 #endif
1366 x_clear_image_1 (f, img,
1367 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1368 unblock_input ();
1372 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1373 cannot be allocated, use DFLT. Add a newly allocated color to
1374 IMG->colors, so that it can be freed again. Value is the pixel
1375 color. */
1377 static unsigned long
1378 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1379 unsigned long dflt)
1381 XColor color;
1382 unsigned long result;
1384 eassert (STRINGP (color_name));
1386 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1387 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1388 INT_MAX))
1390 /* This isn't called frequently so we get away with simply
1391 reallocating the color vector to the needed size, here. */
1392 ptrdiff_t ncolors = img->ncolors + 1;
1393 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1394 img->colors[ncolors - 1] = color.pixel;
1395 img->ncolors = ncolors;
1396 result = color.pixel;
1398 else
1399 result = dflt;
1401 return result;
1406 /***********************************************************************
1407 Image Cache
1408 ***********************************************************************/
1410 static void cache_image (struct frame *f, struct image *img);
1412 /* Return a new, initialized image cache that is allocated from the
1413 heap. Call free_image_cache to free an image cache. */
1415 struct image_cache *
1416 make_image_cache (void)
1418 struct image_cache *c = xmalloc (sizeof *c);
1420 c->size = 50;
1421 c->used = c->refcount = 0;
1422 c->images = xmalloc (c->size * sizeof *c->images);
1423 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1424 return c;
1428 /* Find an image matching SPEC in the cache, and return it. If no
1429 image is found, return NULL. */
1430 static struct image *
1431 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1433 struct image *img;
1434 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1435 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1437 if (!c) return NULL;
1439 /* If the image spec does not specify a background color, the cached
1440 image must have the same background color as the current frame.
1441 The foreground color must also match, for the sake of monochrome
1442 images.
1444 In fact, we could ignore the foreground color matching condition
1445 for color images, or if the image spec specifies :foreground;
1446 similarly we could ignore the background color matching condition
1447 for formats that don't use transparency (such as jpeg), or if the
1448 image spec specifies :background. However, the extra memory
1449 usage is probably negligible in practice, so we don't bother. */
1451 for (img = c->buckets[i]; img; img = img->next)
1452 if (img->hash == hash
1453 && !NILP (Fequal (img->spec, spec))
1454 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1455 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1456 break;
1457 return img;
1461 /* Search frame F for an image with spec SPEC, and free it. */
1463 static void
1464 uncache_image (struct frame *f, Lisp_Object spec)
1466 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1467 if (img)
1469 free_image (f, img);
1470 /* As display glyphs may still be referring to the image ID, we
1471 must garbage the frame (Bug#6426). */
1472 SET_FRAME_GARBAGED (f);
1477 /* Free image cache of frame F. Be aware that X frames share images
1478 caches. */
1480 void
1481 free_image_cache (struct frame *f)
1483 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1484 if (c)
1486 ptrdiff_t i;
1488 /* Cache should not be referenced by any frame when freed. */
1489 eassert (c->refcount == 0);
1491 for (i = 0; i < c->used; ++i)
1492 free_image (f, c->images[i]);
1493 xfree (c->images);
1494 xfree (c->buckets);
1495 xfree (c);
1496 FRAME_IMAGE_CACHE (f) = NULL;
1501 /* Clear image cache of frame F. FILTER=t means free all images.
1502 FILTER=nil means clear only images that haven't been
1503 displayed for some time.
1504 Else, only free the images which have FILTER in their `dependencies'.
1505 Should be called from time to time to reduce the number of loaded images.
1506 If image-cache-eviction-delay is non-nil, this frees images in the cache
1507 which weren't displayed for at least that many seconds. */
1509 static void
1510 clear_image_cache (struct frame *f, Lisp_Object filter)
1512 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1514 if (c)
1516 ptrdiff_t i, nfreed = 0;
1518 /* Block input so that we won't be interrupted by a SIGIO
1519 while being in an inconsistent state. */
1520 block_input ();
1522 if (!NILP (filter))
1524 /* Filter image cache. */
1525 for (i = 0; i < c->used; ++i)
1527 struct image *img = c->images[i];
1528 if (img && (EQ (Qt, filter)
1529 || !NILP (Fmember (filter, img->dependencies))))
1531 free_image (f, img);
1532 ++nfreed;
1536 else if (INTEGERP (Vimage_cache_eviction_delay))
1538 /* Free cache based on timestamp. */
1539 struct timespec old, t;
1540 double delay;
1541 ptrdiff_t nimages = 0;
1543 for (i = 0; i < c->used; ++i)
1544 if (c->images[i])
1545 nimages++;
1547 /* If the number of cached images has grown unusually large,
1548 decrease the cache eviction delay (Bug#6230). */
1549 delay = XINT (Vimage_cache_eviction_delay);
1550 if (nimages > 40)
1551 delay = 1600 * delay / nimages / nimages;
1552 delay = max (delay, 1);
1554 t = current_timespec ();
1555 old = timespec_sub (t, dtotimespec (delay));
1557 for (i = 0; i < c->used; ++i)
1559 struct image *img = c->images[i];
1560 if (img && timespec_cmp (img->timestamp, old) < 0)
1562 free_image (f, img);
1563 ++nfreed;
1568 /* We may be clearing the image cache because, for example,
1569 Emacs was iconified for a longer period of time. In that
1570 case, current matrices may still contain references to
1571 images freed above. So, clear these matrices. */
1572 if (nfreed)
1574 Lisp_Object tail, frame;
1576 FOR_EACH_FRAME (tail, frame)
1578 struct frame *fr = XFRAME (frame);
1579 if (FRAME_IMAGE_CACHE (fr) == c)
1580 clear_current_matrices (fr);
1583 windows_or_buffers_changed = 19;
1586 unblock_input ();
1590 void
1591 clear_image_caches (Lisp_Object filter)
1593 /* FIXME: We want to do
1594 * struct terminal *t;
1595 * for (t = terminal_list; t; t = t->next_terminal)
1596 * clear_image_cache (t, filter); */
1597 Lisp_Object tail, frame;
1598 FOR_EACH_FRAME (tail, frame)
1599 if (FRAME_WINDOW_P (XFRAME (frame)))
1600 clear_image_cache (XFRAME (frame), filter);
1603 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1604 0, 1, 0,
1605 doc: /* Clear the image cache.
1606 FILTER nil or a frame means clear all images in the selected frame.
1607 FILTER t means clear the image caches of all frames.
1608 Anything else, means only clear those images which refer to FILTER,
1609 which is then usually a filename. */)
1610 (Lisp_Object filter)
1612 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1613 clear_image_caches (filter);
1614 else
1615 clear_image_cache (decode_window_system_frame (filter), Qt);
1617 return Qnil;
1621 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1622 1, 2, 0,
1623 doc: /* Flush the image with specification SPEC on frame FRAME.
1624 This removes the image from the Emacs image cache. If SPEC specifies
1625 an image file, the next redisplay of this image will read from the
1626 current contents of that file.
1628 FRAME nil or omitted means use the selected frame.
1629 FRAME t means refresh the image on all frames. */)
1630 (Lisp_Object spec, Lisp_Object frame)
1632 if (!valid_image_p (spec))
1633 error ("Invalid image specification");
1635 if (EQ (frame, Qt))
1637 Lisp_Object tail;
1638 FOR_EACH_FRAME (tail, frame)
1640 struct frame *f = XFRAME (frame);
1641 if (FRAME_WINDOW_P (f))
1642 uncache_image (f, spec);
1645 else
1646 uncache_image (decode_window_system_frame (frame), spec);
1648 return Qnil;
1652 /* Compute masks and transform image IMG on frame F, as specified
1653 by the image's specification, */
1655 static void
1656 postprocess_image (struct frame *f, struct image *img)
1658 /* Manipulation of the image's mask. */
1659 if (img->pixmap)
1661 Lisp_Object conversion, spec;
1662 Lisp_Object mask;
1664 spec = img->spec;
1666 /* `:heuristic-mask t'
1667 `:mask heuristic'
1668 means build a mask heuristically.
1669 `:heuristic-mask (R G B)'
1670 `:mask (heuristic (R G B))'
1671 means build a mask from color (R G B) in the
1672 image.
1673 `:mask nil'
1674 means remove a mask, if any. */
1676 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1677 if (!NILP (mask))
1678 x_build_heuristic_mask (f, img, mask);
1679 else
1681 bool found_p;
1683 mask = image_spec_value (spec, QCmask, &found_p);
1685 if (EQ (mask, Qheuristic))
1686 x_build_heuristic_mask (f, img, Qt);
1687 else if (CONSP (mask)
1688 && EQ (XCAR (mask), Qheuristic))
1690 if (CONSP (XCDR (mask)))
1691 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1692 else
1693 x_build_heuristic_mask (f, img, XCDR (mask));
1695 else if (NILP (mask) && found_p && img->mask)
1696 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1700 /* Should we apply an image transformation algorithm? */
1701 conversion = image_spec_value (spec, QCconversion, NULL);
1702 if (EQ (conversion, Qdisabled))
1703 x_disable_image (f, img);
1704 else if (EQ (conversion, Qlaplace))
1705 x_laplace (f, img);
1706 else if (EQ (conversion, Qemboss))
1707 x_emboss (f, img);
1708 else if (CONSP (conversion)
1709 && EQ (XCAR (conversion), Qedge_detection))
1711 Lisp_Object tem;
1712 tem = XCDR (conversion);
1713 if (CONSP (tem))
1714 x_edge_detection (f, img,
1715 Fplist_get (tem, QCmatrix),
1716 Fplist_get (tem, QCcolor_adjustment));
1722 /* Return the id of image with Lisp specification SPEC on frame F.
1723 SPEC must be a valid Lisp image specification (see valid_image_p). */
1725 ptrdiff_t
1726 lookup_image (struct frame *f, Lisp_Object spec)
1728 struct image *img;
1729 EMACS_UINT hash;
1731 /* F must be a window-system frame, and SPEC must be a valid image
1732 specification. */
1733 eassert (FRAME_WINDOW_P (f));
1734 eassert (valid_image_p (spec));
1736 /* Look up SPEC in the hash table of the image cache. */
1737 hash = sxhash (spec, 0);
1738 img = search_image_cache (f, spec, hash);
1739 if (img && img->load_failed_p)
1741 free_image (f, img);
1742 img = NULL;
1745 /* If not found, create a new image and cache it. */
1746 if (img == NULL)
1748 block_input ();
1749 img = make_image (spec, hash);
1750 cache_image (f, img);
1751 img->load_failed_p = ! img->type->load (f, img);
1752 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1753 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1755 /* If we can't load the image, and we don't have a width and
1756 height, use some arbitrary width and height so that we can
1757 draw a rectangle for it. */
1758 if (img->load_failed_p)
1760 Lisp_Object value;
1762 value = image_spec_value (spec, QCwidth, NULL);
1763 img->width = (INTEGERP (value)
1764 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1765 value = image_spec_value (spec, QCheight, NULL);
1766 img->height = (INTEGERP (value)
1767 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1769 else
1771 /* Handle image type independent image attributes
1772 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1773 `:background COLOR'. */
1774 Lisp_Object ascent, margin, relief, bg;
1775 int relief_bound;
1777 ascent = image_spec_value (spec, QCascent, NULL);
1778 if (INTEGERP (ascent))
1779 img->ascent = XFASTINT (ascent);
1780 else if (EQ (ascent, Qcenter))
1781 img->ascent = CENTERED_IMAGE_ASCENT;
1783 margin = image_spec_value (spec, QCmargin, NULL);
1784 if (INTEGERP (margin))
1785 img->vmargin = img->hmargin = XFASTINT (margin);
1786 else if (CONSP (margin))
1788 img->hmargin = XFASTINT (XCAR (margin));
1789 img->vmargin = XFASTINT (XCDR (margin));
1792 relief = image_spec_value (spec, QCrelief, NULL);
1793 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1794 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1796 img->relief = XINT (relief);
1797 img->hmargin += eabs (img->relief);
1798 img->vmargin += eabs (img->relief);
1801 if (! img->background_valid)
1803 bg = image_spec_value (img->spec, QCbackground, NULL);
1804 if (!NILP (bg))
1806 img->background
1807 = x_alloc_image_color (f, img, bg,
1808 FRAME_BACKGROUND_PIXEL (f));
1809 img->background_valid = 1;
1813 /* Do image transformations and compute masks, unless we
1814 don't have the image yet. */
1815 if (!EQ (builtin_lisp_symbol (img->type->type), Qpostscript))
1816 postprocess_image (f, img);
1819 unblock_input ();
1822 /* We're using IMG, so set its timestamp to `now'. */
1823 img->timestamp = current_timespec ();
1825 /* Value is the image id. */
1826 return img->id;
1830 /* Cache image IMG in the image cache of frame F. */
1832 static void
1833 cache_image (struct frame *f, struct image *img)
1835 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1836 ptrdiff_t i;
1838 /* Find a free slot in c->images. */
1839 for (i = 0; i < c->used; ++i)
1840 if (c->images[i] == NULL)
1841 break;
1843 /* If no free slot found, maybe enlarge c->images. */
1844 if (i == c->used && c->used == c->size)
1845 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1847 /* Add IMG to c->images, and assign IMG an id. */
1848 c->images[i] = img;
1849 img->id = i;
1850 if (i == c->used)
1851 ++c->used;
1853 /* Add IMG to the cache's hash table. */
1854 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1855 img->next = c->buckets[i];
1856 if (img->next)
1857 img->next->prev = img;
1858 img->prev = NULL;
1859 c->buckets[i] = img;
1863 /* Call FN on every image in the image cache of frame F. Used to mark
1864 Lisp Objects in the image cache. */
1866 /* Mark Lisp objects in image IMG. */
1868 static void
1869 mark_image (struct image *img)
1871 mark_object (img->spec);
1872 mark_object (img->dependencies);
1874 if (!NILP (img->lisp_data))
1875 mark_object (img->lisp_data);
1879 void
1880 mark_image_cache (struct image_cache *c)
1882 if (c)
1884 ptrdiff_t i;
1885 for (i = 0; i < c->used; ++i)
1886 if (c->images[i])
1887 mark_image (c->images[i]);
1893 /***********************************************************************
1894 X / NS / W32 support code
1895 ***********************************************************************/
1897 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1898 windowing system.
1899 WIDTH and HEIGHT must both be positive.
1900 If XIMG is null, assume it is a bitmap. */
1901 static bool
1902 x_check_image_size (XImagePtr ximg, int width, int height)
1904 #ifdef HAVE_X_WINDOWS
1905 /* Respect Xlib's limits: it cannot deal with images that have more
1906 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1907 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1908 enum
1910 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1911 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1914 int bitmap_pad, depth, bytes_per_line;
1915 if (ximg)
1917 bitmap_pad = ximg->bitmap_pad;
1918 depth = ximg->depth;
1919 bytes_per_line = ximg->bytes_per_line;
1921 else
1923 bitmap_pad = 8;
1924 depth = 1;
1925 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1927 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1928 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1929 #else
1930 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1931 For now, assume that every image size is allowed on these systems. */
1932 return 1;
1933 #endif
1936 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1937 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1938 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1939 via xmalloc. Print error messages via image_error if an error
1940 occurs. Value is true if successful.
1942 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1943 should indicate the bit depth of the image. */
1945 static bool
1946 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1947 XImagePtr *ximg, Pixmap *pixmap)
1949 #ifdef HAVE_X_WINDOWS
1950 Display *display = FRAME_X_DISPLAY (f);
1951 Window window = FRAME_X_WINDOW (f);
1952 Screen *screen = FRAME_X_SCREEN (f);
1954 eassert (input_blocked_p ());
1956 if (depth <= 0)
1957 depth = DefaultDepthOfScreen (screen);
1958 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1959 depth, ZPixmap, 0, NULL, width, height,
1960 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1961 if (*ximg == NULL)
1963 image_error ("Unable to allocate X image");
1964 return 0;
1967 if (! x_check_image_size (*ximg, width, height))
1969 x_destroy_x_image (*ximg);
1970 *ximg = NULL;
1971 image_error ("Image too large (%dx%d)",
1972 make_number (width), make_number (height));
1973 return 0;
1976 /* Allocate image raster. */
1977 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1979 /* Allocate a pixmap of the same size. */
1980 *pixmap = XCreatePixmap (display, window, width, height, depth);
1981 if (*pixmap == NO_PIXMAP)
1983 x_destroy_x_image (*ximg);
1984 *ximg = NULL;
1985 image_error ("Unable to create X pixmap");
1986 return 0;
1989 return 1;
1990 #endif /* HAVE_X_WINDOWS */
1992 #ifdef HAVE_NTGUI
1994 BITMAPINFOHEADER *header;
1995 HDC hdc;
1996 int scanline_width_bits;
1997 int remainder;
1998 int palette_colors = 0;
2000 if (depth == 0)
2001 depth = 24;
2003 if (depth != 1 && depth != 4 && depth != 8
2004 && depth != 16 && depth != 24 && depth != 32)
2006 image_error ("Invalid image bit depth specified");
2007 return 0;
2010 scanline_width_bits = width * depth;
2011 remainder = scanline_width_bits % 32;
2013 if (remainder)
2014 scanline_width_bits += 32 - remainder;
2016 /* Bitmaps with a depth less than 16 need a palette. */
2017 /* BITMAPINFO structure already contains the first RGBQUAD. */
2018 if (depth < 16)
2019 palette_colors = 1 << (depth - 1);
2021 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2023 header = &(*ximg)->info.bmiHeader;
2024 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2025 header->biSize = sizeof (*header);
2026 header->biWidth = width;
2027 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2028 header->biPlanes = 1;
2029 header->biBitCount = depth;
2030 header->biCompression = BI_RGB;
2031 header->biClrUsed = palette_colors;
2033 /* TODO: fill in palette. */
2034 if (depth == 1)
2036 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2037 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2038 (*ximg)->info.bmiColors[0].rgbRed = 0;
2039 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2040 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2041 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2042 (*ximg)->info.bmiColors[1].rgbRed = 255;
2043 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2046 hdc = get_frame_dc (f);
2048 /* Create a DIBSection and raster array for the bitmap,
2049 and store its handle in *pixmap. */
2050 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2051 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2052 /* casting avoids a GCC warning */
2053 (void **)&((*ximg)->data), NULL, 0);
2055 /* Realize display palette and garbage all frames. */
2056 release_frame_dc (f, hdc);
2058 if (*pixmap == NULL)
2060 DWORD err = GetLastError ();
2061 Lisp_Object errcode;
2062 /* All system errors are < 10000, so the following is safe. */
2063 XSETINT (errcode, err);
2064 image_error ("Unable to create bitmap, error code %d", errcode);
2065 x_destroy_x_image (*ximg);
2066 *ximg = NULL;
2067 return 0;
2070 return 1;
2072 #endif /* HAVE_NTGUI */
2074 #ifdef HAVE_NS
2075 *pixmap = ns_image_for_XPM (width, height, depth);
2076 if (*pixmap == 0)
2078 *ximg = NULL;
2079 image_error ("Unable to allocate NSImage for XPM pixmap");
2080 return 0;
2082 *ximg = *pixmap;
2083 return 1;
2084 #endif
2088 /* Destroy XImage XIMG. Free XIMG->data. */
2090 static void
2091 x_destroy_x_image (XImagePtr ximg)
2093 eassert (input_blocked_p ());
2094 if (ximg)
2096 #ifdef HAVE_X_WINDOWS
2097 xfree (ximg->data);
2098 ximg->data = NULL;
2099 XDestroyImage (ximg);
2100 #endif /* HAVE_X_WINDOWS */
2101 #ifdef HAVE_NTGUI
2102 /* Data will be freed by DestroyObject. */
2103 ximg->data = NULL;
2104 xfree (ximg);
2105 #endif /* HAVE_NTGUI */
2106 #ifdef HAVE_NS
2107 ns_release_object (ximg);
2108 #endif /* HAVE_NS */
2113 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2114 are width and height of both the image and pixmap. */
2116 static void
2117 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2119 #ifdef HAVE_X_WINDOWS
2120 GC gc;
2122 eassert (input_blocked_p ());
2123 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2124 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2125 XFreeGC (FRAME_X_DISPLAY (f), gc);
2126 #endif /* HAVE_X_WINDOWS */
2128 #ifdef HAVE_NTGUI
2129 #if 0 /* I don't think this is necessary looking at where it is used. */
2130 HDC hdc = get_frame_dc (f);
2131 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2132 release_frame_dc (f, hdc);
2133 #endif
2134 #endif /* HAVE_NTGUI */
2136 #ifdef HAVE_NS
2137 eassert (ximg == pixmap);
2138 ns_retain_object (ximg);
2139 #endif
2142 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2143 with image_put_x_image. */
2145 static bool
2146 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2147 int width, int height, int depth,
2148 XImagePtr *ximg, bool mask_p)
2150 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2152 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2153 !mask_p ? &img->pixmap : &img->mask);
2156 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2157 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2158 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2159 On the other platforms, it puts XIMG into the pixmap, then frees
2160 the X image and its buffer. */
2162 static void
2163 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2164 bool mask_p)
2166 #ifdef HAVE_X_WINDOWS
2167 if (!mask_p)
2169 eassert (img->ximg == NULL);
2170 img->ximg = ximg;
2172 else
2174 eassert (img->mask_img == NULL);
2175 img->mask_img = ximg;
2177 #else
2178 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2179 img->width, img->height);
2180 x_destroy_x_image (ximg);
2181 #endif
2184 #ifdef HAVE_X_WINDOWS
2185 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2186 the X images and their buffers. */
2188 static void
2189 image_sync_to_pixmaps (struct frame *f, struct image *img)
2191 if (img->ximg)
2193 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2194 x_destroy_x_image (img->ximg);
2195 img->ximg = NULL;
2197 if (img->mask_img)
2199 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2200 x_destroy_x_image (img->mask_img);
2201 img->mask_img = NULL;
2204 #endif
2206 #ifdef HAVE_NTGUI
2207 /* Create a memory device context for IMG on frame F. It stores the
2208 currently selected GDI object into *PREV for future restoration by
2209 image_unget_x_image_or_dc. */
2211 static XImagePtr_or_DC
2212 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2213 HGDIOBJ *prev)
2215 HDC frame_dc = get_frame_dc (f);
2216 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2218 release_frame_dc (f, frame_dc);
2219 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2221 return ximg;
2224 static void
2225 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2226 XImagePtr_or_DC ximg, HGDIOBJ prev)
2228 SelectObject (ximg, prev);
2229 DeleteDC (ximg);
2231 #else /* !HAVE_NTGUI */
2232 /* Get the X image for IMG on frame F. The resulting X image data
2233 should be treated as read-only at least on X. */
2235 static XImagePtr
2236 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2238 #ifdef HAVE_X_WINDOWS
2239 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2241 if (ximg_in_img)
2242 return ximg_in_img;
2243 else
2244 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2245 0, 0, img->width, img->height, ~0, ZPixmap);
2246 #elif defined (HAVE_NS)
2247 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2249 ns_retain_object (pixmap);
2250 return pixmap;
2251 #endif
2254 static void
2255 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2257 #ifdef HAVE_X_WINDOWS
2258 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2260 if (ximg_in_img)
2261 eassert (ximg == ximg_in_img);
2262 else
2263 XDestroyImage (ximg);
2264 #elif defined (HAVE_NS)
2265 ns_release_object (ximg);
2266 #endif
2268 #endif /* !HAVE_NTGUI */
2271 /***********************************************************************
2272 File Handling
2273 ***********************************************************************/
2275 /* Find image file FILE. Look in data-directory/images, then
2276 x-bitmap-file-path. Value is the full name of the file
2277 found, or nil if not found. If PFD is nonnull store into *PFD a
2278 readable file descriptor for the file, opened in binary mode. If
2279 PFD is null, do not open the file. */
2281 static Lisp_Object
2282 x_find_image_fd (Lisp_Object file, int *pfd)
2284 Lisp_Object file_found, search_path;
2285 int fd;
2287 /* TODO I think this should use something like image-load-path
2288 instead. Unfortunately, that can contain non-string elements. */
2289 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2290 Vdata_directory),
2291 Vx_bitmap_file_path);
2293 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2294 fd = openp (search_path, file, Qnil, &file_found,
2295 pfd ? Qt : make_number (R_OK), false);
2296 if (fd >= 0 || fd == -2)
2298 file_found = ENCODE_FILE (file_found);
2299 if (fd == -2)
2301 /* The file exists locally, but has a file handler. (This
2302 happens, e.g., under Auto Image File Mode.) 'openp'
2303 didn't open the file, so we should, because the caller
2304 expects that. */
2305 fd = emacs_open (SSDATA (file_found), O_RDONLY | O_BINARY, 0);
2308 else /* fd < 0, but not -2 */
2309 return Qnil;
2310 if (pfd)
2311 *pfd = fd;
2312 return file_found;
2315 /* Find image file FILE. Look in data-directory/images, then
2316 x-bitmap-file-path. Value is the encoded full name of the file
2317 found, or nil if not found. */
2319 Lisp_Object
2320 x_find_image_file (Lisp_Object file)
2322 return x_find_image_fd (file, 0);
2325 /* Read FILE into memory. Value is a pointer to a buffer allocated
2326 with xmalloc holding FILE's contents. Value is null if an error
2327 occurred. FD is a file descriptor open for reading FILE. Set
2328 *SIZE to the size of the file. */
2330 static unsigned char *
2331 slurp_file (int fd, ptrdiff_t *size)
2333 FILE *fp = fdopen (fd, "rb");
2335 unsigned char *buf = NULL;
2336 struct stat st;
2338 if (fp)
2340 ptrdiff_t count = SPECPDL_INDEX ();
2341 record_unwind_protect_ptr (fclose_unwind, fp);
2343 if (fstat (fileno (fp), &st) == 0
2344 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2346 /* Report an error if we read past the purported EOF.
2347 This can happen if the file grows as we read it. */
2348 ptrdiff_t buflen = st.st_size;
2349 buf = xmalloc (buflen + 1);
2350 if (fread (buf, 1, buflen + 1, fp) == buflen)
2351 *size = buflen;
2352 else
2354 xfree (buf);
2355 buf = NULL;
2359 unbind_to (count, Qnil);
2362 return buf;
2367 /***********************************************************************
2368 XBM images
2369 ***********************************************************************/
2371 static bool xbm_load (struct frame *f, struct image *img);
2372 static bool xbm_image_p (Lisp_Object object);
2373 static bool xbm_file_p (Lisp_Object);
2376 /* Indices of image specification fields in xbm_format, below. */
2378 enum xbm_keyword_index
2380 XBM_TYPE,
2381 XBM_FILE,
2382 XBM_WIDTH,
2383 XBM_HEIGHT,
2384 XBM_DATA,
2385 XBM_FOREGROUND,
2386 XBM_BACKGROUND,
2387 XBM_ASCENT,
2388 XBM_MARGIN,
2389 XBM_RELIEF,
2390 XBM_ALGORITHM,
2391 XBM_HEURISTIC_MASK,
2392 XBM_MASK,
2393 XBM_LAST
2396 /* Vector of image_keyword structures describing the format
2397 of valid XBM image specifications. */
2399 static const struct image_keyword xbm_format[XBM_LAST] =
2401 {":type", IMAGE_SYMBOL_VALUE, 1},
2402 {":file", IMAGE_STRING_VALUE, 0},
2403 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2404 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2405 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2406 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2407 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2408 {":ascent", IMAGE_ASCENT_VALUE, 0},
2409 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2410 {":relief", IMAGE_INTEGER_VALUE, 0},
2411 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2412 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2413 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2416 /* Structure describing the image type XBM. */
2418 static struct image_type xbm_type =
2420 SYMBOL_INDEX (Qxbm),
2421 xbm_image_p,
2422 xbm_load,
2423 x_clear_image,
2424 NULL,
2425 NULL
2428 /* Tokens returned from xbm_scan. */
2430 enum xbm_token
2432 XBM_TK_IDENT = 256,
2433 XBM_TK_NUMBER
2437 /* Return true if OBJECT is a valid XBM-type image specification.
2438 A valid specification is a list starting with the symbol `image'
2439 The rest of the list is a property list which must contain an
2440 entry `:type xbm'.
2442 If the specification specifies a file to load, it must contain
2443 an entry `:file FILENAME' where FILENAME is a string.
2445 If the specification is for a bitmap loaded from memory it must
2446 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2447 WIDTH and HEIGHT are integers > 0. DATA may be:
2449 1. a string large enough to hold the bitmap data, i.e. it must
2450 have a size >= (WIDTH + 7) / 8 * HEIGHT
2452 2. a bool-vector of size >= WIDTH * HEIGHT
2454 3. a vector of strings or bool-vectors, one for each line of the
2455 bitmap.
2457 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2458 may not be specified in this case because they are defined in the
2459 XBM file.
2461 Both the file and data forms may contain the additional entries
2462 `:background COLOR' and `:foreground COLOR'. If not present,
2463 foreground and background of the frame on which the image is
2464 displayed is used. */
2466 static bool
2467 xbm_image_p (Lisp_Object object)
2469 struct image_keyword kw[XBM_LAST];
2471 memcpy (kw, xbm_format, sizeof kw);
2472 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2473 return 0;
2475 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2477 if (kw[XBM_FILE].count)
2479 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2480 return 0;
2482 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2484 /* In-memory XBM file. */
2485 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2486 return 0;
2488 else
2490 Lisp_Object data;
2491 int width, height;
2493 /* Entries for `:width', `:height' and `:data' must be present. */
2494 if (!kw[XBM_WIDTH].count
2495 || !kw[XBM_HEIGHT].count
2496 || !kw[XBM_DATA].count)
2497 return 0;
2499 data = kw[XBM_DATA].value;
2500 width = XFASTINT (kw[XBM_WIDTH].value);
2501 height = XFASTINT (kw[XBM_HEIGHT].value);
2503 /* Check type of data, and width and height against contents of
2504 data. */
2505 if (VECTORP (data))
2507 EMACS_INT i;
2509 /* Number of elements of the vector must be >= height. */
2510 if (ASIZE (data) < height)
2511 return 0;
2513 /* Each string or bool-vector in data must be large enough
2514 for one line of the image. */
2515 for (i = 0; i < height; ++i)
2517 Lisp_Object elt = AREF (data, i);
2519 if (STRINGP (elt))
2521 if (SCHARS (elt)
2522 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2523 return 0;
2525 else if (BOOL_VECTOR_P (elt))
2527 if (bool_vector_size (elt) < width)
2528 return 0;
2530 else
2531 return 0;
2534 else if (STRINGP (data))
2536 if (SCHARS (data)
2537 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2538 return 0;
2540 else if (BOOL_VECTOR_P (data))
2542 if (bool_vector_size (data) / height < width)
2543 return 0;
2545 else
2546 return 0;
2549 return 1;
2553 /* Scan a bitmap file. FP is the stream to read from. Value is
2554 either an enumerator from enum xbm_token, or a character for a
2555 single-character token, or 0 at end of file. If scanning an
2556 identifier, store the lexeme of the identifier in SVAL. If
2557 scanning a number, store its value in *IVAL. */
2559 static int
2560 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2562 unsigned int c;
2564 loop:
2566 /* Skip white space. */
2567 while (*s < end && (c = *(*s)++, c_isspace (c)))
2570 if (*s >= end)
2571 c = 0;
2572 else if (c_isdigit (c))
2574 int value = 0, digit;
2576 if (c == '0' && *s < end)
2578 c = *(*s)++;
2579 if (c == 'x' || c == 'X')
2581 while (*s < end)
2583 c = *(*s)++;
2584 if (c_isdigit (c))
2585 digit = c - '0';
2586 else if (c >= 'a' && c <= 'f')
2587 digit = c - 'a' + 10;
2588 else if (c >= 'A' && c <= 'F')
2589 digit = c - 'A' + 10;
2590 else
2591 break;
2592 value = 16 * value + digit;
2595 else if (c_isdigit (c))
2597 value = c - '0';
2598 while (*s < end
2599 && (c = *(*s)++, c_isdigit (c)))
2600 value = 8 * value + c - '0';
2603 else
2605 value = c - '0';
2606 while (*s < end
2607 && (c = *(*s)++, c_isdigit (c)))
2608 value = 10 * value + c - '0';
2611 if (*s < end)
2612 *s = *s - 1;
2613 *ival = value;
2614 c = XBM_TK_NUMBER;
2616 else if (c_isalpha (c) || c == '_')
2618 *sval++ = c;
2619 while (*s < end
2620 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2621 *sval++ = c;
2622 *sval = 0;
2623 if (*s < end)
2624 *s = *s - 1;
2625 c = XBM_TK_IDENT;
2627 else if (c == '/' && **s == '*')
2629 /* C-style comment. */
2630 ++*s;
2631 while (**s && (**s != '*' || *(*s + 1) != '/'))
2632 ++*s;
2633 if (**s)
2635 *s += 2;
2636 goto loop;
2640 return c;
2643 #ifdef HAVE_NTGUI
2645 /* Create a Windows bitmap from X bitmap data. */
2646 static HBITMAP
2647 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2649 static unsigned char swap_nibble[16]
2650 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2651 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2652 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2653 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2654 int i, j, w1, w2;
2655 unsigned char *bits, *p;
2656 HBITMAP bmp;
2658 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2659 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2660 bits = alloca (height * w2);
2661 memset (bits, 0, height * w2);
2662 for (i = 0; i < height; i++)
2664 p = bits + i*w2;
2665 for (j = 0; j < w1; j++)
2667 /* Bitswap XBM bytes to match how Windows does things. */
2668 unsigned char c = *data++;
2669 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2670 | (swap_nibble[(c>>4) & 0xf]));
2673 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2675 return bmp;
2678 static void
2679 convert_mono_to_color_image (struct frame *f, struct image *img,
2680 COLORREF foreground, COLORREF background)
2682 HDC hdc, old_img_dc, new_img_dc;
2683 HGDIOBJ old_prev, new_prev;
2684 HBITMAP new_pixmap;
2686 hdc = get_frame_dc (f);
2687 old_img_dc = CreateCompatibleDC (hdc);
2688 new_img_dc = CreateCompatibleDC (hdc);
2689 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2690 release_frame_dc (f, hdc);
2691 old_prev = SelectObject (old_img_dc, img->pixmap);
2692 new_prev = SelectObject (new_img_dc, new_pixmap);
2693 /* Windows convention for mono bitmaps is black = background,
2694 white = foreground. */
2695 SetTextColor (new_img_dc, background);
2696 SetBkColor (new_img_dc, foreground);
2698 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2699 0, 0, SRCCOPY);
2701 SelectObject (old_img_dc, old_prev);
2702 SelectObject (new_img_dc, new_prev);
2703 DeleteDC (old_img_dc);
2704 DeleteDC (new_img_dc);
2705 DeleteObject (img->pixmap);
2706 if (new_pixmap == 0)
2707 fprintf (stderr, "Failed to convert image to color.\n");
2708 else
2709 img->pixmap = new_pixmap;
2712 #define XBM_BIT_SHUFFLE(b) (~(b))
2714 #else
2716 #define XBM_BIT_SHUFFLE(b) (b)
2718 #endif /* HAVE_NTGUI */
2721 static void
2722 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2723 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2724 bool non_default_colors)
2726 #ifdef HAVE_NTGUI
2727 img->pixmap
2728 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2730 /* If colors were specified, transfer the bitmap to a color one. */
2731 if (non_default_colors)
2732 convert_mono_to_color_image (f, img, fg, bg);
2734 #elif defined (HAVE_NS)
2735 img->pixmap = ns_image_from_XBM (data, img->width, img->height, fg, bg);
2737 #else
2738 img->pixmap =
2739 (x_check_image_size (0, img->width, img->height)
2740 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2741 FRAME_X_WINDOW (f),
2742 data,
2743 img->width, img->height,
2744 fg, bg,
2745 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2746 : NO_PIXMAP);
2747 #endif /* !HAVE_NTGUI && !HAVE_NS */
2752 /* Replacement for XReadBitmapFileData which isn't available under old
2753 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2754 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2755 the image. Return in *DATA the bitmap data allocated with xmalloc.
2756 Value is true if successful. DATA null means just test if
2757 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2758 inhibit the call to image_error when the image size is invalid (the
2759 bitmap remains unread). */
2761 static bool
2762 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2763 int *width, int *height, char **data,
2764 bool inhibit_image_error)
2766 unsigned char *s = contents;
2767 char buffer[BUFSIZ];
2768 bool padding_p = 0;
2769 bool v10 = 0;
2770 int bytes_per_line, i, nbytes;
2771 char *p;
2772 int value;
2773 int LA1;
2775 #define match() \
2776 LA1 = xbm_scan (&s, end, buffer, &value)
2778 #define expect(TOKEN) \
2779 do \
2781 if (LA1 != (TOKEN)) \
2782 goto failure; \
2783 match (); \
2785 while (0)
2787 #define expect_ident(IDENT) \
2788 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2789 match (); \
2790 else \
2791 goto failure
2793 *width = *height = -1;
2794 if (data)
2795 *data = NULL;
2796 LA1 = xbm_scan (&s, end, buffer, &value);
2798 /* Parse defines for width, height and hot-spots. */
2799 while (LA1 == '#')
2801 match ();
2802 expect_ident ("define");
2803 expect (XBM_TK_IDENT);
2805 if (LA1 == XBM_TK_NUMBER)
2807 char *q = strrchr (buffer, '_');
2808 q = q ? q + 1 : buffer;
2809 if (strcmp (q, "width") == 0)
2810 *width = value;
2811 else if (strcmp (q, "height") == 0)
2812 *height = value;
2814 expect (XBM_TK_NUMBER);
2817 if (!check_image_size (f, *width, *height))
2819 if (!inhibit_image_error)
2820 image_size_error ();
2821 goto failure;
2823 else if (data == NULL)
2824 goto success;
2826 /* Parse bits. Must start with `static'. */
2827 expect_ident ("static");
2828 if (LA1 == XBM_TK_IDENT)
2830 if (strcmp (buffer, "unsigned") == 0)
2832 match ();
2833 expect_ident ("char");
2835 else if (strcmp (buffer, "short") == 0)
2837 match ();
2838 v10 = 1;
2839 if (*width % 16 && *width % 16 < 9)
2840 padding_p = 1;
2842 else if (strcmp (buffer, "char") == 0)
2843 match ();
2844 else
2845 goto failure;
2847 else
2848 goto failure;
2850 expect (XBM_TK_IDENT);
2851 expect ('[');
2852 expect (']');
2853 expect ('=');
2854 expect ('{');
2856 if (! x_check_image_size (0, *width, *height))
2858 if (!inhibit_image_error)
2859 image_error ("Image too large (%dx%d)",
2860 make_number (*width), make_number (*height));
2861 goto failure;
2863 bytes_per_line = (*width + 7) / 8 + padding_p;
2864 nbytes = bytes_per_line * *height;
2865 p = *data = xmalloc (nbytes);
2867 if (v10)
2869 for (i = 0; i < nbytes; i += 2)
2871 int val = value;
2872 expect (XBM_TK_NUMBER);
2874 *p++ = XBM_BIT_SHUFFLE (val);
2875 if (!padding_p || ((i + 2) % bytes_per_line))
2876 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2878 if (LA1 == ',' || LA1 == '}')
2879 match ();
2880 else
2881 goto failure;
2884 else
2886 for (i = 0; i < nbytes; ++i)
2888 int val = value;
2889 expect (XBM_TK_NUMBER);
2891 *p++ = XBM_BIT_SHUFFLE (val);
2893 if (LA1 == ',' || LA1 == '}')
2894 match ();
2895 else
2896 goto failure;
2900 success:
2901 return 1;
2903 failure:
2905 if (data && *data)
2907 xfree (*data);
2908 *data = NULL;
2910 return 0;
2912 #undef match
2913 #undef expect
2914 #undef expect_ident
2918 /* Load XBM image IMG which will be displayed on frame F from buffer
2919 CONTENTS. END is the end of the buffer. Value is true if
2920 successful. */
2922 static bool
2923 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2924 unsigned char *end)
2926 bool rc;
2927 char *data;
2928 bool success_p = 0;
2930 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2931 &data, 0);
2932 if (rc)
2934 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2935 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2936 bool non_default_colors = 0;
2937 Lisp_Object value;
2939 eassert (img->width > 0 && img->height > 0);
2941 /* Get foreground and background colors, maybe allocate colors. */
2942 value = image_spec_value (img->spec, QCforeground, NULL);
2943 if (!NILP (value))
2945 foreground = x_alloc_image_color (f, img, value, foreground);
2946 non_default_colors = 1;
2948 value = image_spec_value (img->spec, QCbackground, NULL);
2949 if (!NILP (value))
2951 background = x_alloc_image_color (f, img, value, background);
2952 img->background = background;
2953 img->background_valid = 1;
2954 non_default_colors = 1;
2957 Create_Pixmap_From_Bitmap_Data (f, img, data,
2958 foreground, background,
2959 non_default_colors);
2960 xfree (data);
2962 if (img->pixmap == NO_PIXMAP)
2964 x_clear_image (f, img);
2965 image_error ("Unable to create X pixmap for `%s'", img->spec);
2967 else
2968 success_p = 1;
2970 else
2971 image_error ("Error loading XBM image `%s'", img->spec);
2973 return success_p;
2977 /* Value is true if DATA looks like an in-memory XBM file. */
2979 static bool
2980 xbm_file_p (Lisp_Object data)
2982 int w, h;
2983 return (STRINGP (data)
2984 && xbm_read_bitmap_data (NULL, SDATA (data),
2985 (SDATA (data) + SBYTES (data)),
2986 &w, &h, NULL, 1));
2990 /* Fill image IMG which is used on frame F with pixmap data. Value is
2991 true if successful. */
2993 static bool
2994 xbm_load (struct frame *f, struct image *img)
2996 bool success_p = 0;
2997 Lisp_Object file_name;
2999 eassert (xbm_image_p (img->spec));
3001 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3002 file_name = image_spec_value (img->spec, QCfile, NULL);
3003 if (STRINGP (file_name))
3005 int fd;
3006 Lisp_Object file = x_find_image_fd (file_name, &fd);
3007 if (!STRINGP (file))
3009 image_error ("Cannot find image file `%s'", file_name);
3010 return 0;
3013 ptrdiff_t size;
3014 unsigned char *contents = slurp_file (fd, &size);
3015 if (contents == NULL)
3017 image_error ("Error loading XBM image `%s'", file);
3018 return 0;
3021 success_p = xbm_load_image (f, img, contents, contents + size);
3022 xfree (contents);
3024 else
3026 struct image_keyword fmt[XBM_LAST];
3027 Lisp_Object data;
3028 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3029 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3030 bool non_default_colors = 0;
3031 char *bits;
3032 bool parsed_p;
3033 bool in_memory_file_p = 0;
3035 /* See if data looks like an in-memory XBM file. */
3036 data = image_spec_value (img->spec, QCdata, NULL);
3037 in_memory_file_p = xbm_file_p (data);
3039 /* Parse the image specification. */
3040 memcpy (fmt, xbm_format, sizeof fmt);
3041 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3042 eassert (parsed_p);
3044 /* Get specified width, and height. */
3045 if (!in_memory_file_p)
3047 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3048 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3049 eassert (img->width > 0 && img->height > 0);
3050 if (!check_image_size (f, img->width, img->height))
3052 image_size_error ();
3053 return 0;
3057 /* Get foreground and background colors, maybe allocate colors. */
3058 if (fmt[XBM_FOREGROUND].count
3059 && STRINGP (fmt[XBM_FOREGROUND].value))
3061 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3062 foreground);
3063 non_default_colors = 1;
3066 if (fmt[XBM_BACKGROUND].count
3067 && STRINGP (fmt[XBM_BACKGROUND].value))
3069 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3070 background);
3071 non_default_colors = 1;
3074 if (in_memory_file_p)
3075 success_p = xbm_load_image (f, img, SDATA (data),
3076 (SDATA (data)
3077 + SBYTES (data)));
3078 else
3080 USE_SAFE_ALLOCA;
3082 if (VECTORP (data))
3084 int i;
3085 char *p;
3086 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3088 SAFE_NALLOCA (bits, nbytes, img->height);
3089 p = bits;
3090 for (i = 0; i < img->height; ++i, p += nbytes)
3092 Lisp_Object line = AREF (data, i);
3093 if (STRINGP (line))
3094 memcpy (p, SDATA (line), nbytes);
3095 else
3096 memcpy (p, bool_vector_data (line), nbytes);
3099 else if (STRINGP (data))
3100 bits = SSDATA (data);
3101 else
3102 bits = (char *) bool_vector_data (data);
3104 #ifdef HAVE_NTGUI
3106 char *invertedBits;
3107 int nbytes, i;
3108 /* Windows mono bitmaps are reversed compared with X. */
3109 invertedBits = bits;
3110 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3111 SAFE_NALLOCA (bits, nbytes, img->height);
3112 for (i = 0; i < nbytes; i++)
3113 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3115 #endif
3116 /* Create the pixmap. */
3118 if (x_check_image_size (0, img->width, img->height))
3119 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3120 foreground, background,
3121 non_default_colors);
3122 else
3123 img->pixmap = NO_PIXMAP;
3125 if (img->pixmap)
3126 success_p = 1;
3127 else
3129 image_error ("Unable to create pixmap for XBM image `%s'",
3130 img->spec);
3131 x_clear_image (f, img);
3134 SAFE_FREE ();
3138 return success_p;
3143 /***********************************************************************
3144 XPM images
3145 ***********************************************************************/
3147 #if defined (HAVE_XPM) || defined (HAVE_NS)
3149 static bool xpm_image_p (Lisp_Object object);
3150 static bool xpm_load (struct frame *f, struct image *img);
3152 #endif /* HAVE_XPM || HAVE_NS */
3154 #ifdef HAVE_XPM
3155 #ifdef HAVE_NTGUI
3156 /* Indicate to xpm.h that we don't have Xlib. */
3157 #define FOR_MSW
3158 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3159 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3160 #define XColor xpm_XColor
3161 #define XImage xpm_XImage
3162 #define Display xpm_Display
3163 #define PIXEL_ALREADY_TYPEDEFED
3164 #include "X11/xpm.h"
3165 #undef FOR_MSW
3166 #undef XColor
3167 #undef XImage
3168 #undef Display
3169 #undef PIXEL_ALREADY_TYPEDEFED
3170 #else
3171 #include "X11/xpm.h"
3172 #endif /* HAVE_NTGUI */
3173 #endif /* HAVE_XPM */
3175 #if defined (HAVE_XPM) || defined (HAVE_NS)
3177 /* Indices of image specification fields in xpm_format, below. */
3179 enum xpm_keyword_index
3181 XPM_TYPE,
3182 XPM_FILE,
3183 XPM_DATA,
3184 XPM_ASCENT,
3185 XPM_MARGIN,
3186 XPM_RELIEF,
3187 XPM_ALGORITHM,
3188 XPM_HEURISTIC_MASK,
3189 XPM_MASK,
3190 XPM_COLOR_SYMBOLS,
3191 XPM_BACKGROUND,
3192 XPM_LAST
3195 /* Vector of image_keyword structures describing the format
3196 of valid XPM image specifications. */
3198 static const struct image_keyword xpm_format[XPM_LAST] =
3200 {":type", IMAGE_SYMBOL_VALUE, 1},
3201 {":file", IMAGE_STRING_VALUE, 0},
3202 {":data", IMAGE_STRING_VALUE, 0},
3203 {":ascent", IMAGE_ASCENT_VALUE, 0},
3204 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3205 {":relief", IMAGE_INTEGER_VALUE, 0},
3206 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3207 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3208 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3209 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3210 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3213 #if defined HAVE_NTGUI && defined WINDOWSNT
3214 static bool init_xpm_functions (void);
3215 #else
3216 #define init_xpm_functions NULL
3217 #endif
3219 /* Structure describing the image type XPM. */
3221 static struct image_type xpm_type =
3223 SYMBOL_INDEX (Qxpm),
3224 xpm_image_p,
3225 xpm_load,
3226 x_clear_image,
3227 init_xpm_functions,
3228 NULL
3231 #ifdef HAVE_X_WINDOWS
3233 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3234 functions for allocating image colors. Our own functions handle
3235 color allocation failures more gracefully than the ones on the XPM
3236 lib. */
3238 #ifndef USE_CAIRO
3239 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3240 #define ALLOC_XPM_COLORS
3241 #endif
3242 #endif /* USE_CAIRO */
3243 #endif /* HAVE_X_WINDOWS */
3245 #ifdef ALLOC_XPM_COLORS
3247 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3248 XColor *, int);
3250 /* An entry in a hash table used to cache color definitions of named
3251 colors. This cache is necessary to speed up XPM image loading in
3252 case we do color allocations ourselves. Without it, we would need
3253 a call to XParseColor per pixel in the image.
3255 FIXME Now that we're using x_parse_color and its cache, reevaluate
3256 the need for this caching layer. */
3258 struct xpm_cached_color
3260 /* Next in collision chain. */
3261 struct xpm_cached_color *next;
3263 /* Color definition (RGB and pixel color). */
3264 XColor color;
3266 /* Color name. */
3267 char name[FLEXIBLE_ARRAY_MEMBER];
3270 /* The hash table used for the color cache, and its bucket vector
3271 size. */
3273 #define XPM_COLOR_CACHE_BUCKETS 1001
3274 static struct xpm_cached_color **xpm_color_cache;
3276 /* Initialize the color cache. */
3278 static void
3279 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3281 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3282 xpm_color_cache = xzalloc (nbytes);
3283 init_color_table ();
3285 if (attrs->valuemask & XpmColorSymbols)
3287 int i;
3288 XColor color;
3290 for (i = 0; i < attrs->numsymbols; ++i)
3291 if (x_parse_color (f, attrs->colorsymbols[i].value, &color))
3293 color.pixel = lookup_rgb_color (f, color.red, color.green,
3294 color.blue);
3295 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3300 /* Free the color cache. */
3302 static void
3303 xpm_free_color_cache (void)
3305 struct xpm_cached_color *p, *next;
3306 int i;
3308 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3309 for (p = xpm_color_cache[i]; p; p = next)
3311 next = p->next;
3312 xfree (p);
3315 xfree (xpm_color_cache);
3316 xpm_color_cache = NULL;
3317 free_color_table ();
3320 /* Return the bucket index for color named COLOR_NAME in the color
3321 cache. */
3323 static int
3324 xpm_color_bucket (char *color_name)
3326 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3327 return hash % XPM_COLOR_CACHE_BUCKETS;
3331 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3332 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3333 entry added. */
3335 static struct xpm_cached_color *
3336 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3338 size_t nbytes;
3339 struct xpm_cached_color *p;
3341 if (bucket < 0)
3342 bucket = xpm_color_bucket (color_name);
3344 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3345 p = xmalloc (nbytes);
3346 strcpy (p->name, color_name);
3347 p->color = *color;
3348 p->next = xpm_color_cache[bucket];
3349 xpm_color_cache[bucket] = p;
3350 return p;
3353 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3354 return the cached definition in *COLOR. Otherwise, make a new
3355 entry in the cache and allocate the color. Value is false if color
3356 allocation failed. */
3358 static bool
3359 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3361 struct xpm_cached_color *p;
3362 int h = xpm_color_bucket (color_name);
3364 for (p = xpm_color_cache[h]; p; p = p->next)
3365 if (strcmp (p->name, color_name) == 0)
3366 break;
3368 if (p != NULL)
3369 *color = p->color;
3370 else if (x_parse_color (f, color_name, color))
3372 color->pixel = lookup_rgb_color (f, color->red, color->green,
3373 color->blue);
3374 p = xpm_cache_color (f, color_name, color, h);
3376 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3377 with transparency, and it's useful. */
3378 else if (strcmp ("opaque", color_name) == 0)
3380 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3381 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3382 p = xpm_cache_color (f, color_name, color, h);
3385 return p != NULL;
3389 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3390 CLOSURE is a pointer to the frame on which we allocate the
3391 color. Return in *COLOR the allocated color. Value is non-zero
3392 if successful. */
3394 static int
3395 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3396 void *closure)
3398 return xpm_lookup_color (closure, color_name, color);
3402 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3403 is a pointer to the frame on which we allocate the color. Value is
3404 non-zero if successful. */
3406 static int
3407 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3409 return 1;
3412 #endif /* ALLOC_XPM_COLORS */
3415 #ifdef WINDOWSNT
3417 /* XPM library details. */
3419 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3420 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3421 (Display *, char *, xpm_XImage **,
3422 xpm_XImage **, XpmAttributes *));
3423 DEF_DLL_FN (int, XpmReadFileToImage,
3424 (Display *, char *, xpm_XImage **,
3425 xpm_XImage **, XpmAttributes *));
3426 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3428 static bool
3429 init_xpm_functions (void)
3431 HMODULE library;
3433 if (!(library = w32_delayed_load (Qxpm)))
3434 return 0;
3436 LOAD_DLL_FN (library, XpmFreeAttributes);
3437 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3438 LOAD_DLL_FN (library, XpmReadFileToImage);
3439 LOAD_DLL_FN (library, XImageFree);
3440 return 1;
3443 # undef XImageFree
3444 # undef XpmCreateImageFromBuffer
3445 # undef XpmFreeAttributes
3446 # undef XpmReadFileToImage
3448 # define XImageFree fn_XImageFree
3449 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3450 # define XpmFreeAttributes fn_XpmFreeAttributes
3451 # define XpmReadFileToImage fn_XpmReadFileToImage
3453 #endif /* WINDOWSNT */
3455 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3456 for XPM images. Such a list must consist of conses whose car and
3457 cdr are strings. */
3459 static bool
3460 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3462 while (CONSP (color_symbols))
3464 Lisp_Object sym = XCAR (color_symbols);
3465 if (!CONSP (sym)
3466 || !STRINGP (XCAR (sym))
3467 || !STRINGP (XCDR (sym)))
3468 break;
3469 color_symbols = XCDR (color_symbols);
3472 return NILP (color_symbols);
3476 /* Value is true if OBJECT is a valid XPM image specification. */
3478 static bool
3479 xpm_image_p (Lisp_Object object)
3481 struct image_keyword fmt[XPM_LAST];
3482 memcpy (fmt, xpm_format, sizeof fmt);
3483 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3484 /* Either `:file' or `:data' must be present. */
3485 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3486 /* Either no `:color-symbols' or it's a list of conses
3487 whose car and cdr are strings. */
3488 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3489 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3492 #endif /* HAVE_XPM || HAVE_NS */
3494 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3495 ptrdiff_t
3496 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3498 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3499 ptrdiff_t id;
3500 int rc;
3501 XpmAttributes attrs;
3502 Pixmap bitmap, mask;
3504 memset (&attrs, 0, sizeof attrs);
3506 attrs.visual = FRAME_X_VISUAL (f);
3507 attrs.colormap = FRAME_X_COLORMAP (f);
3508 attrs.valuemask |= XpmVisual;
3509 attrs.valuemask |= XpmColormap;
3511 #ifdef ALLOC_XPM_COLORS
3512 attrs.color_closure = f;
3513 attrs.alloc_color = xpm_alloc_color;
3514 attrs.free_colors = xpm_free_colors;
3515 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3516 xpm_init_color_cache (f, &attrs);
3517 #endif
3519 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3520 (char **) bits, &bitmap, &mask, &attrs);
3521 if (rc != XpmSuccess)
3523 XpmFreeAttributes (&attrs);
3524 return -1;
3527 id = x_allocate_bitmap_record (f);
3528 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3529 dpyinfo->bitmaps[id - 1].have_mask = true;
3530 dpyinfo->bitmaps[id - 1].mask = mask;
3531 dpyinfo->bitmaps[id - 1].file = NULL;
3532 dpyinfo->bitmaps[id - 1].height = attrs.height;
3533 dpyinfo->bitmaps[id - 1].width = attrs.width;
3534 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3535 dpyinfo->bitmaps[id - 1].refcount = 1;
3537 #ifdef ALLOC_XPM_COLORS
3538 xpm_free_color_cache ();
3539 #endif
3540 XpmFreeAttributes (&attrs);
3541 return id;
3543 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3545 /* Load image IMG which will be displayed on frame F. Value is
3546 true if successful. */
3548 #ifdef HAVE_XPM
3550 static bool
3551 xpm_load (struct frame *f, struct image *img)
3553 int rc;
3554 XpmAttributes attrs;
3555 Lisp_Object specified_file, color_symbols;
3556 USE_SAFE_ALLOCA;
3558 #ifdef HAVE_NTGUI
3559 HDC hdc;
3560 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3561 #endif /* HAVE_NTGUI */
3563 /* Configure the XPM lib. Use the visual of frame F. Allocate
3564 close colors. Return colors allocated. */
3565 memset (&attrs, 0, sizeof attrs);
3567 #ifndef HAVE_NTGUI
3568 attrs.visual = FRAME_X_VISUAL (f);
3569 attrs.colormap = FRAME_X_COLORMAP (f);
3570 attrs.valuemask |= XpmVisual;
3571 attrs.valuemask |= XpmColormap;
3572 #endif /* HAVE_NTGUI */
3574 #ifdef ALLOC_XPM_COLORS
3575 /* Allocate colors with our own functions which handle
3576 failing color allocation more gracefully. */
3577 attrs.color_closure = f;
3578 attrs.alloc_color = xpm_alloc_color;
3579 attrs.free_colors = xpm_free_colors;
3580 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3581 #else /* not ALLOC_XPM_COLORS */
3582 /* Let the XPM lib allocate colors. */
3583 attrs.valuemask |= XpmReturnAllocPixels;
3584 #ifdef XpmAllocCloseColors
3585 attrs.alloc_close_colors = 1;
3586 attrs.valuemask |= XpmAllocCloseColors;
3587 #else /* not XpmAllocCloseColors */
3588 attrs.closeness = 600;
3589 attrs.valuemask |= XpmCloseness;
3590 #endif /* not XpmAllocCloseColors */
3591 #endif /* ALLOC_XPM_COLORS */
3593 /* If image specification contains symbolic color definitions, add
3594 these to `attrs'. */
3595 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3596 if (CONSP (color_symbols))
3598 Lisp_Object tail;
3599 XpmColorSymbol *xpm_syms;
3600 ptrdiff_t i, size;
3602 attrs.valuemask |= XpmColorSymbols;
3604 /* Count number of symbols. */
3605 attrs.numsymbols = 0;
3606 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3607 ++attrs.numsymbols;
3609 /* Allocate an XpmColorSymbol array. */
3610 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3611 size = attrs.numsymbols * sizeof *xpm_syms;
3612 memset (xpm_syms, 0, size);
3613 attrs.colorsymbols = xpm_syms;
3615 /* Fill the color symbol array. */
3616 for (tail = color_symbols, i = 0;
3617 CONSP (tail);
3618 ++i, tail = XCDR (tail))
3620 Lisp_Object name;
3621 Lisp_Object color;
3622 char *empty_string = (char *) "";
3624 if (!CONSP (XCAR (tail)))
3626 xpm_syms[i].name = empty_string;
3627 xpm_syms[i].value = empty_string;
3628 continue;
3630 name = XCAR (XCAR (tail));
3631 color = XCDR (XCAR (tail));
3632 if (STRINGP (name))
3633 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3634 else
3635 xpm_syms[i].name = empty_string;
3636 if (STRINGP (color))
3637 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3638 else
3639 xpm_syms[i].value = empty_string;
3643 /* Create a pixmap for the image, either from a file, or from a
3644 string buffer containing data in the same format as an XPM file. */
3645 #ifdef ALLOC_XPM_COLORS
3646 xpm_init_color_cache (f, &attrs);
3647 #endif
3649 specified_file = image_spec_value (img->spec, QCfile, NULL);
3651 #ifdef HAVE_NTGUI
3653 HDC frame_dc = get_frame_dc (f);
3654 hdc = CreateCompatibleDC (frame_dc);
3655 release_frame_dc (f, frame_dc);
3657 #endif /* HAVE_NTGUI */
3659 if (STRINGP (specified_file))
3661 Lisp_Object file = x_find_image_file (specified_file);
3662 if (!STRINGP (file))
3664 image_error ("Cannot find image file `%s'", specified_file);
3665 #ifdef ALLOC_XPM_COLORS
3666 xpm_free_color_cache ();
3667 #endif
3668 SAFE_FREE ();
3669 return 0;
3672 file = ENCODE_FILE (file);
3673 #ifdef HAVE_NTGUI
3674 #ifdef WINDOWSNT
3675 /* FILE is encoded in UTF-8, but image libraries on Windows
3676 support neither UTF-8 nor UTF-16 encoded file names. So we
3677 need to re-encode it in ANSI. */
3678 file = ansi_encode_filename (file);
3679 #endif
3680 /* XpmReadFileToPixmap is not available in the Windows port of
3681 libxpm. But XpmReadFileToImage almost does what we want. */
3682 rc = XpmReadFileToImage (&hdc, SDATA (file),
3683 &xpm_image, &xpm_mask,
3684 &attrs);
3685 #else
3686 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3687 &img->ximg, &img->mask_img,
3688 &attrs);
3689 #endif /* HAVE_NTGUI */
3691 else
3693 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3694 if (!STRINGP (buffer))
3696 image_error ("Invalid image data `%s'", buffer);
3697 #ifdef ALLOC_XPM_COLORS
3698 xpm_free_color_cache ();
3699 #endif
3700 SAFE_FREE ();
3701 return 0;
3703 #ifdef HAVE_NTGUI
3704 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3705 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3706 rc = XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3707 &xpm_image, &xpm_mask,
3708 &attrs);
3709 #else
3710 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3711 &img->ximg, &img->mask_img,
3712 &attrs);
3713 #endif /* HAVE_NTGUI */
3716 #ifdef USE_CAIRO
3717 // Load very specific Xpm:s.
3718 if (rc == XpmSuccess
3719 && img->ximg->format == ZPixmap
3720 && img->ximg->bits_per_pixel == 32
3721 && (! img->mask_img || img->mask_img->bits_per_pixel == 1))
3723 int width = img->ximg->width;
3724 int height = img->ximg->height;
3725 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
3726 int i;
3727 uint32_t *od = (uint32_t *)data;
3728 uint32_t *id = (uint32_t *)img->ximg->data;
3729 char *mid = img->mask_img ? img->mask_img->data : 0;
3730 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
3732 for (i = 0; i < height; ++i)
3734 int k;
3735 for (k = 0; k < width; ++k)
3737 int idx = i * img->ximg->bytes_per_line/4 + k;
3738 int maskidx = mid ? i * img->mask_img->bytes_per_line + k/8 : 0;
3739 int mask = mid ? mid[maskidx] & (1 << (k % 8)) : 1;
3741 if (mask) od[idx] = id[idx] + 0xff000000; // ff => full alpha
3742 else od[idx] = bgcolor;
3746 create_cairo_image_surface (img, data, width, height);
3748 else
3750 rc = XpmFileInvalid;
3751 x_clear_image (f, img);
3753 #else
3754 #ifdef HAVE_X_WINDOWS
3755 if (rc == XpmSuccess)
3757 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3758 img->ximg->width, img->ximg->height,
3759 img->ximg->depth);
3760 if (img->pixmap == NO_PIXMAP)
3762 x_clear_image (f, img);
3763 rc = XpmNoMemory;
3765 else if (img->mask_img)
3767 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3768 img->mask_img->width,
3769 img->mask_img->height,
3770 img->mask_img->depth);
3771 if (img->mask == NO_PIXMAP)
3773 x_clear_image (f, img);
3774 rc = XpmNoMemory;
3778 #endif
3779 #endif /* ! USE_CAIRO */
3781 if (rc == XpmSuccess)
3783 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3784 img->colors = colors_in_color_table (&img->ncolors);
3785 #else /* not ALLOC_XPM_COLORS */
3786 int i;
3788 #ifdef HAVE_NTGUI
3789 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3790 plus some duplicate attributes. */
3791 if (xpm_image && xpm_image->bitmap)
3793 img->pixmap = xpm_image->bitmap;
3794 /* XImageFree in libXpm frees XImage struct without destroying
3795 the bitmap, which is what we want. */
3796 XImageFree (xpm_image);
3798 if (xpm_mask && xpm_mask->bitmap)
3800 /* The mask appears to be inverted compared with what we expect.
3801 TODO: invert our expectations. See other places where we
3802 have to invert bits because our idea of masks is backwards. */
3803 HGDIOBJ old_obj;
3804 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3806 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3807 SelectObject (hdc, old_obj);
3809 img->mask = xpm_mask->bitmap;
3810 XImageFree (xpm_mask);
3811 DeleteDC (hdc);
3814 DeleteDC (hdc);
3815 #endif /* HAVE_NTGUI */
3817 /* Remember allocated colors. */
3818 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3819 img->ncolors = attrs.nalloc_pixels;
3820 for (i = 0; i < attrs.nalloc_pixels; ++i)
3822 img->colors[i] = attrs.alloc_pixels[i];
3823 #ifdef DEBUG_X_COLORS
3824 register_color (img->colors[i]);
3825 #endif
3827 #endif /* not ALLOC_XPM_COLORS */
3829 img->width = attrs.width;
3830 img->height = attrs.height;
3831 eassert (img->width > 0 && img->height > 0);
3833 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3834 XpmFreeAttributes (&attrs);
3836 #ifdef HAVE_X_WINDOWS
3837 /* Maybe fill in the background field while we have ximg handy. */
3838 IMAGE_BACKGROUND (img, f, img->ximg);
3839 if (img->mask_img)
3840 /* Fill in the background_transparent field while we have the
3841 mask handy. */
3842 image_background_transparent (img, f, img->mask_img);
3843 #endif
3845 else
3847 #ifdef HAVE_NTGUI
3848 DeleteDC (hdc);
3849 #endif /* HAVE_NTGUI */
3851 switch (rc)
3853 case XpmOpenFailed:
3854 image_error ("Error opening XPM file (%s)", img->spec);
3855 break;
3857 case XpmFileInvalid:
3858 image_error ("Invalid XPM file (%s)", img->spec);
3859 break;
3861 case XpmNoMemory:
3862 image_error ("Out of memory (%s)", img->spec);
3863 break;
3865 case XpmColorFailed:
3866 image_error ("Color allocation error (%s)", img->spec);
3867 break;
3869 default:
3870 image_error ("Unknown error (%s)", img->spec);
3871 break;
3875 #ifdef ALLOC_XPM_COLORS
3876 xpm_free_color_cache ();
3877 #endif
3878 SAFE_FREE ();
3879 return rc == XpmSuccess;
3882 #endif /* HAVE_XPM */
3884 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3886 /* XPM support functions for NS where libxpm is not available.
3887 Only XPM version 3 (without any extensions) is supported. */
3889 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3890 int, Lisp_Object);
3891 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3892 const unsigned char *, int);
3893 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3894 int, Lisp_Object);
3895 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3896 const unsigned char *, int);
3898 /* Tokens returned from xpm_scan. */
3900 enum xpm_token
3902 XPM_TK_IDENT = 256,
3903 XPM_TK_STRING,
3904 XPM_TK_EOF
3907 /* Scan an XPM data and return a character (< 256) or a token defined
3908 by enum xpm_token above. *S and END are the start (inclusive) and
3909 the end (exclusive) addresses of the data, respectively. Advance
3910 *S while scanning. If token is either XPM_TK_IDENT or
3911 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3912 length of the corresponding token, respectively. */
3914 static int
3915 xpm_scan (const unsigned char **s,
3916 const unsigned char *end,
3917 const unsigned char **beg,
3918 ptrdiff_t *len)
3920 int c;
3922 while (*s < end)
3924 /* Skip white-space. */
3925 while (*s < end && (c = *(*s)++, c_isspace (c)))
3928 /* gnus-pointer.xpm uses '-' in its identifier.
3929 sb-dir-plus.xpm uses '+' in its identifier. */
3930 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3932 *beg = *s - 1;
3933 while (*s < end
3934 && (c = **s, c_isalnum (c)
3935 || c == '_' || c == '-' || c == '+'))
3936 ++*s;
3937 *len = *s - *beg;
3938 return XPM_TK_IDENT;
3940 else if (c == '"')
3942 *beg = *s;
3943 while (*s < end && **s != '"')
3944 ++*s;
3945 *len = *s - *beg;
3946 if (*s < end)
3947 ++*s;
3948 return XPM_TK_STRING;
3950 else if (c == '/')
3952 if (*s < end && **s == '*')
3954 /* C-style comment. */
3955 ++*s;
3958 while (*s < end && *(*s)++ != '*')
3961 while (*s < end && **s != '/');
3962 if (*s < end)
3963 ++*s;
3965 else
3966 return c;
3968 else
3969 return c;
3972 return XPM_TK_EOF;
3975 /* Functions for color table lookup in XPM data. A key is a string
3976 specifying the color of each pixel in XPM data. A value is either
3977 an integer that specifies a pixel color, Qt that specifies
3978 transparency, or Qnil for the unspecified color. If the length of
3979 the key string is one, a vector is used as a table. Otherwise, a
3980 hash table is used. */
3982 static Lisp_Object
3983 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3984 const unsigned char *,
3985 int,
3986 Lisp_Object),
3987 Lisp_Object (**get_func) (Lisp_Object,
3988 const unsigned char *,
3989 int))
3991 *put_func = xpm_put_color_table_v;
3992 *get_func = xpm_get_color_table_v;
3993 return Fmake_vector (make_number (256), Qnil);
3996 static void
3997 xpm_put_color_table_v (Lisp_Object color_table,
3998 const unsigned char *chars_start,
3999 int chars_len,
4000 Lisp_Object color)
4002 ASET (color_table, *chars_start, color);
4005 static Lisp_Object
4006 xpm_get_color_table_v (Lisp_Object color_table,
4007 const unsigned char *chars_start,
4008 int chars_len)
4010 return AREF (color_table, *chars_start);
4013 static Lisp_Object
4014 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
4015 const unsigned char *,
4016 int,
4017 Lisp_Object),
4018 Lisp_Object (**get_func) (Lisp_Object,
4019 const unsigned char *,
4020 int))
4022 *put_func = xpm_put_color_table_h;
4023 *get_func = xpm_get_color_table_h;
4024 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
4025 make_float (DEFAULT_REHASH_SIZE),
4026 make_float (DEFAULT_REHASH_THRESHOLD),
4027 Qnil);
4030 static void
4031 xpm_put_color_table_h (Lisp_Object color_table,
4032 const unsigned char *chars_start,
4033 int chars_len,
4034 Lisp_Object color)
4036 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4037 EMACS_UINT hash_code;
4038 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4040 hash_lookup (table, chars, &hash_code);
4041 hash_put (table, chars, color, hash_code);
4044 static Lisp_Object
4045 xpm_get_color_table_h (Lisp_Object color_table,
4046 const unsigned char *chars_start,
4047 int chars_len)
4049 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4050 ptrdiff_t i =
4051 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
4053 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4056 enum xpm_color_key {
4057 XPM_COLOR_KEY_S,
4058 XPM_COLOR_KEY_M,
4059 XPM_COLOR_KEY_G4,
4060 XPM_COLOR_KEY_G,
4061 XPM_COLOR_KEY_C
4064 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4066 static int
4067 xpm_str_to_color_key (const char *s)
4069 int i;
4071 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
4072 if (strcmp (xpm_color_key_strings[i], s) == 0)
4073 return i;
4074 return -1;
4077 static bool
4078 xpm_load_image (struct frame *f,
4079 struct image *img,
4080 const unsigned char *contents,
4081 const unsigned char *end)
4083 const unsigned char *s = contents, *beg, *str;
4084 unsigned char buffer[BUFSIZ];
4085 int width, height, x, y;
4086 int num_colors, chars_per_pixel;
4087 ptrdiff_t len;
4088 int LA1;
4089 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4090 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
4091 Lisp_Object frame, color_symbols, color_table;
4092 int best_key;
4093 bool have_mask = false;
4094 XImagePtr ximg = NULL, mask_img = NULL;
4096 #define match() \
4097 LA1 = xpm_scan (&s, end, &beg, &len)
4099 #define expect(TOKEN) \
4100 do \
4102 if (LA1 != (TOKEN)) \
4103 goto failure; \
4104 match (); \
4106 while (0)
4108 #define expect_ident(IDENT) \
4109 if (LA1 == XPM_TK_IDENT \
4110 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4111 match (); \
4112 else \
4113 goto failure
4115 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4116 goto failure;
4117 s += 9;
4118 match ();
4119 expect_ident ("static");
4120 expect_ident ("char");
4121 expect ('*');
4122 expect (XPM_TK_IDENT);
4123 expect ('[');
4124 expect (']');
4125 expect ('=');
4126 expect ('{');
4127 expect (XPM_TK_STRING);
4128 if (len >= BUFSIZ)
4129 goto failure;
4130 memcpy (buffer, beg, len);
4131 buffer[len] = '\0';
4132 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4133 &num_colors, &chars_per_pixel) != 4
4134 || width <= 0 || height <= 0
4135 || num_colors <= 0 || chars_per_pixel <= 0)
4136 goto failure;
4138 if (!check_image_size (f, width, height))
4140 image_size_error ();
4141 goto failure;
4144 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4145 #ifndef HAVE_NS
4146 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4147 &mask_img, 1)
4148 #endif
4151 image_error ("Image too large");
4152 goto failure;
4155 expect (',');
4157 XSETFRAME (frame, f);
4158 if (!NILP (Fxw_display_color_p (frame)))
4159 best_key = XPM_COLOR_KEY_C;
4160 else if (!NILP (Fx_display_grayscale_p (frame)))
4161 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4162 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4163 else
4164 best_key = XPM_COLOR_KEY_M;
4166 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4167 if (chars_per_pixel == 1)
4168 color_table = xpm_make_color_table_v (&put_color_table,
4169 &get_color_table);
4170 else
4171 color_table = xpm_make_color_table_h (&put_color_table,
4172 &get_color_table);
4174 while (num_colors-- > 0)
4176 char *color, *max_color;
4177 int key, next_key, max_key = 0;
4178 Lisp_Object symbol_color = Qnil, color_val;
4179 XColor cdef;
4181 expect (XPM_TK_STRING);
4182 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4183 goto failure;
4184 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4185 buffer[len - chars_per_pixel] = '\0';
4187 str = strtok (buffer, " \t");
4188 if (str == NULL)
4189 goto failure;
4190 key = xpm_str_to_color_key (str);
4191 if (key < 0)
4192 goto failure;
4195 color = strtok (NULL, " \t");
4196 if (color == NULL)
4197 goto failure;
4199 while ((str = strtok (NULL, " \t")) != NULL)
4201 next_key = xpm_str_to_color_key (str);
4202 if (next_key >= 0)
4203 break;
4204 color[strlen (color)] = ' ';
4207 if (key == XPM_COLOR_KEY_S)
4209 if (NILP (symbol_color))
4210 symbol_color = build_string (color);
4212 else if (max_key < key && key <= best_key)
4214 max_key = key;
4215 max_color = color;
4217 key = next_key;
4219 while (str);
4221 color_val = Qnil;
4222 if (!NILP (color_symbols) && !NILP (symbol_color))
4224 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4226 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4228 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4229 color_val = Qt;
4230 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4231 &cdef, 0))
4232 color_val = make_number (cdef.pixel);
4235 if (NILP (color_val) && max_key > 0)
4237 if (xstrcasecmp (max_color, "None") == 0)
4238 color_val = Qt;
4239 else if (x_defined_color (f, max_color, &cdef, 0))
4240 color_val = make_number (cdef.pixel);
4242 if (!NILP (color_val))
4243 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4245 expect (',');
4248 for (y = 0; y < height; y++)
4250 expect (XPM_TK_STRING);
4251 str = beg;
4252 if (len < width * chars_per_pixel)
4253 goto failure;
4254 for (x = 0; x < width; x++, str += chars_per_pixel)
4256 Lisp_Object color_val =
4257 (*get_color_table) (color_table, str, chars_per_pixel);
4259 XPutPixel (ximg, x, y,
4260 (INTEGERP (color_val) ? XINT (color_val)
4261 : FRAME_FOREGROUND_PIXEL (f)));
4262 #ifndef HAVE_NS
4263 XPutPixel (mask_img, x, y,
4264 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4265 : (have_mask = true, PIX_MASK_RETAIN)));
4266 #else
4267 if (EQ (color_val, Qt))
4268 ns_set_alpha (ximg, x, y, 0);
4269 #endif
4271 if (y + 1 < height)
4272 expect (',');
4275 img->width = width;
4276 img->height = height;
4278 /* Maybe fill in the background field while we have ximg handy. */
4279 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4280 IMAGE_BACKGROUND (img, f, ximg);
4282 image_put_x_image (f, img, ximg, 0);
4283 #ifndef HAVE_NS
4284 if (have_mask)
4286 /* Fill in the background_transparent field while we have the
4287 mask handy. */
4288 image_background_transparent (img, f, mask_img);
4290 image_put_x_image (f, img, mask_img, 1);
4292 else
4294 x_destroy_x_image (mask_img);
4295 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4297 #endif
4298 return 1;
4300 failure:
4301 image_error ("Invalid XPM file (%s)", img->spec);
4302 x_destroy_x_image (ximg);
4303 x_destroy_x_image (mask_img);
4304 x_clear_image (f, img);
4305 return 0;
4307 #undef match
4308 #undef expect
4309 #undef expect_ident
4312 static bool
4313 xpm_load (struct frame *f,
4314 struct image *img)
4316 bool success_p = 0;
4317 Lisp_Object file_name;
4319 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4320 file_name = image_spec_value (img->spec, QCfile, NULL);
4321 if (STRINGP (file_name))
4323 int fd;
4324 Lisp_Object file = x_find_image_fd (file_name, &fd);
4325 if (!STRINGP (file))
4327 image_error ("Cannot find image file `%s'", file_name);
4328 return 0;
4331 ptrdiff_t size;
4332 unsigned char *contents = slurp_file (fd, &size);
4333 if (contents == NULL)
4335 image_error ("Error loading XPM image `%s'", file);
4336 return 0;
4339 success_p = xpm_load_image (f, img, contents, contents + size);
4340 xfree (contents);
4342 else
4344 Lisp_Object data;
4346 data = image_spec_value (img->spec, QCdata, NULL);
4347 if (!STRINGP (data))
4349 image_error ("Invalid image data `%s'", data);
4350 return 0;
4352 success_p = xpm_load_image (f, img, SDATA (data),
4353 SDATA (data) + SBYTES (data));
4356 return success_p;
4359 #endif /* HAVE_NS && !HAVE_XPM */
4363 /***********************************************************************
4364 Color table
4365 ***********************************************************************/
4367 #ifdef COLOR_TABLE_SUPPORT
4369 /* An entry in the color table mapping an RGB color to a pixel color. */
4371 struct ct_color
4373 int r, g, b;
4374 unsigned long pixel;
4376 /* Next in color table collision list. */
4377 struct ct_color *next;
4380 /* The bucket vector size to use. Must be prime. */
4382 #define CT_SIZE 101
4384 /* Value is a hash of the RGB color given by R, G, and B. */
4386 static unsigned
4387 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4389 return (r << 16) ^ (g << 8) ^ b;
4392 /* The color hash table. */
4394 static struct ct_color **ct_table;
4396 /* Number of entries in the color table. */
4398 static int ct_colors_allocated;
4399 enum
4401 ct_colors_allocated_max =
4402 min (INT_MAX,
4403 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4406 /* Initialize the color table. */
4408 static void
4409 init_color_table (void)
4411 int size = CT_SIZE * sizeof (*ct_table);
4412 ct_table = xzalloc (size);
4413 ct_colors_allocated = 0;
4417 /* Free memory associated with the color table. */
4419 static void
4420 free_color_table (void)
4422 int i;
4423 struct ct_color *p, *next;
4425 for (i = 0; i < CT_SIZE; ++i)
4426 for (p = ct_table[i]; p; p = next)
4428 next = p->next;
4429 xfree (p);
4432 xfree (ct_table);
4433 ct_table = NULL;
4437 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4438 entry for that color already is in the color table, return the
4439 pixel color of that entry. Otherwise, allocate a new color for R,
4440 G, B, and make an entry in the color table. */
4442 static unsigned long
4443 lookup_rgb_color (struct frame *f, int r, int g, int b)
4445 unsigned hash = ct_hash_rgb (r, g, b);
4446 int i = hash % CT_SIZE;
4447 struct ct_color *p;
4448 Display_Info *dpyinfo;
4450 /* Handle TrueColor visuals specially, which improves performance by
4451 two orders of magnitude. Freeing colors on TrueColor visuals is
4452 a nop, and pixel colors specify RGB values directly. See also
4453 the Xlib spec, chapter 3.1. */
4454 dpyinfo = FRAME_DISPLAY_INFO (f);
4455 if (dpyinfo->red_bits > 0)
4457 /* Apply gamma-correction like normal color allocation does. */
4458 if (f->gamma)
4460 XColor color;
4461 color.red = r, color.green = g, color.blue = b;
4462 gamma_correct (f, &color);
4463 r = color.red, g = color.green, b = color.blue;
4466 return x_make_truecolor_pixel (dpyinfo, r, g, b);
4469 for (p = ct_table[i]; p; p = p->next)
4470 if (p->r == r && p->g == g && p->b == b)
4471 break;
4473 if (p == NULL)
4476 #ifdef HAVE_X_WINDOWS
4477 XColor color;
4478 Colormap cmap;
4479 bool rc;
4480 #else
4481 COLORREF color;
4482 #endif
4484 if (ct_colors_allocated_max <= ct_colors_allocated)
4485 return FRAME_FOREGROUND_PIXEL (f);
4487 #ifdef HAVE_X_WINDOWS
4488 color.red = r;
4489 color.green = g;
4490 color.blue = b;
4492 cmap = FRAME_X_COLORMAP (f);
4493 rc = x_alloc_nearest_color (f, cmap, &color);
4494 if (rc)
4496 ++ct_colors_allocated;
4497 p = xmalloc (sizeof *p);
4498 p->r = r;
4499 p->g = g;
4500 p->b = b;
4501 p->pixel = color.pixel;
4502 p->next = ct_table[i];
4503 ct_table[i] = p;
4505 else
4506 return FRAME_FOREGROUND_PIXEL (f);
4508 #else
4509 #ifdef HAVE_NTGUI
4510 color = PALETTERGB (r, g, b);
4511 #else
4512 color = RGB_TO_ULONG (r, g, b);
4513 #endif /* HAVE_NTGUI */
4514 ++ct_colors_allocated;
4515 p = xmalloc (sizeof *p);
4516 p->r = r;
4517 p->g = g;
4518 p->b = b;
4519 p->pixel = color;
4520 p->next = ct_table[i];
4521 ct_table[i] = p;
4522 #endif /* HAVE_X_WINDOWS */
4526 return p->pixel;
4530 /* Look up pixel color PIXEL which is used on frame F in the color
4531 table. If not already present, allocate it. Value is PIXEL. */
4533 static unsigned long
4534 lookup_pixel_color (struct frame *f, unsigned long pixel)
4536 int i = pixel % CT_SIZE;
4537 struct ct_color *p;
4539 for (p = ct_table[i]; p; p = p->next)
4540 if (p->pixel == pixel)
4541 break;
4543 if (p == NULL)
4545 XColor color;
4546 Colormap cmap;
4547 bool rc;
4549 if (ct_colors_allocated >= ct_colors_allocated_max)
4550 return FRAME_FOREGROUND_PIXEL (f);
4552 #ifdef HAVE_X_WINDOWS
4553 cmap = FRAME_X_COLORMAP (f);
4554 color.pixel = pixel;
4555 x_query_color (f, &color);
4556 rc = x_alloc_nearest_color (f, cmap, &color);
4557 #else
4558 block_input ();
4559 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4560 color.pixel = pixel;
4561 XQueryColor (NULL, cmap, &color);
4562 rc = x_alloc_nearest_color (f, cmap, &color);
4563 unblock_input ();
4564 #endif /* HAVE_X_WINDOWS */
4566 if (rc)
4568 ++ct_colors_allocated;
4570 p = xmalloc (sizeof *p);
4571 p->r = color.red;
4572 p->g = color.green;
4573 p->b = color.blue;
4574 p->pixel = pixel;
4575 p->next = ct_table[i];
4576 ct_table[i] = p;
4578 else
4579 return FRAME_FOREGROUND_PIXEL (f);
4581 return p->pixel;
4585 /* Value is a vector of all pixel colors contained in the color table,
4586 allocated via xmalloc. Set *N to the number of colors. */
4588 static unsigned long *
4589 colors_in_color_table (int *n)
4591 int i, j;
4592 struct ct_color *p;
4593 unsigned long *colors;
4595 if (ct_colors_allocated == 0)
4597 *n = 0;
4598 colors = NULL;
4600 else
4602 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4603 *n = ct_colors_allocated;
4605 for (i = j = 0; i < CT_SIZE; ++i)
4606 for (p = ct_table[i]; p; p = p->next)
4607 colors[j++] = p->pixel;
4610 return colors;
4613 #else /* COLOR_TABLE_SUPPORT */
4615 static unsigned long
4616 lookup_rgb_color (struct frame *f, int r, int g, int b)
4618 unsigned long pixel;
4620 #ifdef HAVE_NTGUI
4621 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4622 #endif /* HAVE_NTGUI */
4624 #ifdef HAVE_NS
4625 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4626 #endif /* HAVE_NS */
4627 return pixel;
4630 static void
4631 init_color_table (void)
4634 #endif /* COLOR_TABLE_SUPPORT */
4637 /***********************************************************************
4638 Algorithms
4639 ***********************************************************************/
4641 /* Edge detection matrices for different edge-detection
4642 strategies. */
4644 static int emboss_matrix[9] = {
4645 /* x - 1 x x + 1 */
4646 2, -1, 0, /* y - 1 */
4647 -1, 0, 1, /* y */
4648 0, 1, -2 /* y + 1 */
4651 static int laplace_matrix[9] = {
4652 /* x - 1 x x + 1 */
4653 1, 0, 0, /* y - 1 */
4654 0, 0, 0, /* y */
4655 0, 0, -1 /* y + 1 */
4658 /* Value is the intensity of the color whose red/green/blue values
4659 are R, G, and B. */
4661 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4664 /* On frame F, return an array of XColor structures describing image
4665 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4666 means also fill the red/green/blue members of the XColor
4667 structures. Value is a pointer to the array of XColors structures,
4668 allocated with xmalloc; it must be freed by the caller. */
4670 static XColor *
4671 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4673 int x, y;
4674 XColor *colors, *p;
4675 XImagePtr_or_DC ximg;
4676 ptrdiff_t nbytes;
4677 #ifdef HAVE_NTGUI
4678 HGDIOBJ prev;
4679 #endif /* HAVE_NTGUI */
4681 if (INT_MULTIPLY_WRAPV (sizeof *colors, img->width, &nbytes)
4682 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes)
4683 || SIZE_MAX < nbytes)
4684 memory_full (SIZE_MAX);
4685 colors = xmalloc (nbytes);
4687 /* Get the X image or create a memory device context for IMG. */
4688 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4690 /* Fill the `pixel' members of the XColor array. I wished there
4691 were an easy and portable way to circumvent XGetPixel. */
4692 p = colors;
4693 for (y = 0; y < img->height; ++y)
4695 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4696 XColor *row = p;
4697 for (x = 0; x < img->width; ++x, ++p)
4698 p->pixel = GET_PIXEL (ximg, x, y);
4699 if (rgb_p)
4700 x_query_colors (f, row, img->width);
4702 #else
4704 for (x = 0; x < img->width; ++x, ++p)
4706 /* W32_TODO: palette support needed here? */
4707 p->pixel = GET_PIXEL (ximg, x, y);
4708 if (rgb_p)
4710 p->red = RED16_FROM_ULONG (p->pixel);
4711 p->green = GREEN16_FROM_ULONG (p->pixel);
4712 p->blue = BLUE16_FROM_ULONG (p->pixel);
4715 #endif /* HAVE_X_WINDOWS */
4718 image_unget_x_image_or_dc (img, 0, ximg, prev);
4720 return colors;
4723 #ifdef HAVE_NTGUI
4725 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4726 created with CreateDIBSection, with the pointer to the bit values
4727 stored in ximg->data. */
4729 static void
4730 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4732 int width = ximg->info.bmiHeader.biWidth;
4733 unsigned char * pixel;
4735 /* True color images. */
4736 if (ximg->info.bmiHeader.biBitCount == 24)
4738 int rowbytes = width * 3;
4739 /* Ensure scanlines are aligned on 4 byte boundaries. */
4740 if (rowbytes % 4)
4741 rowbytes += 4 - (rowbytes % 4);
4743 pixel = ximg->data + y * rowbytes + x * 3;
4744 /* Windows bitmaps are in BGR order. */
4745 *pixel = GetBValue (color);
4746 *(pixel + 1) = GetGValue (color);
4747 *(pixel + 2) = GetRValue (color);
4749 /* Monochrome images. */
4750 else if (ximg->info.bmiHeader.biBitCount == 1)
4752 int rowbytes = width / 8;
4753 /* Ensure scanlines are aligned on 4 byte boundaries. */
4754 if (rowbytes % 4)
4755 rowbytes += 4 - (rowbytes % 4);
4756 pixel = ximg->data + y * rowbytes + x / 8;
4757 /* Filter out palette info. */
4758 if (color & 0x00ffffff)
4759 *pixel = *pixel | (1 << x % 8);
4760 else
4761 *pixel = *pixel & ~(1 << x % 8);
4763 else
4764 image_error ("XPutPixel: palette image not supported");
4767 #endif /* HAVE_NTGUI */
4769 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4770 RGB members are set. F is the frame on which this all happens.
4771 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4773 static void
4774 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4776 int x, y;
4777 XImagePtr oimg = NULL;
4778 XColor *p;
4780 init_color_table ();
4782 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4783 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4784 &oimg, 0);
4785 p = colors;
4786 for (y = 0; y < img->height; ++y)
4787 for (x = 0; x < img->width; ++x, ++p)
4789 unsigned long pixel;
4790 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4791 XPutPixel (oimg, x, y, pixel);
4794 xfree (colors);
4796 image_put_x_image (f, img, oimg, 0);
4797 #ifdef COLOR_TABLE_SUPPORT
4798 img->colors = colors_in_color_table (&img->ncolors);
4799 free_color_table ();
4800 #endif /* COLOR_TABLE_SUPPORT */
4804 /* On frame F, perform edge-detection on image IMG.
4806 MATRIX is a nine-element array specifying the transformation
4807 matrix. See emboss_matrix for an example.
4809 COLOR_ADJUST is a color adjustment added to each pixel of the
4810 outgoing image. */
4812 static void
4813 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4815 XColor *colors = x_to_xcolors (f, img, 1);
4816 XColor *new, *p;
4817 int x, y, i, sum;
4818 ptrdiff_t nbytes;
4820 for (i = sum = 0; i < 9; ++i)
4821 sum += eabs (matrix[i]);
4823 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4825 if (INT_MULTIPLY_WRAPV (sizeof *new, img->width, &nbytes)
4826 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes))
4827 memory_full (SIZE_MAX);
4828 new = xmalloc (nbytes);
4830 for (y = 0; y < img->height; ++y)
4832 p = COLOR (new, 0, y);
4833 p->red = p->green = p->blue = 0xffff/2;
4834 p = COLOR (new, img->width - 1, y);
4835 p->red = p->green = p->blue = 0xffff/2;
4838 for (x = 1; x < img->width - 1; ++x)
4840 p = COLOR (new, x, 0);
4841 p->red = p->green = p->blue = 0xffff/2;
4842 p = COLOR (new, x, img->height - 1);
4843 p->red = p->green = p->blue = 0xffff/2;
4846 for (y = 1; y < img->height - 1; ++y)
4848 p = COLOR (new, 1, y);
4850 for (x = 1; x < img->width - 1; ++x, ++p)
4852 int r, g, b, yy, xx;
4854 r = g = b = i = 0;
4855 for (yy = y - 1; yy < y + 2; ++yy)
4856 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4857 if (matrix[i])
4859 XColor *t = COLOR (colors, xx, yy);
4860 r += matrix[i] * t->red;
4861 g += matrix[i] * t->green;
4862 b += matrix[i] * t->blue;
4865 r = (r / sum + color_adjust) & 0xffff;
4866 g = (g / sum + color_adjust) & 0xffff;
4867 b = (b / sum + color_adjust) & 0xffff;
4868 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4872 xfree (colors);
4873 x_from_xcolors (f, img, new);
4875 #undef COLOR
4879 /* Perform the pre-defined `emboss' edge-detection on image IMG
4880 on frame F. */
4882 static void
4883 x_emboss (struct frame *f, struct image *img)
4885 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4889 /* Transform image IMG which is used on frame F with a Laplace
4890 edge-detection algorithm. The result is an image that can be used
4891 to draw disabled buttons, for example. */
4893 static void
4894 x_laplace (struct frame *f, struct image *img)
4896 x_detect_edges (f, img, laplace_matrix, 45000);
4900 /* Perform edge-detection on image IMG on frame F, with specified
4901 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4903 MATRIX must be either
4905 - a list of at least 9 numbers in row-major form
4906 - a vector of at least 9 numbers
4908 COLOR_ADJUST nil means use a default; otherwise it must be a
4909 number. */
4911 static void
4912 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4913 Lisp_Object color_adjust)
4915 int i = 0;
4916 int trans[9];
4918 if (CONSP (matrix))
4920 for (i = 0;
4921 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4922 ++i, matrix = XCDR (matrix))
4923 trans[i] = XFLOATINT (XCAR (matrix));
4925 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4927 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4928 trans[i] = XFLOATINT (AREF (matrix, i));
4931 if (NILP (color_adjust))
4932 color_adjust = make_number (0xffff / 2);
4934 if (i == 9 && NUMBERP (color_adjust))
4935 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4939 /* Transform image IMG on frame F so that it looks disabled. */
4941 static void
4942 x_disable_image (struct frame *f, struct image *img)
4944 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4945 #ifdef HAVE_NTGUI
4946 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4947 #else
4948 int n_planes = dpyinfo->n_planes;
4949 #endif /* HAVE_NTGUI */
4951 if (n_planes >= 2)
4953 /* Color (or grayscale). Convert to gray, and equalize. Just
4954 drawing such images with a stipple can look very odd, so
4955 we're using this method instead. */
4956 XColor *colors = x_to_xcolors (f, img, 1);
4957 XColor *p, *end;
4958 const int h = 15000;
4959 const int l = 30000;
4961 for (p = colors, end = colors + img->width * img->height;
4962 p < end;
4963 ++p)
4965 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4966 int i2 = (0xffff - h - l) * i / 0xffff + l;
4967 p->red = p->green = p->blue = i2;
4970 x_from_xcolors (f, img, colors);
4973 /* Draw a cross over the disabled image, if we must or if we
4974 should. */
4975 if (n_planes < 2 || cross_disabled_images)
4977 #ifndef HAVE_NTGUI
4978 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4980 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4982 Display *dpy = FRAME_X_DISPLAY (f);
4983 GC gc;
4985 image_sync_to_pixmaps (f, img);
4986 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4987 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4988 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4989 img->width - 1, img->height - 1);
4990 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4991 img->width - 1, 0);
4992 XFreeGC (dpy, gc);
4994 if (img->mask)
4996 gc = XCreateGC (dpy, img->mask, 0, NULL);
4997 XSetForeground (dpy, gc, MaskForeground (f));
4998 XDrawLine (dpy, img->mask, gc, 0, 0,
4999 img->width - 1, img->height - 1);
5000 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
5001 img->width - 1, 0);
5002 XFreeGC (dpy, gc);
5004 #endif /* !HAVE_NS */
5005 #else
5006 HDC hdc, bmpdc;
5007 HGDIOBJ prev;
5009 hdc = get_frame_dc (f);
5010 bmpdc = CreateCompatibleDC (hdc);
5011 release_frame_dc (f, hdc);
5013 prev = SelectObject (bmpdc, img->pixmap);
5015 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5016 MoveToEx (bmpdc, 0, 0, NULL);
5017 LineTo (bmpdc, img->width - 1, img->height - 1);
5018 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5019 LineTo (bmpdc, img->width - 1, 0);
5021 if (img->mask)
5023 SelectObject (bmpdc, img->mask);
5024 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5025 MoveToEx (bmpdc, 0, 0, NULL);
5026 LineTo (bmpdc, img->width - 1, img->height - 1);
5027 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5028 LineTo (bmpdc, img->width - 1, 0);
5030 SelectObject (bmpdc, prev);
5031 DeleteDC (bmpdc);
5032 #endif /* HAVE_NTGUI */
5037 /* Build a mask for image IMG which is used on frame F. FILE is the
5038 name of an image file, for error messages. HOW determines how to
5039 determine the background color of IMG. If it is a list '(R G B)',
5040 with R, G, and B being integers >= 0, take that as the color of the
5041 background. Otherwise, determine the background color of IMG
5042 heuristically. */
5044 static void
5045 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
5047 XImagePtr_or_DC ximg;
5048 #ifndef HAVE_NTGUI
5049 XImagePtr mask_img;
5050 #else
5051 HGDIOBJ prev;
5052 char *mask_img;
5053 int row_width;
5054 #endif /* HAVE_NTGUI */
5055 int x, y;
5056 bool use_img_background;
5057 unsigned long bg = 0;
5059 if (img->mask)
5060 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
5062 #ifndef HAVE_NTGUI
5063 #ifndef HAVE_NS
5064 /* Create an image and pixmap serving as mask. */
5065 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
5066 &mask_img, 1))
5067 return;
5068 #endif /* !HAVE_NS */
5069 #else
5070 /* Create the bit array serving as mask. */
5071 row_width = (img->width + 7) / 8;
5072 mask_img = xzalloc (row_width * img->height);
5073 #endif /* HAVE_NTGUI */
5075 /* Get the X image or create a memory device context for IMG. */
5076 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
5078 /* Determine the background color of ximg. If HOW is `(R G B)'
5079 take that as color. Otherwise, use the image's background color. */
5080 use_img_background = 1;
5082 if (CONSP (how))
5084 int rgb[3], i;
5086 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5088 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5089 how = XCDR (how);
5092 if (i == 3 && NILP (how))
5094 char color_name[30];
5095 sprintf (color_name, "#%04x%04x%04x",
5096 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
5097 bg = (
5098 #ifdef HAVE_NTGUI
5099 0x00ffffff & /* Filter out palette info. */
5100 #endif /* HAVE_NTGUI */
5101 x_alloc_image_color (f, img, build_string (color_name), 0));
5102 use_img_background = 0;
5106 if (use_img_background)
5107 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5109 /* Set all bits in mask_img to 1 whose color in ximg is different
5110 from the background color bg. */
5111 #ifndef HAVE_NTGUI
5112 for (y = 0; y < img->height; ++y)
5113 for (x = 0; x < img->width; ++x)
5114 #ifndef HAVE_NS
5115 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5116 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5117 #else
5118 if (XGetPixel (ximg, x, y) == bg)
5119 ns_set_alpha (ximg, x, y, 0);
5120 #endif /* HAVE_NS */
5121 #ifndef HAVE_NS
5122 /* Fill in the background_transparent field while we have the mask handy. */
5123 image_background_transparent (img, f, mask_img);
5125 /* Put mask_img into the image. */
5126 image_put_x_image (f, img, mask_img, 1);
5127 #endif /* !HAVE_NS */
5128 #else
5129 for (y = 0; y < img->height; ++y)
5130 for (x = 0; x < img->width; ++x)
5132 COLORREF p = GetPixel (ximg, x, y);
5133 if (p != bg)
5134 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5137 /* Create the mask image. */
5138 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5139 mask_img);
5140 /* Fill in the background_transparent field while we have the mask handy. */
5141 SelectObject (ximg, img->mask);
5142 image_background_transparent (img, f, ximg);
5144 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5145 xfree (mask_img);
5146 #endif /* HAVE_NTGUI */
5148 image_unget_x_image_or_dc (img, 0, ximg, prev);
5152 /***********************************************************************
5153 PBM (mono, gray, color)
5154 ***********************************************************************/
5156 static bool pbm_image_p (Lisp_Object object);
5157 static bool pbm_load (struct frame *f, struct image *img);
5159 /* Indices of image specification fields in gs_format, below. */
5161 enum pbm_keyword_index
5163 PBM_TYPE,
5164 PBM_FILE,
5165 PBM_DATA,
5166 PBM_ASCENT,
5167 PBM_MARGIN,
5168 PBM_RELIEF,
5169 PBM_ALGORITHM,
5170 PBM_HEURISTIC_MASK,
5171 PBM_MASK,
5172 PBM_FOREGROUND,
5173 PBM_BACKGROUND,
5174 PBM_LAST
5177 /* Vector of image_keyword structures describing the format
5178 of valid user-defined image specifications. */
5180 static const struct image_keyword pbm_format[PBM_LAST] =
5182 {":type", IMAGE_SYMBOL_VALUE, 1},
5183 {":file", IMAGE_STRING_VALUE, 0},
5184 {":data", IMAGE_STRING_VALUE, 0},
5185 {":ascent", IMAGE_ASCENT_VALUE, 0},
5186 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5187 {":relief", IMAGE_INTEGER_VALUE, 0},
5188 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5189 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5190 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5191 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5192 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5195 /* Structure describing the image type `pbm'. */
5197 static struct image_type pbm_type =
5199 SYMBOL_INDEX (Qpbm),
5200 pbm_image_p,
5201 pbm_load,
5202 x_clear_image,
5203 NULL,
5204 NULL
5208 /* Return true if OBJECT is a valid PBM image specification. */
5210 static bool
5211 pbm_image_p (Lisp_Object object)
5213 struct image_keyword fmt[PBM_LAST];
5215 memcpy (fmt, pbm_format, sizeof fmt);
5217 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5218 return 0;
5220 /* Must specify either :data or :file. */
5221 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5225 /* Get next char skipping comments in Netpbm header. Returns -1 at
5226 end of input. */
5228 static int
5229 pbm_next_char (unsigned char **s, unsigned char *end)
5231 int c = -1;
5233 while (*s < end && (c = *(*s)++, c == '#'))
5235 /* Skip to the next line break. */
5236 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5239 c = -1;
5242 return c;
5246 /* Scan a decimal number from *S and return it. Advance *S while
5247 reading the number. END is the end of the string. Value is -1 at
5248 end of input. */
5250 static int
5251 pbm_scan_number (unsigned char **s, unsigned char *end)
5253 int c = 0, val = -1;
5255 /* Skip white-space. */
5256 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5259 if (c_isdigit (c))
5261 /* Read decimal number. */
5262 val = c - '0';
5263 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5264 val = 10 * val + c - '0';
5267 return val;
5271 /* Load PBM image IMG for use on frame F. */
5273 static bool
5274 pbm_load (struct frame *f, struct image *img)
5276 bool raw_p;
5277 int x, y;
5278 int width, height, max_color_idx = 0;
5279 Lisp_Object specified_file;
5280 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5281 unsigned char *contents = NULL;
5282 unsigned char *end, *p;
5283 #ifdef USE_CAIRO
5284 unsigned char *data = 0;
5285 uint32_t *dataptr;
5286 #else
5287 XImagePtr ximg;
5288 #endif
5290 specified_file = image_spec_value (img->spec, QCfile, NULL);
5292 if (STRINGP (specified_file))
5294 int fd;
5295 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5296 if (!STRINGP (file))
5298 image_error ("Cannot find image file `%s'", specified_file);
5299 return 0;
5302 ptrdiff_t size;
5303 contents = slurp_file (fd, &size);
5304 if (contents == NULL)
5306 image_error ("Error reading `%s'", file);
5307 return 0;
5310 p = contents;
5311 end = contents + size;
5313 else
5315 Lisp_Object data;
5316 data = image_spec_value (img->spec, QCdata, NULL);
5317 if (!STRINGP (data))
5319 image_error ("Invalid image data `%s'", data);
5320 return 0;
5322 p = SDATA (data);
5323 end = p + SBYTES (data);
5326 /* Check magic number. */
5327 if (end - p < 2 || *p++ != 'P')
5329 image_error ("Not a PBM image: `%s'", img->spec);
5330 error:
5331 xfree (contents);
5332 img->pixmap = NO_PIXMAP;
5333 return 0;
5336 switch (*p++)
5338 case '1':
5339 raw_p = 0, type = PBM_MONO;
5340 break;
5342 case '2':
5343 raw_p = 0, type = PBM_GRAY;
5344 break;
5346 case '3':
5347 raw_p = 0, type = PBM_COLOR;
5348 break;
5350 case '4':
5351 raw_p = 1, type = PBM_MONO;
5352 break;
5354 case '5':
5355 raw_p = 1, type = PBM_GRAY;
5356 break;
5358 case '6':
5359 raw_p = 1, type = PBM_COLOR;
5360 break;
5362 default:
5363 image_error ("Not a PBM image: `%s'", img->spec);
5364 goto error;
5367 /* Read width, height, maximum color-component. Characters
5368 starting with `#' up to the end of a line are ignored. */
5369 width = pbm_scan_number (&p, end);
5370 height = pbm_scan_number (&p, end);
5372 #ifdef USE_CAIRO
5373 data = (unsigned char *) xmalloc (width * height * 4);
5374 dataptr = (uint32_t *) data;
5375 #endif
5377 if (type != PBM_MONO)
5379 max_color_idx = pbm_scan_number (&p, end);
5380 if (max_color_idx > 65535 || max_color_idx < 0)
5382 image_error ("Unsupported maximum PBM color value");
5383 goto error;
5387 if (!check_image_size (f, width, height))
5389 image_size_error ();
5390 goto error;
5393 #ifndef USE_CAIRO
5394 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5395 goto error;
5396 #endif
5398 /* Initialize the color hash table. */
5399 init_color_table ();
5401 if (type == PBM_MONO)
5403 int c = 0, g;
5404 struct image_keyword fmt[PBM_LAST];
5405 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5406 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5407 #ifdef USE_CAIRO
5408 XColor xfg, xbg;
5409 int fga32, bga32;
5410 #endif
5411 /* Parse the image specification. */
5412 memcpy (fmt, pbm_format, sizeof fmt);
5413 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5415 /* Get foreground and background colors, maybe allocate colors. */
5416 #ifdef USE_CAIRO
5417 if (! fmt[PBM_FOREGROUND].count
5418 || ! STRINGP (fmt[PBM_FOREGROUND].value)
5419 || ! x_defined_color (f, SSDATA (fmt[PBM_FOREGROUND].value), &xfg, 0))
5421 xfg.pixel = fg;
5422 x_query_color (f, &xfg);
5424 fga32 = xcolor_to_argb32 (xfg);
5426 if (! fmt[PBM_BACKGROUND].count
5427 || ! STRINGP (fmt[PBM_BACKGROUND].value)
5428 || ! x_defined_color (f, SSDATA (fmt[PBM_BACKGROUND].value), &xbg, 0))
5430 xbg.pixel = bg;
5431 x_query_color (f, &xbg);
5433 bga32 = xcolor_to_argb32 (xbg);
5434 #else
5435 if (fmt[PBM_FOREGROUND].count
5436 && STRINGP (fmt[PBM_FOREGROUND].value))
5437 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5438 if (fmt[PBM_BACKGROUND].count
5439 && STRINGP (fmt[PBM_BACKGROUND].value))
5441 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5442 img->background = bg;
5443 img->background_valid = 1;
5445 #endif
5447 for (y = 0; y < height; ++y)
5448 for (x = 0; x < width; ++x)
5450 if (raw_p)
5452 if ((x & 7) == 0)
5454 if (p >= end)
5456 #ifdef USE_CAIRO
5457 xfree (data);
5458 #else
5459 x_destroy_x_image (ximg);
5460 #endif
5461 x_clear_image (f, img);
5462 image_error ("Invalid image size in image `%s'",
5463 img->spec);
5464 goto error;
5466 c = *p++;
5468 g = c & 0x80;
5469 c <<= 1;
5471 else
5472 g = pbm_scan_number (&p, end);
5474 #ifdef USE_CAIRO
5475 *dataptr++ = g ? fga32 : bga32;
5476 #else
5477 XPutPixel (ximg, x, y, g ? fg : bg);
5478 #endif
5481 else
5483 int expected_size = height * width;
5484 if (max_color_idx > 255)
5485 expected_size *= 2;
5486 if (type == PBM_COLOR)
5487 expected_size *= 3;
5489 if (raw_p && p + expected_size > end)
5491 #ifdef USE_CAIRO
5492 xfree (data);
5493 #else
5494 x_destroy_x_image (ximg);
5495 #endif
5496 x_clear_image (f, img);
5497 image_error ("Invalid image size in image `%s'", img->spec);
5498 goto error;
5501 for (y = 0; y < height; ++y)
5502 for (x = 0; x < width; ++x)
5504 int r, g, b;
5506 if (type == PBM_GRAY && raw_p)
5508 r = g = b = *p++;
5509 if (max_color_idx > 255)
5510 r = g = b = r * 256 + *p++;
5512 else if (type == PBM_GRAY)
5513 r = g = b = pbm_scan_number (&p, end);
5514 else if (raw_p)
5516 r = *p++;
5517 if (max_color_idx > 255)
5518 r = r * 256 + *p++;
5519 g = *p++;
5520 if (max_color_idx > 255)
5521 g = g * 256 + *p++;
5522 b = *p++;
5523 if (max_color_idx > 255)
5524 b = b * 256 + *p++;
5526 else
5528 r = pbm_scan_number (&p, end);
5529 g = pbm_scan_number (&p, end);
5530 b = pbm_scan_number (&p, end);
5533 if (r < 0 || g < 0 || b < 0)
5535 #ifdef USE_CAIRO
5536 xfree (data);
5537 #else
5538 x_destroy_x_image (ximg);
5539 #endif
5540 image_error ("Invalid pixel value in image `%s'", img->spec);
5541 goto error;
5544 #ifdef USE_CAIRO
5545 r = (double) r * 255 / max_color_idx;
5546 g = (double) g * 255 / max_color_idx;
5547 b = (double) b * 255 / max_color_idx;
5548 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
5549 #else
5550 /* RGB values are now in the range 0..max_color_idx.
5551 Scale this to the range 0..0xffff supported by X. */
5552 r = (double) r * 65535 / max_color_idx;
5553 g = (double) g * 65535 / max_color_idx;
5554 b = (double) b * 65535 / max_color_idx;
5555 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5556 #endif
5560 #ifdef COLOR_TABLE_SUPPORT
5561 /* Store in IMG->colors the colors allocated for the image, and
5562 free the color table. */
5563 img->colors = colors_in_color_table (&img->ncolors);
5564 free_color_table ();
5565 #endif /* COLOR_TABLE_SUPPORT */
5567 img->width = width;
5568 img->height = height;
5570 /* Maybe fill in the background field while we have ximg handy. */
5572 #ifdef USE_CAIRO
5573 create_cairo_image_surface (img, data, width, height);
5574 #else
5575 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5576 /* Casting avoids a GCC warning. */
5577 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5579 /* Put ximg into the image. */
5580 image_put_x_image (f, img, ximg, 0);
5581 #endif
5583 /* X and W32 versions did it here, MAC version above. ++kfs
5584 img->width = width;
5585 img->height = height; */
5587 xfree (contents);
5588 return 1;
5592 /***********************************************************************
5594 ***********************************************************************/
5596 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5598 /* Function prototypes. */
5600 static bool png_image_p (Lisp_Object object);
5601 static bool png_load (struct frame *f, struct image *img);
5603 /* Indices of image specification fields in png_format, below. */
5605 enum png_keyword_index
5607 PNG_TYPE,
5608 PNG_DATA,
5609 PNG_FILE,
5610 PNG_ASCENT,
5611 PNG_MARGIN,
5612 PNG_RELIEF,
5613 PNG_ALGORITHM,
5614 PNG_HEURISTIC_MASK,
5615 PNG_MASK,
5616 PNG_BACKGROUND,
5617 PNG_LAST
5620 /* Vector of image_keyword structures describing the format
5621 of valid user-defined image specifications. */
5623 static const struct image_keyword png_format[PNG_LAST] =
5625 {":type", IMAGE_SYMBOL_VALUE, 1},
5626 {":data", IMAGE_STRING_VALUE, 0},
5627 {":file", IMAGE_STRING_VALUE, 0},
5628 {":ascent", IMAGE_ASCENT_VALUE, 0},
5629 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5630 {":relief", IMAGE_INTEGER_VALUE, 0},
5631 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5632 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5633 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5634 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5637 #if defined HAVE_NTGUI && defined WINDOWSNT
5638 static bool init_png_functions (void);
5639 #else
5640 #define init_png_functions NULL
5641 #endif
5643 /* Structure describing the image type `png'. */
5645 static struct image_type png_type =
5647 SYMBOL_INDEX (Qpng),
5648 png_image_p,
5649 png_load,
5650 x_clear_image,
5651 init_png_functions,
5652 NULL
5655 /* Return true if OBJECT is a valid PNG image specification. */
5657 static bool
5658 png_image_p (Lisp_Object object)
5660 struct image_keyword fmt[PNG_LAST];
5661 memcpy (fmt, png_format, sizeof fmt);
5663 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5664 return 0;
5666 /* Must specify either the :data or :file keyword. */
5667 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5670 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5673 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5675 # ifdef WINDOWSNT
5676 /* PNG library details. */
5678 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5679 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5680 DEF_DLL_FN (png_structp, png_create_read_struct,
5681 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5682 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5683 DEF_DLL_FN (void, png_destroy_read_struct,
5684 (png_structpp, png_infopp, png_infopp));
5685 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5686 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5687 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5688 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5689 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5690 int *, int *, int *, int *, int *));
5691 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5692 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5693 DEF_DLL_FN (void, png_set_expand, (png_structp));
5694 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5695 DEF_DLL_FN (void, png_set_background,
5696 (png_structp, png_color_16p, int, int, double));
5697 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5698 (png_structp, png_infop, png_color_16p *));
5699 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5700 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5701 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5702 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5703 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5704 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5706 # if (PNG_LIBPNG_VER >= 10500)
5707 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5708 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5709 (png_structp, png_longjmp_ptr, size_t));
5710 # endif /* libpng version >= 1.5 */
5712 static bool
5713 init_png_functions (void)
5715 HMODULE library;
5717 if (!(library = w32_delayed_load (Qpng)))
5718 return 0;
5720 LOAD_DLL_FN (library, png_get_io_ptr);
5721 LOAD_DLL_FN (library, png_sig_cmp);
5722 LOAD_DLL_FN (library, png_create_read_struct);
5723 LOAD_DLL_FN (library, png_create_info_struct);
5724 LOAD_DLL_FN (library, png_destroy_read_struct);
5725 LOAD_DLL_FN (library, png_set_read_fn);
5726 LOAD_DLL_FN (library, png_set_sig_bytes);
5727 LOAD_DLL_FN (library, png_read_info);
5728 LOAD_DLL_FN (library, png_get_IHDR);
5729 LOAD_DLL_FN (library, png_get_valid);
5730 LOAD_DLL_FN (library, png_set_strip_16);
5731 LOAD_DLL_FN (library, png_set_expand);
5732 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5733 LOAD_DLL_FN (library, png_set_background);
5734 LOAD_DLL_FN (library, png_get_bKGD);
5735 LOAD_DLL_FN (library, png_read_update_info);
5736 LOAD_DLL_FN (library, png_get_channels);
5737 LOAD_DLL_FN (library, png_get_rowbytes);
5738 LOAD_DLL_FN (library, png_read_image);
5739 LOAD_DLL_FN (library, png_read_end);
5740 LOAD_DLL_FN (library, png_error);
5742 # if (PNG_LIBPNG_VER >= 10500)
5743 LOAD_DLL_FN (library, png_longjmp);
5744 LOAD_DLL_FN (library, png_set_longjmp_fn);
5745 # endif /* libpng version >= 1.5 */
5747 return 1;
5750 # undef png_create_info_struct
5751 # undef png_create_read_struct
5752 # undef png_destroy_read_struct
5753 # undef png_error
5754 # undef png_get_bKGD
5755 # undef png_get_channels
5756 # undef png_get_IHDR
5757 # undef png_get_io_ptr
5758 # undef png_get_rowbytes
5759 # undef png_get_valid
5760 # undef png_longjmp
5761 # undef png_read_end
5762 # undef png_read_image
5763 # undef png_read_info
5764 # undef png_read_update_info
5765 # undef png_set_background
5766 # undef png_set_expand
5767 # undef png_set_gray_to_rgb
5768 # undef png_set_longjmp_fn
5769 # undef png_set_read_fn
5770 # undef png_set_sig_bytes
5771 # undef png_set_strip_16
5772 # undef png_sig_cmp
5774 # define png_create_info_struct fn_png_create_info_struct
5775 # define png_create_read_struct fn_png_create_read_struct
5776 # define png_destroy_read_struct fn_png_destroy_read_struct
5777 # define png_error fn_png_error
5778 # define png_get_bKGD fn_png_get_bKGD
5779 # define png_get_channels fn_png_get_channels
5780 # define png_get_IHDR fn_png_get_IHDR
5781 # define png_get_io_ptr fn_png_get_io_ptr
5782 # define png_get_rowbytes fn_png_get_rowbytes
5783 # define png_get_valid fn_png_get_valid
5784 # define png_longjmp fn_png_longjmp
5785 # define png_read_end fn_png_read_end
5786 # define png_read_image fn_png_read_image
5787 # define png_read_info fn_png_read_info
5788 # define png_read_update_info fn_png_read_update_info
5789 # define png_set_background fn_png_set_background
5790 # define png_set_expand fn_png_set_expand
5791 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5792 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5793 # define png_set_read_fn fn_png_set_read_fn
5794 # define png_set_sig_bytes fn_png_set_sig_bytes
5795 # define png_set_strip_16 fn_png_set_strip_16
5796 # define png_sig_cmp fn_png_sig_cmp
5798 # endif /* WINDOWSNT */
5800 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5801 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5802 Do not use sys_setjmp, as PNG supports only jmp_buf.
5803 It's OK if the longjmp substitute restores the signal mask. */
5804 # ifdef HAVE__SETJMP
5805 # define FAST_SETJMP(j) _setjmp (j)
5806 # define FAST_LONGJMP _longjmp
5807 # else
5808 # define FAST_SETJMP(j) setjmp (j)
5809 # define FAST_LONGJMP longjmp
5810 # endif
5812 # if PNG_LIBPNG_VER < 10500
5813 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5814 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5815 # else
5816 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5817 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5818 # define PNG_JMPBUF(ptr) \
5819 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5820 # endif
5822 /* Error and warning handlers installed when the PNG library
5823 is initialized. */
5825 static _Noreturn void
5826 my_png_error (png_struct *png_ptr, const char *msg)
5828 eassert (png_ptr != NULL);
5829 /* Avoid compiler warning about deprecated direct access to
5830 png_ptr's fields in libpng versions 1.4.x. */
5831 image_error ("PNG error: %s", build_string (msg));
5832 PNG_LONGJMP (png_ptr);
5836 static void
5837 my_png_warning (png_struct *png_ptr, const char *msg)
5839 eassert (png_ptr != NULL);
5840 image_error ("PNG warning: %s", build_string (msg));
5843 /* Memory source for PNG decoding. */
5845 struct png_memory_storage
5847 unsigned char *bytes; /* The data */
5848 ptrdiff_t len; /* How big is it? */
5849 ptrdiff_t index; /* Where are we? */
5853 /* Function set as reader function when reading PNG image from memory.
5854 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5855 bytes from the input to DATA. */
5857 static void
5858 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5860 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5862 if (length > tbr->len - tbr->index)
5863 png_error (png_ptr, "Read error");
5865 memcpy (data, tbr->bytes + tbr->index, length);
5866 tbr->index = tbr->index + length;
5870 /* Function set as reader function when reading PNG image from a file.
5871 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5872 bytes from the input to DATA. */
5874 static void
5875 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5877 FILE *fp = png_get_io_ptr (png_ptr);
5879 if (fread (data, 1, length, fp) < length)
5880 png_error (png_ptr, "Read error");
5884 /* Load PNG image IMG for use on frame F. Value is true if
5885 successful. */
5887 struct png_load_context
5889 /* These are members so that longjmp doesn't munge local variables. */
5890 png_struct *png_ptr;
5891 png_info *info_ptr;
5892 png_info *end_info;
5893 FILE *fp;
5894 png_byte *pixels;
5895 png_byte **rows;
5898 static bool
5899 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5901 Lisp_Object specified_file;
5902 Lisp_Object specified_data;
5903 int x, y;
5904 ptrdiff_t i;
5905 png_struct *png_ptr;
5906 png_info *info_ptr = NULL, *end_info = NULL;
5907 FILE *fp = NULL;
5908 png_byte sig[8];
5909 png_byte *pixels = NULL;
5910 png_byte **rows = NULL;
5911 png_uint_32 width, height;
5912 int bit_depth, color_type, interlace_type;
5913 png_byte channels;
5914 png_uint_32 row_bytes;
5915 bool transparent_p;
5916 struct png_memory_storage tbr; /* Data to be read */
5917 ptrdiff_t nbytes;
5919 #ifdef USE_CAIRO
5920 unsigned char *data = 0;
5921 uint32_t *dataptr;
5922 #else
5923 XImagePtr ximg, mask_img = NULL;
5924 #endif
5926 /* Find out what file to load. */
5927 specified_file = image_spec_value (img->spec, QCfile, NULL);
5928 specified_data = image_spec_value (img->spec, QCdata, NULL);
5929 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
5931 if (NILP (specified_data))
5933 int fd;
5934 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5935 if (!STRINGP (file))
5937 image_error ("Cannot find image file `%s'", specified_file);
5938 return 0;
5941 /* Open the image file. */
5942 fp = fdopen (fd, "rb");
5943 if (!fp)
5945 image_error ("Cannot open image file `%s'", file);
5946 return 0;
5949 /* Check PNG signature. */
5950 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5951 || png_sig_cmp (sig, 0, sizeof sig))
5953 fclose (fp);
5954 image_error ("Not a PNG file: `%s'", file);
5955 return 0;
5958 else
5960 if (!STRINGP (specified_data))
5962 image_error ("Invalid image data `%s'", specified_data);
5963 return 0;
5966 /* Read from memory. */
5967 tbr.bytes = SDATA (specified_data);
5968 tbr.len = SBYTES (specified_data);
5969 tbr.index = 0;
5971 /* Check PNG signature. */
5972 if (tbr.len < sizeof sig
5973 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5975 image_error ("Not a PNG image: `%s'", img->spec);
5976 return 0;
5979 /* Need to skip past the signature. */
5980 tbr.bytes += sizeof (sig);
5983 /* Initialize read and info structs for PNG lib. */
5984 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5985 NULL, my_png_error,
5986 my_png_warning);
5987 if (png_ptr)
5989 info_ptr = png_create_info_struct (png_ptr);
5990 end_info = png_create_info_struct (png_ptr);
5993 c->png_ptr = png_ptr;
5994 c->info_ptr = info_ptr;
5995 c->end_info = end_info;
5996 c->fp = fp;
5997 c->pixels = pixels;
5998 c->rows = rows;
6000 if (! (info_ptr && end_info))
6002 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6003 png_ptr = 0;
6005 if (! png_ptr)
6007 if (fp) fclose (fp);
6008 return 0;
6011 /* Set error jump-back. We come back here when the PNG library
6012 detects an error. */
6013 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
6015 error:
6016 if (c->png_ptr)
6017 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6018 xfree (c->pixels);
6019 xfree (c->rows);
6020 if (c->fp)
6021 fclose (c->fp);
6022 return 0;
6025 /* Silence a bogus diagnostic; see GCC bug 54561. */
6026 IF_LINT (fp = c->fp);
6027 IF_LINT (specified_data = specified_data_volatile);
6029 /* Read image info. */
6030 if (!NILP (specified_data))
6031 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
6032 else
6033 png_set_read_fn (png_ptr, fp, png_read_from_file);
6035 png_set_sig_bytes (png_ptr, sizeof sig);
6036 png_read_info (png_ptr, info_ptr);
6037 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6038 &interlace_type, NULL, NULL);
6040 if (! (width <= INT_MAX && height <= INT_MAX
6041 && check_image_size (f, width, height)))
6043 image_size_error ();
6044 goto error;
6047 #ifndef USE_CAIRO
6048 /* Create the X image and pixmap now, so that the work below can be
6049 omitted if the image is too large for X. */
6050 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6051 goto error;
6052 #endif
6054 /* If image contains simply transparency data, we prefer to
6055 construct a clipping mask. */
6056 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6057 transparent_p = 1;
6058 else
6059 transparent_p = 0;
6061 /* This function is easier to write if we only have to handle
6062 one data format: RGB or RGBA with 8 bits per channel. Let's
6063 transform other formats into that format. */
6065 /* Strip more than 8 bits per channel. */
6066 if (bit_depth == 16)
6067 png_set_strip_16 (png_ptr);
6069 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6070 if available. */
6071 png_set_expand (png_ptr);
6073 /* Convert grayscale images to RGB. */
6074 if (color_type == PNG_COLOR_TYPE_GRAY
6075 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6076 png_set_gray_to_rgb (png_ptr);
6078 /* Handle alpha channel by combining the image with a background
6079 color. Do this only if a real alpha channel is supplied. For
6080 simple transparency, we prefer a clipping mask. */
6081 if (!transparent_p)
6083 /* png_color_16 *image_bg; */
6084 Lisp_Object specified_bg
6085 = image_spec_value (img->spec, QCbackground, NULL);
6086 XColor color;
6088 /* If the user specified a color, try to use it; if not, use the
6089 current frame background, ignoring any default background
6090 color set by the image. */
6091 if (STRINGP (specified_bg)
6092 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
6093 : (x_query_frame_background_color (f, &color), true))
6094 /* The user specified `:background', use that. */
6096 int shift = bit_depth == 16 ? 0 : 8;
6097 png_color_16 bg = { 0 };
6098 bg.red = color.red >> shift;
6099 bg.green = color.green >> shift;
6100 bg.blue = color.blue >> shift;
6102 png_set_background (png_ptr, &bg,
6103 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6107 /* Update info structure. */
6108 png_read_update_info (png_ptr, info_ptr);
6110 /* Get number of channels. Valid values are 1 for grayscale images
6111 and images with a palette, 2 for grayscale images with transparency
6112 information (alpha channel), 3 for RGB images, and 4 for RGB
6113 images with alpha channel, i.e. RGBA. If conversions above were
6114 sufficient we should only have 3 or 4 channels here. */
6115 channels = png_get_channels (png_ptr, info_ptr);
6116 eassert (channels == 3 || channels == 4);
6118 /* Number of bytes needed for one row of the image. */
6119 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
6121 /* Allocate memory for the image. */
6122 if (INT_MULTIPLY_WRAPV (row_bytes, sizeof *pixels, &nbytes)
6123 || INT_MULTIPLY_WRAPV (nbytes, height, &nbytes))
6124 memory_full (SIZE_MAX);
6125 c->pixels = pixels = xmalloc (nbytes);
6126 c->rows = rows = xmalloc (height * sizeof *rows);
6127 for (i = 0; i < height; ++i)
6128 rows[i] = pixels + i * row_bytes;
6130 /* Read the entire image. */
6131 png_read_image (png_ptr, rows);
6132 png_read_end (png_ptr, info_ptr);
6133 if (fp)
6135 fclose (fp);
6136 c->fp = NULL;
6139 #ifdef USE_CAIRO
6140 data = (unsigned char *) xmalloc (width * height * 4);
6141 dataptr = (uint32_t *) data;
6142 #else
6143 /* Create an image and pixmap serving as mask if the PNG image
6144 contains an alpha channel. */
6145 if (channels == 4
6146 && !transparent_p
6147 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
6148 &mask_img, 1))
6150 x_destroy_x_image (ximg);
6151 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
6152 goto error;
6154 #endif
6156 /* Fill the X image and mask from PNG data. */
6157 init_color_table ();
6159 for (y = 0; y < height; ++y)
6161 png_byte *p = rows[y];
6163 for (x = 0; x < width; ++x)
6165 int r, g, b;
6167 #ifdef USE_CAIRO
6168 int a = 0xff;
6169 r = *p++;
6170 g = *p++;
6171 b = *p++;
6172 if (channels == 4) a = *p++;
6173 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
6174 #else
6175 r = *p++ << 8;
6176 g = *p++ << 8;
6177 b = *p++ << 8;
6178 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6179 /* An alpha channel, aka mask channel, associates variable
6180 transparency with an image. Where other image formats
6181 support binary transparency---fully transparent or fully
6182 opaque---PNG allows up to 254 levels of partial transparency.
6183 The PNG library implements partial transparency by combining
6184 the image with a specified background color.
6186 I'm not sure how to handle this here nicely: because the
6187 background on which the image is displayed may change, for
6188 real alpha channel support, it would be necessary to create
6189 a new image for each possible background.
6191 What I'm doing now is that a mask is created if we have
6192 boolean transparency information. Otherwise I'm using
6193 the frame's background color to combine the image with. */
6195 if (channels == 4)
6197 if (mask_img)
6198 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6199 ++p;
6201 #endif
6205 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6206 /* Set IMG's background color from the PNG image, unless the user
6207 overrode it. */
6209 png_color_16 *bg;
6210 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6212 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6213 img->background_valid = 1;
6217 # ifdef COLOR_TABLE_SUPPORT
6218 /* Remember colors allocated for this image. */
6219 img->colors = colors_in_color_table (&img->ncolors);
6220 free_color_table ();
6221 # endif /* COLOR_TABLE_SUPPORT */
6223 /* Clean up. */
6224 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6225 xfree (rows);
6226 xfree (pixels);
6228 img->width = width;
6229 img->height = height;
6231 #ifdef USE_CAIRO
6232 create_cairo_image_surface (img, data, width, height);
6233 #else
6234 /* Maybe fill in the background field while we have ximg handy.
6235 Casting avoids a GCC warning. */
6236 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6238 /* Put ximg into the image. */
6239 image_put_x_image (f, img, ximg, 0);
6241 /* Same for the mask. */
6242 if (mask_img)
6244 /* Fill in the background_transparent field while we have the
6245 mask handy. Casting avoids a GCC warning. */
6246 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6248 image_put_x_image (f, img, mask_img, 1);
6250 #endif
6252 return 1;
6255 static bool
6256 png_load (struct frame *f, struct image *img)
6258 struct png_load_context c;
6259 return png_load_body (f, img, &c);
6262 #elif defined HAVE_NS
6264 static bool
6265 png_load (struct frame *f, struct image *img)
6267 return ns_load_image (f, img,
6268 image_spec_value (img->spec, QCfile, NULL),
6269 image_spec_value (img->spec, QCdata, NULL));
6273 #endif /* HAVE_NS */
6277 /***********************************************************************
6278 JPEG
6279 ***********************************************************************/
6281 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6283 static bool jpeg_image_p (Lisp_Object object);
6284 static bool jpeg_load (struct frame *f, struct image *img);
6286 /* Indices of image specification fields in gs_format, below. */
6288 enum jpeg_keyword_index
6290 JPEG_TYPE,
6291 JPEG_DATA,
6292 JPEG_FILE,
6293 JPEG_ASCENT,
6294 JPEG_MARGIN,
6295 JPEG_RELIEF,
6296 JPEG_ALGORITHM,
6297 JPEG_HEURISTIC_MASK,
6298 JPEG_MASK,
6299 JPEG_BACKGROUND,
6300 JPEG_LAST
6303 /* Vector of image_keyword structures describing the format
6304 of valid user-defined image specifications. */
6306 static const struct image_keyword jpeg_format[JPEG_LAST] =
6308 {":type", IMAGE_SYMBOL_VALUE, 1},
6309 {":data", IMAGE_STRING_VALUE, 0},
6310 {":file", IMAGE_STRING_VALUE, 0},
6311 {":ascent", IMAGE_ASCENT_VALUE, 0},
6312 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6313 {":relief", IMAGE_INTEGER_VALUE, 0},
6314 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6315 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6316 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6317 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6320 #if defined HAVE_NTGUI && defined WINDOWSNT
6321 static bool init_jpeg_functions (void);
6322 #else
6323 #define init_jpeg_functions NULL
6324 #endif
6326 /* Structure describing the image type `jpeg'. */
6328 static struct image_type jpeg_type =
6330 SYMBOL_INDEX (Qjpeg),
6331 jpeg_image_p,
6332 jpeg_load,
6333 x_clear_image,
6334 init_jpeg_functions,
6335 NULL
6338 /* Return true if OBJECT is a valid JPEG image specification. */
6340 static bool
6341 jpeg_image_p (Lisp_Object object)
6343 struct image_keyword fmt[JPEG_LAST];
6345 memcpy (fmt, jpeg_format, sizeof fmt);
6347 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6348 return 0;
6350 /* Must specify either the :data or :file keyword. */
6351 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6354 #endif /* HAVE_JPEG || HAVE_NS */
6356 #ifdef HAVE_JPEG
6358 /* Work around a warning about HAVE_STDLIB_H being redefined in
6359 jconfig.h. */
6360 # ifdef HAVE_STDLIB_H
6361 # undef HAVE_STDLIB_H
6362 # endif
6364 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6365 /* In older releases of the jpeg library, jpeglib.h will define boolean
6366 differently depending on __WIN32__, so make sure it is defined. */
6367 # define __WIN32__ 1
6368 # endif
6370 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6371 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6372 using the Windows boolean type instead of the jpeglib boolean type
6373 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6374 headers are included along with windows.h, so under Cygwin, jpeglib
6375 attempts to define a conflicting boolean type. Worse, forcing
6376 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6377 because it created an ABI incompatibility between the
6378 already-compiled jpeg library and the header interface definition.
6380 The best we can do is to define jpeglib's boolean type to a
6381 different name. This name, jpeg_boolean, remains in effect through
6382 the rest of image.c.
6384 # if defined CYGWIN && defined HAVE_NTGUI
6385 # define boolean jpeg_boolean
6386 # endif
6387 # include <jpeglib.h>
6388 # include <jerror.h>
6390 # ifdef WINDOWSNT
6392 /* JPEG library details. */
6393 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6394 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6395 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6396 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6397 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6398 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6399 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6400 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6401 (struct jpeg_error_mgr *));
6402 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6404 static bool
6405 init_jpeg_functions (void)
6407 HMODULE library;
6409 if (!(library = w32_delayed_load (Qjpeg)))
6410 return 0;
6412 LOAD_DLL_FN (library, jpeg_finish_decompress);
6413 LOAD_DLL_FN (library, jpeg_read_scanlines);
6414 LOAD_DLL_FN (library, jpeg_start_decompress);
6415 LOAD_DLL_FN (library, jpeg_read_header);
6416 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6417 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6418 LOAD_DLL_FN (library, jpeg_std_error);
6419 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6420 return 1;
6423 # undef jpeg_CreateDecompress
6424 # undef jpeg_destroy_decompress
6425 # undef jpeg_finish_decompress
6426 # undef jpeg_read_header
6427 # undef jpeg_read_scanlines
6428 # undef jpeg_resync_to_restart
6429 # undef jpeg_start_decompress
6430 # undef jpeg_std_error
6432 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6433 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6434 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6435 # define jpeg_read_header fn_jpeg_read_header
6436 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6437 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6438 # define jpeg_start_decompress fn_jpeg_start_decompress
6439 # define jpeg_std_error fn_jpeg_std_error
6441 /* Wrapper since we can't directly assign the function pointer
6442 to another function pointer that was declared more completely easily. */
6443 static boolean
6444 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6446 return jpeg_resync_to_restart (cinfo, desired);
6448 # undef jpeg_resync_to_restart
6449 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6451 # endif /* WINDOWSNT */
6453 struct my_jpeg_error_mgr
6455 struct jpeg_error_mgr pub;
6456 sys_jmp_buf setjmp_buffer;
6458 /* The remaining members are so that longjmp doesn't munge local
6459 variables. */
6460 struct jpeg_decompress_struct cinfo;
6461 enum
6463 MY_JPEG_ERROR_EXIT,
6464 MY_JPEG_INVALID_IMAGE_SIZE,
6465 MY_JPEG_CANNOT_CREATE_X
6466 } failure_code;
6470 static _Noreturn void
6471 my_error_exit (j_common_ptr cinfo)
6473 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6474 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6475 sys_longjmp (mgr->setjmp_buffer, 1);
6479 /* Init source method for JPEG data source manager. Called by
6480 jpeg_read_header() before any data is actually read. See
6481 libjpeg.doc from the JPEG lib distribution. */
6483 static void
6484 our_common_init_source (j_decompress_ptr cinfo)
6489 /* Method to terminate data source. Called by
6490 jpeg_finish_decompress() after all data has been processed. */
6492 static void
6493 our_common_term_source (j_decompress_ptr cinfo)
6498 /* Fill input buffer method for JPEG data source manager. Called
6499 whenever more data is needed. We read the whole image in one step,
6500 so this only adds a fake end of input marker at the end. */
6502 static JOCTET our_memory_buffer[2];
6504 static boolean
6505 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6507 /* Insert a fake EOI marker. */
6508 struct jpeg_source_mgr *src = cinfo->src;
6510 our_memory_buffer[0] = (JOCTET) 0xFF;
6511 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6513 src->next_input_byte = our_memory_buffer;
6514 src->bytes_in_buffer = 2;
6515 return 1;
6519 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6520 is the JPEG data source manager. */
6522 static void
6523 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6525 struct jpeg_source_mgr *src = cinfo->src;
6527 if (src)
6529 if (num_bytes > src->bytes_in_buffer)
6530 ERREXIT (cinfo, JERR_INPUT_EOF);
6532 src->bytes_in_buffer -= num_bytes;
6533 src->next_input_byte += num_bytes;
6538 /* Set up the JPEG lib for reading an image from DATA which contains
6539 LEN bytes. CINFO is the decompression info structure created for
6540 reading the image. */
6542 static void
6543 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6545 struct jpeg_source_mgr *src = cinfo->src;
6547 if (! src)
6549 /* First time for this JPEG object? */
6550 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6551 JPOOL_PERMANENT, sizeof *src);
6552 cinfo->src = src;
6553 src->next_input_byte = data;
6556 src->init_source = our_common_init_source;
6557 src->fill_input_buffer = our_memory_fill_input_buffer;
6558 src->skip_input_data = our_memory_skip_input_data;
6559 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6560 src->term_source = our_common_term_source;
6561 src->bytes_in_buffer = len;
6562 src->next_input_byte = data;
6566 struct jpeg_stdio_mgr
6568 struct jpeg_source_mgr mgr;
6569 boolean finished;
6570 FILE *file;
6571 JOCTET *buffer;
6575 /* Size of buffer to read JPEG from file.
6576 Not too big, as we want to use alloc_small. */
6577 #define JPEG_STDIO_BUFFER_SIZE 8192
6580 /* Fill input buffer method for JPEG data source manager. Called
6581 whenever more data is needed. The data is read from a FILE *. */
6583 static boolean
6584 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6586 struct jpeg_stdio_mgr *src;
6588 src = (struct jpeg_stdio_mgr *) cinfo->src;
6589 if (!src->finished)
6591 ptrdiff_t bytes;
6593 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6594 if (bytes > 0)
6595 src->mgr.bytes_in_buffer = bytes;
6596 else
6598 WARNMS (cinfo, JWRN_JPEG_EOF);
6599 src->finished = 1;
6600 src->buffer[0] = (JOCTET) 0xFF;
6601 src->buffer[1] = (JOCTET) JPEG_EOI;
6602 src->mgr.bytes_in_buffer = 2;
6604 src->mgr.next_input_byte = src->buffer;
6607 return 1;
6611 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6612 is the JPEG data source manager. */
6614 static void
6615 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6617 struct jpeg_stdio_mgr *src;
6618 src = (struct jpeg_stdio_mgr *) cinfo->src;
6620 while (num_bytes > 0 && !src->finished)
6622 if (num_bytes <= src->mgr.bytes_in_buffer)
6624 src->mgr.bytes_in_buffer -= num_bytes;
6625 src->mgr.next_input_byte += num_bytes;
6626 break;
6628 else
6630 num_bytes -= src->mgr.bytes_in_buffer;
6631 src->mgr.bytes_in_buffer = 0;
6632 src->mgr.next_input_byte = NULL;
6634 our_stdio_fill_input_buffer (cinfo);
6640 /* Set up the JPEG lib for reading an image from a FILE *.
6641 CINFO is the decompression info structure created for
6642 reading the image. */
6644 static void
6645 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6647 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6649 if (! src)
6651 /* First time for this JPEG object? */
6652 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6653 JPOOL_PERMANENT, sizeof *src);
6654 cinfo->src = (struct jpeg_source_mgr *) src;
6655 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6656 JPOOL_PERMANENT,
6657 JPEG_STDIO_BUFFER_SIZE);
6660 src->file = fp;
6661 src->finished = 0;
6662 src->mgr.init_source = our_common_init_source;
6663 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6664 src->mgr.skip_input_data = our_stdio_skip_input_data;
6665 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6666 src->mgr.term_source = our_common_term_source;
6667 src->mgr.bytes_in_buffer = 0;
6668 src->mgr.next_input_byte = NULL;
6671 /* Load image IMG for use on frame F. Patterned after example.c
6672 from the JPEG lib. */
6674 static bool
6675 jpeg_load_body (struct frame *f, struct image *img,
6676 struct my_jpeg_error_mgr *mgr)
6678 Lisp_Object specified_file;
6679 Lisp_Object specified_data;
6680 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6681 FILE * IF_LINT (volatile) fp = NULL;
6682 JSAMPARRAY buffer;
6683 int row_stride, x, y;
6684 unsigned long *colors;
6685 int width, height;
6686 int i, ir, ig, ib;
6687 #ifndef USE_CAIRO
6688 XImagePtr ximg = NULL;
6689 #endif
6691 /* Open the JPEG file. */
6692 specified_file = image_spec_value (img->spec, QCfile, NULL);
6693 specified_data = image_spec_value (img->spec, QCdata, NULL);
6694 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
6696 if (NILP (specified_data))
6698 int fd;
6699 Lisp_Object file = x_find_image_fd (specified_file, &fd);
6700 if (!STRINGP (file))
6702 image_error ("Cannot find image file `%s'", specified_file);
6703 return 0;
6706 fp = fdopen (fd, "rb");
6707 if (fp == NULL)
6709 image_error ("Cannot open `%s'", file);
6710 return 0;
6713 else if (!STRINGP (specified_data))
6715 image_error ("Invalid image data `%s'", specified_data);
6716 return 0;
6719 /* Customize libjpeg's error handling to call my_error_exit when an
6720 error is detected. This function will perform a longjmp. */
6721 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6722 mgr->pub.error_exit = my_error_exit;
6723 if (sys_setjmp (mgr->setjmp_buffer))
6725 switch (mgr->failure_code)
6727 case MY_JPEG_ERROR_EXIT:
6729 char buf[JMSG_LENGTH_MAX];
6730 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6731 image_error ("Error reading JPEG image `%s': %s",
6732 img->spec, build_string (buf));
6733 break;
6736 case MY_JPEG_INVALID_IMAGE_SIZE:
6737 image_size_error ();
6738 break;
6740 case MY_JPEG_CANNOT_CREATE_X:
6741 break;
6744 /* Close the input file and destroy the JPEG object. */
6745 if (fp)
6746 fclose (fp);
6747 jpeg_destroy_decompress (&mgr->cinfo);
6749 /* If we already have an XImage, free that. */
6750 #ifndef USE_CAIRO
6751 x_destroy_x_image (ximg);
6752 #endif
6753 /* Free pixmap and colors. */
6754 x_clear_image (f, img);
6755 return 0;
6758 /* Silence a bogus diagnostic; see GCC bug 54561. */
6759 IF_LINT (specified_data = specified_data_volatile);
6761 /* Create the JPEG decompression object. Let it read from fp.
6762 Read the JPEG image header. */
6763 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6765 if (NILP (specified_data))
6766 jpeg_file_src (&mgr->cinfo, fp);
6767 else
6768 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6769 SBYTES (specified_data));
6771 jpeg_read_header (&mgr->cinfo, 1);
6773 /* Customize decompression so that color quantization will be used.
6774 Start decompression. */
6775 mgr->cinfo.quantize_colors = 1;
6776 jpeg_start_decompress (&mgr->cinfo);
6777 width = img->width = mgr->cinfo.output_width;
6778 height = img->height = mgr->cinfo.output_height;
6780 if (!check_image_size (f, width, height))
6782 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6783 sys_longjmp (mgr->setjmp_buffer, 1);
6786 #ifndef USE_CAIRO
6787 /* Create X image and pixmap. */
6788 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6790 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6791 sys_longjmp (mgr->setjmp_buffer, 1);
6793 #endif
6795 /* Allocate colors. When color quantization is used,
6796 mgr->cinfo.actual_number_of_colors has been set with the number of
6797 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6798 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6799 No more than 255 colors will be generated. */
6800 USE_SAFE_ALLOCA;
6802 if (mgr->cinfo.out_color_components > 2)
6803 ir = 0, ig = 1, ib = 2;
6804 else if (mgr->cinfo.out_color_components > 1)
6805 ir = 0, ig = 1, ib = 0;
6806 else
6807 ir = 0, ig = 0, ib = 0;
6809 #ifndef CAIRO
6810 /* Use the color table mechanism because it handles colors that
6811 cannot be allocated nicely. Such colors will be replaced with
6812 a default color, and we don't have to care about which colors
6813 can be freed safely, and which can't. */
6814 init_color_table ();
6815 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6817 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6819 /* Multiply RGB values with 255 because X expects RGB values
6820 in the range 0..0xffff. */
6821 int r = mgr->cinfo.colormap[ir][i] << 8;
6822 int g = mgr->cinfo.colormap[ig][i] << 8;
6823 int b = mgr->cinfo.colormap[ib][i] << 8;
6824 colors[i] = lookup_rgb_color (f, r, g, b);
6826 #endif
6828 #ifdef COLOR_TABLE_SUPPORT
6829 /* Remember those colors actually allocated. */
6830 img->colors = colors_in_color_table (&img->ncolors);
6831 free_color_table ();
6832 #endif /* COLOR_TABLE_SUPPORT */
6835 /* Read pixels. */
6836 row_stride = width * mgr->cinfo.output_components;
6837 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6838 JPOOL_IMAGE, row_stride, 1);
6839 #ifdef USE_CAIRO
6841 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
6842 uint32_t *dataptr = (uint32_t *) data;
6843 int r, g, b;
6845 for (y = 0; y < height; ++y)
6847 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6849 for (x = 0; x < width; ++x)
6851 i = buffer[0][x];
6852 r = mgr->cinfo.colormap[ir][i];
6853 g = mgr->cinfo.colormap[ig][i];
6854 b = mgr->cinfo.colormap[ib][i];
6855 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
6859 create_cairo_image_surface (img, data, width, height);
6861 #else
6862 for (y = 0; y < height; ++y)
6864 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6865 for (x = 0; x < mgr->cinfo.output_width; ++x)
6866 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6868 #endif
6870 /* Clean up. */
6871 jpeg_finish_decompress (&mgr->cinfo);
6872 jpeg_destroy_decompress (&mgr->cinfo);
6873 if (fp)
6874 fclose (fp);
6876 #ifndef USE_CAIRO
6877 /* Maybe fill in the background field while we have ximg handy. */
6878 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6879 /* Casting avoids a GCC warning. */
6880 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6882 /* Put ximg into the image. */
6883 image_put_x_image (f, img, ximg, 0);
6884 #endif
6885 SAFE_FREE ();
6886 return 1;
6889 static bool
6890 jpeg_load (struct frame *f, struct image *img)
6892 struct my_jpeg_error_mgr mgr;
6893 return jpeg_load_body (f, img, &mgr);
6896 #else /* HAVE_JPEG */
6898 #ifdef HAVE_NS
6899 static bool
6900 jpeg_load (struct frame *f, struct image *img)
6902 return ns_load_image (f, img,
6903 image_spec_value (img->spec, QCfile, NULL),
6904 image_spec_value (img->spec, QCdata, NULL));
6906 #endif /* HAVE_NS */
6908 #endif /* !HAVE_JPEG */
6912 /***********************************************************************
6913 TIFF
6914 ***********************************************************************/
6916 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6918 static bool tiff_image_p (Lisp_Object object);
6919 static bool tiff_load (struct frame *f, struct image *img);
6921 /* Indices of image specification fields in tiff_format, below. */
6923 enum tiff_keyword_index
6925 TIFF_TYPE,
6926 TIFF_DATA,
6927 TIFF_FILE,
6928 TIFF_ASCENT,
6929 TIFF_MARGIN,
6930 TIFF_RELIEF,
6931 TIFF_ALGORITHM,
6932 TIFF_HEURISTIC_MASK,
6933 TIFF_MASK,
6934 TIFF_BACKGROUND,
6935 TIFF_INDEX,
6936 TIFF_LAST
6939 /* Vector of image_keyword structures describing the format
6940 of valid user-defined image specifications. */
6942 static const struct image_keyword tiff_format[TIFF_LAST] =
6944 {":type", IMAGE_SYMBOL_VALUE, 1},
6945 {":data", IMAGE_STRING_VALUE, 0},
6946 {":file", IMAGE_STRING_VALUE, 0},
6947 {":ascent", IMAGE_ASCENT_VALUE, 0},
6948 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6949 {":relief", IMAGE_INTEGER_VALUE, 0},
6950 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6951 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6952 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6953 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6954 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6957 #if defined HAVE_NTGUI && defined WINDOWSNT
6958 static bool init_tiff_functions (void);
6959 #else
6960 #define init_tiff_functions NULL
6961 #endif
6963 /* Structure describing the image type `tiff'. */
6965 static struct image_type tiff_type =
6967 SYMBOL_INDEX (Qtiff),
6968 tiff_image_p,
6969 tiff_load,
6970 x_clear_image,
6971 init_tiff_functions,
6972 NULL
6975 /* Return true if OBJECT is a valid TIFF image specification. */
6977 static bool
6978 tiff_image_p (Lisp_Object object)
6980 struct image_keyword fmt[TIFF_LAST];
6981 memcpy (fmt, tiff_format, sizeof fmt);
6983 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6984 return 0;
6986 /* Must specify either the :data or :file keyword. */
6987 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6990 #endif /* HAVE_TIFF || HAVE_NS */
6992 #ifdef HAVE_TIFF
6994 # include <tiffio.h>
6996 # ifdef WINDOWSNT
6998 /* TIFF library details. */
6999 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
7000 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
7001 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
7002 DEF_DLL_FN (TIFF *, TIFFClientOpen,
7003 (const char *, const char *, thandle_t, TIFFReadWriteProc,
7004 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
7005 TIFFMapFileProc, TIFFUnmapFileProc));
7006 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
7007 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
7008 DEF_DLL_FN (void, TIFFClose, (TIFF *));
7009 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
7011 static bool
7012 init_tiff_functions (void)
7014 HMODULE library;
7016 if (!(library = w32_delayed_load (Qtiff)))
7017 return 0;
7019 LOAD_DLL_FN (library, TIFFSetErrorHandler);
7020 LOAD_DLL_FN (library, TIFFSetWarningHandler);
7021 LOAD_DLL_FN (library, TIFFOpen);
7022 LOAD_DLL_FN (library, TIFFClientOpen);
7023 LOAD_DLL_FN (library, TIFFGetField);
7024 LOAD_DLL_FN (library, TIFFReadRGBAImage);
7025 LOAD_DLL_FN (library, TIFFClose);
7026 LOAD_DLL_FN (library, TIFFSetDirectory);
7027 return 1;
7030 # undef TIFFClientOpen
7031 # undef TIFFClose
7032 # undef TIFFGetField
7033 # undef TIFFOpen
7034 # undef TIFFReadRGBAImage
7035 # undef TIFFSetDirectory
7036 # undef TIFFSetErrorHandler
7037 # undef TIFFSetWarningHandler
7039 # define TIFFClientOpen fn_TIFFClientOpen
7040 # define TIFFClose fn_TIFFClose
7041 # define TIFFGetField fn_TIFFGetField
7042 # define TIFFOpen fn_TIFFOpen
7043 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7044 # define TIFFSetDirectory fn_TIFFSetDirectory
7045 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7046 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7048 # endif /* WINDOWSNT */
7051 /* Reading from a memory buffer for TIFF images Based on the PNG
7052 memory source, but we have to provide a lot of extra functions.
7053 Blah.
7055 We really only need to implement read and seek, but I am not
7056 convinced that the TIFF library is smart enough not to destroy
7057 itself if we only hand it the function pointers we need to
7058 override. */
7060 typedef struct
7062 unsigned char *bytes;
7063 ptrdiff_t len;
7064 ptrdiff_t index;
7066 tiff_memory_source;
7068 static tsize_t
7069 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7071 tiff_memory_source *src = (tiff_memory_source *) data;
7073 size = min (size, src->len - src->index);
7074 memcpy (buf, src->bytes + src->index, size);
7075 src->index += size;
7076 return size;
7079 static tsize_t
7080 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7082 return -1;
7085 static toff_t
7086 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
7088 tiff_memory_source *src = (tiff_memory_source *) data;
7089 ptrdiff_t idx;
7091 switch (whence)
7093 case SEEK_SET: /* Go from beginning of source. */
7094 idx = off;
7095 break;
7097 case SEEK_END: /* Go from end of source. */
7098 idx = src->len + off;
7099 break;
7101 case SEEK_CUR: /* Go from current position. */
7102 idx = src->index + off;
7103 break;
7105 default: /* Invalid `whence'. */
7106 return -1;
7109 if (idx > src->len || idx < 0)
7110 return -1;
7112 src->index = idx;
7113 return src->index;
7116 static int
7117 tiff_close_memory (thandle_t data)
7119 /* NOOP */
7120 return 0;
7123 static int
7124 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
7126 /* It is already _IN_ memory. */
7127 return 0;
7130 static void
7131 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
7133 /* We don't need to do this. */
7136 static toff_t
7137 tiff_size_of_memory (thandle_t data)
7139 return ((tiff_memory_source *) data)->len;
7142 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7143 compiler error compiling tiff_handler, see Bugzilla bug #17406
7144 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7145 this function as external works around that problem. */
7146 # if defined (__MINGW32__) && __GNUC__ == 3
7147 # define MINGW_STATIC
7148 # else
7149 # define MINGW_STATIC static
7150 # endif
7152 MINGW_STATIC void
7153 tiff_handler (const char *, const char *, const char *, va_list)
7154 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7155 MINGW_STATIC void
7156 tiff_handler (const char *log_format, const char *title,
7157 const char *format, va_list ap)
7159 /* doprnt is not suitable here, as TIFF handlers are called from
7160 libtiff and are passed arbitrary printf directives. Instead, use
7161 vsnprintf, taking care to be portable to nonstandard environments
7162 where vsnprintf returns -1 on buffer overflow. Since it's just a
7163 log entry, it's OK to truncate it. */
7164 char buf[4000];
7165 int len = vsnprintf (buf, sizeof buf, format, ap);
7166 add_to_log (log_format, build_string (title),
7167 make_string (buf, max (0, min (len, sizeof buf - 1))));
7169 # undef MINGW_STATIC
7171 static void tiff_error_handler (const char *, const char *, va_list)
7172 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7173 static void
7174 tiff_error_handler (const char *title, const char *format, va_list ap)
7176 tiff_handler ("TIFF error: %s %s", title, format, ap);
7180 static void tiff_warning_handler (const char *, const char *, va_list)
7181 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7182 static void
7183 tiff_warning_handler (const char *title, const char *format, va_list ap)
7185 tiff_handler ("TIFF warning: %s %s", title, format, ap);
7189 /* Load TIFF image IMG for use on frame F. Value is true if
7190 successful. */
7192 static bool
7193 tiff_load (struct frame *f, struct image *img)
7195 Lisp_Object specified_file;
7196 Lisp_Object specified_data;
7197 TIFF *tiff;
7198 int width, height, x, y, count;
7199 uint32 *buf;
7200 int rc;
7201 XImagePtr ximg;
7202 tiff_memory_source memsrc;
7203 Lisp_Object image;
7205 specified_file = image_spec_value (img->spec, QCfile, NULL);
7206 specified_data = image_spec_value (img->spec, QCdata, NULL);
7208 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
7209 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7211 if (NILP (specified_data))
7213 /* Read from a file */
7214 Lisp_Object file = x_find_image_file (specified_file);
7215 if (!STRINGP (file))
7217 image_error ("Cannot find image file `%s'", specified_file);
7218 return 0;
7221 Lisp_Object encoded_file = ENCODE_FILE (file);
7222 # ifdef WINDOWSNT
7223 encoded_file = ansi_encode_filename (encoded_file);
7224 # endif
7226 /* Try to open the image file. */
7227 tiff = TIFFOpen (SSDATA (encoded_file), "r");
7228 if (tiff == NULL)
7230 image_error ("Cannot open `%s'", file);
7231 return 0;
7234 else
7236 if (!STRINGP (specified_data))
7238 image_error ("Invalid image data `%s'", specified_data);
7239 return 0;
7242 /* Memory source! */
7243 memsrc.bytes = SDATA (specified_data);
7244 memsrc.len = SBYTES (specified_data);
7245 memsrc.index = 0;
7247 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7248 tiff_read_from_memory,
7249 tiff_write_from_memory,
7250 tiff_seek_in_memory,
7251 tiff_close_memory,
7252 tiff_size_of_memory,
7253 tiff_mmap_memory,
7254 tiff_unmap_memory);
7256 if (!tiff)
7258 image_error ("Cannot open memory source for `%s'", img->spec);
7259 return 0;
7263 image = image_spec_value (img->spec, QCindex, NULL);
7264 if (INTEGERP (image))
7266 EMACS_INT ino = XFASTINT (image);
7267 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7268 && TIFFSetDirectory (tiff, ino)))
7270 image_error ("Invalid image number `%s' in image `%s'",
7271 image, img->spec);
7272 TIFFClose (tiff);
7273 return 0;
7277 /* Get width and height of the image, and allocate a raster buffer
7278 of width x height 32-bit values. */
7279 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7280 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7282 if (!check_image_size (f, width, height))
7284 image_size_error ();
7285 TIFFClose (tiff);
7286 return 0;
7289 /* Create the X image and pixmap. */
7290 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7291 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7292 &ximg, 0)))
7294 TIFFClose (tiff);
7295 return 0;
7298 buf = xmalloc (sizeof *buf * width * height);
7300 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7302 /* Count the number of images in the file. */
7303 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7304 continue;
7306 if (count > 1)
7307 img->lisp_data = Fcons (Qcount,
7308 Fcons (make_number (count),
7309 img->lisp_data));
7311 TIFFClose (tiff);
7312 if (!rc)
7314 image_error ("Error reading TIFF image `%s'", img->spec);
7315 xfree (buf);
7316 return 0;
7319 #ifdef USE_CAIRO
7321 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
7322 uint32_t *dataptr = (uint32_t *) data;
7323 int r, g, b, a;
7325 for (y = 0; y < height; ++y)
7327 uint32 *row = buf + (height - 1 - y) * width;
7328 for (x = 0; x < width; ++x)
7330 uint32 abgr = row[x];
7331 int r = TIFFGetR (abgr);
7332 int g = TIFFGetG (abgr);
7333 int b = TIFFGetB (abgr);
7334 int a = TIFFGetA (abgr);
7335 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
7339 create_cairo_image_surface (img, data, width, height);
7341 #else
7342 /* Initialize the color table. */
7343 init_color_table ();
7345 /* Process the pixel raster. Origin is in the lower-left corner. */
7346 for (y = 0; y < height; ++y)
7348 uint32 *row = buf + y * width;
7350 for (x = 0; x < width; ++x)
7352 uint32 abgr = row[x];
7353 int r = TIFFGetR (abgr) << 8;
7354 int g = TIFFGetG (abgr) << 8;
7355 int b = TIFFGetB (abgr) << 8;
7356 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7360 # ifdef COLOR_TABLE_SUPPORT
7361 /* Remember the colors allocated for the image. Free the color table. */
7362 img->colors = colors_in_color_table (&img->ncolors);
7363 free_color_table ();
7364 # endif /* COLOR_TABLE_SUPPORT */
7366 img->width = width;
7367 img->height = height;
7369 /* Maybe fill in the background field while we have ximg handy. */
7370 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7371 /* Casting avoids a GCC warning on W32. */
7372 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7374 /* Put ximg into the image. */
7375 image_put_x_image (f, img, ximg, 0);
7377 #endif /* ! USE_CAIRO */
7379 xfree (buf);
7380 return 1;
7383 #elif defined HAVE_NS
7385 static bool
7386 tiff_load (struct frame *f, struct image *img)
7388 return ns_load_image (f, img,
7389 image_spec_value (img->spec, QCfile, NULL),
7390 image_spec_value (img->spec, QCdata, NULL));
7393 #endif
7397 /***********************************************************************
7399 ***********************************************************************/
7401 #if defined (HAVE_GIF) || defined (HAVE_NS)
7403 static bool gif_image_p (Lisp_Object object);
7404 static bool gif_load (struct frame *f, struct image *img);
7405 static void gif_clear_image (struct frame *f, struct image *img);
7407 /* Indices of image specification fields in gif_format, below. */
7409 enum gif_keyword_index
7411 GIF_TYPE,
7412 GIF_DATA,
7413 GIF_FILE,
7414 GIF_ASCENT,
7415 GIF_MARGIN,
7416 GIF_RELIEF,
7417 GIF_ALGORITHM,
7418 GIF_HEURISTIC_MASK,
7419 GIF_MASK,
7420 GIF_IMAGE,
7421 GIF_BACKGROUND,
7422 GIF_LAST
7425 /* Vector of image_keyword structures describing the format
7426 of valid user-defined image specifications. */
7428 static const struct image_keyword gif_format[GIF_LAST] =
7430 {":type", IMAGE_SYMBOL_VALUE, 1},
7431 {":data", IMAGE_STRING_VALUE, 0},
7432 {":file", IMAGE_STRING_VALUE, 0},
7433 {":ascent", IMAGE_ASCENT_VALUE, 0},
7434 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7435 {":relief", IMAGE_INTEGER_VALUE, 0},
7436 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7437 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7438 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7439 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7440 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7443 #if defined HAVE_NTGUI && defined WINDOWSNT
7444 static bool init_gif_functions (void);
7445 #else
7446 #define init_gif_functions NULL
7447 #endif
7449 /* Structure describing the image type `gif'. */
7451 static struct image_type gif_type =
7453 SYMBOL_INDEX (Qgif),
7454 gif_image_p,
7455 gif_load,
7456 gif_clear_image,
7457 init_gif_functions,
7458 NULL
7461 /* Free X resources of GIF image IMG which is used on frame F. */
7463 static void
7464 gif_clear_image (struct frame *f, struct image *img)
7466 img->lisp_data = Qnil;
7467 x_clear_image (f, img);
7470 /* Return true if OBJECT is a valid GIF image specification. */
7472 static bool
7473 gif_image_p (Lisp_Object object)
7475 struct image_keyword fmt[GIF_LAST];
7476 memcpy (fmt, gif_format, sizeof fmt);
7478 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7479 return 0;
7481 /* Must specify either the :data or :file keyword. */
7482 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7485 #endif /* HAVE_GIF */
7487 #ifdef HAVE_GIF
7489 # ifdef HAVE_NTGUI
7491 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7492 Undefine before redefining to avoid a preprocessor warning. */
7493 # ifdef DrawText
7494 # undef DrawText
7495 # endif
7496 /* avoid conflict with QuickdrawText.h */
7497 # define DrawText gif_DrawText
7498 # include <gif_lib.h>
7499 # undef DrawText
7501 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7502 # ifndef GIFLIB_MINOR
7503 # define GIFLIB_MINOR 0
7504 # endif
7505 # ifndef GIFLIB_RELEASE
7506 # define GIFLIB_RELEASE 0
7507 # endif
7509 # else /* HAVE_NTGUI */
7511 # include <gif_lib.h>
7513 # endif /* HAVE_NTGUI */
7515 /* Giflib before 5.0 didn't define these macros. */
7516 # ifndef GIFLIB_MAJOR
7517 # define GIFLIB_MAJOR 4
7518 # endif
7520 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7521 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7522 earlier releases, where either it returns char * or GIFLIB_MINOR
7523 may be incorrect. */
7524 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7526 # ifdef WINDOWSNT
7528 /* GIF library details. */
7529 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7530 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7531 # else
7532 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7533 # endif
7534 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7535 # if GIFLIB_MAJOR < 5
7536 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7537 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7538 # else
7539 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7540 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7541 # endif
7542 # if HAVE_GIFERRORSTRING
7543 DEF_DLL_FN (char const *, GifErrorString, (int));
7544 # endif
7546 static bool
7547 init_gif_functions (void)
7549 HMODULE library;
7551 if (!(library = w32_delayed_load (Qgif)))
7552 return 0;
7554 LOAD_DLL_FN (library, DGifCloseFile);
7555 LOAD_DLL_FN (library, DGifSlurp);
7556 LOAD_DLL_FN (library, DGifOpen);
7557 LOAD_DLL_FN (library, DGifOpenFileName);
7558 # if HAVE_GIFERRORSTRING
7559 LOAD_DLL_FN (library, GifErrorString);
7560 # endif
7561 return 1;
7564 # undef DGifCloseFile
7565 # undef DGifOpen
7566 # undef DGifOpenFileName
7567 # undef DGifSlurp
7568 # undef GifErrorString
7570 # define DGifCloseFile fn_DGifCloseFile
7571 # define DGifOpen fn_DGifOpen
7572 # define DGifOpenFileName fn_DGifOpenFileName
7573 # define DGifSlurp fn_DGifSlurp
7574 # define GifErrorString fn_GifErrorString
7576 # endif /* WINDOWSNT */
7578 /* Reading a GIF image from memory
7579 Based on the PNG memory stuff to a certain extent. */
7581 typedef struct
7583 unsigned char *bytes;
7584 ptrdiff_t len;
7585 ptrdiff_t index;
7587 gif_memory_source;
7589 /* Make the current memory source available to gif_read_from_memory.
7590 It's done this way because not all versions of libungif support
7591 a UserData field in the GifFileType structure. */
7592 static gif_memory_source *current_gif_memory_src;
7594 static int
7595 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7597 gif_memory_source *src = current_gif_memory_src;
7599 if (len > src->len - src->index)
7600 return -1;
7602 memcpy (buf, src->bytes + src->index, len);
7603 src->index += len;
7604 return len;
7607 static int
7608 gif_close (GifFileType *gif, int *err)
7610 int retval;
7612 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7613 retval = DGifCloseFile (gif, err);
7614 #else
7615 retval = DGifCloseFile (gif);
7616 #if GIFLIB_MAJOR >= 5
7617 if (err)
7618 *err = gif->Error;
7619 #endif
7620 #endif
7621 return retval;
7624 /* Load GIF image IMG for use on frame F. Value is true if
7625 successful. */
7627 static const int interlace_start[] = {0, 4, 2, 1};
7628 static const int interlace_increment[] = {8, 8, 4, 2};
7630 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7632 static bool
7633 gif_load (struct frame *f, struct image *img)
7635 int rc, width, height, x, y, i, j;
7636 ColorMapObject *gif_color_map;
7637 unsigned long pixel_colors[256];
7638 GifFileType *gif;
7639 gif_memory_source memsrc;
7640 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7641 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7642 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7643 unsigned long bgcolor = 0;
7644 EMACS_INT idx;
7645 int gif_err;
7647 #ifdef USE_CAIRO
7648 unsigned char *data = 0;
7649 #else
7650 XImagePtr ximg;
7651 #endif
7653 if (NILP (specified_data))
7655 Lisp_Object file = x_find_image_file (specified_file);
7656 if (!STRINGP (file))
7658 image_error ("Cannot find image file `%s'", specified_file);
7659 return 0;
7662 Lisp_Object encoded_file = ENCODE_FILE (file);
7663 #ifdef WINDOWSNT
7664 encoded_file = ansi_encode_filename (encoded_file);
7665 #endif
7667 /* Open the GIF file. */
7668 #if GIFLIB_MAJOR < 5
7669 gif = DGifOpenFileName (SSDATA (encoded_file));
7670 #else
7671 gif = DGifOpenFileName (SSDATA (encoded_file), &gif_err);
7672 #endif
7673 if (gif == NULL)
7675 #if HAVE_GIFERRORSTRING
7676 image_error ("Cannot open `%s': %s",
7677 file, build_string (GifErrorString (gif_err)));
7678 #else
7679 image_error ("Cannot open `%s'", file);
7680 #endif
7681 return 0;
7684 else
7686 if (!STRINGP (specified_data))
7688 image_error ("Invalid image data `%s'", specified_data);
7689 return 0;
7692 /* Read from memory! */
7693 current_gif_memory_src = &memsrc;
7694 memsrc.bytes = SDATA (specified_data);
7695 memsrc.len = SBYTES (specified_data);
7696 memsrc.index = 0;
7698 #if GIFLIB_MAJOR < 5
7699 gif = DGifOpen (&memsrc, gif_read_from_memory);
7700 #else
7701 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7702 #endif
7703 if (!gif)
7705 #if HAVE_GIFERRORSTRING
7706 image_error ("Cannot open memory source `%s': %s",
7707 img->spec, build_string (GifErrorString (gif_err)));
7708 #else
7709 image_error ("Cannot open memory source `%s'", img->spec);
7710 #endif
7711 return 0;
7715 /* Before reading entire contents, check the declared image size. */
7716 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7718 image_size_error ();
7719 gif_close (gif, NULL);
7720 return 0;
7723 /* Read entire contents. */
7724 rc = DGifSlurp (gif);
7725 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7727 image_error ("Error reading `%s'", img->spec);
7728 gif_close (gif, NULL);
7729 return 0;
7732 /* Which sub-image are we to display? */
7734 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7735 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7736 if (idx < 0 || idx >= gif->ImageCount)
7738 image_error ("Invalid image number `%s' in image `%s'",
7739 image_number, img->spec);
7740 gif_close (gif, NULL);
7741 return 0;
7745 width = img->width = gif->SWidth;
7746 height = img->height = gif->SHeight;
7748 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7749 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7750 img->corners[BOT_CORNER]
7751 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7752 img->corners[RIGHT_CORNER]
7753 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7755 if (!check_image_size (f, width, height))
7757 image_size_error ();
7758 gif_close (gif, NULL);
7759 return 0;
7762 /* Check that the selected subimages fit. It's not clear whether
7763 the GIF spec requires this, but Emacs can crash if they don't fit. */
7764 for (j = 0; j <= idx; ++j)
7766 struct SavedImage *subimage = gif->SavedImages + j;
7767 int subimg_width = subimage->ImageDesc.Width;
7768 int subimg_height = subimage->ImageDesc.Height;
7769 int subimg_top = subimage->ImageDesc.Top;
7770 int subimg_left = subimage->ImageDesc.Left;
7771 if (! (subimg_width >= 0 && subimg_height >= 0
7772 && 0 <= subimg_top && subimg_top <= height - subimg_height
7773 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7775 image_error ("Subimage does not fit in image");
7776 gif_close (gif, NULL);
7777 return 0;
7781 #ifdef USE_CAIRO
7782 /* xzalloc so data is zero => transparent */
7783 data = (unsigned char *) xzalloc (width * height * 4);
7784 if (STRINGP (specified_bg))
7786 XColor color;
7787 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
7789 uint32_t *dataptr = (uint32_t *)data;
7790 int r = color.red/256;
7791 int g = color.green/256;
7792 int b = color.blue/256;
7794 for (y = 0; y < height; ++y)
7795 for (x = 0; x < width; ++x)
7796 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
7799 #else
7800 /* Create the X image and pixmap. */
7801 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7803 gif_close (gif, NULL);
7804 return 0;
7807 /* Clear the part of the screen image not covered by the image.
7808 Full animated GIF support requires more here (see the gif89 spec,
7809 disposal methods). Let's simply assume that the part not covered
7810 by a sub-image is in the frame's background color. */
7811 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7812 for (x = 0; x < width; ++x)
7813 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7815 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7816 for (x = 0; x < width; ++x)
7817 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7819 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7821 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7822 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7823 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7824 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7826 #endif
7828 /* Read the GIF image into the X image. */
7830 /* FIXME: With the current implementation, loading an animated gif
7831 is quadratic in the number of animation frames, since each frame
7832 is a separate struct image. We must provide a way for a single
7833 gif_load call to construct and save all animation frames. */
7835 init_color_table ();
7836 if (STRINGP (specified_bg))
7837 bgcolor = x_alloc_image_color (f, img, specified_bg,
7838 FRAME_BACKGROUND_PIXEL (f));
7839 for (j = 0; j <= idx; ++j)
7841 /* We use a local variable `raster' here because RasterBits is a
7842 char *, which invites problems with bytes >= 0x80. */
7843 struct SavedImage *subimage = gif->SavedImages + j;
7844 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7845 int transparency_color_index = -1;
7846 int disposal = 0;
7847 int subimg_width = subimage->ImageDesc.Width;
7848 int subimg_height = subimage->ImageDesc.Height;
7849 int subimg_top = subimage->ImageDesc.Top;
7850 int subimg_left = subimage->ImageDesc.Left;
7852 /* Find the Graphic Control Extension block for this sub-image.
7853 Extract the disposal method and transparency color. */
7854 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7856 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7858 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7859 && extblock->ByteCount == 4
7860 && extblock->Bytes[0] & 1)
7862 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7863 to background". Treat any other value like 2. */
7864 disposal = (extblock->Bytes[0] >> 2) & 7;
7865 transparency_color_index = (unsigned char) extblock->Bytes[3];
7866 break;
7870 /* We can't "keep in place" the first subimage. */
7871 if (j == 0)
7872 disposal = 2;
7874 /* For disposal == 0, the spec says "No disposal specified. The
7875 decoder is not required to take any action." In practice, it
7876 seems we need to treat this like "keep in place", see e.g.
7877 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7878 if (disposal == 0)
7879 disposal = 1;
7881 gif_color_map = subimage->ImageDesc.ColorMap;
7882 if (!gif_color_map)
7883 gif_color_map = gif->SColorMap;
7885 #ifndef USE_CAIRO
7886 /* Allocate subimage colors. */
7887 memset (pixel_colors, 0, sizeof pixel_colors);
7889 if (gif_color_map)
7890 for (i = 0; i < gif_color_map->ColorCount; ++i)
7892 if (transparency_color_index == i)
7893 pixel_colors[i] = STRINGP (specified_bg)
7894 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7895 else
7897 int r = gif_color_map->Colors[i].Red << 8;
7898 int g = gif_color_map->Colors[i].Green << 8;
7899 int b = gif_color_map->Colors[i].Blue << 8;
7900 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7903 #endif
7905 /* Apply the pixel values. */
7906 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7908 int row, pass;
7910 for (y = 0, row = interlace_start[0], pass = 0;
7911 y < subimg_height;
7912 y++, row += interlace_increment[pass])
7914 while (subimg_height <= row)
7915 row = interlace_start[++pass];
7917 for (x = 0; x < subimg_width; x++)
7919 int c = raster[y * subimg_width + x];
7920 if (transparency_color_index != c || disposal != 1)
7922 #ifdef USE_CAIRO
7923 uint32_t *dataptr =
7924 ((uint32_t*)data + ((row + subimg_top) * subimg_width
7925 + x + subimg_left));
7926 int r = gif_color_map->Colors[c].Red;
7927 int g = gif_color_map->Colors[c].Green;
7928 int b = gif_color_map->Colors[c].Blue;
7930 if (transparency_color_index != c)
7931 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7932 #else
7933 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7934 pixel_colors[c]);
7935 #endif
7940 else
7942 for (y = 0; y < subimg_height; ++y)
7943 for (x = 0; x < subimg_width; ++x)
7945 int c = raster[y * subimg_width + x];
7946 if (transparency_color_index != c || disposal != 1)
7948 #ifdef USE_CAIRO
7949 uint32_t *dataptr =
7950 ((uint32_t*)data + ((y + subimg_top) * subimg_width
7951 + x + subimg_left));
7952 int r = gif_color_map->Colors[c].Red;
7953 int g = gif_color_map->Colors[c].Green;
7954 int b = gif_color_map->Colors[c].Blue;
7955 if (transparency_color_index != c)
7956 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7957 #else
7958 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7959 pixel_colors[c]);
7960 #endif
7966 #ifdef COLOR_TABLE_SUPPORT
7967 img->colors = colors_in_color_table (&img->ncolors);
7968 free_color_table ();
7969 #endif /* COLOR_TABLE_SUPPORT */
7971 /* Save GIF image extension data for `image-metadata'.
7972 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7973 img->lisp_data = Qnil;
7974 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7976 int delay = 0;
7977 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7978 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7979 /* Append (... FUNCTION "BYTES") */
7981 img->lisp_data
7982 = Fcons (make_number (ext->Function),
7983 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7984 img->lisp_data));
7985 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7986 && ext->ByteCount == 4)
7988 delay = ext->Bytes[2] << CHAR_BIT;
7989 delay |= ext->Bytes[1];
7992 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7993 if (delay)
7994 img->lisp_data
7995 = Fcons (Qdelay,
7996 Fcons (make_float (delay / 100.0),
7997 img->lisp_data));
8000 if (gif->ImageCount > 1)
8001 img->lisp_data = Fcons (Qcount,
8002 Fcons (make_number (gif->ImageCount),
8003 img->lisp_data));
8005 if (gif_close (gif, &gif_err) == GIF_ERROR)
8007 #if HAVE_GIFERRORSTRING
8008 char const *error_text = GifErrorString (gif_err);
8010 if (error_text)
8011 image_error ("Error closing `%s': %s",
8012 img->spec, build_string (error_text));
8013 #else
8014 image_error ("Error closing `%s'", img->spec);
8015 #endif
8018 #ifdef USE_CAIRO
8019 create_cairo_image_surface (img, data, width, height);
8020 #else
8021 /* Maybe fill in the background field while we have ximg handy. */
8022 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8023 /* Casting avoids a GCC warning. */
8024 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8026 /* Put ximg into the image. */
8027 image_put_x_image (f, img, ximg, 0);
8028 #endif
8030 return 1;
8033 #else /* !HAVE_GIF */
8035 #ifdef HAVE_NS
8036 static bool
8037 gif_load (struct frame *f, struct image *img)
8039 return ns_load_image (f, img,
8040 image_spec_value (img->spec, QCfile, NULL),
8041 image_spec_value (img->spec, QCdata, NULL));
8043 #endif /* HAVE_NS */
8045 #endif /* HAVE_GIF */
8048 #ifdef HAVE_IMAGEMAGICK
8050 /***********************************************************************
8051 ImageMagick
8052 ***********************************************************************/
8054 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8055 safely rounded and clipped to int range. */
8057 static int
8058 scale_image_size (int size, size_t divisor, size_t multiplier)
8060 if (divisor != 0)
8062 double s = size;
8063 double scaled = s * multiplier / divisor + 0.5;
8064 if (scaled < INT_MAX)
8065 return scaled;
8067 return INT_MAX;
8070 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8071 Use SPEC to deduce the size. Store the desired size into
8072 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8073 static void
8074 compute_image_size (size_t width, size_t height,
8075 Lisp_Object spec,
8076 int *d_width, int *d_height)
8078 Lisp_Object value;
8079 int desired_width, desired_height;
8081 /* If width and/or height is set in the display spec assume we want
8082 to scale to those values. If either h or w is unspecified, the
8083 unspecified should be calculated from the specified to preserve
8084 aspect ratio. */
8085 value = image_spec_value (spec, QCwidth, NULL);
8086 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8087 value = image_spec_value (spec, QCheight, NULL);
8088 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8090 if (desired_width == -1)
8092 value = image_spec_value (spec, QCmax_width, NULL);
8093 if (NATNUMP (value))
8095 int max_width = min (XFASTINT (value), INT_MAX);
8096 if (max_width < width)
8098 /* The image is wider than :max-width. */
8099 desired_width = max_width;
8100 if (desired_height == -1)
8102 desired_height = scale_image_size (desired_width,
8103 width, height);
8104 value = image_spec_value (spec, QCmax_height, NULL);
8105 if (NATNUMP (value))
8107 int max_height = min (XFASTINT (value), INT_MAX);
8108 if (max_height < desired_height)
8110 desired_height = max_height;
8111 desired_width = scale_image_size (desired_height,
8112 height, width);
8120 if (desired_height == -1)
8122 value = image_spec_value (spec, QCmax_height, NULL);
8123 if (NATNUMP (value))
8125 int max_height = min (XFASTINT (value), INT_MAX);
8126 if (max_height < height)
8127 desired_height = max_height;
8131 if (desired_width != -1 && desired_height == -1)
8132 /* w known, calculate h. */
8133 desired_height = scale_image_size (desired_width, width, height);
8135 if (desired_width == -1 && desired_height != -1)
8136 /* h known, calculate w. */
8137 desired_width = scale_image_size (desired_height, height, width);
8139 *d_width = desired_width;
8140 *d_height = desired_height;
8143 static bool imagemagick_image_p (Lisp_Object);
8144 static bool imagemagick_load (struct frame *, struct image *);
8145 static void imagemagick_clear_image (struct frame *, struct image *);
8147 /* Indices of image specification fields in imagemagick_format. */
8149 enum imagemagick_keyword_index
8151 IMAGEMAGICK_TYPE,
8152 IMAGEMAGICK_DATA,
8153 IMAGEMAGICK_FILE,
8154 IMAGEMAGICK_ASCENT,
8155 IMAGEMAGICK_MARGIN,
8156 IMAGEMAGICK_RELIEF,
8157 IMAGEMAGICK_ALGORITHM,
8158 IMAGEMAGICK_HEURISTIC_MASK,
8159 IMAGEMAGICK_MASK,
8160 IMAGEMAGICK_BACKGROUND,
8161 IMAGEMAGICK_HEIGHT,
8162 IMAGEMAGICK_WIDTH,
8163 IMAGEMAGICK_MAX_HEIGHT,
8164 IMAGEMAGICK_MAX_WIDTH,
8165 IMAGEMAGICK_FORMAT,
8166 IMAGEMAGICK_ROTATION,
8167 IMAGEMAGICK_CROP,
8168 IMAGEMAGICK_LAST
8171 /* Vector of image_keyword structures describing the format
8172 of valid user-defined image specifications. */
8174 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
8176 {":type", IMAGE_SYMBOL_VALUE, 1},
8177 {":data", IMAGE_STRING_VALUE, 0},
8178 {":file", IMAGE_STRING_VALUE, 0},
8179 {":ascent", IMAGE_ASCENT_VALUE, 0},
8180 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8181 {":relief", IMAGE_INTEGER_VALUE, 0},
8182 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8183 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8184 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8185 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8186 {":height", IMAGE_INTEGER_VALUE, 0},
8187 {":width", IMAGE_INTEGER_VALUE, 0},
8188 {":max-height", IMAGE_INTEGER_VALUE, 0},
8189 {":max-width", IMAGE_INTEGER_VALUE, 0},
8190 {":format", IMAGE_SYMBOL_VALUE, 0},
8191 {":rotation", IMAGE_NUMBER_VALUE, 0},
8192 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8195 #if defined HAVE_NTGUI && defined WINDOWSNT
8196 static bool init_imagemagick_functions (void);
8197 #else
8198 #define init_imagemagick_functions NULL
8199 #endif
8201 /* Structure describing the image type for any image handled via
8202 ImageMagick. */
8204 static struct image_type imagemagick_type =
8206 SYMBOL_INDEX (Qimagemagick),
8207 imagemagick_image_p,
8208 imagemagick_load,
8209 imagemagick_clear_image,
8210 init_imagemagick_functions,
8211 NULL
8214 /* Free X resources of imagemagick image IMG which is used on frame F. */
8216 static void
8217 imagemagick_clear_image (struct frame *f,
8218 struct image *img)
8220 x_clear_image (f, img);
8223 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8224 this by calling parse_image_spec and supplying the keywords that
8225 identify the IMAGEMAGICK format. */
8227 static bool
8228 imagemagick_image_p (Lisp_Object object)
8230 struct image_keyword fmt[IMAGEMAGICK_LAST];
8231 memcpy (fmt, imagemagick_format, sizeof fmt);
8233 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
8234 return 0;
8236 /* Must specify either the :data or :file keyword. */
8237 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
8240 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8241 Therefore rename the function so it doesn't collide with ImageMagick. */
8242 #define DrawRectangle DrawRectangleGif
8243 #include <wand/MagickWand.h>
8245 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8246 Emacs seems to work fine with the hidden version, so unhide it. */
8247 #include <magick/version.h>
8248 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8249 extern WandExport void PixelGetMagickColor (const PixelWand *,
8250 MagickPixelPacket *);
8251 #endif
8253 /* Log ImageMagick error message.
8254 Useful when a ImageMagick function returns the status `MagickFalse'. */
8256 static void
8257 imagemagick_error (MagickWand *wand)
8259 char *description;
8260 ExceptionType severity;
8262 description = MagickGetException (wand, &severity);
8263 image_error ("ImageMagick error: %s", build_string (description));
8264 MagickRelinquishMemory (description);
8267 /* Possibly give ImageMagick some extra help to determine the image
8268 type by supplying a "dummy" filename based on the Content-Type. */
8270 static char *
8271 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
8273 Lisp_Object symbol = intern ("image-format-suffixes");
8274 Lisp_Object val = find_symbol_value (symbol);
8275 Lisp_Object format;
8277 if (! CONSP (val))
8278 return NULL;
8280 format = image_spec_value (spec, intern (":format"), NULL);
8281 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
8282 if (! STRINGP (val))
8283 return NULL;
8285 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8286 as ImageMagick would ignore the extra bytes anyway. */
8287 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
8288 return hint_buffer;
8291 /* Animated images (e.g., GIF89a) are composed from one "master image"
8292 (which is the first one, and then there's a number of images that
8293 follow. If following images have non-transparent colors, these are
8294 composed "on top" of the master image. So, in general, one has to
8295 compute ann the preceding images to be able to display a particular
8296 sub-image.
8298 Computing all the preceding images is too slow, so we maintain a
8299 cache of previously computed images. We have to maintain a cache
8300 separate from the image cache, because the images may be scaled
8301 before display. */
8303 struct animation_cache
8305 MagickWand *wand;
8306 int index;
8307 struct timespec update_time;
8308 struct animation_cache *next;
8309 char signature[FLEXIBLE_ARRAY_MEMBER];
8312 static struct animation_cache *animation_cache = NULL;
8314 static struct animation_cache *
8315 imagemagick_create_cache (char *signature)
8317 struct animation_cache *cache
8318 = xmalloc (offsetof (struct animation_cache, signature)
8319 + strlen (signature) + 1);
8320 cache->wand = 0;
8321 cache->index = 0;
8322 cache->next = 0;
8323 strcpy (cache->signature, signature);
8324 return cache;
8327 /* Discard cached images that haven't been used for a minute. */
8328 static void
8329 imagemagick_prune_animation_cache (void)
8331 struct animation_cache **pcache = &animation_cache;
8332 struct timespec old = timespec_sub (current_timespec (),
8333 make_timespec (60, 0));
8335 while (*pcache)
8337 struct animation_cache *cache = *pcache;
8338 if (timespec_cmp (old, cache->update_time) <= 0)
8339 pcache = &cache->next;
8340 else
8342 if (cache->wand)
8343 DestroyMagickWand (cache->wand);
8344 *pcache = cache->next;
8345 xfree (cache);
8350 static struct animation_cache *
8351 imagemagick_get_animation_cache (MagickWand *wand)
8353 char *signature = MagickGetImageSignature (wand);
8354 struct animation_cache *cache;
8355 struct animation_cache **pcache = &animation_cache;
8357 imagemagick_prune_animation_cache ();
8359 while (1)
8361 cache = *pcache;
8362 if (! cache)
8364 *pcache = cache = imagemagick_create_cache (signature);
8365 break;
8367 if (strcmp (signature, cache->signature) == 0)
8368 break;
8369 pcache = &cache->next;
8372 DestroyString (signature);
8373 cache->update_time = current_timespec ();
8374 return cache;
8377 static MagickWand *
8378 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8380 int i;
8381 MagickWand *composite_wand;
8382 size_t dest_width, dest_height;
8383 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8385 MagickSetIteratorIndex (super_wand, 0);
8387 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8389 composite_wand = MagickGetImage (super_wand);
8390 if (cache->wand)
8391 DestroyMagickWand (cache->wand);
8393 else
8394 composite_wand = cache->wand;
8396 dest_height = MagickGetImageHeight (composite_wand);
8398 for (i = max (1, cache->index + 1); i <= ino; i++)
8400 MagickWand *sub_wand;
8401 PixelIterator *source_iterator, *dest_iterator;
8402 PixelWand **source, **dest;
8403 size_t source_width, source_height;
8404 ssize_t source_left, source_top;
8405 MagickPixelPacket pixel;
8406 DisposeType dispose;
8407 ptrdiff_t lines = 0;
8409 MagickSetIteratorIndex (super_wand, i);
8410 sub_wand = MagickGetImage (super_wand);
8412 MagickGetImagePage (sub_wand, &source_width, &source_height,
8413 &source_left, &source_top);
8415 /* This flag says how to handle transparent pixels. */
8416 dispose = MagickGetImageDispose (sub_wand);
8418 source_iterator = NewPixelIterator (sub_wand);
8419 if (! source_iterator)
8421 DestroyMagickWand (composite_wand);
8422 DestroyMagickWand (sub_wand);
8423 cache->wand = NULL;
8424 image_error ("Imagemagick pixel iterator creation failed");
8425 return NULL;
8428 dest_iterator = NewPixelIterator (composite_wand);
8429 if (! dest_iterator)
8431 DestroyMagickWand (composite_wand);
8432 DestroyMagickWand (sub_wand);
8433 DestroyPixelIterator (source_iterator);
8434 cache->wand = NULL;
8435 image_error ("Imagemagick pixel iterator creation failed");
8436 return NULL;
8439 /* The sub-image may not start at origin, so move the destination
8440 iterator to where the sub-image should start. */
8441 if (source_top > 0)
8443 PixelSetIteratorRow (dest_iterator, source_top);
8444 lines = source_top;
8447 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8448 != NULL)
8450 ptrdiff_t x;
8452 /* Sanity check. This shouldn't happen, but apparently
8453 does in some pictures. */
8454 if (++lines >= dest_height)
8455 break;
8457 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8458 for (x = 0; x < source_width; x++)
8460 /* Sanity check. This shouldn't happen, but apparently
8461 also does in some pictures. */
8462 if (x + source_left >= dest_width)
8463 break;
8464 /* Normally we only copy over non-transparent pixels,
8465 but if the disposal method is "Background", then we
8466 copy over all pixels. */
8467 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8469 PixelGetMagickColor (source[x], &pixel);
8470 PixelSetMagickColor (dest[x + source_left], &pixel);
8473 PixelSyncIterator (dest_iterator);
8476 DestroyPixelIterator (source_iterator);
8477 DestroyPixelIterator (dest_iterator);
8478 DestroyMagickWand (sub_wand);
8481 /* Cache a copy for the next iteration. The current wand will be
8482 destroyed by the caller. */
8483 cache->wand = CloneMagickWand (composite_wand);
8484 cache->index = ino;
8486 return composite_wand;
8490 /* Helper function for imagemagick_load, which does the actual loading
8491 given contents and size, apart from frame and image structures,
8492 passed from imagemagick_load. Uses librimagemagick to do most of
8493 the image processing.
8495 F is a pointer to the Emacs frame; IMG to the image structure to
8496 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8497 be parsed; SIZE is the number of bytes of data; and FILENAME is
8498 either the file name or the image data.
8500 Return true if successful. */
8502 static bool
8503 imagemagick_load_image (struct frame *f, struct image *img,
8504 unsigned char *contents, unsigned int size,
8505 char *filename)
8507 int width, height;
8508 size_t image_width, image_height;
8509 MagickBooleanType status;
8510 XImagePtr ximg;
8511 int x, y;
8512 MagickWand *image_wand;
8513 PixelIterator *iterator;
8514 PixelWand **pixels, *bg_wand = NULL;
8515 MagickPixelPacket pixel;
8516 Lisp_Object image;
8517 Lisp_Object value;
8518 Lisp_Object crop;
8519 EMACS_INT ino;
8520 int desired_width, desired_height;
8521 double rotation;
8522 int pixelwidth;
8523 char hint_buffer[MaxTextExtent];
8524 char *filename_hint = NULL;
8526 /* Handle image index for image types who can contain more than one image.
8527 Interface :index is same as for GIF. First we "ping" the image to see how
8528 many sub-images it contains. Pinging is faster than loading the image to
8529 find out things about it. */
8531 /* Initialize the imagemagick environment. */
8532 MagickWandGenesis ();
8533 image = image_spec_value (img->spec, QCindex, NULL);
8534 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8535 image_wand = NewMagickWand ();
8537 if (filename)
8538 status = MagickReadImage (image_wand, filename);
8539 else
8541 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8542 MagickSetFilename (image_wand, filename_hint);
8543 status = MagickReadImageBlob (image_wand, contents, size);
8546 if (status == MagickFalse)
8548 imagemagick_error (image_wand);
8549 DestroyMagickWand (image_wand);
8550 return 0;
8553 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8555 image_error ("Invalid image number `%s' in image `%s'", image, img->spec);
8556 DestroyMagickWand (image_wand);
8557 return 0;
8560 if (MagickGetImageDelay (image_wand) > 0)
8561 img->lisp_data =
8562 Fcons (Qdelay,
8563 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8564 img->lisp_data));
8566 if (MagickGetNumberImages (image_wand) > 1)
8567 img->lisp_data =
8568 Fcons (Qcount,
8569 Fcons (make_number (MagickGetNumberImages (image_wand)),
8570 img->lisp_data));
8572 /* If we have an animated image, get the new wand based on the
8573 "super-wand". */
8574 if (MagickGetNumberImages (image_wand) > 1)
8576 MagickWand *super_wand = image_wand;
8577 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8578 if (! image_wand)
8579 image_wand = super_wand;
8580 else
8581 DestroyMagickWand (super_wand);
8584 /* Retrieve the frame's background color, for use later. */
8586 XColor bgcolor;
8587 Lisp_Object specified_bg;
8589 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8590 if (!STRINGP (specified_bg)
8591 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8592 x_query_frame_background_color (f, &bgcolor);
8594 bg_wand = NewPixelWand ();
8595 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8596 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8597 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8600 compute_image_size (MagickGetImageWidth (image_wand),
8601 MagickGetImageHeight (image_wand),
8602 img->spec, &desired_width, &desired_height);
8604 if (desired_width != -1 && desired_height != -1)
8606 status = MagickScaleImage (image_wand, desired_width, desired_height);
8607 if (status == MagickFalse)
8609 image_error ("Imagemagick scale failed");
8610 imagemagick_error (image_wand);
8611 goto imagemagick_error;
8615 /* crop behaves similar to image slicing in Emacs but is more memory
8616 efficient. */
8617 crop = image_spec_value (img->spec, QCcrop, NULL);
8619 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8621 /* After some testing, it seems MagickCropImage is the fastest crop
8622 function in ImageMagick. This crop function seems to do less copying
8623 than the alternatives, but it still reads the entire image into memory
8624 before cropping, which is apparently difficult to avoid when using
8625 imagemagick. */
8626 size_t crop_width = XINT (XCAR (crop));
8627 crop = XCDR (crop);
8628 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8630 size_t crop_height = XINT (XCAR (crop));
8631 crop = XCDR (crop);
8632 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8634 ssize_t crop_x = XINT (XCAR (crop));
8635 crop = XCDR (crop);
8636 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8638 ssize_t crop_y = XINT (XCAR (crop));
8639 MagickCropImage (image_wand, crop_width, crop_height,
8640 crop_x, crop_y);
8646 /* Furthermore :rotation. we need background color and angle for
8647 rotation. */
8649 TODO background handling for rotation specified_bg =
8650 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8651 (specified_bg). */
8652 value = image_spec_value (img->spec, QCrotation, NULL);
8653 if (FLOATP (value))
8655 rotation = extract_float (value);
8656 status = MagickRotateImage (image_wand, bg_wand, rotation);
8657 if (status == MagickFalse)
8659 image_error ("Imagemagick image rotate failed");
8660 imagemagick_error (image_wand);
8661 goto imagemagick_error;
8665 /* Set the canvas background color to the frame or specified
8666 background, and flatten the image. Note: as of ImageMagick
8667 6.6.0, SVG image transparency is not handled properly
8668 (e.g. etc/images/splash.svg shows a white background always). */
8670 MagickWand *new_wand;
8671 MagickSetImageBackgroundColor (image_wand, bg_wand);
8672 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8673 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8674 #else
8675 new_wand = MagickFlattenImages (image_wand);
8676 #endif
8677 DestroyMagickWand (image_wand);
8678 image_wand = new_wand;
8681 /* Finally we are done manipulating the image. Figure out the
8682 resulting width/height and transfer ownership to Emacs. */
8683 image_height = MagickGetImageHeight (image_wand);
8684 image_width = MagickGetImageWidth (image_wand);
8686 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8687 && check_image_size (f, image_width, image_height)))
8689 image_size_error ();
8690 goto imagemagick_error;
8693 width = image_width;
8694 height = image_height;
8696 /* We can now get a valid pixel buffer from the imagemagick file, if all
8697 went ok. */
8699 init_color_table ();
8701 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8702 if (imagemagick_render_type != 0)
8704 /* Magicexportimage is normally faster than pixelpushing. This
8705 method is also well tested. Some aspects of this method are
8706 ad-hoc and needs to be more researched. */
8707 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8708 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8709 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8710 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8711 &ximg, 0))
8713 #ifdef COLOR_TABLE_SUPPORT
8714 free_color_table ();
8715 #endif
8716 image_error ("Imagemagick X bitmap allocation failure");
8717 goto imagemagick_error;
8720 /* Oddly, the below code doesn't seem to work:*/
8721 /* switch(ximg->bitmap_unit){ */
8722 /* case 8: */
8723 /* pixelwidth=CharPixel; */
8724 /* break; */
8725 /* case 16: */
8726 /* pixelwidth=ShortPixel; */
8727 /* break; */
8728 /* case 32: */
8729 /* pixelwidth=LongPixel; */
8730 /* break; */
8731 /* } */
8733 Here im just guessing the format of the bitmap.
8734 happens to work fine for:
8735 - bw djvu images
8736 on rgb display.
8737 seems about 3 times as fast as pixel pushing(not carefully measured)
8739 pixelwidth = CharPixel; /*??? TODO figure out*/
8740 MagickExportImagePixels (image_wand, 0, 0, width, height,
8741 exportdepth, pixelwidth, ximg->data);
8743 else
8744 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8746 size_t image_height;
8747 MagickRealType color_scale = 65535.0 / QuantumRange;
8749 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8750 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8751 &ximg, 0))
8753 #ifdef COLOR_TABLE_SUPPORT
8754 free_color_table ();
8755 #endif
8756 image_error ("Imagemagick X bitmap allocation failure");
8757 goto imagemagick_error;
8760 /* Copy imagemagick image to x with primitive yet robust pixel
8761 pusher loop. This has been tested a lot with many different
8762 images. */
8764 /* Copy pixels from the imagemagick image structure to the x image map. */
8765 iterator = NewPixelIterator (image_wand);
8766 if (! iterator)
8768 #ifdef COLOR_TABLE_SUPPORT
8769 free_color_table ();
8770 #endif
8771 x_destroy_x_image (ximg);
8772 image_error ("Imagemagick pixel iterator creation failed");
8773 goto imagemagick_error;
8776 image_height = MagickGetImageHeight (image_wand);
8777 for (y = 0; y < image_height; y++)
8779 size_t row_width;
8780 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8781 if (! pixels)
8782 break;
8783 int xlim = min (row_width, width);
8784 for (x = 0; x < xlim; x++)
8786 PixelGetMagickColor (pixels[x], &pixel);
8787 XPutPixel (ximg, x, y,
8788 lookup_rgb_color (f,
8789 color_scale * pixel.red,
8790 color_scale * pixel.green,
8791 color_scale * pixel.blue));
8794 DestroyPixelIterator (iterator);
8797 #ifdef COLOR_TABLE_SUPPORT
8798 /* Remember colors allocated for this image. */
8799 img->colors = colors_in_color_table (&img->ncolors);
8800 free_color_table ();
8801 #endif /* COLOR_TABLE_SUPPORT */
8803 img->width = width;
8804 img->height = height;
8806 /* Put ximg into the image. */
8807 image_put_x_image (f, img, ximg, 0);
8809 /* Final cleanup. image_wand should be the only resource left. */
8810 DestroyMagickWand (image_wand);
8811 if (bg_wand) DestroyPixelWand (bg_wand);
8813 /* `MagickWandTerminus' terminates the imagemagick environment. */
8814 MagickWandTerminus ();
8816 return 1;
8818 imagemagick_error:
8819 DestroyMagickWand (image_wand);
8820 if (bg_wand) DestroyPixelWand (bg_wand);
8822 MagickWandTerminus ();
8823 /* TODO more cleanup. */
8824 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec);
8825 return 0;
8829 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8830 successful. this function will go into the imagemagick_type structure, and
8831 the prototype thus needs to be compatible with that structure. */
8833 static bool
8834 imagemagick_load (struct frame *f, struct image *img)
8836 bool success_p = 0;
8837 Lisp_Object file_name;
8839 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8840 file_name = image_spec_value (img->spec, QCfile, NULL);
8841 if (STRINGP (file_name))
8843 Lisp_Object file = x_find_image_file (file_name);
8844 if (!STRINGP (file))
8846 image_error ("Cannot find image file `%s'", file_name);
8847 return 0;
8849 file = ENCODE_FILE (file);
8850 #ifdef WINDOWSNT
8851 file = ansi_encode_filename (file);
8852 #endif
8853 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8855 /* Else its not a file, its a lisp object. Load the image from a
8856 lisp object rather than a file. */
8857 else
8859 Lisp_Object data;
8861 data = image_spec_value (img->spec, QCdata, NULL);
8862 if (!STRINGP (data))
8864 image_error ("Invalid image data `%s'", data);
8865 return 0;
8867 success_p = imagemagick_load_image (f, img, SDATA (data),
8868 SBYTES (data), NULL);
8871 return success_p;
8874 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8875 doc: /* Return a list of image types supported by ImageMagick.
8876 Each entry in this list is a symbol named after an ImageMagick format
8877 tag. See the ImageMagick manual for a list of ImageMagick formats and
8878 their descriptions (http://www.imagemagick.org/script/formats.php).
8879 You can also try the shell command: `identify -list format'.
8881 Note that ImageMagick recognizes many file-types that Emacs does not
8882 recognize as images, such as C. See `imagemagick-types-enable'
8883 and `imagemagick-types-inhibit'. */)
8884 (void)
8886 Lisp_Object typelist = Qnil;
8887 size_t numf = 0;
8888 ExceptionInfo ex;
8889 char **imtypes;
8890 size_t i;
8892 GetExceptionInfo(&ex);
8893 imtypes = GetMagickList ("*", &numf, &ex);
8894 DestroyExceptionInfo(&ex);
8896 for (i = 0; i < numf; i++)
8898 Lisp_Object imagemagicktype = intern (imtypes[i]);
8899 typelist = Fcons (imagemagicktype, typelist);
8900 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8903 MagickRelinquishMemory (imtypes);
8904 return Fnreverse (typelist);
8907 #endif /* defined (HAVE_IMAGEMAGICK) */
8911 /***********************************************************************
8913 ***********************************************************************/
8915 #ifdef HAVE_RSVG
8917 /* Function prototypes. */
8919 static bool svg_image_p (Lisp_Object object);
8920 static bool svg_load (struct frame *f, struct image *img);
8922 static bool svg_load_image (struct frame *, struct image *,
8923 unsigned char *, ptrdiff_t, char *);
8925 /* Indices of image specification fields in svg_format, below. */
8927 enum svg_keyword_index
8929 SVG_TYPE,
8930 SVG_DATA,
8931 SVG_FILE,
8932 SVG_ASCENT,
8933 SVG_MARGIN,
8934 SVG_RELIEF,
8935 SVG_ALGORITHM,
8936 SVG_HEURISTIC_MASK,
8937 SVG_MASK,
8938 SVG_BACKGROUND,
8939 SVG_LAST
8942 /* Vector of image_keyword structures describing the format
8943 of valid user-defined image specifications. */
8945 static const struct image_keyword svg_format[SVG_LAST] =
8947 {":type", IMAGE_SYMBOL_VALUE, 1},
8948 {":data", IMAGE_STRING_VALUE, 0},
8949 {":file", IMAGE_STRING_VALUE, 0},
8950 {":ascent", IMAGE_ASCENT_VALUE, 0},
8951 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8952 {":relief", IMAGE_INTEGER_VALUE, 0},
8953 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8954 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8955 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8956 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8959 # if defined HAVE_NTGUI && defined WINDOWSNT
8960 static bool init_svg_functions (void);
8961 # else
8962 #define init_svg_functions NULL
8963 # endif
8965 /* Structure describing the image type `svg'. Its the same type of
8966 structure defined for all image formats, handled by emacs image
8967 functions. See struct image_type in dispextern.h. */
8969 static struct image_type svg_type =
8971 SYMBOL_INDEX (Qsvg),
8972 svg_image_p,
8973 svg_load,
8974 x_clear_image,
8975 init_svg_functions,
8976 NULL
8980 /* Return true if OBJECT is a valid SVG image specification. Do
8981 this by calling parse_image_spec and supplying the keywords that
8982 identify the SVG format. */
8984 static bool
8985 svg_image_p (Lisp_Object object)
8987 struct image_keyword fmt[SVG_LAST];
8988 memcpy (fmt, svg_format, sizeof fmt);
8990 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8991 return 0;
8993 /* Must specify either the :data or :file keyword. */
8994 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8997 # include <librsvg/rsvg.h>
8999 # ifdef WINDOWSNT
9001 /* SVG library functions. */
9002 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
9003 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
9004 (RsvgHandle *, RsvgDimensionData *));
9005 DEF_DLL_FN (gboolean, rsvg_handle_write,
9006 (RsvgHandle *, const guchar *, gsize, GError **));
9007 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
9008 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
9009 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
9011 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
9012 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
9013 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
9014 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
9015 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
9016 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
9017 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
9018 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
9020 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9021 DEF_DLL_FN (void, g_type_init, (void));
9022 # endif
9023 DEF_DLL_FN (void, g_object_unref, (gpointer));
9024 DEF_DLL_FN (void, g_clear_error, (GError **));
9026 static bool
9027 init_svg_functions (void)
9029 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
9031 if (!(glib = w32_delayed_load (Qglib))
9032 || !(gobject = w32_delayed_load (Qgobject))
9033 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
9034 || !(library = w32_delayed_load (Qsvg)))
9036 if (gdklib) FreeLibrary (gdklib);
9037 if (gobject) FreeLibrary (gobject);
9038 if (glib) FreeLibrary (glib);
9039 return 0;
9042 LOAD_DLL_FN (library, rsvg_handle_new);
9043 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
9044 LOAD_DLL_FN (library, rsvg_handle_write);
9045 LOAD_DLL_FN (library, rsvg_handle_close);
9046 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
9047 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
9049 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
9050 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
9051 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
9052 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
9053 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
9054 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
9055 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
9056 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
9058 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9059 LOAD_DLL_FN (gobject, g_type_init);
9060 # endif
9061 LOAD_DLL_FN (gobject, g_object_unref);
9062 LOAD_DLL_FN (glib, g_clear_error);
9064 return 1;
9067 /* The following aliases for library functions allow dynamic loading
9068 to be used on some platforms. */
9070 # undef gdk_pixbuf_get_bits_per_sample
9071 # undef gdk_pixbuf_get_colorspace
9072 # undef gdk_pixbuf_get_has_alpha
9073 # undef gdk_pixbuf_get_height
9074 # undef gdk_pixbuf_get_n_channels
9075 # undef gdk_pixbuf_get_pixels
9076 # undef gdk_pixbuf_get_rowstride
9077 # undef gdk_pixbuf_get_width
9078 # undef g_clear_error
9079 # undef g_object_unref
9080 # undef g_type_init
9081 # undef rsvg_handle_close
9082 # undef rsvg_handle_get_dimensions
9083 # undef rsvg_handle_get_pixbuf
9084 # undef rsvg_handle_new
9085 # undef rsvg_handle_set_base_uri
9086 # undef rsvg_handle_write
9088 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9089 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9090 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9091 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9092 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9093 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9094 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9095 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9096 # define g_clear_error fn_g_clear_error
9097 # define g_object_unref fn_g_object_unref
9098 # define g_type_init fn_g_type_init
9099 # define rsvg_handle_close fn_rsvg_handle_close
9100 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9101 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9102 # define rsvg_handle_new fn_rsvg_handle_new
9103 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9104 # define rsvg_handle_write fn_rsvg_handle_write
9106 # endif /* !WINDOWSNT */
9108 /* Load SVG image IMG for use on frame F. Value is true if
9109 successful. */
9111 static bool
9112 svg_load (struct frame *f, struct image *img)
9114 bool success_p = 0;
9115 Lisp_Object file_name;
9117 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9118 file_name = image_spec_value (img->spec, QCfile, NULL);
9119 if (STRINGP (file_name))
9121 int fd;
9122 Lisp_Object file = x_find_image_fd (file_name, &fd);
9123 if (!STRINGP (file))
9125 image_error ("Cannot find image file `%s'", file_name);
9126 return 0;
9129 /* Read the entire file into memory. */
9130 ptrdiff_t size;
9131 unsigned char *contents = slurp_file (fd, &size);
9132 if (contents == NULL)
9134 image_error ("Error loading SVG image `%s'", file);
9135 return 0;
9137 /* If the file was slurped into memory properly, parse it. */
9138 success_p = svg_load_image (f, img, contents, size,
9139 SSDATA (ENCODE_FILE (file)));
9140 xfree (contents);
9142 /* Else its not a file, its a lisp object. Load the image from a
9143 lisp object rather than a file. */
9144 else
9146 Lisp_Object data, original_filename;
9148 data = image_spec_value (img->spec, QCdata, NULL);
9149 if (!STRINGP (data))
9151 image_error ("Invalid image data `%s'", data);
9152 return 0;
9154 original_filename = BVAR (current_buffer, filename);
9155 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data),
9156 (NILP (original_filename) ? NULL
9157 : SSDATA (original_filename)));
9160 return success_p;
9163 /* svg_load_image is a helper function for svg_load, which does the
9164 actual loading given contents and size, apart from frame and image
9165 structures, passed from svg_load.
9167 Uses librsvg to do most of the image processing.
9169 Returns true when successful. */
9170 static bool
9171 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
9172 struct image *img, /* Pointer to emacs image structure. */
9173 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
9174 ptrdiff_t size, /* Size of data in bytes. */
9175 char *filename) /* Name of SVG file being loaded. */
9177 RsvgHandle *rsvg_handle;
9178 RsvgDimensionData dimension_data;
9179 GError *err = NULL;
9180 GdkPixbuf *pixbuf;
9181 int width;
9182 int height;
9183 const guint8 *pixels;
9184 int rowstride;
9185 XImagePtr ximg;
9186 Lisp_Object specified_bg;
9187 XColor background;
9188 int x;
9189 int y;
9191 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9192 /* g_type_init is a glib function that must be called prior to
9193 using gnome type library functions (obsolete since 2.36.0). */
9194 g_type_init ();
9195 #endif
9197 /* Make a handle to a new rsvg object. */
9198 rsvg_handle = rsvg_handle_new ();
9200 /* Set base_uri for properly handling referenced images (via 'href').
9201 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9202 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9203 if (filename)
9204 rsvg_handle_set_base_uri(rsvg_handle, filename);
9206 /* Parse the contents argument and fill in the rsvg_handle. */
9207 rsvg_handle_write (rsvg_handle, contents, size, &err);
9208 if (err) goto rsvg_error;
9210 /* The parsing is complete, rsvg_handle is ready to used, close it
9211 for further writes. */
9212 rsvg_handle_close (rsvg_handle, &err);
9213 if (err) goto rsvg_error;
9215 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
9216 if (! check_image_size (f, dimension_data.width, dimension_data.height))
9218 image_size_error ();
9219 goto rsvg_error;
9222 /* We can now get a valid pixel buffer from the svg file, if all
9223 went ok. */
9224 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
9225 if (!pixbuf) goto rsvg_error;
9226 g_object_unref (rsvg_handle);
9228 /* Extract some meta data from the svg handle. */
9229 width = gdk_pixbuf_get_width (pixbuf);
9230 height = gdk_pixbuf_get_height (pixbuf);
9231 pixels = gdk_pixbuf_get_pixels (pixbuf);
9232 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
9234 /* Validate the svg meta data. */
9235 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
9236 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
9237 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
9238 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
9240 #ifdef USE_CAIRO
9242 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
9243 int y;
9244 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
9246 for (y = 0; y < height; ++y)
9248 const guchar *iconptr = pixels + y * rowstride;
9249 uint32_t *dataptr = (uint32_t *) (data + y * rowstride);
9250 int x;
9252 for (x = 0; x < width; ++x)
9254 if (iconptr[3] == 0)
9255 *dataptr = bgcolor;
9256 else
9257 *dataptr = (iconptr[0] << 16)
9258 | (iconptr[1] << 8)
9259 | iconptr[2]
9260 | (iconptr[3] << 24);
9262 iconptr += 4;
9263 ++dataptr;
9267 create_cairo_image_surface (img, data, width, height);
9268 g_object_unref (pixbuf);
9270 #else
9271 /* Try to create a x pixmap to hold the svg pixmap. */
9272 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
9274 g_object_unref (pixbuf);
9275 return 0;
9278 init_color_table ();
9280 /* Handle alpha channel by combining the image with a background
9281 color. */
9282 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
9283 if (!STRINGP (specified_bg)
9284 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
9285 x_query_frame_background_color (f, &background);
9287 /* SVG pixmaps specify transparency in the last byte, so right
9288 shift 8 bits to get rid of it, since emacs doesn't support
9289 transparency. */
9290 background.red >>= 8;
9291 background.green >>= 8;
9292 background.blue >>= 8;
9294 /* This loop handles opacity values, since Emacs assumes
9295 non-transparent images. Each pixel must be "flattened" by
9296 calculating the resulting color, given the transparency of the
9297 pixel, and the image background color. */
9298 for (y = 0; y < height; ++y)
9300 for (x = 0; x < width; ++x)
9302 int red;
9303 int green;
9304 int blue;
9305 int opacity;
9307 red = *pixels++;
9308 green = *pixels++;
9309 blue = *pixels++;
9310 opacity = *pixels++;
9312 red = ((red * opacity)
9313 + (background.red * ((1 << 8) - opacity)));
9314 green = ((green * opacity)
9315 + (background.green * ((1 << 8) - opacity)));
9316 blue = ((blue * opacity)
9317 + (background.blue * ((1 << 8) - opacity)));
9319 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9322 pixels += rowstride - 4 * width;
9325 #ifdef COLOR_TABLE_SUPPORT
9326 /* Remember colors allocated for this image. */
9327 img->colors = colors_in_color_table (&img->ncolors);
9328 free_color_table ();
9329 #endif /* COLOR_TABLE_SUPPORT */
9331 g_object_unref (pixbuf);
9333 img->width = width;
9334 img->height = height;
9336 /* Maybe fill in the background field while we have ximg handy.
9337 Casting avoids a GCC warning. */
9338 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9340 /* Put ximg into the image. */
9341 image_put_x_image (f, img, ximg, 0);
9342 #endif /* ! USE_CAIRO */
9344 return 1;
9346 rsvg_error:
9347 g_object_unref (rsvg_handle);
9348 /* FIXME: Use error->message so the user knows what is the actual
9349 problem with the image. */
9350 image_error ("Error parsing SVG image `%s'", img->spec);
9351 g_clear_error (&err);
9352 return 0;
9355 #endif /* defined (HAVE_RSVG) */
9360 /***********************************************************************
9361 Ghostscript
9362 ***********************************************************************/
9364 #ifdef HAVE_X_WINDOWS
9365 #define HAVE_GHOSTSCRIPT 1
9366 #endif /* HAVE_X_WINDOWS */
9368 #ifdef HAVE_GHOSTSCRIPT
9370 static bool gs_image_p (Lisp_Object object);
9371 static bool gs_load (struct frame *f, struct image *img);
9372 static void gs_clear_image (struct frame *f, struct image *img);
9374 /* Indices of image specification fields in gs_format, below. */
9376 enum gs_keyword_index
9378 GS_TYPE,
9379 GS_PT_WIDTH,
9380 GS_PT_HEIGHT,
9381 GS_FILE,
9382 GS_LOADER,
9383 GS_BOUNDING_BOX,
9384 GS_ASCENT,
9385 GS_MARGIN,
9386 GS_RELIEF,
9387 GS_ALGORITHM,
9388 GS_HEURISTIC_MASK,
9389 GS_MASK,
9390 GS_BACKGROUND,
9391 GS_LAST
9394 /* Vector of image_keyword structures describing the format
9395 of valid user-defined image specifications. */
9397 static const struct image_keyword gs_format[GS_LAST] =
9399 {":type", IMAGE_SYMBOL_VALUE, 1},
9400 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9401 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9402 {":file", IMAGE_STRING_VALUE, 1},
9403 {":loader", IMAGE_FUNCTION_VALUE, 0},
9404 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9405 {":ascent", IMAGE_ASCENT_VALUE, 0},
9406 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9407 {":relief", IMAGE_INTEGER_VALUE, 0},
9408 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9409 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9410 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9411 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9414 /* Structure describing the image type `ghostscript'. */
9416 static struct image_type gs_type =
9418 SYMBOL_INDEX (Qpostscript),
9419 gs_image_p,
9420 gs_load,
9421 gs_clear_image,
9422 NULL,
9423 NULL
9427 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9429 static void
9430 gs_clear_image (struct frame *f, struct image *img)
9432 x_clear_image (f, img);
9436 /* Return true if OBJECT is a valid Ghostscript image
9437 specification. */
9439 static bool
9440 gs_image_p (Lisp_Object object)
9442 struct image_keyword fmt[GS_LAST];
9443 Lisp_Object tem;
9444 int i;
9446 memcpy (fmt, gs_format, sizeof fmt);
9448 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9449 return 0;
9451 /* Bounding box must be a list or vector containing 4 integers. */
9452 tem = fmt[GS_BOUNDING_BOX].value;
9453 if (CONSP (tem))
9455 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9456 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9457 return 0;
9458 if (!NILP (tem))
9459 return 0;
9461 else if (VECTORP (tem))
9463 if (ASIZE (tem) != 4)
9464 return 0;
9465 for (i = 0; i < 4; ++i)
9466 if (!INTEGERP (AREF (tem, i)))
9467 return 0;
9469 else
9470 return 0;
9472 return 1;
9476 /* Load Ghostscript image IMG for use on frame F. Value is true
9477 if successful. */
9479 static bool
9480 gs_load (struct frame *f, struct image *img)
9482 uprintmax_t printnum1, printnum2;
9483 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9484 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9485 Lisp_Object frame;
9486 double in_width, in_height;
9487 Lisp_Object pixel_colors = Qnil;
9489 /* Compute pixel size of pixmap needed from the given size in the
9490 image specification. Sizes in the specification are in pt. 1 pt
9491 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9492 info. */
9493 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9494 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9495 in_width *= FRAME_RES_X (f);
9496 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9497 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9498 in_height *= FRAME_RES_Y (f);
9500 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9501 && check_image_size (f, in_width, in_height)))
9503 image_size_error ();
9504 return 0;
9506 img->width = in_width;
9507 img->height = in_height;
9509 /* Create the pixmap. */
9510 eassert (img->pixmap == NO_PIXMAP);
9512 if (x_check_image_size (0, img->width, img->height))
9514 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9515 block_input ();
9516 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9517 img->width, img->height,
9518 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9519 unblock_input ();
9522 if (!img->pixmap)
9524 image_error ("Unable to create pixmap for `%s'" , img->spec);
9525 return 0;
9528 /* Call the loader to fill the pixmap. It returns a process object
9529 if successful. We do not record_unwind_protect here because
9530 other places in redisplay like calling window scroll functions
9531 don't either. Let the Lisp loader use `unwind-protect' instead. */
9532 printnum1 = FRAME_X_WINDOW (f);
9533 printnum2 = img->pixmap;
9534 window_and_pixmap_id
9535 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9537 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9538 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9539 pixel_colors
9540 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9542 XSETFRAME (frame, f);
9543 loader = image_spec_value (img->spec, QCloader, NULL);
9544 if (NILP (loader))
9545 loader = intern ("gs-load-image");
9547 img->lisp_data = call6 (loader, frame, img->spec,
9548 make_number (img->width),
9549 make_number (img->height),
9550 window_and_pixmap_id,
9551 pixel_colors);
9552 return PROCESSP (img->lisp_data);
9556 /* Kill the Ghostscript process that was started to fill PIXMAP on
9557 frame F. Called from XTread_socket when receiving an event
9558 telling Emacs that Ghostscript has finished drawing. */
9560 void
9561 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9563 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9564 ptrdiff_t i;
9565 struct image *img;
9567 /* Find the image containing PIXMAP. */
9568 for (i = 0; i < c->used; ++i)
9569 if (c->images[i]->pixmap == pixmap)
9570 break;
9572 /* Should someone in between have cleared the image cache, for
9573 instance, give up. */
9574 if (i == c->used)
9575 return;
9577 /* Kill the GS process. We should have found PIXMAP in the image
9578 cache and its image should contain a process object. */
9579 img = c->images[i];
9580 eassert (PROCESSP (img->lisp_data));
9581 Fkill_process (img->lisp_data, Qnil);
9582 img->lisp_data = Qnil;
9584 #if defined (HAVE_X_WINDOWS)
9586 /* On displays with a mutable colormap, figure out the colors
9587 allocated for the image by looking at the pixels of an XImage for
9588 img->pixmap. */
9589 if (x_mutable_colormap (FRAME_X_VISUAL (f)))
9591 XImagePtr ximg;
9593 block_input ();
9595 /* Try to get an XImage for img->pixmep. */
9596 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9597 0, 0, img->width, img->height, ~0, ZPixmap);
9598 if (ximg)
9600 int x, y;
9602 /* Initialize the color table. */
9603 init_color_table ();
9605 /* For each pixel of the image, look its color up in the
9606 color table. After having done so, the color table will
9607 contain an entry for each color used by the image. */
9608 #ifdef COLOR_TABLE_SUPPORT
9609 for (y = 0; y < img->height; ++y)
9610 for (x = 0; x < img->width; ++x)
9612 unsigned long pixel = XGetPixel (ximg, x, y);
9614 lookup_pixel_color (f, pixel);
9617 /* Record colors in the image. Free color table and XImage. */
9618 img->colors = colors_in_color_table (&img->ncolors);
9619 free_color_table ();
9620 #endif
9621 XDestroyImage (ximg);
9623 #if 0 /* This doesn't seem to be the case. If we free the colors
9624 here, we get a BadAccess later in x_clear_image when
9625 freeing the colors. */
9626 /* We have allocated colors once, but Ghostscript has also
9627 allocated colors on behalf of us. So, to get the
9628 reference counts right, free them once. */
9629 if (img->ncolors)
9630 x_free_colors (f, img->colors, img->ncolors);
9631 #endif
9633 else
9634 image_error ("Cannot get X image of `%s'; colors will not be freed",
9635 img->spec);
9637 unblock_input ();
9639 #endif /* HAVE_X_WINDOWS */
9641 /* Now that we have the pixmap, compute mask and transform the
9642 image if requested. */
9643 block_input ();
9644 postprocess_image (f, img);
9645 unblock_input ();
9648 #endif /* HAVE_GHOSTSCRIPT */
9651 /***********************************************************************
9652 Tests
9653 ***********************************************************************/
9655 #ifdef GLYPH_DEBUG
9657 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9658 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9659 (Lisp_Object spec)
9661 return valid_image_p (spec) ? Qt : Qnil;
9665 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0,
9666 doc: /* */)
9667 (Lisp_Object spec)
9669 ptrdiff_t id = -1;
9671 if (valid_image_p (spec))
9672 id = lookup_image (SELECTED_FRAME (), spec);
9674 debug_print (spec);
9675 return make_number (id);
9678 #endif /* GLYPH_DEBUG */
9681 /***********************************************************************
9682 Initialization
9683 ***********************************************************************/
9685 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9686 doc: /* Initialize image library implementing image type TYPE.
9687 Return non-nil if TYPE is a supported image type.
9689 If image libraries are loaded dynamically (currently only the case on
9690 MS-Windows), load the library for TYPE if it is not yet loaded, using
9691 the library file(s) specified by `dynamic-library-alist'. */)
9692 (Lisp_Object type)
9694 return lookup_image_type (type) ? Qt : Qnil;
9697 /* Look up image type TYPE, and return a pointer to its image_type
9698 structure. Return 0 if TYPE is not a known image type. */
9700 static struct image_type *
9701 lookup_image_type (Lisp_Object type)
9703 /* Types pbm and xbm are built-in and always available. */
9704 if (EQ (type, Qpbm))
9705 return define_image_type (&pbm_type);
9707 if (EQ (type, Qxbm))
9708 return define_image_type (&xbm_type);
9710 #if defined (HAVE_XPM) || defined (HAVE_NS)
9711 if (EQ (type, Qxpm))
9712 return define_image_type (&xpm_type);
9713 #endif
9715 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9716 if (EQ (type, Qjpeg))
9717 return define_image_type (&jpeg_type);
9718 #endif
9720 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9721 if (EQ (type, Qtiff))
9722 return define_image_type (&tiff_type);
9723 #endif
9725 #if defined (HAVE_GIF) || defined (HAVE_NS)
9726 if (EQ (type, Qgif))
9727 return define_image_type (&gif_type);
9728 #endif
9730 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9731 if (EQ (type, Qpng))
9732 return define_image_type (&png_type);
9733 #endif
9735 #if defined (HAVE_RSVG)
9736 if (EQ (type, Qsvg))
9737 return define_image_type (&svg_type);
9738 #endif
9740 #if defined (HAVE_IMAGEMAGICK)
9741 if (EQ (type, Qimagemagick))
9742 return define_image_type (&imagemagick_type);
9743 #endif
9745 #ifdef HAVE_GHOSTSCRIPT
9746 if (EQ (type, Qpostscript))
9747 return define_image_type (&gs_type);
9748 #endif
9750 return NULL;
9753 /* Reset image_types before dumping.
9754 Called from Fdump_emacs. */
9756 void
9757 reset_image_types (void)
9759 while (image_types)
9761 struct image_type *next = image_types->next;
9762 xfree (image_types);
9763 image_types = next;
9767 void
9768 syms_of_image (void)
9770 /* Initialize this only once; it will be reset before dumping. */
9771 image_types = NULL;
9773 /* Must be defined now because we're going to update it below, while
9774 defining the supported image types. */
9775 DEFVAR_LISP ("image-types", Vimage_types,
9776 doc: /* List of potentially supported image types.
9777 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9778 To check whether it is really supported, use `image-type-available-p'. */);
9779 Vimage_types = Qnil;
9781 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9782 doc: /* Maximum size of images.
9783 Emacs will not load an image into memory if its pixel width or
9784 pixel height exceeds this limit.
9786 If the value is an integer, it directly specifies the maximum
9787 image height and width, measured in pixels. If it is a floating
9788 point number, it specifies the maximum image height and width
9789 as a ratio to the frame height and width. If the value is
9790 non-numeric, there is no explicit limit on the size of images. */);
9791 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9793 /* Other symbols. */
9794 DEFSYM (Qcount, "count");
9795 DEFSYM (Qextension_data, "extension-data");
9796 DEFSYM (Qdelay, "delay");
9798 /* Keywords. */
9799 DEFSYM (QCascent, ":ascent");
9800 DEFSYM (QCmargin, ":margin");
9801 DEFSYM (QCrelief, ":relief");
9802 DEFSYM (QCconversion, ":conversion");
9803 DEFSYM (QCcolor_symbols, ":color-symbols");
9804 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9805 DEFSYM (QCindex, ":index");
9806 DEFSYM (QCcrop, ":crop");
9807 DEFSYM (QCrotation, ":rotation");
9808 DEFSYM (QCmatrix, ":matrix");
9809 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9810 DEFSYM (QCmask, ":mask");
9812 /* Other symbols. */
9813 DEFSYM (Qlaplace, "laplace");
9814 DEFSYM (Qemboss, "emboss");
9815 DEFSYM (Qedge_detection, "edge-detection");
9816 DEFSYM (Qheuristic, "heuristic");
9818 DEFSYM (Qpostscript, "postscript");
9819 DEFSYM (QCmax_width, ":max-width");
9820 DEFSYM (QCmax_height, ":max-height");
9821 #ifdef HAVE_GHOSTSCRIPT
9822 ADD_IMAGE_TYPE (Qpostscript);
9823 DEFSYM (QCloader, ":loader");
9824 DEFSYM (QCpt_width, ":pt-width");
9825 DEFSYM (QCpt_height, ":pt-height");
9826 #endif /* HAVE_GHOSTSCRIPT */
9828 #ifdef HAVE_NTGUI
9829 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9830 or -1 if no PNG/GIF support was compiled in. This is tested by
9831 w32-win.el to correctly set up the alist used to search for the
9832 respective image libraries. */
9833 DEFSYM (Qlibpng_version, "libpng-version");
9834 Fset (Qlibpng_version,
9835 #if HAVE_PNG
9836 make_number (PNG_LIBPNG_VER)
9837 #else
9838 make_number (-1)
9839 #endif
9841 DEFSYM (Qlibgif_version, "libgif-version");
9842 Fset (Qlibgif_version,
9843 #ifdef HAVE_GIF
9844 make_number (GIFLIB_MAJOR * 10000
9845 + GIFLIB_MINOR * 100
9846 + GIFLIB_RELEASE)
9847 #else
9848 make_number (-1)
9849 #endif
9851 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9852 Fset (Qlibjpeg_version,
9853 #if HAVE_JPEG
9854 make_number (JPEG_LIB_VERSION)
9855 #else
9856 make_number (-1)
9857 #endif
9859 #endif
9861 DEFSYM (Qpbm, "pbm");
9862 ADD_IMAGE_TYPE (Qpbm);
9864 DEFSYM (Qxbm, "xbm");
9865 ADD_IMAGE_TYPE (Qxbm);
9867 #if defined (HAVE_XPM) || defined (HAVE_NS)
9868 DEFSYM (Qxpm, "xpm");
9869 ADD_IMAGE_TYPE (Qxpm);
9870 #endif
9872 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9873 DEFSYM (Qjpeg, "jpeg");
9874 ADD_IMAGE_TYPE (Qjpeg);
9875 #endif
9877 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9878 DEFSYM (Qtiff, "tiff");
9879 ADD_IMAGE_TYPE (Qtiff);
9880 #endif
9882 #if defined (HAVE_GIF) || defined (HAVE_NS)
9883 DEFSYM (Qgif, "gif");
9884 ADD_IMAGE_TYPE (Qgif);
9885 #endif
9887 #if defined (HAVE_PNG) || defined (HAVE_NS)
9888 DEFSYM (Qpng, "png");
9889 ADD_IMAGE_TYPE (Qpng);
9890 #endif
9892 #if defined (HAVE_IMAGEMAGICK)
9893 DEFSYM (Qimagemagick, "imagemagick");
9894 ADD_IMAGE_TYPE (Qimagemagick);
9895 #endif
9897 #if defined (HAVE_RSVG)
9898 DEFSYM (Qsvg, "svg");
9899 ADD_IMAGE_TYPE (Qsvg);
9900 #ifdef HAVE_NTGUI
9901 /* Other libraries used directly by svg code. */
9902 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9903 DEFSYM (Qglib, "glib");
9904 DEFSYM (Qgobject, "gobject");
9905 #endif /* HAVE_NTGUI */
9906 #endif /* HAVE_RSVG */
9908 defsubr (&Sinit_image_library);
9909 #ifdef HAVE_IMAGEMAGICK
9910 defsubr (&Simagemagick_types);
9911 #endif
9912 defsubr (&Sclear_image_cache);
9913 defsubr (&Simage_flush);
9914 defsubr (&Simage_size);
9915 defsubr (&Simage_mask_p);
9916 defsubr (&Simage_metadata);
9918 #ifdef GLYPH_DEBUG
9919 defsubr (&Simagep);
9920 defsubr (&Slookup_image);
9921 #endif
9923 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9924 doc: /* Non-nil means always draw a cross over disabled images.
9925 Disabled images are those having a `:conversion disabled' property.
9926 A cross is always drawn on black & white displays. */);
9927 cross_disabled_images = 0;
9929 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9930 doc: /* List of directories to search for window system bitmap files. */);
9931 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9933 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9934 doc: /* Maximum time after which images are removed from the cache.
9935 When an image has not been displayed this many seconds, Emacs
9936 automatically removes it from the image cache. If the cache contains
9937 a large number of images, the actual eviction time may be shorter.
9938 The value can also be nil, meaning the cache is never cleared.
9940 The function `clear-image-cache' disregards this variable. */);
9941 Vimage_cache_eviction_delay = make_number (300);
9942 #ifdef HAVE_IMAGEMAGICK
9943 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9944 doc: /* Integer indicating which ImageMagick rendering method to use.
9945 The options are:
9946 0 -- the default method (pixel pushing)
9947 1 -- a newer method ("MagickExportImagePixels") that may perform
9948 better (speed etc) in some cases, but has not been as thoroughly
9949 tested with Emacs as the default method. This method requires
9950 ImageMagick version 6.4.6 (approximately) or later.
9951 */);
9952 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9953 imagemagick_render_type = 0;
9954 #endif