* etc/NEWS: Remove comment lost in emacs-25 merge.
[emacs.git] / src / image.c
blobf15c2788967bfd192e2d96722098f8f5255abd63
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <unistd.h>
26 /* Include this before including <setjmp.h> to work around bugs with
27 older libpng; see Bug#17429. */
28 #if defined HAVE_PNG && !defined HAVE_NS
29 # include <png.h>
30 #endif
32 #include <setjmp.h>
34 #include <c-ctype.h>
35 #include <flexmember.h>
37 #include "lisp.h"
38 #include "frame.h"
39 #include "window.h"
40 #include "buffer.h"
41 #include "dispextern.h"
42 #include "blockinput.h"
43 #include "systime.h"
44 #include <epaths.h>
45 #include "coding.h"
46 #include "termhooks.h"
47 #include "font.h"
49 #ifdef HAVE_SYS_STAT_H
50 #include <sys/stat.h>
51 #endif /* HAVE_SYS_STAT_H */
53 #ifdef HAVE_SYS_TYPES_H
54 #include <sys/types.h>
55 #endif /* HAVE_SYS_TYPES_H */
57 #ifdef HAVE_WINDOW_SYSTEM
58 #include TERM_HEADER
59 #endif /* HAVE_WINDOW_SYSTEM */
61 /* Work around GCC bug 54561. */
62 #if GNUC_PREREQ (4, 3, 0)
63 # pragma GCC diagnostic ignored "-Wclobbered"
64 #endif
66 #ifdef HAVE_X_WINDOWS
67 typedef struct x_bitmap_record Bitmap_Record;
68 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
69 #define NO_PIXMAP None
71 #define PIX_MASK_RETAIN 0
72 #define PIX_MASK_DRAW 1
73 #endif /* HAVE_X_WINDOWS */
75 #ifdef HAVE_NTGUI
77 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
78 #ifdef WINDOWSNT
79 # include "w32.h"
80 #endif
82 typedef struct w32_bitmap_record Bitmap_Record;
83 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
84 #define NO_PIXMAP 0
86 #define PIX_MASK_RETAIN 0
87 #define PIX_MASK_DRAW 1
89 #define x_defined_color w32_defined_color
91 #endif /* HAVE_NTGUI */
93 #ifdef HAVE_NS
94 typedef struct ns_bitmap_record Bitmap_Record;
96 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
97 #define NO_PIXMAP 0
99 #define PIX_MASK_RETAIN 0
100 #define PIX_MASK_DRAW 1
102 #define x_defined_color(f, name, color_def, alloc) \
103 ns_defined_color (f, name, color_def, alloc, 0)
104 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
105 #endif /* HAVE_NS */
107 #if (defined HAVE_X_WINDOWS \
108 && ! (defined HAVE_NTGUI || defined USE_CAIRO || defined HAVE_NS))
109 /* W32_TODO : Color tables on W32. */
110 # define COLOR_TABLE_SUPPORT 1
111 #endif
113 static void x_disable_image (struct frame *, struct image *);
114 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
115 Lisp_Object);
117 static void init_color_table (void);
118 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
119 #ifdef COLOR_TABLE_SUPPORT
120 static void free_color_table (void);
121 static unsigned long *colors_in_color_table (int *n);
122 #endif
124 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
125 id, which is just an int that this section returns. Bitmaps are
126 reference counted so they can be shared among frames.
128 Bitmap indices are guaranteed to be > 0, so a negative number can
129 be used to indicate no bitmap.
131 If you use x_create_bitmap_from_data, then you must keep track of
132 the bitmaps yourself. That is, creating a bitmap from the same
133 data more than once will not be caught. */
135 #ifdef HAVE_NS
136 /* Use with images created by ns_image_for_XPM. */
137 static unsigned long
138 XGetPixel (XImagePtr ximage, int x, int y)
140 return ns_get_pixel (ximage, x, y);
143 /* Use with images created by ns_image_for_XPM; alpha set to 1;
144 pixel is assumed to be in RGB form. */
145 static void
146 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
148 ns_put_pixel (ximage, x, y, pixel);
150 #endif /* HAVE_NS */
153 /* Functions to access the contents of a bitmap, given an id. */
155 #ifdef HAVE_X_WINDOWS
156 static int
157 x_bitmap_height (struct frame *f, ptrdiff_t id)
159 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
162 static int
163 x_bitmap_width (struct frame *f, ptrdiff_t id)
165 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
167 #endif
169 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
170 ptrdiff_t
171 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
173 /* HAVE_NTGUI needs the explicit cast here. */
174 return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
176 #endif
178 #ifdef HAVE_X_WINDOWS
180 x_bitmap_mask (struct frame *f, ptrdiff_t id)
182 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
184 #endif
186 /* Allocate a new bitmap record. Returns index of new record. */
188 static ptrdiff_t
189 x_allocate_bitmap_record (struct frame *f)
191 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
192 ptrdiff_t i;
194 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
195 return ++dpyinfo->bitmaps_last;
197 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
198 if (dpyinfo->bitmaps[i].refcount == 0)
199 return i + 1;
201 dpyinfo->bitmaps =
202 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
203 10, -1, sizeof *dpyinfo->bitmaps);
204 return ++dpyinfo->bitmaps_last;
207 /* Add one reference to the reference count of the bitmap with id ID. */
209 void
210 x_reference_bitmap (struct frame *f, ptrdiff_t id)
212 ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
215 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
217 ptrdiff_t
218 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
220 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
221 ptrdiff_t id;
223 #ifdef HAVE_X_WINDOWS
224 Pixmap bitmap;
225 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
226 bits, width, height);
227 if (! bitmap)
228 return -1;
229 #endif /* HAVE_X_WINDOWS */
231 #ifdef HAVE_NTGUI
232 Lisp_Object frame UNINIT; /* The value is not used. */
233 Pixmap bitmap;
234 bitmap = CreateBitmap (width, height,
235 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
236 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
237 bits);
238 if (! bitmap)
239 return -1;
240 #endif /* HAVE_NTGUI */
242 #ifdef HAVE_NS
243 void *bitmap = ns_image_from_XBM (bits, width, height, 0, 0);
244 if (!bitmap)
245 return -1;
246 #endif
248 id = x_allocate_bitmap_record (f);
250 #ifdef HAVE_NS
251 dpyinfo->bitmaps[id - 1].img = bitmap;
252 dpyinfo->bitmaps[id - 1].depth = 1;
253 #endif
255 dpyinfo->bitmaps[id - 1].file = NULL;
256 dpyinfo->bitmaps[id - 1].height = height;
257 dpyinfo->bitmaps[id - 1].width = width;
258 dpyinfo->bitmaps[id - 1].refcount = 1;
260 #ifdef HAVE_X_WINDOWS
261 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
262 dpyinfo->bitmaps[id - 1].have_mask = false;
263 dpyinfo->bitmaps[id - 1].depth = 1;
264 #endif /* HAVE_X_WINDOWS */
266 #ifdef HAVE_NTGUI
267 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
268 dpyinfo->bitmaps[id - 1].hinst = NULL;
269 dpyinfo->bitmaps[id - 1].depth = 1;
270 #endif /* HAVE_NTGUI */
272 return id;
275 /* Create bitmap from file FILE for frame F. */
277 ptrdiff_t
278 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
280 #ifdef HAVE_NTGUI
281 return -1; /* W32_TODO : bitmap support */
282 #else
283 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
284 #endif
286 #ifdef HAVE_NS
287 ptrdiff_t id;
288 void *bitmap = ns_image_from_file (file);
290 if (!bitmap)
291 return -1;
294 id = x_allocate_bitmap_record (f);
295 dpyinfo->bitmaps[id - 1].img = bitmap;
296 dpyinfo->bitmaps[id - 1].refcount = 1;
297 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
298 dpyinfo->bitmaps[id - 1].depth = 1;
299 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
300 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
301 return id;
302 #endif
304 #ifdef HAVE_X_WINDOWS
305 unsigned int width, height;
306 Pixmap bitmap;
307 int xhot, yhot, result;
308 ptrdiff_t id;
309 Lisp_Object found;
310 char *filename;
312 /* Look for an existing bitmap with the same name. */
313 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
315 if (dpyinfo->bitmaps[id].refcount
316 && dpyinfo->bitmaps[id].file
317 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
319 ++dpyinfo->bitmaps[id].refcount;
320 return id + 1;
324 /* Search bitmap-file-path for the file, if appropriate. */
325 if (openp (Vx_bitmap_file_path, file, Qnil, &found,
326 make_number (R_OK), false)
327 < 0)
328 return -1;
330 filename = SSDATA (found);
332 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
333 filename, &width, &height, &bitmap, &xhot, &yhot);
334 if (result != BitmapSuccess)
335 return -1;
337 id = x_allocate_bitmap_record (f);
338 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
339 dpyinfo->bitmaps[id - 1].have_mask = false;
340 dpyinfo->bitmaps[id - 1].refcount = 1;
341 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
342 dpyinfo->bitmaps[id - 1].depth = 1;
343 dpyinfo->bitmaps[id - 1].height = height;
344 dpyinfo->bitmaps[id - 1].width = width;
346 return id;
347 #endif /* HAVE_X_WINDOWS */
350 /* Free bitmap B. */
352 static void
353 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
355 #ifdef HAVE_X_WINDOWS
356 XFreePixmap (dpyinfo->display, bm->pixmap);
357 if (bm->have_mask)
358 XFreePixmap (dpyinfo->display, bm->mask);
359 #endif /* HAVE_X_WINDOWS */
361 #ifdef HAVE_NTGUI
362 DeleteObject (bm->pixmap);
363 #endif /* HAVE_NTGUI */
365 #ifdef HAVE_NS
366 ns_release_object (bm->img);
367 #endif
369 if (bm->file)
371 xfree (bm->file);
372 bm->file = NULL;
376 /* Remove reference to bitmap with id number ID. */
378 void
379 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
381 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
383 if (id > 0)
385 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
387 if (--bm->refcount == 0)
389 block_input ();
390 free_bitmap_record (dpyinfo, bm);
391 unblock_input ();
396 /* Free all the bitmaps for the display specified by DPYINFO. */
398 void
399 x_destroy_all_bitmaps (Display_Info *dpyinfo)
401 ptrdiff_t i;
402 Bitmap_Record *bm = dpyinfo->bitmaps;
404 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
405 if (bm->refcount > 0)
406 free_bitmap_record (dpyinfo, bm);
408 dpyinfo->bitmaps_last = 0;
411 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
412 XImagePtr *, Pixmap *);
413 static void x_destroy_x_image (XImagePtr ximg);
415 #ifdef HAVE_NTGUI
416 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
417 bool, HGDIOBJ *);
418 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
419 HGDIOBJ);
420 #else
421 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
422 static void image_unget_x_image (struct image *, bool, XImagePtr);
423 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
424 image_get_x_image (f, img, mask_p)
425 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
426 image_unget_x_image (img, mask_p, ximg)
427 #endif
429 #ifdef HAVE_X_WINDOWS
431 static void image_sync_to_pixmaps (struct frame *, struct image *);
433 /* Useful functions defined in the section
434 `Image type independent image structures' below. */
436 static unsigned long four_corners_best (XImagePtr ximg,
437 int *corners,
438 unsigned long width,
439 unsigned long height);
442 /* Create a mask of a bitmap. Note is this not a perfect mask.
443 It's nicer with some borders in this context */
445 void
446 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
448 Pixmap pixmap, mask;
449 XImagePtr ximg, mask_img;
450 unsigned long width, height;
451 bool result;
452 unsigned long bg;
453 unsigned long x, y, xp, xm, yp, ym;
454 GC gc;
456 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
458 if (!(id > 0))
459 return;
461 pixmap = x_bitmap_pixmap (f, id);
462 width = x_bitmap_width (f, id);
463 height = x_bitmap_height (f, id);
465 block_input ();
466 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
467 ~0, ZPixmap);
469 if (!ximg)
471 unblock_input ();
472 return;
475 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
477 unblock_input ();
478 if (!result)
480 XDestroyImage (ximg);
481 return;
484 bg = four_corners_best (ximg, NULL, width, height);
486 for (y = 0; y < ximg->height; ++y)
488 for (x = 0; x < ximg->width; ++x)
490 xp = x != ximg->width - 1 ? x + 1 : 0;
491 xm = x != 0 ? x - 1 : ximg->width - 1;
492 yp = y != ximg->height - 1 ? y + 1 : 0;
493 ym = y != 0 ? y - 1 : ximg->height - 1;
494 if (XGetPixel (ximg, x, y) == bg
495 && XGetPixel (ximg, x, yp) == bg
496 && XGetPixel (ximg, x, ym) == bg
497 && XGetPixel (ximg, xp, y) == bg
498 && XGetPixel (ximg, xp, yp) == bg
499 && XGetPixel (ximg, xp, ym) == bg
500 && XGetPixel (ximg, xm, y) == bg
501 && XGetPixel (ximg, xm, yp) == bg
502 && XGetPixel (ximg, xm, ym) == bg)
503 XPutPixel (mask_img, x, y, 0);
504 else
505 XPutPixel (mask_img, x, y, 1);
509 eassert (input_blocked_p ());
510 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
511 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
512 width, height);
513 XFreeGC (FRAME_X_DISPLAY (f), gc);
515 dpyinfo->bitmaps[id - 1].have_mask = true;
516 dpyinfo->bitmaps[id - 1].mask = mask;
518 XDestroyImage (ximg);
519 x_destroy_x_image (mask_img);
522 #endif /* HAVE_X_WINDOWS */
524 /***********************************************************************
525 Image types
526 ***********************************************************************/
528 /* List of supported image types. Use define_image_type to add new
529 types. Use lookup_image_type to find a type for a given symbol. */
531 static struct image_type *image_types;
533 /* Forward function prototypes. */
535 static struct image_type *lookup_image_type (Lisp_Object);
536 static void x_laplace (struct frame *, struct image *);
537 static void x_emboss (struct frame *, struct image *);
538 static void x_build_heuristic_mask (struct frame *, struct image *,
539 Lisp_Object);
540 #ifdef WINDOWSNT
541 #define CACHE_IMAGE_TYPE(type, status) \
542 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
543 #else
544 #define CACHE_IMAGE_TYPE(type, status)
545 #endif
547 #define ADD_IMAGE_TYPE(type) \
548 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
550 /* Define a new image type from TYPE. This adds a copy of TYPE to
551 image_types and caches the loading status of TYPE. */
553 static struct image_type *
554 define_image_type (struct image_type *type)
556 struct image_type *p = NULL;
557 int new_type = type->type;
558 bool type_valid = true;
560 block_input ();
562 for (p = image_types; p; p = p->next)
563 if (p->type == new_type)
564 goto done;
566 if (type->init)
568 #if defined HAVE_NTGUI && defined WINDOWSNT
569 /* If we failed to load the library before, don't try again. */
570 Lisp_Object tested = Fassq (builtin_lisp_symbol (new_type),
571 Vlibrary_cache);
572 if (CONSP (tested) && NILP (XCDR (tested)))
573 type_valid = false;
574 else
575 #endif
577 type_valid = type->init ();
578 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type),
579 type_valid ? Qt : Qnil);
583 if (type_valid)
585 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
586 The initialized data segment is read-only. */
587 p = xmalloc (sizeof *p);
588 *p = *type;
589 p->next = image_types;
590 image_types = p;
593 done:
594 unblock_input ();
595 return p;
599 /* Value is true if OBJECT is a valid Lisp image specification. A
600 valid image specification is a list whose car is the symbol
601 `image', and whose rest is a property list. The property list must
602 contain a value for key `:type'. That value must be the name of a
603 supported image type. The rest of the property list depends on the
604 image type. */
606 bool
607 valid_image_p (Lisp_Object object)
609 bool valid_p = 0;
611 if (IMAGEP (object))
613 Lisp_Object tem;
615 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
616 if (EQ (XCAR (tem), QCtype))
618 tem = XCDR (tem);
619 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
621 struct image_type *type;
622 type = lookup_image_type (XCAR (tem));
623 if (type)
624 valid_p = type->valid_p (object);
627 break;
631 return valid_p;
635 /* Log error message with format string FORMAT and trailing arguments.
636 Signaling an error, e.g. when an image cannot be loaded, is not a
637 good idea because this would interrupt redisplay, and the error
638 message display would lead to another redisplay. This function
639 therefore simply displays a message. */
641 static void
642 image_error (const char *format, ...)
644 va_list ap;
645 va_start (ap, format);
646 vadd_to_log (format, ap);
647 va_end (ap);
650 static void
651 image_size_error (void)
653 image_error ("Invalid image size (see `max-image-size')");
657 /***********************************************************************
658 Image specifications
659 ***********************************************************************/
661 enum image_value_type
663 IMAGE_DONT_CHECK_VALUE_TYPE,
664 IMAGE_STRING_VALUE,
665 IMAGE_STRING_OR_NIL_VALUE,
666 IMAGE_SYMBOL_VALUE,
667 IMAGE_POSITIVE_INTEGER_VALUE,
668 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
669 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
670 IMAGE_ASCENT_VALUE,
671 IMAGE_INTEGER_VALUE,
672 IMAGE_FUNCTION_VALUE,
673 IMAGE_NUMBER_VALUE,
674 IMAGE_BOOL_VALUE
677 /* Structure used when parsing image specifications. */
679 struct image_keyword
681 /* Name of keyword. */
682 const char *name;
684 /* The type of value allowed. */
685 enum image_value_type type;
687 /* True means key must be present. */
688 bool mandatory_p;
690 /* Used to recognize duplicate keywords in a property list. */
691 int count;
693 /* The value that was found. */
694 Lisp_Object value;
698 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
699 has the format (image KEYWORD VALUE ...). One of the keyword/
700 value pairs must be `:type TYPE'. KEYWORDS is a vector of
701 image_keywords structures of size NKEYWORDS describing other
702 allowed keyword/value pairs. Value is true if SPEC is valid. */
704 static bool
705 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
706 int nkeywords, Lisp_Object type)
708 int i;
709 Lisp_Object plist;
711 if (!IMAGEP (spec))
712 return 0;
714 plist = XCDR (spec);
715 while (CONSP (plist))
717 Lisp_Object key, value;
719 /* First element of a pair must be a symbol. */
720 key = XCAR (plist);
721 plist = XCDR (plist);
722 if (!SYMBOLP (key))
723 return 0;
725 /* There must follow a value. */
726 if (!CONSP (plist))
727 return 0;
728 value = XCAR (plist);
729 plist = XCDR (plist);
731 /* Find key in KEYWORDS. Error if not found. */
732 for (i = 0; i < nkeywords; ++i)
733 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
734 break;
736 if (i == nkeywords)
737 continue;
739 /* Record that we recognized the keyword. If a keywords
740 was found more than once, it's an error. */
741 keywords[i].value = value;
742 if (keywords[i].count > 1)
743 return 0;
744 ++keywords[i].count;
746 /* Check type of value against allowed type. */
747 switch (keywords[i].type)
749 case IMAGE_STRING_VALUE:
750 if (!STRINGP (value))
751 return 0;
752 break;
754 case IMAGE_STRING_OR_NIL_VALUE:
755 if (!STRINGP (value) && !NILP (value))
756 return 0;
757 break;
759 case IMAGE_SYMBOL_VALUE:
760 if (!SYMBOLP (value))
761 return 0;
762 break;
764 case IMAGE_POSITIVE_INTEGER_VALUE:
765 if (! RANGED_INTEGERP (1, value, INT_MAX))
766 return 0;
767 break;
769 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
770 if (RANGED_INTEGERP (0, value, INT_MAX))
771 break;
772 if (CONSP (value)
773 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
774 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
775 break;
776 return 0;
778 case IMAGE_ASCENT_VALUE:
779 if (SYMBOLP (value) && EQ (value, Qcenter))
780 break;
781 else if (RANGED_INTEGERP (0, value, 100))
782 break;
783 return 0;
785 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
786 /* Unlike the other integer-related cases, this one does not
787 verify that VALUE fits in 'int'. This is because callers
788 want EMACS_INT. */
789 if (!INTEGERP (value) || XINT (value) < 0)
790 return 0;
791 break;
793 case IMAGE_DONT_CHECK_VALUE_TYPE:
794 break;
796 case IMAGE_FUNCTION_VALUE:
797 value = indirect_function (value);
798 if (!NILP (Ffunctionp (value)))
799 break;
800 return 0;
802 case IMAGE_NUMBER_VALUE:
803 if (! NUMBERP (value))
804 return 0;
805 break;
807 case IMAGE_INTEGER_VALUE:
808 if (! TYPE_RANGED_INTEGERP (int, value))
809 return 0;
810 break;
812 case IMAGE_BOOL_VALUE:
813 if (!NILP (value) && !EQ (value, Qt))
814 return 0;
815 break;
817 default:
818 emacs_abort ();
819 break;
822 if (EQ (key, QCtype) && !EQ (type, value))
823 return 0;
826 /* Check that all mandatory fields are present. */
827 for (i = 0; i < nkeywords; ++i)
828 if (keywords[i].mandatory_p && keywords[i].count == 0)
829 return 0;
831 return NILP (plist);
835 /* Return the value of KEY in image specification SPEC. Value is nil
836 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
837 was found in SPEC. */
839 static Lisp_Object
840 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
842 Lisp_Object tail;
844 eassert (valid_image_p (spec));
846 for (tail = XCDR (spec);
847 CONSP (tail) && CONSP (XCDR (tail));
848 tail = XCDR (XCDR (tail)))
850 if (EQ (XCAR (tail), key))
852 if (found)
853 *found = 1;
854 return XCAR (XCDR (tail));
858 if (found)
859 *found = 0;
860 return Qnil;
864 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
865 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
866 PIXELS non-nil means return the size in pixels, otherwise return the
867 size in canonical character units.
868 FRAME is the frame on which the image will be displayed. FRAME nil
869 or omitted means use the selected frame. */)
870 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
872 Lisp_Object size;
874 size = Qnil;
875 if (valid_image_p (spec))
877 struct frame *f = decode_window_system_frame (frame);
878 ptrdiff_t id = lookup_image (f, spec);
879 struct image *img = IMAGE_FROM_ID (f, id);
880 int width = img->width + 2 * img->hmargin;
881 int height = img->height + 2 * img->vmargin;
883 if (NILP (pixels))
884 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
885 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
886 else
887 size = Fcons (make_number (width), make_number (height));
889 else
890 error ("Invalid image specification");
892 return size;
896 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
897 doc: /* Return t if image SPEC has a mask bitmap.
898 FRAME is the frame on which the image will be displayed. FRAME nil
899 or omitted means use the selected frame. */)
900 (Lisp_Object spec, Lisp_Object frame)
902 Lisp_Object mask;
904 mask = Qnil;
905 if (valid_image_p (spec))
907 struct frame *f = decode_window_system_frame (frame);
908 ptrdiff_t id = lookup_image (f, spec);
909 struct image *img = IMAGE_FROM_ID (f, id);
910 if (img->mask)
911 mask = Qt;
913 else
914 error ("Invalid image specification");
916 return mask;
919 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
920 doc: /* Return metadata for image SPEC.
921 FRAME is the frame on which the image will be displayed. FRAME nil
922 or omitted means use the selected frame. */)
923 (Lisp_Object spec, Lisp_Object frame)
925 Lisp_Object ext;
927 ext = Qnil;
928 if (valid_image_p (spec))
930 struct frame *f = decode_window_system_frame (frame);
931 ptrdiff_t id = lookup_image (f, spec);
932 struct image *img = IMAGE_FROM_ID (f, id);
933 ext = img->lisp_data;
936 return ext;
940 /***********************************************************************
941 Image type independent image structures
942 ***********************************************************************/
944 #define MAX_IMAGE_SIZE 10.0
945 /* Allocate and return a new image structure for image specification
946 SPEC. SPEC has a hash value of HASH. */
948 static struct image *
949 make_image (Lisp_Object spec, EMACS_UINT hash)
951 struct image *img = xzalloc (sizeof *img);
952 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
954 eassert (valid_image_p (spec));
955 img->dependencies = NILP (file) ? Qnil : list1 (file);
956 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
957 eassert (img->type != NULL);
958 img->spec = spec;
959 img->lisp_data = Qnil;
960 img->ascent = DEFAULT_IMAGE_ASCENT;
961 img->hash = hash;
962 img->corners[BOT_CORNER] = -1; /* Full image */
963 return img;
967 /* Free image IMG which was used on frame F, including its resources. */
969 static void
970 free_image (struct frame *f, struct image *img)
972 if (img)
974 struct image_cache *c = FRAME_IMAGE_CACHE (f);
976 /* Remove IMG from the hash table of its cache. */
977 if (img->prev)
978 img->prev->next = img->next;
979 else
980 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
982 if (img->next)
983 img->next->prev = img->prev;
985 c->images[img->id] = NULL;
987 /* Windows NT redefines 'free', but in this file, we need to
988 avoid the redefinition. */
989 #ifdef WINDOWSNT
990 #undef free
991 #endif
992 /* Free resources, then free IMG. */
993 img->type->free (f, img);
994 xfree (img);
998 /* Return true if the given widths and heights are valid for display. */
1000 static bool
1001 check_image_size (struct frame *f, int width, int height)
1003 int w, h;
1005 if (width <= 0 || height <= 0)
1006 return 0;
1008 if (INTEGERP (Vmax_image_size))
1009 return (width <= XINT (Vmax_image_size)
1010 && height <= XINT (Vmax_image_size));
1011 else if (FLOATP (Vmax_image_size))
1013 if (f != NULL)
1015 w = FRAME_PIXEL_WIDTH (f);
1016 h = FRAME_PIXEL_HEIGHT (f);
1018 else
1019 w = h = 1024; /* Arbitrary size for unknown frame. */
1020 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1021 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1023 else
1024 return 1;
1027 /* Prepare image IMG for display on frame F. Must be called before
1028 drawing an image. */
1030 void
1031 prepare_image_for_display (struct frame *f, struct image *img)
1033 /* We're about to display IMG, so set its timestamp to `now'. */
1034 img->timestamp = current_timespec ();
1036 #ifndef USE_CAIRO
1037 /* If IMG doesn't have a pixmap yet, load it now, using the image
1038 type dependent loader function. */
1039 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1040 img->load_failed_p = ! img->type->load (f, img);
1042 #ifdef HAVE_X_WINDOWS
1043 if (!img->load_failed_p)
1045 block_input ();
1046 image_sync_to_pixmaps (f, img);
1047 unblock_input ();
1049 #endif
1050 #endif
1054 /* Value is the number of pixels for the ascent of image IMG when
1055 drawn in face FACE. */
1058 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1060 int height;
1061 int ascent;
1063 if (slice->height == img->height)
1064 height = img->height + img->vmargin;
1065 else if (slice->y == 0)
1066 height = slice->height + img->vmargin;
1067 else
1068 height = slice->height;
1070 if (img->ascent == CENTERED_IMAGE_ASCENT)
1072 if (face->font)
1074 #ifdef HAVE_NTGUI
1075 /* W32 specific version. Why?. ++kfs */
1076 ascent = height / 2 - (FONT_DESCENT (face->font)
1077 - FONT_BASE (face->font)) / 2;
1078 #else
1079 /* This expression is arranged so that if the image can't be
1080 exactly centered, it will be moved slightly up. This is
1081 because a typical font is `top-heavy' (due to the presence
1082 uppercase letters), so the image placement should err towards
1083 being top-heavy too. It also just generally looks better. */
1084 ascent = (height + FONT_BASE (face->font)
1085 - FONT_DESCENT (face->font) + 1) / 2;
1086 #endif /* HAVE_NTGUI */
1088 else
1089 ascent = height / 2;
1091 else
1092 ascent = height * (img->ascent / 100.0);
1094 return ascent;
1097 #ifdef USE_CAIRO
1098 static uint32_t
1099 xcolor_to_argb32 (XColor xc)
1101 return (0xff << 24) | ((xc.red / 256) << 16)
1102 | ((xc.green / 256) << 8) | (xc.blue / 256);
1105 static uint32_t
1106 get_spec_bg_or_alpha_as_argb (struct image *img,
1107 struct frame *f)
1109 uint32_t bgcolor = 0;
1110 XColor xbgcolor;
1111 Lisp_Object bg = image_spec_value (img->spec, QCbackground, NULL);
1113 if (STRINGP (bg) && x_parse_color (f, SSDATA (bg), &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];
1153 RGB_PIXEL_COLOR best UNINIT;
1154 int i, best_count;
1156 if (corners && corners[BOT_CORNER] >= 0)
1158 /* Get the colors at the corner_pixels of ximg. */
1159 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1160 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1161 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1162 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1164 else
1166 /* Get the colors at the corner_pixels of ximg. */
1167 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1168 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1169 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1170 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1172 /* Choose the most frequently found color as background. */
1173 for (i = best_count = 0; i < 4; ++i)
1175 int j, n;
1177 for (j = n = 0; j < 4; ++j)
1178 if (corner_pixels[i] == corner_pixels[j])
1179 ++n;
1181 if (n > best_count)
1182 best = corner_pixels[i], best_count = n;
1185 return best;
1188 /* Portability macros */
1190 #ifdef HAVE_NTGUI
1192 #define Free_Pixmap(display, pixmap) \
1193 DeleteObject (pixmap)
1195 #elif defined (HAVE_NS)
1197 #define Free_Pixmap(display, pixmap) \
1198 ns_release_object (pixmap)
1200 #else
1202 #define Free_Pixmap(display, pixmap) \
1203 XFreePixmap (display, pixmap)
1205 #endif /* !HAVE_NTGUI && !HAVE_NS */
1208 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1209 it is guessed heuristically. If non-zero, XIMG is an existing
1210 XImage object (or device context with the image selected on W32) to
1211 use for the heuristic. */
1213 RGB_PIXEL_COLOR
1214 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1216 if (! img->background_valid)
1217 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1219 bool free_ximg = !ximg;
1220 #ifdef HAVE_NTGUI
1221 HGDIOBJ prev;
1222 #endif /* HAVE_NTGUI */
1224 if (free_ximg)
1225 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1227 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1229 if (free_ximg)
1230 image_unget_x_image_or_dc (img, 0, ximg, prev);
1232 img->background_valid = 1;
1235 return img->background;
1238 /* Return the `background_transparent' field of IMG. If IMG doesn't
1239 have one yet, it is guessed heuristically. If non-zero, MASK is an
1240 existing XImage object to use for the heuristic. */
1243 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1245 if (! img->background_transparent_valid)
1246 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1248 if (img->mask)
1250 bool free_mask = !mask;
1251 #ifdef HAVE_NTGUI
1252 HGDIOBJ prev;
1253 #endif /* HAVE_NTGUI */
1255 if (free_mask)
1256 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1258 img->background_transparent
1259 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1261 if (free_mask)
1262 image_unget_x_image_or_dc (img, 1, mask, prev);
1264 else
1265 img->background_transparent = 0;
1267 img->background_transparent_valid = 1;
1270 return img->background_transparent;
1273 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1274 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1276 /* Store F's background color into *BGCOLOR. */
1277 static void
1278 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1280 #ifndef HAVE_NS
1281 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1282 x_query_color (f, bgcolor);
1283 #else
1284 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1285 #endif
1288 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1290 /***********************************************************************
1291 Helper functions for X image types
1292 ***********************************************************************/
1294 /* Clear X resources of image IMG on frame F according to FLAGS.
1295 FLAGS is bitwise-or of the following masks:
1296 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1297 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1298 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1299 any. */
1301 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1302 #define CLEAR_IMAGE_MASK (1 << 1)
1303 #define CLEAR_IMAGE_COLORS (1 << 2)
1305 static void
1306 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1308 if (flags & CLEAR_IMAGE_PIXMAP)
1310 if (img->pixmap)
1312 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1313 img->pixmap = NO_PIXMAP;
1314 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1315 img->background_valid = 0;
1317 #ifdef HAVE_X_WINDOWS
1318 if (img->ximg)
1320 x_destroy_x_image (img->ximg);
1321 img->ximg = NULL;
1322 img->background_valid = 0;
1324 #endif
1327 if (flags & CLEAR_IMAGE_MASK)
1329 if (img->mask)
1331 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1332 img->mask = NO_PIXMAP;
1333 img->background_transparent_valid = 0;
1335 #ifdef HAVE_X_WINDOWS
1336 if (img->mask_img)
1338 x_destroy_x_image (img->mask_img);
1339 img->mask_img = NULL;
1340 img->background_transparent_valid = 0;
1342 #endif
1345 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1347 /* W32_TODO: color table support. */
1348 #ifdef HAVE_X_WINDOWS
1349 x_free_colors (f, img->colors, img->ncolors);
1350 #endif /* HAVE_X_WINDOWS */
1351 xfree (img->colors);
1352 img->colors = NULL;
1353 img->ncolors = 0;
1358 /* Free X resources of image IMG which is used on frame F. */
1360 static void
1361 x_clear_image (struct frame *f, struct image *img)
1363 block_input ();
1364 #ifdef USE_CAIRO
1365 if (img->cr_data)
1366 cairo_surface_destroy ((cairo_surface_t *)img->cr_data);
1367 if (img->cr_data2) xfree (img->cr_data2);
1368 #endif
1369 x_clear_image_1 (f, img,
1370 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1371 unblock_input ();
1375 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1376 cannot be allocated, use DFLT. Add a newly allocated color to
1377 IMG->colors, so that it can be freed again. Value is the pixel
1378 color. */
1380 static unsigned long
1381 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1382 unsigned long dflt)
1384 XColor color;
1385 unsigned long result;
1387 eassert (STRINGP (color_name));
1389 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1390 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1391 INT_MAX))
1393 /* This isn't called frequently so we get away with simply
1394 reallocating the color vector to the needed size, here. */
1395 ptrdiff_t ncolors = img->ncolors + 1;
1396 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1397 img->colors[ncolors - 1] = color.pixel;
1398 img->ncolors = ncolors;
1399 result = color.pixel;
1401 else
1402 result = dflt;
1404 return result;
1409 /***********************************************************************
1410 Image Cache
1411 ***********************************************************************/
1413 static void cache_image (struct frame *f, struct image *img);
1415 /* Return a new, initialized image cache that is allocated from the
1416 heap. Call free_image_cache to free an image cache. */
1418 struct image_cache *
1419 make_image_cache (void)
1421 struct image_cache *c = xmalloc (sizeof *c);
1423 c->size = 50;
1424 c->used = c->refcount = 0;
1425 c->images = xmalloc (c->size * sizeof *c->images);
1426 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1427 return c;
1431 /* Find an image matching SPEC in the cache, and return it. If no
1432 image is found, return NULL. */
1433 static struct image *
1434 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1436 struct image *img;
1437 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1438 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1440 if (!c) return NULL;
1442 /* If the image spec does not specify a background color, the cached
1443 image must have the same background color as the current frame.
1444 The foreground color must also match, for the sake of monochrome
1445 images.
1447 In fact, we could ignore the foreground color matching condition
1448 for color images, or if the image spec specifies :foreground;
1449 similarly we could ignore the background color matching condition
1450 for formats that don't use transparency (such as jpeg), or if the
1451 image spec specifies :background. However, the extra memory
1452 usage is probably negligible in practice, so we don't bother. */
1454 for (img = c->buckets[i]; img; img = img->next)
1455 if (img->hash == hash
1456 && !NILP (Fequal (img->spec, spec))
1457 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1458 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1459 break;
1460 return img;
1464 /* Search frame F for an image with spec SPEC, and free it. */
1466 static void
1467 uncache_image (struct frame *f, Lisp_Object spec)
1469 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1470 if (img)
1472 free_image (f, img);
1473 /* As display glyphs may still be referring to the image ID, we
1474 must garbage the frame (Bug#6426). */
1475 SET_FRAME_GARBAGED (f);
1480 /* Free image cache of frame F. Be aware that X frames share images
1481 caches. */
1483 void
1484 free_image_cache (struct frame *f)
1486 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1487 if (c)
1489 ptrdiff_t i;
1491 /* Cache should not be referenced by any frame when freed. */
1492 eassert (c->refcount == 0);
1494 for (i = 0; i < c->used; ++i)
1495 free_image (f, c->images[i]);
1496 xfree (c->images);
1497 xfree (c->buckets);
1498 xfree (c);
1499 FRAME_IMAGE_CACHE (f) = NULL;
1504 /* Clear image cache of frame F. FILTER=t means free all images.
1505 FILTER=nil means clear only images that haven't been
1506 displayed for some time.
1507 Else, only free the images which have FILTER in their `dependencies'.
1508 Should be called from time to time to reduce the number of loaded images.
1509 If image-cache-eviction-delay is non-nil, this frees images in the cache
1510 which weren't displayed for at least that many seconds. */
1512 static void
1513 clear_image_cache (struct frame *f, Lisp_Object filter)
1515 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1517 if (c)
1519 ptrdiff_t i, nfreed = 0;
1521 /* Block input so that we won't be interrupted by a SIGIO
1522 while being in an inconsistent state. */
1523 block_input ();
1525 if (!NILP (filter))
1527 /* Filter image cache. */
1528 for (i = 0; i < c->used; ++i)
1530 struct image *img = c->images[i];
1531 if (img && (EQ (Qt, filter)
1532 || !NILP (Fmember (filter, img->dependencies))))
1534 free_image (f, img);
1535 ++nfreed;
1539 else if (INTEGERP (Vimage_cache_eviction_delay))
1541 /* Free cache based on timestamp. */
1542 struct timespec old, t;
1543 double delay;
1544 ptrdiff_t nimages = 0;
1546 for (i = 0; i < c->used; ++i)
1547 if (c->images[i])
1548 nimages++;
1550 /* If the number of cached images has grown unusually large,
1551 decrease the cache eviction delay (Bug#6230). */
1552 delay = XINT (Vimage_cache_eviction_delay);
1553 if (nimages > 40)
1554 delay = 1600 * delay / nimages / nimages;
1555 delay = max (delay, 1);
1557 t = current_timespec ();
1558 old = timespec_sub (t, dtotimespec (delay));
1560 for (i = 0; i < c->used; ++i)
1562 struct image *img = c->images[i];
1563 if (img && timespec_cmp (img->timestamp, old) < 0)
1565 free_image (f, img);
1566 ++nfreed;
1571 /* We may be clearing the image cache because, for example,
1572 Emacs was iconified for a longer period of time. In that
1573 case, current matrices may still contain references to
1574 images freed above. So, clear these matrices. */
1575 if (nfreed)
1577 Lisp_Object tail, frame;
1579 FOR_EACH_FRAME (tail, frame)
1581 struct frame *fr = XFRAME (frame);
1582 if (FRAME_IMAGE_CACHE (fr) == c)
1583 clear_current_matrices (fr);
1586 windows_or_buffers_changed = 19;
1589 unblock_input ();
1593 void
1594 clear_image_caches (Lisp_Object filter)
1596 /* FIXME: We want to do
1597 * struct terminal *t;
1598 * for (t = terminal_list; t; t = t->next_terminal)
1599 * clear_image_cache (t, filter); */
1600 Lisp_Object tail, frame;
1601 FOR_EACH_FRAME (tail, frame)
1602 if (FRAME_WINDOW_P (XFRAME (frame)))
1603 clear_image_cache (XFRAME (frame), filter);
1606 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1607 0, 1, 0,
1608 doc: /* Clear the image cache.
1609 FILTER nil or a frame means clear all images in the selected frame.
1610 FILTER t means clear the image caches of all frames.
1611 Anything else, means only clear those images which refer to FILTER,
1612 which is then usually a filename. */)
1613 (Lisp_Object filter)
1615 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1616 clear_image_caches (filter);
1617 else
1618 clear_image_cache (decode_window_system_frame (filter), Qt);
1620 return Qnil;
1624 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1625 1, 2, 0,
1626 doc: /* Flush the image with specification SPEC on frame FRAME.
1627 This removes the image from the Emacs image cache. If SPEC specifies
1628 an image file, the next redisplay of this image will read from the
1629 current contents of that file.
1631 FRAME nil or omitted means use the selected frame.
1632 FRAME t means refresh the image on all frames. */)
1633 (Lisp_Object spec, Lisp_Object frame)
1635 if (!valid_image_p (spec))
1636 error ("Invalid image specification");
1638 if (EQ (frame, Qt))
1640 Lisp_Object tail;
1641 FOR_EACH_FRAME (tail, frame)
1643 struct frame *f = XFRAME (frame);
1644 if (FRAME_WINDOW_P (f))
1645 uncache_image (f, spec);
1648 else
1649 uncache_image (decode_window_system_frame (frame), spec);
1651 return Qnil;
1655 /* Compute masks and transform image IMG on frame F, as specified
1656 by the image's specification, */
1658 static void
1659 postprocess_image (struct frame *f, struct image *img)
1661 /* Manipulation of the image's mask. */
1662 if (img->pixmap)
1664 Lisp_Object conversion, spec;
1665 Lisp_Object mask;
1667 spec = img->spec;
1669 /* `:heuristic-mask t'
1670 `:mask heuristic'
1671 means build a mask heuristically.
1672 `:heuristic-mask (R G B)'
1673 `:mask (heuristic (R G B))'
1674 means build a mask from color (R G B) in the
1675 image.
1676 `:mask nil'
1677 means remove a mask, if any. */
1679 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1680 if (!NILP (mask))
1681 x_build_heuristic_mask (f, img, mask);
1682 else
1684 bool found_p;
1686 mask = image_spec_value (spec, QCmask, &found_p);
1688 if (EQ (mask, Qheuristic))
1689 x_build_heuristic_mask (f, img, Qt);
1690 else if (CONSP (mask)
1691 && EQ (XCAR (mask), Qheuristic))
1693 if (CONSP (XCDR (mask)))
1694 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1695 else
1696 x_build_heuristic_mask (f, img, XCDR (mask));
1698 else if (NILP (mask) && found_p && img->mask)
1699 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1703 /* Should we apply an image transformation algorithm? */
1704 conversion = image_spec_value (spec, QCconversion, NULL);
1705 if (EQ (conversion, Qdisabled))
1706 x_disable_image (f, img);
1707 else if (EQ (conversion, Qlaplace))
1708 x_laplace (f, img);
1709 else if (EQ (conversion, Qemboss))
1710 x_emboss (f, img);
1711 else if (CONSP (conversion)
1712 && EQ (XCAR (conversion), Qedge_detection))
1714 Lisp_Object tem;
1715 tem = XCDR (conversion);
1716 if (CONSP (tem))
1717 x_edge_detection (f, img,
1718 Fplist_get (tem, QCmatrix),
1719 Fplist_get (tem, QCcolor_adjustment));
1725 /* Return the id of image with Lisp specification SPEC on frame F.
1726 SPEC must be a valid Lisp image specification (see valid_image_p). */
1728 ptrdiff_t
1729 lookup_image (struct frame *f, Lisp_Object spec)
1731 struct image *img;
1732 EMACS_UINT hash;
1734 /* F must be a window-system frame, and SPEC must be a valid image
1735 specification. */
1736 eassert (FRAME_WINDOW_P (f));
1737 eassert (valid_image_p (spec));
1739 /* Look up SPEC in the hash table of the image cache. */
1740 hash = sxhash (spec, 0);
1741 img = search_image_cache (f, spec, hash);
1742 if (img && img->load_failed_p)
1744 free_image (f, img);
1745 img = NULL;
1748 /* If not found, create a new image and cache it. */
1749 if (img == NULL)
1751 block_input ();
1752 img = make_image (spec, hash);
1753 cache_image (f, img);
1754 img->load_failed_p = ! img->type->load (f, img);
1755 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1756 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1758 /* If we can't load the image, and we don't have a width and
1759 height, use some arbitrary width and height so that we can
1760 draw a rectangle for it. */
1761 if (img->load_failed_p)
1763 Lisp_Object value;
1765 value = image_spec_value (spec, QCwidth, NULL);
1766 img->width = (INTEGERP (value)
1767 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1768 value = image_spec_value (spec, QCheight, NULL);
1769 img->height = (INTEGERP (value)
1770 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1772 else
1774 /* Handle image type independent image attributes
1775 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1776 `:background COLOR'. */
1777 Lisp_Object ascent, margin, relief, bg;
1778 int relief_bound;
1780 ascent = image_spec_value (spec, QCascent, NULL);
1781 if (INTEGERP (ascent))
1782 img->ascent = XFASTINT (ascent);
1783 else if (EQ (ascent, Qcenter))
1784 img->ascent = CENTERED_IMAGE_ASCENT;
1786 margin = image_spec_value (spec, QCmargin, NULL);
1787 if (INTEGERP (margin))
1788 img->vmargin = img->hmargin = XFASTINT (margin);
1789 else if (CONSP (margin))
1791 img->hmargin = XFASTINT (XCAR (margin));
1792 img->vmargin = XFASTINT (XCDR (margin));
1795 relief = image_spec_value (spec, QCrelief, NULL);
1796 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1797 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1799 img->relief = XINT (relief);
1800 img->hmargin += eabs (img->relief);
1801 img->vmargin += eabs (img->relief);
1804 if (! img->background_valid)
1806 bg = image_spec_value (img->spec, QCbackground, NULL);
1807 if (!NILP (bg))
1809 img->background
1810 = x_alloc_image_color (f, img, bg,
1811 FRAME_BACKGROUND_PIXEL (f));
1812 img->background_valid = 1;
1816 /* Do image transformations and compute masks, unless we
1817 don't have the image yet. */
1818 if (!EQ (builtin_lisp_symbol (img->type->type), Qpostscript))
1819 postprocess_image (f, img);
1822 unblock_input ();
1825 /* We're using IMG, so set its timestamp to `now'. */
1826 img->timestamp = current_timespec ();
1828 /* Value is the image id. */
1829 return img->id;
1833 /* Cache image IMG in the image cache of frame F. */
1835 static void
1836 cache_image (struct frame *f, struct image *img)
1838 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1839 ptrdiff_t i;
1841 if (!c)
1842 c = FRAME_IMAGE_CACHE (f) = make_image_cache ();
1844 /* Find a free slot in c->images. */
1845 for (i = 0; i < c->used; ++i)
1846 if (c->images[i] == NULL)
1847 break;
1849 /* If no free slot found, maybe enlarge c->images. */
1850 if (i == c->used && c->used == c->size)
1851 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1853 /* Add IMG to c->images, and assign IMG an id. */
1854 c->images[i] = img;
1855 img->id = i;
1856 if (i == c->used)
1857 ++c->used;
1859 /* Add IMG to the cache's hash table. */
1860 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1861 img->next = c->buckets[i];
1862 if (img->next)
1863 img->next->prev = img;
1864 img->prev = NULL;
1865 c->buckets[i] = img;
1869 /* Call FN on every image in the image cache of frame F. Used to mark
1870 Lisp Objects in the image cache. */
1872 /* Mark Lisp objects in image IMG. */
1874 static void
1875 mark_image (struct image *img)
1877 mark_object (img->spec);
1878 mark_object (img->dependencies);
1880 if (!NILP (img->lisp_data))
1881 mark_object (img->lisp_data);
1885 void
1886 mark_image_cache (struct image_cache *c)
1888 if (c)
1890 ptrdiff_t i;
1891 for (i = 0; i < c->used; ++i)
1892 if (c->images[i])
1893 mark_image (c->images[i]);
1899 /***********************************************************************
1900 X / NS / W32 support code
1901 ***********************************************************************/
1903 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1904 windowing system.
1905 WIDTH and HEIGHT must both be positive.
1906 If XIMG is null, assume it is a bitmap. */
1907 static bool
1908 x_check_image_size (XImagePtr ximg, int width, int height)
1910 #ifdef HAVE_X_WINDOWS
1911 /* Respect Xlib's limits: it cannot deal with images that have more
1912 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1913 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1914 enum
1916 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1917 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1920 int bitmap_pad, depth, bytes_per_line;
1921 if (ximg)
1923 bitmap_pad = ximg->bitmap_pad;
1924 depth = ximg->depth;
1925 bytes_per_line = ximg->bytes_per_line;
1927 else
1929 bitmap_pad = 8;
1930 depth = 1;
1931 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1933 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1934 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1935 #else
1936 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1937 For now, assume that every image size is allowed on these systems. */
1938 return 1;
1939 #endif
1942 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1943 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1944 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1945 via xmalloc. Print error messages via image_error if an error
1946 occurs. Value is true if successful.
1948 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1949 should indicate the bit depth of the image. */
1951 static bool
1952 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1953 XImagePtr *ximg, Pixmap *pixmap)
1955 #ifdef HAVE_X_WINDOWS
1956 Display *display = FRAME_X_DISPLAY (f);
1957 Window window = FRAME_X_WINDOW (f);
1958 Screen *screen = FRAME_X_SCREEN (f);
1960 eassert (input_blocked_p ());
1962 if (depth <= 0)
1963 depth = DefaultDepthOfScreen (screen);
1964 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1965 depth, ZPixmap, 0, NULL, width, height,
1966 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1967 if (*ximg == NULL)
1969 image_error ("Unable to allocate X image");
1970 return 0;
1973 if (! x_check_image_size (*ximg, width, height))
1975 x_destroy_x_image (*ximg);
1976 *ximg = NULL;
1977 image_error ("Image too large (%dx%d)",
1978 make_number (width), make_number (height));
1979 return 0;
1982 /* Allocate image raster. */
1983 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1985 /* Allocate a pixmap of the same size. */
1986 *pixmap = XCreatePixmap (display, window, width, height, depth);
1987 if (*pixmap == NO_PIXMAP)
1989 x_destroy_x_image (*ximg);
1990 *ximg = NULL;
1991 image_error ("Unable to create X pixmap");
1992 return 0;
1995 return 1;
1996 #endif /* HAVE_X_WINDOWS */
1998 #ifdef HAVE_NTGUI
2000 BITMAPINFOHEADER *header;
2001 HDC hdc;
2002 int scanline_width_bits;
2003 int remainder;
2004 int palette_colors = 0;
2006 if (depth == 0)
2007 depth = 24;
2009 if (depth != 1 && depth != 4 && depth != 8
2010 && depth != 16 && depth != 24 && depth != 32)
2012 image_error ("Invalid image bit depth specified");
2013 return 0;
2016 scanline_width_bits = width * depth;
2017 remainder = scanline_width_bits % 32;
2019 if (remainder)
2020 scanline_width_bits += 32 - remainder;
2022 /* Bitmaps with a depth less than 16 need a palette. */
2023 /* BITMAPINFO structure already contains the first RGBQUAD. */
2024 if (depth < 16)
2025 palette_colors = 1 << (depth - 1);
2027 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2029 header = &(*ximg)->info.bmiHeader;
2030 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2031 header->biSize = sizeof (*header);
2032 header->biWidth = width;
2033 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2034 header->biPlanes = 1;
2035 header->biBitCount = depth;
2036 header->biCompression = BI_RGB;
2037 header->biClrUsed = palette_colors;
2039 /* TODO: fill in palette. */
2040 if (depth == 1)
2042 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2043 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2044 (*ximg)->info.bmiColors[0].rgbRed = 0;
2045 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2046 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2047 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2048 (*ximg)->info.bmiColors[1].rgbRed = 255;
2049 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2052 hdc = get_frame_dc (f);
2054 /* Create a DIBSection and raster array for the bitmap,
2055 and store its handle in *pixmap. */
2056 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2057 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2058 /* casting avoids a GCC warning */
2059 (void **)&((*ximg)->data), NULL, 0);
2061 /* Realize display palette and garbage all frames. */
2062 release_frame_dc (f, hdc);
2064 if (*pixmap == NULL)
2066 DWORD err = GetLastError ();
2067 Lisp_Object errcode;
2068 /* All system errors are < 10000, so the following is safe. */
2069 XSETINT (errcode, err);
2070 image_error ("Unable to create bitmap, error code %d", errcode);
2071 x_destroy_x_image (*ximg);
2072 *ximg = NULL;
2073 return 0;
2076 return 1;
2078 #endif /* HAVE_NTGUI */
2080 #ifdef HAVE_NS
2081 *pixmap = ns_image_for_XPM (width, height, depth);
2082 if (*pixmap == 0)
2084 *ximg = NULL;
2085 image_error ("Unable to allocate NSImage for XPM pixmap");
2086 return 0;
2088 *ximg = *pixmap;
2089 return 1;
2090 #endif
2094 /* Destroy XImage XIMG. Free XIMG->data. */
2096 static void
2097 x_destroy_x_image (XImagePtr ximg)
2099 eassert (input_blocked_p ());
2100 if (ximg)
2102 #ifdef HAVE_X_WINDOWS
2103 xfree (ximg->data);
2104 ximg->data = NULL;
2105 XDestroyImage (ximg);
2106 #endif /* HAVE_X_WINDOWS */
2107 #ifdef HAVE_NTGUI
2108 /* Data will be freed by DestroyObject. */
2109 ximg->data = NULL;
2110 xfree (ximg);
2111 #endif /* HAVE_NTGUI */
2112 #ifdef HAVE_NS
2113 ns_release_object (ximg);
2114 #endif /* HAVE_NS */
2119 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2120 are width and height of both the image and pixmap. */
2122 static void
2123 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2125 #ifdef HAVE_X_WINDOWS
2126 GC gc;
2128 eassert (input_blocked_p ());
2129 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2130 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2131 XFreeGC (FRAME_X_DISPLAY (f), gc);
2132 #endif /* HAVE_X_WINDOWS */
2134 #ifdef HAVE_NTGUI
2135 #if 0 /* I don't think this is necessary looking at where it is used. */
2136 HDC hdc = get_frame_dc (f);
2137 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2138 release_frame_dc (f, hdc);
2139 #endif
2140 #endif /* HAVE_NTGUI */
2142 #ifdef HAVE_NS
2143 eassert (ximg == pixmap);
2144 ns_retain_object (ximg);
2145 #endif
2148 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2149 with image_put_x_image. */
2151 static bool
2152 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2153 int width, int height, int depth,
2154 XImagePtr *ximg, bool mask_p)
2156 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2158 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2159 !mask_p ? &img->pixmap : &img->mask);
2162 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2163 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2164 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2165 On the other platforms, it puts XIMG into the pixmap, then frees
2166 the X image and its buffer. */
2168 static void
2169 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2170 bool mask_p)
2172 #ifdef HAVE_X_WINDOWS
2173 if (!mask_p)
2175 eassert (img->ximg == NULL);
2176 img->ximg = ximg;
2178 else
2180 eassert (img->mask_img == NULL);
2181 img->mask_img = ximg;
2183 #else
2184 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2185 img->width, img->height);
2186 x_destroy_x_image (ximg);
2187 #endif
2190 #ifdef HAVE_X_WINDOWS
2191 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2192 the X images and their buffers. */
2194 static void
2195 image_sync_to_pixmaps (struct frame *f, struct image *img)
2197 if (img->ximg)
2199 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2200 x_destroy_x_image (img->ximg);
2201 img->ximg = NULL;
2203 if (img->mask_img)
2205 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2206 x_destroy_x_image (img->mask_img);
2207 img->mask_img = NULL;
2210 #endif
2212 #ifdef HAVE_NTGUI
2213 /* Create a memory device context for IMG on frame F. It stores the
2214 currently selected GDI object into *PREV for future restoration by
2215 image_unget_x_image_or_dc. */
2217 static XImagePtr_or_DC
2218 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2219 HGDIOBJ *prev)
2221 HDC frame_dc = get_frame_dc (f);
2222 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2224 release_frame_dc (f, frame_dc);
2225 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2227 return ximg;
2230 static void
2231 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2232 XImagePtr_or_DC ximg, HGDIOBJ prev)
2234 SelectObject (ximg, prev);
2235 DeleteDC (ximg);
2237 #else /* !HAVE_NTGUI */
2238 /* Get the X image for IMG on frame F. The resulting X image data
2239 should be treated as read-only at least on X. */
2241 static XImagePtr
2242 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2244 #ifdef HAVE_X_WINDOWS
2245 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2247 if (ximg_in_img)
2248 return ximg_in_img;
2249 else
2250 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2251 0, 0, img->width, img->height, ~0, ZPixmap);
2252 #elif defined (HAVE_NS)
2253 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2255 ns_retain_object (pixmap);
2256 return pixmap;
2257 #endif
2260 static void
2261 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2263 #ifdef HAVE_X_WINDOWS
2264 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2266 if (ximg_in_img)
2267 eassert (ximg == ximg_in_img);
2268 else
2269 XDestroyImage (ximg);
2270 #elif defined (HAVE_NS)
2271 ns_release_object (ximg);
2272 #endif
2274 #endif /* !HAVE_NTGUI */
2277 /***********************************************************************
2278 File Handling
2279 ***********************************************************************/
2281 /* Find image file FILE. Look in data-directory/images, then
2282 x-bitmap-file-path. Value is the full name of the file
2283 found, or nil if not found. If PFD is nonnull store into *PFD a
2284 readable file descriptor for the file, opened in binary mode. If
2285 PFD is null, do not open the file. */
2287 static Lisp_Object
2288 x_find_image_fd (Lisp_Object file, int *pfd)
2290 Lisp_Object file_found, search_path;
2291 int fd;
2293 /* TODO I think this should use something like image-load-path
2294 instead. Unfortunately, that can contain non-string elements. */
2295 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2296 Vdata_directory),
2297 Vx_bitmap_file_path);
2299 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2300 fd = openp (search_path, file, Qnil, &file_found,
2301 pfd ? Qt : make_number (R_OK), false);
2302 if (fd >= 0 || fd == -2)
2304 file_found = ENCODE_FILE (file_found);
2305 if (fd == -2)
2307 /* The file exists locally, but has a file handler. (This
2308 happens, e.g., under Auto Image File Mode.) 'openp'
2309 didn't open the file, so we should, because the caller
2310 expects that. */
2311 fd = emacs_open (SSDATA (file_found), O_RDONLY, 0);
2314 else /* fd < 0, but not -2 */
2315 return Qnil;
2316 if (pfd)
2317 *pfd = fd;
2318 return file_found;
2321 /* Find image file FILE. Look in data-directory/images, then
2322 x-bitmap-file-path. Value is the encoded full name of the file
2323 found, or nil if not found. */
2325 Lisp_Object
2326 x_find_image_file (Lisp_Object file)
2328 return x_find_image_fd (file, 0);
2331 /* Read FILE into memory. Value is a pointer to a buffer allocated
2332 with xmalloc holding FILE's contents. Value is null if an error
2333 occurred. FD is a file descriptor open for reading FILE. Set
2334 *SIZE to the size of the file. */
2336 static unsigned char *
2337 slurp_file (int fd, ptrdiff_t *size)
2339 FILE *fp = fdopen (fd, "rb");
2341 unsigned char *buf = NULL;
2342 struct stat st;
2344 if (fp)
2346 ptrdiff_t count = SPECPDL_INDEX ();
2347 record_unwind_protect_ptr (fclose_unwind, fp);
2349 if (fstat (fileno (fp), &st) == 0
2350 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2352 /* Report an error if we read past the purported EOF.
2353 This can happen if the file grows as we read it. */
2354 ptrdiff_t buflen = st.st_size;
2355 buf = xmalloc (buflen + 1);
2356 if (fread (buf, 1, buflen + 1, fp) == buflen)
2357 *size = buflen;
2358 else
2360 xfree (buf);
2361 buf = NULL;
2365 unbind_to (count, Qnil);
2368 return buf;
2373 /***********************************************************************
2374 XBM images
2375 ***********************************************************************/
2377 static bool xbm_load (struct frame *f, struct image *img);
2378 static bool xbm_image_p (Lisp_Object object);
2379 static bool xbm_file_p (Lisp_Object);
2382 /* Indices of image specification fields in xbm_format, below. */
2384 enum xbm_keyword_index
2386 XBM_TYPE,
2387 XBM_FILE,
2388 XBM_WIDTH,
2389 XBM_HEIGHT,
2390 XBM_DATA,
2391 XBM_FOREGROUND,
2392 XBM_BACKGROUND,
2393 XBM_ASCENT,
2394 XBM_MARGIN,
2395 XBM_RELIEF,
2396 XBM_ALGORITHM,
2397 XBM_HEURISTIC_MASK,
2398 XBM_MASK,
2399 XBM_LAST
2402 /* Vector of image_keyword structures describing the format
2403 of valid XBM image specifications. */
2405 static const struct image_keyword xbm_format[XBM_LAST] =
2407 {":type", IMAGE_SYMBOL_VALUE, 1},
2408 {":file", IMAGE_STRING_VALUE, 0},
2409 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2410 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2411 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2412 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2413 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2414 {":ascent", IMAGE_ASCENT_VALUE, 0},
2415 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2416 {":relief", IMAGE_INTEGER_VALUE, 0},
2417 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2418 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2419 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2422 /* Structure describing the image type XBM. */
2424 static struct image_type xbm_type =
2426 SYMBOL_INDEX (Qxbm),
2427 xbm_image_p,
2428 xbm_load,
2429 x_clear_image,
2430 NULL,
2431 NULL
2434 /* Tokens returned from xbm_scan. */
2436 enum xbm_token
2438 XBM_TK_IDENT = 256,
2439 XBM_TK_NUMBER
2443 /* Return true if OBJECT is a valid XBM-type image specification.
2444 A valid specification is a list starting with the symbol `image'
2445 The rest of the list is a property list which must contain an
2446 entry `:type xbm'.
2448 If the specification specifies a file to load, it must contain
2449 an entry `:file FILENAME' where FILENAME is a string.
2451 If the specification is for a bitmap loaded from memory it must
2452 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2453 WIDTH and HEIGHT are integers > 0. DATA may be:
2455 1. a string large enough to hold the bitmap data, i.e. it must
2456 have a size >= (WIDTH + 7) / 8 * HEIGHT
2458 2. a bool-vector of size >= WIDTH * HEIGHT
2460 3. a vector of strings or bool-vectors, one for each line of the
2461 bitmap.
2463 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2464 may not be specified in this case because they are defined in the
2465 XBM file.
2467 Both the file and data forms may contain the additional entries
2468 `:background COLOR' and `:foreground COLOR'. If not present,
2469 foreground and background of the frame on which the image is
2470 displayed is used. */
2472 static bool
2473 xbm_image_p (Lisp_Object object)
2475 struct image_keyword kw[XBM_LAST];
2477 memcpy (kw, xbm_format, sizeof kw);
2478 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2479 return 0;
2481 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2483 if (kw[XBM_FILE].count)
2485 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2486 return 0;
2488 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2490 /* In-memory XBM file. */
2491 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2492 return 0;
2494 else
2496 Lisp_Object data;
2497 int width, height;
2499 /* Entries for `:width', `:height' and `:data' must be present. */
2500 if (!kw[XBM_WIDTH].count
2501 || !kw[XBM_HEIGHT].count
2502 || !kw[XBM_DATA].count)
2503 return 0;
2505 data = kw[XBM_DATA].value;
2506 width = XFASTINT (kw[XBM_WIDTH].value);
2507 height = XFASTINT (kw[XBM_HEIGHT].value);
2509 /* Check type of data, and width and height against contents of
2510 data. */
2511 if (VECTORP (data))
2513 EMACS_INT i;
2515 /* Number of elements of the vector must be >= height. */
2516 if (ASIZE (data) < height)
2517 return 0;
2519 /* Each string or bool-vector in data must be large enough
2520 for one line of the image. */
2521 for (i = 0; i < height; ++i)
2523 Lisp_Object elt = AREF (data, i);
2525 if (STRINGP (elt))
2527 if (SCHARS (elt)
2528 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2529 return 0;
2531 else if (BOOL_VECTOR_P (elt))
2533 if (bool_vector_size (elt) < width)
2534 return 0;
2536 else
2537 return 0;
2540 else if (STRINGP (data))
2542 if (SCHARS (data)
2543 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2544 return 0;
2546 else if (BOOL_VECTOR_P (data))
2548 if (bool_vector_size (data) / height < width)
2549 return 0;
2551 else
2552 return 0;
2555 return 1;
2559 /* Scan a bitmap file. FP is the stream to read from. Value is
2560 either an enumerator from enum xbm_token, or a character for a
2561 single-character token, or 0 at end of file. If scanning an
2562 identifier, store the lexeme of the identifier in SVAL. If
2563 scanning a number, store its value in *IVAL. */
2565 static int
2566 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2568 unsigned int c;
2570 loop:
2572 /* Skip white space. */
2573 while (*s < end && (c = *(*s)++, c_isspace (c)))
2576 if (*s >= end)
2577 c = 0;
2578 else if (c_isdigit (c))
2580 int value = 0, digit;
2582 if (c == '0' && *s < end)
2584 c = *(*s)++;
2585 if (c == 'x' || c == 'X')
2587 while (*s < end)
2589 c = *(*s)++;
2590 if (c_isdigit (c))
2591 digit = c - '0';
2592 else if (c >= 'a' && c <= 'f')
2593 digit = c - 'a' + 10;
2594 else if (c >= 'A' && c <= 'F')
2595 digit = c - 'A' + 10;
2596 else
2597 break;
2598 value = 16 * value + digit;
2601 else if (c_isdigit (c))
2603 value = c - '0';
2604 while (*s < end
2605 && (c = *(*s)++, c_isdigit (c)))
2606 value = 8 * value + c - '0';
2609 else
2611 value = c - '0';
2612 while (*s < end
2613 && (c = *(*s)++, c_isdigit (c)))
2614 value = 10 * value + c - '0';
2617 if (*s < end)
2618 *s = *s - 1;
2619 *ival = value;
2620 c = XBM_TK_NUMBER;
2622 else if (c_isalpha (c) || c == '_')
2624 *sval++ = c;
2625 while (*s < end
2626 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2627 *sval++ = c;
2628 *sval = 0;
2629 if (*s < end)
2630 *s = *s - 1;
2631 c = XBM_TK_IDENT;
2633 else if (c == '/' && **s == '*')
2635 /* C-style comment. */
2636 ++*s;
2637 while (**s && (**s != '*' || *(*s + 1) != '/'))
2638 ++*s;
2639 if (**s)
2641 *s += 2;
2642 goto loop;
2646 return c;
2649 #ifdef HAVE_NTGUI
2651 /* Create a Windows bitmap from X bitmap data. */
2652 static HBITMAP
2653 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2655 static unsigned char swap_nibble[16]
2656 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2657 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2658 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2659 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2660 int i, j, w1, w2;
2661 unsigned char *bits, *p;
2662 HBITMAP bmp;
2664 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2665 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2666 bits = alloca (height * w2);
2667 memset (bits, 0, height * w2);
2668 for (i = 0; i < height; i++)
2670 p = bits + i*w2;
2671 for (j = 0; j < w1; j++)
2673 /* Bitswap XBM bytes to match how Windows does things. */
2674 unsigned char c = *data++;
2675 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2676 | (swap_nibble[(c>>4) & 0xf]));
2679 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2681 return bmp;
2684 static void
2685 convert_mono_to_color_image (struct frame *f, struct image *img,
2686 COLORREF foreground, COLORREF background)
2688 HDC hdc, old_img_dc, new_img_dc;
2689 HGDIOBJ old_prev, new_prev;
2690 HBITMAP new_pixmap;
2692 hdc = get_frame_dc (f);
2693 old_img_dc = CreateCompatibleDC (hdc);
2694 new_img_dc = CreateCompatibleDC (hdc);
2695 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2696 release_frame_dc (f, hdc);
2697 old_prev = SelectObject (old_img_dc, img->pixmap);
2698 new_prev = SelectObject (new_img_dc, new_pixmap);
2699 /* Windows convention for mono bitmaps is black = background,
2700 white = foreground. */
2701 SetTextColor (new_img_dc, background);
2702 SetBkColor (new_img_dc, foreground);
2704 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2705 0, 0, SRCCOPY);
2707 SelectObject (old_img_dc, old_prev);
2708 SelectObject (new_img_dc, new_prev);
2709 DeleteDC (old_img_dc);
2710 DeleteDC (new_img_dc);
2711 DeleteObject (img->pixmap);
2712 if (new_pixmap == 0)
2713 fprintf (stderr, "Failed to convert image to color.\n");
2714 else
2715 img->pixmap = new_pixmap;
2718 #define XBM_BIT_SHUFFLE(b) (~(b))
2720 #else
2722 #define XBM_BIT_SHUFFLE(b) (b)
2724 #endif /* HAVE_NTGUI */
2727 static void
2728 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2729 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2730 bool non_default_colors)
2732 #ifdef HAVE_NTGUI
2733 img->pixmap
2734 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2736 /* If colors were specified, transfer the bitmap to a color one. */
2737 if (non_default_colors)
2738 convert_mono_to_color_image (f, img, fg, bg);
2740 #elif defined (HAVE_NS)
2741 img->pixmap = ns_image_from_XBM (data, img->width, img->height, fg, bg);
2743 #else
2744 img->pixmap =
2745 (x_check_image_size (0, img->width, img->height)
2746 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2747 FRAME_X_WINDOW (f),
2748 data,
2749 img->width, img->height,
2750 fg, bg,
2751 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2752 : NO_PIXMAP);
2753 #endif /* !HAVE_NTGUI && !HAVE_NS */
2758 /* Replacement for XReadBitmapFileData which isn't available under old
2759 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2760 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2761 the image. Return in *DATA the bitmap data allocated with xmalloc.
2762 Value is true if successful. DATA null means just test if
2763 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2764 inhibit the call to image_error when the image size is invalid (the
2765 bitmap remains unread). */
2767 static bool
2768 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2769 int *width, int *height, char **data,
2770 bool inhibit_image_error)
2772 unsigned char *s = contents;
2773 char buffer[BUFSIZ];
2774 bool padding_p = 0;
2775 bool v10 = 0;
2776 int bytes_per_line, i, nbytes;
2777 char *p;
2778 int value;
2779 int LA1;
2781 #define match() \
2782 LA1 = xbm_scan (&s, end, buffer, &value)
2784 #define expect(TOKEN) \
2785 do \
2787 if (LA1 != (TOKEN)) \
2788 goto failure; \
2789 match (); \
2791 while (0)
2793 #define expect_ident(IDENT) \
2794 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2795 match (); \
2796 else \
2797 goto failure
2799 *width = *height = -1;
2800 if (data)
2801 *data = NULL;
2802 LA1 = xbm_scan (&s, end, buffer, &value);
2804 /* Parse defines for width, height and hot-spots. */
2805 while (LA1 == '#')
2807 match ();
2808 expect_ident ("define");
2809 expect (XBM_TK_IDENT);
2811 if (LA1 == XBM_TK_NUMBER)
2813 char *q = strrchr (buffer, '_');
2814 q = q ? q + 1 : buffer;
2815 if (strcmp (q, "width") == 0)
2816 *width = value;
2817 else if (strcmp (q, "height") == 0)
2818 *height = value;
2820 expect (XBM_TK_NUMBER);
2823 if (!check_image_size (f, *width, *height))
2825 if (!inhibit_image_error)
2826 image_size_error ();
2827 goto failure;
2829 else if (data == NULL)
2830 goto success;
2832 /* Parse bits. Must start with `static'. */
2833 expect_ident ("static");
2834 if (LA1 == XBM_TK_IDENT)
2836 if (strcmp (buffer, "unsigned") == 0)
2838 match ();
2839 expect_ident ("char");
2841 else if (strcmp (buffer, "short") == 0)
2843 match ();
2844 v10 = 1;
2845 if (*width % 16 && *width % 16 < 9)
2846 padding_p = 1;
2848 else if (strcmp (buffer, "char") == 0)
2849 match ();
2850 else
2851 goto failure;
2853 else
2854 goto failure;
2856 expect (XBM_TK_IDENT);
2857 expect ('[');
2858 expect (']');
2859 expect ('=');
2860 expect ('{');
2862 if (! x_check_image_size (0, *width, *height))
2864 if (!inhibit_image_error)
2865 image_error ("Image too large (%dx%d)",
2866 make_number (*width), make_number (*height));
2867 goto failure;
2869 bytes_per_line = (*width + 7) / 8 + padding_p;
2870 nbytes = bytes_per_line * *height;
2871 p = *data = xmalloc (nbytes);
2873 if (v10)
2875 for (i = 0; i < nbytes; i += 2)
2877 int val = value;
2878 expect (XBM_TK_NUMBER);
2880 *p++ = XBM_BIT_SHUFFLE (val);
2881 if (!padding_p || ((i + 2) % bytes_per_line))
2882 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2884 if (LA1 == ',' || LA1 == '}')
2885 match ();
2886 else
2887 goto failure;
2890 else
2892 for (i = 0; i < nbytes; ++i)
2894 int val = value;
2895 expect (XBM_TK_NUMBER);
2897 *p++ = XBM_BIT_SHUFFLE (val);
2899 if (LA1 == ',' || LA1 == '}')
2900 match ();
2901 else
2902 goto failure;
2906 success:
2907 return 1;
2909 failure:
2911 if (data && *data)
2913 xfree (*data);
2914 *data = NULL;
2916 return 0;
2918 #undef match
2919 #undef expect
2920 #undef expect_ident
2924 /* Load XBM image IMG which will be displayed on frame F from buffer
2925 CONTENTS. END is the end of the buffer. Value is true if
2926 successful. */
2928 static bool
2929 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2930 unsigned char *end)
2932 bool rc;
2933 char *data;
2934 bool success_p = 0;
2936 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2937 &data, 0);
2938 if (rc)
2940 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2941 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2942 bool non_default_colors = 0;
2943 Lisp_Object value;
2945 eassert (img->width > 0 && img->height > 0);
2947 /* Get foreground and background colors, maybe allocate colors. */
2948 value = image_spec_value (img->spec, QCforeground, NULL);
2949 if (!NILP (value))
2951 foreground = x_alloc_image_color (f, img, value, foreground);
2952 non_default_colors = 1;
2954 value = image_spec_value (img->spec, QCbackground, NULL);
2955 if (!NILP (value))
2957 background = x_alloc_image_color (f, img, value, background);
2958 img->background = background;
2959 img->background_valid = 1;
2960 non_default_colors = 1;
2963 Create_Pixmap_From_Bitmap_Data (f, img, data,
2964 foreground, background,
2965 non_default_colors);
2966 xfree (data);
2968 if (img->pixmap == NO_PIXMAP)
2970 x_clear_image (f, img);
2971 image_error ("Unable to create X pixmap for `%s'", img->spec);
2973 else
2974 success_p = 1;
2976 else
2977 image_error ("Error loading XBM image `%s'", img->spec);
2979 return success_p;
2983 /* Value is true if DATA looks like an in-memory XBM file. */
2985 static bool
2986 xbm_file_p (Lisp_Object data)
2988 int w, h;
2989 return (STRINGP (data)
2990 && xbm_read_bitmap_data (NULL, SDATA (data),
2991 (SDATA (data) + SBYTES (data)),
2992 &w, &h, NULL, 1));
2996 /* Fill image IMG which is used on frame F with pixmap data. Value is
2997 true if successful. */
2999 static bool
3000 xbm_load (struct frame *f, struct image *img)
3002 bool success_p = 0;
3003 Lisp_Object file_name;
3005 eassert (xbm_image_p (img->spec));
3007 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3008 file_name = image_spec_value (img->spec, QCfile, NULL);
3009 if (STRINGP (file_name))
3011 int fd;
3012 Lisp_Object file = x_find_image_fd (file_name, &fd);
3013 if (!STRINGP (file))
3015 image_error ("Cannot find image file `%s'", file_name);
3016 return 0;
3019 ptrdiff_t size;
3020 unsigned char *contents = slurp_file (fd, &size);
3021 if (contents == NULL)
3023 image_error ("Error loading XBM image `%s'", file);
3024 return 0;
3027 success_p = xbm_load_image (f, img, contents, contents + size);
3028 xfree (contents);
3030 else
3032 struct image_keyword fmt[XBM_LAST];
3033 Lisp_Object data;
3034 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3035 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3036 bool non_default_colors = 0;
3037 char *bits;
3038 bool parsed_p;
3039 bool in_memory_file_p = 0;
3041 /* See if data looks like an in-memory XBM file. */
3042 data = image_spec_value (img->spec, QCdata, NULL);
3043 in_memory_file_p = xbm_file_p (data);
3045 /* Parse the image specification. */
3046 memcpy (fmt, xbm_format, sizeof fmt);
3047 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3048 eassert (parsed_p);
3050 /* Get specified width, and height. */
3051 if (!in_memory_file_p)
3053 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3054 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3055 eassert (img->width > 0 && img->height > 0);
3056 if (!check_image_size (f, img->width, img->height))
3058 image_size_error ();
3059 return 0;
3063 /* Get foreground and background colors, maybe allocate colors. */
3064 if (fmt[XBM_FOREGROUND].count
3065 && STRINGP (fmt[XBM_FOREGROUND].value))
3067 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3068 foreground);
3069 non_default_colors = 1;
3072 if (fmt[XBM_BACKGROUND].count
3073 && STRINGP (fmt[XBM_BACKGROUND].value))
3075 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3076 background);
3077 non_default_colors = 1;
3080 if (in_memory_file_p)
3081 success_p = xbm_load_image (f, img, SDATA (data),
3082 (SDATA (data)
3083 + SBYTES (data)));
3084 else
3086 USE_SAFE_ALLOCA;
3088 if (VECTORP (data))
3090 int i;
3091 char *p;
3092 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3094 SAFE_NALLOCA (bits, nbytes, img->height);
3095 p = bits;
3096 for (i = 0; i < img->height; ++i, p += nbytes)
3098 Lisp_Object line = AREF (data, i);
3099 if (STRINGP (line))
3100 memcpy (p, SDATA (line), nbytes);
3101 else
3102 memcpy (p, bool_vector_data (line), nbytes);
3105 else if (STRINGP (data))
3106 bits = SSDATA (data);
3107 else
3108 bits = (char *) bool_vector_data (data);
3110 #ifdef HAVE_NTGUI
3112 char *invertedBits;
3113 int nbytes, i;
3114 /* Windows mono bitmaps are reversed compared with X. */
3115 invertedBits = bits;
3116 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3117 SAFE_NALLOCA (bits, nbytes, img->height);
3118 for (i = 0; i < nbytes; i++)
3119 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3121 #endif
3122 /* Create the pixmap. */
3124 if (x_check_image_size (0, img->width, img->height))
3125 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3126 foreground, background,
3127 non_default_colors);
3128 else
3129 img->pixmap = NO_PIXMAP;
3131 if (img->pixmap)
3132 success_p = 1;
3133 else
3135 image_error ("Unable to create pixmap for XBM image `%s'",
3136 img->spec);
3137 x_clear_image (f, img);
3140 SAFE_FREE ();
3144 return success_p;
3149 /***********************************************************************
3150 XPM images
3151 ***********************************************************************/
3153 #if defined (HAVE_XPM) || defined (HAVE_NS)
3155 static bool xpm_image_p (Lisp_Object object);
3156 static bool xpm_load (struct frame *f, struct image *img);
3158 #endif /* HAVE_XPM || HAVE_NS */
3160 #ifdef HAVE_XPM
3161 #ifdef HAVE_NTGUI
3162 /* Indicate to xpm.h that we don't have Xlib. */
3163 #define FOR_MSW
3164 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3165 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3166 #define XColor xpm_XColor
3167 #define XImage xpm_XImage
3168 #define Display xpm_Display
3169 #ifdef CYGWIN
3170 #include "noX/xpm.h"
3171 #else /* not CYGWIN */
3172 #include "X11/xpm.h"
3173 #endif /* not CYGWIN */
3174 #undef FOR_MSW
3175 #undef XColor
3176 #undef XImage
3177 #undef Display
3178 #else /* not HAVE_NTGUI */
3179 #include "X11/xpm.h"
3180 #endif /* not HAVE_NTGUI */
3181 #endif /* HAVE_XPM */
3183 #if defined (HAVE_XPM) || defined (HAVE_NS)
3185 /* Indices of image specification fields in xpm_format, below. */
3187 enum xpm_keyword_index
3189 XPM_TYPE,
3190 XPM_FILE,
3191 XPM_DATA,
3192 XPM_ASCENT,
3193 XPM_MARGIN,
3194 XPM_RELIEF,
3195 XPM_ALGORITHM,
3196 XPM_HEURISTIC_MASK,
3197 XPM_MASK,
3198 XPM_COLOR_SYMBOLS,
3199 XPM_BACKGROUND,
3200 XPM_LAST
3203 /* Vector of image_keyword structures describing the format
3204 of valid XPM image specifications. */
3206 static const struct image_keyword xpm_format[XPM_LAST] =
3208 {":type", IMAGE_SYMBOL_VALUE, 1},
3209 {":file", IMAGE_STRING_VALUE, 0},
3210 {":data", IMAGE_STRING_VALUE, 0},
3211 {":ascent", IMAGE_ASCENT_VALUE, 0},
3212 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3213 {":relief", IMAGE_INTEGER_VALUE, 0},
3214 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3215 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3216 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3217 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3218 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3221 #if defined HAVE_NTGUI && defined WINDOWSNT
3222 static bool init_xpm_functions (void);
3223 #else
3224 #define init_xpm_functions NULL
3225 #endif
3227 /* Structure describing the image type XPM. */
3229 static struct image_type xpm_type =
3231 SYMBOL_INDEX (Qxpm),
3232 xpm_image_p,
3233 xpm_load,
3234 x_clear_image,
3235 init_xpm_functions,
3236 NULL
3239 #ifdef HAVE_X_WINDOWS
3241 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3242 functions for allocating image colors. Our own functions handle
3243 color allocation failures more gracefully than the ones on the XPM
3244 lib. */
3246 #ifndef USE_CAIRO
3247 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3248 #define ALLOC_XPM_COLORS
3249 #endif
3250 #endif /* USE_CAIRO */
3251 #endif /* HAVE_X_WINDOWS */
3253 #ifdef ALLOC_XPM_COLORS
3255 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3256 XColor *, int);
3258 /* An entry in a hash table used to cache color definitions of named
3259 colors. This cache is necessary to speed up XPM image loading in
3260 case we do color allocations ourselves. Without it, we would need
3261 a call to XParseColor per pixel in the image.
3263 FIXME Now that we're using x_parse_color and its cache, reevaluate
3264 the need for this caching layer. */
3266 struct xpm_cached_color
3268 /* Next in collision chain. */
3269 struct xpm_cached_color *next;
3271 /* Color definition (RGB and pixel color). */
3272 XColor color;
3274 /* Color name. */
3275 char name[FLEXIBLE_ARRAY_MEMBER];
3278 /* The hash table used for the color cache, and its bucket vector
3279 size. */
3281 #define XPM_COLOR_CACHE_BUCKETS 1001
3282 static struct xpm_cached_color **xpm_color_cache;
3284 /* Initialize the color cache. */
3286 static void
3287 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3289 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3290 xpm_color_cache = xzalloc (nbytes);
3291 init_color_table ();
3293 if (attrs->valuemask & XpmColorSymbols)
3295 int i;
3296 XColor color;
3298 for (i = 0; i < attrs->numsymbols; ++i)
3299 if (x_parse_color (f, attrs->colorsymbols[i].value, &color))
3301 color.pixel = lookup_rgb_color (f, color.red, color.green,
3302 color.blue);
3303 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3308 /* Free the color cache. */
3310 static void
3311 xpm_free_color_cache (void)
3313 struct xpm_cached_color *p, *next;
3314 int i;
3316 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3317 for (p = xpm_color_cache[i]; p; p = next)
3319 next = p->next;
3320 xfree (p);
3323 xfree (xpm_color_cache);
3324 xpm_color_cache = NULL;
3325 free_color_table ();
3328 /* Return the bucket index for color named COLOR_NAME in the color
3329 cache. */
3331 static int
3332 xpm_color_bucket (char *color_name)
3334 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3335 return hash % XPM_COLOR_CACHE_BUCKETS;
3339 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3340 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3341 entry added. */
3343 static struct xpm_cached_color *
3344 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3346 size_t nbytes;
3347 struct xpm_cached_color *p;
3349 if (bucket < 0)
3350 bucket = xpm_color_bucket (color_name);
3352 nbytes = FLEXSIZEOF (struct xpm_cached_color, name, strlen (color_name) + 1);
3353 p = xmalloc (nbytes);
3354 strcpy (p->name, color_name);
3355 p->color = *color;
3356 p->next = xpm_color_cache[bucket];
3357 xpm_color_cache[bucket] = p;
3358 return p;
3361 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3362 return the cached definition in *COLOR. Otherwise, make a new
3363 entry in the cache and allocate the color. Value is false if color
3364 allocation failed. */
3366 static bool
3367 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3369 struct xpm_cached_color *p;
3370 int h = xpm_color_bucket (color_name);
3372 for (p = xpm_color_cache[h]; p; p = p->next)
3373 if (strcmp (p->name, color_name) == 0)
3374 break;
3376 if (p != NULL)
3377 *color = p->color;
3378 else if (x_parse_color (f, color_name, color))
3380 color->pixel = lookup_rgb_color (f, color->red, color->green,
3381 color->blue);
3382 p = xpm_cache_color (f, color_name, color, h);
3384 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3385 with transparency, and it's useful. */
3386 else if (strcmp ("opaque", color_name) == 0)
3388 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3389 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3390 p = xpm_cache_color (f, color_name, color, h);
3393 return p != NULL;
3397 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3398 CLOSURE is a pointer to the frame on which we allocate the
3399 color. Return in *COLOR the allocated color. Value is non-zero
3400 if successful. */
3402 static int
3403 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3404 void *closure)
3406 return xpm_lookup_color (closure, color_name, color);
3410 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3411 is a pointer to the frame on which we allocate the color. Value is
3412 non-zero if successful. */
3414 static int
3415 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3417 return 1;
3420 #endif /* ALLOC_XPM_COLORS */
3423 #ifdef WINDOWSNT
3425 /* XPM library details. */
3427 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3428 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3429 (Display *, char *, xpm_XImage **,
3430 xpm_XImage **, XpmAttributes *));
3431 DEF_DLL_FN (int, XpmReadFileToImage,
3432 (Display *, char *, xpm_XImage **,
3433 xpm_XImage **, XpmAttributes *));
3434 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3436 static bool
3437 init_xpm_functions (void)
3439 HMODULE library;
3441 if (!(library = w32_delayed_load (Qxpm)))
3442 return 0;
3444 LOAD_DLL_FN (library, XpmFreeAttributes);
3445 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3446 LOAD_DLL_FN (library, XpmReadFileToImage);
3447 LOAD_DLL_FN (library, XImageFree);
3448 return 1;
3451 # undef XImageFree
3452 # undef XpmCreateImageFromBuffer
3453 # undef XpmFreeAttributes
3454 # undef XpmReadFileToImage
3456 # define XImageFree fn_XImageFree
3457 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3458 # define XpmFreeAttributes fn_XpmFreeAttributes
3459 # define XpmReadFileToImage fn_XpmReadFileToImage
3461 #endif /* WINDOWSNT */
3463 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3464 for XPM images. Such a list must consist of conses whose car and
3465 cdr are strings. */
3467 static bool
3468 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3470 while (CONSP (color_symbols))
3472 Lisp_Object sym = XCAR (color_symbols);
3473 if (!CONSP (sym)
3474 || !STRINGP (XCAR (sym))
3475 || !STRINGP (XCDR (sym)))
3476 break;
3477 color_symbols = XCDR (color_symbols);
3480 return NILP (color_symbols);
3484 /* Value is true if OBJECT is a valid XPM image specification. */
3486 static bool
3487 xpm_image_p (Lisp_Object object)
3489 struct image_keyword fmt[XPM_LAST];
3490 memcpy (fmt, xpm_format, sizeof fmt);
3491 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3492 /* Either `:file' or `:data' must be present. */
3493 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3494 /* Either no `:color-symbols' or it's a list of conses
3495 whose car and cdr are strings. */
3496 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3497 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3500 #endif /* HAVE_XPM || HAVE_NS */
3502 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3503 ptrdiff_t
3504 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3506 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3507 ptrdiff_t id;
3508 int rc;
3509 XpmAttributes attrs;
3510 Pixmap bitmap, mask;
3512 memset (&attrs, 0, sizeof attrs);
3514 attrs.visual = FRAME_X_VISUAL (f);
3515 attrs.colormap = FRAME_X_COLORMAP (f);
3516 attrs.valuemask |= XpmVisual;
3517 attrs.valuemask |= XpmColormap;
3519 #ifdef ALLOC_XPM_COLORS
3520 attrs.color_closure = f;
3521 attrs.alloc_color = xpm_alloc_color;
3522 attrs.free_colors = xpm_free_colors;
3523 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3524 xpm_init_color_cache (f, &attrs);
3525 #endif
3527 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3528 (char **) bits, &bitmap, &mask, &attrs);
3529 if (rc != XpmSuccess)
3531 XpmFreeAttributes (&attrs);
3532 return -1;
3535 id = x_allocate_bitmap_record (f);
3536 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3537 dpyinfo->bitmaps[id - 1].have_mask = true;
3538 dpyinfo->bitmaps[id - 1].mask = mask;
3539 dpyinfo->bitmaps[id - 1].file = NULL;
3540 dpyinfo->bitmaps[id - 1].height = attrs.height;
3541 dpyinfo->bitmaps[id - 1].width = attrs.width;
3542 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3543 dpyinfo->bitmaps[id - 1].refcount = 1;
3545 #ifdef ALLOC_XPM_COLORS
3546 xpm_free_color_cache ();
3547 #endif
3548 XpmFreeAttributes (&attrs);
3549 return id;
3551 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3553 /* Load image IMG which will be displayed on frame F. Value is
3554 true if successful. */
3556 #ifdef HAVE_XPM
3558 static bool
3559 xpm_load (struct frame *f, struct image *img)
3561 int rc;
3562 XpmAttributes attrs;
3563 Lisp_Object specified_file, color_symbols;
3564 USE_SAFE_ALLOCA;
3566 #ifdef HAVE_NTGUI
3567 HDC hdc;
3568 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3569 #endif /* HAVE_NTGUI */
3571 /* Configure the XPM lib. Use the visual of frame F. Allocate
3572 close colors. Return colors allocated. */
3573 memset (&attrs, 0, sizeof attrs);
3575 #ifndef HAVE_NTGUI
3576 attrs.visual = FRAME_X_VISUAL (f);
3577 attrs.colormap = FRAME_X_COLORMAP (f);
3578 attrs.valuemask |= XpmVisual;
3579 attrs.valuemask |= XpmColormap;
3580 #endif /* HAVE_NTGUI */
3582 #ifdef ALLOC_XPM_COLORS
3583 /* Allocate colors with our own functions which handle
3584 failing color allocation more gracefully. */
3585 attrs.color_closure = f;
3586 attrs.alloc_color = xpm_alloc_color;
3587 attrs.free_colors = xpm_free_colors;
3588 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3589 #else /* not ALLOC_XPM_COLORS */
3590 /* Let the XPM lib allocate colors. */
3591 attrs.valuemask |= XpmReturnAllocPixels;
3592 #ifdef XpmAllocCloseColors
3593 attrs.alloc_close_colors = 1;
3594 attrs.valuemask |= XpmAllocCloseColors;
3595 #else /* not XpmAllocCloseColors */
3596 attrs.closeness = 600;
3597 attrs.valuemask |= XpmCloseness;
3598 #endif /* not XpmAllocCloseColors */
3599 #endif /* ALLOC_XPM_COLORS */
3601 /* If image specification contains symbolic color definitions, add
3602 these to `attrs'. */
3603 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3604 if (CONSP (color_symbols))
3606 Lisp_Object tail;
3607 XpmColorSymbol *xpm_syms;
3608 ptrdiff_t i, size;
3610 attrs.valuemask |= XpmColorSymbols;
3612 /* Count number of symbols. */
3613 attrs.numsymbols = 0;
3614 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3615 ++attrs.numsymbols;
3617 /* Allocate an XpmColorSymbol array. */
3618 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3619 size = attrs.numsymbols * sizeof *xpm_syms;
3620 memset (xpm_syms, 0, size);
3621 attrs.colorsymbols = xpm_syms;
3623 /* Fill the color symbol array. */
3624 for (tail = color_symbols, i = 0;
3625 CONSP (tail);
3626 ++i, tail = XCDR (tail))
3628 Lisp_Object name;
3629 Lisp_Object color;
3630 char *empty_string = (char *) "";
3632 if (!CONSP (XCAR (tail)))
3634 xpm_syms[i].name = empty_string;
3635 xpm_syms[i].value = empty_string;
3636 continue;
3638 name = XCAR (XCAR (tail));
3639 color = XCDR (XCAR (tail));
3640 if (STRINGP (name))
3641 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3642 else
3643 xpm_syms[i].name = empty_string;
3644 if (STRINGP (color))
3645 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3646 else
3647 xpm_syms[i].value = empty_string;
3651 /* Create a pixmap for the image, either from a file, or from a
3652 string buffer containing data in the same format as an XPM file. */
3653 #ifdef ALLOC_XPM_COLORS
3654 xpm_init_color_cache (f, &attrs);
3655 #endif
3657 specified_file = image_spec_value (img->spec, QCfile, NULL);
3659 #ifdef HAVE_NTGUI
3661 HDC frame_dc = get_frame_dc (f);
3662 hdc = CreateCompatibleDC (frame_dc);
3663 release_frame_dc (f, frame_dc);
3665 #endif /* HAVE_NTGUI */
3667 if (STRINGP (specified_file))
3669 Lisp_Object file = x_find_image_file (specified_file);
3670 if (!STRINGP (file))
3672 image_error ("Cannot find image file `%s'", specified_file);
3673 #ifdef ALLOC_XPM_COLORS
3674 xpm_free_color_cache ();
3675 #endif
3676 SAFE_FREE ();
3677 return 0;
3680 file = ENCODE_FILE (file);
3681 #ifdef HAVE_NTGUI
3682 #ifdef WINDOWSNT
3683 /* FILE is encoded in UTF-8, but image libraries on Windows
3684 support neither UTF-8 nor UTF-16 encoded file names. So we
3685 need to re-encode it in ANSI. */
3686 file = ansi_encode_filename (file);
3687 #endif
3688 /* XpmReadFileToPixmap is not available in the Windows port of
3689 libxpm. But XpmReadFileToImage almost does what we want. */
3690 rc = XpmReadFileToImage (&hdc, SSDATA (file),
3691 &xpm_image, &xpm_mask,
3692 &attrs);
3693 #else
3694 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3695 &img->ximg, &img->mask_img,
3696 &attrs);
3697 #endif /* HAVE_NTGUI */
3699 else
3701 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3702 if (!STRINGP (buffer))
3704 image_error ("Invalid image data `%s'", buffer);
3705 #ifdef ALLOC_XPM_COLORS
3706 xpm_free_color_cache ();
3707 #endif
3708 SAFE_FREE ();
3709 return 0;
3711 #ifdef HAVE_NTGUI
3712 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3713 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3714 rc = XpmCreateImageFromBuffer (&hdc, SSDATA (buffer),
3715 &xpm_image, &xpm_mask,
3716 &attrs);
3717 #else
3718 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3719 &img->ximg, &img->mask_img,
3720 &attrs);
3721 #endif /* HAVE_NTGUI */
3724 #ifdef USE_CAIRO
3725 // Load very specific Xpm:s.
3726 if (rc == XpmSuccess
3727 && img->ximg->format == ZPixmap
3728 && img->ximg->bits_per_pixel == 32
3729 && (! img->mask_img || img->mask_img->bits_per_pixel == 1))
3731 int width = img->ximg->width;
3732 int height = img->ximg->height;
3733 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
3734 int i;
3735 uint32_t *od = (uint32_t *)data;
3736 uint32_t *id = (uint32_t *)img->ximg->data;
3737 char *mid = img->mask_img ? img->mask_img->data : 0;
3738 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
3740 for (i = 0; i < height; ++i)
3742 int k;
3743 for (k = 0; k < width; ++k)
3745 int idx = i * img->ximg->bytes_per_line/4 + k;
3746 int maskidx = mid ? i * img->mask_img->bytes_per_line + k/8 : 0;
3747 int mask = mid ? mid[maskidx] & (1 << (k % 8)) : 1;
3749 if (mask) od[idx] = id[idx] + 0xff000000; // ff => full alpha
3750 else od[idx] = bgcolor;
3754 create_cairo_image_surface (img, data, width, height);
3756 else
3758 rc = XpmFileInvalid;
3759 x_clear_image (f, img);
3761 #else
3762 #ifdef HAVE_X_WINDOWS
3763 if (rc == XpmSuccess)
3765 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3766 img->ximg->width, img->ximg->height,
3767 img->ximg->depth);
3768 if (img->pixmap == NO_PIXMAP)
3770 x_clear_image (f, img);
3771 rc = XpmNoMemory;
3773 else if (img->mask_img)
3775 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3776 img->mask_img->width,
3777 img->mask_img->height,
3778 img->mask_img->depth);
3779 if (img->mask == NO_PIXMAP)
3781 x_clear_image (f, img);
3782 rc = XpmNoMemory;
3786 #endif
3787 #endif /* ! USE_CAIRO */
3789 if (rc == XpmSuccess)
3791 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3792 img->colors = colors_in_color_table (&img->ncolors);
3793 #else /* not ALLOC_XPM_COLORS */
3794 int i;
3796 #ifdef HAVE_NTGUI
3797 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3798 plus some duplicate attributes. */
3799 if (xpm_image && xpm_image->bitmap)
3801 img->pixmap = xpm_image->bitmap;
3802 /* XImageFree in libXpm frees XImage struct without destroying
3803 the bitmap, which is what we want. */
3804 XImageFree (xpm_image);
3806 if (xpm_mask && xpm_mask->bitmap)
3808 /* The mask appears to be inverted compared with what we expect.
3809 TODO: invert our expectations. See other places where we
3810 have to invert bits because our idea of masks is backwards. */
3811 HGDIOBJ old_obj;
3812 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3814 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3815 SelectObject (hdc, old_obj);
3817 img->mask = xpm_mask->bitmap;
3818 XImageFree (xpm_mask);
3819 DeleteDC (hdc);
3822 DeleteDC (hdc);
3823 #endif /* HAVE_NTGUI */
3825 /* Remember allocated colors. */
3826 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3827 img->ncolors = attrs.nalloc_pixels;
3828 for (i = 0; i < attrs.nalloc_pixels; ++i)
3830 img->colors[i] = attrs.alloc_pixels[i];
3831 #ifdef DEBUG_X_COLORS
3832 register_color (img->colors[i]);
3833 #endif
3835 #endif /* not ALLOC_XPM_COLORS */
3837 img->width = attrs.width;
3838 img->height = attrs.height;
3839 eassert (img->width > 0 && img->height > 0);
3841 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3842 XpmFreeAttributes (&attrs);
3844 #ifdef HAVE_X_WINDOWS
3845 /* Maybe fill in the background field while we have ximg handy. */
3846 IMAGE_BACKGROUND (img, f, img->ximg);
3847 if (img->mask_img)
3848 /* Fill in the background_transparent field while we have the
3849 mask handy. */
3850 image_background_transparent (img, f, img->mask_img);
3851 #endif
3853 else
3855 #ifdef HAVE_NTGUI
3856 DeleteDC (hdc);
3857 #endif /* HAVE_NTGUI */
3859 switch (rc)
3861 case XpmOpenFailed:
3862 image_error ("Error opening XPM file (%s)", img->spec);
3863 break;
3865 case XpmFileInvalid:
3866 image_error ("Invalid XPM file (%s)", img->spec);
3867 break;
3869 case XpmNoMemory:
3870 image_error ("Out of memory (%s)", img->spec);
3871 break;
3873 case XpmColorFailed:
3874 image_error ("Color allocation error (%s)", img->spec);
3875 break;
3877 default:
3878 image_error ("Unknown error (%s)", img->spec);
3879 break;
3883 #ifdef ALLOC_XPM_COLORS
3884 xpm_free_color_cache ();
3885 #endif
3886 SAFE_FREE ();
3887 return rc == XpmSuccess;
3890 #endif /* HAVE_XPM */
3892 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3894 /* XPM support functions for NS where libxpm is not available.
3895 Only XPM version 3 (without any extensions) is supported. */
3897 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3898 int, Lisp_Object);
3899 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3900 const unsigned char *, int);
3901 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3902 int, Lisp_Object);
3903 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3904 const unsigned char *, int);
3906 /* Tokens returned from xpm_scan. */
3908 enum xpm_token
3910 XPM_TK_IDENT = 256,
3911 XPM_TK_STRING,
3912 XPM_TK_EOF
3915 /* Scan an XPM data and return a character (< 256) or a token defined
3916 by enum xpm_token above. *S and END are the start (inclusive) and
3917 the end (exclusive) addresses of the data, respectively. Advance
3918 *S while scanning. If token is either XPM_TK_IDENT or
3919 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3920 length of the corresponding token, respectively. */
3922 static int
3923 xpm_scan (const unsigned char **s,
3924 const unsigned char *end,
3925 const unsigned char **beg,
3926 ptrdiff_t *len)
3928 int c;
3930 while (*s < end)
3932 /* Skip white-space. */
3933 while (*s < end && (c = *(*s)++, c_isspace (c)))
3936 /* gnus-pointer.xpm uses '-' in its identifier.
3937 sb-dir-plus.xpm uses '+' in its identifier. */
3938 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3940 *beg = *s - 1;
3941 while (*s < end
3942 && (c = **s, c_isalnum (c)
3943 || c == '_' || c == '-' || c == '+'))
3944 ++*s;
3945 *len = *s - *beg;
3946 return XPM_TK_IDENT;
3948 else if (c == '"')
3950 *beg = *s;
3951 while (*s < end && **s != '"')
3952 ++*s;
3953 *len = *s - *beg;
3954 if (*s < end)
3955 ++*s;
3956 return XPM_TK_STRING;
3958 else if (c == '/')
3960 if (*s < end && **s == '*')
3962 /* C-style comment. */
3963 ++*s;
3966 while (*s < end && *(*s)++ != '*')
3969 while (*s < end && **s != '/');
3970 if (*s < end)
3971 ++*s;
3973 else
3974 return c;
3976 else
3977 return c;
3980 return XPM_TK_EOF;
3983 /* Functions for color table lookup in XPM data. A key is a string
3984 specifying the color of each pixel in XPM data. A value is either
3985 an integer that specifies a pixel color, Qt that specifies
3986 transparency, or Qnil for the unspecified color. If the length of
3987 the key string is one, a vector is used as a table. Otherwise, a
3988 hash table is used. */
3990 static Lisp_Object
3991 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3992 const unsigned char *,
3993 int,
3994 Lisp_Object),
3995 Lisp_Object (**get_func) (Lisp_Object,
3996 const unsigned char *,
3997 int))
3999 *put_func = xpm_put_color_table_v;
4000 *get_func = xpm_get_color_table_v;
4001 return Fmake_vector (make_number (256), Qnil);
4004 static void
4005 xpm_put_color_table_v (Lisp_Object color_table,
4006 const unsigned char *chars_start,
4007 int chars_len,
4008 Lisp_Object color)
4010 ASET (color_table, *chars_start, color);
4013 static Lisp_Object
4014 xpm_get_color_table_v (Lisp_Object color_table,
4015 const unsigned char *chars_start,
4016 int chars_len)
4018 return AREF (color_table, *chars_start);
4021 static Lisp_Object
4022 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
4023 const unsigned char *,
4024 int,
4025 Lisp_Object),
4026 Lisp_Object (**get_func) (Lisp_Object,
4027 const unsigned char *,
4028 int))
4030 *put_func = xpm_put_color_table_h;
4031 *get_func = xpm_get_color_table_h;
4032 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
4033 make_float (DEFAULT_REHASH_SIZE),
4034 make_float (DEFAULT_REHASH_THRESHOLD),
4035 Qnil);
4038 static void
4039 xpm_put_color_table_h (Lisp_Object color_table,
4040 const unsigned char *chars_start,
4041 int chars_len,
4042 Lisp_Object color)
4044 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4045 EMACS_UINT hash_code;
4046 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4048 hash_lookup (table, chars, &hash_code);
4049 hash_put (table, chars, color, hash_code);
4052 static Lisp_Object
4053 xpm_get_color_table_h (Lisp_Object color_table,
4054 const unsigned char *chars_start,
4055 int chars_len)
4057 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4058 ptrdiff_t i =
4059 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
4061 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4064 enum xpm_color_key {
4065 XPM_COLOR_KEY_S,
4066 XPM_COLOR_KEY_M,
4067 XPM_COLOR_KEY_G4,
4068 XPM_COLOR_KEY_G,
4069 XPM_COLOR_KEY_C
4072 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4074 static int
4075 xpm_str_to_color_key (const char *s)
4077 int i;
4079 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
4080 if (strcmp (xpm_color_key_strings[i], s) == 0)
4081 return i;
4082 return -1;
4085 static bool
4086 xpm_load_image (struct frame *f,
4087 struct image *img,
4088 const unsigned char *contents,
4089 const unsigned char *end)
4091 const unsigned char *s = contents, *beg, *str;
4092 unsigned char buffer[BUFSIZ];
4093 int width, height, x, y;
4094 int num_colors, chars_per_pixel;
4095 ptrdiff_t len;
4096 int LA1;
4097 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4098 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
4099 Lisp_Object frame, color_symbols, color_table;
4100 int best_key;
4101 bool have_mask = false;
4102 XImagePtr ximg = NULL, mask_img = NULL;
4104 #define match() \
4105 LA1 = xpm_scan (&s, end, &beg, &len)
4107 #define expect(TOKEN) \
4108 do \
4110 if (LA1 != (TOKEN)) \
4111 goto failure; \
4112 match (); \
4114 while (0)
4116 #define expect_ident(IDENT) \
4117 if (LA1 == XPM_TK_IDENT \
4118 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4119 match (); \
4120 else \
4121 goto failure
4123 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4124 goto failure;
4125 s += 9;
4126 match ();
4127 expect_ident ("static");
4128 expect_ident ("char");
4129 expect ('*');
4130 expect (XPM_TK_IDENT);
4131 expect ('[');
4132 expect (']');
4133 expect ('=');
4134 expect ('{');
4135 expect (XPM_TK_STRING);
4136 if (len >= BUFSIZ)
4137 goto failure;
4138 memcpy (buffer, beg, len);
4139 buffer[len] = '\0';
4140 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4141 &num_colors, &chars_per_pixel) != 4
4142 || width <= 0 || height <= 0
4143 || num_colors <= 0 || chars_per_pixel <= 0)
4144 goto failure;
4146 if (!check_image_size (f, width, height))
4148 image_size_error ();
4149 goto failure;
4152 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4153 #ifndef HAVE_NS
4154 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4155 &mask_img, 1)
4156 #endif
4159 image_error ("Image too large");
4160 goto failure;
4163 expect (',');
4165 XSETFRAME (frame, f);
4166 if (!NILP (Fxw_display_color_p (frame)))
4167 best_key = XPM_COLOR_KEY_C;
4168 else if (!NILP (Fx_display_grayscale_p (frame)))
4169 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4170 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4171 else
4172 best_key = XPM_COLOR_KEY_M;
4174 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4175 if (chars_per_pixel == 1)
4176 color_table = xpm_make_color_table_v (&put_color_table,
4177 &get_color_table);
4178 else
4179 color_table = xpm_make_color_table_h (&put_color_table,
4180 &get_color_table);
4182 while (num_colors-- > 0)
4184 char *color, *max_color;
4185 int key, next_key, max_key = 0;
4186 Lisp_Object symbol_color = Qnil, color_val;
4187 XColor cdef;
4189 expect (XPM_TK_STRING);
4190 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4191 goto failure;
4192 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4193 buffer[len - chars_per_pixel] = '\0';
4195 str = strtok (buffer, " \t");
4196 if (str == NULL)
4197 goto failure;
4198 key = xpm_str_to_color_key (str);
4199 if (key < 0)
4200 goto failure;
4203 color = strtok (NULL, " \t");
4204 if (color == NULL)
4205 goto failure;
4207 while ((str = strtok (NULL, " \t")) != NULL)
4209 next_key = xpm_str_to_color_key (str);
4210 if (next_key >= 0)
4211 break;
4212 color[strlen (color)] = ' ';
4215 if (key == XPM_COLOR_KEY_S)
4217 if (NILP (symbol_color))
4218 symbol_color = build_string (color);
4220 else if (max_key < key && key <= best_key)
4222 max_key = key;
4223 max_color = color;
4225 key = next_key;
4227 while (str);
4229 color_val = Qnil;
4230 if (!NILP (color_symbols) && !NILP (symbol_color))
4232 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4234 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4236 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4237 color_val = Qt;
4238 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4239 &cdef, 0))
4240 color_val = make_number (cdef.pixel);
4243 if (NILP (color_val) && max_key > 0)
4245 if (xstrcasecmp (max_color, "None") == 0)
4246 color_val = Qt;
4247 else if (x_defined_color (f, max_color, &cdef, 0))
4248 color_val = make_number (cdef.pixel);
4250 if (!NILP (color_val))
4251 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4253 expect (',');
4256 for (y = 0; y < height; y++)
4258 expect (XPM_TK_STRING);
4259 str = beg;
4260 if (len < width * chars_per_pixel)
4261 goto failure;
4262 for (x = 0; x < width; x++, str += chars_per_pixel)
4264 Lisp_Object color_val =
4265 (*get_color_table) (color_table, str, chars_per_pixel);
4267 XPutPixel (ximg, x, y,
4268 (INTEGERP (color_val) ? XINT (color_val)
4269 : FRAME_FOREGROUND_PIXEL (f)));
4270 #ifndef HAVE_NS
4271 XPutPixel (mask_img, x, y,
4272 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4273 : (have_mask = true, PIX_MASK_RETAIN)));
4274 #else
4275 if (EQ (color_val, Qt))
4276 ns_set_alpha (ximg, x, y, 0);
4277 #endif
4279 if (y + 1 < height)
4280 expect (',');
4283 img->width = width;
4284 img->height = height;
4286 /* Maybe fill in the background field while we have ximg handy. */
4287 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4288 IMAGE_BACKGROUND (img, f, ximg);
4290 image_put_x_image (f, img, ximg, 0);
4291 #ifndef HAVE_NS
4292 if (have_mask)
4294 /* Fill in the background_transparent field while we have the
4295 mask handy. */
4296 image_background_transparent (img, f, mask_img);
4298 image_put_x_image (f, img, mask_img, 1);
4300 else
4302 x_destroy_x_image (mask_img);
4303 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4305 #endif
4306 return 1;
4308 failure:
4309 image_error ("Invalid XPM file (%s)", img->spec);
4310 x_destroy_x_image (ximg);
4311 x_destroy_x_image (mask_img);
4312 x_clear_image (f, img);
4313 return 0;
4315 #undef match
4316 #undef expect
4317 #undef expect_ident
4320 static bool
4321 xpm_load (struct frame *f,
4322 struct image *img)
4324 bool success_p = 0;
4325 Lisp_Object file_name;
4327 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4328 file_name = image_spec_value (img->spec, QCfile, NULL);
4329 if (STRINGP (file_name))
4331 int fd;
4332 Lisp_Object file = x_find_image_fd (file_name, &fd);
4333 if (!STRINGP (file))
4335 image_error ("Cannot find image file `%s'", file_name);
4336 return 0;
4339 ptrdiff_t size;
4340 unsigned char *contents = slurp_file (fd, &size);
4341 if (contents == NULL)
4343 image_error ("Error loading XPM image `%s'", file);
4344 return 0;
4347 success_p = xpm_load_image (f, img, contents, contents + size);
4348 xfree (contents);
4350 else
4352 Lisp_Object data;
4354 data = image_spec_value (img->spec, QCdata, NULL);
4355 if (!STRINGP (data))
4357 image_error ("Invalid image data `%s'", data);
4358 return 0;
4360 success_p = xpm_load_image (f, img, SDATA (data),
4361 SDATA (data) + SBYTES (data));
4364 return success_p;
4367 #endif /* HAVE_NS && !HAVE_XPM */
4371 /***********************************************************************
4372 Color table
4373 ***********************************************************************/
4375 #ifdef COLOR_TABLE_SUPPORT
4377 /* An entry in the color table mapping an RGB color to a pixel color. */
4379 struct ct_color
4381 int r, g, b;
4382 unsigned long pixel;
4384 /* Next in color table collision list. */
4385 struct ct_color *next;
4388 /* The bucket vector size to use. Must be prime. */
4390 #define CT_SIZE 101
4392 /* Value is a hash of the RGB color given by R, G, and B. */
4394 static unsigned
4395 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4397 return (r << 16) ^ (g << 8) ^ b;
4400 /* The color hash table. */
4402 static struct ct_color **ct_table;
4404 /* Number of entries in the color table. */
4406 static int ct_colors_allocated;
4407 enum
4409 ct_colors_allocated_max =
4410 min (INT_MAX,
4411 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4414 /* Initialize the color table. */
4416 static void
4417 init_color_table (void)
4419 int size = CT_SIZE * sizeof (*ct_table);
4420 ct_table = xzalloc (size);
4421 ct_colors_allocated = 0;
4425 /* Free memory associated with the color table. */
4427 static void
4428 free_color_table (void)
4430 int i;
4431 struct ct_color *p, *next;
4433 for (i = 0; i < CT_SIZE; ++i)
4434 for (p = ct_table[i]; p; p = next)
4436 next = p->next;
4437 xfree (p);
4440 xfree (ct_table);
4441 ct_table = NULL;
4445 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4446 entry for that color already is in the color table, return the
4447 pixel color of that entry. Otherwise, allocate a new color for R,
4448 G, B, and make an entry in the color table. */
4450 static unsigned long
4451 lookup_rgb_color (struct frame *f, int r, int g, int b)
4453 unsigned hash = ct_hash_rgb (r, g, b);
4454 int i = hash % CT_SIZE;
4455 struct ct_color *p;
4456 Display_Info *dpyinfo;
4458 /* Handle TrueColor visuals specially, which improves performance by
4459 two orders of magnitude. Freeing colors on TrueColor visuals is
4460 a nop, and pixel colors specify RGB values directly. See also
4461 the Xlib spec, chapter 3.1. */
4462 dpyinfo = FRAME_DISPLAY_INFO (f);
4463 if (dpyinfo->red_bits > 0)
4465 /* Apply gamma-correction like normal color allocation does. */
4466 if (f->gamma)
4468 XColor color;
4469 color.red = r, color.green = g, color.blue = b;
4470 gamma_correct (f, &color);
4471 r = color.red, g = color.green, b = color.blue;
4474 return x_make_truecolor_pixel (dpyinfo, r, g, b);
4477 for (p = ct_table[i]; p; p = p->next)
4478 if (p->r == r && p->g == g && p->b == b)
4479 break;
4481 if (p == NULL)
4484 #ifdef HAVE_X_WINDOWS
4485 XColor color;
4486 Colormap cmap;
4487 bool rc;
4488 #else
4489 COLORREF color;
4490 #endif
4492 if (ct_colors_allocated_max <= ct_colors_allocated)
4493 return FRAME_FOREGROUND_PIXEL (f);
4495 #ifdef HAVE_X_WINDOWS
4496 color.red = r;
4497 color.green = g;
4498 color.blue = b;
4500 cmap = FRAME_X_COLORMAP (f);
4501 rc = x_alloc_nearest_color (f, cmap, &color);
4502 if (rc)
4504 ++ct_colors_allocated;
4505 p = xmalloc (sizeof *p);
4506 p->r = r;
4507 p->g = g;
4508 p->b = b;
4509 p->pixel = color.pixel;
4510 p->next = ct_table[i];
4511 ct_table[i] = p;
4513 else
4514 return FRAME_FOREGROUND_PIXEL (f);
4516 #else
4517 #ifdef HAVE_NTGUI
4518 color = PALETTERGB (r, g, b);
4519 #else
4520 color = RGB_TO_ULONG (r, g, b);
4521 #endif /* HAVE_NTGUI */
4522 ++ct_colors_allocated;
4523 p = xmalloc (sizeof *p);
4524 p->r = r;
4525 p->g = g;
4526 p->b = b;
4527 p->pixel = color;
4528 p->next = ct_table[i];
4529 ct_table[i] = p;
4530 #endif /* HAVE_X_WINDOWS */
4534 return p->pixel;
4538 /* Look up pixel color PIXEL which is used on frame F in the color
4539 table. If not already present, allocate it. Value is PIXEL. */
4541 static unsigned long
4542 lookup_pixel_color (struct frame *f, unsigned long pixel)
4544 int i = pixel % CT_SIZE;
4545 struct ct_color *p;
4547 for (p = ct_table[i]; p; p = p->next)
4548 if (p->pixel == pixel)
4549 break;
4551 if (p == NULL)
4553 XColor color;
4554 Colormap cmap;
4555 bool rc;
4557 if (ct_colors_allocated >= ct_colors_allocated_max)
4558 return FRAME_FOREGROUND_PIXEL (f);
4560 #ifdef HAVE_X_WINDOWS
4561 cmap = FRAME_X_COLORMAP (f);
4562 color.pixel = pixel;
4563 x_query_color (f, &color);
4564 rc = x_alloc_nearest_color (f, cmap, &color);
4565 #else
4566 block_input ();
4567 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4568 color.pixel = pixel;
4569 XQueryColor (NULL, cmap, &color);
4570 rc = x_alloc_nearest_color (f, cmap, &color);
4571 unblock_input ();
4572 #endif /* HAVE_X_WINDOWS */
4574 if (rc)
4576 ++ct_colors_allocated;
4578 p = xmalloc (sizeof *p);
4579 p->r = color.red;
4580 p->g = color.green;
4581 p->b = color.blue;
4582 p->pixel = pixel;
4583 p->next = ct_table[i];
4584 ct_table[i] = p;
4586 else
4587 return FRAME_FOREGROUND_PIXEL (f);
4589 return p->pixel;
4593 /* Value is a vector of all pixel colors contained in the color table,
4594 allocated via xmalloc. Set *N to the number of colors. */
4596 static unsigned long *
4597 colors_in_color_table (int *n)
4599 int i, j;
4600 struct ct_color *p;
4601 unsigned long *colors;
4603 if (ct_colors_allocated == 0)
4605 *n = 0;
4606 colors = NULL;
4608 else
4610 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4611 *n = ct_colors_allocated;
4613 for (i = j = 0; i < CT_SIZE; ++i)
4614 for (p = ct_table[i]; p; p = p->next)
4615 colors[j++] = p->pixel;
4618 return colors;
4621 #else /* COLOR_TABLE_SUPPORT */
4623 static unsigned long
4624 lookup_rgb_color (struct frame *f, int r, int g, int b)
4626 #ifdef HAVE_NTGUI
4627 return PALETTERGB (r >> 8, g >> 8, b >> 8);
4628 #elif defined HAVE_NS
4629 return RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4630 #else
4631 xsignal1 (Qfile_error,
4632 build_string ("This Emacs mishandles this image file type"));
4633 #endif
4636 static void
4637 init_color_table (void)
4640 #endif /* COLOR_TABLE_SUPPORT */
4643 /***********************************************************************
4644 Algorithms
4645 ***********************************************************************/
4647 /* Edge detection matrices for different edge-detection
4648 strategies. */
4650 static int emboss_matrix[9] = {
4651 /* x - 1 x x + 1 */
4652 2, -1, 0, /* y - 1 */
4653 -1, 0, 1, /* y */
4654 0, 1, -2 /* y + 1 */
4657 static int laplace_matrix[9] = {
4658 /* x - 1 x x + 1 */
4659 1, 0, 0, /* y - 1 */
4660 0, 0, 0, /* y */
4661 0, 0, -1 /* y + 1 */
4664 /* Value is the intensity of the color whose red/green/blue values
4665 are R, G, and B. */
4667 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4670 /* On frame F, return an array of XColor structures describing image
4671 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4672 means also fill the red/green/blue members of the XColor
4673 structures. Value is a pointer to the array of XColors structures,
4674 allocated with xmalloc; it must be freed by the caller. */
4676 static XColor *
4677 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4679 int x, y;
4680 XColor *colors, *p;
4681 XImagePtr_or_DC ximg;
4682 ptrdiff_t nbytes;
4683 #ifdef HAVE_NTGUI
4684 HGDIOBJ prev;
4685 #endif /* HAVE_NTGUI */
4687 if (INT_MULTIPLY_WRAPV (sizeof *colors, img->width, &nbytes)
4688 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes)
4689 || SIZE_MAX < nbytes)
4690 memory_full (SIZE_MAX);
4691 colors = xmalloc (nbytes);
4693 /* Get the X image or create a memory device context for IMG. */
4694 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4696 /* Fill the `pixel' members of the XColor array. I wished there
4697 were an easy and portable way to circumvent XGetPixel. */
4698 p = colors;
4699 for (y = 0; y < img->height; ++y)
4701 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4702 XColor *row = p;
4703 for (x = 0; x < img->width; ++x, ++p)
4704 p->pixel = GET_PIXEL (ximg, x, y);
4705 if (rgb_p)
4706 x_query_colors (f, row, img->width);
4708 #else
4710 for (x = 0; x < img->width; ++x, ++p)
4712 /* W32_TODO: palette support needed here? */
4713 p->pixel = GET_PIXEL (ximg, x, y);
4714 if (rgb_p)
4716 p->red = RED16_FROM_ULONG (p->pixel);
4717 p->green = GREEN16_FROM_ULONG (p->pixel);
4718 p->blue = BLUE16_FROM_ULONG (p->pixel);
4721 #endif /* HAVE_X_WINDOWS */
4724 image_unget_x_image_or_dc (img, 0, ximg, prev);
4726 return colors;
4729 #ifdef HAVE_NTGUI
4731 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4732 created with CreateDIBSection, with the pointer to the bit values
4733 stored in ximg->data. */
4735 static void
4736 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4738 int width = ximg->info.bmiHeader.biWidth;
4739 unsigned char * pixel;
4741 /* True color images. */
4742 if (ximg->info.bmiHeader.biBitCount == 24)
4744 int rowbytes = width * 3;
4745 /* Ensure scanlines are aligned on 4 byte boundaries. */
4746 if (rowbytes % 4)
4747 rowbytes += 4 - (rowbytes % 4);
4749 pixel = ximg->data + y * rowbytes + x * 3;
4750 /* Windows bitmaps are in BGR order. */
4751 *pixel = GetBValue (color);
4752 *(pixel + 1) = GetGValue (color);
4753 *(pixel + 2) = GetRValue (color);
4755 /* Monochrome images. */
4756 else if (ximg->info.bmiHeader.biBitCount == 1)
4758 int rowbytes = width / 8;
4759 /* Ensure scanlines are aligned on 4 byte boundaries. */
4760 if (rowbytes % 4)
4761 rowbytes += 4 - (rowbytes % 4);
4762 pixel = ximg->data + y * rowbytes + x / 8;
4763 /* Filter out palette info. */
4764 if (color & 0x00ffffff)
4765 *pixel = *pixel | (1 << x % 8);
4766 else
4767 *pixel = *pixel & ~(1 << x % 8);
4769 else
4770 image_error ("XPutPixel: palette image not supported");
4773 #endif /* HAVE_NTGUI */
4775 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4776 RGB members are set. F is the frame on which this all happens.
4777 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4779 static void
4780 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4782 int x, y;
4783 XImagePtr oimg = NULL;
4784 XColor *p;
4786 init_color_table ();
4788 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4789 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4790 &oimg, 0);
4791 p = colors;
4792 for (y = 0; y < img->height; ++y)
4793 for (x = 0; x < img->width; ++x, ++p)
4795 unsigned long pixel;
4796 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4797 XPutPixel (oimg, x, y, pixel);
4800 xfree (colors);
4802 image_put_x_image (f, img, oimg, 0);
4803 #ifdef COLOR_TABLE_SUPPORT
4804 img->colors = colors_in_color_table (&img->ncolors);
4805 free_color_table ();
4806 #endif /* COLOR_TABLE_SUPPORT */
4810 /* On frame F, perform edge-detection on image IMG.
4812 MATRIX is a nine-element array specifying the transformation
4813 matrix. See emboss_matrix for an example.
4815 COLOR_ADJUST is a color adjustment added to each pixel of the
4816 outgoing image. */
4818 static void
4819 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4821 XColor *colors = x_to_xcolors (f, img, 1);
4822 XColor *new, *p;
4823 int x, y, i, sum;
4824 ptrdiff_t nbytes;
4826 for (i = sum = 0; i < 9; ++i)
4827 sum += eabs (matrix[i]);
4829 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4831 if (INT_MULTIPLY_WRAPV (sizeof *new, img->width, &nbytes)
4832 || INT_MULTIPLY_WRAPV (img->height, nbytes, &nbytes))
4833 memory_full (SIZE_MAX);
4834 new = xmalloc (nbytes);
4836 for (y = 0; y < img->height; ++y)
4838 p = COLOR (new, 0, y);
4839 p->red = p->green = p->blue = 0xffff/2;
4840 p = COLOR (new, img->width - 1, y);
4841 p->red = p->green = p->blue = 0xffff/2;
4844 for (x = 1; x < img->width - 1; ++x)
4846 p = COLOR (new, x, 0);
4847 p->red = p->green = p->blue = 0xffff/2;
4848 p = COLOR (new, x, img->height - 1);
4849 p->red = p->green = p->blue = 0xffff/2;
4852 for (y = 1; y < img->height - 1; ++y)
4854 p = COLOR (new, 1, y);
4856 for (x = 1; x < img->width - 1; ++x, ++p)
4858 int r, g, b, yy, xx;
4860 r = g = b = i = 0;
4861 for (yy = y - 1; yy < y + 2; ++yy)
4862 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4863 if (matrix[i])
4865 XColor *t = COLOR (colors, xx, yy);
4866 r += matrix[i] * t->red;
4867 g += matrix[i] * t->green;
4868 b += matrix[i] * t->blue;
4871 r = (r / sum + color_adjust) & 0xffff;
4872 g = (g / sum + color_adjust) & 0xffff;
4873 b = (b / sum + color_adjust) & 0xffff;
4874 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4878 xfree (colors);
4879 x_from_xcolors (f, img, new);
4881 #undef COLOR
4885 /* Perform the pre-defined `emboss' edge-detection on image IMG
4886 on frame F. */
4888 static void
4889 x_emboss (struct frame *f, struct image *img)
4891 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4895 /* Transform image IMG which is used on frame F with a Laplace
4896 edge-detection algorithm. The result is an image that can be used
4897 to draw disabled buttons, for example. */
4899 static void
4900 x_laplace (struct frame *f, struct image *img)
4902 x_detect_edges (f, img, laplace_matrix, 45000);
4906 /* Perform edge-detection on image IMG on frame F, with specified
4907 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4909 MATRIX must be either
4911 - a list of at least 9 numbers in row-major form
4912 - a vector of at least 9 numbers
4914 COLOR_ADJUST nil means use a default; otherwise it must be a
4915 number. */
4917 static void
4918 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4919 Lisp_Object color_adjust)
4921 int i = 0;
4922 int trans[9];
4924 if (CONSP (matrix))
4926 for (i = 0;
4927 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4928 ++i, matrix = XCDR (matrix))
4929 trans[i] = XFLOATINT (XCAR (matrix));
4931 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4933 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4934 trans[i] = XFLOATINT (AREF (matrix, i));
4937 if (NILP (color_adjust))
4938 color_adjust = make_number (0xffff / 2);
4940 if (i == 9 && NUMBERP (color_adjust))
4941 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4945 /* Transform image IMG on frame F so that it looks disabled. */
4947 static void
4948 x_disable_image (struct frame *f, struct image *img)
4950 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4951 #ifdef HAVE_NTGUI
4952 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4953 #else
4954 int n_planes = dpyinfo->n_planes;
4955 #endif /* HAVE_NTGUI */
4957 if (n_planes >= 2)
4959 /* Color (or grayscale). Convert to gray, and equalize. Just
4960 drawing such images with a stipple can look very odd, so
4961 we're using this method instead. */
4962 XColor *colors = x_to_xcolors (f, img, 1);
4963 XColor *p, *end;
4964 const int h = 15000;
4965 const int l = 30000;
4967 for (p = colors, end = colors + img->width * img->height;
4968 p < end;
4969 ++p)
4971 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4972 int i2 = (0xffff - h - l) * i / 0xffff + l;
4973 p->red = p->green = p->blue = i2;
4976 x_from_xcolors (f, img, colors);
4979 /* Draw a cross over the disabled image, if we must or if we
4980 should. */
4981 if (n_planes < 2 || cross_disabled_images)
4983 #ifndef HAVE_NTGUI
4984 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4986 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4988 Display *dpy = FRAME_X_DISPLAY (f);
4989 GC gc;
4991 image_sync_to_pixmaps (f, img);
4992 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4993 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4994 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4995 img->width - 1, img->height - 1);
4996 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4997 img->width - 1, 0);
4998 XFreeGC (dpy, gc);
5000 if (img->mask)
5002 gc = XCreateGC (dpy, img->mask, 0, NULL);
5003 XSetForeground (dpy, gc, MaskForeground (f));
5004 XDrawLine (dpy, img->mask, gc, 0, 0,
5005 img->width - 1, img->height - 1);
5006 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
5007 img->width - 1, 0);
5008 XFreeGC (dpy, gc);
5010 #endif /* !HAVE_NS */
5011 #else
5012 HDC hdc, bmpdc;
5013 HGDIOBJ prev;
5015 hdc = get_frame_dc (f);
5016 bmpdc = CreateCompatibleDC (hdc);
5017 release_frame_dc (f, hdc);
5019 prev = SelectObject (bmpdc, img->pixmap);
5021 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5022 MoveToEx (bmpdc, 0, 0, NULL);
5023 LineTo (bmpdc, img->width - 1, img->height - 1);
5024 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5025 LineTo (bmpdc, img->width - 1, 0);
5027 if (img->mask)
5029 SelectObject (bmpdc, img->mask);
5030 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5031 MoveToEx (bmpdc, 0, 0, NULL);
5032 LineTo (bmpdc, img->width - 1, img->height - 1);
5033 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5034 LineTo (bmpdc, img->width - 1, 0);
5036 SelectObject (bmpdc, prev);
5037 DeleteDC (bmpdc);
5038 #endif /* HAVE_NTGUI */
5043 /* Build a mask for image IMG which is used on frame F. FILE is the
5044 name of an image file, for error messages. HOW determines how to
5045 determine the background color of IMG. If it is a list '(R G B)',
5046 with R, G, and B being integers >= 0, take that as the color of the
5047 background. Otherwise, determine the background color of IMG
5048 heuristically. */
5050 static void
5051 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
5053 XImagePtr_or_DC ximg;
5054 #ifndef HAVE_NTGUI
5055 XImagePtr mask_img;
5056 #else
5057 HGDIOBJ prev;
5058 char *mask_img;
5059 int row_width;
5060 #endif /* HAVE_NTGUI */
5061 int x, y;
5062 bool use_img_background;
5063 unsigned long bg = 0;
5065 if (img->mask)
5066 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
5068 #ifndef HAVE_NTGUI
5069 #ifndef HAVE_NS
5070 /* Create an image and pixmap serving as mask. */
5071 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
5072 &mask_img, 1))
5073 return;
5074 #endif /* !HAVE_NS */
5075 #else
5076 /* Create the bit array serving as mask. */
5077 row_width = (img->width + 7) / 8;
5078 mask_img = xzalloc (row_width * img->height);
5079 #endif /* HAVE_NTGUI */
5081 /* Get the X image or create a memory device context for IMG. */
5082 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
5084 /* Determine the background color of ximg. If HOW is `(R G B)'
5085 take that as color. Otherwise, use the image's background color. */
5086 use_img_background = 1;
5088 if (CONSP (how))
5090 int rgb[3], i;
5092 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5094 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5095 how = XCDR (how);
5098 if (i == 3 && NILP (how))
5100 char color_name[30];
5101 sprintf (color_name, "#%04x%04x%04x",
5102 rgb[0] + 0u, rgb[1] + 0u, rgb[2] + 0u);
5103 bg = (
5104 #ifdef HAVE_NTGUI
5105 0x00ffffff & /* Filter out palette info. */
5106 #endif /* HAVE_NTGUI */
5107 x_alloc_image_color (f, img, build_string (color_name), 0));
5108 use_img_background = 0;
5112 if (use_img_background)
5113 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5115 /* Set all bits in mask_img to 1 whose color in ximg is different
5116 from the background color bg. */
5117 #ifndef HAVE_NTGUI
5118 for (y = 0; y < img->height; ++y)
5119 for (x = 0; x < img->width; ++x)
5120 #ifndef HAVE_NS
5121 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5122 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5123 #else
5124 if (XGetPixel (ximg, x, y) == bg)
5125 ns_set_alpha (ximg, x, y, 0);
5126 #endif /* HAVE_NS */
5127 #ifndef HAVE_NS
5128 /* Fill in the background_transparent field while we have the mask handy. */
5129 image_background_transparent (img, f, mask_img);
5131 /* Put mask_img into the image. */
5132 image_put_x_image (f, img, mask_img, 1);
5133 #endif /* !HAVE_NS */
5134 #else
5135 for (y = 0; y < img->height; ++y)
5136 for (x = 0; x < img->width; ++x)
5138 COLORREF p = GetPixel (ximg, x, y);
5139 if (p != bg)
5140 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5143 /* Create the mask image. */
5144 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5145 mask_img);
5146 /* Fill in the background_transparent field while we have the mask handy. */
5147 SelectObject (ximg, img->mask);
5148 image_background_transparent (img, f, ximg);
5150 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5151 xfree (mask_img);
5152 #endif /* HAVE_NTGUI */
5154 image_unget_x_image_or_dc (img, 0, ximg, prev);
5158 /***********************************************************************
5159 PBM (mono, gray, color)
5160 ***********************************************************************/
5162 static bool pbm_image_p (Lisp_Object object);
5163 static bool pbm_load (struct frame *f, struct image *img);
5165 /* Indices of image specification fields in gs_format, below. */
5167 enum pbm_keyword_index
5169 PBM_TYPE,
5170 PBM_FILE,
5171 PBM_DATA,
5172 PBM_ASCENT,
5173 PBM_MARGIN,
5174 PBM_RELIEF,
5175 PBM_ALGORITHM,
5176 PBM_HEURISTIC_MASK,
5177 PBM_MASK,
5178 PBM_FOREGROUND,
5179 PBM_BACKGROUND,
5180 PBM_LAST
5183 /* Vector of image_keyword structures describing the format
5184 of valid user-defined image specifications. */
5186 static const struct image_keyword pbm_format[PBM_LAST] =
5188 {":type", IMAGE_SYMBOL_VALUE, 1},
5189 {":file", IMAGE_STRING_VALUE, 0},
5190 {":data", IMAGE_STRING_VALUE, 0},
5191 {":ascent", IMAGE_ASCENT_VALUE, 0},
5192 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5193 {":relief", IMAGE_INTEGER_VALUE, 0},
5194 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5195 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5196 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5197 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5198 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5201 /* Structure describing the image type `pbm'. */
5203 static struct image_type pbm_type =
5205 SYMBOL_INDEX (Qpbm),
5206 pbm_image_p,
5207 pbm_load,
5208 x_clear_image,
5209 NULL,
5210 NULL
5214 /* Return true if OBJECT is a valid PBM image specification. */
5216 static bool
5217 pbm_image_p (Lisp_Object object)
5219 struct image_keyword fmt[PBM_LAST];
5221 memcpy (fmt, pbm_format, sizeof fmt);
5223 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5224 return 0;
5226 /* Must specify either :data or :file. */
5227 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5231 /* Get next char skipping comments in Netpbm header. Returns -1 at
5232 end of input. */
5234 static int
5235 pbm_next_char (unsigned char **s, unsigned char *end)
5237 int c = -1;
5239 while (*s < end && (c = *(*s)++, c == '#'))
5241 /* Skip to the next line break. */
5242 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5245 c = -1;
5248 return c;
5252 /* Scan a decimal number from *S and return it. Advance *S while
5253 reading the number. END is the end of the string. Value is -1 at
5254 end of input. */
5256 static int
5257 pbm_scan_number (unsigned char **s, unsigned char *end)
5259 int c = 0, val = -1;
5261 /* Skip white-space. */
5262 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5265 if (c_isdigit (c))
5267 /* Read decimal number. */
5268 val = c - '0';
5269 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5270 val = 10 * val + c - '0';
5273 return val;
5277 /* Load PBM image IMG for use on frame F. */
5279 static bool
5280 pbm_load (struct frame *f, struct image *img)
5282 bool raw_p;
5283 int x, y;
5284 int width, height, max_color_idx = 0;
5285 Lisp_Object specified_file;
5286 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5287 unsigned char *contents = NULL;
5288 unsigned char *end, *p;
5289 #ifdef USE_CAIRO
5290 unsigned char *data = 0;
5291 uint32_t *dataptr;
5292 #else
5293 XImagePtr ximg;
5294 #endif
5296 specified_file = image_spec_value (img->spec, QCfile, NULL);
5298 if (STRINGP (specified_file))
5300 int fd;
5301 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5302 if (!STRINGP (file))
5304 image_error ("Cannot find image file `%s'", specified_file);
5305 return 0;
5308 ptrdiff_t size;
5309 contents = slurp_file (fd, &size);
5310 if (contents == NULL)
5312 image_error ("Error reading `%s'", file);
5313 return 0;
5316 p = contents;
5317 end = contents + size;
5319 else
5321 Lisp_Object data;
5322 data = image_spec_value (img->spec, QCdata, NULL);
5323 if (!STRINGP (data))
5325 image_error ("Invalid image data `%s'", data);
5326 return 0;
5328 p = SDATA (data);
5329 end = p + SBYTES (data);
5332 /* Check magic number. */
5333 if (end - p < 2 || *p++ != 'P')
5335 image_error ("Not a PBM image: `%s'", img->spec);
5336 error:
5337 xfree (contents);
5338 img->pixmap = NO_PIXMAP;
5339 return 0;
5342 switch (*p++)
5344 case '1':
5345 raw_p = 0, type = PBM_MONO;
5346 break;
5348 case '2':
5349 raw_p = 0, type = PBM_GRAY;
5350 break;
5352 case '3':
5353 raw_p = 0, type = PBM_COLOR;
5354 break;
5356 case '4':
5357 raw_p = 1, type = PBM_MONO;
5358 break;
5360 case '5':
5361 raw_p = 1, type = PBM_GRAY;
5362 break;
5364 case '6':
5365 raw_p = 1, type = PBM_COLOR;
5366 break;
5368 default:
5369 image_error ("Not a PBM image: `%s'", img->spec);
5370 goto error;
5373 /* Read width, height, maximum color-component. Characters
5374 starting with `#' up to the end of a line are ignored. */
5375 width = pbm_scan_number (&p, end);
5376 height = pbm_scan_number (&p, end);
5378 #ifdef USE_CAIRO
5379 data = (unsigned char *) xmalloc (width * height * 4);
5380 dataptr = (uint32_t *) data;
5381 #endif
5383 if (type != PBM_MONO)
5385 max_color_idx = pbm_scan_number (&p, end);
5386 if (max_color_idx > 65535 || max_color_idx < 0)
5388 image_error ("Unsupported maximum PBM color value");
5389 goto error;
5393 if (!check_image_size (f, width, height))
5395 image_size_error ();
5396 goto error;
5399 #ifndef USE_CAIRO
5400 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5401 goto error;
5402 #endif
5404 /* Initialize the color hash table. */
5405 init_color_table ();
5407 if (type == PBM_MONO)
5409 int c = 0, g;
5410 struct image_keyword fmt[PBM_LAST];
5411 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5412 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5413 #ifdef USE_CAIRO
5414 XColor xfg, xbg;
5415 int fga32, bga32;
5416 #endif
5417 /* Parse the image specification. */
5418 memcpy (fmt, pbm_format, sizeof fmt);
5419 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5421 /* Get foreground and background colors, maybe allocate colors. */
5422 #ifdef USE_CAIRO
5423 if (! fmt[PBM_FOREGROUND].count
5424 || ! STRINGP (fmt[PBM_FOREGROUND].value)
5425 || ! x_defined_color (f, SSDATA (fmt[PBM_FOREGROUND].value), &xfg, 0))
5427 xfg.pixel = fg;
5428 x_query_color (f, &xfg);
5430 fga32 = xcolor_to_argb32 (xfg);
5432 if (! fmt[PBM_BACKGROUND].count
5433 || ! STRINGP (fmt[PBM_BACKGROUND].value)
5434 || ! x_defined_color (f, SSDATA (fmt[PBM_BACKGROUND].value), &xbg, 0))
5436 xbg.pixel = bg;
5437 x_query_color (f, &xbg);
5439 bga32 = xcolor_to_argb32 (xbg);
5440 #else
5441 if (fmt[PBM_FOREGROUND].count
5442 && STRINGP (fmt[PBM_FOREGROUND].value))
5443 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5444 if (fmt[PBM_BACKGROUND].count
5445 && STRINGP (fmt[PBM_BACKGROUND].value))
5447 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5448 img->background = bg;
5449 img->background_valid = 1;
5451 #endif
5453 for (y = 0; y < height; ++y)
5454 for (x = 0; x < width; ++x)
5456 if (raw_p)
5458 if ((x & 7) == 0)
5460 if (p >= end)
5462 #ifdef USE_CAIRO
5463 xfree (data);
5464 #else
5465 x_destroy_x_image (ximg);
5466 #endif
5467 x_clear_image (f, img);
5468 image_error ("Invalid image size in image `%s'",
5469 img->spec);
5470 goto error;
5472 c = *p++;
5474 g = c & 0x80;
5475 c <<= 1;
5477 else
5478 g = pbm_scan_number (&p, end);
5480 #ifdef USE_CAIRO
5481 *dataptr++ = g ? fga32 : bga32;
5482 #else
5483 XPutPixel (ximg, x, y, g ? fg : bg);
5484 #endif
5487 else
5489 int expected_size = height * width;
5490 if (max_color_idx > 255)
5491 expected_size *= 2;
5492 if (type == PBM_COLOR)
5493 expected_size *= 3;
5495 if (raw_p && p + expected_size > end)
5497 #ifdef USE_CAIRO
5498 xfree (data);
5499 #else
5500 x_destroy_x_image (ximg);
5501 #endif
5502 x_clear_image (f, img);
5503 image_error ("Invalid image size in image `%s'", img->spec);
5504 goto error;
5507 for (y = 0; y < height; ++y)
5508 for (x = 0; x < width; ++x)
5510 int r, g, b;
5512 if (type == PBM_GRAY && raw_p)
5514 r = g = b = *p++;
5515 if (max_color_idx > 255)
5516 r = g = b = r * 256 + *p++;
5518 else if (type == PBM_GRAY)
5519 r = g = b = pbm_scan_number (&p, end);
5520 else if (raw_p)
5522 r = *p++;
5523 if (max_color_idx > 255)
5524 r = r * 256 + *p++;
5525 g = *p++;
5526 if (max_color_idx > 255)
5527 g = g * 256 + *p++;
5528 b = *p++;
5529 if (max_color_idx > 255)
5530 b = b * 256 + *p++;
5532 else
5534 r = pbm_scan_number (&p, end);
5535 g = pbm_scan_number (&p, end);
5536 b = pbm_scan_number (&p, end);
5539 if (r < 0 || g < 0 || b < 0)
5541 #ifdef USE_CAIRO
5542 xfree (data);
5543 #else
5544 x_destroy_x_image (ximg);
5545 #endif
5546 image_error ("Invalid pixel value in image `%s'", img->spec);
5547 goto error;
5550 #ifdef USE_CAIRO
5551 r = (double) r * 255 / max_color_idx;
5552 g = (double) g * 255 / max_color_idx;
5553 b = (double) b * 255 / max_color_idx;
5554 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
5555 #else
5556 /* RGB values are now in the range 0..max_color_idx.
5557 Scale this to the range 0..0xffff supported by X. */
5558 r = (double) r * 65535 / max_color_idx;
5559 g = (double) g * 65535 / max_color_idx;
5560 b = (double) b * 65535 / max_color_idx;
5561 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5562 #endif
5566 #ifdef COLOR_TABLE_SUPPORT
5567 /* Store in IMG->colors the colors allocated for the image, and
5568 free the color table. */
5569 img->colors = colors_in_color_table (&img->ncolors);
5570 free_color_table ();
5571 #endif /* COLOR_TABLE_SUPPORT */
5573 img->width = width;
5574 img->height = height;
5576 /* Maybe fill in the background field while we have ximg handy. */
5578 #ifdef USE_CAIRO
5579 create_cairo_image_surface (img, data, width, height);
5580 #else
5581 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5582 /* Casting avoids a GCC warning. */
5583 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5585 /* Put ximg into the image. */
5586 image_put_x_image (f, img, ximg, 0);
5587 #endif
5589 /* X and W32 versions did it here, MAC version above. ++kfs
5590 img->width = width;
5591 img->height = height; */
5593 xfree (contents);
5594 return 1;
5598 /***********************************************************************
5600 ***********************************************************************/
5602 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5604 /* Function prototypes. */
5606 static bool png_image_p (Lisp_Object object);
5607 static bool png_load (struct frame *f, struct image *img);
5609 /* Indices of image specification fields in png_format, below. */
5611 enum png_keyword_index
5613 PNG_TYPE,
5614 PNG_DATA,
5615 PNG_FILE,
5616 PNG_ASCENT,
5617 PNG_MARGIN,
5618 PNG_RELIEF,
5619 PNG_ALGORITHM,
5620 PNG_HEURISTIC_MASK,
5621 PNG_MASK,
5622 PNG_BACKGROUND,
5623 PNG_LAST
5626 /* Vector of image_keyword structures describing the format
5627 of valid user-defined image specifications. */
5629 static const struct image_keyword png_format[PNG_LAST] =
5631 {":type", IMAGE_SYMBOL_VALUE, 1},
5632 {":data", IMAGE_STRING_VALUE, 0},
5633 {":file", IMAGE_STRING_VALUE, 0},
5634 {":ascent", IMAGE_ASCENT_VALUE, 0},
5635 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5636 {":relief", IMAGE_INTEGER_VALUE, 0},
5637 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5638 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5639 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5640 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5643 #if defined HAVE_NTGUI && defined WINDOWSNT
5644 static bool init_png_functions (void);
5645 #else
5646 #define init_png_functions NULL
5647 #endif
5649 /* Structure describing the image type `png'. */
5651 static struct image_type png_type =
5653 SYMBOL_INDEX (Qpng),
5654 png_image_p,
5655 png_load,
5656 x_clear_image,
5657 init_png_functions,
5658 NULL
5661 /* Return true if OBJECT is a valid PNG image specification. */
5663 static bool
5664 png_image_p (Lisp_Object object)
5666 struct image_keyword fmt[PNG_LAST];
5667 memcpy (fmt, png_format, sizeof fmt);
5669 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5670 return 0;
5672 /* Must specify either the :data or :file keyword. */
5673 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5676 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5679 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5681 # ifdef WINDOWSNT
5682 /* PNG library details. */
5684 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5685 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5686 DEF_DLL_FN (png_structp, png_create_read_struct,
5687 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5688 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5689 DEF_DLL_FN (void, png_destroy_read_struct,
5690 (png_structpp, png_infopp, png_infopp));
5691 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5692 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5693 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5694 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5695 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5696 int *, int *, int *, int *, int *));
5697 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5698 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5699 DEF_DLL_FN (void, png_set_expand, (png_structp));
5700 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5701 DEF_DLL_FN (void, png_set_background,
5702 (png_structp, png_color_16p, int, int, double));
5703 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5704 (png_structp, png_infop, png_color_16p *));
5705 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5706 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5707 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5708 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5709 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5710 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5712 # if (PNG_LIBPNG_VER >= 10500)
5713 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5714 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5715 (png_structp, png_longjmp_ptr, size_t));
5716 # endif /* libpng version >= 1.5 */
5718 static bool
5719 init_png_functions (void)
5721 HMODULE library;
5723 if (!(library = w32_delayed_load (Qpng)))
5724 return 0;
5726 LOAD_DLL_FN (library, png_get_io_ptr);
5727 LOAD_DLL_FN (library, png_sig_cmp);
5728 LOAD_DLL_FN (library, png_create_read_struct);
5729 LOAD_DLL_FN (library, png_create_info_struct);
5730 LOAD_DLL_FN (library, png_destroy_read_struct);
5731 LOAD_DLL_FN (library, png_set_read_fn);
5732 LOAD_DLL_FN (library, png_set_sig_bytes);
5733 LOAD_DLL_FN (library, png_read_info);
5734 LOAD_DLL_FN (library, png_get_IHDR);
5735 LOAD_DLL_FN (library, png_get_valid);
5736 LOAD_DLL_FN (library, png_set_strip_16);
5737 LOAD_DLL_FN (library, png_set_expand);
5738 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5739 LOAD_DLL_FN (library, png_set_background);
5740 LOAD_DLL_FN (library, png_get_bKGD);
5741 LOAD_DLL_FN (library, png_read_update_info);
5742 LOAD_DLL_FN (library, png_get_channels);
5743 LOAD_DLL_FN (library, png_get_rowbytes);
5744 LOAD_DLL_FN (library, png_read_image);
5745 LOAD_DLL_FN (library, png_read_end);
5746 LOAD_DLL_FN (library, png_error);
5748 # if (PNG_LIBPNG_VER >= 10500)
5749 LOAD_DLL_FN (library, png_longjmp);
5750 LOAD_DLL_FN (library, png_set_longjmp_fn);
5751 # endif /* libpng version >= 1.5 */
5753 return 1;
5756 # undef png_create_info_struct
5757 # undef png_create_read_struct
5758 # undef png_destroy_read_struct
5759 # undef png_error
5760 # undef png_get_bKGD
5761 # undef png_get_channels
5762 # undef png_get_IHDR
5763 # undef png_get_io_ptr
5764 # undef png_get_rowbytes
5765 # undef png_get_valid
5766 # undef png_longjmp
5767 # undef png_read_end
5768 # undef png_read_image
5769 # undef png_read_info
5770 # undef png_read_update_info
5771 # undef png_set_background
5772 # undef png_set_expand
5773 # undef png_set_gray_to_rgb
5774 # undef png_set_longjmp_fn
5775 # undef png_set_read_fn
5776 # undef png_set_sig_bytes
5777 # undef png_set_strip_16
5778 # undef png_sig_cmp
5780 # define png_create_info_struct fn_png_create_info_struct
5781 # define png_create_read_struct fn_png_create_read_struct
5782 # define png_destroy_read_struct fn_png_destroy_read_struct
5783 # define png_error fn_png_error
5784 # define png_get_bKGD fn_png_get_bKGD
5785 # define png_get_channels fn_png_get_channels
5786 # define png_get_IHDR fn_png_get_IHDR
5787 # define png_get_io_ptr fn_png_get_io_ptr
5788 # define png_get_rowbytes fn_png_get_rowbytes
5789 # define png_get_valid fn_png_get_valid
5790 # define png_longjmp fn_png_longjmp
5791 # define png_read_end fn_png_read_end
5792 # define png_read_image fn_png_read_image
5793 # define png_read_info fn_png_read_info
5794 # define png_read_update_info fn_png_read_update_info
5795 # define png_set_background fn_png_set_background
5796 # define png_set_expand fn_png_set_expand
5797 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5798 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5799 # define png_set_read_fn fn_png_set_read_fn
5800 # define png_set_sig_bytes fn_png_set_sig_bytes
5801 # define png_set_strip_16 fn_png_set_strip_16
5802 # define png_sig_cmp fn_png_sig_cmp
5804 # endif /* WINDOWSNT */
5806 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5807 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5808 Do not use sys_setjmp, as PNG supports only jmp_buf.
5809 It's OK if the longjmp substitute restores the signal mask. */
5810 # ifdef HAVE__SETJMP
5811 # define FAST_SETJMP(j) _setjmp (j)
5812 # define FAST_LONGJMP _longjmp
5813 # else
5814 # define FAST_SETJMP(j) setjmp (j)
5815 # define FAST_LONGJMP longjmp
5816 # endif
5818 # if PNG_LIBPNG_VER < 10500
5819 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5820 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5821 # else
5822 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5823 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5824 # define PNG_JMPBUF(ptr) \
5825 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5826 # endif
5828 /* Error and warning handlers installed when the PNG library
5829 is initialized. */
5831 static _Noreturn void
5832 my_png_error (png_struct *png_ptr, const char *msg)
5834 eassert (png_ptr != NULL);
5835 /* Avoid compiler warning about deprecated direct access to
5836 png_ptr's fields in libpng versions 1.4.x. */
5837 image_error ("PNG error: %s", build_string (msg));
5838 PNG_LONGJMP (png_ptr);
5842 static void
5843 my_png_warning (png_struct *png_ptr, const char *msg)
5845 eassert (png_ptr != NULL);
5846 image_error ("PNG warning: %s", build_string (msg));
5849 /* Memory source for PNG decoding. */
5851 struct png_memory_storage
5853 unsigned char *bytes; /* The data */
5854 ptrdiff_t len; /* How big is it? */
5855 ptrdiff_t index; /* Where are we? */
5859 /* Function set as reader function when reading PNG image from memory.
5860 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5861 bytes from the input to DATA. */
5863 static void
5864 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5866 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5868 if (length > tbr->len - tbr->index)
5869 png_error (png_ptr, "Read error");
5871 memcpy (data, tbr->bytes + tbr->index, length);
5872 tbr->index = tbr->index + length;
5876 /* Function set as reader function when reading PNG image from a file.
5877 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5878 bytes from the input to DATA. */
5880 static void
5881 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5883 FILE *fp = png_get_io_ptr (png_ptr);
5885 if (fread (data, 1, length, fp) < length)
5886 png_error (png_ptr, "Read error");
5890 /* Load PNG image IMG for use on frame F. Value is true if
5891 successful. */
5893 struct png_load_context
5895 /* These are members so that longjmp doesn't munge local variables. */
5896 png_struct *png_ptr;
5897 png_info *info_ptr;
5898 png_info *end_info;
5899 FILE *fp;
5900 png_byte *pixels;
5901 png_byte **rows;
5904 static bool
5905 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5907 Lisp_Object specified_file, specified_data;
5908 FILE *fp = NULL;
5909 int x, y;
5910 ptrdiff_t i;
5911 png_struct *png_ptr;
5912 png_info *info_ptr = NULL, *end_info = NULL;
5913 png_byte sig[8];
5914 png_byte *pixels = NULL;
5915 png_byte **rows = NULL;
5916 png_uint_32 width, height;
5917 int bit_depth, color_type, interlace_type;
5918 png_byte channels;
5919 png_uint_32 row_bytes;
5920 bool transparent_p;
5921 struct png_memory_storage tbr; /* Data to be read */
5922 ptrdiff_t nbytes;
5924 #ifdef USE_CAIRO
5925 unsigned char *data = 0;
5926 uint32_t *dataptr;
5927 #else
5928 XImagePtr ximg, mask_img = NULL;
5929 #endif
5931 /* Find out what file to load. */
5932 specified_file = image_spec_value (img->spec, QCfile, NULL);
5933 specified_data = image_spec_value (img->spec, QCdata, NULL);
5935 if (NILP (specified_data))
5937 int fd;
5938 Lisp_Object file = x_find_image_fd (specified_file, &fd);
5939 if (!STRINGP (file))
5941 image_error ("Cannot find image file `%s'", specified_file);
5942 return 0;
5945 /* Open the image file. */
5946 fp = fdopen (fd, "rb");
5947 if (!fp)
5949 image_error ("Cannot open image file `%s'", file);
5950 return 0;
5953 /* Check PNG signature. */
5954 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5955 || png_sig_cmp (sig, 0, sizeof sig))
5957 fclose (fp);
5958 image_error ("Not a PNG file: `%s'", file);
5959 return 0;
5962 else
5964 if (!STRINGP (specified_data))
5966 image_error ("Invalid image data `%s'", specified_data);
5967 return 0;
5970 /* Read from memory. */
5971 tbr.bytes = SDATA (specified_data);
5972 tbr.len = SBYTES (specified_data);
5973 tbr.index = 0;
5975 /* Check PNG signature. */
5976 if (tbr.len < sizeof sig
5977 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5979 image_error ("Not a PNG image: `%s'", img->spec);
5980 return 0;
5983 /* Need to skip past the signature. */
5984 tbr.bytes += sizeof (sig);
5987 /* Initialize read and info structs for PNG lib. */
5988 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5989 NULL, my_png_error,
5990 my_png_warning);
5991 if (png_ptr)
5993 info_ptr = png_create_info_struct (png_ptr);
5994 end_info = png_create_info_struct (png_ptr);
5997 c->png_ptr = png_ptr;
5998 c->info_ptr = info_ptr;
5999 c->end_info = end_info;
6000 c->fp = fp;
6001 c->pixels = pixels;
6002 c->rows = rows;
6004 if (! (info_ptr && end_info))
6006 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6007 png_ptr = 0;
6009 if (! png_ptr)
6011 if (fp) fclose (fp);
6012 return 0;
6015 /* Set error jump-back. We come back here when the PNG library
6016 detects an error. */
6017 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
6019 error:
6020 if (c->png_ptr)
6021 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6022 xfree (c->pixels);
6023 xfree (c->rows);
6024 if (c->fp)
6025 fclose (c->fp);
6026 return 0;
6029 /* Read image info. */
6030 if (!NILP (specified_data))
6031 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
6032 else
6033 png_set_read_fn (png_ptr, fp, png_read_from_file);
6035 png_set_sig_bytes (png_ptr, sizeof sig);
6036 png_read_info (png_ptr, info_ptr);
6037 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6038 &interlace_type, NULL, NULL);
6040 if (! (width <= INT_MAX && height <= INT_MAX
6041 && check_image_size (f, width, height)))
6043 image_size_error ();
6044 goto error;
6047 #ifndef USE_CAIRO
6048 /* Create the X image and pixmap now, so that the work below can be
6049 omitted if the image is too large for X. */
6050 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6051 goto error;
6052 #endif
6054 /* If image contains simply transparency data, we prefer to
6055 construct a clipping mask. */
6056 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6057 transparent_p = 1;
6058 else
6059 transparent_p = 0;
6061 /* This function is easier to write if we only have to handle
6062 one data format: RGB or RGBA with 8 bits per channel. Let's
6063 transform other formats into that format. */
6065 /* Strip more than 8 bits per channel. */
6066 if (bit_depth == 16)
6067 png_set_strip_16 (png_ptr);
6069 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6070 if available. */
6071 png_set_expand (png_ptr);
6073 /* Convert grayscale images to RGB. */
6074 if (color_type == PNG_COLOR_TYPE_GRAY
6075 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6076 png_set_gray_to_rgb (png_ptr);
6078 /* Handle alpha channel by combining the image with a background
6079 color. Do this only if a real alpha channel is supplied. For
6080 simple transparency, we prefer a clipping mask. */
6081 if (!transparent_p)
6083 /* png_color_16 *image_bg; */
6084 Lisp_Object specified_bg
6085 = image_spec_value (img->spec, QCbackground, NULL);
6086 XColor color;
6088 /* If the user specified a color, try to use it; if not, use the
6089 current frame background, ignoring any default background
6090 color set by the image. */
6091 if (STRINGP (specified_bg)
6092 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
6093 : (x_query_frame_background_color (f, &color), true))
6094 /* The user specified `:background', use that. */
6096 int shift = bit_depth == 16 ? 0 : 8;
6097 png_color_16 bg = { 0 };
6098 bg.red = color.red >> shift;
6099 bg.green = color.green >> shift;
6100 bg.blue = color.blue >> shift;
6102 png_set_background (png_ptr, &bg,
6103 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6107 /* Update info structure. */
6108 png_read_update_info (png_ptr, info_ptr);
6110 /* Get number of channels. Valid values are 1 for grayscale images
6111 and images with a palette, 2 for grayscale images with transparency
6112 information (alpha channel), 3 for RGB images, and 4 for RGB
6113 images with alpha channel, i.e. RGBA. If conversions above were
6114 sufficient we should only have 3 or 4 channels here. */
6115 channels = png_get_channels (png_ptr, info_ptr);
6116 eassert (channels == 3 || channels == 4);
6118 /* Number of bytes needed for one row of the image. */
6119 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
6121 /* Allocate memory for the image. */
6122 if (INT_MULTIPLY_WRAPV (row_bytes, sizeof *pixels, &nbytes)
6123 || INT_MULTIPLY_WRAPV (nbytes, height, &nbytes))
6124 memory_full (SIZE_MAX);
6125 c->pixels = pixels = xmalloc (nbytes);
6126 c->rows = rows = xmalloc (height * sizeof *rows);
6127 for (i = 0; i < height; ++i)
6128 rows[i] = pixels + i * row_bytes;
6130 /* Read the entire image. */
6131 png_read_image (png_ptr, rows);
6132 png_read_end (png_ptr, info_ptr);
6133 if (fp)
6135 fclose (fp);
6136 c->fp = NULL;
6139 #ifdef USE_CAIRO
6140 data = (unsigned char *) xmalloc (width * height * 4);
6141 dataptr = (uint32_t *) data;
6142 #else
6143 /* Create an image and pixmap serving as mask if the PNG image
6144 contains an alpha channel. */
6145 if (channels == 4
6146 && !transparent_p
6147 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
6148 &mask_img, 1))
6150 x_destroy_x_image (ximg);
6151 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
6152 goto error;
6154 #endif
6156 /* Fill the X image and mask from PNG data. */
6157 init_color_table ();
6159 for (y = 0; y < height; ++y)
6161 png_byte *p = rows[y];
6163 for (x = 0; x < width; ++x)
6165 int r, g, b;
6167 #ifdef USE_CAIRO
6168 int a = 0xff;
6169 r = *p++;
6170 g = *p++;
6171 b = *p++;
6172 if (channels == 4) a = *p++;
6173 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
6174 #else
6175 r = *p++ << 8;
6176 g = *p++ << 8;
6177 b = *p++ << 8;
6178 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6179 /* An alpha channel, aka mask channel, associates variable
6180 transparency with an image. Where other image formats
6181 support binary transparency---fully transparent or fully
6182 opaque---PNG allows up to 254 levels of partial transparency.
6183 The PNG library implements partial transparency by combining
6184 the image with a specified background color.
6186 I'm not sure how to handle this here nicely: because the
6187 background on which the image is displayed may change, for
6188 real alpha channel support, it would be necessary to create
6189 a new image for each possible background.
6191 What I'm doing now is that a mask is created if we have
6192 boolean transparency information. Otherwise I'm using
6193 the frame's background color to combine the image with. */
6195 if (channels == 4)
6197 if (mask_img)
6198 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6199 ++p;
6201 #endif
6205 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6206 /* Set IMG's background color from the PNG image, unless the user
6207 overrode it. */
6209 png_color_16 *bg;
6210 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6212 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6213 img->background_valid = 1;
6217 # ifdef COLOR_TABLE_SUPPORT
6218 /* Remember colors allocated for this image. */
6219 img->colors = colors_in_color_table (&img->ncolors);
6220 free_color_table ();
6221 # endif /* COLOR_TABLE_SUPPORT */
6223 /* Clean up. */
6224 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6225 xfree (rows);
6226 xfree (pixels);
6228 img->width = width;
6229 img->height = height;
6231 #ifdef USE_CAIRO
6232 create_cairo_image_surface (img, data, width, height);
6233 #else
6234 /* Maybe fill in the background field while we have ximg handy.
6235 Casting avoids a GCC warning. */
6236 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6238 /* Put ximg into the image. */
6239 image_put_x_image (f, img, ximg, 0);
6241 /* Same for the mask. */
6242 if (mask_img)
6244 /* Fill in the background_transparent field while we have the
6245 mask handy. Casting avoids a GCC warning. */
6246 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6248 image_put_x_image (f, img, mask_img, 1);
6250 #endif
6252 return 1;
6255 static bool
6256 png_load (struct frame *f, struct image *img)
6258 struct png_load_context c;
6259 return png_load_body (f, img, &c);
6262 #elif defined HAVE_NS
6264 static bool
6265 png_load (struct frame *f, struct image *img)
6267 return ns_load_image (f, img,
6268 image_spec_value (img->spec, QCfile, NULL),
6269 image_spec_value (img->spec, QCdata, NULL));
6273 #endif /* HAVE_NS */
6277 /***********************************************************************
6278 JPEG
6279 ***********************************************************************/
6281 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6283 static bool jpeg_image_p (Lisp_Object object);
6284 static bool jpeg_load (struct frame *f, struct image *img);
6286 /* Indices of image specification fields in gs_format, below. */
6288 enum jpeg_keyword_index
6290 JPEG_TYPE,
6291 JPEG_DATA,
6292 JPEG_FILE,
6293 JPEG_ASCENT,
6294 JPEG_MARGIN,
6295 JPEG_RELIEF,
6296 JPEG_ALGORITHM,
6297 JPEG_HEURISTIC_MASK,
6298 JPEG_MASK,
6299 JPEG_BACKGROUND,
6300 JPEG_LAST
6303 /* Vector of image_keyword structures describing the format
6304 of valid user-defined image specifications. */
6306 static const struct image_keyword jpeg_format[JPEG_LAST] =
6308 {":type", IMAGE_SYMBOL_VALUE, 1},
6309 {":data", IMAGE_STRING_VALUE, 0},
6310 {":file", IMAGE_STRING_VALUE, 0},
6311 {":ascent", IMAGE_ASCENT_VALUE, 0},
6312 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6313 {":relief", IMAGE_INTEGER_VALUE, 0},
6314 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6315 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6316 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6317 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6320 #if defined HAVE_NTGUI && defined WINDOWSNT
6321 static bool init_jpeg_functions (void);
6322 #else
6323 #define init_jpeg_functions NULL
6324 #endif
6326 /* Structure describing the image type `jpeg'. */
6328 static struct image_type jpeg_type =
6330 SYMBOL_INDEX (Qjpeg),
6331 jpeg_image_p,
6332 jpeg_load,
6333 x_clear_image,
6334 init_jpeg_functions,
6335 NULL
6338 /* Return true if OBJECT is a valid JPEG image specification. */
6340 static bool
6341 jpeg_image_p (Lisp_Object object)
6343 struct image_keyword fmt[JPEG_LAST];
6345 memcpy (fmt, jpeg_format, sizeof fmt);
6347 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6348 return 0;
6350 /* Must specify either the :data or :file keyword. */
6351 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6354 #endif /* HAVE_JPEG || HAVE_NS */
6356 #ifdef HAVE_JPEG
6358 /* Work around a warning about HAVE_STDLIB_H being redefined in
6359 jconfig.h. */
6360 # ifdef HAVE_STDLIB_H
6361 # undef HAVE_STDLIB_H
6362 # endif
6364 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6365 /* In older releases of the jpeg library, jpeglib.h will define boolean
6366 differently depending on __WIN32__, so make sure it is defined. */
6367 # define __WIN32__ 1
6368 # endif
6370 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6371 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6372 using the Windows boolean type instead of the jpeglib boolean type
6373 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6374 headers are included along with windows.h, so under Cygwin, jpeglib
6375 attempts to define a conflicting boolean type. Worse, forcing
6376 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6377 because it created an ABI incompatibility between the
6378 already-compiled jpeg library and the header interface definition.
6380 The best we can do is to define jpeglib's boolean type to a
6381 different name. This name, jpeg_boolean, remains in effect through
6382 the rest of image.c.
6384 # if defined CYGWIN && defined HAVE_NTGUI
6385 # define boolean jpeg_boolean
6386 # endif
6387 # include <jpeglib.h>
6388 # include <jerror.h>
6390 # ifdef WINDOWSNT
6392 /* JPEG library details. */
6393 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6394 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6395 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6396 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6397 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6398 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6399 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6400 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6401 (struct jpeg_error_mgr *));
6402 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6404 static bool
6405 init_jpeg_functions (void)
6407 HMODULE library;
6409 if (!(library = w32_delayed_load (Qjpeg)))
6410 return 0;
6412 LOAD_DLL_FN (library, jpeg_finish_decompress);
6413 LOAD_DLL_FN (library, jpeg_read_scanlines);
6414 LOAD_DLL_FN (library, jpeg_start_decompress);
6415 LOAD_DLL_FN (library, jpeg_read_header);
6416 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6417 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6418 LOAD_DLL_FN (library, jpeg_std_error);
6419 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6420 return 1;
6423 # undef jpeg_CreateDecompress
6424 # undef jpeg_destroy_decompress
6425 # undef jpeg_finish_decompress
6426 # undef jpeg_read_header
6427 # undef jpeg_read_scanlines
6428 # undef jpeg_resync_to_restart
6429 # undef jpeg_start_decompress
6430 # undef jpeg_std_error
6432 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6433 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6434 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6435 # define jpeg_read_header fn_jpeg_read_header
6436 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6437 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6438 # define jpeg_start_decompress fn_jpeg_start_decompress
6439 # define jpeg_std_error fn_jpeg_std_error
6441 /* Wrapper since we can't directly assign the function pointer
6442 to another function pointer that was declared more completely easily. */
6443 static boolean
6444 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6446 return jpeg_resync_to_restart (cinfo, desired);
6448 # undef jpeg_resync_to_restart
6449 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6451 # endif /* WINDOWSNT */
6453 struct my_jpeg_error_mgr
6455 struct jpeg_error_mgr pub;
6456 sys_jmp_buf setjmp_buffer;
6458 /* The remaining members are so that longjmp doesn't munge local
6459 variables. */
6460 struct jpeg_decompress_struct cinfo;
6461 enum
6463 MY_JPEG_ERROR_EXIT,
6464 MY_JPEG_INVALID_IMAGE_SIZE,
6465 MY_JPEG_CANNOT_CREATE_X
6466 } failure_code;
6470 static _Noreturn void
6471 my_error_exit (j_common_ptr cinfo)
6473 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6474 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6475 sys_longjmp (mgr->setjmp_buffer, 1);
6479 /* Init source method for JPEG data source manager. Called by
6480 jpeg_read_header() before any data is actually read. See
6481 libjpeg.doc from the JPEG lib distribution. */
6483 static void
6484 our_common_init_source (j_decompress_ptr cinfo)
6489 /* Method to terminate data source. Called by
6490 jpeg_finish_decompress() after all data has been processed. */
6492 static void
6493 our_common_term_source (j_decompress_ptr cinfo)
6498 /* Fill input buffer method for JPEG data source manager. Called
6499 whenever more data is needed. We read the whole image in one step,
6500 so this only adds a fake end of input marker at the end. */
6502 static JOCTET our_memory_buffer[2];
6504 static boolean
6505 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6507 /* Insert a fake EOI marker. */
6508 struct jpeg_source_mgr *src = cinfo->src;
6510 our_memory_buffer[0] = (JOCTET) 0xFF;
6511 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6513 src->next_input_byte = our_memory_buffer;
6514 src->bytes_in_buffer = 2;
6515 return 1;
6519 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6520 is the JPEG data source manager. */
6522 static void
6523 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6525 struct jpeg_source_mgr *src = cinfo->src;
6527 if (src)
6529 if (num_bytes > src->bytes_in_buffer)
6530 ERREXIT (cinfo, JERR_INPUT_EOF);
6532 src->bytes_in_buffer -= num_bytes;
6533 src->next_input_byte += num_bytes;
6538 /* Set up the JPEG lib for reading an image from DATA which contains
6539 LEN bytes. CINFO is the decompression info structure created for
6540 reading the image. */
6542 static void
6543 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6545 struct jpeg_source_mgr *src = cinfo->src;
6547 if (! src)
6549 /* First time for this JPEG object? */
6550 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6551 JPOOL_PERMANENT, sizeof *src);
6552 cinfo->src = src;
6553 src->next_input_byte = data;
6556 src->init_source = our_common_init_source;
6557 src->fill_input_buffer = our_memory_fill_input_buffer;
6558 src->skip_input_data = our_memory_skip_input_data;
6559 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6560 src->term_source = our_common_term_source;
6561 src->bytes_in_buffer = len;
6562 src->next_input_byte = data;
6566 struct jpeg_stdio_mgr
6568 struct jpeg_source_mgr mgr;
6569 boolean finished;
6570 FILE *file;
6571 JOCTET *buffer;
6575 /* Size of buffer to read JPEG from file.
6576 Not too big, as we want to use alloc_small. */
6577 #define JPEG_STDIO_BUFFER_SIZE 8192
6580 /* Fill input buffer method for JPEG data source manager. Called
6581 whenever more data is needed. The data is read from a FILE *. */
6583 static boolean
6584 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6586 struct jpeg_stdio_mgr *src;
6588 src = (struct jpeg_stdio_mgr *) cinfo->src;
6589 if (!src->finished)
6591 ptrdiff_t bytes;
6593 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6594 if (bytes > 0)
6595 src->mgr.bytes_in_buffer = bytes;
6596 else
6598 WARNMS (cinfo, JWRN_JPEG_EOF);
6599 src->finished = 1;
6600 src->buffer[0] = (JOCTET) 0xFF;
6601 src->buffer[1] = (JOCTET) JPEG_EOI;
6602 src->mgr.bytes_in_buffer = 2;
6604 src->mgr.next_input_byte = src->buffer;
6607 return 1;
6611 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6612 is the JPEG data source manager. */
6614 static void
6615 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6617 struct jpeg_stdio_mgr *src;
6618 src = (struct jpeg_stdio_mgr *) cinfo->src;
6620 while (num_bytes > 0 && !src->finished)
6622 if (num_bytes <= src->mgr.bytes_in_buffer)
6624 src->mgr.bytes_in_buffer -= num_bytes;
6625 src->mgr.next_input_byte += num_bytes;
6626 break;
6628 else
6630 num_bytes -= src->mgr.bytes_in_buffer;
6631 src->mgr.bytes_in_buffer = 0;
6632 src->mgr.next_input_byte = NULL;
6634 our_stdio_fill_input_buffer (cinfo);
6640 /* Set up the JPEG lib for reading an image from a FILE *.
6641 CINFO is the decompression info structure created for
6642 reading the image. */
6644 static void
6645 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6647 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6649 if (! src)
6651 /* First time for this JPEG object? */
6652 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6653 JPOOL_PERMANENT, sizeof *src);
6654 cinfo->src = (struct jpeg_source_mgr *) src;
6655 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6656 JPOOL_PERMANENT,
6657 JPEG_STDIO_BUFFER_SIZE);
6660 src->file = fp;
6661 src->finished = 0;
6662 src->mgr.init_source = our_common_init_source;
6663 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6664 src->mgr.skip_input_data = our_stdio_skip_input_data;
6665 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6666 src->mgr.term_source = our_common_term_source;
6667 src->mgr.bytes_in_buffer = 0;
6668 src->mgr.next_input_byte = NULL;
6671 /* Load image IMG for use on frame F. Patterned after example.c
6672 from the JPEG lib. */
6674 static bool
6675 jpeg_load_body (struct frame *f, struct image *img,
6676 struct my_jpeg_error_mgr *mgr)
6678 Lisp_Object specified_file, specified_data;
6679 FILE *volatile fp = NULL;
6680 JSAMPARRAY buffer;
6681 int row_stride, x, y;
6682 unsigned long *colors;
6683 int width, height;
6684 int i, ir, ig, ib;
6685 #ifndef USE_CAIRO
6686 XImagePtr ximg = NULL;
6687 #endif
6689 /* Open the JPEG file. */
6690 specified_file = image_spec_value (img->spec, QCfile, NULL);
6691 specified_data = image_spec_value (img->spec, QCdata, NULL);
6693 if (NILP (specified_data))
6695 int fd;
6696 Lisp_Object file = x_find_image_fd (specified_file, &fd);
6697 if (!STRINGP (file))
6699 image_error ("Cannot find image file `%s'", specified_file);
6700 return 0;
6703 fp = fdopen (fd, "rb");
6704 if (fp == NULL)
6706 image_error ("Cannot open `%s'", file);
6707 return 0;
6710 else if (!STRINGP (specified_data))
6712 image_error ("Invalid image data `%s'", specified_data);
6713 return 0;
6716 /* Customize libjpeg's error handling to call my_error_exit when an
6717 error is detected. This function will perform a longjmp. */
6718 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6719 mgr->pub.error_exit = my_error_exit;
6720 if (sys_setjmp (mgr->setjmp_buffer))
6722 switch (mgr->failure_code)
6724 case MY_JPEG_ERROR_EXIT:
6726 char buf[JMSG_LENGTH_MAX];
6727 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6728 image_error ("Error reading JPEG image `%s': %s",
6729 img->spec, build_string (buf));
6730 break;
6733 case MY_JPEG_INVALID_IMAGE_SIZE:
6734 image_size_error ();
6735 break;
6737 case MY_JPEG_CANNOT_CREATE_X:
6738 break;
6741 /* Close the input file and destroy the JPEG object. */
6742 if (fp)
6743 fclose (fp);
6744 jpeg_destroy_decompress (&mgr->cinfo);
6746 /* If we already have an XImage, free that. */
6747 #ifndef USE_CAIRO
6748 x_destroy_x_image (ximg);
6749 #endif
6750 /* Free pixmap and colors. */
6751 x_clear_image (f, img);
6752 return 0;
6755 /* Create the JPEG decompression object. Let it read from fp.
6756 Read the JPEG image header. */
6757 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6759 if (NILP (specified_data))
6760 jpeg_file_src (&mgr->cinfo, fp);
6761 else
6762 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6763 SBYTES (specified_data));
6765 jpeg_read_header (&mgr->cinfo, 1);
6767 /* Customize decompression so that color quantization will be used.
6768 Start decompression. */
6769 mgr->cinfo.quantize_colors = 1;
6770 jpeg_start_decompress (&mgr->cinfo);
6771 width = img->width = mgr->cinfo.output_width;
6772 height = img->height = mgr->cinfo.output_height;
6774 if (!check_image_size (f, width, height))
6776 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6777 sys_longjmp (mgr->setjmp_buffer, 1);
6780 #ifndef USE_CAIRO
6781 /* Create X image and pixmap. */
6782 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6784 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6785 sys_longjmp (mgr->setjmp_buffer, 1);
6787 #endif
6789 /* Allocate colors. When color quantization is used,
6790 mgr->cinfo.actual_number_of_colors has been set with the number of
6791 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6792 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6793 No more than 255 colors will be generated. */
6794 USE_SAFE_ALLOCA;
6796 if (mgr->cinfo.out_color_components > 2)
6797 ir = 0, ig = 1, ib = 2;
6798 else if (mgr->cinfo.out_color_components > 1)
6799 ir = 0, ig = 1, ib = 0;
6800 else
6801 ir = 0, ig = 0, ib = 0;
6803 #ifndef CAIRO
6804 /* Use the color table mechanism because it handles colors that
6805 cannot be allocated nicely. Such colors will be replaced with
6806 a default color, and we don't have to care about which colors
6807 can be freed safely, and which can't. */
6808 init_color_table ();
6809 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6811 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6813 /* Multiply RGB values with 255 because X expects RGB values
6814 in the range 0..0xffff. */
6815 int r = mgr->cinfo.colormap[ir][i] << 8;
6816 int g = mgr->cinfo.colormap[ig][i] << 8;
6817 int b = mgr->cinfo.colormap[ib][i] << 8;
6818 colors[i] = lookup_rgb_color (f, r, g, b);
6820 #endif
6822 #ifdef COLOR_TABLE_SUPPORT
6823 /* Remember those colors actually allocated. */
6824 img->colors = colors_in_color_table (&img->ncolors);
6825 free_color_table ();
6826 #endif /* COLOR_TABLE_SUPPORT */
6829 /* Read pixels. */
6830 row_stride = width * mgr->cinfo.output_components;
6831 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6832 JPOOL_IMAGE, row_stride, 1);
6833 #ifdef USE_CAIRO
6835 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
6836 uint32_t *dataptr = (uint32_t *) data;
6837 int r, g, b;
6839 for (y = 0; y < height; ++y)
6841 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6843 for (x = 0; x < width; ++x)
6845 i = buffer[0][x];
6846 r = mgr->cinfo.colormap[ir][i];
6847 g = mgr->cinfo.colormap[ig][i];
6848 b = mgr->cinfo.colormap[ib][i];
6849 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
6853 create_cairo_image_surface (img, data, width, height);
6855 #else
6856 for (y = 0; y < height; ++y)
6858 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6859 for (x = 0; x < mgr->cinfo.output_width; ++x)
6860 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6862 #endif
6864 /* Clean up. */
6865 jpeg_finish_decompress (&mgr->cinfo);
6866 jpeg_destroy_decompress (&mgr->cinfo);
6867 if (fp)
6868 fclose (fp);
6870 #ifndef USE_CAIRO
6871 /* Maybe fill in the background field while we have ximg handy. */
6872 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6873 /* Casting avoids a GCC warning. */
6874 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6876 /* Put ximg into the image. */
6877 image_put_x_image (f, img, ximg, 0);
6878 #endif
6879 SAFE_FREE ();
6880 return 1;
6883 static bool
6884 jpeg_load (struct frame *f, struct image *img)
6886 struct my_jpeg_error_mgr mgr;
6887 return jpeg_load_body (f, img, &mgr);
6890 #else /* HAVE_JPEG */
6892 #ifdef HAVE_NS
6893 static bool
6894 jpeg_load (struct frame *f, struct image *img)
6896 return ns_load_image (f, img,
6897 image_spec_value (img->spec, QCfile, NULL),
6898 image_spec_value (img->spec, QCdata, NULL));
6900 #endif /* HAVE_NS */
6902 #endif /* !HAVE_JPEG */
6906 /***********************************************************************
6907 TIFF
6908 ***********************************************************************/
6910 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6912 static bool tiff_image_p (Lisp_Object object);
6913 static bool tiff_load (struct frame *f, struct image *img);
6915 /* Indices of image specification fields in tiff_format, below. */
6917 enum tiff_keyword_index
6919 TIFF_TYPE,
6920 TIFF_DATA,
6921 TIFF_FILE,
6922 TIFF_ASCENT,
6923 TIFF_MARGIN,
6924 TIFF_RELIEF,
6925 TIFF_ALGORITHM,
6926 TIFF_HEURISTIC_MASK,
6927 TIFF_MASK,
6928 TIFF_BACKGROUND,
6929 TIFF_INDEX,
6930 TIFF_LAST
6933 /* Vector of image_keyword structures describing the format
6934 of valid user-defined image specifications. */
6936 static const struct image_keyword tiff_format[TIFF_LAST] =
6938 {":type", IMAGE_SYMBOL_VALUE, 1},
6939 {":data", IMAGE_STRING_VALUE, 0},
6940 {":file", IMAGE_STRING_VALUE, 0},
6941 {":ascent", IMAGE_ASCENT_VALUE, 0},
6942 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6943 {":relief", IMAGE_INTEGER_VALUE, 0},
6944 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6945 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6946 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6947 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6948 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6951 #if defined HAVE_NTGUI && defined WINDOWSNT
6952 static bool init_tiff_functions (void);
6953 #else
6954 #define init_tiff_functions NULL
6955 #endif
6957 /* Structure describing the image type `tiff'. */
6959 static struct image_type tiff_type =
6961 SYMBOL_INDEX (Qtiff),
6962 tiff_image_p,
6963 tiff_load,
6964 x_clear_image,
6965 init_tiff_functions,
6966 NULL
6969 /* Return true if OBJECT is a valid TIFF image specification. */
6971 static bool
6972 tiff_image_p (Lisp_Object object)
6974 struct image_keyword fmt[TIFF_LAST];
6975 memcpy (fmt, tiff_format, sizeof fmt);
6977 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6978 return 0;
6980 /* Must specify either the :data or :file keyword. */
6981 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6984 #endif /* HAVE_TIFF || HAVE_NS */
6986 #ifdef HAVE_TIFF
6988 # include <tiffio.h>
6990 # ifdef WINDOWSNT
6992 /* TIFF library details. */
6993 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6994 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6995 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
6996 DEF_DLL_FN (TIFF *, TIFFClientOpen,
6997 (const char *, const char *, thandle_t, TIFFReadWriteProc,
6998 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6999 TIFFMapFileProc, TIFFUnmapFileProc));
7000 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
7001 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
7002 DEF_DLL_FN (void, TIFFClose, (TIFF *));
7003 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
7005 static bool
7006 init_tiff_functions (void)
7008 HMODULE library;
7010 if (!(library = w32_delayed_load (Qtiff)))
7011 return 0;
7013 LOAD_DLL_FN (library, TIFFSetErrorHandler);
7014 LOAD_DLL_FN (library, TIFFSetWarningHandler);
7015 LOAD_DLL_FN (library, TIFFOpen);
7016 LOAD_DLL_FN (library, TIFFClientOpen);
7017 LOAD_DLL_FN (library, TIFFGetField);
7018 LOAD_DLL_FN (library, TIFFReadRGBAImage);
7019 LOAD_DLL_FN (library, TIFFClose);
7020 LOAD_DLL_FN (library, TIFFSetDirectory);
7021 return 1;
7024 # undef TIFFClientOpen
7025 # undef TIFFClose
7026 # undef TIFFGetField
7027 # undef TIFFOpen
7028 # undef TIFFReadRGBAImage
7029 # undef TIFFSetDirectory
7030 # undef TIFFSetErrorHandler
7031 # undef TIFFSetWarningHandler
7033 # define TIFFClientOpen fn_TIFFClientOpen
7034 # define TIFFClose fn_TIFFClose
7035 # define TIFFGetField fn_TIFFGetField
7036 # define TIFFOpen fn_TIFFOpen
7037 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7038 # define TIFFSetDirectory fn_TIFFSetDirectory
7039 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7040 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7042 # endif /* WINDOWSNT */
7045 /* Reading from a memory buffer for TIFF images Based on the PNG
7046 memory source, but we have to provide a lot of extra functions.
7047 Blah.
7049 We really only need to implement read and seek, but I am not
7050 convinced that the TIFF library is smart enough not to destroy
7051 itself if we only hand it the function pointers we need to
7052 override. */
7054 typedef struct
7056 unsigned char *bytes;
7057 ptrdiff_t len;
7058 ptrdiff_t index;
7060 tiff_memory_source;
7062 static tsize_t
7063 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7065 tiff_memory_source *src = (tiff_memory_source *) data;
7067 size = min (size, src->len - src->index);
7068 memcpy (buf, src->bytes + src->index, size);
7069 src->index += size;
7070 return size;
7073 static tsize_t
7074 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
7076 return -1;
7079 static toff_t
7080 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
7082 tiff_memory_source *src = (tiff_memory_source *) data;
7083 ptrdiff_t idx;
7085 switch (whence)
7087 case SEEK_SET: /* Go from beginning of source. */
7088 idx = off;
7089 break;
7091 case SEEK_END: /* Go from end of source. */
7092 idx = src->len + off;
7093 break;
7095 case SEEK_CUR: /* Go from current position. */
7096 idx = src->index + off;
7097 break;
7099 default: /* Invalid `whence'. */
7100 return -1;
7103 if (idx > src->len || idx < 0)
7104 return -1;
7106 src->index = idx;
7107 return src->index;
7110 static int
7111 tiff_close_memory (thandle_t data)
7113 /* NOOP */
7114 return 0;
7117 static int
7118 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
7120 /* It is already _IN_ memory. */
7121 return 0;
7124 static void
7125 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
7127 /* We don't need to do this. */
7130 static toff_t
7131 tiff_size_of_memory (thandle_t data)
7133 return ((tiff_memory_source *) data)->len;
7136 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7137 compiler error compiling tiff_handler, see Bugzilla bug #17406
7138 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7139 this function as external works around that problem. */
7140 # if defined (__MINGW32__) && __GNUC__ == 3
7141 # define MINGW_STATIC
7142 # else
7143 # define MINGW_STATIC static
7144 # endif
7146 MINGW_STATIC void
7147 tiff_handler (const char *, const char *, const char *, va_list)
7148 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7149 MINGW_STATIC void
7150 tiff_handler (const char *log_format, const char *title,
7151 const char *format, va_list ap)
7153 /* doprnt is not suitable here, as TIFF handlers are called from
7154 libtiff and are passed arbitrary printf directives. Instead, use
7155 vsnprintf, taking care to be portable to nonstandard environments
7156 where vsnprintf returns -1 on buffer overflow. Since it's just a
7157 log entry, it's OK to truncate it. */
7158 char buf[4000];
7159 int len = vsnprintf (buf, sizeof buf, format, ap);
7160 add_to_log (log_format, build_string (title),
7161 make_string (buf, max (0, min (len, sizeof buf - 1))));
7163 # undef MINGW_STATIC
7165 static void tiff_error_handler (const char *, const char *, va_list)
7166 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7167 static void
7168 tiff_error_handler (const char *title, const char *format, va_list ap)
7170 tiff_handler ("TIFF error: %s %s", title, format, ap);
7174 static void tiff_warning_handler (const char *, const char *, va_list)
7175 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7176 static void
7177 tiff_warning_handler (const char *title, const char *format, va_list ap)
7179 tiff_handler ("TIFF warning: %s %s", title, format, ap);
7183 /* Load TIFF image IMG for use on frame F. Value is true if
7184 successful. */
7186 static bool
7187 tiff_load (struct frame *f, struct image *img)
7189 Lisp_Object specified_file;
7190 Lisp_Object specified_data;
7191 TIFF *tiff;
7192 int width, height, x, y, count;
7193 uint32 *buf;
7194 int rc;
7195 XImagePtr ximg;
7196 tiff_memory_source memsrc;
7197 Lisp_Object image;
7199 specified_file = image_spec_value (img->spec, QCfile, NULL);
7200 specified_data = image_spec_value (img->spec, QCdata, NULL);
7202 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
7203 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7205 if (NILP (specified_data))
7207 /* Read from a file */
7208 Lisp_Object file = x_find_image_file (specified_file);
7209 if (!STRINGP (file))
7211 image_error ("Cannot find image file `%s'", specified_file);
7212 return 0;
7215 Lisp_Object encoded_file = ENCODE_FILE (file);
7216 # ifdef WINDOWSNT
7217 encoded_file = ansi_encode_filename (encoded_file);
7218 # endif
7220 /* Try to open the image file. */
7221 tiff = TIFFOpen (SSDATA (encoded_file), "r");
7222 if (tiff == NULL)
7224 image_error ("Cannot open `%s'", file);
7225 return 0;
7228 else
7230 if (!STRINGP (specified_data))
7232 image_error ("Invalid image data `%s'", specified_data);
7233 return 0;
7236 /* Memory source! */
7237 memsrc.bytes = SDATA (specified_data);
7238 memsrc.len = SBYTES (specified_data);
7239 memsrc.index = 0;
7241 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7242 tiff_read_from_memory,
7243 tiff_write_from_memory,
7244 tiff_seek_in_memory,
7245 tiff_close_memory,
7246 tiff_size_of_memory,
7247 tiff_mmap_memory,
7248 tiff_unmap_memory);
7250 if (!tiff)
7252 image_error ("Cannot open memory source for `%s'", img->spec);
7253 return 0;
7257 image = image_spec_value (img->spec, QCindex, NULL);
7258 if (INTEGERP (image))
7260 EMACS_INT ino = XFASTINT (image);
7261 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7262 && TIFFSetDirectory (tiff, ino)))
7264 image_error ("Invalid image number `%s' in image `%s'",
7265 image, img->spec);
7266 TIFFClose (tiff);
7267 return 0;
7271 /* Get width and height of the image, and allocate a raster buffer
7272 of width x height 32-bit values. */
7273 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7274 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7276 if (!check_image_size (f, width, height))
7278 image_size_error ();
7279 TIFFClose (tiff);
7280 return 0;
7283 /* Create the X image and pixmap. */
7284 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7285 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7286 &ximg, 0)))
7288 TIFFClose (tiff);
7289 return 0;
7292 buf = xmalloc (sizeof *buf * width * height);
7294 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7296 /* Count the number of images in the file. */
7297 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7298 continue;
7300 if (count > 1)
7301 img->lisp_data = Fcons (Qcount,
7302 Fcons (make_number (count),
7303 img->lisp_data));
7305 TIFFClose (tiff);
7306 if (!rc)
7308 image_error ("Error reading TIFF image `%s'", img->spec);
7309 xfree (buf);
7310 return 0;
7313 #ifdef USE_CAIRO
7315 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
7316 uint32_t *dataptr = (uint32_t *) data;
7318 for (y = 0; y < height; ++y)
7320 uint32 *row = buf + (height - 1 - y) * width;
7321 for (x = 0; x < width; ++x)
7323 uint32 abgr = row[x];
7324 int r = TIFFGetR (abgr);
7325 int g = TIFFGetG (abgr);
7326 int b = TIFFGetB (abgr);
7327 int a = TIFFGetA (abgr);
7328 *dataptr++ = (a << 24) | (r << 16) | (g << 8) | b;
7332 create_cairo_image_surface (img, data, width, height);
7334 #else
7335 /* Initialize the color table. */
7336 init_color_table ();
7338 /* Process the pixel raster. Origin is in the lower-left corner. */
7339 for (y = 0; y < height; ++y)
7341 uint32 *row = buf + y * width;
7343 for (x = 0; x < width; ++x)
7345 uint32 abgr = row[x];
7346 int r = TIFFGetR (abgr) << 8;
7347 int g = TIFFGetG (abgr) << 8;
7348 int b = TIFFGetB (abgr) << 8;
7349 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7353 # ifdef COLOR_TABLE_SUPPORT
7354 /* Remember the colors allocated for the image. Free the color table. */
7355 img->colors = colors_in_color_table (&img->ncolors);
7356 free_color_table ();
7357 # endif /* COLOR_TABLE_SUPPORT */
7359 img->width = width;
7360 img->height = height;
7362 /* Maybe fill in the background field while we have ximg handy. */
7363 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7364 /* Casting avoids a GCC warning on W32. */
7365 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7367 /* Put ximg into the image. */
7368 image_put_x_image (f, img, ximg, 0);
7370 #endif /* ! USE_CAIRO */
7372 xfree (buf);
7373 return 1;
7376 #elif defined HAVE_NS
7378 static bool
7379 tiff_load (struct frame *f, struct image *img)
7381 return ns_load_image (f, img,
7382 image_spec_value (img->spec, QCfile, NULL),
7383 image_spec_value (img->spec, QCdata, NULL));
7386 #endif
7390 /***********************************************************************
7392 ***********************************************************************/
7394 #if defined (HAVE_GIF) || defined (HAVE_NS)
7396 static bool gif_image_p (Lisp_Object object);
7397 static bool gif_load (struct frame *f, struct image *img);
7398 static void gif_clear_image (struct frame *f, struct image *img);
7400 /* Indices of image specification fields in gif_format, below. */
7402 enum gif_keyword_index
7404 GIF_TYPE,
7405 GIF_DATA,
7406 GIF_FILE,
7407 GIF_ASCENT,
7408 GIF_MARGIN,
7409 GIF_RELIEF,
7410 GIF_ALGORITHM,
7411 GIF_HEURISTIC_MASK,
7412 GIF_MASK,
7413 GIF_IMAGE,
7414 GIF_BACKGROUND,
7415 GIF_LAST
7418 /* Vector of image_keyword structures describing the format
7419 of valid user-defined image specifications. */
7421 static const struct image_keyword gif_format[GIF_LAST] =
7423 {":type", IMAGE_SYMBOL_VALUE, 1},
7424 {":data", IMAGE_STRING_VALUE, 0},
7425 {":file", IMAGE_STRING_VALUE, 0},
7426 {":ascent", IMAGE_ASCENT_VALUE, 0},
7427 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7428 {":relief", IMAGE_INTEGER_VALUE, 0},
7429 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7430 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7431 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7432 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7433 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7436 #if defined HAVE_NTGUI && defined WINDOWSNT
7437 static bool init_gif_functions (void);
7438 #else
7439 #define init_gif_functions NULL
7440 #endif
7442 /* Structure describing the image type `gif'. */
7444 static struct image_type gif_type =
7446 SYMBOL_INDEX (Qgif),
7447 gif_image_p,
7448 gif_load,
7449 gif_clear_image,
7450 init_gif_functions,
7451 NULL
7454 /* Free X resources of GIF image IMG which is used on frame F. */
7456 static void
7457 gif_clear_image (struct frame *f, struct image *img)
7459 img->lisp_data = Qnil;
7460 x_clear_image (f, img);
7463 /* Return true if OBJECT is a valid GIF image specification. */
7465 static bool
7466 gif_image_p (Lisp_Object object)
7468 struct image_keyword fmt[GIF_LAST];
7469 memcpy (fmt, gif_format, sizeof fmt);
7471 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7472 return 0;
7474 /* Must specify either the :data or :file keyword. */
7475 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7478 #endif /* HAVE_GIF */
7480 #ifdef HAVE_GIF
7482 # ifdef HAVE_NTGUI
7484 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7485 Undefine before redefining to avoid a preprocessor warning. */
7486 # ifdef DrawText
7487 # undef DrawText
7488 # endif
7489 /* avoid conflict with QuickdrawText.h */
7490 # define DrawText gif_DrawText
7491 # include <gif_lib.h>
7492 # undef DrawText
7494 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7495 # ifndef GIFLIB_MINOR
7496 # define GIFLIB_MINOR 0
7497 # endif
7498 # ifndef GIFLIB_RELEASE
7499 # define GIFLIB_RELEASE 0
7500 # endif
7502 # else /* HAVE_NTGUI */
7504 # include <gif_lib.h>
7506 # endif /* HAVE_NTGUI */
7508 /* Giflib before 5.0 didn't define these macros. */
7509 # ifndef GIFLIB_MAJOR
7510 # define GIFLIB_MAJOR 4
7511 # endif
7513 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7514 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7515 earlier releases, where either it returns char * or GIFLIB_MINOR
7516 may be incorrect. */
7517 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7519 # ifdef WINDOWSNT
7521 /* GIF library details. */
7522 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7523 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7524 # else
7525 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7526 # endif
7527 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7528 # if GIFLIB_MAJOR < 5
7529 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7530 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7531 # else
7532 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7533 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7534 # endif
7535 # if HAVE_GIFERRORSTRING
7536 DEF_DLL_FN (char const *, GifErrorString, (int));
7537 # endif
7539 static bool
7540 init_gif_functions (void)
7542 HMODULE library;
7544 if (!(library = w32_delayed_load (Qgif)))
7545 return 0;
7547 LOAD_DLL_FN (library, DGifCloseFile);
7548 LOAD_DLL_FN (library, DGifSlurp);
7549 LOAD_DLL_FN (library, DGifOpen);
7550 LOAD_DLL_FN (library, DGifOpenFileName);
7551 # if HAVE_GIFERRORSTRING
7552 LOAD_DLL_FN (library, GifErrorString);
7553 # endif
7554 return 1;
7557 # undef DGifCloseFile
7558 # undef DGifOpen
7559 # undef DGifOpenFileName
7560 # undef DGifSlurp
7561 # undef GifErrorString
7563 # define DGifCloseFile fn_DGifCloseFile
7564 # define DGifOpen fn_DGifOpen
7565 # define DGifOpenFileName fn_DGifOpenFileName
7566 # define DGifSlurp fn_DGifSlurp
7567 # define GifErrorString fn_GifErrorString
7569 # endif /* WINDOWSNT */
7571 /* Reading a GIF image from memory
7572 Based on the PNG memory stuff to a certain extent. */
7574 typedef struct
7576 unsigned char *bytes;
7577 ptrdiff_t len;
7578 ptrdiff_t index;
7580 gif_memory_source;
7582 /* Make the current memory source available to gif_read_from_memory.
7583 It's done this way because not all versions of libungif support
7584 a UserData field in the GifFileType structure. */
7585 static gif_memory_source *current_gif_memory_src;
7587 static int
7588 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7590 gif_memory_source *src = current_gif_memory_src;
7592 if (len > src->len - src->index)
7593 return -1;
7595 memcpy (buf, src->bytes + src->index, len);
7596 src->index += len;
7597 return len;
7600 static int
7601 gif_close (GifFileType *gif, int *err)
7603 int retval;
7605 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7606 retval = DGifCloseFile (gif, err);
7607 #else
7608 retval = DGifCloseFile (gif);
7609 #if GIFLIB_MAJOR >= 5
7610 if (err)
7611 *err = gif->Error;
7612 #endif
7613 #endif
7614 return retval;
7617 /* Load GIF image IMG for use on frame F. Value is true if
7618 successful. */
7620 static const int interlace_start[] = {0, 4, 2, 1};
7621 static const int interlace_increment[] = {8, 8, 4, 2};
7623 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7625 static bool
7626 gif_load (struct frame *f, struct image *img)
7628 int rc, width, height, x, y, i, j;
7629 ColorMapObject *gif_color_map;
7630 GifFileType *gif;
7631 gif_memory_source memsrc;
7632 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7633 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7634 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7635 EMACS_INT idx;
7636 int gif_err;
7638 #ifdef USE_CAIRO
7639 unsigned char *data = 0;
7640 #else
7641 unsigned long pixel_colors[256];
7642 unsigned long bgcolor = 0;
7643 XImagePtr ximg;
7644 #endif
7646 if (NILP (specified_data))
7648 Lisp_Object file = x_find_image_file (specified_file);
7649 if (!STRINGP (file))
7651 image_error ("Cannot find image file `%s'", specified_file);
7652 return 0;
7655 Lisp_Object encoded_file = ENCODE_FILE (file);
7656 #ifdef WINDOWSNT
7657 encoded_file = ansi_encode_filename (encoded_file);
7658 #endif
7660 /* Open the GIF file. */
7661 #if GIFLIB_MAJOR < 5
7662 gif = DGifOpenFileName (SSDATA (encoded_file));
7663 #else
7664 gif = DGifOpenFileName (SSDATA (encoded_file), &gif_err);
7665 #endif
7666 if (gif == NULL)
7668 #if HAVE_GIFERRORSTRING
7669 image_error ("Cannot open `%s': %s",
7670 file, build_string (GifErrorString (gif_err)));
7671 #else
7672 image_error ("Cannot open `%s'", file);
7673 #endif
7674 return 0;
7677 else
7679 if (!STRINGP (specified_data))
7681 image_error ("Invalid image data `%s'", specified_data);
7682 return 0;
7685 /* Read from memory! */
7686 current_gif_memory_src = &memsrc;
7687 memsrc.bytes = SDATA (specified_data);
7688 memsrc.len = SBYTES (specified_data);
7689 memsrc.index = 0;
7691 #if GIFLIB_MAJOR < 5
7692 gif = DGifOpen (&memsrc, gif_read_from_memory);
7693 #else
7694 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7695 #endif
7696 if (!gif)
7698 #if HAVE_GIFERRORSTRING
7699 image_error ("Cannot open memory source `%s': %s",
7700 img->spec, build_string (GifErrorString (gif_err)));
7701 #else
7702 image_error ("Cannot open memory source `%s'", img->spec);
7703 #endif
7704 return 0;
7708 /* Before reading entire contents, check the declared image size. */
7709 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7711 image_size_error ();
7712 gif_close (gif, NULL);
7713 return 0;
7716 /* Read entire contents. */
7717 rc = DGifSlurp (gif);
7718 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7720 image_error ("Error reading `%s'", img->spec);
7721 gif_close (gif, NULL);
7722 return 0;
7725 /* Which sub-image are we to display? */
7727 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7728 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7729 if (idx < 0 || idx >= gif->ImageCount)
7731 image_error ("Invalid image number `%s' in image `%s'",
7732 image_number, img->spec);
7733 gif_close (gif, NULL);
7734 return 0;
7738 width = img->width = gif->SWidth;
7739 height = img->height = gif->SHeight;
7741 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7742 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7743 img->corners[BOT_CORNER]
7744 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7745 img->corners[RIGHT_CORNER]
7746 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7748 if (!check_image_size (f, width, height))
7750 image_size_error ();
7751 gif_close (gif, NULL);
7752 return 0;
7755 /* Check that the selected subimages fit. It's not clear whether
7756 the GIF spec requires this, but Emacs can crash if they don't fit. */
7757 for (j = 0; j <= idx; ++j)
7759 struct SavedImage *subimage = gif->SavedImages + j;
7760 int subimg_width = subimage->ImageDesc.Width;
7761 int subimg_height = subimage->ImageDesc.Height;
7762 int subimg_top = subimage->ImageDesc.Top;
7763 int subimg_left = subimage->ImageDesc.Left;
7764 if (! (subimg_width >= 0 && subimg_height >= 0
7765 && 0 <= subimg_top && subimg_top <= height - subimg_height
7766 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7768 image_error ("Subimage does not fit in image");
7769 gif_close (gif, NULL);
7770 return 0;
7774 #ifdef USE_CAIRO
7775 /* xzalloc so data is zero => transparent */
7776 data = (unsigned char *) xzalloc (width * height * 4);
7777 if (STRINGP (specified_bg))
7779 XColor color;
7780 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
7782 uint32_t *dataptr = (uint32_t *)data;
7783 int r = color.red/256;
7784 int g = color.green/256;
7785 int b = color.blue/256;
7787 for (y = 0; y < height; ++y)
7788 for (x = 0; x < width; ++x)
7789 *dataptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
7792 #else
7793 /* Create the X image and pixmap. */
7794 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7796 gif_close (gif, NULL);
7797 return 0;
7800 /* Clear the part of the screen image not covered by the image.
7801 Full animated GIF support requires more here (see the gif89 spec,
7802 disposal methods). Let's simply assume that the part not covered
7803 by a sub-image is in the frame's background color. */
7804 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7805 for (x = 0; x < width; ++x)
7806 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7808 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7809 for (x = 0; x < width; ++x)
7810 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7812 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7814 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7815 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7816 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7817 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7819 #endif
7821 /* Read the GIF image into the X image. */
7823 /* FIXME: With the current implementation, loading an animated gif
7824 is quadratic in the number of animation frames, since each frame
7825 is a separate struct image. We must provide a way for a single
7826 gif_load call to construct and save all animation frames. */
7828 init_color_table ();
7830 #ifndef USE_CAIRO
7831 if (STRINGP (specified_bg))
7832 bgcolor = x_alloc_image_color (f, img, specified_bg,
7833 FRAME_BACKGROUND_PIXEL (f));
7834 #endif
7836 for (j = 0; j <= idx; ++j)
7838 /* We use a local variable `raster' here because RasterBits is a
7839 char *, which invites problems with bytes >= 0x80. */
7840 struct SavedImage *subimage = gif->SavedImages + j;
7841 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7842 int transparency_color_index = -1;
7843 int disposal = 0;
7844 int subimg_width = subimage->ImageDesc.Width;
7845 int subimg_height = subimage->ImageDesc.Height;
7846 int subimg_top = subimage->ImageDesc.Top;
7847 int subimg_left = subimage->ImageDesc.Left;
7849 /* Find the Graphic Control Extension block for this sub-image.
7850 Extract the disposal method and transparency color. */
7851 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7853 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7855 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7856 && extblock->ByteCount == 4
7857 && extblock->Bytes[0] & 1)
7859 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7860 to background". Treat any other value like 2. */
7861 disposal = (extblock->Bytes[0] >> 2) & 7;
7862 transparency_color_index = (unsigned char) extblock->Bytes[3];
7863 break;
7867 /* We can't "keep in place" the first subimage. */
7868 if (j == 0)
7869 disposal = 2;
7871 /* For disposal == 0, the spec says "No disposal specified. The
7872 decoder is not required to take any action." In practice, it
7873 seems we need to treat this like "keep in place", see e.g.
7874 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7875 if (disposal == 0)
7876 disposal = 1;
7878 gif_color_map = subimage->ImageDesc.ColorMap;
7879 if (!gif_color_map)
7880 gif_color_map = gif->SColorMap;
7882 #ifndef USE_CAIRO
7883 /* Allocate subimage colors. */
7884 memset (pixel_colors, 0, sizeof pixel_colors);
7886 if (gif_color_map)
7887 for (i = 0; i < gif_color_map->ColorCount; ++i)
7889 if (transparency_color_index == i)
7890 pixel_colors[i] = STRINGP (specified_bg)
7891 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7892 else
7894 int r = gif_color_map->Colors[i].Red << 8;
7895 int g = gif_color_map->Colors[i].Green << 8;
7896 int b = gif_color_map->Colors[i].Blue << 8;
7897 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7900 #endif
7902 /* Apply the pixel values. */
7903 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7905 int row, pass;
7907 for (y = 0, row = interlace_start[0], pass = 0;
7908 y < subimg_height;
7909 y++, row += interlace_increment[pass])
7911 while (subimg_height <= row)
7912 row = interlace_start[++pass];
7914 for (x = 0; x < subimg_width; x++)
7916 int c = raster[y * subimg_width + x];
7917 if (transparency_color_index != c || disposal != 1)
7919 #ifdef USE_CAIRO
7920 uint32_t *dataptr =
7921 ((uint32_t*)data + ((row + subimg_top) * subimg_width
7922 + x + subimg_left));
7923 int r = gif_color_map->Colors[c].Red;
7924 int g = gif_color_map->Colors[c].Green;
7925 int b = gif_color_map->Colors[c].Blue;
7927 if (transparency_color_index != c)
7928 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7929 #else
7930 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7931 pixel_colors[c]);
7932 #endif
7937 else
7939 for (y = 0; y < subimg_height; ++y)
7940 for (x = 0; x < subimg_width; ++x)
7942 int c = raster[y * subimg_width + x];
7943 if (transparency_color_index != c || disposal != 1)
7945 #ifdef USE_CAIRO
7946 uint32_t *dataptr =
7947 ((uint32_t*)data + ((y + subimg_top) * subimg_width
7948 + x + subimg_left));
7949 int r = gif_color_map->Colors[c].Red;
7950 int g = gif_color_map->Colors[c].Green;
7951 int b = gif_color_map->Colors[c].Blue;
7952 if (transparency_color_index != c)
7953 *dataptr = (0xff << 24) | (r << 16) | (g << 8) | b;
7954 #else
7955 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7956 pixel_colors[c]);
7957 #endif
7963 #ifdef COLOR_TABLE_SUPPORT
7964 img->colors = colors_in_color_table (&img->ncolors);
7965 free_color_table ();
7966 #endif /* COLOR_TABLE_SUPPORT */
7968 /* Save GIF image extension data for `image-metadata'.
7969 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7970 img->lisp_data = Qnil;
7971 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7973 int delay = 0;
7974 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7975 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7976 /* Append (... FUNCTION "BYTES") */
7978 img->lisp_data
7979 = Fcons (make_number (ext->Function),
7980 Fcons (make_unibyte_string ((char *) ext->Bytes,
7981 ext->ByteCount),
7982 img->lisp_data));
7983 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7984 && ext->ByteCount == 4)
7986 delay = ext->Bytes[2] << CHAR_BIT;
7987 delay |= ext->Bytes[1];
7990 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7991 if (delay)
7992 img->lisp_data
7993 = Fcons (Qdelay,
7994 Fcons (make_float (delay / 100.0),
7995 img->lisp_data));
7998 if (gif->ImageCount > 1)
7999 img->lisp_data = Fcons (Qcount,
8000 Fcons (make_number (gif->ImageCount),
8001 img->lisp_data));
8003 if (gif_close (gif, &gif_err) == GIF_ERROR)
8005 #if HAVE_GIFERRORSTRING
8006 char const *error_text = GifErrorString (gif_err);
8008 if (error_text)
8009 image_error ("Error closing `%s': %s",
8010 img->spec, build_string (error_text));
8011 #else
8012 image_error ("Error closing `%s'", img->spec);
8013 #endif
8016 #ifdef USE_CAIRO
8017 create_cairo_image_surface (img, data, width, height);
8018 #else
8019 /* Maybe fill in the background field while we have ximg handy. */
8020 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8021 /* Casting avoids a GCC warning. */
8022 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8024 /* Put ximg into the image. */
8025 image_put_x_image (f, img, ximg, 0);
8026 #endif
8028 return 1;
8031 #else /* !HAVE_GIF */
8033 #ifdef HAVE_NS
8034 static bool
8035 gif_load (struct frame *f, struct image *img)
8037 return ns_load_image (f, img,
8038 image_spec_value (img->spec, QCfile, NULL),
8039 image_spec_value (img->spec, QCdata, NULL));
8041 #endif /* HAVE_NS */
8043 #endif /* HAVE_GIF */
8046 #ifdef HAVE_IMAGEMAGICK
8048 /***********************************************************************
8049 ImageMagick
8050 ***********************************************************************/
8052 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8053 safely rounded and clipped to int range. */
8055 static int
8056 scale_image_size (int size, size_t divisor, size_t multiplier)
8058 if (divisor != 0)
8060 double s = size;
8061 double scaled = s * multiplier / divisor + 0.5;
8062 if (scaled < INT_MAX)
8063 return scaled;
8065 return INT_MAX;
8068 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8069 Use SPEC to deduce the size. Store the desired size into
8070 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8071 static void
8072 compute_image_size (size_t width, size_t height,
8073 Lisp_Object spec,
8074 int *d_width, int *d_height)
8076 Lisp_Object value;
8077 int desired_width, desired_height;
8078 double scale = 1;
8080 value = image_spec_value (spec, QCscale, NULL);
8081 if (NUMBERP (value))
8082 scale = extract_float (value);
8084 /* If width and/or height is set in the display spec assume we want
8085 to scale to those values. If either h or w is unspecified, the
8086 unspecified should be calculated from the specified to preserve
8087 aspect ratio. */
8088 value = image_spec_value (spec, QCwidth, NULL);
8089 desired_width = NATNUMP (value) ?
8090 min (XFASTINT (value) * scale, INT_MAX) : -1;
8091 value = image_spec_value (spec, QCheight, NULL);
8092 desired_height = NATNUMP (value) ?
8093 min (XFASTINT (value) * scale, INT_MAX) : -1;
8095 width = width * scale;
8096 height = height * scale;
8098 if (desired_width == -1)
8100 value = image_spec_value (spec, QCmax_width, NULL);
8101 if (NATNUMP (value))
8103 int max_width = min (XFASTINT (value), INT_MAX);
8104 if (max_width < width)
8106 /* The image is wider than :max-width. */
8107 desired_width = max_width;
8108 if (desired_height == -1)
8110 desired_height = scale_image_size (desired_width,
8111 width, height);
8112 value = image_spec_value (spec, QCmax_height, NULL);
8113 if (NATNUMP (value))
8115 int max_height = min (XFASTINT (value), INT_MAX);
8116 if (max_height < desired_height)
8118 desired_height = max_height;
8119 desired_width = scale_image_size (desired_height,
8120 height, width);
8128 if (desired_height == -1)
8130 value = image_spec_value (spec, QCmax_height, NULL);
8131 if (NATNUMP (value))
8133 int max_height = min (XFASTINT (value), INT_MAX);
8134 if (max_height < height)
8135 desired_height = max_height;
8139 if (desired_width != -1 && desired_height == -1)
8140 /* w known, calculate h. */
8141 desired_height = scale_image_size (desired_width, width, height);
8143 if (desired_width == -1 && desired_height != -1)
8144 /* h known, calculate w. */
8145 desired_width = scale_image_size (desired_height, height, width);
8147 /* We have no width/height settings, so just apply the scale. */
8148 if (desired_width == -1 && desired_height == -1)
8150 desired_width = width;
8151 desired_height = height;
8154 *d_width = desired_width;
8155 *d_height = desired_height;
8158 static bool imagemagick_image_p (Lisp_Object);
8159 static bool imagemagick_load (struct frame *, struct image *);
8160 static void imagemagick_clear_image (struct frame *, struct image *);
8162 /* Indices of image specification fields in imagemagick_format. */
8164 enum imagemagick_keyword_index
8166 IMAGEMAGICK_TYPE,
8167 IMAGEMAGICK_DATA,
8168 IMAGEMAGICK_FILE,
8169 IMAGEMAGICK_ASCENT,
8170 IMAGEMAGICK_MARGIN,
8171 IMAGEMAGICK_RELIEF,
8172 IMAGEMAGICK_ALGORITHM,
8173 IMAGEMAGICK_HEURISTIC_MASK,
8174 IMAGEMAGICK_MASK,
8175 IMAGEMAGICK_BACKGROUND,
8176 IMAGEMAGICK_HEIGHT,
8177 IMAGEMAGICK_WIDTH,
8178 IMAGEMAGICK_MAX_HEIGHT,
8179 IMAGEMAGICK_MAX_WIDTH,
8180 IMAGEMAGICK_FORMAT,
8181 IMAGEMAGICK_ROTATION,
8182 IMAGEMAGICK_CROP,
8183 IMAGEMAGICK_LAST
8186 /* Vector of image_keyword structures describing the format
8187 of valid user-defined image specifications. */
8189 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
8191 {":type", IMAGE_SYMBOL_VALUE, 1},
8192 {":data", IMAGE_STRING_VALUE, 0},
8193 {":file", IMAGE_STRING_VALUE, 0},
8194 {":ascent", IMAGE_ASCENT_VALUE, 0},
8195 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8196 {":relief", IMAGE_INTEGER_VALUE, 0},
8197 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8198 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8199 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8200 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8201 {":height", IMAGE_INTEGER_VALUE, 0},
8202 {":width", IMAGE_INTEGER_VALUE, 0},
8203 {":max-height", IMAGE_INTEGER_VALUE, 0},
8204 {":max-width", IMAGE_INTEGER_VALUE, 0},
8205 {":format", IMAGE_SYMBOL_VALUE, 0},
8206 {":rotation", IMAGE_NUMBER_VALUE, 0},
8207 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8210 #if defined HAVE_NTGUI && defined WINDOWSNT
8211 static bool init_imagemagick_functions (void);
8212 #else
8213 #define init_imagemagick_functions NULL
8214 #endif
8216 /* Structure describing the image type for any image handled via
8217 ImageMagick. */
8219 static struct image_type imagemagick_type =
8221 SYMBOL_INDEX (Qimagemagick),
8222 imagemagick_image_p,
8223 imagemagick_load,
8224 imagemagick_clear_image,
8225 init_imagemagick_functions,
8226 NULL
8229 /* Free X resources of imagemagick image IMG which is used on frame F. */
8231 static void
8232 imagemagick_clear_image (struct frame *f,
8233 struct image *img)
8235 x_clear_image (f, img);
8238 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8239 this by calling parse_image_spec and supplying the keywords that
8240 identify the IMAGEMAGICK format. */
8242 static bool
8243 imagemagick_image_p (Lisp_Object object)
8245 struct image_keyword fmt[IMAGEMAGICK_LAST];
8246 memcpy (fmt, imagemagick_format, sizeof fmt);
8248 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
8249 return 0;
8251 /* Must specify either the :data or :file keyword. */
8252 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
8255 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8256 Therefore rename the function so it doesn't collide with ImageMagick. */
8257 #define DrawRectangle DrawRectangleGif
8258 #include <wand/MagickWand.h>
8260 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8261 Emacs seems to work fine with the hidden version, so unhide it. */
8262 #include <magick/version.h>
8263 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8264 extern WandExport void PixelGetMagickColor (const PixelWand *,
8265 MagickPixelPacket *);
8266 #endif
8268 /* Log ImageMagick error message.
8269 Useful when a ImageMagick function returns the status `MagickFalse'. */
8271 static void
8272 imagemagick_error (MagickWand *wand)
8274 char *description;
8275 ExceptionType severity;
8277 description = MagickGetException (wand, &severity);
8278 image_error ("ImageMagick error: %s", build_string (description));
8279 MagickRelinquishMemory (description);
8282 /* Possibly give ImageMagick some extra help to determine the image
8283 type by supplying a "dummy" filename based on the Content-Type. */
8285 static char *
8286 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
8288 Lisp_Object symbol = intern ("image-format-suffixes");
8289 Lisp_Object val = find_symbol_value (symbol);
8290 Lisp_Object format;
8292 if (! CONSP (val))
8293 return NULL;
8295 format = image_spec_value (spec, intern (":format"), NULL);
8296 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
8297 if (! STRINGP (val))
8298 return NULL;
8300 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8301 as ImageMagick would ignore the extra bytes anyway. */
8302 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
8303 return hint_buffer;
8306 /* Animated images (e.g., GIF89a) are composed from one "master image"
8307 (which is the first one, and then there's a number of images that
8308 follow. If following images have non-transparent colors, these are
8309 composed "on top" of the master image. So, in general, one has to
8310 compute ann the preceding images to be able to display a particular
8311 sub-image.
8313 Computing all the preceding images is too slow, so we maintain a
8314 cache of previously computed images. We have to maintain a cache
8315 separate from the image cache, because the images may be scaled
8316 before display. */
8318 struct animation_cache
8320 MagickWand *wand;
8321 int index;
8322 struct timespec update_time;
8323 struct animation_cache *next;
8324 char signature[FLEXIBLE_ARRAY_MEMBER];
8327 static struct animation_cache *animation_cache = NULL;
8329 static struct animation_cache *
8330 imagemagick_create_cache (char *signature)
8332 struct animation_cache *cache
8333 = xmalloc (FLEXSIZEOF (struct animation_cache, signature,
8334 strlen (signature) + 1));
8335 cache->wand = 0;
8336 cache->index = 0;
8337 cache->next = 0;
8338 strcpy (cache->signature, signature);
8339 return cache;
8342 /* Discard cached images that haven't been used for a minute. */
8343 static void
8344 imagemagick_prune_animation_cache (void)
8346 struct animation_cache **pcache = &animation_cache;
8347 struct timespec old = timespec_sub (current_timespec (),
8348 make_timespec (60, 0));
8350 while (*pcache)
8352 struct animation_cache *cache = *pcache;
8353 if (timespec_cmp (old, cache->update_time) <= 0)
8354 pcache = &cache->next;
8355 else
8357 if (cache->wand)
8358 DestroyMagickWand (cache->wand);
8359 *pcache = cache->next;
8360 xfree (cache);
8365 static struct animation_cache *
8366 imagemagick_get_animation_cache (MagickWand *wand)
8368 char *signature = MagickGetImageSignature (wand);
8369 struct animation_cache *cache;
8370 struct animation_cache **pcache = &animation_cache;
8372 imagemagick_prune_animation_cache ();
8374 while (1)
8376 cache = *pcache;
8377 if (! cache)
8379 *pcache = cache = imagemagick_create_cache (signature);
8380 break;
8382 if (strcmp (signature, cache->signature) == 0)
8383 break;
8384 pcache = &cache->next;
8387 DestroyString (signature);
8388 cache->update_time = current_timespec ();
8389 return cache;
8392 static MagickWand *
8393 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8395 int i;
8396 MagickWand *composite_wand;
8397 size_t dest_width, dest_height;
8398 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8400 MagickSetIteratorIndex (super_wand, 0);
8402 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8404 composite_wand = MagickGetImage (super_wand);
8405 if (cache->wand)
8406 DestroyMagickWand (cache->wand);
8408 else
8409 composite_wand = cache->wand;
8411 dest_height = MagickGetImageHeight (composite_wand);
8413 for (i = max (1, cache->index + 1); i <= ino; i++)
8415 MagickWand *sub_wand;
8416 PixelIterator *source_iterator, *dest_iterator;
8417 PixelWand **source, **dest;
8418 size_t source_width, source_height;
8419 ssize_t source_left, source_top;
8420 MagickPixelPacket pixel;
8421 DisposeType dispose;
8422 ptrdiff_t lines = 0;
8424 MagickSetIteratorIndex (super_wand, i);
8425 sub_wand = MagickGetImage (super_wand);
8427 MagickGetImagePage (sub_wand, &source_width, &source_height,
8428 &source_left, &source_top);
8430 /* This flag says how to handle transparent pixels. */
8431 dispose = MagickGetImageDispose (sub_wand);
8433 source_iterator = NewPixelIterator (sub_wand);
8434 if (! source_iterator)
8436 DestroyMagickWand (composite_wand);
8437 DestroyMagickWand (sub_wand);
8438 cache->wand = NULL;
8439 image_error ("Imagemagick pixel iterator creation failed");
8440 return NULL;
8443 dest_iterator = NewPixelIterator (composite_wand);
8444 if (! dest_iterator)
8446 DestroyMagickWand (composite_wand);
8447 DestroyMagickWand (sub_wand);
8448 DestroyPixelIterator (source_iterator);
8449 cache->wand = NULL;
8450 image_error ("Imagemagick pixel iterator creation failed");
8451 return NULL;
8454 /* The sub-image may not start at origin, so move the destination
8455 iterator to where the sub-image should start. */
8456 if (source_top > 0)
8458 PixelSetIteratorRow (dest_iterator, source_top);
8459 lines = source_top;
8462 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8463 != NULL)
8465 ptrdiff_t x;
8467 /* Sanity check. This shouldn't happen, but apparently
8468 does in some pictures. */
8469 if (++lines >= dest_height)
8470 break;
8472 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8473 for (x = 0; x < source_width; x++)
8475 /* Sanity check. This shouldn't happen, but apparently
8476 also does in some pictures. */
8477 if (x + source_left >= dest_width)
8478 break;
8479 /* Normally we only copy over non-transparent pixels,
8480 but if the disposal method is "Background", then we
8481 copy over all pixels. */
8482 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8484 PixelGetMagickColor (source[x], &pixel);
8485 PixelSetMagickColor (dest[x + source_left], &pixel);
8488 PixelSyncIterator (dest_iterator);
8491 DestroyPixelIterator (source_iterator);
8492 DestroyPixelIterator (dest_iterator);
8493 DestroyMagickWand (sub_wand);
8496 /* Cache a copy for the next iteration. The current wand will be
8497 destroyed by the caller. */
8498 cache->wand = CloneMagickWand (composite_wand);
8499 cache->index = ino;
8501 return composite_wand;
8505 /* Helper function for imagemagick_load, which does the actual loading
8506 given contents and size, apart from frame and image structures,
8507 passed from imagemagick_load. Uses librimagemagick to do most of
8508 the image processing.
8510 F is a pointer to the Emacs frame; IMG to the image structure to
8511 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8512 be parsed; SIZE is the number of bytes of data; and FILENAME is
8513 either the file name or the image data.
8515 Return true if successful. */
8517 static bool
8518 imagemagick_load_image (struct frame *f, struct image *img,
8519 unsigned char *contents, unsigned int size,
8520 char *filename)
8522 int width, height;
8523 size_t image_width, image_height;
8524 MagickBooleanType status;
8525 XImagePtr ximg;
8526 int x, y;
8527 MagickWand *image_wand;
8528 PixelIterator *iterator;
8529 PixelWand **pixels, *bg_wand = NULL;
8530 MagickPixelPacket pixel;
8531 Lisp_Object image;
8532 Lisp_Object value;
8533 Lisp_Object crop;
8534 EMACS_INT ino;
8535 int desired_width, desired_height;
8536 double rotation;
8537 int pixelwidth;
8538 char hint_buffer[MaxTextExtent];
8539 char *filename_hint = NULL;
8541 /* Handle image index for image types who can contain more than one image.
8542 Interface :index is same as for GIF. First we "ping" the image to see how
8543 many sub-images it contains. Pinging is faster than loading the image to
8544 find out things about it. */
8546 /* Initialize the imagemagick environment. */
8547 MagickWandGenesis ();
8548 image = image_spec_value (img->spec, QCindex, NULL);
8549 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8550 image_wand = NewMagickWand ();
8552 if (filename)
8553 status = MagickReadImage (image_wand, filename);
8554 else
8556 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8557 MagickSetFilename (image_wand, filename_hint);
8558 status = MagickReadImageBlob (image_wand, contents, size);
8561 if (status == MagickFalse)
8563 imagemagick_error (image_wand);
8564 DestroyMagickWand (image_wand);
8565 return 0;
8568 #ifdef HAVE_MAGICKAUTOORIENTIMAGE
8569 /* If no :rotation is explicitly specified, apply the automatic
8570 rotation from EXIF. */
8571 if (NILP (image_spec_value (img->spec, QCrotation, NULL)))
8572 if (MagickAutoOrientImage (image_wand) == MagickFalse)
8574 image_error ("Error applying automatic orientation in image `%s'", img->spec);
8575 DestroyMagickWand (image_wand);
8576 return 0;
8578 #endif
8580 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8582 image_error ("Invalid image number `%s' in image `%s'", image, img->spec);
8583 DestroyMagickWand (image_wand);
8584 return 0;
8587 if (MagickGetImageDelay (image_wand) > 0)
8588 img->lisp_data =
8589 Fcons (Qdelay,
8590 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8591 img->lisp_data));
8593 if (MagickGetNumberImages (image_wand) > 1)
8594 img->lisp_data =
8595 Fcons (Qcount,
8596 Fcons (make_number (MagickGetNumberImages (image_wand)),
8597 img->lisp_data));
8599 /* If we have an animated image, get the new wand based on the
8600 "super-wand". */
8601 if (MagickGetNumberImages (image_wand) > 1)
8603 MagickWand *super_wand = image_wand;
8604 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8605 if (! image_wand)
8606 image_wand = super_wand;
8607 else
8608 DestroyMagickWand (super_wand);
8611 /* Retrieve the frame's background color, for use later. */
8613 XColor bgcolor;
8614 Lisp_Object specified_bg;
8616 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8617 if (!STRINGP (specified_bg)
8618 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8619 x_query_frame_background_color (f, &bgcolor);
8621 bg_wand = NewPixelWand ();
8622 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8623 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8624 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8627 compute_image_size (MagickGetImageWidth (image_wand),
8628 MagickGetImageHeight (image_wand),
8629 img->spec, &desired_width, &desired_height);
8631 if (desired_width != -1 && desired_height != -1)
8633 status = MagickScaleImage (image_wand, desired_width, desired_height);
8634 if (status == MagickFalse)
8636 image_error ("Imagemagick scale failed");
8637 imagemagick_error (image_wand);
8638 goto imagemagick_error;
8642 /* crop behaves similar to image slicing in Emacs but is more memory
8643 efficient. */
8644 crop = image_spec_value (img->spec, QCcrop, NULL);
8646 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8648 /* After some testing, it seems MagickCropImage is the fastest crop
8649 function in ImageMagick. This crop function seems to do less copying
8650 than the alternatives, but it still reads the entire image into memory
8651 before cropping, which is apparently difficult to avoid when using
8652 imagemagick. */
8653 size_t crop_width = XINT (XCAR (crop));
8654 crop = XCDR (crop);
8655 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8657 size_t crop_height = XINT (XCAR (crop));
8658 crop = XCDR (crop);
8659 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8661 ssize_t crop_x = XINT (XCAR (crop));
8662 crop = XCDR (crop);
8663 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8665 ssize_t crop_y = XINT (XCAR (crop));
8666 MagickCropImage (image_wand, crop_width, crop_height,
8667 crop_x, crop_y);
8673 /* Furthermore :rotation. we need background color and angle for
8674 rotation. */
8676 TODO background handling for rotation specified_bg =
8677 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8678 (specified_bg). */
8679 value = image_spec_value (img->spec, QCrotation, NULL);
8680 if (FLOATP (value))
8682 rotation = extract_float (value);
8683 status = MagickRotateImage (image_wand, bg_wand, rotation);
8684 if (status == MagickFalse)
8686 image_error ("Imagemagick image rotate failed");
8687 imagemagick_error (image_wand);
8688 goto imagemagick_error;
8692 /* Set the canvas background color to the frame or specified
8693 background, and flatten the image. Note: as of ImageMagick
8694 6.6.0, SVG image transparency is not handled properly
8695 (e.g. etc/images/splash.svg shows a white background always). */
8697 MagickWand *new_wand;
8698 MagickSetImageBackgroundColor (image_wand, bg_wand);
8699 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8700 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8701 #else
8702 new_wand = MagickFlattenImages (image_wand);
8703 #endif
8704 DestroyMagickWand (image_wand);
8705 image_wand = new_wand;
8708 /* Finally we are done manipulating the image. Figure out the
8709 resulting width/height and transfer ownership to Emacs. */
8710 image_height = MagickGetImageHeight (image_wand);
8711 image_width = MagickGetImageWidth (image_wand);
8713 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8714 && check_image_size (f, image_width, image_height)))
8716 image_size_error ();
8717 goto imagemagick_error;
8720 width = image_width;
8721 height = image_height;
8723 /* We can now get a valid pixel buffer from the imagemagick file, if all
8724 went ok. */
8726 init_color_table ();
8728 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8729 if (imagemagick_render_type != 0)
8731 /* Magicexportimage is normally faster than pixelpushing. This
8732 method is also well tested. Some aspects of this method are
8733 ad-hoc and needs to be more researched. */
8734 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8735 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8736 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8737 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8738 &ximg, 0))
8740 #ifdef COLOR_TABLE_SUPPORT
8741 free_color_table ();
8742 #endif
8743 image_error ("Imagemagick X bitmap allocation failure");
8744 goto imagemagick_error;
8747 /* Oddly, the below code doesn't seem to work:*/
8748 /* switch(ximg->bitmap_unit){ */
8749 /* case 8: */
8750 /* pixelwidth=CharPixel; */
8751 /* break; */
8752 /* case 16: */
8753 /* pixelwidth=ShortPixel; */
8754 /* break; */
8755 /* case 32: */
8756 /* pixelwidth=LongPixel; */
8757 /* break; */
8758 /* } */
8760 Here im just guessing the format of the bitmap.
8761 happens to work fine for:
8762 - bw djvu images
8763 on rgb display.
8764 seems about 3 times as fast as pixel pushing(not carefully measured)
8766 pixelwidth = CharPixel; /*??? TODO figure out*/
8767 MagickExportImagePixels (image_wand, 0, 0, width, height,
8768 exportdepth, pixelwidth, ximg->data);
8770 else
8771 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8773 size_t image_height;
8774 MagickRealType color_scale = 65535.0 / QuantumRange;
8776 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8777 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8778 &ximg, 0))
8780 #ifdef COLOR_TABLE_SUPPORT
8781 free_color_table ();
8782 #endif
8783 image_error ("Imagemagick X bitmap allocation failure");
8784 goto imagemagick_error;
8787 /* Copy imagemagick image to x with primitive yet robust pixel
8788 pusher loop. This has been tested a lot with many different
8789 images. */
8791 /* Copy pixels from the imagemagick image structure to the x image map. */
8792 iterator = NewPixelIterator (image_wand);
8793 if (! iterator)
8795 #ifdef COLOR_TABLE_SUPPORT
8796 free_color_table ();
8797 #endif
8798 x_destroy_x_image (ximg);
8799 image_error ("Imagemagick pixel iterator creation failed");
8800 goto imagemagick_error;
8803 image_height = MagickGetImageHeight (image_wand);
8804 for (y = 0; y < image_height; y++)
8806 size_t row_width;
8807 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8808 if (! pixels)
8809 break;
8810 int xlim = min (row_width, width);
8811 for (x = 0; x < xlim; x++)
8813 PixelGetMagickColor (pixels[x], &pixel);
8814 XPutPixel (ximg, x, y,
8815 lookup_rgb_color (f,
8816 color_scale * pixel.red,
8817 color_scale * pixel.green,
8818 color_scale * pixel.blue));
8821 DestroyPixelIterator (iterator);
8824 #ifdef COLOR_TABLE_SUPPORT
8825 /* Remember colors allocated for this image. */
8826 img->colors = colors_in_color_table (&img->ncolors);
8827 free_color_table ();
8828 #endif /* COLOR_TABLE_SUPPORT */
8830 img->width = width;
8831 img->height = height;
8833 /* Put ximg into the image. */
8834 image_put_x_image (f, img, ximg, 0);
8836 /* Final cleanup. image_wand should be the only resource left. */
8837 DestroyMagickWand (image_wand);
8838 if (bg_wand) DestroyPixelWand (bg_wand);
8840 /* `MagickWandTerminus' terminates the imagemagick environment. */
8841 MagickWandTerminus ();
8843 return 1;
8845 imagemagick_error:
8846 DestroyMagickWand (image_wand);
8847 if (bg_wand) DestroyPixelWand (bg_wand);
8849 MagickWandTerminus ();
8850 /* TODO more cleanup. */
8851 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec);
8852 return 0;
8856 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8857 successful. this function will go into the imagemagick_type structure, and
8858 the prototype thus needs to be compatible with that structure. */
8860 static bool
8861 imagemagick_load (struct frame *f, struct image *img)
8863 bool success_p = 0;
8864 Lisp_Object file_name;
8866 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8867 file_name = image_spec_value (img->spec, QCfile, NULL);
8868 if (STRINGP (file_name))
8870 Lisp_Object file = x_find_image_file (file_name);
8871 if (!STRINGP (file))
8873 image_error ("Cannot find image file `%s'", file_name);
8874 return 0;
8876 file = ENCODE_FILE (file);
8877 #ifdef WINDOWSNT
8878 file = ansi_encode_filename (file);
8879 #endif
8880 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8882 /* Else its not a file, its a lisp object. Load the image from a
8883 lisp object rather than a file. */
8884 else
8886 Lisp_Object data;
8888 data = image_spec_value (img->spec, QCdata, NULL);
8889 if (!STRINGP (data))
8891 image_error ("Invalid image data `%s'", data);
8892 return 0;
8894 success_p = imagemagick_load_image (f, img, SDATA (data),
8895 SBYTES (data), NULL);
8898 return success_p;
8901 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8902 doc: /* Return a list of image types supported by ImageMagick.
8903 Each entry in this list is a symbol named after an ImageMagick format
8904 tag. See the ImageMagick manual for a list of ImageMagick formats and
8905 their descriptions (http://www.imagemagick.org/script/formats.php).
8906 You can also try the shell command: `identify -list format'.
8908 Note that ImageMagick recognizes many file-types that Emacs does not
8909 recognize as images, such as C. See `imagemagick-types-enable'
8910 and `imagemagick-types-inhibit'. */)
8911 (void)
8913 Lisp_Object typelist = Qnil;
8914 size_t numf = 0;
8915 ExceptionInfo *ex;
8916 char **imtypes;
8917 size_t i;
8919 ex = AcquireExceptionInfo ();
8920 imtypes = GetMagickList ("*", &numf, ex);
8921 DestroyExceptionInfo (ex);
8923 for (i = 0; i < numf; i++)
8925 Lisp_Object imagemagicktype = intern (imtypes[i]);
8926 typelist = Fcons (imagemagicktype, typelist);
8927 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8930 MagickRelinquishMemory (imtypes);
8931 return Fnreverse (typelist);
8934 #endif /* defined (HAVE_IMAGEMAGICK) */
8938 /***********************************************************************
8940 ***********************************************************************/
8942 #ifdef HAVE_RSVG
8944 /* Function prototypes. */
8946 static bool svg_image_p (Lisp_Object object);
8947 static bool svg_load (struct frame *f, struct image *img);
8949 static bool svg_load_image (struct frame *, struct image *,
8950 unsigned char *, ptrdiff_t, char *);
8952 /* Indices of image specification fields in svg_format, below. */
8954 enum svg_keyword_index
8956 SVG_TYPE,
8957 SVG_DATA,
8958 SVG_FILE,
8959 SVG_ASCENT,
8960 SVG_MARGIN,
8961 SVG_RELIEF,
8962 SVG_ALGORITHM,
8963 SVG_HEURISTIC_MASK,
8964 SVG_MASK,
8965 SVG_BACKGROUND,
8966 SVG_LAST
8969 /* Vector of image_keyword structures describing the format
8970 of valid user-defined image specifications. */
8972 static const struct image_keyword svg_format[SVG_LAST] =
8974 {":type", IMAGE_SYMBOL_VALUE, 1},
8975 {":data", IMAGE_STRING_VALUE, 0},
8976 {":file", IMAGE_STRING_VALUE, 0},
8977 {":ascent", IMAGE_ASCENT_VALUE, 0},
8978 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8979 {":relief", IMAGE_INTEGER_VALUE, 0},
8980 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8981 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8982 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8983 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8986 # if defined HAVE_NTGUI && defined WINDOWSNT
8987 static bool init_svg_functions (void);
8988 # else
8989 #define init_svg_functions NULL
8990 # endif
8992 /* Structure describing the image type `svg'. Its the same type of
8993 structure defined for all image formats, handled by emacs image
8994 functions. See struct image_type in dispextern.h. */
8996 static struct image_type svg_type =
8998 SYMBOL_INDEX (Qsvg),
8999 svg_image_p,
9000 svg_load,
9001 x_clear_image,
9002 init_svg_functions,
9003 NULL
9007 /* Return true if OBJECT is a valid SVG image specification. Do
9008 this by calling parse_image_spec and supplying the keywords that
9009 identify the SVG format. */
9011 static bool
9012 svg_image_p (Lisp_Object object)
9014 struct image_keyword fmt[SVG_LAST];
9015 memcpy (fmt, svg_format, sizeof fmt);
9017 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
9018 return 0;
9020 /* Must specify either the :data or :file keyword. */
9021 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
9024 # include <librsvg/rsvg.h>
9026 # ifdef WINDOWSNT
9028 /* SVG library functions. */
9029 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
9030 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
9031 (RsvgHandle *, RsvgDimensionData *));
9032 DEF_DLL_FN (gboolean, rsvg_handle_write,
9033 (RsvgHandle *, const guchar *, gsize, GError **));
9034 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
9035 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
9036 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
9038 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
9039 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
9040 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
9041 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
9042 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
9043 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
9044 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
9045 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
9047 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9048 DEF_DLL_FN (void, g_type_init, (void));
9049 # endif
9050 DEF_DLL_FN (void, g_object_unref, (gpointer));
9051 DEF_DLL_FN (void, g_clear_error, (GError **));
9053 static bool
9054 init_svg_functions (void)
9056 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
9058 if (!(glib = w32_delayed_load (Qglib))
9059 || !(gobject = w32_delayed_load (Qgobject))
9060 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
9061 || !(library = w32_delayed_load (Qsvg)))
9063 if (gdklib) FreeLibrary (gdklib);
9064 if (gobject) FreeLibrary (gobject);
9065 if (glib) FreeLibrary (glib);
9066 return 0;
9069 LOAD_DLL_FN (library, rsvg_handle_new);
9070 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
9071 LOAD_DLL_FN (library, rsvg_handle_write);
9072 LOAD_DLL_FN (library, rsvg_handle_close);
9073 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
9074 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
9076 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
9077 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
9078 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
9079 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
9080 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
9081 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
9082 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
9083 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
9085 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9086 LOAD_DLL_FN (gobject, g_type_init);
9087 # endif
9088 LOAD_DLL_FN (gobject, g_object_unref);
9089 LOAD_DLL_FN (glib, g_clear_error);
9091 return 1;
9094 /* The following aliases for library functions allow dynamic loading
9095 to be used on some platforms. */
9097 # undef gdk_pixbuf_get_bits_per_sample
9098 # undef gdk_pixbuf_get_colorspace
9099 # undef gdk_pixbuf_get_has_alpha
9100 # undef gdk_pixbuf_get_height
9101 # undef gdk_pixbuf_get_n_channels
9102 # undef gdk_pixbuf_get_pixels
9103 # undef gdk_pixbuf_get_rowstride
9104 # undef gdk_pixbuf_get_width
9105 # undef g_clear_error
9106 # undef g_object_unref
9107 # undef g_type_init
9108 # undef rsvg_handle_close
9109 # undef rsvg_handle_get_dimensions
9110 # undef rsvg_handle_get_pixbuf
9111 # undef rsvg_handle_new
9112 # undef rsvg_handle_set_base_uri
9113 # undef rsvg_handle_write
9115 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9116 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9117 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9118 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9119 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9120 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9121 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9122 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9123 # define g_clear_error fn_g_clear_error
9124 # define g_object_unref fn_g_object_unref
9125 # define g_type_init fn_g_type_init
9126 # define rsvg_handle_close fn_rsvg_handle_close
9127 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9128 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9129 # define rsvg_handle_new fn_rsvg_handle_new
9130 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9131 # define rsvg_handle_write fn_rsvg_handle_write
9133 # endif /* !WINDOWSNT */
9135 /* Load SVG image IMG for use on frame F. Value is true if
9136 successful. */
9138 static bool
9139 svg_load (struct frame *f, struct image *img)
9141 bool success_p = 0;
9142 Lisp_Object file_name;
9144 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9145 file_name = image_spec_value (img->spec, QCfile, NULL);
9146 if (STRINGP (file_name))
9148 int fd;
9149 Lisp_Object file = x_find_image_fd (file_name, &fd);
9150 if (!STRINGP (file))
9152 image_error ("Cannot find image file `%s'", file_name);
9153 return 0;
9156 /* Read the entire file into memory. */
9157 ptrdiff_t size;
9158 unsigned char *contents = slurp_file (fd, &size);
9159 if (contents == NULL)
9161 image_error ("Error loading SVG image `%s'", file);
9162 return 0;
9164 /* If the file was slurped into memory properly, parse it. */
9165 success_p = svg_load_image (f, img, contents, size,
9166 SSDATA (ENCODE_FILE (file)));
9167 xfree (contents);
9169 /* Else its not a file, its a lisp object. Load the image from a
9170 lisp object rather than a file. */
9171 else
9173 Lisp_Object data, original_filename;
9175 data = image_spec_value (img->spec, QCdata, NULL);
9176 if (!STRINGP (data))
9178 image_error ("Invalid image data `%s'", data);
9179 return 0;
9181 original_filename = BVAR (current_buffer, filename);
9182 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data),
9183 (NILP (original_filename) ? NULL
9184 : SSDATA (original_filename)));
9187 return success_p;
9190 /* svg_load_image is a helper function for svg_load, which does the
9191 actual loading given contents and size, apart from frame and image
9192 structures, passed from svg_load.
9194 Uses librsvg to do most of the image processing.
9196 Returns true when successful. */
9197 static bool
9198 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
9199 struct image *img, /* Pointer to emacs image structure. */
9200 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
9201 ptrdiff_t size, /* Size of data in bytes. */
9202 char *filename) /* Name of SVG file being loaded. */
9204 RsvgHandle *rsvg_handle;
9205 RsvgDimensionData dimension_data;
9206 GError *err = NULL;
9207 GdkPixbuf *pixbuf;
9208 int width;
9209 int height;
9210 const guint8 *pixels;
9211 int rowstride;
9213 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9214 /* g_type_init is a glib function that must be called prior to
9215 using gnome type library functions (obsolete since 2.36.0). */
9216 g_type_init ();
9217 #endif
9219 /* Make a handle to a new rsvg object. */
9220 rsvg_handle = rsvg_handle_new ();
9222 /* Set base_uri for properly handling referenced images (via 'href').
9223 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9224 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9225 if (filename)
9226 rsvg_handle_set_base_uri(rsvg_handle, filename);
9228 /* Parse the contents argument and fill in the rsvg_handle. */
9229 rsvg_handle_write (rsvg_handle, contents, size, &err);
9230 if (err) goto rsvg_error;
9232 /* The parsing is complete, rsvg_handle is ready to used, close it
9233 for further writes. */
9234 rsvg_handle_close (rsvg_handle, &err);
9235 if (err) goto rsvg_error;
9237 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
9238 if (! check_image_size (f, dimension_data.width, dimension_data.height))
9240 image_size_error ();
9241 goto rsvg_error;
9244 /* We can now get a valid pixel buffer from the svg file, if all
9245 went ok. */
9246 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
9247 if (!pixbuf) goto rsvg_error;
9248 g_object_unref (rsvg_handle);
9250 /* Extract some meta data from the svg handle. */
9251 width = gdk_pixbuf_get_width (pixbuf);
9252 height = gdk_pixbuf_get_height (pixbuf);
9253 pixels = gdk_pixbuf_get_pixels (pixbuf);
9254 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
9256 /* Validate the svg meta data. */
9257 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
9258 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
9259 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
9260 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
9263 #ifdef USE_CAIRO
9264 unsigned char *data = (unsigned char *) xmalloc (width*height*4);
9265 uint32_t bgcolor = get_spec_bg_or_alpha_as_argb (img, f);
9267 for (int y = 0; y < height; ++y)
9269 const guchar *iconptr = pixels + y * rowstride;
9270 uint32_t *dataptr = (uint32_t *) (data + y * rowstride);
9272 for (int x = 0; x < width; ++x)
9274 if (iconptr[3] == 0)
9275 *dataptr = bgcolor;
9276 else
9277 *dataptr = (iconptr[0] << 16)
9278 | (iconptr[1] << 8)
9279 | iconptr[2]
9280 | (iconptr[3] << 24);
9282 iconptr += 4;
9283 ++dataptr;
9287 create_cairo_image_surface (img, data, width, height);
9288 g_object_unref (pixbuf);
9289 #else
9290 /* Try to create a x pixmap to hold the svg pixmap. */
9291 XImagePtr ximg;
9292 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
9294 g_object_unref (pixbuf);
9295 return 0;
9298 init_color_table ();
9300 /* Handle alpha channel by combining the image with a background
9301 color. */
9302 XColor background;
9303 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
9304 if (!STRINGP (specified_bg)
9305 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
9306 x_query_frame_background_color (f, &background);
9308 /* SVG pixmaps specify transparency in the last byte, so right
9309 shift 8 bits to get rid of it, since emacs doesn't support
9310 transparency. */
9311 background.red >>= 8;
9312 background.green >>= 8;
9313 background.blue >>= 8;
9315 /* This loop handles opacity values, since Emacs assumes
9316 non-transparent images. Each pixel must be "flattened" by
9317 calculating the resulting color, given the transparency of the
9318 pixel, and the image background color. */
9319 for (int y = 0; y < height; ++y)
9321 for (int x = 0; x < width; ++x)
9323 int red = *pixels++;
9324 int green = *pixels++;
9325 int blue = *pixels++;
9326 int opacity = *pixels++;
9328 red = ((red * opacity)
9329 + (background.red * ((1 << 8) - opacity)));
9330 green = ((green * opacity)
9331 + (background.green * ((1 << 8) - opacity)));
9332 blue = ((blue * opacity)
9333 + (background.blue * ((1 << 8) - opacity)));
9335 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9338 pixels += rowstride - 4 * width;
9341 #ifdef COLOR_TABLE_SUPPORT
9342 /* Remember colors allocated for this image. */
9343 img->colors = colors_in_color_table (&img->ncolors);
9344 free_color_table ();
9345 #endif /* COLOR_TABLE_SUPPORT */
9347 g_object_unref (pixbuf);
9349 img->width = width;
9350 img->height = height;
9352 /* Maybe fill in the background field while we have ximg handy.
9353 Casting avoids a GCC warning. */
9354 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9356 /* Put ximg into the image. */
9357 image_put_x_image (f, img, ximg, 0);
9358 #endif /* ! USE_CAIRO */
9361 return 1;
9363 rsvg_error:
9364 g_object_unref (rsvg_handle);
9365 /* FIXME: Use error->message so the user knows what is the actual
9366 problem with the image. */
9367 image_error ("Error parsing SVG image `%s'", img->spec);
9368 g_clear_error (&err);
9369 return 0;
9372 #endif /* defined (HAVE_RSVG) */
9377 /***********************************************************************
9378 Ghostscript
9379 ***********************************************************************/
9381 #ifdef HAVE_X_WINDOWS
9382 #define HAVE_GHOSTSCRIPT 1
9383 #endif /* HAVE_X_WINDOWS */
9385 #ifdef HAVE_GHOSTSCRIPT
9387 static bool gs_image_p (Lisp_Object object);
9388 static bool gs_load (struct frame *f, struct image *img);
9389 static void gs_clear_image (struct frame *f, struct image *img);
9391 /* Indices of image specification fields in gs_format, below. */
9393 enum gs_keyword_index
9395 GS_TYPE,
9396 GS_PT_WIDTH,
9397 GS_PT_HEIGHT,
9398 GS_FILE,
9399 GS_LOADER,
9400 GS_BOUNDING_BOX,
9401 GS_ASCENT,
9402 GS_MARGIN,
9403 GS_RELIEF,
9404 GS_ALGORITHM,
9405 GS_HEURISTIC_MASK,
9406 GS_MASK,
9407 GS_BACKGROUND,
9408 GS_LAST
9411 /* Vector of image_keyword structures describing the format
9412 of valid user-defined image specifications. */
9414 static const struct image_keyword gs_format[GS_LAST] =
9416 {":type", IMAGE_SYMBOL_VALUE, 1},
9417 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9418 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9419 {":file", IMAGE_STRING_VALUE, 1},
9420 {":loader", IMAGE_FUNCTION_VALUE, 0},
9421 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9422 {":ascent", IMAGE_ASCENT_VALUE, 0},
9423 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9424 {":relief", IMAGE_INTEGER_VALUE, 0},
9425 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9426 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9427 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9428 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9431 /* Structure describing the image type `ghostscript'. */
9433 static struct image_type gs_type =
9435 SYMBOL_INDEX (Qpostscript),
9436 gs_image_p,
9437 gs_load,
9438 gs_clear_image,
9439 NULL,
9440 NULL
9444 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9446 static void
9447 gs_clear_image (struct frame *f, struct image *img)
9449 x_clear_image (f, img);
9453 /* Return true if OBJECT is a valid Ghostscript image
9454 specification. */
9456 static bool
9457 gs_image_p (Lisp_Object object)
9459 struct image_keyword fmt[GS_LAST];
9460 Lisp_Object tem;
9461 int i;
9463 memcpy (fmt, gs_format, sizeof fmt);
9465 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9466 return 0;
9468 /* Bounding box must be a list or vector containing 4 integers. */
9469 tem = fmt[GS_BOUNDING_BOX].value;
9470 if (CONSP (tem))
9472 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9473 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9474 return 0;
9475 if (!NILP (tem))
9476 return 0;
9478 else if (VECTORP (tem))
9480 if (ASIZE (tem) != 4)
9481 return 0;
9482 for (i = 0; i < 4; ++i)
9483 if (!INTEGERP (AREF (tem, i)))
9484 return 0;
9486 else
9487 return 0;
9489 return 1;
9493 /* Load Ghostscript image IMG for use on frame F. Value is true
9494 if successful. */
9496 static bool
9497 gs_load (struct frame *f, struct image *img)
9499 uprintmax_t printnum1, printnum2;
9500 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9501 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9502 Lisp_Object frame;
9503 double in_width, in_height;
9504 Lisp_Object pixel_colors = Qnil;
9506 /* Compute pixel size of pixmap needed from the given size in the
9507 image specification. Sizes in the specification are in pt. 1 pt
9508 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9509 info. */
9510 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9511 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9512 in_width *= FRAME_RES_X (f);
9513 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9514 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9515 in_height *= FRAME_RES_Y (f);
9517 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9518 && check_image_size (f, in_width, in_height)))
9520 image_size_error ();
9521 return 0;
9523 img->width = in_width;
9524 img->height = in_height;
9526 /* Create the pixmap. */
9527 eassert (img->pixmap == NO_PIXMAP);
9529 if (x_check_image_size (0, img->width, img->height))
9531 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9532 block_input ();
9533 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9534 img->width, img->height,
9535 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9536 unblock_input ();
9539 if (!img->pixmap)
9541 image_error ("Unable to create pixmap for `%s'" , img->spec);
9542 return 0;
9545 /* Call the loader to fill the pixmap. It returns a process object
9546 if successful. We do not record_unwind_protect here because
9547 other places in redisplay like calling window scroll functions
9548 don't either. Let the Lisp loader use `unwind-protect' instead. */
9549 printnum1 = FRAME_X_WINDOW (f);
9550 printnum2 = img->pixmap;
9551 window_and_pixmap_id
9552 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9554 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9555 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9556 pixel_colors
9557 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9559 XSETFRAME (frame, f);
9560 loader = image_spec_value (img->spec, QCloader, NULL);
9561 if (NILP (loader))
9562 loader = intern ("gs-load-image");
9564 img->lisp_data = call6 (loader, frame, img->spec,
9565 make_number (img->width),
9566 make_number (img->height),
9567 window_and_pixmap_id,
9568 pixel_colors);
9569 return PROCESSP (img->lisp_data);
9573 /* Kill the Ghostscript process that was started to fill PIXMAP on
9574 frame F. Called from XTread_socket when receiving an event
9575 telling Emacs that Ghostscript has finished drawing. */
9577 void
9578 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9580 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9581 ptrdiff_t i;
9582 struct image *img;
9584 /* Find the image containing PIXMAP. */
9585 for (i = 0; i < c->used; ++i)
9586 if (c->images[i]->pixmap == pixmap)
9587 break;
9589 /* Should someone in between have cleared the image cache, for
9590 instance, give up. */
9591 if (i == c->used)
9592 return;
9594 /* Kill the GS process. We should have found PIXMAP in the image
9595 cache and its image should contain a process object. */
9596 img = c->images[i];
9597 eassert (PROCESSP (img->lisp_data));
9598 Fkill_process (img->lisp_data, Qnil);
9599 img->lisp_data = Qnil;
9601 #if defined (HAVE_X_WINDOWS)
9603 /* On displays with a mutable colormap, figure out the colors
9604 allocated for the image by looking at the pixels of an XImage for
9605 img->pixmap. */
9606 if (x_mutable_colormap (FRAME_X_VISUAL (f)))
9608 XImagePtr ximg;
9610 block_input ();
9612 /* Try to get an XImage for img->pixmep. */
9613 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9614 0, 0, img->width, img->height, ~0, ZPixmap);
9615 if (ximg)
9617 /* Initialize the color table. */
9618 init_color_table ();
9620 /* For each pixel of the image, look its color up in the
9621 color table. After having done so, the color table will
9622 contain an entry for each color used by the image. */
9623 #ifdef COLOR_TABLE_SUPPORT
9624 for (int y = 0; y < img->height; ++y)
9625 for (int x = 0; x < img->width; ++x)
9627 unsigned long pixel = XGetPixel (ximg, x, y);
9629 lookup_pixel_color (f, pixel);
9632 /* Record colors in the image. Free color table and XImage. */
9633 img->colors = colors_in_color_table (&img->ncolors);
9634 free_color_table ();
9635 #endif
9636 XDestroyImage (ximg);
9638 #if 0 /* This doesn't seem to be the case. If we free the colors
9639 here, we get a BadAccess later in x_clear_image when
9640 freeing the colors. */
9641 /* We have allocated colors once, but Ghostscript has also
9642 allocated colors on behalf of us. So, to get the
9643 reference counts right, free them once. */
9644 if (img->ncolors)
9645 x_free_colors (f, img->colors, img->ncolors);
9646 #endif
9648 else
9649 image_error ("Cannot get X image of `%s'; colors will not be freed",
9650 img->spec);
9652 unblock_input ();
9654 #endif /* HAVE_X_WINDOWS */
9656 /* Now that we have the pixmap, compute mask and transform the
9657 image if requested. */
9658 block_input ();
9659 postprocess_image (f, img);
9660 unblock_input ();
9663 #endif /* HAVE_GHOSTSCRIPT */
9666 /***********************************************************************
9667 Tests
9668 ***********************************************************************/
9670 #ifdef GLYPH_DEBUG
9672 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9673 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9674 (Lisp_Object spec)
9676 return valid_image_p (spec) ? Qt : Qnil;
9680 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0,
9681 doc: /* */)
9682 (Lisp_Object spec)
9684 ptrdiff_t id = -1;
9686 if (valid_image_p (spec))
9687 id = lookup_image (SELECTED_FRAME (), spec);
9689 debug_print (spec);
9690 return make_number (id);
9693 #endif /* GLYPH_DEBUG */
9696 /***********************************************************************
9697 Initialization
9698 ***********************************************************************/
9700 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9701 doc: /* Initialize image library implementing image type TYPE.
9702 Return non-nil if TYPE is a supported image type.
9704 If image libraries are loaded dynamically (currently only the case on
9705 MS-Windows), load the library for TYPE if it is not yet loaded, using
9706 the library file(s) specified by `dynamic-library-alist'. */)
9707 (Lisp_Object type)
9709 return lookup_image_type (type) ? Qt : Qnil;
9712 /* Look up image type TYPE, and return a pointer to its image_type
9713 structure. Return 0 if TYPE is not a known image type. */
9715 static struct image_type *
9716 lookup_image_type (Lisp_Object type)
9718 /* Types pbm and xbm are built-in and always available. */
9719 if (EQ (type, Qpbm))
9720 return define_image_type (&pbm_type);
9722 if (EQ (type, Qxbm))
9723 return define_image_type (&xbm_type);
9725 #if defined (HAVE_XPM) || defined (HAVE_NS)
9726 if (EQ (type, Qxpm))
9727 return define_image_type (&xpm_type);
9728 #endif
9730 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9731 if (EQ (type, Qjpeg))
9732 return define_image_type (&jpeg_type);
9733 #endif
9735 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9736 if (EQ (type, Qtiff))
9737 return define_image_type (&tiff_type);
9738 #endif
9740 #if defined (HAVE_GIF) || defined (HAVE_NS)
9741 if (EQ (type, Qgif))
9742 return define_image_type (&gif_type);
9743 #endif
9745 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9746 if (EQ (type, Qpng))
9747 return define_image_type (&png_type);
9748 #endif
9750 #if defined (HAVE_RSVG)
9751 if (EQ (type, Qsvg))
9752 return define_image_type (&svg_type);
9753 #endif
9755 #if defined (HAVE_IMAGEMAGICK)
9756 if (EQ (type, Qimagemagick))
9757 return define_image_type (&imagemagick_type);
9758 #endif
9760 #ifdef HAVE_GHOSTSCRIPT
9761 if (EQ (type, Qpostscript))
9762 return define_image_type (&gs_type);
9763 #endif
9765 return NULL;
9768 /* Reset image_types before dumping.
9769 Called from Fdump_emacs. */
9771 void
9772 reset_image_types (void)
9774 while (image_types)
9776 struct image_type *next = image_types->next;
9777 xfree (image_types);
9778 image_types = next;
9782 void
9783 syms_of_image (void)
9785 /* Initialize this only once; it will be reset before dumping. */
9786 image_types = NULL;
9788 /* Must be defined now because we're going to update it below, while
9789 defining the supported image types. */
9790 DEFVAR_LISP ("image-types", Vimage_types,
9791 doc: /* List of potentially supported image types.
9792 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9793 To check whether it is really supported, use `image-type-available-p'. */);
9794 Vimage_types = Qnil;
9796 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9797 doc: /* Maximum size of images.
9798 Emacs will not load an image into memory if its pixel width or
9799 pixel height exceeds this limit.
9801 If the value is an integer, it directly specifies the maximum
9802 image height and width, measured in pixels. If it is a floating
9803 point number, it specifies the maximum image height and width
9804 as a ratio to the frame height and width. If the value is
9805 non-numeric, there is no explicit limit on the size of images. */);
9806 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9808 /* Other symbols. */
9809 DEFSYM (Qcount, "count");
9810 DEFSYM (Qextension_data, "extension-data");
9811 DEFSYM (Qdelay, "delay");
9813 /* Keywords. */
9814 DEFSYM (QCascent, ":ascent");
9815 DEFSYM (QCmargin, ":margin");
9816 DEFSYM (QCrelief, ":relief");
9817 DEFSYM (QCconversion, ":conversion");
9818 DEFSYM (QCcolor_symbols, ":color-symbols");
9819 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9820 DEFSYM (QCindex, ":index");
9821 DEFSYM (QCcrop, ":crop");
9822 DEFSYM (QCrotation, ":rotation");
9823 DEFSYM (QCmatrix, ":matrix");
9824 DEFSYM (QCscale, ":scale");
9825 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9826 DEFSYM (QCmask, ":mask");
9828 /* Other symbols. */
9829 DEFSYM (Qlaplace, "laplace");
9830 DEFSYM (Qemboss, "emboss");
9831 DEFSYM (Qedge_detection, "edge-detection");
9832 DEFSYM (Qheuristic, "heuristic");
9834 DEFSYM (Qpostscript, "postscript");
9835 DEFSYM (QCmax_width, ":max-width");
9836 DEFSYM (QCmax_height, ":max-height");
9837 #ifdef HAVE_GHOSTSCRIPT
9838 ADD_IMAGE_TYPE (Qpostscript);
9839 DEFSYM (QCloader, ":loader");
9840 DEFSYM (QCpt_width, ":pt-width");
9841 DEFSYM (QCpt_height, ":pt-height");
9842 #endif /* HAVE_GHOSTSCRIPT */
9844 #ifdef HAVE_NTGUI
9845 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9846 or -1 if no PNG/GIF support was compiled in. This is tested by
9847 w32-win.el to correctly set up the alist used to search for the
9848 respective image libraries. */
9849 DEFSYM (Qlibpng_version, "libpng-version");
9850 Fset (Qlibpng_version,
9851 #if HAVE_PNG
9852 make_number (PNG_LIBPNG_VER)
9853 #else
9854 make_number (-1)
9855 #endif
9857 DEFSYM (Qlibgif_version, "libgif-version");
9858 Fset (Qlibgif_version,
9859 #ifdef HAVE_GIF
9860 make_number (GIFLIB_MAJOR * 10000
9861 + GIFLIB_MINOR * 100
9862 + GIFLIB_RELEASE)
9863 #else
9864 make_number (-1)
9865 #endif
9867 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9868 Fset (Qlibjpeg_version,
9869 #if HAVE_JPEG
9870 make_number (JPEG_LIB_VERSION)
9871 #else
9872 make_number (-1)
9873 #endif
9875 #endif
9877 DEFSYM (Qpbm, "pbm");
9878 ADD_IMAGE_TYPE (Qpbm);
9880 DEFSYM (Qxbm, "xbm");
9881 ADD_IMAGE_TYPE (Qxbm);
9883 #if defined (HAVE_XPM) || defined (HAVE_NS)
9884 DEFSYM (Qxpm, "xpm");
9885 ADD_IMAGE_TYPE (Qxpm);
9886 #endif
9888 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9889 DEFSYM (Qjpeg, "jpeg");
9890 ADD_IMAGE_TYPE (Qjpeg);
9891 #endif
9893 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9894 DEFSYM (Qtiff, "tiff");
9895 ADD_IMAGE_TYPE (Qtiff);
9896 #endif
9898 #if defined (HAVE_GIF) || defined (HAVE_NS)
9899 DEFSYM (Qgif, "gif");
9900 ADD_IMAGE_TYPE (Qgif);
9901 #endif
9903 #if defined (HAVE_PNG) || defined (HAVE_NS)
9904 DEFSYM (Qpng, "png");
9905 ADD_IMAGE_TYPE (Qpng);
9906 #endif
9908 #if defined (HAVE_IMAGEMAGICK)
9909 DEFSYM (Qimagemagick, "imagemagick");
9910 ADD_IMAGE_TYPE (Qimagemagick);
9911 #endif
9913 #if defined (HAVE_RSVG)
9914 DEFSYM (Qsvg, "svg");
9915 ADD_IMAGE_TYPE (Qsvg);
9916 #ifdef HAVE_NTGUI
9917 /* Other libraries used directly by svg code. */
9918 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9919 DEFSYM (Qglib, "glib");
9920 DEFSYM (Qgobject, "gobject");
9921 #endif /* HAVE_NTGUI */
9922 #endif /* HAVE_RSVG */
9924 defsubr (&Sinit_image_library);
9925 #ifdef HAVE_IMAGEMAGICK
9926 defsubr (&Simagemagick_types);
9927 #endif
9928 defsubr (&Sclear_image_cache);
9929 defsubr (&Simage_flush);
9930 defsubr (&Simage_size);
9931 defsubr (&Simage_mask_p);
9932 defsubr (&Simage_metadata);
9934 #ifdef GLYPH_DEBUG
9935 defsubr (&Simagep);
9936 defsubr (&Slookup_image);
9937 #endif
9939 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9940 doc: /* Non-nil means always draw a cross over disabled images.
9941 Disabled images are those having a `:conversion disabled' property.
9942 A cross is always drawn on black & white displays. */);
9943 cross_disabled_images = 0;
9945 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9946 doc: /* List of directories to search for window system bitmap files. */);
9947 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9949 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9950 doc: /* Maximum time after which images are removed from the cache.
9951 When an image has not been displayed this many seconds, Emacs
9952 automatically removes it from the image cache. If the cache contains
9953 a large number of images, the actual eviction time may be shorter.
9954 The value can also be nil, meaning the cache is never cleared.
9956 The function `clear-image-cache' disregards this variable. */);
9957 Vimage_cache_eviction_delay = make_number (300);
9958 #ifdef HAVE_IMAGEMAGICK
9959 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9960 doc: /* Integer indicating which ImageMagick rendering method to use.
9961 The options are:
9962 0 -- the default method (pixel pushing)
9963 1 -- a newer method ("MagickExportImagePixels") that may perform
9964 better (speed etc) in some cases, but has not been as thoroughly
9965 tested with Emacs as the default method. This method requires
9966 ImageMagick version 6.4.6 (approximately) or later.
9967 */);
9968 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9969 imagemagick_render_type = 0;
9970 #endif