1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2013 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/>. */
25 #if defined HAVE_LIBPNG_PNG_H
26 # include <libpng/png.h>
36 /* This makes the fields of a Display accessible, in Xlib header files. */
38 #define XLIB_ILLEGAL_ACCESS
43 #include "dispextern.h"
44 #include "blockinput.h"
47 #include "character.h"
49 #include "termhooks.h"
52 #ifdef HAVE_SYS_STAT_H
54 #endif /* HAVE_SYS_STAT_H */
56 #ifdef HAVE_SYS_TYPES_H
57 #include <sys/types.h>
58 #endif /* HAVE_SYS_TYPES_H */
60 #ifdef HAVE_WINDOW_SYSTEM
62 #endif /* HAVE_WINDOW_SYSTEM */
65 #define COLOR_TABLE_SUPPORT 1
67 typedef struct x_bitmap_record Bitmap_Record
;
68 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
69 #define NO_PIXMAP None
71 #define PIX_MASK_RETAIN 0
72 #define PIX_MASK_DRAW 1
73 #endif /* HAVE_X_WINDOWS */
77 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
82 /* W32_TODO : Color tables on W32. */
83 #undef COLOR_TABLE_SUPPORT
85 typedef struct w32_bitmap_record Bitmap_Record
;
86 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
89 #define PIX_MASK_RETAIN 0
90 #define PIX_MASK_DRAW 1
92 #define x_defined_color w32_defined_color
93 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
95 /* Version of libpng that we were compiled with, or -1 if no PNG
96 support was compiled in. This is tested by w32-win.el to correctly
97 set up the alist used to search for PNG libraries. */
98 Lisp_Object Qlibpng_version
;
99 #endif /* HAVE_NTGUI */
102 #undef COLOR_TABLE_SUPPORT
104 typedef struct ns_bitmap_record Bitmap_Record
;
106 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
109 #define PIX_MASK_RETAIN 0
110 #define PIX_MASK_DRAW 1
112 #define x_defined_color(f, name, color_def, alloc) \
113 ns_defined_color (f, name, color_def, alloc, 0)
114 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
118 /* The symbol `postscript' identifying images of this type. */
120 static Lisp_Object Qpostscript
;
122 static void x_disable_image (struct frame
*, struct image
*);
123 static void x_edge_detection (struct frame
*, struct image
*, Lisp_Object
,
126 static void init_color_table (void);
127 static unsigned long lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
);
128 #ifdef COLOR_TABLE_SUPPORT
129 static void free_color_table (void);
130 static unsigned long *colors_in_color_table (int *n
);
133 static Lisp_Object QCmax_width
, QCmax_height
;
135 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
136 id, which is just an int that this section returns. Bitmaps are
137 reference counted so they can be shared among frames.
139 Bitmap indices are guaranteed to be > 0, so a negative number can
140 be used to indicate no bitmap.
142 If you use x_create_bitmap_from_data, then you must keep track of
143 the bitmaps yourself. That is, creating a bitmap from the same
144 data more than once will not be caught. */
147 /* Use with images created by ns_image_for_XPM. */
149 XGetPixel (XImagePtr ximage
, int x
, int y
)
151 return ns_get_pixel (ximage
, x
, y
);
154 /* Use with images created by ns_image_for_XPM; alpha set to 1;
155 pixel is assumed to be in RGB form. */
157 XPutPixel (XImagePtr ximage
, int x
, int y
, unsigned long pixel
)
159 ns_put_pixel (ximage
, x
, y
, pixel
);
164 /* Functions to access the contents of a bitmap, given an id. */
167 x_bitmap_height (struct frame
*f
, ptrdiff_t id
)
169 return FRAME_X_DISPLAY_INFO (f
)->bitmaps
[id
- 1].height
;
173 x_bitmap_width (struct frame
*f
, ptrdiff_t id
)
175 return FRAME_X_DISPLAY_INFO (f
)->bitmaps
[id
- 1].width
;
178 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
180 x_bitmap_pixmap (struct frame
*f
, ptrdiff_t id
)
182 /* HAVE_NTGUI needs the explicit cast here. */
183 return (ptrdiff_t) FRAME_X_DISPLAY_INFO (f
)->bitmaps
[id
- 1].pixmap
;
187 #ifdef HAVE_X_WINDOWS
189 x_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
191 return FRAME_X_DISPLAY_INFO (f
)->bitmaps
[id
- 1].mask
;
195 /* Allocate a new bitmap record. Returns index of new record. */
198 x_allocate_bitmap_record (struct frame
*f
)
200 Display_Info
*dpyinfo
= FRAME_X_DISPLAY_INFO (f
);
203 if (dpyinfo
->bitmaps_last
< dpyinfo
->bitmaps_size
)
204 return ++dpyinfo
->bitmaps_last
;
206 for (i
= 0; i
< dpyinfo
->bitmaps_size
; ++i
)
207 if (dpyinfo
->bitmaps
[i
].refcount
== 0)
211 xpalloc (dpyinfo
->bitmaps
, &dpyinfo
->bitmaps_size
,
212 10, -1, sizeof *dpyinfo
->bitmaps
);
213 return ++dpyinfo
->bitmaps_last
;
216 /* Add one reference to the reference count of the bitmap with id ID. */
219 x_reference_bitmap (struct frame
*f
, ptrdiff_t id
)
221 ++FRAME_X_DISPLAY_INFO (f
)->bitmaps
[id
- 1].refcount
;
224 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
227 x_create_bitmap_from_data (struct frame
*f
, char *bits
, unsigned int width
, unsigned int height
)
229 Display_Info
*dpyinfo
= FRAME_X_DISPLAY_INFO (f
);
232 #ifdef HAVE_X_WINDOWS
234 bitmap
= XCreateBitmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
235 bits
, width
, height
);
238 #endif /* HAVE_X_WINDOWS */
242 bitmap
= CreateBitmap (width
, height
,
243 FRAME_X_DISPLAY_INFO (XFRAME (frame
))->n_planes
,
244 FRAME_X_DISPLAY_INFO (XFRAME (frame
))->n_cbits
,
248 #endif /* HAVE_NTGUI */
251 void *bitmap
= ns_image_from_XBM (bits
, width
, height
);
256 id
= x_allocate_bitmap_record (f
);
259 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
260 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
263 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
264 dpyinfo
->bitmaps
[id
- 1].height
= height
;
265 dpyinfo
->bitmaps
[id
- 1].width
= width
;
266 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
268 #ifdef HAVE_X_WINDOWS
269 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
270 dpyinfo
->bitmaps
[id
- 1].have_mask
= 0;
271 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
272 #endif /* HAVE_X_WINDOWS */
275 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
276 dpyinfo
->bitmaps
[id
- 1].hinst
= NULL
;
277 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
278 #endif /* HAVE_NTGUI */
283 /* Create bitmap from file FILE for frame F. */
286 x_create_bitmap_from_file (struct frame
*f
, Lisp_Object file
)
288 Display_Info
*dpyinfo
= FRAME_X_DISPLAY_INFO (f
);
291 return -1; /* W32_TODO : bitmap support */
292 #endif /* HAVE_NTGUI */
296 void *bitmap
= ns_image_from_file (file
);
302 id
= x_allocate_bitmap_record (f
);
303 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
304 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
305 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
306 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
307 dpyinfo
->bitmaps
[id
- 1].height
= ns_image_width (bitmap
);
308 dpyinfo
->bitmaps
[id
- 1].width
= ns_image_height (bitmap
);
312 #ifdef HAVE_X_WINDOWS
313 unsigned int width
, height
;
315 int xhot
, yhot
, result
;
320 /* Look for an existing bitmap with the same name. */
321 for (id
= 0; id
< dpyinfo
->bitmaps_last
; ++id
)
323 if (dpyinfo
->bitmaps
[id
].refcount
324 && dpyinfo
->bitmaps
[id
].file
325 && !strcmp (dpyinfo
->bitmaps
[id
].file
, SSDATA (file
)))
327 ++dpyinfo
->bitmaps
[id
].refcount
;
332 /* Search bitmap-file-path for the file, if appropriate. */
333 if (openp (Vx_bitmap_file_path
, file
, Qnil
, &found
, make_number (R_OK
)) < 0)
336 filename
= SSDATA (found
);
338 result
= XReadBitmapFile (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
339 filename
, &width
, &height
, &bitmap
, &xhot
, &yhot
);
340 if (result
!= BitmapSuccess
)
343 id
= x_allocate_bitmap_record (f
);
344 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
345 dpyinfo
->bitmaps
[id
- 1].have_mask
= 0;
346 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
347 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
348 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
349 dpyinfo
->bitmaps
[id
- 1].height
= height
;
350 dpyinfo
->bitmaps
[id
- 1].width
= width
;
353 #endif /* HAVE_X_WINDOWS */
359 free_bitmap_record (Display_Info
*dpyinfo
, Bitmap_Record
*bm
)
361 #ifdef HAVE_X_WINDOWS
362 XFreePixmap (dpyinfo
->display
, bm
->pixmap
);
364 XFreePixmap (dpyinfo
->display
, bm
->mask
);
365 #endif /* HAVE_X_WINDOWS */
368 DeleteObject (bm
->pixmap
);
369 #endif /* HAVE_NTGUI */
372 ns_release_object (bm
->img
);
382 /* Remove reference to bitmap with id number ID. */
385 x_destroy_bitmap (struct frame
*f
, ptrdiff_t id
)
387 Display_Info
*dpyinfo
= FRAME_X_DISPLAY_INFO (f
);
391 Bitmap_Record
*bm
= &dpyinfo
->bitmaps
[id
- 1];
393 if (--bm
->refcount
== 0)
396 free_bitmap_record (dpyinfo
, bm
);
402 /* Free all the bitmaps for the display specified by DPYINFO. */
405 x_destroy_all_bitmaps (Display_Info
*dpyinfo
)
408 Bitmap_Record
*bm
= dpyinfo
->bitmaps
;
410 for (i
= 0; i
< dpyinfo
->bitmaps_last
; i
++, bm
++)
411 if (bm
->refcount
> 0)
412 free_bitmap_record (dpyinfo
, bm
);
414 dpyinfo
->bitmaps_last
= 0;
417 static bool x_create_x_image_and_pixmap (struct frame
*, int, int, int,
418 XImagePtr
*, Pixmap
*);
419 static void x_destroy_x_image (XImagePtr ximg
);
422 static XImagePtr_or_DC
image_get_x_image_or_dc (struct frame
*, struct image
*,
424 static void image_unget_x_image_or_dc (struct image
*, bool, XImagePtr_or_DC
,
427 static XImagePtr
image_get_x_image (struct frame
*, struct image
*, bool);
428 static void image_unget_x_image (struct image
*, bool, XImagePtr
);
429 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
430 image_get_x_image (f, img, mask_p)
431 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
432 image_unget_x_image (img, mask_p, ximg)
435 #ifdef HAVE_X_WINDOWS
437 static void image_sync_to_pixmaps (struct frame
*, struct image
*);
439 /* Useful functions defined in the section
440 `Image type independent image structures' below. */
442 static unsigned long four_corners_best (XImagePtr ximg
,
445 unsigned long height
);
448 /* Create a mask of a bitmap. Note is this not a perfect mask.
449 It's nicer with some borders in this context */
452 x_create_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
455 XImagePtr ximg
, mask_img
;
456 unsigned long width
, height
;
459 unsigned long x
, y
, xp
, xm
, yp
, ym
;
462 Display_Info
*dpyinfo
= FRAME_X_DISPLAY_INFO (f
);
467 pixmap
= x_bitmap_pixmap (f
, id
);
468 width
= x_bitmap_width (f
, id
);
469 height
= x_bitmap_height (f
, id
);
472 ximg
= XGetImage (FRAME_X_DISPLAY (f
), pixmap
, 0, 0, width
, height
,
481 result
= x_create_x_image_and_pixmap (f
, width
, height
, 1, &mask_img
, &mask
);
486 XDestroyImage (ximg
);
490 bg
= four_corners_best (ximg
, NULL
, width
, height
);
492 for (y
= 0; y
< ximg
->height
; ++y
)
494 for (x
= 0; x
< ximg
->width
; ++x
)
496 xp
= x
!= ximg
->width
- 1 ? x
+ 1 : 0;
497 xm
= x
!= 0 ? x
- 1 : ximg
->width
- 1;
498 yp
= y
!= ximg
->height
- 1 ? y
+ 1 : 0;
499 ym
= y
!= 0 ? y
- 1 : ximg
->height
- 1;
500 if (XGetPixel (ximg
, x
, y
) == bg
501 && XGetPixel (ximg
, x
, yp
) == bg
502 && XGetPixel (ximg
, x
, ym
) == bg
503 && XGetPixel (ximg
, xp
, y
) == bg
504 && XGetPixel (ximg
, xp
, yp
) == bg
505 && XGetPixel (ximg
, xp
, ym
) == bg
506 && XGetPixel (ximg
, xm
, y
) == bg
507 && XGetPixel (ximg
, xm
, yp
) == bg
508 && XGetPixel (ximg
, xm
, ym
) == bg
)
509 XPutPixel (mask_img
, x
, y
, 0);
511 XPutPixel (mask_img
, x
, y
, 1);
515 eassert (input_blocked_p ());
516 gc
= XCreateGC (FRAME_X_DISPLAY (f
), mask
, 0, NULL
);
517 XPutImage (FRAME_X_DISPLAY (f
), mask
, gc
, mask_img
, 0, 0, 0, 0,
519 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
521 dpyinfo
->bitmaps
[id
- 1].have_mask
= 1;
522 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
524 XDestroyImage (ximg
);
525 x_destroy_x_image (mask_img
);
528 #endif /* HAVE_X_WINDOWS */
531 /***********************************************************************
533 ***********************************************************************/
535 /* List of supported image types. Use define_image_type to add new
536 types. Use lookup_image_type to find a type for a given symbol. */
538 static struct image_type
*image_types
;
540 /* The symbol `xbm' which is used as the type symbol for XBM images. */
542 static Lisp_Object Qxbm
;
546 Lisp_Object QCascent
, QCmargin
, QCrelief
;
547 Lisp_Object QCconversion
;
548 static Lisp_Object QCheuristic_mask
;
549 static Lisp_Object QCcolor_symbols
;
550 static Lisp_Object QCindex
, QCmatrix
, QCcolor_adjustment
, QCmask
, QCgeometry
;
551 static Lisp_Object QCcrop
, QCrotation
;
555 static Lisp_Object Qcount
, Qextension_data
, Qdelay
;
556 static Lisp_Object Qlaplace
, Qemboss
, Qedge_detection
, Qheuristic
;
558 /* Forward function prototypes. */
560 static struct image_type
*lookup_image_type (Lisp_Object
);
561 static void x_laplace (struct frame
*, struct image
*);
562 static void x_emboss (struct frame
*, struct image
*);
563 static void x_build_heuristic_mask (struct frame
*, struct image
*,
566 extern Lisp_Object Vlibrary_cache
;
567 #define CACHE_IMAGE_TYPE(type, status) \
568 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
570 #define CACHE_IMAGE_TYPE(type, status)
573 #define ADD_IMAGE_TYPE(type) \
574 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
576 /* Define a new image type from TYPE. This adds a copy of TYPE to
577 image_types and caches the loading status of TYPE. */
579 static struct image_type
*
580 define_image_type (struct image_type
*type
)
582 struct image_type
*p
= NULL
;
583 Lisp_Object target_type
= *type
->type
;
588 for (p
= image_types
; p
; p
= p
->next
)
589 if (EQ (*p
->type
, target_type
))
594 #if defined HAVE_NTGUI && defined WINDOWSNT
595 /* If we failed to load the library before, don't try again. */
596 Lisp_Object tested
= Fassq (target_type
, Vlibrary_cache
);
597 if (CONSP (tested
) && NILP (XCDR (tested
)))
602 type_valid
= type
->init ();
603 CACHE_IMAGE_TYPE (target_type
, type_valid
? Qt
: Qnil
);
609 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
610 The initialized data segment is read-only. */
611 p
= xmalloc (sizeof *p
);
613 p
->next
= image_types
;
623 /* Value is true if OBJECT is a valid Lisp image specification. A
624 valid image specification is a list whose car is the symbol
625 `image', and whose rest is a property list. The property list must
626 contain a value for key `:type'. That value must be the name of a
627 supported image type. The rest of the property list depends on the
631 valid_image_p (Lisp_Object object
)
639 for (tem
= XCDR (object
); CONSP (tem
); tem
= XCDR (tem
))
640 if (EQ (XCAR (tem
), QCtype
))
643 if (CONSP (tem
) && SYMBOLP (XCAR (tem
)))
645 struct image_type
*type
;
646 type
= lookup_image_type (XCAR (tem
));
648 valid_p
= type
->valid_p (object
);
659 /* Log error message with format string FORMAT and argument ARG.
660 Signaling an error, e.g. when an image cannot be loaded, is not a
661 good idea because this would interrupt redisplay, and the error
662 message display would lead to another redisplay. This function
663 therefore simply displays a message. */
666 image_error (const char *format
, Lisp_Object arg1
, Lisp_Object arg2
)
668 add_to_log (format
, arg1
, arg2
);
673 /***********************************************************************
675 ***********************************************************************/
677 enum image_value_type
679 IMAGE_DONT_CHECK_VALUE_TYPE
,
681 IMAGE_STRING_OR_NIL_VALUE
,
683 IMAGE_POSITIVE_INTEGER_VALUE
,
684 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
,
685 IMAGE_NON_NEGATIVE_INTEGER_VALUE
,
688 IMAGE_FUNCTION_VALUE
,
693 /* Structure used when parsing image specifications. */
697 /* Name of keyword. */
700 /* The type of value allowed. */
701 enum image_value_type type
;
703 /* True means key must be present. */
706 /* Used to recognize duplicate keywords in a property list. */
709 /* The value that was found. */
714 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
715 has the format (image KEYWORD VALUE ...). One of the keyword/
716 value pairs must be `:type TYPE'. KEYWORDS is a vector of
717 image_keywords structures of size NKEYWORDS describing other
718 allowed keyword/value pairs. Value is true if SPEC is valid. */
721 parse_image_spec (Lisp_Object spec
, struct image_keyword
*keywords
,
722 int nkeywords
, Lisp_Object type
)
731 while (CONSP (plist
))
733 Lisp_Object key
, value
;
735 /* First element of a pair must be a symbol. */
737 plist
= XCDR (plist
);
741 /* There must follow a value. */
744 value
= XCAR (plist
);
745 plist
= XCDR (plist
);
747 /* Find key in KEYWORDS. Error if not found. */
748 for (i
= 0; i
< nkeywords
; ++i
)
749 if (strcmp (keywords
[i
].name
, SSDATA (SYMBOL_NAME (key
))) == 0)
755 /* Record that we recognized the keyword. If a keywords
756 was found more than once, it's an error. */
757 keywords
[i
].value
= value
;
758 if (keywords
[i
].count
> 1)
762 /* Check type of value against allowed type. */
763 switch (keywords
[i
].type
)
765 case IMAGE_STRING_VALUE
:
766 if (!STRINGP (value
))
770 case IMAGE_STRING_OR_NIL_VALUE
:
771 if (!STRINGP (value
) && !NILP (value
))
775 case IMAGE_SYMBOL_VALUE
:
776 if (!SYMBOLP (value
))
780 case IMAGE_POSITIVE_INTEGER_VALUE
:
781 if (! RANGED_INTEGERP (1, value
, INT_MAX
))
785 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
:
786 if (RANGED_INTEGERP (0, value
, INT_MAX
))
789 && RANGED_INTEGERP (0, XCAR (value
), INT_MAX
)
790 && RANGED_INTEGERP (0, XCDR (value
), INT_MAX
))
794 case IMAGE_ASCENT_VALUE
:
795 if (SYMBOLP (value
) && EQ (value
, Qcenter
))
797 else if (RANGED_INTEGERP (0, value
, 100))
801 case IMAGE_NON_NEGATIVE_INTEGER_VALUE
:
802 /* Unlike the other integer-related cases, this one does not
803 verify that VALUE fits in 'int'. This is because callers
805 if (!INTEGERP (value
) || XINT (value
) < 0)
809 case IMAGE_DONT_CHECK_VALUE_TYPE
:
812 case IMAGE_FUNCTION_VALUE
:
813 value
= indirect_function (value
);
814 if (!NILP (Ffunctionp (value
)))
818 case IMAGE_NUMBER_VALUE
:
819 if (!INTEGERP (value
) && !FLOATP (value
))
823 case IMAGE_INTEGER_VALUE
:
824 if (! TYPE_RANGED_INTEGERP (int, value
))
828 case IMAGE_BOOL_VALUE
:
829 if (!NILP (value
) && !EQ (value
, Qt
))
838 if (EQ (key
, QCtype
) && !EQ (type
, value
))
842 /* Check that all mandatory fields are present. */
843 for (i
= 0; i
< nkeywords
; ++i
)
844 if (keywords
[i
].mandatory_p
&& keywords
[i
].count
== 0)
851 /* Return the value of KEY in image specification SPEC. Value is nil
852 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
853 was found in SPEC. */
856 image_spec_value (Lisp_Object spec
, Lisp_Object key
, bool *found
)
860 eassert (valid_image_p (spec
));
862 for (tail
= XCDR (spec
);
863 CONSP (tail
) && CONSP (XCDR (tail
));
864 tail
= XCDR (XCDR (tail
)))
866 if (EQ (XCAR (tail
), key
))
870 return XCAR (XCDR (tail
));
880 DEFUN ("image-size", Fimage_size
, Simage_size
, 1, 3, 0,
881 doc
: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
882 PIXELS non-nil means return the size in pixels, otherwise return the
883 size in canonical character units.
884 FRAME is the frame on which the image will be displayed. FRAME nil
885 or omitted means use the selected frame. */)
886 (Lisp_Object spec
, Lisp_Object pixels
, Lisp_Object frame
)
891 if (valid_image_p (spec
))
893 struct frame
*f
= decode_window_system_frame (frame
);
894 ptrdiff_t id
= lookup_image (f
, spec
);
895 struct image
*img
= IMAGE_FROM_ID (f
, id
);
896 int width
= img
->width
+ 2 * img
->hmargin
;
897 int height
= img
->height
+ 2 * img
->vmargin
;
900 size
= Fcons (make_float ((double) width
/ FRAME_COLUMN_WIDTH (f
)),
901 make_float ((double) height
/ FRAME_LINE_HEIGHT (f
)));
903 size
= Fcons (make_number (width
), make_number (height
));
906 error ("Invalid image specification");
912 DEFUN ("image-mask-p", Fimage_mask_p
, Simage_mask_p
, 1, 2, 0,
913 doc
: /* Return t if image SPEC has a mask bitmap.
914 FRAME is the frame on which the image will be displayed. FRAME nil
915 or omitted means use the selected frame. */)
916 (Lisp_Object spec
, Lisp_Object frame
)
921 if (valid_image_p (spec
))
923 struct frame
*f
= decode_window_system_frame (frame
);
924 ptrdiff_t id
= lookup_image (f
, spec
);
925 struct image
*img
= IMAGE_FROM_ID (f
, id
);
930 error ("Invalid image specification");
935 DEFUN ("image-metadata", Fimage_metadata
, Simage_metadata
, 1, 2, 0,
936 doc
: /* Return metadata for image SPEC.
937 FRAME is the frame on which the image will be displayed. FRAME nil
938 or omitted means use the selected frame. */)
939 (Lisp_Object spec
, Lisp_Object frame
)
944 if (valid_image_p (spec
))
946 struct frame
*f
= decode_window_system_frame (frame
);
947 ptrdiff_t id
= lookup_image (f
, spec
);
948 struct image
*img
= IMAGE_FROM_ID (f
, id
);
949 ext
= img
->lisp_data
;
956 /***********************************************************************
957 Image type independent image structures
958 ***********************************************************************/
960 #define MAX_IMAGE_SIZE 10.0
961 /* Allocate and return a new image structure for image specification
962 SPEC. SPEC has a hash value of HASH. */
964 static struct image
*
965 make_image (Lisp_Object spec
, EMACS_UINT hash
)
967 struct image
*img
= xzalloc (sizeof *img
);
968 Lisp_Object file
= image_spec_value (spec
, QCfile
, NULL
);
970 eassert (valid_image_p (spec
));
971 img
->dependencies
= NILP (file
) ? Qnil
: list1 (file
);
972 img
->type
= lookup_image_type (image_spec_value (spec
, QCtype
, NULL
));
973 eassert (img
->type
!= NULL
);
975 img
->lisp_data
= Qnil
;
976 img
->ascent
= DEFAULT_IMAGE_ASCENT
;
978 img
->corners
[BOT_CORNER
] = -1; /* Full image */
983 /* Free image IMG which was used on frame F, including its resources. */
986 free_image (struct frame
*f
, struct image
*img
)
990 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
992 /* Remove IMG from the hash table of its cache. */
994 img
->prev
->next
= img
->next
;
996 c
->buckets
[img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
] = img
->next
;
999 img
->next
->prev
= img
->prev
;
1001 c
->images
[img
->id
] = NULL
;
1003 /* Free resources, then free IMG. */
1004 img
->type
->free (f
, img
);
1009 /* Return true if the given widths and heights are valid for display. */
1012 check_image_size (struct frame
*f
, int width
, int height
)
1016 if (width
<= 0 || height
<= 0)
1019 if (INTEGERP (Vmax_image_size
))
1020 return (width
<= XINT (Vmax_image_size
)
1021 && height
<= XINT (Vmax_image_size
));
1022 else if (FLOATP (Vmax_image_size
))
1026 w
= FRAME_PIXEL_WIDTH (f
);
1027 h
= FRAME_PIXEL_HEIGHT (f
);
1030 w
= h
= 1024; /* Arbitrary size for unknown frame. */
1031 return (width
<= XFLOAT_DATA (Vmax_image_size
) * w
1032 && height
<= XFLOAT_DATA (Vmax_image_size
) * h
);
1038 /* Prepare image IMG for display on frame F. Must be called before
1039 drawing an image. */
1042 prepare_image_for_display (struct frame
*f
, struct image
*img
)
1044 /* We're about to display IMG, so set its timestamp to `now'. */
1045 img
->timestamp
= current_emacs_time ();
1047 /* If IMG doesn't have a pixmap yet, load it now, using the image
1048 type dependent loader function. */
1049 if (img
->pixmap
== NO_PIXMAP
&& !img
->load_failed_p
)
1050 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1052 #ifdef HAVE_X_WINDOWS
1053 if (!img
->load_failed_p
)
1056 image_sync_to_pixmaps (f
, img
);
1063 /* Value is the number of pixels for the ascent of image IMG when
1064 drawn in face FACE. */
1067 image_ascent (struct image
*img
, struct face
*face
, struct glyph_slice
*slice
)
1072 if (slice
->height
== img
->height
)
1073 height
= img
->height
+ img
->vmargin
;
1074 else if (slice
->y
== 0)
1075 height
= slice
->height
+ img
->vmargin
;
1077 height
= slice
->height
;
1079 if (img
->ascent
== CENTERED_IMAGE_ASCENT
)
1084 /* W32 specific version. Why?. ++kfs */
1085 ascent
= height
/ 2 - (FONT_DESCENT (face
->font
)
1086 - FONT_BASE (face
->font
)) / 2;
1088 /* This expression is arranged so that if the image can't be
1089 exactly centered, it will be moved slightly up. This is
1090 because a typical font is `top-heavy' (due to the presence
1091 uppercase letters), so the image placement should err towards
1092 being top-heavy too. It also just generally looks better. */
1093 ascent
= (height
+ FONT_BASE (face
->font
)
1094 - FONT_DESCENT (face
->font
) + 1) / 2;
1095 #endif /* HAVE_NTGUI */
1098 ascent
= height
/ 2;
1101 ascent
= height
* (img
->ascent
/ 100.0);
1107 /* Image background colors. */
1109 /* Find the "best" corner color of a bitmap.
1110 On W32, XIMG is assumed to a device context with the bitmap selected. */
1112 static RGB_PIXEL_COLOR
1113 four_corners_best (XImagePtr_or_DC ximg
, int *corners
,
1114 unsigned long width
, unsigned long height
)
1116 RGB_PIXEL_COLOR corner_pixels
[4], best
IF_LINT (= 0);
1119 if (corners
&& corners
[BOT_CORNER
] >= 0)
1121 /* Get the colors at the corner_pixels of ximg. */
1122 corner_pixels
[0] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[TOP_CORNER
]);
1123 corner_pixels
[1] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[TOP_CORNER
]);
1124 corner_pixels
[2] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[BOT_CORNER
] - 1);
1125 corner_pixels
[3] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[BOT_CORNER
] - 1);
1129 /* Get the colors at the corner_pixels of ximg. */
1130 corner_pixels
[0] = GET_PIXEL (ximg
, 0, 0);
1131 corner_pixels
[1] = GET_PIXEL (ximg
, width
- 1, 0);
1132 corner_pixels
[2] = GET_PIXEL (ximg
, width
- 1, height
- 1);
1133 corner_pixels
[3] = GET_PIXEL (ximg
, 0, height
- 1);
1135 /* Choose the most frequently found color as background. */
1136 for (i
= best_count
= 0; i
< 4; ++i
)
1140 for (j
= n
= 0; j
< 4; ++j
)
1141 if (corner_pixels
[i
] == corner_pixels
[j
])
1145 best
= corner_pixels
[i
], best_count
= n
;
1151 /* Portability macros */
1155 #define Free_Pixmap(display, pixmap) \
1156 DeleteObject (pixmap)
1158 #elif defined (HAVE_NS)
1160 #define Free_Pixmap(display, pixmap) \
1161 ns_release_object (pixmap)
1165 #define Free_Pixmap(display, pixmap) \
1166 XFreePixmap (display, pixmap)
1168 #endif /* !HAVE_NTGUI && !HAVE_NS */
1171 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1172 it is guessed heuristically. If non-zero, XIMG is an existing
1173 XImage object (or device context with the image selected on W32) to
1174 use for the heuristic. */
1177 image_background (struct image
*img
, struct frame
*f
, XImagePtr_or_DC ximg
)
1179 if (! img
->background_valid
)
1180 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1182 bool free_ximg
= !ximg
;
1185 #endif /* HAVE_NTGUI */
1188 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
1190 img
->background
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
1193 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
1195 img
->background_valid
= 1;
1198 return img
->background
;
1201 /* Return the `background_transparent' field of IMG. If IMG doesn't
1202 have one yet, it is guessed heuristically. If non-zero, MASK is an
1203 existing XImage object to use for the heuristic. */
1206 image_background_transparent (struct image
*img
, struct frame
*f
, XImagePtr_or_DC mask
)
1208 if (! img
->background_transparent_valid
)
1209 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1213 bool free_mask
= !mask
;
1216 #endif /* HAVE_NTGUI */
1219 mask
= image_get_x_image_or_dc (f
, img
, 1, &prev
);
1221 img
->background_transparent
1222 = (four_corners_best (mask
, img
->corners
, img
->width
, img
->height
) == PIX_MASK_RETAIN
);
1225 image_unget_x_image_or_dc (img
, 1, mask
, prev
);
1228 img
->background_transparent
= 0;
1230 img
->background_transparent_valid
= 1;
1233 return img
->background_transparent
;
1237 /***********************************************************************
1238 Helper functions for X image types
1239 ***********************************************************************/
1241 /* Clear X resources of image IMG on frame F according to FLAGS.
1242 FLAGS is bitwise-or of the following masks:
1243 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1244 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1245 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1248 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1249 #define CLEAR_IMAGE_MASK (1 << 1)
1250 #define CLEAR_IMAGE_COLORS (1 << 2)
1253 x_clear_image_1 (struct frame
*f
, struct image
*img
, int flags
)
1255 if (flags
& CLEAR_IMAGE_PIXMAP
)
1259 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->pixmap
);
1260 img
->pixmap
= NO_PIXMAP
;
1261 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1262 img
->background_valid
= 0;
1264 #ifdef HAVE_X_WINDOWS
1267 x_destroy_x_image (img
->ximg
);
1269 img
->background_valid
= 0;
1274 if (flags
& CLEAR_IMAGE_MASK
)
1278 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->mask
);
1279 img
->mask
= NO_PIXMAP
;
1280 img
->background_transparent_valid
= 0;
1282 #ifdef HAVE_X_WINDOWS
1285 x_destroy_x_image (img
->mask_img
);
1286 img
->mask_img
= NULL
;
1287 img
->background_transparent_valid
= 0;
1292 if ((flags
& CLEAR_IMAGE_COLORS
) && img
->ncolors
)
1294 /* W32_TODO: color table support. */
1295 #ifdef HAVE_X_WINDOWS
1296 x_free_colors (f
, img
->colors
, img
->ncolors
);
1297 #endif /* HAVE_X_WINDOWS */
1298 xfree (img
->colors
);
1305 /* Free X resources of image IMG which is used on frame F. */
1308 x_clear_image (struct frame
*f
, struct image
*img
)
1311 x_clear_image_1 (f
, img
,
1312 CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_MASK
| CLEAR_IMAGE_COLORS
);
1317 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1318 cannot be allocated, use DFLT. Add a newly allocated color to
1319 IMG->colors, so that it can be freed again. Value is the pixel
1322 static unsigned long
1323 x_alloc_image_color (struct frame
*f
, struct image
*img
, Lisp_Object color_name
,
1327 unsigned long result
;
1329 eassert (STRINGP (color_name
));
1331 if (x_defined_color (f
, SSDATA (color_name
), &color
, 1)
1332 && img
->ncolors
< min (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *img
->colors
,
1335 /* This isn't called frequently so we get away with simply
1336 reallocating the color vector to the needed size, here. */
1337 ptrdiff_t ncolors
= img
->ncolors
+ 1;
1338 img
->colors
= xrealloc (img
->colors
, ncolors
* sizeof *img
->colors
);
1339 img
->colors
[ncolors
- 1] = color
.pixel
;
1340 img
->ncolors
= ncolors
;
1341 result
= color
.pixel
;
1351 /***********************************************************************
1353 ***********************************************************************/
1355 static void cache_image (struct frame
*f
, struct image
*img
);
1357 /* Return a new, initialized image cache that is allocated from the
1358 heap. Call free_image_cache to free an image cache. */
1360 struct image_cache
*
1361 make_image_cache (void)
1363 struct image_cache
*c
= xzalloc (sizeof *c
);
1367 c
->images
= xmalloc (size
* sizeof *c
->images
);
1369 size
= IMAGE_CACHE_BUCKETS_SIZE
* sizeof *c
->buckets
;
1370 c
->buckets
= xzalloc (size
);
1375 /* Find an image matching SPEC in the cache, and return it. If no
1376 image is found, return NULL. */
1377 static struct image
*
1378 search_image_cache (struct frame
*f
, Lisp_Object spec
, EMACS_UINT hash
)
1381 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1382 int i
= hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1384 if (!c
) return NULL
;
1386 /* If the image spec does not specify a background color, the cached
1387 image must have the same background color as the current frame.
1388 The foreground color must also match, for the sake of monochrome
1391 In fact, we could ignore the foreground color matching condition
1392 for color images, or if the image spec specifies :foreground;
1393 similarly we could ignore the background color matching condition
1394 for formats that don't use transparency (such as jpeg), or if the
1395 image spec specifies :background. However, the extra memory
1396 usage is probably negligible in practice, so we don't bother. */
1398 for (img
= c
->buckets
[i
]; img
; img
= img
->next
)
1399 if (img
->hash
== hash
1400 && !NILP (Fequal (img
->spec
, spec
))
1401 && img
->frame_foreground
== FRAME_FOREGROUND_PIXEL (f
)
1402 && img
->frame_background
== FRAME_BACKGROUND_PIXEL (f
))
1408 /* Search frame F for an image with spec SPEC, and free it. */
1411 uncache_image (struct frame
*f
, Lisp_Object spec
)
1413 struct image
*img
= search_image_cache (f
, spec
, sxhash (spec
, 0));
1416 free_image (f
, img
);
1417 /* As display glyphs may still be referring to the image ID, we
1418 must garbage the frame (Bug#6426). */
1419 SET_FRAME_GARBAGED (f
);
1424 /* Free image cache of frame F. Be aware that X frames share images
1428 free_image_cache (struct frame
*f
)
1430 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1435 /* Cache should not be referenced by any frame when freed. */
1436 eassert (c
->refcount
== 0);
1438 for (i
= 0; i
< c
->used
; ++i
)
1439 free_image (f
, c
->images
[i
]);
1443 FRAME_IMAGE_CACHE (f
) = NULL
;
1448 /* Clear image cache of frame F. FILTER=t means free all images.
1449 FILTER=nil means clear only images that haven't been
1450 displayed for some time.
1451 Else, only free the images which have FILTER in their `dependencies'.
1452 Should be called from time to time to reduce the number of loaded images.
1453 If image-cache-eviction-delay is non-nil, this frees images in the cache
1454 which weren't displayed for at least that many seconds. */
1457 clear_image_cache (struct frame
*f
, Lisp_Object filter
)
1459 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1463 ptrdiff_t i
, nfreed
= 0;
1465 /* Block input so that we won't be interrupted by a SIGIO
1466 while being in an inconsistent state. */
1471 /* Filter image cache. */
1472 for (i
= 0; i
< c
->used
; ++i
)
1474 struct image
*img
= c
->images
[i
];
1475 if (img
&& (EQ (Qt
, filter
)
1476 || !NILP (Fmember (filter
, img
->dependencies
))))
1478 free_image (f
, img
);
1483 else if (INTEGERP (Vimage_cache_eviction_delay
))
1485 /* Free cache based on timestamp. */
1488 ptrdiff_t nimages
= 0;
1490 for (i
= 0; i
< c
->used
; ++i
)
1494 /* If the number of cached images has grown unusually large,
1495 decrease the cache eviction delay (Bug#6230). */
1496 delay
= XINT (Vimage_cache_eviction_delay
);
1498 delay
= 1600 * delay
/ nimages
/ nimages
;
1499 delay
= max (delay
, 1);
1501 t
= current_emacs_time ();
1502 old
= sub_emacs_time (t
, EMACS_TIME_FROM_DOUBLE (delay
));
1504 for (i
= 0; i
< c
->used
; ++i
)
1506 struct image
*img
= c
->images
[i
];
1507 if (img
&& EMACS_TIME_LT (img
->timestamp
, old
))
1509 free_image (f
, img
);
1515 /* We may be clearing the image cache because, for example,
1516 Emacs was iconified for a longer period of time. In that
1517 case, current matrices may still contain references to
1518 images freed above. So, clear these matrices. */
1521 Lisp_Object tail
, frame
;
1523 FOR_EACH_FRAME (tail
, frame
)
1525 struct frame
*fr
= XFRAME (frame
);
1526 if (FRAME_IMAGE_CACHE (fr
) == c
)
1527 clear_current_matrices (fr
);
1530 ++windows_or_buffers_changed
;
1538 clear_image_caches (Lisp_Object filter
)
1540 /* FIXME: We want to do
1541 * struct terminal *t;
1542 * for (t = terminal_list; t; t = t->next_terminal)
1543 * clear_image_cache (t, filter); */
1544 Lisp_Object tail
, frame
;
1545 FOR_EACH_FRAME (tail
, frame
)
1546 if (FRAME_WINDOW_P (XFRAME (frame
)))
1547 clear_image_cache (XFRAME (frame
), filter
);
1550 DEFUN ("clear-image-cache", Fclear_image_cache
, Sclear_image_cache
,
1552 doc
: /* Clear the image cache.
1553 FILTER nil or a frame means clear all images in the selected frame.
1554 FILTER t means clear the image caches of all frames.
1555 Anything else, means only clear those images which refer to FILTER,
1556 which is then usually a filename. */)
1557 (Lisp_Object filter
)
1559 if (!(EQ (filter
, Qnil
) || FRAMEP (filter
)))
1560 clear_image_caches (filter
);
1562 clear_image_cache (decode_window_system_frame (filter
), Qt
);
1568 DEFUN ("image-flush", Fimage_flush
, Simage_flush
,
1570 doc
: /* Flush the image with specification SPEC on frame FRAME.
1571 This removes the image from the Emacs image cache. If SPEC specifies
1572 an image file, the next redisplay of this image will read from the
1573 current contents of that file.
1575 FRAME nil or omitted means use the selected frame.
1576 FRAME t means refresh the image on all frames. */)
1577 (Lisp_Object spec
, Lisp_Object frame
)
1579 if (!valid_image_p (spec
))
1580 error ("Invalid image specification");
1585 FOR_EACH_FRAME (tail
, frame
)
1587 struct frame
*f
= XFRAME (frame
);
1588 if (FRAME_WINDOW_P (f
))
1589 uncache_image (f
, spec
);
1593 uncache_image (decode_window_system_frame (frame
), spec
);
1599 /* Compute masks and transform image IMG on frame F, as specified
1600 by the image's specification, */
1603 postprocess_image (struct frame
*f
, struct image
*img
)
1605 /* Manipulation of the image's mask. */
1608 Lisp_Object conversion
, spec
;
1613 /* `:heuristic-mask t'
1615 means build a mask heuristically.
1616 `:heuristic-mask (R G B)'
1617 `:mask (heuristic (R G B))'
1618 means build a mask from color (R G B) in the
1621 means remove a mask, if any. */
1623 mask
= image_spec_value (spec
, QCheuristic_mask
, NULL
);
1625 x_build_heuristic_mask (f
, img
, mask
);
1630 mask
= image_spec_value (spec
, QCmask
, &found_p
);
1632 if (EQ (mask
, Qheuristic
))
1633 x_build_heuristic_mask (f
, img
, Qt
);
1634 else if (CONSP (mask
)
1635 && EQ (XCAR (mask
), Qheuristic
))
1637 if (CONSP (XCDR (mask
)))
1638 x_build_heuristic_mask (f
, img
, XCAR (XCDR (mask
)));
1640 x_build_heuristic_mask (f
, img
, XCDR (mask
));
1642 else if (NILP (mask
) && found_p
&& img
->mask
)
1643 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
1647 /* Should we apply an image transformation algorithm? */
1648 conversion
= image_spec_value (spec
, QCconversion
, NULL
);
1649 if (EQ (conversion
, Qdisabled
))
1650 x_disable_image (f
, img
);
1651 else if (EQ (conversion
, Qlaplace
))
1653 else if (EQ (conversion
, Qemboss
))
1655 else if (CONSP (conversion
)
1656 && EQ (XCAR (conversion
), Qedge_detection
))
1659 tem
= XCDR (conversion
);
1661 x_edge_detection (f
, img
,
1662 Fplist_get (tem
, QCmatrix
),
1663 Fplist_get (tem
, QCcolor_adjustment
));
1669 /* Return the id of image with Lisp specification SPEC on frame F.
1670 SPEC must be a valid Lisp image specification (see valid_image_p). */
1673 lookup_image (struct frame
*f
, Lisp_Object spec
)
1678 /* F must be a window-system frame, and SPEC must be a valid image
1680 eassert (FRAME_WINDOW_P (f
));
1681 eassert (valid_image_p (spec
));
1683 /* Look up SPEC in the hash table of the image cache. */
1684 hash
= sxhash (spec
, 0);
1685 img
= search_image_cache (f
, spec
, hash
);
1686 if (img
&& img
->load_failed_p
)
1688 free_image (f
, img
);
1692 /* If not found, create a new image and cache it. */
1696 img
= make_image (spec
, hash
);
1697 cache_image (f
, img
);
1698 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1699 img
->frame_foreground
= FRAME_FOREGROUND_PIXEL (f
);
1700 img
->frame_background
= FRAME_BACKGROUND_PIXEL (f
);
1702 /* If we can't load the image, and we don't have a width and
1703 height, use some arbitrary width and height so that we can
1704 draw a rectangle for it. */
1705 if (img
->load_failed_p
)
1709 value
= image_spec_value (spec
, QCwidth
, NULL
);
1710 img
->width
= (INTEGERP (value
)
1711 ? XFASTINT (value
) : DEFAULT_IMAGE_WIDTH
);
1712 value
= image_spec_value (spec
, QCheight
, NULL
);
1713 img
->height
= (INTEGERP (value
)
1714 ? XFASTINT (value
) : DEFAULT_IMAGE_HEIGHT
);
1718 /* Handle image type independent image attributes
1719 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1720 `:background COLOR'. */
1721 Lisp_Object ascent
, margin
, relief
, bg
;
1724 ascent
= image_spec_value (spec
, QCascent
, NULL
);
1725 if (INTEGERP (ascent
))
1726 img
->ascent
= XFASTINT (ascent
);
1727 else if (EQ (ascent
, Qcenter
))
1728 img
->ascent
= CENTERED_IMAGE_ASCENT
;
1730 margin
= image_spec_value (spec
, QCmargin
, NULL
);
1731 if (INTEGERP (margin
))
1732 img
->vmargin
= img
->hmargin
= XFASTINT (margin
);
1733 else if (CONSP (margin
))
1735 img
->hmargin
= XFASTINT (XCAR (margin
));
1736 img
->vmargin
= XFASTINT (XCDR (margin
));
1739 relief
= image_spec_value (spec
, QCrelief
, NULL
);
1740 relief_bound
= INT_MAX
- max (img
->hmargin
, img
->vmargin
);
1741 if (RANGED_INTEGERP (- relief_bound
, relief
, relief_bound
))
1743 img
->relief
= XINT (relief
);
1744 img
->hmargin
+= eabs (img
->relief
);
1745 img
->vmargin
+= eabs (img
->relief
);
1748 if (! img
->background_valid
)
1750 bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1754 = x_alloc_image_color (f
, img
, bg
,
1755 FRAME_BACKGROUND_PIXEL (f
));
1756 img
->background_valid
= 1;
1760 /* Do image transformations and compute masks, unless we
1761 don't have the image yet. */
1762 if (!EQ (*img
->type
->type
, Qpostscript
))
1763 postprocess_image (f
, img
);
1769 /* We're using IMG, so set its timestamp to `now'. */
1770 img
->timestamp
= current_emacs_time ();
1772 /* Value is the image id. */
1777 /* Cache image IMG in the image cache of frame F. */
1780 cache_image (struct frame
*f
, struct image
*img
)
1782 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1785 /* Find a free slot in c->images. */
1786 for (i
= 0; i
< c
->used
; ++i
)
1787 if (c
->images
[i
] == NULL
)
1790 /* If no free slot found, maybe enlarge c->images. */
1791 if (i
== c
->used
&& c
->used
== c
->size
)
1792 c
->images
= xpalloc (c
->images
, &c
->size
, 1, -1, sizeof *c
->images
);
1794 /* Add IMG to c->images, and assign IMG an id. */
1800 /* Add IMG to the cache's hash table. */
1801 i
= img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1802 img
->next
= c
->buckets
[i
];
1804 img
->next
->prev
= img
;
1806 c
->buckets
[i
] = img
;
1810 /* Call FN on every image in the image cache of frame F. Used to mark
1811 Lisp Objects in the image cache. */
1813 /* Mark Lisp objects in image IMG. */
1816 mark_image (struct image
*img
)
1818 mark_object (img
->spec
);
1819 mark_object (img
->dependencies
);
1821 if (!NILP (img
->lisp_data
))
1822 mark_object (img
->lisp_data
);
1827 mark_image_cache (struct image_cache
*c
)
1832 for (i
= 0; i
< c
->used
; ++i
)
1834 mark_image (c
->images
[i
]);
1840 /***********************************************************************
1841 X / NS / W32 support code
1842 ***********************************************************************/
1846 /* Macro for defining functions that will be loaded from image DLLs. */
1847 #define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
1849 /* Macro for loading those image functions from the library. */
1850 #define LOAD_IMGLIB_FN(lib,func) { \
1851 fn_##func = (void *) GetProcAddress (lib, #func); \
1852 if (!fn_##func) return 0; \
1855 #endif /* WINDOWSNT */
1857 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1859 WIDTH and HEIGHT must both be positive.
1860 If XIMG is null, assume it is a bitmap. */
1862 x_check_image_size (XImagePtr ximg
, int width
, int height
)
1864 #ifdef HAVE_X_WINDOWS
1865 /* Respect Xlib's limits: it cannot deal with images that have more
1866 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1867 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1870 XLIB_BYTES_MAX
= min (INT_MAX
, UINT_MAX
),
1871 X_IMAGE_BYTES_MAX
= min (XLIB_BYTES_MAX
, min (PTRDIFF_MAX
, SIZE_MAX
))
1874 int bitmap_pad
, depth
, bytes_per_line
;
1877 bitmap_pad
= ximg
->bitmap_pad
;
1878 depth
= ximg
->depth
;
1879 bytes_per_line
= ximg
->bytes_per_line
;
1885 bytes_per_line
= (width
>> 3) + ((width
& 7) != 0);
1887 return (width
<= (INT_MAX
- (bitmap_pad
- 1)) / depth
1888 && height
<= X_IMAGE_BYTES_MAX
/ bytes_per_line
);
1890 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1891 For now, assume that every image size is allowed on these systems. */
1896 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1897 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1898 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1899 via xmalloc. Print error messages via image_error if an error
1900 occurs. Value is true if successful.
1902 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1903 should indicate the bit depth of the image. */
1906 x_create_x_image_and_pixmap (struct frame
*f
, int width
, int height
, int depth
,
1907 XImagePtr
*ximg
, Pixmap
*pixmap
)
1909 #ifdef HAVE_X_WINDOWS
1910 Display
*display
= FRAME_X_DISPLAY (f
);
1911 Window window
= FRAME_X_WINDOW (f
);
1912 Screen
*screen
= FRAME_X_SCREEN (f
);
1914 eassert (input_blocked_p ());
1917 depth
= DefaultDepthOfScreen (screen
);
1918 *ximg
= XCreateImage (display
, DefaultVisualOfScreen (screen
),
1919 depth
, ZPixmap
, 0, NULL
, width
, height
,
1920 depth
> 16 ? 32 : depth
> 8 ? 16 : 8, 0);
1923 image_error ("Unable to allocate X image", Qnil
, Qnil
);
1927 if (! x_check_image_size (*ximg
, width
, height
))
1929 x_destroy_x_image (*ximg
);
1931 image_error ("Image too large (%dx%d)",
1932 make_number (width
), make_number (height
));
1936 /* Allocate image raster. */
1937 (*ximg
)->data
= xmalloc ((*ximg
)->bytes_per_line
* height
);
1939 /* Allocate a pixmap of the same size. */
1940 *pixmap
= XCreatePixmap (display
, window
, width
, height
, depth
);
1941 if (*pixmap
== NO_PIXMAP
)
1943 x_destroy_x_image (*ximg
);
1945 image_error ("Unable to create X pixmap", Qnil
, Qnil
);
1950 #endif /* HAVE_X_WINDOWS */
1954 BITMAPINFOHEADER
*header
;
1956 int scanline_width_bits
;
1958 int palette_colors
= 0;
1963 if (depth
!= 1 && depth
!= 4 && depth
!= 8
1964 && depth
!= 16 && depth
!= 24 && depth
!= 32)
1966 image_error ("Invalid image bit depth specified", Qnil
, Qnil
);
1970 scanline_width_bits
= width
* depth
;
1971 remainder
= scanline_width_bits
% 32;
1974 scanline_width_bits
+= 32 - remainder
;
1976 /* Bitmaps with a depth less than 16 need a palette. */
1977 /* BITMAPINFO structure already contains the first RGBQUAD. */
1979 palette_colors
= 1 << (depth
- 1);
1981 *ximg
= xmalloc (sizeof (XImage
) + palette_colors
* sizeof (RGBQUAD
));
1983 header
= &(*ximg
)->info
.bmiHeader
;
1984 memset (&(*ximg
)->info
, 0, sizeof (BITMAPINFO
));
1985 header
->biSize
= sizeof (*header
);
1986 header
->biWidth
= width
;
1987 header
->biHeight
= -height
; /* negative indicates a top-down bitmap. */
1988 header
->biPlanes
= 1;
1989 header
->biBitCount
= depth
;
1990 header
->biCompression
= BI_RGB
;
1991 header
->biClrUsed
= palette_colors
;
1993 /* TODO: fill in palette. */
1996 (*ximg
)->info
.bmiColors
[0].rgbBlue
= 0;
1997 (*ximg
)->info
.bmiColors
[0].rgbGreen
= 0;
1998 (*ximg
)->info
.bmiColors
[0].rgbRed
= 0;
1999 (*ximg
)->info
.bmiColors
[0].rgbReserved
= 0;
2000 (*ximg
)->info
.bmiColors
[1].rgbBlue
= 255;
2001 (*ximg
)->info
.bmiColors
[1].rgbGreen
= 255;
2002 (*ximg
)->info
.bmiColors
[1].rgbRed
= 255;
2003 (*ximg
)->info
.bmiColors
[1].rgbReserved
= 0;
2006 hdc
= get_frame_dc (f
);
2008 /* Create a DIBSection and raster array for the bitmap,
2009 and store its handle in *pixmap. */
2010 *pixmap
= CreateDIBSection (hdc
, &((*ximg
)->info
),
2011 (depth
< 16) ? DIB_PAL_COLORS
: DIB_RGB_COLORS
,
2012 /* casting avoids a GCC warning */
2013 (void **)&((*ximg
)->data
), NULL
, 0);
2015 /* Realize display palette and garbage all frames. */
2016 release_frame_dc (f
, hdc
);
2018 if (*pixmap
== NULL
)
2020 DWORD err
= GetLastError ();
2021 Lisp_Object errcode
;
2022 /* All system errors are < 10000, so the following is safe. */
2023 XSETINT (errcode
, err
);
2024 image_error ("Unable to create bitmap, error code %d", errcode
, Qnil
);
2025 x_destroy_x_image (*ximg
);
2031 #endif /* HAVE_NTGUI */
2034 *pixmap
= ns_image_for_XPM (width
, height
, depth
);
2038 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil
, Qnil
);
2047 /* Destroy XImage XIMG. Free XIMG->data. */
2050 x_destroy_x_image (XImagePtr ximg
)
2052 eassert (input_blocked_p ());
2055 #ifdef HAVE_X_WINDOWS
2058 XDestroyImage (ximg
);
2059 #endif /* HAVE_X_WINDOWS */
2061 /* Data will be freed by DestroyObject. */
2064 #endif /* HAVE_NTGUI */
2066 ns_release_object (ximg
);
2067 #endif /* HAVE_NS */
2072 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2073 are width and height of both the image and pixmap. */
2076 x_put_x_image (struct frame
*f
, XImagePtr ximg
, Pixmap pixmap
, int width
, int height
)
2078 #ifdef HAVE_X_WINDOWS
2081 eassert (input_blocked_p ());
2082 gc
= XCreateGC (FRAME_X_DISPLAY (f
), pixmap
, 0, NULL
);
2083 XPutImage (FRAME_X_DISPLAY (f
), pixmap
, gc
, ximg
, 0, 0, 0, 0, width
, height
);
2084 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
2085 #endif /* HAVE_X_WINDOWS */
2088 #if 0 /* I don't think this is necessary looking at where it is used. */
2089 HDC hdc
= get_frame_dc (f
);
2090 SetDIBits (hdc
, pixmap
, 0, height
, ximg
->data
, &(ximg
->info
), DIB_RGB_COLORS
);
2091 release_frame_dc (f
, hdc
);
2093 #endif /* HAVE_NTGUI */
2096 eassert (ximg
== pixmap
);
2097 ns_retain_object (ximg
);
2101 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2102 with image_put_x_image. */
2105 image_create_x_image_and_pixmap (struct frame
*f
, struct image
*img
,
2106 int width
, int height
, int depth
,
2107 XImagePtr
*ximg
, bool mask_p
)
2109 eassert ((!mask_p
? img
->pixmap
: img
->mask
) == NO_PIXMAP
);
2111 return x_create_x_image_and_pixmap (f
, width
, height
, depth
, ximg
,
2112 !mask_p
? &img
->pixmap
: &img
->mask
);
2115 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2116 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2117 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2118 On the other platforms, it puts XIMG into the pixmap, then frees
2119 the X image and its buffer. */
2122 image_put_x_image (struct frame
*f
, struct image
*img
, XImagePtr ximg
,
2125 #ifdef HAVE_X_WINDOWS
2128 eassert (img
->ximg
== NULL
);
2133 eassert (img
->mask_img
== NULL
);
2134 img
->mask_img
= ximg
;
2137 x_put_x_image (f
, ximg
, !mask_p
? img
->pixmap
: img
->mask
,
2138 img
->width
, img
->height
);
2139 x_destroy_x_image (ximg
);
2143 #ifdef HAVE_X_WINDOWS
2144 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2145 the X images and their buffers. */
2148 image_sync_to_pixmaps (struct frame
*f
, struct image
*img
)
2152 x_put_x_image (f
, img
->ximg
, img
->pixmap
, img
->width
, img
->height
);
2153 x_destroy_x_image (img
->ximg
);
2158 x_put_x_image (f
, img
->mask_img
, img
->mask
, img
->width
, img
->height
);
2159 x_destroy_x_image (img
->mask_img
);
2160 img
->mask_img
= NULL
;
2166 /* Create a memory device context for IMG on frame F. It stores the
2167 currently selected GDI object into *PREV for future restoration by
2168 image_unget_x_image_or_dc. */
2170 static XImagePtr_or_DC
2171 image_get_x_image_or_dc (struct frame
*f
, struct image
*img
, bool mask_p
,
2174 HDC frame_dc
= get_frame_dc (f
);
2175 XImagePtr_or_DC ximg
= CreateCompatibleDC (frame_dc
);
2177 release_frame_dc (f
, frame_dc
);
2178 *prev
= SelectObject (ximg
, !mask_p
? img
->pixmap
: img
->mask
);
2184 image_unget_x_image_or_dc (struct image
*img
, bool mask_p
,
2185 XImagePtr_or_DC ximg
, HGDIOBJ prev
)
2187 SelectObject (ximg
, prev
);
2190 #else /* !HAVE_NTGUI */
2191 /* Get the X image for IMG on frame F. The resulting X image data
2192 should be treated as read-only at least on X. */
2195 image_get_x_image (struct frame
*f
, struct image
*img
, bool mask_p
)
2197 #ifdef HAVE_X_WINDOWS
2198 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2203 return XGetImage (FRAME_X_DISPLAY (f
), !mask_p
? img
->pixmap
: img
->mask
,
2204 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
2205 #elif defined (HAVE_NS)
2206 XImagePtr pixmap
= !mask_p
? img
->pixmap
: img
->mask
;
2208 ns_retain_object (pixmap
);
2214 image_unget_x_image (struct image
*img
, bool mask_p
, XImagePtr ximg
)
2216 #ifdef HAVE_X_WINDOWS
2217 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2220 eassert (ximg
== ximg_in_img
);
2222 XDestroyImage (ximg
);
2223 #elif defined (HAVE_NS)
2224 ns_release_object (ximg
);
2227 #endif /* !HAVE_NTGUI */
2230 /***********************************************************************
2232 ***********************************************************************/
2234 /* Find image file FILE. Look in data-directory/images, then
2235 x-bitmap-file-path. Value is the encoded full name of the file
2236 found, or nil if not found. */
2239 x_find_image_file (Lisp_Object file
)
2241 Lisp_Object file_found
, search_path
;
2244 /* TODO I think this should use something like image-load-path
2245 instead. Unfortunately, that can contain non-string elements. */
2246 search_path
= Fcons (Fexpand_file_name (build_string ("images"),
2248 Vx_bitmap_file_path
);
2250 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2251 fd
= openp (search_path
, file
, Qnil
, &file_found
, Qnil
);
2257 file_found
= ENCODE_FILE (file_found
);
2266 /* Read FILE into memory. Value is a pointer to a buffer allocated
2267 with xmalloc holding FILE's contents. Value is null if an error
2268 occurred. *SIZE is set to the size of the file. */
2270 static unsigned char *
2271 slurp_file (char *file
, ptrdiff_t *size
)
2273 FILE *fp
= emacs_fopen (file
, "rb");
2274 unsigned char *buf
= NULL
;
2279 ptrdiff_t count
= SPECPDL_INDEX ();
2280 record_unwind_protect_ptr (fclose_unwind
, fp
);
2282 if (fstat (fileno (fp
), &st
) == 0
2283 && 0 <= st
.st_size
&& st
.st_size
< min (PTRDIFF_MAX
, SIZE_MAX
))
2285 /* Report an error if we read past the purported EOF.
2286 This can happen if the file grows as we read it. */
2287 ptrdiff_t buflen
= st
.st_size
;
2288 buf
= xmalloc (buflen
+ 1);
2289 if (fread (buf
, 1, buflen
+ 1, fp
) == buflen
)
2298 unbind_to (count
, Qnil
);
2306 /***********************************************************************
2308 ***********************************************************************/
2310 static bool xbm_load (struct frame
*f
, struct image
*img
);
2311 static bool xbm_image_p (Lisp_Object object
);
2312 static bool xbm_file_p (Lisp_Object
);
2315 /* Indices of image specification fields in xbm_format, below. */
2317 enum xbm_keyword_index
2335 /* Vector of image_keyword structures describing the format
2336 of valid XBM image specifications. */
2338 static const struct image_keyword xbm_format
[XBM_LAST
] =
2340 {":type", IMAGE_SYMBOL_VALUE
, 1},
2341 {":file", IMAGE_STRING_VALUE
, 0},
2342 {":width", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2343 {":height", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2344 {":data", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2345 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
2346 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
2347 {":ascent", IMAGE_ASCENT_VALUE
, 0},
2348 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
2349 {":relief", IMAGE_INTEGER_VALUE
, 0},
2350 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2351 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2352 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
2355 /* Structure describing the image type XBM. */
2357 static struct image_type xbm_type
=
2367 /* Tokens returned from xbm_scan. */
2376 /* Return true if OBJECT is a valid XBM-type image specification.
2377 A valid specification is a list starting with the symbol `image'
2378 The rest of the list is a property list which must contain an
2381 If the specification specifies a file to load, it must contain
2382 an entry `:file FILENAME' where FILENAME is a string.
2384 If the specification is for a bitmap loaded from memory it must
2385 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2386 WIDTH and HEIGHT are integers > 0. DATA may be:
2388 1. a string large enough to hold the bitmap data, i.e. it must
2389 have a size >= (WIDTH + 7) / 8 * HEIGHT
2391 2. a bool-vector of size >= WIDTH * HEIGHT
2393 3. a vector of strings or bool-vectors, one for each line of the
2396 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2397 may not be specified in this case because they are defined in the
2400 Both the file and data forms may contain the additional entries
2401 `:background COLOR' and `:foreground COLOR'. If not present,
2402 foreground and background of the frame on which the image is
2403 displayed is used. */
2406 xbm_image_p (Lisp_Object object
)
2408 struct image_keyword kw
[XBM_LAST
];
2410 memcpy (kw
, xbm_format
, sizeof kw
);
2411 if (!parse_image_spec (object
, kw
, XBM_LAST
, Qxbm
))
2414 eassert (EQ (kw
[XBM_TYPE
].value
, Qxbm
));
2416 if (kw
[XBM_FILE
].count
)
2418 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_DATA
].count
)
2421 else if (kw
[XBM_DATA
].count
&& xbm_file_p (kw
[XBM_DATA
].value
))
2423 /* In-memory XBM file. */
2424 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_FILE
].count
)
2432 /* Entries for `:width', `:height' and `:data' must be present. */
2433 if (!kw
[XBM_WIDTH
].count
2434 || !kw
[XBM_HEIGHT
].count
2435 || !kw
[XBM_DATA
].count
)
2438 data
= kw
[XBM_DATA
].value
;
2439 width
= XFASTINT (kw
[XBM_WIDTH
].value
);
2440 height
= XFASTINT (kw
[XBM_HEIGHT
].value
);
2442 /* Check type of data, and width and height against contents of
2448 /* Number of elements of the vector must be >= height. */
2449 if (ASIZE (data
) < height
)
2452 /* Each string or bool-vector in data must be large enough
2453 for one line of the image. */
2454 for (i
= 0; i
< height
; ++i
)
2456 Lisp_Object elt
= AREF (data
, i
);
2461 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
)
2464 else if (BOOL_VECTOR_P (elt
))
2466 if (XBOOL_VECTOR (elt
)->size
< width
)
2473 else if (STRINGP (data
))
2476 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
* height
)
2479 else if (BOOL_VECTOR_P (data
))
2481 if (XBOOL_VECTOR (data
)->size
/ height
< width
)
2492 /* Scan a bitmap file. FP is the stream to read from. Value is
2493 either an enumerator from enum xbm_token, or a character for a
2494 single-character token, or 0 at end of file. If scanning an
2495 identifier, store the lexeme of the identifier in SVAL. If
2496 scanning a number, store its value in *IVAL. */
2499 xbm_scan (unsigned char **s
, unsigned char *end
, char *sval
, int *ival
)
2505 /* Skip white space. */
2506 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
2511 else if (c_isdigit (c
))
2513 int value
= 0, digit
;
2515 if (c
== '0' && *s
< end
)
2518 if (c
== 'x' || c
== 'X')
2525 else if (c
>= 'a' && c
<= 'f')
2526 digit
= c
- 'a' + 10;
2527 else if (c
>= 'A' && c
<= 'F')
2528 digit
= c
- 'A' + 10;
2531 value
= 16 * value
+ digit
;
2534 else if (c_isdigit (c
))
2538 && (c
= *(*s
)++, c_isdigit (c
)))
2539 value
= 8 * value
+ c
- '0';
2546 && (c
= *(*s
)++, c_isdigit (c
)))
2547 value
= 10 * value
+ c
- '0';
2555 else if (c_isalpha (c
) || c
== '_')
2559 && (c
= *(*s
)++, (c_isalnum (c
) || c
== '_')))
2566 else if (c
== '/' && **s
== '*')
2568 /* C-style comment. */
2570 while (**s
&& (**s
!= '*' || *(*s
+ 1) != '/'))
2584 /* Create a Windows bitmap from X bitmap data. */
2586 w32_create_pixmap_from_bitmap_data (int width
, int height
, char *data
)
2588 static unsigned char swap_nibble
[16]
2589 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2590 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2591 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2592 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2594 unsigned char *bits
, *p
;
2597 w1
= (width
+ 7) / 8; /* nb of 8bits elt in X bitmap */
2598 w2
= ((width
+ 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2599 bits
= alloca (height
* w2
);
2600 memset (bits
, 0, height
* w2
);
2601 for (i
= 0; i
< height
; i
++)
2604 for (j
= 0; j
< w1
; j
++)
2606 /* Bitswap XBM bytes to match how Windows does things. */
2607 unsigned char c
= *data
++;
2608 *p
++ = (unsigned char)((swap_nibble
[c
& 0xf] << 4)
2609 | (swap_nibble
[(c
>>4) & 0xf]));
2612 bmp
= CreateBitmap (width
, height
, 1, 1, (char *) bits
);
2618 convert_mono_to_color_image (struct frame
*f
, struct image
*img
,
2619 COLORREF foreground
, COLORREF background
)
2621 HDC hdc
, old_img_dc
, new_img_dc
;
2622 HGDIOBJ old_prev
, new_prev
;
2625 hdc
= get_frame_dc (f
);
2626 old_img_dc
= CreateCompatibleDC (hdc
);
2627 new_img_dc
= CreateCompatibleDC (hdc
);
2628 new_pixmap
= CreateCompatibleBitmap (hdc
, img
->width
, img
->height
);
2629 release_frame_dc (f
, hdc
);
2630 old_prev
= SelectObject (old_img_dc
, img
->pixmap
);
2631 new_prev
= SelectObject (new_img_dc
, new_pixmap
);
2632 /* Windows convention for mono bitmaps is black = background,
2633 white = foreground. */
2634 SetTextColor (new_img_dc
, background
);
2635 SetBkColor (new_img_dc
, foreground
);
2637 BitBlt (new_img_dc
, 0, 0, img
->width
, img
->height
, old_img_dc
,
2640 SelectObject (old_img_dc
, old_prev
);
2641 SelectObject (new_img_dc
, new_prev
);
2642 DeleteDC (old_img_dc
);
2643 DeleteDC (new_img_dc
);
2644 DeleteObject (img
->pixmap
);
2645 if (new_pixmap
== 0)
2646 fprintf (stderr
, "Failed to convert image to color.\n");
2648 img
->pixmap
= new_pixmap
;
2651 #define XBM_BIT_SHUFFLE(b) (~(b))
2655 #define XBM_BIT_SHUFFLE(b) (b)
2657 #endif /* HAVE_NTGUI */
2661 Create_Pixmap_From_Bitmap_Data (struct frame
*f
, struct image
*img
, char *data
,
2662 RGB_PIXEL_COLOR fg
, RGB_PIXEL_COLOR bg
,
2663 bool non_default_colors
)
2667 = w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
, data
);
2669 /* If colors were specified, transfer the bitmap to a color one. */
2670 if (non_default_colors
)
2671 convert_mono_to_color_image (f
, img
, fg
, bg
);
2673 #elif defined (HAVE_NS)
2674 img
->pixmap
= ns_image_from_XBM (data
, img
->width
, img
->height
);
2678 (x_check_image_size (0, img
->width
, img
->height
)
2679 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f
),
2682 img
->width
, img
->height
,
2684 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)))
2686 #endif /* !HAVE_NTGUI && !HAVE_NS */
2691 /* Replacement for XReadBitmapFileData which isn't available under old
2692 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2693 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2694 the image. Return in *DATA the bitmap data allocated with xmalloc.
2695 Value is true if successful. DATA null means just test if
2696 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2697 inhibit the call to image_error when the image size is invalid (the
2698 bitmap remains unread). */
2701 xbm_read_bitmap_data (struct frame
*f
, unsigned char *contents
, unsigned char *end
,
2702 int *width
, int *height
, char **data
,
2703 bool inhibit_image_error
)
2705 unsigned char *s
= contents
;
2706 char buffer
[BUFSIZ
];
2709 int bytes_per_line
, i
, nbytes
;
2715 LA1 = xbm_scan (&s, end, buffer, &value)
2717 #define expect(TOKEN) \
2718 if (LA1 != (TOKEN)) \
2723 #define expect_ident(IDENT) \
2724 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2729 *width
= *height
= -1;
2732 LA1
= xbm_scan (&s
, end
, buffer
, &value
);
2734 /* Parse defines for width, height and hot-spots. */
2738 expect_ident ("define");
2739 expect (XBM_TK_IDENT
);
2741 if (LA1
== XBM_TK_NUMBER
)
2743 char *q
= strrchr (buffer
, '_');
2744 q
= q
? q
+ 1 : buffer
;
2745 if (strcmp (q
, "width") == 0)
2747 else if (strcmp (q
, "height") == 0)
2750 expect (XBM_TK_NUMBER
);
2753 if (!check_image_size (f
, *width
, *height
))
2755 if (!inhibit_image_error
)
2756 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
2759 else if (data
== NULL
)
2762 /* Parse bits. Must start with `static'. */
2763 expect_ident ("static");
2764 if (LA1
== XBM_TK_IDENT
)
2766 if (strcmp (buffer
, "unsigned") == 0)
2769 expect_ident ("char");
2771 else if (strcmp (buffer
, "short") == 0)
2775 if (*width
% 16 && *width
% 16 < 9)
2778 else if (strcmp (buffer
, "char") == 0)
2786 expect (XBM_TK_IDENT
);
2792 if (! x_check_image_size (0, *width
, *height
))
2794 if (!inhibit_image_error
)
2795 image_error ("Image too large (%dx%d)",
2796 make_number (*width
), make_number (*height
));
2799 bytes_per_line
= (*width
+ 7) / 8 + padding_p
;
2800 nbytes
= bytes_per_line
* *height
;
2801 p
= *data
= xmalloc (nbytes
);
2805 for (i
= 0; i
< nbytes
; i
+= 2)
2808 expect (XBM_TK_NUMBER
);
2810 *p
++ = XBM_BIT_SHUFFLE (val
);
2811 if (!padding_p
|| ((i
+ 2) % bytes_per_line
))
2812 *p
++ = XBM_BIT_SHUFFLE (value
>> 8);
2814 if (LA1
== ',' || LA1
== '}')
2822 for (i
= 0; i
< nbytes
; ++i
)
2825 expect (XBM_TK_NUMBER
);
2827 *p
++ = XBM_BIT_SHUFFLE (val
);
2829 if (LA1
== ',' || LA1
== '}')
2854 /* Load XBM image IMG which will be displayed on frame F from buffer
2855 CONTENTS. END is the end of the buffer. Value is true if
2859 xbm_load_image (struct frame
*f
, struct image
*img
, unsigned char *contents
,
2866 rc
= xbm_read_bitmap_data (f
, contents
, end
, &img
->width
, &img
->height
,
2870 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
2871 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
2872 bool non_default_colors
= 0;
2875 eassert (img
->width
> 0 && img
->height
> 0);
2877 /* Get foreground and background colors, maybe allocate colors. */
2878 value
= image_spec_value (img
->spec
, QCforeground
, NULL
);
2881 foreground
= x_alloc_image_color (f
, img
, value
, foreground
);
2882 non_default_colors
= 1;
2884 value
= image_spec_value (img
->spec
, QCbackground
, NULL
);
2887 background
= x_alloc_image_color (f
, img
, value
, background
);
2888 img
->background
= background
;
2889 img
->background_valid
= 1;
2890 non_default_colors
= 1;
2893 Create_Pixmap_From_Bitmap_Data (f
, img
, data
,
2894 foreground
, background
,
2895 non_default_colors
);
2898 if (img
->pixmap
== NO_PIXMAP
)
2900 x_clear_image (f
, img
);
2901 image_error ("Unable to create X pixmap for `%s'", img
->spec
, Qnil
);
2907 image_error ("Error loading XBM image `%s'", img
->spec
, Qnil
);
2913 /* Value is true if DATA looks like an in-memory XBM file. */
2916 xbm_file_p (Lisp_Object data
)
2919 return (STRINGP (data
)
2920 && xbm_read_bitmap_data (NULL
, SDATA (data
),
2921 (SDATA (data
) + SBYTES (data
)),
2926 /* Fill image IMG which is used on frame F with pixmap data. Value is
2927 true if successful. */
2930 xbm_load (struct frame
*f
, struct image
*img
)
2933 Lisp_Object file_name
;
2935 eassert (xbm_image_p (img
->spec
));
2937 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2938 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
2939 if (STRINGP (file_name
))
2942 unsigned char *contents
;
2945 file
= x_find_image_file (file_name
);
2946 if (!STRINGP (file
))
2948 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
2952 contents
= slurp_file (SSDATA (file
), &size
);
2953 if (contents
== NULL
)
2955 image_error ("Error loading XBM image `%s'", img
->spec
, Qnil
);
2959 success_p
= xbm_load_image (f
, img
, contents
, contents
+ size
);
2964 struct image_keyword fmt
[XBM_LAST
];
2966 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
2967 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
2968 bool non_default_colors
= 0;
2971 bool in_memory_file_p
= 0;
2973 /* See if data looks like an in-memory XBM file. */
2974 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
2975 in_memory_file_p
= xbm_file_p (data
);
2977 /* Parse the image specification. */
2978 memcpy (fmt
, xbm_format
, sizeof fmt
);
2979 parsed_p
= parse_image_spec (img
->spec
, fmt
, XBM_LAST
, Qxbm
);
2982 /* Get specified width, and height. */
2983 if (!in_memory_file_p
)
2985 img
->width
= XFASTINT (fmt
[XBM_WIDTH
].value
);
2986 img
->height
= XFASTINT (fmt
[XBM_HEIGHT
].value
);
2987 eassert (img
->width
> 0 && img
->height
> 0);
2988 if (!check_image_size (f
, img
->width
, img
->height
))
2990 image_error ("Invalid image size (see `max-image-size')",
2996 /* Get foreground and background colors, maybe allocate colors. */
2997 if (fmt
[XBM_FOREGROUND
].count
2998 && STRINGP (fmt
[XBM_FOREGROUND
].value
))
3000 foreground
= x_alloc_image_color (f
, img
, fmt
[XBM_FOREGROUND
].value
,
3002 non_default_colors
= 1;
3005 if (fmt
[XBM_BACKGROUND
].count
3006 && STRINGP (fmt
[XBM_BACKGROUND
].value
))
3008 background
= x_alloc_image_color (f
, img
, fmt
[XBM_BACKGROUND
].value
,
3010 non_default_colors
= 1;
3013 if (in_memory_file_p
)
3014 success_p
= xbm_load_image (f
, img
, SDATA (data
),
3023 int nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3025 p
= bits
= alloca (nbytes
* img
->height
);
3026 for (i
= 0; i
< img
->height
; ++i
, p
+= nbytes
)
3028 Lisp_Object line
= AREF (data
, i
);
3030 memcpy (p
, SDATA (line
), nbytes
);
3032 memcpy (p
, XBOOL_VECTOR (line
)->data
, nbytes
);
3035 else if (STRINGP (data
))
3036 bits
= SSDATA (data
);
3038 bits
= (char *) XBOOL_VECTOR (data
)->data
;
3044 /* Windows mono bitmaps are reversed compared with X. */
3045 invertedBits
= bits
;
3046 nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
3048 bits
= alloca (nbytes
);
3049 for (i
= 0; i
< nbytes
; i
++)
3050 bits
[i
] = XBM_BIT_SHUFFLE (invertedBits
[i
]);
3053 /* Create the pixmap. */
3055 if (x_check_image_size (0, img
->width
, img
->height
))
3056 Create_Pixmap_From_Bitmap_Data (f
, img
, bits
,
3057 foreground
, background
,
3058 non_default_colors
);
3060 img
->pixmap
= NO_PIXMAP
;
3066 image_error ("Unable to create pixmap for XBM image `%s'",
3068 x_clear_image (f
, img
);
3078 /***********************************************************************
3080 ***********************************************************************/
3082 #if defined (HAVE_XPM) || defined (HAVE_NS)
3084 static bool xpm_image_p (Lisp_Object object
);
3085 static bool xpm_load (struct frame
*f
, struct image
*img
);
3087 #endif /* HAVE_XPM || HAVE_NS */
3091 /* Indicate to xpm.h that we don't have Xlib. */
3093 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3094 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3095 #define XColor xpm_XColor
3096 #define XImage xpm_XImage
3097 #define Display xpm_Display
3098 #define PIXEL_ALREADY_TYPEDEFED
3099 #include "X11/xpm.h"
3104 #undef PIXEL_ALREADY_TYPEDEFED
3106 #include "X11/xpm.h"
3107 #endif /* HAVE_NTGUI */
3108 #endif /* HAVE_XPM */
3110 #if defined (HAVE_XPM) || defined (HAVE_NS)
3111 /* The symbol `xpm' identifying XPM-format images. */
3113 static Lisp_Object Qxpm
;
3115 /* Indices of image specification fields in xpm_format, below. */
3117 enum xpm_keyword_index
3133 /* Vector of image_keyword structures describing the format
3134 of valid XPM image specifications. */
3136 static const struct image_keyword xpm_format
[XPM_LAST
] =
3138 {":type", IMAGE_SYMBOL_VALUE
, 1},
3139 {":file", IMAGE_STRING_VALUE
, 0},
3140 {":data", IMAGE_STRING_VALUE
, 0},
3141 {":ascent", IMAGE_ASCENT_VALUE
, 0},
3142 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
3143 {":relief", IMAGE_INTEGER_VALUE
, 0},
3144 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3145 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3146 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3147 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3148 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
3151 #if defined HAVE_NTGUI && defined WINDOWSNT
3152 static bool init_xpm_functions (void);
3154 #define init_xpm_functions NULL
3157 /* Structure describing the image type XPM. */
3159 static struct image_type xpm_type
=
3169 #ifdef HAVE_X_WINDOWS
3171 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3172 functions for allocating image colors. Our own functions handle
3173 color allocation failures more gracefully than the ones on the XPM
3176 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3177 #define ALLOC_XPM_COLORS
3179 #endif /* HAVE_X_WINDOWS */
3181 #ifdef ALLOC_XPM_COLORS
3183 static struct xpm_cached_color
*xpm_cache_color (struct frame
*, char *,
3186 /* An entry in a hash table used to cache color definitions of named
3187 colors. This cache is necessary to speed up XPM image loading in
3188 case we do color allocations ourselves. Without it, we would need
3189 a call to XParseColor per pixel in the image. */
3191 struct xpm_cached_color
3193 /* Next in collision chain. */
3194 struct xpm_cached_color
*next
;
3196 /* Color definition (RGB and pixel color). */
3200 char name
[FLEXIBLE_ARRAY_MEMBER
];
3203 /* The hash table used for the color cache, and its bucket vector
3206 #define XPM_COLOR_CACHE_BUCKETS 1001
3207 static struct xpm_cached_color
**xpm_color_cache
;
3209 /* Initialize the color cache. */
3212 xpm_init_color_cache (struct frame
*f
, XpmAttributes
*attrs
)
3214 size_t nbytes
= XPM_COLOR_CACHE_BUCKETS
* sizeof *xpm_color_cache
;
3215 xpm_color_cache
= xzalloc (nbytes
);
3216 init_color_table ();
3218 if (attrs
->valuemask
& XpmColorSymbols
)
3223 for (i
= 0; i
< attrs
->numsymbols
; ++i
)
3224 if (XParseColor (FRAME_X_DISPLAY (f
), FRAME_X_COLORMAP (f
),
3225 attrs
->colorsymbols
[i
].value
, &color
))
3227 color
.pixel
= lookup_rgb_color (f
, color
.red
, color
.green
,
3229 xpm_cache_color (f
, attrs
->colorsymbols
[i
].name
, &color
, -1);
3234 /* Free the color cache. */
3237 xpm_free_color_cache (void)
3239 struct xpm_cached_color
*p
, *next
;
3242 for (i
= 0; i
< XPM_COLOR_CACHE_BUCKETS
; ++i
)
3243 for (p
= xpm_color_cache
[i
]; p
; p
= next
)
3249 xfree (xpm_color_cache
);
3250 xpm_color_cache
= NULL
;
3251 free_color_table ();
3254 /* Return the bucket index for color named COLOR_NAME in the color
3258 xpm_color_bucket (char *color_name
)
3260 EMACS_UINT hash
= hash_string (color_name
, strlen (color_name
));
3261 return hash
% XPM_COLOR_CACHE_BUCKETS
;
3265 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3266 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3269 static struct xpm_cached_color
*
3270 xpm_cache_color (struct frame
*f
, char *color_name
, XColor
*color
, int bucket
)
3273 struct xpm_cached_color
*p
;
3276 bucket
= xpm_color_bucket (color_name
);
3278 nbytes
= offsetof (struct xpm_cached_color
, name
) + strlen (color_name
) + 1;
3279 p
= xmalloc (nbytes
);
3280 strcpy (p
->name
, color_name
);
3282 p
->next
= xpm_color_cache
[bucket
];
3283 xpm_color_cache
[bucket
] = p
;
3287 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3288 return the cached definition in *COLOR. Otherwise, make a new
3289 entry in the cache and allocate the color. Value is false if color
3290 allocation failed. */
3293 xpm_lookup_color (struct frame
*f
, char *color_name
, XColor
*color
)
3295 struct xpm_cached_color
*p
;
3296 int h
= xpm_color_bucket (color_name
);
3298 for (p
= xpm_color_cache
[h
]; p
; p
= p
->next
)
3299 if (strcmp (p
->name
, color_name
) == 0)
3304 else if (XParseColor (FRAME_X_DISPLAY (f
), FRAME_X_COLORMAP (f
),
3307 color
->pixel
= lookup_rgb_color (f
, color
->red
, color
->green
,
3309 p
= xpm_cache_color (f
, color_name
, color
, h
);
3311 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3312 with transparency, and it's useful. */
3313 else if (strcmp ("opaque", color_name
) == 0)
3315 memset (color
, 0, sizeof (XColor
)); /* Is this necessary/correct? */
3316 color
->pixel
= FRAME_FOREGROUND_PIXEL (f
);
3317 p
= xpm_cache_color (f
, color_name
, color
, h
);
3324 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3325 CLOSURE is a pointer to the frame on which we allocate the
3326 color. Return in *COLOR the allocated color. Value is non-zero
3330 xpm_alloc_color (Display
*dpy
, Colormap cmap
, char *color_name
, XColor
*color
,
3333 return xpm_lookup_color (closure
, color_name
, color
);
3337 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3338 is a pointer to the frame on which we allocate the color. Value is
3339 non-zero if successful. */
3342 xpm_free_colors (Display
*dpy
, Colormap cmap
, Pixel
*pixels
, int npixels
, void *closure
)
3347 #endif /* ALLOC_XPM_COLORS */
3352 /* XPM library details. */
3354 DEF_IMGLIB_FN (void, XpmFreeAttributes
, (XpmAttributes
*));
3355 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer
, (Display
*, char *, xpm_XImage
**,
3356 xpm_XImage
**, XpmAttributes
*));
3357 DEF_IMGLIB_FN (int, XpmReadFileToImage
, (Display
*, char *, xpm_XImage
**,
3358 xpm_XImage
**, XpmAttributes
*));
3359 DEF_IMGLIB_FN (void, XImageFree
, (xpm_XImage
*));
3362 init_xpm_functions (void)
3366 if (!(library
= w32_delayed_load (Qxpm
)))
3369 LOAD_IMGLIB_FN (library
, XpmFreeAttributes
);
3370 LOAD_IMGLIB_FN (library
, XpmCreateImageFromBuffer
);
3371 LOAD_IMGLIB_FN (library
, XpmReadFileToImage
);
3372 LOAD_IMGLIB_FN (library
, XImageFree
);
3376 #endif /* WINDOWSNT */
3378 #if defined HAVE_NTGUI && !defined WINDOWSNT
3379 /* Glue for code below */
3380 #define fn_XpmReadFileToImage XpmReadFileToImage
3381 #define fn_XpmCreateImageFromBuffer XpmCreateImageFromBuffer
3382 #define fn_XImageFree XImageFree
3383 #define fn_XpmFreeAttributes XpmFreeAttributes
3384 #endif /* HAVE_NTGUI && !WINDOWSNT */
3386 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3387 for XPM images. Such a list must consist of conses whose car and
3391 xpm_valid_color_symbols_p (Lisp_Object color_symbols
)
3393 while (CONSP (color_symbols
))
3395 Lisp_Object sym
= XCAR (color_symbols
);
3397 || !STRINGP (XCAR (sym
))
3398 || !STRINGP (XCDR (sym
)))
3400 color_symbols
= XCDR (color_symbols
);
3403 return NILP (color_symbols
);
3407 /* Value is true if OBJECT is a valid XPM image specification. */
3410 xpm_image_p (Lisp_Object object
)
3412 struct image_keyword fmt
[XPM_LAST
];
3413 memcpy (fmt
, xpm_format
, sizeof fmt
);
3414 return (parse_image_spec (object
, fmt
, XPM_LAST
, Qxpm
)
3415 /* Either `:file' or `:data' must be present. */
3416 && fmt
[XPM_FILE
].count
+ fmt
[XPM_DATA
].count
== 1
3417 /* Either no `:color-symbols' or it's a list of conses
3418 whose car and cdr are strings. */
3419 && (fmt
[XPM_COLOR_SYMBOLS
].count
== 0
3420 || xpm_valid_color_symbols_p (fmt
[XPM_COLOR_SYMBOLS
].value
)));
3423 #endif /* HAVE_XPM || HAVE_NS */
3425 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3427 x_create_bitmap_from_xpm_data (struct frame
*f
, const char **bits
)
3429 Display_Info
*dpyinfo
= FRAME_X_DISPLAY_INFO (f
);
3432 XpmAttributes attrs
;
3433 Pixmap bitmap
, mask
;
3435 memset (&attrs
, 0, sizeof attrs
);
3437 attrs
.visual
= FRAME_X_VISUAL (f
);
3438 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3439 attrs
.valuemask
|= XpmVisual
;
3440 attrs
.valuemask
|= XpmColormap
;
3442 rc
= XpmCreatePixmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3443 (char **) bits
, &bitmap
, &mask
, &attrs
);
3444 if (rc
!= XpmSuccess
)
3446 XpmFreeAttributes (&attrs
);
3450 id
= x_allocate_bitmap_record (f
);
3451 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
3452 dpyinfo
->bitmaps
[id
- 1].have_mask
= 1;
3453 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
3454 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
3455 dpyinfo
->bitmaps
[id
- 1].height
= attrs
.height
;
3456 dpyinfo
->bitmaps
[id
- 1].width
= attrs
.width
;
3457 dpyinfo
->bitmaps
[id
- 1].depth
= attrs
.depth
;
3458 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
3460 XpmFreeAttributes (&attrs
);
3463 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3465 /* Load image IMG which will be displayed on frame F. Value is
3466 true if successful. */
3471 xpm_load (struct frame
*f
, struct image
*img
)
3474 XpmAttributes attrs
;
3475 Lisp_Object specified_file
, color_symbols
;
3478 xpm_XImage
* xpm_image
= NULL
, * xpm_mask
= NULL
;
3479 #endif /* HAVE_NTGUI */
3481 /* Configure the XPM lib. Use the visual of frame F. Allocate
3482 close colors. Return colors allocated. */
3483 memset (&attrs
, 0, sizeof attrs
);
3486 attrs
.visual
= FRAME_X_VISUAL (f
);
3487 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3488 attrs
.valuemask
|= XpmVisual
;
3489 attrs
.valuemask
|= XpmColormap
;
3490 #endif /* HAVE_NTGUI */
3492 #ifdef ALLOC_XPM_COLORS
3493 /* Allocate colors with our own functions which handle
3494 failing color allocation more gracefully. */
3495 attrs
.color_closure
= f
;
3496 attrs
.alloc_color
= xpm_alloc_color
;
3497 attrs
.free_colors
= xpm_free_colors
;
3498 attrs
.valuemask
|= XpmAllocColor
| XpmFreeColors
| XpmColorClosure
;
3499 #else /* not ALLOC_XPM_COLORS */
3500 /* Let the XPM lib allocate colors. */
3501 attrs
.valuemask
|= XpmReturnAllocPixels
;
3502 #ifdef XpmAllocCloseColors
3503 attrs
.alloc_close_colors
= 1;
3504 attrs
.valuemask
|= XpmAllocCloseColors
;
3505 #else /* not XpmAllocCloseColors */
3506 attrs
.closeness
= 600;
3507 attrs
.valuemask
|= XpmCloseness
;
3508 #endif /* not XpmAllocCloseColors */
3509 #endif /* ALLOC_XPM_COLORS */
3511 /* If image specification contains symbolic color definitions, add
3512 these to `attrs'. */
3513 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
3514 if (CONSP (color_symbols
))
3517 XpmColorSymbol
*xpm_syms
;
3520 attrs
.valuemask
|= XpmColorSymbols
;
3522 /* Count number of symbols. */
3523 attrs
.numsymbols
= 0;
3524 for (tail
= color_symbols
; CONSP (tail
); tail
= XCDR (tail
))
3527 /* Allocate an XpmColorSymbol array. */
3528 size
= attrs
.numsymbols
* sizeof *xpm_syms
;
3529 xpm_syms
= alloca (size
);
3530 memset (xpm_syms
, 0, size
);
3531 attrs
.colorsymbols
= xpm_syms
;
3533 /* Fill the color symbol array. */
3534 for (tail
= color_symbols
, i
= 0;
3536 ++i
, tail
= XCDR (tail
))
3540 char *empty_string
= (char *) "";
3542 if (!CONSP (XCAR (tail
)))
3544 xpm_syms
[i
].name
= empty_string
;
3545 xpm_syms
[i
].value
= empty_string
;
3548 name
= XCAR (XCAR (tail
));
3549 color
= XCDR (XCAR (tail
));
3552 xpm_syms
[i
].name
= alloca (SCHARS (name
) + 1);
3553 strcpy (xpm_syms
[i
].name
, SSDATA (name
));
3556 xpm_syms
[i
].name
= empty_string
;
3557 if (STRINGP (color
))
3559 xpm_syms
[i
].value
= alloca (SCHARS (color
) + 1);
3560 strcpy (xpm_syms
[i
].value
, SSDATA (color
));
3563 xpm_syms
[i
].value
= empty_string
;
3567 /* Create a pixmap for the image, either from a file, or from a
3568 string buffer containing data in the same format as an XPM file. */
3569 #ifdef ALLOC_XPM_COLORS
3570 xpm_init_color_cache (f
, &attrs
);
3573 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
3577 HDC frame_dc
= get_frame_dc (f
);
3578 hdc
= CreateCompatibleDC (frame_dc
);
3579 release_frame_dc (f
, frame_dc
);
3581 #endif /* HAVE_NTGUI */
3583 if (STRINGP (specified_file
))
3585 Lisp_Object file
= x_find_image_file (specified_file
);
3586 if (!STRINGP (file
))
3588 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
3589 #ifdef ALLOC_XPM_COLORS
3590 xpm_free_color_cache ();
3596 /* XpmReadFileToPixmap is not available in the Windows port of
3597 libxpm. But XpmReadFileToImage almost does what we want. */
3598 rc
= fn_XpmReadFileToImage (&hdc
, SDATA (file
),
3599 &xpm_image
, &xpm_mask
,
3602 rc
= XpmReadFileToImage (FRAME_X_DISPLAY (f
), SSDATA (file
),
3603 &img
->ximg
, &img
->mask_img
,
3605 #endif /* HAVE_NTGUI */
3609 Lisp_Object buffer
= image_spec_value (img
->spec
, QCdata
, NULL
);
3610 if (!STRINGP (buffer
))
3612 image_error ("Invalid image data `%s'", buffer
, Qnil
);
3613 #ifdef ALLOC_XPM_COLORS
3614 xpm_free_color_cache ();
3619 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3620 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3621 rc
= fn_XpmCreateImageFromBuffer (&hdc
, SDATA (buffer
),
3622 &xpm_image
, &xpm_mask
,
3625 rc
= XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f
), SSDATA (buffer
),
3626 &img
->ximg
, &img
->mask_img
,
3628 #endif /* HAVE_NTGUI */
3631 #ifdef HAVE_X_WINDOWS
3632 if (rc
== XpmSuccess
)
3634 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3635 img
->ximg
->width
, img
->ximg
->height
,
3637 if (img
->pixmap
== NO_PIXMAP
)
3639 x_clear_image (f
, img
);
3642 else if (img
->mask_img
)
3644 img
->mask
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3645 img
->mask_img
->width
,
3646 img
->mask_img
->height
,
3647 img
->mask_img
->depth
);
3648 if (img
->mask
== NO_PIXMAP
)
3650 x_clear_image (f
, img
);
3657 if (rc
== XpmSuccess
)
3659 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3660 img
->colors
= colors_in_color_table (&img
->ncolors
);
3661 #else /* not ALLOC_XPM_COLORS */
3665 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3666 plus some duplicate attributes. */
3667 if (xpm_image
&& xpm_image
->bitmap
)
3669 img
->pixmap
= xpm_image
->bitmap
;
3670 /* XImageFree in libXpm frees XImage struct without destroying
3671 the bitmap, which is what we want. */
3672 fn_XImageFree (xpm_image
);
3674 if (xpm_mask
&& xpm_mask
->bitmap
)
3676 /* The mask appears to be inverted compared with what we expect.
3677 TODO: invert our expectations. See other places where we
3678 have to invert bits because our idea of masks is backwards. */
3680 old_obj
= SelectObject (hdc
, xpm_mask
->bitmap
);
3682 PatBlt (hdc
, 0, 0, xpm_mask
->width
, xpm_mask
->height
, DSTINVERT
);
3683 SelectObject (hdc
, old_obj
);
3685 img
->mask
= xpm_mask
->bitmap
;
3686 fn_XImageFree (xpm_mask
);
3691 #endif /* HAVE_NTGUI */
3693 /* Remember allocated colors. */
3694 img
->colors
= xnmalloc (attrs
.nalloc_pixels
, sizeof *img
->colors
);
3695 img
->ncolors
= attrs
.nalloc_pixels
;
3696 for (i
= 0; i
< attrs
.nalloc_pixels
; ++i
)
3698 img
->colors
[i
] = attrs
.alloc_pixels
[i
];
3699 #ifdef DEBUG_X_COLORS
3700 register_color (img
->colors
[i
]);
3703 #endif /* not ALLOC_XPM_COLORS */
3705 img
->width
= attrs
.width
;
3706 img
->height
= attrs
.height
;
3707 eassert (img
->width
> 0 && img
->height
> 0);
3709 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3711 fn_XpmFreeAttributes (&attrs
);
3713 XpmFreeAttributes (&attrs
);
3714 #endif /* HAVE_NTGUI */
3716 #ifdef HAVE_X_WINDOWS
3717 /* Maybe fill in the background field while we have ximg handy. */
3718 IMAGE_BACKGROUND (img
, f
, img
->ximg
);
3720 /* Fill in the background_transparent field while we have the
3722 image_background_transparent (img
, f
, img
->mask_img
);
3729 #endif /* HAVE_NTGUI */
3734 image_error ("Error opening XPM file (%s)", img
->spec
, Qnil
);
3737 case XpmFileInvalid
:
3738 image_error ("Invalid XPM file (%s)", img
->spec
, Qnil
);
3742 image_error ("Out of memory (%s)", img
->spec
, Qnil
);
3745 case XpmColorFailed
:
3746 image_error ("Color allocation error (%s)", img
->spec
, Qnil
);
3750 image_error ("Unknown error (%s)", img
->spec
, Qnil
);
3755 #ifdef ALLOC_XPM_COLORS
3756 xpm_free_color_cache ();
3758 return rc
== XpmSuccess
;
3761 #endif /* HAVE_XPM */
3763 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3765 /* XPM support functions for NS where libxpm is not available.
3766 Only XPM version 3 (without any extensions) is supported. */
3768 static void xpm_put_color_table_v (Lisp_Object
, const unsigned char *,
3770 static Lisp_Object
xpm_get_color_table_v (Lisp_Object
,
3771 const unsigned char *, int);
3772 static void xpm_put_color_table_h (Lisp_Object
, const unsigned char *,
3774 static Lisp_Object
xpm_get_color_table_h (Lisp_Object
,
3775 const unsigned char *, int);
3777 /* Tokens returned from xpm_scan. */
3786 /* Scan an XPM data and return a character (< 256) or a token defined
3787 by enum xpm_token above. *S and END are the start (inclusive) and
3788 the end (exclusive) addresses of the data, respectively. Advance
3789 *S while scanning. If token is either XPM_TK_IDENT or
3790 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3791 length of the corresponding token, respectively. */
3794 xpm_scan (const unsigned char **s
,
3795 const unsigned char *end
,
3796 const unsigned char **beg
,
3803 /* Skip white-space. */
3804 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
3807 /* gnus-pointer.xpm uses '-' in its identifier.
3808 sb-dir-plus.xpm uses '+' in its identifier. */
3809 if (c_isalpha (c
) || c
== '_' || c
== '-' || c
== '+')
3813 && (c
= **s
, c_isalnum (c
)
3814 || c
== '_' || c
== '-' || c
== '+'))
3817 return XPM_TK_IDENT
;
3822 while (*s
< end
&& **s
!= '"')
3827 return XPM_TK_STRING
;
3831 if (*s
< end
&& **s
== '*')
3833 /* C-style comment. */
3837 while (*s
< end
&& *(*s
)++ != '*')
3840 while (*s
< end
&& **s
!= '/');
3854 /* Functions for color table lookup in XPM data. A key is a string
3855 specifying the color of each pixel in XPM data. A value is either
3856 an integer that specifies a pixel color, Qt that specifies
3857 transparency, or Qnil for the unspecified color. If the length of
3858 the key string is one, a vector is used as a table. Otherwise, a
3859 hash table is used. */
3862 xpm_make_color_table_v (void (**put_func
) (Lisp_Object
,
3863 const unsigned char *,
3866 Lisp_Object (**get_func
) (Lisp_Object
,
3867 const unsigned char *,
3870 *put_func
= xpm_put_color_table_v
;
3871 *get_func
= xpm_get_color_table_v
;
3872 return Fmake_vector (make_number (256), Qnil
);
3876 xpm_put_color_table_v (Lisp_Object color_table
,
3877 const unsigned char *chars_start
,
3881 ASET (color_table
, *chars_start
, color
);
3885 xpm_get_color_table_v (Lisp_Object color_table
,
3886 const unsigned char *chars_start
,
3889 return AREF (color_table
, *chars_start
);
3893 xpm_make_color_table_h (void (**put_func
) (Lisp_Object
,
3894 const unsigned char *,
3897 Lisp_Object (**get_func
) (Lisp_Object
,
3898 const unsigned char *,
3901 *put_func
= xpm_put_color_table_h
;
3902 *get_func
= xpm_get_color_table_h
;
3903 return make_hash_table (hashtest_equal
, make_number (DEFAULT_HASH_SIZE
),
3904 make_float (DEFAULT_REHASH_SIZE
),
3905 make_float (DEFAULT_REHASH_THRESHOLD
),
3910 xpm_put_color_table_h (Lisp_Object color_table
,
3911 const unsigned char *chars_start
,
3915 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
3916 EMACS_UINT hash_code
;
3917 Lisp_Object chars
= make_unibyte_string (chars_start
, chars_len
);
3919 hash_lookup (table
, chars
, &hash_code
);
3920 hash_put (table
, chars
, color
, hash_code
);
3924 xpm_get_color_table_h (Lisp_Object color_table
,
3925 const unsigned char *chars_start
,
3928 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
3930 hash_lookup (table
, make_unibyte_string (chars_start
, chars_len
), NULL
);
3932 return i
>= 0 ? HASH_VALUE (table
, i
) : Qnil
;
3935 enum xpm_color_key
{
3943 static const char xpm_color_key_strings
[][4] = {"s", "m", "g4", "g", "c"};
3946 xpm_str_to_color_key (const char *s
)
3951 i
< sizeof xpm_color_key_strings
/ sizeof xpm_color_key_strings
[0];
3953 if (strcmp (xpm_color_key_strings
[i
], s
) == 0)
3959 xpm_load_image (struct frame
*f
,
3961 const unsigned char *contents
,
3962 const unsigned char *end
)
3964 const unsigned char *s
= contents
, *beg
, *str
;
3965 unsigned char buffer
[BUFSIZ
];
3966 int width
, height
, x
, y
;
3967 int num_colors
, chars_per_pixel
;
3970 void (*put_color_table
) (Lisp_Object
, const unsigned char *, int, Lisp_Object
);
3971 Lisp_Object (*get_color_table
) (Lisp_Object
, const unsigned char *, int);
3972 Lisp_Object frame
, color_symbols
, color_table
;
3975 XImagePtr ximg
= NULL
, mask_img
= NULL
;
3978 LA1 = xpm_scan (&s, end, &beg, &len)
3980 #define expect(TOKEN) \
3981 if (LA1 != (TOKEN)) \
3986 #define expect_ident(IDENT) \
3987 if (LA1 == XPM_TK_IDENT \
3988 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3993 if (!(end
- s
>= 9 && memcmp (s
, "/* XPM */", 9) == 0))
3997 expect_ident ("static");
3998 expect_ident ("char");
4000 expect (XPM_TK_IDENT
);
4005 expect (XPM_TK_STRING
);
4008 memcpy (buffer
, beg
, len
);
4010 if (sscanf (buffer
, "%d %d %d %d", &width
, &height
,
4011 &num_colors
, &chars_per_pixel
) != 4
4012 || width
<= 0 || height
<= 0
4013 || num_colors
<= 0 || chars_per_pixel
<= 0)
4016 if (!check_image_size (f
, width
, height
))
4018 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
4022 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0)
4024 || !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
4029 image_error ("Image too large", Qnil
, Qnil
);
4035 XSETFRAME (frame
, f
);
4036 if (!NILP (Fxw_display_color_p (frame
)))
4037 best_key
= XPM_COLOR_KEY_C
;
4038 else if (!NILP (Fx_display_grayscale_p (frame
)))
4039 best_key
= (XFASTINT (Fx_display_planes (frame
)) > 2
4040 ? XPM_COLOR_KEY_G
: XPM_COLOR_KEY_G4
);
4042 best_key
= XPM_COLOR_KEY_M
;
4044 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
4045 if (chars_per_pixel
== 1)
4046 color_table
= xpm_make_color_table_v (&put_color_table
,
4049 color_table
= xpm_make_color_table_h (&put_color_table
,
4052 while (num_colors
-- > 0)
4054 char *color
, *max_color
;
4055 int key
, next_key
, max_key
= 0;
4056 Lisp_Object symbol_color
= Qnil
, color_val
;
4059 expect (XPM_TK_STRING
);
4060 if (len
<= chars_per_pixel
|| len
>= BUFSIZ
+ chars_per_pixel
)
4062 memcpy (buffer
, beg
+ chars_per_pixel
, len
- chars_per_pixel
);
4063 buffer
[len
- chars_per_pixel
] = '\0';
4065 str
= strtok (buffer
, " \t");
4068 key
= xpm_str_to_color_key (str
);
4073 color
= strtok (NULL
, " \t");
4077 while ((str
= strtok (NULL
, " \t")) != NULL
)
4079 next_key
= xpm_str_to_color_key (str
);
4082 color
[strlen (color
)] = ' ';
4085 if (key
== XPM_COLOR_KEY_S
)
4087 if (NILP (symbol_color
))
4088 symbol_color
= build_string (color
);
4090 else if (max_key
< key
&& key
<= best_key
)
4100 if (!NILP (color_symbols
) && !NILP (symbol_color
))
4102 Lisp_Object specified_color
= Fassoc (symbol_color
, color_symbols
);
4104 if (CONSP (specified_color
) && STRINGP (XCDR (specified_color
)))
4106 if (xstrcasecmp (SSDATA (XCDR (specified_color
)), "None") == 0)
4108 else if (x_defined_color (f
, SSDATA (XCDR (specified_color
)),
4110 color_val
= make_number (cdef
.pixel
);
4113 if (NILP (color_val
) && max_key
> 0)
4115 if (xstrcasecmp (max_color
, "None") == 0)
4117 else if (x_defined_color (f
, max_color
, &cdef
, 0))
4118 color_val
= make_number (cdef
.pixel
);
4120 if (!NILP (color_val
))
4121 (*put_color_table
) (color_table
, beg
, chars_per_pixel
, color_val
);
4126 for (y
= 0; y
< height
; y
++)
4128 expect (XPM_TK_STRING
);
4130 if (len
< width
* chars_per_pixel
)
4132 for (x
= 0; x
< width
; x
++, str
+= chars_per_pixel
)
4134 Lisp_Object color_val
=
4135 (*get_color_table
) (color_table
, str
, chars_per_pixel
);
4137 XPutPixel (ximg
, x
, y
,
4138 (INTEGERP (color_val
) ? XINT (color_val
)
4139 : FRAME_FOREGROUND_PIXEL (f
)));
4141 XPutPixel (mask_img
, x
, y
,
4142 (!EQ (color_val
, Qt
) ? PIX_MASK_DRAW
4143 : (have_mask
= 1, PIX_MASK_RETAIN
)));
4145 if (EQ (color_val
, Qt
))
4146 ns_set_alpha (ximg
, x
, y
, 0);
4154 img
->height
= height
;
4156 /* Maybe fill in the background field while we have ximg handy. */
4157 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
4158 IMAGE_BACKGROUND (img
, f
, ximg
);
4160 image_put_x_image (f
, img
, ximg
, 0);
4164 /* Fill in the background_transparent field while we have the
4166 image_background_transparent (img
, f
, mask_img
);
4168 image_put_x_image (f
, img
, mask_img
, 1);
4172 x_destroy_x_image (mask_img
);
4173 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4179 image_error ("Invalid XPM file (%s)", img
->spec
, Qnil
);
4180 x_destroy_x_image (ximg
);
4181 x_destroy_x_image (mask_img
);
4182 x_clear_image (f
, img
);
4191 xpm_load (struct frame
*f
,
4195 Lisp_Object file_name
;
4197 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4198 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
4199 if (STRINGP (file_name
))
4202 unsigned char *contents
;
4205 file
= x_find_image_file (file_name
);
4206 if (!STRINGP (file
))
4208 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
4212 contents
= slurp_file (SSDATA (file
), &size
);
4213 if (contents
== NULL
)
4215 image_error ("Error loading XPM image `%s'", img
->spec
, Qnil
);
4219 success_p
= xpm_load_image (f
, img
, contents
, contents
+ size
);
4226 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
4227 if (!STRINGP (data
))
4229 image_error ("Invalid image data `%s'", data
, Qnil
);
4232 success_p
= xpm_load_image (f
, img
, SDATA (data
),
4233 SDATA (data
) + SBYTES (data
));
4239 #endif /* HAVE_NS && !HAVE_XPM */
4243 /***********************************************************************
4245 ***********************************************************************/
4247 #ifdef COLOR_TABLE_SUPPORT
4249 /* An entry in the color table mapping an RGB color to a pixel color. */
4254 unsigned long pixel
;
4256 /* Next in color table collision list. */
4257 struct ct_color
*next
;
4260 /* The bucket vector size to use. Must be prime. */
4264 /* Value is a hash of the RGB color given by R, G, and B. */
4266 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4268 /* The color hash table. */
4270 static struct ct_color
**ct_table
;
4272 /* Number of entries in the color table. */
4274 static int ct_colors_allocated
;
4277 ct_colors_allocated_max
=
4279 min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof (unsigned long))
4282 /* Initialize the color table. */
4285 init_color_table (void)
4287 int size
= CT_SIZE
* sizeof (*ct_table
);
4288 ct_table
= xzalloc (size
);
4289 ct_colors_allocated
= 0;
4293 /* Free memory associated with the color table. */
4296 free_color_table (void)
4299 struct ct_color
*p
, *next
;
4301 for (i
= 0; i
< CT_SIZE
; ++i
)
4302 for (p
= ct_table
[i
]; p
; p
= next
)
4313 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4314 entry for that color already is in the color table, return the
4315 pixel color of that entry. Otherwise, allocate a new color for R,
4316 G, B, and make an entry in the color table. */
4318 static unsigned long
4319 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4321 unsigned hash
= CT_HASH_RGB (r
, g
, b
);
4322 int i
= hash
% CT_SIZE
;
4324 Display_Info
*dpyinfo
;
4326 /* Handle TrueColor visuals specially, which improves performance by
4327 two orders of magnitude. Freeing colors on TrueColor visuals is
4328 a nop, and pixel colors specify RGB values directly. See also
4329 the Xlib spec, chapter 3.1. */
4330 dpyinfo
= FRAME_X_DISPLAY_INFO (f
);
4331 if (dpyinfo
->red_bits
> 0)
4333 unsigned long pr
, pg
, pb
;
4335 /* Apply gamma-correction like normal color allocation does. */
4339 color
.red
= r
, color
.green
= g
, color
.blue
= b
;
4340 gamma_correct (f
, &color
);
4341 r
= color
.red
, g
= color
.green
, b
= color
.blue
;
4344 /* Scale down RGB values to the visual's bits per RGB, and shift
4345 them to the right position in the pixel color. Note that the
4346 original RGB values are 16-bit values, as usual in X. */
4347 pr
= (r
>> (16 - dpyinfo
->red_bits
)) << dpyinfo
->red_offset
;
4348 pg
= (g
>> (16 - dpyinfo
->green_bits
)) << dpyinfo
->green_offset
;
4349 pb
= (b
>> (16 - dpyinfo
->blue_bits
)) << dpyinfo
->blue_offset
;
4351 /* Assemble the pixel color. */
4352 return pr
| pg
| pb
;
4355 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4356 if (p
->r
== r
&& p
->g
== g
&& p
->b
== b
)
4362 #ifdef HAVE_X_WINDOWS
4370 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4371 return FRAME_FOREGROUND_PIXEL (f
);
4373 #ifdef HAVE_X_WINDOWS
4378 cmap
= FRAME_X_COLORMAP (f
);
4379 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4382 ++ct_colors_allocated
;
4383 p
= xmalloc (sizeof *p
);
4387 p
->pixel
= color
.pixel
;
4388 p
->next
= ct_table
[i
];
4392 return FRAME_FOREGROUND_PIXEL (f
);
4396 color
= PALETTERGB (r
, g
, b
);
4398 color
= RGB_TO_ULONG (r
, g
, b
);
4399 #endif /* HAVE_NTGUI */
4400 ++ct_colors_allocated
;
4401 p
= xmalloc (sizeof *p
);
4406 p
->next
= ct_table
[i
];
4408 #endif /* HAVE_X_WINDOWS */
4416 /* Look up pixel color PIXEL which is used on frame F in the color
4417 table. If not already present, allocate it. Value is PIXEL. */
4419 static unsigned long
4420 lookup_pixel_color (struct frame
*f
, unsigned long pixel
)
4422 int i
= pixel
% CT_SIZE
;
4425 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4426 if (p
->pixel
== pixel
)
4435 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4436 return FRAME_FOREGROUND_PIXEL (f
);
4438 #ifdef HAVE_X_WINDOWS
4439 cmap
= FRAME_X_COLORMAP (f
);
4440 color
.pixel
= pixel
;
4441 x_query_color (f
, &color
);
4442 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4445 cmap
= DefaultColormapOfScreen (FRAME_X_SCREEN (f
));
4446 color
.pixel
= pixel
;
4447 XQueryColor (NULL
, cmap
, &color
);
4448 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4450 #endif /* HAVE_X_WINDOWS */
4454 ++ct_colors_allocated
;
4456 p
= xmalloc (sizeof *p
);
4461 p
->next
= ct_table
[i
];
4465 return FRAME_FOREGROUND_PIXEL (f
);
4471 /* Value is a vector of all pixel colors contained in the color table,
4472 allocated via xmalloc. Set *N to the number of colors. */
4474 static unsigned long *
4475 colors_in_color_table (int *n
)
4479 unsigned long *colors
;
4481 if (ct_colors_allocated
== 0)
4488 colors
= xmalloc (ct_colors_allocated
* sizeof *colors
);
4489 *n
= ct_colors_allocated
;
4491 for (i
= j
= 0; i
< CT_SIZE
; ++i
)
4492 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4493 colors
[j
++] = p
->pixel
;
4499 #else /* COLOR_TABLE_SUPPORT */
4501 static unsigned long
4502 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4504 unsigned long pixel
;
4507 pixel
= PALETTERGB (r
>> 8, g
>> 8, b
>> 8);
4508 #endif /* HAVE_NTGUI */
4511 pixel
= RGB_TO_ULONG (r
>> 8, g
>> 8, b
>> 8);
4512 #endif /* HAVE_NS */
4517 init_color_table (void)
4520 #endif /* COLOR_TABLE_SUPPORT */
4523 /***********************************************************************
4525 ***********************************************************************/
4527 /* Edge detection matrices for different edge-detection
4530 static int emboss_matrix
[9] = {
4532 2, -1, 0, /* y - 1 */
4534 0, 1, -2 /* y + 1 */
4537 static int laplace_matrix
[9] = {
4539 1, 0, 0, /* y - 1 */
4541 0, 0, -1 /* y + 1 */
4544 /* Value is the intensity of the color whose red/green/blue values
4547 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4550 /* On frame F, return an array of XColor structures describing image
4551 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4552 means also fill the red/green/blue members of the XColor
4553 structures. Value is a pointer to the array of XColors structures,
4554 allocated with xmalloc; it must be freed by the caller. */
4557 x_to_xcolors (struct frame
*f
, struct image
*img
, bool rgb_p
)
4561 XImagePtr_or_DC ximg
;
4564 #endif /* HAVE_NTGUI */
4566 if (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *colors
/ img
->width
< img
->height
)
4567 memory_full (SIZE_MAX
);
4568 colors
= xmalloc (sizeof *colors
* img
->width
* img
->height
);
4570 /* Get the X image or create a memory device context for IMG. */
4571 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4573 /* Fill the `pixel' members of the XColor array. I wished there
4574 were an easy and portable way to circumvent XGetPixel. */
4576 for (y
= 0; y
< img
->height
; ++y
)
4578 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4580 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4581 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4583 x_query_colors (f
, row
, img
->width
);
4587 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4589 /* W32_TODO: palette support needed here? */
4590 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4593 p
->red
= RED16_FROM_ULONG (p
->pixel
);
4594 p
->green
= GREEN16_FROM_ULONG (p
->pixel
);
4595 p
->blue
= BLUE16_FROM_ULONG (p
->pixel
);
4598 #endif /* HAVE_X_WINDOWS */
4601 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
4608 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4609 created with CreateDIBSection, with the pointer to the bit values
4610 stored in ximg->data. */
4613 XPutPixel (XImagePtr ximg
, int x
, int y
, COLORREF color
)
4615 int width
= ximg
->info
.bmiHeader
.biWidth
;
4616 unsigned char * pixel
;
4618 /* True color images. */
4619 if (ximg
->info
.bmiHeader
.biBitCount
== 24)
4621 int rowbytes
= width
* 3;
4622 /* Ensure scanlines are aligned on 4 byte boundaries. */
4624 rowbytes
+= 4 - (rowbytes
% 4);
4626 pixel
= ximg
->data
+ y
* rowbytes
+ x
* 3;
4627 /* Windows bitmaps are in BGR order. */
4628 *pixel
= GetBValue (color
);
4629 *(pixel
+ 1) = GetGValue (color
);
4630 *(pixel
+ 2) = GetRValue (color
);
4632 /* Monochrome images. */
4633 else if (ximg
->info
.bmiHeader
.biBitCount
== 1)
4635 int rowbytes
= width
/ 8;
4636 /* Ensure scanlines are aligned on 4 byte boundaries. */
4638 rowbytes
+= 4 - (rowbytes
% 4);
4639 pixel
= ximg
->data
+ y
* rowbytes
+ x
/ 8;
4640 /* Filter out palette info. */
4641 if (color
& 0x00ffffff)
4642 *pixel
= *pixel
| (1 << x
% 8);
4644 *pixel
= *pixel
& ~(1 << x
% 8);
4647 image_error ("XPutPixel: palette image not supported", Qnil
, Qnil
);
4650 #endif /* HAVE_NTGUI */
4652 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4653 RGB members are set. F is the frame on which this all happens.
4654 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4657 x_from_xcolors (struct frame
*f
, struct image
*img
, XColor
*colors
)
4660 XImagePtr oimg
= NULL
;
4663 init_color_table ();
4665 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_COLORS
);
4666 image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 0,
4669 for (y
= 0; y
< img
->height
; ++y
)
4670 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4672 unsigned long pixel
;
4673 pixel
= lookup_rgb_color (f
, p
->red
, p
->green
, p
->blue
);
4674 XPutPixel (oimg
, x
, y
, pixel
);
4679 image_put_x_image (f
, img
, oimg
, 0);
4680 #ifdef COLOR_TABLE_SUPPORT
4681 img
->colors
= colors_in_color_table (&img
->ncolors
);
4682 free_color_table ();
4683 #endif /* COLOR_TABLE_SUPPORT */
4687 /* On frame F, perform edge-detection on image IMG.
4689 MATRIX is a nine-element array specifying the transformation
4690 matrix. See emboss_matrix for an example.
4692 COLOR_ADJUST is a color adjustment added to each pixel of the
4696 x_detect_edges (struct frame
*f
, struct image
*img
, int *matrix
, int color_adjust
)
4698 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4702 for (i
= sum
= 0; i
< 9; ++i
)
4703 sum
+= eabs (matrix
[i
]);
4705 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4707 if (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *new / img
->width
< img
->height
)
4708 memory_full (SIZE_MAX
);
4709 new = xmalloc (sizeof *new * img
->width
* img
->height
);
4711 for (y
= 0; y
< img
->height
; ++y
)
4713 p
= COLOR (new, 0, y
);
4714 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4715 p
= COLOR (new, img
->width
- 1, y
);
4716 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4719 for (x
= 1; x
< img
->width
- 1; ++x
)
4721 p
= COLOR (new, x
, 0);
4722 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4723 p
= COLOR (new, x
, img
->height
- 1);
4724 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4727 for (y
= 1; y
< img
->height
- 1; ++y
)
4729 p
= COLOR (new, 1, y
);
4731 for (x
= 1; x
< img
->width
- 1; ++x
, ++p
)
4733 int r
, g
, b
, yy
, xx
;
4736 for (yy
= y
- 1; yy
< y
+ 2; ++yy
)
4737 for (xx
= x
- 1; xx
< x
+ 2; ++xx
, ++i
)
4740 XColor
*t
= COLOR (colors
, xx
, yy
);
4741 r
+= matrix
[i
] * t
->red
;
4742 g
+= matrix
[i
] * t
->green
;
4743 b
+= matrix
[i
] * t
->blue
;
4746 r
= (r
/ sum
+ color_adjust
) & 0xffff;
4747 g
= (g
/ sum
+ color_adjust
) & 0xffff;
4748 b
= (b
/ sum
+ color_adjust
) & 0xffff;
4749 p
->red
= p
->green
= p
->blue
= COLOR_INTENSITY (r
, g
, b
);
4754 x_from_xcolors (f
, img
, new);
4760 /* Perform the pre-defined `emboss' edge-detection on image IMG
4764 x_emboss (struct frame
*f
, struct image
*img
)
4766 x_detect_edges (f
, img
, emboss_matrix
, 0xffff / 2);
4770 /* Transform image IMG which is used on frame F with a Laplace
4771 edge-detection algorithm. The result is an image that can be used
4772 to draw disabled buttons, for example. */
4775 x_laplace (struct frame
*f
, struct image
*img
)
4777 x_detect_edges (f
, img
, laplace_matrix
, 45000);
4781 /* Perform edge-detection on image IMG on frame F, with specified
4782 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4784 MATRIX must be either
4786 - a list of at least 9 numbers in row-major form
4787 - a vector of at least 9 numbers
4789 COLOR_ADJUST nil means use a default; otherwise it must be a
4793 x_edge_detection (struct frame
*f
, struct image
*img
, Lisp_Object matrix
,
4794 Lisp_Object color_adjust
)
4802 i
< 9 && CONSP (matrix
) && NUMBERP (XCAR (matrix
));
4803 ++i
, matrix
= XCDR (matrix
))
4804 trans
[i
] = XFLOATINT (XCAR (matrix
));
4806 else if (VECTORP (matrix
) && ASIZE (matrix
) >= 9)
4808 for (i
= 0; i
< 9 && NUMBERP (AREF (matrix
, i
)); ++i
)
4809 trans
[i
] = XFLOATINT (AREF (matrix
, i
));
4812 if (NILP (color_adjust
))
4813 color_adjust
= make_number (0xffff / 2);
4815 if (i
== 9 && NUMBERP (color_adjust
))
4816 x_detect_edges (f
, img
, trans
, XFLOATINT (color_adjust
));
4820 /* Transform image IMG on frame F so that it looks disabled. */
4823 x_disable_image (struct frame
*f
, struct image
*img
)
4825 Display_Info
*dpyinfo
= FRAME_X_DISPLAY_INFO (f
);
4827 int n_planes
= dpyinfo
->n_planes
* dpyinfo
->n_cbits
;
4829 int n_planes
= dpyinfo
->n_planes
;
4830 #endif /* HAVE_NTGUI */
4834 /* Color (or grayscale). Convert to gray, and equalize. Just
4835 drawing such images with a stipple can look very odd, so
4836 we're using this method instead. */
4837 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4839 const int h
= 15000;
4840 const int l
= 30000;
4842 for (p
= colors
, end
= colors
+ img
->width
* img
->height
;
4846 int i
= COLOR_INTENSITY (p
->red
, p
->green
, p
->blue
);
4847 int i2
= (0xffff - h
- l
) * i
/ 0xffff + l
;
4848 p
->red
= p
->green
= p
->blue
= i2
;
4851 x_from_xcolors (f
, img
, colors
);
4854 /* Draw a cross over the disabled image, if we must or if we
4856 if (n_planes
< 2 || cross_disabled_images
)
4859 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4861 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4863 Display
*dpy
= FRAME_X_DISPLAY (f
);
4866 image_sync_to_pixmaps (f
, img
);
4867 gc
= XCreateGC (dpy
, img
->pixmap
, 0, NULL
);
4868 XSetForeground (dpy
, gc
, BLACK_PIX_DEFAULT (f
));
4869 XDrawLine (dpy
, img
->pixmap
, gc
, 0, 0,
4870 img
->width
- 1, img
->height
- 1);
4871 XDrawLine (dpy
, img
->pixmap
, gc
, 0, img
->height
- 1,
4877 gc
= XCreateGC (dpy
, img
->mask
, 0, NULL
);
4878 XSetForeground (dpy
, gc
, MaskForeground (f
));
4879 XDrawLine (dpy
, img
->mask
, gc
, 0, 0,
4880 img
->width
- 1, img
->height
- 1);
4881 XDrawLine (dpy
, img
->mask
, gc
, 0, img
->height
- 1,
4885 #endif /* !HAVE_NS */
4890 hdc
= get_frame_dc (f
);
4891 bmpdc
= CreateCompatibleDC (hdc
);
4892 release_frame_dc (f
, hdc
);
4894 prev
= SelectObject (bmpdc
, img
->pixmap
);
4896 SetTextColor (bmpdc
, BLACK_PIX_DEFAULT (f
));
4897 MoveToEx (bmpdc
, 0, 0, NULL
);
4898 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
4899 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
4900 LineTo (bmpdc
, img
->width
- 1, 0);
4904 SelectObject (bmpdc
, img
->mask
);
4905 SetTextColor (bmpdc
, WHITE_PIX_DEFAULT (f
));
4906 MoveToEx (bmpdc
, 0, 0, NULL
);
4907 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
4908 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
4909 LineTo (bmpdc
, img
->width
- 1, 0);
4911 SelectObject (bmpdc
, prev
);
4913 #endif /* HAVE_NTGUI */
4918 /* Build a mask for image IMG which is used on frame F. FILE is the
4919 name of an image file, for error messages. HOW determines how to
4920 determine the background color of IMG. If it is a list '(R G B)',
4921 with R, G, and B being integers >= 0, take that as the color of the
4922 background. Otherwise, determine the background color of IMG
4926 x_build_heuristic_mask (struct frame
*f
, struct image
*img
, Lisp_Object how
)
4928 XImagePtr_or_DC ximg
;
4935 #endif /* HAVE_NTGUI */
4937 bool rc
, use_img_background
;
4938 unsigned long bg
= 0;
4941 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4945 /* Create an image and pixmap serving as mask. */
4946 rc
= image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 1,
4950 #endif /* !HAVE_NS */
4952 /* Create the bit array serving as mask. */
4953 row_width
= (img
->width
+ 7) / 8;
4954 mask_img
= xzalloc (row_width
* img
->height
);
4955 #endif /* HAVE_NTGUI */
4957 /* Get the X image or create a memory device context for IMG. */
4958 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4960 /* Determine the background color of ximg. If HOW is `(R G B)'
4961 take that as color. Otherwise, use the image's background color. */
4962 use_img_background
= 1;
4968 for (i
= 0; i
< 3 && CONSP (how
) && NATNUMP (XCAR (how
)); ++i
)
4970 rgb
[i
] = XFASTINT (XCAR (how
)) & 0xffff;
4974 if (i
== 3 && NILP (how
))
4976 char color_name
[30];
4977 sprintf (color_name
, "#%04x%04x%04x", rgb
[0], rgb
[1], rgb
[2]);
4980 0x00ffffff & /* Filter out palette info. */
4981 #endif /* HAVE_NTGUI */
4982 x_alloc_image_color (f
, img
, build_string (color_name
), 0));
4983 use_img_background
= 0;
4987 if (use_img_background
)
4988 bg
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
4990 /* Set all bits in mask_img to 1 whose color in ximg is different
4991 from the background color bg. */
4993 for (y
= 0; y
< img
->height
; ++y
)
4994 for (x
= 0; x
< img
->width
; ++x
)
4996 XPutPixel (mask_img
, x
, y
, (XGetPixel (ximg
, x
, y
) != bg
4997 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
));
4999 if (XGetPixel (ximg
, x
, y
) == bg
)
5000 ns_set_alpha (ximg
, x
, y
, 0);
5001 #endif /* HAVE_NS */
5003 /* Fill in the background_transparent field while we have the mask handy. */
5004 image_background_transparent (img
, f
, mask_img
);
5006 /* Put mask_img into the image. */
5007 image_put_x_image (f
, img
, mask_img
, 1);
5008 #endif /* !HAVE_NS */
5010 for (y
= 0; y
< img
->height
; ++y
)
5011 for (x
= 0; x
< img
->width
; ++x
)
5013 COLORREF p
= GetPixel (ximg
, x
, y
);
5015 mask_img
[y
* row_width
+ x
/ 8] |= 1 << (x
% 8);
5018 /* Create the mask image. */
5019 img
->mask
= w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
,
5021 /* Fill in the background_transparent field while we have the mask handy. */
5022 SelectObject (ximg
, img
->mask
);
5023 image_background_transparent (img
, f
, ximg
);
5025 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5027 #endif /* HAVE_NTGUI */
5029 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
5033 /***********************************************************************
5034 PBM (mono, gray, color)
5035 ***********************************************************************/
5037 static bool pbm_image_p (Lisp_Object object
);
5038 static bool pbm_load (struct frame
*f
, struct image
*img
);
5040 /* The symbol `pbm' identifying images of this type. */
5042 static Lisp_Object Qpbm
;
5044 /* Indices of image specification fields in gs_format, below. */
5046 enum pbm_keyword_index
5062 /* Vector of image_keyword structures describing the format
5063 of valid user-defined image specifications. */
5065 static const struct image_keyword pbm_format
[PBM_LAST
] =
5067 {":type", IMAGE_SYMBOL_VALUE
, 1},
5068 {":file", IMAGE_STRING_VALUE
, 0},
5069 {":data", IMAGE_STRING_VALUE
, 0},
5070 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5071 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5072 {":relief", IMAGE_INTEGER_VALUE
, 0},
5073 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5074 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5075 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5076 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
5077 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5080 /* Structure describing the image type `pbm'. */
5082 static struct image_type pbm_type
=
5093 /* Return true if OBJECT is a valid PBM image specification. */
5096 pbm_image_p (Lisp_Object object
)
5098 struct image_keyword fmt
[PBM_LAST
];
5100 memcpy (fmt
, pbm_format
, sizeof fmt
);
5102 if (!parse_image_spec (object
, fmt
, PBM_LAST
, Qpbm
))
5105 /* Must specify either :data or :file. */
5106 return fmt
[PBM_DATA
].count
+ fmt
[PBM_FILE
].count
== 1;
5110 /* Scan a decimal number from *S and return it. Advance *S while
5111 reading the number. END is the end of the string. Value is -1 at
5115 pbm_scan_number (unsigned char **s
, unsigned char *end
)
5117 int c
= 0, val
= -1;
5121 /* Skip white-space. */
5122 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
5127 /* Skip comment to end of line. */
5128 while (*s
< end
&& (c
= *(*s
)++, c
!= '\n'))
5131 else if (c_isdigit (c
))
5133 /* Read decimal number. */
5135 while (*s
< end
&& (c
= *(*s
)++, c_isdigit (c
)))
5136 val
= 10 * val
+ c
- '0';
5147 /* Load PBM image IMG for use on frame F. */
5150 pbm_load (struct frame
*f
, struct image
*img
)
5154 int width
, height
, max_color_idx
= 0;
5156 Lisp_Object file
, specified_file
;
5157 enum {PBM_MONO
, PBM_GRAY
, PBM_COLOR
} type
;
5158 unsigned char *contents
= NULL
;
5159 unsigned char *end
, *p
;
5162 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5164 if (STRINGP (specified_file
))
5166 file
= x_find_image_file (specified_file
);
5167 if (!STRINGP (file
))
5169 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
5173 contents
= slurp_file (SSDATA (file
), &size
);
5174 if (contents
== NULL
)
5176 image_error ("Error reading `%s'", file
, Qnil
);
5181 end
= contents
+ size
;
5186 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5187 if (!STRINGP (data
))
5189 image_error ("Invalid image data `%s'", data
, Qnil
);
5193 end
= p
+ SBYTES (data
);
5196 /* Check magic number. */
5197 if (end
- p
< 2 || *p
++ != 'P')
5199 image_error ("Not a PBM image: `%s'", img
->spec
, Qnil
);
5208 raw_p
= 0, type
= PBM_MONO
;
5212 raw_p
= 0, type
= PBM_GRAY
;
5216 raw_p
= 0, type
= PBM_COLOR
;
5220 raw_p
= 1, type
= PBM_MONO
;
5224 raw_p
= 1, type
= PBM_GRAY
;
5228 raw_p
= 1, type
= PBM_COLOR
;
5232 image_error ("Not a PBM image: `%s'", img
->spec
, Qnil
);
5236 /* Read width, height, maximum color-component. Characters
5237 starting with `#' up to the end of a line are ignored. */
5238 width
= pbm_scan_number (&p
, end
);
5239 height
= pbm_scan_number (&p
, end
);
5241 if (type
!= PBM_MONO
)
5243 max_color_idx
= pbm_scan_number (&p
, end
);
5244 if (max_color_idx
> 65535 || max_color_idx
< 0)
5246 image_error ("Unsupported maximum PBM color value", Qnil
, Qnil
);
5251 if (!check_image_size (f
, width
, height
))
5253 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
5257 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5260 /* Initialize the color hash table. */
5261 init_color_table ();
5263 if (type
== PBM_MONO
)
5266 struct image_keyword fmt
[PBM_LAST
];
5267 unsigned long fg
= FRAME_FOREGROUND_PIXEL (f
);
5268 unsigned long bg
= FRAME_BACKGROUND_PIXEL (f
);
5270 /* Parse the image specification. */
5271 memcpy (fmt
, pbm_format
, sizeof fmt
);
5272 parse_image_spec (img
->spec
, fmt
, PBM_LAST
, Qpbm
);
5274 /* Get foreground and background colors, maybe allocate colors. */
5275 if (fmt
[PBM_FOREGROUND
].count
5276 && STRINGP (fmt
[PBM_FOREGROUND
].value
))
5277 fg
= x_alloc_image_color (f
, img
, fmt
[PBM_FOREGROUND
].value
, fg
);
5278 if (fmt
[PBM_BACKGROUND
].count
5279 && STRINGP (fmt
[PBM_BACKGROUND
].value
))
5281 bg
= x_alloc_image_color (f
, img
, fmt
[PBM_BACKGROUND
].value
, bg
);
5282 img
->background
= bg
;
5283 img
->background_valid
= 1;
5286 for (y
= 0; y
< height
; ++y
)
5287 for (x
= 0; x
< width
; ++x
)
5295 x_destroy_x_image (ximg
);
5296 x_clear_image (f
, img
);
5297 image_error ("Invalid image size in image `%s'",
5307 g
= pbm_scan_number (&p
, end
);
5309 XPutPixel (ximg
, x
, y
, g
? fg
: bg
);
5314 int expected_size
= height
* width
;
5315 if (max_color_idx
> 255)
5317 if (type
== PBM_COLOR
)
5320 if (raw_p
&& p
+ expected_size
> end
)
5322 x_destroy_x_image (ximg
);
5323 x_clear_image (f
, img
);
5324 image_error ("Invalid image size in image `%s'",
5329 for (y
= 0; y
< height
; ++y
)
5330 for (x
= 0; x
< width
; ++x
)
5334 if (type
== PBM_GRAY
&& raw_p
)
5337 if (max_color_idx
> 255)
5338 r
= g
= b
= r
* 256 + *p
++;
5340 else if (type
== PBM_GRAY
)
5341 r
= g
= b
= pbm_scan_number (&p
, end
);
5345 if (max_color_idx
> 255)
5348 if (max_color_idx
> 255)
5351 if (max_color_idx
> 255)
5356 r
= pbm_scan_number (&p
, end
);
5357 g
= pbm_scan_number (&p
, end
);
5358 b
= pbm_scan_number (&p
, end
);
5361 if (r
< 0 || g
< 0 || b
< 0)
5363 x_destroy_x_image (ximg
);
5364 image_error ("Invalid pixel value in image `%s'",
5369 /* RGB values are now in the range 0..max_color_idx.
5370 Scale this to the range 0..0xffff supported by X. */
5371 r
= (double) r
* 65535 / max_color_idx
;
5372 g
= (double) g
* 65535 / max_color_idx
;
5373 b
= (double) b
* 65535 / max_color_idx
;
5374 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5378 #ifdef COLOR_TABLE_SUPPORT
5379 /* Store in IMG->colors the colors allocated for the image, and
5380 free the color table. */
5381 img
->colors
= colors_in_color_table (&img
->ncolors
);
5382 free_color_table ();
5383 #endif /* COLOR_TABLE_SUPPORT */
5386 img
->height
= height
;
5388 /* Maybe fill in the background field while we have ximg handy. */
5390 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
5391 /* Casting avoids a GCC warning. */
5392 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
5394 /* Put ximg into the image. */
5395 image_put_x_image (f
, img
, ximg
, 0);
5397 /* X and W32 versions did it here, MAC version above. ++kfs
5399 img->height = height; */
5406 /***********************************************************************
5408 ***********************************************************************/
5410 #if defined (HAVE_PNG) || defined (HAVE_NS)
5412 /* Function prototypes. */
5414 static bool png_image_p (Lisp_Object object
);
5415 static bool png_load (struct frame
*f
, struct image
*img
);
5417 /* The symbol `png' identifying images of this type. */
5419 static Lisp_Object Qpng
;
5421 /* Indices of image specification fields in png_format, below. */
5423 enum png_keyword_index
5438 /* Vector of image_keyword structures describing the format
5439 of valid user-defined image specifications. */
5441 static const struct image_keyword png_format
[PNG_LAST
] =
5443 {":type", IMAGE_SYMBOL_VALUE
, 1},
5444 {":data", IMAGE_STRING_VALUE
, 0},
5445 {":file", IMAGE_STRING_VALUE
, 0},
5446 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5447 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5448 {":relief", IMAGE_INTEGER_VALUE
, 0},
5449 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5450 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5451 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5452 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5455 #if defined HAVE_NTGUI && defined WINDOWSNT
5456 static bool init_png_functions (void);
5458 #define init_png_functions NULL
5461 /* Structure describing the image type `png'. */
5463 static struct image_type png_type
=
5473 /* Return true if OBJECT is a valid PNG image specification. */
5476 png_image_p (Lisp_Object object
)
5478 struct image_keyword fmt
[PNG_LAST
];
5479 memcpy (fmt
, png_format
, sizeof fmt
);
5481 if (!parse_image_spec (object
, fmt
, PNG_LAST
, Qpng
))
5484 /* Must specify either the :data or :file keyword. */
5485 return fmt
[PNG_FILE
].count
+ fmt
[PNG_DATA
].count
== 1;
5488 #endif /* HAVE_PNG || HAVE_NS */
5494 /* PNG library details. */
5496 DEF_IMGLIB_FN (png_voidp
, png_get_io_ptr
, (png_structp
));
5497 DEF_IMGLIB_FN (int, png_sig_cmp
, (png_bytep
, png_size_t
, png_size_t
));
5498 DEF_IMGLIB_FN (png_structp
, png_create_read_struct
, (png_const_charp
, png_voidp
,
5499 png_error_ptr
, png_error_ptr
));
5500 DEF_IMGLIB_FN (png_infop
, png_create_info_struct
, (png_structp
));
5501 DEF_IMGLIB_FN (void, png_destroy_read_struct
, (png_structpp
, png_infopp
, png_infopp
));
5502 DEF_IMGLIB_FN (void, png_set_read_fn
, (png_structp
, png_voidp
, png_rw_ptr
));
5503 DEF_IMGLIB_FN (void, png_set_sig_bytes
, (png_structp
, int));
5504 DEF_IMGLIB_FN (void, png_read_info
, (png_structp
, png_infop
));
5505 DEF_IMGLIB_FN (png_uint_32
, png_get_IHDR
, (png_structp
, png_infop
,
5506 png_uint_32
*, png_uint_32
*,
5507 int *, int *, int *, int *, int *));
5508 DEF_IMGLIB_FN (png_uint_32
, png_get_valid
, (png_structp
, png_infop
, png_uint_32
));
5509 DEF_IMGLIB_FN (void, png_set_strip_16
, (png_structp
));
5510 DEF_IMGLIB_FN (void, png_set_expand
, (png_structp
));
5511 DEF_IMGLIB_FN (void, png_set_gray_to_rgb
, (png_structp
));
5512 DEF_IMGLIB_FN (void, png_set_background
, (png_structp
, png_color_16p
,
5514 DEF_IMGLIB_FN (png_uint_32
, png_get_bKGD
, (png_structp
, png_infop
, png_color_16p
*));
5515 DEF_IMGLIB_FN (void, png_read_update_info
, (png_structp
, png_infop
));
5516 DEF_IMGLIB_FN (png_byte
, png_get_channels
, (png_structp
, png_infop
));
5517 DEF_IMGLIB_FN (png_size_t
, png_get_rowbytes
, (png_structp
, png_infop
));
5518 DEF_IMGLIB_FN (void, png_read_image
, (png_structp
, png_bytepp
));
5519 DEF_IMGLIB_FN (void, png_read_end
, (png_structp
, png_infop
));
5520 DEF_IMGLIB_FN (void, png_error
, (png_structp
, png_const_charp
));
5522 #if (PNG_LIBPNG_VER >= 10500)
5523 DEF_IMGLIB_FN (void, png_longjmp
, (png_structp
, int));
5524 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn
, (png_structp
, png_longjmp_ptr
, size_t));
5525 #endif /* libpng version >= 1.5 */
5528 init_png_functions (void)
5532 if (!(library
= w32_delayed_load (Qpng
)))
5535 LOAD_IMGLIB_FN (library
, png_get_io_ptr
);
5536 LOAD_IMGLIB_FN (library
, png_sig_cmp
);
5537 LOAD_IMGLIB_FN (library
, png_create_read_struct
);
5538 LOAD_IMGLIB_FN (library
, png_create_info_struct
);
5539 LOAD_IMGLIB_FN (library
, png_destroy_read_struct
);
5540 LOAD_IMGLIB_FN (library
, png_set_read_fn
);
5541 LOAD_IMGLIB_FN (library
, png_set_sig_bytes
);
5542 LOAD_IMGLIB_FN (library
, png_read_info
);
5543 LOAD_IMGLIB_FN (library
, png_get_IHDR
);
5544 LOAD_IMGLIB_FN (library
, png_get_valid
);
5545 LOAD_IMGLIB_FN (library
, png_set_strip_16
);
5546 LOAD_IMGLIB_FN (library
, png_set_expand
);
5547 LOAD_IMGLIB_FN (library
, png_set_gray_to_rgb
);
5548 LOAD_IMGLIB_FN (library
, png_set_background
);
5549 LOAD_IMGLIB_FN (library
, png_get_bKGD
);
5550 LOAD_IMGLIB_FN (library
, png_read_update_info
);
5551 LOAD_IMGLIB_FN (library
, png_get_channels
);
5552 LOAD_IMGLIB_FN (library
, png_get_rowbytes
);
5553 LOAD_IMGLIB_FN (library
, png_read_image
);
5554 LOAD_IMGLIB_FN (library
, png_read_end
);
5555 LOAD_IMGLIB_FN (library
, png_error
);
5557 #if (PNG_LIBPNG_VER >= 10500)
5558 LOAD_IMGLIB_FN (library
, png_longjmp
);
5559 LOAD_IMGLIB_FN (library
, png_set_longjmp_fn
);
5560 #endif /* libpng version >= 1.5 */
5566 #define fn_png_get_io_ptr png_get_io_ptr
5567 #define fn_png_sig_cmp png_sig_cmp
5568 #define fn_png_create_read_struct png_create_read_struct
5569 #define fn_png_create_info_struct png_create_info_struct
5570 #define fn_png_destroy_read_struct png_destroy_read_struct
5571 #define fn_png_set_read_fn png_set_read_fn
5572 #define fn_png_set_sig_bytes png_set_sig_bytes
5573 #define fn_png_read_info png_read_info
5574 #define fn_png_get_IHDR png_get_IHDR
5575 #define fn_png_get_valid png_get_valid
5576 #define fn_png_set_strip_16 png_set_strip_16
5577 #define fn_png_set_expand png_set_expand
5578 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5579 #define fn_png_set_background png_set_background
5580 #define fn_png_get_bKGD png_get_bKGD
5581 #define fn_png_read_update_info png_read_update_info
5582 #define fn_png_get_channels png_get_channels
5583 #define fn_png_get_rowbytes png_get_rowbytes
5584 #define fn_png_read_image png_read_image
5585 #define fn_png_read_end png_read_end
5586 #define fn_png_error png_error
5588 #if (PNG_LIBPNG_VER >= 10500)
5589 #define fn_png_longjmp png_longjmp
5590 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5591 #endif /* libpng version >= 1.5 */
5593 #endif /* WINDOWSNT */
5595 /* Possibly inefficient/inexact substitutes for _setjmp and _longjmp.
5596 Do not use sys_setjmp, as PNG supports only jmp_buf. The _longjmp
5597 substitute may munge the signal mask, but that should be OK here.
5598 MinGW (MS-Windows) uses _setjmp and defines setjmp to _setjmp in
5599 the system header setjmp.h; don't mess up that. */
5600 #ifndef HAVE__SETJMP
5601 # define _setjmp(j) setjmp (j)
5602 # define _longjmp longjmp
5605 #if (PNG_LIBPNG_VER < 10500)
5606 #define PNG_LONGJMP(ptr) (_longjmp ((ptr)->jmpbuf, 1))
5607 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5609 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5610 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5611 #define PNG_JMPBUF(ptr) \
5612 (*fn_png_set_longjmp_fn ((ptr), _longjmp, sizeof (jmp_buf)))
5615 /* Error and warning handlers installed when the PNG library
5618 static _Noreturn
void
5619 my_png_error (png_struct
*png_ptr
, const char *msg
)
5621 eassert (png_ptr
!= NULL
);
5622 /* Avoid compiler warning about deprecated direct access to
5623 png_ptr's fields in libpng versions 1.4.x. */
5624 image_error ("PNG error: %s", build_string (msg
), Qnil
);
5625 PNG_LONGJMP (png_ptr
);
5630 my_png_warning (png_struct
*png_ptr
, const char *msg
)
5632 eassert (png_ptr
!= NULL
);
5633 image_error ("PNG warning: %s", build_string (msg
), Qnil
);
5636 /* Memory source for PNG decoding. */
5638 struct png_memory_storage
5640 unsigned char *bytes
; /* The data */
5641 ptrdiff_t len
; /* How big is it? */
5642 ptrdiff_t index
; /* Where are we? */
5646 /* Function set as reader function when reading PNG image from memory.
5647 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5648 bytes from the input to DATA. */
5651 png_read_from_memory (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5653 struct png_memory_storage
*tbr
= fn_png_get_io_ptr (png_ptr
);
5655 if (length
> tbr
->len
- tbr
->index
)
5656 fn_png_error (png_ptr
, "Read error");
5658 memcpy (data
, tbr
->bytes
+ tbr
->index
, length
);
5659 tbr
->index
= tbr
->index
+ length
;
5663 /* Function set as reader function when reading PNG image from a file.
5664 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5665 bytes from the input to DATA. */
5668 png_read_from_file (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5670 FILE *fp
= fn_png_get_io_ptr (png_ptr
);
5672 if (fread (data
, 1, length
, fp
) < length
)
5673 fn_png_error (png_ptr
, "Read error");
5677 /* Load PNG image IMG for use on frame F. Value is true if
5680 struct png_load_context
5682 /* These are members so that longjmp doesn't munge local variables. */
5683 png_struct
*png_ptr
;
5692 png_load_body (struct frame
*f
, struct image
*img
, struct png_load_context
*c
)
5694 Lisp_Object file
, specified_file
;
5695 Lisp_Object specified_data
;
5698 XImagePtr ximg
, mask_img
= NULL
;
5699 png_struct
*png_ptr
;
5700 png_info
*info_ptr
= NULL
, *end_info
= NULL
;
5703 png_byte
*pixels
= NULL
;
5704 png_byte
**rows
= NULL
;
5705 png_uint_32 width
, height
;
5706 int bit_depth
, color_type
, interlace_type
;
5708 png_uint_32 row_bytes
;
5710 struct png_memory_storage tbr
; /* Data to be read */
5712 /* Find out what file to load. */
5713 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5714 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5716 if (NILP (specified_data
))
5718 file
= x_find_image_file (specified_file
);
5719 if (!STRINGP (file
))
5721 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
5725 /* Open the image file. */
5726 fp
= emacs_fopen (SSDATA (file
), "rb");
5729 image_error ("Cannot open image file `%s'", file
, Qnil
);
5733 /* Check PNG signature. */
5734 if (fread (sig
, 1, sizeof sig
, fp
) != sizeof sig
5735 || fn_png_sig_cmp (sig
, 0, sizeof sig
))
5738 image_error ("Not a PNG file: `%s'", file
, Qnil
);
5744 if (!STRINGP (specified_data
))
5746 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
5750 /* Read from memory. */
5751 tbr
.bytes
= SDATA (specified_data
);
5752 tbr
.len
= SBYTES (specified_data
);
5755 /* Check PNG signature. */
5756 if (tbr
.len
< sizeof sig
5757 || fn_png_sig_cmp (tbr
.bytes
, 0, sizeof sig
))
5759 image_error ("Not a PNG image: `%s'", img
->spec
, Qnil
);
5763 /* Need to skip past the signature. */
5764 tbr
.bytes
+= sizeof (sig
);
5767 /* Initialize read and info structs for PNG lib. */
5768 png_ptr
= fn_png_create_read_struct (PNG_LIBPNG_VER_STRING
,
5773 info_ptr
= fn_png_create_info_struct (png_ptr
);
5774 end_info
= fn_png_create_info_struct (png_ptr
);
5777 c
->png_ptr
= png_ptr
;
5778 c
->info_ptr
= info_ptr
;
5779 c
->end_info
= end_info
;
5784 if (! (info_ptr
&& end_info
))
5786 fn_png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5791 if (fp
) fclose (fp
);
5795 /* Set error jump-back. We come back here when the PNG library
5796 detects an error. */
5797 if (_setjmp (PNG_JMPBUF (png_ptr
)))
5801 fn_png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5809 /* Silence a bogus diagnostic; see GCC bug 54561. */
5810 IF_LINT (fp
= c
->fp
);
5812 /* Read image info. */
5813 if (!NILP (specified_data
))
5814 fn_png_set_read_fn (png_ptr
, &tbr
, png_read_from_memory
);
5816 fn_png_set_read_fn (png_ptr
, fp
, png_read_from_file
);
5818 fn_png_set_sig_bytes (png_ptr
, sizeof sig
);
5819 fn_png_read_info (png_ptr
, info_ptr
);
5820 fn_png_get_IHDR (png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
,
5821 &interlace_type
, NULL
, NULL
);
5823 if (! (width
<= INT_MAX
&& height
<= INT_MAX
5824 && check_image_size (f
, width
, height
)))
5826 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
5830 /* Create the X image and pixmap now, so that the work below can be
5831 omitted if the image is too large for X. */
5832 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5835 /* If image contains simply transparency data, we prefer to
5836 construct a clipping mask. */
5837 if (fn_png_get_valid (png_ptr
, info_ptr
, PNG_INFO_tRNS
))
5842 /* This function is easier to write if we only have to handle
5843 one data format: RGB or RGBA with 8 bits per channel. Let's
5844 transform other formats into that format. */
5846 /* Strip more than 8 bits per channel. */
5847 if (bit_depth
== 16)
5848 fn_png_set_strip_16 (png_ptr
);
5850 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5852 fn_png_set_expand (png_ptr
);
5854 /* Convert grayscale images to RGB. */
5855 if (color_type
== PNG_COLOR_TYPE_GRAY
5856 || color_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
5857 fn_png_set_gray_to_rgb (png_ptr
);
5859 /* Handle alpha channel by combining the image with a background
5860 color. Do this only if a real alpha channel is supplied. For
5861 simple transparency, we prefer a clipping mask. */
5864 /* png_color_16 *image_bg; */
5865 Lisp_Object specified_bg
5866 = image_spec_value (img
->spec
, QCbackground
, NULL
);
5867 int shift
= (bit_depth
== 16) ? 0 : 8;
5869 if (STRINGP (specified_bg
))
5870 /* The user specified `:background', use that. */
5873 if (x_defined_color (f
, SSDATA (specified_bg
), &color
, 0))
5875 png_color_16 user_bg
;
5877 memset (&user_bg
, 0, sizeof user_bg
);
5878 user_bg
.red
= color
.red
>> shift
;
5879 user_bg
.green
= color
.green
>> shift
;
5880 user_bg
.blue
= color
.blue
>> shift
;
5882 fn_png_set_background (png_ptr
, &user_bg
,
5883 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
5888 /* We use the current frame background, ignoring any default
5889 background color set by the image. */
5890 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5892 png_color_16 frame_background
;
5894 color
.pixel
= FRAME_BACKGROUND_PIXEL (f
);
5895 x_query_color (f
, &color
);
5897 memset (&frame_background
, 0, sizeof frame_background
);
5898 frame_background
.red
= color
.red
>> shift
;
5899 frame_background
.green
= color
.green
>> shift
;
5900 frame_background
.blue
= color
.blue
>> shift
;
5901 #endif /* HAVE_X_WINDOWS */
5903 fn_png_set_background (png_ptr
, &frame_background
,
5904 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
5908 /* Update info structure. */
5909 fn_png_read_update_info (png_ptr
, info_ptr
);
5911 /* Get number of channels. Valid values are 1 for grayscale images
5912 and images with a palette, 2 for grayscale images with transparency
5913 information (alpha channel), 3 for RGB images, and 4 for RGB
5914 images with alpha channel, i.e. RGBA. If conversions above were
5915 sufficient we should only have 3 or 4 channels here. */
5916 channels
= fn_png_get_channels (png_ptr
, info_ptr
);
5917 eassert (channels
== 3 || channels
== 4);
5919 /* Number of bytes needed for one row of the image. */
5920 row_bytes
= fn_png_get_rowbytes (png_ptr
, info_ptr
);
5922 /* Allocate memory for the image. */
5923 if (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *rows
< height
5924 || min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *pixels
/ height
< row_bytes
)
5925 memory_full (SIZE_MAX
);
5926 c
->pixels
= pixels
= xmalloc (sizeof *pixels
* row_bytes
* height
);
5927 c
->rows
= rows
= xmalloc (height
* sizeof *rows
);
5928 for (i
= 0; i
< height
; ++i
)
5929 rows
[i
] = pixels
+ i
* row_bytes
;
5931 /* Read the entire image. */
5932 fn_png_read_image (png_ptr
, rows
);
5933 fn_png_read_end (png_ptr
, info_ptr
);
5940 /* Create an image and pixmap serving as mask if the PNG image
5941 contains an alpha channel. */
5944 && !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
5947 x_destroy_x_image (ximg
);
5948 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
);
5952 /* Fill the X image and mask from PNG data. */
5953 init_color_table ();
5955 for (y
= 0; y
< height
; ++y
)
5957 png_byte
*p
= rows
[y
];
5959 for (x
= 0; x
< width
; ++x
)
5966 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5967 /* An alpha channel, aka mask channel, associates variable
5968 transparency with an image. Where other image formats
5969 support binary transparency---fully transparent or fully
5970 opaque---PNG allows up to 254 levels of partial transparency.
5971 The PNG library implements partial transparency by combining
5972 the image with a specified background color.
5974 I'm not sure how to handle this here nicely: because the
5975 background on which the image is displayed may change, for
5976 real alpha channel support, it would be necessary to create
5977 a new image for each possible background.
5979 What I'm doing now is that a mask is created if we have
5980 boolean transparency information. Otherwise I'm using
5981 the frame's background color to combine the image with. */
5986 XPutPixel (mask_img
, x
, y
, *p
> 0 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
);
5992 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
5993 /* Set IMG's background color from the PNG image, unless the user
5997 if (fn_png_get_bKGD (png_ptr
, info_ptr
, &bg
))
5999 img
->background
= lookup_rgb_color (f
, bg
->red
, bg
->green
, bg
->blue
);
6000 img
->background_valid
= 1;
6004 #ifdef COLOR_TABLE_SUPPORT
6005 /* Remember colors allocated for this image. */
6006 img
->colors
= colors_in_color_table (&img
->ncolors
);
6007 free_color_table ();
6008 #endif /* COLOR_TABLE_SUPPORT */
6011 fn_png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6016 img
->height
= height
;
6018 /* Maybe fill in the background field while we have ximg handy.
6019 Casting avoids a GCC warning. */
6020 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6022 /* Put ximg into the image. */
6023 image_put_x_image (f
, img
, ximg
, 0);
6025 /* Same for the mask. */
6028 /* Fill in the background_transparent field while we have the
6029 mask handy. Casting avoids a GCC warning. */
6030 image_background_transparent (img
, f
, (XImagePtr_or_DC
)mask_img
);
6032 image_put_x_image (f
, img
, mask_img
, 1);
6039 png_load (struct frame
*f
, struct image
*img
)
6041 struct png_load_context c
;
6042 return png_load_body (f
, img
, &c
);
6045 #else /* HAVE_PNG */
6049 png_load (struct frame
*f
, struct image
*img
)
6051 return ns_load_image (f
, img
,
6052 image_spec_value (img
->spec
, QCfile
, NULL
),
6053 image_spec_value (img
->spec
, QCdata
, NULL
));
6055 #endif /* HAVE_NS */
6058 #endif /* !HAVE_PNG */
6062 /***********************************************************************
6064 ***********************************************************************/
6066 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6068 static bool jpeg_image_p (Lisp_Object object
);
6069 static bool jpeg_load (struct frame
*f
, struct image
*img
);
6071 /* The symbol `jpeg' identifying images of this type. */
6073 static Lisp_Object Qjpeg
;
6075 /* Indices of image specification fields in gs_format, below. */
6077 enum jpeg_keyword_index
6086 JPEG_HEURISTIC_MASK
,
6092 /* Vector of image_keyword structures describing the format
6093 of valid user-defined image specifications. */
6095 static const struct image_keyword jpeg_format
[JPEG_LAST
] =
6097 {":type", IMAGE_SYMBOL_VALUE
, 1},
6098 {":data", IMAGE_STRING_VALUE
, 0},
6099 {":file", IMAGE_STRING_VALUE
, 0},
6100 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6101 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6102 {":relief", IMAGE_INTEGER_VALUE
, 0},
6103 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6104 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6105 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6106 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
6109 #if defined HAVE_NTGUI && defined WINDOWSNT
6110 static bool init_jpeg_functions (void);
6112 #define init_jpeg_functions NULL
6115 /* Structure describing the image type `jpeg'. */
6117 static struct image_type jpeg_type
=
6123 init_jpeg_functions
,
6127 /* Return true if OBJECT is a valid JPEG image specification. */
6130 jpeg_image_p (Lisp_Object object
)
6132 struct image_keyword fmt
[JPEG_LAST
];
6134 memcpy (fmt
, jpeg_format
, sizeof fmt
);
6136 if (!parse_image_spec (object
, fmt
, JPEG_LAST
, Qjpeg
))
6139 /* Must specify either the :data or :file keyword. */
6140 return fmt
[JPEG_FILE
].count
+ fmt
[JPEG_DATA
].count
== 1;
6143 #endif /* HAVE_JPEG || HAVE_NS */
6147 /* Work around a warning about HAVE_STDLIB_H being redefined in
6149 #ifdef HAVE_STDLIB_H
6150 #undef HAVE_STDLIB_H
6151 #endif /* HAVE_STLIB_H */
6153 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6154 /* In older releases of the jpeg library, jpeglib.h will define boolean
6155 differently depending on __WIN32__, so make sure it is defined. */
6159 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6160 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6161 using the Windows boolean type instead of the jpeglib boolean type
6162 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6163 headers are included along with windows.h, so under Cygwin, jpeglib
6164 attempts to define a conflicting boolean type. Worse, forcing
6165 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6166 because it created an ABI incompatibility between the
6167 already-compiled jpeg library and the header interface definition.
6169 The best we can do is to define jpeglib's boolean type to a
6170 different name. This name, jpeg_boolean, remains in effect through
6171 the rest of image.c.
6173 #if defined CYGWIN && defined HAVE_NTGUI
6174 #define boolean jpeg_boolean
6176 #include <jpeglib.h>
6181 /* JPEG library details. */
6182 DEF_IMGLIB_FN (void, jpeg_CreateDecompress
, (j_decompress_ptr
, int, size_t));
6183 DEF_IMGLIB_FN (boolean
, jpeg_start_decompress
, (j_decompress_ptr
));
6184 DEF_IMGLIB_FN (boolean
, jpeg_finish_decompress
, (j_decompress_ptr
));
6185 DEF_IMGLIB_FN (void, jpeg_destroy_decompress
, (j_decompress_ptr
));
6186 DEF_IMGLIB_FN (int, jpeg_read_header
, (j_decompress_ptr
, boolean
));
6187 DEF_IMGLIB_FN (JDIMENSION
, jpeg_read_scanlines
, (j_decompress_ptr
, JSAMPARRAY
, JDIMENSION
));
6188 DEF_IMGLIB_FN (struct jpeg_error_mgr
*, jpeg_std_error
, (struct jpeg_error_mgr
*));
6189 DEF_IMGLIB_FN (boolean
, jpeg_resync_to_restart
, (j_decompress_ptr
, int));
6192 init_jpeg_functions (void)
6196 if (!(library
= w32_delayed_load (Qjpeg
)))
6199 LOAD_IMGLIB_FN (library
, jpeg_finish_decompress
);
6200 LOAD_IMGLIB_FN (library
, jpeg_read_scanlines
);
6201 LOAD_IMGLIB_FN (library
, jpeg_start_decompress
);
6202 LOAD_IMGLIB_FN (library
, jpeg_read_header
);
6203 LOAD_IMGLIB_FN (library
, jpeg_CreateDecompress
);
6204 LOAD_IMGLIB_FN (library
, jpeg_destroy_decompress
);
6205 LOAD_IMGLIB_FN (library
, jpeg_std_error
);
6206 LOAD_IMGLIB_FN (library
, jpeg_resync_to_restart
);
6210 /* Wrapper since we can't directly assign the function pointer
6211 to another function pointer that was declared more completely easily. */
6213 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo
, int desired
)
6215 return fn_jpeg_resync_to_restart (cinfo
, desired
);
6220 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
6221 #define fn_jpeg_start_decompress jpeg_start_decompress
6222 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6223 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6224 #define fn_jpeg_read_header jpeg_read_header
6225 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6226 #define fn_jpeg_std_error jpeg_std_error
6227 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6229 #endif /* WINDOWSNT */
6231 struct my_jpeg_error_mgr
6233 struct jpeg_error_mgr pub
;
6234 sys_jmp_buf setjmp_buffer
;
6236 /* The remaining members are so that longjmp doesn't munge local
6238 struct jpeg_decompress_struct cinfo
;
6242 MY_JPEG_INVALID_IMAGE_SIZE
,
6243 MY_JPEG_CANNOT_CREATE_X
6251 static _Noreturn
void
6252 my_error_exit (j_common_ptr cinfo
)
6254 struct my_jpeg_error_mgr
*mgr
= (struct my_jpeg_error_mgr
*) cinfo
->err
;
6255 mgr
->failure_code
= MY_JPEG_ERROR_EXIT
;
6256 sys_longjmp (mgr
->setjmp_buffer
, 1);
6260 /* Init source method for JPEG data source manager. Called by
6261 jpeg_read_header() before any data is actually read. See
6262 libjpeg.doc from the JPEG lib distribution. */
6265 our_common_init_source (j_decompress_ptr cinfo
)
6270 /* Method to terminate data source. Called by
6271 jpeg_finish_decompress() after all data has been processed. */
6274 our_common_term_source (j_decompress_ptr cinfo
)
6279 /* Fill input buffer method for JPEG data source manager. Called
6280 whenever more data is needed. We read the whole image in one step,
6281 so this only adds a fake end of input marker at the end. */
6283 static JOCTET our_memory_buffer
[2];
6286 our_memory_fill_input_buffer (j_decompress_ptr cinfo
)
6288 /* Insert a fake EOI marker. */
6289 struct jpeg_source_mgr
*src
= cinfo
->src
;
6291 our_memory_buffer
[0] = (JOCTET
) 0xFF;
6292 our_memory_buffer
[1] = (JOCTET
) JPEG_EOI
;
6294 src
->next_input_byte
= our_memory_buffer
;
6295 src
->bytes_in_buffer
= 2;
6300 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6301 is the JPEG data source manager. */
6304 our_memory_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6306 struct jpeg_source_mgr
*src
= cinfo
->src
;
6310 if (num_bytes
> src
->bytes_in_buffer
)
6311 ERREXIT (cinfo
, JERR_INPUT_EOF
);
6313 src
->bytes_in_buffer
-= num_bytes
;
6314 src
->next_input_byte
+= num_bytes
;
6319 /* Set up the JPEG lib for reading an image from DATA which contains
6320 LEN bytes. CINFO is the decompression info structure created for
6321 reading the image. */
6324 jpeg_memory_src (j_decompress_ptr cinfo
, JOCTET
*data
, ptrdiff_t len
)
6326 struct jpeg_source_mgr
*src
= cinfo
->src
;
6330 /* First time for this JPEG object? */
6331 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6332 JPOOL_PERMANENT
, sizeof *src
);
6334 src
->next_input_byte
= data
;
6337 src
->init_source
= our_common_init_source
;
6338 src
->fill_input_buffer
= our_memory_fill_input_buffer
;
6339 src
->skip_input_data
= our_memory_skip_input_data
;
6340 src
->resync_to_restart
= jpeg_resync_to_restart_wrapper
; /* Use default method. */
6341 src
->term_source
= our_common_term_source
;
6342 src
->bytes_in_buffer
= len
;
6343 src
->next_input_byte
= data
;
6347 struct jpeg_stdio_mgr
6349 struct jpeg_source_mgr mgr
;
6356 /* Size of buffer to read JPEG from file.
6357 Not too big, as we want to use alloc_small. */
6358 #define JPEG_STDIO_BUFFER_SIZE 8192
6361 /* Fill input buffer method for JPEG data source manager. Called
6362 whenever more data is needed. The data is read from a FILE *. */
6365 our_stdio_fill_input_buffer (j_decompress_ptr cinfo
)
6367 struct jpeg_stdio_mgr
*src
;
6369 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6374 bytes
= fread (src
->buffer
, 1, JPEG_STDIO_BUFFER_SIZE
, src
->file
);
6376 src
->mgr
.bytes_in_buffer
= bytes
;
6379 WARNMS (cinfo
, JWRN_JPEG_EOF
);
6381 src
->buffer
[0] = (JOCTET
) 0xFF;
6382 src
->buffer
[1] = (JOCTET
) JPEG_EOI
;
6383 src
->mgr
.bytes_in_buffer
= 2;
6385 src
->mgr
.next_input_byte
= src
->buffer
;
6392 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6393 is the JPEG data source manager. */
6396 our_stdio_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6398 struct jpeg_stdio_mgr
*src
;
6399 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6401 while (num_bytes
> 0 && !src
->finished
)
6403 if (num_bytes
<= src
->mgr
.bytes_in_buffer
)
6405 src
->mgr
.bytes_in_buffer
-= num_bytes
;
6406 src
->mgr
.next_input_byte
+= num_bytes
;
6411 num_bytes
-= src
->mgr
.bytes_in_buffer
;
6412 src
->mgr
.bytes_in_buffer
= 0;
6413 src
->mgr
.next_input_byte
= NULL
;
6415 our_stdio_fill_input_buffer (cinfo
);
6421 /* Set up the JPEG lib for reading an image from a FILE *.
6422 CINFO is the decompression info structure created for
6423 reading the image. */
6426 jpeg_file_src (j_decompress_ptr cinfo
, FILE *fp
)
6428 struct jpeg_stdio_mgr
*src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6432 /* First time for this JPEG object? */
6433 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6434 JPOOL_PERMANENT
, sizeof *src
);
6435 cinfo
->src
= (struct jpeg_source_mgr
*) src
;
6436 src
->buffer
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6438 JPEG_STDIO_BUFFER_SIZE
);
6443 src
->mgr
.init_source
= our_common_init_source
;
6444 src
->mgr
.fill_input_buffer
= our_stdio_fill_input_buffer
;
6445 src
->mgr
.skip_input_data
= our_stdio_skip_input_data
;
6446 src
->mgr
.resync_to_restart
= jpeg_resync_to_restart_wrapper
; /* Use default method. */
6447 src
->mgr
.term_source
= our_common_term_source
;
6448 src
->mgr
.bytes_in_buffer
= 0;
6449 src
->mgr
.next_input_byte
= NULL
;
6453 /* Load image IMG for use on frame F. Patterned after example.c
6454 from the JPEG lib. */
6457 jpeg_load_body (struct frame
*f
, struct image
*img
,
6458 struct my_jpeg_error_mgr
*mgr
)
6460 Lisp_Object file
, specified_file
;
6461 Lisp_Object specified_data
;
6464 int row_stride
, x
, y
;
6465 XImagePtr ximg
= NULL
;
6466 unsigned long *colors
;
6469 /* Open the JPEG file. */
6470 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6471 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6473 if (NILP (specified_data
))
6475 file
= x_find_image_file (specified_file
);
6476 if (!STRINGP (file
))
6478 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
6482 fp
= emacs_fopen (SSDATA (file
), "rb");
6485 image_error ("Cannot open `%s'", file
, Qnil
);
6489 else if (!STRINGP (specified_data
))
6491 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
6495 IF_LINT (mgr
->fp
= fp
);
6497 /* Customize libjpeg's error handling to call my_error_exit when an
6498 error is detected. This function will perform a longjmp. */
6499 mgr
->cinfo
.err
= fn_jpeg_std_error (&mgr
->pub
);
6500 mgr
->pub
.error_exit
= my_error_exit
;
6501 if (sys_setjmp (mgr
->setjmp_buffer
))
6503 switch (mgr
->failure_code
)
6505 case MY_JPEG_ERROR_EXIT
:
6507 char buf
[JMSG_LENGTH_MAX
];
6508 mgr
->cinfo
.err
->format_message ((j_common_ptr
) &mgr
->cinfo
, buf
);
6509 image_error ("Error reading JPEG image `%s': %s", img
->spec
,
6510 build_string (buf
));
6514 case MY_JPEG_INVALID_IMAGE_SIZE
:
6515 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
6518 case MY_JPEG_CANNOT_CREATE_X
:
6522 /* Close the input file and destroy the JPEG object. */
6525 fn_jpeg_destroy_decompress (&mgr
->cinfo
);
6527 /* If we already have an XImage, free that. */
6528 x_destroy_x_image (ximg
);
6530 /* Free pixmap and colors. */
6531 x_clear_image (f
, img
);
6535 /* Silence a bogus diagnostic; see GCC bug 54561. */
6536 IF_LINT (fp
= mgr
->fp
);
6538 /* Create the JPEG decompression object. Let it read from fp.
6539 Read the JPEG image header. */
6540 fn_jpeg_CreateDecompress (&mgr
->cinfo
, JPEG_LIB_VERSION
, sizeof *&mgr
->cinfo
);
6542 if (NILP (specified_data
))
6543 jpeg_file_src (&mgr
->cinfo
, fp
);
6545 jpeg_memory_src (&mgr
->cinfo
, SDATA (specified_data
),
6546 SBYTES (specified_data
));
6548 fn_jpeg_read_header (&mgr
->cinfo
, 1);
6550 /* Customize decompression so that color quantization will be used.
6551 Start decompression. */
6552 mgr
->cinfo
.quantize_colors
= 1;
6553 fn_jpeg_start_decompress (&mgr
->cinfo
);
6554 width
= img
->width
= mgr
->cinfo
.output_width
;
6555 height
= img
->height
= mgr
->cinfo
.output_height
;
6557 if (!check_image_size (f
, width
, height
))
6559 mgr
->failure_code
= MY_JPEG_INVALID_IMAGE_SIZE
;
6560 sys_longjmp (mgr
->setjmp_buffer
, 1);
6563 /* Create X image and pixmap. */
6564 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6566 mgr
->failure_code
= MY_JPEG_CANNOT_CREATE_X
;
6567 sys_longjmp (mgr
->setjmp_buffer
, 1);
6570 /* Allocate colors. When color quantization is used,
6571 mgr->cinfo.actual_number_of_colors has been set with the number of
6572 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6573 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6574 No more than 255 colors will be generated. */
6578 if (mgr
->cinfo
.out_color_components
> 2)
6579 ir
= 0, ig
= 1, ib
= 2;
6580 else if (mgr
->cinfo
.out_color_components
> 1)
6581 ir
= 0, ig
= 1, ib
= 0;
6583 ir
= 0, ig
= 0, ib
= 0;
6585 /* Use the color table mechanism because it handles colors that
6586 cannot be allocated nicely. Such colors will be replaced with
6587 a default color, and we don't have to care about which colors
6588 can be freed safely, and which can't. */
6589 init_color_table ();
6590 colors
= alloca (mgr
->cinfo
.actual_number_of_colors
* sizeof *colors
);
6592 for (i
= 0; i
< mgr
->cinfo
.actual_number_of_colors
; ++i
)
6594 /* Multiply RGB values with 255 because X expects RGB values
6595 in the range 0..0xffff. */
6596 int r
= mgr
->cinfo
.colormap
[ir
][i
] << 8;
6597 int g
= mgr
->cinfo
.colormap
[ig
][i
] << 8;
6598 int b
= mgr
->cinfo
.colormap
[ib
][i
] << 8;
6599 colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
6602 #ifdef COLOR_TABLE_SUPPORT
6603 /* Remember those colors actually allocated. */
6604 img
->colors
= colors_in_color_table (&img
->ncolors
);
6605 free_color_table ();
6606 #endif /* COLOR_TABLE_SUPPORT */
6610 row_stride
= width
* mgr
->cinfo
.output_components
;
6611 buffer
= mgr
->cinfo
.mem
->alloc_sarray ((j_common_ptr
) &mgr
->cinfo
,
6612 JPOOL_IMAGE
, row_stride
, 1);
6613 for (y
= 0; y
< height
; ++y
)
6615 fn_jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6616 for (x
= 0; x
< mgr
->cinfo
.output_width
; ++x
)
6617 XPutPixel (ximg
, x
, y
, colors
[buffer
[0][x
]]);
6621 fn_jpeg_finish_decompress (&mgr
->cinfo
);
6622 fn_jpeg_destroy_decompress (&mgr
->cinfo
);
6626 /* Maybe fill in the background field while we have ximg handy. */
6627 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6628 /* Casting avoids a GCC warning. */
6629 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6631 /* Put ximg into the image. */
6632 image_put_x_image (f
, img
, ximg
, 0);
6637 jpeg_load (struct frame
*f
, struct image
*img
)
6639 struct my_jpeg_error_mgr mgr
;
6640 return jpeg_load_body (f
, img
, &mgr
);
6643 #else /* HAVE_JPEG */
6647 jpeg_load (struct frame
*f
, struct image
*img
)
6649 return ns_load_image (f
, img
,
6650 image_spec_value (img
->spec
, QCfile
, NULL
),
6651 image_spec_value (img
->spec
, QCdata
, NULL
));
6653 #endif /* HAVE_NS */
6655 #endif /* !HAVE_JPEG */
6659 /***********************************************************************
6661 ***********************************************************************/
6663 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6665 static bool tiff_image_p (Lisp_Object object
);
6666 static bool tiff_load (struct frame
*f
, struct image
*img
);
6668 /* The symbol `tiff' identifying images of this type. */
6670 static Lisp_Object Qtiff
;
6672 /* Indices of image specification fields in tiff_format, below. */
6674 enum tiff_keyword_index
6683 TIFF_HEURISTIC_MASK
,
6690 /* Vector of image_keyword structures describing the format
6691 of valid user-defined image specifications. */
6693 static const struct image_keyword tiff_format
[TIFF_LAST
] =
6695 {":type", IMAGE_SYMBOL_VALUE
, 1},
6696 {":data", IMAGE_STRING_VALUE
, 0},
6697 {":file", IMAGE_STRING_VALUE
, 0},
6698 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6699 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6700 {":relief", IMAGE_INTEGER_VALUE
, 0},
6701 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6702 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6703 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6704 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
6705 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0}
6708 #if defined HAVE_NTGUI && defined WINDOWSNT
6709 static bool init_tiff_functions (void);
6711 #define init_tiff_functions NULL
6714 /* Structure describing the image type `tiff'. */
6716 static struct image_type tiff_type
=
6722 init_tiff_functions
,
6726 /* Return true if OBJECT is a valid TIFF image specification. */
6729 tiff_image_p (Lisp_Object object
)
6731 struct image_keyword fmt
[TIFF_LAST
];
6732 memcpy (fmt
, tiff_format
, sizeof fmt
);
6734 if (!parse_image_spec (object
, fmt
, TIFF_LAST
, Qtiff
))
6737 /* Must specify either the :data or :file keyword. */
6738 return fmt
[TIFF_FILE
].count
+ fmt
[TIFF_DATA
].count
== 1;
6741 #endif /* HAVE_TIFF || HAVE_NS */
6749 /* TIFF library details. */
6750 DEF_IMGLIB_FN (TIFFErrorHandler
, TIFFSetErrorHandler
, (TIFFErrorHandler
));
6751 DEF_IMGLIB_FN (TIFFErrorHandler
, TIFFSetWarningHandler
, (TIFFErrorHandler
));
6752 DEF_IMGLIB_FN (TIFF
*, TIFFOpen
, (const char *, const char *));
6753 DEF_IMGLIB_FN (TIFF
*, TIFFClientOpen
, (const char *, const char *, thandle_t
,
6754 TIFFReadWriteProc
, TIFFReadWriteProc
,
6755 TIFFSeekProc
, TIFFCloseProc
, TIFFSizeProc
,
6756 TIFFMapFileProc
, TIFFUnmapFileProc
));
6757 DEF_IMGLIB_FN (int, TIFFGetField
, (TIFF
*, ttag_t
, ...));
6758 DEF_IMGLIB_FN (int, TIFFReadRGBAImage
, (TIFF
*, uint32
, uint32
, uint32
*, int));
6759 DEF_IMGLIB_FN (void, TIFFClose
, (TIFF
*));
6760 DEF_IMGLIB_FN (int, TIFFSetDirectory
, (TIFF
*, tdir_t
));
6763 init_tiff_functions (void)
6767 if (!(library
= w32_delayed_load (Qtiff
)))
6770 LOAD_IMGLIB_FN (library
, TIFFSetErrorHandler
);
6771 LOAD_IMGLIB_FN (library
, TIFFSetWarningHandler
);
6772 LOAD_IMGLIB_FN (library
, TIFFOpen
);
6773 LOAD_IMGLIB_FN (library
, TIFFClientOpen
);
6774 LOAD_IMGLIB_FN (library
, TIFFGetField
);
6775 LOAD_IMGLIB_FN (library
, TIFFReadRGBAImage
);
6776 LOAD_IMGLIB_FN (library
, TIFFClose
);
6777 LOAD_IMGLIB_FN (library
, TIFFSetDirectory
);
6783 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6784 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6785 #define fn_TIFFOpen TIFFOpen
6786 #define fn_TIFFClientOpen TIFFClientOpen
6787 #define fn_TIFFGetField TIFFGetField
6788 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6789 #define fn_TIFFClose TIFFClose
6790 #define fn_TIFFSetDirectory TIFFSetDirectory
6791 #endif /* WINDOWSNT */
6794 /* Reading from a memory buffer for TIFF images Based on the PNG
6795 memory source, but we have to provide a lot of extra functions.
6798 We really only need to implement read and seek, but I am not
6799 convinced that the TIFF library is smart enough not to destroy
6800 itself if we only hand it the function pointers we need to
6805 unsigned char *bytes
;
6812 tiff_read_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
6814 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
6816 size
= min (size
, src
->len
- src
->index
);
6817 memcpy (buf
, src
->bytes
+ src
->index
, size
);
6823 tiff_write_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
6829 tiff_seek_in_memory (thandle_t data
, toff_t off
, int whence
)
6831 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
6836 case SEEK_SET
: /* Go from beginning of source. */
6840 case SEEK_END
: /* Go from end of source. */
6841 idx
= src
->len
+ off
;
6844 case SEEK_CUR
: /* Go from current position. */
6845 idx
= src
->index
+ off
;
6848 default: /* Invalid `whence'. */
6852 if (idx
> src
->len
|| idx
< 0)
6860 tiff_close_memory (thandle_t data
)
6867 tiff_mmap_memory (thandle_t data
, tdata_t
*pbase
, toff_t
*psize
)
6869 /* It is already _IN_ memory. */
6874 tiff_unmap_memory (thandle_t data
, tdata_t base
, toff_t size
)
6876 /* We don't need to do this. */
6880 tiff_size_of_memory (thandle_t data
)
6882 return ((tiff_memory_source
*) data
)->len
;
6885 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6886 compiler error compiling tiff_handler, see Bugzilla bug #17406
6887 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6888 this function as external works around that problem. */
6889 #if defined (__MINGW32__) && __GNUC__ == 3
6890 # define MINGW_STATIC
6892 # define MINGW_STATIC static
6896 tiff_handler (const char *, const char *, const char *, va_list)
6897 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6899 tiff_handler (const char *log_format
, const char *title
,
6900 const char *format
, va_list ap
)
6902 /* doprnt is not suitable here, as TIFF handlers are called from
6903 libtiff and are passed arbitrary printf directives. Instead, use
6904 vsnprintf, taking care to be portable to nonstandard environments
6905 where vsnprintf returns -1 on buffer overflow. Since it's just a
6906 log entry, it's OK to truncate it. */
6908 int len
= vsnprintf (buf
, sizeof buf
, format
, ap
);
6909 add_to_log (log_format
, build_string (title
),
6910 make_string (buf
, max (0, min (len
, sizeof buf
- 1))));
6914 static void tiff_error_handler (const char *, const char *, va_list)
6915 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6917 tiff_error_handler (const char *title
, const char *format
, va_list ap
)
6919 tiff_handler ("TIFF error: %s %s", title
, format
, ap
);
6923 static void tiff_warning_handler (const char *, const char *, va_list)
6924 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6926 tiff_warning_handler (const char *title
, const char *format
, va_list ap
)
6928 tiff_handler ("TIFF warning: %s %s", title
, format
, ap
);
6932 /* Load TIFF image IMG for use on frame F. Value is true if
6936 tiff_load (struct frame
*f
, struct image
*img
)
6938 Lisp_Object file
, specified_file
;
6939 Lisp_Object specified_data
;
6941 int width
, height
, x
, y
, count
;
6945 tiff_memory_source memsrc
;
6948 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6949 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6951 fn_TIFFSetErrorHandler ((TIFFErrorHandler
) tiff_error_handler
);
6952 fn_TIFFSetWarningHandler ((TIFFErrorHandler
) tiff_warning_handler
);
6954 if (NILP (specified_data
))
6956 /* Read from a file */
6957 file
= x_find_image_file (specified_file
);
6958 if (!STRINGP (file
))
6960 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
6964 /* Try to open the image file. */
6965 tiff
= fn_TIFFOpen (SSDATA (file
), "r");
6968 image_error ("Cannot open `%s'", file
, Qnil
);
6974 if (!STRINGP (specified_data
))
6976 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
6980 /* Memory source! */
6981 memsrc
.bytes
= SDATA (specified_data
);
6982 memsrc
.len
= SBYTES (specified_data
);
6985 tiff
= fn_TIFFClientOpen ("memory_source", "r", (thandle_t
)&memsrc
,
6986 tiff_read_from_memory
,
6987 tiff_write_from_memory
,
6988 tiff_seek_in_memory
,
6990 tiff_size_of_memory
,
6996 image_error ("Cannot open memory source for `%s'", img
->spec
, Qnil
);
7001 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
7002 if (INTEGERP (image
))
7004 EMACS_INT ino
= XFASTINT (image
);
7005 if (! (TYPE_MINIMUM (tdir_t
) <= ino
&& ino
<= TYPE_MAXIMUM (tdir_t
)
7006 && fn_TIFFSetDirectory (tiff
, ino
)))
7008 image_error ("Invalid image number `%s' in image `%s'",
7010 fn_TIFFClose (tiff
);
7015 /* Get width and height of the image, and allocate a raster buffer
7016 of width x height 32-bit values. */
7017 fn_TIFFGetField (tiff
, TIFFTAG_IMAGEWIDTH
, &width
);
7018 fn_TIFFGetField (tiff
, TIFFTAG_IMAGELENGTH
, &height
);
7020 if (!check_image_size (f
, width
, height
))
7022 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
7023 fn_TIFFClose (tiff
);
7027 /* Create the X image and pixmap. */
7028 if (! (height
<= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *buf
/ width
7029 && image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
7032 fn_TIFFClose (tiff
);
7036 buf
= xmalloc (sizeof *buf
* width
* height
);
7038 rc
= fn_TIFFReadRGBAImage (tiff
, width
, height
, buf
, 0);
7040 /* Count the number of images in the file. */
7041 for (count
= 1; fn_TIFFSetDirectory (tiff
, count
); count
++)
7045 img
->lisp_data
= Fcons (Qcount
,
7046 Fcons (make_number (count
),
7049 fn_TIFFClose (tiff
);
7052 image_error ("Error reading TIFF image `%s'", img
->spec
, Qnil
);
7057 /* Initialize the color table. */
7058 init_color_table ();
7060 /* Process the pixel raster. Origin is in the lower-left corner. */
7061 for (y
= 0; y
< height
; ++y
)
7063 uint32
*row
= buf
+ y
* width
;
7065 for (x
= 0; x
< width
; ++x
)
7067 uint32 abgr
= row
[x
];
7068 int r
= TIFFGetR (abgr
) << 8;
7069 int g
= TIFFGetG (abgr
) << 8;
7070 int b
= TIFFGetB (abgr
) << 8;
7071 XPutPixel (ximg
, x
, height
- 1 - y
, lookup_rgb_color (f
, r
, g
, b
));
7075 #ifdef COLOR_TABLE_SUPPORT
7076 /* Remember the colors allocated for the image. Free the color table. */
7077 img
->colors
= colors_in_color_table (&img
->ncolors
);
7078 free_color_table ();
7079 #endif /* COLOR_TABLE_SUPPORT */
7082 img
->height
= height
;
7084 /* Maybe fill in the background field while we have ximg handy. */
7085 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7086 /* Casting avoids a GCC warning on W32. */
7087 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7089 /* Put ximg into the image. */
7090 image_put_x_image (f
, img
, ximg
, 0);
7096 #else /* HAVE_TIFF */
7100 tiff_load (struct frame
*f
, struct image
*img
)
7102 return ns_load_image (f
, img
,
7103 image_spec_value (img
->spec
, QCfile
, NULL
),
7104 image_spec_value (img
->spec
, QCdata
, NULL
));
7106 #endif /* HAVE_NS */
7108 #endif /* !HAVE_TIFF */
7112 /***********************************************************************
7114 ***********************************************************************/
7116 #if defined (HAVE_GIF) || defined (HAVE_NS)
7118 static bool gif_image_p (Lisp_Object object
);
7119 static bool gif_load (struct frame
*f
, struct image
*img
);
7120 static void gif_clear_image (struct frame
*f
, struct image
*img
);
7122 /* The symbol `gif' identifying images of this type. */
7124 static Lisp_Object Qgif
;
7126 /* Indices of image specification fields in gif_format, below. */
7128 enum gif_keyword_index
7144 /* Vector of image_keyword structures describing the format
7145 of valid user-defined image specifications. */
7147 static const struct image_keyword gif_format
[GIF_LAST
] =
7149 {":type", IMAGE_SYMBOL_VALUE
, 1},
7150 {":data", IMAGE_STRING_VALUE
, 0},
7151 {":file", IMAGE_STRING_VALUE
, 0},
7152 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7153 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7154 {":relief", IMAGE_INTEGER_VALUE
, 0},
7155 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7156 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7157 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7158 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0},
7159 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
7162 #if defined HAVE_NTGUI && defined WINDOWSNT
7163 static bool init_gif_functions (void);
7165 #define init_gif_functions NULL
7168 /* Structure describing the image type `gif'. */
7170 static struct image_type gif_type
=
7180 /* Free X resources of GIF image IMG which is used on frame F. */
7183 gif_clear_image (struct frame
*f
, struct image
*img
)
7185 img
->lisp_data
= Qnil
;
7186 x_clear_image (f
, img
);
7189 /* Return true if OBJECT is a valid GIF image specification. */
7192 gif_image_p (Lisp_Object object
)
7194 struct image_keyword fmt
[GIF_LAST
];
7195 memcpy (fmt
, gif_format
, sizeof fmt
);
7197 if (!parse_image_spec (object
, fmt
, GIF_LAST
, Qgif
))
7200 /* Must specify either the :data or :file keyword. */
7201 return fmt
[GIF_FILE
].count
+ fmt
[GIF_DATA
].count
== 1;
7204 #endif /* HAVE_GIF */
7208 #if defined (HAVE_NTGUI)
7209 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7210 Undefine before redefining to avoid a preprocessor warning. */
7214 /* avoid conflict with QuickdrawText.h */
7215 #define DrawText gif_DrawText
7216 #include <gif_lib.h>
7219 #else /* HAVE_NTGUI */
7221 #include <gif_lib.h>
7223 #endif /* HAVE_NTGUI */
7228 /* GIF library details. */
7229 DEF_IMGLIB_FN (int, DGifCloseFile
, (GifFileType
*));
7230 DEF_IMGLIB_FN (int, DGifSlurp
, (GifFileType
*));
7231 DEF_IMGLIB_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
));
7232 DEF_IMGLIB_FN (GifFileType
*, DGifOpenFileName
, (const char *));
7235 init_gif_functions (void)
7239 if (!(library
= w32_delayed_load (Qgif
)))
7242 LOAD_IMGLIB_FN (library
, DGifCloseFile
);
7243 LOAD_IMGLIB_FN (library
, DGifSlurp
);
7244 LOAD_IMGLIB_FN (library
, DGifOpen
);
7245 LOAD_IMGLIB_FN (library
, DGifOpenFileName
);
7251 #define fn_DGifCloseFile DGifCloseFile
7252 #define fn_DGifSlurp DGifSlurp
7253 #define fn_DGifOpen DGifOpen
7254 #define fn_DGifOpenFileName DGifOpenFileName
7256 #endif /* WINDOWSNT */
7258 /* Reading a GIF image from memory
7259 Based on the PNG memory stuff to a certain extent. */
7263 unsigned char *bytes
;
7269 /* Make the current memory source available to gif_read_from_memory.
7270 It's done this way because not all versions of libungif support
7271 a UserData field in the GifFileType structure. */
7272 static gif_memory_source
*current_gif_memory_src
;
7275 gif_read_from_memory (GifFileType
*file
, GifByteType
*buf
, int len
)
7277 gif_memory_source
*src
= current_gif_memory_src
;
7279 if (len
> src
->len
- src
->index
)
7282 memcpy (buf
, src
->bytes
+ src
->index
, len
);
7288 /* Load GIF image IMG for use on frame F. Value is true if
7291 static const int interlace_start
[] = {0, 4, 2, 1};
7292 static const int interlace_increment
[] = {8, 8, 4, 2};
7294 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7297 gif_load (struct frame
*f
, struct image
*img
)
7300 int rc
, width
, height
, x
, y
, i
, j
;
7302 ColorMapObject
*gif_color_map
;
7303 unsigned long pixel_colors
[256];
7305 gif_memory_source memsrc
;
7306 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
7307 Lisp_Object specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7308 Lisp_Object specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7309 unsigned long bgcolor
= 0;
7312 if (NILP (specified_data
))
7314 file
= x_find_image_file (specified_file
);
7315 if (!STRINGP (file
))
7317 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
7321 /* Open the GIF file. */
7322 gif
= fn_DGifOpenFileName (SSDATA (file
));
7325 image_error ("Cannot open `%s'", file
, Qnil
);
7331 if (!STRINGP (specified_data
))
7333 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
7337 /* Read from memory! */
7338 current_gif_memory_src
= &memsrc
;
7339 memsrc
.bytes
= SDATA (specified_data
);
7340 memsrc
.len
= SBYTES (specified_data
);
7343 gif
= fn_DGifOpen (&memsrc
, gif_read_from_memory
);
7346 image_error ("Cannot open memory source `%s'", img
->spec
, Qnil
);
7351 /* Before reading entire contents, check the declared image size. */
7352 if (!check_image_size (f
, gif
->SWidth
, gif
->SHeight
))
7354 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
7355 fn_DGifCloseFile (gif
);
7359 /* Read entire contents. */
7360 rc
= fn_DGifSlurp (gif
);
7361 if (rc
== GIF_ERROR
|| gif
->ImageCount
<= 0)
7363 image_error ("Error reading `%s'", img
->spec
, Qnil
);
7364 fn_DGifCloseFile (gif
);
7368 /* Which sub-image are we to display? */
7370 Lisp_Object image_number
= image_spec_value (img
->spec
, QCindex
, NULL
);
7371 idx
= INTEGERP (image_number
) ? XFASTINT (image_number
) : 0;
7372 if (idx
< 0 || idx
>= gif
->ImageCount
)
7374 image_error ("Invalid image number `%s' in image `%s'",
7375 image_number
, img
->spec
);
7376 fn_DGifCloseFile (gif
);
7381 width
= img
->width
= gif
->SWidth
;
7382 height
= img
->height
= gif
->SHeight
;
7384 img
->corners
[TOP_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Top
;
7385 img
->corners
[LEFT_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Left
;
7386 img
->corners
[BOT_CORNER
]
7387 = img
->corners
[TOP_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Height
;
7388 img
->corners
[RIGHT_CORNER
]
7389 = img
->corners
[LEFT_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Width
;
7391 if (!check_image_size (f
, width
, height
))
7393 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
7394 fn_DGifCloseFile (gif
);
7398 /* Check that the selected subimages fit. It's not clear whether
7399 the GIF spec requires this, but Emacs can crash if they don't fit. */
7400 for (j
= 0; j
<= idx
; ++j
)
7402 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7403 int subimg_width
= subimage
->ImageDesc
.Width
;
7404 int subimg_height
= subimage
->ImageDesc
.Height
;
7405 int subimg_top
= subimage
->ImageDesc
.Top
;
7406 int subimg_left
= subimage
->ImageDesc
.Left
;
7407 if (! (0 <= subimg_width
&& 0 <= subimg_height
7408 && 0 <= subimg_top
&& subimg_top
<= height
- subimg_height
7409 && 0 <= subimg_left
&& subimg_left
<= width
- subimg_width
))
7411 image_error ("Subimage does not fit in image", Qnil
, Qnil
);
7412 fn_DGifCloseFile (gif
);
7417 /* Create the X image and pixmap. */
7418 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
7420 fn_DGifCloseFile (gif
);
7424 /* Clear the part of the screen image not covered by the image.
7425 Full animated GIF support requires more here (see the gif89 spec,
7426 disposal methods). Let's simply assume that the part not covered
7427 by a sub-image is in the frame's background color. */
7428 for (y
= 0; y
< img
->corners
[TOP_CORNER
]; ++y
)
7429 for (x
= 0; x
< width
; ++x
)
7430 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7432 for (y
= img
->corners
[BOT_CORNER
]; y
< height
; ++y
)
7433 for (x
= 0; x
< width
; ++x
)
7434 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7436 for (y
= img
->corners
[TOP_CORNER
]; y
< img
->corners
[BOT_CORNER
]; ++y
)
7438 for (x
= 0; x
< img
->corners
[LEFT_CORNER
]; ++x
)
7439 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7440 for (x
= img
->corners
[RIGHT_CORNER
]; x
< width
; ++x
)
7441 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7444 /* Read the GIF image into the X image. */
7446 /* FIXME: With the current implementation, loading an animated gif
7447 is quadratic in the number of animation frames, since each frame
7448 is a separate struct image. We must provide a way for a single
7449 gif_load call to construct and save all animation frames. */
7451 init_color_table ();
7452 if (STRINGP (specified_bg
))
7453 bgcolor
= x_alloc_image_color (f
, img
, specified_bg
,
7454 FRAME_BACKGROUND_PIXEL (f
));
7455 for (j
= 0; j
<= idx
; ++j
)
7457 /* We use a local variable `raster' here because RasterBits is a
7458 char *, which invites problems with bytes >= 0x80. */
7459 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7460 unsigned char *raster
= (unsigned char *) subimage
->RasterBits
;
7461 int transparency_color_index
= -1;
7463 int subimg_width
= subimage
->ImageDesc
.Width
;
7464 int subimg_height
= subimage
->ImageDesc
.Height
;
7465 int subimg_top
= subimage
->ImageDesc
.Top
;
7466 int subimg_left
= subimage
->ImageDesc
.Left
;
7468 /* Find the Graphic Control Extension block for this sub-image.
7469 Extract the disposal method and transparency color. */
7470 for (i
= 0; i
< subimage
->ExtensionBlockCount
; i
++)
7472 ExtensionBlock
*extblock
= subimage
->ExtensionBlocks
+ i
;
7474 if ((extblock
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
)
7475 && extblock
->ByteCount
== 4
7476 && extblock
->Bytes
[0] & 1)
7478 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7479 to background". Treat any other value like 2. */
7480 disposal
= (extblock
->Bytes
[0] >> 2) & 7;
7481 transparency_color_index
= (unsigned char) extblock
->Bytes
[3];
7486 /* We can't "keep in place" the first subimage. */
7490 /* For disposal == 0, the spec says "No disposal specified. The
7491 decoder is not required to take any action." In practice, it
7492 seems we need to treat this like "keep in place", see e.g.
7493 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7497 /* Allocate subimage colors. */
7498 memset (pixel_colors
, 0, sizeof pixel_colors
);
7499 gif_color_map
= subimage
->ImageDesc
.ColorMap
;
7501 gif_color_map
= gif
->SColorMap
;
7504 for (i
= 0; i
< gif_color_map
->ColorCount
; ++i
)
7506 if (transparency_color_index
== i
)
7507 pixel_colors
[i
] = STRINGP (specified_bg
)
7508 ? bgcolor
: FRAME_BACKGROUND_PIXEL (f
);
7511 int r
= gif_color_map
->Colors
[i
].Red
<< 8;
7512 int g
= gif_color_map
->Colors
[i
].Green
<< 8;
7513 int b
= gif_color_map
->Colors
[i
].Blue
<< 8;
7514 pixel_colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
7518 /* Apply the pixel values. */
7519 if (gif
->SavedImages
[j
].ImageDesc
.Interlace
)
7523 for (y
= 0, row
= interlace_start
[0], pass
= 0;
7525 y
++, row
+= interlace_increment
[pass
])
7527 while (subimg_height
<= row
)
7529 lint_assume (pass
< 3);
7530 row
= interlace_start
[++pass
];
7533 for (x
= 0; x
< subimg_width
; x
++)
7535 int c
= raster
[y
* subimg_width
+ x
];
7536 if (transparency_color_index
!= c
|| disposal
!= 1)
7537 XPutPixel (ximg
, x
+ subimg_left
, row
+ subimg_top
,
7544 for (y
= 0; y
< subimg_height
; ++y
)
7545 for (x
= 0; x
< subimg_width
; ++x
)
7547 int c
= raster
[y
* subimg_width
+ x
];
7548 if (transparency_color_index
!= c
|| disposal
!= 1)
7549 XPutPixel (ximg
, x
+ subimg_left
, y
+ subimg_top
,
7555 #ifdef COLOR_TABLE_SUPPORT
7556 img
->colors
= colors_in_color_table (&img
->ncolors
);
7557 free_color_table ();
7558 #endif /* COLOR_TABLE_SUPPORT */
7560 /* Save GIF image extension data for `image-metadata'.
7561 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7562 img
->lisp_data
= Qnil
;
7563 if (gif
->SavedImages
[idx
].ExtensionBlockCount
> 0)
7566 ExtensionBlock
*ext
= gif
->SavedImages
[idx
].ExtensionBlocks
;
7567 for (i
= 0; i
< gif
->SavedImages
[idx
].ExtensionBlockCount
; i
++, ext
++)
7568 /* Append (... FUNCTION "BYTES") */
7571 = Fcons (make_number (ext
->Function
),
7572 Fcons (make_unibyte_string (ext
->Bytes
, ext
->ByteCount
),
7574 if (ext
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
7575 && ext
->ByteCount
== 4)
7577 delay
= ext
->Bytes
[2] << CHAR_BIT
;
7578 delay
|= ext
->Bytes
[1];
7581 img
->lisp_data
= list2 (Qextension_data
, img
->lisp_data
);
7585 Fcons (make_float (delay
/ 100.0),
7589 if (gif
->ImageCount
> 1)
7590 img
->lisp_data
= Fcons (Qcount
,
7591 Fcons (make_number (gif
->ImageCount
),
7594 fn_DGifCloseFile (gif
);
7596 /* Maybe fill in the background field while we have ximg handy. */
7597 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7598 /* Casting avoids a GCC warning. */
7599 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7601 /* Put ximg into the image. */
7602 image_put_x_image (f
, img
, ximg
, 0);
7607 #else /* !HAVE_GIF */
7611 gif_load (struct frame
*f
, struct image
*img
)
7613 return ns_load_image (f
, img
,
7614 image_spec_value (img
->spec
, QCfile
, NULL
),
7615 image_spec_value (img
->spec
, QCdata
, NULL
));
7617 #endif /* HAVE_NS */
7619 #endif /* HAVE_GIF */
7622 #ifdef HAVE_IMAGEMAGICK
7624 /***********************************************************************
7626 ***********************************************************************/
7628 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
7629 safely rounded and clipped to int range. */
7632 scale_image_size (int size
, size_t divisor
, size_t multiplier
)
7637 double scaled
= s
* multiplier
/ divisor
+ 0.5;
7638 if (scaled
< INT_MAX
)
7644 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
7645 Use SPEC to deduce the size. Store the desired size into
7646 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
7648 compute_image_size (size_t width
, size_t height
,
7650 int *d_width
, int *d_height
)
7653 int desired_width
, desired_height
;
7655 /* If width and/or height is set in the display spec assume we want
7656 to scale to those values. If either h or w is unspecified, the
7657 unspecified should be calculated from the specified to preserve
7659 value
= image_spec_value (spec
, QCwidth
, NULL
);
7660 desired_width
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
7661 value
= image_spec_value (spec
, QCheight
, NULL
);
7662 desired_height
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
7664 if (desired_width
== -1)
7666 value
= image_spec_value (spec
, QCmax_width
, NULL
);
7667 if (NATNUMP (value
))
7669 int max_width
= min (XFASTINT (value
), INT_MAX
);
7670 if (max_width
< width
)
7672 /* The image is wider than :max-width. */
7673 desired_width
= max_width
;
7674 if (desired_height
== -1)
7676 desired_height
= scale_image_size (desired_width
,
7678 value
= image_spec_value (spec
, QCmax_height
, NULL
);
7679 if (NATNUMP (value
))
7681 int max_height
= min (XFASTINT (value
), INT_MAX
);
7682 if (max_height
< desired_height
)
7684 desired_height
= max_height
;
7685 desired_width
= scale_image_size (desired_height
,
7694 if (desired_height
== -1)
7696 value
= image_spec_value (spec
, QCmax_height
, NULL
);
7697 if (NATNUMP (value
))
7699 int max_height
= min (XFASTINT (value
), INT_MAX
);
7700 if (max_height
< height
)
7701 desired_height
= max_height
;
7705 if (desired_width
!= -1 && desired_height
== -1)
7706 /* w known, calculate h. */
7707 desired_height
= scale_image_size (desired_width
, width
, height
);
7709 if (desired_width
== -1 && desired_height
!= -1)
7710 /* h known, calculate w. */
7711 desired_width
= scale_image_size (desired_height
, height
, width
);
7713 *d_width
= desired_width
;
7714 *d_height
= desired_height
;
7717 static Lisp_Object Qimagemagick
;
7719 static bool imagemagick_image_p (Lisp_Object
);
7720 static bool imagemagick_load (struct frame
*, struct image
*);
7721 static void imagemagick_clear_image (struct frame
*, struct image
*);
7723 /* Indices of image specification fields in imagemagick_format. */
7725 enum imagemagick_keyword_index
7733 IMAGEMAGICK_ALGORITHM
,
7734 IMAGEMAGICK_HEURISTIC_MASK
,
7736 IMAGEMAGICK_BACKGROUND
,
7739 IMAGEMAGICK_MAX_HEIGHT
,
7740 IMAGEMAGICK_MAX_WIDTH
,
7742 IMAGEMAGICK_ROTATION
,
7747 /* Vector of image_keyword structures describing the format
7748 of valid user-defined image specifications. */
7750 static struct image_keyword imagemagick_format
[IMAGEMAGICK_LAST
] =
7752 {":type", IMAGE_SYMBOL_VALUE
, 1},
7753 {":data", IMAGE_STRING_VALUE
, 0},
7754 {":file", IMAGE_STRING_VALUE
, 0},
7755 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7756 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7757 {":relief", IMAGE_INTEGER_VALUE
, 0},
7758 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7759 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7760 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7761 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
7762 {":height", IMAGE_INTEGER_VALUE
, 0},
7763 {":width", IMAGE_INTEGER_VALUE
, 0},
7764 {":max-height", IMAGE_INTEGER_VALUE
, 0},
7765 {":max-width", IMAGE_INTEGER_VALUE
, 0},
7766 {":format", IMAGE_SYMBOL_VALUE
, 0},
7767 {":rotation", IMAGE_NUMBER_VALUE
, 0},
7768 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
7771 #if defined HAVE_NTGUI && defined WINDOWSNT
7772 static bool init_imagemagick_functions (void);
7774 #define init_imagemagick_functions NULL
7777 /* Structure describing the image type for any image handled via
7780 static struct image_type imagemagick_type
=
7783 imagemagick_image_p
,
7785 imagemagick_clear_image
,
7786 init_imagemagick_functions
,
7790 /* Free X resources of imagemagick image IMG which is used on frame F. */
7793 imagemagick_clear_image (struct frame
*f
,
7796 x_clear_image (f
, img
);
7799 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7800 this by calling parse_image_spec and supplying the keywords that
7801 identify the IMAGEMAGICK format. */
7804 imagemagick_image_p (Lisp_Object object
)
7806 struct image_keyword fmt
[IMAGEMAGICK_LAST
];
7807 memcpy (fmt
, imagemagick_format
, sizeof fmt
);
7809 if (!parse_image_spec (object
, fmt
, IMAGEMAGICK_LAST
, Qimagemagick
))
7812 /* Must specify either the :data or :file keyword. */
7813 return fmt
[IMAGEMAGICK_FILE
].count
+ fmt
[IMAGEMAGICK_DATA
].count
== 1;
7816 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7817 Therefore rename the function so it doesn't collide with ImageMagick. */
7818 #define DrawRectangle DrawRectangleGif
7819 #include <wand/MagickWand.h>
7821 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7822 Emacs seems to work fine with the hidden version, so unhide it. */
7823 #include <magick/version.h>
7824 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7825 extern WandExport
void PixelGetMagickColor (const PixelWand
*,
7826 MagickPixelPacket
*);
7829 /* Log ImageMagick error message.
7830 Useful when a ImageMagick function returns the status `MagickFalse'. */
7833 imagemagick_error (MagickWand
*wand
)
7836 ExceptionType severity
;
7838 description
= MagickGetException (wand
, &severity
);
7839 image_error ("ImageMagick error: %s",
7840 build_string (description
),
7842 description
= (char *) MagickRelinquishMemory (description
);
7845 /* Possibly give ImageMagick some extra help to determine the image
7846 type by supplying a "dummy" filename based on the Content-Type. */
7849 imagemagick_filename_hint (Lisp_Object spec
, char hint_buffer
[MaxTextExtent
])
7851 Lisp_Object symbol
= intern ("image-format-suffixes");
7852 Lisp_Object val
= find_symbol_value (symbol
);
7858 format
= image_spec_value (spec
, intern (":format"), NULL
);
7859 val
= Fcar_safe (Fcdr_safe (Fassq (format
, val
)));
7860 if (! STRINGP (val
))
7863 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
7864 as ImageMagick would ignore the extra bytes anyway. */
7865 snprintf (hint_buffer
, MaxTextExtent
, "/tmp/foo.%s", SSDATA (val
));
7869 /* Helper function for imagemagick_load, which does the actual loading
7870 given contents and size, apart from frame and image structures,
7871 passed from imagemagick_load. Uses librimagemagick to do most of
7872 the image processing.
7874 F is a pointer to the Emacs frame; IMG to the image structure to
7875 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
7876 be parsed; SIZE is the number of bytes of data; and FILENAME is
7877 either the file name or the image data.
7879 Return true if successful. */
7882 imagemagick_load_image (struct frame
*f
, struct image
*img
,
7883 unsigned char *contents
, unsigned int size
,
7886 size_t width
, height
;
7887 MagickBooleanType status
;
7890 MagickWand
*image_wand
;
7891 MagickWand
*ping_wand
;
7892 PixelIterator
*iterator
;
7893 PixelWand
**pixels
, *bg_wand
= NULL
;
7894 MagickPixelPacket pixel
;
7899 int desired_width
, desired_height
;
7902 char hint_buffer
[MaxTextExtent
];
7903 char *filename_hint
= NULL
;
7905 /* Handle image index for image types who can contain more than one image.
7906 Interface :index is same as for GIF. First we "ping" the image to see how
7907 many sub-images it contains. Pinging is faster than loading the image to
7908 find out things about it. */
7910 /* Initialize the imagemagick environment. */
7911 MagickWandGenesis ();
7912 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
7913 ino
= INTEGERP (image
) ? XFASTINT (image
) : 0;
7914 ping_wand
= NewMagickWand ();
7915 /* MagickSetResolution (ping_wand, 2, 2); (Bug#10112) */
7918 status
= MagickPingImage (ping_wand
, filename
);
7921 filename_hint
= imagemagick_filename_hint (img
->spec
, hint_buffer
);
7922 MagickSetFilename (ping_wand
, filename_hint
);
7923 status
= MagickPingImageBlob (ping_wand
, contents
, size
);
7926 if (status
== MagickFalse
)
7928 imagemagick_error (ping_wand
);
7929 DestroyMagickWand (ping_wand
);
7933 if (ino
< 0 || ino
>= MagickGetNumberImages (ping_wand
))
7935 image_error ("Invalid image number `%s' in image `%s'",
7937 DestroyMagickWand (ping_wand
);
7941 if (MagickGetNumberImages (ping_wand
) > 1)
7944 Fcons (make_number (MagickGetNumberImages (ping_wand
)),
7947 DestroyMagickWand (ping_wand
);
7949 /* Now we know how many images are inside the file. If it's not a
7950 bundle, the number is one. Load the image data. */
7952 image_wand
= NewMagickWand ();
7955 status
= MagickReadImage (image_wand
, filename
);
7958 MagickSetFilename (image_wand
, filename_hint
);
7959 status
= MagickReadImageBlob (image_wand
, contents
, size
);
7962 if (status
== MagickFalse
)
7964 imagemagick_error (image_wand
);
7965 goto imagemagick_error
;
7968 /* If we have an animated image, get the new wand based on the
7972 MagickWand
*super_wand
= image_wand
;
7973 MagickSetIteratorIndex (super_wand
, ino
);
7974 image_wand
= MagickGetImage (super_wand
);
7975 DestroyMagickWand (super_wand
);
7978 /* Retrieve the frame's background color, for use later. */
7981 Lisp_Object specified_bg
;
7983 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
7984 if (!STRINGP (specified_bg
)
7985 || !x_defined_color (f
, SSDATA (specified_bg
), &bgcolor
, 0))
7988 bgcolor
.pixel
= FRAME_BACKGROUND_PIXEL (f
);
7989 x_query_color (f
, &bgcolor
);
7991 ns_query_color (FRAME_BACKGROUND_COLOR (f
), &bgcolor
, 1);
7995 bg_wand
= NewPixelWand ();
7996 PixelSetRed (bg_wand
, (double) bgcolor
.red
/ 65535);
7997 PixelSetGreen (bg_wand
, (double) bgcolor
.green
/ 65535);
7998 PixelSetBlue (bg_wand
, (double) bgcolor
.blue
/ 65535);
8001 compute_image_size (MagickGetImageWidth (image_wand
),
8002 MagickGetImageHeight (image_wand
),
8003 img
->spec
, &desired_width
, &desired_height
);
8005 if (desired_width
!= -1 && desired_height
!= -1)
8007 status
= MagickScaleImage (image_wand
, desired_width
, desired_height
);
8008 if (status
== MagickFalse
)
8010 image_error ("Imagemagick scale failed", Qnil
, Qnil
);
8011 imagemagick_error (image_wand
);
8012 goto imagemagick_error
;
8016 /* crop behaves similar to image slicing in Emacs but is more memory
8018 crop
= image_spec_value (img
->spec
, QCcrop
, NULL
);
8020 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8022 /* After some testing, it seems MagickCropImage is the fastest crop
8023 function in ImageMagick. This crop function seems to do less copying
8024 than the alternatives, but it still reads the entire image into memory
8025 before cropping, which is apparently difficult to avoid when using
8027 size_t crop_width
= XINT (XCAR (crop
));
8029 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8031 size_t crop_height
= XINT (XCAR (crop
));
8033 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8035 ssize_t crop_x
= XINT (XCAR (crop
));
8037 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8039 ssize_t crop_y
= XINT (XCAR (crop
));
8040 MagickCropImage (image_wand
, crop_width
, crop_height
,
8047 /* Furthermore :rotation. we need background color and angle for
8050 TODO background handling for rotation specified_bg =
8051 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8053 value
= image_spec_value (img
->spec
, QCrotation
, NULL
);
8056 rotation
= extract_float (value
);
8057 status
= MagickRotateImage (image_wand
, bg_wand
, rotation
);
8058 if (status
== MagickFalse
)
8060 image_error ("Imagemagick image rotate failed", Qnil
, Qnil
);
8061 imagemagick_error (image_wand
);
8062 goto imagemagick_error
;
8066 /* Set the canvas background color to the frame or specified
8067 background, and flatten the image. Note: as of ImageMagick
8068 6.6.0, SVG image transparency is not handled properly
8069 (e.g. etc/images/splash.svg shows a white background always). */
8071 MagickWand
*new_wand
;
8072 MagickSetImageBackgroundColor (image_wand
, bg_wand
);
8073 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8074 new_wand
= MagickMergeImageLayers (image_wand
, MergeLayer
);
8076 new_wand
= MagickFlattenImages (image_wand
);
8078 DestroyMagickWand (image_wand
);
8079 image_wand
= new_wand
;
8082 /* Finally we are done manipulating the image. Figure out the
8083 resulting width/height and transfer ownership to Emacs. */
8084 height
= MagickGetImageHeight (image_wand
);
8085 width
= MagickGetImageWidth (image_wand
);
8087 if (! (width
<= INT_MAX
&& height
<= INT_MAX
8088 && check_image_size (f
, width
, height
)))
8090 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
8091 goto imagemagick_error
;
8094 /* We can now get a valid pixel buffer from the imagemagick file, if all
8097 init_color_table ();
8099 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8100 if (imagemagick_render_type
!= 0)
8102 /* Magicexportimage is normally faster than pixelpushing. This
8103 method is also well tested. Some aspects of this method are
8104 ad-hoc and needs to be more researched. */
8105 int imagedepth
= 24; /*MagickGetImageDepth(image_wand);*/
8106 const char *exportdepth
= imagedepth
<= 8 ? "I" : "BGRP"; /*"RGBP";*/
8107 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8108 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, imagedepth
,
8111 #ifdef COLOR_TABLE_SUPPORT
8112 free_color_table ();
8114 image_error ("Imagemagick X bitmap allocation failure", Qnil
, Qnil
);
8115 goto imagemagick_error
;
8118 /* Oddly, the below code doesn't seem to work:*/
8119 /* switch(ximg->bitmap_unit){ */
8121 /* pixelwidth=CharPixel; */
8124 /* pixelwidth=ShortPixel; */
8127 /* pixelwidth=LongPixel; */
8131 Here im just guessing the format of the bitmap.
8132 happens to work fine for:
8135 seems about 3 times as fast as pixel pushing(not carefully measured)
8137 pixelwidth
= CharPixel
; /*??? TODO figure out*/
8138 MagickExportImagePixels (image_wand
, 0, 0, width
, height
,
8139 exportdepth
, pixelwidth
, ximg
->data
);
8142 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8144 size_t image_height
;
8146 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8147 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
8150 #ifdef COLOR_TABLE_SUPPORT
8151 free_color_table ();
8153 image_error ("Imagemagick X bitmap allocation failure", Qnil
, Qnil
);
8154 goto imagemagick_error
;
8157 /* Copy imagemagick image to x with primitive yet robust pixel
8158 pusher loop. This has been tested a lot with many different
8161 /* Copy pixels from the imagemagick image structure to the x image map. */
8162 iterator
= NewPixelIterator (image_wand
);
8165 #ifdef COLOR_TABLE_SUPPORT
8166 free_color_table ();
8168 x_destroy_x_image (ximg
);
8169 image_error ("Imagemagick pixel iterator creation failed",
8171 goto imagemagick_error
;
8174 image_height
= MagickGetImageHeight (image_wand
);
8175 for (y
= 0; y
< image_height
; y
++)
8177 pixels
= PixelGetNextIteratorRow (iterator
, &width
);
8180 for (x
= 0; x
< (long) width
; x
++)
8182 PixelGetMagickColor (pixels
[x
], &pixel
);
8183 XPutPixel (ximg
, x
, y
,
8184 lookup_rgb_color (f
,
8190 DestroyPixelIterator (iterator
);
8193 #ifdef COLOR_TABLE_SUPPORT
8194 /* Remember colors allocated for this image. */
8195 img
->colors
= colors_in_color_table (&img
->ncolors
);
8196 free_color_table ();
8197 #endif /* COLOR_TABLE_SUPPORT */
8200 img
->height
= height
;
8202 /* Put ximg into the image. */
8203 image_put_x_image (f
, img
, ximg
, 0);
8205 /* Final cleanup. image_wand should be the only resource left. */
8206 DestroyMagickWand (image_wand
);
8207 if (bg_wand
) DestroyPixelWand (bg_wand
);
8209 /* `MagickWandTerminus' terminates the imagemagick environment. */
8210 MagickWandTerminus ();
8215 DestroyMagickWand (image_wand
);
8216 if (bg_wand
) DestroyPixelWand (bg_wand
);
8218 MagickWandTerminus ();
8219 /* TODO more cleanup. */
8220 image_error ("Error parsing IMAGEMAGICK image `%s'", img
->spec
, Qnil
);
8225 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8226 successful. this function will go into the imagemagick_type structure, and
8227 the prototype thus needs to be compatible with that structure. */
8230 imagemagick_load (struct frame
*f
, struct image
*img
)
8233 Lisp_Object file_name
;
8235 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8236 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8237 if (STRINGP (file_name
))
8241 file
= x_find_image_file (file_name
);
8242 if (!STRINGP (file
))
8244 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
8247 success_p
= imagemagick_load_image (f
, img
, 0, 0, SSDATA (file
));
8249 /* Else its not a file, its a lisp object. Load the image from a
8250 lisp object rather than a file. */
8255 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8256 if (!STRINGP (data
))
8258 image_error ("Invalid image data `%s'", data
, Qnil
);
8261 success_p
= imagemagick_load_image (f
, img
, SDATA (data
),
8262 SBYTES (data
), NULL
);
8268 DEFUN ("imagemagick-types", Fimagemagick_types
, Simagemagick_types
, 0, 0, 0,
8269 doc
: /* Return a list of image types supported by ImageMagick.
8270 Each entry in this list is a symbol named after an ImageMagick format
8271 tag. See the ImageMagick manual for a list of ImageMagick formats and
8272 their descriptions (http://www.imagemagick.org/script/formats.php).
8273 You can also try the shell command: `identify -list format'.
8275 Note that ImageMagick recognizes many file-types that Emacs does not
8276 recognize as images, such as C. See `imagemagick-types-enable'
8277 and `imagemagick-types-inhibit'. */)
8280 Lisp_Object typelist
= Qnil
;
8285 Lisp_Object Qimagemagicktype
;
8287 GetExceptionInfo(&ex
);
8288 imtypes
= GetMagickList ("*", &numf
, &ex
);
8289 DestroyExceptionInfo(&ex
);
8291 for (i
= 0; i
< numf
; i
++)
8293 Qimagemagicktype
= intern (imtypes
[i
]);
8294 typelist
= Fcons (Qimagemagicktype
, typelist
);
8296 return Fnreverse (typelist
);
8299 #endif /* defined (HAVE_IMAGEMAGICK) */
8303 /***********************************************************************
8305 ***********************************************************************/
8307 #if defined (HAVE_RSVG)
8309 /* Function prototypes. */
8311 static bool svg_image_p (Lisp_Object object
);
8312 static bool svg_load (struct frame
*f
, struct image
*img
);
8314 static bool svg_load_image (struct frame
*, struct image
*,
8315 unsigned char *, ptrdiff_t);
8317 /* The symbol `svg' identifying images of this type. */
8319 static Lisp_Object Qsvg
;
8321 /* Indices of image specification fields in svg_format, below. */
8323 enum svg_keyword_index
8338 /* Vector of image_keyword structures describing the format
8339 of valid user-defined image specifications. */
8341 static const struct image_keyword svg_format
[SVG_LAST
] =
8343 {":type", IMAGE_SYMBOL_VALUE
, 1},
8344 {":data", IMAGE_STRING_VALUE
, 0},
8345 {":file", IMAGE_STRING_VALUE
, 0},
8346 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8347 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8348 {":relief", IMAGE_INTEGER_VALUE
, 0},
8349 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8350 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8351 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8352 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8355 #if defined HAVE_NTGUI && defined WINDOWSNT
8356 static bool init_svg_functions (void);
8358 #define init_svg_functions NULL
8361 /* Structure describing the image type `svg'. Its the same type of
8362 structure defined for all image formats, handled by emacs image
8363 functions. See struct image_type in dispextern.h. */
8365 static struct image_type svg_type
=
8376 /* Return true if OBJECT is a valid SVG image specification. Do
8377 this by calling parse_image_spec and supplying the keywords that
8378 identify the SVG format. */
8381 svg_image_p (Lisp_Object object
)
8383 struct image_keyword fmt
[SVG_LAST
];
8384 memcpy (fmt
, svg_format
, sizeof fmt
);
8386 if (!parse_image_spec (object
, fmt
, SVG_LAST
, Qsvg
))
8389 /* Must specify either the :data or :file keyword. */
8390 return fmt
[SVG_FILE
].count
+ fmt
[SVG_DATA
].count
== 1;
8393 #include <librsvg/rsvg.h>
8397 /* SVG library functions. */
8398 DEF_IMGLIB_FN (RsvgHandle
*, rsvg_handle_new
, (void));
8399 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions
, (RsvgHandle
*, RsvgDimensionData
*));
8400 DEF_IMGLIB_FN (gboolean
, rsvg_handle_write
, (RsvgHandle
*, const guchar
*, gsize
, GError
**));
8401 DEF_IMGLIB_FN (gboolean
, rsvg_handle_close
, (RsvgHandle
*, GError
**));
8402 DEF_IMGLIB_FN (GdkPixbuf
*, rsvg_handle_get_pixbuf
, (RsvgHandle
*));
8403 DEF_IMGLIB_FN (void *, rsvg_handle_set_size_callback
, (RsvgHandle
*, RsvgSizeFunc
, gpointer
, GDestroyNotify
));
8405 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width
, (const GdkPixbuf
*));
8406 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height
, (const GdkPixbuf
*));
8407 DEF_IMGLIB_FN (guchar
*, gdk_pixbuf_get_pixels
, (const GdkPixbuf
*));
8408 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride
, (const GdkPixbuf
*));
8409 DEF_IMGLIB_FN (GdkColorspace
, gdk_pixbuf_get_colorspace
, (const GdkPixbuf
*));
8410 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels
, (const GdkPixbuf
*));
8411 DEF_IMGLIB_FN (gboolean
, gdk_pixbuf_get_has_alpha
, (const GdkPixbuf
*));
8412 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample
, (const GdkPixbuf
*));
8414 DEF_IMGLIB_FN (void, g_type_init
, (void));
8415 DEF_IMGLIB_FN (void, g_object_unref
, (gpointer
));
8416 DEF_IMGLIB_FN (void, g_error_free
, (GError
*));
8418 Lisp_Object Qgdk_pixbuf
, Qglib
, Qgobject
;
8421 init_svg_functions (void)
8423 HMODULE library
, gdklib
, glib
, gobject
;
8425 if (!(glib
= w32_delayed_load (Qglib
))
8426 || !(gobject
= w32_delayed_load (Qgobject
))
8427 || !(gdklib
= w32_delayed_load (Qgdk_pixbuf
))
8428 || !(library
= w32_delayed_load (Qsvg
)))
8431 LOAD_IMGLIB_FN (library
, rsvg_handle_new
);
8432 LOAD_IMGLIB_FN (library
, rsvg_handle_get_dimensions
);
8433 LOAD_IMGLIB_FN (library
, rsvg_handle_write
);
8434 LOAD_IMGLIB_FN (library
, rsvg_handle_close
);
8435 LOAD_IMGLIB_FN (library
, rsvg_handle_get_pixbuf
);
8437 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_width
);
8438 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_height
);
8439 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_pixels
);
8440 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_rowstride
);
8441 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_colorspace
);
8442 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_n_channels
);
8443 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_has_alpha
);
8444 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_bits_per_sample
);
8446 LOAD_IMGLIB_FN (gobject
, g_type_init
);
8447 LOAD_IMGLIB_FN (gobject
, g_object_unref
);
8448 LOAD_IMGLIB_FN (glib
, g_error_free
);
8454 /* The following aliases for library functions allow dynamic loading
8455 to be used on some platforms. */
8456 #define fn_rsvg_handle_new rsvg_handle_new
8457 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8458 #define fn_rsvg_handle_write rsvg_handle_write
8459 #define fn_rsvg_handle_close rsvg_handle_close
8460 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8462 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8463 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8464 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8465 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8466 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8467 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8468 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8469 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8471 #define fn_g_type_init g_type_init
8472 #define fn_g_object_unref g_object_unref
8473 #define fn_g_error_free g_error_free
8474 #endif /* !WINDOWSNT */
8476 /* Load SVG image IMG for use on frame F. Value is true if
8480 svg_load (struct frame
*f
, struct image
*img
)
8483 Lisp_Object file_name
;
8485 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8486 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8487 if (STRINGP (file_name
))
8490 unsigned char *contents
;
8493 file
= x_find_image_file (file_name
);
8494 if (!STRINGP (file
))
8496 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
8500 /* Read the entire file into memory. */
8501 contents
= slurp_file (SSDATA (file
), &size
);
8502 if (contents
== NULL
)
8504 image_error ("Error loading SVG image `%s'", img
->spec
, Qnil
);
8507 /* If the file was slurped into memory properly, parse it. */
8508 success_p
= svg_load_image (f
, img
, contents
, size
);
8511 /* Else its not a file, its a lisp object. Load the image from a
8512 lisp object rather than a file. */
8517 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8518 if (!STRINGP (data
))
8520 image_error ("Invalid image data `%s'", data
, Qnil
);
8523 success_p
= svg_load_image (f
, img
, SDATA (data
), SBYTES (data
));
8529 /* svg_load_image is a helper function for svg_load, which does the
8530 actual loading given contents and size, apart from frame and image
8531 structures, passed from svg_load.
8533 Uses librsvg to do most of the image processing.
8535 Returns true when successful. */
8537 svg_load_image (struct frame
*f
, /* Pointer to emacs frame structure. */
8538 struct image
*img
, /* Pointer to emacs image structure. */
8539 unsigned char *contents
, /* String containing the SVG XML data to be parsed. */
8540 ptrdiff_t size
) /* Size of data in bytes. */
8542 RsvgHandle
*rsvg_handle
;
8543 RsvgDimensionData dimension_data
;
8548 const guint8
*pixels
;
8551 Lisp_Object specified_bg
;
8556 /* g_type_init is a glib function that must be called prior to using
8557 gnome type library functions. */
8559 /* Make a handle to a new rsvg object. */
8560 rsvg_handle
= fn_rsvg_handle_new ();
8562 /* Parse the contents argument and fill in the rsvg_handle. */
8563 fn_rsvg_handle_write (rsvg_handle
, contents
, size
, &err
);
8564 if (err
) goto rsvg_error
;
8566 /* The parsing is complete, rsvg_handle is ready to used, close it
8567 for further writes. */
8568 fn_rsvg_handle_close (rsvg_handle
, &err
);
8569 if (err
) goto rsvg_error
;
8571 fn_rsvg_handle_get_dimensions (rsvg_handle
, &dimension_data
);
8572 if (! check_image_size (f
, dimension_data
.width
, dimension_data
.height
))
8574 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
8578 /* We can now get a valid pixel buffer from the svg file, if all
8580 pixbuf
= fn_rsvg_handle_get_pixbuf (rsvg_handle
);
8581 if (!pixbuf
) goto rsvg_error
;
8582 fn_g_object_unref (rsvg_handle
);
8584 /* Extract some meta data from the svg handle. */
8585 width
= fn_gdk_pixbuf_get_width (pixbuf
);
8586 height
= fn_gdk_pixbuf_get_height (pixbuf
);
8587 pixels
= fn_gdk_pixbuf_get_pixels (pixbuf
);
8588 rowstride
= fn_gdk_pixbuf_get_rowstride (pixbuf
);
8590 /* Validate the svg meta data. */
8591 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf
) == GDK_COLORSPACE_RGB
);
8592 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf
) == 4);
8593 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf
));
8594 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf
) == 8);
8596 /* Try to create a x pixmap to hold the svg pixmap. */
8597 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
8599 fn_g_object_unref (pixbuf
);
8603 init_color_table ();
8605 /* Handle alpha channel by combining the image with a background
8607 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8608 if (!STRINGP (specified_bg
)
8609 || !x_defined_color (f
, SSDATA (specified_bg
), &background
, 0))
8612 background
.pixel
= FRAME_BACKGROUND_PIXEL (f
);
8613 x_query_color (f
, &background
);
8615 ns_query_color (FRAME_BACKGROUND_COLOR (f
), &background
, 1);
8619 /* SVG pixmaps specify transparency in the last byte, so right
8620 shift 8 bits to get rid of it, since emacs doesn't support
8622 background
.red
>>= 8;
8623 background
.green
>>= 8;
8624 background
.blue
>>= 8;
8626 /* This loop handles opacity values, since Emacs assumes
8627 non-transparent images. Each pixel must be "flattened" by
8628 calculating the resulting color, given the transparency of the
8629 pixel, and the image background color. */
8630 for (y
= 0; y
< height
; ++y
)
8632 for (x
= 0; x
< width
; ++x
)
8642 opacity
= *pixels
++;
8644 red
= ((red
* opacity
)
8645 + (background
.red
* ((1 << 8) - opacity
)));
8646 green
= ((green
* opacity
)
8647 + (background
.green
* ((1 << 8) - opacity
)));
8648 blue
= ((blue
* opacity
)
8649 + (background
.blue
* ((1 << 8) - opacity
)));
8651 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, red
, green
, blue
));
8654 pixels
+= rowstride
- 4 * width
;
8657 #ifdef COLOR_TABLE_SUPPORT
8658 /* Remember colors allocated for this image. */
8659 img
->colors
= colors_in_color_table (&img
->ncolors
);
8660 free_color_table ();
8661 #endif /* COLOR_TABLE_SUPPORT */
8663 fn_g_object_unref (pixbuf
);
8666 img
->height
= height
;
8668 /* Maybe fill in the background field while we have ximg handy.
8669 Casting avoids a GCC warning. */
8670 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
8672 /* Put ximg into the image. */
8673 image_put_x_image (f
, img
, ximg
, 0);
8678 fn_g_object_unref (rsvg_handle
);
8679 /* FIXME: Use error->message so the user knows what is the actual
8680 problem with the image. */
8681 image_error ("Error parsing SVG image `%s'", img
->spec
, Qnil
);
8682 fn_g_error_free (err
);
8686 #endif /* defined (HAVE_RSVG) */
8691 /***********************************************************************
8693 ***********************************************************************/
8695 #ifdef HAVE_X_WINDOWS
8696 #define HAVE_GHOSTSCRIPT 1
8697 #endif /* HAVE_X_WINDOWS */
8699 #ifdef HAVE_GHOSTSCRIPT
8701 static bool gs_image_p (Lisp_Object object
);
8702 static bool gs_load (struct frame
*f
, struct image
*img
);
8703 static void gs_clear_image (struct frame
*f
, struct image
*img
);
8705 /* Keyword symbols. */
8707 static Lisp_Object QCloader
, QCbounding_box
, QCpt_width
, QCpt_height
;
8709 /* Indices of image specification fields in gs_format, below. */
8711 enum gs_keyword_index
8729 /* Vector of image_keyword structures describing the format
8730 of valid user-defined image specifications. */
8732 static const struct image_keyword gs_format
[GS_LAST
] =
8734 {":type", IMAGE_SYMBOL_VALUE
, 1},
8735 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
8736 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
8737 {":file", IMAGE_STRING_VALUE
, 1},
8738 {":loader", IMAGE_FUNCTION_VALUE
, 0},
8739 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE
, 1},
8740 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8741 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8742 {":relief", IMAGE_INTEGER_VALUE
, 0},
8743 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8744 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8745 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8746 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8749 /* Structure describing the image type `ghostscript'. */
8751 static struct image_type gs_type
=
8762 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8765 gs_clear_image (struct frame
*f
, struct image
*img
)
8767 x_clear_image (f
, img
);
8771 /* Return true if OBJECT is a valid Ghostscript image
8775 gs_image_p (Lisp_Object object
)
8777 struct image_keyword fmt
[GS_LAST
];
8781 memcpy (fmt
, gs_format
, sizeof fmt
);
8783 if (!parse_image_spec (object
, fmt
, GS_LAST
, Qpostscript
))
8786 /* Bounding box must be a list or vector containing 4 integers. */
8787 tem
= fmt
[GS_BOUNDING_BOX
].value
;
8790 for (i
= 0; i
< 4; ++i
, tem
= XCDR (tem
))
8791 if (!CONSP (tem
) || !INTEGERP (XCAR (tem
)))
8796 else if (VECTORP (tem
))
8798 if (ASIZE (tem
) != 4)
8800 for (i
= 0; i
< 4; ++i
)
8801 if (!INTEGERP (AREF (tem
, i
)))
8811 /* Load Ghostscript image IMG for use on frame F. Value is true
8815 gs_load (struct frame
*f
, struct image
*img
)
8817 uprintmax_t printnum1
, printnum2
;
8818 char buffer
[sizeof " " + INT_STRLEN_BOUND (printmax_t
)];
8819 Lisp_Object window_and_pixmap_id
= Qnil
, loader
, pt_height
, pt_width
;
8821 double in_width
, in_height
;
8822 Lisp_Object pixel_colors
= Qnil
;
8824 /* Compute pixel size of pixmap needed from the given size in the
8825 image specification. Sizes in the specification are in pt. 1 pt
8826 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8828 pt_width
= image_spec_value (img
->spec
, QCpt_width
, NULL
);
8829 in_width
= INTEGERP (pt_width
) ? XFASTINT (pt_width
) / 72.0 : 0;
8830 in_width
*= FRAME_RES_X (f
);
8831 pt_height
= image_spec_value (img
->spec
, QCpt_height
, NULL
);
8832 in_height
= INTEGERP (pt_height
) ? XFASTINT (pt_height
) / 72.0 : 0;
8833 in_height
*= FRAME_RES_Y (f
);
8835 if (! (in_width
<= INT_MAX
&& in_height
<= INT_MAX
8836 && check_image_size (f
, in_width
, in_height
)))
8838 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
8841 img
->width
= in_width
;
8842 img
->height
= in_height
;
8844 /* Create the pixmap. */
8845 eassert (img
->pixmap
== NO_PIXMAP
);
8847 if (x_check_image_size (0, img
->width
, img
->height
))
8849 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8851 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
8852 img
->width
, img
->height
,
8853 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)));
8859 image_error ("Unable to create pixmap for `%s'", img
->spec
, Qnil
);
8863 /* Call the loader to fill the pixmap. It returns a process object
8864 if successful. We do not record_unwind_protect here because
8865 other places in redisplay like calling window scroll functions
8866 don't either. Let the Lisp loader use `unwind-protect' instead. */
8867 printnum1
= FRAME_X_WINDOW (f
);
8868 printnum2
= img
->pixmap
;
8869 window_and_pixmap_id
8870 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
8872 printnum1
= FRAME_FOREGROUND_PIXEL (f
);
8873 printnum2
= FRAME_BACKGROUND_PIXEL (f
);
8875 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
8877 XSETFRAME (frame
, f
);
8878 loader
= image_spec_value (img
->spec
, QCloader
, NULL
);
8880 loader
= intern ("gs-load-image");
8882 img
->lisp_data
= call6 (loader
, frame
, img
->spec
,
8883 make_number (img
->width
),
8884 make_number (img
->height
),
8885 window_and_pixmap_id
,
8887 return PROCESSP (img
->lisp_data
);
8891 /* Kill the Ghostscript process that was started to fill PIXMAP on
8892 frame F. Called from XTread_socket when receiving an event
8893 telling Emacs that Ghostscript has finished drawing. */
8896 x_kill_gs_process (Pixmap pixmap
, struct frame
*f
)
8898 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
8903 /* Find the image containing PIXMAP. */
8904 for (i
= 0; i
< c
->used
; ++i
)
8905 if (c
->images
[i
]->pixmap
== pixmap
)
8908 /* Should someone in between have cleared the image cache, for
8909 instance, give up. */
8913 /* Kill the GS process. We should have found PIXMAP in the image
8914 cache and its image should contain a process object. */
8916 eassert (PROCESSP (img
->lisp_data
));
8917 Fkill_process (img
->lisp_data
, Qnil
);
8918 img
->lisp_data
= Qnil
;
8920 #if defined (HAVE_X_WINDOWS)
8922 /* On displays with a mutable colormap, figure out the colors
8923 allocated for the image by looking at the pixels of an XImage for
8925 class = FRAME_X_VISUAL (f
)->class;
8926 if (class != StaticColor
&& class != StaticGray
&& class != TrueColor
)
8932 /* Try to get an XImage for img->pixmep. */
8933 ximg
= XGetImage (FRAME_X_DISPLAY (f
), img
->pixmap
,
8934 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
8939 /* Initialize the color table. */
8940 init_color_table ();
8942 /* For each pixel of the image, look its color up in the
8943 color table. After having done so, the color table will
8944 contain an entry for each color used by the image. */
8945 for (y
= 0; y
< img
->height
; ++y
)
8946 for (x
= 0; x
< img
->width
; ++x
)
8948 unsigned long pixel
= XGetPixel (ximg
, x
, y
);
8949 lookup_pixel_color (f
, pixel
);
8952 /* Record colors in the image. Free color table and XImage. */
8953 #ifdef COLOR_TABLE_SUPPORT
8954 img
->colors
= colors_in_color_table (&img
->ncolors
);
8955 free_color_table ();
8957 XDestroyImage (ximg
);
8959 #if 0 /* This doesn't seem to be the case. If we free the colors
8960 here, we get a BadAccess later in x_clear_image when
8961 freeing the colors. */
8962 /* We have allocated colors once, but Ghostscript has also
8963 allocated colors on behalf of us. So, to get the
8964 reference counts right, free them once. */
8966 x_free_colors (f
, img
->colors
, img
->ncolors
);
8970 image_error ("Cannot get X image of `%s'; colors will not be freed",
8975 #endif /* HAVE_X_WINDOWS */
8977 /* Now that we have the pixmap, compute mask and transform the
8978 image if requested. */
8980 postprocess_image (f
, img
);
8984 #endif /* HAVE_GHOSTSCRIPT */
8987 /***********************************************************************
8989 ***********************************************************************/
8993 DEFUN ("imagep", Fimagep
, Simagep
, 1, 1, 0,
8994 doc
: /* Value is non-nil if SPEC is a valid image specification. */)
8997 return valid_image_p (spec
) ? Qt
: Qnil
;
9001 DEFUN ("lookup-image", Flookup_image
, Slookup_image
, 1, 1, 0, "")
9006 if (valid_image_p (spec
))
9007 id
= lookup_image (SELECTED_FRAME (), spec
);
9010 return make_number (id
);
9013 #endif /* GLYPH_DEBUG */
9016 /***********************************************************************
9018 ***********************************************************************/
9020 DEFUN ("init-image-library", Finit_image_library
, Sinit_image_library
, 1, 1, 0,
9021 doc
: /* Initialize image library implementing image type TYPE.
9022 Return non-nil if TYPE is a supported image type.
9024 If image libraries are loaded dynamically (currently only the case on
9025 MS-Windows), load the library for TYPE if it is not yet loaded, using
9026 the library file(s) specified by `dynamic-library-alist'. */)
9029 return lookup_image_type (type
) ? Qt
: Qnil
;
9032 /* Look up image type TYPE, and return a pointer to its image_type
9033 structure. Return 0 if TYPE is not a known image type. */
9035 static struct image_type
*
9036 lookup_image_type (Lisp_Object type
)
9038 /* Types pbm and xbm are built-in and always available. */
9039 if (EQ (type
, Qpbm
))
9040 return define_image_type (&pbm_type
);
9042 if (EQ (type
, Qxbm
))
9043 return define_image_type (&xbm_type
);
9045 #if defined (HAVE_XPM) || defined (HAVE_NS)
9046 if (EQ (type
, Qxpm
))
9047 return define_image_type (&xpm_type
);
9050 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9051 if (EQ (type
, Qjpeg
))
9052 return define_image_type (&jpeg_type
);
9055 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9056 if (EQ (type
, Qtiff
))
9057 return define_image_type (&tiff_type
);
9060 #if defined (HAVE_GIF) || defined (HAVE_NS)
9061 if (EQ (type
, Qgif
))
9062 return define_image_type (&gif_type
);
9065 #if defined (HAVE_PNG) || defined (HAVE_NS)
9066 if (EQ (type
, Qpng
))
9067 return define_image_type (&png_type
);
9070 #if defined (HAVE_RSVG)
9071 if (EQ (type
, Qsvg
))
9072 return define_image_type (&svg_type
);
9075 #if defined (HAVE_IMAGEMAGICK)
9076 if (EQ (type
, Qimagemagick
))
9077 return define_image_type (&imagemagick_type
);
9080 #ifdef HAVE_GHOSTSCRIPT
9081 if (EQ (type
, Qpostscript
))
9082 return define_image_type (&gs_type
);
9088 /* Reset image_types before dumping.
9089 Called from Fdump_emacs. */
9092 reset_image_types (void)
9096 struct image_type
*next
= image_types
->next
;
9097 xfree (image_types
);
9103 syms_of_image (void)
9105 /* Initialize this only once; it will be reset before dumping. */
9108 /* Must be defined now because we're going to update it below, while
9109 defining the supported image types. */
9110 DEFVAR_LISP ("image-types", Vimage_types
,
9111 doc
: /* List of potentially supported image types.
9112 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9113 To check whether it is really supported, use `image-type-available-p'. */);
9114 Vimage_types
= Qnil
;
9116 DEFVAR_LISP ("max-image-size", Vmax_image_size
,
9117 doc
: /* Maximum size of images.
9118 Emacs will not load an image into memory if its pixel width or
9119 pixel height exceeds this limit.
9121 If the value is an integer, it directly specifies the maximum
9122 image height and width, measured in pixels. If it is a floating
9123 point number, it specifies the maximum image height and width
9124 as a ratio to the frame height and width. If the value is
9125 non-numeric, there is no explicit limit on the size of images. */);
9126 Vmax_image_size
= make_float (MAX_IMAGE_SIZE
);
9128 DEFSYM (Qcount
, "count");
9129 DEFSYM (Qextension_data
, "extension-data");
9130 DEFSYM (Qdelay
, "delay");
9132 DEFSYM (QCascent
, ":ascent");
9133 DEFSYM (QCmargin
, ":margin");
9134 DEFSYM (QCrelief
, ":relief");
9135 DEFSYM (QCconversion
, ":conversion");
9136 DEFSYM (QCcolor_symbols
, ":color-symbols");
9137 DEFSYM (QCheuristic_mask
, ":heuristic-mask");
9138 DEFSYM (QCindex
, ":index");
9139 DEFSYM (QCgeometry
, ":geometry");
9140 DEFSYM (QCcrop
, ":crop");
9141 DEFSYM (QCrotation
, ":rotation");
9142 DEFSYM (QCmatrix
, ":matrix");
9143 DEFSYM (QCcolor_adjustment
, ":color-adjustment");
9144 DEFSYM (QCmask
, ":mask");
9146 DEFSYM (Qlaplace
, "laplace");
9147 DEFSYM (Qemboss
, "emboss");
9148 DEFSYM (Qedge_detection
, "edge-detection");
9149 DEFSYM (Qheuristic
, "heuristic");
9151 DEFSYM (Qpostscript
, "postscript");
9152 DEFSYM (QCmax_width
, ":max-width");
9153 DEFSYM (QCmax_height
, ":max-height");
9154 #ifdef HAVE_GHOSTSCRIPT
9155 ADD_IMAGE_TYPE (Qpostscript
);
9156 DEFSYM (QCloader
, ":loader");
9157 DEFSYM (QCbounding_box
, ":bounding-box");
9158 DEFSYM (QCpt_width
, ":pt-width");
9159 DEFSYM (QCpt_height
, ":pt-height");
9160 #endif /* HAVE_GHOSTSCRIPT */
9163 DEFSYM (Qlibpng_version
, "libpng-version");
9164 Fset (Qlibpng_version
,
9166 make_number (PNG_LIBPNG_VER
)
9173 DEFSYM (Qpbm
, "pbm");
9174 ADD_IMAGE_TYPE (Qpbm
);
9176 DEFSYM (Qxbm
, "xbm");
9177 ADD_IMAGE_TYPE (Qxbm
);
9179 #if defined (HAVE_XPM) || defined (HAVE_NS)
9180 DEFSYM (Qxpm
, "xpm");
9181 ADD_IMAGE_TYPE (Qxpm
);
9184 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9185 DEFSYM (Qjpeg
, "jpeg");
9186 ADD_IMAGE_TYPE (Qjpeg
);
9189 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9190 DEFSYM (Qtiff
, "tiff");
9191 ADD_IMAGE_TYPE (Qtiff
);
9194 #if defined (HAVE_GIF) || defined (HAVE_NS)
9195 DEFSYM (Qgif
, "gif");
9196 ADD_IMAGE_TYPE (Qgif
);
9199 #if defined (HAVE_PNG) || defined (HAVE_NS)
9200 DEFSYM (Qpng
, "png");
9201 ADD_IMAGE_TYPE (Qpng
);
9204 #if defined (HAVE_IMAGEMAGICK)
9205 DEFSYM (Qimagemagick
, "imagemagick");
9206 ADD_IMAGE_TYPE (Qimagemagick
);
9209 #if defined (HAVE_RSVG)
9210 DEFSYM (Qsvg
, "svg");
9211 ADD_IMAGE_TYPE (Qsvg
);
9213 /* Other libraries used directly by svg code. */
9214 DEFSYM (Qgdk_pixbuf
, "gdk-pixbuf");
9215 DEFSYM (Qglib
, "glib");
9216 DEFSYM (Qgobject
, "gobject");
9217 #endif /* HAVE_NTGUI */
9218 #endif /* HAVE_RSVG */
9220 defsubr (&Sinit_image_library
);
9221 #ifdef HAVE_IMAGEMAGICK
9222 defsubr (&Simagemagick_types
);
9224 defsubr (&Sclear_image_cache
);
9225 defsubr (&Simage_flush
);
9226 defsubr (&Simage_size
);
9227 defsubr (&Simage_mask_p
);
9228 defsubr (&Simage_metadata
);
9232 defsubr (&Slookup_image
);
9235 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images
,
9236 doc
: /* Non-nil means always draw a cross over disabled images.
9237 Disabled images are those having a `:conversion disabled' property.
9238 A cross is always drawn on black & white displays. */);
9239 cross_disabled_images
= 0;
9241 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path
,
9242 doc
: /* List of directories to search for window system bitmap files. */);
9243 Vx_bitmap_file_path
= decode_env_path (0, PATH_BITMAPS
);
9245 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay
,
9246 doc
: /* Maximum time after which images are removed from the cache.
9247 When an image has not been displayed this many seconds, Emacs
9248 automatically removes it from the image cache. If the cache contains
9249 a large number of images, the actual eviction time may be shorter.
9250 The value can also be nil, meaning the cache is never cleared.
9252 The function `clear-image-cache' disregards this variable. */);
9253 Vimage_cache_eviction_delay
= make_number (300);
9254 #ifdef HAVE_IMAGEMAGICK
9255 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type
,
9256 doc
: /* Integer indicating which ImageMagick rendering method to use.
9258 0 -- the default method (pixel pushing)
9259 1 -- a newer method ("MagickExportImagePixels") that may perform
9260 better (speed etc) in some cases, but has not been as thoroughly
9261 tested with Emacs as the default method. This method requires
9262 ImageMagick version 6.4.6 (approximately) or later.
9264 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9265 imagemagick_render_type
= 0;