1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
24 /* Include this before including <setjmp.h> to work around bugs with
25 older libpng; see Bug#17429. */
26 #if defined HAVE_PNG && !defined HAVE_NS
37 #include "dispextern.h"
38 #include "blockinput.h"
41 #include "character.h"
43 #include "termhooks.h"
46 #ifdef HAVE_SYS_STAT_H
48 #endif /* HAVE_SYS_STAT_H */
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
52 #endif /* HAVE_SYS_TYPES_H */
54 #ifdef HAVE_WINDOW_SYSTEM
56 #endif /* HAVE_WINDOW_SYSTEM */
59 #define COLOR_TABLE_SUPPORT 1
61 typedef struct x_bitmap_record Bitmap_Record
;
62 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
63 #define NO_PIXMAP None
65 #define PIX_MASK_RETAIN 0
66 #define PIX_MASK_DRAW 1
67 #endif /* HAVE_X_WINDOWS */
71 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
76 /* W32_TODO : Color tables on W32. */
77 #undef COLOR_TABLE_SUPPORT
79 typedef struct w32_bitmap_record Bitmap_Record
;
80 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
83 #define PIX_MASK_RETAIN 0
84 #define PIX_MASK_DRAW 1
86 #define x_defined_color w32_defined_color
87 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
89 #endif /* HAVE_NTGUI */
92 #undef COLOR_TABLE_SUPPORT
96 #undef COLOR_TABLE_SUPPORT
98 typedef struct ns_bitmap_record Bitmap_Record
;
100 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
103 #define PIX_MASK_RETAIN 0
104 #define PIX_MASK_DRAW 1
106 #define x_defined_color(f, name, color_def, alloc) \
107 ns_defined_color (f, name, color_def, alloc, 0)
108 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
111 static void x_disable_image (struct frame
*, struct image
*);
112 static void x_edge_detection (struct frame
*, struct image
*, Lisp_Object
,
115 static void init_color_table (void);
116 static unsigned long lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
);
117 #ifdef COLOR_TABLE_SUPPORT
118 static void free_color_table (void);
119 static unsigned long *colors_in_color_table (int *n
);
122 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
123 id, which is just an int that this section returns. Bitmaps are
124 reference counted so they can be shared among frames.
126 Bitmap indices are guaranteed to be > 0, so a negative number can
127 be used to indicate no bitmap.
129 If you use x_create_bitmap_from_data, then you must keep track of
130 the bitmaps yourself. That is, creating a bitmap from the same
131 data more than once will not be caught. */
134 /* Use with images created by ns_image_for_XPM. */
136 XGetPixel (XImagePtr ximage
, int x
, int y
)
138 return ns_get_pixel (ximage
, x
, y
);
141 /* Use with images created by ns_image_for_XPM; alpha set to 1;
142 pixel is assumed to be in RGB form. */
144 XPutPixel (XImagePtr ximage
, int x
, int y
, unsigned long pixel
)
146 ns_put_pixel (ximage
, x
, y
, pixel
);
151 /* Functions to access the contents of a bitmap, given an id. */
153 #ifdef HAVE_X_WINDOWS
155 x_bitmap_height (struct frame
*f
, ptrdiff_t id
)
157 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].height
;
161 x_bitmap_width (struct frame
*f
, ptrdiff_t id
)
163 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].width
;
167 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
169 x_bitmap_pixmap (struct frame
*f
, ptrdiff_t id
)
171 /* HAVE_NTGUI needs the explicit cast here. */
172 return (ptrdiff_t) FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].pixmap
;
176 #ifdef HAVE_X_WINDOWS
178 x_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
180 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].mask
;
184 /* Allocate a new bitmap record. Returns index of new record. */
187 x_allocate_bitmap_record (struct frame
*f
)
189 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
192 if (dpyinfo
->bitmaps_last
< dpyinfo
->bitmaps_size
)
193 return ++dpyinfo
->bitmaps_last
;
195 for (i
= 0; i
< dpyinfo
->bitmaps_size
; ++i
)
196 if (dpyinfo
->bitmaps
[i
].refcount
== 0)
200 xpalloc (dpyinfo
->bitmaps
, &dpyinfo
->bitmaps_size
,
201 10, -1, sizeof *dpyinfo
->bitmaps
);
202 return ++dpyinfo
->bitmaps_last
;
205 /* Add one reference to the reference count of the bitmap with id ID. */
208 x_reference_bitmap (struct frame
*f
, ptrdiff_t id
)
210 ++FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].refcount
;
213 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
216 x_create_bitmap_from_data (struct frame
*f
, char *bits
, unsigned int width
, unsigned int height
)
218 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
221 #ifdef HAVE_X_WINDOWS
223 bitmap
= XCreateBitmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
224 bits
, width
, height
);
227 #endif /* HAVE_X_WINDOWS */
231 bitmap
= CreateBitmap (width
, height
,
232 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_planes
,
233 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_cbits
,
237 #endif /* HAVE_NTGUI */
240 void *bitmap
= ns_image_from_XBM (bits
, width
, height
, 0, 0);
245 id
= x_allocate_bitmap_record (f
);
248 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
249 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
252 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
253 dpyinfo
->bitmaps
[id
- 1].height
= height
;
254 dpyinfo
->bitmaps
[id
- 1].width
= width
;
255 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
257 #ifdef HAVE_X_WINDOWS
258 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
259 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
260 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
261 #endif /* HAVE_X_WINDOWS */
264 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
265 dpyinfo
->bitmaps
[id
- 1].hinst
= NULL
;
266 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
267 #endif /* HAVE_NTGUI */
272 /* Create bitmap from file FILE for frame F. */
275 x_create_bitmap_from_file (struct frame
*f
, Lisp_Object file
)
277 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
280 return -1; /* W32_TODO : bitmap support */
281 #endif /* HAVE_NTGUI */
285 void *bitmap
= ns_image_from_file (file
);
291 id
= x_allocate_bitmap_record (f
);
292 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
293 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
294 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
295 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
296 dpyinfo
->bitmaps
[id
- 1].height
= ns_image_width (bitmap
);
297 dpyinfo
->bitmaps
[id
- 1].width
= ns_image_height (bitmap
);
301 #ifdef HAVE_X_WINDOWS
302 unsigned int width
, height
;
304 int xhot
, yhot
, result
;
309 /* Look for an existing bitmap with the same name. */
310 for (id
= 0; id
< dpyinfo
->bitmaps_last
; ++id
)
312 if (dpyinfo
->bitmaps
[id
].refcount
313 && dpyinfo
->bitmaps
[id
].file
314 && !strcmp (dpyinfo
->bitmaps
[id
].file
, SSDATA (file
)))
316 ++dpyinfo
->bitmaps
[id
].refcount
;
321 /* Search bitmap-file-path for the file, if appropriate. */
322 if (openp (Vx_bitmap_file_path
, file
, Qnil
, &found
,
323 make_number (R_OK
), false)
327 filename
= SSDATA (found
);
329 result
= XReadBitmapFile (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
330 filename
, &width
, &height
, &bitmap
, &xhot
, &yhot
);
331 if (result
!= BitmapSuccess
)
334 id
= x_allocate_bitmap_record (f
);
335 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
336 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
337 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
338 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
339 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
340 dpyinfo
->bitmaps
[id
- 1].height
= height
;
341 dpyinfo
->bitmaps
[id
- 1].width
= width
;
344 #endif /* HAVE_X_WINDOWS */
350 free_bitmap_record (Display_Info
*dpyinfo
, Bitmap_Record
*bm
)
352 #ifdef HAVE_X_WINDOWS
353 XFreePixmap (dpyinfo
->display
, bm
->pixmap
);
355 XFreePixmap (dpyinfo
->display
, bm
->mask
);
356 #endif /* HAVE_X_WINDOWS */
359 DeleteObject (bm
->pixmap
);
360 #endif /* HAVE_NTGUI */
363 ns_release_object (bm
->img
);
373 /* Remove reference to bitmap with id number ID. */
376 x_destroy_bitmap (struct frame
*f
, ptrdiff_t id
)
378 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
382 Bitmap_Record
*bm
= &dpyinfo
->bitmaps
[id
- 1];
384 if (--bm
->refcount
== 0)
387 free_bitmap_record (dpyinfo
, bm
);
393 /* Free all the bitmaps for the display specified by DPYINFO. */
396 x_destroy_all_bitmaps (Display_Info
*dpyinfo
)
399 Bitmap_Record
*bm
= dpyinfo
->bitmaps
;
401 for (i
= 0; i
< dpyinfo
->bitmaps_last
; i
++, bm
++)
402 if (bm
->refcount
> 0)
403 free_bitmap_record (dpyinfo
, bm
);
405 dpyinfo
->bitmaps_last
= 0;
408 static bool x_create_x_image_and_pixmap (struct frame
*, int, int, int,
409 XImagePtr
*, Pixmap
*);
410 static void x_destroy_x_image (XImagePtr ximg
);
413 static XImagePtr_or_DC
image_get_x_image_or_dc (struct frame
*, struct image
*,
415 static void image_unget_x_image_or_dc (struct image
*, bool, XImagePtr_or_DC
,
418 static XImagePtr
image_get_x_image (struct frame
*, struct image
*, bool);
419 static void image_unget_x_image (struct image
*, bool, XImagePtr
);
420 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
421 image_get_x_image (f, img, mask_p)
422 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
423 image_unget_x_image (img, mask_p, ximg)
426 #ifdef HAVE_X_WINDOWS
428 static void image_sync_to_pixmaps (struct frame
*, struct image
*);
430 /* Useful functions defined in the section
431 `Image type independent image structures' below. */
433 static unsigned long four_corners_best (XImagePtr ximg
,
436 unsigned long height
);
439 /* Create a mask of a bitmap. Note is this not a perfect mask.
440 It's nicer with some borders in this context */
443 x_create_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
446 XImagePtr ximg
, mask_img
;
447 unsigned long width
, height
;
450 unsigned long x
, y
, xp
, xm
, yp
, ym
;
453 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
458 pixmap
= x_bitmap_pixmap (f
, id
);
459 width
= x_bitmap_width (f
, id
);
460 height
= x_bitmap_height (f
, id
);
463 ximg
= XGetImage (FRAME_X_DISPLAY (f
), pixmap
, 0, 0, width
, height
,
472 result
= x_create_x_image_and_pixmap (f
, width
, height
, 1, &mask_img
, &mask
);
477 XDestroyImage (ximg
);
481 bg
= four_corners_best (ximg
, NULL
, width
, height
);
483 for (y
= 0; y
< ximg
->height
; ++y
)
485 for (x
= 0; x
< ximg
->width
; ++x
)
487 xp
= x
!= ximg
->width
- 1 ? x
+ 1 : 0;
488 xm
= x
!= 0 ? x
- 1 : ximg
->width
- 1;
489 yp
= y
!= ximg
->height
- 1 ? y
+ 1 : 0;
490 ym
= y
!= 0 ? y
- 1 : ximg
->height
- 1;
491 if (XGetPixel (ximg
, x
, y
) == bg
492 && XGetPixel (ximg
, x
, yp
) == bg
493 && XGetPixel (ximg
, x
, ym
) == bg
494 && XGetPixel (ximg
, xp
, y
) == bg
495 && XGetPixel (ximg
, xp
, yp
) == bg
496 && XGetPixel (ximg
, xp
, ym
) == bg
497 && XGetPixel (ximg
, xm
, y
) == bg
498 && XGetPixel (ximg
, xm
, yp
) == bg
499 && XGetPixel (ximg
, xm
, ym
) == bg
)
500 XPutPixel (mask_img
, x
, y
, 0);
502 XPutPixel (mask_img
, x
, y
, 1);
506 eassert (input_blocked_p ());
507 gc
= XCreateGC (FRAME_X_DISPLAY (f
), mask
, 0, NULL
);
508 XPutImage (FRAME_X_DISPLAY (f
), mask
, gc
, mask_img
, 0, 0, 0, 0,
510 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
512 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
513 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
515 XDestroyImage (ximg
);
516 x_destroy_x_image (mask_img
);
519 #endif /* HAVE_X_WINDOWS */
521 /***********************************************************************
523 ***********************************************************************/
525 /* List of supported image types. Use define_image_type to add new
526 types. Use lookup_image_type to find a type for a given symbol. */
528 static struct image_type
*image_types
;
530 /* Forward function prototypes. */
532 static struct image_type
*lookup_image_type (Lisp_Object
);
533 static void x_laplace (struct frame
*, struct image
*);
534 static void x_emboss (struct frame
*, struct image
*);
535 static void x_build_heuristic_mask (struct frame
*, struct image
*,
538 #define CACHE_IMAGE_TYPE(type, status) \
539 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
541 #define CACHE_IMAGE_TYPE(type, status)
544 #define ADD_IMAGE_TYPE(type) \
545 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
547 /* Define a new image type from TYPE. This adds a copy of TYPE to
548 image_types and caches the loading status of TYPE. */
550 static struct image_type
*
551 define_image_type (struct image_type
*type
)
553 struct image_type
*p
= NULL
;
554 int new_type
= type
->type
;
555 bool type_valid
= true;
559 for (p
= image_types
; p
; p
= p
->next
)
560 if (p
->type
== new_type
)
565 #if defined HAVE_NTGUI && defined WINDOWSNT
566 /* If we failed to load the library before, don't try again. */
567 Lisp_Object tested
= Fassq (builtin_lisp_symbol (new_type
),
569 if (CONSP (tested
) && NILP (XCDR (tested
)))
574 type_valid
= type
->init ();
575 CACHE_IMAGE_TYPE (builtin_lisp_symbol (new_type
),
576 type_valid
? Qt
: Qnil
);
582 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
583 The initialized data segment is read-only. */
584 p
= xmalloc (sizeof *p
);
586 p
->next
= image_types
;
596 /* Value is true if OBJECT is a valid Lisp image specification. A
597 valid image specification is a list whose car is the symbol
598 `image', and whose rest is a property list. The property list must
599 contain a value for key `:type'. That value must be the name of a
600 supported image type. The rest of the property list depends on the
604 valid_image_p (Lisp_Object object
)
612 for (tem
= XCDR (object
); CONSP (tem
); tem
= XCDR (tem
))
613 if (EQ (XCAR (tem
), QCtype
))
616 if (CONSP (tem
) && SYMBOLP (XCAR (tem
)))
618 struct image_type
*type
;
619 type
= lookup_image_type (XCAR (tem
));
621 valid_p
= type
->valid_p (object
);
632 /* Log error message with format string FORMAT and trailing arguments.
633 Signaling an error, e.g. when an image cannot be loaded, is not a
634 good idea because this would interrupt redisplay, and the error
635 message display would lead to another redisplay. This function
636 therefore simply displays a message. */
639 image_error (const char *format
, ...)
642 va_start (ap
, format
);
643 vadd_to_log (format
, ap
);
648 image_size_error (void)
650 image_error ("Invalid image size (see `max-image-size')");
654 /***********************************************************************
656 ***********************************************************************/
658 enum image_value_type
660 IMAGE_DONT_CHECK_VALUE_TYPE
,
662 IMAGE_STRING_OR_NIL_VALUE
,
664 IMAGE_POSITIVE_INTEGER_VALUE
,
665 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
,
666 IMAGE_NON_NEGATIVE_INTEGER_VALUE
,
669 IMAGE_FUNCTION_VALUE
,
674 /* Structure used when parsing image specifications. */
678 /* Name of keyword. */
681 /* The type of value allowed. */
682 enum image_value_type type
;
684 /* True means key must be present. */
687 /* Used to recognize duplicate keywords in a property list. */
690 /* The value that was found. */
695 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
696 has the format (image KEYWORD VALUE ...). One of the keyword/
697 value pairs must be `:type TYPE'. KEYWORDS is a vector of
698 image_keywords structures of size NKEYWORDS describing other
699 allowed keyword/value pairs. Value is true if SPEC is valid. */
702 parse_image_spec (Lisp_Object spec
, struct image_keyword
*keywords
,
703 int nkeywords
, Lisp_Object type
)
712 while (CONSP (plist
))
714 Lisp_Object key
, value
;
716 /* First element of a pair must be a symbol. */
718 plist
= XCDR (plist
);
722 /* There must follow a value. */
725 value
= XCAR (plist
);
726 plist
= XCDR (plist
);
728 /* Find key in KEYWORDS. Error if not found. */
729 for (i
= 0; i
< nkeywords
; ++i
)
730 if (strcmp (keywords
[i
].name
, SSDATA (SYMBOL_NAME (key
))) == 0)
736 /* Record that we recognized the keyword. If a keywords
737 was found more than once, it's an error. */
738 keywords
[i
].value
= value
;
739 if (keywords
[i
].count
> 1)
743 /* Check type of value against allowed type. */
744 switch (keywords
[i
].type
)
746 case IMAGE_STRING_VALUE
:
747 if (!STRINGP (value
))
751 case IMAGE_STRING_OR_NIL_VALUE
:
752 if (!STRINGP (value
) && !NILP (value
))
756 case IMAGE_SYMBOL_VALUE
:
757 if (!SYMBOLP (value
))
761 case IMAGE_POSITIVE_INTEGER_VALUE
:
762 if (! RANGED_INTEGERP (1, value
, INT_MAX
))
766 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
:
767 if (RANGED_INTEGERP (0, value
, INT_MAX
))
770 && RANGED_INTEGERP (0, XCAR (value
), INT_MAX
)
771 && RANGED_INTEGERP (0, XCDR (value
), INT_MAX
))
775 case IMAGE_ASCENT_VALUE
:
776 if (SYMBOLP (value
) && EQ (value
, Qcenter
))
778 else if (RANGED_INTEGERP (0, value
, 100))
782 case IMAGE_NON_NEGATIVE_INTEGER_VALUE
:
783 /* Unlike the other integer-related cases, this one does not
784 verify that VALUE fits in 'int'. This is because callers
786 if (!INTEGERP (value
) || XINT (value
) < 0)
790 case IMAGE_DONT_CHECK_VALUE_TYPE
:
793 case IMAGE_FUNCTION_VALUE
:
794 value
= indirect_function (value
);
795 if (!NILP (Ffunctionp (value
)))
799 case IMAGE_NUMBER_VALUE
:
800 if (! NUMBERP (value
))
804 case IMAGE_INTEGER_VALUE
:
805 if (! TYPE_RANGED_INTEGERP (int, value
))
809 case IMAGE_BOOL_VALUE
:
810 if (!NILP (value
) && !EQ (value
, Qt
))
819 if (EQ (key
, QCtype
) && !EQ (type
, value
))
823 /* Check that all mandatory fields are present. */
824 for (i
= 0; i
< nkeywords
; ++i
)
825 if (keywords
[i
].mandatory_p
&& keywords
[i
].count
== 0)
832 /* Return the value of KEY in image specification SPEC. Value is nil
833 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
834 was found in SPEC. */
837 image_spec_value (Lisp_Object spec
, Lisp_Object key
, bool *found
)
841 eassert (valid_image_p (spec
));
843 for (tail
= XCDR (spec
);
844 CONSP (tail
) && CONSP (XCDR (tail
));
845 tail
= XCDR (XCDR (tail
)))
847 if (EQ (XCAR (tail
), key
))
851 return XCAR (XCDR (tail
));
861 DEFUN ("image-size", Fimage_size
, Simage_size
, 1, 3, 0,
862 doc
: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
863 PIXELS non-nil means return the size in pixels, otherwise return the
864 size in canonical character units.
865 FRAME is the frame on which the image will be displayed. FRAME nil
866 or omitted means use the selected frame. */)
867 (Lisp_Object spec
, Lisp_Object pixels
, Lisp_Object frame
)
872 if (valid_image_p (spec
))
874 struct frame
*f
= decode_window_system_frame (frame
);
875 ptrdiff_t id
= lookup_image (f
, spec
);
876 struct image
*img
= IMAGE_FROM_ID (f
, id
);
877 int width
= img
->width
+ 2 * img
->hmargin
;
878 int height
= img
->height
+ 2 * img
->vmargin
;
881 size
= Fcons (make_float ((double) width
/ FRAME_COLUMN_WIDTH (f
)),
882 make_float ((double) height
/ FRAME_LINE_HEIGHT (f
)));
884 size
= Fcons (make_number (width
), make_number (height
));
887 error ("Invalid image specification");
893 DEFUN ("image-mask-p", Fimage_mask_p
, Simage_mask_p
, 1, 2, 0,
894 doc
: /* Return t if image SPEC has a mask bitmap.
895 FRAME is the frame on which the image will be displayed. FRAME nil
896 or omitted means use the selected frame. */)
897 (Lisp_Object spec
, Lisp_Object frame
)
902 if (valid_image_p (spec
))
904 struct frame
*f
= decode_window_system_frame (frame
);
905 ptrdiff_t id
= lookup_image (f
, spec
);
906 struct image
*img
= IMAGE_FROM_ID (f
, id
);
911 error ("Invalid image specification");
916 DEFUN ("image-metadata", Fimage_metadata
, Simage_metadata
, 1, 2, 0,
917 doc
: /* Return metadata for image SPEC.
918 FRAME is the frame on which the image will be displayed. FRAME nil
919 or omitted means use the selected frame. */)
920 (Lisp_Object spec
, Lisp_Object frame
)
925 if (valid_image_p (spec
))
927 struct frame
*f
= decode_window_system_frame (frame
);
928 ptrdiff_t id
= lookup_image (f
, spec
);
929 struct image
*img
= IMAGE_FROM_ID (f
, id
);
930 ext
= img
->lisp_data
;
937 /***********************************************************************
938 Image type independent image structures
939 ***********************************************************************/
941 #define MAX_IMAGE_SIZE 10.0
942 /* Allocate and return a new image structure for image specification
943 SPEC. SPEC has a hash value of HASH. */
945 static struct image
*
946 make_image (Lisp_Object spec
, EMACS_UINT hash
)
948 struct image
*img
= xzalloc (sizeof *img
);
949 Lisp_Object file
= image_spec_value (spec
, QCfile
, NULL
);
951 eassert (valid_image_p (spec
));
952 img
->dependencies
= NILP (file
) ? Qnil
: list1 (file
);
953 img
->type
= lookup_image_type (image_spec_value (spec
, QCtype
, NULL
));
954 eassert (img
->type
!= NULL
);
956 img
->lisp_data
= Qnil
;
957 img
->ascent
= DEFAULT_IMAGE_ASCENT
;
959 img
->corners
[BOT_CORNER
] = -1; /* Full image */
964 /* Free image IMG which was used on frame F, including its resources. */
967 free_image (struct frame
*f
, struct image
*img
)
971 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
973 /* Remove IMG from the hash table of its cache. */
975 img
->prev
->next
= img
->next
;
977 c
->buckets
[img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
] = img
->next
;
980 img
->next
->prev
= img
->prev
;
982 c
->images
[img
->id
] = NULL
;
984 /* Windows NT redefines 'free', but in this file, we need to
985 avoid the redefinition. */
989 /* Free resources, then free IMG. */
990 img
->type
->free (f
, img
);
995 /* Return true if the given widths and heights are valid for display. */
998 check_image_size (struct frame
*f
, int width
, int height
)
1002 if (width
<= 0 || height
<= 0)
1005 if (INTEGERP (Vmax_image_size
))
1006 return (width
<= XINT (Vmax_image_size
)
1007 && height
<= XINT (Vmax_image_size
));
1008 else if (FLOATP (Vmax_image_size
))
1012 w
= FRAME_PIXEL_WIDTH (f
);
1013 h
= FRAME_PIXEL_HEIGHT (f
);
1016 w
= h
= 1024; /* Arbitrary size for unknown frame. */
1017 return (width
<= XFLOAT_DATA (Vmax_image_size
) * w
1018 && height
<= XFLOAT_DATA (Vmax_image_size
) * h
);
1024 /* Prepare image IMG for display on frame F. Must be called before
1025 drawing an image. */
1028 prepare_image_for_display (struct frame
*f
, struct image
*img
)
1030 /* We're about to display IMG, so set its timestamp to `now'. */
1031 img
->timestamp
= current_timespec ();
1034 /* If IMG doesn't have a pixmap yet, load it now, using the image
1035 type dependent loader function. */
1036 if (img
->pixmap
== NO_PIXMAP
&& !img
->load_failed_p
)
1037 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1039 #ifdef HAVE_X_WINDOWS
1040 if (!img
->load_failed_p
)
1043 image_sync_to_pixmaps (f
, img
);
1051 /* Value is the number of pixels for the ascent of image IMG when
1052 drawn in face FACE. */
1055 image_ascent (struct image
*img
, struct face
*face
, struct glyph_slice
*slice
)
1060 if (slice
->height
== img
->height
)
1061 height
= img
->height
+ img
->vmargin
;
1062 else if (slice
->y
== 0)
1063 height
= slice
->height
+ img
->vmargin
;
1065 height
= slice
->height
;
1067 if (img
->ascent
== CENTERED_IMAGE_ASCENT
)
1072 /* W32 specific version. Why?. ++kfs */
1073 ascent
= height
/ 2 - (FONT_DESCENT (face
->font
)
1074 - FONT_BASE (face
->font
)) / 2;
1076 /* This expression is arranged so that if the image can't be
1077 exactly centered, it will be moved slightly up. This is
1078 because a typical font is `top-heavy' (due to the presence
1079 uppercase letters), so the image placement should err towards
1080 being top-heavy too. It also just generally looks better. */
1081 ascent
= (height
+ FONT_BASE (face
->font
)
1082 - FONT_DESCENT (face
->font
) + 1) / 2;
1083 #endif /* HAVE_NTGUI */
1086 ascent
= height
/ 2;
1089 ascent
= height
* (img
->ascent
/ 100.0);
1096 xcolor_to_argb32 (XColor xc
)
1098 return (0xff << 24) | ((xc
.red
/ 256) << 16)
1099 | ((xc
.green
/ 256) << 8) | (xc
.blue
/ 256);
1103 get_spec_bg_or_alpha_as_argb (struct image
*img
,
1106 uint32_t bgcolor
= 0;
1108 Lisp_Object bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1110 if (STRINGP (bg
) && x_parse_color (f
, SSDATA (bg
), &xbgcolor
))
1111 bgcolor
= xcolor_to_argb32 (xbgcolor
);
1117 create_cairo_image_surface (struct image
*img
,
1118 unsigned char *data
,
1122 cairo_surface_t
*surface
;
1123 cairo_format_t format
= CAIRO_FORMAT_ARGB32
;
1124 int stride
= cairo_format_stride_for_width (format
, width
);
1125 surface
= cairo_image_surface_create_for_data (data
,
1131 img
->height
= height
;
1132 img
->cr_data
= surface
;
1133 img
->cr_data2
= data
;
1140 /* Image background colors. */
1142 /* Find the "best" corner color of a bitmap.
1143 On W32, XIMG is assumed to a device context with the bitmap selected. */
1145 static RGB_PIXEL_COLOR
1146 four_corners_best (XImagePtr_or_DC ximg
, int *corners
,
1147 unsigned long width
, unsigned long height
)
1149 RGB_PIXEL_COLOR corner_pixels
[4], best
IF_LINT (= 0);
1152 if (corners
&& corners
[BOT_CORNER
] >= 0)
1154 /* Get the colors at the corner_pixels of ximg. */
1155 corner_pixels
[0] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[TOP_CORNER
]);
1156 corner_pixels
[1] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[TOP_CORNER
]);
1157 corner_pixels
[2] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[BOT_CORNER
] - 1);
1158 corner_pixels
[3] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[BOT_CORNER
] - 1);
1162 /* Get the colors at the corner_pixels of ximg. */
1163 corner_pixels
[0] = GET_PIXEL (ximg
, 0, 0);
1164 corner_pixels
[1] = GET_PIXEL (ximg
, width
- 1, 0);
1165 corner_pixels
[2] = GET_PIXEL (ximg
, width
- 1, height
- 1);
1166 corner_pixels
[3] = GET_PIXEL (ximg
, 0, height
- 1);
1168 /* Choose the most frequently found color as background. */
1169 for (i
= best_count
= 0; i
< 4; ++i
)
1173 for (j
= n
= 0; j
< 4; ++j
)
1174 if (corner_pixels
[i
] == corner_pixels
[j
])
1178 best
= corner_pixels
[i
], best_count
= n
;
1184 /* Portability macros */
1188 #define Free_Pixmap(display, pixmap) \
1189 DeleteObject (pixmap)
1191 #elif defined (HAVE_NS)
1193 #define Free_Pixmap(display, pixmap) \
1194 ns_release_object (pixmap)
1198 #define Free_Pixmap(display, pixmap) \
1199 XFreePixmap (display, pixmap)
1201 #endif /* !HAVE_NTGUI && !HAVE_NS */
1204 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1205 it is guessed heuristically. If non-zero, XIMG is an existing
1206 XImage object (or device context with the image selected on W32) to
1207 use for the heuristic. */
1210 image_background (struct image
*img
, struct frame
*f
, XImagePtr_or_DC ximg
)
1212 if (! img
->background_valid
)
1213 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1215 bool free_ximg
= !ximg
;
1218 #endif /* HAVE_NTGUI */
1221 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
1223 img
->background
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
1226 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
1228 img
->background_valid
= 1;
1231 return img
->background
;
1234 /* Return the `background_transparent' field of IMG. If IMG doesn't
1235 have one yet, it is guessed heuristically. If non-zero, MASK is an
1236 existing XImage object to use for the heuristic. */
1239 image_background_transparent (struct image
*img
, struct frame
*f
, XImagePtr_or_DC mask
)
1241 if (! img
->background_transparent_valid
)
1242 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1246 bool free_mask
= !mask
;
1249 #endif /* HAVE_NTGUI */
1252 mask
= image_get_x_image_or_dc (f
, img
, 1, &prev
);
1254 img
->background_transparent
1255 = (four_corners_best (mask
, img
->corners
, img
->width
, img
->height
) == PIX_MASK_RETAIN
);
1258 image_unget_x_image_or_dc (img
, 1, mask
, prev
);
1261 img
->background_transparent
= 0;
1263 img
->background_transparent_valid
= 1;
1266 return img
->background_transparent
;
1269 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1270 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1272 /* Store F's background color into *BGCOLOR. */
1274 x_query_frame_background_color (struct frame
*f
, XColor
*bgcolor
)
1277 bgcolor
->pixel
= FRAME_BACKGROUND_PIXEL (f
);
1278 x_query_color (f
, bgcolor
);
1280 ns_query_color (FRAME_BACKGROUND_COLOR (f
), bgcolor
, 1);
1284 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1286 /***********************************************************************
1287 Helper functions for X image types
1288 ***********************************************************************/
1290 /* Clear X resources of image IMG on frame F according to FLAGS.
1291 FLAGS is bitwise-or of the following masks:
1292 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1293 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1294 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1297 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1298 #define CLEAR_IMAGE_MASK (1 << 1)
1299 #define CLEAR_IMAGE_COLORS (1 << 2)
1302 x_clear_image_1 (struct frame
*f
, struct image
*img
, int flags
)
1304 if (flags
& CLEAR_IMAGE_PIXMAP
)
1308 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->pixmap
);
1309 img
->pixmap
= NO_PIXMAP
;
1310 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1311 img
->background_valid
= 0;
1313 #ifdef HAVE_X_WINDOWS
1316 x_destroy_x_image (img
->ximg
);
1318 img
->background_valid
= 0;
1323 if (flags
& CLEAR_IMAGE_MASK
)
1327 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->mask
);
1328 img
->mask
= NO_PIXMAP
;
1329 img
->background_transparent_valid
= 0;
1331 #ifdef HAVE_X_WINDOWS
1334 x_destroy_x_image (img
->mask_img
);
1335 img
->mask_img
= NULL
;
1336 img
->background_transparent_valid
= 0;
1341 if ((flags
& CLEAR_IMAGE_COLORS
) && img
->ncolors
)
1343 /* W32_TODO: color table support. */
1344 #ifdef HAVE_X_WINDOWS
1345 x_free_colors (f
, img
->colors
, img
->ncolors
);
1346 #endif /* HAVE_X_WINDOWS */
1347 xfree (img
->colors
);
1354 /* Free X resources of image IMG which is used on frame F. */
1357 x_clear_image (struct frame
*f
, struct image
*img
)
1362 cairo_surface_destroy ((cairo_surface_t
*)img
->cr_data
);
1363 if (img
->cr_data2
) xfree (img
->cr_data2
);
1365 x_clear_image_1 (f
, img
,
1366 CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_MASK
| CLEAR_IMAGE_COLORS
);
1371 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1372 cannot be allocated, use DFLT. Add a newly allocated color to
1373 IMG->colors, so that it can be freed again. Value is the pixel
1376 static unsigned long
1377 x_alloc_image_color (struct frame
*f
, struct image
*img
, Lisp_Object color_name
,
1381 unsigned long result
;
1383 eassert (STRINGP (color_name
));
1385 if (x_defined_color (f
, SSDATA (color_name
), &color
, 1)
1386 && img
->ncolors
< min (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *img
->colors
,
1389 /* This isn't called frequently so we get away with simply
1390 reallocating the color vector to the needed size, here. */
1391 ptrdiff_t ncolors
= img
->ncolors
+ 1;
1392 img
->colors
= xrealloc (img
->colors
, ncolors
* sizeof *img
->colors
);
1393 img
->colors
[ncolors
- 1] = color
.pixel
;
1394 img
->ncolors
= ncolors
;
1395 result
= color
.pixel
;
1405 /***********************************************************************
1407 ***********************************************************************/
1409 static void cache_image (struct frame
*f
, struct image
*img
);
1411 /* Return a new, initialized image cache that is allocated from the
1412 heap. Call free_image_cache to free an image cache. */
1414 struct image_cache
*
1415 make_image_cache (void)
1417 struct image_cache
*c
= xmalloc (sizeof *c
);
1420 c
->used
= c
->refcount
= 0;
1421 c
->images
= xmalloc (c
->size
* sizeof *c
->images
);
1422 c
->buckets
= xzalloc (IMAGE_CACHE_BUCKETS_SIZE
* sizeof *c
->buckets
);
1427 /* Find an image matching SPEC in the cache, and return it. If no
1428 image is found, return NULL. */
1429 static struct image
*
1430 search_image_cache (struct frame
*f
, Lisp_Object spec
, EMACS_UINT hash
)
1433 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1434 int i
= hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1436 if (!c
) return NULL
;
1438 /* If the image spec does not specify a background color, the cached
1439 image must have the same background color as the current frame.
1440 The foreground color must also match, for the sake of monochrome
1443 In fact, we could ignore the foreground color matching condition
1444 for color images, or if the image spec specifies :foreground;
1445 similarly we could ignore the background color matching condition
1446 for formats that don't use transparency (such as jpeg), or if the
1447 image spec specifies :background. However, the extra memory
1448 usage is probably negligible in practice, so we don't bother. */
1450 for (img
= c
->buckets
[i
]; img
; img
= img
->next
)
1451 if (img
->hash
== hash
1452 && !NILP (Fequal (img
->spec
, spec
))
1453 && img
->frame_foreground
== FRAME_FOREGROUND_PIXEL (f
)
1454 && img
->frame_background
== FRAME_BACKGROUND_PIXEL (f
))
1460 /* Search frame F for an image with spec SPEC, and free it. */
1463 uncache_image (struct frame
*f
, Lisp_Object spec
)
1465 struct image
*img
= search_image_cache (f
, spec
, sxhash (spec
, 0));
1468 free_image (f
, img
);
1469 /* As display glyphs may still be referring to the image ID, we
1470 must garbage the frame (Bug#6426). */
1471 SET_FRAME_GARBAGED (f
);
1476 /* Free image cache of frame F. Be aware that X frames share images
1480 free_image_cache (struct frame
*f
)
1482 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1487 /* Cache should not be referenced by any frame when freed. */
1488 eassert (c
->refcount
== 0);
1490 for (i
= 0; i
< c
->used
; ++i
)
1491 free_image (f
, c
->images
[i
]);
1495 FRAME_IMAGE_CACHE (f
) = NULL
;
1500 /* Clear image cache of frame F. FILTER=t means free all images.
1501 FILTER=nil means clear only images that haven't been
1502 displayed for some time.
1503 Else, only free the images which have FILTER in their `dependencies'.
1504 Should be called from time to time to reduce the number of loaded images.
1505 If image-cache-eviction-delay is non-nil, this frees images in the cache
1506 which weren't displayed for at least that many seconds. */
1509 clear_image_cache (struct frame
*f
, Lisp_Object filter
)
1511 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1515 ptrdiff_t i
, nfreed
= 0;
1517 /* Block input so that we won't be interrupted by a SIGIO
1518 while being in an inconsistent state. */
1523 /* Filter image cache. */
1524 for (i
= 0; i
< c
->used
; ++i
)
1526 struct image
*img
= c
->images
[i
];
1527 if (img
&& (EQ (Qt
, filter
)
1528 || !NILP (Fmember (filter
, img
->dependencies
))))
1530 free_image (f
, img
);
1535 else if (INTEGERP (Vimage_cache_eviction_delay
))
1537 /* Free cache based on timestamp. */
1538 struct timespec old
, t
;
1540 ptrdiff_t nimages
= 0;
1542 for (i
= 0; i
< c
->used
; ++i
)
1546 /* If the number of cached images has grown unusually large,
1547 decrease the cache eviction delay (Bug#6230). */
1548 delay
= XINT (Vimage_cache_eviction_delay
);
1550 delay
= 1600 * delay
/ nimages
/ nimages
;
1551 delay
= max (delay
, 1);
1553 t
= current_timespec ();
1554 old
= timespec_sub (t
, dtotimespec (delay
));
1556 for (i
= 0; i
< c
->used
; ++i
)
1558 struct image
*img
= c
->images
[i
];
1559 if (img
&& timespec_cmp (img
->timestamp
, old
) < 0)
1561 free_image (f
, img
);
1567 /* We may be clearing the image cache because, for example,
1568 Emacs was iconified for a longer period of time. In that
1569 case, current matrices may still contain references to
1570 images freed above. So, clear these matrices. */
1573 Lisp_Object tail
, frame
;
1575 FOR_EACH_FRAME (tail
, frame
)
1577 struct frame
*fr
= XFRAME (frame
);
1578 if (FRAME_IMAGE_CACHE (fr
) == c
)
1579 clear_current_matrices (fr
);
1582 windows_or_buffers_changed
= 19;
1590 clear_image_caches (Lisp_Object filter
)
1592 /* FIXME: We want to do
1593 * struct terminal *t;
1594 * for (t = terminal_list; t; t = t->next_terminal)
1595 * clear_image_cache (t, filter); */
1596 Lisp_Object tail
, frame
;
1597 FOR_EACH_FRAME (tail
, frame
)
1598 if (FRAME_WINDOW_P (XFRAME (frame
)))
1599 clear_image_cache (XFRAME (frame
), filter
);
1602 DEFUN ("clear-image-cache", Fclear_image_cache
, Sclear_image_cache
,
1604 doc
: /* Clear the image cache.
1605 FILTER nil or a frame means clear all images in the selected frame.
1606 FILTER t means clear the image caches of all frames.
1607 Anything else, means only clear those images which refer to FILTER,
1608 which is then usually a filename. */)
1609 (Lisp_Object filter
)
1611 if (!(EQ (filter
, Qnil
) || FRAMEP (filter
)))
1612 clear_image_caches (filter
);
1614 clear_image_cache (decode_window_system_frame (filter
), Qt
);
1620 DEFUN ("image-flush", Fimage_flush
, Simage_flush
,
1622 doc
: /* Flush the image with specification SPEC on frame FRAME.
1623 This removes the image from the Emacs image cache. If SPEC specifies
1624 an image file, the next redisplay of this image will read from the
1625 current contents of that file.
1627 FRAME nil or omitted means use the selected frame.
1628 FRAME t means refresh the image on all frames. */)
1629 (Lisp_Object spec
, Lisp_Object frame
)
1631 if (!valid_image_p (spec
))
1632 error ("Invalid image specification");
1637 FOR_EACH_FRAME (tail
, frame
)
1639 struct frame
*f
= XFRAME (frame
);
1640 if (FRAME_WINDOW_P (f
))
1641 uncache_image (f
, spec
);
1645 uncache_image (decode_window_system_frame (frame
), spec
);
1651 /* Compute masks and transform image IMG on frame F, as specified
1652 by the image's specification, */
1655 postprocess_image (struct frame
*f
, struct image
*img
)
1657 /* Manipulation of the image's mask. */
1660 Lisp_Object conversion
, spec
;
1665 /* `:heuristic-mask t'
1667 means build a mask heuristically.
1668 `:heuristic-mask (R G B)'
1669 `:mask (heuristic (R G B))'
1670 means build a mask from color (R G B) in the
1673 means remove a mask, if any. */
1675 mask
= image_spec_value (spec
, QCheuristic_mask
, NULL
);
1677 x_build_heuristic_mask (f
, img
, mask
);
1682 mask
= image_spec_value (spec
, QCmask
, &found_p
);
1684 if (EQ (mask
, Qheuristic
))
1685 x_build_heuristic_mask (f
, img
, Qt
);
1686 else if (CONSP (mask
)
1687 && EQ (XCAR (mask
), Qheuristic
))
1689 if (CONSP (XCDR (mask
)))
1690 x_build_heuristic_mask (f
, img
, XCAR (XCDR (mask
)));
1692 x_build_heuristic_mask (f
, img
, XCDR (mask
));
1694 else if (NILP (mask
) && found_p
&& img
->mask
)
1695 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
1699 /* Should we apply an image transformation algorithm? */
1700 conversion
= image_spec_value (spec
, QCconversion
, NULL
);
1701 if (EQ (conversion
, Qdisabled
))
1702 x_disable_image (f
, img
);
1703 else if (EQ (conversion
, Qlaplace
))
1705 else if (EQ (conversion
, Qemboss
))
1707 else if (CONSP (conversion
)
1708 && EQ (XCAR (conversion
), Qedge_detection
))
1711 tem
= XCDR (conversion
);
1713 x_edge_detection (f
, img
,
1714 Fplist_get (tem
, QCmatrix
),
1715 Fplist_get (tem
, QCcolor_adjustment
));
1721 /* Return the id of image with Lisp specification SPEC on frame F.
1722 SPEC must be a valid Lisp image specification (see valid_image_p). */
1725 lookup_image (struct frame
*f
, Lisp_Object spec
)
1730 /* F must be a window-system frame, and SPEC must be a valid image
1732 eassert (FRAME_WINDOW_P (f
));
1733 eassert (valid_image_p (spec
));
1735 /* Look up SPEC in the hash table of the image cache. */
1736 hash
= sxhash (spec
, 0);
1737 img
= search_image_cache (f
, spec
, hash
);
1738 if (img
&& img
->load_failed_p
)
1740 free_image (f
, img
);
1744 /* If not found, create a new image and cache it. */
1748 img
= make_image (spec
, hash
);
1749 cache_image (f
, img
);
1750 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1751 img
->frame_foreground
= FRAME_FOREGROUND_PIXEL (f
);
1752 img
->frame_background
= FRAME_BACKGROUND_PIXEL (f
);
1754 /* If we can't load the image, and we don't have a width and
1755 height, use some arbitrary width and height so that we can
1756 draw a rectangle for it. */
1757 if (img
->load_failed_p
)
1761 value
= image_spec_value (spec
, QCwidth
, NULL
);
1762 img
->width
= (INTEGERP (value
)
1763 ? XFASTINT (value
) : DEFAULT_IMAGE_WIDTH
);
1764 value
= image_spec_value (spec
, QCheight
, NULL
);
1765 img
->height
= (INTEGERP (value
)
1766 ? XFASTINT (value
) : DEFAULT_IMAGE_HEIGHT
);
1770 /* Handle image type independent image attributes
1771 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1772 `:background COLOR'. */
1773 Lisp_Object ascent
, margin
, relief
, bg
;
1776 ascent
= image_spec_value (spec
, QCascent
, NULL
);
1777 if (INTEGERP (ascent
))
1778 img
->ascent
= XFASTINT (ascent
);
1779 else if (EQ (ascent
, Qcenter
))
1780 img
->ascent
= CENTERED_IMAGE_ASCENT
;
1782 margin
= image_spec_value (spec
, QCmargin
, NULL
);
1783 if (INTEGERP (margin
))
1784 img
->vmargin
= img
->hmargin
= XFASTINT (margin
);
1785 else if (CONSP (margin
))
1787 img
->hmargin
= XFASTINT (XCAR (margin
));
1788 img
->vmargin
= XFASTINT (XCDR (margin
));
1791 relief
= image_spec_value (spec
, QCrelief
, NULL
);
1792 relief_bound
= INT_MAX
- max (img
->hmargin
, img
->vmargin
);
1793 if (RANGED_INTEGERP (- relief_bound
, relief
, relief_bound
))
1795 img
->relief
= XINT (relief
);
1796 img
->hmargin
+= eabs (img
->relief
);
1797 img
->vmargin
+= eabs (img
->relief
);
1800 if (! img
->background_valid
)
1802 bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1806 = x_alloc_image_color (f
, img
, bg
,
1807 FRAME_BACKGROUND_PIXEL (f
));
1808 img
->background_valid
= 1;
1812 /* Do image transformations and compute masks, unless we
1813 don't have the image yet. */
1814 if (!EQ (builtin_lisp_symbol (img
->type
->type
), Qpostscript
))
1815 postprocess_image (f
, img
);
1821 /* We're using IMG, so set its timestamp to `now'. */
1822 img
->timestamp
= current_timespec ();
1824 /* Value is the image id. */
1829 /* Cache image IMG in the image cache of frame F. */
1832 cache_image (struct frame
*f
, struct image
*img
)
1834 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1837 /* Find a free slot in c->images. */
1838 for (i
= 0; i
< c
->used
; ++i
)
1839 if (c
->images
[i
] == NULL
)
1842 /* If no free slot found, maybe enlarge c->images. */
1843 if (i
== c
->used
&& c
->used
== c
->size
)
1844 c
->images
= xpalloc (c
->images
, &c
->size
, 1, -1, sizeof *c
->images
);
1846 /* Add IMG to c->images, and assign IMG an id. */
1852 /* Add IMG to the cache's hash table. */
1853 i
= img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1854 img
->next
= c
->buckets
[i
];
1856 img
->next
->prev
= img
;
1858 c
->buckets
[i
] = img
;
1862 /* Call FN on every image in the image cache of frame F. Used to mark
1863 Lisp Objects in the image cache. */
1865 /* Mark Lisp objects in image IMG. */
1868 mark_image (struct image
*img
)
1870 mark_object (img
->spec
);
1871 mark_object (img
->dependencies
);
1873 if (!NILP (img
->lisp_data
))
1874 mark_object (img
->lisp_data
);
1879 mark_image_cache (struct image_cache
*c
)
1884 for (i
= 0; i
< c
->used
; ++i
)
1886 mark_image (c
->images
[i
]);
1892 /***********************************************************************
1893 X / NS / W32 support code
1894 ***********************************************************************/
1896 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1898 WIDTH and HEIGHT must both be positive.
1899 If XIMG is null, assume it is a bitmap. */
1901 x_check_image_size (XImagePtr ximg
, int width
, int height
)
1903 #ifdef HAVE_X_WINDOWS
1904 /* Respect Xlib's limits: it cannot deal with images that have more
1905 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1906 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1909 XLIB_BYTES_MAX
= min (INT_MAX
, UINT_MAX
),
1910 X_IMAGE_BYTES_MAX
= min (XLIB_BYTES_MAX
, min (PTRDIFF_MAX
, SIZE_MAX
))
1913 int bitmap_pad
, depth
, bytes_per_line
;
1916 bitmap_pad
= ximg
->bitmap_pad
;
1917 depth
= ximg
->depth
;
1918 bytes_per_line
= ximg
->bytes_per_line
;
1924 bytes_per_line
= (width
>> 3) + ((width
& 7) != 0);
1926 return (width
<= (INT_MAX
- (bitmap_pad
- 1)) / depth
1927 && height
<= X_IMAGE_BYTES_MAX
/ bytes_per_line
);
1929 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1930 For now, assume that every image size is allowed on these systems. */
1935 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1936 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1937 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1938 via xmalloc. Print error messages via image_error if an error
1939 occurs. Value is true if successful.
1941 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1942 should indicate the bit depth of the image. */
1945 x_create_x_image_and_pixmap (struct frame
*f
, int width
, int height
, int depth
,
1946 XImagePtr
*ximg
, Pixmap
*pixmap
)
1948 #ifdef HAVE_X_WINDOWS
1949 Display
*display
= FRAME_X_DISPLAY (f
);
1950 Window window
= FRAME_X_WINDOW (f
);
1951 Screen
*screen
= FRAME_X_SCREEN (f
);
1953 eassert (input_blocked_p ());
1956 depth
= DefaultDepthOfScreen (screen
);
1957 *ximg
= XCreateImage (display
, DefaultVisualOfScreen (screen
),
1958 depth
, ZPixmap
, 0, NULL
, width
, height
,
1959 depth
> 16 ? 32 : depth
> 8 ? 16 : 8, 0);
1962 image_error ("Unable to allocate X image");
1966 if (! x_check_image_size (*ximg
, width
, height
))
1968 x_destroy_x_image (*ximg
);
1970 image_error ("Image too large (%dx%d)",
1971 make_number (width
), make_number (height
));
1975 /* Allocate image raster. */
1976 (*ximg
)->data
= xmalloc ((*ximg
)->bytes_per_line
* height
);
1978 /* Allocate a pixmap of the same size. */
1979 *pixmap
= XCreatePixmap (display
, window
, width
, height
, depth
);
1980 if (*pixmap
== NO_PIXMAP
)
1982 x_destroy_x_image (*ximg
);
1984 image_error ("Unable to create X pixmap");
1989 #endif /* HAVE_X_WINDOWS */
1993 BITMAPINFOHEADER
*header
;
1995 int scanline_width_bits
;
1997 int palette_colors
= 0;
2002 if (depth
!= 1 && depth
!= 4 && depth
!= 8
2003 && depth
!= 16 && depth
!= 24 && depth
!= 32)
2005 image_error ("Invalid image bit depth specified");
2009 scanline_width_bits
= width
* depth
;
2010 remainder
= scanline_width_bits
% 32;
2013 scanline_width_bits
+= 32 - remainder
;
2015 /* Bitmaps with a depth less than 16 need a palette. */
2016 /* BITMAPINFO structure already contains the first RGBQUAD. */
2018 palette_colors
= 1 << (depth
- 1);
2020 *ximg
= xmalloc (sizeof (XImage
) + palette_colors
* sizeof (RGBQUAD
));
2022 header
= &(*ximg
)->info
.bmiHeader
;
2023 memset (&(*ximg
)->info
, 0, sizeof (BITMAPINFO
));
2024 header
->biSize
= sizeof (*header
);
2025 header
->biWidth
= width
;
2026 header
->biHeight
= -height
; /* negative indicates a top-down bitmap. */
2027 header
->biPlanes
= 1;
2028 header
->biBitCount
= depth
;
2029 header
->biCompression
= BI_RGB
;
2030 header
->biClrUsed
= palette_colors
;
2032 /* TODO: fill in palette. */
2035 (*ximg
)->info
.bmiColors
[0].rgbBlue
= 0;
2036 (*ximg
)->info
.bmiColors
[0].rgbGreen
= 0;
2037 (*ximg
)->info
.bmiColors
[0].rgbRed
= 0;
2038 (*ximg
)->info
.bmiColors
[0].rgbReserved
= 0;
2039 (*ximg
)->info
.bmiColors
[1].rgbBlue
= 255;
2040 (*ximg
)->info
.bmiColors
[1].rgbGreen
= 255;
2041 (*ximg
)->info
.bmiColors
[1].rgbRed
= 255;
2042 (*ximg
)->info
.bmiColors
[1].rgbReserved
= 0;
2045 hdc
= get_frame_dc (f
);
2047 /* Create a DIBSection and raster array for the bitmap,
2048 and store its handle in *pixmap. */
2049 *pixmap
= CreateDIBSection (hdc
, &((*ximg
)->info
),
2050 (depth
< 16) ? DIB_PAL_COLORS
: DIB_RGB_COLORS
,
2051 /* casting avoids a GCC warning */
2052 (void **)&((*ximg
)->data
), NULL
, 0);
2054 /* Realize display palette and garbage all frames. */
2055 release_frame_dc (f
, hdc
);
2057 if (*pixmap
== NULL
)
2059 DWORD err
= GetLastError ();
2060 Lisp_Object errcode
;
2061 /* All system errors are < 10000, so the following is safe. */
2062 XSETINT (errcode
, err
);
2063 image_error ("Unable to create bitmap, error code %d", errcode
);
2064 x_destroy_x_image (*ximg
);
2071 #endif /* HAVE_NTGUI */
2074 *pixmap
= ns_image_for_XPM (width
, height
, depth
);
2078 image_error ("Unable to allocate NSImage for XPM pixmap");
2087 /* Destroy XImage XIMG. Free XIMG->data. */
2090 x_destroy_x_image (XImagePtr ximg
)
2092 eassert (input_blocked_p ());
2095 #ifdef HAVE_X_WINDOWS
2098 XDestroyImage (ximg
);
2099 #endif /* HAVE_X_WINDOWS */
2101 /* Data will be freed by DestroyObject. */
2104 #endif /* HAVE_NTGUI */
2106 ns_release_object (ximg
);
2107 #endif /* HAVE_NS */
2112 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2113 are width and height of both the image and pixmap. */
2116 x_put_x_image (struct frame
*f
, XImagePtr ximg
, Pixmap pixmap
, int width
, int height
)
2118 #ifdef HAVE_X_WINDOWS
2121 eassert (input_blocked_p ());
2122 gc
= XCreateGC (FRAME_X_DISPLAY (f
), pixmap
, 0, NULL
);
2123 XPutImage (FRAME_X_DISPLAY (f
), pixmap
, gc
, ximg
, 0, 0, 0, 0, width
, height
);
2124 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
2125 #endif /* HAVE_X_WINDOWS */
2128 #if 0 /* I don't think this is necessary looking at where it is used. */
2129 HDC hdc
= get_frame_dc (f
);
2130 SetDIBits (hdc
, pixmap
, 0, height
, ximg
->data
, &(ximg
->info
), DIB_RGB_COLORS
);
2131 release_frame_dc (f
, hdc
);
2133 #endif /* HAVE_NTGUI */
2136 eassert (ximg
== pixmap
);
2137 ns_retain_object (ximg
);
2141 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2142 with image_put_x_image. */
2145 image_create_x_image_and_pixmap (struct frame
*f
, struct image
*img
,
2146 int width
, int height
, int depth
,
2147 XImagePtr
*ximg
, bool mask_p
)
2149 eassert ((!mask_p
? img
->pixmap
: img
->mask
) == NO_PIXMAP
);
2151 return x_create_x_image_and_pixmap (f
, width
, height
, depth
, ximg
,
2152 !mask_p
? &img
->pixmap
: &img
->mask
);
2155 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2156 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2157 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2158 On the other platforms, it puts XIMG into the pixmap, then frees
2159 the X image and its buffer. */
2162 image_put_x_image (struct frame
*f
, struct image
*img
, XImagePtr ximg
,
2165 #ifdef HAVE_X_WINDOWS
2168 eassert (img
->ximg
== NULL
);
2173 eassert (img
->mask_img
== NULL
);
2174 img
->mask_img
= ximg
;
2177 x_put_x_image (f
, ximg
, !mask_p
? img
->pixmap
: img
->mask
,
2178 img
->width
, img
->height
);
2179 x_destroy_x_image (ximg
);
2183 #ifdef HAVE_X_WINDOWS
2184 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2185 the X images and their buffers. */
2188 image_sync_to_pixmaps (struct frame
*f
, struct image
*img
)
2192 x_put_x_image (f
, img
->ximg
, img
->pixmap
, img
->width
, img
->height
);
2193 x_destroy_x_image (img
->ximg
);
2198 x_put_x_image (f
, img
->mask_img
, img
->mask
, img
->width
, img
->height
);
2199 x_destroy_x_image (img
->mask_img
);
2200 img
->mask_img
= NULL
;
2206 /* Create a memory device context for IMG on frame F. It stores the
2207 currently selected GDI object into *PREV for future restoration by
2208 image_unget_x_image_or_dc. */
2210 static XImagePtr_or_DC
2211 image_get_x_image_or_dc (struct frame
*f
, struct image
*img
, bool mask_p
,
2214 HDC frame_dc
= get_frame_dc (f
);
2215 XImagePtr_or_DC ximg
= CreateCompatibleDC (frame_dc
);
2217 release_frame_dc (f
, frame_dc
);
2218 *prev
= SelectObject (ximg
, !mask_p
? img
->pixmap
: img
->mask
);
2224 image_unget_x_image_or_dc (struct image
*img
, bool mask_p
,
2225 XImagePtr_or_DC ximg
, HGDIOBJ prev
)
2227 SelectObject (ximg
, prev
);
2230 #else /* !HAVE_NTGUI */
2231 /* Get the X image for IMG on frame F. The resulting X image data
2232 should be treated as read-only at least on X. */
2235 image_get_x_image (struct frame
*f
, struct image
*img
, bool mask_p
)
2237 #ifdef HAVE_X_WINDOWS
2238 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2243 return XGetImage (FRAME_X_DISPLAY (f
), !mask_p
? img
->pixmap
: img
->mask
,
2244 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
2245 #elif defined (HAVE_NS)
2246 XImagePtr pixmap
= !mask_p
? img
->pixmap
: img
->mask
;
2248 ns_retain_object (pixmap
);
2254 image_unget_x_image (struct image
*img
, bool mask_p
, XImagePtr ximg
)
2256 #ifdef HAVE_X_WINDOWS
2257 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2260 eassert (ximg
== ximg_in_img
);
2262 XDestroyImage (ximg
);
2263 #elif defined (HAVE_NS)
2264 ns_release_object (ximg
);
2267 #endif /* !HAVE_NTGUI */
2270 /***********************************************************************
2272 ***********************************************************************/
2274 /* Find image file FILE. Look in data-directory/images, then
2275 x-bitmap-file-path. Value is the full name of the file
2276 found, or nil if not found. If PFD is nonnull store into *PFD a
2277 readable file descriptor for the file, opened in binary mode. If
2278 PFD is null, do not open the file. */
2281 x_find_image_fd (Lisp_Object file
, int *pfd
)
2283 Lisp_Object file_found
, search_path
;
2286 /* TODO I think this should use something like image-load-path
2287 instead. Unfortunately, that can contain non-string elements. */
2288 search_path
= Fcons (Fexpand_file_name (build_string ("images"),
2290 Vx_bitmap_file_path
);
2292 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2293 fd
= openp (search_path
, file
, Qnil
, &file_found
,
2294 pfd
? Qt
: make_number (R_OK
), false);
2295 if (fd
>= 0 || fd
== -2)
2297 file_found
= ENCODE_FILE (file_found
);
2300 /* The file exists locally, but has a file handler. (This
2301 happens, e.g., under Auto Image File Mode.) 'openp'
2302 didn't open the file, so we should, because the caller
2304 fd
= emacs_open (SSDATA (file_found
), O_RDONLY
| O_BINARY
, 0);
2307 else /* fd < 0, but not -2 */
2314 /* Find image file FILE. Look in data-directory/images, then
2315 x-bitmap-file-path. Value is the encoded full name of the file
2316 found, or nil if not found. */
2319 x_find_image_file (Lisp_Object file
)
2321 return x_find_image_fd (file
, 0);
2324 /* Read FILE into memory. Value is a pointer to a buffer allocated
2325 with xmalloc holding FILE's contents. Value is null if an error
2326 occurred. FD is a file descriptor open for reading FILE. Set
2327 *SIZE to the size of the file. */
2329 static unsigned char *
2330 slurp_file (int fd
, ptrdiff_t *size
)
2332 FILE *fp
= fdopen (fd
, "rb");
2334 unsigned char *buf
= NULL
;
2339 ptrdiff_t count
= SPECPDL_INDEX ();
2340 record_unwind_protect_ptr (fclose_unwind
, fp
);
2342 if (fstat (fileno (fp
), &st
) == 0
2343 && 0 <= st
.st_size
&& st
.st_size
< min (PTRDIFF_MAX
, SIZE_MAX
))
2345 /* Report an error if we read past the purported EOF.
2346 This can happen if the file grows as we read it. */
2347 ptrdiff_t buflen
= st
.st_size
;
2348 buf
= xmalloc (buflen
+ 1);
2349 if (fread (buf
, 1, buflen
+ 1, fp
) == buflen
)
2358 unbind_to (count
, Qnil
);
2366 /***********************************************************************
2368 ***********************************************************************/
2370 static bool xbm_load (struct frame
*f
, struct image
*img
);
2371 static bool xbm_image_p (Lisp_Object object
);
2372 static bool xbm_file_p (Lisp_Object
);
2375 /* Indices of image specification fields in xbm_format, below. */
2377 enum xbm_keyword_index
2395 /* Vector of image_keyword structures describing the format
2396 of valid XBM image specifications. */
2398 static const struct image_keyword xbm_format
[XBM_LAST
] =
2400 {":type", IMAGE_SYMBOL_VALUE
, 1},
2401 {":file", IMAGE_STRING_VALUE
, 0},
2402 {":width", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2403 {":height", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2404 {":data", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2405 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
2406 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
2407 {":ascent", IMAGE_ASCENT_VALUE
, 0},
2408 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
2409 {":relief", IMAGE_INTEGER_VALUE
, 0},
2410 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2411 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2412 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
2415 /* Structure describing the image type XBM. */
2417 static struct image_type xbm_type
=
2419 SYMBOL_INDEX (Qxbm
),
2427 /* Tokens returned from xbm_scan. */
2436 /* Return true if OBJECT is a valid XBM-type image specification.
2437 A valid specification is a list starting with the symbol `image'
2438 The rest of the list is a property list which must contain an
2441 If the specification specifies a file to load, it must contain
2442 an entry `:file FILENAME' where FILENAME is a string.
2444 If the specification is for a bitmap loaded from memory it must
2445 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2446 WIDTH and HEIGHT are integers > 0. DATA may be:
2448 1. a string large enough to hold the bitmap data, i.e. it must
2449 have a size >= (WIDTH + 7) / 8 * HEIGHT
2451 2. a bool-vector of size >= WIDTH * HEIGHT
2453 3. a vector of strings or bool-vectors, one for each line of the
2456 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2457 may not be specified in this case because they are defined in the
2460 Both the file and data forms may contain the additional entries
2461 `:background COLOR' and `:foreground COLOR'. If not present,
2462 foreground and background of the frame on which the image is
2463 displayed is used. */
2466 xbm_image_p (Lisp_Object object
)
2468 struct image_keyword kw
[XBM_LAST
];
2470 memcpy (kw
, xbm_format
, sizeof kw
);
2471 if (!parse_image_spec (object
, kw
, XBM_LAST
, Qxbm
))
2474 eassert (EQ (kw
[XBM_TYPE
].value
, Qxbm
));
2476 if (kw
[XBM_FILE
].count
)
2478 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_DATA
].count
)
2481 else if (kw
[XBM_DATA
].count
&& xbm_file_p (kw
[XBM_DATA
].value
))
2483 /* In-memory XBM file. */
2484 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_FILE
].count
)
2492 /* Entries for `:width', `:height' and `:data' must be present. */
2493 if (!kw
[XBM_WIDTH
].count
2494 || !kw
[XBM_HEIGHT
].count
2495 || !kw
[XBM_DATA
].count
)
2498 data
= kw
[XBM_DATA
].value
;
2499 width
= XFASTINT (kw
[XBM_WIDTH
].value
);
2500 height
= XFASTINT (kw
[XBM_HEIGHT
].value
);
2502 /* Check type of data, and width and height against contents of
2508 /* Number of elements of the vector must be >= height. */
2509 if (ASIZE (data
) < height
)
2512 /* Each string or bool-vector in data must be large enough
2513 for one line of the image. */
2514 for (i
= 0; i
< height
; ++i
)
2516 Lisp_Object elt
= AREF (data
, i
);
2521 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
)
2524 else if (BOOL_VECTOR_P (elt
))
2526 if (bool_vector_size (elt
) < width
)
2533 else if (STRINGP (data
))
2536 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
* height
)
2539 else if (BOOL_VECTOR_P (data
))
2541 if (bool_vector_size (data
) / height
< width
)
2552 /* Scan a bitmap file. FP is the stream to read from. Value is
2553 either an enumerator from enum xbm_token, or a character for a
2554 single-character token, or 0 at end of file. If scanning an
2555 identifier, store the lexeme of the identifier in SVAL. If
2556 scanning a number, store its value in *IVAL. */
2559 xbm_scan (unsigned char **s
, unsigned char *end
, char *sval
, int *ival
)
2565 /* Skip white space. */
2566 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
2571 else if (c_isdigit (c
))
2573 int value
= 0, digit
;
2575 if (c
== '0' && *s
< end
)
2578 if (c
== 'x' || c
== 'X')
2585 else if (c
>= 'a' && c
<= 'f')
2586 digit
= c
- 'a' + 10;
2587 else if (c
>= 'A' && c
<= 'F')
2588 digit
= c
- 'A' + 10;
2591 value
= 16 * value
+ digit
;
2594 else if (c_isdigit (c
))
2598 && (c
= *(*s
)++, c_isdigit (c
)))
2599 value
= 8 * value
+ c
- '0';
2606 && (c
= *(*s
)++, c_isdigit (c
)))
2607 value
= 10 * value
+ c
- '0';
2615 else if (c_isalpha (c
) || c
== '_')
2619 && (c
= *(*s
)++, (c_isalnum (c
) || c
== '_')))
2626 else if (c
== '/' && **s
== '*')
2628 /* C-style comment. */
2630 while (**s
&& (**s
!= '*' || *(*s
+ 1) != '/'))
2644 /* Create a Windows bitmap from X bitmap data. */
2646 w32_create_pixmap_from_bitmap_data (int width
, int height
, char *data
)
2648 static unsigned char swap_nibble
[16]
2649 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2650 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2651 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2652 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2654 unsigned char *bits
, *p
;
2657 w1
= (width
+ 7) / 8; /* nb of 8bits elt in X bitmap */
2658 w2
= ((width
+ 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2659 bits
= alloca (height
* w2
);
2660 memset (bits
, 0, height
* w2
);
2661 for (i
= 0; i
< height
; i
++)
2664 for (j
= 0; j
< w1
; j
++)
2666 /* Bitswap XBM bytes to match how Windows does things. */
2667 unsigned char c
= *data
++;
2668 *p
++ = (unsigned char)((swap_nibble
[c
& 0xf] << 4)
2669 | (swap_nibble
[(c
>>4) & 0xf]));
2672 bmp
= CreateBitmap (width
, height
, 1, 1, (char *) bits
);
2678 convert_mono_to_color_image (struct frame
*f
, struct image
*img
,
2679 COLORREF foreground
, COLORREF background
)
2681 HDC hdc
, old_img_dc
, new_img_dc
;
2682 HGDIOBJ old_prev
, new_prev
;
2685 hdc
= get_frame_dc (f
);
2686 old_img_dc
= CreateCompatibleDC (hdc
);
2687 new_img_dc
= CreateCompatibleDC (hdc
);
2688 new_pixmap
= CreateCompatibleBitmap (hdc
, img
->width
, img
->height
);
2689 release_frame_dc (f
, hdc
);
2690 old_prev
= SelectObject (old_img_dc
, img
->pixmap
);
2691 new_prev
= SelectObject (new_img_dc
, new_pixmap
);
2692 /* Windows convention for mono bitmaps is black = background,
2693 white = foreground. */
2694 SetTextColor (new_img_dc
, background
);
2695 SetBkColor (new_img_dc
, foreground
);
2697 BitBlt (new_img_dc
, 0, 0, img
->width
, img
->height
, old_img_dc
,
2700 SelectObject (old_img_dc
, old_prev
);
2701 SelectObject (new_img_dc
, new_prev
);
2702 DeleteDC (old_img_dc
);
2703 DeleteDC (new_img_dc
);
2704 DeleteObject (img
->pixmap
);
2705 if (new_pixmap
== 0)
2706 fprintf (stderr
, "Failed to convert image to color.\n");
2708 img
->pixmap
= new_pixmap
;
2711 #define XBM_BIT_SHUFFLE(b) (~(b))
2715 #define XBM_BIT_SHUFFLE(b) (b)
2717 #endif /* HAVE_NTGUI */
2721 Create_Pixmap_From_Bitmap_Data (struct frame
*f
, struct image
*img
, char *data
,
2722 RGB_PIXEL_COLOR fg
, RGB_PIXEL_COLOR bg
,
2723 bool non_default_colors
)
2727 = w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
, data
);
2729 /* If colors were specified, transfer the bitmap to a color one. */
2730 if (non_default_colors
)
2731 convert_mono_to_color_image (f
, img
, fg
, bg
);
2733 #elif defined (HAVE_NS)
2734 img
->pixmap
= ns_image_from_XBM (data
, img
->width
, img
->height
, fg
, bg
);
2738 (x_check_image_size (0, img
->width
, img
->height
)
2739 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f
),
2742 img
->width
, img
->height
,
2744 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)))
2746 #endif /* !HAVE_NTGUI && !HAVE_NS */
2751 /* Replacement for XReadBitmapFileData which isn't available under old
2752 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2753 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2754 the image. Return in *DATA the bitmap data allocated with xmalloc.
2755 Value is true if successful. DATA null means just test if
2756 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2757 inhibit the call to image_error when the image size is invalid (the
2758 bitmap remains unread). */
2761 xbm_read_bitmap_data (struct frame
*f
, unsigned char *contents
, unsigned char *end
,
2762 int *width
, int *height
, char **data
,
2763 bool inhibit_image_error
)
2765 unsigned char *s
= contents
;
2766 char buffer
[BUFSIZ
];
2769 int bytes_per_line
, i
, nbytes
;
2775 LA1 = xbm_scan (&s, end, buffer, &value)
2777 #define expect(TOKEN) \
2780 if (LA1 != (TOKEN)) \
2786 #define expect_ident(IDENT) \
2787 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2792 *width
= *height
= -1;
2795 LA1
= xbm_scan (&s
, end
, buffer
, &value
);
2797 /* Parse defines for width, height and hot-spots. */
2801 expect_ident ("define");
2802 expect (XBM_TK_IDENT
);
2804 if (LA1
== XBM_TK_NUMBER
)
2806 char *q
= strrchr (buffer
, '_');
2807 q
= q
? q
+ 1 : buffer
;
2808 if (strcmp (q
, "width") == 0)
2810 else if (strcmp (q
, "height") == 0)
2813 expect (XBM_TK_NUMBER
);
2816 if (!check_image_size (f
, *width
, *height
))
2818 if (!inhibit_image_error
)
2819 image_size_error ();
2822 else if (data
== NULL
)
2825 /* Parse bits. Must start with `static'. */
2826 expect_ident ("static");
2827 if (LA1
== XBM_TK_IDENT
)
2829 if (strcmp (buffer
, "unsigned") == 0)
2832 expect_ident ("char");
2834 else if (strcmp (buffer
, "short") == 0)
2838 if (*width
% 16 && *width
% 16 < 9)
2841 else if (strcmp (buffer
, "char") == 0)
2849 expect (XBM_TK_IDENT
);
2855 if (! x_check_image_size (0, *width
, *height
))
2857 if (!inhibit_image_error
)
2858 image_error ("Image too large (%dx%d)",
2859 make_number (*width
), make_number (*height
));
2862 bytes_per_line
= (*width
+ 7) / 8 + padding_p
;
2863 nbytes
= bytes_per_line
* *height
;
2864 p
= *data
= xmalloc (nbytes
);
2868 for (i
= 0; i
< nbytes
; i
+= 2)
2871 expect (XBM_TK_NUMBER
);
2873 *p
++ = XBM_BIT_SHUFFLE (val
);
2874 if (!padding_p
|| ((i
+ 2) % bytes_per_line
))
2875 *p
++ = XBM_BIT_SHUFFLE (value
>> 8);
2877 if (LA1
== ',' || LA1
== '}')
2885 for (i
= 0; i
< nbytes
; ++i
)
2888 expect (XBM_TK_NUMBER
);
2890 *p
++ = XBM_BIT_SHUFFLE (val
);
2892 if (LA1
== ',' || LA1
== '}')
2917 /* Load XBM image IMG which will be displayed on frame F from buffer
2918 CONTENTS. END is the end of the buffer. Value is true if
2922 xbm_load_image (struct frame
*f
, struct image
*img
, unsigned char *contents
,
2929 rc
= xbm_read_bitmap_data (f
, contents
, end
, &img
->width
, &img
->height
,
2933 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
2934 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
2935 bool non_default_colors
= 0;
2938 eassert (img
->width
> 0 && img
->height
> 0);
2940 /* Get foreground and background colors, maybe allocate colors. */
2941 value
= image_spec_value (img
->spec
, QCforeground
, NULL
);
2944 foreground
= x_alloc_image_color (f
, img
, value
, foreground
);
2945 non_default_colors
= 1;
2947 value
= image_spec_value (img
->spec
, QCbackground
, NULL
);
2950 background
= x_alloc_image_color (f
, img
, value
, background
);
2951 img
->background
= background
;
2952 img
->background_valid
= 1;
2953 non_default_colors
= 1;
2956 Create_Pixmap_From_Bitmap_Data (f
, img
, data
,
2957 foreground
, background
,
2958 non_default_colors
);
2961 if (img
->pixmap
== NO_PIXMAP
)
2963 x_clear_image (f
, img
);
2964 image_error ("Unable to create X pixmap for `%s'", img
->spec
);
2970 image_error ("Error loading XBM image `%s'", img
->spec
);
2976 /* Value is true if DATA looks like an in-memory XBM file. */
2979 xbm_file_p (Lisp_Object data
)
2982 return (STRINGP (data
)
2983 && xbm_read_bitmap_data (NULL
, SDATA (data
),
2984 (SDATA (data
) + SBYTES (data
)),
2989 /* Fill image IMG which is used on frame F with pixmap data. Value is
2990 true if successful. */
2993 xbm_load (struct frame
*f
, struct image
*img
)
2996 Lisp_Object file_name
;
2998 eassert (xbm_image_p (img
->spec
));
3000 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3001 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
3002 if (STRINGP (file_name
))
3005 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
3006 if (!STRINGP (file
))
3008 image_error ("Cannot find image file `%s'", file_name
);
3013 unsigned char *contents
= slurp_file (fd
, &size
);
3014 if (contents
== NULL
)
3016 image_error ("Error loading XBM image `%s'", file
);
3020 success_p
= xbm_load_image (f
, img
, contents
, contents
+ size
);
3025 struct image_keyword fmt
[XBM_LAST
];
3027 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
3028 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
3029 bool non_default_colors
= 0;
3032 bool in_memory_file_p
= 0;
3034 /* See if data looks like an in-memory XBM file. */
3035 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
3036 in_memory_file_p
= xbm_file_p (data
);
3038 /* Parse the image specification. */
3039 memcpy (fmt
, xbm_format
, sizeof fmt
);
3040 parsed_p
= parse_image_spec (img
->spec
, fmt
, XBM_LAST
, Qxbm
);
3043 /* Get specified width, and height. */
3044 if (!in_memory_file_p
)
3046 img
->width
= XFASTINT (fmt
[XBM_WIDTH
].value
);
3047 img
->height
= XFASTINT (fmt
[XBM_HEIGHT
].value
);
3048 eassert (img
->width
> 0 && img
->height
> 0);
3049 if (!check_image_size (f
, img
->width
, img
->height
))
3051 image_size_error ();
3056 /* Get foreground and background colors, maybe allocate colors. */
3057 if (fmt
[XBM_FOREGROUND
].count
3058 && STRINGP (fmt
[XBM_FOREGROUND
].value
))
3060 foreground
= x_alloc_image_color (f
, img
, fmt
[XBM_FOREGROUND
].value
,
3062 non_default_colors
= 1;
3065 if (fmt
[XBM_BACKGROUND
].count
3066 && STRINGP (fmt
[XBM_BACKGROUND
].value
))
3068 background
= x_alloc_image_color (f
, img
, fmt
[XBM_BACKGROUND
].value
,
3070 non_default_colors
= 1;
3073 if (in_memory_file_p
)
3074 success_p
= xbm_load_image (f
, img
, SDATA (data
),
3085 int nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3087 SAFE_NALLOCA (bits
, nbytes
, img
->height
);
3089 for (i
= 0; i
< img
->height
; ++i
, p
+= nbytes
)
3091 Lisp_Object line
= AREF (data
, i
);
3093 memcpy (p
, SDATA (line
), nbytes
);
3095 memcpy (p
, bool_vector_data (line
), nbytes
);
3098 else if (STRINGP (data
))
3099 bits
= SSDATA (data
);
3101 bits
= (char *) bool_vector_data (data
);
3107 /* Windows mono bitmaps are reversed compared with X. */
3108 invertedBits
= bits
;
3109 nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3110 SAFE_NALLOCA (bits
, nbytes
, img
->height
);
3111 for (i
= 0; i
< nbytes
; i
++)
3112 bits
[i
] = XBM_BIT_SHUFFLE (invertedBits
[i
]);
3115 /* Create the pixmap. */
3117 if (x_check_image_size (0, img
->width
, img
->height
))
3118 Create_Pixmap_From_Bitmap_Data (f
, img
, bits
,
3119 foreground
, background
,
3120 non_default_colors
);
3122 img
->pixmap
= NO_PIXMAP
;
3128 image_error ("Unable to create pixmap for XBM image `%s'",
3130 x_clear_image (f
, img
);
3142 /***********************************************************************
3144 ***********************************************************************/
3146 #if defined (HAVE_XPM) || defined (HAVE_NS)
3148 static bool xpm_image_p (Lisp_Object object
);
3149 static bool xpm_load (struct frame
*f
, struct image
*img
);
3151 #endif /* HAVE_XPM || HAVE_NS */
3155 /* Indicate to xpm.h that we don't have Xlib. */
3157 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3158 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3159 #define XColor xpm_XColor
3160 #define XImage xpm_XImage
3161 #define Display xpm_Display
3162 #define PIXEL_ALREADY_TYPEDEFED
3163 #include "X11/xpm.h"
3168 #undef PIXEL_ALREADY_TYPEDEFED
3170 #include "X11/xpm.h"
3171 #endif /* HAVE_NTGUI */
3172 #endif /* HAVE_XPM */
3174 #if defined (HAVE_XPM) || defined (HAVE_NS)
3176 /* Indices of image specification fields in xpm_format, below. */
3178 enum xpm_keyword_index
3194 /* Vector of image_keyword structures describing the format
3195 of valid XPM image specifications. */
3197 static const struct image_keyword xpm_format
[XPM_LAST
] =
3199 {":type", IMAGE_SYMBOL_VALUE
, 1},
3200 {":file", IMAGE_STRING_VALUE
, 0},
3201 {":data", IMAGE_STRING_VALUE
, 0},
3202 {":ascent", IMAGE_ASCENT_VALUE
, 0},
3203 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
3204 {":relief", IMAGE_INTEGER_VALUE
, 0},
3205 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3206 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3207 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3208 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3209 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
3212 #if defined HAVE_NTGUI && defined WINDOWSNT
3213 static bool init_xpm_functions (void);
3215 #define init_xpm_functions NULL
3218 /* Structure describing the image type XPM. */
3220 static struct image_type xpm_type
=
3222 SYMBOL_INDEX (Qxpm
),
3230 #ifdef HAVE_X_WINDOWS
3232 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3233 functions for allocating image colors. Our own functions handle
3234 color allocation failures more gracefully than the ones on the XPM
3238 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3239 #define ALLOC_XPM_COLORS
3241 #endif /* USE_CAIRO */
3242 #endif /* HAVE_X_WINDOWS */
3244 #ifdef ALLOC_XPM_COLORS
3246 static struct xpm_cached_color
*xpm_cache_color (struct frame
*, char *,
3249 /* An entry in a hash table used to cache color definitions of named
3250 colors. This cache is necessary to speed up XPM image loading in
3251 case we do color allocations ourselves. Without it, we would need
3252 a call to XParseColor per pixel in the image.
3254 FIXME Now that we're using x_parse_color and its cache, reevaluate
3255 the need for this caching layer. */
3257 struct xpm_cached_color
3259 /* Next in collision chain. */
3260 struct xpm_cached_color
*next
;
3262 /* Color definition (RGB and pixel color). */
3266 char name
[FLEXIBLE_ARRAY_MEMBER
];
3269 /* The hash table used for the color cache, and its bucket vector
3272 #define XPM_COLOR_CACHE_BUCKETS 1001
3273 static struct xpm_cached_color
**xpm_color_cache
;
3275 /* Initialize the color cache. */
3278 xpm_init_color_cache (struct frame
*f
, XpmAttributes
*attrs
)
3280 size_t nbytes
= XPM_COLOR_CACHE_BUCKETS
* sizeof *xpm_color_cache
;
3281 xpm_color_cache
= xzalloc (nbytes
);
3282 init_color_table ();
3284 if (attrs
->valuemask
& XpmColorSymbols
)
3289 for (i
= 0; i
< attrs
->numsymbols
; ++i
)
3290 if (x_parse_color (f
, attrs
->colorsymbols
[i
].value
, &color
))
3292 color
.pixel
= lookup_rgb_color (f
, color
.red
, color
.green
,
3294 xpm_cache_color (f
, attrs
->colorsymbols
[i
].name
, &color
, -1);
3299 /* Free the color cache. */
3302 xpm_free_color_cache (void)
3304 struct xpm_cached_color
*p
, *next
;
3307 for (i
= 0; i
< XPM_COLOR_CACHE_BUCKETS
; ++i
)
3308 for (p
= xpm_color_cache
[i
]; p
; p
= next
)
3314 xfree (xpm_color_cache
);
3315 xpm_color_cache
= NULL
;
3316 free_color_table ();
3319 /* Return the bucket index for color named COLOR_NAME in the color
3323 xpm_color_bucket (char *color_name
)
3325 EMACS_UINT hash
= hash_string (color_name
, strlen (color_name
));
3326 return hash
% XPM_COLOR_CACHE_BUCKETS
;
3330 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3331 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3334 static struct xpm_cached_color
*
3335 xpm_cache_color (struct frame
*f
, char *color_name
, XColor
*color
, int bucket
)
3338 struct xpm_cached_color
*p
;
3341 bucket
= xpm_color_bucket (color_name
);
3343 nbytes
= offsetof (struct xpm_cached_color
, name
) + strlen (color_name
) + 1;
3344 p
= xmalloc (nbytes
);
3345 strcpy (p
->name
, color_name
);
3347 p
->next
= xpm_color_cache
[bucket
];
3348 xpm_color_cache
[bucket
] = p
;
3352 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3353 return the cached definition in *COLOR. Otherwise, make a new
3354 entry in the cache and allocate the color. Value is false if color
3355 allocation failed. */
3358 xpm_lookup_color (struct frame
*f
, char *color_name
, XColor
*color
)
3360 struct xpm_cached_color
*p
;
3361 int h
= xpm_color_bucket (color_name
);
3363 for (p
= xpm_color_cache
[h
]; p
; p
= p
->next
)
3364 if (strcmp (p
->name
, color_name
) == 0)
3369 else if (x_parse_color (f
, color_name
, color
))
3371 color
->pixel
= lookup_rgb_color (f
, color
->red
, color
->green
,
3373 p
= xpm_cache_color (f
, color_name
, color
, h
);
3375 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3376 with transparency, and it's useful. */
3377 else if (strcmp ("opaque", color_name
) == 0)
3379 memset (color
, 0, sizeof (XColor
)); /* Is this necessary/correct? */
3380 color
->pixel
= FRAME_FOREGROUND_PIXEL (f
);
3381 p
= xpm_cache_color (f
, color_name
, color
, h
);
3388 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3389 CLOSURE is a pointer to the frame on which we allocate the
3390 color. Return in *COLOR the allocated color. Value is non-zero
3394 xpm_alloc_color (Display
*dpy
, Colormap cmap
, char *color_name
, XColor
*color
,
3397 return xpm_lookup_color (closure
, color_name
, color
);
3401 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3402 is a pointer to the frame on which we allocate the color. Value is
3403 non-zero if successful. */
3406 xpm_free_colors (Display
*dpy
, Colormap cmap
, Pixel
*pixels
, int npixels
, void *closure
)
3411 #endif /* ALLOC_XPM_COLORS */
3416 /* XPM library details. */
3418 DEF_DLL_FN (void, XpmFreeAttributes
, (XpmAttributes
*));
3419 DEF_DLL_FN (int, XpmCreateImageFromBuffer
,
3420 (Display
*, char *, xpm_XImage
**,
3421 xpm_XImage
**, XpmAttributes
*));
3422 DEF_DLL_FN (int, XpmReadFileToImage
,
3423 (Display
*, char *, xpm_XImage
**,
3424 xpm_XImage
**, XpmAttributes
*));
3425 DEF_DLL_FN (void, XImageFree
, (xpm_XImage
*));
3428 init_xpm_functions (void)
3432 if (!(library
= w32_delayed_load (Qxpm
)))
3435 LOAD_DLL_FN (library
, XpmFreeAttributes
);
3436 LOAD_DLL_FN (library
, XpmCreateImageFromBuffer
);
3437 LOAD_DLL_FN (library
, XpmReadFileToImage
);
3438 LOAD_DLL_FN (library
, XImageFree
);
3443 # undef XpmCreateImageFromBuffer
3444 # undef XpmFreeAttributes
3445 # undef XpmReadFileToImage
3447 # define XImageFree fn_XImageFree
3448 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3449 # define XpmFreeAttributes fn_XpmFreeAttributes
3450 # define XpmReadFileToImage fn_XpmReadFileToImage
3452 #endif /* WINDOWSNT */
3454 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3455 for XPM images. Such a list must consist of conses whose car and
3459 xpm_valid_color_symbols_p (Lisp_Object color_symbols
)
3461 while (CONSP (color_symbols
))
3463 Lisp_Object sym
= XCAR (color_symbols
);
3465 || !STRINGP (XCAR (sym
))
3466 || !STRINGP (XCDR (sym
)))
3468 color_symbols
= XCDR (color_symbols
);
3471 return NILP (color_symbols
);
3475 /* Value is true if OBJECT is a valid XPM image specification. */
3478 xpm_image_p (Lisp_Object object
)
3480 struct image_keyword fmt
[XPM_LAST
];
3481 memcpy (fmt
, xpm_format
, sizeof fmt
);
3482 return (parse_image_spec (object
, fmt
, XPM_LAST
, Qxpm
)
3483 /* Either `:file' or `:data' must be present. */
3484 && fmt
[XPM_FILE
].count
+ fmt
[XPM_DATA
].count
== 1
3485 /* Either no `:color-symbols' or it's a list of conses
3486 whose car and cdr are strings. */
3487 && (fmt
[XPM_COLOR_SYMBOLS
].count
== 0
3488 || xpm_valid_color_symbols_p (fmt
[XPM_COLOR_SYMBOLS
].value
)));
3491 #endif /* HAVE_XPM || HAVE_NS */
3493 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3495 x_create_bitmap_from_xpm_data (struct frame
*f
, const char **bits
)
3497 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
3500 XpmAttributes attrs
;
3501 Pixmap bitmap
, mask
;
3503 memset (&attrs
, 0, sizeof attrs
);
3505 attrs
.visual
= FRAME_X_VISUAL (f
);
3506 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3507 attrs
.valuemask
|= XpmVisual
;
3508 attrs
.valuemask
|= XpmColormap
;
3510 rc
= XpmCreatePixmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3511 (char **) bits
, &bitmap
, &mask
, &attrs
);
3512 if (rc
!= XpmSuccess
)
3514 XpmFreeAttributes (&attrs
);
3518 id
= x_allocate_bitmap_record (f
);
3519 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
3520 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
3521 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
3522 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
3523 dpyinfo
->bitmaps
[id
- 1].height
= attrs
.height
;
3524 dpyinfo
->bitmaps
[id
- 1].width
= attrs
.width
;
3525 dpyinfo
->bitmaps
[id
- 1].depth
= attrs
.depth
;
3526 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
3528 XpmFreeAttributes (&attrs
);
3531 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3533 /* Load image IMG which will be displayed on frame F. Value is
3534 true if successful. */
3539 xpm_load (struct frame
*f
, struct image
*img
)
3542 XpmAttributes attrs
;
3543 Lisp_Object specified_file
, color_symbols
;
3548 xpm_XImage
* xpm_image
= NULL
, * xpm_mask
= NULL
;
3549 #endif /* HAVE_NTGUI */
3551 /* Configure the XPM lib. Use the visual of frame F. Allocate
3552 close colors. Return colors allocated. */
3553 memset (&attrs
, 0, sizeof attrs
);
3556 attrs
.visual
= FRAME_X_VISUAL (f
);
3557 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3558 attrs
.valuemask
|= XpmVisual
;
3559 attrs
.valuemask
|= XpmColormap
;
3560 #endif /* HAVE_NTGUI */
3562 #ifdef ALLOC_XPM_COLORS
3563 /* Allocate colors with our own functions which handle
3564 failing color allocation more gracefully. */
3565 attrs
.color_closure
= f
;
3566 attrs
.alloc_color
= xpm_alloc_color
;
3567 attrs
.free_colors
= xpm_free_colors
;
3568 attrs
.valuemask
|= XpmAllocColor
| XpmFreeColors
| XpmColorClosure
;
3569 #else /* not ALLOC_XPM_COLORS */
3570 /* Let the XPM lib allocate colors. */
3571 attrs
.valuemask
|= XpmReturnAllocPixels
;
3572 #ifdef XpmAllocCloseColors
3573 attrs
.alloc_close_colors
= 1;
3574 attrs
.valuemask
|= XpmAllocCloseColors
;
3575 #else /* not XpmAllocCloseColors */
3576 attrs
.closeness
= 600;
3577 attrs
.valuemask
|= XpmCloseness
;
3578 #endif /* not XpmAllocCloseColors */
3579 #endif /* ALLOC_XPM_COLORS */
3581 /* If image specification contains symbolic color definitions, add
3582 these to `attrs'. */
3583 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
3584 if (CONSP (color_symbols
))
3587 XpmColorSymbol
*xpm_syms
;
3590 attrs
.valuemask
|= XpmColorSymbols
;
3592 /* Count number of symbols. */
3593 attrs
.numsymbols
= 0;
3594 for (tail
= color_symbols
; CONSP (tail
); tail
= XCDR (tail
))
3597 /* Allocate an XpmColorSymbol array. */
3598 SAFE_NALLOCA (xpm_syms
, 1, attrs
.numsymbols
);
3599 size
= attrs
.numsymbols
* sizeof *xpm_syms
;
3600 memset (xpm_syms
, 0, size
);
3601 attrs
.colorsymbols
= xpm_syms
;
3603 /* Fill the color symbol array. */
3604 for (tail
= color_symbols
, i
= 0;
3606 ++i
, tail
= XCDR (tail
))
3610 char *empty_string
= (char *) "";
3612 if (!CONSP (XCAR (tail
)))
3614 xpm_syms
[i
].name
= empty_string
;
3615 xpm_syms
[i
].value
= empty_string
;
3618 name
= XCAR (XCAR (tail
));
3619 color
= XCDR (XCAR (tail
));
3621 SAFE_ALLOCA_STRING (xpm_syms
[i
].name
, name
);
3623 xpm_syms
[i
].name
= empty_string
;
3624 if (STRINGP (color
))
3625 SAFE_ALLOCA_STRING (xpm_syms
[i
].value
, color
);
3627 xpm_syms
[i
].value
= empty_string
;
3631 /* Create a pixmap for the image, either from a file, or from a
3632 string buffer containing data in the same format as an XPM file. */
3633 #ifdef ALLOC_XPM_COLORS
3634 xpm_init_color_cache (f
, &attrs
);
3637 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
3641 HDC frame_dc
= get_frame_dc (f
);
3642 hdc
= CreateCompatibleDC (frame_dc
);
3643 release_frame_dc (f
, frame_dc
);
3645 #endif /* HAVE_NTGUI */
3647 if (STRINGP (specified_file
))
3649 Lisp_Object file
= x_find_image_file (specified_file
);
3650 if (!STRINGP (file
))
3652 image_error ("Cannot find image file `%s'", specified_file
);
3653 #ifdef ALLOC_XPM_COLORS
3654 xpm_free_color_cache ();
3660 file
= ENCODE_FILE (file
);
3663 /* FILE is encoded in UTF-8, but image libraries on Windows
3664 support neither UTF-8 nor UTF-16 encoded file names. So we
3665 need to re-encode it in ANSI. */
3666 file
= ansi_encode_filename (file
);
3668 /* XpmReadFileToPixmap is not available in the Windows port of
3669 libxpm. But XpmReadFileToImage almost does what we want. */
3670 rc
= XpmReadFileToImage (&hdc
, SDATA (file
),
3671 &xpm_image
, &xpm_mask
,
3674 rc
= XpmReadFileToImage (FRAME_X_DISPLAY (f
), SSDATA (file
),
3675 &img
->ximg
, &img
->mask_img
,
3677 #endif /* HAVE_NTGUI */
3681 Lisp_Object buffer
= image_spec_value (img
->spec
, QCdata
, NULL
);
3682 if (!STRINGP (buffer
))
3684 image_error ("Invalid image data `%s'", buffer
);
3685 #ifdef ALLOC_XPM_COLORS
3686 xpm_free_color_cache ();
3692 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3693 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3694 rc
= XpmCreateImageFromBuffer (&hdc
, SDATA (buffer
),
3695 &xpm_image
, &xpm_mask
,
3698 rc
= XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f
), SSDATA (buffer
),
3699 &img
->ximg
, &img
->mask_img
,
3701 #endif /* HAVE_NTGUI */
3705 // Load very specific Xpm:s.
3706 if (rc
== XpmSuccess
3707 && img
->ximg
->format
== ZPixmap
3708 && img
->ximg
->bits_per_pixel
== 32
3709 && (! img
->mask_img
|| img
->mask_img
->bits_per_pixel
== 1))
3711 int width
= img
->ximg
->width
;
3712 int height
= img
->ximg
->height
;
3713 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
3715 uint32_t *od
= (uint32_t *)data
;
3716 uint32_t *id
= (uint32_t *)img
->ximg
->data
;
3717 char *mid
= img
->mask_img
? img
->mask_img
->data
: 0;
3718 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
3720 for (i
= 0; i
< height
; ++i
)
3723 for (k
= 0; k
< width
; ++k
)
3725 int idx
= i
* img
->ximg
->bytes_per_line
/4 + k
;
3726 int maskidx
= mid
? i
* img
->mask_img
->bytes_per_line
+ k
/8 : 0;
3727 int mask
= mid
? mid
[maskidx
] & (1 << (k
% 8)) : 1;
3729 if (mask
) od
[idx
] = id
[idx
] + 0xff000000; // ff => full alpha
3730 else od
[idx
] = bgcolor
;
3734 create_cairo_image_surface (img
, data
, width
, height
);
3738 rc
= XpmFileInvalid
;
3739 x_clear_image (f
, img
);
3742 #ifdef HAVE_X_WINDOWS
3743 if (rc
== XpmSuccess
)
3745 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3746 img
->ximg
->width
, img
->ximg
->height
,
3748 if (img
->pixmap
== NO_PIXMAP
)
3750 x_clear_image (f
, img
);
3753 else if (img
->mask_img
)
3755 img
->mask
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3756 img
->mask_img
->width
,
3757 img
->mask_img
->height
,
3758 img
->mask_img
->depth
);
3759 if (img
->mask
== NO_PIXMAP
)
3761 x_clear_image (f
, img
);
3767 #endif /* ! USE_CAIRO */
3769 if (rc
== XpmSuccess
)
3771 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3772 img
->colors
= colors_in_color_table (&img
->ncolors
);
3773 #else /* not ALLOC_XPM_COLORS */
3777 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3778 plus some duplicate attributes. */
3779 if (xpm_image
&& xpm_image
->bitmap
)
3781 img
->pixmap
= xpm_image
->bitmap
;
3782 /* XImageFree in libXpm frees XImage struct without destroying
3783 the bitmap, which is what we want. */
3784 XImageFree (xpm_image
);
3786 if (xpm_mask
&& xpm_mask
->bitmap
)
3788 /* The mask appears to be inverted compared with what we expect.
3789 TODO: invert our expectations. See other places where we
3790 have to invert bits because our idea of masks is backwards. */
3792 old_obj
= SelectObject (hdc
, xpm_mask
->bitmap
);
3794 PatBlt (hdc
, 0, 0, xpm_mask
->width
, xpm_mask
->height
, DSTINVERT
);
3795 SelectObject (hdc
, old_obj
);
3797 img
->mask
= xpm_mask
->bitmap
;
3798 XImageFree (xpm_mask
);
3803 #endif /* HAVE_NTGUI */
3805 /* Remember allocated colors. */
3806 img
->colors
= xnmalloc (attrs
.nalloc_pixels
, sizeof *img
->colors
);
3807 img
->ncolors
= attrs
.nalloc_pixels
;
3808 for (i
= 0; i
< attrs
.nalloc_pixels
; ++i
)
3810 img
->colors
[i
] = attrs
.alloc_pixels
[i
];
3811 #ifdef DEBUG_X_COLORS
3812 register_color (img
->colors
[i
]);
3815 #endif /* not ALLOC_XPM_COLORS */
3817 img
->width
= attrs
.width
;
3818 img
->height
= attrs
.height
;
3819 eassert (img
->width
> 0 && img
->height
> 0);
3821 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3822 XpmFreeAttributes (&attrs
);
3824 #ifdef HAVE_X_WINDOWS
3825 /* Maybe fill in the background field while we have ximg handy. */
3826 IMAGE_BACKGROUND (img
, f
, img
->ximg
);
3828 /* Fill in the background_transparent field while we have the
3830 image_background_transparent (img
, f
, img
->mask_img
);
3837 #endif /* HAVE_NTGUI */
3842 image_error ("Error opening XPM file (%s)", img
->spec
);
3845 case XpmFileInvalid
:
3846 image_error ("Invalid XPM file (%s)", img
->spec
);
3850 image_error ("Out of memory (%s)", img
->spec
);
3853 case XpmColorFailed
:
3854 image_error ("Color allocation error (%s)", img
->spec
);
3858 image_error ("Unknown error (%s)", img
->spec
);
3863 #ifdef ALLOC_XPM_COLORS
3864 xpm_free_color_cache ();
3867 return rc
== XpmSuccess
;
3870 #endif /* HAVE_XPM */
3872 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3874 /* XPM support functions for NS where libxpm is not available.
3875 Only XPM version 3 (without any extensions) is supported. */
3877 static void xpm_put_color_table_v (Lisp_Object
, const unsigned char *,
3879 static Lisp_Object
xpm_get_color_table_v (Lisp_Object
,
3880 const unsigned char *, int);
3881 static void xpm_put_color_table_h (Lisp_Object
, const unsigned char *,
3883 static Lisp_Object
xpm_get_color_table_h (Lisp_Object
,
3884 const unsigned char *, int);
3886 /* Tokens returned from xpm_scan. */
3895 /* Scan an XPM data and return a character (< 256) or a token defined
3896 by enum xpm_token above. *S and END are the start (inclusive) and
3897 the end (exclusive) addresses of the data, respectively. Advance
3898 *S while scanning. If token is either XPM_TK_IDENT or
3899 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3900 length of the corresponding token, respectively. */
3903 xpm_scan (const unsigned char **s
,
3904 const unsigned char *end
,
3905 const unsigned char **beg
,
3912 /* Skip white-space. */
3913 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
3916 /* gnus-pointer.xpm uses '-' in its identifier.
3917 sb-dir-plus.xpm uses '+' in its identifier. */
3918 if (c_isalpha (c
) || c
== '_' || c
== '-' || c
== '+')
3922 && (c
= **s
, c_isalnum (c
)
3923 || c
== '_' || c
== '-' || c
== '+'))
3926 return XPM_TK_IDENT
;
3931 while (*s
< end
&& **s
!= '"')
3936 return XPM_TK_STRING
;
3940 if (*s
< end
&& **s
== '*')
3942 /* C-style comment. */
3946 while (*s
< end
&& *(*s
)++ != '*')
3949 while (*s
< end
&& **s
!= '/');
3963 /* Functions for color table lookup in XPM data. A key is a string
3964 specifying the color of each pixel in XPM data. A value is either
3965 an integer that specifies a pixel color, Qt that specifies
3966 transparency, or Qnil for the unspecified color. If the length of
3967 the key string is one, a vector is used as a table. Otherwise, a
3968 hash table is used. */
3971 xpm_make_color_table_v (void (**put_func
) (Lisp_Object
,
3972 const unsigned char *,
3975 Lisp_Object (**get_func
) (Lisp_Object
,
3976 const unsigned char *,
3979 *put_func
= xpm_put_color_table_v
;
3980 *get_func
= xpm_get_color_table_v
;
3981 return Fmake_vector (make_number (256), Qnil
);
3985 xpm_put_color_table_v (Lisp_Object color_table
,
3986 const unsigned char *chars_start
,
3990 ASET (color_table
, *chars_start
, color
);
3994 xpm_get_color_table_v (Lisp_Object color_table
,
3995 const unsigned char *chars_start
,
3998 return AREF (color_table
, *chars_start
);
4002 xpm_make_color_table_h (void (**put_func
) (Lisp_Object
,
4003 const unsigned char *,
4006 Lisp_Object (**get_func
) (Lisp_Object
,
4007 const unsigned char *,
4010 *put_func
= xpm_put_color_table_h
;
4011 *get_func
= xpm_get_color_table_h
;
4012 return make_hash_table (hashtest_equal
, make_number (DEFAULT_HASH_SIZE
),
4013 make_float (DEFAULT_REHASH_SIZE
),
4014 make_float (DEFAULT_REHASH_THRESHOLD
),
4019 xpm_put_color_table_h (Lisp_Object color_table
,
4020 const unsigned char *chars_start
,
4024 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4025 EMACS_UINT hash_code
;
4026 Lisp_Object chars
= make_unibyte_string (chars_start
, chars_len
);
4028 hash_lookup (table
, chars
, &hash_code
);
4029 hash_put (table
, chars
, color
, hash_code
);
4033 xpm_get_color_table_h (Lisp_Object color_table
,
4034 const unsigned char *chars_start
,
4037 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
4039 hash_lookup (table
, make_unibyte_string (chars_start
, chars_len
), NULL
);
4041 return i
>= 0 ? HASH_VALUE (table
, i
) : Qnil
;
4044 enum xpm_color_key
{
4052 static const char xpm_color_key_strings
[][4] = {"s", "m", "g4", "g", "c"};
4055 xpm_str_to_color_key (const char *s
)
4059 for (i
= 0; i
< ARRAYELTS (xpm_color_key_strings
); i
++)
4060 if (strcmp (xpm_color_key_strings
[i
], s
) == 0)
4066 xpm_load_image (struct frame
*f
,
4068 const unsigned char *contents
,
4069 const unsigned char *end
)
4071 const unsigned char *s
= contents
, *beg
, *str
;
4072 unsigned char buffer
[BUFSIZ
];
4073 int width
, height
, x
, y
;
4074 int num_colors
, chars_per_pixel
;
4077 void (*put_color_table
) (Lisp_Object
, const unsigned char *, int, Lisp_Object
);
4078 Lisp_Object (*get_color_table
) (Lisp_Object
, const unsigned char *, int);
4079 Lisp_Object frame
, color_symbols
, color_table
;
4081 bool have_mask
= false;
4082 XImagePtr ximg
= NULL
, mask_img
= NULL
;
4085 LA1 = xpm_scan (&s, end, &beg, &len)
4087 #define expect(TOKEN) \
4090 if (LA1 != (TOKEN)) \
4096 #define expect_ident(IDENT) \
4097 if (LA1 == XPM_TK_IDENT \
4098 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4103 if (!(end
- s
>= 9 && memcmp (s
, "/* XPM */", 9) == 0))
4107 expect_ident ("static");
4108 expect_ident ("char");
4110 expect (XPM_TK_IDENT
);
4115 expect (XPM_TK_STRING
);
4118 memcpy (buffer
, beg
, len
);
4120 if (sscanf (buffer
, "%d %d %d %d", &width
, &height
,
4121 &num_colors
, &chars_per_pixel
) != 4
4122 || width
<= 0 || height
<= 0
4123 || num_colors
<= 0 || chars_per_pixel
<= 0)
4126 if (!check_image_size (f
, width
, height
))
4128 image_size_error ();
4132 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0)
4134 || !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
4139 image_error ("Image too large");
4145 XSETFRAME (frame
, f
);
4146 if (!NILP (Fxw_display_color_p (frame
)))
4147 best_key
= XPM_COLOR_KEY_C
;
4148 else if (!NILP (Fx_display_grayscale_p (frame
)))
4149 best_key
= (XFASTINT (Fx_display_planes (frame
)) > 2
4150 ? XPM_COLOR_KEY_G
: XPM_COLOR_KEY_G4
);
4152 best_key
= XPM_COLOR_KEY_M
;
4154 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
4155 if (chars_per_pixel
== 1)
4156 color_table
= xpm_make_color_table_v (&put_color_table
,
4159 color_table
= xpm_make_color_table_h (&put_color_table
,
4162 while (num_colors
-- > 0)
4164 char *color
, *max_color
;
4165 int key
, next_key
, max_key
= 0;
4166 Lisp_Object symbol_color
= Qnil
, color_val
;
4169 expect (XPM_TK_STRING
);
4170 if (len
<= chars_per_pixel
|| len
>= BUFSIZ
+ chars_per_pixel
)
4172 memcpy (buffer
, beg
+ chars_per_pixel
, len
- chars_per_pixel
);
4173 buffer
[len
- chars_per_pixel
] = '\0';
4175 str
= strtok (buffer
, " \t");
4178 key
= xpm_str_to_color_key (str
);
4183 color
= strtok (NULL
, " \t");
4187 while ((str
= strtok (NULL
, " \t")) != NULL
)
4189 next_key
= xpm_str_to_color_key (str
);
4192 color
[strlen (color
)] = ' ';
4195 if (key
== XPM_COLOR_KEY_S
)
4197 if (NILP (symbol_color
))
4198 symbol_color
= build_string (color
);
4200 else if (max_key
< key
&& key
<= best_key
)
4210 if (!NILP (color_symbols
) && !NILP (symbol_color
))
4212 Lisp_Object specified_color
= Fassoc (symbol_color
, color_symbols
);
4214 if (CONSP (specified_color
) && STRINGP (XCDR (specified_color
)))
4216 if (xstrcasecmp (SSDATA (XCDR (specified_color
)), "None") == 0)
4218 else if (x_defined_color (f
, SSDATA (XCDR (specified_color
)),
4220 color_val
= make_number (cdef
.pixel
);
4223 if (NILP (color_val
) && max_key
> 0)
4225 if (xstrcasecmp (max_color
, "None") == 0)
4227 else if (x_defined_color (f
, max_color
, &cdef
, 0))
4228 color_val
= make_number (cdef
.pixel
);
4230 if (!NILP (color_val
))
4231 (*put_color_table
) (color_table
, beg
, chars_per_pixel
, color_val
);
4236 for (y
= 0; y
< height
; y
++)
4238 expect (XPM_TK_STRING
);
4240 if (len
< width
* chars_per_pixel
)
4242 for (x
= 0; x
< width
; x
++, str
+= chars_per_pixel
)
4244 Lisp_Object color_val
=
4245 (*get_color_table
) (color_table
, str
, chars_per_pixel
);
4247 XPutPixel (ximg
, x
, y
,
4248 (INTEGERP (color_val
) ? XINT (color_val
)
4249 : FRAME_FOREGROUND_PIXEL (f
)));
4251 XPutPixel (mask_img
, x
, y
,
4252 (!EQ (color_val
, Qt
) ? PIX_MASK_DRAW
4253 : (have_mask
= true, PIX_MASK_RETAIN
)));
4255 if (EQ (color_val
, Qt
))
4256 ns_set_alpha (ximg
, x
, y
, 0);
4264 img
->height
= height
;
4266 /* Maybe fill in the background field while we have ximg handy. */
4267 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
4268 IMAGE_BACKGROUND (img
, f
, ximg
);
4270 image_put_x_image (f
, img
, ximg
, 0);
4274 /* Fill in the background_transparent field while we have the
4276 image_background_transparent (img
, f
, mask_img
);
4278 image_put_x_image (f
, img
, mask_img
, 1);
4282 x_destroy_x_image (mask_img
);
4283 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4289 image_error ("Invalid XPM file (%s)", img
->spec
);
4290 x_destroy_x_image (ximg
);
4291 x_destroy_x_image (mask_img
);
4292 x_clear_image (f
, img
);
4301 xpm_load (struct frame
*f
,
4305 Lisp_Object file_name
;
4307 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4308 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
4309 if (STRINGP (file_name
))
4312 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
4313 if (!STRINGP (file
))
4315 image_error ("Cannot find image file `%s'", file_name
);
4320 unsigned char *contents
= slurp_file (fd
, &size
);
4321 if (contents
== NULL
)
4323 image_error ("Error loading XPM image `%s'", file
);
4327 success_p
= xpm_load_image (f
, img
, contents
, contents
+ size
);
4334 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
4335 if (!STRINGP (data
))
4337 image_error ("Invalid image data `%s'", data
);
4340 success_p
= xpm_load_image (f
, img
, SDATA (data
),
4341 SDATA (data
) + SBYTES (data
));
4347 #endif /* HAVE_NS && !HAVE_XPM */
4351 /***********************************************************************
4353 ***********************************************************************/
4355 #ifdef COLOR_TABLE_SUPPORT
4357 /* An entry in the color table mapping an RGB color to a pixel color. */
4362 unsigned long pixel
;
4364 /* Next in color table collision list. */
4365 struct ct_color
*next
;
4368 /* The bucket vector size to use. Must be prime. */
4372 /* Value is a hash of the RGB color given by R, G, and B. */
4375 ct_hash_rgb (unsigned r
, unsigned g
, unsigned b
)
4377 return (r
<< 16) ^ (g
<< 8) ^ b
;
4380 /* The color hash table. */
4382 static struct ct_color
**ct_table
;
4384 /* Number of entries in the color table. */
4386 static int ct_colors_allocated
;
4389 ct_colors_allocated_max
=
4391 min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof (unsigned long))
4394 /* Initialize the color table. */
4397 init_color_table (void)
4399 int size
= CT_SIZE
* sizeof (*ct_table
);
4400 ct_table
= xzalloc (size
);
4401 ct_colors_allocated
= 0;
4405 /* Free memory associated with the color table. */
4408 free_color_table (void)
4411 struct ct_color
*p
, *next
;
4413 for (i
= 0; i
< CT_SIZE
; ++i
)
4414 for (p
= ct_table
[i
]; p
; p
= next
)
4425 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4426 entry for that color already is in the color table, return the
4427 pixel color of that entry. Otherwise, allocate a new color for R,
4428 G, B, and make an entry in the color table. */
4430 static unsigned long
4431 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4433 unsigned hash
= ct_hash_rgb (r
, g
, b
);
4434 int i
= hash
% CT_SIZE
;
4436 Display_Info
*dpyinfo
;
4438 /* Handle TrueColor visuals specially, which improves performance by
4439 two orders of magnitude. Freeing colors on TrueColor visuals is
4440 a nop, and pixel colors specify RGB values directly. See also
4441 the Xlib spec, chapter 3.1. */
4442 dpyinfo
= FRAME_DISPLAY_INFO (f
);
4443 if (dpyinfo
->red_bits
> 0)
4445 /* Apply gamma-correction like normal color allocation does. */
4449 color
.red
= r
, color
.green
= g
, color
.blue
= b
;
4450 gamma_correct (f
, &color
);
4451 r
= color
.red
, g
= color
.green
, b
= color
.blue
;
4454 return x_make_truecolor_pixel (dpyinfo
, r
, g
, b
);
4457 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4458 if (p
->r
== r
&& p
->g
== g
&& p
->b
== b
)
4464 #ifdef HAVE_X_WINDOWS
4472 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4473 return FRAME_FOREGROUND_PIXEL (f
);
4475 #ifdef HAVE_X_WINDOWS
4480 cmap
= FRAME_X_COLORMAP (f
);
4481 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4484 ++ct_colors_allocated
;
4485 p
= xmalloc (sizeof *p
);
4489 p
->pixel
= color
.pixel
;
4490 p
->next
= ct_table
[i
];
4494 return FRAME_FOREGROUND_PIXEL (f
);
4498 color
= PALETTERGB (r
, g
, b
);
4500 color
= RGB_TO_ULONG (r
, g
, b
);
4501 #endif /* HAVE_NTGUI */
4502 ++ct_colors_allocated
;
4503 p
= xmalloc (sizeof *p
);
4508 p
->next
= ct_table
[i
];
4510 #endif /* HAVE_X_WINDOWS */
4518 /* Look up pixel color PIXEL which is used on frame F in the color
4519 table. If not already present, allocate it. Value is PIXEL. */
4521 static unsigned long
4522 lookup_pixel_color (struct frame
*f
, unsigned long pixel
)
4524 int i
= pixel
% CT_SIZE
;
4527 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4528 if (p
->pixel
== pixel
)
4537 if (ct_colors_allocated
>= ct_colors_allocated_max
)
4538 return FRAME_FOREGROUND_PIXEL (f
);
4540 #ifdef HAVE_X_WINDOWS
4541 cmap
= FRAME_X_COLORMAP (f
);
4542 color
.pixel
= pixel
;
4543 x_query_color (f
, &color
);
4544 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4547 cmap
= DefaultColormapOfScreen (FRAME_X_SCREEN (f
));
4548 color
.pixel
= pixel
;
4549 XQueryColor (NULL
, cmap
, &color
);
4550 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4552 #endif /* HAVE_X_WINDOWS */
4556 ++ct_colors_allocated
;
4558 p
= xmalloc (sizeof *p
);
4563 p
->next
= ct_table
[i
];
4567 return FRAME_FOREGROUND_PIXEL (f
);
4573 /* Value is a vector of all pixel colors contained in the color table,
4574 allocated via xmalloc. Set *N to the number of colors. */
4576 static unsigned long *
4577 colors_in_color_table (int *n
)
4581 unsigned long *colors
;
4583 if (ct_colors_allocated
== 0)
4590 colors
= xmalloc (ct_colors_allocated
* sizeof *colors
);
4591 *n
= ct_colors_allocated
;
4593 for (i
= j
= 0; i
< CT_SIZE
; ++i
)
4594 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4595 colors
[j
++] = p
->pixel
;
4601 #else /* COLOR_TABLE_SUPPORT */
4603 static unsigned long
4604 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4606 unsigned long pixel
;
4609 pixel
= PALETTERGB (r
>> 8, g
>> 8, b
>> 8);
4610 #endif /* HAVE_NTGUI */
4613 pixel
= RGB_TO_ULONG (r
>> 8, g
>> 8, b
>> 8);
4614 #endif /* HAVE_NS */
4619 init_color_table (void)
4622 #endif /* COLOR_TABLE_SUPPORT */
4625 /***********************************************************************
4627 ***********************************************************************/
4629 /* Edge detection matrices for different edge-detection
4632 static int emboss_matrix
[9] = {
4634 2, -1, 0, /* y - 1 */
4636 0, 1, -2 /* y + 1 */
4639 static int laplace_matrix
[9] = {
4641 1, 0, 0, /* y - 1 */
4643 0, 0, -1 /* y + 1 */
4646 /* Value is the intensity of the color whose red/green/blue values
4649 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4652 /* On frame F, return an array of XColor structures describing image
4653 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4654 means also fill the red/green/blue members of the XColor
4655 structures. Value is a pointer to the array of XColors structures,
4656 allocated with xmalloc; it must be freed by the caller. */
4659 x_to_xcolors (struct frame
*f
, struct image
*img
, bool rgb_p
)
4663 XImagePtr_or_DC ximg
;
4666 #endif /* HAVE_NTGUI */
4668 if (img
->height
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *colors
/ img
->width
)
4669 memory_full (SIZE_MAX
);
4670 colors
= xmalloc (sizeof *colors
* img
->width
* img
->height
);
4672 /* Get the X image or create a memory device context for IMG. */
4673 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4675 /* Fill the `pixel' members of the XColor array. I wished there
4676 were an easy and portable way to circumvent XGetPixel. */
4678 for (y
= 0; y
< img
->height
; ++y
)
4680 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4682 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4683 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4685 x_query_colors (f
, row
, img
->width
);
4689 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4691 /* W32_TODO: palette support needed here? */
4692 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4695 p
->red
= RED16_FROM_ULONG (p
->pixel
);
4696 p
->green
= GREEN16_FROM_ULONG (p
->pixel
);
4697 p
->blue
= BLUE16_FROM_ULONG (p
->pixel
);
4700 #endif /* HAVE_X_WINDOWS */
4703 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
4710 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4711 created with CreateDIBSection, with the pointer to the bit values
4712 stored in ximg->data. */
4715 XPutPixel (XImagePtr ximg
, int x
, int y
, COLORREF color
)
4717 int width
= ximg
->info
.bmiHeader
.biWidth
;
4718 unsigned char * pixel
;
4720 /* True color images. */
4721 if (ximg
->info
.bmiHeader
.biBitCount
== 24)
4723 int rowbytes
= width
* 3;
4724 /* Ensure scanlines are aligned on 4 byte boundaries. */
4726 rowbytes
+= 4 - (rowbytes
% 4);
4728 pixel
= ximg
->data
+ y
* rowbytes
+ x
* 3;
4729 /* Windows bitmaps are in BGR order. */
4730 *pixel
= GetBValue (color
);
4731 *(pixel
+ 1) = GetGValue (color
);
4732 *(pixel
+ 2) = GetRValue (color
);
4734 /* Monochrome images. */
4735 else if (ximg
->info
.bmiHeader
.biBitCount
== 1)
4737 int rowbytes
= width
/ 8;
4738 /* Ensure scanlines are aligned on 4 byte boundaries. */
4740 rowbytes
+= 4 - (rowbytes
% 4);
4741 pixel
= ximg
->data
+ y
* rowbytes
+ x
/ 8;
4742 /* Filter out palette info. */
4743 if (color
& 0x00ffffff)
4744 *pixel
= *pixel
| (1 << x
% 8);
4746 *pixel
= *pixel
& ~(1 << x
% 8);
4749 image_error ("XPutPixel: palette image not supported");
4752 #endif /* HAVE_NTGUI */
4754 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4755 RGB members are set. F is the frame on which this all happens.
4756 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4759 x_from_xcolors (struct frame
*f
, struct image
*img
, XColor
*colors
)
4762 XImagePtr oimg
= NULL
;
4765 init_color_table ();
4767 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_COLORS
);
4768 image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 0,
4771 for (y
= 0; y
< img
->height
; ++y
)
4772 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4774 unsigned long pixel
;
4775 pixel
= lookup_rgb_color (f
, p
->red
, p
->green
, p
->blue
);
4776 XPutPixel (oimg
, x
, y
, pixel
);
4781 image_put_x_image (f
, img
, oimg
, 0);
4782 #ifdef COLOR_TABLE_SUPPORT
4783 img
->colors
= colors_in_color_table (&img
->ncolors
);
4784 free_color_table ();
4785 #endif /* COLOR_TABLE_SUPPORT */
4789 /* On frame F, perform edge-detection on image IMG.
4791 MATRIX is a nine-element array specifying the transformation
4792 matrix. See emboss_matrix for an example.
4794 COLOR_ADJUST is a color adjustment added to each pixel of the
4798 x_detect_edges (struct frame
*f
, struct image
*img
, int *matrix
, int color_adjust
)
4800 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4804 for (i
= sum
= 0; i
< 9; ++i
)
4805 sum
+= eabs (matrix
[i
]);
4807 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4809 if (img
->height
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *new / img
->width
)
4810 memory_full (SIZE_MAX
);
4811 new = xmalloc (sizeof *new * img
->width
* img
->height
);
4813 for (y
= 0; y
< img
->height
; ++y
)
4815 p
= COLOR (new, 0, y
);
4816 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4817 p
= COLOR (new, img
->width
- 1, y
);
4818 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4821 for (x
= 1; x
< img
->width
- 1; ++x
)
4823 p
= COLOR (new, x
, 0);
4824 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4825 p
= COLOR (new, x
, img
->height
- 1);
4826 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4829 for (y
= 1; y
< img
->height
- 1; ++y
)
4831 p
= COLOR (new, 1, y
);
4833 for (x
= 1; x
< img
->width
- 1; ++x
, ++p
)
4835 int r
, g
, b
, yy
, xx
;
4838 for (yy
= y
- 1; yy
< y
+ 2; ++yy
)
4839 for (xx
= x
- 1; xx
< x
+ 2; ++xx
, ++i
)
4842 XColor
*t
= COLOR (colors
, xx
, yy
);
4843 r
+= matrix
[i
] * t
->red
;
4844 g
+= matrix
[i
] * t
->green
;
4845 b
+= matrix
[i
] * t
->blue
;
4848 r
= (r
/ sum
+ color_adjust
) & 0xffff;
4849 g
= (g
/ sum
+ color_adjust
) & 0xffff;
4850 b
= (b
/ sum
+ color_adjust
) & 0xffff;
4851 p
->red
= p
->green
= p
->blue
= COLOR_INTENSITY (r
, g
, b
);
4856 x_from_xcolors (f
, img
, new);
4862 /* Perform the pre-defined `emboss' edge-detection on image IMG
4866 x_emboss (struct frame
*f
, struct image
*img
)
4868 x_detect_edges (f
, img
, emboss_matrix
, 0xffff / 2);
4872 /* Transform image IMG which is used on frame F with a Laplace
4873 edge-detection algorithm. The result is an image that can be used
4874 to draw disabled buttons, for example. */
4877 x_laplace (struct frame
*f
, struct image
*img
)
4879 x_detect_edges (f
, img
, laplace_matrix
, 45000);
4883 /* Perform edge-detection on image IMG on frame F, with specified
4884 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4886 MATRIX must be either
4888 - a list of at least 9 numbers in row-major form
4889 - a vector of at least 9 numbers
4891 COLOR_ADJUST nil means use a default; otherwise it must be a
4895 x_edge_detection (struct frame
*f
, struct image
*img
, Lisp_Object matrix
,
4896 Lisp_Object color_adjust
)
4904 i
< 9 && CONSP (matrix
) && NUMBERP (XCAR (matrix
));
4905 ++i
, matrix
= XCDR (matrix
))
4906 trans
[i
] = XFLOATINT (XCAR (matrix
));
4908 else if (VECTORP (matrix
) && ASIZE (matrix
) >= 9)
4910 for (i
= 0; i
< 9 && NUMBERP (AREF (matrix
, i
)); ++i
)
4911 trans
[i
] = XFLOATINT (AREF (matrix
, i
));
4914 if (NILP (color_adjust
))
4915 color_adjust
= make_number (0xffff / 2);
4917 if (i
== 9 && NUMBERP (color_adjust
))
4918 x_detect_edges (f
, img
, trans
, XFLOATINT (color_adjust
));
4922 /* Transform image IMG on frame F so that it looks disabled. */
4925 x_disable_image (struct frame
*f
, struct image
*img
)
4927 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
4929 int n_planes
= dpyinfo
->n_planes
* dpyinfo
->n_cbits
;
4931 int n_planes
= dpyinfo
->n_planes
;
4932 #endif /* HAVE_NTGUI */
4936 /* Color (or grayscale). Convert to gray, and equalize. Just
4937 drawing such images with a stipple can look very odd, so
4938 we're using this method instead. */
4939 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4941 const int h
= 15000;
4942 const int l
= 30000;
4944 for (p
= colors
, end
= colors
+ img
->width
* img
->height
;
4948 int i
= COLOR_INTENSITY (p
->red
, p
->green
, p
->blue
);
4949 int i2
= (0xffff - h
- l
) * i
/ 0xffff + l
;
4950 p
->red
= p
->green
= p
->blue
= i2
;
4953 x_from_xcolors (f
, img
, colors
);
4956 /* Draw a cross over the disabled image, if we must or if we
4958 if (n_planes
< 2 || cross_disabled_images
)
4961 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4963 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4965 Display
*dpy
= FRAME_X_DISPLAY (f
);
4968 image_sync_to_pixmaps (f
, img
);
4969 gc
= XCreateGC (dpy
, img
->pixmap
, 0, NULL
);
4970 XSetForeground (dpy
, gc
, BLACK_PIX_DEFAULT (f
));
4971 XDrawLine (dpy
, img
->pixmap
, gc
, 0, 0,
4972 img
->width
- 1, img
->height
- 1);
4973 XDrawLine (dpy
, img
->pixmap
, gc
, 0, img
->height
- 1,
4979 gc
= XCreateGC (dpy
, img
->mask
, 0, NULL
);
4980 XSetForeground (dpy
, gc
, MaskForeground (f
));
4981 XDrawLine (dpy
, img
->mask
, gc
, 0, 0,
4982 img
->width
- 1, img
->height
- 1);
4983 XDrawLine (dpy
, img
->mask
, gc
, 0, img
->height
- 1,
4987 #endif /* !HAVE_NS */
4992 hdc
= get_frame_dc (f
);
4993 bmpdc
= CreateCompatibleDC (hdc
);
4994 release_frame_dc (f
, hdc
);
4996 prev
= SelectObject (bmpdc
, img
->pixmap
);
4998 SetTextColor (bmpdc
, BLACK_PIX_DEFAULT (f
));
4999 MoveToEx (bmpdc
, 0, 0, NULL
);
5000 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
5001 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
5002 LineTo (bmpdc
, img
->width
- 1, 0);
5006 SelectObject (bmpdc
, img
->mask
);
5007 SetTextColor (bmpdc
, WHITE_PIX_DEFAULT (f
));
5008 MoveToEx (bmpdc
, 0, 0, NULL
);
5009 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
5010 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
5011 LineTo (bmpdc
, img
->width
- 1, 0);
5013 SelectObject (bmpdc
, prev
);
5015 #endif /* HAVE_NTGUI */
5020 /* Build a mask for image IMG which is used on frame F. FILE is the
5021 name of an image file, for error messages. HOW determines how to
5022 determine the background color of IMG. If it is a list '(R G B)',
5023 with R, G, and B being integers >= 0, take that as the color of the
5024 background. Otherwise, determine the background color of IMG
5028 x_build_heuristic_mask (struct frame
*f
, struct image
*img
, Lisp_Object how
)
5030 XImagePtr_or_DC ximg
;
5037 #endif /* HAVE_NTGUI */
5039 bool use_img_background
;
5040 unsigned long bg
= 0;
5043 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
5047 /* Create an image and pixmap serving as mask. */
5048 if (! image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 1,
5051 #endif /* !HAVE_NS */
5053 /* Create the bit array serving as mask. */
5054 row_width
= (img
->width
+ 7) / 8;
5055 mask_img
= xzalloc (row_width
* img
->height
);
5056 #endif /* HAVE_NTGUI */
5058 /* Get the X image or create a memory device context for IMG. */
5059 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
5061 /* Determine the background color of ximg. If HOW is `(R G B)'
5062 take that as color. Otherwise, use the image's background color. */
5063 use_img_background
= 1;
5069 for (i
= 0; i
< 3 && CONSP (how
) && NATNUMP (XCAR (how
)); ++i
)
5071 rgb
[i
] = XFASTINT (XCAR (how
)) & 0xffff;
5075 if (i
== 3 && NILP (how
))
5077 char color_name
[30];
5078 sprintf (color_name
, "#%04x%04x%04x",
5079 rgb
[0] + 0u, rgb
[1] + 0u, rgb
[2] + 0u);
5082 0x00ffffff & /* Filter out palette info. */
5083 #endif /* HAVE_NTGUI */
5084 x_alloc_image_color (f
, img
, build_string (color_name
), 0));
5085 use_img_background
= 0;
5089 if (use_img_background
)
5090 bg
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
5092 /* Set all bits in mask_img to 1 whose color in ximg is different
5093 from the background color bg. */
5095 for (y
= 0; y
< img
->height
; ++y
)
5096 for (x
= 0; x
< img
->width
; ++x
)
5098 XPutPixel (mask_img
, x
, y
, (XGetPixel (ximg
, x
, y
) != bg
5099 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
));
5101 if (XGetPixel (ximg
, x
, y
) == bg
)
5102 ns_set_alpha (ximg
, x
, y
, 0);
5103 #endif /* HAVE_NS */
5105 /* Fill in the background_transparent field while we have the mask handy. */
5106 image_background_transparent (img
, f
, mask_img
);
5108 /* Put mask_img into the image. */
5109 image_put_x_image (f
, img
, mask_img
, 1);
5110 #endif /* !HAVE_NS */
5112 for (y
= 0; y
< img
->height
; ++y
)
5113 for (x
= 0; x
< img
->width
; ++x
)
5115 COLORREF p
= GetPixel (ximg
, x
, y
);
5117 mask_img
[y
* row_width
+ x
/ 8] |= 1 << (x
% 8);
5120 /* Create the mask image. */
5121 img
->mask
= w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
,
5123 /* Fill in the background_transparent field while we have the mask handy. */
5124 SelectObject (ximg
, img
->mask
);
5125 image_background_transparent (img
, f
, ximg
);
5127 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5129 #endif /* HAVE_NTGUI */
5131 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
5135 /***********************************************************************
5136 PBM (mono, gray, color)
5137 ***********************************************************************/
5139 static bool pbm_image_p (Lisp_Object object
);
5140 static bool pbm_load (struct frame
*f
, struct image
*img
);
5142 /* Indices of image specification fields in gs_format, below. */
5144 enum pbm_keyword_index
5160 /* Vector of image_keyword structures describing the format
5161 of valid user-defined image specifications. */
5163 static const struct image_keyword pbm_format
[PBM_LAST
] =
5165 {":type", IMAGE_SYMBOL_VALUE
, 1},
5166 {":file", IMAGE_STRING_VALUE
, 0},
5167 {":data", IMAGE_STRING_VALUE
, 0},
5168 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5169 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5170 {":relief", IMAGE_INTEGER_VALUE
, 0},
5171 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5172 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5173 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5174 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
5175 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5178 /* Structure describing the image type `pbm'. */
5180 static struct image_type pbm_type
=
5182 SYMBOL_INDEX (Qpbm
),
5191 /* Return true if OBJECT is a valid PBM image specification. */
5194 pbm_image_p (Lisp_Object object
)
5196 struct image_keyword fmt
[PBM_LAST
];
5198 memcpy (fmt
, pbm_format
, sizeof fmt
);
5200 if (!parse_image_spec (object
, fmt
, PBM_LAST
, Qpbm
))
5203 /* Must specify either :data or :file. */
5204 return fmt
[PBM_DATA
].count
+ fmt
[PBM_FILE
].count
== 1;
5208 /* Get next char skipping comments in Netpbm header. Returns -1 at
5212 pbm_next_char (unsigned char **s
, unsigned char *end
)
5216 while (*s
< end
&& (c
= *(*s
)++, c
== '#'))
5218 /* Skip to the next line break. */
5219 while (*s
< end
&& (c
= *(*s
)++, c
!= '\n' && c
!= '\r'))
5229 /* Scan a decimal number from *S and return it. Advance *S while
5230 reading the number. END is the end of the string. Value is -1 at
5234 pbm_scan_number (unsigned char **s
, unsigned char *end
)
5236 int c
= 0, val
= -1;
5238 /* Skip white-space. */
5239 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isspace (c
))
5244 /* Read decimal number. */
5246 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isdigit (c
))
5247 val
= 10 * val
+ c
- '0';
5254 /* Load PBM image IMG for use on frame F. */
5257 pbm_load (struct frame
*f
, struct image
*img
)
5261 int width
, height
, max_color_idx
= 0;
5262 Lisp_Object specified_file
;
5263 enum {PBM_MONO
, PBM_GRAY
, PBM_COLOR
} type
;
5264 unsigned char *contents
= NULL
;
5265 unsigned char *end
, *p
;
5267 unsigned char *data
= 0;
5273 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5275 if (STRINGP (specified_file
))
5278 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5279 if (!STRINGP (file
))
5281 image_error ("Cannot find image file `%s'", specified_file
);
5286 contents
= slurp_file (fd
, &size
);
5287 if (contents
== NULL
)
5289 image_error ("Error reading `%s'", file
);
5294 end
= contents
+ size
;
5299 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5300 if (!STRINGP (data
))
5302 image_error ("Invalid image data `%s'", data
);
5306 end
= p
+ SBYTES (data
);
5309 /* Check magic number. */
5310 if (end
- p
< 2 || *p
++ != 'P')
5312 image_error ("Not a PBM image: `%s'", img
->spec
);
5315 img
->pixmap
= NO_PIXMAP
;
5322 raw_p
= 0, type
= PBM_MONO
;
5326 raw_p
= 0, type
= PBM_GRAY
;
5330 raw_p
= 0, type
= PBM_COLOR
;
5334 raw_p
= 1, type
= PBM_MONO
;
5338 raw_p
= 1, type
= PBM_GRAY
;
5342 raw_p
= 1, type
= PBM_COLOR
;
5346 image_error ("Not a PBM image: `%s'", img
->spec
);
5350 /* Read width, height, maximum color-component. Characters
5351 starting with `#' up to the end of a line are ignored. */
5352 width
= pbm_scan_number (&p
, end
);
5353 height
= pbm_scan_number (&p
, end
);
5356 data
= (unsigned char *) xmalloc (width
* height
* 4);
5357 dataptr
= (uint32_t *) data
;
5360 if (type
!= PBM_MONO
)
5362 max_color_idx
= pbm_scan_number (&p
, end
);
5363 if (max_color_idx
> 65535 || max_color_idx
< 0)
5365 image_error ("Unsupported maximum PBM color value");
5370 if (!check_image_size (f
, width
, height
))
5372 image_size_error ();
5377 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5381 /* Initialize the color hash table. */
5382 init_color_table ();
5384 if (type
== PBM_MONO
)
5387 struct image_keyword fmt
[PBM_LAST
];
5388 unsigned long fg
= FRAME_FOREGROUND_PIXEL (f
);
5389 unsigned long bg
= FRAME_BACKGROUND_PIXEL (f
);
5394 /* Parse the image specification. */
5395 memcpy (fmt
, pbm_format
, sizeof fmt
);
5396 parse_image_spec (img
->spec
, fmt
, PBM_LAST
, Qpbm
);
5398 /* Get foreground and background colors, maybe allocate colors. */
5400 if (! fmt
[PBM_FOREGROUND
].count
5401 || ! STRINGP (fmt
[PBM_FOREGROUND
].value
)
5402 || ! x_defined_color (f
, SSDATA (fmt
[PBM_FOREGROUND
].value
), &xfg
, 0))
5405 x_query_color (f
, &xfg
);
5407 fga32
= xcolor_to_argb32 (xfg
);
5409 if (! fmt
[PBM_BACKGROUND
].count
5410 || ! STRINGP (fmt
[PBM_BACKGROUND
].value
)
5411 || ! x_defined_color (f
, SSDATA (fmt
[PBM_BACKGROUND
].value
), &xbg
, 0))
5414 x_query_color (f
, &xbg
);
5416 bga32
= xcolor_to_argb32 (xbg
);
5418 if (fmt
[PBM_FOREGROUND
].count
5419 && STRINGP (fmt
[PBM_FOREGROUND
].value
))
5420 fg
= x_alloc_image_color (f
, img
, fmt
[PBM_FOREGROUND
].value
, fg
);
5421 if (fmt
[PBM_BACKGROUND
].count
5422 && STRINGP (fmt
[PBM_BACKGROUND
].value
))
5424 bg
= x_alloc_image_color (f
, img
, fmt
[PBM_BACKGROUND
].value
, bg
);
5425 img
->background
= bg
;
5426 img
->background_valid
= 1;
5430 for (y
= 0; y
< height
; ++y
)
5431 for (x
= 0; x
< width
; ++x
)
5442 x_destroy_x_image (ximg
);
5444 x_clear_image (f
, img
);
5445 image_error ("Invalid image size in image `%s'",
5455 g
= pbm_scan_number (&p
, end
);
5458 *dataptr
++ = g
? fga32
: bga32
;
5460 XPutPixel (ximg
, x
, y
, g
? fg
: bg
);
5466 int expected_size
= height
* width
;
5467 if (max_color_idx
> 255)
5469 if (type
== PBM_COLOR
)
5472 if (raw_p
&& p
+ expected_size
> end
)
5477 x_destroy_x_image (ximg
);
5479 x_clear_image (f
, img
);
5480 image_error ("Invalid image size in image `%s'", img
->spec
);
5484 for (y
= 0; y
< height
; ++y
)
5485 for (x
= 0; x
< width
; ++x
)
5489 if (type
== PBM_GRAY
&& raw_p
)
5492 if (max_color_idx
> 255)
5493 r
= g
= b
= r
* 256 + *p
++;
5495 else if (type
== PBM_GRAY
)
5496 r
= g
= b
= pbm_scan_number (&p
, end
);
5500 if (max_color_idx
> 255)
5503 if (max_color_idx
> 255)
5506 if (max_color_idx
> 255)
5511 r
= pbm_scan_number (&p
, end
);
5512 g
= pbm_scan_number (&p
, end
);
5513 b
= pbm_scan_number (&p
, end
);
5516 if (r
< 0 || g
< 0 || b
< 0)
5521 x_destroy_x_image (ximg
);
5523 image_error ("Invalid pixel value in image `%s'", img
->spec
);
5528 r
= (double) r
* 255 / max_color_idx
;
5529 g
= (double) g
* 255 / max_color_idx
;
5530 b
= (double) b
* 255 / max_color_idx
;
5531 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
5533 /* RGB values are now in the range 0..max_color_idx.
5534 Scale this to the range 0..0xffff supported by X. */
5535 r
= (double) r
* 65535 / max_color_idx
;
5536 g
= (double) g
* 65535 / max_color_idx
;
5537 b
= (double) b
* 65535 / max_color_idx
;
5538 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5543 #ifdef COLOR_TABLE_SUPPORT
5544 /* Store in IMG->colors the colors allocated for the image, and
5545 free the color table. */
5546 img
->colors
= colors_in_color_table (&img
->ncolors
);
5547 free_color_table ();
5548 #endif /* COLOR_TABLE_SUPPORT */
5551 img
->height
= height
;
5553 /* Maybe fill in the background field while we have ximg handy. */
5556 create_cairo_image_surface (img
, data
, width
, height
);
5558 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
5559 /* Casting avoids a GCC warning. */
5560 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
5562 /* Put ximg into the image. */
5563 image_put_x_image (f
, img
, ximg
, 0);
5566 /* X and W32 versions did it here, MAC version above. ++kfs
5568 img->height = height; */
5575 /***********************************************************************
5577 ***********************************************************************/
5579 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
5581 /* Function prototypes. */
5583 static bool png_image_p (Lisp_Object object
);
5584 static bool png_load (struct frame
*f
, struct image
*img
);
5586 /* Indices of image specification fields in png_format, below. */
5588 enum png_keyword_index
5603 /* Vector of image_keyword structures describing the format
5604 of valid user-defined image specifications. */
5606 static const struct image_keyword png_format
[PNG_LAST
] =
5608 {":type", IMAGE_SYMBOL_VALUE
, 1},
5609 {":data", IMAGE_STRING_VALUE
, 0},
5610 {":file", IMAGE_STRING_VALUE
, 0},
5611 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5612 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5613 {":relief", IMAGE_INTEGER_VALUE
, 0},
5614 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5615 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5616 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5617 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5620 #if defined HAVE_NTGUI && defined WINDOWSNT
5621 static bool init_png_functions (void);
5623 #define init_png_functions NULL
5626 /* Structure describing the image type `png'. */
5628 static struct image_type png_type
=
5630 SYMBOL_INDEX (Qpng
),
5638 /* Return true if OBJECT is a valid PNG image specification. */
5641 png_image_p (Lisp_Object object
)
5643 struct image_keyword fmt
[PNG_LAST
];
5644 memcpy (fmt
, png_format
, sizeof fmt
);
5646 if (!parse_image_spec (object
, fmt
, PNG_LAST
, Qpng
))
5649 /* Must specify either the :data or :file keyword. */
5650 return fmt
[PNG_FILE
].count
+ fmt
[PNG_DATA
].count
== 1;
5653 #endif /* HAVE_PNG || HAVE_NS || USE_CAIRO */
5656 #if (defined HAVE_PNG && !defined HAVE_NS) || defined USE_CAIRO
5659 /* PNG library details. */
5661 DEF_DLL_FN (png_voidp
, png_get_io_ptr
, (png_structp
));
5662 DEF_DLL_FN (int, png_sig_cmp
, (png_bytep
, png_size_t
, png_size_t
));
5663 DEF_DLL_FN (png_structp
, png_create_read_struct
,
5664 (png_const_charp
, png_voidp
, png_error_ptr
, png_error_ptr
));
5665 DEF_DLL_FN (png_infop
, png_create_info_struct
, (png_structp
));
5666 DEF_DLL_FN (void, png_destroy_read_struct
,
5667 (png_structpp
, png_infopp
, png_infopp
));
5668 DEF_DLL_FN (void, png_set_read_fn
, (png_structp
, png_voidp
, png_rw_ptr
));
5669 DEF_DLL_FN (void, png_set_sig_bytes
, (png_structp
, int));
5670 DEF_DLL_FN (void, png_read_info
, (png_structp
, png_infop
));
5671 DEF_DLL_FN (png_uint_32
, png_get_IHDR
,
5672 (png_structp
, png_infop
, png_uint_32
*, png_uint_32
*,
5673 int *, int *, int *, int *, int *));
5674 DEF_DLL_FN (png_uint_32
, png_get_valid
, (png_structp
, png_infop
, png_uint_32
));
5675 DEF_DLL_FN (void, png_set_strip_16
, (png_structp
));
5676 DEF_DLL_FN (void, png_set_expand
, (png_structp
));
5677 DEF_DLL_FN (void, png_set_gray_to_rgb
, (png_structp
));
5678 DEF_DLL_FN (void, png_set_background
,
5679 (png_structp
, png_color_16p
, int, int, double));
5680 DEF_DLL_FN (png_uint_32
, png_get_bKGD
,
5681 (png_structp
, png_infop
, png_color_16p
*));
5682 DEF_DLL_FN (void, png_read_update_info
, (png_structp
, png_infop
));
5683 DEF_DLL_FN (png_byte
, png_get_channels
, (png_structp
, png_infop
));
5684 DEF_DLL_FN (png_size_t
, png_get_rowbytes
, (png_structp
, png_infop
));
5685 DEF_DLL_FN (void, png_read_image
, (png_structp
, png_bytepp
));
5686 DEF_DLL_FN (void, png_read_end
, (png_structp
, png_infop
));
5687 DEF_DLL_FN (void, png_error
, (png_structp
, png_const_charp
));
5689 # if (PNG_LIBPNG_VER >= 10500)
5690 DEF_DLL_FN (void, png_longjmp
, (png_structp
, int)) PNG_NORETURN
;
5691 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn
,
5692 (png_structp
, png_longjmp_ptr
, size_t));
5693 # endif /* libpng version >= 1.5 */
5696 init_png_functions (void)
5700 if (!(library
= w32_delayed_load (Qpng
)))
5703 LOAD_DLL_FN (library
, png_get_io_ptr
);
5704 LOAD_DLL_FN (library
, png_sig_cmp
);
5705 LOAD_DLL_FN (library
, png_create_read_struct
);
5706 LOAD_DLL_FN (library
, png_create_info_struct
);
5707 LOAD_DLL_FN (library
, png_destroy_read_struct
);
5708 LOAD_DLL_FN (library
, png_set_read_fn
);
5709 LOAD_DLL_FN (library
, png_set_sig_bytes
);
5710 LOAD_DLL_FN (library
, png_read_info
);
5711 LOAD_DLL_FN (library
, png_get_IHDR
);
5712 LOAD_DLL_FN (library
, png_get_valid
);
5713 LOAD_DLL_FN (library
, png_set_strip_16
);
5714 LOAD_DLL_FN (library
, png_set_expand
);
5715 LOAD_DLL_FN (library
, png_set_gray_to_rgb
);
5716 LOAD_DLL_FN (library
, png_set_background
);
5717 LOAD_DLL_FN (library
, png_get_bKGD
);
5718 LOAD_DLL_FN (library
, png_read_update_info
);
5719 LOAD_DLL_FN (library
, png_get_channels
);
5720 LOAD_DLL_FN (library
, png_get_rowbytes
);
5721 LOAD_DLL_FN (library
, png_read_image
);
5722 LOAD_DLL_FN (library
, png_read_end
);
5723 LOAD_DLL_FN (library
, png_error
);
5725 # if (PNG_LIBPNG_VER >= 10500)
5726 LOAD_DLL_FN (library
, png_longjmp
);
5727 LOAD_DLL_FN (library
, png_set_longjmp_fn
);
5728 # endif /* libpng version >= 1.5 */
5733 # undef png_create_info_struct
5734 # undef png_create_read_struct
5735 # undef png_destroy_read_struct
5737 # undef png_get_bKGD
5738 # undef png_get_channels
5739 # undef png_get_IHDR
5740 # undef png_get_io_ptr
5741 # undef png_get_rowbytes
5742 # undef png_get_valid
5744 # undef png_read_end
5745 # undef png_read_image
5746 # undef png_read_info
5747 # undef png_read_update_info
5748 # undef png_set_background
5749 # undef png_set_expand
5750 # undef png_set_gray_to_rgb
5751 # undef png_set_longjmp_fn
5752 # undef png_set_read_fn
5753 # undef png_set_sig_bytes
5754 # undef png_set_strip_16
5757 # define png_create_info_struct fn_png_create_info_struct
5758 # define png_create_read_struct fn_png_create_read_struct
5759 # define png_destroy_read_struct fn_png_destroy_read_struct
5760 # define png_error fn_png_error
5761 # define png_get_bKGD fn_png_get_bKGD
5762 # define png_get_channels fn_png_get_channels
5763 # define png_get_IHDR fn_png_get_IHDR
5764 # define png_get_io_ptr fn_png_get_io_ptr
5765 # define png_get_rowbytes fn_png_get_rowbytes
5766 # define png_get_valid fn_png_get_valid
5767 # define png_longjmp fn_png_longjmp
5768 # define png_read_end fn_png_read_end
5769 # define png_read_image fn_png_read_image
5770 # define png_read_info fn_png_read_info
5771 # define png_read_update_info fn_png_read_update_info
5772 # define png_set_background fn_png_set_background
5773 # define png_set_expand fn_png_set_expand
5774 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5775 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5776 # define png_set_read_fn fn_png_set_read_fn
5777 # define png_set_sig_bytes fn_png_set_sig_bytes
5778 # define png_set_strip_16 fn_png_set_strip_16
5779 # define png_sig_cmp fn_png_sig_cmp
5781 # endif /* WINDOWSNT */
5783 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5784 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5785 Do not use sys_setjmp, as PNG supports only jmp_buf.
5786 It's OK if the longjmp substitute restores the signal mask. */
5787 # ifdef HAVE__SETJMP
5788 # define FAST_SETJMP(j) _setjmp (j)
5789 # define FAST_LONGJMP _longjmp
5791 # define FAST_SETJMP(j) setjmp (j)
5792 # define FAST_LONGJMP longjmp
5795 # if PNG_LIBPNG_VER < 10500
5796 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5797 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5799 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5800 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5801 # define PNG_JMPBUF(ptr) \
5802 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5805 /* Error and warning handlers installed when the PNG library
5808 static _Noreturn
void
5809 my_png_error (png_struct
*png_ptr
, const char *msg
)
5811 eassert (png_ptr
!= NULL
);
5812 /* Avoid compiler warning about deprecated direct access to
5813 png_ptr's fields in libpng versions 1.4.x. */
5814 image_error ("PNG error: %s", build_string (msg
));
5815 PNG_LONGJMP (png_ptr
);
5820 my_png_warning (png_struct
*png_ptr
, const char *msg
)
5822 eassert (png_ptr
!= NULL
);
5823 image_error ("PNG warning: %s", build_string (msg
));
5826 /* Memory source for PNG decoding. */
5828 struct png_memory_storage
5830 unsigned char *bytes
; /* The data */
5831 ptrdiff_t len
; /* How big is it? */
5832 ptrdiff_t index
; /* Where are we? */
5836 /* Function set as reader function when reading PNG image from memory.
5837 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5838 bytes from the input to DATA. */
5841 png_read_from_memory (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5843 struct png_memory_storage
*tbr
= png_get_io_ptr (png_ptr
);
5845 if (length
> tbr
->len
- tbr
->index
)
5846 png_error (png_ptr
, "Read error");
5848 memcpy (data
, tbr
->bytes
+ tbr
->index
, length
);
5849 tbr
->index
= tbr
->index
+ length
;
5853 /* Function set as reader function when reading PNG image from a file.
5854 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5855 bytes from the input to DATA. */
5858 png_read_from_file (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5860 FILE *fp
= png_get_io_ptr (png_ptr
);
5862 if (fread (data
, 1, length
, fp
) < length
)
5863 png_error (png_ptr
, "Read error");
5867 /* Load PNG image IMG for use on frame F. Value is true if
5870 struct png_load_context
5872 /* These are members so that longjmp doesn't munge local variables. */
5873 png_struct
*png_ptr
;
5882 png_load_body (struct frame
*f
, struct image
*img
, struct png_load_context
*c
)
5884 Lisp_Object specified_file
;
5885 Lisp_Object specified_data
;
5888 png_struct
*png_ptr
;
5889 png_info
*info_ptr
= NULL
, *end_info
= NULL
;
5892 png_byte
*pixels
= NULL
;
5893 png_byte
**rows
= NULL
;
5894 png_uint_32 width
, height
;
5895 int bit_depth
, color_type
, interlace_type
;
5897 png_uint_32 row_bytes
;
5899 struct png_memory_storage tbr
; /* Data to be read */
5902 unsigned char *data
= 0;
5905 XImagePtr ximg
, mask_img
= NULL
;
5908 /* Find out what file to load. */
5909 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5910 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5911 IF_LINT (Lisp_Object
volatile specified_data_volatile
= specified_data
);
5913 if (NILP (specified_data
))
5916 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
5917 if (!STRINGP (file
))
5919 image_error ("Cannot find image file `%s'", specified_file
);
5923 /* Open the image file. */
5924 fp
= fdopen (fd
, "rb");
5927 image_error ("Cannot open image file `%s'", file
);
5931 /* Check PNG signature. */
5932 if (fread (sig
, 1, sizeof sig
, fp
) != sizeof sig
5933 || png_sig_cmp (sig
, 0, sizeof sig
))
5936 image_error ("Not a PNG file: `%s'", file
);
5942 if (!STRINGP (specified_data
))
5944 image_error ("Invalid image data `%s'", specified_data
);
5948 /* Read from memory. */
5949 tbr
.bytes
= SDATA (specified_data
);
5950 tbr
.len
= SBYTES (specified_data
);
5953 /* Check PNG signature. */
5954 if (tbr
.len
< sizeof sig
5955 || png_sig_cmp (tbr
.bytes
, 0, sizeof sig
))
5957 image_error ("Not a PNG image: `%s'", img
->spec
);
5961 /* Need to skip past the signature. */
5962 tbr
.bytes
+= sizeof (sig
);
5965 /* Initialize read and info structs for PNG lib. */
5966 png_ptr
= png_create_read_struct (PNG_LIBPNG_VER_STRING
,
5971 info_ptr
= png_create_info_struct (png_ptr
);
5972 end_info
= png_create_info_struct (png_ptr
);
5975 c
->png_ptr
= png_ptr
;
5976 c
->info_ptr
= info_ptr
;
5977 c
->end_info
= end_info
;
5982 if (! (info_ptr
&& end_info
))
5984 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5989 if (fp
) fclose (fp
);
5993 /* Set error jump-back. We come back here when the PNG library
5994 detects an error. */
5995 if (FAST_SETJMP (PNG_JMPBUF (png_ptr
)))
5999 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6007 /* Silence a bogus diagnostic; see GCC bug 54561. */
6008 IF_LINT (fp
= c
->fp
);
6009 IF_LINT (specified_data
= specified_data_volatile
);
6011 /* Read image info. */
6012 if (!NILP (specified_data
))
6013 png_set_read_fn (png_ptr
, &tbr
, png_read_from_memory
);
6015 png_set_read_fn (png_ptr
, fp
, png_read_from_file
);
6017 png_set_sig_bytes (png_ptr
, sizeof sig
);
6018 png_read_info (png_ptr
, info_ptr
);
6019 png_get_IHDR (png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
,
6020 &interlace_type
, NULL
, NULL
);
6022 if (! (width
<= INT_MAX
&& height
<= INT_MAX
6023 && check_image_size (f
, width
, height
)))
6025 image_size_error ();
6030 /* Create the X image and pixmap now, so that the work below can be
6031 omitted if the image is too large for X. */
6032 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6036 /* If image contains simply transparency data, we prefer to
6037 construct a clipping mask. */
6038 if (png_get_valid (png_ptr
, info_ptr
, PNG_INFO_tRNS
))
6043 /* This function is easier to write if we only have to handle
6044 one data format: RGB or RGBA with 8 bits per channel. Let's
6045 transform other formats into that format. */
6047 /* Strip more than 8 bits per channel. */
6048 if (bit_depth
== 16)
6049 png_set_strip_16 (png_ptr
);
6051 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6053 png_set_expand (png_ptr
);
6055 /* Convert grayscale images to RGB. */
6056 if (color_type
== PNG_COLOR_TYPE_GRAY
6057 || color_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
6058 png_set_gray_to_rgb (png_ptr
);
6060 /* Handle alpha channel by combining the image with a background
6061 color. Do this only if a real alpha channel is supplied. For
6062 simple transparency, we prefer a clipping mask. */
6065 /* png_color_16 *image_bg; */
6066 Lisp_Object specified_bg
6067 = image_spec_value (img
->spec
, QCbackground
, NULL
);
6070 /* If the user specified a color, try to use it; if not, use the
6071 current frame background, ignoring any default background
6072 color set by the image. */
6073 if (STRINGP (specified_bg
)
6074 ? x_defined_color (f
, SSDATA (specified_bg
), &color
, false)
6075 : (x_query_frame_background_color (f
, &color
), true))
6076 /* The user specified `:background', use that. */
6078 int shift
= bit_depth
== 16 ? 0 : 8;
6079 png_color_16 bg
= { 0 };
6080 bg
.red
= color
.red
>> shift
;
6081 bg
.green
= color
.green
>> shift
;
6082 bg
.blue
= color
.blue
>> shift
;
6084 png_set_background (png_ptr
, &bg
,
6085 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
6089 /* Update info structure. */
6090 png_read_update_info (png_ptr
, info_ptr
);
6092 /* Get number of channels. Valid values are 1 for grayscale images
6093 and images with a palette, 2 for grayscale images with transparency
6094 information (alpha channel), 3 for RGB images, and 4 for RGB
6095 images with alpha channel, i.e. RGBA. If conversions above were
6096 sufficient we should only have 3 or 4 channels here. */
6097 channels
= png_get_channels (png_ptr
, info_ptr
);
6098 eassert (channels
== 3 || channels
== 4);
6100 /* Number of bytes needed for one row of the image. */
6101 row_bytes
= png_get_rowbytes (png_ptr
, info_ptr
);
6103 /* Allocate memory for the image. */
6104 if (height
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *rows
6105 || row_bytes
> min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *pixels
/ height
)
6106 memory_full (SIZE_MAX
);
6107 c
->pixels
= pixels
= xmalloc (sizeof *pixels
* row_bytes
* height
);
6108 c
->rows
= rows
= xmalloc (height
* sizeof *rows
);
6109 for (i
= 0; i
< height
; ++i
)
6110 rows
[i
] = pixels
+ i
* row_bytes
;
6112 /* Read the entire image. */
6113 png_read_image (png_ptr
, rows
);
6114 png_read_end (png_ptr
, info_ptr
);
6122 data
= (unsigned char *) xmalloc (width
* height
* 4);
6123 dataptr
= (uint32_t *) data
;
6125 /* Create an image and pixmap serving as mask if the PNG image
6126 contains an alpha channel. */
6129 && !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
6132 x_destroy_x_image (ximg
);
6133 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
);
6138 /* Fill the X image and mask from PNG data. */
6139 init_color_table ();
6141 for (y
= 0; y
< height
; ++y
)
6143 png_byte
*p
= rows
[y
];
6145 for (x
= 0; x
< width
; ++x
)
6154 if (channels
== 4) a
= *p
++;
6155 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
6160 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
6161 /* An alpha channel, aka mask channel, associates variable
6162 transparency with an image. Where other image formats
6163 support binary transparency---fully transparent or fully
6164 opaque---PNG allows up to 254 levels of partial transparency.
6165 The PNG library implements partial transparency by combining
6166 the image with a specified background color.
6168 I'm not sure how to handle this here nicely: because the
6169 background on which the image is displayed may change, for
6170 real alpha channel support, it would be necessary to create
6171 a new image for each possible background.
6173 What I'm doing now is that a mask is created if we have
6174 boolean transparency information. Otherwise I'm using
6175 the frame's background color to combine the image with. */
6180 XPutPixel (mask_img
, x
, y
, *p
> 0 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
);
6187 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6188 /* Set IMG's background color from the PNG image, unless the user
6192 if (png_get_bKGD (png_ptr
, info_ptr
, &bg
))
6194 img
->background
= lookup_rgb_color (f
, bg
->red
, bg
->green
, bg
->blue
);
6195 img
->background_valid
= 1;
6199 # ifdef COLOR_TABLE_SUPPORT
6200 /* Remember colors allocated for this image. */
6201 img
->colors
= colors_in_color_table (&img
->ncolors
);
6202 free_color_table ();
6203 # endif /* COLOR_TABLE_SUPPORT */
6206 png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6211 img
->height
= height
;
6214 create_cairo_image_surface (img
, data
, width
, height
);
6216 /* Maybe fill in the background field while we have ximg handy.
6217 Casting avoids a GCC warning. */
6218 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6220 /* Put ximg into the image. */
6221 image_put_x_image (f
, img
, ximg
, 0);
6223 /* Same for the mask. */
6226 /* Fill in the background_transparent field while we have the
6227 mask handy. Casting avoids a GCC warning. */
6228 image_background_transparent (img
, f
, (XImagePtr_or_DC
)mask_img
);
6230 image_put_x_image (f
, img
, mask_img
, 1);
6238 png_load (struct frame
*f
, struct image
*img
)
6240 struct png_load_context c
;
6241 return png_load_body (f
, img
, &c
);
6244 #elif defined HAVE_NS
6247 png_load (struct frame
*f
, struct image
*img
)
6249 return ns_load_image (f
, img
,
6250 image_spec_value (img
->spec
, QCfile
, NULL
),
6251 image_spec_value (img
->spec
, QCdata
, NULL
));
6255 #endif /* HAVE_NS */
6259 /***********************************************************************
6261 ***********************************************************************/
6263 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6265 static bool jpeg_image_p (Lisp_Object object
);
6266 static bool jpeg_load (struct frame
*f
, struct image
*img
);
6268 /* Indices of image specification fields in gs_format, below. */
6270 enum jpeg_keyword_index
6279 JPEG_HEURISTIC_MASK
,
6285 /* Vector of image_keyword structures describing the format
6286 of valid user-defined image specifications. */
6288 static const struct image_keyword jpeg_format
[JPEG_LAST
] =
6290 {":type", IMAGE_SYMBOL_VALUE
, 1},
6291 {":data", IMAGE_STRING_VALUE
, 0},
6292 {":file", IMAGE_STRING_VALUE
, 0},
6293 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6294 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6295 {":relief", IMAGE_INTEGER_VALUE
, 0},
6296 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6297 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6298 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6299 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
6302 #if defined HAVE_NTGUI && defined WINDOWSNT
6303 static bool init_jpeg_functions (void);
6305 #define init_jpeg_functions NULL
6308 /* Structure describing the image type `jpeg'. */
6310 static struct image_type jpeg_type
=
6312 SYMBOL_INDEX (Qjpeg
),
6316 init_jpeg_functions
,
6320 /* Return true if OBJECT is a valid JPEG image specification. */
6323 jpeg_image_p (Lisp_Object object
)
6325 struct image_keyword fmt
[JPEG_LAST
];
6327 memcpy (fmt
, jpeg_format
, sizeof fmt
);
6329 if (!parse_image_spec (object
, fmt
, JPEG_LAST
, Qjpeg
))
6332 /* Must specify either the :data or :file keyword. */
6333 return fmt
[JPEG_FILE
].count
+ fmt
[JPEG_DATA
].count
== 1;
6336 #endif /* HAVE_JPEG || HAVE_NS */
6340 /* Work around a warning about HAVE_STDLIB_H being redefined in
6342 # ifdef HAVE_STDLIB_H
6343 # undef HAVE_STDLIB_H
6346 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6347 /* In older releases of the jpeg library, jpeglib.h will define boolean
6348 differently depending on __WIN32__, so make sure it is defined. */
6349 # define __WIN32__ 1
6352 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6353 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6354 using the Windows boolean type instead of the jpeglib boolean type
6355 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6356 headers are included along with windows.h, so under Cygwin, jpeglib
6357 attempts to define a conflicting boolean type. Worse, forcing
6358 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6359 because it created an ABI incompatibility between the
6360 already-compiled jpeg library and the header interface definition.
6362 The best we can do is to define jpeglib's boolean type to a
6363 different name. This name, jpeg_boolean, remains in effect through
6364 the rest of image.c.
6366 # if defined CYGWIN && defined HAVE_NTGUI
6367 # define boolean jpeg_boolean
6369 # include <jpeglib.h>
6370 # include <jerror.h>
6374 /* JPEG library details. */
6375 DEF_DLL_FN (void, jpeg_CreateDecompress
, (j_decompress_ptr
, int, size_t));
6376 DEF_DLL_FN (boolean
, jpeg_start_decompress
, (j_decompress_ptr
));
6377 DEF_DLL_FN (boolean
, jpeg_finish_decompress
, (j_decompress_ptr
));
6378 DEF_DLL_FN (void, jpeg_destroy_decompress
, (j_decompress_ptr
));
6379 DEF_DLL_FN (int, jpeg_read_header
, (j_decompress_ptr
, boolean
));
6380 DEF_DLL_FN (JDIMENSION
, jpeg_read_scanlines
,
6381 (j_decompress_ptr
, JSAMPARRAY
, JDIMENSION
));
6382 DEF_DLL_FN (struct jpeg_error_mgr
*, jpeg_std_error
,
6383 (struct jpeg_error_mgr
*));
6384 DEF_DLL_FN (boolean
, jpeg_resync_to_restart
, (j_decompress_ptr
, int));
6387 init_jpeg_functions (void)
6391 if (!(library
= w32_delayed_load (Qjpeg
)))
6394 LOAD_DLL_FN (library
, jpeg_finish_decompress
);
6395 LOAD_DLL_FN (library
, jpeg_read_scanlines
);
6396 LOAD_DLL_FN (library
, jpeg_start_decompress
);
6397 LOAD_DLL_FN (library
, jpeg_read_header
);
6398 LOAD_DLL_FN (library
, jpeg_CreateDecompress
);
6399 LOAD_DLL_FN (library
, jpeg_destroy_decompress
);
6400 LOAD_DLL_FN (library
, jpeg_std_error
);
6401 LOAD_DLL_FN (library
, jpeg_resync_to_restart
);
6405 # undef jpeg_CreateDecompress
6406 # undef jpeg_destroy_decompress
6407 # undef jpeg_finish_decompress
6408 # undef jpeg_read_header
6409 # undef jpeg_read_scanlines
6410 # undef jpeg_resync_to_restart
6411 # undef jpeg_start_decompress
6412 # undef jpeg_std_error
6414 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6415 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6416 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6417 # define jpeg_read_header fn_jpeg_read_header
6418 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6419 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6420 # define jpeg_start_decompress fn_jpeg_start_decompress
6421 # define jpeg_std_error fn_jpeg_std_error
6423 /* Wrapper since we can't directly assign the function pointer
6424 to another function pointer that was declared more completely easily. */
6426 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo
, int desired
)
6428 return jpeg_resync_to_restart (cinfo
, desired
);
6430 # undef jpeg_resync_to_restart
6431 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6433 # endif /* WINDOWSNT */
6435 struct my_jpeg_error_mgr
6437 struct jpeg_error_mgr pub
;
6438 sys_jmp_buf setjmp_buffer
;
6440 /* The remaining members are so that longjmp doesn't munge local
6442 struct jpeg_decompress_struct cinfo
;
6446 MY_JPEG_INVALID_IMAGE_SIZE
,
6447 MY_JPEG_CANNOT_CREATE_X
6452 static _Noreturn
void
6453 my_error_exit (j_common_ptr cinfo
)
6455 struct my_jpeg_error_mgr
*mgr
= (struct my_jpeg_error_mgr
*) cinfo
->err
;
6456 mgr
->failure_code
= MY_JPEG_ERROR_EXIT
;
6457 sys_longjmp (mgr
->setjmp_buffer
, 1);
6461 /* Init source method for JPEG data source manager. Called by
6462 jpeg_read_header() before any data is actually read. See
6463 libjpeg.doc from the JPEG lib distribution. */
6466 our_common_init_source (j_decompress_ptr cinfo
)
6471 /* Method to terminate data source. Called by
6472 jpeg_finish_decompress() after all data has been processed. */
6475 our_common_term_source (j_decompress_ptr cinfo
)
6480 /* Fill input buffer method for JPEG data source manager. Called
6481 whenever more data is needed. We read the whole image in one step,
6482 so this only adds a fake end of input marker at the end. */
6484 static JOCTET our_memory_buffer
[2];
6487 our_memory_fill_input_buffer (j_decompress_ptr cinfo
)
6489 /* Insert a fake EOI marker. */
6490 struct jpeg_source_mgr
*src
= cinfo
->src
;
6492 our_memory_buffer
[0] = (JOCTET
) 0xFF;
6493 our_memory_buffer
[1] = (JOCTET
) JPEG_EOI
;
6495 src
->next_input_byte
= our_memory_buffer
;
6496 src
->bytes_in_buffer
= 2;
6501 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6502 is the JPEG data source manager. */
6505 our_memory_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6507 struct jpeg_source_mgr
*src
= cinfo
->src
;
6511 if (num_bytes
> src
->bytes_in_buffer
)
6512 ERREXIT (cinfo
, JERR_INPUT_EOF
);
6514 src
->bytes_in_buffer
-= num_bytes
;
6515 src
->next_input_byte
+= num_bytes
;
6520 /* Set up the JPEG lib for reading an image from DATA which contains
6521 LEN bytes. CINFO is the decompression info structure created for
6522 reading the image. */
6525 jpeg_memory_src (j_decompress_ptr cinfo
, JOCTET
*data
, ptrdiff_t len
)
6527 struct jpeg_source_mgr
*src
= cinfo
->src
;
6531 /* First time for this JPEG object? */
6532 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6533 JPOOL_PERMANENT
, sizeof *src
);
6535 src
->next_input_byte
= data
;
6538 src
->init_source
= our_common_init_source
;
6539 src
->fill_input_buffer
= our_memory_fill_input_buffer
;
6540 src
->skip_input_data
= our_memory_skip_input_data
;
6541 src
->resync_to_restart
= jpeg_resync_to_restart
; /* Use default method. */
6542 src
->term_source
= our_common_term_source
;
6543 src
->bytes_in_buffer
= len
;
6544 src
->next_input_byte
= data
;
6548 struct jpeg_stdio_mgr
6550 struct jpeg_source_mgr mgr
;
6557 /* Size of buffer to read JPEG from file.
6558 Not too big, as we want to use alloc_small. */
6559 #define JPEG_STDIO_BUFFER_SIZE 8192
6562 /* Fill input buffer method for JPEG data source manager. Called
6563 whenever more data is needed. The data is read from a FILE *. */
6566 our_stdio_fill_input_buffer (j_decompress_ptr cinfo
)
6568 struct jpeg_stdio_mgr
*src
;
6570 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6575 bytes
= fread (src
->buffer
, 1, JPEG_STDIO_BUFFER_SIZE
, src
->file
);
6577 src
->mgr
.bytes_in_buffer
= bytes
;
6580 WARNMS (cinfo
, JWRN_JPEG_EOF
);
6582 src
->buffer
[0] = (JOCTET
) 0xFF;
6583 src
->buffer
[1] = (JOCTET
) JPEG_EOI
;
6584 src
->mgr
.bytes_in_buffer
= 2;
6586 src
->mgr
.next_input_byte
= src
->buffer
;
6593 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6594 is the JPEG data source manager. */
6597 our_stdio_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6599 struct jpeg_stdio_mgr
*src
;
6600 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6602 while (num_bytes
> 0 && !src
->finished
)
6604 if (num_bytes
<= src
->mgr
.bytes_in_buffer
)
6606 src
->mgr
.bytes_in_buffer
-= num_bytes
;
6607 src
->mgr
.next_input_byte
+= num_bytes
;
6612 num_bytes
-= src
->mgr
.bytes_in_buffer
;
6613 src
->mgr
.bytes_in_buffer
= 0;
6614 src
->mgr
.next_input_byte
= NULL
;
6616 our_stdio_fill_input_buffer (cinfo
);
6622 /* Set up the JPEG lib for reading an image from a FILE *.
6623 CINFO is the decompression info structure created for
6624 reading the image. */
6627 jpeg_file_src (j_decompress_ptr cinfo
, FILE *fp
)
6629 struct jpeg_stdio_mgr
*src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6633 /* First time for this JPEG object? */
6634 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6635 JPOOL_PERMANENT
, sizeof *src
);
6636 cinfo
->src
= (struct jpeg_source_mgr
*) src
;
6637 src
->buffer
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6639 JPEG_STDIO_BUFFER_SIZE
);
6644 src
->mgr
.init_source
= our_common_init_source
;
6645 src
->mgr
.fill_input_buffer
= our_stdio_fill_input_buffer
;
6646 src
->mgr
.skip_input_data
= our_stdio_skip_input_data
;
6647 src
->mgr
.resync_to_restart
= jpeg_resync_to_restart
; /* Use default. */
6648 src
->mgr
.term_source
= our_common_term_source
;
6649 src
->mgr
.bytes_in_buffer
= 0;
6650 src
->mgr
.next_input_byte
= NULL
;
6653 /* Load image IMG for use on frame F. Patterned after example.c
6654 from the JPEG lib. */
6657 jpeg_load_body (struct frame
*f
, struct image
*img
,
6658 struct my_jpeg_error_mgr
*mgr
)
6660 Lisp_Object specified_file
;
6661 Lisp_Object specified_data
;
6662 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6663 FILE * IF_LINT (volatile) fp
= NULL
;
6665 int row_stride
, x
, y
;
6666 unsigned long *colors
;
6670 XImagePtr ximg
= NULL
;
6673 /* Open the JPEG file. */
6674 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6675 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6676 IF_LINT (Lisp_Object
volatile specified_data_volatile
= specified_data
);
6678 if (NILP (specified_data
))
6681 Lisp_Object file
= x_find_image_fd (specified_file
, &fd
);
6682 if (!STRINGP (file
))
6684 image_error ("Cannot find image file `%s'", specified_file
);
6688 fp
= fdopen (fd
, "rb");
6691 image_error ("Cannot open `%s'", file
);
6695 else if (!STRINGP (specified_data
))
6697 image_error ("Invalid image data `%s'", specified_data
);
6701 /* Customize libjpeg's error handling to call my_error_exit when an
6702 error is detected. This function will perform a longjmp. */
6703 mgr
->cinfo
.err
= jpeg_std_error (&mgr
->pub
);
6704 mgr
->pub
.error_exit
= my_error_exit
;
6705 if (sys_setjmp (mgr
->setjmp_buffer
))
6707 switch (mgr
->failure_code
)
6709 case MY_JPEG_ERROR_EXIT
:
6711 char buf
[JMSG_LENGTH_MAX
];
6712 mgr
->cinfo
.err
->format_message ((j_common_ptr
) &mgr
->cinfo
, buf
);
6713 image_error ("Error reading JPEG image `%s': %s",
6714 img
->spec
, build_string (buf
));
6718 case MY_JPEG_INVALID_IMAGE_SIZE
:
6719 image_size_error ();
6722 case MY_JPEG_CANNOT_CREATE_X
:
6726 /* Close the input file and destroy the JPEG object. */
6729 jpeg_destroy_decompress (&mgr
->cinfo
);
6731 /* If we already have an XImage, free that. */
6733 x_destroy_x_image (ximg
);
6735 /* Free pixmap and colors. */
6736 x_clear_image (f
, img
);
6740 /* Silence a bogus diagnostic; see GCC bug 54561. */
6741 IF_LINT (specified_data
= specified_data_volatile
);
6743 /* Create the JPEG decompression object. Let it read from fp.
6744 Read the JPEG image header. */
6745 jpeg_CreateDecompress (&mgr
->cinfo
, JPEG_LIB_VERSION
, sizeof *&mgr
->cinfo
);
6747 if (NILP (specified_data
))
6748 jpeg_file_src (&mgr
->cinfo
, fp
);
6750 jpeg_memory_src (&mgr
->cinfo
, SDATA (specified_data
),
6751 SBYTES (specified_data
));
6753 jpeg_read_header (&mgr
->cinfo
, 1);
6755 /* Customize decompression so that color quantization will be used.
6756 Start decompression. */
6757 mgr
->cinfo
.quantize_colors
= 1;
6758 jpeg_start_decompress (&mgr
->cinfo
);
6759 width
= img
->width
= mgr
->cinfo
.output_width
;
6760 height
= img
->height
= mgr
->cinfo
.output_height
;
6762 if (!check_image_size (f
, width
, height
))
6764 mgr
->failure_code
= MY_JPEG_INVALID_IMAGE_SIZE
;
6765 sys_longjmp (mgr
->setjmp_buffer
, 1);
6769 /* Create X image and pixmap. */
6770 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6772 mgr
->failure_code
= MY_JPEG_CANNOT_CREATE_X
;
6773 sys_longjmp (mgr
->setjmp_buffer
, 1);
6777 /* Allocate colors. When color quantization is used,
6778 mgr->cinfo.actual_number_of_colors has been set with the number of
6779 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6780 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6781 No more than 255 colors will be generated. */
6784 if (mgr
->cinfo
.out_color_components
> 2)
6785 ir
= 0, ig
= 1, ib
= 2;
6786 else if (mgr
->cinfo
.out_color_components
> 1)
6787 ir
= 0, ig
= 1, ib
= 0;
6789 ir
= 0, ig
= 0, ib
= 0;
6792 /* Use the color table mechanism because it handles colors that
6793 cannot be allocated nicely. Such colors will be replaced with
6794 a default color, and we don't have to care about which colors
6795 can be freed safely, and which can't. */
6796 init_color_table ();
6797 SAFE_NALLOCA (colors
, 1, mgr
->cinfo
.actual_number_of_colors
);
6799 for (i
= 0; i
< mgr
->cinfo
.actual_number_of_colors
; ++i
)
6801 /* Multiply RGB values with 255 because X expects RGB values
6802 in the range 0..0xffff. */
6803 int r
= mgr
->cinfo
.colormap
[ir
][i
] << 8;
6804 int g
= mgr
->cinfo
.colormap
[ig
][i
] << 8;
6805 int b
= mgr
->cinfo
.colormap
[ib
][i
] << 8;
6806 colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
6810 #ifdef COLOR_TABLE_SUPPORT
6811 /* Remember those colors actually allocated. */
6812 img
->colors
= colors_in_color_table (&img
->ncolors
);
6813 free_color_table ();
6814 #endif /* COLOR_TABLE_SUPPORT */
6818 row_stride
= width
* mgr
->cinfo
.output_components
;
6819 buffer
= mgr
->cinfo
.mem
->alloc_sarray ((j_common_ptr
) &mgr
->cinfo
,
6820 JPOOL_IMAGE
, row_stride
, 1);
6823 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
6824 uint32_t *dataptr
= (uint32_t *) data
;
6827 for (y
= 0; y
< height
; ++y
)
6829 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6831 for (x
= 0; x
< width
; ++x
)
6834 r
= mgr
->cinfo
.colormap
[ir
][i
];
6835 g
= mgr
->cinfo
.colormap
[ig
][i
];
6836 b
= mgr
->cinfo
.colormap
[ib
][i
];
6837 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
6841 create_cairo_image_surface (img
, data
, width
, height
);
6844 for (y
= 0; y
< height
; ++y
)
6846 jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6847 for (x
= 0; x
< mgr
->cinfo
.output_width
; ++x
)
6848 XPutPixel (ximg
, x
, y
, colors
[buffer
[0][x
]]);
6853 jpeg_finish_decompress (&mgr
->cinfo
);
6854 jpeg_destroy_decompress (&mgr
->cinfo
);
6859 /* Maybe fill in the background field while we have ximg handy. */
6860 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6861 /* Casting avoids a GCC warning. */
6862 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6864 /* Put ximg into the image. */
6865 image_put_x_image (f
, img
, ximg
, 0);
6872 jpeg_load (struct frame
*f
, struct image
*img
)
6874 struct my_jpeg_error_mgr mgr
;
6875 return jpeg_load_body (f
, img
, &mgr
);
6878 #else /* HAVE_JPEG */
6882 jpeg_load (struct frame
*f
, struct image
*img
)
6884 return ns_load_image (f
, img
,
6885 image_spec_value (img
->spec
, QCfile
, NULL
),
6886 image_spec_value (img
->spec
, QCdata
, NULL
));
6888 #endif /* HAVE_NS */
6890 #endif /* !HAVE_JPEG */
6894 /***********************************************************************
6896 ***********************************************************************/
6898 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6900 static bool tiff_image_p (Lisp_Object object
);
6901 static bool tiff_load (struct frame
*f
, struct image
*img
);
6903 /* Indices of image specification fields in tiff_format, below. */
6905 enum tiff_keyword_index
6914 TIFF_HEURISTIC_MASK
,
6921 /* Vector of image_keyword structures describing the format
6922 of valid user-defined image specifications. */
6924 static const struct image_keyword tiff_format
[TIFF_LAST
] =
6926 {":type", IMAGE_SYMBOL_VALUE
, 1},
6927 {":data", IMAGE_STRING_VALUE
, 0},
6928 {":file", IMAGE_STRING_VALUE
, 0},
6929 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6930 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6931 {":relief", IMAGE_INTEGER_VALUE
, 0},
6932 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6933 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6934 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6935 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
6936 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0}
6939 #if defined HAVE_NTGUI && defined WINDOWSNT
6940 static bool init_tiff_functions (void);
6942 #define init_tiff_functions NULL
6945 /* Structure describing the image type `tiff'. */
6947 static struct image_type tiff_type
=
6949 SYMBOL_INDEX (Qtiff
),
6953 init_tiff_functions
,
6957 /* Return true if OBJECT is a valid TIFF image specification. */
6960 tiff_image_p (Lisp_Object object
)
6962 struct image_keyword fmt
[TIFF_LAST
];
6963 memcpy (fmt
, tiff_format
, sizeof fmt
);
6965 if (!parse_image_spec (object
, fmt
, TIFF_LAST
, Qtiff
))
6968 /* Must specify either the :data or :file keyword. */
6969 return fmt
[TIFF_FILE
].count
+ fmt
[TIFF_DATA
].count
== 1;
6972 #endif /* HAVE_TIFF || HAVE_NS */
6976 # include <tiffio.h>
6980 /* TIFF library details. */
6981 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetErrorHandler
, (TIFFErrorHandler
));
6982 DEF_DLL_FN (TIFFErrorHandler
, TIFFSetWarningHandler
, (TIFFErrorHandler
));
6983 DEF_DLL_FN (TIFF
*, TIFFOpen
, (const char *, const char *));
6984 DEF_DLL_FN (TIFF
*, TIFFClientOpen
,
6985 (const char *, const char *, thandle_t
, TIFFReadWriteProc
,
6986 TIFFReadWriteProc
, TIFFSeekProc
, TIFFCloseProc
, TIFFSizeProc
,
6987 TIFFMapFileProc
, TIFFUnmapFileProc
));
6988 DEF_DLL_FN (int, TIFFGetField
, (TIFF
*, ttag_t
, ...));
6989 DEF_DLL_FN (int, TIFFReadRGBAImage
, (TIFF
*, uint32
, uint32
, uint32
*, int));
6990 DEF_DLL_FN (void, TIFFClose
, (TIFF
*));
6991 DEF_DLL_FN (int, TIFFSetDirectory
, (TIFF
*, tdir_t
));
6994 init_tiff_functions (void)
6998 if (!(library
= w32_delayed_load (Qtiff
)))
7001 LOAD_DLL_FN (library
, TIFFSetErrorHandler
);
7002 LOAD_DLL_FN (library
, TIFFSetWarningHandler
);
7003 LOAD_DLL_FN (library
, TIFFOpen
);
7004 LOAD_DLL_FN (library
, TIFFClientOpen
);
7005 LOAD_DLL_FN (library
, TIFFGetField
);
7006 LOAD_DLL_FN (library
, TIFFReadRGBAImage
);
7007 LOAD_DLL_FN (library
, TIFFClose
);
7008 LOAD_DLL_FN (library
, TIFFSetDirectory
);
7012 # undef TIFFClientOpen
7014 # undef TIFFGetField
7016 # undef TIFFReadRGBAImage
7017 # undef TIFFSetDirectory
7018 # undef TIFFSetErrorHandler
7019 # undef TIFFSetWarningHandler
7021 # define TIFFClientOpen fn_TIFFClientOpen
7022 # define TIFFClose fn_TIFFClose
7023 # define TIFFGetField fn_TIFFGetField
7024 # define TIFFOpen fn_TIFFOpen
7025 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
7026 # define TIFFSetDirectory fn_TIFFSetDirectory
7027 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
7028 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
7030 # endif /* WINDOWSNT */
7033 /* Reading from a memory buffer for TIFF images Based on the PNG
7034 memory source, but we have to provide a lot of extra functions.
7037 We really only need to implement read and seek, but I am not
7038 convinced that the TIFF library is smart enough not to destroy
7039 itself if we only hand it the function pointers we need to
7044 unsigned char *bytes
;
7051 tiff_read_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7053 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7055 size
= min (size
, src
->len
- src
->index
);
7056 memcpy (buf
, src
->bytes
+ src
->index
, size
);
7062 tiff_write_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
7068 tiff_seek_in_memory (thandle_t data
, toff_t off
, int whence
)
7070 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
7075 case SEEK_SET
: /* Go from beginning of source. */
7079 case SEEK_END
: /* Go from end of source. */
7080 idx
= src
->len
+ off
;
7083 case SEEK_CUR
: /* Go from current position. */
7084 idx
= src
->index
+ off
;
7087 default: /* Invalid `whence'. */
7091 if (idx
> src
->len
|| idx
< 0)
7099 tiff_close_memory (thandle_t data
)
7106 tiff_mmap_memory (thandle_t data
, tdata_t
*pbase
, toff_t
*psize
)
7108 /* It is already _IN_ memory. */
7113 tiff_unmap_memory (thandle_t data
, tdata_t base
, toff_t size
)
7115 /* We don't need to do this. */
7119 tiff_size_of_memory (thandle_t data
)
7121 return ((tiff_memory_source
*) data
)->len
;
7124 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
7125 compiler error compiling tiff_handler, see Bugzilla bug #17406
7126 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
7127 this function as external works around that problem. */
7128 # if defined (__MINGW32__) && __GNUC__ == 3
7129 # define MINGW_STATIC
7131 # define MINGW_STATIC static
7135 tiff_handler (const char *, const char *, const char *, va_list)
7136 ATTRIBUTE_FORMAT_PRINTF (3, 0);
7138 tiff_handler (const char *log_format
, const char *title
,
7139 const char *format
, va_list ap
)
7141 /* doprnt is not suitable here, as TIFF handlers are called from
7142 libtiff and are passed arbitrary printf directives. Instead, use
7143 vsnprintf, taking care to be portable to nonstandard environments
7144 where vsnprintf returns -1 on buffer overflow. Since it's just a
7145 log entry, it's OK to truncate it. */
7147 int len
= vsnprintf (buf
, sizeof buf
, format
, ap
);
7148 add_to_log (log_format
, build_string (title
),
7149 make_string (buf
, max (0, min (len
, sizeof buf
- 1))));
7151 # undef MINGW_STATIC
7153 static void tiff_error_handler (const char *, const char *, va_list)
7154 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7156 tiff_error_handler (const char *title
, const char *format
, va_list ap
)
7158 tiff_handler ("TIFF error: %s %s", title
, format
, ap
);
7162 static void tiff_warning_handler (const char *, const char *, va_list)
7163 ATTRIBUTE_FORMAT_PRINTF (2, 0);
7165 tiff_warning_handler (const char *title
, const char *format
, va_list ap
)
7167 tiff_handler ("TIFF warning: %s %s", title
, format
, ap
);
7171 /* Load TIFF image IMG for use on frame F. Value is true if
7175 tiff_load (struct frame
*f
, struct image
*img
)
7177 Lisp_Object specified_file
;
7178 Lisp_Object specified_data
;
7180 int width
, height
, x
, y
, count
;
7184 tiff_memory_source memsrc
;
7187 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7188 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7190 TIFFSetErrorHandler ((TIFFErrorHandler
) tiff_error_handler
);
7191 TIFFSetWarningHandler ((TIFFErrorHandler
) tiff_warning_handler
);
7193 if (NILP (specified_data
))
7195 /* Read from a file */
7196 Lisp_Object file
= x_find_image_file (specified_file
);
7197 if (!STRINGP (file
))
7199 image_error ("Cannot find image file `%s'", specified_file
);
7203 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7205 encoded_file
= ansi_encode_filename (encoded_file
);
7208 /* Try to open the image file. */
7209 tiff
= TIFFOpen (SSDATA (encoded_file
), "r");
7212 image_error ("Cannot open `%s'", file
);
7218 if (!STRINGP (specified_data
))
7220 image_error ("Invalid image data `%s'", specified_data
);
7224 /* Memory source! */
7225 memsrc
.bytes
= SDATA (specified_data
);
7226 memsrc
.len
= SBYTES (specified_data
);
7229 tiff
= TIFFClientOpen ("memory_source", "r", (thandle_t
)&memsrc
,
7230 tiff_read_from_memory
,
7231 tiff_write_from_memory
,
7232 tiff_seek_in_memory
,
7234 tiff_size_of_memory
,
7240 image_error ("Cannot open memory source for `%s'", img
->spec
);
7245 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
7246 if (INTEGERP (image
))
7248 EMACS_INT ino
= XFASTINT (image
);
7249 if (! (TYPE_MINIMUM (tdir_t
) <= ino
&& ino
<= TYPE_MAXIMUM (tdir_t
)
7250 && TIFFSetDirectory (tiff
, ino
)))
7252 image_error ("Invalid image number `%s' in image `%s'",
7259 /* Get width and height of the image, and allocate a raster buffer
7260 of width x height 32-bit values. */
7261 TIFFGetField (tiff
, TIFFTAG_IMAGEWIDTH
, &width
);
7262 TIFFGetField (tiff
, TIFFTAG_IMAGELENGTH
, &height
);
7264 if (!check_image_size (f
, width
, height
))
7266 image_size_error ();
7271 /* Create the X image and pixmap. */
7272 if (! (height
<= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *buf
/ width
7273 && image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
7280 buf
= xmalloc (sizeof *buf
* width
* height
);
7282 rc
= TIFFReadRGBAImage (tiff
, width
, height
, buf
, 0);
7284 /* Count the number of images in the file. */
7285 for (count
= 1; TIFFSetDirectory (tiff
, count
); count
++)
7289 img
->lisp_data
= Fcons (Qcount
,
7290 Fcons (make_number (count
),
7296 image_error ("Error reading TIFF image `%s'", img
->spec
);
7303 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
7304 uint32_t *dataptr
= (uint32_t *) data
;
7307 for (y
= 0; y
< height
; ++y
)
7309 uint32
*row
= buf
+ (height
- 1 - y
) * width
;
7310 for (x
= 0; x
< width
; ++x
)
7312 uint32 abgr
= row
[x
];
7313 int r
= TIFFGetR (abgr
);
7314 int g
= TIFFGetG (abgr
);
7315 int b
= TIFFGetB (abgr
);
7316 int a
= TIFFGetA (abgr
);
7317 *dataptr
++ = (a
<< 24) | (r
<< 16) | (g
<< 8) | b
;
7321 create_cairo_image_surface (img
, data
, width
, height
);
7324 /* Initialize the color table. */
7325 init_color_table ();
7327 /* Process the pixel raster. Origin is in the lower-left corner. */
7328 for (y
= 0; y
< height
; ++y
)
7330 uint32
*row
= buf
+ y
* width
;
7332 for (x
= 0; x
< width
; ++x
)
7334 uint32 abgr
= row
[x
];
7335 int r
= TIFFGetR (abgr
) << 8;
7336 int g
= TIFFGetG (abgr
) << 8;
7337 int b
= TIFFGetB (abgr
) << 8;
7338 XPutPixel (ximg
, x
, height
- 1 - y
, lookup_rgb_color (f
, r
, g
, b
));
7342 # ifdef COLOR_TABLE_SUPPORT
7343 /* Remember the colors allocated for the image. Free the color table. */
7344 img
->colors
= colors_in_color_table (&img
->ncolors
);
7345 free_color_table ();
7346 # endif /* COLOR_TABLE_SUPPORT */
7349 img
->height
= height
;
7351 /* Maybe fill in the background field while we have ximg handy. */
7352 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7353 /* Casting avoids a GCC warning on W32. */
7354 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7356 /* Put ximg into the image. */
7357 image_put_x_image (f
, img
, ximg
, 0);
7359 #endif /* ! USE_CAIRO */
7365 #elif defined HAVE_NS
7368 tiff_load (struct frame
*f
, struct image
*img
)
7370 return ns_load_image (f
, img
,
7371 image_spec_value (img
->spec
, QCfile
, NULL
),
7372 image_spec_value (img
->spec
, QCdata
, NULL
));
7379 /***********************************************************************
7381 ***********************************************************************/
7383 #if defined (HAVE_GIF) || defined (HAVE_NS)
7385 static bool gif_image_p (Lisp_Object object
);
7386 static bool gif_load (struct frame
*f
, struct image
*img
);
7387 static void gif_clear_image (struct frame
*f
, struct image
*img
);
7389 /* Indices of image specification fields in gif_format, below. */
7391 enum gif_keyword_index
7407 /* Vector of image_keyword structures describing the format
7408 of valid user-defined image specifications. */
7410 static const struct image_keyword gif_format
[GIF_LAST
] =
7412 {":type", IMAGE_SYMBOL_VALUE
, 1},
7413 {":data", IMAGE_STRING_VALUE
, 0},
7414 {":file", IMAGE_STRING_VALUE
, 0},
7415 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7416 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7417 {":relief", IMAGE_INTEGER_VALUE
, 0},
7418 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7419 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7420 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7421 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0},
7422 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
7425 #if defined HAVE_NTGUI && defined WINDOWSNT
7426 static bool init_gif_functions (void);
7428 #define init_gif_functions NULL
7431 /* Structure describing the image type `gif'. */
7433 static struct image_type gif_type
=
7435 SYMBOL_INDEX (Qgif
),
7443 /* Free X resources of GIF image IMG which is used on frame F. */
7446 gif_clear_image (struct frame
*f
, struct image
*img
)
7448 img
->lisp_data
= Qnil
;
7449 x_clear_image (f
, img
);
7452 /* Return true if OBJECT is a valid GIF image specification. */
7455 gif_image_p (Lisp_Object object
)
7457 struct image_keyword fmt
[GIF_LAST
];
7458 memcpy (fmt
, gif_format
, sizeof fmt
);
7460 if (!parse_image_spec (object
, fmt
, GIF_LAST
, Qgif
))
7463 /* Must specify either the :data or :file keyword. */
7464 return fmt
[GIF_FILE
].count
+ fmt
[GIF_DATA
].count
== 1;
7467 #endif /* HAVE_GIF */
7473 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7474 Undefine before redefining to avoid a preprocessor warning. */
7478 /* avoid conflict with QuickdrawText.h */
7479 # define DrawText gif_DrawText
7480 # include <gif_lib.h>
7483 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7484 # ifndef GIFLIB_MINOR
7485 # define GIFLIB_MINOR 0
7487 # ifndef GIFLIB_RELEASE
7488 # define GIFLIB_RELEASE 0
7491 # else /* HAVE_NTGUI */
7493 # include <gif_lib.h>
7495 # endif /* HAVE_NTGUI */
7497 /* Giflib before 5.0 didn't define these macros. */
7498 # ifndef GIFLIB_MAJOR
7499 # define GIFLIB_MAJOR 4
7502 /* GifErrorString is declared to return char const * when GIFLIB_MAJOR
7503 and GIFLIB_MINOR indicate 5.1 or later. Do not bother using it in
7504 earlier releases, where either it returns char * or GIFLIB_MINOR
7505 may be incorrect. */
7506 # define HAVE_GIFERRORSTRING (5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR))
7510 /* GIF library details. */
7511 # if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7512 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*, int *));
7514 DEF_DLL_FN (int, DGifCloseFile
, (GifFileType
*));
7516 DEF_DLL_FN (int, DGifSlurp
, (GifFileType
*));
7517 # if GIFLIB_MAJOR < 5
7518 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
));
7519 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *));
7521 DEF_DLL_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
, int *));
7522 DEF_DLL_FN (GifFileType
*, DGifOpenFileName
, (const char *, int *));
7524 # if HAVE_GIFERRORSTRING
7525 DEF_DLL_FN (char const *, GifErrorString
, (int));
7529 init_gif_functions (void)
7533 if (!(library
= w32_delayed_load (Qgif
)))
7536 LOAD_DLL_FN (library
, DGifCloseFile
);
7537 LOAD_DLL_FN (library
, DGifSlurp
);
7538 LOAD_DLL_FN (library
, DGifOpen
);
7539 LOAD_DLL_FN (library
, DGifOpenFileName
);
7540 # if HAVE_GIFERRORSTRING
7541 LOAD_DLL_FN (library
, GifErrorString
);
7546 # undef DGifCloseFile
7548 # undef DGifOpenFileName
7550 # undef GifErrorString
7552 # define DGifCloseFile fn_DGifCloseFile
7553 # define DGifOpen fn_DGifOpen
7554 # define DGifOpenFileName fn_DGifOpenFileName
7555 # define DGifSlurp fn_DGifSlurp
7556 # define GifErrorString fn_GifErrorString
7558 # endif /* WINDOWSNT */
7560 /* Reading a GIF image from memory
7561 Based on the PNG memory stuff to a certain extent. */
7565 unsigned char *bytes
;
7571 /* Make the current memory source available to gif_read_from_memory.
7572 It's done this way because not all versions of libungif support
7573 a UserData field in the GifFileType structure. */
7574 static gif_memory_source
*current_gif_memory_src
;
7577 gif_read_from_memory (GifFileType
*file
, GifByteType
*buf
, int len
)
7579 gif_memory_source
*src
= current_gif_memory_src
;
7581 if (len
> src
->len
- src
->index
)
7584 memcpy (buf
, src
->bytes
+ src
->index
, len
);
7590 gif_close (GifFileType
*gif
, int *err
)
7594 #if GIFLIB_MAJOR + (GIFLIB_MINOR >= 1) > 5
7595 retval
= DGifCloseFile (gif
, err
);
7597 retval
= DGifCloseFile (gif
);
7598 #if GIFLIB_MAJOR >= 5
7606 /* Load GIF image IMG for use on frame F. Value is true if
7609 static const int interlace_start
[] = {0, 4, 2, 1};
7610 static const int interlace_increment
[] = {8, 8, 4, 2};
7612 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7615 gif_load (struct frame
*f
, struct image
*img
)
7617 int rc
, width
, height
, x
, y
, i
, j
;
7618 ColorMapObject
*gif_color_map
;
7619 unsigned long pixel_colors
[256];
7621 gif_memory_source memsrc
;
7622 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
7623 Lisp_Object specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7624 Lisp_Object specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7625 unsigned long bgcolor
= 0;
7630 unsigned char *data
= 0;
7635 if (NILP (specified_data
))
7637 Lisp_Object file
= x_find_image_file (specified_file
);
7638 if (!STRINGP (file
))
7640 image_error ("Cannot find image file `%s'", specified_file
);
7644 Lisp_Object encoded_file
= ENCODE_FILE (file
);
7646 encoded_file
= ansi_encode_filename (encoded_file
);
7649 /* Open the GIF file. */
7650 #if GIFLIB_MAJOR < 5
7651 gif
= DGifOpenFileName (SSDATA (encoded_file
));
7653 gif
= DGifOpenFileName (SSDATA (encoded_file
), &gif_err
);
7657 #if HAVE_GIFERRORSTRING
7658 image_error ("Cannot open `%s': %s",
7659 file
, build_string (GifErrorString (gif_err
)));
7661 image_error ("Cannot open `%s'", file
);
7668 if (!STRINGP (specified_data
))
7670 image_error ("Invalid image data `%s'", specified_data
);
7674 /* Read from memory! */
7675 current_gif_memory_src
= &memsrc
;
7676 memsrc
.bytes
= SDATA (specified_data
);
7677 memsrc
.len
= SBYTES (specified_data
);
7680 #if GIFLIB_MAJOR < 5
7681 gif
= DGifOpen (&memsrc
, gif_read_from_memory
);
7683 gif
= DGifOpen (&memsrc
, gif_read_from_memory
, &gif_err
);
7687 #if HAVE_GIFERRORSTRING
7688 image_error ("Cannot open memory source `%s': %s",
7689 img
->spec
, build_string (GifErrorString (gif_err
)));
7691 image_error ("Cannot open memory source `%s'", img
->spec
);
7697 /* Before reading entire contents, check the declared image size. */
7698 if (!check_image_size (f
, gif
->SWidth
, gif
->SHeight
))
7700 image_size_error ();
7701 gif_close (gif
, NULL
);
7705 /* Read entire contents. */
7706 rc
= DGifSlurp (gif
);
7707 if (rc
== GIF_ERROR
|| gif
->ImageCount
<= 0)
7709 image_error ("Error reading `%s'", img
->spec
);
7710 gif_close (gif
, NULL
);
7714 /* Which sub-image are we to display? */
7716 Lisp_Object image_number
= image_spec_value (img
->spec
, QCindex
, NULL
);
7717 idx
= INTEGERP (image_number
) ? XFASTINT (image_number
) : 0;
7718 if (idx
< 0 || idx
>= gif
->ImageCount
)
7720 image_error ("Invalid image number `%s' in image `%s'",
7721 image_number
, img
->spec
);
7722 gif_close (gif
, NULL
);
7727 width
= img
->width
= gif
->SWidth
;
7728 height
= img
->height
= gif
->SHeight
;
7730 img
->corners
[TOP_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Top
;
7731 img
->corners
[LEFT_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Left
;
7732 img
->corners
[BOT_CORNER
]
7733 = img
->corners
[TOP_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Height
;
7734 img
->corners
[RIGHT_CORNER
]
7735 = img
->corners
[LEFT_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Width
;
7737 if (!check_image_size (f
, width
, height
))
7739 image_size_error ();
7740 gif_close (gif
, NULL
);
7744 /* Check that the selected subimages fit. It's not clear whether
7745 the GIF spec requires this, but Emacs can crash if they don't fit. */
7746 for (j
= 0; j
<= idx
; ++j
)
7748 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7749 int subimg_width
= subimage
->ImageDesc
.Width
;
7750 int subimg_height
= subimage
->ImageDesc
.Height
;
7751 int subimg_top
= subimage
->ImageDesc
.Top
;
7752 int subimg_left
= subimage
->ImageDesc
.Left
;
7753 if (! (subimg_width
>= 0 && subimg_height
>= 0
7754 && 0 <= subimg_top
&& subimg_top
<= height
- subimg_height
7755 && 0 <= subimg_left
&& subimg_left
<= width
- subimg_width
))
7757 image_error ("Subimage does not fit in image");
7758 gif_close (gif
, NULL
);
7764 /* xzalloc so data is zero => transparent */
7765 data
= (unsigned char *) xzalloc (width
* height
* 4);
7766 if (STRINGP (specified_bg
))
7769 if (x_defined_color (f
, SSDATA (specified_bg
), &color
, 0))
7771 uint32_t *dataptr
= (uint32_t *)data
;
7772 int r
= color
.red
/256;
7773 int g
= color
.green
/256;
7774 int b
= color
.blue
/256;
7776 for (y
= 0; y
< height
; ++y
)
7777 for (x
= 0; x
< width
; ++x
)
7778 *dataptr
++ = (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7782 /* Create the X image and pixmap. */
7783 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
7785 gif_close (gif
, NULL
);
7789 /* Clear the part of the screen image not covered by the image.
7790 Full animated GIF support requires more here (see the gif89 spec,
7791 disposal methods). Let's simply assume that the part not covered
7792 by a sub-image is in the frame's background color. */
7793 for (y
= 0; y
< img
->corners
[TOP_CORNER
]; ++y
)
7794 for (x
= 0; x
< width
; ++x
)
7795 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7797 for (y
= img
->corners
[BOT_CORNER
]; y
< height
; ++y
)
7798 for (x
= 0; x
< width
; ++x
)
7799 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7801 for (y
= img
->corners
[TOP_CORNER
]; y
< img
->corners
[BOT_CORNER
]; ++y
)
7803 for (x
= 0; x
< img
->corners
[LEFT_CORNER
]; ++x
)
7804 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7805 for (x
= img
->corners
[RIGHT_CORNER
]; x
< width
; ++x
)
7806 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7810 /* Read the GIF image into the X image. */
7812 /* FIXME: With the current implementation, loading an animated gif
7813 is quadratic in the number of animation frames, since each frame
7814 is a separate struct image. We must provide a way for a single
7815 gif_load call to construct and save all animation frames. */
7817 init_color_table ();
7818 if (STRINGP (specified_bg
))
7819 bgcolor
= x_alloc_image_color (f
, img
, specified_bg
,
7820 FRAME_BACKGROUND_PIXEL (f
));
7821 for (j
= 0; j
<= idx
; ++j
)
7823 /* We use a local variable `raster' here because RasterBits is a
7824 char *, which invites problems with bytes >= 0x80. */
7825 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7826 unsigned char *raster
= (unsigned char *) subimage
->RasterBits
;
7827 int transparency_color_index
= -1;
7829 int subimg_width
= subimage
->ImageDesc
.Width
;
7830 int subimg_height
= subimage
->ImageDesc
.Height
;
7831 int subimg_top
= subimage
->ImageDesc
.Top
;
7832 int subimg_left
= subimage
->ImageDesc
.Left
;
7834 /* Find the Graphic Control Extension block for this sub-image.
7835 Extract the disposal method and transparency color. */
7836 for (i
= 0; i
< subimage
->ExtensionBlockCount
; i
++)
7838 ExtensionBlock
*extblock
= subimage
->ExtensionBlocks
+ i
;
7840 if ((extblock
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
)
7841 && extblock
->ByteCount
== 4
7842 && extblock
->Bytes
[0] & 1)
7844 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7845 to background". Treat any other value like 2. */
7846 disposal
= (extblock
->Bytes
[0] >> 2) & 7;
7847 transparency_color_index
= (unsigned char) extblock
->Bytes
[3];
7852 /* We can't "keep in place" the first subimage. */
7856 /* For disposal == 0, the spec says "No disposal specified. The
7857 decoder is not required to take any action." In practice, it
7858 seems we need to treat this like "keep in place", see e.g.
7859 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7863 gif_color_map
= subimage
->ImageDesc
.ColorMap
;
7865 gif_color_map
= gif
->SColorMap
;
7868 /* Allocate subimage colors. */
7869 memset (pixel_colors
, 0, sizeof pixel_colors
);
7872 for (i
= 0; i
< gif_color_map
->ColorCount
; ++i
)
7874 if (transparency_color_index
== i
)
7875 pixel_colors
[i
] = STRINGP (specified_bg
)
7876 ? bgcolor
: FRAME_BACKGROUND_PIXEL (f
);
7879 int r
= gif_color_map
->Colors
[i
].Red
<< 8;
7880 int g
= gif_color_map
->Colors
[i
].Green
<< 8;
7881 int b
= gif_color_map
->Colors
[i
].Blue
<< 8;
7882 pixel_colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
7887 /* Apply the pixel values. */
7888 if (GIFLIB_MAJOR
< 5 && gif
->SavedImages
[j
].ImageDesc
.Interlace
)
7892 for (y
= 0, row
= interlace_start
[0], pass
= 0;
7894 y
++, row
+= interlace_increment
[pass
])
7896 while (subimg_height
<= row
)
7897 row
= interlace_start
[++pass
];
7899 for (x
= 0; x
< subimg_width
; x
++)
7901 int c
= raster
[y
* subimg_width
+ x
];
7902 if (transparency_color_index
!= c
|| disposal
!= 1)
7906 ((uint32_t*)data
+ ((row
+ subimg_top
) * subimg_width
7907 + x
+ subimg_left
));
7908 int r
= gif_color_map
->Colors
[c
].Red
;
7909 int g
= gif_color_map
->Colors
[c
].Green
;
7910 int b
= gif_color_map
->Colors
[c
].Blue
;
7912 if (transparency_color_index
!= c
)
7913 *dataptr
= (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7915 XPutPixel (ximg
, x
+ subimg_left
, row
+ subimg_top
,
7924 for (y
= 0; y
< subimg_height
; ++y
)
7925 for (x
= 0; x
< subimg_width
; ++x
)
7927 int c
= raster
[y
* subimg_width
+ x
];
7928 if (transparency_color_index
!= c
|| disposal
!= 1)
7932 ((uint32_t*)data
+ ((y
+ subimg_top
) * subimg_width
7933 + x
+ subimg_left
));
7934 int r
= gif_color_map
->Colors
[c
].Red
;
7935 int g
= gif_color_map
->Colors
[c
].Green
;
7936 int b
= gif_color_map
->Colors
[c
].Blue
;
7937 if (transparency_color_index
!= c
)
7938 *dataptr
= (0xff << 24) | (r
<< 16) | (g
<< 8) | b
;
7940 XPutPixel (ximg
, x
+ subimg_left
, y
+ subimg_top
,
7948 #ifdef COLOR_TABLE_SUPPORT
7949 img
->colors
= colors_in_color_table (&img
->ncolors
);
7950 free_color_table ();
7951 #endif /* COLOR_TABLE_SUPPORT */
7953 /* Save GIF image extension data for `image-metadata'.
7954 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7955 img
->lisp_data
= Qnil
;
7956 if (gif
->SavedImages
[idx
].ExtensionBlockCount
> 0)
7959 ExtensionBlock
*ext
= gif
->SavedImages
[idx
].ExtensionBlocks
;
7960 for (i
= 0; i
< gif
->SavedImages
[idx
].ExtensionBlockCount
; i
++, ext
++)
7961 /* Append (... FUNCTION "BYTES") */
7964 = Fcons (make_number (ext
->Function
),
7965 Fcons (make_unibyte_string (ext
->Bytes
, ext
->ByteCount
),
7967 if (ext
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
7968 && ext
->ByteCount
== 4)
7970 delay
= ext
->Bytes
[2] << CHAR_BIT
;
7971 delay
|= ext
->Bytes
[1];
7974 img
->lisp_data
= list2 (Qextension_data
, img
->lisp_data
);
7978 Fcons (make_float (delay
/ 100.0),
7982 if (gif
->ImageCount
> 1)
7983 img
->lisp_data
= Fcons (Qcount
,
7984 Fcons (make_number (gif
->ImageCount
),
7987 if (gif_close (gif
, &gif_err
) == GIF_ERROR
)
7989 #if HAVE_GIFERRORSTRING
7990 char const *error_text
= GifErrorString (gif_err
);
7993 image_error ("Error closing `%s': %s",
7994 img
->spec
, build_string (error_text
));
7996 image_error ("Error closing `%s'", img
->spec
);
8001 create_cairo_image_surface (img
, data
, width
, height
);
8003 /* Maybe fill in the background field while we have ximg handy. */
8004 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
8005 /* Casting avoids a GCC warning. */
8006 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
8008 /* Put ximg into the image. */
8009 image_put_x_image (f
, img
, ximg
, 0);
8015 #else /* !HAVE_GIF */
8019 gif_load (struct frame
*f
, struct image
*img
)
8021 return ns_load_image (f
, img
,
8022 image_spec_value (img
->spec
, QCfile
, NULL
),
8023 image_spec_value (img
->spec
, QCdata
, NULL
));
8025 #endif /* HAVE_NS */
8027 #endif /* HAVE_GIF */
8030 #ifdef HAVE_IMAGEMAGICK
8032 /***********************************************************************
8034 ***********************************************************************/
8036 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
8037 safely rounded and clipped to int range. */
8040 scale_image_size (int size
, size_t divisor
, size_t multiplier
)
8045 double scaled
= s
* multiplier
/ divisor
+ 0.5;
8046 if (scaled
< INT_MAX
)
8052 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
8053 Use SPEC to deduce the size. Store the desired size into
8054 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
8056 compute_image_size (size_t width
, size_t height
,
8058 int *d_width
, int *d_height
)
8061 int desired_width
, desired_height
;
8063 /* If width and/or height is set in the display spec assume we want
8064 to scale to those values. If either h or w is unspecified, the
8065 unspecified should be calculated from the specified to preserve
8067 value
= image_spec_value (spec
, QCwidth
, NULL
);
8068 desired_width
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
8069 value
= image_spec_value (spec
, QCheight
, NULL
);
8070 desired_height
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
8072 if (desired_width
== -1)
8074 value
= image_spec_value (spec
, QCmax_width
, NULL
);
8075 if (NATNUMP (value
))
8077 int max_width
= min (XFASTINT (value
), INT_MAX
);
8078 if (max_width
< width
)
8080 /* The image is wider than :max-width. */
8081 desired_width
= max_width
;
8082 if (desired_height
== -1)
8084 desired_height
= scale_image_size (desired_width
,
8086 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8087 if (NATNUMP (value
))
8089 int max_height
= min (XFASTINT (value
), INT_MAX
);
8090 if (max_height
< desired_height
)
8092 desired_height
= max_height
;
8093 desired_width
= scale_image_size (desired_height
,
8102 if (desired_height
== -1)
8104 value
= image_spec_value (spec
, QCmax_height
, NULL
);
8105 if (NATNUMP (value
))
8107 int max_height
= min (XFASTINT (value
), INT_MAX
);
8108 if (max_height
< height
)
8109 desired_height
= max_height
;
8113 if (desired_width
!= -1 && desired_height
== -1)
8114 /* w known, calculate h. */
8115 desired_height
= scale_image_size (desired_width
, width
, height
);
8117 if (desired_width
== -1 && desired_height
!= -1)
8118 /* h known, calculate w. */
8119 desired_width
= scale_image_size (desired_height
, height
, width
);
8121 *d_width
= desired_width
;
8122 *d_height
= desired_height
;
8125 static bool imagemagick_image_p (Lisp_Object
);
8126 static bool imagemagick_load (struct frame
*, struct image
*);
8127 static void imagemagick_clear_image (struct frame
*, struct image
*);
8129 /* Indices of image specification fields in imagemagick_format. */
8131 enum imagemagick_keyword_index
8139 IMAGEMAGICK_ALGORITHM
,
8140 IMAGEMAGICK_HEURISTIC_MASK
,
8142 IMAGEMAGICK_BACKGROUND
,
8145 IMAGEMAGICK_MAX_HEIGHT
,
8146 IMAGEMAGICK_MAX_WIDTH
,
8148 IMAGEMAGICK_ROTATION
,
8153 /* Vector of image_keyword structures describing the format
8154 of valid user-defined image specifications. */
8156 static struct image_keyword imagemagick_format
[IMAGEMAGICK_LAST
] =
8158 {":type", IMAGE_SYMBOL_VALUE
, 1},
8159 {":data", IMAGE_STRING_VALUE
, 0},
8160 {":file", IMAGE_STRING_VALUE
, 0},
8161 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8162 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8163 {":relief", IMAGE_INTEGER_VALUE
, 0},
8164 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8165 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8166 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8167 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
8168 {":height", IMAGE_INTEGER_VALUE
, 0},
8169 {":width", IMAGE_INTEGER_VALUE
, 0},
8170 {":max-height", IMAGE_INTEGER_VALUE
, 0},
8171 {":max-width", IMAGE_INTEGER_VALUE
, 0},
8172 {":format", IMAGE_SYMBOL_VALUE
, 0},
8173 {":rotation", IMAGE_NUMBER_VALUE
, 0},
8174 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
8177 #if defined HAVE_NTGUI && defined WINDOWSNT
8178 static bool init_imagemagick_functions (void);
8180 #define init_imagemagick_functions NULL
8183 /* Structure describing the image type for any image handled via
8186 static struct image_type imagemagick_type
=
8188 SYMBOL_INDEX (Qimagemagick
),
8189 imagemagick_image_p
,
8191 imagemagick_clear_image
,
8192 init_imagemagick_functions
,
8196 /* Free X resources of imagemagick image IMG which is used on frame F. */
8199 imagemagick_clear_image (struct frame
*f
,
8202 x_clear_image (f
, img
);
8205 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
8206 this by calling parse_image_spec and supplying the keywords that
8207 identify the IMAGEMAGICK format. */
8210 imagemagick_image_p (Lisp_Object object
)
8212 struct image_keyword fmt
[IMAGEMAGICK_LAST
];
8213 memcpy (fmt
, imagemagick_format
, sizeof fmt
);
8215 if (!parse_image_spec (object
, fmt
, IMAGEMAGICK_LAST
, Qimagemagick
))
8218 /* Must specify either the :data or :file keyword. */
8219 return fmt
[IMAGEMAGICK_FILE
].count
+ fmt
[IMAGEMAGICK_DATA
].count
== 1;
8222 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
8223 Therefore rename the function so it doesn't collide with ImageMagick. */
8224 #define DrawRectangle DrawRectangleGif
8225 #include <wand/MagickWand.h>
8227 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
8228 Emacs seems to work fine with the hidden version, so unhide it. */
8229 #include <magick/version.h>
8230 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
8231 extern WandExport
void PixelGetMagickColor (const PixelWand
*,
8232 MagickPixelPacket
*);
8235 /* Log ImageMagick error message.
8236 Useful when a ImageMagick function returns the status `MagickFalse'. */
8239 imagemagick_error (MagickWand
*wand
)
8242 ExceptionType severity
;
8244 description
= MagickGetException (wand
, &severity
);
8245 image_error ("ImageMagick error: %s", build_string (description
));
8246 MagickRelinquishMemory (description
);
8249 /* Possibly give ImageMagick some extra help to determine the image
8250 type by supplying a "dummy" filename based on the Content-Type. */
8253 imagemagick_filename_hint (Lisp_Object spec
, char hint_buffer
[MaxTextExtent
])
8255 Lisp_Object symbol
= intern ("image-format-suffixes");
8256 Lisp_Object val
= find_symbol_value (symbol
);
8262 format
= image_spec_value (spec
, intern (":format"), NULL
);
8263 val
= Fcar_safe (Fcdr_safe (Fassq (format
, val
)));
8264 if (! STRINGP (val
))
8267 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
8268 as ImageMagick would ignore the extra bytes anyway. */
8269 snprintf (hint_buffer
, MaxTextExtent
, "/tmp/foo.%s", SSDATA (val
));
8273 /* Animated images (e.g., GIF89a) are composed from one "master image"
8274 (which is the first one, and then there's a number of images that
8275 follow. If following images have non-transparent colors, these are
8276 composed "on top" of the master image. So, in general, one has to
8277 compute ann the preceding images to be able to display a particular
8280 Computing all the preceding images is too slow, so we maintain a
8281 cache of previously computed images. We have to maintain a cache
8282 separate from the image cache, because the images may be scaled
8285 struct animation_cache
8289 struct timespec update_time
;
8290 struct animation_cache
*next
;
8291 char signature
[FLEXIBLE_ARRAY_MEMBER
];
8294 static struct animation_cache
*animation_cache
= NULL
;
8296 static struct animation_cache
*
8297 imagemagick_create_cache (char *signature
)
8299 struct animation_cache
*cache
8300 = xmalloc (offsetof (struct animation_cache
, signature
)
8301 + strlen (signature
) + 1);
8305 strcpy (cache
->signature
, signature
);
8309 /* Discard cached images that haven't been used for a minute. */
8311 imagemagick_prune_animation_cache (void)
8313 struct animation_cache
**pcache
= &animation_cache
;
8314 struct timespec old
= timespec_sub (current_timespec (),
8315 make_timespec (60, 0));
8319 struct animation_cache
*cache
= *pcache
;
8320 if (timespec_cmp (old
, cache
->update_time
) <= 0)
8321 pcache
= &cache
->next
;
8325 DestroyMagickWand (cache
->wand
);
8326 *pcache
= cache
->next
;
8332 static struct animation_cache
*
8333 imagemagick_get_animation_cache (MagickWand
*wand
)
8335 char *signature
= MagickGetImageSignature (wand
);
8336 struct animation_cache
*cache
;
8337 struct animation_cache
**pcache
= &animation_cache
;
8339 imagemagick_prune_animation_cache ();
8346 *pcache
= cache
= imagemagick_create_cache (signature
);
8349 if (strcmp (signature
, cache
->signature
) == 0)
8351 pcache
= &cache
->next
;
8354 DestroyString (signature
);
8355 cache
->update_time
= current_timespec ();
8360 imagemagick_compute_animated_image (MagickWand
*super_wand
, int ino
)
8363 MagickWand
*composite_wand
;
8364 size_t dest_width
, dest_height
;
8365 struct animation_cache
*cache
= imagemagick_get_animation_cache (super_wand
);
8367 MagickSetIteratorIndex (super_wand
, 0);
8369 if (ino
== 0 || cache
->wand
== NULL
|| cache
->index
> ino
)
8371 composite_wand
= MagickGetImage (super_wand
);
8373 DestroyMagickWand (cache
->wand
);
8376 composite_wand
= cache
->wand
;
8378 dest_height
= MagickGetImageHeight (composite_wand
);
8380 for (i
= max (1, cache
->index
+ 1); i
<= ino
; i
++)
8382 MagickWand
*sub_wand
;
8383 PixelIterator
*source_iterator
, *dest_iterator
;
8384 PixelWand
**source
, **dest
;
8385 size_t source_width
, source_height
;
8386 ssize_t source_left
, source_top
;
8387 MagickPixelPacket pixel
;
8388 DisposeType dispose
;
8389 ptrdiff_t lines
= 0;
8391 MagickSetIteratorIndex (super_wand
, i
);
8392 sub_wand
= MagickGetImage (super_wand
);
8394 MagickGetImagePage (sub_wand
, &source_width
, &source_height
,
8395 &source_left
, &source_top
);
8397 /* This flag says how to handle transparent pixels. */
8398 dispose
= MagickGetImageDispose (sub_wand
);
8400 source_iterator
= NewPixelIterator (sub_wand
);
8401 if (! source_iterator
)
8403 DestroyMagickWand (composite_wand
);
8404 DestroyMagickWand (sub_wand
);
8406 image_error ("Imagemagick pixel iterator creation failed");
8410 dest_iterator
= NewPixelIterator (composite_wand
);
8411 if (! dest_iterator
)
8413 DestroyMagickWand (composite_wand
);
8414 DestroyMagickWand (sub_wand
);
8415 DestroyPixelIterator (source_iterator
);
8417 image_error ("Imagemagick pixel iterator creation failed");
8421 /* The sub-image may not start at origin, so move the destination
8422 iterator to where the sub-image should start. */
8425 PixelSetIteratorRow (dest_iterator
, source_top
);
8429 while ((source
= PixelGetNextIteratorRow (source_iterator
, &source_width
))
8434 /* Sanity check. This shouldn't happen, but apparently
8435 does in some pictures. */
8436 if (++lines
>= dest_height
)
8439 dest
= PixelGetNextIteratorRow (dest_iterator
, &dest_width
);
8440 for (x
= 0; x
< source_width
; x
++)
8442 /* Sanity check. This shouldn't happen, but apparently
8443 also does in some pictures. */
8444 if (x
+ source_left
>= dest_width
)
8446 /* Normally we only copy over non-transparent pixels,
8447 but if the disposal method is "Background", then we
8448 copy over all pixels. */
8449 if (dispose
== BackgroundDispose
|| PixelGetAlpha (source
[x
]))
8451 PixelGetMagickColor (source
[x
], &pixel
);
8452 PixelSetMagickColor (dest
[x
+ source_left
], &pixel
);
8455 PixelSyncIterator (dest_iterator
);
8458 DestroyPixelIterator (source_iterator
);
8459 DestroyPixelIterator (dest_iterator
);
8460 DestroyMagickWand (sub_wand
);
8463 /* Cache a copy for the next iteration. The current wand will be
8464 destroyed by the caller. */
8465 cache
->wand
= CloneMagickWand (composite_wand
);
8468 return composite_wand
;
8472 /* Helper function for imagemagick_load, which does the actual loading
8473 given contents and size, apart from frame and image structures,
8474 passed from imagemagick_load. Uses librimagemagick to do most of
8475 the image processing.
8477 F is a pointer to the Emacs frame; IMG to the image structure to
8478 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8479 be parsed; SIZE is the number of bytes of data; and FILENAME is
8480 either the file name or the image data.
8482 Return true if successful. */
8485 imagemagick_load_image (struct frame
*f
, struct image
*img
,
8486 unsigned char *contents
, unsigned int size
,
8490 size_t image_width
, image_height
;
8491 MagickBooleanType status
;
8494 MagickWand
*image_wand
;
8495 PixelIterator
*iterator
;
8496 PixelWand
**pixels
, *bg_wand
= NULL
;
8497 MagickPixelPacket pixel
;
8502 int desired_width
, desired_height
;
8505 char hint_buffer
[MaxTextExtent
];
8506 char *filename_hint
= NULL
;
8508 /* Handle image index for image types who can contain more than one image.
8509 Interface :index is same as for GIF. First we "ping" the image to see how
8510 many sub-images it contains. Pinging is faster than loading the image to
8511 find out things about it. */
8513 /* Initialize the imagemagick environment. */
8514 MagickWandGenesis ();
8515 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
8516 ino
= INTEGERP (image
) ? XFASTINT (image
) : 0;
8517 image_wand
= NewMagickWand ();
8520 status
= MagickReadImage (image_wand
, filename
);
8523 filename_hint
= imagemagick_filename_hint (img
->spec
, hint_buffer
);
8524 MagickSetFilename (image_wand
, filename_hint
);
8525 status
= MagickReadImageBlob (image_wand
, contents
, size
);
8528 if (status
== MagickFalse
)
8530 imagemagick_error (image_wand
);
8531 DestroyMagickWand (image_wand
);
8535 if (ino
< 0 || ino
>= MagickGetNumberImages (image_wand
))
8537 image_error ("Invalid image number `%s' in image `%s'", image
, img
->spec
);
8538 DestroyMagickWand (image_wand
);
8542 if (MagickGetImageDelay (image_wand
) > 0)
8545 Fcons (make_float (MagickGetImageDelay (image_wand
) / 100.0),
8548 if (MagickGetNumberImages (image_wand
) > 1)
8551 Fcons (make_number (MagickGetNumberImages (image_wand
)),
8554 /* If we have an animated image, get the new wand based on the
8556 if (MagickGetNumberImages (image_wand
) > 1)
8558 MagickWand
*super_wand
= image_wand
;
8559 image_wand
= imagemagick_compute_animated_image (super_wand
, ino
);
8561 image_wand
= super_wand
;
8563 DestroyMagickWand (super_wand
);
8566 /* Retrieve the frame's background color, for use later. */
8569 Lisp_Object specified_bg
;
8571 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8572 if (!STRINGP (specified_bg
)
8573 || !x_defined_color (f
, SSDATA (specified_bg
), &bgcolor
, 0))
8574 x_query_frame_background_color (f
, &bgcolor
);
8576 bg_wand
= NewPixelWand ();
8577 PixelSetRed (bg_wand
, (double) bgcolor
.red
/ 65535);
8578 PixelSetGreen (bg_wand
, (double) bgcolor
.green
/ 65535);
8579 PixelSetBlue (bg_wand
, (double) bgcolor
.blue
/ 65535);
8582 compute_image_size (MagickGetImageWidth (image_wand
),
8583 MagickGetImageHeight (image_wand
),
8584 img
->spec
, &desired_width
, &desired_height
);
8586 if (desired_width
!= -1 && desired_height
!= -1)
8588 status
= MagickScaleImage (image_wand
, desired_width
, desired_height
);
8589 if (status
== MagickFalse
)
8591 image_error ("Imagemagick scale failed");
8592 imagemagick_error (image_wand
);
8593 goto imagemagick_error
;
8597 /* crop behaves similar to image slicing in Emacs but is more memory
8599 crop
= image_spec_value (img
->spec
, QCcrop
, NULL
);
8601 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8603 /* After some testing, it seems MagickCropImage is the fastest crop
8604 function in ImageMagick. This crop function seems to do less copying
8605 than the alternatives, but it still reads the entire image into memory
8606 before cropping, which is apparently difficult to avoid when using
8608 size_t crop_width
= XINT (XCAR (crop
));
8610 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8612 size_t crop_height
= XINT (XCAR (crop
));
8614 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8616 ssize_t crop_x
= XINT (XCAR (crop
));
8618 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8620 ssize_t crop_y
= XINT (XCAR (crop
));
8621 MagickCropImage (image_wand
, crop_width
, crop_height
,
8628 /* Furthermore :rotation. we need background color and angle for
8631 TODO background handling for rotation specified_bg =
8632 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8634 value
= image_spec_value (img
->spec
, QCrotation
, NULL
);
8637 rotation
= extract_float (value
);
8638 status
= MagickRotateImage (image_wand
, bg_wand
, rotation
);
8639 if (status
== MagickFalse
)
8641 image_error ("Imagemagick image rotate failed");
8642 imagemagick_error (image_wand
);
8643 goto imagemagick_error
;
8647 /* Set the canvas background color to the frame or specified
8648 background, and flatten the image. Note: as of ImageMagick
8649 6.6.0, SVG image transparency is not handled properly
8650 (e.g. etc/images/splash.svg shows a white background always). */
8652 MagickWand
*new_wand
;
8653 MagickSetImageBackgroundColor (image_wand
, bg_wand
);
8654 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8655 new_wand
= MagickMergeImageLayers (image_wand
, MergeLayer
);
8657 new_wand
= MagickFlattenImages (image_wand
);
8659 DestroyMagickWand (image_wand
);
8660 image_wand
= new_wand
;
8663 /* Finally we are done manipulating the image. Figure out the
8664 resulting width/height and transfer ownership to Emacs. */
8665 image_height
= MagickGetImageHeight (image_wand
);
8666 image_width
= MagickGetImageWidth (image_wand
);
8668 if (! (image_width
<= INT_MAX
&& image_height
<= INT_MAX
8669 && check_image_size (f
, image_width
, image_height
)))
8671 image_size_error ();
8672 goto imagemagick_error
;
8675 width
= image_width
;
8676 height
= image_height
;
8678 /* We can now get a valid pixel buffer from the imagemagick file, if all
8681 init_color_table ();
8683 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8684 if (imagemagick_render_type
!= 0)
8686 /* Magicexportimage is normally faster than pixelpushing. This
8687 method is also well tested. Some aspects of this method are
8688 ad-hoc and needs to be more researched. */
8689 int imagedepth
= 24; /*MagickGetImageDepth(image_wand);*/
8690 const char *exportdepth
= imagedepth
<= 8 ? "I" : "BGRP"; /*"RGBP";*/
8691 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8692 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, imagedepth
,
8695 #ifdef COLOR_TABLE_SUPPORT
8696 free_color_table ();
8698 image_error ("Imagemagick X bitmap allocation failure");
8699 goto imagemagick_error
;
8702 /* Oddly, the below code doesn't seem to work:*/
8703 /* switch(ximg->bitmap_unit){ */
8705 /* pixelwidth=CharPixel; */
8708 /* pixelwidth=ShortPixel; */
8711 /* pixelwidth=LongPixel; */
8715 Here im just guessing the format of the bitmap.
8716 happens to work fine for:
8719 seems about 3 times as fast as pixel pushing(not carefully measured)
8721 pixelwidth
= CharPixel
; /*??? TODO figure out*/
8722 MagickExportImagePixels (image_wand
, 0, 0, width
, height
,
8723 exportdepth
, pixelwidth
, ximg
->data
);
8726 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8728 size_t image_height
;
8729 MagickRealType color_scale
= 65535.0 / QuantumRange
;
8731 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8732 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
8735 #ifdef COLOR_TABLE_SUPPORT
8736 free_color_table ();
8738 image_error ("Imagemagick X bitmap allocation failure");
8739 goto imagemagick_error
;
8742 /* Copy imagemagick image to x with primitive yet robust pixel
8743 pusher loop. This has been tested a lot with many different
8746 /* Copy pixels from the imagemagick image structure to the x image map. */
8747 iterator
= NewPixelIterator (image_wand
);
8750 #ifdef COLOR_TABLE_SUPPORT
8751 free_color_table ();
8753 x_destroy_x_image (ximg
);
8754 image_error ("Imagemagick pixel iterator creation failed");
8755 goto imagemagick_error
;
8758 image_height
= MagickGetImageHeight (image_wand
);
8759 for (y
= 0; y
< image_height
; y
++)
8762 pixels
= PixelGetNextIteratorRow (iterator
, &row_width
);
8765 int xlim
= min (row_width
, width
);
8766 for (x
= 0; x
< xlim
; x
++)
8768 PixelGetMagickColor (pixels
[x
], &pixel
);
8769 XPutPixel (ximg
, x
, y
,
8770 lookup_rgb_color (f
,
8771 color_scale
* pixel
.red
,
8772 color_scale
* pixel
.green
,
8773 color_scale
* pixel
.blue
));
8776 DestroyPixelIterator (iterator
);
8779 #ifdef COLOR_TABLE_SUPPORT
8780 /* Remember colors allocated for this image. */
8781 img
->colors
= colors_in_color_table (&img
->ncolors
);
8782 free_color_table ();
8783 #endif /* COLOR_TABLE_SUPPORT */
8786 img
->height
= height
;
8788 /* Put ximg into the image. */
8789 image_put_x_image (f
, img
, ximg
, 0);
8791 /* Final cleanup. image_wand should be the only resource left. */
8792 DestroyMagickWand (image_wand
);
8793 if (bg_wand
) DestroyPixelWand (bg_wand
);
8795 /* `MagickWandTerminus' terminates the imagemagick environment. */
8796 MagickWandTerminus ();
8801 DestroyMagickWand (image_wand
);
8802 if (bg_wand
) DestroyPixelWand (bg_wand
);
8804 MagickWandTerminus ();
8805 /* TODO more cleanup. */
8806 image_error ("Error parsing IMAGEMAGICK image `%s'", img
->spec
);
8811 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8812 successful. this function will go into the imagemagick_type structure, and
8813 the prototype thus needs to be compatible with that structure. */
8816 imagemagick_load (struct frame
*f
, struct image
*img
)
8819 Lisp_Object file_name
;
8821 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8822 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8823 if (STRINGP (file_name
))
8825 Lisp_Object file
= x_find_image_file (file_name
);
8826 if (!STRINGP (file
))
8828 image_error ("Cannot find image file `%s'", file_name
);
8831 file
= ENCODE_FILE (file
);
8833 file
= ansi_encode_filename (file
);
8835 success_p
= imagemagick_load_image (f
, img
, 0, 0, SSDATA (file
));
8837 /* Else its not a file, its a lisp object. Load the image from a
8838 lisp object rather than a file. */
8843 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8844 if (!STRINGP (data
))
8846 image_error ("Invalid image data `%s'", data
);
8849 success_p
= imagemagick_load_image (f
, img
, SDATA (data
),
8850 SBYTES (data
), NULL
);
8856 DEFUN ("imagemagick-types", Fimagemagick_types
, Simagemagick_types
, 0, 0, 0,
8857 doc
: /* Return a list of image types supported by ImageMagick.
8858 Each entry in this list is a symbol named after an ImageMagick format
8859 tag. See the ImageMagick manual for a list of ImageMagick formats and
8860 their descriptions (http://www.imagemagick.org/script/formats.php).
8861 You can also try the shell command: `identify -list format'.
8863 Note that ImageMagick recognizes many file-types that Emacs does not
8864 recognize as images, such as C. See `imagemagick-types-enable'
8865 and `imagemagick-types-inhibit'. */)
8868 Lisp_Object typelist
= Qnil
;
8874 GetExceptionInfo(&ex
);
8875 imtypes
= GetMagickList ("*", &numf
, &ex
);
8876 DestroyExceptionInfo(&ex
);
8878 for (i
= 0; i
< numf
; i
++)
8880 Lisp_Object imagemagicktype
= intern (imtypes
[i
]);
8881 typelist
= Fcons (imagemagicktype
, typelist
);
8882 imtypes
[i
] = MagickRelinquishMemory (imtypes
[i
]);
8885 MagickRelinquishMemory (imtypes
);
8886 return Fnreverse (typelist
);
8889 #endif /* defined (HAVE_IMAGEMAGICK) */
8893 /***********************************************************************
8895 ***********************************************************************/
8899 /* Function prototypes. */
8901 static bool svg_image_p (Lisp_Object object
);
8902 static bool svg_load (struct frame
*f
, struct image
*img
);
8904 static bool svg_load_image (struct frame
*, struct image
*,
8905 unsigned char *, ptrdiff_t, char *);
8907 /* Indices of image specification fields in svg_format, below. */
8909 enum svg_keyword_index
8924 /* Vector of image_keyword structures describing the format
8925 of valid user-defined image specifications. */
8927 static const struct image_keyword svg_format
[SVG_LAST
] =
8929 {":type", IMAGE_SYMBOL_VALUE
, 1},
8930 {":data", IMAGE_STRING_VALUE
, 0},
8931 {":file", IMAGE_STRING_VALUE
, 0},
8932 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8933 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8934 {":relief", IMAGE_INTEGER_VALUE
, 0},
8935 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8936 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8937 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8938 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8941 # if defined HAVE_NTGUI && defined WINDOWSNT
8942 static bool init_svg_functions (void);
8944 #define init_svg_functions NULL
8947 /* Structure describing the image type `svg'. Its the same type of
8948 structure defined for all image formats, handled by emacs image
8949 functions. See struct image_type in dispextern.h. */
8951 static struct image_type svg_type
=
8953 SYMBOL_INDEX (Qsvg
),
8962 /* Return true if OBJECT is a valid SVG image specification. Do
8963 this by calling parse_image_spec and supplying the keywords that
8964 identify the SVG format. */
8967 svg_image_p (Lisp_Object object
)
8969 struct image_keyword fmt
[SVG_LAST
];
8970 memcpy (fmt
, svg_format
, sizeof fmt
);
8972 if (!parse_image_spec (object
, fmt
, SVG_LAST
, Qsvg
))
8975 /* Must specify either the :data or :file keyword. */
8976 return fmt
[SVG_FILE
].count
+ fmt
[SVG_DATA
].count
== 1;
8979 # include <librsvg/rsvg.h>
8983 /* SVG library functions. */
8984 DEF_DLL_FN (RsvgHandle
*, rsvg_handle_new
, (void));
8985 DEF_DLL_FN (void, rsvg_handle_get_dimensions
,
8986 (RsvgHandle
*, RsvgDimensionData
*));
8987 DEF_DLL_FN (gboolean
, rsvg_handle_write
,
8988 (RsvgHandle
*, const guchar
*, gsize
, GError
**));
8989 DEF_DLL_FN (gboolean
, rsvg_handle_close
, (RsvgHandle
*, GError
**));
8990 DEF_DLL_FN (GdkPixbuf
*, rsvg_handle_get_pixbuf
, (RsvgHandle
*));
8991 DEF_DLL_FN (void, rsvg_handle_set_base_uri
, (RsvgHandle
*, const char *));
8993 DEF_DLL_FN (int, gdk_pixbuf_get_width
, (const GdkPixbuf
*));
8994 DEF_DLL_FN (int, gdk_pixbuf_get_height
, (const GdkPixbuf
*));
8995 DEF_DLL_FN (guchar
*, gdk_pixbuf_get_pixels
, (const GdkPixbuf
*));
8996 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride
, (const GdkPixbuf
*));
8997 DEF_DLL_FN (GdkColorspace
, gdk_pixbuf_get_colorspace
, (const GdkPixbuf
*));
8998 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels
, (const GdkPixbuf
*));
8999 DEF_DLL_FN (gboolean
, gdk_pixbuf_get_has_alpha
, (const GdkPixbuf
*));
9000 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample
, (const GdkPixbuf
*));
9002 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9003 DEF_DLL_FN (void, g_type_init
, (void));
9005 DEF_DLL_FN (void, g_object_unref
, (gpointer
));
9006 DEF_DLL_FN (void, g_clear_error
, (GError
**));
9009 init_svg_functions (void)
9011 HMODULE library
, gdklib
= NULL
, glib
= NULL
, gobject
= NULL
;
9013 if (!(glib
= w32_delayed_load (Qglib
))
9014 || !(gobject
= w32_delayed_load (Qgobject
))
9015 || !(gdklib
= w32_delayed_load (Qgdk_pixbuf
))
9016 || !(library
= w32_delayed_load (Qsvg
)))
9018 if (gdklib
) FreeLibrary (gdklib
);
9019 if (gobject
) FreeLibrary (gobject
);
9020 if (glib
) FreeLibrary (glib
);
9024 LOAD_DLL_FN (library
, rsvg_handle_new
);
9025 LOAD_DLL_FN (library
, rsvg_handle_get_dimensions
);
9026 LOAD_DLL_FN (library
, rsvg_handle_write
);
9027 LOAD_DLL_FN (library
, rsvg_handle_close
);
9028 LOAD_DLL_FN (library
, rsvg_handle_get_pixbuf
);
9029 LOAD_DLL_FN (library
, rsvg_handle_set_base_uri
);
9031 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_width
);
9032 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_height
);
9033 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_pixels
);
9034 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_rowstride
);
9035 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_colorspace
);
9036 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_n_channels
);
9037 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_has_alpha
);
9038 LOAD_DLL_FN (gdklib
, gdk_pixbuf_get_bits_per_sample
);
9040 # if ! GLIB_CHECK_VERSION (2, 36, 0)
9041 LOAD_DLL_FN (gobject
, g_type_init
);
9043 LOAD_DLL_FN (gobject
, g_object_unref
);
9044 LOAD_DLL_FN (glib
, g_clear_error
);
9049 /* The following aliases for library functions allow dynamic loading
9050 to be used on some platforms. */
9052 # undef gdk_pixbuf_get_bits_per_sample
9053 # undef gdk_pixbuf_get_colorspace
9054 # undef gdk_pixbuf_get_has_alpha
9055 # undef gdk_pixbuf_get_height
9056 # undef gdk_pixbuf_get_n_channels
9057 # undef gdk_pixbuf_get_pixels
9058 # undef gdk_pixbuf_get_rowstride
9059 # undef gdk_pixbuf_get_width
9060 # undef g_clear_error
9061 # undef g_object_unref
9063 # undef rsvg_handle_close
9064 # undef rsvg_handle_get_dimensions
9065 # undef rsvg_handle_get_pixbuf
9066 # undef rsvg_handle_new
9067 # undef rsvg_handle_set_base_uri
9068 # undef rsvg_handle_write
9070 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
9071 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
9072 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
9073 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
9074 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
9075 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
9076 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
9077 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
9078 # define g_clear_error fn_g_clear_error
9079 # define g_object_unref fn_g_object_unref
9080 # define g_type_init fn_g_type_init
9081 # define rsvg_handle_close fn_rsvg_handle_close
9082 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
9083 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
9084 # define rsvg_handle_new fn_rsvg_handle_new
9085 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
9086 # define rsvg_handle_write fn_rsvg_handle_write
9088 # endif /* !WINDOWSNT */
9090 /* Load SVG image IMG for use on frame F. Value is true if
9094 svg_load (struct frame
*f
, struct image
*img
)
9097 Lisp_Object file_name
;
9099 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9100 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
9101 if (STRINGP (file_name
))
9104 Lisp_Object file
= x_find_image_fd (file_name
, &fd
);
9105 if (!STRINGP (file
))
9107 image_error ("Cannot find image file `%s'", file_name
);
9111 /* Read the entire file into memory. */
9113 unsigned char *contents
= slurp_file (fd
, &size
);
9114 if (contents
== NULL
)
9116 image_error ("Error loading SVG image `%s'", file
);
9119 /* If the file was slurped into memory properly, parse it. */
9120 success_p
= svg_load_image (f
, img
, contents
, size
,
9121 SSDATA (ENCODE_FILE (file
)));
9124 /* Else its not a file, its a lisp object. Load the image from a
9125 lisp object rather than a file. */
9128 Lisp_Object data
, original_filename
;
9130 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
9131 if (!STRINGP (data
))
9133 image_error ("Invalid image data `%s'", data
);
9136 original_filename
= BVAR (current_buffer
, filename
);
9137 success_p
= svg_load_image (f
, img
, SDATA (data
), SBYTES (data
),
9138 (NILP (original_filename
) ? NULL
9139 : SSDATA (original_filename
)));
9145 /* svg_load_image is a helper function for svg_load, which does the
9146 actual loading given contents and size, apart from frame and image
9147 structures, passed from svg_load.
9149 Uses librsvg to do most of the image processing.
9151 Returns true when successful. */
9153 svg_load_image (struct frame
*f
, /* Pointer to emacs frame structure. */
9154 struct image
*img
, /* Pointer to emacs image structure. */
9155 unsigned char *contents
, /* String containing the SVG XML data to be parsed. */
9156 ptrdiff_t size
, /* Size of data in bytes. */
9157 char *filename
) /* Name of SVG file being loaded. */
9159 RsvgHandle
*rsvg_handle
;
9160 RsvgDimensionData dimension_data
;
9165 const guint8
*pixels
;
9168 Lisp_Object specified_bg
;
9173 #if ! GLIB_CHECK_VERSION (2, 36, 0)
9174 /* g_type_init is a glib function that must be called prior to
9175 using gnome type library functions (obsolete since 2.36.0). */
9179 /* Make a handle to a new rsvg object. */
9180 rsvg_handle
= rsvg_handle_new ();
9182 /* Set base_uri for properly handling referenced images (via 'href').
9183 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
9184 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
9186 rsvg_handle_set_base_uri(rsvg_handle
, filename
);
9188 /* Parse the contents argument and fill in the rsvg_handle. */
9189 rsvg_handle_write (rsvg_handle
, contents
, size
, &err
);
9190 if (err
) goto rsvg_error
;
9192 /* The parsing is complete, rsvg_handle is ready to used, close it
9193 for further writes. */
9194 rsvg_handle_close (rsvg_handle
, &err
);
9195 if (err
) goto rsvg_error
;
9197 rsvg_handle_get_dimensions (rsvg_handle
, &dimension_data
);
9198 if (! check_image_size (f
, dimension_data
.width
, dimension_data
.height
))
9200 image_size_error ();
9204 /* We can now get a valid pixel buffer from the svg file, if all
9206 pixbuf
= rsvg_handle_get_pixbuf (rsvg_handle
);
9207 if (!pixbuf
) goto rsvg_error
;
9208 g_object_unref (rsvg_handle
);
9210 /* Extract some meta data from the svg handle. */
9211 width
= gdk_pixbuf_get_width (pixbuf
);
9212 height
= gdk_pixbuf_get_height (pixbuf
);
9213 pixels
= gdk_pixbuf_get_pixels (pixbuf
);
9214 rowstride
= gdk_pixbuf_get_rowstride (pixbuf
);
9216 /* Validate the svg meta data. */
9217 eassert (gdk_pixbuf_get_colorspace (pixbuf
) == GDK_COLORSPACE_RGB
);
9218 eassert (gdk_pixbuf_get_n_channels (pixbuf
) == 4);
9219 eassert (gdk_pixbuf_get_has_alpha (pixbuf
));
9220 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf
) == 8);
9224 unsigned char *data
= (unsigned char *) xmalloc (width
*height
*4);
9226 uint32_t bgcolor
= get_spec_bg_or_alpha_as_argb (img
, f
);
9228 for (y
= 0; y
< height
; ++y
)
9230 const guchar
*iconptr
= pixels
+ y
* rowstride
;
9231 uint32_t *dataptr
= (uint32_t *) (data
+ y
* rowstride
);
9234 for (x
= 0; x
< width
; ++x
)
9236 if (iconptr
[3] == 0)
9239 *dataptr
= (iconptr
[0] << 16)
9242 | (iconptr
[3] << 24);
9249 create_cairo_image_surface (img
, data
, width
, height
);
9250 g_object_unref (pixbuf
);
9253 /* Try to create a x pixmap to hold the svg pixmap. */
9254 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
9256 g_object_unref (pixbuf
);
9260 init_color_table ();
9262 /* Handle alpha channel by combining the image with a background
9264 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
9265 if (!STRINGP (specified_bg
)
9266 || !x_defined_color (f
, SSDATA (specified_bg
), &background
, 0))
9267 x_query_frame_background_color (f
, &background
);
9269 /* SVG pixmaps specify transparency in the last byte, so right
9270 shift 8 bits to get rid of it, since emacs doesn't support
9272 background
.red
>>= 8;
9273 background
.green
>>= 8;
9274 background
.blue
>>= 8;
9276 /* This loop handles opacity values, since Emacs assumes
9277 non-transparent images. Each pixel must be "flattened" by
9278 calculating the resulting color, given the transparency of the
9279 pixel, and the image background color. */
9280 for (y
= 0; y
< height
; ++y
)
9282 for (x
= 0; x
< width
; ++x
)
9292 opacity
= *pixels
++;
9294 red
= ((red
* opacity
)
9295 + (background
.red
* ((1 << 8) - opacity
)));
9296 green
= ((green
* opacity
)
9297 + (background
.green
* ((1 << 8) - opacity
)));
9298 blue
= ((blue
* opacity
)
9299 + (background
.blue
* ((1 << 8) - opacity
)));
9301 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, red
, green
, blue
));
9304 pixels
+= rowstride
- 4 * width
;
9307 #ifdef COLOR_TABLE_SUPPORT
9308 /* Remember colors allocated for this image. */
9309 img
->colors
= colors_in_color_table (&img
->ncolors
);
9310 free_color_table ();
9311 #endif /* COLOR_TABLE_SUPPORT */
9313 g_object_unref (pixbuf
);
9316 img
->height
= height
;
9318 /* Maybe fill in the background field while we have ximg handy.
9319 Casting avoids a GCC warning. */
9320 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
9322 /* Put ximg into the image. */
9323 image_put_x_image (f
, img
, ximg
, 0);
9324 #endif /* ! USE_CAIRO */
9329 g_object_unref (rsvg_handle
);
9330 /* FIXME: Use error->message so the user knows what is the actual
9331 problem with the image. */
9332 image_error ("Error parsing SVG image `%s'", img
->spec
);
9333 g_clear_error (&err
);
9337 #endif /* defined (HAVE_RSVG) */
9342 /***********************************************************************
9344 ***********************************************************************/
9346 #ifdef HAVE_X_WINDOWS
9347 #define HAVE_GHOSTSCRIPT 1
9348 #endif /* HAVE_X_WINDOWS */
9350 #ifdef HAVE_GHOSTSCRIPT
9352 static bool gs_image_p (Lisp_Object object
);
9353 static bool gs_load (struct frame
*f
, struct image
*img
);
9354 static void gs_clear_image (struct frame
*f
, struct image
*img
);
9356 /* Indices of image specification fields in gs_format, below. */
9358 enum gs_keyword_index
9376 /* Vector of image_keyword structures describing the format
9377 of valid user-defined image specifications. */
9379 static const struct image_keyword gs_format
[GS_LAST
] =
9381 {":type", IMAGE_SYMBOL_VALUE
, 1},
9382 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9383 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
9384 {":file", IMAGE_STRING_VALUE
, 1},
9385 {":loader", IMAGE_FUNCTION_VALUE
, 0},
9386 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE
, 1},
9387 {":ascent", IMAGE_ASCENT_VALUE
, 0},
9388 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
9389 {":relief", IMAGE_INTEGER_VALUE
, 0},
9390 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9391 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9392 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9393 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
9396 /* Structure describing the image type `ghostscript'. */
9398 static struct image_type gs_type
=
9400 SYMBOL_INDEX (Qpostscript
),
9409 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9412 gs_clear_image (struct frame
*f
, struct image
*img
)
9414 x_clear_image (f
, img
);
9418 /* Return true if OBJECT is a valid Ghostscript image
9422 gs_image_p (Lisp_Object object
)
9424 struct image_keyword fmt
[GS_LAST
];
9428 memcpy (fmt
, gs_format
, sizeof fmt
);
9430 if (!parse_image_spec (object
, fmt
, GS_LAST
, Qpostscript
))
9433 /* Bounding box must be a list or vector containing 4 integers. */
9434 tem
= fmt
[GS_BOUNDING_BOX
].value
;
9437 for (i
= 0; i
< 4; ++i
, tem
= XCDR (tem
))
9438 if (!CONSP (tem
) || !INTEGERP (XCAR (tem
)))
9443 else if (VECTORP (tem
))
9445 if (ASIZE (tem
) != 4)
9447 for (i
= 0; i
< 4; ++i
)
9448 if (!INTEGERP (AREF (tem
, i
)))
9458 /* Load Ghostscript image IMG for use on frame F. Value is true
9462 gs_load (struct frame
*f
, struct image
*img
)
9464 uprintmax_t printnum1
, printnum2
;
9465 char buffer
[sizeof " " + INT_STRLEN_BOUND (printmax_t
)];
9466 Lisp_Object window_and_pixmap_id
= Qnil
, loader
, pt_height
, pt_width
;
9468 double in_width
, in_height
;
9469 Lisp_Object pixel_colors
= Qnil
;
9471 /* Compute pixel size of pixmap needed from the given size in the
9472 image specification. Sizes in the specification are in pt. 1 pt
9473 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9475 pt_width
= image_spec_value (img
->spec
, QCpt_width
, NULL
);
9476 in_width
= INTEGERP (pt_width
) ? XFASTINT (pt_width
) / 72.0 : 0;
9477 in_width
*= FRAME_RES_X (f
);
9478 pt_height
= image_spec_value (img
->spec
, QCpt_height
, NULL
);
9479 in_height
= INTEGERP (pt_height
) ? XFASTINT (pt_height
) / 72.0 : 0;
9480 in_height
*= FRAME_RES_Y (f
);
9482 if (! (in_width
<= INT_MAX
&& in_height
<= INT_MAX
9483 && check_image_size (f
, in_width
, in_height
)))
9485 image_size_error ();
9488 img
->width
= in_width
;
9489 img
->height
= in_height
;
9491 /* Create the pixmap. */
9492 eassert (img
->pixmap
== NO_PIXMAP
);
9494 if (x_check_image_size (0, img
->width
, img
->height
))
9496 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9498 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
9499 img
->width
, img
->height
,
9500 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)));
9506 image_error ("Unable to create pixmap for `%s'" , img
->spec
);
9510 /* Call the loader to fill the pixmap. It returns a process object
9511 if successful. We do not record_unwind_protect here because
9512 other places in redisplay like calling window scroll functions
9513 don't either. Let the Lisp loader use `unwind-protect' instead. */
9514 printnum1
= FRAME_X_WINDOW (f
);
9515 printnum2
= img
->pixmap
;
9516 window_and_pixmap_id
9517 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9519 printnum1
= FRAME_FOREGROUND_PIXEL (f
);
9520 printnum2
= FRAME_BACKGROUND_PIXEL (f
);
9522 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9524 XSETFRAME (frame
, f
);
9525 loader
= image_spec_value (img
->spec
, QCloader
, NULL
);
9527 loader
= intern ("gs-load-image");
9529 img
->lisp_data
= call6 (loader
, frame
, img
->spec
,
9530 make_number (img
->width
),
9531 make_number (img
->height
),
9532 window_and_pixmap_id
,
9534 return PROCESSP (img
->lisp_data
);
9538 /* Kill the Ghostscript process that was started to fill PIXMAP on
9539 frame F. Called from XTread_socket when receiving an event
9540 telling Emacs that Ghostscript has finished drawing. */
9543 x_kill_gs_process (Pixmap pixmap
, struct frame
*f
)
9545 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
9549 /* Find the image containing PIXMAP. */
9550 for (i
= 0; i
< c
->used
; ++i
)
9551 if (c
->images
[i
]->pixmap
== pixmap
)
9554 /* Should someone in between have cleared the image cache, for
9555 instance, give up. */
9559 /* Kill the GS process. We should have found PIXMAP in the image
9560 cache and its image should contain a process object. */
9562 eassert (PROCESSP (img
->lisp_data
));
9563 Fkill_process (img
->lisp_data
, Qnil
);
9564 img
->lisp_data
= Qnil
;
9566 #if defined (HAVE_X_WINDOWS)
9568 /* On displays with a mutable colormap, figure out the colors
9569 allocated for the image by looking at the pixels of an XImage for
9571 if (x_mutable_colormap (FRAME_X_VISUAL (f
)))
9577 /* Try to get an XImage for img->pixmep. */
9578 ximg
= XGetImage (FRAME_X_DISPLAY (f
), img
->pixmap
,
9579 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
9584 /* Initialize the color table. */
9585 init_color_table ();
9587 /* For each pixel of the image, look its color up in the
9588 color table. After having done so, the color table will
9589 contain an entry for each color used by the image. */
9590 #ifdef COLOR_TABLE_SUPPORT
9591 for (y
= 0; y
< img
->height
; ++y
)
9592 for (x
= 0; x
< img
->width
; ++x
)
9594 unsigned long pixel
= XGetPixel (ximg
, x
, y
);
9596 lookup_pixel_color (f
, pixel
);
9599 /* Record colors in the image. Free color table and XImage. */
9600 img
->colors
= colors_in_color_table (&img
->ncolors
);
9601 free_color_table ();
9603 XDestroyImage (ximg
);
9605 #if 0 /* This doesn't seem to be the case. If we free the colors
9606 here, we get a BadAccess later in x_clear_image when
9607 freeing the colors. */
9608 /* We have allocated colors once, but Ghostscript has also
9609 allocated colors on behalf of us. So, to get the
9610 reference counts right, free them once. */
9612 x_free_colors (f
, img
->colors
, img
->ncolors
);
9616 image_error ("Cannot get X image of `%s'; colors will not be freed",
9621 #endif /* HAVE_X_WINDOWS */
9623 /* Now that we have the pixmap, compute mask and transform the
9624 image if requested. */
9626 postprocess_image (f
, img
);
9630 #endif /* HAVE_GHOSTSCRIPT */
9633 /***********************************************************************
9635 ***********************************************************************/
9639 DEFUN ("imagep", Fimagep
, Simagep
, 1, 1, 0,
9640 doc
: /* Value is non-nil if SPEC is a valid image specification. */)
9643 return valid_image_p (spec
) ? Qt
: Qnil
;
9647 DEFUN ("lookup-image", Flookup_image
, Slookup_image
, 1, 1, 0,
9653 if (valid_image_p (spec
))
9654 id
= lookup_image (SELECTED_FRAME (), spec
);
9657 return make_number (id
);
9660 #endif /* GLYPH_DEBUG */
9663 /***********************************************************************
9665 ***********************************************************************/
9667 DEFUN ("init-image-library", Finit_image_library
, Sinit_image_library
, 1, 1, 0,
9668 doc
: /* Initialize image library implementing image type TYPE.
9669 Return non-nil if TYPE is a supported image type.
9671 If image libraries are loaded dynamically (currently only the case on
9672 MS-Windows), load the library for TYPE if it is not yet loaded, using
9673 the library file(s) specified by `dynamic-library-alist'. */)
9676 return lookup_image_type (type
) ? Qt
: Qnil
;
9679 /* Look up image type TYPE, and return a pointer to its image_type
9680 structure. Return 0 if TYPE is not a known image type. */
9682 static struct image_type
*
9683 lookup_image_type (Lisp_Object type
)
9685 /* Types pbm and xbm are built-in and always available. */
9686 if (EQ (type
, Qpbm
))
9687 return define_image_type (&pbm_type
);
9689 if (EQ (type
, Qxbm
))
9690 return define_image_type (&xbm_type
);
9692 #if defined (HAVE_XPM) || defined (HAVE_NS)
9693 if (EQ (type
, Qxpm
))
9694 return define_image_type (&xpm_type
);
9697 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9698 if (EQ (type
, Qjpeg
))
9699 return define_image_type (&jpeg_type
);
9702 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9703 if (EQ (type
, Qtiff
))
9704 return define_image_type (&tiff_type
);
9707 #if defined (HAVE_GIF) || defined (HAVE_NS)
9708 if (EQ (type
, Qgif
))
9709 return define_image_type (&gif_type
);
9712 #if defined (HAVE_PNG) || defined (HAVE_NS) || defined (USE_CAIRO)
9713 if (EQ (type
, Qpng
))
9714 return define_image_type (&png_type
);
9717 #if defined (HAVE_RSVG)
9718 if (EQ (type
, Qsvg
))
9719 return define_image_type (&svg_type
);
9722 #if defined (HAVE_IMAGEMAGICK)
9723 if (EQ (type
, Qimagemagick
))
9724 return define_image_type (&imagemagick_type
);
9727 #ifdef HAVE_GHOSTSCRIPT
9728 if (EQ (type
, Qpostscript
))
9729 return define_image_type (&gs_type
);
9735 /* Reset image_types before dumping.
9736 Called from Fdump_emacs. */
9739 reset_image_types (void)
9743 struct image_type
*next
= image_types
->next
;
9744 xfree (image_types
);
9750 syms_of_image (void)
9752 /* Initialize this only once; it will be reset before dumping. */
9755 /* Must be defined now because we're going to update it below, while
9756 defining the supported image types. */
9757 DEFVAR_LISP ("image-types", Vimage_types
,
9758 doc
: /* List of potentially supported image types.
9759 Each element of the list is a symbol for an image type, like `jpeg' or `png'.
9760 To check whether it is really supported, use `image-type-available-p'. */);
9761 Vimage_types
= Qnil
;
9763 DEFVAR_LISP ("max-image-size", Vmax_image_size
,
9764 doc
: /* Maximum size of images.
9765 Emacs will not load an image into memory if its pixel width or
9766 pixel height exceeds this limit.
9768 If the value is an integer, it directly specifies the maximum
9769 image height and width, measured in pixels. If it is a floating
9770 point number, it specifies the maximum image height and width
9771 as a ratio to the frame height and width. If the value is
9772 non-numeric, there is no explicit limit on the size of images. */);
9773 Vmax_image_size
= make_float (MAX_IMAGE_SIZE
);
9775 /* Other symbols. */
9776 DEFSYM (Qcount
, "count");
9777 DEFSYM (Qextension_data
, "extension-data");
9778 DEFSYM (Qdelay
, "delay");
9781 DEFSYM (QCascent
, ":ascent");
9782 DEFSYM (QCmargin
, ":margin");
9783 DEFSYM (QCrelief
, ":relief");
9784 DEFSYM (QCconversion
, ":conversion");
9785 DEFSYM (QCcolor_symbols
, ":color-symbols");
9786 DEFSYM (QCheuristic_mask
, ":heuristic-mask");
9787 DEFSYM (QCindex
, ":index");
9788 DEFSYM (QCcrop
, ":crop");
9789 DEFSYM (QCrotation
, ":rotation");
9790 DEFSYM (QCmatrix
, ":matrix");
9791 DEFSYM (QCcolor_adjustment
, ":color-adjustment");
9792 DEFSYM (QCmask
, ":mask");
9794 /* Other symbols. */
9795 DEFSYM (Qlaplace
, "laplace");
9796 DEFSYM (Qemboss
, "emboss");
9797 DEFSYM (Qedge_detection
, "edge-detection");
9798 DEFSYM (Qheuristic
, "heuristic");
9800 DEFSYM (Qpostscript
, "postscript");
9801 DEFSYM (QCmax_width
, ":max-width");
9802 DEFSYM (QCmax_height
, ":max-height");
9803 #ifdef HAVE_GHOSTSCRIPT
9804 ADD_IMAGE_TYPE (Qpostscript
);
9805 DEFSYM (QCloader
, ":loader");
9806 DEFSYM (QCpt_width
, ":pt-width");
9807 DEFSYM (QCpt_height
, ":pt-height");
9808 #endif /* HAVE_GHOSTSCRIPT */
9811 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
9812 or -1 if no PNG/GIF support was compiled in. This is tested by
9813 w32-win.el to correctly set up the alist used to search for the
9814 respective image libraries. */
9815 DEFSYM (Qlibpng_version
, "libpng-version");
9816 Fset (Qlibpng_version
,
9818 make_number (PNG_LIBPNG_VER
)
9823 DEFSYM (Qlibgif_version
, "libgif-version");
9824 Fset (Qlibgif_version
,
9826 make_number (GIFLIB_MAJOR
* 10000
9827 + GIFLIB_MINOR
* 100
9833 DEFSYM (Qlibjpeg_version
, "libjpeg-version");
9834 Fset (Qlibjpeg_version
,
9836 make_number (JPEG_LIB_VERSION
)
9843 DEFSYM (Qpbm
, "pbm");
9844 ADD_IMAGE_TYPE (Qpbm
);
9846 DEFSYM (Qxbm
, "xbm");
9847 ADD_IMAGE_TYPE (Qxbm
);
9849 #if defined (HAVE_XPM) || defined (HAVE_NS)
9850 DEFSYM (Qxpm
, "xpm");
9851 ADD_IMAGE_TYPE (Qxpm
);
9854 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9855 DEFSYM (Qjpeg
, "jpeg");
9856 ADD_IMAGE_TYPE (Qjpeg
);
9859 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9860 DEFSYM (Qtiff
, "tiff");
9861 ADD_IMAGE_TYPE (Qtiff
);
9864 #if defined (HAVE_GIF) || defined (HAVE_NS)
9865 DEFSYM (Qgif
, "gif");
9866 ADD_IMAGE_TYPE (Qgif
);
9869 #if defined (HAVE_PNG) || defined (HAVE_NS)
9870 DEFSYM (Qpng
, "png");
9871 ADD_IMAGE_TYPE (Qpng
);
9874 #if defined (HAVE_IMAGEMAGICK)
9875 DEFSYM (Qimagemagick
, "imagemagick");
9876 ADD_IMAGE_TYPE (Qimagemagick
);
9879 #if defined (HAVE_RSVG)
9880 DEFSYM (Qsvg
, "svg");
9881 ADD_IMAGE_TYPE (Qsvg
);
9883 /* Other libraries used directly by svg code. */
9884 DEFSYM (Qgdk_pixbuf
, "gdk-pixbuf");
9885 DEFSYM (Qglib
, "glib");
9886 DEFSYM (Qgobject
, "gobject");
9887 #endif /* HAVE_NTGUI */
9888 #endif /* HAVE_RSVG */
9890 defsubr (&Sinit_image_library
);
9891 #ifdef HAVE_IMAGEMAGICK
9892 defsubr (&Simagemagick_types
);
9894 defsubr (&Sclear_image_cache
);
9895 defsubr (&Simage_flush
);
9896 defsubr (&Simage_size
);
9897 defsubr (&Simage_mask_p
);
9898 defsubr (&Simage_metadata
);
9902 defsubr (&Slookup_image
);
9905 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images
,
9906 doc
: /* Non-nil means always draw a cross over disabled images.
9907 Disabled images are those having a `:conversion disabled' property.
9908 A cross is always drawn on black & white displays. */);
9909 cross_disabled_images
= 0;
9911 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path
,
9912 doc
: /* List of directories to search for window system bitmap files. */);
9913 Vx_bitmap_file_path
= decode_env_path (0, PATH_BITMAPS
, 0);
9915 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay
,
9916 doc
: /* Maximum time after which images are removed from the cache.
9917 When an image has not been displayed this many seconds, Emacs
9918 automatically removes it from the image cache. If the cache contains
9919 a large number of images, the actual eviction time may be shorter.
9920 The value can also be nil, meaning the cache is never cleared.
9922 The function `clear-image-cache' disregards this variable. */);
9923 Vimage_cache_eviction_delay
= make_number (300);
9924 #ifdef HAVE_IMAGEMAGICK
9925 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type
,
9926 doc
: /* Integer indicating which ImageMagick rendering method to use.
9928 0 -- the default method (pixel pushing)
9929 1 -- a newer method ("MagickExportImagePixels") that may perform
9930 better (speed etc) in some cases, but has not been as thoroughly
9931 tested with Emacs as the default method. This method requires
9932 ImageMagick version 6.4.6 (approximately) or later.
9934 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9935 imagemagick_render_type
= 0;