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 AUTO_STRING (max_image_size_name
, "max-image-size");
651 image_error ("Invalid image size (see `%s')", max_image_size_name
);
655 /***********************************************************************
657 ***********************************************************************/
659 enum image_value_type
661 IMAGE_DONT_CHECK_VALUE_TYPE
,
663 IMAGE_STRING_OR_NIL_VALUE
,
665 IMAGE_POSITIVE_INTEGER_VALUE
,
666 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
,
667 IMAGE_NON_NEGATIVE_INTEGER_VALUE
,
670 IMAGE_FUNCTION_VALUE
,
675 /* Structure used when parsing image specifications. */
679 /* Name of keyword. */
682 /* The type of value allowed. */
683 enum image_value_type type
;
685 /* True means key must be present. */
688 /* Used to recognize duplicate keywords in a property list. */
691 /* The value that was found. */
696 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
697 has the format (image KEYWORD VALUE ...). One of the keyword/
698 value pairs must be `:type TYPE'. KEYWORDS is a vector of
699 image_keywords structures of size NKEYWORDS describing other
700 allowed keyword/value pairs. Value is true if SPEC is valid. */
703 parse_image_spec (Lisp_Object spec
, struct image_keyword
*keywords
,
704 int nkeywords
, Lisp_Object type
)
713 while (CONSP (plist
))
715 Lisp_Object key
, value
;
717 /* First element of a pair must be a symbol. */
719 plist
= XCDR (plist
);
723 /* There must follow a value. */
726 value
= XCAR (plist
);
727 plist
= XCDR (plist
);
729 /* Find key in KEYWORDS. Error if not found. */
730 for (i
= 0; i
< nkeywords
; ++i
)
731 if (strcmp (keywords
[i
].name
, SSDATA (SYMBOL_NAME (key
))) == 0)
737 /* Record that we recognized the keyword. If a keywords
738 was found more than once, it's an error. */
739 keywords
[i
].value
= value
;
740 if (keywords
[i
].count
> 1)
744 /* Check type of value against allowed type. */
745 switch (keywords
[i
].type
)
747 case IMAGE_STRING_VALUE
:
748 if (!STRINGP (value
))
752 case IMAGE_STRING_OR_NIL_VALUE
:
753 if (!STRINGP (value
) && !NILP (value
))
757 case IMAGE_SYMBOL_VALUE
:
758 if (!SYMBOLP (value
))
762 case IMAGE_POSITIVE_INTEGER_VALUE
:
763 if (! RANGED_INTEGERP (1, value
, INT_MAX
))
767 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
:
768 if (RANGED_INTEGERP (0, value
, INT_MAX
))
771 && RANGED_INTEGERP (0, XCAR (value
), INT_MAX
)
772 && RANGED_INTEGERP (0, XCDR (value
), INT_MAX
))
776 case IMAGE_ASCENT_VALUE
:
777 if (SYMBOLP (value
) && EQ (value
, Qcenter
))
779 else if (RANGED_INTEGERP (0, value
, 100))
783 case IMAGE_NON_NEGATIVE_INTEGER_VALUE
:
784 /* Unlike the other integer-related cases, this one does not
785 verify that VALUE fits in 'int'. This is because callers
787 if (!INTEGERP (value
) || XINT (value
) < 0)
791 case IMAGE_DONT_CHECK_VALUE_TYPE
:
794 case IMAGE_FUNCTION_VALUE
:
795 value
= indirect_function (value
);
796 if (!NILP (Ffunctionp (value
)))
800 case IMAGE_NUMBER_VALUE
:
801 if (! NUMBERP (value
))
805 case IMAGE_INTEGER_VALUE
:
806 if (! TYPE_RANGED_INTEGERP (int, value
))
810 case IMAGE_BOOL_VALUE
:
811 if (!NILP (value
) && !EQ (value
, Qt
))
820 if (EQ (key
, QCtype
) && !EQ (type
, value
))
824 /* Check that all mandatory fields are present. */
825 for (i
= 0; i
< nkeywords
; ++i
)
826 if (keywords
[i
].mandatory_p
&& keywords
[i
].count
== 0)
833 /* Return the value of KEY in image specification SPEC. Value is nil
834 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
835 was found in SPEC. */
838 image_spec_value (Lisp_Object spec
, Lisp_Object key
, bool *found
)
842 eassert (valid_image_p (spec
));
844 for (tail
= XCDR (spec
);
845 CONSP (tail
) && CONSP (XCDR (tail
));
846 tail
= XCDR (XCDR (tail
)))
848 if (EQ (XCAR (tail
), key
))
852 return XCAR (XCDR (tail
));
862 DEFUN ("image-size", Fimage_size
, Simage_size
, 1, 3, 0,
863 doc
: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
864 PIXELS non-nil means return the size in pixels, otherwise return the
865 size in canonical character units.
866 FRAME is the frame on which the image will be displayed. FRAME nil
867 or omitted means use the selected frame. */)
868 (Lisp_Object spec
, Lisp_Object pixels
, Lisp_Object frame
)
873 if (valid_image_p (spec
))
875 struct frame
*f
= decode_window_system_frame (frame
);
876 ptrdiff_t id
= lookup_image (f
, spec
);
877 struct image
*img
= IMAGE_FROM_ID (f
, id
);
878 int width
= img
->width
+ 2 * img
->hmargin
;
879 int height
= img
->height
+ 2 * img
->vmargin
;
882 size
= Fcons (make_float ((double) width
/ FRAME_COLUMN_WIDTH (f
)),
883 make_float ((double) height
/ FRAME_LINE_HEIGHT (f
)));
885 size
= Fcons (make_number (width
), make_number (height
));
888 error ("Invalid image specification");
894 DEFUN ("image-mask-p", Fimage_mask_p
, Simage_mask_p
, 1, 2, 0,
895 doc
: /* Return t if image SPEC has a mask bitmap.
896 FRAME is the frame on which the image will be displayed. FRAME nil
897 or omitted means use the selected frame. */)
898 (Lisp_Object spec
, Lisp_Object frame
)
903 if (valid_image_p (spec
))
905 struct frame
*f
= decode_window_system_frame (frame
);
906 ptrdiff_t id
= lookup_image (f
, spec
);
907 struct image
*img
= IMAGE_FROM_ID (f
, id
);
912 error ("Invalid image specification");
917 DEFUN ("image-metadata", Fimage_metadata
, Simage_metadata
, 1, 2, 0,
918 doc
: /* Return metadata for image SPEC.
919 FRAME is the frame on which the image will be displayed. FRAME nil
920 or omitted means use the selected frame. */)
921 (Lisp_Object spec
, Lisp_Object frame
)
926 if (valid_image_p (spec
))
928 struct frame
*f
= decode_window_system_frame (frame
);
929 ptrdiff_t id
= lookup_image (f
, spec
);
930 struct image
*img
= IMAGE_FROM_ID (f
, id
);
931 ext
= img
->lisp_data
;
938 /***********************************************************************
939 Image type independent image structures
940 ***********************************************************************/
942 #define MAX_IMAGE_SIZE 10.0
943 /* Allocate and return a new image structure for image specification
944 SPEC. SPEC has a hash value of HASH. */
946 static struct image
*
947 make_image (Lisp_Object spec
, EMACS_UINT hash
)
949 struct image
*img
= xzalloc (sizeof *img
);
950 Lisp_Object file
= image_spec_value (spec
, QCfile
, NULL
);
952 eassert (valid_image_p (spec
));
953 img
->dependencies
= NILP (file
) ? Qnil
: list1 (file
);
954 img
->type
= lookup_image_type (image_spec_value (spec
, QCtype
, NULL
));
955 eassert (img
->type
!= NULL
);
957 img
->lisp_data
= Qnil
;
958 img
->ascent
= DEFAULT_IMAGE_ASCENT
;
960 img
->corners
[BOT_CORNER
] = -1; /* Full image */
965 /* Free image IMG which was used on frame F, including its resources. */
968 free_image (struct frame
*f
, struct image
*img
)
972 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
974 /* Remove IMG from the hash table of its cache. */
976 img
->prev
->next
= img
->next
;
978 c
->buckets
[img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
] = img
->next
;
981 img
->next
->prev
= img
->prev
;
983 c
->images
[img
->id
] = NULL
;
985 /* Windows NT redefines 'free', but in this file, we need to
986 avoid the redefinition. */
990 /* Free resources, then free IMG. */
991 img
->type
->free (f
, img
);
996 /* Return true if the given widths and heights are valid for display. */
999 check_image_size (struct frame
*f
, int width
, int height
)
1003 if (width
<= 0 || height
<= 0)
1006 if (INTEGERP (Vmax_image_size
))
1007 return (width
<= XINT (Vmax_image_size
)
1008 && height
<= XINT (Vmax_image_size
));
1009 else if (FLOATP (Vmax_image_size
))
1013 w
= FRAME_PIXEL_WIDTH (f
);
1014 h
= FRAME_PIXEL_HEIGHT (f
);
1017 w
= h
= 1024; /* Arbitrary size for unknown frame. */
1018 return (width
<= XFLOAT_DATA (Vmax_image_size
) * w
1019 && height
<= XFLOAT_DATA (Vmax_image_size
) * h
);
1025 /* Prepare image IMG for display on frame F. Must be called before
1026 drawing an image. */
1029 prepare_image_for_display (struct frame
*f
, struct image
*img
)
1031 /* We're about to display IMG, so set its timestamp to `now'. */
1032 img
->timestamp
= current_timespec ();
1035 /* If IMG doesn't have a pixmap yet, load it now, using the image
1036 type dependent loader function. */
1037 if (img
->pixmap
== NO_PIXMAP
&& !img
->load_failed_p
)
1038 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1040 #ifdef HAVE_X_WINDOWS
1041 if (!img
->load_failed_p
)
1044 image_sync_to_pixmaps (f
, img
);
1052 /* Value is the number of pixels for the ascent of image IMG when
1053 drawn in face FACE. */
1056 image_ascent (struct image
*img
, struct face
*face
, struct glyph_slice
*slice
)
1061 if (slice
->height
== img
->height
)
1062 height
= img
->height
+ img
->vmargin
;
1063 else if (slice
->y
== 0)
1064 height
= slice
->height
+ img
->vmargin
;
1066 height
= slice
->height
;
1068 if (img
->ascent
== CENTERED_IMAGE_ASCENT
)
1073 /* W32 specific version. Why?. ++kfs */
1074 ascent
= height
/ 2 - (FONT_DESCENT (face
->font
)
1075 - FONT_BASE (face
->font
)) / 2;
1077 /* This expression is arranged so that if the image can't be
1078 exactly centered, it will be moved slightly up. This is
1079 because a typical font is `top-heavy' (due to the presence
1080 uppercase letters), so the image placement should err towards
1081 being top-heavy too. It also just generally looks better. */
1082 ascent
= (height
+ FONT_BASE (face
->font
)
1083 - FONT_DESCENT (face
->font
) + 1) / 2;
1084 #endif /* HAVE_NTGUI */
1087 ascent
= height
/ 2;
1090 ascent
= height
* (img
->ascent
/ 100.0);
1097 xcolor_to_argb32 (XColor xc
)
1099 return (0xff << 24) | ((xc
.red
/ 256) << 16)
1100 | ((xc
.green
/ 256) << 8) | (xc
.blue
/ 256);
1104 get_spec_bg_or_alpha_as_argb (struct image
*img
,
1107 uint32_t bgcolor
= 0;
1109 Lisp_Object bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1111 if (STRINGP (bg
) && x_parse_color (f
, SSDATA (bg
), &xbgcolor
))
1112 bgcolor
= xcolor_to_argb32 (xbgcolor
);
1118 create_cairo_image_surface (struct image
*img
,
1119 unsigned char *data
,
1123 cairo_surface_t
*surface
;
1124 cairo_format_t format
= CAIRO_FORMAT_ARGB32
;
1125 int stride
= cairo_format_stride_for_width (format
, width
);
1126 surface
= cairo_image_surface_create_for_data (data
,
1132 img
->height
= height
;
1133 img
->cr_data
= surface
;
1134 img
->cr_data2
= data
;
1141 /* Image background colors. */
1143 /* Find the "best" corner color of a bitmap.
1144 On W32, XIMG is assumed to a device context with the bitmap selected. */
1146 static RGB_PIXEL_COLOR
1147 four_corners_best (XImagePtr_or_DC ximg
, int *corners
,
1148 unsigned long width
, unsigned long height
)
1150 RGB_PIXEL_COLOR corner_pixels
[4], best
IF_LINT (= 0);
1153 if (corners
&& corners
[BOT_CORNER
] >= 0)
1155 /* Get the colors at the corner_pixels of ximg. */
1156 corner_pixels
[0] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[TOP_CORNER
]);
1157 corner_pixels
[1] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[TOP_CORNER
]);
1158 corner_pixels
[2] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[BOT_CORNER
] - 1);
1159 corner_pixels
[3] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[BOT_CORNER
] - 1);
1163 /* Get the colors at the corner_pixels of ximg. */
1164 corner_pixels
[0] = GET_PIXEL (ximg
, 0, 0);
1165 corner_pixels
[1] = GET_PIXEL (ximg
, width
- 1, 0);
1166 corner_pixels
[2] = GET_PIXEL (ximg
, width
- 1, height
- 1);
1167 corner_pixels
[3] = GET_PIXEL (ximg
, 0, height
- 1);
1169 /* Choose the most frequently found color as background. */
1170 for (i
= best_count
= 0; i
< 4; ++i
)
1174 for (j
= n
= 0; j
< 4; ++j
)
1175 if (corner_pixels
[i
] == corner_pixels
[j
])
1179 best
= corner_pixels
[i
], best_count
= n
;
1185 /* Portability macros */
1189 #define Free_Pixmap(display, pixmap) \
1190 DeleteObject (pixmap)
1192 #elif defined (HAVE_NS)
1194 #define Free_Pixmap(display, pixmap) \
1195 ns_release_object (pixmap)
1199 #define Free_Pixmap(display, pixmap) \
1200 XFreePixmap (display, pixmap)
1202 #endif /* !HAVE_NTGUI && !HAVE_NS */
1205 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1206 it is guessed heuristically. If non-zero, XIMG is an existing
1207 XImage object (or device context with the image selected on W32) to
1208 use for the heuristic. */
1211 image_background (struct image
*img
, struct frame
*f
, XImagePtr_or_DC ximg
)
1213 if (! img
->background_valid
)
1214 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1216 bool free_ximg
= !ximg
;
1219 #endif /* HAVE_NTGUI */
1222 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
1224 img
->background
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
1227 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
1229 img
->background_valid
= 1;
1232 return img
->background
;
1235 /* Return the `background_transparent' field of IMG. If IMG doesn't
1236 have one yet, it is guessed heuristically. If non-zero, MASK is an
1237 existing XImage object to use for the heuristic. */
1240 image_background_transparent (struct image
*img
, struct frame
*f
, XImagePtr_or_DC mask
)
1242 if (! img
->background_transparent_valid
)
1243 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1247 bool free_mask
= !mask
;
1250 #endif /* HAVE_NTGUI */
1253 mask
= image_get_x_image_or_dc (f
, img
, 1, &prev
);
1255 img
->background_transparent
1256 = (four_corners_best (mask
, img
->corners
, img
->width
, img
->height
) == PIX_MASK_RETAIN
);
1259 image_unget_x_image_or_dc (img
, 1, mask
, prev
);
1262 img
->background_transparent
= 0;
1264 img
->background_transparent_valid
= 1;
1267 return img
->background_transparent
;
1270 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1271 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1273 /* Store F's background color into *BGCOLOR. */
1275 x_query_frame_background_color (struct frame
*f
, XColor
*bgcolor
)
1278 bgcolor
->pixel
= FRAME_BACKGROUND_PIXEL (f
);
1279 x_query_color (f
, bgcolor
);
1281 ns_query_color (FRAME_BACKGROUND_COLOR (f
), bgcolor
, 1);
1285 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1287 /***********************************************************************
1288 Helper functions for X image types
1289 ***********************************************************************/
1291 /* Clear X resources of image IMG on frame F according to FLAGS.
1292 FLAGS is bitwise-or of the following masks:
1293 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1294 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1295 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1298 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1299 #define CLEAR_IMAGE_MASK (1 << 1)
1300 #define CLEAR_IMAGE_COLORS (1 << 2)
1303 x_clear_image_1 (struct frame
*f
, struct image
*img
, int flags
)
1305 if (flags
& CLEAR_IMAGE_PIXMAP
)
1309 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->pixmap
);
1310 img
->pixmap
= NO_PIXMAP
;
1311 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1312 img
->background_valid
= 0;
1314 #ifdef HAVE_X_WINDOWS
1317 x_destroy_x_image (img
->ximg
);
1319 img
->background_valid
= 0;
1324 if (flags
& CLEAR_IMAGE_MASK
)
1328 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->mask
);
1329 img
->mask
= NO_PIXMAP
;
1330 img
->background_transparent_valid
= 0;
1332 #ifdef HAVE_X_WINDOWS
1335 x_destroy_x_image (img
->mask_img
);
1336 img
->mask_img
= NULL
;
1337 img
->background_transparent_valid
= 0;
1342 if ((flags
& CLEAR_IMAGE_COLORS
) && img
->ncolors
)
1344 /* W32_TODO: color table support. */
1345 #ifdef HAVE_X_WINDOWS
1346 x_free_colors (f
, img
->colors
, img
->ncolors
);
1347 #endif /* HAVE_X_WINDOWS */
1348 xfree (img
->colors
);
1355 /* Free X resources of image IMG which is used on frame F. */
1358 x_clear_image (struct frame
*f
, struct image
*img
)
1363 cairo_surface_destroy ((cairo_surface_t
*)img
->cr_data
);
1364 if (img
->cr_data2
) xfree (img
->cr_data2
);
1366 x_clear_image_1 (f
, img
,
1367 CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_MASK
| CLEAR_IMAGE_COLORS
);
1372 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1373 cannot be allocated, use DFLT. Add a newly allocated color to
1374 IMG->colors, so that it can be freed again. Value is the pixel
1377 static unsigned long
1378 x_alloc_image_color (struct frame
*f
, struct image
*img
, Lisp_Object color_name
,
1382 unsigned long result
;
1384 eassert (STRINGP (color_name
));
1386 if (x_defined_color (f
, SSDATA (color_name
), &color
, 1)
1387 && img
->ncolors
< min (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *img
->colors
,
1390 /* This isn't called frequently so we get away with simply
1391 reallocating the color vector to the needed size, here. */
1392 ptrdiff_t ncolors
= img
->ncolors
+ 1;
1393 img
->colors
= xrealloc (img
->colors
, ncolors
* sizeof *img
->colors
);
1394 img
->colors
[ncolors
- 1] = color
.pixel
;
1395 img
->ncolors
= ncolors
;
1396 result
= color
.pixel
;
1406 /***********************************************************************
1408 ***********************************************************************/
1410 static void cache_image (struct frame
*f
, struct image
*img
);
1412 /* Return a new, initialized image cache that is allocated from the
1413 heap. Call free_image_cache to free an image cache. */
1415 struct image_cache
*
1416 make_image_cache (void)
1418 struct image_cache
*c
= xmalloc (sizeof *c
);
1421 c
->used
= c
->refcount
= 0;
1422 c
->images
= xmalloc (c
->size
* sizeof *c
->images
);
1423 c
->buckets
= xzalloc (IMAGE_CACHE_BUCKETS_SIZE
* sizeof *c
->buckets
);
1428 /* Find an image matching SPEC in the cache, and return it. If no
1429 image is found, return NULL. */
1430 static struct image
*
1431 search_image_cache (struct frame
*f
, Lisp_Object spec
, EMACS_UINT hash
)
1434 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1435 int i
= hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1437 if (!c
) return NULL
;
1439 /* If the image spec does not specify a background color, the cached
1440 image must have the same background color as the current frame.
1441 The foreground color must also match, for the sake of monochrome
1444 In fact, we could ignore the foreground color matching condition
1445 for color images, or if the image spec specifies :foreground;
1446 similarly we could ignore the background color matching condition
1447 for formats that don't use transparency (such as jpeg), or if the
1448 image spec specifies :background. However, the extra memory
1449 usage is probably negligible in practice, so we don't bother. */
1451 for (img
= c
->buckets
[i
]; img
; img
= img
->next
)
1452 if (img
->hash
== hash
1453 && !NILP (Fequal (img
->spec
, spec
))
1454 && img
->frame_foreground
== FRAME_FOREGROUND_PIXEL (f
)
1455 && img
->frame_background
== FRAME_BACKGROUND_PIXEL (f
))
1461 /* Search frame F for an image with spec SPEC, and free it. */
1464 uncache_image (struct frame
*f
, Lisp_Object spec
)
1466 struct image
*img
= search_image_cache (f
, spec
, sxhash (spec
, 0));
1469 free_image (f
, img
);
1470 /* As display glyphs may still be referring to the image ID, we
1471 must garbage the frame (Bug#6426). */
1472 SET_FRAME_GARBAGED (f
);
1477 /* Free image cache of frame F. Be aware that X frames share images
1481 free_image_cache (struct frame
*f
)
1483 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1488 /* Cache should not be referenced by any frame when freed. */
1489 eassert (c
->refcount
== 0);
1491 for (i
= 0; i
< c
->used
; ++i
)
1492 free_image (f
, c
->images
[i
]);
1496 FRAME_IMAGE_CACHE (f
) = NULL
;
1501 /* Clear image cache of frame F. FILTER=t means free all images.
1502 FILTER=nil means clear only images that haven't been
1503 displayed for some time.
1504 Else, only free the images which have FILTER in their `dependencies'.
1505 Should be called from time to time to reduce the number of loaded images.
1506 If image-cache-eviction-delay is non-nil, this frees images in the cache
1507 which weren't displayed for at least that many seconds. */
1510 clear_image_cache (struct frame
*f
, Lisp_Object filter
)
1512 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1516 ptrdiff_t i
, nfreed
= 0;
1518 /* Block input so that we won't be interrupted by a SIGIO
1519 while being in an inconsistent state. */
1524 /* Filter image cache. */
1525 for (i
= 0; i
< c
->used
; ++i
)
1527 struct image
*img
= c
->images
[i
];
1528 if (img
&& (EQ (Qt
, filter
)
1529 || !NILP (Fmember (filter
, img
->dependencies
))))
1531 free_image (f
, img
);
1536 else if (INTEGERP (Vimage_cache_eviction_delay
))
1538 /* Free cache based on timestamp. */
1539 struct timespec old
, t
;
1541 ptrdiff_t nimages
= 0;
1543 for (i
= 0; i
< c
->used
; ++i
)
1547 /* If the number of cached images has grown unusually large,
1548 decrease the cache eviction delay (Bug#6230). */
1549 delay
= XINT (Vimage_cache_eviction_delay
);
1551 delay
= 1600 * delay
/ nimages
/ nimages
;
1552 delay
= max (delay
, 1);
1554 t
= current_timespec ();
1555 old
= timespec_sub (t
, dtotimespec (delay
));
1557 for (i
= 0; i
< c
->used
; ++i
)
1559 struct image
*img
= c
->images
[i
];
1560 if (img
&& timespec_cmp (img
->timestamp
, old
) < 0)
1562 free_image (f
, img
);
1568 /* We may be clearing the image cache because, for example,
1569 Emacs was iconified for a longer period of time. In that
1570 case, current matrices may still contain references to
1571 images freed above. So, clear these matrices. */
1574 Lisp_Object tail
, frame
;
1576 FOR_EACH_FRAME (tail
, frame
)
1578 struct frame
*fr
= XFRAME (frame
);
1579 if (FRAME_IMAGE_CACHE (fr
) == c
)
1580 clear_current_matrices (fr
);
1583 windows_or_buffers_changed
= 19;
1591 clear_image_caches (Lisp_Object filter
)
1593 /* FIXME: We want to do
1594 * struct terminal *t;
1595 * for (t = terminal_list; t; t = t->next_terminal)
1596 * clear_image_cache (t, filter); */
1597 Lisp_Object tail
, frame
;
1598 FOR_EACH_FRAME (tail
, frame
)
1599 if (FRAME_WINDOW_P (XFRAME (frame
)))
1600 clear_image_cache (XFRAME (frame
), filter
);
1603 DEFUN ("clear-image-cache", Fclear_image_cache
, Sclear_image_cache
,
1605 doc
: /* Clear the image cache.
1606 FILTER nil or a frame means clear all images in the selected frame.
1607 FILTER t means clear the image caches of all frames.
1608 Anything else, means only clear those images which refer to FILTER,
1609 which is then usually a filename. */)
1610 (Lisp_Object filter
)
1612 if (!(EQ (filter
, Qnil
) || FRAMEP (filter
)))
1613 clear_image_caches (filter
);
1615 clear_image_cache (decode_window_system_frame (filter
), Qt
);
1621 DEFUN ("image-flush", Fimage_flush
, Simage_flush
,
1623 doc
: /* Flush the image with specification SPEC on frame FRAME.
1624 This removes the image from the Emacs image cache. If SPEC specifies
1625 an image file, the next redisplay of this image will read from the
1626 current contents of that file.
1628 FRAME nil or omitted means use the selected frame.
1629 FRAME t means refresh the image on all frames. */)
1630 (Lisp_Object spec
, Lisp_Object frame
)
1632 if (!valid_image_p (spec
))
1633 error ("Invalid image specification");
1638 FOR_EACH_FRAME (tail
, frame
)
1640 struct frame
*f
= XFRAME (frame
);
1641 if (FRAME_WINDOW_P (f
))
1642 uncache_image (f
, spec
);
1646 uncache_image (decode_window_system_frame (frame
), spec
);
1652 /* Compute masks and transform image IMG on frame F, as specified
1653 by the image's specification, */
1656 postprocess_image (struct frame
*f
, struct image
*img
)
1658 /* Manipulation of the image's mask. */
1661 Lisp_Object conversion
, spec
;
1666 /* `:heuristic-mask t'
1668 means build a mask heuristically.
1669 `:heuristic-mask (R G B)'
1670 `:mask (heuristic (R G B))'
1671 means build a mask from color (R G B) in the
1674 means remove a mask, if any. */
1676 mask
= image_spec_value (spec
, QCheuristic_mask
, NULL
);
1678 x_build_heuristic_mask (f
, img
, mask
);
1683 mask
= image_spec_value (spec
, QCmask
, &found_p
);
1685 if (EQ (mask
, Qheuristic
))
1686 x_build_heuristic_mask (f
, img
, Qt
);
1687 else if (CONSP (mask
)
1688 && EQ (XCAR (mask
), Qheuristic
))
1690 if (CONSP (XCDR (mask
)))
1691 x_build_heuristic_mask (f
, img
, XCAR (XCDR (mask
)));
1693 x_build_heuristic_mask (f
, img
, XCDR (mask
));
1695 else if (NILP (mask
) && found_p
&& img
->mask
)
1696 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
1700 /* Should we apply an image transformation algorithm? */
1701 conversion
= image_spec_value (spec
, QCconversion
, NULL
);
1702 if (EQ (conversion
, Qdisabled
))
1703 x_disable_image (f
, img
);
1704 else if (EQ (conversion
, Qlaplace
))
1706 else if (EQ (conversion
, Qemboss
))
1708 else if (CONSP (conversion
)
1709 && EQ (XCAR (conversion
), Qedge_detection
))
1712 tem
= XCDR (conversion
);
1714 x_edge_detection (f
, img
,
1715 Fplist_get (tem
, QCmatrix
),
1716 Fplist_get (tem
, QCcolor_adjustment
));
1722 /* Return the id of image with Lisp specification SPEC on frame F.
1723 SPEC must be a valid Lisp image specification (see valid_image_p). */
1726 lookup_image (struct frame
*f
, Lisp_Object spec
)
1731 /* F must be a window-system frame, and SPEC must be a valid image
1733 eassert (FRAME_WINDOW_P (f
));
1734 eassert (valid_image_p (spec
));
1736 /* Look up SPEC in the hash table of the image cache. */
1737 hash
= sxhash (spec
, 0);
1738 img
= search_image_cache (f
, spec
, hash
);
1739 if (img
&& img
->load_failed_p
)
1741 free_image (f
, img
);
1745 /* If not found, create a new image and cache it. */
1749 img
= make_image (spec
, hash
);
1750 cache_image (f
, img
);
1751 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1752 img
->frame_foreground
= FRAME_FOREGROUND_PIXEL (f
);
1753 img
->frame_background
= FRAME_BACKGROUND_PIXEL (f
);
1755 /* If we can't load the image, and we don't have a width and
1756 height, use some arbitrary width and height so that we can
1757 draw a rectangle for it. */
1758 if (img
->load_failed_p
)
1762 value
= image_spec_value (spec
, QCwidth
, NULL
);
1763 img
->width
= (INTEGERP (value
)
1764 ? XFASTINT (value
) : DEFAULT_IMAGE_WIDTH
);
1765 value
= image_spec_value (spec
, QCheight
, NULL
);
1766 img
->height
= (INTEGERP (value
)
1767 ? XFASTINT (value
) : DEFAULT_IMAGE_HEIGHT
);
1771 /* Handle image type independent image attributes
1772 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1773 `:background COLOR'. */
1774 Lisp_Object ascent
, margin
, relief
, bg
;
1777 ascent
= image_spec_value (spec
, QCascent
, NULL
);
1778 if (INTEGERP (ascent
))
1779 img
->ascent
= XFASTINT (ascent
);
1780 else if (EQ (ascent
, Qcenter
))
1781 img
->ascent
= CENTERED_IMAGE_ASCENT
;
1783 margin
= image_spec_value (spec
, QCmargin
, NULL
);
1784 if (INTEGERP (margin
))
1785 img
->vmargin
= img
->hmargin
= XFASTINT (margin
);
1786 else if (CONSP (margin
))
1788 img
->hmargin
= XFASTINT (XCAR (margin
));
1789 img
->vmargin
= XFASTINT (XCDR (margin
));
1792 relief
= image_spec_value (spec
, QCrelief
, NULL
);
1793 relief_bound
= INT_MAX
- max (img
->hmargin
, img
->vmargin
);
1794 if (RANGED_INTEGERP (- relief_bound
, relief
, relief_bound
))
1796 img
->relief
= XINT (relief
);
1797 img
->hmargin
+= eabs (img
->relief
);
1798 img
->vmargin
+= eabs (img
->relief
);
1801 if (! img
->background_valid
)
1803 bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1807 = x_alloc_image_color (f
, img
, bg
,
1808 FRAME_BACKGROUND_PIXEL (f
));
1809 img
->background_valid
= 1;
1813 /* Do image transformations and compute masks, unless we
1814 don't have the image yet. */
1815 if (!EQ (builtin_lisp_symbol (img
->type
->type
), Qpostscript
))
1816 postprocess_image (f
, img
);
1822 /* We're using IMG, so set its timestamp to `now'. */
1823 img
->timestamp
= current_timespec ();
1825 /* Value is the image id. */
1830 /* Cache image IMG in the image cache of frame F. */
1833 cache_image (struct frame
*f
, struct image
*img
)
1835 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1838 /* Find a free slot in c->images. */
1839 for (i
= 0; i
< c
->used
; ++i
)
1840 if (c
->images
[i
] == NULL
)
1843 /* If no free slot found, maybe enlarge c->images. */
1844 if (i
== c
->used
&& c
->used
== c
->size
)
1845 c
->images
= xpalloc (c
->images
, &c
->size
, 1, -1, sizeof *c
->images
);
1847 /* Add IMG to c->images, and assign IMG an id. */
1853 /* Add IMG to the cache's hash table. */
1854 i
= img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1855 img
->next
= c
->buckets
[i
];
1857 img
->next
->prev
= img
;
1859 c
->buckets
[i
] = img
;
1863 /* Call FN on every image in the image cache of frame F. Used to mark
1864 Lisp Objects in the image cache. */
1866 /* Mark Lisp objects in image IMG. */
1869 mark_image (struct image
*img
)
1871 mark_object (img
->spec
);
1872 mark_object (img
->dependencies
);
1874 if (!NILP (img
->lisp_data
))
1875 mark_object (img
->lisp_data
);
1880 mark_image_cache (struct image_cache
*c
)
1885 for (i
= 0; i
< c
->used
; ++i
)
1887 mark_image (c
->images
[i
]);
1893 /***********************************************************************
1894 X / NS / W32 support code
1895 ***********************************************************************/
1897 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1899 WIDTH and HEIGHT must both be positive.
1900 If XIMG is null, assume it is a bitmap. */
1902 x_check_image_size (XImagePtr ximg
, int width
, int height
)
1904 #ifdef HAVE_X_WINDOWS
1905 /* Respect Xlib's limits: it cannot deal with images that have more
1906 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1907 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1910 XLIB_BYTES_MAX
= min (INT_MAX
, UINT_MAX
),
1911 X_IMAGE_BYTES_MAX
= min (XLIB_BYTES_MAX
, min (PTRDIFF_MAX
, SIZE_MAX
))
1914 int bitmap_pad
, depth
, bytes_per_line
;
1917 bitmap_pad
= ximg
->bitmap_pad
;
1918 depth
= ximg
->depth
;
1919 bytes_per_line
= ximg
->bytes_per_line
;
1925 bytes_per_line
= (width
>> 3) + ((width
& 7) != 0);
1927 return (width
<= (INT_MAX
- (bitmap_pad
- 1)) / depth
1928 && height
<= X_IMAGE_BYTES_MAX
/ bytes_per_line
);
1930 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1931 For now, assume that every image size is allowed on these systems. */
1936 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1937 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1938 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1939 via xmalloc. Print error messages via image_error if an error
1940 occurs. Value is true if successful.
1942 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1943 should indicate the bit depth of the image. */
1946 x_create_x_image_and_pixmap (struct frame
*f
, int width
, int height
, int depth
,
1947 XImagePtr
*ximg
, Pixmap
*pixmap
)
1949 #ifdef HAVE_X_WINDOWS
1950 Display
*display
= FRAME_X_DISPLAY (f
);
1951 Window window
= FRAME_X_WINDOW (f
);
1952 Screen
*screen
= FRAME_X_SCREEN (f
);
1954 eassert (input_blocked_p ());
1957 depth
= DefaultDepthOfScreen (screen
);
1958 *ximg
= XCreateImage (display
, DefaultVisualOfScreen (screen
),
1959 depth
, ZPixmap
, 0, NULL
, width
, height
,
1960 depth
> 16 ? 32 : depth
> 8 ? 16 : 8, 0);
1963 image_error ("Unable to allocate X image");
1967 if (! x_check_image_size (*ximg
, width
, height
))
1969 x_destroy_x_image (*ximg
);
1971 image_error ("Image too large (%dx%d)",
1972 make_number (width
), make_number (height
));
1976 /* Allocate image raster. */
1977 (*ximg
)->data
= xmalloc ((*ximg
)->bytes_per_line
* height
);
1979 /* Allocate a pixmap of the same size. */
1980 *pixmap
= XCreatePixmap (display
, window
, width
, height
, depth
);
1981 if (*pixmap
== NO_PIXMAP
)
1983 x_destroy_x_image (*ximg
);
1985 image_error ("Unable to create X pixmap");
1990 #endif /* HAVE_X_WINDOWS */
1994 BITMAPINFOHEADER
*header
;
1996 int scanline_width_bits
;
1998 int palette_colors
= 0;
2003 if (depth
!= 1 && depth
!= 4 && depth
!= 8
2004 && depth
!= 16 && depth
!= 24 && depth
!= 32)
2006 image_error ("Invalid image bit depth specified");
2010 scanline_width_bits
= width
* depth
;
2011 remainder
= scanline_width_bits
% 32;
2014 scanline_width_bits
+= 32 - remainder
;
2016 /* Bitmaps with a depth less than 16 need a palette. */
2017 /* BITMAPINFO structure already contains the first RGBQUAD. */
2019 palette_colors
= 1 << (depth
- 1);
2021 *ximg
= xmalloc (sizeof (XImage
) + palette_colors
* sizeof (RGBQUAD
));
2023 header
= &(*ximg
)->info
.bmiHeader
;
2024 memset (&(*ximg
)->info
, 0, sizeof (BITMAPINFO
));
2025 header
->biSize
= sizeof (*header
);
2026 header
->biWidth
= width
;
2027 header
->biHeight
= -height
; /* negative indicates a top-down bitmap. */
2028 header
->biPlanes
= 1;
2029 header
->biBitCount
= depth
;
2030 header
->biCompression
= BI_RGB
;
2031 header
->biClrUsed
= palette_colors
;
2033 /* TODO: fill in palette. */
2036 (*ximg
)->info
.bmiColors
[0].rgbBlue
= 0;
2037 (*ximg
)->info
.bmiColors
[0].rgbGreen
= 0;
2038 (*ximg
)->info
.bmiColors
[0].rgbRed
= 0;
2039 (*ximg
)->info
.bmiColors
[0].rgbReserved
= 0;
2040 (*ximg
)->info
.bmiColors
[1].rgbBlue
= 255;
2041 (*ximg
)->info
.bmiColors
[1].rgbGreen
= 255;
2042 (*ximg
)->info
.bmiColors
[1].rgbRed
= 255;
2043 (*ximg
)->info
.bmiColors
[1].rgbReserved
= 0;
2046 hdc
= get_frame_dc (f
);
2048 /* Create a DIBSection and raster array for the bitmap,
2049 and store its handle in *pixmap. */
2050 *pixmap
= CreateDIBSection (hdc
, &((*ximg
)->info
),
2051 (depth
< 16) ? DIB_PAL_COLORS
: DIB_RGB_COLORS
,
2052 /* casting avoids a GCC warning */
2053 (void **)&((*ximg
)->data
), NULL
, 0);
2055 /* Realize display palette and garbage all frames. */
2056 release_frame_dc (f
, hdc
);
2058 if (*pixmap
== NULL
)
2060 DWORD err
= GetLastError ();
2061 Lisp_Object errcode
;
2062 /* All system errors are < 10000, so the following is safe. */
2063 XSETINT (errcode
, err
);
2064 image_error ("Unable to create bitmap, error code %d", errcode
);
2065 x_destroy_x_image (*ximg
);
2072 #endif /* HAVE_NTGUI */
2075 *pixmap
= ns_image_for_XPM (width
, height
, depth
);
2079 image_error ("Unable to allocate NSImage for XPM pixmap");
2088 /* Destroy XImage XIMG. Free XIMG->data. */
2091 x_destroy_x_image (XImagePtr ximg
)
2093 eassert (input_blocked_p ());
2096 #ifdef HAVE_X_WINDOWS
2099 XDestroyImage (ximg
);
2100 #endif /* HAVE_X_WINDOWS */
2102 /* Data will be freed by DestroyObject. */
2105 #endif /* HAVE_NTGUI */
2107 ns_release_object (ximg
);
2108 #endif /* HAVE_NS */
2113 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2114 are width and height of both the image and pixmap. */
2117 x_put_x_image (struct frame
*f
, XImagePtr ximg
, Pixmap pixmap
, int width
, int height
)
2119 #ifdef HAVE_X_WINDOWS
2122 eassert (input_blocked_p ());
2123 gc
= XCreateGC (FRAME_X_DISPLAY (f
), pixmap
, 0, NULL
);
2124 XPutImage (FRAME_X_DISPLAY (f
), pixmap
, gc
, ximg
, 0, 0, 0, 0, width
, height
);
2125 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
2126 #endif /* HAVE_X_WINDOWS */
2129 #if 0 /* I don't think this is necessary looking at where it is used. */
2130 HDC hdc
= get_frame_dc (f
);
2131 SetDIBits (hdc
, pixmap
, 0, height
, ximg
->data
, &(ximg
->info
), DIB_RGB_COLORS
);
2132 release_frame_dc (f
, hdc
);
2134 #endif /* HAVE_NTGUI */
2137 eassert (ximg
== pixmap
);
2138 ns_retain_object (ximg
);
2142 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2143 with image_put_x_image. */
2146 image_create_x_image_and_pixmap (struct frame
*f
, struct image
*img
,
2147 int width
, int height
, int depth
,
2148 XImagePtr
*ximg
, bool mask_p
)
2150 eassert ((!mask_p
? img
->pixmap
: img
->mask
) == NO_PIXMAP
);
2152 return x_create_x_image_and_pixmap (f
, width
, height
, depth
, ximg
,
2153 !mask_p
? &img
->pixmap
: &img
->mask
);
2156 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2157 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2158 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2159 On the other platforms, it puts XIMG into the pixmap, then frees
2160 the X image and its buffer. */
2163 image_put_x_image (struct frame
*f
, struct image
*img
, XImagePtr ximg
,
2166 #ifdef HAVE_X_WINDOWS
2169 eassert (img
->ximg
== NULL
);
2174 eassert (img
->mask_img
== NULL
);
2175 img
->mask_img
= ximg
;
2178 x_put_x_image (f
, ximg
, !mask_p
? img
->pixmap
: img
->mask
,
2179 img
->width
, img
->height
);
2180 x_destroy_x_image (ximg
);
2184 #ifdef HAVE_X_WINDOWS
2185 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2186 the X images and their buffers. */
2189 image_sync_to_pixmaps (struct frame
*f
, struct image
*img
)
2193 x_put_x_image (f
, img
->ximg
, img
->pixmap
, img
->width
, img
->height
);
2194 x_destroy_x_image (img
->ximg
);
2199 x_put_x_image (f
, img
->mask_img
, img
->mask
, img
->width
, img
->height
);
2200 x_destroy_x_image (img
->mask_img
);
2201 img
->mask_img
= NULL
;
2207 /* Create a memory device context for IMG on frame F. It stores the
2208 currently selected GDI object into *PREV for future restoration by
2209 image_unget_x_image_or_dc. */
2211 static XImagePtr_or_DC
2212 image_get_x_image_or_dc (struct frame
*f
, struct image
*img
, bool mask_p
,
2215 HDC frame_dc
= get_frame_dc (f
);
2216 XImagePtr_or_DC ximg
= CreateCompatibleDC (frame_dc
);
2218 release_frame_dc (f
, frame_dc
);
2219 *prev
= SelectObject (ximg
, !mask_p
? img
->pixmap
: img
->mask
);
2225 image_unget_x_image_or_dc (struct image
*img
, bool mask_p
,
2226 XImagePtr_or_DC ximg
, HGDIOBJ prev
)
2228 SelectObject (ximg
, prev
);
2231 #else /* !HAVE_NTGUI */
2232 /* Get the X image for IMG on frame F. The resulting X image data
2233 should be treated as read-only at least on X. */
2236 image_get_x_image (struct frame
*f
, struct image
*img
, bool mask_p
)
2238 #ifdef HAVE_X_WINDOWS
2239 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2244 return XGetImage (FRAME_X_DISPLAY (f
), !mask_p
? img
->pixmap
: img
->mask
,
2245 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
2246 #elif defined (HAVE_NS)
2247 XImagePtr pixmap
= !mask_p
? img
->pixmap
: img
->mask
;
2249 ns_retain_object (pixmap
);
2255 image_unget_x_image (struct image
*img
, bool mask_p
, XImagePtr ximg
)
2257 #ifdef HAVE_X_WINDOWS
2258 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2261 eassert (ximg
== ximg_in_img
);
2263 XDestroyImage (ximg
);
2264 #elif defined (HAVE_NS)
2265 ns_release_object (ximg
);
2268 #endif /* !HAVE_NTGUI */
2271 /***********************************************************************
2273 ***********************************************************************/
2275 /* Find image file FILE. Look in data-directory/images, then
2276 x-bitmap-file-path. Value is the full name of the file
2277 found, or nil if not found. If PFD is nonnull store into *PFD a
2278 readable file descriptor for the file, opened in binary mode. If
2279 PFD is null, do not open the file. */
2282 x_find_image_fd (Lisp_Object file
, int *pfd
)
2284 Lisp_Object file_found
, search_path
;
2287 /* TODO I think this should use something like image-load-path
2288 instead. Unfortunately, that can contain non-string elements. */
2289 search_path
= Fcons (Fexpand_file_name (build_string ("images"),
2291 Vx_bitmap_file_path
);
2293 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2294 fd
= openp (search_path
, file
, Qnil
, &file_found
,
2295 pfd
? Qt
: make_number (R_OK
), false);
2303 /* Find image file FILE. Look in data-directory/images, then
2304 x-bitmap-file-path. Value is the encoded full name of the file
2305 found, or nil if not found. */
2308 x_find_image_file (Lisp_Object file
)
2310 return x_find_image_fd (file
, 0);
2313 /* Read FILE into memory. Value is a pointer to a buffer allocated
2314 with xmalloc holding FILE's contents. Value is null if an error
2315 occurred. FD is a file descriptor open for reading FILE. Set
2316 *SIZE to the size of the file. */
2318 static unsigned char *
2319 slurp_file (int fd
, ptrdiff_t *size
)
2321 FILE *fp
= fdopen (fd
, "rb");
2323 unsigned char *buf
= NULL
;
2328 ptrdiff_t count
= SPECPDL_INDEX ();
2329 record_unwind_protect_ptr (fclose_unwind
, fp
);
2331 if (fstat (fileno (fp
), &st
) == 0
2332 && 0 <= st
.st_size
&& st
.st_size
< min (PTRDIFF_MAX
, SIZE_MAX
))
2334 /* Report an error if we read past the purported EOF.
2335 This can happen if the file grows as we read it. */
2336 ptrdiff_t buflen
= st
.st_size
;
2337 buf
= xmalloc (buflen
+ 1);
2338 if (fread (buf
, 1, buflen
+ 1, fp
) == buflen
)
2347 unbind_to (count
, Qnil
);
2355 /***********************************************************************
2357 ***********************************************************************/
2359 static bool xbm_load (struct frame
*f
, struct image
*img
);
2360 static bool xbm_image_p (Lisp_Object object
);
2361 static bool xbm_file_p (Lisp_Object
);
2364 /* Indices of image specification fields in xbm_format, below. */
2366 enum xbm_keyword_index
2384 /* Vector of image_keyword structures describing the format
2385 of valid XBM image specifications. */
2387 static const struct image_keyword xbm_format
[XBM_LAST
] =
2389 {":type", IMAGE_SYMBOL_VALUE
, 1},
2390 {":file", IMAGE_STRING_VALUE
, 0},
2391 {":width", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2392 {":height", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2393 {":data", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2394 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
2395 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
2396 {":ascent", IMAGE_ASCENT_VALUE
, 0},
2397 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
2398 {":relief", IMAGE_INTEGER_VALUE
, 0},
2399 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2400 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2401 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
2404 /* Structure describing the image type XBM. */
2406 static struct image_type xbm_type
=
2408 SYMBOL_INDEX (Qxbm
),
2416 /* Tokens returned from xbm_scan. */
2425 /* Return true if OBJECT is a valid XBM-type image specification.
2426 A valid specification is a list starting with the symbol `image'
2427 The rest of the list is a property list which must contain an
2430 If the specification specifies a file to load, it must contain
2431 an entry `:file FILENAME' where FILENAME is a string.
2433 If the specification is for a bitmap loaded from memory it must
2434 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2435 WIDTH and HEIGHT are integers > 0. DATA may be:
2437 1. a string large enough to hold the bitmap data, i.e. it must
2438 have a size >= (WIDTH + 7) / 8 * HEIGHT
2440 2. a bool-vector of size >= WIDTH * HEIGHT
2442 3. a vector of strings or bool-vectors, one for each line of the
2445 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2446 may not be specified in this case because they are defined in the
2449 Both the file and data forms may contain the additional entries
2450 `:background COLOR' and `:foreground COLOR'. If not present,
2451 foreground and background of the frame on which the image is
2452 displayed is used. */
2455 xbm_image_p (Lisp_Object object
)
2457 struct image_keyword kw
[XBM_LAST
];
2459 memcpy (kw
, xbm_format
, sizeof kw
);
2460 if (!parse_image_spec (object
, kw
, XBM_LAST
, Qxbm
))
2463 eassert (EQ (kw
[XBM_TYPE
].value
, Qxbm
));
2465 if (kw
[XBM_FILE
].count
)
2467 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_DATA
].count
)
2470 else if (kw
[XBM_DATA
].count
&& xbm_file_p (kw
[XBM_DATA
].value
))
2472 /* In-memory XBM file. */
2473 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_FILE
].count
)
2481 /* Entries for `:width', `:height' and `:data' must be present. */
2482 if (!kw
[XBM_WIDTH
].count
2483 || !kw
[XBM_HEIGHT
].count
2484 || !kw
[XBM_DATA
].count
)
2487 data
= kw
[XBM_DATA
].value
;
2488 width
= XFASTINT (kw
[XBM_WIDTH
].value
);
2489 height
= XFASTINT (kw
[XBM_HEIGHT
].value
);
2491 /* Check type of data, and width and height against contents of
2497 /* Number of elements of the vector must be >= height. */
2498 if (ASIZE (data
) < height
)
2501 /* Each string or bool-vector in data must be large enough
2502 for one line of the image. */
2503 for (i
= 0; i
< height
; ++i
)
2505 Lisp_Object elt
= AREF (data
, i
);
2510 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
)
2513 else if (BOOL_VECTOR_P (elt
))
2515 if (bool_vector_size (elt
) < width
)
2522 else if (STRINGP (data
))
2525 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
* height
)
2528 else if (BOOL_VECTOR_P (data
))
2530 if (bool_vector_size (data
) / height
< width
)
2541 /* Scan a bitmap file. FP is the stream to read from. Value is
2542 either an enumerator from enum xbm_token, or a character for a
2543 single-character token, or 0 at end of file. If scanning an
2544 identifier, store the lexeme of the identifier in SVAL. If
2545 scanning a number, store its value in *IVAL. */
2548 xbm_scan (unsigned char **s
, unsigned char *end
, char *sval
, int *ival
)
2554 /* Skip white space. */
2555 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
2560 else if (c_isdigit (c
))
2562 int value
= 0, digit
;
2564 if (c
== '0' && *s
< end
)
2567 if (c
== 'x' || c
== 'X')
2574 else if (c
>= 'a' && c
<= 'f')
2575 digit
= c
- 'a' + 10;
2576 else if (c
>= 'A' && c
<= 'F')
2577 digit
= c
- 'A' + 10;
2580 value
= 16 * value
+ digit
;
2583 else if (c_isdigit (c
))
2587 && (c
= *(*s
)++, c_isdigit (c
)))
2588 value
= 8 * value
+ c
- '0';
2595 && (c
= *(*s
)++, c_isdigit (c
)))
2596 value
= 10 * value
+ c
- '0';
2604 else if (c_isalpha (c
) || c
== '_')
2608 && (c
= *(*s
)++, (c_isalnum (c
) || c
== '_')))
2615 else if (c
== '/' && **s
== '*')
2617 /* C-style comment. */
2619 while (**s
&& (**s
!= '*' || *(*s
+ 1) != '/'))
2633 /* Create a Windows bitmap from X bitmap data. */
2635 w32_create_pixmap_from_bitmap_data (int width
, int height
, char *data
)
2637 static unsigned char swap_nibble
[16]
2638 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2639 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2640 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2641 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2643 unsigned char *bits
, *p
;
2646 w1
= (width
+ 7) / 8; /* nb of 8bits elt in X bitmap */
2647 w2
= ((width
+ 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2648 bits
= alloca (height
* w2
);
2649 memset (bits
, 0, height
* w2
);
2650 for (i
= 0; i
< height
; i
++)
2653 for (j
= 0; j
< w1
; j
++)
2655 /* Bitswap XBM bytes to match how Windows does things. */
2656 unsigned char c
= *data
++;
2657 *p
++ = (unsigned char)((swap_nibble
[c
& 0xf] << 4)
2658 | (swap_nibble
[(c
>>4) & 0xf]));
2661 bmp
= CreateBitmap (width
, height
, 1, 1, (char *) bits
);
2667 convert_mono_to_color_image (struct frame
*f
, struct image
*img
,
2668 COLORREF foreground
, COLORREF background
)
2670 HDC hdc
, old_img_dc
, new_img_dc
;
2671 HGDIOBJ old_prev
, new_prev
;
2674 hdc
= get_frame_dc (f
);
2675 old_img_dc
= CreateCompatibleDC (hdc
);
2676 new_img_dc
= CreateCompatibleDC (hdc
);
2677 new_pixmap
= CreateCompatibleBitmap (hdc
, img
->width
, img
->height
);
2678 release_frame_dc (f
, hdc
);
2679 old_prev
= SelectObject (old_img_dc
, img
->pixmap
);
2680 new_prev
= SelectObject (new_img_dc
, new_pixmap
);
2681 /* Windows convention for mono bitmaps is black = background,
2682 white = foreground. */
2683 SetTextColor (new_img_dc
, background
);
2684 SetBkColor (new_img_dc
, foreground
);
2686 BitBlt (new_img_dc
, 0, 0, img
->width
, img
->height
, old_img_dc
,
2689 SelectObject (old_img_dc
, old_prev
);
2690 SelectObject (new_img_dc
, new_prev
);
2691 DeleteDC (old_img_dc
);
2692 DeleteDC (new_img_dc
);
2693 DeleteObject (img
->pixmap
);
2694 if (new_pixmap
== 0)
2695 fprintf (stderr
, "Failed to convert image to color.\n");
2697 img
->pixmap
= new_pixmap
;
2700 #define XBM_BIT_SHUFFLE(b) (~(b))
2704 #define XBM_BIT_SHUFFLE(b) (b)
2706 #endif /* HAVE_NTGUI */
2710 Create_Pixmap_From_Bitmap_Data (struct frame
*f
, struct image
*img
, char *data
,
2711 RGB_PIXEL_COLOR fg
, RGB_PIXEL_COLOR bg
,
2712 bool non_default_colors
)
2716 = w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
, data
);
2718 /* If colors were specified, transfer the bitmap to a color one. */
2719 if (non_default_colors
)
2720 convert_mono_to_color_image (f
, img
, fg
, bg
);
2722 #elif defined (HAVE_NS)
2723 img
->pixmap
= ns_image_from_XBM (data
, img
->width
, img
->height
, fg
, bg
);
2727 (x_check_image_size (0, img
->width
, img
->height
)
2728 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f
),
2731 img
->width
, img
->height
,
2733 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)))
2735 #endif /* !HAVE_NTGUI && !HAVE_NS */
2740 /* Replacement for XReadBitmapFileData which isn't available under old
2741 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2742 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2743 the image. Return in *DATA the bitmap data allocated with xmalloc.
2744 Value is true if successful. DATA null means just test if
2745 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2746 inhibit the call to image_error when the image size is invalid (the
2747 bitmap remains unread). */
2750 xbm_read_bitmap_data (struct frame
*f
, unsigned char *contents
, unsigned char *end
,
2751 int *width
, int *height
, char **data
,
2752 bool inhibit_image_error
)
2754 unsigned char *s
= contents
;
2755 char buffer
[BUFSIZ
];
2758 int bytes_per_line
, i
, nbytes
;
2764 LA1 = xbm_scan (&s, end, buffer, &value)
2766 #define expect(TOKEN) \
2769 if (LA1 != (TOKEN)) \
2775 #define expect_ident(IDENT) \
2776 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2781 *width
= *height
= -1;
2784 LA1
= xbm_scan (&s
, end
, buffer
, &value
);
2786 /* Parse defines for width, height and hot-spots. */
2790 expect_ident ("define");
2791 expect (XBM_TK_IDENT
);
2793 if (LA1
== XBM_TK_NUMBER
)
2795 char *q
= strrchr (buffer
, '_');
2796 q
= q
? q
+ 1 : buffer
;
2797 if (strcmp (q
, "width") == 0)
2799 else if (strcmp (q
, "height") == 0)
2802 expect (XBM_TK_NUMBER
);
2805 if (!check_image_size (f
, *width
, *height
))
2807 if (!inhibit_image_error
)
2808 image_size_error ();
2811 else if (data
== NULL
)
2814 /* Parse bits. Must start with `static'. */
2815 expect_ident ("static");
2816 if (LA1
== XBM_TK_IDENT
)
2818 if (strcmp (buffer
, "unsigned") == 0)
2821 expect_ident ("char");
2823 else if (strcmp (buffer
, "short") == 0)
2827 if (*width
% 16 && *width
% 16 < 9)
2830 else if (strcmp (buffer
, "char") == 0)
2838 expect (XBM_TK_IDENT
);
2844 if (! x_check_image_size (0, *width
, *height
))
2846 if (!inhibit_image_error
)
2847 image_error ("Image too large (%dx%d)",
2848 make_number (*width
), make_number (*height
));
2851 bytes_per_line
= (*width
+ 7) / 8 + padding_p
;
2852 nbytes
= bytes_per_line
* *height
;
2853 p
= *data
= xmalloc (nbytes
);
2857 for (i
= 0; i
< nbytes
; i
+= 2)
2860 expect (XBM_TK_NUMBER
);
2862 *p
++ = XBM_BIT_SHUFFLE (val
);
2863 if (!padding_p
|| ((i
+ 2) % bytes_per_line
))
2864 *p
++ = XBM_BIT_SHUFFLE (value
>> 8);
2866 if (LA1
== ',' || LA1
== '}')
2874 for (i
= 0; i
< nbytes
; ++i
)
2877 expect (XBM_TK_NUMBER
);
2879 *p
++ = XBM_BIT_SHUFFLE (val
);
2881 if (LA1
== ',' || LA1
== '}')
2906 /* Load XBM image IMG which will be displayed on frame F from buffer
2907 CONTENTS. END is the end of the buffer. Value is true if
2911 xbm_load_image (struct frame
*f
, struct image
*img
, unsigned char *contents
,
2918 rc
= xbm_read_bitmap_data (f
, contents
, end
, &img
->width
, &img
->height
,
2922 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
2923 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
2924 bool non_default_colors
= 0;
2927 eassert (img
->width
> 0 && img
->height
> 0);
2929 /* Get foreground and background colors, maybe allocate colors. */
2930 value
= image_spec_value (img
->spec
, QCforeground
, NULL
);
2933 foreground
= x_alloc_image_color (f
, img
, value
, foreground
);
2934 non_default_colors
= 1;
2936 value
= image_spec_value (img
->spec
, QCbackground
, NULL
);
2939 background
= x_alloc_image_color (f
, img
, value
, background
);
2940 img
->background
= background
;
2941 img
->background_valid
= 1;
2942 non_default_colors
= 1;
2945 Create_Pixmap_From_Bitmap_Data (f
, img
, data
,
2946 foreground
, background
,
2947 non_default_colors
);
2950 if (img
->pixmap
== NO_PIXMAP
)
2952 x_clear_image (f
, img
);
2953 image_error ("Unable to create X pixmap for `%s'", img
->spec
);
2959 image_error ("Error loading XBM image `%s'", img
->spec
);
2965 /* Value is true if DATA looks like an in-memory XBM file. */
2968 xbm_file_p (Lisp_Object data
)
2971 return (STRINGP (data
)
2972 && xbm_read_bitmap_data (NULL
, SDATA (data
),
2973 (SDATA (data
) + SBYTES (data
)),
2978 /* Fill image IMG which is used on frame F with pixmap data. Value is
2979 true if successful. */
2982 xbm_load (struct frame
*f
, struct image
*img
)
2985 Lisp_Object file_name
;
2987 eassert (xbm_image_p (img
->spec
));
2989 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2990 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
2991 if (STRINGP (file_name
))
2994 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
2995 if (!STRINGP (file
))
2997 image_error ("Cannot find image file `%s'", file_name
);
3002 unsigned char *contents
= slurp_file (fd
, &size
);
3003 if (contents
== NULL
)
3005 image_error ("Error loading XBM image `%s'", file
);
3009 success_p
= xbm_load_image (f
, img
, contents
, contents
+ size
);
3014 struct image_keyword fmt
[XBM_LAST
];
3016 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
3017 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
3018 bool non_default_colors
= 0;
3021 bool in_memory_file_p
= 0;
3023 /* See if data looks like an in-memory XBM file. */
3024 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
3025 in_memory_file_p
= xbm_file_p (data
);
3027 /* Parse the image specification. */
3028 memcpy (fmt
, xbm_format
, sizeof fmt
);
3029 parsed_p
= parse_image_spec (img
->spec
, fmt
, XBM_LAST
, Qxbm
);
3032 /* Get specified width, and height. */
3033 if (!in_memory_file_p
)
3035 img
->width
= XFASTINT (fmt
[XBM_WIDTH
].value
);
3036 img
->height
= XFASTINT (fmt
[XBM_HEIGHT
].value
);
3037 eassert (img
->width
> 0 && img
->height
> 0);
3038 if (!check_image_size (f
, img
->width
, img
->height
))
3040 image_size_error ();
3045 /* Get foreground and background colors, maybe allocate colors. */
3046 if (fmt
[XBM_FOREGROUND
].count
3047 && STRINGP (fmt
[XBM_FOREGROUND
].value
))
3049 foreground
= x_alloc_image_color (f
, img
, fmt
[XBM_FOREGROUND
].value
,
3051 non_default_colors
= 1;
3054 if (fmt
[XBM_BACKGROUND
].count
3055 && STRINGP (fmt
[XBM_BACKGROUND
].value
))
3057 background
= x_alloc_image_color (f
, img
, fmt
[XBM_BACKGROUND
].value
,
3059 non_default_colors
= 1;
3062 if (in_memory_file_p
)
3063 success_p
= xbm_load_image (f
, img
, SDATA (data
),
3074 int nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3076 SAFE_NALLOCA (bits
, nbytes
, img
->height
);
3078 for (i
= 0; i
< img
->height
; ++i
, p
+= nbytes
)
3080 Lisp_Object line
= AREF (data
, i
);
3082 memcpy (p
, SDATA (line
), nbytes
);
3084 memcpy (p
, bool_vector_data (line
), nbytes
);
3087 else if (STRINGP (data
))
3088 bits
= SSDATA (data
);
3090 bits
= (char *) bool_vector_data (data
);
3096 /* Windows mono bitmaps are reversed compared with X. */
3097 invertedBits
= bits
;
3098 nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3099 SAFE_NALLOCA (bits
, nbytes
, img
->height
);
3100 for (i
= 0; i
< nbytes
; i
++)
3101 bits
[i
] = XBM_BIT_SHUFFLE (invertedBits
[i
]);
3104 /* Create the pixmap. */
3106 if (x_check_image_size (0, img
->width
, img
->height
))
3107 Create_Pixmap_From_Bitmap_Data (f
, img
, bits
,
3108 foreground
, background
,
3109 non_default_colors
);
3111 img
->pixmap
= NO_PIXMAP
;
3117 image_error ("Unable to create pixmap for XBM image `%s'",
3119 x_clear_image (f
, img
);
3131 /***********************************************************************
3133 ***********************************************************************/
3135 #if defined (HAVE_XPM) || defined (HAVE_NS)
3137 static bool xpm_image_p (Lisp_Object object
);
3138 static bool xpm_load (struct frame
*f
, struct image
*img
);
3140 #endif /* HAVE_XPM || HAVE_NS */
3144 /* Indicate to xpm.h that we don't have Xlib. */
3146 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3147 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3148 #define XColor xpm_XColor
3149 #define XImage xpm_XImage
3150 #define Display xpm_Display
3151 #define PIXEL_ALREADY_TYPEDEFED
3152 #include "X11/xpm.h"
3157 #undef PIXEL_ALREADY_TYPEDEFED
3159 #include "X11/xpm.h"
3160 #endif /* HAVE_NTGUI */
3161 #endif /* HAVE_XPM */
3163 #if defined (HAVE_XPM) || defined (HAVE_NS)
3165 /* Indices of image specification fields in xpm_format, below. */
3167 enum xpm_keyword_index
3183 /* Vector of image_keyword structures describing the format
3184 of valid XPM image specifications. */
3186 static const struct image_keyword xpm_format
[XPM_LAST
] =
3188 {":type", IMAGE_SYMBOL_VALUE
, 1},
3189 {":file", IMAGE_STRING_VALUE
, 0},
3190 {":data", IMAGE_STRING_VALUE
, 0},
3191 {":ascent", IMAGE_ASCENT_VALUE
, 0},
3192 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
3193 {":relief", IMAGE_INTEGER_VALUE
, 0},
3194 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3195 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3196 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3197 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3198 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
3201 #if defined HAVE_NTGUI && defined WINDOWSNT
3202 static bool init_xpm_functions (void);
3204 #define init_xpm_functions NULL
3207 /* Structure describing the image type XPM. */
3209 static struct image_type xpm_type
=
3211 SYMBOL_INDEX (Qxpm
),
3219 #ifdef HAVE_X_WINDOWS
3221 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3222 functions for allocating image colors. Our own functions handle
3223 color allocation failures more gracefully than the ones on the XPM
3227 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3228 #define ALLOC_XPM_COLORS
3230 #endif /* USE_CAIRO */
3231 #endif /* HAVE_X_WINDOWS */
3233 #ifdef ALLOC_XPM_COLORS
3235 static struct xpm_cached_color
*xpm_cache_color (struct frame
*, char *,
3238 /* An entry in a hash table used to cache color definitions of named
3239 colors. This cache is necessary to speed up XPM image loading in
3240 case we do color allocations ourselves. Without it, we would need
3241 a call to XParseColor per pixel in the image.
3243 FIXME Now that we're using x_parse_color and its cache, reevaluate
3244 the need for this caching layer. */
3246 struct xpm_cached_color
3248 /* Next in collision chain. */
3249 struct xpm_cached_color
*next
;
3251 /* Color definition (RGB and pixel color). */
3255 char name
[FLEXIBLE_ARRAY_MEMBER
];
3258 /* The hash table used for the color cache, and its bucket vector
3261 #define XPM_COLOR_CACHE_BUCKETS 1001
3262 static struct xpm_cached_color
**xpm_color_cache
;
3264 /* Initialize the color cache. */
3267 xpm_init_color_cache (struct frame
*f
, XpmAttributes
*attrs
)
3269 size_t nbytes
= XPM_COLOR_CACHE_BUCKETS
* sizeof *xpm_color_cache
;
3270 xpm_color_cache
= xzalloc (nbytes
);
3271 init_color_table ();
3273 if (attrs
->valuemask
& XpmColorSymbols
)
3278 for (i
= 0; i
< attrs
->numsymbols
; ++i
)
3279 if (x_parse_color (f
, 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 (x_parse_color (f
, color_name
, color
))
3360 color
->pixel
= lookup_rgb_color (f
, color
->red
, color
->green
,
3362 p
= xpm_cache_color (f
, color_name
, color
, h
);
3364 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3365 with transparency, and it's useful. */
3366 else if (strcmp ("opaque", color_name
) == 0)
3368 memset (color
, 0, sizeof (XColor
)); /* Is this necessary/correct? */
3369 color
->pixel
= FRAME_FOREGROUND_PIXEL (f
);
3370 p
= xpm_cache_color (f
, color_name
, color
, h
);
3377 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3378 CLOSURE is a pointer to the frame on which we allocate the
3379 color. Return in *COLOR the allocated color. Value is non-zero
3383 xpm_alloc_color (Display
*dpy
, Colormap cmap
, char *color_name
, XColor
*color
,
3386 return xpm_lookup_color (closure
, color_name
, color
);
3390 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3391 is a pointer to the frame on which we allocate the color. Value is
3392 non-zero if successful. */
3395 xpm_free_colors (Display
*dpy
, Colormap cmap
, Pixel
*pixels
, int npixels
, void *closure
)
3400 #endif /* ALLOC_XPM_COLORS */
3405 /* XPM library details. */
3407 DEF_DLL_FN (void, XpmFreeAttributes
, (XpmAttributes
*));
3408 DEF_DLL_FN (int, XpmCreateImageFromBuffer
,
3409 (Display
*, char *, xpm_XImage
**,
3410 xpm_XImage
**, XpmAttributes
*));
3411 DEF_DLL_FN (int, XpmReadFileToImage
,
3412 (Display
*, char *, xpm_XImage
**,
3413 xpm_XImage
**, XpmAttributes
*));
3414 DEF_DLL_FN (void, XImageFree
, (xpm_XImage
*));
3417 init_xpm_functions (void)
3421 if (!(library
= w32_delayed_load (Qxpm
)))
3424 LOAD_DLL_FN (library
, XpmFreeAttributes
);
3425 LOAD_DLL_FN (library
, XpmCreateImageFromBuffer
);
3426 LOAD_DLL_FN (library
, XpmReadFileToImage
);
3427 LOAD_DLL_FN (library
, XImageFree
);
3432 # undef XpmCreateImageFromBuffer
3433 # undef XpmFreeAttributes
3434 # undef XpmReadFileToImage
3436 # define XImageFree fn_XImageFree
3437 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3438 # define XpmFreeAttributes fn_XpmFreeAttributes
3439 # define XpmReadFileToImage fn_XpmReadFileToImage
3441 #endif /* WINDOWSNT */
3443 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3444 for XPM images. Such a list must consist of conses whose car and
3448 xpm_valid_color_symbols_p (Lisp_Object color_symbols
)
3450 while (CONSP (color_symbols
))
3452 Lisp_Object sym
= XCAR (color_symbols
);
3454 || !STRINGP (XCAR (sym
))
3455 || !STRINGP (XCDR (sym
)))
3457 color_symbols
= XCDR (color_symbols
);
3460 return NILP (color_symbols
);
3464 /* Value is true if OBJECT is a valid XPM image specification. */
3467 xpm_image_p (Lisp_Object object
)
3469 struct image_keyword fmt
[XPM_LAST
];
3470 memcpy (fmt
, xpm_format
, sizeof fmt
);
3471 return (parse_image_spec (object
, fmt
, XPM_LAST
, Qxpm
)
3472 /* Either `:file' or `:data' must be present. */
3473 && fmt
[XPM_FILE
].count
+ fmt
[XPM_DATA
].count
== 1
3474 /* Either no `:color-symbols' or it's a list of conses
3475 whose car and cdr are strings. */
3476 && (fmt
[XPM_COLOR_SYMBOLS
].count
== 0
3477 || xpm_valid_color_symbols_p (fmt
[XPM_COLOR_SYMBOLS
].value
)));
3480 #endif /* HAVE_XPM || HAVE_NS */
3482 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3484 x_create_bitmap_from_xpm_data (struct frame
*f
, const char **bits
)
3486 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
3489 XpmAttributes attrs
;
3490 Pixmap bitmap
, mask
;
3492 memset (&attrs
, 0, sizeof attrs
);
3494 attrs
.visual
= FRAME_X_VISUAL (f
);
3495 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3496 attrs
.valuemask
|= XpmVisual
;
3497 attrs
.valuemask
|= XpmColormap
;
3499 rc
= XpmCreatePixmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3500 (char **) bits
, &bitmap
, &mask
, &attrs
);
3501 if (rc
!= XpmSuccess
)
3503 XpmFreeAttributes (&attrs
);
3507 id
= x_allocate_bitmap_record (f
);
3508 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
3509 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
3510 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
3511 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
3512 dpyinfo
->bitmaps
[id
- 1].height
= attrs
.height
;
3513 dpyinfo
->bitmaps
[id
- 1].width
= attrs
.width
;
3514 dpyinfo
->bitmaps
[id
- 1].depth
= attrs
.depth
;
3515 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
3517 XpmFreeAttributes (&attrs
);
3520 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3522 /* Load image IMG which will be displayed on frame F. Value is
3523 true if successful. */
3528 xpm_load (struct frame
*f
, struct image
*img
)
3531 XpmAttributes attrs
;
3532 Lisp_Object specified_file
, color_symbols
;
3537 xpm_XImage
* xpm_image
= NULL
, * xpm_mask
= NULL
;
3538 #endif /* HAVE_NTGUI */
3540 /* Configure the XPM lib. Use the visual of frame F. Allocate
3541 close colors. Return colors allocated. */
3542 memset (&attrs
, 0, sizeof attrs
);
3545 attrs
.visual
= FRAME_X_VISUAL (f
);
3546 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3547 attrs
.valuemask
|= XpmVisual
;
3548 attrs
.valuemask
|= XpmColormap
;
3549 #endif /* HAVE_NTGUI */
3551 #ifdef ALLOC_XPM_COLORS
3552 /* Allocate colors with our own functions which handle
3553 failing color allocation more gracefully. */
3554 attrs
.color_closure
= f
;
3555 attrs
.alloc_color
= xpm_alloc_color
;
3556 attrs
.free_colors
= xpm_free_colors
;
3557 attrs
.valuemask
|= XpmAllocColor
| XpmFreeColors
| XpmColorClosure
;
3558 #else /* not ALLOC_XPM_COLORS */
3559 /* Let the XPM lib allocate colors. */
3560 attrs
.valuemask
|= XpmReturnAllocPixels
;
3561 #ifdef XpmAllocCloseColors
3562 attrs
.alloc_close_colors
= 1;
3563 attrs
.valuemask
|= XpmAllocCloseColors
;
3564 #else /* not XpmAllocCloseColors */
3565 attrs
.closeness
= 600;
3566 attrs
.valuemask
|= XpmCloseness
;
3567 #endif /* not XpmAllocCloseColors */
3568 #endif /* ALLOC_XPM_COLORS */
3570 /* If image specification contains symbolic color definitions, add
3571 these to `attrs'. */
3572 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
3573 if (CONSP (color_symbols
))
3576 XpmColorSymbol
*xpm_syms
;
3579 attrs
.valuemask
|= XpmColorSymbols
;
3581 /* Count number of symbols. */
3582 attrs
.numsymbols
= 0;
3583 for (tail
= color_symbols
; CONSP (tail
); tail
= XCDR (tail
))
3586 /* Allocate an XpmColorSymbol array. */
3587 SAFE_NALLOCA (xpm_syms
, 1, attrs
.numsymbols
);
3588 size
= attrs
.numsymbols
* sizeof *xpm_syms
;
3589 memset (xpm_syms
, 0, size
);
3590 attrs
.colorsymbols
= xpm_syms
;
3592 /* Fill the color symbol array. */
3593 for (tail
= color_symbols
, i
= 0;
3595 ++i
, tail
= XCDR (tail
))
3599 char *empty_string
= (char *) "";
3601 if (!CONSP (XCAR (tail
)))
3603 xpm_syms
[i
].name
= empty_string
;
3604 xpm_syms
[i
].value
= empty_string
;
3607 name
= XCAR (XCAR (tail
));
3608 color
= XCDR (XCAR (tail
));
3610 SAFE_ALLOCA_STRING (xpm_syms
[i
].name
, name
);
3612 xpm_syms
[i
].name
= empty_string
;
3613 if (STRINGP (color
))
3614 SAFE_ALLOCA_STRING (xpm_syms
[i
].value
, color
);
3616 xpm_syms
[i
].value
= empty_string
;
3620 /* Create a pixmap for the image, either from a file, or from a
3621 string buffer containing data in the same format as an XPM file. */
3622 #ifdef ALLOC_XPM_COLORS
3623 xpm_init_color_cache (f
, &attrs
);
3626 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
3630 HDC frame_dc
= get_frame_dc (f
);
3631 hdc
= CreateCompatibleDC (frame_dc
);
3632 release_frame_dc (f
, frame_dc
);
3634 #endif /* HAVE_NTGUI */
3636 if (STRINGP (specified_file
))
3638 Lisp_Object file
= x_find_image_file (specified_file
);
3639 if (!STRINGP (file
))
3641 image_error ("Cannot find image file `%s'", specified_file
);
3642 #ifdef ALLOC_XPM_COLORS
3643 xpm_free_color_cache ();
3649 file
= ENCODE_FILE (file
);
3652 /* FILE is encoded in UTF-8, but image libraries on Windows
3653 support neither UTF-8 nor UTF-16 encoded file names. So we
3654 need to re-encode it in ANSI. */
3655 file
= ansi_encode_filename (file
);
3657 /* XpmReadFileToPixmap is not available in the Windows port of
3658 libxpm. But XpmReadFileToImage almost does what we want. */
3659 rc
= XpmReadFileToImage (&hdc
, SDATA (file
),
3660 &xpm_image
, &xpm_mask
,
3663 rc
= XpmReadFileToImage (FRAME_X_DISPLAY (f
), SSDATA (file
),
3664 &img
->ximg
, &img
->mask_img
,
3666 #endif /* HAVE_NTGUI */
3670 Lisp_Object buffer
= image_spec_value (img
->spec
, QCdata
, NULL
);
3671 if (!STRINGP (buffer
))
3673 image_error ("Invalid image data `%s'", buffer
);
3674 #ifdef ALLOC_XPM_COLORS
3675 xpm_free_color_cache ();
3681 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3682 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3683 rc
= XpmCreateImageFromBuffer (&hdc
, SDATA (buffer
),
3684 &xpm_image
, &xpm_mask
,
3687 rc
= XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f
), SSDATA (buffer
),
3688 &img
->ximg
, &img
->mask_img
,
3690 #endif /* HAVE_NTGUI */
3694 // Load very specific Xpm:s.
3695 if (rc
== XpmSuccess
3696 && img
->ximg
->format
== ZPixmap
3697 && img
->ximg
->bits_per_pixel
== 32
3698 && (! img
->mask_img
|| img
->mask_img
->bits_per_pixel
== 1))
3700 int width
= img
->ximg
->width
;
3701 int height
= img
->ximg
->height
;
3702 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
3704 uint32_t *od
= (uint32_t *)data
;
3705 uint32_t *id
= (uint32_t *)img
->ximg
->data
;
3706 char *mid
= img
->mask_img
? img
->mask_img
->data
: 0;
3707 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
3709 for (i
= 0; i
< height
; ++i
)
3712 for (k
= 0; k
< width
; ++k
)
3714 int idx
= i
* img
->ximg
->bytes_per_line
/4 + k
;
3715 int maskidx
= mid
? i
* img
->mask_img
->bytes_per_line
+ k
/8 : 0;
3716 int mask
= mid
? mid
[maskidx
] & (1 << (k
% 8)) : 1;
3718 if (mask
) od
[idx
] = id
[idx
] + 0xff000000; // ff => full alpha
3719 else od
[idx
] = bgcolor
;
3723 create_cairo_image_surface (img
, data
, width
, height
);
3727 rc
= XpmFileInvalid
;
3728 x_clear_image (f
, img
);
3731 #ifdef HAVE_X_WINDOWS
3732 if (rc
== XpmSuccess
)
3734 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3735 img
->ximg
->width
, img
->ximg
->height
,
3737 if (img
->pixmap
== NO_PIXMAP
)
3739 x_clear_image (f
, img
);
3742 else if (img
->mask_img
)
3744 img
->mask
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3745 img
->mask_img
->width
,
3746 img
->mask_img
->height
,
3747 img
->mask_img
->depth
);
3748 if (img
->mask
== NO_PIXMAP
)
3750 x_clear_image (f
, img
);
3756 #endif /* ! USE_CAIRO */
3758 if (rc
== XpmSuccess
)
3760 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3761 img
->colors
= colors_in_color_table (&img
->ncolors
);
3762 #else /* not ALLOC_XPM_COLORS */
3766 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3767 plus some duplicate attributes. */
3768 if (xpm_image
&& xpm_image
->bitmap
)
3770 img
->pixmap
= xpm_image
->bitmap
;
3771 /* XImageFree in libXpm frees XImage struct without destroying
3772 the bitmap, which is what we want. */
3773 XImageFree (xpm_image
);
3775 if (xpm_mask
&& xpm_mask
->bitmap
)
3777 /* The mask appears to be inverted compared with what we expect.
3778 TODO: invert our expectations. See other places where we
3779 have to invert bits because our idea of masks is backwards. */
3781 old_obj
= SelectObject (hdc
, xpm_mask
->bitmap
);
3783 PatBlt (hdc
, 0, 0, xpm_mask
->width
, xpm_mask
->height
, DSTINVERT
);
3784 SelectObject (hdc
, old_obj
);
3786 img
->mask
= xpm_mask
->bitmap
;
3787 XImageFree (xpm_mask
);
3792 #endif /* HAVE_NTGUI */
3794 /* Remember allocated colors. */
3795 img
->colors
= xnmalloc (attrs
.nalloc_pixels
, sizeof *img
->colors
);
3796 img
->ncolors
= attrs
.nalloc_pixels
;
3797 for (i
= 0; i
< attrs
.nalloc_pixels
; ++i
)
3799 img
->colors
[i
] = attrs
.alloc_pixels
[i
];
3800 #ifdef DEBUG_X_COLORS
3801 register_color (img
->colors
[i
]);
3804 #endif /* not ALLOC_XPM_COLORS */
3806 img
->width
= attrs
.width
;
3807 img
->height
= attrs
.height
;
3808 eassert (img
->width
> 0 && img
->height
> 0);
3810 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3811 XpmFreeAttributes (&attrs
);
3813 #ifdef HAVE_X_WINDOWS
3814 /* Maybe fill in the background field while we have ximg handy. */
3815 IMAGE_BACKGROUND (img
, f
, img
->ximg
);
3817 /* Fill in the background_transparent field while we have the
3819 image_background_transparent (img
, f
, img
->mask_img
);
3826 #endif /* HAVE_NTGUI */
3831 image_error ("Error opening XPM file (%s)", img
->spec
);
3834 case XpmFileInvalid
:
3835 image_error ("Invalid XPM file (%s)", img
->spec
);
3839 image_error ("Out of memory (%s)", img
->spec
);
3842 case XpmColorFailed
:
3843 image_error ("Color allocation error (%s)", img
->spec
);
3847 image_error ("Unknown error (%s)", img
->spec
);
3852 #ifdef ALLOC_XPM_COLORS
3853 xpm_free_color_cache ();
3856 return rc
== XpmSuccess
;
3859 #endif /* HAVE_XPM */
3861 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3863 /* XPM support functions for NS where libxpm is not available.
3864 Only XPM version 3 (without any extensions) is supported. */
3866 static void xpm_put_color_table_v (Lisp_Object
, const unsigned char *,
3868 static Lisp_Object
xpm_get_color_table_v (Lisp_Object
,
3869 const unsigned char *, int);
3870 static void xpm_put_color_table_h (Lisp_Object
, const unsigned char *,
3872 static Lisp_Object
xpm_get_color_table_h (Lisp_Object
,
3873 const unsigned char *, int);
3875 /* Tokens returned from xpm_scan. */
3884 /* Scan an XPM data and return a character (< 256) or a token defined
3885 by enum xpm_token above. *S and END are the start (inclusive) and
3886 the end (exclusive) addresses of the data, respectively. Advance
3887 *S while scanning. If token is either XPM_TK_IDENT or
3888 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3889 length of the corresponding token, respectively. */
3892 xpm_scan (const unsigned char **s
,
3893 const unsigned char *end
,
3894 const unsigned char **beg
,
3901 /* Skip white-space. */
3902 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
3905 /* gnus-pointer.xpm uses '-' in its identifier.
3906 sb-dir-plus.xpm uses '+' in its identifier. */
3907 if (c_isalpha (c
) || c
== '_' || c
== '-' || c
== '+')
3911 && (c
= **s
, c_isalnum (c
)
3912 || c
== '_' || c
== '-' || c
== '+'))
3915 return XPM_TK_IDENT
;
3920 while (*s
< end
&& **s
!= '"')
3925 return XPM_TK_STRING
;
3929 if (*s
< end
&& **s
== '*')
3931 /* C-style comment. */
3935 while (*s
< end
&& *(*s
)++ != '*')
3938 while (*s
< end
&& **s
!= '/');
3952 /* Functions for color table lookup in XPM data. A key is a string
3953 specifying the color of each pixel in XPM data. A value is either
3954 an integer that specifies a pixel color, Qt that specifies
3955 transparency, or Qnil for the unspecified color. If the length of
3956 the key string is one, a vector is used as a table. Otherwise, a
3957 hash table is used. */
3960 xpm_make_color_table_v (void (**put_func
) (Lisp_Object
,
3961 const unsigned char *,
3964 Lisp_Object (**get_func
) (Lisp_Object
,
3965 const unsigned char *,
3968 *put_func
= xpm_put_color_table_v
;
3969 *get_func
= xpm_get_color_table_v
;
3970 return Fmake_vector (make_number (256), Qnil
);
3974 xpm_put_color_table_v (Lisp_Object color_table
,
3975 const unsigned char *chars_start
,
3979 ASET (color_table
, *chars_start
, color
);
3983 xpm_get_color_table_v (Lisp_Object color_table
,
3984 const unsigned char *chars_start
,
3987 return AREF (color_table
, *chars_start
);
3991 xpm_make_color_table_h (void (**put_func
) (Lisp_Object
,
3992 const unsigned char *,
3995 Lisp_Object (**get_func
) (Lisp_Object
,
3996 const unsigned char *,
3999 *put_func
= xpm_put_color_table_h
;
4000 *get_func
= xpm_get_color_table_h
;
4001 return make_hash_table (hashtest_equal
, make_number (DEFAULT_HASH_SIZE
),
4002 make_float (DEFAULT_REHASH_SIZE
),
4003 make_float (DEFAULT_REHASH_THRESHOLD
),
4008 xpm_put_color_table_h (Lisp_Object color_table
,
4009 const unsigned char *chars_start
,
4013 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4014 EMACS_UINT hash_code
;
4015 Lisp_Object chars
= make_unibyte_string (chars_start
, chars_len
);
4017 hash_lookup (table
, chars
, &hash_code
);
4018 hash_put (table
, chars
, color
, hash_code
);
4022 xpm_get_color_table_h (Lisp_Object color_table
,
4023 const unsigned char *chars_start
,
4026 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4028 hash_lookup (table
, make_unibyte_string (chars_start
, chars_len
), NULL
);
4030 return i
>= 0 ? HASH_VALUE (table
, i
) : Qnil
;
4033 enum xpm_color_key
{
4041 static const char xpm_color_key_strings
[][4] = {"s", "m", "g4", "g", "c"};
4044 xpm_str_to_color_key (const char *s
)
4048 for (i
= 0; i
< ARRAYELTS (xpm_color_key_strings
); i
++)
4049 if (strcmp (xpm_color_key_strings
[i
], s
) == 0)
4055 xpm_load_image (struct frame
*f
,
4057 const unsigned char *contents
,
4058 const unsigned char *end
)
4060 const unsigned char *s
= contents
, *beg
, *str
;
4061 unsigned char buffer
[BUFSIZ
];
4062 int width
, height
, x
, y
;
4063 int num_colors
, chars_per_pixel
;
4066 void (*put_color_table
) (Lisp_Object
, const unsigned char *, int, Lisp_Object
);
4067 Lisp_Object (*get_color_table
) (Lisp_Object
, const unsigned char *, int);
4068 Lisp_Object frame
, color_symbols
, color_table
;
4070 bool have_mask
= false;
4071 XImagePtr ximg
= NULL
, mask_img
= NULL
;
4074 LA1 = xpm_scan (&s, end, &beg, &len)
4076 #define expect(TOKEN) \
4079 if (LA1 != (TOKEN)) \
4085 #define expect_ident(IDENT) \
4086 if (LA1 == XPM_TK_IDENT \
4087 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4092 if (!(end
- s
>= 9 && memcmp (s
, "/* XPM */", 9) == 0))
4096 expect_ident ("static");
4097 expect_ident ("char");
4099 expect (XPM_TK_IDENT
);
4104 expect (XPM_TK_STRING
);
4107 memcpy (buffer
, beg
, len
);
4109 if (sscanf (buffer
, "%d %d %d %d", &width
, &height
,
4110 &num_colors
, &chars_per_pixel
) != 4
4111 || width
<= 0 || height
<= 0
4112 || num_colors
<= 0 || chars_per_pixel
<= 0)
4115 if (!check_image_size (f
, width
, height
))
4117 image_size_error ();
4121 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0)
4123 || !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
4128 image_error ("Image too large");
4134 XSETFRAME (frame
, f
);
4135 if (!NILP (Fxw_display_color_p (frame
)))
4136 best_key
= XPM_COLOR_KEY_C
;
4137 else if (!NILP (Fx_display_grayscale_p (frame
)))
4138 best_key
= (XFASTINT (Fx_display_planes (frame
)) > 2
4139 ? XPM_COLOR_KEY_G
: XPM_COLOR_KEY_G4
);
4141 best_key
= XPM_COLOR_KEY_M
;
4143 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
4144 if (chars_per_pixel
== 1)
4145 color_table
= xpm_make_color_table_v (&put_color_table
,
4148 color_table
= xpm_make_color_table_h (&put_color_table
,
4151 while (num_colors
-- > 0)
4153 char *color
, *max_color
;
4154 int key
, next_key
, max_key
= 0;
4155 Lisp_Object symbol_color
= Qnil
, color_val
;
4158 expect (XPM_TK_STRING
);
4159 if (len
<= chars_per_pixel
|| len
>= BUFSIZ
+ chars_per_pixel
)
4161 memcpy (buffer
, beg
+ chars_per_pixel
, len
- chars_per_pixel
);
4162 buffer
[len
- chars_per_pixel
] = '\0';
4164 str
= strtok (buffer
, " \t");
4167 key
= xpm_str_to_color_key (str
);
4172 color
= strtok (NULL
, " \t");
4176 while ((str
= strtok (NULL
, " \t")) != NULL
)
4178 next_key
= xpm_str_to_color_key (str
);
4181 color
[strlen (color
)] = ' ';
4184 if (key
== XPM_COLOR_KEY_S
)
4186 if (NILP (symbol_color
))
4187 symbol_color
= build_string (color
);
4189 else if (max_key
< key
&& key
<= best_key
)
4199 if (!NILP (color_symbols
) && !NILP (symbol_color
))
4201 Lisp_Object specified_color
= Fassoc (symbol_color
, color_symbols
);
4203 if (CONSP (specified_color
) && STRINGP (XCDR (specified_color
)))
4205 if (xstrcasecmp (SSDATA (XCDR (specified_color
)), "None") == 0)
4207 else if (x_defined_color (f
, SSDATA (XCDR (specified_color
)),
4209 color_val
= make_number (cdef
.pixel
);
4212 if (NILP (color_val
) && max_key
> 0)
4214 if (xstrcasecmp (max_color
, "None") == 0)
4216 else if (x_defined_color (f
, max_color
, &cdef
, 0))
4217 color_val
= make_number (cdef
.pixel
);
4219 if (!NILP (color_val
))
4220 (*put_color_table
) (color_table
, beg
, chars_per_pixel
, color_val
);
4225 for (y
= 0; y
< height
; y
++)
4227 expect (XPM_TK_STRING
);
4229 if (len
< width
* chars_per_pixel
)
4231 for (x
= 0; x
< width
; x
++, str
+= chars_per_pixel
)
4233 Lisp_Object color_val
=
4234 (*get_color_table
) (color_table
, str
, chars_per_pixel
);
4236 XPutPixel (ximg
, x
, y
,
4237 (INTEGERP (color_val
) ? XINT (color_val
)
4238 : FRAME_FOREGROUND_PIXEL (f
)));
4240 XPutPixel (mask_img
, x
, y
,
4241 (!EQ (color_val
, Qt
) ? PIX_MASK_DRAW
4242 : (have_mask
= true, PIX_MASK_RETAIN
)));
4244 if (EQ (color_val
, Qt
))
4245 ns_set_alpha (ximg
, x
, y
, 0);
4253 img
->height
= height
;
4255 /* Maybe fill in the background field while we have ximg handy. */
4256 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
4257 IMAGE_BACKGROUND (img
, f
, ximg
);
4259 image_put_x_image (f
, img
, ximg
, 0);
4263 /* Fill in the background_transparent field while we have the
4265 image_background_transparent (img
, f
, mask_img
);
4267 image_put_x_image (f
, img
, mask_img
, 1);
4271 x_destroy_x_image (mask_img
);
4272 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4278 image_error ("Invalid XPM file (%s)", img
->spec
);
4279 x_destroy_x_image (ximg
);
4280 x_destroy_x_image (mask_img
);
4281 x_clear_image (f
, img
);
4290 xpm_load (struct frame
*f
,
4294 Lisp_Object file_name
;
4296 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4297 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
4298 if (STRINGP (file_name
))
4301 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
4302 if (!STRINGP (file
))
4304 image_error ("Cannot find image file `%s'", file_name
);
4309 unsigned char *contents
= slurp_file (fd
, &size
);
4310 if (contents
== NULL
)
4312 image_error ("Error loading XPM image `%s'", file
);
4316 success_p
= xpm_load_image (f
, img
, contents
, contents
+ size
);
4323 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
4324 if (!STRINGP (data
))
4326 image_error ("Invalid image data `%s'", data
);
4329 success_p
= xpm_load_image (f
, img
, SDATA (data
),
4330 SDATA (data
) + SBYTES (data
));
4336 #endif /* HAVE_NS && !HAVE_XPM */
4340 /***********************************************************************
4342 ***********************************************************************/
4344 #ifdef COLOR_TABLE_SUPPORT
4346 /* An entry in the color table mapping an RGB color to a pixel color. */
4351 unsigned long pixel
;
4353 /* Next in color table collision list. */
4354 struct ct_color
*next
;
4357 /* The bucket vector size to use. Must be prime. */
4361 /* Value is a hash of the RGB color given by R, G, and B. */
4364 ct_hash_rgb (unsigned r
, unsigned g
, unsigned b
)
4366 return (r
<< 16) ^ (g
<< 8) ^ b
;
4369 /* The color hash table. */
4371 static struct ct_color
**ct_table
;
4373 /* Number of entries in the color table. */
4375 static int ct_colors_allocated
;
4378 ct_colors_allocated_max
=
4380 min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof (unsigned long))
4383 /* Initialize the color table. */
4386 init_color_table (void)
4388 int size
= CT_SIZE
* sizeof (*ct_table
);
4389 ct_table
= xzalloc (size
);
4390 ct_colors_allocated
= 0;
4394 /* Free memory associated with the color table. */
4397 free_color_table (void)
4400 struct ct_color
*p
, *next
;
4402 for (i
= 0; i
< CT_SIZE
; ++i
)
4403 for (p
= ct_table
[i
]; p
; p
= next
)
4414 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4415 entry for that color already is in the color table, return the
4416 pixel color of that entry. Otherwise, allocate a new color for R,
4417 G, B, and make an entry in the color table. */
4419 static unsigned long
4420 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4422 unsigned hash
= ct_hash_rgb (r
, g
, b
);
4423 int i
= hash
% CT_SIZE
;
4425 Display_Info
*dpyinfo
;
4427 /* Handle TrueColor visuals specially, which improves performance by
4428 two orders of magnitude. Freeing colors on TrueColor visuals is
4429 a nop, and pixel colors specify RGB values directly. See also
4430 the Xlib spec, chapter 3.1. */
4431 dpyinfo
= FRAME_DISPLAY_INFO (f
);
4432 if (dpyinfo
->red_bits
> 0)
4434 /* Apply gamma-correction like normal color allocation does. */
4438 color
.red
= r
, color
.green
= g
, color
.blue
= b
;
4439 gamma_correct (f
, &color
);
4440 r
= color
.red
, g
= color
.green
, b
= color
.blue
;
4443 return x_make_truecolor_pixel (dpyinfo
, r
, g
, b
);
4446 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4447 if (p
->r
== r
&& p
->g
== g
&& p
->b
== b
)
4453 #ifdef HAVE_X_WINDOWS
4461 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4462 return FRAME_FOREGROUND_PIXEL (f
);
4464 #ifdef HAVE_X_WINDOWS
4469 cmap
= FRAME_X_COLORMAP (f
);
4470 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4473 ++ct_colors_allocated
;
4474 p
= xmalloc (sizeof *p
);
4478 p
->pixel
= color
.pixel
;
4479 p
->next
= ct_table
[i
];
4483 return FRAME_FOREGROUND_PIXEL (f
);
4487 color
= PALETTERGB (r
, g
, b
);
4489 color
= RGB_TO_ULONG (r
, g
, b
);
4490 #endif /* HAVE_NTGUI */
4491 ++ct_colors_allocated
;
4492 p
= xmalloc (sizeof *p
);
4497 p
->next
= ct_table
[i
];
4499 #endif /* HAVE_X_WINDOWS */
4507 /* Look up pixel color PIXEL which is used on frame F in the color
4508 table. If not already present, allocate it. Value is PIXEL. */
4510 static unsigned long
4511 lookup_pixel_color (struct frame
*f
, unsigned long pixel
)
4513 int i
= pixel
% CT_SIZE
;
4516 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4517 if (p
->pixel
== pixel
)
4526 if (ct_colors_allocated
>= ct_colors_allocated_max
)
4527 return FRAME_FOREGROUND_PIXEL (f
);
4529 #ifdef HAVE_X_WINDOWS
4530 cmap
= FRAME_X_COLORMAP (f
);
4531 color
.pixel
= pixel
;
4532 x_query_color (f
, &color
);
4533 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4536 cmap
= DefaultColormapOfScreen (FRAME_X_SCREEN (f
));
4537 color
.pixel
= pixel
;
4538 XQueryColor (NULL
, cmap
, &color
);
4539 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4541 #endif /* HAVE_X_WINDOWS */
4545 ++ct_colors_allocated
;
4547 p
= xmalloc (sizeof *p
);
4552 p
->next
= ct_table
[i
];
4556 return FRAME_FOREGROUND_PIXEL (f
);
4562 /* Value is a vector of all pixel colors contained in the color table,
4563 allocated via xmalloc. Set *N to the number of colors. */
4565 static unsigned long *
4566 colors_in_color_table (int *n
)
4570 unsigned long *colors
;
4572 if (ct_colors_allocated
== 0)
4579 colors
= xmalloc (ct_colors_allocated
* sizeof *colors
);
4580 *n
= ct_colors_allocated
;
4582 for (i
= j
= 0; i
< CT_SIZE
; ++i
)
4583 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4584 colors
[j
++] = p
->pixel
;
4590 #else /* COLOR_TABLE_SUPPORT */
4592 static unsigned long
4593 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4595 unsigned long pixel
;
4598 pixel
= PALETTERGB (r
>> 8, g
>> 8, b
>> 8);
4599 #endif /* HAVE_NTGUI */
4602 pixel
= RGB_TO_ULONG (r
>> 8, g
>> 8, b
>> 8);
4603 #endif /* HAVE_NS */
4608 init_color_table (void)
4611 #endif /* COLOR_TABLE_SUPPORT */
4614 /***********************************************************************
4616 ***********************************************************************/
4618 /* Edge detection matrices for different edge-detection
4621 static int emboss_matrix
[9] = {
4623 2, -1, 0, /* y - 1 */
4625 0, 1, -2 /* y + 1 */
4628 static int laplace_matrix
[9] = {
4630 1, 0, 0, /* y - 1 */
4632 0, 0, -1 /* y + 1 */
4635 /* Value is the intensity of the color whose red/green/blue values
4638 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4641 /* On frame F, return an array of XColor structures describing image
4642 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4643 means also fill the red/green/blue members of the XColor
4644 structures. Value is a pointer to the array of XColors structures,
4645 allocated with xmalloc; it must be freed by the caller. */
4648 x_to_xcolors (struct frame
*f
, struct image
*img
, bool rgb_p
)
4652 XImagePtr_or_DC ximg
;
4655 #endif /* HAVE_NTGUI */
4657 if (img
->height
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *colors
/ img
->width
)
4658 memory_full (SIZE_MAX
);
4659 colors
= xmalloc (sizeof *colors
* img
->width
* img
->height
);
4661 /* Get the X image or create a memory device context for IMG. */
4662 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4664 /* Fill the `pixel' members of the XColor array. I wished there
4665 were an easy and portable way to circumvent XGetPixel. */
4667 for (y
= 0; y
< img
->height
; ++y
)
4669 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4671 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4672 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4674 x_query_colors (f
, row
, img
->width
);
4678 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4680 /* W32_TODO: palette support needed here? */
4681 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4684 p
->red
= RED16_FROM_ULONG (p
->pixel
);
4685 p
->green
= GREEN16_FROM_ULONG (p
->pixel
);
4686 p
->blue
= BLUE16_FROM_ULONG (p
->pixel
);
4689 #endif /* HAVE_X_WINDOWS */
4692 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
4699 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4700 created with CreateDIBSection, with the pointer to the bit values
4701 stored in ximg->data. */
4704 XPutPixel (XImagePtr ximg
, int x
, int y
, COLORREF color
)
4706 int width
= ximg
->info
.bmiHeader
.biWidth
;
4707 unsigned char * pixel
;
4709 /* True color images. */
4710 if (ximg
->info
.bmiHeader
.biBitCount
== 24)
4712 int rowbytes
= width
* 3;
4713 /* Ensure scanlines are aligned on 4 byte boundaries. */
4715 rowbytes
+= 4 - (rowbytes
% 4);
4717 pixel
= ximg
->data
+ y
* rowbytes
+ x
* 3;
4718 /* Windows bitmaps are in BGR order. */
4719 *pixel
= GetBValue (color
);
4720 *(pixel
+ 1) = GetGValue (color
);
4721 *(pixel
+ 2) = GetRValue (color
);
4723 /* Monochrome images. */
4724 else if (ximg
->info
.bmiHeader
.biBitCount
== 1)
4726 int rowbytes
= width
/ 8;
4727 /* Ensure scanlines are aligned on 4 byte boundaries. */
4729 rowbytes
+= 4 - (rowbytes
% 4);
4730 pixel
= ximg
->data
+ y
* rowbytes
+ x
/ 8;
4731 /* Filter out palette info. */
4732 if (color
& 0x00ffffff)
4733 *pixel
= *pixel
| (1 << x
% 8);
4735 *pixel
= *pixel
& ~(1 << x
% 8);
4738 image_error ("XPutPixel: palette image not supported");
4741 #endif /* HAVE_NTGUI */
4743 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4744 RGB members are set. F is the frame on which this all happens.
4745 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4748 x_from_xcolors (struct frame
*f
, struct image
*img
, XColor
*colors
)
4751 XImagePtr oimg
= NULL
;
4754 init_color_table ();
4756 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_COLORS
);
4757 image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 0,
4760 for (y
= 0; y
< img
->height
; ++y
)
4761 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4763 unsigned long pixel
;
4764 pixel
= lookup_rgb_color (f
, p
->red
, p
->green
, p
->blue
);
4765 XPutPixel (oimg
, x
, y
, pixel
);
4770 image_put_x_image (f
, img
, oimg
, 0);
4771 #ifdef COLOR_TABLE_SUPPORT
4772 img
->colors
= colors_in_color_table (&img
->ncolors
);
4773 free_color_table ();
4774 #endif /* COLOR_TABLE_SUPPORT */
4778 /* On frame F, perform edge-detection on image IMG.
4780 MATRIX is a nine-element array specifying the transformation
4781 matrix. See emboss_matrix for an example.
4783 COLOR_ADJUST is a color adjustment added to each pixel of the
4787 x_detect_edges (struct frame
*f
, struct image
*img
, int *matrix
, int color_adjust
)
4789 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4793 for (i
= sum
= 0; i
< 9; ++i
)
4794 sum
+= eabs (matrix
[i
]);
4796 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4798 if (img
->height
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *new / img
->width
)
4799 memory_full (SIZE_MAX
);
4800 new = xmalloc (sizeof *new * img
->width
* img
->height
);
4802 for (y
= 0; y
< img
->height
; ++y
)
4804 p
= COLOR (new, 0, y
);
4805 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4806 p
= COLOR (new, img
->width
- 1, y
);
4807 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4810 for (x
= 1; x
< img
->width
- 1; ++x
)
4812 p
= COLOR (new, x
, 0);
4813 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4814 p
= COLOR (new, x
, img
->height
- 1);
4815 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4818 for (y
= 1; y
< img
->height
- 1; ++y
)
4820 p
= COLOR (new, 1, y
);
4822 for (x
= 1; x
< img
->width
- 1; ++x
, ++p
)
4824 int r
, g
, b
, yy
, xx
;
4827 for (yy
= y
- 1; yy
< y
+ 2; ++yy
)
4828 for (xx
= x
- 1; xx
< x
+ 2; ++xx
, ++i
)
4831 XColor
*t
= COLOR (colors
, xx
, yy
);
4832 r
+= matrix
[i
] * t
->red
;
4833 g
+= matrix
[i
] * t
->green
;
4834 b
+= matrix
[i
] * t
->blue
;
4837 r
= (r
/ sum
+ color_adjust
) & 0xffff;
4838 g
= (g
/ sum
+ color_adjust
) & 0xffff;
4839 b
= (b
/ sum
+ color_adjust
) & 0xffff;
4840 p
->red
= p
->green
= p
->blue
= COLOR_INTENSITY (r
, g
, b
);
4845 x_from_xcolors (f
, img
, new);
4851 /* Perform the pre-defined `emboss' edge-detection on image IMG
4855 x_emboss (struct frame
*f
, struct image
*img
)
4857 x_detect_edges (f
, img
, emboss_matrix
, 0xffff / 2);
4861 /* Transform image IMG which is used on frame F with a Laplace
4862 edge-detection algorithm. The result is an image that can be used
4863 to draw disabled buttons, for example. */
4866 x_laplace (struct frame
*f
, struct image
*img
)
4868 x_detect_edges (f
, img
, laplace_matrix
, 45000);
4872 /* Perform edge-detection on image IMG on frame F, with specified
4873 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4875 MATRIX must be either
4877 - a list of at least 9 numbers in row-major form
4878 - a vector of at least 9 numbers
4880 COLOR_ADJUST nil means use a default; otherwise it must be a
4884 x_edge_detection (struct frame
*f
, struct image
*img
, Lisp_Object matrix
,
4885 Lisp_Object color_adjust
)
4893 i
< 9 && CONSP (matrix
) && NUMBERP (XCAR (matrix
));
4894 ++i
, matrix
= XCDR (matrix
))
4895 trans
[i
] = XFLOATINT (XCAR (matrix
));
4897 else if (VECTORP (matrix
) && ASIZE (matrix
) >= 9)
4899 for (i
= 0; i
< 9 && NUMBERP (AREF (matrix
, i
)); ++i
)
4900 trans
[i
] = XFLOATINT (AREF (matrix
, i
));
4903 if (NILP (color_adjust
))
4904 color_adjust
= make_number (0xffff / 2);
4906 if (i
== 9 && NUMBERP (color_adjust
))
4907 x_detect_edges (f
, img
, trans
, XFLOATINT (color_adjust
));
4911 /* Transform image IMG on frame F so that it looks disabled. */
4914 x_disable_image (struct frame
*f
, struct image
*img
)
4916 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
4918 int n_planes
= dpyinfo
->n_planes
* dpyinfo
->n_cbits
;
4920 int n_planes
= dpyinfo
->n_planes
;
4921 #endif /* HAVE_NTGUI */
4925 /* Color (or grayscale). Convert to gray, and equalize. Just
4926 drawing such images with a stipple can look very odd, so
4927 we're using this method instead. */
4928 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4930 const int h
= 15000;
4931 const int l
= 30000;
4933 for (p
= colors
, end
= colors
+ img
->width
* img
->height
;
4937 int i
= COLOR_INTENSITY (p
->red
, p
->green
, p
->blue
);
4938 int i2
= (0xffff - h
- l
) * i
/ 0xffff + l
;
4939 p
->red
= p
->green
= p
->blue
= i2
;
4942 x_from_xcolors (f
, img
, colors
);
4945 /* Draw a cross over the disabled image, if we must or if we
4947 if (n_planes
< 2 || cross_disabled_images
)
4950 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4952 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4954 Display
*dpy
= FRAME_X_DISPLAY (f
);
4957 image_sync_to_pixmaps (f
, img
);
4958 gc
= XCreateGC (dpy
, img
->pixmap
, 0, NULL
);
4959 XSetForeground (dpy
, gc
, BLACK_PIX_DEFAULT (f
));
4960 XDrawLine (dpy
, img
->pixmap
, gc
, 0, 0,
4961 img
->width
- 1, img
->height
- 1);
4962 XDrawLine (dpy
, img
->pixmap
, gc
, 0, img
->height
- 1,
4968 gc
= XCreateGC (dpy
, img
->mask
, 0, NULL
);
4969 XSetForeground (dpy
, gc
, MaskForeground (f
));
4970 XDrawLine (dpy
, img
->mask
, gc
, 0, 0,
4971 img
->width
- 1, img
->height
- 1);
4972 XDrawLine (dpy
, img
->mask
, gc
, 0, img
->height
- 1,
4976 #endif /* !HAVE_NS */
4981 hdc
= get_frame_dc (f
);
4982 bmpdc
= CreateCompatibleDC (hdc
);
4983 release_frame_dc (f
, hdc
);
4985 prev
= SelectObject (bmpdc
, img
->pixmap
);
4987 SetTextColor (bmpdc
, BLACK_PIX_DEFAULT (f
));
4988 MoveToEx (bmpdc
, 0, 0, NULL
);
4989 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
4990 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
4991 LineTo (bmpdc
, img
->width
- 1, 0);
4995 SelectObject (bmpdc
, img
->mask
);
4996 SetTextColor (bmpdc
, WHITE_PIX_DEFAULT (f
));
4997 MoveToEx (bmpdc
, 0, 0, NULL
);
4998 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
4999 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
5000 LineTo (bmpdc
, img
->width
- 1, 0);
5002 SelectObject (bmpdc
, prev
);
5004 #endif /* HAVE_NTGUI */
5009 /* Build a mask for image IMG which is used on frame F. FILE is the
5010 name of an image file, for error messages. HOW determines how to
5011 determine the background color of IMG. If it is a list '(R G B)',
5012 with R, G, and B being integers >= 0, take that as the color of the
5013 background. Otherwise, determine the background color of IMG
5017 x_build_heuristic_mask (struct frame
*f
, struct image
*img
, Lisp_Object how
)
5019 XImagePtr_or_DC ximg
;
5026 #endif /* HAVE_NTGUI */
5028 bool use_img_background
;
5029 unsigned long bg
= 0;
5032 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
5036 /* Create an image and pixmap serving as mask. */
5037 if (! image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 1,
5040 #endif /* !HAVE_NS */
5042 /* Create the bit array serving as mask. */
5043 row_width
= (img
->width
+ 7) / 8;
5044 mask_img
= xzalloc (row_width
* img
->height
);
5045 #endif /* HAVE_NTGUI */
5047 /* Get the X image or create a memory device context for IMG. */
5048 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
5050 /* Determine the background color of ximg. If HOW is `(R G B)'
5051 take that as color. Otherwise, use the image's background color. */
5052 use_img_background
= 1;
5058 for (i
= 0; i
< 3 && CONSP (how
) && NATNUMP (XCAR (how
)); ++i
)
5060 rgb
[i
] = XFASTINT (XCAR (how
)) & 0xffff;
5064 if (i
== 3 && NILP (how
))
5066 char color_name
[30];
5067 sprintf (color_name
, "#%04x%04x%04x",
5068 rgb
[0] + 0u, rgb
[1] + 0u, rgb
[2] + 0u);
5071 0x00ffffff & /* Filter out palette info. */
5072 #endif /* HAVE_NTGUI */
5073 x_alloc_image_color (f
, img
, build_string (color_name
), 0));
5074 use_img_background
= 0;
5078 if (use_img_background
)
5079 bg
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
5081 /* Set all bits in mask_img to 1 whose color in ximg is different
5082 from the background color bg. */
5084 for (y
= 0; y
< img
->height
; ++y
)
5085 for (x
= 0; x
< img
->width
; ++x
)
5087 XPutPixel (mask_img
, x
, y
, (XGetPixel (ximg
, x
, y
) != bg
5088 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
));
5090 if (XGetPixel (ximg
, x
, y
) == bg
)
5091 ns_set_alpha (ximg
, x
, y
, 0);
5092 #endif /* HAVE_NS */
5094 /* Fill in the background_transparent field while we have the mask handy. */
5095 image_background_transparent (img
, f
, mask_img
);
5097 /* Put mask_img into the image. */
5098 image_put_x_image (f
, img
, mask_img
, 1);
5099 #endif /* !HAVE_NS */
5101 for (y
= 0; y
< img
->height
; ++y
)
5102 for (x
= 0; x
< img
->width
; ++x
)
5104 COLORREF p
= GetPixel (ximg
, x
, y
);
5106 mask_img
[y
* row_width
+ x
/ 8] |= 1 << (x
% 8);
5109 /* Create the mask image. */
5110 img
->mask
= w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
,
5112 /* Fill in the background_transparent field while we have the mask handy. */
5113 SelectObject (ximg
, img
->mask
);
5114 image_background_transparent (img
, f
, ximg
);
5116 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5118 #endif /* HAVE_NTGUI */
5120 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
5124 /***********************************************************************
5125 PBM (mono, gray, color)
5126 ***********************************************************************/
5128 static bool pbm_image_p (Lisp_Object object
);
5129 static bool pbm_load (struct frame
*f
, struct image
*img
);
5131 /* Indices of image specification fields in gs_format, below. */
5133 enum pbm_keyword_index
5149 /* Vector of image_keyword structures describing the format
5150 of valid user-defined image specifications. */
5152 static const struct image_keyword pbm_format
[PBM_LAST
] =
5154 {":type", IMAGE_SYMBOL_VALUE
, 1},
5155 {":file", IMAGE_STRING_VALUE
, 0},
5156 {":data", IMAGE_STRING_VALUE
, 0},
5157 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5158 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5159 {":relief", IMAGE_INTEGER_VALUE
, 0},
5160 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5161 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5162 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5163 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
5164 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5167 /* Structure describing the image type `pbm'. */
5169 static struct image_type pbm_type
=
5171 SYMBOL_INDEX (Qpbm
),
5180 /* Return true if OBJECT is a valid PBM image specification. */
5183 pbm_image_p (Lisp_Object object
)
5185 struct image_keyword fmt
[PBM_LAST
];
5187 memcpy (fmt
, pbm_format
, sizeof fmt
);
5189 if (!parse_image_spec (object
, fmt
, PBM_LAST
, Qpbm
))
5192 /* Must specify either :data or :file. */
5193 return fmt
[PBM_DATA
].count
+ fmt
[PBM_FILE
].count
== 1;
5197 /* Get next char skipping comments in Netpbm header. Returns -1 at
5201 pbm_next_char (unsigned char **s
, unsigned char *end
)
5205 while (*s
< end
&& (c
= *(*s
)++, c
== '#'))
5207 /* Skip to the next line break. */
5208 while (*s
< end
&& (c
= *(*s
)++, c
!= '\n' && c
!= '\r'))
5218 /* Scan a decimal number from *S and return it. Advance *S while
5219 reading the number. END is the end of the string. Value is -1 at
5223 pbm_scan_number (unsigned char **s
, unsigned char *end
)
5225 int c
= 0, val
= -1;
5227 /* Skip white-space. */
5228 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isspace (c
))
5233 /* Read decimal number. */
5235 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isdigit (c
))
5236 val
= 10 * val
+ c
- '0';
5243 /* Load PBM image IMG for use on frame F. */
5246 pbm_load (struct frame
*f
, struct image
*img
)
5250 int width
, height
, max_color_idx
= 0;
5251 Lisp_Object specified_file
;
5252 enum {PBM_MONO
, PBM_GRAY
, PBM_COLOR
} type
;
5253 unsigned char *contents
= NULL
;
5254 unsigned char *end
, *p
;
5256 unsigned char *data
= 0;
5262 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5264 if (STRINGP (specified_file
))
5267 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5268 if (!STRINGP (file
))
5270 image_error ("Cannot find image file `%s'", specified_file
);
5275 contents
= slurp_file (fd
, &size
);
5276 if (contents
== NULL
)
5278 image_error ("Error reading `%s'", file
);
5283 end
= contents
+ size
;
5288 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5289 if (!STRINGP (data
))
5291 image_error ("Invalid image data `%s'", data
);
5295 end
= p
+ SBYTES (data
);
5298 /* Check magic number. */
5299 if (end
- p
< 2 || *p
++ != 'P')
5301 image_error ("Not a PBM image: `%s'", img
->spec
);
5304 img
->pixmap
= NO_PIXMAP
;
5311 raw_p
= 0, type
= PBM_MONO
;
5315 raw_p
= 0, type
= PBM_GRAY
;
5319 raw_p
= 0, type
= PBM_COLOR
;
5323 raw_p
= 1, type
= PBM_MONO
;
5327 raw_p
= 1, type
= PBM_GRAY
;
5331 raw_p
= 1, type
= PBM_COLOR
;
5335 image_error ("Not a PBM image: `%s'", img
->spec
);
5339 /* Read width, height, maximum color-component. Characters
5340 starting with `#' up to the end of a line are ignored. */
5341 width
= pbm_scan_number (&p
, end
);
5342 height
= pbm_scan_number (&p
, end
);
5345 data
= (unsigned char *) xmalloc (width
* height
* 4);
5346 dataptr
= (uint32_t *) data
;
5349 if (type
!= PBM_MONO
)
5351 max_color_idx
= pbm_scan_number (&p
, end
);
5352 if (max_color_idx
> 65535 || max_color_idx
< 0)
5354 image_error ("Unsupported maximum PBM color value");
5359 if (!check_image_size (f
, width
, height
))
5361 image_size_error ();
5366 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5370 /* Initialize the color hash table. */
5371 init_color_table ();
5373 if (type
== PBM_MONO
)
5376 struct image_keyword fmt
[PBM_LAST
];
5377 unsigned long fg
= FRAME_FOREGROUND_PIXEL (f
);
5378 unsigned long bg
= FRAME_BACKGROUND_PIXEL (f
);
5383 /* Parse the image specification. */
5384 memcpy (fmt
, pbm_format
, sizeof fmt
);
5385 parse_image_spec (img
->spec
, fmt
, PBM_LAST
, Qpbm
);
5387 /* Get foreground and background colors, maybe allocate colors. */
5389 if (! fmt
[PBM_FOREGROUND
].count
5390 || ! STRINGP (fmt
[PBM_FOREGROUND
].value
)
5391 || ! x_defined_color (f
, SSDATA (fmt
[PBM_FOREGROUND
].value
), &xfg
, 0))
5394 x_query_color (f
, &xfg
);
5396 fga32
= xcolor_to_argb32 (xfg
);
5398 if (! fmt
[PBM_BACKGROUND
].count
5399 || ! STRINGP (fmt
[PBM_BACKGROUND
].value
)
5400 || ! x_defined_color (f
, SSDATA (fmt
[PBM_BACKGROUND
].value
), &xbg
, 0))
5403 x_query_color (f
, &xbg
);
5405 bga32
= xcolor_to_argb32 (xbg
);
5407 if (fmt
[PBM_FOREGROUND
].count
5408 && STRINGP (fmt
[PBM_FOREGROUND
].value
))
5409 fg
= x_alloc_image_color (f
, img
, fmt
[PBM_FOREGROUND
].value
, fg
);
5410 if (fmt
[PBM_BACKGROUND
].count
5411 && STRINGP (fmt
[PBM_BACKGROUND
].value
))
5413 bg
= x_alloc_image_color (f
, img
, fmt
[PBM_BACKGROUND
].value
, bg
);
5414 img
->background
= bg
;
5415 img
->background_valid
= 1;
5419 for (y
= 0; y
< height
; ++y
)
5420 for (x
= 0; x
< width
; ++x
)
5431 x_destroy_x_image (ximg
);
5433 x_clear_image (f
, img
);
5434 image_error ("Invalid image size in image `%s'",
5444 g
= pbm_scan_number (&p
, end
);
5447 *dataptr
++ = g
? fga32
: bga32
;
5449 XPutPixel (ximg
, x
, y
, g
? fg
: bg
);
5455 int expected_size
= height
* width
;
5456 if (max_color_idx
> 255)
5458 if (type
== PBM_COLOR
)
5461 if (raw_p
&& p
+ expected_size
> end
)
5466 x_destroy_x_image (ximg
);
5468 x_clear_image (f
, img
);
5469 image_error ("Invalid image size in image `%s'", img
->spec
);
5473 for (y
= 0; y
< height
; ++y
)
5474 for (x
= 0; x
< width
; ++x
)
5478 if (type
== PBM_GRAY
&& raw_p
)
5481 if (max_color_idx
> 255)
5482 r
= g
= b
= r
* 256 + *p
++;
5484 else if (type
== PBM_GRAY
)
5485 r
= g
= b
= pbm_scan_number (&p
, end
);
5489 if (max_color_idx
> 255)
5492 if (max_color_idx
> 255)
5495 if (max_color_idx
> 255)
5500 r
= pbm_scan_number (&p
, end
);
5501 g
= pbm_scan_number (&p
, end
);
5502 b
= pbm_scan_number (&p
, end
);
5505 if (r
< 0 || g
< 0 || b
< 0)
5510 x_destroy_x_image (ximg
);
5512 image_error ("Invalid pixel value in image `%s'", img
->spec
);
5517 r
= (double) r
* 255 / max_color_idx
;
5518 g
= (double) g
* 255 / max_color_idx
;
5519 b
= (double) b
* 255 / max_color_idx
;
5520 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
5522 /* RGB values are now in the range 0..max_color_idx.
5523 Scale this to the range 0..0xffff supported by X. */
5524 r
= (double) r
* 65535 / max_color_idx
;
5525 g
= (double) g
* 65535 / max_color_idx
;
5526 b
= (double) b
* 65535 / max_color_idx
;
5527 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5532 #ifdef COLOR_TABLE_SUPPORT
5533 /* Store in IMG->colors the colors allocated for the image, and
5534 free the color table. */
5535 img
->colors
= colors_in_color_table (&img
->ncolors
);
5536 free_color_table ();
5537 #endif /* COLOR_TABLE_SUPPORT */
5540 img
->height
= height
;
5542 /* Maybe fill in the background field while we have ximg handy. */
5545 create_cairo_image_surface (img
, data
, width
, height
);
5547 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
5548 /* Casting avoids a GCC warning. */
5549 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
5551 /* Put ximg into the image. */
5552 image_put_x_image (f
, img
, ximg
, 0);
5555 /* X and W32 versions did it here, MAC version above. ++kfs
5557 img->height = height; */
5564 /***********************************************************************
5566 ***********************************************************************/
5568 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5570 /* Function prototypes. */
5572 static bool png_image_p (Lisp_Object object
);
5573 static bool png_load (struct frame
*f
, struct image
*img
);
5575 /* Indices of image specification fields in png_format, below. */
5577 enum png_keyword_index
5592 /* Vector of image_keyword structures describing the format
5593 of valid user-defined image specifications. */
5595 static const struct image_keyword png_format
[PNG_LAST
] =
5597 {":type", IMAGE_SYMBOL_VALUE
, 1},
5598 {":data", IMAGE_STRING_VALUE
, 0},
5599 {":file", IMAGE_STRING_VALUE
, 0},
5600 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5601 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5602 {":relief", IMAGE_INTEGER_VALUE
, 0},
5603 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5604 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5605 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5606 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5609 #if defined HAVE_NTGUI && defined WINDOWSNT
5610 static bool init_png_functions (void);
5612 #define init_png_functions NULL
5615 /* Structure describing the image type `png'. */
5617 static struct image_type png_type
=
5619 SYMBOL_INDEX (Qpng
),
5627 /* Return true if OBJECT is a valid PNG image specification. */
5630 png_image_p (Lisp_Object object
)
5632 struct image_keyword fmt
[PNG_LAST
];
5633 memcpy (fmt
, png_format
, sizeof fmt
);
5635 if (!parse_image_spec (object
, fmt
, PNG_LAST
, Qpng
))
5638 /* Must specify either the :data or :file keyword. */
5639 return fmt
[PNG_FILE
].count
+ fmt
[PNG_DATA
].count
== 1;
5642 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5645 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5648 /* PNG library details. */
5650 DEF_DLL_FN (png_voidp
, png_get_io_ptr
, (png_structp
));
5651 DEF_DLL_FN (int, png_sig_cmp
, (png_bytep
, png_size_t
, png_size_t
));
5652 DEF_DLL_FN (png_structp
, png_create_read_struct
,
5653 (png_const_charp
, png_voidp
, png_error_ptr
, png_error_ptr
));
5654 DEF_DLL_FN (png_infop
, png_create_info_struct
, (png_structp
));
5655 DEF_DLL_FN (void, png_destroy_read_struct
,
5656 (png_structpp
, png_infopp
, png_infopp
));
5657 DEF_DLL_FN (void, png_set_read_fn
, (png_structp
, png_voidp
, png_rw_ptr
));
5658 DEF_DLL_FN (void, png_set_sig_bytes
, (png_structp
, int));
5659 DEF_DLL_FN (void, png_read_info
, (png_structp
, png_infop
));
5660 DEF_DLL_FN (png_uint_32
, png_get_IHDR
,
5661 (png_structp
, png_infop
, png_uint_32
*, png_uint_32
*,
5662 int *, int *, int *, int *, int *));
5663 DEF_DLL_FN (png_uint_32
, png_get_valid
, (png_structp
, png_infop
, png_uint_32
));
5664 DEF_DLL_FN (void, png_set_strip_16
, (png_structp
));
5665 DEF_DLL_FN (void, png_set_expand
, (png_structp
));
5666 DEF_DLL_FN (void, png_set_gray_to_rgb
, (png_structp
));
5667 DEF_DLL_FN (void, png_set_background
,
5668 (png_structp
, png_color_16p
, int, int, double));
5669 DEF_DLL_FN (png_uint_32
, png_get_bKGD
,
5670 (png_structp
, png_infop
, png_color_16p
*));
5671 DEF_DLL_FN (void, png_read_update_info
, (png_structp
, png_infop
));
5672 DEF_DLL_FN (png_byte
, png_get_channels
, (png_structp
, png_infop
));
5673 DEF_DLL_FN (png_size_t
, png_get_rowbytes
, (png_structp
, png_infop
));
5674 DEF_DLL_FN (void, png_read_image
, (png_structp
, png_bytepp
));
5675 DEF_DLL_FN (void, png_read_end
, (png_structp
, png_infop
));
5676 DEF_DLL_FN (void, png_error
, (png_structp
, png_const_charp
));
5678 # if (PNG_LIBPNG_VER >= 10500)
5679 DEF_DLL_FN (void, png_longjmp
, (png_structp
, int)) PNG_NORETURN
;
5680 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn
,
5681 (png_structp
, png_longjmp_ptr
, size_t));
5682 # endif /* libpng version >= 1.5 */
5685 init_png_functions (void)
5689 if (!(library
= w32_delayed_load (Qpng
)))
5692 LOAD_DLL_FN (library
, png_get_io_ptr
);
5693 LOAD_DLL_FN (library
, png_sig_cmp
);
5694 LOAD_DLL_FN (library
, png_create_read_struct
);
5695 LOAD_DLL_FN (library
, png_create_info_struct
);
5696 LOAD_DLL_FN (library
, png_destroy_read_struct
);
5697 LOAD_DLL_FN (library
, png_set_read_fn
);
5698 LOAD_DLL_FN (library
, png_set_sig_bytes
);
5699 LOAD_DLL_FN (library
, png_read_info
);
5700 LOAD_DLL_FN (library
, png_get_IHDR
);
5701 LOAD_DLL_FN (library
, png_get_valid
);
5702 LOAD_DLL_FN (library
, png_set_strip_16
);
5703 LOAD_DLL_FN (library
, png_set_expand
);
5704 LOAD_DLL_FN (library
, png_set_gray_to_rgb
);
5705 LOAD_DLL_FN (library
, png_set_background
);
5706 LOAD_DLL_FN (library
, png_get_bKGD
);
5707 LOAD_DLL_FN (library
, png_read_update_info
);
5708 LOAD_DLL_FN (library
, png_get_channels
);
5709 LOAD_DLL_FN (library
, png_get_rowbytes
);
5710 LOAD_DLL_FN (library
, png_read_image
);
5711 LOAD_DLL_FN (library
, png_read_end
);
5712 LOAD_DLL_FN (library
, png_error
);
5714 # if (PNG_LIBPNG_VER >= 10500)
5715 LOAD_DLL_FN (library
, png_longjmp
);
5716 LOAD_DLL_FN (library
, png_set_longjmp_fn
);
5717 # endif /* libpng version >= 1.5 */
5722 # undef png_create_info_struct
5723 # undef png_create_read_struct
5724 # undef png_destroy_read_struct
5726 # undef png_get_bKGD
5727 # undef png_get_channels
5728 # undef png_get_IHDR
5729 # undef png_get_io_ptr
5730 # undef png_get_rowbytes
5731 # undef png_get_valid
5733 # undef png_read_end
5734 # undef png_read_image
5735 # undef png_read_info
5736 # undef png_read_update_info
5737 # undef png_set_background
5738 # undef png_set_expand
5739 # undef png_set_gray_to_rgb
5740 # undef png_set_longjmp_fn
5741 # undef png_set_read_fn
5742 # undef png_set_sig_bytes
5743 # undef png_set_strip_16
5746 # define png_create_info_struct fn_png_create_info_struct
5747 # define png_create_read_struct fn_png_create_read_struct
5748 # define png_destroy_read_struct fn_png_destroy_read_struct
5749 # define png_error fn_png_error
5750 # define png_get_bKGD fn_png_get_bKGD
5751 # define png_get_channels fn_png_get_channels
5752 # define png_get_IHDR fn_png_get_IHDR
5753 # define png_get_io_ptr fn_png_get_io_ptr
5754 # define png_get_rowbytes fn_png_get_rowbytes
5755 # define png_get_valid fn_png_get_valid
5756 # define png_longjmp fn_png_longjmp
5757 # define png_read_end fn_png_read_end
5758 # define png_read_image fn_png_read_image
5759 # define png_read_info fn_png_read_info
5760 # define png_read_update_info fn_png_read_update_info
5761 # define png_set_background fn_png_set_background
5762 # define png_set_expand fn_png_set_expand
5763 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5764 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5765 # define png_set_read_fn fn_png_set_read_fn
5766 # define png_set_sig_bytes fn_png_set_sig_bytes
5767 # define png_set_strip_16 fn_png_set_strip_16
5768 # define png_sig_cmp fn_png_sig_cmp
5770 # endif /* WINDOWSNT */
5772 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5773 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5774 Do not use sys_setjmp, as PNG supports only jmp_buf.
5775 It's OK if the longjmp substitute restores the signal mask. */
5776 # ifdef HAVE__SETJMP
5777 # define FAST_SETJMP(j) _setjmp (j)
5778 # define FAST_LONGJMP _longjmp
5780 # define FAST_SETJMP(j) setjmp (j)
5781 # define FAST_LONGJMP longjmp
5784 # if PNG_LIBPNG_VER < 10500
5785 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5786 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5788 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5789 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5790 # define PNG_JMPBUF(ptr) \
5791 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5794 /* Error and warning handlers installed when the PNG library
5797 static _Noreturn
void
5798 my_png_error (png_struct
*png_ptr
, const char *msg
)
5800 eassert (png_ptr
!= NULL
);
5801 /* Avoid compiler warning about deprecated direct access to
5802 png_ptr's fields in libpng versions 1.4.x. */
5803 image_error ("PNG error: %s", build_string (msg
));
5804 PNG_LONGJMP (png_ptr
);
5809 my_png_warning (png_struct
*png_ptr
, const char *msg
)
5811 eassert (png_ptr
!= NULL
);
5812 image_error ("PNG warning: %s", build_string (msg
));
5815 /* Memory source for PNG decoding. */
5817 struct png_memory_storage
5819 unsigned char *bytes
; /* The data */
5820 ptrdiff_t len
; /* How big is it? */
5821 ptrdiff_t index
; /* Where are we? */
5825 /* Function set as reader function when reading PNG image from memory.
5826 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5827 bytes from the input to DATA. */
5830 png_read_from_memory (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5832 struct png_memory_storage
*tbr
= png_get_io_ptr (png_ptr
);
5834 if (length
> tbr
->len
- tbr
->index
)
5835 png_error (png_ptr
, "Read error");
5837 memcpy (data
, tbr
->bytes
+ tbr
->index
, length
);
5838 tbr
->index
= tbr
->index
+ length
;
5842 /* Function set as reader function when reading PNG image from a file.
5843 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5844 bytes from the input to DATA. */
5847 png_read_from_file (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5849 FILE *fp
= png_get_io_ptr (png_ptr
);
5851 if (fread (data
, 1, length
, fp
) < length
)
5852 png_error (png_ptr
, "Read error");
5856 /* Load PNG image IMG for use on frame F. Value is true if
5859 struct png_load_context
5861 /* These are members so that longjmp doesn't munge local variables. */
5862 png_struct
*png_ptr
;
5871 png_load_body (struct frame
*f
, struct image
*img
, struct png_load_context
*c
)
5873 Lisp_Object specified_file
;
5874 Lisp_Object specified_data
;
5877 png_struct
*png_ptr
;
5878 png_info
*info_ptr
= NULL
, *end_info
= NULL
;
5881 png_byte
*pixels
= NULL
;
5882 png_byte
**rows
= NULL
;
5883 png_uint_32 width
, height
;
5884 int bit_depth
, color_type
, interlace_type
;
5886 png_uint_32 row_bytes
;
5888 struct png_memory_storage tbr
; /* Data to be read */
5891 unsigned char *data
= 0;
5894 XImagePtr ximg
, mask_img
= NULL
;
5897 /* Find out what file to load. */
5898 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5899 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5900 IF_LINT (Lisp_Object
volatile specified_data_volatile
= specified_data
);
5902 if (NILP (specified_data
))
5905 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5906 if (!STRINGP (file
))
5908 image_error ("Cannot find image file `%s'", specified_file
);
5912 /* Open the image file. */
5913 fp
= fdopen (fd
, "rb");
5916 image_error ("Cannot open image file `%s'", file
);
5920 /* Check PNG signature. */
5921 if (fread (sig
, 1, sizeof sig
, fp
) != sizeof sig
5922 || png_sig_cmp (sig
, 0, sizeof sig
))
5925 image_error ("Not a PNG file: `%s'", file
);
5931 if (!STRINGP (specified_data
))
5933 image_error ("Invalid image data `%s'", specified_data
);
5937 /* Read from memory. */
5938 tbr
.bytes
= SDATA (specified_data
);
5939 tbr
.len
= SBYTES (specified_data
);
5942 /* Check PNG signature. */
5943 if (tbr
.len
< sizeof sig
5944 || png_sig_cmp (tbr
.bytes
, 0, sizeof sig
))
5946 image_error ("Not a PNG image: `%s'", img
->spec
);
5950 /* Need to skip past the signature. */
5951 tbr
.bytes
+= sizeof (sig
);
5954 /* Initialize read and info structs for PNG lib. */
5955 png_ptr
= png_create_read_struct (PNG_LIBPNG_VER_STRING
,
5960 info_ptr
= png_create_info_struct (png_ptr
);
5961 end_info
= png_create_info_struct (png_ptr
);
5964 c
->png_ptr
= png_ptr
;
5965 c
->info_ptr
= info_ptr
;
5966 c
->end_info
= end_info
;
5971 if (! (info_ptr
&& end_info
))
5973 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5978 if (fp
) fclose (fp
);
5982 /* Set error jump-back. We come back here when the PNG library
5983 detects an error. */
5984 if (FAST_SETJMP (PNG_JMPBUF (png_ptr
)))
5988 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5996 /* Silence a bogus diagnostic; see GCC bug 54561. */
5997 IF_LINT (fp
= c
->fp
);
5998 IF_LINT (specified_data
= specified_data_volatile
);
6000 /* Read image info. */
6001 if (!NILP (specified_data
))
6002 png_set_read_fn (png_ptr
, &tbr
, png_read_from_memory
);
6004 png_set_read_fn (png_ptr
, fp
, png_read_from_file
);
6006 png_set_sig_bytes (png_ptr
, sizeof sig
);
6007 png_read_info (png_ptr
, info_ptr
);
6008 png_get_IHDR (png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
,
6009 &interlace_type
, NULL
, NULL
);
6011 if (! (width
<= INT_MAX
&& height
<= INT_MAX
6012 && check_image_size (f
, width
, height
)))
6014 image_size_error ();
6019 /* Create the X image and pixmap now, so that the work below can be
6020 omitted if the image is too large for X. */
6021 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6025 /* If image contains simply transparency data, we prefer to
6026 construct a clipping mask. */
6027 if (png_get_valid (png_ptr
, info_ptr
, PNG_INFO_tRNS
))
6032 /* This function is easier to write if we only have to handle
6033 one data format: RGB or RGBA with 8 bits per channel. Let's
6034 transform other formats into that format. */
6036 /* Strip more than 8 bits per channel. */
6037 if (bit_depth
== 16)
6038 png_set_strip_16 (png_ptr
);
6040 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6042 png_set_expand (png_ptr
);
6044 /* Convert grayscale images to RGB. */
6045 if (color_type
== PNG_COLOR_TYPE_GRAY
6046 || color_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
6047 png_set_gray_to_rgb (png_ptr
);
6049 /* Handle alpha channel by combining the image with a background
6050 color. Do this only if a real alpha channel is supplied. For
6051 simple transparency, we prefer a clipping mask. */
6054 /* png_color_16 *image_bg; */
6055 Lisp_Object specified_bg
6056 = image_spec_value (img
->spec
, QCbackground
, NULL
);
6059 /* If the user specified a color, try to use it; if not, use the
6060 current frame background, ignoring any default background
6061 color set by the image. */
6062 if (STRINGP (specified_bg
)
6063 ? x_defined_color (f
, SSDATA (specified_bg
), &color
, false)
6064 : (x_query_frame_background_color (f
, &color
), true))
6065 /* The user specified `:background', use that. */
6067 int shift
= bit_depth
== 16 ? 0 : 8;
6068 png_color_16 bg
= { 0 };
6069 bg
.red
= color
.red
>> shift
;
6070 bg
.green
= color
.green
>> shift
;
6071 bg
.blue
= color
.blue
>> shift
;
6073 png_set_background (png_ptr
, &bg
,
6074 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
6078 /* Update info structure. */
6079 png_read_update_info (png_ptr
, info_ptr
);
6081 /* Get number of channels. Valid values are 1 for grayscale images
6082 and images with a palette, 2 for grayscale images with transparency
6083 information (alpha channel), 3 for RGB images, and 4 for RGB
6084 images with alpha channel, i.e. RGBA. If conversions above were
6085 sufficient we should only have 3 or 4 channels here. */
6086 channels
= png_get_channels (png_ptr
, info_ptr
);
6087 eassert (channels
== 3 || channels
== 4);
6089 /* Number of bytes needed for one row of the image. */
6090 row_bytes
= png_get_rowbytes (png_ptr
, info_ptr
);
6092 /* Allocate memory for the image. */
6093 if (height
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *rows
6094 || row_bytes
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *pixels
/ height
)
6095 memory_full (SIZE_MAX
);
6096 c
->pixels
= pixels
= xmalloc (sizeof *pixels
* row_bytes
* height
);
6097 c
->rows
= rows
= xmalloc (height
* sizeof *rows
);
6098 for (i
= 0; i
< height
; ++i
)
6099 rows
[i
] = pixels
+ i
* row_bytes
;
6101 /* Read the entire image. */
6102 png_read_image (png_ptr
, rows
);
6103 png_read_end (png_ptr
, info_ptr
);
6111 data
= (unsigned char *) xmalloc (width
* height
* 4);
6112 dataptr
= (uint32_t *) data
;
6114 /* Create an image and pixmap serving as mask if the PNG image
6115 contains an alpha channel. */
6118 && !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
6121 x_destroy_x_image (ximg
);
6122 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
);
6127 /* Fill the X image and mask from PNG data. */
6128 init_color_table ();
6130 for (y
= 0; y
< height
; ++y
)
6132 png_byte
*p
= rows
[y
];
6134 for (x
= 0; x
< width
; ++x
)
6143 if (channels
== 4) a
= *p
++;
6144 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
6149 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
6150 /* An alpha channel, aka mask channel, associates variable
6151 transparency with an image. Where other image formats
6152 support binary transparency---fully transparent or fully
6153 opaque---PNG allows up to 254 levels of partial transparency.
6154 The PNG library implements partial transparency by combining
6155 the image with a specified background color.
6157 I'm not sure how to handle this here nicely: because the
6158 background on which the image is displayed may change, for
6159 real alpha channel support, it would be necessary to create
6160 a new image for each possible background.
6162 What I'm doing now is that a mask is created if we have
6163 boolean transparency information. Otherwise I'm using
6164 the frame's background color to combine the image with. */
6169 XPutPixel (mask_img
, x
, y
, *p
> 0 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
);
6176 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6177 /* Set IMG's background color from the PNG image, unless the user
6181 if (png_get_bKGD (png_ptr
, info_ptr
, &bg
))
6183 img
->background
= lookup_rgb_color (f
, bg
->red
, bg
->green
, bg
->blue
);
6184 img
->background_valid
= 1;
6188 # ifdef COLOR_TABLE_SUPPORT
6189 /* Remember colors allocated for this image. */
6190 img
->colors
= colors_in_color_table (&img
->ncolors
);
6191 free_color_table ();
6192 # endif /* COLOR_TABLE_SUPPORT */
6195 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6200 img
->height
= height
;
6203 create_cairo_image_surface (img
, data
, width
, height
);
6205 /* Maybe fill in the background field while we have ximg handy.
6206 Casting avoids a GCC warning. */
6207 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6209 /* Put ximg into the image. */
6210 image_put_x_image (f
, img
, ximg
, 0);
6212 /* Same for the mask. */
6215 /* Fill in the background_transparent field while we have the
6216 mask handy. Casting avoids a GCC warning. */
6217 image_background_transparent (img
, f
, (XImagePtr_or_DC
)mask_img
);
6219 image_put_x_image (f
, img
, mask_img
, 1);
6227 png_load (struct frame
*f
, struct image
*img
)
6229 struct png_load_context c
;
6230 return png_load_body (f
, img
, &c
);
6233 #elif defined HAVE_NS
6236 png_load (struct frame
*f
, struct image
*img
)
6238 return ns_load_image (f
, img
,
6239 image_spec_value (img
->spec
, QCfile
, NULL
),
6240 image_spec_value (img
->spec
, QCdata
, NULL
));
6244 #endif /* HAVE_NS */
6248 /***********************************************************************
6250 ***********************************************************************/
6252 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6254 static bool jpeg_image_p (Lisp_Object object
);
6255 static bool jpeg_load (struct frame
*f
, struct image
*img
);
6257 /* Indices of image specification fields in gs_format, below. */
6259 enum jpeg_keyword_index
6268 JPEG_HEURISTIC_MASK
,
6274 /* Vector of image_keyword structures describing the format
6275 of valid user-defined image specifications. */
6277 static const struct image_keyword jpeg_format
[JPEG_LAST
] =
6279 {":type", IMAGE_SYMBOL_VALUE
, 1},
6280 {":data", IMAGE_STRING_VALUE
, 0},
6281 {":file", IMAGE_STRING_VALUE
, 0},
6282 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6283 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6284 {":relief", IMAGE_INTEGER_VALUE
, 0},
6285 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6286 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6287 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6288 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
6291 #if defined HAVE_NTGUI && defined WINDOWSNT
6292 static bool init_jpeg_functions (void);
6294 #define init_jpeg_functions NULL
6297 /* Structure describing the image type `jpeg'. */
6299 static struct image_type jpeg_type
=
6301 SYMBOL_INDEX (Qjpeg
),
6305 init_jpeg_functions
,
6309 /* Return true if OBJECT is a valid JPEG image specification. */
6312 jpeg_image_p (Lisp_Object object
)
6314 struct image_keyword fmt
[JPEG_LAST
];
6316 memcpy (fmt
, jpeg_format
, sizeof fmt
);
6318 if (!parse_image_spec (object
, fmt
, JPEG_LAST
, Qjpeg
))
6321 /* Must specify either the :data or :file keyword. */
6322 return fmt
[JPEG_FILE
].count
+ fmt
[JPEG_DATA
].count
== 1;
6325 #endif /* HAVE_JPEG || HAVE_NS */
6329 /* Work around a warning about HAVE_STDLIB_H being redefined in
6331 # ifdef HAVE_STDLIB_H
6332 # undef HAVE_STDLIB_H
6335 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6336 /* In older releases of the jpeg library, jpeglib.h will define boolean
6337 differently depending on __WIN32__, so make sure it is defined. */
6338 # define __WIN32__ 1
6341 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6342 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6343 using the Windows boolean type instead of the jpeglib boolean type
6344 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6345 headers are included along with windows.h, so under Cygwin, jpeglib
6346 attempts to define a conflicting boolean type. Worse, forcing
6347 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6348 because it created an ABI incompatibility between the
6349 already-compiled jpeg library and the header interface definition.
6351 The best we can do is to define jpeglib's boolean type to a
6352 different name. This name, jpeg_boolean, remains in effect through
6353 the rest of image.c.
6355 # if defined CYGWIN && defined HAVE_NTGUI
6356 # define boolean jpeg_boolean
6358 # include <jpeglib.h>
6359 # include <jerror.h>
6363 /* JPEG library details. */
6364 DEF_DLL_FN (void, jpeg_CreateDecompress
, (j_decompress_ptr
, int, size_t));
6365 DEF_DLL_FN (boolean
, jpeg_start_decompress
, (j_decompress_ptr
));
6366 DEF_DLL_FN (boolean
, jpeg_finish_decompress
, (j_decompress_ptr
));
6367 DEF_DLL_FN (void, jpeg_destroy_decompress
, (j_decompress_ptr
));
6368 DEF_DLL_FN (int, jpeg_read_header
, (j_decompress_ptr
, boolean
));
6369 DEF_DLL_FN (JDIMENSION
, jpeg_read_scanlines
,
6370 (j_decompress_ptr
, JSAMPARRAY
, JDIMENSION
));
6371 DEF_DLL_FN (struct jpeg_error_mgr
*, jpeg_std_error
,
6372 (struct jpeg_error_mgr
*));
6373 DEF_DLL_FN (boolean
, jpeg_resync_to_restart
, (j_decompress_ptr
, int));
6376 init_jpeg_functions (void)
6380 if (!(library
= w32_delayed_load (Qjpeg
)))
6383 LOAD_DLL_FN (library
, jpeg_finish_decompress
);
6384 LOAD_DLL_FN (library
, jpeg_read_scanlines
);
6385 LOAD_DLL_FN (library
, jpeg_start_decompress
);
6386 LOAD_DLL_FN (library
, jpeg_read_header
);
6387 LOAD_DLL_FN (library
, jpeg_CreateDecompress
);
6388 LOAD_DLL_FN (library
, jpeg_destroy_decompress
);
6389 LOAD_DLL_FN (library
, jpeg_std_error
);
6390 LOAD_DLL_FN (library
, jpeg_resync_to_restart
);
6394 # undef jpeg_CreateDecompress
6395 # undef jpeg_destroy_decompress
6396 # undef jpeg_finish_decompress
6397 # undef jpeg_read_header
6398 # undef jpeg_read_scanlines
6399 # undef jpeg_resync_to_restart
6400 # undef jpeg_start_decompress
6401 # undef jpeg_std_error
6403 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6404 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6405 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6406 # define jpeg_read_header fn_jpeg_read_header
6407 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6408 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6409 # define jpeg_start_decompress fn_jpeg_start_decompress
6410 # define jpeg_std_error fn_jpeg_std_error
6412 /* Wrapper since we can't directly assign the function pointer
6413 to another function pointer that was declared more completely easily. */
6415 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo
, int desired
)
6417 return jpeg_resync_to_restart (cinfo
, desired
);
6419 # undef jpeg_resync_to_restart
6420 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6422 # endif /* WINDOWSNT */
6424 struct my_jpeg_error_mgr
6426 struct jpeg_error_mgr pub
;
6427 sys_jmp_buf setjmp_buffer
;
6429 /* The remaining members are so that longjmp doesn't munge local
6431 struct jpeg_decompress_struct cinfo
;
6435 MY_JPEG_INVALID_IMAGE_SIZE
,
6436 MY_JPEG_CANNOT_CREATE_X
6441 static _Noreturn
void
6442 my_error_exit (j_common_ptr cinfo
)
6444 struct my_jpeg_error_mgr
*mgr
= (struct my_jpeg_error_mgr
*) cinfo
->err
;
6445 mgr
->failure_code
= MY_JPEG_ERROR_EXIT
;
6446 sys_longjmp (mgr
->setjmp_buffer
, 1);
6450 /* Init source method for JPEG data source manager. Called by
6451 jpeg_read_header() before any data is actually read. See
6452 libjpeg.doc from the JPEG lib distribution. */
6455 our_common_init_source (j_decompress_ptr cinfo
)
6460 /* Method to terminate data source. Called by
6461 jpeg_finish_decompress() after all data has been processed. */
6464 our_common_term_source (j_decompress_ptr cinfo
)
6469 /* Fill input buffer method for JPEG data source manager. Called
6470 whenever more data is needed. We read the whole image in one step,
6471 so this only adds a fake end of input marker at the end. */
6473 static JOCTET our_memory_buffer
[2];
6476 our_memory_fill_input_buffer (j_decompress_ptr cinfo
)
6478 /* Insert a fake EOI marker. */
6479 struct jpeg_source_mgr
*src
= cinfo
->src
;
6481 our_memory_buffer
[0] = (JOCTET
) 0xFF;
6482 our_memory_buffer
[1] = (JOCTET
) JPEG_EOI
;
6484 src
->next_input_byte
= our_memory_buffer
;
6485 src
->bytes_in_buffer
= 2;
6490 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6491 is the JPEG data source manager. */
6494 our_memory_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6496 struct jpeg_source_mgr
*src
= cinfo
->src
;
6500 if (num_bytes
> src
->bytes_in_buffer
)
6501 ERREXIT (cinfo
, JERR_INPUT_EOF
);
6503 src
->bytes_in_buffer
-= num_bytes
;
6504 src
->next_input_byte
+= num_bytes
;
6509 /* Set up the JPEG lib for reading an image from DATA which contains
6510 LEN bytes. CINFO is the decompression info structure created for
6511 reading the image. */
6514 jpeg_memory_src (j_decompress_ptr cinfo
, JOCTET
*data
, ptrdiff_t len
)
6516 struct jpeg_source_mgr
*src
= cinfo
->src
;
6520 /* First time for this JPEG object? */
6521 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6522 JPOOL_PERMANENT
, sizeof *src
);
6524 src
->next_input_byte
= data
;
6527 src
->init_source
= our_common_init_source
;
6528 src
->fill_input_buffer
= our_memory_fill_input_buffer
;
6529 src
->skip_input_data
= our_memory_skip_input_data
;
6530 src
->resync_to_restart
= jpeg_resync_to_restart
; /* Use default method. */
6531 src
->term_source
= our_common_term_source
;
6532 src
->bytes_in_buffer
= len
;
6533 src
->next_input_byte
= data
;
6537 struct jpeg_stdio_mgr
6539 struct jpeg_source_mgr mgr
;
6546 /* Size of buffer to read JPEG from file.
6547 Not too big, as we want to use alloc_small. */
6548 #define JPEG_STDIO_BUFFER_SIZE 8192
6551 /* Fill input buffer method for JPEG data source manager. Called
6552 whenever more data is needed. The data is read from a FILE *. */
6555 our_stdio_fill_input_buffer (j_decompress_ptr cinfo
)
6557 struct jpeg_stdio_mgr
*src
;
6559 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6564 bytes
= fread (src
->buffer
, 1, JPEG_STDIO_BUFFER_SIZE
, src
->file
);
6566 src
->mgr
.bytes_in_buffer
= bytes
;
6569 WARNMS (cinfo
, JWRN_JPEG_EOF
);
6571 src
->buffer
[0] = (JOCTET
) 0xFF;
6572 src
->buffer
[1] = (JOCTET
) JPEG_EOI
;
6573 src
->mgr
.bytes_in_buffer
= 2;
6575 src
->mgr
.next_input_byte
= src
->buffer
;
6582 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6583 is the JPEG data source manager. */
6586 our_stdio_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6588 struct jpeg_stdio_mgr
*src
;
6589 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6591 while (num_bytes
> 0 && !src
->finished
)
6593 if (num_bytes
<= src
->mgr
.bytes_in_buffer
)
6595 src
->mgr
.bytes_in_buffer
-= num_bytes
;
6596 src
->mgr
.next_input_byte
+= num_bytes
;
6601 num_bytes
-= src
->mgr
.bytes_in_buffer
;
6602 src
->mgr
.bytes_in_buffer
= 0;
6603 src
->mgr
.next_input_byte
= NULL
;
6605 our_stdio_fill_input_buffer (cinfo
);
6611 /* Set up the JPEG lib for reading an image from a FILE *.
6612 CINFO is the decompression info structure created for
6613 reading the image. */
6616 jpeg_file_src (j_decompress_ptr cinfo
, FILE *fp
)
6618 struct jpeg_stdio_mgr
*src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6622 /* First time for this JPEG object? */
6623 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6624 JPOOL_PERMANENT
, sizeof *src
);
6625 cinfo
->src
= (struct jpeg_source_mgr
*) src
;
6626 src
->buffer
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6628 JPEG_STDIO_BUFFER_SIZE
);
6633 src
->mgr
.init_source
= our_common_init_source
;
6634 src
->mgr
.fill_input_buffer
= our_stdio_fill_input_buffer
;
6635 src
->mgr
.skip_input_data
= our_stdio_skip_input_data
;
6636 src
->mgr
.resync_to_restart
= jpeg_resync_to_restart
; /* Use default. */
6637 src
->mgr
.term_source
= our_common_term_source
;
6638 src
->mgr
.bytes_in_buffer
= 0;
6639 src
->mgr
.next_input_byte
= NULL
;
6642 /* Load image IMG for use on frame F. Patterned after example.c
6643 from the JPEG lib. */
6646 jpeg_load_body (struct frame
*f
, struct image
*img
,
6647 struct my_jpeg_error_mgr
*mgr
)
6649 Lisp_Object specified_file
;
6650 Lisp_Object specified_data
;
6651 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6652 FILE * IF_LINT (volatile) fp
= NULL
;
6654 int row_stride
, x
, y
;
6655 unsigned long *colors
;
6659 XImagePtr ximg
= NULL
;
6662 /* Open the JPEG file. */
6663 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6664 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6665 IF_LINT (Lisp_Object
volatile specified_data_volatile
= specified_data
);
6667 if (NILP (specified_data
))
6670 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
6671 if (!STRINGP (file
))
6673 image_error ("Cannot find image file `%s'", specified_file
);
6677 fp
= fdopen (fd
, "rb");
6680 image_error ("Cannot open `%s'", file
);
6684 else if (!STRINGP (specified_data
))
6686 image_error ("Invalid image data `%s'", specified_data
);
6690 /* Customize libjpeg's error handling to call my_error_exit when an
6691 error is detected. This function will perform a longjmp. */
6692 mgr
->cinfo
.err
= jpeg_std_error (&mgr
->pub
);
6693 mgr
->pub
.error_exit
= my_error_exit
;
6694 if (sys_setjmp (mgr
->setjmp_buffer
))
6696 switch (mgr
->failure_code
)
6698 case MY_JPEG_ERROR_EXIT
:
6700 char buf
[JMSG_LENGTH_MAX
];
6701 mgr
->cinfo
.err
->format_message ((j_common_ptr
) &mgr
->cinfo
, buf
);
6702 image_error ("Error reading JPEG image `%s': %s",
6703 img
->spec
, build_string (buf
));
6707 case MY_JPEG_INVALID_IMAGE_SIZE
:
6708 image_size_error ();
6711 case MY_JPEG_CANNOT_CREATE_X
:
6715 /* Close the input file and destroy the JPEG object. */
6718 jpeg_destroy_decompress (&mgr
->cinfo
);
6720 /* If we already have an XImage, free that. */
6722 x_destroy_x_image (ximg
);
6724 /* Free pixmap and colors. */
6725 x_clear_image (f
, img
);
6729 /* Silence a bogus diagnostic; see GCC bug 54561. */
6730 IF_LINT (specified_data
= specified_data_volatile
);
6732 /* Create the JPEG decompression object. Let it read from fp.
6733 Read the JPEG image header. */
6734 jpeg_CreateDecompress (&mgr
->cinfo
, JPEG_LIB_VERSION
, sizeof *&mgr
->cinfo
);
6736 if (NILP (specified_data
))
6737 jpeg_file_src (&mgr
->cinfo
, fp
);
6739 jpeg_memory_src (&mgr
->cinfo
, SDATA (specified_data
),
6740 SBYTES (specified_data
));
6742 jpeg_read_header (&mgr
->cinfo
, 1);
6744 /* Customize decompression so that color quantization will be used.
6745 Start decompression. */
6746 mgr
->cinfo
.quantize_colors
= 1;
6747 jpeg_start_decompress (&mgr
->cinfo
);
6748 width
= img
->width
= mgr
->cinfo
.output_width
;
6749 height
= img
->height
= mgr
->cinfo
.output_height
;
6751 if (!check_image_size (f
, width
, height
))
6753 mgr
->failure_code
= MY_JPEG_INVALID_IMAGE_SIZE
;
6754 sys_longjmp (mgr
->setjmp_buffer
, 1);
6758 /* Create X image and pixmap. */
6759 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6761 mgr
->failure_code
= MY_JPEG_CANNOT_CREATE_X
;
6762 sys_longjmp (mgr
->setjmp_buffer
, 1);
6766 /* Allocate colors. When color quantization is used,
6767 mgr->cinfo.actual_number_of_colors has been set with the number of
6768 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6769 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6770 No more than 255 colors will be generated. */
6773 if (mgr
->cinfo
.out_color_components
> 2)
6774 ir
= 0, ig
= 1, ib
= 2;
6775 else if (mgr
->cinfo
.out_color_components
> 1)
6776 ir
= 0, ig
= 1, ib
= 0;
6778 ir
= 0, ig
= 0, ib
= 0;
6781 /* Use the color table mechanism because it handles colors that
6782 cannot be allocated nicely. Such colors will be replaced with
6783 a default color, and we don't have to care about which colors
6784 can be freed safely, and which can't. */
6785 init_color_table ();
6786 SAFE_NALLOCA (colors
, 1, mgr
->cinfo
.actual_number_of_colors
);
6788 for (i
= 0; i
< mgr
->cinfo
.actual_number_of_colors
; ++i
)
6790 /* Multiply RGB values with 255 because X expects RGB values
6791 in the range 0..0xffff. */
6792 int r
= mgr
->cinfo
.colormap
[ir
][i
] << 8;
6793 int g
= mgr
->cinfo
.colormap
[ig
][i
] << 8;
6794 int b
= mgr
->cinfo
.colormap
[ib
][i
] << 8;
6795 colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
6799 #ifdef COLOR_TABLE_SUPPORT
6800 /* Remember those colors actually allocated. */
6801 img
->colors
= colors_in_color_table (&img
->ncolors
);
6802 free_color_table ();
6803 #endif /* COLOR_TABLE_SUPPORT */
6807 row_stride
= width
* mgr
->cinfo
.output_components
;
6808 buffer
= mgr
->cinfo
.mem
->alloc_sarray ((j_common_ptr
) &mgr
->cinfo
,
6809 JPOOL_IMAGE
, row_stride
, 1);
6812 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
6813 uint32_t *dataptr
= (uint32_t *) data
;
6816 for (y
= 0; y
< height
; ++y
)
6818 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6820 for (x
= 0; x
< width
; ++x
)
6823 r
= mgr
->cinfo
.colormap
[ir
][i
];
6824 g
= mgr
->cinfo
.colormap
[ig
][i
];
6825 b
= mgr
->cinfo
.colormap
[ib
][i
];
6826 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
6830 create_cairo_image_surface (img
, data
, width
, height
);
6833 for (y
= 0; y
< height
; ++y
)
6835 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6836 for (x
= 0; x
< mgr
->cinfo
.output_width
; ++x
)
6837 XPutPixel (ximg
, x
, y
, colors
[buffer
[0][x
]]);
6842 jpeg_finish_decompress (&mgr
->cinfo
);
6843 jpeg_destroy_decompress (&mgr
->cinfo
);
6848 /* Maybe fill in the background field while we have ximg handy. */
6849 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6850 /* Casting avoids a GCC warning. */
6851 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6853 /* Put ximg into the image. */
6854 image_put_x_image (f
, img
, ximg
, 0);
6861 jpeg_load (struct frame
*f
, struct image
*img
)
6863 struct my_jpeg_error_mgr mgr
;
6864 return jpeg_load_body (f
, img
, &mgr
);
6867 #else /* HAVE_JPEG */
6871 jpeg_load (struct frame
*f
, struct image
*img
)
6873 return ns_load_image (f
, img
,
6874 image_spec_value (img
->spec
, QCfile
, NULL
),
6875 image_spec_value (img
->spec
, QCdata
, NULL
));
6877 #endif /* HAVE_NS */
6879 #endif /* !HAVE_JPEG */
6883 /***********************************************************************
6885 ***********************************************************************/
6887 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6889 static bool tiff_image_p (Lisp_Object object
);
6890 static bool tiff_load (struct frame
*f
, struct image
*img
);
6892 /* Indices of image specification fields in tiff_format, below. */
6894 enum tiff_keyword_index
6903 TIFF_HEURISTIC_MASK
,
6910 /* Vector of image_keyword structures describing the format
6911 of valid user-defined image specifications. */
6913 static const struct image_keyword tiff_format
[TIFF_LAST
] =
6915 {":type", IMAGE_SYMBOL_VALUE
, 1},
6916 {":data", IMAGE_STRING_VALUE
, 0},
6917 {":file", IMAGE_STRING_VALUE
, 0},
6918 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6919 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6920 {":relief", IMAGE_INTEGER_VALUE
, 0},
6921 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6922 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6923 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6924 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
6925 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0}
6928 #if defined HAVE_NTGUI && defined WINDOWSNT
6929 static bool init_tiff_functions (void);
6931 #define init_tiff_functions NULL
6934 /* Structure describing the image type `tiff'. */
6936 static struct image_type tiff_type
=
6938 SYMBOL_INDEX (Qtiff
),
6942 init_tiff_functions
,
6946 /* Return true if OBJECT is a valid TIFF image specification. */
6949 tiff_image_p (Lisp_Object object
)
6951 struct image_keyword fmt
[TIFF_LAST
];
6952 memcpy (fmt
, tiff_format
, sizeof fmt
);
6954 if (!parse_image_spec (object
, fmt
, TIFF_LAST
, Qtiff
))
6957 /* Must specify either the :data or :file keyword. */
6958 return fmt
[TIFF_FILE
].count
+ fmt
[TIFF_DATA
].count
== 1;
6961 #endif /* HAVE_TIFF || HAVE_NS */
6965 # include <tiffio.h>
6969 /* TIFF library details. */
6970 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetErrorHandler
, (TIFFErrorHandler
));
6971 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetWarningHandler
, (TIFFErrorHandler
));
6972 DEF_DLL_FN (TIFF
*, TIFFOpen
, (const char *, const char *));
6973 DEF_DLL_FN (TIFF
*, TIFFClientOpen
,
6974 (const char *, const char *, thandle_t
, TIFFReadWriteProc
,
6975 TIFFReadWriteProc
, TIFFSeekProc
, TIFFCloseProc
, TIFFSizeProc
,
6976 TIFFMapFileProc
, TIFFUnmapFileProc
));
6977 DEF_DLL_FN (int, TIFFGetField
, (TIFF
*, ttag_t
, ...));
6978 DEF_DLL_FN (int, TIFFReadRGBAImage
, (TIFF
*, uint32
, uint32
, uint32
*, int));
6979 DEF_DLL_FN (void, TIFFClose
, (TIFF
*));
6980 DEF_DLL_FN (int, TIFFSetDirectory
, (TIFF
*, tdir_t
));
6983 init_tiff_functions (void)
6987 if (!(library
= w32_delayed_load (Qtiff
)))
6990 LOAD_DLL_FN (library
, TIFFSetErrorHandler
);
6991 LOAD_DLL_FN (library
, TIFFSetWarningHandler
);
6992 LOAD_DLL_FN (library
, TIFFOpen
);
6993 LOAD_DLL_FN (library
, TIFFClientOpen
);
6994 LOAD_DLL_FN (library
, TIFFGetField
);
6995 LOAD_DLL_FN (library
, TIFFReadRGBAImage
);
6996 LOAD_DLL_FN (library
, TIFFClose
);
6997 LOAD_DLL_FN (library
, TIFFSetDirectory
);
7001 # undef TIFFClientOpen
7003 # undef TIFFGetField
7005 # undef TIFFReadRGBAImage
7006 # undef TIFFSetDirectory
7007 # undef TIFFSetErrorHandler
7008 # undef TIFFSetWarningHandler
7010 # define TIFFClientOpen fn_TIFFClientOpen
7011 # define TIFFClose fn_TIFFClose
7012 # define TIFFGetField fn_TIFFGetField
7013 # define TIFFOpen fn_TIFFOpen
7014 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7015 # define TIFFSetDirectory fn_TIFFSetDirectory
7016 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7017 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7019 # endif /* WINDOWSNT */
7022 /* Reading from a memory buffer for TIFF images Based on the PNG
7023 memory source, but we have to provide a lot of extra functions.
7026 We really only need to implement read and seek, but I am not
7027 convinced that the TIFF library is smart enough not to destroy
7028 itself if we only hand it the function pointers we need to
7033 unsigned char *bytes
;
7040 tiff_read_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7042 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7044 size
= min (size
, src
->len
- src
->index
);
7045 memcpy (buf
, src
->bytes
+ src
->index
, size
);
7051 tiff_write_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7057 tiff_seek_in_memory (thandle_t data
, toff_t off
, int whence
)
7059 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7064 case SEEK_SET
: /* Go from beginning of source. */
7068 case SEEK_END
: /* Go from end of source. */
7069 idx
= src
->len
+ off
;
7072 case SEEK_CUR
: /* Go from current position. */
7073 idx
= src
->index
+ off
;
7076 default: /* Invalid `whence'. */
7080 if (idx
> src
->len
|| idx
< 0)
7088 tiff_close_memory (thandle_t data
)
7095 tiff_mmap_memory (thandle_t data
, tdata_t
*pbase
, toff_t
*psize
)
7097 /* It is already _IN_ memory. */
7102 tiff_unmap_memory (thandle_t data
, tdata_t base
, toff_t size
)
7104 /* We don't need to do this. */
7108 tiff_size_of_memory (thandle_t data
)
7110 return ((tiff_memory_source
*) data
)->len
;
7113 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7114 compiler error compiling tiff_handler, see Bugzilla bug #17406
7115 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7116 this function as external works around that problem. */
7117 # if defined (__MINGW32__) && __GNUC__ == 3
7118 # define MINGW_STATIC
7120 # define MINGW_STATIC static
7124 tiff_handler (const char *, const char *, const char *, va_list)
7125 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7127 tiff_handler (const char *log_format
, const char *title
,
7128 const char *format
, va_list ap
)
7130 /* doprnt is not suitable here, as TIFF handlers are called from
7131 libtiff and are passed arbitrary printf directives. Instead, use
7132 vsnprintf, taking care to be portable to nonstandard environments
7133 where vsnprintf returns -1 on buffer overflow. Since it's just a
7134 log entry, it's OK to truncate it. */
7136 int len
= vsnprintf (buf
, sizeof buf
, format
, ap
);
7137 add_to_log (log_format
, build_string (title
),
7138 make_string (buf
, max (0, min (len
, sizeof buf
- 1))));
7140 # undef MINGW_STATIC
7142 static void tiff_error_handler (const char *, const char *, va_list)
7143 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7145 tiff_error_handler (const char *title
, const char *format
, va_list ap
)
7147 tiff_handler ("TIFF error: %s %s", title
, format
, ap
);
7151 static void tiff_warning_handler (const char *, const char *, va_list)
7152 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7154 tiff_warning_handler (const char *title
, const char *format
, va_list ap
)
7156 tiff_handler ("TIFF warning: %s %s", title
, format
, ap
);
7160 /* Load TIFF image IMG for use on frame F. Value is true if
7164 tiff_load (struct frame
*f
, struct image
*img
)
7166 Lisp_Object specified_file
;
7167 Lisp_Object specified_data
;
7169 int width
, height
, x
, y
, count
;
7173 tiff_memory_source memsrc
;
7176 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7177 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7179 TIFFSetErrorHandler ((TIFFErrorHandler
) tiff_error_handler
);
7180 TIFFSetWarningHandler ((TIFFErrorHandler
) tiff_warning_handler
);
7182 if (NILP (specified_data
))
7184 /* Read from a file */
7185 Lisp_Object file
= x_find_image_file (specified_file
);
7186 if (!STRINGP (file
))
7188 image_error ("Cannot find image file `%s'", specified_file
);
7192 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7194 encoded_file
= ansi_encode_filename (encoded_file
);
7197 /* Try to open the image file. */
7198 tiff
= TIFFOpen (SSDATA (encoded_file
), "r");
7201 image_error ("Cannot open `%s'", file
);
7207 if (!STRINGP (specified_data
))
7209 image_error ("Invalid image data `%s'", specified_data
);
7213 /* Memory source! */
7214 memsrc
.bytes
= SDATA (specified_data
);
7215 memsrc
.len
= SBYTES (specified_data
);
7218 tiff
= TIFFClientOpen ("memory_source", "r", (thandle_t
)&memsrc
,
7219 tiff_read_from_memory
,
7220 tiff_write_from_memory
,
7221 tiff_seek_in_memory
,
7223 tiff_size_of_memory
,
7229 image_error ("Cannot open memory source for `%s'", img
->spec
);
7234 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
7235 if (INTEGERP (image
))
7237 EMACS_INT ino
= XFASTINT (image
);
7238 if (! (TYPE_MINIMUM (tdir_t
) <= ino
&& ino
<= TYPE_MAXIMUM (tdir_t
)
7239 && TIFFSetDirectory (tiff
, ino
)))
7241 image_error ("Invalid image number `%s' in image `%s'",
7248 /* Get width and height of the image, and allocate a raster buffer
7249 of width x height 32-bit values. */
7250 TIFFGetField (tiff
, TIFFTAG_IMAGEWIDTH
, &width
);
7251 TIFFGetField (tiff
, TIFFTAG_IMAGELENGTH
, &height
);
7253 if (!check_image_size (f
, width
, height
))
7255 image_size_error ();
7260 /* Create the X image and pixmap. */
7261 if (! (height
<= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *buf
/ width
7262 && image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
7269 buf
= xmalloc (sizeof *buf
* width
* height
);
7271 rc
= TIFFReadRGBAImage (tiff
, width
, height
, buf
, 0);
7273 /* Count the number of images in the file. */
7274 for (count
= 1; TIFFSetDirectory (tiff
, count
); count
++)
7278 img
->lisp_data
= Fcons (Qcount
,
7279 Fcons (make_number (count
),
7285 image_error ("Error reading TIFF image `%s'", img
->spec
);
7292 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
7293 uint32_t *dataptr
= (uint32_t *) data
;
7296 for (y
= 0; y
< height
; ++y
)
7298 uint32
*row
= buf
+ (height
- 1 - y
) * width
;
7299 for (x
= 0; x
< width
; ++x
)
7301 uint32 abgr
= row
[x
];
7302 int r
= TIFFGetR (abgr
);
7303 int g
= TIFFGetG (abgr
);
7304 int b
= TIFFGetB (abgr
);
7305 int a
= TIFFGetA (abgr
);
7306 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
7310 create_cairo_image_surface (img
, data
, width
, height
);
7313 /* Initialize the color table. */
7314 init_color_table ();
7316 /* Process the pixel raster. Origin is in the lower-left corner. */
7317 for (y
= 0; y
< height
; ++y
)
7319 uint32
*row
= buf
+ y
* width
;
7321 for (x
= 0; x
< width
; ++x
)
7323 uint32 abgr
= row
[x
];
7324 int r
= TIFFGetR (abgr
) << 8;
7325 int g
= TIFFGetG (abgr
) << 8;
7326 int b
= TIFFGetB (abgr
) << 8;
7327 XPutPixel (ximg
, x
, height
- 1 - y
, lookup_rgb_color (f
, r
, g
, b
));
7331 # ifdef COLOR_TABLE_SUPPORT
7332 /* Remember the colors allocated for the image. Free the color table. */
7333 img
->colors
= colors_in_color_table (&img
->ncolors
);
7334 free_color_table ();
7335 # endif /* COLOR_TABLE_SUPPORT */
7338 img
->height
= height
;
7340 /* Maybe fill in the background field while we have ximg handy. */
7341 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7342 /* Casting avoids a GCC warning on W32. */
7343 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7345 /* Put ximg into the image. */
7346 image_put_x_image (f
, img
, ximg
, 0);
7348 #endif /* ! USE_CAIRO */
7354 #elif defined HAVE_NS
7357 tiff_load (struct frame
*f
, struct image
*img
)
7359 return ns_load_image (f
, img
,
7360 image_spec_value (img
->spec
, QCfile
, NULL
),
7361 image_spec_value (img
->spec
, QCdata
, NULL
));
7368 /***********************************************************************
7370 ***********************************************************************/
7372 #if defined (HAVE_GIF) || defined (HAVE_NS)
7374 static bool gif_image_p (Lisp_Object object
);
7375 static bool gif_load (struct frame
*f
, struct image
*img
);
7376 static void gif_clear_image (struct frame
*f
, struct image
*img
);
7378 /* Indices of image specification fields in gif_format, below. */
7380 enum gif_keyword_index
7396 /* Vector of image_keyword structures describing the format
7397 of valid user-defined image specifications. */
7399 static const struct image_keyword gif_format
[GIF_LAST
] =
7401 {":type", IMAGE_SYMBOL_VALUE
, 1},
7402 {":data", IMAGE_STRING_VALUE
, 0},
7403 {":file", IMAGE_STRING_VALUE
, 0},
7404 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7405 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7406 {":relief", IMAGE_INTEGER_VALUE
, 0},
7407 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7408 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7409 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7410 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0},
7411 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
7414 #if defined HAVE_NTGUI && defined WINDOWSNT
7415 static bool init_gif_functions (void);
7417 #define init_gif_functions NULL
7420 /* Structure describing the image type `gif'. */
7422 static struct image_type gif_type
=
7424 SYMBOL_INDEX (Qgif
),
7432 /* Free X resources of GIF image IMG which is used on frame F. */
7435 gif_clear_image (struct frame
*f
, struct image
*img
)
7437 img
->lisp_data
= Qnil
;
7438 x_clear_image (f
, img
);
7441 /* Return true if OBJECT is a valid GIF image specification. */
7444 gif_image_p (Lisp_Object object
)
7446 struct image_keyword fmt
[GIF_LAST
];
7447 memcpy (fmt
, gif_format
, sizeof fmt
);
7449 if (!parse_image_spec (object
, fmt
, GIF_LAST
, Qgif
))
7452 /* Must specify either the :data or :file keyword. */
7453 return fmt
[GIF_FILE
].count
+ fmt
[GIF_DATA
].count
== 1;
7456 #endif /* HAVE_GIF */
7462 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7463 Undefine before redefining to avoid a preprocessor warning. */
7467 /* avoid conflict with QuickdrawText.h */
7468 # define DrawText gif_DrawText
7469 # include <gif_lib.h>
7472 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7473 # ifndef GIFLIB_MINOR
7474 # define GIFLIB_MINOR 0
7476 # ifndef GIFLIB_RELEASE
7477 # define GIFLIB_RELEASE 0
7480 # else /* HAVE_NTGUI */
7482 # include <gif_lib.h>
7484 # endif /* HAVE_NTGUI */
7486 /* Giflib before 5.0 didn't define these macros. */
7487 # ifndef GIFLIB_MAJOR
7488 # define GIFLIB_MAJOR 4
7491 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7492 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7493 earlier releases, where either it returns char * or GIFLIB_MINOR
7494 may be incorrect. */
7495 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7499 /* GIF library details. */
7500 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7501 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*, int *));
7503 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*));
7505 DEF_DLL_FN (int, DGifSlurp
, (GifFileType
*));
7506 # if GIFLIB_MAJOR < 5
7507 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
));
7508 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *));
7510 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
, int *));
7511 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *, int *));
7513 # if HAVE_GIFERRORSTRING
7514 DEF_DLL_FN (char const *, GifErrorString
, (int));
7518 init_gif_functions (void)
7522 if (!(library
= w32_delayed_load (Qgif
)))
7525 LOAD_DLL_FN (library
, DGifCloseFile
);
7526 LOAD_DLL_FN (library
, DGifSlurp
);
7527 LOAD_DLL_FN (library
, DGifOpen
);
7528 LOAD_DLL_FN (library
, DGifOpenFileName
);
7529 # if HAVE_GIFERRORSTRING
7530 LOAD_DLL_FN (library
, GifErrorString
);
7535 # undef DGifCloseFile
7537 # undef DGifOpenFileName
7539 # undef GifErrorString
7541 # define DGifCloseFile fn_DGifCloseFile
7542 # define DGifOpen fn_DGifOpen
7543 # define DGifOpenFileName fn_DGifOpenFileName
7544 # define DGifSlurp fn_DGifSlurp
7545 # define GifErrorString fn_GifErrorString
7547 # endif /* WINDOWSNT */
7549 /* Reading a GIF image from memory
7550 Based on the PNG memory stuff to a certain extent. */
7554 unsigned char *bytes
;
7560 /* Make the current memory source available to gif_read_from_memory.
7561 It's done this way because not all versions of libungif support
7562 a UserData field in the GifFileType structure. */
7563 static gif_memory_source
*current_gif_memory_src
;
7566 gif_read_from_memory (GifFileType
*file
, GifByteType
*buf
, int len
)
7568 gif_memory_source
*src
= current_gif_memory_src
;
7570 if (len
> src
->len
- src
->index
)
7573 memcpy (buf
, src
->bytes
+ src
->index
, len
);
7579 gif_close (GifFileType
*gif
, int *err
)
7583 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7584 retval
= DGifCloseFile (gif
, err
);
7586 retval
= DGifCloseFile (gif
);
7587 #if GIFLIB_MAJOR >= 5
7595 /* Load GIF image IMG for use on frame F. Value is true if
7598 static const int interlace_start
[] = {0, 4, 2, 1};
7599 static const int interlace_increment
[] = {8, 8, 4, 2};
7601 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7604 gif_load (struct frame
*f
, struct image
*img
)
7606 int rc
, width
, height
, x
, y
, i
, j
;
7607 ColorMapObject
*gif_color_map
;
7608 unsigned long pixel_colors
[256];
7610 gif_memory_source memsrc
;
7611 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
7612 Lisp_Object specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7613 Lisp_Object specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7614 unsigned long bgcolor
= 0;
7619 unsigned char *data
= 0;
7624 if (NILP (specified_data
))
7626 Lisp_Object file
= x_find_image_file (specified_file
);
7627 if (!STRINGP (file
))
7629 image_error ("Cannot find image file `%s'", specified_file
);
7633 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7635 encoded_file
= ansi_encode_filename (encoded_file
);
7638 /* Open the GIF file. */
7639 #if GIFLIB_MAJOR < 5
7640 gif
= DGifOpenFileName (SSDATA (encoded_file
));
7642 gif
= DGifOpenFileName (SSDATA (encoded_file
), &gif_err
);
7646 #if HAVE_GIFERRORSTRING
7647 image_error ("Cannot open `%s': %s",
7648 file
, build_string (GifErrorString (gif_err
)));
7650 image_error ("Cannot open `%s'", file
);
7657 if (!STRINGP (specified_data
))
7659 image_error ("Invalid image data `%s'", specified_data
);
7663 /* Read from memory! */
7664 current_gif_memory_src
= &memsrc
;
7665 memsrc
.bytes
= SDATA (specified_data
);
7666 memsrc
.len
= SBYTES (specified_data
);
7669 #if GIFLIB_MAJOR < 5
7670 gif
= DGifOpen (&memsrc
, gif_read_from_memory
);
7672 gif
= DGifOpen (&memsrc
, gif_read_from_memory
, &gif_err
);
7676 #if HAVE_GIFERRORSTRING
7677 image_error ("Cannot open memory source `%s': %s",
7678 img
->spec
, build_string (GifErrorString (gif_err
)));
7680 image_error ("Cannot open memory source `%s'", img
->spec
);
7686 /* Before reading entire contents, check the declared image size. */
7687 if (!check_image_size (f
, gif
->SWidth
, gif
->SHeight
))
7689 image_size_error ();
7690 gif_close (gif
, NULL
);
7694 /* Read entire contents. */
7695 rc
= DGifSlurp (gif
);
7696 if (rc
== GIF_ERROR
|| gif
->ImageCount
<= 0)
7698 image_error ("Error reading `%s'", img
->spec
);
7699 gif_close (gif
, NULL
);
7703 /* Which sub-image are we to display? */
7705 Lisp_Object image_number
= image_spec_value (img
->spec
, QCindex
, NULL
);
7706 idx
= INTEGERP (image_number
) ? XFASTINT (image_number
) : 0;
7707 if (idx
< 0 || idx
>= gif
->ImageCount
)
7709 image_error ("Invalid image number `%s' in image `%s'",
7710 image_number
, img
->spec
);
7711 gif_close (gif
, NULL
);
7716 width
= img
->width
= gif
->SWidth
;
7717 height
= img
->height
= gif
->SHeight
;
7719 img
->corners
[TOP_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Top
;
7720 img
->corners
[LEFT_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Left
;
7721 img
->corners
[BOT_CORNER
]
7722 = img
->corners
[TOP_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Height
;
7723 img
->corners
[RIGHT_CORNER
]
7724 = img
->corners
[LEFT_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Width
;
7726 if (!check_image_size (f
, width
, height
))
7728 image_size_error ();
7729 gif_close (gif
, NULL
);
7733 /* Check that the selected subimages fit. It's not clear whether
7734 the GIF spec requires this, but Emacs can crash if they don't fit. */
7735 for (j
= 0; j
<= idx
; ++j
)
7737 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7738 int subimg_width
= subimage
->ImageDesc
.Width
;
7739 int subimg_height
= subimage
->ImageDesc
.Height
;
7740 int subimg_top
= subimage
->ImageDesc
.Top
;
7741 int subimg_left
= subimage
->ImageDesc
.Left
;
7742 if (! (subimg_width
>= 0 && subimg_height
>= 0
7743 && 0 <= subimg_top
&& subimg_top
<= height
- subimg_height
7744 && 0 <= subimg_left
&& subimg_left
<= width
- subimg_width
))
7746 image_error ("Subimage does not fit in image");
7747 gif_close (gif
, NULL
);
7753 /* xzalloc so data is zero => transparent */
7754 data
= (unsigned char *) xzalloc (width
* height
* 4);
7755 if (STRINGP (specified_bg
))
7758 if (x_defined_color (f
, SSDATA (specified_bg
), &color
, 0))
7760 uint32_t *dataptr
= (uint32_t *)data
;
7761 int r
= color
.red
/256;
7762 int g
= color
.green
/256;
7763 int b
= color
.blue
/256;
7765 for (y
= 0; y
< height
; ++y
)
7766 for (x
= 0; x
< width
; ++x
)
7767 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7771 /* Create the X image and pixmap. */
7772 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
7774 gif_close (gif
, NULL
);
7778 /* Clear the part of the screen image not covered by the image.
7779 Full animated GIF support requires more here (see the gif89 spec,
7780 disposal methods). Let's simply assume that the part not covered
7781 by a sub-image is in the frame's background color. */
7782 for (y
= 0; y
< img
->corners
[TOP_CORNER
]; ++y
)
7783 for (x
= 0; x
< width
; ++x
)
7784 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7786 for (y
= img
->corners
[BOT_CORNER
]; y
< height
; ++y
)
7787 for (x
= 0; x
< width
; ++x
)
7788 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7790 for (y
= img
->corners
[TOP_CORNER
]; y
< img
->corners
[BOT_CORNER
]; ++y
)
7792 for (x
= 0; x
< img
->corners
[LEFT_CORNER
]; ++x
)
7793 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7794 for (x
= img
->corners
[RIGHT_CORNER
]; x
< width
; ++x
)
7795 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7799 /* Read the GIF image into the X image. */
7801 /* FIXME: With the current implementation, loading an animated gif
7802 is quadratic in the number of animation frames, since each frame
7803 is a separate struct image. We must provide a way for a single
7804 gif_load call to construct and save all animation frames. */
7806 init_color_table ();
7807 if (STRINGP (specified_bg
))
7808 bgcolor
= x_alloc_image_color (f
, img
, specified_bg
,
7809 FRAME_BACKGROUND_PIXEL (f
));
7810 for (j
= 0; j
<= idx
; ++j
)
7812 /* We use a local variable `raster' here because RasterBits is a
7813 char *, which invites problems with bytes >= 0x80. */
7814 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7815 unsigned char *raster
= (unsigned char *) subimage
->RasterBits
;
7816 int transparency_color_index
= -1;
7818 int subimg_width
= subimage
->ImageDesc
.Width
;
7819 int subimg_height
= subimage
->ImageDesc
.Height
;
7820 int subimg_top
= subimage
->ImageDesc
.Top
;
7821 int subimg_left
= subimage
->ImageDesc
.Left
;
7823 /* Find the Graphic Control Extension block for this sub-image.
7824 Extract the disposal method and transparency color. */
7825 for (i
= 0; i
< subimage
->ExtensionBlockCount
; i
++)
7827 ExtensionBlock
*extblock
= subimage
->ExtensionBlocks
+ i
;
7829 if ((extblock
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
)
7830 && extblock
->ByteCount
== 4
7831 && extblock
->Bytes
[0] & 1)
7833 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7834 to background". Treat any other value like 2. */
7835 disposal
= (extblock
->Bytes
[0] >> 2) & 7;
7836 transparency_color_index
= (unsigned char) extblock
->Bytes
[3];
7841 /* We can't "keep in place" the first subimage. */
7845 /* For disposal == 0, the spec says "No disposal specified. The
7846 decoder is not required to take any action." In practice, it
7847 seems we need to treat this like "keep in place", see e.g.
7848 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7852 gif_color_map
= subimage
->ImageDesc
.ColorMap
;
7854 gif_color_map
= gif
->SColorMap
;
7857 /* Allocate subimage colors. */
7858 memset (pixel_colors
, 0, sizeof pixel_colors
);
7861 for (i
= 0; i
< gif_color_map
->ColorCount
; ++i
)
7863 if (transparency_color_index
== i
)
7864 pixel_colors
[i
] = STRINGP (specified_bg
)
7865 ? bgcolor
: FRAME_BACKGROUND_PIXEL (f
);
7868 int r
= gif_color_map
->Colors
[i
].Red
<< 8;
7869 int g
= gif_color_map
->Colors
[i
].Green
<< 8;
7870 int b
= gif_color_map
->Colors
[i
].Blue
<< 8;
7871 pixel_colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
7876 /* Apply the pixel values. */
7877 if (GIFLIB_MAJOR
< 5 && gif
->SavedImages
[j
].ImageDesc
.Interlace
)
7881 for (y
= 0, row
= interlace_start
[0], pass
= 0;
7883 y
++, row
+= interlace_increment
[pass
])
7885 while (subimg_height
<= row
)
7886 row
= interlace_start
[++pass
];
7888 for (x
= 0; x
< subimg_width
; x
++)
7890 int c
= raster
[y
* subimg_width
+ x
];
7891 if (transparency_color_index
!= c
|| disposal
!= 1)
7895 ((uint32_t*)data
+ ((row
+ subimg_top
) * subimg_width
7896 + x
+ subimg_left
));
7897 int r
= gif_color_map
->Colors
[c
].Red
;
7898 int g
= gif_color_map
->Colors
[c
].Green
;
7899 int b
= gif_color_map
->Colors
[c
].Blue
;
7901 if (transparency_color_index
!= c
)
7902 *dataptr
= (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7904 XPutPixel (ximg
, x
+ subimg_left
, row
+ subimg_top
,
7913 for (y
= 0; y
< subimg_height
; ++y
)
7914 for (x
= 0; x
< subimg_width
; ++x
)
7916 int c
= raster
[y
* subimg_width
+ x
];
7917 if (transparency_color_index
!= c
|| disposal
!= 1)
7921 ((uint32_t*)data
+ ((y
+ subimg_top
) * subimg_width
7922 + x
+ subimg_left
));
7923 int r
= gif_color_map
->Colors
[c
].Red
;
7924 int g
= gif_color_map
->Colors
[c
].Green
;
7925 int b
= gif_color_map
->Colors
[c
].Blue
;
7926 if (transparency_color_index
!= c
)
7927 *dataptr
= (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7929 XPutPixel (ximg
, x
+ subimg_left
, y
+ subimg_top
,
7937 #ifdef COLOR_TABLE_SUPPORT
7938 img
->colors
= colors_in_color_table (&img
->ncolors
);
7939 free_color_table ();
7940 #endif /* COLOR_TABLE_SUPPORT */
7942 /* Save GIF image extension data for `image-metadata'.
7943 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7944 img
->lisp_data
= Qnil
;
7945 if (gif
->SavedImages
[idx
].ExtensionBlockCount
> 0)
7948 ExtensionBlock
*ext
= gif
->SavedImages
[idx
].ExtensionBlocks
;
7949 for (i
= 0; i
< gif
->SavedImages
[idx
].ExtensionBlockCount
; i
++, ext
++)
7950 /* Append (... FUNCTION "BYTES") */
7953 = Fcons (make_number (ext
->Function
),
7954 Fcons (make_unibyte_string (ext
->Bytes
, ext
->ByteCount
),
7956 if (ext
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
7957 && ext
->ByteCount
== 4)
7959 delay
= ext
->Bytes
[2] << CHAR_BIT
;
7960 delay
|= ext
->Bytes
[1];
7963 img
->lisp_data
= list2 (Qextension_data
, img
->lisp_data
);
7967 Fcons (make_float (delay
/ 100.0),
7971 if (gif
->ImageCount
> 1)
7972 img
->lisp_data
= Fcons (Qcount
,
7973 Fcons (make_number (gif
->ImageCount
),
7976 if (gif_close (gif
, &gif_err
) == GIF_ERROR
)
7978 #if HAVE_GIFERRORSTRING
7979 char const *error_text
= GifErrorString (gif_err
);
7982 image_error ("Error closing `%s': %s",
7983 img
->spec
, build_string (error_text
));
7985 image_error ("Error closing `%s'", img
->spec
);
7990 create_cairo_image_surface (img
, data
, width
, height
);
7992 /* Maybe fill in the background field while we have ximg handy. */
7993 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7994 /* Casting avoids a GCC warning. */
7995 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7997 /* Put ximg into the image. */
7998 image_put_x_image (f
, img
, ximg
, 0);
8004 #else /* !HAVE_GIF */
8008 gif_load (struct frame
*f
, struct image
*img
)
8010 return ns_load_image (f
, img
,
8011 image_spec_value (img
->spec
, QCfile
, NULL
),
8012 image_spec_value (img
->spec
, QCdata
, NULL
));
8014 #endif /* HAVE_NS */
8016 #endif /* HAVE_GIF */
8019 #ifdef HAVE_IMAGEMAGICK
8021 /***********************************************************************
8023 ***********************************************************************/
8025 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8026 safely rounded and clipped to int range. */
8029 scale_image_size (int size
, size_t divisor
, size_t multiplier
)
8034 double scaled
= s
* multiplier
/ divisor
+ 0.5;
8035 if (scaled
< INT_MAX
)
8041 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8042 Use SPEC to deduce the size. Store the desired size into
8043 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8045 compute_image_size (size_t width
, size_t height
,
8047 int *d_width
, int *d_height
)
8050 int desired_width
, desired_height
;
8052 /* If width and/or height is set in the display spec assume we want
8053 to scale to those values. If either h or w is unspecified, the
8054 unspecified should be calculated from the specified to preserve
8056 value
= image_spec_value (spec
, QCwidth
, NULL
);
8057 desired_width
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
8058 value
= image_spec_value (spec
, QCheight
, NULL
);
8059 desired_height
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
8061 if (desired_width
== -1)
8063 value
= image_spec_value (spec
, QCmax_width
, NULL
);
8064 if (NATNUMP (value
))
8066 int max_width
= min (XFASTINT (value
), INT_MAX
);
8067 if (max_width
< width
)
8069 /* The image is wider than :max-width. */
8070 desired_width
= max_width
;
8071 if (desired_height
== -1)
8073 desired_height
= scale_image_size (desired_width
,
8075 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8076 if (NATNUMP (value
))
8078 int max_height
= min (XFASTINT (value
), INT_MAX
);
8079 if (max_height
< desired_height
)
8081 desired_height
= max_height
;
8082 desired_width
= scale_image_size (desired_height
,
8091 if (desired_height
== -1)
8093 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8094 if (NATNUMP (value
))
8096 int max_height
= min (XFASTINT (value
), INT_MAX
);
8097 if (max_height
< height
)
8098 desired_height
= max_height
;
8102 if (desired_width
!= -1 && desired_height
== -1)
8103 /* w known, calculate h. */
8104 desired_height
= scale_image_size (desired_width
, width
, height
);
8106 if (desired_width
== -1 && desired_height
!= -1)
8107 /* h known, calculate w. */
8108 desired_width
= scale_image_size (desired_height
, height
, width
);
8110 *d_width
= desired_width
;
8111 *d_height
= desired_height
;
8114 static bool imagemagick_image_p (Lisp_Object
);
8115 static bool imagemagick_load (struct frame
*, struct image
*);
8116 static void imagemagick_clear_image (struct frame
*, struct image
*);
8118 /* Indices of image specification fields in imagemagick_format. */
8120 enum imagemagick_keyword_index
8128 IMAGEMAGICK_ALGORITHM
,
8129 IMAGEMAGICK_HEURISTIC_MASK
,
8131 IMAGEMAGICK_BACKGROUND
,
8134 IMAGEMAGICK_MAX_HEIGHT
,
8135 IMAGEMAGICK_MAX_WIDTH
,
8137 IMAGEMAGICK_ROTATION
,
8142 /* Vector of image_keyword structures describing the format
8143 of valid user-defined image specifications. */
8145 static struct image_keyword imagemagick_format
[IMAGEMAGICK_LAST
] =
8147 {":type", IMAGE_SYMBOL_VALUE
, 1},
8148 {":data", IMAGE_STRING_VALUE
, 0},
8149 {":file", IMAGE_STRING_VALUE
, 0},
8150 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8151 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8152 {":relief", IMAGE_INTEGER_VALUE
, 0},
8153 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8154 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8155 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8156 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
8157 {":height", IMAGE_INTEGER_VALUE
, 0},
8158 {":width", IMAGE_INTEGER_VALUE
, 0},
8159 {":max-height", IMAGE_INTEGER_VALUE
, 0},
8160 {":max-width", IMAGE_INTEGER_VALUE
, 0},
8161 {":format", IMAGE_SYMBOL_VALUE
, 0},
8162 {":rotation", IMAGE_NUMBER_VALUE
, 0},
8163 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
8166 #if defined HAVE_NTGUI && defined WINDOWSNT
8167 static bool init_imagemagick_functions (void);
8169 #define init_imagemagick_functions NULL
8172 /* Structure describing the image type for any image handled via
8175 static struct image_type imagemagick_type
=
8177 SYMBOL_INDEX (Qimagemagick
),
8178 imagemagick_image_p
,
8180 imagemagick_clear_image
,
8181 init_imagemagick_functions
,
8185 /* Free X resources of imagemagick image IMG which is used on frame F. */
8188 imagemagick_clear_image (struct frame
*f
,
8191 x_clear_image (f
, img
);
8194 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8195 this by calling parse_image_spec and supplying the keywords that
8196 identify the IMAGEMAGICK format. */
8199 imagemagick_image_p (Lisp_Object object
)
8201 struct image_keyword fmt
[IMAGEMAGICK_LAST
];
8202 memcpy (fmt
, imagemagick_format
, sizeof fmt
);
8204 if (!parse_image_spec (object
, fmt
, IMAGEMAGICK_LAST
, Qimagemagick
))
8207 /* Must specify either the :data or :file keyword. */
8208 return fmt
[IMAGEMAGICK_FILE
].count
+ fmt
[IMAGEMAGICK_DATA
].count
== 1;
8211 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8212 Therefore rename the function so it doesn't collide with ImageMagick. */
8213 #define DrawRectangle DrawRectangleGif
8214 #include <wand/MagickWand.h>
8216 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8217 Emacs seems to work fine with the hidden version, so unhide it. */
8218 #include <magick/version.h>
8219 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8220 extern WandExport
void PixelGetMagickColor (const PixelWand
*,
8221 MagickPixelPacket
*);
8224 /* Log ImageMagick error message.
8225 Useful when a ImageMagick function returns the status `MagickFalse'. */
8228 imagemagick_error (MagickWand
*wand
)
8231 ExceptionType severity
;
8233 description
= MagickGetException (wand
, &severity
);
8234 image_error ("ImageMagick error: %s", build_string (description
));
8235 MagickRelinquishMemory (description
);
8238 /* Possibly give ImageMagick some extra help to determine the image
8239 type by supplying a "dummy" filename based on the Content-Type. */
8242 imagemagick_filename_hint (Lisp_Object spec
, char hint_buffer
[MaxTextExtent
])
8244 Lisp_Object symbol
= intern ("image-format-suffixes");
8245 Lisp_Object val
= find_symbol_value (symbol
);
8251 format
= image_spec_value (spec
, intern (":format"), NULL
);
8252 val
= Fcar_safe (Fcdr_safe (Fassq (format
, val
)));
8253 if (! STRINGP (val
))
8256 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8257 as ImageMagick would ignore the extra bytes anyway. */
8258 snprintf (hint_buffer
, MaxTextExtent
, "/tmp/foo.%s", SSDATA (val
));
8262 /* Animated images (e.g., GIF89a) are composed from one "master image"
8263 (which is the first one, and then there's a number of images that
8264 follow. If following images have non-transparent colors, these are
8265 composed "on top" of the master image. So, in general, one has to
8266 compute ann the preceding images to be able to display a particular
8269 Computing all the preceding images is too slow, so we maintain a
8270 cache of previously computed images. We have to maintain a cache
8271 separate from the image cache, because the images may be scaled
8274 struct animation_cache
8278 struct timespec update_time
;
8279 struct animation_cache
*next
;
8280 char signature
[FLEXIBLE_ARRAY_MEMBER
];
8283 static struct animation_cache
*animation_cache
= NULL
;
8285 static struct animation_cache
*
8286 imagemagick_create_cache (char *signature
)
8288 struct animation_cache
*cache
8289 = xmalloc (offsetof (struct animation_cache
, signature
)
8290 + strlen (signature
) + 1);
8294 strcpy (cache
->signature
, signature
);
8298 /* Discard cached images that haven't been used for a minute. */
8300 imagemagick_prune_animation_cache (void)
8302 struct animation_cache
**pcache
= &animation_cache
;
8303 struct timespec old
= timespec_sub (current_timespec (),
8304 make_timespec (60, 0));
8308 struct animation_cache
*cache
= *pcache
;
8309 if (timespec_cmp (old
, cache
->update_time
) <= 0)
8310 pcache
= &cache
->next
;
8314 DestroyMagickWand (cache
->wand
);
8315 *pcache
= cache
->next
;
8321 static struct animation_cache
*
8322 imagemagick_get_animation_cache (MagickWand
*wand
)
8324 char *signature
= MagickGetImageSignature (wand
);
8325 struct animation_cache
*cache
;
8326 struct animation_cache
**pcache
= &animation_cache
;
8328 imagemagick_prune_animation_cache ();
8335 *pcache
= cache
= imagemagick_create_cache (signature
);
8338 if (strcmp (signature
, cache
->signature
) == 0)
8340 pcache
= &cache
->next
;
8343 DestroyString (signature
);
8344 cache
->update_time
= current_timespec ();
8349 imagemagick_compute_animated_image (MagickWand
*super_wand
, int ino
)
8352 MagickWand
*composite_wand
;
8353 size_t dest_width
, dest_height
;
8354 struct animation_cache
*cache
= imagemagick_get_animation_cache (super_wand
);
8356 MagickSetIteratorIndex (super_wand
, 0);
8358 if (ino
== 0 || cache
->wand
== NULL
|| cache
->index
> ino
)
8360 composite_wand
= MagickGetImage (super_wand
);
8362 DestroyMagickWand (cache
->wand
);
8365 composite_wand
= cache
->wand
;
8367 dest_height
= MagickGetImageHeight (composite_wand
);
8369 for (i
= max (1, cache
->index
+ 1); i
<= ino
; i
++)
8371 MagickWand
*sub_wand
;
8372 PixelIterator
*source_iterator
, *dest_iterator
;
8373 PixelWand
**source
, **dest
;
8374 size_t source_width
, source_height
;
8375 ssize_t source_left
, source_top
;
8376 MagickPixelPacket pixel
;
8377 DisposeType dispose
;
8378 ptrdiff_t lines
= 0;
8380 MagickSetIteratorIndex (super_wand
, i
);
8381 sub_wand
= MagickGetImage (super_wand
);
8383 MagickGetImagePage (sub_wand
, &source_width
, &source_height
,
8384 &source_left
, &source_top
);
8386 /* This flag says how to handle transparent pixels. */
8387 dispose
= MagickGetImageDispose (sub_wand
);
8389 source_iterator
= NewPixelIterator (sub_wand
);
8390 if (! source_iterator
)
8392 DestroyMagickWand (composite_wand
);
8393 DestroyMagickWand (sub_wand
);
8395 image_error ("Imagemagick pixel iterator creation failed");
8399 dest_iterator
= NewPixelIterator (composite_wand
);
8400 if (! dest_iterator
)
8402 DestroyMagickWand (composite_wand
);
8403 DestroyMagickWand (sub_wand
);
8404 DestroyPixelIterator (source_iterator
);
8406 image_error ("Imagemagick pixel iterator creation failed");
8410 /* The sub-image may not start at origin, so move the destination
8411 iterator to where the sub-image should start. */
8414 PixelSetIteratorRow (dest_iterator
, source_top
);
8418 while ((source
= PixelGetNextIteratorRow (source_iterator
, &source_width
))
8423 /* Sanity check. This shouldn't happen, but apparently
8424 does in some pictures. */
8425 if (++lines
>= dest_height
)
8428 dest
= PixelGetNextIteratorRow (dest_iterator
, &dest_width
);
8429 for (x
= 0; x
< source_width
; x
++)
8431 /* Sanity check. This shouldn't happen, but apparently
8432 also does in some pictures. */
8433 if (x
+ source_left
>= dest_width
)
8435 /* Normally we only copy over non-transparent pixels,
8436 but if the disposal method is "Background", then we
8437 copy over all pixels. */
8438 if (dispose
== BackgroundDispose
|| PixelGetAlpha (source
[x
]))
8440 PixelGetMagickColor (source
[x
], &pixel
);
8441 PixelSetMagickColor (dest
[x
+ source_left
], &pixel
);
8444 PixelSyncIterator (dest_iterator
);
8447 DestroyPixelIterator (source_iterator
);
8448 DestroyPixelIterator (dest_iterator
);
8449 DestroyMagickWand (sub_wand
);
8452 /* Cache a copy for the next iteration. The current wand will be
8453 destroyed by the caller. */
8454 cache
->wand
= CloneMagickWand (composite_wand
);
8457 return composite_wand
;
8461 /* Helper function for imagemagick_load, which does the actual loading
8462 given contents and size, apart from frame and image structures,
8463 passed from imagemagick_load. Uses librimagemagick to do most of
8464 the image processing.
8466 F is a pointer to the Emacs frame; IMG to the image structure to
8467 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8468 be parsed; SIZE is the number of bytes of data; and FILENAME is
8469 either the file name or the image data.
8471 Return true if successful. */
8474 imagemagick_load_image (struct frame
*f
, struct image
*img
,
8475 unsigned char *contents
, unsigned int size
,
8479 size_t image_width
, image_height
;
8480 MagickBooleanType status
;
8483 MagickWand
*image_wand
;
8484 PixelIterator
*iterator
;
8485 PixelWand
**pixels
, *bg_wand
= NULL
;
8486 MagickPixelPacket pixel
;
8491 int desired_width
, desired_height
;
8494 char hint_buffer
[MaxTextExtent
];
8495 char *filename_hint
= NULL
;
8497 /* Handle image index for image types who can contain more than one image.
8498 Interface :index is same as for GIF. First we "ping" the image to see how
8499 many sub-images it contains. Pinging is faster than loading the image to
8500 find out things about it. */
8502 /* Initialize the imagemagick environment. */
8503 MagickWandGenesis ();
8504 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
8505 ino
= INTEGERP (image
) ? XFASTINT (image
) : 0;
8506 image_wand
= NewMagickWand ();
8509 status
= MagickReadImage (image_wand
, filename
);
8512 filename_hint
= imagemagick_filename_hint (img
->spec
, hint_buffer
);
8513 MagickSetFilename (image_wand
, filename_hint
);
8514 status
= MagickReadImageBlob (image_wand
, contents
, size
);
8517 if (status
== MagickFalse
)
8519 imagemagick_error (image_wand
);
8520 DestroyMagickWand (image_wand
);
8524 if (ino
< 0 || ino
>= MagickGetNumberImages (image_wand
))
8526 image_error ("Invalid image number `%s' in image `%s'", image
, img
->spec
);
8527 DestroyMagickWand (image_wand
);
8531 if (MagickGetImageDelay (image_wand
) > 0)
8534 Fcons (make_float (MagickGetImageDelay (image_wand
) / 100.0),
8537 if (MagickGetNumberImages (image_wand
) > 1)
8540 Fcons (make_number (MagickGetNumberImages (image_wand
)),
8543 /* If we have an animated image, get the new wand based on the
8545 if (MagickGetNumberImages (image_wand
) > 1)
8547 MagickWand
*super_wand
= image_wand
;
8548 image_wand
= imagemagick_compute_animated_image (super_wand
, ino
);
8550 image_wand
= super_wand
;
8552 DestroyMagickWand (super_wand
);
8555 /* Retrieve the frame's background color, for use later. */
8558 Lisp_Object specified_bg
;
8560 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8561 if (!STRINGP (specified_bg
)
8562 || !x_defined_color (f
, SSDATA (specified_bg
), &bgcolor
, 0))
8563 x_query_frame_background_color (f
, &bgcolor
);
8565 bg_wand
= NewPixelWand ();
8566 PixelSetRed (bg_wand
, (double) bgcolor
.red
/ 65535);
8567 PixelSetGreen (bg_wand
, (double) bgcolor
.green
/ 65535);
8568 PixelSetBlue (bg_wand
, (double) bgcolor
.blue
/ 65535);
8571 compute_image_size (MagickGetImageWidth (image_wand
),
8572 MagickGetImageHeight (image_wand
),
8573 img
->spec
, &desired_width
, &desired_height
);
8575 if (desired_width
!= -1 && desired_height
!= -1)
8577 status
= MagickScaleImage (image_wand
, desired_width
, desired_height
);
8578 if (status
== MagickFalse
)
8580 image_error ("Imagemagick scale failed");
8581 imagemagick_error (image_wand
);
8582 goto imagemagick_error
;
8586 /* crop behaves similar to image slicing in Emacs but is more memory
8588 crop
= image_spec_value (img
->spec
, QCcrop
, NULL
);
8590 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8592 /* After some testing, it seems MagickCropImage is the fastest crop
8593 function in ImageMagick. This crop function seems to do less copying
8594 than the alternatives, but it still reads the entire image into memory
8595 before cropping, which is apparently difficult to avoid when using
8597 size_t crop_width
= XINT (XCAR (crop
));
8599 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8601 size_t crop_height
= XINT (XCAR (crop
));
8603 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8605 ssize_t crop_x
= XINT (XCAR (crop
));
8607 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8609 ssize_t crop_y
= XINT (XCAR (crop
));
8610 MagickCropImage (image_wand
, crop_width
, crop_height
,
8617 /* Furthermore :rotation. we need background color and angle for
8620 TODO background handling for rotation specified_bg =
8621 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8623 value
= image_spec_value (img
->spec
, QCrotation
, NULL
);
8626 rotation
= extract_float (value
);
8627 status
= MagickRotateImage (image_wand
, bg_wand
, rotation
);
8628 if (status
== MagickFalse
)
8630 image_error ("Imagemagick image rotate failed");
8631 imagemagick_error (image_wand
);
8632 goto imagemagick_error
;
8636 /* Set the canvas background color to the frame or specified
8637 background, and flatten the image. Note: as of ImageMagick
8638 6.6.0, SVG image transparency is not handled properly
8639 (e.g. etc/images/splash.svg shows a white background always). */
8641 MagickWand
*new_wand
;
8642 MagickSetImageBackgroundColor (image_wand
, bg_wand
);
8643 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8644 new_wand
= MagickMergeImageLayers (image_wand
, MergeLayer
);
8646 new_wand
= MagickFlattenImages (image_wand
);
8648 DestroyMagickWand (image_wand
);
8649 image_wand
= new_wand
;
8652 /* Finally we are done manipulating the image. Figure out the
8653 resulting width/height and transfer ownership to Emacs. */
8654 image_height
= MagickGetImageHeight (image_wand
);
8655 image_width
= MagickGetImageWidth (image_wand
);
8657 if (! (image_width
<= INT_MAX
&& image_height
<= INT_MAX
8658 && check_image_size (f
, image_width
, image_height
)))
8660 image_size_error ();
8661 goto imagemagick_error
;
8664 width
= image_width
;
8665 height
= image_height
;
8667 /* We can now get a valid pixel buffer from the imagemagick file, if all
8670 init_color_table ();
8672 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8673 if (imagemagick_render_type
!= 0)
8675 /* Magicexportimage is normally faster than pixelpushing. This
8676 method is also well tested. Some aspects of this method are
8677 ad-hoc and needs to be more researched. */
8678 int imagedepth
= 24; /*MagickGetImageDepth(image_wand);*/
8679 const char *exportdepth
= imagedepth
<= 8 ? "I" : "BGRP"; /*"RGBP";*/
8680 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8681 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, imagedepth
,
8684 #ifdef COLOR_TABLE_SUPPORT
8685 free_color_table ();
8687 image_error ("Imagemagick X bitmap allocation failure");
8688 goto imagemagick_error
;
8691 /* Oddly, the below code doesn't seem to work:*/
8692 /* switch(ximg->bitmap_unit){ */
8694 /* pixelwidth=CharPixel; */
8697 /* pixelwidth=ShortPixel; */
8700 /* pixelwidth=LongPixel; */
8704 Here im just guessing the format of the bitmap.
8705 happens to work fine for:
8708 seems about 3 times as fast as pixel pushing(not carefully measured)
8710 pixelwidth
= CharPixel
; /*??? TODO figure out*/
8711 MagickExportImagePixels (image_wand
, 0, 0, width
, height
,
8712 exportdepth
, pixelwidth
, ximg
->data
);
8715 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8717 size_t image_height
;
8718 MagickRealType color_scale
= 65535.0 / QuantumRange
;
8720 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8721 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
8724 #ifdef COLOR_TABLE_SUPPORT
8725 free_color_table ();
8727 image_error ("Imagemagick X bitmap allocation failure");
8728 goto imagemagick_error
;
8731 /* Copy imagemagick image to x with primitive yet robust pixel
8732 pusher loop. This has been tested a lot with many different
8735 /* Copy pixels from the imagemagick image structure to the x image map. */
8736 iterator
= NewPixelIterator (image_wand
);
8739 #ifdef COLOR_TABLE_SUPPORT
8740 free_color_table ();
8742 x_destroy_x_image (ximg
);
8743 image_error ("Imagemagick pixel iterator creation failed");
8744 goto imagemagick_error
;
8747 image_height
= MagickGetImageHeight (image_wand
);
8748 for (y
= 0; y
< image_height
; y
++)
8751 pixels
= PixelGetNextIteratorRow (iterator
, &row_width
);
8754 int xlim
= min (row_width
, width
);
8755 for (x
= 0; x
< xlim
; x
++)
8757 PixelGetMagickColor (pixels
[x
], &pixel
);
8758 XPutPixel (ximg
, x
, y
,
8759 lookup_rgb_color (f
,
8760 color_scale
* pixel
.red
,
8761 color_scale
* pixel
.green
,
8762 color_scale
* pixel
.blue
));
8765 DestroyPixelIterator (iterator
);
8768 #ifdef COLOR_TABLE_SUPPORT
8769 /* Remember colors allocated for this image. */
8770 img
->colors
= colors_in_color_table (&img
->ncolors
);
8771 free_color_table ();
8772 #endif /* COLOR_TABLE_SUPPORT */
8775 img
->height
= height
;
8777 /* Put ximg into the image. */
8778 image_put_x_image (f
, img
, ximg
, 0);
8780 /* Final cleanup. image_wand should be the only resource left. */
8781 DestroyMagickWand (image_wand
);
8782 if (bg_wand
) DestroyPixelWand (bg_wand
);
8784 /* `MagickWandTerminus' terminates the imagemagick environment. */
8785 MagickWandTerminus ();
8790 DestroyMagickWand (image_wand
);
8791 if (bg_wand
) DestroyPixelWand (bg_wand
);
8793 MagickWandTerminus ();
8794 /* TODO more cleanup. */
8795 image_error ("Error parsing IMAGEMAGICK image `%s'", img
->spec
);
8800 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8801 successful. this function will go into the imagemagick_type structure, and
8802 the prototype thus needs to be compatible with that structure. */
8805 imagemagick_load (struct frame
*f
, struct image
*img
)
8808 Lisp_Object file_name
;
8810 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8811 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8812 if (STRINGP (file_name
))
8814 Lisp_Object file
= x_find_image_file (file_name
);
8815 if (!STRINGP (file
))
8817 image_error ("Cannot find image file `%s'", file_name
);
8820 file
= ENCODE_FILE (file
);
8822 file
= ansi_encode_filename (file
);
8824 success_p
= imagemagick_load_image (f
, img
, 0, 0, SSDATA (file
));
8826 /* Else its not a file, its a lisp object. Load the image from a
8827 lisp object rather than a file. */
8832 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8833 if (!STRINGP (data
))
8835 image_error ("Invalid image data `%s'", data
);
8838 success_p
= imagemagick_load_image (f
, img
, SDATA (data
),
8839 SBYTES (data
), NULL
);
8845 DEFUN ("imagemagick-types", Fimagemagick_types
, Simagemagick_types
, 0, 0, 0,
8846 doc
: /* Return a list of image types supported by ImageMagick.
8847 Each entry in this list is a symbol named after an ImageMagick format
8848 tag. See the ImageMagick manual for a list of ImageMagick formats and
8849 their descriptions (http://www.imagemagick.org/script/formats.php).
8850 You can also try the shell command: `identify -list format'.
8852 Note that ImageMagick recognizes many file-types that Emacs does not
8853 recognize as images, such as C. See `imagemagick-types-enable'
8854 and `imagemagick-types-inhibit'. */)
8857 Lisp_Object typelist
= Qnil
;
8863 GetExceptionInfo(&ex
);
8864 imtypes
= GetMagickList ("*", &numf
, &ex
);
8865 DestroyExceptionInfo(&ex
);
8867 for (i
= 0; i
< numf
; i
++)
8869 Lisp_Object imagemagicktype
= intern (imtypes
[i
]);
8870 typelist
= Fcons (imagemagicktype
, typelist
);
8871 imtypes
[i
] = MagickRelinquishMemory (imtypes
[i
]);
8874 MagickRelinquishMemory (imtypes
);
8875 return Fnreverse (typelist
);
8878 #endif /* defined (HAVE_IMAGEMAGICK) */
8882 /***********************************************************************
8884 ***********************************************************************/
8888 /* Function prototypes. */
8890 static bool svg_image_p (Lisp_Object object
);
8891 static bool svg_load (struct frame
*f
, struct image
*img
);
8893 static bool svg_load_image (struct frame
*, struct image
*,
8894 unsigned char *, ptrdiff_t, char *);
8896 /* Indices of image specification fields in svg_format, below. */
8898 enum svg_keyword_index
8913 /* Vector of image_keyword structures describing the format
8914 of valid user-defined image specifications. */
8916 static const struct image_keyword svg_format
[SVG_LAST
] =
8918 {":type", IMAGE_SYMBOL_VALUE
, 1},
8919 {":data", IMAGE_STRING_VALUE
, 0},
8920 {":file", IMAGE_STRING_VALUE
, 0},
8921 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8922 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8923 {":relief", IMAGE_INTEGER_VALUE
, 0},
8924 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8925 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8926 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8927 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8930 # if defined HAVE_NTGUI && defined WINDOWSNT
8931 static bool init_svg_functions (void);
8933 #define init_svg_functions NULL
8936 /* Structure describing the image type `svg'. Its the same type of
8937 structure defined for all image formats, handled by emacs image
8938 functions. See struct image_type in dispextern.h. */
8940 static struct image_type svg_type
=
8942 SYMBOL_INDEX (Qsvg
),
8951 /* Return true if OBJECT is a valid SVG image specification. Do
8952 this by calling parse_image_spec and supplying the keywords that
8953 identify the SVG format. */
8956 svg_image_p (Lisp_Object object
)
8958 struct image_keyword fmt
[SVG_LAST
];
8959 memcpy (fmt
, svg_format
, sizeof fmt
);
8961 if (!parse_image_spec (object
, fmt
, SVG_LAST
, Qsvg
))
8964 /* Must specify either the :data or :file keyword. */
8965 return fmt
[SVG_FILE
].count
+ fmt
[SVG_DATA
].count
== 1;
8968 # include <librsvg/rsvg.h>
8972 /* SVG library functions. */
8973 DEF_DLL_FN (RsvgHandle
*, rsvg_handle_new
, (void));
8974 DEF_DLL_FN (void, rsvg_handle_get_dimensions
,
8975 (RsvgHandle
*, RsvgDimensionData
*));
8976 DEF_DLL_FN (gboolean
, rsvg_handle_write
,
8977 (RsvgHandle
*, const guchar
*, gsize
, GError
**));
8978 DEF_DLL_FN (gboolean
, rsvg_handle_close
, (RsvgHandle
*, GError
**));
8979 DEF_DLL_FN (GdkPixbuf
*, rsvg_handle_get_pixbuf
, (RsvgHandle
*));
8980 DEF_DLL_FN (void, rsvg_handle_set_base_uri
, (RsvgHandle
*, const char *));
8982 DEF_DLL_FN (int, gdk_pixbuf_get_width
, (const GdkPixbuf
*));
8983 DEF_DLL_FN (int, gdk_pixbuf_get_height
, (const GdkPixbuf
*));
8984 DEF_DLL_FN (guchar
*, gdk_pixbuf_get_pixels
, (const GdkPixbuf
*));
8985 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride
, (const GdkPixbuf
*));
8986 DEF_DLL_FN (GdkColorspace
, gdk_pixbuf_get_colorspace
, (const GdkPixbuf
*));
8987 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels
, (const GdkPixbuf
*));
8988 DEF_DLL_FN (gboolean
, gdk_pixbuf_get_has_alpha
, (const GdkPixbuf
*));
8989 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample
, (const GdkPixbuf
*));
8991 # if ! GLIB_CHECK_VERSION (2, 36, 0)
8992 DEF_DLL_FN (void, g_type_init
, (void));
8994 DEF_DLL_FN (void, g_object_unref
, (gpointer
));
8995 DEF_DLL_FN (void, g_error_free
, (GError
*));
8998 init_svg_functions (void)
9000 HMODULE library
, gdklib
= NULL
, glib
= NULL
, gobject
= NULL
;
9002 if (!(glib
= w32_delayed_load (Qglib
))
9003 || !(gobject
= w32_delayed_load (Qgobject
))
9004 || !(gdklib
= w32_delayed_load (Qgdk_pixbuf
))
9005 || !(library
= w32_delayed_load (Qsvg
)))
9007 if (gdklib
) FreeLibrary (gdklib
);
9008 if (gobject
) FreeLibrary (gobject
);
9009 if (glib
) FreeLibrary (glib
);
9013 LOAD_DLL_FN (library
, rsvg_handle_new
);
9014 LOAD_DLL_FN (library
, rsvg_handle_get_dimensions
);
9015 LOAD_DLL_FN (library
, rsvg_handle_write
);
9016 LOAD_DLL_FN (library
, rsvg_handle_close
);
9017 LOAD_DLL_FN (library
, rsvg_handle_get_pixbuf
);
9018 LOAD_DLL_FN (library
, rsvg_handle_set_base_uri
);
9020 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_width
);
9021 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_height
);
9022 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_pixels
);
9023 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_rowstride
);
9024 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_colorspace
);
9025 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_n_channels
);
9026 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_has_alpha
);
9027 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_bits_per_sample
);
9029 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9030 LOAD_DLL_FN (gobject
, g_type_init
);
9032 LOAD_DLL_FN (gobject
, g_object_unref
);
9033 LOAD_DLL_FN (glib
, g_error_free
);
9038 /* The following aliases for library functions allow dynamic loading
9039 to be used on some platforms. */
9041 # undef gdk_pixbuf_get_bits_per_sample
9042 # undef gdk_pixbuf_get_colorspace
9043 # undef gdk_pixbuf_get_has_alpha
9044 # undef gdk_pixbuf_get_height
9045 # undef gdk_pixbuf_get_n_channels
9046 # undef gdk_pixbuf_get_pixels
9047 # undef gdk_pixbuf_get_rowstride
9048 # undef gdk_pixbuf_get_width
9049 # undef g_error_free
9050 # undef g_object_unref
9052 # undef rsvg_handle_close
9053 # undef rsvg_handle_get_dimensions
9054 # undef rsvg_handle_get_pixbuf
9055 # undef rsvg_handle_new
9056 # undef rsvg_handle_set_base_uri
9057 # undef rsvg_handle_write
9059 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9060 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9061 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9062 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9063 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9064 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9065 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9066 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9067 # define g_error_free fn_g_error_free
9068 # define g_object_unref fn_g_object_unref
9069 # define g_type_init fn_g_type_init
9070 # define rsvg_handle_close fn_rsvg_handle_close
9071 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9072 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9073 # define rsvg_handle_new fn_rsvg_handle_new
9074 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9075 # define rsvg_handle_write fn_rsvg_handle_write
9077 # endif /* !WINDOWSNT */
9079 /* Load SVG image IMG for use on frame F. Value is true if
9083 svg_load (struct frame
*f
, struct image
*img
)
9086 Lisp_Object file_name
;
9088 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9089 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
9090 if (STRINGP (file_name
))
9093 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
9094 if (!STRINGP (file
))
9096 image_error ("Cannot find image file `%s'", file_name
);
9100 /* Read the entire file into memory. */
9102 unsigned char *contents
= slurp_file (fd
, &size
);
9103 if (contents
== NULL
)
9105 image_error ("Error loading SVG image `%s'", file
);
9108 /* If the file was slurped into memory properly, parse it. */
9109 success_p
= svg_load_image (f
, img
, contents
, size
,
9110 SSDATA (ENCODE_FILE (file
)));
9113 /* Else its not a file, its a lisp object. Load the image from a
9114 lisp object rather than a file. */
9117 Lisp_Object data
, original_filename
;
9119 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
9120 if (!STRINGP (data
))
9122 image_error ("Invalid image data `%s'", data
);
9125 original_filename
= BVAR (current_buffer
, filename
);
9126 success_p
= svg_load_image (f
, img
, SDATA (data
), SBYTES (data
),
9127 (NILP (original_filename
) ? NULL
9128 : SSDATA (original_filename
)));
9134 /* svg_load_image is a helper function for svg_load, which does the
9135 actual loading given contents and size, apart from frame and image
9136 structures, passed from svg_load.
9138 Uses librsvg to do most of the image processing.
9140 Returns true when successful. */
9142 svg_load_image (struct frame
*f
, /* Pointer to emacs frame structure. */
9143 struct image
*img
, /* Pointer to emacs image structure. */
9144 unsigned char *contents
, /* String containing the SVG XML data to be parsed. */
9145 ptrdiff_t size
, /* Size of data in bytes. */
9146 char *filename
) /* Name of SVG file being loaded. */
9148 RsvgHandle
*rsvg_handle
;
9149 RsvgDimensionData dimension_data
;
9154 const guint8
*pixels
;
9157 Lisp_Object specified_bg
;
9162 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9163 /* g_type_init is a glib function that must be called prior to
9164 using gnome type library functions (obsolete since 2.36.0). */
9168 /* Make a handle to a new rsvg object. */
9169 rsvg_handle
= rsvg_handle_new ();
9171 /* Set base_uri for properly handling referenced images (via 'href').
9172 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9173 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9175 rsvg_handle_set_base_uri(rsvg_handle
, filename
);
9177 /* Parse the contents argument and fill in the rsvg_handle. */
9178 rsvg_handle_write (rsvg_handle
, contents
, size
, &err
);
9179 if (err
) goto rsvg_error
;
9181 /* The parsing is complete, rsvg_handle is ready to used, close it
9182 for further writes. */
9183 rsvg_handle_close (rsvg_handle
, &err
);
9184 if (err
) goto rsvg_error
;
9186 rsvg_handle_get_dimensions (rsvg_handle
, &dimension_data
);
9187 if (! check_image_size (f
, dimension_data
.width
, dimension_data
.height
))
9189 image_size_error ();
9193 /* We can now get a valid pixel buffer from the svg file, if all
9195 pixbuf
= rsvg_handle_get_pixbuf (rsvg_handle
);
9196 if (!pixbuf
) goto rsvg_error
;
9197 g_object_unref (rsvg_handle
);
9199 /* Extract some meta data from the svg handle. */
9200 width
= gdk_pixbuf_get_width (pixbuf
);
9201 height
= gdk_pixbuf_get_height (pixbuf
);
9202 pixels
= gdk_pixbuf_get_pixels (pixbuf
);
9203 rowstride
= gdk_pixbuf_get_rowstride (pixbuf
);
9205 /* Validate the svg meta data. */
9206 eassert (gdk_pixbuf_get_colorspace (pixbuf
) == GDK_COLORSPACE_RGB
);
9207 eassert (gdk_pixbuf_get_n_channels (pixbuf
) == 4);
9208 eassert (gdk_pixbuf_get_has_alpha (pixbuf
));
9209 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf
) == 8);
9213 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
9215 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
9217 for (y
= 0; y
< height
; ++y
)
9219 const guchar
*iconptr
= pixels
+ y
* rowstride
;
9220 uint32_t *dataptr
= (uint32_t *) (data
+ y
* rowstride
);
9223 for (x
= 0; x
< width
; ++x
)
9225 if (iconptr
[3] == 0)
9228 *dataptr
= (iconptr
[0] << 16)
9231 | (iconptr
[3] << 24);
9238 create_cairo_image_surface (img
, data
, width
, height
);
9239 g_object_unref (pixbuf
);
9242 /* Try to create a x pixmap to hold the svg pixmap. */
9243 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
9245 g_object_unref (pixbuf
);
9249 init_color_table ();
9251 /* Handle alpha channel by combining the image with a background
9253 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
9254 if (!STRINGP (specified_bg
)
9255 || !x_defined_color (f
, SSDATA (specified_bg
), &background
, 0))
9256 x_query_frame_background_color (f
, &background
);
9258 /* SVG pixmaps specify transparency in the last byte, so right
9259 shift 8 bits to get rid of it, since emacs doesn't support
9261 background
.red
>>= 8;
9262 background
.green
>>= 8;
9263 background
.blue
>>= 8;
9265 /* This loop handles opacity values, since Emacs assumes
9266 non-transparent images. Each pixel must be "flattened" by
9267 calculating the resulting color, given the transparency of the
9268 pixel, and the image background color. */
9269 for (y
= 0; y
< height
; ++y
)
9271 for (x
= 0; x
< width
; ++x
)
9281 opacity
= *pixels
++;
9283 red
= ((red
* opacity
)
9284 + (background
.red
* ((1 << 8) - opacity
)));
9285 green
= ((green
* opacity
)
9286 + (background
.green
* ((1 << 8) - opacity
)));
9287 blue
= ((blue
* opacity
)
9288 + (background
.blue
* ((1 << 8) - opacity
)));
9290 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, red
, green
, blue
));
9293 pixels
+= rowstride
- 4 * width
;
9296 #ifdef COLOR_TABLE_SUPPORT
9297 /* Remember colors allocated for this image. */
9298 img
->colors
= colors_in_color_table (&img
->ncolors
);
9299 free_color_table ();
9300 #endif /* COLOR_TABLE_SUPPORT */
9302 g_object_unref (pixbuf
);
9305 img
->height
= height
;
9307 /* Maybe fill in the background field while we have ximg handy.
9308 Casting avoids a GCC warning. */
9309 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
9311 /* Put ximg into the image. */
9312 image_put_x_image (f
, img
, ximg
, 0);
9313 #endif /* ! USE_CAIRO */
9318 g_object_unref (rsvg_handle
);
9319 /* FIXME: Use error->message so the user knows what is the actual
9320 problem with the image. */
9321 image_error ("Error parsing SVG image `%s'", img
->spec
);
9326 #endif /* defined (HAVE_RSVG) */
9331 /***********************************************************************
9333 ***********************************************************************/
9335 #ifdef HAVE_X_WINDOWS
9336 #define HAVE_GHOSTSCRIPT 1
9337 #endif /* HAVE_X_WINDOWS */
9339 #ifdef HAVE_GHOSTSCRIPT
9341 static bool gs_image_p (Lisp_Object object
);
9342 static bool gs_load (struct frame
*f
, struct image
*img
);
9343 static void gs_clear_image (struct frame
*f
, struct image
*img
);
9345 /* Indices of image specification fields in gs_format, below. */
9347 enum gs_keyword_index
9365 /* Vector of image_keyword structures describing the format
9366 of valid user-defined image specifications. */
9368 static const struct image_keyword gs_format
[GS_LAST
] =
9370 {":type", IMAGE_SYMBOL_VALUE
, 1},
9371 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9372 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9373 {":file", IMAGE_STRING_VALUE
, 1},
9374 {":loader", IMAGE_FUNCTION_VALUE
, 0},
9375 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE
, 1},
9376 {":ascent", IMAGE_ASCENT_VALUE
, 0},
9377 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
9378 {":relief", IMAGE_INTEGER_VALUE
, 0},
9379 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9380 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9381 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9382 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
9385 /* Structure describing the image type `ghostscript'. */
9387 static struct image_type gs_type
=
9389 SYMBOL_INDEX (Qpostscript
),
9398 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9401 gs_clear_image (struct frame
*f
, struct image
*img
)
9403 x_clear_image (f
, img
);
9407 /* Return true if OBJECT is a valid Ghostscript image
9411 gs_image_p (Lisp_Object object
)
9413 struct image_keyword fmt
[GS_LAST
];
9417 memcpy (fmt
, gs_format
, sizeof fmt
);
9419 if (!parse_image_spec (object
, fmt
, GS_LAST
, Qpostscript
))
9422 /* Bounding box must be a list or vector containing 4 integers. */
9423 tem
= fmt
[GS_BOUNDING_BOX
].value
;
9426 for (i
= 0; i
< 4; ++i
, tem
= XCDR (tem
))
9427 if (!CONSP (tem
) || !INTEGERP (XCAR (tem
)))
9432 else if (VECTORP (tem
))
9434 if (ASIZE (tem
) != 4)
9436 for (i
= 0; i
< 4; ++i
)
9437 if (!INTEGERP (AREF (tem
, i
)))
9447 /* Load Ghostscript image IMG for use on frame F. Value is true
9451 gs_load (struct frame
*f
, struct image
*img
)
9453 uprintmax_t printnum1
, printnum2
;
9454 char buffer
[sizeof " " + INT_STRLEN_BOUND (printmax_t
)];
9455 Lisp_Object window_and_pixmap_id
= Qnil
, loader
, pt_height
, pt_width
;
9457 double in_width
, in_height
;
9458 Lisp_Object pixel_colors
= Qnil
;
9460 /* Compute pixel size of pixmap needed from the given size in the
9461 image specification. Sizes in the specification are in pt. 1 pt
9462 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9464 pt_width
= image_spec_value (img
->spec
, QCpt_width
, NULL
);
9465 in_width
= INTEGERP (pt_width
) ? XFASTINT (pt_width
) / 72.0 : 0;
9466 in_width
*= FRAME_RES_X (f
);
9467 pt_height
= image_spec_value (img
->spec
, QCpt_height
, NULL
);
9468 in_height
= INTEGERP (pt_height
) ? XFASTINT (pt_height
) / 72.0 : 0;
9469 in_height
*= FRAME_RES_Y (f
);
9471 if (! (in_width
<= INT_MAX
&& in_height
<= INT_MAX
9472 && check_image_size (f
, in_width
, in_height
)))
9474 image_size_error ();
9477 img
->width
= in_width
;
9478 img
->height
= in_height
;
9480 /* Create the pixmap. */
9481 eassert (img
->pixmap
== NO_PIXMAP
);
9483 if (x_check_image_size (0, img
->width
, img
->height
))
9485 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9487 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
9488 img
->width
, img
->height
,
9489 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)));
9495 image_error ("Unable to create pixmap for `%s'" , img
->spec
);
9499 /* Call the loader to fill the pixmap. It returns a process object
9500 if successful. We do not record_unwind_protect here because
9501 other places in redisplay like calling window scroll functions
9502 don't either. Let the Lisp loader use `unwind-protect' instead. */
9503 printnum1
= FRAME_X_WINDOW (f
);
9504 printnum2
= img
->pixmap
;
9505 window_and_pixmap_id
9506 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9508 printnum1
= FRAME_FOREGROUND_PIXEL (f
);
9509 printnum2
= FRAME_BACKGROUND_PIXEL (f
);
9511 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9513 XSETFRAME (frame
, f
);
9514 loader
= image_spec_value (img
->spec
, QCloader
, NULL
);
9516 loader
= intern ("gs-load-image");
9518 img
->lisp_data
= call6 (loader
, frame
, img
->spec
,
9519 make_number (img
->width
),
9520 make_number (img
->height
),
9521 window_and_pixmap_id
,
9523 return PROCESSP (img
->lisp_data
);
9527 /* Kill the Ghostscript process that was started to fill PIXMAP on
9528 frame F. Called from XTread_socket when receiving an event
9529 telling Emacs that Ghostscript has finished drawing. */
9532 x_kill_gs_process (Pixmap pixmap
, struct frame
*f
)
9534 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
9538 /* Find the image containing PIXMAP. */
9539 for (i
= 0; i
< c
->used
; ++i
)
9540 if (c
->images
[i
]->pixmap
== pixmap
)
9543 /* Should someone in between have cleared the image cache, for
9544 instance, give up. */
9548 /* Kill the GS process. We should have found PIXMAP in the image
9549 cache and its image should contain a process object. */
9551 eassert (PROCESSP (img
->lisp_data
));
9552 Fkill_process (img
->lisp_data
, Qnil
);
9553 img
->lisp_data
= Qnil
;
9555 #if defined (HAVE_X_WINDOWS)
9557 /* On displays with a mutable colormap, figure out the colors
9558 allocated for the image by looking at the pixels of an XImage for
9560 if (x_mutable_colormap (FRAME_X_VISUAL (f
)))
9566 /* Try to get an XImage for img->pixmep. */
9567 ximg
= XGetImage (FRAME_X_DISPLAY (f
), img
->pixmap
,
9568 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
9573 /* Initialize the color table. */
9574 init_color_table ();
9576 /* For each pixel of the image, look its color up in the
9577 color table. After having done so, the color table will
9578 contain an entry for each color used by the image. */
9579 #ifdef COLOR_TABLE_SUPPORT
9580 for (y
= 0; y
< img
->height
; ++y
)
9581 for (x
= 0; x
< img
->width
; ++x
)
9583 unsigned long pixel
= XGetPixel (ximg
, x
, y
);
9585 lookup_pixel_color (f
, pixel
);
9588 /* Record colors in the image. Free color table and XImage. */
9589 img
->colors
= colors_in_color_table (&img
->ncolors
);
9590 free_color_table ();
9592 XDestroyImage (ximg
);
9594 #if 0 /* This doesn't seem to be the case. If we free the colors
9595 here, we get a BadAccess later in x_clear_image when
9596 freeing the colors. */
9597 /* We have allocated colors once, but Ghostscript has also
9598 allocated colors on behalf of us. So, to get the
9599 reference counts right, free them once. */
9601 x_free_colors (f
, img
->colors
, img
->ncolors
);
9605 image_error ("Cannot get X image of `%s'; colors will not be freed",
9610 #endif /* HAVE_X_WINDOWS */
9612 /* Now that we have the pixmap, compute mask and transform the
9613 image if requested. */
9615 postprocess_image (f
, img
);
9619 #endif /* HAVE_GHOSTSCRIPT */
9622 /***********************************************************************
9624 ***********************************************************************/
9628 DEFUN ("imagep", Fimagep
, Simagep
, 1, 1, 0,
9629 doc
: /* Value is non-nil if SPEC is a valid image specification. */)
9632 return valid_image_p (spec
) ? Qt
: Qnil
;
9636 DEFUN ("lookup-image", Flookup_image
, Slookup_image
, 1, 1, 0,
9642 if (valid_image_p (spec
))
9643 id
= lookup_image (SELECTED_FRAME (), spec
);
9646 return make_number (id
);
9649 #endif /* GLYPH_DEBUG */
9652 /***********************************************************************
9654 ***********************************************************************/
9656 DEFUN ("init-image-library", Finit_image_library
, Sinit_image_library
, 1, 1, 0,
9657 doc
: /* Initialize image library implementing image type TYPE.
9658 Return non-nil if TYPE is a supported image type.
9660 If image libraries are loaded dynamically (currently only the case on
9661 MS-Windows), load the library for TYPE if it is not yet loaded, using
9662 the library file(s) specified by `dynamic-library-alist'. */)
9665 return lookup_image_type (type
) ? Qt
: Qnil
;
9668 /* Look up image type TYPE, and return a pointer to its image_type
9669 structure. Return 0 if TYPE is not a known image type. */
9671 static struct image_type
*
9672 lookup_image_type (Lisp_Object type
)
9674 /* Types pbm and xbm are built-in and always available. */
9675 if (EQ (type
, Qpbm
))
9676 return define_image_type (&pbm_type
);
9678 if (EQ (type
, Qxbm
))
9679 return define_image_type (&xbm_type
);
9681 #if defined (HAVE_XPM) || defined (HAVE_NS)
9682 if (EQ (type
, Qxpm
))
9683 return define_image_type (&xpm_type
);
9686 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9687 if (EQ (type
, Qjpeg
))
9688 return define_image_type (&jpeg_type
);
9691 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9692 if (EQ (type
, Qtiff
))
9693 return define_image_type (&tiff_type
);
9696 #if defined (HAVE_GIF) || defined (HAVE_NS)
9697 if (EQ (type
, Qgif
))
9698 return define_image_type (&gif_type
);
9701 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9702 if (EQ (type
, Qpng
))
9703 return define_image_type (&png_type
);
9706 #if defined (HAVE_RSVG)
9707 if (EQ (type
, Qsvg
))
9708 return define_image_type (&svg_type
);
9711 #if defined (HAVE_IMAGEMAGICK)
9712 if (EQ (type
, Qimagemagick
))
9713 return define_image_type (&imagemagick_type
);
9716 #ifdef HAVE_GHOSTSCRIPT
9717 if (EQ (type
, Qpostscript
))
9718 return define_image_type (&gs_type
);
9724 /* Reset image_types before dumping.
9725 Called from Fdump_emacs. */
9728 reset_image_types (void)
9732 struct image_type
*next
= image_types
->next
;
9733 xfree (image_types
);
9739 syms_of_image (void)
9741 /* Initialize this only once; it will be reset before dumping. */
9744 /* Must be defined now because we're going to update it below, while
9745 defining the supported image types. */
9746 DEFVAR_LISP ("image-types", Vimage_types
,
9747 doc
: /* List of potentially supported image types.
9748 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9749 To check whether it is really supported, use `image-type-available-p'. */);
9750 Vimage_types
= Qnil
;
9752 DEFVAR_LISP ("max-image-size", Vmax_image_size
,
9753 doc
: /* Maximum size of images.
9754 Emacs will not load an image into memory if its pixel width or
9755 pixel height exceeds this limit.
9757 If the value is an integer, it directly specifies the maximum
9758 image height and width, measured in pixels. If it is a floating
9759 point number, it specifies the maximum image height and width
9760 as a ratio to the frame height and width. If the value is
9761 non-numeric, there is no explicit limit on the size of images. */);
9762 Vmax_image_size
= make_float (MAX_IMAGE_SIZE
);
9764 /* Other symbols. */
9765 DEFSYM (Qcount
, "count");
9766 DEFSYM (Qextension_data
, "extension-data");
9767 DEFSYM (Qdelay
, "delay");
9770 DEFSYM (QCascent
, ":ascent");
9771 DEFSYM (QCmargin
, ":margin");
9772 DEFSYM (QCrelief
, ":relief");
9773 DEFSYM (QCconversion
, ":conversion");
9774 DEFSYM (QCcolor_symbols
, ":color-symbols");
9775 DEFSYM (QCheuristic_mask
, ":heuristic-mask");
9776 DEFSYM (QCindex
, ":index");
9777 DEFSYM (QCcrop
, ":crop");
9778 DEFSYM (QCrotation
, ":rotation");
9779 DEFSYM (QCmatrix
, ":matrix");
9780 DEFSYM (QCcolor_adjustment
, ":color-adjustment");
9781 DEFSYM (QCmask
, ":mask");
9783 /* Other symbols. */
9784 DEFSYM (Qlaplace
, "laplace");
9785 DEFSYM (Qemboss
, "emboss");
9786 DEFSYM (Qedge_detection
, "edge-detection");
9787 DEFSYM (Qheuristic
, "heuristic");
9789 DEFSYM (Qpostscript
, "postscript");
9790 DEFSYM (QCmax_width
, ":max-width");
9791 DEFSYM (QCmax_height
, ":max-height");
9792 #ifdef HAVE_GHOSTSCRIPT
9793 ADD_IMAGE_TYPE (Qpostscript
);
9794 DEFSYM (QCloader
, ":loader");
9795 DEFSYM (QCpt_width
, ":pt-width");
9796 DEFSYM (QCpt_height
, ":pt-height");
9797 #endif /* HAVE_GHOSTSCRIPT */
9800 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9801 or -1 if no PNG/GIF support was compiled in. This is tested by
9802 w32-win.el to correctly set up the alist used to search for the
9803 respective image libraries. */
9804 DEFSYM (Qlibpng_version
, "libpng-version");
9805 Fset (Qlibpng_version
,
9807 make_number (PNG_LIBPNG_VER
)
9812 DEFSYM (Qlibgif_version
, "libgif-version");
9813 Fset (Qlibgif_version
,
9815 make_number (GIFLIB_MAJOR
* 10000
9816 + GIFLIB_MINOR
* 100
9822 DEFSYM (Qlibjpeg_version
, "libjpeg-version");
9823 Fset (Qlibjpeg_version
,
9825 make_number (JPEG_LIB_VERSION
)
9832 DEFSYM (Qpbm
, "pbm");
9833 ADD_IMAGE_TYPE (Qpbm
);
9835 DEFSYM (Qxbm
, "xbm");
9836 ADD_IMAGE_TYPE (Qxbm
);
9838 #if defined (HAVE_XPM) || defined (HAVE_NS)
9839 DEFSYM (Qxpm
, "xpm");
9840 ADD_IMAGE_TYPE (Qxpm
);
9843 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9844 DEFSYM (Qjpeg
, "jpeg");
9845 ADD_IMAGE_TYPE (Qjpeg
);
9848 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9849 DEFSYM (Qtiff
, "tiff");
9850 ADD_IMAGE_TYPE (Qtiff
);
9853 #if defined (HAVE_GIF) || defined (HAVE_NS)
9854 DEFSYM (Qgif
, "gif");
9855 ADD_IMAGE_TYPE (Qgif
);
9858 #if defined (HAVE_PNG) || defined (HAVE_NS)
9859 DEFSYM (Qpng
, "png");
9860 ADD_IMAGE_TYPE (Qpng
);
9863 #if defined (HAVE_IMAGEMAGICK)
9864 DEFSYM (Qimagemagick
, "imagemagick");
9865 ADD_IMAGE_TYPE (Qimagemagick
);
9868 #if defined (HAVE_RSVG)
9869 DEFSYM (Qsvg
, "svg");
9870 ADD_IMAGE_TYPE (Qsvg
);
9872 /* Other libraries used directly by svg code. */
9873 DEFSYM (Qgdk_pixbuf
, "gdk-pixbuf");
9874 DEFSYM (Qglib
, "glib");
9875 DEFSYM (Qgobject
, "gobject");
9876 #endif /* HAVE_NTGUI */
9877 #endif /* HAVE_RSVG */
9879 defsubr (&Sinit_image_library
);
9880 #ifdef HAVE_IMAGEMAGICK
9881 defsubr (&Simagemagick_types
);
9883 defsubr (&Sclear_image_cache
);
9884 defsubr (&Simage_flush
);
9885 defsubr (&Simage_size
);
9886 defsubr (&Simage_mask_p
);
9887 defsubr (&Simage_metadata
);
9891 defsubr (&Slookup_image
);
9894 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images
,
9895 doc
: /* Non-nil means always draw a cross over disabled images.
9896 Disabled images are those having a `:conversion disabled' property.
9897 A cross is always drawn on black & white displays. */);
9898 cross_disabled_images
= 0;
9900 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path
,
9901 doc
: /* List of directories to search for window system bitmap files. */);
9902 Vx_bitmap_file_path
= decode_env_path (0, PATH_BITMAPS
, 0);
9904 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay
,
9905 doc
: /* Maximum time after which images are removed from the cache.
9906 When an image has not been displayed this many seconds, Emacs
9907 automatically removes it from the image cache. If the cache contains
9908 a large number of images, the actual eviction time may be shorter.
9909 The value can also be nil, meaning the cache is never cleared.
9911 The function `clear-image-cache' disregards this variable. */);
9912 Vimage_cache_eviction_delay
= make_number (300);
9913 #ifdef HAVE_IMAGEMAGICK
9914 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type
,
9915 doc
: /* Integer indicating which ImageMagick rendering method to use.
9917 0 -- the default method (pixel pushing)
9918 1 -- a newer method ("MagickExportImagePixels") that may perform
9919 better (speed etc) in some cases, but has not been as thoroughly
9920 tested with Emacs as the default method. This method requires
9921 ImageMagick version 6.4.6 (approximately) or later.
9923 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9924 imagemagick_render_type
= 0;