Fix problems found by static checking --with-ns
[emacs.git] / src / image.c
blobe508550629c4814ee85fa4223791181527888ab6
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <unistd.h>
26 /* Include this before including <setjmp.h> to work around bugs with
27 older libpng; see Bug#17429. */
28 #if defined HAVE_PNG && !defined HAVE_NS
29 # include <png.h>
30 #endif
32 #include <setjmp.h>
34 #include <c-ctype.h>
35 #include <flexmember.h>
37 #include "lisp.h"
38 #include "frame.h"
39 #include "window.h"
40 #include "buffer.h"
41 #include "dispextern.h"
42 #include "blockinput.h"
43 #include "systime.h"
44 #include <epaths.h>
45 #include "coding.h"
46 #include "termhooks.h"
47 #include "font.h"
49 #ifdef HAVE_SYS_STAT_H
50 #include <sys/stat.h>
51 #endif /* HAVE_SYS_STAT_H */
53 #ifdef HAVE_SYS_TYPES_H
54 #include <sys/types.h>
55 #endif /* HAVE_SYS_TYPES_H */
57 #ifdef HAVE_WINDOW_SYSTEM
58 #include TERM_HEADER
59 #endif /* HAVE_WINDOW_SYSTEM */
61 /* Work around GCC bug 54561. */
62 #if GNUC_PREREQ (4, 3, 0)
63 # pragma GCC diagnostic ignored "-Wclobbered"
64 #endif
66 #ifdef HAVE_X_WINDOWS
67 typedef struct x_bitmap_record Bitmap_Record;
68 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
69 #define NO_PIXMAP None
71 #define PIX_MASK_RETAIN 0
72 #define PIX_MASK_DRAW 1
73 #endif /* HAVE_X_WINDOWS */
75 #ifdef HAVE_NTGUI
77 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
78 #ifdef WINDOWSNT
79 # include "w32.h"
80 #endif
82 typedef struct w32_bitmap_record Bitmap_Record;
83 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
84 #define NO_PIXMAP 0
86 #define PIX_MASK_RETAIN 0
87 #define PIX_MASK_DRAW 1
89 #define x_defined_color w32_defined_color
91 #endif /* HAVE_NTGUI */
93 #ifdef HAVE_NS
94 typedef struct ns_bitmap_record Bitmap_Record;
96 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
97 #define NO_PIXMAP 0
99 #define PIX_MASK_RETAIN 0
101 #define x_defined_color(f, name, color_def, alloc) \
102 ns_defined_color (f, name, color_def, alloc, 0)
103 #endif /* HAVE_NS */
105 #if (defined HAVE_X_WINDOWS \
106 && ! (defined HAVE_NTGUI || defined USE_CAIRO || defined HAVE_NS))
107 /* W32_TODO : Color tables on W32. */
108 # define COLOR_TABLE_SUPPORT 1
109 #endif
111 static void x_disable_image (struct frame *, struct image *);
112 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
113 Lisp_Object);
115 static void init_color_table (void);
116 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
117 #ifdef COLOR_TABLE_SUPPORT
118 static void free_color_table (void);
119 static unsigned long *colors_in_color_table (int *n);
120 #endif
122 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
123 id, which is just an int that this section returns. Bitmaps are
124 reference counted so they can be shared among frames.
126 Bitmap indices are guaranteed to be > 0, so a negative number can
127 be used to indicate no bitmap.
129 If you use x_create_bitmap_from_data, then you must keep track of
130 the bitmaps yourself. That is, creating a bitmap from the same
131 data more than once will not be caught. */
133 #ifdef HAVE_NS
134 /* Use with images created by ns_image_for_XPM. */
135 static unsigned long
136 XGetPixel (XImagePtr ximage, int x, int y)
138 return ns_get_pixel (ximage, x, y);
141 /* Use with images created by ns_image_for_XPM; alpha set to 1;
142 pixel is assumed to be in RGB form. */
143 static void
144 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
146 ns_put_pixel (ximage, x, y, pixel);
148 #endif /* HAVE_NS */
151 /* Functions to access the contents of a bitmap, given an id. */
153 #ifdef HAVE_X_WINDOWS
154 static int
155 x_bitmap_height (struct frame *f, ptrdiff_t id)
157 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
160 static int
161 x_bitmap_width (struct frame *f, ptrdiff_t id)
163 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
165 #endif
167 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
168 ptrdiff_t
169 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
171 /* HAVE_NTGUI needs the explicit cast here. */
172 return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
174 #endif
176 #ifdef HAVE_X_WINDOWS
178 x_bitmap_mask (struct frame *f, ptrdiff_t id)
180 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
182 #endif
184 /* Allocate a new bitmap record. Returns index of new record. */
186 static ptrdiff_t
187 x_allocate_bitmap_record (struct frame *f)
189 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
190 ptrdiff_t i;
192 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
193 return ++dpyinfo->bitmaps_last;
195 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
196 if (dpyinfo->bitmaps[i].refcount == 0)
197 return i + 1;
199 dpyinfo->bitmaps =
200 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
201 10, -1, sizeof *dpyinfo->bitmaps);
202 return ++dpyinfo->bitmaps_last;
205 /* Add one reference to the reference count of the bitmap with id ID. */
207 void
208 x_reference_bitmap (struct frame *f, ptrdiff_t id)
210 ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
213 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
215 ptrdiff_t
216 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
218 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
219 ptrdiff_t id;
221 #ifdef HAVE_X_WINDOWS
222 Pixmap bitmap;
223 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
224 bits, width, height);
225 if (! bitmap)
226 return -1;
227 #endif /* HAVE_X_WINDOWS */
229 #ifdef HAVE_NTGUI
230 Lisp_Object frame UNINIT; /* The value is not used. */
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 #ifdef HAVE_NTGUI
279 return -1; /* W32_TODO : bitmap support */
280 #else
281 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
282 #endif
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];
1151 RGB_PIXEL_COLOR best UNINIT;
1152 int i, best_count;
1154 if (corners && corners[BOT_CORNER] >= 0)
1156 /* Get the colors at the corner_pixels of ximg. */
1157 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1158 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1159 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1160 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1162 else
1164 /* Get the colors at the corner_pixels of ximg. */
1165 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1166 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1167 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1168 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1170 /* Choose the most frequently found color as background. */
1171 for (i = best_count = 0; i < 4; ++i)
1173 int j, n;
1175 for (j = n = 0; j < 4; ++j)
1176 if (corner_pixels[i] == corner_pixels[j])
1177 ++n;
1179 if (n > best_count)
1180 best = corner_pixels[i], best_count = n;
1183 return best;
1186 /* Portability macros */
1188 #ifdef HAVE_NTGUI
1190 #define Free_Pixmap(display, pixmap) \
1191 DeleteObject (pixmap)
1193 #elif defined (HAVE_NS)
1195 #define Free_Pixmap(display, pixmap) \
1196 ns_release_object (pixmap)
1198 #else
1200 #define Free_Pixmap(display, pixmap) \
1201 XFreePixmap (display, pixmap)
1203 #endif /* !HAVE_NTGUI && !HAVE_NS */
1206 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1207 it is guessed heuristically. If non-zero, XIMG is an existing
1208 XImage object (or device context with the image selected on W32) to
1209 use for the heuristic. */
1211 RGB_PIXEL_COLOR
1212 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1214 if (! img->background_valid)
1215 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1217 bool free_ximg = !ximg;
1218 #ifdef HAVE_NTGUI
1219 HGDIOBJ prev;
1220 #endif /* HAVE_NTGUI */
1222 if (free_ximg)
1223 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1225 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1227 if (free_ximg)
1228 image_unget_x_image_or_dc (img, 0, ximg, prev);
1230 img->background_valid = 1;
1233 return img->background;
1236 /* Return the `background_transparent' field of IMG. If IMG doesn't
1237 have one yet, it is guessed heuristically. If non-zero, MASK is an
1238 existing XImage object to use for the heuristic. */
1241 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1243 if (! img->background_transparent_valid)
1244 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1246 if (img->mask)
1248 bool free_mask = !mask;
1249 #ifdef HAVE_NTGUI
1250 HGDIOBJ prev;
1251 #endif /* HAVE_NTGUI */
1253 if (free_mask)
1254 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1256 img->background_transparent
1257 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1259 if (free_mask)
1260 image_unget_x_image_or_dc (img, 1, mask, prev);
1262 else
1263 img->background_transparent = 0;
1265 img->background_transparent_valid = 1;
1268 return img->background_transparent;
1271 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1272 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1274 /* Store F's background color into *BGCOLOR. */
1275 static void
1276 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1278 #ifndef HAVE_NS
1279 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1280 x_query_color (f, bgcolor);
1281 #else
1282 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1283 #endif
1286 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1288 /***********************************************************************
1289 Helper functions for X image types
1290 ***********************************************************************/
1292 /* Clear X resources of image IMG on frame F according to FLAGS.
1293 FLAGS is bitwise-or of the following masks:
1294 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1295 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1296 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1297 any. */
1299 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1300 #define CLEAR_IMAGE_MASK (1 << 1)
1301 #define CLEAR_IMAGE_COLORS (1 << 2)
1303 static void
1304 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1306 if (flags & CLEAR_IMAGE_PIXMAP)
1308 if (img->pixmap)
1310 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1311 img->pixmap = NO_PIXMAP;
1312 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1313 img->background_valid = 0;
1315 #ifdef HAVE_X_WINDOWS
1316 if (img->ximg)
1318 x_destroy_x_image (img->ximg);
1319 img->ximg = NULL;
1320 img->background_valid = 0;
1322 #endif
1325 if (flags & CLEAR_IMAGE_MASK)
1327 if (img->mask)
1329 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1330 img->mask = NO_PIXMAP;
1331 img->background_transparent_valid = 0;
1333 #ifdef HAVE_X_WINDOWS
1334 if (img->mask_img)
1336 x_destroy_x_image (img->mask_img);
1337 img->mask_img = NULL;
1338 img->background_transparent_valid = 0;
1340 #endif
1343 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1345 /* W32_TODO: color table support. */
1346 #ifdef HAVE_X_WINDOWS
1347 x_free_colors (f, img->colors, img->ncolors);
1348 #endif /* HAVE_X_WINDOWS */
1349 xfree (img->colors);
1350 img->colors = NULL;
1351 img->ncolors = 0;
1356 /* Free X resources of image IMG which is used on frame F. */
1358 static void
1359 x_clear_image (struct frame *f, struct image *img)
1361 block_input ();
1362 #ifdef USE_CAIRO
1363 if (img->cr_data)
1364 cairo_surface_destroy ((cairo_surface_t *)img->cr_data);
1365 if (img->cr_data2) xfree (img->cr_data2);
1366 #endif
1367 x_clear_image_1 (f, img,
1368 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1369 unblock_input ();
1373 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1374 cannot be allocated, use DFLT. Add a newly allocated color to
1375 IMG->colors, so that it can be freed again. Value is the pixel
1376 color. */
1378 static unsigned long
1379 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1380 unsigned long dflt)
1382 XColor color;
1383 unsigned long result;
1385 eassert (STRINGP (color_name));
1387 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1388 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1389 INT_MAX))
1391 /* This isn't called frequently so we get away with simply
1392 reallocating the color vector to the needed size, here. */
1393 ptrdiff_t ncolors = img->ncolors + 1;
1394 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1395 img->colors[ncolors - 1] = color.pixel;
1396 img->ncolors = ncolors;
1397 result = color.pixel;
1399 else
1400 result = dflt;
1402 return result;
1407 /***********************************************************************
1408 Image Cache
1409 ***********************************************************************/
1411 static void cache_image (struct frame *f, struct image *img);
1413 /* Return a new, initialized image cache that is allocated from the
1414 heap. Call free_image_cache to free an image cache. */
1416 struct image_cache *
1417 make_image_cache (void)
1419 struct image_cache *c = xmalloc (sizeof *c);
1421 c->size = 50;
1422 c->used = c->refcount = 0;
1423 c->images = xmalloc (c->size * sizeof *c->images);
1424 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1425 return c;
1429 /* Find an image matching SPEC in the cache, and return it. If no
1430 image is found, return NULL. */
1431 static struct image *
1432 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1434 struct image *img;
1435 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1436 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1438 if (!c) return NULL;
1440 /* If the image spec does not specify a background color, the cached
1441 image must have the same background color as the current frame.
1442 The foreground color must also match, for the sake of monochrome
1443 images.
1445 In fact, we could ignore the foreground color matching condition
1446 for color images, or if the image spec specifies :foreground;
1447 similarly we could ignore the background color matching condition
1448 for formats that don't use transparency (such as jpeg), or if the
1449 image spec specifies :background. However, the extra memory
1450 usage is probably negligible in practice, so we don't bother. */
1452 for (img = c->buckets[i]; img; img = img->next)
1453 if (img->hash == hash
1454 && !NILP (Fequal (img->spec, spec))
1455 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1456 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1457 break;
1458 return img;
1462 /* Search frame F for an image with spec SPEC, and free it. */
1464 static void
1465 uncache_image (struct frame *f, Lisp_Object spec)
1467 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1468 if (img)
1470 free_image (f, img);
1471 /* As display glyphs may still be referring to the image ID, we
1472 must garbage the frame (Bug#6426). */
1473 SET_FRAME_GARBAGED (f);
1478 /* Free image cache of frame F. Be aware that X frames share images
1479 caches. */
1481 void
1482 free_image_cache (struct frame *f)
1484 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1485 if (c)
1487 ptrdiff_t i;
1489 /* Cache should not be referenced by any frame when freed. */
1490 eassert (c->refcount == 0);
1492 for (i = 0; i < c->used; ++i)
1493 free_image (f, c->images[i]);
1494 xfree (c->images);
1495 xfree (c->buckets);
1496 xfree (c);
1497 FRAME_IMAGE_CACHE (f) = NULL;
1502 /* Clear image cache of frame F. FILTER=t means free all images.
1503 FILTER=nil means clear only images that haven't been
1504 displayed for some time.
1505 Else, only free the images which have FILTER in their `dependencies'.
1506 Should be called from time to time to reduce the number of loaded images.
1507 If image-cache-eviction-delay is non-nil, this frees images in the cache
1508 which weren't displayed for at least that many seconds. */
1510 static void
1511 clear_image_cache (struct frame *f, Lisp_Object filter)
1513 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1515 if (c)
1517 ptrdiff_t i, nfreed = 0;
1519 /* Block input so that we won't be interrupted by a SIGIO
1520 while being in an inconsistent state. */
1521 block_input ();
1523 if (!NILP (filter))
1525 /* Filter image cache. */
1526 for (i = 0; i < c->used; ++i)
1528 struct image *img = c->images[i];
1529 if (img && (EQ (Qt, filter)
1530 || !NILP (Fmember (filter, img->dependencies))))
1532 free_image (f, img);
1533 ++nfreed;
1537 else if (INTEGERP (Vimage_cache_eviction_delay))
1539 /* Free cache based on timestamp. */
1540 struct timespec old, t;
1541 double delay;
1542 ptrdiff_t nimages = 0;
1544 for (i = 0; i < c->used; ++i)
1545 if (c->images[i])
1546 nimages++;
1548 /* If the number of cached images has grown unusually large,
1549 decrease the cache eviction delay (Bug#6230). */
1550 delay = XINT (Vimage_cache_eviction_delay);
1551 if (nimages > 40)
1552 delay = 1600 * delay / nimages / nimages;
1553 delay = max (delay, 1);
1555 t = current_timespec ();
1556 old = timespec_sub (t, dtotimespec (delay));
1558 for (i = 0; i < c->used; ++i)
1560 struct image *img = c->images[i];
1561 if (img && timespec_cmp (img->timestamp, old) < 0)
1563 free_image (f, img);
1564 ++nfreed;
1569 /* We may be clearing the image cache because, for example,
1570 Emacs was iconified for a longer period of time. In that
1571 case, current matrices may still contain references to
1572 images freed above. So, clear these matrices. */
1573 if (nfreed)
1575 Lisp_Object tail, frame;
1577 FOR_EACH_FRAME (tail, frame)
1579 struct frame *fr = XFRAME (frame);
1580 if (FRAME_IMAGE_CACHE (fr) == c)
1581 clear_current_matrices (fr);
1584 windows_or_buffers_changed = 19;
1587 unblock_input ();
1591 void
1592 clear_image_caches (Lisp_Object filter)
1594 /* FIXME: We want to do
1595 * struct terminal *t;
1596 * for (t = terminal_list; t; t = t->next_terminal)
1597 * clear_image_cache (t, filter); */
1598 Lisp_Object tail, frame;
1599 FOR_EACH_FRAME (tail, frame)
1600 if (FRAME_WINDOW_P (XFRAME (frame)))
1601 clear_image_cache (XFRAME (frame), filter);
1604 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1605 0, 1, 0,
1606 doc: /* Clear the image cache.
1607 FILTER nil or a frame means clear all images in the selected frame.
1608 FILTER t means clear the image caches of all frames.
1609 Anything else, means only clear those images which refer to FILTER,
1610 which is then usually a filename. */)
1611 (Lisp_Object filter)
1613 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1614 clear_image_caches (filter);
1615 else
1616 clear_image_cache (decode_window_system_frame (filter), Qt);
1618 return Qnil;
1622 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1623 1, 2, 0,
1624 doc: /* Flush the image with specification SPEC on frame FRAME.
1625 This removes the image from the Emacs image cache. If SPEC specifies
1626 an image file, the next redisplay of this image will read from the
1627 current contents of that file.
1629 FRAME nil or omitted means use the selected frame.
1630 FRAME t means refresh the image on all frames. */)
1631 (Lisp_Object spec, Lisp_Object frame)
1633 if (!valid_image_p (spec))
1634 error ("Invalid image specification");
1636 if (EQ (frame, Qt))
1638 Lisp_Object tail;
1639 FOR_EACH_FRAME (tail, frame)
1641 struct frame *f = XFRAME (frame);
1642 if (FRAME_WINDOW_P (f))
1643 uncache_image (f, spec);
1646 else
1647 uncache_image (decode_window_system_frame (frame), spec);
1649 return Qnil;
1653 /* Compute masks and transform image IMG on frame F, as specified
1654 by the image's specification, */
1656 static void
1657 postprocess_image (struct frame *f, struct image *img)
1659 /* Manipulation of the image's mask. */
1660 if (img->pixmap)
1662 Lisp_Object conversion, spec;
1663 Lisp_Object mask;
1665 spec = img->spec;
1667 /* `:heuristic-mask t'
1668 `:mask heuristic'
1669 means build a mask heuristically.
1670 `:heuristic-mask (R G B)'
1671 `:mask (heuristic (R G B))'
1672 means build a mask from color (R G B) in the
1673 image.
1674 `:mask nil'
1675 means remove a mask, if any. */
1677 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1678 if (!NILP (mask))
1679 x_build_heuristic_mask (f, img, mask);
1680 else
1682 bool found_p;
1684 mask = image_spec_value (spec, QCmask, &found_p);
1686 if (EQ (mask, Qheuristic))
1687 x_build_heuristic_mask (f, img, Qt);
1688 else if (CONSP (mask)
1689 && EQ (XCAR (mask), Qheuristic))
1691 if (CONSP (XCDR (mask)))
1692 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1693 else
1694 x_build_heuristic_mask (f, img, XCDR (mask));
1696 else if (NILP (mask) && found_p && img->mask)
1697 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1701 /* Should we apply an image transformation algorithm? */
1702 conversion = image_spec_value (spec, QCconversion, NULL);
1703 if (EQ (conversion, Qdisabled))
1704 x_disable_image (f, img);
1705 else if (EQ (conversion, Qlaplace))
1706 x_laplace (f, img);
1707 else if (EQ (conversion, Qemboss))
1708 x_emboss (f, img);
1709 else if (CONSP (conversion)
1710 && EQ (XCAR (conversion), Qedge_detection))
1712 Lisp_Object tem;
1713 tem = XCDR (conversion);
1714 if (CONSP (tem))
1715 x_edge_detection (f, img,
1716 Fplist_get (tem, QCmatrix),
1717 Fplist_get (tem, QCcolor_adjustment));
1723 /* Return the id of image with Lisp specification SPEC on frame F.
1724 SPEC must be a valid Lisp image specification (see valid_image_p). */
1726 ptrdiff_t
1727 lookup_image (struct frame *f, Lisp_Object spec)
1729 struct image *img;
1730 EMACS_UINT hash;
1732 /* F must be a window-system frame, and SPEC must be a valid image
1733 specification. */
1734 eassert (FRAME_WINDOW_P (f));
1735 eassert (valid_image_p (spec));
1737 /* Look up SPEC in the hash table of the image cache. */
1738 hash = sxhash (spec, 0);
1739 img = search_image_cache (f, spec, hash);
1740 if (img && img->load_failed_p)
1742 free_image (f, img);
1743 img = NULL;
1746 /* If not found, create a new image and cache it. */
1747 if (img == NULL)
1749 block_input ();
1750 img = make_image (spec, hash);
1751 cache_image (f, img);
1752 img->load_failed_p = ! img->type->load (f, img);
1753 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1754 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1756 /* If we can't load the image, and we don't have a width and
1757 height, use some arbitrary width and height so that we can
1758 draw a rectangle for it. */
1759 if (img->load_failed_p)
1761 Lisp_Object value;
1763 value = image_spec_value (spec, QCwidth, NULL);
1764 img->width = (INTEGERP (value)
1765 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1766 value = image_spec_value (spec, QCheight, NULL);
1767 img->height = (INTEGERP (value)
1768 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1770 else
1772 /* Handle image type independent image attributes
1773 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1774 `:background COLOR'. */
1775 Lisp_Object ascent, margin, relief, bg;
1776 int relief_bound;
1778 ascent = image_spec_value (spec, QCascent, NULL);
1779 if (INTEGERP (ascent))
1780 img->ascent = XFASTINT (ascent);
1781 else if (EQ (ascent, Qcenter))
1782 img->ascent = CENTERED_IMAGE_ASCENT;
1784 margin = image_spec_value (spec, QCmargin, NULL);
1785 if (INTEGERP (margin))
1786 img->vmargin = img->hmargin = XFASTINT (margin);
1787 else if (CONSP (margin))
1789 img->hmargin = XFASTINT (XCAR (margin));
1790 img->vmargin = XFASTINT (XCDR (margin));
1793 relief = image_spec_value (spec, QCrelief, NULL);
1794 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1795 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1797 img->relief = XINT (relief);
1798 img->hmargin += eabs (img->relief);
1799 img->vmargin += eabs (img->relief);
1802 if (! img->background_valid)
1804 bg = image_spec_value (img->spec, QCbackground, NULL);
1805 if (!NILP (bg))
1807 img->background
1808 = x_alloc_image_color (f, img, bg,
1809 FRAME_BACKGROUND_PIXEL (f));
1810 img->background_valid = 1;
1814 /* Do image transformations and compute masks, unless we
1815 don't have the image yet. */
1816 if (!EQ (builtin_lisp_symbol (img->type->type), Qpostscript))
1817 postprocess_image (f, img);
1820 unblock_input ();
1823 /* We're using IMG, so set its timestamp to `now'. */
1824 img->timestamp = current_timespec ();
1826 /* Value is the image id. */
1827 return img->id;
1831 /* Cache image IMG in the image cache of frame F. */
1833 static void
1834 cache_image (struct frame *f, struct image *img)
1836 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1837 ptrdiff_t i;
1839 if (!c)
1840 c = FRAME_IMAGE_CACHE (f) = make_image_cache ();
1842 /* Find a free slot in c->images. */
1843 for (i = 0; i < c->used; ++i)
1844 if (c->images[i] == NULL)
1845 break;
1847 /* If no free slot found, maybe enlarge c->images. */
1848 if (i == c->used && c->used == c->size)
1849 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1851 /* Add IMG to c->images, and assign IMG an id. */
1852 c->images[i] = img;
1853 img->id = i;
1854 if (i == c->used)
1855 ++c->used;
1857 /* Add IMG to the cache's hash table. */
1858 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1859 img->next = c->buckets[i];
1860 if (img->next)
1861 img->next->prev = img;
1862 img->prev = NULL;
1863 c->buckets[i] = img;
1867 /* Call FN on every image in the image cache of frame F. Used to mark
1868 Lisp Objects in the image cache. */
1870 /* Mark Lisp objects in image IMG. */
1872 static void
1873 mark_image (struct image *img)
1875 mark_object (img->spec);
1876 mark_object (img->dependencies);
1878 if (!NILP (img->lisp_data))
1879 mark_object (img->lisp_data);
1883 void
1884 mark_image_cache (struct image_cache *c)
1886 if (c)
1888 ptrdiff_t i;
1889 for (i = 0; i < c->used; ++i)
1890 if (c->images[i])
1891 mark_image (c->images[i]);
1897 /***********************************************************************
1898 X / NS / W32 support code
1899 ***********************************************************************/
1901 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1902 windowing system.
1903 WIDTH and HEIGHT must both be positive.
1904 If XIMG is null, assume it is a bitmap. */
1905 static bool
1906 x_check_image_size (XImagePtr ximg, int width, int height)
1908 #ifdef HAVE_X_WINDOWS
1909 /* Respect Xlib's limits: it cannot deal with images that have more
1910 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1911 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1912 enum
1914 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1915 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1918 int bitmap_pad, depth, bytes_per_line;
1919 if (ximg)
1921 bitmap_pad = ximg->bitmap_pad;
1922 depth = ximg->depth;
1923 bytes_per_line = ximg->bytes_per_line;
1925 else
1927 bitmap_pad = 8;
1928 depth = 1;
1929 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1931 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1932 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1933 #else
1934 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1935 For now, assume that every image size is allowed on these systems. */
1936 return 1;
1937 #endif
1940 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1941 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1942 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1943 via xmalloc. Print error messages via image_error if an error
1944 occurs. Value is true if successful.
1946 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1947 should indicate the bit depth of the image. */
1949 static bool
1950 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1951 XImagePtr *ximg, Pixmap *pixmap)
1953 #ifdef HAVE_X_WINDOWS
1954 Display *display = FRAME_X_DISPLAY (f);
1955 Window window = FRAME_X_WINDOW (f);
1956 Screen *screen = FRAME_X_SCREEN (f);
1958 eassert (input_blocked_p ());
1960 if (depth <= 0)
1961 depth = DefaultDepthOfScreen (screen);
1962 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1963 depth, ZPixmap, 0, NULL, width, height,
1964 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1965 if (*ximg == NULL)
1967 image_error ("Unable to allocate X image");
1968 return 0;
1971 if (! x_check_image_size (*ximg, width, height))
1973 x_destroy_x_image (*ximg);
1974 *ximg = NULL;
1975 image_error ("Image too large (%dx%d)",
1976 make_number (width), make_number (height));
1977 return 0;
1980 /* Allocate image raster. */
1981 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1983 /* Allocate a pixmap of the same size. */
1984 *pixmap = XCreatePixmap (display, window, width, height, depth);
1985 if (*pixmap == NO_PIXMAP)
1987 x_destroy_x_image (*ximg);
1988 *ximg = NULL;
1989 image_error ("Unable to create X pixmap");
1990 return 0;
1993 return 1;
1994 #endif /* HAVE_X_WINDOWS */
1996 #ifdef HAVE_NTGUI
1998 BITMAPINFOHEADER *header;
1999 HDC hdc;
2000 int scanline_width_bits;
2001 int remainder;
2002 int palette_colors = 0;
2004 if (depth == 0)
2005 depth = 24;
2007 if (depth != 1 && depth != 4 && depth != 8
2008 && depth != 16 && depth != 24 && depth != 32)
2010 image_error ("Invalid image bit depth specified");
2011 return 0;
2014 scanline_width_bits = width * depth;
2015 remainder = scanline_width_bits % 32;
2017 if (remainder)
2018 scanline_width_bits += 32 - remainder;
2020 /* Bitmaps with a depth less than 16 need a palette. */
2021 /* BITMAPINFO structure already contains the first RGBQUAD. */
2022 if (depth < 16)
2023 palette_colors = 1 << (depth - 1);
2025 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2027 header = &(*ximg)->info.bmiHeader;
2028 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2029 header->biSize = sizeof (*header);
2030 header->biWidth = width;
2031 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2032 header->biPlanes = 1;
2033 header->biBitCount = depth;
2034 header->biCompression = BI_RGB;
2035 header->biClrUsed = palette_colors;
2037 /* TODO: fill in palette. */
2038 if (depth == 1)
2040 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2041 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2042 (*ximg)->info.bmiColors[0].rgbRed = 0;
2043 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2044 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2045 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2046 (*ximg)->info.bmiColors[1].rgbRed = 255;
2047 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2050 hdc = get_frame_dc (f);
2052 /* Create a DIBSection and raster array for the bitmap,
2053 and store its handle in *pixmap. */
2054 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2055 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2056 /* casting avoids a GCC warning */
2057 (void **)&((*ximg)->data), NULL, 0);
2059 /* Realize display palette and garbage all frames. */
2060 release_frame_dc (f, hdc);
2062 if (*pixmap == NULL)
2064 DWORD err = GetLastError ();
2065 Lisp_Object errcode;
2066 /* All system errors are < 10000, so the following is safe. */
2067 XSETINT (errcode, err);
2068 image_error ("Unable to create bitmap, error code %d", errcode);
2069 x_destroy_x_image (*ximg);
2070 *ximg = NULL;
2071 return 0;
2074 return 1;
2076 #endif /* HAVE_NTGUI */
2078 #ifdef HAVE_NS
2079 *pixmap = ns_image_for_XPM (width, height, depth);
2080 if (*pixmap == 0)
2082 *ximg = NULL;
2083 image_error ("Unable to allocate NSImage for XPM pixmap");
2084 return 0;
2086 *ximg = *pixmap;
2087 return 1;
2088 #endif
2092 /* Destroy XImage XIMG. Free XIMG->data. */
2094 static void
2095 x_destroy_x_image (XImagePtr ximg)
2097 eassert (input_blocked_p ());
2098 if (ximg)
2100 #ifdef HAVE_X_WINDOWS
2101 xfree (ximg->data);
2102 ximg->data = NULL;
2103 XDestroyImage (ximg);
2104 #endif /* HAVE_X_WINDOWS */
2105 #ifdef HAVE_NTGUI
2106 /* Data will be freed by DestroyObject. */
2107 ximg->data = NULL;
2108 xfree (ximg);
2109 #endif /* HAVE_NTGUI */
2110 #ifdef HAVE_NS
2111 ns_release_object (ximg);
2112 #endif /* HAVE_NS */
2117 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2118 are width and height of both the image and pixmap. */
2120 static void
2121 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2123 #ifdef HAVE_X_WINDOWS
2124 GC gc;
2126 eassert (input_blocked_p ());
2127 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2128 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2129 XFreeGC (FRAME_X_DISPLAY (f), gc);
2130 #endif /* HAVE_X_WINDOWS */
2132 #ifdef HAVE_NTGUI
2133 #if 0 /* I don't think this is necessary looking at where it is used. */
2134 HDC hdc = get_frame_dc (f);
2135 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2136 release_frame_dc (f, hdc);
2137 #endif
2138 #endif /* HAVE_NTGUI */
2140 #ifdef HAVE_NS
2141 eassert (ximg == pixmap);
2142 ns_retain_object (ximg);
2143 #endif
2146 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2147 with image_put_x_image. */
2149 static bool
2150 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2151 int width, int height, int depth,
2152 XImagePtr *ximg, bool mask_p)
2154 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2156 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2157 !mask_p ? &img->pixmap : &img->mask);
2160 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2161 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2162 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2163 On the other platforms, it puts XIMG into the pixmap, then frees
2164 the X image and its buffer. */
2166 static void
2167 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2168 bool mask_p)
2170 #ifdef HAVE_X_WINDOWS
2171 if (!mask_p)
2173 eassert (img->ximg == NULL);
2174 img->ximg = ximg;
2176 else
2178 eassert (img->mask_img == NULL);
2179 img->mask_img = ximg;
2181 #else
2182 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2183 img->width, img->height);
2184 x_destroy_x_image (ximg);
2185 #endif
2188 #ifdef HAVE_X_WINDOWS
2189 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2190 the X images and their buffers. */
2192 static void
2193 image_sync_to_pixmaps (struct frame *f, struct image *img)
2195 if (img->ximg)
2197 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2198 x_destroy_x_image (img->ximg);
2199 img->ximg = NULL;
2201 if (img->mask_img)
2203 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2204 x_destroy_x_image (img->mask_img);
2205 img->mask_img = NULL;
2208 #endif
2210 #ifdef HAVE_NTGUI
2211 /* Create a memory device context for IMG on frame F. It stores the
2212 currently selected GDI object into *PREV for future restoration by
2213 image_unget_x_image_or_dc. */
2215 static XImagePtr_or_DC
2216 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2217 HGDIOBJ *prev)
2219 HDC frame_dc = get_frame_dc (f);
2220 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2222 release_frame_dc (f, frame_dc);
2223 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2225 return ximg;
2228 static void
2229 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2230 XImagePtr_or_DC ximg, HGDIOBJ prev)
2232 SelectObject (ximg, prev);
2233 DeleteDC (ximg);
2235 #else /* !HAVE_NTGUI */
2236 /* Get the X image for IMG on frame F. The resulting X image data
2237 should be treated as read-only at least on X. */
2239 static XImagePtr
2240 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2242 #ifdef HAVE_X_WINDOWS
2243 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2245 if (ximg_in_img)
2246 return ximg_in_img;
2247 else
2248 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2249 0, 0, img->width, img->height, ~0, ZPixmap);
2250 #elif defined (HAVE_NS)
2251 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2253 ns_retain_object (pixmap);
2254 return pixmap;
2255 #endif
2258 static void
2259 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2261 #ifdef HAVE_X_WINDOWS
2262 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2264 if (ximg_in_img)
2265 eassert (ximg == ximg_in_img);
2266 else
2267 XDestroyImage (ximg);
2268 #elif defined (HAVE_NS)
2269 ns_release_object (ximg);
2270 #endif
2272 #endif /* !HAVE_NTGUI */
2275 /***********************************************************************
2276 File Handling
2277 ***********************************************************************/
2279 /* Find image file FILE. Look in data-directory/images, then
2280 x-bitmap-file-path. Value is the full name of the file
2281 found, or nil if not found. If PFD is nonnull store into *PFD a
2282 readable file descriptor for the file, opened in binary mode. If
2283 PFD is null, do not open the file. */
2285 static Lisp_Object
2286 x_find_image_fd (Lisp_Object file, int *pfd)
2288 Lisp_Object file_found, search_path;
2289 int fd;
2291 /* TODO I think this should use something like image-load-path
2292 instead. Unfortunately, that can contain non-string elements. */
2293 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2294 Vdata_directory),
2295 Vx_bitmap_file_path);
2297 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2298 fd = openp (search_path, file, Qnil, &file_found,
2299 pfd ? Qt : make_number (R_OK), false);
2300 if (fd >= 0 || fd == -2)
2302 file_found = ENCODE_FILE (file_found);
2303 if (fd == -2)
2305 /* The file exists locally, but has a file handler. (This
2306 happens, e.g., under Auto Image File Mode.) 'openp'
2307 didn't open the file, so we should, because the caller
2308 expects that. */
2309 fd = emacs_open (SSDATA (file_found), O_RDONLY, 0);
2312 else /* fd < 0, but not -2 */
2313 return Qnil;
2314 if (pfd)
2315 *pfd = fd;
2316 return file_found;
2319 /* Find image file FILE. Look in data-directory/images, then
2320 x-bitmap-file-path. Value is the encoded full name of the file
2321 found, or nil if not found. */
2323 Lisp_Object
2324 x_find_image_file (Lisp_Object file)
2326 return x_find_image_fd (file, 0);
2329 /* Read FILE into memory. Value is a pointer to a buffer allocated
2330 with xmalloc holding FILE's contents. Value is null if an error
2331 occurred. FD is a file descriptor open for reading FILE. Set
2332 *SIZE to the size of the file. */
2334 static char *
2335 slurp_file (int fd, ptrdiff_t *size)
2337 FILE *fp = fdopen (fd, "rb");
2339 char *buf = NULL;
2340 struct stat st;
2342 if (fp)
2344 ptrdiff_t count = SPECPDL_INDEX ();
2345 record_unwind_protect_ptr (fclose_unwind, fp);
2347 if (fstat (fileno (fp), &st) == 0
2348 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2350 /* Report an error if we read past the purported EOF.
2351 This can happen if the file grows as we read it. */
2352 ptrdiff_t buflen = st.st_size;
2353 buf = xmalloc (buflen + 1);
2354 if (fread (buf, 1, buflen + 1, fp) == buflen)
2355 *size = buflen;
2356 else
2358 xfree (buf);
2359 buf = NULL;
2363 unbind_to (count, Qnil);
2366 return buf;
2371 /***********************************************************************
2372 XBM images
2373 ***********************************************************************/
2375 static bool xbm_load (struct frame *f, struct image *img);
2376 static bool xbm_image_p (Lisp_Object object);
2377 static bool xbm_file_p (Lisp_Object);
2380 /* Indices of image specification fields in xbm_format, below. */
2382 enum xbm_keyword_index
2384 XBM_TYPE,
2385 XBM_FILE,
2386 XBM_WIDTH,
2387 XBM_HEIGHT,
2388 XBM_DATA,
2389 XBM_FOREGROUND,
2390 XBM_BACKGROUND,
2391 XBM_ASCENT,
2392 XBM_MARGIN,
2393 XBM_RELIEF,
2394 XBM_ALGORITHM,
2395 XBM_HEURISTIC_MASK,
2396 XBM_MASK,
2397 XBM_LAST
2400 /* Vector of image_keyword structures describing the format
2401 of valid XBM image specifications. */
2403 static const struct image_keyword xbm_format[XBM_LAST] =
2405 {":type", IMAGE_SYMBOL_VALUE, 1},
2406 {":file", IMAGE_STRING_VALUE, 0},
2407 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2408 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2409 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2410 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2411 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2412 {":ascent", IMAGE_ASCENT_VALUE, 0},
2413 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2414 {":relief", IMAGE_INTEGER_VALUE, 0},
2415 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2416 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2417 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2420 /* Structure describing the image type XBM. */
2422 static struct image_type xbm_type =
2424 SYMBOL_INDEX (Qxbm),
2425 xbm_image_p,
2426 xbm_load,
2427 x_clear_image,
2428 NULL,
2429 NULL
2432 /* Tokens returned from xbm_scan. */
2434 enum xbm_token
2436 XBM_TK_IDENT = 256,
2437 XBM_TK_NUMBER
2441 /* Return true if OBJECT is a valid XBM-type image specification.
2442 A valid specification is a list starting with the symbol `image'
2443 The rest of the list is a property list which must contain an
2444 entry `:type xbm'.
2446 If the specification specifies a file to load, it must contain
2447 an entry `:file FILENAME' where FILENAME is a string.
2449 If the specification is for a bitmap loaded from memory it must
2450 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2451 WIDTH and HEIGHT are integers > 0. DATA may be:
2453 1. a string large enough to hold the bitmap data, i.e. it must
2454 have a size >= (WIDTH + 7) / 8 * HEIGHT
2456 2. a bool-vector of size >= WIDTH * HEIGHT
2458 3. a vector of strings or bool-vectors, one for each line of the
2459 bitmap.
2461 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2462 may not be specified in this case because they are defined in the
2463 XBM file.
2465 Both the file and data forms may contain the additional entries
2466 `:background COLOR' and `:foreground COLOR'. If not present,
2467 foreground and background of the frame on which the image is
2468 displayed is used. */
2470 static bool
2471 xbm_image_p (Lisp_Object object)
2473 struct image_keyword kw[XBM_LAST];
2475 memcpy (kw, xbm_format, sizeof kw);
2476 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2477 return 0;
2479 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2481 if (kw[XBM_FILE].count)
2483 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2484 return 0;
2486 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2488 /* In-memory XBM file. */
2489 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2490 return 0;
2492 else
2494 Lisp_Object data;
2495 int width, height;
2497 /* Entries for `:width', `:height' and `:data' must be present. */
2498 if (!kw[XBM_WIDTH].count
2499 || !kw[XBM_HEIGHT].count
2500 || !kw[XBM_DATA].count)
2501 return 0;
2503 data = kw[XBM_DATA].value;
2504 width = XFASTINT (kw[XBM_WIDTH].value);
2505 height = XFASTINT (kw[XBM_HEIGHT].value);
2507 /* Check type of data, and width and height against contents of
2508 data. */
2509 if (VECTORP (data))
2511 EMACS_INT i;
2513 /* Number of elements of the vector must be >= height. */
2514 if (ASIZE (data) < height)
2515 return 0;
2517 /* Each string or bool-vector in data must be large enough
2518 for one line of the image. */
2519 for (i = 0; i < height; ++i)
2521 Lisp_Object elt = AREF (data, i);
2523 if (STRINGP (elt))
2525 if (SCHARS (elt)
2526 < (width + CHAR_BIT - 1) / CHAR_BIT)
2527 return 0;
2529 else if (BOOL_VECTOR_P (elt))
2531 if (bool_vector_size (elt) < width)
2532 return 0;
2534 else
2535 return 0;
2538 else if (STRINGP (data))
2540 if (SCHARS (data)
2541 < (width + CHAR_BIT - 1) / CHAR_BIT * height)
2542 return 0;
2544 else if (BOOL_VECTOR_P (data))
2546 if (bool_vector_size (data) / height < width)
2547 return 0;
2549 else
2550 return 0;
2553 return 1;
2557 /* Scan a bitmap file. FP is the stream to read from. Value is
2558 either an enumerator from enum xbm_token, or a character for a
2559 single-character token, or 0 at end of file. If scanning an
2560 identifier, store the lexeme of the identifier in SVAL. If
2561 scanning a number, store its value in *IVAL. */
2563 static int
2564 xbm_scan (char **s, char *end, char *sval, int *ival)
2566 unsigned char c;
2568 loop:
2570 /* Skip white space. */
2571 while (*s < end && (c = *(*s)++, c_isspace (c)))
2574 if (*s >= end)
2575 c = 0;
2576 else if (c_isdigit (c))
2578 int value = 0, digit;
2580 if (c == '0' && *s < end)
2582 c = *(*s)++;
2583 if (c == 'x' || c == 'X')
2585 while (*s < end)
2587 c = *(*s)++;
2588 if (c_isdigit (c))
2589 digit = c - '0';
2590 else if (c >= 'a' && c <= 'f')
2591 digit = c - 'a' + 10;
2592 else if (c >= 'A' && c <= 'F')
2593 digit = c - 'A' + 10;
2594 else
2595 break;
2596 value = 16 * value + digit;
2599 else if (c_isdigit (c))
2601 value = c - '0';
2602 while (*s < end
2603 && (c = *(*s)++, c_isdigit (c)))
2604 value = 8 * value + c - '0';
2607 else
2609 value = c - '0';
2610 while (*s < end
2611 && (c = *(*s)++, c_isdigit (c)))
2612 value = 10 * value + c - '0';
2615 if (*s < end)
2616 *s = *s - 1;
2617 *ival = value;
2618 return XBM_TK_NUMBER;
2620 else if (c_isalpha (c) || c == '_')
2622 *sval++ = c;
2623 while (*s < end
2624 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2625 *sval++ = c;
2626 *sval = 0;
2627 if (*s < end)
2628 *s = *s - 1;
2629 return XBM_TK_IDENT;
2631 else if (c == '/' && **s == '*')
2633 /* C-style comment. */
2634 ++*s;
2635 while (**s && (**s != '*' || *(*s + 1) != '/'))
2636 ++*s;
2637 if (**s)
2639 *s += 2;
2640 goto loop;
2644 return c;
2647 #ifdef HAVE_NTGUI
2649 /* Create a Windows bitmap from X bitmap data. */
2650 static HBITMAP
2651 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2653 static unsigned char swap_nibble[16]
2654 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2655 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2656 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2657 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2658 int i, j, w1, w2;
2659 unsigned char *bits, *p;
2660 HBITMAP bmp;
2662 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2663 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2664 bits = alloca (height * w2);
2665 memset (bits, 0, height * w2);
2666 for (i = 0; i < height; i++)
2668 p = bits + i*w2;
2669 for (j = 0; j < w1; j++)
2671 /* Bitswap XBM bytes to match how Windows does things. */
2672 unsigned char c = *data++;
2673 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2674 | (swap_nibble[(c>>4) & 0xf]));
2677 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2679 return bmp;
2682 static void
2683 convert_mono_to_color_image (struct frame *f, struct image *img,
2684 COLORREF foreground, COLORREF background)
2686 HDC hdc, old_img_dc, new_img_dc;
2687 HGDIOBJ old_prev, new_prev;
2688 HBITMAP new_pixmap;
2690 hdc = get_frame_dc (f);
2691 old_img_dc = CreateCompatibleDC (hdc);
2692 new_img_dc = CreateCompatibleDC (hdc);
2693 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2694 release_frame_dc (f, hdc);
2695 old_prev = SelectObject (old_img_dc, img->pixmap);
2696 new_prev = SelectObject (new_img_dc, new_pixmap);
2697 /* Windows convention for mono bitmaps is black = background,
2698 white = foreground. */
2699 SetTextColor (new_img_dc, background);
2700 SetBkColor (new_img_dc, foreground);
2702 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2703 0, 0, SRCCOPY);
2705 SelectObject (old_img_dc, old_prev);
2706 SelectObject (new_img_dc, new_prev);
2707 DeleteDC (old_img_dc);
2708 DeleteDC (new_img_dc);
2709 DeleteObject (img->pixmap);
2710 if (new_pixmap == 0)
2711 fprintf (stderr, "Failed to convert image to color.\n");
2712 else
2713 img->pixmap = new_pixmap;
2716 #define XBM_BIT_SHUFFLE(b) (~(b))
2718 #else
2720 #define XBM_BIT_SHUFFLE(b) (b)
2722 #endif /* HAVE_NTGUI */
2725 static void
2726 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2727 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2728 bool non_default_colors)
2730 #ifdef HAVE_NTGUI
2731 img->pixmap
2732 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2734 /* If colors were specified, transfer the bitmap to a color one. */
2735 if (non_default_colors)
2736 convert_mono_to_color_image (f, img, fg, bg);
2738 #elif defined (HAVE_NS)
2739 img->pixmap = ns_image_from_XBM (data, img->width, img->height, fg, bg);
2741 #else
2742 img->pixmap =
2743 (x_check_image_size (0, img->width, img->height)
2744 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2745 FRAME_X_WINDOW (f),
2746 data,
2747 img->width, img->height,
2748 fg, bg,
2749 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2750 : NO_PIXMAP);
2751 #endif /* !HAVE_NTGUI && !HAVE_NS */
2756 /* Replacement for XReadBitmapFileData which isn't available under old
2757 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2758 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2759 the image. Return in *DATA the bitmap data allocated with xmalloc.
2760 Value is true if successful. DATA null means just test if
2761 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2762 inhibit the call to image_error when the image size is invalid (the
2763 bitmap remains unread). */
2765 static bool
2766 xbm_read_bitmap_data (struct frame *f, char *contents, char *end,
2767 int *width, int *height, char **data,
2768 bool inhibit_image_error)
2770 char *s = contents;
2771 char buffer[BUFSIZ];
2772 bool padding_p = 0;
2773 bool v10 = 0;
2774 int bytes_per_line, i, nbytes;
2775 char *p;
2776 int value;
2777 int LA1;
2779 #define match() \
2780 LA1 = xbm_scan (&s, end, buffer, &value)
2782 #define expect(TOKEN) \
2783 do \
2785 if (LA1 != (TOKEN)) \
2786 goto failure; \
2787 match (); \
2789 while (0)
2791 #define expect_ident(IDENT) \
2792 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2793 match (); \
2794 else \
2795 goto failure
2797 *width = *height = -1;
2798 if (data)
2799 *data = NULL;
2800 LA1 = xbm_scan (&s, end, buffer, &value);
2802 /* Parse defines for width, height and hot-spots. */
2803 while (LA1 == '#')
2805 match ();
2806 expect_ident ("define");
2807 expect (XBM_TK_IDENT);
2809 if (LA1 == XBM_TK_NUMBER)
2811 char *q = strrchr (buffer, '_');
2812 q = q ? q + 1 : buffer;
2813 if (strcmp (q, "width") == 0)
2814 *width = value;
2815 else if (strcmp (q, "height") == 0)
2816 *height = value;
2818 expect (XBM_TK_NUMBER);
2821 if (!check_image_size (f, *width, *height))
2823 if (!inhibit_image_error)
2824 image_size_error ();
2825 goto failure;
2827 else if (data == NULL)
2828 goto success;
2830 /* Parse bits. Must start with `static'. */
2831 expect_ident ("static");
2832 if (LA1 == XBM_TK_IDENT)
2834 if (strcmp (buffer, "unsigned") == 0)
2836 match ();
2837 expect_ident ("char");
2839 else if (strcmp (buffer, "short") == 0)
2841 match ();
2842 v10 = 1;
2843 if (*width % 16 && *width % 16 < 9)
2844 padding_p = 1;
2846 else if (strcmp (buffer, "char") == 0)
2847 match ();
2848 else
2849 goto failure;
2851 else
2852 goto failure;
2854 expect (XBM_TK_IDENT);
2855 expect ('[');
2856 expect (']');
2857 expect ('=');
2858 expect ('{');
2860 if (! x_check_image_size (0, *width, *height))
2862 if (!inhibit_image_error)
2863 image_error ("Image too large (%dx%d)",
2864 make_number (*width), make_number (*height));
2865 goto failure;
2867 bytes_per_line = (*width + 7) / 8 + padding_p;
2868 nbytes = bytes_per_line * *height;
2869 p = *data = xmalloc (nbytes);
2871 if (v10)
2873 for (i = 0; i < nbytes; i += 2)
2875 int val = value;
2876 expect (XBM_TK_NUMBER);
2878 *p++ = XBM_BIT_SHUFFLE (val);
2879 if (!padding_p || ((i + 2) % bytes_per_line))
2880 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2882 if (LA1 == ',' || LA1 == '}')
2883 match ();
2884 else
2885 goto failure;
2888 else
2890 for (i = 0; i < nbytes; ++i)
2892 int val = value;
2893 expect (XBM_TK_NUMBER);
2895 *p++ = XBM_BIT_SHUFFLE (val);
2897 if (LA1 == ',' || LA1 == '}')
2898 match ();
2899 else
2900 goto failure;
2904 success:
2905 return 1;
2907 failure:
2909 if (data && *data)
2911 xfree (*data);
2912 *data = NULL;
2914 return 0;
2916 #undef match
2917 #undef expect
2918 #undef expect_ident
2922 /* Load XBM image IMG which will be displayed on frame F from buffer
2923 CONTENTS. END is the end of the buffer. Value is true if
2924 successful. */
2926 static bool
2927 xbm_load_image (struct frame *f, struct image *img, char *contents, char *end)
2929 bool rc;
2930 char *data;
2931 bool success_p = 0;
2933 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2934 &data, 0);
2935 if (rc)
2937 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2938 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2939 bool non_default_colors = 0;
2940 Lisp_Object value;
2942 eassert (img->width > 0 && img->height > 0);
2944 /* Get foreground and background colors, maybe allocate colors. */
2945 value = image_spec_value (img->spec, QCforeground, NULL);
2946 if (!NILP (value))
2948 foreground = x_alloc_image_color (f, img, value, foreground);
2949 non_default_colors = 1;
2951 value = image_spec_value (img->spec, QCbackground, NULL);
2952 if (!NILP (value))
2954 background = x_alloc_image_color (f, img, value, background);
2955 img->background = background;
2956 img->background_valid = 1;
2957 non_default_colors = 1;
2960 Create_Pixmap_From_Bitmap_Data (f, img, data,
2961 foreground, background,
2962 non_default_colors);
2963 xfree (data);
2965 if (img->pixmap == NO_PIXMAP)
2967 x_clear_image (f, img);
2968 image_error ("Unable to create X pixmap for `%s'", img->spec);
2970 else
2971 success_p = 1;
2973 else
2974 image_error ("Error loading XBM image `%s'", img->spec);
2976 return success_p;
2980 /* Value is true if DATA looks like an in-memory XBM file. */
2982 static bool
2983 xbm_file_p (Lisp_Object data)
2985 int w, h;
2986 return (STRINGP (data)
2987 && xbm_read_bitmap_data (NULL, SSDATA (data),
2988 SSDATA (data) + SBYTES (data),
2989 &w, &h, NULL, 1));
2993 /* Fill image IMG which is used on frame F with pixmap data. Value is
2994 true if successful. */
2996 static bool
2997 xbm_load (struct frame *f, struct image *img)
2999 bool success_p = 0;
3000 Lisp_Object file_name;
3002 eassert (xbm_image_p (img->spec));
3004 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3005 file_name = image_spec_value (img->spec, QCfile, NULL);
3006 if (STRINGP (file_name))
3008 int fd;
3009 Lisp_Object file = x_find_image_fd (file_name, &fd);
3010 if (!STRINGP (file))
3012 image_error ("Cannot find image file `%s'", file_name);
3013 return 0;
3016 ptrdiff_t size;
3017 char *contents = slurp_file (fd, &size);
3018 if (contents == NULL)
3020 image_error ("Error loading XBM image `%s'", file);
3021 return 0;
3024 success_p = xbm_load_image (f, img, contents, contents + size);
3025 xfree (contents);
3027 else
3029 struct image_keyword fmt[XBM_LAST];
3030 Lisp_Object data;
3031 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3032 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3033 bool non_default_colors = 0;
3034 char *bits;
3035 bool parsed_p;
3036 bool in_memory_file_p = 0;
3038 /* See if data looks like an in-memory XBM file. */
3039 data = image_spec_value (img->spec, QCdata, NULL);
3040 in_memory_file_p = xbm_file_p (data);
3042 /* Parse the image specification. */
3043 memcpy (fmt, xbm_format, sizeof fmt);
3044 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3045 eassert (parsed_p);
3047 /* Get specified width, and height. */
3048 if (!in_memory_file_p)
3050 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3051 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3052 eassert (img->width > 0 && img->height > 0);
3053 if (!check_image_size (f, img->width, img->height))
3055 image_size_error ();
3056 return 0;
3060 /* Get foreground and background colors, maybe allocate colors. */
3061 if (fmt[XBM_FOREGROUND].count
3062 && STRINGP (fmt[XBM_FOREGROUND].value))
3064 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3065 foreground);
3066 non_default_colors = 1;
3069 if (fmt[XBM_BACKGROUND].count
3070 && STRINGP (fmt[XBM_BACKGROUND].value))
3072 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3073 background);
3074 non_default_colors = 1;
3077 if (in_memory_file_p)
3078 success_p = xbm_load_image (f, img, SSDATA (data),
3079 SSDATA (data) + SBYTES (data));
3080 else
3082 USE_SAFE_ALLOCA;
3084 if (VECTORP (data))
3086 int i;
3087 char *p;
3088 int nbytes = (img->width + CHAR_BIT - 1) / CHAR_BIT;
3090 SAFE_NALLOCA (bits, nbytes, img->height);
3091 p = bits;
3092 for (i = 0; i < img->height; ++i, p += nbytes)
3094 Lisp_Object line = AREF (data, i);
3095 if (STRINGP (line))
3096 memcpy (p, SDATA (line), nbytes);
3097 else
3098 memcpy (p, bool_vector_data (line), nbytes);
3101 else if (STRINGP (data))
3102 bits = SSDATA (data);
3103 else
3104 bits = (char *) bool_vector_data (data);
3106 #ifdef HAVE_NTGUI
3108 char *invertedBits;
3109 int nbytes, i;
3110 /* Windows mono bitmaps are reversed compared with X. */
3111 invertedBits = bits;
3112 nbytes = (img->width + CHAR_BIT - 1) / CHAR_BIT;
3113 SAFE_NALLOCA (bits, nbytes, img->height);
3114 for (i = 0; i < nbytes; i++)
3115 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3117 #endif
3118 /* Create the pixmap. */
3120 if (x_check_image_size (0, img->width, img->height))
3121 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3122 foreground, background,
3123 non_default_colors);
3124 else
3125 img->pixmap = NO_PIXMAP;
3127 if (img->pixmap)
3128 success_p = 1;
3129 else
3131 image_error ("Unable to create pixmap for XBM image `%s'",
3132 img->spec);
3133 x_clear_image (f, img);
3136 SAFE_FREE ();
3140 return success_p;
3145 /***********************************************************************
3146 XPM images
3147 ***********************************************************************/
3149 #if defined (HAVE_XPM) || defined (HAVE_NS)
3151 static bool xpm_image_p (Lisp_Object object);
3152 static bool xpm_load (struct frame *f, struct image *img);
3154 #endif /* HAVE_XPM || HAVE_NS */
3156 #ifdef HAVE_XPM
3157 #ifdef HAVE_NTGUI
3158 /* Indicate to xpm.h that we don't have Xlib. */
3159 #define FOR_MSW
3160 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3161 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3162 #define XColor xpm_XColor
3163 #define XImage xpm_XImage
3164 #define Display xpm_Display
3165 #ifdef CYGWIN
3166 #include "noX/xpm.h"
3167 #else /* not CYGWIN */
3168 #include "X11/xpm.h"
3169 #endif /* not CYGWIN */
3170 #undef FOR_MSW
3171 #undef XColor
3172 #undef XImage
3173 #undef Display
3174 #else /* not HAVE_NTGUI */
3175 #include "X11/xpm.h"
3176 #endif /* not HAVE_NTGUI */
3177 #endif /* HAVE_XPM */
3179 #if defined (HAVE_XPM) || defined (HAVE_NS)
3181 /* Indices of image specification fields in xpm_format, below. */
3183 enum xpm_keyword_index
3185 XPM_TYPE,
3186 XPM_FILE,
3187 XPM_DATA,
3188 XPM_ASCENT,
3189 XPM_MARGIN,
3190 XPM_RELIEF,
3191 XPM_ALGORITHM,
3192 XPM_HEURISTIC_MASK,
3193 XPM_MASK,
3194 XPM_COLOR_SYMBOLS,
3195 XPM_BACKGROUND,
3196 XPM_LAST
3199 /* Vector of image_keyword structures describing the format
3200 of valid XPM image specifications. */
3202 static const struct image_keyword xpm_format[XPM_LAST] =
3204 {":type", IMAGE_SYMBOL_VALUE, 1},
3205 {":file", IMAGE_STRING_VALUE, 0},
3206 {":data", IMAGE_STRING_VALUE, 0},
3207 {":ascent", IMAGE_ASCENT_VALUE, 0},
3208 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3209 {":relief", IMAGE_INTEGER_VALUE, 0},
3210 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3211 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3212 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3213 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3214 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3217 #if defined HAVE_NTGUI && defined WINDOWSNT
3218 static bool init_xpm_functions (void);
3219 #else
3220 #define init_xpm_functions NULL
3221 #endif
3223 /* Structure describing the image type XPM. */
3225 static struct image_type xpm_type =
3227 SYMBOL_INDEX (Qxpm),
3228 xpm_image_p,
3229 xpm_load,
3230 x_clear_image,
3231 init_xpm_functions,
3232 NULL
3235 #ifdef HAVE_X_WINDOWS
3237 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3238 functions for allocating image colors. Our own functions handle
3239 color allocation failures more gracefully than the ones on the XPM
3240 lib. */
3242 #ifndef USE_CAIRO
3243 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3244 #define ALLOC_XPM_COLORS
3245 #endif
3246 #endif /* USE_CAIRO */
3247 #endif /* HAVE_X_WINDOWS */
3249 #ifdef ALLOC_XPM_COLORS
3251 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3252 XColor *, int);
3254 /* An entry in a hash table used to cache color definitions of named
3255 colors. This cache is necessary to speed up XPM image loading in
3256 case we do color allocations ourselves. Without it, we would need
3257 a call to XParseColor per pixel in the image.
3259 FIXME Now that we're using x_parse_color and its cache, reevaluate
3260 the need for this caching layer. */
3262 struct xpm_cached_color
3264 /* Next in collision chain. */
3265 struct xpm_cached_color *next;
3267 /* Color definition (RGB and pixel color). */
3268 XColor color;
3270 /* Color name. */
3271 char name[FLEXIBLE_ARRAY_MEMBER];
3274 /* The hash table used for the color cache, and its bucket vector
3275 size. */
3277 #define XPM_COLOR_CACHE_BUCKETS 1001
3278 static struct xpm_cached_color **xpm_color_cache;
3280 /* Initialize the color cache. */
3282 static void
3283 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3285 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3286 xpm_color_cache = xzalloc (nbytes);
3287 init_color_table ();
3289 if (attrs->valuemask & XpmColorSymbols)
3291 int i;
3292 XColor color;
3294 for (i = 0; i < attrs->numsymbols; ++i)
3295 if (x_parse_color (f, attrs->colorsymbols[i].value, &color))
3297 color.pixel = lookup_rgb_color (f, color.red, color.green,
3298 color.blue);
3299 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3304 /* Free the color cache. */
3306 static void
3307 xpm_free_color_cache (void)
3309 struct xpm_cached_color *p, *next;
3310 int i;
3312 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3313 for (p = xpm_color_cache[i]; p; p = next)
3315 next = p->next;
3316 xfree (p);
3319 xfree (xpm_color_cache);
3320 xpm_color_cache = NULL;
3321 free_color_table ();
3324 /* Return the bucket index for color named COLOR_NAME in the color
3325 cache. */
3327 static int
3328 xpm_color_bucket (char *color_name)
3330 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3331 return hash % XPM_COLOR_CACHE_BUCKETS;
3335 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3336 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3337 entry added. */
3339 static struct xpm_cached_color *
3340 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3342 size_t nbytes;
3343 struct xpm_cached_color *p;
3345 if (bucket < 0)
3346 bucket = xpm_color_bucket (color_name);
3348 nbytes = FLEXSIZEOF (struct xpm_cached_color, name, strlen (color_name) + 1);
3349 p = xmalloc (nbytes);
3350 strcpy (p->name, color_name);
3351 p->color = *color;
3352 p->next = xpm_color_cache[bucket];
3353 xpm_color_cache[bucket] = p;
3354 return p;
3357 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3358 return the cached definition in *COLOR. Otherwise, make a new
3359 entry in the cache and allocate the color. Value is false if color
3360 allocation failed. */
3362 static bool
3363 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3365 struct xpm_cached_color *p;
3366 int h = xpm_color_bucket (color_name);
3368 for (p = xpm_color_cache[h]; p; p = p->next)
3369 if (strcmp (p->name, color_name) == 0)
3370 break;
3372 if (p != NULL)
3373 *color = p->color;
3374 else if (x_parse_color (f, color_name, color))
3376 color->pixel = lookup_rgb_color (f, color->red, color->green,
3377 color->blue);
3378 p = xpm_cache_color (f, color_name, color, h);
3380 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3381 with transparency, and it's useful. */
3382 else if (strcmp ("opaque", color_name) == 0)
3384 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3385 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3386 p = xpm_cache_color (f, color_name, color, h);
3389 return p != NULL;
3393 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3394 CLOSURE is a pointer to the frame on which we allocate the
3395 color. Return in *COLOR the allocated color. Value is non-zero
3396 if successful. */
3398 static int
3399 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3400 void *closure)
3402 return xpm_lookup_color (closure, color_name, color);
3406 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3407 is a pointer to the frame on which we allocate the color. Value is
3408 non-zero if successful. */
3410 static int
3411 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3413 return 1;
3416 #endif /* ALLOC_XPM_COLORS */
3419 #ifdef WINDOWSNT
3421 /* XPM library details. */
3423 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3424 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3425 (Display *, char *, xpm_XImage **,
3426 xpm_XImage **, XpmAttributes *));
3427 DEF_DLL_FN (int, XpmReadFileToImage,
3428 (Display *, char *, xpm_XImage **,
3429 xpm_XImage **, XpmAttributes *));
3430 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3432 static bool
3433 init_xpm_functions (void)
3435 HMODULE library;
3437 if (!(library = w32_delayed_load (Qxpm)))
3438 return 0;
3440 LOAD_DLL_FN (library, XpmFreeAttributes);
3441 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3442 LOAD_DLL_FN (library, XpmReadFileToImage);
3443 LOAD_DLL_FN (library, XImageFree);
3444 return 1;
3447 # undef XImageFree
3448 # undef XpmCreateImageFromBuffer
3449 # undef XpmFreeAttributes
3450 # undef XpmReadFileToImage
3452 # define XImageFree fn_XImageFree
3453 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3454 # define XpmFreeAttributes fn_XpmFreeAttributes
3455 # define XpmReadFileToImage fn_XpmReadFileToImage
3457 #endif /* WINDOWSNT */
3459 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3460 for XPM images. Such a list must consist of conses whose car and
3461 cdr are strings. */
3463 static bool
3464 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3466 while (CONSP (color_symbols))
3468 Lisp_Object sym = XCAR (color_symbols);
3469 if (!CONSP (sym)
3470 || !STRINGP (XCAR (sym))
3471 || !STRINGP (XCDR (sym)))
3472 break;
3473 color_symbols = XCDR (color_symbols);
3476 return NILP (color_symbols);
3480 /* Value is true if OBJECT is a valid XPM image specification. */
3482 static bool
3483 xpm_image_p (Lisp_Object object)
3485 struct image_keyword fmt[XPM_LAST];
3486 memcpy (fmt, xpm_format, sizeof fmt);
3487 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3488 /* Either `:file' or `:data' must be present. */
3489 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3490 /* Either no `:color-symbols' or it's a list of conses
3491 whose car and cdr are strings. */
3492 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3493 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3496 #endif /* HAVE_XPM || HAVE_NS */
3498 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3499 ptrdiff_t
3500 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3502 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3503 ptrdiff_t id;
3504 int rc;
3505 XpmAttributes attrs;
3506 Pixmap bitmap, mask;
3508 memset (&attrs, 0, sizeof attrs);
3510 attrs.visual = FRAME_X_VISUAL (f);
3511 attrs.colormap = FRAME_X_COLORMAP (f);
3512 attrs.valuemask |= XpmVisual;
3513 attrs.valuemask |= XpmColormap;
3515 #ifdef ALLOC_XPM_COLORS
3516 attrs.color_closure = f;
3517 attrs.alloc_color = xpm_alloc_color;
3518 attrs.free_colors = xpm_free_colors;
3519 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3520 xpm_init_color_cache (f, &attrs);
3521 #endif
3523 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3524 (char **) bits, &bitmap, &mask, &attrs);
3525 if (rc != XpmSuccess)
3527 XpmFreeAttributes (&attrs);
3528 return -1;
3531 id = x_allocate_bitmap_record (f);
3532 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3533 dpyinfo->bitmaps[id - 1].have_mask = true;
3534 dpyinfo->bitmaps[id - 1].mask = mask;
3535 dpyinfo->bitmaps[id - 1].file = NULL;
3536 dpyinfo->bitmaps[id - 1].height = attrs.height;
3537 dpyinfo->bitmaps[id - 1].width = attrs.width;
3538 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3539 dpyinfo->bitmaps[id - 1].refcount = 1;
3541 #ifdef ALLOC_XPM_COLORS
3542 xpm_free_color_cache ();
3543 #endif
3544 XpmFreeAttributes (&attrs);
3545 return id;
3547 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3549 /* Load image IMG which will be displayed on frame F. Value is
3550 true if successful. */
3552 #ifdef HAVE_XPM
3554 static bool
3555 xpm_load (struct frame *f, struct image *img)
3557 int rc;
3558 XpmAttributes attrs;
3559 Lisp_Object specified_file, color_symbols;
3560 USE_SAFE_ALLOCA;
3562 #ifdef HAVE_NTGUI
3563 HDC hdc;
3564 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3565 #endif /* HAVE_NTGUI */
3567 /* Configure the XPM lib. Use the visual of frame F. Allocate
3568 close colors. Return colors allocated. */
3569 memset (&attrs, 0, sizeof attrs);
3571 #ifndef HAVE_NTGUI
3572 attrs.visual = FRAME_X_VISUAL (f);
3573 attrs.colormap = FRAME_X_COLORMAP (f);
3574 attrs.valuemask |= XpmVisual;
3575 attrs.valuemask |= XpmColormap;
3576 #endif /* HAVE_NTGUI */
3578 #ifdef ALLOC_XPM_COLORS
3579 /* Allocate colors with our own functions which handle
3580 failing color allocation more gracefully. */
3581 attrs.color_closure = f;
3582 attrs.alloc_color = xpm_alloc_color;
3583 attrs.free_colors = xpm_free_colors;
3584 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3585 #else /* not ALLOC_XPM_COLORS */
3586 /* Let the XPM lib allocate colors. */
3587 attrs.valuemask |= XpmReturnAllocPixels;
3588 #ifdef XpmAllocCloseColors
3589 attrs.alloc_close_colors = 1;
3590 attrs.valuemask |= XpmAllocCloseColors;
3591 #else /* not XpmAllocCloseColors */
3592 attrs.closeness = 600;
3593 attrs.valuemask |= XpmCloseness;
3594 #endif /* not XpmAllocCloseColors */
3595 #endif /* ALLOC_XPM_COLORS */
3597 /* If image specification contains symbolic color definitions, add
3598 these to `attrs'. */
3599 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3600 if (CONSP (color_symbols))
3602 Lisp_Object tail;
3603 XpmColorSymbol *xpm_syms;
3604 ptrdiff_t i, size;
3606 attrs.valuemask |= XpmColorSymbols;
3608 /* Count number of symbols. */
3609 attrs.numsymbols = 0;
3610 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3611 ++attrs.numsymbols;
3613 /* Allocate an XpmColorSymbol array. */
3614 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3615 size = attrs.numsymbols * sizeof *xpm_syms;
3616 memset (xpm_syms, 0, size);
3617 attrs.colorsymbols = xpm_syms;
3619 /* Fill the color symbol array. */
3620 for (tail = color_symbols, i = 0;
3621 CONSP (tail);
3622 ++i, tail = XCDR (tail))
3624 Lisp_Object name;
3625 Lisp_Object color;
3626 char *empty_string = (char *) "";
3628 if (!CONSP (XCAR (tail)))
3630 xpm_syms[i].name = empty_string;
3631 xpm_syms[i].value = empty_string;
3632 continue;
3634 name = XCAR (XCAR (tail));
3635 color = XCDR (XCAR (tail));
3636 if (STRINGP (name))
3637 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3638 else
3639 xpm_syms[i].name = empty_string;
3640 if (STRINGP (color))
3641 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3642 else
3643 xpm_syms[i].value = empty_string;
3647 /* Create a pixmap for the image, either from a file, or from a
3648 string buffer containing data in the same format as an XPM file. */
3649 #ifdef ALLOC_XPM_COLORS
3650 xpm_init_color_cache (f, &attrs);
3651 #endif
3653 specified_file = image_spec_value (img->spec, QCfile, NULL);
3655 #ifdef HAVE_NTGUI
3657 HDC frame_dc = get_frame_dc (f);
3658 hdc = CreateCompatibleDC (frame_dc);
3659 release_frame_dc (f, frame_dc);
3661 #endif /* HAVE_NTGUI */
3663 if (STRINGP (specified_file))
3665 Lisp_Object file = x_find_image_file (specified_file);
3666 if (!STRINGP (file))
3668 image_error ("Cannot find image file `%s'", specified_file);
3669 #ifdef ALLOC_XPM_COLORS
3670 xpm_free_color_cache ();
3671 #endif
3672 SAFE_FREE ();
3673 return 0;
3676 file = ENCODE_FILE (file);
3677 #ifdef HAVE_NTGUI
3678 #ifdef WINDOWSNT
3679 /* FILE is encoded in UTF-8, but image libraries on Windows
3680 support neither UTF-8 nor UTF-16 encoded file names. So we
3681 need to re-encode it in ANSI. */
3682 file = ansi_encode_filename (file);
3683 #endif
3684 /* XpmReadFileToPixmap is not available in the Windows port of
3685 libxpm. But XpmReadFileToImage almost does what we want. */
3686 rc = XpmReadFileToImage (&hdc, SSDATA (file),
3687 &xpm_image, &xpm_mask,
3688 &attrs);
3689 #else
3690 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3691 &img->ximg, &img->mask_img,
3692 &attrs);
3693 #endif /* HAVE_NTGUI */
3695 else
3697 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3698 if (!STRINGP (buffer))
3700 image_error ("Invalid image data `%s'", buffer);
3701 #ifdef ALLOC_XPM_COLORS
3702 xpm_free_color_cache ();
3703 #endif
3704 SAFE_FREE ();
3705 return 0;
3707 #ifdef HAVE_NTGUI
3708 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3709 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3710 rc = XpmCreateImageFromBuffer (&hdc, SSDATA (buffer),
3711 &xpm_image, &xpm_mask,
3712 &attrs);
3713 #else
3714 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3715 &img->ximg, &img->mask_img,
3716 &attrs);
3717 #endif /* HAVE_NTGUI */
3720 #ifdef USE_CAIRO
3721 // Load very specific Xpm:s.
3722 if (rc == XpmSuccess
3723 && img->ximg->format == ZPixmap
3724 && img->ximg->bits_per_pixel == 32
3725 && (! img->mask_img || img->mask_img->bits_per_pixel == 1))
3727 int width = img->ximg->width;
3728 int height = img->ximg->height;
3729 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
3730 int i;
3731 uint32_t *od = (uint32_t *)data;
3732 uint32_t *id = (uint32_t *)img->ximg->data;
3733 char *mid = img->mask_img ? img->mask_img->data : 0;
3734 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
3736 for (i = 0; i < height; ++i)
3738 int k;
3739 for (k = 0; k < width; ++k)
3741 int idx = i * img->ximg->bytes_per_line/4 + k;
3742 int maskidx = mid ? i * img->mask_img->bytes_per_line + k/8 : 0;
3743 int mask = mid ? mid[maskidx] & (1 << (k % 8)) : 1;
3745 if (mask) od[idx] = id[idx] + 0xff000000; // ff => full alpha
3746 else od[idx] = bgcolor;
3750 create_cairo_image_surface (img, data, width, height);
3752 else
3754 rc = XpmFileInvalid;
3755 x_clear_image (f, img);
3757 #else
3758 #ifdef HAVE_X_WINDOWS
3759 if (rc == XpmSuccess)
3761 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3762 img->ximg->width, img->ximg->height,
3763 img->ximg->depth);
3764 if (img->pixmap == NO_PIXMAP)
3766 x_clear_image (f, img);
3767 rc = XpmNoMemory;
3769 else if (img->mask_img)
3771 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3772 img->mask_img->width,
3773 img->mask_img->height,
3774 img->mask_img->depth);
3775 if (img->mask == NO_PIXMAP)
3777 x_clear_image (f, img);
3778 rc = XpmNoMemory;
3782 #endif
3783 #endif /* ! USE_CAIRO */
3785 if (rc == XpmSuccess)
3787 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3788 img->colors = colors_in_color_table (&img->ncolors);
3789 #else /* not ALLOC_XPM_COLORS */
3790 int i;
3792 #ifdef HAVE_NTGUI
3793 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3794 plus some duplicate attributes. */
3795 if (xpm_image && xpm_image->bitmap)
3797 img->pixmap = xpm_image->bitmap;
3798 /* XImageFree in libXpm frees XImage struct without destroying
3799 the bitmap, which is what we want. */
3800 XImageFree (xpm_image);
3802 if (xpm_mask && xpm_mask->bitmap)
3804 /* The mask appears to be inverted compared with what we expect.
3805 TODO: invert our expectations. See other places where we
3806 have to invert bits because our idea of masks is backwards. */
3807 HGDIOBJ old_obj;
3808 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3810 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3811 SelectObject (hdc, old_obj);
3813 img->mask = xpm_mask->bitmap;
3814 XImageFree (xpm_mask);
3815 DeleteDC (hdc);
3818 DeleteDC (hdc);
3819 #endif /* HAVE_NTGUI */
3821 /* Remember allocated colors. */
3822 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3823 img->ncolors = attrs.nalloc_pixels;
3824 for (i = 0; i < attrs.nalloc_pixels; ++i)
3826 img->colors[i] = attrs.alloc_pixels[i];
3827 #ifdef DEBUG_X_COLORS
3828 register_color (img->colors[i]);
3829 #endif
3831 #endif /* not ALLOC_XPM_COLORS */
3833 img->width = attrs.width;
3834 img->height = attrs.height;
3835 eassert (img->width > 0 && img->height > 0);
3837 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3838 XpmFreeAttributes (&attrs);
3840 #ifdef HAVE_X_WINDOWS
3841 /* Maybe fill in the background field while we have ximg handy. */
3842 IMAGE_BACKGROUND (img, f, img->ximg);
3843 if (img->mask_img)
3844 /* Fill in the background_transparent field while we have the
3845 mask handy. */
3846 image_background_transparent (img, f, img->mask_img);
3847 #endif
3849 else
3851 #ifdef HAVE_NTGUI
3852 DeleteDC (hdc);
3853 #endif /* HAVE_NTGUI */
3855 switch (rc)
3857 case XpmOpenFailed:
3858 image_error ("Error opening XPM file (%s)", img->spec);
3859 break;
3861 case XpmFileInvalid:
3862 image_error ("Invalid XPM file (%s)", img->spec);
3863 break;
3865 case XpmNoMemory:
3866 image_error ("Out of memory (%s)", img->spec);
3867 break;
3869 case XpmColorFailed:
3870 image_error ("Color allocation error (%s)", img->spec);
3871 break;
3873 default:
3874 image_error ("Unknown error (%s)", img->spec);
3875 break;
3879 #ifdef ALLOC_XPM_COLORS
3880 xpm_free_color_cache ();
3881 #endif
3882 SAFE_FREE ();
3883 return rc == XpmSuccess;
3886 #endif /* HAVE_XPM */
3888 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3890 /* XPM support functions for NS where libxpm is not available.
3891 Only XPM version 3 (without any extensions) is supported. */
3893 static void xpm_put_color_table_v (Lisp_Object, const char *,
3894 int, Lisp_Object);
3895 static Lisp_Object xpm_get_color_table_v (Lisp_Object, const char *, int);
3896 static void xpm_put_color_table_h (Lisp_Object, const char *,
3897 int, Lisp_Object);
3898 static Lisp_Object xpm_get_color_table_h (Lisp_Object, const char *, int);
3900 /* Tokens returned from xpm_scan. */
3902 enum xpm_token
3904 XPM_TK_IDENT = 256,
3905 XPM_TK_STRING,
3906 XPM_TK_EOF
3909 /* Scan an XPM data and return a character (< 256) or a token defined
3910 by enum xpm_token above. *S and END are the start (inclusive) and
3911 the end (exclusive) addresses of the data, respectively. Advance
3912 *S while scanning. If token is either XPM_TK_IDENT or
3913 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3914 length of the corresponding token, respectively. */
3916 static int
3917 xpm_scan (const char **s, const char *end, const char **beg, ptrdiff_t *len)
3919 unsigned char c;
3921 while (*s < end)
3923 /* Skip white-space. */
3924 while (*s < end && (c = *(*s)++, c_isspace (c)))
3927 /* gnus-pointer.xpm uses '-' in its identifier.
3928 sb-dir-plus.xpm uses '+' in its identifier. */
3929 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3931 *beg = *s - 1;
3932 while (*s < end
3933 && (c = **s, c_isalnum (c)
3934 || c == '_' || c == '-' || c == '+'))
3935 ++*s;
3936 *len = *s - *beg;
3937 return XPM_TK_IDENT;
3939 else if (c == '"')
3941 *beg = *s;
3942 while (*s < end && **s != '"')
3943 ++*s;
3944 *len = *s - *beg;
3945 if (*s < end)
3946 ++*s;
3947 return XPM_TK_STRING;
3949 else if (c == '/')
3951 if (*s < end && **s == '*')
3953 /* C-style comment. */
3954 ++*s;
3957 while (*s < end && *(*s)++ != '*')
3960 while (*s < end && **s != '/');
3961 if (*s < end)
3962 ++*s;
3964 else
3965 return c;
3967 else
3968 return c;
3971 return XPM_TK_EOF;
3974 /* Functions for color table lookup in XPM data. A key is a string
3975 specifying the color of each pixel in XPM data. A value is either
3976 an integer that specifies a pixel color, Qt that specifies
3977 transparency, or Qnil for the unspecified color. If the length of
3978 the key string is one, a vector is used as a table. Otherwise, a
3979 hash table is used. */
3981 static Lisp_Object
3982 xpm_make_color_table_v (void (**put_func) (Lisp_Object, const char *, int,
3983 Lisp_Object),
3984 Lisp_Object (**get_func) (Lisp_Object, const char *,
3985 int))
3987 *put_func = xpm_put_color_table_v;
3988 *get_func = xpm_get_color_table_v;
3989 return Fmake_vector (make_number (256), Qnil);
3992 static void
3993 xpm_put_color_table_v (Lisp_Object color_table,
3994 const char *chars_start,
3995 int chars_len,
3996 Lisp_Object color)
3998 unsigned char uc = *chars_start;
3999 ASET (color_table, uc, color);
4002 static Lisp_Object
4003 xpm_get_color_table_v (Lisp_Object color_table,
4004 const char *chars_start,
4005 int chars_len)
4007 unsigned char uc = *chars_start;
4008 return AREF (color_table, uc);
4011 static Lisp_Object
4012 xpm_make_color_table_h (void (**put_func) (Lisp_Object, const char *, int,
4013 Lisp_Object),
4014 Lisp_Object (**get_func) (Lisp_Object, const char *,
4015 int))
4017 *put_func = xpm_put_color_table_h;
4018 *get_func = xpm_get_color_table_h;
4019 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
4020 make_float (DEFAULT_REHASH_SIZE),
4021 make_float (DEFAULT_REHASH_THRESHOLD),
4022 Qnil);
4025 static void
4026 xpm_put_color_table_h (Lisp_Object color_table,
4027 const char *chars_start,
4028 int chars_len,
4029 Lisp_Object color)
4031 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4032 EMACS_UINT hash_code;
4033 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4035 hash_lookup (table, chars, &hash_code);
4036 hash_put (table, chars, color, hash_code);
4039 static Lisp_Object
4040 xpm_get_color_table_h (Lisp_Object color_table,
4041 const char *chars_start,
4042 int chars_len)
4044 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4045 ptrdiff_t i =
4046 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
4048 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4051 enum xpm_color_key {
4052 XPM_COLOR_KEY_S,
4053 XPM_COLOR_KEY_M,
4054 XPM_COLOR_KEY_G4,
4055 XPM_COLOR_KEY_G,
4056 XPM_COLOR_KEY_C
4059 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4061 static int
4062 xpm_str_to_color_key (const char *s)
4064 int i;
4066 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
4067 if (strcmp (xpm_color_key_strings[i], s) == 0)
4068 return i;
4069 return -1;
4072 static bool
4073 xpm_load_image (struct frame *f,
4074 struct image *img,
4075 const char *contents,
4076 const char *end)
4078 const char *s = contents, *beg, *str;
4079 char buffer[BUFSIZ];
4080 int width, height, x, y;
4081 int num_colors, chars_per_pixel;
4082 ptrdiff_t len;
4083 int LA1;
4084 void (*put_color_table) (Lisp_Object, const char *, int, Lisp_Object);
4085 Lisp_Object (*get_color_table) (Lisp_Object, const char *, int);
4086 Lisp_Object frame, color_symbols, color_table;
4087 int best_key;
4088 #ifndef HAVE_NS
4089 bool have_mask = false;
4090 #endif
4091 XImagePtr ximg = NULL, mask_img = NULL;
4093 #define match() \
4094 LA1 = xpm_scan (&s, end, &beg, &len)
4096 #define expect(TOKEN) \
4097 do \
4099 if (LA1 != (TOKEN)) \
4100 goto failure; \
4101 match (); \
4103 while (0)
4105 #define expect_ident(IDENT) \
4106 if (LA1 == XPM_TK_IDENT \
4107 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4108 match (); \
4109 else \
4110 goto failure
4112 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4113 goto failure;
4114 s += 9;
4115 match ();
4116 expect_ident ("static");
4117 expect_ident ("char");
4118 expect ('*');
4119 expect (XPM_TK_IDENT);
4120 expect ('[');
4121 expect (']');
4122 expect ('=');
4123 expect ('{');
4124 expect (XPM_TK_STRING);
4125 if (len >= BUFSIZ)
4126 goto failure;
4127 memcpy (buffer, beg, len);
4128 buffer[len] = '\0';
4129 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4130 &num_colors, &chars_per_pixel) != 4
4131 || width <= 0 || height <= 0
4132 || num_colors <= 0 || chars_per_pixel <= 0)
4133 goto failure;
4135 if (!check_image_size (f, width, height))
4137 image_size_error ();
4138 goto failure;
4141 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4142 #ifndef HAVE_NS
4143 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4144 &mask_img, 1)
4145 #endif
4148 image_error ("Image too large");
4149 goto failure;
4152 expect (',');
4154 XSETFRAME (frame, f);
4155 if (!NILP (Fxw_display_color_p (frame)))
4156 best_key = XPM_COLOR_KEY_C;
4157 else if (!NILP (Fx_display_grayscale_p (frame)))
4158 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4159 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4160 else
4161 best_key = XPM_COLOR_KEY_M;
4163 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4164 if (chars_per_pixel == 1)
4165 color_table = xpm_make_color_table_v (&put_color_table,
4166 &get_color_table);
4167 else
4168 color_table = xpm_make_color_table_h (&put_color_table,
4169 &get_color_table);
4171 while (num_colors-- > 0)
4173 char *color, *max_color;
4174 int key, next_key, max_key = 0;
4175 Lisp_Object symbol_color = Qnil, color_val;
4176 XColor cdef;
4178 expect (XPM_TK_STRING);
4179 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4180 goto failure;
4181 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4182 buffer[len - chars_per_pixel] = '\0';
4184 str = strtok (buffer, " \t");
4185 if (str == NULL)
4186 goto failure;
4187 key = xpm_str_to_color_key (str);
4188 if (key < 0)
4189 goto failure;
4192 color = strtok (NULL, " \t");
4193 if (color == NULL)
4194 goto failure;
4196 while ((str = strtok (NULL, " \t")) != NULL)
4198 next_key = xpm_str_to_color_key (str);
4199 if (next_key >= 0)
4200 break;
4201 color[strlen (color)] = ' ';
4204 if (key == XPM_COLOR_KEY_S)
4206 if (NILP (symbol_color))
4207 symbol_color = build_string (color);
4209 else if (max_key < key && key <= best_key)
4211 max_key = key;
4212 max_color = color;
4214 key = next_key;
4216 while (str);
4218 color_val = Qnil;
4219 if (!NILP (color_symbols) && !NILP (symbol_color))
4221 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4223 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4225 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4226 color_val = Qt;
4227 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4228 &cdef, 0))
4229 color_val = make_number (cdef.pixel);
4232 if (NILP (color_val) && max_key > 0)
4234 if (xstrcasecmp (max_color, "None") == 0)
4235 color_val = Qt;
4236 else if (x_defined_color (f, max_color, &cdef, 0))
4237 color_val = make_number (cdef.pixel);
4239 if (!NILP (color_val))
4240 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4242 expect (',');
4245 for (y = 0; y < height; y++)
4247 expect (XPM_TK_STRING);
4248 str = beg;
4249 if (len < width * chars_per_pixel)
4250 goto failure;
4251 for (x = 0; x < width; x++, str += chars_per_pixel)
4253 Lisp_Object color_val =
4254 (*get_color_table) (color_table, str, chars_per_pixel);
4256 XPutPixel (ximg, x, y,
4257 (INTEGERP (color_val) ? XINT (color_val)
4258 : FRAME_FOREGROUND_PIXEL (f)));
4259 #ifndef HAVE_NS
4260 XPutPixel (mask_img, x, y,
4261 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4262 : (have_mask = true, PIX_MASK_RETAIN)));
4263 #else
4264 if (EQ (color_val, Qt))
4265 ns_set_alpha (ximg, x, y, 0);
4266 #endif
4268 if (y + 1 < height)
4269 expect (',');
4272 img->width = width;
4273 img->height = height;
4275 /* Maybe fill in the background field while we have ximg handy. */
4276 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4277 IMAGE_BACKGROUND (img, f, ximg);
4279 image_put_x_image (f, img, ximg, 0);
4280 #ifndef HAVE_NS
4281 if (have_mask)
4283 /* Fill in the background_transparent field while we have the
4284 mask handy. */
4285 image_background_transparent (img, f, mask_img);
4287 image_put_x_image (f, img, mask_img, 1);
4289 else
4291 x_destroy_x_image (mask_img);
4292 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4294 #endif
4295 return 1;
4297 failure:
4298 image_error ("Invalid XPM file (%s)", img->spec);
4299 x_destroy_x_image (ximg);
4300 x_destroy_x_image (mask_img);
4301 x_clear_image (f, img);
4302 return 0;
4304 #undef match
4305 #undef expect
4306 #undef expect_ident
4309 static bool
4310 xpm_load (struct frame *f,
4311 struct image *img)
4313 bool success_p = 0;
4314 Lisp_Object file_name;
4316 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4317 file_name = image_spec_value (img->spec, QCfile, NULL);
4318 if (STRINGP (file_name))
4320 int fd;
4321 Lisp_Object file = x_find_image_fd (file_name, &fd);
4322 if (!STRINGP (file))
4324 image_error ("Cannot find image file `%s'", file_name);
4325 return 0;
4328 ptrdiff_t size;
4329 char *contents = slurp_file (fd, &size);
4330 if (contents == NULL)
4332 image_error ("Error loading XPM image `%s'", file);
4333 return 0;
4336 success_p = xpm_load_image (f, img, contents, contents + size);
4337 xfree (contents);
4339 else
4341 Lisp_Object data;
4343 data = image_spec_value (img->spec, QCdata, NULL);
4344 if (!STRINGP (data))
4346 image_error ("Invalid image data `%s'", data);
4347 return 0;
4349 success_p = xpm_load_image (f, img, SSDATA (data),
4350 SSDATA (data) + SBYTES (data));
4353 return success_p;
4356 #endif /* HAVE_NS && !HAVE_XPM */
4360 /***********************************************************************
4361 Color table
4362 ***********************************************************************/
4364 #ifdef COLOR_TABLE_SUPPORT
4366 /* An entry in the color table mapping an RGB color to a pixel color. */
4368 struct ct_color
4370 int r, g, b;
4371 unsigned long pixel;
4373 /* Next in color table collision list. */
4374 struct ct_color *next;
4377 /* The bucket vector size to use. Must be prime. */
4379 #define CT_SIZE 101
4381 /* Value is a hash of the RGB color given by R, G, and B. */
4383 static unsigned
4384 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4386 return (r << 16) ^ (g << 8) ^ b;
4389 /* The color hash table. */
4391 static struct ct_color **ct_table;
4393 /* Number of entries in the color table. */
4395 static int ct_colors_allocated;
4396 enum
4398 ct_colors_allocated_max =
4399 min (INT_MAX,
4400 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4403 /* Initialize the color table. */
4405 static void
4406 init_color_table (void)
4408 int size = CT_SIZE * sizeof (*ct_table);
4409 ct_table = xzalloc (size);
4410 ct_colors_allocated = 0;
4414 /* Free memory associated with the color table. */
4416 static void
4417 free_color_table (void)
4419 int i;
4420 struct ct_color *p, *next;
4422 for (i = 0; i < CT_SIZE; ++i)
4423 for (p = ct_table[i]; p; p = next)
4425 next = p->next;
4426 xfree (p);
4429 xfree (ct_table);
4430 ct_table = NULL;
4434 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4435 entry for that color already is in the color table, return the
4436 pixel color of that entry. Otherwise, allocate a new color for R,
4437 G, B, and make an entry in the color table. */
4439 static unsigned long
4440 lookup_rgb_color (struct frame *f, int r, int g, int b)
4442 unsigned hash = ct_hash_rgb (r, g, b);
4443 int i = hash % CT_SIZE;
4444 struct ct_color *p;
4445 Display_Info *dpyinfo;
4447 /* Handle TrueColor visuals specially, which improves performance by
4448 two orders of magnitude. Freeing colors on TrueColor visuals is
4449 a nop, and pixel colors specify RGB values directly. See also
4450 the Xlib spec, chapter 3.1. */
4451 dpyinfo = FRAME_DISPLAY_INFO (f);
4452 if (dpyinfo->red_bits > 0)
4454 /* Apply gamma-correction like normal color allocation does. */
4455 if (f->gamma)
4457 XColor color;
4458 color.red = r, color.green = g, color.blue = b;
4459 gamma_correct (f, &color);
4460 r = color.red, g = color.green, b = color.blue;
4463 return x_make_truecolor_pixel (dpyinfo, r, g, b);
4466 for (p = ct_table[i]; p; p = p->next)
4467 if (p->r == r && p->g == g && p->b == b)
4468 break;
4470 if (p == NULL)
4473 #ifdef HAVE_X_WINDOWS
4474 XColor color;
4475 Colormap cmap;
4476 bool rc;
4477 #else
4478 COLORREF color;
4479 #endif
4481 if (ct_colors_allocated_max <= ct_colors_allocated)
4482 return FRAME_FOREGROUND_PIXEL (f);
4484 #ifdef HAVE_X_WINDOWS
4485 color.red = r;
4486 color.green = g;
4487 color.blue = b;
4489 cmap = FRAME_X_COLORMAP (f);
4490 rc = x_alloc_nearest_color (f, cmap, &color);
4491 if (rc)
4493 ++ct_colors_allocated;
4494 p = xmalloc (sizeof *p);
4495 p->r = r;
4496 p->g = g;
4497 p->b = b;
4498 p->pixel = color.pixel;
4499 p->next = ct_table[i];
4500 ct_table[i] = p;
4502 else
4503 return FRAME_FOREGROUND_PIXEL (f);
4505 #else
4506 #ifdef HAVE_NTGUI
4507 color = PALETTERGB (r, g, b);
4508 #else
4509 color = RGB_TO_ULONG (r, g, b);
4510 #endif /* HAVE_NTGUI */
4511 ++ct_colors_allocated;
4512 p = xmalloc (sizeof *p);
4513 p->r = r;
4514 p->g = g;
4515 p->b = b;
4516 p->pixel = color;
4517 p->next = ct_table[i];
4518 ct_table[i] = p;
4519 #endif /* HAVE_X_WINDOWS */
4523 return p->pixel;
4527 /* Look up pixel color PIXEL which is used on frame F in the color
4528 table. If not already present, allocate it. Value is PIXEL. */
4530 static unsigned long
4531 lookup_pixel_color (struct frame *f, unsigned long pixel)
4533 int i = pixel % CT_SIZE;
4534 struct ct_color *p;
4536 for (p = ct_table[i]; p; p = p->next)
4537 if (p->pixel == pixel)
4538 break;
4540 if (p == NULL)
4542 XColor color;
4543 Colormap cmap;
4544 bool rc;
4546 if (ct_colors_allocated >= ct_colors_allocated_max)
4547 return FRAME_FOREGROUND_PIXEL (f);
4549 #ifdef HAVE_X_WINDOWS
4550 cmap = FRAME_X_COLORMAP (f);
4551 color.pixel = pixel;
4552 x_query_color (f, &color);
4553 rc = x_alloc_nearest_color (f, cmap, &color);
4554 #else
4555 block_input ();
4556 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4557 color.pixel = pixel;
4558 XQueryColor (NULL, cmap, &color);
4559 rc = x_alloc_nearest_color (f, cmap, &color);
4560 unblock_input ();
4561 #endif /* HAVE_X_WINDOWS */
4563 if (rc)
4565 ++ct_colors_allocated;
4567 p = xmalloc (sizeof *p);
4568 p->r = color.red;
4569 p->g = color.green;
4570 p->b = color.blue;
4571 p->pixel = pixel;
4572 p->next = ct_table[i];
4573 ct_table[i] = p;
4575 else
4576 return FRAME_FOREGROUND_PIXEL (f);
4578 return p->pixel;
4582 /* Value is a vector of all pixel colors contained in the color table,
4583 allocated via xmalloc. Set *N to the number of colors. */
4585 static unsigned long *
4586 colors_in_color_table (int *n)
4588 int i, j;
4589 struct ct_color *p;
4590 unsigned long *colors;
4592 if (ct_colors_allocated == 0)
4594 *n = 0;
4595 colors = NULL;
4597 else
4599 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4600 *n = ct_colors_allocated;
4602 for (i = j = 0; i < CT_SIZE; ++i)
4603 for (p = ct_table[i]; p; p = p->next)
4604 colors[j++] = p->pixel;
4607 return colors;
4610 #else /* COLOR_TABLE_SUPPORT */
4612 static unsigned long
4613 lookup_rgb_color (struct frame *f, int r, int g, int b)
4615 #ifdef HAVE_NTGUI
4616 return PALETTERGB (r >> 8, g >> 8, b >> 8);
4617 #elif defined HAVE_NS
4618 return RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4619 #else
4620 xsignal1 (Qfile_error,
4621 build_string ("This Emacs mishandles this image file type"));
4622 #endif
4625 static void
4626 init_color_table (void)
4629 #endif /* COLOR_TABLE_SUPPORT */
4632 /***********************************************************************
4633 Algorithms
4634 ***********************************************************************/
4636 /* Edge detection matrices for different edge-detection
4637 strategies. */
4639 static int emboss_matrix[9] = {
4640 /* x - 1 x x + 1 */
4641 2, -1, 0, /* y - 1 */
4642 -1, 0, 1, /* y */
4643 0, 1, -2 /* y + 1 */
4646 static int laplace_matrix[9] = {
4647 /* x - 1 x x + 1 */
4648 1, 0, 0, /* y - 1 */
4649 0, 0, 0, /* y */
4650 0, 0, -1 /* y + 1 */
4653 /* Value is the intensity of the color whose red/green/blue values
4654 are R, G, and B. */
4656 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4659 /* On frame F, return an array of XColor structures describing image
4660 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4661 means also fill the red/green/blue members of the XColor
4662 structures. Value is a pointer to the array of XColors structures,
4663 allocated with xmalloc; it must be freed by the caller. */
4665 static XColor *
4666 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4668 int x, y;
4669 XColor *colors, *p;
4670 XImagePtr_or_DC ximg;
4671 ptrdiff_t nbytes;
4672 #ifdef HAVE_NTGUI
4673 HGDIOBJ prev;
4674 #endif /* HAVE_NTGUI */
4676 if (INT_MULTIPLY_WRAPV (sizeof *colors, img->width, &nbytes)
4677 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes)
4678 || SIZE_MAX < nbytes)
4679 memory_full (SIZE_MAX);
4680 colors = xmalloc (nbytes);
4682 /* Get the X image or create a memory device context for IMG. */
4683 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4685 /* Fill the `pixel' members of the XColor array. I wished there
4686 were an easy and portable way to circumvent XGetPixel. */
4687 p = colors;
4688 for (y = 0; y < img->height; ++y)
4690 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4691 XColor *row = p;
4692 for (x = 0; x < img->width; ++x, ++p)
4693 p->pixel = GET_PIXEL (ximg, x, y);
4694 if (rgb_p)
4695 x_query_colors (f, row, img->width);
4697 #else
4699 for (x = 0; x < img->width; ++x, ++p)
4701 /* W32_TODO: palette support needed here? */
4702 p->pixel = GET_PIXEL (ximg, x, y);
4703 if (rgb_p)
4705 p->red = RED16_FROM_ULONG (p->pixel);
4706 p->green = GREEN16_FROM_ULONG (p->pixel);
4707 p->blue = BLUE16_FROM_ULONG (p->pixel);
4710 #endif /* HAVE_X_WINDOWS */
4713 image_unget_x_image_or_dc (img, 0, ximg, prev);
4715 return colors;
4718 #ifdef HAVE_NTGUI
4720 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4721 created with CreateDIBSection, with the pointer to the bit values
4722 stored in ximg->data. */
4724 static void
4725 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4727 int width = ximg->info.bmiHeader.biWidth;
4728 unsigned char * pixel;
4730 /* True color images. */
4731 if (ximg->info.bmiHeader.biBitCount == 24)
4733 int rowbytes = width * 3;
4734 /* Ensure scanlines are aligned on 4 byte boundaries. */
4735 if (rowbytes % 4)
4736 rowbytes += 4 - (rowbytes % 4);
4738 pixel = ximg->data + y * rowbytes + x * 3;
4739 /* Windows bitmaps are in BGR order. */
4740 *pixel = GetBValue (color);
4741 *(pixel + 1) = GetGValue (color);
4742 *(pixel + 2) = GetRValue (color);
4744 /* Monochrome images. */
4745 else if (ximg->info.bmiHeader.biBitCount == 1)
4747 int rowbytes = width / 8;
4748 /* Ensure scanlines are aligned on 4 byte boundaries. */
4749 if (rowbytes % 4)
4750 rowbytes += 4 - (rowbytes % 4);
4751 pixel = ximg->data + y * rowbytes + x / 8;
4752 /* Filter out palette info. */
4753 if (color & 0x00ffffff)
4754 *pixel = *pixel | (1 << x % 8);
4755 else
4756 *pixel = *pixel & ~(1 << x % 8);
4758 else
4759 image_error ("XPutPixel: palette image not supported");
4762 #endif /* HAVE_NTGUI */
4764 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4765 RGB members are set. F is the frame on which this all happens.
4766 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4768 static void
4769 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4771 int x, y;
4772 XImagePtr oimg = NULL;
4773 XColor *p;
4775 init_color_table ();
4777 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4778 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4779 &oimg, 0);
4780 p = colors;
4781 for (y = 0; y < img->height; ++y)
4782 for (x = 0; x < img->width; ++x, ++p)
4784 unsigned long pixel;
4785 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4786 XPutPixel (oimg, x, y, pixel);
4789 xfree (colors);
4791 image_put_x_image (f, img, oimg, 0);
4792 #ifdef COLOR_TABLE_SUPPORT
4793 img->colors = colors_in_color_table (&img->ncolors);
4794 free_color_table ();
4795 #endif /* COLOR_TABLE_SUPPORT */
4799 /* On frame F, perform edge-detection on image IMG.
4801 MATRIX is a nine-element array specifying the transformation
4802 matrix. See emboss_matrix for an example.
4804 COLOR_ADJUST is a color adjustment added to each pixel of the
4805 outgoing image. */
4807 static void
4808 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4810 XColor *colors = x_to_xcolors (f, img, 1);
4811 XColor *new, *p;
4812 int x, y, i, sum;
4813 ptrdiff_t nbytes;
4815 for (i = sum = 0; i < 9; ++i)
4816 sum += eabs (matrix[i]);
4818 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4820 if (INT_MULTIPLY_WRAPV (sizeof *new, img->width, &nbytes)
4821 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes))
4822 memory_full (SIZE_MAX);
4823 new = xmalloc (nbytes);
4825 for (y = 0; y < img->height; ++y)
4827 p = COLOR (new, 0, y);
4828 p->red = p->green = p->blue = 0xffff/2;
4829 p = COLOR (new, img->width - 1, y);
4830 p->red = p->green = p->blue = 0xffff/2;
4833 for (x = 1; x < img->width - 1; ++x)
4835 p = COLOR (new, x, 0);
4836 p->red = p->green = p->blue = 0xffff/2;
4837 p = COLOR (new, x, img->height - 1);
4838 p->red = p->green = p->blue = 0xffff/2;
4841 for (y = 1; y < img->height - 1; ++y)
4843 p = COLOR (new, 1, y);
4845 for (x = 1; x < img->width - 1; ++x, ++p)
4847 int r, g, b, yy, xx;
4849 r = g = b = i = 0;
4850 for (yy = y - 1; yy < y + 2; ++yy)
4851 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4852 if (matrix[i])
4854 XColor *t = COLOR (colors, xx, yy);
4855 r += matrix[i] * t->red;
4856 g += matrix[i] * t->green;
4857 b += matrix[i] * t->blue;
4860 r = (r / sum + color_adjust) & 0xffff;
4861 g = (g / sum + color_adjust) & 0xffff;
4862 b = (b / sum + color_adjust) & 0xffff;
4863 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4867 xfree (colors);
4868 x_from_xcolors (f, img, new);
4870 #undef COLOR
4874 /* Perform the pre-defined `emboss' edge-detection on image IMG
4875 on frame F. */
4877 static void
4878 x_emboss (struct frame *f, struct image *img)
4880 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4884 /* Transform image IMG which is used on frame F with a Laplace
4885 edge-detection algorithm. The result is an image that can be used
4886 to draw disabled buttons, for example. */
4888 static void
4889 x_laplace (struct frame *f, struct image *img)
4891 x_detect_edges (f, img, laplace_matrix, 45000);
4895 /* Perform edge-detection on image IMG on frame F, with specified
4896 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4898 MATRIX must be either
4900 - a list of at least 9 numbers in row-major form
4901 - a vector of at least 9 numbers
4903 COLOR_ADJUST nil means use a default; otherwise it must be a
4904 number. */
4906 static void
4907 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4908 Lisp_Object color_adjust)
4910 int i = 0;
4911 int trans[9];
4913 if (CONSP (matrix))
4915 for (i = 0;
4916 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4917 ++i, matrix = XCDR (matrix))
4918 trans[i] = XFLOATINT (XCAR (matrix));
4920 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4922 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4923 trans[i] = XFLOATINT (AREF (matrix, i));
4926 if (NILP (color_adjust))
4927 color_adjust = make_number (0xffff / 2);
4929 if (i == 9 && NUMBERP (color_adjust))
4930 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4934 /* Transform image IMG on frame F so that it looks disabled. */
4936 static void
4937 x_disable_image (struct frame *f, struct image *img)
4939 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4940 #ifdef HAVE_NTGUI
4941 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4942 #else
4943 int n_planes = dpyinfo->n_planes;
4944 #endif /* HAVE_NTGUI */
4946 if (n_planes >= 2)
4948 /* Color (or grayscale). Convert to gray, and equalize. Just
4949 drawing such images with a stipple can look very odd, so
4950 we're using this method instead. */
4951 XColor *colors = x_to_xcolors (f, img, 1);
4952 XColor *p, *end;
4953 const int h = 15000;
4954 const int l = 30000;
4956 for (p = colors, end = colors + img->width * img->height;
4957 p < end;
4958 ++p)
4960 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4961 int i2 = (0xffff - h - l) * i / 0xffff + l;
4962 p->red = p->green = p->blue = i2;
4965 x_from_xcolors (f, img, colors);
4968 /* Draw a cross over the disabled image, if we must or if we
4969 should. */
4970 if (n_planes < 2 || cross_disabled_images)
4972 #ifndef HAVE_NTGUI
4973 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4975 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4977 Display *dpy = FRAME_X_DISPLAY (f);
4978 GC gc;
4980 image_sync_to_pixmaps (f, img);
4981 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4982 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4983 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4984 img->width - 1, img->height - 1);
4985 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4986 img->width - 1, 0);
4987 XFreeGC (dpy, gc);
4989 if (img->mask)
4991 gc = XCreateGC (dpy, img->mask, 0, NULL);
4992 XSetForeground (dpy, gc, MaskForeground (f));
4993 XDrawLine (dpy, img->mask, gc, 0, 0,
4994 img->width - 1, img->height - 1);
4995 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4996 img->width - 1, 0);
4997 XFreeGC (dpy, gc);
4999 #endif /* !HAVE_NS */
5000 #else
5001 HDC hdc, bmpdc;
5002 HGDIOBJ prev;
5004 hdc = get_frame_dc (f);
5005 bmpdc = CreateCompatibleDC (hdc);
5006 release_frame_dc (f, hdc);
5008 prev = SelectObject (bmpdc, img->pixmap);
5010 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5011 MoveToEx (bmpdc, 0, 0, NULL);
5012 LineTo (bmpdc, img->width - 1, img->height - 1);
5013 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5014 LineTo (bmpdc, img->width - 1, 0);
5016 if (img->mask)
5018 SelectObject (bmpdc, img->mask);
5019 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5020 MoveToEx (bmpdc, 0, 0, NULL);
5021 LineTo (bmpdc, img->width - 1, img->height - 1);
5022 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5023 LineTo (bmpdc, img->width - 1, 0);
5025 SelectObject (bmpdc, prev);
5026 DeleteDC (bmpdc);
5027 #endif /* HAVE_NTGUI */
5032 /* Build a mask for image IMG which is used on frame F. FILE is the
5033 name of an image file, for error messages. HOW determines how to
5034 determine the background color of IMG. If it is a list '(R G B)',
5035 with R, G, and B being integers >= 0, take that as the color of the
5036 background. Otherwise, determine the background color of IMG
5037 heuristically. */
5039 static void
5040 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
5042 XImagePtr_or_DC ximg;
5043 #ifdef HAVE_NTGUI
5044 HGDIOBJ prev;
5045 char *mask_img;
5046 int row_width;
5047 #elif !defined HAVE_NS
5048 XImagePtr mask_img;
5049 #endif
5050 int x, y;
5051 bool use_img_background;
5052 unsigned long bg = 0;
5054 if (img->mask)
5055 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
5057 #ifndef HAVE_NTGUI
5058 #ifndef HAVE_NS
5059 /* Create an image and pixmap serving as mask. */
5060 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
5061 &mask_img, 1))
5062 return;
5063 #endif /* !HAVE_NS */
5064 #else
5065 /* Create the bit array serving as mask. */
5066 row_width = (img->width + 7) / 8;
5067 mask_img = xzalloc (row_width * img->height);
5068 #endif /* HAVE_NTGUI */
5070 /* Get the X image or create a memory device context for IMG. */
5071 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
5073 /* Determine the background color of ximg. If HOW is `(R G B)'
5074 take that as color. Otherwise, use the image's background color. */
5075 use_img_background = 1;
5077 if (CONSP (how))
5079 int rgb[3], i;
5081 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5083 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5084 how = XCDR (how);
5087 if (i == 3 && NILP (how))
5089 char color_name[30];
5090 sprintf (color_name, "#%04x%04x%04x",
5091 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
5092 bg = (
5093 #ifdef HAVE_NTGUI
5094 0x00ffffff & /* Filter out palette info. */
5095 #endif /* HAVE_NTGUI */
5096 x_alloc_image_color (f, img, build_string (color_name), 0));
5097 use_img_background = 0;
5101 if (use_img_background)
5102 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5104 /* Set all bits in mask_img to 1 whose color in ximg is different
5105 from the background color bg. */
5106 #ifndef HAVE_NTGUI
5107 for (y = 0; y < img->height; ++y)
5108 for (x = 0; x < img->width; ++x)
5109 #ifndef HAVE_NS
5110 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5111 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5112 #else
5113 if (XGetPixel (ximg, x, y) == bg)
5114 ns_set_alpha (ximg, x, y, 0);
5115 #endif /* HAVE_NS */
5116 #ifndef HAVE_NS
5117 /* Fill in the background_transparent field while we have the mask handy. */
5118 image_background_transparent (img, f, mask_img);
5120 /* Put mask_img into the image. */
5121 image_put_x_image (f, img, mask_img, 1);
5122 #endif /* !HAVE_NS */
5123 #else
5124 for (y = 0; y < img->height; ++y)
5125 for (x = 0; x < img->width; ++x)
5127 COLORREF p = GetPixel (ximg, x, y);
5128 if (p != bg)
5129 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5132 /* Create the mask image. */
5133 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5134 mask_img);
5135 /* Fill in the background_transparent field while we have the mask handy. */
5136 SelectObject (ximg, img->mask);
5137 image_background_transparent (img, f, ximg);
5139 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5140 xfree (mask_img);
5141 #endif /* HAVE_NTGUI */
5143 image_unget_x_image_or_dc (img, 0, ximg, prev);
5147 /***********************************************************************
5148 PBM (mono, gray, color)
5149 ***********************************************************************/
5151 static bool pbm_image_p (Lisp_Object object);
5152 static bool pbm_load (struct frame *f, struct image *img);
5154 /* Indices of image specification fields in gs_format, below. */
5156 enum pbm_keyword_index
5158 PBM_TYPE,
5159 PBM_FILE,
5160 PBM_DATA,
5161 PBM_ASCENT,
5162 PBM_MARGIN,
5163 PBM_RELIEF,
5164 PBM_ALGORITHM,
5165 PBM_HEURISTIC_MASK,
5166 PBM_MASK,
5167 PBM_FOREGROUND,
5168 PBM_BACKGROUND,
5169 PBM_LAST
5172 /* Vector of image_keyword structures describing the format
5173 of valid user-defined image specifications. */
5175 static const struct image_keyword pbm_format[PBM_LAST] =
5177 {":type", IMAGE_SYMBOL_VALUE, 1},
5178 {":file", IMAGE_STRING_VALUE, 0},
5179 {":data", IMAGE_STRING_VALUE, 0},
5180 {":ascent", IMAGE_ASCENT_VALUE, 0},
5181 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5182 {":relief", IMAGE_INTEGER_VALUE, 0},
5183 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5184 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5185 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5186 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5187 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5190 /* Structure describing the image type `pbm'. */
5192 static struct image_type pbm_type =
5194 SYMBOL_INDEX (Qpbm),
5195 pbm_image_p,
5196 pbm_load,
5197 x_clear_image,
5198 NULL,
5199 NULL
5203 /* Return true if OBJECT is a valid PBM image specification. */
5205 static bool
5206 pbm_image_p (Lisp_Object object)
5208 struct image_keyword fmt[PBM_LAST];
5210 memcpy (fmt, pbm_format, sizeof fmt);
5212 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5213 return 0;
5215 /* Must specify either :data or :file. */
5216 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5220 /* Get next char skipping comments in Netpbm header. Returns -1 at
5221 end of input. */
5223 static int
5224 pbm_next_char (char **s, char *end)
5226 while (*s < end)
5228 unsigned char c = *(*s)++;
5229 if (c != '#')
5230 return c;
5231 while (*s < end)
5233 c = *(*s)++;
5234 if (c == '\n' || c == '\r')
5235 break;
5239 return -1;
5243 /* Scan a decimal number from *S and return it. Advance *S while
5244 reading the number. END is the end of the string. Value is -1 at
5245 end of input. */
5247 static int
5248 pbm_scan_number (char **s, char *end)
5250 int c = 0, val = -1;
5252 /* Skip white-space. */
5253 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5256 if (c_isdigit (c))
5258 /* Read decimal number. */
5259 val = c - '0';
5260 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5261 val = 10 * val + c - '0';
5264 return val;
5268 /* Load PBM image IMG for use on frame F. */
5270 static bool
5271 pbm_load (struct frame *f, struct image *img)
5273 bool raw_p;
5274 int x, y;
5275 int width, height, max_color_idx = 0;
5276 Lisp_Object specified_file;
5277 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5278 char *contents = NULL;
5279 char *end, *p;
5280 #ifndef USE_CAIRO
5281 XImagePtr ximg;
5282 #endif
5284 specified_file = image_spec_value (img->spec, QCfile, NULL);
5286 if (STRINGP (specified_file))
5288 int fd;
5289 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5290 if (!STRINGP (file))
5292 image_error ("Cannot find image file `%s'", specified_file);
5293 return 0;
5296 ptrdiff_t size;
5297 contents = slurp_file (fd, &size);
5298 if (contents == NULL)
5300 image_error ("Error reading `%s'", file);
5301 return 0;
5304 p = contents;
5305 end = contents + size;
5307 else
5309 Lisp_Object data;
5310 data = image_spec_value (img->spec, QCdata, NULL);
5311 if (!STRINGP (data))
5313 image_error ("Invalid image data `%s'", data);
5314 return 0;
5316 p = SSDATA (data);
5317 end = p + SBYTES (data);
5320 /* Check magic number. */
5321 if (end - p < 2 || *p++ != 'P')
5323 image_error ("Not a PBM image: `%s'", img->spec);
5324 error:
5325 xfree (contents);
5326 img->pixmap = NO_PIXMAP;
5327 return 0;
5330 switch (*p++)
5332 case '1':
5333 raw_p = 0, type = PBM_MONO;
5334 break;
5336 case '2':
5337 raw_p = 0, type = PBM_GRAY;
5338 break;
5340 case '3':
5341 raw_p = 0, type = PBM_COLOR;
5342 break;
5344 case '4':
5345 raw_p = 1, type = PBM_MONO;
5346 break;
5348 case '5':
5349 raw_p = 1, type = PBM_GRAY;
5350 break;
5352 case '6':
5353 raw_p = 1, type = PBM_COLOR;
5354 break;
5356 default:
5357 image_error ("Not a PBM image: `%s'", img->spec);
5358 goto error;
5361 /* Read width, height, maximum color-component. Characters
5362 starting with `#' up to the end of a line are ignored. */
5363 width = pbm_scan_number (&p, end);
5364 height = pbm_scan_number (&p, end);
5366 #ifdef USE_CAIRO
5367 uint32_t *data = xmalloc (width * height * 4);
5368 uint32_t *dataptr = data;
5369 #endif
5371 if (type != PBM_MONO)
5373 max_color_idx = pbm_scan_number (&p, end);
5374 if (max_color_idx > 65535 || max_color_idx < 0)
5376 image_error ("Unsupported maximum PBM color value");
5377 goto error;
5381 if (!check_image_size (f, width, height))
5383 image_size_error ();
5384 goto error;
5387 #ifndef USE_CAIRO
5388 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5389 goto error;
5390 #endif
5392 /* Initialize the color hash table. */
5393 init_color_table ();
5395 if (type == PBM_MONO)
5397 unsigned char c = 0;
5398 int g;
5399 struct image_keyword fmt[PBM_LAST];
5400 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5401 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5402 #ifdef USE_CAIRO
5403 XColor xfg, xbg;
5404 int fga32, bga32;
5405 #endif
5406 /* Parse the image specification. */
5407 memcpy (fmt, pbm_format, sizeof fmt);
5408 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5410 /* Get foreground and background colors, maybe allocate colors. */
5411 #ifdef USE_CAIRO
5412 if (! fmt[PBM_FOREGROUND].count
5413 || ! STRINGP (fmt[PBM_FOREGROUND].value)
5414 || ! x_defined_color (f, SSDATA (fmt[PBM_FOREGROUND].value), &xfg, 0))
5416 xfg.pixel = fg;
5417 x_query_color (f, &xfg);
5419 fga32 = xcolor_to_argb32 (xfg);
5421 if (! fmt[PBM_BACKGROUND].count
5422 || ! STRINGP (fmt[PBM_BACKGROUND].value)
5423 || ! x_defined_color (f, SSDATA (fmt[PBM_BACKGROUND].value), &xbg, 0))
5425 xbg.pixel = bg;
5426 x_query_color (f, &xbg);
5428 bga32 = xcolor_to_argb32 (xbg);
5429 #else
5430 if (fmt[PBM_FOREGROUND].count
5431 && STRINGP (fmt[PBM_FOREGROUND].value))
5432 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5433 if (fmt[PBM_BACKGROUND].count
5434 && STRINGP (fmt[PBM_BACKGROUND].value))
5436 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5437 img->background = bg;
5438 img->background_valid = 1;
5440 #endif
5442 for (y = 0; y < height; ++y)
5443 for (x = 0; x < width; ++x)
5445 if (raw_p)
5447 if ((x & 7) == 0)
5449 if (p >= end)
5451 #ifdef USE_CAIRO
5452 xfree (data);
5453 #else
5454 x_destroy_x_image (ximg);
5455 #endif
5456 x_clear_image (f, img);
5457 image_error ("Invalid image size in image `%s'",
5458 img->spec);
5459 goto error;
5461 c = *p++;
5463 g = c & 0x80;
5464 c <<= 1;
5466 else
5467 g = pbm_scan_number (&p, end);
5469 #ifdef USE_CAIRO
5470 *dataptr++ = g ? fga32 : bga32;
5471 #else
5472 XPutPixel (ximg, x, y, g ? fg : bg);
5473 #endif
5476 else
5478 int expected_size = height * width;
5479 if (max_color_idx > 255)
5480 expected_size *= 2;
5481 if (type == PBM_COLOR)
5482 expected_size *= 3;
5484 if (raw_p && p + expected_size > end)
5486 #ifdef USE_CAIRO
5487 xfree (data);
5488 #else
5489 x_destroy_x_image (ximg);
5490 #endif
5491 x_clear_image (f, img);
5492 image_error ("Invalid image size in image `%s'", img->spec);
5493 goto error;
5496 for (y = 0; y < height; ++y)
5497 for (x = 0; x < width; ++x)
5499 int r, g, b;
5501 if (type == PBM_GRAY && raw_p)
5503 r = g = b = *p++;
5504 if (max_color_idx > 255)
5505 r = g = b = r * 256 + *p++;
5507 else if (type == PBM_GRAY)
5508 r = g = b = pbm_scan_number (&p, end);
5509 else if (raw_p)
5511 r = *p++;
5512 if (max_color_idx > 255)
5513 r = r * 256 + *p++;
5514 g = *p++;
5515 if (max_color_idx > 255)
5516 g = g * 256 + *p++;
5517 b = *p++;
5518 if (max_color_idx > 255)
5519 b = b * 256 + *p++;
5521 else
5523 r = pbm_scan_number (&p, end);
5524 g = pbm_scan_number (&p, end);
5525 b = pbm_scan_number (&p, end);
5528 if (r < 0 || g < 0 || b < 0)
5530 #ifdef USE_CAIRO
5531 xfree (data);
5532 #else
5533 x_destroy_x_image (ximg);
5534 #endif
5535 image_error ("Invalid pixel value in image `%s'", img->spec);
5536 goto error;
5539 #ifdef USE_CAIRO
5540 r = (double) r * 255 / max_color_idx;
5541 g = (double) g * 255 / max_color_idx;
5542 b = (double) b * 255 / max_color_idx;
5543 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
5544 #else
5545 /* RGB values are now in the range 0..max_color_idx.
5546 Scale this to the range 0..0xffff supported by X. */
5547 r = (double) r * 65535 / max_color_idx;
5548 g = (double) g * 65535 / max_color_idx;
5549 b = (double) b * 65535 / max_color_idx;
5550 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5551 #endif
5555 #ifdef COLOR_TABLE_SUPPORT
5556 /* Store in IMG->colors the colors allocated for the image, and
5557 free the color table. */
5558 img->colors = colors_in_color_table (&img->ncolors);
5559 free_color_table ();
5560 #endif /* COLOR_TABLE_SUPPORT */
5562 img->width = width;
5563 img->height = height;
5565 /* Maybe fill in the background field while we have ximg handy. */
5567 #ifdef USE_CAIRO
5568 create_cairo_image_surface (img, data, width, height);
5569 #else
5570 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5571 /* Casting avoids a GCC warning. */
5572 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5574 /* Put ximg into the image. */
5575 image_put_x_image (f, img, ximg, 0);
5576 #endif
5578 /* X and W32 versions did it here, MAC version above. ++kfs
5579 img->width = width;
5580 img->height = height; */
5582 xfree (contents);
5583 return 1;
5587 /***********************************************************************
5589 ***********************************************************************/
5591 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5593 /* Function prototypes. */
5595 static bool png_image_p (Lisp_Object object);
5596 static bool png_load (struct frame *f, struct image *img);
5598 /* Indices of image specification fields in png_format, below. */
5600 enum png_keyword_index
5602 PNG_TYPE,
5603 PNG_DATA,
5604 PNG_FILE,
5605 PNG_ASCENT,
5606 PNG_MARGIN,
5607 PNG_RELIEF,
5608 PNG_ALGORITHM,
5609 PNG_HEURISTIC_MASK,
5610 PNG_MASK,
5611 PNG_BACKGROUND,
5612 PNG_LAST
5615 /* Vector of image_keyword structures describing the format
5616 of valid user-defined image specifications. */
5618 static const struct image_keyword png_format[PNG_LAST] =
5620 {":type", IMAGE_SYMBOL_VALUE, 1},
5621 {":data", IMAGE_STRING_VALUE, 0},
5622 {":file", IMAGE_STRING_VALUE, 0},
5623 {":ascent", IMAGE_ASCENT_VALUE, 0},
5624 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5625 {":relief", IMAGE_INTEGER_VALUE, 0},
5626 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5627 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5628 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5629 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5632 #if defined HAVE_NTGUI && defined WINDOWSNT
5633 static bool init_png_functions (void);
5634 #else
5635 #define init_png_functions NULL
5636 #endif
5638 /* Structure describing the image type `png'. */
5640 static struct image_type png_type =
5642 SYMBOL_INDEX (Qpng),
5643 png_image_p,
5644 png_load,
5645 x_clear_image,
5646 init_png_functions,
5647 NULL
5650 /* Return true if OBJECT is a valid PNG image specification. */
5652 static bool
5653 png_image_p (Lisp_Object object)
5655 struct image_keyword fmt[PNG_LAST];
5656 memcpy (fmt, png_format, sizeof fmt);
5658 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5659 return 0;
5661 /* Must specify either the :data or :file keyword. */
5662 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5665 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5668 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5670 # ifdef WINDOWSNT
5671 /* PNG library details. */
5673 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5674 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5675 DEF_DLL_FN (png_structp, png_create_read_struct,
5676 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5677 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5678 DEF_DLL_FN (void, png_destroy_read_struct,
5679 (png_structpp, png_infopp, png_infopp));
5680 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5681 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5682 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5683 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5684 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5685 int *, int *, int *, int *, int *));
5686 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5687 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5688 DEF_DLL_FN (void, png_set_expand, (png_structp));
5689 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5690 DEF_DLL_FN (void, png_set_background,
5691 (png_structp, png_color_16p, int, int, double));
5692 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5693 (png_structp, png_infop, png_color_16p *));
5694 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5695 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5696 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5697 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5698 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5699 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5701 # if (PNG_LIBPNG_VER >= 10500)
5702 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5703 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5704 (png_structp, png_longjmp_ptr, size_t));
5705 # endif /* libpng version >= 1.5 */
5707 static bool
5708 init_png_functions (void)
5710 HMODULE library;
5712 if (!(library = w32_delayed_load (Qpng)))
5713 return 0;
5715 LOAD_DLL_FN (library, png_get_io_ptr);
5716 LOAD_DLL_FN (library, png_sig_cmp);
5717 LOAD_DLL_FN (library, png_create_read_struct);
5718 LOAD_DLL_FN (library, png_create_info_struct);
5719 LOAD_DLL_FN (library, png_destroy_read_struct);
5720 LOAD_DLL_FN (library, png_set_read_fn);
5721 LOAD_DLL_FN (library, png_set_sig_bytes);
5722 LOAD_DLL_FN (library, png_read_info);
5723 LOAD_DLL_FN (library, png_get_IHDR);
5724 LOAD_DLL_FN (library, png_get_valid);
5725 LOAD_DLL_FN (library, png_set_strip_16);
5726 LOAD_DLL_FN (library, png_set_expand);
5727 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5728 LOAD_DLL_FN (library, png_set_background);
5729 LOAD_DLL_FN (library, png_get_bKGD);
5730 LOAD_DLL_FN (library, png_read_update_info);
5731 LOAD_DLL_FN (library, png_get_channels);
5732 LOAD_DLL_FN (library, png_get_rowbytes);
5733 LOAD_DLL_FN (library, png_read_image);
5734 LOAD_DLL_FN (library, png_read_end);
5735 LOAD_DLL_FN (library, png_error);
5737 # if (PNG_LIBPNG_VER >= 10500)
5738 LOAD_DLL_FN (library, png_longjmp);
5739 LOAD_DLL_FN (library, png_set_longjmp_fn);
5740 # endif /* libpng version >= 1.5 */
5742 return 1;
5745 # undef png_create_info_struct
5746 # undef png_create_read_struct
5747 # undef png_destroy_read_struct
5748 # undef png_error
5749 # undef png_get_bKGD
5750 # undef png_get_channels
5751 # undef png_get_IHDR
5752 # undef png_get_io_ptr
5753 # undef png_get_rowbytes
5754 # undef png_get_valid
5755 # undef png_longjmp
5756 # undef png_read_end
5757 # undef png_read_image
5758 # undef png_read_info
5759 # undef png_read_update_info
5760 # undef png_set_background
5761 # undef png_set_expand
5762 # undef png_set_gray_to_rgb
5763 # undef png_set_longjmp_fn
5764 # undef png_set_read_fn
5765 # undef png_set_sig_bytes
5766 # undef png_set_strip_16
5767 # undef png_sig_cmp
5769 # define png_create_info_struct fn_png_create_info_struct
5770 # define png_create_read_struct fn_png_create_read_struct
5771 # define png_destroy_read_struct fn_png_destroy_read_struct
5772 # define png_error fn_png_error
5773 # define png_get_bKGD fn_png_get_bKGD
5774 # define png_get_channels fn_png_get_channels
5775 # define png_get_IHDR fn_png_get_IHDR
5776 # define png_get_io_ptr fn_png_get_io_ptr
5777 # define png_get_rowbytes fn_png_get_rowbytes
5778 # define png_get_valid fn_png_get_valid
5779 # define png_longjmp fn_png_longjmp
5780 # define png_read_end fn_png_read_end
5781 # define png_read_image fn_png_read_image
5782 # define png_read_info fn_png_read_info
5783 # define png_read_update_info fn_png_read_update_info
5784 # define png_set_background fn_png_set_background
5785 # define png_set_expand fn_png_set_expand
5786 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5787 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5788 # define png_set_read_fn fn_png_set_read_fn
5789 # define png_set_sig_bytes fn_png_set_sig_bytes
5790 # define png_set_strip_16 fn_png_set_strip_16
5791 # define png_sig_cmp fn_png_sig_cmp
5793 # endif /* WINDOWSNT */
5795 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5796 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5797 Do not use sys_setjmp, as PNG supports only jmp_buf.
5798 It's OK if the longjmp substitute restores the signal mask. */
5799 # ifdef HAVE__SETJMP
5800 # define FAST_SETJMP(j) _setjmp (j)
5801 # define FAST_LONGJMP _longjmp
5802 # else
5803 # define FAST_SETJMP(j) setjmp (j)
5804 # define FAST_LONGJMP longjmp
5805 # endif
5807 # if PNG_LIBPNG_VER < 10500
5808 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5809 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5810 # else
5811 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5812 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5813 # define PNG_JMPBUF(ptr) \
5814 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5815 # endif
5817 /* Error and warning handlers installed when the PNG library
5818 is initialized. */
5820 static _Noreturn void
5821 my_png_error (png_struct *png_ptr, const char *msg)
5823 eassert (png_ptr != NULL);
5824 /* Avoid compiler warning about deprecated direct access to
5825 png_ptr's fields in libpng versions 1.4.x. */
5826 image_error ("PNG error: %s", build_string (msg));
5827 PNG_LONGJMP (png_ptr);
5831 static void
5832 my_png_warning (png_struct *png_ptr, const char *msg)
5834 eassert (png_ptr != NULL);
5835 image_error ("PNG warning: %s", build_string (msg));
5838 /* Memory source for PNG decoding. */
5840 struct png_memory_storage
5842 unsigned char *bytes; /* The data */
5843 ptrdiff_t len; /* How big is it? */
5844 ptrdiff_t index; /* Where are we? */
5848 /* Function set as reader function when reading PNG image from memory.
5849 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5850 bytes from the input to DATA. */
5852 static void
5853 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5855 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5857 if (length > tbr->len - tbr->index)
5858 png_error (png_ptr, "Read error");
5860 memcpy (data, tbr->bytes + tbr->index, length);
5861 tbr->index = tbr->index + length;
5865 /* Function set as reader function when reading PNG image from a file.
5866 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5867 bytes from the input to DATA. */
5869 static void
5870 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5872 FILE *fp = png_get_io_ptr (png_ptr);
5874 if (fread (data, 1, length, fp) < length)
5875 png_error (png_ptr, "Read error");
5879 /* Load PNG image IMG for use on frame F. Value is true if
5880 successful. */
5882 struct png_load_context
5884 /* These are members so that longjmp doesn't munge local variables. */
5885 png_struct *png_ptr;
5886 png_info *info_ptr;
5887 png_info *end_info;
5888 FILE *fp;
5889 png_byte *pixels;
5890 png_byte **rows;
5893 static bool
5894 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5896 Lisp_Object specified_file, specified_data;
5897 FILE *fp = NULL;
5898 int x, y;
5899 ptrdiff_t i;
5900 png_struct *png_ptr;
5901 png_info *info_ptr = NULL, *end_info = NULL;
5902 png_byte sig[8];
5903 png_byte *pixels = NULL;
5904 png_byte **rows = NULL;
5905 png_uint_32 width, height;
5906 int bit_depth, color_type, interlace_type;
5907 png_byte channels;
5908 png_uint_32 row_bytes;
5909 bool transparent_p;
5910 struct png_memory_storage tbr; /* Data to be read */
5911 ptrdiff_t nbytes;
5913 #ifdef USE_CAIRO
5914 unsigned char *data = 0;
5915 uint32_t *dataptr;
5916 #else
5917 XImagePtr ximg, mask_img = NULL;
5918 #endif
5920 /* Find out what file to load. */
5921 specified_file = image_spec_value (img->spec, QCfile, NULL);
5922 specified_data = image_spec_value (img->spec, QCdata, NULL);
5924 if (NILP (specified_data))
5926 int fd;
5927 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5928 if (!STRINGP (file))
5930 image_error ("Cannot find image file `%s'", specified_file);
5931 return 0;
5934 /* Open the image file. */
5935 fp = fdopen (fd, "rb");
5936 if (!fp)
5938 image_error ("Cannot open image file `%s'", file);
5939 return 0;
5942 /* Check PNG signature. */
5943 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5944 || png_sig_cmp (sig, 0, sizeof sig))
5946 fclose (fp);
5947 image_error ("Not a PNG file: `%s'", file);
5948 return 0;
5951 else
5953 if (!STRINGP (specified_data))
5955 image_error ("Invalid image data `%s'", specified_data);
5956 return 0;
5959 /* Read from memory. */
5960 tbr.bytes = SDATA (specified_data);
5961 tbr.len = SBYTES (specified_data);
5962 tbr.index = 0;
5964 /* Check PNG signature. */
5965 if (tbr.len < sizeof sig
5966 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5968 image_error ("Not a PNG image: `%s'", img->spec);
5969 return 0;
5972 /* Need to skip past the signature. */
5973 tbr.bytes += sizeof (sig);
5976 /* Initialize read and info structs for PNG lib. */
5977 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5978 NULL, my_png_error,
5979 my_png_warning);
5980 if (png_ptr)
5982 info_ptr = png_create_info_struct (png_ptr);
5983 end_info = png_create_info_struct (png_ptr);
5986 c->png_ptr = png_ptr;
5987 c->info_ptr = info_ptr;
5988 c->end_info = end_info;
5989 c->fp = fp;
5990 c->pixels = pixels;
5991 c->rows = rows;
5993 if (! (info_ptr && end_info))
5995 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5996 png_ptr = 0;
5998 if (! png_ptr)
6000 if (fp) fclose (fp);
6001 return 0;
6004 /* Set error jump-back. We come back here when the PNG library
6005 detects an error. */
6006 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
6008 error:
6009 if (c->png_ptr)
6010 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6011 xfree (c->pixels);
6012 xfree (c->rows);
6013 if (c->fp)
6014 fclose (c->fp);
6015 return 0;
6018 /* Read image info. */
6019 if (!NILP (specified_data))
6020 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
6021 else
6022 png_set_read_fn (png_ptr, fp, png_read_from_file);
6024 png_set_sig_bytes (png_ptr, sizeof sig);
6025 png_read_info (png_ptr, info_ptr);
6026 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6027 &interlace_type, NULL, NULL);
6029 if (! (width <= INT_MAX && height <= INT_MAX
6030 && check_image_size (f, width, height)))
6032 image_size_error ();
6033 goto error;
6036 #ifndef USE_CAIRO
6037 /* Create the X image and pixmap now, so that the work below can be
6038 omitted if the image is too large for X. */
6039 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6040 goto error;
6041 #endif
6043 /* If image contains simply transparency data, we prefer to
6044 construct a clipping mask. */
6045 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6046 transparent_p = 1;
6047 else
6048 transparent_p = 0;
6050 /* This function is easier to write if we only have to handle
6051 one data format: RGB or RGBA with 8 bits per channel. Let's
6052 transform other formats into that format. */
6054 /* Strip more than 8 bits per channel. */
6055 if (bit_depth == 16)
6056 png_set_strip_16 (png_ptr);
6058 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6059 if available. */
6060 png_set_expand (png_ptr);
6062 /* Convert grayscale images to RGB. */
6063 if (color_type == PNG_COLOR_TYPE_GRAY
6064 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6065 png_set_gray_to_rgb (png_ptr);
6067 /* Handle alpha channel by combining the image with a background
6068 color. Do this only if a real alpha channel is supplied. For
6069 simple transparency, we prefer a clipping mask. */
6070 if (!transparent_p)
6072 /* png_color_16 *image_bg; */
6073 Lisp_Object specified_bg
6074 = image_spec_value (img->spec, QCbackground, NULL);
6075 XColor color;
6077 /* If the user specified a color, try to use it; if not, use the
6078 current frame background, ignoring any default background
6079 color set by the image. */
6080 if (STRINGP (specified_bg)
6081 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
6082 : (x_query_frame_background_color (f, &color), true))
6083 /* The user specified `:background', use that. */
6085 int shift = bit_depth == 16 ? 0 : 8;
6086 png_color_16 bg = { 0 };
6087 bg.red = color.red >> shift;
6088 bg.green = color.green >> shift;
6089 bg.blue = color.blue >> shift;
6091 png_set_background (png_ptr, &bg,
6092 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6096 /* Update info structure. */
6097 png_read_update_info (png_ptr, info_ptr);
6099 /* Get number of channels. Valid values are 1 for grayscale images
6100 and images with a palette, 2 for grayscale images with transparency
6101 information (alpha channel), 3 for RGB images, and 4 for RGB
6102 images with alpha channel, i.e. RGBA. If conversions above were
6103 sufficient we should only have 3 or 4 channels here. */
6104 channels = png_get_channels (png_ptr, info_ptr);
6105 eassert (channels == 3 || channels == 4);
6107 /* Number of bytes needed for one row of the image. */
6108 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
6110 /* Allocate memory for the image. */
6111 if (INT_MULTIPLY_WRAPV (row_bytes, sizeof *pixels, &nbytes)
6112 || INT_MULTIPLY_WRAPV (nbytes, height, &nbytes))
6113 memory_full (SIZE_MAX);
6114 c->pixels = pixels = xmalloc (nbytes);
6115 c->rows = rows = xmalloc (height * sizeof *rows);
6116 for (i = 0; i < height; ++i)
6117 rows[i] = pixels + i * row_bytes;
6119 /* Read the entire image. */
6120 png_read_image (png_ptr, rows);
6121 png_read_end (png_ptr, info_ptr);
6122 if (fp)
6124 fclose (fp);
6125 c->fp = NULL;
6128 #ifdef USE_CAIRO
6129 data = (unsigned char *) xmalloc (width * height * 4);
6130 dataptr = (uint32_t *) data;
6131 #else
6132 /* Create an image and pixmap serving as mask if the PNG image
6133 contains an alpha channel. */
6134 if (channels == 4
6135 && !transparent_p
6136 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
6137 &mask_img, 1))
6139 x_destroy_x_image (ximg);
6140 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
6141 goto error;
6143 #endif
6145 /* Fill the X image and mask from PNG data. */
6146 init_color_table ();
6148 for (y = 0; y < height; ++y)
6150 png_byte *p = rows[y];
6152 for (x = 0; x < width; ++x)
6154 int r, g, b;
6156 #ifdef USE_CAIRO
6157 int a = 0xff;
6158 r = *p++;
6159 g = *p++;
6160 b = *p++;
6161 if (channels == 4) a = *p++;
6162 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
6163 #else
6164 r = *p++ << 8;
6165 g = *p++ << 8;
6166 b = *p++ << 8;
6167 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6168 /* An alpha channel, aka mask channel, associates variable
6169 transparency with an image. Where other image formats
6170 support binary transparency---fully transparent or fully
6171 opaque---PNG allows up to 254 levels of partial transparency.
6172 The PNG library implements partial transparency by combining
6173 the image with a specified background color.
6175 I'm not sure how to handle this here nicely: because the
6176 background on which the image is displayed may change, for
6177 real alpha channel support, it would be necessary to create
6178 a new image for each possible background.
6180 What I'm doing now is that a mask is created if we have
6181 boolean transparency information. Otherwise I'm using
6182 the frame's background color to combine the image with. */
6184 if (channels == 4)
6186 if (mask_img)
6187 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6188 ++p;
6190 #endif
6194 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6195 /* Set IMG's background color from the PNG image, unless the user
6196 overrode it. */
6198 png_color_16 *bg;
6199 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6201 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6202 img->background_valid = 1;
6206 # ifdef COLOR_TABLE_SUPPORT
6207 /* Remember colors allocated for this image. */
6208 img->colors = colors_in_color_table (&img->ncolors);
6209 free_color_table ();
6210 # endif /* COLOR_TABLE_SUPPORT */
6212 /* Clean up. */
6213 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6214 xfree (rows);
6215 xfree (pixels);
6217 img->width = width;
6218 img->height = height;
6220 #ifdef USE_CAIRO
6221 create_cairo_image_surface (img, data, width, height);
6222 #else
6223 /* Maybe fill in the background field while we have ximg handy.
6224 Casting avoids a GCC warning. */
6225 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6227 /* Put ximg into the image. */
6228 image_put_x_image (f, img, ximg, 0);
6230 /* Same for the mask. */
6231 if (mask_img)
6233 /* Fill in the background_transparent field while we have the
6234 mask handy. Casting avoids a GCC warning. */
6235 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6237 image_put_x_image (f, img, mask_img, 1);
6239 #endif
6241 return 1;
6244 static bool
6245 png_load (struct frame *f, struct image *img)
6247 struct png_load_context c;
6248 return png_load_body (f, img, &c);
6251 #elif defined HAVE_NS
6253 static bool
6254 png_load (struct frame *f, struct image *img)
6256 return ns_load_image (f, img,
6257 image_spec_value (img->spec, QCfile, NULL),
6258 image_spec_value (img->spec, QCdata, NULL));
6262 #endif /* HAVE_NS */
6266 /***********************************************************************
6267 JPEG
6268 ***********************************************************************/
6270 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6272 static bool jpeg_image_p (Lisp_Object object);
6273 static bool jpeg_load (struct frame *f, struct image *img);
6275 /* Indices of image specification fields in gs_format, below. */
6277 enum jpeg_keyword_index
6279 JPEG_TYPE,
6280 JPEG_DATA,
6281 JPEG_FILE,
6282 JPEG_ASCENT,
6283 JPEG_MARGIN,
6284 JPEG_RELIEF,
6285 JPEG_ALGORITHM,
6286 JPEG_HEURISTIC_MASK,
6287 JPEG_MASK,
6288 JPEG_BACKGROUND,
6289 JPEG_LAST
6292 /* Vector of image_keyword structures describing the format
6293 of valid user-defined image specifications. */
6295 static const struct image_keyword jpeg_format[JPEG_LAST] =
6297 {":type", IMAGE_SYMBOL_VALUE, 1},
6298 {":data", IMAGE_STRING_VALUE, 0},
6299 {":file", IMAGE_STRING_VALUE, 0},
6300 {":ascent", IMAGE_ASCENT_VALUE, 0},
6301 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6302 {":relief", IMAGE_INTEGER_VALUE, 0},
6303 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6304 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6305 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6306 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6309 #if defined HAVE_NTGUI && defined WINDOWSNT
6310 static bool init_jpeg_functions (void);
6311 #else
6312 #define init_jpeg_functions NULL
6313 #endif
6315 /* Structure describing the image type `jpeg'. */
6317 static struct image_type jpeg_type =
6319 SYMBOL_INDEX (Qjpeg),
6320 jpeg_image_p,
6321 jpeg_load,
6322 x_clear_image,
6323 init_jpeg_functions,
6324 NULL
6327 /* Return true if OBJECT is a valid JPEG image specification. */
6329 static bool
6330 jpeg_image_p (Lisp_Object object)
6332 struct image_keyword fmt[JPEG_LAST];
6334 memcpy (fmt, jpeg_format, sizeof fmt);
6336 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6337 return 0;
6339 /* Must specify either the :data or :file keyword. */
6340 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6343 #endif /* HAVE_JPEG || HAVE_NS */
6345 #ifdef HAVE_JPEG
6347 /* Work around a warning about HAVE_STDLIB_H being redefined in
6348 jconfig.h. */
6349 # ifdef HAVE_STDLIB_H
6350 # undef HAVE_STDLIB_H
6351 # endif
6353 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6354 /* In older releases of the jpeg library, jpeglib.h will define boolean
6355 differently depending on __WIN32__, so make sure it is defined. */
6356 # define __WIN32__ 1
6357 # endif
6359 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6360 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6361 using the Windows boolean type instead of the jpeglib boolean type
6362 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6363 headers are included along with windows.h, so under Cygwin, jpeglib
6364 attempts to define a conflicting boolean type. Worse, forcing
6365 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6366 because it created an ABI incompatibility between the
6367 already-compiled jpeg library and the header interface definition.
6369 The best we can do is to define jpeglib's boolean type to a
6370 different name. This name, jpeg_boolean, remains in effect through
6371 the rest of image.c.
6373 # if defined CYGWIN && defined HAVE_NTGUI
6374 # define boolean jpeg_boolean
6375 # endif
6376 # include <jpeglib.h>
6377 # include <jerror.h>
6379 # ifdef WINDOWSNT
6381 /* JPEG library details. */
6382 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6383 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6384 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6385 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6386 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6387 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6388 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6389 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6390 (struct jpeg_error_mgr *));
6391 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6393 static bool
6394 init_jpeg_functions (void)
6396 HMODULE library;
6398 if (!(library = w32_delayed_load (Qjpeg)))
6399 return 0;
6401 LOAD_DLL_FN (library, jpeg_finish_decompress);
6402 LOAD_DLL_FN (library, jpeg_read_scanlines);
6403 LOAD_DLL_FN (library, jpeg_start_decompress);
6404 LOAD_DLL_FN (library, jpeg_read_header);
6405 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6406 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6407 LOAD_DLL_FN (library, jpeg_std_error);
6408 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6409 return 1;
6412 # undef jpeg_CreateDecompress
6413 # undef jpeg_destroy_decompress
6414 # undef jpeg_finish_decompress
6415 # undef jpeg_read_header
6416 # undef jpeg_read_scanlines
6417 # undef jpeg_resync_to_restart
6418 # undef jpeg_start_decompress
6419 # undef jpeg_std_error
6421 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6422 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6423 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6424 # define jpeg_read_header fn_jpeg_read_header
6425 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6426 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6427 # define jpeg_start_decompress fn_jpeg_start_decompress
6428 # define jpeg_std_error fn_jpeg_std_error
6430 /* Wrapper since we can't directly assign the function pointer
6431 to another function pointer that was declared more completely easily. */
6432 static boolean
6433 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6435 return jpeg_resync_to_restart (cinfo, desired);
6437 # undef jpeg_resync_to_restart
6438 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6440 # endif /* WINDOWSNT */
6442 struct my_jpeg_error_mgr
6444 struct jpeg_error_mgr pub;
6445 sys_jmp_buf setjmp_buffer;
6447 /* The remaining members are so that longjmp doesn't munge local
6448 variables. */
6449 struct jpeg_decompress_struct cinfo;
6450 enum
6452 MY_JPEG_ERROR_EXIT,
6453 MY_JPEG_INVALID_IMAGE_SIZE,
6454 MY_JPEG_CANNOT_CREATE_X
6455 } failure_code;
6459 static _Noreturn void
6460 my_error_exit (j_common_ptr cinfo)
6462 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6463 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6464 sys_longjmp (mgr->setjmp_buffer, 1);
6468 /* Init source method for JPEG data source manager. Called by
6469 jpeg_read_header() before any data is actually read. See
6470 libjpeg.doc from the JPEG lib distribution. */
6472 static void
6473 our_common_init_source (j_decompress_ptr cinfo)
6478 /* Method to terminate data source. Called by
6479 jpeg_finish_decompress() after all data has been processed. */
6481 static void
6482 our_common_term_source (j_decompress_ptr cinfo)
6487 /* Fill input buffer method for JPEG data source manager. Called
6488 whenever more data is needed. We read the whole image in one step,
6489 so this only adds a fake end of input marker at the end. */
6491 static JOCTET our_memory_buffer[2];
6493 static boolean
6494 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6496 /* Insert a fake EOI marker. */
6497 struct jpeg_source_mgr *src = cinfo->src;
6499 our_memory_buffer[0] = (JOCTET) 0xFF;
6500 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6502 src->next_input_byte = our_memory_buffer;
6503 src->bytes_in_buffer = 2;
6504 return 1;
6508 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6509 is the JPEG data source manager. */
6511 static void
6512 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6514 struct jpeg_source_mgr *src = cinfo->src;
6516 if (src)
6518 if (num_bytes > src->bytes_in_buffer)
6519 ERREXIT (cinfo, JERR_INPUT_EOF);
6521 src->bytes_in_buffer -= num_bytes;
6522 src->next_input_byte += num_bytes;
6527 /* Set up the JPEG lib for reading an image from DATA which contains
6528 LEN bytes. CINFO is the decompression info structure created for
6529 reading the image. */
6531 static void
6532 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6534 struct jpeg_source_mgr *src = cinfo->src;
6536 if (! src)
6538 /* First time for this JPEG object? */
6539 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6540 JPOOL_PERMANENT, sizeof *src);
6541 cinfo->src = src;
6542 src->next_input_byte = data;
6545 src->init_source = our_common_init_source;
6546 src->fill_input_buffer = our_memory_fill_input_buffer;
6547 src->skip_input_data = our_memory_skip_input_data;
6548 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6549 src->term_source = our_common_term_source;
6550 src->bytes_in_buffer = len;
6551 src->next_input_byte = data;
6555 struct jpeg_stdio_mgr
6557 struct jpeg_source_mgr mgr;
6558 boolean finished;
6559 FILE *file;
6560 JOCTET *buffer;
6564 /* Size of buffer to read JPEG from file.
6565 Not too big, as we want to use alloc_small. */
6566 #define JPEG_STDIO_BUFFER_SIZE 8192
6569 /* Fill input buffer method for JPEG data source manager. Called
6570 whenever more data is needed. The data is read from a FILE *. */
6572 static boolean
6573 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6575 struct jpeg_stdio_mgr *src;
6577 src = (struct jpeg_stdio_mgr *) cinfo->src;
6578 if (!src->finished)
6580 ptrdiff_t bytes;
6582 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6583 if (bytes > 0)
6584 src->mgr.bytes_in_buffer = bytes;
6585 else
6587 WARNMS (cinfo, JWRN_JPEG_EOF);
6588 src->finished = 1;
6589 src->buffer[0] = (JOCTET) 0xFF;
6590 src->buffer[1] = (JOCTET) JPEG_EOI;
6591 src->mgr.bytes_in_buffer = 2;
6593 src->mgr.next_input_byte = src->buffer;
6596 return 1;
6600 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6601 is the JPEG data source manager. */
6603 static void
6604 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6606 struct jpeg_stdio_mgr *src;
6607 src = (struct jpeg_stdio_mgr *) cinfo->src;
6609 while (num_bytes > 0 && !src->finished)
6611 if (num_bytes <= src->mgr.bytes_in_buffer)
6613 src->mgr.bytes_in_buffer -= num_bytes;
6614 src->mgr.next_input_byte += num_bytes;
6615 break;
6617 else
6619 num_bytes -= src->mgr.bytes_in_buffer;
6620 src->mgr.bytes_in_buffer = 0;
6621 src->mgr.next_input_byte = NULL;
6623 our_stdio_fill_input_buffer (cinfo);
6629 /* Set up the JPEG lib for reading an image from a FILE *.
6630 CINFO is the decompression info structure created for
6631 reading the image. */
6633 static void
6634 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6636 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6638 if (! src)
6640 /* First time for this JPEG object? */
6641 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6642 JPOOL_PERMANENT, sizeof *src);
6643 cinfo->src = (struct jpeg_source_mgr *) src;
6644 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6645 JPOOL_PERMANENT,
6646 JPEG_STDIO_BUFFER_SIZE);
6649 src->file = fp;
6650 src->finished = 0;
6651 src->mgr.init_source = our_common_init_source;
6652 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6653 src->mgr.skip_input_data = our_stdio_skip_input_data;
6654 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6655 src->mgr.term_source = our_common_term_source;
6656 src->mgr.bytes_in_buffer = 0;
6657 src->mgr.next_input_byte = NULL;
6660 /* Load image IMG for use on frame F. Patterned after example.c
6661 from the JPEG lib. */
6663 static bool
6664 jpeg_load_body (struct frame *f, struct image *img,
6665 struct my_jpeg_error_mgr *mgr)
6667 Lisp_Object specified_file, specified_data;
6668 FILE *volatile fp = NULL;
6669 JSAMPARRAY buffer;
6670 int row_stride, x, y;
6671 unsigned long *colors;
6672 int width, height;
6673 int i, ir, ig, ib;
6674 #ifndef USE_CAIRO
6675 XImagePtr ximg = NULL;
6676 #endif
6678 /* Open the JPEG file. */
6679 specified_file = image_spec_value (img->spec, QCfile, NULL);
6680 specified_data = image_spec_value (img->spec, QCdata, NULL);
6682 if (NILP (specified_data))
6684 int fd;
6685 Lisp_Object file = x_find_image_fd (specified_file, &fd);
6686 if (!STRINGP (file))
6688 image_error ("Cannot find image file `%s'", specified_file);
6689 return 0;
6692 fp = fdopen (fd, "rb");
6693 if (fp == NULL)
6695 image_error ("Cannot open `%s'", file);
6696 return 0;
6699 else if (!STRINGP (specified_data))
6701 image_error ("Invalid image data `%s'", specified_data);
6702 return 0;
6705 /* Customize libjpeg's error handling to call my_error_exit when an
6706 error is detected. This function will perform a longjmp. */
6707 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6708 mgr->pub.error_exit = my_error_exit;
6709 if (sys_setjmp (mgr->setjmp_buffer))
6711 switch (mgr->failure_code)
6713 case MY_JPEG_ERROR_EXIT:
6715 char buf[JMSG_LENGTH_MAX];
6716 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6717 image_error ("Error reading JPEG image `%s': %s",
6718 img->spec, build_string (buf));
6719 break;
6722 case MY_JPEG_INVALID_IMAGE_SIZE:
6723 image_size_error ();
6724 break;
6726 case MY_JPEG_CANNOT_CREATE_X:
6727 break;
6730 /* Close the input file and destroy the JPEG object. */
6731 if (fp)
6732 fclose (fp);
6733 jpeg_destroy_decompress (&mgr->cinfo);
6735 /* If we already have an XImage, free that. */
6736 #ifndef USE_CAIRO
6737 x_destroy_x_image (ximg);
6738 #endif
6739 /* Free pixmap and colors. */
6740 x_clear_image (f, img);
6741 return 0;
6744 /* Create the JPEG decompression object. Let it read from fp.
6745 Read the JPEG image header. */
6746 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6748 if (NILP (specified_data))
6749 jpeg_file_src (&mgr->cinfo, fp);
6750 else
6751 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6752 SBYTES (specified_data));
6754 jpeg_read_header (&mgr->cinfo, 1);
6756 /* Customize decompression so that color quantization will be used.
6757 Start decompression. */
6758 mgr->cinfo.quantize_colors = 1;
6759 jpeg_start_decompress (&mgr->cinfo);
6760 width = img->width = mgr->cinfo.output_width;
6761 height = img->height = mgr->cinfo.output_height;
6763 if (!check_image_size (f, width, height))
6765 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6766 sys_longjmp (mgr->setjmp_buffer, 1);
6769 #ifndef USE_CAIRO
6770 /* Create X image and pixmap. */
6771 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6773 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6774 sys_longjmp (mgr->setjmp_buffer, 1);
6776 #endif
6778 /* Allocate colors. When color quantization is used,
6779 mgr->cinfo.actual_number_of_colors has been set with the number of
6780 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6781 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6782 No more than 255 colors will be generated. */
6783 USE_SAFE_ALLOCA;
6785 if (mgr->cinfo.out_color_components > 2)
6786 ir = 0, ig = 1, ib = 2;
6787 else if (mgr->cinfo.out_color_components > 1)
6788 ir = 0, ig = 1, ib = 0;
6789 else
6790 ir = 0, ig = 0, ib = 0;
6792 #ifndef CAIRO
6793 /* Use the color table mechanism because it handles colors that
6794 cannot be allocated nicely. Such colors will be replaced with
6795 a default color, and we don't have to care about which colors
6796 can be freed safely, and which can't. */
6797 init_color_table ();
6798 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6800 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6802 /* Multiply RGB values with 255 because X expects RGB values
6803 in the range 0..0xffff. */
6804 int r = mgr->cinfo.colormap[ir][i] << 8;
6805 int g = mgr->cinfo.colormap[ig][i] << 8;
6806 int b = mgr->cinfo.colormap[ib][i] << 8;
6807 colors[i] = lookup_rgb_color (f, r, g, b);
6809 #endif
6811 #ifdef COLOR_TABLE_SUPPORT
6812 /* Remember those colors actually allocated. */
6813 img->colors = colors_in_color_table (&img->ncolors);
6814 free_color_table ();
6815 #endif /* COLOR_TABLE_SUPPORT */
6818 /* Read pixels. */
6819 row_stride = width * mgr->cinfo.output_components;
6820 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6821 JPOOL_IMAGE, row_stride, 1);
6822 #ifdef USE_CAIRO
6824 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
6825 uint32_t *dataptr = (uint32_t *) data;
6826 int r, g, b;
6828 for (y = 0; y < height; ++y)
6830 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6832 for (x = 0; x < width; ++x)
6834 i = buffer[0][x];
6835 r = mgr->cinfo.colormap[ir][i];
6836 g = mgr->cinfo.colormap[ig][i];
6837 b = mgr->cinfo.colormap[ib][i];
6838 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
6842 create_cairo_image_surface (img, data, width, height);
6844 #else
6845 for (y = 0; y < height; ++y)
6847 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6848 for (x = 0; x < mgr->cinfo.output_width; ++x)
6849 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6851 #endif
6853 /* Clean up. */
6854 jpeg_finish_decompress (&mgr->cinfo);
6855 jpeg_destroy_decompress (&mgr->cinfo);
6856 if (fp)
6857 fclose (fp);
6859 #ifndef USE_CAIRO
6860 /* Maybe fill in the background field while we have ximg handy. */
6861 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6862 /* Casting avoids a GCC warning. */
6863 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6865 /* Put ximg into the image. */
6866 image_put_x_image (f, img, ximg, 0);
6867 #endif
6868 SAFE_FREE ();
6869 return 1;
6872 static bool
6873 jpeg_load (struct frame *f, struct image *img)
6875 struct my_jpeg_error_mgr mgr;
6876 return jpeg_load_body (f, img, &mgr);
6879 #else /* HAVE_JPEG */
6881 #ifdef HAVE_NS
6882 static bool
6883 jpeg_load (struct frame *f, struct image *img)
6885 return ns_load_image (f, img,
6886 image_spec_value (img->spec, QCfile, NULL),
6887 image_spec_value (img->spec, QCdata, NULL));
6889 #endif /* HAVE_NS */
6891 #endif /* !HAVE_JPEG */
6895 /***********************************************************************
6896 TIFF
6897 ***********************************************************************/
6899 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6901 static bool tiff_image_p (Lisp_Object object);
6902 static bool tiff_load (struct frame *f, struct image *img);
6904 /* Indices of image specification fields in tiff_format, below. */
6906 enum tiff_keyword_index
6908 TIFF_TYPE,
6909 TIFF_DATA,
6910 TIFF_FILE,
6911 TIFF_ASCENT,
6912 TIFF_MARGIN,
6913 TIFF_RELIEF,
6914 TIFF_ALGORITHM,
6915 TIFF_HEURISTIC_MASK,
6916 TIFF_MASK,
6917 TIFF_BACKGROUND,
6918 TIFF_INDEX,
6919 TIFF_LAST
6922 /* Vector of image_keyword structures describing the format
6923 of valid user-defined image specifications. */
6925 static const struct image_keyword tiff_format[TIFF_LAST] =
6927 {":type", IMAGE_SYMBOL_VALUE, 1},
6928 {":data", IMAGE_STRING_VALUE, 0},
6929 {":file", IMAGE_STRING_VALUE, 0},
6930 {":ascent", IMAGE_ASCENT_VALUE, 0},
6931 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6932 {":relief", IMAGE_INTEGER_VALUE, 0},
6933 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6934 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6935 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6936 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6937 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6940 #if defined HAVE_NTGUI && defined WINDOWSNT
6941 static bool init_tiff_functions (void);
6942 #else
6943 #define init_tiff_functions NULL
6944 #endif
6946 /* Structure describing the image type `tiff'. */
6948 static struct image_type tiff_type =
6950 SYMBOL_INDEX (Qtiff),
6951 tiff_image_p,
6952 tiff_load,
6953 x_clear_image,
6954 init_tiff_functions,
6955 NULL
6958 /* Return true if OBJECT is a valid TIFF image specification. */
6960 static bool
6961 tiff_image_p (Lisp_Object object)
6963 struct image_keyword fmt[TIFF_LAST];
6964 memcpy (fmt, tiff_format, sizeof fmt);
6966 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6967 return 0;
6969 /* Must specify either the :data or :file keyword. */
6970 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6973 #endif /* HAVE_TIFF || HAVE_NS */
6975 #ifdef HAVE_TIFF
6977 # include <tiffio.h>
6979 # ifdef WINDOWSNT
6981 /* TIFF library details. */
6982 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6983 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6984 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
6985 DEF_DLL_FN (TIFF *, TIFFClientOpen,
6986 (const char *, const char *, thandle_t, TIFFReadWriteProc,
6987 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6988 TIFFMapFileProc, TIFFUnmapFileProc));
6989 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6990 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6991 DEF_DLL_FN (void, TIFFClose, (TIFF *));
6992 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6994 static bool
6995 init_tiff_functions (void)
6997 HMODULE library;
6999 if (!(library = w32_delayed_load (Qtiff)))
7000 return 0;
7002 LOAD_DLL_FN (library, TIFFSetErrorHandler);
7003 LOAD_DLL_FN (library, TIFFSetWarningHandler);
7004 LOAD_DLL_FN (library, TIFFOpen);
7005 LOAD_DLL_FN (library, TIFFClientOpen);
7006 LOAD_DLL_FN (library, TIFFGetField);
7007 LOAD_DLL_FN (library, TIFFReadRGBAImage);
7008 LOAD_DLL_FN (library, TIFFClose);
7009 LOAD_DLL_FN (library, TIFFSetDirectory);
7010 return 1;
7013 # undef TIFFClientOpen
7014 # undef TIFFClose
7015 # undef TIFFGetField
7016 # undef TIFFOpen
7017 # undef TIFFReadRGBAImage
7018 # undef TIFFSetDirectory
7019 # undef TIFFSetErrorHandler
7020 # undef TIFFSetWarningHandler
7022 # define TIFFClientOpen fn_TIFFClientOpen
7023 # define TIFFClose fn_TIFFClose
7024 # define TIFFGetField fn_TIFFGetField
7025 # define TIFFOpen fn_TIFFOpen
7026 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7027 # define TIFFSetDirectory fn_TIFFSetDirectory
7028 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7029 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7031 # endif /* WINDOWSNT */
7034 /* Reading from a memory buffer for TIFF images Based on the PNG
7035 memory source, but we have to provide a lot of extra functions.
7036 Blah.
7038 We really only need to implement read and seek, but I am not
7039 convinced that the TIFF library is smart enough not to destroy
7040 itself if we only hand it the function pointers we need to
7041 override. */
7043 typedef struct
7045 unsigned char *bytes;
7046 ptrdiff_t len;
7047 ptrdiff_t index;
7049 tiff_memory_source;
7051 static tsize_t
7052 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7054 tiff_memory_source *src = (tiff_memory_source *) data;
7056 size = min (size, src->len - src->index);
7057 memcpy (buf, src->bytes + src->index, size);
7058 src->index += size;
7059 return size;
7062 static tsize_t
7063 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7065 return -1;
7068 static toff_t
7069 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
7071 tiff_memory_source *src = (tiff_memory_source *) data;
7072 ptrdiff_t idx;
7074 switch (whence)
7076 case SEEK_SET: /* Go from beginning of source. */
7077 idx = off;
7078 break;
7080 case SEEK_END: /* Go from end of source. */
7081 idx = src->len + off;
7082 break;
7084 case SEEK_CUR: /* Go from current position. */
7085 idx = src->index + off;
7086 break;
7088 default: /* Invalid `whence'. */
7089 return -1;
7092 if (idx > src->len || idx < 0)
7093 return -1;
7095 src->index = idx;
7096 return src->index;
7099 static int
7100 tiff_close_memory (thandle_t data)
7102 /* NOOP */
7103 return 0;
7106 static int
7107 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
7109 /* It is already _IN_ memory. */
7110 return 0;
7113 static void
7114 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
7116 /* We don't need to do this. */
7119 static toff_t
7120 tiff_size_of_memory (thandle_t data)
7122 return ((tiff_memory_source *) data)->len;
7125 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7126 compiler error compiling tiff_handler, see Bugzilla bug #17406
7127 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7128 this function as external works around that problem. */
7129 # if defined (__MINGW32__) && __GNUC__ == 3
7130 # define MINGW_STATIC
7131 # else
7132 # define MINGW_STATIC static
7133 # endif
7135 MINGW_STATIC void
7136 tiff_handler (const char *, const char *, const char *, va_list)
7137 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7138 MINGW_STATIC void
7139 tiff_handler (const char *log_format, const char *title,
7140 const char *format, va_list ap)
7142 /* doprnt is not suitable here, as TIFF handlers are called from
7143 libtiff and are passed arbitrary printf directives. Instead, use
7144 vsnprintf, taking care to be portable to nonstandard environments
7145 where vsnprintf returns -1 on buffer overflow. Since it's just a
7146 log entry, it's OK to truncate it. */
7147 char buf[4000];
7148 int len = vsnprintf (buf, sizeof buf, format, ap);
7149 add_to_log (log_format, build_string (title),
7150 make_string (buf, max (0, min (len, sizeof buf - 1))));
7152 # undef MINGW_STATIC
7154 static void tiff_error_handler (const char *, const char *, va_list)
7155 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7156 static void
7157 tiff_error_handler (const char *title, const char *format, va_list ap)
7159 tiff_handler ("TIFF error: %s %s", title, format, ap);
7163 static void tiff_warning_handler (const char *, const char *, va_list)
7164 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7165 static void
7166 tiff_warning_handler (const char *title, const char *format, va_list ap)
7168 tiff_handler ("TIFF warning: %s %s", title, format, ap);
7172 /* Load TIFF image IMG for use on frame F. Value is true if
7173 successful. */
7175 static bool
7176 tiff_load (struct frame *f, struct image *img)
7178 Lisp_Object specified_file;
7179 Lisp_Object specified_data;
7180 TIFF *tiff;
7181 int width, height, x, y, count;
7182 uint32 *buf;
7183 int rc;
7184 XImagePtr ximg;
7185 tiff_memory_source memsrc;
7186 Lisp_Object image;
7188 specified_file = image_spec_value (img->spec, QCfile, NULL);
7189 specified_data = image_spec_value (img->spec, QCdata, NULL);
7191 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
7192 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7194 if (NILP (specified_data))
7196 /* Read from a file */
7197 Lisp_Object file = x_find_image_file (specified_file);
7198 if (!STRINGP (file))
7200 image_error ("Cannot find image file `%s'", specified_file);
7201 return 0;
7204 Lisp_Object encoded_file = ENCODE_FILE (file);
7205 # ifdef WINDOWSNT
7206 encoded_file = ansi_encode_filename (encoded_file);
7207 # endif
7209 /* Try to open the image file. */
7210 tiff = TIFFOpen (SSDATA (encoded_file), "r");
7211 if (tiff == NULL)
7213 image_error ("Cannot open `%s'", file);
7214 return 0;
7217 else
7219 if (!STRINGP (specified_data))
7221 image_error ("Invalid image data `%s'", specified_data);
7222 return 0;
7225 /* Memory source! */
7226 memsrc.bytes = SDATA (specified_data);
7227 memsrc.len = SBYTES (specified_data);
7228 memsrc.index = 0;
7230 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7231 tiff_read_from_memory,
7232 tiff_write_from_memory,
7233 tiff_seek_in_memory,
7234 tiff_close_memory,
7235 tiff_size_of_memory,
7236 tiff_mmap_memory,
7237 tiff_unmap_memory);
7239 if (!tiff)
7241 image_error ("Cannot open memory source for `%s'", img->spec);
7242 return 0;
7246 image = image_spec_value (img->spec, QCindex, NULL);
7247 if (INTEGERP (image))
7249 EMACS_INT ino = XFASTINT (image);
7250 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7251 && TIFFSetDirectory (tiff, ino)))
7253 image_error ("Invalid image number `%s' in image `%s'",
7254 image, img->spec);
7255 TIFFClose (tiff);
7256 return 0;
7260 /* Get width and height of the image, and allocate a raster buffer
7261 of width x height 32-bit values. */
7262 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7263 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7265 if (!check_image_size (f, width, height))
7267 image_size_error ();
7268 TIFFClose (tiff);
7269 return 0;
7272 /* Create the X image and pixmap. */
7273 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7274 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7275 &ximg, 0)))
7277 TIFFClose (tiff);
7278 return 0;
7281 buf = xmalloc (sizeof *buf * width * height);
7283 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7285 /* Count the number of images in the file. */
7286 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7287 continue;
7289 if (count > 1)
7290 img->lisp_data = Fcons (Qcount,
7291 Fcons (make_number (count),
7292 img->lisp_data));
7294 TIFFClose (tiff);
7295 if (!rc)
7297 image_error ("Error reading TIFF image `%s'", img->spec);
7298 xfree (buf);
7299 return 0;
7302 #ifdef USE_CAIRO
7304 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
7305 uint32_t *dataptr = (uint32_t *) data;
7307 for (y = 0; y < height; ++y)
7309 uint32 *row = buf + (height - 1 - y) * width;
7310 for (x = 0; x < width; ++x)
7312 uint32 abgr = row[x];
7313 int r = TIFFGetR (abgr);
7314 int g = TIFFGetG (abgr);
7315 int b = TIFFGetB (abgr);
7316 int a = TIFFGetA (abgr);
7317 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
7321 create_cairo_image_surface (img, data, width, height);
7323 #else
7324 /* Initialize the color table. */
7325 init_color_table ();
7327 /* Process the pixel raster. Origin is in the lower-left corner. */
7328 for (y = 0; y < height; ++y)
7330 uint32 *row = buf + y * width;
7332 for (x = 0; x < width; ++x)
7334 uint32 abgr = row[x];
7335 int r = TIFFGetR (abgr) << 8;
7336 int g = TIFFGetG (abgr) << 8;
7337 int b = TIFFGetB (abgr) << 8;
7338 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7342 # ifdef COLOR_TABLE_SUPPORT
7343 /* Remember the colors allocated for the image. Free the color table. */
7344 img->colors = colors_in_color_table (&img->ncolors);
7345 free_color_table ();
7346 # endif /* COLOR_TABLE_SUPPORT */
7348 img->width = width;
7349 img->height = height;
7351 /* Maybe fill in the background field while we have ximg handy. */
7352 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7353 /* Casting avoids a GCC warning on W32. */
7354 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7356 /* Put ximg into the image. */
7357 image_put_x_image (f, img, ximg, 0);
7359 #endif /* ! USE_CAIRO */
7361 xfree (buf);
7362 return 1;
7365 #elif defined HAVE_NS
7367 static bool
7368 tiff_load (struct frame *f, struct image *img)
7370 return ns_load_image (f, img,
7371 image_spec_value (img->spec, QCfile, NULL),
7372 image_spec_value (img->spec, QCdata, NULL));
7375 #endif
7379 /***********************************************************************
7381 ***********************************************************************/
7383 #if defined (HAVE_GIF) || defined (HAVE_NS)
7385 static bool gif_image_p (Lisp_Object object);
7386 static bool gif_load (struct frame *f, struct image *img);
7387 static void gif_clear_image (struct frame *f, struct image *img);
7389 /* Indices of image specification fields in gif_format, below. */
7391 enum gif_keyword_index
7393 GIF_TYPE,
7394 GIF_DATA,
7395 GIF_FILE,
7396 GIF_ASCENT,
7397 GIF_MARGIN,
7398 GIF_RELIEF,
7399 GIF_ALGORITHM,
7400 GIF_HEURISTIC_MASK,
7401 GIF_MASK,
7402 GIF_IMAGE,
7403 GIF_BACKGROUND,
7404 GIF_LAST
7407 /* Vector of image_keyword structures describing the format
7408 of valid user-defined image specifications. */
7410 static const struct image_keyword gif_format[GIF_LAST] =
7412 {":type", IMAGE_SYMBOL_VALUE, 1},
7413 {":data", IMAGE_STRING_VALUE, 0},
7414 {":file", IMAGE_STRING_VALUE, 0},
7415 {":ascent", IMAGE_ASCENT_VALUE, 0},
7416 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7417 {":relief", IMAGE_INTEGER_VALUE, 0},
7418 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7419 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7420 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7421 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7422 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7425 #if defined HAVE_NTGUI && defined WINDOWSNT
7426 static bool init_gif_functions (void);
7427 #else
7428 #define init_gif_functions NULL
7429 #endif
7431 /* Structure describing the image type `gif'. */
7433 static struct image_type gif_type =
7435 SYMBOL_INDEX (Qgif),
7436 gif_image_p,
7437 gif_load,
7438 gif_clear_image,
7439 init_gif_functions,
7440 NULL
7443 /* Free X resources of GIF image IMG which is used on frame F. */
7445 static void
7446 gif_clear_image (struct frame *f, struct image *img)
7448 img->lisp_data = Qnil;
7449 x_clear_image (f, img);
7452 /* Return true if OBJECT is a valid GIF image specification. */
7454 static bool
7455 gif_image_p (Lisp_Object object)
7457 struct image_keyword fmt[GIF_LAST];
7458 memcpy (fmt, gif_format, sizeof fmt);
7460 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7461 return 0;
7463 /* Must specify either the :data or :file keyword. */
7464 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7467 #endif /* HAVE_GIF */
7469 #ifdef HAVE_GIF
7471 # ifdef HAVE_NTGUI
7473 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7474 Undefine before redefining to avoid a preprocessor warning. */
7475 # ifdef DrawText
7476 # undef DrawText
7477 # endif
7478 /* avoid conflict with QuickdrawText.h */
7479 # define DrawText gif_DrawText
7480 # include <gif_lib.h>
7481 # undef DrawText
7483 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7484 # ifndef GIFLIB_MINOR
7485 # define GIFLIB_MINOR 0
7486 # endif
7487 # ifndef GIFLIB_RELEASE
7488 # define GIFLIB_RELEASE 0
7489 # endif
7491 # else /* HAVE_NTGUI */
7493 # include <gif_lib.h>
7495 # endif /* HAVE_NTGUI */
7497 /* Giflib before 5.0 didn't define these macros. */
7498 # ifndef GIFLIB_MAJOR
7499 # define GIFLIB_MAJOR 4
7500 # endif
7502 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7503 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7504 earlier releases, where either it returns char * or GIFLIB_MINOR
7505 may be incorrect. */
7506 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7508 # ifdef WINDOWSNT
7510 /* GIF library details. */
7511 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7512 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7513 # else
7514 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7515 # endif
7516 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7517 # if GIFLIB_MAJOR < 5
7518 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7519 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7520 # else
7521 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7522 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7523 # endif
7524 # if HAVE_GIFERRORSTRING
7525 DEF_DLL_FN (char const *, GifErrorString, (int));
7526 # endif
7528 static bool
7529 init_gif_functions (void)
7531 HMODULE library;
7533 if (!(library = w32_delayed_load (Qgif)))
7534 return 0;
7536 LOAD_DLL_FN (library, DGifCloseFile);
7537 LOAD_DLL_FN (library, DGifSlurp);
7538 LOAD_DLL_FN (library, DGifOpen);
7539 LOAD_DLL_FN (library, DGifOpenFileName);
7540 # if HAVE_GIFERRORSTRING
7541 LOAD_DLL_FN (library, GifErrorString);
7542 # endif
7543 return 1;
7546 # undef DGifCloseFile
7547 # undef DGifOpen
7548 # undef DGifOpenFileName
7549 # undef DGifSlurp
7550 # undef GifErrorString
7552 # define DGifCloseFile fn_DGifCloseFile
7553 # define DGifOpen fn_DGifOpen
7554 # define DGifOpenFileName fn_DGifOpenFileName
7555 # define DGifSlurp fn_DGifSlurp
7556 # define GifErrorString fn_GifErrorString
7558 # endif /* WINDOWSNT */
7560 /* Reading a GIF image from memory
7561 Based on the PNG memory stuff to a certain extent. */
7563 typedef struct
7565 unsigned char *bytes;
7566 ptrdiff_t len;
7567 ptrdiff_t index;
7569 gif_memory_source;
7571 /* Make the current memory source available to gif_read_from_memory.
7572 It's done this way because not all versions of libungif support
7573 a UserData field in the GifFileType structure. */
7574 static gif_memory_source *current_gif_memory_src;
7576 static int
7577 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7579 gif_memory_source *src = current_gif_memory_src;
7581 if (len > src->len - src->index)
7582 return -1;
7584 memcpy (buf, src->bytes + src->index, len);
7585 src->index += len;
7586 return len;
7589 static int
7590 gif_close (GifFileType *gif, int *err)
7592 int retval;
7594 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7595 retval = DGifCloseFile (gif, err);
7596 #else
7597 retval = DGifCloseFile (gif);
7598 #if GIFLIB_MAJOR >= 5
7599 if (err)
7600 *err = gif->Error;
7601 #endif
7602 #endif
7603 return retval;
7606 /* Load GIF image IMG for use on frame F. Value is true if
7607 successful. */
7609 static const int interlace_start[] = {0, 4, 2, 1};
7610 static const int interlace_increment[] = {8, 8, 4, 2};
7612 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7614 static bool
7615 gif_load (struct frame *f, struct image *img)
7617 int rc, width, height, x, y, i, j;
7618 ColorMapObject *gif_color_map;
7619 GifFileType *gif;
7620 gif_memory_source memsrc;
7621 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7622 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7623 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7624 EMACS_INT idx;
7625 int gif_err;
7627 #ifdef USE_CAIRO
7628 unsigned char *data = 0;
7629 #else
7630 unsigned long pixel_colors[256];
7631 unsigned long bgcolor = 0;
7632 XImagePtr ximg;
7633 #endif
7635 if (NILP (specified_data))
7637 Lisp_Object file = x_find_image_file (specified_file);
7638 if (!STRINGP (file))
7640 image_error ("Cannot find image file `%s'", specified_file);
7641 return 0;
7644 Lisp_Object encoded_file = ENCODE_FILE (file);
7645 #ifdef WINDOWSNT
7646 encoded_file = ansi_encode_filename (encoded_file);
7647 #endif
7649 /* Open the GIF file. */
7650 #if GIFLIB_MAJOR < 5
7651 gif = DGifOpenFileName (SSDATA (encoded_file));
7652 #else
7653 gif = DGifOpenFileName (SSDATA (encoded_file), &gif_err);
7654 #endif
7655 if (gif == NULL)
7657 #if HAVE_GIFERRORSTRING
7658 image_error ("Cannot open `%s': %s",
7659 file, build_string (GifErrorString (gif_err)));
7660 #else
7661 image_error ("Cannot open `%s'", file);
7662 #endif
7663 return 0;
7666 else
7668 if (!STRINGP (specified_data))
7670 image_error ("Invalid image data `%s'", specified_data);
7671 return 0;
7674 /* Read from memory! */
7675 current_gif_memory_src = &memsrc;
7676 memsrc.bytes = SDATA (specified_data);
7677 memsrc.len = SBYTES (specified_data);
7678 memsrc.index = 0;
7680 #if GIFLIB_MAJOR < 5
7681 gif = DGifOpen (&memsrc, gif_read_from_memory);
7682 #else
7683 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7684 #endif
7685 if (!gif)
7687 #if HAVE_GIFERRORSTRING
7688 image_error ("Cannot open memory source `%s': %s",
7689 img->spec, build_string (GifErrorString (gif_err)));
7690 #else
7691 image_error ("Cannot open memory source `%s'", img->spec);
7692 #endif
7693 return 0;
7697 /* Before reading entire contents, check the declared image size. */
7698 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7700 image_size_error ();
7701 gif_close (gif, NULL);
7702 return 0;
7705 /* Read entire contents. */
7706 rc = DGifSlurp (gif);
7707 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7709 image_error ("Error reading `%s'", img->spec);
7710 gif_close (gif, NULL);
7711 return 0;
7714 /* Which sub-image are we to display? */
7716 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7717 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7718 if (idx < 0 || idx >= gif->ImageCount)
7720 image_error ("Invalid image number `%s' in image `%s'",
7721 image_number, img->spec);
7722 gif_close (gif, NULL);
7723 return 0;
7727 width = img->width = gif->SWidth;
7728 height = img->height = gif->SHeight;
7730 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7731 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7732 img->corners[BOT_CORNER]
7733 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7734 img->corners[RIGHT_CORNER]
7735 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7737 if (!check_image_size (f, width, height))
7739 image_size_error ();
7740 gif_close (gif, NULL);
7741 return 0;
7744 /* Check that the selected subimages fit. It's not clear whether
7745 the GIF spec requires this, but Emacs can crash if they don't fit. */
7746 for (j = 0; j <= idx; ++j)
7748 struct SavedImage *subimage = gif->SavedImages + j;
7749 int subimg_width = subimage->ImageDesc.Width;
7750 int subimg_height = subimage->ImageDesc.Height;
7751 int subimg_top = subimage->ImageDesc.Top;
7752 int subimg_left = subimage->ImageDesc.Left;
7753 if (! (subimg_width >= 0 && subimg_height >= 0
7754 && 0 <= subimg_top && subimg_top <= height - subimg_height
7755 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7757 image_error ("Subimage does not fit in image");
7758 gif_close (gif, NULL);
7759 return 0;
7763 #ifdef USE_CAIRO
7764 /* xzalloc so data is zero => transparent */
7765 data = (unsigned char *) xzalloc (width * height * 4);
7766 if (STRINGP (specified_bg))
7768 XColor color;
7769 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
7771 uint32_t *dataptr = (uint32_t *)data;
7772 int r = color.red/256;
7773 int g = color.green/256;
7774 int b = color.blue/256;
7776 for (y = 0; y < height; ++y)
7777 for (x = 0; x < width; ++x)
7778 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
7781 #else
7782 /* Create the X image and pixmap. */
7783 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7785 gif_close (gif, NULL);
7786 return 0;
7789 /* Clear the part of the screen image not covered by the image.
7790 Full animated GIF support requires more here (see the gif89 spec,
7791 disposal methods). Let's simply assume that the part not covered
7792 by a sub-image is in the frame's background color. */
7793 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7794 for (x = 0; x < width; ++x)
7795 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7797 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7798 for (x = 0; x < width; ++x)
7799 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7801 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7803 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7804 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7805 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7806 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7808 #endif
7810 /* Read the GIF image into the X image. */
7812 /* FIXME: With the current implementation, loading an animated gif
7813 is quadratic in the number of animation frames, since each frame
7814 is a separate struct image. We must provide a way for a single
7815 gif_load call to construct and save all animation frames. */
7817 init_color_table ();
7819 #ifndef USE_CAIRO
7820 if (STRINGP (specified_bg))
7821 bgcolor = x_alloc_image_color (f, img, specified_bg,
7822 FRAME_BACKGROUND_PIXEL (f));
7823 #endif
7825 for (j = 0; j <= idx; ++j)
7827 /* We use a local variable `raster' here because RasterBits is a
7828 char *, which invites problems with bytes >= 0x80. */
7829 struct SavedImage *subimage = gif->SavedImages + j;
7830 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7831 int transparency_color_index = -1;
7832 int disposal = 0;
7833 int subimg_width = subimage->ImageDesc.Width;
7834 int subimg_height = subimage->ImageDesc.Height;
7835 int subimg_top = subimage->ImageDesc.Top;
7836 int subimg_left = subimage->ImageDesc.Left;
7838 /* Find the Graphic Control Extension block for this sub-image.
7839 Extract the disposal method and transparency color. */
7840 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7842 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7844 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7845 && extblock->ByteCount == 4
7846 && extblock->Bytes[0] & 1)
7848 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7849 to background". Treat any other value like 2. */
7850 disposal = (extblock->Bytes[0] >> 2) & 7;
7851 transparency_color_index = (unsigned char) extblock->Bytes[3];
7852 break;
7856 /* We can't "keep in place" the first subimage. */
7857 if (j == 0)
7858 disposal = 2;
7860 /* For disposal == 0, the spec says "No disposal specified. The
7861 decoder is not required to take any action." In practice, it
7862 seems we need to treat this like "keep in place", see e.g.
7863 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7864 if (disposal == 0)
7865 disposal = 1;
7867 gif_color_map = subimage->ImageDesc.ColorMap;
7868 if (!gif_color_map)
7869 gif_color_map = gif->SColorMap;
7871 #ifndef USE_CAIRO
7872 /* Allocate subimage colors. */
7873 memset (pixel_colors, 0, sizeof pixel_colors);
7875 if (gif_color_map)
7876 for (i = 0; i < gif_color_map->ColorCount; ++i)
7878 if (transparency_color_index == i)
7879 pixel_colors[i] = STRINGP (specified_bg)
7880 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7881 else
7883 int r = gif_color_map->Colors[i].Red << 8;
7884 int g = gif_color_map->Colors[i].Green << 8;
7885 int b = gif_color_map->Colors[i].Blue << 8;
7886 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7889 #endif
7891 /* Apply the pixel values. */
7892 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7894 int row, pass;
7896 for (y = 0, row = interlace_start[0], pass = 0;
7897 y < subimg_height;
7898 y++, row += interlace_increment[pass])
7900 while (subimg_height <= row)
7901 row = interlace_start[++pass];
7903 for (x = 0; x < subimg_width; x++)
7905 int c = raster[y * subimg_width + x];
7906 if (transparency_color_index != c || disposal != 1)
7908 #ifdef USE_CAIRO
7909 uint32_t *dataptr =
7910 ((uint32_t*)data + ((row + subimg_top) * subimg_width
7911 + x + subimg_left));
7912 int r = gif_color_map->Colors[c].Red;
7913 int g = gif_color_map->Colors[c].Green;
7914 int b = gif_color_map->Colors[c].Blue;
7916 if (transparency_color_index != c)
7917 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7918 #else
7919 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7920 pixel_colors[c]);
7921 #endif
7926 else
7928 for (y = 0; y < subimg_height; ++y)
7929 for (x = 0; x < subimg_width; ++x)
7931 int c = raster[y * subimg_width + x];
7932 if (transparency_color_index != c || disposal != 1)
7934 #ifdef USE_CAIRO
7935 uint32_t *dataptr =
7936 ((uint32_t*)data + ((y + subimg_top) * subimg_width
7937 + x + subimg_left));
7938 int r = gif_color_map->Colors[c].Red;
7939 int g = gif_color_map->Colors[c].Green;
7940 int b = gif_color_map->Colors[c].Blue;
7941 if (transparency_color_index != c)
7942 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7943 #else
7944 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7945 pixel_colors[c]);
7946 #endif
7952 #ifdef COLOR_TABLE_SUPPORT
7953 img->colors = colors_in_color_table (&img->ncolors);
7954 free_color_table ();
7955 #endif /* COLOR_TABLE_SUPPORT */
7957 /* Save GIF image extension data for `image-metadata'.
7958 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7959 img->lisp_data = Qnil;
7960 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7962 int delay = 0;
7963 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7964 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7965 /* Append (... FUNCTION "BYTES") */
7967 img->lisp_data
7968 = Fcons (make_number (ext->Function),
7969 Fcons (make_unibyte_string ((char *) ext->Bytes,
7970 ext->ByteCount),
7971 img->lisp_data));
7972 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7973 && ext->ByteCount == 4)
7975 delay = ext->Bytes[2] << CHAR_BIT;
7976 delay |= ext->Bytes[1];
7979 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7980 if (delay)
7981 img->lisp_data
7982 = Fcons (Qdelay,
7983 Fcons (make_float (delay / 100.0),
7984 img->lisp_data));
7987 if (gif->ImageCount > 1)
7988 img->lisp_data = Fcons (Qcount,
7989 Fcons (make_number (gif->ImageCount),
7990 img->lisp_data));
7992 if (gif_close (gif, &gif_err) == GIF_ERROR)
7994 #if HAVE_GIFERRORSTRING
7995 char const *error_text = GifErrorString (gif_err);
7997 if (error_text)
7998 image_error ("Error closing `%s': %s",
7999 img->spec, build_string (error_text));
8000 #else
8001 image_error ("Error closing `%s'", img->spec);
8002 #endif
8005 #ifdef USE_CAIRO
8006 create_cairo_image_surface (img, data, width, height);
8007 #else
8008 /* Maybe fill in the background field while we have ximg handy. */
8009 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8010 /* Casting avoids a GCC warning. */
8011 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8013 /* Put ximg into the image. */
8014 image_put_x_image (f, img, ximg, 0);
8015 #endif
8017 return 1;
8020 #else /* !HAVE_GIF */
8022 #ifdef HAVE_NS
8023 static bool
8024 gif_load (struct frame *f, struct image *img)
8026 return ns_load_image (f, img,
8027 image_spec_value (img->spec, QCfile, NULL),
8028 image_spec_value (img->spec, QCdata, NULL));
8030 #endif /* HAVE_NS */
8032 #endif /* HAVE_GIF */
8035 #ifdef HAVE_IMAGEMAGICK
8037 /***********************************************************************
8038 ImageMagick
8039 ***********************************************************************/
8041 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8042 safely rounded and clipped to int range. */
8044 static int
8045 scale_image_size (int size, size_t divisor, size_t multiplier)
8047 if (divisor != 0)
8049 double s = size;
8050 double scaled = s * multiplier / divisor + 0.5;
8051 if (scaled < INT_MAX)
8052 return scaled;
8054 return INT_MAX;
8057 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8058 Use SPEC to deduce the size. Store the desired size into
8059 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8060 static void
8061 compute_image_size (size_t width, size_t height,
8062 Lisp_Object spec,
8063 int *d_width, int *d_height)
8065 Lisp_Object value;
8066 int desired_width, desired_height;
8067 double scale = 1;
8069 value = image_spec_value (spec, QCscale, NULL);
8070 if (NUMBERP (value))
8071 scale = extract_float (value);
8073 /* If width and/or height is set in the display spec assume we want
8074 to scale to those values. If either h or w is unspecified, the
8075 unspecified should be calculated from the specified to preserve
8076 aspect ratio. */
8077 value = image_spec_value (spec, QCwidth, NULL);
8078 desired_width = NATNUMP (value) ?
8079 min (XFASTINT (value) * scale, INT_MAX) : -1;
8080 value = image_spec_value (spec, QCheight, NULL);
8081 desired_height = NATNUMP (value) ?
8082 min (XFASTINT (value) * scale, INT_MAX) : -1;
8084 width = width * scale;
8085 height = height * scale;
8087 if (desired_width == -1)
8089 value = image_spec_value (spec, QCmax_width, NULL);
8090 if (NATNUMP (value))
8092 int max_width = min (XFASTINT (value), INT_MAX);
8093 if (max_width < width)
8095 /* The image is wider than :max-width. */
8096 desired_width = max_width;
8097 if (desired_height == -1)
8099 desired_height = scale_image_size (desired_width,
8100 width, height);
8101 value = image_spec_value (spec, QCmax_height, NULL);
8102 if (NATNUMP (value))
8104 int max_height = min (XFASTINT (value), INT_MAX);
8105 if (max_height < desired_height)
8107 desired_height = max_height;
8108 desired_width = scale_image_size (desired_height,
8109 height, width);
8117 if (desired_height == -1)
8119 value = image_spec_value (spec, QCmax_height, NULL);
8120 if (NATNUMP (value))
8122 int max_height = min (XFASTINT (value), INT_MAX);
8123 if (max_height < height)
8124 desired_height = max_height;
8128 if (desired_width != -1 && desired_height == -1)
8129 /* w known, calculate h. */
8130 desired_height = scale_image_size (desired_width, width, height);
8132 if (desired_width == -1 && desired_height != -1)
8133 /* h known, calculate w. */
8134 desired_width = scale_image_size (desired_height, height, width);
8136 /* We have no width/height settings, so just apply the scale. */
8137 if (desired_width == -1 && desired_height == -1)
8139 desired_width = width;
8140 desired_height = height;
8143 *d_width = desired_width;
8144 *d_height = desired_height;
8147 static bool imagemagick_image_p (Lisp_Object);
8148 static bool imagemagick_load (struct frame *, struct image *);
8149 static void imagemagick_clear_image (struct frame *, struct image *);
8151 /* Indices of image specification fields in imagemagick_format. */
8153 enum imagemagick_keyword_index
8155 IMAGEMAGICK_TYPE,
8156 IMAGEMAGICK_DATA,
8157 IMAGEMAGICK_FILE,
8158 IMAGEMAGICK_ASCENT,
8159 IMAGEMAGICK_MARGIN,
8160 IMAGEMAGICK_RELIEF,
8161 IMAGEMAGICK_ALGORITHM,
8162 IMAGEMAGICK_HEURISTIC_MASK,
8163 IMAGEMAGICK_MASK,
8164 IMAGEMAGICK_BACKGROUND,
8165 IMAGEMAGICK_HEIGHT,
8166 IMAGEMAGICK_WIDTH,
8167 IMAGEMAGICK_MAX_HEIGHT,
8168 IMAGEMAGICK_MAX_WIDTH,
8169 IMAGEMAGICK_FORMAT,
8170 IMAGEMAGICK_ROTATION,
8171 IMAGEMAGICK_CROP,
8172 IMAGEMAGICK_LAST
8175 /* Vector of image_keyword structures describing the format
8176 of valid user-defined image specifications. */
8178 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
8180 {":type", IMAGE_SYMBOL_VALUE, 1},
8181 {":data", IMAGE_STRING_VALUE, 0},
8182 {":file", IMAGE_STRING_VALUE, 0},
8183 {":ascent", IMAGE_ASCENT_VALUE, 0},
8184 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8185 {":relief", IMAGE_INTEGER_VALUE, 0},
8186 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8187 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8188 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8189 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8190 {":height", IMAGE_INTEGER_VALUE, 0},
8191 {":width", IMAGE_INTEGER_VALUE, 0},
8192 {":max-height", IMAGE_INTEGER_VALUE, 0},
8193 {":max-width", IMAGE_INTEGER_VALUE, 0},
8194 {":format", IMAGE_SYMBOL_VALUE, 0},
8195 {":rotation", IMAGE_NUMBER_VALUE, 0},
8196 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8199 #if defined HAVE_NTGUI && defined WINDOWSNT
8200 static bool init_imagemagick_functions (void);
8201 #else
8202 #define init_imagemagick_functions NULL
8203 #endif
8205 /* Structure describing the image type for any image handled via
8206 ImageMagick. */
8208 static struct image_type imagemagick_type =
8210 SYMBOL_INDEX (Qimagemagick),
8211 imagemagick_image_p,
8212 imagemagick_load,
8213 imagemagick_clear_image,
8214 init_imagemagick_functions,
8215 NULL
8218 /* Free X resources of imagemagick image IMG which is used on frame F. */
8220 static void
8221 imagemagick_clear_image (struct frame *f,
8222 struct image *img)
8224 x_clear_image (f, img);
8227 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8228 this by calling parse_image_spec and supplying the keywords that
8229 identify the IMAGEMAGICK format. */
8231 static bool
8232 imagemagick_image_p (Lisp_Object object)
8234 struct image_keyword fmt[IMAGEMAGICK_LAST];
8235 memcpy (fmt, imagemagick_format, sizeof fmt);
8237 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
8238 return 0;
8240 /* Must specify either the :data or :file keyword. */
8241 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
8244 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8245 Therefore rename the function so it doesn't collide with ImageMagick. */
8246 #define DrawRectangle DrawRectangleGif
8247 #include <wand/MagickWand.h>
8249 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8250 Emacs seems to work fine with the hidden version, so unhide it. */
8251 #include <magick/version.h>
8252 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8253 extern WandExport void PixelGetMagickColor (const PixelWand *,
8254 MagickPixelPacket *);
8255 #endif
8257 /* Log ImageMagick error message.
8258 Useful when a ImageMagick function returns the status `MagickFalse'. */
8260 static void
8261 imagemagick_error (MagickWand *wand)
8263 char *description;
8264 ExceptionType severity;
8266 description = MagickGetException (wand, &severity);
8267 image_error ("ImageMagick error: %s", build_string (description));
8268 MagickRelinquishMemory (description);
8271 /* Possibly give ImageMagick some extra help to determine the image
8272 type by supplying a "dummy" filename based on the Content-Type. */
8274 static char *
8275 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
8277 Lisp_Object symbol = intern ("image-format-suffixes");
8278 Lisp_Object val = find_symbol_value (symbol);
8279 Lisp_Object format;
8281 if (! CONSP (val))
8282 return NULL;
8284 format = image_spec_value (spec, intern (":format"), NULL);
8285 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
8286 if (! STRINGP (val))
8287 return NULL;
8289 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8290 as ImageMagick would ignore the extra bytes anyway. */
8291 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
8292 return hint_buffer;
8295 /* Animated images (e.g., GIF89a) are composed from one "master image"
8296 (which is the first one, and then there's a number of images that
8297 follow. If following images have non-transparent colors, these are
8298 composed "on top" of the master image. So, in general, one has to
8299 compute ann the preceding images to be able to display a particular
8300 sub-image.
8302 Computing all the preceding images is too slow, so we maintain a
8303 cache of previously computed images. We have to maintain a cache
8304 separate from the image cache, because the images may be scaled
8305 before display. */
8307 struct animation_cache
8309 MagickWand *wand;
8310 int index;
8311 struct timespec update_time;
8312 struct animation_cache *next;
8313 char signature[FLEXIBLE_ARRAY_MEMBER];
8316 static struct animation_cache *animation_cache = NULL;
8318 static struct animation_cache *
8319 imagemagick_create_cache (char *signature)
8321 struct animation_cache *cache
8322 = xmalloc (FLEXSIZEOF (struct animation_cache, signature,
8323 strlen (signature) + 1));
8324 cache->wand = 0;
8325 cache->index = 0;
8326 cache->next = 0;
8327 strcpy (cache->signature, signature);
8328 return cache;
8331 /* Discard cached images that haven't been used for a minute. */
8332 static void
8333 imagemagick_prune_animation_cache (void)
8335 struct animation_cache **pcache = &animation_cache;
8336 struct timespec old = timespec_sub (current_timespec (),
8337 make_timespec (60, 0));
8339 while (*pcache)
8341 struct animation_cache *cache = *pcache;
8342 if (timespec_cmp (old, cache->update_time) <= 0)
8343 pcache = &cache->next;
8344 else
8346 if (cache->wand)
8347 DestroyMagickWand (cache->wand);
8348 *pcache = cache->next;
8349 xfree (cache);
8354 static struct animation_cache *
8355 imagemagick_get_animation_cache (MagickWand *wand)
8357 char *signature = MagickGetImageSignature (wand);
8358 struct animation_cache *cache;
8359 struct animation_cache **pcache = &animation_cache;
8361 imagemagick_prune_animation_cache ();
8363 while (1)
8365 cache = *pcache;
8366 if (! cache)
8368 *pcache = cache = imagemagick_create_cache (signature);
8369 break;
8371 if (strcmp (signature, cache->signature) == 0)
8372 break;
8373 pcache = &cache->next;
8376 DestroyString (signature);
8377 cache->update_time = current_timespec ();
8378 return cache;
8381 static MagickWand *
8382 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8384 int i;
8385 MagickWand *composite_wand;
8386 size_t dest_width, dest_height;
8387 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8389 MagickSetIteratorIndex (super_wand, 0);
8391 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8393 composite_wand = MagickGetImage (super_wand);
8394 if (cache->wand)
8395 DestroyMagickWand (cache->wand);
8397 else
8398 composite_wand = cache->wand;
8400 dest_height = MagickGetImageHeight (composite_wand);
8402 for (i = max (1, cache->index + 1); i <= ino; i++)
8404 MagickWand *sub_wand;
8405 PixelIterator *source_iterator, *dest_iterator;
8406 PixelWand **source, **dest;
8407 size_t source_width, source_height;
8408 ssize_t source_left, source_top;
8409 MagickPixelPacket pixel;
8410 DisposeType dispose;
8411 ptrdiff_t lines = 0;
8413 MagickSetIteratorIndex (super_wand, i);
8414 sub_wand = MagickGetImage (super_wand);
8416 MagickGetImagePage (sub_wand, &source_width, &source_height,
8417 &source_left, &source_top);
8419 /* This flag says how to handle transparent pixels. */
8420 dispose = MagickGetImageDispose (sub_wand);
8422 source_iterator = NewPixelIterator (sub_wand);
8423 if (! source_iterator)
8425 DestroyMagickWand (composite_wand);
8426 DestroyMagickWand (sub_wand);
8427 cache->wand = NULL;
8428 image_error ("Imagemagick pixel iterator creation failed");
8429 return NULL;
8432 dest_iterator = NewPixelIterator (composite_wand);
8433 if (! dest_iterator)
8435 DestroyMagickWand (composite_wand);
8436 DestroyMagickWand (sub_wand);
8437 DestroyPixelIterator (source_iterator);
8438 cache->wand = NULL;
8439 image_error ("Imagemagick pixel iterator creation failed");
8440 return NULL;
8443 /* The sub-image may not start at origin, so move the destination
8444 iterator to where the sub-image should start. */
8445 if (source_top > 0)
8447 PixelSetIteratorRow (dest_iterator, source_top);
8448 lines = source_top;
8451 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8452 != NULL)
8454 ptrdiff_t x;
8456 /* Sanity check. This shouldn't happen, but apparently
8457 does in some pictures. */
8458 if (++lines >= dest_height)
8459 break;
8461 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8462 for (x = 0; x < source_width; x++)
8464 /* Sanity check. This shouldn't happen, but apparently
8465 also does in some pictures. */
8466 if (x + source_left >= dest_width)
8467 break;
8468 /* Normally we only copy over non-transparent pixels,
8469 but if the disposal method is "Background", then we
8470 copy over all pixels. */
8471 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8473 PixelGetMagickColor (source[x], &pixel);
8474 PixelSetMagickColor (dest[x + source_left], &pixel);
8477 PixelSyncIterator (dest_iterator);
8480 DestroyPixelIterator (source_iterator);
8481 DestroyPixelIterator (dest_iterator);
8482 DestroyMagickWand (sub_wand);
8485 /* Cache a copy for the next iteration. The current wand will be
8486 destroyed by the caller. */
8487 cache->wand = CloneMagickWand (composite_wand);
8488 cache->index = ino;
8490 return composite_wand;
8494 /* Helper function for imagemagick_load, which does the actual loading
8495 given contents and size, apart from frame and image structures,
8496 passed from imagemagick_load. Uses librimagemagick to do most of
8497 the image processing.
8499 F is a pointer to the Emacs frame; IMG to the image structure to
8500 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8501 be parsed; SIZE is the number of bytes of data; and FILENAME is
8502 either the file name or the image data.
8504 Return true if successful. */
8506 static bool
8507 imagemagick_load_image (struct frame *f, struct image *img,
8508 unsigned char *contents, unsigned int size,
8509 char *filename)
8511 int width, height;
8512 size_t image_width, image_height;
8513 MagickBooleanType status;
8514 XImagePtr ximg;
8515 int x, y;
8516 MagickWand *image_wand;
8517 PixelIterator *iterator;
8518 PixelWand **pixels, *bg_wand = NULL;
8519 MagickPixelPacket pixel;
8520 Lisp_Object image;
8521 Lisp_Object value;
8522 Lisp_Object crop;
8523 EMACS_INT ino;
8524 int desired_width, desired_height;
8525 double rotation;
8526 char hint_buffer[MaxTextExtent];
8527 char *filename_hint = NULL;
8529 /* Handle image index for image types who can contain more than one image.
8530 Interface :index is same as for GIF. First we "ping" the image to see how
8531 many sub-images it contains. Pinging is faster than loading the image to
8532 find out things about it. */
8534 /* Initialize the imagemagick environment. */
8535 MagickWandGenesis ();
8536 image = image_spec_value (img->spec, QCindex, NULL);
8537 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8538 image_wand = NewMagickWand ();
8540 if (filename)
8541 status = MagickReadImage (image_wand, filename);
8542 else
8544 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8545 MagickSetFilename (image_wand, filename_hint);
8546 status = MagickReadImageBlob (image_wand, contents, size);
8549 if (status == MagickFalse)
8551 imagemagick_error (image_wand);
8552 DestroyMagickWand (image_wand);
8553 return 0;
8556 #ifdef HAVE_MAGICKAUTOORIENTIMAGE
8557 /* If no :rotation is explicitly specified, apply the automatic
8558 rotation from EXIF. */
8559 if (NILP (image_spec_value (img->spec, QCrotation, NULL)))
8560 if (MagickAutoOrientImage (image_wand) == MagickFalse)
8562 image_error ("Error applying automatic orientation in image `%s'", img->spec);
8563 DestroyMagickWand (image_wand);
8564 return 0;
8566 #endif
8568 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8570 image_error ("Invalid image number `%s' in image `%s'", image, img->spec);
8571 DestroyMagickWand (image_wand);
8572 return 0;
8575 if (MagickGetImageDelay (image_wand) > 0)
8576 img->lisp_data =
8577 Fcons (Qdelay,
8578 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8579 img->lisp_data));
8581 if (MagickGetNumberImages (image_wand) > 1)
8582 img->lisp_data =
8583 Fcons (Qcount,
8584 Fcons (make_number (MagickGetNumberImages (image_wand)),
8585 img->lisp_data));
8587 /* If we have an animated image, get the new wand based on the
8588 "super-wand". */
8589 if (MagickGetNumberImages (image_wand) > 1)
8591 MagickWand *super_wand = image_wand;
8592 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8593 if (! image_wand)
8594 image_wand = super_wand;
8595 else
8596 DestroyMagickWand (super_wand);
8599 /* Retrieve the frame's background color, for use later. */
8601 XColor bgcolor;
8602 Lisp_Object specified_bg;
8604 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8605 if (!STRINGP (specified_bg)
8606 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8607 x_query_frame_background_color (f, &bgcolor);
8609 bg_wand = NewPixelWand ();
8610 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8611 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8612 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8615 compute_image_size (MagickGetImageWidth (image_wand),
8616 MagickGetImageHeight (image_wand),
8617 img->spec, &desired_width, &desired_height);
8619 if (desired_width != -1 && desired_height != -1)
8621 status = MagickScaleImage (image_wand, desired_width, desired_height);
8622 if (status == MagickFalse)
8624 image_error ("Imagemagick scale failed");
8625 imagemagick_error (image_wand);
8626 goto imagemagick_error;
8630 /* crop behaves similar to image slicing in Emacs but is more memory
8631 efficient. */
8632 crop = image_spec_value (img->spec, QCcrop, NULL);
8634 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8636 /* After some testing, it seems MagickCropImage is the fastest crop
8637 function in ImageMagick. This crop function seems to do less copying
8638 than the alternatives, but it still reads the entire image into memory
8639 before cropping, which is apparently difficult to avoid when using
8640 imagemagick. */
8641 size_t crop_width = XINT (XCAR (crop));
8642 crop = XCDR (crop);
8643 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8645 size_t crop_height = XINT (XCAR (crop));
8646 crop = XCDR (crop);
8647 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8649 ssize_t crop_x = XINT (XCAR (crop));
8650 crop = XCDR (crop);
8651 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8653 ssize_t crop_y = XINT (XCAR (crop));
8654 MagickCropImage (image_wand, crop_width, crop_height,
8655 crop_x, crop_y);
8661 /* Furthermore :rotation. we need background color and angle for
8662 rotation. */
8664 TODO background handling for rotation specified_bg =
8665 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8666 (specified_bg). */
8667 value = image_spec_value (img->spec, QCrotation, NULL);
8668 if (FLOATP (value))
8670 rotation = extract_float (value);
8671 status = MagickRotateImage (image_wand, bg_wand, rotation);
8672 if (status == MagickFalse)
8674 image_error ("Imagemagick image rotate failed");
8675 imagemagick_error (image_wand);
8676 goto imagemagick_error;
8680 /* Set the canvas background color to the frame or specified
8681 background, and flatten the image. Note: as of ImageMagick
8682 6.6.0, SVG image transparency is not handled properly
8683 (e.g. etc/images/splash.svg shows a white background always). */
8685 MagickWand *new_wand;
8686 MagickSetImageBackgroundColor (image_wand, bg_wand);
8687 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8688 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8689 #else
8690 new_wand = MagickFlattenImages (image_wand);
8691 #endif
8692 DestroyMagickWand (image_wand);
8693 image_wand = new_wand;
8696 /* Finally we are done manipulating the image. Figure out the
8697 resulting width/height and transfer ownership to Emacs. */
8698 image_height = MagickGetImageHeight (image_wand);
8699 image_width = MagickGetImageWidth (image_wand);
8701 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8702 && check_image_size (f, image_width, image_height)))
8704 image_size_error ();
8705 goto imagemagick_error;
8708 width = image_width;
8709 height = image_height;
8711 /* We can now get a valid pixel buffer from the imagemagick file, if all
8712 went ok. */
8714 init_color_table ();
8716 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8717 if (imagemagick_render_type != 0)
8719 /* Magicexportimage is normally faster than pixelpushing. This
8720 method is also well tested. Some aspects of this method are
8721 ad-hoc and needs to be more researched. */
8722 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8723 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8724 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8725 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8726 &ximg, 0))
8728 #ifdef COLOR_TABLE_SUPPORT
8729 free_color_table ();
8730 #endif
8731 image_error ("Imagemagick X bitmap allocation failure");
8732 goto imagemagick_error;
8735 /* Oddly, the below code doesn't seem to work:*/
8736 /* switch(ximg->bitmap_unit){ */
8737 /* case 8: */
8738 /* pixelwidth=CharPixel; */
8739 /* break; */
8740 /* case 16: */
8741 /* pixelwidth=ShortPixel; */
8742 /* break; */
8743 /* case 32: */
8744 /* pixelwidth=LongPixel; */
8745 /* break; */
8746 /* } */
8748 Here im just guessing the format of the bitmap.
8749 happens to work fine for:
8750 - bw djvu images
8751 on rgb display.
8752 seems about 3 times as fast as pixel pushing(not carefully measured)
8754 int pixelwidth = CharPixel; /*??? TODO figure out*/
8755 MagickExportImagePixels (image_wand, 0, 0, width, height,
8756 exportdepth, pixelwidth, ximg->data);
8758 else
8759 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8761 size_t image_height;
8762 MagickRealType color_scale = 65535.0 / QuantumRange;
8764 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8765 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8766 &ximg, 0))
8768 #ifdef COLOR_TABLE_SUPPORT
8769 free_color_table ();
8770 #endif
8771 image_error ("Imagemagick X bitmap allocation failure");
8772 goto imagemagick_error;
8775 /* Copy imagemagick image to x with primitive yet robust pixel
8776 pusher loop. This has been tested a lot with many different
8777 images. */
8779 /* Copy pixels from the imagemagick image structure to the x image map. */
8780 iterator = NewPixelIterator (image_wand);
8781 if (! iterator)
8783 #ifdef COLOR_TABLE_SUPPORT
8784 free_color_table ();
8785 #endif
8786 x_destroy_x_image (ximg);
8787 image_error ("Imagemagick pixel iterator creation failed");
8788 goto imagemagick_error;
8791 image_height = MagickGetImageHeight (image_wand);
8792 for (y = 0; y < image_height; y++)
8794 size_t row_width;
8795 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8796 if (! pixels)
8797 break;
8798 int xlim = min (row_width, width);
8799 for (x = 0; x < xlim; x++)
8801 PixelGetMagickColor (pixels[x], &pixel);
8802 XPutPixel (ximg, x, y,
8803 lookup_rgb_color (f,
8804 color_scale * pixel.red,
8805 color_scale * pixel.green,
8806 color_scale * pixel.blue));
8809 DestroyPixelIterator (iterator);
8812 #ifdef COLOR_TABLE_SUPPORT
8813 /* Remember colors allocated for this image. */
8814 img->colors = colors_in_color_table (&img->ncolors);
8815 free_color_table ();
8816 #endif /* COLOR_TABLE_SUPPORT */
8818 img->width = width;
8819 img->height = height;
8821 /* Put ximg into the image. */
8822 image_put_x_image (f, img, ximg, 0);
8824 /* Final cleanup. image_wand should be the only resource left. */
8825 DestroyMagickWand (image_wand);
8826 if (bg_wand) DestroyPixelWand (bg_wand);
8828 /* `MagickWandTerminus' terminates the imagemagick environment. */
8829 MagickWandTerminus ();
8831 return 1;
8833 imagemagick_error:
8834 DestroyMagickWand (image_wand);
8835 if (bg_wand) DestroyPixelWand (bg_wand);
8837 MagickWandTerminus ();
8838 /* TODO more cleanup. */
8839 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec);
8840 return 0;
8844 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8845 successful. this function will go into the imagemagick_type structure, and
8846 the prototype thus needs to be compatible with that structure. */
8848 static bool
8849 imagemagick_load (struct frame *f, struct image *img)
8851 bool success_p = 0;
8852 Lisp_Object file_name;
8854 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8855 file_name = image_spec_value (img->spec, QCfile, NULL);
8856 if (STRINGP (file_name))
8858 Lisp_Object file = x_find_image_file (file_name);
8859 if (!STRINGP (file))
8861 image_error ("Cannot find image file `%s'", file_name);
8862 return 0;
8864 file = ENCODE_FILE (file);
8865 #ifdef WINDOWSNT
8866 file = ansi_encode_filename (file);
8867 #endif
8868 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8870 /* Else its not a file, its a lisp object. Load the image from a
8871 lisp object rather than a file. */
8872 else
8874 Lisp_Object data;
8876 data = image_spec_value (img->spec, QCdata, NULL);
8877 if (!STRINGP (data))
8879 image_error ("Invalid image data `%s'", data);
8880 return 0;
8882 success_p = imagemagick_load_image (f, img, SDATA (data),
8883 SBYTES (data), NULL);
8886 return success_p;
8889 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8890 doc: /* Return a list of image types supported by ImageMagick.
8891 Each entry in this list is a symbol named after an ImageMagick format
8892 tag. See the ImageMagick manual for a list of ImageMagick formats and
8893 their descriptions (http://www.imagemagick.org/script/formats.php).
8894 You can also try the shell command: `identify -list format'.
8896 Note that ImageMagick recognizes many file-types that Emacs does not
8897 recognize as images, such as C. See `imagemagick-types-enable'
8898 and `imagemagick-types-inhibit'. */)
8899 (void)
8901 Lisp_Object typelist = Qnil;
8902 size_t numf = 0;
8903 ExceptionInfo *ex;
8904 char **imtypes;
8905 size_t i;
8907 ex = AcquireExceptionInfo ();
8908 imtypes = GetMagickList ("*", &numf, ex);
8909 DestroyExceptionInfo (ex);
8911 for (i = 0; i < numf; i++)
8913 Lisp_Object imagemagicktype = intern (imtypes[i]);
8914 typelist = Fcons (imagemagicktype, typelist);
8915 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8918 MagickRelinquishMemory (imtypes);
8919 return Fnreverse (typelist);
8922 #endif /* defined (HAVE_IMAGEMAGICK) */
8926 /***********************************************************************
8928 ***********************************************************************/
8930 #ifdef HAVE_RSVG
8932 /* Function prototypes. */
8934 static bool svg_image_p (Lisp_Object object);
8935 static bool svg_load (struct frame *f, struct image *img);
8937 static bool svg_load_image (struct frame *, struct image *,
8938 char *, ptrdiff_t, char *);
8940 /* Indices of image specification fields in svg_format, below. */
8942 enum svg_keyword_index
8944 SVG_TYPE,
8945 SVG_DATA,
8946 SVG_FILE,
8947 SVG_ASCENT,
8948 SVG_MARGIN,
8949 SVG_RELIEF,
8950 SVG_ALGORITHM,
8951 SVG_HEURISTIC_MASK,
8952 SVG_MASK,
8953 SVG_BACKGROUND,
8954 SVG_LAST
8957 /* Vector of image_keyword structures describing the format
8958 of valid user-defined image specifications. */
8960 static const struct image_keyword svg_format[SVG_LAST] =
8962 {":type", IMAGE_SYMBOL_VALUE, 1},
8963 {":data", IMAGE_STRING_VALUE, 0},
8964 {":file", IMAGE_STRING_VALUE, 0},
8965 {":ascent", IMAGE_ASCENT_VALUE, 0},
8966 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8967 {":relief", IMAGE_INTEGER_VALUE, 0},
8968 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8969 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8970 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8971 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8974 # if defined HAVE_NTGUI && defined WINDOWSNT
8975 static bool init_svg_functions (void);
8976 # else
8977 #define init_svg_functions NULL
8978 # endif
8980 /* Structure describing the image type `svg'. Its the same type of
8981 structure defined for all image formats, handled by emacs image
8982 functions. See struct image_type in dispextern.h. */
8984 static struct image_type svg_type =
8986 SYMBOL_INDEX (Qsvg),
8987 svg_image_p,
8988 svg_load,
8989 x_clear_image,
8990 init_svg_functions,
8991 NULL
8995 /* Return true if OBJECT is a valid SVG image specification. Do
8996 this by calling parse_image_spec and supplying the keywords that
8997 identify the SVG format. */
8999 static bool
9000 svg_image_p (Lisp_Object object)
9002 struct image_keyword fmt[SVG_LAST];
9003 memcpy (fmt, svg_format, sizeof fmt);
9005 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
9006 return 0;
9008 /* Must specify either the :data or :file keyword. */
9009 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
9012 # include <librsvg/rsvg.h>
9014 # ifdef WINDOWSNT
9016 /* SVG library functions. */
9017 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
9018 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
9019 (RsvgHandle *, RsvgDimensionData *));
9020 DEF_DLL_FN (gboolean, rsvg_handle_write,
9021 (RsvgHandle *, const guchar *, gsize, GError **));
9022 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
9023 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
9024 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
9026 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
9027 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
9028 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
9029 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
9030 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
9031 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
9032 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
9033 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
9035 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9036 DEF_DLL_FN (void, g_type_init, (void));
9037 # endif
9038 DEF_DLL_FN (void, g_object_unref, (gpointer));
9039 DEF_DLL_FN (void, g_clear_error, (GError **));
9041 static bool
9042 init_svg_functions (void)
9044 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
9046 if (!(glib = w32_delayed_load (Qglib))
9047 || !(gobject = w32_delayed_load (Qgobject))
9048 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
9049 || !(library = w32_delayed_load (Qsvg)))
9051 if (gdklib) FreeLibrary (gdklib);
9052 if (gobject) FreeLibrary (gobject);
9053 if (glib) FreeLibrary (glib);
9054 return 0;
9057 LOAD_DLL_FN (library, rsvg_handle_new);
9058 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
9059 LOAD_DLL_FN (library, rsvg_handle_write);
9060 LOAD_DLL_FN (library, rsvg_handle_close);
9061 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
9062 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
9064 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
9065 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
9066 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
9067 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
9068 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
9069 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
9070 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
9071 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
9073 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9074 LOAD_DLL_FN (gobject, g_type_init);
9075 # endif
9076 LOAD_DLL_FN (gobject, g_object_unref);
9077 LOAD_DLL_FN (glib, g_clear_error);
9079 return 1;
9082 /* The following aliases for library functions allow dynamic loading
9083 to be used on some platforms. */
9085 # undef gdk_pixbuf_get_bits_per_sample
9086 # undef gdk_pixbuf_get_colorspace
9087 # undef gdk_pixbuf_get_has_alpha
9088 # undef gdk_pixbuf_get_height
9089 # undef gdk_pixbuf_get_n_channels
9090 # undef gdk_pixbuf_get_pixels
9091 # undef gdk_pixbuf_get_rowstride
9092 # undef gdk_pixbuf_get_width
9093 # undef g_clear_error
9094 # undef g_object_unref
9095 # undef g_type_init
9096 # undef rsvg_handle_close
9097 # undef rsvg_handle_get_dimensions
9098 # undef rsvg_handle_get_pixbuf
9099 # undef rsvg_handle_new
9100 # undef rsvg_handle_set_base_uri
9101 # undef rsvg_handle_write
9103 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9104 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9105 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9106 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9107 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9108 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9109 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9110 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9111 # define g_clear_error fn_g_clear_error
9112 # define g_object_unref fn_g_object_unref
9113 # define g_type_init fn_g_type_init
9114 # define rsvg_handle_close fn_rsvg_handle_close
9115 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9116 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9117 # define rsvg_handle_new fn_rsvg_handle_new
9118 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9119 # define rsvg_handle_write fn_rsvg_handle_write
9121 # endif /* !WINDOWSNT */
9123 /* Load SVG image IMG for use on frame F. Value is true if
9124 successful. */
9126 static bool
9127 svg_load (struct frame *f, struct image *img)
9129 bool success_p = 0;
9130 Lisp_Object file_name;
9132 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9133 file_name = image_spec_value (img->spec, QCfile, NULL);
9134 if (STRINGP (file_name))
9136 int fd;
9137 Lisp_Object file = x_find_image_fd (file_name, &fd);
9138 if (!STRINGP (file))
9140 image_error ("Cannot find image file `%s'", file_name);
9141 return 0;
9144 /* Read the entire file into memory. */
9145 ptrdiff_t size;
9146 char *contents = slurp_file (fd, &size);
9147 if (contents == NULL)
9149 image_error ("Error loading SVG image `%s'", file);
9150 return 0;
9152 /* If the file was slurped into memory properly, parse it. */
9153 success_p = svg_load_image (f, img, contents, size,
9154 SSDATA (ENCODE_FILE (file)));
9155 xfree (contents);
9157 /* Else its not a file, its a lisp object. Load the image from a
9158 lisp object rather than a file. */
9159 else
9161 Lisp_Object data, original_filename;
9163 data = image_spec_value (img->spec, QCdata, NULL);
9164 if (!STRINGP (data))
9166 image_error ("Invalid image data `%s'", data);
9167 return 0;
9169 original_filename = BVAR (current_buffer, filename);
9170 success_p = svg_load_image (f, img, SSDATA (data), SBYTES (data),
9171 (NILP (original_filename) ? NULL
9172 : SSDATA (original_filename)));
9175 return success_p;
9178 /* Load frame F and image IMG. CONTENTS contains the SVG XML data to
9179 be parsed, SIZE is its size, and FILENAME is the name of the SVG
9180 file being loaded.
9182 Use librsvg to do most of the image processing.
9184 Return true when successful. */
9185 static bool
9186 svg_load_image (struct frame *f, struct image *img, char *contents,
9187 ptrdiff_t size, char *filename)
9189 RsvgHandle *rsvg_handle;
9190 RsvgDimensionData dimension_data;
9191 GError *err = NULL;
9192 GdkPixbuf *pixbuf;
9193 int width;
9194 int height;
9195 const guint8 *pixels;
9196 int rowstride;
9198 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9199 /* g_type_init is a glib function that must be called prior to
9200 using gnome type library functions (obsolete since 2.36.0). */
9201 g_type_init ();
9202 #endif
9204 /* Make a handle to a new rsvg object. */
9205 rsvg_handle = rsvg_handle_new ();
9207 /* Set base_uri for properly handling referenced images (via 'href').
9208 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9209 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9210 if (filename)
9211 rsvg_handle_set_base_uri(rsvg_handle, filename);
9213 /* Parse the contents argument and fill in the rsvg_handle. */
9214 rsvg_handle_write (rsvg_handle, (unsigned char *) contents, size, &err);
9215 if (err) goto rsvg_error;
9217 /* The parsing is complete, rsvg_handle is ready to used, close it
9218 for further writes. */
9219 rsvg_handle_close (rsvg_handle, &err);
9220 if (err) goto rsvg_error;
9222 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
9223 if (! check_image_size (f, dimension_data.width, dimension_data.height))
9225 image_size_error ();
9226 goto rsvg_error;
9229 /* We can now get a valid pixel buffer from the svg file, if all
9230 went ok. */
9231 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
9232 if (!pixbuf) goto rsvg_error;
9233 g_object_unref (rsvg_handle);
9235 /* Extract some meta data from the svg handle. */
9236 width = gdk_pixbuf_get_width (pixbuf);
9237 height = gdk_pixbuf_get_height (pixbuf);
9238 pixels = gdk_pixbuf_get_pixels (pixbuf);
9239 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
9241 /* Validate the svg meta data. */
9242 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
9243 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
9244 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
9245 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
9248 #ifdef USE_CAIRO
9249 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
9250 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
9252 for (int y = 0; y < height; ++y)
9254 const guchar *iconptr = pixels + y * rowstride;
9255 uint32_t *dataptr = (uint32_t *) (data + y * rowstride);
9257 for (int x = 0; x < width; ++x)
9259 if (iconptr[3] == 0)
9260 *dataptr = bgcolor;
9261 else
9262 *dataptr = (iconptr[0] << 16)
9263 | (iconptr[1] << 8)
9264 | iconptr[2]
9265 | (iconptr[3] << 24);
9267 iconptr += 4;
9268 ++dataptr;
9272 create_cairo_image_surface (img, data, width, height);
9273 g_object_unref (pixbuf);
9274 #else
9275 /* Try to create a x pixmap to hold the svg pixmap. */
9276 XImagePtr ximg;
9277 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
9279 g_object_unref (pixbuf);
9280 return 0;
9283 init_color_table ();
9285 /* Handle alpha channel by combining the image with a background
9286 color. */
9287 XColor background;
9288 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
9289 if (!STRINGP (specified_bg)
9290 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
9291 x_query_frame_background_color (f, &background);
9293 /* SVG pixmaps specify transparency in the last byte, so right
9294 shift 8 bits to get rid of it, since emacs doesn't support
9295 transparency. */
9296 background.red >>= 8;
9297 background.green >>= 8;
9298 background.blue >>= 8;
9300 /* This loop handles opacity values, since Emacs assumes
9301 non-transparent images. Each pixel must be "flattened" by
9302 calculating the resulting color, given the transparency of the
9303 pixel, and the image background color. */
9304 for (int y = 0; y < height; ++y)
9306 for (int x = 0; x < width; ++x)
9308 int red = *pixels++;
9309 int green = *pixels++;
9310 int blue = *pixels++;
9311 int opacity = *pixels++;
9313 red = ((red * opacity)
9314 + (background.red * ((1 << 8) - opacity)));
9315 green = ((green * opacity)
9316 + (background.green * ((1 << 8) - opacity)));
9317 blue = ((blue * opacity)
9318 + (background.blue * ((1 << 8) - opacity)));
9320 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9323 pixels += rowstride - 4 * width;
9326 #ifdef COLOR_TABLE_SUPPORT
9327 /* Remember colors allocated for this image. */
9328 img->colors = colors_in_color_table (&img->ncolors);
9329 free_color_table ();
9330 #endif /* COLOR_TABLE_SUPPORT */
9332 g_object_unref (pixbuf);
9334 img->width = width;
9335 img->height = height;
9337 /* Maybe fill in the background field while we have ximg handy.
9338 Casting avoids a GCC warning. */
9339 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9341 /* Put ximg into the image. */
9342 image_put_x_image (f, img, ximg, 0);
9343 #endif /* ! USE_CAIRO */
9346 return 1;
9348 rsvg_error:
9349 g_object_unref (rsvg_handle);
9350 /* FIXME: Use error->message so the user knows what is the actual
9351 problem with the image. */
9352 image_error ("Error parsing SVG image `%s'", img->spec);
9353 g_clear_error (&err);
9354 return 0;
9357 #endif /* defined (HAVE_RSVG) */
9362 /***********************************************************************
9363 Ghostscript
9364 ***********************************************************************/
9366 #ifdef HAVE_X_WINDOWS
9367 #define HAVE_GHOSTSCRIPT 1
9368 #endif /* HAVE_X_WINDOWS */
9370 #ifdef HAVE_GHOSTSCRIPT
9372 static bool gs_image_p (Lisp_Object object);
9373 static bool gs_load (struct frame *f, struct image *img);
9374 static void gs_clear_image (struct frame *f, struct image *img);
9376 /* Indices of image specification fields in gs_format, below. */
9378 enum gs_keyword_index
9380 GS_TYPE,
9381 GS_PT_WIDTH,
9382 GS_PT_HEIGHT,
9383 GS_FILE,
9384 GS_LOADER,
9385 GS_BOUNDING_BOX,
9386 GS_ASCENT,
9387 GS_MARGIN,
9388 GS_RELIEF,
9389 GS_ALGORITHM,
9390 GS_HEURISTIC_MASK,
9391 GS_MASK,
9392 GS_BACKGROUND,
9393 GS_LAST
9396 /* Vector of image_keyword structures describing the format
9397 of valid user-defined image specifications. */
9399 static const struct image_keyword gs_format[GS_LAST] =
9401 {":type", IMAGE_SYMBOL_VALUE, 1},
9402 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9403 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9404 {":file", IMAGE_STRING_VALUE, 1},
9405 {":loader", IMAGE_FUNCTION_VALUE, 0},
9406 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9407 {":ascent", IMAGE_ASCENT_VALUE, 0},
9408 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9409 {":relief", IMAGE_INTEGER_VALUE, 0},
9410 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9411 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9412 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9413 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9416 /* Structure describing the image type `ghostscript'. */
9418 static struct image_type gs_type =
9420 SYMBOL_INDEX (Qpostscript),
9421 gs_image_p,
9422 gs_load,
9423 gs_clear_image,
9424 NULL,
9425 NULL
9429 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9431 static void
9432 gs_clear_image (struct frame *f, struct image *img)
9434 x_clear_image (f, img);
9438 /* Return true if OBJECT is a valid Ghostscript image
9439 specification. */
9441 static bool
9442 gs_image_p (Lisp_Object object)
9444 struct image_keyword fmt[GS_LAST];
9445 Lisp_Object tem;
9446 int i;
9448 memcpy (fmt, gs_format, sizeof fmt);
9450 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9451 return 0;
9453 /* Bounding box must be a list or vector containing 4 integers. */
9454 tem = fmt[GS_BOUNDING_BOX].value;
9455 if (CONSP (tem))
9457 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9458 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9459 return 0;
9460 if (!NILP (tem))
9461 return 0;
9463 else if (VECTORP (tem))
9465 if (ASIZE (tem) != 4)
9466 return 0;
9467 for (i = 0; i < 4; ++i)
9468 if (!INTEGERP (AREF (tem, i)))
9469 return 0;
9471 else
9472 return 0;
9474 return 1;
9478 /* Load Ghostscript image IMG for use on frame F. Value is true
9479 if successful. */
9481 static bool
9482 gs_load (struct frame *f, struct image *img)
9484 uprintmax_t printnum1, printnum2;
9485 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9486 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9487 Lisp_Object frame;
9488 double in_width, in_height;
9489 Lisp_Object pixel_colors = Qnil;
9491 /* Compute pixel size of pixmap needed from the given size in the
9492 image specification. Sizes in the specification are in pt. 1 pt
9493 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9494 info. */
9495 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9496 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9497 in_width *= FRAME_RES_X (f);
9498 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9499 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9500 in_height *= FRAME_RES_Y (f);
9502 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9503 && check_image_size (f, in_width, in_height)))
9505 image_size_error ();
9506 return 0;
9508 img->width = in_width;
9509 img->height = in_height;
9511 /* Create the pixmap. */
9512 eassert (img->pixmap == NO_PIXMAP);
9514 if (x_check_image_size (0, img->width, img->height))
9516 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9517 block_input ();
9518 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9519 img->width, img->height,
9520 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9521 unblock_input ();
9524 if (!img->pixmap)
9526 image_error ("Unable to create pixmap for `%s'" , img->spec);
9527 return 0;
9530 /* Call the loader to fill the pixmap. It returns a process object
9531 if successful. We do not record_unwind_protect here because
9532 other places in redisplay like calling window scroll functions
9533 don't either. Let the Lisp loader use `unwind-protect' instead. */
9534 printnum1 = FRAME_X_WINDOW (f);
9535 printnum2 = img->pixmap;
9536 window_and_pixmap_id
9537 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9539 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9540 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9541 pixel_colors
9542 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9544 XSETFRAME (frame, f);
9545 loader = image_spec_value (img->spec, QCloader, NULL);
9546 if (NILP (loader))
9547 loader = intern ("gs-load-image");
9549 img->lisp_data = call6 (loader, frame, img->spec,
9550 make_number (img->width),
9551 make_number (img->height),
9552 window_and_pixmap_id,
9553 pixel_colors);
9554 return PROCESSP (img->lisp_data);
9558 /* Kill the Ghostscript process that was started to fill PIXMAP on
9559 frame F. Called from XTread_socket when receiving an event
9560 telling Emacs that Ghostscript has finished drawing. */
9562 void
9563 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9565 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9566 ptrdiff_t i;
9567 struct image *img;
9569 /* Find the image containing PIXMAP. */
9570 for (i = 0; i < c->used; ++i)
9571 if (c->images[i]->pixmap == pixmap)
9572 break;
9574 /* Should someone in between have cleared the image cache, for
9575 instance, give up. */
9576 if (i == c->used)
9577 return;
9579 /* Kill the GS process. We should have found PIXMAP in the image
9580 cache and its image should contain a process object. */
9581 img = c->images[i];
9582 eassert (PROCESSP (img->lisp_data));
9583 Fkill_process (img->lisp_data, Qnil);
9584 img->lisp_data = Qnil;
9586 #if defined (HAVE_X_WINDOWS)
9588 /* On displays with a mutable colormap, figure out the colors
9589 allocated for the image by looking at the pixels of an XImage for
9590 img->pixmap. */
9591 if (x_mutable_colormap (FRAME_X_VISUAL (f)))
9593 XImagePtr ximg;
9595 block_input ();
9597 /* Try to get an XImage for img->pixmep. */
9598 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9599 0, 0, img->width, img->height, ~0, ZPixmap);
9600 if (ximg)
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 (int y = 0; y < img->height; ++y)
9610 for (int 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 (QCscale, ":scale");
9810 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9811 DEFSYM (QCmask, ":mask");
9813 /* Other symbols. */
9814 DEFSYM (Qlaplace, "laplace");
9815 DEFSYM (Qemboss, "emboss");
9816 DEFSYM (Qedge_detection, "edge-detection");
9817 DEFSYM (Qheuristic, "heuristic");
9819 DEFSYM (Qpostscript, "postscript");
9820 DEFSYM (QCmax_width, ":max-width");
9821 DEFSYM (QCmax_height, ":max-height");
9822 #ifdef HAVE_GHOSTSCRIPT
9823 ADD_IMAGE_TYPE (Qpostscript);
9824 DEFSYM (QCloader, ":loader");
9825 DEFSYM (QCpt_width, ":pt-width");
9826 DEFSYM (QCpt_height, ":pt-height");
9827 #endif /* HAVE_GHOSTSCRIPT */
9829 #ifdef HAVE_NTGUI
9830 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9831 or -1 if no PNG/GIF support was compiled in. This is tested by
9832 w32-win.el to correctly set up the alist used to search for the
9833 respective image libraries. */
9834 DEFSYM (Qlibpng_version, "libpng-version");
9835 Fset (Qlibpng_version,
9836 #if HAVE_PNG
9837 make_number (PNG_LIBPNG_VER)
9838 #else
9839 make_number (-1)
9840 #endif
9842 DEFSYM (Qlibgif_version, "libgif-version");
9843 Fset (Qlibgif_version,
9844 #ifdef HAVE_GIF
9845 make_number (GIFLIB_MAJOR * 10000
9846 + GIFLIB_MINOR * 100
9847 + GIFLIB_RELEASE)
9848 #else
9849 make_number (-1)
9850 #endif
9852 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9853 Fset (Qlibjpeg_version,
9854 #if HAVE_JPEG
9855 make_number (JPEG_LIB_VERSION)
9856 #else
9857 make_number (-1)
9858 #endif
9860 #endif
9862 DEFSYM (Qpbm, "pbm");
9863 ADD_IMAGE_TYPE (Qpbm);
9865 DEFSYM (Qxbm, "xbm");
9866 ADD_IMAGE_TYPE (Qxbm);
9868 #if defined (HAVE_XPM) || defined (HAVE_NS)
9869 DEFSYM (Qxpm, "xpm");
9870 ADD_IMAGE_TYPE (Qxpm);
9871 #endif
9873 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9874 DEFSYM (Qjpeg, "jpeg");
9875 ADD_IMAGE_TYPE (Qjpeg);
9876 #endif
9878 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9879 DEFSYM (Qtiff, "tiff");
9880 ADD_IMAGE_TYPE (Qtiff);
9881 #endif
9883 #if defined (HAVE_GIF) || defined (HAVE_NS)
9884 DEFSYM (Qgif, "gif");
9885 ADD_IMAGE_TYPE (Qgif);
9886 #endif
9888 #if defined (HAVE_PNG) || defined (HAVE_NS)
9889 DEFSYM (Qpng, "png");
9890 ADD_IMAGE_TYPE (Qpng);
9891 #endif
9893 #if defined (HAVE_IMAGEMAGICK)
9894 DEFSYM (Qimagemagick, "imagemagick");
9895 ADD_IMAGE_TYPE (Qimagemagick);
9896 #endif
9898 #if defined (HAVE_RSVG)
9899 DEFSYM (Qsvg, "svg");
9900 ADD_IMAGE_TYPE (Qsvg);
9901 #ifdef HAVE_NTGUI
9902 /* Other libraries used directly by svg code. */
9903 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9904 DEFSYM (Qglib, "glib");
9905 DEFSYM (Qgobject, "gobject");
9906 #endif /* HAVE_NTGUI */
9907 #endif /* HAVE_RSVG */
9909 defsubr (&Sinit_image_library);
9910 #ifdef HAVE_IMAGEMAGICK
9911 defsubr (&Simagemagick_types);
9912 #endif
9913 defsubr (&Sclear_image_cache);
9914 defsubr (&Simage_flush);
9915 defsubr (&Simage_size);
9916 defsubr (&Simage_mask_p);
9917 defsubr (&Simage_metadata);
9919 #ifdef GLYPH_DEBUG
9920 defsubr (&Simagep);
9921 defsubr (&Slookup_image);
9922 #endif
9924 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9925 doc: /* Non-nil means always draw a cross over disabled images.
9926 Disabled images are those having a `:conversion disabled' property.
9927 A cross is always drawn on black & white displays. */);
9928 cross_disabled_images = 0;
9930 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9931 doc: /* List of directories to search for window system bitmap files. */);
9932 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9934 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9935 doc: /* Maximum time after which images are removed from the cache.
9936 When an image has not been displayed this many seconds, Emacs
9937 automatically removes it from the image cache. If the cache contains
9938 a large number of images, the actual eviction time may be shorter.
9939 The value can also be nil, meaning the cache is never cleared.
9941 The function `clear-image-cache' disregards this variable. */);
9942 Vimage_cache_eviction_delay = make_number (300);
9943 #ifdef HAVE_IMAGEMAGICK
9944 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9945 doc: /* Integer indicating which ImageMagick rendering method to use.
9946 The options are:
9947 0 -- the default method (pixel pushing)
9948 1 -- a newer method ("MagickExportImagePixels") that may perform
9949 better (speed etc) in some cases, but has not been as thoroughly
9950 tested with Emacs as the default method. This method requires
9951 ImageMagick version 6.4.6 (approximately) or later.
9952 */);
9953 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9954 imagemagick_render_type = 0;
9955 #endif