Default to inotify instead of gfile
[emacs.git] / src / image.c
blob313419b3232dc67716585a353c35d7412ebdb259
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include "sysstdio.h"
22 #include <unistd.h>
24 /* Include this before including <setjmp.h> to work around bugs with
25 older libpng; see Bug#17429. */
26 #if defined HAVE_PNG && !defined HAVE_NS
27 # include <png.h>
28 #endif
30 #include <setjmp.h>
31 #include <c-ctype.h>
33 #include "lisp.h"
34 #include "frame.h"
35 #include "window.h"
36 #include "buffer.h"
37 #include "dispextern.h"
38 #include "blockinput.h"
39 #include "systime.h"
40 #include <epaths.h>
41 #include "character.h"
42 #include "coding.h"
43 #include "termhooks.h"
44 #include "font.h"
46 #ifdef HAVE_SYS_STAT_H
47 #include <sys/stat.h>
48 #endif /* HAVE_SYS_STAT_H */
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
52 #endif /* HAVE_SYS_TYPES_H */
54 #ifdef HAVE_WINDOW_SYSTEM
55 #include TERM_HEADER
56 #endif /* HAVE_WINDOW_SYSTEM */
58 #ifdef HAVE_X_WINDOWS
59 #define COLOR_TABLE_SUPPORT 1
61 typedef struct x_bitmap_record Bitmap_Record;
62 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
63 #define NO_PIXMAP None
65 #define PIX_MASK_RETAIN 0
66 #define PIX_MASK_DRAW 1
67 #endif /* HAVE_X_WINDOWS */
69 #ifdef HAVE_NTGUI
71 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
72 #ifdef WINDOWSNT
73 # include "w32.h"
74 #endif
76 /* W32_TODO : Color tables on W32. */
77 #undef COLOR_TABLE_SUPPORT
79 typedef struct w32_bitmap_record Bitmap_Record;
80 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
81 #define NO_PIXMAP 0
83 #define PIX_MASK_RETAIN 0
84 #define PIX_MASK_DRAW 1
86 #define x_defined_color w32_defined_color
87 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
89 #endif /* HAVE_NTGUI */
91 #ifdef USE_CAIRO
92 #undef COLOR_TABLE_SUPPORT
93 #endif
95 #ifdef HAVE_NS
96 #undef COLOR_TABLE_SUPPORT
98 typedef struct ns_bitmap_record Bitmap_Record;
100 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
101 #define NO_PIXMAP 0
103 #define PIX_MASK_RETAIN 0
104 #define PIX_MASK_DRAW 1
106 #define x_defined_color(f, name, color_def, alloc) \
107 ns_defined_color (f, name, color_def, alloc, 0)
108 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
109 #endif /* HAVE_NS */
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 Pixmap bitmap;
231 bitmap = CreateBitmap (width, height,
232 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
233 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
234 bits);
235 if (! bitmap)
236 return -1;
237 #endif /* HAVE_NTGUI */
239 #ifdef HAVE_NS
240 void *bitmap = ns_image_from_XBM (bits, width, height, 0, 0);
241 if (!bitmap)
242 return -1;
243 #endif
245 id = x_allocate_bitmap_record (f);
247 #ifdef HAVE_NS
248 dpyinfo->bitmaps[id - 1].img = bitmap;
249 dpyinfo->bitmaps[id - 1].depth = 1;
250 #endif
252 dpyinfo->bitmaps[id - 1].file = NULL;
253 dpyinfo->bitmaps[id - 1].height = height;
254 dpyinfo->bitmaps[id - 1].width = width;
255 dpyinfo->bitmaps[id - 1].refcount = 1;
257 #ifdef HAVE_X_WINDOWS
258 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
259 dpyinfo->bitmaps[id - 1].have_mask = false;
260 dpyinfo->bitmaps[id - 1].depth = 1;
261 #endif /* HAVE_X_WINDOWS */
263 #ifdef HAVE_NTGUI
264 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
265 dpyinfo->bitmaps[id - 1].hinst = NULL;
266 dpyinfo->bitmaps[id - 1].depth = 1;
267 #endif /* HAVE_NTGUI */
269 return id;
272 /* Create bitmap from file FILE for frame F. */
274 ptrdiff_t
275 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
277 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
279 #ifdef HAVE_NTGUI
280 return -1; /* W32_TODO : bitmap support */
281 #endif /* HAVE_NTGUI */
283 #ifdef HAVE_NS
284 ptrdiff_t id;
285 void *bitmap = ns_image_from_file (file);
287 if (!bitmap)
288 return -1;
291 id = x_allocate_bitmap_record (f);
292 dpyinfo->bitmaps[id - 1].img = bitmap;
293 dpyinfo->bitmaps[id - 1].refcount = 1;
294 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
295 dpyinfo->bitmaps[id - 1].depth = 1;
296 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
297 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
298 return id;
299 #endif
301 #ifdef HAVE_X_WINDOWS
302 unsigned int width, height;
303 Pixmap bitmap;
304 int xhot, yhot, result;
305 ptrdiff_t id;
306 Lisp_Object found;
307 char *filename;
309 /* Look for an existing bitmap with the same name. */
310 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
312 if (dpyinfo->bitmaps[id].refcount
313 && dpyinfo->bitmaps[id].file
314 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
316 ++dpyinfo->bitmaps[id].refcount;
317 return id + 1;
321 /* Search bitmap-file-path for the file, if appropriate. */
322 if (openp (Vx_bitmap_file_path, file, Qnil, &found,
323 make_number (R_OK), false)
324 < 0)
325 return -1;
327 filename = SSDATA (found);
329 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
330 filename, &width, &height, &bitmap, &xhot, &yhot);
331 if (result != BitmapSuccess)
332 return -1;
334 id = x_allocate_bitmap_record (f);
335 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
336 dpyinfo->bitmaps[id - 1].have_mask = false;
337 dpyinfo->bitmaps[id - 1].refcount = 1;
338 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
339 dpyinfo->bitmaps[id - 1].depth = 1;
340 dpyinfo->bitmaps[id - 1].height = height;
341 dpyinfo->bitmaps[id - 1].width = width;
343 return id;
344 #endif /* HAVE_X_WINDOWS */
347 /* Free bitmap B. */
349 static void
350 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
352 #ifdef HAVE_X_WINDOWS
353 XFreePixmap (dpyinfo->display, bm->pixmap);
354 if (bm->have_mask)
355 XFreePixmap (dpyinfo->display, bm->mask);
356 #endif /* HAVE_X_WINDOWS */
358 #ifdef HAVE_NTGUI
359 DeleteObject (bm->pixmap);
360 #endif /* HAVE_NTGUI */
362 #ifdef HAVE_NS
363 ns_release_object (bm->img);
364 #endif
366 if (bm->file)
368 xfree (bm->file);
369 bm->file = NULL;
373 /* Remove reference to bitmap with id number ID. */
375 void
376 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
378 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
380 if (id > 0)
382 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
384 if (--bm->refcount == 0)
386 block_input ();
387 free_bitmap_record (dpyinfo, bm);
388 unblock_input ();
393 /* Free all the bitmaps for the display specified by DPYINFO. */
395 void
396 x_destroy_all_bitmaps (Display_Info *dpyinfo)
398 ptrdiff_t i;
399 Bitmap_Record *bm = dpyinfo->bitmaps;
401 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
402 if (bm->refcount > 0)
403 free_bitmap_record (dpyinfo, bm);
405 dpyinfo->bitmaps_last = 0;
408 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
409 XImagePtr *, Pixmap *);
410 static void x_destroy_x_image (XImagePtr ximg);
412 #ifdef HAVE_NTGUI
413 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
414 bool, HGDIOBJ *);
415 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
416 HGDIOBJ);
417 #else
418 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
419 static void image_unget_x_image (struct image *, bool, XImagePtr);
420 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
421 image_get_x_image (f, img, mask_p)
422 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
423 image_unget_x_image (img, mask_p, ximg)
424 #endif
426 #ifdef HAVE_X_WINDOWS
428 static void image_sync_to_pixmaps (struct frame *, struct image *);
430 /* Useful functions defined in the section
431 `Image type independent image structures' below. */
433 static unsigned long four_corners_best (XImagePtr ximg,
434 int *corners,
435 unsigned long width,
436 unsigned long height);
439 /* Create a mask of a bitmap. Note is this not a perfect mask.
440 It's nicer with some borders in this context */
442 void
443 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
445 Pixmap pixmap, mask;
446 XImagePtr ximg, mask_img;
447 unsigned long width, height;
448 bool result;
449 unsigned long bg;
450 unsigned long x, y, xp, xm, yp, ym;
451 GC gc;
453 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
455 if (!(id > 0))
456 return;
458 pixmap = x_bitmap_pixmap (f, id);
459 width = x_bitmap_width (f, id);
460 height = x_bitmap_height (f, id);
462 block_input ();
463 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
464 ~0, ZPixmap);
466 if (!ximg)
468 unblock_input ();
469 return;
472 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
474 unblock_input ();
475 if (!result)
477 XDestroyImage (ximg);
478 return;
481 bg = four_corners_best (ximg, NULL, width, height);
483 for (y = 0; y < ximg->height; ++y)
485 for (x = 0; x < ximg->width; ++x)
487 xp = x != ximg->width - 1 ? x + 1 : 0;
488 xm = x != 0 ? x - 1 : ximg->width - 1;
489 yp = y != ximg->height - 1 ? y + 1 : 0;
490 ym = y != 0 ? y - 1 : ximg->height - 1;
491 if (XGetPixel (ximg, x, y) == bg
492 && XGetPixel (ximg, x, yp) == bg
493 && XGetPixel (ximg, x, ym) == bg
494 && XGetPixel (ximg, xp, y) == bg
495 && XGetPixel (ximg, xp, yp) == bg
496 && XGetPixel (ximg, xp, ym) == bg
497 && XGetPixel (ximg, xm, y) == bg
498 && XGetPixel (ximg, xm, yp) == bg
499 && XGetPixel (ximg, xm, ym) == bg)
500 XPutPixel (mask_img, x, y, 0);
501 else
502 XPutPixel (mask_img, x, y, 1);
506 eassert (input_blocked_p ());
507 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
508 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
509 width, height);
510 XFreeGC (FRAME_X_DISPLAY (f), gc);
512 dpyinfo->bitmaps[id - 1].have_mask = true;
513 dpyinfo->bitmaps[id - 1].mask = mask;
515 XDestroyImage (ximg);
516 x_destroy_x_image (mask_img);
519 #endif /* HAVE_X_WINDOWS */
521 /***********************************************************************
522 Image types
523 ***********************************************************************/
525 /* List of supported image types. Use define_image_type to add new
526 types. Use lookup_image_type to find a type for a given symbol. */
528 static struct image_type *image_types;
530 /* Forward function prototypes. */
532 static struct image_type *lookup_image_type (Lisp_Object);
533 static void x_laplace (struct frame *, struct image *);
534 static void x_emboss (struct frame *, struct image *);
535 static void x_build_heuristic_mask (struct frame *, struct image *,
536 Lisp_Object);
537 #ifdef WINDOWSNT
538 #define CACHE_IMAGE_TYPE(type, status) \
539 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
540 #else
541 #define CACHE_IMAGE_TYPE(type, status)
542 #endif
544 #define ADD_IMAGE_TYPE(type) \
545 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
547 /* Define a new image type from TYPE. This adds a copy of TYPE to
548 image_types and caches the loading status of TYPE. */
550 static struct image_type *
551 define_image_type (struct image_type *type)
553 struct image_type *p = NULL;
554 int new_type = type->type;
555 bool type_valid = true;
557 block_input ();
559 for (p = image_types; p; p = p->next)
560 if (p->type == new_type)
561 goto done;
563 if (type->init)
565 #if defined HAVE_NTGUI && defined WINDOWSNT
566 /* If we failed to load the library before, don't try again. */
567 Lisp_Object tested = Fassq (builtin_lisp_symbol (new_type),
568 Vlibrary_cache);
569 if (CONSP (tested) && NILP (XCDR (tested)))
570 type_valid = false;
571 else
572 #endif
574 type_valid = type->init ();
575 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type),
576 type_valid ? Qt : Qnil);
580 if (type_valid)
582 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
583 The initialized data segment is read-only. */
584 p = xmalloc (sizeof *p);
585 *p = *type;
586 p->next = image_types;
587 image_types = p;
590 done:
591 unblock_input ();
592 return p;
596 /* Value is true if OBJECT is a valid Lisp image specification. A
597 valid image specification is a list whose car is the symbol
598 `image', and whose rest is a property list. The property list must
599 contain a value for key `:type'. That value must be the name of a
600 supported image type. The rest of the property list depends on the
601 image type. */
603 bool
604 valid_image_p (Lisp_Object object)
606 bool valid_p = 0;
608 if (IMAGEP (object))
610 Lisp_Object tem;
612 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
613 if (EQ (XCAR (tem), QCtype))
615 tem = XCDR (tem);
616 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
618 struct image_type *type;
619 type = lookup_image_type (XCAR (tem));
620 if (type)
621 valid_p = type->valid_p (object);
624 break;
628 return valid_p;
632 /* Log error message with format string FORMAT and trailing arguments.
633 Signaling an error, e.g. when an image cannot be loaded, is not a
634 good idea because this would interrupt redisplay, and the error
635 message display would lead to another redisplay. This function
636 therefore simply displays a message. */
638 static void
639 image_error (const char *format, ...)
641 va_list ap;
642 va_start (ap, format);
643 vadd_to_log (format, ap);
644 va_end (ap);
649 /***********************************************************************
650 Image specifications
651 ***********************************************************************/
653 enum image_value_type
655 IMAGE_DONT_CHECK_VALUE_TYPE,
656 IMAGE_STRING_VALUE,
657 IMAGE_STRING_OR_NIL_VALUE,
658 IMAGE_SYMBOL_VALUE,
659 IMAGE_POSITIVE_INTEGER_VALUE,
660 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
661 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
662 IMAGE_ASCENT_VALUE,
663 IMAGE_INTEGER_VALUE,
664 IMAGE_FUNCTION_VALUE,
665 IMAGE_NUMBER_VALUE,
666 IMAGE_BOOL_VALUE
669 /* Structure used when parsing image specifications. */
671 struct image_keyword
673 /* Name of keyword. */
674 const char *name;
676 /* The type of value allowed. */
677 enum image_value_type type;
679 /* True means key must be present. */
680 bool mandatory_p;
682 /* Used to recognize duplicate keywords in a property list. */
683 int count;
685 /* The value that was found. */
686 Lisp_Object value;
690 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
691 has the format (image KEYWORD VALUE ...). One of the keyword/
692 value pairs must be `:type TYPE'. KEYWORDS is a vector of
693 image_keywords structures of size NKEYWORDS describing other
694 allowed keyword/value pairs. Value is true if SPEC is valid. */
696 static bool
697 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
698 int nkeywords, Lisp_Object type)
700 int i;
701 Lisp_Object plist;
703 if (!IMAGEP (spec))
704 return 0;
706 plist = XCDR (spec);
707 while (CONSP (plist))
709 Lisp_Object key, value;
711 /* First element of a pair must be a symbol. */
712 key = XCAR (plist);
713 plist = XCDR (plist);
714 if (!SYMBOLP (key))
715 return 0;
717 /* There must follow a value. */
718 if (!CONSP (plist))
719 return 0;
720 value = XCAR (plist);
721 plist = XCDR (plist);
723 /* Find key in KEYWORDS. Error if not found. */
724 for (i = 0; i < nkeywords; ++i)
725 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
726 break;
728 if (i == nkeywords)
729 continue;
731 /* Record that we recognized the keyword. If a keywords
732 was found more than once, it's an error. */
733 keywords[i].value = value;
734 if (keywords[i].count > 1)
735 return 0;
736 ++keywords[i].count;
738 /* Check type of value against allowed type. */
739 switch (keywords[i].type)
741 case IMAGE_STRING_VALUE:
742 if (!STRINGP (value))
743 return 0;
744 break;
746 case IMAGE_STRING_OR_NIL_VALUE:
747 if (!STRINGP (value) && !NILP (value))
748 return 0;
749 break;
751 case IMAGE_SYMBOL_VALUE:
752 if (!SYMBOLP (value))
753 return 0;
754 break;
756 case IMAGE_POSITIVE_INTEGER_VALUE:
757 if (! RANGED_INTEGERP (1, value, INT_MAX))
758 return 0;
759 break;
761 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
762 if (RANGED_INTEGERP (0, value, INT_MAX))
763 break;
764 if (CONSP (value)
765 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
766 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
767 break;
768 return 0;
770 case IMAGE_ASCENT_VALUE:
771 if (SYMBOLP (value) && EQ (value, Qcenter))
772 break;
773 else if (RANGED_INTEGERP (0, value, 100))
774 break;
775 return 0;
777 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
778 /* Unlike the other integer-related cases, this one does not
779 verify that VALUE fits in 'int'. This is because callers
780 want EMACS_INT. */
781 if (!INTEGERP (value) || XINT (value) < 0)
782 return 0;
783 break;
785 case IMAGE_DONT_CHECK_VALUE_TYPE:
786 break;
788 case IMAGE_FUNCTION_VALUE:
789 value = indirect_function (value);
790 if (!NILP (Ffunctionp (value)))
791 break;
792 return 0;
794 case IMAGE_NUMBER_VALUE:
795 if (!INTEGERP (value) && !FLOATP (value))
796 return 0;
797 break;
799 case IMAGE_INTEGER_VALUE:
800 if (! TYPE_RANGED_INTEGERP (int, value))
801 return 0;
802 break;
804 case IMAGE_BOOL_VALUE:
805 if (!NILP (value) && !EQ (value, Qt))
806 return 0;
807 break;
809 default:
810 emacs_abort ();
811 break;
814 if (EQ (key, QCtype) && !EQ (type, value))
815 return 0;
818 /* Check that all mandatory fields are present. */
819 for (i = 0; i < nkeywords; ++i)
820 if (keywords[i].mandatory_p && keywords[i].count == 0)
821 return 0;
823 return NILP (plist);
827 /* Return the value of KEY in image specification SPEC. Value is nil
828 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
829 was found in SPEC. */
831 static Lisp_Object
832 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
834 Lisp_Object tail;
836 eassert (valid_image_p (spec));
838 for (tail = XCDR (spec);
839 CONSP (tail) && CONSP (XCDR (tail));
840 tail = XCDR (XCDR (tail)))
842 if (EQ (XCAR (tail), key))
844 if (found)
845 *found = 1;
846 return XCAR (XCDR (tail));
850 if (found)
851 *found = 0;
852 return Qnil;
856 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
857 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
858 PIXELS non-nil means return the size in pixels, otherwise return the
859 size in canonical character units.
860 FRAME is the frame on which the image will be displayed. FRAME nil
861 or omitted means use the selected frame. */)
862 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
864 Lisp_Object size;
866 size = Qnil;
867 if (valid_image_p (spec))
869 struct frame *f = decode_window_system_frame (frame);
870 ptrdiff_t id = lookup_image (f, spec);
871 struct image *img = IMAGE_FROM_ID (f, id);
872 int width = img->width + 2 * img->hmargin;
873 int height = img->height + 2 * img->vmargin;
875 if (NILP (pixels))
876 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
877 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
878 else
879 size = Fcons (make_number (width), make_number (height));
881 else
882 error ("Invalid image specification");
884 return size;
888 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
889 doc: /* Return t if image SPEC has a mask bitmap.
890 FRAME is the frame on which the image will be displayed. FRAME nil
891 or omitted means use the selected frame. */)
892 (Lisp_Object spec, Lisp_Object frame)
894 Lisp_Object mask;
896 mask = Qnil;
897 if (valid_image_p (spec))
899 struct frame *f = decode_window_system_frame (frame);
900 ptrdiff_t id = lookup_image (f, spec);
901 struct image *img = IMAGE_FROM_ID (f, id);
902 if (img->mask)
903 mask = Qt;
905 else
906 error ("Invalid image specification");
908 return mask;
911 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
912 doc: /* Return metadata for image SPEC.
913 FRAME is the frame on which the image will be displayed. FRAME nil
914 or omitted means use the selected frame. */)
915 (Lisp_Object spec, Lisp_Object frame)
917 Lisp_Object ext;
919 ext = Qnil;
920 if (valid_image_p (spec))
922 struct frame *f = decode_window_system_frame (frame);
923 ptrdiff_t id = lookup_image (f, spec);
924 struct image *img = IMAGE_FROM_ID (f, id);
925 ext = img->lisp_data;
928 return ext;
932 /***********************************************************************
933 Image type independent image structures
934 ***********************************************************************/
936 #define MAX_IMAGE_SIZE 10.0
937 /* Allocate and return a new image structure for image specification
938 SPEC. SPEC has a hash value of HASH. */
940 static struct image *
941 make_image (Lisp_Object spec, EMACS_UINT hash)
943 struct image *img = xzalloc (sizeof *img);
944 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
946 eassert (valid_image_p (spec));
947 img->dependencies = NILP (file) ? Qnil : list1 (file);
948 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
949 eassert (img->type != NULL);
950 img->spec = spec;
951 img->lisp_data = Qnil;
952 img->ascent = DEFAULT_IMAGE_ASCENT;
953 img->hash = hash;
954 img->corners[BOT_CORNER] = -1; /* Full image */
955 return img;
959 /* Free image IMG which was used on frame F, including its resources. */
961 static void
962 free_image (struct frame *f, struct image *img)
964 if (img)
966 struct image_cache *c = FRAME_IMAGE_CACHE (f);
968 /* Remove IMG from the hash table of its cache. */
969 if (img->prev)
970 img->prev->next = img->next;
971 else
972 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
974 if (img->next)
975 img->next->prev = img->prev;
977 c->images[img->id] = NULL;
979 /* Windows NT redefines 'free', but in this file, we need to
980 avoid the redefinition. */
981 #ifdef WINDOWSNT
982 #undef free
983 #endif
984 /* Free resources, then free IMG. */
985 img->type->free (f, img);
986 xfree (img);
990 /* Return true if the given widths and heights are valid for display. */
992 static bool
993 check_image_size (struct frame *f, int width, int height)
995 int w, h;
997 if (width <= 0 || height <= 0)
998 return 0;
1000 if (INTEGERP (Vmax_image_size))
1001 return (width <= XINT (Vmax_image_size)
1002 && height <= XINT (Vmax_image_size));
1003 else if (FLOATP (Vmax_image_size))
1005 if (f != NULL)
1007 w = FRAME_PIXEL_WIDTH (f);
1008 h = FRAME_PIXEL_HEIGHT (f);
1010 else
1011 w = h = 1024; /* Arbitrary size for unknown frame. */
1012 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1013 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1015 else
1016 return 1;
1019 /* Prepare image IMG for display on frame F. Must be called before
1020 drawing an image. */
1022 void
1023 prepare_image_for_display (struct frame *f, struct image *img)
1025 /* We're about to display IMG, so set its timestamp to `now'. */
1026 img->timestamp = current_timespec ();
1028 #ifndef USE_CAIRO
1029 /* If IMG doesn't have a pixmap yet, load it now, using the image
1030 type dependent loader function. */
1031 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1032 img->load_failed_p = ! img->type->load (f, img);
1034 #ifdef HAVE_X_WINDOWS
1035 if (!img->load_failed_p)
1037 block_input ();
1038 image_sync_to_pixmaps (f, img);
1039 unblock_input ();
1041 #endif
1042 #endif
1046 /* Value is the number of pixels for the ascent of image IMG when
1047 drawn in face FACE. */
1050 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1052 int height;
1053 int ascent;
1055 if (slice->height == img->height)
1056 height = img->height + img->vmargin;
1057 else if (slice->y == 0)
1058 height = slice->height + img->vmargin;
1059 else
1060 height = slice->height;
1062 if (img->ascent == CENTERED_IMAGE_ASCENT)
1064 if (face->font)
1066 #ifdef HAVE_NTGUI
1067 /* W32 specific version. Why?. ++kfs */
1068 ascent = height / 2 - (FONT_DESCENT (face->font)
1069 - FONT_BASE (face->font)) / 2;
1070 #else
1071 /* This expression is arranged so that if the image can't be
1072 exactly centered, it will be moved slightly up. This is
1073 because a typical font is `top-heavy' (due to the presence
1074 uppercase letters), so the image placement should err towards
1075 being top-heavy too. It also just generally looks better. */
1076 ascent = (height + FONT_BASE (face->font)
1077 - FONT_DESCENT (face->font) + 1) / 2;
1078 #endif /* HAVE_NTGUI */
1080 else
1081 ascent = height / 2;
1083 else
1084 ascent = height * (img->ascent / 100.0);
1086 return ascent;
1089 #ifdef USE_CAIRO
1090 static uint32_t
1091 xcolor_to_argb32 (XColor xc)
1093 return (0xff << 24) | ((xc.red / 256) << 16)
1094 | ((xc.green / 256) << 8) | (xc.blue / 256);
1097 static uint32_t
1098 get_spec_bg_or_alpha_as_argb (struct image *img,
1099 struct frame *f)
1101 uint32_t bgcolor = 0;
1102 XColor xbgcolor;
1103 Lisp_Object bg = image_spec_value (img->spec, QCbackground, NULL);
1105 if (STRINGP (bg) && XParseColor (FRAME_X_DISPLAY (f),
1106 FRAME_X_COLORMAP (f),
1107 SSDATA (bg),
1108 &xbgcolor))
1109 bgcolor = xcolor_to_argb32 (xbgcolor);
1111 return bgcolor;
1114 static void
1115 create_cairo_image_surface (struct image *img,
1116 unsigned char *data,
1117 int width,
1118 int height)
1120 cairo_surface_t *surface;
1121 cairo_format_t format = CAIRO_FORMAT_ARGB32;
1122 int stride = cairo_format_stride_for_width (format, width);
1123 surface = cairo_image_surface_create_for_data (data,
1124 format,
1125 width,
1126 height,
1127 stride);
1128 img->width = width;
1129 img->height = height;
1130 img->cr_data = surface;
1131 img->cr_data2 = data;
1132 img->pixmap = 0;
1134 #endif
1138 /* Image background colors. */
1140 /* Find the "best" corner color of a bitmap.
1141 On W32, XIMG is assumed to a device context with the bitmap selected. */
1143 static RGB_PIXEL_COLOR
1144 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1145 unsigned long width, unsigned long height)
1147 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1148 int i, best_count;
1150 if (corners && corners[BOT_CORNER] >= 0)
1152 /* Get the colors at the corner_pixels of ximg. */
1153 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1154 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1155 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1156 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1158 else
1160 /* Get the colors at the corner_pixels of ximg. */
1161 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1162 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1163 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1164 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1166 /* Choose the most frequently found color as background. */
1167 for (i = best_count = 0; i < 4; ++i)
1169 int j, n;
1171 for (j = n = 0; j < 4; ++j)
1172 if (corner_pixels[i] == corner_pixels[j])
1173 ++n;
1175 if (n > best_count)
1176 best = corner_pixels[i], best_count = n;
1179 return best;
1182 /* Portability macros */
1184 #ifdef HAVE_NTGUI
1186 #define Free_Pixmap(display, pixmap) \
1187 DeleteObject (pixmap)
1189 #elif defined (HAVE_NS)
1191 #define Free_Pixmap(display, pixmap) \
1192 ns_release_object (pixmap)
1194 #else
1196 #define Free_Pixmap(display, pixmap) \
1197 XFreePixmap (display, pixmap)
1199 #endif /* !HAVE_NTGUI && !HAVE_NS */
1202 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1203 it is guessed heuristically. If non-zero, XIMG is an existing
1204 XImage object (or device context with the image selected on W32) to
1205 use for the heuristic. */
1207 RGB_PIXEL_COLOR
1208 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1210 if (! img->background_valid)
1211 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1213 bool free_ximg = !ximg;
1214 #ifdef HAVE_NTGUI
1215 HGDIOBJ prev;
1216 #endif /* HAVE_NTGUI */
1218 if (free_ximg)
1219 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1221 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1223 if (free_ximg)
1224 image_unget_x_image_or_dc (img, 0, ximg, prev);
1226 img->background_valid = 1;
1229 return img->background;
1232 /* Return the `background_transparent' field of IMG. If IMG doesn't
1233 have one yet, it is guessed heuristically. If non-zero, MASK is an
1234 existing XImage object to use for the heuristic. */
1237 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1239 if (! img->background_transparent_valid)
1240 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1242 if (img->mask)
1244 bool free_mask = !mask;
1245 #ifdef HAVE_NTGUI
1246 HGDIOBJ prev;
1247 #endif /* HAVE_NTGUI */
1249 if (free_mask)
1250 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1252 img->background_transparent
1253 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1255 if (free_mask)
1256 image_unget_x_image_or_dc (img, 1, mask, prev);
1258 else
1259 img->background_transparent = 0;
1261 img->background_transparent_valid = 1;
1264 return img->background_transparent;
1267 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1268 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1270 /* Store F's background color into *BGCOLOR. */
1271 static void
1272 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1274 #ifndef HAVE_NS
1275 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1276 x_query_color (f, bgcolor);
1277 #else
1278 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1279 #endif
1282 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1284 /***********************************************************************
1285 Helper functions for X image types
1286 ***********************************************************************/
1288 /* Clear X resources of image IMG on frame F according to FLAGS.
1289 FLAGS is bitwise-or of the following masks:
1290 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1291 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1292 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1293 any. */
1295 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1296 #define CLEAR_IMAGE_MASK (1 << 1)
1297 #define CLEAR_IMAGE_COLORS (1 << 2)
1299 static void
1300 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1302 if (flags & CLEAR_IMAGE_PIXMAP)
1304 if (img->pixmap)
1306 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1307 img->pixmap = NO_PIXMAP;
1308 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1309 img->background_valid = 0;
1311 #ifdef HAVE_X_WINDOWS
1312 if (img->ximg)
1314 x_destroy_x_image (img->ximg);
1315 img->ximg = NULL;
1316 img->background_valid = 0;
1318 #endif
1321 if (flags & CLEAR_IMAGE_MASK)
1323 if (img->mask)
1325 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1326 img->mask = NO_PIXMAP;
1327 img->background_transparent_valid = 0;
1329 #ifdef HAVE_X_WINDOWS
1330 if (img->mask_img)
1332 x_destroy_x_image (img->mask_img);
1333 img->mask_img = NULL;
1334 img->background_transparent_valid = 0;
1336 #endif
1339 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1341 /* W32_TODO: color table support. */
1342 #ifdef HAVE_X_WINDOWS
1343 x_free_colors (f, img->colors, img->ncolors);
1344 #endif /* HAVE_X_WINDOWS */
1345 xfree (img->colors);
1346 img->colors = NULL;
1347 img->ncolors = 0;
1352 /* Free X resources of image IMG which is used on frame F. */
1354 static void
1355 x_clear_image (struct frame *f, struct image *img)
1357 block_input ();
1358 #ifdef USE_CAIRO
1359 if (img->cr_data)
1360 cairo_surface_destroy ((cairo_surface_t *)img->cr_data);
1361 if (img->cr_data2) xfree (img->cr_data2);
1362 #endif
1363 x_clear_image_1 (f, img,
1364 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1365 unblock_input ();
1369 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1370 cannot be allocated, use DFLT. Add a newly allocated color to
1371 IMG->colors, so that it can be freed again. Value is the pixel
1372 color. */
1374 static unsigned long
1375 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1376 unsigned long dflt)
1378 XColor color;
1379 unsigned long result;
1381 eassert (STRINGP (color_name));
1383 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1384 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1385 INT_MAX))
1387 /* This isn't called frequently so we get away with simply
1388 reallocating the color vector to the needed size, here. */
1389 ptrdiff_t ncolors = img->ncolors + 1;
1390 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1391 img->colors[ncolors - 1] = color.pixel;
1392 img->ncolors = ncolors;
1393 result = color.pixel;
1395 else
1396 result = dflt;
1398 return result;
1403 /***********************************************************************
1404 Image Cache
1405 ***********************************************************************/
1407 static void cache_image (struct frame *f, struct image *img);
1409 /* Return a new, initialized image cache that is allocated from the
1410 heap. Call free_image_cache to free an image cache. */
1412 struct image_cache *
1413 make_image_cache (void)
1415 struct image_cache *c = xmalloc (sizeof *c);
1417 c->size = 50;
1418 c->used = c->refcount = 0;
1419 c->images = xmalloc (c->size * sizeof *c->images);
1420 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1421 return c;
1425 /* Find an image matching SPEC in the cache, and return it. If no
1426 image is found, return NULL. */
1427 static struct image *
1428 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1430 struct image *img;
1431 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1432 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1434 if (!c) return NULL;
1436 /* If the image spec does not specify a background color, the cached
1437 image must have the same background color as the current frame.
1438 The foreground color must also match, for the sake of monochrome
1439 images.
1441 In fact, we could ignore the foreground color matching condition
1442 for color images, or if the image spec specifies :foreground;
1443 similarly we could ignore the background color matching condition
1444 for formats that don't use transparency (such as jpeg), or if the
1445 image spec specifies :background. However, the extra memory
1446 usage is probably negligible in practice, so we don't bother. */
1448 for (img = c->buckets[i]; img; img = img->next)
1449 if (img->hash == hash
1450 && !NILP (Fequal (img->spec, spec))
1451 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1452 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1453 break;
1454 return img;
1458 /* Search frame F for an image with spec SPEC, and free it. */
1460 static void
1461 uncache_image (struct frame *f, Lisp_Object spec)
1463 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1464 if (img)
1466 free_image (f, img);
1467 /* As display glyphs may still be referring to the image ID, we
1468 must garbage the frame (Bug#6426). */
1469 SET_FRAME_GARBAGED (f);
1474 /* Free image cache of frame F. Be aware that X frames share images
1475 caches. */
1477 void
1478 free_image_cache (struct frame *f)
1480 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1481 if (c)
1483 ptrdiff_t i;
1485 /* Cache should not be referenced by any frame when freed. */
1486 eassert (c->refcount == 0);
1488 for (i = 0; i < c->used; ++i)
1489 free_image (f, c->images[i]);
1490 xfree (c->images);
1491 xfree (c->buckets);
1492 xfree (c);
1493 FRAME_IMAGE_CACHE (f) = NULL;
1498 /* Clear image cache of frame F. FILTER=t means free all images.
1499 FILTER=nil means clear only images that haven't been
1500 displayed for some time.
1501 Else, only free the images which have FILTER in their `dependencies'.
1502 Should be called from time to time to reduce the number of loaded images.
1503 If image-cache-eviction-delay is non-nil, this frees images in the cache
1504 which weren't displayed for at least that many seconds. */
1506 static void
1507 clear_image_cache (struct frame *f, Lisp_Object filter)
1509 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1511 if (c)
1513 ptrdiff_t i, nfreed = 0;
1515 /* Block input so that we won't be interrupted by a SIGIO
1516 while being in an inconsistent state. */
1517 block_input ();
1519 if (!NILP (filter))
1521 /* Filter image cache. */
1522 for (i = 0; i < c->used; ++i)
1524 struct image *img = c->images[i];
1525 if (img && (EQ (Qt, filter)
1526 || !NILP (Fmember (filter, img->dependencies))))
1528 free_image (f, img);
1529 ++nfreed;
1533 else if (INTEGERP (Vimage_cache_eviction_delay))
1535 /* Free cache based on timestamp. */
1536 struct timespec old, t;
1537 double delay;
1538 ptrdiff_t nimages = 0;
1540 for (i = 0; i < c->used; ++i)
1541 if (c->images[i])
1542 nimages++;
1544 /* If the number of cached images has grown unusually large,
1545 decrease the cache eviction delay (Bug#6230). */
1546 delay = XINT (Vimage_cache_eviction_delay);
1547 if (nimages > 40)
1548 delay = 1600 * delay / nimages / nimages;
1549 delay = max (delay, 1);
1551 t = current_timespec ();
1552 old = timespec_sub (t, dtotimespec (delay));
1554 for (i = 0; i < c->used; ++i)
1556 struct image *img = c->images[i];
1557 if (img && timespec_cmp (img->timestamp, old) < 0)
1559 free_image (f, img);
1560 ++nfreed;
1565 /* We may be clearing the image cache because, for example,
1566 Emacs was iconified for a longer period of time. In that
1567 case, current matrices may still contain references to
1568 images freed above. So, clear these matrices. */
1569 if (nfreed)
1571 Lisp_Object tail, frame;
1573 FOR_EACH_FRAME (tail, frame)
1575 struct frame *fr = XFRAME (frame);
1576 if (FRAME_IMAGE_CACHE (fr) == c)
1577 clear_current_matrices (fr);
1580 windows_or_buffers_changed = 19;
1583 unblock_input ();
1587 void
1588 clear_image_caches (Lisp_Object filter)
1590 /* FIXME: We want to do
1591 * struct terminal *t;
1592 * for (t = terminal_list; t; t = t->next_terminal)
1593 * clear_image_cache (t, filter); */
1594 Lisp_Object tail, frame;
1595 FOR_EACH_FRAME (tail, frame)
1596 if (FRAME_WINDOW_P (XFRAME (frame)))
1597 clear_image_cache (XFRAME (frame), filter);
1600 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1601 0, 1, 0,
1602 doc: /* Clear the image cache.
1603 FILTER nil or a frame means clear all images in the selected frame.
1604 FILTER t means clear the image caches of all frames.
1605 Anything else, means only clear those images which refer to FILTER,
1606 which is then usually a filename. */)
1607 (Lisp_Object filter)
1609 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1610 clear_image_caches (filter);
1611 else
1612 clear_image_cache (decode_window_system_frame (filter), Qt);
1614 return Qnil;
1618 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1619 1, 2, 0,
1620 doc: /* Flush the image with specification SPEC on frame FRAME.
1621 This removes the image from the Emacs image cache. If SPEC specifies
1622 an image file, the next redisplay of this image will read from the
1623 current contents of that file.
1625 FRAME nil or omitted means use the selected frame.
1626 FRAME t means refresh the image on all frames. */)
1627 (Lisp_Object spec, Lisp_Object frame)
1629 if (!valid_image_p (spec))
1630 error ("Invalid image specification");
1632 if (EQ (frame, Qt))
1634 Lisp_Object tail;
1635 FOR_EACH_FRAME (tail, frame)
1637 struct frame *f = XFRAME (frame);
1638 if (FRAME_WINDOW_P (f))
1639 uncache_image (f, spec);
1642 else
1643 uncache_image (decode_window_system_frame (frame), spec);
1645 return Qnil;
1649 /* Compute masks and transform image IMG on frame F, as specified
1650 by the image's specification, */
1652 static void
1653 postprocess_image (struct frame *f, struct image *img)
1655 /* Manipulation of the image's mask. */
1656 if (img->pixmap)
1658 Lisp_Object conversion, spec;
1659 Lisp_Object mask;
1661 spec = img->spec;
1663 /* `:heuristic-mask t'
1664 `:mask heuristic'
1665 means build a mask heuristically.
1666 `:heuristic-mask (R G B)'
1667 `:mask (heuristic (R G B))'
1668 means build a mask from color (R G B) in the
1669 image.
1670 `:mask nil'
1671 means remove a mask, if any. */
1673 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1674 if (!NILP (mask))
1675 x_build_heuristic_mask (f, img, mask);
1676 else
1678 bool found_p;
1680 mask = image_spec_value (spec, QCmask, &found_p);
1682 if (EQ (mask, Qheuristic))
1683 x_build_heuristic_mask (f, img, Qt);
1684 else if (CONSP (mask)
1685 && EQ (XCAR (mask), Qheuristic))
1687 if (CONSP (XCDR (mask)))
1688 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1689 else
1690 x_build_heuristic_mask (f, img, XCDR (mask));
1692 else if (NILP (mask) && found_p && img->mask)
1693 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1697 /* Should we apply an image transformation algorithm? */
1698 conversion = image_spec_value (spec, QCconversion, NULL);
1699 if (EQ (conversion, Qdisabled))
1700 x_disable_image (f, img);
1701 else if (EQ (conversion, Qlaplace))
1702 x_laplace (f, img);
1703 else if (EQ (conversion, Qemboss))
1704 x_emboss (f, img);
1705 else if (CONSP (conversion)
1706 && EQ (XCAR (conversion), Qedge_detection))
1708 Lisp_Object tem;
1709 tem = XCDR (conversion);
1710 if (CONSP (tem))
1711 x_edge_detection (f, img,
1712 Fplist_get (tem, QCmatrix),
1713 Fplist_get (tem, QCcolor_adjustment));
1719 /* Return the id of image with Lisp specification SPEC on frame F.
1720 SPEC must be a valid Lisp image specification (see valid_image_p). */
1722 ptrdiff_t
1723 lookup_image (struct frame *f, Lisp_Object spec)
1725 struct image *img;
1726 EMACS_UINT hash;
1728 /* F must be a window-system frame, and SPEC must be a valid image
1729 specification. */
1730 eassert (FRAME_WINDOW_P (f));
1731 eassert (valid_image_p (spec));
1733 /* Look up SPEC in the hash table of the image cache. */
1734 hash = sxhash (spec, 0);
1735 img = search_image_cache (f, spec, hash);
1736 if (img && img->load_failed_p)
1738 free_image (f, img);
1739 img = NULL;
1742 /* If not found, create a new image and cache it. */
1743 if (img == NULL)
1745 block_input ();
1746 img = make_image (spec, hash);
1747 cache_image (f, img);
1748 img->load_failed_p = ! img->type->load (f, img);
1749 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1750 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1752 /* If we can't load the image, and we don't have a width and
1753 height, use some arbitrary width and height so that we can
1754 draw a rectangle for it. */
1755 if (img->load_failed_p)
1757 Lisp_Object value;
1759 value = image_spec_value (spec, QCwidth, NULL);
1760 img->width = (INTEGERP (value)
1761 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1762 value = image_spec_value (spec, QCheight, NULL);
1763 img->height = (INTEGERP (value)
1764 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1766 else
1768 /* Handle image type independent image attributes
1769 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1770 `:background COLOR'. */
1771 Lisp_Object ascent, margin, relief, bg;
1772 int relief_bound;
1774 ascent = image_spec_value (spec, QCascent, NULL);
1775 if (INTEGERP (ascent))
1776 img->ascent = XFASTINT (ascent);
1777 else if (EQ (ascent, Qcenter))
1778 img->ascent = CENTERED_IMAGE_ASCENT;
1780 margin = image_spec_value (spec, QCmargin, NULL);
1781 if (INTEGERP (margin))
1782 img->vmargin = img->hmargin = XFASTINT (margin);
1783 else if (CONSP (margin))
1785 img->hmargin = XFASTINT (XCAR (margin));
1786 img->vmargin = XFASTINT (XCDR (margin));
1789 relief = image_spec_value (spec, QCrelief, NULL);
1790 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1791 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1793 img->relief = XINT (relief);
1794 img->hmargin += eabs (img->relief);
1795 img->vmargin += eabs (img->relief);
1798 if (! img->background_valid)
1800 bg = image_spec_value (img->spec, QCbackground, NULL);
1801 if (!NILP (bg))
1803 img->background
1804 = x_alloc_image_color (f, img, bg,
1805 FRAME_BACKGROUND_PIXEL (f));
1806 img->background_valid = 1;
1810 /* Do image transformations and compute masks, unless we
1811 don't have the image yet. */
1812 if (!EQ (builtin_lisp_symbol (img->type->type), Qpostscript))
1813 postprocess_image (f, img);
1816 unblock_input ();
1819 /* We're using IMG, so set its timestamp to `now'. */
1820 img->timestamp = current_timespec ();
1822 /* Value is the image id. */
1823 return img->id;
1827 /* Cache image IMG in the image cache of frame F. */
1829 static void
1830 cache_image (struct frame *f, struct image *img)
1832 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1833 ptrdiff_t i;
1835 /* Find a free slot in c->images. */
1836 for (i = 0; i < c->used; ++i)
1837 if (c->images[i] == NULL)
1838 break;
1840 /* If no free slot found, maybe enlarge c->images. */
1841 if (i == c->used && c->used == c->size)
1842 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1844 /* Add IMG to c->images, and assign IMG an id. */
1845 c->images[i] = img;
1846 img->id = i;
1847 if (i == c->used)
1848 ++c->used;
1850 /* Add IMG to the cache's hash table. */
1851 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1852 img->next = c->buckets[i];
1853 if (img->next)
1854 img->next->prev = img;
1855 img->prev = NULL;
1856 c->buckets[i] = img;
1860 /* Call FN on every image in the image cache of frame F. Used to mark
1861 Lisp Objects in the image cache. */
1863 /* Mark Lisp objects in image IMG. */
1865 static void
1866 mark_image (struct image *img)
1868 mark_object (img->spec);
1869 mark_object (img->dependencies);
1871 if (!NILP (img->lisp_data))
1872 mark_object (img->lisp_data);
1876 void
1877 mark_image_cache (struct image_cache *c)
1879 if (c)
1881 ptrdiff_t i;
1882 for (i = 0; i < c->used; ++i)
1883 if (c->images[i])
1884 mark_image (c->images[i]);
1890 /***********************************************************************
1891 X / NS / W32 support code
1892 ***********************************************************************/
1894 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1895 windowing system.
1896 WIDTH and HEIGHT must both be positive.
1897 If XIMG is null, assume it is a bitmap. */
1898 static bool
1899 x_check_image_size (XImagePtr ximg, int width, int height)
1901 #ifdef HAVE_X_WINDOWS
1902 /* Respect Xlib's limits: it cannot deal with images that have more
1903 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1904 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1905 enum
1907 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1908 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1911 int bitmap_pad, depth, bytes_per_line;
1912 if (ximg)
1914 bitmap_pad = ximg->bitmap_pad;
1915 depth = ximg->depth;
1916 bytes_per_line = ximg->bytes_per_line;
1918 else
1920 bitmap_pad = 8;
1921 depth = 1;
1922 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1924 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1925 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1926 #else
1927 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1928 For now, assume that every image size is allowed on these systems. */
1929 return 1;
1930 #endif
1933 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1934 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1935 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1936 via xmalloc. Print error messages via image_error if an error
1937 occurs. Value is true if successful.
1939 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1940 should indicate the bit depth of the image. */
1942 static bool
1943 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1944 XImagePtr *ximg, Pixmap *pixmap)
1946 #ifdef HAVE_X_WINDOWS
1947 Display *display = FRAME_X_DISPLAY (f);
1948 Window window = FRAME_X_WINDOW (f);
1949 Screen *screen = FRAME_X_SCREEN (f);
1951 eassert (input_blocked_p ());
1953 if (depth <= 0)
1954 depth = DefaultDepthOfScreen (screen);
1955 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1956 depth, ZPixmap, 0, NULL, width, height,
1957 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1958 if (*ximg == NULL)
1960 image_error ("Unable to allocate X image");
1961 return 0;
1964 if (! x_check_image_size (*ximg, width, height))
1966 x_destroy_x_image (*ximg);
1967 *ximg = NULL;
1968 image_error ("Image too large (%dx%d)",
1969 make_number (width), make_number (height));
1970 return 0;
1973 /* Allocate image raster. */
1974 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1976 /* Allocate a pixmap of the same size. */
1977 *pixmap = XCreatePixmap (display, window, width, height, depth);
1978 if (*pixmap == NO_PIXMAP)
1980 x_destroy_x_image (*ximg);
1981 *ximg = NULL;
1982 image_error ("Unable to create X pixmap");
1983 return 0;
1986 return 1;
1987 #endif /* HAVE_X_WINDOWS */
1989 #ifdef HAVE_NTGUI
1991 BITMAPINFOHEADER *header;
1992 HDC hdc;
1993 int scanline_width_bits;
1994 int remainder;
1995 int palette_colors = 0;
1997 if (depth == 0)
1998 depth = 24;
2000 if (depth != 1 && depth != 4 && depth != 8
2001 && depth != 16 && depth != 24 && depth != 32)
2003 image_error ("Invalid image bit depth specified");
2004 return 0;
2007 scanline_width_bits = width * depth;
2008 remainder = scanline_width_bits % 32;
2010 if (remainder)
2011 scanline_width_bits += 32 - remainder;
2013 /* Bitmaps with a depth less than 16 need a palette. */
2014 /* BITMAPINFO structure already contains the first RGBQUAD. */
2015 if (depth < 16)
2016 palette_colors = 1 << (depth - 1);
2018 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2020 header = &(*ximg)->info.bmiHeader;
2021 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2022 header->biSize = sizeof (*header);
2023 header->biWidth = width;
2024 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2025 header->biPlanes = 1;
2026 header->biBitCount = depth;
2027 header->biCompression = BI_RGB;
2028 header->biClrUsed = palette_colors;
2030 /* TODO: fill in palette. */
2031 if (depth == 1)
2033 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2034 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2035 (*ximg)->info.bmiColors[0].rgbRed = 0;
2036 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2037 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2038 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2039 (*ximg)->info.bmiColors[1].rgbRed = 255;
2040 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2043 hdc = get_frame_dc (f);
2045 /* Create a DIBSection and raster array for the bitmap,
2046 and store its handle in *pixmap. */
2047 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2048 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2049 /* casting avoids a GCC warning */
2050 (void **)&((*ximg)->data), NULL, 0);
2052 /* Realize display palette and garbage all frames. */
2053 release_frame_dc (f, hdc);
2055 if (*pixmap == NULL)
2057 DWORD err = GetLastError ();
2058 Lisp_Object errcode;
2059 /* All system errors are < 10000, so the following is safe. */
2060 XSETINT (errcode, err);
2061 image_error ("Unable to create bitmap, error code %d", errcode);
2062 x_destroy_x_image (*ximg);
2063 *ximg = NULL;
2064 return 0;
2067 return 1;
2069 #endif /* HAVE_NTGUI */
2071 #ifdef HAVE_NS
2072 *pixmap = ns_image_for_XPM (width, height, depth);
2073 if (*pixmap == 0)
2075 *ximg = NULL;
2076 image_error ("Unable to allocate NSImage for XPM pixmap");
2077 return 0;
2079 *ximg = *pixmap;
2080 return 1;
2081 #endif
2085 /* Destroy XImage XIMG. Free XIMG->data. */
2087 static void
2088 x_destroy_x_image (XImagePtr ximg)
2090 eassert (input_blocked_p ());
2091 if (ximg)
2093 #ifdef HAVE_X_WINDOWS
2094 xfree (ximg->data);
2095 ximg->data = NULL;
2096 XDestroyImage (ximg);
2097 #endif /* HAVE_X_WINDOWS */
2098 #ifdef HAVE_NTGUI
2099 /* Data will be freed by DestroyObject. */
2100 ximg->data = NULL;
2101 xfree (ximg);
2102 #endif /* HAVE_NTGUI */
2103 #ifdef HAVE_NS
2104 ns_release_object (ximg);
2105 #endif /* HAVE_NS */
2110 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2111 are width and height of both the image and pixmap. */
2113 static void
2114 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2116 #ifdef HAVE_X_WINDOWS
2117 GC gc;
2119 eassert (input_blocked_p ());
2120 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2121 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2122 XFreeGC (FRAME_X_DISPLAY (f), gc);
2123 #endif /* HAVE_X_WINDOWS */
2125 #ifdef HAVE_NTGUI
2126 #if 0 /* I don't think this is necessary looking at where it is used. */
2127 HDC hdc = get_frame_dc (f);
2128 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2129 release_frame_dc (f, hdc);
2130 #endif
2131 #endif /* HAVE_NTGUI */
2133 #ifdef HAVE_NS
2134 eassert (ximg == pixmap);
2135 ns_retain_object (ximg);
2136 #endif
2139 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2140 with image_put_x_image. */
2142 static bool
2143 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2144 int width, int height, int depth,
2145 XImagePtr *ximg, bool mask_p)
2147 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2149 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2150 !mask_p ? &img->pixmap : &img->mask);
2153 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2154 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2155 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2156 On the other platforms, it puts XIMG into the pixmap, then frees
2157 the X image and its buffer. */
2159 static void
2160 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2161 bool mask_p)
2163 #ifdef HAVE_X_WINDOWS
2164 if (!mask_p)
2166 eassert (img->ximg == NULL);
2167 img->ximg = ximg;
2169 else
2171 eassert (img->mask_img == NULL);
2172 img->mask_img = ximg;
2174 #else
2175 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2176 img->width, img->height);
2177 x_destroy_x_image (ximg);
2178 #endif
2181 #ifdef HAVE_X_WINDOWS
2182 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2183 the X images and their buffers. */
2185 static void
2186 image_sync_to_pixmaps (struct frame *f, struct image *img)
2188 if (img->ximg)
2190 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2191 x_destroy_x_image (img->ximg);
2192 img->ximg = NULL;
2194 if (img->mask_img)
2196 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2197 x_destroy_x_image (img->mask_img);
2198 img->mask_img = NULL;
2201 #endif
2203 #ifdef HAVE_NTGUI
2204 /* Create a memory device context for IMG on frame F. It stores the
2205 currently selected GDI object into *PREV for future restoration by
2206 image_unget_x_image_or_dc. */
2208 static XImagePtr_or_DC
2209 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2210 HGDIOBJ *prev)
2212 HDC frame_dc = get_frame_dc (f);
2213 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2215 release_frame_dc (f, frame_dc);
2216 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2218 return ximg;
2221 static void
2222 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2223 XImagePtr_or_DC ximg, HGDIOBJ prev)
2225 SelectObject (ximg, prev);
2226 DeleteDC (ximg);
2228 #else /* !HAVE_NTGUI */
2229 /* Get the X image for IMG on frame F. The resulting X image data
2230 should be treated as read-only at least on X. */
2232 static XImagePtr
2233 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2235 #ifdef HAVE_X_WINDOWS
2236 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2238 if (ximg_in_img)
2239 return ximg_in_img;
2240 else
2241 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2242 0, 0, img->width, img->height, ~0, ZPixmap);
2243 #elif defined (HAVE_NS)
2244 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2246 ns_retain_object (pixmap);
2247 return pixmap;
2248 #endif
2251 static void
2252 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2254 #ifdef HAVE_X_WINDOWS
2255 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2257 if (ximg_in_img)
2258 eassert (ximg == ximg_in_img);
2259 else
2260 XDestroyImage (ximg);
2261 #elif defined (HAVE_NS)
2262 ns_release_object (ximg);
2263 #endif
2265 #endif /* !HAVE_NTGUI */
2268 /***********************************************************************
2269 File Handling
2270 ***********************************************************************/
2272 /* Find image file FILE. Look in data-directory/images, then
2273 x-bitmap-file-path. Value is the encoded full name of the file
2274 found, or nil if not found. */
2276 Lisp_Object
2277 x_find_image_file (Lisp_Object file)
2279 Lisp_Object file_found, search_path;
2280 int fd;
2282 /* TODO I think this should use something like image-load-path
2283 instead. Unfortunately, that can contain non-string elements. */
2284 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2285 Vdata_directory),
2286 Vx_bitmap_file_path);
2288 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2289 fd = openp (search_path, file, Qnil, &file_found, Qnil, false);
2291 if (fd == -1)
2292 file_found = Qnil;
2293 else
2295 file_found = ENCODE_FILE (file_found);
2296 if (fd != -2)
2297 emacs_close (fd);
2300 return file_found;
2304 /* Read FILE into memory. Value is a pointer to a buffer allocated
2305 with xmalloc holding FILE's contents. Value is null if an error
2306 occurred. *SIZE is set to the size of the file. */
2308 static unsigned char *
2309 slurp_file (char *file, ptrdiff_t *size)
2311 FILE *fp = emacs_fopen (file, "rb");
2312 unsigned char *buf = NULL;
2313 struct stat st;
2315 if (fp)
2317 ptrdiff_t count = SPECPDL_INDEX ();
2318 record_unwind_protect_ptr (fclose_unwind, fp);
2320 if (fstat (fileno (fp), &st) == 0
2321 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2323 /* Report an error if we read past the purported EOF.
2324 This can happen if the file grows as we read it. */
2325 ptrdiff_t buflen = st.st_size;
2326 buf = xmalloc (buflen + 1);
2327 if (fread (buf, 1, buflen + 1, fp) == buflen)
2328 *size = buflen;
2329 else
2331 xfree (buf);
2332 buf = NULL;
2336 unbind_to (count, Qnil);
2339 return buf;
2344 /***********************************************************************
2345 XBM images
2346 ***********************************************************************/
2348 static bool xbm_load (struct frame *f, struct image *img);
2349 static bool xbm_image_p (Lisp_Object object);
2350 static bool xbm_file_p (Lisp_Object);
2353 /* Indices of image specification fields in xbm_format, below. */
2355 enum xbm_keyword_index
2357 XBM_TYPE,
2358 XBM_FILE,
2359 XBM_WIDTH,
2360 XBM_HEIGHT,
2361 XBM_DATA,
2362 XBM_FOREGROUND,
2363 XBM_BACKGROUND,
2364 XBM_ASCENT,
2365 XBM_MARGIN,
2366 XBM_RELIEF,
2367 XBM_ALGORITHM,
2368 XBM_HEURISTIC_MASK,
2369 XBM_MASK,
2370 XBM_LAST
2373 /* Vector of image_keyword structures describing the format
2374 of valid XBM image specifications. */
2376 static const struct image_keyword xbm_format[XBM_LAST] =
2378 {":type", IMAGE_SYMBOL_VALUE, 1},
2379 {":file", IMAGE_STRING_VALUE, 0},
2380 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2381 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2382 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2383 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2384 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2385 {":ascent", IMAGE_ASCENT_VALUE, 0},
2386 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2387 {":relief", IMAGE_INTEGER_VALUE, 0},
2388 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2389 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2390 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2393 /* Structure describing the image type XBM. */
2395 static struct image_type xbm_type =
2397 SYMBOL_INDEX (Qxbm),
2398 xbm_image_p,
2399 xbm_load,
2400 x_clear_image,
2401 NULL,
2402 NULL
2405 /* Tokens returned from xbm_scan. */
2407 enum xbm_token
2409 XBM_TK_IDENT = 256,
2410 XBM_TK_NUMBER
2414 /* Return true if OBJECT is a valid XBM-type image specification.
2415 A valid specification is a list starting with the symbol `image'
2416 The rest of the list is a property list which must contain an
2417 entry `:type xbm'.
2419 If the specification specifies a file to load, it must contain
2420 an entry `:file FILENAME' where FILENAME is a string.
2422 If the specification is for a bitmap loaded from memory it must
2423 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2424 WIDTH and HEIGHT are integers > 0. DATA may be:
2426 1. a string large enough to hold the bitmap data, i.e. it must
2427 have a size >= (WIDTH + 7) / 8 * HEIGHT
2429 2. a bool-vector of size >= WIDTH * HEIGHT
2431 3. a vector of strings or bool-vectors, one for each line of the
2432 bitmap.
2434 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2435 may not be specified in this case because they are defined in the
2436 XBM file.
2438 Both the file and data forms may contain the additional entries
2439 `:background COLOR' and `:foreground COLOR'. If not present,
2440 foreground and background of the frame on which the image is
2441 displayed is used. */
2443 static bool
2444 xbm_image_p (Lisp_Object object)
2446 struct image_keyword kw[XBM_LAST];
2448 memcpy (kw, xbm_format, sizeof kw);
2449 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2450 return 0;
2452 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2454 if (kw[XBM_FILE].count)
2456 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2457 return 0;
2459 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2461 /* In-memory XBM file. */
2462 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2463 return 0;
2465 else
2467 Lisp_Object data;
2468 int width, height;
2470 /* Entries for `:width', `:height' and `:data' must be present. */
2471 if (!kw[XBM_WIDTH].count
2472 || !kw[XBM_HEIGHT].count
2473 || !kw[XBM_DATA].count)
2474 return 0;
2476 data = kw[XBM_DATA].value;
2477 width = XFASTINT (kw[XBM_WIDTH].value);
2478 height = XFASTINT (kw[XBM_HEIGHT].value);
2480 /* Check type of data, and width and height against contents of
2481 data. */
2482 if (VECTORP (data))
2484 EMACS_INT i;
2486 /* Number of elements of the vector must be >= height. */
2487 if (ASIZE (data) < height)
2488 return 0;
2490 /* Each string or bool-vector in data must be large enough
2491 for one line of the image. */
2492 for (i = 0; i < height; ++i)
2494 Lisp_Object elt = AREF (data, i);
2496 if (STRINGP (elt))
2498 if (SCHARS (elt)
2499 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2500 return 0;
2502 else if (BOOL_VECTOR_P (elt))
2504 if (bool_vector_size (elt) < width)
2505 return 0;
2507 else
2508 return 0;
2511 else if (STRINGP (data))
2513 if (SCHARS (data)
2514 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2515 return 0;
2517 else if (BOOL_VECTOR_P (data))
2519 if (bool_vector_size (data) / height < width)
2520 return 0;
2522 else
2523 return 0;
2526 return 1;
2530 /* Scan a bitmap file. FP is the stream to read from. Value is
2531 either an enumerator from enum xbm_token, or a character for a
2532 single-character token, or 0 at end of file. If scanning an
2533 identifier, store the lexeme of the identifier in SVAL. If
2534 scanning a number, store its value in *IVAL. */
2536 static int
2537 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2539 unsigned int c;
2541 loop:
2543 /* Skip white space. */
2544 while (*s < end && (c = *(*s)++, c_isspace (c)))
2547 if (*s >= end)
2548 c = 0;
2549 else if (c_isdigit (c))
2551 int value = 0, digit;
2553 if (c == '0' && *s < end)
2555 c = *(*s)++;
2556 if (c == 'x' || c == 'X')
2558 while (*s < end)
2560 c = *(*s)++;
2561 if (c_isdigit (c))
2562 digit = c - '0';
2563 else if (c >= 'a' && c <= 'f')
2564 digit = c - 'a' + 10;
2565 else if (c >= 'A' && c <= 'F')
2566 digit = c - 'A' + 10;
2567 else
2568 break;
2569 value = 16 * value + digit;
2572 else if (c_isdigit (c))
2574 value = c - '0';
2575 while (*s < end
2576 && (c = *(*s)++, c_isdigit (c)))
2577 value = 8 * value + c - '0';
2580 else
2582 value = c - '0';
2583 while (*s < end
2584 && (c = *(*s)++, c_isdigit (c)))
2585 value = 10 * value + c - '0';
2588 if (*s < end)
2589 *s = *s - 1;
2590 *ival = value;
2591 c = XBM_TK_NUMBER;
2593 else if (c_isalpha (c) || c == '_')
2595 *sval++ = c;
2596 while (*s < end
2597 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2598 *sval++ = c;
2599 *sval = 0;
2600 if (*s < end)
2601 *s = *s - 1;
2602 c = XBM_TK_IDENT;
2604 else if (c == '/' && **s == '*')
2606 /* C-style comment. */
2607 ++*s;
2608 while (**s && (**s != '*' || *(*s + 1) != '/'))
2609 ++*s;
2610 if (**s)
2612 *s += 2;
2613 goto loop;
2617 return c;
2620 #ifdef HAVE_NTGUI
2622 /* Create a Windows bitmap from X bitmap data. */
2623 static HBITMAP
2624 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2626 static unsigned char swap_nibble[16]
2627 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2628 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2629 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2630 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2631 int i, j, w1, w2;
2632 unsigned char *bits, *p;
2633 HBITMAP bmp;
2635 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2636 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2637 bits = alloca (height * w2);
2638 memset (bits, 0, height * w2);
2639 for (i = 0; i < height; i++)
2641 p = bits + i*w2;
2642 for (j = 0; j < w1; j++)
2644 /* Bitswap XBM bytes to match how Windows does things. */
2645 unsigned char c = *data++;
2646 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2647 | (swap_nibble[(c>>4) & 0xf]));
2650 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2652 return bmp;
2655 static void
2656 convert_mono_to_color_image (struct frame *f, struct image *img,
2657 COLORREF foreground, COLORREF background)
2659 HDC hdc, old_img_dc, new_img_dc;
2660 HGDIOBJ old_prev, new_prev;
2661 HBITMAP new_pixmap;
2663 hdc = get_frame_dc (f);
2664 old_img_dc = CreateCompatibleDC (hdc);
2665 new_img_dc = CreateCompatibleDC (hdc);
2666 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2667 release_frame_dc (f, hdc);
2668 old_prev = SelectObject (old_img_dc, img->pixmap);
2669 new_prev = SelectObject (new_img_dc, new_pixmap);
2670 /* Windows convention for mono bitmaps is black = background,
2671 white = foreground. */
2672 SetTextColor (new_img_dc, background);
2673 SetBkColor (new_img_dc, foreground);
2675 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2676 0, 0, SRCCOPY);
2678 SelectObject (old_img_dc, old_prev);
2679 SelectObject (new_img_dc, new_prev);
2680 DeleteDC (old_img_dc);
2681 DeleteDC (new_img_dc);
2682 DeleteObject (img->pixmap);
2683 if (new_pixmap == 0)
2684 fprintf (stderr, "Failed to convert image to color.\n");
2685 else
2686 img->pixmap = new_pixmap;
2689 #define XBM_BIT_SHUFFLE(b) (~(b))
2691 #else
2693 #define XBM_BIT_SHUFFLE(b) (b)
2695 #endif /* HAVE_NTGUI */
2698 static void
2699 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2700 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2701 bool non_default_colors)
2703 #ifdef HAVE_NTGUI
2704 img->pixmap
2705 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2707 /* If colors were specified, transfer the bitmap to a color one. */
2708 if (non_default_colors)
2709 convert_mono_to_color_image (f, img, fg, bg);
2711 #elif defined (HAVE_NS)
2712 img->pixmap = ns_image_from_XBM (data, img->width, img->height, fg, bg);
2714 #else
2715 img->pixmap =
2716 (x_check_image_size (0, img->width, img->height)
2717 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2718 FRAME_X_WINDOW (f),
2719 data,
2720 img->width, img->height,
2721 fg, bg,
2722 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2723 : NO_PIXMAP);
2724 #endif /* !HAVE_NTGUI && !HAVE_NS */
2729 /* Replacement for XReadBitmapFileData which isn't available under old
2730 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2731 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2732 the image. Return in *DATA the bitmap data allocated with xmalloc.
2733 Value is true if successful. DATA null means just test if
2734 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2735 inhibit the call to image_error when the image size is invalid (the
2736 bitmap remains unread). */
2738 static bool
2739 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2740 int *width, int *height, char **data,
2741 bool inhibit_image_error)
2743 unsigned char *s = contents;
2744 char buffer[BUFSIZ];
2745 bool padding_p = 0;
2746 bool v10 = 0;
2747 int bytes_per_line, i, nbytes;
2748 char *p;
2749 int value;
2750 int LA1;
2752 #define match() \
2753 LA1 = xbm_scan (&s, end, buffer, &value)
2755 #define expect(TOKEN) \
2756 do \
2758 if (LA1 != (TOKEN)) \
2759 goto failure; \
2760 match (); \
2762 while (0)
2764 #define expect_ident(IDENT) \
2765 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2766 match (); \
2767 else \
2768 goto failure
2770 *width = *height = -1;
2771 if (data)
2772 *data = NULL;
2773 LA1 = xbm_scan (&s, end, buffer, &value);
2775 /* Parse defines for width, height and hot-spots. */
2776 while (LA1 == '#')
2778 match ();
2779 expect_ident ("define");
2780 expect (XBM_TK_IDENT);
2782 if (LA1 == XBM_TK_NUMBER)
2784 char *q = strrchr (buffer, '_');
2785 q = q ? q + 1 : buffer;
2786 if (strcmp (q, "width") == 0)
2787 *width = value;
2788 else if (strcmp (q, "height") == 0)
2789 *height = value;
2791 expect (XBM_TK_NUMBER);
2794 if (!check_image_size (f, *width, *height))
2796 if (!inhibit_image_error)
2797 image_error ("Invalid image size (see `max-image-size')");
2798 goto failure;
2800 else if (data == NULL)
2801 goto success;
2803 /* Parse bits. Must start with `static'. */
2804 expect_ident ("static");
2805 if (LA1 == XBM_TK_IDENT)
2807 if (strcmp (buffer, "unsigned") == 0)
2809 match ();
2810 expect_ident ("char");
2812 else if (strcmp (buffer, "short") == 0)
2814 match ();
2815 v10 = 1;
2816 if (*width % 16 && *width % 16 < 9)
2817 padding_p = 1;
2819 else if (strcmp (buffer, "char") == 0)
2820 match ();
2821 else
2822 goto failure;
2824 else
2825 goto failure;
2827 expect (XBM_TK_IDENT);
2828 expect ('[');
2829 expect (']');
2830 expect ('=');
2831 expect ('{');
2833 if (! x_check_image_size (0, *width, *height))
2835 if (!inhibit_image_error)
2836 image_error ("Image too large (%dx%d)",
2837 make_number (*width), make_number (*height));
2838 goto failure;
2840 bytes_per_line = (*width + 7) / 8 + padding_p;
2841 nbytes = bytes_per_line * *height;
2842 p = *data = xmalloc (nbytes);
2844 if (v10)
2846 for (i = 0; i < nbytes; i += 2)
2848 int val = value;
2849 expect (XBM_TK_NUMBER);
2851 *p++ = XBM_BIT_SHUFFLE (val);
2852 if (!padding_p || ((i + 2) % bytes_per_line))
2853 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2855 if (LA1 == ',' || LA1 == '}')
2856 match ();
2857 else
2858 goto failure;
2861 else
2863 for (i = 0; i < nbytes; ++i)
2865 int val = value;
2866 expect (XBM_TK_NUMBER);
2868 *p++ = XBM_BIT_SHUFFLE (val);
2870 if (LA1 == ',' || LA1 == '}')
2871 match ();
2872 else
2873 goto failure;
2877 success:
2878 return 1;
2880 failure:
2882 if (data && *data)
2884 xfree (*data);
2885 *data = NULL;
2887 return 0;
2889 #undef match
2890 #undef expect
2891 #undef expect_ident
2895 /* Load XBM image IMG which will be displayed on frame F from buffer
2896 CONTENTS. END is the end of the buffer. Value is true if
2897 successful. */
2899 static bool
2900 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2901 unsigned char *end)
2903 bool rc;
2904 char *data;
2905 bool success_p = 0;
2907 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2908 &data, 0);
2909 if (rc)
2911 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2912 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2913 bool non_default_colors = 0;
2914 Lisp_Object value;
2916 eassert (img->width > 0 && img->height > 0);
2918 /* Get foreground and background colors, maybe allocate colors. */
2919 value = image_spec_value (img->spec, QCforeground, NULL);
2920 if (!NILP (value))
2922 foreground = x_alloc_image_color (f, img, value, foreground);
2923 non_default_colors = 1;
2925 value = image_spec_value (img->spec, QCbackground, NULL);
2926 if (!NILP (value))
2928 background = x_alloc_image_color (f, img, value, background);
2929 img->background = background;
2930 img->background_valid = 1;
2931 non_default_colors = 1;
2934 Create_Pixmap_From_Bitmap_Data (f, img, data,
2935 foreground, background,
2936 non_default_colors);
2937 xfree (data);
2939 if (img->pixmap == NO_PIXMAP)
2941 x_clear_image (f, img);
2942 image_error ("Unable to create X pixmap for `%s'", img->spec);
2944 else
2945 success_p = 1;
2947 else
2948 image_error ("Error loading XBM image `%s'", img->spec);
2950 return success_p;
2954 /* Value is true if DATA looks like an in-memory XBM file. */
2956 static bool
2957 xbm_file_p (Lisp_Object data)
2959 int w, h;
2960 return (STRINGP (data)
2961 && xbm_read_bitmap_data (NULL, SDATA (data),
2962 (SDATA (data) + SBYTES (data)),
2963 &w, &h, NULL, 1));
2967 /* Fill image IMG which is used on frame F with pixmap data. Value is
2968 true if successful. */
2970 static bool
2971 xbm_load (struct frame *f, struct image *img)
2973 bool success_p = 0;
2974 Lisp_Object file_name;
2976 eassert (xbm_image_p (img->spec));
2978 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2979 file_name = image_spec_value (img->spec, QCfile, NULL);
2980 if (STRINGP (file_name))
2982 Lisp_Object file;
2983 unsigned char *contents;
2984 ptrdiff_t size;
2986 file = x_find_image_file (file_name);
2987 if (!STRINGP (file))
2989 image_error ("Cannot find image file `%s'", file_name);
2990 return 0;
2993 contents = slurp_file (SSDATA (file), &size);
2994 if (contents == NULL)
2996 image_error ("Error loading XBM image `%s'", img->spec);
2997 return 0;
3000 success_p = xbm_load_image (f, img, contents, contents + size);
3001 xfree (contents);
3003 else
3005 struct image_keyword fmt[XBM_LAST];
3006 Lisp_Object data;
3007 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3008 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3009 bool non_default_colors = 0;
3010 char *bits;
3011 bool parsed_p;
3012 bool in_memory_file_p = 0;
3014 /* See if data looks like an in-memory XBM file. */
3015 data = image_spec_value (img->spec, QCdata, NULL);
3016 in_memory_file_p = xbm_file_p (data);
3018 /* Parse the image specification. */
3019 memcpy (fmt, xbm_format, sizeof fmt);
3020 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3021 eassert (parsed_p);
3023 /* Get specified width, and height. */
3024 if (!in_memory_file_p)
3026 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3027 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3028 eassert (img->width > 0 && img->height > 0);
3029 if (!check_image_size (f, img->width, img->height))
3031 image_error ("Invalid image size (see `max-image-size')");
3032 return 0;
3036 /* Get foreground and background colors, maybe allocate colors. */
3037 if (fmt[XBM_FOREGROUND].count
3038 && STRINGP (fmt[XBM_FOREGROUND].value))
3040 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3041 foreground);
3042 non_default_colors = 1;
3045 if (fmt[XBM_BACKGROUND].count
3046 && STRINGP (fmt[XBM_BACKGROUND].value))
3048 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3049 background);
3050 non_default_colors = 1;
3053 if (in_memory_file_p)
3054 success_p = xbm_load_image (f, img, SDATA (data),
3055 (SDATA (data)
3056 + SBYTES (data)));
3057 else
3059 USE_SAFE_ALLOCA;
3061 if (VECTORP (data))
3063 int i;
3064 char *p;
3065 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3067 SAFE_NALLOCA (bits, nbytes, img->height);
3068 p = bits;
3069 for (i = 0; i < img->height; ++i, p += nbytes)
3071 Lisp_Object line = AREF (data, i);
3072 if (STRINGP (line))
3073 memcpy (p, SDATA (line), nbytes);
3074 else
3075 memcpy (p, bool_vector_data (line), nbytes);
3078 else if (STRINGP (data))
3079 bits = SSDATA (data);
3080 else
3081 bits = (char *) bool_vector_data (data);
3083 #ifdef HAVE_NTGUI
3085 char *invertedBits;
3086 int nbytes, i;
3087 /* Windows mono bitmaps are reversed compared with X. */
3088 invertedBits = bits;
3089 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3090 SAFE_NALLOCA (bits, nbytes, img->height);
3091 for (i = 0; i < nbytes; i++)
3092 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3094 #endif
3095 /* Create the pixmap. */
3097 if (x_check_image_size (0, img->width, img->height))
3098 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3099 foreground, background,
3100 non_default_colors);
3101 else
3102 img->pixmap = NO_PIXMAP;
3104 if (img->pixmap)
3105 success_p = 1;
3106 else
3108 image_error ("Unable to create pixmap for XBM image `%s'",
3109 img->spec);
3110 x_clear_image (f, img);
3113 SAFE_FREE ();
3117 return success_p;
3122 /***********************************************************************
3123 XPM images
3124 ***********************************************************************/
3126 #if defined (HAVE_XPM) || defined (HAVE_NS)
3128 static bool xpm_image_p (Lisp_Object object);
3129 static bool xpm_load (struct frame *f, struct image *img);
3131 #endif /* HAVE_XPM || HAVE_NS */
3133 #ifdef HAVE_XPM
3134 #ifdef HAVE_NTGUI
3135 /* Indicate to xpm.h that we don't have Xlib. */
3136 #define FOR_MSW
3137 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3138 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3139 #define XColor xpm_XColor
3140 #define XImage xpm_XImage
3141 #define Display xpm_Display
3142 #define PIXEL_ALREADY_TYPEDEFED
3143 #include "X11/xpm.h"
3144 #undef FOR_MSW
3145 #undef XColor
3146 #undef XImage
3147 #undef Display
3148 #undef PIXEL_ALREADY_TYPEDEFED
3149 #else
3150 #include "X11/xpm.h"
3151 #endif /* HAVE_NTGUI */
3152 #endif /* HAVE_XPM */
3154 #if defined (HAVE_XPM) || defined (HAVE_NS)
3156 /* Indices of image specification fields in xpm_format, below. */
3158 enum xpm_keyword_index
3160 XPM_TYPE,
3161 XPM_FILE,
3162 XPM_DATA,
3163 XPM_ASCENT,
3164 XPM_MARGIN,
3165 XPM_RELIEF,
3166 XPM_ALGORITHM,
3167 XPM_HEURISTIC_MASK,
3168 XPM_MASK,
3169 XPM_COLOR_SYMBOLS,
3170 XPM_BACKGROUND,
3171 XPM_LAST
3174 /* Vector of image_keyword structures describing the format
3175 of valid XPM image specifications. */
3177 static const struct image_keyword xpm_format[XPM_LAST] =
3179 {":type", IMAGE_SYMBOL_VALUE, 1},
3180 {":file", IMAGE_STRING_VALUE, 0},
3181 {":data", IMAGE_STRING_VALUE, 0},
3182 {":ascent", IMAGE_ASCENT_VALUE, 0},
3183 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3184 {":relief", IMAGE_INTEGER_VALUE, 0},
3185 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3186 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3187 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3188 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3189 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3192 #if defined HAVE_NTGUI && defined WINDOWSNT
3193 static bool init_xpm_functions (void);
3194 #else
3195 #define init_xpm_functions NULL
3196 #endif
3198 /* Structure describing the image type XPM. */
3200 static struct image_type xpm_type =
3202 SYMBOL_INDEX (Qxpm),
3203 xpm_image_p,
3204 xpm_load,
3205 x_clear_image,
3206 init_xpm_functions,
3207 NULL
3210 #ifdef HAVE_X_WINDOWS
3212 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3213 functions for allocating image colors. Our own functions handle
3214 color allocation failures more gracefully than the ones on the XPM
3215 lib. */
3217 #ifndef USE_CAIRO
3218 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3219 #define ALLOC_XPM_COLORS
3220 #endif
3221 #endif /* USE_CAIRO */
3222 #endif /* HAVE_X_WINDOWS */
3224 #ifdef ALLOC_XPM_COLORS
3226 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3227 XColor *, int);
3229 /* An entry in a hash table used to cache color definitions of named
3230 colors. This cache is necessary to speed up XPM image loading in
3231 case we do color allocations ourselves. Without it, we would need
3232 a call to XParseColor per pixel in the image. */
3234 struct xpm_cached_color
3236 /* Next in collision chain. */
3237 struct xpm_cached_color *next;
3239 /* Color definition (RGB and pixel color). */
3240 XColor color;
3242 /* Color name. */
3243 char name[FLEXIBLE_ARRAY_MEMBER];
3246 /* The hash table used for the color cache, and its bucket vector
3247 size. */
3249 #define XPM_COLOR_CACHE_BUCKETS 1001
3250 static struct xpm_cached_color **xpm_color_cache;
3252 /* Initialize the color cache. */
3254 static void
3255 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3257 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3258 xpm_color_cache = xzalloc (nbytes);
3259 init_color_table ();
3261 if (attrs->valuemask & XpmColorSymbols)
3263 int i;
3264 XColor color;
3266 for (i = 0; i < attrs->numsymbols; ++i)
3267 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3268 attrs->colorsymbols[i].value, &color))
3270 color.pixel = lookup_rgb_color (f, color.red, color.green,
3271 color.blue);
3272 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3277 /* Free the color cache. */
3279 static void
3280 xpm_free_color_cache (void)
3282 struct xpm_cached_color *p, *next;
3283 int i;
3285 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3286 for (p = xpm_color_cache[i]; p; p = next)
3288 next = p->next;
3289 xfree (p);
3292 xfree (xpm_color_cache);
3293 xpm_color_cache = NULL;
3294 free_color_table ();
3297 /* Return the bucket index for color named COLOR_NAME in the color
3298 cache. */
3300 static int
3301 xpm_color_bucket (char *color_name)
3303 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3304 return hash % XPM_COLOR_CACHE_BUCKETS;
3308 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3309 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3310 entry added. */
3312 static struct xpm_cached_color *
3313 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3315 size_t nbytes;
3316 struct xpm_cached_color *p;
3318 if (bucket < 0)
3319 bucket = xpm_color_bucket (color_name);
3321 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3322 p = xmalloc (nbytes);
3323 strcpy (p->name, color_name);
3324 p->color = *color;
3325 p->next = xpm_color_cache[bucket];
3326 xpm_color_cache[bucket] = p;
3327 return p;
3330 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3331 return the cached definition in *COLOR. Otherwise, make a new
3332 entry in the cache and allocate the color. Value is false if color
3333 allocation failed. */
3335 static bool
3336 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3338 struct xpm_cached_color *p;
3339 int h = xpm_color_bucket (color_name);
3341 for (p = xpm_color_cache[h]; p; p = p->next)
3342 if (strcmp (p->name, color_name) == 0)
3343 break;
3345 if (p != NULL)
3346 *color = p->color;
3347 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3348 color_name, color))
3350 color->pixel = lookup_rgb_color (f, color->red, color->green,
3351 color->blue);
3352 p = xpm_cache_color (f, color_name, color, h);
3354 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3355 with transparency, and it's useful. */
3356 else if (strcmp ("opaque", color_name) == 0)
3358 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3359 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3360 p = xpm_cache_color (f, color_name, color, h);
3363 return p != NULL;
3367 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3368 CLOSURE is a pointer to the frame on which we allocate the
3369 color. Return in *COLOR the allocated color. Value is non-zero
3370 if successful. */
3372 static int
3373 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3374 void *closure)
3376 return xpm_lookup_color (closure, color_name, color);
3380 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3381 is a pointer to the frame on which we allocate the color. Value is
3382 non-zero if successful. */
3384 static int
3385 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3387 return 1;
3390 #endif /* ALLOC_XPM_COLORS */
3393 #ifdef WINDOWSNT
3395 /* XPM library details. */
3397 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3398 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3399 (Display *, char *, xpm_XImage **,
3400 xpm_XImage **, XpmAttributes *));
3401 DEF_DLL_FN (int, XpmReadFileToImage,
3402 (Display *, char *, xpm_XImage **,
3403 xpm_XImage **, XpmAttributes *));
3404 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3406 static bool
3407 init_xpm_functions (void)
3409 HMODULE library;
3411 if (!(library = w32_delayed_load (Qxpm)))
3412 return 0;
3414 LOAD_DLL_FN (library, XpmFreeAttributes);
3415 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3416 LOAD_DLL_FN (library, XpmReadFileToImage);
3417 LOAD_DLL_FN (library, XImageFree);
3418 return 1;
3421 # undef XImageFree
3422 # undef XpmCreateImageFromBuffer
3423 # undef XpmFreeAttributes
3424 # undef XpmReadFileToImage
3426 # define XImageFree fn_XImageFree
3427 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3428 # define XpmFreeAttributes fn_XpmFreeAttributes
3429 # define XpmReadFileToImage fn_XpmReadFileToImage
3431 #endif /* WINDOWSNT */
3433 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3434 for XPM images. Such a list must consist of conses whose car and
3435 cdr are strings. */
3437 static bool
3438 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3440 while (CONSP (color_symbols))
3442 Lisp_Object sym = XCAR (color_symbols);
3443 if (!CONSP (sym)
3444 || !STRINGP (XCAR (sym))
3445 || !STRINGP (XCDR (sym)))
3446 break;
3447 color_symbols = XCDR (color_symbols);
3450 return NILP (color_symbols);
3454 /* Value is true if OBJECT is a valid XPM image specification. */
3456 static bool
3457 xpm_image_p (Lisp_Object object)
3459 struct image_keyword fmt[XPM_LAST];
3460 memcpy (fmt, xpm_format, sizeof fmt);
3461 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3462 /* Either `:file' or `:data' must be present. */
3463 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3464 /* Either no `:color-symbols' or it's a list of conses
3465 whose car and cdr are strings. */
3466 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3467 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3470 #endif /* HAVE_XPM || HAVE_NS */
3472 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3473 ptrdiff_t
3474 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3476 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3477 ptrdiff_t id;
3478 int rc;
3479 XpmAttributes attrs;
3480 Pixmap bitmap, mask;
3482 memset (&attrs, 0, sizeof attrs);
3484 attrs.visual = FRAME_X_VISUAL (f);
3485 attrs.colormap = FRAME_X_COLORMAP (f);
3486 attrs.valuemask |= XpmVisual;
3487 attrs.valuemask |= XpmColormap;
3489 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3490 (char **) bits, &bitmap, &mask, &attrs);
3491 if (rc != XpmSuccess)
3493 XpmFreeAttributes (&attrs);
3494 return -1;
3497 id = x_allocate_bitmap_record (f);
3498 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3499 dpyinfo->bitmaps[id - 1].have_mask = true;
3500 dpyinfo->bitmaps[id - 1].mask = mask;
3501 dpyinfo->bitmaps[id - 1].file = NULL;
3502 dpyinfo->bitmaps[id - 1].height = attrs.height;
3503 dpyinfo->bitmaps[id - 1].width = attrs.width;
3504 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3505 dpyinfo->bitmaps[id - 1].refcount = 1;
3507 XpmFreeAttributes (&attrs);
3508 return id;
3510 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3512 /* Load image IMG which will be displayed on frame F. Value is
3513 true if successful. */
3515 #ifdef HAVE_XPM
3517 static bool
3518 xpm_load (struct frame *f, struct image *img)
3520 int rc;
3521 XpmAttributes attrs;
3522 Lisp_Object specified_file, color_symbols;
3523 USE_SAFE_ALLOCA;
3525 #ifdef HAVE_NTGUI
3526 HDC hdc;
3527 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3528 #endif /* HAVE_NTGUI */
3530 /* Configure the XPM lib. Use the visual of frame F. Allocate
3531 close colors. Return colors allocated. */
3532 memset (&attrs, 0, sizeof attrs);
3534 #ifndef HAVE_NTGUI
3535 attrs.visual = FRAME_X_VISUAL (f);
3536 attrs.colormap = FRAME_X_COLORMAP (f);
3537 attrs.valuemask |= XpmVisual;
3538 attrs.valuemask |= XpmColormap;
3539 #endif /* HAVE_NTGUI */
3541 #ifdef ALLOC_XPM_COLORS
3542 /* Allocate colors with our own functions which handle
3543 failing color allocation more gracefully. */
3544 attrs.color_closure = f;
3545 attrs.alloc_color = xpm_alloc_color;
3546 attrs.free_colors = xpm_free_colors;
3547 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3548 #else /* not ALLOC_XPM_COLORS */
3549 /* Let the XPM lib allocate colors. */
3550 attrs.valuemask |= XpmReturnAllocPixels;
3551 #ifdef XpmAllocCloseColors
3552 attrs.alloc_close_colors = 1;
3553 attrs.valuemask |= XpmAllocCloseColors;
3554 #else /* not XpmAllocCloseColors */
3555 attrs.closeness = 600;
3556 attrs.valuemask |= XpmCloseness;
3557 #endif /* not XpmAllocCloseColors */
3558 #endif /* ALLOC_XPM_COLORS */
3560 /* If image specification contains symbolic color definitions, add
3561 these to `attrs'. */
3562 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3563 if (CONSP (color_symbols))
3565 Lisp_Object tail;
3566 XpmColorSymbol *xpm_syms;
3567 ptrdiff_t i, size;
3569 attrs.valuemask |= XpmColorSymbols;
3571 /* Count number of symbols. */
3572 attrs.numsymbols = 0;
3573 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3574 ++attrs.numsymbols;
3576 /* Allocate an XpmColorSymbol array. */
3577 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3578 size = attrs.numsymbols * sizeof *xpm_syms;
3579 memset (xpm_syms, 0, size);
3580 attrs.colorsymbols = xpm_syms;
3582 /* Fill the color symbol array. */
3583 for (tail = color_symbols, i = 0;
3584 CONSP (tail);
3585 ++i, tail = XCDR (tail))
3587 Lisp_Object name;
3588 Lisp_Object color;
3589 char *empty_string = (char *) "";
3591 if (!CONSP (XCAR (tail)))
3593 xpm_syms[i].name = empty_string;
3594 xpm_syms[i].value = empty_string;
3595 continue;
3597 name = XCAR (XCAR (tail));
3598 color = XCDR (XCAR (tail));
3599 if (STRINGP (name))
3600 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3601 else
3602 xpm_syms[i].name = empty_string;
3603 if (STRINGP (color))
3604 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3605 else
3606 xpm_syms[i].value = empty_string;
3610 /* Create a pixmap for the image, either from a file, or from a
3611 string buffer containing data in the same format as an XPM file. */
3612 #ifdef ALLOC_XPM_COLORS
3613 xpm_init_color_cache (f, &attrs);
3614 #endif
3616 specified_file = image_spec_value (img->spec, QCfile, NULL);
3618 #ifdef HAVE_NTGUI
3620 HDC frame_dc = get_frame_dc (f);
3621 hdc = CreateCompatibleDC (frame_dc);
3622 release_frame_dc (f, frame_dc);
3624 #endif /* HAVE_NTGUI */
3626 if (STRINGP (specified_file))
3628 Lisp_Object file = x_find_image_file (specified_file);
3629 if (!STRINGP (file))
3631 image_error ("Cannot find image file `%s'", specified_file);
3632 #ifdef ALLOC_XPM_COLORS
3633 xpm_free_color_cache ();
3634 #endif
3635 SAFE_FREE ();
3636 return 0;
3639 #ifdef HAVE_NTGUI
3640 #ifdef WINDOWSNT
3641 /* FILE is encoded in UTF-8, but image libraries on Windows
3642 support neither UTF-8 nor UTF-16 encoded file names. So we
3643 need to re-encode it in ANSI. */
3644 file = ansi_encode_filename (file);
3645 #endif
3646 /* XpmReadFileToPixmap is not available in the Windows port of
3647 libxpm. But XpmReadFileToImage almost does what we want. */
3648 rc = XpmReadFileToImage (&hdc, SDATA (file),
3649 &xpm_image, &xpm_mask,
3650 &attrs);
3651 #else
3652 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3653 &img->ximg, &img->mask_img,
3654 &attrs);
3655 #endif /* HAVE_NTGUI */
3657 else
3659 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3660 if (!STRINGP (buffer))
3662 image_error ("Invalid image data `%s'", buffer);
3663 #ifdef ALLOC_XPM_COLORS
3664 xpm_free_color_cache ();
3665 #endif
3666 SAFE_FREE ();
3667 return 0;
3669 #ifdef HAVE_NTGUI
3670 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3671 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3672 rc = XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3673 &xpm_image, &xpm_mask,
3674 &attrs);
3675 #else
3676 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3677 &img->ximg, &img->mask_img,
3678 &attrs);
3679 #endif /* HAVE_NTGUI */
3682 #ifdef USE_CAIRO
3683 // Load very specific Xpm:s.
3684 if (rc == XpmSuccess
3685 && img->ximg->format == ZPixmap
3686 && img->ximg->bits_per_pixel == 32
3687 && (! img->mask_img || img->mask_img->bits_per_pixel == 1))
3689 int width = img->ximg->width;
3690 int height = img->ximg->height;
3691 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
3692 int i;
3693 uint32_t *od = (uint32_t *)data;
3694 uint32_t *id = (uint32_t *)img->ximg->data;
3695 char *mid = img->mask_img ? img->mask_img->data : 0;
3696 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
3698 for (i = 0; i < height; ++i)
3700 int k;
3701 for (k = 0; k < width; ++k)
3703 int idx = i * img->ximg->bytes_per_line/4 + k;
3704 int maskidx = mid ? i * img->mask_img->bytes_per_line + k/8 : 0;
3705 int mask = mid ? mid[maskidx] & (1 << (k % 8)) : 1;
3707 if (mask) od[idx] = id[idx] + 0xff000000; // ff => full alpha
3708 else od[idx] = bgcolor;
3712 create_cairo_image_surface (img, data, width, height);
3714 else
3716 rc = XpmFileInvalid;
3717 x_clear_image (f, img);
3719 #else
3720 #ifdef HAVE_X_WINDOWS
3721 if (rc == XpmSuccess)
3723 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3724 img->ximg->width, img->ximg->height,
3725 img->ximg->depth);
3726 if (img->pixmap == NO_PIXMAP)
3728 x_clear_image (f, img);
3729 rc = XpmNoMemory;
3731 else if (img->mask_img)
3733 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3734 img->mask_img->width,
3735 img->mask_img->height,
3736 img->mask_img->depth);
3737 if (img->mask == NO_PIXMAP)
3739 x_clear_image (f, img);
3740 rc = XpmNoMemory;
3744 #endif
3745 #endif /* ! USE_CAIRO */
3747 if (rc == XpmSuccess)
3749 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3750 img->colors = colors_in_color_table (&img->ncolors);
3751 #else /* not ALLOC_XPM_COLORS */
3752 int i;
3754 #ifdef HAVE_NTGUI
3755 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3756 plus some duplicate attributes. */
3757 if (xpm_image && xpm_image->bitmap)
3759 img->pixmap = xpm_image->bitmap;
3760 /* XImageFree in libXpm frees XImage struct without destroying
3761 the bitmap, which is what we want. */
3762 XImageFree (xpm_image);
3764 if (xpm_mask && xpm_mask->bitmap)
3766 /* The mask appears to be inverted compared with what we expect.
3767 TODO: invert our expectations. See other places where we
3768 have to invert bits because our idea of masks is backwards. */
3769 HGDIOBJ old_obj;
3770 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3772 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3773 SelectObject (hdc, old_obj);
3775 img->mask = xpm_mask->bitmap;
3776 XImageFree (xpm_mask);
3777 DeleteDC (hdc);
3780 DeleteDC (hdc);
3781 #endif /* HAVE_NTGUI */
3783 /* Remember allocated colors. */
3784 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3785 img->ncolors = attrs.nalloc_pixels;
3786 for (i = 0; i < attrs.nalloc_pixels; ++i)
3788 img->colors[i] = attrs.alloc_pixels[i];
3789 #ifdef DEBUG_X_COLORS
3790 register_color (img->colors[i]);
3791 #endif
3793 #endif /* not ALLOC_XPM_COLORS */
3795 img->width = attrs.width;
3796 img->height = attrs.height;
3797 eassert (img->width > 0 && img->height > 0);
3799 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3800 XpmFreeAttributes (&attrs);
3802 #ifdef HAVE_X_WINDOWS
3803 /* Maybe fill in the background field while we have ximg handy. */
3804 IMAGE_BACKGROUND (img, f, img->ximg);
3805 if (img->mask_img)
3806 /* Fill in the background_transparent field while we have the
3807 mask handy. */
3808 image_background_transparent (img, f, img->mask_img);
3809 #endif
3811 else
3813 #ifdef HAVE_NTGUI
3814 DeleteDC (hdc);
3815 #endif /* HAVE_NTGUI */
3817 switch (rc)
3819 case XpmOpenFailed:
3820 image_error ("Error opening XPM file (%s)", img->spec);
3821 break;
3823 case XpmFileInvalid:
3824 image_error ("Invalid XPM file (%s)", img->spec);
3825 break;
3827 case XpmNoMemory:
3828 image_error ("Out of memory (%s)", img->spec);
3829 break;
3831 case XpmColorFailed:
3832 image_error ("Color allocation error (%s)", img->spec);
3833 break;
3835 default:
3836 image_error ("Unknown error (%s)", img->spec);
3837 break;
3841 #ifdef ALLOC_XPM_COLORS
3842 xpm_free_color_cache ();
3843 #endif
3844 SAFE_FREE ();
3845 return rc == XpmSuccess;
3848 #endif /* HAVE_XPM */
3850 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3852 /* XPM support functions for NS where libxpm is not available.
3853 Only XPM version 3 (without any extensions) is supported. */
3855 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3856 int, Lisp_Object);
3857 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3858 const unsigned char *, int);
3859 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3860 int, Lisp_Object);
3861 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3862 const unsigned char *, int);
3864 /* Tokens returned from xpm_scan. */
3866 enum xpm_token
3868 XPM_TK_IDENT = 256,
3869 XPM_TK_STRING,
3870 XPM_TK_EOF
3873 /* Scan an XPM data and return a character (< 256) or a token defined
3874 by enum xpm_token above. *S and END are the start (inclusive) and
3875 the end (exclusive) addresses of the data, respectively. Advance
3876 *S while scanning. If token is either XPM_TK_IDENT or
3877 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3878 length of the corresponding token, respectively. */
3880 static int
3881 xpm_scan (const unsigned char **s,
3882 const unsigned char *end,
3883 const unsigned char **beg,
3884 ptrdiff_t *len)
3886 int c;
3888 while (*s < end)
3890 /* Skip white-space. */
3891 while (*s < end && (c = *(*s)++, c_isspace (c)))
3894 /* gnus-pointer.xpm uses '-' in its identifier.
3895 sb-dir-plus.xpm uses '+' in its identifier. */
3896 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3898 *beg = *s - 1;
3899 while (*s < end
3900 && (c = **s, c_isalnum (c)
3901 || c == '_' || c == '-' || c == '+'))
3902 ++*s;
3903 *len = *s - *beg;
3904 return XPM_TK_IDENT;
3906 else if (c == '"')
3908 *beg = *s;
3909 while (*s < end && **s != '"')
3910 ++*s;
3911 *len = *s - *beg;
3912 if (*s < end)
3913 ++*s;
3914 return XPM_TK_STRING;
3916 else if (c == '/')
3918 if (*s < end && **s == '*')
3920 /* C-style comment. */
3921 ++*s;
3924 while (*s < end && *(*s)++ != '*')
3927 while (*s < end && **s != '/');
3928 if (*s < end)
3929 ++*s;
3931 else
3932 return c;
3934 else
3935 return c;
3938 return XPM_TK_EOF;
3941 /* Functions for color table lookup in XPM data. A key is a string
3942 specifying the color of each pixel in XPM data. A value is either
3943 an integer that specifies a pixel color, Qt that specifies
3944 transparency, or Qnil for the unspecified color. If the length of
3945 the key string is one, a vector is used as a table. Otherwise, a
3946 hash table is used. */
3948 static Lisp_Object
3949 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3950 const unsigned char *,
3951 int,
3952 Lisp_Object),
3953 Lisp_Object (**get_func) (Lisp_Object,
3954 const unsigned char *,
3955 int))
3957 *put_func = xpm_put_color_table_v;
3958 *get_func = xpm_get_color_table_v;
3959 return Fmake_vector (make_number (256), Qnil);
3962 static void
3963 xpm_put_color_table_v (Lisp_Object color_table,
3964 const unsigned char *chars_start,
3965 int chars_len,
3966 Lisp_Object color)
3968 ASET (color_table, *chars_start, color);
3971 static Lisp_Object
3972 xpm_get_color_table_v (Lisp_Object color_table,
3973 const unsigned char *chars_start,
3974 int chars_len)
3976 return AREF (color_table, *chars_start);
3979 static Lisp_Object
3980 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3981 const unsigned char *,
3982 int,
3983 Lisp_Object),
3984 Lisp_Object (**get_func) (Lisp_Object,
3985 const unsigned char *,
3986 int))
3988 *put_func = xpm_put_color_table_h;
3989 *get_func = xpm_get_color_table_h;
3990 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
3991 make_float (DEFAULT_REHASH_SIZE),
3992 make_float (DEFAULT_REHASH_THRESHOLD),
3993 Qnil);
3996 static void
3997 xpm_put_color_table_h (Lisp_Object color_table,
3998 const unsigned char *chars_start,
3999 int chars_len,
4000 Lisp_Object color)
4002 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4003 EMACS_UINT hash_code;
4004 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4006 hash_lookup (table, chars, &hash_code);
4007 hash_put (table, chars, color, hash_code);
4010 static Lisp_Object
4011 xpm_get_color_table_h (Lisp_Object color_table,
4012 const unsigned char *chars_start,
4013 int chars_len)
4015 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4016 ptrdiff_t i =
4017 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
4019 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4022 enum xpm_color_key {
4023 XPM_COLOR_KEY_S,
4024 XPM_COLOR_KEY_M,
4025 XPM_COLOR_KEY_G4,
4026 XPM_COLOR_KEY_G,
4027 XPM_COLOR_KEY_C
4030 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4032 static int
4033 xpm_str_to_color_key (const char *s)
4035 int i;
4037 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
4038 if (strcmp (xpm_color_key_strings[i], s) == 0)
4039 return i;
4040 return -1;
4043 static bool
4044 xpm_load_image (struct frame *f,
4045 struct image *img,
4046 const unsigned char *contents,
4047 const unsigned char *end)
4049 const unsigned char *s = contents, *beg, *str;
4050 unsigned char buffer[BUFSIZ];
4051 int width, height, x, y;
4052 int num_colors, chars_per_pixel;
4053 ptrdiff_t len;
4054 int LA1;
4055 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4056 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
4057 Lisp_Object frame, color_symbols, color_table;
4058 int best_key;
4059 bool have_mask = false;
4060 XImagePtr ximg = NULL, mask_img = NULL;
4062 #define match() \
4063 LA1 = xpm_scan (&s, end, &beg, &len)
4065 #define expect(TOKEN) \
4066 do \
4068 if (LA1 != (TOKEN)) \
4069 goto failure; \
4070 match (); \
4072 while (0)
4074 #define expect_ident(IDENT) \
4075 if (LA1 == XPM_TK_IDENT \
4076 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4077 match (); \
4078 else \
4079 goto failure
4081 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4082 goto failure;
4083 s += 9;
4084 match ();
4085 expect_ident ("static");
4086 expect_ident ("char");
4087 expect ('*');
4088 expect (XPM_TK_IDENT);
4089 expect ('[');
4090 expect (']');
4091 expect ('=');
4092 expect ('{');
4093 expect (XPM_TK_STRING);
4094 if (len >= BUFSIZ)
4095 goto failure;
4096 memcpy (buffer, beg, len);
4097 buffer[len] = '\0';
4098 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4099 &num_colors, &chars_per_pixel) != 4
4100 || width <= 0 || height <= 0
4101 || num_colors <= 0 || chars_per_pixel <= 0)
4102 goto failure;
4104 if (!check_image_size (f, width, height))
4106 image_error ("Invalid image size (see `max-image-size')");
4107 goto failure;
4110 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4111 #ifndef HAVE_NS
4112 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4113 &mask_img, 1)
4114 #endif
4117 image_error ("Image too large");
4118 goto failure;
4121 expect (',');
4123 XSETFRAME (frame, f);
4124 if (!NILP (Fxw_display_color_p (frame)))
4125 best_key = XPM_COLOR_KEY_C;
4126 else if (!NILP (Fx_display_grayscale_p (frame)))
4127 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4128 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4129 else
4130 best_key = XPM_COLOR_KEY_M;
4132 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4133 if (chars_per_pixel == 1)
4134 color_table = xpm_make_color_table_v (&put_color_table,
4135 &get_color_table);
4136 else
4137 color_table = xpm_make_color_table_h (&put_color_table,
4138 &get_color_table);
4140 while (num_colors-- > 0)
4142 char *color, *max_color;
4143 int key, next_key, max_key = 0;
4144 Lisp_Object symbol_color = Qnil, color_val;
4145 XColor cdef;
4147 expect (XPM_TK_STRING);
4148 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4149 goto failure;
4150 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4151 buffer[len - chars_per_pixel] = '\0';
4153 str = strtok (buffer, " \t");
4154 if (str == NULL)
4155 goto failure;
4156 key = xpm_str_to_color_key (str);
4157 if (key < 0)
4158 goto failure;
4161 color = strtok (NULL, " \t");
4162 if (color == NULL)
4163 goto failure;
4165 while ((str = strtok (NULL, " \t")) != NULL)
4167 next_key = xpm_str_to_color_key (str);
4168 if (next_key >= 0)
4169 break;
4170 color[strlen (color)] = ' ';
4173 if (key == XPM_COLOR_KEY_S)
4175 if (NILP (symbol_color))
4176 symbol_color = build_string (color);
4178 else if (max_key < key && key <= best_key)
4180 max_key = key;
4181 max_color = color;
4183 key = next_key;
4185 while (str);
4187 color_val = Qnil;
4188 if (!NILP (color_symbols) && !NILP (symbol_color))
4190 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4192 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4194 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4195 color_val = Qt;
4196 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4197 &cdef, 0))
4198 color_val = make_number (cdef.pixel);
4201 if (NILP (color_val) && max_key > 0)
4203 if (xstrcasecmp (max_color, "None") == 0)
4204 color_val = Qt;
4205 else if (x_defined_color (f, max_color, &cdef, 0))
4206 color_val = make_number (cdef.pixel);
4208 if (!NILP (color_val))
4209 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4211 expect (',');
4214 for (y = 0; y < height; y++)
4216 expect (XPM_TK_STRING);
4217 str = beg;
4218 if (len < width * chars_per_pixel)
4219 goto failure;
4220 for (x = 0; x < width; x++, str += chars_per_pixel)
4222 Lisp_Object color_val =
4223 (*get_color_table) (color_table, str, chars_per_pixel);
4225 XPutPixel (ximg, x, y,
4226 (INTEGERP (color_val) ? XINT (color_val)
4227 : FRAME_FOREGROUND_PIXEL (f)));
4228 #ifndef HAVE_NS
4229 XPutPixel (mask_img, x, y,
4230 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4231 : (have_mask = true, PIX_MASK_RETAIN)));
4232 #else
4233 if (EQ (color_val, Qt))
4234 ns_set_alpha (ximg, x, y, 0);
4235 #endif
4237 if (y + 1 < height)
4238 expect (',');
4241 img->width = width;
4242 img->height = height;
4244 /* Maybe fill in the background field while we have ximg handy. */
4245 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4246 IMAGE_BACKGROUND (img, f, ximg);
4248 image_put_x_image (f, img, ximg, 0);
4249 #ifndef HAVE_NS
4250 if (have_mask)
4252 /* Fill in the background_transparent field while we have the
4253 mask handy. */
4254 image_background_transparent (img, f, mask_img);
4256 image_put_x_image (f, img, mask_img, 1);
4258 else
4260 x_destroy_x_image (mask_img);
4261 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4263 #endif
4264 return 1;
4266 failure:
4267 image_error ("Invalid XPM file (%s)", img->spec);
4268 x_destroy_x_image (ximg);
4269 x_destroy_x_image (mask_img);
4270 x_clear_image (f, img);
4271 return 0;
4273 #undef match
4274 #undef expect
4275 #undef expect_ident
4278 static bool
4279 xpm_load (struct frame *f,
4280 struct image *img)
4282 bool success_p = 0;
4283 Lisp_Object file_name;
4285 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4286 file_name = image_spec_value (img->spec, QCfile, NULL);
4287 if (STRINGP (file_name))
4289 Lisp_Object file;
4290 unsigned char *contents;
4291 ptrdiff_t size;
4293 file = x_find_image_file (file_name);
4294 if (!STRINGP (file))
4296 image_error ("Cannot find image file `%s'", file_name);
4297 return 0;
4300 contents = slurp_file (SSDATA (file), &size);
4301 if (contents == NULL)
4303 image_error ("Error loading XPM image `%s'", img->spec);
4304 return 0;
4307 success_p = xpm_load_image (f, img, contents, contents + size);
4308 xfree (contents);
4310 else
4312 Lisp_Object data;
4314 data = image_spec_value (img->spec, QCdata, NULL);
4315 if (!STRINGP (data))
4317 image_error ("Invalid image data `%s'", data);
4318 return 0;
4320 success_p = xpm_load_image (f, img, SDATA (data),
4321 SDATA (data) + SBYTES (data));
4324 return success_p;
4327 #endif /* HAVE_NS && !HAVE_XPM */
4331 /***********************************************************************
4332 Color table
4333 ***********************************************************************/
4335 #ifdef COLOR_TABLE_SUPPORT
4337 /* An entry in the color table mapping an RGB color to a pixel color. */
4339 struct ct_color
4341 int r, g, b;
4342 unsigned long pixel;
4344 /* Next in color table collision list. */
4345 struct ct_color *next;
4348 /* The bucket vector size to use. Must be prime. */
4350 #define CT_SIZE 101
4352 /* Value is a hash of the RGB color given by R, G, and B. */
4354 static unsigned
4355 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4357 return (r << 16) ^ (g << 8) ^ b;
4360 /* The color hash table. */
4362 static struct ct_color **ct_table;
4364 /* Number of entries in the color table. */
4366 static int ct_colors_allocated;
4367 enum
4369 ct_colors_allocated_max =
4370 min (INT_MAX,
4371 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4374 /* Initialize the color table. */
4376 static void
4377 init_color_table (void)
4379 int size = CT_SIZE * sizeof (*ct_table);
4380 ct_table = xzalloc (size);
4381 ct_colors_allocated = 0;
4385 /* Free memory associated with the color table. */
4387 static void
4388 free_color_table (void)
4390 int i;
4391 struct ct_color *p, *next;
4393 for (i = 0; i < CT_SIZE; ++i)
4394 for (p = ct_table[i]; p; p = next)
4396 next = p->next;
4397 xfree (p);
4400 xfree (ct_table);
4401 ct_table = NULL;
4405 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4406 entry for that color already is in the color table, return the
4407 pixel color of that entry. Otherwise, allocate a new color for R,
4408 G, B, and make an entry in the color table. */
4410 static unsigned long
4411 lookup_rgb_color (struct frame *f, int r, int g, int b)
4413 unsigned hash = ct_hash_rgb (r, g, b);
4414 int i = hash % CT_SIZE;
4415 struct ct_color *p;
4416 Display_Info *dpyinfo;
4418 /* Handle TrueColor visuals specially, which improves performance by
4419 two orders of magnitude. Freeing colors on TrueColor visuals is
4420 a nop, and pixel colors specify RGB values directly. See also
4421 the Xlib spec, chapter 3.1. */
4422 dpyinfo = FRAME_DISPLAY_INFO (f);
4423 if (dpyinfo->red_bits > 0)
4425 unsigned long pr, pg, pb;
4427 /* Apply gamma-correction like normal color allocation does. */
4428 if (f->gamma)
4430 XColor color;
4431 color.red = r, color.green = g, color.blue = b;
4432 gamma_correct (f, &color);
4433 r = color.red, g = color.green, b = color.blue;
4436 /* Scale down RGB values to the visual's bits per RGB, and shift
4437 them to the right position in the pixel color. Note that the
4438 original RGB values are 16-bit values, as usual in X. */
4439 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4440 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4441 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4443 /* Assemble the pixel color. */
4444 return pr | pg | pb;
4447 for (p = ct_table[i]; p; p = p->next)
4448 if (p->r == r && p->g == g && p->b == b)
4449 break;
4451 if (p == NULL)
4454 #ifdef HAVE_X_WINDOWS
4455 XColor color;
4456 Colormap cmap;
4457 bool rc;
4458 #else
4459 COLORREF color;
4460 #endif
4462 if (ct_colors_allocated_max <= ct_colors_allocated)
4463 return FRAME_FOREGROUND_PIXEL (f);
4465 #ifdef HAVE_X_WINDOWS
4466 color.red = r;
4467 color.green = g;
4468 color.blue = b;
4470 cmap = FRAME_X_COLORMAP (f);
4471 rc = x_alloc_nearest_color (f, cmap, &color);
4472 if (rc)
4474 ++ct_colors_allocated;
4475 p = xmalloc (sizeof *p);
4476 p->r = r;
4477 p->g = g;
4478 p->b = b;
4479 p->pixel = color.pixel;
4480 p->next = ct_table[i];
4481 ct_table[i] = p;
4483 else
4484 return FRAME_FOREGROUND_PIXEL (f);
4486 #else
4487 #ifdef HAVE_NTGUI
4488 color = PALETTERGB (r, g, b);
4489 #else
4490 color = RGB_TO_ULONG (r, g, b);
4491 #endif /* HAVE_NTGUI */
4492 ++ct_colors_allocated;
4493 p = xmalloc (sizeof *p);
4494 p->r = r;
4495 p->g = g;
4496 p->b = b;
4497 p->pixel = color;
4498 p->next = ct_table[i];
4499 ct_table[i] = p;
4500 #endif /* HAVE_X_WINDOWS */
4504 return p->pixel;
4508 /* Look up pixel color PIXEL which is used on frame F in the color
4509 table. If not already present, allocate it. Value is PIXEL. */
4511 static unsigned long
4512 lookup_pixel_color (struct frame *f, unsigned long pixel)
4514 int i = pixel % CT_SIZE;
4515 struct ct_color *p;
4517 for (p = ct_table[i]; p; p = p->next)
4518 if (p->pixel == pixel)
4519 break;
4521 if (p == NULL)
4523 XColor color;
4524 Colormap cmap;
4525 bool rc;
4527 if (ct_colors_allocated >= ct_colors_allocated_max)
4528 return FRAME_FOREGROUND_PIXEL (f);
4530 #ifdef HAVE_X_WINDOWS
4531 cmap = FRAME_X_COLORMAP (f);
4532 color.pixel = pixel;
4533 x_query_color (f, &color);
4534 rc = x_alloc_nearest_color (f, cmap, &color);
4535 #else
4536 block_input ();
4537 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4538 color.pixel = pixel;
4539 XQueryColor (NULL, cmap, &color);
4540 rc = x_alloc_nearest_color (f, cmap, &color);
4541 unblock_input ();
4542 #endif /* HAVE_X_WINDOWS */
4544 if (rc)
4546 ++ct_colors_allocated;
4548 p = xmalloc (sizeof *p);
4549 p->r = color.red;
4550 p->g = color.green;
4551 p->b = color.blue;
4552 p->pixel = pixel;
4553 p->next = ct_table[i];
4554 ct_table[i] = p;
4556 else
4557 return FRAME_FOREGROUND_PIXEL (f);
4559 return p->pixel;
4563 /* Value is a vector of all pixel colors contained in the color table,
4564 allocated via xmalloc. Set *N to the number of colors. */
4566 static unsigned long *
4567 colors_in_color_table (int *n)
4569 int i, j;
4570 struct ct_color *p;
4571 unsigned long *colors;
4573 if (ct_colors_allocated == 0)
4575 *n = 0;
4576 colors = NULL;
4578 else
4580 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4581 *n = ct_colors_allocated;
4583 for (i = j = 0; i < CT_SIZE; ++i)
4584 for (p = ct_table[i]; p; p = p->next)
4585 colors[j++] = p->pixel;
4588 return colors;
4591 #else /* COLOR_TABLE_SUPPORT */
4593 static unsigned long
4594 lookup_rgb_color (struct frame *f, int r, int g, int b)
4596 unsigned long pixel;
4598 #ifdef HAVE_NTGUI
4599 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4600 #endif /* HAVE_NTGUI */
4602 #ifdef HAVE_NS
4603 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4604 #endif /* HAVE_NS */
4605 return pixel;
4608 static void
4609 init_color_table (void)
4612 #endif /* COLOR_TABLE_SUPPORT */
4615 /***********************************************************************
4616 Algorithms
4617 ***********************************************************************/
4619 /* Edge detection matrices for different edge-detection
4620 strategies. */
4622 static int emboss_matrix[9] = {
4623 /* x - 1 x x + 1 */
4624 2, -1, 0, /* y - 1 */
4625 -1, 0, 1, /* y */
4626 0, 1, -2 /* y + 1 */
4629 static int laplace_matrix[9] = {
4630 /* x - 1 x x + 1 */
4631 1, 0, 0, /* y - 1 */
4632 0, 0, 0, /* y */
4633 0, 0, -1 /* y + 1 */
4636 /* Value is the intensity of the color whose red/green/blue values
4637 are R, G, and B. */
4639 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4642 /* On frame F, return an array of XColor structures describing image
4643 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4644 means also fill the red/green/blue members of the XColor
4645 structures. Value is a pointer to the array of XColors structures,
4646 allocated with xmalloc; it must be freed by the caller. */
4648 static XColor *
4649 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4651 int x, y;
4652 XColor *colors, *p;
4653 XImagePtr_or_DC ximg;
4654 #ifdef HAVE_NTGUI
4655 HGDIOBJ prev;
4656 #endif /* HAVE_NTGUI */
4658 if (img->height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width)
4659 memory_full (SIZE_MAX);
4660 colors = xmalloc (sizeof *colors * img->width * img->height);
4662 /* Get the X image or create a memory device context for IMG. */
4663 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4665 /* Fill the `pixel' members of the XColor array. I wished there
4666 were an easy and portable way to circumvent XGetPixel. */
4667 p = colors;
4668 for (y = 0; y < img->height; ++y)
4670 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4671 XColor *row = p;
4672 for (x = 0; x < img->width; ++x, ++p)
4673 p->pixel = GET_PIXEL (ximg, x, y);
4674 if (rgb_p)
4675 x_query_colors (f, row, img->width);
4677 #else
4679 for (x = 0; x < img->width; ++x, ++p)
4681 /* W32_TODO: palette support needed here? */
4682 p->pixel = GET_PIXEL (ximg, x, y);
4683 if (rgb_p)
4685 p->red = RED16_FROM_ULONG (p->pixel);
4686 p->green = GREEN16_FROM_ULONG (p->pixel);
4687 p->blue = BLUE16_FROM_ULONG (p->pixel);
4690 #endif /* HAVE_X_WINDOWS */
4693 image_unget_x_image_or_dc (img, 0, ximg, prev);
4695 return colors;
4698 #ifdef HAVE_NTGUI
4700 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4701 created with CreateDIBSection, with the pointer to the bit values
4702 stored in ximg->data. */
4704 static void
4705 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4707 int width = ximg->info.bmiHeader.biWidth;
4708 unsigned char * pixel;
4710 /* True color images. */
4711 if (ximg->info.bmiHeader.biBitCount == 24)
4713 int rowbytes = width * 3;
4714 /* Ensure scanlines are aligned on 4 byte boundaries. */
4715 if (rowbytes % 4)
4716 rowbytes += 4 - (rowbytes % 4);
4718 pixel = ximg->data + y * rowbytes + x * 3;
4719 /* Windows bitmaps are in BGR order. */
4720 *pixel = GetBValue (color);
4721 *(pixel + 1) = GetGValue (color);
4722 *(pixel + 2) = GetRValue (color);
4724 /* Monochrome images. */
4725 else if (ximg->info.bmiHeader.biBitCount == 1)
4727 int rowbytes = width / 8;
4728 /* Ensure scanlines are aligned on 4 byte boundaries. */
4729 if (rowbytes % 4)
4730 rowbytes += 4 - (rowbytes % 4);
4731 pixel = ximg->data + y * rowbytes + x / 8;
4732 /* Filter out palette info. */
4733 if (color & 0x00ffffff)
4734 *pixel = *pixel | (1 << x % 8);
4735 else
4736 *pixel = *pixel & ~(1 << x % 8);
4738 else
4739 image_error ("XPutPixel: palette image not supported");
4742 #endif /* HAVE_NTGUI */
4744 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4745 RGB members are set. F is the frame on which this all happens.
4746 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4748 static void
4749 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4751 int x, y;
4752 XImagePtr oimg = NULL;
4753 XColor *p;
4755 init_color_table ();
4757 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4758 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4759 &oimg, 0);
4760 p = colors;
4761 for (y = 0; y < img->height; ++y)
4762 for (x = 0; x < img->width; ++x, ++p)
4764 unsigned long pixel;
4765 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4766 XPutPixel (oimg, x, y, pixel);
4769 xfree (colors);
4771 image_put_x_image (f, img, oimg, 0);
4772 #ifdef COLOR_TABLE_SUPPORT
4773 img->colors = colors_in_color_table (&img->ncolors);
4774 free_color_table ();
4775 #endif /* COLOR_TABLE_SUPPORT */
4779 /* On frame F, perform edge-detection on image IMG.
4781 MATRIX is a nine-element array specifying the transformation
4782 matrix. See emboss_matrix for an example.
4784 COLOR_ADJUST is a color adjustment added to each pixel of the
4785 outgoing image. */
4787 static void
4788 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4790 XColor *colors = x_to_xcolors (f, img, 1);
4791 XColor *new, *p;
4792 int x, y, i, sum;
4794 for (i = sum = 0; i < 9; ++i)
4795 sum += eabs (matrix[i]);
4797 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4799 if (img->height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width)
4800 memory_full (SIZE_MAX);
4801 new = xmalloc (sizeof *new * img->width * img->height);
4803 for (y = 0; y < img->height; ++y)
4805 p = COLOR (new, 0, y);
4806 p->red = p->green = p->blue = 0xffff/2;
4807 p = COLOR (new, img->width - 1, y);
4808 p->red = p->green = p->blue = 0xffff/2;
4811 for (x = 1; x < img->width - 1; ++x)
4813 p = COLOR (new, x, 0);
4814 p->red = p->green = p->blue = 0xffff/2;
4815 p = COLOR (new, x, img->height - 1);
4816 p->red = p->green = p->blue = 0xffff/2;
4819 for (y = 1; y < img->height - 1; ++y)
4821 p = COLOR (new, 1, y);
4823 for (x = 1; x < img->width - 1; ++x, ++p)
4825 int r, g, b, yy, xx;
4827 r = g = b = i = 0;
4828 for (yy = y - 1; yy < y + 2; ++yy)
4829 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4830 if (matrix[i])
4832 XColor *t = COLOR (colors, xx, yy);
4833 r += matrix[i] * t->red;
4834 g += matrix[i] * t->green;
4835 b += matrix[i] * t->blue;
4838 r = (r / sum + color_adjust) & 0xffff;
4839 g = (g / sum + color_adjust) & 0xffff;
4840 b = (b / sum + color_adjust) & 0xffff;
4841 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4845 xfree (colors);
4846 x_from_xcolors (f, img, new);
4848 #undef COLOR
4852 /* Perform the pre-defined `emboss' edge-detection on image IMG
4853 on frame F. */
4855 static void
4856 x_emboss (struct frame *f, struct image *img)
4858 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4862 /* Transform image IMG which is used on frame F with a Laplace
4863 edge-detection algorithm. The result is an image that can be used
4864 to draw disabled buttons, for example. */
4866 static void
4867 x_laplace (struct frame *f, struct image *img)
4869 x_detect_edges (f, img, laplace_matrix, 45000);
4873 /* Perform edge-detection on image IMG on frame F, with specified
4874 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4876 MATRIX must be either
4878 - a list of at least 9 numbers in row-major form
4879 - a vector of at least 9 numbers
4881 COLOR_ADJUST nil means use a default; otherwise it must be a
4882 number. */
4884 static void
4885 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4886 Lisp_Object color_adjust)
4888 int i = 0;
4889 int trans[9];
4891 if (CONSP (matrix))
4893 for (i = 0;
4894 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4895 ++i, matrix = XCDR (matrix))
4896 trans[i] = XFLOATINT (XCAR (matrix));
4898 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4900 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4901 trans[i] = XFLOATINT (AREF (matrix, i));
4904 if (NILP (color_adjust))
4905 color_adjust = make_number (0xffff / 2);
4907 if (i == 9 && NUMBERP (color_adjust))
4908 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4912 /* Transform image IMG on frame F so that it looks disabled. */
4914 static void
4915 x_disable_image (struct frame *f, struct image *img)
4917 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4918 #ifdef HAVE_NTGUI
4919 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4920 #else
4921 int n_planes = dpyinfo->n_planes;
4922 #endif /* HAVE_NTGUI */
4924 if (n_planes >= 2)
4926 /* Color (or grayscale). Convert to gray, and equalize. Just
4927 drawing such images with a stipple can look very odd, so
4928 we're using this method instead. */
4929 XColor *colors = x_to_xcolors (f, img, 1);
4930 XColor *p, *end;
4931 const int h = 15000;
4932 const int l = 30000;
4934 for (p = colors, end = colors + img->width * img->height;
4935 p < end;
4936 ++p)
4938 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4939 int i2 = (0xffff - h - l) * i / 0xffff + l;
4940 p->red = p->green = p->blue = i2;
4943 x_from_xcolors (f, img, colors);
4946 /* Draw a cross over the disabled image, if we must or if we
4947 should. */
4948 if (n_planes < 2 || cross_disabled_images)
4950 #ifndef HAVE_NTGUI
4951 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4953 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4955 Display *dpy = FRAME_X_DISPLAY (f);
4956 GC gc;
4958 image_sync_to_pixmaps (f, img);
4959 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4960 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4961 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4962 img->width - 1, img->height - 1);
4963 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4964 img->width - 1, 0);
4965 XFreeGC (dpy, gc);
4967 if (img->mask)
4969 gc = XCreateGC (dpy, img->mask, 0, NULL);
4970 XSetForeground (dpy, gc, MaskForeground (f));
4971 XDrawLine (dpy, img->mask, gc, 0, 0,
4972 img->width - 1, img->height - 1);
4973 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4974 img->width - 1, 0);
4975 XFreeGC (dpy, gc);
4977 #endif /* !HAVE_NS */
4978 #else
4979 HDC hdc, bmpdc;
4980 HGDIOBJ prev;
4982 hdc = get_frame_dc (f);
4983 bmpdc = CreateCompatibleDC (hdc);
4984 release_frame_dc (f, hdc);
4986 prev = SelectObject (bmpdc, img->pixmap);
4988 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4989 MoveToEx (bmpdc, 0, 0, NULL);
4990 LineTo (bmpdc, img->width - 1, img->height - 1);
4991 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4992 LineTo (bmpdc, img->width - 1, 0);
4994 if (img->mask)
4996 SelectObject (bmpdc, img->mask);
4997 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4998 MoveToEx (bmpdc, 0, 0, NULL);
4999 LineTo (bmpdc, img->width - 1, img->height - 1);
5000 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5001 LineTo (bmpdc, img->width - 1, 0);
5003 SelectObject (bmpdc, prev);
5004 DeleteDC (bmpdc);
5005 #endif /* HAVE_NTGUI */
5010 /* Build a mask for image IMG which is used on frame F. FILE is the
5011 name of an image file, for error messages. HOW determines how to
5012 determine the background color of IMG. If it is a list '(R G B)',
5013 with R, G, and B being integers >= 0, take that as the color of the
5014 background. Otherwise, determine the background color of IMG
5015 heuristically. */
5017 static void
5018 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
5020 XImagePtr_or_DC ximg;
5021 #ifndef HAVE_NTGUI
5022 XImagePtr mask_img;
5023 #else
5024 HGDIOBJ prev;
5025 char *mask_img;
5026 int row_width;
5027 #endif /* HAVE_NTGUI */
5028 int x, y;
5029 bool use_img_background;
5030 unsigned long bg = 0;
5032 if (img->mask)
5033 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
5035 #ifndef HAVE_NTGUI
5036 #ifndef HAVE_NS
5037 /* Create an image and pixmap serving as mask. */
5038 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
5039 &mask_img, 1))
5040 return;
5041 #endif /* !HAVE_NS */
5042 #else
5043 /* Create the bit array serving as mask. */
5044 row_width = (img->width + 7) / 8;
5045 mask_img = xzalloc (row_width * img->height);
5046 #endif /* HAVE_NTGUI */
5048 /* Get the X image or create a memory device context for IMG. */
5049 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
5051 /* Determine the background color of ximg. If HOW is `(R G B)'
5052 take that as color. Otherwise, use the image's background color. */
5053 use_img_background = 1;
5055 if (CONSP (how))
5057 int rgb[3], i;
5059 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5061 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5062 how = XCDR (how);
5065 if (i == 3 && NILP (how))
5067 char color_name[30];
5068 sprintf (color_name, "#%04x%04x%04x",
5069 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
5070 bg = (
5071 #ifdef HAVE_NTGUI
5072 0x00ffffff & /* Filter out palette info. */
5073 #endif /* HAVE_NTGUI */
5074 x_alloc_image_color (f, img, build_string (color_name), 0));
5075 use_img_background = 0;
5079 if (use_img_background)
5080 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5082 /* Set all bits in mask_img to 1 whose color in ximg is different
5083 from the background color bg. */
5084 #ifndef HAVE_NTGUI
5085 for (y = 0; y < img->height; ++y)
5086 for (x = 0; x < img->width; ++x)
5087 #ifndef HAVE_NS
5088 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5089 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5090 #else
5091 if (XGetPixel (ximg, x, y) == bg)
5092 ns_set_alpha (ximg, x, y, 0);
5093 #endif /* HAVE_NS */
5094 #ifndef HAVE_NS
5095 /* Fill in the background_transparent field while we have the mask handy. */
5096 image_background_transparent (img, f, mask_img);
5098 /* Put mask_img into the image. */
5099 image_put_x_image (f, img, mask_img, 1);
5100 #endif /* !HAVE_NS */
5101 #else
5102 for (y = 0; y < img->height; ++y)
5103 for (x = 0; x < img->width; ++x)
5105 COLORREF p = GetPixel (ximg, x, y);
5106 if (p != bg)
5107 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5110 /* Create the mask image. */
5111 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5112 mask_img);
5113 /* Fill in the background_transparent field while we have the mask handy. */
5114 SelectObject (ximg, img->mask);
5115 image_background_transparent (img, f, ximg);
5117 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5118 xfree (mask_img);
5119 #endif /* HAVE_NTGUI */
5121 image_unget_x_image_or_dc (img, 0, ximg, prev);
5125 /***********************************************************************
5126 PBM (mono, gray, color)
5127 ***********************************************************************/
5129 static bool pbm_image_p (Lisp_Object object);
5130 static bool pbm_load (struct frame *f, struct image *img);
5132 /* Indices of image specification fields in gs_format, below. */
5134 enum pbm_keyword_index
5136 PBM_TYPE,
5137 PBM_FILE,
5138 PBM_DATA,
5139 PBM_ASCENT,
5140 PBM_MARGIN,
5141 PBM_RELIEF,
5142 PBM_ALGORITHM,
5143 PBM_HEURISTIC_MASK,
5144 PBM_MASK,
5145 PBM_FOREGROUND,
5146 PBM_BACKGROUND,
5147 PBM_LAST
5150 /* Vector of image_keyword structures describing the format
5151 of valid user-defined image specifications. */
5153 static const struct image_keyword pbm_format[PBM_LAST] =
5155 {":type", IMAGE_SYMBOL_VALUE, 1},
5156 {":file", IMAGE_STRING_VALUE, 0},
5157 {":data", IMAGE_STRING_VALUE, 0},
5158 {":ascent", IMAGE_ASCENT_VALUE, 0},
5159 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5160 {":relief", IMAGE_INTEGER_VALUE, 0},
5161 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5162 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5163 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5164 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5165 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5168 /* Structure describing the image type `pbm'. */
5170 static struct image_type pbm_type =
5172 SYMBOL_INDEX (Qpbm),
5173 pbm_image_p,
5174 pbm_load,
5175 x_clear_image,
5176 NULL,
5177 NULL
5181 /* Return true if OBJECT is a valid PBM image specification. */
5183 static bool
5184 pbm_image_p (Lisp_Object object)
5186 struct image_keyword fmt[PBM_LAST];
5188 memcpy (fmt, pbm_format, sizeof fmt);
5190 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5191 return 0;
5193 /* Must specify either :data or :file. */
5194 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5198 /* Get next char skipping comments in Netpbm header. Returns -1 at
5199 end of input. */
5201 static int
5202 pbm_next_char (unsigned char **s, unsigned char *end)
5204 int c = -1;
5206 while (*s < end && (c = *(*s)++, c == '#'))
5208 /* Skip to the next line break. */
5209 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5212 c = -1;
5215 return c;
5219 /* Scan a decimal number from *S and return it. Advance *S while
5220 reading the number. END is the end of the string. Value is -1 at
5221 end of input. */
5223 static int
5224 pbm_scan_number (unsigned char **s, unsigned char *end)
5226 int c = 0, val = -1;
5228 /* Skip white-space. */
5229 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5232 if (c_isdigit (c))
5234 /* Read decimal number. */
5235 val = c - '0';
5236 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5237 val = 10 * val + c - '0';
5240 return val;
5244 /* Load PBM image IMG for use on frame F. */
5246 static bool
5247 pbm_load (struct frame *f, struct image *img)
5249 bool raw_p;
5250 int x, y;
5251 int width, height, max_color_idx = 0;
5252 Lisp_Object file, specified_file;
5253 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5254 unsigned char *contents = NULL;
5255 unsigned char *end, *p;
5256 ptrdiff_t size;
5257 #ifdef USE_CAIRO
5258 unsigned char *data = 0;
5259 uint32_t *dataptr;
5260 #else
5261 XImagePtr ximg;
5262 #endif
5264 specified_file = image_spec_value (img->spec, QCfile, NULL);
5266 if (STRINGP (specified_file))
5268 file = x_find_image_file (specified_file);
5269 if (!STRINGP (file))
5271 image_error ("Cannot find image file `%s'", specified_file);
5272 return 0;
5275 contents = slurp_file (SSDATA (file), &size);
5276 if (contents == NULL)
5278 image_error ("Error reading `%s'", file);
5279 return 0;
5282 p = contents;
5283 end = contents + size;
5285 else
5287 Lisp_Object data;
5288 data = image_spec_value (img->spec, QCdata, NULL);
5289 if (!STRINGP (data))
5291 image_error ("Invalid image data `%s'", data);
5292 return 0;
5294 p = SDATA (data);
5295 end = p + SBYTES (data);
5298 /* Check magic number. */
5299 if (end - p < 2 || *p++ != 'P')
5301 image_error ("Not a PBM image: `%s'", img->spec);
5302 error:
5303 xfree (contents);
5304 img->pixmap = NO_PIXMAP;
5305 return 0;
5308 switch (*p++)
5310 case '1':
5311 raw_p = 0, type = PBM_MONO;
5312 break;
5314 case '2':
5315 raw_p = 0, type = PBM_GRAY;
5316 break;
5318 case '3':
5319 raw_p = 0, type = PBM_COLOR;
5320 break;
5322 case '4':
5323 raw_p = 1, type = PBM_MONO;
5324 break;
5326 case '5':
5327 raw_p = 1, type = PBM_GRAY;
5328 break;
5330 case '6':
5331 raw_p = 1, type = PBM_COLOR;
5332 break;
5334 default:
5335 image_error ("Not a PBM image: `%s'", img->spec);
5336 goto error;
5339 /* Read width, height, maximum color-component. Characters
5340 starting with `#' up to the end of a line are ignored. */
5341 width = pbm_scan_number (&p, end);
5342 height = pbm_scan_number (&p, end);
5344 #ifdef USE_CAIRO
5345 data = (unsigned char *) xmalloc (width * height * 4);
5346 dataptr = (uint32_t *) data;
5347 #endif
5349 if (type != PBM_MONO)
5351 max_color_idx = pbm_scan_number (&p, end);
5352 if (max_color_idx > 65535 || max_color_idx < 0)
5354 image_error ("Unsupported maximum PBM color value");
5355 goto error;
5359 if (!check_image_size (f, width, height))
5361 image_error ("Invalid image size (see `max-image-size')");
5362 goto error;
5365 #ifndef USE_CAIRO
5366 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5367 goto error;
5368 #endif
5370 /* Initialize the color hash table. */
5371 init_color_table ();
5373 if (type == PBM_MONO)
5375 int c = 0, g;
5376 struct image_keyword fmt[PBM_LAST];
5377 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5378 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5379 #ifdef USE_CAIRO
5380 XColor xfg, xbg;
5381 int fga32, bga32;
5382 #endif
5383 /* Parse the image specification. */
5384 memcpy (fmt, pbm_format, sizeof fmt);
5385 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5387 /* Get foreground and background colors, maybe allocate colors. */
5388 #ifdef USE_CAIRO
5389 if (! fmt[PBM_FOREGROUND].count
5390 || ! STRINGP (fmt[PBM_FOREGROUND].value)
5391 || ! x_defined_color (f, SSDATA (fmt[PBM_FOREGROUND].value), &xfg, 0))
5393 xfg.pixel = fg;
5394 x_query_color (f, &xfg);
5396 fga32 = xcolor_to_argb32 (xfg);
5398 if (! fmt[PBM_BACKGROUND].count
5399 || ! STRINGP (fmt[PBM_BACKGROUND].value)
5400 || ! x_defined_color (f, SSDATA (fmt[PBM_BACKGROUND].value), &xbg, 0))
5402 xbg.pixel = bg;
5403 x_query_color (f, &xbg);
5405 bga32 = xcolor_to_argb32 (xbg);
5406 #else
5407 if (fmt[PBM_FOREGROUND].count
5408 && STRINGP (fmt[PBM_FOREGROUND].value))
5409 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5410 if (fmt[PBM_BACKGROUND].count
5411 && STRINGP (fmt[PBM_BACKGROUND].value))
5413 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5414 img->background = bg;
5415 img->background_valid = 1;
5417 #endif
5419 for (y = 0; y < height; ++y)
5420 for (x = 0; x < width; ++x)
5422 if (raw_p)
5424 if ((x & 7) == 0)
5426 if (p >= end)
5428 #ifdef USE_CAIRO
5429 xfree (data);
5430 #else
5431 x_destroy_x_image (ximg);
5432 #endif
5433 x_clear_image (f, img);
5434 image_error ("Invalid image size in image `%s'",
5435 img->spec);
5436 goto error;
5438 c = *p++;
5440 g = c & 0x80;
5441 c <<= 1;
5443 else
5444 g = pbm_scan_number (&p, end);
5446 #ifdef USE_CAIRO
5447 *dataptr++ = g ? fga32 : bga32;
5448 #else
5449 XPutPixel (ximg, x, y, g ? fg : bg);
5450 #endif
5453 else
5455 int expected_size = height * width;
5456 if (max_color_idx > 255)
5457 expected_size *= 2;
5458 if (type == PBM_COLOR)
5459 expected_size *= 3;
5461 if (raw_p && p + expected_size > end)
5463 #ifdef USE_CAIRO
5464 xfree (data);
5465 #else
5466 x_destroy_x_image (ximg);
5467 #endif
5468 x_clear_image (f, img);
5469 image_error ("Invalid image size in image `%s'",
5470 img->spec);
5471 goto error;
5474 for (y = 0; y < height; ++y)
5475 for (x = 0; x < width; ++x)
5477 int r, g, b;
5479 if (type == PBM_GRAY && raw_p)
5481 r = g = b = *p++;
5482 if (max_color_idx > 255)
5483 r = g = b = r * 256 + *p++;
5485 else if (type == PBM_GRAY)
5486 r = g = b = pbm_scan_number (&p, end);
5487 else if (raw_p)
5489 r = *p++;
5490 if (max_color_idx > 255)
5491 r = r * 256 + *p++;
5492 g = *p++;
5493 if (max_color_idx > 255)
5494 g = g * 256 + *p++;
5495 b = *p++;
5496 if (max_color_idx > 255)
5497 b = b * 256 + *p++;
5499 else
5501 r = pbm_scan_number (&p, end);
5502 g = pbm_scan_number (&p, end);
5503 b = pbm_scan_number (&p, end);
5506 if (r < 0 || g < 0 || b < 0)
5508 #ifdef USE_CAIRO
5509 xfree (data);
5510 #else
5511 x_destroy_x_image (ximg);
5512 #endif
5513 image_error ("Invalid pixel value in image `%s'",
5514 img->spec);
5515 goto error;
5518 #ifdef USE_CAIRO
5519 r = (double) r * 255 / max_color_idx;
5520 g = (double) g * 255 / max_color_idx;
5521 b = (double) b * 255 / max_color_idx;
5522 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
5523 #else
5524 /* RGB values are now in the range 0..max_color_idx.
5525 Scale this to the range 0..0xffff supported by X. */
5526 r = (double) r * 65535 / max_color_idx;
5527 g = (double) g * 65535 / max_color_idx;
5528 b = (double) b * 65535 / max_color_idx;
5529 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5530 #endif
5534 #ifdef COLOR_TABLE_SUPPORT
5535 /* Store in IMG->colors the colors allocated for the image, and
5536 free the color table. */
5537 img->colors = colors_in_color_table (&img->ncolors);
5538 free_color_table ();
5539 #endif /* COLOR_TABLE_SUPPORT */
5541 img->width = width;
5542 img->height = height;
5544 /* Maybe fill in the background field while we have ximg handy. */
5546 #ifdef USE_CAIRO
5547 create_cairo_image_surface (img, data, width, height);
5548 #else
5549 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5550 /* Casting avoids a GCC warning. */
5551 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5553 /* Put ximg into the image. */
5554 image_put_x_image (f, img, ximg, 0);
5555 #endif
5557 /* X and W32 versions did it here, MAC version above. ++kfs
5558 img->width = width;
5559 img->height = height; */
5561 xfree (contents);
5562 return 1;
5566 /***********************************************************************
5568 ***********************************************************************/
5570 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5572 /* Function prototypes. */
5574 static bool png_image_p (Lisp_Object object);
5575 static bool png_load (struct frame *f, struct image *img);
5577 /* Indices of image specification fields in png_format, below. */
5579 enum png_keyword_index
5581 PNG_TYPE,
5582 PNG_DATA,
5583 PNG_FILE,
5584 PNG_ASCENT,
5585 PNG_MARGIN,
5586 PNG_RELIEF,
5587 PNG_ALGORITHM,
5588 PNG_HEURISTIC_MASK,
5589 PNG_MASK,
5590 PNG_BACKGROUND,
5591 PNG_LAST
5594 /* Vector of image_keyword structures describing the format
5595 of valid user-defined image specifications. */
5597 static const struct image_keyword png_format[PNG_LAST] =
5599 {":type", IMAGE_SYMBOL_VALUE, 1},
5600 {":data", IMAGE_STRING_VALUE, 0},
5601 {":file", IMAGE_STRING_VALUE, 0},
5602 {":ascent", IMAGE_ASCENT_VALUE, 0},
5603 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5604 {":relief", IMAGE_INTEGER_VALUE, 0},
5605 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5606 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5607 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5608 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5611 #if defined HAVE_NTGUI && defined WINDOWSNT
5612 static bool init_png_functions (void);
5613 #else
5614 #define init_png_functions NULL
5615 #endif
5617 /* Structure describing the image type `png'. */
5619 static struct image_type png_type =
5621 SYMBOL_INDEX (Qpng),
5622 png_image_p,
5623 png_load,
5624 x_clear_image,
5625 init_png_functions,
5626 NULL
5629 /* Return true if OBJECT is a valid PNG image specification. */
5631 static bool
5632 png_image_p (Lisp_Object object)
5634 struct image_keyword fmt[PNG_LAST];
5635 memcpy (fmt, png_format, sizeof fmt);
5637 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5638 return 0;
5640 /* Must specify either the :data or :file keyword. */
5641 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5644 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5647 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5649 # ifdef WINDOWSNT
5650 /* PNG library details. */
5652 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5653 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5654 DEF_DLL_FN (png_structp, png_create_read_struct,
5655 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5656 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5657 DEF_DLL_FN (void, png_destroy_read_struct,
5658 (png_structpp, png_infopp, png_infopp));
5659 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5660 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5661 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5662 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5663 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5664 int *, int *, int *, int *, int *));
5665 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5666 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5667 DEF_DLL_FN (void, png_set_expand, (png_structp));
5668 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5669 DEF_DLL_FN (void, png_set_background,
5670 (png_structp, png_color_16p, int, int, double));
5671 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5672 (png_structp, png_infop, png_color_16p *));
5673 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5674 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5675 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5676 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5677 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5678 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5680 # if (PNG_LIBPNG_VER >= 10500)
5681 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5682 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5683 (png_structp, png_longjmp_ptr, size_t));
5684 # endif /* libpng version >= 1.5 */
5686 static bool
5687 init_png_functions (void)
5689 HMODULE library;
5691 if (!(library = w32_delayed_load (Qpng)))
5692 return 0;
5694 LOAD_DLL_FN (library, png_get_io_ptr);
5695 LOAD_DLL_FN (library, png_sig_cmp);
5696 LOAD_DLL_FN (library, png_create_read_struct);
5697 LOAD_DLL_FN (library, png_create_info_struct);
5698 LOAD_DLL_FN (library, png_destroy_read_struct);
5699 LOAD_DLL_FN (library, png_set_read_fn);
5700 LOAD_DLL_FN (library, png_set_sig_bytes);
5701 LOAD_DLL_FN (library, png_read_info);
5702 LOAD_DLL_FN (library, png_get_IHDR);
5703 LOAD_DLL_FN (library, png_get_valid);
5704 LOAD_DLL_FN (library, png_set_strip_16);
5705 LOAD_DLL_FN (library, png_set_expand);
5706 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5707 LOAD_DLL_FN (library, png_set_background);
5708 LOAD_DLL_FN (library, png_get_bKGD);
5709 LOAD_DLL_FN (library, png_read_update_info);
5710 LOAD_DLL_FN (library, png_get_channels);
5711 LOAD_DLL_FN (library, png_get_rowbytes);
5712 LOAD_DLL_FN (library, png_read_image);
5713 LOAD_DLL_FN (library, png_read_end);
5714 LOAD_DLL_FN (library, png_error);
5716 # if (PNG_LIBPNG_VER >= 10500)
5717 LOAD_DLL_FN (library, png_longjmp);
5718 LOAD_DLL_FN (library, png_set_longjmp_fn);
5719 # endif /* libpng version >= 1.5 */
5721 return 1;
5724 # undef png_create_info_struct
5725 # undef png_create_read_struct
5726 # undef png_destroy_read_struct
5727 # undef png_error
5728 # undef png_get_bKGD
5729 # undef png_get_channels
5730 # undef png_get_IHDR
5731 # undef png_get_io_ptr
5732 # undef png_get_rowbytes
5733 # undef png_get_valid
5734 # undef png_longjmp
5735 # undef png_read_end
5736 # undef png_read_image
5737 # undef png_read_info
5738 # undef png_read_update_info
5739 # undef png_set_background
5740 # undef png_set_expand
5741 # undef png_set_gray_to_rgb
5742 # undef png_set_longjmp_fn
5743 # undef png_set_read_fn
5744 # undef png_set_sig_bytes
5745 # undef png_set_strip_16
5746 # undef png_sig_cmp
5748 # define png_create_info_struct fn_png_create_info_struct
5749 # define png_create_read_struct fn_png_create_read_struct
5750 # define png_destroy_read_struct fn_png_destroy_read_struct
5751 # define png_error fn_png_error
5752 # define png_get_bKGD fn_png_get_bKGD
5753 # define png_get_channels fn_png_get_channels
5754 # define png_get_IHDR fn_png_get_IHDR
5755 # define png_get_io_ptr fn_png_get_io_ptr
5756 # define png_get_rowbytes fn_png_get_rowbytes
5757 # define png_get_valid fn_png_get_valid
5758 # define png_longjmp fn_png_longjmp
5759 # define png_read_end fn_png_read_end
5760 # define png_read_image fn_png_read_image
5761 # define png_read_info fn_png_read_info
5762 # define png_read_update_info fn_png_read_update_info
5763 # define png_set_background fn_png_set_background
5764 # define png_set_expand fn_png_set_expand
5765 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5766 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5767 # define png_set_read_fn fn_png_set_read_fn
5768 # define png_set_sig_bytes fn_png_set_sig_bytes
5769 # define png_set_strip_16 fn_png_set_strip_16
5770 # define png_sig_cmp fn_png_sig_cmp
5772 # endif /* WINDOWSNT */
5774 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5775 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5776 Do not use sys_setjmp, as PNG supports only jmp_buf.
5777 It's OK if the longjmp substitute restores the signal mask. */
5778 # ifdef HAVE__SETJMP
5779 # define FAST_SETJMP(j) _setjmp (j)
5780 # define FAST_LONGJMP _longjmp
5781 # else
5782 # define FAST_SETJMP(j) setjmp (j)
5783 # define FAST_LONGJMP longjmp
5784 # endif
5786 # if PNG_LIBPNG_VER < 10500
5787 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5788 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5789 # else
5790 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5791 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5792 # define PNG_JMPBUF(ptr) \
5793 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5794 # endif
5796 /* Error and warning handlers installed when the PNG library
5797 is initialized. */
5799 static _Noreturn void
5800 my_png_error (png_struct *png_ptr, const char *msg)
5802 eassert (png_ptr != NULL);
5803 /* Avoid compiler warning about deprecated direct access to
5804 png_ptr's fields in libpng versions 1.4.x. */
5805 image_error ("PNG error: %s", build_string (msg));
5806 PNG_LONGJMP (png_ptr);
5810 static void
5811 my_png_warning (png_struct *png_ptr, const char *msg)
5813 eassert (png_ptr != NULL);
5814 image_error ("PNG warning: %s", build_string (msg));
5817 /* Memory source for PNG decoding. */
5819 struct png_memory_storage
5821 unsigned char *bytes; /* The data */
5822 ptrdiff_t len; /* How big is it? */
5823 ptrdiff_t index; /* Where are we? */
5827 /* Function set as reader function when reading PNG image from memory.
5828 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5829 bytes from the input to DATA. */
5831 static void
5832 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5834 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5836 if (length > tbr->len - tbr->index)
5837 png_error (png_ptr, "Read error");
5839 memcpy (data, tbr->bytes + tbr->index, length);
5840 tbr->index = tbr->index + length;
5844 /* Function set as reader function when reading PNG image from a file.
5845 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5846 bytes from the input to DATA. */
5848 static void
5849 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5851 FILE *fp = png_get_io_ptr (png_ptr);
5853 if (fread (data, 1, length, fp) < length)
5854 png_error (png_ptr, "Read error");
5858 /* Load PNG image IMG for use on frame F. Value is true if
5859 successful. */
5861 struct png_load_context
5863 /* These are members so that longjmp doesn't munge local variables. */
5864 png_struct *png_ptr;
5865 png_info *info_ptr;
5866 png_info *end_info;
5867 FILE *fp;
5868 png_byte *pixels;
5869 png_byte **rows;
5872 static bool
5873 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5875 Lisp_Object file, specified_file;
5876 Lisp_Object specified_data;
5877 int x, y;
5878 ptrdiff_t i;
5879 png_struct *png_ptr;
5880 png_info *info_ptr = NULL, *end_info = NULL;
5881 FILE *fp = NULL;
5882 png_byte sig[8];
5883 png_byte *pixels = NULL;
5884 png_byte **rows = NULL;
5885 png_uint_32 width, height;
5886 int bit_depth, color_type, interlace_type;
5887 png_byte channels;
5888 png_uint_32 row_bytes;
5889 bool transparent_p;
5890 struct png_memory_storage tbr; /* Data to be read */
5892 #ifdef USE_CAIRO
5893 unsigned char *data = 0;
5894 uint32_t *dataptr;
5895 #else
5896 XImagePtr ximg, mask_img = NULL;
5897 #endif
5899 /* Find out what file to load. */
5900 specified_file = image_spec_value (img->spec, QCfile, NULL);
5901 specified_data = image_spec_value (img->spec, QCdata, NULL);
5902 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
5904 if (NILP (specified_data))
5906 file = x_find_image_file (specified_file);
5907 if (!STRINGP (file))
5909 image_error ("Cannot find image file `%s'", specified_file);
5910 return 0;
5913 /* Open the image file. */
5914 fp = emacs_fopen (SSDATA (file), "rb");
5915 if (!fp)
5917 image_error ("Cannot open image file `%s'", file);
5918 return 0;
5921 /* Check PNG signature. */
5922 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5923 || png_sig_cmp (sig, 0, sizeof sig))
5925 fclose (fp);
5926 image_error ("Not a PNG file: `%s'", file);
5927 return 0;
5930 else
5932 if (!STRINGP (specified_data))
5934 image_error ("Invalid image data `%s'", specified_data);
5935 return 0;
5938 /* Read from memory. */
5939 tbr.bytes = SDATA (specified_data);
5940 tbr.len = SBYTES (specified_data);
5941 tbr.index = 0;
5943 /* Check PNG signature. */
5944 if (tbr.len < sizeof sig
5945 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5947 image_error ("Not a PNG image: `%s'", img->spec);
5948 return 0;
5951 /* Need to skip past the signature. */
5952 tbr.bytes += sizeof (sig);
5955 /* Initialize read and info structs for PNG lib. */
5956 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5957 NULL, my_png_error,
5958 my_png_warning);
5959 if (png_ptr)
5961 info_ptr = png_create_info_struct (png_ptr);
5962 end_info = png_create_info_struct (png_ptr);
5965 c->png_ptr = png_ptr;
5966 c->info_ptr = info_ptr;
5967 c->end_info = end_info;
5968 c->fp = fp;
5969 c->pixels = pixels;
5970 c->rows = rows;
5972 if (! (info_ptr && end_info))
5974 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5975 png_ptr = 0;
5977 if (! png_ptr)
5979 if (fp) fclose (fp);
5980 return 0;
5983 /* Set error jump-back. We come back here when the PNG library
5984 detects an error. */
5985 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
5987 error:
5988 if (c->png_ptr)
5989 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5990 xfree (c->pixels);
5991 xfree (c->rows);
5992 if (c->fp)
5993 fclose (c->fp);
5994 return 0;
5997 /* Silence a bogus diagnostic; see GCC bug 54561. */
5998 IF_LINT (fp = c->fp);
5999 IF_LINT (specified_data = specified_data_volatile);
6001 /* Read image info. */
6002 if (!NILP (specified_data))
6003 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
6004 else
6005 png_set_read_fn (png_ptr, fp, png_read_from_file);
6007 png_set_sig_bytes (png_ptr, sizeof sig);
6008 png_read_info (png_ptr, info_ptr);
6009 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6010 &interlace_type, NULL, NULL);
6012 if (! (width <= INT_MAX && height <= INT_MAX
6013 && check_image_size (f, width, height)))
6015 image_error ("Invalid image size (see `max-image-size')");
6016 goto error;
6019 #ifndef USE_CAIRO
6020 /* Create the X image and pixmap now, so that the work below can be
6021 omitted if the image is too large for X. */
6022 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6023 goto error;
6024 #endif
6026 /* If image contains simply transparency data, we prefer to
6027 construct a clipping mask. */
6028 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6029 transparent_p = 1;
6030 else
6031 transparent_p = 0;
6033 /* This function is easier to write if we only have to handle
6034 one data format: RGB or RGBA with 8 bits per channel. Let's
6035 transform other formats into that format. */
6037 /* Strip more than 8 bits per channel. */
6038 if (bit_depth == 16)
6039 png_set_strip_16 (png_ptr);
6041 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6042 if available. */
6043 png_set_expand (png_ptr);
6045 /* Convert grayscale images to RGB. */
6046 if (color_type == PNG_COLOR_TYPE_GRAY
6047 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6048 png_set_gray_to_rgb (png_ptr);
6050 /* Handle alpha channel by combining the image with a background
6051 color. Do this only if a real alpha channel is supplied. For
6052 simple transparency, we prefer a clipping mask. */
6053 if (!transparent_p)
6055 /* png_color_16 *image_bg; */
6056 Lisp_Object specified_bg
6057 = image_spec_value (img->spec, QCbackground, NULL);
6058 XColor color;
6060 /* If the user specified a color, try to use it; if not, use the
6061 current frame background, ignoring any default background
6062 color set by the image. */
6063 if (STRINGP (specified_bg)
6064 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
6065 : (x_query_frame_background_color (f, &color), true))
6066 /* The user specified `:background', use that. */
6068 int shift = bit_depth == 16 ? 0 : 8;
6069 png_color_16 bg = { 0 };
6070 bg.red = color.red >> shift;
6071 bg.green = color.green >> shift;
6072 bg.blue = color.blue >> shift;
6074 png_set_background (png_ptr, &bg,
6075 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6079 /* Update info structure. */
6080 png_read_update_info (png_ptr, info_ptr);
6082 /* Get number of channels. Valid values are 1 for grayscale images
6083 and images with a palette, 2 for grayscale images with transparency
6084 information (alpha channel), 3 for RGB images, and 4 for RGB
6085 images with alpha channel, i.e. RGBA. If conversions above were
6086 sufficient we should only have 3 or 4 channels here. */
6087 channels = png_get_channels (png_ptr, info_ptr);
6088 eassert (channels == 3 || channels == 4);
6090 /* Number of bytes needed for one row of the image. */
6091 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
6093 /* Allocate memory for the image. */
6094 if (height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows
6095 || row_bytes > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height)
6096 memory_full (SIZE_MAX);
6097 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
6098 c->rows = rows = xmalloc (height * sizeof *rows);
6099 for (i = 0; i < height; ++i)
6100 rows[i] = pixels + i * row_bytes;
6102 /* Read the entire image. */
6103 png_read_image (png_ptr, rows);
6104 png_read_end (png_ptr, info_ptr);
6105 if (fp)
6107 fclose (fp);
6108 c->fp = NULL;
6111 #ifdef USE_CAIRO
6112 data = (unsigned char *) xmalloc (width * height * 4);
6113 dataptr = (uint32_t *) data;
6114 #else
6115 /* Create an image and pixmap serving as mask if the PNG image
6116 contains an alpha channel. */
6117 if (channels == 4
6118 && !transparent_p
6119 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
6120 &mask_img, 1))
6122 x_destroy_x_image (ximg);
6123 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
6124 goto error;
6126 #endif
6128 /* Fill the X image and mask from PNG data. */
6129 init_color_table ();
6131 for (y = 0; y < height; ++y)
6133 png_byte *p = rows[y];
6135 for (x = 0; x < width; ++x)
6137 int r, g, b;
6139 #ifdef USE_CAIRO
6140 int a = 0xff;
6141 r = *p++;
6142 g = *p++;
6143 b = *p++;
6144 if (channels == 4) a = *p++;
6145 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
6146 #else
6147 r = *p++ << 8;
6148 g = *p++ << 8;
6149 b = *p++ << 8;
6150 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6151 /* An alpha channel, aka mask channel, associates variable
6152 transparency with an image. Where other image formats
6153 support binary transparency---fully transparent or fully
6154 opaque---PNG allows up to 254 levels of partial transparency.
6155 The PNG library implements partial transparency by combining
6156 the image with a specified background color.
6158 I'm not sure how to handle this here nicely: because the
6159 background on which the image is displayed may change, for
6160 real alpha channel support, it would be necessary to create
6161 a new image for each possible background.
6163 What I'm doing now is that a mask is created if we have
6164 boolean transparency information. Otherwise I'm using
6165 the frame's background color to combine the image with. */
6167 if (channels == 4)
6169 if (mask_img)
6170 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6171 ++p;
6173 #endif
6177 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6178 /* Set IMG's background color from the PNG image, unless the user
6179 overrode it. */
6181 png_color_16 *bg;
6182 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6184 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6185 img->background_valid = 1;
6189 # ifdef COLOR_TABLE_SUPPORT
6190 /* Remember colors allocated for this image. */
6191 img->colors = colors_in_color_table (&img->ncolors);
6192 free_color_table ();
6193 # endif /* COLOR_TABLE_SUPPORT */
6195 /* Clean up. */
6196 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6197 xfree (rows);
6198 xfree (pixels);
6200 img->width = width;
6201 img->height = height;
6203 #ifdef USE_CAIRO
6204 create_cairo_image_surface (img, data, width, height);
6205 #else
6206 /* Maybe fill in the background field while we have ximg handy.
6207 Casting avoids a GCC warning. */
6208 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6210 /* Put ximg into the image. */
6211 image_put_x_image (f, img, ximg, 0);
6213 /* Same for the mask. */
6214 if (mask_img)
6216 /* Fill in the background_transparent field while we have the
6217 mask handy. Casting avoids a GCC warning. */
6218 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6220 image_put_x_image (f, img, mask_img, 1);
6222 #endif
6224 return 1;
6227 static bool
6228 png_load (struct frame *f, struct image *img)
6230 struct png_load_context c;
6231 return png_load_body (f, img, &c);
6234 #elif defined HAVE_NS
6236 static bool
6237 png_load (struct frame *f, struct image *img)
6239 return ns_load_image (f, img,
6240 image_spec_value (img->spec, QCfile, NULL),
6241 image_spec_value (img->spec, QCdata, NULL));
6245 #endif /* HAVE_NS */
6249 /***********************************************************************
6250 JPEG
6251 ***********************************************************************/
6253 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6255 static bool jpeg_image_p (Lisp_Object object);
6256 static bool jpeg_load (struct frame *f, struct image *img);
6258 /* Indices of image specification fields in gs_format, below. */
6260 enum jpeg_keyword_index
6262 JPEG_TYPE,
6263 JPEG_DATA,
6264 JPEG_FILE,
6265 JPEG_ASCENT,
6266 JPEG_MARGIN,
6267 JPEG_RELIEF,
6268 JPEG_ALGORITHM,
6269 JPEG_HEURISTIC_MASK,
6270 JPEG_MASK,
6271 JPEG_BACKGROUND,
6272 JPEG_LAST
6275 /* Vector of image_keyword structures describing the format
6276 of valid user-defined image specifications. */
6278 static const struct image_keyword jpeg_format[JPEG_LAST] =
6280 {":type", IMAGE_SYMBOL_VALUE, 1},
6281 {":data", IMAGE_STRING_VALUE, 0},
6282 {":file", IMAGE_STRING_VALUE, 0},
6283 {":ascent", IMAGE_ASCENT_VALUE, 0},
6284 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6285 {":relief", IMAGE_INTEGER_VALUE, 0},
6286 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6287 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6288 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6289 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6292 #if defined HAVE_NTGUI && defined WINDOWSNT
6293 static bool init_jpeg_functions (void);
6294 #else
6295 #define init_jpeg_functions NULL
6296 #endif
6298 /* Structure describing the image type `jpeg'. */
6300 static struct image_type jpeg_type =
6302 SYMBOL_INDEX (Qjpeg),
6303 jpeg_image_p,
6304 jpeg_load,
6305 x_clear_image,
6306 init_jpeg_functions,
6307 NULL
6310 /* Return true if OBJECT is a valid JPEG image specification. */
6312 static bool
6313 jpeg_image_p (Lisp_Object object)
6315 struct image_keyword fmt[JPEG_LAST];
6317 memcpy (fmt, jpeg_format, sizeof fmt);
6319 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6320 return 0;
6322 /* Must specify either the :data or :file keyword. */
6323 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6326 #endif /* HAVE_JPEG || HAVE_NS */
6328 #ifdef HAVE_JPEG
6330 /* Work around a warning about HAVE_STDLIB_H being redefined in
6331 jconfig.h. */
6332 # ifdef HAVE_STDLIB_H
6333 # undef HAVE_STDLIB_H
6334 # endif
6336 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6337 /* In older releases of the jpeg library, jpeglib.h will define boolean
6338 differently depending on __WIN32__, so make sure it is defined. */
6339 # define __WIN32__ 1
6340 # endif
6342 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6343 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6344 using the Windows boolean type instead of the jpeglib boolean type
6345 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6346 headers are included along with windows.h, so under Cygwin, jpeglib
6347 attempts to define a conflicting boolean type. Worse, forcing
6348 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6349 because it created an ABI incompatibility between the
6350 already-compiled jpeg library and the header interface definition.
6352 The best we can do is to define jpeglib's boolean type to a
6353 different name. This name, jpeg_boolean, remains in effect through
6354 the rest of image.c.
6356 # if defined CYGWIN && defined HAVE_NTGUI
6357 # define boolean jpeg_boolean
6358 # endif
6359 # include <jpeglib.h>
6360 # include <jerror.h>
6362 # ifdef WINDOWSNT
6364 /* JPEG library details. */
6365 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6366 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6367 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6368 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6369 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6370 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6371 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6372 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6373 (struct jpeg_error_mgr *));
6374 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6376 static bool
6377 init_jpeg_functions (void)
6379 HMODULE library;
6381 if (!(library = w32_delayed_load (Qjpeg)))
6382 return 0;
6384 LOAD_DLL_FN (library, jpeg_finish_decompress);
6385 LOAD_DLL_FN (library, jpeg_read_scanlines);
6386 LOAD_DLL_FN (library, jpeg_start_decompress);
6387 LOAD_DLL_FN (library, jpeg_read_header);
6388 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6389 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6390 LOAD_DLL_FN (library, jpeg_std_error);
6391 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6392 return 1;
6395 # undef jpeg_CreateDecompress
6396 # undef jpeg_destroy_decompress
6397 # undef jpeg_finish_decompress
6398 # undef jpeg_read_header
6399 # undef jpeg_read_scanlines
6400 # undef jpeg_resync_to_restart
6401 # undef jpeg_start_decompress
6402 # undef jpeg_std_error
6404 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6405 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6406 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6407 # define jpeg_read_header fn_jpeg_read_header
6408 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6409 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6410 # define jpeg_start_decompress fn_jpeg_start_decompress
6411 # define jpeg_std_error fn_jpeg_std_error
6413 /* Wrapper since we can't directly assign the function pointer
6414 to another function pointer that was declared more completely easily. */
6415 static boolean
6416 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6418 return jpeg_resync_to_restart (cinfo, desired);
6420 # undef jpeg_resync_to_restart
6421 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6423 # endif /* WINDOWSNT */
6425 struct my_jpeg_error_mgr
6427 struct jpeg_error_mgr pub;
6428 sys_jmp_buf setjmp_buffer;
6430 /* The remaining members are so that longjmp doesn't munge local
6431 variables. */
6432 struct jpeg_decompress_struct cinfo;
6433 enum
6435 MY_JPEG_ERROR_EXIT,
6436 MY_JPEG_INVALID_IMAGE_SIZE,
6437 MY_JPEG_CANNOT_CREATE_X
6438 } failure_code;
6442 static _Noreturn void
6443 my_error_exit (j_common_ptr cinfo)
6445 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6446 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6447 sys_longjmp (mgr->setjmp_buffer, 1);
6451 /* Init source method for JPEG data source manager. Called by
6452 jpeg_read_header() before any data is actually read. See
6453 libjpeg.doc from the JPEG lib distribution. */
6455 static void
6456 our_common_init_source (j_decompress_ptr cinfo)
6461 /* Method to terminate data source. Called by
6462 jpeg_finish_decompress() after all data has been processed. */
6464 static void
6465 our_common_term_source (j_decompress_ptr cinfo)
6470 /* Fill input buffer method for JPEG data source manager. Called
6471 whenever more data is needed. We read the whole image in one step,
6472 so this only adds a fake end of input marker at the end. */
6474 static JOCTET our_memory_buffer[2];
6476 static boolean
6477 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6479 /* Insert a fake EOI marker. */
6480 struct jpeg_source_mgr *src = cinfo->src;
6482 our_memory_buffer[0] = (JOCTET) 0xFF;
6483 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6485 src->next_input_byte = our_memory_buffer;
6486 src->bytes_in_buffer = 2;
6487 return 1;
6491 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6492 is the JPEG data source manager. */
6494 static void
6495 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6497 struct jpeg_source_mgr *src = cinfo->src;
6499 if (src)
6501 if (num_bytes > src->bytes_in_buffer)
6502 ERREXIT (cinfo, JERR_INPUT_EOF);
6504 src->bytes_in_buffer -= num_bytes;
6505 src->next_input_byte += num_bytes;
6510 /* Set up the JPEG lib for reading an image from DATA which contains
6511 LEN bytes. CINFO is the decompression info structure created for
6512 reading the image. */
6514 static void
6515 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6517 struct jpeg_source_mgr *src = cinfo->src;
6519 if (! src)
6521 /* First time for this JPEG object? */
6522 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6523 JPOOL_PERMANENT, sizeof *src);
6524 cinfo->src = src;
6525 src->next_input_byte = data;
6528 src->init_source = our_common_init_source;
6529 src->fill_input_buffer = our_memory_fill_input_buffer;
6530 src->skip_input_data = our_memory_skip_input_data;
6531 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6532 src->term_source = our_common_term_source;
6533 src->bytes_in_buffer = len;
6534 src->next_input_byte = data;
6538 struct jpeg_stdio_mgr
6540 struct jpeg_source_mgr mgr;
6541 boolean finished;
6542 FILE *file;
6543 JOCTET *buffer;
6547 /* Size of buffer to read JPEG from file.
6548 Not too big, as we want to use alloc_small. */
6549 #define JPEG_STDIO_BUFFER_SIZE 8192
6552 /* Fill input buffer method for JPEG data source manager. Called
6553 whenever more data is needed. The data is read from a FILE *. */
6555 static boolean
6556 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6558 struct jpeg_stdio_mgr *src;
6560 src = (struct jpeg_stdio_mgr *) cinfo->src;
6561 if (!src->finished)
6563 ptrdiff_t bytes;
6565 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6566 if (bytes > 0)
6567 src->mgr.bytes_in_buffer = bytes;
6568 else
6570 WARNMS (cinfo, JWRN_JPEG_EOF);
6571 src->finished = 1;
6572 src->buffer[0] = (JOCTET) 0xFF;
6573 src->buffer[1] = (JOCTET) JPEG_EOI;
6574 src->mgr.bytes_in_buffer = 2;
6576 src->mgr.next_input_byte = src->buffer;
6579 return 1;
6583 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6584 is the JPEG data source manager. */
6586 static void
6587 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6589 struct jpeg_stdio_mgr *src;
6590 src = (struct jpeg_stdio_mgr *) cinfo->src;
6592 while (num_bytes > 0 && !src->finished)
6594 if (num_bytes <= src->mgr.bytes_in_buffer)
6596 src->mgr.bytes_in_buffer -= num_bytes;
6597 src->mgr.next_input_byte += num_bytes;
6598 break;
6600 else
6602 num_bytes -= src->mgr.bytes_in_buffer;
6603 src->mgr.bytes_in_buffer = 0;
6604 src->mgr.next_input_byte = NULL;
6606 our_stdio_fill_input_buffer (cinfo);
6612 /* Set up the JPEG lib for reading an image from a FILE *.
6613 CINFO is the decompression info structure created for
6614 reading the image. */
6616 static void
6617 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6619 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6621 if (! src)
6623 /* First time for this JPEG object? */
6624 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6625 JPOOL_PERMANENT, sizeof *src);
6626 cinfo->src = (struct jpeg_source_mgr *) src;
6627 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6628 JPOOL_PERMANENT,
6629 JPEG_STDIO_BUFFER_SIZE);
6632 src->file = fp;
6633 src->finished = 0;
6634 src->mgr.init_source = our_common_init_source;
6635 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6636 src->mgr.skip_input_data = our_stdio_skip_input_data;
6637 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6638 src->mgr.term_source = our_common_term_source;
6639 src->mgr.bytes_in_buffer = 0;
6640 src->mgr.next_input_byte = NULL;
6643 /* Load image IMG for use on frame F. Patterned after example.c
6644 from the JPEG lib. */
6646 static bool
6647 jpeg_load_body (struct frame *f, struct image *img,
6648 struct my_jpeg_error_mgr *mgr)
6650 Lisp_Object file, specified_file;
6651 Lisp_Object specified_data;
6652 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6653 FILE * IF_LINT (volatile) fp = NULL;
6654 JSAMPARRAY buffer;
6655 int row_stride, x, y;
6656 unsigned long *colors;
6657 int width, height;
6658 int i, ir, ig, ib;
6659 #ifndef USE_CAIRO
6660 XImagePtr ximg = NULL;
6661 #endif
6663 /* Open the JPEG file. */
6664 specified_file = image_spec_value (img->spec, QCfile, NULL);
6665 specified_data = image_spec_value (img->spec, QCdata, NULL);
6666 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
6668 if (NILP (specified_data))
6670 file = x_find_image_file (specified_file);
6671 if (!STRINGP (file))
6673 image_error ("Cannot find image file `%s'", specified_file);
6674 return 0;
6677 fp = emacs_fopen (SSDATA (file), "rb");
6678 if (fp == NULL)
6680 image_error ("Cannot open `%s'", file);
6681 return 0;
6684 else if (!STRINGP (specified_data))
6686 image_error ("Invalid image data `%s'", specified_data);
6687 return 0;
6690 /* Customize libjpeg's error handling to call my_error_exit when an
6691 error is detected. This function will perform a longjmp. */
6692 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6693 mgr->pub.error_exit = my_error_exit;
6694 if (sys_setjmp (mgr->setjmp_buffer))
6696 switch (mgr->failure_code)
6698 case MY_JPEG_ERROR_EXIT:
6700 char buf[JMSG_LENGTH_MAX];
6701 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6702 image_error ("Error reading JPEG image `%s': %s", img->spec,
6703 build_string (buf));
6704 break;
6707 case MY_JPEG_INVALID_IMAGE_SIZE:
6708 image_error ("Invalid image size (see `max-image-size')");
6709 break;
6711 case MY_JPEG_CANNOT_CREATE_X:
6712 break;
6715 /* Close the input file and destroy the JPEG object. */
6716 if (fp)
6717 fclose (fp);
6718 jpeg_destroy_decompress (&mgr->cinfo);
6720 /* If we already have an XImage, free that. */
6721 #ifndef USE_CAIRO
6722 x_destroy_x_image (ximg);
6723 #endif
6724 /* Free pixmap and colors. */
6725 x_clear_image (f, img);
6726 return 0;
6729 /* Silence a bogus diagnostic; see GCC bug 54561. */
6730 IF_LINT (specified_data = specified_data_volatile);
6732 /* Create the JPEG decompression object. Let it read from fp.
6733 Read the JPEG image header. */
6734 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6736 if (NILP (specified_data))
6737 jpeg_file_src (&mgr->cinfo, fp);
6738 else
6739 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6740 SBYTES (specified_data));
6742 jpeg_read_header (&mgr->cinfo, 1);
6744 /* Customize decompression so that color quantization will be used.
6745 Start decompression. */
6746 mgr->cinfo.quantize_colors = 1;
6747 jpeg_start_decompress (&mgr->cinfo);
6748 width = img->width = mgr->cinfo.output_width;
6749 height = img->height = mgr->cinfo.output_height;
6751 if (!check_image_size (f, width, height))
6753 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6754 sys_longjmp (mgr->setjmp_buffer, 1);
6757 #ifndef USE_CAIRO
6758 /* Create X image and pixmap. */
6759 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6761 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6762 sys_longjmp (mgr->setjmp_buffer, 1);
6764 #endif
6766 /* Allocate colors. When color quantization is used,
6767 mgr->cinfo.actual_number_of_colors has been set with the number of
6768 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6769 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6770 No more than 255 colors will be generated. */
6771 USE_SAFE_ALLOCA;
6773 if (mgr->cinfo.out_color_components > 2)
6774 ir = 0, ig = 1, ib = 2;
6775 else if (mgr->cinfo.out_color_components > 1)
6776 ir = 0, ig = 1, ib = 0;
6777 else
6778 ir = 0, ig = 0, ib = 0;
6780 #ifndef CAIRO
6781 /* Use the color table mechanism because it handles colors that
6782 cannot be allocated nicely. Such colors will be replaced with
6783 a default color, and we don't have to care about which colors
6784 can be freed safely, and which can't. */
6785 init_color_table ();
6786 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6788 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6790 /* Multiply RGB values with 255 because X expects RGB values
6791 in the range 0..0xffff. */
6792 int r = mgr->cinfo.colormap[ir][i] << 8;
6793 int g = mgr->cinfo.colormap[ig][i] << 8;
6794 int b = mgr->cinfo.colormap[ib][i] << 8;
6795 colors[i] = lookup_rgb_color (f, r, g, b);
6797 #endif
6799 #ifdef COLOR_TABLE_SUPPORT
6800 /* Remember those colors actually allocated. */
6801 img->colors = colors_in_color_table (&img->ncolors);
6802 free_color_table ();
6803 #endif /* COLOR_TABLE_SUPPORT */
6806 /* Read pixels. */
6807 row_stride = width * mgr->cinfo.output_components;
6808 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6809 JPOOL_IMAGE, row_stride, 1);
6810 #ifdef USE_CAIRO
6812 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
6813 uint32_t *dataptr = (uint32_t *) data;
6814 int r, g, b;
6816 for (y = 0; y < height; ++y)
6818 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6820 for (x = 0; x < width; ++x)
6822 i = buffer[0][x];
6823 r = mgr->cinfo.colormap[ir][i];
6824 g = mgr->cinfo.colormap[ig][i];
6825 b = mgr->cinfo.colormap[ib][i];
6826 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
6830 create_cairo_image_surface (img, data, width, height);
6832 #else
6833 for (y = 0; y < height; ++y)
6835 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6836 for (x = 0; x < mgr->cinfo.output_width; ++x)
6837 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6839 #endif
6841 /* Clean up. */
6842 jpeg_finish_decompress (&mgr->cinfo);
6843 jpeg_destroy_decompress (&mgr->cinfo);
6844 if (fp)
6845 fclose (fp);
6847 #ifndef USE_CAIRO
6848 /* Maybe fill in the background field while we have ximg handy. */
6849 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6850 /* Casting avoids a GCC warning. */
6851 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6853 /* Put ximg into the image. */
6854 image_put_x_image (f, img, ximg, 0);
6855 #endif
6856 SAFE_FREE ();
6857 return 1;
6860 static bool
6861 jpeg_load (struct frame *f, struct image *img)
6863 struct my_jpeg_error_mgr mgr;
6864 return jpeg_load_body (f, img, &mgr);
6867 #else /* HAVE_JPEG */
6869 #ifdef HAVE_NS
6870 static bool
6871 jpeg_load (struct frame *f, struct image *img)
6873 return ns_load_image (f, img,
6874 image_spec_value (img->spec, QCfile, NULL),
6875 image_spec_value (img->spec, QCdata, NULL));
6877 #endif /* HAVE_NS */
6879 #endif /* !HAVE_JPEG */
6883 /***********************************************************************
6884 TIFF
6885 ***********************************************************************/
6887 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6889 static bool tiff_image_p (Lisp_Object object);
6890 static bool tiff_load (struct frame *f, struct image *img);
6892 /* Indices of image specification fields in tiff_format, below. */
6894 enum tiff_keyword_index
6896 TIFF_TYPE,
6897 TIFF_DATA,
6898 TIFF_FILE,
6899 TIFF_ASCENT,
6900 TIFF_MARGIN,
6901 TIFF_RELIEF,
6902 TIFF_ALGORITHM,
6903 TIFF_HEURISTIC_MASK,
6904 TIFF_MASK,
6905 TIFF_BACKGROUND,
6906 TIFF_INDEX,
6907 TIFF_LAST
6910 /* Vector of image_keyword structures describing the format
6911 of valid user-defined image specifications. */
6913 static const struct image_keyword tiff_format[TIFF_LAST] =
6915 {":type", IMAGE_SYMBOL_VALUE, 1},
6916 {":data", IMAGE_STRING_VALUE, 0},
6917 {":file", IMAGE_STRING_VALUE, 0},
6918 {":ascent", IMAGE_ASCENT_VALUE, 0},
6919 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6920 {":relief", IMAGE_INTEGER_VALUE, 0},
6921 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6922 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6923 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6924 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6925 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6928 #if defined HAVE_NTGUI && defined WINDOWSNT
6929 static bool init_tiff_functions (void);
6930 #else
6931 #define init_tiff_functions NULL
6932 #endif
6934 /* Structure describing the image type `tiff'. */
6936 static struct image_type tiff_type =
6938 SYMBOL_INDEX (Qtiff),
6939 tiff_image_p,
6940 tiff_load,
6941 x_clear_image,
6942 init_tiff_functions,
6943 NULL
6946 /* Return true if OBJECT is a valid TIFF image specification. */
6948 static bool
6949 tiff_image_p (Lisp_Object object)
6951 struct image_keyword fmt[TIFF_LAST];
6952 memcpy (fmt, tiff_format, sizeof fmt);
6954 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6955 return 0;
6957 /* Must specify either the :data or :file keyword. */
6958 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6961 #endif /* HAVE_TIFF || HAVE_NS */
6963 #ifdef HAVE_TIFF
6965 # include <tiffio.h>
6967 # ifdef WINDOWSNT
6969 /* TIFF library details. */
6970 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6971 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6972 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
6973 DEF_DLL_FN (TIFF *, TIFFClientOpen,
6974 (const char *, const char *, thandle_t, TIFFReadWriteProc,
6975 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6976 TIFFMapFileProc, TIFFUnmapFileProc));
6977 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6978 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6979 DEF_DLL_FN (void, TIFFClose, (TIFF *));
6980 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6982 static bool
6983 init_tiff_functions (void)
6985 HMODULE library;
6987 if (!(library = w32_delayed_load (Qtiff)))
6988 return 0;
6990 LOAD_DLL_FN (library, TIFFSetErrorHandler);
6991 LOAD_DLL_FN (library, TIFFSetWarningHandler);
6992 LOAD_DLL_FN (library, TIFFOpen);
6993 LOAD_DLL_FN (library, TIFFClientOpen);
6994 LOAD_DLL_FN (library, TIFFGetField);
6995 LOAD_DLL_FN (library, TIFFReadRGBAImage);
6996 LOAD_DLL_FN (library, TIFFClose);
6997 LOAD_DLL_FN (library, TIFFSetDirectory);
6998 return 1;
7001 # undef TIFFClientOpen
7002 # undef TIFFClose
7003 # undef TIFFGetField
7004 # undef TIFFOpen
7005 # undef TIFFReadRGBAImage
7006 # undef TIFFSetDirectory
7007 # undef TIFFSetErrorHandler
7008 # undef TIFFSetWarningHandler
7010 # define TIFFClientOpen fn_TIFFClientOpen
7011 # define TIFFClose fn_TIFFClose
7012 # define TIFFGetField fn_TIFFGetField
7013 # define TIFFOpen fn_TIFFOpen
7014 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7015 # define TIFFSetDirectory fn_TIFFSetDirectory
7016 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7017 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7019 # endif /* WINDOWSNT */
7022 /* Reading from a memory buffer for TIFF images Based on the PNG
7023 memory source, but we have to provide a lot of extra functions.
7024 Blah.
7026 We really only need to implement read and seek, but I am not
7027 convinced that the TIFF library is smart enough not to destroy
7028 itself if we only hand it the function pointers we need to
7029 override. */
7031 typedef struct
7033 unsigned char *bytes;
7034 ptrdiff_t len;
7035 ptrdiff_t index;
7037 tiff_memory_source;
7039 static tsize_t
7040 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7042 tiff_memory_source *src = (tiff_memory_source *) data;
7044 size = min (size, src->len - src->index);
7045 memcpy (buf, src->bytes + src->index, size);
7046 src->index += size;
7047 return size;
7050 static tsize_t
7051 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7053 return -1;
7056 static toff_t
7057 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
7059 tiff_memory_source *src = (tiff_memory_source *) data;
7060 ptrdiff_t idx;
7062 switch (whence)
7064 case SEEK_SET: /* Go from beginning of source. */
7065 idx = off;
7066 break;
7068 case SEEK_END: /* Go from end of source. */
7069 idx = src->len + off;
7070 break;
7072 case SEEK_CUR: /* Go from current position. */
7073 idx = src->index + off;
7074 break;
7076 default: /* Invalid `whence'. */
7077 return -1;
7080 if (idx > src->len || idx < 0)
7081 return -1;
7083 src->index = idx;
7084 return src->index;
7087 static int
7088 tiff_close_memory (thandle_t data)
7090 /* NOOP */
7091 return 0;
7094 static int
7095 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
7097 /* It is already _IN_ memory. */
7098 return 0;
7101 static void
7102 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
7104 /* We don't need to do this. */
7107 static toff_t
7108 tiff_size_of_memory (thandle_t data)
7110 return ((tiff_memory_source *) data)->len;
7113 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7114 compiler error compiling tiff_handler, see Bugzilla bug #17406
7115 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7116 this function as external works around that problem. */
7117 # if defined (__MINGW32__) && __GNUC__ == 3
7118 # define MINGW_STATIC
7119 # else
7120 # define MINGW_STATIC static
7121 # endif
7123 MINGW_STATIC void
7124 tiff_handler (const char *, const char *, const char *, va_list)
7125 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7126 MINGW_STATIC void
7127 tiff_handler (const char *log_format, const char *title,
7128 const char *format, va_list ap)
7130 /* doprnt is not suitable here, as TIFF handlers are called from
7131 libtiff and are passed arbitrary printf directives. Instead, use
7132 vsnprintf, taking care to be portable to nonstandard environments
7133 where vsnprintf returns -1 on buffer overflow. Since it's just a
7134 log entry, it's OK to truncate it. */
7135 char buf[4000];
7136 int len = vsnprintf (buf, sizeof buf, format, ap);
7137 add_to_log (log_format, build_string (title),
7138 make_string (buf, max (0, min (len, sizeof buf - 1))));
7140 # undef MINGW_STATIC
7142 static void tiff_error_handler (const char *, const char *, va_list)
7143 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7144 static void
7145 tiff_error_handler (const char *title, const char *format, va_list ap)
7147 tiff_handler ("TIFF error: %s %s", title, format, ap);
7151 static void tiff_warning_handler (const char *, const char *, va_list)
7152 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7153 static void
7154 tiff_warning_handler (const char *title, const char *format, va_list ap)
7156 tiff_handler ("TIFF warning: %s %s", title, format, ap);
7160 /* Load TIFF image IMG for use on frame F. Value is true if
7161 successful. */
7163 static bool
7164 tiff_load (struct frame *f, struct image *img)
7166 Lisp_Object file, specified_file;
7167 Lisp_Object specified_data;
7168 TIFF *tiff;
7169 int width, height, x, y, count;
7170 uint32 *buf;
7171 int rc;
7172 XImagePtr ximg;
7173 tiff_memory_source memsrc;
7174 Lisp_Object image;
7176 specified_file = image_spec_value (img->spec, QCfile, NULL);
7177 specified_data = image_spec_value (img->spec, QCdata, NULL);
7179 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
7180 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7182 if (NILP (specified_data))
7184 /* Read from a file */
7185 file = x_find_image_file (specified_file);
7186 if (!STRINGP (file))
7188 image_error ("Cannot find image file `%s'", specified_file);
7189 return 0;
7191 # ifdef WINDOWSNT
7192 file = ansi_encode_filename (file);
7193 # endif
7195 /* Try to open the image file. */
7196 tiff = TIFFOpen (SSDATA (file), "r");
7197 if (tiff == NULL)
7199 image_error ("Cannot open `%s'", file);
7200 return 0;
7203 else
7205 if (!STRINGP (specified_data))
7207 image_error ("Invalid image data `%s'", specified_data);
7208 return 0;
7211 /* Memory source! */
7212 memsrc.bytes = SDATA (specified_data);
7213 memsrc.len = SBYTES (specified_data);
7214 memsrc.index = 0;
7216 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7217 tiff_read_from_memory,
7218 tiff_write_from_memory,
7219 tiff_seek_in_memory,
7220 tiff_close_memory,
7221 tiff_size_of_memory,
7222 tiff_mmap_memory,
7223 tiff_unmap_memory);
7225 if (!tiff)
7227 image_error ("Cannot open memory source for `%s'", img->spec);
7228 return 0;
7232 image = image_spec_value (img->spec, QCindex, NULL);
7233 if (INTEGERP (image))
7235 EMACS_INT ino = XFASTINT (image);
7236 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7237 && TIFFSetDirectory (tiff, ino)))
7239 image_error ("Invalid image number `%s' in image `%s'",
7240 image, img->spec);
7241 TIFFClose (tiff);
7242 return 0;
7246 /* Get width and height of the image, and allocate a raster buffer
7247 of width x height 32-bit values. */
7248 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7249 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7251 if (!check_image_size (f, width, height))
7253 image_error ("Invalid image size (see `max-image-size')");
7254 TIFFClose (tiff);
7255 return 0;
7258 /* Create the X image and pixmap. */
7259 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7260 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7261 &ximg, 0)))
7263 TIFFClose (tiff);
7264 return 0;
7267 buf = xmalloc (sizeof *buf * width * height);
7269 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7271 /* Count the number of images in the file. */
7272 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7273 continue;
7275 if (count > 1)
7276 img->lisp_data = Fcons (Qcount,
7277 Fcons (make_number (count),
7278 img->lisp_data));
7280 TIFFClose (tiff);
7281 if (!rc)
7283 image_error ("Error reading TIFF image `%s'", img->spec);
7284 xfree (buf);
7285 return 0;
7288 #ifdef USE_CAIRO
7290 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
7291 uint32_t *dataptr = (uint32_t *) data;
7292 int r, g, b, a;
7294 for (y = 0; y < height; ++y)
7296 uint32 *row = buf + (height - 1 - y) * width;
7297 for (x = 0; x < width; ++x)
7299 uint32 abgr = row[x];
7300 int r = TIFFGetR (abgr);
7301 int g = TIFFGetG (abgr);
7302 int b = TIFFGetB (abgr);
7303 int a = TIFFGetA (abgr);
7304 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
7308 create_cairo_image_surface (img, data, width, height);
7310 #else
7311 /* Initialize the color table. */
7312 init_color_table ();
7314 /* Process the pixel raster. Origin is in the lower-left corner. */
7315 for (y = 0; y < height; ++y)
7317 uint32 *row = buf + y * width;
7319 for (x = 0; x < width; ++x)
7321 uint32 abgr = row[x];
7322 int r = TIFFGetR (abgr) << 8;
7323 int g = TIFFGetG (abgr) << 8;
7324 int b = TIFFGetB (abgr) << 8;
7325 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7329 # ifdef COLOR_TABLE_SUPPORT
7330 /* Remember the colors allocated for the image. Free the color table. */
7331 img->colors = colors_in_color_table (&img->ncolors);
7332 free_color_table ();
7333 # endif /* COLOR_TABLE_SUPPORT */
7335 img->width = width;
7336 img->height = height;
7338 /* Maybe fill in the background field while we have ximg handy. */
7339 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7340 /* Casting avoids a GCC warning on W32. */
7341 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7343 /* Put ximg into the image. */
7344 image_put_x_image (f, img, ximg, 0);
7346 #endif /* ! USE_CAIRO */
7348 xfree (buf);
7349 return 1;
7352 #elif defined HAVE_NS
7354 static bool
7355 tiff_load (struct frame *f, struct image *img)
7357 return ns_load_image (f, img,
7358 image_spec_value (img->spec, QCfile, NULL),
7359 image_spec_value (img->spec, QCdata, NULL));
7362 #endif
7366 /***********************************************************************
7368 ***********************************************************************/
7370 #if defined (HAVE_GIF) || defined (HAVE_NS)
7372 static bool gif_image_p (Lisp_Object object);
7373 static bool gif_load (struct frame *f, struct image *img);
7374 static void gif_clear_image (struct frame *f, struct image *img);
7376 /* Indices of image specification fields in gif_format, below. */
7378 enum gif_keyword_index
7380 GIF_TYPE,
7381 GIF_DATA,
7382 GIF_FILE,
7383 GIF_ASCENT,
7384 GIF_MARGIN,
7385 GIF_RELIEF,
7386 GIF_ALGORITHM,
7387 GIF_HEURISTIC_MASK,
7388 GIF_MASK,
7389 GIF_IMAGE,
7390 GIF_BACKGROUND,
7391 GIF_LAST
7394 /* Vector of image_keyword structures describing the format
7395 of valid user-defined image specifications. */
7397 static const struct image_keyword gif_format[GIF_LAST] =
7399 {":type", IMAGE_SYMBOL_VALUE, 1},
7400 {":data", IMAGE_STRING_VALUE, 0},
7401 {":file", IMAGE_STRING_VALUE, 0},
7402 {":ascent", IMAGE_ASCENT_VALUE, 0},
7403 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7404 {":relief", IMAGE_INTEGER_VALUE, 0},
7405 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7406 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7407 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7408 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7409 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7412 #if defined HAVE_NTGUI && defined WINDOWSNT
7413 static bool init_gif_functions (void);
7414 #else
7415 #define init_gif_functions NULL
7416 #endif
7418 /* Structure describing the image type `gif'. */
7420 static struct image_type gif_type =
7422 SYMBOL_INDEX (Qgif),
7423 gif_image_p,
7424 gif_load,
7425 gif_clear_image,
7426 init_gif_functions,
7427 NULL
7430 /* Free X resources of GIF image IMG which is used on frame F. */
7432 static void
7433 gif_clear_image (struct frame *f, struct image *img)
7435 img->lisp_data = Qnil;
7436 x_clear_image (f, img);
7439 /* Return true if OBJECT is a valid GIF image specification. */
7441 static bool
7442 gif_image_p (Lisp_Object object)
7444 struct image_keyword fmt[GIF_LAST];
7445 memcpy (fmt, gif_format, sizeof fmt);
7447 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7448 return 0;
7450 /* Must specify either the :data or :file keyword. */
7451 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7454 #endif /* HAVE_GIF */
7456 #ifdef HAVE_GIF
7458 # ifdef HAVE_NTGUI
7460 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7461 Undefine before redefining to avoid a preprocessor warning. */
7462 # ifdef DrawText
7463 # undef DrawText
7464 # endif
7465 /* avoid conflict with QuickdrawText.h */
7466 # define DrawText gif_DrawText
7467 # include <gif_lib.h>
7468 # undef DrawText
7470 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7471 # ifndef GIFLIB_MINOR
7472 # define GIFLIB_MINOR 0
7473 # endif
7474 # ifndef GIFLIB_RELEASE
7475 # define GIFLIB_RELEASE 0
7476 # endif
7478 # else /* HAVE_NTGUI */
7480 # include <gif_lib.h>
7482 # endif /* HAVE_NTGUI */
7484 /* Giflib before 5.0 didn't define these macros. */
7485 # ifndef GIFLIB_MAJOR
7486 # define GIFLIB_MAJOR 4
7487 # endif
7489 # ifdef WINDOWSNT
7491 /* GIF library details. */
7492 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7493 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7494 # else
7495 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7496 # endif
7497 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7498 # if GIFLIB_MAJOR < 5
7499 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7500 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7501 # else
7502 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7503 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7504 DEF_DLL_FN (char *, GifErrorString, (int));
7505 # endif
7507 static bool
7508 init_gif_functions (void)
7510 HMODULE library;
7512 if (!(library = w32_delayed_load (Qgif)))
7513 return 0;
7515 LOAD_DLL_FN (library, DGifCloseFile);
7516 LOAD_DLL_FN (library, DGifSlurp);
7517 LOAD_DLL_FN (library, DGifOpen);
7518 LOAD_DLL_FN (library, DGifOpenFileName);
7519 # if GIFLIB_MAJOR >= 5
7520 LOAD_DLL_FN (library, GifErrorString);
7521 # endif
7522 return 1;
7525 # undef DGifCloseFile
7526 # undef DGifOpen
7527 # undef DGifOpenFileName
7528 # undef DGifSlurp
7529 # undef GifErrorString
7531 # define DGifCloseFile fn_DGifCloseFile
7532 # define DGifOpen fn_DGifOpen
7533 # define DGifOpenFileName fn_DGifOpenFileName
7534 # define DGifSlurp fn_DGifSlurp
7535 # define GifErrorString fn_GifErrorString
7537 # endif /* WINDOWSNT */
7539 /* Reading a GIF image from memory
7540 Based on the PNG memory stuff to a certain extent. */
7542 typedef struct
7544 unsigned char *bytes;
7545 ptrdiff_t len;
7546 ptrdiff_t index;
7548 gif_memory_source;
7550 /* Make the current memory source available to gif_read_from_memory.
7551 It's done this way because not all versions of libungif support
7552 a UserData field in the GifFileType structure. */
7553 static gif_memory_source *current_gif_memory_src;
7555 static int
7556 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7558 gif_memory_source *src = current_gif_memory_src;
7560 if (len > src->len - src->index)
7561 return -1;
7563 memcpy (buf, src->bytes + src->index, len);
7564 src->index += len;
7565 return len;
7568 static int
7569 gif_close (GifFileType *gif, int *err)
7571 int retval;
7573 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7574 retval = DGifCloseFile (gif, err);
7575 #else
7576 retval = DGifCloseFile (gif);
7577 #if GIFLIB_MAJOR >= 5
7578 if (err)
7579 *err = gif->Error;
7580 #endif
7581 #endif
7582 return retval;
7585 /* Load GIF image IMG for use on frame F. Value is true if
7586 successful. */
7588 static const int interlace_start[] = {0, 4, 2, 1};
7589 static const int interlace_increment[] = {8, 8, 4, 2};
7591 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7593 static bool
7594 gif_load (struct frame *f, struct image *img)
7596 Lisp_Object file;
7597 int rc, width, height, x, y, i, j;
7598 ColorMapObject *gif_color_map;
7599 unsigned long pixel_colors[256];
7600 GifFileType *gif;
7601 gif_memory_source memsrc;
7602 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7603 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7604 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7605 unsigned long bgcolor = 0;
7606 EMACS_INT idx;
7607 int gif_err;
7609 #ifdef USE_CAIRO
7610 unsigned char *data = 0;
7611 #else
7612 XImagePtr ximg;
7613 #endif
7615 if (NILP (specified_data))
7617 file = x_find_image_file (specified_file);
7618 if (!STRINGP (file))
7620 image_error ("Cannot find image file `%s'", specified_file);
7621 return 0;
7623 #ifdef WINDOWSNT
7624 file = ansi_encode_filename (file);
7625 #endif
7627 /* Open the GIF file. */
7628 #if GIFLIB_MAJOR < 5
7629 gif = DGifOpenFileName (SSDATA (file));
7630 if (gif == NULL)
7632 image_error ("Cannot open `%s'", file);
7633 return 0;
7635 #else
7636 gif = DGifOpenFileName (SSDATA (file), &gif_err);
7637 if (gif == NULL)
7639 image_error ("Cannot open `%s': %s",
7640 file, build_string (GifErrorString (gif_err)));
7641 return 0;
7643 #endif
7645 else
7647 if (!STRINGP (specified_data))
7649 image_error ("Invalid image data `%s'", specified_data);
7650 return 0;
7653 /* Read from memory! */
7654 current_gif_memory_src = &memsrc;
7655 memsrc.bytes = SDATA (specified_data);
7656 memsrc.len = SBYTES (specified_data);
7657 memsrc.index = 0;
7659 #if GIFLIB_MAJOR < 5
7660 gif = DGifOpen (&memsrc, gif_read_from_memory);
7661 if (!gif)
7663 image_error ("Cannot open memory source `%s'", img->spec);
7664 return 0;
7666 #else
7667 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7668 if (!gif)
7670 image_error ("Cannot open memory source `%s': %s",
7671 img->spec, build_string (GifErrorString (gif_err)));
7672 return 0;
7674 #endif
7677 /* Before reading entire contents, check the declared image size. */
7678 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7680 image_error ("Invalid image size (see `max-image-size')");
7681 gif_close (gif, NULL);
7682 return 0;
7685 /* Read entire contents. */
7686 rc = DGifSlurp (gif);
7687 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7689 image_error ("Error reading `%s'", img->spec);
7690 gif_close (gif, NULL);
7691 return 0;
7694 /* Which sub-image are we to display? */
7696 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7697 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7698 if (idx < 0 || idx >= gif->ImageCount)
7700 image_error ("Invalid image number `%s' in image `%s'",
7701 image_number, img->spec);
7702 gif_close (gif, NULL);
7703 return 0;
7707 width = img->width = gif->SWidth;
7708 height = img->height = gif->SHeight;
7710 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7711 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7712 img->corners[BOT_CORNER]
7713 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7714 img->corners[RIGHT_CORNER]
7715 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7717 if (!check_image_size (f, width, height))
7719 image_error ("Invalid image size (see `max-image-size')");
7720 gif_close (gif, NULL);
7721 return 0;
7724 /* Check that the selected subimages fit. It's not clear whether
7725 the GIF spec requires this, but Emacs can crash if they don't fit. */
7726 for (j = 0; j <= idx; ++j)
7728 struct SavedImage *subimage = gif->SavedImages + j;
7729 int subimg_width = subimage->ImageDesc.Width;
7730 int subimg_height = subimage->ImageDesc.Height;
7731 int subimg_top = subimage->ImageDesc.Top;
7732 int subimg_left = subimage->ImageDesc.Left;
7733 if (! (subimg_width >= 0 && subimg_height >= 0
7734 && 0 <= subimg_top && subimg_top <= height - subimg_height
7735 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7737 image_error ("Subimage does not fit in image");
7738 gif_close (gif, NULL);
7739 return 0;
7743 #ifdef USE_CAIRO
7744 /* xzalloc so data is zero => transparent */
7745 data = (unsigned char *) xzalloc (width * height * 4);
7746 if (STRINGP (specified_bg))
7748 XColor color;
7749 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
7751 uint32_t *dataptr = (uint32_t *)data;
7752 int r = color.red/256;
7753 int g = color.green/256;
7754 int b = color.blue/256;
7756 for (y = 0; y < height; ++y)
7757 for (x = 0; x < width; ++x)
7758 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
7761 #else
7762 /* Create the X image and pixmap. */
7763 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7765 gif_close (gif, NULL);
7766 return 0;
7769 /* Clear the part of the screen image not covered by the image.
7770 Full animated GIF support requires more here (see the gif89 spec,
7771 disposal methods). Let's simply assume that the part not covered
7772 by a sub-image is in the frame's background color. */
7773 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7774 for (x = 0; x < width; ++x)
7775 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7777 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7778 for (x = 0; x < width; ++x)
7779 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7781 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7783 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7784 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7785 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7786 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7788 #endif
7790 /* Read the GIF image into the X image. */
7792 /* FIXME: With the current implementation, loading an animated gif
7793 is quadratic in the number of animation frames, since each frame
7794 is a separate struct image. We must provide a way for a single
7795 gif_load call to construct and save all animation frames. */
7797 init_color_table ();
7798 if (STRINGP (specified_bg))
7799 bgcolor = x_alloc_image_color (f, img, specified_bg,
7800 FRAME_BACKGROUND_PIXEL (f));
7801 for (j = 0; j <= idx; ++j)
7803 /* We use a local variable `raster' here because RasterBits is a
7804 char *, which invites problems with bytes >= 0x80. */
7805 struct SavedImage *subimage = gif->SavedImages + j;
7806 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7807 int transparency_color_index = -1;
7808 int disposal = 0;
7809 int subimg_width = subimage->ImageDesc.Width;
7810 int subimg_height = subimage->ImageDesc.Height;
7811 int subimg_top = subimage->ImageDesc.Top;
7812 int subimg_left = subimage->ImageDesc.Left;
7814 /* Find the Graphic Control Extension block for this sub-image.
7815 Extract the disposal method and transparency color. */
7816 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7818 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7820 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7821 && extblock->ByteCount == 4
7822 && extblock->Bytes[0] & 1)
7824 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7825 to background". Treat any other value like 2. */
7826 disposal = (extblock->Bytes[0] >> 2) & 7;
7827 transparency_color_index = (unsigned char) extblock->Bytes[3];
7828 break;
7832 /* We can't "keep in place" the first subimage. */
7833 if (j == 0)
7834 disposal = 2;
7836 /* For disposal == 0, the spec says "No disposal specified. The
7837 decoder is not required to take any action." In practice, it
7838 seems we need to treat this like "keep in place", see e.g.
7839 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7840 if (disposal == 0)
7841 disposal = 1;
7843 gif_color_map = subimage->ImageDesc.ColorMap;
7844 if (!gif_color_map)
7845 gif_color_map = gif->SColorMap;
7847 #ifndef USE_CAIRO
7848 /* Allocate subimage colors. */
7849 memset (pixel_colors, 0, sizeof pixel_colors);
7851 if (gif_color_map)
7852 for (i = 0; i < gif_color_map->ColorCount; ++i)
7854 if (transparency_color_index == i)
7855 pixel_colors[i] = STRINGP (specified_bg)
7856 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7857 else
7859 int r = gif_color_map->Colors[i].Red << 8;
7860 int g = gif_color_map->Colors[i].Green << 8;
7861 int b = gif_color_map->Colors[i].Blue << 8;
7862 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7865 #endif
7867 /* Apply the pixel values. */
7868 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7870 int row, pass;
7872 for (y = 0, row = interlace_start[0], pass = 0;
7873 y < subimg_height;
7874 y++, row += interlace_increment[pass])
7876 while (subimg_height <= row)
7877 row = interlace_start[++pass];
7879 for (x = 0; x < subimg_width; x++)
7881 int c = raster[y * subimg_width + x];
7882 if (transparency_color_index != c || disposal != 1)
7884 #ifdef USE_CAIRO
7885 uint32_t *dataptr =
7886 ((uint32_t*)data + ((row + subimg_top) * subimg_width
7887 + x + subimg_left));
7888 int r = gif_color_map->Colors[c].Red;
7889 int g = gif_color_map->Colors[c].Green;
7890 int b = gif_color_map->Colors[c].Blue;
7892 if (transparency_color_index != c)
7893 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7894 #else
7895 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7896 pixel_colors[c]);
7897 #endif
7902 else
7904 for (y = 0; y < subimg_height; ++y)
7905 for (x = 0; x < subimg_width; ++x)
7907 int c = raster[y * subimg_width + x];
7908 if (transparency_color_index != c || disposal != 1)
7910 #ifdef USE_CAIRO
7911 uint32_t *dataptr =
7912 ((uint32_t*)data + ((y + subimg_top) * subimg_width
7913 + x + subimg_left));
7914 int r = gif_color_map->Colors[c].Red;
7915 int g = gif_color_map->Colors[c].Green;
7916 int b = gif_color_map->Colors[c].Blue;
7917 if (transparency_color_index != c)
7918 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7919 #else
7920 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7921 pixel_colors[c]);
7922 #endif
7928 #ifdef COLOR_TABLE_SUPPORT
7929 img->colors = colors_in_color_table (&img->ncolors);
7930 free_color_table ();
7931 #endif /* COLOR_TABLE_SUPPORT */
7933 /* Save GIF image extension data for `image-metadata'.
7934 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7935 img->lisp_data = Qnil;
7936 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7938 int delay = 0;
7939 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7940 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7941 /* Append (... FUNCTION "BYTES") */
7943 img->lisp_data
7944 = Fcons (make_number (ext->Function),
7945 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7946 img->lisp_data));
7947 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7948 && ext->ByteCount == 4)
7950 delay = ext->Bytes[2] << CHAR_BIT;
7951 delay |= ext->Bytes[1];
7954 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7955 if (delay)
7956 img->lisp_data
7957 = Fcons (Qdelay,
7958 Fcons (make_float (delay / 100.0),
7959 img->lisp_data));
7962 if (gif->ImageCount > 1)
7963 img->lisp_data = Fcons (Qcount,
7964 Fcons (make_number (gif->ImageCount),
7965 img->lisp_data));
7967 if (gif_close (gif, &gif_err) == GIF_ERROR)
7969 #if 5 <= GIFLIB_MAJOR
7970 char *error_text = GifErrorString (gif_err);
7972 if (error_text)
7973 image_error ("Error closing `%s': %s",
7974 img->spec, build_string (error_text));
7975 #else
7976 image_error ("Error closing `%s'", img->spec);
7977 #endif
7980 #ifdef USE_CAIRO
7981 create_cairo_image_surface (img, data, width, height);
7982 #else
7983 /* Maybe fill in the background field while we have ximg handy. */
7984 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7985 /* Casting avoids a GCC warning. */
7986 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7988 /* Put ximg into the image. */
7989 image_put_x_image (f, img, ximg, 0);
7990 #endif
7992 return 1;
7995 #else /* !HAVE_GIF */
7997 #ifdef HAVE_NS
7998 static bool
7999 gif_load (struct frame *f, struct image *img)
8001 return ns_load_image (f, img,
8002 image_spec_value (img->spec, QCfile, NULL),
8003 image_spec_value (img->spec, QCdata, NULL));
8005 #endif /* HAVE_NS */
8007 #endif /* HAVE_GIF */
8010 #ifdef HAVE_IMAGEMAGICK
8012 /***********************************************************************
8013 ImageMagick
8014 ***********************************************************************/
8016 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8017 safely rounded and clipped to int range. */
8019 static int
8020 scale_image_size (int size, size_t divisor, size_t multiplier)
8022 if (divisor != 0)
8024 double s = size;
8025 double scaled = s * multiplier / divisor + 0.5;
8026 if (scaled < INT_MAX)
8027 return scaled;
8029 return INT_MAX;
8032 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8033 Use SPEC to deduce the size. Store the desired size into
8034 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8035 static void
8036 compute_image_size (size_t width, size_t height,
8037 Lisp_Object spec,
8038 int *d_width, int *d_height)
8040 Lisp_Object value;
8041 int desired_width, desired_height;
8043 /* If width and/or height is set in the display spec assume we want
8044 to scale to those values. If either h or w is unspecified, the
8045 unspecified should be calculated from the specified to preserve
8046 aspect ratio. */
8047 value = image_spec_value (spec, QCwidth, NULL);
8048 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8049 value = image_spec_value (spec, QCheight, NULL);
8050 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8052 if (desired_width == -1)
8054 value = image_spec_value (spec, QCmax_width, NULL);
8055 if (NATNUMP (value))
8057 int max_width = min (XFASTINT (value), INT_MAX);
8058 if (max_width < width)
8060 /* The image is wider than :max-width. */
8061 desired_width = max_width;
8062 if (desired_height == -1)
8064 desired_height = scale_image_size (desired_width,
8065 width, height);
8066 value = image_spec_value (spec, QCmax_height, NULL);
8067 if (NATNUMP (value))
8069 int max_height = min (XFASTINT (value), INT_MAX);
8070 if (max_height < desired_height)
8072 desired_height = max_height;
8073 desired_width = scale_image_size (desired_height,
8074 height, width);
8082 if (desired_height == -1)
8084 value = image_spec_value (spec, QCmax_height, NULL);
8085 if (NATNUMP (value))
8087 int max_height = min (XFASTINT (value), INT_MAX);
8088 if (max_height < height)
8089 desired_height = max_height;
8093 if (desired_width != -1 && desired_height == -1)
8094 /* w known, calculate h. */
8095 desired_height = scale_image_size (desired_width, width, height);
8097 if (desired_width == -1 && desired_height != -1)
8098 /* h known, calculate w. */
8099 desired_width = scale_image_size (desired_height, height, width);
8101 *d_width = desired_width;
8102 *d_height = desired_height;
8105 static bool imagemagick_image_p (Lisp_Object);
8106 static bool imagemagick_load (struct frame *, struct image *);
8107 static void imagemagick_clear_image (struct frame *, struct image *);
8109 /* Indices of image specification fields in imagemagick_format. */
8111 enum imagemagick_keyword_index
8113 IMAGEMAGICK_TYPE,
8114 IMAGEMAGICK_DATA,
8115 IMAGEMAGICK_FILE,
8116 IMAGEMAGICK_ASCENT,
8117 IMAGEMAGICK_MARGIN,
8118 IMAGEMAGICK_RELIEF,
8119 IMAGEMAGICK_ALGORITHM,
8120 IMAGEMAGICK_HEURISTIC_MASK,
8121 IMAGEMAGICK_MASK,
8122 IMAGEMAGICK_BACKGROUND,
8123 IMAGEMAGICK_HEIGHT,
8124 IMAGEMAGICK_WIDTH,
8125 IMAGEMAGICK_MAX_HEIGHT,
8126 IMAGEMAGICK_MAX_WIDTH,
8127 IMAGEMAGICK_FORMAT,
8128 IMAGEMAGICK_ROTATION,
8129 IMAGEMAGICK_CROP,
8130 IMAGEMAGICK_LAST
8133 /* Vector of image_keyword structures describing the format
8134 of valid user-defined image specifications. */
8136 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
8138 {":type", IMAGE_SYMBOL_VALUE, 1},
8139 {":data", IMAGE_STRING_VALUE, 0},
8140 {":file", IMAGE_STRING_VALUE, 0},
8141 {":ascent", IMAGE_ASCENT_VALUE, 0},
8142 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8143 {":relief", IMAGE_INTEGER_VALUE, 0},
8144 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8145 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8146 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8147 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8148 {":height", IMAGE_INTEGER_VALUE, 0},
8149 {":width", IMAGE_INTEGER_VALUE, 0},
8150 {":max-height", IMAGE_INTEGER_VALUE, 0},
8151 {":max-width", IMAGE_INTEGER_VALUE, 0},
8152 {":format", IMAGE_SYMBOL_VALUE, 0},
8153 {":rotation", IMAGE_NUMBER_VALUE, 0},
8154 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8157 #if defined HAVE_NTGUI && defined WINDOWSNT
8158 static bool init_imagemagick_functions (void);
8159 #else
8160 #define init_imagemagick_functions NULL
8161 #endif
8163 /* Structure describing the image type for any image handled via
8164 ImageMagick. */
8166 static struct image_type imagemagick_type =
8168 SYMBOL_INDEX (Qimagemagick),
8169 imagemagick_image_p,
8170 imagemagick_load,
8171 imagemagick_clear_image,
8172 init_imagemagick_functions,
8173 NULL
8176 /* Free X resources of imagemagick image IMG which is used on frame F. */
8178 static void
8179 imagemagick_clear_image (struct frame *f,
8180 struct image *img)
8182 x_clear_image (f, img);
8185 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8186 this by calling parse_image_spec and supplying the keywords that
8187 identify the IMAGEMAGICK format. */
8189 static bool
8190 imagemagick_image_p (Lisp_Object object)
8192 struct image_keyword fmt[IMAGEMAGICK_LAST];
8193 memcpy (fmt, imagemagick_format, sizeof fmt);
8195 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
8196 return 0;
8198 /* Must specify either the :data or :file keyword. */
8199 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
8202 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8203 Therefore rename the function so it doesn't collide with ImageMagick. */
8204 #define DrawRectangle DrawRectangleGif
8205 #include <wand/MagickWand.h>
8207 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8208 Emacs seems to work fine with the hidden version, so unhide it. */
8209 #include <magick/version.h>
8210 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8211 extern WandExport void PixelGetMagickColor (const PixelWand *,
8212 MagickPixelPacket *);
8213 #endif
8215 /* Log ImageMagick error message.
8216 Useful when a ImageMagick function returns the status `MagickFalse'. */
8218 static void
8219 imagemagick_error (MagickWand *wand)
8221 char *description;
8222 ExceptionType severity;
8224 description = MagickGetException (wand, &severity);
8225 image_error ("ImageMagick error: %s", build_string (description));
8226 MagickRelinquishMemory (description);
8229 /* Possibly give ImageMagick some extra help to determine the image
8230 type by supplying a "dummy" filename based on the Content-Type. */
8232 static char *
8233 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
8235 Lisp_Object symbol = intern ("image-format-suffixes");
8236 Lisp_Object val = find_symbol_value (symbol);
8237 Lisp_Object format;
8239 if (! CONSP (val))
8240 return NULL;
8242 format = image_spec_value (spec, intern (":format"), NULL);
8243 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
8244 if (! STRINGP (val))
8245 return NULL;
8247 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8248 as ImageMagick would ignore the extra bytes anyway. */
8249 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
8250 return hint_buffer;
8253 /* Animated images (e.g., GIF89a) are composed from one "master image"
8254 (which is the first one, and then there's a number of images that
8255 follow. If following images have non-transparent colors, these are
8256 composed "on top" of the master image. So, in general, one has to
8257 compute ann the preceding images to be able to display a particular
8258 sub-image.
8260 Computing all the preceding images is too slow, so we maintain a
8261 cache of previously computed images. We have to maintain a cache
8262 separate from the image cache, because the images may be scaled
8263 before display. */
8265 struct animation_cache
8267 MagickWand *wand;
8268 int index;
8269 struct timespec update_time;
8270 struct animation_cache *next;
8271 char signature[FLEXIBLE_ARRAY_MEMBER];
8274 static struct animation_cache *animation_cache = NULL;
8276 static struct animation_cache *
8277 imagemagick_create_cache (char *signature)
8279 struct animation_cache *cache
8280 = xmalloc (offsetof (struct animation_cache, signature)
8281 + strlen (signature) + 1);
8282 cache->wand = 0;
8283 cache->index = 0;
8284 cache->next = 0;
8285 strcpy (cache->signature, signature);
8286 return cache;
8289 /* Discard cached images that haven't been used for a minute. */
8290 static void
8291 imagemagick_prune_animation_cache (void)
8293 struct animation_cache **pcache = &animation_cache;
8294 struct timespec old = timespec_sub (current_timespec (),
8295 make_timespec (60, 0));
8297 while (*pcache)
8299 struct animation_cache *cache = *pcache;
8300 if (timespec_cmp (old, cache->update_time) <= 0)
8301 pcache = &cache->next;
8302 else
8304 if (cache->wand)
8305 DestroyMagickWand (cache->wand);
8306 *pcache = cache->next;
8307 xfree (cache);
8312 static struct animation_cache *
8313 imagemagick_get_animation_cache (MagickWand *wand)
8315 char *signature = MagickGetImageSignature (wand);
8316 struct animation_cache *cache;
8317 struct animation_cache **pcache = &animation_cache;
8319 imagemagick_prune_animation_cache ();
8321 while (1)
8323 cache = *pcache;
8324 if (! cache)
8326 *pcache = cache = imagemagick_create_cache (signature);
8327 break;
8329 if (strcmp (signature, cache->signature) == 0)
8330 break;
8331 pcache = &cache->next;
8334 DestroyString (signature);
8335 cache->update_time = current_timespec ();
8336 return cache;
8339 static MagickWand *
8340 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8342 int i;
8343 MagickWand *composite_wand;
8344 size_t dest_width, dest_height;
8345 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8347 MagickSetIteratorIndex (super_wand, 0);
8349 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8351 composite_wand = MagickGetImage (super_wand);
8352 if (cache->wand)
8353 DestroyMagickWand (cache->wand);
8355 else
8356 composite_wand = cache->wand;
8358 dest_height = MagickGetImageHeight (composite_wand);
8360 for (i = max (1, cache->index + 1); i <= ino; i++)
8362 MagickWand *sub_wand;
8363 PixelIterator *source_iterator, *dest_iterator;
8364 PixelWand **source, **dest;
8365 size_t source_width, source_height;
8366 ssize_t source_left, source_top;
8367 MagickPixelPacket pixel;
8368 DisposeType dispose;
8369 ptrdiff_t lines = 0;
8371 MagickSetIteratorIndex (super_wand, i);
8372 sub_wand = MagickGetImage (super_wand);
8374 MagickGetImagePage (sub_wand, &source_width, &source_height,
8375 &source_left, &source_top);
8377 /* This flag says how to handle transparent pixels. */
8378 dispose = MagickGetImageDispose (sub_wand);
8380 source_iterator = NewPixelIterator (sub_wand);
8381 if (! source_iterator)
8383 DestroyMagickWand (composite_wand);
8384 DestroyMagickWand (sub_wand);
8385 cache->wand = NULL;
8386 image_error ("Imagemagick pixel iterator creation failed");
8387 return NULL;
8390 dest_iterator = NewPixelIterator (composite_wand);
8391 if (! dest_iterator)
8393 DestroyMagickWand (composite_wand);
8394 DestroyMagickWand (sub_wand);
8395 DestroyPixelIterator (source_iterator);
8396 cache->wand = NULL;
8397 image_error ("Imagemagick pixel iterator creation failed");
8398 return NULL;
8401 /* The sub-image may not start at origin, so move the destination
8402 iterator to where the sub-image should start. */
8403 if (source_top > 0)
8405 PixelSetIteratorRow (dest_iterator, source_top);
8406 lines = source_top;
8409 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8410 != NULL)
8412 ptrdiff_t x;
8414 /* Sanity check. This shouldn't happen, but apparently
8415 does in some pictures. */
8416 if (++lines >= dest_height)
8417 break;
8419 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8420 for (x = 0; x < source_width; x++)
8422 /* Sanity check. This shouldn't happen, but apparently
8423 also does in some pictures. */
8424 if (x + source_left >= dest_width)
8425 break;
8426 /* Normally we only copy over non-transparent pixels,
8427 but if the disposal method is "Background", then we
8428 copy over all pixels. */
8429 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8431 PixelGetMagickColor (source[x], &pixel);
8432 PixelSetMagickColor (dest[x + source_left], &pixel);
8435 PixelSyncIterator (dest_iterator);
8438 DestroyPixelIterator (source_iterator);
8439 DestroyPixelIterator (dest_iterator);
8440 DestroyMagickWand (sub_wand);
8443 /* Cache a copy for the next iteration. The current wand will be
8444 destroyed by the caller. */
8445 cache->wand = CloneMagickWand (composite_wand);
8446 cache->index = ino;
8448 return composite_wand;
8452 /* Helper function for imagemagick_load, which does the actual loading
8453 given contents and size, apart from frame and image structures,
8454 passed from imagemagick_load. Uses librimagemagick to do most of
8455 the image processing.
8457 F is a pointer to the Emacs frame; IMG to the image structure to
8458 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8459 be parsed; SIZE is the number of bytes of data; and FILENAME is
8460 either the file name or the image data.
8462 Return true if successful. */
8464 static bool
8465 imagemagick_load_image (struct frame *f, struct image *img,
8466 unsigned char *contents, unsigned int size,
8467 char *filename)
8469 int width, height;
8470 size_t image_width, image_height;
8471 MagickBooleanType status;
8472 XImagePtr ximg;
8473 int x, y;
8474 MagickWand *image_wand;
8475 PixelIterator *iterator;
8476 PixelWand **pixels, *bg_wand = NULL;
8477 MagickPixelPacket pixel;
8478 Lisp_Object image;
8479 Lisp_Object value;
8480 Lisp_Object crop;
8481 EMACS_INT ino;
8482 int desired_width, desired_height;
8483 double rotation;
8484 int pixelwidth;
8485 char hint_buffer[MaxTextExtent];
8486 char *filename_hint = NULL;
8488 /* Handle image index for image types who can contain more than one image.
8489 Interface :index is same as for GIF. First we "ping" the image to see how
8490 many sub-images it contains. Pinging is faster than loading the image to
8491 find out things about it. */
8493 /* Initialize the imagemagick environment. */
8494 MagickWandGenesis ();
8495 image = image_spec_value (img->spec, QCindex, NULL);
8496 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8497 image_wand = NewMagickWand ();
8499 if (filename)
8500 status = MagickReadImage (image_wand, filename);
8501 else
8503 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8504 MagickSetFilename (image_wand, filename_hint);
8505 status = MagickReadImageBlob (image_wand, contents, size);
8508 if (status == MagickFalse)
8510 imagemagick_error (image_wand);
8511 DestroyMagickWand (image_wand);
8512 return 0;
8515 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8517 image_error ("Invalid image number `%s' in image `%s'",
8518 image, img->spec);
8519 DestroyMagickWand (image_wand);
8520 return 0;
8523 if (MagickGetImageDelay (image_wand) > 0)
8524 img->lisp_data =
8525 Fcons (Qdelay,
8526 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8527 img->lisp_data));
8529 if (MagickGetNumberImages (image_wand) > 1)
8530 img->lisp_data =
8531 Fcons (Qcount,
8532 Fcons (make_number (MagickGetNumberImages (image_wand)),
8533 img->lisp_data));
8535 /* If we have an animated image, get the new wand based on the
8536 "super-wand". */
8537 if (MagickGetNumberImages (image_wand) > 1)
8539 MagickWand *super_wand = image_wand;
8540 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8541 if (! image_wand)
8542 image_wand = super_wand;
8543 else
8544 DestroyMagickWand (super_wand);
8547 /* Retrieve the frame's background color, for use later. */
8549 XColor bgcolor;
8550 Lisp_Object specified_bg;
8552 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8553 if (!STRINGP (specified_bg)
8554 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8555 x_query_frame_background_color (f, &bgcolor);
8557 bg_wand = NewPixelWand ();
8558 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8559 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8560 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8563 compute_image_size (MagickGetImageWidth (image_wand),
8564 MagickGetImageHeight (image_wand),
8565 img->spec, &desired_width, &desired_height);
8567 if (desired_width != -1 && desired_height != -1)
8569 status = MagickScaleImage (image_wand, desired_width, desired_height);
8570 if (status == MagickFalse)
8572 image_error ("Imagemagick scale failed");
8573 imagemagick_error (image_wand);
8574 goto imagemagick_error;
8578 /* crop behaves similar to image slicing in Emacs but is more memory
8579 efficient. */
8580 crop = image_spec_value (img->spec, QCcrop, NULL);
8582 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8584 /* After some testing, it seems MagickCropImage is the fastest crop
8585 function in ImageMagick. This crop function seems to do less copying
8586 than the alternatives, but it still reads the entire image into memory
8587 before cropping, which is apparently difficult to avoid when using
8588 imagemagick. */
8589 size_t crop_width = XINT (XCAR (crop));
8590 crop = XCDR (crop);
8591 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8593 size_t crop_height = XINT (XCAR (crop));
8594 crop = XCDR (crop);
8595 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8597 ssize_t crop_x = XINT (XCAR (crop));
8598 crop = XCDR (crop);
8599 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8601 ssize_t crop_y = XINT (XCAR (crop));
8602 MagickCropImage (image_wand, crop_width, crop_height,
8603 crop_x, crop_y);
8609 /* Furthermore :rotation. we need background color and angle for
8610 rotation. */
8612 TODO background handling for rotation specified_bg =
8613 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8614 (specified_bg). */
8615 value = image_spec_value (img->spec, QCrotation, NULL);
8616 if (FLOATP (value))
8618 rotation = extract_float (value);
8619 status = MagickRotateImage (image_wand, bg_wand, rotation);
8620 if (status == MagickFalse)
8622 image_error ("Imagemagick image rotate failed");
8623 imagemagick_error (image_wand);
8624 goto imagemagick_error;
8628 /* Set the canvas background color to the frame or specified
8629 background, and flatten the image. Note: as of ImageMagick
8630 6.6.0, SVG image transparency is not handled properly
8631 (e.g. etc/images/splash.svg shows a white background always). */
8633 MagickWand *new_wand;
8634 MagickSetImageBackgroundColor (image_wand, bg_wand);
8635 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8636 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8637 #else
8638 new_wand = MagickFlattenImages (image_wand);
8639 #endif
8640 DestroyMagickWand (image_wand);
8641 image_wand = new_wand;
8644 /* Finally we are done manipulating the image. Figure out the
8645 resulting width/height and transfer ownership to Emacs. */
8646 image_height = MagickGetImageHeight (image_wand);
8647 image_width = MagickGetImageWidth (image_wand);
8649 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8650 && check_image_size (f, image_width, image_height)))
8652 image_error ("Invalid image size (see `max-image-size')");
8653 goto imagemagick_error;
8656 width = image_width;
8657 height = image_height;
8659 /* We can now get a valid pixel buffer from the imagemagick file, if all
8660 went ok. */
8662 init_color_table ();
8664 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8665 if (imagemagick_render_type != 0)
8667 /* Magicexportimage is normally faster than pixelpushing. This
8668 method is also well tested. Some aspects of this method are
8669 ad-hoc and needs to be more researched. */
8670 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8671 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8672 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8673 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8674 &ximg, 0))
8676 #ifdef COLOR_TABLE_SUPPORT
8677 free_color_table ();
8678 #endif
8679 image_error ("Imagemagick X bitmap allocation failure");
8680 goto imagemagick_error;
8683 /* Oddly, the below code doesn't seem to work:*/
8684 /* switch(ximg->bitmap_unit){ */
8685 /* case 8: */
8686 /* pixelwidth=CharPixel; */
8687 /* break; */
8688 /* case 16: */
8689 /* pixelwidth=ShortPixel; */
8690 /* break; */
8691 /* case 32: */
8692 /* pixelwidth=LongPixel; */
8693 /* break; */
8694 /* } */
8696 Here im just guessing the format of the bitmap.
8697 happens to work fine for:
8698 - bw djvu images
8699 on rgb display.
8700 seems about 3 times as fast as pixel pushing(not carefully measured)
8702 pixelwidth = CharPixel; /*??? TODO figure out*/
8703 MagickExportImagePixels (image_wand, 0, 0, width, height,
8704 exportdepth, pixelwidth, ximg->data);
8706 else
8707 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8709 size_t image_height;
8710 MagickRealType color_scale = 65535.0 / QuantumRange;
8712 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8713 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8714 &ximg, 0))
8716 #ifdef COLOR_TABLE_SUPPORT
8717 free_color_table ();
8718 #endif
8719 image_error ("Imagemagick X bitmap allocation failure");
8720 goto imagemagick_error;
8723 /* Copy imagemagick image to x with primitive yet robust pixel
8724 pusher loop. This has been tested a lot with many different
8725 images. */
8727 /* Copy pixels from the imagemagick image structure to the x image map. */
8728 iterator = NewPixelIterator (image_wand);
8729 if (! iterator)
8731 #ifdef COLOR_TABLE_SUPPORT
8732 free_color_table ();
8733 #endif
8734 x_destroy_x_image (ximg);
8735 image_error ("Imagemagick pixel iterator creation failed");
8736 goto imagemagick_error;
8739 image_height = MagickGetImageHeight (image_wand);
8740 for (y = 0; y < image_height; y++)
8742 size_t row_width;
8743 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8744 if (! pixels)
8745 break;
8746 int xlim = min (row_width, width);
8747 for (x = 0; x < xlim; x++)
8749 PixelGetMagickColor (pixels[x], &pixel);
8750 XPutPixel (ximg, x, y,
8751 lookup_rgb_color (f,
8752 color_scale * pixel.red,
8753 color_scale * pixel.green,
8754 color_scale * pixel.blue));
8757 DestroyPixelIterator (iterator);
8760 #ifdef COLOR_TABLE_SUPPORT
8761 /* Remember colors allocated for this image. */
8762 img->colors = colors_in_color_table (&img->ncolors);
8763 free_color_table ();
8764 #endif /* COLOR_TABLE_SUPPORT */
8766 img->width = width;
8767 img->height = height;
8769 /* Put ximg into the image. */
8770 image_put_x_image (f, img, ximg, 0);
8772 /* Final cleanup. image_wand should be the only resource left. */
8773 DestroyMagickWand (image_wand);
8774 if (bg_wand) DestroyPixelWand (bg_wand);
8776 /* `MagickWandTerminus' terminates the imagemagick environment. */
8777 MagickWandTerminus ();
8779 return 1;
8781 imagemagick_error:
8782 DestroyMagickWand (image_wand);
8783 if (bg_wand) DestroyPixelWand (bg_wand);
8785 MagickWandTerminus ();
8786 /* TODO more cleanup. */
8787 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec);
8788 return 0;
8792 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8793 successful. this function will go into the imagemagick_type structure, and
8794 the prototype thus needs to be compatible with that structure. */
8796 static bool
8797 imagemagick_load (struct frame *f, struct image *img)
8799 bool success_p = 0;
8800 Lisp_Object file_name;
8802 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8803 file_name = image_spec_value (img->spec, QCfile, NULL);
8804 if (STRINGP (file_name))
8806 Lisp_Object file;
8808 file = x_find_image_file (file_name);
8809 if (!STRINGP (file))
8811 image_error ("Cannot find image file `%s'", file_name);
8812 return 0;
8814 #ifdef WINDOWSNT
8815 file = ansi_encode_filename (file);
8816 #endif
8817 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8819 /* Else its not a file, its a lisp object. Load the image from a
8820 lisp object rather than a file. */
8821 else
8823 Lisp_Object data;
8825 data = image_spec_value (img->spec, QCdata, NULL);
8826 if (!STRINGP (data))
8828 image_error ("Invalid image data `%s'", data);
8829 return 0;
8831 success_p = imagemagick_load_image (f, img, SDATA (data),
8832 SBYTES (data), NULL);
8835 return success_p;
8838 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8839 doc: /* Return a list of image types supported by ImageMagick.
8840 Each entry in this list is a symbol named after an ImageMagick format
8841 tag. See the ImageMagick manual for a list of ImageMagick formats and
8842 their descriptions (http://www.imagemagick.org/script/formats.php).
8843 You can also try the shell command: `identify -list format'.
8845 Note that ImageMagick recognizes many file-types that Emacs does not
8846 recognize as images, such as C. See `imagemagick-types-enable'
8847 and `imagemagick-types-inhibit'. */)
8848 (void)
8850 Lisp_Object typelist = Qnil;
8851 size_t numf = 0;
8852 ExceptionInfo ex;
8853 char **imtypes;
8854 size_t i;
8856 GetExceptionInfo(&ex);
8857 imtypes = GetMagickList ("*", &numf, &ex);
8858 DestroyExceptionInfo(&ex);
8860 for (i = 0; i < numf; i++)
8862 Lisp_Object imagemagicktype = intern (imtypes[i]);
8863 typelist = Fcons (imagemagicktype, typelist);
8864 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8867 MagickRelinquishMemory (imtypes);
8868 return Fnreverse (typelist);
8871 #endif /* defined (HAVE_IMAGEMAGICK) */
8875 /***********************************************************************
8877 ***********************************************************************/
8879 #ifdef HAVE_RSVG
8881 /* Function prototypes. */
8883 static bool svg_image_p (Lisp_Object object);
8884 static bool svg_load (struct frame *f, struct image *img);
8886 static bool svg_load_image (struct frame *, struct image *,
8887 unsigned char *, ptrdiff_t, char *);
8889 /* Indices of image specification fields in svg_format, below. */
8891 enum svg_keyword_index
8893 SVG_TYPE,
8894 SVG_DATA,
8895 SVG_FILE,
8896 SVG_ASCENT,
8897 SVG_MARGIN,
8898 SVG_RELIEF,
8899 SVG_ALGORITHM,
8900 SVG_HEURISTIC_MASK,
8901 SVG_MASK,
8902 SVG_BACKGROUND,
8903 SVG_LAST
8906 /* Vector of image_keyword structures describing the format
8907 of valid user-defined image specifications. */
8909 static const struct image_keyword svg_format[SVG_LAST] =
8911 {":type", IMAGE_SYMBOL_VALUE, 1},
8912 {":data", IMAGE_STRING_VALUE, 0},
8913 {":file", IMAGE_STRING_VALUE, 0},
8914 {":ascent", IMAGE_ASCENT_VALUE, 0},
8915 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8916 {":relief", IMAGE_INTEGER_VALUE, 0},
8917 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8918 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8919 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8920 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8923 # if defined HAVE_NTGUI && defined WINDOWSNT
8924 static bool init_svg_functions (void);
8925 # else
8926 #define init_svg_functions NULL
8927 # endif
8929 /* Structure describing the image type `svg'. Its the same type of
8930 structure defined for all image formats, handled by emacs image
8931 functions. See struct image_type in dispextern.h. */
8933 static struct image_type svg_type =
8935 SYMBOL_INDEX (Qsvg),
8936 svg_image_p,
8937 svg_load,
8938 x_clear_image,
8939 init_svg_functions,
8940 NULL
8944 /* Return true if OBJECT is a valid SVG image specification. Do
8945 this by calling parse_image_spec and supplying the keywords that
8946 identify the SVG format. */
8948 static bool
8949 svg_image_p (Lisp_Object object)
8951 struct image_keyword fmt[SVG_LAST];
8952 memcpy (fmt, svg_format, sizeof fmt);
8954 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8955 return 0;
8957 /* Must specify either the :data or :file keyword. */
8958 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8961 # include <librsvg/rsvg.h>
8963 # ifdef WINDOWSNT
8965 /* SVG library functions. */
8966 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
8967 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
8968 (RsvgHandle *, RsvgDimensionData *));
8969 DEF_DLL_FN (gboolean, rsvg_handle_write,
8970 (RsvgHandle *, const guchar *, gsize, GError **));
8971 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8972 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8973 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
8975 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8976 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8977 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8978 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8979 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8980 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8981 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8982 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8984 # if ! GLIB_CHECK_VERSION (2, 36, 0)
8985 DEF_DLL_FN (void, g_type_init, (void));
8986 # endif
8987 DEF_DLL_FN (void, g_object_unref, (gpointer));
8988 DEF_DLL_FN (void, g_error_free, (GError *));
8990 static bool
8991 init_svg_functions (void)
8993 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
8995 if (!(glib = w32_delayed_load (Qglib))
8996 || !(gobject = w32_delayed_load (Qgobject))
8997 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
8998 || !(library = w32_delayed_load (Qsvg)))
9000 if (gdklib) FreeLibrary (gdklib);
9001 if (gobject) FreeLibrary (gobject);
9002 if (glib) FreeLibrary (glib);
9003 return 0;
9006 LOAD_DLL_FN (library, rsvg_handle_new);
9007 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
9008 LOAD_DLL_FN (library, rsvg_handle_write);
9009 LOAD_DLL_FN (library, rsvg_handle_close);
9010 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
9011 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
9013 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
9014 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
9015 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
9016 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
9017 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
9018 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
9019 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
9020 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
9022 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9023 LOAD_DLL_FN (gobject, g_type_init);
9024 # endif
9025 LOAD_DLL_FN (gobject, g_object_unref);
9026 LOAD_DLL_FN (glib, g_error_free);
9028 return 1;
9031 /* The following aliases for library functions allow dynamic loading
9032 to be used on some platforms. */
9034 # undef gdk_pixbuf_get_bits_per_sample
9035 # undef gdk_pixbuf_get_colorspace
9036 # undef gdk_pixbuf_get_has_alpha
9037 # undef gdk_pixbuf_get_height
9038 # undef gdk_pixbuf_get_n_channels
9039 # undef gdk_pixbuf_get_pixels
9040 # undef gdk_pixbuf_get_rowstride
9041 # undef gdk_pixbuf_get_width
9042 # undef g_error_free
9043 # undef g_object_unref
9044 # undef g_type_init
9045 # undef rsvg_handle_close
9046 # undef rsvg_handle_get_dimensions
9047 # undef rsvg_handle_get_pixbuf
9048 # undef rsvg_handle_new
9049 # undef rsvg_handle_set_base_uri
9050 # undef rsvg_handle_write
9052 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9053 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9054 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9055 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9056 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9057 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9058 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9059 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9060 # define g_error_free fn_g_error_free
9061 # define g_object_unref fn_g_object_unref
9062 # define g_type_init fn_g_type_init
9063 # define rsvg_handle_close fn_rsvg_handle_close
9064 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9065 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9066 # define rsvg_handle_new fn_rsvg_handle_new
9067 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9068 # define rsvg_handle_write fn_rsvg_handle_write
9070 # endif /* !WINDOWSNT */
9072 /* Load SVG image IMG for use on frame F. Value is true if
9073 successful. */
9075 static bool
9076 svg_load (struct frame *f, struct image *img)
9078 bool success_p = 0;
9079 Lisp_Object file_name;
9081 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9082 file_name = image_spec_value (img->spec, QCfile, NULL);
9083 if (STRINGP (file_name))
9085 Lisp_Object file;
9086 unsigned char *contents;
9087 ptrdiff_t size;
9089 file = x_find_image_file (file_name);
9090 if (!STRINGP (file))
9092 image_error ("Cannot find image file `%s'", file_name);
9093 return 0;
9096 /* Read the entire file into memory. */
9097 contents = slurp_file (SSDATA (file), &size);
9098 if (contents == NULL)
9100 image_error ("Error loading SVG image `%s'", img->spec);
9101 return 0;
9103 /* If the file was slurped into memory properly, parse it. */
9104 success_p = svg_load_image (f, img, contents, size, SSDATA (file));
9105 xfree (contents);
9107 /* Else its not a file, its a lisp object. Load the image from a
9108 lisp object rather than a file. */
9109 else
9111 Lisp_Object data, original_filename;
9113 data = image_spec_value (img->spec, QCdata, NULL);
9114 if (!STRINGP (data))
9116 image_error ("Invalid image data `%s'", data);
9117 return 0;
9119 original_filename = BVAR (current_buffer, filename);
9120 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data),
9121 (NILP (original_filename) ? NULL
9122 : SSDATA (original_filename)));
9125 return success_p;
9128 /* svg_load_image is a helper function for svg_load, which does the
9129 actual loading given contents and size, apart from frame and image
9130 structures, passed from svg_load.
9132 Uses librsvg to do most of the image processing.
9134 Returns true when successful. */
9135 static bool
9136 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
9137 struct image *img, /* Pointer to emacs image structure. */
9138 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
9139 ptrdiff_t size, /* Size of data in bytes. */
9140 char *filename) /* Name of SVG file being loaded. */
9142 RsvgHandle *rsvg_handle;
9143 RsvgDimensionData dimension_data;
9144 GError *err = NULL;
9145 GdkPixbuf *pixbuf;
9146 int width;
9147 int height;
9148 const guint8 *pixels;
9149 int rowstride;
9150 XImagePtr ximg;
9151 Lisp_Object specified_bg;
9152 XColor background;
9153 int x;
9154 int y;
9156 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9157 /* g_type_init is a glib function that must be called prior to
9158 using gnome type library functions (obsolete since 2.36.0). */
9159 g_type_init ();
9160 #endif
9162 /* Make a handle to a new rsvg object. */
9163 rsvg_handle = rsvg_handle_new ();
9165 /* Set base_uri for properly handling referenced images (via 'href').
9166 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9167 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9168 if (filename)
9169 rsvg_handle_set_base_uri(rsvg_handle, filename);
9171 /* Parse the contents argument and fill in the rsvg_handle. */
9172 rsvg_handle_write (rsvg_handle, contents, size, &err);
9173 if (err) goto rsvg_error;
9175 /* The parsing is complete, rsvg_handle is ready to used, close it
9176 for further writes. */
9177 rsvg_handle_close (rsvg_handle, &err);
9178 if (err) goto rsvg_error;
9180 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
9181 if (! check_image_size (f, dimension_data.width, dimension_data.height))
9183 image_error ("Invalid image size (see `max-image-size')");
9184 goto rsvg_error;
9187 /* We can now get a valid pixel buffer from the svg file, if all
9188 went ok. */
9189 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
9190 if (!pixbuf) goto rsvg_error;
9191 g_object_unref (rsvg_handle);
9193 /* Extract some meta data from the svg handle. */
9194 width = gdk_pixbuf_get_width (pixbuf);
9195 height = gdk_pixbuf_get_height (pixbuf);
9196 pixels = gdk_pixbuf_get_pixels (pixbuf);
9197 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
9199 /* Validate the svg meta data. */
9200 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
9201 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
9202 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
9203 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
9205 #ifdef USE_CAIRO
9207 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
9208 int y;
9209 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
9211 for (y = 0; y < height; ++y)
9213 const guchar *iconptr = pixels + y * rowstride;
9214 uint32_t *dataptr = (uint32_t *) (data + y * rowstride);
9215 int x;
9217 for (x = 0; x < width; ++x)
9219 if (iconptr[3] == 0)
9220 *dataptr = bgcolor;
9221 else
9222 *dataptr = (iconptr[0] << 16)
9223 | (iconptr[1] << 8)
9224 | iconptr[2]
9225 | (iconptr[3] << 24);
9227 iconptr += 4;
9228 ++dataptr;
9232 create_cairo_image_surface (img, data, width, height);
9233 g_object_unref (pixbuf);
9235 #else
9236 /* Try to create a x pixmap to hold the svg pixmap. */
9237 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
9239 g_object_unref (pixbuf);
9240 return 0;
9243 init_color_table ();
9245 /* Handle alpha channel by combining the image with a background
9246 color. */
9247 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
9248 if (!STRINGP (specified_bg)
9249 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
9250 x_query_frame_background_color (f, &background);
9252 /* SVG pixmaps specify transparency in the last byte, so right
9253 shift 8 bits to get rid of it, since emacs doesn't support
9254 transparency. */
9255 background.red >>= 8;
9256 background.green >>= 8;
9257 background.blue >>= 8;
9259 /* This loop handles opacity values, since Emacs assumes
9260 non-transparent images. Each pixel must be "flattened" by
9261 calculating the resulting color, given the transparency of the
9262 pixel, and the image background color. */
9263 for (y = 0; y < height; ++y)
9265 for (x = 0; x < width; ++x)
9267 int red;
9268 int green;
9269 int blue;
9270 int opacity;
9272 red = *pixels++;
9273 green = *pixels++;
9274 blue = *pixels++;
9275 opacity = *pixels++;
9277 red = ((red * opacity)
9278 + (background.red * ((1 << 8) - opacity)));
9279 green = ((green * opacity)
9280 + (background.green * ((1 << 8) - opacity)));
9281 blue = ((blue * opacity)
9282 + (background.blue * ((1 << 8) - opacity)));
9284 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9287 pixels += rowstride - 4 * width;
9290 #ifdef COLOR_TABLE_SUPPORT
9291 /* Remember colors allocated for this image. */
9292 img->colors = colors_in_color_table (&img->ncolors);
9293 free_color_table ();
9294 #endif /* COLOR_TABLE_SUPPORT */
9296 g_object_unref (pixbuf);
9298 img->width = width;
9299 img->height = height;
9301 /* Maybe fill in the background field while we have ximg handy.
9302 Casting avoids a GCC warning. */
9303 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9305 /* Put ximg into the image. */
9306 image_put_x_image (f, img, ximg, 0);
9307 #endif /* ! USE_CAIRO */
9309 return 1;
9311 rsvg_error:
9312 g_object_unref (rsvg_handle);
9313 /* FIXME: Use error->message so the user knows what is the actual
9314 problem with the image. */
9315 image_error ("Error parsing SVG image `%s'", img->spec);
9316 g_error_free (err);
9317 return 0;
9320 #endif /* defined (HAVE_RSVG) */
9325 /***********************************************************************
9326 Ghostscript
9327 ***********************************************************************/
9329 #ifdef HAVE_X_WINDOWS
9330 #define HAVE_GHOSTSCRIPT 1
9331 #endif /* HAVE_X_WINDOWS */
9333 #ifdef HAVE_GHOSTSCRIPT
9335 static bool gs_image_p (Lisp_Object object);
9336 static bool gs_load (struct frame *f, struct image *img);
9337 static void gs_clear_image (struct frame *f, struct image *img);
9339 /* Indices of image specification fields in gs_format, below. */
9341 enum gs_keyword_index
9343 GS_TYPE,
9344 GS_PT_WIDTH,
9345 GS_PT_HEIGHT,
9346 GS_FILE,
9347 GS_LOADER,
9348 GS_BOUNDING_BOX,
9349 GS_ASCENT,
9350 GS_MARGIN,
9351 GS_RELIEF,
9352 GS_ALGORITHM,
9353 GS_HEURISTIC_MASK,
9354 GS_MASK,
9355 GS_BACKGROUND,
9356 GS_LAST
9359 /* Vector of image_keyword structures describing the format
9360 of valid user-defined image specifications. */
9362 static const struct image_keyword gs_format[GS_LAST] =
9364 {":type", IMAGE_SYMBOL_VALUE, 1},
9365 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9366 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9367 {":file", IMAGE_STRING_VALUE, 1},
9368 {":loader", IMAGE_FUNCTION_VALUE, 0},
9369 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9370 {":ascent", IMAGE_ASCENT_VALUE, 0},
9371 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9372 {":relief", IMAGE_INTEGER_VALUE, 0},
9373 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9374 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9375 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9376 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9379 /* Structure describing the image type `ghostscript'. */
9381 static struct image_type gs_type =
9383 SYMBOL_INDEX (Qpostscript),
9384 gs_image_p,
9385 gs_load,
9386 gs_clear_image,
9387 NULL,
9388 NULL
9392 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9394 static void
9395 gs_clear_image (struct frame *f, struct image *img)
9397 x_clear_image (f, img);
9401 /* Return true if OBJECT is a valid Ghostscript image
9402 specification. */
9404 static bool
9405 gs_image_p (Lisp_Object object)
9407 struct image_keyword fmt[GS_LAST];
9408 Lisp_Object tem;
9409 int i;
9411 memcpy (fmt, gs_format, sizeof fmt);
9413 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9414 return 0;
9416 /* Bounding box must be a list or vector containing 4 integers. */
9417 tem = fmt[GS_BOUNDING_BOX].value;
9418 if (CONSP (tem))
9420 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9421 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9422 return 0;
9423 if (!NILP (tem))
9424 return 0;
9426 else if (VECTORP (tem))
9428 if (ASIZE (tem) != 4)
9429 return 0;
9430 for (i = 0; i < 4; ++i)
9431 if (!INTEGERP (AREF (tem, i)))
9432 return 0;
9434 else
9435 return 0;
9437 return 1;
9441 /* Load Ghostscript image IMG for use on frame F. Value is true
9442 if successful. */
9444 static bool
9445 gs_load (struct frame *f, struct image *img)
9447 uprintmax_t printnum1, printnum2;
9448 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9449 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9450 Lisp_Object frame;
9451 double in_width, in_height;
9452 Lisp_Object pixel_colors = Qnil;
9454 /* Compute pixel size of pixmap needed from the given size in the
9455 image specification. Sizes in the specification are in pt. 1 pt
9456 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9457 info. */
9458 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9459 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9460 in_width *= FRAME_RES_X (f);
9461 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9462 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9463 in_height *= FRAME_RES_Y (f);
9465 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9466 && check_image_size (f, in_width, in_height)))
9468 image_error ("Invalid image size (see `max-image-size')");
9469 return 0;
9471 img->width = in_width;
9472 img->height = in_height;
9474 /* Create the pixmap. */
9475 eassert (img->pixmap == NO_PIXMAP);
9477 if (x_check_image_size (0, img->width, img->height))
9479 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9480 block_input ();
9481 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9482 img->width, img->height,
9483 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9484 unblock_input ();
9487 if (!img->pixmap)
9489 image_error ("Unable to create pixmap for `%s'", img->spec);
9490 return 0;
9493 /* Call the loader to fill the pixmap. It returns a process object
9494 if successful. We do not record_unwind_protect here because
9495 other places in redisplay like calling window scroll functions
9496 don't either. Let the Lisp loader use `unwind-protect' instead. */
9497 printnum1 = FRAME_X_WINDOW (f);
9498 printnum2 = img->pixmap;
9499 window_and_pixmap_id
9500 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9502 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9503 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9504 pixel_colors
9505 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9507 XSETFRAME (frame, f);
9508 loader = image_spec_value (img->spec, QCloader, NULL);
9509 if (NILP (loader))
9510 loader = intern ("gs-load-image");
9512 img->lisp_data = call6 (loader, frame, img->spec,
9513 make_number (img->width),
9514 make_number (img->height),
9515 window_and_pixmap_id,
9516 pixel_colors);
9517 return PROCESSP (img->lisp_data);
9521 /* Kill the Ghostscript process that was started to fill PIXMAP on
9522 frame F. Called from XTread_socket when receiving an event
9523 telling Emacs that Ghostscript has finished drawing. */
9525 void
9526 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9528 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9529 int class;
9530 ptrdiff_t i;
9531 struct image *img;
9533 /* Find the image containing PIXMAP. */
9534 for (i = 0; i < c->used; ++i)
9535 if (c->images[i]->pixmap == pixmap)
9536 break;
9538 /* Should someone in between have cleared the image cache, for
9539 instance, give up. */
9540 if (i == c->used)
9541 return;
9543 /* Kill the GS process. We should have found PIXMAP in the image
9544 cache and its image should contain a process object. */
9545 img = c->images[i];
9546 eassert (PROCESSP (img->lisp_data));
9547 Fkill_process (img->lisp_data, Qnil);
9548 img->lisp_data = Qnil;
9550 #if defined (HAVE_X_WINDOWS)
9552 /* On displays with a mutable colormap, figure out the colors
9553 allocated for the image by looking at the pixels of an XImage for
9554 img->pixmap. */
9555 class = FRAME_X_VISUAL (f)->class;
9556 if (class != StaticColor && class != StaticGray && class != TrueColor)
9558 XImagePtr ximg;
9560 block_input ();
9562 /* Try to get an XImage for img->pixmep. */
9563 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9564 0, 0, img->width, img->height, ~0, ZPixmap);
9565 if (ximg)
9567 int x, y;
9569 /* Initialize the color table. */
9570 init_color_table ();
9572 /* For each pixel of the image, look its color up in the
9573 color table. After having done so, the color table will
9574 contain an entry for each color used by the image. */
9575 #ifdef COLOR_TABLE_SUPPORT
9576 for (y = 0; y < img->height; ++y)
9577 for (x = 0; x < img->width; ++x)
9579 unsigned long pixel = XGetPixel (ximg, x, y);
9581 lookup_pixel_color (f, pixel);
9584 /* Record colors in the image. Free color table and XImage. */
9585 img->colors = colors_in_color_table (&img->ncolors);
9586 free_color_table ();
9587 #endif
9588 XDestroyImage (ximg);
9590 #if 0 /* This doesn't seem to be the case. If we free the colors
9591 here, we get a BadAccess later in x_clear_image when
9592 freeing the colors. */
9593 /* We have allocated colors once, but Ghostscript has also
9594 allocated colors on behalf of us. So, to get the
9595 reference counts right, free them once. */
9596 if (img->ncolors)
9597 x_free_colors (f, img->colors, img->ncolors);
9598 #endif
9600 else
9601 image_error ("Cannot get X image of `%s'; colors will not be freed",
9602 img->spec);
9604 unblock_input ();
9606 #endif /* HAVE_X_WINDOWS */
9608 /* Now that we have the pixmap, compute mask and transform the
9609 image if requested. */
9610 block_input ();
9611 postprocess_image (f, img);
9612 unblock_input ();
9615 #endif /* HAVE_GHOSTSCRIPT */
9618 /***********************************************************************
9619 Tests
9620 ***********************************************************************/
9622 #ifdef GLYPH_DEBUG
9624 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9625 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9626 (Lisp_Object spec)
9628 return valid_image_p (spec) ? Qt : Qnil;
9632 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0,
9633 doc: /* */)
9634 (Lisp_Object spec)
9636 ptrdiff_t id = -1;
9638 if (valid_image_p (spec))
9639 id = lookup_image (SELECTED_FRAME (), spec);
9641 debug_print (spec);
9642 return make_number (id);
9645 #endif /* GLYPH_DEBUG */
9648 /***********************************************************************
9649 Initialization
9650 ***********************************************************************/
9652 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9653 doc: /* Initialize image library implementing image type TYPE.
9654 Return non-nil if TYPE is a supported image type.
9656 If image libraries are loaded dynamically (currently only the case on
9657 MS-Windows), load the library for TYPE if it is not yet loaded, using
9658 the library file(s) specified by `dynamic-library-alist'. */)
9659 (Lisp_Object type)
9661 return lookup_image_type (type) ? Qt : Qnil;
9664 /* Look up image type TYPE, and return a pointer to its image_type
9665 structure. Return 0 if TYPE is not a known image type. */
9667 static struct image_type *
9668 lookup_image_type (Lisp_Object type)
9670 /* Types pbm and xbm are built-in and always available. */
9671 if (EQ (type, Qpbm))
9672 return define_image_type (&pbm_type);
9674 if (EQ (type, Qxbm))
9675 return define_image_type (&xbm_type);
9677 #if defined (HAVE_XPM) || defined (HAVE_NS)
9678 if (EQ (type, Qxpm))
9679 return define_image_type (&xpm_type);
9680 #endif
9682 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9683 if (EQ (type, Qjpeg))
9684 return define_image_type (&jpeg_type);
9685 #endif
9687 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9688 if (EQ (type, Qtiff))
9689 return define_image_type (&tiff_type);
9690 #endif
9692 #if defined (HAVE_GIF) || defined (HAVE_NS)
9693 if (EQ (type, Qgif))
9694 return define_image_type (&gif_type);
9695 #endif
9697 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9698 if (EQ (type, Qpng))
9699 return define_image_type (&png_type);
9700 #endif
9702 #if defined (HAVE_RSVG)
9703 if (EQ (type, Qsvg))
9704 return define_image_type (&svg_type);
9705 #endif
9707 #if defined (HAVE_IMAGEMAGICK)
9708 if (EQ (type, Qimagemagick))
9709 return define_image_type (&imagemagick_type);
9710 #endif
9712 #ifdef HAVE_GHOSTSCRIPT
9713 if (EQ (type, Qpostscript))
9714 return define_image_type (&gs_type);
9715 #endif
9717 return NULL;
9720 /* Reset image_types before dumping.
9721 Called from Fdump_emacs. */
9723 void
9724 reset_image_types (void)
9726 while (image_types)
9728 struct image_type *next = image_types->next;
9729 xfree (image_types);
9730 image_types = next;
9734 void
9735 syms_of_image (void)
9737 /* Initialize this only once; it will be reset before dumping. */
9738 image_types = NULL;
9740 /* Must be defined now because we're going to update it below, while
9741 defining the supported image types. */
9742 DEFVAR_LISP ("image-types", Vimage_types,
9743 doc: /* List of potentially supported image types.
9744 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9745 To check whether it is really supported, use `image-type-available-p'. */);
9746 Vimage_types = Qnil;
9748 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9749 doc: /* Maximum size of images.
9750 Emacs will not load an image into memory if its pixel width or
9751 pixel height exceeds this limit.
9753 If the value is an integer, it directly specifies the maximum
9754 image height and width, measured in pixels. If it is a floating
9755 point number, it specifies the maximum image height and width
9756 as a ratio to the frame height and width. If the value is
9757 non-numeric, there is no explicit limit on the size of images. */);
9758 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9760 /* Other symbols. */
9761 DEFSYM (Qcount, "count");
9762 DEFSYM (Qextension_data, "extension-data");
9763 DEFSYM (Qdelay, "delay");
9765 /* Keywords. */
9766 DEFSYM (QCascent, ":ascent");
9767 DEFSYM (QCmargin, ":margin");
9768 DEFSYM (QCrelief, ":relief");
9769 DEFSYM (QCconversion, ":conversion");
9770 DEFSYM (QCcolor_symbols, ":color-symbols");
9771 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9772 DEFSYM (QCindex, ":index");
9773 DEFSYM (QCcrop, ":crop");
9774 DEFSYM (QCrotation, ":rotation");
9775 DEFSYM (QCmatrix, ":matrix");
9776 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9777 DEFSYM (QCmask, ":mask");
9779 /* Other symbols. */
9780 DEFSYM (Qlaplace, "laplace");
9781 DEFSYM (Qemboss, "emboss");
9782 DEFSYM (Qedge_detection, "edge-detection");
9783 DEFSYM (Qheuristic, "heuristic");
9785 DEFSYM (Qpostscript, "postscript");
9786 DEFSYM (QCmax_width, ":max-width");
9787 DEFSYM (QCmax_height, ":max-height");
9788 #ifdef HAVE_GHOSTSCRIPT
9789 ADD_IMAGE_TYPE (Qpostscript);
9790 DEFSYM (QCloader, ":loader");
9791 DEFSYM (QCpt_width, ":pt-width");
9792 DEFSYM (QCpt_height, ":pt-height");
9793 #endif /* HAVE_GHOSTSCRIPT */
9795 #ifdef HAVE_NTGUI
9796 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9797 or -1 if no PNG/GIF support was compiled in. This is tested by
9798 w32-win.el to correctly set up the alist used to search for the
9799 respective image libraries. */
9800 DEFSYM (Qlibpng_version, "libpng-version");
9801 Fset (Qlibpng_version,
9802 #if HAVE_PNG
9803 make_number (PNG_LIBPNG_VER)
9804 #else
9805 make_number (-1)
9806 #endif
9808 DEFSYM (Qlibgif_version, "libgif-version");
9809 Fset (Qlibgif_version,
9810 #ifdef HAVE_GIF
9811 make_number (GIFLIB_MAJOR * 10000
9812 + GIFLIB_MINOR * 100
9813 + GIFLIB_RELEASE)
9814 #else
9815 make_number (-1)
9816 #endif
9818 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9819 Fset (Qlibjpeg_version,
9820 #if HAVE_JPEG
9821 make_number (JPEG_LIB_VERSION)
9822 #else
9823 make_number (-1)
9824 #endif
9826 #endif
9828 DEFSYM (Qpbm, "pbm");
9829 ADD_IMAGE_TYPE (Qpbm);
9831 DEFSYM (Qxbm, "xbm");
9832 ADD_IMAGE_TYPE (Qxbm);
9834 #if defined (HAVE_XPM) || defined (HAVE_NS)
9835 DEFSYM (Qxpm, "xpm");
9836 ADD_IMAGE_TYPE (Qxpm);
9837 #endif
9839 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9840 DEFSYM (Qjpeg, "jpeg");
9841 ADD_IMAGE_TYPE (Qjpeg);
9842 #endif
9844 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9845 DEFSYM (Qtiff, "tiff");
9846 ADD_IMAGE_TYPE (Qtiff);
9847 #endif
9849 #if defined (HAVE_GIF) || defined (HAVE_NS)
9850 DEFSYM (Qgif, "gif");
9851 ADD_IMAGE_TYPE (Qgif);
9852 #endif
9854 #if defined (HAVE_PNG) || defined (HAVE_NS)
9855 DEFSYM (Qpng, "png");
9856 ADD_IMAGE_TYPE (Qpng);
9857 #endif
9859 #if defined (HAVE_IMAGEMAGICK)
9860 DEFSYM (Qimagemagick, "imagemagick");
9861 ADD_IMAGE_TYPE (Qimagemagick);
9862 #endif
9864 #if defined (HAVE_RSVG)
9865 DEFSYM (Qsvg, "svg");
9866 ADD_IMAGE_TYPE (Qsvg);
9867 #ifdef HAVE_NTGUI
9868 /* Other libraries used directly by svg code. */
9869 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9870 DEFSYM (Qglib, "glib");
9871 DEFSYM (Qgobject, "gobject");
9872 #endif /* HAVE_NTGUI */
9873 #endif /* HAVE_RSVG */
9875 defsubr (&Sinit_image_library);
9876 #ifdef HAVE_IMAGEMAGICK
9877 defsubr (&Simagemagick_types);
9878 #endif
9879 defsubr (&Sclear_image_cache);
9880 defsubr (&Simage_flush);
9881 defsubr (&Simage_size);
9882 defsubr (&Simage_mask_p);
9883 defsubr (&Simage_metadata);
9885 #ifdef GLYPH_DEBUG
9886 defsubr (&Simagep);
9887 defsubr (&Slookup_image);
9888 #endif
9890 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9891 doc: /* Non-nil means always draw a cross over disabled images.
9892 Disabled images are those having a `:conversion disabled' property.
9893 A cross is always drawn on black & white displays. */);
9894 cross_disabled_images = 0;
9896 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9897 doc: /* List of directories to search for window system bitmap files. */);
9898 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9900 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9901 doc: /* Maximum time after which images are removed from the cache.
9902 When an image has not been displayed this many seconds, Emacs
9903 automatically removes it from the image cache. If the cache contains
9904 a large number of images, the actual eviction time may be shorter.
9905 The value can also be nil, meaning the cache is never cleared.
9907 The function `clear-image-cache' disregards this variable. */);
9908 Vimage_cache_eviction_delay = make_number (300);
9909 #ifdef HAVE_IMAGEMAGICK
9910 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9911 doc: /* Integer indicating which ImageMagick rendering method to use.
9912 The options are:
9913 0 -- the default method (pixel pushing)
9914 1 -- a newer method ("MagickExportImagePixels") that may perform
9915 better (speed etc) in some cases, but has not been as thoroughly
9916 tested with Emacs as the default method. This method requires
9917 ImageMagick version 6.4.6 (approximately) or later.
9918 */);
9919 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9920 imagemagick_render_type = 0;
9921 #endif