Add xref-pulse-on-jump
[emacs.git] / src / image.c
blob5e4843834c198b037a9877d595db501f433d6587
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 HAVE_NS
92 #undef COLOR_TABLE_SUPPORT
94 typedef struct ns_bitmap_record Bitmap_Record;
96 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
97 #define NO_PIXMAP 0
99 #define PIX_MASK_RETAIN 0
100 #define PIX_MASK_DRAW 1
102 #define x_defined_color(f, name, color_def, alloc) \
103 ns_defined_color (f, name, color_def, alloc, 0)
104 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
105 #endif /* HAVE_NS */
107 static void x_disable_image (struct frame *, struct image *);
108 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
109 Lisp_Object);
111 static void init_color_table (void);
112 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
113 #ifdef COLOR_TABLE_SUPPORT
114 static void free_color_table (void);
115 static unsigned long *colors_in_color_table (int *n);
116 #endif
118 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
119 id, which is just an int that this section returns. Bitmaps are
120 reference counted so they can be shared among frames.
122 Bitmap indices are guaranteed to be > 0, so a negative number can
123 be used to indicate no bitmap.
125 If you use x_create_bitmap_from_data, then you must keep track of
126 the bitmaps yourself. That is, creating a bitmap from the same
127 data more than once will not be caught. */
129 #ifdef HAVE_NS
130 /* Use with images created by ns_image_for_XPM. */
131 static unsigned long
132 XGetPixel (XImagePtr ximage, int x, int y)
134 return ns_get_pixel (ximage, x, y);
137 /* Use with images created by ns_image_for_XPM; alpha set to 1;
138 pixel is assumed to be in RGB form. */
139 static void
140 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
142 ns_put_pixel (ximage, x, y, pixel);
144 #endif /* HAVE_NS */
147 /* Functions to access the contents of a bitmap, given an id. */
149 #ifdef HAVE_X_WINDOWS
150 static int
151 x_bitmap_height (struct frame *f, ptrdiff_t id)
153 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
156 static int
157 x_bitmap_width (struct frame *f, ptrdiff_t id)
159 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
161 #endif
163 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
164 ptrdiff_t
165 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
167 /* HAVE_NTGUI needs the explicit cast here. */
168 return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
170 #endif
172 #ifdef HAVE_X_WINDOWS
174 x_bitmap_mask (struct frame *f, ptrdiff_t id)
176 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
178 #endif
180 /* Allocate a new bitmap record. Returns index of new record. */
182 static ptrdiff_t
183 x_allocate_bitmap_record (struct frame *f)
185 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
186 ptrdiff_t i;
188 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
189 return ++dpyinfo->bitmaps_last;
191 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
192 if (dpyinfo->bitmaps[i].refcount == 0)
193 return i + 1;
195 dpyinfo->bitmaps =
196 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
197 10, -1, sizeof *dpyinfo->bitmaps);
198 return ++dpyinfo->bitmaps_last;
201 /* Add one reference to the reference count of the bitmap with id ID. */
203 void
204 x_reference_bitmap (struct frame *f, ptrdiff_t id)
206 ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
209 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
211 ptrdiff_t
212 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
214 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
215 ptrdiff_t id;
217 #ifdef HAVE_X_WINDOWS
218 Pixmap bitmap;
219 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
220 bits, width, height);
221 if (! bitmap)
222 return -1;
223 #endif /* HAVE_X_WINDOWS */
225 #ifdef HAVE_NTGUI
226 Pixmap bitmap;
227 bitmap = CreateBitmap (width, height,
228 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
229 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
230 bits);
231 if (! bitmap)
232 return -1;
233 #endif /* HAVE_NTGUI */
235 #ifdef HAVE_NS
236 void *bitmap = ns_image_from_XBM (bits, width, height);
237 if (!bitmap)
238 return -1;
239 #endif
241 id = x_allocate_bitmap_record (f);
243 #ifdef HAVE_NS
244 dpyinfo->bitmaps[id - 1].img = bitmap;
245 dpyinfo->bitmaps[id - 1].depth = 1;
246 #endif
248 dpyinfo->bitmaps[id - 1].file = NULL;
249 dpyinfo->bitmaps[id - 1].height = height;
250 dpyinfo->bitmaps[id - 1].width = width;
251 dpyinfo->bitmaps[id - 1].refcount = 1;
253 #ifdef HAVE_X_WINDOWS
254 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
255 dpyinfo->bitmaps[id - 1].have_mask = false;
256 dpyinfo->bitmaps[id - 1].depth = 1;
257 #endif /* HAVE_X_WINDOWS */
259 #ifdef HAVE_NTGUI
260 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
261 dpyinfo->bitmaps[id - 1].hinst = NULL;
262 dpyinfo->bitmaps[id - 1].depth = 1;
263 #endif /* HAVE_NTGUI */
265 return id;
268 /* Create bitmap from file FILE for frame F. */
270 ptrdiff_t
271 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
273 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
275 #ifdef HAVE_NTGUI
276 return -1; /* W32_TODO : bitmap support */
277 #endif /* HAVE_NTGUI */
279 #ifdef HAVE_NS
280 ptrdiff_t id;
281 void *bitmap = ns_image_from_file (file);
283 if (!bitmap)
284 return -1;
287 id = x_allocate_bitmap_record (f);
288 dpyinfo->bitmaps[id - 1].img = bitmap;
289 dpyinfo->bitmaps[id - 1].refcount = 1;
290 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
291 dpyinfo->bitmaps[id - 1].depth = 1;
292 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
293 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
294 return id;
295 #endif
297 #ifdef HAVE_X_WINDOWS
298 unsigned int width, height;
299 Pixmap bitmap;
300 int xhot, yhot, result;
301 ptrdiff_t id;
302 Lisp_Object found;
303 char *filename;
305 /* Look for an existing bitmap with the same name. */
306 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
308 if (dpyinfo->bitmaps[id].refcount
309 && dpyinfo->bitmaps[id].file
310 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
312 ++dpyinfo->bitmaps[id].refcount;
313 return id + 1;
317 /* Search bitmap-file-path for the file, if appropriate. */
318 if (openp (Vx_bitmap_file_path, file, Qnil, &found,
319 make_number (R_OK), false)
320 < 0)
321 return -1;
323 filename = SSDATA (found);
325 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
326 filename, &width, &height, &bitmap, &xhot, &yhot);
327 if (result != BitmapSuccess)
328 return -1;
330 id = x_allocate_bitmap_record (f);
331 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
332 dpyinfo->bitmaps[id - 1].have_mask = false;
333 dpyinfo->bitmaps[id - 1].refcount = 1;
334 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
335 dpyinfo->bitmaps[id - 1].depth = 1;
336 dpyinfo->bitmaps[id - 1].height = height;
337 dpyinfo->bitmaps[id - 1].width = width;
339 return id;
340 #endif /* HAVE_X_WINDOWS */
343 /* Free bitmap B. */
345 static void
346 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
348 #ifdef HAVE_X_WINDOWS
349 XFreePixmap (dpyinfo->display, bm->pixmap);
350 if (bm->have_mask)
351 XFreePixmap (dpyinfo->display, bm->mask);
352 #endif /* HAVE_X_WINDOWS */
354 #ifdef HAVE_NTGUI
355 DeleteObject (bm->pixmap);
356 #endif /* HAVE_NTGUI */
358 #ifdef HAVE_NS
359 ns_release_object (bm->img);
360 #endif
362 if (bm->file)
364 xfree (bm->file);
365 bm->file = NULL;
369 /* Remove reference to bitmap with id number ID. */
371 void
372 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
374 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
376 if (id > 0)
378 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
380 if (--bm->refcount == 0)
382 block_input ();
383 free_bitmap_record (dpyinfo, bm);
384 unblock_input ();
389 /* Free all the bitmaps for the display specified by DPYINFO. */
391 void
392 x_destroy_all_bitmaps (Display_Info *dpyinfo)
394 ptrdiff_t i;
395 Bitmap_Record *bm = dpyinfo->bitmaps;
397 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
398 if (bm->refcount > 0)
399 free_bitmap_record (dpyinfo, bm);
401 dpyinfo->bitmaps_last = 0;
404 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
405 XImagePtr *, Pixmap *);
406 static void x_destroy_x_image (XImagePtr ximg);
408 #ifdef HAVE_NTGUI
409 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
410 bool, HGDIOBJ *);
411 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
412 HGDIOBJ);
413 #else
414 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
415 static void image_unget_x_image (struct image *, bool, XImagePtr);
416 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
417 image_get_x_image (f, img, mask_p)
418 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
419 image_unget_x_image (img, mask_p, ximg)
420 #endif
422 #ifdef HAVE_X_WINDOWS
424 static void image_sync_to_pixmaps (struct frame *, struct image *);
426 /* Useful functions defined in the section
427 `Image type independent image structures' below. */
429 static unsigned long four_corners_best (XImagePtr ximg,
430 int *corners,
431 unsigned long width,
432 unsigned long height);
435 /* Create a mask of a bitmap. Note is this not a perfect mask.
436 It's nicer with some borders in this context */
438 void
439 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
441 Pixmap pixmap, mask;
442 XImagePtr ximg, mask_img;
443 unsigned long width, height;
444 bool result;
445 unsigned long bg;
446 unsigned long x, y, xp, xm, yp, ym;
447 GC gc;
449 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
451 if (!(id > 0))
452 return;
454 pixmap = x_bitmap_pixmap (f, id);
455 width = x_bitmap_width (f, id);
456 height = x_bitmap_height (f, id);
458 block_input ();
459 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
460 ~0, ZPixmap);
462 if (!ximg)
464 unblock_input ();
465 return;
468 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
470 unblock_input ();
471 if (!result)
473 XDestroyImage (ximg);
474 return;
477 bg = four_corners_best (ximg, NULL, width, height);
479 for (y = 0; y < ximg->height; ++y)
481 for (x = 0; x < ximg->width; ++x)
483 xp = x != ximg->width - 1 ? x + 1 : 0;
484 xm = x != 0 ? x - 1 : ximg->width - 1;
485 yp = y != ximg->height - 1 ? y + 1 : 0;
486 ym = y != 0 ? y - 1 : ximg->height - 1;
487 if (XGetPixel (ximg, x, y) == bg
488 && XGetPixel (ximg, x, yp) == bg
489 && XGetPixel (ximg, x, ym) == bg
490 && XGetPixel (ximg, xp, y) == bg
491 && XGetPixel (ximg, xp, yp) == bg
492 && XGetPixel (ximg, xp, ym) == bg
493 && XGetPixel (ximg, xm, y) == bg
494 && XGetPixel (ximg, xm, yp) == bg
495 && XGetPixel (ximg, xm, ym) == bg)
496 XPutPixel (mask_img, x, y, 0);
497 else
498 XPutPixel (mask_img, x, y, 1);
502 eassert (input_blocked_p ());
503 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
504 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
505 width, height);
506 XFreeGC (FRAME_X_DISPLAY (f), gc);
508 dpyinfo->bitmaps[id - 1].have_mask = true;
509 dpyinfo->bitmaps[id - 1].mask = mask;
511 XDestroyImage (ximg);
512 x_destroy_x_image (mask_img);
515 #endif /* HAVE_X_WINDOWS */
518 /***********************************************************************
519 Image types
520 ***********************************************************************/
522 /* List of supported image types. Use define_image_type to add new
523 types. Use lookup_image_type to find a type for a given symbol. */
525 static struct image_type *image_types;
527 /* Forward function prototypes. */
529 static struct image_type *lookup_image_type (Lisp_Object);
530 static void x_laplace (struct frame *, struct image *);
531 static void x_emboss (struct frame *, struct image *);
532 static void x_build_heuristic_mask (struct frame *, struct image *,
533 Lisp_Object);
534 #ifdef WINDOWSNT
535 #define CACHE_IMAGE_TYPE(type, status) \
536 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
537 #else
538 #define CACHE_IMAGE_TYPE(type, status)
539 #endif
541 #define ADD_IMAGE_TYPE(type) \
542 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
544 /* Define a new image type from TYPE. This adds a copy of TYPE to
545 image_types and caches the loading status of TYPE. */
547 static struct image_type *
548 define_image_type (struct image_type *type)
550 struct image_type *p = NULL;
551 int new_type = type->type;
552 bool type_valid = true;
554 block_input ();
556 for (p = image_types; p; p = p->next)
557 if (p->type == new_type)
558 goto done;
560 if (type->init)
562 #if defined HAVE_NTGUI && defined WINDOWSNT
563 /* If we failed to load the library before, don't try again. */
564 Lisp_Object tested = Fassq (builtin_lisp_symbol (new_type),
565 Vlibrary_cache);
566 if (CONSP (tested) && NILP (XCDR (tested)))
567 type_valid = false;
568 else
569 #endif
571 type_valid = type->init ();
572 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type),
573 type_valid ? Qt : Qnil);
577 if (type_valid)
579 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
580 The initialized data segment is read-only. */
581 p = xmalloc (sizeof *p);
582 *p = *type;
583 p->next = image_types;
584 image_types = p;
587 done:
588 unblock_input ();
589 return p;
593 /* Value is true if OBJECT is a valid Lisp image specification. A
594 valid image specification is a list whose car is the symbol
595 `image', and whose rest is a property list. The property list must
596 contain a value for key `:type'. That value must be the name of a
597 supported image type. The rest of the property list depends on the
598 image type. */
600 bool
601 valid_image_p (Lisp_Object object)
603 bool valid_p = 0;
605 if (IMAGEP (object))
607 Lisp_Object tem;
609 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
610 if (EQ (XCAR (tem), QCtype))
612 tem = XCDR (tem);
613 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
615 struct image_type *type;
616 type = lookup_image_type (XCAR (tem));
617 if (type)
618 valid_p = type->valid_p (object);
621 break;
625 return valid_p;
629 /* Log error message with format string FORMAT and argument ARG.
630 Signaling an error, e.g. when an image cannot be loaded, is not a
631 good idea because this would interrupt redisplay, and the error
632 message display would lead to another redisplay. This function
633 therefore simply displays a message. */
635 static void
636 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
638 add_to_log (format, arg1, arg2);
643 /***********************************************************************
644 Image specifications
645 ***********************************************************************/
647 enum image_value_type
649 IMAGE_DONT_CHECK_VALUE_TYPE,
650 IMAGE_STRING_VALUE,
651 IMAGE_STRING_OR_NIL_VALUE,
652 IMAGE_SYMBOL_VALUE,
653 IMAGE_POSITIVE_INTEGER_VALUE,
654 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
655 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
656 IMAGE_ASCENT_VALUE,
657 IMAGE_INTEGER_VALUE,
658 IMAGE_FUNCTION_VALUE,
659 IMAGE_NUMBER_VALUE,
660 IMAGE_BOOL_VALUE
663 /* Structure used when parsing image specifications. */
665 struct image_keyword
667 /* Name of keyword. */
668 const char *name;
670 /* The type of value allowed. */
671 enum image_value_type type;
673 /* True means key must be present. */
674 bool mandatory_p;
676 /* Used to recognize duplicate keywords in a property list. */
677 int count;
679 /* The value that was found. */
680 Lisp_Object value;
684 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
685 has the format (image KEYWORD VALUE ...). One of the keyword/
686 value pairs must be `:type TYPE'. KEYWORDS is a vector of
687 image_keywords structures of size NKEYWORDS describing other
688 allowed keyword/value pairs. Value is true if SPEC is valid. */
690 static bool
691 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
692 int nkeywords, Lisp_Object type)
694 int i;
695 Lisp_Object plist;
697 if (!IMAGEP (spec))
698 return 0;
700 plist = XCDR (spec);
701 while (CONSP (plist))
703 Lisp_Object key, value;
705 /* First element of a pair must be a symbol. */
706 key = XCAR (plist);
707 plist = XCDR (plist);
708 if (!SYMBOLP (key))
709 return 0;
711 /* There must follow a value. */
712 if (!CONSP (plist))
713 return 0;
714 value = XCAR (plist);
715 plist = XCDR (plist);
717 /* Find key in KEYWORDS. Error if not found. */
718 for (i = 0; i < nkeywords; ++i)
719 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
720 break;
722 if (i == nkeywords)
723 continue;
725 /* Record that we recognized the keyword. If a keywords
726 was found more than once, it's an error. */
727 keywords[i].value = value;
728 if (keywords[i].count > 1)
729 return 0;
730 ++keywords[i].count;
732 /* Check type of value against allowed type. */
733 switch (keywords[i].type)
735 case IMAGE_STRING_VALUE:
736 if (!STRINGP (value))
737 return 0;
738 break;
740 case IMAGE_STRING_OR_NIL_VALUE:
741 if (!STRINGP (value) && !NILP (value))
742 return 0;
743 break;
745 case IMAGE_SYMBOL_VALUE:
746 if (!SYMBOLP (value))
747 return 0;
748 break;
750 case IMAGE_POSITIVE_INTEGER_VALUE:
751 if (! RANGED_INTEGERP (1, value, INT_MAX))
752 return 0;
753 break;
755 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
756 if (RANGED_INTEGERP (0, value, INT_MAX))
757 break;
758 if (CONSP (value)
759 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
760 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
761 break;
762 return 0;
764 case IMAGE_ASCENT_VALUE:
765 if (SYMBOLP (value) && EQ (value, Qcenter))
766 break;
767 else if (RANGED_INTEGERP (0, value, 100))
768 break;
769 return 0;
771 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
772 /* Unlike the other integer-related cases, this one does not
773 verify that VALUE fits in 'int'. This is because callers
774 want EMACS_INT. */
775 if (!INTEGERP (value) || XINT (value) < 0)
776 return 0;
777 break;
779 case IMAGE_DONT_CHECK_VALUE_TYPE:
780 break;
782 case IMAGE_FUNCTION_VALUE:
783 value = indirect_function (value);
784 if (!NILP (Ffunctionp (value)))
785 break;
786 return 0;
788 case IMAGE_NUMBER_VALUE:
789 if (!INTEGERP (value) && !FLOATP (value))
790 return 0;
791 break;
793 case IMAGE_INTEGER_VALUE:
794 if (! TYPE_RANGED_INTEGERP (int, value))
795 return 0;
796 break;
798 case IMAGE_BOOL_VALUE:
799 if (!NILP (value) && !EQ (value, Qt))
800 return 0;
801 break;
803 default:
804 emacs_abort ();
805 break;
808 if (EQ (key, QCtype) && !EQ (type, value))
809 return 0;
812 /* Check that all mandatory fields are present. */
813 for (i = 0; i < nkeywords; ++i)
814 if (keywords[i].mandatory_p && keywords[i].count == 0)
815 return 0;
817 return NILP (plist);
821 /* Return the value of KEY in image specification SPEC. Value is nil
822 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
823 was found in SPEC. */
825 static Lisp_Object
826 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
828 Lisp_Object tail;
830 eassert (valid_image_p (spec));
832 for (tail = XCDR (spec);
833 CONSP (tail) && CONSP (XCDR (tail));
834 tail = XCDR (XCDR (tail)))
836 if (EQ (XCAR (tail), key))
838 if (found)
839 *found = 1;
840 return XCAR (XCDR (tail));
844 if (found)
845 *found = 0;
846 return Qnil;
850 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
851 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
852 PIXELS non-nil means return the size in pixels, otherwise return the
853 size in canonical character units.
854 FRAME is the frame on which the image will be displayed. FRAME nil
855 or omitted means use the selected frame. */)
856 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
858 Lisp_Object size;
860 size = Qnil;
861 if (valid_image_p (spec))
863 struct frame *f = decode_window_system_frame (frame);
864 ptrdiff_t id = lookup_image (f, spec);
865 struct image *img = IMAGE_FROM_ID (f, id);
866 int width = img->width + 2 * img->hmargin;
867 int height = img->height + 2 * img->vmargin;
869 if (NILP (pixels))
870 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
871 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
872 else
873 size = Fcons (make_number (width), make_number (height));
875 else
876 error ("Invalid image specification");
878 return size;
882 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
883 doc: /* Return t if image SPEC has a mask bitmap.
884 FRAME is the frame on which the image will be displayed. FRAME nil
885 or omitted means use the selected frame. */)
886 (Lisp_Object spec, Lisp_Object frame)
888 Lisp_Object mask;
890 mask = Qnil;
891 if (valid_image_p (spec))
893 struct frame *f = decode_window_system_frame (frame);
894 ptrdiff_t id = lookup_image (f, spec);
895 struct image *img = IMAGE_FROM_ID (f, id);
896 if (img->mask)
897 mask = Qt;
899 else
900 error ("Invalid image specification");
902 return mask;
905 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
906 doc: /* Return metadata for image SPEC.
907 FRAME is the frame on which the image will be displayed. FRAME nil
908 or omitted means use the selected frame. */)
909 (Lisp_Object spec, Lisp_Object frame)
911 Lisp_Object ext;
913 ext = Qnil;
914 if (valid_image_p (spec))
916 struct frame *f = decode_window_system_frame (frame);
917 ptrdiff_t id = lookup_image (f, spec);
918 struct image *img = IMAGE_FROM_ID (f, id);
919 ext = img->lisp_data;
922 return ext;
926 /***********************************************************************
927 Image type independent image structures
928 ***********************************************************************/
930 #define MAX_IMAGE_SIZE 10.0
931 /* Allocate and return a new image structure for image specification
932 SPEC. SPEC has a hash value of HASH. */
934 static struct image *
935 make_image (Lisp_Object spec, EMACS_UINT hash)
937 struct image *img = xzalloc (sizeof *img);
938 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
940 eassert (valid_image_p (spec));
941 img->dependencies = NILP (file) ? Qnil : list1 (file);
942 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
943 eassert (img->type != NULL);
944 img->spec = spec;
945 img->lisp_data = Qnil;
946 img->ascent = DEFAULT_IMAGE_ASCENT;
947 img->hash = hash;
948 img->corners[BOT_CORNER] = -1; /* Full image */
949 return img;
953 /* Free image IMG which was used on frame F, including its resources. */
955 static void
956 free_image (struct frame *f, struct image *img)
958 if (img)
960 struct image_cache *c = FRAME_IMAGE_CACHE (f);
962 /* Remove IMG from the hash table of its cache. */
963 if (img->prev)
964 img->prev->next = img->next;
965 else
966 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
968 if (img->next)
969 img->next->prev = img->prev;
971 c->images[img->id] = NULL;
973 /* Windows NT redefines 'free', but in this file, we need to
974 avoid the redefinition. */
975 #ifdef WINDOWSNT
976 #undef free
977 #endif
978 /* Free resources, then free IMG. */
979 img->type->free (f, img);
980 xfree (img);
984 /* Return true if the given widths and heights are valid for display. */
986 static bool
987 check_image_size (struct frame *f, int width, int height)
989 int w, h;
991 if (width <= 0 || height <= 0)
992 return 0;
994 if (INTEGERP (Vmax_image_size))
995 return (width <= XINT (Vmax_image_size)
996 && height <= XINT (Vmax_image_size));
997 else if (FLOATP (Vmax_image_size))
999 if (f != NULL)
1001 w = FRAME_PIXEL_WIDTH (f);
1002 h = FRAME_PIXEL_HEIGHT (f);
1004 else
1005 w = h = 1024; /* Arbitrary size for unknown frame. */
1006 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1007 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1009 else
1010 return 1;
1013 /* Prepare image IMG for display on frame F. Must be called before
1014 drawing an image. */
1016 void
1017 prepare_image_for_display (struct frame *f, struct image *img)
1019 /* We're about to display IMG, so set its timestamp to `now'. */
1020 img->timestamp = current_timespec ();
1022 /* If IMG doesn't have a pixmap yet, load it now, using the image
1023 type dependent loader function. */
1024 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1025 img->load_failed_p = ! img->type->load (f, img);
1027 #ifdef HAVE_X_WINDOWS
1028 if (!img->load_failed_p)
1030 block_input ();
1031 image_sync_to_pixmaps (f, img);
1032 unblock_input ();
1034 #endif
1038 /* Value is the number of pixels for the ascent of image IMG when
1039 drawn in face FACE. */
1042 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1044 int height;
1045 int ascent;
1047 if (slice->height == img->height)
1048 height = img->height + img->vmargin;
1049 else if (slice->y == 0)
1050 height = slice->height + img->vmargin;
1051 else
1052 height = slice->height;
1054 if (img->ascent == CENTERED_IMAGE_ASCENT)
1056 if (face->font)
1058 #ifdef HAVE_NTGUI
1059 /* W32 specific version. Why?. ++kfs */
1060 ascent = height / 2 - (FONT_DESCENT (face->font)
1061 - FONT_BASE (face->font)) / 2;
1062 #else
1063 /* This expression is arranged so that if the image can't be
1064 exactly centered, it will be moved slightly up. This is
1065 because a typical font is `top-heavy' (due to the presence
1066 uppercase letters), so the image placement should err towards
1067 being top-heavy too. It also just generally looks better. */
1068 ascent = (height + FONT_BASE (face->font)
1069 - FONT_DESCENT (face->font) + 1) / 2;
1070 #endif /* HAVE_NTGUI */
1072 else
1073 ascent = height / 2;
1075 else
1076 ascent = height * (img->ascent / 100.0);
1078 return ascent;
1082 /* Image background colors. */
1084 /* Find the "best" corner color of a bitmap.
1085 On W32, XIMG is assumed to a device context with the bitmap selected. */
1087 static RGB_PIXEL_COLOR
1088 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1089 unsigned long width, unsigned long height)
1091 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1092 int i, best_count;
1094 if (corners && corners[BOT_CORNER] >= 0)
1096 /* Get the colors at the corner_pixels of ximg. */
1097 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1098 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1099 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1100 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1102 else
1104 /* Get the colors at the corner_pixels of ximg. */
1105 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1106 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1107 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1108 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1110 /* Choose the most frequently found color as background. */
1111 for (i = best_count = 0; i < 4; ++i)
1113 int j, n;
1115 for (j = n = 0; j < 4; ++j)
1116 if (corner_pixels[i] == corner_pixels[j])
1117 ++n;
1119 if (n > best_count)
1120 best = corner_pixels[i], best_count = n;
1123 return best;
1126 /* Portability macros */
1128 #ifdef HAVE_NTGUI
1130 #define Free_Pixmap(display, pixmap) \
1131 DeleteObject (pixmap)
1133 #elif defined (HAVE_NS)
1135 #define Free_Pixmap(display, pixmap) \
1136 ns_release_object (pixmap)
1138 #else
1140 #define Free_Pixmap(display, pixmap) \
1141 XFreePixmap (display, pixmap)
1143 #endif /* !HAVE_NTGUI && !HAVE_NS */
1146 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1147 it is guessed heuristically. If non-zero, XIMG is an existing
1148 XImage object (or device context with the image selected on W32) to
1149 use for the heuristic. */
1151 RGB_PIXEL_COLOR
1152 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1154 if (! img->background_valid)
1155 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1157 bool free_ximg = !ximg;
1158 #ifdef HAVE_NTGUI
1159 HGDIOBJ prev;
1160 #endif /* HAVE_NTGUI */
1162 if (free_ximg)
1163 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1165 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1167 if (free_ximg)
1168 image_unget_x_image_or_dc (img, 0, ximg, prev);
1170 img->background_valid = 1;
1173 return img->background;
1176 /* Return the `background_transparent' field of IMG. If IMG doesn't
1177 have one yet, it is guessed heuristically. If non-zero, MASK is an
1178 existing XImage object to use for the heuristic. */
1181 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1183 if (! img->background_transparent_valid)
1184 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1186 if (img->mask)
1188 bool free_mask = !mask;
1189 #ifdef HAVE_NTGUI
1190 HGDIOBJ prev;
1191 #endif /* HAVE_NTGUI */
1193 if (free_mask)
1194 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1196 img->background_transparent
1197 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1199 if (free_mask)
1200 image_unget_x_image_or_dc (img, 1, mask, prev);
1202 else
1203 img->background_transparent = 0;
1205 img->background_transparent_valid = 1;
1208 return img->background_transparent;
1211 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1212 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1214 /* Store F's background color into *BGCOLOR. */
1215 static void
1216 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1218 #ifndef HAVE_NS
1219 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1220 x_query_color (f, bgcolor);
1221 #else
1222 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1223 #endif
1226 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1228 /***********************************************************************
1229 Helper functions for X image types
1230 ***********************************************************************/
1232 /* Clear X resources of image IMG on frame F according to FLAGS.
1233 FLAGS is bitwise-or of the following masks:
1234 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1235 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1236 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1237 any. */
1239 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1240 #define CLEAR_IMAGE_MASK (1 << 1)
1241 #define CLEAR_IMAGE_COLORS (1 << 2)
1243 static void
1244 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1246 if (flags & CLEAR_IMAGE_PIXMAP)
1248 if (img->pixmap)
1250 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1251 img->pixmap = NO_PIXMAP;
1252 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1253 img->background_valid = 0;
1255 #ifdef HAVE_X_WINDOWS
1256 if (img->ximg)
1258 x_destroy_x_image (img->ximg);
1259 img->ximg = NULL;
1260 img->background_valid = 0;
1262 #endif
1265 if (flags & CLEAR_IMAGE_MASK)
1267 if (img->mask)
1269 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1270 img->mask = NO_PIXMAP;
1271 img->background_transparent_valid = 0;
1273 #ifdef HAVE_X_WINDOWS
1274 if (img->mask_img)
1276 x_destroy_x_image (img->mask_img);
1277 img->mask_img = NULL;
1278 img->background_transparent_valid = 0;
1280 #endif
1283 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1285 /* W32_TODO: color table support. */
1286 #ifdef HAVE_X_WINDOWS
1287 x_free_colors (f, img->colors, img->ncolors);
1288 #endif /* HAVE_X_WINDOWS */
1289 xfree (img->colors);
1290 img->colors = NULL;
1291 img->ncolors = 0;
1296 /* Free X resources of image IMG which is used on frame F. */
1298 static void
1299 x_clear_image (struct frame *f, struct image *img)
1301 block_input ();
1302 x_clear_image_1 (f, img,
1303 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1304 unblock_input ();
1308 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1309 cannot be allocated, use DFLT. Add a newly allocated color to
1310 IMG->colors, so that it can be freed again. Value is the pixel
1311 color. */
1313 static unsigned long
1314 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1315 unsigned long dflt)
1317 XColor color;
1318 unsigned long result;
1320 eassert (STRINGP (color_name));
1322 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1323 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1324 INT_MAX))
1326 /* This isn't called frequently so we get away with simply
1327 reallocating the color vector to the needed size, here. */
1328 ptrdiff_t ncolors = img->ncolors + 1;
1329 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1330 img->colors[ncolors - 1] = color.pixel;
1331 img->ncolors = ncolors;
1332 result = color.pixel;
1334 else
1335 result = dflt;
1337 return result;
1342 /***********************************************************************
1343 Image Cache
1344 ***********************************************************************/
1346 static void cache_image (struct frame *f, struct image *img);
1348 /* Return a new, initialized image cache that is allocated from the
1349 heap. Call free_image_cache to free an image cache. */
1351 struct image_cache *
1352 make_image_cache (void)
1354 struct image_cache *c = xmalloc (sizeof *c);
1356 c->size = 50;
1357 c->used = c->refcount = 0;
1358 c->images = xmalloc (c->size * sizeof *c->images);
1359 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1360 return c;
1364 /* Find an image matching SPEC in the cache, and return it. If no
1365 image is found, return NULL. */
1366 static struct image *
1367 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1369 struct image *img;
1370 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1371 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1373 if (!c) return NULL;
1375 /* If the image spec does not specify a background color, the cached
1376 image must have the same background color as the current frame.
1377 The foreground color must also match, for the sake of monochrome
1378 images.
1380 In fact, we could ignore the foreground color matching condition
1381 for color images, or if the image spec specifies :foreground;
1382 similarly we could ignore the background color matching condition
1383 for formats that don't use transparency (such as jpeg), or if the
1384 image spec specifies :background. However, the extra memory
1385 usage is probably negligible in practice, so we don't bother. */
1387 for (img = c->buckets[i]; img; img = img->next)
1388 if (img->hash == hash
1389 && !NILP (Fequal (img->spec, spec))
1390 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1391 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1392 break;
1393 return img;
1397 /* Search frame F for an image with spec SPEC, and free it. */
1399 static void
1400 uncache_image (struct frame *f, Lisp_Object spec)
1402 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1403 if (img)
1405 free_image (f, img);
1406 /* As display glyphs may still be referring to the image ID, we
1407 must garbage the frame (Bug#6426). */
1408 SET_FRAME_GARBAGED (f);
1413 /* Free image cache of frame F. Be aware that X frames share images
1414 caches. */
1416 void
1417 free_image_cache (struct frame *f)
1419 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1420 if (c)
1422 ptrdiff_t i;
1424 /* Cache should not be referenced by any frame when freed. */
1425 eassert (c->refcount == 0);
1427 for (i = 0; i < c->used; ++i)
1428 free_image (f, c->images[i]);
1429 xfree (c->images);
1430 xfree (c->buckets);
1431 xfree (c);
1432 FRAME_IMAGE_CACHE (f) = NULL;
1437 /* Clear image cache of frame F. FILTER=t means free all images.
1438 FILTER=nil means clear only images that haven't been
1439 displayed for some time.
1440 Else, only free the images which have FILTER in their `dependencies'.
1441 Should be called from time to time to reduce the number of loaded images.
1442 If image-cache-eviction-delay is non-nil, this frees images in the cache
1443 which weren't displayed for at least that many seconds. */
1445 static void
1446 clear_image_cache (struct frame *f, Lisp_Object filter)
1448 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1450 if (c)
1452 ptrdiff_t i, nfreed = 0;
1454 /* Block input so that we won't be interrupted by a SIGIO
1455 while being in an inconsistent state. */
1456 block_input ();
1458 if (!NILP (filter))
1460 /* Filter image cache. */
1461 for (i = 0; i < c->used; ++i)
1463 struct image *img = c->images[i];
1464 if (img && (EQ (Qt, filter)
1465 || !NILP (Fmember (filter, img->dependencies))))
1467 free_image (f, img);
1468 ++nfreed;
1472 else if (INTEGERP (Vimage_cache_eviction_delay))
1474 /* Free cache based on timestamp. */
1475 struct timespec old, t;
1476 double delay;
1477 ptrdiff_t nimages = 0;
1479 for (i = 0; i < c->used; ++i)
1480 if (c->images[i])
1481 nimages++;
1483 /* If the number of cached images has grown unusually large,
1484 decrease the cache eviction delay (Bug#6230). */
1485 delay = XINT (Vimage_cache_eviction_delay);
1486 if (nimages > 40)
1487 delay = 1600 * delay / nimages / nimages;
1488 delay = max (delay, 1);
1490 t = current_timespec ();
1491 old = timespec_sub (t, dtotimespec (delay));
1493 for (i = 0; i < c->used; ++i)
1495 struct image *img = c->images[i];
1496 if (img && timespec_cmp (img->timestamp, old) < 0)
1498 free_image (f, img);
1499 ++nfreed;
1504 /* We may be clearing the image cache because, for example,
1505 Emacs was iconified for a longer period of time. In that
1506 case, current matrices may still contain references to
1507 images freed above. So, clear these matrices. */
1508 if (nfreed)
1510 Lisp_Object tail, frame;
1512 FOR_EACH_FRAME (tail, frame)
1514 struct frame *fr = XFRAME (frame);
1515 if (FRAME_IMAGE_CACHE (fr) == c)
1516 clear_current_matrices (fr);
1519 windows_or_buffers_changed = 19;
1522 unblock_input ();
1526 void
1527 clear_image_caches (Lisp_Object filter)
1529 /* FIXME: We want to do
1530 * struct terminal *t;
1531 * for (t = terminal_list; t; t = t->next_terminal)
1532 * clear_image_cache (t, filter); */
1533 Lisp_Object tail, frame;
1534 FOR_EACH_FRAME (tail, frame)
1535 if (FRAME_WINDOW_P (XFRAME (frame)))
1536 clear_image_cache (XFRAME (frame), filter);
1539 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1540 0, 1, 0,
1541 doc: /* Clear the image cache.
1542 FILTER nil or a frame means clear all images in the selected frame.
1543 FILTER t means clear the image caches of all frames.
1544 Anything else, means only clear those images which refer to FILTER,
1545 which is then usually a filename. */)
1546 (Lisp_Object filter)
1548 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1549 clear_image_caches (filter);
1550 else
1551 clear_image_cache (decode_window_system_frame (filter), Qt);
1553 return Qnil;
1557 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1558 1, 2, 0,
1559 doc: /* Flush the image with specification SPEC on frame FRAME.
1560 This removes the image from the Emacs image cache. If SPEC specifies
1561 an image file, the next redisplay of this image will read from the
1562 current contents of that file.
1564 FRAME nil or omitted means use the selected frame.
1565 FRAME t means refresh the image on all frames. */)
1566 (Lisp_Object spec, Lisp_Object frame)
1568 if (!valid_image_p (spec))
1569 error ("Invalid image specification");
1571 if (EQ (frame, Qt))
1573 Lisp_Object tail;
1574 FOR_EACH_FRAME (tail, frame)
1576 struct frame *f = XFRAME (frame);
1577 if (FRAME_WINDOW_P (f))
1578 uncache_image (f, spec);
1581 else
1582 uncache_image (decode_window_system_frame (frame), spec);
1584 return Qnil;
1588 /* Compute masks and transform image IMG on frame F, as specified
1589 by the image's specification, */
1591 static void
1592 postprocess_image (struct frame *f, struct image *img)
1594 /* Manipulation of the image's mask. */
1595 if (img->pixmap)
1597 Lisp_Object conversion, spec;
1598 Lisp_Object mask;
1600 spec = img->spec;
1602 /* `:heuristic-mask t'
1603 `:mask heuristic'
1604 means build a mask heuristically.
1605 `:heuristic-mask (R G B)'
1606 `:mask (heuristic (R G B))'
1607 means build a mask from color (R G B) in the
1608 image.
1609 `:mask nil'
1610 means remove a mask, if any. */
1612 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1613 if (!NILP (mask))
1614 x_build_heuristic_mask (f, img, mask);
1615 else
1617 bool found_p;
1619 mask = image_spec_value (spec, QCmask, &found_p);
1621 if (EQ (mask, Qheuristic))
1622 x_build_heuristic_mask (f, img, Qt);
1623 else if (CONSP (mask)
1624 && EQ (XCAR (mask), Qheuristic))
1626 if (CONSP (XCDR (mask)))
1627 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1628 else
1629 x_build_heuristic_mask (f, img, XCDR (mask));
1631 else if (NILP (mask) && found_p && img->mask)
1632 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1636 /* Should we apply an image transformation algorithm? */
1637 conversion = image_spec_value (spec, QCconversion, NULL);
1638 if (EQ (conversion, Qdisabled))
1639 x_disable_image (f, img);
1640 else if (EQ (conversion, Qlaplace))
1641 x_laplace (f, img);
1642 else if (EQ (conversion, Qemboss))
1643 x_emboss (f, img);
1644 else if (CONSP (conversion)
1645 && EQ (XCAR (conversion), Qedge_detection))
1647 Lisp_Object tem;
1648 tem = XCDR (conversion);
1649 if (CONSP (tem))
1650 x_edge_detection (f, img,
1651 Fplist_get (tem, QCmatrix),
1652 Fplist_get (tem, QCcolor_adjustment));
1658 /* Return the id of image with Lisp specification SPEC on frame F.
1659 SPEC must be a valid Lisp image specification (see valid_image_p). */
1661 ptrdiff_t
1662 lookup_image (struct frame *f, Lisp_Object spec)
1664 struct image *img;
1665 EMACS_UINT hash;
1667 /* F must be a window-system frame, and SPEC must be a valid image
1668 specification. */
1669 eassert (FRAME_WINDOW_P (f));
1670 eassert (valid_image_p (spec));
1672 /* Look up SPEC in the hash table of the image cache. */
1673 hash = sxhash (spec, 0);
1674 img = search_image_cache (f, spec, hash);
1675 if (img && img->load_failed_p)
1677 free_image (f, img);
1678 img = NULL;
1681 /* If not found, create a new image and cache it. */
1682 if (img == NULL)
1684 block_input ();
1685 img = make_image (spec, hash);
1686 cache_image (f, img);
1687 img->load_failed_p = ! img->type->load (f, img);
1688 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1689 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1691 /* If we can't load the image, and we don't have a width and
1692 height, use some arbitrary width and height so that we can
1693 draw a rectangle for it. */
1694 if (img->load_failed_p)
1696 Lisp_Object value;
1698 value = image_spec_value (spec, QCwidth, NULL);
1699 img->width = (INTEGERP (value)
1700 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1701 value = image_spec_value (spec, QCheight, NULL);
1702 img->height = (INTEGERP (value)
1703 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1705 else
1707 /* Handle image type independent image attributes
1708 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1709 `:background COLOR'. */
1710 Lisp_Object ascent, margin, relief, bg;
1711 int relief_bound;
1713 ascent = image_spec_value (spec, QCascent, NULL);
1714 if (INTEGERP (ascent))
1715 img->ascent = XFASTINT (ascent);
1716 else if (EQ (ascent, Qcenter))
1717 img->ascent = CENTERED_IMAGE_ASCENT;
1719 margin = image_spec_value (spec, QCmargin, NULL);
1720 if (INTEGERP (margin))
1721 img->vmargin = img->hmargin = XFASTINT (margin);
1722 else if (CONSP (margin))
1724 img->hmargin = XFASTINT (XCAR (margin));
1725 img->vmargin = XFASTINT (XCDR (margin));
1728 relief = image_spec_value (spec, QCrelief, NULL);
1729 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1730 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1732 img->relief = XINT (relief);
1733 img->hmargin += eabs (img->relief);
1734 img->vmargin += eabs (img->relief);
1737 if (! img->background_valid)
1739 bg = image_spec_value (img->spec, QCbackground, NULL);
1740 if (!NILP (bg))
1742 img->background
1743 = x_alloc_image_color (f, img, bg,
1744 FRAME_BACKGROUND_PIXEL (f));
1745 img->background_valid = 1;
1749 /* Do image transformations and compute masks, unless we
1750 don't have the image yet. */
1751 if (!EQ (builtin_lisp_symbol (img->type->type), Qpostscript))
1752 postprocess_image (f, img);
1755 unblock_input ();
1758 /* We're using IMG, so set its timestamp to `now'. */
1759 img->timestamp = current_timespec ();
1761 /* Value is the image id. */
1762 return img->id;
1766 /* Cache image IMG in the image cache of frame F. */
1768 static void
1769 cache_image (struct frame *f, struct image *img)
1771 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1772 ptrdiff_t i;
1774 /* Find a free slot in c->images. */
1775 for (i = 0; i < c->used; ++i)
1776 if (c->images[i] == NULL)
1777 break;
1779 /* If no free slot found, maybe enlarge c->images. */
1780 if (i == c->used && c->used == c->size)
1781 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1783 /* Add IMG to c->images, and assign IMG an id. */
1784 c->images[i] = img;
1785 img->id = i;
1786 if (i == c->used)
1787 ++c->used;
1789 /* Add IMG to the cache's hash table. */
1790 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1791 img->next = c->buckets[i];
1792 if (img->next)
1793 img->next->prev = img;
1794 img->prev = NULL;
1795 c->buckets[i] = img;
1799 /* Call FN on every image in the image cache of frame F. Used to mark
1800 Lisp Objects in the image cache. */
1802 /* Mark Lisp objects in image IMG. */
1804 static void
1805 mark_image (struct image *img)
1807 mark_object (img->spec);
1808 mark_object (img->dependencies);
1810 if (!NILP (img->lisp_data))
1811 mark_object (img->lisp_data);
1815 void
1816 mark_image_cache (struct image_cache *c)
1818 if (c)
1820 ptrdiff_t i;
1821 for (i = 0; i < c->used; ++i)
1822 if (c->images[i])
1823 mark_image (c->images[i]);
1829 /***********************************************************************
1830 X / NS / W32 support code
1831 ***********************************************************************/
1833 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1834 windowing system.
1835 WIDTH and HEIGHT must both be positive.
1836 If XIMG is null, assume it is a bitmap. */
1837 static bool
1838 x_check_image_size (XImagePtr ximg, int width, int height)
1840 #ifdef HAVE_X_WINDOWS
1841 /* Respect Xlib's limits: it cannot deal with images that have more
1842 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1843 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1844 enum
1846 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1847 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1850 int bitmap_pad, depth, bytes_per_line;
1851 if (ximg)
1853 bitmap_pad = ximg->bitmap_pad;
1854 depth = ximg->depth;
1855 bytes_per_line = ximg->bytes_per_line;
1857 else
1859 bitmap_pad = 8;
1860 depth = 1;
1861 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1863 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1864 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1865 #else
1866 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1867 For now, assume that every image size is allowed on these systems. */
1868 return 1;
1869 #endif
1872 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1873 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1874 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1875 via xmalloc. Print error messages via image_error if an error
1876 occurs. Value is true if successful.
1878 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1879 should indicate the bit depth of the image. */
1881 static bool
1882 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1883 XImagePtr *ximg, Pixmap *pixmap)
1885 #ifdef HAVE_X_WINDOWS
1886 Display *display = FRAME_X_DISPLAY (f);
1887 Window window = FRAME_X_WINDOW (f);
1888 Screen *screen = FRAME_X_SCREEN (f);
1890 eassert (input_blocked_p ());
1892 if (depth <= 0)
1893 depth = DefaultDepthOfScreen (screen);
1894 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1895 depth, ZPixmap, 0, NULL, width, height,
1896 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1897 if (*ximg == NULL)
1899 image_error ("Unable to allocate X image", Qnil, Qnil);
1900 return 0;
1903 if (! x_check_image_size (*ximg, width, height))
1905 x_destroy_x_image (*ximg);
1906 *ximg = NULL;
1907 image_error ("Image too large (%dx%d)",
1908 make_number (width), make_number (height));
1909 return 0;
1912 /* Allocate image raster. */
1913 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1915 /* Allocate a pixmap of the same size. */
1916 *pixmap = XCreatePixmap (display, window, width, height, depth);
1917 if (*pixmap == NO_PIXMAP)
1919 x_destroy_x_image (*ximg);
1920 *ximg = NULL;
1921 image_error ("Unable to create X pixmap", Qnil, Qnil);
1922 return 0;
1925 return 1;
1926 #endif /* HAVE_X_WINDOWS */
1928 #ifdef HAVE_NTGUI
1930 BITMAPINFOHEADER *header;
1931 HDC hdc;
1932 int scanline_width_bits;
1933 int remainder;
1934 int palette_colors = 0;
1936 if (depth == 0)
1937 depth = 24;
1939 if (depth != 1 && depth != 4 && depth != 8
1940 && depth != 16 && depth != 24 && depth != 32)
1942 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1943 return 0;
1946 scanline_width_bits = width * depth;
1947 remainder = scanline_width_bits % 32;
1949 if (remainder)
1950 scanline_width_bits += 32 - remainder;
1952 /* Bitmaps with a depth less than 16 need a palette. */
1953 /* BITMAPINFO structure already contains the first RGBQUAD. */
1954 if (depth < 16)
1955 palette_colors = 1 << (depth - 1);
1957 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1959 header = &(*ximg)->info.bmiHeader;
1960 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
1961 header->biSize = sizeof (*header);
1962 header->biWidth = width;
1963 header->biHeight = -height; /* negative indicates a top-down bitmap. */
1964 header->biPlanes = 1;
1965 header->biBitCount = depth;
1966 header->biCompression = BI_RGB;
1967 header->biClrUsed = palette_colors;
1969 /* TODO: fill in palette. */
1970 if (depth == 1)
1972 (*ximg)->info.bmiColors[0].rgbBlue = 0;
1973 (*ximg)->info.bmiColors[0].rgbGreen = 0;
1974 (*ximg)->info.bmiColors[0].rgbRed = 0;
1975 (*ximg)->info.bmiColors[0].rgbReserved = 0;
1976 (*ximg)->info.bmiColors[1].rgbBlue = 255;
1977 (*ximg)->info.bmiColors[1].rgbGreen = 255;
1978 (*ximg)->info.bmiColors[1].rgbRed = 255;
1979 (*ximg)->info.bmiColors[1].rgbReserved = 0;
1982 hdc = get_frame_dc (f);
1984 /* Create a DIBSection and raster array for the bitmap,
1985 and store its handle in *pixmap. */
1986 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
1987 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
1988 /* casting avoids a GCC warning */
1989 (void **)&((*ximg)->data), NULL, 0);
1991 /* Realize display palette and garbage all frames. */
1992 release_frame_dc (f, hdc);
1994 if (*pixmap == NULL)
1996 DWORD err = GetLastError ();
1997 Lisp_Object errcode;
1998 /* All system errors are < 10000, so the following is safe. */
1999 XSETINT (errcode, err);
2000 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2001 x_destroy_x_image (*ximg);
2002 *ximg = NULL;
2003 return 0;
2006 return 1;
2008 #endif /* HAVE_NTGUI */
2010 #ifdef HAVE_NS
2011 *pixmap = ns_image_for_XPM (width, height, depth);
2012 if (*pixmap == 0)
2014 *ximg = NULL;
2015 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2016 return 0;
2018 *ximg = *pixmap;
2019 return 1;
2020 #endif
2024 /* Destroy XImage XIMG. Free XIMG->data. */
2026 static void
2027 x_destroy_x_image (XImagePtr ximg)
2029 eassert (input_blocked_p ());
2030 if (ximg)
2032 #ifdef HAVE_X_WINDOWS
2033 xfree (ximg->data);
2034 ximg->data = NULL;
2035 XDestroyImage (ximg);
2036 #endif /* HAVE_X_WINDOWS */
2037 #ifdef HAVE_NTGUI
2038 /* Data will be freed by DestroyObject. */
2039 ximg->data = NULL;
2040 xfree (ximg);
2041 #endif /* HAVE_NTGUI */
2042 #ifdef HAVE_NS
2043 ns_release_object (ximg);
2044 #endif /* HAVE_NS */
2049 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2050 are width and height of both the image and pixmap. */
2052 static void
2053 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2055 #ifdef HAVE_X_WINDOWS
2056 GC gc;
2058 eassert (input_blocked_p ());
2059 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2060 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2061 XFreeGC (FRAME_X_DISPLAY (f), gc);
2062 #endif /* HAVE_X_WINDOWS */
2064 #ifdef HAVE_NTGUI
2065 #if 0 /* I don't think this is necessary looking at where it is used. */
2066 HDC hdc = get_frame_dc (f);
2067 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2068 release_frame_dc (f, hdc);
2069 #endif
2070 #endif /* HAVE_NTGUI */
2072 #ifdef HAVE_NS
2073 eassert (ximg == pixmap);
2074 ns_retain_object (ximg);
2075 #endif
2078 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2079 with image_put_x_image. */
2081 static bool
2082 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2083 int width, int height, int depth,
2084 XImagePtr *ximg, bool mask_p)
2086 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2088 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2089 !mask_p ? &img->pixmap : &img->mask);
2092 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2093 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2094 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2095 On the other platforms, it puts XIMG into the pixmap, then frees
2096 the X image and its buffer. */
2098 static void
2099 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2100 bool mask_p)
2102 #ifdef HAVE_X_WINDOWS
2103 if (!mask_p)
2105 eassert (img->ximg == NULL);
2106 img->ximg = ximg;
2108 else
2110 eassert (img->mask_img == NULL);
2111 img->mask_img = ximg;
2113 #else
2114 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2115 img->width, img->height);
2116 x_destroy_x_image (ximg);
2117 #endif
2120 #ifdef HAVE_X_WINDOWS
2121 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2122 the X images and their buffers. */
2124 static void
2125 image_sync_to_pixmaps (struct frame *f, struct image *img)
2127 if (img->ximg)
2129 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2130 x_destroy_x_image (img->ximg);
2131 img->ximg = NULL;
2133 if (img->mask_img)
2135 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2136 x_destroy_x_image (img->mask_img);
2137 img->mask_img = NULL;
2140 #endif
2142 #ifdef HAVE_NTGUI
2143 /* Create a memory device context for IMG on frame F. It stores the
2144 currently selected GDI object into *PREV for future restoration by
2145 image_unget_x_image_or_dc. */
2147 static XImagePtr_or_DC
2148 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2149 HGDIOBJ *prev)
2151 HDC frame_dc = get_frame_dc (f);
2152 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2154 release_frame_dc (f, frame_dc);
2155 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2157 return ximg;
2160 static void
2161 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2162 XImagePtr_or_DC ximg, HGDIOBJ prev)
2164 SelectObject (ximg, prev);
2165 DeleteDC (ximg);
2167 #else /* !HAVE_NTGUI */
2168 /* Get the X image for IMG on frame F. The resulting X image data
2169 should be treated as read-only at least on X. */
2171 static XImagePtr
2172 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2174 #ifdef HAVE_X_WINDOWS
2175 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2177 if (ximg_in_img)
2178 return ximg_in_img;
2179 else
2180 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2181 0, 0, img->width, img->height, ~0, ZPixmap);
2182 #elif defined (HAVE_NS)
2183 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2185 ns_retain_object (pixmap);
2186 return pixmap;
2187 #endif
2190 static void
2191 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2193 #ifdef HAVE_X_WINDOWS
2194 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2196 if (ximg_in_img)
2197 eassert (ximg == ximg_in_img);
2198 else
2199 XDestroyImage (ximg);
2200 #elif defined (HAVE_NS)
2201 ns_release_object (ximg);
2202 #endif
2204 #endif /* !HAVE_NTGUI */
2207 /***********************************************************************
2208 File Handling
2209 ***********************************************************************/
2211 /* Find image file FILE. Look in data-directory/images, then
2212 x-bitmap-file-path. Value is the encoded full name of the file
2213 found, or nil if not found. */
2215 Lisp_Object
2216 x_find_image_file (Lisp_Object file)
2218 Lisp_Object file_found, search_path;
2219 int fd;
2221 /* TODO I think this should use something like image-load-path
2222 instead. Unfortunately, that can contain non-string elements. */
2223 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2224 Vdata_directory),
2225 Vx_bitmap_file_path);
2227 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2228 fd = openp (search_path, file, Qnil, &file_found, Qnil, false);
2230 if (fd == -1)
2231 file_found = Qnil;
2232 else
2234 file_found = ENCODE_FILE (file_found);
2235 if (fd != -2)
2236 emacs_close (fd);
2239 return file_found;
2243 /* Read FILE into memory. Value is a pointer to a buffer allocated
2244 with xmalloc holding FILE's contents. Value is null if an error
2245 occurred. *SIZE is set to the size of the file. */
2247 static unsigned char *
2248 slurp_file (char *file, ptrdiff_t *size)
2250 FILE *fp = emacs_fopen (file, "rb");
2251 unsigned char *buf = NULL;
2252 struct stat st;
2254 if (fp)
2256 ptrdiff_t count = SPECPDL_INDEX ();
2257 record_unwind_protect_ptr (fclose_unwind, fp);
2259 if (fstat (fileno (fp), &st) == 0
2260 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2262 /* Report an error if we read past the purported EOF.
2263 This can happen if the file grows as we read it. */
2264 ptrdiff_t buflen = st.st_size;
2265 buf = xmalloc (buflen + 1);
2266 if (fread (buf, 1, buflen + 1, fp) == buflen)
2267 *size = buflen;
2268 else
2270 xfree (buf);
2271 buf = NULL;
2275 unbind_to (count, Qnil);
2278 return buf;
2283 /***********************************************************************
2284 XBM images
2285 ***********************************************************************/
2287 static bool xbm_load (struct frame *f, struct image *img);
2288 static bool xbm_image_p (Lisp_Object object);
2289 static bool xbm_file_p (Lisp_Object);
2292 /* Indices of image specification fields in xbm_format, below. */
2294 enum xbm_keyword_index
2296 XBM_TYPE,
2297 XBM_FILE,
2298 XBM_WIDTH,
2299 XBM_HEIGHT,
2300 XBM_DATA,
2301 XBM_FOREGROUND,
2302 XBM_BACKGROUND,
2303 XBM_ASCENT,
2304 XBM_MARGIN,
2305 XBM_RELIEF,
2306 XBM_ALGORITHM,
2307 XBM_HEURISTIC_MASK,
2308 XBM_MASK,
2309 XBM_LAST
2312 /* Vector of image_keyword structures describing the format
2313 of valid XBM image specifications. */
2315 static const struct image_keyword xbm_format[XBM_LAST] =
2317 {":type", IMAGE_SYMBOL_VALUE, 1},
2318 {":file", IMAGE_STRING_VALUE, 0},
2319 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2320 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2321 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2322 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2323 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2324 {":ascent", IMAGE_ASCENT_VALUE, 0},
2325 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2326 {":relief", IMAGE_INTEGER_VALUE, 0},
2327 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2328 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2329 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2332 /* Structure describing the image type XBM. */
2334 static struct image_type xbm_type =
2336 SYMBOL_INDEX (Qxbm),
2337 xbm_image_p,
2338 xbm_load,
2339 x_clear_image,
2340 NULL,
2341 NULL
2344 /* Tokens returned from xbm_scan. */
2346 enum xbm_token
2348 XBM_TK_IDENT = 256,
2349 XBM_TK_NUMBER
2353 /* Return true if OBJECT is a valid XBM-type image specification.
2354 A valid specification is a list starting with the symbol `image'
2355 The rest of the list is a property list which must contain an
2356 entry `:type xbm'.
2358 If the specification specifies a file to load, it must contain
2359 an entry `:file FILENAME' where FILENAME is a string.
2361 If the specification is for a bitmap loaded from memory it must
2362 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2363 WIDTH and HEIGHT are integers > 0. DATA may be:
2365 1. a string large enough to hold the bitmap data, i.e. it must
2366 have a size >= (WIDTH + 7) / 8 * HEIGHT
2368 2. a bool-vector of size >= WIDTH * HEIGHT
2370 3. a vector of strings or bool-vectors, one for each line of the
2371 bitmap.
2373 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2374 may not be specified in this case because they are defined in the
2375 XBM file.
2377 Both the file and data forms may contain the additional entries
2378 `:background COLOR' and `:foreground COLOR'. If not present,
2379 foreground and background of the frame on which the image is
2380 displayed is used. */
2382 static bool
2383 xbm_image_p (Lisp_Object object)
2385 struct image_keyword kw[XBM_LAST];
2387 memcpy (kw, xbm_format, sizeof kw);
2388 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2389 return 0;
2391 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2393 if (kw[XBM_FILE].count)
2395 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2396 return 0;
2398 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2400 /* In-memory XBM file. */
2401 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2402 return 0;
2404 else
2406 Lisp_Object data;
2407 int width, height;
2409 /* Entries for `:width', `:height' and `:data' must be present. */
2410 if (!kw[XBM_WIDTH].count
2411 || !kw[XBM_HEIGHT].count
2412 || !kw[XBM_DATA].count)
2413 return 0;
2415 data = kw[XBM_DATA].value;
2416 width = XFASTINT (kw[XBM_WIDTH].value);
2417 height = XFASTINT (kw[XBM_HEIGHT].value);
2419 /* Check type of data, and width and height against contents of
2420 data. */
2421 if (VECTORP (data))
2423 EMACS_INT i;
2425 /* Number of elements of the vector must be >= height. */
2426 if (ASIZE (data) < height)
2427 return 0;
2429 /* Each string or bool-vector in data must be large enough
2430 for one line of the image. */
2431 for (i = 0; i < height; ++i)
2433 Lisp_Object elt = AREF (data, i);
2435 if (STRINGP (elt))
2437 if (SCHARS (elt)
2438 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2439 return 0;
2441 else if (BOOL_VECTOR_P (elt))
2443 if (bool_vector_size (elt) < width)
2444 return 0;
2446 else
2447 return 0;
2450 else if (STRINGP (data))
2452 if (SCHARS (data)
2453 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2454 return 0;
2456 else if (BOOL_VECTOR_P (data))
2458 if (bool_vector_size (data) / height < width)
2459 return 0;
2461 else
2462 return 0;
2465 return 1;
2469 /* Scan a bitmap file. FP is the stream to read from. Value is
2470 either an enumerator from enum xbm_token, or a character for a
2471 single-character token, or 0 at end of file. If scanning an
2472 identifier, store the lexeme of the identifier in SVAL. If
2473 scanning a number, store its value in *IVAL. */
2475 static int
2476 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2478 unsigned int c;
2480 loop:
2482 /* Skip white space. */
2483 while (*s < end && (c = *(*s)++, c_isspace (c)))
2486 if (*s >= end)
2487 c = 0;
2488 else if (c_isdigit (c))
2490 int value = 0, digit;
2492 if (c == '0' && *s < end)
2494 c = *(*s)++;
2495 if (c == 'x' || c == 'X')
2497 while (*s < end)
2499 c = *(*s)++;
2500 if (c_isdigit (c))
2501 digit = c - '0';
2502 else if (c >= 'a' && c <= 'f')
2503 digit = c - 'a' + 10;
2504 else if (c >= 'A' && c <= 'F')
2505 digit = c - 'A' + 10;
2506 else
2507 break;
2508 value = 16 * value + digit;
2511 else if (c_isdigit (c))
2513 value = c - '0';
2514 while (*s < end
2515 && (c = *(*s)++, c_isdigit (c)))
2516 value = 8 * value + c - '0';
2519 else
2521 value = c - '0';
2522 while (*s < end
2523 && (c = *(*s)++, c_isdigit (c)))
2524 value = 10 * value + c - '0';
2527 if (*s < end)
2528 *s = *s - 1;
2529 *ival = value;
2530 c = XBM_TK_NUMBER;
2532 else if (c_isalpha (c) || c == '_')
2534 *sval++ = c;
2535 while (*s < end
2536 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2537 *sval++ = c;
2538 *sval = 0;
2539 if (*s < end)
2540 *s = *s - 1;
2541 c = XBM_TK_IDENT;
2543 else if (c == '/' && **s == '*')
2545 /* C-style comment. */
2546 ++*s;
2547 while (**s && (**s != '*' || *(*s + 1) != '/'))
2548 ++*s;
2549 if (**s)
2551 *s += 2;
2552 goto loop;
2556 return c;
2559 #ifdef HAVE_NTGUI
2561 /* Create a Windows bitmap from X bitmap data. */
2562 static HBITMAP
2563 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2565 static unsigned char swap_nibble[16]
2566 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2567 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2568 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2569 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2570 int i, j, w1, w2;
2571 unsigned char *bits, *p;
2572 HBITMAP bmp;
2574 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2575 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2576 bits = alloca (height * w2);
2577 memset (bits, 0, height * w2);
2578 for (i = 0; i < height; i++)
2580 p = bits + i*w2;
2581 for (j = 0; j < w1; j++)
2583 /* Bitswap XBM bytes to match how Windows does things. */
2584 unsigned char c = *data++;
2585 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2586 | (swap_nibble[(c>>4) & 0xf]));
2589 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2591 return bmp;
2594 static void
2595 convert_mono_to_color_image (struct frame *f, struct image *img,
2596 COLORREF foreground, COLORREF background)
2598 HDC hdc, old_img_dc, new_img_dc;
2599 HGDIOBJ old_prev, new_prev;
2600 HBITMAP new_pixmap;
2602 hdc = get_frame_dc (f);
2603 old_img_dc = CreateCompatibleDC (hdc);
2604 new_img_dc = CreateCompatibleDC (hdc);
2605 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2606 release_frame_dc (f, hdc);
2607 old_prev = SelectObject (old_img_dc, img->pixmap);
2608 new_prev = SelectObject (new_img_dc, new_pixmap);
2609 /* Windows convention for mono bitmaps is black = background,
2610 white = foreground. */
2611 SetTextColor (new_img_dc, background);
2612 SetBkColor (new_img_dc, foreground);
2614 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2615 0, 0, SRCCOPY);
2617 SelectObject (old_img_dc, old_prev);
2618 SelectObject (new_img_dc, new_prev);
2619 DeleteDC (old_img_dc);
2620 DeleteDC (new_img_dc);
2621 DeleteObject (img->pixmap);
2622 if (new_pixmap == 0)
2623 fprintf (stderr, "Failed to convert image to color.\n");
2624 else
2625 img->pixmap = new_pixmap;
2628 #define XBM_BIT_SHUFFLE(b) (~(b))
2630 #else
2632 #define XBM_BIT_SHUFFLE(b) (b)
2634 #endif /* HAVE_NTGUI */
2637 static void
2638 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2639 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2640 bool non_default_colors)
2642 #ifdef HAVE_NTGUI
2643 img->pixmap
2644 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2646 /* If colors were specified, transfer the bitmap to a color one. */
2647 if (non_default_colors)
2648 convert_mono_to_color_image (f, img, fg, bg);
2650 #elif defined (HAVE_NS)
2651 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2653 #else
2654 img->pixmap =
2655 (x_check_image_size (0, img->width, img->height)
2656 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2657 FRAME_X_WINDOW (f),
2658 data,
2659 img->width, img->height,
2660 fg, bg,
2661 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2662 : NO_PIXMAP);
2663 #endif /* !HAVE_NTGUI && !HAVE_NS */
2668 /* Replacement for XReadBitmapFileData which isn't available under old
2669 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2670 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2671 the image. Return in *DATA the bitmap data allocated with xmalloc.
2672 Value is true if successful. DATA null means just test if
2673 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2674 inhibit the call to image_error when the image size is invalid (the
2675 bitmap remains unread). */
2677 static bool
2678 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2679 int *width, int *height, char **data,
2680 bool inhibit_image_error)
2682 unsigned char *s = contents;
2683 char buffer[BUFSIZ];
2684 bool padding_p = 0;
2685 bool v10 = 0;
2686 int bytes_per_line, i, nbytes;
2687 char *p;
2688 int value;
2689 int LA1;
2691 #define match() \
2692 LA1 = xbm_scan (&s, end, buffer, &value)
2694 #define expect(TOKEN) \
2695 do \
2697 if (LA1 != (TOKEN)) \
2698 goto failure; \
2699 match (); \
2701 while (0)
2703 #define expect_ident(IDENT) \
2704 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2705 match (); \
2706 else \
2707 goto failure
2709 *width = *height = -1;
2710 if (data)
2711 *data = NULL;
2712 LA1 = xbm_scan (&s, end, buffer, &value);
2714 /* Parse defines for width, height and hot-spots. */
2715 while (LA1 == '#')
2717 match ();
2718 expect_ident ("define");
2719 expect (XBM_TK_IDENT);
2721 if (LA1 == XBM_TK_NUMBER)
2723 char *q = strrchr (buffer, '_');
2724 q = q ? q + 1 : buffer;
2725 if (strcmp (q, "width") == 0)
2726 *width = value;
2727 else if (strcmp (q, "height") == 0)
2728 *height = value;
2730 expect (XBM_TK_NUMBER);
2733 if (!check_image_size (f, *width, *height))
2735 if (!inhibit_image_error)
2736 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2737 goto failure;
2739 else if (data == NULL)
2740 goto success;
2742 /* Parse bits. Must start with `static'. */
2743 expect_ident ("static");
2744 if (LA1 == XBM_TK_IDENT)
2746 if (strcmp (buffer, "unsigned") == 0)
2748 match ();
2749 expect_ident ("char");
2751 else if (strcmp (buffer, "short") == 0)
2753 match ();
2754 v10 = 1;
2755 if (*width % 16 && *width % 16 < 9)
2756 padding_p = 1;
2758 else if (strcmp (buffer, "char") == 0)
2759 match ();
2760 else
2761 goto failure;
2763 else
2764 goto failure;
2766 expect (XBM_TK_IDENT);
2767 expect ('[');
2768 expect (']');
2769 expect ('=');
2770 expect ('{');
2772 if (! x_check_image_size (0, *width, *height))
2774 if (!inhibit_image_error)
2775 image_error ("Image too large (%dx%d)",
2776 make_number (*width), make_number (*height));
2777 goto failure;
2779 bytes_per_line = (*width + 7) / 8 + padding_p;
2780 nbytes = bytes_per_line * *height;
2781 p = *data = xmalloc (nbytes);
2783 if (v10)
2785 for (i = 0; i < nbytes; i += 2)
2787 int val = value;
2788 expect (XBM_TK_NUMBER);
2790 *p++ = XBM_BIT_SHUFFLE (val);
2791 if (!padding_p || ((i + 2) % bytes_per_line))
2792 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2794 if (LA1 == ',' || LA1 == '}')
2795 match ();
2796 else
2797 goto failure;
2800 else
2802 for (i = 0; i < nbytes; ++i)
2804 int val = value;
2805 expect (XBM_TK_NUMBER);
2807 *p++ = XBM_BIT_SHUFFLE (val);
2809 if (LA1 == ',' || LA1 == '}')
2810 match ();
2811 else
2812 goto failure;
2816 success:
2817 return 1;
2819 failure:
2821 if (data && *data)
2823 xfree (*data);
2824 *data = NULL;
2826 return 0;
2828 #undef match
2829 #undef expect
2830 #undef expect_ident
2834 /* Load XBM image IMG which will be displayed on frame F from buffer
2835 CONTENTS. END is the end of the buffer. Value is true if
2836 successful. */
2838 static bool
2839 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2840 unsigned char *end)
2842 bool rc;
2843 char *data;
2844 bool success_p = 0;
2846 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2847 &data, 0);
2848 if (rc)
2850 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2851 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2852 bool non_default_colors = 0;
2853 Lisp_Object value;
2855 eassert (img->width > 0 && img->height > 0);
2857 /* Get foreground and background colors, maybe allocate colors. */
2858 value = image_spec_value (img->spec, QCforeground, NULL);
2859 if (!NILP (value))
2861 foreground = x_alloc_image_color (f, img, value, foreground);
2862 non_default_colors = 1;
2864 value = image_spec_value (img->spec, QCbackground, NULL);
2865 if (!NILP (value))
2867 background = x_alloc_image_color (f, img, value, background);
2868 img->background = background;
2869 img->background_valid = 1;
2870 non_default_colors = 1;
2873 Create_Pixmap_From_Bitmap_Data (f, img, data,
2874 foreground, background,
2875 non_default_colors);
2876 xfree (data);
2878 if (img->pixmap == NO_PIXMAP)
2880 x_clear_image (f, img);
2881 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2883 else
2884 success_p = 1;
2886 else
2887 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2889 return success_p;
2893 /* Value is true if DATA looks like an in-memory XBM file. */
2895 static bool
2896 xbm_file_p (Lisp_Object data)
2898 int w, h;
2899 return (STRINGP (data)
2900 && xbm_read_bitmap_data (NULL, SDATA (data),
2901 (SDATA (data) + SBYTES (data)),
2902 &w, &h, NULL, 1));
2906 /* Fill image IMG which is used on frame F with pixmap data. Value is
2907 true if successful. */
2909 static bool
2910 xbm_load (struct frame *f, struct image *img)
2912 bool success_p = 0;
2913 Lisp_Object file_name;
2915 eassert (xbm_image_p (img->spec));
2917 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2918 file_name = image_spec_value (img->spec, QCfile, NULL);
2919 if (STRINGP (file_name))
2921 Lisp_Object file;
2922 unsigned char *contents;
2923 ptrdiff_t size;
2925 file = x_find_image_file (file_name);
2926 if (!STRINGP (file))
2928 image_error ("Cannot find image file `%s'", file_name, Qnil);
2929 return 0;
2932 contents = slurp_file (SSDATA (file), &size);
2933 if (contents == NULL)
2935 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2936 return 0;
2939 success_p = xbm_load_image (f, img, contents, contents + size);
2940 xfree (contents);
2942 else
2944 struct image_keyword fmt[XBM_LAST];
2945 Lisp_Object data;
2946 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2947 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2948 bool non_default_colors = 0;
2949 char *bits;
2950 bool parsed_p;
2951 bool in_memory_file_p = 0;
2953 /* See if data looks like an in-memory XBM file. */
2954 data = image_spec_value (img->spec, QCdata, NULL);
2955 in_memory_file_p = xbm_file_p (data);
2957 /* Parse the image specification. */
2958 memcpy (fmt, xbm_format, sizeof fmt);
2959 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2960 eassert (parsed_p);
2962 /* Get specified width, and height. */
2963 if (!in_memory_file_p)
2965 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2966 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2967 eassert (img->width > 0 && img->height > 0);
2968 if (!check_image_size (f, img->width, img->height))
2970 image_error ("Invalid image size (see `max-image-size')",
2971 Qnil, Qnil);
2972 return 0;
2976 /* Get foreground and background colors, maybe allocate colors. */
2977 if (fmt[XBM_FOREGROUND].count
2978 && STRINGP (fmt[XBM_FOREGROUND].value))
2980 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2981 foreground);
2982 non_default_colors = 1;
2985 if (fmt[XBM_BACKGROUND].count
2986 && STRINGP (fmt[XBM_BACKGROUND].value))
2988 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2989 background);
2990 non_default_colors = 1;
2993 if (in_memory_file_p)
2994 success_p = xbm_load_image (f, img, SDATA (data),
2995 (SDATA (data)
2996 + SBYTES (data)));
2997 else
2999 USE_SAFE_ALLOCA;
3001 if (VECTORP (data))
3003 int i;
3004 char *p;
3005 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3007 SAFE_NALLOCA (bits, nbytes, img->height);
3008 p = bits;
3009 for (i = 0; i < img->height; ++i, p += nbytes)
3011 Lisp_Object line = AREF (data, i);
3012 if (STRINGP (line))
3013 memcpy (p, SDATA (line), nbytes);
3014 else
3015 memcpy (p, bool_vector_data (line), nbytes);
3018 else if (STRINGP (data))
3019 bits = SSDATA (data);
3020 else
3021 bits = (char *) bool_vector_data (data);
3023 #ifdef HAVE_NTGUI
3025 char *invertedBits;
3026 int nbytes, i;
3027 /* Windows mono bitmaps are reversed compared with X. */
3028 invertedBits = bits;
3029 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3030 SAFE_NALLOCA (bits, nbytes, img->height);
3031 for (i = 0; i < nbytes; i++)
3032 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3034 #endif
3035 /* Create the pixmap. */
3037 if (x_check_image_size (0, img->width, img->height))
3038 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3039 foreground, background,
3040 non_default_colors);
3041 else
3042 img->pixmap = NO_PIXMAP;
3044 if (img->pixmap)
3045 success_p = 1;
3046 else
3048 image_error ("Unable to create pixmap for XBM image `%s'",
3049 img->spec, Qnil);
3050 x_clear_image (f, img);
3053 SAFE_FREE ();
3057 return success_p;
3062 /***********************************************************************
3063 XPM images
3064 ***********************************************************************/
3066 #if defined (HAVE_XPM) || defined (HAVE_NS)
3068 static bool xpm_image_p (Lisp_Object object);
3069 static bool xpm_load (struct frame *f, struct image *img);
3071 #endif /* HAVE_XPM || HAVE_NS */
3073 #ifdef HAVE_XPM
3074 #ifdef HAVE_NTGUI
3075 /* Indicate to xpm.h that we don't have Xlib. */
3076 #define FOR_MSW
3077 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3078 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3079 #define XColor xpm_XColor
3080 #define XImage xpm_XImage
3081 #define Display xpm_Display
3082 #define PIXEL_ALREADY_TYPEDEFED
3083 #include "X11/xpm.h"
3084 #undef FOR_MSW
3085 #undef XColor
3086 #undef XImage
3087 #undef Display
3088 #undef PIXEL_ALREADY_TYPEDEFED
3089 #else
3090 #include "X11/xpm.h"
3091 #endif /* HAVE_NTGUI */
3092 #endif /* HAVE_XPM */
3094 #if defined (HAVE_XPM) || defined (HAVE_NS)
3096 /* Indices of image specification fields in xpm_format, below. */
3098 enum xpm_keyword_index
3100 XPM_TYPE,
3101 XPM_FILE,
3102 XPM_DATA,
3103 XPM_ASCENT,
3104 XPM_MARGIN,
3105 XPM_RELIEF,
3106 XPM_ALGORITHM,
3107 XPM_HEURISTIC_MASK,
3108 XPM_MASK,
3109 XPM_COLOR_SYMBOLS,
3110 XPM_BACKGROUND,
3111 XPM_LAST
3114 /* Vector of image_keyword structures describing the format
3115 of valid XPM image specifications. */
3117 static const struct image_keyword xpm_format[XPM_LAST] =
3119 {":type", IMAGE_SYMBOL_VALUE, 1},
3120 {":file", IMAGE_STRING_VALUE, 0},
3121 {":data", IMAGE_STRING_VALUE, 0},
3122 {":ascent", IMAGE_ASCENT_VALUE, 0},
3123 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3124 {":relief", IMAGE_INTEGER_VALUE, 0},
3125 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3126 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3127 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3128 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3129 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3132 #if defined HAVE_NTGUI && defined WINDOWSNT
3133 static bool init_xpm_functions (void);
3134 #else
3135 #define init_xpm_functions NULL
3136 #endif
3138 /* Structure describing the image type XPM. */
3140 static struct image_type xpm_type =
3142 SYMBOL_INDEX (Qxpm),
3143 xpm_image_p,
3144 xpm_load,
3145 x_clear_image,
3146 init_xpm_functions,
3147 NULL
3150 #ifdef HAVE_X_WINDOWS
3152 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3153 functions for allocating image colors. Our own functions handle
3154 color allocation failures more gracefully than the ones on the XPM
3155 lib. */
3157 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3158 #define ALLOC_XPM_COLORS
3159 #endif
3160 #endif /* HAVE_X_WINDOWS */
3162 #ifdef ALLOC_XPM_COLORS
3164 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3165 XColor *, int);
3167 /* An entry in a hash table used to cache color definitions of named
3168 colors. This cache is necessary to speed up XPM image loading in
3169 case we do color allocations ourselves. Without it, we would need
3170 a call to XParseColor per pixel in the image. */
3172 struct xpm_cached_color
3174 /* Next in collision chain. */
3175 struct xpm_cached_color *next;
3177 /* Color definition (RGB and pixel color). */
3178 XColor color;
3180 /* Color name. */
3181 char name[FLEXIBLE_ARRAY_MEMBER];
3184 /* The hash table used for the color cache, and its bucket vector
3185 size. */
3187 #define XPM_COLOR_CACHE_BUCKETS 1001
3188 static struct xpm_cached_color **xpm_color_cache;
3190 /* Initialize the color cache. */
3192 static void
3193 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3195 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3196 xpm_color_cache = xzalloc (nbytes);
3197 init_color_table ();
3199 if (attrs->valuemask & XpmColorSymbols)
3201 int i;
3202 XColor color;
3204 for (i = 0; i < attrs->numsymbols; ++i)
3205 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3206 attrs->colorsymbols[i].value, &color))
3208 color.pixel = lookup_rgb_color (f, color.red, color.green,
3209 color.blue);
3210 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3215 /* Free the color cache. */
3217 static void
3218 xpm_free_color_cache (void)
3220 struct xpm_cached_color *p, *next;
3221 int i;
3223 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3224 for (p = xpm_color_cache[i]; p; p = next)
3226 next = p->next;
3227 xfree (p);
3230 xfree (xpm_color_cache);
3231 xpm_color_cache = NULL;
3232 free_color_table ();
3235 /* Return the bucket index for color named COLOR_NAME in the color
3236 cache. */
3238 static int
3239 xpm_color_bucket (char *color_name)
3241 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3242 return hash % XPM_COLOR_CACHE_BUCKETS;
3246 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3247 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3248 entry added. */
3250 static struct xpm_cached_color *
3251 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3253 size_t nbytes;
3254 struct xpm_cached_color *p;
3256 if (bucket < 0)
3257 bucket = xpm_color_bucket (color_name);
3259 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3260 p = xmalloc (nbytes);
3261 strcpy (p->name, color_name);
3262 p->color = *color;
3263 p->next = xpm_color_cache[bucket];
3264 xpm_color_cache[bucket] = p;
3265 return p;
3268 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3269 return the cached definition in *COLOR. Otherwise, make a new
3270 entry in the cache and allocate the color. Value is false if color
3271 allocation failed. */
3273 static bool
3274 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3276 struct xpm_cached_color *p;
3277 int h = xpm_color_bucket (color_name);
3279 for (p = xpm_color_cache[h]; p; p = p->next)
3280 if (strcmp (p->name, color_name) == 0)
3281 break;
3283 if (p != NULL)
3284 *color = p->color;
3285 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3286 color_name, color))
3288 color->pixel = lookup_rgb_color (f, color->red, color->green,
3289 color->blue);
3290 p = xpm_cache_color (f, color_name, color, h);
3292 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3293 with transparency, and it's useful. */
3294 else if (strcmp ("opaque", color_name) == 0)
3296 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3297 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3298 p = xpm_cache_color (f, color_name, color, h);
3301 return p != NULL;
3305 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3306 CLOSURE is a pointer to the frame on which we allocate the
3307 color. Return in *COLOR the allocated color. Value is non-zero
3308 if successful. */
3310 static int
3311 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3312 void *closure)
3314 return xpm_lookup_color (closure, color_name, color);
3318 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3319 is a pointer to the frame on which we allocate the color. Value is
3320 non-zero if successful. */
3322 static int
3323 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3325 return 1;
3328 #endif /* ALLOC_XPM_COLORS */
3331 #ifdef WINDOWSNT
3333 /* XPM library details. */
3335 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3336 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3337 (Display *, char *, xpm_XImage **,
3338 xpm_XImage **, XpmAttributes *));
3339 DEF_DLL_FN (int, XpmReadFileToImage,
3340 (Display *, char *, xpm_XImage **,
3341 xpm_XImage **, XpmAttributes *));
3342 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3344 static bool
3345 init_xpm_functions (void)
3347 HMODULE library;
3349 if (!(library = w32_delayed_load (Qxpm)))
3350 return 0;
3352 LOAD_DLL_FN (library, XpmFreeAttributes);
3353 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3354 LOAD_DLL_FN (library, XpmReadFileToImage);
3355 LOAD_DLL_FN (library, XImageFree);
3356 return 1;
3359 # undef XImageFree
3360 # undef XpmCreateImageFromBuffer
3361 # undef XpmFreeAttributes
3362 # undef XpmReadFileToImage
3364 # define XImageFree fn_XImageFree
3365 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3366 # define XpmFreeAttributes fn_XpmFreeAttributes
3367 # define XpmReadFileToImage fn_XpmReadFileToImage
3369 #endif /* WINDOWSNT */
3371 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3372 for XPM images. Such a list must consist of conses whose car and
3373 cdr are strings. */
3375 static bool
3376 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3378 while (CONSP (color_symbols))
3380 Lisp_Object sym = XCAR (color_symbols);
3381 if (!CONSP (sym)
3382 || !STRINGP (XCAR (sym))
3383 || !STRINGP (XCDR (sym)))
3384 break;
3385 color_symbols = XCDR (color_symbols);
3388 return NILP (color_symbols);
3392 /* Value is true if OBJECT is a valid XPM image specification. */
3394 static bool
3395 xpm_image_p (Lisp_Object object)
3397 struct image_keyword fmt[XPM_LAST];
3398 memcpy (fmt, xpm_format, sizeof fmt);
3399 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3400 /* Either `:file' or `:data' must be present. */
3401 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3402 /* Either no `:color-symbols' or it's a list of conses
3403 whose car and cdr are strings. */
3404 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3405 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3408 #endif /* HAVE_XPM || HAVE_NS */
3410 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3411 ptrdiff_t
3412 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3414 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3415 ptrdiff_t id;
3416 int rc;
3417 XpmAttributes attrs;
3418 Pixmap bitmap, mask;
3420 memset (&attrs, 0, sizeof attrs);
3422 attrs.visual = FRAME_X_VISUAL (f);
3423 attrs.colormap = FRAME_X_COLORMAP (f);
3424 attrs.valuemask |= XpmVisual;
3425 attrs.valuemask |= XpmColormap;
3427 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3428 (char **) bits, &bitmap, &mask, &attrs);
3429 if (rc != XpmSuccess)
3431 XpmFreeAttributes (&attrs);
3432 return -1;
3435 id = x_allocate_bitmap_record (f);
3436 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3437 dpyinfo->bitmaps[id - 1].have_mask = true;
3438 dpyinfo->bitmaps[id - 1].mask = mask;
3439 dpyinfo->bitmaps[id - 1].file = NULL;
3440 dpyinfo->bitmaps[id - 1].height = attrs.height;
3441 dpyinfo->bitmaps[id - 1].width = attrs.width;
3442 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3443 dpyinfo->bitmaps[id - 1].refcount = 1;
3445 XpmFreeAttributes (&attrs);
3446 return id;
3448 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3450 /* Load image IMG which will be displayed on frame F. Value is
3451 true if successful. */
3453 #ifdef HAVE_XPM
3455 static bool
3456 xpm_load (struct frame *f, struct image *img)
3458 int rc;
3459 XpmAttributes attrs;
3460 Lisp_Object specified_file, color_symbols;
3461 USE_SAFE_ALLOCA;
3463 #ifdef HAVE_NTGUI
3464 HDC hdc;
3465 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3466 #endif /* HAVE_NTGUI */
3468 /* Configure the XPM lib. Use the visual of frame F. Allocate
3469 close colors. Return colors allocated. */
3470 memset (&attrs, 0, sizeof attrs);
3472 #ifndef HAVE_NTGUI
3473 attrs.visual = FRAME_X_VISUAL (f);
3474 attrs.colormap = FRAME_X_COLORMAP (f);
3475 attrs.valuemask |= XpmVisual;
3476 attrs.valuemask |= XpmColormap;
3477 #endif /* HAVE_NTGUI */
3479 #ifdef ALLOC_XPM_COLORS
3480 /* Allocate colors with our own functions which handle
3481 failing color allocation more gracefully. */
3482 attrs.color_closure = f;
3483 attrs.alloc_color = xpm_alloc_color;
3484 attrs.free_colors = xpm_free_colors;
3485 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3486 #else /* not ALLOC_XPM_COLORS */
3487 /* Let the XPM lib allocate colors. */
3488 attrs.valuemask |= XpmReturnAllocPixels;
3489 #ifdef XpmAllocCloseColors
3490 attrs.alloc_close_colors = 1;
3491 attrs.valuemask |= XpmAllocCloseColors;
3492 #else /* not XpmAllocCloseColors */
3493 attrs.closeness = 600;
3494 attrs.valuemask |= XpmCloseness;
3495 #endif /* not XpmAllocCloseColors */
3496 #endif /* ALLOC_XPM_COLORS */
3498 /* If image specification contains symbolic color definitions, add
3499 these to `attrs'. */
3500 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3501 if (CONSP (color_symbols))
3503 Lisp_Object tail;
3504 XpmColorSymbol *xpm_syms;
3505 ptrdiff_t i, size;
3507 attrs.valuemask |= XpmColorSymbols;
3509 /* Count number of symbols. */
3510 attrs.numsymbols = 0;
3511 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3512 ++attrs.numsymbols;
3514 /* Allocate an XpmColorSymbol array. */
3515 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3516 size = attrs.numsymbols * sizeof *xpm_syms;
3517 memset (xpm_syms, 0, size);
3518 attrs.colorsymbols = xpm_syms;
3520 /* Fill the color symbol array. */
3521 for (tail = color_symbols, i = 0;
3522 CONSP (tail);
3523 ++i, tail = XCDR (tail))
3525 Lisp_Object name;
3526 Lisp_Object color;
3527 char *empty_string = (char *) "";
3529 if (!CONSP (XCAR (tail)))
3531 xpm_syms[i].name = empty_string;
3532 xpm_syms[i].value = empty_string;
3533 continue;
3535 name = XCAR (XCAR (tail));
3536 color = XCDR (XCAR (tail));
3537 if (STRINGP (name))
3538 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3539 else
3540 xpm_syms[i].name = empty_string;
3541 if (STRINGP (color))
3542 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3543 else
3544 xpm_syms[i].value = empty_string;
3548 /* Create a pixmap for the image, either from a file, or from a
3549 string buffer containing data in the same format as an XPM file. */
3550 #ifdef ALLOC_XPM_COLORS
3551 xpm_init_color_cache (f, &attrs);
3552 #endif
3554 specified_file = image_spec_value (img->spec, QCfile, NULL);
3556 #ifdef HAVE_NTGUI
3558 HDC frame_dc = get_frame_dc (f);
3559 hdc = CreateCompatibleDC (frame_dc);
3560 release_frame_dc (f, frame_dc);
3562 #endif /* HAVE_NTGUI */
3564 if (STRINGP (specified_file))
3566 Lisp_Object file = x_find_image_file (specified_file);
3567 if (!STRINGP (file))
3569 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3570 #ifdef ALLOC_XPM_COLORS
3571 xpm_free_color_cache ();
3572 #endif
3573 SAFE_FREE ();
3574 return 0;
3577 #ifdef HAVE_NTGUI
3578 #ifdef WINDOWSNT
3579 /* FILE is encoded in UTF-8, but image libraries on Windows
3580 support neither UTF-8 nor UTF-16 encoded file names. So we
3581 need to re-encode it in ANSI. */
3582 file = ansi_encode_filename (file);
3583 #endif
3584 /* XpmReadFileToPixmap is not available in the Windows port of
3585 libxpm. But XpmReadFileToImage almost does what we want. */
3586 rc = XpmReadFileToImage (&hdc, SDATA (file),
3587 &xpm_image, &xpm_mask,
3588 &attrs);
3589 #else
3590 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3591 &img->ximg, &img->mask_img,
3592 &attrs);
3593 #endif /* HAVE_NTGUI */
3595 else
3597 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3598 if (!STRINGP (buffer))
3600 image_error ("Invalid image data `%s'", buffer, Qnil);
3601 #ifdef ALLOC_XPM_COLORS
3602 xpm_free_color_cache ();
3603 #endif
3604 SAFE_FREE ();
3605 return 0;
3607 #ifdef HAVE_NTGUI
3608 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3609 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3610 rc = XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3611 &xpm_image, &xpm_mask,
3612 &attrs);
3613 #else
3614 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3615 &img->ximg, &img->mask_img,
3616 &attrs);
3617 #endif /* HAVE_NTGUI */
3620 #ifdef HAVE_X_WINDOWS
3621 if (rc == XpmSuccess)
3623 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3624 img->ximg->width, img->ximg->height,
3625 img->ximg->depth);
3626 if (img->pixmap == NO_PIXMAP)
3628 x_clear_image (f, img);
3629 rc = XpmNoMemory;
3631 else if (img->mask_img)
3633 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3634 img->mask_img->width,
3635 img->mask_img->height,
3636 img->mask_img->depth);
3637 if (img->mask == NO_PIXMAP)
3639 x_clear_image (f, img);
3640 rc = XpmNoMemory;
3644 #endif
3646 if (rc == XpmSuccess)
3648 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3649 img->colors = colors_in_color_table (&img->ncolors);
3650 #else /* not ALLOC_XPM_COLORS */
3651 int i;
3653 #ifdef HAVE_NTGUI
3654 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3655 plus some duplicate attributes. */
3656 if (xpm_image && xpm_image->bitmap)
3658 img->pixmap = xpm_image->bitmap;
3659 /* XImageFree in libXpm frees XImage struct without destroying
3660 the bitmap, which is what we want. */
3661 XImageFree (xpm_image);
3663 if (xpm_mask && xpm_mask->bitmap)
3665 /* The mask appears to be inverted compared with what we expect.
3666 TODO: invert our expectations. See other places where we
3667 have to invert bits because our idea of masks is backwards. */
3668 HGDIOBJ old_obj;
3669 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3671 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3672 SelectObject (hdc, old_obj);
3674 img->mask = xpm_mask->bitmap;
3675 XImageFree (xpm_mask);
3676 DeleteDC (hdc);
3679 DeleteDC (hdc);
3680 #endif /* HAVE_NTGUI */
3682 /* Remember allocated colors. */
3683 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3684 img->ncolors = attrs.nalloc_pixels;
3685 for (i = 0; i < attrs.nalloc_pixels; ++i)
3687 img->colors[i] = attrs.alloc_pixels[i];
3688 #ifdef DEBUG_X_COLORS
3689 register_color (img->colors[i]);
3690 #endif
3692 #endif /* not ALLOC_XPM_COLORS */
3694 img->width = attrs.width;
3695 img->height = attrs.height;
3696 eassert (img->width > 0 && img->height > 0);
3698 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3699 XpmFreeAttributes (&attrs);
3701 #ifdef HAVE_X_WINDOWS
3702 /* Maybe fill in the background field while we have ximg handy. */
3703 IMAGE_BACKGROUND (img, f, img->ximg);
3704 if (img->mask_img)
3705 /* Fill in the background_transparent field while we have the
3706 mask handy. */
3707 image_background_transparent (img, f, img->mask_img);
3708 #endif
3710 else
3712 #ifdef HAVE_NTGUI
3713 DeleteDC (hdc);
3714 #endif /* HAVE_NTGUI */
3716 switch (rc)
3718 case XpmOpenFailed:
3719 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3720 break;
3722 case XpmFileInvalid:
3723 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3724 break;
3726 case XpmNoMemory:
3727 image_error ("Out of memory (%s)", img->spec, Qnil);
3728 break;
3730 case XpmColorFailed:
3731 image_error ("Color allocation error (%s)", img->spec, Qnil);
3732 break;
3734 default:
3735 image_error ("Unknown error (%s)", img->spec, Qnil);
3736 break;
3740 #ifdef ALLOC_XPM_COLORS
3741 xpm_free_color_cache ();
3742 #endif
3743 SAFE_FREE ();
3744 return rc == XpmSuccess;
3747 #endif /* HAVE_XPM */
3749 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3751 /* XPM support functions for NS where libxpm is not available.
3752 Only XPM version 3 (without any extensions) is supported. */
3754 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3755 int, Lisp_Object);
3756 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3757 const unsigned char *, int);
3758 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3759 int, Lisp_Object);
3760 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3761 const unsigned char *, int);
3763 /* Tokens returned from xpm_scan. */
3765 enum xpm_token
3767 XPM_TK_IDENT = 256,
3768 XPM_TK_STRING,
3769 XPM_TK_EOF
3772 /* Scan an XPM data and return a character (< 256) or a token defined
3773 by enum xpm_token above. *S and END are the start (inclusive) and
3774 the end (exclusive) addresses of the data, respectively. Advance
3775 *S while scanning. If token is either XPM_TK_IDENT or
3776 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3777 length of the corresponding token, respectively. */
3779 static int
3780 xpm_scan (const unsigned char **s,
3781 const unsigned char *end,
3782 const unsigned char **beg,
3783 ptrdiff_t *len)
3785 int c;
3787 while (*s < end)
3789 /* Skip white-space. */
3790 while (*s < end && (c = *(*s)++, c_isspace (c)))
3793 /* gnus-pointer.xpm uses '-' in its identifier.
3794 sb-dir-plus.xpm uses '+' in its identifier. */
3795 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3797 *beg = *s - 1;
3798 while (*s < end
3799 && (c = **s, c_isalnum (c)
3800 || c == '_' || c == '-' || c == '+'))
3801 ++*s;
3802 *len = *s - *beg;
3803 return XPM_TK_IDENT;
3805 else if (c == '"')
3807 *beg = *s;
3808 while (*s < end && **s != '"')
3809 ++*s;
3810 *len = *s - *beg;
3811 if (*s < end)
3812 ++*s;
3813 return XPM_TK_STRING;
3815 else if (c == '/')
3817 if (*s < end && **s == '*')
3819 /* C-style comment. */
3820 ++*s;
3823 while (*s < end && *(*s)++ != '*')
3826 while (*s < end && **s != '/');
3827 if (*s < end)
3828 ++*s;
3830 else
3831 return c;
3833 else
3834 return c;
3837 return XPM_TK_EOF;
3840 /* Functions for color table lookup in XPM data. A key is a string
3841 specifying the color of each pixel in XPM data. A value is either
3842 an integer that specifies a pixel color, Qt that specifies
3843 transparency, or Qnil for the unspecified color. If the length of
3844 the key string is one, a vector is used as a table. Otherwise, a
3845 hash table is used. */
3847 static Lisp_Object
3848 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3849 const unsigned char *,
3850 int,
3851 Lisp_Object),
3852 Lisp_Object (**get_func) (Lisp_Object,
3853 const unsigned char *,
3854 int))
3856 *put_func = xpm_put_color_table_v;
3857 *get_func = xpm_get_color_table_v;
3858 return Fmake_vector (make_number (256), Qnil);
3861 static void
3862 xpm_put_color_table_v (Lisp_Object color_table,
3863 const unsigned char *chars_start,
3864 int chars_len,
3865 Lisp_Object color)
3867 ASET (color_table, *chars_start, color);
3870 static Lisp_Object
3871 xpm_get_color_table_v (Lisp_Object color_table,
3872 const unsigned char *chars_start,
3873 int chars_len)
3875 return AREF (color_table, *chars_start);
3878 static Lisp_Object
3879 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3880 const unsigned char *,
3881 int,
3882 Lisp_Object),
3883 Lisp_Object (**get_func) (Lisp_Object,
3884 const unsigned char *,
3885 int))
3887 *put_func = xpm_put_color_table_h;
3888 *get_func = xpm_get_color_table_h;
3889 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
3890 make_float (DEFAULT_REHASH_SIZE),
3891 make_float (DEFAULT_REHASH_THRESHOLD),
3892 Qnil);
3895 static void
3896 xpm_put_color_table_h (Lisp_Object color_table,
3897 const unsigned char *chars_start,
3898 int chars_len,
3899 Lisp_Object color)
3901 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3902 EMACS_UINT hash_code;
3903 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3905 hash_lookup (table, chars, &hash_code);
3906 hash_put (table, chars, color, hash_code);
3909 static Lisp_Object
3910 xpm_get_color_table_h (Lisp_Object color_table,
3911 const unsigned char *chars_start,
3912 int chars_len)
3914 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3915 ptrdiff_t i =
3916 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
3918 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3921 enum xpm_color_key {
3922 XPM_COLOR_KEY_S,
3923 XPM_COLOR_KEY_M,
3924 XPM_COLOR_KEY_G4,
3925 XPM_COLOR_KEY_G,
3926 XPM_COLOR_KEY_C
3929 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3931 static int
3932 xpm_str_to_color_key (const char *s)
3934 int i;
3936 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
3937 if (strcmp (xpm_color_key_strings[i], s) == 0)
3938 return i;
3939 return -1;
3942 static bool
3943 xpm_load_image (struct frame *f,
3944 struct image *img,
3945 const unsigned char *contents,
3946 const unsigned char *end)
3948 const unsigned char *s = contents, *beg, *str;
3949 unsigned char buffer[BUFSIZ];
3950 int width, height, x, y;
3951 int num_colors, chars_per_pixel;
3952 ptrdiff_t len;
3953 int LA1;
3954 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3955 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3956 Lisp_Object frame, color_symbols, color_table;
3957 int best_key;
3958 bool have_mask = false;
3959 XImagePtr ximg = NULL, mask_img = NULL;
3961 #define match() \
3962 LA1 = xpm_scan (&s, end, &beg, &len)
3964 #define expect(TOKEN) \
3965 do \
3967 if (LA1 != (TOKEN)) \
3968 goto failure; \
3969 match (); \
3971 while (0)
3973 #define expect_ident(IDENT) \
3974 if (LA1 == XPM_TK_IDENT \
3975 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3976 match (); \
3977 else \
3978 goto failure
3980 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3981 goto failure;
3982 s += 9;
3983 match ();
3984 expect_ident ("static");
3985 expect_ident ("char");
3986 expect ('*');
3987 expect (XPM_TK_IDENT);
3988 expect ('[');
3989 expect (']');
3990 expect ('=');
3991 expect ('{');
3992 expect (XPM_TK_STRING);
3993 if (len >= BUFSIZ)
3994 goto failure;
3995 memcpy (buffer, beg, len);
3996 buffer[len] = '\0';
3997 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3998 &num_colors, &chars_per_pixel) != 4
3999 || width <= 0 || height <= 0
4000 || num_colors <= 0 || chars_per_pixel <= 0)
4001 goto failure;
4003 if (!check_image_size (f, width, height))
4005 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
4006 goto failure;
4009 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4010 #ifndef HAVE_NS
4011 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4012 &mask_img, 1)
4013 #endif
4016 image_error ("Image too large", Qnil, Qnil);
4017 goto failure;
4020 expect (',');
4022 XSETFRAME (frame, f);
4023 if (!NILP (Fxw_display_color_p (frame)))
4024 best_key = XPM_COLOR_KEY_C;
4025 else if (!NILP (Fx_display_grayscale_p (frame)))
4026 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4027 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4028 else
4029 best_key = XPM_COLOR_KEY_M;
4031 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4032 if (chars_per_pixel == 1)
4033 color_table = xpm_make_color_table_v (&put_color_table,
4034 &get_color_table);
4035 else
4036 color_table = xpm_make_color_table_h (&put_color_table,
4037 &get_color_table);
4039 while (num_colors-- > 0)
4041 char *color, *max_color;
4042 int key, next_key, max_key = 0;
4043 Lisp_Object symbol_color = Qnil, color_val;
4044 XColor cdef;
4046 expect (XPM_TK_STRING);
4047 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4048 goto failure;
4049 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4050 buffer[len - chars_per_pixel] = '\0';
4052 str = strtok (buffer, " \t");
4053 if (str == NULL)
4054 goto failure;
4055 key = xpm_str_to_color_key (str);
4056 if (key < 0)
4057 goto failure;
4060 color = strtok (NULL, " \t");
4061 if (color == NULL)
4062 goto failure;
4064 while ((str = strtok (NULL, " \t")) != NULL)
4066 next_key = xpm_str_to_color_key (str);
4067 if (next_key >= 0)
4068 break;
4069 color[strlen (color)] = ' ';
4072 if (key == XPM_COLOR_KEY_S)
4074 if (NILP (symbol_color))
4075 symbol_color = build_string (color);
4077 else if (max_key < key && key <= best_key)
4079 max_key = key;
4080 max_color = color;
4082 key = next_key;
4084 while (str);
4086 color_val = Qnil;
4087 if (!NILP (color_symbols) && !NILP (symbol_color))
4089 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4091 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4093 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4094 color_val = Qt;
4095 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4096 &cdef, 0))
4097 color_val = make_number (cdef.pixel);
4100 if (NILP (color_val) && max_key > 0)
4102 if (xstrcasecmp (max_color, "None") == 0)
4103 color_val = Qt;
4104 else if (x_defined_color (f, max_color, &cdef, 0))
4105 color_val = make_number (cdef.pixel);
4107 if (!NILP (color_val))
4108 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4110 expect (',');
4113 for (y = 0; y < height; y++)
4115 expect (XPM_TK_STRING);
4116 str = beg;
4117 if (len < width * chars_per_pixel)
4118 goto failure;
4119 for (x = 0; x < width; x++, str += chars_per_pixel)
4121 Lisp_Object color_val =
4122 (*get_color_table) (color_table, str, chars_per_pixel);
4124 XPutPixel (ximg, x, y,
4125 (INTEGERP (color_val) ? XINT (color_val)
4126 : FRAME_FOREGROUND_PIXEL (f)));
4127 #ifndef HAVE_NS
4128 XPutPixel (mask_img, x, y,
4129 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4130 : (have_mask = true, PIX_MASK_RETAIN)));
4131 #else
4132 if (EQ (color_val, Qt))
4133 ns_set_alpha (ximg, x, y, 0);
4134 #endif
4136 if (y + 1 < height)
4137 expect (',');
4140 img->width = width;
4141 img->height = height;
4143 /* Maybe fill in the background field while we have ximg handy. */
4144 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4145 IMAGE_BACKGROUND (img, f, ximg);
4147 image_put_x_image (f, img, ximg, 0);
4148 #ifndef HAVE_NS
4149 if (have_mask)
4151 /* Fill in the background_transparent field while we have the
4152 mask handy. */
4153 image_background_transparent (img, f, mask_img);
4155 image_put_x_image (f, img, mask_img, 1);
4157 else
4159 x_destroy_x_image (mask_img);
4160 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4162 #endif
4163 return 1;
4165 failure:
4166 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4167 x_destroy_x_image (ximg);
4168 x_destroy_x_image (mask_img);
4169 x_clear_image (f, img);
4170 return 0;
4172 #undef match
4173 #undef expect
4174 #undef expect_ident
4177 static bool
4178 xpm_load (struct frame *f,
4179 struct image *img)
4181 bool success_p = 0;
4182 Lisp_Object file_name;
4184 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4185 file_name = image_spec_value (img->spec, QCfile, NULL);
4186 if (STRINGP (file_name))
4188 Lisp_Object file;
4189 unsigned char *contents;
4190 ptrdiff_t size;
4192 file = x_find_image_file (file_name);
4193 if (!STRINGP (file))
4195 image_error ("Cannot find image file `%s'", file_name, Qnil);
4196 return 0;
4199 contents = slurp_file (SSDATA (file), &size);
4200 if (contents == NULL)
4202 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4203 return 0;
4206 success_p = xpm_load_image (f, img, contents, contents + size);
4207 xfree (contents);
4209 else
4211 Lisp_Object data;
4213 data = image_spec_value (img->spec, QCdata, NULL);
4214 if (!STRINGP (data))
4216 image_error ("Invalid image data `%s'", data, Qnil);
4217 return 0;
4219 success_p = xpm_load_image (f, img, SDATA (data),
4220 SDATA (data) + SBYTES (data));
4223 return success_p;
4226 #endif /* HAVE_NS && !HAVE_XPM */
4230 /***********************************************************************
4231 Color table
4232 ***********************************************************************/
4234 #ifdef COLOR_TABLE_SUPPORT
4236 /* An entry in the color table mapping an RGB color to a pixel color. */
4238 struct ct_color
4240 int r, g, b;
4241 unsigned long pixel;
4243 /* Next in color table collision list. */
4244 struct ct_color *next;
4247 /* The bucket vector size to use. Must be prime. */
4249 #define CT_SIZE 101
4251 /* Value is a hash of the RGB color given by R, G, and B. */
4253 static unsigned
4254 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4256 return (r << 16) ^ (g << 8) ^ b;
4259 /* The color hash table. */
4261 static struct ct_color **ct_table;
4263 /* Number of entries in the color table. */
4265 static int ct_colors_allocated;
4266 enum
4268 ct_colors_allocated_max =
4269 min (INT_MAX,
4270 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4273 /* Initialize the color table. */
4275 static void
4276 init_color_table (void)
4278 int size = CT_SIZE * sizeof (*ct_table);
4279 ct_table = xzalloc (size);
4280 ct_colors_allocated = 0;
4284 /* Free memory associated with the color table. */
4286 static void
4287 free_color_table (void)
4289 int i;
4290 struct ct_color *p, *next;
4292 for (i = 0; i < CT_SIZE; ++i)
4293 for (p = ct_table[i]; p; p = next)
4295 next = p->next;
4296 xfree (p);
4299 xfree (ct_table);
4300 ct_table = NULL;
4304 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4305 entry for that color already is in the color table, return the
4306 pixel color of that entry. Otherwise, allocate a new color for R,
4307 G, B, and make an entry in the color table. */
4309 static unsigned long
4310 lookup_rgb_color (struct frame *f, int r, int g, int b)
4312 unsigned hash = ct_hash_rgb (r, g, b);
4313 int i = hash % CT_SIZE;
4314 struct ct_color *p;
4315 Display_Info *dpyinfo;
4317 /* Handle TrueColor visuals specially, which improves performance by
4318 two orders of magnitude. Freeing colors on TrueColor visuals is
4319 a nop, and pixel colors specify RGB values directly. See also
4320 the Xlib spec, chapter 3.1. */
4321 dpyinfo = FRAME_DISPLAY_INFO (f);
4322 if (dpyinfo->red_bits > 0)
4324 unsigned long pr, pg, pb;
4326 /* Apply gamma-correction like normal color allocation does. */
4327 if (f->gamma)
4329 XColor color;
4330 color.red = r, color.green = g, color.blue = b;
4331 gamma_correct (f, &color);
4332 r = color.red, g = color.green, b = color.blue;
4335 /* Scale down RGB values to the visual's bits per RGB, and shift
4336 them to the right position in the pixel color. Note that the
4337 original RGB values are 16-bit values, as usual in X. */
4338 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4339 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4340 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4342 /* Assemble the pixel color. */
4343 return pr | pg | pb;
4346 for (p = ct_table[i]; p; p = p->next)
4347 if (p->r == r && p->g == g && p->b == b)
4348 break;
4350 if (p == NULL)
4353 #ifdef HAVE_X_WINDOWS
4354 XColor color;
4355 Colormap cmap;
4356 bool rc;
4357 #else
4358 COLORREF color;
4359 #endif
4361 if (ct_colors_allocated_max <= ct_colors_allocated)
4362 return FRAME_FOREGROUND_PIXEL (f);
4364 #ifdef HAVE_X_WINDOWS
4365 color.red = r;
4366 color.green = g;
4367 color.blue = b;
4369 cmap = FRAME_X_COLORMAP (f);
4370 rc = x_alloc_nearest_color (f, cmap, &color);
4371 if (rc)
4373 ++ct_colors_allocated;
4374 p = xmalloc (sizeof *p);
4375 p->r = r;
4376 p->g = g;
4377 p->b = b;
4378 p->pixel = color.pixel;
4379 p->next = ct_table[i];
4380 ct_table[i] = p;
4382 else
4383 return FRAME_FOREGROUND_PIXEL (f);
4385 #else
4386 #ifdef HAVE_NTGUI
4387 color = PALETTERGB (r, g, b);
4388 #else
4389 color = RGB_TO_ULONG (r, g, b);
4390 #endif /* HAVE_NTGUI */
4391 ++ct_colors_allocated;
4392 p = xmalloc (sizeof *p);
4393 p->r = r;
4394 p->g = g;
4395 p->b = b;
4396 p->pixel = color;
4397 p->next = ct_table[i];
4398 ct_table[i] = p;
4399 #endif /* HAVE_X_WINDOWS */
4403 return p->pixel;
4407 /* Look up pixel color PIXEL which is used on frame F in the color
4408 table. If not already present, allocate it. Value is PIXEL. */
4410 static unsigned long
4411 lookup_pixel_color (struct frame *f, unsigned long pixel)
4413 int i = pixel % CT_SIZE;
4414 struct ct_color *p;
4416 for (p = ct_table[i]; p; p = p->next)
4417 if (p->pixel == pixel)
4418 break;
4420 if (p == NULL)
4422 XColor color;
4423 Colormap cmap;
4424 bool rc;
4426 if (ct_colors_allocated >= ct_colors_allocated_max)
4427 return FRAME_FOREGROUND_PIXEL (f);
4429 #ifdef HAVE_X_WINDOWS
4430 cmap = FRAME_X_COLORMAP (f);
4431 color.pixel = pixel;
4432 x_query_color (f, &color);
4433 rc = x_alloc_nearest_color (f, cmap, &color);
4434 #else
4435 block_input ();
4436 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4437 color.pixel = pixel;
4438 XQueryColor (NULL, cmap, &color);
4439 rc = x_alloc_nearest_color (f, cmap, &color);
4440 unblock_input ();
4441 #endif /* HAVE_X_WINDOWS */
4443 if (rc)
4445 ++ct_colors_allocated;
4447 p = xmalloc (sizeof *p);
4448 p->r = color.red;
4449 p->g = color.green;
4450 p->b = color.blue;
4451 p->pixel = pixel;
4452 p->next = ct_table[i];
4453 ct_table[i] = p;
4455 else
4456 return FRAME_FOREGROUND_PIXEL (f);
4458 return p->pixel;
4462 /* Value is a vector of all pixel colors contained in the color table,
4463 allocated via xmalloc. Set *N to the number of colors. */
4465 static unsigned long *
4466 colors_in_color_table (int *n)
4468 int i, j;
4469 struct ct_color *p;
4470 unsigned long *colors;
4472 if (ct_colors_allocated == 0)
4474 *n = 0;
4475 colors = NULL;
4477 else
4479 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4480 *n = ct_colors_allocated;
4482 for (i = j = 0; i < CT_SIZE; ++i)
4483 for (p = ct_table[i]; p; p = p->next)
4484 colors[j++] = p->pixel;
4487 return colors;
4490 #else /* COLOR_TABLE_SUPPORT */
4492 static unsigned long
4493 lookup_rgb_color (struct frame *f, int r, int g, int b)
4495 unsigned long pixel;
4497 #ifdef HAVE_NTGUI
4498 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4499 #endif /* HAVE_NTGUI */
4501 #ifdef HAVE_NS
4502 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4503 #endif /* HAVE_NS */
4504 return pixel;
4507 static void
4508 init_color_table (void)
4511 #endif /* COLOR_TABLE_SUPPORT */
4514 /***********************************************************************
4515 Algorithms
4516 ***********************************************************************/
4518 /* Edge detection matrices for different edge-detection
4519 strategies. */
4521 static int emboss_matrix[9] = {
4522 /* x - 1 x x + 1 */
4523 2, -1, 0, /* y - 1 */
4524 -1, 0, 1, /* y */
4525 0, 1, -2 /* y + 1 */
4528 static int laplace_matrix[9] = {
4529 /* x - 1 x x + 1 */
4530 1, 0, 0, /* y - 1 */
4531 0, 0, 0, /* y */
4532 0, 0, -1 /* y + 1 */
4535 /* Value is the intensity of the color whose red/green/blue values
4536 are R, G, and B. */
4538 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4541 /* On frame F, return an array of XColor structures describing image
4542 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4543 means also fill the red/green/blue members of the XColor
4544 structures. Value is a pointer to the array of XColors structures,
4545 allocated with xmalloc; it must be freed by the caller. */
4547 static XColor *
4548 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4550 int x, y;
4551 XColor *colors, *p;
4552 XImagePtr_or_DC ximg;
4553 #ifdef HAVE_NTGUI
4554 HGDIOBJ prev;
4555 #endif /* HAVE_NTGUI */
4557 if (img->height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width)
4558 memory_full (SIZE_MAX);
4559 colors = xmalloc (sizeof *colors * img->width * img->height);
4561 /* Get the X image or create a memory device context for IMG. */
4562 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4564 /* Fill the `pixel' members of the XColor array. I wished there
4565 were an easy and portable way to circumvent XGetPixel. */
4566 p = colors;
4567 for (y = 0; y < img->height; ++y)
4569 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4570 XColor *row = p;
4571 for (x = 0; x < img->width; ++x, ++p)
4572 p->pixel = GET_PIXEL (ximg, x, y);
4573 if (rgb_p)
4574 x_query_colors (f, row, img->width);
4576 #else
4578 for (x = 0; x < img->width; ++x, ++p)
4580 /* W32_TODO: palette support needed here? */
4581 p->pixel = GET_PIXEL (ximg, x, y);
4582 if (rgb_p)
4584 p->red = RED16_FROM_ULONG (p->pixel);
4585 p->green = GREEN16_FROM_ULONG (p->pixel);
4586 p->blue = BLUE16_FROM_ULONG (p->pixel);
4589 #endif /* HAVE_X_WINDOWS */
4592 image_unget_x_image_or_dc (img, 0, ximg, prev);
4594 return colors;
4597 #ifdef HAVE_NTGUI
4599 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4600 created with CreateDIBSection, with the pointer to the bit values
4601 stored in ximg->data. */
4603 static void
4604 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4606 int width = ximg->info.bmiHeader.biWidth;
4607 unsigned char * pixel;
4609 /* True color images. */
4610 if (ximg->info.bmiHeader.biBitCount == 24)
4612 int rowbytes = width * 3;
4613 /* Ensure scanlines are aligned on 4 byte boundaries. */
4614 if (rowbytes % 4)
4615 rowbytes += 4 - (rowbytes % 4);
4617 pixel = ximg->data + y * rowbytes + x * 3;
4618 /* Windows bitmaps are in BGR order. */
4619 *pixel = GetBValue (color);
4620 *(pixel + 1) = GetGValue (color);
4621 *(pixel + 2) = GetRValue (color);
4623 /* Monochrome images. */
4624 else if (ximg->info.bmiHeader.biBitCount == 1)
4626 int rowbytes = width / 8;
4627 /* Ensure scanlines are aligned on 4 byte boundaries. */
4628 if (rowbytes % 4)
4629 rowbytes += 4 - (rowbytes % 4);
4630 pixel = ximg->data + y * rowbytes + x / 8;
4631 /* Filter out palette info. */
4632 if (color & 0x00ffffff)
4633 *pixel = *pixel | (1 << x % 8);
4634 else
4635 *pixel = *pixel & ~(1 << x % 8);
4637 else
4638 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4641 #endif /* HAVE_NTGUI */
4643 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4644 RGB members are set. F is the frame on which this all happens.
4645 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4647 static void
4648 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4650 int x, y;
4651 XImagePtr oimg = NULL;
4652 XColor *p;
4654 init_color_table ();
4656 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4657 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4658 &oimg, 0);
4659 p = colors;
4660 for (y = 0; y < img->height; ++y)
4661 for (x = 0; x < img->width; ++x, ++p)
4663 unsigned long pixel;
4664 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4665 XPutPixel (oimg, x, y, pixel);
4668 xfree (colors);
4670 image_put_x_image (f, img, oimg, 0);
4671 #ifdef COLOR_TABLE_SUPPORT
4672 img->colors = colors_in_color_table (&img->ncolors);
4673 free_color_table ();
4674 #endif /* COLOR_TABLE_SUPPORT */
4678 /* On frame F, perform edge-detection on image IMG.
4680 MATRIX is a nine-element array specifying the transformation
4681 matrix. See emboss_matrix for an example.
4683 COLOR_ADJUST is a color adjustment added to each pixel of the
4684 outgoing image. */
4686 static void
4687 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4689 XColor *colors = x_to_xcolors (f, img, 1);
4690 XColor *new, *p;
4691 int x, y, i, sum;
4693 for (i = sum = 0; i < 9; ++i)
4694 sum += eabs (matrix[i]);
4696 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4698 if (img->height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width)
4699 memory_full (SIZE_MAX);
4700 new = xmalloc (sizeof *new * img->width * img->height);
4702 for (y = 0; y < img->height; ++y)
4704 p = COLOR (new, 0, y);
4705 p->red = p->green = p->blue = 0xffff/2;
4706 p = COLOR (new, img->width - 1, y);
4707 p->red = p->green = p->blue = 0xffff/2;
4710 for (x = 1; x < img->width - 1; ++x)
4712 p = COLOR (new, x, 0);
4713 p->red = p->green = p->blue = 0xffff/2;
4714 p = COLOR (new, x, img->height - 1);
4715 p->red = p->green = p->blue = 0xffff/2;
4718 for (y = 1; y < img->height - 1; ++y)
4720 p = COLOR (new, 1, y);
4722 for (x = 1; x < img->width - 1; ++x, ++p)
4724 int r, g, b, yy, xx;
4726 r = g = b = i = 0;
4727 for (yy = y - 1; yy < y + 2; ++yy)
4728 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4729 if (matrix[i])
4731 XColor *t = COLOR (colors, xx, yy);
4732 r += matrix[i] * t->red;
4733 g += matrix[i] * t->green;
4734 b += matrix[i] * t->blue;
4737 r = (r / sum + color_adjust) & 0xffff;
4738 g = (g / sum + color_adjust) & 0xffff;
4739 b = (b / sum + color_adjust) & 0xffff;
4740 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4744 xfree (colors);
4745 x_from_xcolors (f, img, new);
4747 #undef COLOR
4751 /* Perform the pre-defined `emboss' edge-detection on image IMG
4752 on frame F. */
4754 static void
4755 x_emboss (struct frame *f, struct image *img)
4757 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4761 /* Transform image IMG which is used on frame F with a Laplace
4762 edge-detection algorithm. The result is an image that can be used
4763 to draw disabled buttons, for example. */
4765 static void
4766 x_laplace (struct frame *f, struct image *img)
4768 x_detect_edges (f, img, laplace_matrix, 45000);
4772 /* Perform edge-detection on image IMG on frame F, with specified
4773 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4775 MATRIX must be either
4777 - a list of at least 9 numbers in row-major form
4778 - a vector of at least 9 numbers
4780 COLOR_ADJUST nil means use a default; otherwise it must be a
4781 number. */
4783 static void
4784 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4785 Lisp_Object color_adjust)
4787 int i = 0;
4788 int trans[9];
4790 if (CONSP (matrix))
4792 for (i = 0;
4793 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4794 ++i, matrix = XCDR (matrix))
4795 trans[i] = XFLOATINT (XCAR (matrix));
4797 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4799 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4800 trans[i] = XFLOATINT (AREF (matrix, i));
4803 if (NILP (color_adjust))
4804 color_adjust = make_number (0xffff / 2);
4806 if (i == 9 && NUMBERP (color_adjust))
4807 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4811 /* Transform image IMG on frame F so that it looks disabled. */
4813 static void
4814 x_disable_image (struct frame *f, struct image *img)
4816 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4817 #ifdef HAVE_NTGUI
4818 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4819 #else
4820 int n_planes = dpyinfo->n_planes;
4821 #endif /* HAVE_NTGUI */
4823 if (n_planes >= 2)
4825 /* Color (or grayscale). Convert to gray, and equalize. Just
4826 drawing such images with a stipple can look very odd, so
4827 we're using this method instead. */
4828 XColor *colors = x_to_xcolors (f, img, 1);
4829 XColor *p, *end;
4830 const int h = 15000;
4831 const int l = 30000;
4833 for (p = colors, end = colors + img->width * img->height;
4834 p < end;
4835 ++p)
4837 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4838 int i2 = (0xffff - h - l) * i / 0xffff + l;
4839 p->red = p->green = p->blue = i2;
4842 x_from_xcolors (f, img, colors);
4845 /* Draw a cross over the disabled image, if we must or if we
4846 should. */
4847 if (n_planes < 2 || cross_disabled_images)
4849 #ifndef HAVE_NTGUI
4850 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4852 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4854 Display *dpy = FRAME_X_DISPLAY (f);
4855 GC gc;
4857 image_sync_to_pixmaps (f, img);
4858 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4859 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4860 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4861 img->width - 1, img->height - 1);
4862 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4863 img->width - 1, 0);
4864 XFreeGC (dpy, gc);
4866 if (img->mask)
4868 gc = XCreateGC (dpy, img->mask, 0, NULL);
4869 XSetForeground (dpy, gc, MaskForeground (f));
4870 XDrawLine (dpy, img->mask, gc, 0, 0,
4871 img->width - 1, img->height - 1);
4872 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4873 img->width - 1, 0);
4874 XFreeGC (dpy, gc);
4876 #endif /* !HAVE_NS */
4877 #else
4878 HDC hdc, bmpdc;
4879 HGDIOBJ prev;
4881 hdc = get_frame_dc (f);
4882 bmpdc = CreateCompatibleDC (hdc);
4883 release_frame_dc (f, hdc);
4885 prev = SelectObject (bmpdc, img->pixmap);
4887 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4888 MoveToEx (bmpdc, 0, 0, NULL);
4889 LineTo (bmpdc, img->width - 1, img->height - 1);
4890 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4891 LineTo (bmpdc, img->width - 1, 0);
4893 if (img->mask)
4895 SelectObject (bmpdc, img->mask);
4896 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4897 MoveToEx (bmpdc, 0, 0, NULL);
4898 LineTo (bmpdc, img->width - 1, img->height - 1);
4899 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4900 LineTo (bmpdc, img->width - 1, 0);
4902 SelectObject (bmpdc, prev);
4903 DeleteDC (bmpdc);
4904 #endif /* HAVE_NTGUI */
4909 /* Build a mask for image IMG which is used on frame F. FILE is the
4910 name of an image file, for error messages. HOW determines how to
4911 determine the background color of IMG. If it is a list '(R G B)',
4912 with R, G, and B being integers >= 0, take that as the color of the
4913 background. Otherwise, determine the background color of IMG
4914 heuristically. */
4916 static void
4917 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4919 XImagePtr_or_DC ximg;
4920 #ifndef HAVE_NTGUI
4921 XImagePtr mask_img;
4922 #else
4923 HGDIOBJ prev;
4924 char *mask_img;
4925 int row_width;
4926 #endif /* HAVE_NTGUI */
4927 int x, y;
4928 bool use_img_background;
4929 unsigned long bg = 0;
4931 if (img->mask)
4932 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4934 #ifndef HAVE_NTGUI
4935 #ifndef HAVE_NS
4936 /* Create an image and pixmap serving as mask. */
4937 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
4938 &mask_img, 1))
4939 return;
4940 #endif /* !HAVE_NS */
4941 #else
4942 /* Create the bit array serving as mask. */
4943 row_width = (img->width + 7) / 8;
4944 mask_img = xzalloc (row_width * img->height);
4945 #endif /* HAVE_NTGUI */
4947 /* Get the X image or create a memory device context for IMG. */
4948 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4950 /* Determine the background color of ximg. If HOW is `(R G B)'
4951 take that as color. Otherwise, use the image's background color. */
4952 use_img_background = 1;
4954 if (CONSP (how))
4956 int rgb[3], i;
4958 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4960 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4961 how = XCDR (how);
4964 if (i == 3 && NILP (how))
4966 char color_name[30];
4967 sprintf (color_name, "#%04x%04x%04x",
4968 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
4969 bg = (
4970 #ifdef HAVE_NTGUI
4971 0x00ffffff & /* Filter out palette info. */
4972 #endif /* HAVE_NTGUI */
4973 x_alloc_image_color (f, img, build_string (color_name), 0));
4974 use_img_background = 0;
4978 if (use_img_background)
4979 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4981 /* Set all bits in mask_img to 1 whose color in ximg is different
4982 from the background color bg. */
4983 #ifndef HAVE_NTGUI
4984 for (y = 0; y < img->height; ++y)
4985 for (x = 0; x < img->width; ++x)
4986 #ifndef HAVE_NS
4987 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4988 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4989 #else
4990 if (XGetPixel (ximg, x, y) == bg)
4991 ns_set_alpha (ximg, x, y, 0);
4992 #endif /* HAVE_NS */
4993 #ifndef HAVE_NS
4994 /* Fill in the background_transparent field while we have the mask handy. */
4995 image_background_transparent (img, f, mask_img);
4997 /* Put mask_img into the image. */
4998 image_put_x_image (f, img, mask_img, 1);
4999 #endif /* !HAVE_NS */
5000 #else
5001 for (y = 0; y < img->height; ++y)
5002 for (x = 0; x < img->width; ++x)
5004 COLORREF p = GetPixel (ximg, x, y);
5005 if (p != bg)
5006 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5009 /* Create the mask image. */
5010 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5011 mask_img);
5012 /* Fill in the background_transparent field while we have the mask handy. */
5013 SelectObject (ximg, img->mask);
5014 image_background_transparent (img, f, ximg);
5016 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5017 xfree (mask_img);
5018 #endif /* HAVE_NTGUI */
5020 image_unget_x_image_or_dc (img, 0, ximg, prev);
5024 /***********************************************************************
5025 PBM (mono, gray, color)
5026 ***********************************************************************/
5028 static bool pbm_image_p (Lisp_Object object);
5029 static bool pbm_load (struct frame *f, struct image *img);
5031 /* Indices of image specification fields in gs_format, below. */
5033 enum pbm_keyword_index
5035 PBM_TYPE,
5036 PBM_FILE,
5037 PBM_DATA,
5038 PBM_ASCENT,
5039 PBM_MARGIN,
5040 PBM_RELIEF,
5041 PBM_ALGORITHM,
5042 PBM_HEURISTIC_MASK,
5043 PBM_MASK,
5044 PBM_FOREGROUND,
5045 PBM_BACKGROUND,
5046 PBM_LAST
5049 /* Vector of image_keyword structures describing the format
5050 of valid user-defined image specifications. */
5052 static const struct image_keyword pbm_format[PBM_LAST] =
5054 {":type", IMAGE_SYMBOL_VALUE, 1},
5055 {":file", IMAGE_STRING_VALUE, 0},
5056 {":data", IMAGE_STRING_VALUE, 0},
5057 {":ascent", IMAGE_ASCENT_VALUE, 0},
5058 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5059 {":relief", IMAGE_INTEGER_VALUE, 0},
5060 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5061 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5062 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5063 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5064 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5067 /* Structure describing the image type `pbm'. */
5069 static struct image_type pbm_type =
5071 SYMBOL_INDEX (Qpbm),
5072 pbm_image_p,
5073 pbm_load,
5074 x_clear_image,
5075 NULL,
5076 NULL
5080 /* Return true if OBJECT is a valid PBM image specification. */
5082 static bool
5083 pbm_image_p (Lisp_Object object)
5085 struct image_keyword fmt[PBM_LAST];
5087 memcpy (fmt, pbm_format, sizeof fmt);
5089 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5090 return 0;
5092 /* Must specify either :data or :file. */
5093 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5097 /* Get next char skipping comments in Netpbm header. Returns -1 at
5098 end of input. */
5100 static int
5101 pbm_next_char (unsigned char **s, unsigned char *end)
5103 int c = -1;
5105 while (*s < end && (c = *(*s)++, c == '#'))
5107 /* Skip to the next line break. */
5108 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5111 c = -1;
5114 return c;
5118 /* Scan a decimal number from *S and return it. Advance *S while
5119 reading the number. END is the end of the string. Value is -1 at
5120 end of input. */
5122 static int
5123 pbm_scan_number (unsigned char **s, unsigned char *end)
5125 int c = 0, val = -1;
5127 /* Skip white-space. */
5128 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5131 if (c_isdigit (c))
5133 /* Read decimal number. */
5134 val = c - '0';
5135 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5136 val = 10 * val + c - '0';
5139 return val;
5143 /* Load PBM image IMG for use on frame F. */
5145 static bool
5146 pbm_load (struct frame *f, struct image *img)
5148 bool raw_p;
5149 int x, y;
5150 int width, height, max_color_idx = 0;
5151 XImagePtr ximg;
5152 Lisp_Object file, specified_file;
5153 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5154 unsigned char *contents = NULL;
5155 unsigned char *end, *p;
5156 ptrdiff_t size;
5158 specified_file = image_spec_value (img->spec, QCfile, NULL);
5160 if (STRINGP (specified_file))
5162 file = x_find_image_file (specified_file);
5163 if (!STRINGP (file))
5165 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5166 return 0;
5169 contents = slurp_file (SSDATA (file), &size);
5170 if (contents == NULL)
5172 image_error ("Error reading `%s'", file, Qnil);
5173 return 0;
5176 p = contents;
5177 end = contents + size;
5179 else
5181 Lisp_Object data;
5182 data = image_spec_value (img->spec, QCdata, NULL);
5183 if (!STRINGP (data))
5185 image_error ("Invalid image data `%s'", data, Qnil);
5186 return 0;
5188 p = SDATA (data);
5189 end = p + SBYTES (data);
5192 /* Check magic number. */
5193 if (end - p < 2 || *p++ != 'P')
5195 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5196 error:
5197 xfree (contents);
5198 img->pixmap = NO_PIXMAP;
5199 return 0;
5202 switch (*p++)
5204 case '1':
5205 raw_p = 0, type = PBM_MONO;
5206 break;
5208 case '2':
5209 raw_p = 0, type = PBM_GRAY;
5210 break;
5212 case '3':
5213 raw_p = 0, type = PBM_COLOR;
5214 break;
5216 case '4':
5217 raw_p = 1, type = PBM_MONO;
5218 break;
5220 case '5':
5221 raw_p = 1, type = PBM_GRAY;
5222 break;
5224 case '6':
5225 raw_p = 1, type = PBM_COLOR;
5226 break;
5228 default:
5229 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5230 goto error;
5233 /* Read width, height, maximum color-component. Characters
5234 starting with `#' up to the end of a line are ignored. */
5235 width = pbm_scan_number (&p, end);
5236 height = pbm_scan_number (&p, end);
5238 if (type != PBM_MONO)
5240 max_color_idx = pbm_scan_number (&p, end);
5241 if (max_color_idx > 65535 || max_color_idx < 0)
5243 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5244 goto error;
5248 if (!check_image_size (f, width, height))
5250 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5251 goto error;
5254 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5255 goto error;
5257 /* Initialize the color hash table. */
5258 init_color_table ();
5260 if (type == PBM_MONO)
5262 int c = 0, g;
5263 struct image_keyword fmt[PBM_LAST];
5264 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5265 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5267 /* Parse the image specification. */
5268 memcpy (fmt, pbm_format, sizeof fmt);
5269 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5271 /* Get foreground and background colors, maybe allocate colors. */
5272 if (fmt[PBM_FOREGROUND].count
5273 && STRINGP (fmt[PBM_FOREGROUND].value))
5274 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5275 if (fmt[PBM_BACKGROUND].count
5276 && STRINGP (fmt[PBM_BACKGROUND].value))
5278 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5279 img->background = bg;
5280 img->background_valid = 1;
5283 for (y = 0; y < height; ++y)
5284 for (x = 0; x < width; ++x)
5286 if (raw_p)
5288 if ((x & 7) == 0)
5290 if (p >= end)
5292 x_destroy_x_image (ximg);
5293 x_clear_image (f, img);
5294 image_error ("Invalid image size in image `%s'",
5295 img->spec, Qnil);
5296 goto error;
5298 c = *p++;
5300 g = c & 0x80;
5301 c <<= 1;
5303 else
5304 g = pbm_scan_number (&p, end);
5306 XPutPixel (ximg, x, y, g ? fg : bg);
5309 else
5311 int expected_size = height * width;
5312 if (max_color_idx > 255)
5313 expected_size *= 2;
5314 if (type == PBM_COLOR)
5315 expected_size *= 3;
5317 if (raw_p && p + expected_size > end)
5319 x_destroy_x_image (ximg);
5320 x_clear_image (f, img);
5321 image_error ("Invalid image size in image `%s'",
5322 img->spec, Qnil);
5323 goto error;
5326 for (y = 0; y < height; ++y)
5327 for (x = 0; x < width; ++x)
5329 int r, g, b;
5331 if (type == PBM_GRAY && raw_p)
5333 r = g = b = *p++;
5334 if (max_color_idx > 255)
5335 r = g = b = r * 256 + *p++;
5337 else if (type == PBM_GRAY)
5338 r = g = b = pbm_scan_number (&p, end);
5339 else if (raw_p)
5341 r = *p++;
5342 if (max_color_idx > 255)
5343 r = r * 256 + *p++;
5344 g = *p++;
5345 if (max_color_idx > 255)
5346 g = g * 256 + *p++;
5347 b = *p++;
5348 if (max_color_idx > 255)
5349 b = b * 256 + *p++;
5351 else
5353 r = pbm_scan_number (&p, end);
5354 g = pbm_scan_number (&p, end);
5355 b = pbm_scan_number (&p, end);
5358 if (r < 0 || g < 0 || b < 0)
5360 x_destroy_x_image (ximg);
5361 image_error ("Invalid pixel value in image `%s'",
5362 img->spec, Qnil);
5363 goto error;
5366 /* RGB values are now in the range 0..max_color_idx.
5367 Scale this to the range 0..0xffff supported by X. */
5368 r = (double) r * 65535 / max_color_idx;
5369 g = (double) g * 65535 / max_color_idx;
5370 b = (double) b * 65535 / max_color_idx;
5371 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5375 #ifdef COLOR_TABLE_SUPPORT
5376 /* Store in IMG->colors the colors allocated for the image, and
5377 free the color table. */
5378 img->colors = colors_in_color_table (&img->ncolors);
5379 free_color_table ();
5380 #endif /* COLOR_TABLE_SUPPORT */
5382 img->width = width;
5383 img->height = height;
5385 /* Maybe fill in the background field while we have ximg handy. */
5387 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5388 /* Casting avoids a GCC warning. */
5389 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5391 /* Put ximg into the image. */
5392 image_put_x_image (f, img, ximg, 0);
5394 /* X and W32 versions did it here, MAC version above. ++kfs
5395 img->width = width;
5396 img->height = height; */
5398 xfree (contents);
5399 return 1;
5403 /***********************************************************************
5405 ***********************************************************************/
5407 #if defined (HAVE_PNG) || defined (HAVE_NS)
5409 /* Function prototypes. */
5411 static bool png_image_p (Lisp_Object object);
5412 static bool png_load (struct frame *f, struct image *img);
5414 /* Indices of image specification fields in png_format, below. */
5416 enum png_keyword_index
5418 PNG_TYPE,
5419 PNG_DATA,
5420 PNG_FILE,
5421 PNG_ASCENT,
5422 PNG_MARGIN,
5423 PNG_RELIEF,
5424 PNG_ALGORITHM,
5425 PNG_HEURISTIC_MASK,
5426 PNG_MASK,
5427 PNG_BACKGROUND,
5428 PNG_LAST
5431 /* Vector of image_keyword structures describing the format
5432 of valid user-defined image specifications. */
5434 static const struct image_keyword png_format[PNG_LAST] =
5436 {":type", IMAGE_SYMBOL_VALUE, 1},
5437 {":data", IMAGE_STRING_VALUE, 0},
5438 {":file", IMAGE_STRING_VALUE, 0},
5439 {":ascent", IMAGE_ASCENT_VALUE, 0},
5440 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5441 {":relief", IMAGE_INTEGER_VALUE, 0},
5442 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5443 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5444 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5445 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5448 #if defined HAVE_NTGUI && defined WINDOWSNT
5449 static bool init_png_functions (void);
5450 #else
5451 #define init_png_functions NULL
5452 #endif
5454 /* Structure describing the image type `png'. */
5456 static struct image_type png_type =
5458 SYMBOL_INDEX (Qpng),
5459 png_image_p,
5460 png_load,
5461 x_clear_image,
5462 init_png_functions,
5463 NULL
5466 /* Return true if OBJECT is a valid PNG image specification. */
5468 static bool
5469 png_image_p (Lisp_Object object)
5471 struct image_keyword fmt[PNG_LAST];
5472 memcpy (fmt, png_format, sizeof fmt);
5474 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5475 return 0;
5477 /* Must specify either the :data or :file keyword. */
5478 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5481 #endif /* HAVE_PNG || HAVE_NS */
5484 #if defined HAVE_PNG && !defined HAVE_NS
5486 # ifdef WINDOWSNT
5487 /* PNG library details. */
5489 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5490 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5491 DEF_DLL_FN (png_structp, png_create_read_struct,
5492 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5493 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5494 DEF_DLL_FN (void, png_destroy_read_struct,
5495 (png_structpp, png_infopp, png_infopp));
5496 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5497 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5498 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5499 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5500 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5501 int *, int *, int *, int *, int *));
5502 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5503 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5504 DEF_DLL_FN (void, png_set_expand, (png_structp));
5505 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5506 DEF_DLL_FN (void, png_set_background,
5507 (png_structp, png_color_16p, int, int, double));
5508 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5509 (png_structp, png_infop, png_color_16p *));
5510 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5511 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5512 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5513 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5514 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5515 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5517 # if (PNG_LIBPNG_VER >= 10500)
5518 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5519 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5520 (png_structp, png_longjmp_ptr, size_t));
5521 # endif /* libpng version >= 1.5 */
5523 static bool
5524 init_png_functions (void)
5526 HMODULE library;
5528 if (!(library = w32_delayed_load (Qpng)))
5529 return 0;
5531 LOAD_DLL_FN (library, png_get_io_ptr);
5532 LOAD_DLL_FN (library, png_sig_cmp);
5533 LOAD_DLL_FN (library, png_create_read_struct);
5534 LOAD_DLL_FN (library, png_create_info_struct);
5535 LOAD_DLL_FN (library, png_destroy_read_struct);
5536 LOAD_DLL_FN (library, png_set_read_fn);
5537 LOAD_DLL_FN (library, png_set_sig_bytes);
5538 LOAD_DLL_FN (library, png_read_info);
5539 LOAD_DLL_FN (library, png_get_IHDR);
5540 LOAD_DLL_FN (library, png_get_valid);
5541 LOAD_DLL_FN (library, png_set_strip_16);
5542 LOAD_DLL_FN (library, png_set_expand);
5543 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5544 LOAD_DLL_FN (library, png_set_background);
5545 LOAD_DLL_FN (library, png_get_bKGD);
5546 LOAD_DLL_FN (library, png_read_update_info);
5547 LOAD_DLL_FN (library, png_get_channels);
5548 LOAD_DLL_FN (library, png_get_rowbytes);
5549 LOAD_DLL_FN (library, png_read_image);
5550 LOAD_DLL_FN (library, png_read_end);
5551 LOAD_DLL_FN (library, png_error);
5553 # if (PNG_LIBPNG_VER >= 10500)
5554 LOAD_DLL_FN (library, png_longjmp);
5555 LOAD_DLL_FN (library, png_set_longjmp_fn);
5556 # endif /* libpng version >= 1.5 */
5558 return 1;
5561 # undef png_create_info_struct
5562 # undef png_create_read_struct
5563 # undef png_destroy_read_struct
5564 # undef png_error
5565 # undef png_get_bKGD
5566 # undef png_get_channels
5567 # undef png_get_IHDR
5568 # undef png_get_io_ptr
5569 # undef png_get_rowbytes
5570 # undef png_get_valid
5571 # undef png_longjmp
5572 # undef png_read_end
5573 # undef png_read_image
5574 # undef png_read_info
5575 # undef png_read_update_info
5576 # undef png_set_background
5577 # undef png_set_expand
5578 # undef png_set_gray_to_rgb
5579 # undef png_set_longjmp_fn
5580 # undef png_set_read_fn
5581 # undef png_set_sig_bytes
5582 # undef png_set_strip_16
5583 # undef png_sig_cmp
5585 # define png_create_info_struct fn_png_create_info_struct
5586 # define png_create_read_struct fn_png_create_read_struct
5587 # define png_destroy_read_struct fn_png_destroy_read_struct
5588 # define png_error fn_png_error
5589 # define png_get_bKGD fn_png_get_bKGD
5590 # define png_get_channels fn_png_get_channels
5591 # define png_get_IHDR fn_png_get_IHDR
5592 # define png_get_io_ptr fn_png_get_io_ptr
5593 # define png_get_rowbytes fn_png_get_rowbytes
5594 # define png_get_valid fn_png_get_valid
5595 # define png_longjmp fn_png_longjmp
5596 # define png_read_end fn_png_read_end
5597 # define png_read_image fn_png_read_image
5598 # define png_read_info fn_png_read_info
5599 # define png_read_update_info fn_png_read_update_info
5600 # define png_set_background fn_png_set_background
5601 # define png_set_expand fn_png_set_expand
5602 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5603 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5604 # define png_set_read_fn fn_png_set_read_fn
5605 # define png_set_sig_bytes fn_png_set_sig_bytes
5606 # define png_set_strip_16 fn_png_set_strip_16
5607 # define png_sig_cmp fn_png_sig_cmp
5609 # endif /* WINDOWSNT */
5611 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5612 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5613 Do not use sys_setjmp, as PNG supports only jmp_buf.
5614 It's OK if the longjmp substitute restores the signal mask. */
5615 # ifdef HAVE__SETJMP
5616 # define FAST_SETJMP(j) _setjmp (j)
5617 # define FAST_LONGJMP _longjmp
5618 # else
5619 # define FAST_SETJMP(j) setjmp (j)
5620 # define FAST_LONGJMP longjmp
5621 # endif
5623 # if PNG_LIBPNG_VER < 10500
5624 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5625 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5626 # else
5627 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5628 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5629 # define PNG_JMPBUF(ptr) \
5630 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5631 # endif
5633 /* Error and warning handlers installed when the PNG library
5634 is initialized. */
5636 static _Noreturn void
5637 my_png_error (png_struct *png_ptr, const char *msg)
5639 eassert (png_ptr != NULL);
5640 /* Avoid compiler warning about deprecated direct access to
5641 png_ptr's fields in libpng versions 1.4.x. */
5642 image_error ("PNG error: %s", build_string (msg), Qnil);
5643 PNG_LONGJMP (png_ptr);
5647 static void
5648 my_png_warning (png_struct *png_ptr, const char *msg)
5650 eassert (png_ptr != NULL);
5651 image_error ("PNG warning: %s", build_string (msg), Qnil);
5654 /* Memory source for PNG decoding. */
5656 struct png_memory_storage
5658 unsigned char *bytes; /* The data */
5659 ptrdiff_t len; /* How big is it? */
5660 ptrdiff_t index; /* Where are we? */
5664 /* Function set as reader function when reading PNG image from memory.
5665 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5666 bytes from the input to DATA. */
5668 static void
5669 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5671 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5673 if (length > tbr->len - tbr->index)
5674 png_error (png_ptr, "Read error");
5676 memcpy (data, tbr->bytes + tbr->index, length);
5677 tbr->index = tbr->index + length;
5681 /* Function set as reader function when reading PNG image from a file.
5682 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5683 bytes from the input to DATA. */
5685 static void
5686 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5688 FILE *fp = png_get_io_ptr (png_ptr);
5690 if (fread (data, 1, length, fp) < length)
5691 png_error (png_ptr, "Read error");
5695 /* Load PNG image IMG for use on frame F. Value is true if
5696 successful. */
5698 struct png_load_context
5700 /* These are members so that longjmp doesn't munge local variables. */
5701 png_struct *png_ptr;
5702 png_info *info_ptr;
5703 png_info *end_info;
5704 FILE *fp;
5705 png_byte *pixels;
5706 png_byte **rows;
5709 static bool
5710 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5712 Lisp_Object file, specified_file;
5713 Lisp_Object specified_data;
5714 int x, y;
5715 ptrdiff_t i;
5716 XImagePtr ximg, mask_img = NULL;
5717 png_struct *png_ptr;
5718 png_info *info_ptr = NULL, *end_info = NULL;
5719 FILE *fp = NULL;
5720 png_byte sig[8];
5721 png_byte *pixels = NULL;
5722 png_byte **rows = NULL;
5723 png_uint_32 width, height;
5724 int bit_depth, color_type, interlace_type;
5725 png_byte channels;
5726 png_uint_32 row_bytes;
5727 bool transparent_p;
5728 struct png_memory_storage tbr; /* Data to be read */
5730 /* Find out what file to load. */
5731 specified_file = image_spec_value (img->spec, QCfile, NULL);
5732 specified_data = image_spec_value (img->spec, QCdata, NULL);
5733 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
5735 if (NILP (specified_data))
5737 file = x_find_image_file (specified_file);
5738 if (!STRINGP (file))
5740 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5741 return 0;
5744 /* Open the image file. */
5745 fp = emacs_fopen (SSDATA (file), "rb");
5746 if (!fp)
5748 image_error ("Cannot open image file `%s'", file, Qnil);
5749 return 0;
5752 /* Check PNG signature. */
5753 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5754 || png_sig_cmp (sig, 0, sizeof sig))
5756 fclose (fp);
5757 image_error ("Not a PNG file: `%s'", file, Qnil);
5758 return 0;
5761 else
5763 if (!STRINGP (specified_data))
5765 image_error ("Invalid image data `%s'", specified_data, Qnil);
5766 return 0;
5769 /* Read from memory. */
5770 tbr.bytes = SDATA (specified_data);
5771 tbr.len = SBYTES (specified_data);
5772 tbr.index = 0;
5774 /* Check PNG signature. */
5775 if (tbr.len < sizeof sig
5776 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5778 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5779 return 0;
5782 /* Need to skip past the signature. */
5783 tbr.bytes += sizeof (sig);
5786 /* Initialize read and info structs for PNG lib. */
5787 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5788 NULL, my_png_error,
5789 my_png_warning);
5790 if (png_ptr)
5792 info_ptr = png_create_info_struct (png_ptr);
5793 end_info = png_create_info_struct (png_ptr);
5796 c->png_ptr = png_ptr;
5797 c->info_ptr = info_ptr;
5798 c->end_info = end_info;
5799 c->fp = fp;
5800 c->pixels = pixels;
5801 c->rows = rows;
5803 if (! (info_ptr && end_info))
5805 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5806 png_ptr = 0;
5808 if (! png_ptr)
5810 if (fp) fclose (fp);
5811 return 0;
5814 /* Set error jump-back. We come back here when the PNG library
5815 detects an error. */
5816 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
5818 error:
5819 if (c->png_ptr)
5820 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5821 xfree (c->pixels);
5822 xfree (c->rows);
5823 if (c->fp)
5824 fclose (c->fp);
5825 return 0;
5828 /* Silence a bogus diagnostic; see GCC bug 54561. */
5829 IF_LINT (fp = c->fp);
5830 IF_LINT (specified_data = specified_data_volatile);
5832 /* Read image info. */
5833 if (!NILP (specified_data))
5834 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
5835 else
5836 png_set_read_fn (png_ptr, fp, png_read_from_file);
5838 png_set_sig_bytes (png_ptr, sizeof sig);
5839 png_read_info (png_ptr, info_ptr);
5840 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5841 &interlace_type, NULL, NULL);
5843 if (! (width <= INT_MAX && height <= INT_MAX
5844 && check_image_size (f, width, height)))
5846 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5847 goto error;
5850 /* Create the X image and pixmap now, so that the work below can be
5851 omitted if the image is too large for X. */
5852 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5853 goto error;
5855 /* If image contains simply transparency data, we prefer to
5856 construct a clipping mask. */
5857 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5858 transparent_p = 1;
5859 else
5860 transparent_p = 0;
5862 /* This function is easier to write if we only have to handle
5863 one data format: RGB or RGBA with 8 bits per channel. Let's
5864 transform other formats into that format. */
5866 /* Strip more than 8 bits per channel. */
5867 if (bit_depth == 16)
5868 png_set_strip_16 (png_ptr);
5870 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5871 if available. */
5872 png_set_expand (png_ptr);
5874 /* Convert grayscale images to RGB. */
5875 if (color_type == PNG_COLOR_TYPE_GRAY
5876 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5877 png_set_gray_to_rgb (png_ptr);
5879 /* Handle alpha channel by combining the image with a background
5880 color. Do this only if a real alpha channel is supplied. For
5881 simple transparency, we prefer a clipping mask. */
5882 if (!transparent_p)
5884 /* png_color_16 *image_bg; */
5885 Lisp_Object specified_bg
5886 = image_spec_value (img->spec, QCbackground, NULL);
5887 XColor color;
5889 /* If the user specified a color, try to use it; if not, use the
5890 current frame background, ignoring any default background
5891 color set by the image. */
5892 if (STRINGP (specified_bg)
5893 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
5894 : (x_query_frame_background_color (f, &color), true))
5895 /* The user specified `:background', use that. */
5897 int shift = bit_depth == 16 ? 0 : 8;
5898 png_color_16 bg = { 0 };
5899 bg.red = color.red >> shift;
5900 bg.green = color.green >> shift;
5901 bg.blue = color.blue >> shift;
5903 png_set_background (png_ptr, &bg,
5904 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5908 /* Update info structure. */
5909 png_read_update_info (png_ptr, info_ptr);
5911 /* Get number of channels. Valid values are 1 for grayscale images
5912 and images with a palette, 2 for grayscale images with transparency
5913 information (alpha channel), 3 for RGB images, and 4 for RGB
5914 images with alpha channel, i.e. RGBA. If conversions above were
5915 sufficient we should only have 3 or 4 channels here. */
5916 channels = png_get_channels (png_ptr, info_ptr);
5917 eassert (channels == 3 || channels == 4);
5919 /* Number of bytes needed for one row of the image. */
5920 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
5922 /* Allocate memory for the image. */
5923 if (height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows
5924 || row_bytes > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height)
5925 memory_full (SIZE_MAX);
5926 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
5927 c->rows = rows = xmalloc (height * sizeof *rows);
5928 for (i = 0; i < height; ++i)
5929 rows[i] = pixels + i * row_bytes;
5931 /* Read the entire image. */
5932 png_read_image (png_ptr, rows);
5933 png_read_end (png_ptr, info_ptr);
5934 if (fp)
5936 fclose (fp);
5937 c->fp = NULL;
5940 /* Create an image and pixmap serving as mask if the PNG image
5941 contains an alpha channel. */
5942 if (channels == 4
5943 && !transparent_p
5944 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
5945 &mask_img, 1))
5947 x_destroy_x_image (ximg);
5948 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
5949 goto error;
5952 /* Fill the X image and mask from PNG data. */
5953 init_color_table ();
5955 for (y = 0; y < height; ++y)
5957 png_byte *p = rows[y];
5959 for (x = 0; x < width; ++x)
5961 int r, g, b;
5963 r = *p++ << 8;
5964 g = *p++ << 8;
5965 b = *p++ << 8;
5966 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5967 /* An alpha channel, aka mask channel, associates variable
5968 transparency with an image. Where other image formats
5969 support binary transparency---fully transparent or fully
5970 opaque---PNG allows up to 254 levels of partial transparency.
5971 The PNG library implements partial transparency by combining
5972 the image with a specified background color.
5974 I'm not sure how to handle this here nicely: because the
5975 background on which the image is displayed may change, for
5976 real alpha channel support, it would be necessary to create
5977 a new image for each possible background.
5979 What I'm doing now is that a mask is created if we have
5980 boolean transparency information. Otherwise I'm using
5981 the frame's background color to combine the image with. */
5983 if (channels == 4)
5985 if (mask_img)
5986 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5987 ++p;
5992 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5993 /* Set IMG's background color from the PNG image, unless the user
5994 overrode it. */
5996 png_color_16 *bg;
5997 if (png_get_bKGD (png_ptr, info_ptr, &bg))
5999 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6000 img->background_valid = 1;
6004 # ifdef COLOR_TABLE_SUPPORT
6005 /* Remember colors allocated for this image. */
6006 img->colors = colors_in_color_table (&img->ncolors);
6007 free_color_table ();
6008 # endif /* COLOR_TABLE_SUPPORT */
6010 /* Clean up. */
6011 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6012 xfree (rows);
6013 xfree (pixels);
6015 img->width = width;
6016 img->height = height;
6018 /* Maybe fill in the background field while we have ximg handy.
6019 Casting avoids a GCC warning. */
6020 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6022 /* Put ximg into the image. */
6023 image_put_x_image (f, img, ximg, 0);
6025 /* Same for the mask. */
6026 if (mask_img)
6028 /* Fill in the background_transparent field while we have the
6029 mask handy. Casting avoids a GCC warning. */
6030 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6032 image_put_x_image (f, img, mask_img, 1);
6035 return 1;
6038 static bool
6039 png_load (struct frame *f, struct image *img)
6041 struct png_load_context c;
6042 return png_load_body (f, img, &c);
6045 #elif defined HAVE_NS
6047 static bool
6048 png_load (struct frame *f, struct image *img)
6050 return ns_load_image (f, img,
6051 image_spec_value (img->spec, QCfile, NULL),
6052 image_spec_value (img->spec, QCdata, NULL));
6055 #endif /* HAVE_NS */
6059 /***********************************************************************
6060 JPEG
6061 ***********************************************************************/
6063 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6065 static bool jpeg_image_p (Lisp_Object object);
6066 static bool jpeg_load (struct frame *f, struct image *img);
6068 /* Indices of image specification fields in gs_format, below. */
6070 enum jpeg_keyword_index
6072 JPEG_TYPE,
6073 JPEG_DATA,
6074 JPEG_FILE,
6075 JPEG_ASCENT,
6076 JPEG_MARGIN,
6077 JPEG_RELIEF,
6078 JPEG_ALGORITHM,
6079 JPEG_HEURISTIC_MASK,
6080 JPEG_MASK,
6081 JPEG_BACKGROUND,
6082 JPEG_LAST
6085 /* Vector of image_keyword structures describing the format
6086 of valid user-defined image specifications. */
6088 static const struct image_keyword jpeg_format[JPEG_LAST] =
6090 {":type", IMAGE_SYMBOL_VALUE, 1},
6091 {":data", IMAGE_STRING_VALUE, 0},
6092 {":file", IMAGE_STRING_VALUE, 0},
6093 {":ascent", IMAGE_ASCENT_VALUE, 0},
6094 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6095 {":relief", IMAGE_INTEGER_VALUE, 0},
6096 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6097 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6098 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6099 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6102 #if defined HAVE_NTGUI && defined WINDOWSNT
6103 static bool init_jpeg_functions (void);
6104 #else
6105 #define init_jpeg_functions NULL
6106 #endif
6108 /* Structure describing the image type `jpeg'. */
6110 static struct image_type jpeg_type =
6112 SYMBOL_INDEX (Qjpeg),
6113 jpeg_image_p,
6114 jpeg_load,
6115 x_clear_image,
6116 init_jpeg_functions,
6117 NULL
6120 /* Return true if OBJECT is a valid JPEG image specification. */
6122 static bool
6123 jpeg_image_p (Lisp_Object object)
6125 struct image_keyword fmt[JPEG_LAST];
6127 memcpy (fmt, jpeg_format, sizeof fmt);
6129 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6130 return 0;
6132 /* Must specify either the :data or :file keyword. */
6133 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6136 #endif /* HAVE_JPEG || HAVE_NS */
6138 #ifdef HAVE_JPEG
6140 /* Work around a warning about HAVE_STDLIB_H being redefined in
6141 jconfig.h. */
6142 # ifdef HAVE_STDLIB_H
6143 # undef HAVE_STDLIB_H
6144 # endif
6146 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6147 /* In older releases of the jpeg library, jpeglib.h will define boolean
6148 differently depending on __WIN32__, so make sure it is defined. */
6149 # define __WIN32__ 1
6150 # endif
6152 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6153 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6154 using the Windows boolean type instead of the jpeglib boolean type
6155 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6156 headers are included along with windows.h, so under Cygwin, jpeglib
6157 attempts to define a conflicting boolean type. Worse, forcing
6158 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6159 because it created an ABI incompatibility between the
6160 already-compiled jpeg library and the header interface definition.
6162 The best we can do is to define jpeglib's boolean type to a
6163 different name. This name, jpeg_boolean, remains in effect through
6164 the rest of image.c.
6166 # if defined CYGWIN && defined HAVE_NTGUI
6167 # define boolean jpeg_boolean
6168 # endif
6169 # include <jpeglib.h>
6170 # include <jerror.h>
6172 # ifdef WINDOWSNT
6174 /* JPEG library details. */
6175 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6176 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6177 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6178 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6179 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6180 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6181 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6182 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6183 (struct jpeg_error_mgr *));
6184 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6186 static bool
6187 init_jpeg_functions (void)
6189 HMODULE library;
6191 if (!(library = w32_delayed_load (Qjpeg)))
6192 return 0;
6194 LOAD_DLL_FN (library, jpeg_finish_decompress);
6195 LOAD_DLL_FN (library, jpeg_read_scanlines);
6196 LOAD_DLL_FN (library, jpeg_start_decompress);
6197 LOAD_DLL_FN (library, jpeg_read_header);
6198 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6199 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6200 LOAD_DLL_FN (library, jpeg_std_error);
6201 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6202 return 1;
6205 # undef jpeg_CreateDecompress
6206 # undef jpeg_destroy_decompress
6207 # undef jpeg_finish_decompress
6208 # undef jpeg_read_header
6209 # undef jpeg_read_scanlines
6210 # undef jpeg_resync_to_restart
6211 # undef jpeg_start_decompress
6212 # undef jpeg_std_error
6214 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6215 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6216 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6217 # define jpeg_read_header fn_jpeg_read_header
6218 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6219 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6220 # define jpeg_start_decompress fn_jpeg_start_decompress
6221 # define jpeg_std_error fn_jpeg_std_error
6223 /* Wrapper since we can't directly assign the function pointer
6224 to another function pointer that was declared more completely easily. */
6225 static boolean
6226 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6228 return jpeg_resync_to_restart (cinfo, desired);
6230 # undef jpeg_resync_to_restart
6231 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6233 # endif /* WINDOWSNT */
6235 struct my_jpeg_error_mgr
6237 struct jpeg_error_mgr pub;
6238 sys_jmp_buf setjmp_buffer;
6240 /* The remaining members are so that longjmp doesn't munge local
6241 variables. */
6242 struct jpeg_decompress_struct cinfo;
6243 enum
6245 MY_JPEG_ERROR_EXIT,
6246 MY_JPEG_INVALID_IMAGE_SIZE,
6247 MY_JPEG_CANNOT_CREATE_X
6248 } failure_code;
6252 static _Noreturn void
6253 my_error_exit (j_common_ptr cinfo)
6255 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6256 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6257 sys_longjmp (mgr->setjmp_buffer, 1);
6261 /* Init source method for JPEG data source manager. Called by
6262 jpeg_read_header() before any data is actually read. See
6263 libjpeg.doc from the JPEG lib distribution. */
6265 static void
6266 our_common_init_source (j_decompress_ptr cinfo)
6271 /* Method to terminate data source. Called by
6272 jpeg_finish_decompress() after all data has been processed. */
6274 static void
6275 our_common_term_source (j_decompress_ptr cinfo)
6280 /* Fill input buffer method for JPEG data source manager. Called
6281 whenever more data is needed. We read the whole image in one step,
6282 so this only adds a fake end of input marker at the end. */
6284 static JOCTET our_memory_buffer[2];
6286 static boolean
6287 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6289 /* Insert a fake EOI marker. */
6290 struct jpeg_source_mgr *src = cinfo->src;
6292 our_memory_buffer[0] = (JOCTET) 0xFF;
6293 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6295 src->next_input_byte = our_memory_buffer;
6296 src->bytes_in_buffer = 2;
6297 return 1;
6301 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6302 is the JPEG data source manager. */
6304 static void
6305 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6307 struct jpeg_source_mgr *src = cinfo->src;
6309 if (src)
6311 if (num_bytes > src->bytes_in_buffer)
6312 ERREXIT (cinfo, JERR_INPUT_EOF);
6314 src->bytes_in_buffer -= num_bytes;
6315 src->next_input_byte += num_bytes;
6320 /* Set up the JPEG lib for reading an image from DATA which contains
6321 LEN bytes. CINFO is the decompression info structure created for
6322 reading the image. */
6324 static void
6325 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6327 struct jpeg_source_mgr *src = cinfo->src;
6329 if (! src)
6331 /* First time for this JPEG object? */
6332 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6333 JPOOL_PERMANENT, sizeof *src);
6334 cinfo->src = src;
6335 src->next_input_byte = data;
6338 src->init_source = our_common_init_source;
6339 src->fill_input_buffer = our_memory_fill_input_buffer;
6340 src->skip_input_data = our_memory_skip_input_data;
6341 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6342 src->term_source = our_common_term_source;
6343 src->bytes_in_buffer = len;
6344 src->next_input_byte = data;
6348 struct jpeg_stdio_mgr
6350 struct jpeg_source_mgr mgr;
6351 boolean finished;
6352 FILE *file;
6353 JOCTET *buffer;
6357 /* Size of buffer to read JPEG from file.
6358 Not too big, as we want to use alloc_small. */
6359 #define JPEG_STDIO_BUFFER_SIZE 8192
6362 /* Fill input buffer method for JPEG data source manager. Called
6363 whenever more data is needed. The data is read from a FILE *. */
6365 static boolean
6366 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6368 struct jpeg_stdio_mgr *src;
6370 src = (struct jpeg_stdio_mgr *) cinfo->src;
6371 if (!src->finished)
6373 ptrdiff_t bytes;
6375 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6376 if (bytes > 0)
6377 src->mgr.bytes_in_buffer = bytes;
6378 else
6380 WARNMS (cinfo, JWRN_JPEG_EOF);
6381 src->finished = 1;
6382 src->buffer[0] = (JOCTET) 0xFF;
6383 src->buffer[1] = (JOCTET) JPEG_EOI;
6384 src->mgr.bytes_in_buffer = 2;
6386 src->mgr.next_input_byte = src->buffer;
6389 return 1;
6393 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6394 is the JPEG data source manager. */
6396 static void
6397 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6399 struct jpeg_stdio_mgr *src;
6400 src = (struct jpeg_stdio_mgr *) cinfo->src;
6402 while (num_bytes > 0 && !src->finished)
6404 if (num_bytes <= src->mgr.bytes_in_buffer)
6406 src->mgr.bytes_in_buffer -= num_bytes;
6407 src->mgr.next_input_byte += num_bytes;
6408 break;
6410 else
6412 num_bytes -= src->mgr.bytes_in_buffer;
6413 src->mgr.bytes_in_buffer = 0;
6414 src->mgr.next_input_byte = NULL;
6416 our_stdio_fill_input_buffer (cinfo);
6422 /* Set up the JPEG lib for reading an image from a FILE *.
6423 CINFO is the decompression info structure created for
6424 reading the image. */
6426 static void
6427 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6429 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6431 if (! src)
6433 /* First time for this JPEG object? */
6434 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6435 JPOOL_PERMANENT, sizeof *src);
6436 cinfo->src = (struct jpeg_source_mgr *) src;
6437 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6438 JPOOL_PERMANENT,
6439 JPEG_STDIO_BUFFER_SIZE);
6442 src->file = fp;
6443 src->finished = 0;
6444 src->mgr.init_source = our_common_init_source;
6445 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6446 src->mgr.skip_input_data = our_stdio_skip_input_data;
6447 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6448 src->mgr.term_source = our_common_term_source;
6449 src->mgr.bytes_in_buffer = 0;
6450 src->mgr.next_input_byte = NULL;
6453 /* Load image IMG for use on frame F. Patterned after example.c
6454 from the JPEG lib. */
6456 static bool
6457 jpeg_load_body (struct frame *f, struct image *img,
6458 struct my_jpeg_error_mgr *mgr)
6460 Lisp_Object file, specified_file;
6461 Lisp_Object specified_data;
6462 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6463 FILE * IF_LINT (volatile) fp = NULL;
6464 JSAMPARRAY buffer;
6465 int row_stride, x, y;
6466 XImagePtr ximg = NULL;
6467 unsigned long *colors;
6468 int width, height;
6470 /* Open the JPEG file. */
6471 specified_file = image_spec_value (img->spec, QCfile, NULL);
6472 specified_data = image_spec_value (img->spec, QCdata, NULL);
6473 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
6475 if (NILP (specified_data))
6477 file = x_find_image_file (specified_file);
6478 if (!STRINGP (file))
6480 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6481 return 0;
6484 fp = emacs_fopen (SSDATA (file), "rb");
6485 if (fp == NULL)
6487 image_error ("Cannot open `%s'", file, Qnil);
6488 return 0;
6491 else if (!STRINGP (specified_data))
6493 image_error ("Invalid image data `%s'", specified_data, Qnil);
6494 return 0;
6497 /* Customize libjpeg's error handling to call my_error_exit when an
6498 error is detected. This function will perform a longjmp. */
6499 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6500 mgr->pub.error_exit = my_error_exit;
6501 if (sys_setjmp (mgr->setjmp_buffer))
6503 switch (mgr->failure_code)
6505 case MY_JPEG_ERROR_EXIT:
6507 char buf[JMSG_LENGTH_MAX];
6508 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6509 image_error ("Error reading JPEG image `%s': %s", img->spec,
6510 build_string (buf));
6511 break;
6514 case MY_JPEG_INVALID_IMAGE_SIZE:
6515 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6516 break;
6518 case MY_JPEG_CANNOT_CREATE_X:
6519 break;
6522 /* Close the input file and destroy the JPEG object. */
6523 if (fp)
6524 fclose (fp);
6525 jpeg_destroy_decompress (&mgr->cinfo);
6527 /* If we already have an XImage, free that. */
6528 x_destroy_x_image (ximg);
6530 /* Free pixmap and colors. */
6531 x_clear_image (f, img);
6532 return 0;
6535 /* Silence a bogus diagnostic; see GCC bug 54561. */
6536 IF_LINT (specified_data = specified_data_volatile);
6538 /* Create the JPEG decompression object. Let it read from fp.
6539 Read the JPEG image header. */
6540 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6542 if (NILP (specified_data))
6543 jpeg_file_src (&mgr->cinfo, fp);
6544 else
6545 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6546 SBYTES (specified_data));
6548 jpeg_read_header (&mgr->cinfo, 1);
6550 /* Customize decompression so that color quantization will be used.
6551 Start decompression. */
6552 mgr->cinfo.quantize_colors = 1;
6553 jpeg_start_decompress (&mgr->cinfo);
6554 width = img->width = mgr->cinfo.output_width;
6555 height = img->height = mgr->cinfo.output_height;
6557 if (!check_image_size (f, width, height))
6559 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6560 sys_longjmp (mgr->setjmp_buffer, 1);
6563 /* Create X image and pixmap. */
6564 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6566 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6567 sys_longjmp (mgr->setjmp_buffer, 1);
6570 /* Allocate colors. When color quantization is used,
6571 mgr->cinfo.actual_number_of_colors has been set with the number of
6572 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6573 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6574 No more than 255 colors will be generated. */
6575 USE_SAFE_ALLOCA;
6577 int i, ir, ig, ib;
6579 if (mgr->cinfo.out_color_components > 2)
6580 ir = 0, ig = 1, ib = 2;
6581 else if (mgr->cinfo.out_color_components > 1)
6582 ir = 0, ig = 1, ib = 0;
6583 else
6584 ir = 0, ig = 0, ib = 0;
6586 /* Use the color table mechanism because it handles colors that
6587 cannot be allocated nicely. Such colors will be replaced with
6588 a default color, and we don't have to care about which colors
6589 can be freed safely, and which can't. */
6590 init_color_table ();
6591 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6593 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6595 /* Multiply RGB values with 255 because X expects RGB values
6596 in the range 0..0xffff. */
6597 int r = mgr->cinfo.colormap[ir][i] << 8;
6598 int g = mgr->cinfo.colormap[ig][i] << 8;
6599 int b = mgr->cinfo.colormap[ib][i] << 8;
6600 colors[i] = lookup_rgb_color (f, r, g, b);
6603 #ifdef COLOR_TABLE_SUPPORT
6604 /* Remember those colors actually allocated. */
6605 img->colors = colors_in_color_table (&img->ncolors);
6606 free_color_table ();
6607 #endif /* COLOR_TABLE_SUPPORT */
6610 /* Read pixels. */
6611 row_stride = width * mgr->cinfo.output_components;
6612 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6613 JPOOL_IMAGE, row_stride, 1);
6614 for (y = 0; y < height; ++y)
6616 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6617 for (x = 0; x < mgr->cinfo.output_width; ++x)
6618 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6621 /* Clean up. */
6622 jpeg_finish_decompress (&mgr->cinfo);
6623 jpeg_destroy_decompress (&mgr->cinfo);
6624 if (fp)
6625 fclose (fp);
6627 /* Maybe fill in the background field while we have ximg handy. */
6628 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6629 /* Casting avoids a GCC warning. */
6630 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6632 /* Put ximg into the image. */
6633 image_put_x_image (f, img, ximg, 0);
6634 SAFE_FREE ();
6635 return 1;
6638 static bool
6639 jpeg_load (struct frame *f, struct image *img)
6641 struct my_jpeg_error_mgr mgr;
6642 return jpeg_load_body (f, img, &mgr);
6645 #else /* HAVE_JPEG */
6647 #ifdef HAVE_NS
6648 static bool
6649 jpeg_load (struct frame *f, struct image *img)
6651 return ns_load_image (f, img,
6652 image_spec_value (img->spec, QCfile, NULL),
6653 image_spec_value (img->spec, QCdata, NULL));
6655 #endif /* HAVE_NS */
6657 #endif /* !HAVE_JPEG */
6661 /***********************************************************************
6662 TIFF
6663 ***********************************************************************/
6665 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6667 static bool tiff_image_p (Lisp_Object object);
6668 static bool tiff_load (struct frame *f, struct image *img);
6670 /* Indices of image specification fields in tiff_format, below. */
6672 enum tiff_keyword_index
6674 TIFF_TYPE,
6675 TIFF_DATA,
6676 TIFF_FILE,
6677 TIFF_ASCENT,
6678 TIFF_MARGIN,
6679 TIFF_RELIEF,
6680 TIFF_ALGORITHM,
6681 TIFF_HEURISTIC_MASK,
6682 TIFF_MASK,
6683 TIFF_BACKGROUND,
6684 TIFF_INDEX,
6685 TIFF_LAST
6688 /* Vector of image_keyword structures describing the format
6689 of valid user-defined image specifications. */
6691 static const struct image_keyword tiff_format[TIFF_LAST] =
6693 {":type", IMAGE_SYMBOL_VALUE, 1},
6694 {":data", IMAGE_STRING_VALUE, 0},
6695 {":file", IMAGE_STRING_VALUE, 0},
6696 {":ascent", IMAGE_ASCENT_VALUE, 0},
6697 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6698 {":relief", IMAGE_INTEGER_VALUE, 0},
6699 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6700 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6701 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6702 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6703 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6706 #if defined HAVE_NTGUI && defined WINDOWSNT
6707 static bool init_tiff_functions (void);
6708 #else
6709 #define init_tiff_functions NULL
6710 #endif
6712 /* Structure describing the image type `tiff'. */
6714 static struct image_type tiff_type =
6716 SYMBOL_INDEX (Qtiff),
6717 tiff_image_p,
6718 tiff_load,
6719 x_clear_image,
6720 init_tiff_functions,
6721 NULL
6724 /* Return true if OBJECT is a valid TIFF image specification. */
6726 static bool
6727 tiff_image_p (Lisp_Object object)
6729 struct image_keyword fmt[TIFF_LAST];
6730 memcpy (fmt, tiff_format, sizeof fmt);
6732 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6733 return 0;
6735 /* Must specify either the :data or :file keyword. */
6736 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6739 #endif /* HAVE_TIFF || HAVE_NS */
6741 #ifdef HAVE_TIFF
6743 # include <tiffio.h>
6745 # ifdef WINDOWSNT
6747 /* TIFF library details. */
6748 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6749 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6750 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
6751 DEF_DLL_FN (TIFF *, TIFFClientOpen,
6752 (const char *, const char *, thandle_t, TIFFReadWriteProc,
6753 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6754 TIFFMapFileProc, TIFFUnmapFileProc));
6755 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6756 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6757 DEF_DLL_FN (void, TIFFClose, (TIFF *));
6758 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6760 static bool
6761 init_tiff_functions (void)
6763 HMODULE library;
6765 if (!(library = w32_delayed_load (Qtiff)))
6766 return 0;
6768 LOAD_DLL_FN (library, TIFFSetErrorHandler);
6769 LOAD_DLL_FN (library, TIFFSetWarningHandler);
6770 LOAD_DLL_FN (library, TIFFOpen);
6771 LOAD_DLL_FN (library, TIFFClientOpen);
6772 LOAD_DLL_FN (library, TIFFGetField);
6773 LOAD_DLL_FN (library, TIFFReadRGBAImage);
6774 LOAD_DLL_FN (library, TIFFClose);
6775 LOAD_DLL_FN (library, TIFFSetDirectory);
6776 return 1;
6779 # undef TIFFClientOpen
6780 # undef TIFFClose
6781 # undef TIFFGetField
6782 # undef TIFFOpen
6783 # undef TIFFReadRGBAImage
6784 # undef TIFFSetDirectory
6785 # undef TIFFSetErrorHandler
6786 # undef TIFFSetWarningHandler
6788 # define TIFFClientOpen fn_TIFFClientOpen
6789 # define TIFFClose fn_TIFFClose
6790 # define TIFFGetField fn_TIFFGetField
6791 # define TIFFOpen fn_TIFFOpen
6792 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
6793 # define TIFFSetDirectory fn_TIFFSetDirectory
6794 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
6795 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
6797 # endif /* WINDOWSNT */
6800 /* Reading from a memory buffer for TIFF images Based on the PNG
6801 memory source, but we have to provide a lot of extra functions.
6802 Blah.
6804 We really only need to implement read and seek, but I am not
6805 convinced that the TIFF library is smart enough not to destroy
6806 itself if we only hand it the function pointers we need to
6807 override. */
6809 typedef struct
6811 unsigned char *bytes;
6812 ptrdiff_t len;
6813 ptrdiff_t index;
6815 tiff_memory_source;
6817 static tsize_t
6818 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6820 tiff_memory_source *src = (tiff_memory_source *) data;
6822 size = min (size, src->len - src->index);
6823 memcpy (buf, src->bytes + src->index, size);
6824 src->index += size;
6825 return size;
6828 static tsize_t
6829 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6831 return -1;
6834 static toff_t
6835 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6837 tiff_memory_source *src = (tiff_memory_source *) data;
6838 ptrdiff_t idx;
6840 switch (whence)
6842 case SEEK_SET: /* Go from beginning of source. */
6843 idx = off;
6844 break;
6846 case SEEK_END: /* Go from end of source. */
6847 idx = src->len + off;
6848 break;
6850 case SEEK_CUR: /* Go from current position. */
6851 idx = src->index + off;
6852 break;
6854 default: /* Invalid `whence'. */
6855 return -1;
6858 if (idx > src->len || idx < 0)
6859 return -1;
6861 src->index = idx;
6862 return src->index;
6865 static int
6866 tiff_close_memory (thandle_t data)
6868 /* NOOP */
6869 return 0;
6872 static int
6873 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6875 /* It is already _IN_ memory. */
6876 return 0;
6879 static void
6880 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6882 /* We don't need to do this. */
6885 static toff_t
6886 tiff_size_of_memory (thandle_t data)
6888 return ((tiff_memory_source *) data)->len;
6891 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6892 compiler error compiling tiff_handler, see Bugzilla bug #17406
6893 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6894 this function as external works around that problem. */
6895 # if defined (__MINGW32__) && __GNUC__ == 3
6896 # define MINGW_STATIC
6897 # else
6898 # define MINGW_STATIC static
6899 # endif
6901 MINGW_STATIC void
6902 tiff_handler (const char *, const char *, const char *, va_list)
6903 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6904 MINGW_STATIC void
6905 tiff_handler (const char *log_format, const char *title,
6906 const char *format, va_list ap)
6908 /* doprnt is not suitable here, as TIFF handlers are called from
6909 libtiff and are passed arbitrary printf directives. Instead, use
6910 vsnprintf, taking care to be portable to nonstandard environments
6911 where vsnprintf returns -1 on buffer overflow. Since it's just a
6912 log entry, it's OK to truncate it. */
6913 char buf[4000];
6914 int len = vsnprintf (buf, sizeof buf, format, ap);
6915 add_to_log (log_format, build_string (title),
6916 make_string (buf, max (0, min (len, sizeof buf - 1))));
6918 # undef MINGW_STATIC
6920 static void tiff_error_handler (const char *, const char *, va_list)
6921 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6922 static void
6923 tiff_error_handler (const char *title, const char *format, va_list ap)
6925 tiff_handler ("TIFF error: %s %s", title, format, ap);
6929 static void tiff_warning_handler (const char *, const char *, va_list)
6930 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6931 static void
6932 tiff_warning_handler (const char *title, const char *format, va_list ap)
6934 tiff_handler ("TIFF warning: %s %s", title, format, ap);
6938 /* Load TIFF image IMG for use on frame F. Value is true if
6939 successful. */
6941 static bool
6942 tiff_load (struct frame *f, struct image *img)
6944 Lisp_Object file, specified_file;
6945 Lisp_Object specified_data;
6946 TIFF *tiff;
6947 int width, height, x, y, count;
6948 uint32 *buf;
6949 int rc;
6950 XImagePtr ximg;
6951 tiff_memory_source memsrc;
6952 Lisp_Object image;
6954 specified_file = image_spec_value (img->spec, QCfile, NULL);
6955 specified_data = image_spec_value (img->spec, QCdata, NULL);
6957 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6958 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
6960 if (NILP (specified_data))
6962 /* Read from a file */
6963 file = x_find_image_file (specified_file);
6964 if (!STRINGP (file))
6966 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6967 return 0;
6969 # ifdef WINDOWSNT
6970 file = ansi_encode_filename (file);
6971 # endif
6973 /* Try to open the image file. */
6974 tiff = TIFFOpen (SSDATA (file), "r");
6975 if (tiff == NULL)
6977 image_error ("Cannot open `%s'", file, Qnil);
6978 return 0;
6981 else
6983 if (!STRINGP (specified_data))
6985 image_error ("Invalid image data `%s'", specified_data, Qnil);
6986 return 0;
6989 /* Memory source! */
6990 memsrc.bytes = SDATA (specified_data);
6991 memsrc.len = SBYTES (specified_data);
6992 memsrc.index = 0;
6994 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
6995 tiff_read_from_memory,
6996 tiff_write_from_memory,
6997 tiff_seek_in_memory,
6998 tiff_close_memory,
6999 tiff_size_of_memory,
7000 tiff_mmap_memory,
7001 tiff_unmap_memory);
7003 if (!tiff)
7005 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7006 return 0;
7010 image = image_spec_value (img->spec, QCindex, NULL);
7011 if (INTEGERP (image))
7013 EMACS_INT ino = XFASTINT (image);
7014 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7015 && TIFFSetDirectory (tiff, ino)))
7017 image_error ("Invalid image number `%s' in image `%s'",
7018 image, img->spec);
7019 TIFFClose (tiff);
7020 return 0;
7024 /* Get width and height of the image, and allocate a raster buffer
7025 of width x height 32-bit values. */
7026 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7027 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7029 if (!check_image_size (f, width, height))
7031 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7032 TIFFClose (tiff);
7033 return 0;
7036 /* Create the X image and pixmap. */
7037 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7038 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7039 &ximg, 0)))
7041 TIFFClose (tiff);
7042 return 0;
7045 buf = xmalloc (sizeof *buf * width * height);
7047 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7049 /* Count the number of images in the file. */
7050 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7051 continue;
7053 if (count > 1)
7054 img->lisp_data = Fcons (Qcount,
7055 Fcons (make_number (count),
7056 img->lisp_data));
7058 TIFFClose (tiff);
7059 if (!rc)
7061 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7062 xfree (buf);
7063 return 0;
7066 /* Initialize the color table. */
7067 init_color_table ();
7069 /* Process the pixel raster. Origin is in the lower-left corner. */
7070 for (y = 0; y < height; ++y)
7072 uint32 *row = buf + y * width;
7074 for (x = 0; x < width; ++x)
7076 uint32 abgr = row[x];
7077 int r = TIFFGetR (abgr) << 8;
7078 int g = TIFFGetG (abgr) << 8;
7079 int b = TIFFGetB (abgr) << 8;
7080 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7084 # ifdef COLOR_TABLE_SUPPORT
7085 /* Remember the colors allocated for the image. Free the color table. */
7086 img->colors = colors_in_color_table (&img->ncolors);
7087 free_color_table ();
7088 # endif /* COLOR_TABLE_SUPPORT */
7090 img->width = width;
7091 img->height = height;
7093 /* Maybe fill in the background field while we have ximg handy. */
7094 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7095 /* Casting avoids a GCC warning on W32. */
7096 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7098 /* Put ximg into the image. */
7099 image_put_x_image (f, img, ximg, 0);
7100 xfree (buf);
7102 return 1;
7105 #elif defined HAVE_NS
7107 static bool
7108 tiff_load (struct frame *f, struct image *img)
7110 return ns_load_image (f, img,
7111 image_spec_value (img->spec, QCfile, NULL),
7112 image_spec_value (img->spec, QCdata, NULL));
7115 #endif
7119 /***********************************************************************
7121 ***********************************************************************/
7123 #if defined (HAVE_GIF) || defined (HAVE_NS)
7125 static bool gif_image_p (Lisp_Object object);
7126 static bool gif_load (struct frame *f, struct image *img);
7127 static void gif_clear_image (struct frame *f, struct image *img);
7129 /* Indices of image specification fields in gif_format, below. */
7131 enum gif_keyword_index
7133 GIF_TYPE,
7134 GIF_DATA,
7135 GIF_FILE,
7136 GIF_ASCENT,
7137 GIF_MARGIN,
7138 GIF_RELIEF,
7139 GIF_ALGORITHM,
7140 GIF_HEURISTIC_MASK,
7141 GIF_MASK,
7142 GIF_IMAGE,
7143 GIF_BACKGROUND,
7144 GIF_LAST
7147 /* Vector of image_keyword structures describing the format
7148 of valid user-defined image specifications. */
7150 static const struct image_keyword gif_format[GIF_LAST] =
7152 {":type", IMAGE_SYMBOL_VALUE, 1},
7153 {":data", IMAGE_STRING_VALUE, 0},
7154 {":file", IMAGE_STRING_VALUE, 0},
7155 {":ascent", IMAGE_ASCENT_VALUE, 0},
7156 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7157 {":relief", IMAGE_INTEGER_VALUE, 0},
7158 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7159 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7160 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7161 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7162 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7165 #if defined HAVE_NTGUI && defined WINDOWSNT
7166 static bool init_gif_functions (void);
7167 #else
7168 #define init_gif_functions NULL
7169 #endif
7171 /* Structure describing the image type `gif'. */
7173 static struct image_type gif_type =
7175 SYMBOL_INDEX (Qgif),
7176 gif_image_p,
7177 gif_load,
7178 gif_clear_image,
7179 init_gif_functions,
7180 NULL
7183 /* Free X resources of GIF image IMG which is used on frame F. */
7185 static void
7186 gif_clear_image (struct frame *f, struct image *img)
7188 img->lisp_data = Qnil;
7189 x_clear_image (f, img);
7192 /* Return true if OBJECT is a valid GIF image specification. */
7194 static bool
7195 gif_image_p (Lisp_Object object)
7197 struct image_keyword fmt[GIF_LAST];
7198 memcpy (fmt, gif_format, sizeof fmt);
7200 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7201 return 0;
7203 /* Must specify either the :data or :file keyword. */
7204 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7207 #endif /* HAVE_GIF */
7209 #ifdef HAVE_GIF
7211 # ifdef HAVE_NTGUI
7213 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7214 Undefine before redefining to avoid a preprocessor warning. */
7215 # ifdef DrawText
7216 # undef DrawText
7217 # endif
7218 /* avoid conflict with QuickdrawText.h */
7219 # define DrawText gif_DrawText
7220 # include <gif_lib.h>
7221 # undef DrawText
7223 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7224 # ifndef GIFLIB_MINOR
7225 # define GIFLIB_MINOR 0
7226 # endif
7227 # ifndef GIFLIB_RELEASE
7228 # define GIFLIB_RELEASE 0
7229 # endif
7231 # else /* HAVE_NTGUI */
7233 # include <gif_lib.h>
7235 # endif /* HAVE_NTGUI */
7237 /* Giflib before 5.0 didn't define these macros. */
7238 # ifndef GIFLIB_MAJOR
7239 # define GIFLIB_MAJOR 4
7240 # endif
7242 # ifdef WINDOWSNT
7244 /* GIF library details. */
7245 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7246 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7247 # else
7248 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7249 # endif
7250 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7251 # if GIFLIB_MAJOR < 5
7252 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7253 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7254 # else
7255 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7256 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7257 DEF_DLL_FN (char *, GifErrorString, (int));
7258 # endif
7260 static bool
7261 init_gif_functions (void)
7263 HMODULE library;
7265 if (!(library = w32_delayed_load (Qgif)))
7266 return 0;
7268 LOAD_DLL_FN (library, DGifCloseFile);
7269 LOAD_DLL_FN (library, DGifSlurp);
7270 LOAD_DLL_FN (library, DGifOpen);
7271 LOAD_DLL_FN (library, DGifOpenFileName);
7272 # if GIFLIB_MAJOR >= 5
7273 LOAD_DLL_FN (library, GifErrorString);
7274 # endif
7275 return 1;
7278 # undef DGifCloseFile
7279 # undef DGifOpen
7280 # undef DGifOpenFileName
7281 # undef DGifSlurp
7282 # undef GifErrorString
7284 # define DGifCloseFile fn_DGifCloseFile
7285 # define DGifOpen fn_DGifOpen
7286 # define DGifOpenFileName fn_DGifOpenFileName
7287 # define DGifSlurp fn_DGifSlurp
7288 # define GifErrorString fn_GifErrorString
7290 # endif /* WINDOWSNT */
7292 /* Reading a GIF image from memory
7293 Based on the PNG memory stuff to a certain extent. */
7295 typedef struct
7297 unsigned char *bytes;
7298 ptrdiff_t len;
7299 ptrdiff_t index;
7301 gif_memory_source;
7303 /* Make the current memory source available to gif_read_from_memory.
7304 It's done this way because not all versions of libungif support
7305 a UserData field in the GifFileType structure. */
7306 static gif_memory_source *current_gif_memory_src;
7308 static int
7309 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7311 gif_memory_source *src = current_gif_memory_src;
7313 if (len > src->len - src->index)
7314 return -1;
7316 memcpy (buf, src->bytes + src->index, len);
7317 src->index += len;
7318 return len;
7321 static int
7322 gif_close (GifFileType *gif, int *err)
7324 int retval;
7326 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7327 retval = DGifCloseFile (gif, err);
7328 #else
7329 retval = DGifCloseFile (gif);
7330 #if GIFLIB_MAJOR >= 5
7331 if (err)
7332 *err = gif->Error;
7333 #endif
7334 #endif
7335 return retval;
7338 /* Load GIF image IMG for use on frame F. Value is true if
7339 successful. */
7341 static const int interlace_start[] = {0, 4, 2, 1};
7342 static const int interlace_increment[] = {8, 8, 4, 2};
7344 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7346 static bool
7347 gif_load (struct frame *f, struct image *img)
7349 Lisp_Object file;
7350 int rc, width, height, x, y, i, j;
7351 XImagePtr ximg;
7352 ColorMapObject *gif_color_map;
7353 unsigned long pixel_colors[256];
7354 GifFileType *gif;
7355 gif_memory_source memsrc;
7356 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7357 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7358 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7359 unsigned long bgcolor = 0;
7360 EMACS_INT idx;
7361 int gif_err;
7363 if (NILP (specified_data))
7365 file = x_find_image_file (specified_file);
7366 if (!STRINGP (file))
7368 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7369 return 0;
7371 #ifdef WINDOWSNT
7372 file = ansi_encode_filename (file);
7373 #endif
7375 /* Open the GIF file. */
7376 #if GIFLIB_MAJOR < 5
7377 gif = DGifOpenFileName (SSDATA (file));
7378 if (gif == NULL)
7380 image_error ("Cannot open `%s'", file, Qnil);
7381 return 0;
7383 #else
7384 gif = DGifOpenFileName (SSDATA (file), &gif_err);
7385 if (gif == NULL)
7387 image_error ("Cannot open `%s': %s",
7388 file, build_string (GifErrorString (gif_err)));
7389 return 0;
7391 #endif
7393 else
7395 if (!STRINGP (specified_data))
7397 image_error ("Invalid image data `%s'", specified_data, Qnil);
7398 return 0;
7401 /* Read from memory! */
7402 current_gif_memory_src = &memsrc;
7403 memsrc.bytes = SDATA (specified_data);
7404 memsrc.len = SBYTES (specified_data);
7405 memsrc.index = 0;
7407 #if GIFLIB_MAJOR < 5
7408 gif = DGifOpen (&memsrc, gif_read_from_memory);
7409 if (!gif)
7411 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7412 return 0;
7414 #else
7415 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7416 if (!gif)
7418 image_error ("Cannot open memory source `%s': %s",
7419 img->spec, build_string (GifErrorString (gif_err)));
7420 return 0;
7422 #endif
7425 /* Before reading entire contents, check the declared image size. */
7426 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7428 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7429 gif_close (gif, NULL);
7430 return 0;
7433 /* Read entire contents. */
7434 rc = DGifSlurp (gif);
7435 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7437 image_error ("Error reading `%s'", img->spec, Qnil);
7438 gif_close (gif, NULL);
7439 return 0;
7442 /* Which sub-image are we to display? */
7444 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7445 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7446 if (idx < 0 || idx >= gif->ImageCount)
7448 image_error ("Invalid image number `%s' in image `%s'",
7449 image_number, img->spec);
7450 gif_close (gif, NULL);
7451 return 0;
7455 width = img->width = gif->SWidth;
7456 height = img->height = gif->SHeight;
7458 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7459 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7460 img->corners[BOT_CORNER]
7461 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7462 img->corners[RIGHT_CORNER]
7463 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7465 if (!check_image_size (f, width, height))
7467 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7468 gif_close (gif, NULL);
7469 return 0;
7472 /* Check that the selected subimages fit. It's not clear whether
7473 the GIF spec requires this, but Emacs can crash if they don't fit. */
7474 for (j = 0; j <= idx; ++j)
7476 struct SavedImage *subimage = gif->SavedImages + j;
7477 int subimg_width = subimage->ImageDesc.Width;
7478 int subimg_height = subimage->ImageDesc.Height;
7479 int subimg_top = subimage->ImageDesc.Top;
7480 int subimg_left = subimage->ImageDesc.Left;
7481 if (! (subimg_width >= 0 && subimg_height >= 0
7482 && 0 <= subimg_top && subimg_top <= height - subimg_height
7483 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7485 image_error ("Subimage does not fit in image", Qnil, Qnil);
7486 gif_close (gif, NULL);
7487 return 0;
7491 /* Create the X image and pixmap. */
7492 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7494 gif_close (gif, NULL);
7495 return 0;
7498 /* Clear the part of the screen image not covered by the image.
7499 Full animated GIF support requires more here (see the gif89 spec,
7500 disposal methods). Let's simply assume that the part not covered
7501 by a sub-image is in the frame's background color. */
7502 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7503 for (x = 0; x < width; ++x)
7504 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7506 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7507 for (x = 0; x < width; ++x)
7508 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7510 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7512 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7513 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7514 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7515 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7518 /* Read the GIF image into the X image. */
7520 /* FIXME: With the current implementation, loading an animated gif
7521 is quadratic in the number of animation frames, since each frame
7522 is a separate struct image. We must provide a way for a single
7523 gif_load call to construct and save all animation frames. */
7525 init_color_table ();
7526 if (STRINGP (specified_bg))
7527 bgcolor = x_alloc_image_color (f, img, specified_bg,
7528 FRAME_BACKGROUND_PIXEL (f));
7529 for (j = 0; j <= idx; ++j)
7531 /* We use a local variable `raster' here because RasterBits is a
7532 char *, which invites problems with bytes >= 0x80. */
7533 struct SavedImage *subimage = gif->SavedImages + j;
7534 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7535 int transparency_color_index = -1;
7536 int disposal = 0;
7537 int subimg_width = subimage->ImageDesc.Width;
7538 int subimg_height = subimage->ImageDesc.Height;
7539 int subimg_top = subimage->ImageDesc.Top;
7540 int subimg_left = subimage->ImageDesc.Left;
7542 /* Find the Graphic Control Extension block for this sub-image.
7543 Extract the disposal method and transparency color. */
7544 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7546 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7548 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7549 && extblock->ByteCount == 4
7550 && extblock->Bytes[0] & 1)
7552 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7553 to background". Treat any other value like 2. */
7554 disposal = (extblock->Bytes[0] >> 2) & 7;
7555 transparency_color_index = (unsigned char) extblock->Bytes[3];
7556 break;
7560 /* We can't "keep in place" the first subimage. */
7561 if (j == 0)
7562 disposal = 2;
7564 /* For disposal == 0, the spec says "No disposal specified. The
7565 decoder is not required to take any action." In practice, it
7566 seems we need to treat this like "keep in place", see e.g.
7567 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7568 if (disposal == 0)
7569 disposal = 1;
7571 /* Allocate subimage colors. */
7572 memset (pixel_colors, 0, sizeof pixel_colors);
7573 gif_color_map = subimage->ImageDesc.ColorMap;
7574 if (!gif_color_map)
7575 gif_color_map = gif->SColorMap;
7577 if (gif_color_map)
7578 for (i = 0; i < gif_color_map->ColorCount; ++i)
7580 if (transparency_color_index == i)
7581 pixel_colors[i] = STRINGP (specified_bg)
7582 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7583 else
7585 int r = gif_color_map->Colors[i].Red << 8;
7586 int g = gif_color_map->Colors[i].Green << 8;
7587 int b = gif_color_map->Colors[i].Blue << 8;
7588 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7592 /* Apply the pixel values. */
7593 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7595 int row, pass;
7597 for (y = 0, row = interlace_start[0], pass = 0;
7598 y < subimg_height;
7599 y++, row += interlace_increment[pass])
7601 while (subimg_height <= row)
7602 row = interlace_start[++pass];
7604 for (x = 0; x < subimg_width; x++)
7606 int c = raster[y * subimg_width + x];
7607 if (transparency_color_index != c || disposal != 1)
7608 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7609 pixel_colors[c]);
7613 else
7615 for (y = 0; y < subimg_height; ++y)
7616 for (x = 0; x < subimg_width; ++x)
7618 int c = raster[y * subimg_width + x];
7619 if (transparency_color_index != c || disposal != 1)
7620 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7621 pixel_colors[c]);
7626 #ifdef COLOR_TABLE_SUPPORT
7627 img->colors = colors_in_color_table (&img->ncolors);
7628 free_color_table ();
7629 #endif /* COLOR_TABLE_SUPPORT */
7631 /* Save GIF image extension data for `image-metadata'.
7632 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7633 img->lisp_data = Qnil;
7634 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7636 int delay = 0;
7637 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7638 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7639 /* Append (... FUNCTION "BYTES") */
7641 img->lisp_data
7642 = Fcons (make_number (ext->Function),
7643 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7644 img->lisp_data));
7645 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7646 && ext->ByteCount == 4)
7648 delay = ext->Bytes[2] << CHAR_BIT;
7649 delay |= ext->Bytes[1];
7652 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7653 if (delay)
7654 img->lisp_data
7655 = Fcons (Qdelay,
7656 Fcons (make_float (delay / 100.0),
7657 img->lisp_data));
7660 if (gif->ImageCount > 1)
7661 img->lisp_data = Fcons (Qcount,
7662 Fcons (make_number (gif->ImageCount),
7663 img->lisp_data));
7665 if (gif_close (gif, &gif_err) == GIF_ERROR)
7667 #if 5 <= GIFLIB_MAJOR
7668 char *error_text = GifErrorString (gif_err);
7670 if (error_text)
7671 image_error ("Error closing `%s': %s",
7672 img->spec, build_string (error_text));
7673 #else
7674 image_error ("Error closing `%s'", img->spec, Qnil);
7675 #endif
7678 /* Maybe fill in the background field while we have ximg handy. */
7679 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7680 /* Casting avoids a GCC warning. */
7681 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7683 /* Put ximg into the image. */
7684 image_put_x_image (f, img, ximg, 0);
7686 return 1;
7689 #else /* !HAVE_GIF */
7691 #ifdef HAVE_NS
7692 static bool
7693 gif_load (struct frame *f, struct image *img)
7695 return ns_load_image (f, img,
7696 image_spec_value (img->spec, QCfile, NULL),
7697 image_spec_value (img->spec, QCdata, NULL));
7699 #endif /* HAVE_NS */
7701 #endif /* HAVE_GIF */
7704 #ifdef HAVE_IMAGEMAGICK
7706 /***********************************************************************
7707 ImageMagick
7708 ***********************************************************************/
7710 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
7711 safely rounded and clipped to int range. */
7713 static int
7714 scale_image_size (int size, size_t divisor, size_t multiplier)
7716 if (divisor != 0)
7718 double s = size;
7719 double scaled = s * multiplier / divisor + 0.5;
7720 if (scaled < INT_MAX)
7721 return scaled;
7723 return INT_MAX;
7726 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
7727 Use SPEC to deduce the size. Store the desired size into
7728 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
7729 static void
7730 compute_image_size (size_t width, size_t height,
7731 Lisp_Object spec,
7732 int *d_width, int *d_height)
7734 Lisp_Object value;
7735 int desired_width, desired_height;
7737 /* If width and/or height is set in the display spec assume we want
7738 to scale to those values. If either h or w is unspecified, the
7739 unspecified should be calculated from the specified to preserve
7740 aspect ratio. */
7741 value = image_spec_value (spec, QCwidth, NULL);
7742 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7743 value = image_spec_value (spec, QCheight, NULL);
7744 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7746 if (desired_width == -1)
7748 value = image_spec_value (spec, QCmax_width, NULL);
7749 if (NATNUMP (value))
7751 int max_width = min (XFASTINT (value), INT_MAX);
7752 if (max_width < width)
7754 /* The image is wider than :max-width. */
7755 desired_width = max_width;
7756 if (desired_height == -1)
7758 desired_height = scale_image_size (desired_width,
7759 width, height);
7760 value = image_spec_value (spec, QCmax_height, NULL);
7761 if (NATNUMP (value))
7763 int max_height = min (XFASTINT (value), INT_MAX);
7764 if (max_height < desired_height)
7766 desired_height = max_height;
7767 desired_width = scale_image_size (desired_height,
7768 height, width);
7776 if (desired_height == -1)
7778 value = image_spec_value (spec, QCmax_height, NULL);
7779 if (NATNUMP (value))
7781 int max_height = min (XFASTINT (value), INT_MAX);
7782 if (max_height < height)
7783 desired_height = max_height;
7787 if (desired_width != -1 && desired_height == -1)
7788 /* w known, calculate h. */
7789 desired_height = scale_image_size (desired_width, width, height);
7791 if (desired_width == -1 && desired_height != -1)
7792 /* h known, calculate w. */
7793 desired_width = scale_image_size (desired_height, height, width);
7795 *d_width = desired_width;
7796 *d_height = desired_height;
7799 static bool imagemagick_image_p (Lisp_Object);
7800 static bool imagemagick_load (struct frame *, struct image *);
7801 static void imagemagick_clear_image (struct frame *, struct image *);
7803 /* Indices of image specification fields in imagemagick_format. */
7805 enum imagemagick_keyword_index
7807 IMAGEMAGICK_TYPE,
7808 IMAGEMAGICK_DATA,
7809 IMAGEMAGICK_FILE,
7810 IMAGEMAGICK_ASCENT,
7811 IMAGEMAGICK_MARGIN,
7812 IMAGEMAGICK_RELIEF,
7813 IMAGEMAGICK_ALGORITHM,
7814 IMAGEMAGICK_HEURISTIC_MASK,
7815 IMAGEMAGICK_MASK,
7816 IMAGEMAGICK_BACKGROUND,
7817 IMAGEMAGICK_HEIGHT,
7818 IMAGEMAGICK_WIDTH,
7819 IMAGEMAGICK_MAX_HEIGHT,
7820 IMAGEMAGICK_MAX_WIDTH,
7821 IMAGEMAGICK_FORMAT,
7822 IMAGEMAGICK_ROTATION,
7823 IMAGEMAGICK_CROP,
7824 IMAGEMAGICK_LAST
7827 /* Vector of image_keyword structures describing the format
7828 of valid user-defined image specifications. */
7830 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7832 {":type", IMAGE_SYMBOL_VALUE, 1},
7833 {":data", IMAGE_STRING_VALUE, 0},
7834 {":file", IMAGE_STRING_VALUE, 0},
7835 {":ascent", IMAGE_ASCENT_VALUE, 0},
7836 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7837 {":relief", IMAGE_INTEGER_VALUE, 0},
7838 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7839 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7840 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7841 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7842 {":height", IMAGE_INTEGER_VALUE, 0},
7843 {":width", IMAGE_INTEGER_VALUE, 0},
7844 {":max-height", IMAGE_INTEGER_VALUE, 0},
7845 {":max-width", IMAGE_INTEGER_VALUE, 0},
7846 {":format", IMAGE_SYMBOL_VALUE, 0},
7847 {":rotation", IMAGE_NUMBER_VALUE, 0},
7848 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7851 #if defined HAVE_NTGUI && defined WINDOWSNT
7852 static bool init_imagemagick_functions (void);
7853 #else
7854 #define init_imagemagick_functions NULL
7855 #endif
7857 /* Structure describing the image type for any image handled via
7858 ImageMagick. */
7860 static struct image_type imagemagick_type =
7862 SYMBOL_INDEX (Qimagemagick),
7863 imagemagick_image_p,
7864 imagemagick_load,
7865 imagemagick_clear_image,
7866 init_imagemagick_functions,
7867 NULL
7870 /* Free X resources of imagemagick image IMG which is used on frame F. */
7872 static void
7873 imagemagick_clear_image (struct frame *f,
7874 struct image *img)
7876 x_clear_image (f, img);
7879 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7880 this by calling parse_image_spec and supplying the keywords that
7881 identify the IMAGEMAGICK format. */
7883 static bool
7884 imagemagick_image_p (Lisp_Object object)
7886 struct image_keyword fmt[IMAGEMAGICK_LAST];
7887 memcpy (fmt, imagemagick_format, sizeof fmt);
7889 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7890 return 0;
7892 /* Must specify either the :data or :file keyword. */
7893 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7896 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7897 Therefore rename the function so it doesn't collide with ImageMagick. */
7898 #define DrawRectangle DrawRectangleGif
7899 #include <wand/MagickWand.h>
7901 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7902 Emacs seems to work fine with the hidden version, so unhide it. */
7903 #include <magick/version.h>
7904 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7905 extern WandExport void PixelGetMagickColor (const PixelWand *,
7906 MagickPixelPacket *);
7907 #endif
7909 /* Log ImageMagick error message.
7910 Useful when a ImageMagick function returns the status `MagickFalse'. */
7912 static void
7913 imagemagick_error (MagickWand *wand)
7915 char *description;
7916 ExceptionType severity;
7918 description = MagickGetException (wand, &severity);
7919 image_error ("ImageMagick error: %s",
7920 build_string (description),
7921 Qnil);
7922 MagickRelinquishMemory (description);
7925 /* Possibly give ImageMagick some extra help to determine the image
7926 type by supplying a "dummy" filename based on the Content-Type. */
7928 static char *
7929 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
7931 Lisp_Object symbol = intern ("image-format-suffixes");
7932 Lisp_Object val = find_symbol_value (symbol);
7933 Lisp_Object format;
7935 if (! CONSP (val))
7936 return NULL;
7938 format = image_spec_value (spec, intern (":format"), NULL);
7939 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
7940 if (! STRINGP (val))
7941 return NULL;
7943 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
7944 as ImageMagick would ignore the extra bytes anyway. */
7945 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
7946 return hint_buffer;
7949 /* Animated images (e.g., GIF89a) are composed from one "master image"
7950 (which is the first one, and then there's a number of images that
7951 follow. If following images have non-transparent colors, these are
7952 composed "on top" of the master image. So, in general, one has to
7953 compute ann the preceding images to be able to display a particular
7954 sub-image.
7956 Computing all the preceding images is too slow, so we maintain a
7957 cache of previously computed images. We have to maintain a cache
7958 separate from the image cache, because the images may be scaled
7959 before display. */
7961 struct animation_cache
7963 MagickWand *wand;
7964 int index;
7965 struct timespec update_time;
7966 struct animation_cache *next;
7967 char signature[FLEXIBLE_ARRAY_MEMBER];
7970 static struct animation_cache *animation_cache = NULL;
7972 static struct animation_cache *
7973 imagemagick_create_cache (char *signature)
7975 struct animation_cache *cache
7976 = xmalloc (offsetof (struct animation_cache, signature)
7977 + strlen (signature) + 1);
7978 cache->wand = 0;
7979 cache->index = 0;
7980 cache->next = 0;
7981 strcpy (cache->signature, signature);
7982 return cache;
7985 /* Discard cached images that haven't been used for a minute. */
7986 static void
7987 imagemagick_prune_animation_cache (void)
7989 struct animation_cache **pcache = &animation_cache;
7990 struct timespec old = timespec_sub (current_timespec (),
7991 make_timespec (60, 0));
7993 while (*pcache)
7995 struct animation_cache *cache = *pcache;
7996 if (timespec_cmp (old, cache->update_time) <= 0)
7997 pcache = &cache->next;
7998 else
8000 if (cache->wand)
8001 DestroyMagickWand (cache->wand);
8002 *pcache = cache->next;
8003 xfree (cache);
8008 static struct animation_cache *
8009 imagemagick_get_animation_cache (MagickWand *wand)
8011 char *signature = MagickGetImageSignature (wand);
8012 struct animation_cache *cache;
8013 struct animation_cache **pcache = &animation_cache;
8015 imagemagick_prune_animation_cache ();
8017 while (1)
8019 cache = *pcache;
8020 if (! cache)
8022 *pcache = cache = imagemagick_create_cache (signature);
8023 break;
8025 if (strcmp (signature, cache->signature) == 0)
8026 break;
8027 pcache = &cache->next;
8030 DestroyString (signature);
8031 cache->update_time = current_timespec ();
8032 return cache;
8035 static MagickWand *
8036 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8038 int i;
8039 MagickWand *composite_wand;
8040 size_t dest_width, dest_height;
8041 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8043 MagickSetIteratorIndex (super_wand, 0);
8045 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8047 composite_wand = MagickGetImage (super_wand);
8048 if (cache->wand)
8049 DestroyMagickWand (cache->wand);
8051 else
8052 composite_wand = cache->wand;
8054 dest_height = MagickGetImageHeight (composite_wand);
8056 for (i = max (1, cache->index + 1); i <= ino; i++)
8058 MagickWand *sub_wand;
8059 PixelIterator *source_iterator, *dest_iterator;
8060 PixelWand **source, **dest;
8061 size_t source_width, source_height;
8062 ssize_t source_left, source_top;
8063 MagickPixelPacket pixel;
8064 DisposeType dispose;
8065 ptrdiff_t lines = 0;
8067 MagickSetIteratorIndex (super_wand, i);
8068 sub_wand = MagickGetImage (super_wand);
8070 MagickGetImagePage (sub_wand, &source_width, &source_height,
8071 &source_left, &source_top);
8073 /* This flag says how to handle transparent pixels. */
8074 dispose = MagickGetImageDispose (sub_wand);
8076 source_iterator = NewPixelIterator (sub_wand);
8077 if (! source_iterator)
8079 DestroyMagickWand (composite_wand);
8080 DestroyMagickWand (sub_wand);
8081 cache->wand = NULL;
8082 image_error ("Imagemagick pixel iterator creation failed",
8083 Qnil, Qnil);
8084 return NULL;
8087 dest_iterator = NewPixelIterator (composite_wand);
8088 if (! dest_iterator)
8090 DestroyMagickWand (composite_wand);
8091 DestroyMagickWand (sub_wand);
8092 DestroyPixelIterator (source_iterator);
8093 cache->wand = NULL;
8094 image_error ("Imagemagick pixel iterator creation failed",
8095 Qnil, Qnil);
8096 return NULL;
8099 /* The sub-image may not start at origin, so move the destination
8100 iterator to where the sub-image should start. */
8101 if (source_top > 0)
8103 PixelSetIteratorRow (dest_iterator, source_top);
8104 lines = source_top;
8107 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8108 != NULL)
8110 ptrdiff_t x;
8112 /* Sanity check. This shouldn't happen, but apparently
8113 does in some pictures. */
8114 if (++lines >= dest_height)
8115 break;
8117 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8118 for (x = 0; x < source_width; x++)
8120 /* Sanity check. This shouldn't happen, but apparently
8121 also does in some pictures. */
8122 if (x + source_left >= dest_width)
8123 break;
8124 /* Normally we only copy over non-transparent pixels,
8125 but if the disposal method is "Background", then we
8126 copy over all pixels. */
8127 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8129 PixelGetMagickColor (source[x], &pixel);
8130 PixelSetMagickColor (dest[x + source_left], &pixel);
8133 PixelSyncIterator (dest_iterator);
8136 DestroyPixelIterator (source_iterator);
8137 DestroyPixelIterator (dest_iterator);
8138 DestroyMagickWand (sub_wand);
8141 /* Cache a copy for the next iteration. The current wand will be
8142 destroyed by the caller. */
8143 cache->wand = CloneMagickWand (composite_wand);
8144 cache->index = ino;
8146 return composite_wand;
8150 /* Helper function for imagemagick_load, which does the actual loading
8151 given contents and size, apart from frame and image structures,
8152 passed from imagemagick_load. Uses librimagemagick to do most of
8153 the image processing.
8155 F is a pointer to the Emacs frame; IMG to the image structure to
8156 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8157 be parsed; SIZE is the number of bytes of data; and FILENAME is
8158 either the file name or the image data.
8160 Return true if successful. */
8162 static bool
8163 imagemagick_load_image (struct frame *f, struct image *img,
8164 unsigned char *contents, unsigned int size,
8165 char *filename)
8167 int width, height;
8168 size_t image_width, image_height;
8169 MagickBooleanType status;
8170 XImagePtr ximg;
8171 int x, y;
8172 MagickWand *image_wand;
8173 PixelIterator *iterator;
8174 PixelWand **pixels, *bg_wand = NULL;
8175 MagickPixelPacket pixel;
8176 Lisp_Object image;
8177 Lisp_Object value;
8178 Lisp_Object crop;
8179 EMACS_INT ino;
8180 int desired_width, desired_height;
8181 double rotation;
8182 int pixelwidth;
8183 char hint_buffer[MaxTextExtent];
8184 char *filename_hint = NULL;
8186 /* Handle image index for image types who can contain more than one image.
8187 Interface :index is same as for GIF. First we "ping" the image to see how
8188 many sub-images it contains. Pinging is faster than loading the image to
8189 find out things about it. */
8191 /* Initialize the imagemagick environment. */
8192 MagickWandGenesis ();
8193 image = image_spec_value (img->spec, QCindex, NULL);
8194 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8195 image_wand = NewMagickWand ();
8197 if (filename)
8198 status = MagickReadImage (image_wand, filename);
8199 else
8201 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8202 MagickSetFilename (image_wand, filename_hint);
8203 status = MagickReadImageBlob (image_wand, contents, size);
8206 if (status == MagickFalse)
8208 imagemagick_error (image_wand);
8209 DestroyMagickWand (image_wand);
8210 return 0;
8213 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8215 image_error ("Invalid image number `%s' in image `%s'",
8216 image, img->spec);
8217 DestroyMagickWand (image_wand);
8218 return 0;
8221 if (MagickGetImageDelay (image_wand) > 0)
8222 img->lisp_data =
8223 Fcons (Qdelay,
8224 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8225 img->lisp_data));
8227 if (MagickGetNumberImages (image_wand) > 1)
8228 img->lisp_data =
8229 Fcons (Qcount,
8230 Fcons (make_number (MagickGetNumberImages (image_wand)),
8231 img->lisp_data));
8233 /* If we have an animated image, get the new wand based on the
8234 "super-wand". */
8235 if (MagickGetNumberImages (image_wand) > 1)
8237 MagickWand *super_wand = image_wand;
8238 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8239 if (! image_wand)
8240 image_wand = super_wand;
8241 else
8242 DestroyMagickWand (super_wand);
8245 /* Retrieve the frame's background color, for use later. */
8247 XColor bgcolor;
8248 Lisp_Object specified_bg;
8250 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8251 if (!STRINGP (specified_bg)
8252 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8253 x_query_frame_background_color (f, &bgcolor);
8255 bg_wand = NewPixelWand ();
8256 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8257 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8258 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8261 compute_image_size (MagickGetImageWidth (image_wand),
8262 MagickGetImageHeight (image_wand),
8263 img->spec, &desired_width, &desired_height);
8265 if (desired_width != -1 && desired_height != -1)
8267 status = MagickScaleImage (image_wand, desired_width, desired_height);
8268 if (status == MagickFalse)
8270 image_error ("Imagemagick scale failed", Qnil, Qnil);
8271 imagemagick_error (image_wand);
8272 goto imagemagick_error;
8276 /* crop behaves similar to image slicing in Emacs but is more memory
8277 efficient. */
8278 crop = image_spec_value (img->spec, QCcrop, NULL);
8280 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8282 /* After some testing, it seems MagickCropImage is the fastest crop
8283 function in ImageMagick. This crop function seems to do less copying
8284 than the alternatives, but it still reads the entire image into memory
8285 before cropping, which is apparently difficult to avoid when using
8286 imagemagick. */
8287 size_t crop_width = XINT (XCAR (crop));
8288 crop = XCDR (crop);
8289 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8291 size_t crop_height = XINT (XCAR (crop));
8292 crop = XCDR (crop);
8293 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8295 ssize_t crop_x = XINT (XCAR (crop));
8296 crop = XCDR (crop);
8297 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8299 ssize_t crop_y = XINT (XCAR (crop));
8300 MagickCropImage (image_wand, crop_width, crop_height,
8301 crop_x, crop_y);
8307 /* Furthermore :rotation. we need background color and angle for
8308 rotation. */
8310 TODO background handling for rotation specified_bg =
8311 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8312 (specified_bg). */
8313 value = image_spec_value (img->spec, QCrotation, NULL);
8314 if (FLOATP (value))
8316 rotation = extract_float (value);
8317 status = MagickRotateImage (image_wand, bg_wand, rotation);
8318 if (status == MagickFalse)
8320 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
8321 imagemagick_error (image_wand);
8322 goto imagemagick_error;
8326 /* Set the canvas background color to the frame or specified
8327 background, and flatten the image. Note: as of ImageMagick
8328 6.6.0, SVG image transparency is not handled properly
8329 (e.g. etc/images/splash.svg shows a white background always). */
8331 MagickWand *new_wand;
8332 MagickSetImageBackgroundColor (image_wand, bg_wand);
8333 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8334 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8335 #else
8336 new_wand = MagickFlattenImages (image_wand);
8337 #endif
8338 DestroyMagickWand (image_wand);
8339 image_wand = new_wand;
8342 /* Finally we are done manipulating the image. Figure out the
8343 resulting width/height and transfer ownership to Emacs. */
8344 image_height = MagickGetImageHeight (image_wand);
8345 image_width = MagickGetImageWidth (image_wand);
8347 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8348 && check_image_size (f, image_width, image_height)))
8350 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8351 goto imagemagick_error;
8354 width = image_width;
8355 height = image_height;
8357 /* We can now get a valid pixel buffer from the imagemagick file, if all
8358 went ok. */
8360 init_color_table ();
8362 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8363 if (imagemagick_render_type != 0)
8365 /* Magicexportimage is normally faster than pixelpushing. This
8366 method is also well tested. Some aspects of this method are
8367 ad-hoc and needs to be more researched. */
8368 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8369 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8370 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8371 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8372 &ximg, 0))
8374 #ifdef COLOR_TABLE_SUPPORT
8375 free_color_table ();
8376 #endif
8377 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8378 goto imagemagick_error;
8381 /* Oddly, the below code doesn't seem to work:*/
8382 /* switch(ximg->bitmap_unit){ */
8383 /* case 8: */
8384 /* pixelwidth=CharPixel; */
8385 /* break; */
8386 /* case 16: */
8387 /* pixelwidth=ShortPixel; */
8388 /* break; */
8389 /* case 32: */
8390 /* pixelwidth=LongPixel; */
8391 /* break; */
8392 /* } */
8394 Here im just guessing the format of the bitmap.
8395 happens to work fine for:
8396 - bw djvu images
8397 on rgb display.
8398 seems about 3 times as fast as pixel pushing(not carefully measured)
8400 pixelwidth = CharPixel; /*??? TODO figure out*/
8401 MagickExportImagePixels (image_wand, 0, 0, width, height,
8402 exportdepth, pixelwidth, ximg->data);
8404 else
8405 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8407 size_t image_height;
8408 MagickRealType color_scale = 65535.0 / QuantumRange;
8410 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8411 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8412 &ximg, 0))
8414 #ifdef COLOR_TABLE_SUPPORT
8415 free_color_table ();
8416 #endif
8417 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8418 goto imagemagick_error;
8421 /* Copy imagemagick image to x with primitive yet robust pixel
8422 pusher loop. This has been tested a lot with many different
8423 images. */
8425 /* Copy pixels from the imagemagick image structure to the x image map. */
8426 iterator = NewPixelIterator (image_wand);
8427 if (! iterator)
8429 #ifdef COLOR_TABLE_SUPPORT
8430 free_color_table ();
8431 #endif
8432 x_destroy_x_image (ximg);
8433 image_error ("Imagemagick pixel iterator creation failed",
8434 Qnil, Qnil);
8435 goto imagemagick_error;
8438 image_height = MagickGetImageHeight (image_wand);
8439 for (y = 0; y < image_height; y++)
8441 size_t row_width;
8442 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8443 if (! pixels)
8444 break;
8445 int xlim = min (row_width, width);
8446 for (x = 0; x < xlim; x++)
8448 PixelGetMagickColor (pixels[x], &pixel);
8449 XPutPixel (ximg, x, y,
8450 lookup_rgb_color (f,
8451 color_scale * pixel.red,
8452 color_scale * pixel.green,
8453 color_scale * pixel.blue));
8456 DestroyPixelIterator (iterator);
8459 #ifdef COLOR_TABLE_SUPPORT
8460 /* Remember colors allocated for this image. */
8461 img->colors = colors_in_color_table (&img->ncolors);
8462 free_color_table ();
8463 #endif /* COLOR_TABLE_SUPPORT */
8465 img->width = width;
8466 img->height = height;
8468 /* Put ximg into the image. */
8469 image_put_x_image (f, img, ximg, 0);
8471 /* Final cleanup. image_wand should be the only resource left. */
8472 DestroyMagickWand (image_wand);
8473 if (bg_wand) DestroyPixelWand (bg_wand);
8475 /* `MagickWandTerminus' terminates the imagemagick environment. */
8476 MagickWandTerminus ();
8478 return 1;
8480 imagemagick_error:
8481 DestroyMagickWand (image_wand);
8482 if (bg_wand) DestroyPixelWand (bg_wand);
8484 MagickWandTerminus ();
8485 /* TODO more cleanup. */
8486 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
8487 return 0;
8491 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8492 successful. this function will go into the imagemagick_type structure, and
8493 the prototype thus needs to be compatible with that structure. */
8495 static bool
8496 imagemagick_load (struct frame *f, struct image *img)
8498 bool success_p = 0;
8499 Lisp_Object file_name;
8501 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8502 file_name = image_spec_value (img->spec, QCfile, NULL);
8503 if (STRINGP (file_name))
8505 Lisp_Object file;
8507 file = x_find_image_file (file_name);
8508 if (!STRINGP (file))
8510 image_error ("Cannot find image file `%s'", file_name, Qnil);
8511 return 0;
8513 #ifdef WINDOWSNT
8514 file = ansi_encode_filename (file);
8515 #endif
8516 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8518 /* Else its not a file, its a lisp object. Load the image from a
8519 lisp object rather than a file. */
8520 else
8522 Lisp_Object data;
8524 data = image_spec_value (img->spec, QCdata, NULL);
8525 if (!STRINGP (data))
8527 image_error ("Invalid image data `%s'", data, Qnil);
8528 return 0;
8530 success_p = imagemagick_load_image (f, img, SDATA (data),
8531 SBYTES (data), NULL);
8534 return success_p;
8537 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8538 doc: /* Return a list of image types supported by ImageMagick.
8539 Each entry in this list is a symbol named after an ImageMagick format
8540 tag. See the ImageMagick manual for a list of ImageMagick formats and
8541 their descriptions (http://www.imagemagick.org/script/formats.php).
8542 You can also try the shell command: `identify -list format'.
8544 Note that ImageMagick recognizes many file-types that Emacs does not
8545 recognize as images, such as C. See `imagemagick-types-enable'
8546 and `imagemagick-types-inhibit'. */)
8547 (void)
8549 Lisp_Object typelist = Qnil;
8550 size_t numf = 0;
8551 ExceptionInfo ex;
8552 char **imtypes;
8553 size_t i;
8555 GetExceptionInfo(&ex);
8556 imtypes = GetMagickList ("*", &numf, &ex);
8557 DestroyExceptionInfo(&ex);
8559 for (i = 0; i < numf; i++)
8561 Lisp_Object imagemagicktype = intern (imtypes[i]);
8562 typelist = Fcons (imagemagicktype, typelist);
8563 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8566 MagickRelinquishMemory (imtypes);
8567 return Fnreverse (typelist);
8570 #endif /* defined (HAVE_IMAGEMAGICK) */
8574 /***********************************************************************
8576 ***********************************************************************/
8578 #ifdef HAVE_RSVG
8580 /* Function prototypes. */
8582 static bool svg_image_p (Lisp_Object object);
8583 static bool svg_load (struct frame *f, struct image *img);
8585 static bool svg_load_image (struct frame *, struct image *,
8586 unsigned char *, ptrdiff_t, char *);
8588 /* Indices of image specification fields in svg_format, below. */
8590 enum svg_keyword_index
8592 SVG_TYPE,
8593 SVG_DATA,
8594 SVG_FILE,
8595 SVG_ASCENT,
8596 SVG_MARGIN,
8597 SVG_RELIEF,
8598 SVG_ALGORITHM,
8599 SVG_HEURISTIC_MASK,
8600 SVG_MASK,
8601 SVG_BACKGROUND,
8602 SVG_LAST
8605 /* Vector of image_keyword structures describing the format
8606 of valid user-defined image specifications. */
8608 static const struct image_keyword svg_format[SVG_LAST] =
8610 {":type", IMAGE_SYMBOL_VALUE, 1},
8611 {":data", IMAGE_STRING_VALUE, 0},
8612 {":file", IMAGE_STRING_VALUE, 0},
8613 {":ascent", IMAGE_ASCENT_VALUE, 0},
8614 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8615 {":relief", IMAGE_INTEGER_VALUE, 0},
8616 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8617 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8618 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8619 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8622 # if defined HAVE_NTGUI && defined WINDOWSNT
8623 static bool init_svg_functions (void);
8624 # else
8625 #define init_svg_functions NULL
8626 # endif
8628 /* Structure describing the image type `svg'. Its the same type of
8629 structure defined for all image formats, handled by emacs image
8630 functions. See struct image_type in dispextern.h. */
8632 static struct image_type svg_type =
8634 SYMBOL_INDEX (Qsvg),
8635 svg_image_p,
8636 svg_load,
8637 x_clear_image,
8638 init_svg_functions,
8639 NULL
8643 /* Return true if OBJECT is a valid SVG image specification. Do
8644 this by calling parse_image_spec and supplying the keywords that
8645 identify the SVG format. */
8647 static bool
8648 svg_image_p (Lisp_Object object)
8650 struct image_keyword fmt[SVG_LAST];
8651 memcpy (fmt, svg_format, sizeof fmt);
8653 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8654 return 0;
8656 /* Must specify either the :data or :file keyword. */
8657 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8660 # include <librsvg/rsvg.h>
8662 # ifdef WINDOWSNT
8664 /* SVG library functions. */
8665 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
8666 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
8667 (RsvgHandle *, RsvgDimensionData *));
8668 DEF_DLL_FN (gboolean, rsvg_handle_write,
8669 (RsvgHandle *, const guchar *, gsize, GError **));
8670 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8671 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8672 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
8674 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8675 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8676 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8677 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8678 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8679 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8680 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8681 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8683 # if ! GLIB_CHECK_VERSION (2, 36, 0)
8684 DEF_DLL_FN (void, g_type_init, (void));
8685 # endif
8686 DEF_DLL_FN (void, g_object_unref, (gpointer));
8687 DEF_DLL_FN (void, g_error_free, (GError *));
8689 static bool
8690 init_svg_functions (void)
8692 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
8694 if (!(glib = w32_delayed_load (Qglib))
8695 || !(gobject = w32_delayed_load (Qgobject))
8696 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
8697 || !(library = w32_delayed_load (Qsvg)))
8699 if (gdklib) FreeLibrary (gdklib);
8700 if (gobject) FreeLibrary (gobject);
8701 if (glib) FreeLibrary (glib);
8702 return 0;
8705 LOAD_DLL_FN (library, rsvg_handle_new);
8706 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
8707 LOAD_DLL_FN (library, rsvg_handle_write);
8708 LOAD_DLL_FN (library, rsvg_handle_close);
8709 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
8710 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
8712 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
8713 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
8714 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
8715 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
8716 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
8717 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
8718 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
8719 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8721 # if ! GLIB_CHECK_VERSION (2, 36, 0)
8722 LOAD_DLL_FN (gobject, g_type_init);
8723 # endif
8724 LOAD_DLL_FN (gobject, g_object_unref);
8725 LOAD_DLL_FN (glib, g_error_free);
8727 return 1;
8730 /* The following aliases for library functions allow dynamic loading
8731 to be used on some platforms. */
8733 # undef gdk_pixbuf_get_bits_per_sample
8734 # undef gdk_pixbuf_get_colorspace
8735 # undef gdk_pixbuf_get_has_alpha
8736 # undef gdk_pixbuf_get_height
8737 # undef gdk_pixbuf_get_n_channels
8738 # undef gdk_pixbuf_get_pixels
8739 # undef gdk_pixbuf_get_rowstride
8740 # undef gdk_pixbuf_get_width
8741 # undef g_error_free
8742 # undef g_object_unref
8743 # undef g_type_init
8744 # undef rsvg_handle_close
8745 # undef rsvg_handle_get_dimensions
8746 # undef rsvg_handle_get_pixbuf
8747 # undef rsvg_handle_new
8748 # undef rsvg_handle_set_base_uri
8749 # undef rsvg_handle_write
8751 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
8752 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
8753 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
8754 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
8755 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
8756 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
8757 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
8758 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
8759 # define g_error_free fn_g_error_free
8760 # define g_object_unref fn_g_object_unref
8761 # define g_type_init fn_g_type_init
8762 # define rsvg_handle_close fn_rsvg_handle_close
8763 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
8764 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
8765 # define rsvg_handle_new fn_rsvg_handle_new
8766 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
8767 # define rsvg_handle_write fn_rsvg_handle_write
8769 # endif /* !WINDOWSNT */
8771 /* Load SVG image IMG for use on frame F. Value is true if
8772 successful. */
8774 static bool
8775 svg_load (struct frame *f, struct image *img)
8777 bool success_p = 0;
8778 Lisp_Object file_name;
8780 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8781 file_name = image_spec_value (img->spec, QCfile, NULL);
8782 if (STRINGP (file_name))
8784 Lisp_Object file;
8785 unsigned char *contents;
8786 ptrdiff_t size;
8788 file = x_find_image_file (file_name);
8789 if (!STRINGP (file))
8791 image_error ("Cannot find image file `%s'", file_name, Qnil);
8792 return 0;
8795 /* Read the entire file into memory. */
8796 contents = slurp_file (SSDATA (file), &size);
8797 if (contents == NULL)
8799 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8800 return 0;
8802 /* If the file was slurped into memory properly, parse it. */
8803 success_p = svg_load_image (f, img, contents, size, SSDATA (file));
8804 xfree (contents);
8806 /* Else its not a file, its a lisp object. Load the image from a
8807 lisp object rather than a file. */
8808 else
8810 Lisp_Object data, original_filename;
8812 data = image_spec_value (img->spec, QCdata, NULL);
8813 if (!STRINGP (data))
8815 image_error ("Invalid image data `%s'", data, Qnil);
8816 return 0;
8818 original_filename = BVAR (current_buffer, filename);
8819 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data),
8820 (NILP (original_filename) ? NULL
8821 : SSDATA (original_filename)));
8824 return success_p;
8827 /* svg_load_image is a helper function for svg_load, which does the
8828 actual loading given contents and size, apart from frame and image
8829 structures, passed from svg_load.
8831 Uses librsvg to do most of the image processing.
8833 Returns true when successful. */
8834 static bool
8835 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8836 struct image *img, /* Pointer to emacs image structure. */
8837 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8838 ptrdiff_t size, /* Size of data in bytes. */
8839 char *filename) /* Name of SVG file being loaded. */
8841 RsvgHandle *rsvg_handle;
8842 RsvgDimensionData dimension_data;
8843 GError *err = NULL;
8844 GdkPixbuf *pixbuf;
8845 int width;
8846 int height;
8847 const guint8 *pixels;
8848 int rowstride;
8849 XImagePtr ximg;
8850 Lisp_Object specified_bg;
8851 XColor background;
8852 int x;
8853 int y;
8855 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8856 /* g_type_init is a glib function that must be called prior to
8857 using gnome type library functions (obsolete since 2.36.0). */
8858 g_type_init ();
8859 #endif
8861 /* Make a handle to a new rsvg object. */
8862 rsvg_handle = rsvg_handle_new ();
8864 /* Set base_uri for properly handling referenced images (via 'href').
8865 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
8866 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
8867 if (filename)
8868 rsvg_handle_set_base_uri(rsvg_handle, filename);
8870 /* Parse the contents argument and fill in the rsvg_handle. */
8871 rsvg_handle_write (rsvg_handle, contents, size, &err);
8872 if (err) goto rsvg_error;
8874 /* The parsing is complete, rsvg_handle is ready to used, close it
8875 for further writes. */
8876 rsvg_handle_close (rsvg_handle, &err);
8877 if (err) goto rsvg_error;
8879 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8880 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8882 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8883 goto rsvg_error;
8886 /* We can now get a valid pixel buffer from the svg file, if all
8887 went ok. */
8888 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
8889 if (!pixbuf) goto rsvg_error;
8890 g_object_unref (rsvg_handle);
8892 /* Extract some meta data from the svg handle. */
8893 width = gdk_pixbuf_get_width (pixbuf);
8894 height = gdk_pixbuf_get_height (pixbuf);
8895 pixels = gdk_pixbuf_get_pixels (pixbuf);
8896 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
8898 /* Validate the svg meta data. */
8899 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8900 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
8901 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
8902 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8904 /* Try to create a x pixmap to hold the svg pixmap. */
8905 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
8907 g_object_unref (pixbuf);
8908 return 0;
8911 init_color_table ();
8913 /* Handle alpha channel by combining the image with a background
8914 color. */
8915 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8916 if (!STRINGP (specified_bg)
8917 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
8918 x_query_frame_background_color (f, &background);
8920 /* SVG pixmaps specify transparency in the last byte, so right
8921 shift 8 bits to get rid of it, since emacs doesn't support
8922 transparency. */
8923 background.red >>= 8;
8924 background.green >>= 8;
8925 background.blue >>= 8;
8927 /* This loop handles opacity values, since Emacs assumes
8928 non-transparent images. Each pixel must be "flattened" by
8929 calculating the resulting color, given the transparency of the
8930 pixel, and the image background color. */
8931 for (y = 0; y < height; ++y)
8933 for (x = 0; x < width; ++x)
8935 int red;
8936 int green;
8937 int blue;
8938 int opacity;
8940 red = *pixels++;
8941 green = *pixels++;
8942 blue = *pixels++;
8943 opacity = *pixels++;
8945 red = ((red * opacity)
8946 + (background.red * ((1 << 8) - opacity)));
8947 green = ((green * opacity)
8948 + (background.green * ((1 << 8) - opacity)));
8949 blue = ((blue * opacity)
8950 + (background.blue * ((1 << 8) - opacity)));
8952 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8955 pixels += rowstride - 4 * width;
8958 #ifdef COLOR_TABLE_SUPPORT
8959 /* Remember colors allocated for this image. */
8960 img->colors = colors_in_color_table (&img->ncolors);
8961 free_color_table ();
8962 #endif /* COLOR_TABLE_SUPPORT */
8964 g_object_unref (pixbuf);
8966 img->width = width;
8967 img->height = height;
8969 /* Maybe fill in the background field while we have ximg handy.
8970 Casting avoids a GCC warning. */
8971 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8973 /* Put ximg into the image. */
8974 image_put_x_image (f, img, ximg, 0);
8976 return 1;
8978 rsvg_error:
8979 g_object_unref (rsvg_handle);
8980 /* FIXME: Use error->message so the user knows what is the actual
8981 problem with the image. */
8982 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8983 g_error_free (err);
8984 return 0;
8987 #endif /* defined (HAVE_RSVG) */
8992 /***********************************************************************
8993 Ghostscript
8994 ***********************************************************************/
8996 #ifdef HAVE_X_WINDOWS
8997 #define HAVE_GHOSTSCRIPT 1
8998 #endif /* HAVE_X_WINDOWS */
9000 #ifdef HAVE_GHOSTSCRIPT
9002 static bool gs_image_p (Lisp_Object object);
9003 static bool gs_load (struct frame *f, struct image *img);
9004 static void gs_clear_image (struct frame *f, struct image *img);
9006 /* Indices of image specification fields in gs_format, below. */
9008 enum gs_keyword_index
9010 GS_TYPE,
9011 GS_PT_WIDTH,
9012 GS_PT_HEIGHT,
9013 GS_FILE,
9014 GS_LOADER,
9015 GS_BOUNDING_BOX,
9016 GS_ASCENT,
9017 GS_MARGIN,
9018 GS_RELIEF,
9019 GS_ALGORITHM,
9020 GS_HEURISTIC_MASK,
9021 GS_MASK,
9022 GS_BACKGROUND,
9023 GS_LAST
9026 /* Vector of image_keyword structures describing the format
9027 of valid user-defined image specifications. */
9029 static const struct image_keyword gs_format[GS_LAST] =
9031 {":type", IMAGE_SYMBOL_VALUE, 1},
9032 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9033 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9034 {":file", IMAGE_STRING_VALUE, 1},
9035 {":loader", IMAGE_FUNCTION_VALUE, 0},
9036 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9037 {":ascent", IMAGE_ASCENT_VALUE, 0},
9038 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9039 {":relief", IMAGE_INTEGER_VALUE, 0},
9040 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9041 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9042 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9043 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9046 /* Structure describing the image type `ghostscript'. */
9048 static struct image_type gs_type =
9050 SYMBOL_INDEX (Qpostscript),
9051 gs_image_p,
9052 gs_load,
9053 gs_clear_image,
9054 NULL,
9055 NULL
9059 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9061 static void
9062 gs_clear_image (struct frame *f, struct image *img)
9064 x_clear_image (f, img);
9068 /* Return true if OBJECT is a valid Ghostscript image
9069 specification. */
9071 static bool
9072 gs_image_p (Lisp_Object object)
9074 struct image_keyword fmt[GS_LAST];
9075 Lisp_Object tem;
9076 int i;
9078 memcpy (fmt, gs_format, sizeof fmt);
9080 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9081 return 0;
9083 /* Bounding box must be a list or vector containing 4 integers. */
9084 tem = fmt[GS_BOUNDING_BOX].value;
9085 if (CONSP (tem))
9087 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9088 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9089 return 0;
9090 if (!NILP (tem))
9091 return 0;
9093 else if (VECTORP (tem))
9095 if (ASIZE (tem) != 4)
9096 return 0;
9097 for (i = 0; i < 4; ++i)
9098 if (!INTEGERP (AREF (tem, i)))
9099 return 0;
9101 else
9102 return 0;
9104 return 1;
9108 /* Load Ghostscript image IMG for use on frame F. Value is true
9109 if successful. */
9111 static bool
9112 gs_load (struct frame *f, struct image *img)
9114 uprintmax_t printnum1, printnum2;
9115 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9116 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9117 Lisp_Object frame;
9118 double in_width, in_height;
9119 Lisp_Object pixel_colors = Qnil;
9121 /* Compute pixel size of pixmap needed from the given size in the
9122 image specification. Sizes in the specification are in pt. 1 pt
9123 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9124 info. */
9125 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9126 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9127 in_width *= FRAME_RES_X (f);
9128 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9129 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9130 in_height *= FRAME_RES_Y (f);
9132 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9133 && check_image_size (f, in_width, in_height)))
9135 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
9136 return 0;
9138 img->width = in_width;
9139 img->height = in_height;
9141 /* Create the pixmap. */
9142 eassert (img->pixmap == NO_PIXMAP);
9144 if (x_check_image_size (0, img->width, img->height))
9146 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9147 block_input ();
9148 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9149 img->width, img->height,
9150 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9151 unblock_input ();
9154 if (!img->pixmap)
9156 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
9157 return 0;
9160 /* Call the loader to fill the pixmap. It returns a process object
9161 if successful. We do not record_unwind_protect here because
9162 other places in redisplay like calling window scroll functions
9163 don't either. Let the Lisp loader use `unwind-protect' instead. */
9164 printnum1 = FRAME_X_WINDOW (f);
9165 printnum2 = img->pixmap;
9166 window_and_pixmap_id
9167 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9169 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9170 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9171 pixel_colors
9172 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9174 XSETFRAME (frame, f);
9175 loader = image_spec_value (img->spec, QCloader, NULL);
9176 if (NILP (loader))
9177 loader = intern ("gs-load-image");
9179 img->lisp_data = call6 (loader, frame, img->spec,
9180 make_number (img->width),
9181 make_number (img->height),
9182 window_and_pixmap_id,
9183 pixel_colors);
9184 return PROCESSP (img->lisp_data);
9188 /* Kill the Ghostscript process that was started to fill PIXMAP on
9189 frame F. Called from XTread_socket when receiving an event
9190 telling Emacs that Ghostscript has finished drawing. */
9192 void
9193 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9195 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9196 int class;
9197 ptrdiff_t i;
9198 struct image *img;
9200 /* Find the image containing PIXMAP. */
9201 for (i = 0; i < c->used; ++i)
9202 if (c->images[i]->pixmap == pixmap)
9203 break;
9205 /* Should someone in between have cleared the image cache, for
9206 instance, give up. */
9207 if (i == c->used)
9208 return;
9210 /* Kill the GS process. We should have found PIXMAP in the image
9211 cache and its image should contain a process object. */
9212 img = c->images[i];
9213 eassert (PROCESSP (img->lisp_data));
9214 Fkill_process (img->lisp_data, Qnil);
9215 img->lisp_data = Qnil;
9217 #if defined (HAVE_X_WINDOWS)
9219 /* On displays with a mutable colormap, figure out the colors
9220 allocated for the image by looking at the pixels of an XImage for
9221 img->pixmap. */
9222 class = FRAME_X_VISUAL (f)->class;
9223 if (class != StaticColor && class != StaticGray && class != TrueColor)
9225 XImagePtr ximg;
9227 block_input ();
9229 /* Try to get an XImage for img->pixmep. */
9230 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9231 0, 0, img->width, img->height, ~0, ZPixmap);
9232 if (ximg)
9234 int x, y;
9236 /* Initialize the color table. */
9237 init_color_table ();
9239 /* For each pixel of the image, look its color up in the
9240 color table. After having done so, the color table will
9241 contain an entry for each color used by the image. */
9242 for (y = 0; y < img->height; ++y)
9243 for (x = 0; x < img->width; ++x)
9245 unsigned long pixel = XGetPixel (ximg, x, y);
9246 lookup_pixel_color (f, pixel);
9249 /* Record colors in the image. Free color table and XImage. */
9250 #ifdef COLOR_TABLE_SUPPORT
9251 img->colors = colors_in_color_table (&img->ncolors);
9252 free_color_table ();
9253 #endif
9254 XDestroyImage (ximg);
9256 #if 0 /* This doesn't seem to be the case. If we free the colors
9257 here, we get a BadAccess later in x_clear_image when
9258 freeing the colors. */
9259 /* We have allocated colors once, but Ghostscript has also
9260 allocated colors on behalf of us. So, to get the
9261 reference counts right, free them once. */
9262 if (img->ncolors)
9263 x_free_colors (f, img->colors, img->ncolors);
9264 #endif
9266 else
9267 image_error ("Cannot get X image of `%s'; colors will not be freed",
9268 img->spec, Qnil);
9270 unblock_input ();
9272 #endif /* HAVE_X_WINDOWS */
9274 /* Now that we have the pixmap, compute mask and transform the
9275 image if requested. */
9276 block_input ();
9277 postprocess_image (f, img);
9278 unblock_input ();
9281 #endif /* HAVE_GHOSTSCRIPT */
9284 /***********************************************************************
9285 Tests
9286 ***********************************************************************/
9288 #ifdef GLYPH_DEBUG
9290 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9291 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9292 (Lisp_Object spec)
9294 return valid_image_p (spec) ? Qt : Qnil;
9298 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0,
9299 doc: /* */)
9300 (Lisp_Object spec)
9302 ptrdiff_t id = -1;
9304 if (valid_image_p (spec))
9305 id = lookup_image (SELECTED_FRAME (), spec);
9307 debug_print (spec);
9308 return make_number (id);
9311 #endif /* GLYPH_DEBUG */
9314 /***********************************************************************
9315 Initialization
9316 ***********************************************************************/
9318 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9319 doc: /* Initialize image library implementing image type TYPE.
9320 Return non-nil if TYPE is a supported image type.
9322 If image libraries are loaded dynamically (currently only the case on
9323 MS-Windows), load the library for TYPE if it is not yet loaded, using
9324 the library file(s) specified by `dynamic-library-alist'. */)
9325 (Lisp_Object type)
9327 return lookup_image_type (type) ? Qt : Qnil;
9330 /* Look up image type TYPE, and return a pointer to its image_type
9331 structure. Return 0 if TYPE is not a known image type. */
9333 static struct image_type *
9334 lookup_image_type (Lisp_Object type)
9336 /* Types pbm and xbm are built-in and always available. */
9337 if (EQ (type, Qpbm))
9338 return define_image_type (&pbm_type);
9340 if (EQ (type, Qxbm))
9341 return define_image_type (&xbm_type);
9343 #if defined (HAVE_XPM) || defined (HAVE_NS)
9344 if (EQ (type, Qxpm))
9345 return define_image_type (&xpm_type);
9346 #endif
9348 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9349 if (EQ (type, Qjpeg))
9350 return define_image_type (&jpeg_type);
9351 #endif
9353 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9354 if (EQ (type, Qtiff))
9355 return define_image_type (&tiff_type);
9356 #endif
9358 #if defined (HAVE_GIF) || defined (HAVE_NS)
9359 if (EQ (type, Qgif))
9360 return define_image_type (&gif_type);
9361 #endif
9363 #if defined (HAVE_PNG) || defined (HAVE_NS)
9364 if (EQ (type, Qpng))
9365 return define_image_type (&png_type);
9366 #endif
9368 #if defined (HAVE_RSVG)
9369 if (EQ (type, Qsvg))
9370 return define_image_type (&svg_type);
9371 #endif
9373 #if defined (HAVE_IMAGEMAGICK)
9374 if (EQ (type, Qimagemagick))
9375 return define_image_type (&imagemagick_type);
9376 #endif
9378 #ifdef HAVE_GHOSTSCRIPT
9379 if (EQ (type, Qpostscript))
9380 return define_image_type (&gs_type);
9381 #endif
9383 return NULL;
9386 /* Reset image_types before dumping.
9387 Called from Fdump_emacs. */
9389 void
9390 reset_image_types (void)
9392 while (image_types)
9394 struct image_type *next = image_types->next;
9395 xfree (image_types);
9396 image_types = next;
9400 void
9401 syms_of_image (void)
9403 /* Initialize this only once; it will be reset before dumping. */
9404 image_types = NULL;
9406 /* Must be defined now because we're going to update it below, while
9407 defining the supported image types. */
9408 DEFVAR_LISP ("image-types", Vimage_types,
9409 doc: /* List of potentially supported image types.
9410 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9411 To check whether it is really supported, use `image-type-available-p'. */);
9412 Vimage_types = Qnil;
9414 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9415 doc: /* Maximum size of images.
9416 Emacs will not load an image into memory if its pixel width or
9417 pixel height exceeds this limit.
9419 If the value is an integer, it directly specifies the maximum
9420 image height and width, measured in pixels. If it is a floating
9421 point number, it specifies the maximum image height and width
9422 as a ratio to the frame height and width. If the value is
9423 non-numeric, there is no explicit limit on the size of images. */);
9424 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9426 /* Other symbols. */
9427 DEFSYM (Qcount, "count");
9428 DEFSYM (Qextension_data, "extension-data");
9429 DEFSYM (Qdelay, "delay");
9431 /* Keywords. */
9432 DEFSYM (QCascent, ":ascent");
9433 DEFSYM (QCmargin, ":margin");
9434 DEFSYM (QCrelief, ":relief");
9435 DEFSYM (QCconversion, ":conversion");
9436 DEFSYM (QCcolor_symbols, ":color-symbols");
9437 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9438 DEFSYM (QCindex, ":index");
9439 DEFSYM (QCgeometry, ":geometry");
9440 DEFSYM (QCcrop, ":crop");
9441 DEFSYM (QCrotation, ":rotation");
9442 DEFSYM (QCmatrix, ":matrix");
9443 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9444 DEFSYM (QCmask, ":mask");
9446 /* Other symbols. */
9447 DEFSYM (Qlaplace, "laplace");
9448 DEFSYM (Qemboss, "emboss");
9449 DEFSYM (Qedge_detection, "edge-detection");
9450 DEFSYM (Qheuristic, "heuristic");
9452 DEFSYM (Qpostscript, "postscript");
9453 DEFSYM (QCmax_width, ":max-width");
9454 DEFSYM (QCmax_height, ":max-height");
9455 #ifdef HAVE_GHOSTSCRIPT
9456 ADD_IMAGE_TYPE (Qpostscript);
9457 DEFSYM (QCloader, ":loader");
9458 DEFSYM (QCbounding_box, ":bounding-box");
9459 DEFSYM (QCpt_width, ":pt-width");
9460 DEFSYM (QCpt_height, ":pt-height");
9461 #endif /* HAVE_GHOSTSCRIPT */
9463 #ifdef HAVE_NTGUI
9464 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9465 or -1 if no PNG/GIF support was compiled in. This is tested by
9466 w32-win.el to correctly set up the alist used to search for the
9467 respective image libraries. */
9468 DEFSYM (Qlibpng_version, "libpng-version");
9469 Fset (Qlibpng_version,
9470 #if HAVE_PNG
9471 make_number (PNG_LIBPNG_VER)
9472 #else
9473 make_number (-1)
9474 #endif
9476 DEFSYM (Qlibgif_version, "libgif-version");
9477 Fset (Qlibgif_version,
9478 #ifdef HAVE_GIF
9479 make_number (GIFLIB_MAJOR * 10000
9480 + GIFLIB_MINOR * 100
9481 + GIFLIB_RELEASE)
9482 #else
9483 make_number (-1)
9484 #endif
9486 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9487 Fset (Qlibjpeg_version,
9488 #if HAVE_JPEG
9489 make_number (JPEG_LIB_VERSION)
9490 #else
9491 make_number (-1)
9492 #endif
9494 #endif
9496 DEFSYM (Qpbm, "pbm");
9497 ADD_IMAGE_TYPE (Qpbm);
9499 DEFSYM (Qxbm, "xbm");
9500 ADD_IMAGE_TYPE (Qxbm);
9502 #if defined (HAVE_XPM) || defined (HAVE_NS)
9503 DEFSYM (Qxpm, "xpm");
9504 ADD_IMAGE_TYPE (Qxpm);
9505 #endif
9507 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9508 DEFSYM (Qjpeg, "jpeg");
9509 ADD_IMAGE_TYPE (Qjpeg);
9510 #endif
9512 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9513 DEFSYM (Qtiff, "tiff");
9514 ADD_IMAGE_TYPE (Qtiff);
9515 #endif
9517 #if defined (HAVE_GIF) || defined (HAVE_NS)
9518 DEFSYM (Qgif, "gif");
9519 ADD_IMAGE_TYPE (Qgif);
9520 #endif
9522 #if defined (HAVE_PNG) || defined (HAVE_NS)
9523 DEFSYM (Qpng, "png");
9524 ADD_IMAGE_TYPE (Qpng);
9525 #endif
9527 #if defined (HAVE_IMAGEMAGICK)
9528 DEFSYM (Qimagemagick, "imagemagick");
9529 ADD_IMAGE_TYPE (Qimagemagick);
9530 #endif
9532 #if defined (HAVE_RSVG)
9533 DEFSYM (Qsvg, "svg");
9534 ADD_IMAGE_TYPE (Qsvg);
9535 #ifdef HAVE_NTGUI
9536 /* Other libraries used directly by svg code. */
9537 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9538 DEFSYM (Qglib, "glib");
9539 DEFSYM (Qgobject, "gobject");
9540 #endif /* HAVE_NTGUI */
9541 #endif /* HAVE_RSVG */
9543 defsubr (&Sinit_image_library);
9544 #ifdef HAVE_IMAGEMAGICK
9545 defsubr (&Simagemagick_types);
9546 #endif
9547 defsubr (&Sclear_image_cache);
9548 defsubr (&Simage_flush);
9549 defsubr (&Simage_size);
9550 defsubr (&Simage_mask_p);
9551 defsubr (&Simage_metadata);
9553 #ifdef GLYPH_DEBUG
9554 defsubr (&Simagep);
9555 defsubr (&Slookup_image);
9556 #endif
9558 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9559 doc: /* Non-nil means always draw a cross over disabled images.
9560 Disabled images are those having a `:conversion disabled' property.
9561 A cross is always drawn on black & white displays. */);
9562 cross_disabled_images = 0;
9564 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9565 doc: /* List of directories to search for window system bitmap files. */);
9566 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9568 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9569 doc: /* Maximum time after which images are removed from the cache.
9570 When an image has not been displayed this many seconds, Emacs
9571 automatically removes it from the image cache. If the cache contains
9572 a large number of images, the actual eviction time may be shorter.
9573 The value can also be nil, meaning the cache is never cleared.
9575 The function `clear-image-cache' disregards this variable. */);
9576 Vimage_cache_eviction_delay = make_number (300);
9577 #ifdef HAVE_IMAGEMAGICK
9578 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9579 doc: /* Integer indicating which ImageMagick rendering method to use.
9580 The options are:
9581 0 -- the default method (pixel pushing)
9582 1 -- a newer method ("MagickExportImagePixels") that may perform
9583 better (speed etc) in some cases, but has not been as thoroughly
9584 tested with Emacs as the default method. This method requires
9585 ImageMagick version 6.4.6 (approximately) or later.
9586 */);
9587 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9588 imagemagick_render_type = 0;
9589 #endif