1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
24 /* Include this before including <setjmp.h> to work around bugs with
25 older libpng; see Bug#17429. */
26 #if defined HAVE_PNG && !defined HAVE_NS
37 #include "dispextern.h"
38 #include "blockinput.h"
41 #include "character.h"
43 #include "termhooks.h"
46 #ifdef HAVE_SYS_STAT_H
48 #endif /* HAVE_SYS_STAT_H */
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
52 #endif /* HAVE_SYS_TYPES_H */
54 #ifdef HAVE_WINDOW_SYSTEM
56 #endif /* HAVE_WINDOW_SYSTEM */
59 #define COLOR_TABLE_SUPPORT 1
61 typedef struct x_bitmap_record Bitmap_Record
;
62 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
63 #define NO_PIXMAP None
65 #define PIX_MASK_RETAIN 0
66 #define PIX_MASK_DRAW 1
67 #endif /* HAVE_X_WINDOWS */
71 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
76 /* W32_TODO : Color tables on W32. */
77 #undef COLOR_TABLE_SUPPORT
79 typedef struct w32_bitmap_record Bitmap_Record
;
80 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
83 #define PIX_MASK_RETAIN 0
84 #define PIX_MASK_DRAW 1
86 #define x_defined_color w32_defined_color
87 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
89 #endif /* HAVE_NTGUI */
92 #undef COLOR_TABLE_SUPPORT
96 #undef COLOR_TABLE_SUPPORT
98 typedef struct ns_bitmap_record Bitmap_Record
;
100 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
103 #define PIX_MASK_RETAIN 0
104 #define PIX_MASK_DRAW 1
106 #define x_defined_color(f, name, color_def, alloc) \
107 ns_defined_color (f, name, color_def, alloc, 0)
108 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
111 static void x_disable_image (struct frame
*, struct image
*);
112 static void x_edge_detection (struct frame
*, struct image
*, Lisp_Object
,
115 static void init_color_table (void);
116 static unsigned long lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
);
117 #ifdef COLOR_TABLE_SUPPORT
118 static void free_color_table (void);
119 static unsigned long *colors_in_color_table (int *n
);
122 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
123 id, which is just an int that this section returns. Bitmaps are
124 reference counted so they can be shared among frames.
126 Bitmap indices are guaranteed to be > 0, so a negative number can
127 be used to indicate no bitmap.
129 If you use x_create_bitmap_from_data, then you must keep track of
130 the bitmaps yourself. That is, creating a bitmap from the same
131 data more than once will not be caught. */
134 /* Use with images created by ns_image_for_XPM. */
136 XGetPixel (XImagePtr ximage
, int x
, int y
)
138 return ns_get_pixel (ximage
, x
, y
);
141 /* Use with images created by ns_image_for_XPM; alpha set to 1;
142 pixel is assumed to be in RGB form. */
144 XPutPixel (XImagePtr ximage
, int x
, int y
, unsigned long pixel
)
146 ns_put_pixel (ximage
, x
, y
, pixel
);
151 /* Functions to access the contents of a bitmap, given an id. */
153 #ifdef HAVE_X_WINDOWS
155 x_bitmap_height (struct frame
*f
, ptrdiff_t id
)
157 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].height
;
161 x_bitmap_width (struct frame
*f
, ptrdiff_t id
)
163 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].width
;
167 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
169 x_bitmap_pixmap (struct frame
*f
, ptrdiff_t id
)
171 /* HAVE_NTGUI needs the explicit cast here. */
172 return (ptrdiff_t) FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].pixmap
;
176 #ifdef HAVE_X_WINDOWS
178 x_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
180 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].mask
;
184 /* Allocate a new bitmap record. Returns index of new record. */
187 x_allocate_bitmap_record (struct frame
*f
)
189 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
192 if (dpyinfo
->bitmaps_last
< dpyinfo
->bitmaps_size
)
193 return ++dpyinfo
->bitmaps_last
;
195 for (i
= 0; i
< dpyinfo
->bitmaps_size
; ++i
)
196 if (dpyinfo
->bitmaps
[i
].refcount
== 0)
200 xpalloc (dpyinfo
->bitmaps
, &dpyinfo
->bitmaps_size
,
201 10, -1, sizeof *dpyinfo
->bitmaps
);
202 return ++dpyinfo
->bitmaps_last
;
205 /* Add one reference to the reference count of the bitmap with id ID. */
208 x_reference_bitmap (struct frame
*f
, ptrdiff_t id
)
210 ++FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].refcount
;
213 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
216 x_create_bitmap_from_data (struct frame
*f
, char *bits
, unsigned int width
, unsigned int height
)
218 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
221 #ifdef HAVE_X_WINDOWS
223 bitmap
= XCreateBitmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
224 bits
, width
, height
);
227 #endif /* HAVE_X_WINDOWS */
231 bitmap
= CreateBitmap (width
, height
,
232 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_planes
,
233 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_cbits
,
237 #endif /* HAVE_NTGUI */
240 void *bitmap
= ns_image_from_XBM (bits
, width
, height
, 0, 0);
245 id
= x_allocate_bitmap_record (f
);
248 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
249 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
252 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
253 dpyinfo
->bitmaps
[id
- 1].height
= height
;
254 dpyinfo
->bitmaps
[id
- 1].width
= width
;
255 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
257 #ifdef HAVE_X_WINDOWS
258 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
259 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
260 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
261 #endif /* HAVE_X_WINDOWS */
264 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
265 dpyinfo
->bitmaps
[id
- 1].hinst
= NULL
;
266 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
267 #endif /* HAVE_NTGUI */
272 /* Create bitmap from file FILE for frame F. */
275 x_create_bitmap_from_file (struct frame
*f
, Lisp_Object file
)
277 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
280 return -1; /* W32_TODO : bitmap support */
281 #endif /* HAVE_NTGUI */
285 void *bitmap
= ns_image_from_file (file
);
291 id
= x_allocate_bitmap_record (f
);
292 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
293 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
294 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
295 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
296 dpyinfo
->bitmaps
[id
- 1].height
= ns_image_width (bitmap
);
297 dpyinfo
->bitmaps
[id
- 1].width
= ns_image_height (bitmap
);
301 #ifdef HAVE_X_WINDOWS
302 unsigned int width
, height
;
304 int xhot
, yhot
, result
;
309 /* Look for an existing bitmap with the same name. */
310 for (id
= 0; id
< dpyinfo
->bitmaps_last
; ++id
)
312 if (dpyinfo
->bitmaps
[id
].refcount
313 && dpyinfo
->bitmaps
[id
].file
314 && !strcmp (dpyinfo
->bitmaps
[id
].file
, SSDATA (file
)))
316 ++dpyinfo
->bitmaps
[id
].refcount
;
321 /* Search bitmap-file-path for the file, if appropriate. */
322 if (openp (Vx_bitmap_file_path
, file
, Qnil
, &found
,
323 make_number (R_OK
), false)
327 filename
= SSDATA (found
);
329 result
= XReadBitmapFile (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
330 filename
, &width
, &height
, &bitmap
, &xhot
, &yhot
);
331 if (result
!= BitmapSuccess
)
334 id
= x_allocate_bitmap_record (f
);
335 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
336 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
337 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
338 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
339 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
340 dpyinfo
->bitmaps
[id
- 1].height
= height
;
341 dpyinfo
->bitmaps
[id
- 1].width
= width
;
344 #endif /* HAVE_X_WINDOWS */
350 free_bitmap_record (Display_Info
*dpyinfo
, Bitmap_Record
*bm
)
352 #ifdef HAVE_X_WINDOWS
353 XFreePixmap (dpyinfo
->display
, bm
->pixmap
);
355 XFreePixmap (dpyinfo
->display
, bm
->mask
);
356 #endif /* HAVE_X_WINDOWS */
359 DeleteObject (bm
->pixmap
);
360 #endif /* HAVE_NTGUI */
363 ns_release_object (bm
->img
);
373 /* Remove reference to bitmap with id number ID. */
376 x_destroy_bitmap (struct frame
*f
, ptrdiff_t id
)
378 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
382 Bitmap_Record
*bm
= &dpyinfo
->bitmaps
[id
- 1];
384 if (--bm
->refcount
== 0)
387 free_bitmap_record (dpyinfo
, bm
);
393 /* Free all the bitmaps for the display specified by DPYINFO. */
396 x_destroy_all_bitmaps (Display_Info
*dpyinfo
)
399 Bitmap_Record
*bm
= dpyinfo
->bitmaps
;
401 for (i
= 0; i
< dpyinfo
->bitmaps_last
; i
++, bm
++)
402 if (bm
->refcount
> 0)
403 free_bitmap_record (dpyinfo
, bm
);
405 dpyinfo
->bitmaps_last
= 0;
408 static bool x_create_x_image_and_pixmap (struct frame
*, int, int, int,
409 XImagePtr
*, Pixmap
*);
410 static void x_destroy_x_image (XImagePtr ximg
);
413 static XImagePtr_or_DC
image_get_x_image_or_dc (struct frame
*, struct image
*,
415 static void image_unget_x_image_or_dc (struct image
*, bool, XImagePtr_or_DC
,
418 static XImagePtr
image_get_x_image (struct frame
*, struct image
*, bool);
419 static void image_unget_x_image (struct image
*, bool, XImagePtr
);
420 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
421 image_get_x_image (f, img, mask_p)
422 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
423 image_unget_x_image (img, mask_p, ximg)
426 #ifdef HAVE_X_WINDOWS
428 static void image_sync_to_pixmaps (struct frame
*, struct image
*);
430 /* Useful functions defined in the section
431 `Image type independent image structures' below. */
433 static unsigned long four_corners_best (XImagePtr ximg
,
436 unsigned long height
);
439 /* Create a mask of a bitmap. Note is this not a perfect mask.
440 It's nicer with some borders in this context */
443 x_create_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
446 XImagePtr ximg
, mask_img
;
447 unsigned long width
, height
;
450 unsigned long x
, y
, xp
, xm
, yp
, ym
;
453 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
458 pixmap
= x_bitmap_pixmap (f
, id
);
459 width
= x_bitmap_width (f
, id
);
460 height
= x_bitmap_height (f
, id
);
463 ximg
= XGetImage (FRAME_X_DISPLAY (f
), pixmap
, 0, 0, width
, height
,
472 result
= x_create_x_image_and_pixmap (f
, width
, height
, 1, &mask_img
, &mask
);
477 XDestroyImage (ximg
);
481 bg
= four_corners_best (ximg
, NULL
, width
, height
);
483 for (y
= 0; y
< ximg
->height
; ++y
)
485 for (x
= 0; x
< ximg
->width
; ++x
)
487 xp
= x
!= ximg
->width
- 1 ? x
+ 1 : 0;
488 xm
= x
!= 0 ? x
- 1 : ximg
->width
- 1;
489 yp
= y
!= ximg
->height
- 1 ? y
+ 1 : 0;
490 ym
= y
!= 0 ? y
- 1 : ximg
->height
- 1;
491 if (XGetPixel (ximg
, x
, y
) == bg
492 && XGetPixel (ximg
, x
, yp
) == bg
493 && XGetPixel (ximg
, x
, ym
) == bg
494 && XGetPixel (ximg
, xp
, y
) == bg
495 && XGetPixel (ximg
, xp
, yp
) == bg
496 && XGetPixel (ximg
, xp
, ym
) == bg
497 && XGetPixel (ximg
, xm
, y
) == bg
498 && XGetPixel (ximg
, xm
, yp
) == bg
499 && XGetPixel (ximg
, xm
, ym
) == bg
)
500 XPutPixel (mask_img
, x
, y
, 0);
502 XPutPixel (mask_img
, x
, y
, 1);
506 eassert (input_blocked_p ());
507 gc
= XCreateGC (FRAME_X_DISPLAY (f
), mask
, 0, NULL
);
508 XPutImage (FRAME_X_DISPLAY (f
), mask
, gc
, mask_img
, 0, 0, 0, 0,
510 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
512 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
513 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
515 XDestroyImage (ximg
);
516 x_destroy_x_image (mask_img
);
519 #endif /* HAVE_X_WINDOWS */
521 /***********************************************************************
523 ***********************************************************************/
525 /* List of supported image types. Use define_image_type to add new
526 types. Use lookup_image_type to find a type for a given symbol. */
528 static struct image_type
*image_types
;
530 /* Forward function prototypes. */
532 static struct image_type
*lookup_image_type (Lisp_Object
);
533 static void x_laplace (struct frame
*, struct image
*);
534 static void x_emboss (struct frame
*, struct image
*);
535 static void x_build_heuristic_mask (struct frame
*, struct image
*,
538 #define CACHE_IMAGE_TYPE(type, status) \
539 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
541 #define CACHE_IMAGE_TYPE(type, status)
544 #define ADD_IMAGE_TYPE(type) \
545 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
547 /* Define a new image type from TYPE. This adds a copy of TYPE to
548 image_types and caches the loading status of TYPE. */
550 static struct image_type
*
551 define_image_type (struct image_type
*type
)
553 struct image_type
*p
= NULL
;
554 int new_type
= type
->type
;
555 bool type_valid
= true;
559 for (p
= image_types
; p
; p
= p
->next
)
560 if (p
->type
== new_type
)
565 #if defined HAVE_NTGUI && defined WINDOWSNT
566 /* If we failed to load the library before, don't try again. */
567 Lisp_Object tested
= Fassq (builtin_lisp_symbol (new_type
),
569 if (CONSP (tested
) && NILP (XCDR (tested
)))
574 type_valid
= type
->init ();
575 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type
),
576 type_valid
? Qt
: Qnil
);
582 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
583 The initialized data segment is read-only. */
584 p
= xmalloc (sizeof *p
);
586 p
->next
= image_types
;
596 /* Value is true if OBJECT is a valid Lisp image specification. A
597 valid image specification is a list whose car is the symbol
598 `image', and whose rest is a property list. The property list must
599 contain a value for key `:type'. That value must be the name of a
600 supported image type. The rest of the property list depends on the
604 valid_image_p (Lisp_Object object
)
612 for (tem
= XCDR (object
); CONSP (tem
); tem
= XCDR (tem
))
613 if (EQ (XCAR (tem
), QCtype
))
616 if (CONSP (tem
) && SYMBOLP (XCAR (tem
)))
618 struct image_type
*type
;
619 type
= lookup_image_type (XCAR (tem
));
621 valid_p
= type
->valid_p (object
);
632 /* Log error message with format string FORMAT and trailing arguments.
633 Signaling an error, e.g. when an image cannot be loaded, is not a
634 good idea because this would interrupt redisplay, and the error
635 message display would lead to another redisplay. This function
636 therefore simply displays a message. */
639 image_error (const char *format
, ...)
642 va_start (ap
, format
);
643 vadd_to_log (format
, ap
);
648 image_size_error (void)
650 image_error ("Invalid image size (see `%s')", "max-image-size");
654 /***********************************************************************
656 ***********************************************************************/
658 enum image_value_type
660 IMAGE_DONT_CHECK_VALUE_TYPE
,
662 IMAGE_STRING_OR_NIL_VALUE
,
664 IMAGE_POSITIVE_INTEGER_VALUE
,
665 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
,
666 IMAGE_NON_NEGATIVE_INTEGER_VALUE
,
669 IMAGE_FUNCTION_VALUE
,
674 /* Structure used when parsing image specifications. */
678 /* Name of keyword. */
681 /* The type of value allowed. */
682 enum image_value_type type
;
684 /* True means key must be present. */
687 /* Used to recognize duplicate keywords in a property list. */
690 /* The value that was found. */
695 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
696 has the format (image KEYWORD VALUE ...). One of the keyword/
697 value pairs must be `:type TYPE'. KEYWORDS is a vector of
698 image_keywords structures of size NKEYWORDS describing other
699 allowed keyword/value pairs. Value is true if SPEC is valid. */
702 parse_image_spec (Lisp_Object spec
, struct image_keyword
*keywords
,
703 int nkeywords
, Lisp_Object type
)
712 while (CONSP (plist
))
714 Lisp_Object key
, value
;
716 /* First element of a pair must be a symbol. */
718 plist
= XCDR (plist
);
722 /* There must follow a value. */
725 value
= XCAR (plist
);
726 plist
= XCDR (plist
);
728 /* Find key in KEYWORDS. Error if not found. */
729 for (i
= 0; i
< nkeywords
; ++i
)
730 if (strcmp (keywords
[i
].name
, SSDATA (SYMBOL_NAME (key
))) == 0)
736 /* Record that we recognized the keyword. If a keywords
737 was found more than once, it's an error. */
738 keywords
[i
].value
= value
;
739 if (keywords
[i
].count
> 1)
743 /* Check type of value against allowed type. */
744 switch (keywords
[i
].type
)
746 case IMAGE_STRING_VALUE
:
747 if (!STRINGP (value
))
751 case IMAGE_STRING_OR_NIL_VALUE
:
752 if (!STRINGP (value
) && !NILP (value
))
756 case IMAGE_SYMBOL_VALUE
:
757 if (!SYMBOLP (value
))
761 case IMAGE_POSITIVE_INTEGER_VALUE
:
762 if (! RANGED_INTEGERP (1, value
, INT_MAX
))
766 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
:
767 if (RANGED_INTEGERP (0, value
, INT_MAX
))
770 && RANGED_INTEGERP (0, XCAR (value
), INT_MAX
)
771 && RANGED_INTEGERP (0, XCDR (value
), INT_MAX
))
775 case IMAGE_ASCENT_VALUE
:
776 if (SYMBOLP (value
) && EQ (value
, Qcenter
))
778 else if (RANGED_INTEGERP (0, value
, 100))
782 case IMAGE_NON_NEGATIVE_INTEGER_VALUE
:
783 /* Unlike the other integer-related cases, this one does not
784 verify that VALUE fits in 'int'. This is because callers
786 if (!INTEGERP (value
) || XINT (value
) < 0)
790 case IMAGE_DONT_CHECK_VALUE_TYPE
:
793 case IMAGE_FUNCTION_VALUE
:
794 value
= indirect_function (value
);
795 if (!NILP (Ffunctionp (value
)))
799 case IMAGE_NUMBER_VALUE
:
800 if (! NUMBERP (value
))
804 case IMAGE_INTEGER_VALUE
:
805 if (! TYPE_RANGED_INTEGERP (int, value
))
809 case IMAGE_BOOL_VALUE
:
810 if (!NILP (value
) && !EQ (value
, Qt
))
819 if (EQ (key
, QCtype
) && !EQ (type
, value
))
823 /* Check that all mandatory fields are present. */
824 for (i
= 0; i
< nkeywords
; ++i
)
825 if (keywords
[i
].mandatory_p
&& keywords
[i
].count
== 0)
832 /* Return the value of KEY in image specification SPEC. Value is nil
833 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
834 was found in SPEC. */
837 image_spec_value (Lisp_Object spec
, Lisp_Object key
, bool *found
)
841 eassert (valid_image_p (spec
));
843 for (tail
= XCDR (spec
);
844 CONSP (tail
) && CONSP (XCDR (tail
));
845 tail
= XCDR (XCDR (tail
)))
847 if (EQ (XCAR (tail
), key
))
851 return XCAR (XCDR (tail
));
861 DEFUN ("image-size", Fimage_size
, Simage_size
, 1, 3, 0,
862 doc
: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
863 PIXELS non-nil means return the size in pixels, otherwise return the
864 size in canonical character units.
865 FRAME is the frame on which the image will be displayed. FRAME nil
866 or omitted means use the selected frame. */)
867 (Lisp_Object spec
, Lisp_Object pixels
, Lisp_Object frame
)
872 if (valid_image_p (spec
))
874 struct frame
*f
= decode_window_system_frame (frame
);
875 ptrdiff_t id
= lookup_image (f
, spec
);
876 struct image
*img
= IMAGE_FROM_ID (f
, id
);
877 int width
= img
->width
+ 2 * img
->hmargin
;
878 int height
= img
->height
+ 2 * img
->vmargin
;
881 size
= Fcons (make_float ((double) width
/ FRAME_COLUMN_WIDTH (f
)),
882 make_float ((double) height
/ FRAME_LINE_HEIGHT (f
)));
884 size
= Fcons (make_number (width
), make_number (height
));
887 error ("Invalid image specification");
893 DEFUN ("image-mask-p", Fimage_mask_p
, Simage_mask_p
, 1, 2, 0,
894 doc
: /* Return t if image SPEC has a mask bitmap.
895 FRAME is the frame on which the image will be displayed. FRAME nil
896 or omitted means use the selected frame. */)
897 (Lisp_Object spec
, Lisp_Object frame
)
902 if (valid_image_p (spec
))
904 struct frame
*f
= decode_window_system_frame (frame
);
905 ptrdiff_t id
= lookup_image (f
, spec
);
906 struct image
*img
= IMAGE_FROM_ID (f
, id
);
911 error ("Invalid image specification");
916 DEFUN ("image-metadata", Fimage_metadata
, Simage_metadata
, 1, 2, 0,
917 doc
: /* Return metadata for image SPEC.
918 FRAME is the frame on which the image will be displayed. FRAME nil
919 or omitted means use the selected frame. */)
920 (Lisp_Object spec
, Lisp_Object frame
)
925 if (valid_image_p (spec
))
927 struct frame
*f
= decode_window_system_frame (frame
);
928 ptrdiff_t id
= lookup_image (f
, spec
);
929 struct image
*img
= IMAGE_FROM_ID (f
, id
);
930 ext
= img
->lisp_data
;
937 /***********************************************************************
938 Image type independent image structures
939 ***********************************************************************/
941 #define MAX_IMAGE_SIZE 10.0
942 /* Allocate and return a new image structure for image specification
943 SPEC. SPEC has a hash value of HASH. */
945 static struct image
*
946 make_image (Lisp_Object spec
, EMACS_UINT hash
)
948 struct image
*img
= xzalloc (sizeof *img
);
949 Lisp_Object file
= image_spec_value (spec
, QCfile
, NULL
);
951 eassert (valid_image_p (spec
));
952 img
->dependencies
= NILP (file
) ? Qnil
: list1 (file
);
953 img
->type
= lookup_image_type (image_spec_value (spec
, QCtype
, NULL
));
954 eassert (img
->type
!= NULL
);
956 img
->lisp_data
= Qnil
;
957 img
->ascent
= DEFAULT_IMAGE_ASCENT
;
959 img
->corners
[BOT_CORNER
] = -1; /* Full image */
964 /* Free image IMG which was used on frame F, including its resources. */
967 free_image (struct frame
*f
, struct image
*img
)
971 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
973 /* Remove IMG from the hash table of its cache. */
975 img
->prev
->next
= img
->next
;
977 c
->buckets
[img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
] = img
->next
;
980 img
->next
->prev
= img
->prev
;
982 c
->images
[img
->id
] = NULL
;
984 /* Windows NT redefines 'free', but in this file, we need to
985 avoid the redefinition. */
989 /* Free resources, then free IMG. */
990 img
->type
->free (f
, img
);
995 /* Return true if the given widths and heights are valid for display. */
998 check_image_size (struct frame
*f
, int width
, int height
)
1002 if (width
<= 0 || height
<= 0)
1005 if (INTEGERP (Vmax_image_size
))
1006 return (width
<= XINT (Vmax_image_size
)
1007 && height
<= XINT (Vmax_image_size
));
1008 else if (FLOATP (Vmax_image_size
))
1012 w
= FRAME_PIXEL_WIDTH (f
);
1013 h
= FRAME_PIXEL_HEIGHT (f
);
1016 w
= h
= 1024; /* Arbitrary size for unknown frame. */
1017 return (width
<= XFLOAT_DATA (Vmax_image_size
) * w
1018 && height
<= XFLOAT_DATA (Vmax_image_size
) * h
);
1024 /* Prepare image IMG for display on frame F. Must be called before
1025 drawing an image. */
1028 prepare_image_for_display (struct frame
*f
, struct image
*img
)
1030 /* We're about to display IMG, so set its timestamp to `now'. */
1031 img
->timestamp
= current_timespec ();
1034 /* If IMG doesn't have a pixmap yet, load it now, using the image
1035 type dependent loader function. */
1036 if (img
->pixmap
== NO_PIXMAP
&& !img
->load_failed_p
)
1037 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1039 #ifdef HAVE_X_WINDOWS
1040 if (!img
->load_failed_p
)
1043 image_sync_to_pixmaps (f
, img
);
1051 /* Value is the number of pixels for the ascent of image IMG when
1052 drawn in face FACE. */
1055 image_ascent (struct image
*img
, struct face
*face
, struct glyph_slice
*slice
)
1060 if (slice
->height
== img
->height
)
1061 height
= img
->height
+ img
->vmargin
;
1062 else if (slice
->y
== 0)
1063 height
= slice
->height
+ img
->vmargin
;
1065 height
= slice
->height
;
1067 if (img
->ascent
== CENTERED_IMAGE_ASCENT
)
1072 /* W32 specific version. Why?. ++kfs */
1073 ascent
= height
/ 2 - (FONT_DESCENT (face
->font
)
1074 - FONT_BASE (face
->font
)) / 2;
1076 /* This expression is arranged so that if the image can't be
1077 exactly centered, it will be moved slightly up. This is
1078 because a typical font is `top-heavy' (due to the presence
1079 uppercase letters), so the image placement should err towards
1080 being top-heavy too. It also just generally looks better. */
1081 ascent
= (height
+ FONT_BASE (face
->font
)
1082 - FONT_DESCENT (face
->font
) + 1) / 2;
1083 #endif /* HAVE_NTGUI */
1086 ascent
= height
/ 2;
1089 ascent
= height
* (img
->ascent
/ 100.0);
1096 xcolor_to_argb32 (XColor xc
)
1098 return (0xff << 24) | ((xc
.red
/ 256) << 16)
1099 | ((xc
.green
/ 256) << 8) | (xc
.blue
/ 256);
1103 get_spec_bg_or_alpha_as_argb (struct image
*img
,
1106 uint32_t bgcolor
= 0;
1108 Lisp_Object bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1110 if (STRINGP (bg
) && XParseColor (FRAME_X_DISPLAY (f
),
1111 FRAME_X_COLORMAP (f
),
1114 bgcolor
= xcolor_to_argb32 (xbgcolor
);
1120 create_cairo_image_surface (struct image
*img
,
1121 unsigned char *data
,
1125 cairo_surface_t
*surface
;
1126 cairo_format_t format
= CAIRO_FORMAT_ARGB32
;
1127 int stride
= cairo_format_stride_for_width (format
, width
);
1128 surface
= cairo_image_surface_create_for_data (data
,
1134 img
->height
= height
;
1135 img
->cr_data
= surface
;
1136 img
->cr_data2
= data
;
1143 /* Image background colors. */
1145 /* Find the "best" corner color of a bitmap.
1146 On W32, XIMG is assumed to a device context with the bitmap selected. */
1148 static RGB_PIXEL_COLOR
1149 four_corners_best (XImagePtr_or_DC ximg
, int *corners
,
1150 unsigned long width
, unsigned long height
)
1152 RGB_PIXEL_COLOR corner_pixels
[4], best
IF_LINT (= 0);
1155 if (corners
&& corners
[BOT_CORNER
] >= 0)
1157 /* Get the colors at the corner_pixels of ximg. */
1158 corner_pixels
[0] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[TOP_CORNER
]);
1159 corner_pixels
[1] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[TOP_CORNER
]);
1160 corner_pixels
[2] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[BOT_CORNER
] - 1);
1161 corner_pixels
[3] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[BOT_CORNER
] - 1);
1165 /* Get the colors at the corner_pixels of ximg. */
1166 corner_pixels
[0] = GET_PIXEL (ximg
, 0, 0);
1167 corner_pixels
[1] = GET_PIXEL (ximg
, width
- 1, 0);
1168 corner_pixels
[2] = GET_PIXEL (ximg
, width
- 1, height
- 1);
1169 corner_pixels
[3] = GET_PIXEL (ximg
, 0, height
- 1);
1171 /* Choose the most frequently found color as background. */
1172 for (i
= best_count
= 0; i
< 4; ++i
)
1176 for (j
= n
= 0; j
< 4; ++j
)
1177 if (corner_pixels
[i
] == corner_pixels
[j
])
1181 best
= corner_pixels
[i
], best_count
= n
;
1187 /* Portability macros */
1191 #define Free_Pixmap(display, pixmap) \
1192 DeleteObject (pixmap)
1194 #elif defined (HAVE_NS)
1196 #define Free_Pixmap(display, pixmap) \
1197 ns_release_object (pixmap)
1201 #define Free_Pixmap(display, pixmap) \
1202 XFreePixmap (display, pixmap)
1204 #endif /* !HAVE_NTGUI && !HAVE_NS */
1207 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1208 it is guessed heuristically. If non-zero, XIMG is an existing
1209 XImage object (or device context with the image selected on W32) to
1210 use for the heuristic. */
1213 image_background (struct image
*img
, struct frame
*f
, XImagePtr_or_DC ximg
)
1215 if (! img
->background_valid
)
1216 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1218 bool free_ximg
= !ximg
;
1221 #endif /* HAVE_NTGUI */
1224 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
1226 img
->background
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
1229 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
1231 img
->background_valid
= 1;
1234 return img
->background
;
1237 /* Return the `background_transparent' field of IMG. If IMG doesn't
1238 have one yet, it is guessed heuristically. If non-zero, MASK is an
1239 existing XImage object to use for the heuristic. */
1242 image_background_transparent (struct image
*img
, struct frame
*f
, XImagePtr_or_DC mask
)
1244 if (! img
->background_transparent_valid
)
1245 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1249 bool free_mask
= !mask
;
1252 #endif /* HAVE_NTGUI */
1255 mask
= image_get_x_image_or_dc (f
, img
, 1, &prev
);
1257 img
->background_transparent
1258 = (four_corners_best (mask
, img
->corners
, img
->width
, img
->height
) == PIX_MASK_RETAIN
);
1261 image_unget_x_image_or_dc (img
, 1, mask
, prev
);
1264 img
->background_transparent
= 0;
1266 img
->background_transparent_valid
= 1;
1269 return img
->background_transparent
;
1272 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1273 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1275 /* Store F's background color into *BGCOLOR. */
1277 x_query_frame_background_color (struct frame
*f
, XColor
*bgcolor
)
1280 bgcolor
->pixel
= FRAME_BACKGROUND_PIXEL (f
);
1281 x_query_color (f
, bgcolor
);
1283 ns_query_color (FRAME_BACKGROUND_COLOR (f
), bgcolor
, 1);
1287 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1289 /***********************************************************************
1290 Helper functions for X image types
1291 ***********************************************************************/
1293 /* Clear X resources of image IMG on frame F according to FLAGS.
1294 FLAGS is bitwise-or of the following masks:
1295 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1296 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1297 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1300 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1301 #define CLEAR_IMAGE_MASK (1 << 1)
1302 #define CLEAR_IMAGE_COLORS (1 << 2)
1305 x_clear_image_1 (struct frame
*f
, struct image
*img
, int flags
)
1307 if (flags
& CLEAR_IMAGE_PIXMAP
)
1311 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->pixmap
);
1312 img
->pixmap
= NO_PIXMAP
;
1313 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1314 img
->background_valid
= 0;
1316 #ifdef HAVE_X_WINDOWS
1319 x_destroy_x_image (img
->ximg
);
1321 img
->background_valid
= 0;
1326 if (flags
& CLEAR_IMAGE_MASK
)
1330 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->mask
);
1331 img
->mask
= NO_PIXMAP
;
1332 img
->background_transparent_valid
= 0;
1334 #ifdef HAVE_X_WINDOWS
1337 x_destroy_x_image (img
->mask_img
);
1338 img
->mask_img
= NULL
;
1339 img
->background_transparent_valid
= 0;
1344 if ((flags
& CLEAR_IMAGE_COLORS
) && img
->ncolors
)
1346 /* W32_TODO: color table support. */
1347 #ifdef HAVE_X_WINDOWS
1348 x_free_colors (f
, img
->colors
, img
->ncolors
);
1349 #endif /* HAVE_X_WINDOWS */
1350 xfree (img
->colors
);
1357 /* Free X resources of image IMG which is used on frame F. */
1360 x_clear_image (struct frame
*f
, struct image
*img
)
1365 cairo_surface_destroy ((cairo_surface_t
*)img
->cr_data
);
1366 if (img
->cr_data2
) xfree (img
->cr_data2
);
1368 x_clear_image_1 (f
, img
,
1369 CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_MASK
| CLEAR_IMAGE_COLORS
);
1374 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1375 cannot be allocated, use DFLT. Add a newly allocated color to
1376 IMG->colors, so that it can be freed again. Value is the pixel
1379 static unsigned long
1380 x_alloc_image_color (struct frame
*f
, struct image
*img
, Lisp_Object color_name
,
1384 unsigned long result
;
1386 eassert (STRINGP (color_name
));
1388 if (x_defined_color (f
, SSDATA (color_name
), &color
, 1)
1389 && img
->ncolors
< min (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *img
->colors
,
1392 /* This isn't called frequently so we get away with simply
1393 reallocating the color vector to the needed size, here. */
1394 ptrdiff_t ncolors
= img
->ncolors
+ 1;
1395 img
->colors
= xrealloc (img
->colors
, ncolors
* sizeof *img
->colors
);
1396 img
->colors
[ncolors
- 1] = color
.pixel
;
1397 img
->ncolors
= ncolors
;
1398 result
= color
.pixel
;
1408 /***********************************************************************
1410 ***********************************************************************/
1412 static void cache_image (struct frame
*f
, struct image
*img
);
1414 /* Return a new, initialized image cache that is allocated from the
1415 heap. Call free_image_cache to free an image cache. */
1417 struct image_cache
*
1418 make_image_cache (void)
1420 struct image_cache
*c
= xmalloc (sizeof *c
);
1423 c
->used
= c
->refcount
= 0;
1424 c
->images
= xmalloc (c
->size
* sizeof *c
->images
);
1425 c
->buckets
= xzalloc (IMAGE_CACHE_BUCKETS_SIZE
* sizeof *c
->buckets
);
1430 /* Find an image matching SPEC in the cache, and return it. If no
1431 image is found, return NULL. */
1432 static struct image
*
1433 search_image_cache (struct frame
*f
, Lisp_Object spec
, EMACS_UINT hash
)
1436 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1437 int i
= hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1439 if (!c
) return NULL
;
1441 /* If the image spec does not specify a background color, the cached
1442 image must have the same background color as the current frame.
1443 The foreground color must also match, for the sake of monochrome
1446 In fact, we could ignore the foreground color matching condition
1447 for color images, or if the image spec specifies :foreground;
1448 similarly we could ignore the background color matching condition
1449 for formats that don't use transparency (such as jpeg), or if the
1450 image spec specifies :background. However, the extra memory
1451 usage is probably negligible in practice, so we don't bother. */
1453 for (img
= c
->buckets
[i
]; img
; img
= img
->next
)
1454 if (img
->hash
== hash
1455 && !NILP (Fequal (img
->spec
, spec
))
1456 && img
->frame_foreground
== FRAME_FOREGROUND_PIXEL (f
)
1457 && img
->frame_background
== FRAME_BACKGROUND_PIXEL (f
))
1463 /* Search frame F for an image with spec SPEC, and free it. */
1466 uncache_image (struct frame
*f
, Lisp_Object spec
)
1468 struct image
*img
= search_image_cache (f
, spec
, sxhash (spec
, 0));
1471 free_image (f
, img
);
1472 /* As display glyphs may still be referring to the image ID, we
1473 must garbage the frame (Bug#6426). */
1474 SET_FRAME_GARBAGED (f
);
1479 /* Free image cache of frame F. Be aware that X frames share images
1483 free_image_cache (struct frame
*f
)
1485 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1490 /* Cache should not be referenced by any frame when freed. */
1491 eassert (c
->refcount
== 0);
1493 for (i
= 0; i
< c
->used
; ++i
)
1494 free_image (f
, c
->images
[i
]);
1498 FRAME_IMAGE_CACHE (f
) = NULL
;
1503 /* Clear image cache of frame F. FILTER=t means free all images.
1504 FILTER=nil means clear only images that haven't been
1505 displayed for some time.
1506 Else, only free the images which have FILTER in their `dependencies'.
1507 Should be called from time to time to reduce the number of loaded images.
1508 If image-cache-eviction-delay is non-nil, this frees images in the cache
1509 which weren't displayed for at least that many seconds. */
1512 clear_image_cache (struct frame
*f
, Lisp_Object filter
)
1514 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1518 ptrdiff_t i
, nfreed
= 0;
1520 /* Block input so that we won't be interrupted by a SIGIO
1521 while being in an inconsistent state. */
1526 /* Filter image cache. */
1527 for (i
= 0; i
< c
->used
; ++i
)
1529 struct image
*img
= c
->images
[i
];
1530 if (img
&& (EQ (Qt
, filter
)
1531 || !NILP (Fmember (filter
, img
->dependencies
))))
1533 free_image (f
, img
);
1538 else if (INTEGERP (Vimage_cache_eviction_delay
))
1540 /* Free cache based on timestamp. */
1541 struct timespec old
, t
;
1543 ptrdiff_t nimages
= 0;
1545 for (i
= 0; i
< c
->used
; ++i
)
1549 /* If the number of cached images has grown unusually large,
1550 decrease the cache eviction delay (Bug#6230). */
1551 delay
= XINT (Vimage_cache_eviction_delay
);
1553 delay
= 1600 * delay
/ nimages
/ nimages
;
1554 delay
= max (delay
, 1);
1556 t
= current_timespec ();
1557 old
= timespec_sub (t
, dtotimespec (delay
));
1559 for (i
= 0; i
< c
->used
; ++i
)
1561 struct image
*img
= c
->images
[i
];
1562 if (img
&& timespec_cmp (img
->timestamp
, old
) < 0)
1564 free_image (f
, img
);
1570 /* We may be clearing the image cache because, for example,
1571 Emacs was iconified for a longer period of time. In that
1572 case, current matrices may still contain references to
1573 images freed above. So, clear these matrices. */
1576 Lisp_Object tail
, frame
;
1578 FOR_EACH_FRAME (tail
, frame
)
1580 struct frame
*fr
= XFRAME (frame
);
1581 if (FRAME_IMAGE_CACHE (fr
) == c
)
1582 clear_current_matrices (fr
);
1585 windows_or_buffers_changed
= 19;
1593 clear_image_caches (Lisp_Object filter
)
1595 /* FIXME: We want to do
1596 * struct terminal *t;
1597 * for (t = terminal_list; t; t = t->next_terminal)
1598 * clear_image_cache (t, filter); */
1599 Lisp_Object tail
, frame
;
1600 FOR_EACH_FRAME (tail
, frame
)
1601 if (FRAME_WINDOW_P (XFRAME (frame
)))
1602 clear_image_cache (XFRAME (frame
), filter
);
1605 DEFUN ("clear-image-cache", Fclear_image_cache
, Sclear_image_cache
,
1607 doc
: /* Clear the image cache.
1608 FILTER nil or a frame means clear all images in the selected frame.
1609 FILTER t means clear the image caches of all frames.
1610 Anything else, means only clear those images which refer to FILTER,
1611 which is then usually a filename. */)
1612 (Lisp_Object filter
)
1614 if (!(EQ (filter
, Qnil
) || FRAMEP (filter
)))
1615 clear_image_caches (filter
);
1617 clear_image_cache (decode_window_system_frame (filter
), Qt
);
1623 DEFUN ("image-flush", Fimage_flush
, Simage_flush
,
1625 doc
: /* Flush the image with specification SPEC on frame FRAME.
1626 This removes the image from the Emacs image cache. If SPEC specifies
1627 an image file, the next redisplay of this image will read from the
1628 current contents of that file.
1630 FRAME nil or omitted means use the selected frame.
1631 FRAME t means refresh the image on all frames. */)
1632 (Lisp_Object spec
, Lisp_Object frame
)
1634 if (!valid_image_p (spec
))
1635 error ("Invalid image specification");
1640 FOR_EACH_FRAME (tail
, frame
)
1642 struct frame
*f
= XFRAME (frame
);
1643 if (FRAME_WINDOW_P (f
))
1644 uncache_image (f
, spec
);
1648 uncache_image (decode_window_system_frame (frame
), spec
);
1654 /* Compute masks and transform image IMG on frame F, as specified
1655 by the image's specification, */
1658 postprocess_image (struct frame
*f
, struct image
*img
)
1660 /* Manipulation of the image's mask. */
1663 Lisp_Object conversion
, spec
;
1668 /* `:heuristic-mask t'
1670 means build a mask heuristically.
1671 `:heuristic-mask (R G B)'
1672 `:mask (heuristic (R G B))'
1673 means build a mask from color (R G B) in the
1676 means remove a mask, if any. */
1678 mask
= image_spec_value (spec
, QCheuristic_mask
, NULL
);
1680 x_build_heuristic_mask (f
, img
, mask
);
1685 mask
= image_spec_value (spec
, QCmask
, &found_p
);
1687 if (EQ (mask
, Qheuristic
))
1688 x_build_heuristic_mask (f
, img
, Qt
);
1689 else if (CONSP (mask
)
1690 && EQ (XCAR (mask
), Qheuristic
))
1692 if (CONSP (XCDR (mask
)))
1693 x_build_heuristic_mask (f
, img
, XCAR (XCDR (mask
)));
1695 x_build_heuristic_mask (f
, img
, XCDR (mask
));
1697 else if (NILP (mask
) && found_p
&& img
->mask
)
1698 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
1702 /* Should we apply an image transformation algorithm? */
1703 conversion
= image_spec_value (spec
, QCconversion
, NULL
);
1704 if (EQ (conversion
, Qdisabled
))
1705 x_disable_image (f
, img
);
1706 else if (EQ (conversion
, Qlaplace
))
1708 else if (EQ (conversion
, Qemboss
))
1710 else if (CONSP (conversion
)
1711 && EQ (XCAR (conversion
), Qedge_detection
))
1714 tem
= XCDR (conversion
);
1716 x_edge_detection (f
, img
,
1717 Fplist_get (tem
, QCmatrix
),
1718 Fplist_get (tem
, QCcolor_adjustment
));
1724 /* Return the id of image with Lisp specification SPEC on frame F.
1725 SPEC must be a valid Lisp image specification (see valid_image_p). */
1728 lookup_image (struct frame
*f
, Lisp_Object spec
)
1733 /* F must be a window-system frame, and SPEC must be a valid image
1735 eassert (FRAME_WINDOW_P (f
));
1736 eassert (valid_image_p (spec
));
1738 /* Look up SPEC in the hash table of the image cache. */
1739 hash
= sxhash (spec
, 0);
1740 img
= search_image_cache (f
, spec
, hash
);
1741 if (img
&& img
->load_failed_p
)
1743 free_image (f
, img
);
1747 /* If not found, create a new image and cache it. */
1751 img
= make_image (spec
, hash
);
1752 cache_image (f
, img
);
1753 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1754 img
->frame_foreground
= FRAME_FOREGROUND_PIXEL (f
);
1755 img
->frame_background
= FRAME_BACKGROUND_PIXEL (f
);
1757 /* If we can't load the image, and we don't have a width and
1758 height, use some arbitrary width and height so that we can
1759 draw a rectangle for it. */
1760 if (img
->load_failed_p
)
1764 value
= image_spec_value (spec
, QCwidth
, NULL
);
1765 img
->width
= (INTEGERP (value
)
1766 ? XFASTINT (value
) : DEFAULT_IMAGE_WIDTH
);
1767 value
= image_spec_value (spec
, QCheight
, NULL
);
1768 img
->height
= (INTEGERP (value
)
1769 ? XFASTINT (value
) : DEFAULT_IMAGE_HEIGHT
);
1773 /* Handle image type independent image attributes
1774 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1775 `:background COLOR'. */
1776 Lisp_Object ascent
, margin
, relief
, bg
;
1779 ascent
= image_spec_value (spec
, QCascent
, NULL
);
1780 if (INTEGERP (ascent
))
1781 img
->ascent
= XFASTINT (ascent
);
1782 else if (EQ (ascent
, Qcenter
))
1783 img
->ascent
= CENTERED_IMAGE_ASCENT
;
1785 margin
= image_spec_value (spec
, QCmargin
, NULL
);
1786 if (INTEGERP (margin
))
1787 img
->vmargin
= img
->hmargin
= XFASTINT (margin
);
1788 else if (CONSP (margin
))
1790 img
->hmargin
= XFASTINT (XCAR (margin
));
1791 img
->vmargin
= XFASTINT (XCDR (margin
));
1794 relief
= image_spec_value (spec
, QCrelief
, NULL
);
1795 relief_bound
= INT_MAX
- max (img
->hmargin
, img
->vmargin
);
1796 if (RANGED_INTEGERP (- relief_bound
, relief
, relief_bound
))
1798 img
->relief
= XINT (relief
);
1799 img
->hmargin
+= eabs (img
->relief
);
1800 img
->vmargin
+= eabs (img
->relief
);
1803 if (! img
->background_valid
)
1805 bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1809 = x_alloc_image_color (f
, img
, bg
,
1810 FRAME_BACKGROUND_PIXEL (f
));
1811 img
->background_valid
= 1;
1815 /* Do image transformations and compute masks, unless we
1816 don't have the image yet. */
1817 if (!EQ (builtin_lisp_symbol (img
->type
->type
), Qpostscript
))
1818 postprocess_image (f
, img
);
1824 /* We're using IMG, so set its timestamp to `now'. */
1825 img
->timestamp
= current_timespec ();
1827 /* Value is the image id. */
1832 /* Cache image IMG in the image cache of frame F. */
1835 cache_image (struct frame
*f
, struct image
*img
)
1837 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1840 /* Find a free slot in c->images. */
1841 for (i
= 0; i
< c
->used
; ++i
)
1842 if (c
->images
[i
] == NULL
)
1845 /* If no free slot found, maybe enlarge c->images. */
1846 if (i
== c
->used
&& c
->used
== c
->size
)
1847 c
->images
= xpalloc (c
->images
, &c
->size
, 1, -1, sizeof *c
->images
);
1849 /* Add IMG to c->images, and assign IMG an id. */
1855 /* Add IMG to the cache's hash table. */
1856 i
= img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1857 img
->next
= c
->buckets
[i
];
1859 img
->next
->prev
= img
;
1861 c
->buckets
[i
] = img
;
1865 /* Call FN on every image in the image cache of frame F. Used to mark
1866 Lisp Objects in the image cache. */
1868 /* Mark Lisp objects in image IMG. */
1871 mark_image (struct image
*img
)
1873 mark_object (img
->spec
);
1874 mark_object (img
->dependencies
);
1876 if (!NILP (img
->lisp_data
))
1877 mark_object (img
->lisp_data
);
1882 mark_image_cache (struct image_cache
*c
)
1887 for (i
= 0; i
< c
->used
; ++i
)
1889 mark_image (c
->images
[i
]);
1895 /***********************************************************************
1896 X / NS / W32 support code
1897 ***********************************************************************/
1899 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1901 WIDTH and HEIGHT must both be positive.
1902 If XIMG is null, assume it is a bitmap. */
1904 x_check_image_size (XImagePtr ximg
, int width
, int height
)
1906 #ifdef HAVE_X_WINDOWS
1907 /* Respect Xlib's limits: it cannot deal with images that have more
1908 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1909 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1912 XLIB_BYTES_MAX
= min (INT_MAX
, UINT_MAX
),
1913 X_IMAGE_BYTES_MAX
= min (XLIB_BYTES_MAX
, min (PTRDIFF_MAX
, SIZE_MAX
))
1916 int bitmap_pad
, depth
, bytes_per_line
;
1919 bitmap_pad
= ximg
->bitmap_pad
;
1920 depth
= ximg
->depth
;
1921 bytes_per_line
= ximg
->bytes_per_line
;
1927 bytes_per_line
= (width
>> 3) + ((width
& 7) != 0);
1929 return (width
<= (INT_MAX
- (bitmap_pad
- 1)) / depth
1930 && height
<= X_IMAGE_BYTES_MAX
/ bytes_per_line
);
1932 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1933 For now, assume that every image size is allowed on these systems. */
1938 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1939 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1940 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1941 via xmalloc. Print error messages via image_error if an error
1942 occurs. Value is true if successful.
1944 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1945 should indicate the bit depth of the image. */
1948 x_create_x_image_and_pixmap (struct frame
*f
, int width
, int height
, int depth
,
1949 XImagePtr
*ximg
, Pixmap
*pixmap
)
1951 #ifdef HAVE_X_WINDOWS
1952 Display
*display
= FRAME_X_DISPLAY (f
);
1953 Window window
= FRAME_X_WINDOW (f
);
1954 Screen
*screen
= FRAME_X_SCREEN (f
);
1956 eassert (input_blocked_p ());
1959 depth
= DefaultDepthOfScreen (screen
);
1960 *ximg
= XCreateImage (display
, DefaultVisualOfScreen (screen
),
1961 depth
, ZPixmap
, 0, NULL
, width
, height
,
1962 depth
> 16 ? 32 : depth
> 8 ? 16 : 8, 0);
1965 image_error ("Unable to allocate X image");
1969 if (! x_check_image_size (*ximg
, width
, height
))
1971 x_destroy_x_image (*ximg
);
1973 image_error ("Image too large (%dx%d)",
1974 make_number (width
), make_number (height
));
1978 /* Allocate image raster. */
1979 (*ximg
)->data
= xmalloc ((*ximg
)->bytes_per_line
* height
);
1981 /* Allocate a pixmap of the same size. */
1982 *pixmap
= XCreatePixmap (display
, window
, width
, height
, depth
);
1983 if (*pixmap
== NO_PIXMAP
)
1985 x_destroy_x_image (*ximg
);
1987 image_error ("Unable to create X pixmap");
1992 #endif /* HAVE_X_WINDOWS */
1996 BITMAPINFOHEADER
*header
;
1998 int scanline_width_bits
;
2000 int palette_colors
= 0;
2005 if (depth
!= 1 && depth
!= 4 && depth
!= 8
2006 && depth
!= 16 && depth
!= 24 && depth
!= 32)
2008 image_error ("Invalid image bit depth specified");
2012 scanline_width_bits
= width
* depth
;
2013 remainder
= scanline_width_bits
% 32;
2016 scanline_width_bits
+= 32 - remainder
;
2018 /* Bitmaps with a depth less than 16 need a palette. */
2019 /* BITMAPINFO structure already contains the first RGBQUAD. */
2021 palette_colors
= 1 << (depth
- 1);
2023 *ximg
= xmalloc (sizeof (XImage
) + palette_colors
* sizeof (RGBQUAD
));
2025 header
= &(*ximg
)->info
.bmiHeader
;
2026 memset (&(*ximg
)->info
, 0, sizeof (BITMAPINFO
));
2027 header
->biSize
= sizeof (*header
);
2028 header
->biWidth
= width
;
2029 header
->biHeight
= -height
; /* negative indicates a top-down bitmap. */
2030 header
->biPlanes
= 1;
2031 header
->biBitCount
= depth
;
2032 header
->biCompression
= BI_RGB
;
2033 header
->biClrUsed
= palette_colors
;
2035 /* TODO: fill in palette. */
2038 (*ximg
)->info
.bmiColors
[0].rgbBlue
= 0;
2039 (*ximg
)->info
.bmiColors
[0].rgbGreen
= 0;
2040 (*ximg
)->info
.bmiColors
[0].rgbRed
= 0;
2041 (*ximg
)->info
.bmiColors
[0].rgbReserved
= 0;
2042 (*ximg
)->info
.bmiColors
[1].rgbBlue
= 255;
2043 (*ximg
)->info
.bmiColors
[1].rgbGreen
= 255;
2044 (*ximg
)->info
.bmiColors
[1].rgbRed
= 255;
2045 (*ximg
)->info
.bmiColors
[1].rgbReserved
= 0;
2048 hdc
= get_frame_dc (f
);
2050 /* Create a DIBSection and raster array for the bitmap,
2051 and store its handle in *pixmap. */
2052 *pixmap
= CreateDIBSection (hdc
, &((*ximg
)->info
),
2053 (depth
< 16) ? DIB_PAL_COLORS
: DIB_RGB_COLORS
,
2054 /* casting avoids a GCC warning */
2055 (void **)&((*ximg
)->data
), NULL
, 0);
2057 /* Realize display palette and garbage all frames. */
2058 release_frame_dc (f
, hdc
);
2060 if (*pixmap
== NULL
)
2062 DWORD err
= GetLastError ();
2063 Lisp_Object errcode
;
2064 /* All system errors are < 10000, so the following is safe. */
2065 XSETINT (errcode
, err
);
2066 image_error ("Unable to create bitmap, error code %d", errcode
);
2067 x_destroy_x_image (*ximg
);
2074 #endif /* HAVE_NTGUI */
2077 *pixmap
= ns_image_for_XPM (width
, height
, depth
);
2081 image_error ("Unable to allocate NSImage for XPM pixmap");
2090 /* Destroy XImage XIMG. Free XIMG->data. */
2093 x_destroy_x_image (XImagePtr ximg
)
2095 eassert (input_blocked_p ());
2098 #ifdef HAVE_X_WINDOWS
2101 XDestroyImage (ximg
);
2102 #endif /* HAVE_X_WINDOWS */
2104 /* Data will be freed by DestroyObject. */
2107 #endif /* HAVE_NTGUI */
2109 ns_release_object (ximg
);
2110 #endif /* HAVE_NS */
2115 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2116 are width and height of both the image and pixmap. */
2119 x_put_x_image (struct frame
*f
, XImagePtr ximg
, Pixmap pixmap
, int width
, int height
)
2121 #ifdef HAVE_X_WINDOWS
2124 eassert (input_blocked_p ());
2125 gc
= XCreateGC (FRAME_X_DISPLAY (f
), pixmap
, 0, NULL
);
2126 XPutImage (FRAME_X_DISPLAY (f
), pixmap
, gc
, ximg
, 0, 0, 0, 0, width
, height
);
2127 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
2128 #endif /* HAVE_X_WINDOWS */
2131 #if 0 /* I don't think this is necessary looking at where it is used. */
2132 HDC hdc
= get_frame_dc (f
);
2133 SetDIBits (hdc
, pixmap
, 0, height
, ximg
->data
, &(ximg
->info
), DIB_RGB_COLORS
);
2134 release_frame_dc (f
, hdc
);
2136 #endif /* HAVE_NTGUI */
2139 eassert (ximg
== pixmap
);
2140 ns_retain_object (ximg
);
2144 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2145 with image_put_x_image. */
2148 image_create_x_image_and_pixmap (struct frame
*f
, struct image
*img
,
2149 int width
, int height
, int depth
,
2150 XImagePtr
*ximg
, bool mask_p
)
2152 eassert ((!mask_p
? img
->pixmap
: img
->mask
) == NO_PIXMAP
);
2154 return x_create_x_image_and_pixmap (f
, width
, height
, depth
, ximg
,
2155 !mask_p
? &img
->pixmap
: &img
->mask
);
2158 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2159 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2160 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2161 On the other platforms, it puts XIMG into the pixmap, then frees
2162 the X image and its buffer. */
2165 image_put_x_image (struct frame
*f
, struct image
*img
, XImagePtr ximg
,
2168 #ifdef HAVE_X_WINDOWS
2171 eassert (img
->ximg
== NULL
);
2176 eassert (img
->mask_img
== NULL
);
2177 img
->mask_img
= ximg
;
2180 x_put_x_image (f
, ximg
, !mask_p
? img
->pixmap
: img
->mask
,
2181 img
->width
, img
->height
);
2182 x_destroy_x_image (ximg
);
2186 #ifdef HAVE_X_WINDOWS
2187 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2188 the X images and their buffers. */
2191 image_sync_to_pixmaps (struct frame
*f
, struct image
*img
)
2195 x_put_x_image (f
, img
->ximg
, img
->pixmap
, img
->width
, img
->height
);
2196 x_destroy_x_image (img
->ximg
);
2201 x_put_x_image (f
, img
->mask_img
, img
->mask
, img
->width
, img
->height
);
2202 x_destroy_x_image (img
->mask_img
);
2203 img
->mask_img
= NULL
;
2209 /* Create a memory device context for IMG on frame F. It stores the
2210 currently selected GDI object into *PREV for future restoration by
2211 image_unget_x_image_or_dc. */
2213 static XImagePtr_or_DC
2214 image_get_x_image_or_dc (struct frame
*f
, struct image
*img
, bool mask_p
,
2217 HDC frame_dc
= get_frame_dc (f
);
2218 XImagePtr_or_DC ximg
= CreateCompatibleDC (frame_dc
);
2220 release_frame_dc (f
, frame_dc
);
2221 *prev
= SelectObject (ximg
, !mask_p
? img
->pixmap
: img
->mask
);
2227 image_unget_x_image_or_dc (struct image
*img
, bool mask_p
,
2228 XImagePtr_or_DC ximg
, HGDIOBJ prev
)
2230 SelectObject (ximg
, prev
);
2233 #else /* !HAVE_NTGUI */
2234 /* Get the X image for IMG on frame F. The resulting X image data
2235 should be treated as read-only at least on X. */
2238 image_get_x_image (struct frame
*f
, struct image
*img
, bool mask_p
)
2240 #ifdef HAVE_X_WINDOWS
2241 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2246 return XGetImage (FRAME_X_DISPLAY (f
), !mask_p
? img
->pixmap
: img
->mask
,
2247 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
2248 #elif defined (HAVE_NS)
2249 XImagePtr pixmap
= !mask_p
? img
->pixmap
: img
->mask
;
2251 ns_retain_object (pixmap
);
2257 image_unget_x_image (struct image
*img
, bool mask_p
, XImagePtr ximg
)
2259 #ifdef HAVE_X_WINDOWS
2260 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2263 eassert (ximg
== ximg_in_img
);
2265 XDestroyImage (ximg
);
2266 #elif defined (HAVE_NS)
2267 ns_release_object (ximg
);
2270 #endif /* !HAVE_NTGUI */
2273 /***********************************************************************
2275 ***********************************************************************/
2277 /* Find image file FILE. Look in data-directory/images, then
2278 x-bitmap-file-path. Value is the full name of the file
2279 found, or nil if not found. If PFD is nonnull store into *PFD a
2280 readable file descriptor for the file, opened in binary mode. If
2281 PFD is null, do not open the file. */
2284 x_find_image_fd (Lisp_Object file
, int *pfd
)
2286 Lisp_Object file_found
, search_path
;
2289 /* TODO I think this should use something like image-load-path
2290 instead. Unfortunately, that can contain non-string elements. */
2291 search_path
= Fcons (Fexpand_file_name (build_string ("images"),
2293 Vx_bitmap_file_path
);
2295 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2296 fd
= openp (search_path
, file
, Qnil
, &file_found
,
2297 pfd
? Qt
: make_number (R_OK
), false);
2305 /* Find image file FILE. Look in data-directory/images, then
2306 x-bitmap-file-path. Value is the encoded full name of the file
2307 found, or nil if not found. */
2310 x_find_image_file (Lisp_Object file
)
2312 return x_find_image_fd (file
, 0);
2315 /* Read FILE into memory. Value is a pointer to a buffer allocated
2316 with xmalloc holding FILE's contents. Value is null if an error
2317 occurred. FD is a file descriptor open for reading FILE. Set
2318 *SIZE to the size of the file. */
2320 static unsigned char *
2321 slurp_file (int fd
, ptrdiff_t *size
)
2323 FILE *fp
= fdopen (fd
, "rb");
2325 unsigned char *buf
= NULL
;
2330 ptrdiff_t count
= SPECPDL_INDEX ();
2331 record_unwind_protect_ptr (fclose_unwind
, fp
);
2333 if (fstat (fileno (fp
), &st
) == 0
2334 && 0 <= st
.st_size
&& st
.st_size
< min (PTRDIFF_MAX
, SIZE_MAX
))
2336 /* Report an error if we read past the purported EOF.
2337 This can happen if the file grows as we read it. */
2338 ptrdiff_t buflen
= st
.st_size
;
2339 buf
= xmalloc (buflen
+ 1);
2340 if (fread (buf
, 1, buflen
+ 1, fp
) == buflen
)
2349 unbind_to (count
, Qnil
);
2357 /***********************************************************************
2359 ***********************************************************************/
2361 static bool xbm_load (struct frame
*f
, struct image
*img
);
2362 static bool xbm_image_p (Lisp_Object object
);
2363 static bool xbm_file_p (Lisp_Object
);
2366 /* Indices of image specification fields in xbm_format, below. */
2368 enum xbm_keyword_index
2386 /* Vector of image_keyword structures describing the format
2387 of valid XBM image specifications. */
2389 static const struct image_keyword xbm_format
[XBM_LAST
] =
2391 {":type", IMAGE_SYMBOL_VALUE
, 1},
2392 {":file", IMAGE_STRING_VALUE
, 0},
2393 {":width", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2394 {":height", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2395 {":data", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2396 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
2397 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
2398 {":ascent", IMAGE_ASCENT_VALUE
, 0},
2399 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
2400 {":relief", IMAGE_INTEGER_VALUE
, 0},
2401 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2402 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2403 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
2406 /* Structure describing the image type XBM. */
2408 static struct image_type xbm_type
=
2410 SYMBOL_INDEX (Qxbm
),
2418 /* Tokens returned from xbm_scan. */
2427 /* Return true if OBJECT is a valid XBM-type image specification.
2428 A valid specification is a list starting with the symbol `image'
2429 The rest of the list is a property list which must contain an
2432 If the specification specifies a file to load, it must contain
2433 an entry `:file FILENAME' where FILENAME is a string.
2435 If the specification is for a bitmap loaded from memory it must
2436 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2437 WIDTH and HEIGHT are integers > 0. DATA may be:
2439 1. a string large enough to hold the bitmap data, i.e. it must
2440 have a size >= (WIDTH + 7) / 8 * HEIGHT
2442 2. a bool-vector of size >= WIDTH * HEIGHT
2444 3. a vector of strings or bool-vectors, one for each line of the
2447 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2448 may not be specified in this case because they are defined in the
2451 Both the file and data forms may contain the additional entries
2452 `:background COLOR' and `:foreground COLOR'. If not present,
2453 foreground and background of the frame on which the image is
2454 displayed is used. */
2457 xbm_image_p (Lisp_Object object
)
2459 struct image_keyword kw
[XBM_LAST
];
2461 memcpy (kw
, xbm_format
, sizeof kw
);
2462 if (!parse_image_spec (object
, kw
, XBM_LAST
, Qxbm
))
2465 eassert (EQ (kw
[XBM_TYPE
].value
, Qxbm
));
2467 if (kw
[XBM_FILE
].count
)
2469 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_DATA
].count
)
2472 else if (kw
[XBM_DATA
].count
&& xbm_file_p (kw
[XBM_DATA
].value
))
2474 /* In-memory XBM file. */
2475 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_FILE
].count
)
2483 /* Entries for `:width', `:height' and `:data' must be present. */
2484 if (!kw
[XBM_WIDTH
].count
2485 || !kw
[XBM_HEIGHT
].count
2486 || !kw
[XBM_DATA
].count
)
2489 data
= kw
[XBM_DATA
].value
;
2490 width
= XFASTINT (kw
[XBM_WIDTH
].value
);
2491 height
= XFASTINT (kw
[XBM_HEIGHT
].value
);
2493 /* Check type of data, and width and height against contents of
2499 /* Number of elements of the vector must be >= height. */
2500 if (ASIZE (data
) < height
)
2503 /* Each string or bool-vector in data must be large enough
2504 for one line of the image. */
2505 for (i
= 0; i
< height
; ++i
)
2507 Lisp_Object elt
= AREF (data
, i
);
2512 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
)
2515 else if (BOOL_VECTOR_P (elt
))
2517 if (bool_vector_size (elt
) < width
)
2524 else if (STRINGP (data
))
2527 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
* height
)
2530 else if (BOOL_VECTOR_P (data
))
2532 if (bool_vector_size (data
) / height
< width
)
2543 /* Scan a bitmap file. FP is the stream to read from. Value is
2544 either an enumerator from enum xbm_token, or a character for a
2545 single-character token, or 0 at end of file. If scanning an
2546 identifier, store the lexeme of the identifier in SVAL. If
2547 scanning a number, store its value in *IVAL. */
2550 xbm_scan (unsigned char **s
, unsigned char *end
, char *sval
, int *ival
)
2556 /* Skip white space. */
2557 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
2562 else if (c_isdigit (c
))
2564 int value
= 0, digit
;
2566 if (c
== '0' && *s
< end
)
2569 if (c
== 'x' || c
== 'X')
2576 else if (c
>= 'a' && c
<= 'f')
2577 digit
= c
- 'a' + 10;
2578 else if (c
>= 'A' && c
<= 'F')
2579 digit
= c
- 'A' + 10;
2582 value
= 16 * value
+ digit
;
2585 else if (c_isdigit (c
))
2589 && (c
= *(*s
)++, c_isdigit (c
)))
2590 value
= 8 * value
+ c
- '0';
2597 && (c
= *(*s
)++, c_isdigit (c
)))
2598 value
= 10 * value
+ c
- '0';
2606 else if (c_isalpha (c
) || c
== '_')
2610 && (c
= *(*s
)++, (c_isalnum (c
) || c
== '_')))
2617 else if (c
== '/' && **s
== '*')
2619 /* C-style comment. */
2621 while (**s
&& (**s
!= '*' || *(*s
+ 1) != '/'))
2635 /* Create a Windows bitmap from X bitmap data. */
2637 w32_create_pixmap_from_bitmap_data (int width
, int height
, char *data
)
2639 static unsigned char swap_nibble
[16]
2640 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2641 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2642 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2643 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2645 unsigned char *bits
, *p
;
2648 w1
= (width
+ 7) / 8; /* nb of 8bits elt in X bitmap */
2649 w2
= ((width
+ 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2650 bits
= alloca (height
* w2
);
2651 memset (bits
, 0, height
* w2
);
2652 for (i
= 0; i
< height
; i
++)
2655 for (j
= 0; j
< w1
; j
++)
2657 /* Bitswap XBM bytes to match how Windows does things. */
2658 unsigned char c
= *data
++;
2659 *p
++ = (unsigned char)((swap_nibble
[c
& 0xf] << 4)
2660 | (swap_nibble
[(c
>>4) & 0xf]));
2663 bmp
= CreateBitmap (width
, height
, 1, 1, (char *) bits
);
2669 convert_mono_to_color_image (struct frame
*f
, struct image
*img
,
2670 COLORREF foreground
, COLORREF background
)
2672 HDC hdc
, old_img_dc
, new_img_dc
;
2673 HGDIOBJ old_prev
, new_prev
;
2676 hdc
= get_frame_dc (f
);
2677 old_img_dc
= CreateCompatibleDC (hdc
);
2678 new_img_dc
= CreateCompatibleDC (hdc
);
2679 new_pixmap
= CreateCompatibleBitmap (hdc
, img
->width
, img
->height
);
2680 release_frame_dc (f
, hdc
);
2681 old_prev
= SelectObject (old_img_dc
, img
->pixmap
);
2682 new_prev
= SelectObject (new_img_dc
, new_pixmap
);
2683 /* Windows convention for mono bitmaps is black = background,
2684 white = foreground. */
2685 SetTextColor (new_img_dc
, background
);
2686 SetBkColor (new_img_dc
, foreground
);
2688 BitBlt (new_img_dc
, 0, 0, img
->width
, img
->height
, old_img_dc
,
2691 SelectObject (old_img_dc
, old_prev
);
2692 SelectObject (new_img_dc
, new_prev
);
2693 DeleteDC (old_img_dc
);
2694 DeleteDC (new_img_dc
);
2695 DeleteObject (img
->pixmap
);
2696 if (new_pixmap
== 0)
2697 fprintf (stderr
, "Failed to convert image to color.\n");
2699 img
->pixmap
= new_pixmap
;
2702 #define XBM_BIT_SHUFFLE(b) (~(b))
2706 #define XBM_BIT_SHUFFLE(b) (b)
2708 #endif /* HAVE_NTGUI */
2712 Create_Pixmap_From_Bitmap_Data (struct frame
*f
, struct image
*img
, char *data
,
2713 RGB_PIXEL_COLOR fg
, RGB_PIXEL_COLOR bg
,
2714 bool non_default_colors
)
2718 = w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
, data
);
2720 /* If colors were specified, transfer the bitmap to a color one. */
2721 if (non_default_colors
)
2722 convert_mono_to_color_image (f
, img
, fg
, bg
);
2724 #elif defined (HAVE_NS)
2725 img
->pixmap
= ns_image_from_XBM (data
, img
->width
, img
->height
, fg
, bg
);
2729 (x_check_image_size (0, img
->width
, img
->height
)
2730 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f
),
2733 img
->width
, img
->height
,
2735 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)))
2737 #endif /* !HAVE_NTGUI && !HAVE_NS */
2742 /* Replacement for XReadBitmapFileData which isn't available under old
2743 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2744 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2745 the image. Return in *DATA the bitmap data allocated with xmalloc.
2746 Value is true if successful. DATA null means just test if
2747 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2748 inhibit the call to image_error when the image size is invalid (the
2749 bitmap remains unread). */
2752 xbm_read_bitmap_data (struct frame
*f
, unsigned char *contents
, unsigned char *end
,
2753 int *width
, int *height
, char **data
,
2754 bool inhibit_image_error
)
2756 unsigned char *s
= contents
;
2757 char buffer
[BUFSIZ
];
2760 int bytes_per_line
, i
, nbytes
;
2766 LA1 = xbm_scan (&s, end, buffer, &value)
2768 #define expect(TOKEN) \
2771 if (LA1 != (TOKEN)) \
2777 #define expect_ident(IDENT) \
2778 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2783 *width
= *height
= -1;
2786 LA1
= xbm_scan (&s
, end
, buffer
, &value
);
2788 /* Parse defines for width, height and hot-spots. */
2792 expect_ident ("define");
2793 expect (XBM_TK_IDENT
);
2795 if (LA1
== XBM_TK_NUMBER
)
2797 char *q
= strrchr (buffer
, '_');
2798 q
= q
? q
+ 1 : buffer
;
2799 if (strcmp (q
, "width") == 0)
2801 else if (strcmp (q
, "height") == 0)
2804 expect (XBM_TK_NUMBER
);
2807 if (!check_image_size (f
, *width
, *height
))
2809 if (!inhibit_image_error
)
2810 image_size_error ();
2813 else if (data
== NULL
)
2816 /* Parse bits. Must start with `static'. */
2817 expect_ident ("static");
2818 if (LA1
== XBM_TK_IDENT
)
2820 if (strcmp (buffer
, "unsigned") == 0)
2823 expect_ident ("char");
2825 else if (strcmp (buffer
, "short") == 0)
2829 if (*width
% 16 && *width
% 16 < 9)
2832 else if (strcmp (buffer
, "char") == 0)
2840 expect (XBM_TK_IDENT
);
2846 if (! x_check_image_size (0, *width
, *height
))
2848 if (!inhibit_image_error
)
2849 image_error ("Image too large (%dx%d)",
2850 make_number (*width
), make_number (*height
));
2853 bytes_per_line
= (*width
+ 7) / 8 + padding_p
;
2854 nbytes
= bytes_per_line
* *height
;
2855 p
= *data
= xmalloc (nbytes
);
2859 for (i
= 0; i
< nbytes
; i
+= 2)
2862 expect (XBM_TK_NUMBER
);
2864 *p
++ = XBM_BIT_SHUFFLE (val
);
2865 if (!padding_p
|| ((i
+ 2) % bytes_per_line
))
2866 *p
++ = XBM_BIT_SHUFFLE (value
>> 8);
2868 if (LA1
== ',' || LA1
== '}')
2876 for (i
= 0; i
< nbytes
; ++i
)
2879 expect (XBM_TK_NUMBER
);
2881 *p
++ = XBM_BIT_SHUFFLE (val
);
2883 if (LA1
== ',' || LA1
== '}')
2908 /* Load XBM image IMG which will be displayed on frame F from buffer
2909 CONTENTS. END is the end of the buffer. Value is true if
2913 xbm_load_image (struct frame
*f
, struct image
*img
, unsigned char *contents
,
2920 rc
= xbm_read_bitmap_data (f
, contents
, end
, &img
->width
, &img
->height
,
2924 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
2925 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
2926 bool non_default_colors
= 0;
2929 eassert (img
->width
> 0 && img
->height
> 0);
2931 /* Get foreground and background colors, maybe allocate colors. */
2932 value
= image_spec_value (img
->spec
, QCforeground
, NULL
);
2935 foreground
= x_alloc_image_color (f
, img
, value
, foreground
);
2936 non_default_colors
= 1;
2938 value
= image_spec_value (img
->spec
, QCbackground
, NULL
);
2941 background
= x_alloc_image_color (f
, img
, value
, background
);
2942 img
->background
= background
;
2943 img
->background_valid
= 1;
2944 non_default_colors
= 1;
2947 Create_Pixmap_From_Bitmap_Data (f
, img
, data
,
2948 foreground
, background
,
2949 non_default_colors
);
2952 if (img
->pixmap
== NO_PIXMAP
)
2954 x_clear_image (f
, img
);
2955 image_error ("Unable to create X pixmap for `%s'", img
->spec
);
2961 image_error ("Error loading XBM image `%s'", img
->spec
);
2967 /* Value is true if DATA looks like an in-memory XBM file. */
2970 xbm_file_p (Lisp_Object data
)
2973 return (STRINGP (data
)
2974 && xbm_read_bitmap_data (NULL
, SDATA (data
),
2975 (SDATA (data
) + SBYTES (data
)),
2980 /* Fill image IMG which is used on frame F with pixmap data. Value is
2981 true if successful. */
2984 xbm_load (struct frame
*f
, struct image
*img
)
2987 Lisp_Object file_name
;
2989 eassert (xbm_image_p (img
->spec
));
2991 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2992 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
2993 if (STRINGP (file_name
))
2996 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
2997 if (!STRINGP (file
))
2999 image_error ("Cannot find image file `%s'", file_name
);
3004 unsigned char *contents
= slurp_file (fd
, &size
);
3005 if (contents
== NULL
)
3007 image_error ("Error loading XBM image `%s'", file
);
3011 success_p
= xbm_load_image (f
, img
, contents
, contents
+ size
);
3016 struct image_keyword fmt
[XBM_LAST
];
3018 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
3019 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
3020 bool non_default_colors
= 0;
3023 bool in_memory_file_p
= 0;
3025 /* See if data looks like an in-memory XBM file. */
3026 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
3027 in_memory_file_p
= xbm_file_p (data
);
3029 /* Parse the image specification. */
3030 memcpy (fmt
, xbm_format
, sizeof fmt
);
3031 parsed_p
= parse_image_spec (img
->spec
, fmt
, XBM_LAST
, Qxbm
);
3034 /* Get specified width, and height. */
3035 if (!in_memory_file_p
)
3037 img
->width
= XFASTINT (fmt
[XBM_WIDTH
].value
);
3038 img
->height
= XFASTINT (fmt
[XBM_HEIGHT
].value
);
3039 eassert (img
->width
> 0 && img
->height
> 0);
3040 if (!check_image_size (f
, img
->width
, img
->height
))
3042 image_size_error ();
3047 /* Get foreground and background colors, maybe allocate colors. */
3048 if (fmt
[XBM_FOREGROUND
].count
3049 && STRINGP (fmt
[XBM_FOREGROUND
].value
))
3051 foreground
= x_alloc_image_color (f
, img
, fmt
[XBM_FOREGROUND
].value
,
3053 non_default_colors
= 1;
3056 if (fmt
[XBM_BACKGROUND
].count
3057 && STRINGP (fmt
[XBM_BACKGROUND
].value
))
3059 background
= x_alloc_image_color (f
, img
, fmt
[XBM_BACKGROUND
].value
,
3061 non_default_colors
= 1;
3064 if (in_memory_file_p
)
3065 success_p
= xbm_load_image (f
, img
, SDATA (data
),
3076 int nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3078 SAFE_NALLOCA (bits
, nbytes
, img
->height
);
3080 for (i
= 0; i
< img
->height
; ++i
, p
+= nbytes
)
3082 Lisp_Object line
= AREF (data
, i
);
3084 memcpy (p
, SDATA (line
), nbytes
);
3086 memcpy (p
, bool_vector_data (line
), nbytes
);
3089 else if (STRINGP (data
))
3090 bits
= SSDATA (data
);
3092 bits
= (char *) bool_vector_data (data
);
3098 /* Windows mono bitmaps are reversed compared with X. */
3099 invertedBits
= bits
;
3100 nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3101 SAFE_NALLOCA (bits
, nbytes
, img
->height
);
3102 for (i
= 0; i
< nbytes
; i
++)
3103 bits
[i
] = XBM_BIT_SHUFFLE (invertedBits
[i
]);
3106 /* Create the pixmap. */
3108 if (x_check_image_size (0, img
->width
, img
->height
))
3109 Create_Pixmap_From_Bitmap_Data (f
, img
, bits
,
3110 foreground
, background
,
3111 non_default_colors
);
3113 img
->pixmap
= NO_PIXMAP
;
3119 image_error ("Unable to create pixmap for XBM image `%s'",
3121 x_clear_image (f
, img
);
3133 /***********************************************************************
3135 ***********************************************************************/
3137 #if defined (HAVE_XPM) || defined (HAVE_NS)
3139 static bool xpm_image_p (Lisp_Object object
);
3140 static bool xpm_load (struct frame
*f
, struct image
*img
);
3142 #endif /* HAVE_XPM || HAVE_NS */
3146 /* Indicate to xpm.h that we don't have Xlib. */
3148 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3149 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3150 #define XColor xpm_XColor
3151 #define XImage xpm_XImage
3152 #define Display xpm_Display
3153 #define PIXEL_ALREADY_TYPEDEFED
3154 #include "X11/xpm.h"
3159 #undef PIXEL_ALREADY_TYPEDEFED
3161 #include "X11/xpm.h"
3162 #endif /* HAVE_NTGUI */
3163 #endif /* HAVE_XPM */
3165 #if defined (HAVE_XPM) || defined (HAVE_NS)
3167 /* Indices of image specification fields in xpm_format, below. */
3169 enum xpm_keyword_index
3185 /* Vector of image_keyword structures describing the format
3186 of valid XPM image specifications. */
3188 static const struct image_keyword xpm_format
[XPM_LAST
] =
3190 {":type", IMAGE_SYMBOL_VALUE
, 1},
3191 {":file", IMAGE_STRING_VALUE
, 0},
3192 {":data", IMAGE_STRING_VALUE
, 0},
3193 {":ascent", IMAGE_ASCENT_VALUE
, 0},
3194 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
3195 {":relief", IMAGE_INTEGER_VALUE
, 0},
3196 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3197 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3198 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3199 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3200 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
3203 #if defined HAVE_NTGUI && defined WINDOWSNT
3204 static bool init_xpm_functions (void);
3206 #define init_xpm_functions NULL
3209 /* Structure describing the image type XPM. */
3211 static struct image_type xpm_type
=
3213 SYMBOL_INDEX (Qxpm
),
3221 #ifdef HAVE_X_WINDOWS
3223 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3224 functions for allocating image colors. Our own functions handle
3225 color allocation failures more gracefully than the ones on the XPM
3229 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3230 #define ALLOC_XPM_COLORS
3232 #endif /* USE_CAIRO */
3233 #endif /* HAVE_X_WINDOWS */
3235 #ifdef ALLOC_XPM_COLORS
3237 static struct xpm_cached_color
*xpm_cache_color (struct frame
*, char *,
3240 /* An entry in a hash table used to cache color definitions of named
3241 colors. This cache is necessary to speed up XPM image loading in
3242 case we do color allocations ourselves. Without it, we would need
3243 a call to XParseColor per pixel in the image. */
3245 struct xpm_cached_color
3247 /* Next in collision chain. */
3248 struct xpm_cached_color
*next
;
3250 /* Color definition (RGB and pixel color). */
3254 char name
[FLEXIBLE_ARRAY_MEMBER
];
3257 /* The hash table used for the color cache, and its bucket vector
3260 #define XPM_COLOR_CACHE_BUCKETS 1001
3261 static struct xpm_cached_color
**xpm_color_cache
;
3263 /* Initialize the color cache. */
3266 xpm_init_color_cache (struct frame
*f
, XpmAttributes
*attrs
)
3268 size_t nbytes
= XPM_COLOR_CACHE_BUCKETS
* sizeof *xpm_color_cache
;
3269 xpm_color_cache
= xzalloc (nbytes
);
3270 init_color_table ();
3272 if (attrs
->valuemask
& XpmColorSymbols
)
3277 for (i
= 0; i
< attrs
->numsymbols
; ++i
)
3278 if (XParseColor (FRAME_X_DISPLAY (f
), FRAME_X_COLORMAP (f
),
3279 attrs
->colorsymbols
[i
].value
, &color
))
3281 color
.pixel
= lookup_rgb_color (f
, color
.red
, color
.green
,
3283 xpm_cache_color (f
, attrs
->colorsymbols
[i
].name
, &color
, -1);
3288 /* Free the color cache. */
3291 xpm_free_color_cache (void)
3293 struct xpm_cached_color
*p
, *next
;
3296 for (i
= 0; i
< XPM_COLOR_CACHE_BUCKETS
; ++i
)
3297 for (p
= xpm_color_cache
[i
]; p
; p
= next
)
3303 xfree (xpm_color_cache
);
3304 xpm_color_cache
= NULL
;
3305 free_color_table ();
3308 /* Return the bucket index for color named COLOR_NAME in the color
3312 xpm_color_bucket (char *color_name
)
3314 EMACS_UINT hash
= hash_string (color_name
, strlen (color_name
));
3315 return hash
% XPM_COLOR_CACHE_BUCKETS
;
3319 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3320 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3323 static struct xpm_cached_color
*
3324 xpm_cache_color (struct frame
*f
, char *color_name
, XColor
*color
, int bucket
)
3327 struct xpm_cached_color
*p
;
3330 bucket
= xpm_color_bucket (color_name
);
3332 nbytes
= offsetof (struct xpm_cached_color
, name
) + strlen (color_name
) + 1;
3333 p
= xmalloc (nbytes
);
3334 strcpy (p
->name
, color_name
);
3336 p
->next
= xpm_color_cache
[bucket
];
3337 xpm_color_cache
[bucket
] = p
;
3341 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3342 return the cached definition in *COLOR. Otherwise, make a new
3343 entry in the cache and allocate the color. Value is false if color
3344 allocation failed. */
3347 xpm_lookup_color (struct frame
*f
, char *color_name
, XColor
*color
)
3349 struct xpm_cached_color
*p
;
3350 int h
= xpm_color_bucket (color_name
);
3352 for (p
= xpm_color_cache
[h
]; p
; p
= p
->next
)
3353 if (strcmp (p
->name
, color_name
) == 0)
3358 else if (XParseColor (FRAME_X_DISPLAY (f
), FRAME_X_COLORMAP (f
),
3361 color
->pixel
= lookup_rgb_color (f
, color
->red
, color
->green
,
3363 p
= xpm_cache_color (f
, color_name
, color
, h
);
3365 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3366 with transparency, and it's useful. */
3367 else if (strcmp ("opaque", color_name
) == 0)
3369 memset (color
, 0, sizeof (XColor
)); /* Is this necessary/correct? */
3370 color
->pixel
= FRAME_FOREGROUND_PIXEL (f
);
3371 p
= xpm_cache_color (f
, color_name
, color
, h
);
3378 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3379 CLOSURE is a pointer to the frame on which we allocate the
3380 color. Return in *COLOR the allocated color. Value is non-zero
3384 xpm_alloc_color (Display
*dpy
, Colormap cmap
, char *color_name
, XColor
*color
,
3387 return xpm_lookup_color (closure
, color_name
, color
);
3391 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3392 is a pointer to the frame on which we allocate the color. Value is
3393 non-zero if successful. */
3396 xpm_free_colors (Display
*dpy
, Colormap cmap
, Pixel
*pixels
, int npixels
, void *closure
)
3401 #endif /* ALLOC_XPM_COLORS */
3406 /* XPM library details. */
3408 DEF_DLL_FN (void, XpmFreeAttributes
, (XpmAttributes
*));
3409 DEF_DLL_FN (int, XpmCreateImageFromBuffer
,
3410 (Display
*, char *, xpm_XImage
**,
3411 xpm_XImage
**, XpmAttributes
*));
3412 DEF_DLL_FN (int, XpmReadFileToImage
,
3413 (Display
*, char *, xpm_XImage
**,
3414 xpm_XImage
**, XpmAttributes
*));
3415 DEF_DLL_FN (void, XImageFree
, (xpm_XImage
*));
3418 init_xpm_functions (void)
3422 if (!(library
= w32_delayed_load (Qxpm
)))
3425 LOAD_DLL_FN (library
, XpmFreeAttributes
);
3426 LOAD_DLL_FN (library
, XpmCreateImageFromBuffer
);
3427 LOAD_DLL_FN (library
, XpmReadFileToImage
);
3428 LOAD_DLL_FN (library
, XImageFree
);
3433 # undef XpmCreateImageFromBuffer
3434 # undef XpmFreeAttributes
3435 # undef XpmReadFileToImage
3437 # define XImageFree fn_XImageFree
3438 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3439 # define XpmFreeAttributes fn_XpmFreeAttributes
3440 # define XpmReadFileToImage fn_XpmReadFileToImage
3442 #endif /* WINDOWSNT */
3444 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3445 for XPM images. Such a list must consist of conses whose car and
3449 xpm_valid_color_symbols_p (Lisp_Object color_symbols
)
3451 while (CONSP (color_symbols
))
3453 Lisp_Object sym
= XCAR (color_symbols
);
3455 || !STRINGP (XCAR (sym
))
3456 || !STRINGP (XCDR (sym
)))
3458 color_symbols
= XCDR (color_symbols
);
3461 return NILP (color_symbols
);
3465 /* Value is true if OBJECT is a valid XPM image specification. */
3468 xpm_image_p (Lisp_Object object
)
3470 struct image_keyword fmt
[XPM_LAST
];
3471 memcpy (fmt
, xpm_format
, sizeof fmt
);
3472 return (parse_image_spec (object
, fmt
, XPM_LAST
, Qxpm
)
3473 /* Either `:file' or `:data' must be present. */
3474 && fmt
[XPM_FILE
].count
+ fmt
[XPM_DATA
].count
== 1
3475 /* Either no `:color-symbols' or it's a list of conses
3476 whose car and cdr are strings. */
3477 && (fmt
[XPM_COLOR_SYMBOLS
].count
== 0
3478 || xpm_valid_color_symbols_p (fmt
[XPM_COLOR_SYMBOLS
].value
)));
3481 #endif /* HAVE_XPM || HAVE_NS */
3483 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3485 x_create_bitmap_from_xpm_data (struct frame
*f
, const char **bits
)
3487 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
3490 XpmAttributes attrs
;
3491 Pixmap bitmap
, mask
;
3493 memset (&attrs
, 0, sizeof attrs
);
3495 attrs
.visual
= FRAME_X_VISUAL (f
);
3496 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3497 attrs
.valuemask
|= XpmVisual
;
3498 attrs
.valuemask
|= XpmColormap
;
3500 rc
= XpmCreatePixmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3501 (char **) bits
, &bitmap
, &mask
, &attrs
);
3502 if (rc
!= XpmSuccess
)
3504 XpmFreeAttributes (&attrs
);
3508 id
= x_allocate_bitmap_record (f
);
3509 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
3510 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
3511 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
3512 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
3513 dpyinfo
->bitmaps
[id
- 1].height
= attrs
.height
;
3514 dpyinfo
->bitmaps
[id
- 1].width
= attrs
.width
;
3515 dpyinfo
->bitmaps
[id
- 1].depth
= attrs
.depth
;
3516 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
3518 XpmFreeAttributes (&attrs
);
3521 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3523 /* Load image IMG which will be displayed on frame F. Value is
3524 true if successful. */
3529 xpm_load (struct frame
*f
, struct image
*img
)
3532 XpmAttributes attrs
;
3533 Lisp_Object specified_file
, color_symbols
;
3538 xpm_XImage
* xpm_image
= NULL
, * xpm_mask
= NULL
;
3539 #endif /* HAVE_NTGUI */
3541 /* Configure the XPM lib. Use the visual of frame F. Allocate
3542 close colors. Return colors allocated. */
3543 memset (&attrs
, 0, sizeof attrs
);
3546 attrs
.visual
= FRAME_X_VISUAL (f
);
3547 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3548 attrs
.valuemask
|= XpmVisual
;
3549 attrs
.valuemask
|= XpmColormap
;
3550 #endif /* HAVE_NTGUI */
3552 #ifdef ALLOC_XPM_COLORS
3553 /* Allocate colors with our own functions which handle
3554 failing color allocation more gracefully. */
3555 attrs
.color_closure
= f
;
3556 attrs
.alloc_color
= xpm_alloc_color
;
3557 attrs
.free_colors
= xpm_free_colors
;
3558 attrs
.valuemask
|= XpmAllocColor
| XpmFreeColors
| XpmColorClosure
;
3559 #else /* not ALLOC_XPM_COLORS */
3560 /* Let the XPM lib allocate colors. */
3561 attrs
.valuemask
|= XpmReturnAllocPixels
;
3562 #ifdef XpmAllocCloseColors
3563 attrs
.alloc_close_colors
= 1;
3564 attrs
.valuemask
|= XpmAllocCloseColors
;
3565 #else /* not XpmAllocCloseColors */
3566 attrs
.closeness
= 600;
3567 attrs
.valuemask
|= XpmCloseness
;
3568 #endif /* not XpmAllocCloseColors */
3569 #endif /* ALLOC_XPM_COLORS */
3571 /* If image specification contains symbolic color definitions, add
3572 these to `attrs'. */
3573 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
3574 if (CONSP (color_symbols
))
3577 XpmColorSymbol
*xpm_syms
;
3580 attrs
.valuemask
|= XpmColorSymbols
;
3582 /* Count number of symbols. */
3583 attrs
.numsymbols
= 0;
3584 for (tail
= color_symbols
; CONSP (tail
); tail
= XCDR (tail
))
3587 /* Allocate an XpmColorSymbol array. */
3588 SAFE_NALLOCA (xpm_syms
, 1, attrs
.numsymbols
);
3589 size
= attrs
.numsymbols
* sizeof *xpm_syms
;
3590 memset (xpm_syms
, 0, size
);
3591 attrs
.colorsymbols
= xpm_syms
;
3593 /* Fill the color symbol array. */
3594 for (tail
= color_symbols
, i
= 0;
3596 ++i
, tail
= XCDR (tail
))
3600 char *empty_string
= (char *) "";
3602 if (!CONSP (XCAR (tail
)))
3604 xpm_syms
[i
].name
= empty_string
;
3605 xpm_syms
[i
].value
= empty_string
;
3608 name
= XCAR (XCAR (tail
));
3609 color
= XCDR (XCAR (tail
));
3611 SAFE_ALLOCA_STRING (xpm_syms
[i
].name
, name
);
3613 xpm_syms
[i
].name
= empty_string
;
3614 if (STRINGP (color
))
3615 SAFE_ALLOCA_STRING (xpm_syms
[i
].value
, color
);
3617 xpm_syms
[i
].value
= empty_string
;
3621 /* Create a pixmap for the image, either from a file, or from a
3622 string buffer containing data in the same format as an XPM file. */
3623 #ifdef ALLOC_XPM_COLORS
3624 xpm_init_color_cache (f
, &attrs
);
3627 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
3631 HDC frame_dc
= get_frame_dc (f
);
3632 hdc
= CreateCompatibleDC (frame_dc
);
3633 release_frame_dc (f
, frame_dc
);
3635 #endif /* HAVE_NTGUI */
3637 if (STRINGP (specified_file
))
3639 Lisp_Object file
= x_find_image_file (specified_file
);
3640 if (!STRINGP (file
))
3642 image_error ("Cannot find image file `%s'", specified_file
);
3643 #ifdef ALLOC_XPM_COLORS
3644 xpm_free_color_cache ();
3650 file
= ENCODE_FILE (file
);
3653 /* FILE is encoded in UTF-8, but image libraries on Windows
3654 support neither UTF-8 nor UTF-16 encoded file names. So we
3655 need to re-encode it in ANSI. */
3656 file
= ansi_encode_filename (file
);
3658 /* XpmReadFileToPixmap is not available in the Windows port of
3659 libxpm. But XpmReadFileToImage almost does what we want. */
3660 rc
= XpmReadFileToImage (&hdc
, SDATA (file
),
3661 &xpm_image
, &xpm_mask
,
3664 rc
= XpmReadFileToImage (FRAME_X_DISPLAY (f
), SSDATA (file
),
3665 &img
->ximg
, &img
->mask_img
,
3667 #endif /* HAVE_NTGUI */
3671 Lisp_Object buffer
= image_spec_value (img
->spec
, QCdata
, NULL
);
3672 if (!STRINGP (buffer
))
3674 image_error ("Invalid image data `%s'", buffer
);
3675 #ifdef ALLOC_XPM_COLORS
3676 xpm_free_color_cache ();
3682 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3683 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3684 rc
= XpmCreateImageFromBuffer (&hdc
, SDATA (buffer
),
3685 &xpm_image
, &xpm_mask
,
3688 rc
= XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f
), SSDATA (buffer
),
3689 &img
->ximg
, &img
->mask_img
,
3691 #endif /* HAVE_NTGUI */
3695 // Load very specific Xpm:s.
3696 if (rc
== XpmSuccess
3697 && img
->ximg
->format
== ZPixmap
3698 && img
->ximg
->bits_per_pixel
== 32
3699 && (! img
->mask_img
|| img
->mask_img
->bits_per_pixel
== 1))
3701 int width
= img
->ximg
->width
;
3702 int height
= img
->ximg
->height
;
3703 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
3705 uint32_t *od
= (uint32_t *)data
;
3706 uint32_t *id
= (uint32_t *)img
->ximg
->data
;
3707 char *mid
= img
->mask_img
? img
->mask_img
->data
: 0;
3708 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
3710 for (i
= 0; i
< height
; ++i
)
3713 for (k
= 0; k
< width
; ++k
)
3715 int idx
= i
* img
->ximg
->bytes_per_line
/4 + k
;
3716 int maskidx
= mid
? i
* img
->mask_img
->bytes_per_line
+ k
/8 : 0;
3717 int mask
= mid
? mid
[maskidx
] & (1 << (k
% 8)) : 1;
3719 if (mask
) od
[idx
] = id
[idx
] + 0xff000000; // ff => full alpha
3720 else od
[idx
] = bgcolor
;
3724 create_cairo_image_surface (img
, data
, width
, height
);
3728 rc
= XpmFileInvalid
;
3729 x_clear_image (f
, img
);
3732 #ifdef HAVE_X_WINDOWS
3733 if (rc
== XpmSuccess
)
3735 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3736 img
->ximg
->width
, img
->ximg
->height
,
3738 if (img
->pixmap
== NO_PIXMAP
)
3740 x_clear_image (f
, img
);
3743 else if (img
->mask_img
)
3745 img
->mask
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3746 img
->mask_img
->width
,
3747 img
->mask_img
->height
,
3748 img
->mask_img
->depth
);
3749 if (img
->mask
== NO_PIXMAP
)
3751 x_clear_image (f
, img
);
3757 #endif /* ! USE_CAIRO */
3759 if (rc
== XpmSuccess
)
3761 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3762 img
->colors
= colors_in_color_table (&img
->ncolors
);
3763 #else /* not ALLOC_XPM_COLORS */
3767 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3768 plus some duplicate attributes. */
3769 if (xpm_image
&& xpm_image
->bitmap
)
3771 img
->pixmap
= xpm_image
->bitmap
;
3772 /* XImageFree in libXpm frees XImage struct without destroying
3773 the bitmap, which is what we want. */
3774 XImageFree (xpm_image
);
3776 if (xpm_mask
&& xpm_mask
->bitmap
)
3778 /* The mask appears to be inverted compared with what we expect.
3779 TODO: invert our expectations. See other places where we
3780 have to invert bits because our idea of masks is backwards. */
3782 old_obj
= SelectObject (hdc
, xpm_mask
->bitmap
);
3784 PatBlt (hdc
, 0, 0, xpm_mask
->width
, xpm_mask
->height
, DSTINVERT
);
3785 SelectObject (hdc
, old_obj
);
3787 img
->mask
= xpm_mask
->bitmap
;
3788 XImageFree (xpm_mask
);
3793 #endif /* HAVE_NTGUI */
3795 /* Remember allocated colors. */
3796 img
->colors
= xnmalloc (attrs
.nalloc_pixels
, sizeof *img
->colors
);
3797 img
->ncolors
= attrs
.nalloc_pixels
;
3798 for (i
= 0; i
< attrs
.nalloc_pixels
; ++i
)
3800 img
->colors
[i
] = attrs
.alloc_pixels
[i
];
3801 #ifdef DEBUG_X_COLORS
3802 register_color (img
->colors
[i
]);
3805 #endif /* not ALLOC_XPM_COLORS */
3807 img
->width
= attrs
.width
;
3808 img
->height
= attrs
.height
;
3809 eassert (img
->width
> 0 && img
->height
> 0);
3811 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3812 XpmFreeAttributes (&attrs
);
3814 #ifdef HAVE_X_WINDOWS
3815 /* Maybe fill in the background field while we have ximg handy. */
3816 IMAGE_BACKGROUND (img
, f
, img
->ximg
);
3818 /* Fill in the background_transparent field while we have the
3820 image_background_transparent (img
, f
, img
->mask_img
);
3827 #endif /* HAVE_NTGUI */
3832 image_error ("Error opening XPM file (%s)", img
->spec
);
3835 case XpmFileInvalid
:
3836 image_error ("Invalid XPM file (%s)", img
->spec
);
3840 image_error ("Out of memory (%s)", img
->spec
);
3843 case XpmColorFailed
:
3844 image_error ("Color allocation error (%s)", img
->spec
);
3848 image_error ("Unknown error (%s)", img
->spec
);
3853 #ifdef ALLOC_XPM_COLORS
3854 xpm_free_color_cache ();
3857 return rc
== XpmSuccess
;
3860 #endif /* HAVE_XPM */
3862 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3864 /* XPM support functions for NS where libxpm is not available.
3865 Only XPM version 3 (without any extensions) is supported. */
3867 static void xpm_put_color_table_v (Lisp_Object
, const unsigned char *,
3869 static Lisp_Object
xpm_get_color_table_v (Lisp_Object
,
3870 const unsigned char *, int);
3871 static void xpm_put_color_table_h (Lisp_Object
, const unsigned char *,
3873 static Lisp_Object
xpm_get_color_table_h (Lisp_Object
,
3874 const unsigned char *, int);
3876 /* Tokens returned from xpm_scan. */
3885 /* Scan an XPM data and return a character (< 256) or a token defined
3886 by enum xpm_token above. *S and END are the start (inclusive) and
3887 the end (exclusive) addresses of the data, respectively. Advance
3888 *S while scanning. If token is either XPM_TK_IDENT or
3889 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3890 length of the corresponding token, respectively. */
3893 xpm_scan (const unsigned char **s
,
3894 const unsigned char *end
,
3895 const unsigned char **beg
,
3902 /* Skip white-space. */
3903 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
3906 /* gnus-pointer.xpm uses '-' in its identifier.
3907 sb-dir-plus.xpm uses '+' in its identifier. */
3908 if (c_isalpha (c
) || c
== '_' || c
== '-' || c
== '+')
3912 && (c
= **s
, c_isalnum (c
)
3913 || c
== '_' || c
== '-' || c
== '+'))
3916 return XPM_TK_IDENT
;
3921 while (*s
< end
&& **s
!= '"')
3926 return XPM_TK_STRING
;
3930 if (*s
< end
&& **s
== '*')
3932 /* C-style comment. */
3936 while (*s
< end
&& *(*s
)++ != '*')
3939 while (*s
< end
&& **s
!= '/');
3953 /* Functions for color table lookup in XPM data. A key is a string
3954 specifying the color of each pixel in XPM data. A value is either
3955 an integer that specifies a pixel color, Qt that specifies
3956 transparency, or Qnil for the unspecified color. If the length of
3957 the key string is one, a vector is used as a table. Otherwise, a
3958 hash table is used. */
3961 xpm_make_color_table_v (void (**put_func
) (Lisp_Object
,
3962 const unsigned char *,
3965 Lisp_Object (**get_func
) (Lisp_Object
,
3966 const unsigned char *,
3969 *put_func
= xpm_put_color_table_v
;
3970 *get_func
= xpm_get_color_table_v
;
3971 return Fmake_vector (make_number (256), Qnil
);
3975 xpm_put_color_table_v (Lisp_Object color_table
,
3976 const unsigned char *chars_start
,
3980 ASET (color_table
, *chars_start
, color
);
3984 xpm_get_color_table_v (Lisp_Object color_table
,
3985 const unsigned char *chars_start
,
3988 return AREF (color_table
, *chars_start
);
3992 xpm_make_color_table_h (void (**put_func
) (Lisp_Object
,
3993 const unsigned char *,
3996 Lisp_Object (**get_func
) (Lisp_Object
,
3997 const unsigned char *,
4000 *put_func
= xpm_put_color_table_h
;
4001 *get_func
= xpm_get_color_table_h
;
4002 return make_hash_table (hashtest_equal
, make_number (DEFAULT_HASH_SIZE
),
4003 make_float (DEFAULT_REHASH_SIZE
),
4004 make_float (DEFAULT_REHASH_THRESHOLD
),
4009 xpm_put_color_table_h (Lisp_Object color_table
,
4010 const unsigned char *chars_start
,
4014 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4015 EMACS_UINT hash_code
;
4016 Lisp_Object chars
= make_unibyte_string (chars_start
, chars_len
);
4018 hash_lookup (table
, chars
, &hash_code
);
4019 hash_put (table
, chars
, color
, hash_code
);
4023 xpm_get_color_table_h (Lisp_Object color_table
,
4024 const unsigned char *chars_start
,
4027 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4029 hash_lookup (table
, make_unibyte_string (chars_start
, chars_len
), NULL
);
4031 return i
>= 0 ? HASH_VALUE (table
, i
) : Qnil
;
4034 enum xpm_color_key
{
4042 static const char xpm_color_key_strings
[][4] = {"s", "m", "g4", "g", "c"};
4045 xpm_str_to_color_key (const char *s
)
4049 for (i
= 0; i
< ARRAYELTS (xpm_color_key_strings
); i
++)
4050 if (strcmp (xpm_color_key_strings
[i
], s
) == 0)
4056 xpm_load_image (struct frame
*f
,
4058 const unsigned char *contents
,
4059 const unsigned char *end
)
4061 const unsigned char *s
= contents
, *beg
, *str
;
4062 unsigned char buffer
[BUFSIZ
];
4063 int width
, height
, x
, y
;
4064 int num_colors
, chars_per_pixel
;
4067 void (*put_color_table
) (Lisp_Object
, const unsigned char *, int, Lisp_Object
);
4068 Lisp_Object (*get_color_table
) (Lisp_Object
, const unsigned char *, int);
4069 Lisp_Object frame
, color_symbols
, color_table
;
4071 bool have_mask
= false;
4072 XImagePtr ximg
= NULL
, mask_img
= NULL
;
4075 LA1 = xpm_scan (&s, end, &beg, &len)
4077 #define expect(TOKEN) \
4080 if (LA1 != (TOKEN)) \
4086 #define expect_ident(IDENT) \
4087 if (LA1 == XPM_TK_IDENT \
4088 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4093 if (!(end
- s
>= 9 && memcmp (s
, "/* XPM */", 9) == 0))
4097 expect_ident ("static");
4098 expect_ident ("char");
4100 expect (XPM_TK_IDENT
);
4105 expect (XPM_TK_STRING
);
4108 memcpy (buffer
, beg
, len
);
4110 if (sscanf (buffer
, "%d %d %d %d", &width
, &height
,
4111 &num_colors
, &chars_per_pixel
) != 4
4112 || width
<= 0 || height
<= 0
4113 || num_colors
<= 0 || chars_per_pixel
<= 0)
4116 if (!check_image_size (f
, width
, height
))
4118 image_size_error ();
4122 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0)
4124 || !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
4129 image_error ("Image too large");
4135 XSETFRAME (frame
, f
);
4136 if (!NILP (Fxw_display_color_p (frame
)))
4137 best_key
= XPM_COLOR_KEY_C
;
4138 else if (!NILP (Fx_display_grayscale_p (frame
)))
4139 best_key
= (XFASTINT (Fx_display_planes (frame
)) > 2
4140 ? XPM_COLOR_KEY_G
: XPM_COLOR_KEY_G4
);
4142 best_key
= XPM_COLOR_KEY_M
;
4144 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
4145 if (chars_per_pixel
== 1)
4146 color_table
= xpm_make_color_table_v (&put_color_table
,
4149 color_table
= xpm_make_color_table_h (&put_color_table
,
4152 while (num_colors
-- > 0)
4154 char *color
, *max_color
;
4155 int key
, next_key
, max_key
= 0;
4156 Lisp_Object symbol_color
= Qnil
, color_val
;
4159 expect (XPM_TK_STRING
);
4160 if (len
<= chars_per_pixel
|| len
>= BUFSIZ
+ chars_per_pixel
)
4162 memcpy (buffer
, beg
+ chars_per_pixel
, len
- chars_per_pixel
);
4163 buffer
[len
- chars_per_pixel
] = '\0';
4165 str
= strtok (buffer
, " \t");
4168 key
= xpm_str_to_color_key (str
);
4173 color
= strtok (NULL
, " \t");
4177 while ((str
= strtok (NULL
, " \t")) != NULL
)
4179 next_key
= xpm_str_to_color_key (str
);
4182 color
[strlen (color
)] = ' ';
4185 if (key
== XPM_COLOR_KEY_S
)
4187 if (NILP (symbol_color
))
4188 symbol_color
= build_string (color
);
4190 else if (max_key
< key
&& key
<= best_key
)
4200 if (!NILP (color_symbols
) && !NILP (symbol_color
))
4202 Lisp_Object specified_color
= Fassoc (symbol_color
, color_symbols
);
4204 if (CONSP (specified_color
) && STRINGP (XCDR (specified_color
)))
4206 if (xstrcasecmp (SSDATA (XCDR (specified_color
)), "None") == 0)
4208 else if (x_defined_color (f
, SSDATA (XCDR (specified_color
)),
4210 color_val
= make_number (cdef
.pixel
);
4213 if (NILP (color_val
) && max_key
> 0)
4215 if (xstrcasecmp (max_color
, "None") == 0)
4217 else if (x_defined_color (f
, max_color
, &cdef
, 0))
4218 color_val
= make_number (cdef
.pixel
);
4220 if (!NILP (color_val
))
4221 (*put_color_table
) (color_table
, beg
, chars_per_pixel
, color_val
);
4226 for (y
= 0; y
< height
; y
++)
4228 expect (XPM_TK_STRING
);
4230 if (len
< width
* chars_per_pixel
)
4232 for (x
= 0; x
< width
; x
++, str
+= chars_per_pixel
)
4234 Lisp_Object color_val
=
4235 (*get_color_table
) (color_table
, str
, chars_per_pixel
);
4237 XPutPixel (ximg
, x
, y
,
4238 (INTEGERP (color_val
) ? XINT (color_val
)
4239 : FRAME_FOREGROUND_PIXEL (f
)));
4241 XPutPixel (mask_img
, x
, y
,
4242 (!EQ (color_val
, Qt
) ? PIX_MASK_DRAW
4243 : (have_mask
= true, PIX_MASK_RETAIN
)));
4245 if (EQ (color_val
, Qt
))
4246 ns_set_alpha (ximg
, x
, y
, 0);
4254 img
->height
= height
;
4256 /* Maybe fill in the background field while we have ximg handy. */
4257 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
4258 IMAGE_BACKGROUND (img
, f
, ximg
);
4260 image_put_x_image (f
, img
, ximg
, 0);
4264 /* Fill in the background_transparent field while we have the
4266 image_background_transparent (img
, f
, mask_img
);
4268 image_put_x_image (f
, img
, mask_img
, 1);
4272 x_destroy_x_image (mask_img
);
4273 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4279 image_error ("Invalid XPM file (%s)", img
->spec
);
4280 x_destroy_x_image (ximg
);
4281 x_destroy_x_image (mask_img
);
4282 x_clear_image (f
, img
);
4291 xpm_load (struct frame
*f
,
4295 Lisp_Object file_name
;
4297 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4298 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
4299 if (STRINGP (file_name
))
4302 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
4303 if (!STRINGP (file
))
4305 image_error ("Cannot find image file `%s'", file_name
);
4310 unsigned char *contents
= slurp_file (fd
, &size
);
4311 if (contents
== NULL
)
4313 image_error ("Error loading XPM image `%s'", file
);
4317 success_p
= xpm_load_image (f
, img
, contents
, contents
+ size
);
4324 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
4325 if (!STRINGP (data
))
4327 image_error ("Invalid image data `%s'", data
);
4330 success_p
= xpm_load_image (f
, img
, SDATA (data
),
4331 SDATA (data
) + SBYTES (data
));
4337 #endif /* HAVE_NS && !HAVE_XPM */
4341 /***********************************************************************
4343 ***********************************************************************/
4345 #ifdef COLOR_TABLE_SUPPORT
4347 /* An entry in the color table mapping an RGB color to a pixel color. */
4352 unsigned long pixel
;
4354 /* Next in color table collision list. */
4355 struct ct_color
*next
;
4358 /* The bucket vector size to use. Must be prime. */
4362 /* Value is a hash of the RGB color given by R, G, and B. */
4365 ct_hash_rgb (unsigned r
, unsigned g
, unsigned b
)
4367 return (r
<< 16) ^ (g
<< 8) ^ b
;
4370 /* The color hash table. */
4372 static struct ct_color
**ct_table
;
4374 /* Number of entries in the color table. */
4376 static int ct_colors_allocated
;
4379 ct_colors_allocated_max
=
4381 min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof (unsigned long))
4384 /* Initialize the color table. */
4387 init_color_table (void)
4389 int size
= CT_SIZE
* sizeof (*ct_table
);
4390 ct_table
= xzalloc (size
);
4391 ct_colors_allocated
= 0;
4395 /* Free memory associated with the color table. */
4398 free_color_table (void)
4401 struct ct_color
*p
, *next
;
4403 for (i
= 0; i
< CT_SIZE
; ++i
)
4404 for (p
= ct_table
[i
]; p
; p
= next
)
4415 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4416 entry for that color already is in the color table, return the
4417 pixel color of that entry. Otherwise, allocate a new color for R,
4418 G, B, and make an entry in the color table. */
4420 static unsigned long
4421 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4423 unsigned hash
= ct_hash_rgb (r
, g
, b
);
4424 int i
= hash
% CT_SIZE
;
4426 Display_Info
*dpyinfo
;
4428 /* Handle TrueColor visuals specially, which improves performance by
4429 two orders of magnitude. Freeing colors on TrueColor visuals is
4430 a nop, and pixel colors specify RGB values directly. See also
4431 the Xlib spec, chapter 3.1. */
4432 dpyinfo
= FRAME_DISPLAY_INFO (f
);
4433 if (dpyinfo
->red_bits
> 0)
4435 unsigned long pr
, pg
, pb
;
4437 /* Apply gamma-correction like normal color allocation does. */
4441 color
.red
= r
, color
.green
= g
, color
.blue
= b
;
4442 gamma_correct (f
, &color
);
4443 r
= color
.red
, g
= color
.green
, b
= color
.blue
;
4446 /* Scale down RGB values to the visual's bits per RGB, and shift
4447 them to the right position in the pixel color. Note that the
4448 original RGB values are 16-bit values, as usual in X. */
4449 pr
= (r
>> (16 - dpyinfo
->red_bits
)) << dpyinfo
->red_offset
;
4450 pg
= (g
>> (16 - dpyinfo
->green_bits
)) << dpyinfo
->green_offset
;
4451 pb
= (b
>> (16 - dpyinfo
->blue_bits
)) << dpyinfo
->blue_offset
;
4453 /* Assemble the pixel color. */
4454 return pr
| pg
| pb
;
4457 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4458 if (p
->r
== r
&& p
->g
== g
&& p
->b
== b
)
4464 #ifdef HAVE_X_WINDOWS
4472 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4473 return FRAME_FOREGROUND_PIXEL (f
);
4475 #ifdef HAVE_X_WINDOWS
4480 cmap
= FRAME_X_COLORMAP (f
);
4481 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4484 ++ct_colors_allocated
;
4485 p
= xmalloc (sizeof *p
);
4489 p
->pixel
= color
.pixel
;
4490 p
->next
= ct_table
[i
];
4494 return FRAME_FOREGROUND_PIXEL (f
);
4498 color
= PALETTERGB (r
, g
, b
);
4500 color
= RGB_TO_ULONG (r
, g
, b
);
4501 #endif /* HAVE_NTGUI */
4502 ++ct_colors_allocated
;
4503 p
= xmalloc (sizeof *p
);
4508 p
->next
= ct_table
[i
];
4510 #endif /* HAVE_X_WINDOWS */
4518 /* Look up pixel color PIXEL which is used on frame F in the color
4519 table. If not already present, allocate it. Value is PIXEL. */
4521 static unsigned long
4522 lookup_pixel_color (struct frame
*f
, unsigned long pixel
)
4524 int i
= pixel
% CT_SIZE
;
4527 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4528 if (p
->pixel
== pixel
)
4537 if (ct_colors_allocated
>= ct_colors_allocated_max
)
4538 return FRAME_FOREGROUND_PIXEL (f
);
4540 #ifdef HAVE_X_WINDOWS
4541 cmap
= FRAME_X_COLORMAP (f
);
4542 color
.pixel
= pixel
;
4543 x_query_color (f
, &color
);
4544 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4547 cmap
= DefaultColormapOfScreen (FRAME_X_SCREEN (f
));
4548 color
.pixel
= pixel
;
4549 XQueryColor (NULL
, cmap
, &color
);
4550 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4552 #endif /* HAVE_X_WINDOWS */
4556 ++ct_colors_allocated
;
4558 p
= xmalloc (sizeof *p
);
4563 p
->next
= ct_table
[i
];
4567 return FRAME_FOREGROUND_PIXEL (f
);
4573 /* Value is a vector of all pixel colors contained in the color table,
4574 allocated via xmalloc. Set *N to the number of colors. */
4576 static unsigned long *
4577 colors_in_color_table (int *n
)
4581 unsigned long *colors
;
4583 if (ct_colors_allocated
== 0)
4590 colors
= xmalloc (ct_colors_allocated
* sizeof *colors
);
4591 *n
= ct_colors_allocated
;
4593 for (i
= j
= 0; i
< CT_SIZE
; ++i
)
4594 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4595 colors
[j
++] = p
->pixel
;
4601 #else /* COLOR_TABLE_SUPPORT */
4603 static unsigned long
4604 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4606 unsigned long pixel
;
4609 pixel
= PALETTERGB (r
>> 8, g
>> 8, b
>> 8);
4610 #endif /* HAVE_NTGUI */
4613 pixel
= RGB_TO_ULONG (r
>> 8, g
>> 8, b
>> 8);
4614 #endif /* HAVE_NS */
4619 init_color_table (void)
4622 #endif /* COLOR_TABLE_SUPPORT */
4625 /***********************************************************************
4627 ***********************************************************************/
4629 /* Edge detection matrices for different edge-detection
4632 static int emboss_matrix
[9] = {
4634 2, -1, 0, /* y - 1 */
4636 0, 1, -2 /* y + 1 */
4639 static int laplace_matrix
[9] = {
4641 1, 0, 0, /* y - 1 */
4643 0, 0, -1 /* y + 1 */
4646 /* Value is the intensity of the color whose red/green/blue values
4649 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4652 /* On frame F, return an array of XColor structures describing image
4653 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4654 means also fill the red/green/blue members of the XColor
4655 structures. Value is a pointer to the array of XColors structures,
4656 allocated with xmalloc; it must be freed by the caller. */
4659 x_to_xcolors (struct frame
*f
, struct image
*img
, bool rgb_p
)
4663 XImagePtr_or_DC ximg
;
4666 #endif /* HAVE_NTGUI */
4668 if (img
->height
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *colors
/ img
->width
)
4669 memory_full (SIZE_MAX
);
4670 colors
= xmalloc (sizeof *colors
* img
->width
* img
->height
);
4672 /* Get the X image or create a memory device context for IMG. */
4673 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4675 /* Fill the `pixel' members of the XColor array. I wished there
4676 were an easy and portable way to circumvent XGetPixel. */
4678 for (y
= 0; y
< img
->height
; ++y
)
4680 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4682 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4683 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4685 x_query_colors (f
, row
, img
->width
);
4689 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4691 /* W32_TODO: palette support needed here? */
4692 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4695 p
->red
= RED16_FROM_ULONG (p
->pixel
);
4696 p
->green
= GREEN16_FROM_ULONG (p
->pixel
);
4697 p
->blue
= BLUE16_FROM_ULONG (p
->pixel
);
4700 #endif /* HAVE_X_WINDOWS */
4703 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
4710 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4711 created with CreateDIBSection, with the pointer to the bit values
4712 stored in ximg->data. */
4715 XPutPixel (XImagePtr ximg
, int x
, int y
, COLORREF color
)
4717 int width
= ximg
->info
.bmiHeader
.biWidth
;
4718 unsigned char * pixel
;
4720 /* True color images. */
4721 if (ximg
->info
.bmiHeader
.biBitCount
== 24)
4723 int rowbytes
= width
* 3;
4724 /* Ensure scanlines are aligned on 4 byte boundaries. */
4726 rowbytes
+= 4 - (rowbytes
% 4);
4728 pixel
= ximg
->data
+ y
* rowbytes
+ x
* 3;
4729 /* Windows bitmaps are in BGR order. */
4730 *pixel
= GetBValue (color
);
4731 *(pixel
+ 1) = GetGValue (color
);
4732 *(pixel
+ 2) = GetRValue (color
);
4734 /* Monochrome images. */
4735 else if (ximg
->info
.bmiHeader
.biBitCount
== 1)
4737 int rowbytes
= width
/ 8;
4738 /* Ensure scanlines are aligned on 4 byte boundaries. */
4740 rowbytes
+= 4 - (rowbytes
% 4);
4741 pixel
= ximg
->data
+ y
* rowbytes
+ x
/ 8;
4742 /* Filter out palette info. */
4743 if (color
& 0x00ffffff)
4744 *pixel
= *pixel
| (1 << x
% 8);
4746 *pixel
= *pixel
& ~(1 << x
% 8);
4749 image_error ("XPutPixel: palette image not supported");
4752 #endif /* HAVE_NTGUI */
4754 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4755 RGB members are set. F is the frame on which this all happens.
4756 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4759 x_from_xcolors (struct frame
*f
, struct image
*img
, XColor
*colors
)
4762 XImagePtr oimg
= NULL
;
4765 init_color_table ();
4767 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_COLORS
);
4768 image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 0,
4771 for (y
= 0; y
< img
->height
; ++y
)
4772 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4774 unsigned long pixel
;
4775 pixel
= lookup_rgb_color (f
, p
->red
, p
->green
, p
->blue
);
4776 XPutPixel (oimg
, x
, y
, pixel
);
4781 image_put_x_image (f
, img
, oimg
, 0);
4782 #ifdef COLOR_TABLE_SUPPORT
4783 img
->colors
= colors_in_color_table (&img
->ncolors
);
4784 free_color_table ();
4785 #endif /* COLOR_TABLE_SUPPORT */
4789 /* On frame F, perform edge-detection on image IMG.
4791 MATRIX is a nine-element array specifying the transformation
4792 matrix. See emboss_matrix for an example.
4794 COLOR_ADJUST is a color adjustment added to each pixel of the
4798 x_detect_edges (struct frame
*f
, struct image
*img
, int *matrix
, int color_adjust
)
4800 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4804 for (i
= sum
= 0; i
< 9; ++i
)
4805 sum
+= eabs (matrix
[i
]);
4807 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4809 if (img
->height
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *new / img
->width
)
4810 memory_full (SIZE_MAX
);
4811 new = xmalloc (sizeof *new * img
->width
* img
->height
);
4813 for (y
= 0; y
< img
->height
; ++y
)
4815 p
= COLOR (new, 0, y
);
4816 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4817 p
= COLOR (new, img
->width
- 1, y
);
4818 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4821 for (x
= 1; x
< img
->width
- 1; ++x
)
4823 p
= COLOR (new, x
, 0);
4824 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4825 p
= COLOR (new, x
, img
->height
- 1);
4826 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4829 for (y
= 1; y
< img
->height
- 1; ++y
)
4831 p
= COLOR (new, 1, y
);
4833 for (x
= 1; x
< img
->width
- 1; ++x
, ++p
)
4835 int r
, g
, b
, yy
, xx
;
4838 for (yy
= y
- 1; yy
< y
+ 2; ++yy
)
4839 for (xx
= x
- 1; xx
< x
+ 2; ++xx
, ++i
)
4842 XColor
*t
= COLOR (colors
, xx
, yy
);
4843 r
+= matrix
[i
] * t
->red
;
4844 g
+= matrix
[i
] * t
->green
;
4845 b
+= matrix
[i
] * t
->blue
;
4848 r
= (r
/ sum
+ color_adjust
) & 0xffff;
4849 g
= (g
/ sum
+ color_adjust
) & 0xffff;
4850 b
= (b
/ sum
+ color_adjust
) & 0xffff;
4851 p
->red
= p
->green
= p
->blue
= COLOR_INTENSITY (r
, g
, b
);
4856 x_from_xcolors (f
, img
, new);
4862 /* Perform the pre-defined `emboss' edge-detection on image IMG
4866 x_emboss (struct frame
*f
, struct image
*img
)
4868 x_detect_edges (f
, img
, emboss_matrix
, 0xffff / 2);
4872 /* Transform image IMG which is used on frame F with a Laplace
4873 edge-detection algorithm. The result is an image that can be used
4874 to draw disabled buttons, for example. */
4877 x_laplace (struct frame
*f
, struct image
*img
)
4879 x_detect_edges (f
, img
, laplace_matrix
, 45000);
4883 /* Perform edge-detection on image IMG on frame F, with specified
4884 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4886 MATRIX must be either
4888 - a list of at least 9 numbers in row-major form
4889 - a vector of at least 9 numbers
4891 COLOR_ADJUST nil means use a default; otherwise it must be a
4895 x_edge_detection (struct frame
*f
, struct image
*img
, Lisp_Object matrix
,
4896 Lisp_Object color_adjust
)
4904 i
< 9 && CONSP (matrix
) && NUMBERP (XCAR (matrix
));
4905 ++i
, matrix
= XCDR (matrix
))
4906 trans
[i
] = XFLOATINT (XCAR (matrix
));
4908 else if (VECTORP (matrix
) && ASIZE (matrix
) >= 9)
4910 for (i
= 0; i
< 9 && NUMBERP (AREF (matrix
, i
)); ++i
)
4911 trans
[i
] = XFLOATINT (AREF (matrix
, i
));
4914 if (NILP (color_adjust
))
4915 color_adjust
= make_number (0xffff / 2);
4917 if (i
== 9 && NUMBERP (color_adjust
))
4918 x_detect_edges (f
, img
, trans
, XFLOATINT (color_adjust
));
4922 /* Transform image IMG on frame F so that it looks disabled. */
4925 x_disable_image (struct frame
*f
, struct image
*img
)
4927 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
4929 int n_planes
= dpyinfo
->n_planes
* dpyinfo
->n_cbits
;
4931 int n_planes
= dpyinfo
->n_planes
;
4932 #endif /* HAVE_NTGUI */
4936 /* Color (or grayscale). Convert to gray, and equalize. Just
4937 drawing such images with a stipple can look very odd, so
4938 we're using this method instead. */
4939 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4941 const int h
= 15000;
4942 const int l
= 30000;
4944 for (p
= colors
, end
= colors
+ img
->width
* img
->height
;
4948 int i
= COLOR_INTENSITY (p
->red
, p
->green
, p
->blue
);
4949 int i2
= (0xffff - h
- l
) * i
/ 0xffff + l
;
4950 p
->red
= p
->green
= p
->blue
= i2
;
4953 x_from_xcolors (f
, img
, colors
);
4956 /* Draw a cross over the disabled image, if we must or if we
4958 if (n_planes
< 2 || cross_disabled_images
)
4961 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4963 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4965 Display
*dpy
= FRAME_X_DISPLAY (f
);
4968 image_sync_to_pixmaps (f
, img
);
4969 gc
= XCreateGC (dpy
, img
->pixmap
, 0, NULL
);
4970 XSetForeground (dpy
, gc
, BLACK_PIX_DEFAULT (f
));
4971 XDrawLine (dpy
, img
->pixmap
, gc
, 0, 0,
4972 img
->width
- 1, img
->height
- 1);
4973 XDrawLine (dpy
, img
->pixmap
, gc
, 0, img
->height
- 1,
4979 gc
= XCreateGC (dpy
, img
->mask
, 0, NULL
);
4980 XSetForeground (dpy
, gc
, MaskForeground (f
));
4981 XDrawLine (dpy
, img
->mask
, gc
, 0, 0,
4982 img
->width
- 1, img
->height
- 1);
4983 XDrawLine (dpy
, img
->mask
, gc
, 0, img
->height
- 1,
4987 #endif /* !HAVE_NS */
4992 hdc
= get_frame_dc (f
);
4993 bmpdc
= CreateCompatibleDC (hdc
);
4994 release_frame_dc (f
, hdc
);
4996 prev
= SelectObject (bmpdc
, img
->pixmap
);
4998 SetTextColor (bmpdc
, BLACK_PIX_DEFAULT (f
));
4999 MoveToEx (bmpdc
, 0, 0, NULL
);
5000 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
5001 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
5002 LineTo (bmpdc
, img
->width
- 1, 0);
5006 SelectObject (bmpdc
, img
->mask
);
5007 SetTextColor (bmpdc
, WHITE_PIX_DEFAULT (f
));
5008 MoveToEx (bmpdc
, 0, 0, NULL
);
5009 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
5010 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
5011 LineTo (bmpdc
, img
->width
- 1, 0);
5013 SelectObject (bmpdc
, prev
);
5015 #endif /* HAVE_NTGUI */
5020 /* Build a mask for image IMG which is used on frame F. FILE is the
5021 name of an image file, for error messages. HOW determines how to
5022 determine the background color of IMG. If it is a list '(R G B)',
5023 with R, G, and B being integers >= 0, take that as the color of the
5024 background. Otherwise, determine the background color of IMG
5028 x_build_heuristic_mask (struct frame
*f
, struct image
*img
, Lisp_Object how
)
5030 XImagePtr_or_DC ximg
;
5037 #endif /* HAVE_NTGUI */
5039 bool use_img_background
;
5040 unsigned long bg
= 0;
5043 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
5047 /* Create an image and pixmap serving as mask. */
5048 if (! image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 1,
5051 #endif /* !HAVE_NS */
5053 /* Create the bit array serving as mask. */
5054 row_width
= (img
->width
+ 7) / 8;
5055 mask_img
= xzalloc (row_width
* img
->height
);
5056 #endif /* HAVE_NTGUI */
5058 /* Get the X image or create a memory device context for IMG. */
5059 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
5061 /* Determine the background color of ximg. If HOW is `(R G B)'
5062 take that as color. Otherwise, use the image's background color. */
5063 use_img_background
= 1;
5069 for (i
= 0; i
< 3 && CONSP (how
) && NATNUMP (XCAR (how
)); ++i
)
5071 rgb
[i
] = XFASTINT (XCAR (how
)) & 0xffff;
5075 if (i
== 3 && NILP (how
))
5077 char color_name
[30];
5078 sprintf (color_name
, "#%04x%04x%04x",
5079 rgb
[0] + 0u, rgb
[1] + 0u, rgb
[2] + 0u);
5082 0x00ffffff & /* Filter out palette info. */
5083 #endif /* HAVE_NTGUI */
5084 x_alloc_image_color (f
, img
, build_string (color_name
), 0));
5085 use_img_background
= 0;
5089 if (use_img_background
)
5090 bg
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
5092 /* Set all bits in mask_img to 1 whose color in ximg is different
5093 from the background color bg. */
5095 for (y
= 0; y
< img
->height
; ++y
)
5096 for (x
= 0; x
< img
->width
; ++x
)
5098 XPutPixel (mask_img
, x
, y
, (XGetPixel (ximg
, x
, y
) != bg
5099 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
));
5101 if (XGetPixel (ximg
, x
, y
) == bg
)
5102 ns_set_alpha (ximg
, x
, y
, 0);
5103 #endif /* HAVE_NS */
5105 /* Fill in the background_transparent field while we have the mask handy. */
5106 image_background_transparent (img
, f
, mask_img
);
5108 /* Put mask_img into the image. */
5109 image_put_x_image (f
, img
, mask_img
, 1);
5110 #endif /* !HAVE_NS */
5112 for (y
= 0; y
< img
->height
; ++y
)
5113 for (x
= 0; x
< img
->width
; ++x
)
5115 COLORREF p
= GetPixel (ximg
, x
, y
);
5117 mask_img
[y
* row_width
+ x
/ 8] |= 1 << (x
% 8);
5120 /* Create the mask image. */
5121 img
->mask
= w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
,
5123 /* Fill in the background_transparent field while we have the mask handy. */
5124 SelectObject (ximg
, img
->mask
);
5125 image_background_transparent (img
, f
, ximg
);
5127 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5129 #endif /* HAVE_NTGUI */
5131 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
5135 /***********************************************************************
5136 PBM (mono, gray, color)
5137 ***********************************************************************/
5139 static bool pbm_image_p (Lisp_Object object
);
5140 static bool pbm_load (struct frame
*f
, struct image
*img
);
5142 /* Indices of image specification fields in gs_format, below. */
5144 enum pbm_keyword_index
5160 /* Vector of image_keyword structures describing the format
5161 of valid user-defined image specifications. */
5163 static const struct image_keyword pbm_format
[PBM_LAST
] =
5165 {":type", IMAGE_SYMBOL_VALUE
, 1},
5166 {":file", IMAGE_STRING_VALUE
, 0},
5167 {":data", IMAGE_STRING_VALUE
, 0},
5168 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5169 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5170 {":relief", IMAGE_INTEGER_VALUE
, 0},
5171 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5172 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5173 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5174 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
5175 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5178 /* Structure describing the image type `pbm'. */
5180 static struct image_type pbm_type
=
5182 SYMBOL_INDEX (Qpbm
),
5191 /* Return true if OBJECT is a valid PBM image specification. */
5194 pbm_image_p (Lisp_Object object
)
5196 struct image_keyword fmt
[PBM_LAST
];
5198 memcpy (fmt
, pbm_format
, sizeof fmt
);
5200 if (!parse_image_spec (object
, fmt
, PBM_LAST
, Qpbm
))
5203 /* Must specify either :data or :file. */
5204 return fmt
[PBM_DATA
].count
+ fmt
[PBM_FILE
].count
== 1;
5208 /* Get next char skipping comments in Netpbm header. Returns -1 at
5212 pbm_next_char (unsigned char **s
, unsigned char *end
)
5216 while (*s
< end
&& (c
= *(*s
)++, c
== '#'))
5218 /* Skip to the next line break. */
5219 while (*s
< end
&& (c
= *(*s
)++, c
!= '\n' && c
!= '\r'))
5229 /* Scan a decimal number from *S and return it. Advance *S while
5230 reading the number. END is the end of the string. Value is -1 at
5234 pbm_scan_number (unsigned char **s
, unsigned char *end
)
5236 int c
= 0, val
= -1;
5238 /* Skip white-space. */
5239 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isspace (c
))
5244 /* Read decimal number. */
5246 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isdigit (c
))
5247 val
= 10 * val
+ c
- '0';
5254 /* Load PBM image IMG for use on frame F. */
5257 pbm_load (struct frame
*f
, struct image
*img
)
5261 int width
, height
, max_color_idx
= 0;
5262 Lisp_Object specified_file
;
5263 enum {PBM_MONO
, PBM_GRAY
, PBM_COLOR
} type
;
5264 unsigned char *contents
= NULL
;
5265 unsigned char *end
, *p
;
5267 unsigned char *data
= 0;
5273 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5275 if (STRINGP (specified_file
))
5278 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5279 if (!STRINGP (file
))
5281 image_error ("Cannot find image file `%s'", specified_file
);
5286 contents
= slurp_file (fd
, &size
);
5287 if (contents
== NULL
)
5289 image_error ("Error reading `%s'", file
);
5294 end
= contents
+ size
;
5299 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5300 if (!STRINGP (data
))
5302 image_error ("Invalid image data `%s'", data
);
5306 end
= p
+ SBYTES (data
);
5309 /* Check magic number. */
5310 if (end
- p
< 2 || *p
++ != 'P')
5312 image_error ("Not a PBM image: `%s'", img
->spec
);
5315 img
->pixmap
= NO_PIXMAP
;
5322 raw_p
= 0, type
= PBM_MONO
;
5326 raw_p
= 0, type
= PBM_GRAY
;
5330 raw_p
= 0, type
= PBM_COLOR
;
5334 raw_p
= 1, type
= PBM_MONO
;
5338 raw_p
= 1, type
= PBM_GRAY
;
5342 raw_p
= 1, type
= PBM_COLOR
;
5346 image_error ("Not a PBM image: `%s'", img
->spec
);
5350 /* Read width, height, maximum color-component. Characters
5351 starting with `#' up to the end of a line are ignored. */
5352 width
= pbm_scan_number (&p
, end
);
5353 height
= pbm_scan_number (&p
, end
);
5356 data
= (unsigned char *) xmalloc (width
* height
* 4);
5357 dataptr
= (uint32_t *) data
;
5360 if (type
!= PBM_MONO
)
5362 max_color_idx
= pbm_scan_number (&p
, end
);
5363 if (max_color_idx
> 65535 || max_color_idx
< 0)
5365 image_error ("Unsupported maximum PBM color value");
5370 if (!check_image_size (f
, width
, height
))
5372 image_size_error ();
5377 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5381 /* Initialize the color hash table. */
5382 init_color_table ();
5384 if (type
== PBM_MONO
)
5387 struct image_keyword fmt
[PBM_LAST
];
5388 unsigned long fg
= FRAME_FOREGROUND_PIXEL (f
);
5389 unsigned long bg
= FRAME_BACKGROUND_PIXEL (f
);
5394 /* Parse the image specification. */
5395 memcpy (fmt
, pbm_format
, sizeof fmt
);
5396 parse_image_spec (img
->spec
, fmt
, PBM_LAST
, Qpbm
);
5398 /* Get foreground and background colors, maybe allocate colors. */
5400 if (! fmt
[PBM_FOREGROUND
].count
5401 || ! STRINGP (fmt
[PBM_FOREGROUND
].value
)
5402 || ! x_defined_color (f
, SSDATA (fmt
[PBM_FOREGROUND
].value
), &xfg
, 0))
5405 x_query_color (f
, &xfg
);
5407 fga32
= xcolor_to_argb32 (xfg
);
5409 if (! fmt
[PBM_BACKGROUND
].count
5410 || ! STRINGP (fmt
[PBM_BACKGROUND
].value
)
5411 || ! x_defined_color (f
, SSDATA (fmt
[PBM_BACKGROUND
].value
), &xbg
, 0))
5414 x_query_color (f
, &xbg
);
5416 bga32
= xcolor_to_argb32 (xbg
);
5418 if (fmt
[PBM_FOREGROUND
].count
5419 && STRINGP (fmt
[PBM_FOREGROUND
].value
))
5420 fg
= x_alloc_image_color (f
, img
, fmt
[PBM_FOREGROUND
].value
, fg
);
5421 if (fmt
[PBM_BACKGROUND
].count
5422 && STRINGP (fmt
[PBM_BACKGROUND
].value
))
5424 bg
= x_alloc_image_color (f
, img
, fmt
[PBM_BACKGROUND
].value
, bg
);
5425 img
->background
= bg
;
5426 img
->background_valid
= 1;
5430 for (y
= 0; y
< height
; ++y
)
5431 for (x
= 0; x
< width
; ++x
)
5442 x_destroy_x_image (ximg
);
5444 x_clear_image (f
, img
);
5445 image_error ("Invalid image size in image `%s'",
5455 g
= pbm_scan_number (&p
, end
);
5458 *dataptr
++ = g
? fga32
: bga32
;
5460 XPutPixel (ximg
, x
, y
, g
? fg
: bg
);
5466 int expected_size
= height
* width
;
5467 if (max_color_idx
> 255)
5469 if (type
== PBM_COLOR
)
5472 if (raw_p
&& p
+ expected_size
> end
)
5477 x_destroy_x_image (ximg
);
5479 x_clear_image (f
, img
);
5480 image_error ("Invalid image size in image `%s'", img
->spec
);
5484 for (y
= 0; y
< height
; ++y
)
5485 for (x
= 0; x
< width
; ++x
)
5489 if (type
== PBM_GRAY
&& raw_p
)
5492 if (max_color_idx
> 255)
5493 r
= g
= b
= r
* 256 + *p
++;
5495 else if (type
== PBM_GRAY
)
5496 r
= g
= b
= pbm_scan_number (&p
, end
);
5500 if (max_color_idx
> 255)
5503 if (max_color_idx
> 255)
5506 if (max_color_idx
> 255)
5511 r
= pbm_scan_number (&p
, end
);
5512 g
= pbm_scan_number (&p
, end
);
5513 b
= pbm_scan_number (&p
, end
);
5516 if (r
< 0 || g
< 0 || b
< 0)
5521 x_destroy_x_image (ximg
);
5523 image_error ("Invalid pixel value in image `%s'", img
->spec
);
5528 r
= (double) r
* 255 / max_color_idx
;
5529 g
= (double) g
* 255 / max_color_idx
;
5530 b
= (double) b
* 255 / max_color_idx
;
5531 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
5533 /* RGB values are now in the range 0..max_color_idx.
5534 Scale this to the range 0..0xffff supported by X. */
5535 r
= (double) r
* 65535 / max_color_idx
;
5536 g
= (double) g
* 65535 / max_color_idx
;
5537 b
= (double) b
* 65535 / max_color_idx
;
5538 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5543 #ifdef COLOR_TABLE_SUPPORT
5544 /* Store in IMG->colors the colors allocated for the image, and
5545 free the color table. */
5546 img
->colors
= colors_in_color_table (&img
->ncolors
);
5547 free_color_table ();
5548 #endif /* COLOR_TABLE_SUPPORT */
5551 img
->height
= height
;
5553 /* Maybe fill in the background field while we have ximg handy. */
5556 create_cairo_image_surface (img
, data
, width
, height
);
5558 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
5559 /* Casting avoids a GCC warning. */
5560 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
5562 /* Put ximg into the image. */
5563 image_put_x_image (f
, img
, ximg
, 0);
5566 /* X and W32 versions did it here, MAC version above. ++kfs
5568 img->height = height; */
5575 /***********************************************************************
5577 ***********************************************************************/
5579 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5581 /* Function prototypes. */
5583 static bool png_image_p (Lisp_Object object
);
5584 static bool png_load (struct frame
*f
, struct image
*img
);
5586 /* Indices of image specification fields in png_format, below. */
5588 enum png_keyword_index
5603 /* Vector of image_keyword structures describing the format
5604 of valid user-defined image specifications. */
5606 static const struct image_keyword png_format
[PNG_LAST
] =
5608 {":type", IMAGE_SYMBOL_VALUE
, 1},
5609 {":data", IMAGE_STRING_VALUE
, 0},
5610 {":file", IMAGE_STRING_VALUE
, 0},
5611 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5612 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5613 {":relief", IMAGE_INTEGER_VALUE
, 0},
5614 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5615 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5616 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5617 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5620 #if defined HAVE_NTGUI && defined WINDOWSNT
5621 static bool init_png_functions (void);
5623 #define init_png_functions NULL
5626 /* Structure describing the image type `png'. */
5628 static struct image_type png_type
=
5630 SYMBOL_INDEX (Qpng
),
5638 /* Return true if OBJECT is a valid PNG image specification. */
5641 png_image_p (Lisp_Object object
)
5643 struct image_keyword fmt
[PNG_LAST
];
5644 memcpy (fmt
, png_format
, sizeof fmt
);
5646 if (!parse_image_spec (object
, fmt
, PNG_LAST
, Qpng
))
5649 /* Must specify either the :data or :file keyword. */
5650 return fmt
[PNG_FILE
].count
+ fmt
[PNG_DATA
].count
== 1;
5653 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5656 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5659 /* PNG library details. */
5661 DEF_DLL_FN (png_voidp
, png_get_io_ptr
, (png_structp
));
5662 DEF_DLL_FN (int, png_sig_cmp
, (png_bytep
, png_size_t
, png_size_t
));
5663 DEF_DLL_FN (png_structp
, png_create_read_struct
,
5664 (png_const_charp
, png_voidp
, png_error_ptr
, png_error_ptr
));
5665 DEF_DLL_FN (png_infop
, png_create_info_struct
, (png_structp
));
5666 DEF_DLL_FN (void, png_destroy_read_struct
,
5667 (png_structpp
, png_infopp
, png_infopp
));
5668 DEF_DLL_FN (void, png_set_read_fn
, (png_structp
, png_voidp
, png_rw_ptr
));
5669 DEF_DLL_FN (void, png_set_sig_bytes
, (png_structp
, int));
5670 DEF_DLL_FN (void, png_read_info
, (png_structp
, png_infop
));
5671 DEF_DLL_FN (png_uint_32
, png_get_IHDR
,
5672 (png_structp
, png_infop
, png_uint_32
*, png_uint_32
*,
5673 int *, int *, int *, int *, int *));
5674 DEF_DLL_FN (png_uint_32
, png_get_valid
, (png_structp
, png_infop
, png_uint_32
));
5675 DEF_DLL_FN (void, png_set_strip_16
, (png_structp
));
5676 DEF_DLL_FN (void, png_set_expand
, (png_structp
));
5677 DEF_DLL_FN (void, png_set_gray_to_rgb
, (png_structp
));
5678 DEF_DLL_FN (void, png_set_background
,
5679 (png_structp
, png_color_16p
, int, int, double));
5680 DEF_DLL_FN (png_uint_32
, png_get_bKGD
,
5681 (png_structp
, png_infop
, png_color_16p
*));
5682 DEF_DLL_FN (void, png_read_update_info
, (png_structp
, png_infop
));
5683 DEF_DLL_FN (png_byte
, png_get_channels
, (png_structp
, png_infop
));
5684 DEF_DLL_FN (png_size_t
, png_get_rowbytes
, (png_structp
, png_infop
));
5685 DEF_DLL_FN (void, png_read_image
, (png_structp
, png_bytepp
));
5686 DEF_DLL_FN (void, png_read_end
, (png_structp
, png_infop
));
5687 DEF_DLL_FN (void, png_error
, (png_structp
, png_const_charp
));
5689 # if (PNG_LIBPNG_VER >= 10500)
5690 DEF_DLL_FN (void, png_longjmp
, (png_structp
, int)) PNG_NORETURN
;
5691 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn
,
5692 (png_structp
, png_longjmp_ptr
, size_t));
5693 # endif /* libpng version >= 1.5 */
5696 init_png_functions (void)
5700 if (!(library
= w32_delayed_load (Qpng
)))
5703 LOAD_DLL_FN (library
, png_get_io_ptr
);
5704 LOAD_DLL_FN (library
, png_sig_cmp
);
5705 LOAD_DLL_FN (library
, png_create_read_struct
);
5706 LOAD_DLL_FN (library
, png_create_info_struct
);
5707 LOAD_DLL_FN (library
, png_destroy_read_struct
);
5708 LOAD_DLL_FN (library
, png_set_read_fn
);
5709 LOAD_DLL_FN (library
, png_set_sig_bytes
);
5710 LOAD_DLL_FN (library
, png_read_info
);
5711 LOAD_DLL_FN (library
, png_get_IHDR
);
5712 LOAD_DLL_FN (library
, png_get_valid
);
5713 LOAD_DLL_FN (library
, png_set_strip_16
);
5714 LOAD_DLL_FN (library
, png_set_expand
);
5715 LOAD_DLL_FN (library
, png_set_gray_to_rgb
);
5716 LOAD_DLL_FN (library
, png_set_background
);
5717 LOAD_DLL_FN (library
, png_get_bKGD
);
5718 LOAD_DLL_FN (library
, png_read_update_info
);
5719 LOAD_DLL_FN (library
, png_get_channels
);
5720 LOAD_DLL_FN (library
, png_get_rowbytes
);
5721 LOAD_DLL_FN (library
, png_read_image
);
5722 LOAD_DLL_FN (library
, png_read_end
);
5723 LOAD_DLL_FN (library
, png_error
);
5725 # if (PNG_LIBPNG_VER >= 10500)
5726 LOAD_DLL_FN (library
, png_longjmp
);
5727 LOAD_DLL_FN (library
, png_set_longjmp_fn
);
5728 # endif /* libpng version >= 1.5 */
5733 # undef png_create_info_struct
5734 # undef png_create_read_struct
5735 # undef png_destroy_read_struct
5737 # undef png_get_bKGD
5738 # undef png_get_channels
5739 # undef png_get_IHDR
5740 # undef png_get_io_ptr
5741 # undef png_get_rowbytes
5742 # undef png_get_valid
5744 # undef png_read_end
5745 # undef png_read_image
5746 # undef png_read_info
5747 # undef png_read_update_info
5748 # undef png_set_background
5749 # undef png_set_expand
5750 # undef png_set_gray_to_rgb
5751 # undef png_set_longjmp_fn
5752 # undef png_set_read_fn
5753 # undef png_set_sig_bytes
5754 # undef png_set_strip_16
5757 # define png_create_info_struct fn_png_create_info_struct
5758 # define png_create_read_struct fn_png_create_read_struct
5759 # define png_destroy_read_struct fn_png_destroy_read_struct
5760 # define png_error fn_png_error
5761 # define png_get_bKGD fn_png_get_bKGD
5762 # define png_get_channels fn_png_get_channels
5763 # define png_get_IHDR fn_png_get_IHDR
5764 # define png_get_io_ptr fn_png_get_io_ptr
5765 # define png_get_rowbytes fn_png_get_rowbytes
5766 # define png_get_valid fn_png_get_valid
5767 # define png_longjmp fn_png_longjmp
5768 # define png_read_end fn_png_read_end
5769 # define png_read_image fn_png_read_image
5770 # define png_read_info fn_png_read_info
5771 # define png_read_update_info fn_png_read_update_info
5772 # define png_set_background fn_png_set_background
5773 # define png_set_expand fn_png_set_expand
5774 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5775 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5776 # define png_set_read_fn fn_png_set_read_fn
5777 # define png_set_sig_bytes fn_png_set_sig_bytes
5778 # define png_set_strip_16 fn_png_set_strip_16
5779 # define png_sig_cmp fn_png_sig_cmp
5781 # endif /* WINDOWSNT */
5783 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5784 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5785 Do not use sys_setjmp, as PNG supports only jmp_buf.
5786 It's OK if the longjmp substitute restores the signal mask. */
5787 # ifdef HAVE__SETJMP
5788 # define FAST_SETJMP(j) _setjmp (j)
5789 # define FAST_LONGJMP _longjmp
5791 # define FAST_SETJMP(j) setjmp (j)
5792 # define FAST_LONGJMP longjmp
5795 # if PNG_LIBPNG_VER < 10500
5796 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5797 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5799 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5800 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5801 # define PNG_JMPBUF(ptr) \
5802 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5805 /* Error and warning handlers installed when the PNG library
5808 static _Noreturn
void
5809 my_png_error (png_struct
*png_ptr
, const char *msg
)
5811 eassert (png_ptr
!= NULL
);
5812 /* Avoid compiler warning about deprecated direct access to
5813 png_ptr's fields in libpng versions 1.4.x. */
5814 image_error ("PNG error: %s", build_string (msg
));
5815 PNG_LONGJMP (png_ptr
);
5820 my_png_warning (png_struct
*png_ptr
, const char *msg
)
5822 eassert (png_ptr
!= NULL
);
5823 image_error ("PNG warning: %s", build_string (msg
));
5826 /* Memory source for PNG decoding. */
5828 struct png_memory_storage
5830 unsigned char *bytes
; /* The data */
5831 ptrdiff_t len
; /* How big is it? */
5832 ptrdiff_t index
; /* Where are we? */
5836 /* Function set as reader function when reading PNG image from memory.
5837 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5838 bytes from the input to DATA. */
5841 png_read_from_memory (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5843 struct png_memory_storage
*tbr
= png_get_io_ptr (png_ptr
);
5845 if (length
> tbr
->len
- tbr
->index
)
5846 png_error (png_ptr
, "Read error");
5848 memcpy (data
, tbr
->bytes
+ tbr
->index
, length
);
5849 tbr
->index
= tbr
->index
+ length
;
5853 /* Function set as reader function when reading PNG image from a file.
5854 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5855 bytes from the input to DATA. */
5858 png_read_from_file (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5860 FILE *fp
= png_get_io_ptr (png_ptr
);
5862 if (fread (data
, 1, length
, fp
) < length
)
5863 png_error (png_ptr
, "Read error");
5867 /* Load PNG image IMG for use on frame F. Value is true if
5870 struct png_load_context
5872 /* These are members so that longjmp doesn't munge local variables. */
5873 png_struct
*png_ptr
;
5882 png_load_body (struct frame
*f
, struct image
*img
, struct png_load_context
*c
)
5884 Lisp_Object specified_file
;
5885 Lisp_Object specified_data
;
5888 png_struct
*png_ptr
;
5889 png_info
*info_ptr
= NULL
, *end_info
= NULL
;
5892 png_byte
*pixels
= NULL
;
5893 png_byte
**rows
= NULL
;
5894 png_uint_32 width
, height
;
5895 int bit_depth
, color_type
, interlace_type
;
5897 png_uint_32 row_bytes
;
5899 struct png_memory_storage tbr
; /* Data to be read */
5902 unsigned char *data
= 0;
5905 XImagePtr ximg
, mask_img
= NULL
;
5908 /* Find out what file to load. */
5909 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5910 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5911 IF_LINT (Lisp_Object
volatile specified_data_volatile
= specified_data
);
5913 if (NILP (specified_data
))
5916 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5917 if (!STRINGP (file
))
5919 image_error ("Cannot find image file `%s'", specified_file
);
5923 /* Open the image file. */
5924 fp
= fdopen (fd
, "rb");
5927 image_error ("Cannot open image file `%s'", file
);
5931 /* Check PNG signature. */
5932 if (fread (sig
, 1, sizeof sig
, fp
) != sizeof sig
5933 || png_sig_cmp (sig
, 0, sizeof sig
))
5936 image_error ("Not a PNG file: `%s'", file
);
5942 if (!STRINGP (specified_data
))
5944 image_error ("Invalid image data `%s'", specified_data
);
5948 /* Read from memory. */
5949 tbr
.bytes
= SDATA (specified_data
);
5950 tbr
.len
= SBYTES (specified_data
);
5953 /* Check PNG signature. */
5954 if (tbr
.len
< sizeof sig
5955 || png_sig_cmp (tbr
.bytes
, 0, sizeof sig
))
5957 image_error ("Not a PNG image: `%s'", img
->spec
);
5961 /* Need to skip past the signature. */
5962 tbr
.bytes
+= sizeof (sig
);
5965 /* Initialize read and info structs for PNG lib. */
5966 png_ptr
= png_create_read_struct (PNG_LIBPNG_VER_STRING
,
5971 info_ptr
= png_create_info_struct (png_ptr
);
5972 end_info
= png_create_info_struct (png_ptr
);
5975 c
->png_ptr
= png_ptr
;
5976 c
->info_ptr
= info_ptr
;
5977 c
->end_info
= end_info
;
5982 if (! (info_ptr
&& end_info
))
5984 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5989 if (fp
) fclose (fp
);
5993 /* Set error jump-back. We come back here when the PNG library
5994 detects an error. */
5995 if (FAST_SETJMP (PNG_JMPBUF (png_ptr
)))
5999 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6007 /* Silence a bogus diagnostic; see GCC bug 54561. */
6008 IF_LINT (fp
= c
->fp
);
6009 IF_LINT (specified_data
= specified_data_volatile
);
6011 /* Read image info. */
6012 if (!NILP (specified_data
))
6013 png_set_read_fn (png_ptr
, &tbr
, png_read_from_memory
);
6015 png_set_read_fn (png_ptr
, fp
, png_read_from_file
);
6017 png_set_sig_bytes (png_ptr
, sizeof sig
);
6018 png_read_info (png_ptr
, info_ptr
);
6019 png_get_IHDR (png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
,
6020 &interlace_type
, NULL
, NULL
);
6022 if (! (width
<= INT_MAX
&& height
<= INT_MAX
6023 && check_image_size (f
, width
, height
)))
6025 image_size_error ();
6030 /* Create the X image and pixmap now, so that the work below can be
6031 omitted if the image is too large for X. */
6032 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6036 /* If image contains simply transparency data, we prefer to
6037 construct a clipping mask. */
6038 if (png_get_valid (png_ptr
, info_ptr
, PNG_INFO_tRNS
))
6043 /* This function is easier to write if we only have to handle
6044 one data format: RGB or RGBA with 8 bits per channel. Let's
6045 transform other formats into that format. */
6047 /* Strip more than 8 bits per channel. */
6048 if (bit_depth
== 16)
6049 png_set_strip_16 (png_ptr
);
6051 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6053 png_set_expand (png_ptr
);
6055 /* Convert grayscale images to RGB. */
6056 if (color_type
== PNG_COLOR_TYPE_GRAY
6057 || color_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
6058 png_set_gray_to_rgb (png_ptr
);
6060 /* Handle alpha channel by combining the image with a background
6061 color. Do this only if a real alpha channel is supplied. For
6062 simple transparency, we prefer a clipping mask. */
6065 /* png_color_16 *image_bg; */
6066 Lisp_Object specified_bg
6067 = image_spec_value (img
->spec
, QCbackground
, NULL
);
6070 /* If the user specified a color, try to use it; if not, use the
6071 current frame background, ignoring any default background
6072 color set by the image. */
6073 if (STRINGP (specified_bg
)
6074 ? x_defined_color (f
, SSDATA (specified_bg
), &color
, false)
6075 : (x_query_frame_background_color (f
, &color
), true))
6076 /* The user specified `:background', use that. */
6078 int shift
= bit_depth
== 16 ? 0 : 8;
6079 png_color_16 bg
= { 0 };
6080 bg
.red
= color
.red
>> shift
;
6081 bg
.green
= color
.green
>> shift
;
6082 bg
.blue
= color
.blue
>> shift
;
6084 png_set_background (png_ptr
, &bg
,
6085 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
6089 /* Update info structure. */
6090 png_read_update_info (png_ptr
, info_ptr
);
6092 /* Get number of channels. Valid values are 1 for grayscale images
6093 and images with a palette, 2 for grayscale images with transparency
6094 information (alpha channel), 3 for RGB images, and 4 for RGB
6095 images with alpha channel, i.e. RGBA. If conversions above were
6096 sufficient we should only have 3 or 4 channels here. */
6097 channels
= png_get_channels (png_ptr
, info_ptr
);
6098 eassert (channels
== 3 || channels
== 4);
6100 /* Number of bytes needed for one row of the image. */
6101 row_bytes
= png_get_rowbytes (png_ptr
, info_ptr
);
6103 /* Allocate memory for the image. */
6104 if (height
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *rows
6105 || row_bytes
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *pixels
/ height
)
6106 memory_full (SIZE_MAX
);
6107 c
->pixels
= pixels
= xmalloc (sizeof *pixels
* row_bytes
* height
);
6108 c
->rows
= rows
= xmalloc (height
* sizeof *rows
);
6109 for (i
= 0; i
< height
; ++i
)
6110 rows
[i
] = pixels
+ i
* row_bytes
;
6112 /* Read the entire image. */
6113 png_read_image (png_ptr
, rows
);
6114 png_read_end (png_ptr
, info_ptr
);
6122 data
= (unsigned char *) xmalloc (width
* height
* 4);
6123 dataptr
= (uint32_t *) data
;
6125 /* Create an image and pixmap serving as mask if the PNG image
6126 contains an alpha channel. */
6129 && !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
6132 x_destroy_x_image (ximg
);
6133 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
);
6138 /* Fill the X image and mask from PNG data. */
6139 init_color_table ();
6141 for (y
= 0; y
< height
; ++y
)
6143 png_byte
*p
= rows
[y
];
6145 for (x
= 0; x
< width
; ++x
)
6154 if (channels
== 4) a
= *p
++;
6155 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
6160 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
6161 /* An alpha channel, aka mask channel, associates variable
6162 transparency with an image. Where other image formats
6163 support binary transparency---fully transparent or fully
6164 opaque---PNG allows up to 254 levels of partial transparency.
6165 The PNG library implements partial transparency by combining
6166 the image with a specified background color.
6168 I'm not sure how to handle this here nicely: because the
6169 background on which the image is displayed may change, for
6170 real alpha channel support, it would be necessary to create
6171 a new image for each possible background.
6173 What I'm doing now is that a mask is created if we have
6174 boolean transparency information. Otherwise I'm using
6175 the frame's background color to combine the image with. */
6180 XPutPixel (mask_img
, x
, y
, *p
> 0 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
);
6187 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6188 /* Set IMG's background color from the PNG image, unless the user
6192 if (png_get_bKGD (png_ptr
, info_ptr
, &bg
))
6194 img
->background
= lookup_rgb_color (f
, bg
->red
, bg
->green
, bg
->blue
);
6195 img
->background_valid
= 1;
6199 # ifdef COLOR_TABLE_SUPPORT
6200 /* Remember colors allocated for this image. */
6201 img
->colors
= colors_in_color_table (&img
->ncolors
);
6202 free_color_table ();
6203 # endif /* COLOR_TABLE_SUPPORT */
6206 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6211 img
->height
= height
;
6214 create_cairo_image_surface (img
, data
, width
, height
);
6216 /* Maybe fill in the background field while we have ximg handy.
6217 Casting avoids a GCC warning. */
6218 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6220 /* Put ximg into the image. */
6221 image_put_x_image (f
, img
, ximg
, 0);
6223 /* Same for the mask. */
6226 /* Fill in the background_transparent field while we have the
6227 mask handy. Casting avoids a GCC warning. */
6228 image_background_transparent (img
, f
, (XImagePtr_or_DC
)mask_img
);
6230 image_put_x_image (f
, img
, mask_img
, 1);
6238 png_load (struct frame
*f
, struct image
*img
)
6240 struct png_load_context c
;
6241 return png_load_body (f
, img
, &c
);
6244 #elif defined HAVE_NS
6247 png_load (struct frame
*f
, struct image
*img
)
6249 return ns_load_image (f
, img
,
6250 image_spec_value (img
->spec
, QCfile
, NULL
),
6251 image_spec_value (img
->spec
, QCdata
, NULL
));
6255 #endif /* HAVE_NS */
6259 /***********************************************************************
6261 ***********************************************************************/
6263 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6265 static bool jpeg_image_p (Lisp_Object object
);
6266 static bool jpeg_load (struct frame
*f
, struct image
*img
);
6268 /* Indices of image specification fields in gs_format, below. */
6270 enum jpeg_keyword_index
6279 JPEG_HEURISTIC_MASK
,
6285 /* Vector of image_keyword structures describing the format
6286 of valid user-defined image specifications. */
6288 static const struct image_keyword jpeg_format
[JPEG_LAST
] =
6290 {":type", IMAGE_SYMBOL_VALUE
, 1},
6291 {":data", IMAGE_STRING_VALUE
, 0},
6292 {":file", IMAGE_STRING_VALUE
, 0},
6293 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6294 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6295 {":relief", IMAGE_INTEGER_VALUE
, 0},
6296 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6297 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6298 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6299 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
6302 #if defined HAVE_NTGUI && defined WINDOWSNT
6303 static bool init_jpeg_functions (void);
6305 #define init_jpeg_functions NULL
6308 /* Structure describing the image type `jpeg'. */
6310 static struct image_type jpeg_type
=
6312 SYMBOL_INDEX (Qjpeg
),
6316 init_jpeg_functions
,
6320 /* Return true if OBJECT is a valid JPEG image specification. */
6323 jpeg_image_p (Lisp_Object object
)
6325 struct image_keyword fmt
[JPEG_LAST
];
6327 memcpy (fmt
, jpeg_format
, sizeof fmt
);
6329 if (!parse_image_spec (object
, fmt
, JPEG_LAST
, Qjpeg
))
6332 /* Must specify either the :data or :file keyword. */
6333 return fmt
[JPEG_FILE
].count
+ fmt
[JPEG_DATA
].count
== 1;
6336 #endif /* HAVE_JPEG || HAVE_NS */
6340 /* Work around a warning about HAVE_STDLIB_H being redefined in
6342 # ifdef HAVE_STDLIB_H
6343 # undef HAVE_STDLIB_H
6346 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6347 /* In older releases of the jpeg library, jpeglib.h will define boolean
6348 differently depending on __WIN32__, so make sure it is defined. */
6349 # define __WIN32__ 1
6352 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6353 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6354 using the Windows boolean type instead of the jpeglib boolean type
6355 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6356 headers are included along with windows.h, so under Cygwin, jpeglib
6357 attempts to define a conflicting boolean type. Worse, forcing
6358 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6359 because it created an ABI incompatibility between the
6360 already-compiled jpeg library and the header interface definition.
6362 The best we can do is to define jpeglib's boolean type to a
6363 different name. This name, jpeg_boolean, remains in effect through
6364 the rest of image.c.
6366 # if defined CYGWIN && defined HAVE_NTGUI
6367 # define boolean jpeg_boolean
6369 # include <jpeglib.h>
6370 # include <jerror.h>
6374 /* JPEG library details. */
6375 DEF_DLL_FN (void, jpeg_CreateDecompress
, (j_decompress_ptr
, int, size_t));
6376 DEF_DLL_FN (boolean
, jpeg_start_decompress
, (j_decompress_ptr
));
6377 DEF_DLL_FN (boolean
, jpeg_finish_decompress
, (j_decompress_ptr
));
6378 DEF_DLL_FN (void, jpeg_destroy_decompress
, (j_decompress_ptr
));
6379 DEF_DLL_FN (int, jpeg_read_header
, (j_decompress_ptr
, boolean
));
6380 DEF_DLL_FN (JDIMENSION
, jpeg_read_scanlines
,
6381 (j_decompress_ptr
, JSAMPARRAY
, JDIMENSION
));
6382 DEF_DLL_FN (struct jpeg_error_mgr
*, jpeg_std_error
,
6383 (struct jpeg_error_mgr
*));
6384 DEF_DLL_FN (boolean
, jpeg_resync_to_restart
, (j_decompress_ptr
, int));
6387 init_jpeg_functions (void)
6391 if (!(library
= w32_delayed_load (Qjpeg
)))
6394 LOAD_DLL_FN (library
, jpeg_finish_decompress
);
6395 LOAD_DLL_FN (library
, jpeg_read_scanlines
);
6396 LOAD_DLL_FN (library
, jpeg_start_decompress
);
6397 LOAD_DLL_FN (library
, jpeg_read_header
);
6398 LOAD_DLL_FN (library
, jpeg_CreateDecompress
);
6399 LOAD_DLL_FN (library
, jpeg_destroy_decompress
);
6400 LOAD_DLL_FN (library
, jpeg_std_error
);
6401 LOAD_DLL_FN (library
, jpeg_resync_to_restart
);
6405 # undef jpeg_CreateDecompress
6406 # undef jpeg_destroy_decompress
6407 # undef jpeg_finish_decompress
6408 # undef jpeg_read_header
6409 # undef jpeg_read_scanlines
6410 # undef jpeg_resync_to_restart
6411 # undef jpeg_start_decompress
6412 # undef jpeg_std_error
6414 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6415 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6416 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6417 # define jpeg_read_header fn_jpeg_read_header
6418 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6419 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6420 # define jpeg_start_decompress fn_jpeg_start_decompress
6421 # define jpeg_std_error fn_jpeg_std_error
6423 /* Wrapper since we can't directly assign the function pointer
6424 to another function pointer that was declared more completely easily. */
6426 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo
, int desired
)
6428 return jpeg_resync_to_restart (cinfo
, desired
);
6430 # undef jpeg_resync_to_restart
6431 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6433 # endif /* WINDOWSNT */
6435 struct my_jpeg_error_mgr
6437 struct jpeg_error_mgr pub
;
6438 sys_jmp_buf setjmp_buffer
;
6440 /* The remaining members are so that longjmp doesn't munge local
6442 struct jpeg_decompress_struct cinfo
;
6446 MY_JPEG_INVALID_IMAGE_SIZE
,
6447 MY_JPEG_CANNOT_CREATE_X
6452 static _Noreturn
void
6453 my_error_exit (j_common_ptr cinfo
)
6455 struct my_jpeg_error_mgr
*mgr
= (struct my_jpeg_error_mgr
*) cinfo
->err
;
6456 mgr
->failure_code
= MY_JPEG_ERROR_EXIT
;
6457 sys_longjmp (mgr
->setjmp_buffer
, 1);
6461 /* Init source method for JPEG data source manager. Called by
6462 jpeg_read_header() before any data is actually read. See
6463 libjpeg.doc from the JPEG lib distribution. */
6466 our_common_init_source (j_decompress_ptr cinfo
)
6471 /* Method to terminate data source. Called by
6472 jpeg_finish_decompress() after all data has been processed. */
6475 our_common_term_source (j_decompress_ptr cinfo
)
6480 /* Fill input buffer method for JPEG data source manager. Called
6481 whenever more data is needed. We read the whole image in one step,
6482 so this only adds a fake end of input marker at the end. */
6484 static JOCTET our_memory_buffer
[2];
6487 our_memory_fill_input_buffer (j_decompress_ptr cinfo
)
6489 /* Insert a fake EOI marker. */
6490 struct jpeg_source_mgr
*src
= cinfo
->src
;
6492 our_memory_buffer
[0] = (JOCTET
) 0xFF;
6493 our_memory_buffer
[1] = (JOCTET
) JPEG_EOI
;
6495 src
->next_input_byte
= our_memory_buffer
;
6496 src
->bytes_in_buffer
= 2;
6501 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6502 is the JPEG data source manager. */
6505 our_memory_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6507 struct jpeg_source_mgr
*src
= cinfo
->src
;
6511 if (num_bytes
> src
->bytes_in_buffer
)
6512 ERREXIT (cinfo
, JERR_INPUT_EOF
);
6514 src
->bytes_in_buffer
-= num_bytes
;
6515 src
->next_input_byte
+= num_bytes
;
6520 /* Set up the JPEG lib for reading an image from DATA which contains
6521 LEN bytes. CINFO is the decompression info structure created for
6522 reading the image. */
6525 jpeg_memory_src (j_decompress_ptr cinfo
, JOCTET
*data
, ptrdiff_t len
)
6527 struct jpeg_source_mgr
*src
= cinfo
->src
;
6531 /* First time for this JPEG object? */
6532 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6533 JPOOL_PERMANENT
, sizeof *src
);
6535 src
->next_input_byte
= data
;
6538 src
->init_source
= our_common_init_source
;
6539 src
->fill_input_buffer
= our_memory_fill_input_buffer
;
6540 src
->skip_input_data
= our_memory_skip_input_data
;
6541 src
->resync_to_restart
= jpeg_resync_to_restart
; /* Use default method. */
6542 src
->term_source
= our_common_term_source
;
6543 src
->bytes_in_buffer
= len
;
6544 src
->next_input_byte
= data
;
6548 struct jpeg_stdio_mgr
6550 struct jpeg_source_mgr mgr
;
6557 /* Size of buffer to read JPEG from file.
6558 Not too big, as we want to use alloc_small. */
6559 #define JPEG_STDIO_BUFFER_SIZE 8192
6562 /* Fill input buffer method for JPEG data source manager. Called
6563 whenever more data is needed. The data is read from a FILE *. */
6566 our_stdio_fill_input_buffer (j_decompress_ptr cinfo
)
6568 struct jpeg_stdio_mgr
*src
;
6570 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6575 bytes
= fread (src
->buffer
, 1, JPEG_STDIO_BUFFER_SIZE
, src
->file
);
6577 src
->mgr
.bytes_in_buffer
= bytes
;
6580 WARNMS (cinfo
, JWRN_JPEG_EOF
);
6582 src
->buffer
[0] = (JOCTET
) 0xFF;
6583 src
->buffer
[1] = (JOCTET
) JPEG_EOI
;
6584 src
->mgr
.bytes_in_buffer
= 2;
6586 src
->mgr
.next_input_byte
= src
->buffer
;
6593 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6594 is the JPEG data source manager. */
6597 our_stdio_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6599 struct jpeg_stdio_mgr
*src
;
6600 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6602 while (num_bytes
> 0 && !src
->finished
)
6604 if (num_bytes
<= src
->mgr
.bytes_in_buffer
)
6606 src
->mgr
.bytes_in_buffer
-= num_bytes
;
6607 src
->mgr
.next_input_byte
+= num_bytes
;
6612 num_bytes
-= src
->mgr
.bytes_in_buffer
;
6613 src
->mgr
.bytes_in_buffer
= 0;
6614 src
->mgr
.next_input_byte
= NULL
;
6616 our_stdio_fill_input_buffer (cinfo
);
6622 /* Set up the JPEG lib for reading an image from a FILE *.
6623 CINFO is the decompression info structure created for
6624 reading the image. */
6627 jpeg_file_src (j_decompress_ptr cinfo
, FILE *fp
)
6629 struct jpeg_stdio_mgr
*src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6633 /* First time for this JPEG object? */
6634 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6635 JPOOL_PERMANENT
, sizeof *src
);
6636 cinfo
->src
= (struct jpeg_source_mgr
*) src
;
6637 src
->buffer
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6639 JPEG_STDIO_BUFFER_SIZE
);
6644 src
->mgr
.init_source
= our_common_init_source
;
6645 src
->mgr
.fill_input_buffer
= our_stdio_fill_input_buffer
;
6646 src
->mgr
.skip_input_data
= our_stdio_skip_input_data
;
6647 src
->mgr
.resync_to_restart
= jpeg_resync_to_restart
; /* Use default. */
6648 src
->mgr
.term_source
= our_common_term_source
;
6649 src
->mgr
.bytes_in_buffer
= 0;
6650 src
->mgr
.next_input_byte
= NULL
;
6653 /* Load image IMG for use on frame F. Patterned after example.c
6654 from the JPEG lib. */
6657 jpeg_load_body (struct frame
*f
, struct image
*img
,
6658 struct my_jpeg_error_mgr
*mgr
)
6660 Lisp_Object specified_file
;
6661 Lisp_Object specified_data
;
6662 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6663 FILE * IF_LINT (volatile) fp
= NULL
;
6665 int row_stride
, x
, y
;
6666 unsigned long *colors
;
6670 XImagePtr ximg
= NULL
;
6673 /* Open the JPEG file. */
6674 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6675 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6676 IF_LINT (Lisp_Object
volatile specified_data_volatile
= specified_data
);
6678 if (NILP (specified_data
))
6681 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
6682 if (!STRINGP (file
))
6684 image_error ("Cannot find image file `%s'", specified_file
);
6688 fp
= fdopen (fd
, "rb");
6691 image_error ("Cannot open `%s'", file
);
6695 else if (!STRINGP (specified_data
))
6697 image_error ("Invalid image data `%s'", specified_data
);
6701 /* Customize libjpeg's error handling to call my_error_exit when an
6702 error is detected. This function will perform a longjmp. */
6703 mgr
->cinfo
.err
= jpeg_std_error (&mgr
->pub
);
6704 mgr
->pub
.error_exit
= my_error_exit
;
6705 if (sys_setjmp (mgr
->setjmp_buffer
))
6707 switch (mgr
->failure_code
)
6709 case MY_JPEG_ERROR_EXIT
:
6711 char buf
[JMSG_LENGTH_MAX
];
6712 mgr
->cinfo
.err
->format_message ((j_common_ptr
) &mgr
->cinfo
, buf
);
6713 image_error ("Error reading JPEG image `%s': %s",
6714 img
->spec
, build_string (buf
));
6718 case MY_JPEG_INVALID_IMAGE_SIZE
:
6719 image_size_error ();
6722 case MY_JPEG_CANNOT_CREATE_X
:
6726 /* Close the input file and destroy the JPEG object. */
6729 jpeg_destroy_decompress (&mgr
->cinfo
);
6731 /* If we already have an XImage, free that. */
6733 x_destroy_x_image (ximg
);
6735 /* Free pixmap and colors. */
6736 x_clear_image (f
, img
);
6740 /* Silence a bogus diagnostic; see GCC bug 54561. */
6741 IF_LINT (specified_data
= specified_data_volatile
);
6743 /* Create the JPEG decompression object. Let it read from fp.
6744 Read the JPEG image header. */
6745 jpeg_CreateDecompress (&mgr
->cinfo
, JPEG_LIB_VERSION
, sizeof *&mgr
->cinfo
);
6747 if (NILP (specified_data
))
6748 jpeg_file_src (&mgr
->cinfo
, fp
);
6750 jpeg_memory_src (&mgr
->cinfo
, SDATA (specified_data
),
6751 SBYTES (specified_data
));
6753 jpeg_read_header (&mgr
->cinfo
, 1);
6755 /* Customize decompression so that color quantization will be used.
6756 Start decompression. */
6757 mgr
->cinfo
.quantize_colors
= 1;
6758 jpeg_start_decompress (&mgr
->cinfo
);
6759 width
= img
->width
= mgr
->cinfo
.output_width
;
6760 height
= img
->height
= mgr
->cinfo
.output_height
;
6762 if (!check_image_size (f
, width
, height
))
6764 mgr
->failure_code
= MY_JPEG_INVALID_IMAGE_SIZE
;
6765 sys_longjmp (mgr
->setjmp_buffer
, 1);
6769 /* Create X image and pixmap. */
6770 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6772 mgr
->failure_code
= MY_JPEG_CANNOT_CREATE_X
;
6773 sys_longjmp (mgr
->setjmp_buffer
, 1);
6777 /* Allocate colors. When color quantization is used,
6778 mgr->cinfo.actual_number_of_colors has been set with the number of
6779 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6780 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6781 No more than 255 colors will be generated. */
6784 if (mgr
->cinfo
.out_color_components
> 2)
6785 ir
= 0, ig
= 1, ib
= 2;
6786 else if (mgr
->cinfo
.out_color_components
> 1)
6787 ir
= 0, ig
= 1, ib
= 0;
6789 ir
= 0, ig
= 0, ib
= 0;
6792 /* Use the color table mechanism because it handles colors that
6793 cannot be allocated nicely. Such colors will be replaced with
6794 a default color, and we don't have to care about which colors
6795 can be freed safely, and which can't. */
6796 init_color_table ();
6797 SAFE_NALLOCA (colors
, 1, mgr
->cinfo
.actual_number_of_colors
);
6799 for (i
= 0; i
< mgr
->cinfo
.actual_number_of_colors
; ++i
)
6801 /* Multiply RGB values with 255 because X expects RGB values
6802 in the range 0..0xffff. */
6803 int r
= mgr
->cinfo
.colormap
[ir
][i
] << 8;
6804 int g
= mgr
->cinfo
.colormap
[ig
][i
] << 8;
6805 int b
= mgr
->cinfo
.colormap
[ib
][i
] << 8;
6806 colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
6810 #ifdef COLOR_TABLE_SUPPORT
6811 /* Remember those colors actually allocated. */
6812 img
->colors
= colors_in_color_table (&img
->ncolors
);
6813 free_color_table ();
6814 #endif /* COLOR_TABLE_SUPPORT */
6818 row_stride
= width
* mgr
->cinfo
.output_components
;
6819 buffer
= mgr
->cinfo
.mem
->alloc_sarray ((j_common_ptr
) &mgr
->cinfo
,
6820 JPOOL_IMAGE
, row_stride
, 1);
6823 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
6824 uint32_t *dataptr
= (uint32_t *) data
;
6827 for (y
= 0; y
< height
; ++y
)
6829 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6831 for (x
= 0; x
< width
; ++x
)
6834 r
= mgr
->cinfo
.colormap
[ir
][i
];
6835 g
= mgr
->cinfo
.colormap
[ig
][i
];
6836 b
= mgr
->cinfo
.colormap
[ib
][i
];
6837 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
6841 create_cairo_image_surface (img
, data
, width
, height
);
6844 for (y
= 0; y
< height
; ++y
)
6846 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6847 for (x
= 0; x
< mgr
->cinfo
.output_width
; ++x
)
6848 XPutPixel (ximg
, x
, y
, colors
[buffer
[0][x
]]);
6853 jpeg_finish_decompress (&mgr
->cinfo
);
6854 jpeg_destroy_decompress (&mgr
->cinfo
);
6859 /* Maybe fill in the background field while we have ximg handy. */
6860 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6861 /* Casting avoids a GCC warning. */
6862 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6864 /* Put ximg into the image. */
6865 image_put_x_image (f
, img
, ximg
, 0);
6872 jpeg_load (struct frame
*f
, struct image
*img
)
6874 struct my_jpeg_error_mgr mgr
;
6875 return jpeg_load_body (f
, img
, &mgr
);
6878 #else /* HAVE_JPEG */
6882 jpeg_load (struct frame
*f
, struct image
*img
)
6884 return ns_load_image (f
, img
,
6885 image_spec_value (img
->spec
, QCfile
, NULL
),
6886 image_spec_value (img
->spec
, QCdata
, NULL
));
6888 #endif /* HAVE_NS */
6890 #endif /* !HAVE_JPEG */
6894 /***********************************************************************
6896 ***********************************************************************/
6898 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6900 static bool tiff_image_p (Lisp_Object object
);
6901 static bool tiff_load (struct frame
*f
, struct image
*img
);
6903 /* Indices of image specification fields in tiff_format, below. */
6905 enum tiff_keyword_index
6914 TIFF_HEURISTIC_MASK
,
6921 /* Vector of image_keyword structures describing the format
6922 of valid user-defined image specifications. */
6924 static const struct image_keyword tiff_format
[TIFF_LAST
] =
6926 {":type", IMAGE_SYMBOL_VALUE
, 1},
6927 {":data", IMAGE_STRING_VALUE
, 0},
6928 {":file", IMAGE_STRING_VALUE
, 0},
6929 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6930 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6931 {":relief", IMAGE_INTEGER_VALUE
, 0},
6932 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6933 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6934 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6935 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
6936 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0}
6939 #if defined HAVE_NTGUI && defined WINDOWSNT
6940 static bool init_tiff_functions (void);
6942 #define init_tiff_functions NULL
6945 /* Structure describing the image type `tiff'. */
6947 static struct image_type tiff_type
=
6949 SYMBOL_INDEX (Qtiff
),
6953 init_tiff_functions
,
6957 /* Return true if OBJECT is a valid TIFF image specification. */
6960 tiff_image_p (Lisp_Object object
)
6962 struct image_keyword fmt
[TIFF_LAST
];
6963 memcpy (fmt
, tiff_format
, sizeof fmt
);
6965 if (!parse_image_spec (object
, fmt
, TIFF_LAST
, Qtiff
))
6968 /* Must specify either the :data or :file keyword. */
6969 return fmt
[TIFF_FILE
].count
+ fmt
[TIFF_DATA
].count
== 1;
6972 #endif /* HAVE_TIFF || HAVE_NS */
6976 # include <tiffio.h>
6980 /* TIFF library details. */
6981 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetErrorHandler
, (TIFFErrorHandler
));
6982 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetWarningHandler
, (TIFFErrorHandler
));
6983 DEF_DLL_FN (TIFF
*, TIFFOpen
, (const char *, const char *));
6984 DEF_DLL_FN (TIFF
*, TIFFClientOpen
,
6985 (const char *, const char *, thandle_t
, TIFFReadWriteProc
,
6986 TIFFReadWriteProc
, TIFFSeekProc
, TIFFCloseProc
, TIFFSizeProc
,
6987 TIFFMapFileProc
, TIFFUnmapFileProc
));
6988 DEF_DLL_FN (int, TIFFGetField
, (TIFF
*, ttag_t
, ...));
6989 DEF_DLL_FN (int, TIFFReadRGBAImage
, (TIFF
*, uint32
, uint32
, uint32
*, int));
6990 DEF_DLL_FN (void, TIFFClose
, (TIFF
*));
6991 DEF_DLL_FN (int, TIFFSetDirectory
, (TIFF
*, tdir_t
));
6994 init_tiff_functions (void)
6998 if (!(library
= w32_delayed_load (Qtiff
)))
7001 LOAD_DLL_FN (library
, TIFFSetErrorHandler
);
7002 LOAD_DLL_FN (library
, TIFFSetWarningHandler
);
7003 LOAD_DLL_FN (library
, TIFFOpen
);
7004 LOAD_DLL_FN (library
, TIFFClientOpen
);
7005 LOAD_DLL_FN (library
, TIFFGetField
);
7006 LOAD_DLL_FN (library
, TIFFReadRGBAImage
);
7007 LOAD_DLL_FN (library
, TIFFClose
);
7008 LOAD_DLL_FN (library
, TIFFSetDirectory
);
7012 # undef TIFFClientOpen
7014 # undef TIFFGetField
7016 # undef TIFFReadRGBAImage
7017 # undef TIFFSetDirectory
7018 # undef TIFFSetErrorHandler
7019 # undef TIFFSetWarningHandler
7021 # define TIFFClientOpen fn_TIFFClientOpen
7022 # define TIFFClose fn_TIFFClose
7023 # define TIFFGetField fn_TIFFGetField
7024 # define TIFFOpen fn_TIFFOpen
7025 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7026 # define TIFFSetDirectory fn_TIFFSetDirectory
7027 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7028 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7030 # endif /* WINDOWSNT */
7033 /* Reading from a memory buffer for TIFF images Based on the PNG
7034 memory source, but we have to provide a lot of extra functions.
7037 We really only need to implement read and seek, but I am not
7038 convinced that the TIFF library is smart enough not to destroy
7039 itself if we only hand it the function pointers we need to
7044 unsigned char *bytes
;
7051 tiff_read_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7053 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7055 size
= min (size
, src
->len
- src
->index
);
7056 memcpy (buf
, src
->bytes
+ src
->index
, size
);
7062 tiff_write_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7068 tiff_seek_in_memory (thandle_t data
, toff_t off
, int whence
)
7070 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7075 case SEEK_SET
: /* Go from beginning of source. */
7079 case SEEK_END
: /* Go from end of source. */
7080 idx
= src
->len
+ off
;
7083 case SEEK_CUR
: /* Go from current position. */
7084 idx
= src
->index
+ off
;
7087 default: /* Invalid `whence'. */
7091 if (idx
> src
->len
|| idx
< 0)
7099 tiff_close_memory (thandle_t data
)
7106 tiff_mmap_memory (thandle_t data
, tdata_t
*pbase
, toff_t
*psize
)
7108 /* It is already _IN_ memory. */
7113 tiff_unmap_memory (thandle_t data
, tdata_t base
, toff_t size
)
7115 /* We don't need to do this. */
7119 tiff_size_of_memory (thandle_t data
)
7121 return ((tiff_memory_source
*) data
)->len
;
7124 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7125 compiler error compiling tiff_handler, see Bugzilla bug #17406
7126 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7127 this function as external works around that problem. */
7128 # if defined (__MINGW32__) && __GNUC__ == 3
7129 # define MINGW_STATIC
7131 # define MINGW_STATIC static
7135 tiff_handler (const char *, const char *, const char *, va_list)
7136 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7138 tiff_handler (const char *log_format
, const char *title
,
7139 const char *format
, va_list ap
)
7141 /* doprnt is not suitable here, as TIFF handlers are called from
7142 libtiff and are passed arbitrary printf directives. Instead, use
7143 vsnprintf, taking care to be portable to nonstandard environments
7144 where vsnprintf returns -1 on buffer overflow. Since it's just a
7145 log entry, it's OK to truncate it. */
7147 int len
= vsnprintf (buf
, sizeof buf
, format
, ap
);
7148 add_to_log (log_format
, build_string (title
),
7149 make_string (buf
, max (0, min (len
, sizeof buf
- 1))));
7151 # undef MINGW_STATIC
7153 static void tiff_error_handler (const char *, const char *, va_list)
7154 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7156 tiff_error_handler (const char *title
, const char *format
, va_list ap
)
7158 tiff_handler ("TIFF error: %s %s", title
, format
, ap
);
7162 static void tiff_warning_handler (const char *, const char *, va_list)
7163 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7165 tiff_warning_handler (const char *title
, const char *format
, va_list ap
)
7167 tiff_handler ("TIFF warning: %s %s", title
, format
, ap
);
7171 /* Load TIFF image IMG for use on frame F. Value is true if
7175 tiff_load (struct frame
*f
, struct image
*img
)
7177 Lisp_Object specified_file
;
7178 Lisp_Object specified_data
;
7180 int width
, height
, x
, y
, count
;
7184 tiff_memory_source memsrc
;
7187 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7188 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7190 TIFFSetErrorHandler ((TIFFErrorHandler
) tiff_error_handler
);
7191 TIFFSetWarningHandler ((TIFFErrorHandler
) tiff_warning_handler
);
7193 if (NILP (specified_data
))
7195 /* Read from a file */
7196 Lisp_Object file
= x_find_image_file (specified_file
);
7197 if (!STRINGP (file
))
7199 image_error ("Cannot find image file `%s'", specified_file
);
7203 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7205 encoded_file
= ansi_encode_filename (encoded_file
);
7208 /* Try to open the image file. */
7209 tiff
= TIFFOpen (SSDATA (encoded_file
), "r");
7212 image_error ("Cannot open `%s'", file
);
7218 if (!STRINGP (specified_data
))
7220 image_error ("Invalid image data `%s'", specified_data
);
7224 /* Memory source! */
7225 memsrc
.bytes
= SDATA (specified_data
);
7226 memsrc
.len
= SBYTES (specified_data
);
7229 tiff
= TIFFClientOpen ("memory_source", "r", (thandle_t
)&memsrc
,
7230 tiff_read_from_memory
,
7231 tiff_write_from_memory
,
7232 tiff_seek_in_memory
,
7234 tiff_size_of_memory
,
7240 image_error ("Cannot open memory source for `%s'", img
->spec
);
7245 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
7246 if (INTEGERP (image
))
7248 EMACS_INT ino
= XFASTINT (image
);
7249 if (! (TYPE_MINIMUM (tdir_t
) <= ino
&& ino
<= TYPE_MAXIMUM (tdir_t
)
7250 && TIFFSetDirectory (tiff
, ino
)))
7252 image_error ("Invalid image number `%s' in image `%s'",
7259 /* Get width and height of the image, and allocate a raster buffer
7260 of width x height 32-bit values. */
7261 TIFFGetField (tiff
, TIFFTAG_IMAGEWIDTH
, &width
);
7262 TIFFGetField (tiff
, TIFFTAG_IMAGELENGTH
, &height
);
7264 if (!check_image_size (f
, width
, height
))
7266 image_size_error ();
7271 /* Create the X image and pixmap. */
7272 if (! (height
<= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *buf
/ width
7273 && image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
7280 buf
= xmalloc (sizeof *buf
* width
* height
);
7282 rc
= TIFFReadRGBAImage (tiff
, width
, height
, buf
, 0);
7284 /* Count the number of images in the file. */
7285 for (count
= 1; TIFFSetDirectory (tiff
, count
); count
++)
7289 img
->lisp_data
= Fcons (Qcount
,
7290 Fcons (make_number (count
),
7296 image_error ("Error reading TIFF image `%s'", img
->spec
);
7303 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
7304 uint32_t *dataptr
= (uint32_t *) data
;
7307 for (y
= 0; y
< height
; ++y
)
7309 uint32
*row
= buf
+ (height
- 1 - y
) * width
;
7310 for (x
= 0; x
< width
; ++x
)
7312 uint32 abgr
= row
[x
];
7313 int r
= TIFFGetR (abgr
);
7314 int g
= TIFFGetG (abgr
);
7315 int b
= TIFFGetB (abgr
);
7316 int a
= TIFFGetA (abgr
);
7317 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
7321 create_cairo_image_surface (img
, data
, width
, height
);
7324 /* Initialize the color table. */
7325 init_color_table ();
7327 /* Process the pixel raster. Origin is in the lower-left corner. */
7328 for (y
= 0; y
< height
; ++y
)
7330 uint32
*row
= buf
+ y
* width
;
7332 for (x
= 0; x
< width
; ++x
)
7334 uint32 abgr
= row
[x
];
7335 int r
= TIFFGetR (abgr
) << 8;
7336 int g
= TIFFGetG (abgr
) << 8;
7337 int b
= TIFFGetB (abgr
) << 8;
7338 XPutPixel (ximg
, x
, height
- 1 - y
, lookup_rgb_color (f
, r
, g
, b
));
7342 # ifdef COLOR_TABLE_SUPPORT
7343 /* Remember the colors allocated for the image. Free the color table. */
7344 img
->colors
= colors_in_color_table (&img
->ncolors
);
7345 free_color_table ();
7346 # endif /* COLOR_TABLE_SUPPORT */
7349 img
->height
= height
;
7351 /* Maybe fill in the background field while we have ximg handy. */
7352 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7353 /* Casting avoids a GCC warning on W32. */
7354 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7356 /* Put ximg into the image. */
7357 image_put_x_image (f
, img
, ximg
, 0);
7359 #endif /* ! USE_CAIRO */
7365 #elif defined HAVE_NS
7368 tiff_load (struct frame
*f
, struct image
*img
)
7370 return ns_load_image (f
, img
,
7371 image_spec_value (img
->spec
, QCfile
, NULL
),
7372 image_spec_value (img
->spec
, QCdata
, NULL
));
7379 /***********************************************************************
7381 ***********************************************************************/
7383 #if defined (HAVE_GIF) || defined (HAVE_NS)
7385 static bool gif_image_p (Lisp_Object object
);
7386 static bool gif_load (struct frame
*f
, struct image
*img
);
7387 static void gif_clear_image (struct frame
*f
, struct image
*img
);
7389 /* Indices of image specification fields in gif_format, below. */
7391 enum gif_keyword_index
7407 /* Vector of image_keyword structures describing the format
7408 of valid user-defined image specifications. */
7410 static const struct image_keyword gif_format
[GIF_LAST
] =
7412 {":type", IMAGE_SYMBOL_VALUE
, 1},
7413 {":data", IMAGE_STRING_VALUE
, 0},
7414 {":file", IMAGE_STRING_VALUE
, 0},
7415 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7416 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7417 {":relief", IMAGE_INTEGER_VALUE
, 0},
7418 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7419 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7420 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7421 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0},
7422 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
7425 #if defined HAVE_NTGUI && defined WINDOWSNT
7426 static bool init_gif_functions (void);
7428 #define init_gif_functions NULL
7431 /* Structure describing the image type `gif'. */
7433 static struct image_type gif_type
=
7435 SYMBOL_INDEX (Qgif
),
7443 /* Free X resources of GIF image IMG which is used on frame F. */
7446 gif_clear_image (struct frame
*f
, struct image
*img
)
7448 img
->lisp_data
= Qnil
;
7449 x_clear_image (f
, img
);
7452 /* Return true if OBJECT is a valid GIF image specification. */
7455 gif_image_p (Lisp_Object object
)
7457 struct image_keyword fmt
[GIF_LAST
];
7458 memcpy (fmt
, gif_format
, sizeof fmt
);
7460 if (!parse_image_spec (object
, fmt
, GIF_LAST
, Qgif
))
7463 /* Must specify either the :data or :file keyword. */
7464 return fmt
[GIF_FILE
].count
+ fmt
[GIF_DATA
].count
== 1;
7467 #endif /* HAVE_GIF */
7473 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7474 Undefine before redefining to avoid a preprocessor warning. */
7478 /* avoid conflict with QuickdrawText.h */
7479 # define DrawText gif_DrawText
7480 # include <gif_lib.h>
7483 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7484 # ifndef GIFLIB_MINOR
7485 # define GIFLIB_MINOR 0
7487 # ifndef GIFLIB_RELEASE
7488 # define GIFLIB_RELEASE 0
7491 # else /* HAVE_NTGUI */
7493 # include <gif_lib.h>
7495 # endif /* HAVE_NTGUI */
7497 /* Giflib before 5.0 didn't define these macros. */
7498 # ifndef GIFLIB_MAJOR
7499 # define GIFLIB_MAJOR 4
7502 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7503 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7504 earlier releases, where either it returns char * or GIFLIB_MINOR
7505 may be incorrect. */
7506 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7510 /* GIF library details. */
7511 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7512 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*, int *));
7514 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*));
7516 DEF_DLL_FN (int, DGifSlurp
, (GifFileType
*));
7517 # if GIFLIB_MAJOR < 5
7518 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
));
7519 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *));
7521 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
, int *));
7522 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *, int *));
7524 # if HAVE_GIFERRORSTRING
7525 DEF_DLL_FN (char const *, GifErrorString
, (int));
7529 init_gif_functions (void)
7533 if (!(library
= w32_delayed_load (Qgif
)))
7536 LOAD_DLL_FN (library
, DGifCloseFile
);
7537 LOAD_DLL_FN (library
, DGifSlurp
);
7538 LOAD_DLL_FN (library
, DGifOpen
);
7539 LOAD_DLL_FN (library
, DGifOpenFileName
);
7540 # if HAVE_GIFERRORSTRING
7541 LOAD_DLL_FN (library
, GifErrorString
);
7546 # undef DGifCloseFile
7548 # undef DGifOpenFileName
7550 # undef GifErrorString
7552 # define DGifCloseFile fn_DGifCloseFile
7553 # define DGifOpen fn_DGifOpen
7554 # define DGifOpenFileName fn_DGifOpenFileName
7555 # define DGifSlurp fn_DGifSlurp
7556 # define GifErrorString fn_GifErrorString
7558 # endif /* WINDOWSNT */
7560 /* Reading a GIF image from memory
7561 Based on the PNG memory stuff to a certain extent. */
7565 unsigned char *bytes
;
7571 /* Make the current memory source available to gif_read_from_memory.
7572 It's done this way because not all versions of libungif support
7573 a UserData field in the GifFileType structure. */
7574 static gif_memory_source
*current_gif_memory_src
;
7577 gif_read_from_memory (GifFileType
*file
, GifByteType
*buf
, int len
)
7579 gif_memory_source
*src
= current_gif_memory_src
;
7581 if (len
> src
->len
- src
->index
)
7584 memcpy (buf
, src
->bytes
+ src
->index
, len
);
7590 gif_close (GifFileType
*gif
, int *err
)
7594 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7595 retval
= DGifCloseFile (gif
, err
);
7597 retval
= DGifCloseFile (gif
);
7598 #if GIFLIB_MAJOR >= 5
7606 /* Load GIF image IMG for use on frame F. Value is true if
7609 static const int interlace_start
[] = {0, 4, 2, 1};
7610 static const int interlace_increment
[] = {8, 8, 4, 2};
7612 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7615 gif_load (struct frame
*f
, struct image
*img
)
7617 int rc
, width
, height
, x
, y
, i
, j
;
7618 ColorMapObject
*gif_color_map
;
7619 unsigned long pixel_colors
[256];
7621 gif_memory_source memsrc
;
7622 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
7623 Lisp_Object specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7624 Lisp_Object specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7625 unsigned long bgcolor
= 0;
7630 unsigned char *data
= 0;
7635 if (NILP (specified_data
))
7637 Lisp_Object file
= x_find_image_file (specified_file
);
7638 if (!STRINGP (file
))
7640 image_error ("Cannot find image file `%s'", specified_file
);
7644 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7646 encoded_file
= ansi_encode_filename (encoded_file
);
7649 /* Open the GIF file. */
7650 #if GIFLIB_MAJOR < 5
7651 gif
= DGifOpenFileName (SSDATA (encoded_file
));
7653 gif
= DGifOpenFileName (SSDATA (encoded_file
), &gif_err
);
7657 #if HAVE_GIFERRORSTRING
7658 image_error ("Cannot open `%s': %s",
7659 file
, build_string (GifErrorString (gif_err
)));
7661 image_error ("Cannot open `%s'", file
);
7668 if (!STRINGP (specified_data
))
7670 image_error ("Invalid image data `%s'", specified_data
);
7674 /* Read from memory! */
7675 current_gif_memory_src
= &memsrc
;
7676 memsrc
.bytes
= SDATA (specified_data
);
7677 memsrc
.len
= SBYTES (specified_data
);
7680 #if GIFLIB_MAJOR < 5
7681 gif
= DGifOpen (&memsrc
, gif_read_from_memory
);
7683 gif
= DGifOpen (&memsrc
, gif_read_from_memory
, &gif_err
);
7687 #if HAVE_GIFERRORSTRING
7688 image_error ("Cannot open memory source `%s': %s",
7689 img
->spec
, build_string (GifErrorString (gif_err
)));
7691 image_error ("Cannot open memory source `%s'", img
->spec
);
7697 /* Before reading entire contents, check the declared image size. */
7698 if (!check_image_size (f
, gif
->SWidth
, gif
->SHeight
))
7700 image_size_error ();
7701 gif_close (gif
, NULL
);
7705 /* Read entire contents. */
7706 rc
= DGifSlurp (gif
);
7707 if (rc
== GIF_ERROR
|| gif
->ImageCount
<= 0)
7709 image_error ("Error reading `%s'", img
->spec
);
7710 gif_close (gif
, NULL
);
7714 /* Which sub-image are we to display? */
7716 Lisp_Object image_number
= image_spec_value (img
->spec
, QCindex
, NULL
);
7717 idx
= INTEGERP (image_number
) ? XFASTINT (image_number
) : 0;
7718 if (idx
< 0 || idx
>= gif
->ImageCount
)
7720 image_error ("Invalid image number `%s' in image `%s'",
7721 image_number
, img
->spec
);
7722 gif_close (gif
, NULL
);
7727 width
= img
->width
= gif
->SWidth
;
7728 height
= img
->height
= gif
->SHeight
;
7730 img
->corners
[TOP_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Top
;
7731 img
->corners
[LEFT_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Left
;
7732 img
->corners
[BOT_CORNER
]
7733 = img
->corners
[TOP_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Height
;
7734 img
->corners
[RIGHT_CORNER
]
7735 = img
->corners
[LEFT_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Width
;
7737 if (!check_image_size (f
, width
, height
))
7739 image_size_error ();
7740 gif_close (gif
, NULL
);
7744 /* Check that the selected subimages fit. It's not clear whether
7745 the GIF spec requires this, but Emacs can crash if they don't fit. */
7746 for (j
= 0; j
<= idx
; ++j
)
7748 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7749 int subimg_width
= subimage
->ImageDesc
.Width
;
7750 int subimg_height
= subimage
->ImageDesc
.Height
;
7751 int subimg_top
= subimage
->ImageDesc
.Top
;
7752 int subimg_left
= subimage
->ImageDesc
.Left
;
7753 if (! (subimg_width
>= 0 && subimg_height
>= 0
7754 && 0 <= subimg_top
&& subimg_top
<= height
- subimg_height
7755 && 0 <= subimg_left
&& subimg_left
<= width
- subimg_width
))
7757 image_error ("Subimage does not fit in image");
7758 gif_close (gif
, NULL
);
7764 /* xzalloc so data is zero => transparent */
7765 data
= (unsigned char *) xzalloc (width
* height
* 4);
7766 if (STRINGP (specified_bg
))
7769 if (x_defined_color (f
, SSDATA (specified_bg
), &color
, 0))
7771 uint32_t *dataptr
= (uint32_t *)data
;
7772 int r
= color
.red
/256;
7773 int g
= color
.green
/256;
7774 int b
= color
.blue
/256;
7776 for (y
= 0; y
< height
; ++y
)
7777 for (x
= 0; x
< width
; ++x
)
7778 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7782 /* Create the X image and pixmap. */
7783 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
7785 gif_close (gif
, NULL
);
7789 /* Clear the part of the screen image not covered by the image.
7790 Full animated GIF support requires more here (see the gif89 spec,
7791 disposal methods). Let's simply assume that the part not covered
7792 by a sub-image is in the frame's background color. */
7793 for (y
= 0; y
< img
->corners
[TOP_CORNER
]; ++y
)
7794 for (x
= 0; x
< width
; ++x
)
7795 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7797 for (y
= img
->corners
[BOT_CORNER
]; y
< height
; ++y
)
7798 for (x
= 0; x
< width
; ++x
)
7799 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7801 for (y
= img
->corners
[TOP_CORNER
]; y
< img
->corners
[BOT_CORNER
]; ++y
)
7803 for (x
= 0; x
< img
->corners
[LEFT_CORNER
]; ++x
)
7804 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7805 for (x
= img
->corners
[RIGHT_CORNER
]; x
< width
; ++x
)
7806 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7810 /* Read the GIF image into the X image. */
7812 /* FIXME: With the current implementation, loading an animated gif
7813 is quadratic in the number of animation frames, since each frame
7814 is a separate struct image. We must provide a way for a single
7815 gif_load call to construct and save all animation frames. */
7817 init_color_table ();
7818 if (STRINGP (specified_bg
))
7819 bgcolor
= x_alloc_image_color (f
, img
, specified_bg
,
7820 FRAME_BACKGROUND_PIXEL (f
));
7821 for (j
= 0; j
<= idx
; ++j
)
7823 /* We use a local variable `raster' here because RasterBits is a
7824 char *, which invites problems with bytes >= 0x80. */
7825 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7826 unsigned char *raster
= (unsigned char *) subimage
->RasterBits
;
7827 int transparency_color_index
= -1;
7829 int subimg_width
= subimage
->ImageDesc
.Width
;
7830 int subimg_height
= subimage
->ImageDesc
.Height
;
7831 int subimg_top
= subimage
->ImageDesc
.Top
;
7832 int subimg_left
= subimage
->ImageDesc
.Left
;
7834 /* Find the Graphic Control Extension block for this sub-image.
7835 Extract the disposal method and transparency color. */
7836 for (i
= 0; i
< subimage
->ExtensionBlockCount
; i
++)
7838 ExtensionBlock
*extblock
= subimage
->ExtensionBlocks
+ i
;
7840 if ((extblock
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
)
7841 && extblock
->ByteCount
== 4
7842 && extblock
->Bytes
[0] & 1)
7844 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7845 to background". Treat any other value like 2. */
7846 disposal
= (extblock
->Bytes
[0] >> 2) & 7;
7847 transparency_color_index
= (unsigned char) extblock
->Bytes
[3];
7852 /* We can't "keep in place" the first subimage. */
7856 /* For disposal == 0, the spec says "No disposal specified. The
7857 decoder is not required to take any action." In practice, it
7858 seems we need to treat this like "keep in place", see e.g.
7859 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7863 gif_color_map
= subimage
->ImageDesc
.ColorMap
;
7865 gif_color_map
= gif
->SColorMap
;
7868 /* Allocate subimage colors. */
7869 memset (pixel_colors
, 0, sizeof pixel_colors
);
7872 for (i
= 0; i
< gif_color_map
->ColorCount
; ++i
)
7874 if (transparency_color_index
== i
)
7875 pixel_colors
[i
] = STRINGP (specified_bg
)
7876 ? bgcolor
: FRAME_BACKGROUND_PIXEL (f
);
7879 int r
= gif_color_map
->Colors
[i
].Red
<< 8;
7880 int g
= gif_color_map
->Colors
[i
].Green
<< 8;
7881 int b
= gif_color_map
->Colors
[i
].Blue
<< 8;
7882 pixel_colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
7887 /* Apply the pixel values. */
7888 if (GIFLIB_MAJOR
< 5 && gif
->SavedImages
[j
].ImageDesc
.Interlace
)
7892 for (y
= 0, row
= interlace_start
[0], pass
= 0;
7894 y
++, row
+= interlace_increment
[pass
])
7896 while (subimg_height
<= row
)
7897 row
= interlace_start
[++pass
];
7899 for (x
= 0; x
< subimg_width
; x
++)
7901 int c
= raster
[y
* subimg_width
+ x
];
7902 if (transparency_color_index
!= c
|| disposal
!= 1)
7906 ((uint32_t*)data
+ ((row
+ subimg_top
) * subimg_width
7907 + x
+ subimg_left
));
7908 int r
= gif_color_map
->Colors
[c
].Red
;
7909 int g
= gif_color_map
->Colors
[c
].Green
;
7910 int b
= gif_color_map
->Colors
[c
].Blue
;
7912 if (transparency_color_index
!= c
)
7913 *dataptr
= (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7915 XPutPixel (ximg
, x
+ subimg_left
, row
+ subimg_top
,
7924 for (y
= 0; y
< subimg_height
; ++y
)
7925 for (x
= 0; x
< subimg_width
; ++x
)
7927 int c
= raster
[y
* subimg_width
+ x
];
7928 if (transparency_color_index
!= c
|| disposal
!= 1)
7932 ((uint32_t*)data
+ ((y
+ subimg_top
) * subimg_width
7933 + x
+ subimg_left
));
7934 int r
= gif_color_map
->Colors
[c
].Red
;
7935 int g
= gif_color_map
->Colors
[c
].Green
;
7936 int b
= gif_color_map
->Colors
[c
].Blue
;
7937 if (transparency_color_index
!= c
)
7938 *dataptr
= (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7940 XPutPixel (ximg
, x
+ subimg_left
, y
+ subimg_top
,
7948 #ifdef COLOR_TABLE_SUPPORT
7949 img
->colors
= colors_in_color_table (&img
->ncolors
);
7950 free_color_table ();
7951 #endif /* COLOR_TABLE_SUPPORT */
7953 /* Save GIF image extension data for `image-metadata'.
7954 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7955 img
->lisp_data
= Qnil
;
7956 if (gif
->SavedImages
[idx
].ExtensionBlockCount
> 0)
7959 ExtensionBlock
*ext
= gif
->SavedImages
[idx
].ExtensionBlocks
;
7960 for (i
= 0; i
< gif
->SavedImages
[idx
].ExtensionBlockCount
; i
++, ext
++)
7961 /* Append (... FUNCTION "BYTES") */
7964 = Fcons (make_number (ext
->Function
),
7965 Fcons (make_unibyte_string (ext
->Bytes
, ext
->ByteCount
),
7967 if (ext
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
7968 && ext
->ByteCount
== 4)
7970 delay
= ext
->Bytes
[2] << CHAR_BIT
;
7971 delay
|= ext
->Bytes
[1];
7974 img
->lisp_data
= list2 (Qextension_data
, img
->lisp_data
);
7978 Fcons (make_float (delay
/ 100.0),
7982 if (gif
->ImageCount
> 1)
7983 img
->lisp_data
= Fcons (Qcount
,
7984 Fcons (make_number (gif
->ImageCount
),
7987 if (gif_close (gif
, &gif_err
) == GIF_ERROR
)
7989 #if HAVE_GIFERRORSTRING
7990 char const *error_text
= GifErrorString (gif_err
);
7993 image_error ("Error closing `%s': %s",
7994 img
->spec
, build_string (error_text
));
7996 image_error ("Error closing `%s'", img
->spec
);
8001 create_cairo_image_surface (img
, data
, width
, height
);
8003 /* Maybe fill in the background field while we have ximg handy. */
8004 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
8005 /* Casting avoids a GCC warning. */
8006 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
8008 /* Put ximg into the image. */
8009 image_put_x_image (f
, img
, ximg
, 0);
8015 #else /* !HAVE_GIF */
8019 gif_load (struct frame
*f
, struct image
*img
)
8021 return ns_load_image (f
, img
,
8022 image_spec_value (img
->spec
, QCfile
, NULL
),
8023 image_spec_value (img
->spec
, QCdata
, NULL
));
8025 #endif /* HAVE_NS */
8027 #endif /* HAVE_GIF */
8030 #ifdef HAVE_IMAGEMAGICK
8032 /***********************************************************************
8034 ***********************************************************************/
8036 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8037 safely rounded and clipped to int range. */
8040 scale_image_size (int size
, size_t divisor
, size_t multiplier
)
8045 double scaled
= s
* multiplier
/ divisor
+ 0.5;
8046 if (scaled
< INT_MAX
)
8052 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8053 Use SPEC to deduce the size. Store the desired size into
8054 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8056 compute_image_size (size_t width
, size_t height
,
8058 int *d_width
, int *d_height
)
8061 int desired_width
, desired_height
;
8063 /* If width and/or height is set in the display spec assume we want
8064 to scale to those values. If either h or w is unspecified, the
8065 unspecified should be calculated from the specified to preserve
8067 value
= image_spec_value (spec
, QCwidth
, NULL
);
8068 desired_width
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
8069 value
= image_spec_value (spec
, QCheight
, NULL
);
8070 desired_height
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
8072 if (desired_width
== -1)
8074 value
= image_spec_value (spec
, QCmax_width
, NULL
);
8075 if (NATNUMP (value
))
8077 int max_width
= min (XFASTINT (value
), INT_MAX
);
8078 if (max_width
< width
)
8080 /* The image is wider than :max-width. */
8081 desired_width
= max_width
;
8082 if (desired_height
== -1)
8084 desired_height
= scale_image_size (desired_width
,
8086 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8087 if (NATNUMP (value
))
8089 int max_height
= min (XFASTINT (value
), INT_MAX
);
8090 if (max_height
< desired_height
)
8092 desired_height
= max_height
;
8093 desired_width
= scale_image_size (desired_height
,
8102 if (desired_height
== -1)
8104 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8105 if (NATNUMP (value
))
8107 int max_height
= min (XFASTINT (value
), INT_MAX
);
8108 if (max_height
< height
)
8109 desired_height
= max_height
;
8113 if (desired_width
!= -1 && desired_height
== -1)
8114 /* w known, calculate h. */
8115 desired_height
= scale_image_size (desired_width
, width
, height
);
8117 if (desired_width
== -1 && desired_height
!= -1)
8118 /* h known, calculate w. */
8119 desired_width
= scale_image_size (desired_height
, height
, width
);
8121 *d_width
= desired_width
;
8122 *d_height
= desired_height
;
8125 static bool imagemagick_image_p (Lisp_Object
);
8126 static bool imagemagick_load (struct frame
*, struct image
*);
8127 static void imagemagick_clear_image (struct frame
*, struct image
*);
8129 /* Indices of image specification fields in imagemagick_format. */
8131 enum imagemagick_keyword_index
8139 IMAGEMAGICK_ALGORITHM
,
8140 IMAGEMAGICK_HEURISTIC_MASK
,
8142 IMAGEMAGICK_BACKGROUND
,
8145 IMAGEMAGICK_MAX_HEIGHT
,
8146 IMAGEMAGICK_MAX_WIDTH
,
8148 IMAGEMAGICK_ROTATION
,
8153 /* Vector of image_keyword structures describing the format
8154 of valid user-defined image specifications. */
8156 static struct image_keyword imagemagick_format
[IMAGEMAGICK_LAST
] =
8158 {":type", IMAGE_SYMBOL_VALUE
, 1},
8159 {":data", IMAGE_STRING_VALUE
, 0},
8160 {":file", IMAGE_STRING_VALUE
, 0},
8161 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8162 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8163 {":relief", IMAGE_INTEGER_VALUE
, 0},
8164 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8165 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8166 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8167 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
8168 {":height", IMAGE_INTEGER_VALUE
, 0},
8169 {":width", IMAGE_INTEGER_VALUE
, 0},
8170 {":max-height", IMAGE_INTEGER_VALUE
, 0},
8171 {":max-width", IMAGE_INTEGER_VALUE
, 0},
8172 {":format", IMAGE_SYMBOL_VALUE
, 0},
8173 {":rotation", IMAGE_NUMBER_VALUE
, 0},
8174 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
8177 #if defined HAVE_NTGUI && defined WINDOWSNT
8178 static bool init_imagemagick_functions (void);
8180 #define init_imagemagick_functions NULL
8183 /* Structure describing the image type for any image handled via
8186 static struct image_type imagemagick_type
=
8188 SYMBOL_INDEX (Qimagemagick
),
8189 imagemagick_image_p
,
8191 imagemagick_clear_image
,
8192 init_imagemagick_functions
,
8196 /* Free X resources of imagemagick image IMG which is used on frame F. */
8199 imagemagick_clear_image (struct frame
*f
,
8202 x_clear_image (f
, img
);
8205 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8206 this by calling parse_image_spec and supplying the keywords that
8207 identify the IMAGEMAGICK format. */
8210 imagemagick_image_p (Lisp_Object object
)
8212 struct image_keyword fmt
[IMAGEMAGICK_LAST
];
8213 memcpy (fmt
, imagemagick_format
, sizeof fmt
);
8215 if (!parse_image_spec (object
, fmt
, IMAGEMAGICK_LAST
, Qimagemagick
))
8218 /* Must specify either the :data or :file keyword. */
8219 return fmt
[IMAGEMAGICK_FILE
].count
+ fmt
[IMAGEMAGICK_DATA
].count
== 1;
8222 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8223 Therefore rename the function so it doesn't collide with ImageMagick. */
8224 #define DrawRectangle DrawRectangleGif
8225 #include <wand/MagickWand.h>
8227 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8228 Emacs seems to work fine with the hidden version, so unhide it. */
8229 #include <magick/version.h>
8230 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8231 extern WandExport
void PixelGetMagickColor (const PixelWand
*,
8232 MagickPixelPacket
*);
8235 /* Log ImageMagick error message.
8236 Useful when a ImageMagick function returns the status `MagickFalse'. */
8239 imagemagick_error (MagickWand
*wand
)
8242 ExceptionType severity
;
8244 description
= MagickGetException (wand
, &severity
);
8245 image_error ("ImageMagick error: %s", build_string (description
));
8246 MagickRelinquishMemory (description
);
8249 /* Possibly give ImageMagick some extra help to determine the image
8250 type by supplying a "dummy" filename based on the Content-Type. */
8253 imagemagick_filename_hint (Lisp_Object spec
, char hint_buffer
[MaxTextExtent
])
8255 Lisp_Object symbol
= intern ("image-format-suffixes");
8256 Lisp_Object val
= find_symbol_value (symbol
);
8262 format
= image_spec_value (spec
, intern (":format"), NULL
);
8263 val
= Fcar_safe (Fcdr_safe (Fassq (format
, val
)));
8264 if (! STRINGP (val
))
8267 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8268 as ImageMagick would ignore the extra bytes anyway. */
8269 snprintf (hint_buffer
, MaxTextExtent
, "/tmp/foo.%s", SSDATA (val
));
8273 /* Animated images (e.g., GIF89a) are composed from one "master image"
8274 (which is the first one, and then there's a number of images that
8275 follow. If following images have non-transparent colors, these are
8276 composed "on top" of the master image. So, in general, one has to
8277 compute ann the preceding images to be able to display a particular
8280 Computing all the preceding images is too slow, so we maintain a
8281 cache of previously computed images. We have to maintain a cache
8282 separate from the image cache, because the images may be scaled
8285 struct animation_cache
8289 struct timespec update_time
;
8290 struct animation_cache
*next
;
8291 char signature
[FLEXIBLE_ARRAY_MEMBER
];
8294 static struct animation_cache
*animation_cache
= NULL
;
8296 static struct animation_cache
*
8297 imagemagick_create_cache (char *signature
)
8299 struct animation_cache
*cache
8300 = xmalloc (offsetof (struct animation_cache
, signature
)
8301 + strlen (signature
) + 1);
8305 strcpy (cache
->signature
, signature
);
8309 /* Discard cached images that haven't been used for a minute. */
8311 imagemagick_prune_animation_cache (void)
8313 struct animation_cache
**pcache
= &animation_cache
;
8314 struct timespec old
= timespec_sub (current_timespec (),
8315 make_timespec (60, 0));
8319 struct animation_cache
*cache
= *pcache
;
8320 if (timespec_cmp (old
, cache
->update_time
) <= 0)
8321 pcache
= &cache
->next
;
8325 DestroyMagickWand (cache
->wand
);
8326 *pcache
= cache
->next
;
8332 static struct animation_cache
*
8333 imagemagick_get_animation_cache (MagickWand
*wand
)
8335 char *signature
= MagickGetImageSignature (wand
);
8336 struct animation_cache
*cache
;
8337 struct animation_cache
**pcache
= &animation_cache
;
8339 imagemagick_prune_animation_cache ();
8346 *pcache
= cache
= imagemagick_create_cache (signature
);
8349 if (strcmp (signature
, cache
->signature
) == 0)
8351 pcache
= &cache
->next
;
8354 DestroyString (signature
);
8355 cache
->update_time
= current_timespec ();
8360 imagemagick_compute_animated_image (MagickWand
*super_wand
, int ino
)
8363 MagickWand
*composite_wand
;
8364 size_t dest_width
, dest_height
;
8365 struct animation_cache
*cache
= imagemagick_get_animation_cache (super_wand
);
8367 MagickSetIteratorIndex (super_wand
, 0);
8369 if (ino
== 0 || cache
->wand
== NULL
|| cache
->index
> ino
)
8371 composite_wand
= MagickGetImage (super_wand
);
8373 DestroyMagickWand (cache
->wand
);
8376 composite_wand
= cache
->wand
;
8378 dest_height
= MagickGetImageHeight (composite_wand
);
8380 for (i
= max (1, cache
->index
+ 1); i
<= ino
; i
++)
8382 MagickWand
*sub_wand
;
8383 PixelIterator
*source_iterator
, *dest_iterator
;
8384 PixelWand
**source
, **dest
;
8385 size_t source_width
, source_height
;
8386 ssize_t source_left
, source_top
;
8387 MagickPixelPacket pixel
;
8388 DisposeType dispose
;
8389 ptrdiff_t lines
= 0;
8391 MagickSetIteratorIndex (super_wand
, i
);
8392 sub_wand
= MagickGetImage (super_wand
);
8394 MagickGetImagePage (sub_wand
, &source_width
, &source_height
,
8395 &source_left
, &source_top
);
8397 /* This flag says how to handle transparent pixels. */
8398 dispose
= MagickGetImageDispose (sub_wand
);
8400 source_iterator
= NewPixelIterator (sub_wand
);
8401 if (! source_iterator
)
8403 DestroyMagickWand (composite_wand
);
8404 DestroyMagickWand (sub_wand
);
8406 image_error ("Imagemagick pixel iterator creation failed");
8410 dest_iterator
= NewPixelIterator (composite_wand
);
8411 if (! dest_iterator
)
8413 DestroyMagickWand (composite_wand
);
8414 DestroyMagickWand (sub_wand
);
8415 DestroyPixelIterator (source_iterator
);
8417 image_error ("Imagemagick pixel iterator creation failed");
8421 /* The sub-image may not start at origin, so move the destination
8422 iterator to where the sub-image should start. */
8425 PixelSetIteratorRow (dest_iterator
, source_top
);
8429 while ((source
= PixelGetNextIteratorRow (source_iterator
, &source_width
))
8434 /* Sanity check. This shouldn't happen, but apparently
8435 does in some pictures. */
8436 if (++lines
>= dest_height
)
8439 dest
= PixelGetNextIteratorRow (dest_iterator
, &dest_width
);
8440 for (x
= 0; x
< source_width
; x
++)
8442 /* Sanity check. This shouldn't happen, but apparently
8443 also does in some pictures. */
8444 if (x
+ source_left
>= dest_width
)
8446 /* Normally we only copy over non-transparent pixels,
8447 but if the disposal method is "Background", then we
8448 copy over all pixels. */
8449 if (dispose
== BackgroundDispose
|| PixelGetAlpha (source
[x
]))
8451 PixelGetMagickColor (source
[x
], &pixel
);
8452 PixelSetMagickColor (dest
[x
+ source_left
], &pixel
);
8455 PixelSyncIterator (dest_iterator
);
8458 DestroyPixelIterator (source_iterator
);
8459 DestroyPixelIterator (dest_iterator
);
8460 DestroyMagickWand (sub_wand
);
8463 /* Cache a copy for the next iteration. The current wand will be
8464 destroyed by the caller. */
8465 cache
->wand
= CloneMagickWand (composite_wand
);
8468 return composite_wand
;
8472 /* Helper function for imagemagick_load, which does the actual loading
8473 given contents and size, apart from frame and image structures,
8474 passed from imagemagick_load. Uses librimagemagick to do most of
8475 the image processing.
8477 F is a pointer to the Emacs frame; IMG to the image structure to
8478 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8479 be parsed; SIZE is the number of bytes of data; and FILENAME is
8480 either the file name or the image data.
8482 Return true if successful. */
8485 imagemagick_load_image (struct frame
*f
, struct image
*img
,
8486 unsigned char *contents
, unsigned int size
,
8490 size_t image_width
, image_height
;
8491 MagickBooleanType status
;
8494 MagickWand
*image_wand
;
8495 PixelIterator
*iterator
;
8496 PixelWand
**pixels
, *bg_wand
= NULL
;
8497 MagickPixelPacket pixel
;
8502 int desired_width
, desired_height
;
8505 char hint_buffer
[MaxTextExtent
];
8506 char *filename_hint
= NULL
;
8508 /* Handle image index for image types who can contain more than one image.
8509 Interface :index is same as for GIF. First we "ping" the image to see how
8510 many sub-images it contains. Pinging is faster than loading the image to
8511 find out things about it. */
8513 /* Initialize the imagemagick environment. */
8514 MagickWandGenesis ();
8515 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
8516 ino
= INTEGERP (image
) ? XFASTINT (image
) : 0;
8517 image_wand
= NewMagickWand ();
8520 status
= MagickReadImage (image_wand
, filename
);
8523 filename_hint
= imagemagick_filename_hint (img
->spec
, hint_buffer
);
8524 MagickSetFilename (image_wand
, filename_hint
);
8525 status
= MagickReadImageBlob (image_wand
, contents
, size
);
8528 if (status
== MagickFalse
)
8530 imagemagick_error (image_wand
);
8531 DestroyMagickWand (image_wand
);
8535 if (ino
< 0 || ino
>= MagickGetNumberImages (image_wand
))
8537 image_error ("Invalid image number `%s' in image `%s'", image
, img
->spec
);
8538 DestroyMagickWand (image_wand
);
8542 if (MagickGetImageDelay (image_wand
) > 0)
8545 Fcons (make_float (MagickGetImageDelay (image_wand
) / 100.0),
8548 if (MagickGetNumberImages (image_wand
) > 1)
8551 Fcons (make_number (MagickGetNumberImages (image_wand
)),
8554 /* If we have an animated image, get the new wand based on the
8556 if (MagickGetNumberImages (image_wand
) > 1)
8558 MagickWand
*super_wand
= image_wand
;
8559 image_wand
= imagemagick_compute_animated_image (super_wand
, ino
);
8561 image_wand
= super_wand
;
8563 DestroyMagickWand (super_wand
);
8566 /* Retrieve the frame's background color, for use later. */
8569 Lisp_Object specified_bg
;
8571 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8572 if (!STRINGP (specified_bg
)
8573 || !x_defined_color (f
, SSDATA (specified_bg
), &bgcolor
, 0))
8574 x_query_frame_background_color (f
, &bgcolor
);
8576 bg_wand
= NewPixelWand ();
8577 PixelSetRed (bg_wand
, (double) bgcolor
.red
/ 65535);
8578 PixelSetGreen (bg_wand
, (double) bgcolor
.green
/ 65535);
8579 PixelSetBlue (bg_wand
, (double) bgcolor
.blue
/ 65535);
8582 compute_image_size (MagickGetImageWidth (image_wand
),
8583 MagickGetImageHeight (image_wand
),
8584 img
->spec
, &desired_width
, &desired_height
);
8586 if (desired_width
!= -1 && desired_height
!= -1)
8588 status
= MagickScaleImage (image_wand
, desired_width
, desired_height
);
8589 if (status
== MagickFalse
)
8591 image_error ("Imagemagick scale failed");
8592 imagemagick_error (image_wand
);
8593 goto imagemagick_error
;
8597 /* crop behaves similar to image slicing in Emacs but is more memory
8599 crop
= image_spec_value (img
->spec
, QCcrop
, NULL
);
8601 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8603 /* After some testing, it seems MagickCropImage is the fastest crop
8604 function in ImageMagick. This crop function seems to do less copying
8605 than the alternatives, but it still reads the entire image into memory
8606 before cropping, which is apparently difficult to avoid when using
8608 size_t crop_width
= XINT (XCAR (crop
));
8610 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8612 size_t crop_height
= XINT (XCAR (crop
));
8614 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8616 ssize_t crop_x
= XINT (XCAR (crop
));
8618 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8620 ssize_t crop_y
= XINT (XCAR (crop
));
8621 MagickCropImage (image_wand
, crop_width
, crop_height
,
8628 /* Furthermore :rotation. we need background color and angle for
8631 TODO background handling for rotation specified_bg =
8632 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8634 value
= image_spec_value (img
->spec
, QCrotation
, NULL
);
8637 rotation
= extract_float (value
);
8638 status
= MagickRotateImage (image_wand
, bg_wand
, rotation
);
8639 if (status
== MagickFalse
)
8641 image_error ("Imagemagick image rotate failed");
8642 imagemagick_error (image_wand
);
8643 goto imagemagick_error
;
8647 /* Set the canvas background color to the frame or specified
8648 background, and flatten the image. Note: as of ImageMagick
8649 6.6.0, SVG image transparency is not handled properly
8650 (e.g. etc/images/splash.svg shows a white background always). */
8652 MagickWand
*new_wand
;
8653 MagickSetImageBackgroundColor (image_wand
, bg_wand
);
8654 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8655 new_wand
= MagickMergeImageLayers (image_wand
, MergeLayer
);
8657 new_wand
= MagickFlattenImages (image_wand
);
8659 DestroyMagickWand (image_wand
);
8660 image_wand
= new_wand
;
8663 /* Finally we are done manipulating the image. Figure out the
8664 resulting width/height and transfer ownership to Emacs. */
8665 image_height
= MagickGetImageHeight (image_wand
);
8666 image_width
= MagickGetImageWidth (image_wand
);
8668 if (! (image_width
<= INT_MAX
&& image_height
<= INT_MAX
8669 && check_image_size (f
, image_width
, image_height
)))
8671 image_size_error ();
8672 goto imagemagick_error
;
8675 width
= image_width
;
8676 height
= image_height
;
8678 /* We can now get a valid pixel buffer from the imagemagick file, if all
8681 init_color_table ();
8683 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8684 if (imagemagick_render_type
!= 0)
8686 /* Magicexportimage is normally faster than pixelpushing. This
8687 method is also well tested. Some aspects of this method are
8688 ad-hoc and needs to be more researched. */
8689 int imagedepth
= 24; /*MagickGetImageDepth(image_wand);*/
8690 const char *exportdepth
= imagedepth
<= 8 ? "I" : "BGRP"; /*"RGBP";*/
8691 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8692 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, imagedepth
,
8695 #ifdef COLOR_TABLE_SUPPORT
8696 free_color_table ();
8698 image_error ("Imagemagick X bitmap allocation failure");
8699 goto imagemagick_error
;
8702 /* Oddly, the below code doesn't seem to work:*/
8703 /* switch(ximg->bitmap_unit){ */
8705 /* pixelwidth=CharPixel; */
8708 /* pixelwidth=ShortPixel; */
8711 /* pixelwidth=LongPixel; */
8715 Here im just guessing the format of the bitmap.
8716 happens to work fine for:
8719 seems about 3 times as fast as pixel pushing(not carefully measured)
8721 pixelwidth
= CharPixel
; /*??? TODO figure out*/
8722 MagickExportImagePixels (image_wand
, 0, 0, width
, height
,
8723 exportdepth
, pixelwidth
, ximg
->data
);
8726 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8728 size_t image_height
;
8729 MagickRealType color_scale
= 65535.0 / QuantumRange
;
8731 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8732 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
8735 #ifdef COLOR_TABLE_SUPPORT
8736 free_color_table ();
8738 image_error ("Imagemagick X bitmap allocation failure");
8739 goto imagemagick_error
;
8742 /* Copy imagemagick image to x with primitive yet robust pixel
8743 pusher loop. This has been tested a lot with many different
8746 /* Copy pixels from the imagemagick image structure to the x image map. */
8747 iterator
= NewPixelIterator (image_wand
);
8750 #ifdef COLOR_TABLE_SUPPORT
8751 free_color_table ();
8753 x_destroy_x_image (ximg
);
8754 image_error ("Imagemagick pixel iterator creation failed");
8755 goto imagemagick_error
;
8758 image_height
= MagickGetImageHeight (image_wand
);
8759 for (y
= 0; y
< image_height
; y
++)
8762 pixels
= PixelGetNextIteratorRow (iterator
, &row_width
);
8765 int xlim
= min (row_width
, width
);
8766 for (x
= 0; x
< xlim
; x
++)
8768 PixelGetMagickColor (pixels
[x
], &pixel
);
8769 XPutPixel (ximg
, x
, y
,
8770 lookup_rgb_color (f
,
8771 color_scale
* pixel
.red
,
8772 color_scale
* pixel
.green
,
8773 color_scale
* pixel
.blue
));
8776 DestroyPixelIterator (iterator
);
8779 #ifdef COLOR_TABLE_SUPPORT
8780 /* Remember colors allocated for this image. */
8781 img
->colors
= colors_in_color_table (&img
->ncolors
);
8782 free_color_table ();
8783 #endif /* COLOR_TABLE_SUPPORT */
8786 img
->height
= height
;
8788 /* Put ximg into the image. */
8789 image_put_x_image (f
, img
, ximg
, 0);
8791 /* Final cleanup. image_wand should be the only resource left. */
8792 DestroyMagickWand (image_wand
);
8793 if (bg_wand
) DestroyPixelWand (bg_wand
);
8795 /* `MagickWandTerminus' terminates the imagemagick environment. */
8796 MagickWandTerminus ();
8801 DestroyMagickWand (image_wand
);
8802 if (bg_wand
) DestroyPixelWand (bg_wand
);
8804 MagickWandTerminus ();
8805 /* TODO more cleanup. */
8806 image_error ("Error parsing IMAGEMAGICK image `%s'", img
->spec
);
8811 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8812 successful. this function will go into the imagemagick_type structure, and
8813 the prototype thus needs to be compatible with that structure. */
8816 imagemagick_load (struct frame
*f
, struct image
*img
)
8819 Lisp_Object file_name
;
8821 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8822 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8823 if (STRINGP (file_name
))
8825 Lisp_Object file
= x_find_image_file (file_name
);
8826 if (!STRINGP (file
))
8828 image_error ("Cannot find image file `%s'", file_name
);
8831 file
= ENCODE_FILE (file
);
8833 file
= ansi_encode_filename (file
);
8835 success_p
= imagemagick_load_image (f
, img
, 0, 0, SSDATA (file
));
8837 /* Else its not a file, its a lisp object. Load the image from a
8838 lisp object rather than a file. */
8843 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8844 if (!STRINGP (data
))
8846 image_error ("Invalid image data `%s'", data
);
8849 success_p
= imagemagick_load_image (f
, img
, SDATA (data
),
8850 SBYTES (data
), NULL
);
8856 DEFUN ("imagemagick-types", Fimagemagick_types
, Simagemagick_types
, 0, 0, 0,
8857 doc
: /* Return a list of image types supported by ImageMagick.
8858 Each entry in this list is a symbol named after an ImageMagick format
8859 tag. See the ImageMagick manual for a list of ImageMagick formats and
8860 their descriptions (http://www.imagemagick.org/script/formats.php).
8861 You can also try the shell command: `identify -list format'.
8863 Note that ImageMagick recognizes many file-types that Emacs does not
8864 recognize as images, such as C. See `imagemagick-types-enable'
8865 and `imagemagick-types-inhibit'. */)
8868 Lisp_Object typelist
= Qnil
;
8874 GetExceptionInfo(&ex
);
8875 imtypes
= GetMagickList ("*", &numf
, &ex
);
8876 DestroyExceptionInfo(&ex
);
8878 for (i
= 0; i
< numf
; i
++)
8880 Lisp_Object imagemagicktype
= intern (imtypes
[i
]);
8881 typelist
= Fcons (imagemagicktype
, typelist
);
8882 imtypes
[i
] = MagickRelinquishMemory (imtypes
[i
]);
8885 MagickRelinquishMemory (imtypes
);
8886 return Fnreverse (typelist
);
8889 #endif /* defined (HAVE_IMAGEMAGICK) */
8893 /***********************************************************************
8895 ***********************************************************************/
8899 /* Function prototypes. */
8901 static bool svg_image_p (Lisp_Object object
);
8902 static bool svg_load (struct frame
*f
, struct image
*img
);
8904 static bool svg_load_image (struct frame
*, struct image
*,
8905 unsigned char *, ptrdiff_t, char *);
8907 /* Indices of image specification fields in svg_format, below. */
8909 enum svg_keyword_index
8924 /* Vector of image_keyword structures describing the format
8925 of valid user-defined image specifications. */
8927 static const struct image_keyword svg_format
[SVG_LAST
] =
8929 {":type", IMAGE_SYMBOL_VALUE
, 1},
8930 {":data", IMAGE_STRING_VALUE
, 0},
8931 {":file", IMAGE_STRING_VALUE
, 0},
8932 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8933 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8934 {":relief", IMAGE_INTEGER_VALUE
, 0},
8935 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8936 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8937 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8938 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8941 # if defined HAVE_NTGUI && defined WINDOWSNT
8942 static bool init_svg_functions (void);
8944 #define init_svg_functions NULL
8947 /* Structure describing the image type `svg'. Its the same type of
8948 structure defined for all image formats, handled by emacs image
8949 functions. See struct image_type in dispextern.h. */
8951 static struct image_type svg_type
=
8953 SYMBOL_INDEX (Qsvg
),
8962 /* Return true if OBJECT is a valid SVG image specification. Do
8963 this by calling parse_image_spec and supplying the keywords that
8964 identify the SVG format. */
8967 svg_image_p (Lisp_Object object
)
8969 struct image_keyword fmt
[SVG_LAST
];
8970 memcpy (fmt
, svg_format
, sizeof fmt
);
8972 if (!parse_image_spec (object
, fmt
, SVG_LAST
, Qsvg
))
8975 /* Must specify either the :data or :file keyword. */
8976 return fmt
[SVG_FILE
].count
+ fmt
[SVG_DATA
].count
== 1;
8979 # include <librsvg/rsvg.h>
8983 /* SVG library functions. */
8984 DEF_DLL_FN (RsvgHandle
*, rsvg_handle_new
, (void));
8985 DEF_DLL_FN (void, rsvg_handle_get_dimensions
,
8986 (RsvgHandle
*, RsvgDimensionData
*));
8987 DEF_DLL_FN (gboolean
, rsvg_handle_write
,
8988 (RsvgHandle
*, const guchar
*, gsize
, GError
**));
8989 DEF_DLL_FN (gboolean
, rsvg_handle_close
, (RsvgHandle
*, GError
**));
8990 DEF_DLL_FN (GdkPixbuf
*, rsvg_handle_get_pixbuf
, (RsvgHandle
*));
8991 DEF_DLL_FN (void, rsvg_handle_set_base_uri
, (RsvgHandle
*, const char *));
8993 DEF_DLL_FN (int, gdk_pixbuf_get_width
, (const GdkPixbuf
*));
8994 DEF_DLL_FN (int, gdk_pixbuf_get_height
, (const GdkPixbuf
*));
8995 DEF_DLL_FN (guchar
*, gdk_pixbuf_get_pixels
, (const GdkPixbuf
*));
8996 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride
, (const GdkPixbuf
*));
8997 DEF_DLL_FN (GdkColorspace
, gdk_pixbuf_get_colorspace
, (const GdkPixbuf
*));
8998 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels
, (const GdkPixbuf
*));
8999 DEF_DLL_FN (gboolean
, gdk_pixbuf_get_has_alpha
, (const GdkPixbuf
*));
9000 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample
, (const GdkPixbuf
*));
9002 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9003 DEF_DLL_FN (void, g_type_init
, (void));
9005 DEF_DLL_FN (void, g_object_unref
, (gpointer
));
9006 DEF_DLL_FN (void, g_error_free
, (GError
*));
9009 init_svg_functions (void)
9011 HMODULE library
, gdklib
= NULL
, glib
= NULL
, gobject
= NULL
;
9013 if (!(glib
= w32_delayed_load (Qglib
))
9014 || !(gobject
= w32_delayed_load (Qgobject
))
9015 || !(gdklib
= w32_delayed_load (Qgdk_pixbuf
))
9016 || !(library
= w32_delayed_load (Qsvg
)))
9018 if (gdklib
) FreeLibrary (gdklib
);
9019 if (gobject
) FreeLibrary (gobject
);
9020 if (glib
) FreeLibrary (glib
);
9024 LOAD_DLL_FN (library
, rsvg_handle_new
);
9025 LOAD_DLL_FN (library
, rsvg_handle_get_dimensions
);
9026 LOAD_DLL_FN (library
, rsvg_handle_write
);
9027 LOAD_DLL_FN (library
, rsvg_handle_close
);
9028 LOAD_DLL_FN (library
, rsvg_handle_get_pixbuf
);
9029 LOAD_DLL_FN (library
, rsvg_handle_set_base_uri
);
9031 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_width
);
9032 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_height
);
9033 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_pixels
);
9034 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_rowstride
);
9035 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_colorspace
);
9036 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_n_channels
);
9037 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_has_alpha
);
9038 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_bits_per_sample
);
9040 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9041 LOAD_DLL_FN (gobject
, g_type_init
);
9043 LOAD_DLL_FN (gobject
, g_object_unref
);
9044 LOAD_DLL_FN (glib
, g_error_free
);
9049 /* The following aliases for library functions allow dynamic loading
9050 to be used on some platforms. */
9052 # undef gdk_pixbuf_get_bits_per_sample
9053 # undef gdk_pixbuf_get_colorspace
9054 # undef gdk_pixbuf_get_has_alpha
9055 # undef gdk_pixbuf_get_height
9056 # undef gdk_pixbuf_get_n_channels
9057 # undef gdk_pixbuf_get_pixels
9058 # undef gdk_pixbuf_get_rowstride
9059 # undef gdk_pixbuf_get_width
9060 # undef g_error_free
9061 # undef g_object_unref
9063 # undef rsvg_handle_close
9064 # undef rsvg_handle_get_dimensions
9065 # undef rsvg_handle_get_pixbuf
9066 # undef rsvg_handle_new
9067 # undef rsvg_handle_set_base_uri
9068 # undef rsvg_handle_write
9070 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9071 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9072 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9073 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9074 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9075 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9076 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9077 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9078 # define g_error_free fn_g_error_free
9079 # define g_object_unref fn_g_object_unref
9080 # define g_type_init fn_g_type_init
9081 # define rsvg_handle_close fn_rsvg_handle_close
9082 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9083 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9084 # define rsvg_handle_new fn_rsvg_handle_new
9085 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9086 # define rsvg_handle_write fn_rsvg_handle_write
9088 # endif /* !WINDOWSNT */
9090 /* Load SVG image IMG for use on frame F. Value is true if
9094 svg_load (struct frame
*f
, struct image
*img
)
9097 Lisp_Object file_name
;
9099 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9100 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
9101 if (STRINGP (file_name
))
9104 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
9105 if (!STRINGP (file
))
9107 image_error ("Cannot find image file `%s'", file_name
);
9111 /* Read the entire file into memory. */
9113 unsigned char *contents
= slurp_file (fd
, &size
);
9114 if (contents
== NULL
)
9116 image_error ("Error loading SVG image `%s'", file
);
9119 /* If the file was slurped into memory properly, parse it. */
9120 success_p
= svg_load_image (f
, img
, contents
, size
,
9121 SSDATA (ENCODE_FILE (file
)));
9124 /* Else its not a file, its a lisp object. Load the image from a
9125 lisp object rather than a file. */
9128 Lisp_Object data
, original_filename
;
9130 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
9131 if (!STRINGP (data
))
9133 image_error ("Invalid image data `%s'", data
);
9136 original_filename
= BVAR (current_buffer
, filename
);
9137 success_p
= svg_load_image (f
, img
, SDATA (data
), SBYTES (data
),
9138 (NILP (original_filename
) ? NULL
9139 : SSDATA (original_filename
)));
9145 /* svg_load_image is a helper function for svg_load, which does the
9146 actual loading given contents and size, apart from frame and image
9147 structures, passed from svg_load.
9149 Uses librsvg to do most of the image processing.
9151 Returns true when successful. */
9153 svg_load_image (struct frame
*f
, /* Pointer to emacs frame structure. */
9154 struct image
*img
, /* Pointer to emacs image structure. */
9155 unsigned char *contents
, /* String containing the SVG XML data to be parsed. */
9156 ptrdiff_t size
, /* Size of data in bytes. */
9157 char *filename
) /* Name of SVG file being loaded. */
9159 RsvgHandle
*rsvg_handle
;
9160 RsvgDimensionData dimension_data
;
9165 const guint8
*pixels
;
9168 Lisp_Object specified_bg
;
9173 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9174 /* g_type_init is a glib function that must be called prior to
9175 using gnome type library functions (obsolete since 2.36.0). */
9179 /* Make a handle to a new rsvg object. */
9180 rsvg_handle
= rsvg_handle_new ();
9182 /* Set base_uri for properly handling referenced images (via 'href').
9183 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9184 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9186 rsvg_handle_set_base_uri(rsvg_handle
, filename
);
9188 /* Parse the contents argument and fill in the rsvg_handle. */
9189 rsvg_handle_write (rsvg_handle
, contents
, size
, &err
);
9190 if (err
) goto rsvg_error
;
9192 /* The parsing is complete, rsvg_handle is ready to used, close it
9193 for further writes. */
9194 rsvg_handle_close (rsvg_handle
, &err
);
9195 if (err
) goto rsvg_error
;
9197 rsvg_handle_get_dimensions (rsvg_handle
, &dimension_data
);
9198 if (! check_image_size (f
, dimension_data
.width
, dimension_data
.height
))
9200 image_size_error ();
9204 /* We can now get a valid pixel buffer from the svg file, if all
9206 pixbuf
= rsvg_handle_get_pixbuf (rsvg_handle
);
9207 if (!pixbuf
) goto rsvg_error
;
9208 g_object_unref (rsvg_handle
);
9210 /* Extract some meta data from the svg handle. */
9211 width
= gdk_pixbuf_get_width (pixbuf
);
9212 height
= gdk_pixbuf_get_height (pixbuf
);
9213 pixels
= gdk_pixbuf_get_pixels (pixbuf
);
9214 rowstride
= gdk_pixbuf_get_rowstride (pixbuf
);
9216 /* Validate the svg meta data. */
9217 eassert (gdk_pixbuf_get_colorspace (pixbuf
) == GDK_COLORSPACE_RGB
);
9218 eassert (gdk_pixbuf_get_n_channels (pixbuf
) == 4);
9219 eassert (gdk_pixbuf_get_has_alpha (pixbuf
));
9220 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf
) == 8);
9224 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
9226 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
9228 for (y
= 0; y
< height
; ++y
)
9230 const guchar
*iconptr
= pixels
+ y
* rowstride
;
9231 uint32_t *dataptr
= (uint32_t *) (data
+ y
* rowstride
);
9234 for (x
= 0; x
< width
; ++x
)
9236 if (iconptr
[3] == 0)
9239 *dataptr
= (iconptr
[0] << 16)
9242 | (iconptr
[3] << 24);
9249 create_cairo_image_surface (img
, data
, width
, height
);
9250 g_object_unref (pixbuf
);
9253 /* Try to create a x pixmap to hold the svg pixmap. */
9254 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
9256 g_object_unref (pixbuf
);
9260 init_color_table ();
9262 /* Handle alpha channel by combining the image with a background
9264 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
9265 if (!STRINGP (specified_bg
)
9266 || !x_defined_color (f
, SSDATA (specified_bg
), &background
, 0))
9267 x_query_frame_background_color (f
, &background
);
9269 /* SVG pixmaps specify transparency in the last byte, so right
9270 shift 8 bits to get rid of it, since emacs doesn't support
9272 background
.red
>>= 8;
9273 background
.green
>>= 8;
9274 background
.blue
>>= 8;
9276 /* This loop handles opacity values, since Emacs assumes
9277 non-transparent images. Each pixel must be "flattened" by
9278 calculating the resulting color, given the transparency of the
9279 pixel, and the image background color. */
9280 for (y
= 0; y
< height
; ++y
)
9282 for (x
= 0; x
< width
; ++x
)
9292 opacity
= *pixels
++;
9294 red
= ((red
* opacity
)
9295 + (background
.red
* ((1 << 8) - opacity
)));
9296 green
= ((green
* opacity
)
9297 + (background
.green
* ((1 << 8) - opacity
)));
9298 blue
= ((blue
* opacity
)
9299 + (background
.blue
* ((1 << 8) - opacity
)));
9301 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, red
, green
, blue
));
9304 pixels
+= rowstride
- 4 * width
;
9307 #ifdef COLOR_TABLE_SUPPORT
9308 /* Remember colors allocated for this image. */
9309 img
->colors
= colors_in_color_table (&img
->ncolors
);
9310 free_color_table ();
9311 #endif /* COLOR_TABLE_SUPPORT */
9313 g_object_unref (pixbuf
);
9316 img
->height
= height
;
9318 /* Maybe fill in the background field while we have ximg handy.
9319 Casting avoids a GCC warning. */
9320 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
9322 /* Put ximg into the image. */
9323 image_put_x_image (f
, img
, ximg
, 0);
9324 #endif /* ! USE_CAIRO */
9329 g_object_unref (rsvg_handle
);
9330 /* FIXME: Use error->message so the user knows what is the actual
9331 problem with the image. */
9332 image_error ("Error parsing SVG image `%s'", img
->spec
);
9337 #endif /* defined (HAVE_RSVG) */
9342 /***********************************************************************
9344 ***********************************************************************/
9346 #ifdef HAVE_X_WINDOWS
9347 #define HAVE_GHOSTSCRIPT 1
9348 #endif /* HAVE_X_WINDOWS */
9350 #ifdef HAVE_GHOSTSCRIPT
9352 static bool gs_image_p (Lisp_Object object
);
9353 static bool gs_load (struct frame
*f
, struct image
*img
);
9354 static void gs_clear_image (struct frame
*f
, struct image
*img
);
9356 /* Indices of image specification fields in gs_format, below. */
9358 enum gs_keyword_index
9376 /* Vector of image_keyword structures describing the format
9377 of valid user-defined image specifications. */
9379 static const struct image_keyword gs_format
[GS_LAST
] =
9381 {":type", IMAGE_SYMBOL_VALUE
, 1},
9382 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9383 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9384 {":file", IMAGE_STRING_VALUE
, 1},
9385 {":loader", IMAGE_FUNCTION_VALUE
, 0},
9386 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE
, 1},
9387 {":ascent", IMAGE_ASCENT_VALUE
, 0},
9388 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
9389 {":relief", IMAGE_INTEGER_VALUE
, 0},
9390 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9391 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9392 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9393 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
9396 /* Structure describing the image type `ghostscript'. */
9398 static struct image_type gs_type
=
9400 SYMBOL_INDEX (Qpostscript
),
9409 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9412 gs_clear_image (struct frame
*f
, struct image
*img
)
9414 x_clear_image (f
, img
);
9418 /* Return true if OBJECT is a valid Ghostscript image
9422 gs_image_p (Lisp_Object object
)
9424 struct image_keyword fmt
[GS_LAST
];
9428 memcpy (fmt
, gs_format
, sizeof fmt
);
9430 if (!parse_image_spec (object
, fmt
, GS_LAST
, Qpostscript
))
9433 /* Bounding box must be a list or vector containing 4 integers. */
9434 tem
= fmt
[GS_BOUNDING_BOX
].value
;
9437 for (i
= 0; i
< 4; ++i
, tem
= XCDR (tem
))
9438 if (!CONSP (tem
) || !INTEGERP (XCAR (tem
)))
9443 else if (VECTORP (tem
))
9445 if (ASIZE (tem
) != 4)
9447 for (i
= 0; i
< 4; ++i
)
9448 if (!INTEGERP (AREF (tem
, i
)))
9458 /* Load Ghostscript image IMG for use on frame F. Value is true
9462 gs_load (struct frame
*f
, struct image
*img
)
9464 uprintmax_t printnum1
, printnum2
;
9465 char buffer
[sizeof " " + INT_STRLEN_BOUND (printmax_t
)];
9466 Lisp_Object window_and_pixmap_id
= Qnil
, loader
, pt_height
, pt_width
;
9468 double in_width
, in_height
;
9469 Lisp_Object pixel_colors
= Qnil
;
9471 /* Compute pixel size of pixmap needed from the given size in the
9472 image specification. Sizes in the specification are in pt. 1 pt
9473 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9475 pt_width
= image_spec_value (img
->spec
, QCpt_width
, NULL
);
9476 in_width
= INTEGERP (pt_width
) ? XFASTINT (pt_width
) / 72.0 : 0;
9477 in_width
*= FRAME_RES_X (f
);
9478 pt_height
= image_spec_value (img
->spec
, QCpt_height
, NULL
);
9479 in_height
= INTEGERP (pt_height
) ? XFASTINT (pt_height
) / 72.0 : 0;
9480 in_height
*= FRAME_RES_Y (f
);
9482 if (! (in_width
<= INT_MAX
&& in_height
<= INT_MAX
9483 && check_image_size (f
, in_width
, in_height
)))
9485 image_size_error ();
9488 img
->width
= in_width
;
9489 img
->height
= in_height
;
9491 /* Create the pixmap. */
9492 eassert (img
->pixmap
== NO_PIXMAP
);
9494 if (x_check_image_size (0, img
->width
, img
->height
))
9496 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9498 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
9499 img
->width
, img
->height
,
9500 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)));
9506 image_error ("Unable to create pixmap for `%s'" , img
->spec
);
9510 /* Call the loader to fill the pixmap. It returns a process object
9511 if successful. We do not record_unwind_protect here because
9512 other places in redisplay like calling window scroll functions
9513 don't either. Let the Lisp loader use `unwind-protect' instead. */
9514 printnum1
= FRAME_X_WINDOW (f
);
9515 printnum2
= img
->pixmap
;
9516 window_and_pixmap_id
9517 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9519 printnum1
= FRAME_FOREGROUND_PIXEL (f
);
9520 printnum2
= FRAME_BACKGROUND_PIXEL (f
);
9522 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9524 XSETFRAME (frame
, f
);
9525 loader
= image_spec_value (img
->spec
, QCloader
, NULL
);
9527 loader
= intern ("gs-load-image");
9529 img
->lisp_data
= call6 (loader
, frame
, img
->spec
,
9530 make_number (img
->width
),
9531 make_number (img
->height
),
9532 window_and_pixmap_id
,
9534 return PROCESSP (img
->lisp_data
);
9538 /* Kill the Ghostscript process that was started to fill PIXMAP on
9539 frame F. Called from XTread_socket when receiving an event
9540 telling Emacs that Ghostscript has finished drawing. */
9543 x_kill_gs_process (Pixmap pixmap
, struct frame
*f
)
9545 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
9550 /* Find the image containing PIXMAP. */
9551 for (i
= 0; i
< c
->used
; ++i
)
9552 if (c
->images
[i
]->pixmap
== pixmap
)
9555 /* Should someone in between have cleared the image cache, for
9556 instance, give up. */
9560 /* Kill the GS process. We should have found PIXMAP in the image
9561 cache and its image should contain a process object. */
9563 eassert (PROCESSP (img
->lisp_data
));
9564 Fkill_process (img
->lisp_data
, Qnil
);
9565 img
->lisp_data
= Qnil
;
9567 #if defined (HAVE_X_WINDOWS)
9569 /* On displays with a mutable colormap, figure out the colors
9570 allocated for the image by looking at the pixels of an XImage for
9572 class = FRAME_X_VISUAL (f
)->class;
9573 if (class != StaticColor
&& class != StaticGray
&& class != TrueColor
)
9579 /* Try to get an XImage for img->pixmep. */
9580 ximg
= XGetImage (FRAME_X_DISPLAY (f
), img
->pixmap
,
9581 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
9586 /* Initialize the color table. */
9587 init_color_table ();
9589 /* For each pixel of the image, look its color up in the
9590 color table. After having done so, the color table will
9591 contain an entry for each color used by the image. */
9592 #ifdef COLOR_TABLE_SUPPORT
9593 for (y
= 0; y
< img
->height
; ++y
)
9594 for (x
= 0; x
< img
->width
; ++x
)
9596 unsigned long pixel
= XGetPixel (ximg
, x
, y
);
9598 lookup_pixel_color (f
, pixel
);
9601 /* Record colors in the image. Free color table and XImage. */
9602 img
->colors
= colors_in_color_table (&img
->ncolors
);
9603 free_color_table ();
9605 XDestroyImage (ximg
);
9607 #if 0 /* This doesn't seem to be the case. If we free the colors
9608 here, we get a BadAccess later in x_clear_image when
9609 freeing the colors. */
9610 /* We have allocated colors once, but Ghostscript has also
9611 allocated colors on behalf of us. So, to get the
9612 reference counts right, free them once. */
9614 x_free_colors (f
, img
->colors
, img
->ncolors
);
9618 image_error ("Cannot get X image of `%s'; colors will not be freed",
9623 #endif /* HAVE_X_WINDOWS */
9625 /* Now that we have the pixmap, compute mask and transform the
9626 image if requested. */
9628 postprocess_image (f
, img
);
9632 #endif /* HAVE_GHOSTSCRIPT */
9635 /***********************************************************************
9637 ***********************************************************************/
9641 DEFUN ("imagep", Fimagep
, Simagep
, 1, 1, 0,
9642 doc
: /* Value is non-nil if SPEC is a valid image specification. */)
9645 return valid_image_p (spec
) ? Qt
: Qnil
;
9649 DEFUN ("lookup-image", Flookup_image
, Slookup_image
, 1, 1, 0,
9655 if (valid_image_p (spec
))
9656 id
= lookup_image (SELECTED_FRAME (), spec
);
9659 return make_number (id
);
9662 #endif /* GLYPH_DEBUG */
9665 /***********************************************************************
9667 ***********************************************************************/
9669 DEFUN ("init-image-library", Finit_image_library
, Sinit_image_library
, 1, 1, 0,
9670 doc
: /* Initialize image library implementing image type TYPE.
9671 Return non-nil if TYPE is a supported image type.
9673 If image libraries are loaded dynamically (currently only the case on
9674 MS-Windows), load the library for TYPE if it is not yet loaded, using
9675 the library file(s) specified by `dynamic-library-alist'. */)
9678 return lookup_image_type (type
) ? Qt
: Qnil
;
9681 /* Look up image type TYPE, and return a pointer to its image_type
9682 structure. Return 0 if TYPE is not a known image type. */
9684 static struct image_type
*
9685 lookup_image_type (Lisp_Object type
)
9687 /* Types pbm and xbm are built-in and always available. */
9688 if (EQ (type
, Qpbm
))
9689 return define_image_type (&pbm_type
);
9691 if (EQ (type
, Qxbm
))
9692 return define_image_type (&xbm_type
);
9694 #if defined (HAVE_XPM) || defined (HAVE_NS)
9695 if (EQ (type
, Qxpm
))
9696 return define_image_type (&xpm_type
);
9699 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9700 if (EQ (type
, Qjpeg
))
9701 return define_image_type (&jpeg_type
);
9704 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9705 if (EQ (type
, Qtiff
))
9706 return define_image_type (&tiff_type
);
9709 #if defined (HAVE_GIF) || defined (HAVE_NS)
9710 if (EQ (type
, Qgif
))
9711 return define_image_type (&gif_type
);
9714 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9715 if (EQ (type
, Qpng
))
9716 return define_image_type (&png_type
);
9719 #if defined (HAVE_RSVG)
9720 if (EQ (type
, Qsvg
))
9721 return define_image_type (&svg_type
);
9724 #if defined (HAVE_IMAGEMAGICK)
9725 if (EQ (type
, Qimagemagick
))
9726 return define_image_type (&imagemagick_type
);
9729 #ifdef HAVE_GHOSTSCRIPT
9730 if (EQ (type
, Qpostscript
))
9731 return define_image_type (&gs_type
);
9737 /* Reset image_types before dumping.
9738 Called from Fdump_emacs. */
9741 reset_image_types (void)
9745 struct image_type
*next
= image_types
->next
;
9746 xfree (image_types
);
9752 syms_of_image (void)
9754 /* Initialize this only once; it will be reset before dumping. */
9757 /* Must be defined now because we're going to update it below, while
9758 defining the supported image types. */
9759 DEFVAR_LISP ("image-types", Vimage_types
,
9760 doc
: /* List of potentially supported image types.
9761 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9762 To check whether it is really supported, use `image-type-available-p'. */);
9763 Vimage_types
= Qnil
;
9765 DEFVAR_LISP ("max-image-size", Vmax_image_size
,
9766 doc
: /* Maximum size of images.
9767 Emacs will not load an image into memory if its pixel width or
9768 pixel height exceeds this limit.
9770 If the value is an integer, it directly specifies the maximum
9771 image height and width, measured in pixels. If it is a floating
9772 point number, it specifies the maximum image height and width
9773 as a ratio to the frame height and width. If the value is
9774 non-numeric, there is no explicit limit on the size of images. */);
9775 Vmax_image_size
= make_float (MAX_IMAGE_SIZE
);
9777 /* Other symbols. */
9778 DEFSYM (Qcount
, "count");
9779 DEFSYM (Qextension_data
, "extension-data");
9780 DEFSYM (Qdelay
, "delay");
9783 DEFSYM (QCascent
, ":ascent");
9784 DEFSYM (QCmargin
, ":margin");
9785 DEFSYM (QCrelief
, ":relief");
9786 DEFSYM (QCconversion
, ":conversion");
9787 DEFSYM (QCcolor_symbols
, ":color-symbols");
9788 DEFSYM (QCheuristic_mask
, ":heuristic-mask");
9789 DEFSYM (QCindex
, ":index");
9790 DEFSYM (QCcrop
, ":crop");
9791 DEFSYM (QCrotation
, ":rotation");
9792 DEFSYM (QCmatrix
, ":matrix");
9793 DEFSYM (QCcolor_adjustment
, ":color-adjustment");
9794 DEFSYM (QCmask
, ":mask");
9796 /* Other symbols. */
9797 DEFSYM (Qlaplace
, "laplace");
9798 DEFSYM (Qemboss
, "emboss");
9799 DEFSYM (Qedge_detection
, "edge-detection");
9800 DEFSYM (Qheuristic
, "heuristic");
9802 DEFSYM (Qpostscript
, "postscript");
9803 DEFSYM (QCmax_width
, ":max-width");
9804 DEFSYM (QCmax_height
, ":max-height");
9805 #ifdef HAVE_GHOSTSCRIPT
9806 ADD_IMAGE_TYPE (Qpostscript
);
9807 DEFSYM (QCloader
, ":loader");
9808 DEFSYM (QCpt_width
, ":pt-width");
9809 DEFSYM (QCpt_height
, ":pt-height");
9810 #endif /* HAVE_GHOSTSCRIPT */
9813 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9814 or -1 if no PNG/GIF support was compiled in. This is tested by
9815 w32-win.el to correctly set up the alist used to search for the
9816 respective image libraries. */
9817 DEFSYM (Qlibpng_version
, "libpng-version");
9818 Fset (Qlibpng_version
,
9820 make_number (PNG_LIBPNG_VER
)
9825 DEFSYM (Qlibgif_version
, "libgif-version");
9826 Fset (Qlibgif_version
,
9828 make_number (GIFLIB_MAJOR
* 10000
9829 + GIFLIB_MINOR
* 100
9835 DEFSYM (Qlibjpeg_version
, "libjpeg-version");
9836 Fset (Qlibjpeg_version
,
9838 make_number (JPEG_LIB_VERSION
)
9845 DEFSYM (Qpbm
, "pbm");
9846 ADD_IMAGE_TYPE (Qpbm
);
9848 DEFSYM (Qxbm
, "xbm");
9849 ADD_IMAGE_TYPE (Qxbm
);
9851 #if defined (HAVE_XPM) || defined (HAVE_NS)
9852 DEFSYM (Qxpm
, "xpm");
9853 ADD_IMAGE_TYPE (Qxpm
);
9856 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9857 DEFSYM (Qjpeg
, "jpeg");
9858 ADD_IMAGE_TYPE (Qjpeg
);
9861 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9862 DEFSYM (Qtiff
, "tiff");
9863 ADD_IMAGE_TYPE (Qtiff
);
9866 #if defined (HAVE_GIF) || defined (HAVE_NS)
9867 DEFSYM (Qgif
, "gif");
9868 ADD_IMAGE_TYPE (Qgif
);
9871 #if defined (HAVE_PNG) || defined (HAVE_NS)
9872 DEFSYM (Qpng
, "png");
9873 ADD_IMAGE_TYPE (Qpng
);
9876 #if defined (HAVE_IMAGEMAGICK)
9877 DEFSYM (Qimagemagick
, "imagemagick");
9878 ADD_IMAGE_TYPE (Qimagemagick
);
9881 #if defined (HAVE_RSVG)
9882 DEFSYM (Qsvg
, "svg");
9883 ADD_IMAGE_TYPE (Qsvg
);
9885 /* Other libraries used directly by svg code. */
9886 DEFSYM (Qgdk_pixbuf
, "gdk-pixbuf");
9887 DEFSYM (Qglib
, "glib");
9888 DEFSYM (Qgobject
, "gobject");
9889 #endif /* HAVE_NTGUI */
9890 #endif /* HAVE_RSVG */
9892 defsubr (&Sinit_image_library
);
9893 #ifdef HAVE_IMAGEMAGICK
9894 defsubr (&Simagemagick_types
);
9896 defsubr (&Sclear_image_cache
);
9897 defsubr (&Simage_flush
);
9898 defsubr (&Simage_size
);
9899 defsubr (&Simage_mask_p
);
9900 defsubr (&Simage_metadata
);
9904 defsubr (&Slookup_image
);
9907 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images
,
9908 doc
: /* Non-nil means always draw a cross over disabled images.
9909 Disabled images are those having a `:conversion disabled' property.
9910 A cross is always drawn on black & white displays. */);
9911 cross_disabled_images
= 0;
9913 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path
,
9914 doc
: /* List of directories to search for window system bitmap files. */);
9915 Vx_bitmap_file_path
= decode_env_path (0, PATH_BITMAPS
, 0);
9917 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay
,
9918 doc
: /* Maximum time after which images are removed from the cache.
9919 When an image has not been displayed this many seconds, Emacs
9920 automatically removes it from the image cache. If the cache contains
9921 a large number of images, the actual eviction time may be shorter.
9922 The value can also be nil, meaning the cache is never cleared.
9924 The function `clear-image-cache' disregards this variable. */);
9925 Vimage_cache_eviction_delay
= make_number (300);
9926 #ifdef HAVE_IMAGEMAGICK
9927 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type
,
9928 doc
: /* Integer indicating which ImageMagick rendering method to use.
9930 0 -- the default method (pixel pushing)
9931 1 -- a newer method ("MagickExportImagePixels") that may perform
9932 better (speed etc) in some cases, but has not been as thoroughly
9933 tested with Emacs as the default method. This method requires
9934 ImageMagick version 6.4.6 (approximately) or later.
9936 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9937 imagemagick_render_type
= 0;