1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
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
39 #include "dispextern.h"
40 #include "blockinput.h"
44 #include "termhooks.h"
47 #ifdef HAVE_SYS_STAT_H
49 #endif /* HAVE_SYS_STAT_H */
51 #ifdef HAVE_SYS_TYPES_H
52 #include <sys/types.h>
53 #endif /* HAVE_SYS_TYPES_H */
55 #ifdef HAVE_WINDOW_SYSTEM
57 #endif /* HAVE_WINDOW_SYSTEM */
60 typedef struct x_bitmap_record Bitmap_Record
;
61 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
62 #define NO_PIXMAP None
64 #define PIX_MASK_RETAIN 0
65 #define PIX_MASK_DRAW 1
66 #endif /* HAVE_X_WINDOWS */
70 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
75 typedef struct w32_bitmap_record Bitmap_Record
;
76 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
79 #define PIX_MASK_RETAIN 0
80 #define PIX_MASK_DRAW 1
82 #define x_defined_color w32_defined_color
83 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
85 #endif /* HAVE_NTGUI */
88 typedef struct ns_bitmap_record Bitmap_Record
;
90 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
93 #define PIX_MASK_RETAIN 0
94 #define PIX_MASK_DRAW 1
96 #define x_defined_color(f, name, color_def, alloc) \
97 ns_defined_color (f, name, color_def, alloc, 0)
98 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
101 #if (defined HAVE_X_WINDOWS \
102 && ! (defined HAVE_NTGUI || defined USE_CAIRO || defined HAVE_NS))
103 /* W32_TODO : Color tables on W32. */
104 # define COLOR_TABLE_SUPPORT 1
107 static void x_disable_image (struct frame
*, struct image
*);
108 static void x_edge_detection (struct frame
*, struct image
*, Lisp_Object
,
111 static void init_color_table (void);
112 static unsigned long lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
);
113 #ifdef COLOR_TABLE_SUPPORT
114 static void free_color_table (void);
115 static unsigned long *colors_in_color_table (int *n
);
118 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
119 id, which is just an int that this section returns. Bitmaps are
120 reference counted so they can be shared among frames.
122 Bitmap indices are guaranteed to be > 0, so a negative number can
123 be used to indicate no bitmap.
125 If you use x_create_bitmap_from_data, then you must keep track of
126 the bitmaps yourself. That is, creating a bitmap from the same
127 data more than once will not be caught. */
130 /* Use with images created by ns_image_for_XPM. */
132 XGetPixel (XImagePtr ximage
, int x
, int y
)
134 return ns_get_pixel (ximage
, x
, y
);
137 /* Use with images created by ns_image_for_XPM; alpha set to 1;
138 pixel is assumed to be in RGB form. */
140 XPutPixel (XImagePtr ximage
, int x
, int y
, unsigned long pixel
)
142 ns_put_pixel (ximage
, x
, y
, pixel
);
147 /* Functions to access the contents of a bitmap, given an id. */
149 #ifdef HAVE_X_WINDOWS
151 x_bitmap_height (struct frame
*f
, ptrdiff_t id
)
153 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].height
;
157 x_bitmap_width (struct frame
*f
, ptrdiff_t id
)
159 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].width
;
163 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
165 x_bitmap_pixmap (struct frame
*f
, ptrdiff_t id
)
167 /* HAVE_NTGUI needs the explicit cast here. */
168 return (ptrdiff_t) FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].pixmap
;
172 #ifdef HAVE_X_WINDOWS
174 x_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
176 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].mask
;
180 /* Allocate a new bitmap record. Returns index of new record. */
183 x_allocate_bitmap_record (struct frame
*f
)
185 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
188 if (dpyinfo
->bitmaps_last
< dpyinfo
->bitmaps_size
)
189 return ++dpyinfo
->bitmaps_last
;
191 for (i
= 0; i
< dpyinfo
->bitmaps_size
; ++i
)
192 if (dpyinfo
->bitmaps
[i
].refcount
== 0)
196 xpalloc (dpyinfo
->bitmaps
, &dpyinfo
->bitmaps_size
,
197 10, -1, sizeof *dpyinfo
->bitmaps
);
198 return ++dpyinfo
->bitmaps_last
;
201 /* Add one reference to the reference count of the bitmap with id ID. */
204 x_reference_bitmap (struct frame
*f
, ptrdiff_t id
)
206 ++FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].refcount
;
209 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
212 x_create_bitmap_from_data (struct frame
*f
, char *bits
, unsigned int width
, unsigned int height
)
214 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
217 #ifdef HAVE_X_WINDOWS
219 bitmap
= XCreateBitmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
220 bits
, width
, height
);
223 #endif /* HAVE_X_WINDOWS */
227 bitmap
= CreateBitmap (width
, height
,
228 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_planes
,
229 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_cbits
,
233 #endif /* HAVE_NTGUI */
236 void *bitmap
= ns_image_from_XBM (bits
, width
, height
, 0, 0);
241 id
= x_allocate_bitmap_record (f
);
244 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
245 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
248 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
249 dpyinfo
->bitmaps
[id
- 1].height
= height
;
250 dpyinfo
->bitmaps
[id
- 1].width
= width
;
251 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
253 #ifdef HAVE_X_WINDOWS
254 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
255 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
256 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
257 #endif /* HAVE_X_WINDOWS */
260 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
261 dpyinfo
->bitmaps
[id
- 1].hinst
= NULL
;
262 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
263 #endif /* HAVE_NTGUI */
268 /* Create bitmap from file FILE for frame F. */
271 x_create_bitmap_from_file (struct frame
*f
, Lisp_Object file
)
274 return -1; /* W32_TODO : bitmap support */
275 #endif /* HAVE_NTGUI */
277 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
281 void *bitmap
= ns_image_from_file (file
);
287 id
= x_allocate_bitmap_record (f
);
288 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
289 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
290 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
291 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
292 dpyinfo
->bitmaps
[id
- 1].height
= ns_image_width (bitmap
);
293 dpyinfo
->bitmaps
[id
- 1].width
= ns_image_height (bitmap
);
297 #ifdef HAVE_X_WINDOWS
298 unsigned int width
, height
;
300 int xhot
, yhot
, result
;
305 /* Look for an existing bitmap with the same name. */
306 for (id
= 0; id
< dpyinfo
->bitmaps_last
; ++id
)
308 if (dpyinfo
->bitmaps
[id
].refcount
309 && dpyinfo
->bitmaps
[id
].file
310 && !strcmp (dpyinfo
->bitmaps
[id
].file
, SSDATA (file
)))
312 ++dpyinfo
->bitmaps
[id
].refcount
;
317 /* Search bitmap-file-path for the file, if appropriate. */
318 if (openp (Vx_bitmap_file_path
, file
, Qnil
, &found
,
319 make_number (R_OK
), false)
323 filename
= SSDATA (found
);
325 result
= XReadBitmapFile (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
326 filename
, &width
, &height
, &bitmap
, &xhot
, &yhot
);
327 if (result
!= BitmapSuccess
)
330 id
= x_allocate_bitmap_record (f
);
331 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
332 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
333 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
334 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
335 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
336 dpyinfo
->bitmaps
[id
- 1].height
= height
;
337 dpyinfo
->bitmaps
[id
- 1].width
= width
;
340 #endif /* HAVE_X_WINDOWS */
346 free_bitmap_record (Display_Info
*dpyinfo
, Bitmap_Record
*bm
)
348 #ifdef HAVE_X_WINDOWS
349 XFreePixmap (dpyinfo
->display
, bm
->pixmap
);
351 XFreePixmap (dpyinfo
->display
, bm
->mask
);
352 #endif /* HAVE_X_WINDOWS */
355 DeleteObject (bm
->pixmap
);
356 #endif /* HAVE_NTGUI */
359 ns_release_object (bm
->img
);
369 /* Remove reference to bitmap with id number ID. */
372 x_destroy_bitmap (struct frame
*f
, ptrdiff_t id
)
374 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
378 Bitmap_Record
*bm
= &dpyinfo
->bitmaps
[id
- 1];
380 if (--bm
->refcount
== 0)
383 free_bitmap_record (dpyinfo
, bm
);
389 /* Free all the bitmaps for the display specified by DPYINFO. */
392 x_destroy_all_bitmaps (Display_Info
*dpyinfo
)
395 Bitmap_Record
*bm
= dpyinfo
->bitmaps
;
397 for (i
= 0; i
< dpyinfo
->bitmaps_last
; i
++, bm
++)
398 if (bm
->refcount
> 0)
399 free_bitmap_record (dpyinfo
, bm
);
401 dpyinfo
->bitmaps_last
= 0;
404 static bool x_create_x_image_and_pixmap (struct frame
*, int, int, int,
405 XImagePtr
*, Pixmap
*);
406 static void x_destroy_x_image (XImagePtr ximg
);
409 static XImagePtr_or_DC
image_get_x_image_or_dc (struct frame
*, struct image
*,
411 static void image_unget_x_image_or_dc (struct image
*, bool, XImagePtr_or_DC
,
414 static XImagePtr
image_get_x_image (struct frame
*, struct image
*, bool);
415 static void image_unget_x_image (struct image
*, bool, XImagePtr
);
416 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
417 image_get_x_image (f, img, mask_p)
418 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
419 image_unget_x_image (img, mask_p, ximg)
422 #ifdef HAVE_X_WINDOWS
424 static void image_sync_to_pixmaps (struct frame
*, struct image
*);
426 /* Useful functions defined in the section
427 `Image type independent image structures' below. */
429 static unsigned long four_corners_best (XImagePtr ximg
,
432 unsigned long height
);
435 /* Create a mask of a bitmap. Note is this not a perfect mask.
436 It's nicer with some borders in this context */
439 x_create_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
442 XImagePtr ximg
, mask_img
;
443 unsigned long width
, height
;
446 unsigned long x
, y
, xp
, xm
, yp
, ym
;
449 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
454 pixmap
= x_bitmap_pixmap (f
, id
);
455 width
= x_bitmap_width (f
, id
);
456 height
= x_bitmap_height (f
, id
);
459 ximg
= XGetImage (FRAME_X_DISPLAY (f
), pixmap
, 0, 0, width
, height
,
468 result
= x_create_x_image_and_pixmap (f
, width
, height
, 1, &mask_img
, &mask
);
473 XDestroyImage (ximg
);
477 bg
= four_corners_best (ximg
, NULL
, width
, height
);
479 for (y
= 0; y
< ximg
->height
; ++y
)
481 for (x
= 0; x
< ximg
->width
; ++x
)
483 xp
= x
!= ximg
->width
- 1 ? x
+ 1 : 0;
484 xm
= x
!= 0 ? x
- 1 : ximg
->width
- 1;
485 yp
= y
!= ximg
->height
- 1 ? y
+ 1 : 0;
486 ym
= y
!= 0 ? y
- 1 : ximg
->height
- 1;
487 if (XGetPixel (ximg
, x
, y
) == bg
488 && XGetPixel (ximg
, x
, yp
) == bg
489 && XGetPixel (ximg
, x
, ym
) == bg
490 && XGetPixel (ximg
, xp
, y
) == bg
491 && XGetPixel (ximg
, xp
, yp
) == bg
492 && XGetPixel (ximg
, xp
, ym
) == bg
493 && XGetPixel (ximg
, xm
, y
) == bg
494 && XGetPixel (ximg
, xm
, yp
) == bg
495 && XGetPixel (ximg
, xm
, ym
) == bg
)
496 XPutPixel (mask_img
, x
, y
, 0);
498 XPutPixel (mask_img
, x
, y
, 1);
502 eassert (input_blocked_p ());
503 gc
= XCreateGC (FRAME_X_DISPLAY (f
), mask
, 0, NULL
);
504 XPutImage (FRAME_X_DISPLAY (f
), mask
, gc
, mask_img
, 0, 0, 0, 0,
506 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
508 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
509 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
511 XDestroyImage (ximg
);
512 x_destroy_x_image (mask_img
);
515 #endif /* HAVE_X_WINDOWS */
517 /***********************************************************************
519 ***********************************************************************/
521 /* List of supported image types. Use define_image_type to add new
522 types. Use lookup_image_type to find a type for a given symbol. */
524 static struct image_type
*image_types
;
526 /* Forward function prototypes. */
528 static struct image_type
*lookup_image_type (Lisp_Object
);
529 static void x_laplace (struct frame
*, struct image
*);
530 static void x_emboss (struct frame
*, struct image
*);
531 static void x_build_heuristic_mask (struct frame
*, struct image
*,
534 #define CACHE_IMAGE_TYPE(type, status) \
535 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
537 #define CACHE_IMAGE_TYPE(type, status)
540 #define ADD_IMAGE_TYPE(type) \
541 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
543 /* Define a new image type from TYPE. This adds a copy of TYPE to
544 image_types and caches the loading status of TYPE. */
546 static struct image_type
*
547 define_image_type (struct image_type
*type
)
549 struct image_type
*p
= NULL
;
550 int new_type
= type
->type
;
551 bool type_valid
= true;
555 for (p
= image_types
; p
; p
= p
->next
)
556 if (p
->type
== new_type
)
561 #if defined HAVE_NTGUI && defined WINDOWSNT
562 /* If we failed to load the library before, don't try again. */
563 Lisp_Object tested
= Fassq (builtin_lisp_symbol (new_type
),
565 if (CONSP (tested
) && NILP (XCDR (tested
)))
570 type_valid
= type
->init ();
571 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type
),
572 type_valid
? Qt
: Qnil
);
578 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
579 The initialized data segment is read-only. */
580 p
= xmalloc (sizeof *p
);
582 p
->next
= image_types
;
592 /* Value is true if OBJECT is a valid Lisp image specification. A
593 valid image specification is a list whose car is the symbol
594 `image', and whose rest is a property list. The property list must
595 contain a value for key `:type'. That value must be the name of a
596 supported image type. The rest of the property list depends on the
600 valid_image_p (Lisp_Object object
)
608 for (tem
= XCDR (object
); CONSP (tem
); tem
= XCDR (tem
))
609 if (EQ (XCAR (tem
), QCtype
))
612 if (CONSP (tem
) && SYMBOLP (XCAR (tem
)))
614 struct image_type
*type
;
615 type
= lookup_image_type (XCAR (tem
));
617 valid_p
= type
->valid_p (object
);
628 /* Log error message with format string FORMAT and trailing arguments.
629 Signaling an error, e.g. when an image cannot be loaded, is not a
630 good idea because this would interrupt redisplay, and the error
631 message display would lead to another redisplay. This function
632 therefore simply displays a message. */
635 image_error (const char *format
, ...)
638 va_start (ap
, format
);
639 vadd_to_log (format
, ap
);
644 image_size_error (void)
646 image_error ("Invalid image size (see `max-image-size')");
650 /***********************************************************************
652 ***********************************************************************/
654 enum image_value_type
656 IMAGE_DONT_CHECK_VALUE_TYPE
,
658 IMAGE_STRING_OR_NIL_VALUE
,
660 IMAGE_POSITIVE_INTEGER_VALUE
,
661 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
,
662 IMAGE_NON_NEGATIVE_INTEGER_VALUE
,
665 IMAGE_FUNCTION_VALUE
,
670 /* Structure used when parsing image specifications. */
674 /* Name of keyword. */
677 /* The type of value allowed. */
678 enum image_value_type type
;
680 /* True means key must be present. */
683 /* Used to recognize duplicate keywords in a property list. */
686 /* The value that was found. */
691 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
692 has the format (image KEYWORD VALUE ...). One of the keyword/
693 value pairs must be `:type TYPE'. KEYWORDS is a vector of
694 image_keywords structures of size NKEYWORDS describing other
695 allowed keyword/value pairs. Value is true if SPEC is valid. */
698 parse_image_spec (Lisp_Object spec
, struct image_keyword
*keywords
,
699 int nkeywords
, Lisp_Object type
)
708 while (CONSP (plist
))
710 Lisp_Object key
, value
;
712 /* First element of a pair must be a symbol. */
714 plist
= XCDR (plist
);
718 /* There must follow a value. */
721 value
= XCAR (plist
);
722 plist
= XCDR (plist
);
724 /* Find key in KEYWORDS. Error if not found. */
725 for (i
= 0; i
< nkeywords
; ++i
)
726 if (strcmp (keywords
[i
].name
, SSDATA (SYMBOL_NAME (key
))) == 0)
732 /* Record that we recognized the keyword. If a keywords
733 was found more than once, it's an error. */
734 keywords
[i
].value
= value
;
735 if (keywords
[i
].count
> 1)
739 /* Check type of value against allowed type. */
740 switch (keywords
[i
].type
)
742 case IMAGE_STRING_VALUE
:
743 if (!STRINGP (value
))
747 case IMAGE_STRING_OR_NIL_VALUE
:
748 if (!STRINGP (value
) && !NILP (value
))
752 case IMAGE_SYMBOL_VALUE
:
753 if (!SYMBOLP (value
))
757 case IMAGE_POSITIVE_INTEGER_VALUE
:
758 if (! RANGED_INTEGERP (1, value
, INT_MAX
))
762 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
:
763 if (RANGED_INTEGERP (0, value
, INT_MAX
))
766 && RANGED_INTEGERP (0, XCAR (value
), INT_MAX
)
767 && RANGED_INTEGERP (0, XCDR (value
), INT_MAX
))
771 case IMAGE_ASCENT_VALUE
:
772 if (SYMBOLP (value
) && EQ (value
, Qcenter
))
774 else if (RANGED_INTEGERP (0, value
, 100))
778 case IMAGE_NON_NEGATIVE_INTEGER_VALUE
:
779 /* Unlike the other integer-related cases, this one does not
780 verify that VALUE fits in 'int'. This is because callers
782 if (!INTEGERP (value
) || XINT (value
) < 0)
786 case IMAGE_DONT_CHECK_VALUE_TYPE
:
789 case IMAGE_FUNCTION_VALUE
:
790 value
= indirect_function (value
);
791 if (!NILP (Ffunctionp (value
)))
795 case IMAGE_NUMBER_VALUE
:
796 if (! NUMBERP (value
))
800 case IMAGE_INTEGER_VALUE
:
801 if (! TYPE_RANGED_INTEGERP (int, value
))
805 case IMAGE_BOOL_VALUE
:
806 if (!NILP (value
) && !EQ (value
, Qt
))
815 if (EQ (key
, QCtype
) && !EQ (type
, value
))
819 /* Check that all mandatory fields are present. */
820 for (i
= 0; i
< nkeywords
; ++i
)
821 if (keywords
[i
].mandatory_p
&& keywords
[i
].count
== 0)
828 /* Return the value of KEY in image specification SPEC. Value is nil
829 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
830 was found in SPEC. */
833 image_spec_value (Lisp_Object spec
, Lisp_Object key
, bool *found
)
837 eassert (valid_image_p (spec
));
839 for (tail
= XCDR (spec
);
840 CONSP (tail
) && CONSP (XCDR (tail
));
841 tail
= XCDR (XCDR (tail
)))
843 if (EQ (XCAR (tail
), key
))
847 return XCAR (XCDR (tail
));
857 DEFUN ("image-size", Fimage_size
, Simage_size
, 1, 3, 0,
858 doc
: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
859 PIXELS non-nil means return the size in pixels, otherwise return the
860 size in canonical character units.
861 FRAME is the frame on which the image will be displayed. FRAME nil
862 or omitted means use the selected frame. */)
863 (Lisp_Object spec
, Lisp_Object pixels
, Lisp_Object frame
)
868 if (valid_image_p (spec
))
870 struct frame
*f
= decode_window_system_frame (frame
);
871 ptrdiff_t id
= lookup_image (f
, spec
);
872 struct image
*img
= IMAGE_FROM_ID (f
, id
);
873 int width
= img
->width
+ 2 * img
->hmargin
;
874 int height
= img
->height
+ 2 * img
->vmargin
;
877 size
= Fcons (make_float ((double) width
/ FRAME_COLUMN_WIDTH (f
)),
878 make_float ((double) height
/ FRAME_LINE_HEIGHT (f
)));
880 size
= Fcons (make_number (width
), make_number (height
));
883 error ("Invalid image specification");
889 DEFUN ("image-mask-p", Fimage_mask_p
, Simage_mask_p
, 1, 2, 0,
890 doc
: /* Return t if image SPEC has a mask bitmap.
891 FRAME is the frame on which the image will be displayed. FRAME nil
892 or omitted means use the selected frame. */)
893 (Lisp_Object spec
, Lisp_Object frame
)
898 if (valid_image_p (spec
))
900 struct frame
*f
= decode_window_system_frame (frame
);
901 ptrdiff_t id
= lookup_image (f
, spec
);
902 struct image
*img
= IMAGE_FROM_ID (f
, id
);
907 error ("Invalid image specification");
912 DEFUN ("image-metadata", Fimage_metadata
, Simage_metadata
, 1, 2, 0,
913 doc
: /* Return metadata for image SPEC.
914 FRAME is the frame on which the image will be displayed. FRAME nil
915 or omitted means use the selected frame. */)
916 (Lisp_Object spec
, Lisp_Object frame
)
921 if (valid_image_p (spec
))
923 struct frame
*f
= decode_window_system_frame (frame
);
924 ptrdiff_t id
= lookup_image (f
, spec
);
925 struct image
*img
= IMAGE_FROM_ID (f
, id
);
926 ext
= img
->lisp_data
;
933 /***********************************************************************
934 Image type independent image structures
935 ***********************************************************************/
937 #define MAX_IMAGE_SIZE 10.0
938 /* Allocate and return a new image structure for image specification
939 SPEC. SPEC has a hash value of HASH. */
941 static struct image
*
942 make_image (Lisp_Object spec
, EMACS_UINT hash
)
944 struct image
*img
= xzalloc (sizeof *img
);
945 Lisp_Object file
= image_spec_value (spec
, QCfile
, NULL
);
947 eassert (valid_image_p (spec
));
948 img
->dependencies
= NILP (file
) ? Qnil
: list1 (file
);
949 img
->type
= lookup_image_type (image_spec_value (spec
, QCtype
, NULL
));
950 eassert (img
->type
!= NULL
);
952 img
->lisp_data
= Qnil
;
953 img
->ascent
= DEFAULT_IMAGE_ASCENT
;
955 img
->corners
[BOT_CORNER
] = -1; /* Full image */
960 /* Free image IMG which was used on frame F, including its resources. */
963 free_image (struct frame
*f
, struct image
*img
)
967 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
969 /* Remove IMG from the hash table of its cache. */
971 img
->prev
->next
= img
->next
;
973 c
->buckets
[img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
] = img
->next
;
976 img
->next
->prev
= img
->prev
;
978 c
->images
[img
->id
] = NULL
;
980 /* Windows NT redefines 'free', but in this file, we need to
981 avoid the redefinition. */
985 /* Free resources, then free IMG. */
986 img
->type
->free (f
, img
);
991 /* Return true if the given widths and heights are valid for display. */
994 check_image_size (struct frame
*f
, int width
, int height
)
998 if (width
<= 0 || height
<= 0)
1001 if (INTEGERP (Vmax_image_size
))
1002 return (width
<= XINT (Vmax_image_size
)
1003 && height
<= XINT (Vmax_image_size
));
1004 else if (FLOATP (Vmax_image_size
))
1008 w
= FRAME_PIXEL_WIDTH (f
);
1009 h
= FRAME_PIXEL_HEIGHT (f
);
1012 w
= h
= 1024; /* Arbitrary size for unknown frame. */
1013 return (width
<= XFLOAT_DATA (Vmax_image_size
) * w
1014 && height
<= XFLOAT_DATA (Vmax_image_size
) * h
);
1020 /* Prepare image IMG for display on frame F. Must be called before
1021 drawing an image. */
1024 prepare_image_for_display (struct frame
*f
, struct image
*img
)
1026 /* We're about to display IMG, so set its timestamp to `now'. */
1027 img
->timestamp
= current_timespec ();
1030 /* If IMG doesn't have a pixmap yet, load it now, using the image
1031 type dependent loader function. */
1032 if (img
->pixmap
== NO_PIXMAP
&& !img
->load_failed_p
)
1033 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1035 #ifdef HAVE_X_WINDOWS
1036 if (!img
->load_failed_p
)
1039 image_sync_to_pixmaps (f
, img
);
1047 /* Value is the number of pixels for the ascent of image IMG when
1048 drawn in face FACE. */
1051 image_ascent (struct image
*img
, struct face
*face
, struct glyph_slice
*slice
)
1056 if (slice
->height
== img
->height
)
1057 height
= img
->height
+ img
->vmargin
;
1058 else if (slice
->y
== 0)
1059 height
= slice
->height
+ img
->vmargin
;
1061 height
= slice
->height
;
1063 if (img
->ascent
== CENTERED_IMAGE_ASCENT
)
1068 /* W32 specific version. Why?. ++kfs */
1069 ascent
= height
/ 2 - (FONT_DESCENT (face
->font
)
1070 - FONT_BASE (face
->font
)) / 2;
1072 /* This expression is arranged so that if the image can't be
1073 exactly centered, it will be moved slightly up. This is
1074 because a typical font is `top-heavy' (due to the presence
1075 uppercase letters), so the image placement should err towards
1076 being top-heavy too. It also just generally looks better. */
1077 ascent
= (height
+ FONT_BASE (face
->font
)
1078 - FONT_DESCENT (face
->font
) + 1) / 2;
1079 #endif /* HAVE_NTGUI */
1082 ascent
= height
/ 2;
1085 ascent
= height
* (img
->ascent
/ 100.0);
1092 xcolor_to_argb32 (XColor xc
)
1094 return (0xff << 24) | ((xc
.red
/ 256) << 16)
1095 | ((xc
.green
/ 256) << 8) | (xc
.blue
/ 256);
1099 get_spec_bg_or_alpha_as_argb (struct image
*img
,
1102 uint32_t bgcolor
= 0;
1104 Lisp_Object bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1106 if (STRINGP (bg
) && x_parse_color (f
, SSDATA (bg
), &xbgcolor
))
1107 bgcolor
= xcolor_to_argb32 (xbgcolor
);
1113 create_cairo_image_surface (struct image
*img
,
1114 unsigned char *data
,
1118 cairo_surface_t
*surface
;
1119 cairo_format_t format
= CAIRO_FORMAT_ARGB32
;
1120 int stride
= cairo_format_stride_for_width (format
, width
);
1121 surface
= cairo_image_surface_create_for_data (data
,
1127 img
->height
= height
;
1128 img
->cr_data
= surface
;
1129 img
->cr_data2
= data
;
1136 /* Image background colors. */
1138 /* Find the "best" corner color of a bitmap.
1139 On W32, XIMG is assumed to a device context with the bitmap selected. */
1141 static RGB_PIXEL_COLOR
1142 four_corners_best (XImagePtr_or_DC ximg
, int *corners
,
1143 unsigned long width
, unsigned long height
)
1145 RGB_PIXEL_COLOR corner_pixels
[4];
1146 RGB_PIXEL_COLOR best UNINIT
;
1149 if (corners
&& corners
[BOT_CORNER
] >= 0)
1151 /* Get the colors at the corner_pixels of ximg. */
1152 corner_pixels
[0] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[TOP_CORNER
]);
1153 corner_pixels
[1] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[TOP_CORNER
]);
1154 corner_pixels
[2] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[BOT_CORNER
] - 1);
1155 corner_pixels
[3] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[BOT_CORNER
] - 1);
1159 /* Get the colors at the corner_pixels of ximg. */
1160 corner_pixels
[0] = GET_PIXEL (ximg
, 0, 0);
1161 corner_pixels
[1] = GET_PIXEL (ximg
, width
- 1, 0);
1162 corner_pixels
[2] = GET_PIXEL (ximg
, width
- 1, height
- 1);
1163 corner_pixels
[3] = GET_PIXEL (ximg
, 0, height
- 1);
1165 /* Choose the most frequently found color as background. */
1166 for (i
= best_count
= 0; i
< 4; ++i
)
1170 for (j
= n
= 0; j
< 4; ++j
)
1171 if (corner_pixels
[i
] == corner_pixels
[j
])
1175 best
= corner_pixels
[i
], best_count
= n
;
1181 /* Portability macros */
1185 #define Free_Pixmap(display, pixmap) \
1186 DeleteObject (pixmap)
1188 #elif defined (HAVE_NS)
1190 #define Free_Pixmap(display, pixmap) \
1191 ns_release_object (pixmap)
1195 #define Free_Pixmap(display, pixmap) \
1196 XFreePixmap (display, pixmap)
1198 #endif /* !HAVE_NTGUI && !HAVE_NS */
1201 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1202 it is guessed heuristically. If non-zero, XIMG is an existing
1203 XImage object (or device context with the image selected on W32) to
1204 use for the heuristic. */
1207 image_background (struct image
*img
, struct frame
*f
, XImagePtr_or_DC ximg
)
1209 if (! img
->background_valid
)
1210 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1212 bool free_ximg
= !ximg
;
1215 #endif /* HAVE_NTGUI */
1218 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
1220 img
->background
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
1223 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
1225 img
->background_valid
= 1;
1228 return img
->background
;
1231 /* Return the `background_transparent' field of IMG. If IMG doesn't
1232 have one yet, it is guessed heuristically. If non-zero, MASK is an
1233 existing XImage object to use for the heuristic. */
1236 image_background_transparent (struct image
*img
, struct frame
*f
, XImagePtr_or_DC mask
)
1238 if (! img
->background_transparent_valid
)
1239 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1243 bool free_mask
= !mask
;
1246 #endif /* HAVE_NTGUI */
1249 mask
= image_get_x_image_or_dc (f
, img
, 1, &prev
);
1251 img
->background_transparent
1252 = (four_corners_best (mask
, img
->corners
, img
->width
, img
->height
) == PIX_MASK_RETAIN
);
1255 image_unget_x_image_or_dc (img
, 1, mask
, prev
);
1258 img
->background_transparent
= 0;
1260 img
->background_transparent_valid
= 1;
1263 return img
->background_transparent
;
1266 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1267 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1269 /* Store F's background color into *BGCOLOR. */
1271 x_query_frame_background_color (struct frame
*f
, XColor
*bgcolor
)
1274 bgcolor
->pixel
= FRAME_BACKGROUND_PIXEL (f
);
1275 x_query_color (f
, bgcolor
);
1277 ns_query_color (FRAME_BACKGROUND_COLOR (f
), bgcolor
, 1);
1281 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1283 /***********************************************************************
1284 Helper functions for X image types
1285 ***********************************************************************/
1287 /* Clear X resources of image IMG on frame F according to FLAGS.
1288 FLAGS is bitwise-or of the following masks:
1289 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1290 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1291 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1294 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1295 #define CLEAR_IMAGE_MASK (1 << 1)
1296 #define CLEAR_IMAGE_COLORS (1 << 2)
1299 x_clear_image_1 (struct frame
*f
, struct image
*img
, int flags
)
1301 if (flags
& CLEAR_IMAGE_PIXMAP
)
1305 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->pixmap
);
1306 img
->pixmap
= NO_PIXMAP
;
1307 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1308 img
->background_valid
= 0;
1310 #ifdef HAVE_X_WINDOWS
1313 x_destroy_x_image (img
->ximg
);
1315 img
->background_valid
= 0;
1320 if (flags
& CLEAR_IMAGE_MASK
)
1324 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->mask
);
1325 img
->mask
= NO_PIXMAP
;
1326 img
->background_transparent_valid
= 0;
1328 #ifdef HAVE_X_WINDOWS
1331 x_destroy_x_image (img
->mask_img
);
1332 img
->mask_img
= NULL
;
1333 img
->background_transparent_valid
= 0;
1338 if ((flags
& CLEAR_IMAGE_COLORS
) && img
->ncolors
)
1340 /* W32_TODO: color table support. */
1341 #ifdef HAVE_X_WINDOWS
1342 x_free_colors (f
, img
->colors
, img
->ncolors
);
1343 #endif /* HAVE_X_WINDOWS */
1344 xfree (img
->colors
);
1351 /* Free X resources of image IMG which is used on frame F. */
1354 x_clear_image (struct frame
*f
, struct image
*img
)
1359 cairo_surface_destroy ((cairo_surface_t
*)img
->cr_data
);
1360 if (img
->cr_data2
) xfree (img
->cr_data2
);
1362 x_clear_image_1 (f
, img
,
1363 CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_MASK
| CLEAR_IMAGE_COLORS
);
1368 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1369 cannot be allocated, use DFLT. Add a newly allocated color to
1370 IMG->colors, so that it can be freed again. Value is the pixel
1373 static unsigned long
1374 x_alloc_image_color (struct frame
*f
, struct image
*img
, Lisp_Object color_name
,
1378 unsigned long result
;
1380 eassert (STRINGP (color_name
));
1382 if (x_defined_color (f
, SSDATA (color_name
), &color
, 1)
1383 && img
->ncolors
< min (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *img
->colors
,
1386 /* This isn't called frequently so we get away with simply
1387 reallocating the color vector to the needed size, here. */
1388 ptrdiff_t ncolors
= img
->ncolors
+ 1;
1389 img
->colors
= xrealloc (img
->colors
, ncolors
* sizeof *img
->colors
);
1390 img
->colors
[ncolors
- 1] = color
.pixel
;
1391 img
->ncolors
= ncolors
;
1392 result
= color
.pixel
;
1402 /***********************************************************************
1404 ***********************************************************************/
1406 static void cache_image (struct frame
*f
, struct image
*img
);
1408 /* Return a new, initialized image cache that is allocated from the
1409 heap. Call free_image_cache to free an image cache. */
1411 struct image_cache
*
1412 make_image_cache (void)
1414 struct image_cache
*c
= xmalloc (sizeof *c
);
1417 c
->used
= c
->refcount
= 0;
1418 c
->images
= xmalloc (c
->size
* sizeof *c
->images
);
1419 c
->buckets
= xzalloc (IMAGE_CACHE_BUCKETS_SIZE
* sizeof *c
->buckets
);
1424 /* Find an image matching SPEC in the cache, and return it. If no
1425 image is found, return NULL. */
1426 static struct image
*
1427 search_image_cache (struct frame
*f
, Lisp_Object spec
, EMACS_UINT hash
)
1430 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1431 int i
= hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1433 if (!c
) return NULL
;
1435 /* If the image spec does not specify a background color, the cached
1436 image must have the same background color as the current frame.
1437 The foreground color must also match, for the sake of monochrome
1440 In fact, we could ignore the foreground color matching condition
1441 for color images, or if the image spec specifies :foreground;
1442 similarly we could ignore the background color matching condition
1443 for formats that don't use transparency (such as jpeg), or if the
1444 image spec specifies :background. However, the extra memory
1445 usage is probably negligible in practice, so we don't bother. */
1447 for (img
= c
->buckets
[i
]; img
; img
= img
->next
)
1448 if (img
->hash
== hash
1449 && !NILP (Fequal (img
->spec
, spec
))
1450 && img
->frame_foreground
== FRAME_FOREGROUND_PIXEL (f
)
1451 && img
->frame_background
== FRAME_BACKGROUND_PIXEL (f
))
1457 /* Search frame F for an image with spec SPEC, and free it. */
1460 uncache_image (struct frame
*f
, Lisp_Object spec
)
1462 struct image
*img
= search_image_cache (f
, spec
, sxhash (spec
, 0));
1465 free_image (f
, img
);
1466 /* As display glyphs may still be referring to the image ID, we
1467 must garbage the frame (Bug#6426). */
1468 SET_FRAME_GARBAGED (f
);
1473 /* Free image cache of frame F. Be aware that X frames share images
1477 free_image_cache (struct frame
*f
)
1479 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1484 /* Cache should not be referenced by any frame when freed. */
1485 eassert (c
->refcount
== 0);
1487 for (i
= 0; i
< c
->used
; ++i
)
1488 free_image (f
, c
->images
[i
]);
1492 FRAME_IMAGE_CACHE (f
) = NULL
;
1497 /* Clear image cache of frame F. FILTER=t means free all images.
1498 FILTER=nil means clear only images that haven't been
1499 displayed for some time.
1500 Else, only free the images which have FILTER in their `dependencies'.
1501 Should be called from time to time to reduce the number of loaded images.
1502 If image-cache-eviction-delay is non-nil, this frees images in the cache
1503 which weren't displayed for at least that many seconds. */
1506 clear_image_cache (struct frame
*f
, Lisp_Object filter
)
1508 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1512 ptrdiff_t i
, nfreed
= 0;
1514 /* Block input so that we won't be interrupted by a SIGIO
1515 while being in an inconsistent state. */
1520 /* Filter image cache. */
1521 for (i
= 0; i
< c
->used
; ++i
)
1523 struct image
*img
= c
->images
[i
];
1524 if (img
&& (EQ (Qt
, filter
)
1525 || !NILP (Fmember (filter
, img
->dependencies
))))
1527 free_image (f
, img
);
1532 else if (INTEGERP (Vimage_cache_eviction_delay
))
1534 /* Free cache based on timestamp. */
1535 struct timespec old
, t
;
1537 ptrdiff_t nimages
= 0;
1539 for (i
= 0; i
< c
->used
; ++i
)
1543 /* If the number of cached images has grown unusually large,
1544 decrease the cache eviction delay (Bug#6230). */
1545 delay
= XINT (Vimage_cache_eviction_delay
);
1547 delay
= 1600 * delay
/ nimages
/ nimages
;
1548 delay
= max (delay
, 1);
1550 t
= current_timespec ();
1551 old
= timespec_sub (t
, dtotimespec (delay
));
1553 for (i
= 0; i
< c
->used
; ++i
)
1555 struct image
*img
= c
->images
[i
];
1556 if (img
&& timespec_cmp (img
->timestamp
, old
) < 0)
1558 free_image (f
, img
);
1564 /* We may be clearing the image cache because, for example,
1565 Emacs was iconified for a longer period of time. In that
1566 case, current matrices may still contain references to
1567 images freed above. So, clear these matrices. */
1570 Lisp_Object tail
, frame
;
1572 FOR_EACH_FRAME (tail
, frame
)
1574 struct frame
*fr
= XFRAME (frame
);
1575 if (FRAME_IMAGE_CACHE (fr
) == c
)
1576 clear_current_matrices (fr
);
1579 windows_or_buffers_changed
= 19;
1587 clear_image_caches (Lisp_Object filter
)
1589 /* FIXME: We want to do
1590 * struct terminal *t;
1591 * for (t = terminal_list; t; t = t->next_terminal)
1592 * clear_image_cache (t, filter); */
1593 Lisp_Object tail
, frame
;
1594 FOR_EACH_FRAME (tail
, frame
)
1595 if (FRAME_WINDOW_P (XFRAME (frame
)))
1596 clear_image_cache (XFRAME (frame
), filter
);
1599 DEFUN ("clear-image-cache", Fclear_image_cache
, Sclear_image_cache
,
1601 doc
: /* Clear the image cache.
1602 FILTER nil or a frame means clear all images in the selected frame.
1603 FILTER t means clear the image caches of all frames.
1604 Anything else, means only clear those images which refer to FILTER,
1605 which is then usually a filename. */)
1606 (Lisp_Object filter
)
1608 if (!(EQ (filter
, Qnil
) || FRAMEP (filter
)))
1609 clear_image_caches (filter
);
1611 clear_image_cache (decode_window_system_frame (filter
), Qt
);
1617 DEFUN ("image-flush", Fimage_flush
, Simage_flush
,
1619 doc
: /* Flush the image with specification SPEC on frame FRAME.
1620 This removes the image from the Emacs image cache. If SPEC specifies
1621 an image file, the next redisplay of this image will read from the
1622 current contents of that file.
1624 FRAME nil or omitted means use the selected frame.
1625 FRAME t means refresh the image on all frames. */)
1626 (Lisp_Object spec
, Lisp_Object frame
)
1628 if (!valid_image_p (spec
))
1629 error ("Invalid image specification");
1634 FOR_EACH_FRAME (tail
, frame
)
1636 struct frame
*f
= XFRAME (frame
);
1637 if (FRAME_WINDOW_P (f
))
1638 uncache_image (f
, spec
);
1642 uncache_image (decode_window_system_frame (frame
), spec
);
1648 /* Compute masks and transform image IMG on frame F, as specified
1649 by the image's specification, */
1652 postprocess_image (struct frame
*f
, struct image
*img
)
1654 /* Manipulation of the image's mask. */
1657 Lisp_Object conversion
, spec
;
1662 /* `:heuristic-mask t'
1664 means build a mask heuristically.
1665 `:heuristic-mask (R G B)'
1666 `:mask (heuristic (R G B))'
1667 means build a mask from color (R G B) in the
1670 means remove a mask, if any. */
1672 mask
= image_spec_value (spec
, QCheuristic_mask
, NULL
);
1674 x_build_heuristic_mask (f
, img
, mask
);
1679 mask
= image_spec_value (spec
, QCmask
, &found_p
);
1681 if (EQ (mask
, Qheuristic
))
1682 x_build_heuristic_mask (f
, img
, Qt
);
1683 else if (CONSP (mask
)
1684 && EQ (XCAR (mask
), Qheuristic
))
1686 if (CONSP (XCDR (mask
)))
1687 x_build_heuristic_mask (f
, img
, XCAR (XCDR (mask
)));
1689 x_build_heuristic_mask (f
, img
, XCDR (mask
));
1691 else if (NILP (mask
) && found_p
&& img
->mask
)
1692 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
1696 /* Should we apply an image transformation algorithm? */
1697 conversion
= image_spec_value (spec
, QCconversion
, NULL
);
1698 if (EQ (conversion
, Qdisabled
))
1699 x_disable_image (f
, img
);
1700 else if (EQ (conversion
, Qlaplace
))
1702 else if (EQ (conversion
, Qemboss
))
1704 else if (CONSP (conversion
)
1705 && EQ (XCAR (conversion
), Qedge_detection
))
1708 tem
= XCDR (conversion
);
1710 x_edge_detection (f
, img
,
1711 Fplist_get (tem
, QCmatrix
),
1712 Fplist_get (tem
, QCcolor_adjustment
));
1718 /* Return the id of image with Lisp specification SPEC on frame F.
1719 SPEC must be a valid Lisp image specification (see valid_image_p). */
1722 lookup_image (struct frame
*f
, Lisp_Object spec
)
1727 /* F must be a window-system frame, and SPEC must be a valid image
1729 eassert (FRAME_WINDOW_P (f
));
1730 eassert (valid_image_p (spec
));
1732 /* Look up SPEC in the hash table of the image cache. */
1733 hash
= sxhash (spec
, 0);
1734 img
= search_image_cache (f
, spec
, hash
);
1735 if (img
&& img
->load_failed_p
)
1737 free_image (f
, img
);
1741 /* If not found, create a new image and cache it. */
1745 img
= make_image (spec
, hash
);
1746 cache_image (f
, img
);
1747 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1748 img
->frame_foreground
= FRAME_FOREGROUND_PIXEL (f
);
1749 img
->frame_background
= FRAME_BACKGROUND_PIXEL (f
);
1751 /* If we can't load the image, and we don't have a width and
1752 height, use some arbitrary width and height so that we can
1753 draw a rectangle for it. */
1754 if (img
->load_failed_p
)
1758 value
= image_spec_value (spec
, QCwidth
, NULL
);
1759 img
->width
= (INTEGERP (value
)
1760 ? XFASTINT (value
) : DEFAULT_IMAGE_WIDTH
);
1761 value
= image_spec_value (spec
, QCheight
, NULL
);
1762 img
->height
= (INTEGERP (value
)
1763 ? XFASTINT (value
) : DEFAULT_IMAGE_HEIGHT
);
1767 /* Handle image type independent image attributes
1768 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1769 `:background COLOR'. */
1770 Lisp_Object ascent
, margin
, relief
, bg
;
1773 ascent
= image_spec_value (spec
, QCascent
, NULL
);
1774 if (INTEGERP (ascent
))
1775 img
->ascent
= XFASTINT (ascent
);
1776 else if (EQ (ascent
, Qcenter
))
1777 img
->ascent
= CENTERED_IMAGE_ASCENT
;
1779 margin
= image_spec_value (spec
, QCmargin
, NULL
);
1780 if (INTEGERP (margin
))
1781 img
->vmargin
= img
->hmargin
= XFASTINT (margin
);
1782 else if (CONSP (margin
))
1784 img
->hmargin
= XFASTINT (XCAR (margin
));
1785 img
->vmargin
= XFASTINT (XCDR (margin
));
1788 relief
= image_spec_value (spec
, QCrelief
, NULL
);
1789 relief_bound
= INT_MAX
- max (img
->hmargin
, img
->vmargin
);
1790 if (RANGED_INTEGERP (- relief_bound
, relief
, relief_bound
))
1792 img
->relief
= XINT (relief
);
1793 img
->hmargin
+= eabs (img
->relief
);
1794 img
->vmargin
+= eabs (img
->relief
);
1797 if (! img
->background_valid
)
1799 bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1803 = x_alloc_image_color (f
, img
, bg
,
1804 FRAME_BACKGROUND_PIXEL (f
));
1805 img
->background_valid
= 1;
1809 /* Do image transformations and compute masks, unless we
1810 don't have the image yet. */
1811 if (!EQ (builtin_lisp_symbol (img
->type
->type
), Qpostscript
))
1812 postprocess_image (f
, img
);
1818 /* We're using IMG, so set its timestamp to `now'. */
1819 img
->timestamp
= current_timespec ();
1821 /* Value is the image id. */
1826 /* Cache image IMG in the image cache of frame F. */
1829 cache_image (struct frame
*f
, struct image
*img
)
1831 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1835 c
= FRAME_IMAGE_CACHE (f
) = make_image_cache ();
1837 /* Find a free slot in c->images. */
1838 for (i
= 0; i
< c
->used
; ++i
)
1839 if (c
->images
[i
] == NULL
)
1842 /* If no free slot found, maybe enlarge c->images. */
1843 if (i
== c
->used
&& c
->used
== c
->size
)
1844 c
->images
= xpalloc (c
->images
, &c
->size
, 1, -1, sizeof *c
->images
);
1846 /* Add IMG to c->images, and assign IMG an id. */
1852 /* Add IMG to the cache's hash table. */
1853 i
= img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1854 img
->next
= c
->buckets
[i
];
1856 img
->next
->prev
= img
;
1858 c
->buckets
[i
] = img
;
1862 /* Call FN on every image in the image cache of frame F. Used to mark
1863 Lisp Objects in the image cache. */
1865 /* Mark Lisp objects in image IMG. */
1868 mark_image (struct image
*img
)
1870 mark_object (img
->spec
);
1871 mark_object (img
->dependencies
);
1873 if (!NILP (img
->lisp_data
))
1874 mark_object (img
->lisp_data
);
1879 mark_image_cache (struct image_cache
*c
)
1884 for (i
= 0; i
< c
->used
; ++i
)
1886 mark_image (c
->images
[i
]);
1892 /***********************************************************************
1893 X / NS / W32 support code
1894 ***********************************************************************/
1896 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1898 WIDTH and HEIGHT must both be positive.
1899 If XIMG is null, assume it is a bitmap. */
1901 x_check_image_size (XImagePtr ximg
, int width
, int height
)
1903 #ifdef HAVE_X_WINDOWS
1904 /* Respect Xlib's limits: it cannot deal with images that have more
1905 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1906 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1909 XLIB_BYTES_MAX
= min (INT_MAX
, UINT_MAX
),
1910 X_IMAGE_BYTES_MAX
= min (XLIB_BYTES_MAX
, min (PTRDIFF_MAX
, SIZE_MAX
))
1913 int bitmap_pad
, depth
, bytes_per_line
;
1916 bitmap_pad
= ximg
->bitmap_pad
;
1917 depth
= ximg
->depth
;
1918 bytes_per_line
= ximg
->bytes_per_line
;
1924 bytes_per_line
= (width
>> 3) + ((width
& 7) != 0);
1926 return (width
<= (INT_MAX
- (bitmap_pad
- 1)) / depth
1927 && height
<= X_IMAGE_BYTES_MAX
/ bytes_per_line
);
1929 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1930 For now, assume that every image size is allowed on these systems. */
1935 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1936 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1937 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1938 via xmalloc. Print error messages via image_error if an error
1939 occurs. Value is true if successful.
1941 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1942 should indicate the bit depth of the image. */
1945 x_create_x_image_and_pixmap (struct frame
*f
, int width
, int height
, int depth
,
1946 XImagePtr
*ximg
, Pixmap
*pixmap
)
1948 #ifdef HAVE_X_WINDOWS
1949 Display
*display
= FRAME_X_DISPLAY (f
);
1950 Window window
= FRAME_X_WINDOW (f
);
1951 Screen
*screen
= FRAME_X_SCREEN (f
);
1953 eassert (input_blocked_p ());
1956 depth
= DefaultDepthOfScreen (screen
);
1957 *ximg
= XCreateImage (display
, DefaultVisualOfScreen (screen
),
1958 depth
, ZPixmap
, 0, NULL
, width
, height
,
1959 depth
> 16 ? 32 : depth
> 8 ? 16 : 8, 0);
1962 image_error ("Unable to allocate X image");
1966 if (! x_check_image_size (*ximg
, width
, height
))
1968 x_destroy_x_image (*ximg
);
1970 image_error ("Image too large (%dx%d)",
1971 make_number (width
), make_number (height
));
1975 /* Allocate image raster. */
1976 (*ximg
)->data
= xmalloc ((*ximg
)->bytes_per_line
* height
);
1978 /* Allocate a pixmap of the same size. */
1979 *pixmap
= XCreatePixmap (display
, window
, width
, height
, depth
);
1980 if (*pixmap
== NO_PIXMAP
)
1982 x_destroy_x_image (*ximg
);
1984 image_error ("Unable to create X pixmap");
1989 #endif /* HAVE_X_WINDOWS */
1993 BITMAPINFOHEADER
*header
;
1995 int scanline_width_bits
;
1997 int palette_colors
= 0;
2002 if (depth
!= 1 && depth
!= 4 && depth
!= 8
2003 && depth
!= 16 && depth
!= 24 && depth
!= 32)
2005 image_error ("Invalid image bit depth specified");
2009 scanline_width_bits
= width
* depth
;
2010 remainder
= scanline_width_bits
% 32;
2013 scanline_width_bits
+= 32 - remainder
;
2015 /* Bitmaps with a depth less than 16 need a palette. */
2016 /* BITMAPINFO structure already contains the first RGBQUAD. */
2018 palette_colors
= 1 << (depth
- 1);
2020 *ximg
= xmalloc (sizeof (XImage
) + palette_colors
* sizeof (RGBQUAD
));
2022 header
= &(*ximg
)->info
.bmiHeader
;
2023 memset (&(*ximg
)->info
, 0, sizeof (BITMAPINFO
));
2024 header
->biSize
= sizeof (*header
);
2025 header
->biWidth
= width
;
2026 header
->biHeight
= -height
; /* negative indicates a top-down bitmap. */
2027 header
->biPlanes
= 1;
2028 header
->biBitCount
= depth
;
2029 header
->biCompression
= BI_RGB
;
2030 header
->biClrUsed
= palette_colors
;
2032 /* TODO: fill in palette. */
2035 (*ximg
)->info
.bmiColors
[0].rgbBlue
= 0;
2036 (*ximg
)->info
.bmiColors
[0].rgbGreen
= 0;
2037 (*ximg
)->info
.bmiColors
[0].rgbRed
= 0;
2038 (*ximg
)->info
.bmiColors
[0].rgbReserved
= 0;
2039 (*ximg
)->info
.bmiColors
[1].rgbBlue
= 255;
2040 (*ximg
)->info
.bmiColors
[1].rgbGreen
= 255;
2041 (*ximg
)->info
.bmiColors
[1].rgbRed
= 255;
2042 (*ximg
)->info
.bmiColors
[1].rgbReserved
= 0;
2045 hdc
= get_frame_dc (f
);
2047 /* Create a DIBSection and raster array for the bitmap,
2048 and store its handle in *pixmap. */
2049 *pixmap
= CreateDIBSection (hdc
, &((*ximg
)->info
),
2050 (depth
< 16) ? DIB_PAL_COLORS
: DIB_RGB_COLORS
,
2051 /* casting avoids a GCC warning */
2052 (void **)&((*ximg
)->data
), NULL
, 0);
2054 /* Realize display palette and garbage all frames. */
2055 release_frame_dc (f
, hdc
);
2057 if (*pixmap
== NULL
)
2059 DWORD err
= GetLastError ();
2060 Lisp_Object errcode
;
2061 /* All system errors are < 10000, so the following is safe. */
2062 XSETINT (errcode
, err
);
2063 image_error ("Unable to create bitmap, error code %d", errcode
);
2064 x_destroy_x_image (*ximg
);
2071 #endif /* HAVE_NTGUI */
2074 *pixmap
= ns_image_for_XPM (width
, height
, depth
);
2078 image_error ("Unable to allocate NSImage for XPM pixmap");
2087 /* Destroy XImage XIMG. Free XIMG->data. */
2090 x_destroy_x_image (XImagePtr ximg
)
2092 eassert (input_blocked_p ());
2095 #ifdef HAVE_X_WINDOWS
2098 XDestroyImage (ximg
);
2099 #endif /* HAVE_X_WINDOWS */
2101 /* Data will be freed by DestroyObject. */
2104 #endif /* HAVE_NTGUI */
2106 ns_release_object (ximg
);
2107 #endif /* HAVE_NS */
2112 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2113 are width and height of both the image and pixmap. */
2116 x_put_x_image (struct frame
*f
, XImagePtr ximg
, Pixmap pixmap
, int width
, int height
)
2118 #ifdef HAVE_X_WINDOWS
2121 eassert (input_blocked_p ());
2122 gc
= XCreateGC (FRAME_X_DISPLAY (f
), pixmap
, 0, NULL
);
2123 XPutImage (FRAME_X_DISPLAY (f
), pixmap
, gc
, ximg
, 0, 0, 0, 0, width
, height
);
2124 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
2125 #endif /* HAVE_X_WINDOWS */
2128 #if 0 /* I don't think this is necessary looking at where it is used. */
2129 HDC hdc
= get_frame_dc (f
);
2130 SetDIBits (hdc
, pixmap
, 0, height
, ximg
->data
, &(ximg
->info
), DIB_RGB_COLORS
);
2131 release_frame_dc (f
, hdc
);
2133 #endif /* HAVE_NTGUI */
2136 eassert (ximg
== pixmap
);
2137 ns_retain_object (ximg
);
2141 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2142 with image_put_x_image. */
2145 image_create_x_image_and_pixmap (struct frame
*f
, struct image
*img
,
2146 int width
, int height
, int depth
,
2147 XImagePtr
*ximg
, bool mask_p
)
2149 eassert ((!mask_p
? img
->pixmap
: img
->mask
) == NO_PIXMAP
);
2151 return x_create_x_image_and_pixmap (f
, width
, height
, depth
, ximg
,
2152 !mask_p
? &img
->pixmap
: &img
->mask
);
2155 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2156 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2157 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2158 On the other platforms, it puts XIMG into the pixmap, then frees
2159 the X image and its buffer. */
2162 image_put_x_image (struct frame
*f
, struct image
*img
, XImagePtr ximg
,
2165 #ifdef HAVE_X_WINDOWS
2168 eassert (img
->ximg
== NULL
);
2173 eassert (img
->mask_img
== NULL
);
2174 img
->mask_img
= ximg
;
2177 x_put_x_image (f
, ximg
, !mask_p
? img
->pixmap
: img
->mask
,
2178 img
->width
, img
->height
);
2179 x_destroy_x_image (ximg
);
2183 #ifdef HAVE_X_WINDOWS
2184 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2185 the X images and their buffers. */
2188 image_sync_to_pixmaps (struct frame
*f
, struct image
*img
)
2192 x_put_x_image (f
, img
->ximg
, img
->pixmap
, img
->width
, img
->height
);
2193 x_destroy_x_image (img
->ximg
);
2198 x_put_x_image (f
, img
->mask_img
, img
->mask
, img
->width
, img
->height
);
2199 x_destroy_x_image (img
->mask_img
);
2200 img
->mask_img
= NULL
;
2206 /* Create a memory device context for IMG on frame F. It stores the
2207 currently selected GDI object into *PREV for future restoration by
2208 image_unget_x_image_or_dc. */
2210 static XImagePtr_or_DC
2211 image_get_x_image_or_dc (struct frame
*f
, struct image
*img
, bool mask_p
,
2214 HDC frame_dc
= get_frame_dc (f
);
2215 XImagePtr_or_DC ximg
= CreateCompatibleDC (frame_dc
);
2217 release_frame_dc (f
, frame_dc
);
2218 *prev
= SelectObject (ximg
, !mask_p
? img
->pixmap
: img
->mask
);
2224 image_unget_x_image_or_dc (struct image
*img
, bool mask_p
,
2225 XImagePtr_or_DC ximg
, HGDIOBJ prev
)
2227 SelectObject (ximg
, prev
);
2230 #else /* !HAVE_NTGUI */
2231 /* Get the X image for IMG on frame F. The resulting X image data
2232 should be treated as read-only at least on X. */
2235 image_get_x_image (struct frame
*f
, struct image
*img
, bool mask_p
)
2237 #ifdef HAVE_X_WINDOWS
2238 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2243 return XGetImage (FRAME_X_DISPLAY (f
), !mask_p
? img
->pixmap
: img
->mask
,
2244 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
2245 #elif defined (HAVE_NS)
2246 XImagePtr pixmap
= !mask_p
? img
->pixmap
: img
->mask
;
2248 ns_retain_object (pixmap
);
2254 image_unget_x_image (struct image
*img
, bool mask_p
, XImagePtr ximg
)
2256 #ifdef HAVE_X_WINDOWS
2257 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2260 eassert (ximg
== ximg_in_img
);
2262 XDestroyImage (ximg
);
2263 #elif defined (HAVE_NS)
2264 ns_release_object (ximg
);
2267 #endif /* !HAVE_NTGUI */
2270 /***********************************************************************
2272 ***********************************************************************/
2274 /* Find image file FILE. Look in data-directory/images, then
2275 x-bitmap-file-path. Value is the full name of the file
2276 found, or nil if not found. If PFD is nonnull store into *PFD a
2277 readable file descriptor for the file, opened in binary mode. If
2278 PFD is null, do not open the file. */
2281 x_find_image_fd (Lisp_Object file
, int *pfd
)
2283 Lisp_Object file_found
, search_path
;
2286 /* TODO I think this should use something like image-load-path
2287 instead. Unfortunately, that can contain non-string elements. */
2288 search_path
= Fcons (Fexpand_file_name (build_string ("images"),
2290 Vx_bitmap_file_path
);
2292 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2293 fd
= openp (search_path
, file
, Qnil
, &file_found
,
2294 pfd
? Qt
: make_number (R_OK
), false);
2295 if (fd
>= 0 || fd
== -2)
2297 file_found
= ENCODE_FILE (file_found
);
2300 /* The file exists locally, but has a file handler. (This
2301 happens, e.g., under Auto Image File Mode.) 'openp'
2302 didn't open the file, so we should, because the caller
2304 fd
= emacs_open (SSDATA (file_found
), O_RDONLY
, 0);
2307 else /* fd < 0, but not -2 */
2314 /* Find image file FILE. Look in data-directory/images, then
2315 x-bitmap-file-path. Value is the encoded full name of the file
2316 found, or nil if not found. */
2319 x_find_image_file (Lisp_Object file
)
2321 return x_find_image_fd (file
, 0);
2324 /* Read FILE into memory. Value is a pointer to a buffer allocated
2325 with xmalloc holding FILE's contents. Value is null if an error
2326 occurred. FD is a file descriptor open for reading FILE. Set
2327 *SIZE to the size of the file. */
2329 static unsigned char *
2330 slurp_file (int fd
, ptrdiff_t *size
)
2332 FILE *fp
= fdopen (fd
, "rb");
2334 unsigned char *buf
= NULL
;
2339 ptrdiff_t count
= SPECPDL_INDEX ();
2340 record_unwind_protect_ptr (fclose_unwind
, fp
);
2342 if (fstat (fileno (fp
), &st
) == 0
2343 && 0 <= st
.st_size
&& st
.st_size
< min (PTRDIFF_MAX
, SIZE_MAX
))
2345 /* Report an error if we read past the purported EOF.
2346 This can happen if the file grows as we read it. */
2347 ptrdiff_t buflen
= st
.st_size
;
2348 buf
= xmalloc (buflen
+ 1);
2349 if (fread (buf
, 1, buflen
+ 1, fp
) == buflen
)
2358 unbind_to (count
, Qnil
);
2366 /***********************************************************************
2368 ***********************************************************************/
2370 static bool xbm_load (struct frame
*f
, struct image
*img
);
2371 static bool xbm_image_p (Lisp_Object object
);
2372 static bool xbm_file_p (Lisp_Object
);
2375 /* Indices of image specification fields in xbm_format, below. */
2377 enum xbm_keyword_index
2395 /* Vector of image_keyword structures describing the format
2396 of valid XBM image specifications. */
2398 static const struct image_keyword xbm_format
[XBM_LAST
] =
2400 {":type", IMAGE_SYMBOL_VALUE
, 1},
2401 {":file", IMAGE_STRING_VALUE
, 0},
2402 {":width", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2403 {":height", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2404 {":data", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2405 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
2406 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
2407 {":ascent", IMAGE_ASCENT_VALUE
, 0},
2408 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
2409 {":relief", IMAGE_INTEGER_VALUE
, 0},
2410 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2411 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2412 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
2415 /* Structure describing the image type XBM. */
2417 static struct image_type xbm_type
=
2419 SYMBOL_INDEX (Qxbm
),
2427 /* Tokens returned from xbm_scan. */
2436 /* Return true if OBJECT is a valid XBM-type image specification.
2437 A valid specification is a list starting with the symbol `image'
2438 The rest of the list is a property list which must contain an
2441 If the specification specifies a file to load, it must contain
2442 an entry `:file FILENAME' where FILENAME is a string.
2444 If the specification is for a bitmap loaded from memory it must
2445 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2446 WIDTH and HEIGHT are integers > 0. DATA may be:
2448 1. a string large enough to hold the bitmap data, i.e. it must
2449 have a size >= (WIDTH + 7) / 8 * HEIGHT
2451 2. a bool-vector of size >= WIDTH * HEIGHT
2453 3. a vector of strings or bool-vectors, one for each line of the
2456 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2457 may not be specified in this case because they are defined in the
2460 Both the file and data forms may contain the additional entries
2461 `:background COLOR' and `:foreground COLOR'. If not present,
2462 foreground and background of the frame on which the image is
2463 displayed is used. */
2466 xbm_image_p (Lisp_Object object
)
2468 struct image_keyword kw
[XBM_LAST
];
2470 memcpy (kw
, xbm_format
, sizeof kw
);
2471 if (!parse_image_spec (object
, kw
, XBM_LAST
, Qxbm
))
2474 eassert (EQ (kw
[XBM_TYPE
].value
, Qxbm
));
2476 if (kw
[XBM_FILE
].count
)
2478 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_DATA
].count
)
2481 else if (kw
[XBM_DATA
].count
&& xbm_file_p (kw
[XBM_DATA
].value
))
2483 /* In-memory XBM file. */
2484 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_FILE
].count
)
2492 /* Entries for `:width', `:height' and `:data' must be present. */
2493 if (!kw
[XBM_WIDTH
].count
2494 || !kw
[XBM_HEIGHT
].count
2495 || !kw
[XBM_DATA
].count
)
2498 data
= kw
[XBM_DATA
].value
;
2499 width
= XFASTINT (kw
[XBM_WIDTH
].value
);
2500 height
= XFASTINT (kw
[XBM_HEIGHT
].value
);
2502 /* Check type of data, and width and height against contents of
2508 /* Number of elements of the vector must be >= height. */
2509 if (ASIZE (data
) < height
)
2512 /* Each string or bool-vector in data must be large enough
2513 for one line of the image. */
2514 for (i
= 0; i
< height
; ++i
)
2516 Lisp_Object elt
= AREF (data
, i
);
2521 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
)
2524 else if (BOOL_VECTOR_P (elt
))
2526 if (bool_vector_size (elt
) < width
)
2533 else if (STRINGP (data
))
2536 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
* height
)
2539 else if (BOOL_VECTOR_P (data
))
2541 if (bool_vector_size (data
) / height
< width
)
2552 /* Scan a bitmap file. FP is the stream to read from. Value is
2553 either an enumerator from enum xbm_token, or a character for a
2554 single-character token, or 0 at end of file. If scanning an
2555 identifier, store the lexeme of the identifier in SVAL. If
2556 scanning a number, store its value in *IVAL. */
2559 xbm_scan (unsigned char **s
, unsigned char *end
, char *sval
, int *ival
)
2565 /* Skip white space. */
2566 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
2571 else if (c_isdigit (c
))
2573 int value
= 0, digit
;
2575 if (c
== '0' && *s
< end
)
2578 if (c
== 'x' || c
== 'X')
2585 else if (c
>= 'a' && c
<= 'f')
2586 digit
= c
- 'a' + 10;
2587 else if (c
>= 'A' && c
<= 'F')
2588 digit
= c
- 'A' + 10;
2591 value
= 16 * value
+ digit
;
2594 else if (c_isdigit (c
))
2598 && (c
= *(*s
)++, c_isdigit (c
)))
2599 value
= 8 * value
+ c
- '0';
2606 && (c
= *(*s
)++, c_isdigit (c
)))
2607 value
= 10 * value
+ c
- '0';
2615 else if (c_isalpha (c
) || c
== '_')
2619 && (c
= *(*s
)++, (c_isalnum (c
) || c
== '_')))
2626 else if (c
== '/' && **s
== '*')
2628 /* C-style comment. */
2630 while (**s
&& (**s
!= '*' || *(*s
+ 1) != '/'))
2644 /* Create a Windows bitmap from X bitmap data. */
2646 w32_create_pixmap_from_bitmap_data (int width
, int height
, char *data
)
2648 static unsigned char swap_nibble
[16]
2649 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2650 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2651 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2652 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2654 unsigned char *bits
, *p
;
2657 w1
= (width
+ 7) / 8; /* nb of 8bits elt in X bitmap */
2658 w2
= ((width
+ 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2659 bits
= alloca (height
* w2
);
2660 memset (bits
, 0, height
* w2
);
2661 for (i
= 0; i
< height
; i
++)
2664 for (j
= 0; j
< w1
; j
++)
2666 /* Bitswap XBM bytes to match how Windows does things. */
2667 unsigned char c
= *data
++;
2668 *p
++ = (unsigned char)((swap_nibble
[c
& 0xf] << 4)
2669 | (swap_nibble
[(c
>>4) & 0xf]));
2672 bmp
= CreateBitmap (width
, height
, 1, 1, (char *) bits
);
2678 convert_mono_to_color_image (struct frame
*f
, struct image
*img
,
2679 COLORREF foreground
, COLORREF background
)
2681 HDC hdc
, old_img_dc
, new_img_dc
;
2682 HGDIOBJ old_prev
, new_prev
;
2685 hdc
= get_frame_dc (f
);
2686 old_img_dc
= CreateCompatibleDC (hdc
);
2687 new_img_dc
= CreateCompatibleDC (hdc
);
2688 new_pixmap
= CreateCompatibleBitmap (hdc
, img
->width
, img
->height
);
2689 release_frame_dc (f
, hdc
);
2690 old_prev
= SelectObject (old_img_dc
, img
->pixmap
);
2691 new_prev
= SelectObject (new_img_dc
, new_pixmap
);
2692 /* Windows convention for mono bitmaps is black = background,
2693 white = foreground. */
2694 SetTextColor (new_img_dc
, background
);
2695 SetBkColor (new_img_dc
, foreground
);
2697 BitBlt (new_img_dc
, 0, 0, img
->width
, img
->height
, old_img_dc
,
2700 SelectObject (old_img_dc
, old_prev
);
2701 SelectObject (new_img_dc
, new_prev
);
2702 DeleteDC (old_img_dc
);
2703 DeleteDC (new_img_dc
);
2704 DeleteObject (img
->pixmap
);
2705 if (new_pixmap
== 0)
2706 fprintf (stderr
, "Failed to convert image to color.\n");
2708 img
->pixmap
= new_pixmap
;
2711 #define XBM_BIT_SHUFFLE(b) (~(b))
2715 #define XBM_BIT_SHUFFLE(b) (b)
2717 #endif /* HAVE_NTGUI */
2721 Create_Pixmap_From_Bitmap_Data (struct frame
*f
, struct image
*img
, char *data
,
2722 RGB_PIXEL_COLOR fg
, RGB_PIXEL_COLOR bg
,
2723 bool non_default_colors
)
2727 = w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
, data
);
2729 /* If colors were specified, transfer the bitmap to a color one. */
2730 if (non_default_colors
)
2731 convert_mono_to_color_image (f
, img
, fg
, bg
);
2733 #elif defined (HAVE_NS)
2734 img
->pixmap
= ns_image_from_XBM (data
, img
->width
, img
->height
, fg
, bg
);
2738 (x_check_image_size (0, img
->width
, img
->height
)
2739 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f
),
2742 img
->width
, img
->height
,
2744 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)))
2746 #endif /* !HAVE_NTGUI && !HAVE_NS */
2751 /* Replacement for XReadBitmapFileData which isn't available under old
2752 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2753 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2754 the image. Return in *DATA the bitmap data allocated with xmalloc.
2755 Value is true if successful. DATA null means just test if
2756 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2757 inhibit the call to image_error when the image size is invalid (the
2758 bitmap remains unread). */
2761 xbm_read_bitmap_data (struct frame
*f
, unsigned char *contents
, unsigned char *end
,
2762 int *width
, int *height
, char **data
,
2763 bool inhibit_image_error
)
2765 unsigned char *s
= contents
;
2766 char buffer
[BUFSIZ
];
2769 int bytes_per_line
, i
, nbytes
;
2775 LA1 = xbm_scan (&s, end, buffer, &value)
2777 #define expect(TOKEN) \
2780 if (LA1 != (TOKEN)) \
2786 #define expect_ident(IDENT) \
2787 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2792 *width
= *height
= -1;
2795 LA1
= xbm_scan (&s
, end
, buffer
, &value
);
2797 /* Parse defines for width, height and hot-spots. */
2801 expect_ident ("define");
2802 expect (XBM_TK_IDENT
);
2804 if (LA1
== XBM_TK_NUMBER
)
2806 char *q
= strrchr (buffer
, '_');
2807 q
= q
? q
+ 1 : buffer
;
2808 if (strcmp (q
, "width") == 0)
2810 else if (strcmp (q
, "height") == 0)
2813 expect (XBM_TK_NUMBER
);
2816 if (!check_image_size (f
, *width
, *height
))
2818 if (!inhibit_image_error
)
2819 image_size_error ();
2822 else if (data
== NULL
)
2825 /* Parse bits. Must start with `static'. */
2826 expect_ident ("static");
2827 if (LA1
== XBM_TK_IDENT
)
2829 if (strcmp (buffer
, "unsigned") == 0)
2832 expect_ident ("char");
2834 else if (strcmp (buffer
, "short") == 0)
2838 if (*width
% 16 && *width
% 16 < 9)
2841 else if (strcmp (buffer
, "char") == 0)
2849 expect (XBM_TK_IDENT
);
2855 if (! x_check_image_size (0, *width
, *height
))
2857 if (!inhibit_image_error
)
2858 image_error ("Image too large (%dx%d)",
2859 make_number (*width
), make_number (*height
));
2862 bytes_per_line
= (*width
+ 7) / 8 + padding_p
;
2863 nbytes
= bytes_per_line
* *height
;
2864 p
= *data
= xmalloc (nbytes
);
2868 for (i
= 0; i
< nbytes
; i
+= 2)
2871 expect (XBM_TK_NUMBER
);
2873 *p
++ = XBM_BIT_SHUFFLE (val
);
2874 if (!padding_p
|| ((i
+ 2) % bytes_per_line
))
2875 *p
++ = XBM_BIT_SHUFFLE (value
>> 8);
2877 if (LA1
== ',' || LA1
== '}')
2885 for (i
= 0; i
< nbytes
; ++i
)
2888 expect (XBM_TK_NUMBER
);
2890 *p
++ = XBM_BIT_SHUFFLE (val
);
2892 if (LA1
== ',' || LA1
== '}')
2917 /* Load XBM image IMG which will be displayed on frame F from buffer
2918 CONTENTS. END is the end of the buffer. Value is true if
2922 xbm_load_image (struct frame
*f
, struct image
*img
, unsigned char *contents
,
2929 rc
= xbm_read_bitmap_data (f
, contents
, end
, &img
->width
, &img
->height
,
2933 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
2934 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
2935 bool non_default_colors
= 0;
2938 eassert (img
->width
> 0 && img
->height
> 0);
2940 /* Get foreground and background colors, maybe allocate colors. */
2941 value
= image_spec_value (img
->spec
, QCforeground
, NULL
);
2944 foreground
= x_alloc_image_color (f
, img
, value
, foreground
);
2945 non_default_colors
= 1;
2947 value
= image_spec_value (img
->spec
, QCbackground
, NULL
);
2950 background
= x_alloc_image_color (f
, img
, value
, background
);
2951 img
->background
= background
;
2952 img
->background_valid
= 1;
2953 non_default_colors
= 1;
2956 Create_Pixmap_From_Bitmap_Data (f
, img
, data
,
2957 foreground
, background
,
2958 non_default_colors
);
2961 if (img
->pixmap
== NO_PIXMAP
)
2963 x_clear_image (f
, img
);
2964 image_error ("Unable to create X pixmap for `%s'", img
->spec
);
2970 image_error ("Error loading XBM image `%s'", img
->spec
);
2976 /* Value is true if DATA looks like an in-memory XBM file. */
2979 xbm_file_p (Lisp_Object data
)
2982 return (STRINGP (data
)
2983 && xbm_read_bitmap_data (NULL
, SDATA (data
),
2984 (SDATA (data
) + SBYTES (data
)),
2989 /* Fill image IMG which is used on frame F with pixmap data. Value is
2990 true if successful. */
2993 xbm_load (struct frame
*f
, struct image
*img
)
2996 Lisp_Object file_name
;
2998 eassert (xbm_image_p (img
->spec
));
3000 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3001 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
3002 if (STRINGP (file_name
))
3005 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
3006 if (!STRINGP (file
))
3008 image_error ("Cannot find image file `%s'", file_name
);
3013 unsigned char *contents
= slurp_file (fd
, &size
);
3014 if (contents
== NULL
)
3016 image_error ("Error loading XBM image `%s'", file
);
3020 success_p
= xbm_load_image (f
, img
, contents
, contents
+ size
);
3025 struct image_keyword fmt
[XBM_LAST
];
3027 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
3028 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
3029 bool non_default_colors
= 0;
3032 bool in_memory_file_p
= 0;
3034 /* See if data looks like an in-memory XBM file. */
3035 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
3036 in_memory_file_p
= xbm_file_p (data
);
3038 /* Parse the image specification. */
3039 memcpy (fmt
, xbm_format
, sizeof fmt
);
3040 parsed_p
= parse_image_spec (img
->spec
, fmt
, XBM_LAST
, Qxbm
);
3043 /* Get specified width, and height. */
3044 if (!in_memory_file_p
)
3046 img
->width
= XFASTINT (fmt
[XBM_WIDTH
].value
);
3047 img
->height
= XFASTINT (fmt
[XBM_HEIGHT
].value
);
3048 eassert (img
->width
> 0 && img
->height
> 0);
3049 if (!check_image_size (f
, img
->width
, img
->height
))
3051 image_size_error ();
3056 /* Get foreground and background colors, maybe allocate colors. */
3057 if (fmt
[XBM_FOREGROUND
].count
3058 && STRINGP (fmt
[XBM_FOREGROUND
].value
))
3060 foreground
= x_alloc_image_color (f
, img
, fmt
[XBM_FOREGROUND
].value
,
3062 non_default_colors
= 1;
3065 if (fmt
[XBM_BACKGROUND
].count
3066 && STRINGP (fmt
[XBM_BACKGROUND
].value
))
3068 background
= x_alloc_image_color (f
, img
, fmt
[XBM_BACKGROUND
].value
,
3070 non_default_colors
= 1;
3073 if (in_memory_file_p
)
3074 success_p
= xbm_load_image (f
, img
, SDATA (data
),
3085 int nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3087 SAFE_NALLOCA (bits
, nbytes
, img
->height
);
3089 for (i
= 0; i
< img
->height
; ++i
, p
+= nbytes
)
3091 Lisp_Object line
= AREF (data
, i
);
3093 memcpy (p
, SDATA (line
), nbytes
);
3095 memcpy (p
, bool_vector_data (line
), nbytes
);
3098 else if (STRINGP (data
))
3099 bits
= SSDATA (data
);
3101 bits
= (char *) bool_vector_data (data
);
3107 /* Windows mono bitmaps are reversed compared with X. */
3108 invertedBits
= bits
;
3109 nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3110 SAFE_NALLOCA (bits
, nbytes
, img
->height
);
3111 for (i
= 0; i
< nbytes
; i
++)
3112 bits
[i
] = XBM_BIT_SHUFFLE (invertedBits
[i
]);
3115 /* Create the pixmap. */
3117 if (x_check_image_size (0, img
->width
, img
->height
))
3118 Create_Pixmap_From_Bitmap_Data (f
, img
, bits
,
3119 foreground
, background
,
3120 non_default_colors
);
3122 img
->pixmap
= NO_PIXMAP
;
3128 image_error ("Unable to create pixmap for XBM image `%s'",
3130 x_clear_image (f
, img
);
3142 /***********************************************************************
3144 ***********************************************************************/
3146 #if defined (HAVE_XPM) || defined (HAVE_NS)
3148 static bool xpm_image_p (Lisp_Object object
);
3149 static bool xpm_load (struct frame
*f
, struct image
*img
);
3151 #endif /* HAVE_XPM || HAVE_NS */
3155 /* Indicate to xpm.h that we don't have Xlib. */
3157 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3158 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3159 #define XColor xpm_XColor
3160 #define XImage xpm_XImage
3161 #define Display xpm_Display
3162 #define PIXEL_ALREADY_TYPEDEFED
3163 #include "X11/xpm.h"
3168 #undef PIXEL_ALREADY_TYPEDEFED
3170 #include "X11/xpm.h"
3171 #endif /* HAVE_NTGUI */
3172 #endif /* HAVE_XPM */
3174 #if defined (HAVE_XPM) || defined (HAVE_NS)
3176 /* Indices of image specification fields in xpm_format, below. */
3178 enum xpm_keyword_index
3194 /* Vector of image_keyword structures describing the format
3195 of valid XPM image specifications. */
3197 static const struct image_keyword xpm_format
[XPM_LAST
] =
3199 {":type", IMAGE_SYMBOL_VALUE
, 1},
3200 {":file", IMAGE_STRING_VALUE
, 0},
3201 {":data", IMAGE_STRING_VALUE
, 0},
3202 {":ascent", IMAGE_ASCENT_VALUE
, 0},
3203 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
3204 {":relief", IMAGE_INTEGER_VALUE
, 0},
3205 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3206 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3207 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3208 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3209 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
3212 #if defined HAVE_NTGUI && defined WINDOWSNT
3213 static bool init_xpm_functions (void);
3215 #define init_xpm_functions NULL
3218 /* Structure describing the image type XPM. */
3220 static struct image_type xpm_type
=
3222 SYMBOL_INDEX (Qxpm
),
3230 #ifdef HAVE_X_WINDOWS
3232 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3233 functions for allocating image colors. Our own functions handle
3234 color allocation failures more gracefully than the ones on the XPM
3238 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3239 #define ALLOC_XPM_COLORS
3241 #endif /* USE_CAIRO */
3242 #endif /* HAVE_X_WINDOWS */
3244 #ifdef ALLOC_XPM_COLORS
3246 static struct xpm_cached_color
*xpm_cache_color (struct frame
*, char *,
3249 /* An entry in a hash table used to cache color definitions of named
3250 colors. This cache is necessary to speed up XPM image loading in
3251 case we do color allocations ourselves. Without it, we would need
3252 a call to XParseColor per pixel in the image.
3254 FIXME Now that we're using x_parse_color and its cache, reevaluate
3255 the need for this caching layer. */
3257 struct xpm_cached_color
3259 /* Next in collision chain. */
3260 struct xpm_cached_color
*next
;
3262 /* Color definition (RGB and pixel color). */
3266 char name
[FLEXIBLE_ARRAY_MEMBER
];
3269 /* The hash table used for the color cache, and its bucket vector
3272 #define XPM_COLOR_CACHE_BUCKETS 1001
3273 static struct xpm_cached_color
**xpm_color_cache
;
3275 /* Initialize the color cache. */
3278 xpm_init_color_cache (struct frame
*f
, XpmAttributes
*attrs
)
3280 size_t nbytes
= XPM_COLOR_CACHE_BUCKETS
* sizeof *xpm_color_cache
;
3281 xpm_color_cache
= xzalloc (nbytes
);
3282 init_color_table ();
3284 if (attrs
->valuemask
& XpmColorSymbols
)
3289 for (i
= 0; i
< attrs
->numsymbols
; ++i
)
3290 if (x_parse_color (f
, attrs
->colorsymbols
[i
].value
, &color
))
3292 color
.pixel
= lookup_rgb_color (f
, color
.red
, color
.green
,
3294 xpm_cache_color (f
, attrs
->colorsymbols
[i
].name
, &color
, -1);
3299 /* Free the color cache. */
3302 xpm_free_color_cache (void)
3304 struct xpm_cached_color
*p
, *next
;
3307 for (i
= 0; i
< XPM_COLOR_CACHE_BUCKETS
; ++i
)
3308 for (p
= xpm_color_cache
[i
]; p
; p
= next
)
3314 xfree (xpm_color_cache
);
3315 xpm_color_cache
= NULL
;
3316 free_color_table ();
3319 /* Return the bucket index for color named COLOR_NAME in the color
3323 xpm_color_bucket (char *color_name
)
3325 EMACS_UINT hash
= hash_string (color_name
, strlen (color_name
));
3326 return hash
% XPM_COLOR_CACHE_BUCKETS
;
3330 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3331 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3334 static struct xpm_cached_color
*
3335 xpm_cache_color (struct frame
*f
, char *color_name
, XColor
*color
, int bucket
)
3338 struct xpm_cached_color
*p
;
3341 bucket
= xpm_color_bucket (color_name
);
3343 nbytes
= offsetof (struct xpm_cached_color
, name
) + strlen (color_name
) + 1;
3344 p
= xmalloc (nbytes
);
3345 strcpy (p
->name
, color_name
);
3347 p
->next
= xpm_color_cache
[bucket
];
3348 xpm_color_cache
[bucket
] = p
;
3352 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3353 return the cached definition in *COLOR. Otherwise, make a new
3354 entry in the cache and allocate the color. Value is false if color
3355 allocation failed. */
3358 xpm_lookup_color (struct frame
*f
, char *color_name
, XColor
*color
)
3360 struct xpm_cached_color
*p
;
3361 int h
= xpm_color_bucket (color_name
);
3363 for (p
= xpm_color_cache
[h
]; p
; p
= p
->next
)
3364 if (strcmp (p
->name
, color_name
) == 0)
3369 else if (x_parse_color (f
, color_name
, color
))
3371 color
->pixel
= lookup_rgb_color (f
, color
->red
, color
->green
,
3373 p
= xpm_cache_color (f
, color_name
, color
, h
);
3375 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3376 with transparency, and it's useful. */
3377 else if (strcmp ("opaque", color_name
) == 0)
3379 memset (color
, 0, sizeof (XColor
)); /* Is this necessary/correct? */
3380 color
->pixel
= FRAME_FOREGROUND_PIXEL (f
);
3381 p
= xpm_cache_color (f
, color_name
, color
, h
);
3388 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3389 CLOSURE is a pointer to the frame on which we allocate the
3390 color. Return in *COLOR the allocated color. Value is non-zero
3394 xpm_alloc_color (Display
*dpy
, Colormap cmap
, char *color_name
, XColor
*color
,
3397 return xpm_lookup_color (closure
, color_name
, color
);
3401 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3402 is a pointer to the frame on which we allocate the color. Value is
3403 non-zero if successful. */
3406 xpm_free_colors (Display
*dpy
, Colormap cmap
, Pixel
*pixels
, int npixels
, void *closure
)
3411 #endif /* ALLOC_XPM_COLORS */
3416 /* XPM library details. */
3418 DEF_DLL_FN (void, XpmFreeAttributes
, (XpmAttributes
*));
3419 DEF_DLL_FN (int, XpmCreateImageFromBuffer
,
3420 (Display
*, char *, xpm_XImage
**,
3421 xpm_XImage
**, XpmAttributes
*));
3422 DEF_DLL_FN (int, XpmReadFileToImage
,
3423 (Display
*, char *, xpm_XImage
**,
3424 xpm_XImage
**, XpmAttributes
*));
3425 DEF_DLL_FN (void, XImageFree
, (xpm_XImage
*));
3428 init_xpm_functions (void)
3432 if (!(library
= w32_delayed_load (Qxpm
)))
3435 LOAD_DLL_FN (library
, XpmFreeAttributes
);
3436 LOAD_DLL_FN (library
, XpmCreateImageFromBuffer
);
3437 LOAD_DLL_FN (library
, XpmReadFileToImage
);
3438 LOAD_DLL_FN (library
, XImageFree
);
3443 # undef XpmCreateImageFromBuffer
3444 # undef XpmFreeAttributes
3445 # undef XpmReadFileToImage
3447 # define XImageFree fn_XImageFree
3448 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3449 # define XpmFreeAttributes fn_XpmFreeAttributes
3450 # define XpmReadFileToImage fn_XpmReadFileToImage
3452 #endif /* WINDOWSNT */
3454 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3455 for XPM images. Such a list must consist of conses whose car and
3459 xpm_valid_color_symbols_p (Lisp_Object color_symbols
)
3461 while (CONSP (color_symbols
))
3463 Lisp_Object sym
= XCAR (color_symbols
);
3465 || !STRINGP (XCAR (sym
))
3466 || !STRINGP (XCDR (sym
)))
3468 color_symbols
= XCDR (color_symbols
);
3471 return NILP (color_symbols
);
3475 /* Value is true if OBJECT is a valid XPM image specification. */
3478 xpm_image_p (Lisp_Object object
)
3480 struct image_keyword fmt
[XPM_LAST
];
3481 memcpy (fmt
, xpm_format
, sizeof fmt
);
3482 return (parse_image_spec (object
, fmt
, XPM_LAST
, Qxpm
)
3483 /* Either `:file' or `:data' must be present. */
3484 && fmt
[XPM_FILE
].count
+ fmt
[XPM_DATA
].count
== 1
3485 /* Either no `:color-symbols' or it's a list of conses
3486 whose car and cdr are strings. */
3487 && (fmt
[XPM_COLOR_SYMBOLS
].count
== 0
3488 || xpm_valid_color_symbols_p (fmt
[XPM_COLOR_SYMBOLS
].value
)));
3491 #endif /* HAVE_XPM || HAVE_NS */
3493 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3495 x_create_bitmap_from_xpm_data (struct frame
*f
, const char **bits
)
3497 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
3500 XpmAttributes attrs
;
3501 Pixmap bitmap
, mask
;
3503 memset (&attrs
, 0, sizeof attrs
);
3505 attrs
.visual
= FRAME_X_VISUAL (f
);
3506 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3507 attrs
.valuemask
|= XpmVisual
;
3508 attrs
.valuemask
|= XpmColormap
;
3510 #ifdef ALLOC_XPM_COLORS
3511 attrs
.color_closure
= f
;
3512 attrs
.alloc_color
= xpm_alloc_color
;
3513 attrs
.free_colors
= xpm_free_colors
;
3514 attrs
.valuemask
|= XpmAllocColor
| XpmFreeColors
| XpmColorClosure
;
3515 xpm_init_color_cache (f
, &attrs
);
3518 rc
= XpmCreatePixmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3519 (char **) bits
, &bitmap
, &mask
, &attrs
);
3520 if (rc
!= XpmSuccess
)
3522 XpmFreeAttributes (&attrs
);
3526 id
= x_allocate_bitmap_record (f
);
3527 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
3528 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
3529 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
3530 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
3531 dpyinfo
->bitmaps
[id
- 1].height
= attrs
.height
;
3532 dpyinfo
->bitmaps
[id
- 1].width
= attrs
.width
;
3533 dpyinfo
->bitmaps
[id
- 1].depth
= attrs
.depth
;
3534 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
3536 #ifdef ALLOC_XPM_COLORS
3537 xpm_free_color_cache ();
3539 XpmFreeAttributes (&attrs
);
3542 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3544 /* Load image IMG which will be displayed on frame F. Value is
3545 true if successful. */
3550 xpm_load (struct frame
*f
, struct image
*img
)
3553 XpmAttributes attrs
;
3554 Lisp_Object specified_file
, color_symbols
;
3559 xpm_XImage
* xpm_image
= NULL
, * xpm_mask
= NULL
;
3560 #endif /* HAVE_NTGUI */
3562 /* Configure the XPM lib. Use the visual of frame F. Allocate
3563 close colors. Return colors allocated. */
3564 memset (&attrs
, 0, sizeof attrs
);
3567 attrs
.visual
= FRAME_X_VISUAL (f
);
3568 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3569 attrs
.valuemask
|= XpmVisual
;
3570 attrs
.valuemask
|= XpmColormap
;
3571 #endif /* HAVE_NTGUI */
3573 #ifdef ALLOC_XPM_COLORS
3574 /* Allocate colors with our own functions which handle
3575 failing color allocation more gracefully. */
3576 attrs
.color_closure
= f
;
3577 attrs
.alloc_color
= xpm_alloc_color
;
3578 attrs
.free_colors
= xpm_free_colors
;
3579 attrs
.valuemask
|= XpmAllocColor
| XpmFreeColors
| XpmColorClosure
;
3580 #else /* not ALLOC_XPM_COLORS */
3581 /* Let the XPM lib allocate colors. */
3582 attrs
.valuemask
|= XpmReturnAllocPixels
;
3583 #ifdef XpmAllocCloseColors
3584 attrs
.alloc_close_colors
= 1;
3585 attrs
.valuemask
|= XpmAllocCloseColors
;
3586 #else /* not XpmAllocCloseColors */
3587 attrs
.closeness
= 600;
3588 attrs
.valuemask
|= XpmCloseness
;
3589 #endif /* not XpmAllocCloseColors */
3590 #endif /* ALLOC_XPM_COLORS */
3592 /* If image specification contains symbolic color definitions, add
3593 these to `attrs'. */
3594 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
3595 if (CONSP (color_symbols
))
3598 XpmColorSymbol
*xpm_syms
;
3601 attrs
.valuemask
|= XpmColorSymbols
;
3603 /* Count number of symbols. */
3604 attrs
.numsymbols
= 0;
3605 for (tail
= color_symbols
; CONSP (tail
); tail
= XCDR (tail
))
3608 /* Allocate an XpmColorSymbol array. */
3609 SAFE_NALLOCA (xpm_syms
, 1, attrs
.numsymbols
);
3610 size
= attrs
.numsymbols
* sizeof *xpm_syms
;
3611 memset (xpm_syms
, 0, size
);
3612 attrs
.colorsymbols
= xpm_syms
;
3614 /* Fill the color symbol array. */
3615 for (tail
= color_symbols
, i
= 0;
3617 ++i
, tail
= XCDR (tail
))
3621 char *empty_string
= (char *) "";
3623 if (!CONSP (XCAR (tail
)))
3625 xpm_syms
[i
].name
= empty_string
;
3626 xpm_syms
[i
].value
= empty_string
;
3629 name
= XCAR (XCAR (tail
));
3630 color
= XCDR (XCAR (tail
));
3632 SAFE_ALLOCA_STRING (xpm_syms
[i
].name
, name
);
3634 xpm_syms
[i
].name
= empty_string
;
3635 if (STRINGP (color
))
3636 SAFE_ALLOCA_STRING (xpm_syms
[i
].value
, color
);
3638 xpm_syms
[i
].value
= empty_string
;
3642 /* Create a pixmap for the image, either from a file, or from a
3643 string buffer containing data in the same format as an XPM file. */
3644 #ifdef ALLOC_XPM_COLORS
3645 xpm_init_color_cache (f
, &attrs
);
3648 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
3652 HDC frame_dc
= get_frame_dc (f
);
3653 hdc
= CreateCompatibleDC (frame_dc
);
3654 release_frame_dc (f
, frame_dc
);
3656 #endif /* HAVE_NTGUI */
3658 if (STRINGP (specified_file
))
3660 Lisp_Object file
= x_find_image_file (specified_file
);
3661 if (!STRINGP (file
))
3663 image_error ("Cannot find image file `%s'", specified_file
);
3664 #ifdef ALLOC_XPM_COLORS
3665 xpm_free_color_cache ();
3671 file
= ENCODE_FILE (file
);
3674 /* FILE is encoded in UTF-8, but image libraries on Windows
3675 support neither UTF-8 nor UTF-16 encoded file names. So we
3676 need to re-encode it in ANSI. */
3677 file
= ansi_encode_filename (file
);
3679 /* XpmReadFileToPixmap is not available in the Windows port of
3680 libxpm. But XpmReadFileToImage almost does what we want. */
3681 rc
= XpmReadFileToImage (&hdc
, SSDATA (file
),
3682 &xpm_image
, &xpm_mask
,
3685 rc
= XpmReadFileToImage (FRAME_X_DISPLAY (f
), SSDATA (file
),
3686 &img
->ximg
, &img
->mask_img
,
3688 #endif /* HAVE_NTGUI */
3692 Lisp_Object buffer
= image_spec_value (img
->spec
, QCdata
, NULL
);
3693 if (!STRINGP (buffer
))
3695 image_error ("Invalid image data `%s'", buffer
);
3696 #ifdef ALLOC_XPM_COLORS
3697 xpm_free_color_cache ();
3703 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3704 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3705 rc
= XpmCreateImageFromBuffer (&hdc
, SSDATA (buffer
),
3706 &xpm_image
, &xpm_mask
,
3709 rc
= XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f
), SSDATA (buffer
),
3710 &img
->ximg
, &img
->mask_img
,
3712 #endif /* HAVE_NTGUI */
3716 // Load very specific Xpm:s.
3717 if (rc
== XpmSuccess
3718 && img
->ximg
->format
== ZPixmap
3719 && img
->ximg
->bits_per_pixel
== 32
3720 && (! img
->mask_img
|| img
->mask_img
->bits_per_pixel
== 1))
3722 int width
= img
->ximg
->width
;
3723 int height
= img
->ximg
->height
;
3724 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
3726 uint32_t *od
= (uint32_t *)data
;
3727 uint32_t *id
= (uint32_t *)img
->ximg
->data
;
3728 char *mid
= img
->mask_img
? img
->mask_img
->data
: 0;
3729 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
3731 for (i
= 0; i
< height
; ++i
)
3734 for (k
= 0; k
< width
; ++k
)
3736 int idx
= i
* img
->ximg
->bytes_per_line
/4 + k
;
3737 int maskidx
= mid
? i
* img
->mask_img
->bytes_per_line
+ k
/8 : 0;
3738 int mask
= mid
? mid
[maskidx
] & (1 << (k
% 8)) : 1;
3740 if (mask
) od
[idx
] = id
[idx
] + 0xff000000; // ff => full alpha
3741 else od
[idx
] = bgcolor
;
3745 create_cairo_image_surface (img
, data
, width
, height
);
3749 rc
= XpmFileInvalid
;
3750 x_clear_image (f
, img
);
3753 #ifdef HAVE_X_WINDOWS
3754 if (rc
== XpmSuccess
)
3756 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3757 img
->ximg
->width
, img
->ximg
->height
,
3759 if (img
->pixmap
== NO_PIXMAP
)
3761 x_clear_image (f
, img
);
3764 else if (img
->mask_img
)
3766 img
->mask
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3767 img
->mask_img
->width
,
3768 img
->mask_img
->height
,
3769 img
->mask_img
->depth
);
3770 if (img
->mask
== NO_PIXMAP
)
3772 x_clear_image (f
, img
);
3778 #endif /* ! USE_CAIRO */
3780 if (rc
== XpmSuccess
)
3782 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3783 img
->colors
= colors_in_color_table (&img
->ncolors
);
3784 #else /* not ALLOC_XPM_COLORS */
3788 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3789 plus some duplicate attributes. */
3790 if (xpm_image
&& xpm_image
->bitmap
)
3792 img
->pixmap
= xpm_image
->bitmap
;
3793 /* XImageFree in libXpm frees XImage struct without destroying
3794 the bitmap, which is what we want. */
3795 XImageFree (xpm_image
);
3797 if (xpm_mask
&& xpm_mask
->bitmap
)
3799 /* The mask appears to be inverted compared with what we expect.
3800 TODO: invert our expectations. See other places where we
3801 have to invert bits because our idea of masks is backwards. */
3803 old_obj
= SelectObject (hdc
, xpm_mask
->bitmap
);
3805 PatBlt (hdc
, 0, 0, xpm_mask
->width
, xpm_mask
->height
, DSTINVERT
);
3806 SelectObject (hdc
, old_obj
);
3808 img
->mask
= xpm_mask
->bitmap
;
3809 XImageFree (xpm_mask
);
3814 #endif /* HAVE_NTGUI */
3816 /* Remember allocated colors. */
3817 img
->colors
= xnmalloc (attrs
.nalloc_pixels
, sizeof *img
->colors
);
3818 img
->ncolors
= attrs
.nalloc_pixels
;
3819 for (i
= 0; i
< attrs
.nalloc_pixels
; ++i
)
3821 img
->colors
[i
] = attrs
.alloc_pixels
[i
];
3822 #ifdef DEBUG_X_COLORS
3823 register_color (img
->colors
[i
]);
3826 #endif /* not ALLOC_XPM_COLORS */
3828 img
->width
= attrs
.width
;
3829 img
->height
= attrs
.height
;
3830 eassert (img
->width
> 0 && img
->height
> 0);
3832 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3833 XpmFreeAttributes (&attrs
);
3835 #ifdef HAVE_X_WINDOWS
3836 /* Maybe fill in the background field while we have ximg handy. */
3837 IMAGE_BACKGROUND (img
, f
, img
->ximg
);
3839 /* Fill in the background_transparent field while we have the
3841 image_background_transparent (img
, f
, img
->mask_img
);
3848 #endif /* HAVE_NTGUI */
3853 image_error ("Error opening XPM file (%s)", img
->spec
);
3856 case XpmFileInvalid
:
3857 image_error ("Invalid XPM file (%s)", img
->spec
);
3861 image_error ("Out of memory (%s)", img
->spec
);
3864 case XpmColorFailed
:
3865 image_error ("Color allocation error (%s)", img
->spec
);
3869 image_error ("Unknown error (%s)", img
->spec
);
3874 #ifdef ALLOC_XPM_COLORS
3875 xpm_free_color_cache ();
3878 return rc
== XpmSuccess
;
3881 #endif /* HAVE_XPM */
3883 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3885 /* XPM support functions for NS where libxpm is not available.
3886 Only XPM version 3 (without any extensions) is supported. */
3888 static void xpm_put_color_table_v (Lisp_Object
, const unsigned char *,
3890 static Lisp_Object
xpm_get_color_table_v (Lisp_Object
,
3891 const unsigned char *, int);
3892 static void xpm_put_color_table_h (Lisp_Object
, const unsigned char *,
3894 static Lisp_Object
xpm_get_color_table_h (Lisp_Object
,
3895 const unsigned char *, int);
3897 /* Tokens returned from xpm_scan. */
3906 /* Scan an XPM data and return a character (< 256) or a token defined
3907 by enum xpm_token above. *S and END are the start (inclusive) and
3908 the end (exclusive) addresses of the data, respectively. Advance
3909 *S while scanning. If token is either XPM_TK_IDENT or
3910 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3911 length of the corresponding token, respectively. */
3914 xpm_scan (const unsigned char **s
,
3915 const unsigned char *end
,
3916 const unsigned char **beg
,
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
,
3983 const unsigned char *,
3986 Lisp_Object (**get_func
) (Lisp_Object
,
3987 const unsigned char *,
3990 *put_func
= xpm_put_color_table_v
;
3991 *get_func
= xpm_get_color_table_v
;
3992 return Fmake_vector (make_number (256), Qnil
);
3996 xpm_put_color_table_v (Lisp_Object color_table
,
3997 const unsigned char *chars_start
,
4001 ASET (color_table
, *chars_start
, color
);
4005 xpm_get_color_table_v (Lisp_Object color_table
,
4006 const unsigned char *chars_start
,
4009 return AREF (color_table
, *chars_start
);
4013 xpm_make_color_table_h (void (**put_func
) (Lisp_Object
,
4014 const unsigned char *,
4017 Lisp_Object (**get_func
) (Lisp_Object
,
4018 const unsigned char *,
4021 *put_func
= xpm_put_color_table_h
;
4022 *get_func
= xpm_get_color_table_h
;
4023 return make_hash_table (hashtest_equal
, make_number (DEFAULT_HASH_SIZE
),
4024 make_float (DEFAULT_REHASH_SIZE
),
4025 make_float (DEFAULT_REHASH_THRESHOLD
),
4030 xpm_put_color_table_h (Lisp_Object color_table
,
4031 const unsigned char *chars_start
,
4035 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4036 EMACS_UINT hash_code
;
4037 Lisp_Object chars
= make_unibyte_string (chars_start
, chars_len
);
4039 hash_lookup (table
, chars
, &hash_code
);
4040 hash_put (table
, chars
, color
, hash_code
);
4044 xpm_get_color_table_h (Lisp_Object color_table
,
4045 const unsigned char *chars_start
,
4048 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4050 hash_lookup (table
, make_unibyte_string (chars_start
, chars_len
), NULL
);
4052 return i
>= 0 ? HASH_VALUE (table
, i
) : Qnil
;
4055 enum xpm_color_key
{
4063 static const char xpm_color_key_strings
[][4] = {"s", "m", "g4", "g", "c"};
4066 xpm_str_to_color_key (const char *s
)
4070 for (i
= 0; i
< ARRAYELTS (xpm_color_key_strings
); i
++)
4071 if (strcmp (xpm_color_key_strings
[i
], s
) == 0)
4077 xpm_load_image (struct frame
*f
,
4079 const unsigned char *contents
,
4080 const unsigned char *end
)
4082 const unsigned char *s
= contents
, *beg
, *str
;
4083 unsigned char buffer
[BUFSIZ
];
4084 int width
, height
, x
, y
;
4085 int num_colors
, chars_per_pixel
;
4088 void (*put_color_table
) (Lisp_Object
, const unsigned char *, int, Lisp_Object
);
4089 Lisp_Object (*get_color_table
) (Lisp_Object
, const unsigned char *, int);
4090 Lisp_Object frame
, color_symbols
, color_table
;
4092 bool have_mask
= false;
4093 XImagePtr ximg
= NULL
, mask_img
= NULL
;
4096 LA1 = xpm_scan (&s, end, &beg, &len)
4098 #define expect(TOKEN) \
4101 if (LA1 != (TOKEN)) \
4107 #define expect_ident(IDENT) \
4108 if (LA1 == XPM_TK_IDENT \
4109 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4114 if (!(end
- s
>= 9 && memcmp (s
, "/* XPM */", 9) == 0))
4118 expect_ident ("static");
4119 expect_ident ("char");
4121 expect (XPM_TK_IDENT
);
4126 expect (XPM_TK_STRING
);
4129 memcpy (buffer
, beg
, len
);
4131 if (sscanf (buffer
, "%d %d %d %d", &width
, &height
,
4132 &num_colors
, &chars_per_pixel
) != 4
4133 || width
<= 0 || height
<= 0
4134 || num_colors
<= 0 || chars_per_pixel
<= 0)
4137 if (!check_image_size (f
, width
, height
))
4139 image_size_error ();
4143 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0)
4145 || !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
4150 image_error ("Image too large");
4156 XSETFRAME (frame
, f
);
4157 if (!NILP (Fxw_display_color_p (frame
)))
4158 best_key
= XPM_COLOR_KEY_C
;
4159 else if (!NILP (Fx_display_grayscale_p (frame
)))
4160 best_key
= (XFASTINT (Fx_display_planes (frame
)) > 2
4161 ? XPM_COLOR_KEY_G
: XPM_COLOR_KEY_G4
);
4163 best_key
= XPM_COLOR_KEY_M
;
4165 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
4166 if (chars_per_pixel
== 1)
4167 color_table
= xpm_make_color_table_v (&put_color_table
,
4170 color_table
= xpm_make_color_table_h (&put_color_table
,
4173 while (num_colors
-- > 0)
4175 char *color
, *max_color
;
4176 int key
, next_key
, max_key
= 0;
4177 Lisp_Object symbol_color
= Qnil
, color_val
;
4180 expect (XPM_TK_STRING
);
4181 if (len
<= chars_per_pixel
|| len
>= BUFSIZ
+ chars_per_pixel
)
4183 memcpy (buffer
, beg
+ chars_per_pixel
, len
- chars_per_pixel
);
4184 buffer
[len
- chars_per_pixel
] = '\0';
4186 str
= strtok (buffer
, " \t");
4189 key
= xpm_str_to_color_key (str
);
4194 color
= strtok (NULL
, " \t");
4198 while ((str
= strtok (NULL
, " \t")) != NULL
)
4200 next_key
= xpm_str_to_color_key (str
);
4203 color
[strlen (color
)] = ' ';
4206 if (key
== XPM_COLOR_KEY_S
)
4208 if (NILP (symbol_color
))
4209 symbol_color
= build_string (color
);
4211 else if (max_key
< key
&& key
<= best_key
)
4221 if (!NILP (color_symbols
) && !NILP (symbol_color
))
4223 Lisp_Object specified_color
= Fassoc (symbol_color
, color_symbols
);
4225 if (CONSP (specified_color
) && STRINGP (XCDR (specified_color
)))
4227 if (xstrcasecmp (SSDATA (XCDR (specified_color
)), "None") == 0)
4229 else if (x_defined_color (f
, SSDATA (XCDR (specified_color
)),
4231 color_val
= make_number (cdef
.pixel
);
4234 if (NILP (color_val
) && max_key
> 0)
4236 if (xstrcasecmp (max_color
, "None") == 0)
4238 else if (x_defined_color (f
, max_color
, &cdef
, 0))
4239 color_val
= make_number (cdef
.pixel
);
4241 if (!NILP (color_val
))
4242 (*put_color_table
) (color_table
, beg
, chars_per_pixel
, color_val
);
4247 for (y
= 0; y
< height
; y
++)
4249 expect (XPM_TK_STRING
);
4251 if (len
< width
* chars_per_pixel
)
4253 for (x
= 0; x
< width
; x
++, str
+= chars_per_pixel
)
4255 Lisp_Object color_val
=
4256 (*get_color_table
) (color_table
, str
, chars_per_pixel
);
4258 XPutPixel (ximg
, x
, y
,
4259 (INTEGERP (color_val
) ? XINT (color_val
)
4260 : FRAME_FOREGROUND_PIXEL (f
)));
4262 XPutPixel (mask_img
, x
, y
,
4263 (!EQ (color_val
, Qt
) ? PIX_MASK_DRAW
4264 : (have_mask
= true, PIX_MASK_RETAIN
)));
4266 if (EQ (color_val
, Qt
))
4267 ns_set_alpha (ximg
, x
, y
, 0);
4275 img
->height
= height
;
4277 /* Maybe fill in the background field while we have ximg handy. */
4278 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
4279 IMAGE_BACKGROUND (img
, f
, ximg
);
4281 image_put_x_image (f
, img
, ximg
, 0);
4285 /* Fill in the background_transparent field while we have the
4287 image_background_transparent (img
, f
, mask_img
);
4289 image_put_x_image (f
, img
, mask_img
, 1);
4293 x_destroy_x_image (mask_img
);
4294 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4300 image_error ("Invalid XPM file (%s)", img
->spec
);
4301 x_destroy_x_image (ximg
);
4302 x_destroy_x_image (mask_img
);
4303 x_clear_image (f
, img
);
4312 xpm_load (struct frame
*f
,
4316 Lisp_Object file_name
;
4318 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4319 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
4320 if (STRINGP (file_name
))
4323 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
4324 if (!STRINGP (file
))
4326 image_error ("Cannot find image file `%s'", file_name
);
4331 unsigned char *contents
= slurp_file (fd
, &size
);
4332 if (contents
== NULL
)
4334 image_error ("Error loading XPM image `%s'", file
);
4338 success_p
= xpm_load_image (f
, img
, contents
, contents
+ size
);
4345 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
4346 if (!STRINGP (data
))
4348 image_error ("Invalid image data `%s'", data
);
4351 success_p
= xpm_load_image (f
, img
, SDATA (data
),
4352 SDATA (data
) + SBYTES (data
));
4358 #endif /* HAVE_NS && !HAVE_XPM */
4362 /***********************************************************************
4364 ***********************************************************************/
4366 #ifdef COLOR_TABLE_SUPPORT
4368 /* An entry in the color table mapping an RGB color to a pixel color. */
4373 unsigned long pixel
;
4375 /* Next in color table collision list. */
4376 struct ct_color
*next
;
4379 /* The bucket vector size to use. Must be prime. */
4383 /* Value is a hash of the RGB color given by R, G, and B. */
4386 ct_hash_rgb (unsigned r
, unsigned g
, unsigned b
)
4388 return (r
<< 16) ^ (g
<< 8) ^ b
;
4391 /* The color hash table. */
4393 static struct ct_color
**ct_table
;
4395 /* Number of entries in the color table. */
4397 static int ct_colors_allocated
;
4400 ct_colors_allocated_max
=
4402 min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof (unsigned long))
4405 /* Initialize the color table. */
4408 init_color_table (void)
4410 int size
= CT_SIZE
* sizeof (*ct_table
);
4411 ct_table
= xzalloc (size
);
4412 ct_colors_allocated
= 0;
4416 /* Free memory associated with the color table. */
4419 free_color_table (void)
4422 struct ct_color
*p
, *next
;
4424 for (i
= 0; i
< CT_SIZE
; ++i
)
4425 for (p
= ct_table
[i
]; p
; p
= next
)
4436 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4437 entry for that color already is in the color table, return the
4438 pixel color of that entry. Otherwise, allocate a new color for R,
4439 G, B, and make an entry in the color table. */
4441 static unsigned long
4442 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4444 unsigned hash
= ct_hash_rgb (r
, g
, b
);
4445 int i
= hash
% CT_SIZE
;
4447 Display_Info
*dpyinfo
;
4449 /* Handle TrueColor visuals specially, which improves performance by
4450 two orders of magnitude. Freeing colors on TrueColor visuals is
4451 a nop, and pixel colors specify RGB values directly. See also
4452 the Xlib spec, chapter 3.1. */
4453 dpyinfo
= FRAME_DISPLAY_INFO (f
);
4454 if (dpyinfo
->red_bits
> 0)
4456 /* Apply gamma-correction like normal color allocation does. */
4460 color
.red
= r
, color
.green
= g
, color
.blue
= b
;
4461 gamma_correct (f
, &color
);
4462 r
= color
.red
, g
= color
.green
, b
= color
.blue
;
4465 return x_make_truecolor_pixel (dpyinfo
, r
, g
, b
);
4468 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4469 if (p
->r
== r
&& p
->g
== g
&& p
->b
== b
)
4475 #ifdef HAVE_X_WINDOWS
4483 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4484 return FRAME_FOREGROUND_PIXEL (f
);
4486 #ifdef HAVE_X_WINDOWS
4491 cmap
= FRAME_X_COLORMAP (f
);
4492 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4495 ++ct_colors_allocated
;
4496 p
= xmalloc (sizeof *p
);
4500 p
->pixel
= color
.pixel
;
4501 p
->next
= ct_table
[i
];
4505 return FRAME_FOREGROUND_PIXEL (f
);
4509 color
= PALETTERGB (r
, g
, b
);
4511 color
= RGB_TO_ULONG (r
, g
, b
);
4512 #endif /* HAVE_NTGUI */
4513 ++ct_colors_allocated
;
4514 p
= xmalloc (sizeof *p
);
4519 p
->next
= ct_table
[i
];
4521 #endif /* HAVE_X_WINDOWS */
4529 /* Look up pixel color PIXEL which is used on frame F in the color
4530 table. If not already present, allocate it. Value is PIXEL. */
4532 static unsigned long
4533 lookup_pixel_color (struct frame
*f
, unsigned long pixel
)
4535 int i
= pixel
% CT_SIZE
;
4538 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4539 if (p
->pixel
== pixel
)
4548 if (ct_colors_allocated
>= ct_colors_allocated_max
)
4549 return FRAME_FOREGROUND_PIXEL (f
);
4551 #ifdef HAVE_X_WINDOWS
4552 cmap
= FRAME_X_COLORMAP (f
);
4553 color
.pixel
= pixel
;
4554 x_query_color (f
, &color
);
4555 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4558 cmap
= DefaultColormapOfScreen (FRAME_X_SCREEN (f
));
4559 color
.pixel
= pixel
;
4560 XQueryColor (NULL
, cmap
, &color
);
4561 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4563 #endif /* HAVE_X_WINDOWS */
4567 ++ct_colors_allocated
;
4569 p
= xmalloc (sizeof *p
);
4574 p
->next
= ct_table
[i
];
4578 return FRAME_FOREGROUND_PIXEL (f
);
4584 /* Value is a vector of all pixel colors contained in the color table,
4585 allocated via xmalloc. Set *N to the number of colors. */
4587 static unsigned long *
4588 colors_in_color_table (int *n
)
4592 unsigned long *colors
;
4594 if (ct_colors_allocated
== 0)
4601 colors
= xmalloc (ct_colors_allocated
* sizeof *colors
);
4602 *n
= ct_colors_allocated
;
4604 for (i
= j
= 0; i
< CT_SIZE
; ++i
)
4605 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4606 colors
[j
++] = p
->pixel
;
4612 #else /* COLOR_TABLE_SUPPORT */
4614 static unsigned long
4615 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4618 return PALETTERGB (r
>> 8, g
>> 8, b
>> 8);
4619 #elif defined HAVE_NS
4620 return RGB_TO_ULONG (r
>> 8, g
>> 8, b
>> 8);
4622 xsignal1 (Qfile_error
,
4623 build_string ("This Emacs mishandles this image file type"));
4628 init_color_table (void)
4631 #endif /* COLOR_TABLE_SUPPORT */
4634 /***********************************************************************
4636 ***********************************************************************/
4638 /* Edge detection matrices for different edge-detection
4641 static int emboss_matrix
[9] = {
4643 2, -1, 0, /* y - 1 */
4645 0, 1, -2 /* y + 1 */
4648 static int laplace_matrix
[9] = {
4650 1, 0, 0, /* y - 1 */
4652 0, 0, -1 /* y + 1 */
4655 /* Value is the intensity of the color whose red/green/blue values
4658 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4661 /* On frame F, return an array of XColor structures describing image
4662 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4663 means also fill the red/green/blue members of the XColor
4664 structures. Value is a pointer to the array of XColors structures,
4665 allocated with xmalloc; it must be freed by the caller. */
4668 x_to_xcolors (struct frame
*f
, struct image
*img
, bool rgb_p
)
4672 XImagePtr_or_DC ximg
;
4676 #endif /* HAVE_NTGUI */
4678 if (INT_MULTIPLY_WRAPV (sizeof *colors
, img
->width
, &nbytes
)
4679 || INT_MULTIPLY_WRAPV (img
->height
, nbytes
, &nbytes
)
4680 || SIZE_MAX
< nbytes
)
4681 memory_full (SIZE_MAX
);
4682 colors
= xmalloc (nbytes
);
4684 /* Get the X image or create a memory device context for IMG. */
4685 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4687 /* Fill the `pixel' members of the XColor array. I wished there
4688 were an easy and portable way to circumvent XGetPixel. */
4690 for (y
= 0; y
< img
->height
; ++y
)
4692 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4694 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4695 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4697 x_query_colors (f
, row
, img
->width
);
4701 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4703 /* W32_TODO: palette support needed here? */
4704 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4707 p
->red
= RED16_FROM_ULONG (p
->pixel
);
4708 p
->green
= GREEN16_FROM_ULONG (p
->pixel
);
4709 p
->blue
= BLUE16_FROM_ULONG (p
->pixel
);
4712 #endif /* HAVE_X_WINDOWS */
4715 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
4722 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4723 created with CreateDIBSection, with the pointer to the bit values
4724 stored in ximg->data. */
4727 XPutPixel (XImagePtr ximg
, int x
, int y
, COLORREF color
)
4729 int width
= ximg
->info
.bmiHeader
.biWidth
;
4730 unsigned char * pixel
;
4732 /* True color images. */
4733 if (ximg
->info
.bmiHeader
.biBitCount
== 24)
4735 int rowbytes
= width
* 3;
4736 /* Ensure scanlines are aligned on 4 byte boundaries. */
4738 rowbytes
+= 4 - (rowbytes
% 4);
4740 pixel
= ximg
->data
+ y
* rowbytes
+ x
* 3;
4741 /* Windows bitmaps are in BGR order. */
4742 *pixel
= GetBValue (color
);
4743 *(pixel
+ 1) = GetGValue (color
);
4744 *(pixel
+ 2) = GetRValue (color
);
4746 /* Monochrome images. */
4747 else if (ximg
->info
.bmiHeader
.biBitCount
== 1)
4749 int rowbytes
= width
/ 8;
4750 /* Ensure scanlines are aligned on 4 byte boundaries. */
4752 rowbytes
+= 4 - (rowbytes
% 4);
4753 pixel
= ximg
->data
+ y
* rowbytes
+ x
/ 8;
4754 /* Filter out palette info. */
4755 if (color
& 0x00ffffff)
4756 *pixel
= *pixel
| (1 << x
% 8);
4758 *pixel
= *pixel
& ~(1 << x
% 8);
4761 image_error ("XPutPixel: palette image not supported");
4764 #endif /* HAVE_NTGUI */
4766 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4767 RGB members are set. F is the frame on which this all happens.
4768 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4771 x_from_xcolors (struct frame
*f
, struct image
*img
, XColor
*colors
)
4774 XImagePtr oimg
= NULL
;
4777 init_color_table ();
4779 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_COLORS
);
4780 image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 0,
4783 for (y
= 0; y
< img
->height
; ++y
)
4784 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4786 unsigned long pixel
;
4787 pixel
= lookup_rgb_color (f
, p
->red
, p
->green
, p
->blue
);
4788 XPutPixel (oimg
, x
, y
, pixel
);
4793 image_put_x_image (f
, img
, oimg
, 0);
4794 #ifdef COLOR_TABLE_SUPPORT
4795 img
->colors
= colors_in_color_table (&img
->ncolors
);
4796 free_color_table ();
4797 #endif /* COLOR_TABLE_SUPPORT */
4801 /* On frame F, perform edge-detection on image IMG.
4803 MATRIX is a nine-element array specifying the transformation
4804 matrix. See emboss_matrix for an example.
4806 COLOR_ADJUST is a color adjustment added to each pixel of the
4810 x_detect_edges (struct frame
*f
, struct image
*img
, int *matrix
, int color_adjust
)
4812 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4817 for (i
= sum
= 0; i
< 9; ++i
)
4818 sum
+= eabs (matrix
[i
]);
4820 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4822 if (INT_MULTIPLY_WRAPV (sizeof *new, img
->width
, &nbytes
)
4823 || INT_MULTIPLY_WRAPV (img
->height
, nbytes
, &nbytes
))
4824 memory_full (SIZE_MAX
);
4825 new = xmalloc (nbytes
);
4827 for (y
= 0; y
< img
->height
; ++y
)
4829 p
= COLOR (new, 0, y
);
4830 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4831 p
= COLOR (new, img
->width
- 1, y
);
4832 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4835 for (x
= 1; x
< img
->width
- 1; ++x
)
4837 p
= COLOR (new, x
, 0);
4838 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4839 p
= COLOR (new, x
, img
->height
- 1);
4840 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4843 for (y
= 1; y
< img
->height
- 1; ++y
)
4845 p
= COLOR (new, 1, y
);
4847 for (x
= 1; x
< img
->width
- 1; ++x
, ++p
)
4849 int r
, g
, b
, yy
, xx
;
4852 for (yy
= y
- 1; yy
< y
+ 2; ++yy
)
4853 for (xx
= x
- 1; xx
< x
+ 2; ++xx
, ++i
)
4856 XColor
*t
= COLOR (colors
, xx
, yy
);
4857 r
+= matrix
[i
] * t
->red
;
4858 g
+= matrix
[i
] * t
->green
;
4859 b
+= matrix
[i
] * t
->blue
;
4862 r
= (r
/ sum
+ color_adjust
) & 0xffff;
4863 g
= (g
/ sum
+ color_adjust
) & 0xffff;
4864 b
= (b
/ sum
+ color_adjust
) & 0xffff;
4865 p
->red
= p
->green
= p
->blue
= COLOR_INTENSITY (r
, g
, b
);
4870 x_from_xcolors (f
, img
, new);
4876 /* Perform the pre-defined `emboss' edge-detection on image IMG
4880 x_emboss (struct frame
*f
, struct image
*img
)
4882 x_detect_edges (f
, img
, emboss_matrix
, 0xffff / 2);
4886 /* Transform image IMG which is used on frame F with a Laplace
4887 edge-detection algorithm. The result is an image that can be used
4888 to draw disabled buttons, for example. */
4891 x_laplace (struct frame
*f
, struct image
*img
)
4893 x_detect_edges (f
, img
, laplace_matrix
, 45000);
4897 /* Perform edge-detection on image IMG on frame F, with specified
4898 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4900 MATRIX must be either
4902 - a list of at least 9 numbers in row-major form
4903 - a vector of at least 9 numbers
4905 COLOR_ADJUST nil means use a default; otherwise it must be a
4909 x_edge_detection (struct frame
*f
, struct image
*img
, Lisp_Object matrix
,
4910 Lisp_Object color_adjust
)
4918 i
< 9 && CONSP (matrix
) && NUMBERP (XCAR (matrix
));
4919 ++i
, matrix
= XCDR (matrix
))
4920 trans
[i
] = XFLOATINT (XCAR (matrix
));
4922 else if (VECTORP (matrix
) && ASIZE (matrix
) >= 9)
4924 for (i
= 0; i
< 9 && NUMBERP (AREF (matrix
, i
)); ++i
)
4925 trans
[i
] = XFLOATINT (AREF (matrix
, i
));
4928 if (NILP (color_adjust
))
4929 color_adjust
= make_number (0xffff / 2);
4931 if (i
== 9 && NUMBERP (color_adjust
))
4932 x_detect_edges (f
, img
, trans
, XFLOATINT (color_adjust
));
4936 /* Transform image IMG on frame F so that it looks disabled. */
4939 x_disable_image (struct frame
*f
, struct image
*img
)
4941 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
4943 int n_planes
= dpyinfo
->n_planes
* dpyinfo
->n_cbits
;
4945 int n_planes
= dpyinfo
->n_planes
;
4946 #endif /* HAVE_NTGUI */
4950 /* Color (or grayscale). Convert to gray, and equalize. Just
4951 drawing such images with a stipple can look very odd, so
4952 we're using this method instead. */
4953 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4955 const int h
= 15000;
4956 const int l
= 30000;
4958 for (p
= colors
, end
= colors
+ img
->width
* img
->height
;
4962 int i
= COLOR_INTENSITY (p
->red
, p
->green
, p
->blue
);
4963 int i2
= (0xffff - h
- l
) * i
/ 0xffff + l
;
4964 p
->red
= p
->green
= p
->blue
= i2
;
4967 x_from_xcolors (f
, img
, colors
);
4970 /* Draw a cross over the disabled image, if we must or if we
4972 if (n_planes
< 2 || cross_disabled_images
)
4975 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4977 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4979 Display
*dpy
= FRAME_X_DISPLAY (f
);
4982 image_sync_to_pixmaps (f
, img
);
4983 gc
= XCreateGC (dpy
, img
->pixmap
, 0, NULL
);
4984 XSetForeground (dpy
, gc
, BLACK_PIX_DEFAULT (f
));
4985 XDrawLine (dpy
, img
->pixmap
, gc
, 0, 0,
4986 img
->width
- 1, img
->height
- 1);
4987 XDrawLine (dpy
, img
->pixmap
, gc
, 0, img
->height
- 1,
4993 gc
= XCreateGC (dpy
, img
->mask
, 0, NULL
);
4994 XSetForeground (dpy
, gc
, MaskForeground (f
));
4995 XDrawLine (dpy
, img
->mask
, gc
, 0, 0,
4996 img
->width
- 1, img
->height
- 1);
4997 XDrawLine (dpy
, img
->mask
, gc
, 0, img
->height
- 1,
5001 #endif /* !HAVE_NS */
5006 hdc
= get_frame_dc (f
);
5007 bmpdc
= CreateCompatibleDC (hdc
);
5008 release_frame_dc (f
, hdc
);
5010 prev
= SelectObject (bmpdc
, img
->pixmap
);
5012 SetTextColor (bmpdc
, BLACK_PIX_DEFAULT (f
));
5013 MoveToEx (bmpdc
, 0, 0, NULL
);
5014 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
5015 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
5016 LineTo (bmpdc
, img
->width
- 1, 0);
5020 SelectObject (bmpdc
, img
->mask
);
5021 SetTextColor (bmpdc
, WHITE_PIX_DEFAULT (f
));
5022 MoveToEx (bmpdc
, 0, 0, NULL
);
5023 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
5024 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
5025 LineTo (bmpdc
, img
->width
- 1, 0);
5027 SelectObject (bmpdc
, prev
);
5029 #endif /* HAVE_NTGUI */
5034 /* Build a mask for image IMG which is used on frame F. FILE is the
5035 name of an image file, for error messages. HOW determines how to
5036 determine the background color of IMG. If it is a list '(R G B)',
5037 with R, G, and B being integers >= 0, take that as the color of the
5038 background. Otherwise, determine the background color of IMG
5042 x_build_heuristic_mask (struct frame
*f
, struct image
*img
, Lisp_Object how
)
5044 XImagePtr_or_DC ximg
;
5051 #endif /* HAVE_NTGUI */
5053 bool use_img_background
;
5054 unsigned long bg
= 0;
5057 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
5061 /* Create an image and pixmap serving as mask. */
5062 if (! image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 1,
5065 #endif /* !HAVE_NS */
5067 /* Create the bit array serving as mask. */
5068 row_width
= (img
->width
+ 7) / 8;
5069 mask_img
= xzalloc (row_width
* img
->height
);
5070 #endif /* HAVE_NTGUI */
5072 /* Get the X image or create a memory device context for IMG. */
5073 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
5075 /* Determine the background color of ximg. If HOW is `(R G B)'
5076 take that as color. Otherwise, use the image's background color. */
5077 use_img_background
= 1;
5083 for (i
= 0; i
< 3 && CONSP (how
) && NATNUMP (XCAR (how
)); ++i
)
5085 rgb
[i
] = XFASTINT (XCAR (how
)) & 0xffff;
5089 if (i
== 3 && NILP (how
))
5091 char color_name
[30];
5092 sprintf (color_name
, "#%04x%04x%04x",
5093 rgb
[0] + 0u, rgb
[1] + 0u, rgb
[2] + 0u);
5096 0x00ffffff & /* Filter out palette info. */
5097 #endif /* HAVE_NTGUI */
5098 x_alloc_image_color (f
, img
, build_string (color_name
), 0));
5099 use_img_background
= 0;
5103 if (use_img_background
)
5104 bg
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
5106 /* Set all bits in mask_img to 1 whose color in ximg is different
5107 from the background color bg. */
5109 for (y
= 0; y
< img
->height
; ++y
)
5110 for (x
= 0; x
< img
->width
; ++x
)
5112 XPutPixel (mask_img
, x
, y
, (XGetPixel (ximg
, x
, y
) != bg
5113 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
));
5115 if (XGetPixel (ximg
, x
, y
) == bg
)
5116 ns_set_alpha (ximg
, x
, y
, 0);
5117 #endif /* HAVE_NS */
5119 /* Fill in the background_transparent field while we have the mask handy. */
5120 image_background_transparent (img
, f
, mask_img
);
5122 /* Put mask_img into the image. */
5123 image_put_x_image (f
, img
, mask_img
, 1);
5124 #endif /* !HAVE_NS */
5126 for (y
= 0; y
< img
->height
; ++y
)
5127 for (x
= 0; x
< img
->width
; ++x
)
5129 COLORREF p
= GetPixel (ximg
, x
, y
);
5131 mask_img
[y
* row_width
+ x
/ 8] |= 1 << (x
% 8);
5134 /* Create the mask image. */
5135 img
->mask
= w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
,
5137 /* Fill in the background_transparent field while we have the mask handy. */
5138 SelectObject (ximg
, img
->mask
);
5139 image_background_transparent (img
, f
, ximg
);
5141 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5143 #endif /* HAVE_NTGUI */
5145 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
5149 /***********************************************************************
5150 PBM (mono, gray, color)
5151 ***********************************************************************/
5153 static bool pbm_image_p (Lisp_Object object
);
5154 static bool pbm_load (struct frame
*f
, struct image
*img
);
5156 /* Indices of image specification fields in gs_format, below. */
5158 enum pbm_keyword_index
5174 /* Vector of image_keyword structures describing the format
5175 of valid user-defined image specifications. */
5177 static const struct image_keyword pbm_format
[PBM_LAST
] =
5179 {":type", IMAGE_SYMBOL_VALUE
, 1},
5180 {":file", IMAGE_STRING_VALUE
, 0},
5181 {":data", IMAGE_STRING_VALUE
, 0},
5182 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5183 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5184 {":relief", IMAGE_INTEGER_VALUE
, 0},
5185 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5186 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5187 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5188 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
5189 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5192 /* Structure describing the image type `pbm'. */
5194 static struct image_type pbm_type
=
5196 SYMBOL_INDEX (Qpbm
),
5205 /* Return true if OBJECT is a valid PBM image specification. */
5208 pbm_image_p (Lisp_Object object
)
5210 struct image_keyword fmt
[PBM_LAST
];
5212 memcpy (fmt
, pbm_format
, sizeof fmt
);
5214 if (!parse_image_spec (object
, fmt
, PBM_LAST
, Qpbm
))
5217 /* Must specify either :data or :file. */
5218 return fmt
[PBM_DATA
].count
+ fmt
[PBM_FILE
].count
== 1;
5222 /* Get next char skipping comments in Netpbm header. Returns -1 at
5226 pbm_next_char (unsigned char **s
, unsigned char *end
)
5230 while (*s
< end
&& (c
= *(*s
)++, c
== '#'))
5232 /* Skip to the next line break. */
5233 while (*s
< end
&& (c
= *(*s
)++, c
!= '\n' && c
!= '\r'))
5243 /* Scan a decimal number from *S and return it. Advance *S while
5244 reading the number. END is the end of the string. Value is -1 at
5248 pbm_scan_number (unsigned char **s
, unsigned char *end
)
5250 int c
= 0, val
= -1;
5252 /* Skip white-space. */
5253 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isspace (c
))
5258 /* Read decimal number. */
5260 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isdigit (c
))
5261 val
= 10 * val
+ c
- '0';
5268 /* Load PBM image IMG for use on frame F. */
5271 pbm_load (struct frame
*f
, struct image
*img
)
5275 int width
, height
, max_color_idx
= 0;
5276 Lisp_Object specified_file
;
5277 enum {PBM_MONO
, PBM_GRAY
, PBM_COLOR
} type
;
5278 unsigned char *contents
= NULL
;
5279 unsigned char *end
, *p
;
5281 unsigned char *data
= 0;
5287 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5289 if (STRINGP (specified_file
))
5292 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5293 if (!STRINGP (file
))
5295 image_error ("Cannot find image file `%s'", specified_file
);
5300 contents
= slurp_file (fd
, &size
);
5301 if (contents
== NULL
)
5303 image_error ("Error reading `%s'", file
);
5308 end
= contents
+ size
;
5313 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5314 if (!STRINGP (data
))
5316 image_error ("Invalid image data `%s'", data
);
5320 end
= p
+ SBYTES (data
);
5323 /* Check magic number. */
5324 if (end
- p
< 2 || *p
++ != 'P')
5326 image_error ("Not a PBM image: `%s'", img
->spec
);
5329 img
->pixmap
= NO_PIXMAP
;
5336 raw_p
= 0, type
= PBM_MONO
;
5340 raw_p
= 0, type
= PBM_GRAY
;
5344 raw_p
= 0, type
= PBM_COLOR
;
5348 raw_p
= 1, type
= PBM_MONO
;
5352 raw_p
= 1, type
= PBM_GRAY
;
5356 raw_p
= 1, type
= PBM_COLOR
;
5360 image_error ("Not a PBM image: `%s'", img
->spec
);
5364 /* Read width, height, maximum color-component. Characters
5365 starting with `#' up to the end of a line are ignored. */
5366 width
= pbm_scan_number (&p
, end
);
5367 height
= pbm_scan_number (&p
, end
);
5370 data
= (unsigned char *) xmalloc (width
* height
* 4);
5371 dataptr
= (uint32_t *) data
;
5374 if (type
!= PBM_MONO
)
5376 max_color_idx
= pbm_scan_number (&p
, end
);
5377 if (max_color_idx
> 65535 || max_color_idx
< 0)
5379 image_error ("Unsupported maximum PBM color value");
5384 if (!check_image_size (f
, width
, height
))
5386 image_size_error ();
5391 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5395 /* Initialize the color hash table. */
5396 init_color_table ();
5398 if (type
== PBM_MONO
)
5401 struct image_keyword fmt
[PBM_LAST
];
5402 unsigned long fg
= FRAME_FOREGROUND_PIXEL (f
);
5403 unsigned long bg
= FRAME_BACKGROUND_PIXEL (f
);
5408 /* Parse the image specification. */
5409 memcpy (fmt
, pbm_format
, sizeof fmt
);
5410 parse_image_spec (img
->spec
, fmt
, PBM_LAST
, Qpbm
);
5412 /* Get foreground and background colors, maybe allocate colors. */
5414 if (! fmt
[PBM_FOREGROUND
].count
5415 || ! STRINGP (fmt
[PBM_FOREGROUND
].value
)
5416 || ! x_defined_color (f
, SSDATA (fmt
[PBM_FOREGROUND
].value
), &xfg
, 0))
5419 x_query_color (f
, &xfg
);
5421 fga32
= xcolor_to_argb32 (xfg
);
5423 if (! fmt
[PBM_BACKGROUND
].count
5424 || ! STRINGP (fmt
[PBM_BACKGROUND
].value
)
5425 || ! x_defined_color (f
, SSDATA (fmt
[PBM_BACKGROUND
].value
), &xbg
, 0))
5428 x_query_color (f
, &xbg
);
5430 bga32
= xcolor_to_argb32 (xbg
);
5432 if (fmt
[PBM_FOREGROUND
].count
5433 && STRINGP (fmt
[PBM_FOREGROUND
].value
))
5434 fg
= x_alloc_image_color (f
, img
, fmt
[PBM_FOREGROUND
].value
, fg
);
5435 if (fmt
[PBM_BACKGROUND
].count
5436 && STRINGP (fmt
[PBM_BACKGROUND
].value
))
5438 bg
= x_alloc_image_color (f
, img
, fmt
[PBM_BACKGROUND
].value
, bg
);
5439 img
->background
= bg
;
5440 img
->background_valid
= 1;
5444 for (y
= 0; y
< height
; ++y
)
5445 for (x
= 0; x
< width
; ++x
)
5456 x_destroy_x_image (ximg
);
5458 x_clear_image (f
, img
);
5459 image_error ("Invalid image size in image `%s'",
5469 g
= pbm_scan_number (&p
, end
);
5472 *dataptr
++ = g
? fga32
: bga32
;
5474 XPutPixel (ximg
, x
, y
, g
? fg
: bg
);
5480 int expected_size
= height
* width
;
5481 if (max_color_idx
> 255)
5483 if (type
== PBM_COLOR
)
5486 if (raw_p
&& p
+ expected_size
> end
)
5491 x_destroy_x_image (ximg
);
5493 x_clear_image (f
, img
);
5494 image_error ("Invalid image size in image `%s'", img
->spec
);
5498 for (y
= 0; y
< height
; ++y
)
5499 for (x
= 0; x
< width
; ++x
)
5503 if (type
== PBM_GRAY
&& raw_p
)
5506 if (max_color_idx
> 255)
5507 r
= g
= b
= r
* 256 + *p
++;
5509 else if (type
== PBM_GRAY
)
5510 r
= g
= b
= pbm_scan_number (&p
, end
);
5514 if (max_color_idx
> 255)
5517 if (max_color_idx
> 255)
5520 if (max_color_idx
> 255)
5525 r
= pbm_scan_number (&p
, end
);
5526 g
= pbm_scan_number (&p
, end
);
5527 b
= pbm_scan_number (&p
, end
);
5530 if (r
< 0 || g
< 0 || b
< 0)
5535 x_destroy_x_image (ximg
);
5537 image_error ("Invalid pixel value in image `%s'", img
->spec
);
5542 r
= (double) r
* 255 / max_color_idx
;
5543 g
= (double) g
* 255 / max_color_idx
;
5544 b
= (double) b
* 255 / max_color_idx
;
5545 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
5547 /* RGB values are now in the range 0..max_color_idx.
5548 Scale this to the range 0..0xffff supported by X. */
5549 r
= (double) r
* 65535 / max_color_idx
;
5550 g
= (double) g
* 65535 / max_color_idx
;
5551 b
= (double) b
* 65535 / max_color_idx
;
5552 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5557 #ifdef COLOR_TABLE_SUPPORT
5558 /* Store in IMG->colors the colors allocated for the image, and
5559 free the color table. */
5560 img
->colors
= colors_in_color_table (&img
->ncolors
);
5561 free_color_table ();
5562 #endif /* COLOR_TABLE_SUPPORT */
5565 img
->height
= height
;
5567 /* Maybe fill in the background field while we have ximg handy. */
5570 create_cairo_image_surface (img
, data
, width
, height
);
5572 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
5573 /* Casting avoids a GCC warning. */
5574 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
5576 /* Put ximg into the image. */
5577 image_put_x_image (f
, img
, ximg
, 0);
5580 /* X and W32 versions did it here, MAC version above. ++kfs
5582 img->height = height; */
5589 /***********************************************************************
5591 ***********************************************************************/
5593 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5595 /* Function prototypes. */
5597 static bool png_image_p (Lisp_Object object
);
5598 static bool png_load (struct frame
*f
, struct image
*img
);
5600 /* Indices of image specification fields in png_format, below. */
5602 enum png_keyword_index
5617 /* Vector of image_keyword structures describing the format
5618 of valid user-defined image specifications. */
5620 static const struct image_keyword png_format
[PNG_LAST
] =
5622 {":type", IMAGE_SYMBOL_VALUE
, 1},
5623 {":data", IMAGE_STRING_VALUE
, 0},
5624 {":file", IMAGE_STRING_VALUE
, 0},
5625 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5626 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5627 {":relief", IMAGE_INTEGER_VALUE
, 0},
5628 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5629 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5630 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5631 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5634 #if defined HAVE_NTGUI && defined WINDOWSNT
5635 static bool init_png_functions (void);
5637 #define init_png_functions NULL
5640 /* Structure describing the image type `png'. */
5642 static struct image_type png_type
=
5644 SYMBOL_INDEX (Qpng
),
5652 /* Return true if OBJECT is a valid PNG image specification. */
5655 png_image_p (Lisp_Object object
)
5657 struct image_keyword fmt
[PNG_LAST
];
5658 memcpy (fmt
, png_format
, sizeof fmt
);
5660 if (!parse_image_spec (object
, fmt
, PNG_LAST
, Qpng
))
5663 /* Must specify either the :data or :file keyword. */
5664 return fmt
[PNG_FILE
].count
+ fmt
[PNG_DATA
].count
== 1;
5667 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5670 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5673 /* PNG library details. */
5675 DEF_DLL_FN (png_voidp
, png_get_io_ptr
, (png_structp
));
5676 DEF_DLL_FN (int, png_sig_cmp
, (png_bytep
, png_size_t
, png_size_t
));
5677 DEF_DLL_FN (png_structp
, png_create_read_struct
,
5678 (png_const_charp
, png_voidp
, png_error_ptr
, png_error_ptr
));
5679 DEF_DLL_FN (png_infop
, png_create_info_struct
, (png_structp
));
5680 DEF_DLL_FN (void, png_destroy_read_struct
,
5681 (png_structpp
, png_infopp
, png_infopp
));
5682 DEF_DLL_FN (void, png_set_read_fn
, (png_structp
, png_voidp
, png_rw_ptr
));
5683 DEF_DLL_FN (void, png_set_sig_bytes
, (png_structp
, int));
5684 DEF_DLL_FN (void, png_read_info
, (png_structp
, png_infop
));
5685 DEF_DLL_FN (png_uint_32
, png_get_IHDR
,
5686 (png_structp
, png_infop
, png_uint_32
*, png_uint_32
*,
5687 int *, int *, int *, int *, int *));
5688 DEF_DLL_FN (png_uint_32
, png_get_valid
, (png_structp
, png_infop
, png_uint_32
));
5689 DEF_DLL_FN (void, png_set_strip_16
, (png_structp
));
5690 DEF_DLL_FN (void, png_set_expand
, (png_structp
));
5691 DEF_DLL_FN (void, png_set_gray_to_rgb
, (png_structp
));
5692 DEF_DLL_FN (void, png_set_background
,
5693 (png_structp
, png_color_16p
, int, int, double));
5694 DEF_DLL_FN (png_uint_32
, png_get_bKGD
,
5695 (png_structp
, png_infop
, png_color_16p
*));
5696 DEF_DLL_FN (void, png_read_update_info
, (png_structp
, png_infop
));
5697 DEF_DLL_FN (png_byte
, png_get_channels
, (png_structp
, png_infop
));
5698 DEF_DLL_FN (png_size_t
, png_get_rowbytes
, (png_structp
, png_infop
));
5699 DEF_DLL_FN (void, png_read_image
, (png_structp
, png_bytepp
));
5700 DEF_DLL_FN (void, png_read_end
, (png_structp
, png_infop
));
5701 DEF_DLL_FN (void, png_error
, (png_structp
, png_const_charp
));
5703 # if (PNG_LIBPNG_VER >= 10500)
5704 DEF_DLL_FN (void, png_longjmp
, (png_structp
, int)) PNG_NORETURN
;
5705 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn
,
5706 (png_structp
, png_longjmp_ptr
, size_t));
5707 # endif /* libpng version >= 1.5 */
5710 init_png_functions (void)
5714 if (!(library
= w32_delayed_load (Qpng
)))
5717 LOAD_DLL_FN (library
, png_get_io_ptr
);
5718 LOAD_DLL_FN (library
, png_sig_cmp
);
5719 LOAD_DLL_FN (library
, png_create_read_struct
);
5720 LOAD_DLL_FN (library
, png_create_info_struct
);
5721 LOAD_DLL_FN (library
, png_destroy_read_struct
);
5722 LOAD_DLL_FN (library
, png_set_read_fn
);
5723 LOAD_DLL_FN (library
, png_set_sig_bytes
);
5724 LOAD_DLL_FN (library
, png_read_info
);
5725 LOAD_DLL_FN (library
, png_get_IHDR
);
5726 LOAD_DLL_FN (library
, png_get_valid
);
5727 LOAD_DLL_FN (library
, png_set_strip_16
);
5728 LOAD_DLL_FN (library
, png_set_expand
);
5729 LOAD_DLL_FN (library
, png_set_gray_to_rgb
);
5730 LOAD_DLL_FN (library
, png_set_background
);
5731 LOAD_DLL_FN (library
, png_get_bKGD
);
5732 LOAD_DLL_FN (library
, png_read_update_info
);
5733 LOAD_DLL_FN (library
, png_get_channels
);
5734 LOAD_DLL_FN (library
, png_get_rowbytes
);
5735 LOAD_DLL_FN (library
, png_read_image
);
5736 LOAD_DLL_FN (library
, png_read_end
);
5737 LOAD_DLL_FN (library
, png_error
);
5739 # if (PNG_LIBPNG_VER >= 10500)
5740 LOAD_DLL_FN (library
, png_longjmp
);
5741 LOAD_DLL_FN (library
, png_set_longjmp_fn
);
5742 # endif /* libpng version >= 1.5 */
5747 # undef png_create_info_struct
5748 # undef png_create_read_struct
5749 # undef png_destroy_read_struct
5751 # undef png_get_bKGD
5752 # undef png_get_channels
5753 # undef png_get_IHDR
5754 # undef png_get_io_ptr
5755 # undef png_get_rowbytes
5756 # undef png_get_valid
5758 # undef png_read_end
5759 # undef png_read_image
5760 # undef png_read_info
5761 # undef png_read_update_info
5762 # undef png_set_background
5763 # undef png_set_expand
5764 # undef png_set_gray_to_rgb
5765 # undef png_set_longjmp_fn
5766 # undef png_set_read_fn
5767 # undef png_set_sig_bytes
5768 # undef png_set_strip_16
5771 # define png_create_info_struct fn_png_create_info_struct
5772 # define png_create_read_struct fn_png_create_read_struct
5773 # define png_destroy_read_struct fn_png_destroy_read_struct
5774 # define png_error fn_png_error
5775 # define png_get_bKGD fn_png_get_bKGD
5776 # define png_get_channels fn_png_get_channels
5777 # define png_get_IHDR fn_png_get_IHDR
5778 # define png_get_io_ptr fn_png_get_io_ptr
5779 # define png_get_rowbytes fn_png_get_rowbytes
5780 # define png_get_valid fn_png_get_valid
5781 # define png_longjmp fn_png_longjmp
5782 # define png_read_end fn_png_read_end
5783 # define png_read_image fn_png_read_image
5784 # define png_read_info fn_png_read_info
5785 # define png_read_update_info fn_png_read_update_info
5786 # define png_set_background fn_png_set_background
5787 # define png_set_expand fn_png_set_expand
5788 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5789 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5790 # define png_set_read_fn fn_png_set_read_fn
5791 # define png_set_sig_bytes fn_png_set_sig_bytes
5792 # define png_set_strip_16 fn_png_set_strip_16
5793 # define png_sig_cmp fn_png_sig_cmp
5795 # endif /* WINDOWSNT */
5797 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5798 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5799 Do not use sys_setjmp, as PNG supports only jmp_buf.
5800 It's OK if the longjmp substitute restores the signal mask. */
5801 # ifdef HAVE__SETJMP
5802 # define FAST_SETJMP(j) _setjmp (j)
5803 # define FAST_LONGJMP _longjmp
5805 # define FAST_SETJMP(j) setjmp (j)
5806 # define FAST_LONGJMP longjmp
5809 # if PNG_LIBPNG_VER < 10500
5810 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5811 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5813 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5814 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5815 # define PNG_JMPBUF(ptr) \
5816 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5819 /* Error and warning handlers installed when the PNG library
5822 static _Noreturn
void
5823 my_png_error (png_struct
*png_ptr
, const char *msg
)
5825 eassert (png_ptr
!= NULL
);
5826 /* Avoid compiler warning about deprecated direct access to
5827 png_ptr's fields in libpng versions 1.4.x. */
5828 image_error ("PNG error: %s", build_string (msg
));
5829 PNG_LONGJMP (png_ptr
);
5834 my_png_warning (png_struct
*png_ptr
, const char *msg
)
5836 eassert (png_ptr
!= NULL
);
5837 image_error ("PNG warning: %s", build_string (msg
));
5840 /* Memory source for PNG decoding. */
5842 struct png_memory_storage
5844 unsigned char *bytes
; /* The data */
5845 ptrdiff_t len
; /* How big is it? */
5846 ptrdiff_t index
; /* Where are we? */
5850 /* Function set as reader function when reading PNG image from memory.
5851 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5852 bytes from the input to DATA. */
5855 png_read_from_memory (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5857 struct png_memory_storage
*tbr
= png_get_io_ptr (png_ptr
);
5859 if (length
> tbr
->len
- tbr
->index
)
5860 png_error (png_ptr
, "Read error");
5862 memcpy (data
, tbr
->bytes
+ tbr
->index
, length
);
5863 tbr
->index
= tbr
->index
+ length
;
5867 /* Function set as reader function when reading PNG image from a file.
5868 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5869 bytes from the input to DATA. */
5872 png_read_from_file (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5874 FILE *fp
= png_get_io_ptr (png_ptr
);
5876 if (fread (data
, 1, length
, fp
) < length
)
5877 png_error (png_ptr
, "Read error");
5881 /* Load PNG image IMG for use on frame F. Value is true if
5884 struct png_load_context
5886 /* These are members so that longjmp doesn't munge local variables. */
5887 png_struct
*png_ptr
;
5896 png_load_body (struct frame
*f
, struct image
*img
, struct png_load_context
*c
)
5898 Lisp_Object specified_file
;
5899 Lisp_Object NONVOLATILE specified_data
;
5900 FILE *NONVOLATILE fp
= NULL
;
5903 png_struct
*png_ptr
;
5904 png_info
*info_ptr
= NULL
, *end_info
= NULL
;
5906 png_byte
*pixels
= NULL
;
5907 png_byte
**rows
= NULL
;
5908 png_uint_32 width
, height
;
5909 int bit_depth
, color_type
, interlace_type
;
5911 png_uint_32 row_bytes
;
5913 struct png_memory_storage tbr
; /* Data to be read */
5917 unsigned char *data
= 0;
5920 XImagePtr ximg
, mask_img
= NULL
;
5923 /* Find out what file to load. */
5924 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5925 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5927 if (NILP (specified_data
))
5930 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5931 if (!STRINGP (file
))
5933 image_error ("Cannot find image file `%s'", specified_file
);
5937 /* Open the image file. */
5938 fp
= fdopen (fd
, "rb");
5941 image_error ("Cannot open image file `%s'", file
);
5945 /* Check PNG signature. */
5946 if (fread (sig
, 1, sizeof sig
, fp
) != sizeof sig
5947 || png_sig_cmp (sig
, 0, sizeof sig
))
5950 image_error ("Not a PNG file: `%s'", file
);
5956 if (!STRINGP (specified_data
))
5958 image_error ("Invalid image data `%s'", specified_data
);
5962 /* Read from memory. */
5963 tbr
.bytes
= SDATA (specified_data
);
5964 tbr
.len
= SBYTES (specified_data
);
5967 /* Check PNG signature. */
5968 if (tbr
.len
< sizeof sig
5969 || png_sig_cmp (tbr
.bytes
, 0, sizeof sig
))
5971 image_error ("Not a PNG image: `%s'", img
->spec
);
5975 /* Need to skip past the signature. */
5976 tbr
.bytes
+= sizeof (sig
);
5979 /* Initialize read and info structs for PNG lib. */
5980 png_ptr
= png_create_read_struct (PNG_LIBPNG_VER_STRING
,
5985 info_ptr
= png_create_info_struct (png_ptr
);
5986 end_info
= png_create_info_struct (png_ptr
);
5989 c
->png_ptr
= png_ptr
;
5990 c
->info_ptr
= info_ptr
;
5991 c
->end_info
= end_info
;
5996 if (! (info_ptr
&& end_info
))
5998 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6003 if (fp
) fclose (fp
);
6007 /* Set error jump-back. We come back here when the PNG library
6008 detects an error. */
6009 if (FAST_SETJMP (PNG_JMPBUF (png_ptr
)))
6013 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6021 /* Read image info. */
6022 if (!NILP (specified_data
))
6023 png_set_read_fn (png_ptr
, &tbr
, png_read_from_memory
);
6025 png_set_read_fn (png_ptr
, fp
, png_read_from_file
);
6027 png_set_sig_bytes (png_ptr
, sizeof sig
);
6028 png_read_info (png_ptr
, info_ptr
);
6029 png_get_IHDR (png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
,
6030 &interlace_type
, NULL
, NULL
);
6032 if (! (width
<= INT_MAX
&& height
<= INT_MAX
6033 && check_image_size (f
, width
, height
)))
6035 image_size_error ();
6040 /* Create the X image and pixmap now, so that the work below can be
6041 omitted if the image is too large for X. */
6042 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6046 /* If image contains simply transparency data, we prefer to
6047 construct a clipping mask. */
6048 if (png_get_valid (png_ptr
, info_ptr
, PNG_INFO_tRNS
))
6053 /* This function is easier to write if we only have to handle
6054 one data format: RGB or RGBA with 8 bits per channel. Let's
6055 transform other formats into that format. */
6057 /* Strip more than 8 bits per channel. */
6058 if (bit_depth
== 16)
6059 png_set_strip_16 (png_ptr
);
6061 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6063 png_set_expand (png_ptr
);
6065 /* Convert grayscale images to RGB. */
6066 if (color_type
== PNG_COLOR_TYPE_GRAY
6067 || color_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
6068 png_set_gray_to_rgb (png_ptr
);
6070 /* Handle alpha channel by combining the image with a background
6071 color. Do this only if a real alpha channel is supplied. For
6072 simple transparency, we prefer a clipping mask. */
6075 /* png_color_16 *image_bg; */
6076 Lisp_Object specified_bg
6077 = image_spec_value (img
->spec
, QCbackground
, NULL
);
6080 /* If the user specified a color, try to use it; if not, use the
6081 current frame background, ignoring any default background
6082 color set by the image. */
6083 if (STRINGP (specified_bg
)
6084 ? x_defined_color (f
, SSDATA (specified_bg
), &color
, false)
6085 : (x_query_frame_background_color (f
, &color
), true))
6086 /* The user specified `:background', use that. */
6088 int shift
= bit_depth
== 16 ? 0 : 8;
6089 png_color_16 bg
= { 0 };
6090 bg
.red
= color
.red
>> shift
;
6091 bg
.green
= color
.green
>> shift
;
6092 bg
.blue
= color
.blue
>> shift
;
6094 png_set_background (png_ptr
, &bg
,
6095 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
6099 /* Update info structure. */
6100 png_read_update_info (png_ptr
, info_ptr
);
6102 /* Get number of channels. Valid values are 1 for grayscale images
6103 and images with a palette, 2 for grayscale images with transparency
6104 information (alpha channel), 3 for RGB images, and 4 for RGB
6105 images with alpha channel, i.e. RGBA. If conversions above were
6106 sufficient we should only have 3 or 4 channels here. */
6107 channels
= png_get_channels (png_ptr
, info_ptr
);
6108 eassert (channels
== 3 || channels
== 4);
6110 /* Number of bytes needed for one row of the image. */
6111 row_bytes
= png_get_rowbytes (png_ptr
, info_ptr
);
6113 /* Allocate memory for the image. */
6114 if (INT_MULTIPLY_WRAPV (row_bytes
, sizeof *pixels
, &nbytes
)
6115 || INT_MULTIPLY_WRAPV (nbytes
, height
, &nbytes
))
6116 memory_full (SIZE_MAX
);
6117 c
->pixels
= pixels
= xmalloc (nbytes
);
6118 c
->rows
= rows
= xmalloc (height
* sizeof *rows
);
6119 for (i
= 0; i
< height
; ++i
)
6120 rows
[i
] = pixels
+ i
* row_bytes
;
6122 /* Read the entire image. */
6123 png_read_image (png_ptr
, rows
);
6124 png_read_end (png_ptr
, info_ptr
);
6132 data
= (unsigned char *) xmalloc (width
* height
* 4);
6133 dataptr
= (uint32_t *) data
;
6135 /* Create an image and pixmap serving as mask if the PNG image
6136 contains an alpha channel. */
6139 && !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
6142 x_destroy_x_image (ximg
);
6143 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
);
6148 /* Fill the X image and mask from PNG data. */
6149 init_color_table ();
6151 for (y
= 0; y
< height
; ++y
)
6153 png_byte
*p
= rows
[y
];
6155 for (x
= 0; x
< width
; ++x
)
6164 if (channels
== 4) a
= *p
++;
6165 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
6170 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
6171 /* An alpha channel, aka mask channel, associates variable
6172 transparency with an image. Where other image formats
6173 support binary transparency---fully transparent or fully
6174 opaque---PNG allows up to 254 levels of partial transparency.
6175 The PNG library implements partial transparency by combining
6176 the image with a specified background color.
6178 I'm not sure how to handle this here nicely: because the
6179 background on which the image is displayed may change, for
6180 real alpha channel support, it would be necessary to create
6181 a new image for each possible background.
6183 What I'm doing now is that a mask is created if we have
6184 boolean transparency information. Otherwise I'm using
6185 the frame's background color to combine the image with. */
6190 XPutPixel (mask_img
, x
, y
, *p
> 0 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
);
6197 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6198 /* Set IMG's background color from the PNG image, unless the user
6202 if (png_get_bKGD (png_ptr
, info_ptr
, &bg
))
6204 img
->background
= lookup_rgb_color (f
, bg
->red
, bg
->green
, bg
->blue
);
6205 img
->background_valid
= 1;
6209 # ifdef COLOR_TABLE_SUPPORT
6210 /* Remember colors allocated for this image. */
6211 img
->colors
= colors_in_color_table (&img
->ncolors
);
6212 free_color_table ();
6213 # endif /* COLOR_TABLE_SUPPORT */
6216 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6221 img
->height
= height
;
6224 create_cairo_image_surface (img
, data
, width
, height
);
6226 /* Maybe fill in the background field while we have ximg handy.
6227 Casting avoids a GCC warning. */
6228 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6230 /* Put ximg into the image. */
6231 image_put_x_image (f
, img
, ximg
, 0);
6233 /* Same for the mask. */
6236 /* Fill in the background_transparent field while we have the
6237 mask handy. Casting avoids a GCC warning. */
6238 image_background_transparent (img
, f
, (XImagePtr_or_DC
)mask_img
);
6240 image_put_x_image (f
, img
, mask_img
, 1);
6248 png_load (struct frame
*f
, struct image
*img
)
6250 struct png_load_context c
;
6251 return png_load_body (f
, img
, &c
);
6254 #elif defined HAVE_NS
6257 png_load (struct frame
*f
, struct image
*img
)
6259 return ns_load_image (f
, img
,
6260 image_spec_value (img
->spec
, QCfile
, NULL
),
6261 image_spec_value (img
->spec
, QCdata
, NULL
));
6265 #endif /* HAVE_NS */
6269 /***********************************************************************
6271 ***********************************************************************/
6273 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6275 static bool jpeg_image_p (Lisp_Object object
);
6276 static bool jpeg_load (struct frame
*f
, struct image
*img
);
6278 /* Indices of image specification fields in gs_format, below. */
6280 enum jpeg_keyword_index
6289 JPEG_HEURISTIC_MASK
,
6295 /* Vector of image_keyword structures describing the format
6296 of valid user-defined image specifications. */
6298 static const struct image_keyword jpeg_format
[JPEG_LAST
] =
6300 {":type", IMAGE_SYMBOL_VALUE
, 1},
6301 {":data", IMAGE_STRING_VALUE
, 0},
6302 {":file", IMAGE_STRING_VALUE
, 0},
6303 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6304 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6305 {":relief", IMAGE_INTEGER_VALUE
, 0},
6306 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6307 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6308 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6309 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
6312 #if defined HAVE_NTGUI && defined WINDOWSNT
6313 static bool init_jpeg_functions (void);
6315 #define init_jpeg_functions NULL
6318 /* Structure describing the image type `jpeg'. */
6320 static struct image_type jpeg_type
=
6322 SYMBOL_INDEX (Qjpeg
),
6326 init_jpeg_functions
,
6330 /* Return true if OBJECT is a valid JPEG image specification. */
6333 jpeg_image_p (Lisp_Object object
)
6335 struct image_keyword fmt
[JPEG_LAST
];
6337 memcpy (fmt
, jpeg_format
, sizeof fmt
);
6339 if (!parse_image_spec (object
, fmt
, JPEG_LAST
, Qjpeg
))
6342 /* Must specify either the :data or :file keyword. */
6343 return fmt
[JPEG_FILE
].count
+ fmt
[JPEG_DATA
].count
== 1;
6346 #endif /* HAVE_JPEG || HAVE_NS */
6350 /* Work around a warning about HAVE_STDLIB_H being redefined in
6352 # ifdef HAVE_STDLIB_H
6353 # undef HAVE_STDLIB_H
6356 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6357 /* In older releases of the jpeg library, jpeglib.h will define boolean
6358 differently depending on __WIN32__, so make sure it is defined. */
6359 # define __WIN32__ 1
6362 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6363 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6364 using the Windows boolean type instead of the jpeglib boolean type
6365 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6366 headers are included along with windows.h, so under Cygwin, jpeglib
6367 attempts to define a conflicting boolean type. Worse, forcing
6368 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6369 because it created an ABI incompatibility between the
6370 already-compiled jpeg library and the header interface definition.
6372 The best we can do is to define jpeglib's boolean type to a
6373 different name. This name, jpeg_boolean, remains in effect through
6374 the rest of image.c.
6376 # if defined CYGWIN && defined HAVE_NTGUI
6377 # define boolean jpeg_boolean
6379 # include <jpeglib.h>
6380 # include <jerror.h>
6384 /* JPEG library details. */
6385 DEF_DLL_FN (void, jpeg_CreateDecompress
, (j_decompress_ptr
, int, size_t));
6386 DEF_DLL_FN (boolean
, jpeg_start_decompress
, (j_decompress_ptr
));
6387 DEF_DLL_FN (boolean
, jpeg_finish_decompress
, (j_decompress_ptr
));
6388 DEF_DLL_FN (void, jpeg_destroy_decompress
, (j_decompress_ptr
));
6389 DEF_DLL_FN (int, jpeg_read_header
, (j_decompress_ptr
, boolean
));
6390 DEF_DLL_FN (JDIMENSION
, jpeg_read_scanlines
,
6391 (j_decompress_ptr
, JSAMPARRAY
, JDIMENSION
));
6392 DEF_DLL_FN (struct jpeg_error_mgr
*, jpeg_std_error
,
6393 (struct jpeg_error_mgr
*));
6394 DEF_DLL_FN (boolean
, jpeg_resync_to_restart
, (j_decompress_ptr
, int));
6397 init_jpeg_functions (void)
6401 if (!(library
= w32_delayed_load (Qjpeg
)))
6404 LOAD_DLL_FN (library
, jpeg_finish_decompress
);
6405 LOAD_DLL_FN (library
, jpeg_read_scanlines
);
6406 LOAD_DLL_FN (library
, jpeg_start_decompress
);
6407 LOAD_DLL_FN (library
, jpeg_read_header
);
6408 LOAD_DLL_FN (library
, jpeg_CreateDecompress
);
6409 LOAD_DLL_FN (library
, jpeg_destroy_decompress
);
6410 LOAD_DLL_FN (library
, jpeg_std_error
);
6411 LOAD_DLL_FN (library
, jpeg_resync_to_restart
);
6415 # undef jpeg_CreateDecompress
6416 # undef jpeg_destroy_decompress
6417 # undef jpeg_finish_decompress
6418 # undef jpeg_read_header
6419 # undef jpeg_read_scanlines
6420 # undef jpeg_resync_to_restart
6421 # undef jpeg_start_decompress
6422 # undef jpeg_std_error
6424 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6425 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6426 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6427 # define jpeg_read_header fn_jpeg_read_header
6428 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6429 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6430 # define jpeg_start_decompress fn_jpeg_start_decompress
6431 # define jpeg_std_error fn_jpeg_std_error
6433 /* Wrapper since we can't directly assign the function pointer
6434 to another function pointer that was declared more completely easily. */
6436 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo
, int desired
)
6438 return jpeg_resync_to_restart (cinfo
, desired
);
6440 # undef jpeg_resync_to_restart
6441 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6443 # endif /* WINDOWSNT */
6445 struct my_jpeg_error_mgr
6447 struct jpeg_error_mgr pub
;
6448 sys_jmp_buf setjmp_buffer
;
6450 /* The remaining members are so that longjmp doesn't munge local
6452 struct jpeg_decompress_struct cinfo
;
6456 MY_JPEG_INVALID_IMAGE_SIZE
,
6457 MY_JPEG_CANNOT_CREATE_X
6462 static _Noreturn
void
6463 my_error_exit (j_common_ptr cinfo
)
6465 struct my_jpeg_error_mgr
*mgr
= (struct my_jpeg_error_mgr
*) cinfo
->err
;
6466 mgr
->failure_code
= MY_JPEG_ERROR_EXIT
;
6467 sys_longjmp (mgr
->setjmp_buffer
, 1);
6471 /* Init source method for JPEG data source manager. Called by
6472 jpeg_read_header() before any data is actually read. See
6473 libjpeg.doc from the JPEG lib distribution. */
6476 our_common_init_source (j_decompress_ptr cinfo
)
6481 /* Method to terminate data source. Called by
6482 jpeg_finish_decompress() after all data has been processed. */
6485 our_common_term_source (j_decompress_ptr cinfo
)
6490 /* Fill input buffer method for JPEG data source manager. Called
6491 whenever more data is needed. We read the whole image in one step,
6492 so this only adds a fake end of input marker at the end. */
6494 static JOCTET our_memory_buffer
[2];
6497 our_memory_fill_input_buffer (j_decompress_ptr cinfo
)
6499 /* Insert a fake EOI marker. */
6500 struct jpeg_source_mgr
*src
= cinfo
->src
;
6502 our_memory_buffer
[0] = (JOCTET
) 0xFF;
6503 our_memory_buffer
[1] = (JOCTET
) JPEG_EOI
;
6505 src
->next_input_byte
= our_memory_buffer
;
6506 src
->bytes_in_buffer
= 2;
6511 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6512 is the JPEG data source manager. */
6515 our_memory_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6517 struct jpeg_source_mgr
*src
= cinfo
->src
;
6521 if (num_bytes
> src
->bytes_in_buffer
)
6522 ERREXIT (cinfo
, JERR_INPUT_EOF
);
6524 src
->bytes_in_buffer
-= num_bytes
;
6525 src
->next_input_byte
+= num_bytes
;
6530 /* Set up the JPEG lib for reading an image from DATA which contains
6531 LEN bytes. CINFO is the decompression info structure created for
6532 reading the image. */
6535 jpeg_memory_src (j_decompress_ptr cinfo
, JOCTET
*data
, ptrdiff_t len
)
6537 struct jpeg_source_mgr
*src
= cinfo
->src
;
6541 /* First time for this JPEG object? */
6542 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6543 JPOOL_PERMANENT
, sizeof *src
);
6545 src
->next_input_byte
= data
;
6548 src
->init_source
= our_common_init_source
;
6549 src
->fill_input_buffer
= our_memory_fill_input_buffer
;
6550 src
->skip_input_data
= our_memory_skip_input_data
;
6551 src
->resync_to_restart
= jpeg_resync_to_restart
; /* Use default method. */
6552 src
->term_source
= our_common_term_source
;
6553 src
->bytes_in_buffer
= len
;
6554 src
->next_input_byte
= data
;
6558 struct jpeg_stdio_mgr
6560 struct jpeg_source_mgr mgr
;
6567 /* Size of buffer to read JPEG from file.
6568 Not too big, as we want to use alloc_small. */
6569 #define JPEG_STDIO_BUFFER_SIZE 8192
6572 /* Fill input buffer method for JPEG data source manager. Called
6573 whenever more data is needed. The data is read from a FILE *. */
6576 our_stdio_fill_input_buffer (j_decompress_ptr cinfo
)
6578 struct jpeg_stdio_mgr
*src
;
6580 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6585 bytes
= fread (src
->buffer
, 1, JPEG_STDIO_BUFFER_SIZE
, src
->file
);
6587 src
->mgr
.bytes_in_buffer
= bytes
;
6590 WARNMS (cinfo
, JWRN_JPEG_EOF
);
6592 src
->buffer
[0] = (JOCTET
) 0xFF;
6593 src
->buffer
[1] = (JOCTET
) JPEG_EOI
;
6594 src
->mgr
.bytes_in_buffer
= 2;
6596 src
->mgr
.next_input_byte
= src
->buffer
;
6603 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6604 is the JPEG data source manager. */
6607 our_stdio_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6609 struct jpeg_stdio_mgr
*src
;
6610 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6612 while (num_bytes
> 0 && !src
->finished
)
6614 if (num_bytes
<= src
->mgr
.bytes_in_buffer
)
6616 src
->mgr
.bytes_in_buffer
-= num_bytes
;
6617 src
->mgr
.next_input_byte
+= num_bytes
;
6622 num_bytes
-= src
->mgr
.bytes_in_buffer
;
6623 src
->mgr
.bytes_in_buffer
= 0;
6624 src
->mgr
.next_input_byte
= NULL
;
6626 our_stdio_fill_input_buffer (cinfo
);
6632 /* Set up the JPEG lib for reading an image from a FILE *.
6633 CINFO is the decompression info structure created for
6634 reading the image. */
6637 jpeg_file_src (j_decompress_ptr cinfo
, FILE *fp
)
6639 struct jpeg_stdio_mgr
*src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6643 /* First time for this JPEG object? */
6644 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6645 JPOOL_PERMANENT
, sizeof *src
);
6646 cinfo
->src
= (struct jpeg_source_mgr
*) src
;
6647 src
->buffer
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6649 JPEG_STDIO_BUFFER_SIZE
);
6654 src
->mgr
.init_source
= our_common_init_source
;
6655 src
->mgr
.fill_input_buffer
= our_stdio_fill_input_buffer
;
6656 src
->mgr
.skip_input_data
= our_stdio_skip_input_data
;
6657 src
->mgr
.resync_to_restart
= jpeg_resync_to_restart
; /* Use default. */
6658 src
->mgr
.term_source
= our_common_term_source
;
6659 src
->mgr
.bytes_in_buffer
= 0;
6660 src
->mgr
.next_input_byte
= NULL
;
6663 /* Load image IMG for use on frame F. Patterned after example.c
6664 from the JPEG lib. */
6667 jpeg_load_body (struct frame
*f
, struct image
*img
,
6668 struct my_jpeg_error_mgr
*mgr
)
6670 Lisp_Object specified_file
;
6671 Lisp_Object NONVOLATILE specified_data
;
6672 FILE *volatile fp
= NULL
;
6674 int row_stride
, x
, y
;
6675 unsigned long *colors
;
6679 XImagePtr ximg
= NULL
;
6682 /* Open the JPEG file. */
6683 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6684 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6686 if (NILP (specified_data
))
6689 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
6690 if (!STRINGP (file
))
6692 image_error ("Cannot find image file `%s'", specified_file
);
6696 fp
= fdopen (fd
, "rb");
6699 image_error ("Cannot open `%s'", file
);
6703 else if (!STRINGP (specified_data
))
6705 image_error ("Invalid image data `%s'", specified_data
);
6709 /* Customize libjpeg's error handling to call my_error_exit when an
6710 error is detected. This function will perform a longjmp. */
6711 mgr
->cinfo
.err
= jpeg_std_error (&mgr
->pub
);
6712 mgr
->pub
.error_exit
= my_error_exit
;
6713 if (sys_setjmp (mgr
->setjmp_buffer
))
6715 switch (mgr
->failure_code
)
6717 case MY_JPEG_ERROR_EXIT
:
6719 char buf
[JMSG_LENGTH_MAX
];
6720 mgr
->cinfo
.err
->format_message ((j_common_ptr
) &mgr
->cinfo
, buf
);
6721 image_error ("Error reading JPEG image `%s': %s",
6722 img
->spec
, build_string (buf
));
6726 case MY_JPEG_INVALID_IMAGE_SIZE
:
6727 image_size_error ();
6730 case MY_JPEG_CANNOT_CREATE_X
:
6734 /* Close the input file and destroy the JPEG object. */
6737 jpeg_destroy_decompress (&mgr
->cinfo
);
6739 /* If we already have an XImage, free that. */
6741 x_destroy_x_image (ximg
);
6743 /* Free pixmap and colors. */
6744 x_clear_image (f
, img
);
6748 /* Create the JPEG decompression object. Let it read from fp.
6749 Read the JPEG image header. */
6750 jpeg_CreateDecompress (&mgr
->cinfo
, JPEG_LIB_VERSION
, sizeof *&mgr
->cinfo
);
6752 if (NILP (specified_data
))
6753 jpeg_file_src (&mgr
->cinfo
, fp
);
6755 jpeg_memory_src (&mgr
->cinfo
, SDATA (specified_data
),
6756 SBYTES (specified_data
));
6758 jpeg_read_header (&mgr
->cinfo
, 1);
6760 /* Customize decompression so that color quantization will be used.
6761 Start decompression. */
6762 mgr
->cinfo
.quantize_colors
= 1;
6763 jpeg_start_decompress (&mgr
->cinfo
);
6764 width
= img
->width
= mgr
->cinfo
.output_width
;
6765 height
= img
->height
= mgr
->cinfo
.output_height
;
6767 if (!check_image_size (f
, width
, height
))
6769 mgr
->failure_code
= MY_JPEG_INVALID_IMAGE_SIZE
;
6770 sys_longjmp (mgr
->setjmp_buffer
, 1);
6774 /* Create X image and pixmap. */
6775 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6777 mgr
->failure_code
= MY_JPEG_CANNOT_CREATE_X
;
6778 sys_longjmp (mgr
->setjmp_buffer
, 1);
6782 /* Allocate colors. When color quantization is used,
6783 mgr->cinfo.actual_number_of_colors has been set with the number of
6784 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6785 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6786 No more than 255 colors will be generated. */
6789 if (mgr
->cinfo
.out_color_components
> 2)
6790 ir
= 0, ig
= 1, ib
= 2;
6791 else if (mgr
->cinfo
.out_color_components
> 1)
6792 ir
= 0, ig
= 1, ib
= 0;
6794 ir
= 0, ig
= 0, ib
= 0;
6797 /* Use the color table mechanism because it handles colors that
6798 cannot be allocated nicely. Such colors will be replaced with
6799 a default color, and we don't have to care about which colors
6800 can be freed safely, and which can't. */
6801 init_color_table ();
6802 SAFE_NALLOCA (colors
, 1, mgr
->cinfo
.actual_number_of_colors
);
6804 for (i
= 0; i
< mgr
->cinfo
.actual_number_of_colors
; ++i
)
6806 /* Multiply RGB values with 255 because X expects RGB values
6807 in the range 0..0xffff. */
6808 int r
= mgr
->cinfo
.colormap
[ir
][i
] << 8;
6809 int g
= mgr
->cinfo
.colormap
[ig
][i
] << 8;
6810 int b
= mgr
->cinfo
.colormap
[ib
][i
] << 8;
6811 colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
6815 #ifdef COLOR_TABLE_SUPPORT
6816 /* Remember those colors actually allocated. */
6817 img
->colors
= colors_in_color_table (&img
->ncolors
);
6818 free_color_table ();
6819 #endif /* COLOR_TABLE_SUPPORT */
6823 row_stride
= width
* mgr
->cinfo
.output_components
;
6824 buffer
= mgr
->cinfo
.mem
->alloc_sarray ((j_common_ptr
) &mgr
->cinfo
,
6825 JPOOL_IMAGE
, row_stride
, 1);
6828 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
6829 uint32_t *dataptr
= (uint32_t *) data
;
6832 for (y
= 0; y
< height
; ++y
)
6834 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6836 for (x
= 0; x
< width
; ++x
)
6839 r
= mgr
->cinfo
.colormap
[ir
][i
];
6840 g
= mgr
->cinfo
.colormap
[ig
][i
];
6841 b
= mgr
->cinfo
.colormap
[ib
][i
];
6842 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
6846 create_cairo_image_surface (img
, data
, width
, height
);
6849 for (y
= 0; y
< height
; ++y
)
6851 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6852 for (x
= 0; x
< mgr
->cinfo
.output_width
; ++x
)
6853 XPutPixel (ximg
, x
, y
, colors
[buffer
[0][x
]]);
6858 jpeg_finish_decompress (&mgr
->cinfo
);
6859 jpeg_destroy_decompress (&mgr
->cinfo
);
6864 /* Maybe fill in the background field while we have ximg handy. */
6865 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6866 /* Casting avoids a GCC warning. */
6867 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6869 /* Put ximg into the image. */
6870 image_put_x_image (f
, img
, ximg
, 0);
6877 jpeg_load (struct frame
*f
, struct image
*img
)
6879 struct my_jpeg_error_mgr mgr
;
6880 return jpeg_load_body (f
, img
, &mgr
);
6883 #else /* HAVE_JPEG */
6887 jpeg_load (struct frame
*f
, struct image
*img
)
6889 return ns_load_image (f
, img
,
6890 image_spec_value (img
->spec
, QCfile
, NULL
),
6891 image_spec_value (img
->spec
, QCdata
, NULL
));
6893 #endif /* HAVE_NS */
6895 #endif /* !HAVE_JPEG */
6899 /***********************************************************************
6901 ***********************************************************************/
6903 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6905 static bool tiff_image_p (Lisp_Object object
);
6906 static bool tiff_load (struct frame
*f
, struct image
*img
);
6908 /* Indices of image specification fields in tiff_format, below. */
6910 enum tiff_keyword_index
6919 TIFF_HEURISTIC_MASK
,
6926 /* Vector of image_keyword structures describing the format
6927 of valid user-defined image specifications. */
6929 static const struct image_keyword tiff_format
[TIFF_LAST
] =
6931 {":type", IMAGE_SYMBOL_VALUE
, 1},
6932 {":data", IMAGE_STRING_VALUE
, 0},
6933 {":file", IMAGE_STRING_VALUE
, 0},
6934 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6935 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6936 {":relief", IMAGE_INTEGER_VALUE
, 0},
6937 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6938 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6939 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6940 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
6941 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0}
6944 #if defined HAVE_NTGUI && defined WINDOWSNT
6945 static bool init_tiff_functions (void);
6947 #define init_tiff_functions NULL
6950 /* Structure describing the image type `tiff'. */
6952 static struct image_type tiff_type
=
6954 SYMBOL_INDEX (Qtiff
),
6958 init_tiff_functions
,
6962 /* Return true if OBJECT is a valid TIFF image specification. */
6965 tiff_image_p (Lisp_Object object
)
6967 struct image_keyword fmt
[TIFF_LAST
];
6968 memcpy (fmt
, tiff_format
, sizeof fmt
);
6970 if (!parse_image_spec (object
, fmt
, TIFF_LAST
, Qtiff
))
6973 /* Must specify either the :data or :file keyword. */
6974 return fmt
[TIFF_FILE
].count
+ fmt
[TIFF_DATA
].count
== 1;
6977 #endif /* HAVE_TIFF || HAVE_NS */
6981 # include <tiffio.h>
6985 /* TIFF library details. */
6986 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetErrorHandler
, (TIFFErrorHandler
));
6987 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetWarningHandler
, (TIFFErrorHandler
));
6988 DEF_DLL_FN (TIFF
*, TIFFOpen
, (const char *, const char *));
6989 DEF_DLL_FN (TIFF
*, TIFFClientOpen
,
6990 (const char *, const char *, thandle_t
, TIFFReadWriteProc
,
6991 TIFFReadWriteProc
, TIFFSeekProc
, TIFFCloseProc
, TIFFSizeProc
,
6992 TIFFMapFileProc
, TIFFUnmapFileProc
));
6993 DEF_DLL_FN (int, TIFFGetField
, (TIFF
*, ttag_t
, ...));
6994 DEF_DLL_FN (int, TIFFReadRGBAImage
, (TIFF
*, uint32
, uint32
, uint32
*, int));
6995 DEF_DLL_FN (void, TIFFClose
, (TIFF
*));
6996 DEF_DLL_FN (int, TIFFSetDirectory
, (TIFF
*, tdir_t
));
6999 init_tiff_functions (void)
7003 if (!(library
= w32_delayed_load (Qtiff
)))
7006 LOAD_DLL_FN (library
, TIFFSetErrorHandler
);
7007 LOAD_DLL_FN (library
, TIFFSetWarningHandler
);
7008 LOAD_DLL_FN (library
, TIFFOpen
);
7009 LOAD_DLL_FN (library
, TIFFClientOpen
);
7010 LOAD_DLL_FN (library
, TIFFGetField
);
7011 LOAD_DLL_FN (library
, TIFFReadRGBAImage
);
7012 LOAD_DLL_FN (library
, TIFFClose
);
7013 LOAD_DLL_FN (library
, TIFFSetDirectory
);
7017 # undef TIFFClientOpen
7019 # undef TIFFGetField
7021 # undef TIFFReadRGBAImage
7022 # undef TIFFSetDirectory
7023 # undef TIFFSetErrorHandler
7024 # undef TIFFSetWarningHandler
7026 # define TIFFClientOpen fn_TIFFClientOpen
7027 # define TIFFClose fn_TIFFClose
7028 # define TIFFGetField fn_TIFFGetField
7029 # define TIFFOpen fn_TIFFOpen
7030 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7031 # define TIFFSetDirectory fn_TIFFSetDirectory
7032 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7033 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7035 # endif /* WINDOWSNT */
7038 /* Reading from a memory buffer for TIFF images Based on the PNG
7039 memory source, but we have to provide a lot of extra functions.
7042 We really only need to implement read and seek, but I am not
7043 convinced that the TIFF library is smart enough not to destroy
7044 itself if we only hand it the function pointers we need to
7049 unsigned char *bytes
;
7056 tiff_read_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7058 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7060 size
= min (size
, src
->len
- src
->index
);
7061 memcpy (buf
, src
->bytes
+ src
->index
, size
);
7067 tiff_write_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7073 tiff_seek_in_memory (thandle_t data
, toff_t off
, int whence
)
7075 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7080 case SEEK_SET
: /* Go from beginning of source. */
7084 case SEEK_END
: /* Go from end of source. */
7085 idx
= src
->len
+ off
;
7088 case SEEK_CUR
: /* Go from current position. */
7089 idx
= src
->index
+ off
;
7092 default: /* Invalid `whence'. */
7096 if (idx
> src
->len
|| idx
< 0)
7104 tiff_close_memory (thandle_t data
)
7111 tiff_mmap_memory (thandle_t data
, tdata_t
*pbase
, toff_t
*psize
)
7113 /* It is already _IN_ memory. */
7118 tiff_unmap_memory (thandle_t data
, tdata_t base
, toff_t size
)
7120 /* We don't need to do this. */
7124 tiff_size_of_memory (thandle_t data
)
7126 return ((tiff_memory_source
*) data
)->len
;
7129 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7130 compiler error compiling tiff_handler, see Bugzilla bug #17406
7131 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7132 this function as external works around that problem. */
7133 # if defined (__MINGW32__) && __GNUC__ == 3
7134 # define MINGW_STATIC
7136 # define MINGW_STATIC static
7140 tiff_handler (const char *, const char *, const char *, va_list)
7141 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7143 tiff_handler (const char *log_format
, const char *title
,
7144 const char *format
, va_list ap
)
7146 /* doprnt is not suitable here, as TIFF handlers are called from
7147 libtiff and are passed arbitrary printf directives. Instead, use
7148 vsnprintf, taking care to be portable to nonstandard environments
7149 where vsnprintf returns -1 on buffer overflow. Since it's just a
7150 log entry, it's OK to truncate it. */
7152 int len
= vsnprintf (buf
, sizeof buf
, format
, ap
);
7153 add_to_log (log_format
, build_string (title
),
7154 make_string (buf
, max (0, min (len
, sizeof buf
- 1))));
7156 # undef MINGW_STATIC
7158 static void tiff_error_handler (const char *, const char *, va_list)
7159 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7161 tiff_error_handler (const char *title
, const char *format
, va_list ap
)
7163 tiff_handler ("TIFF error: %s %s", title
, format
, ap
);
7167 static void tiff_warning_handler (const char *, const char *, va_list)
7168 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7170 tiff_warning_handler (const char *title
, const char *format
, va_list ap
)
7172 tiff_handler ("TIFF warning: %s %s", title
, format
, ap
);
7176 /* Load TIFF image IMG for use on frame F. Value is true if
7180 tiff_load (struct frame
*f
, struct image
*img
)
7182 Lisp_Object specified_file
;
7183 Lisp_Object specified_data
;
7185 int width
, height
, x
, y
, count
;
7189 tiff_memory_source memsrc
;
7192 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7193 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7195 TIFFSetErrorHandler ((TIFFErrorHandler
) tiff_error_handler
);
7196 TIFFSetWarningHandler ((TIFFErrorHandler
) tiff_warning_handler
);
7198 if (NILP (specified_data
))
7200 /* Read from a file */
7201 Lisp_Object file
= x_find_image_file (specified_file
);
7202 if (!STRINGP (file
))
7204 image_error ("Cannot find image file `%s'", specified_file
);
7208 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7210 encoded_file
= ansi_encode_filename (encoded_file
);
7213 /* Try to open the image file. */
7214 tiff
= TIFFOpen (SSDATA (encoded_file
), "r");
7217 image_error ("Cannot open `%s'", file
);
7223 if (!STRINGP (specified_data
))
7225 image_error ("Invalid image data `%s'", specified_data
);
7229 /* Memory source! */
7230 memsrc
.bytes
= SDATA (specified_data
);
7231 memsrc
.len
= SBYTES (specified_data
);
7234 tiff
= TIFFClientOpen ("memory_source", "r", (thandle_t
)&memsrc
,
7235 tiff_read_from_memory
,
7236 tiff_write_from_memory
,
7237 tiff_seek_in_memory
,
7239 tiff_size_of_memory
,
7245 image_error ("Cannot open memory source for `%s'", img
->spec
);
7250 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
7251 if (INTEGERP (image
))
7253 EMACS_INT ino
= XFASTINT (image
);
7254 if (! (TYPE_MINIMUM (tdir_t
) <= ino
&& ino
<= TYPE_MAXIMUM (tdir_t
)
7255 && TIFFSetDirectory (tiff
, ino
)))
7257 image_error ("Invalid image number `%s' in image `%s'",
7264 /* Get width and height of the image, and allocate a raster buffer
7265 of width x height 32-bit values. */
7266 TIFFGetField (tiff
, TIFFTAG_IMAGEWIDTH
, &width
);
7267 TIFFGetField (tiff
, TIFFTAG_IMAGELENGTH
, &height
);
7269 if (!check_image_size (f
, width
, height
))
7271 image_size_error ();
7276 /* Create the X image and pixmap. */
7277 if (! (height
<= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *buf
/ width
7278 && image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
7285 buf
= xmalloc (sizeof *buf
* width
* height
);
7287 rc
= TIFFReadRGBAImage (tiff
, width
, height
, buf
, 0);
7289 /* Count the number of images in the file. */
7290 for (count
= 1; TIFFSetDirectory (tiff
, count
); count
++)
7294 img
->lisp_data
= Fcons (Qcount
,
7295 Fcons (make_number (count
),
7301 image_error ("Error reading TIFF image `%s'", img
->spec
);
7308 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
7309 uint32_t *dataptr
= (uint32_t *) data
;
7311 for (y
= 0; y
< height
; ++y
)
7313 uint32
*row
= buf
+ (height
- 1 - y
) * width
;
7314 for (x
= 0; x
< width
; ++x
)
7316 uint32 abgr
= row
[x
];
7317 int r
= TIFFGetR (abgr
);
7318 int g
= TIFFGetG (abgr
);
7319 int b
= TIFFGetB (abgr
);
7320 int a
= TIFFGetA (abgr
);
7321 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
7325 create_cairo_image_surface (img
, data
, width
, height
);
7328 /* Initialize the color table. */
7329 init_color_table ();
7331 /* Process the pixel raster. Origin is in the lower-left corner. */
7332 for (y
= 0; y
< height
; ++y
)
7334 uint32
*row
= buf
+ y
* width
;
7336 for (x
= 0; x
< width
; ++x
)
7338 uint32 abgr
= row
[x
];
7339 int r
= TIFFGetR (abgr
) << 8;
7340 int g
= TIFFGetG (abgr
) << 8;
7341 int b
= TIFFGetB (abgr
) << 8;
7342 XPutPixel (ximg
, x
, height
- 1 - y
, lookup_rgb_color (f
, r
, g
, b
));
7346 # ifdef COLOR_TABLE_SUPPORT
7347 /* Remember the colors allocated for the image. Free the color table. */
7348 img
->colors
= colors_in_color_table (&img
->ncolors
);
7349 free_color_table ();
7350 # endif /* COLOR_TABLE_SUPPORT */
7353 img
->height
= height
;
7355 /* Maybe fill in the background field while we have ximg handy. */
7356 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7357 /* Casting avoids a GCC warning on W32. */
7358 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7360 /* Put ximg into the image. */
7361 image_put_x_image (f
, img
, ximg
, 0);
7363 #endif /* ! USE_CAIRO */
7369 #elif defined HAVE_NS
7372 tiff_load (struct frame
*f
, struct image
*img
)
7374 return ns_load_image (f
, img
,
7375 image_spec_value (img
->spec
, QCfile
, NULL
),
7376 image_spec_value (img
->spec
, QCdata
, NULL
));
7383 /***********************************************************************
7385 ***********************************************************************/
7387 #if defined (HAVE_GIF) || defined (HAVE_NS)
7389 static bool gif_image_p (Lisp_Object object
);
7390 static bool gif_load (struct frame
*f
, struct image
*img
);
7391 static void gif_clear_image (struct frame
*f
, struct image
*img
);
7393 /* Indices of image specification fields in gif_format, below. */
7395 enum gif_keyword_index
7411 /* Vector of image_keyword structures describing the format
7412 of valid user-defined image specifications. */
7414 static const struct image_keyword gif_format
[GIF_LAST
] =
7416 {":type", IMAGE_SYMBOL_VALUE
, 1},
7417 {":data", IMAGE_STRING_VALUE
, 0},
7418 {":file", IMAGE_STRING_VALUE
, 0},
7419 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7420 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7421 {":relief", IMAGE_INTEGER_VALUE
, 0},
7422 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7423 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7424 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7425 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0},
7426 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
7429 #if defined HAVE_NTGUI && defined WINDOWSNT
7430 static bool init_gif_functions (void);
7432 #define init_gif_functions NULL
7435 /* Structure describing the image type `gif'. */
7437 static struct image_type gif_type
=
7439 SYMBOL_INDEX (Qgif
),
7447 /* Free X resources of GIF image IMG which is used on frame F. */
7450 gif_clear_image (struct frame
*f
, struct image
*img
)
7452 img
->lisp_data
= Qnil
;
7453 x_clear_image (f
, img
);
7456 /* Return true if OBJECT is a valid GIF image specification. */
7459 gif_image_p (Lisp_Object object
)
7461 struct image_keyword fmt
[GIF_LAST
];
7462 memcpy (fmt
, gif_format
, sizeof fmt
);
7464 if (!parse_image_spec (object
, fmt
, GIF_LAST
, Qgif
))
7467 /* Must specify either the :data or :file keyword. */
7468 return fmt
[GIF_FILE
].count
+ fmt
[GIF_DATA
].count
== 1;
7471 #endif /* HAVE_GIF */
7477 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7478 Undefine before redefining to avoid a preprocessor warning. */
7482 /* avoid conflict with QuickdrawText.h */
7483 # define DrawText gif_DrawText
7484 # include <gif_lib.h>
7487 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7488 # ifndef GIFLIB_MINOR
7489 # define GIFLIB_MINOR 0
7491 # ifndef GIFLIB_RELEASE
7492 # define GIFLIB_RELEASE 0
7495 # else /* HAVE_NTGUI */
7497 # include <gif_lib.h>
7499 # endif /* HAVE_NTGUI */
7501 /* Giflib before 5.0 didn't define these macros. */
7502 # ifndef GIFLIB_MAJOR
7503 # define GIFLIB_MAJOR 4
7506 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7507 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7508 earlier releases, where either it returns char * or GIFLIB_MINOR
7509 may be incorrect. */
7510 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7514 /* GIF library details. */
7515 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7516 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*, int *));
7518 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*));
7520 DEF_DLL_FN (int, DGifSlurp
, (GifFileType
*));
7521 # if GIFLIB_MAJOR < 5
7522 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
));
7523 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *));
7525 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
, int *));
7526 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *, int *));
7528 # if HAVE_GIFERRORSTRING
7529 DEF_DLL_FN (char const *, GifErrorString
, (int));
7533 init_gif_functions (void)
7537 if (!(library
= w32_delayed_load (Qgif
)))
7540 LOAD_DLL_FN (library
, DGifCloseFile
);
7541 LOAD_DLL_FN (library
, DGifSlurp
);
7542 LOAD_DLL_FN (library
, DGifOpen
);
7543 LOAD_DLL_FN (library
, DGifOpenFileName
);
7544 # if HAVE_GIFERRORSTRING
7545 LOAD_DLL_FN (library
, GifErrorString
);
7550 # undef DGifCloseFile
7552 # undef DGifOpenFileName
7554 # undef GifErrorString
7556 # define DGifCloseFile fn_DGifCloseFile
7557 # define DGifOpen fn_DGifOpen
7558 # define DGifOpenFileName fn_DGifOpenFileName
7559 # define DGifSlurp fn_DGifSlurp
7560 # define GifErrorString fn_GifErrorString
7562 # endif /* WINDOWSNT */
7564 /* Reading a GIF image from memory
7565 Based on the PNG memory stuff to a certain extent. */
7569 unsigned char *bytes
;
7575 /* Make the current memory source available to gif_read_from_memory.
7576 It's done this way because not all versions of libungif support
7577 a UserData field in the GifFileType structure. */
7578 static gif_memory_source
*current_gif_memory_src
;
7581 gif_read_from_memory (GifFileType
*file
, GifByteType
*buf
, int len
)
7583 gif_memory_source
*src
= current_gif_memory_src
;
7585 if (len
> src
->len
- src
->index
)
7588 memcpy (buf
, src
->bytes
+ src
->index
, len
);
7594 gif_close (GifFileType
*gif
, int *err
)
7598 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7599 retval
= DGifCloseFile (gif
, err
);
7601 retval
= DGifCloseFile (gif
);
7602 #if GIFLIB_MAJOR >= 5
7610 /* Load GIF image IMG for use on frame F. Value is true if
7613 static const int interlace_start
[] = {0, 4, 2, 1};
7614 static const int interlace_increment
[] = {8, 8, 4, 2};
7616 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7619 gif_load (struct frame
*f
, struct image
*img
)
7621 int rc
, width
, height
, x
, y
, i
, j
;
7622 ColorMapObject
*gif_color_map
;
7624 gif_memory_source memsrc
;
7625 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
7626 Lisp_Object specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7627 Lisp_Object specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7632 unsigned char *data
= 0;
7634 unsigned long pixel_colors
[256];
7635 unsigned long bgcolor
= 0;
7639 if (NILP (specified_data
))
7641 Lisp_Object file
= x_find_image_file (specified_file
);
7642 if (!STRINGP (file
))
7644 image_error ("Cannot find image file `%s'", specified_file
);
7648 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7650 encoded_file
= ansi_encode_filename (encoded_file
);
7653 /* Open the GIF file. */
7654 #if GIFLIB_MAJOR < 5
7655 gif
= DGifOpenFileName (SSDATA (encoded_file
));
7657 gif
= DGifOpenFileName (SSDATA (encoded_file
), &gif_err
);
7661 #if HAVE_GIFERRORSTRING
7662 image_error ("Cannot open `%s': %s",
7663 file
, build_string (GifErrorString (gif_err
)));
7665 image_error ("Cannot open `%s'", file
);
7672 if (!STRINGP (specified_data
))
7674 image_error ("Invalid image data `%s'", specified_data
);
7678 /* Read from memory! */
7679 current_gif_memory_src
= &memsrc
;
7680 memsrc
.bytes
= SDATA (specified_data
);
7681 memsrc
.len
= SBYTES (specified_data
);
7684 #if GIFLIB_MAJOR < 5
7685 gif
= DGifOpen (&memsrc
, gif_read_from_memory
);
7687 gif
= DGifOpen (&memsrc
, gif_read_from_memory
, &gif_err
);
7691 #if HAVE_GIFERRORSTRING
7692 image_error ("Cannot open memory source `%s': %s",
7693 img
->spec
, build_string (GifErrorString (gif_err
)));
7695 image_error ("Cannot open memory source `%s'", img
->spec
);
7701 /* Before reading entire contents, check the declared image size. */
7702 if (!check_image_size (f
, gif
->SWidth
, gif
->SHeight
))
7704 image_size_error ();
7705 gif_close (gif
, NULL
);
7709 /* Read entire contents. */
7710 rc
= DGifSlurp (gif
);
7711 if (rc
== GIF_ERROR
|| gif
->ImageCount
<= 0)
7713 image_error ("Error reading `%s'", img
->spec
);
7714 gif_close (gif
, NULL
);
7718 /* Which sub-image are we to display? */
7720 Lisp_Object image_number
= image_spec_value (img
->spec
, QCindex
, NULL
);
7721 idx
= INTEGERP (image_number
) ? XFASTINT (image_number
) : 0;
7722 if (idx
< 0 || idx
>= gif
->ImageCount
)
7724 image_error ("Invalid image number `%s' in image `%s'",
7725 image_number
, img
->spec
);
7726 gif_close (gif
, NULL
);
7731 width
= img
->width
= gif
->SWidth
;
7732 height
= img
->height
= gif
->SHeight
;
7734 img
->corners
[TOP_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Top
;
7735 img
->corners
[LEFT_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Left
;
7736 img
->corners
[BOT_CORNER
]
7737 = img
->corners
[TOP_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Height
;
7738 img
->corners
[RIGHT_CORNER
]
7739 = img
->corners
[LEFT_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Width
;
7741 if (!check_image_size (f
, width
, height
))
7743 image_size_error ();
7744 gif_close (gif
, NULL
);
7748 /* Check that the selected subimages fit. It's not clear whether
7749 the GIF spec requires this, but Emacs can crash if they don't fit. */
7750 for (j
= 0; j
<= idx
; ++j
)
7752 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7753 int subimg_width
= subimage
->ImageDesc
.Width
;
7754 int subimg_height
= subimage
->ImageDesc
.Height
;
7755 int subimg_top
= subimage
->ImageDesc
.Top
;
7756 int subimg_left
= subimage
->ImageDesc
.Left
;
7757 if (! (subimg_width
>= 0 && subimg_height
>= 0
7758 && 0 <= subimg_top
&& subimg_top
<= height
- subimg_height
7759 && 0 <= subimg_left
&& subimg_left
<= width
- subimg_width
))
7761 image_error ("Subimage does not fit in image");
7762 gif_close (gif
, NULL
);
7768 /* xzalloc so data is zero => transparent */
7769 data
= (unsigned char *) xzalloc (width
* height
* 4);
7770 if (STRINGP (specified_bg
))
7773 if (x_defined_color (f
, SSDATA (specified_bg
), &color
, 0))
7775 uint32_t *dataptr
= (uint32_t *)data
;
7776 int r
= color
.red
/256;
7777 int g
= color
.green
/256;
7778 int b
= color
.blue
/256;
7780 for (y
= 0; y
< height
; ++y
)
7781 for (x
= 0; x
< width
; ++x
)
7782 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7786 /* Create the X image and pixmap. */
7787 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
7789 gif_close (gif
, NULL
);
7793 /* Clear the part of the screen image not covered by the image.
7794 Full animated GIF support requires more here (see the gif89 spec,
7795 disposal methods). Let's simply assume that the part not covered
7796 by a sub-image is in the frame's background color. */
7797 for (y
= 0; y
< img
->corners
[TOP_CORNER
]; ++y
)
7798 for (x
= 0; x
< width
; ++x
)
7799 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7801 for (y
= img
->corners
[BOT_CORNER
]; y
< height
; ++y
)
7802 for (x
= 0; x
< width
; ++x
)
7803 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7805 for (y
= img
->corners
[TOP_CORNER
]; y
< img
->corners
[BOT_CORNER
]; ++y
)
7807 for (x
= 0; x
< img
->corners
[LEFT_CORNER
]; ++x
)
7808 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7809 for (x
= img
->corners
[RIGHT_CORNER
]; x
< width
; ++x
)
7810 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7814 /* Read the GIF image into the X image. */
7816 /* FIXME: With the current implementation, loading an animated gif
7817 is quadratic in the number of animation frames, since each frame
7818 is a separate struct image. We must provide a way for a single
7819 gif_load call to construct and save all animation frames. */
7821 init_color_table ();
7824 if (STRINGP (specified_bg
))
7825 bgcolor
= x_alloc_image_color (f
, img
, specified_bg
,
7826 FRAME_BACKGROUND_PIXEL (f
));
7829 for (j
= 0; j
<= idx
; ++j
)
7831 /* We use a local variable `raster' here because RasterBits is a
7832 char *, which invites problems with bytes >= 0x80. */
7833 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7834 unsigned char *raster
= (unsigned char *) subimage
->RasterBits
;
7835 int transparency_color_index
= -1;
7837 int subimg_width
= subimage
->ImageDesc
.Width
;
7838 int subimg_height
= subimage
->ImageDesc
.Height
;
7839 int subimg_top
= subimage
->ImageDesc
.Top
;
7840 int subimg_left
= subimage
->ImageDesc
.Left
;
7842 /* Find the Graphic Control Extension block for this sub-image.
7843 Extract the disposal method and transparency color. */
7844 for (i
= 0; i
< subimage
->ExtensionBlockCount
; i
++)
7846 ExtensionBlock
*extblock
= subimage
->ExtensionBlocks
+ i
;
7848 if ((extblock
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
)
7849 && extblock
->ByteCount
== 4
7850 && extblock
->Bytes
[0] & 1)
7852 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7853 to background". Treat any other value like 2. */
7854 disposal
= (extblock
->Bytes
[0] >> 2) & 7;
7855 transparency_color_index
= (unsigned char) extblock
->Bytes
[3];
7860 /* We can't "keep in place" the first subimage. */
7864 /* For disposal == 0, the spec says "No disposal specified. The
7865 decoder is not required to take any action." In practice, it
7866 seems we need to treat this like "keep in place", see e.g.
7867 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7871 gif_color_map
= subimage
->ImageDesc
.ColorMap
;
7873 gif_color_map
= gif
->SColorMap
;
7876 /* Allocate subimage colors. */
7877 memset (pixel_colors
, 0, sizeof pixel_colors
);
7880 for (i
= 0; i
< gif_color_map
->ColorCount
; ++i
)
7882 if (transparency_color_index
== i
)
7883 pixel_colors
[i
] = STRINGP (specified_bg
)
7884 ? bgcolor
: FRAME_BACKGROUND_PIXEL (f
);
7887 int r
= gif_color_map
->Colors
[i
].Red
<< 8;
7888 int g
= gif_color_map
->Colors
[i
].Green
<< 8;
7889 int b
= gif_color_map
->Colors
[i
].Blue
<< 8;
7890 pixel_colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
7895 /* Apply the pixel values. */
7896 if (GIFLIB_MAJOR
< 5 && gif
->SavedImages
[j
].ImageDesc
.Interlace
)
7900 for (y
= 0, row
= interlace_start
[0], pass
= 0;
7902 y
++, row
+= interlace_increment
[pass
])
7904 while (subimg_height
<= row
)
7905 row
= interlace_start
[++pass
];
7907 for (x
= 0; x
< subimg_width
; x
++)
7909 int c
= raster
[y
* subimg_width
+ x
];
7910 if (transparency_color_index
!= c
|| disposal
!= 1)
7914 ((uint32_t*)data
+ ((row
+ subimg_top
) * subimg_width
7915 + x
+ subimg_left
));
7916 int r
= gif_color_map
->Colors
[c
].Red
;
7917 int g
= gif_color_map
->Colors
[c
].Green
;
7918 int b
= gif_color_map
->Colors
[c
].Blue
;
7920 if (transparency_color_index
!= c
)
7921 *dataptr
= (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7923 XPutPixel (ximg
, x
+ subimg_left
, row
+ subimg_top
,
7932 for (y
= 0; y
< subimg_height
; ++y
)
7933 for (x
= 0; x
< subimg_width
; ++x
)
7935 int c
= raster
[y
* subimg_width
+ x
];
7936 if (transparency_color_index
!= c
|| disposal
!= 1)
7940 ((uint32_t*)data
+ ((y
+ subimg_top
) * subimg_width
7941 + x
+ subimg_left
));
7942 int r
= gif_color_map
->Colors
[c
].Red
;
7943 int g
= gif_color_map
->Colors
[c
].Green
;
7944 int b
= gif_color_map
->Colors
[c
].Blue
;
7945 if (transparency_color_index
!= c
)
7946 *dataptr
= (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7948 XPutPixel (ximg
, x
+ subimg_left
, y
+ subimg_top
,
7956 #ifdef COLOR_TABLE_SUPPORT
7957 img
->colors
= colors_in_color_table (&img
->ncolors
);
7958 free_color_table ();
7959 #endif /* COLOR_TABLE_SUPPORT */
7961 /* Save GIF image extension data for `image-metadata'.
7962 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7963 img
->lisp_data
= Qnil
;
7964 if (gif
->SavedImages
[idx
].ExtensionBlockCount
> 0)
7967 ExtensionBlock
*ext
= gif
->SavedImages
[idx
].ExtensionBlocks
;
7968 for (i
= 0; i
< gif
->SavedImages
[idx
].ExtensionBlockCount
; i
++, ext
++)
7969 /* Append (... FUNCTION "BYTES") */
7972 = Fcons (make_number (ext
->Function
),
7973 Fcons (make_unibyte_string ((char *) ext
->Bytes
,
7976 if (ext
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
7977 && ext
->ByteCount
== 4)
7979 delay
= ext
->Bytes
[2] << CHAR_BIT
;
7980 delay
|= ext
->Bytes
[1];
7983 img
->lisp_data
= list2 (Qextension_data
, img
->lisp_data
);
7987 Fcons (make_float (delay
/ 100.0),
7991 if (gif
->ImageCount
> 1)
7992 img
->lisp_data
= Fcons (Qcount
,
7993 Fcons (make_number (gif
->ImageCount
),
7996 if (gif_close (gif
, &gif_err
) == GIF_ERROR
)
7998 #if HAVE_GIFERRORSTRING
7999 char const *error_text
= GifErrorString (gif_err
);
8002 image_error ("Error closing `%s': %s",
8003 img
->spec
, build_string (error_text
));
8005 image_error ("Error closing `%s'", img
->spec
);
8010 create_cairo_image_surface (img
, data
, width
, height
);
8012 /* Maybe fill in the background field while we have ximg handy. */
8013 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
8014 /* Casting avoids a GCC warning. */
8015 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
8017 /* Put ximg into the image. */
8018 image_put_x_image (f
, img
, ximg
, 0);
8024 #else /* !HAVE_GIF */
8028 gif_load (struct frame
*f
, struct image
*img
)
8030 return ns_load_image (f
, img
,
8031 image_spec_value (img
->spec
, QCfile
, NULL
),
8032 image_spec_value (img
->spec
, QCdata
, NULL
));
8034 #endif /* HAVE_NS */
8036 #endif /* HAVE_GIF */
8039 #ifdef HAVE_IMAGEMAGICK
8041 /***********************************************************************
8043 ***********************************************************************/
8045 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8046 safely rounded and clipped to int range. */
8049 scale_image_size (int size
, size_t divisor
, size_t multiplier
)
8054 double scaled
= s
* multiplier
/ divisor
+ 0.5;
8055 if (scaled
< INT_MAX
)
8061 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8062 Use SPEC to deduce the size. Store the desired size into
8063 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8065 compute_image_size (size_t width
, size_t height
,
8067 int *d_width
, int *d_height
)
8070 int desired_width
, desired_height
;
8073 value
= image_spec_value (spec
, QCscale
, NULL
);
8074 if (NUMBERP (value
))
8075 scale
= extract_float (value
);
8077 /* If width and/or height is set in the display spec assume we want
8078 to scale to those values. If either h or w is unspecified, the
8079 unspecified should be calculated from the specified to preserve
8081 value
= image_spec_value (spec
, QCwidth
, NULL
);
8082 desired_width
= NATNUMP (value
) ?
8083 min (XFASTINT (value
) * scale
, INT_MAX
) : -1;
8084 value
= image_spec_value (spec
, QCheight
, NULL
);
8085 desired_height
= NATNUMP (value
) ?
8086 min (XFASTINT (value
) * scale
, INT_MAX
) : -1;
8088 width
= width
* scale
;
8089 height
= height
* scale
;
8091 if (desired_width
== -1)
8093 value
= image_spec_value (spec
, QCmax_width
, NULL
);
8094 if (NATNUMP (value
))
8096 int max_width
= min (XFASTINT (value
), INT_MAX
);
8097 if (max_width
< width
)
8099 /* The image is wider than :max-width. */
8100 desired_width
= max_width
;
8101 if (desired_height
== -1)
8103 desired_height
= scale_image_size (desired_width
,
8105 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8106 if (NATNUMP (value
))
8108 int max_height
= min (XFASTINT (value
), INT_MAX
);
8109 if (max_height
< desired_height
)
8111 desired_height
= max_height
;
8112 desired_width
= scale_image_size (desired_height
,
8121 if (desired_height
== -1)
8123 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8124 if (NATNUMP (value
))
8126 int max_height
= min (XFASTINT (value
), INT_MAX
);
8127 if (max_height
< height
)
8128 desired_height
= max_height
;
8132 if (desired_width
!= -1 && desired_height
== -1)
8133 /* w known, calculate h. */
8134 desired_height
= scale_image_size (desired_width
, width
, height
);
8136 if (desired_width
== -1 && desired_height
!= -1)
8137 /* h known, calculate w. */
8138 desired_width
= scale_image_size (desired_height
, height
, width
);
8140 /* We have no width/height settings, so just apply the scale. */
8141 if (desired_width
== -1 && desired_height
== -1)
8143 desired_width
= width
;
8144 desired_height
= height
;
8147 *d_width
= desired_width
;
8148 *d_height
= desired_height
;
8151 static bool imagemagick_image_p (Lisp_Object
);
8152 static bool imagemagick_load (struct frame
*, struct image
*);
8153 static void imagemagick_clear_image (struct frame
*, struct image
*);
8155 /* Indices of image specification fields in imagemagick_format. */
8157 enum imagemagick_keyword_index
8165 IMAGEMAGICK_ALGORITHM
,
8166 IMAGEMAGICK_HEURISTIC_MASK
,
8168 IMAGEMAGICK_BACKGROUND
,
8171 IMAGEMAGICK_MAX_HEIGHT
,
8172 IMAGEMAGICK_MAX_WIDTH
,
8174 IMAGEMAGICK_ROTATION
,
8179 /* Vector of image_keyword structures describing the format
8180 of valid user-defined image specifications. */
8182 static struct image_keyword imagemagick_format
[IMAGEMAGICK_LAST
] =
8184 {":type", IMAGE_SYMBOL_VALUE
, 1},
8185 {":data", IMAGE_STRING_VALUE
, 0},
8186 {":file", IMAGE_STRING_VALUE
, 0},
8187 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8188 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8189 {":relief", IMAGE_INTEGER_VALUE
, 0},
8190 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8191 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8192 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8193 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
8194 {":height", IMAGE_INTEGER_VALUE
, 0},
8195 {":width", IMAGE_INTEGER_VALUE
, 0},
8196 {":max-height", IMAGE_INTEGER_VALUE
, 0},
8197 {":max-width", IMAGE_INTEGER_VALUE
, 0},
8198 {":format", IMAGE_SYMBOL_VALUE
, 0},
8199 {":rotation", IMAGE_NUMBER_VALUE
, 0},
8200 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
8203 #if defined HAVE_NTGUI && defined WINDOWSNT
8204 static bool init_imagemagick_functions (void);
8206 #define init_imagemagick_functions NULL
8209 /* Structure describing the image type for any image handled via
8212 static struct image_type imagemagick_type
=
8214 SYMBOL_INDEX (Qimagemagick
),
8215 imagemagick_image_p
,
8217 imagemagick_clear_image
,
8218 init_imagemagick_functions
,
8222 /* Free X resources of imagemagick image IMG which is used on frame F. */
8225 imagemagick_clear_image (struct frame
*f
,
8228 x_clear_image (f
, img
);
8231 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8232 this by calling parse_image_spec and supplying the keywords that
8233 identify the IMAGEMAGICK format. */
8236 imagemagick_image_p (Lisp_Object object
)
8238 struct image_keyword fmt
[IMAGEMAGICK_LAST
];
8239 memcpy (fmt
, imagemagick_format
, sizeof fmt
);
8241 if (!parse_image_spec (object
, fmt
, IMAGEMAGICK_LAST
, Qimagemagick
))
8244 /* Must specify either the :data or :file keyword. */
8245 return fmt
[IMAGEMAGICK_FILE
].count
+ fmt
[IMAGEMAGICK_DATA
].count
== 1;
8248 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8249 Therefore rename the function so it doesn't collide with ImageMagick. */
8250 #define DrawRectangle DrawRectangleGif
8251 #include <wand/MagickWand.h>
8253 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8254 Emacs seems to work fine with the hidden version, so unhide it. */
8255 #include <magick/version.h>
8256 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8257 extern WandExport
void PixelGetMagickColor (const PixelWand
*,
8258 MagickPixelPacket
*);
8261 /* Log ImageMagick error message.
8262 Useful when a ImageMagick function returns the status `MagickFalse'. */
8265 imagemagick_error (MagickWand
*wand
)
8268 ExceptionType severity
;
8270 description
= MagickGetException (wand
, &severity
);
8271 image_error ("ImageMagick error: %s", build_string (description
));
8272 MagickRelinquishMemory (description
);
8275 /* Possibly give ImageMagick some extra help to determine the image
8276 type by supplying a "dummy" filename based on the Content-Type. */
8279 imagemagick_filename_hint (Lisp_Object spec
, char hint_buffer
[MaxTextExtent
])
8281 Lisp_Object symbol
= intern ("image-format-suffixes");
8282 Lisp_Object val
= find_symbol_value (symbol
);
8288 format
= image_spec_value (spec
, intern (":format"), NULL
);
8289 val
= Fcar_safe (Fcdr_safe (Fassq (format
, val
)));
8290 if (! STRINGP (val
))
8293 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8294 as ImageMagick would ignore the extra bytes anyway. */
8295 snprintf (hint_buffer
, MaxTextExtent
, "/tmp/foo.%s", SSDATA (val
));
8299 /* Animated images (e.g., GIF89a) are composed from one "master image"
8300 (which is the first one, and then there's a number of images that
8301 follow. If following images have non-transparent colors, these are
8302 composed "on top" of the master image. So, in general, one has to
8303 compute ann the preceding images to be able to display a particular
8306 Computing all the preceding images is too slow, so we maintain a
8307 cache of previously computed images. We have to maintain a cache
8308 separate from the image cache, because the images may be scaled
8311 struct animation_cache
8315 struct timespec update_time
;
8316 struct animation_cache
*next
;
8317 char signature
[FLEXIBLE_ARRAY_MEMBER
];
8320 static struct animation_cache
*animation_cache
= NULL
;
8322 static struct animation_cache
*
8323 imagemagick_create_cache (char *signature
)
8325 struct animation_cache
*cache
8326 = xmalloc (offsetof (struct animation_cache
, signature
)
8327 + strlen (signature
) + 1);
8331 strcpy (cache
->signature
, signature
);
8335 /* Discard cached images that haven't been used for a minute. */
8337 imagemagick_prune_animation_cache (void)
8339 struct animation_cache
**pcache
= &animation_cache
;
8340 struct timespec old
= timespec_sub (current_timespec (),
8341 make_timespec (60, 0));
8345 struct animation_cache
*cache
= *pcache
;
8346 if (timespec_cmp (old
, cache
->update_time
) <= 0)
8347 pcache
= &cache
->next
;
8351 DestroyMagickWand (cache
->wand
);
8352 *pcache
= cache
->next
;
8358 static struct animation_cache
*
8359 imagemagick_get_animation_cache (MagickWand
*wand
)
8361 char *signature
= MagickGetImageSignature (wand
);
8362 struct animation_cache
*cache
;
8363 struct animation_cache
**pcache
= &animation_cache
;
8365 imagemagick_prune_animation_cache ();
8372 *pcache
= cache
= imagemagick_create_cache (signature
);
8375 if (strcmp (signature
, cache
->signature
) == 0)
8377 pcache
= &cache
->next
;
8380 DestroyString (signature
);
8381 cache
->update_time
= current_timespec ();
8386 imagemagick_compute_animated_image (MagickWand
*super_wand
, int ino
)
8389 MagickWand
*composite_wand
;
8390 size_t dest_width
, dest_height
;
8391 struct animation_cache
*cache
= imagemagick_get_animation_cache (super_wand
);
8393 MagickSetIteratorIndex (super_wand
, 0);
8395 if (ino
== 0 || cache
->wand
== NULL
|| cache
->index
> ino
)
8397 composite_wand
= MagickGetImage (super_wand
);
8399 DestroyMagickWand (cache
->wand
);
8402 composite_wand
= cache
->wand
;
8404 dest_height
= MagickGetImageHeight (composite_wand
);
8406 for (i
= max (1, cache
->index
+ 1); i
<= ino
; i
++)
8408 MagickWand
*sub_wand
;
8409 PixelIterator
*source_iterator
, *dest_iterator
;
8410 PixelWand
**source
, **dest
;
8411 size_t source_width
, source_height
;
8412 ssize_t source_left
, source_top
;
8413 MagickPixelPacket pixel
;
8414 DisposeType dispose
;
8415 ptrdiff_t lines
= 0;
8417 MagickSetIteratorIndex (super_wand
, i
);
8418 sub_wand
= MagickGetImage (super_wand
);
8420 MagickGetImagePage (sub_wand
, &source_width
, &source_height
,
8421 &source_left
, &source_top
);
8423 /* This flag says how to handle transparent pixels. */
8424 dispose
= MagickGetImageDispose (sub_wand
);
8426 source_iterator
= NewPixelIterator (sub_wand
);
8427 if (! source_iterator
)
8429 DestroyMagickWand (composite_wand
);
8430 DestroyMagickWand (sub_wand
);
8432 image_error ("Imagemagick pixel iterator creation failed");
8436 dest_iterator
= NewPixelIterator (composite_wand
);
8437 if (! dest_iterator
)
8439 DestroyMagickWand (composite_wand
);
8440 DestroyMagickWand (sub_wand
);
8441 DestroyPixelIterator (source_iterator
);
8443 image_error ("Imagemagick pixel iterator creation failed");
8447 /* The sub-image may not start at origin, so move the destination
8448 iterator to where the sub-image should start. */
8451 PixelSetIteratorRow (dest_iterator
, source_top
);
8455 while ((source
= PixelGetNextIteratorRow (source_iterator
, &source_width
))
8460 /* Sanity check. This shouldn't happen, but apparently
8461 does in some pictures. */
8462 if (++lines
>= dest_height
)
8465 dest
= PixelGetNextIteratorRow (dest_iterator
, &dest_width
);
8466 for (x
= 0; x
< source_width
; x
++)
8468 /* Sanity check. This shouldn't happen, but apparently
8469 also does in some pictures. */
8470 if (x
+ source_left
>= dest_width
)
8472 /* Normally we only copy over non-transparent pixels,
8473 but if the disposal method is "Background", then we
8474 copy over all pixels. */
8475 if (dispose
== BackgroundDispose
|| PixelGetAlpha (source
[x
]))
8477 PixelGetMagickColor (source
[x
], &pixel
);
8478 PixelSetMagickColor (dest
[x
+ source_left
], &pixel
);
8481 PixelSyncIterator (dest_iterator
);
8484 DestroyPixelIterator (source_iterator
);
8485 DestroyPixelIterator (dest_iterator
);
8486 DestroyMagickWand (sub_wand
);
8489 /* Cache a copy for the next iteration. The current wand will be
8490 destroyed by the caller. */
8491 cache
->wand
= CloneMagickWand (composite_wand
);
8494 return composite_wand
;
8498 /* Helper function for imagemagick_load, which does the actual loading
8499 given contents and size, apart from frame and image structures,
8500 passed from imagemagick_load. Uses librimagemagick to do most of
8501 the image processing.
8503 F is a pointer to the Emacs frame; IMG to the image structure to
8504 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8505 be parsed; SIZE is the number of bytes of data; and FILENAME is
8506 either the file name or the image data.
8508 Return true if successful. */
8511 imagemagick_load_image (struct frame
*f
, struct image
*img
,
8512 unsigned char *contents
, unsigned int size
,
8516 size_t image_width
, image_height
;
8517 MagickBooleanType status
;
8520 MagickWand
*image_wand
;
8521 PixelIterator
*iterator
;
8522 PixelWand
**pixels
, *bg_wand
= NULL
;
8523 MagickPixelPacket pixel
;
8528 int desired_width
, desired_height
;
8531 char hint_buffer
[MaxTextExtent
];
8532 char *filename_hint
= NULL
;
8534 /* Handle image index for image types who can contain more than one image.
8535 Interface :index is same as for GIF. First we "ping" the image to see how
8536 many sub-images it contains. Pinging is faster than loading the image to
8537 find out things about it. */
8539 /* Initialize the imagemagick environment. */
8540 MagickWandGenesis ();
8541 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
8542 ino
= INTEGERP (image
) ? XFASTINT (image
) : 0;
8543 image_wand
= NewMagickWand ();
8546 status
= MagickReadImage (image_wand
, filename
);
8549 filename_hint
= imagemagick_filename_hint (img
->spec
, hint_buffer
);
8550 MagickSetFilename (image_wand
, filename_hint
);
8551 status
= MagickReadImageBlob (image_wand
, contents
, size
);
8554 if (status
== MagickFalse
)
8556 imagemagick_error (image_wand
);
8557 DestroyMagickWand (image_wand
);
8561 #ifdef HAVE_MAGICKAUTOORIENTIMAGE
8562 /* If no :rotation is explicitly specified, apply the automatic
8563 rotation from EXIF. */
8564 if (NILP (image_spec_value (img
->spec
, QCrotation
, NULL
)))
8565 if (MagickAutoOrientImage (image_wand
) == MagickFalse
)
8567 image_error ("Error applying automatic orientation in image `%s'", img
->spec
);
8568 DestroyMagickWand (image_wand
);
8573 if (ino
< 0 || ino
>= MagickGetNumberImages (image_wand
))
8575 image_error ("Invalid image number `%s' in image `%s'", image
, img
->spec
);
8576 DestroyMagickWand (image_wand
);
8580 if (MagickGetImageDelay (image_wand
) > 0)
8583 Fcons (make_float (MagickGetImageDelay (image_wand
) / 100.0),
8586 if (MagickGetNumberImages (image_wand
) > 1)
8589 Fcons (make_number (MagickGetNumberImages (image_wand
)),
8592 /* If we have an animated image, get the new wand based on the
8594 if (MagickGetNumberImages (image_wand
) > 1)
8596 MagickWand
*super_wand
= image_wand
;
8597 image_wand
= imagemagick_compute_animated_image (super_wand
, ino
);
8599 image_wand
= super_wand
;
8601 DestroyMagickWand (super_wand
);
8604 /* Retrieve the frame's background color, for use later. */
8607 Lisp_Object specified_bg
;
8609 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8610 if (!STRINGP (specified_bg
)
8611 || !x_defined_color (f
, SSDATA (specified_bg
), &bgcolor
, 0))
8612 x_query_frame_background_color (f
, &bgcolor
);
8614 bg_wand
= NewPixelWand ();
8615 PixelSetRed (bg_wand
, (double) bgcolor
.red
/ 65535);
8616 PixelSetGreen (bg_wand
, (double) bgcolor
.green
/ 65535);
8617 PixelSetBlue (bg_wand
, (double) bgcolor
.blue
/ 65535);
8620 compute_image_size (MagickGetImageWidth (image_wand
),
8621 MagickGetImageHeight (image_wand
),
8622 img
->spec
, &desired_width
, &desired_height
);
8624 if (desired_width
!= -1 && desired_height
!= -1)
8626 status
= MagickScaleImage (image_wand
, desired_width
, desired_height
);
8627 if (status
== MagickFalse
)
8629 image_error ("Imagemagick scale failed");
8630 imagemagick_error (image_wand
);
8631 goto imagemagick_error
;
8635 /* crop behaves similar to image slicing in Emacs but is more memory
8637 crop
= image_spec_value (img
->spec
, QCcrop
, NULL
);
8639 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8641 /* After some testing, it seems MagickCropImage is the fastest crop
8642 function in ImageMagick. This crop function seems to do less copying
8643 than the alternatives, but it still reads the entire image into memory
8644 before cropping, which is apparently difficult to avoid when using
8646 size_t crop_width
= XINT (XCAR (crop
));
8648 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8650 size_t crop_height
= XINT (XCAR (crop
));
8652 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8654 ssize_t crop_x
= XINT (XCAR (crop
));
8656 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8658 ssize_t crop_y
= XINT (XCAR (crop
));
8659 MagickCropImage (image_wand
, crop_width
, crop_height
,
8666 /* Furthermore :rotation. we need background color and angle for
8669 TODO background handling for rotation specified_bg =
8670 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8672 value
= image_spec_value (img
->spec
, QCrotation
, NULL
);
8675 rotation
= extract_float (value
);
8676 status
= MagickRotateImage (image_wand
, bg_wand
, rotation
);
8677 if (status
== MagickFalse
)
8679 image_error ("Imagemagick image rotate failed");
8680 imagemagick_error (image_wand
);
8681 goto imagemagick_error
;
8685 /* Set the canvas background color to the frame or specified
8686 background, and flatten the image. Note: as of ImageMagick
8687 6.6.0, SVG image transparency is not handled properly
8688 (e.g. etc/images/splash.svg shows a white background always). */
8690 MagickWand
*new_wand
;
8691 MagickSetImageBackgroundColor (image_wand
, bg_wand
);
8692 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8693 new_wand
= MagickMergeImageLayers (image_wand
, MergeLayer
);
8695 new_wand
= MagickFlattenImages (image_wand
);
8697 DestroyMagickWand (image_wand
);
8698 image_wand
= new_wand
;
8701 /* Finally we are done manipulating the image. Figure out the
8702 resulting width/height and transfer ownership to Emacs. */
8703 image_height
= MagickGetImageHeight (image_wand
);
8704 image_width
= MagickGetImageWidth (image_wand
);
8706 if (! (image_width
<= INT_MAX
&& image_height
<= INT_MAX
8707 && check_image_size (f
, image_width
, image_height
)))
8709 image_size_error ();
8710 goto imagemagick_error
;
8713 width
= image_width
;
8714 height
= image_height
;
8716 /* We can now get a valid pixel buffer from the imagemagick file, if all
8719 init_color_table ();
8721 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8722 if (imagemagick_render_type
!= 0)
8724 /* Magicexportimage is normally faster than pixelpushing. This
8725 method is also well tested. Some aspects of this method are
8726 ad-hoc and needs to be more researched. */
8727 int imagedepth
= 24; /*MagickGetImageDepth(image_wand);*/
8728 const char *exportdepth
= imagedepth
<= 8 ? "I" : "BGRP"; /*"RGBP";*/
8729 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8730 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, imagedepth
,
8733 #ifdef COLOR_TABLE_SUPPORT
8734 free_color_table ();
8736 image_error ("Imagemagick X bitmap allocation failure");
8737 goto imagemagick_error
;
8740 /* Oddly, the below code doesn't seem to work:*/
8741 /* switch(ximg->bitmap_unit){ */
8743 /* pixelwidth=CharPixel; */
8746 /* pixelwidth=ShortPixel; */
8749 /* pixelwidth=LongPixel; */
8753 Here im just guessing the format of the bitmap.
8754 happens to work fine for:
8757 seems about 3 times as fast as pixel pushing(not carefully measured)
8759 pixelwidth
= CharPixel
; /*??? TODO figure out*/
8760 MagickExportImagePixels (image_wand
, 0, 0, width
, height
,
8761 exportdepth
, pixelwidth
, ximg
->data
);
8764 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8766 size_t image_height
;
8767 MagickRealType color_scale
= 65535.0 / QuantumRange
;
8769 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8770 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
8773 #ifdef COLOR_TABLE_SUPPORT
8774 free_color_table ();
8776 image_error ("Imagemagick X bitmap allocation failure");
8777 goto imagemagick_error
;
8780 /* Copy imagemagick image to x with primitive yet robust pixel
8781 pusher loop. This has been tested a lot with many different
8784 /* Copy pixels from the imagemagick image structure to the x image map. */
8785 iterator
= NewPixelIterator (image_wand
);
8788 #ifdef COLOR_TABLE_SUPPORT
8789 free_color_table ();
8791 x_destroy_x_image (ximg
);
8792 image_error ("Imagemagick pixel iterator creation failed");
8793 goto imagemagick_error
;
8796 image_height
= MagickGetImageHeight (image_wand
);
8797 for (y
= 0; y
< image_height
; y
++)
8800 pixels
= PixelGetNextIteratorRow (iterator
, &row_width
);
8803 int xlim
= min (row_width
, width
);
8804 for (x
= 0; x
< xlim
; x
++)
8806 PixelGetMagickColor (pixels
[x
], &pixel
);
8807 XPutPixel (ximg
, x
, y
,
8808 lookup_rgb_color (f
,
8809 color_scale
* pixel
.red
,
8810 color_scale
* pixel
.green
,
8811 color_scale
* pixel
.blue
));
8814 DestroyPixelIterator (iterator
);
8817 #ifdef COLOR_TABLE_SUPPORT
8818 /* Remember colors allocated for this image. */
8819 img
->colors
= colors_in_color_table (&img
->ncolors
);
8820 free_color_table ();
8821 #endif /* COLOR_TABLE_SUPPORT */
8824 img
->height
= height
;
8826 /* Put ximg into the image. */
8827 image_put_x_image (f
, img
, ximg
, 0);
8829 /* Final cleanup. image_wand should be the only resource left. */
8830 DestroyMagickWand (image_wand
);
8831 if (bg_wand
) DestroyPixelWand (bg_wand
);
8833 /* `MagickWandTerminus' terminates the imagemagick environment. */
8834 MagickWandTerminus ();
8839 DestroyMagickWand (image_wand
);
8840 if (bg_wand
) DestroyPixelWand (bg_wand
);
8842 MagickWandTerminus ();
8843 /* TODO more cleanup. */
8844 image_error ("Error parsing IMAGEMAGICK image `%s'", img
->spec
);
8849 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8850 successful. this function will go into the imagemagick_type structure, and
8851 the prototype thus needs to be compatible with that structure. */
8854 imagemagick_load (struct frame
*f
, struct image
*img
)
8857 Lisp_Object file_name
;
8859 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8860 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8861 if (STRINGP (file_name
))
8863 Lisp_Object file
= x_find_image_file (file_name
);
8864 if (!STRINGP (file
))
8866 image_error ("Cannot find image file `%s'", file_name
);
8869 file
= ENCODE_FILE (file
);
8871 file
= ansi_encode_filename (file
);
8873 success_p
= imagemagick_load_image (f
, img
, 0, 0, SSDATA (file
));
8875 /* Else its not a file, its a lisp object. Load the image from a
8876 lisp object rather than a file. */
8881 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8882 if (!STRINGP (data
))
8884 image_error ("Invalid image data `%s'", data
);
8887 success_p
= imagemagick_load_image (f
, img
, SDATA (data
),
8888 SBYTES (data
), NULL
);
8894 DEFUN ("imagemagick-types", Fimagemagick_types
, Simagemagick_types
, 0, 0, 0,
8895 doc
: /* Return a list of image types supported by ImageMagick.
8896 Each entry in this list is a symbol named after an ImageMagick format
8897 tag. See the ImageMagick manual for a list of ImageMagick formats and
8898 their descriptions (http://www.imagemagick.org/script/formats.php).
8899 You can also try the shell command: `identify -list format'.
8901 Note that ImageMagick recognizes many file-types that Emacs does not
8902 recognize as images, such as C. See `imagemagick-types-enable'
8903 and `imagemagick-types-inhibit'. */)
8906 Lisp_Object typelist
= Qnil
;
8912 GetExceptionInfo(&ex
);
8913 imtypes
= GetMagickList ("*", &numf
, &ex
);
8914 DestroyExceptionInfo(&ex
);
8916 for (i
= 0; i
< numf
; i
++)
8918 Lisp_Object imagemagicktype
= intern (imtypes
[i
]);
8919 typelist
= Fcons (imagemagicktype
, typelist
);
8920 imtypes
[i
] = MagickRelinquishMemory (imtypes
[i
]);
8923 MagickRelinquishMemory (imtypes
);
8924 return Fnreverse (typelist
);
8927 #endif /* defined (HAVE_IMAGEMAGICK) */
8931 /***********************************************************************
8933 ***********************************************************************/
8937 /* Function prototypes. */
8939 static bool svg_image_p (Lisp_Object object
);
8940 static bool svg_load (struct frame
*f
, struct image
*img
);
8942 static bool svg_load_image (struct frame
*, struct image
*,
8943 unsigned char *, ptrdiff_t, char *);
8945 /* Indices of image specification fields in svg_format, below. */
8947 enum svg_keyword_index
8962 /* Vector of image_keyword structures describing the format
8963 of valid user-defined image specifications. */
8965 static const struct image_keyword svg_format
[SVG_LAST
] =
8967 {":type", IMAGE_SYMBOL_VALUE
, 1},
8968 {":data", IMAGE_STRING_VALUE
, 0},
8969 {":file", IMAGE_STRING_VALUE
, 0},
8970 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8971 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8972 {":relief", IMAGE_INTEGER_VALUE
, 0},
8973 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8974 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8975 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8976 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8979 # if defined HAVE_NTGUI && defined WINDOWSNT
8980 static bool init_svg_functions (void);
8982 #define init_svg_functions NULL
8985 /* Structure describing the image type `svg'. Its the same type of
8986 structure defined for all image formats, handled by emacs image
8987 functions. See struct image_type in dispextern.h. */
8989 static struct image_type svg_type
=
8991 SYMBOL_INDEX (Qsvg
),
9000 /* Return true if OBJECT is a valid SVG image specification. Do
9001 this by calling parse_image_spec and supplying the keywords that
9002 identify the SVG format. */
9005 svg_image_p (Lisp_Object object
)
9007 struct image_keyword fmt
[SVG_LAST
];
9008 memcpy (fmt
, svg_format
, sizeof fmt
);
9010 if (!parse_image_spec (object
, fmt
, SVG_LAST
, Qsvg
))
9013 /* Must specify either the :data or :file keyword. */
9014 return fmt
[SVG_FILE
].count
+ fmt
[SVG_DATA
].count
== 1;
9017 # include <librsvg/rsvg.h>
9021 /* SVG library functions. */
9022 DEF_DLL_FN (RsvgHandle
*, rsvg_handle_new
, (void));
9023 DEF_DLL_FN (void, rsvg_handle_get_dimensions
,
9024 (RsvgHandle
*, RsvgDimensionData
*));
9025 DEF_DLL_FN (gboolean
, rsvg_handle_write
,
9026 (RsvgHandle
*, const guchar
*, gsize
, GError
**));
9027 DEF_DLL_FN (gboolean
, rsvg_handle_close
, (RsvgHandle
*, GError
**));
9028 DEF_DLL_FN (GdkPixbuf
*, rsvg_handle_get_pixbuf
, (RsvgHandle
*));
9029 DEF_DLL_FN (void, rsvg_handle_set_base_uri
, (RsvgHandle
*, const char *));
9031 DEF_DLL_FN (int, gdk_pixbuf_get_width
, (const GdkPixbuf
*));
9032 DEF_DLL_FN (int, gdk_pixbuf_get_height
, (const GdkPixbuf
*));
9033 DEF_DLL_FN (guchar
*, gdk_pixbuf_get_pixels
, (const GdkPixbuf
*));
9034 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride
, (const GdkPixbuf
*));
9035 DEF_DLL_FN (GdkColorspace
, gdk_pixbuf_get_colorspace
, (const GdkPixbuf
*));
9036 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels
, (const GdkPixbuf
*));
9037 DEF_DLL_FN (gboolean
, gdk_pixbuf_get_has_alpha
, (const GdkPixbuf
*));
9038 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample
, (const GdkPixbuf
*));
9040 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9041 DEF_DLL_FN (void, g_type_init
, (void));
9043 DEF_DLL_FN (void, g_object_unref
, (gpointer
));
9044 DEF_DLL_FN (void, g_clear_error
, (GError
**));
9047 init_svg_functions (void)
9049 HMODULE library
, gdklib
= NULL
, glib
= NULL
, gobject
= NULL
;
9051 if (!(glib
= w32_delayed_load (Qglib
))
9052 || !(gobject
= w32_delayed_load (Qgobject
))
9053 || !(gdklib
= w32_delayed_load (Qgdk_pixbuf
))
9054 || !(library
= w32_delayed_load (Qsvg
)))
9056 if (gdklib
) FreeLibrary (gdklib
);
9057 if (gobject
) FreeLibrary (gobject
);
9058 if (glib
) FreeLibrary (glib
);
9062 LOAD_DLL_FN (library
, rsvg_handle_new
);
9063 LOAD_DLL_FN (library
, rsvg_handle_get_dimensions
);
9064 LOAD_DLL_FN (library
, rsvg_handle_write
);
9065 LOAD_DLL_FN (library
, rsvg_handle_close
);
9066 LOAD_DLL_FN (library
, rsvg_handle_get_pixbuf
);
9067 LOAD_DLL_FN (library
, rsvg_handle_set_base_uri
);
9069 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_width
);
9070 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_height
);
9071 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_pixels
);
9072 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_rowstride
);
9073 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_colorspace
);
9074 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_n_channels
);
9075 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_has_alpha
);
9076 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_bits_per_sample
);
9078 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9079 LOAD_DLL_FN (gobject
, g_type_init
);
9081 LOAD_DLL_FN (gobject
, g_object_unref
);
9082 LOAD_DLL_FN (glib
, g_clear_error
);
9087 /* The following aliases for library functions allow dynamic loading
9088 to be used on some platforms. */
9090 # undef gdk_pixbuf_get_bits_per_sample
9091 # undef gdk_pixbuf_get_colorspace
9092 # undef gdk_pixbuf_get_has_alpha
9093 # undef gdk_pixbuf_get_height
9094 # undef gdk_pixbuf_get_n_channels
9095 # undef gdk_pixbuf_get_pixels
9096 # undef gdk_pixbuf_get_rowstride
9097 # undef gdk_pixbuf_get_width
9098 # undef g_clear_error
9099 # undef g_object_unref
9101 # undef rsvg_handle_close
9102 # undef rsvg_handle_get_dimensions
9103 # undef rsvg_handle_get_pixbuf
9104 # undef rsvg_handle_new
9105 # undef rsvg_handle_set_base_uri
9106 # undef rsvg_handle_write
9108 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9109 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9110 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9111 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9112 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9113 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9114 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9115 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9116 # define g_clear_error fn_g_clear_error
9117 # define g_object_unref fn_g_object_unref
9118 # define g_type_init fn_g_type_init
9119 # define rsvg_handle_close fn_rsvg_handle_close
9120 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9121 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9122 # define rsvg_handle_new fn_rsvg_handle_new
9123 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9124 # define rsvg_handle_write fn_rsvg_handle_write
9126 # endif /* !WINDOWSNT */
9128 /* Load SVG image IMG for use on frame F. Value is true if
9132 svg_load (struct frame
*f
, struct image
*img
)
9135 Lisp_Object file_name
;
9137 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9138 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
9139 if (STRINGP (file_name
))
9142 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
9143 if (!STRINGP (file
))
9145 image_error ("Cannot find image file `%s'", file_name
);
9149 /* Read the entire file into memory. */
9151 unsigned char *contents
= slurp_file (fd
, &size
);
9152 if (contents
== NULL
)
9154 image_error ("Error loading SVG image `%s'", file
);
9157 /* If the file was slurped into memory properly, parse it. */
9158 success_p
= svg_load_image (f
, img
, contents
, size
,
9159 SSDATA (ENCODE_FILE (file
)));
9162 /* Else its not a file, its a lisp object. Load the image from a
9163 lisp object rather than a file. */
9166 Lisp_Object data
, original_filename
;
9168 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
9169 if (!STRINGP (data
))
9171 image_error ("Invalid image data `%s'", data
);
9174 original_filename
= BVAR (current_buffer
, filename
);
9175 success_p
= svg_load_image (f
, img
, SDATA (data
), SBYTES (data
),
9176 (NILP (original_filename
) ? NULL
9177 : SSDATA (original_filename
)));
9183 /* svg_load_image is a helper function for svg_load, which does the
9184 actual loading given contents and size, apart from frame and image
9185 structures, passed from svg_load.
9187 Uses librsvg to do most of the image processing.
9189 Returns true when successful. */
9191 svg_load_image (struct frame
*f
, /* Pointer to emacs frame structure. */
9192 struct image
*img
, /* Pointer to emacs image structure. */
9193 unsigned char *contents
, /* String containing the SVG XML data to be parsed. */
9194 ptrdiff_t size
, /* Size of data in bytes. */
9195 char *filename
) /* Name of SVG file being loaded. */
9197 RsvgHandle
*rsvg_handle
;
9198 RsvgDimensionData dimension_data
;
9203 const guint8
*pixels
;
9206 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9207 /* g_type_init is a glib function that must be called prior to
9208 using gnome type library functions (obsolete since 2.36.0). */
9212 /* Make a handle to a new rsvg object. */
9213 rsvg_handle
= rsvg_handle_new ();
9215 /* Set base_uri for properly handling referenced images (via 'href').
9216 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9217 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9219 rsvg_handle_set_base_uri(rsvg_handle
, filename
);
9221 /* Parse the contents argument and fill in the rsvg_handle. */
9222 rsvg_handle_write (rsvg_handle
, contents
, size
, &err
);
9223 if (err
) goto rsvg_error
;
9225 /* The parsing is complete, rsvg_handle is ready to used, close it
9226 for further writes. */
9227 rsvg_handle_close (rsvg_handle
, &err
);
9228 if (err
) goto rsvg_error
;
9230 rsvg_handle_get_dimensions (rsvg_handle
, &dimension_data
);
9231 if (! check_image_size (f
, dimension_data
.width
, dimension_data
.height
))
9233 image_size_error ();
9237 /* We can now get a valid pixel buffer from the svg file, if all
9239 pixbuf
= rsvg_handle_get_pixbuf (rsvg_handle
);
9240 if (!pixbuf
) goto rsvg_error
;
9241 g_object_unref (rsvg_handle
);
9243 /* Extract some meta data from the svg handle. */
9244 width
= gdk_pixbuf_get_width (pixbuf
);
9245 height
= gdk_pixbuf_get_height (pixbuf
);
9246 pixels
= gdk_pixbuf_get_pixels (pixbuf
);
9247 rowstride
= gdk_pixbuf_get_rowstride (pixbuf
);
9249 /* Validate the svg meta data. */
9250 eassert (gdk_pixbuf_get_colorspace (pixbuf
) == GDK_COLORSPACE_RGB
);
9251 eassert (gdk_pixbuf_get_n_channels (pixbuf
) == 4);
9252 eassert (gdk_pixbuf_get_has_alpha (pixbuf
));
9253 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf
) == 8);
9257 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
9258 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
9260 for (int y
= 0; y
< height
; ++y
)
9262 const guchar
*iconptr
= pixels
+ y
* rowstride
;
9263 uint32_t *dataptr
= (uint32_t *) (data
+ y
* rowstride
);
9265 for (int x
= 0; x
< width
; ++x
)
9267 if (iconptr
[3] == 0)
9270 *dataptr
= (iconptr
[0] << 16)
9273 | (iconptr
[3] << 24);
9280 create_cairo_image_surface (img
, data
, width
, height
);
9281 g_object_unref (pixbuf
);
9283 /* Try to create a x pixmap to hold the svg pixmap. */
9285 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
9287 g_object_unref (pixbuf
);
9291 init_color_table ();
9293 /* Handle alpha channel by combining the image with a background
9296 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
9297 if (!STRINGP (specified_bg
)
9298 || !x_defined_color (f
, SSDATA (specified_bg
), &background
, 0))
9299 x_query_frame_background_color (f
, &background
);
9301 /* SVG pixmaps specify transparency in the last byte, so right
9302 shift 8 bits to get rid of it, since emacs doesn't support
9304 background
.red
>>= 8;
9305 background
.green
>>= 8;
9306 background
.blue
>>= 8;
9308 /* This loop handles opacity values, since Emacs assumes
9309 non-transparent images. Each pixel must be "flattened" by
9310 calculating the resulting color, given the transparency of the
9311 pixel, and the image background color. */
9312 for (int y
= 0; y
< height
; ++y
)
9314 for (int x
= 0; x
< width
; ++x
)
9316 int red
= *pixels
++;
9317 int green
= *pixels
++;
9318 int blue
= *pixels
++;
9319 int opacity
= *pixels
++;
9321 red
= ((red
* opacity
)
9322 + (background
.red
* ((1 << 8) - opacity
)));
9323 green
= ((green
* opacity
)
9324 + (background
.green
* ((1 << 8) - opacity
)));
9325 blue
= ((blue
* opacity
)
9326 + (background
.blue
* ((1 << 8) - opacity
)));
9328 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, red
, green
, blue
));
9331 pixels
+= rowstride
- 4 * width
;
9334 #ifdef COLOR_TABLE_SUPPORT
9335 /* Remember colors allocated for this image. */
9336 img
->colors
= colors_in_color_table (&img
->ncolors
);
9337 free_color_table ();
9338 #endif /* COLOR_TABLE_SUPPORT */
9340 g_object_unref (pixbuf
);
9343 img
->height
= height
;
9345 /* Maybe fill in the background field while we have ximg handy.
9346 Casting avoids a GCC warning. */
9347 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
9349 /* Put ximg into the image. */
9350 image_put_x_image (f
, img
, ximg
, 0);
9351 #endif /* ! USE_CAIRO */
9357 g_object_unref (rsvg_handle
);
9358 /* FIXME: Use error->message so the user knows what is the actual
9359 problem with the image. */
9360 image_error ("Error parsing SVG image `%s'", img
->spec
);
9361 g_clear_error (&err
);
9365 #endif /* defined (HAVE_RSVG) */
9370 /***********************************************************************
9372 ***********************************************************************/
9374 #ifdef HAVE_X_WINDOWS
9375 #define HAVE_GHOSTSCRIPT 1
9376 #endif /* HAVE_X_WINDOWS */
9378 #ifdef HAVE_GHOSTSCRIPT
9380 static bool gs_image_p (Lisp_Object object
);
9381 static bool gs_load (struct frame
*f
, struct image
*img
);
9382 static void gs_clear_image (struct frame
*f
, struct image
*img
);
9384 /* Indices of image specification fields in gs_format, below. */
9386 enum gs_keyword_index
9404 /* Vector of image_keyword structures describing the format
9405 of valid user-defined image specifications. */
9407 static const struct image_keyword gs_format
[GS_LAST
] =
9409 {":type", IMAGE_SYMBOL_VALUE
, 1},
9410 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9411 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9412 {":file", IMAGE_STRING_VALUE
, 1},
9413 {":loader", IMAGE_FUNCTION_VALUE
, 0},
9414 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE
, 1},
9415 {":ascent", IMAGE_ASCENT_VALUE
, 0},
9416 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
9417 {":relief", IMAGE_INTEGER_VALUE
, 0},
9418 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9419 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9420 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9421 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
9424 /* Structure describing the image type `ghostscript'. */
9426 static struct image_type gs_type
=
9428 SYMBOL_INDEX (Qpostscript
),
9437 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9440 gs_clear_image (struct frame
*f
, struct image
*img
)
9442 x_clear_image (f
, img
);
9446 /* Return true if OBJECT is a valid Ghostscript image
9450 gs_image_p (Lisp_Object object
)
9452 struct image_keyword fmt
[GS_LAST
];
9456 memcpy (fmt
, gs_format
, sizeof fmt
);
9458 if (!parse_image_spec (object
, fmt
, GS_LAST
, Qpostscript
))
9461 /* Bounding box must be a list or vector containing 4 integers. */
9462 tem
= fmt
[GS_BOUNDING_BOX
].value
;
9465 for (i
= 0; i
< 4; ++i
, tem
= XCDR (tem
))
9466 if (!CONSP (tem
) || !INTEGERP (XCAR (tem
)))
9471 else if (VECTORP (tem
))
9473 if (ASIZE (tem
) != 4)
9475 for (i
= 0; i
< 4; ++i
)
9476 if (!INTEGERP (AREF (tem
, i
)))
9486 /* Load Ghostscript image IMG for use on frame F. Value is true
9490 gs_load (struct frame
*f
, struct image
*img
)
9492 uprintmax_t printnum1
, printnum2
;
9493 char buffer
[sizeof " " + INT_STRLEN_BOUND (printmax_t
)];
9494 Lisp_Object window_and_pixmap_id
= Qnil
, loader
, pt_height
, pt_width
;
9496 double in_width
, in_height
;
9497 Lisp_Object pixel_colors
= Qnil
;
9499 /* Compute pixel size of pixmap needed from the given size in the
9500 image specification. Sizes in the specification are in pt. 1 pt
9501 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9503 pt_width
= image_spec_value (img
->spec
, QCpt_width
, NULL
);
9504 in_width
= INTEGERP (pt_width
) ? XFASTINT (pt_width
) / 72.0 : 0;
9505 in_width
*= FRAME_RES_X (f
);
9506 pt_height
= image_spec_value (img
->spec
, QCpt_height
, NULL
);
9507 in_height
= INTEGERP (pt_height
) ? XFASTINT (pt_height
) / 72.0 : 0;
9508 in_height
*= FRAME_RES_Y (f
);
9510 if (! (in_width
<= INT_MAX
&& in_height
<= INT_MAX
9511 && check_image_size (f
, in_width
, in_height
)))
9513 image_size_error ();
9516 img
->width
= in_width
;
9517 img
->height
= in_height
;
9519 /* Create the pixmap. */
9520 eassert (img
->pixmap
== NO_PIXMAP
);
9522 if (x_check_image_size (0, img
->width
, img
->height
))
9524 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9526 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
9527 img
->width
, img
->height
,
9528 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)));
9534 image_error ("Unable to create pixmap for `%s'" , img
->spec
);
9538 /* Call the loader to fill the pixmap. It returns a process object
9539 if successful. We do not record_unwind_protect here because
9540 other places in redisplay like calling window scroll functions
9541 don't either. Let the Lisp loader use `unwind-protect' instead. */
9542 printnum1
= FRAME_X_WINDOW (f
);
9543 printnum2
= img
->pixmap
;
9544 window_and_pixmap_id
9545 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9547 printnum1
= FRAME_FOREGROUND_PIXEL (f
);
9548 printnum2
= FRAME_BACKGROUND_PIXEL (f
);
9550 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9552 XSETFRAME (frame
, f
);
9553 loader
= image_spec_value (img
->spec
, QCloader
, NULL
);
9555 loader
= intern ("gs-load-image");
9557 img
->lisp_data
= call6 (loader
, frame
, img
->spec
,
9558 make_number (img
->width
),
9559 make_number (img
->height
),
9560 window_and_pixmap_id
,
9562 return PROCESSP (img
->lisp_data
);
9566 /* Kill the Ghostscript process that was started to fill PIXMAP on
9567 frame F. Called from XTread_socket when receiving an event
9568 telling Emacs that Ghostscript has finished drawing. */
9571 x_kill_gs_process (Pixmap pixmap
, struct frame
*f
)
9573 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
9577 /* Find the image containing PIXMAP. */
9578 for (i
= 0; i
< c
->used
; ++i
)
9579 if (c
->images
[i
]->pixmap
== pixmap
)
9582 /* Should someone in between have cleared the image cache, for
9583 instance, give up. */
9587 /* Kill the GS process. We should have found PIXMAP in the image
9588 cache and its image should contain a process object. */
9590 eassert (PROCESSP (img
->lisp_data
));
9591 Fkill_process (img
->lisp_data
, Qnil
);
9592 img
->lisp_data
= Qnil
;
9594 #if defined (HAVE_X_WINDOWS)
9596 /* On displays with a mutable colormap, figure out the colors
9597 allocated for the image by looking at the pixels of an XImage for
9599 if (x_mutable_colormap (FRAME_X_VISUAL (f
)))
9605 /* Try to get an XImage for img->pixmep. */
9606 ximg
= XGetImage (FRAME_X_DISPLAY (f
), img
->pixmap
,
9607 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
9610 /* Initialize the color table. */
9611 init_color_table ();
9613 /* For each pixel of the image, look its color up in the
9614 color table. After having done so, the color table will
9615 contain an entry for each color used by the image. */
9616 #ifdef COLOR_TABLE_SUPPORT
9617 for (int y
= 0; y
< img
->height
; ++y
)
9618 for (int x
= 0; x
< img
->width
; ++x
)
9620 unsigned long pixel
= XGetPixel (ximg
, x
, y
);
9622 lookup_pixel_color (f
, pixel
);
9625 /* Record colors in the image. Free color table and XImage. */
9626 img
->colors
= colors_in_color_table (&img
->ncolors
);
9627 free_color_table ();
9629 XDestroyImage (ximg
);
9631 #if 0 /* This doesn't seem to be the case. If we free the colors
9632 here, we get a BadAccess later in x_clear_image when
9633 freeing the colors. */
9634 /* We have allocated colors once, but Ghostscript has also
9635 allocated colors on behalf of us. So, to get the
9636 reference counts right, free them once. */
9638 x_free_colors (f
, img
->colors
, img
->ncolors
);
9642 image_error ("Cannot get X image of `%s'; colors will not be freed",
9647 #endif /* HAVE_X_WINDOWS */
9649 /* Now that we have the pixmap, compute mask and transform the
9650 image if requested. */
9652 postprocess_image (f
, img
);
9656 #endif /* HAVE_GHOSTSCRIPT */
9659 /***********************************************************************
9661 ***********************************************************************/
9665 DEFUN ("imagep", Fimagep
, Simagep
, 1, 1, 0,
9666 doc
: /* Value is non-nil if SPEC is a valid image specification. */)
9669 return valid_image_p (spec
) ? Qt
: Qnil
;
9673 DEFUN ("lookup-image", Flookup_image
, Slookup_image
, 1, 1, 0,
9679 if (valid_image_p (spec
))
9680 id
= lookup_image (SELECTED_FRAME (), spec
);
9683 return make_number (id
);
9686 #endif /* GLYPH_DEBUG */
9689 /***********************************************************************
9691 ***********************************************************************/
9693 DEFUN ("init-image-library", Finit_image_library
, Sinit_image_library
, 1, 1, 0,
9694 doc
: /* Initialize image library implementing image type TYPE.
9695 Return non-nil if TYPE is a supported image type.
9697 If image libraries are loaded dynamically (currently only the case on
9698 MS-Windows), load the library for TYPE if it is not yet loaded, using
9699 the library file(s) specified by `dynamic-library-alist'. */)
9702 return lookup_image_type (type
) ? Qt
: Qnil
;
9705 /* Look up image type TYPE, and return a pointer to its image_type
9706 structure. Return 0 if TYPE is not a known image type. */
9708 static struct image_type
*
9709 lookup_image_type (Lisp_Object type
)
9711 /* Types pbm and xbm are built-in and always available. */
9712 if (EQ (type
, Qpbm
))
9713 return define_image_type (&pbm_type
);
9715 if (EQ (type
, Qxbm
))
9716 return define_image_type (&xbm_type
);
9718 #if defined (HAVE_XPM) || defined (HAVE_NS)
9719 if (EQ (type
, Qxpm
))
9720 return define_image_type (&xpm_type
);
9723 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9724 if (EQ (type
, Qjpeg
))
9725 return define_image_type (&jpeg_type
);
9728 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9729 if (EQ (type
, Qtiff
))
9730 return define_image_type (&tiff_type
);
9733 #if defined (HAVE_GIF) || defined (HAVE_NS)
9734 if (EQ (type
, Qgif
))
9735 return define_image_type (&gif_type
);
9738 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9739 if (EQ (type
, Qpng
))
9740 return define_image_type (&png_type
);
9743 #if defined (HAVE_RSVG)
9744 if (EQ (type
, Qsvg
))
9745 return define_image_type (&svg_type
);
9748 #if defined (HAVE_IMAGEMAGICK)
9749 if (EQ (type
, Qimagemagick
))
9750 return define_image_type (&imagemagick_type
);
9753 #ifdef HAVE_GHOSTSCRIPT
9754 if (EQ (type
, Qpostscript
))
9755 return define_image_type (&gs_type
);
9761 /* Reset image_types before dumping.
9762 Called from Fdump_emacs. */
9765 reset_image_types (void)
9769 struct image_type
*next
= image_types
->next
;
9770 xfree (image_types
);
9776 syms_of_image (void)
9778 /* Initialize this only once; it will be reset before dumping. */
9781 /* Must be defined now because we're going to update it below, while
9782 defining the supported image types. */
9783 DEFVAR_LISP ("image-types", Vimage_types
,
9784 doc
: /* List of potentially supported image types.
9785 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9786 To check whether it is really supported, use `image-type-available-p'. */);
9787 Vimage_types
= Qnil
;
9789 DEFVAR_LISP ("max-image-size", Vmax_image_size
,
9790 doc
: /* Maximum size of images.
9791 Emacs will not load an image into memory if its pixel width or
9792 pixel height exceeds this limit.
9794 If the value is an integer, it directly specifies the maximum
9795 image height and width, measured in pixels. If it is a floating
9796 point number, it specifies the maximum image height and width
9797 as a ratio to the frame height and width. If the value is
9798 non-numeric, there is no explicit limit on the size of images. */);
9799 Vmax_image_size
= make_float (MAX_IMAGE_SIZE
);
9801 /* Other symbols. */
9802 DEFSYM (Qcount
, "count");
9803 DEFSYM (Qextension_data
, "extension-data");
9804 DEFSYM (Qdelay
, "delay");
9807 DEFSYM (QCascent
, ":ascent");
9808 DEFSYM (QCmargin
, ":margin");
9809 DEFSYM (QCrelief
, ":relief");
9810 DEFSYM (QCconversion
, ":conversion");
9811 DEFSYM (QCcolor_symbols
, ":color-symbols");
9812 DEFSYM (QCheuristic_mask
, ":heuristic-mask");
9813 DEFSYM (QCindex
, ":index");
9814 DEFSYM (QCcrop
, ":crop");
9815 DEFSYM (QCrotation
, ":rotation");
9816 DEFSYM (QCmatrix
, ":matrix");
9817 DEFSYM (QCscale
, ":scale");
9818 DEFSYM (QCcolor_adjustment
, ":color-adjustment");
9819 DEFSYM (QCmask
, ":mask");
9821 /* Other symbols. */
9822 DEFSYM (Qlaplace
, "laplace");
9823 DEFSYM (Qemboss
, "emboss");
9824 DEFSYM (Qedge_detection
, "edge-detection");
9825 DEFSYM (Qheuristic
, "heuristic");
9827 DEFSYM (Qpostscript
, "postscript");
9828 DEFSYM (QCmax_width
, ":max-width");
9829 DEFSYM (QCmax_height
, ":max-height");
9830 #ifdef HAVE_GHOSTSCRIPT
9831 ADD_IMAGE_TYPE (Qpostscript
);
9832 DEFSYM (QCloader
, ":loader");
9833 DEFSYM (QCpt_width
, ":pt-width");
9834 DEFSYM (QCpt_height
, ":pt-height");
9835 #endif /* HAVE_GHOSTSCRIPT */
9838 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9839 or -1 if no PNG/GIF support was compiled in. This is tested by
9840 w32-win.el to correctly set up the alist used to search for the
9841 respective image libraries. */
9842 DEFSYM (Qlibpng_version
, "libpng-version");
9843 Fset (Qlibpng_version
,
9845 make_number (PNG_LIBPNG_VER
)
9850 DEFSYM (Qlibgif_version
, "libgif-version");
9851 Fset (Qlibgif_version
,
9853 make_number (GIFLIB_MAJOR
* 10000
9854 + GIFLIB_MINOR
* 100
9860 DEFSYM (Qlibjpeg_version
, "libjpeg-version");
9861 Fset (Qlibjpeg_version
,
9863 make_number (JPEG_LIB_VERSION
)
9870 DEFSYM (Qpbm
, "pbm");
9871 ADD_IMAGE_TYPE (Qpbm
);
9873 DEFSYM (Qxbm
, "xbm");
9874 ADD_IMAGE_TYPE (Qxbm
);
9876 #if defined (HAVE_XPM) || defined (HAVE_NS)
9877 DEFSYM (Qxpm
, "xpm");
9878 ADD_IMAGE_TYPE (Qxpm
);
9881 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9882 DEFSYM (Qjpeg
, "jpeg");
9883 ADD_IMAGE_TYPE (Qjpeg
);
9886 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9887 DEFSYM (Qtiff
, "tiff");
9888 ADD_IMAGE_TYPE (Qtiff
);
9891 #if defined (HAVE_GIF) || defined (HAVE_NS)
9892 DEFSYM (Qgif
, "gif");
9893 ADD_IMAGE_TYPE (Qgif
);
9896 #if defined (HAVE_PNG) || defined (HAVE_NS)
9897 DEFSYM (Qpng
, "png");
9898 ADD_IMAGE_TYPE (Qpng
);
9901 #if defined (HAVE_IMAGEMAGICK)
9902 DEFSYM (Qimagemagick
, "imagemagick");
9903 ADD_IMAGE_TYPE (Qimagemagick
);
9906 #if defined (HAVE_RSVG)
9907 DEFSYM (Qsvg
, "svg");
9908 ADD_IMAGE_TYPE (Qsvg
);
9910 /* Other libraries used directly by svg code. */
9911 DEFSYM (Qgdk_pixbuf
, "gdk-pixbuf");
9912 DEFSYM (Qglib
, "glib");
9913 DEFSYM (Qgobject
, "gobject");
9914 #endif /* HAVE_NTGUI */
9915 #endif /* HAVE_RSVG */
9917 defsubr (&Sinit_image_library
);
9918 #ifdef HAVE_IMAGEMAGICK
9919 defsubr (&Simagemagick_types
);
9921 defsubr (&Sclear_image_cache
);
9922 defsubr (&Simage_flush
);
9923 defsubr (&Simage_size
);
9924 defsubr (&Simage_mask_p
);
9925 defsubr (&Simage_metadata
);
9929 defsubr (&Slookup_image
);
9932 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images
,
9933 doc
: /* Non-nil means always draw a cross over disabled images.
9934 Disabled images are those having a `:conversion disabled' property.
9935 A cross is always drawn on black & white displays. */);
9936 cross_disabled_images
= 0;
9938 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path
,
9939 doc
: /* List of directories to search for window system bitmap files. */);
9940 Vx_bitmap_file_path
= decode_env_path (0, PATH_BITMAPS
, 0);
9942 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay
,
9943 doc
: /* Maximum time after which images are removed from the cache.
9944 When an image has not been displayed this many seconds, Emacs
9945 automatically removes it from the image cache. If the cache contains
9946 a large number of images, the actual eviction time may be shorter.
9947 The value can also be nil, meaning the cache is never cleared.
9949 The function `clear-image-cache' disregards this variable. */);
9950 Vimage_cache_eviction_delay
= make_number (300);
9951 #ifdef HAVE_IMAGEMAGICK
9952 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type
,
9953 doc
: /* Integer indicating which ImageMagick rendering method to use.
9955 0 -- the default method (pixel pushing)
9956 1 -- a newer method ("MagickExportImagePixels") that may perform
9957 better (speed etc) in some cases, but has not been as thoroughly
9958 tested with Emacs as the default method. This method requires
9959 ImageMagick version 6.4.6 (approximately) or later.
9961 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9962 imagemagick_render_type
= 0;