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>
38 #include "dispextern.h"
39 #include "blockinput.h"
42 #include "character.h"
44 #include "termhooks.h"
47 #ifdef HAVE_SYS_STAT_H
49 #endif /* HAVE_SYS_STAT_H */
51 #ifdef HAVE_SYS_TYPES_H
52 #include <sys/types.h>
53 #endif /* HAVE_SYS_TYPES_H */
55 #ifdef HAVE_WINDOW_SYSTEM
57 #endif /* HAVE_WINDOW_SYSTEM */
60 #define COLOR_TABLE_SUPPORT 1
62 typedef struct x_bitmap_record Bitmap_Record
;
63 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
64 #define NO_PIXMAP None
66 #define PIX_MASK_RETAIN 0
67 #define PIX_MASK_DRAW 1
68 #endif /* HAVE_X_WINDOWS */
72 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
77 /* W32_TODO : Color tables on W32. */
78 #undef COLOR_TABLE_SUPPORT
80 typedef struct w32_bitmap_record Bitmap_Record
;
81 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
84 #define PIX_MASK_RETAIN 0
85 #define PIX_MASK_DRAW 1
87 #define x_defined_color w32_defined_color
88 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
90 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
91 or -1 if no PNG/GIF support was compiled in. This is tested by
92 w32-win.el to correctly set up the alist used to search for the
93 respective image libraries. */
94 Lisp_Object Qlibpng_version
, Qlibgif_version
, Qlibjpeg_version
;
96 #endif /* HAVE_NTGUI */
99 #undef COLOR_TABLE_SUPPORT
101 typedef struct ns_bitmap_record Bitmap_Record
;
103 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
106 #define PIX_MASK_RETAIN 0
107 #define PIX_MASK_DRAW 1
109 #define x_defined_color(f, name, color_def, alloc) \
110 ns_defined_color (f, name, color_def, alloc, 0)
111 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
115 /* The symbol `postscript' identifying images of this type. */
117 static Lisp_Object Qpostscript
;
119 static void x_disable_image (struct frame
*, struct image
*);
120 static void x_edge_detection (struct frame
*, struct image
*, Lisp_Object
,
123 static void init_color_table (void);
124 static unsigned long lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
);
125 #ifdef COLOR_TABLE_SUPPORT
126 static void free_color_table (void);
127 static unsigned long *colors_in_color_table (int *n
);
130 static Lisp_Object QCmax_width
, QCmax_height
;
132 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
133 id, which is just an int that this section returns. Bitmaps are
134 reference counted so they can be shared among frames.
136 Bitmap indices are guaranteed to be > 0, so a negative number can
137 be used to indicate no bitmap.
139 If you use x_create_bitmap_from_data, then you must keep track of
140 the bitmaps yourself. That is, creating a bitmap from the same
141 data more than once will not be caught. */
144 /* Use with images created by ns_image_for_XPM. */
146 XGetPixel (XImagePtr ximage
, int x
, int y
)
148 return ns_get_pixel (ximage
, x
, y
);
151 /* Use with images created by ns_image_for_XPM; alpha set to 1;
152 pixel is assumed to be in RGB form. */
154 XPutPixel (XImagePtr ximage
, int x
, int y
, unsigned long pixel
)
156 ns_put_pixel (ximage
, x
, y
, pixel
);
161 /* Functions to access the contents of a bitmap, given an id. */
164 x_bitmap_height (struct frame
*f
, ptrdiff_t id
)
166 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].height
;
170 x_bitmap_width (struct frame
*f
, ptrdiff_t id
)
172 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].width
;
175 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
177 x_bitmap_pixmap (struct frame
*f
, ptrdiff_t id
)
179 /* HAVE_NTGUI needs the explicit cast here. */
180 return (ptrdiff_t) FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].pixmap
;
184 #ifdef HAVE_X_WINDOWS
186 x_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
188 return FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].mask
;
192 /* Allocate a new bitmap record. Returns index of new record. */
195 x_allocate_bitmap_record (struct frame
*f
)
197 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
200 if (dpyinfo
->bitmaps_last
< dpyinfo
->bitmaps_size
)
201 return ++dpyinfo
->bitmaps_last
;
203 for (i
= 0; i
< dpyinfo
->bitmaps_size
; ++i
)
204 if (dpyinfo
->bitmaps
[i
].refcount
== 0)
208 xpalloc (dpyinfo
->bitmaps
, &dpyinfo
->bitmaps_size
,
209 10, -1, sizeof *dpyinfo
->bitmaps
);
210 return ++dpyinfo
->bitmaps_last
;
213 /* Add one reference to the reference count of the bitmap with id ID. */
216 x_reference_bitmap (struct frame
*f
, ptrdiff_t id
)
218 ++FRAME_DISPLAY_INFO (f
)->bitmaps
[id
- 1].refcount
;
221 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
224 x_create_bitmap_from_data (struct frame
*f
, char *bits
, unsigned int width
, unsigned int height
)
226 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
229 #ifdef HAVE_X_WINDOWS
231 bitmap
= XCreateBitmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
232 bits
, width
, height
);
235 #endif /* HAVE_X_WINDOWS */
239 bitmap
= CreateBitmap (width
, height
,
240 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_planes
,
241 FRAME_DISPLAY_INFO (XFRAME (frame
))->n_cbits
,
245 #endif /* HAVE_NTGUI */
248 void *bitmap
= ns_image_from_XBM (bits
, width
, height
);
253 id
= x_allocate_bitmap_record (f
);
256 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
257 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
260 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
261 dpyinfo
->bitmaps
[id
- 1].height
= height
;
262 dpyinfo
->bitmaps
[id
- 1].width
= width
;
263 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
265 #ifdef HAVE_X_WINDOWS
266 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
267 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
268 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
269 #endif /* HAVE_X_WINDOWS */
272 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
273 dpyinfo
->bitmaps
[id
- 1].hinst
= NULL
;
274 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
275 #endif /* HAVE_NTGUI */
280 /* Create bitmap from file FILE for frame F. */
283 x_create_bitmap_from_file (struct frame
*f
, Lisp_Object file
)
285 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
288 return -1; /* W32_TODO : bitmap support */
289 #endif /* HAVE_NTGUI */
293 void *bitmap
= ns_image_from_file (file
);
299 id
= x_allocate_bitmap_record (f
);
300 dpyinfo
->bitmaps
[id
- 1].img
= bitmap
;
301 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
302 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
303 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
304 dpyinfo
->bitmaps
[id
- 1].height
= ns_image_width (bitmap
);
305 dpyinfo
->bitmaps
[id
- 1].width
= ns_image_height (bitmap
);
309 #ifdef HAVE_X_WINDOWS
310 unsigned int width
, height
;
312 int xhot
, yhot
, result
;
317 /* Look for an existing bitmap with the same name. */
318 for (id
= 0; id
< dpyinfo
->bitmaps_last
; ++id
)
320 if (dpyinfo
->bitmaps
[id
].refcount
321 && dpyinfo
->bitmaps
[id
].file
322 && !strcmp (dpyinfo
->bitmaps
[id
].file
, SSDATA (file
)))
324 ++dpyinfo
->bitmaps
[id
].refcount
;
329 /* Search bitmap-file-path for the file, if appropriate. */
330 if (openp (Vx_bitmap_file_path
, file
, Qnil
, &found
, make_number (R_OK
), 0) < 0)
333 filename
= SSDATA (found
);
335 result
= XReadBitmapFile (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
336 filename
, &width
, &height
, &bitmap
, &xhot
, &yhot
);
337 if (result
!= BitmapSuccess
)
340 id
= x_allocate_bitmap_record (f
);
341 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
342 dpyinfo
->bitmaps
[id
- 1].have_mask
= false;
343 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
344 dpyinfo
->bitmaps
[id
- 1].file
= xlispstrdup (file
);
345 dpyinfo
->bitmaps
[id
- 1].depth
= 1;
346 dpyinfo
->bitmaps
[id
- 1].height
= height
;
347 dpyinfo
->bitmaps
[id
- 1].width
= width
;
350 #endif /* HAVE_X_WINDOWS */
356 free_bitmap_record (Display_Info
*dpyinfo
, Bitmap_Record
*bm
)
358 #ifdef HAVE_X_WINDOWS
359 XFreePixmap (dpyinfo
->display
, bm
->pixmap
);
361 XFreePixmap (dpyinfo
->display
, bm
->mask
);
362 #endif /* HAVE_X_WINDOWS */
365 DeleteObject (bm
->pixmap
);
366 #endif /* HAVE_NTGUI */
369 ns_release_object (bm
->img
);
379 /* Remove reference to bitmap with id number ID. */
382 x_destroy_bitmap (struct frame
*f
, ptrdiff_t id
)
384 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
388 Bitmap_Record
*bm
= &dpyinfo
->bitmaps
[id
- 1];
390 if (--bm
->refcount
== 0)
393 free_bitmap_record (dpyinfo
, bm
);
399 /* Free all the bitmaps for the display specified by DPYINFO. */
402 x_destroy_all_bitmaps (Display_Info
*dpyinfo
)
405 Bitmap_Record
*bm
= dpyinfo
->bitmaps
;
407 for (i
= 0; i
< dpyinfo
->bitmaps_last
; i
++, bm
++)
408 if (bm
->refcount
> 0)
409 free_bitmap_record (dpyinfo
, bm
);
411 dpyinfo
->bitmaps_last
= 0;
414 static bool x_create_x_image_and_pixmap (struct frame
*, int, int, int,
415 XImagePtr
*, Pixmap
*);
416 static void x_destroy_x_image (XImagePtr ximg
);
419 static XImagePtr_or_DC
image_get_x_image_or_dc (struct frame
*, struct image
*,
421 static void image_unget_x_image_or_dc (struct image
*, bool, XImagePtr_or_DC
,
424 static XImagePtr
image_get_x_image (struct frame
*, struct image
*, bool);
425 static void image_unget_x_image (struct image
*, bool, XImagePtr
);
426 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
427 image_get_x_image (f, img, mask_p)
428 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
429 image_unget_x_image (img, mask_p, ximg)
432 #ifdef HAVE_X_WINDOWS
434 static void image_sync_to_pixmaps (struct frame
*, struct image
*);
436 /* Useful functions defined in the section
437 `Image type independent image structures' below. */
439 static unsigned long four_corners_best (XImagePtr ximg
,
442 unsigned long height
);
445 /* Create a mask of a bitmap. Note is this not a perfect mask.
446 It's nicer with some borders in this context */
449 x_create_bitmap_mask (struct frame
*f
, ptrdiff_t id
)
452 XImagePtr ximg
, mask_img
;
453 unsigned long width
, height
;
456 unsigned long x
, y
, xp
, xm
, yp
, ym
;
459 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
464 pixmap
= x_bitmap_pixmap (f
, id
);
465 width
= x_bitmap_width (f
, id
);
466 height
= x_bitmap_height (f
, id
);
469 ximg
= XGetImage (FRAME_X_DISPLAY (f
), pixmap
, 0, 0, width
, height
,
478 result
= x_create_x_image_and_pixmap (f
, width
, height
, 1, &mask_img
, &mask
);
483 XDestroyImage (ximg
);
487 bg
= four_corners_best (ximg
, NULL
, width
, height
);
489 for (y
= 0; y
< ximg
->height
; ++y
)
491 for (x
= 0; x
< ximg
->width
; ++x
)
493 xp
= x
!= ximg
->width
- 1 ? x
+ 1 : 0;
494 xm
= x
!= 0 ? x
- 1 : ximg
->width
- 1;
495 yp
= y
!= ximg
->height
- 1 ? y
+ 1 : 0;
496 ym
= y
!= 0 ? y
- 1 : ximg
->height
- 1;
497 if (XGetPixel (ximg
, x
, y
) == bg
498 && XGetPixel (ximg
, x
, yp
) == bg
499 && XGetPixel (ximg
, x
, ym
) == bg
500 && XGetPixel (ximg
, xp
, y
) == bg
501 && XGetPixel (ximg
, xp
, yp
) == bg
502 && XGetPixel (ximg
, xp
, ym
) == bg
503 && XGetPixel (ximg
, xm
, y
) == bg
504 && XGetPixel (ximg
, xm
, yp
) == bg
505 && XGetPixel (ximg
, xm
, ym
) == bg
)
506 XPutPixel (mask_img
, x
, y
, 0);
508 XPutPixel (mask_img
, x
, y
, 1);
512 eassert (input_blocked_p ());
513 gc
= XCreateGC (FRAME_X_DISPLAY (f
), mask
, 0, NULL
);
514 XPutImage (FRAME_X_DISPLAY (f
), mask
, gc
, mask_img
, 0, 0, 0, 0,
516 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
518 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
519 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
521 XDestroyImage (ximg
);
522 x_destroy_x_image (mask_img
);
525 #endif /* HAVE_X_WINDOWS */
528 /***********************************************************************
530 ***********************************************************************/
532 /* List of supported image types. Use define_image_type to add new
533 types. Use lookup_image_type to find a type for a given symbol. */
535 static struct image_type
*image_types
;
537 /* The symbol `xbm' which is used as the type symbol for XBM images. */
539 static Lisp_Object Qxbm
;
543 Lisp_Object QCascent
, QCmargin
, QCrelief
;
544 Lisp_Object QCconversion
;
545 static Lisp_Object QCheuristic_mask
;
546 static Lisp_Object QCcolor_symbols
;
547 static Lisp_Object QCindex
, QCmatrix
, QCcolor_adjustment
, QCmask
, QCgeometry
;
548 static Lisp_Object QCcrop
, QCrotation
;
552 static Lisp_Object Qcount
, Qextension_data
, Qdelay
;
553 static Lisp_Object Qlaplace
, Qemboss
, Qedge_detection
, Qheuristic
;
555 /* Forward function prototypes. */
557 static struct image_type
*lookup_image_type (Lisp_Object
);
558 static void x_laplace (struct frame
*, struct image
*);
559 static void x_emboss (struct frame
*, struct image
*);
560 static void x_build_heuristic_mask (struct frame
*, struct image
*,
563 #define CACHE_IMAGE_TYPE(type, status) \
564 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
566 #define CACHE_IMAGE_TYPE(type, status)
569 #define ADD_IMAGE_TYPE(type) \
570 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
572 /* Define a new image type from TYPE. This adds a copy of TYPE to
573 image_types and caches the loading status of TYPE. */
575 static struct image_type
*
576 define_image_type (struct image_type
*type
)
578 struct image_type
*p
= NULL
;
579 Lisp_Object target_type
= *type
->type
;
584 for (p
= image_types
; p
; p
= p
->next
)
585 if (EQ (*p
->type
, target_type
))
590 #if defined HAVE_NTGUI && defined WINDOWSNT
591 /* If we failed to load the library before, don't try again. */
592 Lisp_Object tested
= Fassq (target_type
, Vlibrary_cache
);
593 if (CONSP (tested
) && NILP (XCDR (tested
)))
598 type_valid
= type
->init ();
599 CACHE_IMAGE_TYPE (target_type
, type_valid
? Qt
: Qnil
);
605 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
606 The initialized data segment is read-only. */
607 p
= xmalloc (sizeof *p
);
609 p
->next
= image_types
;
619 /* Value is true if OBJECT is a valid Lisp image specification. A
620 valid image specification is a list whose car is the symbol
621 `image', and whose rest is a property list. The property list must
622 contain a value for key `:type'. That value must be the name of a
623 supported image type. The rest of the property list depends on the
627 valid_image_p (Lisp_Object object
)
635 for (tem
= XCDR (object
); CONSP (tem
); tem
= XCDR (tem
))
636 if (EQ (XCAR (tem
), QCtype
))
639 if (CONSP (tem
) && SYMBOLP (XCAR (tem
)))
641 struct image_type
*type
;
642 type
= lookup_image_type (XCAR (tem
));
644 valid_p
= type
->valid_p (object
);
655 /* Log error message with format string FORMAT and argument ARG.
656 Signaling an error, e.g. when an image cannot be loaded, is not a
657 good idea because this would interrupt redisplay, and the error
658 message display would lead to another redisplay. This function
659 therefore simply displays a message. */
662 image_error (const char *format
, Lisp_Object arg1
, Lisp_Object arg2
)
664 add_to_log (format
, arg1
, arg2
);
669 /***********************************************************************
671 ***********************************************************************/
673 enum image_value_type
675 IMAGE_DONT_CHECK_VALUE_TYPE
,
677 IMAGE_STRING_OR_NIL_VALUE
,
679 IMAGE_POSITIVE_INTEGER_VALUE
,
680 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
,
681 IMAGE_NON_NEGATIVE_INTEGER_VALUE
,
684 IMAGE_FUNCTION_VALUE
,
689 /* Structure used when parsing image specifications. */
693 /* Name of keyword. */
696 /* The type of value allowed. */
697 enum image_value_type type
;
699 /* True means key must be present. */
702 /* Used to recognize duplicate keywords in a property list. */
705 /* The value that was found. */
710 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
711 has the format (image KEYWORD VALUE ...). One of the keyword/
712 value pairs must be `:type TYPE'. KEYWORDS is a vector of
713 image_keywords structures of size NKEYWORDS describing other
714 allowed keyword/value pairs. Value is true if SPEC is valid. */
717 parse_image_spec (Lisp_Object spec
, struct image_keyword
*keywords
,
718 int nkeywords
, Lisp_Object type
)
727 while (CONSP (plist
))
729 Lisp_Object key
, value
;
731 /* First element of a pair must be a symbol. */
733 plist
= XCDR (plist
);
737 /* There must follow a value. */
740 value
= XCAR (plist
);
741 plist
= XCDR (plist
);
743 /* Find key in KEYWORDS. Error if not found. */
744 for (i
= 0; i
< nkeywords
; ++i
)
745 if (strcmp (keywords
[i
].name
, SSDATA (SYMBOL_NAME (key
))) == 0)
751 /* Record that we recognized the keyword. If a keywords
752 was found more than once, it's an error. */
753 keywords
[i
].value
= value
;
754 if (keywords
[i
].count
> 1)
758 /* Check type of value against allowed type. */
759 switch (keywords
[i
].type
)
761 case IMAGE_STRING_VALUE
:
762 if (!STRINGP (value
))
766 case IMAGE_STRING_OR_NIL_VALUE
:
767 if (!STRINGP (value
) && !NILP (value
))
771 case IMAGE_SYMBOL_VALUE
:
772 if (!SYMBOLP (value
))
776 case IMAGE_POSITIVE_INTEGER_VALUE
:
777 if (! RANGED_INTEGERP (1, value
, INT_MAX
))
781 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
:
782 if (RANGED_INTEGERP (0, value
, INT_MAX
))
785 && RANGED_INTEGERP (0, XCAR (value
), INT_MAX
)
786 && RANGED_INTEGERP (0, XCDR (value
), INT_MAX
))
790 case IMAGE_ASCENT_VALUE
:
791 if (SYMBOLP (value
) && EQ (value
, Qcenter
))
793 else if (RANGED_INTEGERP (0, value
, 100))
797 case IMAGE_NON_NEGATIVE_INTEGER_VALUE
:
798 /* Unlike the other integer-related cases, this one does not
799 verify that VALUE fits in 'int'. This is because callers
801 if (!INTEGERP (value
) || XINT (value
) < 0)
805 case IMAGE_DONT_CHECK_VALUE_TYPE
:
808 case IMAGE_FUNCTION_VALUE
:
809 value
= indirect_function (value
);
810 if (!NILP (Ffunctionp (value
)))
814 case IMAGE_NUMBER_VALUE
:
815 if (!INTEGERP (value
) && !FLOATP (value
))
819 case IMAGE_INTEGER_VALUE
:
820 if (! TYPE_RANGED_INTEGERP (int, value
))
824 case IMAGE_BOOL_VALUE
:
825 if (!NILP (value
) && !EQ (value
, Qt
))
834 if (EQ (key
, QCtype
) && !EQ (type
, value
))
838 /* Check that all mandatory fields are present. */
839 for (i
= 0; i
< nkeywords
; ++i
)
840 if (keywords
[i
].mandatory_p
&& keywords
[i
].count
== 0)
847 /* Return the value of KEY in image specification SPEC. Value is nil
848 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
849 was found in SPEC. */
852 image_spec_value (Lisp_Object spec
, Lisp_Object key
, bool *found
)
856 eassert (valid_image_p (spec
));
858 for (tail
= XCDR (spec
);
859 CONSP (tail
) && CONSP (XCDR (tail
));
860 tail
= XCDR (XCDR (tail
)))
862 if (EQ (XCAR (tail
), key
))
866 return XCAR (XCDR (tail
));
876 DEFUN ("image-size", Fimage_size
, Simage_size
, 1, 3, 0,
877 doc
: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
878 PIXELS non-nil means return the size in pixels, otherwise return the
879 size in canonical character units.
880 FRAME is the frame on which the image will be displayed. FRAME nil
881 or omitted means use the selected frame. */)
882 (Lisp_Object spec
, Lisp_Object pixels
, Lisp_Object frame
)
887 if (valid_image_p (spec
))
889 struct frame
*f
= decode_window_system_frame (frame
);
890 ptrdiff_t id
= lookup_image (f
, spec
);
891 struct image
*img
= IMAGE_FROM_ID (f
, id
);
892 int width
= img
->width
+ 2 * img
->hmargin
;
893 int height
= img
->height
+ 2 * img
->vmargin
;
896 size
= Fcons (make_float ((double) width
/ FRAME_COLUMN_WIDTH (f
)),
897 make_float ((double) height
/ FRAME_LINE_HEIGHT (f
)));
899 size
= Fcons (make_number (width
), make_number (height
));
902 error ("Invalid image specification");
908 DEFUN ("image-mask-p", Fimage_mask_p
, Simage_mask_p
, 1, 2, 0,
909 doc
: /* Return t if image SPEC has a mask bitmap.
910 FRAME is the frame on which the image will be displayed. FRAME nil
911 or omitted means use the selected frame. */)
912 (Lisp_Object spec
, Lisp_Object frame
)
917 if (valid_image_p (spec
))
919 struct frame
*f
= decode_window_system_frame (frame
);
920 ptrdiff_t id
= lookup_image (f
, spec
);
921 struct image
*img
= IMAGE_FROM_ID (f
, id
);
926 error ("Invalid image specification");
931 DEFUN ("image-metadata", Fimage_metadata
, Simage_metadata
, 1, 2, 0,
932 doc
: /* Return metadata for image SPEC.
933 FRAME is the frame on which the image will be displayed. FRAME nil
934 or omitted means use the selected frame. */)
935 (Lisp_Object spec
, Lisp_Object frame
)
940 if (valid_image_p (spec
))
942 struct frame
*f
= decode_window_system_frame (frame
);
943 ptrdiff_t id
= lookup_image (f
, spec
);
944 struct image
*img
= IMAGE_FROM_ID (f
, id
);
945 ext
= img
->lisp_data
;
952 /***********************************************************************
953 Image type independent image structures
954 ***********************************************************************/
956 #define MAX_IMAGE_SIZE 10.0
957 /* Allocate and return a new image structure for image specification
958 SPEC. SPEC has a hash value of HASH. */
960 static struct image
*
961 make_image (Lisp_Object spec
, EMACS_UINT hash
)
963 struct image
*img
= xzalloc (sizeof *img
);
964 Lisp_Object file
= image_spec_value (spec
, QCfile
, NULL
);
966 eassert (valid_image_p (spec
));
967 img
->dependencies
= NILP (file
) ? Qnil
: list1 (file
);
968 img
->type
= lookup_image_type (image_spec_value (spec
, QCtype
, NULL
));
969 eassert (img
->type
!= NULL
);
971 img
->lisp_data
= Qnil
;
972 img
->ascent
= DEFAULT_IMAGE_ASCENT
;
974 img
->corners
[BOT_CORNER
] = -1; /* Full image */
979 /* Free image IMG which was used on frame F, including its resources. */
982 free_image (struct frame
*f
, struct image
*img
)
986 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
988 /* Remove IMG from the hash table of its cache. */
990 img
->prev
->next
= img
->next
;
992 c
->buckets
[img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
] = img
->next
;
995 img
->next
->prev
= img
->prev
;
997 c
->images
[img
->id
] = NULL
;
999 /* Free resources, then free IMG. */
1000 img
->type
->free (f
, img
);
1005 /* Return true if the given widths and heights are valid for display. */
1008 check_image_size (struct frame
*f
, int width
, int height
)
1012 if (width
<= 0 || height
<= 0)
1015 if (INTEGERP (Vmax_image_size
))
1016 return (width
<= XINT (Vmax_image_size
)
1017 && height
<= XINT (Vmax_image_size
));
1018 else if (FLOATP (Vmax_image_size
))
1022 w
= FRAME_PIXEL_WIDTH (f
);
1023 h
= FRAME_PIXEL_HEIGHT (f
);
1026 w
= h
= 1024; /* Arbitrary size for unknown frame. */
1027 return (width
<= XFLOAT_DATA (Vmax_image_size
) * w
1028 && height
<= XFLOAT_DATA (Vmax_image_size
) * h
);
1034 /* Prepare image IMG for display on frame F. Must be called before
1035 drawing an image. */
1038 prepare_image_for_display (struct frame
*f
, struct image
*img
)
1040 /* We're about to display IMG, so set its timestamp to `now'. */
1041 img
->timestamp
= current_timespec ();
1043 /* If IMG doesn't have a pixmap yet, load it now, using the image
1044 type dependent loader function. */
1045 if (img
->pixmap
== NO_PIXMAP
&& !img
->load_failed_p
)
1046 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1048 #ifdef HAVE_X_WINDOWS
1049 if (!img
->load_failed_p
)
1052 image_sync_to_pixmaps (f
, img
);
1059 /* Value is the number of pixels for the ascent of image IMG when
1060 drawn in face FACE. */
1063 image_ascent (struct image
*img
, struct face
*face
, struct glyph_slice
*slice
)
1068 if (slice
->height
== img
->height
)
1069 height
= img
->height
+ img
->vmargin
;
1070 else if (slice
->y
== 0)
1071 height
= slice
->height
+ img
->vmargin
;
1073 height
= slice
->height
;
1075 if (img
->ascent
== CENTERED_IMAGE_ASCENT
)
1080 /* W32 specific version. Why?. ++kfs */
1081 ascent
= height
/ 2 - (FONT_DESCENT (face
->font
)
1082 - FONT_BASE (face
->font
)) / 2;
1084 /* This expression is arranged so that if the image can't be
1085 exactly centered, it will be moved slightly up. This is
1086 because a typical font is `top-heavy' (due to the presence
1087 uppercase letters), so the image placement should err towards
1088 being top-heavy too. It also just generally looks better. */
1089 ascent
= (height
+ FONT_BASE (face
->font
)
1090 - FONT_DESCENT (face
->font
) + 1) / 2;
1091 #endif /* HAVE_NTGUI */
1094 ascent
= height
/ 2;
1097 ascent
= height
* (img
->ascent
/ 100.0);
1103 /* Image background colors. */
1105 /* Find the "best" corner color of a bitmap.
1106 On W32, XIMG is assumed to a device context with the bitmap selected. */
1108 static RGB_PIXEL_COLOR
1109 four_corners_best (XImagePtr_or_DC ximg
, int *corners
,
1110 unsigned long width
, unsigned long height
)
1112 RGB_PIXEL_COLOR corner_pixels
[4], best
IF_LINT (= 0);
1115 if (corners
&& corners
[BOT_CORNER
] >= 0)
1117 /* Get the colors at the corner_pixels of ximg. */
1118 corner_pixels
[0] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[TOP_CORNER
]);
1119 corner_pixels
[1] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[TOP_CORNER
]);
1120 corner_pixels
[2] = GET_PIXEL (ximg
, corners
[RIGHT_CORNER
] - 1, corners
[BOT_CORNER
] - 1);
1121 corner_pixels
[3] = GET_PIXEL (ximg
, corners
[LEFT_CORNER
], corners
[BOT_CORNER
] - 1);
1125 /* Get the colors at the corner_pixels of ximg. */
1126 corner_pixels
[0] = GET_PIXEL (ximg
, 0, 0);
1127 corner_pixels
[1] = GET_PIXEL (ximg
, width
- 1, 0);
1128 corner_pixels
[2] = GET_PIXEL (ximg
, width
- 1, height
- 1);
1129 corner_pixels
[3] = GET_PIXEL (ximg
, 0, height
- 1);
1131 /* Choose the most frequently found color as background. */
1132 for (i
= best_count
= 0; i
< 4; ++i
)
1136 for (j
= n
= 0; j
< 4; ++j
)
1137 if (corner_pixels
[i
] == corner_pixels
[j
])
1141 best
= corner_pixels
[i
], best_count
= n
;
1147 /* Portability macros */
1151 #define Free_Pixmap(display, pixmap) \
1152 DeleteObject (pixmap)
1154 #elif defined (HAVE_NS)
1156 #define Free_Pixmap(display, pixmap) \
1157 ns_release_object (pixmap)
1161 #define Free_Pixmap(display, pixmap) \
1162 XFreePixmap (display, pixmap)
1164 #endif /* !HAVE_NTGUI && !HAVE_NS */
1167 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1168 it is guessed heuristically. If non-zero, XIMG is an existing
1169 XImage object (or device context with the image selected on W32) to
1170 use for the heuristic. */
1173 image_background (struct image
*img
, struct frame
*f
, XImagePtr_or_DC ximg
)
1175 if (! img
->background_valid
)
1176 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1178 bool free_ximg
= !ximg
;
1181 #endif /* HAVE_NTGUI */
1184 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
1186 img
->background
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
1189 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
1191 img
->background_valid
= 1;
1194 return img
->background
;
1197 /* Return the `background_transparent' field of IMG. If IMG doesn't
1198 have one yet, it is guessed heuristically. If non-zero, MASK is an
1199 existing XImage object to use for the heuristic. */
1202 image_background_transparent (struct image
*img
, struct frame
*f
, XImagePtr_or_DC mask
)
1204 if (! img
->background_transparent_valid
)
1205 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1209 bool free_mask
= !mask
;
1212 #endif /* HAVE_NTGUI */
1215 mask
= image_get_x_image_or_dc (f
, img
, 1, &prev
);
1217 img
->background_transparent
1218 = (four_corners_best (mask
, img
->corners
, img
->width
, img
->height
) == PIX_MASK_RETAIN
);
1221 image_unget_x_image_or_dc (img
, 1, mask
, prev
);
1224 img
->background_transparent
= 0;
1226 img
->background_transparent_valid
= 1;
1229 return img
->background_transparent
;
1233 /***********************************************************************
1234 Helper functions for X image types
1235 ***********************************************************************/
1237 /* Clear X resources of image IMG on frame F according to FLAGS.
1238 FLAGS is bitwise-or of the following masks:
1239 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1240 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1241 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1244 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1245 #define CLEAR_IMAGE_MASK (1 << 1)
1246 #define CLEAR_IMAGE_COLORS (1 << 2)
1249 x_clear_image_1 (struct frame
*f
, struct image
*img
, int flags
)
1251 if (flags
& CLEAR_IMAGE_PIXMAP
)
1255 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->pixmap
);
1256 img
->pixmap
= NO_PIXMAP
;
1257 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1258 img
->background_valid
= 0;
1260 #ifdef HAVE_X_WINDOWS
1263 x_destroy_x_image (img
->ximg
);
1265 img
->background_valid
= 0;
1270 if (flags
& CLEAR_IMAGE_MASK
)
1274 Free_Pixmap (FRAME_X_DISPLAY (f
), img
->mask
);
1275 img
->mask
= NO_PIXMAP
;
1276 img
->background_transparent_valid
= 0;
1278 #ifdef HAVE_X_WINDOWS
1281 x_destroy_x_image (img
->mask_img
);
1282 img
->mask_img
= NULL
;
1283 img
->background_transparent_valid
= 0;
1288 if ((flags
& CLEAR_IMAGE_COLORS
) && img
->ncolors
)
1290 /* W32_TODO: color table support. */
1291 #ifdef HAVE_X_WINDOWS
1292 x_free_colors (f
, img
->colors
, img
->ncolors
);
1293 #endif /* HAVE_X_WINDOWS */
1294 xfree (img
->colors
);
1301 /* Free X resources of image IMG which is used on frame F. */
1304 x_clear_image (struct frame
*f
, struct image
*img
)
1307 x_clear_image_1 (f
, img
,
1308 CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_MASK
| CLEAR_IMAGE_COLORS
);
1313 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1314 cannot be allocated, use DFLT. Add a newly allocated color to
1315 IMG->colors, so that it can be freed again. Value is the pixel
1318 static unsigned long
1319 x_alloc_image_color (struct frame
*f
, struct image
*img
, Lisp_Object color_name
,
1323 unsigned long result
;
1325 eassert (STRINGP (color_name
));
1327 if (x_defined_color (f
, SSDATA (color_name
), &color
, 1)
1328 && img
->ncolors
< min (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *img
->colors
,
1331 /* This isn't called frequently so we get away with simply
1332 reallocating the color vector to the needed size, here. */
1333 ptrdiff_t ncolors
= img
->ncolors
+ 1;
1334 img
->colors
= xrealloc (img
->colors
, ncolors
* sizeof *img
->colors
);
1335 img
->colors
[ncolors
- 1] = color
.pixel
;
1336 img
->ncolors
= ncolors
;
1337 result
= color
.pixel
;
1347 /***********************************************************************
1349 ***********************************************************************/
1351 static void cache_image (struct frame
*f
, struct image
*img
);
1353 /* Return a new, initialized image cache that is allocated from the
1354 heap. Call free_image_cache to free an image cache. */
1356 struct image_cache
*
1357 make_image_cache (void)
1359 struct image_cache
*c
= xmalloc (sizeof *c
);
1362 c
->used
= c
->refcount
= 0;
1363 c
->images
= xmalloc (c
->size
* sizeof *c
->images
);
1364 c
->buckets
= xzalloc (IMAGE_CACHE_BUCKETS_SIZE
* sizeof *c
->buckets
);
1369 /* Find an image matching SPEC in the cache, and return it. If no
1370 image is found, return NULL. */
1371 static struct image
*
1372 search_image_cache (struct frame
*f
, Lisp_Object spec
, EMACS_UINT hash
)
1375 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1376 int i
= hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1378 if (!c
) return NULL
;
1380 /* If the image spec does not specify a background color, the cached
1381 image must have the same background color as the current frame.
1382 The foreground color must also match, for the sake of monochrome
1385 In fact, we could ignore the foreground color matching condition
1386 for color images, or if the image spec specifies :foreground;
1387 similarly we could ignore the background color matching condition
1388 for formats that don't use transparency (such as jpeg), or if the
1389 image spec specifies :background. However, the extra memory
1390 usage is probably negligible in practice, so we don't bother. */
1392 for (img
= c
->buckets
[i
]; img
; img
= img
->next
)
1393 if (img
->hash
== hash
1394 && !NILP (Fequal (img
->spec
, spec
))
1395 && img
->frame_foreground
== FRAME_FOREGROUND_PIXEL (f
)
1396 && img
->frame_background
== FRAME_BACKGROUND_PIXEL (f
))
1402 /* Search frame F for an image with spec SPEC, and free it. */
1405 uncache_image (struct frame
*f
, Lisp_Object spec
)
1407 struct image
*img
= search_image_cache (f
, spec
, sxhash (spec
, 0));
1410 free_image (f
, img
);
1411 /* As display glyphs may still be referring to the image ID, we
1412 must garbage the frame (Bug#6426). */
1413 SET_FRAME_GARBAGED (f
);
1418 /* Free image cache of frame F. Be aware that X frames share images
1422 free_image_cache (struct frame
*f
)
1424 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1429 /* Cache should not be referenced by any frame when freed. */
1430 eassert (c
->refcount
== 0);
1432 for (i
= 0; i
< c
->used
; ++i
)
1433 free_image (f
, c
->images
[i
]);
1437 FRAME_IMAGE_CACHE (f
) = NULL
;
1442 /* Clear image cache of frame F. FILTER=t means free all images.
1443 FILTER=nil means clear only images that haven't been
1444 displayed for some time.
1445 Else, only free the images which have FILTER in their `dependencies'.
1446 Should be called from time to time to reduce the number of loaded images.
1447 If image-cache-eviction-delay is non-nil, this frees images in the cache
1448 which weren't displayed for at least that many seconds. */
1451 clear_image_cache (struct frame
*f
, Lisp_Object filter
)
1453 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1457 ptrdiff_t i
, nfreed
= 0;
1459 /* Block input so that we won't be interrupted by a SIGIO
1460 while being in an inconsistent state. */
1465 /* Filter image cache. */
1466 for (i
= 0; i
< c
->used
; ++i
)
1468 struct image
*img
= c
->images
[i
];
1469 if (img
&& (EQ (Qt
, filter
)
1470 || !NILP (Fmember (filter
, img
->dependencies
))))
1472 free_image (f
, img
);
1477 else if (INTEGERP (Vimage_cache_eviction_delay
))
1479 /* Free cache based on timestamp. */
1480 struct timespec old
, t
;
1482 ptrdiff_t nimages
= 0;
1484 for (i
= 0; i
< c
->used
; ++i
)
1488 /* If the number of cached images has grown unusually large,
1489 decrease the cache eviction delay (Bug#6230). */
1490 delay
= XINT (Vimage_cache_eviction_delay
);
1492 delay
= 1600 * delay
/ nimages
/ nimages
;
1493 delay
= max (delay
, 1);
1495 t
= current_timespec ();
1496 old
= timespec_sub (t
, dtotimespec (delay
));
1498 for (i
= 0; i
< c
->used
; ++i
)
1500 struct image
*img
= c
->images
[i
];
1501 if (img
&& timespec_cmp (img
->timestamp
, old
) < 0)
1503 free_image (f
, img
);
1509 /* We may be clearing the image cache because, for example,
1510 Emacs was iconified for a longer period of time. In that
1511 case, current matrices may still contain references to
1512 images freed above. So, clear these matrices. */
1515 Lisp_Object tail
, frame
;
1517 FOR_EACH_FRAME (tail
, frame
)
1519 struct frame
*fr
= XFRAME (frame
);
1520 if (FRAME_IMAGE_CACHE (fr
) == c
)
1521 clear_current_matrices (fr
);
1524 windows_or_buffers_changed
= 19;
1532 clear_image_caches (Lisp_Object filter
)
1534 /* FIXME: We want to do
1535 * struct terminal *t;
1536 * for (t = terminal_list; t; t = t->next_terminal)
1537 * clear_image_cache (t, filter); */
1538 Lisp_Object tail
, frame
;
1539 FOR_EACH_FRAME (tail
, frame
)
1540 if (FRAME_WINDOW_P (XFRAME (frame
)))
1541 clear_image_cache (XFRAME (frame
), filter
);
1544 DEFUN ("clear-image-cache", Fclear_image_cache
, Sclear_image_cache
,
1546 doc
: /* Clear the image cache.
1547 FILTER nil or a frame means clear all images in the selected frame.
1548 FILTER t means clear the image caches of all frames.
1549 Anything else, means only clear those images which refer to FILTER,
1550 which is then usually a filename. */)
1551 (Lisp_Object filter
)
1553 if (!(EQ (filter
, Qnil
) || FRAMEP (filter
)))
1554 clear_image_caches (filter
);
1556 clear_image_cache (decode_window_system_frame (filter
), Qt
);
1562 DEFUN ("image-flush", Fimage_flush
, Simage_flush
,
1564 doc
: /* Flush the image with specification SPEC on frame FRAME.
1565 This removes the image from the Emacs image cache. If SPEC specifies
1566 an image file, the next redisplay of this image will read from the
1567 current contents of that file.
1569 FRAME nil or omitted means use the selected frame.
1570 FRAME t means refresh the image on all frames. */)
1571 (Lisp_Object spec
, Lisp_Object frame
)
1573 if (!valid_image_p (spec
))
1574 error ("Invalid image specification");
1579 FOR_EACH_FRAME (tail
, frame
)
1581 struct frame
*f
= XFRAME (frame
);
1582 if (FRAME_WINDOW_P (f
))
1583 uncache_image (f
, spec
);
1587 uncache_image (decode_window_system_frame (frame
), spec
);
1593 /* Compute masks and transform image IMG on frame F, as specified
1594 by the image's specification, */
1597 postprocess_image (struct frame
*f
, struct image
*img
)
1599 /* Manipulation of the image's mask. */
1602 Lisp_Object conversion
, spec
;
1607 /* `:heuristic-mask t'
1609 means build a mask heuristically.
1610 `:heuristic-mask (R G B)'
1611 `:mask (heuristic (R G B))'
1612 means build a mask from color (R G B) in the
1615 means remove a mask, if any. */
1617 mask
= image_spec_value (spec
, QCheuristic_mask
, NULL
);
1619 x_build_heuristic_mask (f
, img
, mask
);
1624 mask
= image_spec_value (spec
, QCmask
, &found_p
);
1626 if (EQ (mask
, Qheuristic
))
1627 x_build_heuristic_mask (f
, img
, Qt
);
1628 else if (CONSP (mask
)
1629 && EQ (XCAR (mask
), Qheuristic
))
1631 if (CONSP (XCDR (mask
)))
1632 x_build_heuristic_mask (f
, img
, XCAR (XCDR (mask
)));
1634 x_build_heuristic_mask (f
, img
, XCDR (mask
));
1636 else if (NILP (mask
) && found_p
&& img
->mask
)
1637 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
1641 /* Should we apply an image transformation algorithm? */
1642 conversion
= image_spec_value (spec
, QCconversion
, NULL
);
1643 if (EQ (conversion
, Qdisabled
))
1644 x_disable_image (f
, img
);
1645 else if (EQ (conversion
, Qlaplace
))
1647 else if (EQ (conversion
, Qemboss
))
1649 else if (CONSP (conversion
)
1650 && EQ (XCAR (conversion
), Qedge_detection
))
1653 tem
= XCDR (conversion
);
1655 x_edge_detection (f
, img
,
1656 Fplist_get (tem
, QCmatrix
),
1657 Fplist_get (tem
, QCcolor_adjustment
));
1663 /* Return the id of image with Lisp specification SPEC on frame F.
1664 SPEC must be a valid Lisp image specification (see valid_image_p). */
1667 lookup_image (struct frame
*f
, Lisp_Object spec
)
1672 /* F must be a window-system frame, and SPEC must be a valid image
1674 eassert (FRAME_WINDOW_P (f
));
1675 eassert (valid_image_p (spec
));
1677 /* Look up SPEC in the hash table of the image cache. */
1678 hash
= sxhash (spec
, 0);
1679 img
= search_image_cache (f
, spec
, hash
);
1680 if (img
&& img
->load_failed_p
)
1682 free_image (f
, img
);
1686 /* If not found, create a new image and cache it. */
1690 img
= make_image (spec
, hash
);
1691 cache_image (f
, img
);
1692 img
->load_failed_p
= ! img
->type
->load (f
, img
);
1693 img
->frame_foreground
= FRAME_FOREGROUND_PIXEL (f
);
1694 img
->frame_background
= FRAME_BACKGROUND_PIXEL (f
);
1696 /* If we can't load the image, and we don't have a width and
1697 height, use some arbitrary width and height so that we can
1698 draw a rectangle for it. */
1699 if (img
->load_failed_p
)
1703 value
= image_spec_value (spec
, QCwidth
, NULL
);
1704 img
->width
= (INTEGERP (value
)
1705 ? XFASTINT (value
) : DEFAULT_IMAGE_WIDTH
);
1706 value
= image_spec_value (spec
, QCheight
, NULL
);
1707 img
->height
= (INTEGERP (value
)
1708 ? XFASTINT (value
) : DEFAULT_IMAGE_HEIGHT
);
1712 /* Handle image type independent image attributes
1713 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1714 `:background COLOR'. */
1715 Lisp_Object ascent
, margin
, relief
, bg
;
1718 ascent
= image_spec_value (spec
, QCascent
, NULL
);
1719 if (INTEGERP (ascent
))
1720 img
->ascent
= XFASTINT (ascent
);
1721 else if (EQ (ascent
, Qcenter
))
1722 img
->ascent
= CENTERED_IMAGE_ASCENT
;
1724 margin
= image_spec_value (spec
, QCmargin
, NULL
);
1725 if (INTEGERP (margin
))
1726 img
->vmargin
= img
->hmargin
= XFASTINT (margin
);
1727 else if (CONSP (margin
))
1729 img
->hmargin
= XFASTINT (XCAR (margin
));
1730 img
->vmargin
= XFASTINT (XCDR (margin
));
1733 relief
= image_spec_value (spec
, QCrelief
, NULL
);
1734 relief_bound
= INT_MAX
- max (img
->hmargin
, img
->vmargin
);
1735 if (RANGED_INTEGERP (- relief_bound
, relief
, relief_bound
))
1737 img
->relief
= XINT (relief
);
1738 img
->hmargin
+= eabs (img
->relief
);
1739 img
->vmargin
+= eabs (img
->relief
);
1742 if (! img
->background_valid
)
1744 bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
1748 = x_alloc_image_color (f
, img
, bg
,
1749 FRAME_BACKGROUND_PIXEL (f
));
1750 img
->background_valid
= 1;
1754 /* Do image transformations and compute masks, unless we
1755 don't have the image yet. */
1756 if (!EQ (*img
->type
->type
, Qpostscript
))
1757 postprocess_image (f
, img
);
1763 /* We're using IMG, so set its timestamp to `now'. */
1764 img
->timestamp
= current_timespec ();
1766 /* Value is the image id. */
1771 /* Cache image IMG in the image cache of frame F. */
1774 cache_image (struct frame
*f
, struct image
*img
)
1776 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
1779 /* Find a free slot in c->images. */
1780 for (i
= 0; i
< c
->used
; ++i
)
1781 if (c
->images
[i
] == NULL
)
1784 /* If no free slot found, maybe enlarge c->images. */
1785 if (i
== c
->used
&& c
->used
== c
->size
)
1786 c
->images
= xpalloc (c
->images
, &c
->size
, 1, -1, sizeof *c
->images
);
1788 /* Add IMG to c->images, and assign IMG an id. */
1794 /* Add IMG to the cache's hash table. */
1795 i
= img
->hash
% IMAGE_CACHE_BUCKETS_SIZE
;
1796 img
->next
= c
->buckets
[i
];
1798 img
->next
->prev
= img
;
1800 c
->buckets
[i
] = img
;
1804 /* Call FN on every image in the image cache of frame F. Used to mark
1805 Lisp Objects in the image cache. */
1807 /* Mark Lisp objects in image IMG. */
1810 mark_image (struct image
*img
)
1812 mark_object (img
->spec
);
1813 mark_object (img
->dependencies
);
1815 if (!NILP (img
->lisp_data
))
1816 mark_object (img
->lisp_data
);
1821 mark_image_cache (struct image_cache
*c
)
1826 for (i
= 0; i
< c
->used
; ++i
)
1828 mark_image (c
->images
[i
]);
1834 /***********************************************************************
1835 X / NS / W32 support code
1836 ***********************************************************************/
1840 /* Macro for defining functions that will be loaded from image DLLs. */
1841 #define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
1843 /* Macro for loading those image functions from the library. */
1844 #define LOAD_IMGLIB_FN(lib,func) { \
1845 fn_##func = (void *) GetProcAddress (lib, #func); \
1846 if (!fn_##func) return 0; \
1849 #endif /* WINDOWSNT */
1851 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1853 WIDTH and HEIGHT must both be positive.
1854 If XIMG is null, assume it is a bitmap. */
1856 x_check_image_size (XImagePtr ximg
, int width
, int height
)
1858 #ifdef HAVE_X_WINDOWS
1859 /* Respect Xlib's limits: it cannot deal with images that have more
1860 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1861 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1864 XLIB_BYTES_MAX
= min (INT_MAX
, UINT_MAX
),
1865 X_IMAGE_BYTES_MAX
= min (XLIB_BYTES_MAX
, min (PTRDIFF_MAX
, SIZE_MAX
))
1868 int bitmap_pad
, depth
, bytes_per_line
;
1871 bitmap_pad
= ximg
->bitmap_pad
;
1872 depth
= ximg
->depth
;
1873 bytes_per_line
= ximg
->bytes_per_line
;
1879 bytes_per_line
= (width
>> 3) + ((width
& 7) != 0);
1881 return (width
<= (INT_MAX
- (bitmap_pad
- 1)) / depth
1882 && height
<= X_IMAGE_BYTES_MAX
/ bytes_per_line
);
1884 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1885 For now, assume that every image size is allowed on these systems. */
1890 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1891 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1892 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1893 via xmalloc. Print error messages via image_error if an error
1894 occurs. Value is true if successful.
1896 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1897 should indicate the bit depth of the image. */
1900 x_create_x_image_and_pixmap (struct frame
*f
, int width
, int height
, int depth
,
1901 XImagePtr
*ximg
, Pixmap
*pixmap
)
1903 #ifdef HAVE_X_WINDOWS
1904 Display
*display
= FRAME_X_DISPLAY (f
);
1905 Window window
= FRAME_X_WINDOW (f
);
1906 Screen
*screen
= FRAME_X_SCREEN (f
);
1908 eassert (input_blocked_p ());
1911 depth
= DefaultDepthOfScreen (screen
);
1912 *ximg
= XCreateImage (display
, DefaultVisualOfScreen (screen
),
1913 depth
, ZPixmap
, 0, NULL
, width
, height
,
1914 depth
> 16 ? 32 : depth
> 8 ? 16 : 8, 0);
1917 image_error ("Unable to allocate X image", Qnil
, Qnil
);
1921 if (! x_check_image_size (*ximg
, width
, height
))
1923 x_destroy_x_image (*ximg
);
1925 image_error ("Image too large (%dx%d)",
1926 make_number (width
), make_number (height
));
1930 /* Allocate image raster. */
1931 (*ximg
)->data
= xmalloc ((*ximg
)->bytes_per_line
* height
);
1933 /* Allocate a pixmap of the same size. */
1934 *pixmap
= XCreatePixmap (display
, window
, width
, height
, depth
);
1935 if (*pixmap
== NO_PIXMAP
)
1937 x_destroy_x_image (*ximg
);
1939 image_error ("Unable to create X pixmap", Qnil
, Qnil
);
1944 #endif /* HAVE_X_WINDOWS */
1948 BITMAPINFOHEADER
*header
;
1950 int scanline_width_bits
;
1952 int palette_colors
= 0;
1957 if (depth
!= 1 && depth
!= 4 && depth
!= 8
1958 && depth
!= 16 && depth
!= 24 && depth
!= 32)
1960 image_error ("Invalid image bit depth specified", Qnil
, Qnil
);
1964 scanline_width_bits
= width
* depth
;
1965 remainder
= scanline_width_bits
% 32;
1968 scanline_width_bits
+= 32 - remainder
;
1970 /* Bitmaps with a depth less than 16 need a palette. */
1971 /* BITMAPINFO structure already contains the first RGBQUAD. */
1973 palette_colors
= 1 << (depth
- 1);
1975 *ximg
= xmalloc (sizeof (XImage
) + palette_colors
* sizeof (RGBQUAD
));
1977 header
= &(*ximg
)->info
.bmiHeader
;
1978 memset (&(*ximg
)->info
, 0, sizeof (BITMAPINFO
));
1979 header
->biSize
= sizeof (*header
);
1980 header
->biWidth
= width
;
1981 header
->biHeight
= -height
; /* negative indicates a top-down bitmap. */
1982 header
->biPlanes
= 1;
1983 header
->biBitCount
= depth
;
1984 header
->biCompression
= BI_RGB
;
1985 header
->biClrUsed
= palette_colors
;
1987 /* TODO: fill in palette. */
1990 (*ximg
)->info
.bmiColors
[0].rgbBlue
= 0;
1991 (*ximg
)->info
.bmiColors
[0].rgbGreen
= 0;
1992 (*ximg
)->info
.bmiColors
[0].rgbRed
= 0;
1993 (*ximg
)->info
.bmiColors
[0].rgbReserved
= 0;
1994 (*ximg
)->info
.bmiColors
[1].rgbBlue
= 255;
1995 (*ximg
)->info
.bmiColors
[1].rgbGreen
= 255;
1996 (*ximg
)->info
.bmiColors
[1].rgbRed
= 255;
1997 (*ximg
)->info
.bmiColors
[1].rgbReserved
= 0;
2000 hdc
= get_frame_dc (f
);
2002 /* Create a DIBSection and raster array for the bitmap,
2003 and store its handle in *pixmap. */
2004 *pixmap
= CreateDIBSection (hdc
, &((*ximg
)->info
),
2005 (depth
< 16) ? DIB_PAL_COLORS
: DIB_RGB_COLORS
,
2006 /* casting avoids a GCC warning */
2007 (void **)&((*ximg
)->data
), NULL
, 0);
2009 /* Realize display palette and garbage all frames. */
2010 release_frame_dc (f
, hdc
);
2012 if (*pixmap
== NULL
)
2014 DWORD err
= GetLastError ();
2015 Lisp_Object errcode
;
2016 /* All system errors are < 10000, so the following is safe. */
2017 XSETINT (errcode
, err
);
2018 image_error ("Unable to create bitmap, error code %d", errcode
, Qnil
);
2019 x_destroy_x_image (*ximg
);
2025 #endif /* HAVE_NTGUI */
2028 *pixmap
= ns_image_for_XPM (width
, height
, depth
);
2032 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil
, Qnil
);
2041 /* Destroy XImage XIMG. Free XIMG->data. */
2044 x_destroy_x_image (XImagePtr ximg
)
2046 eassert (input_blocked_p ());
2049 #ifdef HAVE_X_WINDOWS
2052 XDestroyImage (ximg
);
2053 #endif /* HAVE_X_WINDOWS */
2055 /* Data will be freed by DestroyObject. */
2058 #endif /* HAVE_NTGUI */
2060 ns_release_object (ximg
);
2061 #endif /* HAVE_NS */
2066 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2067 are width and height of both the image and pixmap. */
2070 x_put_x_image (struct frame
*f
, XImagePtr ximg
, Pixmap pixmap
, int width
, int height
)
2072 #ifdef HAVE_X_WINDOWS
2075 eassert (input_blocked_p ());
2076 gc
= XCreateGC (FRAME_X_DISPLAY (f
), pixmap
, 0, NULL
);
2077 XPutImage (FRAME_X_DISPLAY (f
), pixmap
, gc
, ximg
, 0, 0, 0, 0, width
, height
);
2078 XFreeGC (FRAME_X_DISPLAY (f
), gc
);
2079 #endif /* HAVE_X_WINDOWS */
2082 #if 0 /* I don't think this is necessary looking at where it is used. */
2083 HDC hdc
= get_frame_dc (f
);
2084 SetDIBits (hdc
, pixmap
, 0, height
, ximg
->data
, &(ximg
->info
), DIB_RGB_COLORS
);
2085 release_frame_dc (f
, hdc
);
2087 #endif /* HAVE_NTGUI */
2090 eassert (ximg
== pixmap
);
2091 ns_retain_object (ximg
);
2095 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2096 with image_put_x_image. */
2099 image_create_x_image_and_pixmap (struct frame
*f
, struct image
*img
,
2100 int width
, int height
, int depth
,
2101 XImagePtr
*ximg
, bool mask_p
)
2103 eassert ((!mask_p
? img
->pixmap
: img
->mask
) == NO_PIXMAP
);
2105 return x_create_x_image_and_pixmap (f
, width
, height
, depth
, ximg
,
2106 !mask_p
? &img
->pixmap
: &img
->mask
);
2109 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2110 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2111 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2112 On the other platforms, it puts XIMG into the pixmap, then frees
2113 the X image and its buffer. */
2116 image_put_x_image (struct frame
*f
, struct image
*img
, XImagePtr ximg
,
2119 #ifdef HAVE_X_WINDOWS
2122 eassert (img
->ximg
== NULL
);
2127 eassert (img
->mask_img
== NULL
);
2128 img
->mask_img
= ximg
;
2131 x_put_x_image (f
, ximg
, !mask_p
? img
->pixmap
: img
->mask
,
2132 img
->width
, img
->height
);
2133 x_destroy_x_image (ximg
);
2137 #ifdef HAVE_X_WINDOWS
2138 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2139 the X images and their buffers. */
2142 image_sync_to_pixmaps (struct frame
*f
, struct image
*img
)
2146 x_put_x_image (f
, img
->ximg
, img
->pixmap
, img
->width
, img
->height
);
2147 x_destroy_x_image (img
->ximg
);
2152 x_put_x_image (f
, img
->mask_img
, img
->mask
, img
->width
, img
->height
);
2153 x_destroy_x_image (img
->mask_img
);
2154 img
->mask_img
= NULL
;
2160 /* Create a memory device context for IMG on frame F. It stores the
2161 currently selected GDI object into *PREV for future restoration by
2162 image_unget_x_image_or_dc. */
2164 static XImagePtr_or_DC
2165 image_get_x_image_or_dc (struct frame
*f
, struct image
*img
, bool mask_p
,
2168 HDC frame_dc
= get_frame_dc (f
);
2169 XImagePtr_or_DC ximg
= CreateCompatibleDC (frame_dc
);
2171 release_frame_dc (f
, frame_dc
);
2172 *prev
= SelectObject (ximg
, !mask_p
? img
->pixmap
: img
->mask
);
2178 image_unget_x_image_or_dc (struct image
*img
, bool mask_p
,
2179 XImagePtr_or_DC ximg
, HGDIOBJ prev
)
2181 SelectObject (ximg
, prev
);
2184 #else /* !HAVE_NTGUI */
2185 /* Get the X image for IMG on frame F. The resulting X image data
2186 should be treated as read-only at least on X. */
2189 image_get_x_image (struct frame
*f
, struct image
*img
, bool mask_p
)
2191 #ifdef HAVE_X_WINDOWS
2192 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2197 return XGetImage (FRAME_X_DISPLAY (f
), !mask_p
? img
->pixmap
: img
->mask
,
2198 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
2199 #elif defined (HAVE_NS)
2200 XImagePtr pixmap
= !mask_p
? img
->pixmap
: img
->mask
;
2202 ns_retain_object (pixmap
);
2208 image_unget_x_image (struct image
*img
, bool mask_p
, XImagePtr ximg
)
2210 #ifdef HAVE_X_WINDOWS
2211 XImagePtr ximg_in_img
= !mask_p
? img
->ximg
: img
->mask_img
;
2214 eassert (ximg
== ximg_in_img
);
2216 XDestroyImage (ximg
);
2217 #elif defined (HAVE_NS)
2218 ns_release_object (ximg
);
2221 #endif /* !HAVE_NTGUI */
2224 /***********************************************************************
2226 ***********************************************************************/
2228 /* Find image file FILE. Look in data-directory/images, then
2229 x-bitmap-file-path. Value is the encoded full name of the file
2230 found, or nil if not found. */
2233 x_find_image_file (Lisp_Object file
)
2235 Lisp_Object file_found
, search_path
;
2238 /* TODO I think this should use something like image-load-path
2239 instead. Unfortunately, that can contain non-string elements. */
2240 search_path
= Fcons (Fexpand_file_name (build_string ("images"),
2242 Vx_bitmap_file_path
);
2244 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2245 fd
= openp (search_path
, file
, Qnil
, &file_found
, Qnil
, 0);
2251 file_found
= ENCODE_FILE (file_found
);
2260 /* Read FILE into memory. Value is a pointer to a buffer allocated
2261 with xmalloc holding FILE's contents. Value is null if an error
2262 occurred. *SIZE is set to the size of the file. */
2264 static unsigned char *
2265 slurp_file (char *file
, ptrdiff_t *size
)
2267 FILE *fp
= emacs_fopen (file
, "rb");
2268 unsigned char *buf
= NULL
;
2273 ptrdiff_t count
= SPECPDL_INDEX ();
2274 record_unwind_protect_ptr (fclose_unwind
, fp
);
2276 if (fstat (fileno (fp
), &st
) == 0
2277 && 0 <= st
.st_size
&& st
.st_size
< min (PTRDIFF_MAX
, SIZE_MAX
))
2279 /* Report an error if we read past the purported EOF.
2280 This can happen if the file grows as we read it. */
2281 ptrdiff_t buflen
= st
.st_size
;
2282 buf
= xmalloc (buflen
+ 1);
2283 if (fread (buf
, 1, buflen
+ 1, fp
) == buflen
)
2292 unbind_to (count
, Qnil
);
2300 /***********************************************************************
2302 ***********************************************************************/
2304 static bool xbm_load (struct frame
*f
, struct image
*img
);
2305 static bool xbm_image_p (Lisp_Object object
);
2306 static bool xbm_file_p (Lisp_Object
);
2309 /* Indices of image specification fields in xbm_format, below. */
2311 enum xbm_keyword_index
2329 /* Vector of image_keyword structures describing the format
2330 of valid XBM image specifications. */
2332 static const struct image_keyword xbm_format
[XBM_LAST
] =
2334 {":type", IMAGE_SYMBOL_VALUE
, 1},
2335 {":file", IMAGE_STRING_VALUE
, 0},
2336 {":width", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2337 {":height", IMAGE_POSITIVE_INTEGER_VALUE
, 0},
2338 {":data", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2339 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
2340 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
2341 {":ascent", IMAGE_ASCENT_VALUE
, 0},
2342 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
2343 {":relief", IMAGE_INTEGER_VALUE
, 0},
2344 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2345 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
2346 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
2349 /* Structure describing the image type XBM. */
2351 static struct image_type xbm_type
=
2361 /* Tokens returned from xbm_scan. */
2370 /* Return true if OBJECT is a valid XBM-type image specification.
2371 A valid specification is a list starting with the symbol `image'
2372 The rest of the list is a property list which must contain an
2375 If the specification specifies a file to load, it must contain
2376 an entry `:file FILENAME' where FILENAME is a string.
2378 If the specification is for a bitmap loaded from memory it must
2379 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2380 WIDTH and HEIGHT are integers > 0. DATA may be:
2382 1. a string large enough to hold the bitmap data, i.e. it must
2383 have a size >= (WIDTH + 7) / 8 * HEIGHT
2385 2. a bool-vector of size >= WIDTH * HEIGHT
2387 3. a vector of strings or bool-vectors, one for each line of the
2390 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2391 may not be specified in this case because they are defined in the
2394 Both the file and data forms may contain the additional entries
2395 `:background COLOR' and `:foreground COLOR'. If not present,
2396 foreground and background of the frame on which the image is
2397 displayed is used. */
2400 xbm_image_p (Lisp_Object object
)
2402 struct image_keyword kw
[XBM_LAST
];
2404 memcpy (kw
, xbm_format
, sizeof kw
);
2405 if (!parse_image_spec (object
, kw
, XBM_LAST
, Qxbm
))
2408 eassert (EQ (kw
[XBM_TYPE
].value
, Qxbm
));
2410 if (kw
[XBM_FILE
].count
)
2412 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_DATA
].count
)
2415 else if (kw
[XBM_DATA
].count
&& xbm_file_p (kw
[XBM_DATA
].value
))
2417 /* In-memory XBM file. */
2418 if (kw
[XBM_WIDTH
].count
|| kw
[XBM_HEIGHT
].count
|| kw
[XBM_FILE
].count
)
2426 /* Entries for `:width', `:height' and `:data' must be present. */
2427 if (!kw
[XBM_WIDTH
].count
2428 || !kw
[XBM_HEIGHT
].count
2429 || !kw
[XBM_DATA
].count
)
2432 data
= kw
[XBM_DATA
].value
;
2433 width
= XFASTINT (kw
[XBM_WIDTH
].value
);
2434 height
= XFASTINT (kw
[XBM_HEIGHT
].value
);
2436 /* Check type of data, and width and height against contents of
2442 /* Number of elements of the vector must be >= height. */
2443 if (ASIZE (data
) < height
)
2446 /* Each string or bool-vector in data must be large enough
2447 for one line of the image. */
2448 for (i
= 0; i
< height
; ++i
)
2450 Lisp_Object elt
= AREF (data
, i
);
2455 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
)
2458 else if (BOOL_VECTOR_P (elt
))
2460 if (bool_vector_size (elt
) < width
)
2467 else if (STRINGP (data
))
2470 < (width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
* height
)
2473 else if (BOOL_VECTOR_P (data
))
2475 if (bool_vector_size (data
) / height
< width
)
2486 /* Scan a bitmap file. FP is the stream to read from. Value is
2487 either an enumerator from enum xbm_token, or a character for a
2488 single-character token, or 0 at end of file. If scanning an
2489 identifier, store the lexeme of the identifier in SVAL. If
2490 scanning a number, store its value in *IVAL. */
2493 xbm_scan (unsigned char **s
, unsigned char *end
, char *sval
, int *ival
)
2499 /* Skip white space. */
2500 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
2505 else if (c_isdigit (c
))
2507 int value
= 0, digit
;
2509 if (c
== '0' && *s
< end
)
2512 if (c
== 'x' || c
== 'X')
2519 else if (c
>= 'a' && c
<= 'f')
2520 digit
= c
- 'a' + 10;
2521 else if (c
>= 'A' && c
<= 'F')
2522 digit
= c
- 'A' + 10;
2525 value
= 16 * value
+ digit
;
2528 else if (c_isdigit (c
))
2532 && (c
= *(*s
)++, c_isdigit (c
)))
2533 value
= 8 * value
+ c
- '0';
2540 && (c
= *(*s
)++, c_isdigit (c
)))
2541 value
= 10 * value
+ c
- '0';
2549 else if (c_isalpha (c
) || c
== '_')
2553 && (c
= *(*s
)++, (c_isalnum (c
) || c
== '_')))
2560 else if (c
== '/' && **s
== '*')
2562 /* C-style comment. */
2564 while (**s
&& (**s
!= '*' || *(*s
+ 1) != '/'))
2578 /* Create a Windows bitmap from X bitmap data. */
2580 w32_create_pixmap_from_bitmap_data (int width
, int height
, char *data
)
2582 static unsigned char swap_nibble
[16]
2583 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2584 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2585 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2586 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2588 unsigned char *bits
, *p
;
2591 w1
= (width
+ 7) / 8; /* nb of 8bits elt in X bitmap */
2592 w2
= ((width
+ 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2593 bits
= alloca (height
* w2
);
2594 memset (bits
, 0, height
* w2
);
2595 for (i
= 0; i
< height
; i
++)
2598 for (j
= 0; j
< w1
; j
++)
2600 /* Bitswap XBM bytes to match how Windows does things. */
2601 unsigned char c
= *data
++;
2602 *p
++ = (unsigned char)((swap_nibble
[c
& 0xf] << 4)
2603 | (swap_nibble
[(c
>>4) & 0xf]));
2606 bmp
= CreateBitmap (width
, height
, 1, 1, (char *) bits
);
2612 convert_mono_to_color_image (struct frame
*f
, struct image
*img
,
2613 COLORREF foreground
, COLORREF background
)
2615 HDC hdc
, old_img_dc
, new_img_dc
;
2616 HGDIOBJ old_prev
, new_prev
;
2619 hdc
= get_frame_dc (f
);
2620 old_img_dc
= CreateCompatibleDC (hdc
);
2621 new_img_dc
= CreateCompatibleDC (hdc
);
2622 new_pixmap
= CreateCompatibleBitmap (hdc
, img
->width
, img
->height
);
2623 release_frame_dc (f
, hdc
);
2624 old_prev
= SelectObject (old_img_dc
, img
->pixmap
);
2625 new_prev
= SelectObject (new_img_dc
, new_pixmap
);
2626 /* Windows convention for mono bitmaps is black = background,
2627 white = foreground. */
2628 SetTextColor (new_img_dc
, background
);
2629 SetBkColor (new_img_dc
, foreground
);
2631 BitBlt (new_img_dc
, 0, 0, img
->width
, img
->height
, old_img_dc
,
2634 SelectObject (old_img_dc
, old_prev
);
2635 SelectObject (new_img_dc
, new_prev
);
2636 DeleteDC (old_img_dc
);
2637 DeleteDC (new_img_dc
);
2638 DeleteObject (img
->pixmap
);
2639 if (new_pixmap
== 0)
2640 fprintf (stderr
, "Failed to convert image to color.\n");
2642 img
->pixmap
= new_pixmap
;
2645 #define XBM_BIT_SHUFFLE(b) (~(b))
2649 #define XBM_BIT_SHUFFLE(b) (b)
2651 #endif /* HAVE_NTGUI */
2655 Create_Pixmap_From_Bitmap_Data (struct frame
*f
, struct image
*img
, char *data
,
2656 RGB_PIXEL_COLOR fg
, RGB_PIXEL_COLOR bg
,
2657 bool non_default_colors
)
2661 = w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
, data
);
2663 /* If colors were specified, transfer the bitmap to a color one. */
2664 if (non_default_colors
)
2665 convert_mono_to_color_image (f
, img
, fg
, bg
);
2667 #elif defined (HAVE_NS)
2668 img
->pixmap
= ns_image_from_XBM (data
, img
->width
, img
->height
);
2672 (x_check_image_size (0, img
->width
, img
->height
)
2673 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f
),
2676 img
->width
, img
->height
,
2678 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)))
2680 #endif /* !HAVE_NTGUI && !HAVE_NS */
2685 /* Replacement for XReadBitmapFileData which isn't available under old
2686 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2687 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2688 the image. Return in *DATA the bitmap data allocated with xmalloc.
2689 Value is true if successful. DATA null means just test if
2690 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2691 inhibit the call to image_error when the image size is invalid (the
2692 bitmap remains unread). */
2695 xbm_read_bitmap_data (struct frame
*f
, unsigned char *contents
, unsigned char *end
,
2696 int *width
, int *height
, char **data
,
2697 bool inhibit_image_error
)
2699 unsigned char *s
= contents
;
2700 char buffer
[BUFSIZ
];
2703 int bytes_per_line
, i
, nbytes
;
2709 LA1 = xbm_scan (&s, end, buffer, &value)
2711 #define expect(TOKEN) \
2714 if (LA1 != (TOKEN)) \
2720 #define expect_ident(IDENT) \
2721 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2726 *width
= *height
= -1;
2729 LA1
= xbm_scan (&s
, end
, buffer
, &value
);
2731 /* Parse defines for width, height and hot-spots. */
2735 expect_ident ("define");
2736 expect (XBM_TK_IDENT
);
2738 if (LA1
== XBM_TK_NUMBER
)
2740 char *q
= strrchr (buffer
, '_');
2741 q
= q
? q
+ 1 : buffer
;
2742 if (strcmp (q
, "width") == 0)
2744 else if (strcmp (q
, "height") == 0)
2747 expect (XBM_TK_NUMBER
);
2750 if (!check_image_size (f
, *width
, *height
))
2752 if (!inhibit_image_error
)
2753 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
2756 else if (data
== NULL
)
2759 /* Parse bits. Must start with `static'. */
2760 expect_ident ("static");
2761 if (LA1
== XBM_TK_IDENT
)
2763 if (strcmp (buffer
, "unsigned") == 0)
2766 expect_ident ("char");
2768 else if (strcmp (buffer
, "short") == 0)
2772 if (*width
% 16 && *width
% 16 < 9)
2775 else if (strcmp (buffer
, "char") == 0)
2783 expect (XBM_TK_IDENT
);
2789 if (! x_check_image_size (0, *width
, *height
))
2791 if (!inhibit_image_error
)
2792 image_error ("Image too large (%dx%d)",
2793 make_number (*width
), make_number (*height
));
2796 bytes_per_line
= (*width
+ 7) / 8 + padding_p
;
2797 nbytes
= bytes_per_line
* *height
;
2798 p
= *data
= xmalloc (nbytes
);
2802 for (i
= 0; i
< nbytes
; i
+= 2)
2805 expect (XBM_TK_NUMBER
);
2807 *p
++ = XBM_BIT_SHUFFLE (val
);
2808 if (!padding_p
|| ((i
+ 2) % bytes_per_line
))
2809 *p
++ = XBM_BIT_SHUFFLE (value
>> 8);
2811 if (LA1
== ',' || LA1
== '}')
2819 for (i
= 0; i
< nbytes
; ++i
)
2822 expect (XBM_TK_NUMBER
);
2824 *p
++ = XBM_BIT_SHUFFLE (val
);
2826 if (LA1
== ',' || LA1
== '}')
2851 /* Load XBM image IMG which will be displayed on frame F from buffer
2852 CONTENTS. END is the end of the buffer. Value is true if
2856 xbm_load_image (struct frame
*f
, struct image
*img
, unsigned char *contents
,
2863 rc
= xbm_read_bitmap_data (f
, contents
, end
, &img
->width
, &img
->height
,
2867 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
2868 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
2869 bool non_default_colors
= 0;
2872 eassert (img
->width
> 0 && img
->height
> 0);
2874 /* Get foreground and background colors, maybe allocate colors. */
2875 value
= image_spec_value (img
->spec
, QCforeground
, NULL
);
2878 foreground
= x_alloc_image_color (f
, img
, value
, foreground
);
2879 non_default_colors
= 1;
2881 value
= image_spec_value (img
->spec
, QCbackground
, NULL
);
2884 background
= x_alloc_image_color (f
, img
, value
, background
);
2885 img
->background
= background
;
2886 img
->background_valid
= 1;
2887 non_default_colors
= 1;
2890 Create_Pixmap_From_Bitmap_Data (f
, img
, data
,
2891 foreground
, background
,
2892 non_default_colors
);
2895 if (img
->pixmap
== NO_PIXMAP
)
2897 x_clear_image (f
, img
);
2898 image_error ("Unable to create X pixmap for `%s'", img
->spec
, Qnil
);
2904 image_error ("Error loading XBM image `%s'", img
->spec
, Qnil
);
2910 /* Value is true if DATA looks like an in-memory XBM file. */
2913 xbm_file_p (Lisp_Object data
)
2916 return (STRINGP (data
)
2917 && xbm_read_bitmap_data (NULL
, SDATA (data
),
2918 (SDATA (data
) + SBYTES (data
)),
2923 /* Fill image IMG which is used on frame F with pixmap data. Value is
2924 true if successful. */
2927 xbm_load (struct frame
*f
, struct image
*img
)
2930 Lisp_Object file_name
;
2932 eassert (xbm_image_p (img
->spec
));
2934 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2935 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
2936 if (STRINGP (file_name
))
2939 unsigned char *contents
;
2942 file
= x_find_image_file (file_name
);
2943 if (!STRINGP (file
))
2945 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
2949 contents
= slurp_file (SSDATA (file
), &size
);
2950 if (contents
== NULL
)
2952 image_error ("Error loading XBM image `%s'", img
->spec
, Qnil
);
2956 success_p
= xbm_load_image (f
, img
, contents
, contents
+ size
);
2961 struct image_keyword fmt
[XBM_LAST
];
2963 unsigned long foreground
= FRAME_FOREGROUND_PIXEL (f
);
2964 unsigned long background
= FRAME_BACKGROUND_PIXEL (f
);
2965 bool non_default_colors
= 0;
2968 bool in_memory_file_p
= 0;
2970 /* See if data looks like an in-memory XBM file. */
2971 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
2972 in_memory_file_p
= xbm_file_p (data
);
2974 /* Parse the image specification. */
2975 memcpy (fmt
, xbm_format
, sizeof fmt
);
2976 parsed_p
= parse_image_spec (img
->spec
, fmt
, XBM_LAST
, Qxbm
);
2979 /* Get specified width, and height. */
2980 if (!in_memory_file_p
)
2982 img
->width
= XFASTINT (fmt
[XBM_WIDTH
].value
);
2983 img
->height
= XFASTINT (fmt
[XBM_HEIGHT
].value
);
2984 eassert (img
->width
> 0 && img
->height
> 0);
2985 if (!check_image_size (f
, img
->width
, img
->height
))
2987 image_error ("Invalid image size (see `max-image-size')",
2993 /* Get foreground and background colors, maybe allocate colors. */
2994 if (fmt
[XBM_FOREGROUND
].count
2995 && STRINGP (fmt
[XBM_FOREGROUND
].value
))
2997 foreground
= x_alloc_image_color (f
, img
, fmt
[XBM_FOREGROUND
].value
,
2999 non_default_colors
= 1;
3002 if (fmt
[XBM_BACKGROUND
].count
3003 && STRINGP (fmt
[XBM_BACKGROUND
].value
))
3005 background
= x_alloc_image_color (f
, img
, fmt
[XBM_BACKGROUND
].value
,
3007 non_default_colors
= 1;
3010 if (in_memory_file_p
)
3011 success_p
= xbm_load_image (f
, img
, SDATA (data
),
3020 int nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
;
3022 p
= bits
= alloca (nbytes
* img
->height
);
3023 for (i
= 0; i
< img
->height
; ++i
, p
+= nbytes
)
3025 Lisp_Object line
= AREF (data
, i
);
3027 memcpy (p
, SDATA (line
), nbytes
);
3029 memcpy (p
, bool_vector_data (line
), nbytes
);
3032 else if (STRINGP (data
))
3033 bits
= SSDATA (data
);
3035 bits
= (char *) bool_vector_data (data
);
3041 /* Windows mono bitmaps are reversed compared with X. */
3042 invertedBits
= bits
;
3043 nbytes
= (img
->width
+ BITS_PER_CHAR
- 1) / BITS_PER_CHAR
3045 bits
= alloca (nbytes
);
3046 for (i
= 0; i
< nbytes
; i
++)
3047 bits
[i
] = XBM_BIT_SHUFFLE (invertedBits
[i
]);
3050 /* Create the pixmap. */
3052 if (x_check_image_size (0, img
->width
, img
->height
))
3053 Create_Pixmap_From_Bitmap_Data (f
, img
, bits
,
3054 foreground
, background
,
3055 non_default_colors
);
3057 img
->pixmap
= NO_PIXMAP
;
3063 image_error ("Unable to create pixmap for XBM image `%s'",
3065 x_clear_image (f
, img
);
3075 /***********************************************************************
3077 ***********************************************************************/
3079 #if defined (HAVE_XPM) || defined (HAVE_NS)
3081 static bool xpm_image_p (Lisp_Object object
);
3082 static bool xpm_load (struct frame
*f
, struct image
*img
);
3084 #endif /* HAVE_XPM || HAVE_NS */
3088 /* Indicate to xpm.h that we don't have Xlib. */
3090 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3091 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3092 #define XColor xpm_XColor
3093 #define XImage xpm_XImage
3094 #define Display xpm_Display
3095 #define PIXEL_ALREADY_TYPEDEFED
3096 #include "X11/xpm.h"
3101 #undef PIXEL_ALREADY_TYPEDEFED
3103 #include "X11/xpm.h"
3104 #endif /* HAVE_NTGUI */
3105 #endif /* HAVE_XPM */
3107 #if defined (HAVE_XPM) || defined (HAVE_NS)
3108 /* The symbol `xpm' identifying XPM-format images. */
3110 static Lisp_Object Qxpm
;
3112 /* Indices of image specification fields in xpm_format, below. */
3114 enum xpm_keyword_index
3130 /* Vector of image_keyword structures describing the format
3131 of valid XPM image specifications. */
3133 static const struct image_keyword xpm_format
[XPM_LAST
] =
3135 {":type", IMAGE_SYMBOL_VALUE
, 1},
3136 {":file", IMAGE_STRING_VALUE
, 0},
3137 {":data", IMAGE_STRING_VALUE
, 0},
3138 {":ascent", IMAGE_ASCENT_VALUE
, 0},
3139 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
3140 {":relief", IMAGE_INTEGER_VALUE
, 0},
3141 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3142 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3143 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3144 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
3145 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
3148 #if defined HAVE_NTGUI && defined WINDOWSNT
3149 static bool init_xpm_functions (void);
3151 #define init_xpm_functions NULL
3154 /* Structure describing the image type XPM. */
3156 static struct image_type xpm_type
=
3166 #ifdef HAVE_X_WINDOWS
3168 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3169 functions for allocating image colors. Our own functions handle
3170 color allocation failures more gracefully than the ones on the XPM
3173 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3174 #define ALLOC_XPM_COLORS
3176 #endif /* HAVE_X_WINDOWS */
3178 #ifdef ALLOC_XPM_COLORS
3180 static struct xpm_cached_color
*xpm_cache_color (struct frame
*, char *,
3183 /* An entry in a hash table used to cache color definitions of named
3184 colors. This cache is necessary to speed up XPM image loading in
3185 case we do color allocations ourselves. Without it, we would need
3186 a call to XParseColor per pixel in the image. */
3188 struct xpm_cached_color
3190 /* Next in collision chain. */
3191 struct xpm_cached_color
*next
;
3193 /* Color definition (RGB and pixel color). */
3197 char name
[FLEXIBLE_ARRAY_MEMBER
];
3200 /* The hash table used for the color cache, and its bucket vector
3203 #define XPM_COLOR_CACHE_BUCKETS 1001
3204 static struct xpm_cached_color
**xpm_color_cache
;
3206 /* Initialize the color cache. */
3209 xpm_init_color_cache (struct frame
*f
, XpmAttributes
*attrs
)
3211 size_t nbytes
= XPM_COLOR_CACHE_BUCKETS
* sizeof *xpm_color_cache
;
3212 xpm_color_cache
= xzalloc (nbytes
);
3213 init_color_table ();
3215 if (attrs
->valuemask
& XpmColorSymbols
)
3220 for (i
= 0; i
< attrs
->numsymbols
; ++i
)
3221 if (XParseColor (FRAME_X_DISPLAY (f
), FRAME_X_COLORMAP (f
),
3222 attrs
->colorsymbols
[i
].value
, &color
))
3224 color
.pixel
= lookup_rgb_color (f
, color
.red
, color
.green
,
3226 xpm_cache_color (f
, attrs
->colorsymbols
[i
].name
, &color
, -1);
3231 /* Free the color cache. */
3234 xpm_free_color_cache (void)
3236 struct xpm_cached_color
*p
, *next
;
3239 for (i
= 0; i
< XPM_COLOR_CACHE_BUCKETS
; ++i
)
3240 for (p
= xpm_color_cache
[i
]; p
; p
= next
)
3246 xfree (xpm_color_cache
);
3247 xpm_color_cache
= NULL
;
3248 free_color_table ();
3251 /* Return the bucket index for color named COLOR_NAME in the color
3255 xpm_color_bucket (char *color_name
)
3257 EMACS_UINT hash
= hash_string (color_name
, strlen (color_name
));
3258 return hash
% XPM_COLOR_CACHE_BUCKETS
;
3262 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3263 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3266 static struct xpm_cached_color
*
3267 xpm_cache_color (struct frame
*f
, char *color_name
, XColor
*color
, int bucket
)
3270 struct xpm_cached_color
*p
;
3273 bucket
= xpm_color_bucket (color_name
);
3275 nbytes
= offsetof (struct xpm_cached_color
, name
) + strlen (color_name
) + 1;
3276 p
= xmalloc (nbytes
);
3277 strcpy (p
->name
, color_name
);
3279 p
->next
= xpm_color_cache
[bucket
];
3280 xpm_color_cache
[bucket
] = p
;
3284 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3285 return the cached definition in *COLOR. Otherwise, make a new
3286 entry in the cache and allocate the color. Value is false if color
3287 allocation failed. */
3290 xpm_lookup_color (struct frame
*f
, char *color_name
, XColor
*color
)
3292 struct xpm_cached_color
*p
;
3293 int h
= xpm_color_bucket (color_name
);
3295 for (p
= xpm_color_cache
[h
]; p
; p
= p
->next
)
3296 if (strcmp (p
->name
, color_name
) == 0)
3301 else if (XParseColor (FRAME_X_DISPLAY (f
), FRAME_X_COLORMAP (f
),
3304 color
->pixel
= lookup_rgb_color (f
, color
->red
, color
->green
,
3306 p
= xpm_cache_color (f
, color_name
, color
, h
);
3308 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3309 with transparency, and it's useful. */
3310 else if (strcmp ("opaque", color_name
) == 0)
3312 memset (color
, 0, sizeof (XColor
)); /* Is this necessary/correct? */
3313 color
->pixel
= FRAME_FOREGROUND_PIXEL (f
);
3314 p
= xpm_cache_color (f
, color_name
, color
, h
);
3321 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3322 CLOSURE is a pointer to the frame on which we allocate the
3323 color. Return in *COLOR the allocated color. Value is non-zero
3327 xpm_alloc_color (Display
*dpy
, Colormap cmap
, char *color_name
, XColor
*color
,
3330 return xpm_lookup_color (closure
, color_name
, color
);
3334 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3335 is a pointer to the frame on which we allocate the color. Value is
3336 non-zero if successful. */
3339 xpm_free_colors (Display
*dpy
, Colormap cmap
, Pixel
*pixels
, int npixels
, void *closure
)
3344 #endif /* ALLOC_XPM_COLORS */
3349 /* XPM library details. */
3351 DEF_IMGLIB_FN (void, XpmFreeAttributes
, (XpmAttributes
*));
3352 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer
, (Display
*, char *, xpm_XImage
**,
3353 xpm_XImage
**, XpmAttributes
*));
3354 DEF_IMGLIB_FN (int, XpmReadFileToImage
, (Display
*, char *, xpm_XImage
**,
3355 xpm_XImage
**, XpmAttributes
*));
3356 DEF_IMGLIB_FN (void, XImageFree
, (xpm_XImage
*));
3359 init_xpm_functions (void)
3363 if (!(library
= w32_delayed_load (Qxpm
)))
3366 LOAD_IMGLIB_FN (library
, XpmFreeAttributes
);
3367 LOAD_IMGLIB_FN (library
, XpmCreateImageFromBuffer
);
3368 LOAD_IMGLIB_FN (library
, XpmReadFileToImage
);
3369 LOAD_IMGLIB_FN (library
, XImageFree
);
3373 #endif /* WINDOWSNT */
3375 #if defined HAVE_NTGUI && !defined WINDOWSNT
3376 /* Glue for code below */
3377 #define fn_XpmReadFileToImage XpmReadFileToImage
3378 #define fn_XpmCreateImageFromBuffer XpmCreateImageFromBuffer
3379 #define fn_XImageFree XImageFree
3380 #define fn_XpmFreeAttributes XpmFreeAttributes
3381 #endif /* HAVE_NTGUI && !WINDOWSNT */
3383 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3384 for XPM images. Such a list must consist of conses whose car and
3388 xpm_valid_color_symbols_p (Lisp_Object color_symbols
)
3390 while (CONSP (color_symbols
))
3392 Lisp_Object sym
= XCAR (color_symbols
);
3394 || !STRINGP (XCAR (sym
))
3395 || !STRINGP (XCDR (sym
)))
3397 color_symbols
= XCDR (color_symbols
);
3400 return NILP (color_symbols
);
3404 /* Value is true if OBJECT is a valid XPM image specification. */
3407 xpm_image_p (Lisp_Object object
)
3409 struct image_keyword fmt
[XPM_LAST
];
3410 memcpy (fmt
, xpm_format
, sizeof fmt
);
3411 return (parse_image_spec (object
, fmt
, XPM_LAST
, Qxpm
)
3412 /* Either `:file' or `:data' must be present. */
3413 && fmt
[XPM_FILE
].count
+ fmt
[XPM_DATA
].count
== 1
3414 /* Either no `:color-symbols' or it's a list of conses
3415 whose car and cdr are strings. */
3416 && (fmt
[XPM_COLOR_SYMBOLS
].count
== 0
3417 || xpm_valid_color_symbols_p (fmt
[XPM_COLOR_SYMBOLS
].value
)));
3420 #endif /* HAVE_XPM || HAVE_NS */
3422 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3424 x_create_bitmap_from_xpm_data (struct frame
*f
, const char **bits
)
3426 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
3429 XpmAttributes attrs
;
3430 Pixmap bitmap
, mask
;
3432 memset (&attrs
, 0, sizeof attrs
);
3434 attrs
.visual
= FRAME_X_VISUAL (f
);
3435 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3436 attrs
.valuemask
|= XpmVisual
;
3437 attrs
.valuemask
|= XpmColormap
;
3439 rc
= XpmCreatePixmapFromData (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3440 (char **) bits
, &bitmap
, &mask
, &attrs
);
3441 if (rc
!= XpmSuccess
)
3443 XpmFreeAttributes (&attrs
);
3447 id
= x_allocate_bitmap_record (f
);
3448 dpyinfo
->bitmaps
[id
- 1].pixmap
= bitmap
;
3449 dpyinfo
->bitmaps
[id
- 1].have_mask
= true;
3450 dpyinfo
->bitmaps
[id
- 1].mask
= mask
;
3451 dpyinfo
->bitmaps
[id
- 1].file
= NULL
;
3452 dpyinfo
->bitmaps
[id
- 1].height
= attrs
.height
;
3453 dpyinfo
->bitmaps
[id
- 1].width
= attrs
.width
;
3454 dpyinfo
->bitmaps
[id
- 1].depth
= attrs
.depth
;
3455 dpyinfo
->bitmaps
[id
- 1].refcount
= 1;
3457 XpmFreeAttributes (&attrs
);
3460 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3462 /* Load image IMG which will be displayed on frame F. Value is
3463 true if successful. */
3468 xpm_load (struct frame
*f
, struct image
*img
)
3471 XpmAttributes attrs
;
3472 Lisp_Object specified_file
, color_symbols
;
3475 xpm_XImage
* xpm_image
= NULL
, * xpm_mask
= NULL
;
3476 #endif /* HAVE_NTGUI */
3478 /* Configure the XPM lib. Use the visual of frame F. Allocate
3479 close colors. Return colors allocated. */
3480 memset (&attrs
, 0, sizeof attrs
);
3483 attrs
.visual
= FRAME_X_VISUAL (f
);
3484 attrs
.colormap
= FRAME_X_COLORMAP (f
);
3485 attrs
.valuemask
|= XpmVisual
;
3486 attrs
.valuemask
|= XpmColormap
;
3487 #endif /* HAVE_NTGUI */
3489 #ifdef ALLOC_XPM_COLORS
3490 /* Allocate colors with our own functions which handle
3491 failing color allocation more gracefully. */
3492 attrs
.color_closure
= f
;
3493 attrs
.alloc_color
= xpm_alloc_color
;
3494 attrs
.free_colors
= xpm_free_colors
;
3495 attrs
.valuemask
|= XpmAllocColor
| XpmFreeColors
| XpmColorClosure
;
3496 #else /* not ALLOC_XPM_COLORS */
3497 /* Let the XPM lib allocate colors. */
3498 attrs
.valuemask
|= XpmReturnAllocPixels
;
3499 #ifdef XpmAllocCloseColors
3500 attrs
.alloc_close_colors
= 1;
3501 attrs
.valuemask
|= XpmAllocCloseColors
;
3502 #else /* not XpmAllocCloseColors */
3503 attrs
.closeness
= 600;
3504 attrs
.valuemask
|= XpmCloseness
;
3505 #endif /* not XpmAllocCloseColors */
3506 #endif /* ALLOC_XPM_COLORS */
3508 /* If image specification contains symbolic color definitions, add
3509 these to `attrs'. */
3510 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
3511 if (CONSP (color_symbols
))
3514 XpmColorSymbol
*xpm_syms
;
3517 attrs
.valuemask
|= XpmColorSymbols
;
3519 /* Count number of symbols. */
3520 attrs
.numsymbols
= 0;
3521 for (tail
= color_symbols
; CONSP (tail
); tail
= XCDR (tail
))
3524 /* Allocate an XpmColorSymbol array. */
3525 size
= attrs
.numsymbols
* sizeof *xpm_syms
;
3526 xpm_syms
= alloca (size
);
3527 memset (xpm_syms
, 0, size
);
3528 attrs
.colorsymbols
= xpm_syms
;
3530 /* Fill the color symbol array. */
3531 for (tail
= color_symbols
, i
= 0;
3533 ++i
, tail
= XCDR (tail
))
3537 char *empty_string
= (char *) "";
3539 if (!CONSP (XCAR (tail
)))
3541 xpm_syms
[i
].name
= empty_string
;
3542 xpm_syms
[i
].value
= empty_string
;
3545 name
= XCAR (XCAR (tail
));
3546 color
= XCDR (XCAR (tail
));
3549 xpm_syms
[i
].name
= alloca (SCHARS (name
) + 1);
3550 strcpy (xpm_syms
[i
].name
, SSDATA (name
));
3553 xpm_syms
[i
].name
= empty_string
;
3554 if (STRINGP (color
))
3556 xpm_syms
[i
].value
= alloca (SCHARS (color
) + 1);
3557 strcpy (xpm_syms
[i
].value
, SSDATA (color
));
3560 xpm_syms
[i
].value
= empty_string
;
3564 /* Create a pixmap for the image, either from a file, or from a
3565 string buffer containing data in the same format as an XPM file. */
3566 #ifdef ALLOC_XPM_COLORS
3567 xpm_init_color_cache (f
, &attrs
);
3570 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
3574 HDC frame_dc
= get_frame_dc (f
);
3575 hdc
= CreateCompatibleDC (frame_dc
);
3576 release_frame_dc (f
, frame_dc
);
3578 #endif /* HAVE_NTGUI */
3580 if (STRINGP (specified_file
))
3582 Lisp_Object file
= x_find_image_file (specified_file
);
3583 if (!STRINGP (file
))
3585 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
3586 #ifdef ALLOC_XPM_COLORS
3587 xpm_free_color_cache ();
3594 /* FILE is encoded in UTF-8, but image libraries on Windows
3595 support neither UTF-8 nor UTF-16 encoded file names. So we
3596 need to re-encode it in ANSI. */
3597 file
= ansi_encode_filename (file
);
3599 /* XpmReadFileToPixmap is not available in the Windows port of
3600 libxpm. But XpmReadFileToImage almost does what we want. */
3601 rc
= fn_XpmReadFileToImage (&hdc
, SDATA (file
),
3602 &xpm_image
, &xpm_mask
,
3605 rc
= XpmReadFileToImage (FRAME_X_DISPLAY (f
), SSDATA (file
),
3606 &img
->ximg
, &img
->mask_img
,
3608 #endif /* HAVE_NTGUI */
3612 Lisp_Object buffer
= image_spec_value (img
->spec
, QCdata
, NULL
);
3613 if (!STRINGP (buffer
))
3615 image_error ("Invalid image data `%s'", buffer
, Qnil
);
3616 #ifdef ALLOC_XPM_COLORS
3617 xpm_free_color_cache ();
3622 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3623 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3624 rc
= fn_XpmCreateImageFromBuffer (&hdc
, SDATA (buffer
),
3625 &xpm_image
, &xpm_mask
,
3628 rc
= XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f
), SSDATA (buffer
),
3629 &img
->ximg
, &img
->mask_img
,
3631 #endif /* HAVE_NTGUI */
3634 #ifdef HAVE_X_WINDOWS
3635 if (rc
== XpmSuccess
)
3637 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3638 img
->ximg
->width
, img
->ximg
->height
,
3640 if (img
->pixmap
== NO_PIXMAP
)
3642 x_clear_image (f
, img
);
3645 else if (img
->mask_img
)
3647 img
->mask
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3648 img
->mask_img
->width
,
3649 img
->mask_img
->height
,
3650 img
->mask_img
->depth
);
3651 if (img
->mask
== NO_PIXMAP
)
3653 x_clear_image (f
, img
);
3660 if (rc
== XpmSuccess
)
3662 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3663 img
->colors
= colors_in_color_table (&img
->ncolors
);
3664 #else /* not ALLOC_XPM_COLORS */
3668 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3669 plus some duplicate attributes. */
3670 if (xpm_image
&& xpm_image
->bitmap
)
3672 img
->pixmap
= xpm_image
->bitmap
;
3673 /* XImageFree in libXpm frees XImage struct without destroying
3674 the bitmap, which is what we want. */
3675 fn_XImageFree (xpm_image
);
3677 if (xpm_mask
&& xpm_mask
->bitmap
)
3679 /* The mask appears to be inverted compared with what we expect.
3680 TODO: invert our expectations. See other places where we
3681 have to invert bits because our idea of masks is backwards. */
3683 old_obj
= SelectObject (hdc
, xpm_mask
->bitmap
);
3685 PatBlt (hdc
, 0, 0, xpm_mask
->width
, xpm_mask
->height
, DSTINVERT
);
3686 SelectObject (hdc
, old_obj
);
3688 img
->mask
= xpm_mask
->bitmap
;
3689 fn_XImageFree (xpm_mask
);
3694 #endif /* HAVE_NTGUI */
3696 /* Remember allocated colors. */
3697 img
->colors
= xnmalloc (attrs
.nalloc_pixels
, sizeof *img
->colors
);
3698 img
->ncolors
= attrs
.nalloc_pixels
;
3699 for (i
= 0; i
< attrs
.nalloc_pixels
; ++i
)
3701 img
->colors
[i
] = attrs
.alloc_pixels
[i
];
3702 #ifdef DEBUG_X_COLORS
3703 register_color (img
->colors
[i
]);
3706 #endif /* not ALLOC_XPM_COLORS */
3708 img
->width
= attrs
.width
;
3709 img
->height
= attrs
.height
;
3710 eassert (img
->width
> 0 && img
->height
> 0);
3712 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3714 fn_XpmFreeAttributes (&attrs
);
3716 XpmFreeAttributes (&attrs
);
3717 #endif /* HAVE_NTGUI */
3719 #ifdef HAVE_X_WINDOWS
3720 /* Maybe fill in the background field while we have ximg handy. */
3721 IMAGE_BACKGROUND (img
, f
, img
->ximg
);
3723 /* Fill in the background_transparent field while we have the
3725 image_background_transparent (img
, f
, img
->mask_img
);
3732 #endif /* HAVE_NTGUI */
3737 image_error ("Error opening XPM file (%s)", img
->spec
, Qnil
);
3740 case XpmFileInvalid
:
3741 image_error ("Invalid XPM file (%s)", img
->spec
, Qnil
);
3745 image_error ("Out of memory (%s)", img
->spec
, Qnil
);
3748 case XpmColorFailed
:
3749 image_error ("Color allocation error (%s)", img
->spec
, Qnil
);
3753 image_error ("Unknown error (%s)", img
->spec
, Qnil
);
3758 #ifdef ALLOC_XPM_COLORS
3759 xpm_free_color_cache ();
3761 return rc
== XpmSuccess
;
3764 #endif /* HAVE_XPM */
3766 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3768 /* XPM support functions for NS where libxpm is not available.
3769 Only XPM version 3 (without any extensions) is supported. */
3771 static void xpm_put_color_table_v (Lisp_Object
, const unsigned char *,
3773 static Lisp_Object
xpm_get_color_table_v (Lisp_Object
,
3774 const unsigned char *, int);
3775 static void xpm_put_color_table_h (Lisp_Object
, const unsigned char *,
3777 static Lisp_Object
xpm_get_color_table_h (Lisp_Object
,
3778 const unsigned char *, int);
3780 /* Tokens returned from xpm_scan. */
3789 /* Scan an XPM data and return a character (< 256) or a token defined
3790 by enum xpm_token above. *S and END are the start (inclusive) and
3791 the end (exclusive) addresses of the data, respectively. Advance
3792 *S while scanning. If token is either XPM_TK_IDENT or
3793 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3794 length of the corresponding token, respectively. */
3797 xpm_scan (const unsigned char **s
,
3798 const unsigned char *end
,
3799 const unsigned char **beg
,
3806 /* Skip white-space. */
3807 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
3810 /* gnus-pointer.xpm uses '-' in its identifier.
3811 sb-dir-plus.xpm uses '+' in its identifier. */
3812 if (c_isalpha (c
) || c
== '_' || c
== '-' || c
== '+')
3816 && (c
= **s
, c_isalnum (c
)
3817 || c
== '_' || c
== '-' || c
== '+'))
3820 return XPM_TK_IDENT
;
3825 while (*s
< end
&& **s
!= '"')
3830 return XPM_TK_STRING
;
3834 if (*s
< end
&& **s
== '*')
3836 /* C-style comment. */
3840 while (*s
< end
&& *(*s
)++ != '*')
3843 while (*s
< end
&& **s
!= '/');
3857 /* Functions for color table lookup in XPM data. A key is a string
3858 specifying the color of each pixel in XPM data. A value is either
3859 an integer that specifies a pixel color, Qt that specifies
3860 transparency, or Qnil for the unspecified color. If the length of
3861 the key string is one, a vector is used as a table. Otherwise, a
3862 hash table is used. */
3865 xpm_make_color_table_v (void (**put_func
) (Lisp_Object
,
3866 const unsigned char *,
3869 Lisp_Object (**get_func
) (Lisp_Object
,
3870 const unsigned char *,
3873 *put_func
= xpm_put_color_table_v
;
3874 *get_func
= xpm_get_color_table_v
;
3875 return Fmake_vector (make_number (256), Qnil
);
3879 xpm_put_color_table_v (Lisp_Object color_table
,
3880 const unsigned char *chars_start
,
3884 ASET (color_table
, *chars_start
, color
);
3888 xpm_get_color_table_v (Lisp_Object color_table
,
3889 const unsigned char *chars_start
,
3892 return AREF (color_table
, *chars_start
);
3896 xpm_make_color_table_h (void (**put_func
) (Lisp_Object
,
3897 const unsigned char *,
3900 Lisp_Object (**get_func
) (Lisp_Object
,
3901 const unsigned char *,
3904 *put_func
= xpm_put_color_table_h
;
3905 *get_func
= xpm_get_color_table_h
;
3906 return make_hash_table (hashtest_equal
, make_number (DEFAULT_HASH_SIZE
),
3907 make_float (DEFAULT_REHASH_SIZE
),
3908 make_float (DEFAULT_REHASH_THRESHOLD
),
3913 xpm_put_color_table_h (Lisp_Object color_table
,
3914 const unsigned char *chars_start
,
3918 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
3919 EMACS_UINT hash_code
;
3920 Lisp_Object chars
= make_unibyte_string (chars_start
, chars_len
);
3922 hash_lookup (table
, chars
, &hash_code
);
3923 hash_put (table
, chars
, color
, hash_code
);
3927 xpm_get_color_table_h (Lisp_Object color_table
,
3928 const unsigned char *chars_start
,
3931 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
3933 hash_lookup (table
, make_unibyte_string (chars_start
, chars_len
), NULL
);
3935 return i
>= 0 ? HASH_VALUE (table
, i
) : Qnil
;
3938 enum xpm_color_key
{
3946 static const char xpm_color_key_strings
[][4] = {"s", "m", "g4", "g", "c"};
3949 xpm_str_to_color_key (const char *s
)
3954 i
< sizeof xpm_color_key_strings
/ sizeof xpm_color_key_strings
[0];
3956 if (strcmp (xpm_color_key_strings
[i
], s
) == 0)
3962 xpm_load_image (struct frame
*f
,
3964 const unsigned char *contents
,
3965 const unsigned char *end
)
3967 const unsigned char *s
= contents
, *beg
, *str
;
3968 unsigned char buffer
[BUFSIZ
];
3969 int width
, height
, x
, y
;
3970 int num_colors
, chars_per_pixel
;
3973 void (*put_color_table
) (Lisp_Object
, const unsigned char *, int, Lisp_Object
);
3974 Lisp_Object (*get_color_table
) (Lisp_Object
, const unsigned char *, int);
3975 Lisp_Object frame
, color_symbols
, color_table
;
3977 bool have_mask
= false;
3978 XImagePtr ximg
= NULL
, mask_img
= NULL
;
3981 LA1 = xpm_scan (&s, end, &beg, &len)
3983 #define expect(TOKEN) \
3986 if (LA1 != (TOKEN)) \
3992 #define expect_ident(IDENT) \
3993 if (LA1 == XPM_TK_IDENT \
3994 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3999 if (!(end
- s
>= 9 && memcmp (s
, "/* XPM */", 9) == 0))
4003 expect_ident ("static");
4004 expect_ident ("char");
4006 expect (XPM_TK_IDENT
);
4011 expect (XPM_TK_STRING
);
4014 memcpy (buffer
, beg
, len
);
4016 if (sscanf (buffer
, "%d %d %d %d", &width
, &height
,
4017 &num_colors
, &chars_per_pixel
) != 4
4018 || width
<= 0 || height
<= 0
4019 || num_colors
<= 0 || chars_per_pixel
<= 0)
4022 if (!check_image_size (f
, width
, height
))
4024 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
4028 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0)
4030 || !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
4035 image_error ("Image too large", Qnil
, Qnil
);
4041 XSETFRAME (frame
, f
);
4042 if (!NILP (Fxw_display_color_p (frame
)))
4043 best_key
= XPM_COLOR_KEY_C
;
4044 else if (!NILP (Fx_display_grayscale_p (frame
)))
4045 best_key
= (XFASTINT (Fx_display_planes (frame
)) > 2
4046 ? XPM_COLOR_KEY_G
: XPM_COLOR_KEY_G4
);
4048 best_key
= XPM_COLOR_KEY_M
;
4050 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
4051 if (chars_per_pixel
== 1)
4052 color_table
= xpm_make_color_table_v (&put_color_table
,
4055 color_table
= xpm_make_color_table_h (&put_color_table
,
4058 while (num_colors
-- > 0)
4060 char *color
, *max_color
;
4061 int key
, next_key
, max_key
= 0;
4062 Lisp_Object symbol_color
= Qnil
, color_val
;
4065 expect (XPM_TK_STRING
);
4066 if (len
<= chars_per_pixel
|| len
>= BUFSIZ
+ chars_per_pixel
)
4068 memcpy (buffer
, beg
+ chars_per_pixel
, len
- chars_per_pixel
);
4069 buffer
[len
- chars_per_pixel
] = '\0';
4071 str
= strtok (buffer
, " \t");
4074 key
= xpm_str_to_color_key (str
);
4079 color
= strtok (NULL
, " \t");
4083 while ((str
= strtok (NULL
, " \t")) != NULL
)
4085 next_key
= xpm_str_to_color_key (str
);
4088 color
[strlen (color
)] = ' ';
4091 if (key
== XPM_COLOR_KEY_S
)
4093 if (NILP (symbol_color
))
4094 symbol_color
= build_string (color
);
4096 else if (max_key
< key
&& key
<= best_key
)
4106 if (!NILP (color_symbols
) && !NILP (symbol_color
))
4108 Lisp_Object specified_color
= Fassoc (symbol_color
, color_symbols
);
4110 if (CONSP (specified_color
) && STRINGP (XCDR (specified_color
)))
4112 if (xstrcasecmp (SSDATA (XCDR (specified_color
)), "None") == 0)
4114 else if (x_defined_color (f
, SSDATA (XCDR (specified_color
)),
4116 color_val
= make_number (cdef
.pixel
);
4119 if (NILP (color_val
) && max_key
> 0)
4121 if (xstrcasecmp (max_color
, "None") == 0)
4123 else if (x_defined_color (f
, max_color
, &cdef
, 0))
4124 color_val
= make_number (cdef
.pixel
);
4126 if (!NILP (color_val
))
4127 (*put_color_table
) (color_table
, beg
, chars_per_pixel
, color_val
);
4132 for (y
= 0; y
< height
; y
++)
4134 expect (XPM_TK_STRING
);
4136 if (len
< width
* chars_per_pixel
)
4138 for (x
= 0; x
< width
; x
++, str
+= chars_per_pixel
)
4140 Lisp_Object color_val
=
4141 (*get_color_table
) (color_table
, str
, chars_per_pixel
);
4143 XPutPixel (ximg
, x
, y
,
4144 (INTEGERP (color_val
) ? XINT (color_val
)
4145 : FRAME_FOREGROUND_PIXEL (f
)));
4147 XPutPixel (mask_img
, x
, y
,
4148 (!EQ (color_val
, Qt
) ? PIX_MASK_DRAW
4149 : (have_mask
= true, PIX_MASK_RETAIN
)));
4151 if (EQ (color_val
, Qt
))
4152 ns_set_alpha (ximg
, x
, y
, 0);
4160 img
->height
= height
;
4162 /* Maybe fill in the background field while we have ximg handy. */
4163 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
4164 IMAGE_BACKGROUND (img
, f
, ximg
);
4166 image_put_x_image (f
, img
, ximg
, 0);
4170 /* Fill in the background_transparent field while we have the
4172 image_background_transparent (img
, f
, mask_img
);
4174 image_put_x_image (f
, img
, mask_img
, 1);
4178 x_destroy_x_image (mask_img
);
4179 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4185 image_error ("Invalid XPM file (%s)", img
->spec
, Qnil
);
4186 x_destroy_x_image (ximg
);
4187 x_destroy_x_image (mask_img
);
4188 x_clear_image (f
, img
);
4197 xpm_load (struct frame
*f
,
4201 Lisp_Object file_name
;
4203 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4204 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
4205 if (STRINGP (file_name
))
4208 unsigned char *contents
;
4211 file
= x_find_image_file (file_name
);
4212 if (!STRINGP (file
))
4214 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
4218 contents
= slurp_file (SSDATA (file
), &size
);
4219 if (contents
== NULL
)
4221 image_error ("Error loading XPM image `%s'", img
->spec
, Qnil
);
4225 success_p
= xpm_load_image (f
, img
, contents
, contents
+ size
);
4232 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
4233 if (!STRINGP (data
))
4235 image_error ("Invalid image data `%s'", data
, Qnil
);
4238 success_p
= xpm_load_image (f
, img
, SDATA (data
),
4239 SDATA (data
) + SBYTES (data
));
4245 #endif /* HAVE_NS && !HAVE_XPM */
4249 /***********************************************************************
4251 ***********************************************************************/
4253 #ifdef COLOR_TABLE_SUPPORT
4255 /* An entry in the color table mapping an RGB color to a pixel color. */
4260 unsigned long pixel
;
4262 /* Next in color table collision list. */
4263 struct ct_color
*next
;
4266 /* The bucket vector size to use. Must be prime. */
4270 /* Value is a hash of the RGB color given by R, G, and B. */
4272 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4274 /* The color hash table. */
4276 static struct ct_color
**ct_table
;
4278 /* Number of entries in the color table. */
4280 static int ct_colors_allocated
;
4283 ct_colors_allocated_max
=
4285 min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof (unsigned long))
4288 /* Initialize the color table. */
4291 init_color_table (void)
4293 int size
= CT_SIZE
* sizeof (*ct_table
);
4294 ct_table
= xzalloc (size
);
4295 ct_colors_allocated
= 0;
4299 /* Free memory associated with the color table. */
4302 free_color_table (void)
4305 struct ct_color
*p
, *next
;
4307 for (i
= 0; i
< CT_SIZE
; ++i
)
4308 for (p
= ct_table
[i
]; p
; p
= next
)
4319 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4320 entry for that color already is in the color table, return the
4321 pixel color of that entry. Otherwise, allocate a new color for R,
4322 G, B, and make an entry in the color table. */
4324 static unsigned long
4325 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4327 unsigned hash
= CT_HASH_RGB (r
, g
, b
);
4328 int i
= hash
% CT_SIZE
;
4330 Display_Info
*dpyinfo
;
4332 /* Handle TrueColor visuals specially, which improves performance by
4333 two orders of magnitude. Freeing colors on TrueColor visuals is
4334 a nop, and pixel colors specify RGB values directly. See also
4335 the Xlib spec, chapter 3.1. */
4336 dpyinfo
= FRAME_DISPLAY_INFO (f
);
4337 if (dpyinfo
->red_bits
> 0)
4339 unsigned long pr
, pg
, pb
;
4341 /* Apply gamma-correction like normal color allocation does. */
4345 color
.red
= r
, color
.green
= g
, color
.blue
= b
;
4346 gamma_correct (f
, &color
);
4347 r
= color
.red
, g
= color
.green
, b
= color
.blue
;
4350 /* Scale down RGB values to the visual's bits per RGB, and shift
4351 them to the right position in the pixel color. Note that the
4352 original RGB values are 16-bit values, as usual in X. */
4353 pr
= (r
>> (16 - dpyinfo
->red_bits
)) << dpyinfo
->red_offset
;
4354 pg
= (g
>> (16 - dpyinfo
->green_bits
)) << dpyinfo
->green_offset
;
4355 pb
= (b
>> (16 - dpyinfo
->blue_bits
)) << dpyinfo
->blue_offset
;
4357 /* Assemble the pixel color. */
4358 return pr
| pg
| pb
;
4361 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4362 if (p
->r
== r
&& p
->g
== g
&& p
->b
== b
)
4368 #ifdef HAVE_X_WINDOWS
4376 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4377 return FRAME_FOREGROUND_PIXEL (f
);
4379 #ifdef HAVE_X_WINDOWS
4384 cmap
= FRAME_X_COLORMAP (f
);
4385 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4388 ++ct_colors_allocated
;
4389 p
= xmalloc (sizeof *p
);
4393 p
->pixel
= color
.pixel
;
4394 p
->next
= ct_table
[i
];
4398 return FRAME_FOREGROUND_PIXEL (f
);
4402 color
= PALETTERGB (r
, g
, b
);
4404 color
= RGB_TO_ULONG (r
, g
, b
);
4405 #endif /* HAVE_NTGUI */
4406 ++ct_colors_allocated
;
4407 p
= xmalloc (sizeof *p
);
4412 p
->next
= ct_table
[i
];
4414 #endif /* HAVE_X_WINDOWS */
4422 /* Look up pixel color PIXEL which is used on frame F in the color
4423 table. If not already present, allocate it. Value is PIXEL. */
4425 static unsigned long
4426 lookup_pixel_color (struct frame
*f
, unsigned long pixel
)
4428 int i
= pixel
% CT_SIZE
;
4431 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4432 if (p
->pixel
== pixel
)
4441 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4442 return FRAME_FOREGROUND_PIXEL (f
);
4444 #ifdef HAVE_X_WINDOWS
4445 cmap
= FRAME_X_COLORMAP (f
);
4446 color
.pixel
= pixel
;
4447 x_query_color (f
, &color
);
4448 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4451 cmap
= DefaultColormapOfScreen (FRAME_X_SCREEN (f
));
4452 color
.pixel
= pixel
;
4453 XQueryColor (NULL
, cmap
, &color
);
4454 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4456 #endif /* HAVE_X_WINDOWS */
4460 ++ct_colors_allocated
;
4462 p
= xmalloc (sizeof *p
);
4467 p
->next
= ct_table
[i
];
4471 return FRAME_FOREGROUND_PIXEL (f
);
4477 /* Value is a vector of all pixel colors contained in the color table,
4478 allocated via xmalloc. Set *N to the number of colors. */
4480 static unsigned long *
4481 colors_in_color_table (int *n
)
4485 unsigned long *colors
;
4487 if (ct_colors_allocated
== 0)
4494 colors
= xmalloc (ct_colors_allocated
* sizeof *colors
);
4495 *n
= ct_colors_allocated
;
4497 for (i
= j
= 0; i
< CT_SIZE
; ++i
)
4498 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4499 colors
[j
++] = p
->pixel
;
4505 #else /* COLOR_TABLE_SUPPORT */
4507 static unsigned long
4508 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4510 unsigned long pixel
;
4513 pixel
= PALETTERGB (r
>> 8, g
>> 8, b
>> 8);
4514 #endif /* HAVE_NTGUI */
4517 pixel
= RGB_TO_ULONG (r
>> 8, g
>> 8, b
>> 8);
4518 #endif /* HAVE_NS */
4523 init_color_table (void)
4526 #endif /* COLOR_TABLE_SUPPORT */
4529 /***********************************************************************
4531 ***********************************************************************/
4533 /* Edge detection matrices for different edge-detection
4536 static int emboss_matrix
[9] = {
4538 2, -1, 0, /* y - 1 */
4540 0, 1, -2 /* y + 1 */
4543 static int laplace_matrix
[9] = {
4545 1, 0, 0, /* y - 1 */
4547 0, 0, -1 /* y + 1 */
4550 /* Value is the intensity of the color whose red/green/blue values
4553 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4556 /* On frame F, return an array of XColor structures describing image
4557 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4558 means also fill the red/green/blue members of the XColor
4559 structures. Value is a pointer to the array of XColors structures,
4560 allocated with xmalloc; it must be freed by the caller. */
4563 x_to_xcolors (struct frame
*f
, struct image
*img
, bool rgb_p
)
4567 XImagePtr_or_DC ximg
;
4570 #endif /* HAVE_NTGUI */
4572 if (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *colors
/ img
->width
< img
->height
)
4573 memory_full (SIZE_MAX
);
4574 colors
= xmalloc (sizeof *colors
* img
->width
* img
->height
);
4576 /* Get the X image or create a memory device context for IMG. */
4577 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4579 /* Fill the `pixel' members of the XColor array. I wished there
4580 were an easy and portable way to circumvent XGetPixel. */
4582 for (y
= 0; y
< img
->height
; ++y
)
4584 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4586 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4587 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4589 x_query_colors (f
, row
, img
->width
);
4593 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4595 /* W32_TODO: palette support needed here? */
4596 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4599 p
->red
= RED16_FROM_ULONG (p
->pixel
);
4600 p
->green
= GREEN16_FROM_ULONG (p
->pixel
);
4601 p
->blue
= BLUE16_FROM_ULONG (p
->pixel
);
4604 #endif /* HAVE_X_WINDOWS */
4607 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
4614 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4615 created with CreateDIBSection, with the pointer to the bit values
4616 stored in ximg->data. */
4619 XPutPixel (XImagePtr ximg
, int x
, int y
, COLORREF color
)
4621 int width
= ximg
->info
.bmiHeader
.biWidth
;
4622 unsigned char * pixel
;
4624 /* True color images. */
4625 if (ximg
->info
.bmiHeader
.biBitCount
== 24)
4627 int rowbytes
= width
* 3;
4628 /* Ensure scanlines are aligned on 4 byte boundaries. */
4630 rowbytes
+= 4 - (rowbytes
% 4);
4632 pixel
= ximg
->data
+ y
* rowbytes
+ x
* 3;
4633 /* Windows bitmaps are in BGR order. */
4634 *pixel
= GetBValue (color
);
4635 *(pixel
+ 1) = GetGValue (color
);
4636 *(pixel
+ 2) = GetRValue (color
);
4638 /* Monochrome images. */
4639 else if (ximg
->info
.bmiHeader
.biBitCount
== 1)
4641 int rowbytes
= width
/ 8;
4642 /* Ensure scanlines are aligned on 4 byte boundaries. */
4644 rowbytes
+= 4 - (rowbytes
% 4);
4645 pixel
= ximg
->data
+ y
* rowbytes
+ x
/ 8;
4646 /* Filter out palette info. */
4647 if (color
& 0x00ffffff)
4648 *pixel
= *pixel
| (1 << x
% 8);
4650 *pixel
= *pixel
& ~(1 << x
% 8);
4653 image_error ("XPutPixel: palette image not supported", Qnil
, Qnil
);
4656 #endif /* HAVE_NTGUI */
4658 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4659 RGB members are set. F is the frame on which this all happens.
4660 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4663 x_from_xcolors (struct frame
*f
, struct image
*img
, XColor
*colors
)
4666 XImagePtr oimg
= NULL
;
4669 init_color_table ();
4671 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_COLORS
);
4672 image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 0,
4675 for (y
= 0; y
< img
->height
; ++y
)
4676 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4678 unsigned long pixel
;
4679 pixel
= lookup_rgb_color (f
, p
->red
, p
->green
, p
->blue
);
4680 XPutPixel (oimg
, x
, y
, pixel
);
4685 image_put_x_image (f
, img
, oimg
, 0);
4686 #ifdef COLOR_TABLE_SUPPORT
4687 img
->colors
= colors_in_color_table (&img
->ncolors
);
4688 free_color_table ();
4689 #endif /* COLOR_TABLE_SUPPORT */
4693 /* On frame F, perform edge-detection on image IMG.
4695 MATRIX is a nine-element array specifying the transformation
4696 matrix. See emboss_matrix for an example.
4698 COLOR_ADJUST is a color adjustment added to each pixel of the
4702 x_detect_edges (struct frame
*f
, struct image
*img
, int *matrix
, int color_adjust
)
4704 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4708 for (i
= sum
= 0; i
< 9; ++i
)
4709 sum
+= eabs (matrix
[i
]);
4711 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4713 if (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *new / img
->width
< img
->height
)
4714 memory_full (SIZE_MAX
);
4715 new = xmalloc (sizeof *new * img
->width
* img
->height
);
4717 for (y
= 0; y
< img
->height
; ++y
)
4719 p
= COLOR (new, 0, y
);
4720 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4721 p
= COLOR (new, img
->width
- 1, y
);
4722 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4725 for (x
= 1; x
< img
->width
- 1; ++x
)
4727 p
= COLOR (new, x
, 0);
4728 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4729 p
= COLOR (new, x
, img
->height
- 1);
4730 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4733 for (y
= 1; y
< img
->height
- 1; ++y
)
4735 p
= COLOR (new, 1, y
);
4737 for (x
= 1; x
< img
->width
- 1; ++x
, ++p
)
4739 int r
, g
, b
, yy
, xx
;
4742 for (yy
= y
- 1; yy
< y
+ 2; ++yy
)
4743 for (xx
= x
- 1; xx
< x
+ 2; ++xx
, ++i
)
4746 XColor
*t
= COLOR (colors
, xx
, yy
);
4747 r
+= matrix
[i
] * t
->red
;
4748 g
+= matrix
[i
] * t
->green
;
4749 b
+= matrix
[i
] * t
->blue
;
4752 r
= (r
/ sum
+ color_adjust
) & 0xffff;
4753 g
= (g
/ sum
+ color_adjust
) & 0xffff;
4754 b
= (b
/ sum
+ color_adjust
) & 0xffff;
4755 p
->red
= p
->green
= p
->blue
= COLOR_INTENSITY (r
, g
, b
);
4760 x_from_xcolors (f
, img
, new);
4766 /* Perform the pre-defined `emboss' edge-detection on image IMG
4770 x_emboss (struct frame
*f
, struct image
*img
)
4772 x_detect_edges (f
, img
, emboss_matrix
, 0xffff / 2);
4776 /* Transform image IMG which is used on frame F with a Laplace
4777 edge-detection algorithm. The result is an image that can be used
4778 to draw disabled buttons, for example. */
4781 x_laplace (struct frame
*f
, struct image
*img
)
4783 x_detect_edges (f
, img
, laplace_matrix
, 45000);
4787 /* Perform edge-detection on image IMG on frame F, with specified
4788 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4790 MATRIX must be either
4792 - a list of at least 9 numbers in row-major form
4793 - a vector of at least 9 numbers
4795 COLOR_ADJUST nil means use a default; otherwise it must be a
4799 x_edge_detection (struct frame
*f
, struct image
*img
, Lisp_Object matrix
,
4800 Lisp_Object color_adjust
)
4808 i
< 9 && CONSP (matrix
) && NUMBERP (XCAR (matrix
));
4809 ++i
, matrix
= XCDR (matrix
))
4810 trans
[i
] = XFLOATINT (XCAR (matrix
));
4812 else if (VECTORP (matrix
) && ASIZE (matrix
) >= 9)
4814 for (i
= 0; i
< 9 && NUMBERP (AREF (matrix
, i
)); ++i
)
4815 trans
[i
] = XFLOATINT (AREF (matrix
, i
));
4818 if (NILP (color_adjust
))
4819 color_adjust
= make_number (0xffff / 2);
4821 if (i
== 9 && NUMBERP (color_adjust
))
4822 x_detect_edges (f
, img
, trans
, XFLOATINT (color_adjust
));
4826 /* Transform image IMG on frame F so that it looks disabled. */
4829 x_disable_image (struct frame
*f
, struct image
*img
)
4831 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
4833 int n_planes
= dpyinfo
->n_planes
* dpyinfo
->n_cbits
;
4835 int n_planes
= dpyinfo
->n_planes
;
4836 #endif /* HAVE_NTGUI */
4840 /* Color (or grayscale). Convert to gray, and equalize. Just
4841 drawing such images with a stipple can look very odd, so
4842 we're using this method instead. */
4843 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4845 const int h
= 15000;
4846 const int l
= 30000;
4848 for (p
= colors
, end
= colors
+ img
->width
* img
->height
;
4852 int i
= COLOR_INTENSITY (p
->red
, p
->green
, p
->blue
);
4853 int i2
= (0xffff - h
- l
) * i
/ 0xffff + l
;
4854 p
->red
= p
->green
= p
->blue
= i2
;
4857 x_from_xcolors (f
, img
, colors
);
4860 /* Draw a cross over the disabled image, if we must or if we
4862 if (n_planes
< 2 || cross_disabled_images
)
4865 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4867 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4869 Display
*dpy
= FRAME_X_DISPLAY (f
);
4872 image_sync_to_pixmaps (f
, img
);
4873 gc
= XCreateGC (dpy
, img
->pixmap
, 0, NULL
);
4874 XSetForeground (dpy
, gc
, BLACK_PIX_DEFAULT (f
));
4875 XDrawLine (dpy
, img
->pixmap
, gc
, 0, 0,
4876 img
->width
- 1, img
->height
- 1);
4877 XDrawLine (dpy
, img
->pixmap
, gc
, 0, img
->height
- 1,
4883 gc
= XCreateGC (dpy
, img
->mask
, 0, NULL
);
4884 XSetForeground (dpy
, gc
, MaskForeground (f
));
4885 XDrawLine (dpy
, img
->mask
, gc
, 0, 0,
4886 img
->width
- 1, img
->height
- 1);
4887 XDrawLine (dpy
, img
->mask
, gc
, 0, img
->height
- 1,
4891 #endif /* !HAVE_NS */
4896 hdc
= get_frame_dc (f
);
4897 bmpdc
= CreateCompatibleDC (hdc
);
4898 release_frame_dc (f
, hdc
);
4900 prev
= SelectObject (bmpdc
, img
->pixmap
);
4902 SetTextColor (bmpdc
, BLACK_PIX_DEFAULT (f
));
4903 MoveToEx (bmpdc
, 0, 0, NULL
);
4904 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
4905 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
4906 LineTo (bmpdc
, img
->width
- 1, 0);
4910 SelectObject (bmpdc
, img
->mask
);
4911 SetTextColor (bmpdc
, WHITE_PIX_DEFAULT (f
));
4912 MoveToEx (bmpdc
, 0, 0, NULL
);
4913 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
4914 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
4915 LineTo (bmpdc
, img
->width
- 1, 0);
4917 SelectObject (bmpdc
, prev
);
4919 #endif /* HAVE_NTGUI */
4924 /* Build a mask for image IMG which is used on frame F. FILE is the
4925 name of an image file, for error messages. HOW determines how to
4926 determine the background color of IMG. If it is a list '(R G B)',
4927 with R, G, and B being integers >= 0, take that as the color of the
4928 background. Otherwise, determine the background color of IMG
4932 x_build_heuristic_mask (struct frame
*f
, struct image
*img
, Lisp_Object how
)
4934 XImagePtr_or_DC ximg
;
4941 #endif /* HAVE_NTGUI */
4943 bool use_img_background
;
4944 unsigned long bg
= 0;
4947 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4951 /* Create an image and pixmap serving as mask. */
4952 if (! image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 1,
4955 #endif /* !HAVE_NS */
4957 /* Create the bit array serving as mask. */
4958 row_width
= (img
->width
+ 7) / 8;
4959 mask_img
= xzalloc (row_width
* img
->height
);
4960 #endif /* HAVE_NTGUI */
4962 /* Get the X image or create a memory device context for IMG. */
4963 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4965 /* Determine the background color of ximg. If HOW is `(R G B)'
4966 take that as color. Otherwise, use the image's background color. */
4967 use_img_background
= 1;
4973 for (i
= 0; i
< 3 && CONSP (how
) && NATNUMP (XCAR (how
)); ++i
)
4975 rgb
[i
] = XFASTINT (XCAR (how
)) & 0xffff;
4979 if (i
== 3 && NILP (how
))
4981 char color_name
[30];
4982 sprintf (color_name
, "#%04x%04x%04x", rgb
[0], rgb
[1], rgb
[2]);
4985 0x00ffffff & /* Filter out palette info. */
4986 #endif /* HAVE_NTGUI */
4987 x_alloc_image_color (f
, img
, build_string (color_name
), 0));
4988 use_img_background
= 0;
4992 if (use_img_background
)
4993 bg
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
4995 /* Set all bits in mask_img to 1 whose color in ximg is different
4996 from the background color bg. */
4998 for (y
= 0; y
< img
->height
; ++y
)
4999 for (x
= 0; x
< img
->width
; ++x
)
5001 XPutPixel (mask_img
, x
, y
, (XGetPixel (ximg
, x
, y
) != bg
5002 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
));
5004 if (XGetPixel (ximg
, x
, y
) == bg
)
5005 ns_set_alpha (ximg
, x
, y
, 0);
5006 #endif /* HAVE_NS */
5008 /* Fill in the background_transparent field while we have the mask handy. */
5009 image_background_transparent (img
, f
, mask_img
);
5011 /* Put mask_img into the image. */
5012 image_put_x_image (f
, img
, mask_img
, 1);
5013 #endif /* !HAVE_NS */
5015 for (y
= 0; y
< img
->height
; ++y
)
5016 for (x
= 0; x
< img
->width
; ++x
)
5018 COLORREF p
= GetPixel (ximg
, x
, y
);
5020 mask_img
[y
* row_width
+ x
/ 8] |= 1 << (x
% 8);
5023 /* Create the mask image. */
5024 img
->mask
= w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
,
5026 /* Fill in the background_transparent field while we have the mask handy. */
5027 SelectObject (ximg
, img
->mask
);
5028 image_background_transparent (img
, f
, ximg
);
5030 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5032 #endif /* HAVE_NTGUI */
5034 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
5038 /***********************************************************************
5039 PBM (mono, gray, color)
5040 ***********************************************************************/
5042 static bool pbm_image_p (Lisp_Object object
);
5043 static bool pbm_load (struct frame
*f
, struct image
*img
);
5045 /* The symbol `pbm' identifying images of this type. */
5047 static Lisp_Object Qpbm
;
5049 /* Indices of image specification fields in gs_format, below. */
5051 enum pbm_keyword_index
5067 /* Vector of image_keyword structures describing the format
5068 of valid user-defined image specifications. */
5070 static const struct image_keyword pbm_format
[PBM_LAST
] =
5072 {":type", IMAGE_SYMBOL_VALUE
, 1},
5073 {":file", IMAGE_STRING_VALUE
, 0},
5074 {":data", IMAGE_STRING_VALUE
, 0},
5075 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5076 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5077 {":relief", IMAGE_INTEGER_VALUE
, 0},
5078 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5079 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5080 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5081 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
5082 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5085 /* Structure describing the image type `pbm'. */
5087 static struct image_type pbm_type
=
5098 /* Return true if OBJECT is a valid PBM image specification. */
5101 pbm_image_p (Lisp_Object object
)
5103 struct image_keyword fmt
[PBM_LAST
];
5105 memcpy (fmt
, pbm_format
, sizeof fmt
);
5107 if (!parse_image_spec (object
, fmt
, PBM_LAST
, Qpbm
))
5110 /* Must specify either :data or :file. */
5111 return fmt
[PBM_DATA
].count
+ fmt
[PBM_FILE
].count
== 1;
5115 /* Get next char skipping comments in Netpbm header. Returns -1 at
5119 pbm_next_char (unsigned char **s
, unsigned char *end
)
5123 while (*s
< end
&& (c
= *(*s
)++, c
== '#'))
5125 /* Skip to the next line break. */
5126 while (*s
< end
&& (c
= *(*s
)++, c
!= '\n' && c
!= '\r'))
5136 /* Scan a decimal number from *S and return it. Advance *S while
5137 reading the number. END is the end of the string. Value is -1 at
5141 pbm_scan_number (unsigned char **s
, unsigned char *end
)
5143 int c
= 0, val
= -1;
5145 /* Skip white-space. */
5146 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isspace (c
))
5151 /* Read decimal number. */
5153 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isdigit (c
))
5154 val
= 10 * val
+ c
- '0';
5161 /* Load PBM image IMG for use on frame F. */
5164 pbm_load (struct frame
*f
, struct image
*img
)
5168 int width
, height
, max_color_idx
= 0;
5170 Lisp_Object file
, specified_file
;
5171 enum {PBM_MONO
, PBM_GRAY
, PBM_COLOR
} type
;
5172 unsigned char *contents
= NULL
;
5173 unsigned char *end
, *p
;
5176 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5178 if (STRINGP (specified_file
))
5180 file
= x_find_image_file (specified_file
);
5181 if (!STRINGP (file
))
5183 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
5187 contents
= slurp_file (SSDATA (file
), &size
);
5188 if (contents
== NULL
)
5190 image_error ("Error reading `%s'", file
, Qnil
);
5195 end
= contents
+ size
;
5200 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5201 if (!STRINGP (data
))
5203 image_error ("Invalid image data `%s'", data
, Qnil
);
5207 end
= p
+ SBYTES (data
);
5210 /* Check magic number. */
5211 if (end
- p
< 2 || *p
++ != 'P')
5213 image_error ("Not a PBM image: `%s'", img
->spec
, Qnil
);
5222 raw_p
= 0, type
= PBM_MONO
;
5226 raw_p
= 0, type
= PBM_GRAY
;
5230 raw_p
= 0, type
= PBM_COLOR
;
5234 raw_p
= 1, type
= PBM_MONO
;
5238 raw_p
= 1, type
= PBM_GRAY
;
5242 raw_p
= 1, type
= PBM_COLOR
;
5246 image_error ("Not a PBM image: `%s'", img
->spec
, Qnil
);
5250 /* Read width, height, maximum color-component. Characters
5251 starting with `#' up to the end of a line are ignored. */
5252 width
= pbm_scan_number (&p
, end
);
5253 height
= pbm_scan_number (&p
, end
);
5255 if (type
!= PBM_MONO
)
5257 max_color_idx
= pbm_scan_number (&p
, end
);
5258 if (max_color_idx
> 65535 || max_color_idx
< 0)
5260 image_error ("Unsupported maximum PBM color value", Qnil
, Qnil
);
5265 if (!check_image_size (f
, width
, height
))
5267 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
5271 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5274 /* Initialize the color hash table. */
5275 init_color_table ();
5277 if (type
== PBM_MONO
)
5280 struct image_keyword fmt
[PBM_LAST
];
5281 unsigned long fg
= FRAME_FOREGROUND_PIXEL (f
);
5282 unsigned long bg
= FRAME_BACKGROUND_PIXEL (f
);
5284 /* Parse the image specification. */
5285 memcpy (fmt
, pbm_format
, sizeof fmt
);
5286 parse_image_spec (img
->spec
, fmt
, PBM_LAST
, Qpbm
);
5288 /* Get foreground and background colors, maybe allocate colors. */
5289 if (fmt
[PBM_FOREGROUND
].count
5290 && STRINGP (fmt
[PBM_FOREGROUND
].value
))
5291 fg
= x_alloc_image_color (f
, img
, fmt
[PBM_FOREGROUND
].value
, fg
);
5292 if (fmt
[PBM_BACKGROUND
].count
5293 && STRINGP (fmt
[PBM_BACKGROUND
].value
))
5295 bg
= x_alloc_image_color (f
, img
, fmt
[PBM_BACKGROUND
].value
, bg
);
5296 img
->background
= bg
;
5297 img
->background_valid
= 1;
5300 for (y
= 0; y
< height
; ++y
)
5301 for (x
= 0; x
< width
; ++x
)
5309 x_destroy_x_image (ximg
);
5310 x_clear_image (f
, img
);
5311 image_error ("Invalid image size in image `%s'",
5321 g
= pbm_scan_number (&p
, end
);
5323 XPutPixel (ximg
, x
, y
, g
? fg
: bg
);
5328 int expected_size
= height
* width
;
5329 if (max_color_idx
> 255)
5331 if (type
== PBM_COLOR
)
5334 if (raw_p
&& p
+ expected_size
> end
)
5336 x_destroy_x_image (ximg
);
5337 x_clear_image (f
, img
);
5338 image_error ("Invalid image size in image `%s'",
5343 for (y
= 0; y
< height
; ++y
)
5344 for (x
= 0; x
< width
; ++x
)
5348 if (type
== PBM_GRAY
&& raw_p
)
5351 if (max_color_idx
> 255)
5352 r
= g
= b
= r
* 256 + *p
++;
5354 else if (type
== PBM_GRAY
)
5355 r
= g
= b
= pbm_scan_number (&p
, end
);
5359 if (max_color_idx
> 255)
5362 if (max_color_idx
> 255)
5365 if (max_color_idx
> 255)
5370 r
= pbm_scan_number (&p
, end
);
5371 g
= pbm_scan_number (&p
, end
);
5372 b
= pbm_scan_number (&p
, end
);
5375 if (r
< 0 || g
< 0 || b
< 0)
5377 x_destroy_x_image (ximg
);
5378 image_error ("Invalid pixel value in image `%s'",
5383 /* RGB values are now in the range 0..max_color_idx.
5384 Scale this to the range 0..0xffff supported by X. */
5385 r
= (double) r
* 65535 / max_color_idx
;
5386 g
= (double) g
* 65535 / max_color_idx
;
5387 b
= (double) b
* 65535 / max_color_idx
;
5388 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5392 #ifdef COLOR_TABLE_SUPPORT
5393 /* Store in IMG->colors the colors allocated for the image, and
5394 free the color table. */
5395 img
->colors
= colors_in_color_table (&img
->ncolors
);
5396 free_color_table ();
5397 #endif /* COLOR_TABLE_SUPPORT */
5400 img
->height
= height
;
5402 /* Maybe fill in the background field while we have ximg handy. */
5404 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
5405 /* Casting avoids a GCC warning. */
5406 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
5408 /* Put ximg into the image. */
5409 image_put_x_image (f
, img
, ximg
, 0);
5411 /* X and W32 versions did it here, MAC version above. ++kfs
5413 img->height = height; */
5420 /***********************************************************************
5422 ***********************************************************************/
5424 #if defined (HAVE_PNG) || defined (HAVE_NS)
5426 /* Function prototypes. */
5428 static bool png_image_p (Lisp_Object object
);
5429 static bool png_load (struct frame
*f
, struct image
*img
);
5431 /* The symbol `png' identifying images of this type. */
5433 static Lisp_Object Qpng
;
5435 /* Indices of image specification fields in png_format, below. */
5437 enum png_keyword_index
5452 /* Vector of image_keyword structures describing the format
5453 of valid user-defined image specifications. */
5455 static const struct image_keyword png_format
[PNG_LAST
] =
5457 {":type", IMAGE_SYMBOL_VALUE
, 1},
5458 {":data", IMAGE_STRING_VALUE
, 0},
5459 {":file", IMAGE_STRING_VALUE
, 0},
5460 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5461 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5462 {":relief", IMAGE_INTEGER_VALUE
, 0},
5463 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5464 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5465 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5466 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5469 #if defined HAVE_NTGUI && defined WINDOWSNT
5470 static bool init_png_functions (void);
5472 #define init_png_functions NULL
5475 /* Structure describing the image type `png'. */
5477 static struct image_type png_type
=
5487 /* Return true if OBJECT is a valid PNG image specification. */
5490 png_image_p (Lisp_Object object
)
5492 struct image_keyword fmt
[PNG_LAST
];
5493 memcpy (fmt
, png_format
, sizeof fmt
);
5495 if (!parse_image_spec (object
, fmt
, PNG_LAST
, Qpng
))
5498 /* Must specify either the :data or :file keyword. */
5499 return fmt
[PNG_FILE
].count
+ fmt
[PNG_DATA
].count
== 1;
5502 #endif /* HAVE_PNG || HAVE_NS */
5508 /* PNG library details. */
5510 DEF_IMGLIB_FN (png_voidp
, png_get_io_ptr
, (png_structp
));
5511 DEF_IMGLIB_FN (int, png_sig_cmp
, (png_bytep
, png_size_t
, png_size_t
));
5512 DEF_IMGLIB_FN (png_structp
, png_create_read_struct
, (png_const_charp
, png_voidp
,
5513 png_error_ptr
, png_error_ptr
));
5514 DEF_IMGLIB_FN (png_infop
, png_create_info_struct
, (png_structp
));
5515 DEF_IMGLIB_FN (void, png_destroy_read_struct
, (png_structpp
, png_infopp
, png_infopp
));
5516 DEF_IMGLIB_FN (void, png_set_read_fn
, (png_structp
, png_voidp
, png_rw_ptr
));
5517 DEF_IMGLIB_FN (void, png_set_sig_bytes
, (png_structp
, int));
5518 DEF_IMGLIB_FN (void, png_read_info
, (png_structp
, png_infop
));
5519 DEF_IMGLIB_FN (png_uint_32
, png_get_IHDR
, (png_structp
, png_infop
,
5520 png_uint_32
*, png_uint_32
*,
5521 int *, int *, int *, int *, int *));
5522 DEF_IMGLIB_FN (png_uint_32
, png_get_valid
, (png_structp
, png_infop
, png_uint_32
));
5523 DEF_IMGLIB_FN (void, png_set_strip_16
, (png_structp
));
5524 DEF_IMGLIB_FN (void, png_set_expand
, (png_structp
));
5525 DEF_IMGLIB_FN (void, png_set_gray_to_rgb
, (png_structp
));
5526 DEF_IMGLIB_FN (void, png_set_background
, (png_structp
, png_color_16p
,
5528 DEF_IMGLIB_FN (png_uint_32
, png_get_bKGD
, (png_structp
, png_infop
, png_color_16p
*));
5529 DEF_IMGLIB_FN (void, png_read_update_info
, (png_structp
, png_infop
));
5530 DEF_IMGLIB_FN (png_byte
, png_get_channels
, (png_structp
, png_infop
));
5531 DEF_IMGLIB_FN (png_size_t
, png_get_rowbytes
, (png_structp
, png_infop
));
5532 DEF_IMGLIB_FN (void, png_read_image
, (png_structp
, png_bytepp
));
5533 DEF_IMGLIB_FN (void, png_read_end
, (png_structp
, png_infop
));
5534 DEF_IMGLIB_FN (void, png_error
, (png_structp
, png_const_charp
));
5536 #if (PNG_LIBPNG_VER >= 10500)
5537 DEF_IMGLIB_FN (void, png_longjmp
, (png_structp
, int));
5538 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn
, (png_structp
, png_longjmp_ptr
, size_t));
5539 #endif /* libpng version >= 1.5 */
5542 init_png_functions (void)
5546 if (!(library
= w32_delayed_load (Qpng
)))
5549 LOAD_IMGLIB_FN (library
, png_get_io_ptr
);
5550 LOAD_IMGLIB_FN (library
, png_sig_cmp
);
5551 LOAD_IMGLIB_FN (library
, png_create_read_struct
);
5552 LOAD_IMGLIB_FN (library
, png_create_info_struct
);
5553 LOAD_IMGLIB_FN (library
, png_destroy_read_struct
);
5554 LOAD_IMGLIB_FN (library
, png_set_read_fn
);
5555 LOAD_IMGLIB_FN (library
, png_set_sig_bytes
);
5556 LOAD_IMGLIB_FN (library
, png_read_info
);
5557 LOAD_IMGLIB_FN (library
, png_get_IHDR
);
5558 LOAD_IMGLIB_FN (library
, png_get_valid
);
5559 LOAD_IMGLIB_FN (library
, png_set_strip_16
);
5560 LOAD_IMGLIB_FN (library
, png_set_expand
);
5561 LOAD_IMGLIB_FN (library
, png_set_gray_to_rgb
);
5562 LOAD_IMGLIB_FN (library
, png_set_background
);
5563 LOAD_IMGLIB_FN (library
, png_get_bKGD
);
5564 LOAD_IMGLIB_FN (library
, png_read_update_info
);
5565 LOAD_IMGLIB_FN (library
, png_get_channels
);
5566 LOAD_IMGLIB_FN (library
, png_get_rowbytes
);
5567 LOAD_IMGLIB_FN (library
, png_read_image
);
5568 LOAD_IMGLIB_FN (library
, png_read_end
);
5569 LOAD_IMGLIB_FN (library
, png_error
);
5571 #if (PNG_LIBPNG_VER >= 10500)
5572 LOAD_IMGLIB_FN (library
, png_longjmp
);
5573 LOAD_IMGLIB_FN (library
, png_set_longjmp_fn
);
5574 #endif /* libpng version >= 1.5 */
5580 #define fn_png_get_io_ptr png_get_io_ptr
5581 #define fn_png_sig_cmp png_sig_cmp
5582 #define fn_png_create_read_struct png_create_read_struct
5583 #define fn_png_create_info_struct png_create_info_struct
5584 #define fn_png_destroy_read_struct png_destroy_read_struct
5585 #define fn_png_set_read_fn png_set_read_fn
5586 #define fn_png_set_sig_bytes png_set_sig_bytes
5587 #define fn_png_read_info png_read_info
5588 #define fn_png_get_IHDR png_get_IHDR
5589 #define fn_png_get_valid png_get_valid
5590 #define fn_png_set_strip_16 png_set_strip_16
5591 #define fn_png_set_expand png_set_expand
5592 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5593 #define fn_png_set_background png_set_background
5594 #define fn_png_get_bKGD png_get_bKGD
5595 #define fn_png_read_update_info png_read_update_info
5596 #define fn_png_get_channels png_get_channels
5597 #define fn_png_get_rowbytes png_get_rowbytes
5598 #define fn_png_read_image png_read_image
5599 #define fn_png_read_end png_read_end
5600 #define fn_png_error png_error
5602 #if (PNG_LIBPNG_VER >= 10500)
5603 #define fn_png_longjmp png_longjmp
5604 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5605 #endif /* libpng version >= 1.5 */
5607 #endif /* WINDOWSNT */
5609 /* Possibly inefficient/inexact substitutes for _setjmp and _longjmp.
5610 Do not use sys_setjmp, as PNG supports only jmp_buf. The _longjmp
5611 substitute may munge the signal mask, but that should be OK here.
5612 MinGW (MS-Windows) uses _setjmp and defines setjmp to _setjmp in
5613 the system header setjmp.h; don't mess up that. */
5614 #ifndef HAVE__SETJMP
5615 # define _setjmp(j) setjmp (j)
5616 # define _longjmp longjmp
5619 #if (PNG_LIBPNG_VER < 10500)
5620 #define PNG_LONGJMP(ptr) (_longjmp ((ptr)->jmpbuf, 1))
5621 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5623 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5624 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5625 #define PNG_JMPBUF(ptr) \
5626 (*fn_png_set_longjmp_fn ((ptr), _longjmp, sizeof (jmp_buf)))
5629 /* Error and warning handlers installed when the PNG library
5632 static _Noreturn
void
5633 my_png_error (png_struct
*png_ptr
, const char *msg
)
5635 eassert (png_ptr
!= NULL
);
5636 /* Avoid compiler warning about deprecated direct access to
5637 png_ptr's fields in libpng versions 1.4.x. */
5638 image_error ("PNG error: %s", build_string (msg
), Qnil
);
5639 PNG_LONGJMP (png_ptr
);
5644 my_png_warning (png_struct
*png_ptr
, const char *msg
)
5646 eassert (png_ptr
!= NULL
);
5647 image_error ("PNG warning: %s", build_string (msg
), Qnil
);
5650 /* Memory source for PNG decoding. */
5652 struct png_memory_storage
5654 unsigned char *bytes
; /* The data */
5655 ptrdiff_t len
; /* How big is it? */
5656 ptrdiff_t index
; /* Where are we? */
5660 /* Function set as reader function when reading PNG image from memory.
5661 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5662 bytes from the input to DATA. */
5665 png_read_from_memory (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5667 struct png_memory_storage
*tbr
= fn_png_get_io_ptr (png_ptr
);
5669 if (length
> tbr
->len
- tbr
->index
)
5670 fn_png_error (png_ptr
, "Read error");
5672 memcpy (data
, tbr
->bytes
+ tbr
->index
, length
);
5673 tbr
->index
= tbr
->index
+ length
;
5677 /* Function set as reader function when reading PNG image from a file.
5678 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5679 bytes from the input to DATA. */
5682 png_read_from_file (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5684 FILE *fp
= fn_png_get_io_ptr (png_ptr
);
5686 if (fread (data
, 1, length
, fp
) < length
)
5687 fn_png_error (png_ptr
, "Read error");
5691 /* Load PNG image IMG for use on frame F. Value is true if
5694 struct png_load_context
5696 /* These are members so that longjmp doesn't munge local variables. */
5697 png_struct
*png_ptr
;
5706 png_load_body (struct frame
*f
, struct image
*img
, struct png_load_context
*c
)
5708 Lisp_Object file
, specified_file
;
5709 Lisp_Object specified_data
;
5712 XImagePtr ximg
, mask_img
= NULL
;
5713 png_struct
*png_ptr
;
5714 png_info
*info_ptr
= NULL
, *end_info
= NULL
;
5717 png_byte
*pixels
= NULL
;
5718 png_byte
**rows
= NULL
;
5719 png_uint_32 width
, height
;
5720 int bit_depth
, color_type
, interlace_type
;
5722 png_uint_32 row_bytes
;
5724 struct png_memory_storage tbr
; /* Data to be read */
5726 /* Find out what file to load. */
5727 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5728 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5730 if (NILP (specified_data
))
5732 file
= x_find_image_file (specified_file
);
5733 if (!STRINGP (file
))
5735 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
5739 /* Open the image file. */
5740 fp
= emacs_fopen (SSDATA (file
), "rb");
5743 image_error ("Cannot open image file `%s'", file
, Qnil
);
5747 /* Check PNG signature. */
5748 if (fread (sig
, 1, sizeof sig
, fp
) != sizeof sig
5749 || fn_png_sig_cmp (sig
, 0, sizeof sig
))
5752 image_error ("Not a PNG file: `%s'", file
, Qnil
);
5758 if (!STRINGP (specified_data
))
5760 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
5764 /* Read from memory. */
5765 tbr
.bytes
= SDATA (specified_data
);
5766 tbr
.len
= SBYTES (specified_data
);
5769 /* Check PNG signature. */
5770 if (tbr
.len
< sizeof sig
5771 || fn_png_sig_cmp (tbr
.bytes
, 0, sizeof sig
))
5773 image_error ("Not a PNG image: `%s'", img
->spec
, Qnil
);
5777 /* Need to skip past the signature. */
5778 tbr
.bytes
+= sizeof (sig
);
5781 /* Initialize read and info structs for PNG lib. */
5782 png_ptr
= fn_png_create_read_struct (PNG_LIBPNG_VER_STRING
,
5787 info_ptr
= fn_png_create_info_struct (png_ptr
);
5788 end_info
= fn_png_create_info_struct (png_ptr
);
5791 c
->png_ptr
= png_ptr
;
5792 c
->info_ptr
= info_ptr
;
5793 c
->end_info
= end_info
;
5798 if (! (info_ptr
&& end_info
))
5800 fn_png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5805 if (fp
) fclose (fp
);
5809 /* Set error jump-back. We come back here when the PNG library
5810 detects an error. */
5811 if (_setjmp (PNG_JMPBUF (png_ptr
)))
5815 fn_png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5823 /* Silence a bogus diagnostic; see GCC bug 54561. */
5824 IF_LINT (fp
= c
->fp
);
5826 /* Read image info. */
5827 if (!NILP (specified_data
))
5828 fn_png_set_read_fn (png_ptr
, &tbr
, png_read_from_memory
);
5830 fn_png_set_read_fn (png_ptr
, fp
, png_read_from_file
);
5832 fn_png_set_sig_bytes (png_ptr
, sizeof sig
);
5833 fn_png_read_info (png_ptr
, info_ptr
);
5834 fn_png_get_IHDR (png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
,
5835 &interlace_type
, NULL
, NULL
);
5837 if (! (width
<= INT_MAX
&& height
<= INT_MAX
5838 && check_image_size (f
, width
, height
)))
5840 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
5844 /* Create the X image and pixmap now, so that the work below can be
5845 omitted if the image is too large for X. */
5846 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5849 /* If image contains simply transparency data, we prefer to
5850 construct a clipping mask. */
5851 if (fn_png_get_valid (png_ptr
, info_ptr
, PNG_INFO_tRNS
))
5856 /* This function is easier to write if we only have to handle
5857 one data format: RGB or RGBA with 8 bits per channel. Let's
5858 transform other formats into that format. */
5860 /* Strip more than 8 bits per channel. */
5861 if (bit_depth
== 16)
5862 fn_png_set_strip_16 (png_ptr
);
5864 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5866 fn_png_set_expand (png_ptr
);
5868 /* Convert grayscale images to RGB. */
5869 if (color_type
== PNG_COLOR_TYPE_GRAY
5870 || color_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
5871 fn_png_set_gray_to_rgb (png_ptr
);
5873 /* Handle alpha channel by combining the image with a background
5874 color. Do this only if a real alpha channel is supplied. For
5875 simple transparency, we prefer a clipping mask. */
5878 /* png_color_16 *image_bg; */
5879 Lisp_Object specified_bg
5880 = image_spec_value (img
->spec
, QCbackground
, NULL
);
5881 int shift
= (bit_depth
== 16) ? 0 : 8;
5883 if (STRINGP (specified_bg
))
5884 /* The user specified `:background', use that. */
5887 if (x_defined_color (f
, SSDATA (specified_bg
), &color
, 0))
5889 png_color_16 user_bg
;
5891 memset (&user_bg
, 0, sizeof user_bg
);
5892 user_bg
.red
= color
.red
>> shift
;
5893 user_bg
.green
= color
.green
>> shift
;
5894 user_bg
.blue
= color
.blue
>> shift
;
5896 fn_png_set_background (png_ptr
, &user_bg
,
5897 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
5902 /* We use the current frame background, ignoring any default
5903 background color set by the image. */
5904 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5906 png_color_16 frame_background
;
5908 color
.pixel
= FRAME_BACKGROUND_PIXEL (f
);
5909 x_query_color (f
, &color
);
5911 memset (&frame_background
, 0, sizeof frame_background
);
5912 frame_background
.red
= color
.red
>> shift
;
5913 frame_background
.green
= color
.green
>> shift
;
5914 frame_background
.blue
= color
.blue
>> shift
;
5915 #endif /* HAVE_X_WINDOWS */
5917 fn_png_set_background (png_ptr
, &frame_background
,
5918 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
5922 /* Update info structure. */
5923 fn_png_read_update_info (png_ptr
, info_ptr
);
5925 /* Get number of channels. Valid values are 1 for grayscale images
5926 and images with a palette, 2 for grayscale images with transparency
5927 information (alpha channel), 3 for RGB images, and 4 for RGB
5928 images with alpha channel, i.e. RGBA. If conversions above were
5929 sufficient we should only have 3 or 4 channels here. */
5930 channels
= fn_png_get_channels (png_ptr
, info_ptr
);
5931 eassert (channels
== 3 || channels
== 4);
5933 /* Number of bytes needed for one row of the image. */
5934 row_bytes
= fn_png_get_rowbytes (png_ptr
, info_ptr
);
5936 /* Allocate memory for the image. */
5937 if (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *rows
< height
5938 || min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *pixels
/ height
< row_bytes
)
5939 memory_full (SIZE_MAX
);
5940 c
->pixels
= pixels
= xmalloc (sizeof *pixels
* row_bytes
* height
);
5941 c
->rows
= rows
= xmalloc (height
* sizeof *rows
);
5942 for (i
= 0; i
< height
; ++i
)
5943 rows
[i
] = pixels
+ i
* row_bytes
;
5945 /* Read the entire image. */
5946 fn_png_read_image (png_ptr
, rows
);
5947 fn_png_read_end (png_ptr
, info_ptr
);
5954 /* Create an image and pixmap serving as mask if the PNG image
5955 contains an alpha channel. */
5958 && !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
5961 x_destroy_x_image (ximg
);
5962 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
);
5966 /* Fill the X image and mask from PNG data. */
5967 init_color_table ();
5969 for (y
= 0; y
< height
; ++y
)
5971 png_byte
*p
= rows
[y
];
5973 for (x
= 0; x
< width
; ++x
)
5980 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5981 /* An alpha channel, aka mask channel, associates variable
5982 transparency with an image. Where other image formats
5983 support binary transparency---fully transparent or fully
5984 opaque---PNG allows up to 254 levels of partial transparency.
5985 The PNG library implements partial transparency by combining
5986 the image with a specified background color.
5988 I'm not sure how to handle this here nicely: because the
5989 background on which the image is displayed may change, for
5990 real alpha channel support, it would be necessary to create
5991 a new image for each possible background.
5993 What I'm doing now is that a mask is created if we have
5994 boolean transparency information. Otherwise I'm using
5995 the frame's background color to combine the image with. */
6000 XPutPixel (mask_img
, x
, y
, *p
> 0 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
);
6006 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6007 /* Set IMG's background color from the PNG image, unless the user
6011 if (fn_png_get_bKGD (png_ptr
, info_ptr
, &bg
))
6013 img
->background
= lookup_rgb_color (f
, bg
->red
, bg
->green
, bg
->blue
);
6014 img
->background_valid
= 1;
6018 #ifdef COLOR_TABLE_SUPPORT
6019 /* Remember colors allocated for this image. */
6020 img
->colors
= colors_in_color_table (&img
->ncolors
);
6021 free_color_table ();
6022 #endif /* COLOR_TABLE_SUPPORT */
6025 fn_png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6030 img
->height
= height
;
6032 /* Maybe fill in the background field while we have ximg handy.
6033 Casting avoids a GCC warning. */
6034 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6036 /* Put ximg into the image. */
6037 image_put_x_image (f
, img
, ximg
, 0);
6039 /* Same for the mask. */
6042 /* Fill in the background_transparent field while we have the
6043 mask handy. Casting avoids a GCC warning. */
6044 image_background_transparent (img
, f
, (XImagePtr_or_DC
)mask_img
);
6046 image_put_x_image (f
, img
, mask_img
, 1);
6053 png_load (struct frame
*f
, struct image
*img
)
6055 struct png_load_context c
;
6056 return png_load_body (f
, img
, &c
);
6059 #else /* HAVE_PNG */
6063 png_load (struct frame
*f
, struct image
*img
)
6065 return ns_load_image (f
, img
,
6066 image_spec_value (img
->spec
, QCfile
, NULL
),
6067 image_spec_value (img
->spec
, QCdata
, NULL
));
6069 #endif /* HAVE_NS */
6072 #endif /* !HAVE_PNG */
6076 /***********************************************************************
6078 ***********************************************************************/
6080 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6082 static bool jpeg_image_p (Lisp_Object object
);
6083 static bool jpeg_load (struct frame
*f
, struct image
*img
);
6085 /* The symbol `jpeg' identifying images of this type. */
6087 static Lisp_Object Qjpeg
;
6089 /* Indices of image specification fields in gs_format, below. */
6091 enum jpeg_keyword_index
6100 JPEG_HEURISTIC_MASK
,
6106 /* Vector of image_keyword structures describing the format
6107 of valid user-defined image specifications. */
6109 static const struct image_keyword jpeg_format
[JPEG_LAST
] =
6111 {":type", IMAGE_SYMBOL_VALUE
, 1},
6112 {":data", IMAGE_STRING_VALUE
, 0},
6113 {":file", IMAGE_STRING_VALUE
, 0},
6114 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6115 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6116 {":relief", IMAGE_INTEGER_VALUE
, 0},
6117 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6118 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6119 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6120 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
6123 #if defined HAVE_NTGUI && defined WINDOWSNT
6124 static bool init_jpeg_functions (void);
6126 #define init_jpeg_functions NULL
6129 /* Structure describing the image type `jpeg'. */
6131 static struct image_type jpeg_type
=
6137 init_jpeg_functions
,
6141 /* Return true if OBJECT is a valid JPEG image specification. */
6144 jpeg_image_p (Lisp_Object object
)
6146 struct image_keyword fmt
[JPEG_LAST
];
6148 memcpy (fmt
, jpeg_format
, sizeof fmt
);
6150 if (!parse_image_spec (object
, fmt
, JPEG_LAST
, Qjpeg
))
6153 /* Must specify either the :data or :file keyword. */
6154 return fmt
[JPEG_FILE
].count
+ fmt
[JPEG_DATA
].count
== 1;
6157 #endif /* HAVE_JPEG || HAVE_NS */
6161 /* Work around a warning about HAVE_STDLIB_H being redefined in
6163 #ifdef HAVE_STDLIB_H
6164 #undef HAVE_STDLIB_H
6165 #endif /* HAVE_STLIB_H */
6167 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6168 /* In older releases of the jpeg library, jpeglib.h will define boolean
6169 differently depending on __WIN32__, so make sure it is defined. */
6173 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6174 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6175 using the Windows boolean type instead of the jpeglib boolean type
6176 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6177 headers are included along with windows.h, so under Cygwin, jpeglib
6178 attempts to define a conflicting boolean type. Worse, forcing
6179 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6180 because it created an ABI incompatibility between the
6181 already-compiled jpeg library and the header interface definition.
6183 The best we can do is to define jpeglib's boolean type to a
6184 different name. This name, jpeg_boolean, remains in effect through
6185 the rest of image.c.
6187 #if defined CYGWIN && defined HAVE_NTGUI
6188 #define boolean jpeg_boolean
6190 #include <jpeglib.h>
6195 /* JPEG library details. */
6196 DEF_IMGLIB_FN (void, jpeg_CreateDecompress
, (j_decompress_ptr
, int, size_t));
6197 DEF_IMGLIB_FN (boolean
, jpeg_start_decompress
, (j_decompress_ptr
));
6198 DEF_IMGLIB_FN (boolean
, jpeg_finish_decompress
, (j_decompress_ptr
));
6199 DEF_IMGLIB_FN (void, jpeg_destroy_decompress
, (j_decompress_ptr
));
6200 DEF_IMGLIB_FN (int, jpeg_read_header
, (j_decompress_ptr
, boolean
));
6201 DEF_IMGLIB_FN (JDIMENSION
, jpeg_read_scanlines
, (j_decompress_ptr
, JSAMPARRAY
, JDIMENSION
));
6202 DEF_IMGLIB_FN (struct jpeg_error_mgr
*, jpeg_std_error
, (struct jpeg_error_mgr
*));
6203 DEF_IMGLIB_FN (boolean
, jpeg_resync_to_restart
, (j_decompress_ptr
, int));
6206 init_jpeg_functions (void)
6210 if (!(library
= w32_delayed_load (Qjpeg
)))
6213 LOAD_IMGLIB_FN (library
, jpeg_finish_decompress
);
6214 LOAD_IMGLIB_FN (library
, jpeg_read_scanlines
);
6215 LOAD_IMGLIB_FN (library
, jpeg_start_decompress
);
6216 LOAD_IMGLIB_FN (library
, jpeg_read_header
);
6217 LOAD_IMGLIB_FN (library
, jpeg_CreateDecompress
);
6218 LOAD_IMGLIB_FN (library
, jpeg_destroy_decompress
);
6219 LOAD_IMGLIB_FN (library
, jpeg_std_error
);
6220 LOAD_IMGLIB_FN (library
, jpeg_resync_to_restart
);
6224 /* Wrapper since we can't directly assign the function pointer
6225 to another function pointer that was declared more completely easily. */
6227 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo
, int desired
)
6229 return fn_jpeg_resync_to_restart (cinfo
, desired
);
6234 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
6235 #define fn_jpeg_start_decompress jpeg_start_decompress
6236 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6237 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6238 #define fn_jpeg_read_header jpeg_read_header
6239 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6240 #define fn_jpeg_std_error jpeg_std_error
6241 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6243 #endif /* WINDOWSNT */
6245 struct my_jpeg_error_mgr
6247 struct jpeg_error_mgr pub
;
6248 sys_jmp_buf setjmp_buffer
;
6250 /* The remaining members are so that longjmp doesn't munge local
6252 struct jpeg_decompress_struct cinfo
;
6256 MY_JPEG_INVALID_IMAGE_SIZE
,
6257 MY_JPEG_CANNOT_CREATE_X
6265 static _Noreturn
void
6266 my_error_exit (j_common_ptr cinfo
)
6268 struct my_jpeg_error_mgr
*mgr
= (struct my_jpeg_error_mgr
*) cinfo
->err
;
6269 mgr
->failure_code
= MY_JPEG_ERROR_EXIT
;
6270 sys_longjmp (mgr
->setjmp_buffer
, 1);
6274 /* Init source method for JPEG data source manager. Called by
6275 jpeg_read_header() before any data is actually read. See
6276 libjpeg.doc from the JPEG lib distribution. */
6279 our_common_init_source (j_decompress_ptr cinfo
)
6284 /* Method to terminate data source. Called by
6285 jpeg_finish_decompress() after all data has been processed. */
6288 our_common_term_source (j_decompress_ptr cinfo
)
6293 /* Fill input buffer method for JPEG data source manager. Called
6294 whenever more data is needed. We read the whole image in one step,
6295 so this only adds a fake end of input marker at the end. */
6297 static JOCTET our_memory_buffer
[2];
6300 our_memory_fill_input_buffer (j_decompress_ptr cinfo
)
6302 /* Insert a fake EOI marker. */
6303 struct jpeg_source_mgr
*src
= cinfo
->src
;
6305 our_memory_buffer
[0] = (JOCTET
) 0xFF;
6306 our_memory_buffer
[1] = (JOCTET
) JPEG_EOI
;
6308 src
->next_input_byte
= our_memory_buffer
;
6309 src
->bytes_in_buffer
= 2;
6314 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6315 is the JPEG data source manager. */
6318 our_memory_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6320 struct jpeg_source_mgr
*src
= cinfo
->src
;
6324 if (num_bytes
> src
->bytes_in_buffer
)
6325 ERREXIT (cinfo
, JERR_INPUT_EOF
);
6327 src
->bytes_in_buffer
-= num_bytes
;
6328 src
->next_input_byte
+= num_bytes
;
6333 /* Set up the JPEG lib for reading an image from DATA which contains
6334 LEN bytes. CINFO is the decompression info structure created for
6335 reading the image. */
6338 jpeg_memory_src (j_decompress_ptr cinfo
, JOCTET
*data
, ptrdiff_t len
)
6340 struct jpeg_source_mgr
*src
= cinfo
->src
;
6344 /* First time for this JPEG object? */
6345 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6346 JPOOL_PERMANENT
, sizeof *src
);
6348 src
->next_input_byte
= data
;
6351 src
->init_source
= our_common_init_source
;
6352 src
->fill_input_buffer
= our_memory_fill_input_buffer
;
6353 src
->skip_input_data
= our_memory_skip_input_data
;
6354 src
->resync_to_restart
= jpeg_resync_to_restart_wrapper
; /* Use default method. */
6355 src
->term_source
= our_common_term_source
;
6356 src
->bytes_in_buffer
= len
;
6357 src
->next_input_byte
= data
;
6361 struct jpeg_stdio_mgr
6363 struct jpeg_source_mgr mgr
;
6370 /* Size of buffer to read JPEG from file.
6371 Not too big, as we want to use alloc_small. */
6372 #define JPEG_STDIO_BUFFER_SIZE 8192
6375 /* Fill input buffer method for JPEG data source manager. Called
6376 whenever more data is needed. The data is read from a FILE *. */
6379 our_stdio_fill_input_buffer (j_decompress_ptr cinfo
)
6381 struct jpeg_stdio_mgr
*src
;
6383 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6388 bytes
= fread (src
->buffer
, 1, JPEG_STDIO_BUFFER_SIZE
, src
->file
);
6390 src
->mgr
.bytes_in_buffer
= bytes
;
6393 WARNMS (cinfo
, JWRN_JPEG_EOF
);
6395 src
->buffer
[0] = (JOCTET
) 0xFF;
6396 src
->buffer
[1] = (JOCTET
) JPEG_EOI
;
6397 src
->mgr
.bytes_in_buffer
= 2;
6399 src
->mgr
.next_input_byte
= src
->buffer
;
6406 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6407 is the JPEG data source manager. */
6410 our_stdio_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6412 struct jpeg_stdio_mgr
*src
;
6413 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6415 while (num_bytes
> 0 && !src
->finished
)
6417 if (num_bytes
<= src
->mgr
.bytes_in_buffer
)
6419 src
->mgr
.bytes_in_buffer
-= num_bytes
;
6420 src
->mgr
.next_input_byte
+= num_bytes
;
6425 num_bytes
-= src
->mgr
.bytes_in_buffer
;
6426 src
->mgr
.bytes_in_buffer
= 0;
6427 src
->mgr
.next_input_byte
= NULL
;
6429 our_stdio_fill_input_buffer (cinfo
);
6435 /* Set up the JPEG lib for reading an image from a FILE *.
6436 CINFO is the decompression info structure created for
6437 reading the image. */
6440 jpeg_file_src (j_decompress_ptr cinfo
, FILE *fp
)
6442 struct jpeg_stdio_mgr
*src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6446 /* First time for this JPEG object? */
6447 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6448 JPOOL_PERMANENT
, sizeof *src
);
6449 cinfo
->src
= (struct jpeg_source_mgr
*) src
;
6450 src
->buffer
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6452 JPEG_STDIO_BUFFER_SIZE
);
6457 src
->mgr
.init_source
= our_common_init_source
;
6458 src
->mgr
.fill_input_buffer
= our_stdio_fill_input_buffer
;
6459 src
->mgr
.skip_input_data
= our_stdio_skip_input_data
;
6460 src
->mgr
.resync_to_restart
= jpeg_resync_to_restart_wrapper
; /* Use default method. */
6461 src
->mgr
.term_source
= our_common_term_source
;
6462 src
->mgr
.bytes_in_buffer
= 0;
6463 src
->mgr
.next_input_byte
= NULL
;
6467 /* Load image IMG for use on frame F. Patterned after example.c
6468 from the JPEG lib. */
6471 jpeg_load_body (struct frame
*f
, struct image
*img
,
6472 struct my_jpeg_error_mgr
*mgr
)
6474 Lisp_Object file
, specified_file
;
6475 Lisp_Object specified_data
;
6478 int row_stride
, x
, y
;
6479 XImagePtr ximg
= NULL
;
6480 unsigned long *colors
;
6483 /* Open the JPEG file. */
6484 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6485 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6487 if (NILP (specified_data
))
6489 file
= x_find_image_file (specified_file
);
6490 if (!STRINGP (file
))
6492 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
6496 fp
= emacs_fopen (SSDATA (file
), "rb");
6499 image_error ("Cannot open `%s'", file
, Qnil
);
6503 else if (!STRINGP (specified_data
))
6505 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
6509 IF_LINT (mgr
->fp
= fp
);
6511 /* Customize libjpeg's error handling to call my_error_exit when an
6512 error is detected. This function will perform a longjmp. */
6513 mgr
->cinfo
.err
= fn_jpeg_std_error (&mgr
->pub
);
6514 mgr
->pub
.error_exit
= my_error_exit
;
6515 if (sys_setjmp (mgr
->setjmp_buffer
))
6517 switch (mgr
->failure_code
)
6519 case MY_JPEG_ERROR_EXIT
:
6521 char buf
[JMSG_LENGTH_MAX
];
6522 mgr
->cinfo
.err
->format_message ((j_common_ptr
) &mgr
->cinfo
, buf
);
6523 image_error ("Error reading JPEG image `%s': %s", img
->spec
,
6524 build_string (buf
));
6528 case MY_JPEG_INVALID_IMAGE_SIZE
:
6529 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
6532 case MY_JPEG_CANNOT_CREATE_X
:
6536 /* Close the input file and destroy the JPEG object. */
6539 fn_jpeg_destroy_decompress (&mgr
->cinfo
);
6541 /* If we already have an XImage, free that. */
6542 x_destroy_x_image (ximg
);
6544 /* Free pixmap and colors. */
6545 x_clear_image (f
, img
);
6549 /* Silence a bogus diagnostic; see GCC bug 54561. */
6550 IF_LINT (fp
= mgr
->fp
);
6552 /* Create the JPEG decompression object. Let it read from fp.
6553 Read the JPEG image header. */
6554 fn_jpeg_CreateDecompress (&mgr
->cinfo
, JPEG_LIB_VERSION
, sizeof *&mgr
->cinfo
);
6556 if (NILP (specified_data
))
6557 jpeg_file_src (&mgr
->cinfo
, fp
);
6559 jpeg_memory_src (&mgr
->cinfo
, SDATA (specified_data
),
6560 SBYTES (specified_data
));
6562 fn_jpeg_read_header (&mgr
->cinfo
, 1);
6564 /* Customize decompression so that color quantization will be used.
6565 Start decompression. */
6566 mgr
->cinfo
.quantize_colors
= 1;
6567 fn_jpeg_start_decompress (&mgr
->cinfo
);
6568 width
= img
->width
= mgr
->cinfo
.output_width
;
6569 height
= img
->height
= mgr
->cinfo
.output_height
;
6571 if (!check_image_size (f
, width
, height
))
6573 mgr
->failure_code
= MY_JPEG_INVALID_IMAGE_SIZE
;
6574 sys_longjmp (mgr
->setjmp_buffer
, 1);
6577 /* Create X image and pixmap. */
6578 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6580 mgr
->failure_code
= MY_JPEG_CANNOT_CREATE_X
;
6581 sys_longjmp (mgr
->setjmp_buffer
, 1);
6584 /* Allocate colors. When color quantization is used,
6585 mgr->cinfo.actual_number_of_colors has been set with the number of
6586 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6587 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6588 No more than 255 colors will be generated. */
6592 if (mgr
->cinfo
.out_color_components
> 2)
6593 ir
= 0, ig
= 1, ib
= 2;
6594 else if (mgr
->cinfo
.out_color_components
> 1)
6595 ir
= 0, ig
= 1, ib
= 0;
6597 ir
= 0, ig
= 0, ib
= 0;
6599 /* Use the color table mechanism because it handles colors that
6600 cannot be allocated nicely. Such colors will be replaced with
6601 a default color, and we don't have to care about which colors
6602 can be freed safely, and which can't. */
6603 init_color_table ();
6604 colors
= alloca (mgr
->cinfo
.actual_number_of_colors
* sizeof *colors
);
6606 for (i
= 0; i
< mgr
->cinfo
.actual_number_of_colors
; ++i
)
6608 /* Multiply RGB values with 255 because X expects RGB values
6609 in the range 0..0xffff. */
6610 int r
= mgr
->cinfo
.colormap
[ir
][i
] << 8;
6611 int g
= mgr
->cinfo
.colormap
[ig
][i
] << 8;
6612 int b
= mgr
->cinfo
.colormap
[ib
][i
] << 8;
6613 colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
6616 #ifdef COLOR_TABLE_SUPPORT
6617 /* Remember those colors actually allocated. */
6618 img
->colors
= colors_in_color_table (&img
->ncolors
);
6619 free_color_table ();
6620 #endif /* COLOR_TABLE_SUPPORT */
6624 row_stride
= width
* mgr
->cinfo
.output_components
;
6625 buffer
= mgr
->cinfo
.mem
->alloc_sarray ((j_common_ptr
) &mgr
->cinfo
,
6626 JPOOL_IMAGE
, row_stride
, 1);
6627 for (y
= 0; y
< height
; ++y
)
6629 fn_jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6630 for (x
= 0; x
< mgr
->cinfo
.output_width
; ++x
)
6631 XPutPixel (ximg
, x
, y
, colors
[buffer
[0][x
]]);
6635 fn_jpeg_finish_decompress (&mgr
->cinfo
);
6636 fn_jpeg_destroy_decompress (&mgr
->cinfo
);
6640 /* Maybe fill in the background field while we have ximg handy. */
6641 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6642 /* Casting avoids a GCC warning. */
6643 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6645 /* Put ximg into the image. */
6646 image_put_x_image (f
, img
, ximg
, 0);
6651 jpeg_load (struct frame
*f
, struct image
*img
)
6653 struct my_jpeg_error_mgr mgr
;
6654 return jpeg_load_body (f
, img
, &mgr
);
6657 #else /* HAVE_JPEG */
6661 jpeg_load (struct frame
*f
, struct image
*img
)
6663 return ns_load_image (f
, img
,
6664 image_spec_value (img
->spec
, QCfile
, NULL
),
6665 image_spec_value (img
->spec
, QCdata
, NULL
));
6667 #endif /* HAVE_NS */
6669 #endif /* !HAVE_JPEG */
6673 /***********************************************************************
6675 ***********************************************************************/
6677 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6679 static bool tiff_image_p (Lisp_Object object
);
6680 static bool tiff_load (struct frame
*f
, struct image
*img
);
6682 /* The symbol `tiff' identifying images of this type. */
6684 static Lisp_Object Qtiff
;
6686 /* Indices of image specification fields in tiff_format, below. */
6688 enum tiff_keyword_index
6697 TIFF_HEURISTIC_MASK
,
6704 /* Vector of image_keyword structures describing the format
6705 of valid user-defined image specifications. */
6707 static const struct image_keyword tiff_format
[TIFF_LAST
] =
6709 {":type", IMAGE_SYMBOL_VALUE
, 1},
6710 {":data", IMAGE_STRING_VALUE
, 0},
6711 {":file", IMAGE_STRING_VALUE
, 0},
6712 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6713 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6714 {":relief", IMAGE_INTEGER_VALUE
, 0},
6715 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6716 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6717 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6718 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
6719 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0}
6722 #if defined HAVE_NTGUI && defined WINDOWSNT
6723 static bool init_tiff_functions (void);
6725 #define init_tiff_functions NULL
6728 /* Structure describing the image type `tiff'. */
6730 static struct image_type tiff_type
=
6736 init_tiff_functions
,
6740 /* Return true if OBJECT is a valid TIFF image specification. */
6743 tiff_image_p (Lisp_Object object
)
6745 struct image_keyword fmt
[TIFF_LAST
];
6746 memcpy (fmt
, tiff_format
, sizeof fmt
);
6748 if (!parse_image_spec (object
, fmt
, TIFF_LAST
, Qtiff
))
6751 /* Must specify either the :data or :file keyword. */
6752 return fmt
[TIFF_FILE
].count
+ fmt
[TIFF_DATA
].count
== 1;
6755 #endif /* HAVE_TIFF || HAVE_NS */
6763 /* TIFF library details. */
6764 DEF_IMGLIB_FN (TIFFErrorHandler
, TIFFSetErrorHandler
, (TIFFErrorHandler
));
6765 DEF_IMGLIB_FN (TIFFErrorHandler
, TIFFSetWarningHandler
, (TIFFErrorHandler
));
6766 DEF_IMGLIB_FN (TIFF
*, TIFFOpen
, (const char *, const char *));
6767 DEF_IMGLIB_FN (TIFF
*, TIFFClientOpen
, (const char *, const char *, thandle_t
,
6768 TIFFReadWriteProc
, TIFFReadWriteProc
,
6769 TIFFSeekProc
, TIFFCloseProc
, TIFFSizeProc
,
6770 TIFFMapFileProc
, TIFFUnmapFileProc
));
6771 DEF_IMGLIB_FN (int, TIFFGetField
, (TIFF
*, ttag_t
, ...));
6772 DEF_IMGLIB_FN (int, TIFFReadRGBAImage
, (TIFF
*, uint32
, uint32
, uint32
*, int));
6773 DEF_IMGLIB_FN (void, TIFFClose
, (TIFF
*));
6774 DEF_IMGLIB_FN (int, TIFFSetDirectory
, (TIFF
*, tdir_t
));
6777 init_tiff_functions (void)
6781 if (!(library
= w32_delayed_load (Qtiff
)))
6784 LOAD_IMGLIB_FN (library
, TIFFSetErrorHandler
);
6785 LOAD_IMGLIB_FN (library
, TIFFSetWarningHandler
);
6786 LOAD_IMGLIB_FN (library
, TIFFOpen
);
6787 LOAD_IMGLIB_FN (library
, TIFFClientOpen
);
6788 LOAD_IMGLIB_FN (library
, TIFFGetField
);
6789 LOAD_IMGLIB_FN (library
, TIFFReadRGBAImage
);
6790 LOAD_IMGLIB_FN (library
, TIFFClose
);
6791 LOAD_IMGLIB_FN (library
, TIFFSetDirectory
);
6797 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6798 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6799 #define fn_TIFFOpen TIFFOpen
6800 #define fn_TIFFClientOpen TIFFClientOpen
6801 #define fn_TIFFGetField TIFFGetField
6802 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6803 #define fn_TIFFClose TIFFClose
6804 #define fn_TIFFSetDirectory TIFFSetDirectory
6805 #endif /* WINDOWSNT */
6808 /* Reading from a memory buffer for TIFF images Based on the PNG
6809 memory source, but we have to provide a lot of extra functions.
6812 We really only need to implement read and seek, but I am not
6813 convinced that the TIFF library is smart enough not to destroy
6814 itself if we only hand it the function pointers we need to
6819 unsigned char *bytes
;
6826 tiff_read_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
6828 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
6830 size
= min (size
, src
->len
- src
->index
);
6831 memcpy (buf
, src
->bytes
+ src
->index
, size
);
6837 tiff_write_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
6843 tiff_seek_in_memory (thandle_t data
, toff_t off
, int whence
)
6845 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
6850 case SEEK_SET
: /* Go from beginning of source. */
6854 case SEEK_END
: /* Go from end of source. */
6855 idx
= src
->len
+ off
;
6858 case SEEK_CUR
: /* Go from current position. */
6859 idx
= src
->index
+ off
;
6862 default: /* Invalid `whence'. */
6866 if (idx
> src
->len
|| idx
< 0)
6874 tiff_close_memory (thandle_t data
)
6881 tiff_mmap_memory (thandle_t data
, tdata_t
*pbase
, toff_t
*psize
)
6883 /* It is already _IN_ memory. */
6888 tiff_unmap_memory (thandle_t data
, tdata_t base
, toff_t size
)
6890 /* We don't need to do this. */
6894 tiff_size_of_memory (thandle_t data
)
6896 return ((tiff_memory_source
*) data
)->len
;
6899 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6900 compiler error compiling tiff_handler, see Bugzilla bug #17406
6901 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6902 this function as external works around that problem. */
6903 #if defined (__MINGW32__) && __GNUC__ == 3
6904 # define MINGW_STATIC
6906 # define MINGW_STATIC static
6910 tiff_handler (const char *, const char *, const char *, va_list)
6911 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6913 tiff_handler (const char *log_format
, const char *title
,
6914 const char *format
, va_list ap
)
6916 /* doprnt is not suitable here, as TIFF handlers are called from
6917 libtiff and are passed arbitrary printf directives. Instead, use
6918 vsnprintf, taking care to be portable to nonstandard environments
6919 where vsnprintf returns -1 on buffer overflow. Since it's just a
6920 log entry, it's OK to truncate it. */
6922 int len
= vsnprintf (buf
, sizeof buf
, format
, ap
);
6923 add_to_log (log_format
, build_string (title
),
6924 make_string (buf
, max (0, min (len
, sizeof buf
- 1))));
6928 static void tiff_error_handler (const char *, const char *, va_list)
6929 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6931 tiff_error_handler (const char *title
, const char *format
, va_list ap
)
6933 tiff_handler ("TIFF error: %s %s", title
, format
, ap
);
6937 static void tiff_warning_handler (const char *, const char *, va_list)
6938 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6940 tiff_warning_handler (const char *title
, const char *format
, va_list ap
)
6942 tiff_handler ("TIFF warning: %s %s", title
, format
, ap
);
6946 /* Load TIFF image IMG for use on frame F. Value is true if
6950 tiff_load (struct frame
*f
, struct image
*img
)
6952 Lisp_Object file
, specified_file
;
6953 Lisp_Object specified_data
;
6955 int width
, height
, x
, y
, count
;
6959 tiff_memory_source memsrc
;
6962 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6963 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6965 fn_TIFFSetErrorHandler ((TIFFErrorHandler
) tiff_error_handler
);
6966 fn_TIFFSetWarningHandler ((TIFFErrorHandler
) tiff_warning_handler
);
6968 if (NILP (specified_data
))
6970 /* Read from a file */
6971 file
= x_find_image_file (specified_file
);
6972 if (!STRINGP (file
))
6974 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
6978 file
= ansi_encode_filename (file
);
6981 /* Try to open the image file. */
6982 tiff
= fn_TIFFOpen (SSDATA (file
), "r");
6985 image_error ("Cannot open `%s'", file
, Qnil
);
6991 if (!STRINGP (specified_data
))
6993 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
6997 /* Memory source! */
6998 memsrc
.bytes
= SDATA (specified_data
);
6999 memsrc
.len
= SBYTES (specified_data
);
7002 tiff
= fn_TIFFClientOpen ("memory_source", "r", (thandle_t
)&memsrc
,
7003 tiff_read_from_memory
,
7004 tiff_write_from_memory
,
7005 tiff_seek_in_memory
,
7007 tiff_size_of_memory
,
7013 image_error ("Cannot open memory source for `%s'", img
->spec
, Qnil
);
7018 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
7019 if (INTEGERP (image
))
7021 EMACS_INT ino
= XFASTINT (image
);
7022 if (! (TYPE_MINIMUM (tdir_t
) <= ino
&& ino
<= TYPE_MAXIMUM (tdir_t
)
7023 && fn_TIFFSetDirectory (tiff
, ino
)))
7025 image_error ("Invalid image number `%s' in image `%s'",
7027 fn_TIFFClose (tiff
);
7032 /* Get width and height of the image, and allocate a raster buffer
7033 of width x height 32-bit values. */
7034 fn_TIFFGetField (tiff
, TIFFTAG_IMAGEWIDTH
, &width
);
7035 fn_TIFFGetField (tiff
, TIFFTAG_IMAGELENGTH
, &height
);
7037 if (!check_image_size (f
, width
, height
))
7039 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
7040 fn_TIFFClose (tiff
);
7044 /* Create the X image and pixmap. */
7045 if (! (height
<= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *buf
/ width
7046 && image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
7049 fn_TIFFClose (tiff
);
7053 buf
= xmalloc (sizeof *buf
* width
* height
);
7055 rc
= fn_TIFFReadRGBAImage (tiff
, width
, height
, buf
, 0);
7057 /* Count the number of images in the file. */
7058 for (count
= 1; fn_TIFFSetDirectory (tiff
, count
); count
++)
7062 img
->lisp_data
= Fcons (Qcount
,
7063 Fcons (make_number (count
),
7066 fn_TIFFClose (tiff
);
7069 image_error ("Error reading TIFF image `%s'", img
->spec
, Qnil
);
7074 /* Initialize the color table. */
7075 init_color_table ();
7077 /* Process the pixel raster. Origin is in the lower-left corner. */
7078 for (y
= 0; y
< height
; ++y
)
7080 uint32
*row
= buf
+ y
* width
;
7082 for (x
= 0; x
< width
; ++x
)
7084 uint32 abgr
= row
[x
];
7085 int r
= TIFFGetR (abgr
) << 8;
7086 int g
= TIFFGetG (abgr
) << 8;
7087 int b
= TIFFGetB (abgr
) << 8;
7088 XPutPixel (ximg
, x
, height
- 1 - y
, lookup_rgb_color (f
, r
, g
, b
));
7092 #ifdef COLOR_TABLE_SUPPORT
7093 /* Remember the colors allocated for the image. Free the color table. */
7094 img
->colors
= colors_in_color_table (&img
->ncolors
);
7095 free_color_table ();
7096 #endif /* COLOR_TABLE_SUPPORT */
7099 img
->height
= height
;
7101 /* Maybe fill in the background field while we have ximg handy. */
7102 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7103 /* Casting avoids a GCC warning on W32. */
7104 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7106 /* Put ximg into the image. */
7107 image_put_x_image (f
, img
, ximg
, 0);
7113 #else /* HAVE_TIFF */
7117 tiff_load (struct frame
*f
, struct image
*img
)
7119 return ns_load_image (f
, img
,
7120 image_spec_value (img
->spec
, QCfile
, NULL
),
7121 image_spec_value (img
->spec
, QCdata
, NULL
));
7123 #endif /* HAVE_NS */
7125 #endif /* !HAVE_TIFF */
7129 /***********************************************************************
7131 ***********************************************************************/
7133 #if defined (HAVE_GIF) || defined (HAVE_NS)
7135 static bool gif_image_p (Lisp_Object object
);
7136 static bool gif_load (struct frame
*f
, struct image
*img
);
7137 static void gif_clear_image (struct frame
*f
, struct image
*img
);
7139 /* The symbol `gif' identifying images of this type. */
7141 static Lisp_Object Qgif
;
7143 /* Indices of image specification fields in gif_format, below. */
7145 enum gif_keyword_index
7161 /* Vector of image_keyword structures describing the format
7162 of valid user-defined image specifications. */
7164 static const struct image_keyword gif_format
[GIF_LAST
] =
7166 {":type", IMAGE_SYMBOL_VALUE
, 1},
7167 {":data", IMAGE_STRING_VALUE
, 0},
7168 {":file", IMAGE_STRING_VALUE
, 0},
7169 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7170 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7171 {":relief", IMAGE_INTEGER_VALUE
, 0},
7172 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7173 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7174 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7175 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0},
7176 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
7179 #if defined HAVE_NTGUI && defined WINDOWSNT
7180 static bool init_gif_functions (void);
7182 #define init_gif_functions NULL
7185 /* Structure describing the image type `gif'. */
7187 static struct image_type gif_type
=
7197 /* Free X resources of GIF image IMG which is used on frame F. */
7200 gif_clear_image (struct frame
*f
, struct image
*img
)
7202 img
->lisp_data
= Qnil
;
7203 x_clear_image (f
, img
);
7206 /* Return true if OBJECT is a valid GIF image specification. */
7209 gif_image_p (Lisp_Object object
)
7211 struct image_keyword fmt
[GIF_LAST
];
7212 memcpy (fmt
, gif_format
, sizeof fmt
);
7214 if (!parse_image_spec (object
, fmt
, GIF_LAST
, Qgif
))
7217 /* Must specify either the :data or :file keyword. */
7218 return fmt
[GIF_FILE
].count
+ fmt
[GIF_DATA
].count
== 1;
7221 #endif /* HAVE_GIF */
7225 #if defined (HAVE_NTGUI)
7227 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7228 Undefine before redefining to avoid a preprocessor warning. */
7232 /* avoid conflict with QuickdrawText.h */
7233 #define DrawText gif_DrawText
7234 #include <gif_lib.h>
7237 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7238 #ifndef GIFLIB_MINOR
7239 #define GIFLIB_MINOR 0
7241 #ifndef GIFLIB_RELEASE
7242 #define GIFLIB_RELEASE 0
7245 #else /* HAVE_NTGUI */
7247 #include <gif_lib.h>
7249 #endif /* HAVE_NTGUI */
7251 /* Giflib before 5.0 didn't define these macros. */
7252 #ifndef GIFLIB_MAJOR
7253 #define GIFLIB_MAJOR 4
7258 /* GIF library details. */
7259 DEF_IMGLIB_FN (int, DGifCloseFile
, (GifFileType
*));
7260 DEF_IMGLIB_FN (int, DGifSlurp
, (GifFileType
*));
7261 #if GIFLIB_MAJOR < 5
7262 DEF_IMGLIB_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
));
7263 DEF_IMGLIB_FN (GifFileType
*, DGifOpenFileName
, (const char *));
7265 DEF_IMGLIB_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
, int *));
7266 DEF_IMGLIB_FN (GifFileType
*, DGifOpenFileName
, (const char *, int *));
7267 DEF_IMGLIB_FN (char *, GifErrorString
, (int));
7271 init_gif_functions (void)
7275 if (!(library
= w32_delayed_load (Qgif
)))
7278 LOAD_IMGLIB_FN (library
, DGifCloseFile
);
7279 LOAD_IMGLIB_FN (library
, DGifSlurp
);
7280 LOAD_IMGLIB_FN (library
, DGifOpen
);
7281 LOAD_IMGLIB_FN (library
, DGifOpenFileName
);
7282 #if GIFLIB_MAJOR >= 5
7283 LOAD_IMGLIB_FN (library
, GifErrorString
);
7290 #define fn_DGifCloseFile DGifCloseFile
7291 #define fn_DGifSlurp DGifSlurp
7292 #define fn_DGifOpen DGifOpen
7293 #define fn_DGifOpenFileName DGifOpenFileName
7294 #if 5 <= GIFLIB_MAJOR
7295 # define fn_GifErrorString GifErrorString
7298 #endif /* WINDOWSNT */
7300 /* Reading a GIF image from memory
7301 Based on the PNG memory stuff to a certain extent. */
7305 unsigned char *bytes
;
7311 /* Make the current memory source available to gif_read_from_memory.
7312 It's done this way because not all versions of libungif support
7313 a UserData field in the GifFileType structure. */
7314 static gif_memory_source
*current_gif_memory_src
;
7317 gif_read_from_memory (GifFileType
*file
, GifByteType
*buf
, int len
)
7319 gif_memory_source
*src
= current_gif_memory_src
;
7321 if (len
> src
->len
- src
->index
)
7324 memcpy (buf
, src
->bytes
+ src
->index
, len
);
7330 /* Load GIF image IMG for use on frame F. Value is true if
7333 static const int interlace_start
[] = {0, 4, 2, 1};
7334 static const int interlace_increment
[] = {8, 8, 4, 2};
7336 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7339 gif_load (struct frame
*f
, struct image
*img
)
7342 int rc
, width
, height
, x
, y
, i
, j
;
7344 ColorMapObject
*gif_color_map
;
7345 unsigned long pixel_colors
[256];
7347 gif_memory_source memsrc
;
7348 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
7349 Lisp_Object specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7350 Lisp_Object specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7351 unsigned long bgcolor
= 0;
7353 #if GIFLIB_MAJOR >= 5
7357 if (NILP (specified_data
))
7359 file
= x_find_image_file (specified_file
);
7360 if (!STRINGP (file
))
7362 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
7366 file
= ansi_encode_filename (file
);
7369 /* Open the GIF file. */
7370 #if GIFLIB_MAJOR < 5
7371 gif
= fn_DGifOpenFileName (SSDATA (file
));
7374 image_error ("Cannot open `%s'", file
, Qnil
);
7378 gif
= fn_DGifOpenFileName (SSDATA (file
), &gif_err
);
7381 image_error ("Cannot open `%s': %s",
7382 file
, build_string (fn_GifErrorString (gif_err
)));
7389 if (!STRINGP (specified_data
))
7391 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
7395 /* Read from memory! */
7396 current_gif_memory_src
= &memsrc
;
7397 memsrc
.bytes
= SDATA (specified_data
);
7398 memsrc
.len
= SBYTES (specified_data
);
7401 #if GIFLIB_MAJOR < 5
7402 gif
= fn_DGifOpen (&memsrc
, gif_read_from_memory
);
7405 image_error ("Cannot open memory source `%s'", img
->spec
, Qnil
);
7409 gif
= fn_DGifOpen (&memsrc
, gif_read_from_memory
, &gif_err
);
7412 image_error ("Cannot open memory source `%s': %s",
7413 img
->spec
, build_string (fn_GifErrorString (gif_err
)));
7419 /* Before reading entire contents, check the declared image size. */
7420 if (!check_image_size (f
, gif
->SWidth
, gif
->SHeight
))
7422 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
7423 fn_DGifCloseFile (gif
);
7427 /* Read entire contents. */
7428 rc
= fn_DGifSlurp (gif
);
7429 if (rc
== GIF_ERROR
|| gif
->ImageCount
<= 0)
7431 image_error ("Error reading `%s'", img
->spec
, Qnil
);
7432 fn_DGifCloseFile (gif
);
7436 /* Which sub-image are we to display? */
7438 Lisp_Object image_number
= image_spec_value (img
->spec
, QCindex
, NULL
);
7439 idx
= INTEGERP (image_number
) ? XFASTINT (image_number
) : 0;
7440 if (idx
< 0 || idx
>= gif
->ImageCount
)
7442 image_error ("Invalid image number `%s' in image `%s'",
7443 image_number
, img
->spec
);
7444 fn_DGifCloseFile (gif
);
7449 width
= img
->width
= gif
->SWidth
;
7450 height
= img
->height
= gif
->SHeight
;
7452 img
->corners
[TOP_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Top
;
7453 img
->corners
[LEFT_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Left
;
7454 img
->corners
[BOT_CORNER
]
7455 = img
->corners
[TOP_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Height
;
7456 img
->corners
[RIGHT_CORNER
]
7457 = img
->corners
[LEFT_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Width
;
7459 if (!check_image_size (f
, width
, height
))
7461 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
7462 fn_DGifCloseFile (gif
);
7466 /* Check that the selected subimages fit. It's not clear whether
7467 the GIF spec requires this, but Emacs can crash if they don't fit. */
7468 for (j
= 0; j
<= idx
; ++j
)
7470 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7471 int subimg_width
= subimage
->ImageDesc
.Width
;
7472 int subimg_height
= subimage
->ImageDesc
.Height
;
7473 int subimg_top
= subimage
->ImageDesc
.Top
;
7474 int subimg_left
= subimage
->ImageDesc
.Left
;
7475 if (! (0 <= subimg_width
&& 0 <= subimg_height
7476 && 0 <= subimg_top
&& subimg_top
<= height
- subimg_height
7477 && 0 <= subimg_left
&& subimg_left
<= width
- subimg_width
))
7479 image_error ("Subimage does not fit in image", Qnil
, Qnil
);
7480 fn_DGifCloseFile (gif
);
7485 /* Create the X image and pixmap. */
7486 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
7488 fn_DGifCloseFile (gif
);
7492 /* Clear the part of the screen image not covered by the image.
7493 Full animated GIF support requires more here (see the gif89 spec,
7494 disposal methods). Let's simply assume that the part not covered
7495 by a sub-image is in the frame's background color. */
7496 for (y
= 0; y
< img
->corners
[TOP_CORNER
]; ++y
)
7497 for (x
= 0; x
< width
; ++x
)
7498 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7500 for (y
= img
->corners
[BOT_CORNER
]; y
< height
; ++y
)
7501 for (x
= 0; x
< width
; ++x
)
7502 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7504 for (y
= img
->corners
[TOP_CORNER
]; y
< img
->corners
[BOT_CORNER
]; ++y
)
7506 for (x
= 0; x
< img
->corners
[LEFT_CORNER
]; ++x
)
7507 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7508 for (x
= img
->corners
[RIGHT_CORNER
]; x
< width
; ++x
)
7509 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7512 /* Read the GIF image into the X image. */
7514 /* FIXME: With the current implementation, loading an animated gif
7515 is quadratic in the number of animation frames, since each frame
7516 is a separate struct image. We must provide a way for a single
7517 gif_load call to construct and save all animation frames. */
7519 init_color_table ();
7520 if (STRINGP (specified_bg
))
7521 bgcolor
= x_alloc_image_color (f
, img
, specified_bg
,
7522 FRAME_BACKGROUND_PIXEL (f
));
7523 for (j
= 0; j
<= idx
; ++j
)
7525 /* We use a local variable `raster' here because RasterBits is a
7526 char *, which invites problems with bytes >= 0x80. */
7527 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7528 unsigned char *raster
= (unsigned char *) subimage
->RasterBits
;
7529 int transparency_color_index
= -1;
7531 int subimg_width
= subimage
->ImageDesc
.Width
;
7532 int subimg_height
= subimage
->ImageDesc
.Height
;
7533 int subimg_top
= subimage
->ImageDesc
.Top
;
7534 int subimg_left
= subimage
->ImageDesc
.Left
;
7536 /* Find the Graphic Control Extension block for this sub-image.
7537 Extract the disposal method and transparency color. */
7538 for (i
= 0; i
< subimage
->ExtensionBlockCount
; i
++)
7540 ExtensionBlock
*extblock
= subimage
->ExtensionBlocks
+ i
;
7542 if ((extblock
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
)
7543 && extblock
->ByteCount
== 4
7544 && extblock
->Bytes
[0] & 1)
7546 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7547 to background". Treat any other value like 2. */
7548 disposal
= (extblock
->Bytes
[0] >> 2) & 7;
7549 transparency_color_index
= (unsigned char) extblock
->Bytes
[3];
7554 /* We can't "keep in place" the first subimage. */
7558 /* For disposal == 0, the spec says "No disposal specified. The
7559 decoder is not required to take any action." In practice, it
7560 seems we need to treat this like "keep in place", see e.g.
7561 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7565 /* Allocate subimage colors. */
7566 memset (pixel_colors
, 0, sizeof pixel_colors
);
7567 gif_color_map
= subimage
->ImageDesc
.ColorMap
;
7569 gif_color_map
= gif
->SColorMap
;
7572 for (i
= 0; i
< gif_color_map
->ColorCount
; ++i
)
7574 if (transparency_color_index
== i
)
7575 pixel_colors
[i
] = STRINGP (specified_bg
)
7576 ? bgcolor
: FRAME_BACKGROUND_PIXEL (f
);
7579 int r
= gif_color_map
->Colors
[i
].Red
<< 8;
7580 int g
= gif_color_map
->Colors
[i
].Green
<< 8;
7581 int b
= gif_color_map
->Colors
[i
].Blue
<< 8;
7582 pixel_colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
7586 /* Apply the pixel values. */
7587 if (gif
->SavedImages
[j
].ImageDesc
.Interlace
)
7591 for (y
= 0, row
= interlace_start
[0], pass
= 0;
7593 y
++, row
+= interlace_increment
[pass
])
7595 while (subimg_height
<= row
)
7596 row
= interlace_start
[++pass
];
7598 for (x
= 0; x
< subimg_width
; x
++)
7600 int c
= raster
[y
* subimg_width
+ x
];
7601 if (transparency_color_index
!= c
|| disposal
!= 1)
7602 XPutPixel (ximg
, x
+ subimg_left
, row
+ subimg_top
,
7609 for (y
= 0; y
< subimg_height
; ++y
)
7610 for (x
= 0; x
< subimg_width
; ++x
)
7612 int c
= raster
[y
* subimg_width
+ x
];
7613 if (transparency_color_index
!= c
|| disposal
!= 1)
7614 XPutPixel (ximg
, x
+ subimg_left
, y
+ subimg_top
,
7620 #ifdef COLOR_TABLE_SUPPORT
7621 img
->colors
= colors_in_color_table (&img
->ncolors
);
7622 free_color_table ();
7623 #endif /* COLOR_TABLE_SUPPORT */
7625 /* Save GIF image extension data for `image-metadata'.
7626 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7627 img
->lisp_data
= Qnil
;
7628 if (gif
->SavedImages
[idx
].ExtensionBlockCount
> 0)
7631 ExtensionBlock
*ext
= gif
->SavedImages
[idx
].ExtensionBlocks
;
7632 for (i
= 0; i
< gif
->SavedImages
[idx
].ExtensionBlockCount
; i
++, ext
++)
7633 /* Append (... FUNCTION "BYTES") */
7636 = Fcons (make_number (ext
->Function
),
7637 Fcons (make_unibyte_string (ext
->Bytes
, ext
->ByteCount
),
7639 if (ext
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
7640 && ext
->ByteCount
== 4)
7642 delay
= ext
->Bytes
[2] << CHAR_BIT
;
7643 delay
|= ext
->Bytes
[1];
7646 img
->lisp_data
= list2 (Qextension_data
, img
->lisp_data
);
7650 Fcons (make_float (delay
/ 100.0),
7654 if (gif
->ImageCount
> 1)
7655 img
->lisp_data
= Fcons (Qcount
,
7656 Fcons (make_number (gif
->ImageCount
),
7659 fn_DGifCloseFile (gif
);
7661 /* Maybe fill in the background field while we have ximg handy. */
7662 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7663 /* Casting avoids a GCC warning. */
7664 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7666 /* Put ximg into the image. */
7667 image_put_x_image (f
, img
, ximg
, 0);
7672 #else /* !HAVE_GIF */
7676 gif_load (struct frame
*f
, struct image
*img
)
7678 return ns_load_image (f
, img
,
7679 image_spec_value (img
->spec
, QCfile
, NULL
),
7680 image_spec_value (img
->spec
, QCdata
, NULL
));
7682 #endif /* HAVE_NS */
7684 #endif /* HAVE_GIF */
7687 #ifdef HAVE_IMAGEMAGICK
7689 /***********************************************************************
7691 ***********************************************************************/
7693 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
7694 safely rounded and clipped to int range. */
7697 scale_image_size (int size
, size_t divisor
, size_t multiplier
)
7702 double scaled
= s
* multiplier
/ divisor
+ 0.5;
7703 if (scaled
< INT_MAX
)
7709 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
7710 Use SPEC to deduce the size. Store the desired size into
7711 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
7713 compute_image_size (size_t width
, size_t height
,
7715 int *d_width
, int *d_height
)
7718 int desired_width
, desired_height
;
7720 /* If width and/or height is set in the display spec assume we want
7721 to scale to those values. If either h or w is unspecified, the
7722 unspecified should be calculated from the specified to preserve
7724 value
= image_spec_value (spec
, QCwidth
, NULL
);
7725 desired_width
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
7726 value
= image_spec_value (spec
, QCheight
, NULL
);
7727 desired_height
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
7729 if (desired_width
== -1)
7731 value
= image_spec_value (spec
, QCmax_width
, NULL
);
7732 if (NATNUMP (value
))
7734 int max_width
= min (XFASTINT (value
), INT_MAX
);
7735 if (max_width
< width
)
7737 /* The image is wider than :max-width. */
7738 desired_width
= max_width
;
7739 if (desired_height
== -1)
7741 desired_height
= scale_image_size (desired_width
,
7743 value
= image_spec_value (spec
, QCmax_height
, NULL
);
7744 if (NATNUMP (value
))
7746 int max_height
= min (XFASTINT (value
), INT_MAX
);
7747 if (max_height
< desired_height
)
7749 desired_height
= max_height
;
7750 desired_width
= scale_image_size (desired_height
,
7759 if (desired_height
== -1)
7761 value
= image_spec_value (spec
, QCmax_height
, NULL
);
7762 if (NATNUMP (value
))
7764 int max_height
= min (XFASTINT (value
), INT_MAX
);
7765 if (max_height
< height
)
7766 desired_height
= max_height
;
7770 if (desired_width
!= -1 && desired_height
== -1)
7771 /* w known, calculate h. */
7772 desired_height
= scale_image_size (desired_width
, width
, height
);
7774 if (desired_width
== -1 && desired_height
!= -1)
7775 /* h known, calculate w. */
7776 desired_width
= scale_image_size (desired_height
, height
, width
);
7778 *d_width
= desired_width
;
7779 *d_height
= desired_height
;
7782 static Lisp_Object Qimagemagick
;
7784 static bool imagemagick_image_p (Lisp_Object
);
7785 static bool imagemagick_load (struct frame
*, struct image
*);
7786 static void imagemagick_clear_image (struct frame
*, struct image
*);
7788 /* Indices of image specification fields in imagemagick_format. */
7790 enum imagemagick_keyword_index
7798 IMAGEMAGICK_ALGORITHM
,
7799 IMAGEMAGICK_HEURISTIC_MASK
,
7801 IMAGEMAGICK_BACKGROUND
,
7804 IMAGEMAGICK_MAX_HEIGHT
,
7805 IMAGEMAGICK_MAX_WIDTH
,
7807 IMAGEMAGICK_ROTATION
,
7812 /* Vector of image_keyword structures describing the format
7813 of valid user-defined image specifications. */
7815 static struct image_keyword imagemagick_format
[IMAGEMAGICK_LAST
] =
7817 {":type", IMAGE_SYMBOL_VALUE
, 1},
7818 {":data", IMAGE_STRING_VALUE
, 0},
7819 {":file", IMAGE_STRING_VALUE
, 0},
7820 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7821 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7822 {":relief", IMAGE_INTEGER_VALUE
, 0},
7823 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7824 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7825 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7826 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
7827 {":height", IMAGE_INTEGER_VALUE
, 0},
7828 {":width", IMAGE_INTEGER_VALUE
, 0},
7829 {":max-height", IMAGE_INTEGER_VALUE
, 0},
7830 {":max-width", IMAGE_INTEGER_VALUE
, 0},
7831 {":format", IMAGE_SYMBOL_VALUE
, 0},
7832 {":rotation", IMAGE_NUMBER_VALUE
, 0},
7833 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
7836 #if defined HAVE_NTGUI && defined WINDOWSNT
7837 static bool init_imagemagick_functions (void);
7839 #define init_imagemagick_functions NULL
7842 /* Structure describing the image type for any image handled via
7845 static struct image_type imagemagick_type
=
7848 imagemagick_image_p
,
7850 imagemagick_clear_image
,
7851 init_imagemagick_functions
,
7855 /* Free X resources of imagemagick image IMG which is used on frame F. */
7858 imagemagick_clear_image (struct frame
*f
,
7861 x_clear_image (f
, img
);
7864 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7865 this by calling parse_image_spec and supplying the keywords that
7866 identify the IMAGEMAGICK format. */
7869 imagemagick_image_p (Lisp_Object object
)
7871 struct image_keyword fmt
[IMAGEMAGICK_LAST
];
7872 memcpy (fmt
, imagemagick_format
, sizeof fmt
);
7874 if (!parse_image_spec (object
, fmt
, IMAGEMAGICK_LAST
, Qimagemagick
))
7877 /* Must specify either the :data or :file keyword. */
7878 return fmt
[IMAGEMAGICK_FILE
].count
+ fmt
[IMAGEMAGICK_DATA
].count
== 1;
7881 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7882 Therefore rename the function so it doesn't collide with ImageMagick. */
7883 #define DrawRectangle DrawRectangleGif
7884 #include <wand/MagickWand.h>
7886 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7887 Emacs seems to work fine with the hidden version, so unhide it. */
7888 #include <magick/version.h>
7889 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7890 extern WandExport
void PixelGetMagickColor (const PixelWand
*,
7891 MagickPixelPacket
*);
7894 /* Log ImageMagick error message.
7895 Useful when a ImageMagick function returns the status `MagickFalse'. */
7898 imagemagick_error (MagickWand
*wand
)
7901 ExceptionType severity
;
7903 description
= MagickGetException (wand
, &severity
);
7904 image_error ("ImageMagick error: %s",
7905 build_string (description
),
7907 description
= (char *) MagickRelinquishMemory (description
);
7910 /* Possibly give ImageMagick some extra help to determine the image
7911 type by supplying a "dummy" filename based on the Content-Type. */
7914 imagemagick_filename_hint (Lisp_Object spec
, char hint_buffer
[MaxTextExtent
])
7916 Lisp_Object symbol
= intern ("image-format-suffixes");
7917 Lisp_Object val
= find_symbol_value (symbol
);
7923 format
= image_spec_value (spec
, intern (":format"), NULL
);
7924 val
= Fcar_safe (Fcdr_safe (Fassq (format
, val
)));
7925 if (! STRINGP (val
))
7928 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
7929 as ImageMagick would ignore the extra bytes anyway. */
7930 snprintf (hint_buffer
, MaxTextExtent
, "/tmp/foo.%s", SSDATA (val
));
7934 /* Animated images (e.g., GIF89a) are composed from one "master image"
7935 (which is the first one, and then there's a number of images that
7936 follow. If following images have non-transparent colors, these are
7937 composed "on top" of the master image. So, in general, one has to
7938 compute ann the preceding images to be able to display a particular
7941 Computing all the preceding images is too slow, so we maintain a
7942 cache of previously computed images. We have to maintain a cache
7943 separate from the image cache, because the images may be scaled
7946 struct animation_cache
7950 struct timespec update_time
;
7951 struct animation_cache
*next
;
7952 char signature
[FLEXIBLE_ARRAY_MEMBER
];
7955 static struct animation_cache
*animation_cache
= NULL
;
7957 static struct animation_cache
*
7958 imagemagick_create_cache (char *signature
)
7960 struct animation_cache
*cache
7961 = xmalloc (offsetof (struct animation_cache
, signature
)
7962 + strlen (signature
) + 1);
7966 strcpy (cache
->signature
, signature
);
7970 /* Discard cached images that haven't been used for a minute. */
7972 imagemagick_prune_animation_cache (void)
7974 struct animation_cache
**pcache
= &animation_cache
;
7975 struct timespec old
= timespec_sub (current_timespec (),
7976 make_timespec (60, 0));
7980 struct animation_cache
*cache
= *pcache
;
7981 if (timespec_cmp (old
, cache
->update_time
) <= 0)
7982 pcache
= &cache
->next
;
7986 DestroyMagickWand (cache
->wand
);
7987 *pcache
= cache
->next
;
7993 static struct animation_cache
*
7994 imagemagick_get_animation_cache (MagickWand
*wand
)
7996 char *signature
= MagickGetImageSignature (wand
);
7997 struct animation_cache
*cache
;
7998 struct animation_cache
**pcache
= &animation_cache
;
8000 imagemagick_prune_animation_cache ();
8007 *pcache
= cache
= imagemagick_create_cache (signature
);
8010 if (strcmp (signature
, cache
->signature
) == 0)
8012 pcache
= &cache
->next
;
8015 DestroyString (signature
);
8016 cache
->update_time
= current_timespec ();
8021 imagemagick_compute_animated_image (MagickWand
*super_wand
, int ino
)
8024 MagickWand
*composite_wand
;
8025 size_t dest_width
, dest_height
;
8026 struct animation_cache
*cache
= imagemagick_get_animation_cache (super_wand
);
8028 MagickSetIteratorIndex (super_wand
, 0);
8030 if (ino
== 0 || cache
->wand
== NULL
|| cache
->index
> ino
)
8032 composite_wand
= MagickGetImage (super_wand
);
8034 DestroyMagickWand (cache
->wand
);
8037 composite_wand
= cache
->wand
;
8039 dest_width
= MagickGetImageWidth (composite_wand
);
8040 dest_height
= MagickGetImageHeight (composite_wand
);
8042 for (i
= max (1, cache
->index
+ 1); i
<= ino
; i
++)
8044 MagickWand
*sub_wand
;
8045 PixelIterator
*source_iterator
, *dest_iterator
;
8046 PixelWand
**source
, **dest
;
8047 size_t source_width
, source_height
;
8048 ssize_t source_left
, source_top
;
8049 MagickPixelPacket pixel
;
8050 DisposeType dispose
;
8051 ptrdiff_t lines
= 0;
8053 MagickSetIteratorIndex (super_wand
, i
);
8054 sub_wand
= MagickGetImage (super_wand
);
8056 MagickGetImagePage (sub_wand
, &source_width
, &source_height
,
8057 &source_left
, &source_top
);
8059 /* This flag says how to handle transparent pixels. */
8060 dispose
= MagickGetImageDispose (sub_wand
);
8062 source_iterator
= NewPixelIterator (sub_wand
);
8063 if (! source_iterator
)
8065 DestroyMagickWand (composite_wand
);
8066 DestroyMagickWand (sub_wand
);
8068 image_error ("Imagemagick pixel iterator creation failed",
8073 dest_iterator
= NewPixelIterator (composite_wand
);
8074 if (! dest_iterator
)
8076 DestroyMagickWand (composite_wand
);
8077 DestroyMagickWand (sub_wand
);
8078 DestroyPixelIterator (source_iterator
);
8080 image_error ("Imagemagick pixel iterator creation failed",
8085 /* The sub-image may not start at origin, so move the destination
8086 iterator to where the sub-image should start. */
8089 PixelSetIteratorRow (dest_iterator
, source_top
);
8093 while ((source
= PixelGetNextIteratorRow (source_iterator
, &source_width
))
8098 /* Sanity check. This shouldn't happen, but apparently
8099 does in some pictures. */
8100 if (++lines
>= dest_height
)
8103 dest
= PixelGetNextIteratorRow (dest_iterator
, &dest_width
);
8104 for (x
= 0; x
< source_width
; x
++)
8106 /* Sanity check. This shouldn't happen, but apparently
8107 also does in some pictures. */
8108 if (x
+ source_left
> dest_width
- 1)
8110 /* Normally we only copy over non-transparent pixels,
8111 but if the disposal method is "Background", then we
8112 copy over all pixels. */
8113 if (dispose
== BackgroundDispose
||
8114 PixelGetAlpha (source
[x
]))
8116 PixelGetMagickColor (source
[x
], &pixel
);
8117 PixelSetMagickColor (dest
[x
+ source_left
], &pixel
);
8120 PixelSyncIterator (dest_iterator
);
8123 DestroyPixelIterator (source_iterator
);
8124 DestroyPixelIterator (dest_iterator
);
8125 DestroyMagickWand (sub_wand
);
8128 /* Cache a copy for the next iteration. The current wand will be
8129 destroyed by the caller. */
8130 cache
->wand
= CloneMagickWand (composite_wand
);
8133 return composite_wand
;
8137 /* Helper function for imagemagick_load, which does the actual loading
8138 given contents and size, apart from frame and image structures,
8139 passed from imagemagick_load. Uses librimagemagick to do most of
8140 the image processing.
8142 F is a pointer to the Emacs frame; IMG to the image structure to
8143 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8144 be parsed; SIZE is the number of bytes of data; and FILENAME is
8145 either the file name or the image data.
8147 Return true if successful. */
8150 imagemagick_load_image (struct frame
*f
, struct image
*img
,
8151 unsigned char *contents
, unsigned int size
,
8154 size_t width
, height
;
8155 MagickBooleanType status
;
8158 MagickWand
*image_wand
;
8159 PixelIterator
*iterator
;
8160 PixelWand
**pixels
, *bg_wand
= NULL
;
8161 MagickPixelPacket pixel
;
8166 int desired_width
, desired_height
;
8169 char hint_buffer
[MaxTextExtent
];
8170 char *filename_hint
= NULL
;
8172 /* Handle image index for image types who can contain more than one image.
8173 Interface :index is same as for GIF. First we "ping" the image to see how
8174 many sub-images it contains. Pinging is faster than loading the image to
8175 find out things about it. */
8177 /* Initialize the imagemagick environment. */
8178 MagickWandGenesis ();
8179 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
8180 ino
= INTEGERP (image
) ? XFASTINT (image
) : 0;
8181 image_wand
= NewMagickWand ();
8184 status
= MagickReadImage (image_wand
, filename
);
8187 filename_hint
= imagemagick_filename_hint (img
->spec
, hint_buffer
);
8188 MagickSetFilename (image_wand
, filename_hint
);
8189 status
= MagickReadImageBlob (image_wand
, contents
, size
);
8192 if (status
== MagickFalse
)
8194 imagemagick_error (image_wand
);
8195 DestroyMagickWand (image_wand
);
8199 if (ino
< 0 || ino
>= MagickGetNumberImages (image_wand
))
8201 image_error ("Invalid image number `%s' in image `%s'",
8203 DestroyMagickWand (image_wand
);
8207 if (MagickGetNumberImages (image_wand
) > 1)
8210 Fcons (make_number (MagickGetNumberImages (image_wand
)),
8213 /* If we have an animated image, get the new wand based on the
8215 if (MagickGetNumberImages (image_wand
) > 1)
8217 MagickWand
*super_wand
= image_wand
;
8218 image_wand
= imagemagick_compute_animated_image (super_wand
, ino
);
8220 image_wand
= super_wand
;
8222 DestroyMagickWand (super_wand
);
8225 /* Retrieve the frame's background color, for use later. */
8228 Lisp_Object specified_bg
;
8230 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8231 if (!STRINGP (specified_bg
)
8232 || !x_defined_color (f
, SSDATA (specified_bg
), &bgcolor
, 0))
8235 bgcolor
.pixel
= FRAME_BACKGROUND_PIXEL (f
);
8236 x_query_color (f
, &bgcolor
);
8238 ns_query_color (FRAME_BACKGROUND_COLOR (f
), &bgcolor
, 1);
8242 bg_wand
= NewPixelWand ();
8243 PixelSetRed (bg_wand
, (double) bgcolor
.red
/ 65535);
8244 PixelSetGreen (bg_wand
, (double) bgcolor
.green
/ 65535);
8245 PixelSetBlue (bg_wand
, (double) bgcolor
.blue
/ 65535);
8248 compute_image_size (MagickGetImageWidth (image_wand
),
8249 MagickGetImageHeight (image_wand
),
8250 img
->spec
, &desired_width
, &desired_height
);
8252 if (desired_width
!= -1 && desired_height
!= -1)
8254 status
= MagickScaleImage (image_wand
, desired_width
, desired_height
);
8255 if (status
== MagickFalse
)
8257 image_error ("Imagemagick scale failed", Qnil
, Qnil
);
8258 imagemagick_error (image_wand
);
8259 goto imagemagick_error
;
8263 /* crop behaves similar to image slicing in Emacs but is more memory
8265 crop
= image_spec_value (img
->spec
, QCcrop
, NULL
);
8267 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8269 /* After some testing, it seems MagickCropImage is the fastest crop
8270 function in ImageMagick. This crop function seems to do less copying
8271 than the alternatives, but it still reads the entire image into memory
8272 before cropping, which is apparently difficult to avoid when using
8274 size_t crop_width
= XINT (XCAR (crop
));
8276 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8278 size_t crop_height
= XINT (XCAR (crop
));
8280 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8282 ssize_t crop_x
= XINT (XCAR (crop
));
8284 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8286 ssize_t crop_y
= XINT (XCAR (crop
));
8287 MagickCropImage (image_wand
, crop_width
, crop_height
,
8294 /* Furthermore :rotation. we need background color and angle for
8297 TODO background handling for rotation specified_bg =
8298 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8300 value
= image_spec_value (img
->spec
, QCrotation
, NULL
);
8303 rotation
= extract_float (value
);
8304 status
= MagickRotateImage (image_wand
, bg_wand
, rotation
);
8305 if (status
== MagickFalse
)
8307 image_error ("Imagemagick image rotate failed", Qnil
, Qnil
);
8308 imagemagick_error (image_wand
);
8309 goto imagemagick_error
;
8313 /* Set the canvas background color to the frame or specified
8314 background, and flatten the image. Note: as of ImageMagick
8315 6.6.0, SVG image transparency is not handled properly
8316 (e.g. etc/images/splash.svg shows a white background always). */
8318 MagickWand
*new_wand
;
8319 MagickSetImageBackgroundColor (image_wand
, bg_wand
);
8320 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8321 new_wand
= MagickMergeImageLayers (image_wand
, MergeLayer
);
8323 new_wand
= MagickFlattenImages (image_wand
);
8325 DestroyMagickWand (image_wand
);
8326 image_wand
= new_wand
;
8329 /* Finally we are done manipulating the image. Figure out the
8330 resulting width/height and transfer ownership to Emacs. */
8331 height
= MagickGetImageHeight (image_wand
);
8332 width
= MagickGetImageWidth (image_wand
);
8334 if (! (width
<= INT_MAX
&& height
<= INT_MAX
8335 && check_image_size (f
, width
, height
)))
8337 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
8338 goto imagemagick_error
;
8341 /* We can now get a valid pixel buffer from the imagemagick file, if all
8344 init_color_table ();
8346 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8347 if (imagemagick_render_type
!= 0)
8349 /* Magicexportimage is normally faster than pixelpushing. This
8350 method is also well tested. Some aspects of this method are
8351 ad-hoc and needs to be more researched. */
8352 int imagedepth
= 24; /*MagickGetImageDepth(image_wand);*/
8353 const char *exportdepth
= imagedepth
<= 8 ? "I" : "BGRP"; /*"RGBP";*/
8354 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8355 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, imagedepth
,
8358 #ifdef COLOR_TABLE_SUPPORT
8359 free_color_table ();
8361 image_error ("Imagemagick X bitmap allocation failure", Qnil
, Qnil
);
8362 goto imagemagick_error
;
8365 /* Oddly, the below code doesn't seem to work:*/
8366 /* switch(ximg->bitmap_unit){ */
8368 /* pixelwidth=CharPixel; */
8371 /* pixelwidth=ShortPixel; */
8374 /* pixelwidth=LongPixel; */
8378 Here im just guessing the format of the bitmap.
8379 happens to work fine for:
8382 seems about 3 times as fast as pixel pushing(not carefully measured)
8384 pixelwidth
= CharPixel
; /*??? TODO figure out*/
8385 MagickExportImagePixels (image_wand
, 0, 0, width
, height
,
8386 exportdepth
, pixelwidth
, ximg
->data
);
8389 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8391 size_t image_height
;
8393 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8394 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
8397 #ifdef COLOR_TABLE_SUPPORT
8398 free_color_table ();
8400 image_error ("Imagemagick X bitmap allocation failure", Qnil
, Qnil
);
8401 goto imagemagick_error
;
8404 /* Copy imagemagick image to x with primitive yet robust pixel
8405 pusher loop. This has been tested a lot with many different
8408 /* Copy pixels from the imagemagick image structure to the x image map. */
8409 iterator
= NewPixelIterator (image_wand
);
8412 #ifdef COLOR_TABLE_SUPPORT
8413 free_color_table ();
8415 x_destroy_x_image (ximg
);
8416 image_error ("Imagemagick pixel iterator creation failed",
8418 goto imagemagick_error
;
8421 image_height
= MagickGetImageHeight (image_wand
);
8422 for (y
= 0; y
< image_height
; y
++)
8424 pixels
= PixelGetNextIteratorRow (iterator
, &width
);
8427 for (x
= 0; x
< (long) width
; x
++)
8429 PixelGetMagickColor (pixels
[x
], &pixel
);
8430 XPutPixel (ximg
, x
, y
,
8431 lookup_rgb_color (f
,
8437 DestroyPixelIterator (iterator
);
8440 #ifdef COLOR_TABLE_SUPPORT
8441 /* Remember colors allocated for this image. */
8442 img
->colors
= colors_in_color_table (&img
->ncolors
);
8443 free_color_table ();
8444 #endif /* COLOR_TABLE_SUPPORT */
8447 img
->height
= height
;
8449 /* Put ximg into the image. */
8450 image_put_x_image (f
, img
, ximg
, 0);
8452 /* Final cleanup. image_wand should be the only resource left. */
8453 DestroyMagickWand (image_wand
);
8454 if (bg_wand
) DestroyPixelWand (bg_wand
);
8456 /* `MagickWandTerminus' terminates the imagemagick environment. */
8457 MagickWandTerminus ();
8462 DestroyMagickWand (image_wand
);
8463 if (bg_wand
) DestroyPixelWand (bg_wand
);
8465 MagickWandTerminus ();
8466 /* TODO more cleanup. */
8467 image_error ("Error parsing IMAGEMAGICK image `%s'", img
->spec
, Qnil
);
8472 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8473 successful. this function will go into the imagemagick_type structure, and
8474 the prototype thus needs to be compatible with that structure. */
8477 imagemagick_load (struct frame
*f
, struct image
*img
)
8480 Lisp_Object file_name
;
8482 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8483 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8484 if (STRINGP (file_name
))
8488 file
= x_find_image_file (file_name
);
8489 if (!STRINGP (file
))
8491 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
8495 file
= ansi_encode_filename (file
);
8497 success_p
= imagemagick_load_image (f
, img
, 0, 0, SSDATA (file
));
8499 /* Else its not a file, its a lisp object. Load the image from a
8500 lisp object rather than a file. */
8505 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8506 if (!STRINGP (data
))
8508 image_error ("Invalid image data `%s'", data
, Qnil
);
8511 success_p
= imagemagick_load_image (f
, img
, SDATA (data
),
8512 SBYTES (data
), NULL
);
8518 DEFUN ("imagemagick-types", Fimagemagick_types
, Simagemagick_types
, 0, 0, 0,
8519 doc
: /* Return a list of image types supported by ImageMagick.
8520 Each entry in this list is a symbol named after an ImageMagick format
8521 tag. See the ImageMagick manual for a list of ImageMagick formats and
8522 their descriptions (http://www.imagemagick.org/script/formats.php).
8523 You can also try the shell command: `identify -list format'.
8525 Note that ImageMagick recognizes many file-types that Emacs does not
8526 recognize as images, such as C. See `imagemagick-types-enable'
8527 and `imagemagick-types-inhibit'. */)
8530 Lisp_Object typelist
= Qnil
;
8535 Lisp_Object Qimagemagicktype
;
8537 GetExceptionInfo(&ex
);
8538 imtypes
= GetMagickList ("*", &numf
, &ex
);
8539 DestroyExceptionInfo(&ex
);
8541 for (i
= 0; i
< numf
; i
++)
8543 Qimagemagicktype
= intern (imtypes
[i
]);
8544 typelist
= Fcons (Qimagemagicktype
, typelist
);
8546 return Fnreverse (typelist
);
8549 #endif /* defined (HAVE_IMAGEMAGICK) */
8553 /***********************************************************************
8555 ***********************************************************************/
8557 #if defined (HAVE_RSVG)
8559 /* Function prototypes. */
8561 static bool svg_image_p (Lisp_Object object
);
8562 static bool svg_load (struct frame
*f
, struct image
*img
);
8564 static bool svg_load_image (struct frame
*, struct image
*,
8565 unsigned char *, ptrdiff_t);
8567 /* The symbol `svg' identifying images of this type. */
8569 static Lisp_Object Qsvg
;
8571 /* Indices of image specification fields in svg_format, below. */
8573 enum svg_keyword_index
8588 /* Vector of image_keyword structures describing the format
8589 of valid user-defined image specifications. */
8591 static const struct image_keyword svg_format
[SVG_LAST
] =
8593 {":type", IMAGE_SYMBOL_VALUE
, 1},
8594 {":data", IMAGE_STRING_VALUE
, 0},
8595 {":file", IMAGE_STRING_VALUE
, 0},
8596 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8597 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8598 {":relief", IMAGE_INTEGER_VALUE
, 0},
8599 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8600 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8601 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8602 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8605 #if defined HAVE_NTGUI && defined WINDOWSNT
8606 static bool init_svg_functions (void);
8608 #define init_svg_functions NULL
8611 /* Structure describing the image type `svg'. Its the same type of
8612 structure defined for all image formats, handled by emacs image
8613 functions. See struct image_type in dispextern.h. */
8615 static struct image_type svg_type
=
8626 /* Return true if OBJECT is a valid SVG image specification. Do
8627 this by calling parse_image_spec and supplying the keywords that
8628 identify the SVG format. */
8631 svg_image_p (Lisp_Object object
)
8633 struct image_keyword fmt
[SVG_LAST
];
8634 memcpy (fmt
, svg_format
, sizeof fmt
);
8636 if (!parse_image_spec (object
, fmt
, SVG_LAST
, Qsvg
))
8639 /* Must specify either the :data or :file keyword. */
8640 return fmt
[SVG_FILE
].count
+ fmt
[SVG_DATA
].count
== 1;
8643 #include <librsvg/rsvg.h>
8647 /* SVG library functions. */
8648 DEF_IMGLIB_FN (RsvgHandle
*, rsvg_handle_new
, (void));
8649 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions
, (RsvgHandle
*, RsvgDimensionData
*));
8650 DEF_IMGLIB_FN (gboolean
, rsvg_handle_write
, (RsvgHandle
*, const guchar
*, gsize
, GError
**));
8651 DEF_IMGLIB_FN (gboolean
, rsvg_handle_close
, (RsvgHandle
*, GError
**));
8652 DEF_IMGLIB_FN (GdkPixbuf
*, rsvg_handle_get_pixbuf
, (RsvgHandle
*));
8653 DEF_IMGLIB_FN (void *, rsvg_handle_set_size_callback
, (RsvgHandle
*, RsvgSizeFunc
, gpointer
, GDestroyNotify
));
8655 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width
, (const GdkPixbuf
*));
8656 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height
, (const GdkPixbuf
*));
8657 DEF_IMGLIB_FN (guchar
*, gdk_pixbuf_get_pixels
, (const GdkPixbuf
*));
8658 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride
, (const GdkPixbuf
*));
8659 DEF_IMGLIB_FN (GdkColorspace
, gdk_pixbuf_get_colorspace
, (const GdkPixbuf
*));
8660 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels
, (const GdkPixbuf
*));
8661 DEF_IMGLIB_FN (gboolean
, gdk_pixbuf_get_has_alpha
, (const GdkPixbuf
*));
8662 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample
, (const GdkPixbuf
*));
8664 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8665 DEF_IMGLIB_FN (void, g_type_init
, (void));
8667 DEF_IMGLIB_FN (void, g_object_unref
, (gpointer
));
8668 DEF_IMGLIB_FN (void, g_error_free
, (GError
*));
8670 Lisp_Object Qgdk_pixbuf
, Qglib
, Qgobject
;
8673 init_svg_functions (void)
8675 HMODULE library
, gdklib
, glib
, gobject
;
8677 if (!(glib
= w32_delayed_load (Qglib
))
8678 || !(gobject
= w32_delayed_load (Qgobject
))
8679 || !(gdklib
= w32_delayed_load (Qgdk_pixbuf
))
8680 || !(library
= w32_delayed_load (Qsvg
)))
8683 LOAD_IMGLIB_FN (library
, rsvg_handle_new
);
8684 LOAD_IMGLIB_FN (library
, rsvg_handle_get_dimensions
);
8685 LOAD_IMGLIB_FN (library
, rsvg_handle_write
);
8686 LOAD_IMGLIB_FN (library
, rsvg_handle_close
);
8687 LOAD_IMGLIB_FN (library
, rsvg_handle_get_pixbuf
);
8689 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_width
);
8690 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_height
);
8691 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_pixels
);
8692 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_rowstride
);
8693 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_colorspace
);
8694 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_n_channels
);
8695 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_has_alpha
);
8696 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_bits_per_sample
);
8698 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8699 LOAD_IMGLIB_FN (gobject
, g_type_init
);
8701 LOAD_IMGLIB_FN (gobject
, g_object_unref
);
8702 LOAD_IMGLIB_FN (glib
, g_error_free
);
8708 /* The following aliases for library functions allow dynamic loading
8709 to be used on some platforms. */
8710 #define fn_rsvg_handle_new rsvg_handle_new
8711 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8712 #define fn_rsvg_handle_write rsvg_handle_write
8713 #define fn_rsvg_handle_close rsvg_handle_close
8714 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8716 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8717 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8718 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8719 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8720 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8721 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8722 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8723 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8725 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8726 #define fn_g_type_init g_type_init
8728 #define fn_g_object_unref g_object_unref
8729 #define fn_g_error_free g_error_free
8730 #endif /* !WINDOWSNT */
8732 /* Load SVG image IMG for use on frame F. Value is true if
8736 svg_load (struct frame
*f
, struct image
*img
)
8739 Lisp_Object file_name
;
8741 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8742 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8743 if (STRINGP (file_name
))
8746 unsigned char *contents
;
8749 file
= x_find_image_file (file_name
);
8750 if (!STRINGP (file
))
8752 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
8756 /* Read the entire file into memory. */
8757 contents
= slurp_file (SSDATA (file
), &size
);
8758 if (contents
== NULL
)
8760 image_error ("Error loading SVG image `%s'", img
->spec
, Qnil
);
8763 /* If the file was slurped into memory properly, parse it. */
8764 success_p
= svg_load_image (f
, img
, contents
, size
);
8767 /* Else its not a file, its a lisp object. Load the image from a
8768 lisp object rather than a file. */
8773 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8774 if (!STRINGP (data
))
8776 image_error ("Invalid image data `%s'", data
, Qnil
);
8779 success_p
= svg_load_image (f
, img
, SDATA (data
), SBYTES (data
));
8785 /* svg_load_image is a helper function for svg_load, which does the
8786 actual loading given contents and size, apart from frame and image
8787 structures, passed from svg_load.
8789 Uses librsvg to do most of the image processing.
8791 Returns true when successful. */
8793 svg_load_image (struct frame
*f
, /* Pointer to emacs frame structure. */
8794 struct image
*img
, /* Pointer to emacs image structure. */
8795 unsigned char *contents
, /* String containing the SVG XML data to be parsed. */
8796 ptrdiff_t size
) /* Size of data in bytes. */
8798 RsvgHandle
*rsvg_handle
;
8799 RsvgDimensionData dimension_data
;
8804 const guint8
*pixels
;
8807 Lisp_Object specified_bg
;
8812 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8813 /* g_type_init is a glib function that must be called prior to
8814 using gnome type library functions (obsolete since 2.36.0). */
8818 /* Make a handle to a new rsvg object. */
8819 rsvg_handle
= fn_rsvg_handle_new ();
8821 /* Parse the contents argument and fill in the rsvg_handle. */
8822 fn_rsvg_handle_write (rsvg_handle
, contents
, size
, &err
);
8823 if (err
) goto rsvg_error
;
8825 /* The parsing is complete, rsvg_handle is ready to used, close it
8826 for further writes. */
8827 fn_rsvg_handle_close (rsvg_handle
, &err
);
8828 if (err
) goto rsvg_error
;
8830 fn_rsvg_handle_get_dimensions (rsvg_handle
, &dimension_data
);
8831 if (! check_image_size (f
, dimension_data
.width
, dimension_data
.height
))
8833 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
8837 /* We can now get a valid pixel buffer from the svg file, if all
8839 pixbuf
= fn_rsvg_handle_get_pixbuf (rsvg_handle
);
8840 if (!pixbuf
) goto rsvg_error
;
8841 fn_g_object_unref (rsvg_handle
);
8843 /* Extract some meta data from the svg handle. */
8844 width
= fn_gdk_pixbuf_get_width (pixbuf
);
8845 height
= fn_gdk_pixbuf_get_height (pixbuf
);
8846 pixels
= fn_gdk_pixbuf_get_pixels (pixbuf
);
8847 rowstride
= fn_gdk_pixbuf_get_rowstride (pixbuf
);
8849 /* Validate the svg meta data. */
8850 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf
) == GDK_COLORSPACE_RGB
);
8851 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf
) == 4);
8852 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf
));
8853 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf
) == 8);
8855 /* Try to create a x pixmap to hold the svg pixmap. */
8856 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
8858 fn_g_object_unref (pixbuf
);
8862 init_color_table ();
8864 /* Handle alpha channel by combining the image with a background
8866 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8867 if (!STRINGP (specified_bg
)
8868 || !x_defined_color (f
, SSDATA (specified_bg
), &background
, 0))
8871 background
.pixel
= FRAME_BACKGROUND_PIXEL (f
);
8872 x_query_color (f
, &background
);
8874 ns_query_color (FRAME_BACKGROUND_COLOR (f
), &background
, 1);
8878 /* SVG pixmaps specify transparency in the last byte, so right
8879 shift 8 bits to get rid of it, since emacs doesn't support
8881 background
.red
>>= 8;
8882 background
.green
>>= 8;
8883 background
.blue
>>= 8;
8885 /* This loop handles opacity values, since Emacs assumes
8886 non-transparent images. Each pixel must be "flattened" by
8887 calculating the resulting color, given the transparency of the
8888 pixel, and the image background color. */
8889 for (y
= 0; y
< height
; ++y
)
8891 for (x
= 0; x
< width
; ++x
)
8901 opacity
= *pixels
++;
8903 red
= ((red
* opacity
)
8904 + (background
.red
* ((1 << 8) - opacity
)));
8905 green
= ((green
* opacity
)
8906 + (background
.green
* ((1 << 8) - opacity
)));
8907 blue
= ((blue
* opacity
)
8908 + (background
.blue
* ((1 << 8) - opacity
)));
8910 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, red
, green
, blue
));
8913 pixels
+= rowstride
- 4 * width
;
8916 #ifdef COLOR_TABLE_SUPPORT
8917 /* Remember colors allocated for this image. */
8918 img
->colors
= colors_in_color_table (&img
->ncolors
);
8919 free_color_table ();
8920 #endif /* COLOR_TABLE_SUPPORT */
8922 fn_g_object_unref (pixbuf
);
8925 img
->height
= height
;
8927 /* Maybe fill in the background field while we have ximg handy.
8928 Casting avoids a GCC warning. */
8929 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
8931 /* Put ximg into the image. */
8932 image_put_x_image (f
, img
, ximg
, 0);
8937 fn_g_object_unref (rsvg_handle
);
8938 /* FIXME: Use error->message so the user knows what is the actual
8939 problem with the image. */
8940 image_error ("Error parsing SVG image `%s'", img
->spec
, Qnil
);
8941 fn_g_error_free (err
);
8945 #endif /* defined (HAVE_RSVG) */
8950 /***********************************************************************
8952 ***********************************************************************/
8954 #ifdef HAVE_X_WINDOWS
8955 #define HAVE_GHOSTSCRIPT 1
8956 #endif /* HAVE_X_WINDOWS */
8958 #ifdef HAVE_GHOSTSCRIPT
8960 static bool gs_image_p (Lisp_Object object
);
8961 static bool gs_load (struct frame
*f
, struct image
*img
);
8962 static void gs_clear_image (struct frame
*f
, struct image
*img
);
8964 /* Keyword symbols. */
8966 static Lisp_Object QCloader
, QCbounding_box
, QCpt_width
, QCpt_height
;
8968 /* Indices of image specification fields in gs_format, below. */
8970 enum gs_keyword_index
8988 /* Vector of image_keyword structures describing the format
8989 of valid user-defined image specifications. */
8991 static const struct image_keyword gs_format
[GS_LAST
] =
8993 {":type", IMAGE_SYMBOL_VALUE
, 1},
8994 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
8995 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
8996 {":file", IMAGE_STRING_VALUE
, 1},
8997 {":loader", IMAGE_FUNCTION_VALUE
, 0},
8998 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE
, 1},
8999 {":ascent", IMAGE_ASCENT_VALUE
, 0},
9000 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
9001 {":relief", IMAGE_INTEGER_VALUE
, 0},
9002 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9003 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9004 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
9005 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
9008 /* Structure describing the image type `ghostscript'. */
9010 static struct image_type gs_type
=
9021 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9024 gs_clear_image (struct frame
*f
, struct image
*img
)
9026 x_clear_image (f
, img
);
9030 /* Return true if OBJECT is a valid Ghostscript image
9034 gs_image_p (Lisp_Object object
)
9036 struct image_keyword fmt
[GS_LAST
];
9040 memcpy (fmt
, gs_format
, sizeof fmt
);
9042 if (!parse_image_spec (object
, fmt
, GS_LAST
, Qpostscript
))
9045 /* Bounding box must be a list or vector containing 4 integers. */
9046 tem
= fmt
[GS_BOUNDING_BOX
].value
;
9049 for (i
= 0; i
< 4; ++i
, tem
= XCDR (tem
))
9050 if (!CONSP (tem
) || !INTEGERP (XCAR (tem
)))
9055 else if (VECTORP (tem
))
9057 if (ASIZE (tem
) != 4)
9059 for (i
= 0; i
< 4; ++i
)
9060 if (!INTEGERP (AREF (tem
, i
)))
9070 /* Load Ghostscript image IMG for use on frame F. Value is true
9074 gs_load (struct frame
*f
, struct image
*img
)
9076 uprintmax_t printnum1
, printnum2
;
9077 char buffer
[sizeof " " + INT_STRLEN_BOUND (printmax_t
)];
9078 Lisp_Object window_and_pixmap_id
= Qnil
, loader
, pt_height
, pt_width
;
9080 double in_width
, in_height
;
9081 Lisp_Object pixel_colors
= Qnil
;
9083 /* Compute pixel size of pixmap needed from the given size in the
9084 image specification. Sizes in the specification are in pt. 1 pt
9085 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9087 pt_width
= image_spec_value (img
->spec
, QCpt_width
, NULL
);
9088 in_width
= INTEGERP (pt_width
) ? XFASTINT (pt_width
) / 72.0 : 0;
9089 in_width
*= FRAME_RES_X (f
);
9090 pt_height
= image_spec_value (img
->spec
, QCpt_height
, NULL
);
9091 in_height
= INTEGERP (pt_height
) ? XFASTINT (pt_height
) / 72.0 : 0;
9092 in_height
*= FRAME_RES_Y (f
);
9094 if (! (in_width
<= INT_MAX
&& in_height
<= INT_MAX
9095 && check_image_size (f
, in_width
, in_height
)))
9097 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
9100 img
->width
= in_width
;
9101 img
->height
= in_height
;
9103 /* Create the pixmap. */
9104 eassert (img
->pixmap
== NO_PIXMAP
);
9106 if (x_check_image_size (0, img
->width
, img
->height
))
9108 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9110 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
9111 img
->width
, img
->height
,
9112 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)));
9118 image_error ("Unable to create pixmap for `%s'", img
->spec
, Qnil
);
9122 /* Call the loader to fill the pixmap. It returns a process object
9123 if successful. We do not record_unwind_protect here because
9124 other places in redisplay like calling window scroll functions
9125 don't either. Let the Lisp loader use `unwind-protect' instead. */
9126 printnum1
= FRAME_X_WINDOW (f
);
9127 printnum2
= img
->pixmap
;
9128 window_and_pixmap_id
9129 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9131 printnum1
= FRAME_FOREGROUND_PIXEL (f
);
9132 printnum2
= FRAME_BACKGROUND_PIXEL (f
);
9134 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9136 XSETFRAME (frame
, f
);
9137 loader
= image_spec_value (img
->spec
, QCloader
, NULL
);
9139 loader
= intern ("gs-load-image");
9141 img
->lisp_data
= call6 (loader
, frame
, img
->spec
,
9142 make_number (img
->width
),
9143 make_number (img
->height
),
9144 window_and_pixmap_id
,
9146 return PROCESSP (img
->lisp_data
);
9150 /* Kill the Ghostscript process that was started to fill PIXMAP on
9151 frame F. Called from XTread_socket when receiving an event
9152 telling Emacs that Ghostscript has finished drawing. */
9155 x_kill_gs_process (Pixmap pixmap
, struct frame
*f
)
9157 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
9162 /* Find the image containing PIXMAP. */
9163 for (i
= 0; i
< c
->used
; ++i
)
9164 if (c
->images
[i
]->pixmap
== pixmap
)
9167 /* Should someone in between have cleared the image cache, for
9168 instance, give up. */
9172 /* Kill the GS process. We should have found PIXMAP in the image
9173 cache and its image should contain a process object. */
9175 eassert (PROCESSP (img
->lisp_data
));
9176 Fkill_process (img
->lisp_data
, Qnil
);
9177 img
->lisp_data
= Qnil
;
9179 #if defined (HAVE_X_WINDOWS)
9181 /* On displays with a mutable colormap, figure out the colors
9182 allocated for the image by looking at the pixels of an XImage for
9184 class = FRAME_X_VISUAL (f
)->class;
9185 if (class != StaticColor
&& class != StaticGray
&& class != TrueColor
)
9191 /* Try to get an XImage for img->pixmep. */
9192 ximg
= XGetImage (FRAME_X_DISPLAY (f
), img
->pixmap
,
9193 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
9198 /* Initialize the color table. */
9199 init_color_table ();
9201 /* For each pixel of the image, look its color up in the
9202 color table. After having done so, the color table will
9203 contain an entry for each color used by the image. */
9204 for (y
= 0; y
< img
->height
; ++y
)
9205 for (x
= 0; x
< img
->width
; ++x
)
9207 unsigned long pixel
= XGetPixel (ximg
, x
, y
);
9208 lookup_pixel_color (f
, pixel
);
9211 /* Record colors in the image. Free color table and XImage. */
9212 #ifdef COLOR_TABLE_SUPPORT
9213 img
->colors
= colors_in_color_table (&img
->ncolors
);
9214 free_color_table ();
9216 XDestroyImage (ximg
);
9218 #if 0 /* This doesn't seem to be the case. If we free the colors
9219 here, we get a BadAccess later in x_clear_image when
9220 freeing the colors. */
9221 /* We have allocated colors once, but Ghostscript has also
9222 allocated colors on behalf of us. So, to get the
9223 reference counts right, free them once. */
9225 x_free_colors (f
, img
->colors
, img
->ncolors
);
9229 image_error ("Cannot get X image of `%s'; colors will not be freed",
9234 #endif /* HAVE_X_WINDOWS */
9236 /* Now that we have the pixmap, compute mask and transform the
9237 image if requested. */
9239 postprocess_image (f
, img
);
9243 #endif /* HAVE_GHOSTSCRIPT */
9246 /***********************************************************************
9248 ***********************************************************************/
9252 DEFUN ("imagep", Fimagep
, Simagep
, 1, 1, 0,
9253 doc
: /* Value is non-nil if SPEC is a valid image specification. */)
9256 return valid_image_p (spec
) ? Qt
: Qnil
;
9260 DEFUN ("lookup-image", Flookup_image
, Slookup_image
, 1, 1, 0, "")
9265 if (valid_image_p (spec
))
9266 id
= lookup_image (SELECTED_FRAME (), spec
);
9269 return make_number (id
);
9272 #endif /* GLYPH_DEBUG */
9275 /***********************************************************************
9277 ***********************************************************************/
9279 DEFUN ("init-image-library", Finit_image_library
, Sinit_image_library
, 1, 1, 0,
9280 doc
: /* Initialize image library implementing image type TYPE.
9281 Return non-nil if TYPE is a supported image type.
9283 If image libraries are loaded dynamically (currently only the case on
9284 MS-Windows), load the library for TYPE if it is not yet loaded, using
9285 the library file(s) specified by `dynamic-library-alist'. */)
9288 return lookup_image_type (type
) ? Qt
: Qnil
;
9291 /* Look up image type TYPE, and return a pointer to its image_type
9292 structure. Return 0 if TYPE is not a known image type. */
9294 static struct image_type
*
9295 lookup_image_type (Lisp_Object type
)
9297 /* Types pbm and xbm are built-in and always available. */
9298 if (EQ (type
, Qpbm
))
9299 return define_image_type (&pbm_type
);
9301 if (EQ (type
, Qxbm
))
9302 return define_image_type (&xbm_type
);
9304 #if defined (HAVE_XPM) || defined (HAVE_NS)
9305 if (EQ (type
, Qxpm
))
9306 return define_image_type (&xpm_type
);
9309 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9310 if (EQ (type
, Qjpeg
))
9311 return define_image_type (&jpeg_type
);
9314 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9315 if (EQ (type
, Qtiff
))
9316 return define_image_type (&tiff_type
);
9319 #if defined (HAVE_GIF) || defined (HAVE_NS)
9320 if (EQ (type
, Qgif
))
9321 return define_image_type (&gif_type
);
9324 #if defined (HAVE_PNG) || defined (HAVE_NS)
9325 if (EQ (type
, Qpng
))
9326 return define_image_type (&png_type
);
9329 #if defined (HAVE_RSVG)
9330 if (EQ (type
, Qsvg
))
9331 return define_image_type (&svg_type
);
9334 #if defined (HAVE_IMAGEMAGICK)
9335 if (EQ (type
, Qimagemagick
))
9336 return define_image_type (&imagemagick_type
);
9339 #ifdef HAVE_GHOSTSCRIPT
9340 if (EQ (type
, Qpostscript
))
9341 return define_image_type (&gs_type
);
9347 /* Reset image_types before dumping.
9348 Called from Fdump_emacs. */
9351 reset_image_types (void)
9355 struct image_type
*next
= image_types
->next
;
9356 xfree (image_types
);
9362 syms_of_image (void)
9364 /* Initialize this only once; it will be reset before dumping. */
9367 /* Must be defined now because we're going to update it below, while
9368 defining the supported image types. */
9369 DEFVAR_LISP ("image-types", Vimage_types
,
9370 doc
: /* List of potentially supported image types.
9371 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9372 To check whether it is really supported, use `image-type-available-p'. */);
9373 Vimage_types
= Qnil
;
9375 DEFVAR_LISP ("max-image-size", Vmax_image_size
,
9376 doc
: /* Maximum size of images.
9377 Emacs will not load an image into memory if its pixel width or
9378 pixel height exceeds this limit.
9380 If the value is an integer, it directly specifies the maximum
9381 image height and width, measured in pixels. If it is a floating
9382 point number, it specifies the maximum image height and width
9383 as a ratio to the frame height and width. If the value is
9384 non-numeric, there is no explicit limit on the size of images. */);
9385 Vmax_image_size
= make_float (MAX_IMAGE_SIZE
);
9387 DEFSYM (Qcount
, "count");
9388 DEFSYM (Qextension_data
, "extension-data");
9389 DEFSYM (Qdelay
, "delay");
9391 DEFSYM (QCascent
, ":ascent");
9392 DEFSYM (QCmargin
, ":margin");
9393 DEFSYM (QCrelief
, ":relief");
9394 DEFSYM (QCconversion
, ":conversion");
9395 DEFSYM (QCcolor_symbols
, ":color-symbols");
9396 DEFSYM (QCheuristic_mask
, ":heuristic-mask");
9397 DEFSYM (QCindex
, ":index");
9398 DEFSYM (QCgeometry
, ":geometry");
9399 DEFSYM (QCcrop
, ":crop");
9400 DEFSYM (QCrotation
, ":rotation");
9401 DEFSYM (QCmatrix
, ":matrix");
9402 DEFSYM (QCcolor_adjustment
, ":color-adjustment");
9403 DEFSYM (QCmask
, ":mask");
9405 DEFSYM (Qlaplace
, "laplace");
9406 DEFSYM (Qemboss
, "emboss");
9407 DEFSYM (Qedge_detection
, "edge-detection");
9408 DEFSYM (Qheuristic
, "heuristic");
9410 DEFSYM (Qpostscript
, "postscript");
9411 DEFSYM (QCmax_width
, ":max-width");
9412 DEFSYM (QCmax_height
, ":max-height");
9413 #ifdef HAVE_GHOSTSCRIPT
9414 ADD_IMAGE_TYPE (Qpostscript
);
9415 DEFSYM (QCloader
, ":loader");
9416 DEFSYM (QCbounding_box
, ":bounding-box");
9417 DEFSYM (QCpt_width
, ":pt-width");
9418 DEFSYM (QCpt_height
, ":pt-height");
9419 #endif /* HAVE_GHOSTSCRIPT */
9422 DEFSYM (Qlibpng_version
, "libpng-version");
9423 Fset (Qlibpng_version
,
9425 make_number (PNG_LIBPNG_VER
)
9430 DEFSYM (Qlibgif_version
, "libgif-version");
9431 Fset (Qlibgif_version
,
9433 make_number (GIFLIB_MAJOR
* 10000
9434 + GIFLIB_MINOR
* 100
9440 DEFSYM (Qlibjpeg_version
, "libjpeg-version");
9441 Fset (Qlibjpeg_version
,
9443 make_number (JPEG_LIB_VERSION
)
9450 DEFSYM (Qpbm
, "pbm");
9451 ADD_IMAGE_TYPE (Qpbm
);
9453 DEFSYM (Qxbm
, "xbm");
9454 ADD_IMAGE_TYPE (Qxbm
);
9456 #if defined (HAVE_XPM) || defined (HAVE_NS)
9457 DEFSYM (Qxpm
, "xpm");
9458 ADD_IMAGE_TYPE (Qxpm
);
9461 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9462 DEFSYM (Qjpeg
, "jpeg");
9463 ADD_IMAGE_TYPE (Qjpeg
);
9466 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9467 DEFSYM (Qtiff
, "tiff");
9468 ADD_IMAGE_TYPE (Qtiff
);
9471 #if defined (HAVE_GIF) || defined (HAVE_NS)
9472 DEFSYM (Qgif
, "gif");
9473 ADD_IMAGE_TYPE (Qgif
);
9476 #if defined (HAVE_PNG) || defined (HAVE_NS)
9477 DEFSYM (Qpng
, "png");
9478 ADD_IMAGE_TYPE (Qpng
);
9481 #if defined (HAVE_IMAGEMAGICK)
9482 DEFSYM (Qimagemagick
, "imagemagick");
9483 ADD_IMAGE_TYPE (Qimagemagick
);
9486 #if defined (HAVE_RSVG)
9487 DEFSYM (Qsvg
, "svg");
9488 ADD_IMAGE_TYPE (Qsvg
);
9490 /* Other libraries used directly by svg code. */
9491 DEFSYM (Qgdk_pixbuf
, "gdk-pixbuf");
9492 DEFSYM (Qglib
, "glib");
9493 DEFSYM (Qgobject
, "gobject");
9494 #endif /* HAVE_NTGUI */
9495 #endif /* HAVE_RSVG */
9497 defsubr (&Sinit_image_library
);
9498 #ifdef HAVE_IMAGEMAGICK
9499 defsubr (&Simagemagick_types
);
9501 defsubr (&Sclear_image_cache
);
9502 defsubr (&Simage_flush
);
9503 defsubr (&Simage_size
);
9504 defsubr (&Simage_mask_p
);
9505 defsubr (&Simage_metadata
);
9509 defsubr (&Slookup_image
);
9512 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images
,
9513 doc
: /* Non-nil means always draw a cross over disabled images.
9514 Disabled images are those having a `:conversion disabled' property.
9515 A cross is always drawn on black & white displays. */);
9516 cross_disabled_images
= 0;
9518 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path
,
9519 doc
: /* List of directories to search for window system bitmap files. */);
9520 Vx_bitmap_file_path
= decode_env_path (0, PATH_BITMAPS
, 0);
9522 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay
,
9523 doc
: /* Maximum time after which images are removed from the cache.
9524 When an image has not been displayed this many seconds, Emacs
9525 automatically removes it from the image cache. If the cache contains
9526 a large number of images, the actual eviction time may be shorter.
9527 The value can also be nil, meaning the cache is never cleared.
9529 The function `clear-image-cache' disregards this variable. */);
9530 Vimage_cache_eviction_delay
= make_number (300);
9531 #ifdef HAVE_IMAGEMAGICK
9532 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type
,
9533 doc
: /* Integer indicating which ImageMagick rendering method to use.
9535 0 -- the default method (pixel pushing)
9536 1 -- a newer method ("MagickExportImagePixels") that may perform
9537 better (speed etc) in some cases, but has not been as thoroughly
9538 tested with Emacs as the default method. This method requires
9539 ImageMagick version 6.4.6 (approximately) or later.
9541 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9542 imagemagick_render_type
= 0;