substitute-command-keys a few more doc strings
[emacs.git] / src / image.c
blobfb8c6e791686f2adef92542f3e7031a71b03714a
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 "uLSQM"max-image-size"uRSQM")");
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 "uLSQM"%s"uRSQM,
2943 img->spec);
2945 else
2946 success_p = 1;
2948 else
2949 image_error ("Error loading XBM image "uLSQM"%s"uRSQM, img->spec);
2951 return success_p;
2955 /* Value is true if DATA looks like an in-memory XBM file. */
2957 static bool
2958 xbm_file_p (Lisp_Object data)
2960 int w, h;
2961 return (STRINGP (data)
2962 && xbm_read_bitmap_data (NULL, SDATA (data),
2963 (SDATA (data) + SBYTES (data)),
2964 &w, &h, NULL, 1));
2968 /* Fill image IMG which is used on frame F with pixmap data. Value is
2969 true if successful. */
2971 static bool
2972 xbm_load (struct frame *f, struct image *img)
2974 bool success_p = 0;
2975 Lisp_Object file_name;
2977 eassert (xbm_image_p (img->spec));
2979 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2980 file_name = image_spec_value (img->spec, QCfile, NULL);
2981 if (STRINGP (file_name))
2983 Lisp_Object file;
2984 unsigned char *contents;
2985 ptrdiff_t size;
2987 file = x_find_image_file (file_name);
2988 if (!STRINGP (file))
2990 image_error ("Cannot find image file "uLSQM"%s"uRSQM, file_name);
2991 return 0;
2994 contents = slurp_file (SSDATA (file), &size);
2995 if (contents == NULL)
2997 image_error ("Error loading XBM image "uLSQM"%s"uRSQM, img->spec);
2998 return 0;
3001 success_p = xbm_load_image (f, img, contents, contents + size);
3002 xfree (contents);
3004 else
3006 struct image_keyword fmt[XBM_LAST];
3007 Lisp_Object data;
3008 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3009 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3010 bool non_default_colors = 0;
3011 char *bits;
3012 bool parsed_p;
3013 bool in_memory_file_p = 0;
3015 /* See if data looks like an in-memory XBM file. */
3016 data = image_spec_value (img->spec, QCdata, NULL);
3017 in_memory_file_p = xbm_file_p (data);
3019 /* Parse the image specification. */
3020 memcpy (fmt, xbm_format, sizeof fmt);
3021 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3022 eassert (parsed_p);
3024 /* Get specified width, and height. */
3025 if (!in_memory_file_p)
3027 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3028 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3029 eassert (img->width > 0 && img->height > 0);
3030 if (!check_image_size (f, img->width, img->height))
3032 image_error ("Invalid image size (see "
3033 uLSQM"max-image-size"uRSQM")");
3034 return 0;
3038 /* Get foreground and background colors, maybe allocate colors. */
3039 if (fmt[XBM_FOREGROUND].count
3040 && STRINGP (fmt[XBM_FOREGROUND].value))
3042 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3043 foreground);
3044 non_default_colors = 1;
3047 if (fmt[XBM_BACKGROUND].count
3048 && STRINGP (fmt[XBM_BACKGROUND].value))
3050 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3051 background);
3052 non_default_colors = 1;
3055 if (in_memory_file_p)
3056 success_p = xbm_load_image (f, img, SDATA (data),
3057 (SDATA (data)
3058 + SBYTES (data)));
3059 else
3061 USE_SAFE_ALLOCA;
3063 if (VECTORP (data))
3065 int i;
3066 char *p;
3067 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3069 SAFE_NALLOCA (bits, nbytes, img->height);
3070 p = bits;
3071 for (i = 0; i < img->height; ++i, p += nbytes)
3073 Lisp_Object line = AREF (data, i);
3074 if (STRINGP (line))
3075 memcpy (p, SDATA (line), nbytes);
3076 else
3077 memcpy (p, bool_vector_data (line), nbytes);
3080 else if (STRINGP (data))
3081 bits = SSDATA (data);
3082 else
3083 bits = (char *) bool_vector_data (data);
3085 #ifdef HAVE_NTGUI
3087 char *invertedBits;
3088 int nbytes, i;
3089 /* Windows mono bitmaps are reversed compared with X. */
3090 invertedBits = bits;
3091 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3092 SAFE_NALLOCA (bits, nbytes, img->height);
3093 for (i = 0; i < nbytes; i++)
3094 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3096 #endif
3097 /* Create the pixmap. */
3099 if (x_check_image_size (0, img->width, img->height))
3100 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3101 foreground, background,
3102 non_default_colors);
3103 else
3104 img->pixmap = NO_PIXMAP;
3106 if (img->pixmap)
3107 success_p = 1;
3108 else
3110 image_error (("Unable to create pixmap for XBM image "
3111 uLSQM"%s"uRSQM),
3112 img->spec);
3113 x_clear_image (f, img);
3116 SAFE_FREE ();
3120 return success_p;
3125 /***********************************************************************
3126 XPM images
3127 ***********************************************************************/
3129 #if defined (HAVE_XPM) || defined (HAVE_NS)
3131 static bool xpm_image_p (Lisp_Object object);
3132 static bool xpm_load (struct frame *f, struct image *img);
3134 #endif /* HAVE_XPM || HAVE_NS */
3136 #ifdef HAVE_XPM
3137 #ifdef HAVE_NTGUI
3138 /* Indicate to xpm.h that we don't have Xlib. */
3139 #define FOR_MSW
3140 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3141 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3142 #define XColor xpm_XColor
3143 #define XImage xpm_XImage
3144 #define Display xpm_Display
3145 #define PIXEL_ALREADY_TYPEDEFED
3146 #include "X11/xpm.h"
3147 #undef FOR_MSW
3148 #undef XColor
3149 #undef XImage
3150 #undef Display
3151 #undef PIXEL_ALREADY_TYPEDEFED
3152 #else
3153 #include "X11/xpm.h"
3154 #endif /* HAVE_NTGUI */
3155 #endif /* HAVE_XPM */
3157 #if defined (HAVE_XPM) || defined (HAVE_NS)
3159 /* Indices of image specification fields in xpm_format, below. */
3161 enum xpm_keyword_index
3163 XPM_TYPE,
3164 XPM_FILE,
3165 XPM_DATA,
3166 XPM_ASCENT,
3167 XPM_MARGIN,
3168 XPM_RELIEF,
3169 XPM_ALGORITHM,
3170 XPM_HEURISTIC_MASK,
3171 XPM_MASK,
3172 XPM_COLOR_SYMBOLS,
3173 XPM_BACKGROUND,
3174 XPM_LAST
3177 /* Vector of image_keyword structures describing the format
3178 of valid XPM image specifications. */
3180 static const struct image_keyword xpm_format[XPM_LAST] =
3182 {":type", IMAGE_SYMBOL_VALUE, 1},
3183 {":file", IMAGE_STRING_VALUE, 0},
3184 {":data", IMAGE_STRING_VALUE, 0},
3185 {":ascent", IMAGE_ASCENT_VALUE, 0},
3186 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3187 {":relief", IMAGE_INTEGER_VALUE, 0},
3188 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3189 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3190 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3191 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3192 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3195 #if defined HAVE_NTGUI && defined WINDOWSNT
3196 static bool init_xpm_functions (void);
3197 #else
3198 #define init_xpm_functions NULL
3199 #endif
3201 /* Structure describing the image type XPM. */
3203 static struct image_type xpm_type =
3205 SYMBOL_INDEX (Qxpm),
3206 xpm_image_p,
3207 xpm_load,
3208 x_clear_image,
3209 init_xpm_functions,
3210 NULL
3213 #ifdef HAVE_X_WINDOWS
3215 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3216 functions for allocating image colors. Our own functions handle
3217 color allocation failures more gracefully than the ones on the XPM
3218 lib. */
3220 #ifndef USE_CAIRO
3221 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3222 #define ALLOC_XPM_COLORS
3223 #endif
3224 #endif /* USE_CAIRO */
3225 #endif /* HAVE_X_WINDOWS */
3227 #ifdef ALLOC_XPM_COLORS
3229 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3230 XColor *, int);
3232 /* An entry in a hash table used to cache color definitions of named
3233 colors. This cache is necessary to speed up XPM image loading in
3234 case we do color allocations ourselves. Without it, we would need
3235 a call to XParseColor per pixel in the image. */
3237 struct xpm_cached_color
3239 /* Next in collision chain. */
3240 struct xpm_cached_color *next;
3242 /* Color definition (RGB and pixel color). */
3243 XColor color;
3245 /* Color name. */
3246 char name[FLEXIBLE_ARRAY_MEMBER];
3249 /* The hash table used for the color cache, and its bucket vector
3250 size. */
3252 #define XPM_COLOR_CACHE_BUCKETS 1001
3253 static struct xpm_cached_color **xpm_color_cache;
3255 /* Initialize the color cache. */
3257 static void
3258 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3260 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3261 xpm_color_cache = xzalloc (nbytes);
3262 init_color_table ();
3264 if (attrs->valuemask & XpmColorSymbols)
3266 int i;
3267 XColor color;
3269 for (i = 0; i < attrs->numsymbols; ++i)
3270 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3271 attrs->colorsymbols[i].value, &color))
3273 color.pixel = lookup_rgb_color (f, color.red, color.green,
3274 color.blue);
3275 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3280 /* Free the color cache. */
3282 static void
3283 xpm_free_color_cache (void)
3285 struct xpm_cached_color *p, *next;
3286 int i;
3288 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3289 for (p = xpm_color_cache[i]; p; p = next)
3291 next = p->next;
3292 xfree (p);
3295 xfree (xpm_color_cache);
3296 xpm_color_cache = NULL;
3297 free_color_table ();
3300 /* Return the bucket index for color named COLOR_NAME in the color
3301 cache. */
3303 static int
3304 xpm_color_bucket (char *color_name)
3306 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3307 return hash % XPM_COLOR_CACHE_BUCKETS;
3311 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3312 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3313 entry added. */
3315 static struct xpm_cached_color *
3316 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3318 size_t nbytes;
3319 struct xpm_cached_color *p;
3321 if (bucket < 0)
3322 bucket = xpm_color_bucket (color_name);
3324 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3325 p = xmalloc (nbytes);
3326 strcpy (p->name, color_name);
3327 p->color = *color;
3328 p->next = xpm_color_cache[bucket];
3329 xpm_color_cache[bucket] = p;
3330 return p;
3333 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3334 return the cached definition in *COLOR. Otherwise, make a new
3335 entry in the cache and allocate the color. Value is false if color
3336 allocation failed. */
3338 static bool
3339 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3341 struct xpm_cached_color *p;
3342 int h = xpm_color_bucket (color_name);
3344 for (p = xpm_color_cache[h]; p; p = p->next)
3345 if (strcmp (p->name, color_name) == 0)
3346 break;
3348 if (p != NULL)
3349 *color = p->color;
3350 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3351 color_name, color))
3353 color->pixel = lookup_rgb_color (f, color->red, color->green,
3354 color->blue);
3355 p = xpm_cache_color (f, color_name, color, h);
3357 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3358 with transparency, and it's useful. */
3359 else if (strcmp ("opaque", color_name) == 0)
3361 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3362 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3363 p = xpm_cache_color (f, color_name, color, h);
3366 return p != NULL;
3370 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3371 CLOSURE is a pointer to the frame on which we allocate the
3372 color. Return in *COLOR the allocated color. Value is non-zero
3373 if successful. */
3375 static int
3376 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3377 void *closure)
3379 return xpm_lookup_color (closure, color_name, color);
3383 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3384 is a pointer to the frame on which we allocate the color. Value is
3385 non-zero if successful. */
3387 static int
3388 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3390 return 1;
3393 #endif /* ALLOC_XPM_COLORS */
3396 #ifdef WINDOWSNT
3398 /* XPM library details. */
3400 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3401 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3402 (Display *, char *, xpm_XImage **,
3403 xpm_XImage **, XpmAttributes *));
3404 DEF_DLL_FN (int, XpmReadFileToImage,
3405 (Display *, char *, xpm_XImage **,
3406 xpm_XImage **, XpmAttributes *));
3407 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3409 static bool
3410 init_xpm_functions (void)
3412 HMODULE library;
3414 if (!(library = w32_delayed_load (Qxpm)))
3415 return 0;
3417 LOAD_DLL_FN (library, XpmFreeAttributes);
3418 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3419 LOAD_DLL_FN (library, XpmReadFileToImage);
3420 LOAD_DLL_FN (library, XImageFree);
3421 return 1;
3424 # undef XImageFree
3425 # undef XpmCreateImageFromBuffer
3426 # undef XpmFreeAttributes
3427 # undef XpmReadFileToImage
3429 # define XImageFree fn_XImageFree
3430 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3431 # define XpmFreeAttributes fn_XpmFreeAttributes
3432 # define XpmReadFileToImage fn_XpmReadFileToImage
3434 #endif /* WINDOWSNT */
3436 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3437 for XPM images. Such a list must consist of conses whose car and
3438 cdr are strings. */
3440 static bool
3441 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3443 while (CONSP (color_symbols))
3445 Lisp_Object sym = XCAR (color_symbols);
3446 if (!CONSP (sym)
3447 || !STRINGP (XCAR (sym))
3448 || !STRINGP (XCDR (sym)))
3449 break;
3450 color_symbols = XCDR (color_symbols);
3453 return NILP (color_symbols);
3457 /* Value is true if OBJECT is a valid XPM image specification. */
3459 static bool
3460 xpm_image_p (Lisp_Object object)
3462 struct image_keyword fmt[XPM_LAST];
3463 memcpy (fmt, xpm_format, sizeof fmt);
3464 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3465 /* Either `:file' or `:data' must be present. */
3466 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3467 /* Either no `:color-symbols' or it's a list of conses
3468 whose car and cdr are strings. */
3469 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3470 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3473 #endif /* HAVE_XPM || HAVE_NS */
3475 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3476 ptrdiff_t
3477 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3479 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3480 ptrdiff_t id;
3481 int rc;
3482 XpmAttributes attrs;
3483 Pixmap bitmap, mask;
3485 memset (&attrs, 0, sizeof attrs);
3487 attrs.visual = FRAME_X_VISUAL (f);
3488 attrs.colormap = FRAME_X_COLORMAP (f);
3489 attrs.valuemask |= XpmVisual;
3490 attrs.valuemask |= XpmColormap;
3492 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3493 (char **) bits, &bitmap, &mask, &attrs);
3494 if (rc != XpmSuccess)
3496 XpmFreeAttributes (&attrs);
3497 return -1;
3500 id = x_allocate_bitmap_record (f);
3501 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3502 dpyinfo->bitmaps[id - 1].have_mask = true;
3503 dpyinfo->bitmaps[id - 1].mask = mask;
3504 dpyinfo->bitmaps[id - 1].file = NULL;
3505 dpyinfo->bitmaps[id - 1].height = attrs.height;
3506 dpyinfo->bitmaps[id - 1].width = attrs.width;
3507 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3508 dpyinfo->bitmaps[id - 1].refcount = 1;
3510 XpmFreeAttributes (&attrs);
3511 return id;
3513 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3515 /* Load image IMG which will be displayed on frame F. Value is
3516 true if successful. */
3518 #ifdef HAVE_XPM
3520 static bool
3521 xpm_load (struct frame *f, struct image *img)
3523 int rc;
3524 XpmAttributes attrs;
3525 Lisp_Object specified_file, color_symbols;
3526 USE_SAFE_ALLOCA;
3528 #ifdef HAVE_NTGUI
3529 HDC hdc;
3530 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3531 #endif /* HAVE_NTGUI */
3533 /* Configure the XPM lib. Use the visual of frame F. Allocate
3534 close colors. Return colors allocated. */
3535 memset (&attrs, 0, sizeof attrs);
3537 #ifndef HAVE_NTGUI
3538 attrs.visual = FRAME_X_VISUAL (f);
3539 attrs.colormap = FRAME_X_COLORMAP (f);
3540 attrs.valuemask |= XpmVisual;
3541 attrs.valuemask |= XpmColormap;
3542 #endif /* HAVE_NTGUI */
3544 #ifdef ALLOC_XPM_COLORS
3545 /* Allocate colors with our own functions which handle
3546 failing color allocation more gracefully. */
3547 attrs.color_closure = f;
3548 attrs.alloc_color = xpm_alloc_color;
3549 attrs.free_colors = xpm_free_colors;
3550 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3551 #else /* not ALLOC_XPM_COLORS */
3552 /* Let the XPM lib allocate colors. */
3553 attrs.valuemask |= XpmReturnAllocPixels;
3554 #ifdef XpmAllocCloseColors
3555 attrs.alloc_close_colors = 1;
3556 attrs.valuemask |= XpmAllocCloseColors;
3557 #else /* not XpmAllocCloseColors */
3558 attrs.closeness = 600;
3559 attrs.valuemask |= XpmCloseness;
3560 #endif /* not XpmAllocCloseColors */
3561 #endif /* ALLOC_XPM_COLORS */
3563 /* If image specification contains symbolic color definitions, add
3564 these to `attrs'. */
3565 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3566 if (CONSP (color_symbols))
3568 Lisp_Object tail;
3569 XpmColorSymbol *xpm_syms;
3570 ptrdiff_t i, size;
3572 attrs.valuemask |= XpmColorSymbols;
3574 /* Count number of symbols. */
3575 attrs.numsymbols = 0;
3576 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3577 ++attrs.numsymbols;
3579 /* Allocate an XpmColorSymbol array. */
3580 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3581 size = attrs.numsymbols * sizeof *xpm_syms;
3582 memset (xpm_syms, 0, size);
3583 attrs.colorsymbols = xpm_syms;
3585 /* Fill the color symbol array. */
3586 for (tail = color_symbols, i = 0;
3587 CONSP (tail);
3588 ++i, tail = XCDR (tail))
3590 Lisp_Object name;
3591 Lisp_Object color;
3592 char *empty_string = (char *) "";
3594 if (!CONSP (XCAR (tail)))
3596 xpm_syms[i].name = empty_string;
3597 xpm_syms[i].value = empty_string;
3598 continue;
3600 name = XCAR (XCAR (tail));
3601 color = XCDR (XCAR (tail));
3602 if (STRINGP (name))
3603 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3604 else
3605 xpm_syms[i].name = empty_string;
3606 if (STRINGP (color))
3607 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3608 else
3609 xpm_syms[i].value = empty_string;
3613 /* Create a pixmap for the image, either from a file, or from a
3614 string buffer containing data in the same format as an XPM file. */
3615 #ifdef ALLOC_XPM_COLORS
3616 xpm_init_color_cache (f, &attrs);
3617 #endif
3619 specified_file = image_spec_value (img->spec, QCfile, NULL);
3621 #ifdef HAVE_NTGUI
3623 HDC frame_dc = get_frame_dc (f);
3624 hdc = CreateCompatibleDC (frame_dc);
3625 release_frame_dc (f, frame_dc);
3627 #endif /* HAVE_NTGUI */
3629 if (STRINGP (specified_file))
3631 Lisp_Object file = x_find_image_file (specified_file);
3632 if (!STRINGP (file))
3634 image_error ("Cannot find image file "uLSQM"%s"uRSQM,
3635 specified_file);
3636 #ifdef ALLOC_XPM_COLORS
3637 xpm_free_color_cache ();
3638 #endif
3639 SAFE_FREE ();
3640 return 0;
3643 #ifdef HAVE_NTGUI
3644 #ifdef WINDOWSNT
3645 /* FILE is encoded in UTF-8, but image libraries on Windows
3646 support neither UTF-8 nor UTF-16 encoded file names. So we
3647 need to re-encode it in ANSI. */
3648 file = ansi_encode_filename (file);
3649 #endif
3650 /* XpmReadFileToPixmap is not available in the Windows port of
3651 libxpm. But XpmReadFileToImage almost does what we want. */
3652 rc = XpmReadFileToImage (&hdc, SDATA (file),
3653 &xpm_image, &xpm_mask,
3654 &attrs);
3655 #else
3656 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3657 &img->ximg, &img->mask_img,
3658 &attrs);
3659 #endif /* HAVE_NTGUI */
3661 else
3663 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3664 if (!STRINGP (buffer))
3666 image_error ("Invalid image data "uLSQM"%s"uRSQM, buffer);
3667 #ifdef ALLOC_XPM_COLORS
3668 xpm_free_color_cache ();
3669 #endif
3670 SAFE_FREE ();
3671 return 0;
3673 #ifdef HAVE_NTGUI
3674 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3675 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3676 rc = XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3677 &xpm_image, &xpm_mask,
3678 &attrs);
3679 #else
3680 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3681 &img->ximg, &img->mask_img,
3682 &attrs);
3683 #endif /* HAVE_NTGUI */
3686 #ifdef USE_CAIRO
3687 // Load very specific Xpm:s.
3688 if (rc == XpmSuccess
3689 && img->ximg->format == ZPixmap
3690 && img->ximg->bits_per_pixel == 32
3691 && (! img->mask_img || img->mask_img->bits_per_pixel == 1))
3693 int width = img->ximg->width;
3694 int height = img->ximg->height;
3695 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
3696 int i;
3697 uint32_t *od = (uint32_t *)data;
3698 uint32_t *id = (uint32_t *)img->ximg->data;
3699 char *mid = img->mask_img ? img->mask_img->data : 0;
3700 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
3702 for (i = 0; i < height; ++i)
3704 int k;
3705 for (k = 0; k < width; ++k)
3707 int idx = i * img->ximg->bytes_per_line/4 + k;
3708 int maskidx = mid ? i * img->mask_img->bytes_per_line + k/8 : 0;
3709 int mask = mid ? mid[maskidx] & (1 << (k % 8)) : 1;
3711 if (mask) od[idx] = id[idx] + 0xff000000; // ff => full alpha
3712 else od[idx] = bgcolor;
3716 create_cairo_image_surface (img, data, width, height);
3718 else
3720 rc = XpmFileInvalid;
3721 x_clear_image (f, img);
3723 #else
3724 #ifdef HAVE_X_WINDOWS
3725 if (rc == XpmSuccess)
3727 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3728 img->ximg->width, img->ximg->height,
3729 img->ximg->depth);
3730 if (img->pixmap == NO_PIXMAP)
3732 x_clear_image (f, img);
3733 rc = XpmNoMemory;
3735 else if (img->mask_img)
3737 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3738 img->mask_img->width,
3739 img->mask_img->height,
3740 img->mask_img->depth);
3741 if (img->mask == NO_PIXMAP)
3743 x_clear_image (f, img);
3744 rc = XpmNoMemory;
3748 #endif
3749 #endif /* ! USE_CAIRO */
3751 if (rc == XpmSuccess)
3753 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3754 img->colors = colors_in_color_table (&img->ncolors);
3755 #else /* not ALLOC_XPM_COLORS */
3756 int i;
3758 #ifdef HAVE_NTGUI
3759 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3760 plus some duplicate attributes. */
3761 if (xpm_image && xpm_image->bitmap)
3763 img->pixmap = xpm_image->bitmap;
3764 /* XImageFree in libXpm frees XImage struct without destroying
3765 the bitmap, which is what we want. */
3766 XImageFree (xpm_image);
3768 if (xpm_mask && xpm_mask->bitmap)
3770 /* The mask appears to be inverted compared with what we expect.
3771 TODO: invert our expectations. See other places where we
3772 have to invert bits because our idea of masks is backwards. */
3773 HGDIOBJ old_obj;
3774 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3776 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3777 SelectObject (hdc, old_obj);
3779 img->mask = xpm_mask->bitmap;
3780 XImageFree (xpm_mask);
3781 DeleteDC (hdc);
3784 DeleteDC (hdc);
3785 #endif /* HAVE_NTGUI */
3787 /* Remember allocated colors. */
3788 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3789 img->ncolors = attrs.nalloc_pixels;
3790 for (i = 0; i < attrs.nalloc_pixels; ++i)
3792 img->colors[i] = attrs.alloc_pixels[i];
3793 #ifdef DEBUG_X_COLORS
3794 register_color (img->colors[i]);
3795 #endif
3797 #endif /* not ALLOC_XPM_COLORS */
3799 img->width = attrs.width;
3800 img->height = attrs.height;
3801 eassert (img->width > 0 && img->height > 0);
3803 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3804 XpmFreeAttributes (&attrs);
3806 #ifdef HAVE_X_WINDOWS
3807 /* Maybe fill in the background field while we have ximg handy. */
3808 IMAGE_BACKGROUND (img, f, img->ximg);
3809 if (img->mask_img)
3810 /* Fill in the background_transparent field while we have the
3811 mask handy. */
3812 image_background_transparent (img, f, img->mask_img);
3813 #endif
3815 else
3817 #ifdef HAVE_NTGUI
3818 DeleteDC (hdc);
3819 #endif /* HAVE_NTGUI */
3821 switch (rc)
3823 case XpmOpenFailed:
3824 image_error ("Error opening XPM file (%s)", img->spec);
3825 break;
3827 case XpmFileInvalid:
3828 image_error ("Invalid XPM file (%s)", img->spec);
3829 break;
3831 case XpmNoMemory:
3832 image_error ("Out of memory (%s)", img->spec);
3833 break;
3835 case XpmColorFailed:
3836 image_error ("Color allocation error (%s)", img->spec);
3837 break;
3839 default:
3840 image_error ("Unknown error (%s)", img->spec);
3841 break;
3845 #ifdef ALLOC_XPM_COLORS
3846 xpm_free_color_cache ();
3847 #endif
3848 SAFE_FREE ();
3849 return rc == XpmSuccess;
3852 #endif /* HAVE_XPM */
3854 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3856 /* XPM support functions for NS where libxpm is not available.
3857 Only XPM version 3 (without any extensions) is supported. */
3859 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3860 int, Lisp_Object);
3861 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3862 const unsigned char *, int);
3863 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3864 int, Lisp_Object);
3865 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3866 const unsigned char *, int);
3868 /* Tokens returned from xpm_scan. */
3870 enum xpm_token
3872 XPM_TK_IDENT = 256,
3873 XPM_TK_STRING,
3874 XPM_TK_EOF
3877 /* Scan an XPM data and return a character (< 256) or a token defined
3878 by enum xpm_token above. *S and END are the start (inclusive) and
3879 the end (exclusive) addresses of the data, respectively. Advance
3880 *S while scanning. If token is either XPM_TK_IDENT or
3881 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3882 length of the corresponding token, respectively. */
3884 static int
3885 xpm_scan (const unsigned char **s,
3886 const unsigned char *end,
3887 const unsigned char **beg,
3888 ptrdiff_t *len)
3890 int c;
3892 while (*s < end)
3894 /* Skip white-space. */
3895 while (*s < end && (c = *(*s)++, c_isspace (c)))
3898 /* gnus-pointer.xpm uses '-' in its identifier.
3899 sb-dir-plus.xpm uses '+' in its identifier. */
3900 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3902 *beg = *s - 1;
3903 while (*s < end
3904 && (c = **s, c_isalnum (c)
3905 || c == '_' || c == '-' || c == '+'))
3906 ++*s;
3907 *len = *s - *beg;
3908 return XPM_TK_IDENT;
3910 else if (c == '"')
3912 *beg = *s;
3913 while (*s < end && **s != '"')
3914 ++*s;
3915 *len = *s - *beg;
3916 if (*s < end)
3917 ++*s;
3918 return XPM_TK_STRING;
3920 else if (c == '/')
3922 if (*s < end && **s == '*')
3924 /* C-style comment. */
3925 ++*s;
3928 while (*s < end && *(*s)++ != '*')
3931 while (*s < end && **s != '/');
3932 if (*s < end)
3933 ++*s;
3935 else
3936 return c;
3938 else
3939 return c;
3942 return XPM_TK_EOF;
3945 /* Functions for color table lookup in XPM data. A key is a string
3946 specifying the color of each pixel in XPM data. A value is either
3947 an integer that specifies a pixel color, Qt that specifies
3948 transparency, or Qnil for the unspecified color. If the length of
3949 the key string is one, a vector is used as a table. Otherwise, a
3950 hash table is used. */
3952 static Lisp_Object
3953 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3954 const unsigned char *,
3955 int,
3956 Lisp_Object),
3957 Lisp_Object (**get_func) (Lisp_Object,
3958 const unsigned char *,
3959 int))
3961 *put_func = xpm_put_color_table_v;
3962 *get_func = xpm_get_color_table_v;
3963 return Fmake_vector (make_number (256), Qnil);
3966 static void
3967 xpm_put_color_table_v (Lisp_Object color_table,
3968 const unsigned char *chars_start,
3969 int chars_len,
3970 Lisp_Object color)
3972 ASET (color_table, *chars_start, color);
3975 static Lisp_Object
3976 xpm_get_color_table_v (Lisp_Object color_table,
3977 const unsigned char *chars_start,
3978 int chars_len)
3980 return AREF (color_table, *chars_start);
3983 static Lisp_Object
3984 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3985 const unsigned char *,
3986 int,
3987 Lisp_Object),
3988 Lisp_Object (**get_func) (Lisp_Object,
3989 const unsigned char *,
3990 int))
3992 *put_func = xpm_put_color_table_h;
3993 *get_func = xpm_get_color_table_h;
3994 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
3995 make_float (DEFAULT_REHASH_SIZE),
3996 make_float (DEFAULT_REHASH_THRESHOLD),
3997 Qnil);
4000 static void
4001 xpm_put_color_table_h (Lisp_Object color_table,
4002 const unsigned char *chars_start,
4003 int chars_len,
4004 Lisp_Object color)
4006 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4007 EMACS_UINT hash_code;
4008 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4010 hash_lookup (table, chars, &hash_code);
4011 hash_put (table, chars, color, hash_code);
4014 static Lisp_Object
4015 xpm_get_color_table_h (Lisp_Object color_table,
4016 const unsigned char *chars_start,
4017 int chars_len)
4019 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4020 ptrdiff_t i =
4021 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
4023 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4026 enum xpm_color_key {
4027 XPM_COLOR_KEY_S,
4028 XPM_COLOR_KEY_M,
4029 XPM_COLOR_KEY_G4,
4030 XPM_COLOR_KEY_G,
4031 XPM_COLOR_KEY_C
4034 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4036 static int
4037 xpm_str_to_color_key (const char *s)
4039 int i;
4041 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
4042 if (strcmp (xpm_color_key_strings[i], s) == 0)
4043 return i;
4044 return -1;
4047 static bool
4048 xpm_load_image (struct frame *f,
4049 struct image *img,
4050 const unsigned char *contents,
4051 const unsigned char *end)
4053 const unsigned char *s = contents, *beg, *str;
4054 unsigned char buffer[BUFSIZ];
4055 int width, height, x, y;
4056 int num_colors, chars_per_pixel;
4057 ptrdiff_t len;
4058 int LA1;
4059 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4060 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
4061 Lisp_Object frame, color_symbols, color_table;
4062 int best_key;
4063 bool have_mask = false;
4064 XImagePtr ximg = NULL, mask_img = NULL;
4066 #define match() \
4067 LA1 = xpm_scan (&s, end, &beg, &len)
4069 #define expect(TOKEN) \
4070 do \
4072 if (LA1 != (TOKEN)) \
4073 goto failure; \
4074 match (); \
4076 while (0)
4078 #define expect_ident(IDENT) \
4079 if (LA1 == XPM_TK_IDENT \
4080 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4081 match (); \
4082 else \
4083 goto failure
4085 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4086 goto failure;
4087 s += 9;
4088 match ();
4089 expect_ident ("static");
4090 expect_ident ("char");
4091 expect ('*');
4092 expect (XPM_TK_IDENT);
4093 expect ('[');
4094 expect (']');
4095 expect ('=');
4096 expect ('{');
4097 expect (XPM_TK_STRING);
4098 if (len >= BUFSIZ)
4099 goto failure;
4100 memcpy (buffer, beg, len);
4101 buffer[len] = '\0';
4102 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4103 &num_colors, &chars_per_pixel) != 4
4104 || width <= 0 || height <= 0
4105 || num_colors <= 0 || chars_per_pixel <= 0)
4106 goto failure;
4108 if (!check_image_size (f, width, height))
4110 image_error ("Invalid image size (see "uLSQM"max-image-size"uRSQM")");
4111 goto failure;
4114 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4115 #ifndef HAVE_NS
4116 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4117 &mask_img, 1)
4118 #endif
4121 image_error ("Image too large");
4122 goto failure;
4125 expect (',');
4127 XSETFRAME (frame, f);
4128 if (!NILP (Fxw_display_color_p (frame)))
4129 best_key = XPM_COLOR_KEY_C;
4130 else if (!NILP (Fx_display_grayscale_p (frame)))
4131 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4132 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4133 else
4134 best_key = XPM_COLOR_KEY_M;
4136 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4137 if (chars_per_pixel == 1)
4138 color_table = xpm_make_color_table_v (&put_color_table,
4139 &get_color_table);
4140 else
4141 color_table = xpm_make_color_table_h (&put_color_table,
4142 &get_color_table);
4144 while (num_colors-- > 0)
4146 char *color, *max_color;
4147 int key, next_key, max_key = 0;
4148 Lisp_Object symbol_color = Qnil, color_val;
4149 XColor cdef;
4151 expect (XPM_TK_STRING);
4152 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4153 goto failure;
4154 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4155 buffer[len - chars_per_pixel] = '\0';
4157 str = strtok (buffer, " \t");
4158 if (str == NULL)
4159 goto failure;
4160 key = xpm_str_to_color_key (str);
4161 if (key < 0)
4162 goto failure;
4165 color = strtok (NULL, " \t");
4166 if (color == NULL)
4167 goto failure;
4169 while ((str = strtok (NULL, " \t")) != NULL)
4171 next_key = xpm_str_to_color_key (str);
4172 if (next_key >= 0)
4173 break;
4174 color[strlen (color)] = ' ';
4177 if (key == XPM_COLOR_KEY_S)
4179 if (NILP (symbol_color))
4180 symbol_color = build_string (color);
4182 else if (max_key < key && key <= best_key)
4184 max_key = key;
4185 max_color = color;
4187 key = next_key;
4189 while (str);
4191 color_val = Qnil;
4192 if (!NILP (color_symbols) && !NILP (symbol_color))
4194 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4196 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4198 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4199 color_val = Qt;
4200 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4201 &cdef, 0))
4202 color_val = make_number (cdef.pixel);
4205 if (NILP (color_val) && max_key > 0)
4207 if (xstrcasecmp (max_color, "None") == 0)
4208 color_val = Qt;
4209 else if (x_defined_color (f, max_color, &cdef, 0))
4210 color_val = make_number (cdef.pixel);
4212 if (!NILP (color_val))
4213 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4215 expect (',');
4218 for (y = 0; y < height; y++)
4220 expect (XPM_TK_STRING);
4221 str = beg;
4222 if (len < width * chars_per_pixel)
4223 goto failure;
4224 for (x = 0; x < width; x++, str += chars_per_pixel)
4226 Lisp_Object color_val =
4227 (*get_color_table) (color_table, str, chars_per_pixel);
4229 XPutPixel (ximg, x, y,
4230 (INTEGERP (color_val) ? XINT (color_val)
4231 : FRAME_FOREGROUND_PIXEL (f)));
4232 #ifndef HAVE_NS
4233 XPutPixel (mask_img, x, y,
4234 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4235 : (have_mask = true, PIX_MASK_RETAIN)));
4236 #else
4237 if (EQ (color_val, Qt))
4238 ns_set_alpha (ximg, x, y, 0);
4239 #endif
4241 if (y + 1 < height)
4242 expect (',');
4245 img->width = width;
4246 img->height = height;
4248 /* Maybe fill in the background field while we have ximg handy. */
4249 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4250 IMAGE_BACKGROUND (img, f, ximg);
4252 image_put_x_image (f, img, ximg, 0);
4253 #ifndef HAVE_NS
4254 if (have_mask)
4256 /* Fill in the background_transparent field while we have the
4257 mask handy. */
4258 image_background_transparent (img, f, mask_img);
4260 image_put_x_image (f, img, mask_img, 1);
4262 else
4264 x_destroy_x_image (mask_img);
4265 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4267 #endif
4268 return 1;
4270 failure:
4271 image_error ("Invalid XPM file (%s)", img->spec);
4272 x_destroy_x_image (ximg);
4273 x_destroy_x_image (mask_img);
4274 x_clear_image (f, img);
4275 return 0;
4277 #undef match
4278 #undef expect
4279 #undef expect_ident
4282 static bool
4283 xpm_load (struct frame *f,
4284 struct image *img)
4286 bool success_p = 0;
4287 Lisp_Object file_name;
4289 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4290 file_name = image_spec_value (img->spec, QCfile, NULL);
4291 if (STRINGP (file_name))
4293 Lisp_Object file;
4294 unsigned char *contents;
4295 ptrdiff_t size;
4297 file = x_find_image_file (file_name);
4298 if (!STRINGP (file))
4300 image_error ("Cannot find image file "uLSQM"%s"uRSQM, file_name);
4301 return 0;
4304 contents = slurp_file (SSDATA (file), &size);
4305 if (contents == NULL)
4307 image_error ("Error loading XPM image "uLSQM"%s"uRSQM, img->spec);
4308 return 0;
4311 success_p = xpm_load_image (f, img, contents, contents + size);
4312 xfree (contents);
4314 else
4316 Lisp_Object data;
4318 data = image_spec_value (img->spec, QCdata, NULL);
4319 if (!STRINGP (data))
4321 image_error ("Invalid image data "uLSQM"%s"uRSQM, data);
4322 return 0;
4324 success_p = xpm_load_image (f, img, SDATA (data),
4325 SDATA (data) + SBYTES (data));
4328 return success_p;
4331 #endif /* HAVE_NS && !HAVE_XPM */
4335 /***********************************************************************
4336 Color table
4337 ***********************************************************************/
4339 #ifdef COLOR_TABLE_SUPPORT
4341 /* An entry in the color table mapping an RGB color to a pixel color. */
4343 struct ct_color
4345 int r, g, b;
4346 unsigned long pixel;
4348 /* Next in color table collision list. */
4349 struct ct_color *next;
4352 /* The bucket vector size to use. Must be prime. */
4354 #define CT_SIZE 101
4356 /* Value is a hash of the RGB color given by R, G, and B. */
4358 static unsigned
4359 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4361 return (r << 16) ^ (g << 8) ^ b;
4364 /* The color hash table. */
4366 static struct ct_color **ct_table;
4368 /* Number of entries in the color table. */
4370 static int ct_colors_allocated;
4371 enum
4373 ct_colors_allocated_max =
4374 min (INT_MAX,
4375 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4378 /* Initialize the color table. */
4380 static void
4381 init_color_table (void)
4383 int size = CT_SIZE * sizeof (*ct_table);
4384 ct_table = xzalloc (size);
4385 ct_colors_allocated = 0;
4389 /* Free memory associated with the color table. */
4391 static void
4392 free_color_table (void)
4394 int i;
4395 struct ct_color *p, *next;
4397 for (i = 0; i < CT_SIZE; ++i)
4398 for (p = ct_table[i]; p; p = next)
4400 next = p->next;
4401 xfree (p);
4404 xfree (ct_table);
4405 ct_table = NULL;
4409 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4410 entry for that color already is in the color table, return the
4411 pixel color of that entry. Otherwise, allocate a new color for R,
4412 G, B, and make an entry in the color table. */
4414 static unsigned long
4415 lookup_rgb_color (struct frame *f, int r, int g, int b)
4417 unsigned hash = ct_hash_rgb (r, g, b);
4418 int i = hash % CT_SIZE;
4419 struct ct_color *p;
4420 Display_Info *dpyinfo;
4422 /* Handle TrueColor visuals specially, which improves performance by
4423 two orders of magnitude. Freeing colors on TrueColor visuals is
4424 a nop, and pixel colors specify RGB values directly. See also
4425 the Xlib spec, chapter 3.1. */
4426 dpyinfo = FRAME_DISPLAY_INFO (f);
4427 if (dpyinfo->red_bits > 0)
4429 unsigned long pr, pg, pb;
4431 /* Apply gamma-correction like normal color allocation does. */
4432 if (f->gamma)
4434 XColor color;
4435 color.red = r, color.green = g, color.blue = b;
4436 gamma_correct (f, &color);
4437 r = color.red, g = color.green, b = color.blue;
4440 /* Scale down RGB values to the visual's bits per RGB, and shift
4441 them to the right position in the pixel color. Note that the
4442 original RGB values are 16-bit values, as usual in X. */
4443 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4444 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4445 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4447 /* Assemble the pixel color. */
4448 return pr | pg | pb;
4451 for (p = ct_table[i]; p; p = p->next)
4452 if (p->r == r && p->g == g && p->b == b)
4453 break;
4455 if (p == NULL)
4458 #ifdef HAVE_X_WINDOWS
4459 XColor color;
4460 Colormap cmap;
4461 bool rc;
4462 #else
4463 COLORREF color;
4464 #endif
4466 if (ct_colors_allocated_max <= ct_colors_allocated)
4467 return FRAME_FOREGROUND_PIXEL (f);
4469 #ifdef HAVE_X_WINDOWS
4470 color.red = r;
4471 color.green = g;
4472 color.blue = b;
4474 cmap = FRAME_X_COLORMAP (f);
4475 rc = x_alloc_nearest_color (f, cmap, &color);
4476 if (rc)
4478 ++ct_colors_allocated;
4479 p = xmalloc (sizeof *p);
4480 p->r = r;
4481 p->g = g;
4482 p->b = b;
4483 p->pixel = color.pixel;
4484 p->next = ct_table[i];
4485 ct_table[i] = p;
4487 else
4488 return FRAME_FOREGROUND_PIXEL (f);
4490 #else
4491 #ifdef HAVE_NTGUI
4492 color = PALETTERGB (r, g, b);
4493 #else
4494 color = RGB_TO_ULONG (r, g, b);
4495 #endif /* HAVE_NTGUI */
4496 ++ct_colors_allocated;
4497 p = xmalloc (sizeof *p);
4498 p->r = r;
4499 p->g = g;
4500 p->b = b;
4501 p->pixel = color;
4502 p->next = ct_table[i];
4503 ct_table[i] = p;
4504 #endif /* HAVE_X_WINDOWS */
4508 return p->pixel;
4512 /* Look up pixel color PIXEL which is used on frame F in the color
4513 table. If not already present, allocate it. Value is PIXEL. */
4515 static unsigned long
4516 lookup_pixel_color (struct frame *f, unsigned long pixel)
4518 int i = pixel % CT_SIZE;
4519 struct ct_color *p;
4521 for (p = ct_table[i]; p; p = p->next)
4522 if (p->pixel == pixel)
4523 break;
4525 if (p == NULL)
4527 XColor color;
4528 Colormap cmap;
4529 bool rc;
4531 if (ct_colors_allocated >= ct_colors_allocated_max)
4532 return FRAME_FOREGROUND_PIXEL (f);
4534 #ifdef HAVE_X_WINDOWS
4535 cmap = FRAME_X_COLORMAP (f);
4536 color.pixel = pixel;
4537 x_query_color (f, &color);
4538 rc = x_alloc_nearest_color (f, cmap, &color);
4539 #else
4540 block_input ();
4541 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4542 color.pixel = pixel;
4543 XQueryColor (NULL, cmap, &color);
4544 rc = x_alloc_nearest_color (f, cmap, &color);
4545 unblock_input ();
4546 #endif /* HAVE_X_WINDOWS */
4548 if (rc)
4550 ++ct_colors_allocated;
4552 p = xmalloc (sizeof *p);
4553 p->r = color.red;
4554 p->g = color.green;
4555 p->b = color.blue;
4556 p->pixel = pixel;
4557 p->next = ct_table[i];
4558 ct_table[i] = p;
4560 else
4561 return FRAME_FOREGROUND_PIXEL (f);
4563 return p->pixel;
4567 /* Value is a vector of all pixel colors contained in the color table,
4568 allocated via xmalloc. Set *N to the number of colors. */
4570 static unsigned long *
4571 colors_in_color_table (int *n)
4573 int i, j;
4574 struct ct_color *p;
4575 unsigned long *colors;
4577 if (ct_colors_allocated == 0)
4579 *n = 0;
4580 colors = NULL;
4582 else
4584 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4585 *n = ct_colors_allocated;
4587 for (i = j = 0; i < CT_SIZE; ++i)
4588 for (p = ct_table[i]; p; p = p->next)
4589 colors[j++] = p->pixel;
4592 return colors;
4595 #else /* COLOR_TABLE_SUPPORT */
4597 static unsigned long
4598 lookup_rgb_color (struct frame *f, int r, int g, int b)
4600 unsigned long pixel;
4602 #ifdef HAVE_NTGUI
4603 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4604 #endif /* HAVE_NTGUI */
4606 #ifdef HAVE_NS
4607 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4608 #endif /* HAVE_NS */
4609 return pixel;
4612 static void
4613 init_color_table (void)
4616 #endif /* COLOR_TABLE_SUPPORT */
4619 /***********************************************************************
4620 Algorithms
4621 ***********************************************************************/
4623 /* Edge detection matrices for different edge-detection
4624 strategies. */
4626 static int emboss_matrix[9] = {
4627 /* x - 1 x x + 1 */
4628 2, -1, 0, /* y - 1 */
4629 -1, 0, 1, /* y */
4630 0, 1, -2 /* y + 1 */
4633 static int laplace_matrix[9] = {
4634 /* x - 1 x x + 1 */
4635 1, 0, 0, /* y - 1 */
4636 0, 0, 0, /* y */
4637 0, 0, -1 /* y + 1 */
4640 /* Value is the intensity of the color whose red/green/blue values
4641 are R, G, and B. */
4643 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4646 /* On frame F, return an array of XColor structures describing image
4647 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4648 means also fill the red/green/blue members of the XColor
4649 structures. Value is a pointer to the array of XColors structures,
4650 allocated with xmalloc; it must be freed by the caller. */
4652 static XColor *
4653 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4655 int x, y;
4656 XColor *colors, *p;
4657 XImagePtr_or_DC ximg;
4658 #ifdef HAVE_NTGUI
4659 HGDIOBJ prev;
4660 #endif /* HAVE_NTGUI */
4662 if (img->height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width)
4663 memory_full (SIZE_MAX);
4664 colors = xmalloc (sizeof *colors * img->width * img->height);
4666 /* Get the X image or create a memory device context for IMG. */
4667 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4669 /* Fill the `pixel' members of the XColor array. I wished there
4670 were an easy and portable way to circumvent XGetPixel. */
4671 p = colors;
4672 for (y = 0; y < img->height; ++y)
4674 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4675 XColor *row = p;
4676 for (x = 0; x < img->width; ++x, ++p)
4677 p->pixel = GET_PIXEL (ximg, x, y);
4678 if (rgb_p)
4679 x_query_colors (f, row, img->width);
4681 #else
4683 for (x = 0; x < img->width; ++x, ++p)
4685 /* W32_TODO: palette support needed here? */
4686 p->pixel = GET_PIXEL (ximg, x, y);
4687 if (rgb_p)
4689 p->red = RED16_FROM_ULONG (p->pixel);
4690 p->green = GREEN16_FROM_ULONG (p->pixel);
4691 p->blue = BLUE16_FROM_ULONG (p->pixel);
4694 #endif /* HAVE_X_WINDOWS */
4697 image_unget_x_image_or_dc (img, 0, ximg, prev);
4699 return colors;
4702 #ifdef HAVE_NTGUI
4704 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4705 created with CreateDIBSection, with the pointer to the bit values
4706 stored in ximg->data. */
4708 static void
4709 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4711 int width = ximg->info.bmiHeader.biWidth;
4712 unsigned char * pixel;
4714 /* True color images. */
4715 if (ximg->info.bmiHeader.biBitCount == 24)
4717 int rowbytes = width * 3;
4718 /* Ensure scanlines are aligned on 4 byte boundaries. */
4719 if (rowbytes % 4)
4720 rowbytes += 4 - (rowbytes % 4);
4722 pixel = ximg->data + y * rowbytes + x * 3;
4723 /* Windows bitmaps are in BGR order. */
4724 *pixel = GetBValue (color);
4725 *(pixel + 1) = GetGValue (color);
4726 *(pixel + 2) = GetRValue (color);
4728 /* Monochrome images. */
4729 else if (ximg->info.bmiHeader.biBitCount == 1)
4731 int rowbytes = width / 8;
4732 /* Ensure scanlines are aligned on 4 byte boundaries. */
4733 if (rowbytes % 4)
4734 rowbytes += 4 - (rowbytes % 4);
4735 pixel = ximg->data + y * rowbytes + x / 8;
4736 /* Filter out palette info. */
4737 if (color & 0x00ffffff)
4738 *pixel = *pixel | (1 << x % 8);
4739 else
4740 *pixel = *pixel & ~(1 << x % 8);
4742 else
4743 image_error ("XPutPixel: palette image not supported");
4746 #endif /* HAVE_NTGUI */
4748 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4749 RGB members are set. F is the frame on which this all happens.
4750 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4752 static void
4753 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4755 int x, y;
4756 XImagePtr oimg = NULL;
4757 XColor *p;
4759 init_color_table ();
4761 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4762 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4763 &oimg, 0);
4764 p = colors;
4765 for (y = 0; y < img->height; ++y)
4766 for (x = 0; x < img->width; ++x, ++p)
4768 unsigned long pixel;
4769 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4770 XPutPixel (oimg, x, y, pixel);
4773 xfree (colors);
4775 image_put_x_image (f, img, oimg, 0);
4776 #ifdef COLOR_TABLE_SUPPORT
4777 img->colors = colors_in_color_table (&img->ncolors);
4778 free_color_table ();
4779 #endif /* COLOR_TABLE_SUPPORT */
4783 /* On frame F, perform edge-detection on image IMG.
4785 MATRIX is a nine-element array specifying the transformation
4786 matrix. See emboss_matrix for an example.
4788 COLOR_ADJUST is a color adjustment added to each pixel of the
4789 outgoing image. */
4791 static void
4792 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4794 XColor *colors = x_to_xcolors (f, img, 1);
4795 XColor *new, *p;
4796 int x, y, i, sum;
4798 for (i = sum = 0; i < 9; ++i)
4799 sum += eabs (matrix[i]);
4801 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4803 if (img->height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width)
4804 memory_full (SIZE_MAX);
4805 new = xmalloc (sizeof *new * img->width * img->height);
4807 for (y = 0; y < img->height; ++y)
4809 p = COLOR (new, 0, y);
4810 p->red = p->green = p->blue = 0xffff/2;
4811 p = COLOR (new, img->width - 1, y);
4812 p->red = p->green = p->blue = 0xffff/2;
4815 for (x = 1; x < img->width - 1; ++x)
4817 p = COLOR (new, x, 0);
4818 p->red = p->green = p->blue = 0xffff/2;
4819 p = COLOR (new, x, img->height - 1);
4820 p->red = p->green = p->blue = 0xffff/2;
4823 for (y = 1; y < img->height - 1; ++y)
4825 p = COLOR (new, 1, y);
4827 for (x = 1; x < img->width - 1; ++x, ++p)
4829 int r, g, b, yy, xx;
4831 r = g = b = i = 0;
4832 for (yy = y - 1; yy < y + 2; ++yy)
4833 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4834 if (matrix[i])
4836 XColor *t = COLOR (colors, xx, yy);
4837 r += matrix[i] * t->red;
4838 g += matrix[i] * t->green;
4839 b += matrix[i] * t->blue;
4842 r = (r / sum + color_adjust) & 0xffff;
4843 g = (g / sum + color_adjust) & 0xffff;
4844 b = (b / sum + color_adjust) & 0xffff;
4845 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4849 xfree (colors);
4850 x_from_xcolors (f, img, new);
4852 #undef COLOR
4856 /* Perform the pre-defined `emboss' edge-detection on image IMG
4857 on frame F. */
4859 static void
4860 x_emboss (struct frame *f, struct image *img)
4862 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4866 /* Transform image IMG which is used on frame F with a Laplace
4867 edge-detection algorithm. The result is an image that can be used
4868 to draw disabled buttons, for example. */
4870 static void
4871 x_laplace (struct frame *f, struct image *img)
4873 x_detect_edges (f, img, laplace_matrix, 45000);
4877 /* Perform edge-detection on image IMG on frame F, with specified
4878 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4880 MATRIX must be either
4882 - a list of at least 9 numbers in row-major form
4883 - a vector of at least 9 numbers
4885 COLOR_ADJUST nil means use a default; otherwise it must be a
4886 number. */
4888 static void
4889 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4890 Lisp_Object color_adjust)
4892 int i = 0;
4893 int trans[9];
4895 if (CONSP (matrix))
4897 for (i = 0;
4898 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4899 ++i, matrix = XCDR (matrix))
4900 trans[i] = XFLOATINT (XCAR (matrix));
4902 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4904 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4905 trans[i] = XFLOATINT (AREF (matrix, i));
4908 if (NILP (color_adjust))
4909 color_adjust = make_number (0xffff / 2);
4911 if (i == 9 && NUMBERP (color_adjust))
4912 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4916 /* Transform image IMG on frame F so that it looks disabled. */
4918 static void
4919 x_disable_image (struct frame *f, struct image *img)
4921 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4922 #ifdef HAVE_NTGUI
4923 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4924 #else
4925 int n_planes = dpyinfo->n_planes;
4926 #endif /* HAVE_NTGUI */
4928 if (n_planes >= 2)
4930 /* Color (or grayscale). Convert to gray, and equalize. Just
4931 drawing such images with a stipple can look very odd, so
4932 we're using this method instead. */
4933 XColor *colors = x_to_xcolors (f, img, 1);
4934 XColor *p, *end;
4935 const int h = 15000;
4936 const int l = 30000;
4938 for (p = colors, end = colors + img->width * img->height;
4939 p < end;
4940 ++p)
4942 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4943 int i2 = (0xffff - h - l) * i / 0xffff + l;
4944 p->red = p->green = p->blue = i2;
4947 x_from_xcolors (f, img, colors);
4950 /* Draw a cross over the disabled image, if we must or if we
4951 should. */
4952 if (n_planes < 2 || cross_disabled_images)
4954 #ifndef HAVE_NTGUI
4955 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4957 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4959 Display *dpy = FRAME_X_DISPLAY (f);
4960 GC gc;
4962 image_sync_to_pixmaps (f, img);
4963 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4964 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4965 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4966 img->width - 1, img->height - 1);
4967 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4968 img->width - 1, 0);
4969 XFreeGC (dpy, gc);
4971 if (img->mask)
4973 gc = XCreateGC (dpy, img->mask, 0, NULL);
4974 XSetForeground (dpy, gc, MaskForeground (f));
4975 XDrawLine (dpy, img->mask, gc, 0, 0,
4976 img->width - 1, img->height - 1);
4977 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4978 img->width - 1, 0);
4979 XFreeGC (dpy, gc);
4981 #endif /* !HAVE_NS */
4982 #else
4983 HDC hdc, bmpdc;
4984 HGDIOBJ prev;
4986 hdc = get_frame_dc (f);
4987 bmpdc = CreateCompatibleDC (hdc);
4988 release_frame_dc (f, hdc);
4990 prev = SelectObject (bmpdc, img->pixmap);
4992 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4993 MoveToEx (bmpdc, 0, 0, NULL);
4994 LineTo (bmpdc, img->width - 1, img->height - 1);
4995 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4996 LineTo (bmpdc, img->width - 1, 0);
4998 if (img->mask)
5000 SelectObject (bmpdc, img->mask);
5001 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5002 MoveToEx (bmpdc, 0, 0, NULL);
5003 LineTo (bmpdc, img->width - 1, img->height - 1);
5004 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5005 LineTo (bmpdc, img->width - 1, 0);
5007 SelectObject (bmpdc, prev);
5008 DeleteDC (bmpdc);
5009 #endif /* HAVE_NTGUI */
5014 /* Build a mask for image IMG which is used on frame F. FILE is the
5015 name of an image file, for error messages. HOW determines how to
5016 determine the background color of IMG. If it is a list '(R G B)',
5017 with R, G, and B being integers >= 0, take that as the color of the
5018 background. Otherwise, determine the background color of IMG
5019 heuristically. */
5021 static void
5022 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
5024 XImagePtr_or_DC ximg;
5025 #ifndef HAVE_NTGUI
5026 XImagePtr mask_img;
5027 #else
5028 HGDIOBJ prev;
5029 char *mask_img;
5030 int row_width;
5031 #endif /* HAVE_NTGUI */
5032 int x, y;
5033 bool use_img_background;
5034 unsigned long bg = 0;
5036 if (img->mask)
5037 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
5039 #ifndef HAVE_NTGUI
5040 #ifndef HAVE_NS
5041 /* Create an image and pixmap serving as mask. */
5042 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
5043 &mask_img, 1))
5044 return;
5045 #endif /* !HAVE_NS */
5046 #else
5047 /* Create the bit array serving as mask. */
5048 row_width = (img->width + 7) / 8;
5049 mask_img = xzalloc (row_width * img->height);
5050 #endif /* HAVE_NTGUI */
5052 /* Get the X image or create a memory device context for IMG. */
5053 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
5055 /* Determine the background color of ximg. If HOW is `(R G B)'
5056 take that as color. Otherwise, use the image's background color. */
5057 use_img_background = 1;
5059 if (CONSP (how))
5061 int rgb[3], i;
5063 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5065 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5066 how = XCDR (how);
5069 if (i == 3 && NILP (how))
5071 char color_name[30];
5072 sprintf (color_name, "#%04x%04x%04x",
5073 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
5074 bg = (
5075 #ifdef HAVE_NTGUI
5076 0x00ffffff & /* Filter out palette info. */
5077 #endif /* HAVE_NTGUI */
5078 x_alloc_image_color (f, img, build_string (color_name), 0));
5079 use_img_background = 0;
5083 if (use_img_background)
5084 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5086 /* Set all bits in mask_img to 1 whose color in ximg is different
5087 from the background color bg. */
5088 #ifndef HAVE_NTGUI
5089 for (y = 0; y < img->height; ++y)
5090 for (x = 0; x < img->width; ++x)
5091 #ifndef HAVE_NS
5092 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5093 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5094 #else
5095 if (XGetPixel (ximg, x, y) == bg)
5096 ns_set_alpha (ximg, x, y, 0);
5097 #endif /* HAVE_NS */
5098 #ifndef HAVE_NS
5099 /* Fill in the background_transparent field while we have the mask handy. */
5100 image_background_transparent (img, f, mask_img);
5102 /* Put mask_img into the image. */
5103 image_put_x_image (f, img, mask_img, 1);
5104 #endif /* !HAVE_NS */
5105 #else
5106 for (y = 0; y < img->height; ++y)
5107 for (x = 0; x < img->width; ++x)
5109 COLORREF p = GetPixel (ximg, x, y);
5110 if (p != bg)
5111 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5114 /* Create the mask image. */
5115 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5116 mask_img);
5117 /* Fill in the background_transparent field while we have the mask handy. */
5118 SelectObject (ximg, img->mask);
5119 image_background_transparent (img, f, ximg);
5121 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5122 xfree (mask_img);
5123 #endif /* HAVE_NTGUI */
5125 image_unget_x_image_or_dc (img, 0, ximg, prev);
5129 /***********************************************************************
5130 PBM (mono, gray, color)
5131 ***********************************************************************/
5133 static bool pbm_image_p (Lisp_Object object);
5134 static bool pbm_load (struct frame *f, struct image *img);
5136 /* Indices of image specification fields in gs_format, below. */
5138 enum pbm_keyword_index
5140 PBM_TYPE,
5141 PBM_FILE,
5142 PBM_DATA,
5143 PBM_ASCENT,
5144 PBM_MARGIN,
5145 PBM_RELIEF,
5146 PBM_ALGORITHM,
5147 PBM_HEURISTIC_MASK,
5148 PBM_MASK,
5149 PBM_FOREGROUND,
5150 PBM_BACKGROUND,
5151 PBM_LAST
5154 /* Vector of image_keyword structures describing the format
5155 of valid user-defined image specifications. */
5157 static const struct image_keyword pbm_format[PBM_LAST] =
5159 {":type", IMAGE_SYMBOL_VALUE, 1},
5160 {":file", IMAGE_STRING_VALUE, 0},
5161 {":data", IMAGE_STRING_VALUE, 0},
5162 {":ascent", IMAGE_ASCENT_VALUE, 0},
5163 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5164 {":relief", IMAGE_INTEGER_VALUE, 0},
5165 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5166 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5167 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5168 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5169 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5172 /* Structure describing the image type `pbm'. */
5174 static struct image_type pbm_type =
5176 SYMBOL_INDEX (Qpbm),
5177 pbm_image_p,
5178 pbm_load,
5179 x_clear_image,
5180 NULL,
5181 NULL
5185 /* Return true if OBJECT is a valid PBM image specification. */
5187 static bool
5188 pbm_image_p (Lisp_Object object)
5190 struct image_keyword fmt[PBM_LAST];
5192 memcpy (fmt, pbm_format, sizeof fmt);
5194 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5195 return 0;
5197 /* Must specify either :data or :file. */
5198 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5202 /* Get next char skipping comments in Netpbm header. Returns -1 at
5203 end of input. */
5205 static int
5206 pbm_next_char (unsigned char **s, unsigned char *end)
5208 int c = -1;
5210 while (*s < end && (c = *(*s)++, c == '#'))
5212 /* Skip to the next line break. */
5213 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5216 c = -1;
5219 return c;
5223 /* Scan a decimal number from *S and return it. Advance *S while
5224 reading the number. END is the end of the string. Value is -1 at
5225 end of input. */
5227 static int
5228 pbm_scan_number (unsigned char **s, unsigned char *end)
5230 int c = 0, val = -1;
5232 /* Skip white-space. */
5233 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5236 if (c_isdigit (c))
5238 /* Read decimal number. */
5239 val = c - '0';
5240 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5241 val = 10 * val + c - '0';
5244 return val;
5248 /* Load PBM image IMG for use on frame F. */
5250 static bool
5251 pbm_load (struct frame *f, struct image *img)
5253 bool raw_p;
5254 int x, y;
5255 int width, height, max_color_idx = 0;
5256 Lisp_Object file, specified_file;
5257 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5258 unsigned char *contents = NULL;
5259 unsigned char *end, *p;
5260 ptrdiff_t size;
5261 #ifdef USE_CAIRO
5262 unsigned char *data = 0;
5263 uint32_t *dataptr;
5264 #else
5265 XImagePtr ximg;
5266 #endif
5268 specified_file = image_spec_value (img->spec, QCfile, NULL);
5270 if (STRINGP (specified_file))
5272 file = x_find_image_file (specified_file);
5273 if (!STRINGP (file))
5275 image_error ("Cannot find image file "uLSQM"%s"uRSQM,
5276 specified_file);
5277 return 0;
5280 contents = slurp_file (SSDATA (file), &size);
5281 if (contents == NULL)
5283 image_error ("Error reading "uLSQM"%s"uRSQM, file);
5284 return 0;
5287 p = contents;
5288 end = contents + size;
5290 else
5292 Lisp_Object data;
5293 data = image_spec_value (img->spec, QCdata, NULL);
5294 if (!STRINGP (data))
5296 image_error ("Invalid image data "uLSQM"%s"uRSQM, data);
5297 return 0;
5299 p = SDATA (data);
5300 end = p + SBYTES (data);
5303 /* Check magic number. */
5304 if (end - p < 2 || *p++ != 'P')
5306 image_error ("Not a PBM image: "uLSQM"%s"uRSQM, img->spec);
5307 error:
5308 xfree (contents);
5309 img->pixmap = NO_PIXMAP;
5310 return 0;
5313 switch (*p++)
5315 case '1':
5316 raw_p = 0, type = PBM_MONO;
5317 break;
5319 case '2':
5320 raw_p = 0, type = PBM_GRAY;
5321 break;
5323 case '3':
5324 raw_p = 0, type = PBM_COLOR;
5325 break;
5327 case '4':
5328 raw_p = 1, type = PBM_MONO;
5329 break;
5331 case '5':
5332 raw_p = 1, type = PBM_GRAY;
5333 break;
5335 case '6':
5336 raw_p = 1, type = PBM_COLOR;
5337 break;
5339 default:
5340 image_error ("Not a PBM image: "uLSQM"%s"uRSQM, img->spec);
5341 goto error;
5344 /* Read width, height, maximum color-component. Characters
5345 starting with `#' up to the end of a line are ignored. */
5346 width = pbm_scan_number (&p, end);
5347 height = pbm_scan_number (&p, end);
5349 #ifdef USE_CAIRO
5350 data = (unsigned char *) xmalloc (width * height * 4);
5351 dataptr = (uint32_t *) data;
5352 #endif
5354 if (type != PBM_MONO)
5356 max_color_idx = pbm_scan_number (&p, end);
5357 if (max_color_idx > 65535 || max_color_idx < 0)
5359 image_error ("Unsupported maximum PBM color value");
5360 goto error;
5364 if (!check_image_size (f, width, height))
5366 image_error ("Invalid image size (see "uLSQM"max-image-size"uRSQM")");
5367 goto error;
5370 #ifndef USE_CAIRO
5371 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5372 goto error;
5373 #endif
5375 /* Initialize the color hash table. */
5376 init_color_table ();
5378 if (type == PBM_MONO)
5380 int c = 0, g;
5381 struct image_keyword fmt[PBM_LAST];
5382 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5383 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5384 #ifdef USE_CAIRO
5385 XColor xfg, xbg;
5386 int fga32, bga32;
5387 #endif
5388 /* Parse the image specification. */
5389 memcpy (fmt, pbm_format, sizeof fmt);
5390 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5392 /* Get foreground and background colors, maybe allocate colors. */
5393 #ifdef USE_CAIRO
5394 if (! fmt[PBM_FOREGROUND].count
5395 || ! STRINGP (fmt[PBM_FOREGROUND].value)
5396 || ! x_defined_color (f, SSDATA (fmt[PBM_FOREGROUND].value), &xfg, 0))
5398 xfg.pixel = fg;
5399 x_query_color (f, &xfg);
5401 fga32 = xcolor_to_argb32 (xfg);
5403 if (! fmt[PBM_BACKGROUND].count
5404 || ! STRINGP (fmt[PBM_BACKGROUND].value)
5405 || ! x_defined_color (f, SSDATA (fmt[PBM_BACKGROUND].value), &xbg, 0))
5407 xbg.pixel = bg;
5408 x_query_color (f, &xbg);
5410 bga32 = xcolor_to_argb32 (xbg);
5411 #else
5412 if (fmt[PBM_FOREGROUND].count
5413 && STRINGP (fmt[PBM_FOREGROUND].value))
5414 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5415 if (fmt[PBM_BACKGROUND].count
5416 && STRINGP (fmt[PBM_BACKGROUND].value))
5418 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5419 img->background = bg;
5420 img->background_valid = 1;
5422 #endif
5424 for (y = 0; y < height; ++y)
5425 for (x = 0; x < width; ++x)
5427 if (raw_p)
5429 if ((x & 7) == 0)
5431 if (p >= end)
5433 #ifdef USE_CAIRO
5434 xfree (data);
5435 #else
5436 x_destroy_x_image (ximg);
5437 #endif
5438 x_clear_image (f, img);
5439 image_error (("Invalid image size in image "
5440 uLSQM"%s"uRSQM),
5441 img->spec);
5442 goto error;
5444 c = *p++;
5446 g = c & 0x80;
5447 c <<= 1;
5449 else
5450 g = pbm_scan_number (&p, end);
5452 #ifdef USE_CAIRO
5453 *dataptr++ = g ? fga32 : bga32;
5454 #else
5455 XPutPixel (ximg, x, y, g ? fg : bg);
5456 #endif
5459 else
5461 int expected_size = height * width;
5462 if (max_color_idx > 255)
5463 expected_size *= 2;
5464 if (type == PBM_COLOR)
5465 expected_size *= 3;
5467 if (raw_p && p + expected_size > end)
5469 #ifdef USE_CAIRO
5470 xfree (data);
5471 #else
5472 x_destroy_x_image (ximg);
5473 #endif
5474 x_clear_image (f, img);
5475 image_error ("Invalid image size in image "uLSQM"%s"uRSQM,
5476 img->spec);
5477 goto error;
5480 for (y = 0; y < height; ++y)
5481 for (x = 0; x < width; ++x)
5483 int r, g, b;
5485 if (type == PBM_GRAY && raw_p)
5487 r = g = b = *p++;
5488 if (max_color_idx > 255)
5489 r = g = b = r * 256 + *p++;
5491 else if (type == PBM_GRAY)
5492 r = g = b = pbm_scan_number (&p, end);
5493 else if (raw_p)
5495 r = *p++;
5496 if (max_color_idx > 255)
5497 r = r * 256 + *p++;
5498 g = *p++;
5499 if (max_color_idx > 255)
5500 g = g * 256 + *p++;
5501 b = *p++;
5502 if (max_color_idx > 255)
5503 b = b * 256 + *p++;
5505 else
5507 r = pbm_scan_number (&p, end);
5508 g = pbm_scan_number (&p, end);
5509 b = pbm_scan_number (&p, end);
5512 if (r < 0 || g < 0 || b < 0)
5514 #ifdef USE_CAIRO
5515 xfree (data);
5516 #else
5517 x_destroy_x_image (ximg);
5518 #endif
5519 image_error ("Invalid pixel value in image "uLSQM"%s"uRSQM,
5520 img->spec);
5521 goto error;
5524 #ifdef USE_CAIRO
5525 r = (double) r * 255 / max_color_idx;
5526 g = (double) g * 255 / max_color_idx;
5527 b = (double) b * 255 / max_color_idx;
5528 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
5529 #else
5530 /* RGB values are now in the range 0..max_color_idx.
5531 Scale this to the range 0..0xffff supported by X. */
5532 r = (double) r * 65535 / max_color_idx;
5533 g = (double) g * 65535 / max_color_idx;
5534 b = (double) b * 65535 / max_color_idx;
5535 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5536 #endif
5540 #ifdef COLOR_TABLE_SUPPORT
5541 /* Store in IMG->colors the colors allocated for the image, and
5542 free the color table. */
5543 img->colors = colors_in_color_table (&img->ncolors);
5544 free_color_table ();
5545 #endif /* COLOR_TABLE_SUPPORT */
5547 img->width = width;
5548 img->height = height;
5550 /* Maybe fill in the background field while we have ximg handy. */
5552 #ifdef USE_CAIRO
5553 create_cairo_image_surface (img, data, width, height);
5554 #else
5555 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5556 /* Casting avoids a GCC warning. */
5557 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5559 /* Put ximg into the image. */
5560 image_put_x_image (f, img, ximg, 0);
5561 #endif
5563 /* X and W32 versions did it here, MAC version above. ++kfs
5564 img->width = width;
5565 img->height = height; */
5567 xfree (contents);
5568 return 1;
5572 /***********************************************************************
5574 ***********************************************************************/
5576 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5578 /* Function prototypes. */
5580 static bool png_image_p (Lisp_Object object);
5581 static bool png_load (struct frame *f, struct image *img);
5583 /* Indices of image specification fields in png_format, below. */
5585 enum png_keyword_index
5587 PNG_TYPE,
5588 PNG_DATA,
5589 PNG_FILE,
5590 PNG_ASCENT,
5591 PNG_MARGIN,
5592 PNG_RELIEF,
5593 PNG_ALGORITHM,
5594 PNG_HEURISTIC_MASK,
5595 PNG_MASK,
5596 PNG_BACKGROUND,
5597 PNG_LAST
5600 /* Vector of image_keyword structures describing the format
5601 of valid user-defined image specifications. */
5603 static const struct image_keyword png_format[PNG_LAST] =
5605 {":type", IMAGE_SYMBOL_VALUE, 1},
5606 {":data", IMAGE_STRING_VALUE, 0},
5607 {":file", IMAGE_STRING_VALUE, 0},
5608 {":ascent", IMAGE_ASCENT_VALUE, 0},
5609 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5610 {":relief", IMAGE_INTEGER_VALUE, 0},
5611 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5612 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5613 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5614 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5617 #if defined HAVE_NTGUI && defined WINDOWSNT
5618 static bool init_png_functions (void);
5619 #else
5620 #define init_png_functions NULL
5621 #endif
5623 /* Structure describing the image type `png'. */
5625 static struct image_type png_type =
5627 SYMBOL_INDEX (Qpng),
5628 png_image_p,
5629 png_load,
5630 x_clear_image,
5631 init_png_functions,
5632 NULL
5635 /* Return true if OBJECT is a valid PNG image specification. */
5637 static bool
5638 png_image_p (Lisp_Object object)
5640 struct image_keyword fmt[PNG_LAST];
5641 memcpy (fmt, png_format, sizeof fmt);
5643 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5644 return 0;
5646 /* Must specify either the :data or :file keyword. */
5647 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5650 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5653 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5655 # ifdef WINDOWSNT
5656 /* PNG library details. */
5658 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5659 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5660 DEF_DLL_FN (png_structp, png_create_read_struct,
5661 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5662 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5663 DEF_DLL_FN (void, png_destroy_read_struct,
5664 (png_structpp, png_infopp, png_infopp));
5665 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5666 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5667 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5668 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5669 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5670 int *, int *, int *, int *, int *));
5671 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5672 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5673 DEF_DLL_FN (void, png_set_expand, (png_structp));
5674 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5675 DEF_DLL_FN (void, png_set_background,
5676 (png_structp, png_color_16p, int, int, double));
5677 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5678 (png_structp, png_infop, png_color_16p *));
5679 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5680 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5681 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5682 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5683 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5684 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5686 # if (PNG_LIBPNG_VER >= 10500)
5687 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5688 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5689 (png_structp, png_longjmp_ptr, size_t));
5690 # endif /* libpng version >= 1.5 */
5692 static bool
5693 init_png_functions (void)
5695 HMODULE library;
5697 if (!(library = w32_delayed_load (Qpng)))
5698 return 0;
5700 LOAD_DLL_FN (library, png_get_io_ptr);
5701 LOAD_DLL_FN (library, png_sig_cmp);
5702 LOAD_DLL_FN (library, png_create_read_struct);
5703 LOAD_DLL_FN (library, png_create_info_struct);
5704 LOAD_DLL_FN (library, png_destroy_read_struct);
5705 LOAD_DLL_FN (library, png_set_read_fn);
5706 LOAD_DLL_FN (library, png_set_sig_bytes);
5707 LOAD_DLL_FN (library, png_read_info);
5708 LOAD_DLL_FN (library, png_get_IHDR);
5709 LOAD_DLL_FN (library, png_get_valid);
5710 LOAD_DLL_FN (library, png_set_strip_16);
5711 LOAD_DLL_FN (library, png_set_expand);
5712 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5713 LOAD_DLL_FN (library, png_set_background);
5714 LOAD_DLL_FN (library, png_get_bKGD);
5715 LOAD_DLL_FN (library, png_read_update_info);
5716 LOAD_DLL_FN (library, png_get_channels);
5717 LOAD_DLL_FN (library, png_get_rowbytes);
5718 LOAD_DLL_FN (library, png_read_image);
5719 LOAD_DLL_FN (library, png_read_end);
5720 LOAD_DLL_FN (library, png_error);
5722 # if (PNG_LIBPNG_VER >= 10500)
5723 LOAD_DLL_FN (library, png_longjmp);
5724 LOAD_DLL_FN (library, png_set_longjmp_fn);
5725 # endif /* libpng version >= 1.5 */
5727 return 1;
5730 # undef png_create_info_struct
5731 # undef png_create_read_struct
5732 # undef png_destroy_read_struct
5733 # undef png_error
5734 # undef png_get_bKGD
5735 # undef png_get_channels
5736 # undef png_get_IHDR
5737 # undef png_get_io_ptr
5738 # undef png_get_rowbytes
5739 # undef png_get_valid
5740 # undef png_longjmp
5741 # undef png_read_end
5742 # undef png_read_image
5743 # undef png_read_info
5744 # undef png_read_update_info
5745 # undef png_set_background
5746 # undef png_set_expand
5747 # undef png_set_gray_to_rgb
5748 # undef png_set_longjmp_fn
5749 # undef png_set_read_fn
5750 # undef png_set_sig_bytes
5751 # undef png_set_strip_16
5752 # undef png_sig_cmp
5754 # define png_create_info_struct fn_png_create_info_struct
5755 # define png_create_read_struct fn_png_create_read_struct
5756 # define png_destroy_read_struct fn_png_destroy_read_struct
5757 # define png_error fn_png_error
5758 # define png_get_bKGD fn_png_get_bKGD
5759 # define png_get_channels fn_png_get_channels
5760 # define png_get_IHDR fn_png_get_IHDR
5761 # define png_get_io_ptr fn_png_get_io_ptr
5762 # define png_get_rowbytes fn_png_get_rowbytes
5763 # define png_get_valid fn_png_get_valid
5764 # define png_longjmp fn_png_longjmp
5765 # define png_read_end fn_png_read_end
5766 # define png_read_image fn_png_read_image
5767 # define png_read_info fn_png_read_info
5768 # define png_read_update_info fn_png_read_update_info
5769 # define png_set_background fn_png_set_background
5770 # define png_set_expand fn_png_set_expand
5771 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5772 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5773 # define png_set_read_fn fn_png_set_read_fn
5774 # define png_set_sig_bytes fn_png_set_sig_bytes
5775 # define png_set_strip_16 fn_png_set_strip_16
5776 # define png_sig_cmp fn_png_sig_cmp
5778 # endif /* WINDOWSNT */
5780 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5781 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5782 Do not use sys_setjmp, as PNG supports only jmp_buf.
5783 It's OK if the longjmp substitute restores the signal mask. */
5784 # ifdef HAVE__SETJMP
5785 # define FAST_SETJMP(j) _setjmp (j)
5786 # define FAST_LONGJMP _longjmp
5787 # else
5788 # define FAST_SETJMP(j) setjmp (j)
5789 # define FAST_LONGJMP longjmp
5790 # endif
5792 # if PNG_LIBPNG_VER < 10500
5793 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5794 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5795 # else
5796 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5797 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5798 # define PNG_JMPBUF(ptr) \
5799 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5800 # endif
5802 /* Error and warning handlers installed when the PNG library
5803 is initialized. */
5805 static _Noreturn void
5806 my_png_error (png_struct *png_ptr, const char *msg)
5808 eassert (png_ptr != NULL);
5809 /* Avoid compiler warning about deprecated direct access to
5810 png_ptr's fields in libpng versions 1.4.x. */
5811 image_error ("PNG error: %s", build_string (msg));
5812 PNG_LONGJMP (png_ptr);
5816 static void
5817 my_png_warning (png_struct *png_ptr, const char *msg)
5819 eassert (png_ptr != NULL);
5820 image_error ("PNG warning: %s", build_string (msg));
5823 /* Memory source for PNG decoding. */
5825 struct png_memory_storage
5827 unsigned char *bytes; /* The data */
5828 ptrdiff_t len; /* How big is it? */
5829 ptrdiff_t index; /* Where are we? */
5833 /* Function set as reader function when reading PNG image from memory.
5834 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5835 bytes from the input to DATA. */
5837 static void
5838 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5840 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5842 if (length > tbr->len - tbr->index)
5843 png_error (png_ptr, "Read error");
5845 memcpy (data, tbr->bytes + tbr->index, length);
5846 tbr->index = tbr->index + length;
5850 /* Function set as reader function when reading PNG image from a file.
5851 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5852 bytes from the input to DATA. */
5854 static void
5855 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5857 FILE *fp = png_get_io_ptr (png_ptr);
5859 if (fread (data, 1, length, fp) < length)
5860 png_error (png_ptr, "Read error");
5864 /* Load PNG image IMG for use on frame F. Value is true if
5865 successful. */
5867 struct png_load_context
5869 /* These are members so that longjmp doesn't munge local variables. */
5870 png_struct *png_ptr;
5871 png_info *info_ptr;
5872 png_info *end_info;
5873 FILE *fp;
5874 png_byte *pixels;
5875 png_byte **rows;
5878 static bool
5879 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5881 Lisp_Object file, specified_file;
5882 Lisp_Object specified_data;
5883 int x, y;
5884 ptrdiff_t i;
5885 png_struct *png_ptr;
5886 png_info *info_ptr = NULL, *end_info = NULL;
5887 FILE *fp = NULL;
5888 png_byte sig[8];
5889 png_byte *pixels = NULL;
5890 png_byte **rows = NULL;
5891 png_uint_32 width, height;
5892 int bit_depth, color_type, interlace_type;
5893 png_byte channels;
5894 png_uint_32 row_bytes;
5895 bool transparent_p;
5896 struct png_memory_storage tbr; /* Data to be read */
5898 #ifdef USE_CAIRO
5899 unsigned char *data = 0;
5900 uint32_t *dataptr;
5901 #else
5902 XImagePtr ximg, mask_img = NULL;
5903 #endif
5905 /* Find out what file to load. */
5906 specified_file = image_spec_value (img->spec, QCfile, NULL);
5907 specified_data = image_spec_value (img->spec, QCdata, NULL);
5908 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
5910 if (NILP (specified_data))
5912 file = x_find_image_file (specified_file);
5913 if (!STRINGP (file))
5915 image_error ("Cannot find image file "uLSQM"%s"uRSQM,
5916 specified_file);
5917 return 0;
5920 /* Open the image file. */
5921 fp = emacs_fopen (SSDATA (file), "rb");
5922 if (!fp)
5924 image_error ("Cannot open image file "uLSQM"%s"uRSQM, file);
5925 return 0;
5928 /* Check PNG signature. */
5929 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5930 || png_sig_cmp (sig, 0, sizeof sig))
5932 fclose (fp);
5933 image_error ("Not a PNG file: "uLSQM"%s"uRSQM, file);
5934 return 0;
5937 else
5939 if (!STRINGP (specified_data))
5941 image_error ("Invalid image data "uLSQM"%s"uRSQM, specified_data);
5942 return 0;
5945 /* Read from memory. */
5946 tbr.bytes = SDATA (specified_data);
5947 tbr.len = SBYTES (specified_data);
5948 tbr.index = 0;
5950 /* Check PNG signature. */
5951 if (tbr.len < sizeof sig
5952 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5954 image_error ("Not a PNG image: "uLSQM"%s"uRSQM, img->spec);
5955 return 0;
5958 /* Need to skip past the signature. */
5959 tbr.bytes += sizeof (sig);
5962 /* Initialize read and info structs for PNG lib. */
5963 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5964 NULL, my_png_error,
5965 my_png_warning);
5966 if (png_ptr)
5968 info_ptr = png_create_info_struct (png_ptr);
5969 end_info = png_create_info_struct (png_ptr);
5972 c->png_ptr = png_ptr;
5973 c->info_ptr = info_ptr;
5974 c->end_info = end_info;
5975 c->fp = fp;
5976 c->pixels = pixels;
5977 c->rows = rows;
5979 if (! (info_ptr && end_info))
5981 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5982 png_ptr = 0;
5984 if (! png_ptr)
5986 if (fp) fclose (fp);
5987 return 0;
5990 /* Set error jump-back. We come back here when the PNG library
5991 detects an error. */
5992 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
5994 error:
5995 if (c->png_ptr)
5996 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5997 xfree (c->pixels);
5998 xfree (c->rows);
5999 if (c->fp)
6000 fclose (c->fp);
6001 return 0;
6004 /* Silence a bogus diagnostic; see GCC bug 54561. */
6005 IF_LINT (fp = c->fp);
6006 IF_LINT (specified_data = specified_data_volatile);
6008 /* Read image info. */
6009 if (!NILP (specified_data))
6010 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
6011 else
6012 png_set_read_fn (png_ptr, fp, png_read_from_file);
6014 png_set_sig_bytes (png_ptr, sizeof sig);
6015 png_read_info (png_ptr, info_ptr);
6016 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6017 &interlace_type, NULL, NULL);
6019 if (! (width <= INT_MAX && height <= INT_MAX
6020 && check_image_size (f, width, height)))
6022 image_error ("Invalid image size (see "uLSQM"max-image-size"uRSQM")");
6023 goto error;
6026 #ifndef USE_CAIRO
6027 /* Create the X image and pixmap now, so that the work below can be
6028 omitted if the image is too large for X. */
6029 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6030 goto error;
6031 #endif
6033 /* If image contains simply transparency data, we prefer to
6034 construct a clipping mask. */
6035 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6036 transparent_p = 1;
6037 else
6038 transparent_p = 0;
6040 /* This function is easier to write if we only have to handle
6041 one data format: RGB or RGBA with 8 bits per channel. Let's
6042 transform other formats into that format. */
6044 /* Strip more than 8 bits per channel. */
6045 if (bit_depth == 16)
6046 png_set_strip_16 (png_ptr);
6048 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6049 if available. */
6050 png_set_expand (png_ptr);
6052 /* Convert grayscale images to RGB. */
6053 if (color_type == PNG_COLOR_TYPE_GRAY
6054 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6055 png_set_gray_to_rgb (png_ptr);
6057 /* Handle alpha channel by combining the image with a background
6058 color. Do this only if a real alpha channel is supplied. For
6059 simple transparency, we prefer a clipping mask. */
6060 if (!transparent_p)
6062 /* png_color_16 *image_bg; */
6063 Lisp_Object specified_bg
6064 = image_spec_value (img->spec, QCbackground, NULL);
6065 XColor color;
6067 /* If the user specified a color, try to use it; if not, use the
6068 current frame background, ignoring any default background
6069 color set by the image. */
6070 if (STRINGP (specified_bg)
6071 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
6072 : (x_query_frame_background_color (f, &color), true))
6073 /* The user specified `:background', use that. */
6075 int shift = bit_depth == 16 ? 0 : 8;
6076 png_color_16 bg = { 0 };
6077 bg.red = color.red >> shift;
6078 bg.green = color.green >> shift;
6079 bg.blue = color.blue >> shift;
6081 png_set_background (png_ptr, &bg,
6082 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6086 /* Update info structure. */
6087 png_read_update_info (png_ptr, info_ptr);
6089 /* Get number of channels. Valid values are 1 for grayscale images
6090 and images with a palette, 2 for grayscale images with transparency
6091 information (alpha channel), 3 for RGB images, and 4 for RGB
6092 images with alpha channel, i.e. RGBA. If conversions above were
6093 sufficient we should only have 3 or 4 channels here. */
6094 channels = png_get_channels (png_ptr, info_ptr);
6095 eassert (channels == 3 || channels == 4);
6097 /* Number of bytes needed for one row of the image. */
6098 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
6100 /* Allocate memory for the image. */
6101 if (height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows
6102 || row_bytes > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height)
6103 memory_full (SIZE_MAX);
6104 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
6105 c->rows = rows = xmalloc (height * sizeof *rows);
6106 for (i = 0; i < height; ++i)
6107 rows[i] = pixels + i * row_bytes;
6109 /* Read the entire image. */
6110 png_read_image (png_ptr, rows);
6111 png_read_end (png_ptr, info_ptr);
6112 if (fp)
6114 fclose (fp);
6115 c->fp = NULL;
6118 #ifdef USE_CAIRO
6119 data = (unsigned char *) xmalloc (width * height * 4);
6120 dataptr = (uint32_t *) data;
6121 #else
6122 /* Create an image and pixmap serving as mask if the PNG image
6123 contains an alpha channel. */
6124 if (channels == 4
6125 && !transparent_p
6126 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
6127 &mask_img, 1))
6129 x_destroy_x_image (ximg);
6130 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
6131 goto error;
6133 #endif
6135 /* Fill the X image and mask from PNG data. */
6136 init_color_table ();
6138 for (y = 0; y < height; ++y)
6140 png_byte *p = rows[y];
6142 for (x = 0; x < width; ++x)
6144 int r, g, b;
6146 #ifdef USE_CAIRO
6147 int a = 0xff;
6148 r = *p++;
6149 g = *p++;
6150 b = *p++;
6151 if (channels == 4) a = *p++;
6152 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
6153 #else
6154 r = *p++ << 8;
6155 g = *p++ << 8;
6156 b = *p++ << 8;
6157 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6158 /* An alpha channel, aka mask channel, associates variable
6159 transparency with an image. Where other image formats
6160 support binary transparency---fully transparent or fully
6161 opaque---PNG allows up to 254 levels of partial transparency.
6162 The PNG library implements partial transparency by combining
6163 the image with a specified background color.
6165 I'm not sure how to handle this here nicely: because the
6166 background on which the image is displayed may change, for
6167 real alpha channel support, it would be necessary to create
6168 a new image for each possible background.
6170 What I'm doing now is that a mask is created if we have
6171 boolean transparency information. Otherwise I'm using
6172 the frame's background color to combine the image with. */
6174 if (channels == 4)
6176 if (mask_img)
6177 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6178 ++p;
6180 #endif
6184 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6185 /* Set IMG's background color from the PNG image, unless the user
6186 overrode it. */
6188 png_color_16 *bg;
6189 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6191 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6192 img->background_valid = 1;
6196 # ifdef COLOR_TABLE_SUPPORT
6197 /* Remember colors allocated for this image. */
6198 img->colors = colors_in_color_table (&img->ncolors);
6199 free_color_table ();
6200 # endif /* COLOR_TABLE_SUPPORT */
6202 /* Clean up. */
6203 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6204 xfree (rows);
6205 xfree (pixels);
6207 img->width = width;
6208 img->height = height;
6210 #ifdef USE_CAIRO
6211 create_cairo_image_surface (img, data, width, height);
6212 #else
6213 /* Maybe fill in the background field while we have ximg handy.
6214 Casting avoids a GCC warning. */
6215 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6217 /* Put ximg into the image. */
6218 image_put_x_image (f, img, ximg, 0);
6220 /* Same for the mask. */
6221 if (mask_img)
6223 /* Fill in the background_transparent field while we have the
6224 mask handy. Casting avoids a GCC warning. */
6225 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6227 image_put_x_image (f, img, mask_img, 1);
6229 #endif
6231 return 1;
6234 static bool
6235 png_load (struct frame *f, struct image *img)
6237 struct png_load_context c;
6238 return png_load_body (f, img, &c);
6241 #elif defined HAVE_NS
6243 static bool
6244 png_load (struct frame *f, struct image *img)
6246 return ns_load_image (f, img,
6247 image_spec_value (img->spec, QCfile, NULL),
6248 image_spec_value (img->spec, QCdata, NULL));
6252 #endif /* HAVE_NS */
6256 /***********************************************************************
6257 JPEG
6258 ***********************************************************************/
6260 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6262 static bool jpeg_image_p (Lisp_Object object);
6263 static bool jpeg_load (struct frame *f, struct image *img);
6265 /* Indices of image specification fields in gs_format, below. */
6267 enum jpeg_keyword_index
6269 JPEG_TYPE,
6270 JPEG_DATA,
6271 JPEG_FILE,
6272 JPEG_ASCENT,
6273 JPEG_MARGIN,
6274 JPEG_RELIEF,
6275 JPEG_ALGORITHM,
6276 JPEG_HEURISTIC_MASK,
6277 JPEG_MASK,
6278 JPEG_BACKGROUND,
6279 JPEG_LAST
6282 /* Vector of image_keyword structures describing the format
6283 of valid user-defined image specifications. */
6285 static const struct image_keyword jpeg_format[JPEG_LAST] =
6287 {":type", IMAGE_SYMBOL_VALUE, 1},
6288 {":data", IMAGE_STRING_VALUE, 0},
6289 {":file", IMAGE_STRING_VALUE, 0},
6290 {":ascent", IMAGE_ASCENT_VALUE, 0},
6291 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6292 {":relief", IMAGE_INTEGER_VALUE, 0},
6293 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6294 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6295 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6296 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6299 #if defined HAVE_NTGUI && defined WINDOWSNT
6300 static bool init_jpeg_functions (void);
6301 #else
6302 #define init_jpeg_functions NULL
6303 #endif
6305 /* Structure describing the image type `jpeg'. */
6307 static struct image_type jpeg_type =
6309 SYMBOL_INDEX (Qjpeg),
6310 jpeg_image_p,
6311 jpeg_load,
6312 x_clear_image,
6313 init_jpeg_functions,
6314 NULL
6317 /* Return true if OBJECT is a valid JPEG image specification. */
6319 static bool
6320 jpeg_image_p (Lisp_Object object)
6322 struct image_keyword fmt[JPEG_LAST];
6324 memcpy (fmt, jpeg_format, sizeof fmt);
6326 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6327 return 0;
6329 /* Must specify either the :data or :file keyword. */
6330 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6333 #endif /* HAVE_JPEG || HAVE_NS */
6335 #ifdef HAVE_JPEG
6337 /* Work around a warning about HAVE_STDLIB_H being redefined in
6338 jconfig.h. */
6339 # ifdef HAVE_STDLIB_H
6340 # undef HAVE_STDLIB_H
6341 # endif
6343 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6344 /* In older releases of the jpeg library, jpeglib.h will define boolean
6345 differently depending on __WIN32__, so make sure it is defined. */
6346 # define __WIN32__ 1
6347 # endif
6349 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6350 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6351 using the Windows boolean type instead of the jpeglib boolean type
6352 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6353 headers are included along with windows.h, so under Cygwin, jpeglib
6354 attempts to define a conflicting boolean type. Worse, forcing
6355 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6356 because it created an ABI incompatibility between the
6357 already-compiled jpeg library and the header interface definition.
6359 The best we can do is to define jpeglib's boolean type to a
6360 different name. This name, jpeg_boolean, remains in effect through
6361 the rest of image.c.
6363 # if defined CYGWIN && defined HAVE_NTGUI
6364 # define boolean jpeg_boolean
6365 # endif
6366 # include <jpeglib.h>
6367 # include <jerror.h>
6369 # ifdef WINDOWSNT
6371 /* JPEG library details. */
6372 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6373 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6374 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6375 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6376 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6377 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6378 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6379 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6380 (struct jpeg_error_mgr *));
6381 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6383 static bool
6384 init_jpeg_functions (void)
6386 HMODULE library;
6388 if (!(library = w32_delayed_load (Qjpeg)))
6389 return 0;
6391 LOAD_DLL_FN (library, jpeg_finish_decompress);
6392 LOAD_DLL_FN (library, jpeg_read_scanlines);
6393 LOAD_DLL_FN (library, jpeg_start_decompress);
6394 LOAD_DLL_FN (library, jpeg_read_header);
6395 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6396 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6397 LOAD_DLL_FN (library, jpeg_std_error);
6398 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6399 return 1;
6402 # undef jpeg_CreateDecompress
6403 # undef jpeg_destroy_decompress
6404 # undef jpeg_finish_decompress
6405 # undef jpeg_read_header
6406 # undef jpeg_read_scanlines
6407 # undef jpeg_resync_to_restart
6408 # undef jpeg_start_decompress
6409 # undef jpeg_std_error
6411 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6412 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6413 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6414 # define jpeg_read_header fn_jpeg_read_header
6415 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6416 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6417 # define jpeg_start_decompress fn_jpeg_start_decompress
6418 # define jpeg_std_error fn_jpeg_std_error
6420 /* Wrapper since we can't directly assign the function pointer
6421 to another function pointer that was declared more completely easily. */
6422 static boolean
6423 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6425 return jpeg_resync_to_restart (cinfo, desired);
6427 # undef jpeg_resync_to_restart
6428 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6430 # endif /* WINDOWSNT */
6432 struct my_jpeg_error_mgr
6434 struct jpeg_error_mgr pub;
6435 sys_jmp_buf setjmp_buffer;
6437 /* The remaining members are so that longjmp doesn't munge local
6438 variables. */
6439 struct jpeg_decompress_struct cinfo;
6440 enum
6442 MY_JPEG_ERROR_EXIT,
6443 MY_JPEG_INVALID_IMAGE_SIZE,
6444 MY_JPEG_CANNOT_CREATE_X
6445 } failure_code;
6449 static _Noreturn void
6450 my_error_exit (j_common_ptr cinfo)
6452 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6453 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6454 sys_longjmp (mgr->setjmp_buffer, 1);
6458 /* Init source method for JPEG data source manager. Called by
6459 jpeg_read_header() before any data is actually read. See
6460 libjpeg.doc from the JPEG lib distribution. */
6462 static void
6463 our_common_init_source (j_decompress_ptr cinfo)
6468 /* Method to terminate data source. Called by
6469 jpeg_finish_decompress() after all data has been processed. */
6471 static void
6472 our_common_term_source (j_decompress_ptr cinfo)
6477 /* Fill input buffer method for JPEG data source manager. Called
6478 whenever more data is needed. We read the whole image in one step,
6479 so this only adds a fake end of input marker at the end. */
6481 static JOCTET our_memory_buffer[2];
6483 static boolean
6484 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6486 /* Insert a fake EOI marker. */
6487 struct jpeg_source_mgr *src = cinfo->src;
6489 our_memory_buffer[0] = (JOCTET) 0xFF;
6490 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6492 src->next_input_byte = our_memory_buffer;
6493 src->bytes_in_buffer = 2;
6494 return 1;
6498 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6499 is the JPEG data source manager. */
6501 static void
6502 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6504 struct jpeg_source_mgr *src = cinfo->src;
6506 if (src)
6508 if (num_bytes > src->bytes_in_buffer)
6509 ERREXIT (cinfo, JERR_INPUT_EOF);
6511 src->bytes_in_buffer -= num_bytes;
6512 src->next_input_byte += num_bytes;
6517 /* Set up the JPEG lib for reading an image from DATA which contains
6518 LEN bytes. CINFO is the decompression info structure created for
6519 reading the image. */
6521 static void
6522 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6524 struct jpeg_source_mgr *src = cinfo->src;
6526 if (! src)
6528 /* First time for this JPEG object? */
6529 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6530 JPOOL_PERMANENT, sizeof *src);
6531 cinfo->src = src;
6532 src->next_input_byte = data;
6535 src->init_source = our_common_init_source;
6536 src->fill_input_buffer = our_memory_fill_input_buffer;
6537 src->skip_input_data = our_memory_skip_input_data;
6538 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6539 src->term_source = our_common_term_source;
6540 src->bytes_in_buffer = len;
6541 src->next_input_byte = data;
6545 struct jpeg_stdio_mgr
6547 struct jpeg_source_mgr mgr;
6548 boolean finished;
6549 FILE *file;
6550 JOCTET *buffer;
6554 /* Size of buffer to read JPEG from file.
6555 Not too big, as we want to use alloc_small. */
6556 #define JPEG_STDIO_BUFFER_SIZE 8192
6559 /* Fill input buffer method for JPEG data source manager. Called
6560 whenever more data is needed. The data is read from a FILE *. */
6562 static boolean
6563 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6565 struct jpeg_stdio_mgr *src;
6567 src = (struct jpeg_stdio_mgr *) cinfo->src;
6568 if (!src->finished)
6570 ptrdiff_t bytes;
6572 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6573 if (bytes > 0)
6574 src->mgr.bytes_in_buffer = bytes;
6575 else
6577 WARNMS (cinfo, JWRN_JPEG_EOF);
6578 src->finished = 1;
6579 src->buffer[0] = (JOCTET) 0xFF;
6580 src->buffer[1] = (JOCTET) JPEG_EOI;
6581 src->mgr.bytes_in_buffer = 2;
6583 src->mgr.next_input_byte = src->buffer;
6586 return 1;
6590 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6591 is the JPEG data source manager. */
6593 static void
6594 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6596 struct jpeg_stdio_mgr *src;
6597 src = (struct jpeg_stdio_mgr *) cinfo->src;
6599 while (num_bytes > 0 && !src->finished)
6601 if (num_bytes <= src->mgr.bytes_in_buffer)
6603 src->mgr.bytes_in_buffer -= num_bytes;
6604 src->mgr.next_input_byte += num_bytes;
6605 break;
6607 else
6609 num_bytes -= src->mgr.bytes_in_buffer;
6610 src->mgr.bytes_in_buffer = 0;
6611 src->mgr.next_input_byte = NULL;
6613 our_stdio_fill_input_buffer (cinfo);
6619 /* Set up the JPEG lib for reading an image from a FILE *.
6620 CINFO is the decompression info structure created for
6621 reading the image. */
6623 static void
6624 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6626 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6628 if (! src)
6630 /* First time for this JPEG object? */
6631 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6632 JPOOL_PERMANENT, sizeof *src);
6633 cinfo->src = (struct jpeg_source_mgr *) src;
6634 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6635 JPOOL_PERMANENT,
6636 JPEG_STDIO_BUFFER_SIZE);
6639 src->file = fp;
6640 src->finished = 0;
6641 src->mgr.init_source = our_common_init_source;
6642 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6643 src->mgr.skip_input_data = our_stdio_skip_input_data;
6644 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6645 src->mgr.term_source = our_common_term_source;
6646 src->mgr.bytes_in_buffer = 0;
6647 src->mgr.next_input_byte = NULL;
6650 /* Load image IMG for use on frame F. Patterned after example.c
6651 from the JPEG lib. */
6653 static bool
6654 jpeg_load_body (struct frame *f, struct image *img,
6655 struct my_jpeg_error_mgr *mgr)
6657 Lisp_Object file, specified_file;
6658 Lisp_Object specified_data;
6659 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6660 FILE * IF_LINT (volatile) fp = NULL;
6661 JSAMPARRAY buffer;
6662 int row_stride, x, y;
6663 unsigned long *colors;
6664 int width, height;
6665 int i, ir, ig, ib;
6666 #ifndef USE_CAIRO
6667 XImagePtr ximg = NULL;
6668 #endif
6670 /* Open the JPEG file. */
6671 specified_file = image_spec_value (img->spec, QCfile, NULL);
6672 specified_data = image_spec_value (img->spec, QCdata, NULL);
6673 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
6675 if (NILP (specified_data))
6677 file = x_find_image_file (specified_file);
6678 if (!STRINGP (file))
6680 image_error ("Cannot find image file "uLSQM"%s"uRSQM,
6681 specified_file);
6682 return 0;
6685 fp = emacs_fopen (SSDATA (file), "rb");
6686 if (fp == NULL)
6688 image_error ("Cannot open "uLSQM"%s"uRSQM, file);
6689 return 0;
6692 else if (!STRINGP (specified_data))
6694 image_error ("Invalid image data "uLSQM"%s"uRSQM, specified_data);
6695 return 0;
6698 /* Customize libjpeg's error handling to call my_error_exit when an
6699 error is detected. This function will perform a longjmp. */
6700 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6701 mgr->pub.error_exit = my_error_exit;
6702 if (sys_setjmp (mgr->setjmp_buffer))
6704 switch (mgr->failure_code)
6706 case MY_JPEG_ERROR_EXIT:
6708 char buf[JMSG_LENGTH_MAX];
6709 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6710 image_error ("Error reading JPEG image "uLSQM"%s"uRSQM": %s",
6711 img->spec, build_string (buf));
6712 break;
6715 case MY_JPEG_INVALID_IMAGE_SIZE:
6716 image_error ("Invalid image size (see "
6717 uLSQM"max-image-size"uRSQM")");
6718 break;
6720 case MY_JPEG_CANNOT_CREATE_X:
6721 break;
6724 /* Close the input file and destroy the JPEG object. */
6725 if (fp)
6726 fclose (fp);
6727 jpeg_destroy_decompress (&mgr->cinfo);
6729 /* If we already have an XImage, free that. */
6730 #ifndef USE_CAIRO
6731 x_destroy_x_image (ximg);
6732 #endif
6733 /* Free pixmap and colors. */
6734 x_clear_image (f, img);
6735 return 0;
6738 /* Silence a bogus diagnostic; see GCC bug 54561. */
6739 IF_LINT (specified_data = specified_data_volatile);
6741 /* Create the JPEG decompression object. Let it read from fp.
6742 Read the JPEG image header. */
6743 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6745 if (NILP (specified_data))
6746 jpeg_file_src (&mgr->cinfo, fp);
6747 else
6748 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6749 SBYTES (specified_data));
6751 jpeg_read_header (&mgr->cinfo, 1);
6753 /* Customize decompression so that color quantization will be used.
6754 Start decompression. */
6755 mgr->cinfo.quantize_colors = 1;
6756 jpeg_start_decompress (&mgr->cinfo);
6757 width = img->width = mgr->cinfo.output_width;
6758 height = img->height = mgr->cinfo.output_height;
6760 if (!check_image_size (f, width, height))
6762 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6763 sys_longjmp (mgr->setjmp_buffer, 1);
6766 #ifndef USE_CAIRO
6767 /* Create X image and pixmap. */
6768 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6770 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6771 sys_longjmp (mgr->setjmp_buffer, 1);
6773 #endif
6775 /* Allocate colors. When color quantization is used,
6776 mgr->cinfo.actual_number_of_colors has been set with the number of
6777 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6778 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6779 No more than 255 colors will be generated. */
6780 USE_SAFE_ALLOCA;
6782 if (mgr->cinfo.out_color_components > 2)
6783 ir = 0, ig = 1, ib = 2;
6784 else if (mgr->cinfo.out_color_components > 1)
6785 ir = 0, ig = 1, ib = 0;
6786 else
6787 ir = 0, ig = 0, ib = 0;
6789 #ifndef CAIRO
6790 /* Use the color table mechanism because it handles colors that
6791 cannot be allocated nicely. Such colors will be replaced with
6792 a default color, and we don't have to care about which colors
6793 can be freed safely, and which can't. */
6794 init_color_table ();
6795 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6797 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6799 /* Multiply RGB values with 255 because X expects RGB values
6800 in the range 0..0xffff. */
6801 int r = mgr->cinfo.colormap[ir][i] << 8;
6802 int g = mgr->cinfo.colormap[ig][i] << 8;
6803 int b = mgr->cinfo.colormap[ib][i] << 8;
6804 colors[i] = lookup_rgb_color (f, r, g, b);
6806 #endif
6808 #ifdef COLOR_TABLE_SUPPORT
6809 /* Remember those colors actually allocated. */
6810 img->colors = colors_in_color_table (&img->ncolors);
6811 free_color_table ();
6812 #endif /* COLOR_TABLE_SUPPORT */
6815 /* Read pixels. */
6816 row_stride = width * mgr->cinfo.output_components;
6817 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6818 JPOOL_IMAGE, row_stride, 1);
6819 #ifdef USE_CAIRO
6821 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
6822 uint32_t *dataptr = (uint32_t *) data;
6823 int r, g, b;
6825 for (y = 0; y < height; ++y)
6827 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6829 for (x = 0; x < width; ++x)
6831 i = buffer[0][x];
6832 r = mgr->cinfo.colormap[ir][i];
6833 g = mgr->cinfo.colormap[ig][i];
6834 b = mgr->cinfo.colormap[ib][i];
6835 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
6839 create_cairo_image_surface (img, data, width, height);
6841 #else
6842 for (y = 0; y < height; ++y)
6844 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6845 for (x = 0; x < mgr->cinfo.output_width; ++x)
6846 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6848 #endif
6850 /* Clean up. */
6851 jpeg_finish_decompress (&mgr->cinfo);
6852 jpeg_destroy_decompress (&mgr->cinfo);
6853 if (fp)
6854 fclose (fp);
6856 #ifndef USE_CAIRO
6857 /* Maybe fill in the background field while we have ximg handy. */
6858 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6859 /* Casting avoids a GCC warning. */
6860 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6862 /* Put ximg into the image. */
6863 image_put_x_image (f, img, ximg, 0);
6864 #endif
6865 SAFE_FREE ();
6866 return 1;
6869 static bool
6870 jpeg_load (struct frame *f, struct image *img)
6872 struct my_jpeg_error_mgr mgr;
6873 return jpeg_load_body (f, img, &mgr);
6876 #else /* HAVE_JPEG */
6878 #ifdef HAVE_NS
6879 static bool
6880 jpeg_load (struct frame *f, struct image *img)
6882 return ns_load_image (f, img,
6883 image_spec_value (img->spec, QCfile, NULL),
6884 image_spec_value (img->spec, QCdata, NULL));
6886 #endif /* HAVE_NS */
6888 #endif /* !HAVE_JPEG */
6892 /***********************************************************************
6893 TIFF
6894 ***********************************************************************/
6896 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6898 static bool tiff_image_p (Lisp_Object object);
6899 static bool tiff_load (struct frame *f, struct image *img);
6901 /* Indices of image specification fields in tiff_format, below. */
6903 enum tiff_keyword_index
6905 TIFF_TYPE,
6906 TIFF_DATA,
6907 TIFF_FILE,
6908 TIFF_ASCENT,
6909 TIFF_MARGIN,
6910 TIFF_RELIEF,
6911 TIFF_ALGORITHM,
6912 TIFF_HEURISTIC_MASK,
6913 TIFF_MASK,
6914 TIFF_BACKGROUND,
6915 TIFF_INDEX,
6916 TIFF_LAST
6919 /* Vector of image_keyword structures describing the format
6920 of valid user-defined image specifications. */
6922 static const struct image_keyword tiff_format[TIFF_LAST] =
6924 {":type", IMAGE_SYMBOL_VALUE, 1},
6925 {":data", IMAGE_STRING_VALUE, 0},
6926 {":file", IMAGE_STRING_VALUE, 0},
6927 {":ascent", IMAGE_ASCENT_VALUE, 0},
6928 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6929 {":relief", IMAGE_INTEGER_VALUE, 0},
6930 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6931 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6932 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6933 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6934 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6937 #if defined HAVE_NTGUI && defined WINDOWSNT
6938 static bool init_tiff_functions (void);
6939 #else
6940 #define init_tiff_functions NULL
6941 #endif
6943 /* Structure describing the image type `tiff'. */
6945 static struct image_type tiff_type =
6947 SYMBOL_INDEX (Qtiff),
6948 tiff_image_p,
6949 tiff_load,
6950 x_clear_image,
6951 init_tiff_functions,
6952 NULL
6955 /* Return true if OBJECT is a valid TIFF image specification. */
6957 static bool
6958 tiff_image_p (Lisp_Object object)
6960 struct image_keyword fmt[TIFF_LAST];
6961 memcpy (fmt, tiff_format, sizeof fmt);
6963 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6964 return 0;
6966 /* Must specify either the :data or :file keyword. */
6967 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6970 #endif /* HAVE_TIFF || HAVE_NS */
6972 #ifdef HAVE_TIFF
6974 # include <tiffio.h>
6976 # ifdef WINDOWSNT
6978 /* TIFF library details. */
6979 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6980 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6981 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
6982 DEF_DLL_FN (TIFF *, TIFFClientOpen,
6983 (const char *, const char *, thandle_t, TIFFReadWriteProc,
6984 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6985 TIFFMapFileProc, TIFFUnmapFileProc));
6986 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6987 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6988 DEF_DLL_FN (void, TIFFClose, (TIFF *));
6989 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6991 static bool
6992 init_tiff_functions (void)
6994 HMODULE library;
6996 if (!(library = w32_delayed_load (Qtiff)))
6997 return 0;
6999 LOAD_DLL_FN (library, TIFFSetErrorHandler);
7000 LOAD_DLL_FN (library, TIFFSetWarningHandler);
7001 LOAD_DLL_FN (library, TIFFOpen);
7002 LOAD_DLL_FN (library, TIFFClientOpen);
7003 LOAD_DLL_FN (library, TIFFGetField);
7004 LOAD_DLL_FN (library, TIFFReadRGBAImage);
7005 LOAD_DLL_FN (library, TIFFClose);
7006 LOAD_DLL_FN (library, TIFFSetDirectory);
7007 return 1;
7010 # undef TIFFClientOpen
7011 # undef TIFFClose
7012 # undef TIFFGetField
7013 # undef TIFFOpen
7014 # undef TIFFReadRGBAImage
7015 # undef TIFFSetDirectory
7016 # undef TIFFSetErrorHandler
7017 # undef TIFFSetWarningHandler
7019 # define TIFFClientOpen fn_TIFFClientOpen
7020 # define TIFFClose fn_TIFFClose
7021 # define TIFFGetField fn_TIFFGetField
7022 # define TIFFOpen fn_TIFFOpen
7023 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7024 # define TIFFSetDirectory fn_TIFFSetDirectory
7025 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7026 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7028 # endif /* WINDOWSNT */
7031 /* Reading from a memory buffer for TIFF images Based on the PNG
7032 memory source, but we have to provide a lot of extra functions.
7033 Blah.
7035 We really only need to implement read and seek, but I am not
7036 convinced that the TIFF library is smart enough not to destroy
7037 itself if we only hand it the function pointers we need to
7038 override. */
7040 typedef struct
7042 unsigned char *bytes;
7043 ptrdiff_t len;
7044 ptrdiff_t index;
7046 tiff_memory_source;
7048 static tsize_t
7049 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7051 tiff_memory_source *src = (tiff_memory_source *) data;
7053 size = min (size, src->len - src->index);
7054 memcpy (buf, src->bytes + src->index, size);
7055 src->index += size;
7056 return size;
7059 static tsize_t
7060 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7062 return -1;
7065 static toff_t
7066 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
7068 tiff_memory_source *src = (tiff_memory_source *) data;
7069 ptrdiff_t idx;
7071 switch (whence)
7073 case SEEK_SET: /* Go from beginning of source. */
7074 idx = off;
7075 break;
7077 case SEEK_END: /* Go from end of source. */
7078 idx = src->len + off;
7079 break;
7081 case SEEK_CUR: /* Go from current position. */
7082 idx = src->index + off;
7083 break;
7085 default: /* Invalid `whence'. */
7086 return -1;
7089 if (idx > src->len || idx < 0)
7090 return -1;
7092 src->index = idx;
7093 return src->index;
7096 static int
7097 tiff_close_memory (thandle_t data)
7099 /* NOOP */
7100 return 0;
7103 static int
7104 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
7106 /* It is already _IN_ memory. */
7107 return 0;
7110 static void
7111 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
7113 /* We don't need to do this. */
7116 static toff_t
7117 tiff_size_of_memory (thandle_t data)
7119 return ((tiff_memory_source *) data)->len;
7122 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7123 compiler error compiling tiff_handler, see Bugzilla bug #17406
7124 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7125 this function as external works around that problem. */
7126 # if defined (__MINGW32__) && __GNUC__ == 3
7127 # define MINGW_STATIC
7128 # else
7129 # define MINGW_STATIC static
7130 # endif
7132 MINGW_STATIC void
7133 tiff_handler (const char *, const char *, const char *, va_list)
7134 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7135 MINGW_STATIC void
7136 tiff_handler (const char *log_format, const char *title,
7137 const char *format, va_list ap)
7139 /* doprnt is not suitable here, as TIFF handlers are called from
7140 libtiff and are passed arbitrary printf directives. Instead, use
7141 vsnprintf, taking care to be portable to nonstandard environments
7142 where vsnprintf returns -1 on buffer overflow. Since it's just a
7143 log entry, it's OK to truncate it. */
7144 char buf[4000];
7145 int len = vsnprintf (buf, sizeof buf, format, ap);
7146 add_to_log (log_format, build_string (title),
7147 make_string (buf, max (0, min (len, sizeof buf - 1))));
7149 # undef MINGW_STATIC
7151 static void tiff_error_handler (const char *, const char *, va_list)
7152 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7153 static void
7154 tiff_error_handler (const char *title, const char *format, va_list ap)
7156 tiff_handler ("TIFF error: %s %s", title, format, ap);
7160 static void tiff_warning_handler (const char *, const char *, va_list)
7161 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7162 static void
7163 tiff_warning_handler (const char *title, const char *format, va_list ap)
7165 tiff_handler ("TIFF warning: %s %s", title, format, ap);
7169 /* Load TIFF image IMG for use on frame F. Value is true if
7170 successful. */
7172 static bool
7173 tiff_load (struct frame *f, struct image *img)
7175 Lisp_Object file, specified_file;
7176 Lisp_Object specified_data;
7177 TIFF *tiff;
7178 int width, height, x, y, count;
7179 uint32 *buf;
7180 int rc;
7181 XImagePtr ximg;
7182 tiff_memory_source memsrc;
7183 Lisp_Object image;
7185 specified_file = image_spec_value (img->spec, QCfile, NULL);
7186 specified_data = image_spec_value (img->spec, QCdata, NULL);
7188 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
7189 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7191 if (NILP (specified_data))
7193 /* Read from a file */
7194 file = x_find_image_file (specified_file);
7195 if (!STRINGP (file))
7197 image_error ("Cannot find image file "uLSQM"%s"uRSQM,
7198 specified_file);
7199 return 0;
7201 # ifdef WINDOWSNT
7202 file = ansi_encode_filename (file);
7203 # endif
7205 /* Try to open the image file. */
7206 tiff = TIFFOpen (SSDATA (file), "r");
7207 if (tiff == NULL)
7209 image_error ("Cannot open "uLSQM"%s"uRSQM, file);
7210 return 0;
7213 else
7215 if (!STRINGP (specified_data))
7217 image_error ("Invalid image data "uLSQM"%s"uRSQM, specified_data);
7218 return 0;
7221 /* Memory source! */
7222 memsrc.bytes = SDATA (specified_data);
7223 memsrc.len = SBYTES (specified_data);
7224 memsrc.index = 0;
7226 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7227 tiff_read_from_memory,
7228 tiff_write_from_memory,
7229 tiff_seek_in_memory,
7230 tiff_close_memory,
7231 tiff_size_of_memory,
7232 tiff_mmap_memory,
7233 tiff_unmap_memory);
7235 if (!tiff)
7237 image_error ("Cannot open memory source for "uLSQM"%s"uRSQM,
7238 img->spec);
7239 return 0;
7243 image = image_spec_value (img->spec, QCindex, NULL);
7244 if (INTEGERP (image))
7246 EMACS_INT ino = XFASTINT (image);
7247 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7248 && TIFFSetDirectory (tiff, ino)))
7250 image_error
7251 ("Invalid image number "uLSQM"%s"uRSQM" in image "uLSQM"%s"uRSQM,
7252 image, img->spec);
7253 TIFFClose (tiff);
7254 return 0;
7258 /* Get width and height of the image, and allocate a raster buffer
7259 of width x height 32-bit values. */
7260 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7261 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7263 if (!check_image_size (f, width, height))
7265 image_error ("Invalid image size (see "uLSQM"max-image-size"uRSQM")");
7266 TIFFClose (tiff);
7267 return 0;
7270 /* Create the X image and pixmap. */
7271 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7272 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7273 &ximg, 0)))
7275 TIFFClose (tiff);
7276 return 0;
7279 buf = xmalloc (sizeof *buf * width * height);
7281 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7283 /* Count the number of images in the file. */
7284 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7285 continue;
7287 if (count > 1)
7288 img->lisp_data = Fcons (Qcount,
7289 Fcons (make_number (count),
7290 img->lisp_data));
7292 TIFFClose (tiff);
7293 if (!rc)
7295 image_error ("Error reading TIFF image "uLSQM"%s"uRSQM, img->spec);
7296 xfree (buf);
7297 return 0;
7300 #ifdef USE_CAIRO
7302 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
7303 uint32_t *dataptr = (uint32_t *) data;
7304 int r, g, b, a;
7306 for (y = 0; y < height; ++y)
7308 uint32 *row = buf + (height - 1 - y) * width;
7309 for (x = 0; x < width; ++x)
7311 uint32 abgr = row[x];
7312 int r = TIFFGetR (abgr);
7313 int g = TIFFGetG (abgr);
7314 int b = TIFFGetB (abgr);
7315 int a = TIFFGetA (abgr);
7316 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
7320 create_cairo_image_surface (img, data, width, height);
7322 #else
7323 /* Initialize the color table. */
7324 init_color_table ();
7326 /* Process the pixel raster. Origin is in the lower-left corner. */
7327 for (y = 0; y < height; ++y)
7329 uint32 *row = buf + y * width;
7331 for (x = 0; x < width; ++x)
7333 uint32 abgr = row[x];
7334 int r = TIFFGetR (abgr) << 8;
7335 int g = TIFFGetG (abgr) << 8;
7336 int b = TIFFGetB (abgr) << 8;
7337 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7341 # ifdef COLOR_TABLE_SUPPORT
7342 /* Remember the colors allocated for the image. Free the color table. */
7343 img->colors = colors_in_color_table (&img->ncolors);
7344 free_color_table ();
7345 # endif /* COLOR_TABLE_SUPPORT */
7347 img->width = width;
7348 img->height = height;
7350 /* Maybe fill in the background field while we have ximg handy. */
7351 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7352 /* Casting avoids a GCC warning on W32. */
7353 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7355 /* Put ximg into the image. */
7356 image_put_x_image (f, img, ximg, 0);
7358 #endif /* ! USE_CAIRO */
7360 xfree (buf);
7361 return 1;
7364 #elif defined HAVE_NS
7366 static bool
7367 tiff_load (struct frame *f, struct image *img)
7369 return ns_load_image (f, img,
7370 image_spec_value (img->spec, QCfile, NULL),
7371 image_spec_value (img->spec, QCdata, NULL));
7374 #endif
7378 /***********************************************************************
7380 ***********************************************************************/
7382 #if defined (HAVE_GIF) || defined (HAVE_NS)
7384 static bool gif_image_p (Lisp_Object object);
7385 static bool gif_load (struct frame *f, struct image *img);
7386 static void gif_clear_image (struct frame *f, struct image *img);
7388 /* Indices of image specification fields in gif_format, below. */
7390 enum gif_keyword_index
7392 GIF_TYPE,
7393 GIF_DATA,
7394 GIF_FILE,
7395 GIF_ASCENT,
7396 GIF_MARGIN,
7397 GIF_RELIEF,
7398 GIF_ALGORITHM,
7399 GIF_HEURISTIC_MASK,
7400 GIF_MASK,
7401 GIF_IMAGE,
7402 GIF_BACKGROUND,
7403 GIF_LAST
7406 /* Vector of image_keyword structures describing the format
7407 of valid user-defined image specifications. */
7409 static const struct image_keyword gif_format[GIF_LAST] =
7411 {":type", IMAGE_SYMBOL_VALUE, 1},
7412 {":data", IMAGE_STRING_VALUE, 0},
7413 {":file", IMAGE_STRING_VALUE, 0},
7414 {":ascent", IMAGE_ASCENT_VALUE, 0},
7415 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7416 {":relief", IMAGE_INTEGER_VALUE, 0},
7417 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7418 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7419 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7420 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7421 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7424 #if defined HAVE_NTGUI && defined WINDOWSNT
7425 static bool init_gif_functions (void);
7426 #else
7427 #define init_gif_functions NULL
7428 #endif
7430 /* Structure describing the image type `gif'. */
7432 static struct image_type gif_type =
7434 SYMBOL_INDEX (Qgif),
7435 gif_image_p,
7436 gif_load,
7437 gif_clear_image,
7438 init_gif_functions,
7439 NULL
7442 /* Free X resources of GIF image IMG which is used on frame F. */
7444 static void
7445 gif_clear_image (struct frame *f, struct image *img)
7447 img->lisp_data = Qnil;
7448 x_clear_image (f, img);
7451 /* Return true if OBJECT is a valid GIF image specification. */
7453 static bool
7454 gif_image_p (Lisp_Object object)
7456 struct image_keyword fmt[GIF_LAST];
7457 memcpy (fmt, gif_format, sizeof fmt);
7459 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7460 return 0;
7462 /* Must specify either the :data or :file keyword. */
7463 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7466 #endif /* HAVE_GIF */
7468 #ifdef HAVE_GIF
7470 # ifdef HAVE_NTGUI
7472 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7473 Undefine before redefining to avoid a preprocessor warning. */
7474 # ifdef DrawText
7475 # undef DrawText
7476 # endif
7477 /* avoid conflict with QuickdrawText.h */
7478 # define DrawText gif_DrawText
7479 # include <gif_lib.h>
7480 # undef DrawText
7482 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7483 # ifndef GIFLIB_MINOR
7484 # define GIFLIB_MINOR 0
7485 # endif
7486 # ifndef GIFLIB_RELEASE
7487 # define GIFLIB_RELEASE 0
7488 # endif
7490 # else /* HAVE_NTGUI */
7492 # include <gif_lib.h>
7494 # endif /* HAVE_NTGUI */
7496 /* Giflib before 5.0 didn't define these macros. */
7497 # ifndef GIFLIB_MAJOR
7498 # define GIFLIB_MAJOR 4
7499 # endif
7501 # ifdef WINDOWSNT
7503 /* GIF library details. */
7504 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7505 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7506 # else
7507 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7508 # endif
7509 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7510 # if GIFLIB_MAJOR < 5
7511 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7512 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7513 # else
7514 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7515 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7516 DEF_DLL_FN (char *, GifErrorString, (int));
7517 # endif
7519 static bool
7520 init_gif_functions (void)
7522 HMODULE library;
7524 if (!(library = w32_delayed_load (Qgif)))
7525 return 0;
7527 LOAD_DLL_FN (library, DGifCloseFile);
7528 LOAD_DLL_FN (library, DGifSlurp);
7529 LOAD_DLL_FN (library, DGifOpen);
7530 LOAD_DLL_FN (library, DGifOpenFileName);
7531 # if GIFLIB_MAJOR >= 5
7532 LOAD_DLL_FN (library, GifErrorString);
7533 # endif
7534 return 1;
7537 # undef DGifCloseFile
7538 # undef DGifOpen
7539 # undef DGifOpenFileName
7540 # undef DGifSlurp
7541 # undef GifErrorString
7543 # define DGifCloseFile fn_DGifCloseFile
7544 # define DGifOpen fn_DGifOpen
7545 # define DGifOpenFileName fn_DGifOpenFileName
7546 # define DGifSlurp fn_DGifSlurp
7547 # define GifErrorString fn_GifErrorString
7549 # endif /* WINDOWSNT */
7551 /* Reading a GIF image from memory
7552 Based on the PNG memory stuff to a certain extent. */
7554 typedef struct
7556 unsigned char *bytes;
7557 ptrdiff_t len;
7558 ptrdiff_t index;
7560 gif_memory_source;
7562 /* Make the current memory source available to gif_read_from_memory.
7563 It's done this way because not all versions of libungif support
7564 a UserData field in the GifFileType structure. */
7565 static gif_memory_source *current_gif_memory_src;
7567 static int
7568 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7570 gif_memory_source *src = current_gif_memory_src;
7572 if (len > src->len - src->index)
7573 return -1;
7575 memcpy (buf, src->bytes + src->index, len);
7576 src->index += len;
7577 return len;
7580 static int
7581 gif_close (GifFileType *gif, int *err)
7583 int retval;
7585 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7586 retval = DGifCloseFile (gif, err);
7587 #else
7588 retval = DGifCloseFile (gif);
7589 #if GIFLIB_MAJOR >= 5
7590 if (err)
7591 *err = gif->Error;
7592 #endif
7593 #endif
7594 return retval;
7597 /* Load GIF image IMG for use on frame F. Value is true if
7598 successful. */
7600 static const int interlace_start[] = {0, 4, 2, 1};
7601 static const int interlace_increment[] = {8, 8, 4, 2};
7603 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7605 static bool
7606 gif_load (struct frame *f, struct image *img)
7608 Lisp_Object file;
7609 int rc, width, height, x, y, i, j;
7610 ColorMapObject *gif_color_map;
7611 unsigned long pixel_colors[256];
7612 GifFileType *gif;
7613 gif_memory_source memsrc;
7614 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7615 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7616 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7617 unsigned long bgcolor = 0;
7618 EMACS_INT idx;
7619 int gif_err;
7621 #ifdef USE_CAIRO
7622 unsigned char *data = 0;
7623 #else
7624 XImagePtr ximg;
7625 #endif
7627 if (NILP (specified_data))
7629 file = x_find_image_file (specified_file);
7630 if (!STRINGP (file))
7632 image_error ("Cannot find image file "uLSQM"%s"uRSQM,
7633 specified_file);
7634 return 0;
7636 #ifdef WINDOWSNT
7637 file = ansi_encode_filename (file);
7638 #endif
7640 /* Open the GIF file. */
7641 #if GIFLIB_MAJOR < 5
7642 gif = DGifOpenFileName (SSDATA (file));
7643 if (gif == NULL)
7645 image_error ("Cannot open "uLSQM"%s"uRSQM, file);
7646 return 0;
7648 #else
7649 gif = DGifOpenFileName (SSDATA (file), &gif_err);
7650 if (gif == NULL)
7652 image_error ("Cannot open "uLSQM"%s"uRSQM": %s",
7653 file, build_string (GifErrorString (gif_err)));
7654 return 0;
7656 #endif
7658 else
7660 if (!STRINGP (specified_data))
7662 image_error ("Invalid image data "uLSQM"%s"uRSQM, specified_data);
7663 return 0;
7666 /* Read from memory! */
7667 current_gif_memory_src = &memsrc;
7668 memsrc.bytes = SDATA (specified_data);
7669 memsrc.len = SBYTES (specified_data);
7670 memsrc.index = 0;
7672 #if GIFLIB_MAJOR < 5
7673 gif = DGifOpen (&memsrc, gif_read_from_memory);
7674 if (!gif)
7676 image_error ("Cannot open memory source "uLSQM"%s"uRSQM, img->spec);
7677 return 0;
7679 #else
7680 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7681 if (!gif)
7683 image_error ("Cannot open memory source "uLSQM"%s"uRSQM": %s",
7684 img->spec, build_string (GifErrorString (gif_err)));
7685 return 0;
7687 #endif
7690 /* Before reading entire contents, check the declared image size. */
7691 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7693 image_error ("Invalid image size (see "uLSQM"max-image-size"uRSQM")");
7694 gif_close (gif, NULL);
7695 return 0;
7698 /* Read entire contents. */
7699 rc = DGifSlurp (gif);
7700 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7702 image_error ("Error reading "uLSQM"%s"uRSQM, img->spec);
7703 gif_close (gif, NULL);
7704 return 0;
7707 /* Which sub-image are we to display? */
7709 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7710 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7711 if (idx < 0 || idx >= gif->ImageCount)
7713 image_error
7714 ("Invalid image number "uLSQM"%s"uRSQM" in image "uLSQM"%s"uRSQM,
7715 image_number, img->spec);
7716 gif_close (gif, NULL);
7717 return 0;
7721 width = img->width = gif->SWidth;
7722 height = img->height = gif->SHeight;
7724 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7725 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7726 img->corners[BOT_CORNER]
7727 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7728 img->corners[RIGHT_CORNER]
7729 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7731 if (!check_image_size (f, width, height))
7733 image_error ("Invalid image size (see "uLSQM"max-image-size"uRSQM")");
7734 gif_close (gif, NULL);
7735 return 0;
7738 /* Check that the selected subimages fit. It's not clear whether
7739 the GIF spec requires this, but Emacs can crash if they don't fit. */
7740 for (j = 0; j <= idx; ++j)
7742 struct SavedImage *subimage = gif->SavedImages + j;
7743 int subimg_width = subimage->ImageDesc.Width;
7744 int subimg_height = subimage->ImageDesc.Height;
7745 int subimg_top = subimage->ImageDesc.Top;
7746 int subimg_left = subimage->ImageDesc.Left;
7747 if (! (subimg_width >= 0 && subimg_height >= 0
7748 && 0 <= subimg_top && subimg_top <= height - subimg_height
7749 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7751 image_error ("Subimage does not fit in image");
7752 gif_close (gif, NULL);
7753 return 0;
7757 #ifdef USE_CAIRO
7758 /* xzalloc so data is zero => transparent */
7759 data = (unsigned char *) xzalloc (width * height * 4);
7760 if (STRINGP (specified_bg))
7762 XColor color;
7763 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
7765 uint32_t *dataptr = (uint32_t *)data;
7766 int r = color.red/256;
7767 int g = color.green/256;
7768 int b = color.blue/256;
7770 for (y = 0; y < height; ++y)
7771 for (x = 0; x < width; ++x)
7772 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
7775 #else
7776 /* Create the X image and pixmap. */
7777 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7779 gif_close (gif, NULL);
7780 return 0;
7783 /* Clear the part of the screen image not covered by the image.
7784 Full animated GIF support requires more here (see the gif89 spec,
7785 disposal methods). Let's simply assume that the part not covered
7786 by a sub-image is in the frame's background color. */
7787 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7788 for (x = 0; x < width; ++x)
7789 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7791 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7792 for (x = 0; x < width; ++x)
7793 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7795 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7797 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7798 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7799 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7800 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7802 #endif
7804 /* Read the GIF image into the X image. */
7806 /* FIXME: With the current implementation, loading an animated gif
7807 is quadratic in the number of animation frames, since each frame
7808 is a separate struct image. We must provide a way for a single
7809 gif_load call to construct and save all animation frames. */
7811 init_color_table ();
7812 if (STRINGP (specified_bg))
7813 bgcolor = x_alloc_image_color (f, img, specified_bg,
7814 FRAME_BACKGROUND_PIXEL (f));
7815 for (j = 0; j <= idx; ++j)
7817 /* We use a local variable `raster' here because RasterBits is a
7818 char *, which invites problems with bytes >= 0x80. */
7819 struct SavedImage *subimage = gif->SavedImages + j;
7820 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7821 int transparency_color_index = -1;
7822 int disposal = 0;
7823 int subimg_width = subimage->ImageDesc.Width;
7824 int subimg_height = subimage->ImageDesc.Height;
7825 int subimg_top = subimage->ImageDesc.Top;
7826 int subimg_left = subimage->ImageDesc.Left;
7828 /* Find the Graphic Control Extension block for this sub-image.
7829 Extract the disposal method and transparency color. */
7830 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7832 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7834 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7835 && extblock->ByteCount == 4
7836 && extblock->Bytes[0] & 1)
7838 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7839 to background". Treat any other value like 2. */
7840 disposal = (extblock->Bytes[0] >> 2) & 7;
7841 transparency_color_index = (unsigned char) extblock->Bytes[3];
7842 break;
7846 /* We can't "keep in place" the first subimage. */
7847 if (j == 0)
7848 disposal = 2;
7850 /* For disposal == 0, the spec says "No disposal specified. The
7851 decoder is not required to take any action." In practice, it
7852 seems we need to treat this like "keep in place", see e.g.
7853 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7854 if (disposal == 0)
7855 disposal = 1;
7857 gif_color_map = subimage->ImageDesc.ColorMap;
7858 if (!gif_color_map)
7859 gif_color_map = gif->SColorMap;
7861 #ifndef USE_CAIRO
7862 /* Allocate subimage colors. */
7863 memset (pixel_colors, 0, sizeof pixel_colors);
7865 if (gif_color_map)
7866 for (i = 0; i < gif_color_map->ColorCount; ++i)
7868 if (transparency_color_index == i)
7869 pixel_colors[i] = STRINGP (specified_bg)
7870 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7871 else
7873 int r = gif_color_map->Colors[i].Red << 8;
7874 int g = gif_color_map->Colors[i].Green << 8;
7875 int b = gif_color_map->Colors[i].Blue << 8;
7876 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7879 #endif
7881 /* Apply the pixel values. */
7882 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7884 int row, pass;
7886 for (y = 0, row = interlace_start[0], pass = 0;
7887 y < subimg_height;
7888 y++, row += interlace_increment[pass])
7890 while (subimg_height <= row)
7891 row = interlace_start[++pass];
7893 for (x = 0; x < subimg_width; x++)
7895 int c = raster[y * subimg_width + x];
7896 if (transparency_color_index != c || disposal != 1)
7898 #ifdef USE_CAIRO
7899 uint32_t *dataptr =
7900 ((uint32_t*)data + ((row + subimg_top) * subimg_width
7901 + x + subimg_left));
7902 int r = gif_color_map->Colors[c].Red;
7903 int g = gif_color_map->Colors[c].Green;
7904 int b = gif_color_map->Colors[c].Blue;
7906 if (transparency_color_index != c)
7907 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7908 #else
7909 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7910 pixel_colors[c]);
7911 #endif
7916 else
7918 for (y = 0; y < subimg_height; ++y)
7919 for (x = 0; x < subimg_width; ++x)
7921 int c = raster[y * subimg_width + x];
7922 if (transparency_color_index != c || disposal != 1)
7924 #ifdef USE_CAIRO
7925 uint32_t *dataptr =
7926 ((uint32_t*)data + ((y + subimg_top) * subimg_width
7927 + x + subimg_left));
7928 int r = gif_color_map->Colors[c].Red;
7929 int g = gif_color_map->Colors[c].Green;
7930 int b = gif_color_map->Colors[c].Blue;
7931 if (transparency_color_index != c)
7932 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7933 #else
7934 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7935 pixel_colors[c]);
7936 #endif
7942 #ifdef COLOR_TABLE_SUPPORT
7943 img->colors = colors_in_color_table (&img->ncolors);
7944 free_color_table ();
7945 #endif /* COLOR_TABLE_SUPPORT */
7947 /* Save GIF image extension data for `image-metadata'.
7948 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7949 img->lisp_data = Qnil;
7950 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7952 int delay = 0;
7953 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7954 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7955 /* Append (... FUNCTION "BYTES") */
7957 img->lisp_data
7958 = Fcons (make_number (ext->Function),
7959 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7960 img->lisp_data));
7961 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7962 && ext->ByteCount == 4)
7964 delay = ext->Bytes[2] << CHAR_BIT;
7965 delay |= ext->Bytes[1];
7968 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7969 if (delay)
7970 img->lisp_data
7971 = Fcons (Qdelay,
7972 Fcons (make_float (delay / 100.0),
7973 img->lisp_data));
7976 if (gif->ImageCount > 1)
7977 img->lisp_data = Fcons (Qcount,
7978 Fcons (make_number (gif->ImageCount),
7979 img->lisp_data));
7981 if (gif_close (gif, &gif_err) == GIF_ERROR)
7983 #if 5 <= GIFLIB_MAJOR
7984 char *error_text = GifErrorString (gif_err);
7986 if (error_text)
7987 image_error ("Error closing "uLSQM"%s"uRSQM": %s",
7988 img->spec, build_string (error_text));
7989 #else
7990 image_error ("Error closing "uLSQM"%s"uRSQM, img->spec);
7991 #endif
7994 #ifdef USE_CAIRO
7995 create_cairo_image_surface (img, data, width, height);
7996 #else
7997 /* Maybe fill in the background field while we have ximg handy. */
7998 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7999 /* Casting avoids a GCC warning. */
8000 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8002 /* Put ximg into the image. */
8003 image_put_x_image (f, img, ximg, 0);
8004 #endif
8006 return 1;
8009 #else /* !HAVE_GIF */
8011 #ifdef HAVE_NS
8012 static bool
8013 gif_load (struct frame *f, struct image *img)
8015 return ns_load_image (f, img,
8016 image_spec_value (img->spec, QCfile, NULL),
8017 image_spec_value (img->spec, QCdata, NULL));
8019 #endif /* HAVE_NS */
8021 #endif /* HAVE_GIF */
8024 #ifdef HAVE_IMAGEMAGICK
8026 /***********************************************************************
8027 ImageMagick
8028 ***********************************************************************/
8030 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8031 safely rounded and clipped to int range. */
8033 static int
8034 scale_image_size (int size, size_t divisor, size_t multiplier)
8036 if (divisor != 0)
8038 double s = size;
8039 double scaled = s * multiplier / divisor + 0.5;
8040 if (scaled < INT_MAX)
8041 return scaled;
8043 return INT_MAX;
8046 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8047 Use SPEC to deduce the size. Store the desired size into
8048 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8049 static void
8050 compute_image_size (size_t width, size_t height,
8051 Lisp_Object spec,
8052 int *d_width, int *d_height)
8054 Lisp_Object value;
8055 int desired_width, desired_height;
8057 /* If width and/or height is set in the display spec assume we want
8058 to scale to those values. If either h or w is unspecified, the
8059 unspecified should be calculated from the specified to preserve
8060 aspect ratio. */
8061 value = image_spec_value (spec, QCwidth, NULL);
8062 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8063 value = image_spec_value (spec, QCheight, NULL);
8064 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8066 if (desired_width == -1)
8068 value = image_spec_value (spec, QCmax_width, NULL);
8069 if (NATNUMP (value))
8071 int max_width = min (XFASTINT (value), INT_MAX);
8072 if (max_width < width)
8074 /* The image is wider than :max-width. */
8075 desired_width = max_width;
8076 if (desired_height == -1)
8078 desired_height = scale_image_size (desired_width,
8079 width, height);
8080 value = image_spec_value (spec, QCmax_height, NULL);
8081 if (NATNUMP (value))
8083 int max_height = min (XFASTINT (value), INT_MAX);
8084 if (max_height < desired_height)
8086 desired_height = max_height;
8087 desired_width = scale_image_size (desired_height,
8088 height, width);
8096 if (desired_height == -1)
8098 value = image_spec_value (spec, QCmax_height, NULL);
8099 if (NATNUMP (value))
8101 int max_height = min (XFASTINT (value), INT_MAX);
8102 if (max_height < height)
8103 desired_height = max_height;
8107 if (desired_width != -1 && desired_height == -1)
8108 /* w known, calculate h. */
8109 desired_height = scale_image_size (desired_width, width, height);
8111 if (desired_width == -1 && desired_height != -1)
8112 /* h known, calculate w. */
8113 desired_width = scale_image_size (desired_height, height, width);
8115 *d_width = desired_width;
8116 *d_height = desired_height;
8119 static bool imagemagick_image_p (Lisp_Object);
8120 static bool imagemagick_load (struct frame *, struct image *);
8121 static void imagemagick_clear_image (struct frame *, struct image *);
8123 /* Indices of image specification fields in imagemagick_format. */
8125 enum imagemagick_keyword_index
8127 IMAGEMAGICK_TYPE,
8128 IMAGEMAGICK_DATA,
8129 IMAGEMAGICK_FILE,
8130 IMAGEMAGICK_ASCENT,
8131 IMAGEMAGICK_MARGIN,
8132 IMAGEMAGICK_RELIEF,
8133 IMAGEMAGICK_ALGORITHM,
8134 IMAGEMAGICK_HEURISTIC_MASK,
8135 IMAGEMAGICK_MASK,
8136 IMAGEMAGICK_BACKGROUND,
8137 IMAGEMAGICK_HEIGHT,
8138 IMAGEMAGICK_WIDTH,
8139 IMAGEMAGICK_MAX_HEIGHT,
8140 IMAGEMAGICK_MAX_WIDTH,
8141 IMAGEMAGICK_FORMAT,
8142 IMAGEMAGICK_ROTATION,
8143 IMAGEMAGICK_CROP,
8144 IMAGEMAGICK_LAST
8147 /* Vector of image_keyword structures describing the format
8148 of valid user-defined image specifications. */
8150 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
8152 {":type", IMAGE_SYMBOL_VALUE, 1},
8153 {":data", IMAGE_STRING_VALUE, 0},
8154 {":file", IMAGE_STRING_VALUE, 0},
8155 {":ascent", IMAGE_ASCENT_VALUE, 0},
8156 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8157 {":relief", IMAGE_INTEGER_VALUE, 0},
8158 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8159 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8160 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8161 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8162 {":height", IMAGE_INTEGER_VALUE, 0},
8163 {":width", IMAGE_INTEGER_VALUE, 0},
8164 {":max-height", IMAGE_INTEGER_VALUE, 0},
8165 {":max-width", IMAGE_INTEGER_VALUE, 0},
8166 {":format", IMAGE_SYMBOL_VALUE, 0},
8167 {":rotation", IMAGE_NUMBER_VALUE, 0},
8168 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8171 #if defined HAVE_NTGUI && defined WINDOWSNT
8172 static bool init_imagemagick_functions (void);
8173 #else
8174 #define init_imagemagick_functions NULL
8175 #endif
8177 /* Structure describing the image type for any image handled via
8178 ImageMagick. */
8180 static struct image_type imagemagick_type =
8182 SYMBOL_INDEX (Qimagemagick),
8183 imagemagick_image_p,
8184 imagemagick_load,
8185 imagemagick_clear_image,
8186 init_imagemagick_functions,
8187 NULL
8190 /* Free X resources of imagemagick image IMG which is used on frame F. */
8192 static void
8193 imagemagick_clear_image (struct frame *f,
8194 struct image *img)
8196 x_clear_image (f, img);
8199 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8200 this by calling parse_image_spec and supplying the keywords that
8201 identify the IMAGEMAGICK format. */
8203 static bool
8204 imagemagick_image_p (Lisp_Object object)
8206 struct image_keyword fmt[IMAGEMAGICK_LAST];
8207 memcpy (fmt, imagemagick_format, sizeof fmt);
8209 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
8210 return 0;
8212 /* Must specify either the :data or :file keyword. */
8213 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
8216 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8217 Therefore rename the function so it doesn't collide with ImageMagick. */
8218 #define DrawRectangle DrawRectangleGif
8219 #include <wand/MagickWand.h>
8221 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8222 Emacs seems to work fine with the hidden version, so unhide it. */
8223 #include <magick/version.h>
8224 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8225 extern WandExport void PixelGetMagickColor (const PixelWand *,
8226 MagickPixelPacket *);
8227 #endif
8229 /* Log ImageMagick error message.
8230 Useful when a ImageMagick function returns the status `MagickFalse'. */
8232 static void
8233 imagemagick_error (MagickWand *wand)
8235 char *description;
8236 ExceptionType severity;
8238 description = MagickGetException (wand, &severity);
8239 image_error ("ImageMagick error: %s", build_string (description));
8240 MagickRelinquishMemory (description);
8243 /* Possibly give ImageMagick some extra help to determine the image
8244 type by supplying a "dummy" filename based on the Content-Type. */
8246 static char *
8247 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
8249 Lisp_Object symbol = intern ("image-format-suffixes");
8250 Lisp_Object val = find_symbol_value (symbol);
8251 Lisp_Object format;
8253 if (! CONSP (val))
8254 return NULL;
8256 format = image_spec_value (spec, intern (":format"), NULL);
8257 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
8258 if (! STRINGP (val))
8259 return NULL;
8261 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8262 as ImageMagick would ignore the extra bytes anyway. */
8263 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
8264 return hint_buffer;
8267 /* Animated images (e.g., GIF89a) are composed from one "master image"
8268 (which is the first one, and then there's a number of images that
8269 follow. If following images have non-transparent colors, these are
8270 composed "on top" of the master image. So, in general, one has to
8271 compute ann the preceding images to be able to display a particular
8272 sub-image.
8274 Computing all the preceding images is too slow, so we maintain a
8275 cache of previously computed images. We have to maintain a cache
8276 separate from the image cache, because the images may be scaled
8277 before display. */
8279 struct animation_cache
8281 MagickWand *wand;
8282 int index;
8283 struct timespec update_time;
8284 struct animation_cache *next;
8285 char signature[FLEXIBLE_ARRAY_MEMBER];
8288 static struct animation_cache *animation_cache = NULL;
8290 static struct animation_cache *
8291 imagemagick_create_cache (char *signature)
8293 struct animation_cache *cache
8294 = xmalloc (offsetof (struct animation_cache, signature)
8295 + strlen (signature) + 1);
8296 cache->wand = 0;
8297 cache->index = 0;
8298 cache->next = 0;
8299 strcpy (cache->signature, signature);
8300 return cache;
8303 /* Discard cached images that haven't been used for a minute. */
8304 static void
8305 imagemagick_prune_animation_cache (void)
8307 struct animation_cache **pcache = &animation_cache;
8308 struct timespec old = timespec_sub (current_timespec (),
8309 make_timespec (60, 0));
8311 while (*pcache)
8313 struct animation_cache *cache = *pcache;
8314 if (timespec_cmp (old, cache->update_time) <= 0)
8315 pcache = &cache->next;
8316 else
8318 if (cache->wand)
8319 DestroyMagickWand (cache->wand);
8320 *pcache = cache->next;
8321 xfree (cache);
8326 static struct animation_cache *
8327 imagemagick_get_animation_cache (MagickWand *wand)
8329 char *signature = MagickGetImageSignature (wand);
8330 struct animation_cache *cache;
8331 struct animation_cache **pcache = &animation_cache;
8333 imagemagick_prune_animation_cache ();
8335 while (1)
8337 cache = *pcache;
8338 if (! cache)
8340 *pcache = cache = imagemagick_create_cache (signature);
8341 break;
8343 if (strcmp (signature, cache->signature) == 0)
8344 break;
8345 pcache = &cache->next;
8348 DestroyString (signature);
8349 cache->update_time = current_timespec ();
8350 return cache;
8353 static MagickWand *
8354 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8356 int i;
8357 MagickWand *composite_wand;
8358 size_t dest_width, dest_height;
8359 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8361 MagickSetIteratorIndex (super_wand, 0);
8363 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8365 composite_wand = MagickGetImage (super_wand);
8366 if (cache->wand)
8367 DestroyMagickWand (cache->wand);
8369 else
8370 composite_wand = cache->wand;
8372 dest_height = MagickGetImageHeight (composite_wand);
8374 for (i = max (1, cache->index + 1); i <= ino; i++)
8376 MagickWand *sub_wand;
8377 PixelIterator *source_iterator, *dest_iterator;
8378 PixelWand **source, **dest;
8379 size_t source_width, source_height;
8380 ssize_t source_left, source_top;
8381 MagickPixelPacket pixel;
8382 DisposeType dispose;
8383 ptrdiff_t lines = 0;
8385 MagickSetIteratorIndex (super_wand, i);
8386 sub_wand = MagickGetImage (super_wand);
8388 MagickGetImagePage (sub_wand, &source_width, &source_height,
8389 &source_left, &source_top);
8391 /* This flag says how to handle transparent pixels. */
8392 dispose = MagickGetImageDispose (sub_wand);
8394 source_iterator = NewPixelIterator (sub_wand);
8395 if (! source_iterator)
8397 DestroyMagickWand (composite_wand);
8398 DestroyMagickWand (sub_wand);
8399 cache->wand = NULL;
8400 image_error ("Imagemagick pixel iterator creation failed");
8401 return NULL;
8404 dest_iterator = NewPixelIterator (composite_wand);
8405 if (! dest_iterator)
8407 DestroyMagickWand (composite_wand);
8408 DestroyMagickWand (sub_wand);
8409 DestroyPixelIterator (source_iterator);
8410 cache->wand = NULL;
8411 image_error ("Imagemagick pixel iterator creation failed");
8412 return NULL;
8415 /* The sub-image may not start at origin, so move the destination
8416 iterator to where the sub-image should start. */
8417 if (source_top > 0)
8419 PixelSetIteratorRow (dest_iterator, source_top);
8420 lines = source_top;
8423 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8424 != NULL)
8426 ptrdiff_t x;
8428 /* Sanity check. This shouldn't happen, but apparently
8429 does in some pictures. */
8430 if (++lines >= dest_height)
8431 break;
8433 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8434 for (x = 0; x < source_width; x++)
8436 /* Sanity check. This shouldn't happen, but apparently
8437 also does in some pictures. */
8438 if (x + source_left >= dest_width)
8439 break;
8440 /* Normally we only copy over non-transparent pixels,
8441 but if the disposal method is "Background", then we
8442 copy over all pixels. */
8443 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8445 PixelGetMagickColor (source[x], &pixel);
8446 PixelSetMagickColor (dest[x + source_left], &pixel);
8449 PixelSyncIterator (dest_iterator);
8452 DestroyPixelIterator (source_iterator);
8453 DestroyPixelIterator (dest_iterator);
8454 DestroyMagickWand (sub_wand);
8457 /* Cache a copy for the next iteration. The current wand will be
8458 destroyed by the caller. */
8459 cache->wand = CloneMagickWand (composite_wand);
8460 cache->index = ino;
8462 return composite_wand;
8466 /* Helper function for imagemagick_load, which does the actual loading
8467 given contents and size, apart from frame and image structures,
8468 passed from imagemagick_load. Uses librimagemagick to do most of
8469 the image processing.
8471 F is a pointer to the Emacs frame; IMG to the image structure to
8472 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8473 be parsed; SIZE is the number of bytes of data; and FILENAME is
8474 either the file name or the image data.
8476 Return true if successful. */
8478 static bool
8479 imagemagick_load_image (struct frame *f, struct image *img,
8480 unsigned char *contents, unsigned int size,
8481 char *filename)
8483 int width, height;
8484 size_t image_width, image_height;
8485 MagickBooleanType status;
8486 XImagePtr ximg;
8487 int x, y;
8488 MagickWand *image_wand;
8489 PixelIterator *iterator;
8490 PixelWand **pixels, *bg_wand = NULL;
8491 MagickPixelPacket pixel;
8492 Lisp_Object image;
8493 Lisp_Object value;
8494 Lisp_Object crop;
8495 EMACS_INT ino;
8496 int desired_width, desired_height;
8497 double rotation;
8498 int pixelwidth;
8499 char hint_buffer[MaxTextExtent];
8500 char *filename_hint = NULL;
8502 /* Handle image index for image types who can contain more than one image.
8503 Interface :index is same as for GIF. First we "ping" the image to see how
8504 many sub-images it contains. Pinging is faster than loading the image to
8505 find out things about it. */
8507 /* Initialize the imagemagick environment. */
8508 MagickWandGenesis ();
8509 image = image_spec_value (img->spec, QCindex, NULL);
8510 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8511 image_wand = NewMagickWand ();
8513 if (filename)
8514 status = MagickReadImage (image_wand, filename);
8515 else
8517 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8518 MagickSetFilename (image_wand, filename_hint);
8519 status = MagickReadImageBlob (image_wand, contents, size);
8522 if (status == MagickFalse)
8524 imagemagick_error (image_wand);
8525 DestroyMagickWand (image_wand);
8526 return 0;
8529 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8531 image_error
8532 ("Invalid image number "uLSQM"%s"uRSQM" in image "uLSQM"%s"uRSQM,
8533 image, img->spec);
8534 DestroyMagickWand (image_wand);
8535 return 0;
8538 if (MagickGetImageDelay (image_wand) > 0)
8539 img->lisp_data =
8540 Fcons (Qdelay,
8541 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8542 img->lisp_data));
8544 if (MagickGetNumberImages (image_wand) > 1)
8545 img->lisp_data =
8546 Fcons (Qcount,
8547 Fcons (make_number (MagickGetNumberImages (image_wand)),
8548 img->lisp_data));
8550 /* If we have an animated image, get the new wand based on the
8551 "super-wand". */
8552 if (MagickGetNumberImages (image_wand) > 1)
8554 MagickWand *super_wand = image_wand;
8555 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8556 if (! image_wand)
8557 image_wand = super_wand;
8558 else
8559 DestroyMagickWand (super_wand);
8562 /* Retrieve the frame's background color, for use later. */
8564 XColor bgcolor;
8565 Lisp_Object specified_bg;
8567 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8568 if (!STRINGP (specified_bg)
8569 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8570 x_query_frame_background_color (f, &bgcolor);
8572 bg_wand = NewPixelWand ();
8573 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8574 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8575 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8578 compute_image_size (MagickGetImageWidth (image_wand),
8579 MagickGetImageHeight (image_wand),
8580 img->spec, &desired_width, &desired_height);
8582 if (desired_width != -1 && desired_height != -1)
8584 status = MagickScaleImage (image_wand, desired_width, desired_height);
8585 if (status == MagickFalse)
8587 image_error ("Imagemagick scale failed");
8588 imagemagick_error (image_wand);
8589 goto imagemagick_error;
8593 /* crop behaves similar to image slicing in Emacs but is more memory
8594 efficient. */
8595 crop = image_spec_value (img->spec, QCcrop, NULL);
8597 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8599 /* After some testing, it seems MagickCropImage is the fastest crop
8600 function in ImageMagick. This crop function seems to do less copying
8601 than the alternatives, but it still reads the entire image into memory
8602 before cropping, which is apparently difficult to avoid when using
8603 imagemagick. */
8604 size_t crop_width = XINT (XCAR (crop));
8605 crop = XCDR (crop);
8606 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8608 size_t crop_height = XINT (XCAR (crop));
8609 crop = XCDR (crop);
8610 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8612 ssize_t crop_x = XINT (XCAR (crop));
8613 crop = XCDR (crop);
8614 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8616 ssize_t crop_y = XINT (XCAR (crop));
8617 MagickCropImage (image_wand, crop_width, crop_height,
8618 crop_x, crop_y);
8624 /* Furthermore :rotation. we need background color and angle for
8625 rotation. */
8627 TODO background handling for rotation specified_bg =
8628 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8629 (specified_bg). */
8630 value = image_spec_value (img->spec, QCrotation, NULL);
8631 if (FLOATP (value))
8633 rotation = extract_float (value);
8634 status = MagickRotateImage (image_wand, bg_wand, rotation);
8635 if (status == MagickFalse)
8637 image_error ("Imagemagick image rotate failed");
8638 imagemagick_error (image_wand);
8639 goto imagemagick_error;
8643 /* Set the canvas background color to the frame or specified
8644 background, and flatten the image. Note: as of ImageMagick
8645 6.6.0, SVG image transparency is not handled properly
8646 (e.g. etc/images/splash.svg shows a white background always). */
8648 MagickWand *new_wand;
8649 MagickSetImageBackgroundColor (image_wand, bg_wand);
8650 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8651 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8652 #else
8653 new_wand = MagickFlattenImages (image_wand);
8654 #endif
8655 DestroyMagickWand (image_wand);
8656 image_wand = new_wand;
8659 /* Finally we are done manipulating the image. Figure out the
8660 resulting width/height and transfer ownership to Emacs. */
8661 image_height = MagickGetImageHeight (image_wand);
8662 image_width = MagickGetImageWidth (image_wand);
8664 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8665 && check_image_size (f, image_width, image_height)))
8667 image_error ("Invalid image size (see "uLSQM"max-image-size"uRSQM")");
8668 goto imagemagick_error;
8671 width = image_width;
8672 height = image_height;
8674 /* We can now get a valid pixel buffer from the imagemagick file, if all
8675 went ok. */
8677 init_color_table ();
8679 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8680 if (imagemagick_render_type != 0)
8682 /* Magicexportimage is normally faster than pixelpushing. This
8683 method is also well tested. Some aspects of this method are
8684 ad-hoc and needs to be more researched. */
8685 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8686 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8687 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8688 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8689 &ximg, 0))
8691 #ifdef COLOR_TABLE_SUPPORT
8692 free_color_table ();
8693 #endif
8694 image_error ("Imagemagick X bitmap allocation failure");
8695 goto imagemagick_error;
8698 /* Oddly, the below code doesn't seem to work:*/
8699 /* switch(ximg->bitmap_unit){ */
8700 /* case 8: */
8701 /* pixelwidth=CharPixel; */
8702 /* break; */
8703 /* case 16: */
8704 /* pixelwidth=ShortPixel; */
8705 /* break; */
8706 /* case 32: */
8707 /* pixelwidth=LongPixel; */
8708 /* break; */
8709 /* } */
8711 Here im just guessing the format of the bitmap.
8712 happens to work fine for:
8713 - bw djvu images
8714 on rgb display.
8715 seems about 3 times as fast as pixel pushing(not carefully measured)
8717 pixelwidth = CharPixel; /*??? TODO figure out*/
8718 MagickExportImagePixels (image_wand, 0, 0, width, height,
8719 exportdepth, pixelwidth, ximg->data);
8721 else
8722 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8724 size_t image_height;
8725 MagickRealType color_scale = 65535.0 / QuantumRange;
8727 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8728 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8729 &ximg, 0))
8731 #ifdef COLOR_TABLE_SUPPORT
8732 free_color_table ();
8733 #endif
8734 image_error ("Imagemagick X bitmap allocation failure");
8735 goto imagemagick_error;
8738 /* Copy imagemagick image to x with primitive yet robust pixel
8739 pusher loop. This has been tested a lot with many different
8740 images. */
8742 /* Copy pixels from the imagemagick image structure to the x image map. */
8743 iterator = NewPixelIterator (image_wand);
8744 if (! iterator)
8746 #ifdef COLOR_TABLE_SUPPORT
8747 free_color_table ();
8748 #endif
8749 x_destroy_x_image (ximg);
8750 image_error ("Imagemagick pixel iterator creation failed");
8751 goto imagemagick_error;
8754 image_height = MagickGetImageHeight (image_wand);
8755 for (y = 0; y < image_height; y++)
8757 size_t row_width;
8758 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8759 if (! pixels)
8760 break;
8761 int xlim = min (row_width, width);
8762 for (x = 0; x < xlim; x++)
8764 PixelGetMagickColor (pixels[x], &pixel);
8765 XPutPixel (ximg, x, y,
8766 lookup_rgb_color (f,
8767 color_scale * pixel.red,
8768 color_scale * pixel.green,
8769 color_scale * pixel.blue));
8772 DestroyPixelIterator (iterator);
8775 #ifdef COLOR_TABLE_SUPPORT
8776 /* Remember colors allocated for this image. */
8777 img->colors = colors_in_color_table (&img->ncolors);
8778 free_color_table ();
8779 #endif /* COLOR_TABLE_SUPPORT */
8781 img->width = width;
8782 img->height = height;
8784 /* Put ximg into the image. */
8785 image_put_x_image (f, img, ximg, 0);
8787 /* Final cleanup. image_wand should be the only resource left. */
8788 DestroyMagickWand (image_wand);
8789 if (bg_wand) DestroyPixelWand (bg_wand);
8791 /* `MagickWandTerminus' terminates the imagemagick environment. */
8792 MagickWandTerminus ();
8794 return 1;
8796 imagemagick_error:
8797 DestroyMagickWand (image_wand);
8798 if (bg_wand) DestroyPixelWand (bg_wand);
8800 MagickWandTerminus ();
8801 /* TODO more cleanup. */
8802 image_error ("Error parsing IMAGEMAGICK image "uLSQM"%s"uRSQM, img->spec);
8803 return 0;
8807 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8808 successful. this function will go into the imagemagick_type structure, and
8809 the prototype thus needs to be compatible with that structure. */
8811 static bool
8812 imagemagick_load (struct frame *f, struct image *img)
8814 bool success_p = 0;
8815 Lisp_Object file_name;
8817 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8818 file_name = image_spec_value (img->spec, QCfile, NULL);
8819 if (STRINGP (file_name))
8821 Lisp_Object file;
8823 file = x_find_image_file (file_name);
8824 if (!STRINGP (file))
8826 image_error ("Cannot find image file "uLSQM"%s"uRSQM, file_name);
8827 return 0;
8829 #ifdef WINDOWSNT
8830 file = ansi_encode_filename (file);
8831 #endif
8832 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8834 /* Else its not a file, its a lisp object. Load the image from a
8835 lisp object rather than a file. */
8836 else
8838 Lisp_Object data;
8840 data = image_spec_value (img->spec, QCdata, NULL);
8841 if (!STRINGP (data))
8843 image_error ("Invalid image data "uLSQM"%s"uRSQM, data);
8844 return 0;
8846 success_p = imagemagick_load_image (f, img, SDATA (data),
8847 SBYTES (data), NULL);
8850 return success_p;
8853 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8854 doc: /* Return a list of image types supported by ImageMagick.
8855 Each entry in this list is a symbol named after an ImageMagick format
8856 tag. See the ImageMagick manual for a list of ImageMagick formats and
8857 their descriptions (http://www.imagemagick.org/script/formats.php).
8858 You can also try the shell command: `identify -list format'.
8860 Note that ImageMagick recognizes many file-types that Emacs does not
8861 recognize as images, such as C. See `imagemagick-types-enable'
8862 and `imagemagick-types-inhibit'. */)
8863 (void)
8865 Lisp_Object typelist = Qnil;
8866 size_t numf = 0;
8867 ExceptionInfo ex;
8868 char **imtypes;
8869 size_t i;
8871 GetExceptionInfo(&ex);
8872 imtypes = GetMagickList ("*", &numf, &ex);
8873 DestroyExceptionInfo(&ex);
8875 for (i = 0; i < numf; i++)
8877 Lisp_Object imagemagicktype = intern (imtypes[i]);
8878 typelist = Fcons (imagemagicktype, typelist);
8879 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8882 MagickRelinquishMemory (imtypes);
8883 return Fnreverse (typelist);
8886 #endif /* defined (HAVE_IMAGEMAGICK) */
8890 /***********************************************************************
8892 ***********************************************************************/
8894 #ifdef HAVE_RSVG
8896 /* Function prototypes. */
8898 static bool svg_image_p (Lisp_Object object);
8899 static bool svg_load (struct frame *f, struct image *img);
8901 static bool svg_load_image (struct frame *, struct image *,
8902 unsigned char *, ptrdiff_t, char *);
8904 /* Indices of image specification fields in svg_format, below. */
8906 enum svg_keyword_index
8908 SVG_TYPE,
8909 SVG_DATA,
8910 SVG_FILE,
8911 SVG_ASCENT,
8912 SVG_MARGIN,
8913 SVG_RELIEF,
8914 SVG_ALGORITHM,
8915 SVG_HEURISTIC_MASK,
8916 SVG_MASK,
8917 SVG_BACKGROUND,
8918 SVG_LAST
8921 /* Vector of image_keyword structures describing the format
8922 of valid user-defined image specifications. */
8924 static const struct image_keyword svg_format[SVG_LAST] =
8926 {":type", IMAGE_SYMBOL_VALUE, 1},
8927 {":data", IMAGE_STRING_VALUE, 0},
8928 {":file", IMAGE_STRING_VALUE, 0},
8929 {":ascent", IMAGE_ASCENT_VALUE, 0},
8930 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8931 {":relief", IMAGE_INTEGER_VALUE, 0},
8932 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8933 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8934 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8935 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8938 # if defined HAVE_NTGUI && defined WINDOWSNT
8939 static bool init_svg_functions (void);
8940 # else
8941 #define init_svg_functions NULL
8942 # endif
8944 /* Structure describing the image type `svg'. Its the same type of
8945 structure defined for all image formats, handled by emacs image
8946 functions. See struct image_type in dispextern.h. */
8948 static struct image_type svg_type =
8950 SYMBOL_INDEX (Qsvg),
8951 svg_image_p,
8952 svg_load,
8953 x_clear_image,
8954 init_svg_functions,
8955 NULL
8959 /* Return true if OBJECT is a valid SVG image specification. Do
8960 this by calling parse_image_spec and supplying the keywords that
8961 identify the SVG format. */
8963 static bool
8964 svg_image_p (Lisp_Object object)
8966 struct image_keyword fmt[SVG_LAST];
8967 memcpy (fmt, svg_format, sizeof fmt);
8969 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8970 return 0;
8972 /* Must specify either the :data or :file keyword. */
8973 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8976 # include <librsvg/rsvg.h>
8978 # ifdef WINDOWSNT
8980 /* SVG library functions. */
8981 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
8982 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
8983 (RsvgHandle *, RsvgDimensionData *));
8984 DEF_DLL_FN (gboolean, rsvg_handle_write,
8985 (RsvgHandle *, const guchar *, gsize, GError **));
8986 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8987 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8988 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
8990 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8991 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8992 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8993 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8994 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8995 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8996 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8997 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8999 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9000 DEF_DLL_FN (void, g_type_init, (void));
9001 # endif
9002 DEF_DLL_FN (void, g_object_unref, (gpointer));
9003 DEF_DLL_FN (void, g_error_free, (GError *));
9005 static bool
9006 init_svg_functions (void)
9008 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
9010 if (!(glib = w32_delayed_load (Qglib))
9011 || !(gobject = w32_delayed_load (Qgobject))
9012 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
9013 || !(library = w32_delayed_load (Qsvg)))
9015 if (gdklib) FreeLibrary (gdklib);
9016 if (gobject) FreeLibrary (gobject);
9017 if (glib) FreeLibrary (glib);
9018 return 0;
9021 LOAD_DLL_FN (library, rsvg_handle_new);
9022 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
9023 LOAD_DLL_FN (library, rsvg_handle_write);
9024 LOAD_DLL_FN (library, rsvg_handle_close);
9025 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
9026 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
9028 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
9029 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
9030 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
9031 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
9032 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
9033 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
9034 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
9035 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
9037 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9038 LOAD_DLL_FN (gobject, g_type_init);
9039 # endif
9040 LOAD_DLL_FN (gobject, g_object_unref);
9041 LOAD_DLL_FN (glib, g_error_free);
9043 return 1;
9046 /* The following aliases for library functions allow dynamic loading
9047 to be used on some platforms. */
9049 # undef gdk_pixbuf_get_bits_per_sample
9050 # undef gdk_pixbuf_get_colorspace
9051 # undef gdk_pixbuf_get_has_alpha
9052 # undef gdk_pixbuf_get_height
9053 # undef gdk_pixbuf_get_n_channels
9054 # undef gdk_pixbuf_get_pixels
9055 # undef gdk_pixbuf_get_rowstride
9056 # undef gdk_pixbuf_get_width
9057 # undef g_error_free
9058 # undef g_object_unref
9059 # undef g_type_init
9060 # undef rsvg_handle_close
9061 # undef rsvg_handle_get_dimensions
9062 # undef rsvg_handle_get_pixbuf
9063 # undef rsvg_handle_new
9064 # undef rsvg_handle_set_base_uri
9065 # undef rsvg_handle_write
9067 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9068 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9069 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9070 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9071 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9072 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9073 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9074 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9075 # define g_error_free fn_g_error_free
9076 # define g_object_unref fn_g_object_unref
9077 # define g_type_init fn_g_type_init
9078 # define rsvg_handle_close fn_rsvg_handle_close
9079 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9080 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9081 # define rsvg_handle_new fn_rsvg_handle_new
9082 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9083 # define rsvg_handle_write fn_rsvg_handle_write
9085 # endif /* !WINDOWSNT */
9087 /* Load SVG image IMG for use on frame F. Value is true if
9088 successful. */
9090 static bool
9091 svg_load (struct frame *f, struct image *img)
9093 bool success_p = 0;
9094 Lisp_Object file_name;
9096 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9097 file_name = image_spec_value (img->spec, QCfile, NULL);
9098 if (STRINGP (file_name))
9100 Lisp_Object file;
9101 unsigned char *contents;
9102 ptrdiff_t size;
9104 file = x_find_image_file (file_name);
9105 if (!STRINGP (file))
9107 image_error ("Cannot find image file "uLSQM"%s"uRSQM, file_name);
9108 return 0;
9111 /* Read the entire file into memory. */
9112 contents = slurp_file (SSDATA (file), &size);
9113 if (contents == NULL)
9115 image_error ("Error loading SVG image "uLSQM"%s"uRSQM, img->spec);
9116 return 0;
9118 /* If the file was slurped into memory properly, parse it. */
9119 success_p = svg_load_image (f, img, contents, size, SSDATA (file));
9120 xfree (contents);
9122 /* Else its not a file, its a lisp object. Load the image from a
9123 lisp object rather than a file. */
9124 else
9126 Lisp_Object data, original_filename;
9128 data = image_spec_value (img->spec, QCdata, NULL);
9129 if (!STRINGP (data))
9131 image_error ("Invalid image data "uLSQM"%s"uRSQM, data);
9132 return 0;
9134 original_filename = BVAR (current_buffer, filename);
9135 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data),
9136 (NILP (original_filename) ? NULL
9137 : SSDATA (original_filename)));
9140 return success_p;
9143 /* svg_load_image is a helper function for svg_load, which does the
9144 actual loading given contents and size, apart from frame and image
9145 structures, passed from svg_load.
9147 Uses librsvg to do most of the image processing.
9149 Returns true when successful. */
9150 static bool
9151 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
9152 struct image *img, /* Pointer to emacs image structure. */
9153 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
9154 ptrdiff_t size, /* Size of data in bytes. */
9155 char *filename) /* Name of SVG file being loaded. */
9157 RsvgHandle *rsvg_handle;
9158 RsvgDimensionData dimension_data;
9159 GError *err = NULL;
9160 GdkPixbuf *pixbuf;
9161 int width;
9162 int height;
9163 const guint8 *pixels;
9164 int rowstride;
9165 XImagePtr ximg;
9166 Lisp_Object specified_bg;
9167 XColor background;
9168 int x;
9169 int y;
9171 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9172 /* g_type_init is a glib function that must be called prior to
9173 using gnome type library functions (obsolete since 2.36.0). */
9174 g_type_init ();
9175 #endif
9177 /* Make a handle to a new rsvg object. */
9178 rsvg_handle = rsvg_handle_new ();
9180 /* Set base_uri for properly handling referenced images (via 'href').
9181 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9182 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9183 if (filename)
9184 rsvg_handle_set_base_uri(rsvg_handle, filename);
9186 /* Parse the contents argument and fill in the rsvg_handle. */
9187 rsvg_handle_write (rsvg_handle, contents, size, &err);
9188 if (err) goto rsvg_error;
9190 /* The parsing is complete, rsvg_handle is ready to used, close it
9191 for further writes. */
9192 rsvg_handle_close (rsvg_handle, &err);
9193 if (err) goto rsvg_error;
9195 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
9196 if (! check_image_size (f, dimension_data.width, dimension_data.height))
9198 image_error ("Invalid image size (see "uLSQM"max-image-size"uRSQM")");
9199 goto rsvg_error;
9202 /* We can now get a valid pixel buffer from the svg file, if all
9203 went ok. */
9204 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
9205 if (!pixbuf) goto rsvg_error;
9206 g_object_unref (rsvg_handle);
9208 /* Extract some meta data from the svg handle. */
9209 width = gdk_pixbuf_get_width (pixbuf);
9210 height = gdk_pixbuf_get_height (pixbuf);
9211 pixels = gdk_pixbuf_get_pixels (pixbuf);
9212 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
9214 /* Validate the svg meta data. */
9215 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
9216 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
9217 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
9218 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
9220 #ifdef USE_CAIRO
9222 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
9223 int y;
9224 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
9226 for (y = 0; y < height; ++y)
9228 const guchar *iconptr = pixels + y * rowstride;
9229 uint32_t *dataptr = (uint32_t *) (data + y * rowstride);
9230 int x;
9232 for (x = 0; x < width; ++x)
9234 if (iconptr[3] == 0)
9235 *dataptr = bgcolor;
9236 else
9237 *dataptr = (iconptr[0] << 16)
9238 | (iconptr[1] << 8)
9239 | iconptr[2]
9240 | (iconptr[3] << 24);
9242 iconptr += 4;
9243 ++dataptr;
9247 create_cairo_image_surface (img, data, width, height);
9248 g_object_unref (pixbuf);
9250 #else
9251 /* Try to create a x pixmap to hold the svg pixmap. */
9252 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
9254 g_object_unref (pixbuf);
9255 return 0;
9258 init_color_table ();
9260 /* Handle alpha channel by combining the image with a background
9261 color. */
9262 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
9263 if (!STRINGP (specified_bg)
9264 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
9265 x_query_frame_background_color (f, &background);
9267 /* SVG pixmaps specify transparency in the last byte, so right
9268 shift 8 bits to get rid of it, since emacs doesn't support
9269 transparency. */
9270 background.red >>= 8;
9271 background.green >>= 8;
9272 background.blue >>= 8;
9274 /* This loop handles opacity values, since Emacs assumes
9275 non-transparent images. Each pixel must be "flattened" by
9276 calculating the resulting color, given the transparency of the
9277 pixel, and the image background color. */
9278 for (y = 0; y < height; ++y)
9280 for (x = 0; x < width; ++x)
9282 int red;
9283 int green;
9284 int blue;
9285 int opacity;
9287 red = *pixels++;
9288 green = *pixels++;
9289 blue = *pixels++;
9290 opacity = *pixels++;
9292 red = ((red * opacity)
9293 + (background.red * ((1 << 8) - opacity)));
9294 green = ((green * opacity)
9295 + (background.green * ((1 << 8) - opacity)));
9296 blue = ((blue * opacity)
9297 + (background.blue * ((1 << 8) - opacity)));
9299 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9302 pixels += rowstride - 4 * width;
9305 #ifdef COLOR_TABLE_SUPPORT
9306 /* Remember colors allocated for this image. */
9307 img->colors = colors_in_color_table (&img->ncolors);
9308 free_color_table ();
9309 #endif /* COLOR_TABLE_SUPPORT */
9311 g_object_unref (pixbuf);
9313 img->width = width;
9314 img->height = height;
9316 /* Maybe fill in the background field while we have ximg handy.
9317 Casting avoids a GCC warning. */
9318 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9320 /* Put ximg into the image. */
9321 image_put_x_image (f, img, ximg, 0);
9322 #endif /* ! USE_CAIRO */
9324 return 1;
9326 rsvg_error:
9327 g_object_unref (rsvg_handle);
9328 /* FIXME: Use error->message so the user knows what is the actual
9329 problem with the image. */
9330 image_error ("Error parsing SVG image "uLSQM"%s"uRSQM, img->spec);
9331 g_error_free (err);
9332 return 0;
9335 #endif /* defined (HAVE_RSVG) */
9340 /***********************************************************************
9341 Ghostscript
9342 ***********************************************************************/
9344 #ifdef HAVE_X_WINDOWS
9345 #define HAVE_GHOSTSCRIPT 1
9346 #endif /* HAVE_X_WINDOWS */
9348 #ifdef HAVE_GHOSTSCRIPT
9350 static bool gs_image_p (Lisp_Object object);
9351 static bool gs_load (struct frame *f, struct image *img);
9352 static void gs_clear_image (struct frame *f, struct image *img);
9354 /* Indices of image specification fields in gs_format, below. */
9356 enum gs_keyword_index
9358 GS_TYPE,
9359 GS_PT_WIDTH,
9360 GS_PT_HEIGHT,
9361 GS_FILE,
9362 GS_LOADER,
9363 GS_BOUNDING_BOX,
9364 GS_ASCENT,
9365 GS_MARGIN,
9366 GS_RELIEF,
9367 GS_ALGORITHM,
9368 GS_HEURISTIC_MASK,
9369 GS_MASK,
9370 GS_BACKGROUND,
9371 GS_LAST
9374 /* Vector of image_keyword structures describing the format
9375 of valid user-defined image specifications. */
9377 static const struct image_keyword gs_format[GS_LAST] =
9379 {":type", IMAGE_SYMBOL_VALUE, 1},
9380 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9381 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9382 {":file", IMAGE_STRING_VALUE, 1},
9383 {":loader", IMAGE_FUNCTION_VALUE, 0},
9384 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9385 {":ascent", IMAGE_ASCENT_VALUE, 0},
9386 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9387 {":relief", IMAGE_INTEGER_VALUE, 0},
9388 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9389 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9390 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9391 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9394 /* Structure describing the image type `ghostscript'. */
9396 static struct image_type gs_type =
9398 SYMBOL_INDEX (Qpostscript),
9399 gs_image_p,
9400 gs_load,
9401 gs_clear_image,
9402 NULL,
9403 NULL
9407 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9409 static void
9410 gs_clear_image (struct frame *f, struct image *img)
9412 x_clear_image (f, img);
9416 /* Return true if OBJECT is a valid Ghostscript image
9417 specification. */
9419 static bool
9420 gs_image_p (Lisp_Object object)
9422 struct image_keyword fmt[GS_LAST];
9423 Lisp_Object tem;
9424 int i;
9426 memcpy (fmt, gs_format, sizeof fmt);
9428 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9429 return 0;
9431 /* Bounding box must be a list or vector containing 4 integers. */
9432 tem = fmt[GS_BOUNDING_BOX].value;
9433 if (CONSP (tem))
9435 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9436 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9437 return 0;
9438 if (!NILP (tem))
9439 return 0;
9441 else if (VECTORP (tem))
9443 if (ASIZE (tem) != 4)
9444 return 0;
9445 for (i = 0; i < 4; ++i)
9446 if (!INTEGERP (AREF (tem, i)))
9447 return 0;
9449 else
9450 return 0;
9452 return 1;
9456 /* Load Ghostscript image IMG for use on frame F. Value is true
9457 if successful. */
9459 static bool
9460 gs_load (struct frame *f, struct image *img)
9462 uprintmax_t printnum1, printnum2;
9463 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9464 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9465 Lisp_Object frame;
9466 double in_width, in_height;
9467 Lisp_Object pixel_colors = Qnil;
9469 /* Compute pixel size of pixmap needed from the given size in the
9470 image specification. Sizes in the specification are in pt. 1 pt
9471 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9472 info. */
9473 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9474 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9475 in_width *= FRAME_RES_X (f);
9476 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9477 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9478 in_height *= FRAME_RES_Y (f);
9480 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9481 && check_image_size (f, in_width, in_height)))
9483 image_error ("Invalid image size (see "uLSQM"max-image-size"uRSQM")");
9484 return 0;
9486 img->width = in_width;
9487 img->height = in_height;
9489 /* Create the pixmap. */
9490 eassert (img->pixmap == NO_PIXMAP);
9492 if (x_check_image_size (0, img->width, img->height))
9494 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9495 block_input ();
9496 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9497 img->width, img->height,
9498 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9499 unblock_input ();
9502 if (!img->pixmap)
9504 image_error ("Unable to create pixmap for "uLSQM"%s"uRSQM, img->spec);
9505 return 0;
9508 /* Call the loader to fill the pixmap. It returns a process object
9509 if successful. We do not record_unwind_protect here because
9510 other places in redisplay like calling window scroll functions
9511 don't either. Let the Lisp loader use `unwind-protect' instead. */
9512 printnum1 = FRAME_X_WINDOW (f);
9513 printnum2 = img->pixmap;
9514 window_and_pixmap_id
9515 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9517 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9518 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9519 pixel_colors
9520 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9522 XSETFRAME (frame, f);
9523 loader = image_spec_value (img->spec, QCloader, NULL);
9524 if (NILP (loader))
9525 loader = intern ("gs-load-image");
9527 img->lisp_data = call6 (loader, frame, img->spec,
9528 make_number (img->width),
9529 make_number (img->height),
9530 window_and_pixmap_id,
9531 pixel_colors);
9532 return PROCESSP (img->lisp_data);
9536 /* Kill the Ghostscript process that was started to fill PIXMAP on
9537 frame F. Called from XTread_socket when receiving an event
9538 telling Emacs that Ghostscript has finished drawing. */
9540 void
9541 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9543 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9544 int class;
9545 ptrdiff_t i;
9546 struct image *img;
9548 /* Find the image containing PIXMAP. */
9549 for (i = 0; i < c->used; ++i)
9550 if (c->images[i]->pixmap == pixmap)
9551 break;
9553 /* Should someone in between have cleared the image cache, for
9554 instance, give up. */
9555 if (i == c->used)
9556 return;
9558 /* Kill the GS process. We should have found PIXMAP in the image
9559 cache and its image should contain a process object. */
9560 img = c->images[i];
9561 eassert (PROCESSP (img->lisp_data));
9562 Fkill_process (img->lisp_data, Qnil);
9563 img->lisp_data = Qnil;
9565 #if defined (HAVE_X_WINDOWS)
9567 /* On displays with a mutable colormap, figure out the colors
9568 allocated for the image by looking at the pixels of an XImage for
9569 img->pixmap. */
9570 class = FRAME_X_VISUAL (f)->class;
9571 if (class != StaticColor && class != StaticGray && class != TrueColor)
9573 XImagePtr ximg;
9575 block_input ();
9577 /* Try to get an XImage for img->pixmep. */
9578 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9579 0, 0, img->width, img->height, ~0, ZPixmap);
9580 if (ximg)
9582 int x, y;
9584 /* Initialize the color table. */
9585 init_color_table ();
9587 /* For each pixel of the image, look its color up in the
9588 color table. After having done so, the color table will
9589 contain an entry for each color used by the image. */
9590 #ifdef COLOR_TABLE_SUPPORT
9591 for (y = 0; y < img->height; ++y)
9592 for (x = 0; x < img->width; ++x)
9594 unsigned long pixel = XGetPixel (ximg, x, y);
9596 lookup_pixel_color (f, pixel);
9599 /* Record colors in the image. Free color table and XImage. */
9600 img->colors = colors_in_color_table (&img->ncolors);
9601 free_color_table ();
9602 #endif
9603 XDestroyImage (ximg);
9605 #if 0 /* This doesn't seem to be the case. If we free the colors
9606 here, we get a BadAccess later in x_clear_image when
9607 freeing the colors. */
9608 /* We have allocated colors once, but Ghostscript has also
9609 allocated colors on behalf of us. So, to get the
9610 reference counts right, free them once. */
9611 if (img->ncolors)
9612 x_free_colors (f, img->colors, img->ncolors);
9613 #endif
9615 else
9616 image_error (("Cannot get X image of "uLSQM"%s"uRSQM";"
9617 " colors will not be freed"),
9618 img->spec);
9620 unblock_input ();
9622 #endif /* HAVE_X_WINDOWS */
9624 /* Now that we have the pixmap, compute mask and transform the
9625 image if requested. */
9626 block_input ();
9627 postprocess_image (f, img);
9628 unblock_input ();
9631 #endif /* HAVE_GHOSTSCRIPT */
9634 /***********************************************************************
9635 Tests
9636 ***********************************************************************/
9638 #ifdef GLYPH_DEBUG
9640 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9641 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9642 (Lisp_Object spec)
9644 return valid_image_p (spec) ? Qt : Qnil;
9648 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0,
9649 doc: /* */)
9650 (Lisp_Object spec)
9652 ptrdiff_t id = -1;
9654 if (valid_image_p (spec))
9655 id = lookup_image (SELECTED_FRAME (), spec);
9657 debug_print (spec);
9658 return make_number (id);
9661 #endif /* GLYPH_DEBUG */
9664 /***********************************************************************
9665 Initialization
9666 ***********************************************************************/
9668 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9669 doc: /* Initialize image library implementing image type TYPE.
9670 Return non-nil if TYPE is a supported image type.
9672 If image libraries are loaded dynamically (currently only the case on
9673 MS-Windows), load the library for TYPE if it is not yet loaded, using
9674 the library file(s) specified by `dynamic-library-alist'. */)
9675 (Lisp_Object type)
9677 return lookup_image_type (type) ? Qt : Qnil;
9680 /* Look up image type TYPE, and return a pointer to its image_type
9681 structure. Return 0 if TYPE is not a known image type. */
9683 static struct image_type *
9684 lookup_image_type (Lisp_Object type)
9686 /* Types pbm and xbm are built-in and always available. */
9687 if (EQ (type, Qpbm))
9688 return define_image_type (&pbm_type);
9690 if (EQ (type, Qxbm))
9691 return define_image_type (&xbm_type);
9693 #if defined (HAVE_XPM) || defined (HAVE_NS)
9694 if (EQ (type, Qxpm))
9695 return define_image_type (&xpm_type);
9696 #endif
9698 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9699 if (EQ (type, Qjpeg))
9700 return define_image_type (&jpeg_type);
9701 #endif
9703 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9704 if (EQ (type, Qtiff))
9705 return define_image_type (&tiff_type);
9706 #endif
9708 #if defined (HAVE_GIF) || defined (HAVE_NS)
9709 if (EQ (type, Qgif))
9710 return define_image_type (&gif_type);
9711 #endif
9713 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9714 if (EQ (type, Qpng))
9715 return define_image_type (&png_type);
9716 #endif
9718 #if defined (HAVE_RSVG)
9719 if (EQ (type, Qsvg))
9720 return define_image_type (&svg_type);
9721 #endif
9723 #if defined (HAVE_IMAGEMAGICK)
9724 if (EQ (type, Qimagemagick))
9725 return define_image_type (&imagemagick_type);
9726 #endif
9728 #ifdef HAVE_GHOSTSCRIPT
9729 if (EQ (type, Qpostscript))
9730 return define_image_type (&gs_type);
9731 #endif
9733 return NULL;
9736 /* Reset image_types before dumping.
9737 Called from Fdump_emacs. */
9739 void
9740 reset_image_types (void)
9742 while (image_types)
9744 struct image_type *next = image_types->next;
9745 xfree (image_types);
9746 image_types = next;
9750 void
9751 syms_of_image (void)
9753 /* Initialize this only once; it will be reset before dumping. */
9754 image_types = NULL;
9756 /* Must be defined now because we're going to update it below, while
9757 defining the supported image types. */
9758 DEFVAR_LISP ("image-types", Vimage_types,
9759 doc: /* List of potentially supported image types.
9760 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9761 To check whether it is really supported, use `image-type-available-p'. */);
9762 Vimage_types = Qnil;
9764 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9765 doc: /* Maximum size of images.
9766 Emacs will not load an image into memory if its pixel width or
9767 pixel height exceeds this limit.
9769 If the value is an integer, it directly specifies the maximum
9770 image height and width, measured in pixels. If it is a floating
9771 point number, it specifies the maximum image height and width
9772 as a ratio to the frame height and width. If the value is
9773 non-numeric, there is no explicit limit on the size of images. */);
9774 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9776 /* Other symbols. */
9777 DEFSYM (Qcount, "count");
9778 DEFSYM (Qextension_data, "extension-data");
9779 DEFSYM (Qdelay, "delay");
9781 /* Keywords. */
9782 DEFSYM (QCascent, ":ascent");
9783 DEFSYM (QCmargin, ":margin");
9784 DEFSYM (QCrelief, ":relief");
9785 DEFSYM (QCconversion, ":conversion");
9786 DEFSYM (QCcolor_symbols, ":color-symbols");
9787 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9788 DEFSYM (QCindex, ":index");
9789 DEFSYM (QCcrop, ":crop");
9790 DEFSYM (QCrotation, ":rotation");
9791 DEFSYM (QCmatrix, ":matrix");
9792 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9793 DEFSYM (QCmask, ":mask");
9795 /* Other symbols. */
9796 DEFSYM (Qlaplace, "laplace");
9797 DEFSYM (Qemboss, "emboss");
9798 DEFSYM (Qedge_detection, "edge-detection");
9799 DEFSYM (Qheuristic, "heuristic");
9801 DEFSYM (Qpostscript, "postscript");
9802 DEFSYM (QCmax_width, ":max-width");
9803 DEFSYM (QCmax_height, ":max-height");
9804 #ifdef HAVE_GHOSTSCRIPT
9805 ADD_IMAGE_TYPE (Qpostscript);
9806 DEFSYM (QCloader, ":loader");
9807 DEFSYM (QCpt_width, ":pt-width");
9808 DEFSYM (QCpt_height, ":pt-height");
9809 #endif /* HAVE_GHOSTSCRIPT */
9811 #ifdef HAVE_NTGUI
9812 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9813 or -1 if no PNG/GIF support was compiled in. This is tested by
9814 w32-win.el to correctly set up the alist used to search for the
9815 respective image libraries. */
9816 DEFSYM (Qlibpng_version, "libpng-version");
9817 Fset (Qlibpng_version,
9818 #if HAVE_PNG
9819 make_number (PNG_LIBPNG_VER)
9820 #else
9821 make_number (-1)
9822 #endif
9824 DEFSYM (Qlibgif_version, "libgif-version");
9825 Fset (Qlibgif_version,
9826 #ifdef HAVE_GIF
9827 make_number (GIFLIB_MAJOR * 10000
9828 + GIFLIB_MINOR * 100
9829 + GIFLIB_RELEASE)
9830 #else
9831 make_number (-1)
9832 #endif
9834 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9835 Fset (Qlibjpeg_version,
9836 #if HAVE_JPEG
9837 make_number (JPEG_LIB_VERSION)
9838 #else
9839 make_number (-1)
9840 #endif
9842 #endif
9844 DEFSYM (Qpbm, "pbm");
9845 ADD_IMAGE_TYPE (Qpbm);
9847 DEFSYM (Qxbm, "xbm");
9848 ADD_IMAGE_TYPE (Qxbm);
9850 #if defined (HAVE_XPM) || defined (HAVE_NS)
9851 DEFSYM (Qxpm, "xpm");
9852 ADD_IMAGE_TYPE (Qxpm);
9853 #endif
9855 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9856 DEFSYM (Qjpeg, "jpeg");
9857 ADD_IMAGE_TYPE (Qjpeg);
9858 #endif
9860 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9861 DEFSYM (Qtiff, "tiff");
9862 ADD_IMAGE_TYPE (Qtiff);
9863 #endif
9865 #if defined (HAVE_GIF) || defined (HAVE_NS)
9866 DEFSYM (Qgif, "gif");
9867 ADD_IMAGE_TYPE (Qgif);
9868 #endif
9870 #if defined (HAVE_PNG) || defined (HAVE_NS)
9871 DEFSYM (Qpng, "png");
9872 ADD_IMAGE_TYPE (Qpng);
9873 #endif
9875 #if defined (HAVE_IMAGEMAGICK)
9876 DEFSYM (Qimagemagick, "imagemagick");
9877 ADD_IMAGE_TYPE (Qimagemagick);
9878 #endif
9880 #if defined (HAVE_RSVG)
9881 DEFSYM (Qsvg, "svg");
9882 ADD_IMAGE_TYPE (Qsvg);
9883 #ifdef HAVE_NTGUI
9884 /* Other libraries used directly by svg code. */
9885 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9886 DEFSYM (Qglib, "glib");
9887 DEFSYM (Qgobject, "gobject");
9888 #endif /* HAVE_NTGUI */
9889 #endif /* HAVE_RSVG */
9891 defsubr (&Sinit_image_library);
9892 #ifdef HAVE_IMAGEMAGICK
9893 defsubr (&Simagemagick_types);
9894 #endif
9895 defsubr (&Sclear_image_cache);
9896 defsubr (&Simage_flush);
9897 defsubr (&Simage_size);
9898 defsubr (&Simage_mask_p);
9899 defsubr (&Simage_metadata);
9901 #ifdef GLYPH_DEBUG
9902 defsubr (&Simagep);
9903 defsubr (&Slookup_image);
9904 #endif
9906 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9907 doc: /* Non-nil means always draw a cross over disabled images.
9908 Disabled images are those having a `:conversion disabled' property.
9909 A cross is always drawn on black & white displays. */);
9910 cross_disabled_images = 0;
9912 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9913 doc: /* List of directories to search for window system bitmap files. */);
9914 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9916 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9917 doc: /* Maximum time after which images are removed from the cache.
9918 When an image has not been displayed this many seconds, Emacs
9919 automatically removes it from the image cache. If the cache contains
9920 a large number of images, the actual eviction time may be shorter.
9921 The value can also be nil, meaning the cache is never cleared.
9923 The function `clear-image-cache' disregards this variable. */);
9924 Vimage_cache_eviction_delay = make_number (300);
9925 #ifdef HAVE_IMAGEMAGICK
9926 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9927 doc: /* Integer indicating which ImageMagick rendering method to use.
9928 The options are:
9929 0 -- the default method (pixel pushing)
9930 1 -- a newer method ("MagickExportImagePixels") that may perform
9931 better (speed etc) in some cases, but has not been as thoroughly
9932 tested with Emacs as the default method. This method requires
9933 ImageMagick version 6.4.6 (approximately) or later.
9934 */);
9935 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9936 imagemagick_render_type = 0;
9937 #endif