'.' -> `.' in doc string
[emacs.git] / src / image.c
blobb586c5341d72bd93a659ad0a456c13947956fc41
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include "sysstdio.h"
22 #include <unistd.h>
24 /* Include this before including <setjmp.h> to work around bugs with
25 older libpng; see Bug#17429. */
26 #if defined HAVE_PNG && !defined HAVE_NS
27 # include <png.h>
28 #endif
30 #include <setjmp.h>
31 #include <c-ctype.h>
33 #include "lisp.h"
34 #include "frame.h"
35 #include "window.h"
36 #include "buffer.h"
37 #include "dispextern.h"
38 #include "blockinput.h"
39 #include "systime.h"
40 #include <epaths.h>
41 #include "character.h"
42 #include "coding.h"
43 #include "termhooks.h"
44 #include "font.h"
46 #ifdef HAVE_SYS_STAT_H
47 #include <sys/stat.h>
48 #endif /* HAVE_SYS_STAT_H */
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
52 #endif /* HAVE_SYS_TYPES_H */
54 #ifdef HAVE_WINDOW_SYSTEM
55 #include TERM_HEADER
56 #endif /* HAVE_WINDOW_SYSTEM */
58 #ifdef HAVE_X_WINDOWS
59 #define COLOR_TABLE_SUPPORT 1
61 typedef struct x_bitmap_record Bitmap_Record;
62 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
63 #define NO_PIXMAP None
65 #define PIX_MASK_RETAIN 0
66 #define PIX_MASK_DRAW 1
67 #endif /* HAVE_X_WINDOWS */
69 #ifdef HAVE_NTGUI
71 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
72 #ifdef WINDOWSNT
73 # include "w32.h"
74 #endif
76 /* W32_TODO : Color tables on W32. */
77 #undef COLOR_TABLE_SUPPORT
79 typedef struct w32_bitmap_record Bitmap_Record;
80 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
81 #define NO_PIXMAP 0
83 #define PIX_MASK_RETAIN 0
84 #define PIX_MASK_DRAW 1
86 #define x_defined_color w32_defined_color
87 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
89 #endif /* HAVE_NTGUI */
91 #ifdef USE_CAIRO
92 #undef COLOR_TABLE_SUPPORT
93 #endif
95 #ifdef HAVE_NS
96 #undef COLOR_TABLE_SUPPORT
98 typedef struct ns_bitmap_record Bitmap_Record;
100 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
101 #define NO_PIXMAP 0
103 #define PIX_MASK_RETAIN 0
104 #define PIX_MASK_DRAW 1
106 #define x_defined_color(f, name, color_def, alloc) \
107 ns_defined_color (f, name, color_def, alloc, 0)
108 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
109 #endif /* HAVE_NS */
111 static void x_disable_image (struct frame *, struct image *);
112 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
113 Lisp_Object);
115 static void init_color_table (void);
116 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
117 #ifdef COLOR_TABLE_SUPPORT
118 static void free_color_table (void);
119 static unsigned long *colors_in_color_table (int *n);
120 #endif
122 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
123 id, which is just an int that this section returns. Bitmaps are
124 reference counted so they can be shared among frames.
126 Bitmap indices are guaranteed to be > 0, so a negative number can
127 be used to indicate no bitmap.
129 If you use x_create_bitmap_from_data, then you must keep track of
130 the bitmaps yourself. That is, creating a bitmap from the same
131 data more than once will not be caught. */
133 #ifdef HAVE_NS
134 /* Use with images created by ns_image_for_XPM. */
135 static unsigned long
136 XGetPixel (XImagePtr ximage, int x, int y)
138 return ns_get_pixel (ximage, x, y);
141 /* Use with images created by ns_image_for_XPM; alpha set to 1;
142 pixel is assumed to be in RGB form. */
143 static void
144 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
146 ns_put_pixel (ximage, x, y, pixel);
148 #endif /* HAVE_NS */
151 /* Functions to access the contents of a bitmap, given an id. */
153 #ifdef HAVE_X_WINDOWS
154 static int
155 x_bitmap_height (struct frame *f, ptrdiff_t id)
157 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
160 static int
161 x_bitmap_width (struct frame *f, ptrdiff_t id)
163 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
165 #endif
167 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
168 ptrdiff_t
169 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
171 /* HAVE_NTGUI needs the explicit cast here. */
172 return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
174 #endif
176 #ifdef HAVE_X_WINDOWS
178 x_bitmap_mask (struct frame *f, ptrdiff_t id)
180 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
182 #endif
184 /* Allocate a new bitmap record. Returns index of new record. */
186 static ptrdiff_t
187 x_allocate_bitmap_record (struct frame *f)
189 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
190 ptrdiff_t i;
192 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
193 return ++dpyinfo->bitmaps_last;
195 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
196 if (dpyinfo->bitmaps[i].refcount == 0)
197 return i + 1;
199 dpyinfo->bitmaps =
200 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
201 10, -1, sizeof *dpyinfo->bitmaps);
202 return ++dpyinfo->bitmaps_last;
205 /* Add one reference to the reference count of the bitmap with id ID. */
207 void
208 x_reference_bitmap (struct frame *f, ptrdiff_t id)
210 ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
213 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
215 ptrdiff_t
216 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
218 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
219 ptrdiff_t id;
221 #ifdef HAVE_X_WINDOWS
222 Pixmap bitmap;
223 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
224 bits, width, height);
225 if (! bitmap)
226 return -1;
227 #endif /* HAVE_X_WINDOWS */
229 #ifdef HAVE_NTGUI
230 Pixmap bitmap;
231 bitmap = CreateBitmap (width, height,
232 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
233 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
234 bits);
235 if (! bitmap)
236 return -1;
237 #endif /* HAVE_NTGUI */
239 #ifdef HAVE_NS
240 void *bitmap = ns_image_from_XBM (bits, width, height, 0, 0);
241 if (!bitmap)
242 return -1;
243 #endif
245 id = x_allocate_bitmap_record (f);
247 #ifdef HAVE_NS
248 dpyinfo->bitmaps[id - 1].img = bitmap;
249 dpyinfo->bitmaps[id - 1].depth = 1;
250 #endif
252 dpyinfo->bitmaps[id - 1].file = NULL;
253 dpyinfo->bitmaps[id - 1].height = height;
254 dpyinfo->bitmaps[id - 1].width = width;
255 dpyinfo->bitmaps[id - 1].refcount = 1;
257 #ifdef HAVE_X_WINDOWS
258 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
259 dpyinfo->bitmaps[id - 1].have_mask = false;
260 dpyinfo->bitmaps[id - 1].depth = 1;
261 #endif /* HAVE_X_WINDOWS */
263 #ifdef HAVE_NTGUI
264 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
265 dpyinfo->bitmaps[id - 1].hinst = NULL;
266 dpyinfo->bitmaps[id - 1].depth = 1;
267 #endif /* HAVE_NTGUI */
269 return id;
272 /* Create bitmap from file FILE for frame F. */
274 ptrdiff_t
275 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
277 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
279 #ifdef HAVE_NTGUI
280 return -1; /* W32_TODO : bitmap support */
281 #endif /* HAVE_NTGUI */
283 #ifdef HAVE_NS
284 ptrdiff_t id;
285 void *bitmap = ns_image_from_file (file);
287 if (!bitmap)
288 return -1;
291 id = x_allocate_bitmap_record (f);
292 dpyinfo->bitmaps[id - 1].img = bitmap;
293 dpyinfo->bitmaps[id - 1].refcount = 1;
294 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
295 dpyinfo->bitmaps[id - 1].depth = 1;
296 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
297 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
298 return id;
299 #endif
301 #ifdef HAVE_X_WINDOWS
302 unsigned int width, height;
303 Pixmap bitmap;
304 int xhot, yhot, result;
305 ptrdiff_t id;
306 Lisp_Object found;
307 char *filename;
309 /* Look for an existing bitmap with the same name. */
310 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
312 if (dpyinfo->bitmaps[id].refcount
313 && dpyinfo->bitmaps[id].file
314 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
316 ++dpyinfo->bitmaps[id].refcount;
317 return id + 1;
321 /* Search bitmap-file-path for the file, if appropriate. */
322 if (openp (Vx_bitmap_file_path, file, Qnil, &found,
323 make_number (R_OK), false)
324 < 0)
325 return -1;
327 filename = SSDATA (found);
329 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
330 filename, &width, &height, &bitmap, &xhot, &yhot);
331 if (result != BitmapSuccess)
332 return -1;
334 id = x_allocate_bitmap_record (f);
335 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
336 dpyinfo->bitmaps[id - 1].have_mask = false;
337 dpyinfo->bitmaps[id - 1].refcount = 1;
338 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
339 dpyinfo->bitmaps[id - 1].depth = 1;
340 dpyinfo->bitmaps[id - 1].height = height;
341 dpyinfo->bitmaps[id - 1].width = width;
343 return id;
344 #endif /* HAVE_X_WINDOWS */
347 /* Free bitmap B. */
349 static void
350 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
352 #ifdef HAVE_X_WINDOWS
353 XFreePixmap (dpyinfo->display, bm->pixmap);
354 if (bm->have_mask)
355 XFreePixmap (dpyinfo->display, bm->mask);
356 #endif /* HAVE_X_WINDOWS */
358 #ifdef HAVE_NTGUI
359 DeleteObject (bm->pixmap);
360 #endif /* HAVE_NTGUI */
362 #ifdef HAVE_NS
363 ns_release_object (bm->img);
364 #endif
366 if (bm->file)
368 xfree (bm->file);
369 bm->file = NULL;
373 /* Remove reference to bitmap with id number ID. */
375 void
376 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
378 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
380 if (id > 0)
382 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
384 if (--bm->refcount == 0)
386 block_input ();
387 free_bitmap_record (dpyinfo, bm);
388 unblock_input ();
393 /* Free all the bitmaps for the display specified by DPYINFO. */
395 void
396 x_destroy_all_bitmaps (Display_Info *dpyinfo)
398 ptrdiff_t i;
399 Bitmap_Record *bm = dpyinfo->bitmaps;
401 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
402 if (bm->refcount > 0)
403 free_bitmap_record (dpyinfo, bm);
405 dpyinfo->bitmaps_last = 0;
408 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
409 XImagePtr *, Pixmap *);
410 static void x_destroy_x_image (XImagePtr ximg);
412 #ifdef HAVE_NTGUI
413 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
414 bool, HGDIOBJ *);
415 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
416 HGDIOBJ);
417 #else
418 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
419 static void image_unget_x_image (struct image *, bool, XImagePtr);
420 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
421 image_get_x_image (f, img, mask_p)
422 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
423 image_unget_x_image (img, mask_p, ximg)
424 #endif
426 #ifdef HAVE_X_WINDOWS
428 static void image_sync_to_pixmaps (struct frame *, struct image *);
430 /* Useful functions defined in the section
431 `Image type independent image structures' below. */
433 static unsigned long four_corners_best (XImagePtr ximg,
434 int *corners,
435 unsigned long width,
436 unsigned long height);
439 /* Create a mask of a bitmap. Note is this not a perfect mask.
440 It's nicer with some borders in this context */
442 void
443 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
445 Pixmap pixmap, mask;
446 XImagePtr ximg, mask_img;
447 unsigned long width, height;
448 bool result;
449 unsigned long bg;
450 unsigned long x, y, xp, xm, yp, ym;
451 GC gc;
453 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
455 if (!(id > 0))
456 return;
458 pixmap = x_bitmap_pixmap (f, id);
459 width = x_bitmap_width (f, id);
460 height = x_bitmap_height (f, id);
462 block_input ();
463 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
464 ~0, ZPixmap);
466 if (!ximg)
468 unblock_input ();
469 return;
472 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
474 unblock_input ();
475 if (!result)
477 XDestroyImage (ximg);
478 return;
481 bg = four_corners_best (ximg, NULL, width, height);
483 for (y = 0; y < ximg->height; ++y)
485 for (x = 0; x < ximg->width; ++x)
487 xp = x != ximg->width - 1 ? x + 1 : 0;
488 xm = x != 0 ? x - 1 : ximg->width - 1;
489 yp = y != ximg->height - 1 ? y + 1 : 0;
490 ym = y != 0 ? y - 1 : ximg->height - 1;
491 if (XGetPixel (ximg, x, y) == bg
492 && XGetPixel (ximg, x, yp) == bg
493 && XGetPixel (ximg, x, ym) == bg
494 && XGetPixel (ximg, xp, y) == bg
495 && XGetPixel (ximg, xp, yp) == bg
496 && XGetPixel (ximg, xp, ym) == bg
497 && XGetPixel (ximg, xm, y) == bg
498 && XGetPixel (ximg, xm, yp) == bg
499 && XGetPixel (ximg, xm, ym) == bg)
500 XPutPixel (mask_img, x, y, 0);
501 else
502 XPutPixel (mask_img, x, y, 1);
506 eassert (input_blocked_p ());
507 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
508 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
509 width, height);
510 XFreeGC (FRAME_X_DISPLAY (f), gc);
512 dpyinfo->bitmaps[id - 1].have_mask = true;
513 dpyinfo->bitmaps[id - 1].mask = mask;
515 XDestroyImage (ximg);
516 x_destroy_x_image (mask_img);
519 #endif /* HAVE_X_WINDOWS */
521 /***********************************************************************
522 Image types
523 ***********************************************************************/
525 /* List of supported image types. Use define_image_type to add new
526 types. Use lookup_image_type to find a type for a given symbol. */
528 static struct image_type *image_types;
530 /* Forward function prototypes. */
532 static struct image_type *lookup_image_type (Lisp_Object);
533 static void x_laplace (struct frame *, struct image *);
534 static void x_emboss (struct frame *, struct image *);
535 static void x_build_heuristic_mask (struct frame *, struct image *,
536 Lisp_Object);
537 #ifdef WINDOWSNT
538 #define CACHE_IMAGE_TYPE(type, status) \
539 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
540 #else
541 #define CACHE_IMAGE_TYPE(type, status)
542 #endif
544 #define ADD_IMAGE_TYPE(type) \
545 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
547 /* Define a new image type from TYPE. This adds a copy of TYPE to
548 image_types and caches the loading status of TYPE. */
550 static struct image_type *
551 define_image_type (struct image_type *type)
553 struct image_type *p = NULL;
554 int new_type = type->type;
555 bool type_valid = true;
557 block_input ();
559 for (p = image_types; p; p = p->next)
560 if (p->type == new_type)
561 goto done;
563 if (type->init)
565 #if defined HAVE_NTGUI && defined WINDOWSNT
566 /* If we failed to load the library before, don't try again. */
567 Lisp_Object tested = Fassq (builtin_lisp_symbol (new_type),
568 Vlibrary_cache);
569 if (CONSP (tested) && NILP (XCDR (tested)))
570 type_valid = false;
571 else
572 #endif
574 type_valid = type->init ();
575 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type),
576 type_valid ? Qt : Qnil);
580 if (type_valid)
582 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
583 The initialized data segment is read-only. */
584 p = xmalloc (sizeof *p);
585 *p = *type;
586 p->next = image_types;
587 image_types = p;
590 done:
591 unblock_input ();
592 return p;
596 /* Value is true if OBJECT is a valid Lisp image specification. A
597 valid image specification is a list whose car is the symbol
598 `image', and whose rest is a property list. The property list must
599 contain a value for key `:type'. That value must be the name of a
600 supported image type. The rest of the property list depends on the
601 image type. */
603 bool
604 valid_image_p (Lisp_Object object)
606 bool valid_p = 0;
608 if (IMAGEP (object))
610 Lisp_Object tem;
612 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
613 if (EQ (XCAR (tem), QCtype))
615 tem = XCDR (tem);
616 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
618 struct image_type *type;
619 type = lookup_image_type (XCAR (tem));
620 if (type)
621 valid_p = type->valid_p (object);
624 break;
628 return valid_p;
632 /* Log error message with format string FORMAT and trailing arguments.
633 Signaling an error, e.g. when an image cannot be loaded, is not a
634 good idea because this would interrupt redisplay, and the error
635 message display would lead to another redisplay. This function
636 therefore simply displays a message. */
638 static void
639 image_error (const char *format, ...)
641 va_list ap;
642 va_start (ap, format);
643 vadd_to_log (format, ap);
644 va_end (ap);
647 static void
648 image_size_error (void)
650 image_error ("Invalid image size (see `%s')", "max-image-size");
654 /***********************************************************************
655 Image specifications
656 ***********************************************************************/
658 enum image_value_type
660 IMAGE_DONT_CHECK_VALUE_TYPE,
661 IMAGE_STRING_VALUE,
662 IMAGE_STRING_OR_NIL_VALUE,
663 IMAGE_SYMBOL_VALUE,
664 IMAGE_POSITIVE_INTEGER_VALUE,
665 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
666 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
667 IMAGE_ASCENT_VALUE,
668 IMAGE_INTEGER_VALUE,
669 IMAGE_FUNCTION_VALUE,
670 IMAGE_NUMBER_VALUE,
671 IMAGE_BOOL_VALUE
674 /* Structure used when parsing image specifications. */
676 struct image_keyword
678 /* Name of keyword. */
679 const char *name;
681 /* The type of value allowed. */
682 enum image_value_type type;
684 /* True means key must be present. */
685 bool mandatory_p;
687 /* Used to recognize duplicate keywords in a property list. */
688 int count;
690 /* The value that was found. */
691 Lisp_Object value;
695 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
696 has the format (image KEYWORD VALUE ...). One of the keyword/
697 value pairs must be `:type TYPE'. KEYWORDS is a vector of
698 image_keywords structures of size NKEYWORDS describing other
699 allowed keyword/value pairs. Value is true if SPEC is valid. */
701 static bool
702 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
703 int nkeywords, Lisp_Object type)
705 int i;
706 Lisp_Object plist;
708 if (!IMAGEP (spec))
709 return 0;
711 plist = XCDR (spec);
712 while (CONSP (plist))
714 Lisp_Object key, value;
716 /* First element of a pair must be a symbol. */
717 key = XCAR (plist);
718 plist = XCDR (plist);
719 if (!SYMBOLP (key))
720 return 0;
722 /* There must follow a value. */
723 if (!CONSP (plist))
724 return 0;
725 value = XCAR (plist);
726 plist = XCDR (plist);
728 /* Find key in KEYWORDS. Error if not found. */
729 for (i = 0; i < nkeywords; ++i)
730 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
731 break;
733 if (i == nkeywords)
734 continue;
736 /* Record that we recognized the keyword. If a keywords
737 was found more than once, it's an error. */
738 keywords[i].value = value;
739 if (keywords[i].count > 1)
740 return 0;
741 ++keywords[i].count;
743 /* Check type of value against allowed type. */
744 switch (keywords[i].type)
746 case IMAGE_STRING_VALUE:
747 if (!STRINGP (value))
748 return 0;
749 break;
751 case IMAGE_STRING_OR_NIL_VALUE:
752 if (!STRINGP (value) && !NILP (value))
753 return 0;
754 break;
756 case IMAGE_SYMBOL_VALUE:
757 if (!SYMBOLP (value))
758 return 0;
759 break;
761 case IMAGE_POSITIVE_INTEGER_VALUE:
762 if (! RANGED_INTEGERP (1, value, INT_MAX))
763 return 0;
764 break;
766 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
767 if (RANGED_INTEGERP (0, value, INT_MAX))
768 break;
769 if (CONSP (value)
770 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
771 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
772 break;
773 return 0;
775 case IMAGE_ASCENT_VALUE:
776 if (SYMBOLP (value) && EQ (value, Qcenter))
777 break;
778 else if (RANGED_INTEGERP (0, value, 100))
779 break;
780 return 0;
782 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
783 /* Unlike the other integer-related cases, this one does not
784 verify that VALUE fits in 'int'. This is because callers
785 want EMACS_INT. */
786 if (!INTEGERP (value) || XINT (value) < 0)
787 return 0;
788 break;
790 case IMAGE_DONT_CHECK_VALUE_TYPE:
791 break;
793 case IMAGE_FUNCTION_VALUE:
794 value = indirect_function (value);
795 if (!NILP (Ffunctionp (value)))
796 break;
797 return 0;
799 case IMAGE_NUMBER_VALUE:
800 if (! NUMBERP (value))
801 return 0;
802 break;
804 case IMAGE_INTEGER_VALUE:
805 if (! TYPE_RANGED_INTEGERP (int, value))
806 return 0;
807 break;
809 case IMAGE_BOOL_VALUE:
810 if (!NILP (value) && !EQ (value, Qt))
811 return 0;
812 break;
814 default:
815 emacs_abort ();
816 break;
819 if (EQ (key, QCtype) && !EQ (type, value))
820 return 0;
823 /* Check that all mandatory fields are present. */
824 for (i = 0; i < nkeywords; ++i)
825 if (keywords[i].mandatory_p && keywords[i].count == 0)
826 return 0;
828 return NILP (plist);
832 /* Return the value of KEY in image specification SPEC. Value is nil
833 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
834 was found in SPEC. */
836 static Lisp_Object
837 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
839 Lisp_Object tail;
841 eassert (valid_image_p (spec));
843 for (tail = XCDR (spec);
844 CONSP (tail) && CONSP (XCDR (tail));
845 tail = XCDR (XCDR (tail)))
847 if (EQ (XCAR (tail), key))
849 if (found)
850 *found = 1;
851 return XCAR (XCDR (tail));
855 if (found)
856 *found = 0;
857 return Qnil;
861 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
862 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
863 PIXELS non-nil means return the size in pixels, otherwise return the
864 size in canonical character units.
865 FRAME is the frame on which the image will be displayed. FRAME nil
866 or omitted means use the selected frame. */)
867 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
869 Lisp_Object size;
871 size = Qnil;
872 if (valid_image_p (spec))
874 struct frame *f = decode_window_system_frame (frame);
875 ptrdiff_t id = lookup_image (f, spec);
876 struct image *img = IMAGE_FROM_ID (f, id);
877 int width = img->width + 2 * img->hmargin;
878 int height = img->height + 2 * img->vmargin;
880 if (NILP (pixels))
881 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
882 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
883 else
884 size = Fcons (make_number (width), make_number (height));
886 else
887 error ("Invalid image specification");
889 return size;
893 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
894 doc: /* Return t if image SPEC has a mask bitmap.
895 FRAME is the frame on which the image will be displayed. FRAME nil
896 or omitted means use the selected frame. */)
897 (Lisp_Object spec, Lisp_Object frame)
899 Lisp_Object mask;
901 mask = Qnil;
902 if (valid_image_p (spec))
904 struct frame *f = decode_window_system_frame (frame);
905 ptrdiff_t id = lookup_image (f, spec);
906 struct image *img = IMAGE_FROM_ID (f, id);
907 if (img->mask)
908 mask = Qt;
910 else
911 error ("Invalid image specification");
913 return mask;
916 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
917 doc: /* Return metadata for image SPEC.
918 FRAME is the frame on which the image will be displayed. FRAME nil
919 or omitted means use the selected frame. */)
920 (Lisp_Object spec, Lisp_Object frame)
922 Lisp_Object ext;
924 ext = Qnil;
925 if (valid_image_p (spec))
927 struct frame *f = decode_window_system_frame (frame);
928 ptrdiff_t id = lookup_image (f, spec);
929 struct image *img = IMAGE_FROM_ID (f, id);
930 ext = img->lisp_data;
933 return ext;
937 /***********************************************************************
938 Image type independent image structures
939 ***********************************************************************/
941 #define MAX_IMAGE_SIZE 10.0
942 /* Allocate and return a new image structure for image specification
943 SPEC. SPEC has a hash value of HASH. */
945 static struct image *
946 make_image (Lisp_Object spec, EMACS_UINT hash)
948 struct image *img = xzalloc (sizeof *img);
949 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
951 eassert (valid_image_p (spec));
952 img->dependencies = NILP (file) ? Qnil : list1 (file);
953 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
954 eassert (img->type != NULL);
955 img->spec = spec;
956 img->lisp_data = Qnil;
957 img->ascent = DEFAULT_IMAGE_ASCENT;
958 img->hash = hash;
959 img->corners[BOT_CORNER] = -1; /* Full image */
960 return img;
964 /* Free image IMG which was used on frame F, including its resources. */
966 static void
967 free_image (struct frame *f, struct image *img)
969 if (img)
971 struct image_cache *c = FRAME_IMAGE_CACHE (f);
973 /* Remove IMG from the hash table of its cache. */
974 if (img->prev)
975 img->prev->next = img->next;
976 else
977 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
979 if (img->next)
980 img->next->prev = img->prev;
982 c->images[img->id] = NULL;
984 /* Windows NT redefines 'free', but in this file, we need to
985 avoid the redefinition. */
986 #ifdef WINDOWSNT
987 #undef free
988 #endif
989 /* Free resources, then free IMG. */
990 img->type->free (f, img);
991 xfree (img);
995 /* Return true if the given widths and heights are valid for display. */
997 static bool
998 check_image_size (struct frame *f, int width, int height)
1000 int w, h;
1002 if (width <= 0 || height <= 0)
1003 return 0;
1005 if (INTEGERP (Vmax_image_size))
1006 return (width <= XINT (Vmax_image_size)
1007 && height <= XINT (Vmax_image_size));
1008 else if (FLOATP (Vmax_image_size))
1010 if (f != NULL)
1012 w = FRAME_PIXEL_WIDTH (f);
1013 h = FRAME_PIXEL_HEIGHT (f);
1015 else
1016 w = h = 1024; /* Arbitrary size for unknown frame. */
1017 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1018 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1020 else
1021 return 1;
1024 /* Prepare image IMG for display on frame F. Must be called before
1025 drawing an image. */
1027 void
1028 prepare_image_for_display (struct frame *f, struct image *img)
1030 /* We're about to display IMG, so set its timestamp to `now'. */
1031 img->timestamp = current_timespec ();
1033 #ifndef USE_CAIRO
1034 /* If IMG doesn't have a pixmap yet, load it now, using the image
1035 type dependent loader function. */
1036 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1037 img->load_failed_p = ! img->type->load (f, img);
1039 #ifdef HAVE_X_WINDOWS
1040 if (!img->load_failed_p)
1042 block_input ();
1043 image_sync_to_pixmaps (f, img);
1044 unblock_input ();
1046 #endif
1047 #endif
1051 /* Value is the number of pixels for the ascent of image IMG when
1052 drawn in face FACE. */
1055 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1057 int height;
1058 int ascent;
1060 if (slice->height == img->height)
1061 height = img->height + img->vmargin;
1062 else if (slice->y == 0)
1063 height = slice->height + img->vmargin;
1064 else
1065 height = slice->height;
1067 if (img->ascent == CENTERED_IMAGE_ASCENT)
1069 if (face->font)
1071 #ifdef HAVE_NTGUI
1072 /* W32 specific version. Why?. ++kfs */
1073 ascent = height / 2 - (FONT_DESCENT (face->font)
1074 - FONT_BASE (face->font)) / 2;
1075 #else
1076 /* This expression is arranged so that if the image can't be
1077 exactly centered, it will be moved slightly up. This is
1078 because a typical font is `top-heavy' (due to the presence
1079 uppercase letters), so the image placement should err towards
1080 being top-heavy too. It also just generally looks better. */
1081 ascent = (height + FONT_BASE (face->font)
1082 - FONT_DESCENT (face->font) + 1) / 2;
1083 #endif /* HAVE_NTGUI */
1085 else
1086 ascent = height / 2;
1088 else
1089 ascent = height * (img->ascent / 100.0);
1091 return ascent;
1094 #ifdef USE_CAIRO
1095 static uint32_t
1096 xcolor_to_argb32 (XColor xc)
1098 return (0xff << 24) | ((xc.red / 256) << 16)
1099 | ((xc.green / 256) << 8) | (xc.blue / 256);
1102 static uint32_t
1103 get_spec_bg_or_alpha_as_argb (struct image *img,
1104 struct frame *f)
1106 uint32_t bgcolor = 0;
1107 XColor xbgcolor;
1108 Lisp_Object bg = image_spec_value (img->spec, QCbackground, NULL);
1110 if (STRINGP (bg) && XParseColor (FRAME_X_DISPLAY (f),
1111 FRAME_X_COLORMAP (f),
1112 SSDATA (bg),
1113 &xbgcolor))
1114 bgcolor = xcolor_to_argb32 (xbgcolor);
1116 return bgcolor;
1119 static void
1120 create_cairo_image_surface (struct image *img,
1121 unsigned char *data,
1122 int width,
1123 int height)
1125 cairo_surface_t *surface;
1126 cairo_format_t format = CAIRO_FORMAT_ARGB32;
1127 int stride = cairo_format_stride_for_width (format, width);
1128 surface = cairo_image_surface_create_for_data (data,
1129 format,
1130 width,
1131 height,
1132 stride);
1133 img->width = width;
1134 img->height = height;
1135 img->cr_data = surface;
1136 img->cr_data2 = data;
1137 img->pixmap = 0;
1139 #endif
1143 /* Image background colors. */
1145 /* Find the "best" corner color of a bitmap.
1146 On W32, XIMG is assumed to a device context with the bitmap selected. */
1148 static RGB_PIXEL_COLOR
1149 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1150 unsigned long width, unsigned long height)
1152 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1153 int i, best_count;
1155 if (corners && corners[BOT_CORNER] >= 0)
1157 /* Get the colors at the corner_pixels of ximg. */
1158 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1159 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1160 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1161 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1163 else
1165 /* Get the colors at the corner_pixels of ximg. */
1166 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1167 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1168 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1169 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1171 /* Choose the most frequently found color as background. */
1172 for (i = best_count = 0; i < 4; ++i)
1174 int j, n;
1176 for (j = n = 0; j < 4; ++j)
1177 if (corner_pixels[i] == corner_pixels[j])
1178 ++n;
1180 if (n > best_count)
1181 best = corner_pixels[i], best_count = n;
1184 return best;
1187 /* Portability macros */
1189 #ifdef HAVE_NTGUI
1191 #define Free_Pixmap(display, pixmap) \
1192 DeleteObject (pixmap)
1194 #elif defined (HAVE_NS)
1196 #define Free_Pixmap(display, pixmap) \
1197 ns_release_object (pixmap)
1199 #else
1201 #define Free_Pixmap(display, pixmap) \
1202 XFreePixmap (display, pixmap)
1204 #endif /* !HAVE_NTGUI && !HAVE_NS */
1207 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1208 it is guessed heuristically. If non-zero, XIMG is an existing
1209 XImage object (or device context with the image selected on W32) to
1210 use for the heuristic. */
1212 RGB_PIXEL_COLOR
1213 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1215 if (! img->background_valid)
1216 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1218 bool free_ximg = !ximg;
1219 #ifdef HAVE_NTGUI
1220 HGDIOBJ prev;
1221 #endif /* HAVE_NTGUI */
1223 if (free_ximg)
1224 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1226 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1228 if (free_ximg)
1229 image_unget_x_image_or_dc (img, 0, ximg, prev);
1231 img->background_valid = 1;
1234 return img->background;
1237 /* Return the `background_transparent' field of IMG. If IMG doesn't
1238 have one yet, it is guessed heuristically. If non-zero, MASK is an
1239 existing XImage object to use for the heuristic. */
1242 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1244 if (! img->background_transparent_valid)
1245 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1247 if (img->mask)
1249 bool free_mask = !mask;
1250 #ifdef HAVE_NTGUI
1251 HGDIOBJ prev;
1252 #endif /* HAVE_NTGUI */
1254 if (free_mask)
1255 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1257 img->background_transparent
1258 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1260 if (free_mask)
1261 image_unget_x_image_or_dc (img, 1, mask, prev);
1263 else
1264 img->background_transparent = 0;
1266 img->background_transparent_valid = 1;
1269 return img->background_transparent;
1272 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1273 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1275 /* Store F's background color into *BGCOLOR. */
1276 static void
1277 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1279 #ifndef HAVE_NS
1280 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1281 x_query_color (f, bgcolor);
1282 #else
1283 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1284 #endif
1287 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1289 /***********************************************************************
1290 Helper functions for X image types
1291 ***********************************************************************/
1293 /* Clear X resources of image IMG on frame F according to FLAGS.
1294 FLAGS is bitwise-or of the following masks:
1295 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1296 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1297 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1298 any. */
1300 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1301 #define CLEAR_IMAGE_MASK (1 << 1)
1302 #define CLEAR_IMAGE_COLORS (1 << 2)
1304 static void
1305 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1307 if (flags & CLEAR_IMAGE_PIXMAP)
1309 if (img->pixmap)
1311 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1312 img->pixmap = NO_PIXMAP;
1313 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1314 img->background_valid = 0;
1316 #ifdef HAVE_X_WINDOWS
1317 if (img->ximg)
1319 x_destroy_x_image (img->ximg);
1320 img->ximg = NULL;
1321 img->background_valid = 0;
1323 #endif
1326 if (flags & CLEAR_IMAGE_MASK)
1328 if (img->mask)
1330 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1331 img->mask = NO_PIXMAP;
1332 img->background_transparent_valid = 0;
1334 #ifdef HAVE_X_WINDOWS
1335 if (img->mask_img)
1337 x_destroy_x_image (img->mask_img);
1338 img->mask_img = NULL;
1339 img->background_transparent_valid = 0;
1341 #endif
1344 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1346 /* W32_TODO: color table support. */
1347 #ifdef HAVE_X_WINDOWS
1348 x_free_colors (f, img->colors, img->ncolors);
1349 #endif /* HAVE_X_WINDOWS */
1350 xfree (img->colors);
1351 img->colors = NULL;
1352 img->ncolors = 0;
1357 /* Free X resources of image IMG which is used on frame F. */
1359 static void
1360 x_clear_image (struct frame *f, struct image *img)
1362 block_input ();
1363 #ifdef USE_CAIRO
1364 if (img->cr_data)
1365 cairo_surface_destroy ((cairo_surface_t *)img->cr_data);
1366 if (img->cr_data2) xfree (img->cr_data2);
1367 #endif
1368 x_clear_image_1 (f, img,
1369 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1370 unblock_input ();
1374 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1375 cannot be allocated, use DFLT. Add a newly allocated color to
1376 IMG->colors, so that it can be freed again. Value is the pixel
1377 color. */
1379 static unsigned long
1380 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1381 unsigned long dflt)
1383 XColor color;
1384 unsigned long result;
1386 eassert (STRINGP (color_name));
1388 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1389 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1390 INT_MAX))
1392 /* This isn't called frequently so we get away with simply
1393 reallocating the color vector to the needed size, here. */
1394 ptrdiff_t ncolors = img->ncolors + 1;
1395 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1396 img->colors[ncolors - 1] = color.pixel;
1397 img->ncolors = ncolors;
1398 result = color.pixel;
1400 else
1401 result = dflt;
1403 return result;
1408 /***********************************************************************
1409 Image Cache
1410 ***********************************************************************/
1412 static void cache_image (struct frame *f, struct image *img);
1414 /* Return a new, initialized image cache that is allocated from the
1415 heap. Call free_image_cache to free an image cache. */
1417 struct image_cache *
1418 make_image_cache (void)
1420 struct image_cache *c = xmalloc (sizeof *c);
1422 c->size = 50;
1423 c->used = c->refcount = 0;
1424 c->images = xmalloc (c->size * sizeof *c->images);
1425 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1426 return c;
1430 /* Find an image matching SPEC in the cache, and return it. If no
1431 image is found, return NULL. */
1432 static struct image *
1433 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1435 struct image *img;
1436 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1437 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1439 if (!c) return NULL;
1441 /* If the image spec does not specify a background color, the cached
1442 image must have the same background color as the current frame.
1443 The foreground color must also match, for the sake of monochrome
1444 images.
1446 In fact, we could ignore the foreground color matching condition
1447 for color images, or if the image spec specifies :foreground;
1448 similarly we could ignore the background color matching condition
1449 for formats that don't use transparency (such as jpeg), or if the
1450 image spec specifies :background. However, the extra memory
1451 usage is probably negligible in practice, so we don't bother. */
1453 for (img = c->buckets[i]; img; img = img->next)
1454 if (img->hash == hash
1455 && !NILP (Fequal (img->spec, spec))
1456 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1457 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1458 break;
1459 return img;
1463 /* Search frame F for an image with spec SPEC, and free it. */
1465 static void
1466 uncache_image (struct frame *f, Lisp_Object spec)
1468 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1469 if (img)
1471 free_image (f, img);
1472 /* As display glyphs may still be referring to the image ID, we
1473 must garbage the frame (Bug#6426). */
1474 SET_FRAME_GARBAGED (f);
1479 /* Free image cache of frame F. Be aware that X frames share images
1480 caches. */
1482 void
1483 free_image_cache (struct frame *f)
1485 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1486 if (c)
1488 ptrdiff_t i;
1490 /* Cache should not be referenced by any frame when freed. */
1491 eassert (c->refcount == 0);
1493 for (i = 0; i < c->used; ++i)
1494 free_image (f, c->images[i]);
1495 xfree (c->images);
1496 xfree (c->buckets);
1497 xfree (c);
1498 FRAME_IMAGE_CACHE (f) = NULL;
1503 /* Clear image cache of frame F. FILTER=t means free all images.
1504 FILTER=nil means clear only images that haven't been
1505 displayed for some time.
1506 Else, only free the images which have FILTER in their `dependencies'.
1507 Should be called from time to time to reduce the number of loaded images.
1508 If image-cache-eviction-delay is non-nil, this frees images in the cache
1509 which weren't displayed for at least that many seconds. */
1511 static void
1512 clear_image_cache (struct frame *f, Lisp_Object filter)
1514 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1516 if (c)
1518 ptrdiff_t i, nfreed = 0;
1520 /* Block input so that we won't be interrupted by a SIGIO
1521 while being in an inconsistent state. */
1522 block_input ();
1524 if (!NILP (filter))
1526 /* Filter image cache. */
1527 for (i = 0; i < c->used; ++i)
1529 struct image *img = c->images[i];
1530 if (img && (EQ (Qt, filter)
1531 || !NILP (Fmember (filter, img->dependencies))))
1533 free_image (f, img);
1534 ++nfreed;
1538 else if (INTEGERP (Vimage_cache_eviction_delay))
1540 /* Free cache based on timestamp. */
1541 struct timespec old, t;
1542 double delay;
1543 ptrdiff_t nimages = 0;
1545 for (i = 0; i < c->used; ++i)
1546 if (c->images[i])
1547 nimages++;
1549 /* If the number of cached images has grown unusually large,
1550 decrease the cache eviction delay (Bug#6230). */
1551 delay = XINT (Vimage_cache_eviction_delay);
1552 if (nimages > 40)
1553 delay = 1600 * delay / nimages / nimages;
1554 delay = max (delay, 1);
1556 t = current_timespec ();
1557 old = timespec_sub (t, dtotimespec (delay));
1559 for (i = 0; i < c->used; ++i)
1561 struct image *img = c->images[i];
1562 if (img && timespec_cmp (img->timestamp, old) < 0)
1564 free_image (f, img);
1565 ++nfreed;
1570 /* We may be clearing the image cache because, for example,
1571 Emacs was iconified for a longer period of time. In that
1572 case, current matrices may still contain references to
1573 images freed above. So, clear these matrices. */
1574 if (nfreed)
1576 Lisp_Object tail, frame;
1578 FOR_EACH_FRAME (tail, frame)
1580 struct frame *fr = XFRAME (frame);
1581 if (FRAME_IMAGE_CACHE (fr) == c)
1582 clear_current_matrices (fr);
1585 windows_or_buffers_changed = 19;
1588 unblock_input ();
1592 void
1593 clear_image_caches (Lisp_Object filter)
1595 /* FIXME: We want to do
1596 * struct terminal *t;
1597 * for (t = terminal_list; t; t = t->next_terminal)
1598 * clear_image_cache (t, filter); */
1599 Lisp_Object tail, frame;
1600 FOR_EACH_FRAME (tail, frame)
1601 if (FRAME_WINDOW_P (XFRAME (frame)))
1602 clear_image_cache (XFRAME (frame), filter);
1605 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1606 0, 1, 0,
1607 doc: /* Clear the image cache.
1608 FILTER nil or a frame means clear all images in the selected frame.
1609 FILTER t means clear the image caches of all frames.
1610 Anything else, means only clear those images which refer to FILTER,
1611 which is then usually a filename. */)
1612 (Lisp_Object filter)
1614 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1615 clear_image_caches (filter);
1616 else
1617 clear_image_cache (decode_window_system_frame (filter), Qt);
1619 return Qnil;
1623 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1624 1, 2, 0,
1625 doc: /* Flush the image with specification SPEC on frame FRAME.
1626 This removes the image from the Emacs image cache. If SPEC specifies
1627 an image file, the next redisplay of this image will read from the
1628 current contents of that file.
1630 FRAME nil or omitted means use the selected frame.
1631 FRAME t means refresh the image on all frames. */)
1632 (Lisp_Object spec, Lisp_Object frame)
1634 if (!valid_image_p (spec))
1635 error ("Invalid image specification");
1637 if (EQ (frame, Qt))
1639 Lisp_Object tail;
1640 FOR_EACH_FRAME (tail, frame)
1642 struct frame *f = XFRAME (frame);
1643 if (FRAME_WINDOW_P (f))
1644 uncache_image (f, spec);
1647 else
1648 uncache_image (decode_window_system_frame (frame), spec);
1650 return Qnil;
1654 /* Compute masks and transform image IMG on frame F, as specified
1655 by the image's specification, */
1657 static void
1658 postprocess_image (struct frame *f, struct image *img)
1660 /* Manipulation of the image's mask. */
1661 if (img->pixmap)
1663 Lisp_Object conversion, spec;
1664 Lisp_Object mask;
1666 spec = img->spec;
1668 /* `:heuristic-mask t'
1669 `:mask heuristic'
1670 means build a mask heuristically.
1671 `:heuristic-mask (R G B)'
1672 `:mask (heuristic (R G B))'
1673 means build a mask from color (R G B) in the
1674 image.
1675 `:mask nil'
1676 means remove a mask, if any. */
1678 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1679 if (!NILP (mask))
1680 x_build_heuristic_mask (f, img, mask);
1681 else
1683 bool found_p;
1685 mask = image_spec_value (spec, QCmask, &found_p);
1687 if (EQ (mask, Qheuristic))
1688 x_build_heuristic_mask (f, img, Qt);
1689 else if (CONSP (mask)
1690 && EQ (XCAR (mask), Qheuristic))
1692 if (CONSP (XCDR (mask)))
1693 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1694 else
1695 x_build_heuristic_mask (f, img, XCDR (mask));
1697 else if (NILP (mask) && found_p && img->mask)
1698 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1702 /* Should we apply an image transformation algorithm? */
1703 conversion = image_spec_value (spec, QCconversion, NULL);
1704 if (EQ (conversion, Qdisabled))
1705 x_disable_image (f, img);
1706 else if (EQ (conversion, Qlaplace))
1707 x_laplace (f, img);
1708 else if (EQ (conversion, Qemboss))
1709 x_emboss (f, img);
1710 else if (CONSP (conversion)
1711 && EQ (XCAR (conversion), Qedge_detection))
1713 Lisp_Object tem;
1714 tem = XCDR (conversion);
1715 if (CONSP (tem))
1716 x_edge_detection (f, img,
1717 Fplist_get (tem, QCmatrix),
1718 Fplist_get (tem, QCcolor_adjustment));
1724 /* Return the id of image with Lisp specification SPEC on frame F.
1725 SPEC must be a valid Lisp image specification (see valid_image_p). */
1727 ptrdiff_t
1728 lookup_image (struct frame *f, Lisp_Object spec)
1730 struct image *img;
1731 EMACS_UINT hash;
1733 /* F must be a window-system frame, and SPEC must be a valid image
1734 specification. */
1735 eassert (FRAME_WINDOW_P (f));
1736 eassert (valid_image_p (spec));
1738 /* Look up SPEC in the hash table of the image cache. */
1739 hash = sxhash (spec, 0);
1740 img = search_image_cache (f, spec, hash);
1741 if (img && img->load_failed_p)
1743 free_image (f, img);
1744 img = NULL;
1747 /* If not found, create a new image and cache it. */
1748 if (img == NULL)
1750 block_input ();
1751 img = make_image (spec, hash);
1752 cache_image (f, img);
1753 img->load_failed_p = ! img->type->load (f, img);
1754 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1755 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1757 /* If we can't load the image, and we don't have a width and
1758 height, use some arbitrary width and height so that we can
1759 draw a rectangle for it. */
1760 if (img->load_failed_p)
1762 Lisp_Object value;
1764 value = image_spec_value (spec, QCwidth, NULL);
1765 img->width = (INTEGERP (value)
1766 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1767 value = image_spec_value (spec, QCheight, NULL);
1768 img->height = (INTEGERP (value)
1769 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1771 else
1773 /* Handle image type independent image attributes
1774 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1775 `:background COLOR'. */
1776 Lisp_Object ascent, margin, relief, bg;
1777 int relief_bound;
1779 ascent = image_spec_value (spec, QCascent, NULL);
1780 if (INTEGERP (ascent))
1781 img->ascent = XFASTINT (ascent);
1782 else if (EQ (ascent, Qcenter))
1783 img->ascent = CENTERED_IMAGE_ASCENT;
1785 margin = image_spec_value (spec, QCmargin, NULL);
1786 if (INTEGERP (margin))
1787 img->vmargin = img->hmargin = XFASTINT (margin);
1788 else if (CONSP (margin))
1790 img->hmargin = XFASTINT (XCAR (margin));
1791 img->vmargin = XFASTINT (XCDR (margin));
1794 relief = image_spec_value (spec, QCrelief, NULL);
1795 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1796 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1798 img->relief = XINT (relief);
1799 img->hmargin += eabs (img->relief);
1800 img->vmargin += eabs (img->relief);
1803 if (! img->background_valid)
1805 bg = image_spec_value (img->spec, QCbackground, NULL);
1806 if (!NILP (bg))
1808 img->background
1809 = x_alloc_image_color (f, img, bg,
1810 FRAME_BACKGROUND_PIXEL (f));
1811 img->background_valid = 1;
1815 /* Do image transformations and compute masks, unless we
1816 don't have the image yet. */
1817 if (!EQ (builtin_lisp_symbol (img->type->type), Qpostscript))
1818 postprocess_image (f, img);
1821 unblock_input ();
1824 /* We're using IMG, so set its timestamp to `now'. */
1825 img->timestamp = current_timespec ();
1827 /* Value is the image id. */
1828 return img->id;
1832 /* Cache image IMG in the image cache of frame F. */
1834 static void
1835 cache_image (struct frame *f, struct image *img)
1837 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1838 ptrdiff_t i;
1840 /* Find a free slot in c->images. */
1841 for (i = 0; i < c->used; ++i)
1842 if (c->images[i] == NULL)
1843 break;
1845 /* If no free slot found, maybe enlarge c->images. */
1846 if (i == c->used && c->used == c->size)
1847 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1849 /* Add IMG to c->images, and assign IMG an id. */
1850 c->images[i] = img;
1851 img->id = i;
1852 if (i == c->used)
1853 ++c->used;
1855 /* Add IMG to the cache's hash table. */
1856 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1857 img->next = c->buckets[i];
1858 if (img->next)
1859 img->next->prev = img;
1860 img->prev = NULL;
1861 c->buckets[i] = img;
1865 /* Call FN on every image in the image cache of frame F. Used to mark
1866 Lisp Objects in the image cache. */
1868 /* Mark Lisp objects in image IMG. */
1870 static void
1871 mark_image (struct image *img)
1873 mark_object (img->spec);
1874 mark_object (img->dependencies);
1876 if (!NILP (img->lisp_data))
1877 mark_object (img->lisp_data);
1881 void
1882 mark_image_cache (struct image_cache *c)
1884 if (c)
1886 ptrdiff_t i;
1887 for (i = 0; i < c->used; ++i)
1888 if (c->images[i])
1889 mark_image (c->images[i]);
1895 /***********************************************************************
1896 X / NS / W32 support code
1897 ***********************************************************************/
1899 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1900 windowing system.
1901 WIDTH and HEIGHT must both be positive.
1902 If XIMG is null, assume it is a bitmap. */
1903 static bool
1904 x_check_image_size (XImagePtr ximg, int width, int height)
1906 #ifdef HAVE_X_WINDOWS
1907 /* Respect Xlib's limits: it cannot deal with images that have more
1908 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1909 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1910 enum
1912 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1913 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1916 int bitmap_pad, depth, bytes_per_line;
1917 if (ximg)
1919 bitmap_pad = ximg->bitmap_pad;
1920 depth = ximg->depth;
1921 bytes_per_line = ximg->bytes_per_line;
1923 else
1925 bitmap_pad = 8;
1926 depth = 1;
1927 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1929 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1930 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1931 #else
1932 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1933 For now, assume that every image size is allowed on these systems. */
1934 return 1;
1935 #endif
1938 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1939 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1940 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1941 via xmalloc. Print error messages via image_error if an error
1942 occurs. Value is true if successful.
1944 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1945 should indicate the bit depth of the image. */
1947 static bool
1948 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1949 XImagePtr *ximg, Pixmap *pixmap)
1951 #ifdef HAVE_X_WINDOWS
1952 Display *display = FRAME_X_DISPLAY (f);
1953 Window window = FRAME_X_WINDOW (f);
1954 Screen *screen = FRAME_X_SCREEN (f);
1956 eassert (input_blocked_p ());
1958 if (depth <= 0)
1959 depth = DefaultDepthOfScreen (screen);
1960 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1961 depth, ZPixmap, 0, NULL, width, height,
1962 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1963 if (*ximg == NULL)
1965 image_error ("Unable to allocate X image");
1966 return 0;
1969 if (! x_check_image_size (*ximg, width, height))
1971 x_destroy_x_image (*ximg);
1972 *ximg = NULL;
1973 image_error ("Image too large (%dx%d)",
1974 make_number (width), make_number (height));
1975 return 0;
1978 /* Allocate image raster. */
1979 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1981 /* Allocate a pixmap of the same size. */
1982 *pixmap = XCreatePixmap (display, window, width, height, depth);
1983 if (*pixmap == NO_PIXMAP)
1985 x_destroy_x_image (*ximg);
1986 *ximg = NULL;
1987 image_error ("Unable to create X pixmap");
1988 return 0;
1991 return 1;
1992 #endif /* HAVE_X_WINDOWS */
1994 #ifdef HAVE_NTGUI
1996 BITMAPINFOHEADER *header;
1997 HDC hdc;
1998 int scanline_width_bits;
1999 int remainder;
2000 int palette_colors = 0;
2002 if (depth == 0)
2003 depth = 24;
2005 if (depth != 1 && depth != 4 && depth != 8
2006 && depth != 16 && depth != 24 && depth != 32)
2008 image_error ("Invalid image bit depth specified");
2009 return 0;
2012 scanline_width_bits = width * depth;
2013 remainder = scanline_width_bits % 32;
2015 if (remainder)
2016 scanline_width_bits += 32 - remainder;
2018 /* Bitmaps with a depth less than 16 need a palette. */
2019 /* BITMAPINFO structure already contains the first RGBQUAD. */
2020 if (depth < 16)
2021 palette_colors = 1 << (depth - 1);
2023 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2025 header = &(*ximg)->info.bmiHeader;
2026 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2027 header->biSize = sizeof (*header);
2028 header->biWidth = width;
2029 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2030 header->biPlanes = 1;
2031 header->biBitCount = depth;
2032 header->biCompression = BI_RGB;
2033 header->biClrUsed = palette_colors;
2035 /* TODO: fill in palette. */
2036 if (depth == 1)
2038 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2039 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2040 (*ximg)->info.bmiColors[0].rgbRed = 0;
2041 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2042 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2043 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2044 (*ximg)->info.bmiColors[1].rgbRed = 255;
2045 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2048 hdc = get_frame_dc (f);
2050 /* Create a DIBSection and raster array for the bitmap,
2051 and store its handle in *pixmap. */
2052 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2053 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2054 /* casting avoids a GCC warning */
2055 (void **)&((*ximg)->data), NULL, 0);
2057 /* Realize display palette and garbage all frames. */
2058 release_frame_dc (f, hdc);
2060 if (*pixmap == NULL)
2062 DWORD err = GetLastError ();
2063 Lisp_Object errcode;
2064 /* All system errors are < 10000, so the following is safe. */
2065 XSETINT (errcode, err);
2066 image_error ("Unable to create bitmap, error code %d", errcode);
2067 x_destroy_x_image (*ximg);
2068 *ximg = NULL;
2069 return 0;
2072 return 1;
2074 #endif /* HAVE_NTGUI */
2076 #ifdef HAVE_NS
2077 *pixmap = ns_image_for_XPM (width, height, depth);
2078 if (*pixmap == 0)
2080 *ximg = NULL;
2081 image_error ("Unable to allocate NSImage for XPM pixmap");
2082 return 0;
2084 *ximg = *pixmap;
2085 return 1;
2086 #endif
2090 /* Destroy XImage XIMG. Free XIMG->data. */
2092 static void
2093 x_destroy_x_image (XImagePtr ximg)
2095 eassert (input_blocked_p ());
2096 if (ximg)
2098 #ifdef HAVE_X_WINDOWS
2099 xfree (ximg->data);
2100 ximg->data = NULL;
2101 XDestroyImage (ximg);
2102 #endif /* HAVE_X_WINDOWS */
2103 #ifdef HAVE_NTGUI
2104 /* Data will be freed by DestroyObject. */
2105 ximg->data = NULL;
2106 xfree (ximg);
2107 #endif /* HAVE_NTGUI */
2108 #ifdef HAVE_NS
2109 ns_release_object (ximg);
2110 #endif /* HAVE_NS */
2115 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2116 are width and height of both the image and pixmap. */
2118 static void
2119 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2121 #ifdef HAVE_X_WINDOWS
2122 GC gc;
2124 eassert (input_blocked_p ());
2125 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2126 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2127 XFreeGC (FRAME_X_DISPLAY (f), gc);
2128 #endif /* HAVE_X_WINDOWS */
2130 #ifdef HAVE_NTGUI
2131 #if 0 /* I don't think this is necessary looking at where it is used. */
2132 HDC hdc = get_frame_dc (f);
2133 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2134 release_frame_dc (f, hdc);
2135 #endif
2136 #endif /* HAVE_NTGUI */
2138 #ifdef HAVE_NS
2139 eassert (ximg == pixmap);
2140 ns_retain_object (ximg);
2141 #endif
2144 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2145 with image_put_x_image. */
2147 static bool
2148 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2149 int width, int height, int depth,
2150 XImagePtr *ximg, bool mask_p)
2152 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2154 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2155 !mask_p ? &img->pixmap : &img->mask);
2158 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2159 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2160 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2161 On the other platforms, it puts XIMG into the pixmap, then frees
2162 the X image and its buffer. */
2164 static void
2165 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2166 bool mask_p)
2168 #ifdef HAVE_X_WINDOWS
2169 if (!mask_p)
2171 eassert (img->ximg == NULL);
2172 img->ximg = ximg;
2174 else
2176 eassert (img->mask_img == NULL);
2177 img->mask_img = ximg;
2179 #else
2180 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2181 img->width, img->height);
2182 x_destroy_x_image (ximg);
2183 #endif
2186 #ifdef HAVE_X_WINDOWS
2187 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2188 the X images and their buffers. */
2190 static void
2191 image_sync_to_pixmaps (struct frame *f, struct image *img)
2193 if (img->ximg)
2195 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2196 x_destroy_x_image (img->ximg);
2197 img->ximg = NULL;
2199 if (img->mask_img)
2201 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2202 x_destroy_x_image (img->mask_img);
2203 img->mask_img = NULL;
2206 #endif
2208 #ifdef HAVE_NTGUI
2209 /* Create a memory device context for IMG on frame F. It stores the
2210 currently selected GDI object into *PREV for future restoration by
2211 image_unget_x_image_or_dc. */
2213 static XImagePtr_or_DC
2214 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2215 HGDIOBJ *prev)
2217 HDC frame_dc = get_frame_dc (f);
2218 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2220 release_frame_dc (f, frame_dc);
2221 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2223 return ximg;
2226 static void
2227 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2228 XImagePtr_or_DC ximg, HGDIOBJ prev)
2230 SelectObject (ximg, prev);
2231 DeleteDC (ximg);
2233 #else /* !HAVE_NTGUI */
2234 /* Get the X image for IMG on frame F. The resulting X image data
2235 should be treated as read-only at least on X. */
2237 static XImagePtr
2238 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2240 #ifdef HAVE_X_WINDOWS
2241 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2243 if (ximg_in_img)
2244 return ximg_in_img;
2245 else
2246 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2247 0, 0, img->width, img->height, ~0, ZPixmap);
2248 #elif defined (HAVE_NS)
2249 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2251 ns_retain_object (pixmap);
2252 return pixmap;
2253 #endif
2256 static void
2257 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2259 #ifdef HAVE_X_WINDOWS
2260 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2262 if (ximg_in_img)
2263 eassert (ximg == ximg_in_img);
2264 else
2265 XDestroyImage (ximg);
2266 #elif defined (HAVE_NS)
2267 ns_release_object (ximg);
2268 #endif
2270 #endif /* !HAVE_NTGUI */
2273 /***********************************************************************
2274 File Handling
2275 ***********************************************************************/
2277 /* Find image file FILE. Look in data-directory/images, then
2278 x-bitmap-file-path. Value is the full name of the file
2279 found, or nil if not found. If PFD is nonnull store into *PFD a
2280 readable file descriptor for the file, opened in binary mode. If
2281 PFD is null, do not open the file. */
2283 static Lisp_Object
2284 x_find_image_fd (Lisp_Object file, int *pfd)
2286 Lisp_Object file_found, search_path;
2287 int fd;
2289 /* TODO I think this should use something like image-load-path
2290 instead. Unfortunately, that can contain non-string elements. */
2291 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2292 Vdata_directory),
2293 Vx_bitmap_file_path);
2295 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2296 fd = openp (search_path, file, Qnil, &file_found,
2297 pfd ? Qt : make_number (R_OK), false);
2298 if (fd < 0)
2299 return Qnil;
2300 if (pfd)
2301 *pfd = fd;
2302 return file_found;
2305 /* Find image file FILE. Look in data-directory/images, then
2306 x-bitmap-file-path. Value is the encoded full name of the file
2307 found, or nil if not found. */
2309 Lisp_Object
2310 x_find_image_file (Lisp_Object file)
2312 return x_find_image_fd (file, 0);
2315 /* Read FILE into memory. Value is a pointer to a buffer allocated
2316 with xmalloc holding FILE's contents. Value is null if an error
2317 occurred. FD is a file descriptor open for reading FILE. Set
2318 *SIZE to the size of the file. */
2320 static unsigned char *
2321 slurp_file (int fd, ptrdiff_t *size)
2323 FILE *fp = fdopen (fd, "rb");
2325 unsigned char *buf = NULL;
2326 struct stat st;
2328 if (fp)
2330 ptrdiff_t count = SPECPDL_INDEX ();
2331 record_unwind_protect_ptr (fclose_unwind, fp);
2333 if (fstat (fileno (fp), &st) == 0
2334 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2336 /* Report an error if we read past the purported EOF.
2337 This can happen if the file grows as we read it. */
2338 ptrdiff_t buflen = st.st_size;
2339 buf = xmalloc (buflen + 1);
2340 if (fread (buf, 1, buflen + 1, fp) == buflen)
2341 *size = buflen;
2342 else
2344 xfree (buf);
2345 buf = NULL;
2349 unbind_to (count, Qnil);
2352 return buf;
2357 /***********************************************************************
2358 XBM images
2359 ***********************************************************************/
2361 static bool xbm_load (struct frame *f, struct image *img);
2362 static bool xbm_image_p (Lisp_Object object);
2363 static bool xbm_file_p (Lisp_Object);
2366 /* Indices of image specification fields in xbm_format, below. */
2368 enum xbm_keyword_index
2370 XBM_TYPE,
2371 XBM_FILE,
2372 XBM_WIDTH,
2373 XBM_HEIGHT,
2374 XBM_DATA,
2375 XBM_FOREGROUND,
2376 XBM_BACKGROUND,
2377 XBM_ASCENT,
2378 XBM_MARGIN,
2379 XBM_RELIEF,
2380 XBM_ALGORITHM,
2381 XBM_HEURISTIC_MASK,
2382 XBM_MASK,
2383 XBM_LAST
2386 /* Vector of image_keyword structures describing the format
2387 of valid XBM image specifications. */
2389 static const struct image_keyword xbm_format[XBM_LAST] =
2391 {":type", IMAGE_SYMBOL_VALUE, 1},
2392 {":file", IMAGE_STRING_VALUE, 0},
2393 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2394 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2395 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2396 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2397 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2398 {":ascent", IMAGE_ASCENT_VALUE, 0},
2399 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2400 {":relief", IMAGE_INTEGER_VALUE, 0},
2401 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2402 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2403 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2406 /* Structure describing the image type XBM. */
2408 static struct image_type xbm_type =
2410 SYMBOL_INDEX (Qxbm),
2411 xbm_image_p,
2412 xbm_load,
2413 x_clear_image,
2414 NULL,
2415 NULL
2418 /* Tokens returned from xbm_scan. */
2420 enum xbm_token
2422 XBM_TK_IDENT = 256,
2423 XBM_TK_NUMBER
2427 /* Return true if OBJECT is a valid XBM-type image specification.
2428 A valid specification is a list starting with the symbol `image'
2429 The rest of the list is a property list which must contain an
2430 entry `:type xbm'.
2432 If the specification specifies a file to load, it must contain
2433 an entry `:file FILENAME' where FILENAME is a string.
2435 If the specification is for a bitmap loaded from memory it must
2436 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2437 WIDTH and HEIGHT are integers > 0. DATA may be:
2439 1. a string large enough to hold the bitmap data, i.e. it must
2440 have a size >= (WIDTH + 7) / 8 * HEIGHT
2442 2. a bool-vector of size >= WIDTH * HEIGHT
2444 3. a vector of strings or bool-vectors, one for each line of the
2445 bitmap.
2447 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2448 may not be specified in this case because they are defined in the
2449 XBM file.
2451 Both the file and data forms may contain the additional entries
2452 `:background COLOR' and `:foreground COLOR'. If not present,
2453 foreground and background of the frame on which the image is
2454 displayed is used. */
2456 static bool
2457 xbm_image_p (Lisp_Object object)
2459 struct image_keyword kw[XBM_LAST];
2461 memcpy (kw, xbm_format, sizeof kw);
2462 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2463 return 0;
2465 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2467 if (kw[XBM_FILE].count)
2469 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2470 return 0;
2472 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2474 /* In-memory XBM file. */
2475 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2476 return 0;
2478 else
2480 Lisp_Object data;
2481 int width, height;
2483 /* Entries for `:width', `:height' and `:data' must be present. */
2484 if (!kw[XBM_WIDTH].count
2485 || !kw[XBM_HEIGHT].count
2486 || !kw[XBM_DATA].count)
2487 return 0;
2489 data = kw[XBM_DATA].value;
2490 width = XFASTINT (kw[XBM_WIDTH].value);
2491 height = XFASTINT (kw[XBM_HEIGHT].value);
2493 /* Check type of data, and width and height against contents of
2494 data. */
2495 if (VECTORP (data))
2497 EMACS_INT i;
2499 /* Number of elements of the vector must be >= height. */
2500 if (ASIZE (data) < height)
2501 return 0;
2503 /* Each string or bool-vector in data must be large enough
2504 for one line of the image. */
2505 for (i = 0; i < height; ++i)
2507 Lisp_Object elt = AREF (data, i);
2509 if (STRINGP (elt))
2511 if (SCHARS (elt)
2512 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2513 return 0;
2515 else if (BOOL_VECTOR_P (elt))
2517 if (bool_vector_size (elt) < width)
2518 return 0;
2520 else
2521 return 0;
2524 else if (STRINGP (data))
2526 if (SCHARS (data)
2527 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2528 return 0;
2530 else if (BOOL_VECTOR_P (data))
2532 if (bool_vector_size (data) / height < width)
2533 return 0;
2535 else
2536 return 0;
2539 return 1;
2543 /* Scan a bitmap file. FP is the stream to read from. Value is
2544 either an enumerator from enum xbm_token, or a character for a
2545 single-character token, or 0 at end of file. If scanning an
2546 identifier, store the lexeme of the identifier in SVAL. If
2547 scanning a number, store its value in *IVAL. */
2549 static int
2550 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2552 unsigned int c;
2554 loop:
2556 /* Skip white space. */
2557 while (*s < end && (c = *(*s)++, c_isspace (c)))
2560 if (*s >= end)
2561 c = 0;
2562 else if (c_isdigit (c))
2564 int value = 0, digit;
2566 if (c == '0' && *s < end)
2568 c = *(*s)++;
2569 if (c == 'x' || c == 'X')
2571 while (*s < end)
2573 c = *(*s)++;
2574 if (c_isdigit (c))
2575 digit = c - '0';
2576 else if (c >= 'a' && c <= 'f')
2577 digit = c - 'a' + 10;
2578 else if (c >= 'A' && c <= 'F')
2579 digit = c - 'A' + 10;
2580 else
2581 break;
2582 value = 16 * value + digit;
2585 else if (c_isdigit (c))
2587 value = c - '0';
2588 while (*s < end
2589 && (c = *(*s)++, c_isdigit (c)))
2590 value = 8 * value + c - '0';
2593 else
2595 value = c - '0';
2596 while (*s < end
2597 && (c = *(*s)++, c_isdigit (c)))
2598 value = 10 * value + c - '0';
2601 if (*s < end)
2602 *s = *s - 1;
2603 *ival = value;
2604 c = XBM_TK_NUMBER;
2606 else if (c_isalpha (c) || c == '_')
2608 *sval++ = c;
2609 while (*s < end
2610 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2611 *sval++ = c;
2612 *sval = 0;
2613 if (*s < end)
2614 *s = *s - 1;
2615 c = XBM_TK_IDENT;
2617 else if (c == '/' && **s == '*')
2619 /* C-style comment. */
2620 ++*s;
2621 while (**s && (**s != '*' || *(*s + 1) != '/'))
2622 ++*s;
2623 if (**s)
2625 *s += 2;
2626 goto loop;
2630 return c;
2633 #ifdef HAVE_NTGUI
2635 /* Create a Windows bitmap from X bitmap data. */
2636 static HBITMAP
2637 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2639 static unsigned char swap_nibble[16]
2640 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2641 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2642 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2643 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2644 int i, j, w1, w2;
2645 unsigned char *bits, *p;
2646 HBITMAP bmp;
2648 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2649 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2650 bits = alloca (height * w2);
2651 memset (bits, 0, height * w2);
2652 for (i = 0; i < height; i++)
2654 p = bits + i*w2;
2655 for (j = 0; j < w1; j++)
2657 /* Bitswap XBM bytes to match how Windows does things. */
2658 unsigned char c = *data++;
2659 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2660 | (swap_nibble[(c>>4) & 0xf]));
2663 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2665 return bmp;
2668 static void
2669 convert_mono_to_color_image (struct frame *f, struct image *img,
2670 COLORREF foreground, COLORREF background)
2672 HDC hdc, old_img_dc, new_img_dc;
2673 HGDIOBJ old_prev, new_prev;
2674 HBITMAP new_pixmap;
2676 hdc = get_frame_dc (f);
2677 old_img_dc = CreateCompatibleDC (hdc);
2678 new_img_dc = CreateCompatibleDC (hdc);
2679 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2680 release_frame_dc (f, hdc);
2681 old_prev = SelectObject (old_img_dc, img->pixmap);
2682 new_prev = SelectObject (new_img_dc, new_pixmap);
2683 /* Windows convention for mono bitmaps is black = background,
2684 white = foreground. */
2685 SetTextColor (new_img_dc, background);
2686 SetBkColor (new_img_dc, foreground);
2688 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2689 0, 0, SRCCOPY);
2691 SelectObject (old_img_dc, old_prev);
2692 SelectObject (new_img_dc, new_prev);
2693 DeleteDC (old_img_dc);
2694 DeleteDC (new_img_dc);
2695 DeleteObject (img->pixmap);
2696 if (new_pixmap == 0)
2697 fprintf (stderr, "Failed to convert image to color.\n");
2698 else
2699 img->pixmap = new_pixmap;
2702 #define XBM_BIT_SHUFFLE(b) (~(b))
2704 #else
2706 #define XBM_BIT_SHUFFLE(b) (b)
2708 #endif /* HAVE_NTGUI */
2711 static void
2712 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2713 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2714 bool non_default_colors)
2716 #ifdef HAVE_NTGUI
2717 img->pixmap
2718 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2720 /* If colors were specified, transfer the bitmap to a color one. */
2721 if (non_default_colors)
2722 convert_mono_to_color_image (f, img, fg, bg);
2724 #elif defined (HAVE_NS)
2725 img->pixmap = ns_image_from_XBM (data, img->width, img->height, fg, bg);
2727 #else
2728 img->pixmap =
2729 (x_check_image_size (0, img->width, img->height)
2730 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2731 FRAME_X_WINDOW (f),
2732 data,
2733 img->width, img->height,
2734 fg, bg,
2735 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2736 : NO_PIXMAP);
2737 #endif /* !HAVE_NTGUI && !HAVE_NS */
2742 /* Replacement for XReadBitmapFileData which isn't available under old
2743 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2744 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2745 the image. Return in *DATA the bitmap data allocated with xmalloc.
2746 Value is true if successful. DATA null means just test if
2747 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2748 inhibit the call to image_error when the image size is invalid (the
2749 bitmap remains unread). */
2751 static bool
2752 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2753 int *width, int *height, char **data,
2754 bool inhibit_image_error)
2756 unsigned char *s = contents;
2757 char buffer[BUFSIZ];
2758 bool padding_p = 0;
2759 bool v10 = 0;
2760 int bytes_per_line, i, nbytes;
2761 char *p;
2762 int value;
2763 int LA1;
2765 #define match() \
2766 LA1 = xbm_scan (&s, end, buffer, &value)
2768 #define expect(TOKEN) \
2769 do \
2771 if (LA1 != (TOKEN)) \
2772 goto failure; \
2773 match (); \
2775 while (0)
2777 #define expect_ident(IDENT) \
2778 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2779 match (); \
2780 else \
2781 goto failure
2783 *width = *height = -1;
2784 if (data)
2785 *data = NULL;
2786 LA1 = xbm_scan (&s, end, buffer, &value);
2788 /* Parse defines for width, height and hot-spots. */
2789 while (LA1 == '#')
2791 match ();
2792 expect_ident ("define");
2793 expect (XBM_TK_IDENT);
2795 if (LA1 == XBM_TK_NUMBER)
2797 char *q = strrchr (buffer, '_');
2798 q = q ? q + 1 : buffer;
2799 if (strcmp (q, "width") == 0)
2800 *width = value;
2801 else if (strcmp (q, "height") == 0)
2802 *height = value;
2804 expect (XBM_TK_NUMBER);
2807 if (!check_image_size (f, *width, *height))
2809 if (!inhibit_image_error)
2810 image_size_error ();
2811 goto failure;
2813 else if (data == NULL)
2814 goto success;
2816 /* Parse bits. Must start with `static'. */
2817 expect_ident ("static");
2818 if (LA1 == XBM_TK_IDENT)
2820 if (strcmp (buffer, "unsigned") == 0)
2822 match ();
2823 expect_ident ("char");
2825 else if (strcmp (buffer, "short") == 0)
2827 match ();
2828 v10 = 1;
2829 if (*width % 16 && *width % 16 < 9)
2830 padding_p = 1;
2832 else if (strcmp (buffer, "char") == 0)
2833 match ();
2834 else
2835 goto failure;
2837 else
2838 goto failure;
2840 expect (XBM_TK_IDENT);
2841 expect ('[');
2842 expect (']');
2843 expect ('=');
2844 expect ('{');
2846 if (! x_check_image_size (0, *width, *height))
2848 if (!inhibit_image_error)
2849 image_error ("Image too large (%dx%d)",
2850 make_number (*width), make_number (*height));
2851 goto failure;
2853 bytes_per_line = (*width + 7) / 8 + padding_p;
2854 nbytes = bytes_per_line * *height;
2855 p = *data = xmalloc (nbytes);
2857 if (v10)
2859 for (i = 0; i < nbytes; i += 2)
2861 int val = value;
2862 expect (XBM_TK_NUMBER);
2864 *p++ = XBM_BIT_SHUFFLE (val);
2865 if (!padding_p || ((i + 2) % bytes_per_line))
2866 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2868 if (LA1 == ',' || LA1 == '}')
2869 match ();
2870 else
2871 goto failure;
2874 else
2876 for (i = 0; i < nbytes; ++i)
2878 int val = value;
2879 expect (XBM_TK_NUMBER);
2881 *p++ = XBM_BIT_SHUFFLE (val);
2883 if (LA1 == ',' || LA1 == '}')
2884 match ();
2885 else
2886 goto failure;
2890 success:
2891 return 1;
2893 failure:
2895 if (data && *data)
2897 xfree (*data);
2898 *data = NULL;
2900 return 0;
2902 #undef match
2903 #undef expect
2904 #undef expect_ident
2908 /* Load XBM image IMG which will be displayed on frame F from buffer
2909 CONTENTS. END is the end of the buffer. Value is true if
2910 successful. */
2912 static bool
2913 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2914 unsigned char *end)
2916 bool rc;
2917 char *data;
2918 bool success_p = 0;
2920 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2921 &data, 0);
2922 if (rc)
2924 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2925 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2926 bool non_default_colors = 0;
2927 Lisp_Object value;
2929 eassert (img->width > 0 && img->height > 0);
2931 /* Get foreground and background colors, maybe allocate colors. */
2932 value = image_spec_value (img->spec, QCforeground, NULL);
2933 if (!NILP (value))
2935 foreground = x_alloc_image_color (f, img, value, foreground);
2936 non_default_colors = 1;
2938 value = image_spec_value (img->spec, QCbackground, NULL);
2939 if (!NILP (value))
2941 background = x_alloc_image_color (f, img, value, background);
2942 img->background = background;
2943 img->background_valid = 1;
2944 non_default_colors = 1;
2947 Create_Pixmap_From_Bitmap_Data (f, img, data,
2948 foreground, background,
2949 non_default_colors);
2950 xfree (data);
2952 if (img->pixmap == NO_PIXMAP)
2954 x_clear_image (f, img);
2955 image_error ("Unable to create X pixmap for `%s'", img->spec);
2957 else
2958 success_p = 1;
2960 else
2961 image_error ("Error loading XBM image `%s'", img->spec);
2963 return success_p;
2967 /* Value is true if DATA looks like an in-memory XBM file. */
2969 static bool
2970 xbm_file_p (Lisp_Object data)
2972 int w, h;
2973 return (STRINGP (data)
2974 && xbm_read_bitmap_data (NULL, SDATA (data),
2975 (SDATA (data) + SBYTES (data)),
2976 &w, &h, NULL, 1));
2980 /* Fill image IMG which is used on frame F with pixmap data. Value is
2981 true if successful. */
2983 static bool
2984 xbm_load (struct frame *f, struct image *img)
2986 bool success_p = 0;
2987 Lisp_Object file_name;
2989 eassert (xbm_image_p (img->spec));
2991 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2992 file_name = image_spec_value (img->spec, QCfile, NULL);
2993 if (STRINGP (file_name))
2995 int fd;
2996 Lisp_Object file = x_find_image_fd (file_name, &fd);
2997 if (!STRINGP (file))
2999 image_error ("Cannot find image file `%s'", file_name);
3000 return 0;
3003 ptrdiff_t size;
3004 unsigned char *contents = slurp_file (fd, &size);
3005 if (contents == NULL)
3007 image_error ("Error loading XBM image `%s'", file);
3008 return 0;
3011 success_p = xbm_load_image (f, img, contents, contents + size);
3012 xfree (contents);
3014 else
3016 struct image_keyword fmt[XBM_LAST];
3017 Lisp_Object data;
3018 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3019 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3020 bool non_default_colors = 0;
3021 char *bits;
3022 bool parsed_p;
3023 bool in_memory_file_p = 0;
3025 /* See if data looks like an in-memory XBM file. */
3026 data = image_spec_value (img->spec, QCdata, NULL);
3027 in_memory_file_p = xbm_file_p (data);
3029 /* Parse the image specification. */
3030 memcpy (fmt, xbm_format, sizeof fmt);
3031 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3032 eassert (parsed_p);
3034 /* Get specified width, and height. */
3035 if (!in_memory_file_p)
3037 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3038 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3039 eassert (img->width > 0 && img->height > 0);
3040 if (!check_image_size (f, img->width, img->height))
3042 image_size_error ();
3043 return 0;
3047 /* Get foreground and background colors, maybe allocate colors. */
3048 if (fmt[XBM_FOREGROUND].count
3049 && STRINGP (fmt[XBM_FOREGROUND].value))
3051 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3052 foreground);
3053 non_default_colors = 1;
3056 if (fmt[XBM_BACKGROUND].count
3057 && STRINGP (fmt[XBM_BACKGROUND].value))
3059 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3060 background);
3061 non_default_colors = 1;
3064 if (in_memory_file_p)
3065 success_p = xbm_load_image (f, img, SDATA (data),
3066 (SDATA (data)
3067 + SBYTES (data)));
3068 else
3070 USE_SAFE_ALLOCA;
3072 if (VECTORP (data))
3074 int i;
3075 char *p;
3076 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3078 SAFE_NALLOCA (bits, nbytes, img->height);
3079 p = bits;
3080 for (i = 0; i < img->height; ++i, p += nbytes)
3082 Lisp_Object line = AREF (data, i);
3083 if (STRINGP (line))
3084 memcpy (p, SDATA (line), nbytes);
3085 else
3086 memcpy (p, bool_vector_data (line), nbytes);
3089 else if (STRINGP (data))
3090 bits = SSDATA (data);
3091 else
3092 bits = (char *) bool_vector_data (data);
3094 #ifdef HAVE_NTGUI
3096 char *invertedBits;
3097 int nbytes, i;
3098 /* Windows mono bitmaps are reversed compared with X. */
3099 invertedBits = bits;
3100 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3101 SAFE_NALLOCA (bits, nbytes, img->height);
3102 for (i = 0; i < nbytes; i++)
3103 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3105 #endif
3106 /* Create the pixmap. */
3108 if (x_check_image_size (0, img->width, img->height))
3109 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3110 foreground, background,
3111 non_default_colors);
3112 else
3113 img->pixmap = NO_PIXMAP;
3115 if (img->pixmap)
3116 success_p = 1;
3117 else
3119 image_error ("Unable to create pixmap for XBM image `%s'",
3120 img->spec);
3121 x_clear_image (f, img);
3124 SAFE_FREE ();
3128 return success_p;
3133 /***********************************************************************
3134 XPM images
3135 ***********************************************************************/
3137 #if defined (HAVE_XPM) || defined (HAVE_NS)
3139 static bool xpm_image_p (Lisp_Object object);
3140 static bool xpm_load (struct frame *f, struct image *img);
3142 #endif /* HAVE_XPM || HAVE_NS */
3144 #ifdef HAVE_XPM
3145 #ifdef HAVE_NTGUI
3146 /* Indicate to xpm.h that we don't have Xlib. */
3147 #define FOR_MSW
3148 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3149 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3150 #define XColor xpm_XColor
3151 #define XImage xpm_XImage
3152 #define Display xpm_Display
3153 #define PIXEL_ALREADY_TYPEDEFED
3154 #include "X11/xpm.h"
3155 #undef FOR_MSW
3156 #undef XColor
3157 #undef XImage
3158 #undef Display
3159 #undef PIXEL_ALREADY_TYPEDEFED
3160 #else
3161 #include "X11/xpm.h"
3162 #endif /* HAVE_NTGUI */
3163 #endif /* HAVE_XPM */
3165 #if defined (HAVE_XPM) || defined (HAVE_NS)
3167 /* Indices of image specification fields in xpm_format, below. */
3169 enum xpm_keyword_index
3171 XPM_TYPE,
3172 XPM_FILE,
3173 XPM_DATA,
3174 XPM_ASCENT,
3175 XPM_MARGIN,
3176 XPM_RELIEF,
3177 XPM_ALGORITHM,
3178 XPM_HEURISTIC_MASK,
3179 XPM_MASK,
3180 XPM_COLOR_SYMBOLS,
3181 XPM_BACKGROUND,
3182 XPM_LAST
3185 /* Vector of image_keyword structures describing the format
3186 of valid XPM image specifications. */
3188 static const struct image_keyword xpm_format[XPM_LAST] =
3190 {":type", IMAGE_SYMBOL_VALUE, 1},
3191 {":file", IMAGE_STRING_VALUE, 0},
3192 {":data", IMAGE_STRING_VALUE, 0},
3193 {":ascent", IMAGE_ASCENT_VALUE, 0},
3194 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3195 {":relief", IMAGE_INTEGER_VALUE, 0},
3196 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3197 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3198 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3199 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3200 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3203 #if defined HAVE_NTGUI && defined WINDOWSNT
3204 static bool init_xpm_functions (void);
3205 #else
3206 #define init_xpm_functions NULL
3207 #endif
3209 /* Structure describing the image type XPM. */
3211 static struct image_type xpm_type =
3213 SYMBOL_INDEX (Qxpm),
3214 xpm_image_p,
3215 xpm_load,
3216 x_clear_image,
3217 init_xpm_functions,
3218 NULL
3221 #ifdef HAVE_X_WINDOWS
3223 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3224 functions for allocating image colors. Our own functions handle
3225 color allocation failures more gracefully than the ones on the XPM
3226 lib. */
3228 #ifndef USE_CAIRO
3229 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3230 #define ALLOC_XPM_COLORS
3231 #endif
3232 #endif /* USE_CAIRO */
3233 #endif /* HAVE_X_WINDOWS */
3235 #ifdef ALLOC_XPM_COLORS
3237 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3238 XColor *, int);
3240 /* An entry in a hash table used to cache color definitions of named
3241 colors. This cache is necessary to speed up XPM image loading in
3242 case we do color allocations ourselves. Without it, we would need
3243 a call to XParseColor per pixel in the image. */
3245 struct xpm_cached_color
3247 /* Next in collision chain. */
3248 struct xpm_cached_color *next;
3250 /* Color definition (RGB and pixel color). */
3251 XColor color;
3253 /* Color name. */
3254 char name[FLEXIBLE_ARRAY_MEMBER];
3257 /* The hash table used for the color cache, and its bucket vector
3258 size. */
3260 #define XPM_COLOR_CACHE_BUCKETS 1001
3261 static struct xpm_cached_color **xpm_color_cache;
3263 /* Initialize the color cache. */
3265 static void
3266 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3268 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3269 xpm_color_cache = xzalloc (nbytes);
3270 init_color_table ();
3272 if (attrs->valuemask & XpmColorSymbols)
3274 int i;
3275 XColor color;
3277 for (i = 0; i < attrs->numsymbols; ++i)
3278 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3279 attrs->colorsymbols[i].value, &color))
3281 color.pixel = lookup_rgb_color (f, color.red, color.green,
3282 color.blue);
3283 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3288 /* Free the color cache. */
3290 static void
3291 xpm_free_color_cache (void)
3293 struct xpm_cached_color *p, *next;
3294 int i;
3296 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3297 for (p = xpm_color_cache[i]; p; p = next)
3299 next = p->next;
3300 xfree (p);
3303 xfree (xpm_color_cache);
3304 xpm_color_cache = NULL;
3305 free_color_table ();
3308 /* Return the bucket index for color named COLOR_NAME in the color
3309 cache. */
3311 static int
3312 xpm_color_bucket (char *color_name)
3314 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3315 return hash % XPM_COLOR_CACHE_BUCKETS;
3319 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3320 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3321 entry added. */
3323 static struct xpm_cached_color *
3324 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3326 size_t nbytes;
3327 struct xpm_cached_color *p;
3329 if (bucket < 0)
3330 bucket = xpm_color_bucket (color_name);
3332 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3333 p = xmalloc (nbytes);
3334 strcpy (p->name, color_name);
3335 p->color = *color;
3336 p->next = xpm_color_cache[bucket];
3337 xpm_color_cache[bucket] = p;
3338 return p;
3341 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3342 return the cached definition in *COLOR. Otherwise, make a new
3343 entry in the cache and allocate the color. Value is false if color
3344 allocation failed. */
3346 static bool
3347 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3349 struct xpm_cached_color *p;
3350 int h = xpm_color_bucket (color_name);
3352 for (p = xpm_color_cache[h]; p; p = p->next)
3353 if (strcmp (p->name, color_name) == 0)
3354 break;
3356 if (p != NULL)
3357 *color = p->color;
3358 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3359 color_name, color))
3361 color->pixel = lookup_rgb_color (f, color->red, color->green,
3362 color->blue);
3363 p = xpm_cache_color (f, color_name, color, h);
3365 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3366 with transparency, and it's useful. */
3367 else if (strcmp ("opaque", color_name) == 0)
3369 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3370 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3371 p = xpm_cache_color (f, color_name, color, h);
3374 return p != NULL;
3378 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3379 CLOSURE is a pointer to the frame on which we allocate the
3380 color. Return in *COLOR the allocated color. Value is non-zero
3381 if successful. */
3383 static int
3384 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3385 void *closure)
3387 return xpm_lookup_color (closure, color_name, color);
3391 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3392 is a pointer to the frame on which we allocate the color. Value is
3393 non-zero if successful. */
3395 static int
3396 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3398 return 1;
3401 #endif /* ALLOC_XPM_COLORS */
3404 #ifdef WINDOWSNT
3406 /* XPM library details. */
3408 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3409 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3410 (Display *, char *, xpm_XImage **,
3411 xpm_XImage **, XpmAttributes *));
3412 DEF_DLL_FN (int, XpmReadFileToImage,
3413 (Display *, char *, xpm_XImage **,
3414 xpm_XImage **, XpmAttributes *));
3415 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3417 static bool
3418 init_xpm_functions (void)
3420 HMODULE library;
3422 if (!(library = w32_delayed_load (Qxpm)))
3423 return 0;
3425 LOAD_DLL_FN (library, XpmFreeAttributes);
3426 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3427 LOAD_DLL_FN (library, XpmReadFileToImage);
3428 LOAD_DLL_FN (library, XImageFree);
3429 return 1;
3432 # undef XImageFree
3433 # undef XpmCreateImageFromBuffer
3434 # undef XpmFreeAttributes
3435 # undef XpmReadFileToImage
3437 # define XImageFree fn_XImageFree
3438 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3439 # define XpmFreeAttributes fn_XpmFreeAttributes
3440 # define XpmReadFileToImage fn_XpmReadFileToImage
3442 #endif /* WINDOWSNT */
3444 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3445 for XPM images. Such a list must consist of conses whose car and
3446 cdr are strings. */
3448 static bool
3449 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3451 while (CONSP (color_symbols))
3453 Lisp_Object sym = XCAR (color_symbols);
3454 if (!CONSP (sym)
3455 || !STRINGP (XCAR (sym))
3456 || !STRINGP (XCDR (sym)))
3457 break;
3458 color_symbols = XCDR (color_symbols);
3461 return NILP (color_symbols);
3465 /* Value is true if OBJECT is a valid XPM image specification. */
3467 static bool
3468 xpm_image_p (Lisp_Object object)
3470 struct image_keyword fmt[XPM_LAST];
3471 memcpy (fmt, xpm_format, sizeof fmt);
3472 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3473 /* Either `:file' or `:data' must be present. */
3474 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3475 /* Either no `:color-symbols' or it's a list of conses
3476 whose car and cdr are strings. */
3477 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3478 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3481 #endif /* HAVE_XPM || HAVE_NS */
3483 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3484 ptrdiff_t
3485 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3487 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3488 ptrdiff_t id;
3489 int rc;
3490 XpmAttributes attrs;
3491 Pixmap bitmap, mask;
3493 memset (&attrs, 0, sizeof attrs);
3495 attrs.visual = FRAME_X_VISUAL (f);
3496 attrs.colormap = FRAME_X_COLORMAP (f);
3497 attrs.valuemask |= XpmVisual;
3498 attrs.valuemask |= XpmColormap;
3500 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3501 (char **) bits, &bitmap, &mask, &attrs);
3502 if (rc != XpmSuccess)
3504 XpmFreeAttributes (&attrs);
3505 return -1;
3508 id = x_allocate_bitmap_record (f);
3509 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3510 dpyinfo->bitmaps[id - 1].have_mask = true;
3511 dpyinfo->bitmaps[id - 1].mask = mask;
3512 dpyinfo->bitmaps[id - 1].file = NULL;
3513 dpyinfo->bitmaps[id - 1].height = attrs.height;
3514 dpyinfo->bitmaps[id - 1].width = attrs.width;
3515 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3516 dpyinfo->bitmaps[id - 1].refcount = 1;
3518 XpmFreeAttributes (&attrs);
3519 return id;
3521 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3523 /* Load image IMG which will be displayed on frame F. Value is
3524 true if successful. */
3526 #ifdef HAVE_XPM
3528 static bool
3529 xpm_load (struct frame *f, struct image *img)
3531 int rc;
3532 XpmAttributes attrs;
3533 Lisp_Object specified_file, color_symbols;
3534 USE_SAFE_ALLOCA;
3536 #ifdef HAVE_NTGUI
3537 HDC hdc;
3538 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3539 #endif /* HAVE_NTGUI */
3541 /* Configure the XPM lib. Use the visual of frame F. Allocate
3542 close colors. Return colors allocated. */
3543 memset (&attrs, 0, sizeof attrs);
3545 #ifndef HAVE_NTGUI
3546 attrs.visual = FRAME_X_VISUAL (f);
3547 attrs.colormap = FRAME_X_COLORMAP (f);
3548 attrs.valuemask |= XpmVisual;
3549 attrs.valuemask |= XpmColormap;
3550 #endif /* HAVE_NTGUI */
3552 #ifdef ALLOC_XPM_COLORS
3553 /* Allocate colors with our own functions which handle
3554 failing color allocation more gracefully. */
3555 attrs.color_closure = f;
3556 attrs.alloc_color = xpm_alloc_color;
3557 attrs.free_colors = xpm_free_colors;
3558 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3559 #else /* not ALLOC_XPM_COLORS */
3560 /* Let the XPM lib allocate colors. */
3561 attrs.valuemask |= XpmReturnAllocPixels;
3562 #ifdef XpmAllocCloseColors
3563 attrs.alloc_close_colors = 1;
3564 attrs.valuemask |= XpmAllocCloseColors;
3565 #else /* not XpmAllocCloseColors */
3566 attrs.closeness = 600;
3567 attrs.valuemask |= XpmCloseness;
3568 #endif /* not XpmAllocCloseColors */
3569 #endif /* ALLOC_XPM_COLORS */
3571 /* If image specification contains symbolic color definitions, add
3572 these to `attrs'. */
3573 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3574 if (CONSP (color_symbols))
3576 Lisp_Object tail;
3577 XpmColorSymbol *xpm_syms;
3578 ptrdiff_t i, size;
3580 attrs.valuemask |= XpmColorSymbols;
3582 /* Count number of symbols. */
3583 attrs.numsymbols = 0;
3584 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3585 ++attrs.numsymbols;
3587 /* Allocate an XpmColorSymbol array. */
3588 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3589 size = attrs.numsymbols * sizeof *xpm_syms;
3590 memset (xpm_syms, 0, size);
3591 attrs.colorsymbols = xpm_syms;
3593 /* Fill the color symbol array. */
3594 for (tail = color_symbols, i = 0;
3595 CONSP (tail);
3596 ++i, tail = XCDR (tail))
3598 Lisp_Object name;
3599 Lisp_Object color;
3600 char *empty_string = (char *) "";
3602 if (!CONSP (XCAR (tail)))
3604 xpm_syms[i].name = empty_string;
3605 xpm_syms[i].value = empty_string;
3606 continue;
3608 name = XCAR (XCAR (tail));
3609 color = XCDR (XCAR (tail));
3610 if (STRINGP (name))
3611 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3612 else
3613 xpm_syms[i].name = empty_string;
3614 if (STRINGP (color))
3615 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3616 else
3617 xpm_syms[i].value = empty_string;
3621 /* Create a pixmap for the image, either from a file, or from a
3622 string buffer containing data in the same format as an XPM file. */
3623 #ifdef ALLOC_XPM_COLORS
3624 xpm_init_color_cache (f, &attrs);
3625 #endif
3627 specified_file = image_spec_value (img->spec, QCfile, NULL);
3629 #ifdef HAVE_NTGUI
3631 HDC frame_dc = get_frame_dc (f);
3632 hdc = CreateCompatibleDC (frame_dc);
3633 release_frame_dc (f, frame_dc);
3635 #endif /* HAVE_NTGUI */
3637 if (STRINGP (specified_file))
3639 Lisp_Object file = x_find_image_file (specified_file);
3640 if (!STRINGP (file))
3642 image_error ("Cannot find image file `%s'", specified_file);
3643 #ifdef ALLOC_XPM_COLORS
3644 xpm_free_color_cache ();
3645 #endif
3646 SAFE_FREE ();
3647 return 0;
3650 file = ENCODE_FILE (file);
3651 #ifdef HAVE_NTGUI
3652 #ifdef WINDOWSNT
3653 /* FILE is encoded in UTF-8, but image libraries on Windows
3654 support neither UTF-8 nor UTF-16 encoded file names. So we
3655 need to re-encode it in ANSI. */
3656 file = ansi_encode_filename (file);
3657 #endif
3658 /* XpmReadFileToPixmap is not available in the Windows port of
3659 libxpm. But XpmReadFileToImage almost does what we want. */
3660 rc = XpmReadFileToImage (&hdc, SDATA (file),
3661 &xpm_image, &xpm_mask,
3662 &attrs);
3663 #else
3664 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3665 &img->ximg, &img->mask_img,
3666 &attrs);
3667 #endif /* HAVE_NTGUI */
3669 else
3671 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3672 if (!STRINGP (buffer))
3674 image_error ("Invalid image data `%s'", buffer);
3675 #ifdef ALLOC_XPM_COLORS
3676 xpm_free_color_cache ();
3677 #endif
3678 SAFE_FREE ();
3679 return 0;
3681 #ifdef HAVE_NTGUI
3682 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3683 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3684 rc = XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3685 &xpm_image, &xpm_mask,
3686 &attrs);
3687 #else
3688 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3689 &img->ximg, &img->mask_img,
3690 &attrs);
3691 #endif /* HAVE_NTGUI */
3694 #ifdef USE_CAIRO
3695 // Load very specific Xpm:s.
3696 if (rc == XpmSuccess
3697 && img->ximg->format == ZPixmap
3698 && img->ximg->bits_per_pixel == 32
3699 && (! img->mask_img || img->mask_img->bits_per_pixel == 1))
3701 int width = img->ximg->width;
3702 int height = img->ximg->height;
3703 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
3704 int i;
3705 uint32_t *od = (uint32_t *)data;
3706 uint32_t *id = (uint32_t *)img->ximg->data;
3707 char *mid = img->mask_img ? img->mask_img->data : 0;
3708 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
3710 for (i = 0; i < height; ++i)
3712 int k;
3713 for (k = 0; k < width; ++k)
3715 int idx = i * img->ximg->bytes_per_line/4 + k;
3716 int maskidx = mid ? i * img->mask_img->bytes_per_line + k/8 : 0;
3717 int mask = mid ? mid[maskidx] & (1 << (k % 8)) : 1;
3719 if (mask) od[idx] = id[idx] + 0xff000000; // ff => full alpha
3720 else od[idx] = bgcolor;
3724 create_cairo_image_surface (img, data, width, height);
3726 else
3728 rc = XpmFileInvalid;
3729 x_clear_image (f, img);
3731 #else
3732 #ifdef HAVE_X_WINDOWS
3733 if (rc == XpmSuccess)
3735 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3736 img->ximg->width, img->ximg->height,
3737 img->ximg->depth);
3738 if (img->pixmap == NO_PIXMAP)
3740 x_clear_image (f, img);
3741 rc = XpmNoMemory;
3743 else if (img->mask_img)
3745 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3746 img->mask_img->width,
3747 img->mask_img->height,
3748 img->mask_img->depth);
3749 if (img->mask == NO_PIXMAP)
3751 x_clear_image (f, img);
3752 rc = XpmNoMemory;
3756 #endif
3757 #endif /* ! USE_CAIRO */
3759 if (rc == XpmSuccess)
3761 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3762 img->colors = colors_in_color_table (&img->ncolors);
3763 #else /* not ALLOC_XPM_COLORS */
3764 int i;
3766 #ifdef HAVE_NTGUI
3767 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3768 plus some duplicate attributes. */
3769 if (xpm_image && xpm_image->bitmap)
3771 img->pixmap = xpm_image->bitmap;
3772 /* XImageFree in libXpm frees XImage struct without destroying
3773 the bitmap, which is what we want. */
3774 XImageFree (xpm_image);
3776 if (xpm_mask && xpm_mask->bitmap)
3778 /* The mask appears to be inverted compared with what we expect.
3779 TODO: invert our expectations. See other places where we
3780 have to invert bits because our idea of masks is backwards. */
3781 HGDIOBJ old_obj;
3782 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3784 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3785 SelectObject (hdc, old_obj);
3787 img->mask = xpm_mask->bitmap;
3788 XImageFree (xpm_mask);
3789 DeleteDC (hdc);
3792 DeleteDC (hdc);
3793 #endif /* HAVE_NTGUI */
3795 /* Remember allocated colors. */
3796 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3797 img->ncolors = attrs.nalloc_pixels;
3798 for (i = 0; i < attrs.nalloc_pixels; ++i)
3800 img->colors[i] = attrs.alloc_pixels[i];
3801 #ifdef DEBUG_X_COLORS
3802 register_color (img->colors[i]);
3803 #endif
3805 #endif /* not ALLOC_XPM_COLORS */
3807 img->width = attrs.width;
3808 img->height = attrs.height;
3809 eassert (img->width > 0 && img->height > 0);
3811 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3812 XpmFreeAttributes (&attrs);
3814 #ifdef HAVE_X_WINDOWS
3815 /* Maybe fill in the background field while we have ximg handy. */
3816 IMAGE_BACKGROUND (img, f, img->ximg);
3817 if (img->mask_img)
3818 /* Fill in the background_transparent field while we have the
3819 mask handy. */
3820 image_background_transparent (img, f, img->mask_img);
3821 #endif
3823 else
3825 #ifdef HAVE_NTGUI
3826 DeleteDC (hdc);
3827 #endif /* HAVE_NTGUI */
3829 switch (rc)
3831 case XpmOpenFailed:
3832 image_error ("Error opening XPM file (%s)", img->spec);
3833 break;
3835 case XpmFileInvalid:
3836 image_error ("Invalid XPM file (%s)", img->spec);
3837 break;
3839 case XpmNoMemory:
3840 image_error ("Out of memory (%s)", img->spec);
3841 break;
3843 case XpmColorFailed:
3844 image_error ("Color allocation error (%s)", img->spec);
3845 break;
3847 default:
3848 image_error ("Unknown error (%s)", img->spec);
3849 break;
3853 #ifdef ALLOC_XPM_COLORS
3854 xpm_free_color_cache ();
3855 #endif
3856 SAFE_FREE ();
3857 return rc == XpmSuccess;
3860 #endif /* HAVE_XPM */
3862 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3864 /* XPM support functions for NS where libxpm is not available.
3865 Only XPM version 3 (without any extensions) is supported. */
3867 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3868 int, Lisp_Object);
3869 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3870 const unsigned char *, int);
3871 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3872 int, Lisp_Object);
3873 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3874 const unsigned char *, int);
3876 /* Tokens returned from xpm_scan. */
3878 enum xpm_token
3880 XPM_TK_IDENT = 256,
3881 XPM_TK_STRING,
3882 XPM_TK_EOF
3885 /* Scan an XPM data and return a character (< 256) or a token defined
3886 by enum xpm_token above. *S and END are the start (inclusive) and
3887 the end (exclusive) addresses of the data, respectively. Advance
3888 *S while scanning. If token is either XPM_TK_IDENT or
3889 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3890 length of the corresponding token, respectively. */
3892 static int
3893 xpm_scan (const unsigned char **s,
3894 const unsigned char *end,
3895 const unsigned char **beg,
3896 ptrdiff_t *len)
3898 int c;
3900 while (*s < end)
3902 /* Skip white-space. */
3903 while (*s < end && (c = *(*s)++, c_isspace (c)))
3906 /* gnus-pointer.xpm uses '-' in its identifier.
3907 sb-dir-plus.xpm uses '+' in its identifier. */
3908 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3910 *beg = *s - 1;
3911 while (*s < end
3912 && (c = **s, c_isalnum (c)
3913 || c == '_' || c == '-' || c == '+'))
3914 ++*s;
3915 *len = *s - *beg;
3916 return XPM_TK_IDENT;
3918 else if (c == '"')
3920 *beg = *s;
3921 while (*s < end && **s != '"')
3922 ++*s;
3923 *len = *s - *beg;
3924 if (*s < end)
3925 ++*s;
3926 return XPM_TK_STRING;
3928 else if (c == '/')
3930 if (*s < end && **s == '*')
3932 /* C-style comment. */
3933 ++*s;
3936 while (*s < end && *(*s)++ != '*')
3939 while (*s < end && **s != '/');
3940 if (*s < end)
3941 ++*s;
3943 else
3944 return c;
3946 else
3947 return c;
3950 return XPM_TK_EOF;
3953 /* Functions for color table lookup in XPM data. A key is a string
3954 specifying the color of each pixel in XPM data. A value is either
3955 an integer that specifies a pixel color, Qt that specifies
3956 transparency, or Qnil for the unspecified color. If the length of
3957 the key string is one, a vector is used as a table. Otherwise, a
3958 hash table is used. */
3960 static Lisp_Object
3961 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3962 const unsigned char *,
3963 int,
3964 Lisp_Object),
3965 Lisp_Object (**get_func) (Lisp_Object,
3966 const unsigned char *,
3967 int))
3969 *put_func = xpm_put_color_table_v;
3970 *get_func = xpm_get_color_table_v;
3971 return Fmake_vector (make_number (256), Qnil);
3974 static void
3975 xpm_put_color_table_v (Lisp_Object color_table,
3976 const unsigned char *chars_start,
3977 int chars_len,
3978 Lisp_Object color)
3980 ASET (color_table, *chars_start, color);
3983 static Lisp_Object
3984 xpm_get_color_table_v (Lisp_Object color_table,
3985 const unsigned char *chars_start,
3986 int chars_len)
3988 return AREF (color_table, *chars_start);
3991 static Lisp_Object
3992 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3993 const unsigned char *,
3994 int,
3995 Lisp_Object),
3996 Lisp_Object (**get_func) (Lisp_Object,
3997 const unsigned char *,
3998 int))
4000 *put_func = xpm_put_color_table_h;
4001 *get_func = xpm_get_color_table_h;
4002 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
4003 make_float (DEFAULT_REHASH_SIZE),
4004 make_float (DEFAULT_REHASH_THRESHOLD),
4005 Qnil);
4008 static void
4009 xpm_put_color_table_h (Lisp_Object color_table,
4010 const unsigned char *chars_start,
4011 int chars_len,
4012 Lisp_Object color)
4014 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4015 EMACS_UINT hash_code;
4016 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4018 hash_lookup (table, chars, &hash_code);
4019 hash_put (table, chars, color, hash_code);
4022 static Lisp_Object
4023 xpm_get_color_table_h (Lisp_Object color_table,
4024 const unsigned char *chars_start,
4025 int chars_len)
4027 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4028 ptrdiff_t i =
4029 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
4031 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4034 enum xpm_color_key {
4035 XPM_COLOR_KEY_S,
4036 XPM_COLOR_KEY_M,
4037 XPM_COLOR_KEY_G4,
4038 XPM_COLOR_KEY_G,
4039 XPM_COLOR_KEY_C
4042 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4044 static int
4045 xpm_str_to_color_key (const char *s)
4047 int i;
4049 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
4050 if (strcmp (xpm_color_key_strings[i], s) == 0)
4051 return i;
4052 return -1;
4055 static bool
4056 xpm_load_image (struct frame *f,
4057 struct image *img,
4058 const unsigned char *contents,
4059 const unsigned char *end)
4061 const unsigned char *s = contents, *beg, *str;
4062 unsigned char buffer[BUFSIZ];
4063 int width, height, x, y;
4064 int num_colors, chars_per_pixel;
4065 ptrdiff_t len;
4066 int LA1;
4067 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4068 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
4069 Lisp_Object frame, color_symbols, color_table;
4070 int best_key;
4071 bool have_mask = false;
4072 XImagePtr ximg = NULL, mask_img = NULL;
4074 #define match() \
4075 LA1 = xpm_scan (&s, end, &beg, &len)
4077 #define expect(TOKEN) \
4078 do \
4080 if (LA1 != (TOKEN)) \
4081 goto failure; \
4082 match (); \
4084 while (0)
4086 #define expect_ident(IDENT) \
4087 if (LA1 == XPM_TK_IDENT \
4088 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4089 match (); \
4090 else \
4091 goto failure
4093 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4094 goto failure;
4095 s += 9;
4096 match ();
4097 expect_ident ("static");
4098 expect_ident ("char");
4099 expect ('*');
4100 expect (XPM_TK_IDENT);
4101 expect ('[');
4102 expect (']');
4103 expect ('=');
4104 expect ('{');
4105 expect (XPM_TK_STRING);
4106 if (len >= BUFSIZ)
4107 goto failure;
4108 memcpy (buffer, beg, len);
4109 buffer[len] = '\0';
4110 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4111 &num_colors, &chars_per_pixel) != 4
4112 || width <= 0 || height <= 0
4113 || num_colors <= 0 || chars_per_pixel <= 0)
4114 goto failure;
4116 if (!check_image_size (f, width, height))
4118 image_size_error ();
4119 goto failure;
4122 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4123 #ifndef HAVE_NS
4124 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4125 &mask_img, 1)
4126 #endif
4129 image_error ("Image too large");
4130 goto failure;
4133 expect (',');
4135 XSETFRAME (frame, f);
4136 if (!NILP (Fxw_display_color_p (frame)))
4137 best_key = XPM_COLOR_KEY_C;
4138 else if (!NILP (Fx_display_grayscale_p (frame)))
4139 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4140 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4141 else
4142 best_key = XPM_COLOR_KEY_M;
4144 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4145 if (chars_per_pixel == 1)
4146 color_table = xpm_make_color_table_v (&put_color_table,
4147 &get_color_table);
4148 else
4149 color_table = xpm_make_color_table_h (&put_color_table,
4150 &get_color_table);
4152 while (num_colors-- > 0)
4154 char *color, *max_color;
4155 int key, next_key, max_key = 0;
4156 Lisp_Object symbol_color = Qnil, color_val;
4157 XColor cdef;
4159 expect (XPM_TK_STRING);
4160 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4161 goto failure;
4162 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4163 buffer[len - chars_per_pixel] = '\0';
4165 str = strtok (buffer, " \t");
4166 if (str == NULL)
4167 goto failure;
4168 key = xpm_str_to_color_key (str);
4169 if (key < 0)
4170 goto failure;
4173 color = strtok (NULL, " \t");
4174 if (color == NULL)
4175 goto failure;
4177 while ((str = strtok (NULL, " \t")) != NULL)
4179 next_key = xpm_str_to_color_key (str);
4180 if (next_key >= 0)
4181 break;
4182 color[strlen (color)] = ' ';
4185 if (key == XPM_COLOR_KEY_S)
4187 if (NILP (symbol_color))
4188 symbol_color = build_string (color);
4190 else if (max_key < key && key <= best_key)
4192 max_key = key;
4193 max_color = color;
4195 key = next_key;
4197 while (str);
4199 color_val = Qnil;
4200 if (!NILP (color_symbols) && !NILP (symbol_color))
4202 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4204 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4206 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4207 color_val = Qt;
4208 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4209 &cdef, 0))
4210 color_val = make_number (cdef.pixel);
4213 if (NILP (color_val) && max_key > 0)
4215 if (xstrcasecmp (max_color, "None") == 0)
4216 color_val = Qt;
4217 else if (x_defined_color (f, max_color, &cdef, 0))
4218 color_val = make_number (cdef.pixel);
4220 if (!NILP (color_val))
4221 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4223 expect (',');
4226 for (y = 0; y < height; y++)
4228 expect (XPM_TK_STRING);
4229 str = beg;
4230 if (len < width * chars_per_pixel)
4231 goto failure;
4232 for (x = 0; x < width; x++, str += chars_per_pixel)
4234 Lisp_Object color_val =
4235 (*get_color_table) (color_table, str, chars_per_pixel);
4237 XPutPixel (ximg, x, y,
4238 (INTEGERP (color_val) ? XINT (color_val)
4239 : FRAME_FOREGROUND_PIXEL (f)));
4240 #ifndef HAVE_NS
4241 XPutPixel (mask_img, x, y,
4242 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4243 : (have_mask = true, PIX_MASK_RETAIN)));
4244 #else
4245 if (EQ (color_val, Qt))
4246 ns_set_alpha (ximg, x, y, 0);
4247 #endif
4249 if (y + 1 < height)
4250 expect (',');
4253 img->width = width;
4254 img->height = height;
4256 /* Maybe fill in the background field while we have ximg handy. */
4257 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4258 IMAGE_BACKGROUND (img, f, ximg);
4260 image_put_x_image (f, img, ximg, 0);
4261 #ifndef HAVE_NS
4262 if (have_mask)
4264 /* Fill in the background_transparent field while we have the
4265 mask handy. */
4266 image_background_transparent (img, f, mask_img);
4268 image_put_x_image (f, img, mask_img, 1);
4270 else
4272 x_destroy_x_image (mask_img);
4273 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4275 #endif
4276 return 1;
4278 failure:
4279 image_error ("Invalid XPM file (%s)", img->spec);
4280 x_destroy_x_image (ximg);
4281 x_destroy_x_image (mask_img);
4282 x_clear_image (f, img);
4283 return 0;
4285 #undef match
4286 #undef expect
4287 #undef expect_ident
4290 static bool
4291 xpm_load (struct frame *f,
4292 struct image *img)
4294 bool success_p = 0;
4295 Lisp_Object file_name;
4297 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4298 file_name = image_spec_value (img->spec, QCfile, NULL);
4299 if (STRINGP (file_name))
4301 int fd;
4302 Lisp_Object file = x_find_image_fd (file_name, &fd);
4303 if (!STRINGP (file))
4305 image_error ("Cannot find image file `%s'", file_name);
4306 return 0;
4309 ptrdiff_t size;
4310 unsigned char *contents = slurp_file (fd, &size);
4311 if (contents == NULL)
4313 image_error ("Error loading XPM image `%s'", file);
4314 return 0;
4317 success_p = xpm_load_image (f, img, contents, contents + size);
4318 xfree (contents);
4320 else
4322 Lisp_Object data;
4324 data = image_spec_value (img->spec, QCdata, NULL);
4325 if (!STRINGP (data))
4327 image_error ("Invalid image data `%s'", data);
4328 return 0;
4330 success_p = xpm_load_image (f, img, SDATA (data),
4331 SDATA (data) + SBYTES (data));
4334 return success_p;
4337 #endif /* HAVE_NS && !HAVE_XPM */
4341 /***********************************************************************
4342 Color table
4343 ***********************************************************************/
4345 #ifdef COLOR_TABLE_SUPPORT
4347 /* An entry in the color table mapping an RGB color to a pixel color. */
4349 struct ct_color
4351 int r, g, b;
4352 unsigned long pixel;
4354 /* Next in color table collision list. */
4355 struct ct_color *next;
4358 /* The bucket vector size to use. Must be prime. */
4360 #define CT_SIZE 101
4362 /* Value is a hash of the RGB color given by R, G, and B. */
4364 static unsigned
4365 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4367 return (r << 16) ^ (g << 8) ^ b;
4370 /* The color hash table. */
4372 static struct ct_color **ct_table;
4374 /* Number of entries in the color table. */
4376 static int ct_colors_allocated;
4377 enum
4379 ct_colors_allocated_max =
4380 min (INT_MAX,
4381 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4384 /* Initialize the color table. */
4386 static void
4387 init_color_table (void)
4389 int size = CT_SIZE * sizeof (*ct_table);
4390 ct_table = xzalloc (size);
4391 ct_colors_allocated = 0;
4395 /* Free memory associated with the color table. */
4397 static void
4398 free_color_table (void)
4400 int i;
4401 struct ct_color *p, *next;
4403 for (i = 0; i < CT_SIZE; ++i)
4404 for (p = ct_table[i]; p; p = next)
4406 next = p->next;
4407 xfree (p);
4410 xfree (ct_table);
4411 ct_table = NULL;
4415 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4416 entry for that color already is in the color table, return the
4417 pixel color of that entry. Otherwise, allocate a new color for R,
4418 G, B, and make an entry in the color table. */
4420 static unsigned long
4421 lookup_rgb_color (struct frame *f, int r, int g, int b)
4423 unsigned hash = ct_hash_rgb (r, g, b);
4424 int i = hash % CT_SIZE;
4425 struct ct_color *p;
4426 Display_Info *dpyinfo;
4428 /* Handle TrueColor visuals specially, which improves performance by
4429 two orders of magnitude. Freeing colors on TrueColor visuals is
4430 a nop, and pixel colors specify RGB values directly. See also
4431 the Xlib spec, chapter 3.1. */
4432 dpyinfo = FRAME_DISPLAY_INFO (f);
4433 if (dpyinfo->red_bits > 0)
4435 unsigned long pr, pg, pb;
4437 /* Apply gamma-correction like normal color allocation does. */
4438 if (f->gamma)
4440 XColor color;
4441 color.red = r, color.green = g, color.blue = b;
4442 gamma_correct (f, &color);
4443 r = color.red, g = color.green, b = color.blue;
4446 /* Scale down RGB values to the visual's bits per RGB, and shift
4447 them to the right position in the pixel color. Note that the
4448 original RGB values are 16-bit values, as usual in X. */
4449 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4450 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4451 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4453 /* Assemble the pixel color. */
4454 return pr | pg | pb;
4457 for (p = ct_table[i]; p; p = p->next)
4458 if (p->r == r && p->g == g && p->b == b)
4459 break;
4461 if (p == NULL)
4464 #ifdef HAVE_X_WINDOWS
4465 XColor color;
4466 Colormap cmap;
4467 bool rc;
4468 #else
4469 COLORREF color;
4470 #endif
4472 if (ct_colors_allocated_max <= ct_colors_allocated)
4473 return FRAME_FOREGROUND_PIXEL (f);
4475 #ifdef HAVE_X_WINDOWS
4476 color.red = r;
4477 color.green = g;
4478 color.blue = b;
4480 cmap = FRAME_X_COLORMAP (f);
4481 rc = x_alloc_nearest_color (f, cmap, &color);
4482 if (rc)
4484 ++ct_colors_allocated;
4485 p = xmalloc (sizeof *p);
4486 p->r = r;
4487 p->g = g;
4488 p->b = b;
4489 p->pixel = color.pixel;
4490 p->next = ct_table[i];
4491 ct_table[i] = p;
4493 else
4494 return FRAME_FOREGROUND_PIXEL (f);
4496 #else
4497 #ifdef HAVE_NTGUI
4498 color = PALETTERGB (r, g, b);
4499 #else
4500 color = RGB_TO_ULONG (r, g, b);
4501 #endif /* HAVE_NTGUI */
4502 ++ct_colors_allocated;
4503 p = xmalloc (sizeof *p);
4504 p->r = r;
4505 p->g = g;
4506 p->b = b;
4507 p->pixel = color;
4508 p->next = ct_table[i];
4509 ct_table[i] = p;
4510 #endif /* HAVE_X_WINDOWS */
4514 return p->pixel;
4518 /* Look up pixel color PIXEL which is used on frame F in the color
4519 table. If not already present, allocate it. Value is PIXEL. */
4521 static unsigned long
4522 lookup_pixel_color (struct frame *f, unsigned long pixel)
4524 int i = pixel % CT_SIZE;
4525 struct ct_color *p;
4527 for (p = ct_table[i]; p; p = p->next)
4528 if (p->pixel == pixel)
4529 break;
4531 if (p == NULL)
4533 XColor color;
4534 Colormap cmap;
4535 bool rc;
4537 if (ct_colors_allocated >= ct_colors_allocated_max)
4538 return FRAME_FOREGROUND_PIXEL (f);
4540 #ifdef HAVE_X_WINDOWS
4541 cmap = FRAME_X_COLORMAP (f);
4542 color.pixel = pixel;
4543 x_query_color (f, &color);
4544 rc = x_alloc_nearest_color (f, cmap, &color);
4545 #else
4546 block_input ();
4547 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4548 color.pixel = pixel;
4549 XQueryColor (NULL, cmap, &color);
4550 rc = x_alloc_nearest_color (f, cmap, &color);
4551 unblock_input ();
4552 #endif /* HAVE_X_WINDOWS */
4554 if (rc)
4556 ++ct_colors_allocated;
4558 p = xmalloc (sizeof *p);
4559 p->r = color.red;
4560 p->g = color.green;
4561 p->b = color.blue;
4562 p->pixel = pixel;
4563 p->next = ct_table[i];
4564 ct_table[i] = p;
4566 else
4567 return FRAME_FOREGROUND_PIXEL (f);
4569 return p->pixel;
4573 /* Value is a vector of all pixel colors contained in the color table,
4574 allocated via xmalloc. Set *N to the number of colors. */
4576 static unsigned long *
4577 colors_in_color_table (int *n)
4579 int i, j;
4580 struct ct_color *p;
4581 unsigned long *colors;
4583 if (ct_colors_allocated == 0)
4585 *n = 0;
4586 colors = NULL;
4588 else
4590 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4591 *n = ct_colors_allocated;
4593 for (i = j = 0; i < CT_SIZE; ++i)
4594 for (p = ct_table[i]; p; p = p->next)
4595 colors[j++] = p->pixel;
4598 return colors;
4601 #else /* COLOR_TABLE_SUPPORT */
4603 static unsigned long
4604 lookup_rgb_color (struct frame *f, int r, int g, int b)
4606 unsigned long pixel;
4608 #ifdef HAVE_NTGUI
4609 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4610 #endif /* HAVE_NTGUI */
4612 #ifdef HAVE_NS
4613 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4614 #endif /* HAVE_NS */
4615 return pixel;
4618 static void
4619 init_color_table (void)
4622 #endif /* COLOR_TABLE_SUPPORT */
4625 /***********************************************************************
4626 Algorithms
4627 ***********************************************************************/
4629 /* Edge detection matrices for different edge-detection
4630 strategies. */
4632 static int emboss_matrix[9] = {
4633 /* x - 1 x x + 1 */
4634 2, -1, 0, /* y - 1 */
4635 -1, 0, 1, /* y */
4636 0, 1, -2 /* y + 1 */
4639 static int laplace_matrix[9] = {
4640 /* x - 1 x x + 1 */
4641 1, 0, 0, /* y - 1 */
4642 0, 0, 0, /* y */
4643 0, 0, -1 /* y + 1 */
4646 /* Value is the intensity of the color whose red/green/blue values
4647 are R, G, and B. */
4649 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4652 /* On frame F, return an array of XColor structures describing image
4653 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4654 means also fill the red/green/blue members of the XColor
4655 structures. Value is a pointer to the array of XColors structures,
4656 allocated with xmalloc; it must be freed by the caller. */
4658 static XColor *
4659 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4661 int x, y;
4662 XColor *colors, *p;
4663 XImagePtr_or_DC ximg;
4664 #ifdef HAVE_NTGUI
4665 HGDIOBJ prev;
4666 #endif /* HAVE_NTGUI */
4668 if (img->height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width)
4669 memory_full (SIZE_MAX);
4670 colors = xmalloc (sizeof *colors * img->width * img->height);
4672 /* Get the X image or create a memory device context for IMG. */
4673 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4675 /* Fill the `pixel' members of the XColor array. I wished there
4676 were an easy and portable way to circumvent XGetPixel. */
4677 p = colors;
4678 for (y = 0; y < img->height; ++y)
4680 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4681 XColor *row = p;
4682 for (x = 0; x < img->width; ++x, ++p)
4683 p->pixel = GET_PIXEL (ximg, x, y);
4684 if (rgb_p)
4685 x_query_colors (f, row, img->width);
4687 #else
4689 for (x = 0; x < img->width; ++x, ++p)
4691 /* W32_TODO: palette support needed here? */
4692 p->pixel = GET_PIXEL (ximg, x, y);
4693 if (rgb_p)
4695 p->red = RED16_FROM_ULONG (p->pixel);
4696 p->green = GREEN16_FROM_ULONG (p->pixel);
4697 p->blue = BLUE16_FROM_ULONG (p->pixel);
4700 #endif /* HAVE_X_WINDOWS */
4703 image_unget_x_image_or_dc (img, 0, ximg, prev);
4705 return colors;
4708 #ifdef HAVE_NTGUI
4710 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4711 created with CreateDIBSection, with the pointer to the bit values
4712 stored in ximg->data. */
4714 static void
4715 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4717 int width = ximg->info.bmiHeader.biWidth;
4718 unsigned char * pixel;
4720 /* True color images. */
4721 if (ximg->info.bmiHeader.biBitCount == 24)
4723 int rowbytes = width * 3;
4724 /* Ensure scanlines are aligned on 4 byte boundaries. */
4725 if (rowbytes % 4)
4726 rowbytes += 4 - (rowbytes % 4);
4728 pixel = ximg->data + y * rowbytes + x * 3;
4729 /* Windows bitmaps are in BGR order. */
4730 *pixel = GetBValue (color);
4731 *(pixel + 1) = GetGValue (color);
4732 *(pixel + 2) = GetRValue (color);
4734 /* Monochrome images. */
4735 else if (ximg->info.bmiHeader.biBitCount == 1)
4737 int rowbytes = width / 8;
4738 /* Ensure scanlines are aligned on 4 byte boundaries. */
4739 if (rowbytes % 4)
4740 rowbytes += 4 - (rowbytes % 4);
4741 pixel = ximg->data + y * rowbytes + x / 8;
4742 /* Filter out palette info. */
4743 if (color & 0x00ffffff)
4744 *pixel = *pixel | (1 << x % 8);
4745 else
4746 *pixel = *pixel & ~(1 << x % 8);
4748 else
4749 image_error ("XPutPixel: palette image not supported");
4752 #endif /* HAVE_NTGUI */
4754 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4755 RGB members are set. F is the frame on which this all happens.
4756 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4758 static void
4759 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4761 int x, y;
4762 XImagePtr oimg = NULL;
4763 XColor *p;
4765 init_color_table ();
4767 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4768 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4769 &oimg, 0);
4770 p = colors;
4771 for (y = 0; y < img->height; ++y)
4772 for (x = 0; x < img->width; ++x, ++p)
4774 unsigned long pixel;
4775 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4776 XPutPixel (oimg, x, y, pixel);
4779 xfree (colors);
4781 image_put_x_image (f, img, oimg, 0);
4782 #ifdef COLOR_TABLE_SUPPORT
4783 img->colors = colors_in_color_table (&img->ncolors);
4784 free_color_table ();
4785 #endif /* COLOR_TABLE_SUPPORT */
4789 /* On frame F, perform edge-detection on image IMG.
4791 MATRIX is a nine-element array specifying the transformation
4792 matrix. See emboss_matrix for an example.
4794 COLOR_ADJUST is a color adjustment added to each pixel of the
4795 outgoing image. */
4797 static void
4798 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4800 XColor *colors = x_to_xcolors (f, img, 1);
4801 XColor *new, *p;
4802 int x, y, i, sum;
4804 for (i = sum = 0; i < 9; ++i)
4805 sum += eabs (matrix[i]);
4807 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4809 if (img->height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width)
4810 memory_full (SIZE_MAX);
4811 new = xmalloc (sizeof *new * img->width * img->height);
4813 for (y = 0; y < img->height; ++y)
4815 p = COLOR (new, 0, y);
4816 p->red = p->green = p->blue = 0xffff/2;
4817 p = COLOR (new, img->width - 1, y);
4818 p->red = p->green = p->blue = 0xffff/2;
4821 for (x = 1; x < img->width - 1; ++x)
4823 p = COLOR (new, x, 0);
4824 p->red = p->green = p->blue = 0xffff/2;
4825 p = COLOR (new, x, img->height - 1);
4826 p->red = p->green = p->blue = 0xffff/2;
4829 for (y = 1; y < img->height - 1; ++y)
4831 p = COLOR (new, 1, y);
4833 for (x = 1; x < img->width - 1; ++x, ++p)
4835 int r, g, b, yy, xx;
4837 r = g = b = i = 0;
4838 for (yy = y - 1; yy < y + 2; ++yy)
4839 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4840 if (matrix[i])
4842 XColor *t = COLOR (colors, xx, yy);
4843 r += matrix[i] * t->red;
4844 g += matrix[i] * t->green;
4845 b += matrix[i] * t->blue;
4848 r = (r / sum + color_adjust) & 0xffff;
4849 g = (g / sum + color_adjust) & 0xffff;
4850 b = (b / sum + color_adjust) & 0xffff;
4851 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4855 xfree (colors);
4856 x_from_xcolors (f, img, new);
4858 #undef COLOR
4862 /* Perform the pre-defined `emboss' edge-detection on image IMG
4863 on frame F. */
4865 static void
4866 x_emboss (struct frame *f, struct image *img)
4868 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4872 /* Transform image IMG which is used on frame F with a Laplace
4873 edge-detection algorithm. The result is an image that can be used
4874 to draw disabled buttons, for example. */
4876 static void
4877 x_laplace (struct frame *f, struct image *img)
4879 x_detect_edges (f, img, laplace_matrix, 45000);
4883 /* Perform edge-detection on image IMG on frame F, with specified
4884 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4886 MATRIX must be either
4888 - a list of at least 9 numbers in row-major form
4889 - a vector of at least 9 numbers
4891 COLOR_ADJUST nil means use a default; otherwise it must be a
4892 number. */
4894 static void
4895 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4896 Lisp_Object color_adjust)
4898 int i = 0;
4899 int trans[9];
4901 if (CONSP (matrix))
4903 for (i = 0;
4904 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4905 ++i, matrix = XCDR (matrix))
4906 trans[i] = XFLOATINT (XCAR (matrix));
4908 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4910 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4911 trans[i] = XFLOATINT (AREF (matrix, i));
4914 if (NILP (color_adjust))
4915 color_adjust = make_number (0xffff / 2);
4917 if (i == 9 && NUMBERP (color_adjust))
4918 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4922 /* Transform image IMG on frame F so that it looks disabled. */
4924 static void
4925 x_disable_image (struct frame *f, struct image *img)
4927 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4928 #ifdef HAVE_NTGUI
4929 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4930 #else
4931 int n_planes = dpyinfo->n_planes;
4932 #endif /* HAVE_NTGUI */
4934 if (n_planes >= 2)
4936 /* Color (or grayscale). Convert to gray, and equalize. Just
4937 drawing such images with a stipple can look very odd, so
4938 we're using this method instead. */
4939 XColor *colors = x_to_xcolors (f, img, 1);
4940 XColor *p, *end;
4941 const int h = 15000;
4942 const int l = 30000;
4944 for (p = colors, end = colors + img->width * img->height;
4945 p < end;
4946 ++p)
4948 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4949 int i2 = (0xffff - h - l) * i / 0xffff + l;
4950 p->red = p->green = p->blue = i2;
4953 x_from_xcolors (f, img, colors);
4956 /* Draw a cross over the disabled image, if we must or if we
4957 should. */
4958 if (n_planes < 2 || cross_disabled_images)
4960 #ifndef HAVE_NTGUI
4961 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4963 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4965 Display *dpy = FRAME_X_DISPLAY (f);
4966 GC gc;
4968 image_sync_to_pixmaps (f, img);
4969 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4970 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4971 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4972 img->width - 1, img->height - 1);
4973 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4974 img->width - 1, 0);
4975 XFreeGC (dpy, gc);
4977 if (img->mask)
4979 gc = XCreateGC (dpy, img->mask, 0, NULL);
4980 XSetForeground (dpy, gc, MaskForeground (f));
4981 XDrawLine (dpy, img->mask, gc, 0, 0,
4982 img->width - 1, img->height - 1);
4983 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4984 img->width - 1, 0);
4985 XFreeGC (dpy, gc);
4987 #endif /* !HAVE_NS */
4988 #else
4989 HDC hdc, bmpdc;
4990 HGDIOBJ prev;
4992 hdc = get_frame_dc (f);
4993 bmpdc = CreateCompatibleDC (hdc);
4994 release_frame_dc (f, hdc);
4996 prev = SelectObject (bmpdc, img->pixmap);
4998 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4999 MoveToEx (bmpdc, 0, 0, NULL);
5000 LineTo (bmpdc, img->width - 1, img->height - 1);
5001 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5002 LineTo (bmpdc, img->width - 1, 0);
5004 if (img->mask)
5006 SelectObject (bmpdc, img->mask);
5007 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5008 MoveToEx (bmpdc, 0, 0, NULL);
5009 LineTo (bmpdc, img->width - 1, img->height - 1);
5010 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5011 LineTo (bmpdc, img->width - 1, 0);
5013 SelectObject (bmpdc, prev);
5014 DeleteDC (bmpdc);
5015 #endif /* HAVE_NTGUI */
5020 /* Build a mask for image IMG which is used on frame F. FILE is the
5021 name of an image file, for error messages. HOW determines how to
5022 determine the background color of IMG. If it is a list '(R G B)',
5023 with R, G, and B being integers >= 0, take that as the color of the
5024 background. Otherwise, determine the background color of IMG
5025 heuristically. */
5027 static void
5028 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
5030 XImagePtr_or_DC ximg;
5031 #ifndef HAVE_NTGUI
5032 XImagePtr mask_img;
5033 #else
5034 HGDIOBJ prev;
5035 char *mask_img;
5036 int row_width;
5037 #endif /* HAVE_NTGUI */
5038 int x, y;
5039 bool use_img_background;
5040 unsigned long bg = 0;
5042 if (img->mask)
5043 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
5045 #ifndef HAVE_NTGUI
5046 #ifndef HAVE_NS
5047 /* Create an image and pixmap serving as mask. */
5048 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
5049 &mask_img, 1))
5050 return;
5051 #endif /* !HAVE_NS */
5052 #else
5053 /* Create the bit array serving as mask. */
5054 row_width = (img->width + 7) / 8;
5055 mask_img = xzalloc (row_width * img->height);
5056 #endif /* HAVE_NTGUI */
5058 /* Get the X image or create a memory device context for IMG. */
5059 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
5061 /* Determine the background color of ximg. If HOW is `(R G B)'
5062 take that as color. Otherwise, use the image's background color. */
5063 use_img_background = 1;
5065 if (CONSP (how))
5067 int rgb[3], i;
5069 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5071 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5072 how = XCDR (how);
5075 if (i == 3 && NILP (how))
5077 char color_name[30];
5078 sprintf (color_name, "#%04x%04x%04x",
5079 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
5080 bg = (
5081 #ifdef HAVE_NTGUI
5082 0x00ffffff & /* Filter out palette info. */
5083 #endif /* HAVE_NTGUI */
5084 x_alloc_image_color (f, img, build_string (color_name), 0));
5085 use_img_background = 0;
5089 if (use_img_background)
5090 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5092 /* Set all bits in mask_img to 1 whose color in ximg is different
5093 from the background color bg. */
5094 #ifndef HAVE_NTGUI
5095 for (y = 0; y < img->height; ++y)
5096 for (x = 0; x < img->width; ++x)
5097 #ifndef HAVE_NS
5098 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5099 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5100 #else
5101 if (XGetPixel (ximg, x, y) == bg)
5102 ns_set_alpha (ximg, x, y, 0);
5103 #endif /* HAVE_NS */
5104 #ifndef HAVE_NS
5105 /* Fill in the background_transparent field while we have the mask handy. */
5106 image_background_transparent (img, f, mask_img);
5108 /* Put mask_img into the image. */
5109 image_put_x_image (f, img, mask_img, 1);
5110 #endif /* !HAVE_NS */
5111 #else
5112 for (y = 0; y < img->height; ++y)
5113 for (x = 0; x < img->width; ++x)
5115 COLORREF p = GetPixel (ximg, x, y);
5116 if (p != bg)
5117 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5120 /* Create the mask image. */
5121 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5122 mask_img);
5123 /* Fill in the background_transparent field while we have the mask handy. */
5124 SelectObject (ximg, img->mask);
5125 image_background_transparent (img, f, ximg);
5127 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5128 xfree (mask_img);
5129 #endif /* HAVE_NTGUI */
5131 image_unget_x_image_or_dc (img, 0, ximg, prev);
5135 /***********************************************************************
5136 PBM (mono, gray, color)
5137 ***********************************************************************/
5139 static bool pbm_image_p (Lisp_Object object);
5140 static bool pbm_load (struct frame *f, struct image *img);
5142 /* Indices of image specification fields in gs_format, below. */
5144 enum pbm_keyword_index
5146 PBM_TYPE,
5147 PBM_FILE,
5148 PBM_DATA,
5149 PBM_ASCENT,
5150 PBM_MARGIN,
5151 PBM_RELIEF,
5152 PBM_ALGORITHM,
5153 PBM_HEURISTIC_MASK,
5154 PBM_MASK,
5155 PBM_FOREGROUND,
5156 PBM_BACKGROUND,
5157 PBM_LAST
5160 /* Vector of image_keyword structures describing the format
5161 of valid user-defined image specifications. */
5163 static const struct image_keyword pbm_format[PBM_LAST] =
5165 {":type", IMAGE_SYMBOL_VALUE, 1},
5166 {":file", IMAGE_STRING_VALUE, 0},
5167 {":data", IMAGE_STRING_VALUE, 0},
5168 {":ascent", IMAGE_ASCENT_VALUE, 0},
5169 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5170 {":relief", IMAGE_INTEGER_VALUE, 0},
5171 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5172 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5173 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5174 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5175 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5178 /* Structure describing the image type `pbm'. */
5180 static struct image_type pbm_type =
5182 SYMBOL_INDEX (Qpbm),
5183 pbm_image_p,
5184 pbm_load,
5185 x_clear_image,
5186 NULL,
5187 NULL
5191 /* Return true if OBJECT is a valid PBM image specification. */
5193 static bool
5194 pbm_image_p (Lisp_Object object)
5196 struct image_keyword fmt[PBM_LAST];
5198 memcpy (fmt, pbm_format, sizeof fmt);
5200 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5201 return 0;
5203 /* Must specify either :data or :file. */
5204 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5208 /* Get next char skipping comments in Netpbm header. Returns -1 at
5209 end of input. */
5211 static int
5212 pbm_next_char (unsigned char **s, unsigned char *end)
5214 int c = -1;
5216 while (*s < end && (c = *(*s)++, c == '#'))
5218 /* Skip to the next line break. */
5219 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5222 c = -1;
5225 return c;
5229 /* Scan a decimal number from *S and return it. Advance *S while
5230 reading the number. END is the end of the string. Value is -1 at
5231 end of input. */
5233 static int
5234 pbm_scan_number (unsigned char **s, unsigned char *end)
5236 int c = 0, val = -1;
5238 /* Skip white-space. */
5239 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5242 if (c_isdigit (c))
5244 /* Read decimal number. */
5245 val = c - '0';
5246 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5247 val = 10 * val + c - '0';
5250 return val;
5254 /* Load PBM image IMG for use on frame F. */
5256 static bool
5257 pbm_load (struct frame *f, struct image *img)
5259 bool raw_p;
5260 int x, y;
5261 int width, height, max_color_idx = 0;
5262 Lisp_Object specified_file;
5263 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5264 unsigned char *contents = NULL;
5265 unsigned char *end, *p;
5266 #ifdef USE_CAIRO
5267 unsigned char *data = 0;
5268 uint32_t *dataptr;
5269 #else
5270 XImagePtr ximg;
5271 #endif
5273 specified_file = image_spec_value (img->spec, QCfile, NULL);
5275 if (STRINGP (specified_file))
5277 int fd;
5278 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5279 if (!STRINGP (file))
5281 image_error ("Cannot find image file `%s'", specified_file);
5282 return 0;
5285 ptrdiff_t size;
5286 contents = slurp_file (fd, &size);
5287 if (contents == NULL)
5289 image_error ("Error reading `%s'", file);
5290 return 0;
5293 p = contents;
5294 end = contents + size;
5296 else
5298 Lisp_Object data;
5299 data = image_spec_value (img->spec, QCdata, NULL);
5300 if (!STRINGP (data))
5302 image_error ("Invalid image data `%s'", data);
5303 return 0;
5305 p = SDATA (data);
5306 end = p + SBYTES (data);
5309 /* Check magic number. */
5310 if (end - p < 2 || *p++ != 'P')
5312 image_error ("Not a PBM image: `%s'", img->spec);
5313 error:
5314 xfree (contents);
5315 img->pixmap = NO_PIXMAP;
5316 return 0;
5319 switch (*p++)
5321 case '1':
5322 raw_p = 0, type = PBM_MONO;
5323 break;
5325 case '2':
5326 raw_p = 0, type = PBM_GRAY;
5327 break;
5329 case '3':
5330 raw_p = 0, type = PBM_COLOR;
5331 break;
5333 case '4':
5334 raw_p = 1, type = PBM_MONO;
5335 break;
5337 case '5':
5338 raw_p = 1, type = PBM_GRAY;
5339 break;
5341 case '6':
5342 raw_p = 1, type = PBM_COLOR;
5343 break;
5345 default:
5346 image_error ("Not a PBM image: `%s'", img->spec);
5347 goto error;
5350 /* Read width, height, maximum color-component. Characters
5351 starting with `#' up to the end of a line are ignored. */
5352 width = pbm_scan_number (&p, end);
5353 height = pbm_scan_number (&p, end);
5355 #ifdef USE_CAIRO
5356 data = (unsigned char *) xmalloc (width * height * 4);
5357 dataptr = (uint32_t *) data;
5358 #endif
5360 if (type != PBM_MONO)
5362 max_color_idx = pbm_scan_number (&p, end);
5363 if (max_color_idx > 65535 || max_color_idx < 0)
5365 image_error ("Unsupported maximum PBM color value");
5366 goto error;
5370 if (!check_image_size (f, width, height))
5372 image_size_error ();
5373 goto error;
5376 #ifndef USE_CAIRO
5377 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5378 goto error;
5379 #endif
5381 /* Initialize the color hash table. */
5382 init_color_table ();
5384 if (type == PBM_MONO)
5386 int c = 0, g;
5387 struct image_keyword fmt[PBM_LAST];
5388 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5389 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5390 #ifdef USE_CAIRO
5391 XColor xfg, xbg;
5392 int fga32, bga32;
5393 #endif
5394 /* Parse the image specification. */
5395 memcpy (fmt, pbm_format, sizeof fmt);
5396 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5398 /* Get foreground and background colors, maybe allocate colors. */
5399 #ifdef USE_CAIRO
5400 if (! fmt[PBM_FOREGROUND].count
5401 || ! STRINGP (fmt[PBM_FOREGROUND].value)
5402 || ! x_defined_color (f, SSDATA (fmt[PBM_FOREGROUND].value), &xfg, 0))
5404 xfg.pixel = fg;
5405 x_query_color (f, &xfg);
5407 fga32 = xcolor_to_argb32 (xfg);
5409 if (! fmt[PBM_BACKGROUND].count
5410 || ! STRINGP (fmt[PBM_BACKGROUND].value)
5411 || ! x_defined_color (f, SSDATA (fmt[PBM_BACKGROUND].value), &xbg, 0))
5413 xbg.pixel = bg;
5414 x_query_color (f, &xbg);
5416 bga32 = xcolor_to_argb32 (xbg);
5417 #else
5418 if (fmt[PBM_FOREGROUND].count
5419 && STRINGP (fmt[PBM_FOREGROUND].value))
5420 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5421 if (fmt[PBM_BACKGROUND].count
5422 && STRINGP (fmt[PBM_BACKGROUND].value))
5424 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5425 img->background = bg;
5426 img->background_valid = 1;
5428 #endif
5430 for (y = 0; y < height; ++y)
5431 for (x = 0; x < width; ++x)
5433 if (raw_p)
5435 if ((x & 7) == 0)
5437 if (p >= end)
5439 #ifdef USE_CAIRO
5440 xfree (data);
5441 #else
5442 x_destroy_x_image (ximg);
5443 #endif
5444 x_clear_image (f, img);
5445 image_error ("Invalid image size in image `%s'",
5446 img->spec);
5447 goto error;
5449 c = *p++;
5451 g = c & 0x80;
5452 c <<= 1;
5454 else
5455 g = pbm_scan_number (&p, end);
5457 #ifdef USE_CAIRO
5458 *dataptr++ = g ? fga32 : bga32;
5459 #else
5460 XPutPixel (ximg, x, y, g ? fg : bg);
5461 #endif
5464 else
5466 int expected_size = height * width;
5467 if (max_color_idx > 255)
5468 expected_size *= 2;
5469 if (type == PBM_COLOR)
5470 expected_size *= 3;
5472 if (raw_p && p + expected_size > end)
5474 #ifdef USE_CAIRO
5475 xfree (data);
5476 #else
5477 x_destroy_x_image (ximg);
5478 #endif
5479 x_clear_image (f, img);
5480 image_error ("Invalid image size in image `%s'", img->spec);
5481 goto error;
5484 for (y = 0; y < height; ++y)
5485 for (x = 0; x < width; ++x)
5487 int r, g, b;
5489 if (type == PBM_GRAY && raw_p)
5491 r = g = b = *p++;
5492 if (max_color_idx > 255)
5493 r = g = b = r * 256 + *p++;
5495 else if (type == PBM_GRAY)
5496 r = g = b = pbm_scan_number (&p, end);
5497 else if (raw_p)
5499 r = *p++;
5500 if (max_color_idx > 255)
5501 r = r * 256 + *p++;
5502 g = *p++;
5503 if (max_color_idx > 255)
5504 g = g * 256 + *p++;
5505 b = *p++;
5506 if (max_color_idx > 255)
5507 b = b * 256 + *p++;
5509 else
5511 r = pbm_scan_number (&p, end);
5512 g = pbm_scan_number (&p, end);
5513 b = pbm_scan_number (&p, end);
5516 if (r < 0 || g < 0 || b < 0)
5518 #ifdef USE_CAIRO
5519 xfree (data);
5520 #else
5521 x_destroy_x_image (ximg);
5522 #endif
5523 image_error ("Invalid pixel value in image `%s'", img->spec);
5524 goto error;
5527 #ifdef USE_CAIRO
5528 r = (double) r * 255 / max_color_idx;
5529 g = (double) g * 255 / max_color_idx;
5530 b = (double) b * 255 / max_color_idx;
5531 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
5532 #else
5533 /* RGB values are now in the range 0..max_color_idx.
5534 Scale this to the range 0..0xffff supported by X. */
5535 r = (double) r * 65535 / max_color_idx;
5536 g = (double) g * 65535 / max_color_idx;
5537 b = (double) b * 65535 / max_color_idx;
5538 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5539 #endif
5543 #ifdef COLOR_TABLE_SUPPORT
5544 /* Store in IMG->colors the colors allocated for the image, and
5545 free the color table. */
5546 img->colors = colors_in_color_table (&img->ncolors);
5547 free_color_table ();
5548 #endif /* COLOR_TABLE_SUPPORT */
5550 img->width = width;
5551 img->height = height;
5553 /* Maybe fill in the background field while we have ximg handy. */
5555 #ifdef USE_CAIRO
5556 create_cairo_image_surface (img, data, width, height);
5557 #else
5558 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5559 /* Casting avoids a GCC warning. */
5560 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5562 /* Put ximg into the image. */
5563 image_put_x_image (f, img, ximg, 0);
5564 #endif
5566 /* X and W32 versions did it here, MAC version above. ++kfs
5567 img->width = width;
5568 img->height = height; */
5570 xfree (contents);
5571 return 1;
5575 /***********************************************************************
5577 ***********************************************************************/
5579 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5581 /* Function prototypes. */
5583 static bool png_image_p (Lisp_Object object);
5584 static bool png_load (struct frame *f, struct image *img);
5586 /* Indices of image specification fields in png_format, below. */
5588 enum png_keyword_index
5590 PNG_TYPE,
5591 PNG_DATA,
5592 PNG_FILE,
5593 PNG_ASCENT,
5594 PNG_MARGIN,
5595 PNG_RELIEF,
5596 PNG_ALGORITHM,
5597 PNG_HEURISTIC_MASK,
5598 PNG_MASK,
5599 PNG_BACKGROUND,
5600 PNG_LAST
5603 /* Vector of image_keyword structures describing the format
5604 of valid user-defined image specifications. */
5606 static const struct image_keyword png_format[PNG_LAST] =
5608 {":type", IMAGE_SYMBOL_VALUE, 1},
5609 {":data", IMAGE_STRING_VALUE, 0},
5610 {":file", IMAGE_STRING_VALUE, 0},
5611 {":ascent", IMAGE_ASCENT_VALUE, 0},
5612 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5613 {":relief", IMAGE_INTEGER_VALUE, 0},
5614 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5615 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5616 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5617 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5620 #if defined HAVE_NTGUI && defined WINDOWSNT
5621 static bool init_png_functions (void);
5622 #else
5623 #define init_png_functions NULL
5624 #endif
5626 /* Structure describing the image type `png'. */
5628 static struct image_type png_type =
5630 SYMBOL_INDEX (Qpng),
5631 png_image_p,
5632 png_load,
5633 x_clear_image,
5634 init_png_functions,
5635 NULL
5638 /* Return true if OBJECT is a valid PNG image specification. */
5640 static bool
5641 png_image_p (Lisp_Object object)
5643 struct image_keyword fmt[PNG_LAST];
5644 memcpy (fmt, png_format, sizeof fmt);
5646 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5647 return 0;
5649 /* Must specify either the :data or :file keyword. */
5650 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5653 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5656 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5658 # ifdef WINDOWSNT
5659 /* PNG library details. */
5661 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5662 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5663 DEF_DLL_FN (png_structp, png_create_read_struct,
5664 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5665 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5666 DEF_DLL_FN (void, png_destroy_read_struct,
5667 (png_structpp, png_infopp, png_infopp));
5668 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5669 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5670 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5671 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5672 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5673 int *, int *, int *, int *, int *));
5674 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5675 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5676 DEF_DLL_FN (void, png_set_expand, (png_structp));
5677 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5678 DEF_DLL_FN (void, png_set_background,
5679 (png_structp, png_color_16p, int, int, double));
5680 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5681 (png_structp, png_infop, png_color_16p *));
5682 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5683 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5684 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5685 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5686 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5687 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5689 # if (PNG_LIBPNG_VER >= 10500)
5690 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5691 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5692 (png_structp, png_longjmp_ptr, size_t));
5693 # endif /* libpng version >= 1.5 */
5695 static bool
5696 init_png_functions (void)
5698 HMODULE library;
5700 if (!(library = w32_delayed_load (Qpng)))
5701 return 0;
5703 LOAD_DLL_FN (library, png_get_io_ptr);
5704 LOAD_DLL_FN (library, png_sig_cmp);
5705 LOAD_DLL_FN (library, png_create_read_struct);
5706 LOAD_DLL_FN (library, png_create_info_struct);
5707 LOAD_DLL_FN (library, png_destroy_read_struct);
5708 LOAD_DLL_FN (library, png_set_read_fn);
5709 LOAD_DLL_FN (library, png_set_sig_bytes);
5710 LOAD_DLL_FN (library, png_read_info);
5711 LOAD_DLL_FN (library, png_get_IHDR);
5712 LOAD_DLL_FN (library, png_get_valid);
5713 LOAD_DLL_FN (library, png_set_strip_16);
5714 LOAD_DLL_FN (library, png_set_expand);
5715 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5716 LOAD_DLL_FN (library, png_set_background);
5717 LOAD_DLL_FN (library, png_get_bKGD);
5718 LOAD_DLL_FN (library, png_read_update_info);
5719 LOAD_DLL_FN (library, png_get_channels);
5720 LOAD_DLL_FN (library, png_get_rowbytes);
5721 LOAD_DLL_FN (library, png_read_image);
5722 LOAD_DLL_FN (library, png_read_end);
5723 LOAD_DLL_FN (library, png_error);
5725 # if (PNG_LIBPNG_VER >= 10500)
5726 LOAD_DLL_FN (library, png_longjmp);
5727 LOAD_DLL_FN (library, png_set_longjmp_fn);
5728 # endif /* libpng version >= 1.5 */
5730 return 1;
5733 # undef png_create_info_struct
5734 # undef png_create_read_struct
5735 # undef png_destroy_read_struct
5736 # undef png_error
5737 # undef png_get_bKGD
5738 # undef png_get_channels
5739 # undef png_get_IHDR
5740 # undef png_get_io_ptr
5741 # undef png_get_rowbytes
5742 # undef png_get_valid
5743 # undef png_longjmp
5744 # undef png_read_end
5745 # undef png_read_image
5746 # undef png_read_info
5747 # undef png_read_update_info
5748 # undef png_set_background
5749 # undef png_set_expand
5750 # undef png_set_gray_to_rgb
5751 # undef png_set_longjmp_fn
5752 # undef png_set_read_fn
5753 # undef png_set_sig_bytes
5754 # undef png_set_strip_16
5755 # undef png_sig_cmp
5757 # define png_create_info_struct fn_png_create_info_struct
5758 # define png_create_read_struct fn_png_create_read_struct
5759 # define png_destroy_read_struct fn_png_destroy_read_struct
5760 # define png_error fn_png_error
5761 # define png_get_bKGD fn_png_get_bKGD
5762 # define png_get_channels fn_png_get_channels
5763 # define png_get_IHDR fn_png_get_IHDR
5764 # define png_get_io_ptr fn_png_get_io_ptr
5765 # define png_get_rowbytes fn_png_get_rowbytes
5766 # define png_get_valid fn_png_get_valid
5767 # define png_longjmp fn_png_longjmp
5768 # define png_read_end fn_png_read_end
5769 # define png_read_image fn_png_read_image
5770 # define png_read_info fn_png_read_info
5771 # define png_read_update_info fn_png_read_update_info
5772 # define png_set_background fn_png_set_background
5773 # define png_set_expand fn_png_set_expand
5774 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5775 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5776 # define png_set_read_fn fn_png_set_read_fn
5777 # define png_set_sig_bytes fn_png_set_sig_bytes
5778 # define png_set_strip_16 fn_png_set_strip_16
5779 # define png_sig_cmp fn_png_sig_cmp
5781 # endif /* WINDOWSNT */
5783 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5784 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5785 Do not use sys_setjmp, as PNG supports only jmp_buf.
5786 It's OK if the longjmp substitute restores the signal mask. */
5787 # ifdef HAVE__SETJMP
5788 # define FAST_SETJMP(j) _setjmp (j)
5789 # define FAST_LONGJMP _longjmp
5790 # else
5791 # define FAST_SETJMP(j) setjmp (j)
5792 # define FAST_LONGJMP longjmp
5793 # endif
5795 # if PNG_LIBPNG_VER < 10500
5796 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5797 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5798 # else
5799 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5800 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5801 # define PNG_JMPBUF(ptr) \
5802 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5803 # endif
5805 /* Error and warning handlers installed when the PNG library
5806 is initialized. */
5808 static _Noreturn void
5809 my_png_error (png_struct *png_ptr, const char *msg)
5811 eassert (png_ptr != NULL);
5812 /* Avoid compiler warning about deprecated direct access to
5813 png_ptr's fields in libpng versions 1.4.x. */
5814 image_error ("PNG error: %s", build_string (msg));
5815 PNG_LONGJMP (png_ptr);
5819 static void
5820 my_png_warning (png_struct *png_ptr, const char *msg)
5822 eassert (png_ptr != NULL);
5823 image_error ("PNG warning: %s", build_string (msg));
5826 /* Memory source for PNG decoding. */
5828 struct png_memory_storage
5830 unsigned char *bytes; /* The data */
5831 ptrdiff_t len; /* How big is it? */
5832 ptrdiff_t index; /* Where are we? */
5836 /* Function set as reader function when reading PNG image from memory.
5837 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5838 bytes from the input to DATA. */
5840 static void
5841 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5843 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5845 if (length > tbr->len - tbr->index)
5846 png_error (png_ptr, "Read error");
5848 memcpy (data, tbr->bytes + tbr->index, length);
5849 tbr->index = tbr->index + length;
5853 /* Function set as reader function when reading PNG image from a file.
5854 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5855 bytes from the input to DATA. */
5857 static void
5858 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5860 FILE *fp = png_get_io_ptr (png_ptr);
5862 if (fread (data, 1, length, fp) < length)
5863 png_error (png_ptr, "Read error");
5867 /* Load PNG image IMG for use on frame F. Value is true if
5868 successful. */
5870 struct png_load_context
5872 /* These are members so that longjmp doesn't munge local variables. */
5873 png_struct *png_ptr;
5874 png_info *info_ptr;
5875 png_info *end_info;
5876 FILE *fp;
5877 png_byte *pixels;
5878 png_byte **rows;
5881 static bool
5882 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5884 Lisp_Object specified_file;
5885 Lisp_Object specified_data;
5886 int x, y;
5887 ptrdiff_t i;
5888 png_struct *png_ptr;
5889 png_info *info_ptr = NULL, *end_info = NULL;
5890 FILE *fp = NULL;
5891 png_byte sig[8];
5892 png_byte *pixels = NULL;
5893 png_byte **rows = NULL;
5894 png_uint_32 width, height;
5895 int bit_depth, color_type, interlace_type;
5896 png_byte channels;
5897 png_uint_32 row_bytes;
5898 bool transparent_p;
5899 struct png_memory_storage tbr; /* Data to be read */
5901 #ifdef USE_CAIRO
5902 unsigned char *data = 0;
5903 uint32_t *dataptr;
5904 #else
5905 XImagePtr ximg, mask_img = NULL;
5906 #endif
5908 /* Find out what file to load. */
5909 specified_file = image_spec_value (img->spec, QCfile, NULL);
5910 specified_data = image_spec_value (img->spec, QCdata, NULL);
5911 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
5913 if (NILP (specified_data))
5915 int fd;
5916 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5917 if (!STRINGP (file))
5919 image_error ("Cannot find image file `%s'", specified_file);
5920 return 0;
5923 /* Open the image file. */
5924 fp = fdopen (fd, "rb");
5925 if (!fp)
5927 image_error ("Cannot open image file `%s'", file);
5928 return 0;
5931 /* Check PNG signature. */
5932 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5933 || png_sig_cmp (sig, 0, sizeof sig))
5935 fclose (fp);
5936 image_error ("Not a PNG file: `%s'", file);
5937 return 0;
5940 else
5942 if (!STRINGP (specified_data))
5944 image_error ("Invalid image data `%s'", specified_data);
5945 return 0;
5948 /* Read from memory. */
5949 tbr.bytes = SDATA (specified_data);
5950 tbr.len = SBYTES (specified_data);
5951 tbr.index = 0;
5953 /* Check PNG signature. */
5954 if (tbr.len < sizeof sig
5955 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5957 image_error ("Not a PNG image: `%s'", img->spec);
5958 return 0;
5961 /* Need to skip past the signature. */
5962 tbr.bytes += sizeof (sig);
5965 /* Initialize read and info structs for PNG lib. */
5966 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5967 NULL, my_png_error,
5968 my_png_warning);
5969 if (png_ptr)
5971 info_ptr = png_create_info_struct (png_ptr);
5972 end_info = png_create_info_struct (png_ptr);
5975 c->png_ptr = png_ptr;
5976 c->info_ptr = info_ptr;
5977 c->end_info = end_info;
5978 c->fp = fp;
5979 c->pixels = pixels;
5980 c->rows = rows;
5982 if (! (info_ptr && end_info))
5984 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5985 png_ptr = 0;
5987 if (! png_ptr)
5989 if (fp) fclose (fp);
5990 return 0;
5993 /* Set error jump-back. We come back here when the PNG library
5994 detects an error. */
5995 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
5997 error:
5998 if (c->png_ptr)
5999 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6000 xfree (c->pixels);
6001 xfree (c->rows);
6002 if (c->fp)
6003 fclose (c->fp);
6004 return 0;
6007 /* Silence a bogus diagnostic; see GCC bug 54561. */
6008 IF_LINT (fp = c->fp);
6009 IF_LINT (specified_data = specified_data_volatile);
6011 /* Read image info. */
6012 if (!NILP (specified_data))
6013 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
6014 else
6015 png_set_read_fn (png_ptr, fp, png_read_from_file);
6017 png_set_sig_bytes (png_ptr, sizeof sig);
6018 png_read_info (png_ptr, info_ptr);
6019 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6020 &interlace_type, NULL, NULL);
6022 if (! (width <= INT_MAX && height <= INT_MAX
6023 && check_image_size (f, width, height)))
6025 image_size_error ();
6026 goto error;
6029 #ifndef USE_CAIRO
6030 /* Create the X image and pixmap now, so that the work below can be
6031 omitted if the image is too large for X. */
6032 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6033 goto error;
6034 #endif
6036 /* If image contains simply transparency data, we prefer to
6037 construct a clipping mask. */
6038 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6039 transparent_p = 1;
6040 else
6041 transparent_p = 0;
6043 /* This function is easier to write if we only have to handle
6044 one data format: RGB or RGBA with 8 bits per channel. Let's
6045 transform other formats into that format. */
6047 /* Strip more than 8 bits per channel. */
6048 if (bit_depth == 16)
6049 png_set_strip_16 (png_ptr);
6051 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6052 if available. */
6053 png_set_expand (png_ptr);
6055 /* Convert grayscale images to RGB. */
6056 if (color_type == PNG_COLOR_TYPE_GRAY
6057 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6058 png_set_gray_to_rgb (png_ptr);
6060 /* Handle alpha channel by combining the image with a background
6061 color. Do this only if a real alpha channel is supplied. For
6062 simple transparency, we prefer a clipping mask. */
6063 if (!transparent_p)
6065 /* png_color_16 *image_bg; */
6066 Lisp_Object specified_bg
6067 = image_spec_value (img->spec, QCbackground, NULL);
6068 XColor color;
6070 /* If the user specified a color, try to use it; if not, use the
6071 current frame background, ignoring any default background
6072 color set by the image. */
6073 if (STRINGP (specified_bg)
6074 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
6075 : (x_query_frame_background_color (f, &color), true))
6076 /* The user specified `:background', use that. */
6078 int shift = bit_depth == 16 ? 0 : 8;
6079 png_color_16 bg = { 0 };
6080 bg.red = color.red >> shift;
6081 bg.green = color.green >> shift;
6082 bg.blue = color.blue >> shift;
6084 png_set_background (png_ptr, &bg,
6085 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6089 /* Update info structure. */
6090 png_read_update_info (png_ptr, info_ptr);
6092 /* Get number of channels. Valid values are 1 for grayscale images
6093 and images with a palette, 2 for grayscale images with transparency
6094 information (alpha channel), 3 for RGB images, and 4 for RGB
6095 images with alpha channel, i.e. RGBA. If conversions above were
6096 sufficient we should only have 3 or 4 channels here. */
6097 channels = png_get_channels (png_ptr, info_ptr);
6098 eassert (channels == 3 || channels == 4);
6100 /* Number of bytes needed for one row of the image. */
6101 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
6103 /* Allocate memory for the image. */
6104 if (height > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows
6105 || row_bytes > min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height)
6106 memory_full (SIZE_MAX);
6107 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
6108 c->rows = rows = xmalloc (height * sizeof *rows);
6109 for (i = 0; i < height; ++i)
6110 rows[i] = pixels + i * row_bytes;
6112 /* Read the entire image. */
6113 png_read_image (png_ptr, rows);
6114 png_read_end (png_ptr, info_ptr);
6115 if (fp)
6117 fclose (fp);
6118 c->fp = NULL;
6121 #ifdef USE_CAIRO
6122 data = (unsigned char *) xmalloc (width * height * 4);
6123 dataptr = (uint32_t *) data;
6124 #else
6125 /* Create an image and pixmap serving as mask if the PNG image
6126 contains an alpha channel. */
6127 if (channels == 4
6128 && !transparent_p
6129 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
6130 &mask_img, 1))
6132 x_destroy_x_image (ximg);
6133 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
6134 goto error;
6136 #endif
6138 /* Fill the X image and mask from PNG data. */
6139 init_color_table ();
6141 for (y = 0; y < height; ++y)
6143 png_byte *p = rows[y];
6145 for (x = 0; x < width; ++x)
6147 int r, g, b;
6149 #ifdef USE_CAIRO
6150 int a = 0xff;
6151 r = *p++;
6152 g = *p++;
6153 b = *p++;
6154 if (channels == 4) a = *p++;
6155 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
6156 #else
6157 r = *p++ << 8;
6158 g = *p++ << 8;
6159 b = *p++ << 8;
6160 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6161 /* An alpha channel, aka mask channel, associates variable
6162 transparency with an image. Where other image formats
6163 support binary transparency---fully transparent or fully
6164 opaque---PNG allows up to 254 levels of partial transparency.
6165 The PNG library implements partial transparency by combining
6166 the image with a specified background color.
6168 I'm not sure how to handle this here nicely: because the
6169 background on which the image is displayed may change, for
6170 real alpha channel support, it would be necessary to create
6171 a new image for each possible background.
6173 What I'm doing now is that a mask is created if we have
6174 boolean transparency information. Otherwise I'm using
6175 the frame's background color to combine the image with. */
6177 if (channels == 4)
6179 if (mask_img)
6180 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6181 ++p;
6183 #endif
6187 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6188 /* Set IMG's background color from the PNG image, unless the user
6189 overrode it. */
6191 png_color_16 *bg;
6192 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6194 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6195 img->background_valid = 1;
6199 # ifdef COLOR_TABLE_SUPPORT
6200 /* Remember colors allocated for this image. */
6201 img->colors = colors_in_color_table (&img->ncolors);
6202 free_color_table ();
6203 # endif /* COLOR_TABLE_SUPPORT */
6205 /* Clean up. */
6206 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6207 xfree (rows);
6208 xfree (pixels);
6210 img->width = width;
6211 img->height = height;
6213 #ifdef USE_CAIRO
6214 create_cairo_image_surface (img, data, width, height);
6215 #else
6216 /* Maybe fill in the background field while we have ximg handy.
6217 Casting avoids a GCC warning. */
6218 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6220 /* Put ximg into the image. */
6221 image_put_x_image (f, img, ximg, 0);
6223 /* Same for the mask. */
6224 if (mask_img)
6226 /* Fill in the background_transparent field while we have the
6227 mask handy. Casting avoids a GCC warning. */
6228 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6230 image_put_x_image (f, img, mask_img, 1);
6232 #endif
6234 return 1;
6237 static bool
6238 png_load (struct frame *f, struct image *img)
6240 struct png_load_context c;
6241 return png_load_body (f, img, &c);
6244 #elif defined HAVE_NS
6246 static bool
6247 png_load (struct frame *f, struct image *img)
6249 return ns_load_image (f, img,
6250 image_spec_value (img->spec, QCfile, NULL),
6251 image_spec_value (img->spec, QCdata, NULL));
6255 #endif /* HAVE_NS */
6259 /***********************************************************************
6260 JPEG
6261 ***********************************************************************/
6263 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6265 static bool jpeg_image_p (Lisp_Object object);
6266 static bool jpeg_load (struct frame *f, struct image *img);
6268 /* Indices of image specification fields in gs_format, below. */
6270 enum jpeg_keyword_index
6272 JPEG_TYPE,
6273 JPEG_DATA,
6274 JPEG_FILE,
6275 JPEG_ASCENT,
6276 JPEG_MARGIN,
6277 JPEG_RELIEF,
6278 JPEG_ALGORITHM,
6279 JPEG_HEURISTIC_MASK,
6280 JPEG_MASK,
6281 JPEG_BACKGROUND,
6282 JPEG_LAST
6285 /* Vector of image_keyword structures describing the format
6286 of valid user-defined image specifications. */
6288 static const struct image_keyword jpeg_format[JPEG_LAST] =
6290 {":type", IMAGE_SYMBOL_VALUE, 1},
6291 {":data", IMAGE_STRING_VALUE, 0},
6292 {":file", IMAGE_STRING_VALUE, 0},
6293 {":ascent", IMAGE_ASCENT_VALUE, 0},
6294 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6295 {":relief", IMAGE_INTEGER_VALUE, 0},
6296 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6297 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6298 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6299 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6302 #if defined HAVE_NTGUI && defined WINDOWSNT
6303 static bool init_jpeg_functions (void);
6304 #else
6305 #define init_jpeg_functions NULL
6306 #endif
6308 /* Structure describing the image type `jpeg'. */
6310 static struct image_type jpeg_type =
6312 SYMBOL_INDEX (Qjpeg),
6313 jpeg_image_p,
6314 jpeg_load,
6315 x_clear_image,
6316 init_jpeg_functions,
6317 NULL
6320 /* Return true if OBJECT is a valid JPEG image specification. */
6322 static bool
6323 jpeg_image_p (Lisp_Object object)
6325 struct image_keyword fmt[JPEG_LAST];
6327 memcpy (fmt, jpeg_format, sizeof fmt);
6329 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6330 return 0;
6332 /* Must specify either the :data or :file keyword. */
6333 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6336 #endif /* HAVE_JPEG || HAVE_NS */
6338 #ifdef HAVE_JPEG
6340 /* Work around a warning about HAVE_STDLIB_H being redefined in
6341 jconfig.h. */
6342 # ifdef HAVE_STDLIB_H
6343 # undef HAVE_STDLIB_H
6344 # endif
6346 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6347 /* In older releases of the jpeg library, jpeglib.h will define boolean
6348 differently depending on __WIN32__, so make sure it is defined. */
6349 # define __WIN32__ 1
6350 # endif
6352 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6353 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6354 using the Windows boolean type instead of the jpeglib boolean type
6355 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6356 headers are included along with windows.h, so under Cygwin, jpeglib
6357 attempts to define a conflicting boolean type. Worse, forcing
6358 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6359 because it created an ABI incompatibility between the
6360 already-compiled jpeg library and the header interface definition.
6362 The best we can do is to define jpeglib's boolean type to a
6363 different name. This name, jpeg_boolean, remains in effect through
6364 the rest of image.c.
6366 # if defined CYGWIN && defined HAVE_NTGUI
6367 # define boolean jpeg_boolean
6368 # endif
6369 # include <jpeglib.h>
6370 # include <jerror.h>
6372 # ifdef WINDOWSNT
6374 /* JPEG library details. */
6375 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6376 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6377 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6378 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6379 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6380 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6381 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6382 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6383 (struct jpeg_error_mgr *));
6384 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6386 static bool
6387 init_jpeg_functions (void)
6389 HMODULE library;
6391 if (!(library = w32_delayed_load (Qjpeg)))
6392 return 0;
6394 LOAD_DLL_FN (library, jpeg_finish_decompress);
6395 LOAD_DLL_FN (library, jpeg_read_scanlines);
6396 LOAD_DLL_FN (library, jpeg_start_decompress);
6397 LOAD_DLL_FN (library, jpeg_read_header);
6398 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6399 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6400 LOAD_DLL_FN (library, jpeg_std_error);
6401 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6402 return 1;
6405 # undef jpeg_CreateDecompress
6406 # undef jpeg_destroy_decompress
6407 # undef jpeg_finish_decompress
6408 # undef jpeg_read_header
6409 # undef jpeg_read_scanlines
6410 # undef jpeg_resync_to_restart
6411 # undef jpeg_start_decompress
6412 # undef jpeg_std_error
6414 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6415 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6416 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6417 # define jpeg_read_header fn_jpeg_read_header
6418 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6419 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6420 # define jpeg_start_decompress fn_jpeg_start_decompress
6421 # define jpeg_std_error fn_jpeg_std_error
6423 /* Wrapper since we can't directly assign the function pointer
6424 to another function pointer that was declared more completely easily. */
6425 static boolean
6426 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6428 return jpeg_resync_to_restart (cinfo, desired);
6430 # undef jpeg_resync_to_restart
6431 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6433 # endif /* WINDOWSNT */
6435 struct my_jpeg_error_mgr
6437 struct jpeg_error_mgr pub;
6438 sys_jmp_buf setjmp_buffer;
6440 /* The remaining members are so that longjmp doesn't munge local
6441 variables. */
6442 struct jpeg_decompress_struct cinfo;
6443 enum
6445 MY_JPEG_ERROR_EXIT,
6446 MY_JPEG_INVALID_IMAGE_SIZE,
6447 MY_JPEG_CANNOT_CREATE_X
6448 } failure_code;
6452 static _Noreturn void
6453 my_error_exit (j_common_ptr cinfo)
6455 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6456 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6457 sys_longjmp (mgr->setjmp_buffer, 1);
6461 /* Init source method for JPEG data source manager. Called by
6462 jpeg_read_header() before any data is actually read. See
6463 libjpeg.doc from the JPEG lib distribution. */
6465 static void
6466 our_common_init_source (j_decompress_ptr cinfo)
6471 /* Method to terminate data source. Called by
6472 jpeg_finish_decompress() after all data has been processed. */
6474 static void
6475 our_common_term_source (j_decompress_ptr cinfo)
6480 /* Fill input buffer method for JPEG data source manager. Called
6481 whenever more data is needed. We read the whole image in one step,
6482 so this only adds a fake end of input marker at the end. */
6484 static JOCTET our_memory_buffer[2];
6486 static boolean
6487 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6489 /* Insert a fake EOI marker. */
6490 struct jpeg_source_mgr *src = cinfo->src;
6492 our_memory_buffer[0] = (JOCTET) 0xFF;
6493 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6495 src->next_input_byte = our_memory_buffer;
6496 src->bytes_in_buffer = 2;
6497 return 1;
6501 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6502 is the JPEG data source manager. */
6504 static void
6505 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6507 struct jpeg_source_mgr *src = cinfo->src;
6509 if (src)
6511 if (num_bytes > src->bytes_in_buffer)
6512 ERREXIT (cinfo, JERR_INPUT_EOF);
6514 src->bytes_in_buffer -= num_bytes;
6515 src->next_input_byte += num_bytes;
6520 /* Set up the JPEG lib for reading an image from DATA which contains
6521 LEN bytes. CINFO is the decompression info structure created for
6522 reading the image. */
6524 static void
6525 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6527 struct jpeg_source_mgr *src = cinfo->src;
6529 if (! src)
6531 /* First time for this JPEG object? */
6532 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6533 JPOOL_PERMANENT, sizeof *src);
6534 cinfo->src = src;
6535 src->next_input_byte = data;
6538 src->init_source = our_common_init_source;
6539 src->fill_input_buffer = our_memory_fill_input_buffer;
6540 src->skip_input_data = our_memory_skip_input_data;
6541 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6542 src->term_source = our_common_term_source;
6543 src->bytes_in_buffer = len;
6544 src->next_input_byte = data;
6548 struct jpeg_stdio_mgr
6550 struct jpeg_source_mgr mgr;
6551 boolean finished;
6552 FILE *file;
6553 JOCTET *buffer;
6557 /* Size of buffer to read JPEG from file.
6558 Not too big, as we want to use alloc_small. */
6559 #define JPEG_STDIO_BUFFER_SIZE 8192
6562 /* Fill input buffer method for JPEG data source manager. Called
6563 whenever more data is needed. The data is read from a FILE *. */
6565 static boolean
6566 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6568 struct jpeg_stdio_mgr *src;
6570 src = (struct jpeg_stdio_mgr *) cinfo->src;
6571 if (!src->finished)
6573 ptrdiff_t bytes;
6575 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6576 if (bytes > 0)
6577 src->mgr.bytes_in_buffer = bytes;
6578 else
6580 WARNMS (cinfo, JWRN_JPEG_EOF);
6581 src->finished = 1;
6582 src->buffer[0] = (JOCTET) 0xFF;
6583 src->buffer[1] = (JOCTET) JPEG_EOI;
6584 src->mgr.bytes_in_buffer = 2;
6586 src->mgr.next_input_byte = src->buffer;
6589 return 1;
6593 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6594 is the JPEG data source manager. */
6596 static void
6597 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6599 struct jpeg_stdio_mgr *src;
6600 src = (struct jpeg_stdio_mgr *) cinfo->src;
6602 while (num_bytes > 0 && !src->finished)
6604 if (num_bytes <= src->mgr.bytes_in_buffer)
6606 src->mgr.bytes_in_buffer -= num_bytes;
6607 src->mgr.next_input_byte += num_bytes;
6608 break;
6610 else
6612 num_bytes -= src->mgr.bytes_in_buffer;
6613 src->mgr.bytes_in_buffer = 0;
6614 src->mgr.next_input_byte = NULL;
6616 our_stdio_fill_input_buffer (cinfo);
6622 /* Set up the JPEG lib for reading an image from a FILE *.
6623 CINFO is the decompression info structure created for
6624 reading the image. */
6626 static void
6627 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6629 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6631 if (! src)
6633 /* First time for this JPEG object? */
6634 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6635 JPOOL_PERMANENT, sizeof *src);
6636 cinfo->src = (struct jpeg_source_mgr *) src;
6637 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6638 JPOOL_PERMANENT,
6639 JPEG_STDIO_BUFFER_SIZE);
6642 src->file = fp;
6643 src->finished = 0;
6644 src->mgr.init_source = our_common_init_source;
6645 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6646 src->mgr.skip_input_data = our_stdio_skip_input_data;
6647 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6648 src->mgr.term_source = our_common_term_source;
6649 src->mgr.bytes_in_buffer = 0;
6650 src->mgr.next_input_byte = NULL;
6653 /* Load image IMG for use on frame F. Patterned after example.c
6654 from the JPEG lib. */
6656 static bool
6657 jpeg_load_body (struct frame *f, struct image *img,
6658 struct my_jpeg_error_mgr *mgr)
6660 Lisp_Object specified_file;
6661 Lisp_Object specified_data;
6662 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6663 FILE * IF_LINT (volatile) fp = NULL;
6664 JSAMPARRAY buffer;
6665 int row_stride, x, y;
6666 unsigned long *colors;
6667 int width, height;
6668 int i, ir, ig, ib;
6669 #ifndef USE_CAIRO
6670 XImagePtr ximg = NULL;
6671 #endif
6673 /* Open the JPEG file. */
6674 specified_file = image_spec_value (img->spec, QCfile, NULL);
6675 specified_data = image_spec_value (img->spec, QCdata, NULL);
6676 IF_LINT (Lisp_Object volatile specified_data_volatile = specified_data);
6678 if (NILP (specified_data))
6680 int fd;
6681 Lisp_Object file = x_find_image_fd (specified_file, &fd);
6682 if (!STRINGP (file))
6684 image_error ("Cannot find image file `%s'", specified_file);
6685 return 0;
6688 fp = fdopen (fd, "rb");
6689 if (fp == NULL)
6691 image_error ("Cannot open `%s'", file);
6692 return 0;
6695 else if (!STRINGP (specified_data))
6697 image_error ("Invalid image data `%s'", specified_data);
6698 return 0;
6701 /* Customize libjpeg's error handling to call my_error_exit when an
6702 error is detected. This function will perform a longjmp. */
6703 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6704 mgr->pub.error_exit = my_error_exit;
6705 if (sys_setjmp (mgr->setjmp_buffer))
6707 switch (mgr->failure_code)
6709 case MY_JPEG_ERROR_EXIT:
6711 char buf[JMSG_LENGTH_MAX];
6712 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6713 image_error ("Error reading JPEG image `%s': %s",
6714 img->spec, build_string (buf));
6715 break;
6718 case MY_JPEG_INVALID_IMAGE_SIZE:
6719 image_size_error ();
6720 break;
6722 case MY_JPEG_CANNOT_CREATE_X:
6723 break;
6726 /* Close the input file and destroy the JPEG object. */
6727 if (fp)
6728 fclose (fp);
6729 jpeg_destroy_decompress (&mgr->cinfo);
6731 /* If we already have an XImage, free that. */
6732 #ifndef USE_CAIRO
6733 x_destroy_x_image (ximg);
6734 #endif
6735 /* Free pixmap and colors. */
6736 x_clear_image (f, img);
6737 return 0;
6740 /* Silence a bogus diagnostic; see GCC bug 54561. */
6741 IF_LINT (specified_data = specified_data_volatile);
6743 /* Create the JPEG decompression object. Let it read from fp.
6744 Read the JPEG image header. */
6745 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6747 if (NILP (specified_data))
6748 jpeg_file_src (&mgr->cinfo, fp);
6749 else
6750 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6751 SBYTES (specified_data));
6753 jpeg_read_header (&mgr->cinfo, 1);
6755 /* Customize decompression so that color quantization will be used.
6756 Start decompression. */
6757 mgr->cinfo.quantize_colors = 1;
6758 jpeg_start_decompress (&mgr->cinfo);
6759 width = img->width = mgr->cinfo.output_width;
6760 height = img->height = mgr->cinfo.output_height;
6762 if (!check_image_size (f, width, height))
6764 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6765 sys_longjmp (mgr->setjmp_buffer, 1);
6768 #ifndef USE_CAIRO
6769 /* Create X image and pixmap. */
6770 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6772 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6773 sys_longjmp (mgr->setjmp_buffer, 1);
6775 #endif
6777 /* Allocate colors. When color quantization is used,
6778 mgr->cinfo.actual_number_of_colors has been set with the number of
6779 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6780 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6781 No more than 255 colors will be generated. */
6782 USE_SAFE_ALLOCA;
6784 if (mgr->cinfo.out_color_components > 2)
6785 ir = 0, ig = 1, ib = 2;
6786 else if (mgr->cinfo.out_color_components > 1)
6787 ir = 0, ig = 1, ib = 0;
6788 else
6789 ir = 0, ig = 0, ib = 0;
6791 #ifndef CAIRO
6792 /* Use the color table mechanism because it handles colors that
6793 cannot be allocated nicely. Such colors will be replaced with
6794 a default color, and we don't have to care about which colors
6795 can be freed safely, and which can't. */
6796 init_color_table ();
6797 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6799 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6801 /* Multiply RGB values with 255 because X expects RGB values
6802 in the range 0..0xffff. */
6803 int r = mgr->cinfo.colormap[ir][i] << 8;
6804 int g = mgr->cinfo.colormap[ig][i] << 8;
6805 int b = mgr->cinfo.colormap[ib][i] << 8;
6806 colors[i] = lookup_rgb_color (f, r, g, b);
6808 #endif
6810 #ifdef COLOR_TABLE_SUPPORT
6811 /* Remember those colors actually allocated. */
6812 img->colors = colors_in_color_table (&img->ncolors);
6813 free_color_table ();
6814 #endif /* COLOR_TABLE_SUPPORT */
6817 /* Read pixels. */
6818 row_stride = width * mgr->cinfo.output_components;
6819 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6820 JPOOL_IMAGE, row_stride, 1);
6821 #ifdef USE_CAIRO
6823 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
6824 uint32_t *dataptr = (uint32_t *) data;
6825 int r, g, b;
6827 for (y = 0; y < height; ++y)
6829 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6831 for (x = 0; x < width; ++x)
6833 i = buffer[0][x];
6834 r = mgr->cinfo.colormap[ir][i];
6835 g = mgr->cinfo.colormap[ig][i];
6836 b = mgr->cinfo.colormap[ib][i];
6837 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
6841 create_cairo_image_surface (img, data, width, height);
6843 #else
6844 for (y = 0; y < height; ++y)
6846 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6847 for (x = 0; x < mgr->cinfo.output_width; ++x)
6848 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6850 #endif
6852 /* Clean up. */
6853 jpeg_finish_decompress (&mgr->cinfo);
6854 jpeg_destroy_decompress (&mgr->cinfo);
6855 if (fp)
6856 fclose (fp);
6858 #ifndef USE_CAIRO
6859 /* Maybe fill in the background field while we have ximg handy. */
6860 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6861 /* Casting avoids a GCC warning. */
6862 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6864 /* Put ximg into the image. */
6865 image_put_x_image (f, img, ximg, 0);
6866 #endif
6867 SAFE_FREE ();
6868 return 1;
6871 static bool
6872 jpeg_load (struct frame *f, struct image *img)
6874 struct my_jpeg_error_mgr mgr;
6875 return jpeg_load_body (f, img, &mgr);
6878 #else /* HAVE_JPEG */
6880 #ifdef HAVE_NS
6881 static bool
6882 jpeg_load (struct frame *f, struct image *img)
6884 return ns_load_image (f, img,
6885 image_spec_value (img->spec, QCfile, NULL),
6886 image_spec_value (img->spec, QCdata, NULL));
6888 #endif /* HAVE_NS */
6890 #endif /* !HAVE_JPEG */
6894 /***********************************************************************
6895 TIFF
6896 ***********************************************************************/
6898 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6900 static bool tiff_image_p (Lisp_Object object);
6901 static bool tiff_load (struct frame *f, struct image *img);
6903 /* Indices of image specification fields in tiff_format, below. */
6905 enum tiff_keyword_index
6907 TIFF_TYPE,
6908 TIFF_DATA,
6909 TIFF_FILE,
6910 TIFF_ASCENT,
6911 TIFF_MARGIN,
6912 TIFF_RELIEF,
6913 TIFF_ALGORITHM,
6914 TIFF_HEURISTIC_MASK,
6915 TIFF_MASK,
6916 TIFF_BACKGROUND,
6917 TIFF_INDEX,
6918 TIFF_LAST
6921 /* Vector of image_keyword structures describing the format
6922 of valid user-defined image specifications. */
6924 static const struct image_keyword tiff_format[TIFF_LAST] =
6926 {":type", IMAGE_SYMBOL_VALUE, 1},
6927 {":data", IMAGE_STRING_VALUE, 0},
6928 {":file", IMAGE_STRING_VALUE, 0},
6929 {":ascent", IMAGE_ASCENT_VALUE, 0},
6930 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6931 {":relief", IMAGE_INTEGER_VALUE, 0},
6932 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6933 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6934 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6935 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6936 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6939 #if defined HAVE_NTGUI && defined WINDOWSNT
6940 static bool init_tiff_functions (void);
6941 #else
6942 #define init_tiff_functions NULL
6943 #endif
6945 /* Structure describing the image type `tiff'. */
6947 static struct image_type tiff_type =
6949 SYMBOL_INDEX (Qtiff),
6950 tiff_image_p,
6951 tiff_load,
6952 x_clear_image,
6953 init_tiff_functions,
6954 NULL
6957 /* Return true if OBJECT is a valid TIFF image specification. */
6959 static bool
6960 tiff_image_p (Lisp_Object object)
6962 struct image_keyword fmt[TIFF_LAST];
6963 memcpy (fmt, tiff_format, sizeof fmt);
6965 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6966 return 0;
6968 /* Must specify either the :data or :file keyword. */
6969 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6972 #endif /* HAVE_TIFF || HAVE_NS */
6974 #ifdef HAVE_TIFF
6976 # include <tiffio.h>
6978 # ifdef WINDOWSNT
6980 /* TIFF library details. */
6981 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6982 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6983 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
6984 DEF_DLL_FN (TIFF *, TIFFClientOpen,
6985 (const char *, const char *, thandle_t, TIFFReadWriteProc,
6986 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6987 TIFFMapFileProc, TIFFUnmapFileProc));
6988 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6989 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6990 DEF_DLL_FN (void, TIFFClose, (TIFF *));
6991 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6993 static bool
6994 init_tiff_functions (void)
6996 HMODULE library;
6998 if (!(library = w32_delayed_load (Qtiff)))
6999 return 0;
7001 LOAD_DLL_FN (library, TIFFSetErrorHandler);
7002 LOAD_DLL_FN (library, TIFFSetWarningHandler);
7003 LOAD_DLL_FN (library, TIFFOpen);
7004 LOAD_DLL_FN (library, TIFFClientOpen);
7005 LOAD_DLL_FN (library, TIFFGetField);
7006 LOAD_DLL_FN (library, TIFFReadRGBAImage);
7007 LOAD_DLL_FN (library, TIFFClose);
7008 LOAD_DLL_FN (library, TIFFSetDirectory);
7009 return 1;
7012 # undef TIFFClientOpen
7013 # undef TIFFClose
7014 # undef TIFFGetField
7015 # undef TIFFOpen
7016 # undef TIFFReadRGBAImage
7017 # undef TIFFSetDirectory
7018 # undef TIFFSetErrorHandler
7019 # undef TIFFSetWarningHandler
7021 # define TIFFClientOpen fn_TIFFClientOpen
7022 # define TIFFClose fn_TIFFClose
7023 # define TIFFGetField fn_TIFFGetField
7024 # define TIFFOpen fn_TIFFOpen
7025 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7026 # define TIFFSetDirectory fn_TIFFSetDirectory
7027 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7028 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7030 # endif /* WINDOWSNT */
7033 /* Reading from a memory buffer for TIFF images Based on the PNG
7034 memory source, but we have to provide a lot of extra functions.
7035 Blah.
7037 We really only need to implement read and seek, but I am not
7038 convinced that the TIFF library is smart enough not to destroy
7039 itself if we only hand it the function pointers we need to
7040 override. */
7042 typedef struct
7044 unsigned char *bytes;
7045 ptrdiff_t len;
7046 ptrdiff_t index;
7048 tiff_memory_source;
7050 static tsize_t
7051 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7053 tiff_memory_source *src = (tiff_memory_source *) data;
7055 size = min (size, src->len - src->index);
7056 memcpy (buf, src->bytes + src->index, size);
7057 src->index += size;
7058 return size;
7061 static tsize_t
7062 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7064 return -1;
7067 static toff_t
7068 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
7070 tiff_memory_source *src = (tiff_memory_source *) data;
7071 ptrdiff_t idx;
7073 switch (whence)
7075 case SEEK_SET: /* Go from beginning of source. */
7076 idx = off;
7077 break;
7079 case SEEK_END: /* Go from end of source. */
7080 idx = src->len + off;
7081 break;
7083 case SEEK_CUR: /* Go from current position. */
7084 idx = src->index + off;
7085 break;
7087 default: /* Invalid `whence'. */
7088 return -1;
7091 if (idx > src->len || idx < 0)
7092 return -1;
7094 src->index = idx;
7095 return src->index;
7098 static int
7099 tiff_close_memory (thandle_t data)
7101 /* NOOP */
7102 return 0;
7105 static int
7106 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
7108 /* It is already _IN_ memory. */
7109 return 0;
7112 static void
7113 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
7115 /* We don't need to do this. */
7118 static toff_t
7119 tiff_size_of_memory (thandle_t data)
7121 return ((tiff_memory_source *) data)->len;
7124 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7125 compiler error compiling tiff_handler, see Bugzilla bug #17406
7126 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7127 this function as external works around that problem. */
7128 # if defined (__MINGW32__) && __GNUC__ == 3
7129 # define MINGW_STATIC
7130 # else
7131 # define MINGW_STATIC static
7132 # endif
7134 MINGW_STATIC void
7135 tiff_handler (const char *, const char *, const char *, va_list)
7136 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7137 MINGW_STATIC void
7138 tiff_handler (const char *log_format, const char *title,
7139 const char *format, va_list ap)
7141 /* doprnt is not suitable here, as TIFF handlers are called from
7142 libtiff and are passed arbitrary printf directives. Instead, use
7143 vsnprintf, taking care to be portable to nonstandard environments
7144 where vsnprintf returns -1 on buffer overflow. Since it's just a
7145 log entry, it's OK to truncate it. */
7146 char buf[4000];
7147 int len = vsnprintf (buf, sizeof buf, format, ap);
7148 add_to_log (log_format, build_string (title),
7149 make_string (buf, max (0, min (len, sizeof buf - 1))));
7151 # undef MINGW_STATIC
7153 static void tiff_error_handler (const char *, const char *, va_list)
7154 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7155 static void
7156 tiff_error_handler (const char *title, const char *format, va_list ap)
7158 tiff_handler ("TIFF error: %s %s", title, format, ap);
7162 static void tiff_warning_handler (const char *, const char *, va_list)
7163 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7164 static void
7165 tiff_warning_handler (const char *title, const char *format, va_list ap)
7167 tiff_handler ("TIFF warning: %s %s", title, format, ap);
7171 /* Load TIFF image IMG for use on frame F. Value is true if
7172 successful. */
7174 static bool
7175 tiff_load (struct frame *f, struct image *img)
7177 Lisp_Object specified_file;
7178 Lisp_Object specified_data;
7179 TIFF *tiff;
7180 int width, height, x, y, count;
7181 uint32 *buf;
7182 int rc;
7183 XImagePtr ximg;
7184 tiff_memory_source memsrc;
7185 Lisp_Object image;
7187 specified_file = image_spec_value (img->spec, QCfile, NULL);
7188 specified_data = image_spec_value (img->spec, QCdata, NULL);
7190 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
7191 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7193 if (NILP (specified_data))
7195 /* Read from a file */
7196 Lisp_Object file = x_find_image_file (specified_file);
7197 if (!STRINGP (file))
7199 image_error ("Cannot find image file `%s'", specified_file);
7200 return 0;
7203 Lisp_Object encoded_file = ENCODE_FILE (file);
7204 # ifdef WINDOWSNT
7205 encoded_file = ansi_encode_filename (encoded_file);
7206 # endif
7208 /* Try to open the image file. */
7209 tiff = TIFFOpen (SSDATA (encoded_file), "r");
7210 if (tiff == NULL)
7212 image_error ("Cannot open `%s'", file);
7213 return 0;
7216 else
7218 if (!STRINGP (specified_data))
7220 image_error ("Invalid image data `%s'", specified_data);
7221 return 0;
7224 /* Memory source! */
7225 memsrc.bytes = SDATA (specified_data);
7226 memsrc.len = SBYTES (specified_data);
7227 memsrc.index = 0;
7229 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7230 tiff_read_from_memory,
7231 tiff_write_from_memory,
7232 tiff_seek_in_memory,
7233 tiff_close_memory,
7234 tiff_size_of_memory,
7235 tiff_mmap_memory,
7236 tiff_unmap_memory);
7238 if (!tiff)
7240 image_error ("Cannot open memory source for `%s'", img->spec);
7241 return 0;
7245 image = image_spec_value (img->spec, QCindex, NULL);
7246 if (INTEGERP (image))
7248 EMACS_INT ino = XFASTINT (image);
7249 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7250 && TIFFSetDirectory (tiff, ino)))
7252 image_error ("Invalid image number `%s' in image `%s'",
7253 image, img->spec);
7254 TIFFClose (tiff);
7255 return 0;
7259 /* Get width and height of the image, and allocate a raster buffer
7260 of width x height 32-bit values. */
7261 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7262 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7264 if (!check_image_size (f, width, height))
7266 image_size_error ();
7267 TIFFClose (tiff);
7268 return 0;
7271 /* Create the X image and pixmap. */
7272 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7273 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7274 &ximg, 0)))
7276 TIFFClose (tiff);
7277 return 0;
7280 buf = xmalloc (sizeof *buf * width * height);
7282 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7284 /* Count the number of images in the file. */
7285 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7286 continue;
7288 if (count > 1)
7289 img->lisp_data = Fcons (Qcount,
7290 Fcons (make_number (count),
7291 img->lisp_data));
7293 TIFFClose (tiff);
7294 if (!rc)
7296 image_error ("Error reading TIFF image `%s'", img->spec);
7297 xfree (buf);
7298 return 0;
7301 #ifdef USE_CAIRO
7303 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
7304 uint32_t *dataptr = (uint32_t *) data;
7305 int r, g, b, a;
7307 for (y = 0; y < height; ++y)
7309 uint32 *row = buf + (height - 1 - y) * width;
7310 for (x = 0; x < width; ++x)
7312 uint32 abgr = row[x];
7313 int r = TIFFGetR (abgr);
7314 int g = TIFFGetG (abgr);
7315 int b = TIFFGetB (abgr);
7316 int a = TIFFGetA (abgr);
7317 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
7321 create_cairo_image_surface (img, data, width, height);
7323 #else
7324 /* Initialize the color table. */
7325 init_color_table ();
7327 /* Process the pixel raster. Origin is in the lower-left corner. */
7328 for (y = 0; y < height; ++y)
7330 uint32 *row = buf + y * width;
7332 for (x = 0; x < width; ++x)
7334 uint32 abgr = row[x];
7335 int r = TIFFGetR (abgr) << 8;
7336 int g = TIFFGetG (abgr) << 8;
7337 int b = TIFFGetB (abgr) << 8;
7338 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7342 # ifdef COLOR_TABLE_SUPPORT
7343 /* Remember the colors allocated for the image. Free the color table. */
7344 img->colors = colors_in_color_table (&img->ncolors);
7345 free_color_table ();
7346 # endif /* COLOR_TABLE_SUPPORT */
7348 img->width = width;
7349 img->height = height;
7351 /* Maybe fill in the background field while we have ximg handy. */
7352 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7353 /* Casting avoids a GCC warning on W32. */
7354 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7356 /* Put ximg into the image. */
7357 image_put_x_image (f, img, ximg, 0);
7359 #endif /* ! USE_CAIRO */
7361 xfree (buf);
7362 return 1;
7365 #elif defined HAVE_NS
7367 static bool
7368 tiff_load (struct frame *f, struct image *img)
7370 return ns_load_image (f, img,
7371 image_spec_value (img->spec, QCfile, NULL),
7372 image_spec_value (img->spec, QCdata, NULL));
7375 #endif
7379 /***********************************************************************
7381 ***********************************************************************/
7383 #if defined (HAVE_GIF) || defined (HAVE_NS)
7385 static bool gif_image_p (Lisp_Object object);
7386 static bool gif_load (struct frame *f, struct image *img);
7387 static void gif_clear_image (struct frame *f, struct image *img);
7389 /* Indices of image specification fields in gif_format, below. */
7391 enum gif_keyword_index
7393 GIF_TYPE,
7394 GIF_DATA,
7395 GIF_FILE,
7396 GIF_ASCENT,
7397 GIF_MARGIN,
7398 GIF_RELIEF,
7399 GIF_ALGORITHM,
7400 GIF_HEURISTIC_MASK,
7401 GIF_MASK,
7402 GIF_IMAGE,
7403 GIF_BACKGROUND,
7404 GIF_LAST
7407 /* Vector of image_keyword structures describing the format
7408 of valid user-defined image specifications. */
7410 static const struct image_keyword gif_format[GIF_LAST] =
7412 {":type", IMAGE_SYMBOL_VALUE, 1},
7413 {":data", IMAGE_STRING_VALUE, 0},
7414 {":file", IMAGE_STRING_VALUE, 0},
7415 {":ascent", IMAGE_ASCENT_VALUE, 0},
7416 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7417 {":relief", IMAGE_INTEGER_VALUE, 0},
7418 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7419 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7420 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7421 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7422 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7425 #if defined HAVE_NTGUI && defined WINDOWSNT
7426 static bool init_gif_functions (void);
7427 #else
7428 #define init_gif_functions NULL
7429 #endif
7431 /* Structure describing the image type `gif'. */
7433 static struct image_type gif_type =
7435 SYMBOL_INDEX (Qgif),
7436 gif_image_p,
7437 gif_load,
7438 gif_clear_image,
7439 init_gif_functions,
7440 NULL
7443 /* Free X resources of GIF image IMG which is used on frame F. */
7445 static void
7446 gif_clear_image (struct frame *f, struct image *img)
7448 img->lisp_data = Qnil;
7449 x_clear_image (f, img);
7452 /* Return true if OBJECT is a valid GIF image specification. */
7454 static bool
7455 gif_image_p (Lisp_Object object)
7457 struct image_keyword fmt[GIF_LAST];
7458 memcpy (fmt, gif_format, sizeof fmt);
7460 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7461 return 0;
7463 /* Must specify either the :data or :file keyword. */
7464 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7467 #endif /* HAVE_GIF */
7469 #ifdef HAVE_GIF
7471 # ifdef HAVE_NTGUI
7473 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7474 Undefine before redefining to avoid a preprocessor warning. */
7475 # ifdef DrawText
7476 # undef DrawText
7477 # endif
7478 /* avoid conflict with QuickdrawText.h */
7479 # define DrawText gif_DrawText
7480 # include <gif_lib.h>
7481 # undef DrawText
7483 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7484 # ifndef GIFLIB_MINOR
7485 # define GIFLIB_MINOR 0
7486 # endif
7487 # ifndef GIFLIB_RELEASE
7488 # define GIFLIB_RELEASE 0
7489 # endif
7491 # else /* HAVE_NTGUI */
7493 # include <gif_lib.h>
7495 # endif /* HAVE_NTGUI */
7497 /* Giflib before 5.0 didn't define these macros. */
7498 # ifndef GIFLIB_MAJOR
7499 # define GIFLIB_MAJOR 4
7500 # endif
7502 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7503 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7504 earlier releases, where either it returns char * or GIFLIB_MINOR
7505 may be incorrect. */
7506 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7508 # ifdef WINDOWSNT
7510 /* GIF library details. */
7511 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7512 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7513 # else
7514 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7515 # endif
7516 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7517 # if GIFLIB_MAJOR < 5
7518 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7519 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7520 # else
7521 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7522 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7523 # endif
7524 # if HAVE_GIFERRORSTRING
7525 DEF_DLL_FN (char const *, GifErrorString, (int));
7526 # endif
7528 static bool
7529 init_gif_functions (void)
7531 HMODULE library;
7533 if (!(library = w32_delayed_load (Qgif)))
7534 return 0;
7536 LOAD_DLL_FN (library, DGifCloseFile);
7537 LOAD_DLL_FN (library, DGifSlurp);
7538 LOAD_DLL_FN (library, DGifOpen);
7539 LOAD_DLL_FN (library, DGifOpenFileName);
7540 # if HAVE_GIFERRORSTRING
7541 LOAD_DLL_FN (library, GifErrorString);
7542 # endif
7543 return 1;
7546 # undef DGifCloseFile
7547 # undef DGifOpen
7548 # undef DGifOpenFileName
7549 # undef DGifSlurp
7550 # undef GifErrorString
7552 # define DGifCloseFile fn_DGifCloseFile
7553 # define DGifOpen fn_DGifOpen
7554 # define DGifOpenFileName fn_DGifOpenFileName
7555 # define DGifSlurp fn_DGifSlurp
7556 # define GifErrorString fn_GifErrorString
7558 # endif /* WINDOWSNT */
7560 /* Reading a GIF image from memory
7561 Based on the PNG memory stuff to a certain extent. */
7563 typedef struct
7565 unsigned char *bytes;
7566 ptrdiff_t len;
7567 ptrdiff_t index;
7569 gif_memory_source;
7571 /* Make the current memory source available to gif_read_from_memory.
7572 It's done this way because not all versions of libungif support
7573 a UserData field in the GifFileType structure. */
7574 static gif_memory_source *current_gif_memory_src;
7576 static int
7577 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7579 gif_memory_source *src = current_gif_memory_src;
7581 if (len > src->len - src->index)
7582 return -1;
7584 memcpy (buf, src->bytes + src->index, len);
7585 src->index += len;
7586 return len;
7589 static int
7590 gif_close (GifFileType *gif, int *err)
7592 int retval;
7594 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7595 retval = DGifCloseFile (gif, err);
7596 #else
7597 retval = DGifCloseFile (gif);
7598 #if GIFLIB_MAJOR >= 5
7599 if (err)
7600 *err = gif->Error;
7601 #endif
7602 #endif
7603 return retval;
7606 /* Load GIF image IMG for use on frame F. Value is true if
7607 successful. */
7609 static const int interlace_start[] = {0, 4, 2, 1};
7610 static const int interlace_increment[] = {8, 8, 4, 2};
7612 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7614 static bool
7615 gif_load (struct frame *f, struct image *img)
7617 int rc, width, height, x, y, i, j;
7618 ColorMapObject *gif_color_map;
7619 unsigned long pixel_colors[256];
7620 GifFileType *gif;
7621 gif_memory_source memsrc;
7622 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7623 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7624 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7625 unsigned long bgcolor = 0;
7626 EMACS_INT idx;
7627 int gif_err;
7629 #ifdef USE_CAIRO
7630 unsigned char *data = 0;
7631 #else
7632 XImagePtr ximg;
7633 #endif
7635 if (NILP (specified_data))
7637 Lisp_Object file = x_find_image_file (specified_file);
7638 if (!STRINGP (file))
7640 image_error ("Cannot find image file `%s'", specified_file);
7641 return 0;
7644 Lisp_Object encoded_file = ENCODE_FILE (file);
7645 #ifdef WINDOWSNT
7646 encoded_file = ansi_encode_filename (encoded_file);
7647 #endif
7649 /* Open the GIF file. */
7650 #if GIFLIB_MAJOR < 5
7651 gif = DGifOpenFileName (SSDATA (encoded_file));
7652 #else
7653 gif = DGifOpenFileName (SSDATA (encoded_file), &gif_err);
7654 #endif
7655 if (gif == NULL)
7657 #if HAVE_GIFERRORSTRING
7658 image_error ("Cannot open `%s': %s",
7659 file, build_string (GifErrorString (gif_err)));
7660 #else
7661 image_error ("Cannot open `%s'", file);
7662 #endif
7663 return 0;
7666 else
7668 if (!STRINGP (specified_data))
7670 image_error ("Invalid image data `%s'", specified_data);
7671 return 0;
7674 /* Read from memory! */
7675 current_gif_memory_src = &memsrc;
7676 memsrc.bytes = SDATA (specified_data);
7677 memsrc.len = SBYTES (specified_data);
7678 memsrc.index = 0;
7680 #if GIFLIB_MAJOR < 5
7681 gif = DGifOpen (&memsrc, gif_read_from_memory);
7682 #else
7683 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7684 #endif
7685 if (!gif)
7687 #if HAVE_GIFERRORSTRING
7688 image_error ("Cannot open memory source `%s': %s",
7689 img->spec, build_string (GifErrorString (gif_err)));
7690 #else
7691 image_error ("Cannot open memory source `%s'", img->spec);
7692 #endif
7693 return 0;
7697 /* Before reading entire contents, check the declared image size. */
7698 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7700 image_size_error ();
7701 gif_close (gif, NULL);
7702 return 0;
7705 /* Read entire contents. */
7706 rc = DGifSlurp (gif);
7707 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7709 image_error ("Error reading `%s'", img->spec);
7710 gif_close (gif, NULL);
7711 return 0;
7714 /* Which sub-image are we to display? */
7716 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7717 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7718 if (idx < 0 || idx >= gif->ImageCount)
7720 image_error ("Invalid image number `%s' in image `%s'",
7721 image_number, img->spec);
7722 gif_close (gif, NULL);
7723 return 0;
7727 width = img->width = gif->SWidth;
7728 height = img->height = gif->SHeight;
7730 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7731 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7732 img->corners[BOT_CORNER]
7733 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7734 img->corners[RIGHT_CORNER]
7735 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7737 if (!check_image_size (f, width, height))
7739 image_size_error ();
7740 gif_close (gif, NULL);
7741 return 0;
7744 /* Check that the selected subimages fit. It's not clear whether
7745 the GIF spec requires this, but Emacs can crash if they don't fit. */
7746 for (j = 0; j <= idx; ++j)
7748 struct SavedImage *subimage = gif->SavedImages + j;
7749 int subimg_width = subimage->ImageDesc.Width;
7750 int subimg_height = subimage->ImageDesc.Height;
7751 int subimg_top = subimage->ImageDesc.Top;
7752 int subimg_left = subimage->ImageDesc.Left;
7753 if (! (subimg_width >= 0 && subimg_height >= 0
7754 && 0 <= subimg_top && subimg_top <= height - subimg_height
7755 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7757 image_error ("Subimage does not fit in image");
7758 gif_close (gif, NULL);
7759 return 0;
7763 #ifdef USE_CAIRO
7764 /* xzalloc so data is zero => transparent */
7765 data = (unsigned char *) xzalloc (width * height * 4);
7766 if (STRINGP (specified_bg))
7768 XColor color;
7769 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
7771 uint32_t *dataptr = (uint32_t *)data;
7772 int r = color.red/256;
7773 int g = color.green/256;
7774 int b = color.blue/256;
7776 for (y = 0; y < height; ++y)
7777 for (x = 0; x < width; ++x)
7778 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
7781 #else
7782 /* Create the X image and pixmap. */
7783 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7785 gif_close (gif, NULL);
7786 return 0;
7789 /* Clear the part of the screen image not covered by the image.
7790 Full animated GIF support requires more here (see the gif89 spec,
7791 disposal methods). Let's simply assume that the part not covered
7792 by a sub-image is in the frame's background color. */
7793 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7794 for (x = 0; x < width; ++x)
7795 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7797 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7798 for (x = 0; x < width; ++x)
7799 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7801 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7803 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7804 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7805 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7806 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7808 #endif
7810 /* Read the GIF image into the X image. */
7812 /* FIXME: With the current implementation, loading an animated gif
7813 is quadratic in the number of animation frames, since each frame
7814 is a separate struct image. We must provide a way for a single
7815 gif_load call to construct and save all animation frames. */
7817 init_color_table ();
7818 if (STRINGP (specified_bg))
7819 bgcolor = x_alloc_image_color (f, img, specified_bg,
7820 FRAME_BACKGROUND_PIXEL (f));
7821 for (j = 0; j <= idx; ++j)
7823 /* We use a local variable `raster' here because RasterBits is a
7824 char *, which invites problems with bytes >= 0x80. */
7825 struct SavedImage *subimage = gif->SavedImages + j;
7826 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7827 int transparency_color_index = -1;
7828 int disposal = 0;
7829 int subimg_width = subimage->ImageDesc.Width;
7830 int subimg_height = subimage->ImageDesc.Height;
7831 int subimg_top = subimage->ImageDesc.Top;
7832 int subimg_left = subimage->ImageDesc.Left;
7834 /* Find the Graphic Control Extension block for this sub-image.
7835 Extract the disposal method and transparency color. */
7836 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7838 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7840 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7841 && extblock->ByteCount == 4
7842 && extblock->Bytes[0] & 1)
7844 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7845 to background". Treat any other value like 2. */
7846 disposal = (extblock->Bytes[0] >> 2) & 7;
7847 transparency_color_index = (unsigned char) extblock->Bytes[3];
7848 break;
7852 /* We can't "keep in place" the first subimage. */
7853 if (j == 0)
7854 disposal = 2;
7856 /* For disposal == 0, the spec says "No disposal specified. The
7857 decoder is not required to take any action." In practice, it
7858 seems we need to treat this like "keep in place", see e.g.
7859 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7860 if (disposal == 0)
7861 disposal = 1;
7863 gif_color_map = subimage->ImageDesc.ColorMap;
7864 if (!gif_color_map)
7865 gif_color_map = gif->SColorMap;
7867 #ifndef USE_CAIRO
7868 /* Allocate subimage colors. */
7869 memset (pixel_colors, 0, sizeof pixel_colors);
7871 if (gif_color_map)
7872 for (i = 0; i < gif_color_map->ColorCount; ++i)
7874 if (transparency_color_index == i)
7875 pixel_colors[i] = STRINGP (specified_bg)
7876 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7877 else
7879 int r = gif_color_map->Colors[i].Red << 8;
7880 int g = gif_color_map->Colors[i].Green << 8;
7881 int b = gif_color_map->Colors[i].Blue << 8;
7882 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7885 #endif
7887 /* Apply the pixel values. */
7888 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7890 int row, pass;
7892 for (y = 0, row = interlace_start[0], pass = 0;
7893 y < subimg_height;
7894 y++, row += interlace_increment[pass])
7896 while (subimg_height <= row)
7897 row = interlace_start[++pass];
7899 for (x = 0; x < subimg_width; x++)
7901 int c = raster[y * subimg_width + x];
7902 if (transparency_color_index != c || disposal != 1)
7904 #ifdef USE_CAIRO
7905 uint32_t *dataptr =
7906 ((uint32_t*)data + ((row + subimg_top) * subimg_width
7907 + x + subimg_left));
7908 int r = gif_color_map->Colors[c].Red;
7909 int g = gif_color_map->Colors[c].Green;
7910 int b = gif_color_map->Colors[c].Blue;
7912 if (transparency_color_index != c)
7913 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7914 #else
7915 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7916 pixel_colors[c]);
7917 #endif
7922 else
7924 for (y = 0; y < subimg_height; ++y)
7925 for (x = 0; x < subimg_width; ++x)
7927 int c = raster[y * subimg_width + x];
7928 if (transparency_color_index != c || disposal != 1)
7930 #ifdef USE_CAIRO
7931 uint32_t *dataptr =
7932 ((uint32_t*)data + ((y + subimg_top) * subimg_width
7933 + x + subimg_left));
7934 int r = gif_color_map->Colors[c].Red;
7935 int g = gif_color_map->Colors[c].Green;
7936 int b = gif_color_map->Colors[c].Blue;
7937 if (transparency_color_index != c)
7938 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7939 #else
7940 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7941 pixel_colors[c]);
7942 #endif
7948 #ifdef COLOR_TABLE_SUPPORT
7949 img->colors = colors_in_color_table (&img->ncolors);
7950 free_color_table ();
7951 #endif /* COLOR_TABLE_SUPPORT */
7953 /* Save GIF image extension data for `image-metadata'.
7954 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7955 img->lisp_data = Qnil;
7956 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7958 int delay = 0;
7959 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7960 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7961 /* Append (... FUNCTION "BYTES") */
7963 img->lisp_data
7964 = Fcons (make_number (ext->Function),
7965 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7966 img->lisp_data));
7967 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7968 && ext->ByteCount == 4)
7970 delay = ext->Bytes[2] << CHAR_BIT;
7971 delay |= ext->Bytes[1];
7974 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7975 if (delay)
7976 img->lisp_data
7977 = Fcons (Qdelay,
7978 Fcons (make_float (delay / 100.0),
7979 img->lisp_data));
7982 if (gif->ImageCount > 1)
7983 img->lisp_data = Fcons (Qcount,
7984 Fcons (make_number (gif->ImageCount),
7985 img->lisp_data));
7987 if (gif_close (gif, &gif_err) == GIF_ERROR)
7989 #if HAVE_GIFERRORSTRING
7990 char const *error_text = GifErrorString (gif_err);
7992 if (error_text)
7993 image_error ("Error closing `%s': %s",
7994 img->spec, build_string (error_text));
7995 #else
7996 image_error ("Error closing `%s'", img->spec);
7997 #endif
8000 #ifdef USE_CAIRO
8001 create_cairo_image_surface (img, data, width, height);
8002 #else
8003 /* Maybe fill in the background field while we have ximg handy. */
8004 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8005 /* Casting avoids a GCC warning. */
8006 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8008 /* Put ximg into the image. */
8009 image_put_x_image (f, img, ximg, 0);
8010 #endif
8012 return 1;
8015 #else /* !HAVE_GIF */
8017 #ifdef HAVE_NS
8018 static bool
8019 gif_load (struct frame *f, struct image *img)
8021 return ns_load_image (f, img,
8022 image_spec_value (img->spec, QCfile, NULL),
8023 image_spec_value (img->spec, QCdata, NULL));
8025 #endif /* HAVE_NS */
8027 #endif /* HAVE_GIF */
8030 #ifdef HAVE_IMAGEMAGICK
8032 /***********************************************************************
8033 ImageMagick
8034 ***********************************************************************/
8036 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8037 safely rounded and clipped to int range. */
8039 static int
8040 scale_image_size (int size, size_t divisor, size_t multiplier)
8042 if (divisor != 0)
8044 double s = size;
8045 double scaled = s * multiplier / divisor + 0.5;
8046 if (scaled < INT_MAX)
8047 return scaled;
8049 return INT_MAX;
8052 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8053 Use SPEC to deduce the size. Store the desired size into
8054 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8055 static void
8056 compute_image_size (size_t width, size_t height,
8057 Lisp_Object spec,
8058 int *d_width, int *d_height)
8060 Lisp_Object value;
8061 int desired_width, desired_height;
8063 /* If width and/or height is set in the display spec assume we want
8064 to scale to those values. If either h or w is unspecified, the
8065 unspecified should be calculated from the specified to preserve
8066 aspect ratio. */
8067 value = image_spec_value (spec, QCwidth, NULL);
8068 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8069 value = image_spec_value (spec, QCheight, NULL);
8070 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
8072 if (desired_width == -1)
8074 value = image_spec_value (spec, QCmax_width, NULL);
8075 if (NATNUMP (value))
8077 int max_width = min (XFASTINT (value), INT_MAX);
8078 if (max_width < width)
8080 /* The image is wider than :max-width. */
8081 desired_width = max_width;
8082 if (desired_height == -1)
8084 desired_height = scale_image_size (desired_width,
8085 width, height);
8086 value = image_spec_value (spec, QCmax_height, NULL);
8087 if (NATNUMP (value))
8089 int max_height = min (XFASTINT (value), INT_MAX);
8090 if (max_height < desired_height)
8092 desired_height = max_height;
8093 desired_width = scale_image_size (desired_height,
8094 height, width);
8102 if (desired_height == -1)
8104 value = image_spec_value (spec, QCmax_height, NULL);
8105 if (NATNUMP (value))
8107 int max_height = min (XFASTINT (value), INT_MAX);
8108 if (max_height < height)
8109 desired_height = max_height;
8113 if (desired_width != -1 && desired_height == -1)
8114 /* w known, calculate h. */
8115 desired_height = scale_image_size (desired_width, width, height);
8117 if (desired_width == -1 && desired_height != -1)
8118 /* h known, calculate w. */
8119 desired_width = scale_image_size (desired_height, height, width);
8121 *d_width = desired_width;
8122 *d_height = desired_height;
8125 static bool imagemagick_image_p (Lisp_Object);
8126 static bool imagemagick_load (struct frame *, struct image *);
8127 static void imagemagick_clear_image (struct frame *, struct image *);
8129 /* Indices of image specification fields in imagemagick_format. */
8131 enum imagemagick_keyword_index
8133 IMAGEMAGICK_TYPE,
8134 IMAGEMAGICK_DATA,
8135 IMAGEMAGICK_FILE,
8136 IMAGEMAGICK_ASCENT,
8137 IMAGEMAGICK_MARGIN,
8138 IMAGEMAGICK_RELIEF,
8139 IMAGEMAGICK_ALGORITHM,
8140 IMAGEMAGICK_HEURISTIC_MASK,
8141 IMAGEMAGICK_MASK,
8142 IMAGEMAGICK_BACKGROUND,
8143 IMAGEMAGICK_HEIGHT,
8144 IMAGEMAGICK_WIDTH,
8145 IMAGEMAGICK_MAX_HEIGHT,
8146 IMAGEMAGICK_MAX_WIDTH,
8147 IMAGEMAGICK_FORMAT,
8148 IMAGEMAGICK_ROTATION,
8149 IMAGEMAGICK_CROP,
8150 IMAGEMAGICK_LAST
8153 /* Vector of image_keyword structures describing the format
8154 of valid user-defined image specifications. */
8156 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
8158 {":type", IMAGE_SYMBOL_VALUE, 1},
8159 {":data", IMAGE_STRING_VALUE, 0},
8160 {":file", IMAGE_STRING_VALUE, 0},
8161 {":ascent", IMAGE_ASCENT_VALUE, 0},
8162 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8163 {":relief", IMAGE_INTEGER_VALUE, 0},
8164 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8165 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8166 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8167 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8168 {":height", IMAGE_INTEGER_VALUE, 0},
8169 {":width", IMAGE_INTEGER_VALUE, 0},
8170 {":max-height", IMAGE_INTEGER_VALUE, 0},
8171 {":max-width", IMAGE_INTEGER_VALUE, 0},
8172 {":format", IMAGE_SYMBOL_VALUE, 0},
8173 {":rotation", IMAGE_NUMBER_VALUE, 0},
8174 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8177 #if defined HAVE_NTGUI && defined WINDOWSNT
8178 static bool init_imagemagick_functions (void);
8179 #else
8180 #define init_imagemagick_functions NULL
8181 #endif
8183 /* Structure describing the image type for any image handled via
8184 ImageMagick. */
8186 static struct image_type imagemagick_type =
8188 SYMBOL_INDEX (Qimagemagick),
8189 imagemagick_image_p,
8190 imagemagick_load,
8191 imagemagick_clear_image,
8192 init_imagemagick_functions,
8193 NULL
8196 /* Free X resources of imagemagick image IMG which is used on frame F. */
8198 static void
8199 imagemagick_clear_image (struct frame *f,
8200 struct image *img)
8202 x_clear_image (f, img);
8205 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8206 this by calling parse_image_spec and supplying the keywords that
8207 identify the IMAGEMAGICK format. */
8209 static bool
8210 imagemagick_image_p (Lisp_Object object)
8212 struct image_keyword fmt[IMAGEMAGICK_LAST];
8213 memcpy (fmt, imagemagick_format, sizeof fmt);
8215 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
8216 return 0;
8218 /* Must specify either the :data or :file keyword. */
8219 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
8222 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8223 Therefore rename the function so it doesn't collide with ImageMagick. */
8224 #define DrawRectangle DrawRectangleGif
8225 #include <wand/MagickWand.h>
8227 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8228 Emacs seems to work fine with the hidden version, so unhide it. */
8229 #include <magick/version.h>
8230 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8231 extern WandExport void PixelGetMagickColor (const PixelWand *,
8232 MagickPixelPacket *);
8233 #endif
8235 /* Log ImageMagick error message.
8236 Useful when a ImageMagick function returns the status `MagickFalse'. */
8238 static void
8239 imagemagick_error (MagickWand *wand)
8241 char *description;
8242 ExceptionType severity;
8244 description = MagickGetException (wand, &severity);
8245 image_error ("ImageMagick error: %s", build_string (description));
8246 MagickRelinquishMemory (description);
8249 /* Possibly give ImageMagick some extra help to determine the image
8250 type by supplying a "dummy" filename based on the Content-Type. */
8252 static char *
8253 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
8255 Lisp_Object symbol = intern ("image-format-suffixes");
8256 Lisp_Object val = find_symbol_value (symbol);
8257 Lisp_Object format;
8259 if (! CONSP (val))
8260 return NULL;
8262 format = image_spec_value (spec, intern (":format"), NULL);
8263 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
8264 if (! STRINGP (val))
8265 return NULL;
8267 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8268 as ImageMagick would ignore the extra bytes anyway. */
8269 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
8270 return hint_buffer;
8273 /* Animated images (e.g., GIF89a) are composed from one "master image"
8274 (which is the first one, and then there's a number of images that
8275 follow. If following images have non-transparent colors, these are
8276 composed "on top" of the master image. So, in general, one has to
8277 compute ann the preceding images to be able to display a particular
8278 sub-image.
8280 Computing all the preceding images is too slow, so we maintain a
8281 cache of previously computed images. We have to maintain a cache
8282 separate from the image cache, because the images may be scaled
8283 before display. */
8285 struct animation_cache
8287 MagickWand *wand;
8288 int index;
8289 struct timespec update_time;
8290 struct animation_cache *next;
8291 char signature[FLEXIBLE_ARRAY_MEMBER];
8294 static struct animation_cache *animation_cache = NULL;
8296 static struct animation_cache *
8297 imagemagick_create_cache (char *signature)
8299 struct animation_cache *cache
8300 = xmalloc (offsetof (struct animation_cache, signature)
8301 + strlen (signature) + 1);
8302 cache->wand = 0;
8303 cache->index = 0;
8304 cache->next = 0;
8305 strcpy (cache->signature, signature);
8306 return cache;
8309 /* Discard cached images that haven't been used for a minute. */
8310 static void
8311 imagemagick_prune_animation_cache (void)
8313 struct animation_cache **pcache = &animation_cache;
8314 struct timespec old = timespec_sub (current_timespec (),
8315 make_timespec (60, 0));
8317 while (*pcache)
8319 struct animation_cache *cache = *pcache;
8320 if (timespec_cmp (old, cache->update_time) <= 0)
8321 pcache = &cache->next;
8322 else
8324 if (cache->wand)
8325 DestroyMagickWand (cache->wand);
8326 *pcache = cache->next;
8327 xfree (cache);
8332 static struct animation_cache *
8333 imagemagick_get_animation_cache (MagickWand *wand)
8335 char *signature = MagickGetImageSignature (wand);
8336 struct animation_cache *cache;
8337 struct animation_cache **pcache = &animation_cache;
8339 imagemagick_prune_animation_cache ();
8341 while (1)
8343 cache = *pcache;
8344 if (! cache)
8346 *pcache = cache = imagemagick_create_cache (signature);
8347 break;
8349 if (strcmp (signature, cache->signature) == 0)
8350 break;
8351 pcache = &cache->next;
8354 DestroyString (signature);
8355 cache->update_time = current_timespec ();
8356 return cache;
8359 static MagickWand *
8360 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8362 int i;
8363 MagickWand *composite_wand;
8364 size_t dest_width, dest_height;
8365 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8367 MagickSetIteratorIndex (super_wand, 0);
8369 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8371 composite_wand = MagickGetImage (super_wand);
8372 if (cache->wand)
8373 DestroyMagickWand (cache->wand);
8375 else
8376 composite_wand = cache->wand;
8378 dest_height = MagickGetImageHeight (composite_wand);
8380 for (i = max (1, cache->index + 1); i <= ino; i++)
8382 MagickWand *sub_wand;
8383 PixelIterator *source_iterator, *dest_iterator;
8384 PixelWand **source, **dest;
8385 size_t source_width, source_height;
8386 ssize_t source_left, source_top;
8387 MagickPixelPacket pixel;
8388 DisposeType dispose;
8389 ptrdiff_t lines = 0;
8391 MagickSetIteratorIndex (super_wand, i);
8392 sub_wand = MagickGetImage (super_wand);
8394 MagickGetImagePage (sub_wand, &source_width, &source_height,
8395 &source_left, &source_top);
8397 /* This flag says how to handle transparent pixels. */
8398 dispose = MagickGetImageDispose (sub_wand);
8400 source_iterator = NewPixelIterator (sub_wand);
8401 if (! source_iterator)
8403 DestroyMagickWand (composite_wand);
8404 DestroyMagickWand (sub_wand);
8405 cache->wand = NULL;
8406 image_error ("Imagemagick pixel iterator creation failed");
8407 return NULL;
8410 dest_iterator = NewPixelIterator (composite_wand);
8411 if (! dest_iterator)
8413 DestroyMagickWand (composite_wand);
8414 DestroyMagickWand (sub_wand);
8415 DestroyPixelIterator (source_iterator);
8416 cache->wand = NULL;
8417 image_error ("Imagemagick pixel iterator creation failed");
8418 return NULL;
8421 /* The sub-image may not start at origin, so move the destination
8422 iterator to where the sub-image should start. */
8423 if (source_top > 0)
8425 PixelSetIteratorRow (dest_iterator, source_top);
8426 lines = source_top;
8429 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8430 != NULL)
8432 ptrdiff_t x;
8434 /* Sanity check. This shouldn't happen, but apparently
8435 does in some pictures. */
8436 if (++lines >= dest_height)
8437 break;
8439 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8440 for (x = 0; x < source_width; x++)
8442 /* Sanity check. This shouldn't happen, but apparently
8443 also does in some pictures. */
8444 if (x + source_left >= dest_width)
8445 break;
8446 /* Normally we only copy over non-transparent pixels,
8447 but if the disposal method is "Background", then we
8448 copy over all pixels. */
8449 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8451 PixelGetMagickColor (source[x], &pixel);
8452 PixelSetMagickColor (dest[x + source_left], &pixel);
8455 PixelSyncIterator (dest_iterator);
8458 DestroyPixelIterator (source_iterator);
8459 DestroyPixelIterator (dest_iterator);
8460 DestroyMagickWand (sub_wand);
8463 /* Cache a copy for the next iteration. The current wand will be
8464 destroyed by the caller. */
8465 cache->wand = CloneMagickWand (composite_wand);
8466 cache->index = ino;
8468 return composite_wand;
8472 /* Helper function for imagemagick_load, which does the actual loading
8473 given contents and size, apart from frame and image structures,
8474 passed from imagemagick_load. Uses librimagemagick to do most of
8475 the image processing.
8477 F is a pointer to the Emacs frame; IMG to the image structure to
8478 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8479 be parsed; SIZE is the number of bytes of data; and FILENAME is
8480 either the file name or the image data.
8482 Return true if successful. */
8484 static bool
8485 imagemagick_load_image (struct frame *f, struct image *img,
8486 unsigned char *contents, unsigned int size,
8487 char *filename)
8489 int width, height;
8490 size_t image_width, image_height;
8491 MagickBooleanType status;
8492 XImagePtr ximg;
8493 int x, y;
8494 MagickWand *image_wand;
8495 PixelIterator *iterator;
8496 PixelWand **pixels, *bg_wand = NULL;
8497 MagickPixelPacket pixel;
8498 Lisp_Object image;
8499 Lisp_Object value;
8500 Lisp_Object crop;
8501 EMACS_INT ino;
8502 int desired_width, desired_height;
8503 double rotation;
8504 int pixelwidth;
8505 char hint_buffer[MaxTextExtent];
8506 char *filename_hint = NULL;
8508 /* Handle image index for image types who can contain more than one image.
8509 Interface :index is same as for GIF. First we "ping" the image to see how
8510 many sub-images it contains. Pinging is faster than loading the image to
8511 find out things about it. */
8513 /* Initialize the imagemagick environment. */
8514 MagickWandGenesis ();
8515 image = image_spec_value (img->spec, QCindex, NULL);
8516 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8517 image_wand = NewMagickWand ();
8519 if (filename)
8520 status = MagickReadImage (image_wand, filename);
8521 else
8523 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8524 MagickSetFilename (image_wand, filename_hint);
8525 status = MagickReadImageBlob (image_wand, contents, size);
8528 if (status == MagickFalse)
8530 imagemagick_error (image_wand);
8531 DestroyMagickWand (image_wand);
8532 return 0;
8535 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8537 image_error ("Invalid image number `%s' in image `%s'", image, img->spec);
8538 DestroyMagickWand (image_wand);
8539 return 0;
8542 if (MagickGetImageDelay (image_wand) > 0)
8543 img->lisp_data =
8544 Fcons (Qdelay,
8545 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8546 img->lisp_data));
8548 if (MagickGetNumberImages (image_wand) > 1)
8549 img->lisp_data =
8550 Fcons (Qcount,
8551 Fcons (make_number (MagickGetNumberImages (image_wand)),
8552 img->lisp_data));
8554 /* If we have an animated image, get the new wand based on the
8555 "super-wand". */
8556 if (MagickGetNumberImages (image_wand) > 1)
8558 MagickWand *super_wand = image_wand;
8559 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8560 if (! image_wand)
8561 image_wand = super_wand;
8562 else
8563 DestroyMagickWand (super_wand);
8566 /* Retrieve the frame's background color, for use later. */
8568 XColor bgcolor;
8569 Lisp_Object specified_bg;
8571 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8572 if (!STRINGP (specified_bg)
8573 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8574 x_query_frame_background_color (f, &bgcolor);
8576 bg_wand = NewPixelWand ();
8577 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8578 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8579 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8582 compute_image_size (MagickGetImageWidth (image_wand),
8583 MagickGetImageHeight (image_wand),
8584 img->spec, &desired_width, &desired_height);
8586 if (desired_width != -1 && desired_height != -1)
8588 status = MagickScaleImage (image_wand, desired_width, desired_height);
8589 if (status == MagickFalse)
8591 image_error ("Imagemagick scale failed");
8592 imagemagick_error (image_wand);
8593 goto imagemagick_error;
8597 /* crop behaves similar to image slicing in Emacs but is more memory
8598 efficient. */
8599 crop = image_spec_value (img->spec, QCcrop, NULL);
8601 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8603 /* After some testing, it seems MagickCropImage is the fastest crop
8604 function in ImageMagick. This crop function seems to do less copying
8605 than the alternatives, but it still reads the entire image into memory
8606 before cropping, which is apparently difficult to avoid when using
8607 imagemagick. */
8608 size_t crop_width = XINT (XCAR (crop));
8609 crop = XCDR (crop);
8610 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8612 size_t crop_height = XINT (XCAR (crop));
8613 crop = XCDR (crop);
8614 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8616 ssize_t crop_x = XINT (XCAR (crop));
8617 crop = XCDR (crop);
8618 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8620 ssize_t crop_y = XINT (XCAR (crop));
8621 MagickCropImage (image_wand, crop_width, crop_height,
8622 crop_x, crop_y);
8628 /* Furthermore :rotation. we need background color and angle for
8629 rotation. */
8631 TODO background handling for rotation specified_bg =
8632 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8633 (specified_bg). */
8634 value = image_spec_value (img->spec, QCrotation, NULL);
8635 if (FLOATP (value))
8637 rotation = extract_float (value);
8638 status = MagickRotateImage (image_wand, bg_wand, rotation);
8639 if (status == MagickFalse)
8641 image_error ("Imagemagick image rotate failed");
8642 imagemagick_error (image_wand);
8643 goto imagemagick_error;
8647 /* Set the canvas background color to the frame or specified
8648 background, and flatten the image. Note: as of ImageMagick
8649 6.6.0, SVG image transparency is not handled properly
8650 (e.g. etc/images/splash.svg shows a white background always). */
8652 MagickWand *new_wand;
8653 MagickSetImageBackgroundColor (image_wand, bg_wand);
8654 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8655 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8656 #else
8657 new_wand = MagickFlattenImages (image_wand);
8658 #endif
8659 DestroyMagickWand (image_wand);
8660 image_wand = new_wand;
8663 /* Finally we are done manipulating the image. Figure out the
8664 resulting width/height and transfer ownership to Emacs. */
8665 image_height = MagickGetImageHeight (image_wand);
8666 image_width = MagickGetImageWidth (image_wand);
8668 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8669 && check_image_size (f, image_width, image_height)))
8671 image_size_error ();
8672 goto imagemagick_error;
8675 width = image_width;
8676 height = image_height;
8678 /* We can now get a valid pixel buffer from the imagemagick file, if all
8679 went ok. */
8681 init_color_table ();
8683 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8684 if (imagemagick_render_type != 0)
8686 /* Magicexportimage is normally faster than pixelpushing. This
8687 method is also well tested. Some aspects of this method are
8688 ad-hoc and needs to be more researched. */
8689 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8690 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8691 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8692 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8693 &ximg, 0))
8695 #ifdef COLOR_TABLE_SUPPORT
8696 free_color_table ();
8697 #endif
8698 image_error ("Imagemagick X bitmap allocation failure");
8699 goto imagemagick_error;
8702 /* Oddly, the below code doesn't seem to work:*/
8703 /* switch(ximg->bitmap_unit){ */
8704 /* case 8: */
8705 /* pixelwidth=CharPixel; */
8706 /* break; */
8707 /* case 16: */
8708 /* pixelwidth=ShortPixel; */
8709 /* break; */
8710 /* case 32: */
8711 /* pixelwidth=LongPixel; */
8712 /* break; */
8713 /* } */
8715 Here im just guessing the format of the bitmap.
8716 happens to work fine for:
8717 - bw djvu images
8718 on rgb display.
8719 seems about 3 times as fast as pixel pushing(not carefully measured)
8721 pixelwidth = CharPixel; /*??? TODO figure out*/
8722 MagickExportImagePixels (image_wand, 0, 0, width, height,
8723 exportdepth, pixelwidth, ximg->data);
8725 else
8726 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8728 size_t image_height;
8729 MagickRealType color_scale = 65535.0 / QuantumRange;
8731 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8732 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8733 &ximg, 0))
8735 #ifdef COLOR_TABLE_SUPPORT
8736 free_color_table ();
8737 #endif
8738 image_error ("Imagemagick X bitmap allocation failure");
8739 goto imagemagick_error;
8742 /* Copy imagemagick image to x with primitive yet robust pixel
8743 pusher loop. This has been tested a lot with many different
8744 images. */
8746 /* Copy pixels from the imagemagick image structure to the x image map. */
8747 iterator = NewPixelIterator (image_wand);
8748 if (! iterator)
8750 #ifdef COLOR_TABLE_SUPPORT
8751 free_color_table ();
8752 #endif
8753 x_destroy_x_image (ximg);
8754 image_error ("Imagemagick pixel iterator creation failed");
8755 goto imagemagick_error;
8758 image_height = MagickGetImageHeight (image_wand);
8759 for (y = 0; y < image_height; y++)
8761 size_t row_width;
8762 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8763 if (! pixels)
8764 break;
8765 int xlim = min (row_width, width);
8766 for (x = 0; x < xlim; x++)
8768 PixelGetMagickColor (pixels[x], &pixel);
8769 XPutPixel (ximg, x, y,
8770 lookup_rgb_color (f,
8771 color_scale * pixel.red,
8772 color_scale * pixel.green,
8773 color_scale * pixel.blue));
8776 DestroyPixelIterator (iterator);
8779 #ifdef COLOR_TABLE_SUPPORT
8780 /* Remember colors allocated for this image. */
8781 img->colors = colors_in_color_table (&img->ncolors);
8782 free_color_table ();
8783 #endif /* COLOR_TABLE_SUPPORT */
8785 img->width = width;
8786 img->height = height;
8788 /* Put ximg into the image. */
8789 image_put_x_image (f, img, ximg, 0);
8791 /* Final cleanup. image_wand should be the only resource left. */
8792 DestroyMagickWand (image_wand);
8793 if (bg_wand) DestroyPixelWand (bg_wand);
8795 /* `MagickWandTerminus' terminates the imagemagick environment. */
8796 MagickWandTerminus ();
8798 return 1;
8800 imagemagick_error:
8801 DestroyMagickWand (image_wand);
8802 if (bg_wand) DestroyPixelWand (bg_wand);
8804 MagickWandTerminus ();
8805 /* TODO more cleanup. */
8806 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec);
8807 return 0;
8811 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8812 successful. this function will go into the imagemagick_type structure, and
8813 the prototype thus needs to be compatible with that structure. */
8815 static bool
8816 imagemagick_load (struct frame *f, struct image *img)
8818 bool success_p = 0;
8819 Lisp_Object file_name;
8821 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8822 file_name = image_spec_value (img->spec, QCfile, NULL);
8823 if (STRINGP (file_name))
8825 Lisp_Object file = x_find_image_file (file_name);
8826 if (!STRINGP (file))
8828 image_error ("Cannot find image file `%s'", file_name);
8829 return 0;
8831 file = ENCODE_FILE (file);
8832 #ifdef WINDOWSNT
8833 file = ansi_encode_filename (file);
8834 #endif
8835 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8837 /* Else its not a file, its a lisp object. Load the image from a
8838 lisp object rather than a file. */
8839 else
8841 Lisp_Object data;
8843 data = image_spec_value (img->spec, QCdata, NULL);
8844 if (!STRINGP (data))
8846 image_error ("Invalid image data `%s'", data);
8847 return 0;
8849 success_p = imagemagick_load_image (f, img, SDATA (data),
8850 SBYTES (data), NULL);
8853 return success_p;
8856 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8857 doc: /* Return a list of image types supported by ImageMagick.
8858 Each entry in this list is a symbol named after an ImageMagick format
8859 tag. See the ImageMagick manual for a list of ImageMagick formats and
8860 their descriptions (http://www.imagemagick.org/script/formats.php).
8861 You can also try the shell command: `identify -list format'.
8863 Note that ImageMagick recognizes many file-types that Emacs does not
8864 recognize as images, such as C. See `imagemagick-types-enable'
8865 and `imagemagick-types-inhibit'. */)
8866 (void)
8868 Lisp_Object typelist = Qnil;
8869 size_t numf = 0;
8870 ExceptionInfo ex;
8871 char **imtypes;
8872 size_t i;
8874 GetExceptionInfo(&ex);
8875 imtypes = GetMagickList ("*", &numf, &ex);
8876 DestroyExceptionInfo(&ex);
8878 for (i = 0; i < numf; i++)
8880 Lisp_Object imagemagicktype = intern (imtypes[i]);
8881 typelist = Fcons (imagemagicktype, typelist);
8882 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8885 MagickRelinquishMemory (imtypes);
8886 return Fnreverse (typelist);
8889 #endif /* defined (HAVE_IMAGEMAGICK) */
8893 /***********************************************************************
8895 ***********************************************************************/
8897 #ifdef HAVE_RSVG
8899 /* Function prototypes. */
8901 static bool svg_image_p (Lisp_Object object);
8902 static bool svg_load (struct frame *f, struct image *img);
8904 static bool svg_load_image (struct frame *, struct image *,
8905 unsigned char *, ptrdiff_t, char *);
8907 /* Indices of image specification fields in svg_format, below. */
8909 enum svg_keyword_index
8911 SVG_TYPE,
8912 SVG_DATA,
8913 SVG_FILE,
8914 SVG_ASCENT,
8915 SVG_MARGIN,
8916 SVG_RELIEF,
8917 SVG_ALGORITHM,
8918 SVG_HEURISTIC_MASK,
8919 SVG_MASK,
8920 SVG_BACKGROUND,
8921 SVG_LAST
8924 /* Vector of image_keyword structures describing the format
8925 of valid user-defined image specifications. */
8927 static const struct image_keyword svg_format[SVG_LAST] =
8929 {":type", IMAGE_SYMBOL_VALUE, 1},
8930 {":data", IMAGE_STRING_VALUE, 0},
8931 {":file", IMAGE_STRING_VALUE, 0},
8932 {":ascent", IMAGE_ASCENT_VALUE, 0},
8933 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8934 {":relief", IMAGE_INTEGER_VALUE, 0},
8935 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8936 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8937 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8938 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8941 # if defined HAVE_NTGUI && defined WINDOWSNT
8942 static bool init_svg_functions (void);
8943 # else
8944 #define init_svg_functions NULL
8945 # endif
8947 /* Structure describing the image type `svg'. Its the same type of
8948 structure defined for all image formats, handled by emacs image
8949 functions. See struct image_type in dispextern.h. */
8951 static struct image_type svg_type =
8953 SYMBOL_INDEX (Qsvg),
8954 svg_image_p,
8955 svg_load,
8956 x_clear_image,
8957 init_svg_functions,
8958 NULL
8962 /* Return true if OBJECT is a valid SVG image specification. Do
8963 this by calling parse_image_spec and supplying the keywords that
8964 identify the SVG format. */
8966 static bool
8967 svg_image_p (Lisp_Object object)
8969 struct image_keyword fmt[SVG_LAST];
8970 memcpy (fmt, svg_format, sizeof fmt);
8972 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8973 return 0;
8975 /* Must specify either the :data or :file keyword. */
8976 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8979 # include <librsvg/rsvg.h>
8981 # ifdef WINDOWSNT
8983 /* SVG library functions. */
8984 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
8985 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
8986 (RsvgHandle *, RsvgDimensionData *));
8987 DEF_DLL_FN (gboolean, rsvg_handle_write,
8988 (RsvgHandle *, const guchar *, gsize, GError **));
8989 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8990 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8991 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
8993 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8994 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8995 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8996 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8997 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8998 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8999 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
9000 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
9002 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9003 DEF_DLL_FN (void, g_type_init, (void));
9004 # endif
9005 DEF_DLL_FN (void, g_object_unref, (gpointer));
9006 DEF_DLL_FN (void, g_error_free, (GError *));
9008 static bool
9009 init_svg_functions (void)
9011 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
9013 if (!(glib = w32_delayed_load (Qglib))
9014 || !(gobject = w32_delayed_load (Qgobject))
9015 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
9016 || !(library = w32_delayed_load (Qsvg)))
9018 if (gdklib) FreeLibrary (gdklib);
9019 if (gobject) FreeLibrary (gobject);
9020 if (glib) FreeLibrary (glib);
9021 return 0;
9024 LOAD_DLL_FN (library, rsvg_handle_new);
9025 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
9026 LOAD_DLL_FN (library, rsvg_handle_write);
9027 LOAD_DLL_FN (library, rsvg_handle_close);
9028 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
9029 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
9031 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
9032 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
9033 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
9034 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
9035 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
9036 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
9037 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
9038 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
9040 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9041 LOAD_DLL_FN (gobject, g_type_init);
9042 # endif
9043 LOAD_DLL_FN (gobject, g_object_unref);
9044 LOAD_DLL_FN (glib, g_error_free);
9046 return 1;
9049 /* The following aliases for library functions allow dynamic loading
9050 to be used on some platforms. */
9052 # undef gdk_pixbuf_get_bits_per_sample
9053 # undef gdk_pixbuf_get_colorspace
9054 # undef gdk_pixbuf_get_has_alpha
9055 # undef gdk_pixbuf_get_height
9056 # undef gdk_pixbuf_get_n_channels
9057 # undef gdk_pixbuf_get_pixels
9058 # undef gdk_pixbuf_get_rowstride
9059 # undef gdk_pixbuf_get_width
9060 # undef g_error_free
9061 # undef g_object_unref
9062 # undef g_type_init
9063 # undef rsvg_handle_close
9064 # undef rsvg_handle_get_dimensions
9065 # undef rsvg_handle_get_pixbuf
9066 # undef rsvg_handle_new
9067 # undef rsvg_handle_set_base_uri
9068 # undef rsvg_handle_write
9070 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9071 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9072 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9073 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9074 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9075 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9076 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9077 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9078 # define g_error_free fn_g_error_free
9079 # define g_object_unref fn_g_object_unref
9080 # define g_type_init fn_g_type_init
9081 # define rsvg_handle_close fn_rsvg_handle_close
9082 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9083 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9084 # define rsvg_handle_new fn_rsvg_handle_new
9085 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9086 # define rsvg_handle_write fn_rsvg_handle_write
9088 # endif /* !WINDOWSNT */
9090 /* Load SVG image IMG for use on frame F. Value is true if
9091 successful. */
9093 static bool
9094 svg_load (struct frame *f, struct image *img)
9096 bool success_p = 0;
9097 Lisp_Object file_name;
9099 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9100 file_name = image_spec_value (img->spec, QCfile, NULL);
9101 if (STRINGP (file_name))
9103 int fd;
9104 Lisp_Object file = x_find_image_fd (file_name, &fd);
9105 if (!STRINGP (file))
9107 image_error ("Cannot find image file `%s'", file_name);
9108 return 0;
9111 /* Read the entire file into memory. */
9112 ptrdiff_t size;
9113 unsigned char *contents = slurp_file (fd, &size);
9114 if (contents == NULL)
9116 image_error ("Error loading SVG image `%s'", file);
9117 return 0;
9119 /* If the file was slurped into memory properly, parse it. */
9120 success_p = svg_load_image (f, img, contents, size,
9121 SSDATA (ENCODE_FILE (file)));
9122 xfree (contents);
9124 /* Else its not a file, its a lisp object. Load the image from a
9125 lisp object rather than a file. */
9126 else
9128 Lisp_Object data, original_filename;
9130 data = image_spec_value (img->spec, QCdata, NULL);
9131 if (!STRINGP (data))
9133 image_error ("Invalid image data `%s'", data);
9134 return 0;
9136 original_filename = BVAR (current_buffer, filename);
9137 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data),
9138 (NILP (original_filename) ? NULL
9139 : SSDATA (original_filename)));
9142 return success_p;
9145 /* svg_load_image is a helper function for svg_load, which does the
9146 actual loading given contents and size, apart from frame and image
9147 structures, passed from svg_load.
9149 Uses librsvg to do most of the image processing.
9151 Returns true when successful. */
9152 static bool
9153 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
9154 struct image *img, /* Pointer to emacs image structure. */
9155 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
9156 ptrdiff_t size, /* Size of data in bytes. */
9157 char *filename) /* Name of SVG file being loaded. */
9159 RsvgHandle *rsvg_handle;
9160 RsvgDimensionData dimension_data;
9161 GError *err = NULL;
9162 GdkPixbuf *pixbuf;
9163 int width;
9164 int height;
9165 const guint8 *pixels;
9166 int rowstride;
9167 XImagePtr ximg;
9168 Lisp_Object specified_bg;
9169 XColor background;
9170 int x;
9171 int y;
9173 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9174 /* g_type_init is a glib function that must be called prior to
9175 using gnome type library functions (obsolete since 2.36.0). */
9176 g_type_init ();
9177 #endif
9179 /* Make a handle to a new rsvg object. */
9180 rsvg_handle = rsvg_handle_new ();
9182 /* Set base_uri for properly handling referenced images (via 'href').
9183 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9184 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9185 if (filename)
9186 rsvg_handle_set_base_uri(rsvg_handle, filename);
9188 /* Parse the contents argument and fill in the rsvg_handle. */
9189 rsvg_handle_write (rsvg_handle, contents, size, &err);
9190 if (err) goto rsvg_error;
9192 /* The parsing is complete, rsvg_handle is ready to used, close it
9193 for further writes. */
9194 rsvg_handle_close (rsvg_handle, &err);
9195 if (err) goto rsvg_error;
9197 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
9198 if (! check_image_size (f, dimension_data.width, dimension_data.height))
9200 image_size_error ();
9201 goto rsvg_error;
9204 /* We can now get a valid pixel buffer from the svg file, if all
9205 went ok. */
9206 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
9207 if (!pixbuf) goto rsvg_error;
9208 g_object_unref (rsvg_handle);
9210 /* Extract some meta data from the svg handle. */
9211 width = gdk_pixbuf_get_width (pixbuf);
9212 height = gdk_pixbuf_get_height (pixbuf);
9213 pixels = gdk_pixbuf_get_pixels (pixbuf);
9214 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
9216 /* Validate the svg meta data. */
9217 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
9218 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
9219 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
9220 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
9222 #ifdef USE_CAIRO
9224 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
9225 int y;
9226 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
9228 for (y = 0; y < height; ++y)
9230 const guchar *iconptr = pixels + y * rowstride;
9231 uint32_t *dataptr = (uint32_t *) (data + y * rowstride);
9232 int x;
9234 for (x = 0; x < width; ++x)
9236 if (iconptr[3] == 0)
9237 *dataptr = bgcolor;
9238 else
9239 *dataptr = (iconptr[0] << 16)
9240 | (iconptr[1] << 8)
9241 | iconptr[2]
9242 | (iconptr[3] << 24);
9244 iconptr += 4;
9245 ++dataptr;
9249 create_cairo_image_surface (img, data, width, height);
9250 g_object_unref (pixbuf);
9252 #else
9253 /* Try to create a x pixmap to hold the svg pixmap. */
9254 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
9256 g_object_unref (pixbuf);
9257 return 0;
9260 init_color_table ();
9262 /* Handle alpha channel by combining the image with a background
9263 color. */
9264 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
9265 if (!STRINGP (specified_bg)
9266 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
9267 x_query_frame_background_color (f, &background);
9269 /* SVG pixmaps specify transparency in the last byte, so right
9270 shift 8 bits to get rid of it, since emacs doesn't support
9271 transparency. */
9272 background.red >>= 8;
9273 background.green >>= 8;
9274 background.blue >>= 8;
9276 /* This loop handles opacity values, since Emacs assumes
9277 non-transparent images. Each pixel must be "flattened" by
9278 calculating the resulting color, given the transparency of the
9279 pixel, and the image background color. */
9280 for (y = 0; y < height; ++y)
9282 for (x = 0; x < width; ++x)
9284 int red;
9285 int green;
9286 int blue;
9287 int opacity;
9289 red = *pixels++;
9290 green = *pixels++;
9291 blue = *pixels++;
9292 opacity = *pixels++;
9294 red = ((red * opacity)
9295 + (background.red * ((1 << 8) - opacity)));
9296 green = ((green * opacity)
9297 + (background.green * ((1 << 8) - opacity)));
9298 blue = ((blue * opacity)
9299 + (background.blue * ((1 << 8) - opacity)));
9301 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9304 pixels += rowstride - 4 * width;
9307 #ifdef COLOR_TABLE_SUPPORT
9308 /* Remember colors allocated for this image. */
9309 img->colors = colors_in_color_table (&img->ncolors);
9310 free_color_table ();
9311 #endif /* COLOR_TABLE_SUPPORT */
9313 g_object_unref (pixbuf);
9315 img->width = width;
9316 img->height = height;
9318 /* Maybe fill in the background field while we have ximg handy.
9319 Casting avoids a GCC warning. */
9320 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9322 /* Put ximg into the image. */
9323 image_put_x_image (f, img, ximg, 0);
9324 #endif /* ! USE_CAIRO */
9326 return 1;
9328 rsvg_error:
9329 g_object_unref (rsvg_handle);
9330 /* FIXME: Use error->message so the user knows what is the actual
9331 problem with the image. */
9332 image_error ("Error parsing SVG image `%s'", img->spec);
9333 g_error_free (err);
9334 return 0;
9337 #endif /* defined (HAVE_RSVG) */
9342 /***********************************************************************
9343 Ghostscript
9344 ***********************************************************************/
9346 #ifdef HAVE_X_WINDOWS
9347 #define HAVE_GHOSTSCRIPT 1
9348 #endif /* HAVE_X_WINDOWS */
9350 #ifdef HAVE_GHOSTSCRIPT
9352 static bool gs_image_p (Lisp_Object object);
9353 static bool gs_load (struct frame *f, struct image *img);
9354 static void gs_clear_image (struct frame *f, struct image *img);
9356 /* Indices of image specification fields in gs_format, below. */
9358 enum gs_keyword_index
9360 GS_TYPE,
9361 GS_PT_WIDTH,
9362 GS_PT_HEIGHT,
9363 GS_FILE,
9364 GS_LOADER,
9365 GS_BOUNDING_BOX,
9366 GS_ASCENT,
9367 GS_MARGIN,
9368 GS_RELIEF,
9369 GS_ALGORITHM,
9370 GS_HEURISTIC_MASK,
9371 GS_MASK,
9372 GS_BACKGROUND,
9373 GS_LAST
9376 /* Vector of image_keyword structures describing the format
9377 of valid user-defined image specifications. */
9379 static const struct image_keyword gs_format[GS_LAST] =
9381 {":type", IMAGE_SYMBOL_VALUE, 1},
9382 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9383 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9384 {":file", IMAGE_STRING_VALUE, 1},
9385 {":loader", IMAGE_FUNCTION_VALUE, 0},
9386 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9387 {":ascent", IMAGE_ASCENT_VALUE, 0},
9388 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9389 {":relief", IMAGE_INTEGER_VALUE, 0},
9390 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9391 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9392 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9393 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9396 /* Structure describing the image type `ghostscript'. */
9398 static struct image_type gs_type =
9400 SYMBOL_INDEX (Qpostscript),
9401 gs_image_p,
9402 gs_load,
9403 gs_clear_image,
9404 NULL,
9405 NULL
9409 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9411 static void
9412 gs_clear_image (struct frame *f, struct image *img)
9414 x_clear_image (f, img);
9418 /* Return true if OBJECT is a valid Ghostscript image
9419 specification. */
9421 static bool
9422 gs_image_p (Lisp_Object object)
9424 struct image_keyword fmt[GS_LAST];
9425 Lisp_Object tem;
9426 int i;
9428 memcpy (fmt, gs_format, sizeof fmt);
9430 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9431 return 0;
9433 /* Bounding box must be a list or vector containing 4 integers. */
9434 tem = fmt[GS_BOUNDING_BOX].value;
9435 if (CONSP (tem))
9437 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9438 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9439 return 0;
9440 if (!NILP (tem))
9441 return 0;
9443 else if (VECTORP (tem))
9445 if (ASIZE (tem) != 4)
9446 return 0;
9447 for (i = 0; i < 4; ++i)
9448 if (!INTEGERP (AREF (tem, i)))
9449 return 0;
9451 else
9452 return 0;
9454 return 1;
9458 /* Load Ghostscript image IMG for use on frame F. Value is true
9459 if successful. */
9461 static bool
9462 gs_load (struct frame *f, struct image *img)
9464 uprintmax_t printnum1, printnum2;
9465 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9466 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9467 Lisp_Object frame;
9468 double in_width, in_height;
9469 Lisp_Object pixel_colors = Qnil;
9471 /* Compute pixel size of pixmap needed from the given size in the
9472 image specification. Sizes in the specification are in pt. 1 pt
9473 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9474 info. */
9475 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9476 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9477 in_width *= FRAME_RES_X (f);
9478 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9479 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9480 in_height *= FRAME_RES_Y (f);
9482 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9483 && check_image_size (f, in_width, in_height)))
9485 image_size_error ();
9486 return 0;
9488 img->width = in_width;
9489 img->height = in_height;
9491 /* Create the pixmap. */
9492 eassert (img->pixmap == NO_PIXMAP);
9494 if (x_check_image_size (0, img->width, img->height))
9496 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9497 block_input ();
9498 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9499 img->width, img->height,
9500 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9501 unblock_input ();
9504 if (!img->pixmap)
9506 image_error ("Unable to create pixmap for `%s'" , img->spec);
9507 return 0;
9510 /* Call the loader to fill the pixmap. It returns a process object
9511 if successful. We do not record_unwind_protect here because
9512 other places in redisplay like calling window scroll functions
9513 don't either. Let the Lisp loader use `unwind-protect' instead. */
9514 printnum1 = FRAME_X_WINDOW (f);
9515 printnum2 = img->pixmap;
9516 window_and_pixmap_id
9517 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9519 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9520 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9521 pixel_colors
9522 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9524 XSETFRAME (frame, f);
9525 loader = image_spec_value (img->spec, QCloader, NULL);
9526 if (NILP (loader))
9527 loader = intern ("gs-load-image");
9529 img->lisp_data = call6 (loader, frame, img->spec,
9530 make_number (img->width),
9531 make_number (img->height),
9532 window_and_pixmap_id,
9533 pixel_colors);
9534 return PROCESSP (img->lisp_data);
9538 /* Kill the Ghostscript process that was started to fill PIXMAP on
9539 frame F. Called from XTread_socket when receiving an event
9540 telling Emacs that Ghostscript has finished drawing. */
9542 void
9543 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9545 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9546 int class;
9547 ptrdiff_t i;
9548 struct image *img;
9550 /* Find the image containing PIXMAP. */
9551 for (i = 0; i < c->used; ++i)
9552 if (c->images[i]->pixmap == pixmap)
9553 break;
9555 /* Should someone in between have cleared the image cache, for
9556 instance, give up. */
9557 if (i == c->used)
9558 return;
9560 /* Kill the GS process. We should have found PIXMAP in the image
9561 cache and its image should contain a process object. */
9562 img = c->images[i];
9563 eassert (PROCESSP (img->lisp_data));
9564 Fkill_process (img->lisp_data, Qnil);
9565 img->lisp_data = Qnil;
9567 #if defined (HAVE_X_WINDOWS)
9569 /* On displays with a mutable colormap, figure out the colors
9570 allocated for the image by looking at the pixels of an XImage for
9571 img->pixmap. */
9572 class = FRAME_X_VISUAL (f)->class;
9573 if (class != StaticColor && class != StaticGray && class != TrueColor)
9575 XImagePtr ximg;
9577 block_input ();
9579 /* Try to get an XImage for img->pixmep. */
9580 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9581 0, 0, img->width, img->height, ~0, ZPixmap);
9582 if (ximg)
9584 int x, y;
9586 /* Initialize the color table. */
9587 init_color_table ();
9589 /* For each pixel of the image, look its color up in the
9590 color table. After having done so, the color table will
9591 contain an entry for each color used by the image. */
9592 #ifdef COLOR_TABLE_SUPPORT
9593 for (y = 0; y < img->height; ++y)
9594 for (x = 0; x < img->width; ++x)
9596 unsigned long pixel = XGetPixel (ximg, x, y);
9598 lookup_pixel_color (f, pixel);
9601 /* Record colors in the image. Free color table and XImage. */
9602 img->colors = colors_in_color_table (&img->ncolors);
9603 free_color_table ();
9604 #endif
9605 XDestroyImage (ximg);
9607 #if 0 /* This doesn't seem to be the case. If we free the colors
9608 here, we get a BadAccess later in x_clear_image when
9609 freeing the colors. */
9610 /* We have allocated colors once, but Ghostscript has also
9611 allocated colors on behalf of us. So, to get the
9612 reference counts right, free them once. */
9613 if (img->ncolors)
9614 x_free_colors (f, img->colors, img->ncolors);
9615 #endif
9617 else
9618 image_error ("Cannot get X image of `%s'; colors will not be freed",
9619 img->spec);
9621 unblock_input ();
9623 #endif /* HAVE_X_WINDOWS */
9625 /* Now that we have the pixmap, compute mask and transform the
9626 image if requested. */
9627 block_input ();
9628 postprocess_image (f, img);
9629 unblock_input ();
9632 #endif /* HAVE_GHOSTSCRIPT */
9635 /***********************************************************************
9636 Tests
9637 ***********************************************************************/
9639 #ifdef GLYPH_DEBUG
9641 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9642 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9643 (Lisp_Object spec)
9645 return valid_image_p (spec) ? Qt : Qnil;
9649 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0,
9650 doc: /* */)
9651 (Lisp_Object spec)
9653 ptrdiff_t id = -1;
9655 if (valid_image_p (spec))
9656 id = lookup_image (SELECTED_FRAME (), spec);
9658 debug_print (spec);
9659 return make_number (id);
9662 #endif /* GLYPH_DEBUG */
9665 /***********************************************************************
9666 Initialization
9667 ***********************************************************************/
9669 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9670 doc: /* Initialize image library implementing image type TYPE.
9671 Return non-nil if TYPE is a supported image type.
9673 If image libraries are loaded dynamically (currently only the case on
9674 MS-Windows), load the library for TYPE if it is not yet loaded, using
9675 the library file(s) specified by `dynamic-library-alist'. */)
9676 (Lisp_Object type)
9678 return lookup_image_type (type) ? Qt : Qnil;
9681 /* Look up image type TYPE, and return a pointer to its image_type
9682 structure. Return 0 if TYPE is not a known image type. */
9684 static struct image_type *
9685 lookup_image_type (Lisp_Object type)
9687 /* Types pbm and xbm are built-in and always available. */
9688 if (EQ (type, Qpbm))
9689 return define_image_type (&pbm_type);
9691 if (EQ (type, Qxbm))
9692 return define_image_type (&xbm_type);
9694 #if defined (HAVE_XPM) || defined (HAVE_NS)
9695 if (EQ (type, Qxpm))
9696 return define_image_type (&xpm_type);
9697 #endif
9699 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9700 if (EQ (type, Qjpeg))
9701 return define_image_type (&jpeg_type);
9702 #endif
9704 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9705 if (EQ (type, Qtiff))
9706 return define_image_type (&tiff_type);
9707 #endif
9709 #if defined (HAVE_GIF) || defined (HAVE_NS)
9710 if (EQ (type, Qgif))
9711 return define_image_type (&gif_type);
9712 #endif
9714 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9715 if (EQ (type, Qpng))
9716 return define_image_type (&png_type);
9717 #endif
9719 #if defined (HAVE_RSVG)
9720 if (EQ (type, Qsvg))
9721 return define_image_type (&svg_type);
9722 #endif
9724 #if defined (HAVE_IMAGEMAGICK)
9725 if (EQ (type, Qimagemagick))
9726 return define_image_type (&imagemagick_type);
9727 #endif
9729 #ifdef HAVE_GHOSTSCRIPT
9730 if (EQ (type, Qpostscript))
9731 return define_image_type (&gs_type);
9732 #endif
9734 return NULL;
9737 /* Reset image_types before dumping.
9738 Called from Fdump_emacs. */
9740 void
9741 reset_image_types (void)
9743 while (image_types)
9745 struct image_type *next = image_types->next;
9746 xfree (image_types);
9747 image_types = next;
9751 void
9752 syms_of_image (void)
9754 /* Initialize this only once; it will be reset before dumping. */
9755 image_types = NULL;
9757 /* Must be defined now because we're going to update it below, while
9758 defining the supported image types. */
9759 DEFVAR_LISP ("image-types", Vimage_types,
9760 doc: /* List of potentially supported image types.
9761 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9762 To check whether it is really supported, use `image-type-available-p'. */);
9763 Vimage_types = Qnil;
9765 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9766 doc: /* Maximum size of images.
9767 Emacs will not load an image into memory if its pixel width or
9768 pixel height exceeds this limit.
9770 If the value is an integer, it directly specifies the maximum
9771 image height and width, measured in pixels. If it is a floating
9772 point number, it specifies the maximum image height and width
9773 as a ratio to the frame height and width. If the value is
9774 non-numeric, there is no explicit limit on the size of images. */);
9775 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9777 /* Other symbols. */
9778 DEFSYM (Qcount, "count");
9779 DEFSYM (Qextension_data, "extension-data");
9780 DEFSYM (Qdelay, "delay");
9782 /* Keywords. */
9783 DEFSYM (QCascent, ":ascent");
9784 DEFSYM (QCmargin, ":margin");
9785 DEFSYM (QCrelief, ":relief");
9786 DEFSYM (QCconversion, ":conversion");
9787 DEFSYM (QCcolor_symbols, ":color-symbols");
9788 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9789 DEFSYM (QCindex, ":index");
9790 DEFSYM (QCcrop, ":crop");
9791 DEFSYM (QCrotation, ":rotation");
9792 DEFSYM (QCmatrix, ":matrix");
9793 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9794 DEFSYM (QCmask, ":mask");
9796 /* Other symbols. */
9797 DEFSYM (Qlaplace, "laplace");
9798 DEFSYM (Qemboss, "emboss");
9799 DEFSYM (Qedge_detection, "edge-detection");
9800 DEFSYM (Qheuristic, "heuristic");
9802 DEFSYM (Qpostscript, "postscript");
9803 DEFSYM (QCmax_width, ":max-width");
9804 DEFSYM (QCmax_height, ":max-height");
9805 #ifdef HAVE_GHOSTSCRIPT
9806 ADD_IMAGE_TYPE (Qpostscript);
9807 DEFSYM (QCloader, ":loader");
9808 DEFSYM (QCpt_width, ":pt-width");
9809 DEFSYM (QCpt_height, ":pt-height");
9810 #endif /* HAVE_GHOSTSCRIPT */
9812 #ifdef HAVE_NTGUI
9813 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9814 or -1 if no PNG/GIF support was compiled in. This is tested by
9815 w32-win.el to correctly set up the alist used to search for the
9816 respective image libraries. */
9817 DEFSYM (Qlibpng_version, "libpng-version");
9818 Fset (Qlibpng_version,
9819 #if HAVE_PNG
9820 make_number (PNG_LIBPNG_VER)
9821 #else
9822 make_number (-1)
9823 #endif
9825 DEFSYM (Qlibgif_version, "libgif-version");
9826 Fset (Qlibgif_version,
9827 #ifdef HAVE_GIF
9828 make_number (GIFLIB_MAJOR * 10000
9829 + GIFLIB_MINOR * 100
9830 + GIFLIB_RELEASE)
9831 #else
9832 make_number (-1)
9833 #endif
9835 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9836 Fset (Qlibjpeg_version,
9837 #if HAVE_JPEG
9838 make_number (JPEG_LIB_VERSION)
9839 #else
9840 make_number (-1)
9841 #endif
9843 #endif
9845 DEFSYM (Qpbm, "pbm");
9846 ADD_IMAGE_TYPE (Qpbm);
9848 DEFSYM (Qxbm, "xbm");
9849 ADD_IMAGE_TYPE (Qxbm);
9851 #if defined (HAVE_XPM) || defined (HAVE_NS)
9852 DEFSYM (Qxpm, "xpm");
9853 ADD_IMAGE_TYPE (Qxpm);
9854 #endif
9856 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9857 DEFSYM (Qjpeg, "jpeg");
9858 ADD_IMAGE_TYPE (Qjpeg);
9859 #endif
9861 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9862 DEFSYM (Qtiff, "tiff");
9863 ADD_IMAGE_TYPE (Qtiff);
9864 #endif
9866 #if defined (HAVE_GIF) || defined (HAVE_NS)
9867 DEFSYM (Qgif, "gif");
9868 ADD_IMAGE_TYPE (Qgif);
9869 #endif
9871 #if defined (HAVE_PNG) || defined (HAVE_NS)
9872 DEFSYM (Qpng, "png");
9873 ADD_IMAGE_TYPE (Qpng);
9874 #endif
9876 #if defined (HAVE_IMAGEMAGICK)
9877 DEFSYM (Qimagemagick, "imagemagick");
9878 ADD_IMAGE_TYPE (Qimagemagick);
9879 #endif
9881 #if defined (HAVE_RSVG)
9882 DEFSYM (Qsvg, "svg");
9883 ADD_IMAGE_TYPE (Qsvg);
9884 #ifdef HAVE_NTGUI
9885 /* Other libraries used directly by svg code. */
9886 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9887 DEFSYM (Qglib, "glib");
9888 DEFSYM (Qgobject, "gobject");
9889 #endif /* HAVE_NTGUI */
9890 #endif /* HAVE_RSVG */
9892 defsubr (&Sinit_image_library);
9893 #ifdef HAVE_IMAGEMAGICK
9894 defsubr (&Simagemagick_types);
9895 #endif
9896 defsubr (&Sclear_image_cache);
9897 defsubr (&Simage_flush);
9898 defsubr (&Simage_size);
9899 defsubr (&Simage_mask_p);
9900 defsubr (&Simage_metadata);
9902 #ifdef GLYPH_DEBUG
9903 defsubr (&Simagep);
9904 defsubr (&Slookup_image);
9905 #endif
9907 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9908 doc: /* Non-nil means always draw a cross over disabled images.
9909 Disabled images are those having a `:conversion disabled' property.
9910 A cross is always drawn on black & white displays. */);
9911 cross_disabled_images = 0;
9913 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9914 doc: /* List of directories to search for window system bitmap files. */);
9915 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9917 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9918 doc: /* Maximum time after which images are removed from the cache.
9919 When an image has not been displayed this many seconds, Emacs
9920 automatically removes it from the image cache. If the cache contains
9921 a large number of images, the actual eviction time may be shorter.
9922 The value can also be nil, meaning the cache is never cleared.
9924 The function `clear-image-cache' disregards this variable. */);
9925 Vimage_cache_eviction_delay = make_number (300);
9926 #ifdef HAVE_IMAGEMAGICK
9927 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9928 doc: /* Integer indicating which ImageMagick rendering method to use.
9929 The options are:
9930 0 -- the default method (pixel pushing)
9931 1 -- a newer method ("MagickExportImagePixels") that may perform
9932 better (speed etc) in some cases, but has not been as thoroughly
9933 tested with Emacs as the default method. This method requires
9934 ImageMagick version 6.4.6 (approximately) or later.
9935 */);
9936 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9937 imagemagick_render_type = 0;
9938 #endif