1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2017 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/>. */
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
35 #include <flexmember.h>
42 #include "dispextern.h"
43 #include "blockinput.h"
47 #include "termhooks.h"
50 #ifdef HAVE_SYS_STAT_H
52 #endif /* HAVE_SYS_STAT_H */
54 #ifdef HAVE_SYS_TYPES_H
55 #include <sys/types.h>
56 #endif /* HAVE_SYS_TYPES_H */
58 #ifdef HAVE_WINDOW_SYSTEM
60 #endif /* HAVE_WINDOW_SYSTEM */
62 /* Work around GCC bug 54561. */
63 #if GNUC_PREREQ (4, 3, 0)
64 # pragma GCC diagnostic ignored "-Wclobbered"
68 typedef struct x_bitmap_record Bitmap_Record
;
69 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
70 #define NO_PIXMAP None
72 #define PIX_MASK_RETAIN 0
73 #define PIX_MASK_DRAW 1
74 #endif /* HAVE_X_WINDOWS */
78 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
83 typedef struct w32_bitmap_record Bitmap_Record
;
84 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
87 #define PIX_MASK_RETAIN 0
88 #define PIX_MASK_DRAW 1
90 #define x_defined_color w32_defined_color
92 #endif /* HAVE_NTGUI */
95 typedef struct ns_bitmap_record Bitmap_Record
;
97 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
100 #define PIX_MASK_RETAIN 0
102 #define x_defined_color(f, name, color_def, alloc) \
103 ns_defined_color (f, name, color_def, alloc, 0)
106 #if (defined HAVE_X_WINDOWS \
107 && ! (defined HAVE_NTGUI || defined USE_CAIRO || defined HAVE_NS))
108 /* W32_TODO : Color tables on W32. */
109 # define COLOR_TABLE_SUPPORT 1
112 static void x_disable_image (struct frame
*, struct image
*);
113 static void x_edge_detection (struct frame
*, struct image
*, Lisp_Object
,
116 static void init_color_table (void);
117 static unsigned long lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
);
118 #ifdef COLOR_TABLE_SUPPORT
119 static void free_color_table (void);
120 static unsigned long *colors_in_color_table (int *n
);
123 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
124 id, which is just an int that this section returns. Bitmaps are
125 reference counted so they can be shared among frames.
127 Bitmap indices are guaranteed to be > 0, so a negative number can
128 be used to indicate no bitmap.
130 If you use x_create_bitmap_from_data, then you must keep track of
131 the bitmaps yourself. That is, creating a bitmap from the same
132 data more than once will not be caught. */
135 /* Use with images created by ns_image_for_XPM. */
137 XGetPixel (XImagePtr ximage
, int x
, int y
)
139 return ns_get_pixel (ximage
, x
, y
);
142 /* Use with images created by ns_image_for_XPM; alpha set to 1;
143 pixel is assumed to be in RGB form. */
145 XPutPixel (XImagePtr ximage
, int x
, int y
, unsigned long pixel
)
147 ns_put_pixel (ximage
, x
, y
, pixel
);
152 /* Functions to access the contents of a bitmap, given an id. */
154 #ifdef HAVE_X_WINDOWS
156 x_bitmap_height (struct frame
*f
, ptrdiff_t id
)
158 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].height
;
162 x_bitmap_width (struct frame
*f
, ptrdiff_t id
)
164 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].width
;
168 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
170 x_bitmap_pixmap (struct frame
*f
, ptrdiff_t id
)
172 /* HAVE_NTGUI needs the explicit cast here. */
173 return (ptrdiff_t) FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].pixmap
;
177 #ifdef HAVE_X_WINDOWS
179 x_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
181 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].mask
;
185 /* Allocate a new bitmap record. Returns index of new record. */
188 x_allocate_bitmap_record (struct frame
*f
)
190 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
193 if (dpyinfo
->bitmaps_last
< dpyinfo
->bitmaps_size
)
194 return ++dpyinfo
->bitmaps_last
;
196 for (i
= 0; i
< dpyinfo
->bitmaps_size
; ++i
)
197 if (dpyinfo
->bitmaps
[i
].refcount
== 0)
201 xpalloc (dpyinfo
->bitmaps
, &dpyinfo
->bitmaps_size
,
202 10, -1, sizeof *dpyinfo
->bitmaps
);
203 return ++dpyinfo
->bitmaps_last
;
206 /* Add one reference to the reference count of the bitmap with id ID. */
209 x_reference_bitmap (struct frame
*f
, ptrdiff_t id
)
211 ++FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].refcount
;
214 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
217 x_create_bitmap_from_data (struct frame
*f
, char *bits
, unsigned int width
, unsigned int height
)
219 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
222 #ifdef HAVE_X_WINDOWS
224 bitmap
= XCreateBitmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_DRAWABLE (f
),
225 bits
, width
, height
);
228 #endif /* HAVE_X_WINDOWS */
231 Lisp_Object frame UNINIT
; /* The value is not used. */
233 bitmap
= CreateBitmap (width
, height
,
234 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_planes
,
235 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_cbits
,
239 #endif /* HAVE_NTGUI */
242 void *bitmap
= ns_image_from_XBM (bits
, width
, height
, 0, 0);
247 id
= x_allocate_bitmap_record (f
);
250 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
251 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
254 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
255 dpyinfo
->bitmaps
[id
- 1].height
= height
;
256 dpyinfo
->bitmaps
[id
- 1].width
= width
;
257 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
259 #ifdef HAVE_X_WINDOWS
260 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
261 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
262 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
263 #endif /* HAVE_X_WINDOWS */
266 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
267 dpyinfo
->bitmaps
[id
- 1].hinst
= NULL
;
268 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
269 #endif /* HAVE_NTGUI */
274 /* Create bitmap from file FILE for frame F. */
277 x_create_bitmap_from_file (struct frame
*f
, Lisp_Object file
)
280 return -1; /* W32_TODO : bitmap support */
282 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
287 void *bitmap
= ns_image_from_file (file
);
293 id
= x_allocate_bitmap_record (f
);
294 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
295 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
296 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
297 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
298 dpyinfo
->bitmaps
[id
- 1].height
= ns_image_width (bitmap
);
299 dpyinfo
->bitmaps
[id
- 1].width
= ns_image_height (bitmap
);
303 #ifdef HAVE_X_WINDOWS
304 unsigned int width
, height
;
306 int xhot
, yhot
, result
;
311 /* Look for an existing bitmap with the same name. */
312 for (id
= 0; id
< dpyinfo
->bitmaps_last
; ++id
)
314 if (dpyinfo
->bitmaps
[id
].refcount
315 && dpyinfo
->bitmaps
[id
].file
316 && !strcmp (dpyinfo
->bitmaps
[id
].file
, SSDATA (file
)))
318 ++dpyinfo
->bitmaps
[id
].refcount
;
323 /* Search bitmap-file-path for the file, if appropriate. */
324 if (openp (Vx_bitmap_file_path
, file
, Qnil
, &found
,
325 make_number (R_OK
), false)
329 filename
= SSDATA (found
);
331 result
= XReadBitmapFile (FRAME_X_DISPLAY (f
), FRAME_X_DRAWABLE (f
),
332 filename
, &width
, &height
, &bitmap
, &xhot
, &yhot
);
333 if (result
!= BitmapSuccess
)
336 id
= x_allocate_bitmap_record (f
);
337 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
338 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
339 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
340 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
341 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
342 dpyinfo
->bitmaps
[id
- 1].height
= height
;
343 dpyinfo
->bitmaps
[id
- 1].width
= width
;
346 #endif /* HAVE_X_WINDOWS */
352 free_bitmap_record (Display_Info
*dpyinfo
, Bitmap_Record
*bm
)
354 #ifdef HAVE_X_WINDOWS
355 XFreePixmap (dpyinfo
->display
, bm
->pixmap
);
357 XFreePixmap (dpyinfo
->display
, bm
->mask
);
358 #endif /* HAVE_X_WINDOWS */
361 DeleteObject (bm
->pixmap
);
362 #endif /* HAVE_NTGUI */
365 ns_release_object (bm
->img
);
375 /* Remove reference to bitmap with id number ID. */
378 x_destroy_bitmap (struct frame
*f
, ptrdiff_t id
)
380 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
384 Bitmap_Record
*bm
= &dpyinfo
->bitmaps
[id
- 1];
386 if (--bm
->refcount
== 0)
389 free_bitmap_record (dpyinfo
, bm
);
395 /* Free all the bitmaps for the display specified by DPYINFO. */
398 x_destroy_all_bitmaps (Display_Info
*dpyinfo
)
401 Bitmap_Record
*bm
= dpyinfo
->bitmaps
;
403 for (i
= 0; i
< dpyinfo
->bitmaps_last
; i
++, bm
++)
404 if (bm
->refcount
> 0)
405 free_bitmap_record (dpyinfo
, bm
);
407 dpyinfo
->bitmaps_last
= 0;
410 static bool x_create_x_image_and_pixmap (struct frame
*, int, int, int,
411 XImagePtr
*, Pixmap
*);
412 static void x_destroy_x_image (XImagePtr ximg
);
415 static XImagePtr_or_DC
image_get_x_image_or_dc (struct frame
*, struct image
*,
417 static void image_unget_x_image_or_dc (struct image
*, bool, XImagePtr_or_DC
,
420 static XImagePtr
image_get_x_image (struct frame
*, struct image
*, bool);
421 static void image_unget_x_image (struct image
*, bool, XImagePtr
);
422 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
423 image_get_x_image (f, img, mask_p)
424 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
425 image_unget_x_image (img, mask_p, ximg)
428 #ifdef HAVE_X_WINDOWS
430 static void image_sync_to_pixmaps (struct frame
*, struct image
*);
432 /* Useful functions defined in the section
433 `Image type independent image structures' below. */
435 static unsigned long four_corners_best (XImagePtr ximg
,
438 unsigned long height
);
441 /* Create a mask of a bitmap. Note is this not a perfect mask.
442 It's nicer with some borders in this context */
445 x_create_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
448 XImagePtr ximg
, mask_img
;
449 unsigned long width
, height
;
452 unsigned long x
, y
, xp
, xm
, yp
, ym
;
455 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
460 pixmap
= x_bitmap_pixmap (f
, id
);
461 width
= x_bitmap_width (f
, id
);
462 height
= x_bitmap_height (f
, id
);
465 ximg
= XGetImage (FRAME_X_DISPLAY (f
), pixmap
, 0, 0, width
, height
,
474 result
= x_create_x_image_and_pixmap (f
, width
, height
, 1, &mask_img
, &mask
);
479 XDestroyImage (ximg
);
483 bg
= four_corners_best (ximg
, NULL
, width
, height
);
485 for (y
= 0; y
< ximg
->height
; ++y
)
487 for (x
= 0; x
< ximg
->width
; ++x
)
489 xp
= x
!= ximg
->width
- 1 ? x
+ 1 : 0;
490 xm
= x
!= 0 ? x
- 1 : ximg
->width
- 1;
491 yp
= y
!= ximg
->height
- 1 ? y
+ 1 : 0;
492 ym
= y
!= 0 ? y
- 1 : ximg
->height
- 1;
493 if (XGetPixel (ximg
, x
, y
) == bg
494 && XGetPixel (ximg
, x
, yp
) == bg
495 && XGetPixel (ximg
, x
, ym
) == bg
496 && XGetPixel (ximg
, xp
, y
) == bg
497 && XGetPixel (ximg
, xp
, yp
) == bg
498 && XGetPixel (ximg
, xp
, ym
) == bg
499 && XGetPixel (ximg
, xm
, y
) == bg
500 && XGetPixel (ximg
, xm
, yp
) == bg
501 && XGetPixel (ximg
, xm
, ym
) == bg
)
502 XPutPixel (mask_img
, x
, y
, 0);
504 XPutPixel (mask_img
, x
, y
, 1);
508 eassert (input_blocked_p ());
509 gc
= XCreateGC (FRAME_X_DISPLAY (f
), mask
, 0, NULL
);
510 XPutImage (FRAME_X_DISPLAY (f
), mask
, gc
, mask_img
, 0, 0, 0, 0,
512 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
514 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
515 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
517 XDestroyImage (ximg
);
518 x_destroy_x_image (mask_img
);
521 #endif /* HAVE_X_WINDOWS */
523 /***********************************************************************
525 ***********************************************************************/
527 /* List of supported image types. Use define_image_type to add new
528 types. Use lookup_image_type to find a type for a given symbol. */
530 static struct image_type
*image_types
;
532 /* Forward function prototypes. */
534 static struct image_type
*lookup_image_type (Lisp_Object
);
535 static void x_laplace (struct frame
*, struct image
*);
536 static void x_emboss (struct frame
*, struct image
*);
537 static void x_build_heuristic_mask (struct frame
*, struct image
*,
540 #define CACHE_IMAGE_TYPE(type, status) \
541 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
543 #define CACHE_IMAGE_TYPE(type, status)
546 #define ADD_IMAGE_TYPE(type) \
547 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
549 /* Define a new image type from TYPE. This adds a copy of TYPE to
550 image_types and caches the loading status of TYPE. */
552 static struct image_type
*
553 define_image_type (struct image_type
*type
)
555 struct image_type
*p
= NULL
;
556 int new_type
= type
->type
;
557 bool type_valid
= true;
561 for (p
= image_types
; p
; p
= p
->next
)
562 if (p
->type
== new_type
)
567 #if defined HAVE_NTGUI && defined WINDOWSNT
568 /* If we failed to load the library before, don't try again. */
569 Lisp_Object tested
= Fassq (builtin_lisp_symbol (new_type
),
571 if (CONSP (tested
) && NILP (XCDR (tested
)))
576 type_valid
= type
->init ();
577 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type
),
578 type_valid
? Qt
: Qnil
);
584 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
585 The initialized data segment is read-only. */
586 p
= xmalloc (sizeof *p
);
588 p
->next
= image_types
;
598 /* Value is true if OBJECT is a valid Lisp image specification. A
599 valid image specification is a list whose car is the symbol
600 `image', and whose rest is a property list. The property list must
601 contain a value for key `:type'. That value must be the name of a
602 supported image type. The rest of the property list depends on the
606 valid_image_p (Lisp_Object object
)
614 for (tem
= XCDR (object
); CONSP (tem
); tem
= XCDR (tem
))
615 if (EQ (XCAR (tem
), QCtype
))
618 if (CONSP (tem
) && SYMBOLP (XCAR (tem
)))
620 struct image_type
*type
;
621 type
= lookup_image_type (XCAR (tem
));
623 valid_p
= type
->valid_p (object
);
634 /* Log error message with format string FORMAT and trailing arguments.
635 Signaling an error, e.g. when an image cannot be loaded, is not a
636 good idea because this would interrupt redisplay, and the error
637 message display would lead to another redisplay. This function
638 therefore simply displays a message. */
641 image_error (const char *format
, ...)
644 va_start (ap
, format
);
645 vadd_to_log (format
, ap
);
650 image_size_error (void)
652 image_error ("Invalid image size (see `max-image-size')");
656 /***********************************************************************
658 ***********************************************************************/
660 enum image_value_type
662 IMAGE_DONT_CHECK_VALUE_TYPE
,
664 IMAGE_STRING_OR_NIL_VALUE
,
666 IMAGE_POSITIVE_INTEGER_VALUE
,
667 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
,
668 IMAGE_NON_NEGATIVE_INTEGER_VALUE
,
671 IMAGE_FUNCTION_VALUE
,
676 /* Structure used when parsing image specifications. */
680 /* Name of keyword. */
683 /* The type of value allowed. */
684 enum image_value_type type
;
686 /* True means key must be present. */
689 /* Used to recognize duplicate keywords in a property list. */
692 /* The value that was found. */
697 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
698 has the format (image KEYWORD VALUE ...). One of the keyword/
699 value pairs must be `:type TYPE'. KEYWORDS is a vector of
700 image_keywords structures of size NKEYWORDS describing other
701 allowed keyword/value pairs. Value is true if SPEC is valid. */
704 parse_image_spec (Lisp_Object spec
, struct image_keyword
*keywords
,
705 int nkeywords
, Lisp_Object type
)
714 while (CONSP (plist
))
716 Lisp_Object key
, value
;
718 /* First element of a pair must be a symbol. */
720 plist
= XCDR (plist
);
724 /* There must follow a value. */
727 value
= XCAR (plist
);
728 plist
= XCDR (plist
);
730 /* Find key in KEYWORDS. Error if not found. */
731 for (i
= 0; i
< nkeywords
; ++i
)
732 if (strcmp (keywords
[i
].name
, SSDATA (SYMBOL_NAME (key
))) == 0)
738 /* Record that we recognized the keyword. If a keywords
739 was found more than once, it's an error. */
740 keywords
[i
].value
= value
;
741 if (keywords
[i
].count
> 1)
745 /* Check type of value against allowed type. */
746 switch (keywords
[i
].type
)
748 case IMAGE_STRING_VALUE
:
749 if (!STRINGP (value
))
753 case IMAGE_STRING_OR_NIL_VALUE
:
754 if (!STRINGP (value
) && !NILP (value
))
758 case IMAGE_SYMBOL_VALUE
:
759 if (!SYMBOLP (value
))
763 case IMAGE_POSITIVE_INTEGER_VALUE
:
764 if (! RANGED_INTEGERP (1, value
, INT_MAX
))
768 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
:
769 if (RANGED_INTEGERP (0, value
, INT_MAX
))
772 && RANGED_INTEGERP (0, XCAR (value
), INT_MAX
)
773 && RANGED_INTEGERP (0, XCDR (value
), INT_MAX
))
777 case IMAGE_ASCENT_VALUE
:
778 if (SYMBOLP (value
) && EQ (value
, Qcenter
))
780 else if (RANGED_INTEGERP (0, value
, 100))
784 case IMAGE_NON_NEGATIVE_INTEGER_VALUE
:
785 /* Unlike the other integer-related cases, this one does not
786 verify that VALUE fits in 'int'. This is because callers
788 if (!INTEGERP (value
) || XINT (value
) < 0)
792 case IMAGE_DONT_CHECK_VALUE_TYPE
:
795 case IMAGE_FUNCTION_VALUE
:
796 value
= indirect_function (value
);
797 if (FUNCTIONP (value
))
801 case IMAGE_NUMBER_VALUE
:
802 if (! NUMBERP (value
))
806 case IMAGE_INTEGER_VALUE
:
807 if (! TYPE_RANGED_INTEGERP (int, value
))
811 case IMAGE_BOOL_VALUE
:
812 if (!NILP (value
) && !EQ (value
, Qt
))
821 if (EQ (key
, QCtype
) && !EQ (type
, value
))
825 /* Check that all mandatory fields are present. */
826 for (i
= 0; i
< nkeywords
; ++i
)
827 if (keywords
[i
].mandatory_p
&& keywords
[i
].count
== 0)
834 /* Return the value of KEY in image specification SPEC. Value is nil
835 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
836 was found in SPEC. */
839 image_spec_value (Lisp_Object spec
, Lisp_Object key
, bool *found
)
843 eassert (valid_image_p (spec
));
845 for (tail
= XCDR (spec
);
846 CONSP (tail
) && CONSP (XCDR (tail
));
847 tail
= XCDR (XCDR (tail
)))
849 if (EQ (XCAR (tail
), key
))
853 return XCAR (XCDR (tail
));
863 DEFUN ("image-size", Fimage_size
, Simage_size
, 1, 3, 0,
864 doc
: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
865 PIXELS non-nil means return the size in pixels, otherwise return the
866 size in canonical character units.
867 FRAME is the frame on which the image will be displayed. FRAME nil
868 or omitted means use the selected frame. */)
869 (Lisp_Object spec
, Lisp_Object pixels
, Lisp_Object frame
)
874 if (valid_image_p (spec
))
876 struct frame
*f
= decode_window_system_frame (frame
);
877 ptrdiff_t id
= lookup_image (f
, spec
);
878 struct image
*img
= IMAGE_FROM_ID (f
, id
);
879 int width
= img
->width
+ 2 * img
->hmargin
;
880 int height
= img
->height
+ 2 * img
->vmargin
;
883 size
= Fcons (make_float ((double) width
/ FRAME_COLUMN_WIDTH (f
)),
884 make_float ((double) height
/ FRAME_LINE_HEIGHT (f
)));
886 size
= Fcons (make_number (width
), make_number (height
));
889 error ("Invalid image specification");
895 DEFUN ("image-mask-p", Fimage_mask_p
, Simage_mask_p
, 1, 2, 0,
896 doc
: /* Return t if image SPEC has a mask bitmap.
897 FRAME is the frame on which the image will be displayed. FRAME nil
898 or omitted means use the selected frame. */)
899 (Lisp_Object spec
, Lisp_Object frame
)
904 if (valid_image_p (spec
))
906 struct frame
*f
= decode_window_system_frame (frame
);
907 ptrdiff_t id
= lookup_image (f
, spec
);
908 struct image
*img
= IMAGE_FROM_ID (f
, id
);
913 error ("Invalid image specification");
918 DEFUN ("image-metadata", Fimage_metadata
, Simage_metadata
, 1, 2, 0,
919 doc
: /* Return metadata for image SPEC.
920 FRAME is the frame on which the image will be displayed. FRAME nil
921 or omitted means use the selected frame. */)
922 (Lisp_Object spec
, Lisp_Object frame
)
927 if (valid_image_p (spec
))
929 struct frame
*f
= decode_window_system_frame (frame
);
930 ptrdiff_t id
= lookup_image (f
, spec
);
931 struct image
*img
= IMAGE_FROM_ID (f
, id
);
932 ext
= img
->lisp_data
;
939 /***********************************************************************
940 Image type independent image structures
941 ***********************************************************************/
943 #define MAX_IMAGE_SIZE 10.0
944 /* Allocate and return a new image structure for image specification
945 SPEC. SPEC has a hash value of HASH. */
947 static struct image
*
948 make_image (Lisp_Object spec
, EMACS_UINT hash
)
950 struct image
*img
= xzalloc (sizeof *img
);
951 Lisp_Object file
= image_spec_value (spec
, QCfile
, NULL
);
953 eassert (valid_image_p (spec
));
954 img
->dependencies
= NILP (file
) ? Qnil
: list1 (file
);
955 img
->type
= lookup_image_type (image_spec_value (spec
, QCtype
, NULL
));
956 eassert (img
->type
!= NULL
);
958 img
->lisp_data
= Qnil
;
959 img
->ascent
= DEFAULT_IMAGE_ASCENT
;
961 img
->corners
[BOT_CORNER
] = -1; /* Full image */
966 /* Free image IMG which was used on frame F, including its resources. */
969 free_image (struct frame
*f
, struct image
*img
)
973 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
975 /* Remove IMG from the hash table of its cache. */
977 img
->prev
->next
= img
->next
;
979 c
->buckets
[img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
] = img
->next
;
982 img
->next
->prev
= img
->prev
;
984 c
->images
[img
->id
] = NULL
;
986 /* Windows NT redefines 'free', but in this file, we need to
987 avoid the redefinition. */
991 /* Free resources, then free IMG. */
992 img
->type
->free (f
, img
);
997 /* Return true if the given widths and heights are valid for display. */
1000 check_image_size (struct frame
*f
, int width
, int height
)
1004 if (width
<= 0 || height
<= 0)
1007 if (INTEGERP (Vmax_image_size
))
1008 return (width
<= XINT (Vmax_image_size
)
1009 && height
<= XINT (Vmax_image_size
));
1010 else if (FLOATP (Vmax_image_size
))
1014 w
= FRAME_PIXEL_WIDTH (f
);
1015 h
= FRAME_PIXEL_HEIGHT (f
);
1018 w
= h
= 1024; /* Arbitrary size for unknown frame. */
1019 return (width
<= XFLOAT_DATA (Vmax_image_size
) * w
1020 && height
<= XFLOAT_DATA (Vmax_image_size
) * h
);
1026 /* Prepare image IMG for display on frame F. Must be called before
1027 drawing an image. */
1030 prepare_image_for_display (struct frame
*f
, struct image
*img
)
1032 /* We're about to display IMG, so set its timestamp to `now'. */
1033 img
->timestamp
= current_timespec ();
1036 /* If IMG doesn't have a pixmap yet, load it now, using the image
1037 type dependent loader function. */
1038 if (img
->pixmap
== NO_PIXMAP
&& !img
->load_failed_p
)
1039 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1041 #ifdef HAVE_X_WINDOWS
1042 if (!img
->load_failed_p
)
1045 image_sync_to_pixmaps (f
, img
);
1053 /* Value is the number of pixels for the ascent of image IMG when
1054 drawn in face FACE. */
1057 image_ascent (struct image
*img
, struct face
*face
, struct glyph_slice
*slice
)
1062 if (slice
->height
== img
->height
)
1063 height
= img
->height
+ img
->vmargin
;
1064 else if (slice
->y
== 0)
1065 height
= slice
->height
+ img
->vmargin
;
1067 height
= slice
->height
;
1069 if (img
->ascent
== CENTERED_IMAGE_ASCENT
)
1074 /* W32 specific version. Why?. ++kfs */
1075 ascent
= height
/ 2 - (FONT_DESCENT (face
->font
)
1076 - FONT_BASE (face
->font
)) / 2;
1078 /* This expression is arranged so that if the image can't be
1079 exactly centered, it will be moved slightly up. This is
1080 because a typical font is `top-heavy' (due to the presence
1081 uppercase letters), so the image placement should err towards
1082 being top-heavy too. It also just generally looks better. */
1083 ascent
= (height
+ FONT_BASE (face
->font
)
1084 - FONT_DESCENT (face
->font
) + 1) / 2;
1085 #endif /* HAVE_NTGUI */
1088 ascent
= height
/ 2;
1091 ascent
= height
* (img
->ascent
/ 100.0);
1098 xcolor_to_argb32 (XColor xc
)
1100 return ((0xffu
<< 24) | ((xc
.red
/ 256) << 16)
1101 | ((xc
.green
/ 256) << 8) | (xc
.blue
/ 256));
1105 get_spec_bg_or_alpha_as_argb (struct image
*img
,
1108 uint32_t bgcolor
= 0;
1110 Lisp_Object bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1112 if (STRINGP (bg
) && x_parse_color (f
, SSDATA (bg
), &xbgcolor
))
1113 bgcolor
= xcolor_to_argb32 (xbgcolor
);
1119 create_cairo_image_surface (struct image
*img
,
1120 unsigned char *data
,
1124 cairo_surface_t
*surface
;
1125 cairo_format_t format
= CAIRO_FORMAT_ARGB32
;
1126 int stride
= cairo_format_stride_for_width (format
, width
);
1127 surface
= cairo_image_surface_create_for_data (data
,
1133 img
->height
= height
;
1134 img
->cr_data
= surface
;
1135 img
->cr_data2
= data
;
1142 /* Image background colors. */
1144 /* Find the "best" corner color of a bitmap.
1145 On W32, XIMG is assumed to a device context with the bitmap selected. */
1147 static RGB_PIXEL_COLOR
1148 four_corners_best (XImagePtr_or_DC ximg
, int *corners
,
1149 unsigned long width
, unsigned long height
)
1151 RGB_PIXEL_COLOR corner_pixels
[4];
1152 RGB_PIXEL_COLOR best UNINIT
;
1155 if (corners
&& corners
[BOT_CORNER
] >= 0)
1157 /* Get the colors at the corner_pixels of ximg. */
1158 corner_pixels
[0] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[TOP_CORNER
]);
1159 corner_pixels
[1] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[TOP_CORNER
]);
1160 corner_pixels
[2] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[BOT_CORNER
] - 1);
1161 corner_pixels
[3] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[BOT_CORNER
] - 1);
1165 /* Get the colors at the corner_pixels of ximg. */
1166 corner_pixels
[0] = GET_PIXEL (ximg
, 0, 0);
1167 corner_pixels
[1] = GET_PIXEL (ximg
, width
- 1, 0);
1168 corner_pixels
[2] = GET_PIXEL (ximg
, width
- 1, height
- 1);
1169 corner_pixels
[3] = GET_PIXEL (ximg
, 0, height
- 1);
1171 /* Choose the most frequently found color as background. */
1172 for (i
= best_count
= 0; i
< 4; ++i
)
1176 for (j
= n
= 0; j
< 4; ++j
)
1177 if (corner_pixels
[i
] == corner_pixels
[j
])
1181 best
= corner_pixels
[i
], best_count
= n
;
1187 /* Portability macros */
1191 #define Free_Pixmap(display, pixmap) \
1192 DeleteObject (pixmap)
1194 #elif defined (HAVE_NS)
1196 #define Free_Pixmap(display, pixmap) \
1197 ns_release_object (pixmap)
1201 #define Free_Pixmap(display, pixmap) \
1202 XFreePixmap (display, pixmap)
1204 #endif /* !HAVE_NTGUI && !HAVE_NS */
1207 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1208 it is guessed heuristically. If non-zero, XIMG is an existing
1209 XImage object (or device context with the image selected on W32) to
1210 use for the heuristic. */
1213 image_background (struct image
*img
, struct frame
*f
, XImagePtr_or_DC ximg
)
1215 if (! img
->background_valid
)
1216 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1218 bool free_ximg
= !ximg
;
1221 #endif /* HAVE_NTGUI */
1224 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
1226 img
->background
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
1229 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
1231 img
->background_valid
= 1;
1234 return img
->background
;
1237 /* Return the `background_transparent' field of IMG. If IMG doesn't
1238 have one yet, it is guessed heuristically. If non-zero, MASK is an
1239 existing XImage object to use for the heuristic. */
1242 image_background_transparent (struct image
*img
, struct frame
*f
, XImagePtr_or_DC mask
)
1244 if (! img
->background_transparent_valid
)
1245 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1249 bool free_mask
= !mask
;
1252 #endif /* HAVE_NTGUI */
1255 mask
= image_get_x_image_or_dc (f
, img
, 1, &prev
);
1257 img
->background_transparent
1258 = (four_corners_best (mask
, img
->corners
, img
->width
, img
->height
) == PIX_MASK_RETAIN
);
1261 image_unget_x_image_or_dc (img
, 1, mask
, prev
);
1264 img
->background_transparent
= 0;
1266 img
->background_transparent_valid
= 1;
1269 return img
->background_transparent
;
1272 #if defined (HAVE_PNG) || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1274 /* Store F's background color into *BGCOLOR. */
1276 x_query_frame_background_color (struct frame
*f
, XColor
*bgcolor
)
1279 bgcolor
->pixel
= FRAME_BACKGROUND_PIXEL (f
);
1280 x_query_color (f
, bgcolor
);
1282 ns_query_color (FRAME_BACKGROUND_COLOR (f
), bgcolor
, 1);
1286 #endif /* HAVE_PNG || HAVE_IMAGEMAGICK || HAVE_RSVG */
1288 /***********************************************************************
1289 Helper functions for X image types
1290 ***********************************************************************/
1292 /* Clear X resources of image IMG on frame F according to FLAGS.
1293 FLAGS is bitwise-or of the following masks:
1294 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1295 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1296 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1299 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1300 #define CLEAR_IMAGE_MASK (1 << 1)
1301 #define CLEAR_IMAGE_COLORS (1 << 2)
1304 x_clear_image_1 (struct frame
*f
, struct image
*img
, int flags
)
1306 if (flags
& CLEAR_IMAGE_PIXMAP
)
1310 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->pixmap
);
1311 img
->pixmap
= NO_PIXMAP
;
1312 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1313 img
->background_valid
= 0;
1315 #ifdef HAVE_X_WINDOWS
1318 x_destroy_x_image (img
->ximg
);
1320 img
->background_valid
= 0;
1325 if (flags
& CLEAR_IMAGE_MASK
)
1329 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->mask
);
1330 img
->mask
= NO_PIXMAP
;
1331 img
->background_transparent_valid
= 0;
1333 #ifdef HAVE_X_WINDOWS
1336 x_destroy_x_image (img
->mask_img
);
1337 img
->mask_img
= NULL
;
1338 img
->background_transparent_valid
= 0;
1343 if ((flags
& CLEAR_IMAGE_COLORS
) && img
->ncolors
)
1345 /* W32_TODO: color table support. */
1346 #ifdef HAVE_X_WINDOWS
1347 x_free_colors (f
, img
->colors
, img
->ncolors
);
1348 #endif /* HAVE_X_WINDOWS */
1349 xfree (img
->colors
);
1356 /* Free X resources of image IMG which is used on frame F. */
1359 x_clear_image (struct frame
*f
, struct image
*img
)
1364 cairo_surface_destroy ((cairo_surface_t
*)img
->cr_data
);
1365 if (img
->cr_data2
) xfree (img
->cr_data2
);
1367 x_clear_image_1 (f
, img
,
1368 CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_MASK
| CLEAR_IMAGE_COLORS
);
1373 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1374 cannot be allocated, use DFLT. Add a newly allocated color to
1375 IMG->colors, so that it can be freed again. Value is the pixel
1378 static unsigned long
1379 x_alloc_image_color (struct frame
*f
, struct image
*img
, Lisp_Object color_name
,
1383 unsigned long result
;
1385 eassert (STRINGP (color_name
));
1387 if (x_defined_color (f
, SSDATA (color_name
), &color
, 1)
1388 && img
->ncolors
< min (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *img
->colors
,
1391 /* This isn't called frequently so we get away with simply
1392 reallocating the color vector to the needed size, here. */
1393 ptrdiff_t ncolors
= img
->ncolors
+ 1;
1394 img
->colors
= xrealloc (img
->colors
, ncolors
* sizeof *img
->colors
);
1395 img
->colors
[ncolors
- 1] = color
.pixel
;
1396 img
->ncolors
= ncolors
;
1397 result
= color
.pixel
;
1407 /***********************************************************************
1409 ***********************************************************************/
1411 static void cache_image (struct frame
*f
, struct image
*img
);
1413 /* Return a new, initialized image cache that is allocated from the
1414 heap. Call free_image_cache to free an image cache. */
1416 struct image_cache
*
1417 make_image_cache (void)
1419 struct image_cache
*c
= xmalloc (sizeof *c
);
1422 c
->used
= c
->refcount
= 0;
1423 c
->images
= xmalloc (c
->size
* sizeof *c
->images
);
1424 c
->buckets
= xzalloc (IMAGE_CACHE_BUCKETS_SIZE
* sizeof *c
->buckets
);
1429 /* Find an image matching SPEC in the cache, and return it. If no
1430 image is found, return NULL. */
1431 static struct image
*
1432 search_image_cache (struct frame
*f
, Lisp_Object spec
, EMACS_UINT hash
)
1435 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1436 int i
= hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1438 if (!c
) return NULL
;
1440 /* If the image spec does not specify a background color, the cached
1441 image must have the same background color as the current frame.
1442 The foreground color must also match, for the sake of monochrome
1445 In fact, we could ignore the foreground color matching condition
1446 for color images, or if the image spec specifies :foreground;
1447 similarly we could ignore the background color matching condition
1448 for formats that don't use transparency (such as jpeg), or if the
1449 image spec specifies :background. However, the extra memory
1450 usage is probably negligible in practice, so we don't bother. */
1452 for (img
= c
->buckets
[i
]; img
; img
= img
->next
)
1453 if (img
->hash
== hash
1454 && !NILP (Fequal (img
->spec
, spec
))
1455 && img
->frame_foreground
== FRAME_FOREGROUND_PIXEL (f
)
1456 && img
->frame_background
== FRAME_BACKGROUND_PIXEL (f
))
1462 /* Search frame F for an image with spec SPEC, and free it. */
1465 uncache_image (struct frame
*f
, Lisp_Object spec
)
1467 struct image
*img
= search_image_cache (f
, spec
, sxhash (spec
, 0));
1470 free_image (f
, img
);
1471 /* As display glyphs may still be referring to the image ID, we
1472 must garbage the frame (Bug#6426). */
1473 SET_FRAME_GARBAGED (f
);
1478 /* Free image cache of frame F. Be aware that X frames share images
1482 free_image_cache (struct frame
*f
)
1484 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1489 /* Cache should not be referenced by any frame when freed. */
1490 eassert (c
->refcount
== 0);
1492 for (i
= 0; i
< c
->used
; ++i
)
1493 free_image (f
, c
->images
[i
]);
1497 FRAME_IMAGE_CACHE (f
) = NULL
;
1502 /* Clear image cache of frame F. FILTER=t means free all images.
1503 FILTER=nil means clear only images that haven't been
1504 displayed for some time.
1505 Else, only free the images which have FILTER in their `dependencies'.
1506 Should be called from time to time to reduce the number of loaded images.
1507 If image-cache-eviction-delay is non-nil, this frees images in the cache
1508 which weren't displayed for at least that many seconds. */
1511 clear_image_cache (struct frame
*f
, Lisp_Object filter
)
1513 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1517 ptrdiff_t i
, nfreed
= 0;
1519 /* Block input so that we won't be interrupted by a SIGIO
1520 while being in an inconsistent state. */
1525 /* Filter image cache. */
1526 for (i
= 0; i
< c
->used
; ++i
)
1528 struct image
*img
= c
->images
[i
];
1529 if (img
&& (EQ (Qt
, filter
)
1530 || !NILP (Fmember (filter
, img
->dependencies
))))
1532 free_image (f
, img
);
1537 else if (INTEGERP (Vimage_cache_eviction_delay
))
1539 /* Free cache based on timestamp. */
1540 struct timespec old
, t
;
1542 ptrdiff_t nimages
= 0;
1544 for (i
= 0; i
< c
->used
; ++i
)
1548 /* If the number of cached images has grown unusually large,
1549 decrease the cache eviction delay (Bug#6230). */
1550 delay
= XINT (Vimage_cache_eviction_delay
);
1552 delay
= 1600 * delay
/ nimages
/ nimages
;
1553 delay
= max (delay
, 1);
1555 t
= current_timespec ();
1556 old
= timespec_sub (t
, dtotimespec (delay
));
1558 for (i
= 0; i
< c
->used
; ++i
)
1560 struct image
*img
= c
->images
[i
];
1561 if (img
&& timespec_cmp (img
->timestamp
, old
) < 0)
1563 free_image (f
, img
);
1569 /* We may be clearing the image cache because, for example,
1570 Emacs was iconified for a longer period of time. In that
1571 case, current matrices may still contain references to
1572 images freed above. So, clear these matrices. */
1575 Lisp_Object tail
, frame
;
1577 FOR_EACH_FRAME (tail
, frame
)
1579 struct frame
*fr
= XFRAME (frame
);
1580 if (FRAME_IMAGE_CACHE (fr
) == c
)
1581 clear_current_matrices (fr
);
1584 windows_or_buffers_changed
= 19;
1592 clear_image_caches (Lisp_Object filter
)
1594 /* FIXME: We want to do
1595 * struct terminal *t;
1596 * for (t = terminal_list; t; t = t->next_terminal)
1597 * clear_image_cache (t, filter); */
1598 Lisp_Object tail
, frame
;
1599 FOR_EACH_FRAME (tail
, frame
)
1600 if (FRAME_WINDOW_P (XFRAME (frame
)))
1601 clear_image_cache (XFRAME (frame
), filter
);
1604 DEFUN ("clear-image-cache", Fclear_image_cache
, Sclear_image_cache
,
1606 doc
: /* Clear the image cache.
1607 FILTER nil or a frame means clear all images in the selected frame.
1608 FILTER t means clear the image caches of all frames.
1609 Anything else, means only clear those images which refer to FILTER,
1610 which is then usually a filename. */)
1611 (Lisp_Object filter
)
1613 if (!(EQ (filter
, Qnil
) || FRAMEP (filter
)))
1614 clear_image_caches (filter
);
1616 clear_image_cache (decode_window_system_frame (filter
), Qt
);
1622 DEFUN ("image-flush", Fimage_flush
, Simage_flush
,
1624 doc
: /* Flush the image with specification SPEC on frame FRAME.
1625 This removes the image from the Emacs image cache. If SPEC specifies
1626 an image file, the next redisplay of this image will read from the
1627 current contents of that file.
1629 FRAME nil or omitted means use the selected frame.
1630 FRAME t means refresh the image on all frames. */)
1631 (Lisp_Object spec
, Lisp_Object frame
)
1633 if (!valid_image_p (spec
))
1634 error ("Invalid image specification");
1639 FOR_EACH_FRAME (tail
, frame
)
1641 struct frame
*f
= XFRAME (frame
);
1642 if (FRAME_WINDOW_P (f
))
1643 uncache_image (f
, spec
);
1647 uncache_image (decode_window_system_frame (frame
), spec
);
1653 /* Compute masks and transform image IMG on frame F, as specified
1654 by the image's specification, */
1657 postprocess_image (struct frame
*f
, struct image
*img
)
1659 /* Manipulation of the image's mask. */
1662 Lisp_Object conversion
, spec
;
1667 /* `:heuristic-mask t'
1669 means build a mask heuristically.
1670 `:heuristic-mask (R G B)'
1671 `:mask (heuristic (R G B))'
1672 means build a mask from color (R G B) in the
1675 means remove a mask, if any. */
1677 mask
= image_spec_value (spec
, QCheuristic_mask
, NULL
);
1679 x_build_heuristic_mask (f
, img
, mask
);
1684 mask
= image_spec_value (spec
, QCmask
, &found_p
);
1686 if (EQ (mask
, Qheuristic
))
1687 x_build_heuristic_mask (f
, img
, Qt
);
1688 else if (CONSP (mask
)
1689 && EQ (XCAR (mask
), Qheuristic
))
1691 if (CONSP (XCDR (mask
)))
1692 x_build_heuristic_mask (f
, img
, XCAR (XCDR (mask
)));
1694 x_build_heuristic_mask (f
, img
, XCDR (mask
));
1696 else if (NILP (mask
) && found_p
&& img
->mask
)
1697 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
1701 /* Should we apply an image transformation algorithm? */
1702 conversion
= image_spec_value (spec
, QCconversion
, NULL
);
1703 if (EQ (conversion
, Qdisabled
))
1704 x_disable_image (f
, img
);
1705 else if (EQ (conversion
, Qlaplace
))
1707 else if (EQ (conversion
, Qemboss
))
1709 else if (CONSP (conversion
)
1710 && EQ (XCAR (conversion
), Qedge_detection
))
1713 tem
= XCDR (conversion
);
1715 x_edge_detection (f
, img
,
1716 Fplist_get (tem
, QCmatrix
),
1717 Fplist_get (tem
, QCcolor_adjustment
));
1723 /* Return the id of image with Lisp specification SPEC on frame F.
1724 SPEC must be a valid Lisp image specification (see valid_image_p). */
1727 lookup_image (struct frame
*f
, Lisp_Object spec
)
1732 /* F must be a window-system frame, and SPEC must be a valid image
1734 eassert (FRAME_WINDOW_P (f
));
1735 eassert (valid_image_p (spec
));
1737 /* Look up SPEC in the hash table of the image cache. */
1738 hash
= sxhash (spec
, 0);
1739 img
= search_image_cache (f
, spec
, hash
);
1740 if (img
&& img
->load_failed_p
)
1742 free_image (f
, img
);
1746 /* If not found, create a new image and cache it. */
1750 img
= make_image (spec
, hash
);
1751 cache_image (f
, img
);
1752 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1753 img
->frame_foreground
= FRAME_FOREGROUND_PIXEL (f
);
1754 img
->frame_background
= FRAME_BACKGROUND_PIXEL (f
);
1756 /* If we can't load the image, and we don't have a width and
1757 height, use some arbitrary width and height so that we can
1758 draw a rectangle for it. */
1759 if (img
->load_failed_p
)
1763 value
= image_spec_value (spec
, QCwidth
, NULL
);
1764 img
->width
= (INTEGERP (value
)
1765 ? XFASTINT (value
) : DEFAULT_IMAGE_WIDTH
);
1766 value
= image_spec_value (spec
, QCheight
, NULL
);
1767 img
->height
= (INTEGERP (value
)
1768 ? XFASTINT (value
) : DEFAULT_IMAGE_HEIGHT
);
1772 /* Handle image type independent image attributes
1773 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1774 `:background COLOR'. */
1775 Lisp_Object ascent
, margin
, relief
, bg
;
1778 ascent
= image_spec_value (spec
, QCascent
, NULL
);
1779 if (INTEGERP (ascent
))
1780 img
->ascent
= XFASTINT (ascent
);
1781 else if (EQ (ascent
, Qcenter
))
1782 img
->ascent
= CENTERED_IMAGE_ASCENT
;
1784 margin
= image_spec_value (spec
, QCmargin
, NULL
);
1785 if (INTEGERP (margin
))
1786 img
->vmargin
= img
->hmargin
= XFASTINT (margin
);
1787 else if (CONSP (margin
))
1789 img
->hmargin
= XFASTINT (XCAR (margin
));
1790 img
->vmargin
= XFASTINT (XCDR (margin
));
1793 relief
= image_spec_value (spec
, QCrelief
, NULL
);
1794 relief_bound
= INT_MAX
- max (img
->hmargin
, img
->vmargin
);
1795 if (RANGED_INTEGERP (- relief_bound
, relief
, relief_bound
))
1797 img
->relief
= XINT (relief
);
1798 img
->hmargin
+= eabs (img
->relief
);
1799 img
->vmargin
+= eabs (img
->relief
);
1802 if (! img
->background_valid
)
1804 bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1808 = x_alloc_image_color (f
, img
, bg
,
1809 FRAME_BACKGROUND_PIXEL (f
));
1810 img
->background_valid
= 1;
1814 /* Do image transformations and compute masks, unless we
1815 don't have the image yet. */
1816 if (!EQ (builtin_lisp_symbol (img
->type
->type
), Qpostscript
))
1817 postprocess_image (f
, img
);
1823 /* We're using IMG, so set its timestamp to `now'. */
1824 img
->timestamp
= current_timespec ();
1826 /* Value is the image id. */
1831 /* Cache image IMG in the image cache of frame F. */
1834 cache_image (struct frame
*f
, struct image
*img
)
1836 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1840 c
= FRAME_IMAGE_CACHE (f
) = make_image_cache ();
1842 /* Find a free slot in c->images. */
1843 for (i
= 0; i
< c
->used
; ++i
)
1844 if (c
->images
[i
] == NULL
)
1847 /* If no free slot found, maybe enlarge c->images. */
1848 if (i
== c
->used
&& c
->used
== c
->size
)
1849 c
->images
= xpalloc (c
->images
, &c
->size
, 1, -1, sizeof *c
->images
);
1851 /* Add IMG to c->images, and assign IMG an id. */
1857 /* Add IMG to the cache's hash table. */
1858 i
= img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1859 img
->next
= c
->buckets
[i
];
1861 img
->next
->prev
= img
;
1863 c
->buckets
[i
] = img
;
1867 /* Call FN on every image in the image cache of frame F. Used to mark
1868 Lisp Objects in the image cache. */
1870 /* Mark Lisp objects in image IMG. */
1873 mark_image (struct image
*img
)
1875 mark_object (img
->spec
);
1876 mark_object (img
->dependencies
);
1878 if (!NILP (img
->lisp_data
))
1879 mark_object (img
->lisp_data
);
1884 mark_image_cache (struct image_cache
*c
)
1889 for (i
= 0; i
< c
->used
; ++i
)
1891 mark_image (c
->images
[i
]);
1897 /***********************************************************************
1898 X / NS / W32 support code
1899 ***********************************************************************/
1901 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1903 WIDTH and HEIGHT must both be positive.
1904 If XIMG is null, assume it is a bitmap. */
1906 x_check_image_size (XImagePtr ximg
, int width
, int height
)
1908 #ifdef HAVE_X_WINDOWS
1909 /* Respect Xlib's limits: it cannot deal with images that have more
1910 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1911 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1914 XLIB_BYTES_MAX
= min (INT_MAX
, UINT_MAX
),
1915 X_IMAGE_BYTES_MAX
= min (XLIB_BYTES_MAX
, min (PTRDIFF_MAX
, SIZE_MAX
))
1918 int bitmap_pad
, depth
, bytes_per_line
;
1921 bitmap_pad
= ximg
->bitmap_pad
;
1922 depth
= ximg
->depth
;
1923 bytes_per_line
= ximg
->bytes_per_line
;
1929 bytes_per_line
= (width
>> 3) + ((width
& 7) != 0);
1931 return (width
<= (INT_MAX
- (bitmap_pad
- 1)) / depth
1932 && height
<= X_IMAGE_BYTES_MAX
/ bytes_per_line
);
1934 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1935 For now, assume that every image size is allowed on these systems. */
1940 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1941 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1942 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1943 via xmalloc. Print error messages via image_error if an error
1944 occurs. Value is true if successful.
1946 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1947 should indicate the bit depth of the image. */
1950 x_create_x_image_and_pixmap (struct frame
*f
, int width
, int height
, int depth
,
1951 XImagePtr
*ximg
, Pixmap
*pixmap
)
1953 #ifdef HAVE_X_WINDOWS
1954 Display
*display
= FRAME_X_DISPLAY (f
);
1955 Drawable drawable
= FRAME_X_DRAWABLE (f
);
1956 Screen
*screen
= FRAME_X_SCREEN (f
);
1958 eassert (input_blocked_p ());
1961 depth
= DefaultDepthOfScreen (screen
);
1962 *ximg
= XCreateImage (display
, DefaultVisualOfScreen (screen
),
1963 depth
, ZPixmap
, 0, NULL
, width
, height
,
1964 depth
> 16 ? 32 : depth
> 8 ? 16 : 8, 0);
1967 image_error ("Unable to allocate X image");
1971 if (! x_check_image_size (*ximg
, width
, height
))
1973 x_destroy_x_image (*ximg
);
1975 image_error ("Image too large (%dx%d)",
1976 make_number (width
), make_number (height
));
1980 /* Allocate image raster. */
1981 (*ximg
)->data
= xmalloc ((*ximg
)->bytes_per_line
* height
);
1983 /* Allocate a pixmap of the same size. */
1984 *pixmap
= XCreatePixmap (display
, drawable
, width
, height
, depth
);
1985 if (*pixmap
== NO_PIXMAP
)
1987 x_destroy_x_image (*ximg
);
1989 image_error ("Unable to create X pixmap");
1994 #endif /* HAVE_X_WINDOWS */
1998 BITMAPINFOHEADER
*header
;
2000 int scanline_width_bits
;
2002 int palette_colors
= 0;
2007 if (depth
!= 1 && depth
!= 4 && depth
!= 8
2008 && depth
!= 16 && depth
!= 24 && depth
!= 32)
2010 image_error ("Invalid image bit depth specified");
2014 scanline_width_bits
= width
* depth
;
2015 remainder
= scanline_width_bits
% 32;
2018 scanline_width_bits
+= 32 - remainder
;
2020 /* Bitmaps with a depth less than 16 need a palette. */
2021 /* BITMAPINFO structure already contains the first RGBQUAD. */
2023 palette_colors
= 1 << (depth
- 1);
2025 *ximg
= xmalloc (sizeof (XImage
) + palette_colors
* sizeof (RGBQUAD
));
2027 header
= &(*ximg
)->info
.bmiHeader
;
2028 memset (&(*ximg
)->info
, 0, sizeof (BITMAPINFO
));
2029 header
->biSize
= sizeof (*header
);
2030 header
->biWidth
= width
;
2031 header
->biHeight
= -height
; /* negative indicates a top-down bitmap. */
2032 header
->biPlanes
= 1;
2033 header
->biBitCount
= depth
;
2034 header
->biCompression
= BI_RGB
;
2035 header
->biClrUsed
= palette_colors
;
2037 /* TODO: fill in palette. */
2040 (*ximg
)->info
.bmiColors
[0].rgbBlue
= 0;
2041 (*ximg
)->info
.bmiColors
[0].rgbGreen
= 0;
2042 (*ximg
)->info
.bmiColors
[0].rgbRed
= 0;
2043 (*ximg
)->info
.bmiColors
[0].rgbReserved
= 0;
2044 (*ximg
)->info
.bmiColors
[1].rgbBlue
= 255;
2045 (*ximg
)->info
.bmiColors
[1].rgbGreen
= 255;
2046 (*ximg
)->info
.bmiColors
[1].rgbRed
= 255;
2047 (*ximg
)->info
.bmiColors
[1].rgbReserved
= 0;
2050 hdc
= get_frame_dc (f
);
2052 /* Create a DIBSection and raster array for the bitmap,
2053 and store its handle in *pixmap. */
2054 *pixmap
= CreateDIBSection (hdc
, &((*ximg
)->info
),
2055 (depth
< 16) ? DIB_PAL_COLORS
: DIB_RGB_COLORS
,
2056 /* casting avoids a GCC warning */
2057 (void **)&((*ximg
)->data
), NULL
, 0);
2059 /* Realize display palette and garbage all frames. */
2060 release_frame_dc (f
, hdc
);
2062 if (*pixmap
== NULL
)
2064 DWORD err
= GetLastError ();
2065 Lisp_Object errcode
;
2066 /* All system errors are < 10000, so the following is safe. */
2067 XSETINT (errcode
, err
);
2068 image_error ("Unable to create bitmap, error code %d", errcode
);
2069 x_destroy_x_image (*ximg
);
2076 #endif /* HAVE_NTGUI */
2079 *pixmap
= ns_image_for_XPM (width
, height
, depth
);
2083 image_error ("Unable to allocate NSImage for XPM pixmap");
2092 /* Destroy XImage XIMG. Free XIMG->data. */
2095 x_destroy_x_image (XImagePtr ximg
)
2097 eassert (input_blocked_p ());
2100 #ifdef HAVE_X_WINDOWS
2103 XDestroyImage (ximg
);
2104 #endif /* HAVE_X_WINDOWS */
2106 /* Data will be freed by DestroyObject. */
2109 #endif /* HAVE_NTGUI */
2111 ns_release_object (ximg
);
2112 #endif /* HAVE_NS */
2117 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2118 are width and height of both the image and pixmap. */
2121 x_put_x_image (struct frame
*f
, XImagePtr ximg
, Pixmap pixmap
, int width
, int height
)
2123 #ifdef HAVE_X_WINDOWS
2126 eassert (input_blocked_p ());
2127 gc
= XCreateGC (FRAME_X_DISPLAY (f
), pixmap
, 0, NULL
);
2128 XPutImage (FRAME_X_DISPLAY (f
), pixmap
, gc
, ximg
, 0, 0, 0, 0, width
, height
);
2129 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
2130 #endif /* HAVE_X_WINDOWS */
2133 #if 0 /* I don't think this is necessary looking at where it is used. */
2134 HDC hdc
= get_frame_dc (f
);
2135 SetDIBits (hdc
, pixmap
, 0, height
, ximg
->data
, &(ximg
->info
), DIB_RGB_COLORS
);
2136 release_frame_dc (f
, hdc
);
2138 #endif /* HAVE_NTGUI */
2141 eassert (ximg
== pixmap
);
2142 ns_retain_object (ximg
);
2146 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2147 with image_put_x_image. */
2150 image_create_x_image_and_pixmap (struct frame
*f
, struct image
*img
,
2151 int width
, int height
, int depth
,
2152 XImagePtr
*ximg
, bool mask_p
)
2154 eassert ((!mask_p
? img
->pixmap
: img
->mask
) == NO_PIXMAP
);
2156 return x_create_x_image_and_pixmap (f
, width
, height
, depth
, ximg
,
2157 !mask_p
? &img
->pixmap
: &img
->mask
);
2160 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2161 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2162 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2163 On the other platforms, it puts XIMG into the pixmap, then frees
2164 the X image and its buffer. */
2167 image_put_x_image (struct frame
*f
, struct image
*img
, XImagePtr ximg
,
2170 #ifdef HAVE_X_WINDOWS
2173 eassert (img
->ximg
== NULL
);
2178 eassert (img
->mask_img
== NULL
);
2179 img
->mask_img
= ximg
;
2182 x_put_x_image (f
, ximg
, !mask_p
? img
->pixmap
: img
->mask
,
2183 img
->width
, img
->height
);
2184 x_destroy_x_image (ximg
);
2188 #ifdef HAVE_X_WINDOWS
2189 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2190 the X images and their buffers. */
2193 image_sync_to_pixmaps (struct frame
*f
, struct image
*img
)
2197 x_put_x_image (f
, img
->ximg
, img
->pixmap
, img
->width
, img
->height
);
2198 x_destroy_x_image (img
->ximg
);
2203 x_put_x_image (f
, img
->mask_img
, img
->mask
, img
->width
, img
->height
);
2204 x_destroy_x_image (img
->mask_img
);
2205 img
->mask_img
= NULL
;
2211 /* Create a memory device context for IMG on frame F. It stores the
2212 currently selected GDI object into *PREV for future restoration by
2213 image_unget_x_image_or_dc. */
2215 static XImagePtr_or_DC
2216 image_get_x_image_or_dc (struct frame
*f
, struct image
*img
, bool mask_p
,
2219 HDC frame_dc
= get_frame_dc (f
);
2220 XImagePtr_or_DC ximg
= CreateCompatibleDC (frame_dc
);
2222 release_frame_dc (f
, frame_dc
);
2223 *prev
= SelectObject (ximg
, !mask_p
? img
->pixmap
: img
->mask
);
2229 image_unget_x_image_or_dc (struct image
*img
, bool mask_p
,
2230 XImagePtr_or_DC ximg
, HGDIOBJ prev
)
2232 SelectObject (ximg
, prev
);
2235 #else /* !HAVE_NTGUI */
2236 /* Get the X image for IMG on frame F. The resulting X image data
2237 should be treated as read-only at least on X. */
2240 image_get_x_image (struct frame
*f
, struct image
*img
, bool mask_p
)
2242 #ifdef HAVE_X_WINDOWS
2243 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2248 return XGetImage (FRAME_X_DISPLAY (f
), !mask_p
? img
->pixmap
: img
->mask
,
2249 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
2250 #elif defined (HAVE_NS)
2251 XImagePtr pixmap
= !mask_p
? img
->pixmap
: img
->mask
;
2253 ns_retain_object (pixmap
);
2259 image_unget_x_image (struct image
*img
, bool mask_p
, XImagePtr ximg
)
2261 #ifdef HAVE_X_WINDOWS
2262 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2265 eassert (ximg
== ximg_in_img
);
2267 XDestroyImage (ximg
);
2268 #elif defined (HAVE_NS)
2269 ns_release_object (ximg
);
2272 #endif /* !HAVE_NTGUI */
2275 /***********************************************************************
2277 ***********************************************************************/
2279 /* Find image file FILE. Look in data-directory/images, then
2280 x-bitmap-file-path. Value is the full name of the file
2281 found, or nil if not found. If PFD is nonnull store into *PFD a
2282 readable file descriptor for the file, opened in binary mode. If
2283 PFD is null, do not open the file. */
2286 x_find_image_fd (Lisp_Object file
, int *pfd
)
2288 Lisp_Object file_found
, search_path
;
2291 /* TODO I think this should use something like image-load-path
2292 instead. Unfortunately, that can contain non-string elements. */
2293 search_path
= Fcons (Fexpand_file_name (build_string ("images"),
2295 Vx_bitmap_file_path
);
2297 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2298 fd
= openp (search_path
, file
, Qnil
, &file_found
,
2299 pfd
? Qt
: make_number (R_OK
), false);
2300 if (fd
>= 0 || fd
== -2)
2302 file_found
= ENCODE_FILE (file_found
);
2305 /* The file exists locally, but has a file handler. (This
2306 happens, e.g., under Auto Image File Mode.) 'openp'
2307 didn't open the file, so we should, because the caller
2309 fd
= emacs_open (SSDATA (file_found
), O_RDONLY
, 0);
2312 else /* fd < 0, but not -2 */
2319 /* Find image file FILE. Look in data-directory/images, then
2320 x-bitmap-file-path. Value is the encoded full name of the file
2321 found, or nil if not found. */
2324 x_find_image_file (Lisp_Object file
)
2326 return x_find_image_fd (file
, 0);
2329 /* Read FILE into memory. Value is a pointer to a buffer allocated
2330 with xmalloc holding FILE's contents. Value is null if an error
2331 occurred. FD is a file descriptor open for reading FILE. Set
2332 *SIZE to the size of the file. */
2335 slurp_file (int fd
, ptrdiff_t *size
)
2337 FILE *fp
= fdopen (fd
, "rb");
2344 ptrdiff_t count
= SPECPDL_INDEX ();
2345 record_unwind_protect_ptr (fclose_unwind
, fp
);
2347 if (fstat (fileno (fp
), &st
) == 0
2348 && 0 <= st
.st_size
&& st
.st_size
< min (PTRDIFF_MAX
, SIZE_MAX
))
2350 /* Report an error if we read past the purported EOF.
2351 This can happen if the file grows as we read it. */
2352 ptrdiff_t buflen
= st
.st_size
;
2353 buf
= xmalloc (buflen
+ 1);
2354 if (fread (buf
, 1, buflen
+ 1, fp
) == buflen
)
2363 unbind_to (count
, Qnil
);
2371 /***********************************************************************
2373 ***********************************************************************/
2375 static bool xbm_load (struct frame
*f
, struct image
*img
);
2376 static bool xbm_image_p (Lisp_Object object
);
2377 static bool xbm_file_p (Lisp_Object
);
2380 /* Indices of image specification fields in xbm_format, below. */
2382 enum xbm_keyword_index
2400 /* Vector of image_keyword structures describing the format
2401 of valid XBM image specifications. */
2403 static const struct image_keyword xbm_format
[XBM_LAST
] =
2405 {":type", IMAGE_SYMBOL_VALUE
, 1},
2406 {":file", IMAGE_STRING_VALUE
, 0},
2407 {":width", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2408 {":height", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2409 {":data", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2410 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
2411 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
2412 {":ascent", IMAGE_ASCENT_VALUE
, 0},
2413 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
2414 {":relief", IMAGE_INTEGER_VALUE
, 0},
2415 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2416 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2417 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
2420 /* Structure describing the image type XBM. */
2422 static struct image_type xbm_type
=
2424 SYMBOL_INDEX (Qxbm
),
2432 /* Tokens returned from xbm_scan. */
2441 /* Return true if OBJECT is a valid XBM-type image specification.
2442 A valid specification is a list starting with the symbol `image'
2443 The rest of the list is a property list which must contain an
2446 If the specification specifies a file to load, it must contain
2447 an entry `:file FILENAME' where FILENAME is a string.
2449 If the specification is for a bitmap loaded from memory it must
2450 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2451 WIDTH and HEIGHT are integers > 0. DATA may be:
2453 1. a string large enough to hold the bitmap data, i.e. it must
2454 have a size >= (WIDTH + 7) / 8 * HEIGHT
2456 2. a bool-vector of size >= WIDTH * HEIGHT
2458 3. a vector of strings or bool-vectors, one for each line of the
2461 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2462 may not be specified in this case because they are defined in the
2465 Both the file and data forms may contain the additional entries
2466 `:background COLOR' and `:foreground COLOR'. If not present,
2467 foreground and background of the frame on which the image is
2468 displayed is used. */
2471 xbm_image_p (Lisp_Object object
)
2473 struct image_keyword kw
[XBM_LAST
];
2475 memcpy (kw
, xbm_format
, sizeof kw
);
2476 if (!parse_image_spec (object
, kw
, XBM_LAST
, Qxbm
))
2479 eassert (EQ (kw
[XBM_TYPE
].value
, Qxbm
));
2481 if (kw
[XBM_FILE
].count
)
2483 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_DATA
].count
)
2486 else if (kw
[XBM_DATA
].count
&& xbm_file_p (kw
[XBM_DATA
].value
))
2488 /* In-memory XBM file. */
2489 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_FILE
].count
)
2497 /* Entries for `:width', `:height' and `:data' must be present. */
2498 if (!kw
[XBM_WIDTH
].count
2499 || !kw
[XBM_HEIGHT
].count
2500 || !kw
[XBM_DATA
].count
)
2503 data
= kw
[XBM_DATA
].value
;
2504 width
= XFASTINT (kw
[XBM_WIDTH
].value
);
2505 height
= XFASTINT (kw
[XBM_HEIGHT
].value
);
2507 /* Check type of data, and width and height against contents of
2513 /* Number of elements of the vector must be >= height. */
2514 if (ASIZE (data
) < height
)
2517 /* Each string or bool-vector in data must be large enough
2518 for one line of the image. */
2519 for (i
= 0; i
< height
; ++i
)
2521 Lisp_Object elt
= AREF (data
, i
);
2526 < (width
+ CHAR_BIT
- 1) / CHAR_BIT
)
2529 else if (BOOL_VECTOR_P (elt
))
2531 if (bool_vector_size (elt
) < width
)
2538 else if (STRINGP (data
))
2541 < (width
+ CHAR_BIT
- 1) / CHAR_BIT
* height
)
2544 else if (BOOL_VECTOR_P (data
))
2546 if (bool_vector_size (data
) / height
< width
)
2557 /* Scan a bitmap file. FP is the stream to read from. Value is
2558 either an enumerator from enum xbm_token, or a character for a
2559 single-character token, or 0 at end of file. If scanning an
2560 identifier, store the lexeme of the identifier in SVAL. If
2561 scanning a number, store its value in *IVAL. */
2564 xbm_scan (char **s
, char *end
, char *sval
, int *ival
)
2570 /* Skip white space. */
2571 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
2576 else if (c_isdigit (c
))
2578 int value
= 0, digit
;
2580 if (c
== '0' && *s
< end
)
2583 if (c
== 'x' || c
== 'X')
2590 else if (c
>= 'a' && c
<= 'f')
2591 digit
= c
- 'a' + 10;
2592 else if (c
>= 'A' && c
<= 'F')
2593 digit
= c
- 'A' + 10;
2596 value
= 16 * value
+ digit
;
2599 else if (c_isdigit (c
))
2603 && (c
= *(*s
)++, c_isdigit (c
)))
2604 value
= 8 * value
+ c
- '0';
2611 && (c
= *(*s
)++, c_isdigit (c
)))
2612 value
= 10 * value
+ c
- '0';
2618 return XBM_TK_NUMBER
;
2620 else if (c_isalpha (c
) || c
== '_')
2624 && (c
= *(*s
)++, (c_isalnum (c
) || c
== '_')))
2629 return XBM_TK_IDENT
;
2631 else if (c
== '/' && **s
== '*')
2633 /* C-style comment. */
2635 while (**s
&& (**s
!= '*' || *(*s
+ 1) != '/'))
2649 /* Create a Windows bitmap from X bitmap data. */
2651 w32_create_pixmap_from_bitmap_data (int width
, int height
, char *data
)
2653 static unsigned char swap_nibble
[16]
2654 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2655 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2656 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2657 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2659 unsigned char *bits
, *p
;
2662 w1
= (width
+ 7) / 8; /* nb of 8bits elt in X bitmap */
2663 w2
= ((width
+ 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2664 bits
= alloca (height
* w2
);
2665 memset (bits
, 0, height
* w2
);
2666 for (i
= 0; i
< height
; i
++)
2669 for (j
= 0; j
< w1
; j
++)
2671 /* Bitswap XBM bytes to match how Windows does things. */
2672 unsigned char c
= *data
++;
2673 *p
++ = (unsigned char)((swap_nibble
[c
& 0xf] << 4)
2674 | (swap_nibble
[(c
>>4) & 0xf]));
2677 bmp
= CreateBitmap (width
, height
, 1, 1, (char *) bits
);
2683 convert_mono_to_color_image (struct frame
*f
, struct image
*img
,
2684 COLORREF foreground
, COLORREF background
)
2686 HDC hdc
, old_img_dc
, new_img_dc
;
2687 HGDIOBJ old_prev
, new_prev
;
2690 hdc
= get_frame_dc (f
);
2691 old_img_dc
= CreateCompatibleDC (hdc
);
2692 new_img_dc
= CreateCompatibleDC (hdc
);
2693 new_pixmap
= CreateCompatibleBitmap (hdc
, img
->width
, img
->height
);
2694 release_frame_dc (f
, hdc
);
2695 old_prev
= SelectObject (old_img_dc
, img
->pixmap
);
2696 new_prev
= SelectObject (new_img_dc
, new_pixmap
);
2697 /* Windows convention for mono bitmaps is black = background,
2698 white = foreground. */
2699 SetTextColor (new_img_dc
, background
);
2700 SetBkColor (new_img_dc
, foreground
);
2702 BitBlt (new_img_dc
, 0, 0, img
->width
, img
->height
, old_img_dc
,
2705 SelectObject (old_img_dc
, old_prev
);
2706 SelectObject (new_img_dc
, new_prev
);
2707 DeleteDC (old_img_dc
);
2708 DeleteDC (new_img_dc
);
2709 DeleteObject (img
->pixmap
);
2710 if (new_pixmap
== 0)
2711 fprintf (stderr
, "Failed to convert image to color.\n");
2713 img
->pixmap
= new_pixmap
;
2716 #define XBM_BIT_SHUFFLE(b) (~(b))
2720 #define XBM_BIT_SHUFFLE(b) (b)
2722 #endif /* HAVE_NTGUI */
2726 Create_Pixmap_From_Bitmap_Data (struct frame
*f
, struct image
*img
, char *data
,
2727 RGB_PIXEL_COLOR fg
, RGB_PIXEL_COLOR bg
,
2728 bool non_default_colors
)
2732 = w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
, data
);
2734 /* If colors were specified, transfer the bitmap to a color one. */
2735 if (non_default_colors
)
2736 convert_mono_to_color_image (f
, img
, fg
, bg
);
2738 #elif defined (HAVE_NS)
2739 img
->pixmap
= ns_image_from_XBM (data
, img
->width
, img
->height
, fg
, bg
);
2743 (x_check_image_size (0, img
->width
, img
->height
)
2744 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f
),
2745 FRAME_X_DRAWABLE (f
),
2747 img
->width
, img
->height
,
2749 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)))
2751 #endif /* !HAVE_NTGUI && !HAVE_NS */
2756 /* Replacement for XReadBitmapFileData which isn't available under old
2757 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2758 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2759 the image. Return in *DATA the bitmap data allocated with xmalloc.
2760 Value is true if successful. DATA null means just test if
2761 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2762 inhibit the call to image_error when the image size is invalid (the
2763 bitmap remains unread). */
2766 xbm_read_bitmap_data (struct frame
*f
, char *contents
, char *end
,
2767 int *width
, int *height
, char **data
,
2768 bool inhibit_image_error
)
2771 char buffer
[BUFSIZ
];
2774 int bytes_per_line
, i
, nbytes
;
2780 LA1 = xbm_scan (&s, end, buffer, &value)
2782 #define expect(TOKEN) \
2785 if (LA1 != (TOKEN)) \
2791 #define expect_ident(IDENT) \
2792 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2797 *width
= *height
= -1;
2800 LA1
= xbm_scan (&s
, end
, buffer
, &value
);
2802 /* Parse defines for width, height and hot-spots. */
2806 expect_ident ("define");
2807 expect (XBM_TK_IDENT
);
2809 if (LA1
== XBM_TK_NUMBER
)
2811 char *q
= strrchr (buffer
, '_');
2812 q
= q
? q
+ 1 : buffer
;
2813 if (strcmp (q
, "width") == 0)
2815 else if (strcmp (q
, "height") == 0)
2818 expect (XBM_TK_NUMBER
);
2821 if (!check_image_size (f
, *width
, *height
))
2823 if (!inhibit_image_error
)
2824 image_size_error ();
2827 else if (data
== NULL
)
2830 /* Parse bits. Must start with `static'. */
2831 expect_ident ("static");
2832 if (LA1
== XBM_TK_IDENT
)
2834 if (strcmp (buffer
, "unsigned") == 0)
2837 expect_ident ("char");
2839 else if (strcmp (buffer
, "short") == 0)
2843 if (*width
% 16 && *width
% 16 < 9)
2846 else if (strcmp (buffer
, "char") == 0)
2854 expect (XBM_TK_IDENT
);
2860 if (! x_check_image_size (0, *width
, *height
))
2862 if (!inhibit_image_error
)
2863 image_error ("Image too large (%dx%d)",
2864 make_number (*width
), make_number (*height
));
2867 bytes_per_line
= (*width
+ 7) / 8 + padding_p
;
2868 nbytes
= bytes_per_line
* *height
;
2869 p
= *data
= xmalloc (nbytes
);
2873 for (i
= 0; i
< nbytes
; i
+= 2)
2876 expect (XBM_TK_NUMBER
);
2878 *p
++ = XBM_BIT_SHUFFLE (val
);
2879 if (!padding_p
|| ((i
+ 2) % bytes_per_line
))
2880 *p
++ = XBM_BIT_SHUFFLE (value
>> 8);
2882 if (LA1
== ',' || LA1
== '}')
2890 for (i
= 0; i
< nbytes
; ++i
)
2893 expect (XBM_TK_NUMBER
);
2895 *p
++ = XBM_BIT_SHUFFLE (val
);
2897 if (LA1
== ',' || LA1
== '}')
2922 /* Load XBM image IMG which will be displayed on frame F from buffer
2923 CONTENTS. END is the end of the buffer. Value is true if
2927 xbm_load_image (struct frame
*f
, struct image
*img
, char *contents
, char *end
)
2933 rc
= xbm_read_bitmap_data (f
, contents
, end
, &img
->width
, &img
->height
,
2937 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
2938 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
2939 bool non_default_colors
= 0;
2942 eassert (img
->width
> 0 && img
->height
> 0);
2944 /* Get foreground and background colors, maybe allocate colors. */
2945 value
= image_spec_value (img
->spec
, QCforeground
, NULL
);
2948 foreground
= x_alloc_image_color (f
, img
, value
, foreground
);
2949 non_default_colors
= 1;
2951 value
= image_spec_value (img
->spec
, QCbackground
, NULL
);
2954 background
= x_alloc_image_color (f
, img
, value
, background
);
2955 img
->background
= background
;
2956 img
->background_valid
= 1;
2957 non_default_colors
= 1;
2960 Create_Pixmap_From_Bitmap_Data (f
, img
, data
,
2961 foreground
, background
,
2962 non_default_colors
);
2965 if (img
->pixmap
== NO_PIXMAP
)
2967 x_clear_image (f
, img
);
2968 image_error ("Unable to create X pixmap for `%s'", img
->spec
);
2974 image_error ("Error loading XBM image `%s'", img
->spec
);
2980 /* Value is true if DATA looks like an in-memory XBM file. */
2983 xbm_file_p (Lisp_Object data
)
2986 return (STRINGP (data
)
2987 && xbm_read_bitmap_data (NULL
, SSDATA (data
),
2988 SSDATA (data
) + SBYTES (data
),
2993 /* Fill image IMG which is used on frame F with pixmap data. Value is
2994 true if successful. */
2997 xbm_load (struct frame
*f
, struct image
*img
)
3000 Lisp_Object file_name
;
3002 eassert (xbm_image_p (img
->spec
));
3004 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3005 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
3006 if (STRINGP (file_name
))
3009 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
3010 if (!STRINGP (file
))
3012 image_error ("Cannot find image file `%s'", file_name
);
3017 char *contents
= slurp_file (fd
, &size
);
3018 if (contents
== NULL
)
3020 image_error ("Error loading XBM image `%s'", file
);
3024 success_p
= xbm_load_image (f
, img
, contents
, contents
+ size
);
3029 struct image_keyword fmt
[XBM_LAST
];
3031 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
3032 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
3033 bool non_default_colors
= 0;
3036 bool in_memory_file_p
= 0;
3038 /* See if data looks like an in-memory XBM file. */
3039 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
3040 in_memory_file_p
= xbm_file_p (data
);
3042 /* Parse the image specification. */
3043 memcpy (fmt
, xbm_format
, sizeof fmt
);
3044 parsed_p
= parse_image_spec (img
->spec
, fmt
, XBM_LAST
, Qxbm
);
3047 /* Get specified width, and height. */
3048 if (!in_memory_file_p
)
3050 img
->width
= XFASTINT (fmt
[XBM_WIDTH
].value
);
3051 img
->height
= XFASTINT (fmt
[XBM_HEIGHT
].value
);
3052 eassert (img
->width
> 0 && img
->height
> 0);
3053 if (!check_image_size (f
, img
->width
, img
->height
))
3055 image_size_error ();
3060 /* Get foreground and background colors, maybe allocate colors. */
3061 if (fmt
[XBM_FOREGROUND
].count
3062 && STRINGP (fmt
[XBM_FOREGROUND
].value
))
3064 foreground
= x_alloc_image_color (f
, img
, fmt
[XBM_FOREGROUND
].value
,
3066 non_default_colors
= 1;
3069 if (fmt
[XBM_BACKGROUND
].count
3070 && STRINGP (fmt
[XBM_BACKGROUND
].value
))
3072 background
= x_alloc_image_color (f
, img
, fmt
[XBM_BACKGROUND
].value
,
3074 non_default_colors
= 1;
3077 if (in_memory_file_p
)
3078 success_p
= xbm_load_image (f
, img
, SSDATA (data
),
3079 SSDATA (data
) + SBYTES (data
));
3088 int nbytes
= (img
->width
+ CHAR_BIT
- 1) / CHAR_BIT
;
3090 SAFE_NALLOCA (bits
, nbytes
, img
->height
);
3092 for (i
= 0; i
< img
->height
; ++i
, p
+= nbytes
)
3094 Lisp_Object line
= AREF (data
, i
);
3096 memcpy (p
, SDATA (line
), nbytes
);
3098 memcpy (p
, bool_vector_data (line
), nbytes
);
3101 else if (STRINGP (data
))
3102 bits
= SSDATA (data
);
3104 bits
= (char *) bool_vector_data (data
);
3110 /* Windows mono bitmaps are reversed compared with X. */
3111 invertedBits
= bits
;
3112 nbytes
= (img
->width
+ CHAR_BIT
- 1) / CHAR_BIT
* img
->height
;
3113 SAFE_NALLOCA (bits
, 1, nbytes
);
3114 for (i
= 0; i
< nbytes
; i
++)
3115 bits
[i
] = XBM_BIT_SHUFFLE (invertedBits
[i
]);
3118 /* Create the pixmap. */
3120 if (x_check_image_size (0, img
->width
, img
->height
))
3121 Create_Pixmap_From_Bitmap_Data (f
, img
, bits
,
3122 foreground
, background
,
3123 non_default_colors
);
3125 img
->pixmap
= NO_PIXMAP
;
3131 image_error ("Unable to create pixmap for XBM image `%s'",
3133 x_clear_image (f
, img
);
3145 /***********************************************************************
3147 ***********************************************************************/
3149 #if defined (HAVE_XPM) || defined (HAVE_NS)
3151 static bool xpm_image_p (Lisp_Object object
);
3152 static bool xpm_load (struct frame
*f
, struct image
*img
);
3154 #endif /* HAVE_XPM || HAVE_NS */
3158 /* Indicate to xpm.h that we don't have Xlib. */
3160 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3161 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3162 #define XColor xpm_XColor
3163 #define XImage xpm_XImage
3164 #define Display xpm_Display
3166 #include "noX/xpm.h"
3167 #else /* not CYGWIN */
3168 #include "X11/xpm.h"
3169 #endif /* not CYGWIN */
3174 #else /* not HAVE_NTGUI */
3175 #include "X11/xpm.h"
3176 #endif /* not HAVE_NTGUI */
3177 #endif /* HAVE_XPM */
3179 #if defined (HAVE_XPM) || defined (HAVE_NS)
3181 /* Indices of image specification fields in xpm_format, below. */
3183 enum xpm_keyword_index
3199 /* Vector of image_keyword structures describing the format
3200 of valid XPM image specifications. */
3202 static const struct image_keyword xpm_format
[XPM_LAST
] =
3204 {":type", IMAGE_SYMBOL_VALUE
, 1},
3205 {":file", IMAGE_STRING_VALUE
, 0},
3206 {":data", IMAGE_STRING_VALUE
, 0},
3207 {":ascent", IMAGE_ASCENT_VALUE
, 0},
3208 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
3209 {":relief", IMAGE_INTEGER_VALUE
, 0},
3210 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3211 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3212 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3213 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3214 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
3217 #if defined HAVE_NTGUI && defined WINDOWSNT
3218 static bool init_xpm_functions (void);
3220 #define init_xpm_functions NULL
3223 /* Structure describing the image type XPM. */
3225 static struct image_type xpm_type
=
3227 SYMBOL_INDEX (Qxpm
),
3235 #ifdef HAVE_X_WINDOWS
3237 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3238 functions for allocating image colors. Our own functions handle
3239 color allocation failures more gracefully than the ones on the XPM
3243 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3244 #define ALLOC_XPM_COLORS
3246 #endif /* USE_CAIRO */
3247 #endif /* HAVE_X_WINDOWS */
3249 #ifdef ALLOC_XPM_COLORS
3251 static struct xpm_cached_color
*xpm_cache_color (struct frame
*, char *,
3254 /* An entry in a hash table used to cache color definitions of named
3255 colors. This cache is necessary to speed up XPM image loading in
3256 case we do color allocations ourselves. Without it, we would need
3257 a call to XParseColor per pixel in the image.
3259 FIXME Now that we're using x_parse_color and its cache, reevaluate
3260 the need for this caching layer. */
3262 struct xpm_cached_color
3264 /* Next in collision chain. */
3265 struct xpm_cached_color
*next
;
3267 /* Color definition (RGB and pixel color). */
3271 char name
[FLEXIBLE_ARRAY_MEMBER
];
3274 /* The hash table used for the color cache, and its bucket vector
3277 #define XPM_COLOR_CACHE_BUCKETS 1001
3278 static struct xpm_cached_color
**xpm_color_cache
;
3280 /* Initialize the color cache. */
3283 xpm_init_color_cache (struct frame
*f
, XpmAttributes
*attrs
)
3285 size_t nbytes
= XPM_COLOR_CACHE_BUCKETS
* sizeof *xpm_color_cache
;
3286 xpm_color_cache
= xzalloc (nbytes
);
3287 init_color_table ();
3289 if (attrs
->valuemask
& XpmColorSymbols
)
3294 for (i
= 0; i
< attrs
->numsymbols
; ++i
)
3295 if (x_parse_color (f
, attrs
->colorsymbols
[i
].value
, &color
))
3297 color
.pixel
= lookup_rgb_color (f
, color
.red
, color
.green
,
3299 xpm_cache_color (f
, attrs
->colorsymbols
[i
].name
, &color
, -1);
3304 /* Free the color cache. */
3307 xpm_free_color_cache (void)
3309 struct xpm_cached_color
*p
, *next
;
3312 for (i
= 0; i
< XPM_COLOR_CACHE_BUCKETS
; ++i
)
3313 for (p
= xpm_color_cache
[i
]; p
; p
= next
)
3319 xfree (xpm_color_cache
);
3320 xpm_color_cache
= NULL
;
3321 free_color_table ();
3324 /* Return the bucket index for color named COLOR_NAME in the color
3328 xpm_color_bucket (char *color_name
)
3330 EMACS_UINT hash
= hash_string (color_name
, strlen (color_name
));
3331 return hash
% XPM_COLOR_CACHE_BUCKETS
;
3335 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3336 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3339 static struct xpm_cached_color
*
3340 xpm_cache_color (struct frame
*f
, char *color_name
, XColor
*color
, int bucket
)
3343 struct xpm_cached_color
*p
;
3346 bucket
= xpm_color_bucket (color_name
);
3348 nbytes
= FLEXSIZEOF (struct xpm_cached_color
, name
, strlen (color_name
) + 1);
3349 p
= xmalloc (nbytes
);
3350 strcpy (p
->name
, color_name
);
3352 p
->next
= xpm_color_cache
[bucket
];
3353 xpm_color_cache
[bucket
] = p
;
3357 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3358 return the cached definition in *COLOR. Otherwise, make a new
3359 entry in the cache and allocate the color. Value is false if color
3360 allocation failed. */
3363 xpm_lookup_color (struct frame
*f
, char *color_name
, XColor
*color
)
3365 struct xpm_cached_color
*p
;
3366 int h
= xpm_color_bucket (color_name
);
3368 for (p
= xpm_color_cache
[h
]; p
; p
= p
->next
)
3369 if (strcmp (p
->name
, color_name
) == 0)
3374 else if (x_parse_color (f
, color_name
, color
))
3376 color
->pixel
= lookup_rgb_color (f
, color
->red
, color
->green
,
3378 p
= xpm_cache_color (f
, color_name
, color
, h
);
3380 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3381 with transparency, and it's useful. */
3382 else if (strcmp ("opaque", color_name
) == 0)
3384 memset (color
, 0, sizeof (XColor
)); /* Is this necessary/correct? */
3385 color
->pixel
= FRAME_FOREGROUND_PIXEL (f
);
3386 p
= xpm_cache_color (f
, color_name
, color
, h
);
3393 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3394 CLOSURE is a pointer to the frame on which we allocate the
3395 color. Return in *COLOR the allocated color. Value is non-zero
3399 xpm_alloc_color (Display
*dpy
, Colormap cmap
, char *color_name
, XColor
*color
,
3402 return xpm_lookup_color (closure
, color_name
, color
);
3406 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3407 is a pointer to the frame on which we allocate the color. Value is
3408 non-zero if successful. */
3411 xpm_free_colors (Display
*dpy
, Colormap cmap
, Pixel
*pixels
, int npixels
, void *closure
)
3416 #endif /* ALLOC_XPM_COLORS */
3421 /* XPM library details. */
3423 DEF_DLL_FN (void, XpmFreeAttributes
, (XpmAttributes
*));
3424 DEF_DLL_FN (int, XpmCreateImageFromBuffer
,
3425 (Display
*, char *, xpm_XImage
**,
3426 xpm_XImage
**, XpmAttributes
*));
3427 DEF_DLL_FN (int, XpmReadFileToImage
,
3428 (Display
*, char *, xpm_XImage
**,
3429 xpm_XImage
**, XpmAttributes
*));
3430 DEF_DLL_FN (void, XImageFree
, (xpm_XImage
*));
3433 init_xpm_functions (void)
3437 if (!(library
= w32_delayed_load (Qxpm
)))
3440 LOAD_DLL_FN (library
, XpmFreeAttributes
);
3441 LOAD_DLL_FN (library
, XpmCreateImageFromBuffer
);
3442 LOAD_DLL_FN (library
, XpmReadFileToImage
);
3443 LOAD_DLL_FN (library
, XImageFree
);
3448 # undef XpmCreateImageFromBuffer
3449 # undef XpmFreeAttributes
3450 # undef XpmReadFileToImage
3452 # define XImageFree fn_XImageFree
3453 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3454 # define XpmFreeAttributes fn_XpmFreeAttributes
3455 # define XpmReadFileToImage fn_XpmReadFileToImage
3457 #endif /* WINDOWSNT */
3459 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3460 for XPM images. Such a list must consist of conses whose car and
3464 xpm_valid_color_symbols_p (Lisp_Object color_symbols
)
3466 while (CONSP (color_symbols
))
3468 Lisp_Object sym
= XCAR (color_symbols
);
3470 || !STRINGP (XCAR (sym
))
3471 || !STRINGP (XCDR (sym
)))
3473 color_symbols
= XCDR (color_symbols
);
3476 return NILP (color_symbols
);
3480 /* Value is true if OBJECT is a valid XPM image specification. */
3483 xpm_image_p (Lisp_Object object
)
3485 struct image_keyword fmt
[XPM_LAST
];
3486 memcpy (fmt
, xpm_format
, sizeof fmt
);
3487 return (parse_image_spec (object
, fmt
, XPM_LAST
, Qxpm
)
3488 /* Either `:file' or `:data' must be present. */
3489 && fmt
[XPM_FILE
].count
+ fmt
[XPM_DATA
].count
== 1
3490 /* Either no `:color-symbols' or it's a list of conses
3491 whose car and cdr are strings. */
3492 && (fmt
[XPM_COLOR_SYMBOLS
].count
== 0
3493 || xpm_valid_color_symbols_p (fmt
[XPM_COLOR_SYMBOLS
].value
)));
3496 #endif /* HAVE_XPM || HAVE_NS */
3498 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3500 x_create_bitmap_from_xpm_data (struct frame
*f
, const char **bits
)
3502 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
3505 XpmAttributes attrs
;
3506 Pixmap bitmap
, mask
;
3508 memset (&attrs
, 0, sizeof attrs
);
3510 attrs
.visual
= FRAME_X_VISUAL (f
);
3511 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3512 attrs
.valuemask
|= XpmVisual
;
3513 attrs
.valuemask
|= XpmColormap
;
3515 #ifdef ALLOC_XPM_COLORS
3516 attrs
.color_closure
= f
;
3517 attrs
.alloc_color
= xpm_alloc_color
;
3518 attrs
.free_colors
= xpm_free_colors
;
3519 attrs
.valuemask
|= XpmAllocColor
| XpmFreeColors
| XpmColorClosure
;
3520 xpm_init_color_cache (f
, &attrs
);
3523 rc
= XpmCreatePixmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_DRAWABLE (f
),
3524 (char **) bits
, &bitmap
, &mask
, &attrs
);
3525 if (rc
!= XpmSuccess
)
3527 XpmFreeAttributes (&attrs
);
3531 id
= x_allocate_bitmap_record (f
);
3532 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
3533 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
3534 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
3535 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
3536 dpyinfo
->bitmaps
[id
- 1].height
= attrs
.height
;
3537 dpyinfo
->bitmaps
[id
- 1].width
= attrs
.width
;
3538 dpyinfo
->bitmaps
[id
- 1].depth
= attrs
.depth
;
3539 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
3541 #ifdef ALLOC_XPM_COLORS
3542 xpm_free_color_cache ();
3544 XpmFreeAttributes (&attrs
);
3547 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3549 /* Load image IMG which will be displayed on frame F. Value is
3550 true if successful. */
3555 xpm_load (struct frame
*f
, struct image
*img
)
3558 XpmAttributes attrs
;
3559 Lisp_Object specified_file
, color_symbols
;
3564 xpm_XImage
* xpm_image
= NULL
, * xpm_mask
= NULL
;
3565 #endif /* HAVE_NTGUI */
3567 /* Configure the XPM lib. Use the visual of frame F. Allocate
3568 close colors. Return colors allocated. */
3569 memset (&attrs
, 0, sizeof attrs
);
3572 attrs
.visual
= FRAME_X_VISUAL (f
);
3573 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3574 attrs
.valuemask
|= XpmVisual
;
3575 attrs
.valuemask
|= XpmColormap
;
3576 #endif /* HAVE_NTGUI */
3578 #ifdef ALLOC_XPM_COLORS
3579 /* Allocate colors with our own functions which handle
3580 failing color allocation more gracefully. */
3581 attrs
.color_closure
= f
;
3582 attrs
.alloc_color
= xpm_alloc_color
;
3583 attrs
.free_colors
= xpm_free_colors
;
3584 attrs
.valuemask
|= XpmAllocColor
| XpmFreeColors
| XpmColorClosure
;
3585 #else /* not ALLOC_XPM_COLORS */
3586 /* Let the XPM lib allocate colors. */
3587 attrs
.valuemask
|= XpmReturnAllocPixels
;
3588 #ifdef XpmAllocCloseColors
3589 attrs
.alloc_close_colors
= 1;
3590 attrs
.valuemask
|= XpmAllocCloseColors
;
3591 #else /* not XpmAllocCloseColors */
3592 attrs
.closeness
= 600;
3593 attrs
.valuemask
|= XpmCloseness
;
3594 #endif /* not XpmAllocCloseColors */
3595 #endif /* ALLOC_XPM_COLORS */
3597 /* If image specification contains symbolic color definitions, add
3598 these to `attrs'. */
3599 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
3600 if (CONSP (color_symbols
))
3603 XpmColorSymbol
*xpm_syms
;
3606 attrs
.valuemask
|= XpmColorSymbols
;
3608 /* Count number of symbols. */
3609 attrs
.numsymbols
= 0;
3610 for (tail
= color_symbols
; CONSP (tail
); tail
= XCDR (tail
))
3613 /* Allocate an XpmColorSymbol array. */
3614 SAFE_NALLOCA (xpm_syms
, 1, attrs
.numsymbols
);
3615 size
= attrs
.numsymbols
* sizeof *xpm_syms
;
3616 memset (xpm_syms
, 0, size
);
3617 attrs
.colorsymbols
= xpm_syms
;
3619 /* Fill the color symbol array. */
3620 for (tail
= color_symbols
, i
= 0;
3622 ++i
, tail
= XCDR (tail
))
3626 char *empty_string
= (char *) "";
3628 if (!CONSP (XCAR (tail
)))
3630 xpm_syms
[i
].name
= empty_string
;
3631 xpm_syms
[i
].value
= empty_string
;
3634 name
= XCAR (XCAR (tail
));
3635 color
= XCDR (XCAR (tail
));
3637 SAFE_ALLOCA_STRING (xpm_syms
[i
].name
, name
);
3639 xpm_syms
[i
].name
= empty_string
;
3640 if (STRINGP (color
))
3641 SAFE_ALLOCA_STRING (xpm_syms
[i
].value
, color
);
3643 xpm_syms
[i
].value
= empty_string
;
3647 /* Create a pixmap for the image, either from a file, or from a
3648 string buffer containing data in the same format as an XPM file. */
3649 #ifdef ALLOC_XPM_COLORS
3650 xpm_init_color_cache (f
, &attrs
);
3653 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
3657 HDC frame_dc
= get_frame_dc (f
);
3658 hdc
= CreateCompatibleDC (frame_dc
);
3659 release_frame_dc (f
, frame_dc
);
3661 #endif /* HAVE_NTGUI */
3663 if (STRINGP (specified_file
))
3665 Lisp_Object file
= x_find_image_file (specified_file
);
3666 if (!STRINGP (file
))
3668 image_error ("Cannot find image file `%s'", specified_file
);
3669 #ifdef ALLOC_XPM_COLORS
3670 xpm_free_color_cache ();
3676 file
= ENCODE_FILE (file
);
3679 /* FILE is encoded in UTF-8, but image libraries on Windows
3680 support neither UTF-8 nor UTF-16 encoded file names. So we
3681 need to re-encode it in ANSI. */
3682 file
= ansi_encode_filename (file
);
3684 /* XpmReadFileToPixmap is not available in the Windows port of
3685 libxpm. But XpmReadFileToImage almost does what we want. */
3686 rc
= XpmReadFileToImage (&hdc
, SSDATA (file
),
3687 &xpm_image
, &xpm_mask
,
3690 rc
= XpmReadFileToImage (FRAME_X_DISPLAY (f
), SSDATA (file
),
3691 &img
->ximg
, &img
->mask_img
,
3693 #endif /* HAVE_NTGUI */
3697 Lisp_Object buffer
= image_spec_value (img
->spec
, QCdata
, NULL
);
3698 if (!STRINGP (buffer
))
3700 image_error ("Invalid image data `%s'", buffer
);
3701 #ifdef ALLOC_XPM_COLORS
3702 xpm_free_color_cache ();
3708 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3709 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3710 rc
= XpmCreateImageFromBuffer (&hdc
, SSDATA (buffer
),
3711 &xpm_image
, &xpm_mask
,
3714 rc
= XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f
), SSDATA (buffer
),
3715 &img
->ximg
, &img
->mask_img
,
3717 #endif /* HAVE_NTGUI */
3721 /* Load very specific Xpm:s. */
3722 if (rc
== XpmSuccess
3723 && img
->ximg
->format
== ZPixmap
3724 && img
->ximg
->bits_per_pixel
== 32
3725 && (! img
->mask_img
|| img
->mask_img
->bits_per_pixel
== 1))
3727 int width
= img
->ximg
->width
;
3728 int height
= img
->ximg
->height
;
3729 void *data
= xmalloc (width
* height
* 4);
3731 uint32_t *od
= data
;
3732 uint32_t *id
= (uint32_t *) img
->ximg
->data
;
3733 char *mid
= img
->mask_img
? img
->mask_img
->data
: 0;
3734 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
3736 for (i
= 0; i
< height
; ++i
)
3739 for (k
= 0; k
< width
; ++k
)
3741 int idx
= i
* img
->ximg
->bytes_per_line
/4 + k
;
3742 int maskidx
= mid
? i
* img
->mask_img
->bytes_per_line
+ k
/8 : 0;
3743 int mask
= mid
? mid
[maskidx
] & (1 << (k
% 8)) : 1;
3745 if (mask
) od
[idx
] = id
[idx
] + 0xff000000; /* ff => full alpha */
3746 else od
[idx
] = bgcolor
;
3750 create_cairo_image_surface (img
, data
, width
, height
);
3754 rc
= XpmFileInvalid
;
3755 x_clear_image (f
, img
);
3758 #ifdef HAVE_X_WINDOWS
3759 if (rc
== XpmSuccess
)
3761 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_DRAWABLE (f
),
3762 img
->ximg
->width
, img
->ximg
->height
,
3764 if (img
->pixmap
== NO_PIXMAP
)
3766 x_clear_image (f
, img
);
3769 else if (img
->mask_img
)
3771 img
->mask
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_DRAWABLE (f
),
3772 img
->mask_img
->width
,
3773 img
->mask_img
->height
,
3774 img
->mask_img
->depth
);
3775 if (img
->mask
== NO_PIXMAP
)
3777 x_clear_image (f
, img
);
3783 #endif /* ! USE_CAIRO */
3785 if (rc
== XpmSuccess
)
3787 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3788 img
->colors
= colors_in_color_table (&img
->ncolors
);
3789 #else /* not ALLOC_XPM_COLORS */
3793 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3794 plus some duplicate attributes. */
3795 if (xpm_image
&& xpm_image
->bitmap
)
3797 img
->pixmap
= xpm_image
->bitmap
;
3798 /* XImageFree in libXpm frees XImage struct without destroying
3799 the bitmap, which is what we want. */
3800 XImageFree (xpm_image
);
3802 if (xpm_mask
&& xpm_mask
->bitmap
)
3804 /* The mask appears to be inverted compared with what we expect.
3805 TODO: invert our expectations. See other places where we
3806 have to invert bits because our idea of masks is backwards. */
3808 old_obj
= SelectObject (hdc
, xpm_mask
->bitmap
);
3810 PatBlt (hdc
, 0, 0, xpm_mask
->width
, xpm_mask
->height
, DSTINVERT
);
3811 SelectObject (hdc
, old_obj
);
3813 img
->mask
= xpm_mask
->bitmap
;
3814 XImageFree (xpm_mask
);
3819 #endif /* HAVE_NTGUI */
3821 /* Remember allocated colors. */
3822 img
->colors
= xnmalloc (attrs
.nalloc_pixels
, sizeof *img
->colors
);
3823 img
->ncolors
= attrs
.nalloc_pixels
;
3824 for (i
= 0; i
< attrs
.nalloc_pixels
; ++i
)
3826 img
->colors
[i
] = attrs
.alloc_pixels
[i
];
3827 #ifdef DEBUG_X_COLORS
3828 register_color (img
->colors
[i
]);
3831 #endif /* not ALLOC_XPM_COLORS */
3833 img
->width
= attrs
.width
;
3834 img
->height
= attrs
.height
;
3835 eassert (img
->width
> 0 && img
->height
> 0);
3837 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3838 XpmFreeAttributes (&attrs
);
3840 #ifdef HAVE_X_WINDOWS
3841 /* Maybe fill in the background field while we have ximg handy. */
3842 IMAGE_BACKGROUND (img
, f
, img
->ximg
);
3844 /* Fill in the background_transparent field while we have the
3846 image_background_transparent (img
, f
, img
->mask_img
);
3853 #endif /* HAVE_NTGUI */
3858 image_error ("Error opening XPM file (%s)", img
->spec
);
3861 case XpmFileInvalid
:
3862 image_error ("Invalid XPM file (%s)", img
->spec
);
3866 image_error ("Out of memory (%s)", img
->spec
);
3869 case XpmColorFailed
:
3870 image_error ("Color allocation error (%s)", img
->spec
);
3874 image_error ("Unknown error (%s)", img
->spec
);
3879 #ifdef ALLOC_XPM_COLORS
3880 xpm_free_color_cache ();
3883 return rc
== XpmSuccess
;
3886 #endif /* HAVE_XPM */
3888 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3890 /* XPM support functions for NS where libxpm is not available.
3891 Only XPM version 3 (without any extensions) is supported. */
3893 static void xpm_put_color_table_v (Lisp_Object
, const char *,
3895 static Lisp_Object
xpm_get_color_table_v (Lisp_Object
, const char *, int);
3896 static void xpm_put_color_table_h (Lisp_Object
, const char *,
3898 static Lisp_Object
xpm_get_color_table_h (Lisp_Object
, const char *, int);
3900 /* Tokens returned from xpm_scan. */
3909 /* Scan an XPM data and return a character (< 256) or a token defined
3910 by enum xpm_token above. *S and END are the start (inclusive) and
3911 the end (exclusive) addresses of the data, respectively. Advance
3912 *S while scanning. If token is either XPM_TK_IDENT or
3913 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3914 length of the corresponding token, respectively. */
3917 xpm_scan (const char **s
, const char *end
, const char **beg
, ptrdiff_t *len
)
3923 /* Skip white-space. */
3924 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
3927 /* gnus-pointer.xpm uses '-' in its identifier.
3928 sb-dir-plus.xpm uses '+' in its identifier. */
3929 if (c_isalpha (c
) || c
== '_' || c
== '-' || c
== '+')
3933 && (c
= **s
, c_isalnum (c
)
3934 || c
== '_' || c
== '-' || c
== '+'))
3937 return XPM_TK_IDENT
;
3942 while (*s
< end
&& **s
!= '"')
3947 return XPM_TK_STRING
;
3951 if (*s
< end
&& **s
== '*')
3953 /* C-style comment. */
3957 while (*s
< end
&& *(*s
)++ != '*')
3960 while (*s
< end
&& **s
!= '/');
3974 /* Functions for color table lookup in XPM data. A key is a string
3975 specifying the color of each pixel in XPM data. A value is either
3976 an integer that specifies a pixel color, Qt that specifies
3977 transparency, or Qnil for the unspecified color. If the length of
3978 the key string is one, a vector is used as a table. Otherwise, a
3979 hash table is used. */
3982 xpm_make_color_table_v (void (**put_func
) (Lisp_Object
, const char *, int,
3984 Lisp_Object (**get_func
) (Lisp_Object
, const char *,
3987 *put_func
= xpm_put_color_table_v
;
3988 *get_func
= xpm_get_color_table_v
;
3989 return Fmake_vector (make_number (256), Qnil
);
3993 xpm_put_color_table_v (Lisp_Object color_table
,
3994 const char *chars_start
,
3998 unsigned char uc
= *chars_start
;
3999 ASET (color_table
, uc
, color
);
4003 xpm_get_color_table_v (Lisp_Object color_table
,
4004 const char *chars_start
,
4007 unsigned char uc
= *chars_start
;
4008 return AREF (color_table
, uc
);
4012 xpm_make_color_table_h (void (**put_func
) (Lisp_Object
, const char *, int,
4014 Lisp_Object (**get_func
) (Lisp_Object
, const char *,
4017 *put_func
= xpm_put_color_table_h
;
4018 *get_func
= xpm_get_color_table_h
;
4019 return make_hash_table (hashtest_equal
, DEFAULT_HASH_SIZE
,
4020 DEFAULT_REHASH_SIZE
, DEFAULT_REHASH_THRESHOLD
,
4025 xpm_put_color_table_h (Lisp_Object color_table
,
4026 const char *chars_start
,
4030 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4031 EMACS_UINT hash_code
;
4032 Lisp_Object chars
= make_unibyte_string (chars_start
, chars_len
);
4034 hash_lookup (table
, chars
, &hash_code
);
4035 hash_put (table
, chars
, color
, hash_code
);
4039 xpm_get_color_table_h (Lisp_Object color_table
,
4040 const char *chars_start
,
4043 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4045 hash_lookup (table
, make_unibyte_string (chars_start
, chars_len
), NULL
);
4047 return i
>= 0 ? HASH_VALUE (table
, i
) : Qnil
;
4050 enum xpm_color_key
{
4058 static const char xpm_color_key_strings
[][4] = {"s", "m", "g4", "g", "c"};
4061 xpm_str_to_color_key (const char *s
)
4065 for (i
= 0; i
< ARRAYELTS (xpm_color_key_strings
); i
++)
4066 if (strcmp (xpm_color_key_strings
[i
], s
) == 0)
4072 xpm_load_image (struct frame
*f
,
4074 const char *contents
,
4077 const char *s
= contents
, *beg
, *str
;
4078 char buffer
[BUFSIZ
];
4079 int width
, height
, x
, y
;
4080 int num_colors
, chars_per_pixel
;
4083 void (*put_color_table
) (Lisp_Object
, const char *, int, Lisp_Object
);
4084 Lisp_Object (*get_color_table
) (Lisp_Object
, const char *, int);
4085 Lisp_Object frame
, color_symbols
, color_table
;
4088 bool have_mask
= false;
4090 XImagePtr ximg
= NULL
, mask_img
= NULL
;
4093 LA1 = xpm_scan (&s, end, &beg, &len)
4095 #define expect(TOKEN) \
4098 if (LA1 != (TOKEN)) \
4104 #define expect_ident(IDENT) \
4105 if (LA1 == XPM_TK_IDENT \
4106 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4111 if (!(end
- s
>= 9 && memcmp (s
, "/* XPM */", 9) == 0))
4115 expect_ident ("static");
4116 expect_ident ("char");
4118 expect (XPM_TK_IDENT
);
4123 expect (XPM_TK_STRING
);
4126 memcpy (buffer
, beg
, len
);
4128 if (sscanf (buffer
, "%d %d %d %d", &width
, &height
,
4129 &num_colors
, &chars_per_pixel
) != 4
4130 || width
<= 0 || height
<= 0
4131 || num_colors
<= 0 || chars_per_pixel
<= 0)
4134 if (!check_image_size (f
, width
, height
))
4136 image_size_error ();
4140 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0)
4142 || !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
4147 image_error ("Image too large");
4153 XSETFRAME (frame
, f
);
4154 if (!NILP (Fxw_display_color_p (frame
)))
4155 best_key
= XPM_COLOR_KEY_C
;
4156 else if (!NILP (Fx_display_grayscale_p (frame
)))
4157 best_key
= (XFASTINT (Fx_display_planes (frame
)) > 2
4158 ? XPM_COLOR_KEY_G
: XPM_COLOR_KEY_G4
);
4160 best_key
= XPM_COLOR_KEY_M
;
4162 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
4163 if (chars_per_pixel
== 1)
4164 color_table
= xpm_make_color_table_v (&put_color_table
,
4167 color_table
= xpm_make_color_table_h (&put_color_table
,
4170 while (num_colors
-- > 0)
4172 char *color
, *max_color
;
4173 int key
, next_key
, max_key
= 0;
4174 Lisp_Object symbol_color
= Qnil
, color_val
;
4177 expect (XPM_TK_STRING
);
4178 if (len
<= chars_per_pixel
|| len
>= BUFSIZ
+ chars_per_pixel
)
4180 memcpy (buffer
, beg
+ chars_per_pixel
, len
- chars_per_pixel
);
4181 buffer
[len
- chars_per_pixel
] = '\0';
4183 str
= strtok (buffer
, " \t");
4186 key
= xpm_str_to_color_key (str
);
4191 color
= strtok (NULL
, " \t");
4195 while ((str
= strtok (NULL
, " \t")) != NULL
)
4197 next_key
= xpm_str_to_color_key (str
);
4200 color
[strlen (color
)] = ' ';
4203 if (key
== XPM_COLOR_KEY_S
)
4205 if (NILP (symbol_color
))
4206 symbol_color
= build_string (color
);
4208 else if (max_key
< key
&& key
<= best_key
)
4218 if (!NILP (color_symbols
) && !NILP (symbol_color
))
4220 Lisp_Object specified_color
= Fassoc (symbol_color
, color_symbols
);
4222 if (CONSP (specified_color
) && STRINGP (XCDR (specified_color
)))
4224 if (xstrcasecmp (SSDATA (XCDR (specified_color
)), "None") == 0)
4226 else if (x_defined_color (f
, SSDATA (XCDR (specified_color
)),
4228 color_val
= make_number (cdef
.pixel
);
4231 if (NILP (color_val
) && max_key
> 0)
4233 if (xstrcasecmp (max_color
, "None") == 0)
4235 else if (x_defined_color (f
, max_color
, &cdef
, 0))
4236 color_val
= make_number (cdef
.pixel
);
4238 if (!NILP (color_val
))
4239 (*put_color_table
) (color_table
, beg
, chars_per_pixel
, color_val
);
4244 for (y
= 0; y
< height
; y
++)
4246 expect (XPM_TK_STRING
);
4248 if (len
< width
* chars_per_pixel
)
4250 for (x
= 0; x
< width
; x
++, str
+= chars_per_pixel
)
4252 Lisp_Object color_val
=
4253 (*get_color_table
) (color_table
, str
, chars_per_pixel
);
4255 XPutPixel (ximg
, x
, y
,
4256 (INTEGERP (color_val
) ? XINT (color_val
)
4257 : FRAME_FOREGROUND_PIXEL (f
)));
4259 XPutPixel (mask_img
, x
, y
,
4260 (!EQ (color_val
, Qt
) ? PIX_MASK_DRAW
4261 : (have_mask
= true, PIX_MASK_RETAIN
)));
4263 if (EQ (color_val
, Qt
))
4264 ns_set_alpha (ximg
, x
, y
, 0);
4272 img
->height
= height
;
4274 /* Maybe fill in the background field while we have ximg handy. */
4275 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
4276 IMAGE_BACKGROUND (img
, f
, ximg
);
4278 image_put_x_image (f
, img
, ximg
, 0);
4282 /* Fill in the background_transparent field while we have the
4284 image_background_transparent (img
, f
, mask_img
);
4286 image_put_x_image (f
, img
, mask_img
, 1);
4290 x_destroy_x_image (mask_img
);
4291 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4297 image_error ("Invalid XPM file (%s)", img
->spec
);
4298 x_destroy_x_image (ximg
);
4299 x_destroy_x_image (mask_img
);
4300 x_clear_image (f
, img
);
4309 xpm_load (struct frame
*f
,
4313 Lisp_Object file_name
;
4315 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4316 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
4317 if (STRINGP (file_name
))
4320 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
4321 if (!STRINGP (file
))
4323 image_error ("Cannot find image file `%s'", file_name
);
4328 char *contents
= slurp_file (fd
, &size
);
4329 if (contents
== NULL
)
4331 image_error ("Error loading XPM image `%s'", file
);
4335 success_p
= xpm_load_image (f
, img
, contents
, contents
+ size
);
4342 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
4343 if (!STRINGP (data
))
4345 image_error ("Invalid image data `%s'", data
);
4348 success_p
= xpm_load_image (f
, img
, SSDATA (data
),
4349 SSDATA (data
) + SBYTES (data
));
4355 #endif /* HAVE_NS && !HAVE_XPM */
4359 /***********************************************************************
4361 ***********************************************************************/
4363 #ifdef COLOR_TABLE_SUPPORT
4365 /* An entry in the color table mapping an RGB color to a pixel color. */
4370 unsigned long pixel
;
4372 /* Next in color table collision list. */
4373 struct ct_color
*next
;
4376 /* The bucket vector size to use. Must be prime. */
4380 /* Value is a hash of the RGB color given by R, G, and B. */
4383 ct_hash_rgb (unsigned r
, unsigned g
, unsigned b
)
4385 return (r
<< 16) ^ (g
<< 8) ^ b
;
4388 /* The color hash table. */
4390 static struct ct_color
**ct_table
;
4392 /* Number of entries in the color table. */
4394 static int ct_colors_allocated
;
4397 ct_colors_allocated_max
=
4399 min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof (unsigned long))
4402 /* Initialize the color table. */
4405 init_color_table (void)
4407 int size
= CT_SIZE
* sizeof (*ct_table
);
4408 ct_table
= xzalloc (size
);
4409 ct_colors_allocated
= 0;
4413 /* Free memory associated with the color table. */
4416 free_color_table (void)
4419 struct ct_color
*p
, *next
;
4421 for (i
= 0; i
< CT_SIZE
; ++i
)
4422 for (p
= ct_table
[i
]; p
; p
= next
)
4433 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4434 entry for that color already is in the color table, return the
4435 pixel color of that entry. Otherwise, allocate a new color for R,
4436 G, B, and make an entry in the color table. */
4438 static unsigned long
4439 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4441 unsigned hash
= ct_hash_rgb (r
, g
, b
);
4442 int i
= hash
% CT_SIZE
;
4444 Display_Info
*dpyinfo
;
4446 /* Handle TrueColor visuals specially, which improves performance by
4447 two orders of magnitude. Freeing colors on TrueColor visuals is
4448 a nop, and pixel colors specify RGB values directly. See also
4449 the Xlib spec, chapter 3.1. */
4450 dpyinfo
= FRAME_DISPLAY_INFO (f
);
4451 if (dpyinfo
->red_bits
> 0)
4453 /* Apply gamma-correction like normal color allocation does. */
4457 color
.red
= r
, color
.green
= g
, color
.blue
= b
;
4458 gamma_correct (f
, &color
);
4459 r
= color
.red
, g
= color
.green
, b
= color
.blue
;
4462 return x_make_truecolor_pixel (dpyinfo
, r
, g
, b
);
4465 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4466 if (p
->r
== r
&& p
->g
== g
&& p
->b
== b
)
4472 #ifdef HAVE_X_WINDOWS
4480 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4481 return FRAME_FOREGROUND_PIXEL (f
);
4483 #ifdef HAVE_X_WINDOWS
4488 cmap
= FRAME_X_COLORMAP (f
);
4489 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4492 ++ct_colors_allocated
;
4493 p
= xmalloc (sizeof *p
);
4497 p
->pixel
= color
.pixel
;
4498 p
->next
= ct_table
[i
];
4502 return FRAME_FOREGROUND_PIXEL (f
);
4506 color
= PALETTERGB (r
, g
, b
);
4508 color
= RGB_TO_ULONG (r
, g
, b
);
4509 #endif /* HAVE_NTGUI */
4510 ++ct_colors_allocated
;
4511 p
= xmalloc (sizeof *p
);
4516 p
->next
= ct_table
[i
];
4518 #endif /* HAVE_X_WINDOWS */
4526 /* Look up pixel color PIXEL which is used on frame F in the color
4527 table. If not already present, allocate it. Value is PIXEL. */
4529 static unsigned long
4530 lookup_pixel_color (struct frame
*f
, unsigned long pixel
)
4532 int i
= pixel
% CT_SIZE
;
4535 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4536 if (p
->pixel
== pixel
)
4545 if (ct_colors_allocated
>= ct_colors_allocated_max
)
4546 return FRAME_FOREGROUND_PIXEL (f
);
4548 #ifdef HAVE_X_WINDOWS
4549 cmap
= FRAME_X_COLORMAP (f
);
4550 color
.pixel
= pixel
;
4551 x_query_color (f
, &color
);
4552 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4555 cmap
= DefaultColormapOfScreen (FRAME_X_SCREEN (f
));
4556 color
.pixel
= pixel
;
4557 XQueryColor (NULL
, cmap
, &color
);
4558 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4560 #endif /* HAVE_X_WINDOWS */
4564 ++ct_colors_allocated
;
4566 p
= xmalloc (sizeof *p
);
4571 p
->next
= ct_table
[i
];
4575 return FRAME_FOREGROUND_PIXEL (f
);
4581 /* Value is a vector of all pixel colors contained in the color table,
4582 allocated via xmalloc. Set *N to the number of colors. */
4584 static unsigned long *
4585 colors_in_color_table (int *n
)
4589 unsigned long *colors
;
4591 if (ct_colors_allocated
== 0)
4598 colors
= xmalloc (ct_colors_allocated
* sizeof *colors
);
4599 *n
= ct_colors_allocated
;
4601 for (i
= j
= 0; i
< CT_SIZE
; ++i
)
4602 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4603 colors
[j
++] = p
->pixel
;
4609 #else /* COLOR_TABLE_SUPPORT */
4611 static unsigned long
4612 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4615 return PALETTERGB (r
>> 8, g
>> 8, b
>> 8);
4616 #elif defined HAVE_NS
4617 return RGB_TO_ULONG (r
>> 8, g
>> 8, b
>> 8);
4619 xsignal1 (Qfile_error
,
4620 build_string ("This Emacs mishandles this image file type"));
4625 init_color_table (void)
4628 #endif /* COLOR_TABLE_SUPPORT */
4631 /***********************************************************************
4633 ***********************************************************************/
4635 /* Edge detection matrices for different edge-detection
4638 static int emboss_matrix
[9] = {
4640 2, -1, 0, /* y - 1 */
4642 0, 1, -2 /* y + 1 */
4645 static int laplace_matrix
[9] = {
4647 1, 0, 0, /* y - 1 */
4649 0, 0, -1 /* y + 1 */
4652 /* Value is the intensity of the color whose red/green/blue values
4655 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4658 /* On frame F, return an array of XColor structures describing image
4659 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4660 means also fill the red/green/blue members of the XColor
4661 structures. Value is a pointer to the array of XColors structures,
4662 allocated with xmalloc; it must be freed by the caller. */
4665 x_to_xcolors (struct frame
*f
, struct image
*img
, bool rgb_p
)
4669 XImagePtr_or_DC ximg
;
4673 #endif /* HAVE_NTGUI */
4675 if (INT_MULTIPLY_WRAPV (sizeof *colors
, img
->width
, &nbytes
)
4676 || INT_MULTIPLY_WRAPV (img
->height
, nbytes
, &nbytes
)
4677 || SIZE_MAX
< nbytes
)
4678 memory_full (SIZE_MAX
);
4679 colors
= xmalloc (nbytes
);
4681 /* Get the X image or create a memory device context for IMG. */
4682 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4684 /* Fill the `pixel' members of the XColor array. I wished there
4685 were an easy and portable way to circumvent XGetPixel. */
4687 for (y
= 0; y
< img
->height
; ++y
)
4689 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4691 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4692 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4694 x_query_colors (f
, row
, img
->width
);
4698 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4700 /* W32_TODO: palette support needed here? */
4701 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4704 p
->red
= RED16_FROM_ULONG (p
->pixel
);
4705 p
->green
= GREEN16_FROM_ULONG (p
->pixel
);
4706 p
->blue
= BLUE16_FROM_ULONG (p
->pixel
);
4709 #endif /* HAVE_X_WINDOWS */
4712 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
4719 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4720 created with CreateDIBSection, with the pointer to the bit values
4721 stored in ximg->data. */
4724 XPutPixel (XImagePtr ximg
, int x
, int y
, COLORREF color
)
4726 int width
= ximg
->info
.bmiHeader
.biWidth
;
4727 unsigned char * pixel
;
4729 /* True color images. */
4730 if (ximg
->info
.bmiHeader
.biBitCount
== 24)
4732 int rowbytes
= width
* 3;
4733 /* Ensure scanlines are aligned on 4 byte boundaries. */
4735 rowbytes
+= 4 - (rowbytes
% 4);
4737 pixel
= ximg
->data
+ y
* rowbytes
+ x
* 3;
4738 /* Windows bitmaps are in BGR order. */
4739 *pixel
= GetBValue (color
);
4740 *(pixel
+ 1) = GetGValue (color
);
4741 *(pixel
+ 2) = GetRValue (color
);
4743 /* Monochrome images. */
4744 else if (ximg
->info
.bmiHeader
.biBitCount
== 1)
4746 int rowbytes
= width
/ 8;
4747 /* Ensure scanlines are aligned on 4 byte boundaries. */
4749 rowbytes
+= 4 - (rowbytes
% 4);
4750 pixel
= ximg
->data
+ y
* rowbytes
+ x
/ 8;
4751 /* Filter out palette info. */
4752 if (color
& 0x00ffffff)
4753 *pixel
= *pixel
| (1 << x
% 8);
4755 *pixel
= *pixel
& ~(1 << x
% 8);
4758 image_error ("XPutPixel: palette image not supported");
4761 #endif /* HAVE_NTGUI */
4763 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4764 RGB members are set. F is the frame on which this all happens.
4765 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4768 x_from_xcolors (struct frame
*f
, struct image
*img
, XColor
*colors
)
4771 XImagePtr oimg
= NULL
;
4774 init_color_table ();
4776 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_COLORS
);
4777 image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 0,
4780 for (y
= 0; y
< img
->height
; ++y
)
4781 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4783 unsigned long pixel
;
4784 pixel
= lookup_rgb_color (f
, p
->red
, p
->green
, p
->blue
);
4785 XPutPixel (oimg
, x
, y
, pixel
);
4790 image_put_x_image (f
, img
, oimg
, 0);
4791 #ifdef COLOR_TABLE_SUPPORT
4792 img
->colors
= colors_in_color_table (&img
->ncolors
);
4793 free_color_table ();
4794 #endif /* COLOR_TABLE_SUPPORT */
4798 /* On frame F, perform edge-detection on image IMG.
4800 MATRIX is a nine-element array specifying the transformation
4801 matrix. See emboss_matrix for an example.
4803 COLOR_ADJUST is a color adjustment added to each pixel of the
4807 x_detect_edges (struct frame
*f
, struct image
*img
, int *matrix
, int color_adjust
)
4809 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4814 for (i
= sum
= 0; i
< 9; ++i
)
4815 sum
+= eabs (matrix
[i
]);
4817 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4819 if (INT_MULTIPLY_WRAPV (sizeof *new, img
->width
, &nbytes
)
4820 || INT_MULTIPLY_WRAPV (img
->height
, nbytes
, &nbytes
))
4821 memory_full (SIZE_MAX
);
4822 new = xmalloc (nbytes
);
4824 for (y
= 0; y
< img
->height
; ++y
)
4826 p
= COLOR (new, 0, y
);
4827 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4828 p
= COLOR (new, img
->width
- 1, y
);
4829 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4832 for (x
= 1; x
< img
->width
- 1; ++x
)
4834 p
= COLOR (new, x
, 0);
4835 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4836 p
= COLOR (new, x
, img
->height
- 1);
4837 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4840 for (y
= 1; y
< img
->height
- 1; ++y
)
4842 p
= COLOR (new, 1, y
);
4844 for (x
= 1; x
< img
->width
- 1; ++x
, ++p
)
4846 int r
, g
, b
, yy
, xx
;
4849 for (yy
= y
- 1; yy
< y
+ 2; ++yy
)
4850 for (xx
= x
- 1; xx
< x
+ 2; ++xx
, ++i
)
4853 XColor
*t
= COLOR (colors
, xx
, yy
);
4854 r
+= matrix
[i
] * t
->red
;
4855 g
+= matrix
[i
] * t
->green
;
4856 b
+= matrix
[i
] * t
->blue
;
4859 r
= (r
/ sum
+ color_adjust
) & 0xffff;
4860 g
= (g
/ sum
+ color_adjust
) & 0xffff;
4861 b
= (b
/ sum
+ color_adjust
) & 0xffff;
4862 p
->red
= p
->green
= p
->blue
= COLOR_INTENSITY (r
, g
, b
);
4867 x_from_xcolors (f
, img
, new);
4873 /* Perform the pre-defined `emboss' edge-detection on image IMG
4877 x_emboss (struct frame
*f
, struct image
*img
)
4879 x_detect_edges (f
, img
, emboss_matrix
, 0xffff / 2);
4883 /* Transform image IMG which is used on frame F with a Laplace
4884 edge-detection algorithm. The result is an image that can be used
4885 to draw disabled buttons, for example. */
4888 x_laplace (struct frame
*f
, struct image
*img
)
4890 x_detect_edges (f
, img
, laplace_matrix
, 45000);
4894 /* Perform edge-detection on image IMG on frame F, with specified
4895 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4897 MATRIX must be either
4899 - a list of at least 9 numbers in row-major form
4900 - a vector of at least 9 numbers
4902 COLOR_ADJUST nil means use a default; otherwise it must be a
4906 x_edge_detection (struct frame
*f
, struct image
*img
, Lisp_Object matrix
,
4907 Lisp_Object color_adjust
)
4915 i
< 9 && CONSP (matrix
) && NUMBERP (XCAR (matrix
));
4916 ++i
, matrix
= XCDR (matrix
))
4917 trans
[i
] = XFLOATINT (XCAR (matrix
));
4919 else if (VECTORP (matrix
) && ASIZE (matrix
) >= 9)
4921 for (i
= 0; i
< 9 && NUMBERP (AREF (matrix
, i
)); ++i
)
4922 trans
[i
] = XFLOATINT (AREF (matrix
, i
));
4925 if (NILP (color_adjust
))
4926 color_adjust
= make_number (0xffff / 2);
4928 if (i
== 9 && NUMBERP (color_adjust
))
4929 x_detect_edges (f
, img
, trans
, XFLOATINT (color_adjust
));
4933 /* Transform image IMG on frame F so that it looks disabled. */
4936 x_disable_image (struct frame
*f
, struct image
*img
)
4938 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
4940 int n_planes
= dpyinfo
->n_planes
* dpyinfo
->n_cbits
;
4942 int n_planes
= dpyinfo
->n_planes
;
4943 #endif /* HAVE_NTGUI */
4947 /* Color (or grayscale). Convert to gray, and equalize. Just
4948 drawing such images with a stipple can look very odd, so
4949 we're using this method instead. */
4950 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4952 const int h
= 15000;
4953 const int l
= 30000;
4955 for (p
= colors
, end
= colors
+ img
->width
* img
->height
;
4959 int i
= COLOR_INTENSITY (p
->red
, p
->green
, p
->blue
);
4960 int i2
= (0xffff - h
- l
) * i
/ 0xffff + l
;
4961 p
->red
= p
->green
= p
->blue
= i2
;
4964 x_from_xcolors (f
, img
, colors
);
4967 /* Draw a cross over the disabled image, if we must or if we
4969 if (n_planes
< 2 || cross_disabled_images
)
4972 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4974 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4976 Display
*dpy
= FRAME_X_DISPLAY (f
);
4979 image_sync_to_pixmaps (f
, img
);
4980 gc
= XCreateGC (dpy
, img
->pixmap
, 0, NULL
);
4981 XSetForeground (dpy
, gc
, BLACK_PIX_DEFAULT (f
));
4982 XDrawLine (dpy
, img
->pixmap
, gc
, 0, 0,
4983 img
->width
- 1, img
->height
- 1);
4984 XDrawLine (dpy
, img
->pixmap
, gc
, 0, img
->height
- 1,
4990 gc
= XCreateGC (dpy
, img
->mask
, 0, NULL
);
4991 XSetForeground (dpy
, gc
, MaskForeground (f
));
4992 XDrawLine (dpy
, img
->mask
, gc
, 0, 0,
4993 img
->width
- 1, img
->height
- 1);
4994 XDrawLine (dpy
, img
->mask
, gc
, 0, img
->height
- 1,
4998 #endif /* !HAVE_NS */
5003 hdc
= get_frame_dc (f
);
5004 bmpdc
= CreateCompatibleDC (hdc
);
5005 release_frame_dc (f
, hdc
);
5007 prev
= SelectObject (bmpdc
, img
->pixmap
);
5009 SetTextColor (bmpdc
, BLACK_PIX_DEFAULT (f
));
5010 MoveToEx (bmpdc
, 0, 0, NULL
);
5011 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
5012 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
5013 LineTo (bmpdc
, img
->width
- 1, 0);
5017 SelectObject (bmpdc
, img
->mask
);
5018 SetTextColor (bmpdc
, WHITE_PIX_DEFAULT (f
));
5019 MoveToEx (bmpdc
, 0, 0, NULL
);
5020 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
5021 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
5022 LineTo (bmpdc
, img
->width
- 1, 0);
5024 SelectObject (bmpdc
, prev
);
5026 #endif /* HAVE_NTGUI */
5031 /* Build a mask for image IMG which is used on frame F. FILE is the
5032 name of an image file, for error messages. HOW determines how to
5033 determine the background color of IMG. If it is a list '(R G B)',
5034 with R, G, and B being integers >= 0, take that as the color of the
5035 background. Otherwise, determine the background color of IMG
5039 x_build_heuristic_mask (struct frame
*f
, struct image
*img
, Lisp_Object how
)
5041 XImagePtr_or_DC ximg
;
5046 #elif !defined HAVE_NS
5050 bool use_img_background
;
5051 unsigned long bg
= 0;
5054 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
5058 /* Create an image and pixmap serving as mask. */
5059 if (! image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 1,
5062 #endif /* !HAVE_NS */
5064 /* Create the bit array serving as mask. */
5065 row_width
= (img
->width
+ 7) / 8;
5066 mask_img
= xzalloc (row_width
* img
->height
);
5067 #endif /* HAVE_NTGUI */
5069 /* Get the X image or create a memory device context for IMG. */
5070 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
5072 /* Determine the background color of ximg. If HOW is `(R G B)'
5073 take that as color. Otherwise, use the image's background color. */
5074 use_img_background
= 1;
5080 for (i
= 0; i
< 3 && CONSP (how
) && NATNUMP (XCAR (how
)); ++i
)
5082 rgb
[i
] = XFASTINT (XCAR (how
)) & 0xffff;
5086 if (i
== 3 && NILP (how
))
5088 char color_name
[30];
5089 sprintf (color_name
, "#%04x%04x%04x",
5090 rgb
[0] + 0u, rgb
[1] + 0u, rgb
[2] + 0u);
5093 0x00ffffff & /* Filter out palette info. */
5094 #endif /* HAVE_NTGUI */
5095 x_alloc_image_color (f
, img
, build_string (color_name
), 0));
5096 use_img_background
= 0;
5100 if (use_img_background
)
5101 bg
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
5103 /* Set all bits in mask_img to 1 whose color in ximg is different
5104 from the background color bg. */
5106 for (y
= 0; y
< img
->height
; ++y
)
5107 for (x
= 0; x
< img
->width
; ++x
)
5109 XPutPixel (mask_img
, x
, y
, (XGetPixel (ximg
, x
, y
) != bg
5110 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
));
5112 if (XGetPixel (ximg
, x
, y
) == bg
)
5113 ns_set_alpha (ximg
, x
, y
, 0);
5114 #endif /* HAVE_NS */
5116 /* Fill in the background_transparent field while we have the mask handy. */
5117 image_background_transparent (img
, f
, mask_img
);
5119 /* Put mask_img into the image. */
5120 image_put_x_image (f
, img
, mask_img
, 1);
5121 #endif /* !HAVE_NS */
5123 for (y
= 0; y
< img
->height
; ++y
)
5124 for (x
= 0; x
< img
->width
; ++x
)
5126 COLORREF p
= GetPixel (ximg
, x
, y
);
5128 mask_img
[y
* row_width
+ x
/ 8] |= 1 << (x
% 8);
5131 /* Create the mask image. */
5132 img
->mask
= w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
,
5134 /* Fill in the background_transparent field while we have the mask handy. */
5135 SelectObject (ximg
, img
->mask
);
5136 image_background_transparent (img
, f
, ximg
);
5138 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5140 #endif /* HAVE_NTGUI */
5142 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
5146 /***********************************************************************
5147 PBM (mono, gray, color)
5148 ***********************************************************************/
5150 static bool pbm_image_p (Lisp_Object object
);
5151 static bool pbm_load (struct frame
*f
, struct image
*img
);
5153 /* Indices of image specification fields in gs_format, below. */
5155 enum pbm_keyword_index
5171 /* Vector of image_keyword structures describing the format
5172 of valid user-defined image specifications. */
5174 static const struct image_keyword pbm_format
[PBM_LAST
] =
5176 {":type", IMAGE_SYMBOL_VALUE
, 1},
5177 {":file", IMAGE_STRING_VALUE
, 0},
5178 {":data", IMAGE_STRING_VALUE
, 0},
5179 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5180 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5181 {":relief", IMAGE_INTEGER_VALUE
, 0},
5182 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5183 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5184 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5185 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
5186 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5189 /* Structure describing the image type `pbm'. */
5191 static struct image_type pbm_type
=
5193 SYMBOL_INDEX (Qpbm
),
5202 /* Return true if OBJECT is a valid PBM image specification. */
5205 pbm_image_p (Lisp_Object object
)
5207 struct image_keyword fmt
[PBM_LAST
];
5209 memcpy (fmt
, pbm_format
, sizeof fmt
);
5211 if (!parse_image_spec (object
, fmt
, PBM_LAST
, Qpbm
))
5214 /* Must specify either :data or :file. */
5215 return fmt
[PBM_DATA
].count
+ fmt
[PBM_FILE
].count
== 1;
5219 /* Get next char skipping comments in Netpbm header. Returns -1 at
5223 pbm_next_char (char **s
, char *end
)
5227 unsigned char c
= *(*s
)++;
5233 if (c
== '\n' || c
== '\r')
5242 /* Scan a decimal number from *S and return it. Advance *S while
5243 reading the number. END is the end of the string. Value is -1 at
5247 pbm_scan_number (char **s
, char *end
)
5249 int c
= 0, val
= -1;
5251 /* Skip white-space. */
5252 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isspace (c
))
5257 /* Read decimal number. */
5259 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isdigit (c
))
5260 val
= 10 * val
+ c
- '0';
5267 /* Load PBM image IMG for use on frame F. */
5270 pbm_load (struct frame
*f
, struct image
*img
)
5274 int width
, height
, max_color_idx
= 0;
5275 Lisp_Object specified_file
;
5276 enum {PBM_MONO
, PBM_GRAY
, PBM_COLOR
} type
;
5277 char *contents
= NULL
;
5283 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5285 if (STRINGP (specified_file
))
5288 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5289 if (!STRINGP (file
))
5291 image_error ("Cannot find image file `%s'", specified_file
);
5296 contents
= slurp_file (fd
, &size
);
5297 if (contents
== NULL
)
5299 image_error ("Error reading `%s'", file
);
5304 end
= contents
+ size
;
5309 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5310 if (!STRINGP (data
))
5312 image_error ("Invalid image data `%s'", data
);
5316 end
= p
+ SBYTES (data
);
5319 /* Check magic number. */
5320 if (end
- p
< 2 || *p
++ != 'P')
5322 image_error ("Not a PBM image: `%s'", img
->spec
);
5325 img
->pixmap
= NO_PIXMAP
;
5332 raw_p
= 0, type
= PBM_MONO
;
5336 raw_p
= 0, type
= PBM_GRAY
;
5340 raw_p
= 0, type
= PBM_COLOR
;
5344 raw_p
= 1, type
= PBM_MONO
;
5348 raw_p
= 1, type
= PBM_GRAY
;
5352 raw_p
= 1, type
= PBM_COLOR
;
5356 image_error ("Not a PBM image: `%s'", img
->spec
);
5360 /* Read width, height, maximum color-component. Characters
5361 starting with `#' up to the end of a line are ignored. */
5362 width
= pbm_scan_number (&p
, end
);
5363 height
= pbm_scan_number (&p
, end
);
5366 void *data
= xmalloc (width
* height
* 4);
5367 uint32_t *dataptr
= data
;
5370 if (type
!= PBM_MONO
)
5372 max_color_idx
= pbm_scan_number (&p
, end
);
5373 if (max_color_idx
> 65535 || max_color_idx
< 0)
5375 image_error ("Unsupported maximum PBM color value");
5380 if (!check_image_size (f
, width
, height
))
5382 image_size_error ();
5387 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5391 /* Initialize the color hash table. */
5392 init_color_table ();
5394 if (type
== PBM_MONO
)
5396 unsigned char c
= 0;
5398 struct image_keyword fmt
[PBM_LAST
];
5399 unsigned long fg
= FRAME_FOREGROUND_PIXEL (f
);
5400 unsigned long bg
= FRAME_BACKGROUND_PIXEL (f
);
5405 /* Parse the image specification. */
5406 memcpy (fmt
, pbm_format
, sizeof fmt
);
5407 parse_image_spec (img
->spec
, fmt
, PBM_LAST
, Qpbm
);
5409 /* Get foreground and background colors, maybe allocate colors. */
5411 if (! fmt
[PBM_FOREGROUND
].count
5412 || ! STRINGP (fmt
[PBM_FOREGROUND
].value
)
5413 || ! x_defined_color (f
, SSDATA (fmt
[PBM_FOREGROUND
].value
), &xfg
, 0))
5416 x_query_color (f
, &xfg
);
5418 fga32
= xcolor_to_argb32 (xfg
);
5420 if (! fmt
[PBM_BACKGROUND
].count
5421 || ! STRINGP (fmt
[PBM_BACKGROUND
].value
)
5422 || ! x_defined_color (f
, SSDATA (fmt
[PBM_BACKGROUND
].value
), &xbg
, 0))
5425 x_query_color (f
, &xbg
);
5427 bga32
= xcolor_to_argb32 (xbg
);
5429 if (fmt
[PBM_FOREGROUND
].count
5430 && STRINGP (fmt
[PBM_FOREGROUND
].value
))
5431 fg
= x_alloc_image_color (f
, img
, fmt
[PBM_FOREGROUND
].value
, fg
);
5432 if (fmt
[PBM_BACKGROUND
].count
5433 && STRINGP (fmt
[PBM_BACKGROUND
].value
))
5435 bg
= x_alloc_image_color (f
, img
, fmt
[PBM_BACKGROUND
].value
, bg
);
5436 img
->background
= bg
;
5437 img
->background_valid
= 1;
5441 for (y
= 0; y
< height
; ++y
)
5442 for (x
= 0; x
< width
; ++x
)
5453 x_destroy_x_image (ximg
);
5455 x_clear_image (f
, img
);
5456 image_error ("Invalid image size in image `%s'",
5468 /* Skip white-space and comments. */
5469 while ((c
= pbm_next_char (&p
, end
)) != -1 && c_isspace (c
))
5472 if (c
== '0' || c
== '1')
5479 *dataptr
++ = g
? fga32
: bga32
;
5481 XPutPixel (ximg
, x
, y
, g
? fg
: bg
);
5487 int expected_size
= height
* width
;
5488 if (max_color_idx
> 255)
5490 if (type
== PBM_COLOR
)
5493 if (raw_p
&& p
+ expected_size
> end
)
5498 x_destroy_x_image (ximg
);
5500 x_clear_image (f
, img
);
5501 image_error ("Invalid image size in image `%s'", img
->spec
);
5505 for (y
= 0; y
< height
; ++y
)
5506 for (x
= 0; x
< width
; ++x
)
5510 if (type
== PBM_GRAY
&& raw_p
)
5513 if (max_color_idx
> 255)
5514 r
= g
= b
= r
* 256 + *p
++;
5516 else if (type
== PBM_GRAY
)
5517 r
= g
= b
= pbm_scan_number (&p
, end
);
5521 if (max_color_idx
> 255)
5524 if (max_color_idx
> 255)
5527 if (max_color_idx
> 255)
5532 r
= pbm_scan_number (&p
, end
);
5533 g
= pbm_scan_number (&p
, end
);
5534 b
= pbm_scan_number (&p
, end
);
5537 if (r
< 0 || g
< 0 || b
< 0)
5542 x_destroy_x_image (ximg
);
5544 image_error ("Invalid pixel value in image `%s'", img
->spec
);
5549 r
= (double) r
* 255 / max_color_idx
;
5550 g
= (double) g
* 255 / max_color_idx
;
5551 b
= (double) b
* 255 / max_color_idx
;
5552 *dataptr
++ = (0xffu
<< 24) | (r
<< 16) | (g
<< 8) | b
;
5554 /* RGB values are now in the range 0..max_color_idx.
5555 Scale this to the range 0..0xffff supported by X. */
5556 r
= (double) r
* 65535 / max_color_idx
;
5557 g
= (double) g
* 65535 / max_color_idx
;
5558 b
= (double) b
* 65535 / max_color_idx
;
5559 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5564 #ifdef COLOR_TABLE_SUPPORT
5565 /* Store in IMG->colors the colors allocated for the image, and
5566 free the color table. */
5567 img
->colors
= colors_in_color_table (&img
->ncolors
);
5568 free_color_table ();
5569 #endif /* COLOR_TABLE_SUPPORT */
5572 img
->height
= height
;
5574 /* Maybe fill in the background field while we have ximg handy. */
5577 create_cairo_image_surface (img
, data
, width
, height
);
5579 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
5580 /* Casting avoids a GCC warning. */
5581 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
5583 /* Put ximg into the image. */
5584 image_put_x_image (f
, img
, ximg
, 0);
5587 /* X and W32 versions did it here, MAC version above. ++kfs
5589 img->height = height; */
5596 /***********************************************************************
5598 ***********************************************************************/
5600 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5602 /* Function prototypes. */
5604 static bool png_image_p (Lisp_Object object
);
5605 static bool png_load (struct frame
*f
, struct image
*img
);
5607 /* Indices of image specification fields in png_format, below. */
5609 enum png_keyword_index
5624 /* Vector of image_keyword structures describing the format
5625 of valid user-defined image specifications. */
5627 static const struct image_keyword png_format
[PNG_LAST
] =
5629 {":type", IMAGE_SYMBOL_VALUE
, 1},
5630 {":data", IMAGE_STRING_VALUE
, 0},
5631 {":file", IMAGE_STRING_VALUE
, 0},
5632 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5633 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5634 {":relief", IMAGE_INTEGER_VALUE
, 0},
5635 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5636 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5637 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5638 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5641 #if defined HAVE_NTGUI && defined WINDOWSNT
5642 static bool init_png_functions (void);
5644 #define init_png_functions NULL
5647 /* Structure describing the image type `png'. */
5649 static struct image_type png_type
=
5651 SYMBOL_INDEX (Qpng
),
5659 /* Return true if OBJECT is a valid PNG image specification. */
5662 png_image_p (Lisp_Object object
)
5664 struct image_keyword fmt
[PNG_LAST
];
5665 memcpy (fmt
, png_format
, sizeof fmt
);
5667 if (!parse_image_spec (object
, fmt
, PNG_LAST
, Qpng
))
5670 /* Must specify either the :data or :file keyword. */
5671 return fmt
[PNG_FILE
].count
+ fmt
[PNG_DATA
].count
== 1;
5674 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5677 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5680 /* PNG library details. */
5682 DEF_DLL_FN (png_voidp
, png_get_io_ptr
, (png_structp
));
5683 DEF_DLL_FN (int, png_sig_cmp
, (png_bytep
, png_size_t
, png_size_t
));
5684 DEF_DLL_FN (png_structp
, png_create_read_struct
,
5685 (png_const_charp
, png_voidp
, png_error_ptr
, png_error_ptr
));
5686 DEF_DLL_FN (png_infop
, png_create_info_struct
, (png_structp
));
5687 DEF_DLL_FN (void, png_destroy_read_struct
,
5688 (png_structpp
, png_infopp
, png_infopp
));
5689 DEF_DLL_FN (void, png_set_read_fn
, (png_structp
, png_voidp
, png_rw_ptr
));
5690 DEF_DLL_FN (void, png_set_sig_bytes
, (png_structp
, int));
5691 DEF_DLL_FN (void, png_read_info
, (png_structp
, png_infop
));
5692 DEF_DLL_FN (png_uint_32
, png_get_IHDR
,
5693 (png_structp
, png_infop
, png_uint_32
*, png_uint_32
*,
5694 int *, int *, int *, int *, int *));
5695 DEF_DLL_FN (png_uint_32
, png_get_valid
, (png_structp
, png_infop
, png_uint_32
));
5696 DEF_DLL_FN (void, png_set_strip_16
, (png_structp
));
5697 DEF_DLL_FN (void, png_set_expand
, (png_structp
));
5698 DEF_DLL_FN (void, png_set_gray_to_rgb
, (png_structp
));
5699 DEF_DLL_FN (void, png_set_background
,
5700 (png_structp
, png_color_16p
, int, int, double));
5701 DEF_DLL_FN (png_uint_32
, png_get_bKGD
,
5702 (png_structp
, png_infop
, png_color_16p
*));
5703 DEF_DLL_FN (void, png_read_update_info
, (png_structp
, png_infop
));
5704 DEF_DLL_FN (png_byte
, png_get_channels
, (png_structp
, png_infop
));
5705 DEF_DLL_FN (png_size_t
, png_get_rowbytes
, (png_structp
, png_infop
));
5706 DEF_DLL_FN (void, png_read_image
, (png_structp
, png_bytepp
));
5707 DEF_DLL_FN (void, png_read_end
, (png_structp
, png_infop
));
5708 DEF_DLL_FN (void, png_error
, (png_structp
, png_const_charp
));
5710 # if (PNG_LIBPNG_VER >= 10500)
5711 DEF_DLL_FN (void, png_longjmp
, (png_structp
, int)) PNG_NORETURN
;
5712 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn
,
5713 (png_structp
, png_longjmp_ptr
, size_t));
5714 # endif /* libpng version >= 1.5 */
5717 init_png_functions (void)
5721 if (!(library
= w32_delayed_load (Qpng
)))
5724 LOAD_DLL_FN (library
, png_get_io_ptr
);
5725 LOAD_DLL_FN (library
, png_sig_cmp
);
5726 LOAD_DLL_FN (library
, png_create_read_struct
);
5727 LOAD_DLL_FN (library
, png_create_info_struct
);
5728 LOAD_DLL_FN (library
, png_destroy_read_struct
);
5729 LOAD_DLL_FN (library
, png_set_read_fn
);
5730 LOAD_DLL_FN (library
, png_set_sig_bytes
);
5731 LOAD_DLL_FN (library
, png_read_info
);
5732 LOAD_DLL_FN (library
, png_get_IHDR
);
5733 LOAD_DLL_FN (library
, png_get_valid
);
5734 LOAD_DLL_FN (library
, png_set_strip_16
);
5735 LOAD_DLL_FN (library
, png_set_expand
);
5736 LOAD_DLL_FN (library
, png_set_gray_to_rgb
);
5737 LOAD_DLL_FN (library
, png_set_background
);
5738 LOAD_DLL_FN (library
, png_get_bKGD
);
5739 LOAD_DLL_FN (library
, png_read_update_info
);
5740 LOAD_DLL_FN (library
, png_get_channels
);
5741 LOAD_DLL_FN (library
, png_get_rowbytes
);
5742 LOAD_DLL_FN (library
, png_read_image
);
5743 LOAD_DLL_FN (library
, png_read_end
);
5744 LOAD_DLL_FN (library
, png_error
);
5746 # if (PNG_LIBPNG_VER >= 10500)
5747 LOAD_DLL_FN (library
, png_longjmp
);
5748 LOAD_DLL_FN (library
, png_set_longjmp_fn
);
5749 # endif /* libpng version >= 1.5 */
5754 # undef png_create_info_struct
5755 # undef png_create_read_struct
5756 # undef png_destroy_read_struct
5758 # undef png_get_bKGD
5759 # undef png_get_channels
5760 # undef png_get_IHDR
5761 # undef png_get_io_ptr
5762 # undef png_get_rowbytes
5763 # undef png_get_valid
5765 # undef png_read_end
5766 # undef png_read_image
5767 # undef png_read_info
5768 # undef png_read_update_info
5769 # undef png_set_background
5770 # undef png_set_expand
5771 # undef png_set_gray_to_rgb
5772 # undef png_set_longjmp_fn
5773 # undef png_set_read_fn
5774 # undef png_set_sig_bytes
5775 # undef png_set_strip_16
5778 # define png_create_info_struct fn_png_create_info_struct
5779 # define png_create_read_struct fn_png_create_read_struct
5780 # define png_destroy_read_struct fn_png_destroy_read_struct
5781 # define png_error fn_png_error
5782 # define png_get_bKGD fn_png_get_bKGD
5783 # define png_get_channels fn_png_get_channels
5784 # define png_get_IHDR fn_png_get_IHDR
5785 # define png_get_io_ptr fn_png_get_io_ptr
5786 # define png_get_rowbytes fn_png_get_rowbytes
5787 # define png_get_valid fn_png_get_valid
5788 # define png_longjmp fn_png_longjmp
5789 # define png_read_end fn_png_read_end
5790 # define png_read_image fn_png_read_image
5791 # define png_read_info fn_png_read_info
5792 # define png_read_update_info fn_png_read_update_info
5793 # define png_set_background fn_png_set_background
5794 # define png_set_expand fn_png_set_expand
5795 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5796 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5797 # define png_set_read_fn fn_png_set_read_fn
5798 # define png_set_sig_bytes fn_png_set_sig_bytes
5799 # define png_set_strip_16 fn_png_set_strip_16
5800 # define png_sig_cmp fn_png_sig_cmp
5802 # endif /* WINDOWSNT */
5804 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5805 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5806 Do not use sys_setjmp, as PNG supports only jmp_buf.
5807 It's OK if the longjmp substitute restores the signal mask. */
5808 # ifdef HAVE__SETJMP
5809 # define FAST_SETJMP(j) _setjmp (j)
5810 # define FAST_LONGJMP _longjmp
5812 # define FAST_SETJMP(j) setjmp (j)
5813 # define FAST_LONGJMP longjmp
5816 # if PNG_LIBPNG_VER < 10500
5817 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5818 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5820 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5821 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5822 # define PNG_JMPBUF(ptr) \
5823 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5826 /* Error and warning handlers installed when the PNG library
5829 static _Noreturn
void
5830 my_png_error (png_struct
*png_ptr
, const char *msg
)
5832 eassert (png_ptr
!= NULL
);
5833 /* Avoid compiler warning about deprecated direct access to
5834 png_ptr's fields in libpng versions 1.4.x. */
5835 image_error ("PNG error: %s", build_string (msg
));
5836 PNG_LONGJMP (png_ptr
);
5841 my_png_warning (png_struct
*png_ptr
, const char *msg
)
5843 eassert (png_ptr
!= NULL
);
5844 image_error ("PNG warning: %s", build_string (msg
));
5847 /* Memory source for PNG decoding. */
5849 struct png_memory_storage
5851 unsigned char *bytes
; /* The data */
5852 ptrdiff_t len
; /* How big is it? */
5853 ptrdiff_t index
; /* Where are we? */
5857 /* Function set as reader function when reading PNG image from memory.
5858 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5859 bytes from the input to DATA. */
5862 png_read_from_memory (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5864 struct png_memory_storage
*tbr
= png_get_io_ptr (png_ptr
);
5866 if (length
> tbr
->len
- tbr
->index
)
5867 png_error (png_ptr
, "Read error");
5869 memcpy (data
, tbr
->bytes
+ tbr
->index
, length
);
5870 tbr
->index
= tbr
->index
+ length
;
5874 /* Function set as reader function when reading PNG image from a file.
5875 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5876 bytes from the input to DATA. */
5879 png_read_from_file (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5881 FILE *fp
= png_get_io_ptr (png_ptr
);
5883 if (fread (data
, 1, length
, fp
) < length
)
5884 png_error (png_ptr
, "Read error");
5888 /* Load PNG image IMG for use on frame F. Value is true if
5891 struct png_load_context
5893 /* These are members so that longjmp doesn't munge local variables. */
5894 png_struct
*png_ptr
;
5903 png_load_body (struct frame
*f
, struct image
*img
, struct png_load_context
*c
)
5905 Lisp_Object specified_file
, specified_data
;
5909 png_struct
*png_ptr
;
5910 png_info
*info_ptr
= NULL
, *end_info
= NULL
;
5912 png_byte
*pixels
= NULL
;
5913 png_byte
**rows
= NULL
;
5914 png_uint_32 width
, height
;
5915 int bit_depth
, color_type
, interlace_type
;
5917 png_uint_32 row_bytes
;
5919 struct png_memory_storage tbr
; /* Data to be read */
5923 unsigned char *data
= 0;
5926 XImagePtr ximg
, mask_img
= NULL
;
5929 /* Find out what file to load. */
5930 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5931 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5933 if (NILP (specified_data
))
5936 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5937 if (!STRINGP (file
))
5939 image_error ("Cannot find image file `%s'", specified_file
);
5943 /* Open the image file. */
5944 fp
= fdopen (fd
, "rb");
5947 image_error ("Cannot open image file `%s'", file
);
5951 /* Check PNG signature. */
5952 if (fread (sig
, 1, sizeof sig
, fp
) != sizeof sig
5953 || png_sig_cmp (sig
, 0, sizeof sig
))
5956 image_error ("Not a PNG file: `%s'", file
);
5962 if (!STRINGP (specified_data
))
5964 image_error ("Invalid image data `%s'", specified_data
);
5968 /* Read from memory. */
5969 tbr
.bytes
= SDATA (specified_data
);
5970 tbr
.len
= SBYTES (specified_data
);
5973 /* Check PNG signature. */
5974 if (tbr
.len
< sizeof sig
5975 || png_sig_cmp (tbr
.bytes
, 0, sizeof sig
))
5977 image_error ("Not a PNG image: `%s'", img
->spec
);
5981 /* Need to skip past the signature. */
5982 tbr
.bytes
+= sizeof (sig
);
5985 /* Initialize read and info structs for PNG lib. */
5986 png_ptr
= png_create_read_struct (PNG_LIBPNG_VER_STRING
,
5991 info_ptr
= png_create_info_struct (png_ptr
);
5992 end_info
= png_create_info_struct (png_ptr
);
5995 c
->png_ptr
= png_ptr
;
5996 c
->info_ptr
= info_ptr
;
5997 c
->end_info
= end_info
;
6002 if (! (info_ptr
&& end_info
))
6004 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6009 if (fp
) fclose (fp
);
6013 /* Set error jump-back. We come back here when the PNG library
6014 detects an error. */
6015 if (FAST_SETJMP (PNG_JMPBUF (png_ptr
)))
6019 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6027 /* Read image info. */
6028 if (!NILP (specified_data
))
6029 png_set_read_fn (png_ptr
, &tbr
, png_read_from_memory
);
6031 png_set_read_fn (png_ptr
, fp
, png_read_from_file
);
6033 png_set_sig_bytes (png_ptr
, sizeof sig
);
6034 png_read_info (png_ptr
, info_ptr
);
6035 png_get_IHDR (png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
,
6036 &interlace_type
, NULL
, NULL
);
6038 if (! (width
<= INT_MAX
&& height
<= INT_MAX
6039 && check_image_size (f
, width
, height
)))
6041 image_size_error ();
6046 /* Create the X image and pixmap now, so that the work below can be
6047 omitted if the image is too large for X. */
6048 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6052 /* If image contains simply transparency data, we prefer to
6053 construct a clipping mask. */
6054 if (png_get_valid (png_ptr
, info_ptr
, PNG_INFO_tRNS
))
6059 /* This function is easier to write if we only have to handle
6060 one data format: RGB or RGBA with 8 bits per channel. Let's
6061 transform other formats into that format. */
6063 /* Strip more than 8 bits per channel. */
6064 if (bit_depth
== 16)
6065 png_set_strip_16 (png_ptr
);
6067 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6069 png_set_expand (png_ptr
);
6071 /* Convert grayscale images to RGB. */
6072 if (color_type
== PNG_COLOR_TYPE_GRAY
6073 || color_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
6074 png_set_gray_to_rgb (png_ptr
);
6076 /* Handle alpha channel by combining the image with a background
6077 color. Do this only if a real alpha channel is supplied. For
6078 simple transparency, we prefer a clipping mask. */
6081 /* png_color_16 *image_bg; */
6082 Lisp_Object specified_bg
6083 = image_spec_value (img
->spec
, QCbackground
, NULL
);
6086 /* If the user specified a color, try to use it; if not, use the
6087 current frame background, ignoring any default background
6088 color set by the image. */
6089 if (STRINGP (specified_bg
)
6090 ? x_defined_color (f
, SSDATA (specified_bg
), &color
, false)
6091 : (x_query_frame_background_color (f
, &color
), true))
6092 /* The user specified `:background', use that. */
6094 int shift
= bit_depth
== 16 ? 0 : 8;
6095 png_color_16 bg
= { 0 };
6096 bg
.red
= color
.red
>> shift
;
6097 bg
.green
= color
.green
>> shift
;
6098 bg
.blue
= color
.blue
>> shift
;
6100 png_set_background (png_ptr
, &bg
,
6101 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
6105 /* Update info structure. */
6106 png_read_update_info (png_ptr
, info_ptr
);
6108 /* Get number of channels. Valid values are 1 for grayscale images
6109 and images with a palette, 2 for grayscale images with transparency
6110 information (alpha channel), 3 for RGB images, and 4 for RGB
6111 images with alpha channel, i.e. RGBA. If conversions above were
6112 sufficient we should only have 3 or 4 channels here. */
6113 channels
= png_get_channels (png_ptr
, info_ptr
);
6114 eassert (channels
== 3 || channels
== 4);
6116 /* Number of bytes needed for one row of the image. */
6117 row_bytes
= png_get_rowbytes (png_ptr
, info_ptr
);
6119 /* Allocate memory for the image. */
6120 if (INT_MULTIPLY_WRAPV (row_bytes
, sizeof *pixels
, &nbytes
)
6121 || INT_MULTIPLY_WRAPV (nbytes
, height
, &nbytes
))
6122 memory_full (SIZE_MAX
);
6123 c
->pixels
= pixels
= xmalloc (nbytes
);
6124 c
->rows
= rows
= xmalloc (height
* sizeof *rows
);
6125 for (i
= 0; i
< height
; ++i
)
6126 rows
[i
] = pixels
+ i
* row_bytes
;
6128 /* Read the entire image. */
6129 png_read_image (png_ptr
, rows
);
6130 png_read_end (png_ptr
, info_ptr
);
6138 data
= (unsigned char *) xmalloc (width
* height
* 4);
6139 dataptr
= (uint32_t *) data
;
6141 /* Create an image and pixmap serving as mask if the PNG image
6142 contains an alpha channel. */
6145 && !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
6148 x_destroy_x_image (ximg
);
6149 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
);
6154 /* Fill the X image and mask from PNG data. */
6155 init_color_table ();
6157 for (y
= 0; y
< height
; ++y
)
6159 png_byte
*p
= rows
[y
];
6161 for (x
= 0; x
< width
; ++x
)
6170 if (channels
== 4) a
= *p
++;
6171 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
6176 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
6177 /* An alpha channel, aka mask channel, associates variable
6178 transparency with an image. Where other image formats
6179 support binary transparency---fully transparent or fully
6180 opaque---PNG allows up to 254 levels of partial transparency.
6181 The PNG library implements partial transparency by combining
6182 the image with a specified background color.
6184 I'm not sure how to handle this here nicely: because the
6185 background on which the image is displayed may change, for
6186 real alpha channel support, it would be necessary to create
6187 a new image for each possible background.
6189 What I'm doing now is that a mask is created if we have
6190 boolean transparency information. Otherwise I'm using
6191 the frame's background color to combine the image with. */
6196 XPutPixel (mask_img
, x
, y
, *p
> 0 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
);
6203 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6204 /* Set IMG's background color from the PNG image, unless the user
6208 if (png_get_bKGD (png_ptr
, info_ptr
, &bg
))
6210 img
->background
= lookup_rgb_color (f
, bg
->red
, bg
->green
, bg
->blue
);
6211 img
->background_valid
= 1;
6215 # ifdef COLOR_TABLE_SUPPORT
6216 /* Remember colors allocated for this image. */
6217 img
->colors
= colors_in_color_table (&img
->ncolors
);
6218 free_color_table ();
6219 # endif /* COLOR_TABLE_SUPPORT */
6222 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6227 img
->height
= height
;
6230 create_cairo_image_surface (img
, data
, width
, height
);
6232 /* Maybe fill in the background field while we have ximg handy.
6233 Casting avoids a GCC warning. */
6234 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6236 /* Put ximg into the image. */
6237 image_put_x_image (f
, img
, ximg
, 0);
6239 /* Same for the mask. */
6242 /* Fill in the background_transparent field while we have the
6243 mask handy. Casting avoids a GCC warning. */
6244 image_background_transparent (img
, f
, (XImagePtr_or_DC
)mask_img
);
6246 image_put_x_image (f
, img
, mask_img
, 1);
6254 png_load (struct frame
*f
, struct image
*img
)
6256 struct png_load_context c
;
6257 return png_load_body (f
, img
, &c
);
6260 #elif defined HAVE_NS
6263 png_load (struct frame
*f
, struct image
*img
)
6265 return ns_load_image (f
, img
,
6266 image_spec_value (img
->spec
, QCfile
, NULL
),
6267 image_spec_value (img
->spec
, QCdata
, NULL
));
6271 #endif /* HAVE_NS */
6275 /***********************************************************************
6277 ***********************************************************************/
6279 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6281 static bool jpeg_image_p (Lisp_Object object
);
6282 static bool jpeg_load (struct frame
*f
, struct image
*img
);
6284 /* Indices of image specification fields in gs_format, below. */
6286 enum jpeg_keyword_index
6295 JPEG_HEURISTIC_MASK
,
6301 /* Vector of image_keyword structures describing the format
6302 of valid user-defined image specifications. */
6304 static const struct image_keyword jpeg_format
[JPEG_LAST
] =
6306 {":type", IMAGE_SYMBOL_VALUE
, 1},
6307 {":data", IMAGE_STRING_VALUE
, 0},
6308 {":file", IMAGE_STRING_VALUE
, 0},
6309 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6310 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6311 {":relief", IMAGE_INTEGER_VALUE
, 0},
6312 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6313 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6314 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6315 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
6318 #if defined HAVE_NTGUI && defined WINDOWSNT
6319 static bool init_jpeg_functions (void);
6321 #define init_jpeg_functions NULL
6324 /* Structure describing the image type `jpeg'. */
6326 static struct image_type jpeg_type
=
6328 SYMBOL_INDEX (Qjpeg
),
6332 init_jpeg_functions
,
6336 /* Return true if OBJECT is a valid JPEG image specification. */
6339 jpeg_image_p (Lisp_Object object
)
6341 struct image_keyword fmt
[JPEG_LAST
];
6343 memcpy (fmt
, jpeg_format
, sizeof fmt
);
6345 if (!parse_image_spec (object
, fmt
, JPEG_LAST
, Qjpeg
))
6348 /* Must specify either the :data or :file keyword. */
6349 return fmt
[JPEG_FILE
].count
+ fmt
[JPEG_DATA
].count
== 1;
6352 #endif /* HAVE_JPEG || HAVE_NS */
6356 /* Work around a warning about HAVE_STDLIB_H being redefined in
6358 # ifdef HAVE_STDLIB_H
6359 # undef HAVE_STDLIB_H
6362 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6363 /* In older releases of the jpeg library, jpeglib.h will define boolean
6364 differently depending on __WIN32__, so make sure it is defined. */
6365 # define __WIN32__ 1
6368 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6369 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6370 using the Windows boolean type instead of the jpeglib boolean type
6371 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6372 headers are included along with windows.h, so under Cygwin, jpeglib
6373 attempts to define a conflicting boolean type. Worse, forcing
6374 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6375 because it created an ABI incompatibility between the
6376 already-compiled jpeg library and the header interface definition.
6378 The best we can do is to define jpeglib's boolean type to a
6379 different name. This name, jpeg_boolean, remains in effect through
6380 the rest of image.c.
6382 # if defined CYGWIN && defined HAVE_NTGUI
6383 # define boolean jpeg_boolean
6385 # include <jpeglib.h>
6386 # include <jerror.h>
6390 /* JPEG library details. */
6391 DEF_DLL_FN (void, jpeg_CreateDecompress
, (j_decompress_ptr
, int, size_t));
6392 DEF_DLL_FN (boolean
, jpeg_start_decompress
, (j_decompress_ptr
));
6393 DEF_DLL_FN (boolean
, jpeg_finish_decompress
, (j_decompress_ptr
));
6394 DEF_DLL_FN (void, jpeg_destroy_decompress
, (j_decompress_ptr
));
6395 DEF_DLL_FN (int, jpeg_read_header
, (j_decompress_ptr
, boolean
));
6396 DEF_DLL_FN (JDIMENSION
, jpeg_read_scanlines
,
6397 (j_decompress_ptr
, JSAMPARRAY
, JDIMENSION
));
6398 DEF_DLL_FN (struct jpeg_error_mgr
*, jpeg_std_error
,
6399 (struct jpeg_error_mgr
*));
6400 DEF_DLL_FN (boolean
, jpeg_resync_to_restart
, (j_decompress_ptr
, int));
6403 init_jpeg_functions (void)
6407 if (!(library
= w32_delayed_load (Qjpeg
)))
6410 LOAD_DLL_FN (library
, jpeg_finish_decompress
);
6411 LOAD_DLL_FN (library
, jpeg_read_scanlines
);
6412 LOAD_DLL_FN (library
, jpeg_start_decompress
);
6413 LOAD_DLL_FN (library
, jpeg_read_header
);
6414 LOAD_DLL_FN (library
, jpeg_CreateDecompress
);
6415 LOAD_DLL_FN (library
, jpeg_destroy_decompress
);
6416 LOAD_DLL_FN (library
, jpeg_std_error
);
6417 LOAD_DLL_FN (library
, jpeg_resync_to_restart
);
6421 # undef jpeg_CreateDecompress
6422 # undef jpeg_destroy_decompress
6423 # undef jpeg_finish_decompress
6424 # undef jpeg_read_header
6425 # undef jpeg_read_scanlines
6426 # undef jpeg_resync_to_restart
6427 # undef jpeg_start_decompress
6428 # undef jpeg_std_error
6430 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6431 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6432 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6433 # define jpeg_read_header fn_jpeg_read_header
6434 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6435 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6436 # define jpeg_start_decompress fn_jpeg_start_decompress
6437 # define jpeg_std_error fn_jpeg_std_error
6439 /* Wrapper since we can't directly assign the function pointer
6440 to another function pointer that was declared more completely easily. */
6442 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo
, int desired
)
6444 return jpeg_resync_to_restart (cinfo
, desired
);
6446 # undef jpeg_resync_to_restart
6447 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6449 # endif /* WINDOWSNT */
6451 struct my_jpeg_error_mgr
6453 struct jpeg_error_mgr pub
;
6454 sys_jmp_buf setjmp_buffer
;
6456 /* The remaining members are so that longjmp doesn't munge local
6458 struct jpeg_decompress_struct cinfo
;
6462 MY_JPEG_INVALID_IMAGE_SIZE
,
6463 MY_JPEG_CANNOT_CREATE_X
6468 static _Noreturn
void
6469 my_error_exit (j_common_ptr cinfo
)
6471 struct my_jpeg_error_mgr
*mgr
= (struct my_jpeg_error_mgr
*) cinfo
->err
;
6472 mgr
->failure_code
= MY_JPEG_ERROR_EXIT
;
6473 sys_longjmp (mgr
->setjmp_buffer
, 1);
6477 /* Init source method for JPEG data source manager. Called by
6478 jpeg_read_header() before any data is actually read. See
6479 libjpeg.doc from the JPEG lib distribution. */
6482 our_common_init_source (j_decompress_ptr cinfo
)
6487 /* Method to terminate data source. Called by
6488 jpeg_finish_decompress() after all data has been processed. */
6491 our_common_term_source (j_decompress_ptr cinfo
)
6496 /* Fill input buffer method for JPEG data source manager. Called
6497 whenever more data is needed. We read the whole image in one step,
6498 so this only adds a fake end of input marker at the end. */
6500 static JOCTET our_memory_buffer
[2];
6503 our_memory_fill_input_buffer (j_decompress_ptr cinfo
)
6505 /* Insert a fake EOI marker. */
6506 struct jpeg_source_mgr
*src
= cinfo
->src
;
6508 our_memory_buffer
[0] = (JOCTET
) 0xFF;
6509 our_memory_buffer
[1] = (JOCTET
) JPEG_EOI
;
6511 src
->next_input_byte
= our_memory_buffer
;
6512 src
->bytes_in_buffer
= 2;
6517 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6518 is the JPEG data source manager. */
6521 our_memory_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6523 struct jpeg_source_mgr
*src
= cinfo
->src
;
6527 if (num_bytes
> src
->bytes_in_buffer
)
6528 ERREXIT (cinfo
, JERR_INPUT_EOF
);
6530 src
->bytes_in_buffer
-= num_bytes
;
6531 src
->next_input_byte
+= num_bytes
;
6536 /* Set up the JPEG lib for reading an image from DATA which contains
6537 LEN bytes. CINFO is the decompression info structure created for
6538 reading the image. */
6541 jpeg_memory_src (j_decompress_ptr cinfo
, JOCTET
*data
, ptrdiff_t len
)
6543 struct jpeg_source_mgr
*src
= cinfo
->src
;
6547 /* First time for this JPEG object? */
6548 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6549 JPOOL_PERMANENT
, sizeof *src
);
6551 src
->next_input_byte
= data
;
6554 src
->init_source
= our_common_init_source
;
6555 src
->fill_input_buffer
= our_memory_fill_input_buffer
;
6556 src
->skip_input_data
= our_memory_skip_input_data
;
6557 src
->resync_to_restart
= jpeg_resync_to_restart
; /* Use default method. */
6558 src
->term_source
= our_common_term_source
;
6559 src
->bytes_in_buffer
= len
;
6560 src
->next_input_byte
= data
;
6564 struct jpeg_stdio_mgr
6566 struct jpeg_source_mgr mgr
;
6573 /* Size of buffer to read JPEG from file.
6574 Not too big, as we want to use alloc_small. */
6575 #define JPEG_STDIO_BUFFER_SIZE 8192
6578 /* Fill input buffer method for JPEG data source manager. Called
6579 whenever more data is needed. The data is read from a FILE *. */
6582 our_stdio_fill_input_buffer (j_decompress_ptr cinfo
)
6584 struct jpeg_stdio_mgr
*src
;
6586 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6591 bytes
= fread (src
->buffer
, 1, JPEG_STDIO_BUFFER_SIZE
, src
->file
);
6593 src
->mgr
.bytes_in_buffer
= bytes
;
6596 WARNMS (cinfo
, JWRN_JPEG_EOF
);
6598 src
->buffer
[0] = (JOCTET
) 0xFF;
6599 src
->buffer
[1] = (JOCTET
) JPEG_EOI
;
6600 src
->mgr
.bytes_in_buffer
= 2;
6602 src
->mgr
.next_input_byte
= src
->buffer
;
6609 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6610 is the JPEG data source manager. */
6613 our_stdio_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6615 struct jpeg_stdio_mgr
*src
;
6616 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6618 while (num_bytes
> 0 && !src
->finished
)
6620 if (num_bytes
<= src
->mgr
.bytes_in_buffer
)
6622 src
->mgr
.bytes_in_buffer
-= num_bytes
;
6623 src
->mgr
.next_input_byte
+= num_bytes
;
6628 num_bytes
-= src
->mgr
.bytes_in_buffer
;
6629 src
->mgr
.bytes_in_buffer
= 0;
6630 src
->mgr
.next_input_byte
= NULL
;
6632 our_stdio_fill_input_buffer (cinfo
);
6638 /* Set up the JPEG lib for reading an image from a FILE *.
6639 CINFO is the decompression info structure created for
6640 reading the image. */
6643 jpeg_file_src (j_decompress_ptr cinfo
, FILE *fp
)
6645 struct jpeg_stdio_mgr
*src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6649 /* First time for this JPEG object? */
6650 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6651 JPOOL_PERMANENT
, sizeof *src
);
6652 cinfo
->src
= (struct jpeg_source_mgr
*) src
;
6653 src
->buffer
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6655 JPEG_STDIO_BUFFER_SIZE
);
6660 src
->mgr
.init_source
= our_common_init_source
;
6661 src
->mgr
.fill_input_buffer
= our_stdio_fill_input_buffer
;
6662 src
->mgr
.skip_input_data
= our_stdio_skip_input_data
;
6663 src
->mgr
.resync_to_restart
= jpeg_resync_to_restart
; /* Use default. */
6664 src
->mgr
.term_source
= our_common_term_source
;
6665 src
->mgr
.bytes_in_buffer
= 0;
6666 src
->mgr
.next_input_byte
= NULL
;
6669 /* Load image IMG for use on frame F. Patterned after example.c
6670 from the JPEG lib. */
6673 jpeg_load_body (struct frame
*f
, struct image
*img
,
6674 struct my_jpeg_error_mgr
*mgr
)
6676 Lisp_Object specified_file
, specified_data
;
6677 FILE *volatile fp
= NULL
;
6679 int row_stride
, x
, y
;
6680 unsigned long *colors
;
6684 XImagePtr ximg
= NULL
;
6687 /* Open the JPEG file. */
6688 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6689 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6691 if (NILP (specified_data
))
6694 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
6695 if (!STRINGP (file
))
6697 image_error ("Cannot find image file `%s'", specified_file
);
6701 fp
= fdopen (fd
, "rb");
6704 image_error ("Cannot open `%s'", file
);
6708 else if (!STRINGP (specified_data
))
6710 image_error ("Invalid image data `%s'", specified_data
);
6714 /* Customize libjpeg's error handling to call my_error_exit when an
6715 error is detected. This function will perform a longjmp. */
6716 mgr
->cinfo
.err
= jpeg_std_error (&mgr
->pub
);
6717 mgr
->pub
.error_exit
= my_error_exit
;
6718 if (sys_setjmp (mgr
->setjmp_buffer
))
6720 switch (mgr
->failure_code
)
6722 case MY_JPEG_ERROR_EXIT
:
6724 char buf
[JMSG_LENGTH_MAX
];
6725 mgr
->cinfo
.err
->format_message ((j_common_ptr
) &mgr
->cinfo
, buf
);
6726 image_error ("Error reading JPEG image `%s': %s",
6727 img
->spec
, build_string (buf
));
6731 case MY_JPEG_INVALID_IMAGE_SIZE
:
6732 image_size_error ();
6735 case MY_JPEG_CANNOT_CREATE_X
:
6739 /* Close the input file and destroy the JPEG object. */
6742 jpeg_destroy_decompress (&mgr
->cinfo
);
6744 /* If we already have an XImage, free that. */
6746 x_destroy_x_image (ximg
);
6748 /* Free pixmap and colors. */
6749 x_clear_image (f
, img
);
6753 /* Create the JPEG decompression object. Let it read from fp.
6754 Read the JPEG image header. */
6755 jpeg_CreateDecompress (&mgr
->cinfo
, JPEG_LIB_VERSION
, sizeof *&mgr
->cinfo
);
6757 if (NILP (specified_data
))
6758 jpeg_file_src (&mgr
->cinfo
, fp
);
6760 jpeg_memory_src (&mgr
->cinfo
, SDATA (specified_data
),
6761 SBYTES (specified_data
));
6763 jpeg_read_header (&mgr
->cinfo
, 1);
6765 /* Customize decompression so that color quantization will be used.
6766 Start decompression. */
6767 mgr
->cinfo
.quantize_colors
= 1;
6768 jpeg_start_decompress (&mgr
->cinfo
);
6769 width
= img
->width
= mgr
->cinfo
.output_width
;
6770 height
= img
->height
= mgr
->cinfo
.output_height
;
6772 if (!check_image_size (f
, width
, height
))
6774 mgr
->failure_code
= MY_JPEG_INVALID_IMAGE_SIZE
;
6775 sys_longjmp (mgr
->setjmp_buffer
, 1);
6779 /* Create X image and pixmap. */
6780 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6782 mgr
->failure_code
= MY_JPEG_CANNOT_CREATE_X
;
6783 sys_longjmp (mgr
->setjmp_buffer
, 1);
6787 /* Allocate colors. When color quantization is used,
6788 mgr->cinfo.actual_number_of_colors has been set with the number of
6789 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6790 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6791 No more than 255 colors will be generated. */
6794 if (mgr
->cinfo
.out_color_components
> 2)
6795 ir
= 0, ig
= 1, ib
= 2;
6796 else if (mgr
->cinfo
.out_color_components
> 1)
6797 ir
= 0, ig
= 1, ib
= 0;
6799 ir
= 0, ig
= 0, ib
= 0;
6802 /* Use the color table mechanism because it handles colors that
6803 cannot be allocated nicely. Such colors will be replaced with
6804 a default color, and we don't have to care about which colors
6805 can be freed safely, and which can't. */
6806 init_color_table ();
6807 SAFE_NALLOCA (colors
, 1, mgr
->cinfo
.actual_number_of_colors
);
6809 for (i
= 0; i
< mgr
->cinfo
.actual_number_of_colors
; ++i
)
6811 /* Multiply RGB values with 255 because X expects RGB values
6812 in the range 0..0xffff. */
6813 int r
= mgr
->cinfo
.colormap
[ir
][i
] << 8;
6814 int g
= mgr
->cinfo
.colormap
[ig
][i
] << 8;
6815 int b
= mgr
->cinfo
.colormap
[ib
][i
] << 8;
6816 colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
6820 #ifdef COLOR_TABLE_SUPPORT
6821 /* Remember those colors actually allocated. */
6822 img
->colors
= colors_in_color_table (&img
->ncolors
);
6823 free_color_table ();
6824 #endif /* COLOR_TABLE_SUPPORT */
6828 row_stride
= width
* mgr
->cinfo
.output_components
;
6829 buffer
= mgr
->cinfo
.mem
->alloc_sarray ((j_common_ptr
) &mgr
->cinfo
,
6830 JPOOL_IMAGE
, row_stride
, 1);
6833 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
6834 uint32_t *dataptr
= (uint32_t *) data
;
6837 for (y
= 0; y
< height
; ++y
)
6839 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6841 for (x
= 0; x
< width
; ++x
)
6844 r
= mgr
->cinfo
.colormap
[ir
][i
];
6845 g
= mgr
->cinfo
.colormap
[ig
][i
];
6846 b
= mgr
->cinfo
.colormap
[ib
][i
];
6847 *dataptr
++ = (0xffu
<< 24) | (r
<< 16) | (g
<< 8) | b
;
6851 create_cairo_image_surface (img
, data
, width
, height
);
6854 for (y
= 0; y
< height
; ++y
)
6856 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6857 for (x
= 0; x
< mgr
->cinfo
.output_width
; ++x
)
6858 XPutPixel (ximg
, x
, y
, colors
[buffer
[0][x
]]);
6863 jpeg_finish_decompress (&mgr
->cinfo
);
6864 jpeg_destroy_decompress (&mgr
->cinfo
);
6869 /* Maybe fill in the background field while we have ximg handy. */
6870 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6871 /* Casting avoids a GCC warning. */
6872 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6874 /* Put ximg into the image. */
6875 image_put_x_image (f
, img
, ximg
, 0);
6882 jpeg_load (struct frame
*f
, struct image
*img
)
6884 struct my_jpeg_error_mgr mgr
;
6885 return jpeg_load_body (f
, img
, &mgr
);
6888 #else /* HAVE_JPEG */
6892 jpeg_load (struct frame
*f
, struct image
*img
)
6894 return ns_load_image (f
, img
,
6895 image_spec_value (img
->spec
, QCfile
, NULL
),
6896 image_spec_value (img
->spec
, QCdata
, NULL
));
6898 #endif /* HAVE_NS */
6900 #endif /* !HAVE_JPEG */
6904 /***********************************************************************
6906 ***********************************************************************/
6908 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6910 static bool tiff_image_p (Lisp_Object object
);
6911 static bool tiff_load (struct frame
*f
, struct image
*img
);
6913 /* Indices of image specification fields in tiff_format, below. */
6915 enum tiff_keyword_index
6924 TIFF_HEURISTIC_MASK
,
6931 /* Vector of image_keyword structures describing the format
6932 of valid user-defined image specifications. */
6934 static const struct image_keyword tiff_format
[TIFF_LAST
] =
6936 {":type", IMAGE_SYMBOL_VALUE
, 1},
6937 {":data", IMAGE_STRING_VALUE
, 0},
6938 {":file", IMAGE_STRING_VALUE
, 0},
6939 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6940 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6941 {":relief", IMAGE_INTEGER_VALUE
, 0},
6942 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6943 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6944 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6945 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
6946 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0}
6949 #if defined HAVE_NTGUI && defined WINDOWSNT
6950 static bool init_tiff_functions (void);
6952 #define init_tiff_functions NULL
6955 /* Structure describing the image type `tiff'. */
6957 static struct image_type tiff_type
=
6959 SYMBOL_INDEX (Qtiff
),
6963 init_tiff_functions
,
6967 /* Return true if OBJECT is a valid TIFF image specification. */
6970 tiff_image_p (Lisp_Object object
)
6972 struct image_keyword fmt
[TIFF_LAST
];
6973 memcpy (fmt
, tiff_format
, sizeof fmt
);
6975 if (!parse_image_spec (object
, fmt
, TIFF_LAST
, Qtiff
))
6978 /* Must specify either the :data or :file keyword. */
6979 return fmt
[TIFF_FILE
].count
+ fmt
[TIFF_DATA
].count
== 1;
6982 #endif /* HAVE_TIFF || HAVE_NS */
6986 # include <tiffio.h>
6990 /* TIFF library details. */
6991 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetErrorHandler
, (TIFFErrorHandler
));
6992 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetWarningHandler
, (TIFFErrorHandler
));
6993 DEF_DLL_FN (TIFF
*, TIFFOpen
, (const char *, const char *));
6994 DEF_DLL_FN (TIFF
*, TIFFClientOpen
,
6995 (const char *, const char *, thandle_t
, TIFFReadWriteProc
,
6996 TIFFReadWriteProc
, TIFFSeekProc
, TIFFCloseProc
, TIFFSizeProc
,
6997 TIFFMapFileProc
, TIFFUnmapFileProc
));
6998 DEF_DLL_FN (int, TIFFGetField
, (TIFF
*, ttag_t
, ...));
6999 DEF_DLL_FN (int, TIFFReadRGBAImage
, (TIFF
*, uint32
, uint32
, uint32
*, int));
7000 DEF_DLL_FN (void, TIFFClose
, (TIFF
*));
7001 DEF_DLL_FN (int, TIFFSetDirectory
, (TIFF
*, tdir_t
));
7004 init_tiff_functions (void)
7008 if (!(library
= w32_delayed_load (Qtiff
)))
7011 LOAD_DLL_FN (library
, TIFFSetErrorHandler
);
7012 LOAD_DLL_FN (library
, TIFFSetWarningHandler
);
7013 LOAD_DLL_FN (library
, TIFFOpen
);
7014 LOAD_DLL_FN (library
, TIFFClientOpen
);
7015 LOAD_DLL_FN (library
, TIFFGetField
);
7016 LOAD_DLL_FN (library
, TIFFReadRGBAImage
);
7017 LOAD_DLL_FN (library
, TIFFClose
);
7018 LOAD_DLL_FN (library
, TIFFSetDirectory
);
7022 # undef TIFFClientOpen
7024 # undef TIFFGetField
7026 # undef TIFFReadRGBAImage
7027 # undef TIFFSetDirectory
7028 # undef TIFFSetErrorHandler
7029 # undef TIFFSetWarningHandler
7031 # define TIFFClientOpen fn_TIFFClientOpen
7032 # define TIFFClose fn_TIFFClose
7033 # define TIFFGetField fn_TIFFGetField
7034 # define TIFFOpen fn_TIFFOpen
7035 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7036 # define TIFFSetDirectory fn_TIFFSetDirectory
7037 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7038 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7040 # endif /* WINDOWSNT */
7043 /* Reading from a memory buffer for TIFF images Based on the PNG
7044 memory source, but we have to provide a lot of extra functions.
7047 We really only need to implement read and seek, but I am not
7048 convinced that the TIFF library is smart enough not to destroy
7049 itself if we only hand it the function pointers we need to
7054 unsigned char *bytes
;
7061 tiff_read_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7063 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7065 size
= min (size
, src
->len
- src
->index
);
7066 memcpy (buf
, src
->bytes
+ src
->index
, size
);
7072 tiff_write_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7078 tiff_seek_in_memory (thandle_t data
, toff_t off
, int whence
)
7080 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7085 case SEEK_SET
: /* Go from beginning of source. */
7089 case SEEK_END
: /* Go from end of source. */
7090 idx
= src
->len
+ off
;
7093 case SEEK_CUR
: /* Go from current position. */
7094 idx
= src
->index
+ off
;
7097 default: /* Invalid `whence'. */
7101 if (idx
> src
->len
|| idx
< 0)
7109 tiff_close_memory (thandle_t data
)
7116 tiff_mmap_memory (thandle_t data
, tdata_t
*pbase
, toff_t
*psize
)
7118 /* It is already _IN_ memory. */
7123 tiff_unmap_memory (thandle_t data
, tdata_t base
, toff_t size
)
7125 /* We don't need to do this. */
7129 tiff_size_of_memory (thandle_t data
)
7131 return ((tiff_memory_source
*) data
)->len
;
7134 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7135 compiler error compiling tiff_handler, see Bugzilla bug #17406
7136 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7137 this function as external works around that problem. */
7138 # if defined (__MINGW32__) && __GNUC__ == 3
7139 # define MINGW_STATIC
7141 # define MINGW_STATIC static
7145 tiff_handler (const char *, const char *, const char *, va_list)
7146 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7148 tiff_handler (const char *log_format
, const char *title
,
7149 const char *format
, va_list ap
)
7151 /* doprnt is not suitable here, as TIFF handlers are called from
7152 libtiff and are passed arbitrary printf directives. Instead, use
7153 vsnprintf, taking care to be portable to nonstandard environments
7154 where vsnprintf returns -1 on buffer overflow. Since it's just a
7155 log entry, it's OK to truncate it. */
7157 int len
= vsnprintf (buf
, sizeof buf
, format
, ap
);
7158 add_to_log (log_format
, build_string (title
),
7159 make_string (buf
, max (0, min (len
, sizeof buf
- 1))));
7161 # undef MINGW_STATIC
7163 static void tiff_error_handler (const char *, const char *, va_list)
7164 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7166 tiff_error_handler (const char *title
, const char *format
, va_list ap
)
7168 tiff_handler ("TIFF error: %s %s", title
, format
, ap
);
7172 static void tiff_warning_handler (const char *, const char *, va_list)
7173 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7175 tiff_warning_handler (const char *title
, const char *format
, va_list ap
)
7177 tiff_handler ("TIFF warning: %s %s", title
, format
, ap
);
7181 /* Load TIFF image IMG for use on frame F. Value is true if
7185 tiff_load (struct frame
*f
, struct image
*img
)
7187 Lisp_Object specified_file
;
7188 Lisp_Object specified_data
;
7190 int width
, height
, x
, y
, count
;
7194 tiff_memory_source memsrc
;
7197 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7198 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7200 TIFFSetErrorHandler ((TIFFErrorHandler
) tiff_error_handler
);
7201 TIFFSetWarningHandler ((TIFFErrorHandler
) tiff_warning_handler
);
7203 if (NILP (specified_data
))
7205 /* Read from a file */
7206 Lisp_Object file
= x_find_image_file (specified_file
);
7207 if (!STRINGP (file
))
7209 image_error ("Cannot find image file `%s'", specified_file
);
7213 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7215 encoded_file
= ansi_encode_filename (encoded_file
);
7218 /* Try to open the image file. */
7219 tiff
= TIFFOpen (SSDATA (encoded_file
), "r");
7222 image_error ("Cannot open `%s'", file
);
7228 if (!STRINGP (specified_data
))
7230 image_error ("Invalid image data `%s'", specified_data
);
7234 /* Memory source! */
7235 memsrc
.bytes
= SDATA (specified_data
);
7236 memsrc
.len
= SBYTES (specified_data
);
7239 tiff
= TIFFClientOpen ("memory_source", "r", (thandle_t
)&memsrc
,
7240 tiff_read_from_memory
,
7241 tiff_write_from_memory
,
7242 tiff_seek_in_memory
,
7244 tiff_size_of_memory
,
7250 image_error ("Cannot open memory source for `%s'", img
->spec
);
7255 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
7256 if (INTEGERP (image
))
7258 EMACS_INT ino
= XFASTINT (image
);
7259 if (! (TYPE_MINIMUM (tdir_t
) <= ino
&& ino
<= TYPE_MAXIMUM (tdir_t
)
7260 && TIFFSetDirectory (tiff
, ino
)))
7262 image_error ("Invalid image number `%s' in image `%s'",
7269 /* Get width and height of the image, and allocate a raster buffer
7270 of width x height 32-bit values. */
7271 TIFFGetField (tiff
, TIFFTAG_IMAGEWIDTH
, &width
);
7272 TIFFGetField (tiff
, TIFFTAG_IMAGELENGTH
, &height
);
7274 if (!check_image_size (f
, width
, height
))
7276 image_size_error ();
7281 /* Create the X image and pixmap. */
7282 if (! (height
<= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *buf
/ width
7283 && image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
7290 buf
= xmalloc (sizeof *buf
* width
* height
);
7292 rc
= TIFFReadRGBAImage (tiff
, width
, height
, buf
, 0);
7294 /* Count the number of images in the file. */
7295 for (count
= 1; TIFFSetDirectory (tiff
, count
); count
++)
7299 img
->lisp_data
= Fcons (Qcount
,
7300 Fcons (make_number (count
),
7306 image_error ("Error reading TIFF image `%s'", img
->spec
);
7313 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
7314 uint32_t *dataptr
= (uint32_t *) data
;
7316 for (y
= 0; y
< height
; ++y
)
7318 uint32
*row
= buf
+ (height
- 1 - y
) * width
;
7319 for (x
= 0; x
< width
; ++x
)
7321 uint32 abgr
= row
[x
];
7322 int r
= TIFFGetR (abgr
);
7323 int g
= TIFFGetG (abgr
);
7324 int b
= TIFFGetB (abgr
);
7325 int a
= TIFFGetA (abgr
);
7326 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
7330 create_cairo_image_surface (img
, data
, width
, height
);
7333 /* Initialize the color table. */
7334 init_color_table ();
7336 /* Process the pixel raster. Origin is in the lower-left corner. */
7337 for (y
= 0; y
< height
; ++y
)
7339 uint32
*row
= buf
+ y
* width
;
7341 for (x
= 0; x
< width
; ++x
)
7343 uint32 abgr
= row
[x
];
7344 int r
= TIFFGetR (abgr
) << 8;
7345 int g
= TIFFGetG (abgr
) << 8;
7346 int b
= TIFFGetB (abgr
) << 8;
7347 XPutPixel (ximg
, x
, height
- 1 - y
, lookup_rgb_color (f
, r
, g
, b
));
7351 # ifdef COLOR_TABLE_SUPPORT
7352 /* Remember the colors allocated for the image. Free the color table. */
7353 img
->colors
= colors_in_color_table (&img
->ncolors
);
7354 free_color_table ();
7355 # endif /* COLOR_TABLE_SUPPORT */
7358 img
->height
= height
;
7360 /* Maybe fill in the background field while we have ximg handy. */
7361 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7362 /* Casting avoids a GCC warning on W32. */
7363 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7365 /* Put ximg into the image. */
7366 image_put_x_image (f
, img
, ximg
, 0);
7368 #endif /* ! USE_CAIRO */
7374 #elif defined HAVE_NS
7377 tiff_load (struct frame
*f
, struct image
*img
)
7379 return ns_load_image (f
, img
,
7380 image_spec_value (img
->spec
, QCfile
, NULL
),
7381 image_spec_value (img
->spec
, QCdata
, NULL
));
7388 /***********************************************************************
7390 ***********************************************************************/
7392 #if defined (HAVE_GIF) || defined (HAVE_NS)
7394 static bool gif_image_p (Lisp_Object object
);
7395 static bool gif_load (struct frame
*f
, struct image
*img
);
7396 static void gif_clear_image (struct frame
*f
, struct image
*img
);
7398 /* Indices of image specification fields in gif_format, below. */
7400 enum gif_keyword_index
7416 /* Vector of image_keyword structures describing the format
7417 of valid user-defined image specifications. */
7419 static const struct image_keyword gif_format
[GIF_LAST
] =
7421 {":type", IMAGE_SYMBOL_VALUE
, 1},
7422 {":data", IMAGE_STRING_VALUE
, 0},
7423 {":file", IMAGE_STRING_VALUE
, 0},
7424 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7425 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7426 {":relief", IMAGE_INTEGER_VALUE
, 0},
7427 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7428 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7429 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7430 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0},
7431 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
7434 #if defined HAVE_NTGUI && defined WINDOWSNT
7435 static bool init_gif_functions (void);
7437 #define init_gif_functions NULL
7440 /* Structure describing the image type `gif'. */
7442 static struct image_type gif_type
=
7444 SYMBOL_INDEX (Qgif
),
7452 /* Free X resources of GIF image IMG which is used on frame F. */
7455 gif_clear_image (struct frame
*f
, struct image
*img
)
7457 img
->lisp_data
= Qnil
;
7458 x_clear_image (f
, img
);
7461 /* Return true if OBJECT is a valid GIF image specification. */
7464 gif_image_p (Lisp_Object object
)
7466 struct image_keyword fmt
[GIF_LAST
];
7467 memcpy (fmt
, gif_format
, sizeof fmt
);
7469 if (!parse_image_spec (object
, fmt
, GIF_LAST
, Qgif
))
7472 /* Must specify either the :data or :file keyword. */
7473 return fmt
[GIF_FILE
].count
+ fmt
[GIF_DATA
].count
== 1;
7476 #endif /* HAVE_GIF */
7482 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7483 Undefine before redefining to avoid a preprocessor warning. */
7487 /* avoid conflict with QuickdrawText.h */
7488 # define DrawText gif_DrawText
7489 # include <gif_lib.h>
7490 /* The bogus ifdef below, which is always true, is to avoid a compiler
7491 warning about DrawText being unused. */
7496 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7497 # ifndef GIFLIB_MINOR
7498 # define GIFLIB_MINOR 0
7500 # ifndef GIFLIB_RELEASE
7501 # define GIFLIB_RELEASE 0
7504 # else /* HAVE_NTGUI */
7506 # include <gif_lib.h>
7508 # endif /* HAVE_NTGUI */
7510 /* Giflib before 5.0 didn't define these macros. */
7511 # ifndef GIFLIB_MAJOR
7512 # define GIFLIB_MAJOR 4
7515 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7516 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7517 earlier releases, where either it returns char * or GIFLIB_MINOR
7518 may be incorrect. */
7519 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7523 /* GIF library details. */
7524 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7525 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*, int *));
7527 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*));
7529 DEF_DLL_FN (int, DGifSlurp
, (GifFileType
*));
7530 # if GIFLIB_MAJOR < 5
7531 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
));
7532 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *));
7534 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
, int *));
7535 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *, int *));
7537 # if HAVE_GIFERRORSTRING
7538 DEF_DLL_FN (char const *, GifErrorString
, (int));
7542 init_gif_functions (void)
7546 if (!(library
= w32_delayed_load (Qgif
)))
7549 LOAD_DLL_FN (library
, DGifCloseFile
);
7550 LOAD_DLL_FN (library
, DGifSlurp
);
7551 LOAD_DLL_FN (library
, DGifOpen
);
7552 LOAD_DLL_FN (library
, DGifOpenFileName
);
7553 # if HAVE_GIFERRORSTRING
7554 LOAD_DLL_FN (library
, GifErrorString
);
7559 # undef DGifCloseFile
7561 # undef DGifOpenFileName
7563 # undef GifErrorString
7565 # define DGifCloseFile fn_DGifCloseFile
7566 # define DGifOpen fn_DGifOpen
7567 # define DGifOpenFileName fn_DGifOpenFileName
7568 # define DGifSlurp fn_DGifSlurp
7569 # define GifErrorString fn_GifErrorString
7571 # endif /* WINDOWSNT */
7573 /* Reading a GIF image from memory
7574 Based on the PNG memory stuff to a certain extent. */
7578 unsigned char *bytes
;
7584 /* Make the current memory source available to gif_read_from_memory.
7585 It's done this way because not all versions of libungif support
7586 a UserData field in the GifFileType structure. */
7587 static gif_memory_source
*current_gif_memory_src
;
7590 gif_read_from_memory (GifFileType
*file
, GifByteType
*buf
, int len
)
7592 gif_memory_source
*src
= current_gif_memory_src
;
7594 if (len
> src
->len
- src
->index
)
7597 memcpy (buf
, src
->bytes
+ src
->index
, len
);
7603 gif_close (GifFileType
*gif
, int *err
)
7607 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7608 retval
= DGifCloseFile (gif
, err
);
7610 retval
= DGifCloseFile (gif
);
7611 #if GIFLIB_MAJOR >= 5
7619 /* Load GIF image IMG for use on frame F. Value is true if
7622 static const int interlace_start
[] = {0, 4, 2, 1};
7623 static const int interlace_increment
[] = {8, 8, 4, 2};
7625 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7628 gif_load (struct frame
*f
, struct image
*img
)
7630 int rc
, width
, height
, x
, y
, i
, j
;
7631 ColorMapObject
*gif_color_map
;
7633 gif_memory_source memsrc
;
7634 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
7635 Lisp_Object specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7636 Lisp_Object specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7640 if (NILP (specified_data
))
7642 Lisp_Object file
= x_find_image_file (specified_file
);
7643 if (!STRINGP (file
))
7645 image_error ("Cannot find image file `%s'", specified_file
);
7649 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7651 encoded_file
= ansi_encode_filename (encoded_file
);
7654 /* Open the GIF file. */
7655 #if GIFLIB_MAJOR < 5
7656 gif
= DGifOpenFileName (SSDATA (encoded_file
));
7658 gif
= DGifOpenFileName (SSDATA (encoded_file
), &gif_err
);
7662 #if HAVE_GIFERRORSTRING
7663 image_error ("Cannot open `%s': %s",
7664 file
, build_string (GifErrorString (gif_err
)));
7666 image_error ("Cannot open `%s'", file
);
7673 if (!STRINGP (specified_data
))
7675 image_error ("Invalid image data `%s'", specified_data
);
7679 /* Read from memory! */
7680 current_gif_memory_src
= &memsrc
;
7681 memsrc
.bytes
= SDATA (specified_data
);
7682 memsrc
.len
= SBYTES (specified_data
);
7685 #if GIFLIB_MAJOR < 5
7686 gif
= DGifOpen (&memsrc
, gif_read_from_memory
);
7688 gif
= DGifOpen (&memsrc
, gif_read_from_memory
, &gif_err
);
7692 #if HAVE_GIFERRORSTRING
7693 image_error ("Cannot open memory source `%s': %s",
7694 img
->spec
, build_string (GifErrorString (gif_err
)));
7696 image_error ("Cannot open memory source `%s'", img
->spec
);
7702 /* Before reading entire contents, check the declared image size. */
7703 if (!check_image_size (f
, gif
->SWidth
, gif
->SHeight
))
7705 image_size_error ();
7706 gif_close (gif
, NULL
);
7710 /* Read entire contents. */
7711 rc
= DGifSlurp (gif
);
7712 if (rc
== GIF_ERROR
|| gif
->ImageCount
<= 0)
7714 image_error ("Error reading `%s'", img
->spec
);
7715 gif_close (gif
, NULL
);
7719 /* Which sub-image are we to display? */
7721 Lisp_Object image_number
= image_spec_value (img
->spec
, QCindex
, NULL
);
7722 idx
= INTEGERP (image_number
) ? XFASTINT (image_number
) : 0;
7723 if (idx
< 0 || idx
>= gif
->ImageCount
)
7725 image_error ("Invalid image number `%s' in image `%s'",
7726 image_number
, img
->spec
);
7727 gif_close (gif
, NULL
);
7732 width
= img
->width
= gif
->SWidth
;
7733 height
= img
->height
= gif
->SHeight
;
7735 img
->corners
[TOP_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Top
;
7736 img
->corners
[LEFT_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Left
;
7737 img
->corners
[BOT_CORNER
]
7738 = img
->corners
[TOP_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Height
;
7739 img
->corners
[RIGHT_CORNER
]
7740 = img
->corners
[LEFT_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Width
;
7742 if (!check_image_size (f
, width
, height
))
7744 image_size_error ();
7745 gif_close (gif
, NULL
);
7749 /* Check that the selected subimages fit. It's not clear whether
7750 the GIF spec requires this, but Emacs can crash if they don't fit. */
7751 for (j
= 0; j
<= idx
; ++j
)
7753 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7754 int subimg_width
= subimage
->ImageDesc
.Width
;
7755 int subimg_height
= subimage
->ImageDesc
.Height
;
7756 int subimg_top
= subimage
->ImageDesc
.Top
;
7757 int subimg_left
= subimage
->ImageDesc
.Left
;
7758 if (! (subimg_width
>= 0 && subimg_height
>= 0
7759 && 0 <= subimg_top
&& subimg_top
<= height
- subimg_height
7760 && 0 <= subimg_left
&& subimg_left
<= width
- subimg_width
))
7762 image_error ("Subimage does not fit in image");
7763 gif_close (gif
, NULL
);
7769 /* xzalloc so data is zero => transparent */
7770 void *data
= xzalloc (width
* height
* 4);
7771 uint32_t *data32
= data
;
7772 if (STRINGP (specified_bg
))
7775 if (x_defined_color (f
, SSDATA (specified_bg
), &color
, 0))
7777 uint32_t *dataptr
= data32
;
7778 int r
= color
.red
/256;
7779 int g
= color
.green
/256;
7780 int b
= color
.blue
/256;
7782 for (y
= 0; y
< height
; ++y
)
7783 for (x
= 0; x
< width
; ++x
)
7784 *dataptr
++ = (0xffu
<< 24) | (r
<< 16) | (g
<< 8) | b
;
7788 /* Create the X image and pixmap. */
7790 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
7792 gif_close (gif
, NULL
);
7796 /* Clear the part of the screen image not covered by the image.
7797 Full animated GIF support requires more here (see the gif89 spec,
7798 disposal methods). Let's simply assume that the part not covered
7799 by a sub-image is in the frame's background color. */
7800 for (y
= 0; y
< img
->corners
[TOP_CORNER
]; ++y
)
7801 for (x
= 0; x
< width
; ++x
)
7802 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7804 for (y
= img
->corners
[BOT_CORNER
]; y
< height
; ++y
)
7805 for (x
= 0; x
< width
; ++x
)
7806 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7808 for (y
= img
->corners
[TOP_CORNER
]; y
< img
->corners
[BOT_CORNER
]; ++y
)
7810 for (x
= 0; x
< img
->corners
[LEFT_CORNER
]; ++x
)
7811 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7812 for (x
= img
->corners
[RIGHT_CORNER
]; x
< width
; ++x
)
7813 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7817 /* Read the GIF image into the X image. */
7819 /* FIXME: With the current implementation, loading an animated gif
7820 is quadratic in the number of animation frames, since each frame
7821 is a separate struct image. We must provide a way for a single
7822 gif_load call to construct and save all animation frames. */
7824 init_color_table ();
7827 unsigned long bgcolor
;
7828 if (STRINGP (specified_bg
))
7829 bgcolor
= x_alloc_image_color (f
, img
, specified_bg
,
7830 FRAME_BACKGROUND_PIXEL (f
));
7833 for (j
= 0; j
<= idx
; ++j
)
7835 /* We use a local variable `raster' here because RasterBits is a
7836 char *, which invites problems with bytes >= 0x80. */
7837 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7838 unsigned char *raster
= (unsigned char *) subimage
->RasterBits
;
7839 int transparency_color_index
= -1;
7841 int subimg_width
= subimage
->ImageDesc
.Width
;
7842 int subimg_height
= subimage
->ImageDesc
.Height
;
7843 int subimg_top
= subimage
->ImageDesc
.Top
;
7844 int subimg_left
= subimage
->ImageDesc
.Left
;
7846 /* Find the Graphic Control Extension block for this sub-image.
7847 Extract the disposal method and transparency color. */
7848 for (i
= 0; i
< subimage
->ExtensionBlockCount
; i
++)
7850 ExtensionBlock
*extblock
= subimage
->ExtensionBlocks
+ i
;
7852 if ((extblock
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
)
7853 && extblock
->ByteCount
== 4
7854 && extblock
->Bytes
[0] & 1)
7856 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7857 to background". Treat any other value like 2. */
7858 disposal
= (extblock
->Bytes
[0] >> 2) & 7;
7859 transparency_color_index
= (unsigned char) extblock
->Bytes
[3];
7864 /* We can't "keep in place" the first subimage. */
7868 /* For disposal == 0, the spec says "No disposal specified. The
7869 decoder is not required to take any action." In practice, it
7870 seems we need to treat this like "keep in place", see e.g.
7871 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7875 gif_color_map
= subimage
->ImageDesc
.ColorMap
;
7877 gif_color_map
= gif
->SColorMap
;
7880 /* Allocate subimage colors. */
7881 unsigned long pixel_colors
[256] = { 0, };
7884 for (i
= 0; i
< gif_color_map
->ColorCount
; ++i
)
7886 if (transparency_color_index
== i
)
7887 pixel_colors
[i
] = STRINGP (specified_bg
)
7888 ? bgcolor
: FRAME_BACKGROUND_PIXEL (f
);
7891 int r
= gif_color_map
->Colors
[i
].Red
<< 8;
7892 int g
= gif_color_map
->Colors
[i
].Green
<< 8;
7893 int b
= gif_color_map
->Colors
[i
].Blue
<< 8;
7894 pixel_colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
7899 /* Apply the pixel values. */
7900 if (GIFLIB_MAJOR
< 5 && gif
->SavedImages
[j
].ImageDesc
.Interlace
)
7904 for (y
= 0, row
= interlace_start
[0], pass
= 0;
7906 y
++, row
+= interlace_increment
[pass
])
7908 while (subimg_height
<= row
)
7909 row
= interlace_start
[++pass
];
7911 for (x
= 0; x
< subimg_width
; x
++)
7913 int c
= raster
[y
* subimg_width
+ x
];
7914 if (transparency_color_index
!= c
|| disposal
!= 1)
7918 (data32
+ ((row
+ subimg_top
) * subimg_width
7919 + x
+ subimg_left
));
7920 int r
= gif_color_map
->Colors
[c
].Red
;
7921 int g
= gif_color_map
->Colors
[c
].Green
;
7922 int b
= gif_color_map
->Colors
[c
].Blue
;
7924 if (transparency_color_index
!= c
)
7925 *dataptr
= (0xffu
<< 24) | (r
<< 16) | (g
<< 8) | b
;
7927 XPutPixel (ximg
, x
+ subimg_left
, row
+ subimg_top
,
7936 for (y
= 0; y
< subimg_height
; ++y
)
7937 for (x
= 0; x
< subimg_width
; ++x
)
7939 int c
= raster
[y
* subimg_width
+ x
];
7940 if (transparency_color_index
!= c
|| disposal
!= 1)
7944 (data32
+ ((y
+ subimg_top
) * subimg_width
7945 + x
+ subimg_left
));
7946 int r
= gif_color_map
->Colors
[c
].Red
;
7947 int g
= gif_color_map
->Colors
[c
].Green
;
7948 int b
= gif_color_map
->Colors
[c
].Blue
;
7949 if (transparency_color_index
!= c
)
7950 *dataptr
= (0xffu
<< 24) | (r
<< 16) | (g
<< 8) | b
;
7952 XPutPixel (ximg
, x
+ subimg_left
, y
+ subimg_top
,
7960 #ifdef COLOR_TABLE_SUPPORT
7961 img
->colors
= colors_in_color_table (&img
->ncolors
);
7962 free_color_table ();
7963 #endif /* COLOR_TABLE_SUPPORT */
7965 /* Save GIF image extension data for `image-metadata'.
7966 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7967 img
->lisp_data
= Qnil
;
7968 if (gif
->SavedImages
[idx
].ExtensionBlockCount
> 0)
7971 ExtensionBlock
*ext
= gif
->SavedImages
[idx
].ExtensionBlocks
;
7972 for (i
= 0; i
< gif
->SavedImages
[idx
].ExtensionBlockCount
; i
++, ext
++)
7973 /* Append (... FUNCTION "BYTES") */
7976 = Fcons (make_number (ext
->Function
),
7977 Fcons (make_unibyte_string ((char *) ext
->Bytes
,
7980 if (ext
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
7981 && ext
->ByteCount
== 4)
7983 delay
= ext
->Bytes
[2] << CHAR_BIT
;
7984 delay
|= ext
->Bytes
[1];
7987 img
->lisp_data
= list2 (Qextension_data
, img
->lisp_data
);
7991 Fcons (make_float (delay
/ 100.0),
7995 if (gif
->ImageCount
> 1)
7996 img
->lisp_data
= Fcons (Qcount
,
7997 Fcons (make_number (gif
->ImageCount
),
8000 if (gif_close (gif
, &gif_err
) == GIF_ERROR
)
8002 #if HAVE_GIFERRORSTRING
8003 char const *error_text
= GifErrorString (gif_err
);
8006 image_error ("Error closing `%s': %s",
8007 img
->spec
, build_string (error_text
));
8009 image_error ("Error closing `%s'", img
->spec
);
8014 create_cairo_image_surface (img
, data
, width
, height
);
8016 /* Maybe fill in the background field while we have ximg handy. */
8017 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
8018 /* Casting avoids a GCC warning. */
8019 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
8021 /* Put ximg into the image. */
8022 image_put_x_image (f
, img
, ximg
, 0);
8028 #else /* !HAVE_GIF */
8032 gif_load (struct frame
*f
, struct image
*img
)
8034 return ns_load_image (f
, img
,
8035 image_spec_value (img
->spec
, QCfile
, NULL
),
8036 image_spec_value (img
->spec
, QCdata
, NULL
));
8038 #endif /* HAVE_NS */
8040 #endif /* HAVE_GIF */
8043 #ifdef HAVE_IMAGEMAGICK
8045 /***********************************************************************
8047 ***********************************************************************/
8049 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8050 safely rounded and clipped to int range. */
8053 scale_image_size (int size
, size_t divisor
, size_t multiplier
)
8058 double scaled
= s
* multiplier
/ divisor
+ 0.5;
8059 if (scaled
< INT_MAX
)
8065 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8066 Use SPEC to deduce the size. Store the desired size into
8067 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8069 compute_image_size (size_t width
, size_t height
,
8071 int *d_width
, int *d_height
)
8074 int desired_width
, desired_height
;
8077 value
= image_spec_value (spec
, QCscale
, NULL
);
8078 if (NUMBERP (value
))
8079 scale
= XFLOATINT (value
);
8081 /* If width and/or height is set in the display spec assume we want
8082 to scale to those values. If either h or w is unspecified, the
8083 unspecified should be calculated from the specified to preserve
8085 value
= image_spec_value (spec
, QCwidth
, NULL
);
8086 desired_width
= NATNUMP (value
) ?
8087 min (XFASTINT (value
) * scale
, INT_MAX
) : -1;
8088 value
= image_spec_value (spec
, QCheight
, NULL
);
8089 desired_height
= NATNUMP (value
) ?
8090 min (XFASTINT (value
) * scale
, INT_MAX
) : -1;
8092 width
= width
* scale
;
8093 height
= height
* scale
;
8095 if (desired_width
== -1)
8097 value
= image_spec_value (spec
, QCmax_width
, NULL
);
8098 if (NATNUMP (value
))
8100 int max_width
= min (XFASTINT (value
), INT_MAX
);
8101 if (max_width
< width
)
8103 /* The image is wider than :max-width. */
8104 desired_width
= max_width
;
8105 if (desired_height
== -1)
8107 desired_height
= scale_image_size (desired_width
,
8109 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8110 if (NATNUMP (value
))
8112 int max_height
= min (XFASTINT (value
), INT_MAX
);
8113 if (max_height
< desired_height
)
8115 desired_height
= max_height
;
8116 desired_width
= scale_image_size (desired_height
,
8125 if (desired_height
== -1)
8127 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8128 if (NATNUMP (value
))
8130 int max_height
= min (XFASTINT (value
), INT_MAX
);
8131 if (max_height
< height
)
8132 desired_height
= max_height
;
8136 if (desired_width
!= -1 && desired_height
== -1)
8137 /* w known, calculate h. */
8138 desired_height
= scale_image_size (desired_width
, width
, height
);
8140 if (desired_width
== -1 && desired_height
!= -1)
8141 /* h known, calculate w. */
8142 desired_width
= scale_image_size (desired_height
, height
, width
);
8144 /* We have no width/height settings, so just apply the scale. */
8145 if (desired_width
== -1 && desired_height
== -1)
8147 desired_width
= width
;
8148 desired_height
= height
;
8151 *d_width
= desired_width
;
8152 *d_height
= desired_height
;
8155 static bool imagemagick_image_p (Lisp_Object
);
8156 static bool imagemagick_load (struct frame
*, struct image
*);
8157 static void imagemagick_clear_image (struct frame
*, struct image
*);
8159 /* Indices of image specification fields in imagemagick_format. */
8161 enum imagemagick_keyword_index
8169 IMAGEMAGICK_ALGORITHM
,
8170 IMAGEMAGICK_HEURISTIC_MASK
,
8172 IMAGEMAGICK_BACKGROUND
,
8175 IMAGEMAGICK_MAX_HEIGHT
,
8176 IMAGEMAGICK_MAX_WIDTH
,
8178 IMAGEMAGICK_ROTATION
,
8183 /* Vector of image_keyword structures describing the format
8184 of valid user-defined image specifications. */
8186 static struct image_keyword imagemagick_format
[IMAGEMAGICK_LAST
] =
8188 {":type", IMAGE_SYMBOL_VALUE
, 1},
8189 {":data", IMAGE_STRING_VALUE
, 0},
8190 {":file", IMAGE_STRING_VALUE
, 0},
8191 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8192 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8193 {":relief", IMAGE_INTEGER_VALUE
, 0},
8194 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8195 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8196 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8197 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
8198 {":height", IMAGE_INTEGER_VALUE
, 0},
8199 {":width", IMAGE_INTEGER_VALUE
, 0},
8200 {":max-height", IMAGE_INTEGER_VALUE
, 0},
8201 {":max-width", IMAGE_INTEGER_VALUE
, 0},
8202 {":format", IMAGE_SYMBOL_VALUE
, 0},
8203 {":rotation", IMAGE_NUMBER_VALUE
, 0},
8204 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
8207 #if defined HAVE_NTGUI && defined WINDOWSNT
8208 static bool init_imagemagick_functions (void);
8210 #define init_imagemagick_functions NULL
8213 /* Structure describing the image type for any image handled via
8216 static struct image_type imagemagick_type
=
8218 SYMBOL_INDEX (Qimagemagick
),
8219 imagemagick_image_p
,
8221 imagemagick_clear_image
,
8222 init_imagemagick_functions
,
8226 /* Free X resources of imagemagick image IMG which is used on frame F. */
8229 imagemagick_clear_image (struct frame
*f
,
8232 x_clear_image (f
, img
);
8235 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8236 this by calling parse_image_spec and supplying the keywords that
8237 identify the IMAGEMAGICK format. */
8240 imagemagick_image_p (Lisp_Object object
)
8242 struct image_keyword fmt
[IMAGEMAGICK_LAST
];
8243 memcpy (fmt
, imagemagick_format
, sizeof fmt
);
8245 if (!parse_image_spec (object
, fmt
, IMAGEMAGICK_LAST
, Qimagemagick
))
8248 /* Must specify either the :data or :file keyword. */
8249 return fmt
[IMAGEMAGICK_FILE
].count
+ fmt
[IMAGEMAGICK_DATA
].count
== 1;
8252 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8253 Therefore rename the function so it doesn't collide with ImageMagick. */
8254 #define DrawRectangle DrawRectangleGif
8255 #include <wand/MagickWand.h>
8257 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8258 Emacs seems to work fine with the hidden version, so unhide it. */
8259 #include <magick/version.h>
8260 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8261 extern WandExport
void PixelGetMagickColor (const PixelWand
*,
8262 MagickPixelPacket
*);
8265 /* Log ImageMagick error message.
8266 Useful when a ImageMagick function returns the status `MagickFalse'. */
8269 imagemagick_error (MagickWand
*wand
)
8272 ExceptionType severity
;
8274 description
= MagickGetException (wand
, &severity
);
8275 image_error ("ImageMagick error: %s", build_string (description
));
8276 MagickRelinquishMemory (description
);
8279 /* Possibly give ImageMagick some extra help to determine the image
8280 type by supplying a "dummy" filename based on the Content-Type. */
8283 imagemagick_filename_hint (Lisp_Object spec
, char hint_buffer
[MaxTextExtent
])
8285 Lisp_Object symbol
= intern ("image-format-suffixes");
8286 Lisp_Object val
= find_symbol_value (symbol
);
8292 format
= image_spec_value (spec
, intern (":format"), NULL
);
8293 val
= Fcar_safe (Fcdr_safe (Fassq (format
, val
)));
8294 if (! STRINGP (val
))
8297 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8298 as ImageMagick would ignore the extra bytes anyway. */
8299 snprintf (hint_buffer
, MaxTextExtent
, "/tmp/foo.%s", SSDATA (val
));
8303 /* Animated images (e.g., GIF89a) are composed from one "master image"
8304 (which is the first one, and then there's a number of images that
8305 follow. If following images have non-transparent colors, these are
8306 composed "on top" of the master image. So, in general, one has to
8307 compute ann the preceding images to be able to display a particular
8310 Computing all the preceding images is too slow, so we maintain a
8311 cache of previously computed images. We have to maintain a cache
8312 separate from the image cache, because the images may be scaled
8315 struct animation_cache
8319 struct timespec update_time
;
8320 struct animation_cache
*next
;
8321 char signature
[FLEXIBLE_ARRAY_MEMBER
];
8324 static struct animation_cache
*animation_cache
= NULL
;
8326 static struct animation_cache
*
8327 imagemagick_create_cache (char *signature
)
8329 struct animation_cache
*cache
8330 = xmalloc (FLEXSIZEOF (struct animation_cache
, signature
,
8331 strlen (signature
) + 1));
8335 strcpy (cache
->signature
, signature
);
8339 /* Discard cached images that haven't been used for a minute. */
8341 imagemagick_prune_animation_cache (void)
8343 struct animation_cache
**pcache
= &animation_cache
;
8344 struct timespec old
= timespec_sub (current_timespec (),
8345 make_timespec (60, 0));
8349 struct animation_cache
*cache
= *pcache
;
8350 if (timespec_cmp (old
, cache
->update_time
) <= 0)
8351 pcache
= &cache
->next
;
8355 DestroyMagickWand (cache
->wand
);
8356 *pcache
= cache
->next
;
8362 static struct animation_cache
*
8363 imagemagick_get_animation_cache (MagickWand
*wand
)
8365 char *signature
= MagickGetImageSignature (wand
);
8366 struct animation_cache
*cache
;
8367 struct animation_cache
**pcache
= &animation_cache
;
8369 imagemagick_prune_animation_cache ();
8376 *pcache
= cache
= imagemagick_create_cache (signature
);
8379 if (strcmp (signature
, cache
->signature
) == 0)
8381 pcache
= &cache
->next
;
8384 DestroyString (signature
);
8385 cache
->update_time
= current_timespec ();
8390 imagemagick_compute_animated_image (MagickWand
*super_wand
, int ino
)
8393 MagickWand
*composite_wand
;
8394 size_t dest_width
, dest_height
;
8395 struct animation_cache
*cache
= imagemagick_get_animation_cache (super_wand
);
8397 MagickSetIteratorIndex (super_wand
, 0);
8399 if (ino
== 0 || cache
->wand
== NULL
|| cache
->index
> ino
)
8401 composite_wand
= MagickGetImage (super_wand
);
8403 DestroyMagickWand (cache
->wand
);
8406 composite_wand
= cache
->wand
;
8408 dest_height
= MagickGetImageHeight (composite_wand
);
8410 for (i
= max (1, cache
->index
+ 1); i
<= ino
; i
++)
8412 MagickWand
*sub_wand
;
8413 PixelIterator
*source_iterator
, *dest_iterator
;
8414 PixelWand
**source
, **dest
;
8415 size_t source_width
, source_height
;
8416 ssize_t source_left
, source_top
;
8417 MagickPixelPacket pixel
;
8418 DisposeType dispose
;
8419 ptrdiff_t lines
= 0;
8421 MagickSetIteratorIndex (super_wand
, i
);
8422 sub_wand
= MagickGetImage (super_wand
);
8424 MagickGetImagePage (sub_wand
, &source_width
, &source_height
,
8425 &source_left
, &source_top
);
8427 /* This flag says how to handle transparent pixels. */
8428 dispose
= MagickGetImageDispose (sub_wand
);
8430 source_iterator
= NewPixelIterator (sub_wand
);
8431 if (! source_iterator
)
8433 DestroyMagickWand (composite_wand
);
8434 DestroyMagickWand (sub_wand
);
8436 image_error ("Imagemagick pixel iterator creation failed");
8440 dest_iterator
= NewPixelIterator (composite_wand
);
8441 if (! dest_iterator
)
8443 DestroyMagickWand (composite_wand
);
8444 DestroyMagickWand (sub_wand
);
8445 DestroyPixelIterator (source_iterator
);
8447 image_error ("Imagemagick pixel iterator creation failed");
8451 /* The sub-image may not start at origin, so move the destination
8452 iterator to where the sub-image should start. */
8455 PixelSetIteratorRow (dest_iterator
, source_top
);
8459 while ((source
= PixelGetNextIteratorRow (source_iterator
, &source_width
))
8464 /* Sanity check. This shouldn't happen, but apparently
8465 does in some pictures. */
8466 if (++lines
>= dest_height
)
8469 dest
= PixelGetNextIteratorRow (dest_iterator
, &dest_width
);
8470 for (x
= 0; x
< source_width
; x
++)
8472 /* Sanity check. This shouldn't happen, but apparently
8473 also does in some pictures. */
8474 if (x
+ source_left
>= dest_width
)
8476 /* Normally we only copy over non-transparent pixels,
8477 but if the disposal method is "Background", then we
8478 copy over all pixels. */
8479 if (dispose
== BackgroundDispose
|| PixelGetAlpha (source
[x
]))
8481 PixelGetMagickColor (source
[x
], &pixel
);
8482 PixelSetMagickColor (dest
[x
+ source_left
], &pixel
);
8485 PixelSyncIterator (dest_iterator
);
8488 DestroyPixelIterator (source_iterator
);
8489 DestroyPixelIterator (dest_iterator
);
8490 DestroyMagickWand (sub_wand
);
8493 /* Cache a copy for the next iteration. The current wand will be
8494 destroyed by the caller. */
8495 cache
->wand
= CloneMagickWand (composite_wand
);
8498 return composite_wand
;
8502 /* Helper function for imagemagick_load, which does the actual loading
8503 given contents and size, apart from frame and image structures,
8504 passed from imagemagick_load. Uses librimagemagick to do most of
8505 the image processing.
8507 F is a pointer to the Emacs frame; IMG to the image structure to
8508 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8509 be parsed; SIZE is the number of bytes of data; and FILENAME is
8510 either the file name or the image data.
8512 Return true if successful. */
8515 imagemagick_load_image (struct frame
*f
, struct image
*img
,
8516 unsigned char *contents
, unsigned int size
,
8520 size_t image_width
, image_height
;
8521 MagickBooleanType status
;
8524 MagickWand
*image_wand
;
8525 PixelIterator
*iterator
;
8526 PixelWand
**pixels
, *bg_wand
= NULL
;
8527 MagickPixelPacket pixel
;
8532 int desired_width
, desired_height
;
8534 char hint_buffer
[MaxTextExtent
];
8535 char *filename_hint
= NULL
;
8537 /* Handle image index for image types who can contain more than one image.
8538 Interface :index is same as for GIF. First we "ping" the image to see how
8539 many sub-images it contains. Pinging is faster than loading the image to
8540 find out things about it. */
8542 /* Initialize the imagemagick environment. */
8543 MagickWandGenesis ();
8544 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
8545 ino
= INTEGERP (image
) ? XFASTINT (image
) : 0;
8546 image_wand
= NewMagickWand ();
8549 status
= MagickReadImage (image_wand
, filename
);
8552 Lisp_Object lwidth
= image_spec_value (img
->spec
, QCwidth
, NULL
);
8553 Lisp_Object lheight
= image_spec_value (img
->spec
, QCheight
, NULL
);
8555 if (NATNUMP (lwidth
) && NATNUMP (lheight
))
8557 MagickSetSize (image_wand
, XFASTINT (lwidth
), XFASTINT (lheight
));
8558 MagickSetDepth (image_wand
, 8);
8560 filename_hint
= imagemagick_filename_hint (img
->spec
, hint_buffer
);
8561 MagickSetFilename (image_wand
, filename_hint
);
8562 status
= MagickReadImageBlob (image_wand
, contents
, size
);
8565 if (status
== MagickFalse
)
8567 imagemagick_error (image_wand
);
8568 DestroyMagickWand (image_wand
);
8572 #ifdef HAVE_MAGICKAUTOORIENTIMAGE
8573 /* If no :rotation is explicitly specified, apply the automatic
8574 rotation from EXIF. */
8575 if (NILP (image_spec_value (img
->spec
, QCrotation
, NULL
)))
8576 if (MagickAutoOrientImage (image_wand
) == MagickFalse
)
8578 image_error ("Error applying automatic orientation in image `%s'", img
->spec
);
8579 DestroyMagickWand (image_wand
);
8584 if (ino
< 0 || ino
>= MagickGetNumberImages (image_wand
))
8586 image_error ("Invalid image number `%s' in image `%s'", image
, img
->spec
);
8587 DestroyMagickWand (image_wand
);
8591 if (MagickGetImageDelay (image_wand
) > 0)
8594 Fcons (make_float (MagickGetImageDelay (image_wand
) / 100.0),
8597 if (MagickGetNumberImages (image_wand
) > 1)
8600 Fcons (make_number (MagickGetNumberImages (image_wand
)),
8603 /* If we have an animated image, get the new wand based on the
8605 if (MagickGetNumberImages (image_wand
) > 1)
8607 MagickWand
*super_wand
= image_wand
;
8608 image_wand
= imagemagick_compute_animated_image (super_wand
, ino
);
8610 image_wand
= super_wand
;
8612 DestroyMagickWand (super_wand
);
8615 /* Retrieve the frame's background color, for use later. */
8618 Lisp_Object specified_bg
;
8620 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8621 if (!STRINGP (specified_bg
)
8622 || !x_defined_color (f
, SSDATA (specified_bg
), &bgcolor
, 0))
8623 x_query_frame_background_color (f
, &bgcolor
);
8625 bg_wand
= NewPixelWand ();
8626 PixelSetRed (bg_wand
, (double) bgcolor
.red
/ 65535);
8627 PixelSetGreen (bg_wand
, (double) bgcolor
.green
/ 65535);
8628 PixelSetBlue (bg_wand
, (double) bgcolor
.blue
/ 65535);
8631 compute_image_size (MagickGetImageWidth (image_wand
),
8632 MagickGetImageHeight (image_wand
),
8633 img
->spec
, &desired_width
, &desired_height
);
8635 if (desired_width
!= -1 && desired_height
!= -1)
8637 status
= MagickScaleImage (image_wand
, desired_width
, desired_height
);
8638 if (status
== MagickFalse
)
8640 image_error ("Imagemagick scale failed");
8641 imagemagick_error (image_wand
);
8642 goto imagemagick_error
;
8646 /* crop behaves similar to image slicing in Emacs but is more memory
8648 crop
= image_spec_value (img
->spec
, QCcrop
, NULL
);
8650 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8652 /* After some testing, it seems MagickCropImage is the fastest crop
8653 function in ImageMagick. This crop function seems to do less copying
8654 than the alternatives, but it still reads the entire image into memory
8655 before cropping, which is apparently difficult to avoid when using
8657 size_t crop_width
= XINT (XCAR (crop
));
8659 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8661 size_t crop_height
= XINT (XCAR (crop
));
8663 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8665 ssize_t crop_x
= XINT (XCAR (crop
));
8667 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8669 ssize_t crop_y
= XINT (XCAR (crop
));
8670 MagickCropImage (image_wand
, crop_width
, crop_height
,
8677 /* Furthermore :rotation. we need background color and angle for
8680 TODO background handling for rotation specified_bg =
8681 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8683 value
= image_spec_value (img
->spec
, QCrotation
, NULL
);
8686 rotation
= XFLOAT_DATA (value
);
8687 status
= MagickRotateImage (image_wand
, bg_wand
, rotation
);
8688 if (status
== MagickFalse
)
8690 image_error ("Imagemagick image rotate failed");
8691 imagemagick_error (image_wand
);
8692 goto imagemagick_error
;
8696 /* Set the canvas background color to the frame or specified
8697 background, and flatten the image. Note: as of ImageMagick
8698 6.6.0, SVG image transparency is not handled properly
8699 (e.g. etc/images/splash.svg shows a white background always). */
8701 MagickWand
*new_wand
;
8702 MagickSetImageBackgroundColor (image_wand
, bg_wand
);
8703 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8704 new_wand
= MagickMergeImageLayers (image_wand
, MergeLayer
);
8706 new_wand
= MagickFlattenImages (image_wand
);
8708 DestroyMagickWand (image_wand
);
8709 image_wand
= new_wand
;
8712 /* Finally we are done manipulating the image. Figure out the
8713 resulting width/height and transfer ownership to Emacs. */
8714 image_height
= MagickGetImageHeight (image_wand
);
8715 image_width
= MagickGetImageWidth (image_wand
);
8717 if (! (image_width
<= INT_MAX
&& image_height
<= INT_MAX
8718 && check_image_size (f
, image_width
, image_height
)))
8720 image_size_error ();
8721 goto imagemagick_error
;
8724 width
= image_width
;
8725 height
= image_height
;
8727 /* We can now get a valid pixel buffer from the imagemagick file, if all
8730 init_color_table ();
8732 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8733 if (imagemagick_render_type
!= 0)
8735 /* Magicexportimage is normally faster than pixelpushing. This
8736 method is also well tested. Some aspects of this method are
8737 ad-hoc and needs to be more researched. */
8738 int imagedepth
= 24; /*MagickGetImageDepth(image_wand);*/
8739 const char *exportdepth
= imagedepth
<= 8 ? "I" : "BGRP"; /*"RGBP";*/
8740 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8741 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, imagedepth
,
8744 #ifdef COLOR_TABLE_SUPPORT
8745 free_color_table ();
8747 image_error ("Imagemagick X bitmap allocation failure");
8748 goto imagemagick_error
;
8751 /* Oddly, the below code doesn't seem to work:*/
8752 /* switch(ximg->bitmap_unit){ */
8754 /* pixelwidth=CharPixel; */
8757 /* pixelwidth=ShortPixel; */
8760 /* pixelwidth=LongPixel; */
8764 Here im just guessing the format of the bitmap.
8765 happens to work fine for:
8768 seems about 3 times as fast as pixel pushing(not carefully measured)
8770 int pixelwidth
= CharPixel
; /*??? TODO figure out*/
8771 MagickExportImagePixels (image_wand
, 0, 0, width
, height
,
8772 exportdepth
, pixelwidth
, ximg
->data
);
8775 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8777 size_t image_height
;
8778 MagickRealType color_scale
= 65535.0 / QuantumRange
;
8780 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8781 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
8784 #ifdef COLOR_TABLE_SUPPORT
8785 free_color_table ();
8787 image_error ("Imagemagick X bitmap allocation failure");
8788 goto imagemagick_error
;
8791 /* Copy imagemagick image to x with primitive yet robust pixel
8792 pusher loop. This has been tested a lot with many different
8795 /* Copy pixels from the imagemagick image structure to the x image map. */
8796 iterator
= NewPixelIterator (image_wand
);
8799 #ifdef COLOR_TABLE_SUPPORT
8800 free_color_table ();
8802 x_destroy_x_image (ximg
);
8803 image_error ("Imagemagick pixel iterator creation failed");
8804 goto imagemagick_error
;
8807 image_height
= MagickGetImageHeight (image_wand
);
8808 for (y
= 0; y
< image_height
; y
++)
8811 pixels
= PixelGetNextIteratorRow (iterator
, &row_width
);
8814 int xlim
= min (row_width
, width
);
8815 for (x
= 0; x
< xlim
; x
++)
8817 PixelGetMagickColor (pixels
[x
], &pixel
);
8818 XPutPixel (ximg
, x
, y
,
8819 lookup_rgb_color (f
,
8820 color_scale
* pixel
.red
,
8821 color_scale
* pixel
.green
,
8822 color_scale
* pixel
.blue
));
8825 DestroyPixelIterator (iterator
);
8828 #ifdef COLOR_TABLE_SUPPORT
8829 /* Remember colors allocated for this image. */
8830 img
->colors
= colors_in_color_table (&img
->ncolors
);
8831 free_color_table ();
8832 #endif /* COLOR_TABLE_SUPPORT */
8835 img
->height
= height
;
8837 /* Put ximg into the image. */
8838 image_put_x_image (f
, img
, ximg
, 0);
8840 /* Final cleanup. image_wand should be the only resource left. */
8841 DestroyMagickWand (image_wand
);
8842 if (bg_wand
) DestroyPixelWand (bg_wand
);
8844 /* `MagickWandTerminus' terminates the imagemagick environment. */
8845 MagickWandTerminus ();
8850 DestroyMagickWand (image_wand
);
8851 if (bg_wand
) DestroyPixelWand (bg_wand
);
8853 MagickWandTerminus ();
8854 /* TODO more cleanup. */
8855 image_error ("Error parsing IMAGEMAGICK image `%s'", img
->spec
);
8860 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8861 successful. this function will go into the imagemagick_type structure, and
8862 the prototype thus needs to be compatible with that structure. */
8865 imagemagick_load (struct frame
*f
, struct image
*img
)
8868 Lisp_Object file_name
;
8870 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8871 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8872 if (STRINGP (file_name
))
8874 Lisp_Object file
= x_find_image_file (file_name
);
8875 if (!STRINGP (file
))
8877 image_error ("Cannot find image file `%s'", file_name
);
8880 file
= ENCODE_FILE (file
);
8882 file
= ansi_encode_filename (file
);
8884 success_p
= imagemagick_load_image (f
, img
, 0, 0, SSDATA (file
));
8886 /* Else its not a file, its a lisp object. Load the image from a
8887 lisp object rather than a file. */
8892 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8893 if (!STRINGP (data
))
8895 image_error ("Invalid image data `%s'", data
);
8898 success_p
= imagemagick_load_image (f
, img
, SDATA (data
),
8899 SBYTES (data
), NULL
);
8905 DEFUN ("imagemagick-types", Fimagemagick_types
, Simagemagick_types
, 0, 0, 0,
8906 doc
: /* Return a list of image types supported by ImageMagick.
8907 Each entry in this list is a symbol named after an ImageMagick format
8908 tag. See the ImageMagick manual for a list of ImageMagick formats and
8909 their descriptions (http://www.imagemagick.org/script/formats.php).
8910 You can also try the shell command: `identify -list format'.
8912 Note that ImageMagick recognizes many file-types that Emacs does not
8913 recognize as images, such as C. See `imagemagick-types-enable'
8914 and `imagemagick-types-inhibit'. */)
8917 Lisp_Object typelist
= Qnil
;
8923 ex
= AcquireExceptionInfo ();
8924 imtypes
= GetMagickList ("*", &numf
, ex
);
8925 DestroyExceptionInfo (ex
);
8927 for (i
= 0; i
< numf
; i
++)
8929 Lisp_Object imagemagicktype
= intern (imtypes
[i
]);
8930 typelist
= Fcons (imagemagicktype
, typelist
);
8931 imtypes
[i
] = MagickRelinquishMemory (imtypes
[i
]);
8934 MagickRelinquishMemory (imtypes
);
8935 return Fnreverse (typelist
);
8938 #endif /* defined (HAVE_IMAGEMAGICK) */
8942 /***********************************************************************
8944 ***********************************************************************/
8948 /* Function prototypes. */
8950 static bool svg_image_p (Lisp_Object object
);
8951 static bool svg_load (struct frame
*f
, struct image
*img
);
8953 static bool svg_load_image (struct frame
*, struct image
*,
8954 char *, ptrdiff_t, char *);
8956 /* Indices of image specification fields in svg_format, below. */
8958 enum svg_keyword_index
8973 /* Vector of image_keyword structures describing the format
8974 of valid user-defined image specifications. */
8976 static const struct image_keyword svg_format
[SVG_LAST
] =
8978 {":type", IMAGE_SYMBOL_VALUE
, 1},
8979 {":data", IMAGE_STRING_VALUE
, 0},
8980 {":file", IMAGE_STRING_VALUE
, 0},
8981 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8982 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8983 {":relief", IMAGE_INTEGER_VALUE
, 0},
8984 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8985 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8986 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8987 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8990 # if defined HAVE_NTGUI && defined WINDOWSNT
8991 static bool init_svg_functions (void);
8993 #define init_svg_functions NULL
8996 /* Structure describing the image type `svg'. Its the same type of
8997 structure defined for all image formats, handled by emacs image
8998 functions. See struct image_type in dispextern.h. */
9000 static struct image_type svg_type
=
9002 SYMBOL_INDEX (Qsvg
),
9011 /* Return true if OBJECT is a valid SVG image specification. Do
9012 this by calling parse_image_spec and supplying the keywords that
9013 identify the SVG format. */
9016 svg_image_p (Lisp_Object object
)
9018 struct image_keyword fmt
[SVG_LAST
];
9019 memcpy (fmt
, svg_format
, sizeof fmt
);
9021 if (!parse_image_spec (object
, fmt
, SVG_LAST
, Qsvg
))
9024 /* Must specify either the :data or :file keyword. */
9025 return fmt
[SVG_FILE
].count
+ fmt
[SVG_DATA
].count
== 1;
9028 /* Some versions of glib's gatomic.h define MemoryBarrier, but MinGW
9029 w32api 3.18 and later has its own definition. The following gross
9030 hack avoids the clash. */
9032 # if (__W32API_MAJOR_VERSION + (__W32API_MINOR_VERSION >= 18)) >= 4
9033 # define W32_SAVE_MINGW_VERSION __MINGW_MAJOR_VERSION
9034 # undef __MINGW_MAJOR_VERSION
9035 # define __MINGW_MAJOR_VERSION 4
9039 # include <librsvg/rsvg.h>
9043 /* Restore the original definition of __MINGW_MAJOR_VERSION. */
9044 # ifdef W32_SAVE_MINGW_VERSION
9045 # undef __MINGW_MAJOR_VERSION
9046 # define __MINGW_MAJOR_VERSION W32_SAVE_MINGW_VERSION
9047 # ifdef __MINGW_MAJOR_VERSION
9048 # undef W32_SAVE_MINGW_VERSION
9052 /* SVG library functions. */
9053 DEF_DLL_FN (RsvgHandle
*, rsvg_handle_new
, (void));
9054 DEF_DLL_FN (void, rsvg_handle_get_dimensions
,
9055 (RsvgHandle
*, RsvgDimensionData
*));
9056 DEF_DLL_FN (gboolean
, rsvg_handle_write
,
9057 (RsvgHandle
*, const guchar
*, gsize
, GError
**));
9058 DEF_DLL_FN (gboolean
, rsvg_handle_close
, (RsvgHandle
*, GError
**));
9059 DEF_DLL_FN (GdkPixbuf
*, rsvg_handle_get_pixbuf
, (RsvgHandle
*));
9060 DEF_DLL_FN (void, rsvg_handle_set_base_uri
, (RsvgHandle
*, const char *));
9062 DEF_DLL_FN (int, gdk_pixbuf_get_width
, (const GdkPixbuf
*));
9063 DEF_DLL_FN (int, gdk_pixbuf_get_height
, (const GdkPixbuf
*));
9064 DEF_DLL_FN (guchar
*, gdk_pixbuf_get_pixels
, (const GdkPixbuf
*));
9065 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride
, (const GdkPixbuf
*));
9066 DEF_DLL_FN (GdkColorspace
, gdk_pixbuf_get_colorspace
, (const GdkPixbuf
*));
9067 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels
, (const GdkPixbuf
*));
9068 DEF_DLL_FN (gboolean
, gdk_pixbuf_get_has_alpha
, (const GdkPixbuf
*));
9069 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample
, (const GdkPixbuf
*));
9071 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9072 DEF_DLL_FN (void, g_type_init
, (void));
9074 DEF_DLL_FN (void, g_object_unref
, (gpointer
));
9075 DEF_DLL_FN (void, g_clear_error
, (GError
**));
9078 init_svg_functions (void)
9080 HMODULE library
, gdklib
= NULL
, glib
= NULL
, gobject
= NULL
;
9082 if (!(glib
= w32_delayed_load (Qglib
))
9083 || !(gobject
= w32_delayed_load (Qgobject
))
9084 || !(gdklib
= w32_delayed_load (Qgdk_pixbuf
))
9085 || !(library
= w32_delayed_load (Qsvg
)))
9087 if (gdklib
) FreeLibrary (gdklib
);
9088 if (gobject
) FreeLibrary (gobject
);
9089 if (glib
) FreeLibrary (glib
);
9093 LOAD_DLL_FN (library
, rsvg_handle_new
);
9094 LOAD_DLL_FN (library
, rsvg_handle_get_dimensions
);
9095 LOAD_DLL_FN (library
, rsvg_handle_write
);
9096 LOAD_DLL_FN (library
, rsvg_handle_close
);
9097 LOAD_DLL_FN (library
, rsvg_handle_get_pixbuf
);
9098 LOAD_DLL_FN (library
, rsvg_handle_set_base_uri
);
9100 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_width
);
9101 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_height
);
9102 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_pixels
);
9103 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_rowstride
);
9104 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_colorspace
);
9105 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_n_channels
);
9106 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_has_alpha
);
9107 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_bits_per_sample
);
9109 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9110 LOAD_DLL_FN (gobject
, g_type_init
);
9112 LOAD_DLL_FN (gobject
, g_object_unref
);
9113 LOAD_DLL_FN (glib
, g_clear_error
);
9118 /* The following aliases for library functions allow dynamic loading
9119 to be used on some platforms. */
9121 # undef gdk_pixbuf_get_bits_per_sample
9122 # undef gdk_pixbuf_get_colorspace
9123 # undef gdk_pixbuf_get_has_alpha
9124 # undef gdk_pixbuf_get_height
9125 # undef gdk_pixbuf_get_n_channels
9126 # undef gdk_pixbuf_get_pixels
9127 # undef gdk_pixbuf_get_rowstride
9128 # undef gdk_pixbuf_get_width
9129 # undef g_clear_error
9130 # undef g_object_unref
9132 # undef rsvg_handle_close
9133 # undef rsvg_handle_get_dimensions
9134 # undef rsvg_handle_get_pixbuf
9135 # undef rsvg_handle_new
9136 # undef rsvg_handle_set_base_uri
9137 # undef rsvg_handle_write
9139 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9140 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9141 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9142 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9143 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9144 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9145 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9146 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9147 # define g_clear_error fn_g_clear_error
9148 # define g_object_unref fn_g_object_unref
9149 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9150 # define g_type_init fn_g_type_init
9152 # define rsvg_handle_close fn_rsvg_handle_close
9153 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9154 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9155 # define rsvg_handle_new fn_rsvg_handle_new
9156 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9157 # define rsvg_handle_write fn_rsvg_handle_write
9159 # endif /* !WINDOWSNT */
9161 /* Load SVG image IMG for use on frame F. Value is true if
9165 svg_load (struct frame
*f
, struct image
*img
)
9168 Lisp_Object file_name
;
9170 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9171 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
9172 if (STRINGP (file_name
))
9175 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
9176 if (!STRINGP (file
))
9178 image_error ("Cannot find image file `%s'", file_name
);
9182 /* Read the entire file into memory. */
9184 char *contents
= slurp_file (fd
, &size
);
9185 if (contents
== NULL
)
9187 image_error ("Error loading SVG image `%s'", file
);
9190 /* If the file was slurped into memory properly, parse it. */
9191 success_p
= svg_load_image (f
, img
, contents
, size
,
9192 SSDATA (ENCODE_FILE (file
)));
9195 /* Else its not a file, its a lisp object. Load the image from a
9196 lisp object rather than a file. */
9199 Lisp_Object data
, original_filename
;
9201 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
9202 if (!STRINGP (data
))
9204 image_error ("Invalid image data `%s'", data
);
9207 original_filename
= BVAR (current_buffer
, filename
);
9208 success_p
= svg_load_image (f
, img
, SSDATA (data
), SBYTES (data
),
9209 (NILP (original_filename
) ? NULL
9210 : SSDATA (original_filename
)));
9216 /* Load frame F and image IMG. CONTENTS contains the SVG XML data to
9217 be parsed, SIZE is its size, and FILENAME is the name of the SVG
9220 Use librsvg to do most of the image processing.
9222 Return true when successful. */
9224 svg_load_image (struct frame
*f
, struct image
*img
, char *contents
,
9225 ptrdiff_t size
, char *filename
)
9227 RsvgHandle
*rsvg_handle
;
9228 RsvgDimensionData dimension_data
;
9233 const guint8
*pixels
;
9236 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9237 /* g_type_init is a glib function that must be called prior to
9238 using gnome type library functions (obsolete since 2.36.0). */
9242 /* Make a handle to a new rsvg object. */
9243 rsvg_handle
= rsvg_handle_new ();
9245 /* Set base_uri for properly handling referenced images (via 'href').
9246 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9247 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9249 rsvg_handle_set_base_uri(rsvg_handle
, filename
);
9251 /* Parse the contents argument and fill in the rsvg_handle. */
9252 rsvg_handle_write (rsvg_handle
, (unsigned char *) contents
, size
, &err
);
9253 if (err
) goto rsvg_error
;
9255 /* The parsing is complete, rsvg_handle is ready to used, close it
9256 for further writes. */
9257 rsvg_handle_close (rsvg_handle
, &err
);
9258 if (err
) goto rsvg_error
;
9260 rsvg_handle_get_dimensions (rsvg_handle
, &dimension_data
);
9261 if (! check_image_size (f
, dimension_data
.width
, dimension_data
.height
))
9263 image_size_error ();
9267 /* We can now get a valid pixel buffer from the svg file, if all
9269 pixbuf
= rsvg_handle_get_pixbuf (rsvg_handle
);
9270 if (!pixbuf
) goto rsvg_error
;
9271 g_object_unref (rsvg_handle
);
9273 /* Extract some meta data from the svg handle. */
9274 width
= gdk_pixbuf_get_width (pixbuf
);
9275 height
= gdk_pixbuf_get_height (pixbuf
);
9276 pixels
= gdk_pixbuf_get_pixels (pixbuf
);
9277 rowstride
= gdk_pixbuf_get_rowstride (pixbuf
);
9279 /* Validate the svg meta data. */
9280 eassert (gdk_pixbuf_get_colorspace (pixbuf
) == GDK_COLORSPACE_RGB
);
9281 eassert (gdk_pixbuf_get_n_channels (pixbuf
) == 4);
9282 eassert (gdk_pixbuf_get_has_alpha (pixbuf
));
9283 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf
) == 8);
9287 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
9288 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
9290 for (int y
= 0; y
< height
; ++y
)
9292 const guchar
*iconptr
= pixels
+ y
* rowstride
;
9293 uint32_t *dataptr
= (uint32_t *) (data
+ y
* rowstride
);
9295 for (int x
= 0; x
< width
; ++x
)
9297 if (iconptr
[3] == 0)
9300 *dataptr
= (iconptr
[0] << 16)
9303 | (iconptr
[3] << 24);
9310 create_cairo_image_surface (img
, data
, width
, height
);
9311 g_object_unref (pixbuf
);
9313 /* Try to create a x pixmap to hold the svg pixmap. */
9315 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
9317 g_object_unref (pixbuf
);
9321 init_color_table ();
9323 /* Handle alpha channel by combining the image with a background
9326 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
9327 if (!STRINGP (specified_bg
)
9328 || !x_defined_color (f
, SSDATA (specified_bg
), &background
, 0))
9329 x_query_frame_background_color (f
, &background
);
9331 /* SVG pixmaps specify transparency in the last byte, so right
9332 shift 8 bits to get rid of it, since emacs doesn't support
9334 background
.red
>>= 8;
9335 background
.green
>>= 8;
9336 background
.blue
>>= 8;
9338 /* This loop handles opacity values, since Emacs assumes
9339 non-transparent images. Each pixel must be "flattened" by
9340 calculating the resulting color, given the transparency of the
9341 pixel, and the image background color. */
9342 for (int y
= 0; y
< height
; ++y
)
9344 for (int x
= 0; x
< width
; ++x
)
9346 int red
= *pixels
++;
9347 int green
= *pixels
++;
9348 int blue
= *pixels
++;
9349 int opacity
= *pixels
++;
9351 red
= ((red
* opacity
)
9352 + (background
.red
* ((1 << 8) - opacity
)));
9353 green
= ((green
* opacity
)
9354 + (background
.green
* ((1 << 8) - opacity
)));
9355 blue
= ((blue
* opacity
)
9356 + (background
.blue
* ((1 << 8) - opacity
)));
9358 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, red
, green
, blue
));
9361 pixels
+= rowstride
- 4 * width
;
9364 #ifdef COLOR_TABLE_SUPPORT
9365 /* Remember colors allocated for this image. */
9366 img
->colors
= colors_in_color_table (&img
->ncolors
);
9367 free_color_table ();
9368 #endif /* COLOR_TABLE_SUPPORT */
9370 g_object_unref (pixbuf
);
9373 img
->height
= height
;
9375 /* Maybe fill in the background field while we have ximg handy.
9376 Casting avoids a GCC warning. */
9377 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
9379 /* Put ximg into the image. */
9380 image_put_x_image (f
, img
, ximg
, 0);
9381 #endif /* ! USE_CAIRO */
9387 g_object_unref (rsvg_handle
);
9388 /* FIXME: Use error->message so the user knows what is the actual
9389 problem with the image. */
9390 image_error ("Error parsing SVG image `%s'", img
->spec
);
9391 g_clear_error (&err
);
9395 #endif /* defined (HAVE_RSVG) */
9400 /***********************************************************************
9402 ***********************************************************************/
9404 #ifdef HAVE_X_WINDOWS
9405 #define HAVE_GHOSTSCRIPT 1
9406 #endif /* HAVE_X_WINDOWS */
9408 #ifdef HAVE_GHOSTSCRIPT
9410 static bool gs_image_p (Lisp_Object object
);
9411 static bool gs_load (struct frame
*f
, struct image
*img
);
9412 static void gs_clear_image (struct frame
*f
, struct image
*img
);
9414 /* Indices of image specification fields in gs_format, below. */
9416 enum gs_keyword_index
9434 /* Vector of image_keyword structures describing the format
9435 of valid user-defined image specifications. */
9437 static const struct image_keyword gs_format
[GS_LAST
] =
9439 {":type", IMAGE_SYMBOL_VALUE
, 1},
9440 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9441 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9442 {":file", IMAGE_STRING_VALUE
, 1},
9443 {":loader", IMAGE_FUNCTION_VALUE
, 0},
9444 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE
, 1},
9445 {":ascent", IMAGE_ASCENT_VALUE
, 0},
9446 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
9447 {":relief", IMAGE_INTEGER_VALUE
, 0},
9448 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9449 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9450 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9451 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
9454 /* Structure describing the image type `ghostscript'. */
9456 static struct image_type gs_type
=
9458 SYMBOL_INDEX (Qpostscript
),
9467 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9470 gs_clear_image (struct frame
*f
, struct image
*img
)
9472 x_clear_image (f
, img
);
9476 /* Return true if OBJECT is a valid Ghostscript image
9480 gs_image_p (Lisp_Object object
)
9482 struct image_keyword fmt
[GS_LAST
];
9486 memcpy (fmt
, gs_format
, sizeof fmt
);
9488 if (!parse_image_spec (object
, fmt
, GS_LAST
, Qpostscript
))
9491 /* Bounding box must be a list or vector containing 4 integers. */
9492 tem
= fmt
[GS_BOUNDING_BOX
].value
;
9495 for (i
= 0; i
< 4; ++i
, tem
= XCDR (tem
))
9496 if (!CONSP (tem
) || !INTEGERP (XCAR (tem
)))
9501 else if (VECTORP (tem
))
9503 if (ASIZE (tem
) != 4)
9505 for (i
= 0; i
< 4; ++i
)
9506 if (!INTEGERP (AREF (tem
, i
)))
9516 /* Load Ghostscript image IMG for use on frame F. Value is true
9520 gs_load (struct frame
*f
, struct image
*img
)
9522 uprintmax_t printnum1
, printnum2
;
9523 char buffer
[sizeof " " + INT_STRLEN_BOUND (printmax_t
)];
9524 Lisp_Object window_and_pixmap_id
= Qnil
, loader
, pt_height
, pt_width
;
9526 double in_width
, in_height
;
9527 Lisp_Object pixel_colors
= Qnil
;
9529 /* Compute pixel size of pixmap needed from the given size in the
9530 image specification. Sizes in the specification are in pt. 1 pt
9531 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9533 pt_width
= image_spec_value (img
->spec
, QCpt_width
, NULL
);
9534 in_width
= INTEGERP (pt_width
) ? XFASTINT (pt_width
) / 72.0 : 0;
9535 in_width
*= FRAME_RES_X (f
);
9536 pt_height
= image_spec_value (img
->spec
, QCpt_height
, NULL
);
9537 in_height
= INTEGERP (pt_height
) ? XFASTINT (pt_height
) / 72.0 : 0;
9538 in_height
*= FRAME_RES_Y (f
);
9540 if (! (in_width
<= INT_MAX
&& in_height
<= INT_MAX
9541 && check_image_size (f
, in_width
, in_height
)))
9543 image_size_error ();
9546 img
->width
= in_width
;
9547 img
->height
= in_height
;
9549 /* Create the pixmap. */
9550 eassert (img
->pixmap
== NO_PIXMAP
);
9552 if (x_check_image_size (0, img
->width
, img
->height
))
9554 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9556 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_DRAWABLE (f
),
9557 img
->width
, img
->height
,
9558 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)));
9564 image_error ("Unable to create pixmap for `%s'" , img
->spec
);
9568 /* Call the loader to fill the pixmap. It returns a process object
9569 if successful. We do not record_unwind_protect here because
9570 other places in redisplay like calling window scroll functions
9571 don't either. Let the Lisp loader use `unwind-protect' instead. */
9572 printnum1
= FRAME_X_DRAWABLE (f
);
9573 printnum2
= img
->pixmap
;
9574 window_and_pixmap_id
9575 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9577 printnum1
= FRAME_FOREGROUND_PIXEL (f
);
9578 printnum2
= FRAME_BACKGROUND_PIXEL (f
);
9580 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9582 XSETFRAME (frame
, f
);
9583 loader
= image_spec_value (img
->spec
, QCloader
, NULL
);
9585 loader
= intern ("gs-load-image");
9587 img
->lisp_data
= call6 (loader
, frame
, img
->spec
,
9588 make_number (img
->width
),
9589 make_number (img
->height
),
9590 window_and_pixmap_id
,
9592 return PROCESSP (img
->lisp_data
);
9596 /* Kill the Ghostscript process that was started to fill PIXMAP on
9597 frame F. Called from XTread_socket when receiving an event
9598 telling Emacs that Ghostscript has finished drawing. */
9601 x_kill_gs_process (Pixmap pixmap
, struct frame
*f
)
9603 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
9607 /* Find the image containing PIXMAP. */
9608 for (i
= 0; i
< c
->used
; ++i
)
9609 if (c
->images
[i
]->pixmap
== pixmap
)
9612 /* Should someone in between have cleared the image cache, for
9613 instance, give up. */
9617 /* Kill the GS process. We should have found PIXMAP in the image
9618 cache and its image should contain a process object. */
9620 eassert (PROCESSP (img
->lisp_data
));
9621 Fkill_process (img
->lisp_data
, Qnil
);
9622 img
->lisp_data
= Qnil
;
9624 #if defined (HAVE_X_WINDOWS)
9626 /* On displays with a mutable colormap, figure out the colors
9627 allocated for the image by looking at the pixels of an XImage for
9629 if (x_mutable_colormap (FRAME_X_VISUAL (f
)))
9635 /* Try to get an XImage for img->pixmep. */
9636 ximg
= XGetImage (FRAME_X_DISPLAY (f
), img
->pixmap
,
9637 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
9640 /* Initialize the color table. */
9641 init_color_table ();
9643 /* For each pixel of the image, look its color up in the
9644 color table. After having done so, the color table will
9645 contain an entry for each color used by the image. */
9646 #ifdef COLOR_TABLE_SUPPORT
9647 for (int y
= 0; y
< img
->height
; ++y
)
9648 for (int x
= 0; x
< img
->width
; ++x
)
9650 unsigned long pixel
= XGetPixel (ximg
, x
, y
);
9652 lookup_pixel_color (f
, pixel
);
9655 /* Record colors in the image. Free color table and XImage. */
9656 img
->colors
= colors_in_color_table (&img
->ncolors
);
9657 free_color_table ();
9659 XDestroyImage (ximg
);
9661 #if 0 /* This doesn't seem to be the case. If we free the colors
9662 here, we get a BadAccess later in x_clear_image when
9663 freeing the colors. */
9664 /* We have allocated colors once, but Ghostscript has also
9665 allocated colors on behalf of us. So, to get the
9666 reference counts right, free them once. */
9668 x_free_colors (f
, img
->colors
, img
->ncolors
);
9672 image_error ("Cannot get X image of `%s'; colors will not be freed",
9677 #endif /* HAVE_X_WINDOWS */
9679 /* Now that we have the pixmap, compute mask and transform the
9680 image if requested. */
9682 postprocess_image (f
, img
);
9686 #endif /* HAVE_GHOSTSCRIPT */
9689 /***********************************************************************
9691 ***********************************************************************/
9695 DEFUN ("imagep", Fimagep
, Simagep
, 1, 1, 0,
9696 doc
: /* Value is non-nil if SPEC is a valid image specification. */)
9699 return valid_image_p (spec
) ? Qt
: Qnil
;
9703 DEFUN ("lookup-image", Flookup_image
, Slookup_image
, 1, 1, 0,
9709 if (valid_image_p (spec
))
9710 id
= lookup_image (SELECTED_FRAME (), spec
);
9713 return make_number (id
);
9716 #endif /* GLYPH_DEBUG */
9719 /***********************************************************************
9721 ***********************************************************************/
9723 DEFUN ("init-image-library", Finit_image_library
, Sinit_image_library
, 1, 1, 0,
9724 doc
: /* Initialize image library implementing image type TYPE.
9725 Return non-nil if TYPE is a supported image type.
9727 If image libraries are loaded dynamically (currently only the case on
9728 MS-Windows), load the library for TYPE if it is not yet loaded, using
9729 the library file(s) specified by `dynamic-library-alist'. */)
9732 return lookup_image_type (type
) ? Qt
: Qnil
;
9735 /* Look up image type TYPE, and return a pointer to its image_type
9736 structure. Return 0 if TYPE is not a known image type. */
9738 static struct image_type
*
9739 lookup_image_type (Lisp_Object type
)
9741 /* Types pbm and xbm are built-in and always available. */
9742 if (EQ (type
, Qpbm
))
9743 return define_image_type (&pbm_type
);
9745 if (EQ (type
, Qxbm
))
9746 return define_image_type (&xbm_type
);
9748 #if defined (HAVE_XPM) || defined (HAVE_NS)
9749 if (EQ (type
, Qxpm
))
9750 return define_image_type (&xpm_type
);
9753 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9754 if (EQ (type
, Qjpeg
))
9755 return define_image_type (&jpeg_type
);
9758 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9759 if (EQ (type
, Qtiff
))
9760 return define_image_type (&tiff_type
);
9763 #if defined (HAVE_GIF) || defined (HAVE_NS)
9764 if (EQ (type
, Qgif
))
9765 return define_image_type (&gif_type
);
9768 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9769 if (EQ (type
, Qpng
))
9770 return define_image_type (&png_type
);
9773 #if defined (HAVE_RSVG)
9774 if (EQ (type
, Qsvg
))
9775 return define_image_type (&svg_type
);
9778 #if defined (HAVE_IMAGEMAGICK)
9779 if (EQ (type
, Qimagemagick
))
9780 return define_image_type (&imagemagick_type
);
9783 #ifdef HAVE_GHOSTSCRIPT
9784 if (EQ (type
, Qpostscript
))
9785 return define_image_type (&gs_type
);
9791 #if !defined CANNOT_DUMP && defined HAVE_WINDOW_SYSTEM
9793 /* Reset image_types before dumping.
9794 Called from Fdump_emacs. */
9797 reset_image_types (void)
9801 struct image_type
*next
= image_types
->next
;
9802 xfree (image_types
);
9809 syms_of_image (void)
9811 /* Initialize this only once; it will be reset before dumping. */
9814 /* Must be defined now because we're going to update it below, while
9815 defining the supported image types. */
9816 DEFVAR_LISP ("image-types", Vimage_types
,
9817 doc
: /* List of potentially supported image types.
9818 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9819 To check whether it is really supported, use `image-type-available-p'. */);
9820 Vimage_types
= Qnil
;
9822 DEFVAR_LISP ("max-image-size", Vmax_image_size
,
9823 doc
: /* Maximum size of images.
9824 Emacs will not load an image into memory if its pixel width or
9825 pixel height exceeds this limit.
9827 If the value is an integer, it directly specifies the maximum
9828 image height and width, measured in pixels. If it is a floating
9829 point number, it specifies the maximum image height and width
9830 as a ratio to the frame height and width. If the value is
9831 non-numeric, there is no explicit limit on the size of images. */);
9832 Vmax_image_size
= make_float (MAX_IMAGE_SIZE
);
9834 /* Other symbols. */
9835 DEFSYM (Qcount
, "count");
9836 DEFSYM (Qextension_data
, "extension-data");
9837 DEFSYM (Qdelay
, "delay");
9840 DEFSYM (QCascent
, ":ascent");
9841 DEFSYM (QCmargin
, ":margin");
9842 DEFSYM (QCrelief
, ":relief");
9843 DEFSYM (QCconversion
, ":conversion");
9844 DEFSYM (QCcolor_symbols
, ":color-symbols");
9845 DEFSYM (QCheuristic_mask
, ":heuristic-mask");
9846 DEFSYM (QCindex
, ":index");
9847 DEFSYM (QCcrop
, ":crop");
9848 DEFSYM (QCrotation
, ":rotation");
9849 DEFSYM (QCmatrix
, ":matrix");
9850 DEFSYM (QCscale
, ":scale");
9851 DEFSYM (QCcolor_adjustment
, ":color-adjustment");
9852 DEFSYM (QCmask
, ":mask");
9854 /* Other symbols. */
9855 DEFSYM (Qlaplace
, "laplace");
9856 DEFSYM (Qemboss
, "emboss");
9857 DEFSYM (Qedge_detection
, "edge-detection");
9858 DEFSYM (Qheuristic
, "heuristic");
9860 DEFSYM (Qpostscript
, "postscript");
9861 DEFSYM (QCmax_width
, ":max-width");
9862 DEFSYM (QCmax_height
, ":max-height");
9863 #ifdef HAVE_GHOSTSCRIPT
9864 ADD_IMAGE_TYPE (Qpostscript
);
9865 DEFSYM (QCloader
, ":loader");
9866 DEFSYM (QCpt_width
, ":pt-width");
9867 DEFSYM (QCpt_height
, ":pt-height");
9868 #endif /* HAVE_GHOSTSCRIPT */
9871 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9872 or -1 if no PNG/GIF support was compiled in. This is tested by
9873 w32-win.el to correctly set up the alist used to search for the
9874 respective image libraries. */
9875 DEFSYM (Qlibpng_version
, "libpng-version");
9876 Fset (Qlibpng_version
,
9878 make_number (PNG_LIBPNG_VER
)
9883 DEFSYM (Qlibgif_version
, "libgif-version");
9884 Fset (Qlibgif_version
,
9886 make_number (GIFLIB_MAJOR
* 10000
9887 + GIFLIB_MINOR
* 100
9893 DEFSYM (Qlibjpeg_version
, "libjpeg-version");
9894 Fset (Qlibjpeg_version
,
9896 make_number (JPEG_LIB_VERSION
)
9903 DEFSYM (Qpbm
, "pbm");
9904 ADD_IMAGE_TYPE (Qpbm
);
9906 DEFSYM (Qxbm
, "xbm");
9907 ADD_IMAGE_TYPE (Qxbm
);
9909 #if defined (HAVE_XPM) || defined (HAVE_NS)
9910 DEFSYM (Qxpm
, "xpm");
9911 ADD_IMAGE_TYPE (Qxpm
);
9914 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9915 DEFSYM (Qjpeg
, "jpeg");
9916 ADD_IMAGE_TYPE (Qjpeg
);
9919 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9920 DEFSYM (Qtiff
, "tiff");
9921 ADD_IMAGE_TYPE (Qtiff
);
9924 #if defined (HAVE_GIF) || defined (HAVE_NS)
9925 DEFSYM (Qgif
, "gif");
9926 ADD_IMAGE_TYPE (Qgif
);
9929 #if defined (HAVE_PNG) || defined (HAVE_NS)
9930 DEFSYM (Qpng
, "png");
9931 ADD_IMAGE_TYPE (Qpng
);
9934 #if defined (HAVE_IMAGEMAGICK)
9935 DEFSYM (Qimagemagick
, "imagemagick");
9936 ADD_IMAGE_TYPE (Qimagemagick
);
9939 #if defined (HAVE_RSVG)
9940 DEFSYM (Qsvg
, "svg");
9941 ADD_IMAGE_TYPE (Qsvg
);
9943 /* Other libraries used directly by svg code. */
9944 DEFSYM (Qgdk_pixbuf
, "gdk-pixbuf");
9945 DEFSYM (Qglib
, "glib");
9946 DEFSYM (Qgobject
, "gobject");
9947 #endif /* HAVE_NTGUI */
9948 #endif /* HAVE_RSVG */
9950 defsubr (&Sinit_image_library
);
9951 #ifdef HAVE_IMAGEMAGICK
9952 defsubr (&Simagemagick_types
);
9954 defsubr (&Sclear_image_cache
);
9955 defsubr (&Simage_flush
);
9956 defsubr (&Simage_size
);
9957 defsubr (&Simage_mask_p
);
9958 defsubr (&Simage_metadata
);
9962 defsubr (&Slookup_image
);
9965 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images
,
9966 doc
: /* Non-nil means always draw a cross over disabled images.
9967 Disabled images are those having a `:conversion disabled' property.
9968 A cross is always drawn on black & white displays. */);
9969 cross_disabled_images
= 0;
9971 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path
,
9972 doc
: /* List of directories to search for window system bitmap files. */);
9973 Vx_bitmap_file_path
= decode_env_path (0, PATH_BITMAPS
, 0);
9975 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay
,
9976 doc
: /* Maximum time after which images are removed from the cache.
9977 When an image has not been displayed this many seconds, Emacs
9978 automatically removes it from the image cache. If the cache contains
9979 a large number of images, the actual eviction time may be shorter.
9980 The value can also be nil, meaning the cache is never cleared.
9982 The function `clear-image-cache' disregards this variable. */);
9983 Vimage_cache_eviction_delay
= make_number (300);
9984 #ifdef HAVE_IMAGEMAGICK
9985 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type
,
9986 doc
: /* Integer indicating which ImageMagick rendering method to use.
9988 0 -- the default method (pixel pushing)
9989 1 -- a newer method ("MagickExportImagePixels") that may perform
9990 better (speed etc) in some cases, but has not been as thoroughly
9991 tested with Emacs as the default method. This method requires
9992 ImageMagick version 6.4.6 (approximately) or later.
9994 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9995 imagemagick_render_type
= 0;