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
= 0;
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)
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
= 0;
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
= 1;
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
);
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
= 1;
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 ();
3593 /* XpmReadFileToPixmap is not available in the Windows port of
3594 libxpm. But XpmReadFileToImage almost does what we want. */
3595 rc
= fn_XpmReadFileToImage (&hdc
, SDATA (file
),
3596 &xpm_image
, &xpm_mask
,
3599 rc
= XpmReadFileToImage (FRAME_X_DISPLAY (f
), SSDATA (file
),
3600 &img
->ximg
, &img
->mask_img
,
3602 #endif /* HAVE_NTGUI */
3606 Lisp_Object buffer
= image_spec_value (img
->spec
, QCdata
, NULL
);
3607 if (!STRINGP (buffer
))
3609 image_error ("Invalid image data `%s'", buffer
, Qnil
);
3610 #ifdef ALLOC_XPM_COLORS
3611 xpm_free_color_cache ();
3616 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3617 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3618 rc
= fn_XpmCreateImageFromBuffer (&hdc
, SDATA (buffer
),
3619 &xpm_image
, &xpm_mask
,
3622 rc
= XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f
), SSDATA (buffer
),
3623 &img
->ximg
, &img
->mask_img
,
3625 #endif /* HAVE_NTGUI */
3628 #ifdef HAVE_X_WINDOWS
3629 if (rc
== XpmSuccess
)
3631 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3632 img
->ximg
->width
, img
->ximg
->height
,
3634 if (img
->pixmap
== NO_PIXMAP
)
3636 x_clear_image (f
, img
);
3639 else if (img
->mask_img
)
3641 img
->mask
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
3642 img
->mask_img
->width
,
3643 img
->mask_img
->height
,
3644 img
->mask_img
->depth
);
3645 if (img
->mask
== NO_PIXMAP
)
3647 x_clear_image (f
, img
);
3654 if (rc
== XpmSuccess
)
3656 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3657 img
->colors
= colors_in_color_table (&img
->ncolors
);
3658 #else /* not ALLOC_XPM_COLORS */
3662 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3663 plus some duplicate attributes. */
3664 if (xpm_image
&& xpm_image
->bitmap
)
3666 img
->pixmap
= xpm_image
->bitmap
;
3667 /* XImageFree in libXpm frees XImage struct without destroying
3668 the bitmap, which is what we want. */
3669 fn_XImageFree (xpm_image
);
3671 if (xpm_mask
&& xpm_mask
->bitmap
)
3673 /* The mask appears to be inverted compared with what we expect.
3674 TODO: invert our expectations. See other places where we
3675 have to invert bits because our idea of masks is backwards. */
3677 old_obj
= SelectObject (hdc
, xpm_mask
->bitmap
);
3679 PatBlt (hdc
, 0, 0, xpm_mask
->width
, xpm_mask
->height
, DSTINVERT
);
3680 SelectObject (hdc
, old_obj
);
3682 img
->mask
= xpm_mask
->bitmap
;
3683 fn_XImageFree (xpm_mask
);
3688 #endif /* HAVE_NTGUI */
3690 /* Remember allocated colors. */
3691 img
->colors
= xnmalloc (attrs
.nalloc_pixels
, sizeof *img
->colors
);
3692 img
->ncolors
= attrs
.nalloc_pixels
;
3693 for (i
= 0; i
< attrs
.nalloc_pixels
; ++i
)
3695 img
->colors
[i
] = attrs
.alloc_pixels
[i
];
3696 #ifdef DEBUG_X_COLORS
3697 register_color (img
->colors
[i
]);
3700 #endif /* not ALLOC_XPM_COLORS */
3702 img
->width
= attrs
.width
;
3703 img
->height
= attrs
.height
;
3704 eassert (img
->width
> 0 && img
->height
> 0);
3706 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3708 fn_XpmFreeAttributes (&attrs
);
3710 XpmFreeAttributes (&attrs
);
3711 #endif /* HAVE_NTGUI */
3713 #ifdef HAVE_X_WINDOWS
3714 /* Maybe fill in the background field while we have ximg handy. */
3715 IMAGE_BACKGROUND (img
, f
, img
->ximg
);
3717 /* Fill in the background_transparent field while we have the
3719 image_background_transparent (img
, f
, img
->mask_img
);
3726 #endif /* HAVE_NTGUI */
3731 image_error ("Error opening XPM file (%s)", img
->spec
, Qnil
);
3734 case XpmFileInvalid
:
3735 image_error ("Invalid XPM file (%s)", img
->spec
, Qnil
);
3739 image_error ("Out of memory (%s)", img
->spec
, Qnil
);
3742 case XpmColorFailed
:
3743 image_error ("Color allocation error (%s)", img
->spec
, Qnil
);
3747 image_error ("Unknown error (%s)", img
->spec
, Qnil
);
3752 #ifdef ALLOC_XPM_COLORS
3753 xpm_free_color_cache ();
3755 return rc
== XpmSuccess
;
3758 #endif /* HAVE_XPM */
3760 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3762 /* XPM support functions for NS where libxpm is not available.
3763 Only XPM version 3 (without any extensions) is supported. */
3765 static void xpm_put_color_table_v (Lisp_Object
, const unsigned char *,
3767 static Lisp_Object
xpm_get_color_table_v (Lisp_Object
,
3768 const unsigned char *, int);
3769 static void xpm_put_color_table_h (Lisp_Object
, const unsigned char *,
3771 static Lisp_Object
xpm_get_color_table_h (Lisp_Object
,
3772 const unsigned char *, int);
3774 /* Tokens returned from xpm_scan. */
3783 /* Scan an XPM data and return a character (< 256) or a token defined
3784 by enum xpm_token above. *S and END are the start (inclusive) and
3785 the end (exclusive) addresses of the data, respectively. Advance
3786 *S while scanning. If token is either XPM_TK_IDENT or
3787 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3788 length of the corresponding token, respectively. */
3791 xpm_scan (const unsigned char **s
,
3792 const unsigned char *end
,
3793 const unsigned char **beg
,
3800 /* Skip white-space. */
3801 while (*s
< end
&& (c
= *(*s
)++, c_isspace (c
)))
3804 /* gnus-pointer.xpm uses '-' in its identifier.
3805 sb-dir-plus.xpm uses '+' in its identifier. */
3806 if (c_isalpha (c
) || c
== '_' || c
== '-' || c
== '+')
3810 && (c
= **s
, c_isalnum (c
)
3811 || c
== '_' || c
== '-' || c
== '+'))
3814 return XPM_TK_IDENT
;
3819 while (*s
< end
&& **s
!= '"')
3824 return XPM_TK_STRING
;
3828 if (*s
< end
&& **s
== '*')
3830 /* C-style comment. */
3834 while (*s
< end
&& *(*s
)++ != '*')
3837 while (*s
< end
&& **s
!= '/');
3851 /* Functions for color table lookup in XPM data. A key is a string
3852 specifying the color of each pixel in XPM data. A value is either
3853 an integer that specifies a pixel color, Qt that specifies
3854 transparency, or Qnil for the unspecified color. If the length of
3855 the key string is one, a vector is used as a table. Otherwise, a
3856 hash table is used. */
3859 xpm_make_color_table_v (void (**put_func
) (Lisp_Object
,
3860 const unsigned char *,
3863 Lisp_Object (**get_func
) (Lisp_Object
,
3864 const unsigned char *,
3867 *put_func
= xpm_put_color_table_v
;
3868 *get_func
= xpm_get_color_table_v
;
3869 return Fmake_vector (make_number (256), Qnil
);
3873 xpm_put_color_table_v (Lisp_Object color_table
,
3874 const unsigned char *chars_start
,
3878 ASET (color_table
, *chars_start
, color
);
3882 xpm_get_color_table_v (Lisp_Object color_table
,
3883 const unsigned char *chars_start
,
3886 return AREF (color_table
, *chars_start
);
3890 xpm_make_color_table_h (void (**put_func
) (Lisp_Object
,
3891 const unsigned char *,
3894 Lisp_Object (**get_func
) (Lisp_Object
,
3895 const unsigned char *,
3898 *put_func
= xpm_put_color_table_h
;
3899 *get_func
= xpm_get_color_table_h
;
3900 return make_hash_table (hashtest_equal
, make_number (DEFAULT_HASH_SIZE
),
3901 make_float (DEFAULT_REHASH_SIZE
),
3902 make_float (DEFAULT_REHASH_THRESHOLD
),
3907 xpm_put_color_table_h (Lisp_Object color_table
,
3908 const unsigned char *chars_start
,
3912 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
3913 EMACS_UINT hash_code
;
3914 Lisp_Object chars
= make_unibyte_string (chars_start
, chars_len
);
3916 hash_lookup (table
, chars
, &hash_code
);
3917 hash_put (table
, chars
, color
, hash_code
);
3921 xpm_get_color_table_h (Lisp_Object color_table
,
3922 const unsigned char *chars_start
,
3925 struct Lisp_Hash_Table
*table
= XHASH_TABLE (color_table
);
3927 hash_lookup (table
, make_unibyte_string (chars_start
, chars_len
), NULL
);
3929 return i
>= 0 ? HASH_VALUE (table
, i
) : Qnil
;
3932 enum xpm_color_key
{
3940 static const char xpm_color_key_strings
[][4] = {"s", "m", "g4", "g", "c"};
3943 xpm_str_to_color_key (const char *s
)
3948 i
< sizeof xpm_color_key_strings
/ sizeof xpm_color_key_strings
[0];
3950 if (strcmp (xpm_color_key_strings
[i
], s
) == 0)
3956 xpm_load_image (struct frame
*f
,
3958 const unsigned char *contents
,
3959 const unsigned char *end
)
3961 const unsigned char *s
= contents
, *beg
, *str
;
3962 unsigned char buffer
[BUFSIZ
];
3963 int width
, height
, x
, y
;
3964 int num_colors
, chars_per_pixel
;
3967 void (*put_color_table
) (Lisp_Object
, const unsigned char *, int, Lisp_Object
);
3968 Lisp_Object (*get_color_table
) (Lisp_Object
, const unsigned char *, int);
3969 Lisp_Object frame
, color_symbols
, color_table
;
3972 XImagePtr ximg
= NULL
, mask_img
= NULL
;
3975 LA1 = xpm_scan (&s, end, &beg, &len)
3977 #define expect(TOKEN) \
3980 if (LA1 != (TOKEN)) \
3986 #define expect_ident(IDENT) \
3987 if (LA1 == XPM_TK_IDENT \
3988 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3993 if (!(end
- s
>= 9 && memcmp (s
, "/* XPM */", 9) == 0))
3997 expect_ident ("static");
3998 expect_ident ("char");
4000 expect (XPM_TK_IDENT
);
4005 expect (XPM_TK_STRING
);
4008 memcpy (buffer
, beg
, len
);
4010 if (sscanf (buffer
, "%d %d %d %d", &width
, &height
,
4011 &num_colors
, &chars_per_pixel
) != 4
4012 || width
<= 0 || height
<= 0
4013 || num_colors
<= 0 || chars_per_pixel
<= 0)
4016 if (!check_image_size (f
, width
, height
))
4018 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
4022 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0)
4024 || !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
4029 image_error ("Image too large", Qnil
, Qnil
);
4035 XSETFRAME (frame
, f
);
4036 if (!NILP (Fxw_display_color_p (frame
)))
4037 best_key
= XPM_COLOR_KEY_C
;
4038 else if (!NILP (Fx_display_grayscale_p (frame
)))
4039 best_key
= (XFASTINT (Fx_display_planes (frame
)) > 2
4040 ? XPM_COLOR_KEY_G
: XPM_COLOR_KEY_G4
);
4042 best_key
= XPM_COLOR_KEY_M
;
4044 color_symbols
= image_spec_value (img
->spec
, QCcolor_symbols
, NULL
);
4045 if (chars_per_pixel
== 1)
4046 color_table
= xpm_make_color_table_v (&put_color_table
,
4049 color_table
= xpm_make_color_table_h (&put_color_table
,
4052 while (num_colors
-- > 0)
4054 char *color
, *max_color
;
4055 int key
, next_key
, max_key
= 0;
4056 Lisp_Object symbol_color
= Qnil
, color_val
;
4059 expect (XPM_TK_STRING
);
4060 if (len
<= chars_per_pixel
|| len
>= BUFSIZ
+ chars_per_pixel
)
4062 memcpy (buffer
, beg
+ chars_per_pixel
, len
- chars_per_pixel
);
4063 buffer
[len
- chars_per_pixel
] = '\0';
4065 str
= strtok (buffer
, " \t");
4068 key
= xpm_str_to_color_key (str
);
4073 color
= strtok (NULL
, " \t");
4077 while ((str
= strtok (NULL
, " \t")) != NULL
)
4079 next_key
= xpm_str_to_color_key (str
);
4082 color
[strlen (color
)] = ' ';
4085 if (key
== XPM_COLOR_KEY_S
)
4087 if (NILP (symbol_color
))
4088 symbol_color
= build_string (color
);
4090 else if (max_key
< key
&& key
<= best_key
)
4100 if (!NILP (color_symbols
) && !NILP (symbol_color
))
4102 Lisp_Object specified_color
= Fassoc (symbol_color
, color_symbols
);
4104 if (CONSP (specified_color
) && STRINGP (XCDR (specified_color
)))
4106 if (xstrcasecmp (SSDATA (XCDR (specified_color
)), "None") == 0)
4108 else if (x_defined_color (f
, SSDATA (XCDR (specified_color
)),
4110 color_val
= make_number (cdef
.pixel
);
4113 if (NILP (color_val
) && max_key
> 0)
4115 if (xstrcasecmp (max_color
, "None") == 0)
4117 else if (x_defined_color (f
, max_color
, &cdef
, 0))
4118 color_val
= make_number (cdef
.pixel
);
4120 if (!NILP (color_val
))
4121 (*put_color_table
) (color_table
, beg
, chars_per_pixel
, color_val
);
4126 for (y
= 0; y
< height
; y
++)
4128 expect (XPM_TK_STRING
);
4130 if (len
< width
* chars_per_pixel
)
4132 for (x
= 0; x
< width
; x
++, str
+= chars_per_pixel
)
4134 Lisp_Object color_val
=
4135 (*get_color_table
) (color_table
, str
, chars_per_pixel
);
4137 XPutPixel (ximg
, x
, y
,
4138 (INTEGERP (color_val
) ? XINT (color_val
)
4139 : FRAME_FOREGROUND_PIXEL (f
)));
4141 XPutPixel (mask_img
, x
, y
,
4142 (!EQ (color_val
, Qt
) ? PIX_MASK_DRAW
4143 : (have_mask
= 1, PIX_MASK_RETAIN
)));
4145 if (EQ (color_val
, Qt
))
4146 ns_set_alpha (ximg
, x
, y
, 0);
4154 img
->height
= height
;
4156 /* Maybe fill in the background field while we have ximg handy. */
4157 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
4158 IMAGE_BACKGROUND (img
, f
, ximg
);
4160 image_put_x_image (f
, img
, ximg
, 0);
4164 /* Fill in the background_transparent field while we have the
4166 image_background_transparent (img
, f
, mask_img
);
4168 image_put_x_image (f
, img
, mask_img
, 1);
4172 x_destroy_x_image (mask_img
);
4173 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4179 image_error ("Invalid XPM file (%s)", img
->spec
, Qnil
);
4180 x_destroy_x_image (ximg
);
4181 x_destroy_x_image (mask_img
);
4182 x_clear_image (f
, img
);
4191 xpm_load (struct frame
*f
,
4195 Lisp_Object file_name
;
4197 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4198 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
4199 if (STRINGP (file_name
))
4202 unsigned char *contents
;
4205 file
= x_find_image_file (file_name
);
4206 if (!STRINGP (file
))
4208 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
4212 contents
= slurp_file (SSDATA (file
), &size
);
4213 if (contents
== NULL
)
4215 image_error ("Error loading XPM image `%s'", img
->spec
, Qnil
);
4219 success_p
= xpm_load_image (f
, img
, contents
, contents
+ size
);
4226 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
4227 if (!STRINGP (data
))
4229 image_error ("Invalid image data `%s'", data
, Qnil
);
4232 success_p
= xpm_load_image (f
, img
, SDATA (data
),
4233 SDATA (data
) + SBYTES (data
));
4239 #endif /* HAVE_NS && !HAVE_XPM */
4243 /***********************************************************************
4245 ***********************************************************************/
4247 #ifdef COLOR_TABLE_SUPPORT
4249 /* An entry in the color table mapping an RGB color to a pixel color. */
4254 unsigned long pixel
;
4256 /* Next in color table collision list. */
4257 struct ct_color
*next
;
4260 /* The bucket vector size to use. Must be prime. */
4264 /* Value is a hash of the RGB color given by R, G, and B. */
4266 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4268 /* The color hash table. */
4270 static struct ct_color
**ct_table
;
4272 /* Number of entries in the color table. */
4274 static int ct_colors_allocated
;
4277 ct_colors_allocated_max
=
4279 min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof (unsigned long))
4282 /* Initialize the color table. */
4285 init_color_table (void)
4287 int size
= CT_SIZE
* sizeof (*ct_table
);
4288 ct_table
= xzalloc (size
);
4289 ct_colors_allocated
= 0;
4293 /* Free memory associated with the color table. */
4296 free_color_table (void)
4299 struct ct_color
*p
, *next
;
4301 for (i
= 0; i
< CT_SIZE
; ++i
)
4302 for (p
= ct_table
[i
]; p
; p
= next
)
4313 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4314 entry for that color already is in the color table, return the
4315 pixel color of that entry. Otherwise, allocate a new color for R,
4316 G, B, and make an entry in the color table. */
4318 static unsigned long
4319 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4321 unsigned hash
= CT_HASH_RGB (r
, g
, b
);
4322 int i
= hash
% CT_SIZE
;
4324 Display_Info
*dpyinfo
;
4326 /* Handle TrueColor visuals specially, which improves performance by
4327 two orders of magnitude. Freeing colors on TrueColor visuals is
4328 a nop, and pixel colors specify RGB values directly. See also
4329 the Xlib spec, chapter 3.1. */
4330 dpyinfo
= FRAME_DISPLAY_INFO (f
);
4331 if (dpyinfo
->red_bits
> 0)
4333 unsigned long pr
, pg
, pb
;
4335 /* Apply gamma-correction like normal color allocation does. */
4339 color
.red
= r
, color
.green
= g
, color
.blue
= b
;
4340 gamma_correct (f
, &color
);
4341 r
= color
.red
, g
= color
.green
, b
= color
.blue
;
4344 /* Scale down RGB values to the visual's bits per RGB, and shift
4345 them to the right position in the pixel color. Note that the
4346 original RGB values are 16-bit values, as usual in X. */
4347 pr
= (r
>> (16 - dpyinfo
->red_bits
)) << dpyinfo
->red_offset
;
4348 pg
= (g
>> (16 - dpyinfo
->green_bits
)) << dpyinfo
->green_offset
;
4349 pb
= (b
>> (16 - dpyinfo
->blue_bits
)) << dpyinfo
->blue_offset
;
4351 /* Assemble the pixel color. */
4352 return pr
| pg
| pb
;
4355 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4356 if (p
->r
== r
&& p
->g
== g
&& p
->b
== b
)
4362 #ifdef HAVE_X_WINDOWS
4370 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4371 return FRAME_FOREGROUND_PIXEL (f
);
4373 #ifdef HAVE_X_WINDOWS
4378 cmap
= FRAME_X_COLORMAP (f
);
4379 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4382 ++ct_colors_allocated
;
4383 p
= xmalloc (sizeof *p
);
4387 p
->pixel
= color
.pixel
;
4388 p
->next
= ct_table
[i
];
4392 return FRAME_FOREGROUND_PIXEL (f
);
4396 color
= PALETTERGB (r
, g
, b
);
4398 color
= RGB_TO_ULONG (r
, g
, b
);
4399 #endif /* HAVE_NTGUI */
4400 ++ct_colors_allocated
;
4401 p
= xmalloc (sizeof *p
);
4406 p
->next
= ct_table
[i
];
4408 #endif /* HAVE_X_WINDOWS */
4416 /* Look up pixel color PIXEL which is used on frame F in the color
4417 table. If not already present, allocate it. Value is PIXEL. */
4419 static unsigned long
4420 lookup_pixel_color (struct frame
*f
, unsigned long pixel
)
4422 int i
= pixel
% CT_SIZE
;
4425 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4426 if (p
->pixel
== pixel
)
4435 if (ct_colors_allocated_max
<= ct_colors_allocated
)
4436 return FRAME_FOREGROUND_PIXEL (f
);
4438 #ifdef HAVE_X_WINDOWS
4439 cmap
= FRAME_X_COLORMAP (f
);
4440 color
.pixel
= pixel
;
4441 x_query_color (f
, &color
);
4442 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4445 cmap
= DefaultColormapOfScreen (FRAME_X_SCREEN (f
));
4446 color
.pixel
= pixel
;
4447 XQueryColor (NULL
, cmap
, &color
);
4448 rc
= x_alloc_nearest_color (f
, cmap
, &color
);
4450 #endif /* HAVE_X_WINDOWS */
4454 ++ct_colors_allocated
;
4456 p
= xmalloc (sizeof *p
);
4461 p
->next
= ct_table
[i
];
4465 return FRAME_FOREGROUND_PIXEL (f
);
4471 /* Value is a vector of all pixel colors contained in the color table,
4472 allocated via xmalloc. Set *N to the number of colors. */
4474 static unsigned long *
4475 colors_in_color_table (int *n
)
4479 unsigned long *colors
;
4481 if (ct_colors_allocated
== 0)
4488 colors
= xmalloc (ct_colors_allocated
* sizeof *colors
);
4489 *n
= ct_colors_allocated
;
4491 for (i
= j
= 0; i
< CT_SIZE
; ++i
)
4492 for (p
= ct_table
[i
]; p
; p
= p
->next
)
4493 colors
[j
++] = p
->pixel
;
4499 #else /* COLOR_TABLE_SUPPORT */
4501 static unsigned long
4502 lookup_rgb_color (struct frame
*f
, int r
, int g
, int b
)
4504 unsigned long pixel
;
4507 pixel
= PALETTERGB (r
>> 8, g
>> 8, b
>> 8);
4508 #endif /* HAVE_NTGUI */
4511 pixel
= RGB_TO_ULONG (r
>> 8, g
>> 8, b
>> 8);
4512 #endif /* HAVE_NS */
4517 init_color_table (void)
4520 #endif /* COLOR_TABLE_SUPPORT */
4523 /***********************************************************************
4525 ***********************************************************************/
4527 /* Edge detection matrices for different edge-detection
4530 static int emboss_matrix
[9] = {
4532 2, -1, 0, /* y - 1 */
4534 0, 1, -2 /* y + 1 */
4537 static int laplace_matrix
[9] = {
4539 1, 0, 0, /* y - 1 */
4541 0, 0, -1 /* y + 1 */
4544 /* Value is the intensity of the color whose red/green/blue values
4547 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4550 /* On frame F, return an array of XColor structures describing image
4551 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4552 means also fill the red/green/blue members of the XColor
4553 structures. Value is a pointer to the array of XColors structures,
4554 allocated with xmalloc; it must be freed by the caller. */
4557 x_to_xcolors (struct frame
*f
, struct image
*img
, bool rgb_p
)
4561 XImagePtr_or_DC ximg
;
4564 #endif /* HAVE_NTGUI */
4566 if (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *colors
/ img
->width
< img
->height
)
4567 memory_full (SIZE_MAX
);
4568 colors
= xmalloc (sizeof *colors
* img
->width
* img
->height
);
4570 /* Get the X image or create a memory device context for IMG. */
4571 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4573 /* Fill the `pixel' members of the XColor array. I wished there
4574 were an easy and portable way to circumvent XGetPixel. */
4576 for (y
= 0; y
< img
->height
; ++y
)
4578 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4580 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4581 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4583 x_query_colors (f
, row
, img
->width
);
4587 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4589 /* W32_TODO: palette support needed here? */
4590 p
->pixel
= GET_PIXEL (ximg
, x
, y
);
4593 p
->red
= RED16_FROM_ULONG (p
->pixel
);
4594 p
->green
= GREEN16_FROM_ULONG (p
->pixel
);
4595 p
->blue
= BLUE16_FROM_ULONG (p
->pixel
);
4598 #endif /* HAVE_X_WINDOWS */
4601 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
4608 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4609 created with CreateDIBSection, with the pointer to the bit values
4610 stored in ximg->data. */
4613 XPutPixel (XImagePtr ximg
, int x
, int y
, COLORREF color
)
4615 int width
= ximg
->info
.bmiHeader
.biWidth
;
4616 unsigned char * pixel
;
4618 /* True color images. */
4619 if (ximg
->info
.bmiHeader
.biBitCount
== 24)
4621 int rowbytes
= width
* 3;
4622 /* Ensure scanlines are aligned on 4 byte boundaries. */
4624 rowbytes
+= 4 - (rowbytes
% 4);
4626 pixel
= ximg
->data
+ y
* rowbytes
+ x
* 3;
4627 /* Windows bitmaps are in BGR order. */
4628 *pixel
= GetBValue (color
);
4629 *(pixel
+ 1) = GetGValue (color
);
4630 *(pixel
+ 2) = GetRValue (color
);
4632 /* Monochrome images. */
4633 else if (ximg
->info
.bmiHeader
.biBitCount
== 1)
4635 int rowbytes
= width
/ 8;
4636 /* Ensure scanlines are aligned on 4 byte boundaries. */
4638 rowbytes
+= 4 - (rowbytes
% 4);
4639 pixel
= ximg
->data
+ y
* rowbytes
+ x
/ 8;
4640 /* Filter out palette info. */
4641 if (color
& 0x00ffffff)
4642 *pixel
= *pixel
| (1 << x
% 8);
4644 *pixel
= *pixel
& ~(1 << x
% 8);
4647 image_error ("XPutPixel: palette image not supported", Qnil
, Qnil
);
4650 #endif /* HAVE_NTGUI */
4652 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4653 RGB members are set. F is the frame on which this all happens.
4654 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4657 x_from_xcolors (struct frame
*f
, struct image
*img
, XColor
*colors
)
4660 XImagePtr oimg
= NULL
;
4663 init_color_table ();
4665 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
| CLEAR_IMAGE_COLORS
);
4666 image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 0,
4669 for (y
= 0; y
< img
->height
; ++y
)
4670 for (x
= 0; x
< img
->width
; ++x
, ++p
)
4672 unsigned long pixel
;
4673 pixel
= lookup_rgb_color (f
, p
->red
, p
->green
, p
->blue
);
4674 XPutPixel (oimg
, x
, y
, pixel
);
4679 image_put_x_image (f
, img
, oimg
, 0);
4680 #ifdef COLOR_TABLE_SUPPORT
4681 img
->colors
= colors_in_color_table (&img
->ncolors
);
4682 free_color_table ();
4683 #endif /* COLOR_TABLE_SUPPORT */
4687 /* On frame F, perform edge-detection on image IMG.
4689 MATRIX is a nine-element array specifying the transformation
4690 matrix. See emboss_matrix for an example.
4692 COLOR_ADJUST is a color adjustment added to each pixel of the
4696 x_detect_edges (struct frame
*f
, struct image
*img
, int *matrix
, int color_adjust
)
4698 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4702 for (i
= sum
= 0; i
< 9; ++i
)
4703 sum
+= eabs (matrix
[i
]);
4705 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4707 if (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *new / img
->width
< img
->height
)
4708 memory_full (SIZE_MAX
);
4709 new = xmalloc (sizeof *new * img
->width
* img
->height
);
4711 for (y
= 0; y
< img
->height
; ++y
)
4713 p
= COLOR (new, 0, y
);
4714 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4715 p
= COLOR (new, img
->width
- 1, y
);
4716 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4719 for (x
= 1; x
< img
->width
- 1; ++x
)
4721 p
= COLOR (new, x
, 0);
4722 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4723 p
= COLOR (new, x
, img
->height
- 1);
4724 p
->red
= p
->green
= p
->blue
= 0xffff/2;
4727 for (y
= 1; y
< img
->height
- 1; ++y
)
4729 p
= COLOR (new, 1, y
);
4731 for (x
= 1; x
< img
->width
- 1; ++x
, ++p
)
4733 int r
, g
, b
, yy
, xx
;
4736 for (yy
= y
- 1; yy
< y
+ 2; ++yy
)
4737 for (xx
= x
- 1; xx
< x
+ 2; ++xx
, ++i
)
4740 XColor
*t
= COLOR (colors
, xx
, yy
);
4741 r
+= matrix
[i
] * t
->red
;
4742 g
+= matrix
[i
] * t
->green
;
4743 b
+= matrix
[i
] * t
->blue
;
4746 r
= (r
/ sum
+ color_adjust
) & 0xffff;
4747 g
= (g
/ sum
+ color_adjust
) & 0xffff;
4748 b
= (b
/ sum
+ color_adjust
) & 0xffff;
4749 p
->red
= p
->green
= p
->blue
= COLOR_INTENSITY (r
, g
, b
);
4754 x_from_xcolors (f
, img
, new);
4760 /* Perform the pre-defined `emboss' edge-detection on image IMG
4764 x_emboss (struct frame
*f
, struct image
*img
)
4766 x_detect_edges (f
, img
, emboss_matrix
, 0xffff / 2);
4770 /* Transform image IMG which is used on frame F with a Laplace
4771 edge-detection algorithm. The result is an image that can be used
4772 to draw disabled buttons, for example. */
4775 x_laplace (struct frame
*f
, struct image
*img
)
4777 x_detect_edges (f
, img
, laplace_matrix
, 45000);
4781 /* Perform edge-detection on image IMG on frame F, with specified
4782 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4784 MATRIX must be either
4786 - a list of at least 9 numbers in row-major form
4787 - a vector of at least 9 numbers
4789 COLOR_ADJUST nil means use a default; otherwise it must be a
4793 x_edge_detection (struct frame
*f
, struct image
*img
, Lisp_Object matrix
,
4794 Lisp_Object color_adjust
)
4802 i
< 9 && CONSP (matrix
) && NUMBERP (XCAR (matrix
));
4803 ++i
, matrix
= XCDR (matrix
))
4804 trans
[i
] = XFLOATINT (XCAR (matrix
));
4806 else if (VECTORP (matrix
) && ASIZE (matrix
) >= 9)
4808 for (i
= 0; i
< 9 && NUMBERP (AREF (matrix
, i
)); ++i
)
4809 trans
[i
] = XFLOATINT (AREF (matrix
, i
));
4812 if (NILP (color_adjust
))
4813 color_adjust
= make_number (0xffff / 2);
4815 if (i
== 9 && NUMBERP (color_adjust
))
4816 x_detect_edges (f
, img
, trans
, XFLOATINT (color_adjust
));
4820 /* Transform image IMG on frame F so that it looks disabled. */
4823 x_disable_image (struct frame
*f
, struct image
*img
)
4825 Display_Info
*dpyinfo
= FRAME_DISPLAY_INFO (f
);
4827 int n_planes
= dpyinfo
->n_planes
* dpyinfo
->n_cbits
;
4829 int n_planes
= dpyinfo
->n_planes
;
4830 #endif /* HAVE_NTGUI */
4834 /* Color (or grayscale). Convert to gray, and equalize. Just
4835 drawing such images with a stipple can look very odd, so
4836 we're using this method instead. */
4837 XColor
*colors
= x_to_xcolors (f
, img
, 1);
4839 const int h
= 15000;
4840 const int l
= 30000;
4842 for (p
= colors
, end
= colors
+ img
->width
* img
->height
;
4846 int i
= COLOR_INTENSITY (p
->red
, p
->green
, p
->blue
);
4847 int i2
= (0xffff - h
- l
) * i
/ 0xffff + l
;
4848 p
->red
= p
->green
= p
->blue
= i2
;
4851 x_from_xcolors (f
, img
, colors
);
4854 /* Draw a cross over the disabled image, if we must or if we
4856 if (n_planes
< 2 || cross_disabled_images
)
4859 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4861 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4863 Display
*dpy
= FRAME_X_DISPLAY (f
);
4866 image_sync_to_pixmaps (f
, img
);
4867 gc
= XCreateGC (dpy
, img
->pixmap
, 0, NULL
);
4868 XSetForeground (dpy
, gc
, BLACK_PIX_DEFAULT (f
));
4869 XDrawLine (dpy
, img
->pixmap
, gc
, 0, 0,
4870 img
->width
- 1, img
->height
- 1);
4871 XDrawLine (dpy
, img
->pixmap
, gc
, 0, img
->height
- 1,
4877 gc
= XCreateGC (dpy
, img
->mask
, 0, NULL
);
4878 XSetForeground (dpy
, gc
, MaskForeground (f
));
4879 XDrawLine (dpy
, img
->mask
, gc
, 0, 0,
4880 img
->width
- 1, img
->height
- 1);
4881 XDrawLine (dpy
, img
->mask
, gc
, 0, img
->height
- 1,
4885 #endif /* !HAVE_NS */
4890 hdc
= get_frame_dc (f
);
4891 bmpdc
= CreateCompatibleDC (hdc
);
4892 release_frame_dc (f
, hdc
);
4894 prev
= SelectObject (bmpdc
, img
->pixmap
);
4896 SetTextColor (bmpdc
, BLACK_PIX_DEFAULT (f
));
4897 MoveToEx (bmpdc
, 0, 0, NULL
);
4898 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
4899 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
4900 LineTo (bmpdc
, img
->width
- 1, 0);
4904 SelectObject (bmpdc
, img
->mask
);
4905 SetTextColor (bmpdc
, WHITE_PIX_DEFAULT (f
));
4906 MoveToEx (bmpdc
, 0, 0, NULL
);
4907 LineTo (bmpdc
, img
->width
- 1, img
->height
- 1);
4908 MoveToEx (bmpdc
, 0, img
->height
- 1, NULL
);
4909 LineTo (bmpdc
, img
->width
- 1, 0);
4911 SelectObject (bmpdc
, prev
);
4913 #endif /* HAVE_NTGUI */
4918 /* Build a mask for image IMG which is used on frame F. FILE is the
4919 name of an image file, for error messages. HOW determines how to
4920 determine the background color of IMG. If it is a list '(R G B)',
4921 with R, G, and B being integers >= 0, take that as the color of the
4922 background. Otherwise, determine the background color of IMG
4926 x_build_heuristic_mask (struct frame
*f
, struct image
*img
, Lisp_Object how
)
4928 XImagePtr_or_DC ximg
;
4935 #endif /* HAVE_NTGUI */
4937 bool use_img_background
;
4938 unsigned long bg
= 0;
4941 x_clear_image_1 (f
, img
, CLEAR_IMAGE_MASK
);
4945 /* Create an image and pixmap serving as mask. */
4946 if (! image_create_x_image_and_pixmap (f
, img
, img
->width
, img
->height
, 1,
4949 #endif /* !HAVE_NS */
4951 /* Create the bit array serving as mask. */
4952 row_width
= (img
->width
+ 7) / 8;
4953 mask_img
= xzalloc (row_width
* img
->height
);
4954 #endif /* HAVE_NTGUI */
4956 /* Get the X image or create a memory device context for IMG. */
4957 ximg
= image_get_x_image_or_dc (f
, img
, 0, &prev
);
4959 /* Determine the background color of ximg. If HOW is `(R G B)'
4960 take that as color. Otherwise, use the image's background color. */
4961 use_img_background
= 1;
4967 for (i
= 0; i
< 3 && CONSP (how
) && NATNUMP (XCAR (how
)); ++i
)
4969 rgb
[i
] = XFASTINT (XCAR (how
)) & 0xffff;
4973 if (i
== 3 && NILP (how
))
4975 char color_name
[30];
4976 sprintf (color_name
, "#%04x%04x%04x", rgb
[0], rgb
[1], rgb
[2]);
4979 0x00ffffff & /* Filter out palette info. */
4980 #endif /* HAVE_NTGUI */
4981 x_alloc_image_color (f
, img
, build_string (color_name
), 0));
4982 use_img_background
= 0;
4986 if (use_img_background
)
4987 bg
= four_corners_best (ximg
, img
->corners
, img
->width
, img
->height
);
4989 /* Set all bits in mask_img to 1 whose color in ximg is different
4990 from the background color bg. */
4992 for (y
= 0; y
< img
->height
; ++y
)
4993 for (x
= 0; x
< img
->width
; ++x
)
4995 XPutPixel (mask_img
, x
, y
, (XGetPixel (ximg
, x
, y
) != bg
4996 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
));
4998 if (XGetPixel (ximg
, x
, y
) == bg
)
4999 ns_set_alpha (ximg
, x
, y
, 0);
5000 #endif /* HAVE_NS */
5002 /* Fill in the background_transparent field while we have the mask handy. */
5003 image_background_transparent (img
, f
, mask_img
);
5005 /* Put mask_img into the image. */
5006 image_put_x_image (f
, img
, mask_img
, 1);
5007 #endif /* !HAVE_NS */
5009 for (y
= 0; y
< img
->height
; ++y
)
5010 for (x
= 0; x
< img
->width
; ++x
)
5012 COLORREF p
= GetPixel (ximg
, x
, y
);
5014 mask_img
[y
* row_width
+ x
/ 8] |= 1 << (x
% 8);
5017 /* Create the mask image. */
5018 img
->mask
= w32_create_pixmap_from_bitmap_data (img
->width
, img
->height
,
5020 /* Fill in the background_transparent field while we have the mask handy. */
5021 SelectObject (ximg
, img
->mask
);
5022 image_background_transparent (img
, f
, ximg
);
5024 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5026 #endif /* HAVE_NTGUI */
5028 image_unget_x_image_or_dc (img
, 0, ximg
, prev
);
5032 /***********************************************************************
5033 PBM (mono, gray, color)
5034 ***********************************************************************/
5036 static bool pbm_image_p (Lisp_Object object
);
5037 static bool pbm_load (struct frame
*f
, struct image
*img
);
5039 /* The symbol `pbm' identifying images of this type. */
5041 static Lisp_Object Qpbm
;
5043 /* Indices of image specification fields in gs_format, below. */
5045 enum pbm_keyword_index
5061 /* Vector of image_keyword structures describing the format
5062 of valid user-defined image specifications. */
5064 static const struct image_keyword pbm_format
[PBM_LAST
] =
5066 {":type", IMAGE_SYMBOL_VALUE
, 1},
5067 {":file", IMAGE_STRING_VALUE
, 0},
5068 {":data", IMAGE_STRING_VALUE
, 0},
5069 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5070 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5071 {":relief", IMAGE_INTEGER_VALUE
, 0},
5072 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5073 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5074 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5075 {":foreground", IMAGE_STRING_OR_NIL_VALUE
, 0},
5076 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5079 /* Structure describing the image type `pbm'. */
5081 static struct image_type pbm_type
=
5092 /* Return true if OBJECT is a valid PBM image specification. */
5095 pbm_image_p (Lisp_Object object
)
5097 struct image_keyword fmt
[PBM_LAST
];
5099 memcpy (fmt
, pbm_format
, sizeof fmt
);
5101 if (!parse_image_spec (object
, fmt
, PBM_LAST
, Qpbm
))
5104 /* Must specify either :data or :file. */
5105 return fmt
[PBM_DATA
].count
+ fmt
[PBM_FILE
].count
== 1;
5109 /* Get next char skipping comments in Netpbm header. Returns -1 at
5113 pbm_next_char (unsigned char **s
, unsigned char *end
)
5117 while (*s
< end
&& (c
= *(*s
)++, c
== '#'))
5119 /* Skip to the next line break. */
5120 while (*s
< end
&& (c
= *(*s
)++, c
!= '\n' && c
!= '\r'))
5130 /* Scan a decimal number from *S and return it. Advance *S while
5131 reading the number. END is the end of the string. Value is -1 at
5135 pbm_scan_number (unsigned char **s
, unsigned char *end
)
5137 int c
= 0, val
= -1;
5139 /* Skip white-space. */
5140 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isspace (c
))
5145 /* Read decimal number. */
5147 while ((c
= pbm_next_char (s
, end
)) != -1 && c_isdigit (c
))
5148 val
= 10 * val
+ c
- '0';
5155 /* Load PBM image IMG for use on frame F. */
5158 pbm_load (struct frame
*f
, struct image
*img
)
5162 int width
, height
, max_color_idx
= 0;
5164 Lisp_Object file
, specified_file
;
5165 enum {PBM_MONO
, PBM_GRAY
, PBM_COLOR
} type
;
5166 unsigned char *contents
= NULL
;
5167 unsigned char *end
, *p
;
5170 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5172 if (STRINGP (specified_file
))
5174 file
= x_find_image_file (specified_file
);
5175 if (!STRINGP (file
))
5177 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
5181 contents
= slurp_file (SSDATA (file
), &size
);
5182 if (contents
== NULL
)
5184 image_error ("Error reading `%s'", file
, Qnil
);
5189 end
= contents
+ size
;
5194 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5195 if (!STRINGP (data
))
5197 image_error ("Invalid image data `%s'", data
, Qnil
);
5201 end
= p
+ SBYTES (data
);
5204 /* Check magic number. */
5205 if (end
- p
< 2 || *p
++ != 'P')
5207 image_error ("Not a PBM image: `%s'", img
->spec
, Qnil
);
5216 raw_p
= 0, type
= PBM_MONO
;
5220 raw_p
= 0, type
= PBM_GRAY
;
5224 raw_p
= 0, type
= PBM_COLOR
;
5228 raw_p
= 1, type
= PBM_MONO
;
5232 raw_p
= 1, type
= PBM_GRAY
;
5236 raw_p
= 1, type
= PBM_COLOR
;
5240 image_error ("Not a PBM image: `%s'", img
->spec
, Qnil
);
5244 /* Read width, height, maximum color-component. Characters
5245 starting with `#' up to the end of a line are ignored. */
5246 width
= pbm_scan_number (&p
, end
);
5247 height
= pbm_scan_number (&p
, end
);
5249 if (type
!= PBM_MONO
)
5251 max_color_idx
= pbm_scan_number (&p
, end
);
5252 if (max_color_idx
> 65535 || max_color_idx
< 0)
5254 image_error ("Unsupported maximum PBM color value", Qnil
, Qnil
);
5259 if (!check_image_size (f
, width
, height
))
5261 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
5265 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5268 /* Initialize the color hash table. */
5269 init_color_table ();
5271 if (type
== PBM_MONO
)
5274 struct image_keyword fmt
[PBM_LAST
];
5275 unsigned long fg
= FRAME_FOREGROUND_PIXEL (f
);
5276 unsigned long bg
= FRAME_BACKGROUND_PIXEL (f
);
5278 /* Parse the image specification. */
5279 memcpy (fmt
, pbm_format
, sizeof fmt
);
5280 parse_image_spec (img
->spec
, fmt
, PBM_LAST
, Qpbm
);
5282 /* Get foreground and background colors, maybe allocate colors. */
5283 if (fmt
[PBM_FOREGROUND
].count
5284 && STRINGP (fmt
[PBM_FOREGROUND
].value
))
5285 fg
= x_alloc_image_color (f
, img
, fmt
[PBM_FOREGROUND
].value
, fg
);
5286 if (fmt
[PBM_BACKGROUND
].count
5287 && STRINGP (fmt
[PBM_BACKGROUND
].value
))
5289 bg
= x_alloc_image_color (f
, img
, fmt
[PBM_BACKGROUND
].value
, bg
);
5290 img
->background
= bg
;
5291 img
->background_valid
= 1;
5294 for (y
= 0; y
< height
; ++y
)
5295 for (x
= 0; x
< width
; ++x
)
5303 x_destroy_x_image (ximg
);
5304 x_clear_image (f
, img
);
5305 image_error ("Invalid image size in image `%s'",
5315 g
= pbm_scan_number (&p
, end
);
5317 XPutPixel (ximg
, x
, y
, g
? fg
: bg
);
5322 int expected_size
= height
* width
;
5323 if (max_color_idx
> 255)
5325 if (type
== PBM_COLOR
)
5328 if (raw_p
&& p
+ expected_size
> end
)
5330 x_destroy_x_image (ximg
);
5331 x_clear_image (f
, img
);
5332 image_error ("Invalid image size in image `%s'",
5337 for (y
= 0; y
< height
; ++y
)
5338 for (x
= 0; x
< width
; ++x
)
5342 if (type
== PBM_GRAY
&& raw_p
)
5345 if (max_color_idx
> 255)
5346 r
= g
= b
= r
* 256 + *p
++;
5348 else if (type
== PBM_GRAY
)
5349 r
= g
= b
= pbm_scan_number (&p
, end
);
5353 if (max_color_idx
> 255)
5356 if (max_color_idx
> 255)
5359 if (max_color_idx
> 255)
5364 r
= pbm_scan_number (&p
, end
);
5365 g
= pbm_scan_number (&p
, end
);
5366 b
= pbm_scan_number (&p
, end
);
5369 if (r
< 0 || g
< 0 || b
< 0)
5371 x_destroy_x_image (ximg
);
5372 image_error ("Invalid pixel value in image `%s'",
5377 /* RGB values are now in the range 0..max_color_idx.
5378 Scale this to the range 0..0xffff supported by X. */
5379 r
= (double) r
* 65535 / max_color_idx
;
5380 g
= (double) g
* 65535 / max_color_idx
;
5381 b
= (double) b
* 65535 / max_color_idx
;
5382 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5386 #ifdef COLOR_TABLE_SUPPORT
5387 /* Store in IMG->colors the colors allocated for the image, and
5388 free the color table. */
5389 img
->colors
= colors_in_color_table (&img
->ncolors
);
5390 free_color_table ();
5391 #endif /* COLOR_TABLE_SUPPORT */
5394 img
->height
= height
;
5396 /* Maybe fill in the background field while we have ximg handy. */
5398 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
5399 /* Casting avoids a GCC warning. */
5400 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
5402 /* Put ximg into the image. */
5403 image_put_x_image (f
, img
, ximg
, 0);
5405 /* X and W32 versions did it here, MAC version above. ++kfs
5407 img->height = height; */
5414 /***********************************************************************
5416 ***********************************************************************/
5418 #if defined (HAVE_PNG) || defined (HAVE_NS)
5420 /* Function prototypes. */
5422 static bool png_image_p (Lisp_Object object
);
5423 static bool png_load (struct frame
*f
, struct image
*img
);
5425 /* The symbol `png' identifying images of this type. */
5427 static Lisp_Object Qpng
;
5429 /* Indices of image specification fields in png_format, below. */
5431 enum png_keyword_index
5446 /* Vector of image_keyword structures describing the format
5447 of valid user-defined image specifications. */
5449 static const struct image_keyword png_format
[PNG_LAST
] =
5451 {":type", IMAGE_SYMBOL_VALUE
, 1},
5452 {":data", IMAGE_STRING_VALUE
, 0},
5453 {":file", IMAGE_STRING_VALUE
, 0},
5454 {":ascent", IMAGE_ASCENT_VALUE
, 0},
5455 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
5456 {":relief", IMAGE_INTEGER_VALUE
, 0},
5457 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5458 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5459 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
5460 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
5463 #if defined HAVE_NTGUI && defined WINDOWSNT
5464 static bool init_png_functions (void);
5466 #define init_png_functions NULL
5469 /* Structure describing the image type `png'. */
5471 static struct image_type png_type
=
5481 /* Return true if OBJECT is a valid PNG image specification. */
5484 png_image_p (Lisp_Object object
)
5486 struct image_keyword fmt
[PNG_LAST
];
5487 memcpy (fmt
, png_format
, sizeof fmt
);
5489 if (!parse_image_spec (object
, fmt
, PNG_LAST
, Qpng
))
5492 /* Must specify either the :data or :file keyword. */
5493 return fmt
[PNG_FILE
].count
+ fmt
[PNG_DATA
].count
== 1;
5496 #endif /* HAVE_PNG || HAVE_NS */
5502 /* PNG library details. */
5504 DEF_IMGLIB_FN (png_voidp
, png_get_io_ptr
, (png_structp
));
5505 DEF_IMGLIB_FN (int, png_sig_cmp
, (png_bytep
, png_size_t
, png_size_t
));
5506 DEF_IMGLIB_FN (png_structp
, png_create_read_struct
, (png_const_charp
, png_voidp
,
5507 png_error_ptr
, png_error_ptr
));
5508 DEF_IMGLIB_FN (png_infop
, png_create_info_struct
, (png_structp
));
5509 DEF_IMGLIB_FN (void, png_destroy_read_struct
, (png_structpp
, png_infopp
, png_infopp
));
5510 DEF_IMGLIB_FN (void, png_set_read_fn
, (png_structp
, png_voidp
, png_rw_ptr
));
5511 DEF_IMGLIB_FN (void, png_set_sig_bytes
, (png_structp
, int));
5512 DEF_IMGLIB_FN (void, png_read_info
, (png_structp
, png_infop
));
5513 DEF_IMGLIB_FN (png_uint_32
, png_get_IHDR
, (png_structp
, png_infop
,
5514 png_uint_32
*, png_uint_32
*,
5515 int *, int *, int *, int *, int *));
5516 DEF_IMGLIB_FN (png_uint_32
, png_get_valid
, (png_structp
, png_infop
, png_uint_32
));
5517 DEF_IMGLIB_FN (void, png_set_strip_16
, (png_structp
));
5518 DEF_IMGLIB_FN (void, png_set_expand
, (png_structp
));
5519 DEF_IMGLIB_FN (void, png_set_gray_to_rgb
, (png_structp
));
5520 DEF_IMGLIB_FN (void, png_set_background
, (png_structp
, png_color_16p
,
5522 DEF_IMGLIB_FN (png_uint_32
, png_get_bKGD
, (png_structp
, png_infop
, png_color_16p
*));
5523 DEF_IMGLIB_FN (void, png_read_update_info
, (png_structp
, png_infop
));
5524 DEF_IMGLIB_FN (png_byte
, png_get_channels
, (png_structp
, png_infop
));
5525 DEF_IMGLIB_FN (png_size_t
, png_get_rowbytes
, (png_structp
, png_infop
));
5526 DEF_IMGLIB_FN (void, png_read_image
, (png_structp
, png_bytepp
));
5527 DEF_IMGLIB_FN (void, png_read_end
, (png_structp
, png_infop
));
5528 DEF_IMGLIB_FN (void, png_error
, (png_structp
, png_const_charp
));
5530 #if (PNG_LIBPNG_VER >= 10500)
5531 DEF_IMGLIB_FN (void, png_longjmp
, (png_structp
, int));
5532 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn
, (png_structp
, png_longjmp_ptr
, size_t));
5533 #endif /* libpng version >= 1.5 */
5536 init_png_functions (void)
5540 if (!(library
= w32_delayed_load (Qpng
)))
5543 LOAD_IMGLIB_FN (library
, png_get_io_ptr
);
5544 LOAD_IMGLIB_FN (library
, png_sig_cmp
);
5545 LOAD_IMGLIB_FN (library
, png_create_read_struct
);
5546 LOAD_IMGLIB_FN (library
, png_create_info_struct
);
5547 LOAD_IMGLIB_FN (library
, png_destroy_read_struct
);
5548 LOAD_IMGLIB_FN (library
, png_set_read_fn
);
5549 LOAD_IMGLIB_FN (library
, png_set_sig_bytes
);
5550 LOAD_IMGLIB_FN (library
, png_read_info
);
5551 LOAD_IMGLIB_FN (library
, png_get_IHDR
);
5552 LOAD_IMGLIB_FN (library
, png_get_valid
);
5553 LOAD_IMGLIB_FN (library
, png_set_strip_16
);
5554 LOAD_IMGLIB_FN (library
, png_set_expand
);
5555 LOAD_IMGLIB_FN (library
, png_set_gray_to_rgb
);
5556 LOAD_IMGLIB_FN (library
, png_set_background
);
5557 LOAD_IMGLIB_FN (library
, png_get_bKGD
);
5558 LOAD_IMGLIB_FN (library
, png_read_update_info
);
5559 LOAD_IMGLIB_FN (library
, png_get_channels
);
5560 LOAD_IMGLIB_FN (library
, png_get_rowbytes
);
5561 LOAD_IMGLIB_FN (library
, png_read_image
);
5562 LOAD_IMGLIB_FN (library
, png_read_end
);
5563 LOAD_IMGLIB_FN (library
, png_error
);
5565 #if (PNG_LIBPNG_VER >= 10500)
5566 LOAD_IMGLIB_FN (library
, png_longjmp
);
5567 LOAD_IMGLIB_FN (library
, png_set_longjmp_fn
);
5568 #endif /* libpng version >= 1.5 */
5574 #define fn_png_get_io_ptr png_get_io_ptr
5575 #define fn_png_sig_cmp png_sig_cmp
5576 #define fn_png_create_read_struct png_create_read_struct
5577 #define fn_png_create_info_struct png_create_info_struct
5578 #define fn_png_destroy_read_struct png_destroy_read_struct
5579 #define fn_png_set_read_fn png_set_read_fn
5580 #define fn_png_set_sig_bytes png_set_sig_bytes
5581 #define fn_png_read_info png_read_info
5582 #define fn_png_get_IHDR png_get_IHDR
5583 #define fn_png_get_valid png_get_valid
5584 #define fn_png_set_strip_16 png_set_strip_16
5585 #define fn_png_set_expand png_set_expand
5586 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5587 #define fn_png_set_background png_set_background
5588 #define fn_png_get_bKGD png_get_bKGD
5589 #define fn_png_read_update_info png_read_update_info
5590 #define fn_png_get_channels png_get_channels
5591 #define fn_png_get_rowbytes png_get_rowbytes
5592 #define fn_png_read_image png_read_image
5593 #define fn_png_read_end png_read_end
5594 #define fn_png_error png_error
5596 #if (PNG_LIBPNG_VER >= 10500)
5597 #define fn_png_longjmp png_longjmp
5598 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5599 #endif /* libpng version >= 1.5 */
5601 #endif /* WINDOWSNT */
5603 /* Possibly inefficient/inexact substitutes for _setjmp and _longjmp.
5604 Do not use sys_setjmp, as PNG supports only jmp_buf. The _longjmp
5605 substitute may munge the signal mask, but that should be OK here.
5606 MinGW (MS-Windows) uses _setjmp and defines setjmp to _setjmp in
5607 the system header setjmp.h; don't mess up that. */
5608 #ifndef HAVE__SETJMP
5609 # define _setjmp(j) setjmp (j)
5610 # define _longjmp longjmp
5613 #if (PNG_LIBPNG_VER < 10500)
5614 #define PNG_LONGJMP(ptr) (_longjmp ((ptr)->jmpbuf, 1))
5615 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5617 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5618 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5619 #define PNG_JMPBUF(ptr) \
5620 (*fn_png_set_longjmp_fn ((ptr), _longjmp, sizeof (jmp_buf)))
5623 /* Error and warning handlers installed when the PNG library
5626 static _Noreturn
void
5627 my_png_error (png_struct
*png_ptr
, const char *msg
)
5629 eassert (png_ptr
!= NULL
);
5630 /* Avoid compiler warning about deprecated direct access to
5631 png_ptr's fields in libpng versions 1.4.x. */
5632 image_error ("PNG error: %s", build_string (msg
), Qnil
);
5633 PNG_LONGJMP (png_ptr
);
5638 my_png_warning (png_struct
*png_ptr
, const char *msg
)
5640 eassert (png_ptr
!= NULL
);
5641 image_error ("PNG warning: %s", build_string (msg
), Qnil
);
5644 /* Memory source for PNG decoding. */
5646 struct png_memory_storage
5648 unsigned char *bytes
; /* The data */
5649 ptrdiff_t len
; /* How big is it? */
5650 ptrdiff_t index
; /* Where are we? */
5654 /* Function set as reader function when reading PNG image from memory.
5655 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5656 bytes from the input to DATA. */
5659 png_read_from_memory (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5661 struct png_memory_storage
*tbr
= fn_png_get_io_ptr (png_ptr
);
5663 if (length
> tbr
->len
- tbr
->index
)
5664 fn_png_error (png_ptr
, "Read error");
5666 memcpy (data
, tbr
->bytes
+ tbr
->index
, length
);
5667 tbr
->index
= tbr
->index
+ length
;
5671 /* Function set as reader function when reading PNG image from a file.
5672 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5673 bytes from the input to DATA. */
5676 png_read_from_file (png_structp png_ptr
, png_bytep data
, png_size_t length
)
5678 FILE *fp
= fn_png_get_io_ptr (png_ptr
);
5680 if (fread (data
, 1, length
, fp
) < length
)
5681 fn_png_error (png_ptr
, "Read error");
5685 /* Load PNG image IMG for use on frame F. Value is true if
5688 struct png_load_context
5690 /* These are members so that longjmp doesn't munge local variables. */
5691 png_struct
*png_ptr
;
5700 png_load_body (struct frame
*f
, struct image
*img
, struct png_load_context
*c
)
5702 Lisp_Object file
, specified_file
;
5703 Lisp_Object specified_data
;
5706 XImagePtr ximg
, mask_img
= NULL
;
5707 png_struct
*png_ptr
;
5708 png_info
*info_ptr
= NULL
, *end_info
= NULL
;
5711 png_byte
*pixels
= NULL
;
5712 png_byte
**rows
= NULL
;
5713 png_uint_32 width
, height
;
5714 int bit_depth
, color_type
, interlace_type
;
5716 png_uint_32 row_bytes
;
5718 struct png_memory_storage tbr
; /* Data to be read */
5720 /* Find out what file to load. */
5721 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
5722 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
5724 if (NILP (specified_data
))
5726 file
= x_find_image_file (specified_file
);
5727 if (!STRINGP (file
))
5729 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
5733 /* Open the image file. */
5734 fp
= emacs_fopen (SSDATA (file
), "rb");
5737 image_error ("Cannot open image file `%s'", file
, Qnil
);
5741 /* Check PNG signature. */
5742 if (fread (sig
, 1, sizeof sig
, fp
) != sizeof sig
5743 || fn_png_sig_cmp (sig
, 0, sizeof sig
))
5746 image_error ("Not a PNG file: `%s'", file
, Qnil
);
5752 if (!STRINGP (specified_data
))
5754 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
5758 /* Read from memory. */
5759 tbr
.bytes
= SDATA (specified_data
);
5760 tbr
.len
= SBYTES (specified_data
);
5763 /* Check PNG signature. */
5764 if (tbr
.len
< sizeof sig
5765 || fn_png_sig_cmp (tbr
.bytes
, 0, sizeof sig
))
5767 image_error ("Not a PNG image: `%s'", img
->spec
, Qnil
);
5771 /* Need to skip past the signature. */
5772 tbr
.bytes
+= sizeof (sig
);
5775 /* Initialize read and info structs for PNG lib. */
5776 png_ptr
= fn_png_create_read_struct (PNG_LIBPNG_VER_STRING
,
5781 info_ptr
= fn_png_create_info_struct (png_ptr
);
5782 end_info
= fn_png_create_info_struct (png_ptr
);
5785 c
->png_ptr
= png_ptr
;
5786 c
->info_ptr
= info_ptr
;
5787 c
->end_info
= end_info
;
5792 if (! (info_ptr
&& end_info
))
5794 fn_png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5799 if (fp
) fclose (fp
);
5803 /* Set error jump-back. We come back here when the PNG library
5804 detects an error. */
5805 if (_setjmp (PNG_JMPBUF (png_ptr
)))
5809 fn_png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
5817 /* Silence a bogus diagnostic; see GCC bug 54561. */
5818 IF_LINT (fp
= c
->fp
);
5820 /* Read image info. */
5821 if (!NILP (specified_data
))
5822 fn_png_set_read_fn (png_ptr
, &tbr
, png_read_from_memory
);
5824 fn_png_set_read_fn (png_ptr
, fp
, png_read_from_file
);
5826 fn_png_set_sig_bytes (png_ptr
, sizeof sig
);
5827 fn_png_read_info (png_ptr
, info_ptr
);
5828 fn_png_get_IHDR (png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
,
5829 &interlace_type
, NULL
, NULL
);
5831 if (! (width
<= INT_MAX
&& height
<= INT_MAX
5832 && check_image_size (f
, width
, height
)))
5834 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
5838 /* Create the X image and pixmap now, so that the work below can be
5839 omitted if the image is too large for X. */
5840 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
5843 /* If image contains simply transparency data, we prefer to
5844 construct a clipping mask. */
5845 if (fn_png_get_valid (png_ptr
, info_ptr
, PNG_INFO_tRNS
))
5850 /* This function is easier to write if we only have to handle
5851 one data format: RGB or RGBA with 8 bits per channel. Let's
5852 transform other formats into that format. */
5854 /* Strip more than 8 bits per channel. */
5855 if (bit_depth
== 16)
5856 fn_png_set_strip_16 (png_ptr
);
5858 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5860 fn_png_set_expand (png_ptr
);
5862 /* Convert grayscale images to RGB. */
5863 if (color_type
== PNG_COLOR_TYPE_GRAY
5864 || color_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
5865 fn_png_set_gray_to_rgb (png_ptr
);
5867 /* Handle alpha channel by combining the image with a background
5868 color. Do this only if a real alpha channel is supplied. For
5869 simple transparency, we prefer a clipping mask. */
5872 /* png_color_16 *image_bg; */
5873 Lisp_Object specified_bg
5874 = image_spec_value (img
->spec
, QCbackground
, NULL
);
5875 int shift
= (bit_depth
== 16) ? 0 : 8;
5877 if (STRINGP (specified_bg
))
5878 /* The user specified `:background', use that. */
5881 if (x_defined_color (f
, SSDATA (specified_bg
), &color
, 0))
5883 png_color_16 user_bg
;
5885 memset (&user_bg
, 0, sizeof user_bg
);
5886 user_bg
.red
= color
.red
>> shift
;
5887 user_bg
.green
= color
.green
>> shift
;
5888 user_bg
.blue
= color
.blue
>> shift
;
5890 fn_png_set_background (png_ptr
, &user_bg
,
5891 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
5896 /* We use the current frame background, ignoring any default
5897 background color set by the image. */
5898 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5900 png_color_16 frame_background
;
5902 color
.pixel
= FRAME_BACKGROUND_PIXEL (f
);
5903 x_query_color (f
, &color
);
5905 memset (&frame_background
, 0, sizeof frame_background
);
5906 frame_background
.red
= color
.red
>> shift
;
5907 frame_background
.green
= color
.green
>> shift
;
5908 frame_background
.blue
= color
.blue
>> shift
;
5909 #endif /* HAVE_X_WINDOWS */
5911 fn_png_set_background (png_ptr
, &frame_background
,
5912 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
5916 /* Update info structure. */
5917 fn_png_read_update_info (png_ptr
, info_ptr
);
5919 /* Get number of channels. Valid values are 1 for grayscale images
5920 and images with a palette, 2 for grayscale images with transparency
5921 information (alpha channel), 3 for RGB images, and 4 for RGB
5922 images with alpha channel, i.e. RGBA. If conversions above were
5923 sufficient we should only have 3 or 4 channels here. */
5924 channels
= fn_png_get_channels (png_ptr
, info_ptr
);
5925 eassert (channels
== 3 || channels
== 4);
5927 /* Number of bytes needed for one row of the image. */
5928 row_bytes
= fn_png_get_rowbytes (png_ptr
, info_ptr
);
5930 /* Allocate memory for the image. */
5931 if (min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *rows
< height
5932 || min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *pixels
/ height
< row_bytes
)
5933 memory_full (SIZE_MAX
);
5934 c
->pixels
= pixels
= xmalloc (sizeof *pixels
* row_bytes
* height
);
5935 c
->rows
= rows
= xmalloc (height
* sizeof *rows
);
5936 for (i
= 0; i
< height
; ++i
)
5937 rows
[i
] = pixels
+ i
* row_bytes
;
5939 /* Read the entire image. */
5940 fn_png_read_image (png_ptr
, rows
);
5941 fn_png_read_end (png_ptr
, info_ptr
);
5948 /* Create an image and pixmap serving as mask if the PNG image
5949 contains an alpha channel. */
5952 && !image_create_x_image_and_pixmap (f
, img
, width
, height
, 1,
5955 x_destroy_x_image (ximg
);
5956 x_clear_image_1 (f
, img
, CLEAR_IMAGE_PIXMAP
);
5960 /* Fill the X image and mask from PNG data. */
5961 init_color_table ();
5963 for (y
= 0; y
< height
; ++y
)
5965 png_byte
*p
= rows
[y
];
5967 for (x
= 0; x
< width
; ++x
)
5974 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, r
, g
, b
));
5975 /* An alpha channel, aka mask channel, associates variable
5976 transparency with an image. Where other image formats
5977 support binary transparency---fully transparent or fully
5978 opaque---PNG allows up to 254 levels of partial transparency.
5979 The PNG library implements partial transparency by combining
5980 the image with a specified background color.
5982 I'm not sure how to handle this here nicely: because the
5983 background on which the image is displayed may change, for
5984 real alpha channel support, it would be necessary to create
5985 a new image for each possible background.
5987 What I'm doing now is that a mask is created if we have
5988 boolean transparency information. Otherwise I'm using
5989 the frame's background color to combine the image with. */
5994 XPutPixel (mask_img
, x
, y
, *p
> 0 ? PIX_MASK_DRAW
: PIX_MASK_RETAIN
);
6000 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6001 /* Set IMG's background color from the PNG image, unless the user
6005 if (fn_png_get_bKGD (png_ptr
, info_ptr
, &bg
))
6007 img
->background
= lookup_rgb_color (f
, bg
->red
, bg
->green
, bg
->blue
);
6008 img
->background_valid
= 1;
6012 #ifdef COLOR_TABLE_SUPPORT
6013 /* Remember colors allocated for this image. */
6014 img
->colors
= colors_in_color_table (&img
->ncolors
);
6015 free_color_table ();
6016 #endif /* COLOR_TABLE_SUPPORT */
6019 fn_png_destroy_read_struct (&c
->png_ptr
, &c
->info_ptr
, &c
->end_info
);
6024 img
->height
= height
;
6026 /* Maybe fill in the background field while we have ximg handy.
6027 Casting avoids a GCC warning. */
6028 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6030 /* Put ximg into the image. */
6031 image_put_x_image (f
, img
, ximg
, 0);
6033 /* Same for the mask. */
6036 /* Fill in the background_transparent field while we have the
6037 mask handy. Casting avoids a GCC warning. */
6038 image_background_transparent (img
, f
, (XImagePtr_or_DC
)mask_img
);
6040 image_put_x_image (f
, img
, mask_img
, 1);
6047 png_load (struct frame
*f
, struct image
*img
)
6049 struct png_load_context c
;
6050 return png_load_body (f
, img
, &c
);
6053 #else /* HAVE_PNG */
6057 png_load (struct frame
*f
, struct image
*img
)
6059 return ns_load_image (f
, img
,
6060 image_spec_value (img
->spec
, QCfile
, NULL
),
6061 image_spec_value (img
->spec
, QCdata
, NULL
));
6063 #endif /* HAVE_NS */
6066 #endif /* !HAVE_PNG */
6070 /***********************************************************************
6072 ***********************************************************************/
6074 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6076 static bool jpeg_image_p (Lisp_Object object
);
6077 static bool jpeg_load (struct frame
*f
, struct image
*img
);
6079 /* The symbol `jpeg' identifying images of this type. */
6081 static Lisp_Object Qjpeg
;
6083 /* Indices of image specification fields in gs_format, below. */
6085 enum jpeg_keyword_index
6094 JPEG_HEURISTIC_MASK
,
6100 /* Vector of image_keyword structures describing the format
6101 of valid user-defined image specifications. */
6103 static const struct image_keyword jpeg_format
[JPEG_LAST
] =
6105 {":type", IMAGE_SYMBOL_VALUE
, 1},
6106 {":data", IMAGE_STRING_VALUE
, 0},
6107 {":file", IMAGE_STRING_VALUE
, 0},
6108 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6109 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6110 {":relief", IMAGE_INTEGER_VALUE
, 0},
6111 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6112 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6113 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6114 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
6117 #if defined HAVE_NTGUI && defined WINDOWSNT
6118 static bool init_jpeg_functions (void);
6120 #define init_jpeg_functions NULL
6123 /* Structure describing the image type `jpeg'. */
6125 static struct image_type jpeg_type
=
6131 init_jpeg_functions
,
6135 /* Return true if OBJECT is a valid JPEG image specification. */
6138 jpeg_image_p (Lisp_Object object
)
6140 struct image_keyword fmt
[JPEG_LAST
];
6142 memcpy (fmt
, jpeg_format
, sizeof fmt
);
6144 if (!parse_image_spec (object
, fmt
, JPEG_LAST
, Qjpeg
))
6147 /* Must specify either the :data or :file keyword. */
6148 return fmt
[JPEG_FILE
].count
+ fmt
[JPEG_DATA
].count
== 1;
6151 #endif /* HAVE_JPEG || HAVE_NS */
6155 /* Work around a warning about HAVE_STDLIB_H being redefined in
6157 #ifdef HAVE_STDLIB_H
6158 #undef HAVE_STDLIB_H
6159 #endif /* HAVE_STLIB_H */
6161 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6162 /* In older releases of the jpeg library, jpeglib.h will define boolean
6163 differently depending on __WIN32__, so make sure it is defined. */
6167 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6168 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6169 using the Windows boolean type instead of the jpeglib boolean type
6170 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6171 headers are included along with windows.h, so under Cygwin, jpeglib
6172 attempts to define a conflicting boolean type. Worse, forcing
6173 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6174 because it created an ABI incompatibility between the
6175 already-compiled jpeg library and the header interface definition.
6177 The best we can do is to define jpeglib's boolean type to a
6178 different name. This name, jpeg_boolean, remains in effect through
6179 the rest of image.c.
6181 #if defined CYGWIN && defined HAVE_NTGUI
6182 #define boolean jpeg_boolean
6184 #include <jpeglib.h>
6189 /* JPEG library details. */
6190 DEF_IMGLIB_FN (void, jpeg_CreateDecompress
, (j_decompress_ptr
, int, size_t));
6191 DEF_IMGLIB_FN (boolean
, jpeg_start_decompress
, (j_decompress_ptr
));
6192 DEF_IMGLIB_FN (boolean
, jpeg_finish_decompress
, (j_decompress_ptr
));
6193 DEF_IMGLIB_FN (void, jpeg_destroy_decompress
, (j_decompress_ptr
));
6194 DEF_IMGLIB_FN (int, jpeg_read_header
, (j_decompress_ptr
, boolean
));
6195 DEF_IMGLIB_FN (JDIMENSION
, jpeg_read_scanlines
, (j_decompress_ptr
, JSAMPARRAY
, JDIMENSION
));
6196 DEF_IMGLIB_FN (struct jpeg_error_mgr
*, jpeg_std_error
, (struct jpeg_error_mgr
*));
6197 DEF_IMGLIB_FN (boolean
, jpeg_resync_to_restart
, (j_decompress_ptr
, int));
6200 init_jpeg_functions (void)
6204 if (!(library
= w32_delayed_load (Qjpeg
)))
6207 LOAD_IMGLIB_FN (library
, jpeg_finish_decompress
);
6208 LOAD_IMGLIB_FN (library
, jpeg_read_scanlines
);
6209 LOAD_IMGLIB_FN (library
, jpeg_start_decompress
);
6210 LOAD_IMGLIB_FN (library
, jpeg_read_header
);
6211 LOAD_IMGLIB_FN (library
, jpeg_CreateDecompress
);
6212 LOAD_IMGLIB_FN (library
, jpeg_destroy_decompress
);
6213 LOAD_IMGLIB_FN (library
, jpeg_std_error
);
6214 LOAD_IMGLIB_FN (library
, jpeg_resync_to_restart
);
6218 /* Wrapper since we can't directly assign the function pointer
6219 to another function pointer that was declared more completely easily. */
6221 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo
, int desired
)
6223 return fn_jpeg_resync_to_restart (cinfo
, desired
);
6228 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
6229 #define fn_jpeg_start_decompress jpeg_start_decompress
6230 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6231 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6232 #define fn_jpeg_read_header jpeg_read_header
6233 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6234 #define fn_jpeg_std_error jpeg_std_error
6235 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6237 #endif /* WINDOWSNT */
6239 struct my_jpeg_error_mgr
6241 struct jpeg_error_mgr pub
;
6242 sys_jmp_buf setjmp_buffer
;
6244 /* The remaining members are so that longjmp doesn't munge local
6246 struct jpeg_decompress_struct cinfo
;
6250 MY_JPEG_INVALID_IMAGE_SIZE
,
6251 MY_JPEG_CANNOT_CREATE_X
6259 static _Noreturn
void
6260 my_error_exit (j_common_ptr cinfo
)
6262 struct my_jpeg_error_mgr
*mgr
= (struct my_jpeg_error_mgr
*) cinfo
->err
;
6263 mgr
->failure_code
= MY_JPEG_ERROR_EXIT
;
6264 sys_longjmp (mgr
->setjmp_buffer
, 1);
6268 /* Init source method for JPEG data source manager. Called by
6269 jpeg_read_header() before any data is actually read. See
6270 libjpeg.doc from the JPEG lib distribution. */
6273 our_common_init_source (j_decompress_ptr cinfo
)
6278 /* Method to terminate data source. Called by
6279 jpeg_finish_decompress() after all data has been processed. */
6282 our_common_term_source (j_decompress_ptr cinfo
)
6287 /* Fill input buffer method for JPEG data source manager. Called
6288 whenever more data is needed. We read the whole image in one step,
6289 so this only adds a fake end of input marker at the end. */
6291 static JOCTET our_memory_buffer
[2];
6294 our_memory_fill_input_buffer (j_decompress_ptr cinfo
)
6296 /* Insert a fake EOI marker. */
6297 struct jpeg_source_mgr
*src
= cinfo
->src
;
6299 our_memory_buffer
[0] = (JOCTET
) 0xFF;
6300 our_memory_buffer
[1] = (JOCTET
) JPEG_EOI
;
6302 src
->next_input_byte
= our_memory_buffer
;
6303 src
->bytes_in_buffer
= 2;
6308 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6309 is the JPEG data source manager. */
6312 our_memory_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6314 struct jpeg_source_mgr
*src
= cinfo
->src
;
6318 if (num_bytes
> src
->bytes_in_buffer
)
6319 ERREXIT (cinfo
, JERR_INPUT_EOF
);
6321 src
->bytes_in_buffer
-= num_bytes
;
6322 src
->next_input_byte
+= num_bytes
;
6327 /* Set up the JPEG lib for reading an image from DATA which contains
6328 LEN bytes. CINFO is the decompression info structure created for
6329 reading the image. */
6332 jpeg_memory_src (j_decompress_ptr cinfo
, JOCTET
*data
, ptrdiff_t len
)
6334 struct jpeg_source_mgr
*src
= cinfo
->src
;
6338 /* First time for this JPEG object? */
6339 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6340 JPOOL_PERMANENT
, sizeof *src
);
6342 src
->next_input_byte
= data
;
6345 src
->init_source
= our_common_init_source
;
6346 src
->fill_input_buffer
= our_memory_fill_input_buffer
;
6347 src
->skip_input_data
= our_memory_skip_input_data
;
6348 src
->resync_to_restart
= jpeg_resync_to_restart_wrapper
; /* Use default method. */
6349 src
->term_source
= our_common_term_source
;
6350 src
->bytes_in_buffer
= len
;
6351 src
->next_input_byte
= data
;
6355 struct jpeg_stdio_mgr
6357 struct jpeg_source_mgr mgr
;
6364 /* Size of buffer to read JPEG from file.
6365 Not too big, as we want to use alloc_small. */
6366 #define JPEG_STDIO_BUFFER_SIZE 8192
6369 /* Fill input buffer method for JPEG data source manager. Called
6370 whenever more data is needed. The data is read from a FILE *. */
6373 our_stdio_fill_input_buffer (j_decompress_ptr cinfo
)
6375 struct jpeg_stdio_mgr
*src
;
6377 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6382 bytes
= fread (src
->buffer
, 1, JPEG_STDIO_BUFFER_SIZE
, src
->file
);
6384 src
->mgr
.bytes_in_buffer
= bytes
;
6387 WARNMS (cinfo
, JWRN_JPEG_EOF
);
6389 src
->buffer
[0] = (JOCTET
) 0xFF;
6390 src
->buffer
[1] = (JOCTET
) JPEG_EOI
;
6391 src
->mgr
.bytes_in_buffer
= 2;
6393 src
->mgr
.next_input_byte
= src
->buffer
;
6400 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6401 is the JPEG data source manager. */
6404 our_stdio_skip_input_data (j_decompress_ptr cinfo
, long int num_bytes
)
6406 struct jpeg_stdio_mgr
*src
;
6407 src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6409 while (num_bytes
> 0 && !src
->finished
)
6411 if (num_bytes
<= src
->mgr
.bytes_in_buffer
)
6413 src
->mgr
.bytes_in_buffer
-= num_bytes
;
6414 src
->mgr
.next_input_byte
+= num_bytes
;
6419 num_bytes
-= src
->mgr
.bytes_in_buffer
;
6420 src
->mgr
.bytes_in_buffer
= 0;
6421 src
->mgr
.next_input_byte
= NULL
;
6423 our_stdio_fill_input_buffer (cinfo
);
6429 /* Set up the JPEG lib for reading an image from a FILE *.
6430 CINFO is the decompression info structure created for
6431 reading the image. */
6434 jpeg_file_src (j_decompress_ptr cinfo
, FILE *fp
)
6436 struct jpeg_stdio_mgr
*src
= (struct jpeg_stdio_mgr
*) cinfo
->src
;
6440 /* First time for this JPEG object? */
6441 src
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6442 JPOOL_PERMANENT
, sizeof *src
);
6443 cinfo
->src
= (struct jpeg_source_mgr
*) src
;
6444 src
->buffer
= cinfo
->mem
->alloc_small ((j_common_ptr
) cinfo
,
6446 JPEG_STDIO_BUFFER_SIZE
);
6451 src
->mgr
.init_source
= our_common_init_source
;
6452 src
->mgr
.fill_input_buffer
= our_stdio_fill_input_buffer
;
6453 src
->mgr
.skip_input_data
= our_stdio_skip_input_data
;
6454 src
->mgr
.resync_to_restart
= jpeg_resync_to_restart_wrapper
; /* Use default method. */
6455 src
->mgr
.term_source
= our_common_term_source
;
6456 src
->mgr
.bytes_in_buffer
= 0;
6457 src
->mgr
.next_input_byte
= NULL
;
6461 /* Load image IMG for use on frame F. Patterned after example.c
6462 from the JPEG lib. */
6465 jpeg_load_body (struct frame
*f
, struct image
*img
,
6466 struct my_jpeg_error_mgr
*mgr
)
6468 Lisp_Object file
, specified_file
;
6469 Lisp_Object specified_data
;
6472 int row_stride
, x
, y
;
6473 XImagePtr ximg
= NULL
;
6474 unsigned long *colors
;
6477 /* Open the JPEG file. */
6478 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6479 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6481 if (NILP (specified_data
))
6483 file
= x_find_image_file (specified_file
);
6484 if (!STRINGP (file
))
6486 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
6490 fp
= emacs_fopen (SSDATA (file
), "rb");
6493 image_error ("Cannot open `%s'", file
, Qnil
);
6497 else if (!STRINGP (specified_data
))
6499 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
6503 IF_LINT (mgr
->fp
= fp
);
6505 /* Customize libjpeg's error handling to call my_error_exit when an
6506 error is detected. This function will perform a longjmp. */
6507 mgr
->cinfo
.err
= fn_jpeg_std_error (&mgr
->pub
);
6508 mgr
->pub
.error_exit
= my_error_exit
;
6509 if (sys_setjmp (mgr
->setjmp_buffer
))
6511 switch (mgr
->failure_code
)
6513 case MY_JPEG_ERROR_EXIT
:
6515 char buf
[JMSG_LENGTH_MAX
];
6516 mgr
->cinfo
.err
->format_message ((j_common_ptr
) &mgr
->cinfo
, buf
);
6517 image_error ("Error reading JPEG image `%s': %s", img
->spec
,
6518 build_string (buf
));
6522 case MY_JPEG_INVALID_IMAGE_SIZE
:
6523 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
6526 case MY_JPEG_CANNOT_CREATE_X
:
6530 /* Close the input file and destroy the JPEG object. */
6533 fn_jpeg_destroy_decompress (&mgr
->cinfo
);
6535 /* If we already have an XImage, free that. */
6536 x_destroy_x_image (ximg
);
6538 /* Free pixmap and colors. */
6539 x_clear_image (f
, img
);
6543 /* Silence a bogus diagnostic; see GCC bug 54561. */
6544 IF_LINT (fp
= mgr
->fp
);
6546 /* Create the JPEG decompression object. Let it read from fp.
6547 Read the JPEG image header. */
6548 fn_jpeg_CreateDecompress (&mgr
->cinfo
, JPEG_LIB_VERSION
, sizeof *&mgr
->cinfo
);
6550 if (NILP (specified_data
))
6551 jpeg_file_src (&mgr
->cinfo
, fp
);
6553 jpeg_memory_src (&mgr
->cinfo
, SDATA (specified_data
),
6554 SBYTES (specified_data
));
6556 fn_jpeg_read_header (&mgr
->cinfo
, 1);
6558 /* Customize decompression so that color quantization will be used.
6559 Start decompression. */
6560 mgr
->cinfo
.quantize_colors
= 1;
6561 fn_jpeg_start_decompress (&mgr
->cinfo
);
6562 width
= img
->width
= mgr
->cinfo
.output_width
;
6563 height
= img
->height
= mgr
->cinfo
.output_height
;
6565 if (!check_image_size (f
, width
, height
))
6567 mgr
->failure_code
= MY_JPEG_INVALID_IMAGE_SIZE
;
6568 sys_longjmp (mgr
->setjmp_buffer
, 1);
6571 /* Create X image and pixmap. */
6572 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
6574 mgr
->failure_code
= MY_JPEG_CANNOT_CREATE_X
;
6575 sys_longjmp (mgr
->setjmp_buffer
, 1);
6578 /* Allocate colors. When color quantization is used,
6579 mgr->cinfo.actual_number_of_colors has been set with the number of
6580 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6581 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6582 No more than 255 colors will be generated. */
6586 if (mgr
->cinfo
.out_color_components
> 2)
6587 ir
= 0, ig
= 1, ib
= 2;
6588 else if (mgr
->cinfo
.out_color_components
> 1)
6589 ir
= 0, ig
= 1, ib
= 0;
6591 ir
= 0, ig
= 0, ib
= 0;
6593 /* Use the color table mechanism because it handles colors that
6594 cannot be allocated nicely. Such colors will be replaced with
6595 a default color, and we don't have to care about which colors
6596 can be freed safely, and which can't. */
6597 init_color_table ();
6598 colors
= alloca (mgr
->cinfo
.actual_number_of_colors
* sizeof *colors
);
6600 for (i
= 0; i
< mgr
->cinfo
.actual_number_of_colors
; ++i
)
6602 /* Multiply RGB values with 255 because X expects RGB values
6603 in the range 0..0xffff. */
6604 int r
= mgr
->cinfo
.colormap
[ir
][i
] << 8;
6605 int g
= mgr
->cinfo
.colormap
[ig
][i
] << 8;
6606 int b
= mgr
->cinfo
.colormap
[ib
][i
] << 8;
6607 colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
6610 #ifdef COLOR_TABLE_SUPPORT
6611 /* Remember those colors actually allocated. */
6612 img
->colors
= colors_in_color_table (&img
->ncolors
);
6613 free_color_table ();
6614 #endif /* COLOR_TABLE_SUPPORT */
6618 row_stride
= width
* mgr
->cinfo
.output_components
;
6619 buffer
= mgr
->cinfo
.mem
->alloc_sarray ((j_common_ptr
) &mgr
->cinfo
,
6620 JPOOL_IMAGE
, row_stride
, 1);
6621 for (y
= 0; y
< height
; ++y
)
6623 fn_jpeg_read_scanlines (&mgr
->cinfo
, buffer
, 1);
6624 for (x
= 0; x
< mgr
->cinfo
.output_width
; ++x
)
6625 XPutPixel (ximg
, x
, y
, colors
[buffer
[0][x
]]);
6629 fn_jpeg_finish_decompress (&mgr
->cinfo
);
6630 fn_jpeg_destroy_decompress (&mgr
->cinfo
);
6634 /* Maybe fill in the background field while we have ximg handy. */
6635 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
6636 /* Casting avoids a GCC warning. */
6637 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
6639 /* Put ximg into the image. */
6640 image_put_x_image (f
, img
, ximg
, 0);
6645 jpeg_load (struct frame
*f
, struct image
*img
)
6647 struct my_jpeg_error_mgr mgr
;
6648 return jpeg_load_body (f
, img
, &mgr
);
6651 #else /* HAVE_JPEG */
6655 jpeg_load (struct frame
*f
, struct image
*img
)
6657 return ns_load_image (f
, img
,
6658 image_spec_value (img
->spec
, QCfile
, NULL
),
6659 image_spec_value (img
->spec
, QCdata
, NULL
));
6661 #endif /* HAVE_NS */
6663 #endif /* !HAVE_JPEG */
6667 /***********************************************************************
6669 ***********************************************************************/
6671 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6673 static bool tiff_image_p (Lisp_Object object
);
6674 static bool tiff_load (struct frame
*f
, struct image
*img
);
6676 /* The symbol `tiff' identifying images of this type. */
6678 static Lisp_Object Qtiff
;
6680 /* Indices of image specification fields in tiff_format, below. */
6682 enum tiff_keyword_index
6691 TIFF_HEURISTIC_MASK
,
6698 /* Vector of image_keyword structures describing the format
6699 of valid user-defined image specifications. */
6701 static const struct image_keyword tiff_format
[TIFF_LAST
] =
6703 {":type", IMAGE_SYMBOL_VALUE
, 1},
6704 {":data", IMAGE_STRING_VALUE
, 0},
6705 {":file", IMAGE_STRING_VALUE
, 0},
6706 {":ascent", IMAGE_ASCENT_VALUE
, 0},
6707 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
6708 {":relief", IMAGE_INTEGER_VALUE
, 0},
6709 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6710 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6711 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
6712 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
6713 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0}
6716 #if defined HAVE_NTGUI && defined WINDOWSNT
6717 static bool init_tiff_functions (void);
6719 #define init_tiff_functions NULL
6722 /* Structure describing the image type `tiff'. */
6724 static struct image_type tiff_type
=
6730 init_tiff_functions
,
6734 /* Return true if OBJECT is a valid TIFF image specification. */
6737 tiff_image_p (Lisp_Object object
)
6739 struct image_keyword fmt
[TIFF_LAST
];
6740 memcpy (fmt
, tiff_format
, sizeof fmt
);
6742 if (!parse_image_spec (object
, fmt
, TIFF_LAST
, Qtiff
))
6745 /* Must specify either the :data or :file keyword. */
6746 return fmt
[TIFF_FILE
].count
+ fmt
[TIFF_DATA
].count
== 1;
6749 #endif /* HAVE_TIFF || HAVE_NS */
6757 /* TIFF library details. */
6758 DEF_IMGLIB_FN (TIFFErrorHandler
, TIFFSetErrorHandler
, (TIFFErrorHandler
));
6759 DEF_IMGLIB_FN (TIFFErrorHandler
, TIFFSetWarningHandler
, (TIFFErrorHandler
));
6760 DEF_IMGLIB_FN (TIFF
*, TIFFOpen
, (const char *, const char *));
6761 DEF_IMGLIB_FN (TIFF
*, TIFFClientOpen
, (const char *, const char *, thandle_t
,
6762 TIFFReadWriteProc
, TIFFReadWriteProc
,
6763 TIFFSeekProc
, TIFFCloseProc
, TIFFSizeProc
,
6764 TIFFMapFileProc
, TIFFUnmapFileProc
));
6765 DEF_IMGLIB_FN (int, TIFFGetField
, (TIFF
*, ttag_t
, ...));
6766 DEF_IMGLIB_FN (int, TIFFReadRGBAImage
, (TIFF
*, uint32
, uint32
, uint32
*, int));
6767 DEF_IMGLIB_FN (void, TIFFClose
, (TIFF
*));
6768 DEF_IMGLIB_FN (int, TIFFSetDirectory
, (TIFF
*, tdir_t
));
6771 init_tiff_functions (void)
6775 if (!(library
= w32_delayed_load (Qtiff
)))
6778 LOAD_IMGLIB_FN (library
, TIFFSetErrorHandler
);
6779 LOAD_IMGLIB_FN (library
, TIFFSetWarningHandler
);
6780 LOAD_IMGLIB_FN (library
, TIFFOpen
);
6781 LOAD_IMGLIB_FN (library
, TIFFClientOpen
);
6782 LOAD_IMGLIB_FN (library
, TIFFGetField
);
6783 LOAD_IMGLIB_FN (library
, TIFFReadRGBAImage
);
6784 LOAD_IMGLIB_FN (library
, TIFFClose
);
6785 LOAD_IMGLIB_FN (library
, TIFFSetDirectory
);
6791 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6792 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6793 #define fn_TIFFOpen TIFFOpen
6794 #define fn_TIFFClientOpen TIFFClientOpen
6795 #define fn_TIFFGetField TIFFGetField
6796 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6797 #define fn_TIFFClose TIFFClose
6798 #define fn_TIFFSetDirectory TIFFSetDirectory
6799 #endif /* WINDOWSNT */
6802 /* Reading from a memory buffer for TIFF images Based on the PNG
6803 memory source, but we have to provide a lot of extra functions.
6806 We really only need to implement read and seek, but I am not
6807 convinced that the TIFF library is smart enough not to destroy
6808 itself if we only hand it the function pointers we need to
6813 unsigned char *bytes
;
6820 tiff_read_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
6822 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
6824 size
= min (size
, src
->len
- src
->index
);
6825 memcpy (buf
, src
->bytes
+ src
->index
, size
);
6831 tiff_write_from_memory (thandle_t data
, tdata_t buf
, tsize_t size
)
6837 tiff_seek_in_memory (thandle_t data
, toff_t off
, int whence
)
6839 tiff_memory_source
*src
= (tiff_memory_source
*) data
;
6844 case SEEK_SET
: /* Go from beginning of source. */
6848 case SEEK_END
: /* Go from end of source. */
6849 idx
= src
->len
+ off
;
6852 case SEEK_CUR
: /* Go from current position. */
6853 idx
= src
->index
+ off
;
6856 default: /* Invalid `whence'. */
6860 if (idx
> src
->len
|| idx
< 0)
6868 tiff_close_memory (thandle_t data
)
6875 tiff_mmap_memory (thandle_t data
, tdata_t
*pbase
, toff_t
*psize
)
6877 /* It is already _IN_ memory. */
6882 tiff_unmap_memory (thandle_t data
, tdata_t base
, toff_t size
)
6884 /* We don't need to do this. */
6888 tiff_size_of_memory (thandle_t data
)
6890 return ((tiff_memory_source
*) data
)->len
;
6893 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6894 compiler error compiling tiff_handler, see Bugzilla bug #17406
6895 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6896 this function as external works around that problem. */
6897 #if defined (__MINGW32__) && __GNUC__ == 3
6898 # define MINGW_STATIC
6900 # define MINGW_STATIC static
6904 tiff_handler (const char *, const char *, const char *, va_list)
6905 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6907 tiff_handler (const char *log_format
, const char *title
,
6908 const char *format
, va_list ap
)
6910 /* doprnt is not suitable here, as TIFF handlers are called from
6911 libtiff and are passed arbitrary printf directives. Instead, use
6912 vsnprintf, taking care to be portable to nonstandard environments
6913 where vsnprintf returns -1 on buffer overflow. Since it's just a
6914 log entry, it's OK to truncate it. */
6916 int len
= vsnprintf (buf
, sizeof buf
, format
, ap
);
6917 add_to_log (log_format
, build_string (title
),
6918 make_string (buf
, max (0, min (len
, sizeof buf
- 1))));
6922 static void tiff_error_handler (const char *, const char *, va_list)
6923 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6925 tiff_error_handler (const char *title
, const char *format
, va_list ap
)
6927 tiff_handler ("TIFF error: %s %s", title
, format
, ap
);
6931 static void tiff_warning_handler (const char *, const char *, va_list)
6932 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6934 tiff_warning_handler (const char *title
, const char *format
, va_list ap
)
6936 tiff_handler ("TIFF warning: %s %s", title
, format
, ap
);
6940 /* Load TIFF image IMG for use on frame F. Value is true if
6944 tiff_load (struct frame
*f
, struct image
*img
)
6946 Lisp_Object file
, specified_file
;
6947 Lisp_Object specified_data
;
6949 int width
, height
, x
, y
, count
;
6953 tiff_memory_source memsrc
;
6956 specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
6957 specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
6959 fn_TIFFSetErrorHandler ((TIFFErrorHandler
) tiff_error_handler
);
6960 fn_TIFFSetWarningHandler ((TIFFErrorHandler
) tiff_warning_handler
);
6962 if (NILP (specified_data
))
6964 /* Read from a file */
6965 file
= x_find_image_file (specified_file
);
6966 if (!STRINGP (file
))
6968 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
6972 /* Try to open the image file. */
6973 tiff
= fn_TIFFOpen (SSDATA (file
), "r");
6976 image_error ("Cannot open `%s'", file
, Qnil
);
6982 if (!STRINGP (specified_data
))
6984 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
6988 /* Memory source! */
6989 memsrc
.bytes
= SDATA (specified_data
);
6990 memsrc
.len
= SBYTES (specified_data
);
6993 tiff
= fn_TIFFClientOpen ("memory_source", "r", (thandle_t
)&memsrc
,
6994 tiff_read_from_memory
,
6995 tiff_write_from_memory
,
6996 tiff_seek_in_memory
,
6998 tiff_size_of_memory
,
7004 image_error ("Cannot open memory source for `%s'", img
->spec
, Qnil
);
7009 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
7010 if (INTEGERP (image
))
7012 EMACS_INT ino
= XFASTINT (image
);
7013 if (! (TYPE_MINIMUM (tdir_t
) <= ino
&& ino
<= TYPE_MAXIMUM (tdir_t
)
7014 && fn_TIFFSetDirectory (tiff
, ino
)))
7016 image_error ("Invalid image number `%s' in image `%s'",
7018 fn_TIFFClose (tiff
);
7023 /* Get width and height of the image, and allocate a raster buffer
7024 of width x height 32-bit values. */
7025 fn_TIFFGetField (tiff
, TIFFTAG_IMAGEWIDTH
, &width
);
7026 fn_TIFFGetField (tiff
, TIFFTAG_IMAGELENGTH
, &height
);
7028 if (!check_image_size (f
, width
, height
))
7030 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
7031 fn_TIFFClose (tiff
);
7035 /* Create the X image and pixmap. */
7036 if (! (height
<= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *buf
/ width
7037 && image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
7040 fn_TIFFClose (tiff
);
7044 buf
= xmalloc (sizeof *buf
* width
* height
);
7046 rc
= fn_TIFFReadRGBAImage (tiff
, width
, height
, buf
, 0);
7048 /* Count the number of images in the file. */
7049 for (count
= 1; fn_TIFFSetDirectory (tiff
, count
); count
++)
7053 img
->lisp_data
= Fcons (Qcount
,
7054 Fcons (make_number (count
),
7057 fn_TIFFClose (tiff
);
7060 image_error ("Error reading TIFF image `%s'", img
->spec
, Qnil
);
7065 /* Initialize the color table. */
7066 init_color_table ();
7068 /* Process the pixel raster. Origin is in the lower-left corner. */
7069 for (y
= 0; y
< height
; ++y
)
7071 uint32
*row
= buf
+ y
* width
;
7073 for (x
= 0; x
< width
; ++x
)
7075 uint32 abgr
= row
[x
];
7076 int r
= TIFFGetR (abgr
) << 8;
7077 int g
= TIFFGetG (abgr
) << 8;
7078 int b
= TIFFGetB (abgr
) << 8;
7079 XPutPixel (ximg
, x
, height
- 1 - y
, lookup_rgb_color (f
, r
, g
, b
));
7083 #ifdef COLOR_TABLE_SUPPORT
7084 /* Remember the colors allocated for the image. Free the color table. */
7085 img
->colors
= colors_in_color_table (&img
->ncolors
);
7086 free_color_table ();
7087 #endif /* COLOR_TABLE_SUPPORT */
7090 img
->height
= height
;
7092 /* Maybe fill in the background field while we have ximg handy. */
7093 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7094 /* Casting avoids a GCC warning on W32. */
7095 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7097 /* Put ximg into the image. */
7098 image_put_x_image (f
, img
, ximg
, 0);
7104 #else /* HAVE_TIFF */
7108 tiff_load (struct frame
*f
, struct image
*img
)
7110 return ns_load_image (f
, img
,
7111 image_spec_value (img
->spec
, QCfile
, NULL
),
7112 image_spec_value (img
->spec
, QCdata
, NULL
));
7114 #endif /* HAVE_NS */
7116 #endif /* !HAVE_TIFF */
7120 /***********************************************************************
7122 ***********************************************************************/
7124 #if defined (HAVE_GIF) || defined (HAVE_NS)
7126 static bool gif_image_p (Lisp_Object object
);
7127 static bool gif_load (struct frame
*f
, struct image
*img
);
7128 static void gif_clear_image (struct frame
*f
, struct image
*img
);
7130 /* The symbol `gif' identifying images of this type. */
7132 static Lisp_Object Qgif
;
7134 /* Indices of image specification fields in gif_format, below. */
7136 enum gif_keyword_index
7152 /* Vector of image_keyword structures describing the format
7153 of valid user-defined image specifications. */
7155 static const struct image_keyword gif_format
[GIF_LAST
] =
7157 {":type", IMAGE_SYMBOL_VALUE
, 1},
7158 {":data", IMAGE_STRING_VALUE
, 0},
7159 {":file", IMAGE_STRING_VALUE
, 0},
7160 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7161 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7162 {":relief", IMAGE_INTEGER_VALUE
, 0},
7163 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7164 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7165 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7166 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE
, 0},
7167 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
7170 #if defined HAVE_NTGUI && defined WINDOWSNT
7171 static bool init_gif_functions (void);
7173 #define init_gif_functions NULL
7176 /* Structure describing the image type `gif'. */
7178 static struct image_type gif_type
=
7188 /* Free X resources of GIF image IMG which is used on frame F. */
7191 gif_clear_image (struct frame
*f
, struct image
*img
)
7193 img
->lisp_data
= Qnil
;
7194 x_clear_image (f
, img
);
7197 /* Return true if OBJECT is a valid GIF image specification. */
7200 gif_image_p (Lisp_Object object
)
7202 struct image_keyword fmt
[GIF_LAST
];
7203 memcpy (fmt
, gif_format
, sizeof fmt
);
7205 if (!parse_image_spec (object
, fmt
, GIF_LAST
, Qgif
))
7208 /* Must specify either the :data or :file keyword. */
7209 return fmt
[GIF_FILE
].count
+ fmt
[GIF_DATA
].count
== 1;
7212 #endif /* HAVE_GIF */
7216 #if defined (HAVE_NTGUI)
7218 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7219 Undefine before redefining to avoid a preprocessor warning. */
7223 /* avoid conflict with QuickdrawText.h */
7224 #define DrawText gif_DrawText
7225 #include <gif_lib.h>
7228 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7229 #ifndef GIFLIB_MINOR
7230 #define GIFLIB_MINOR 0
7232 #ifndef GIFLIB_RELEASE
7233 #define GIFLIB_RELEASE 0
7236 #else /* HAVE_NTGUI */
7238 #include <gif_lib.h>
7240 #endif /* HAVE_NTGUI */
7242 /* Giflib before 5.0 didn't define these macros. */
7243 #ifndef GIFLIB_MAJOR
7244 #define GIFLIB_MAJOR 4
7249 /* GIF library details. */
7250 DEF_IMGLIB_FN (int, DGifCloseFile
, (GifFileType
*));
7251 DEF_IMGLIB_FN (int, DGifSlurp
, (GifFileType
*));
7252 #if GIFLIB_MAJOR < 5
7253 DEF_IMGLIB_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
));
7254 DEF_IMGLIB_FN (GifFileType
*, DGifOpenFileName
, (const char *));
7256 DEF_IMGLIB_FN (GifFileType
*, DGifOpen
, (void *, InputFunc
, int *));
7257 DEF_IMGLIB_FN (GifFileType
*, DGifOpenFileName
, (const char *, int *));
7258 DEF_IMGLIB_FN (char *, GifErrorString
, (int));
7262 init_gif_functions (void)
7266 if (!(library
= w32_delayed_load (Qgif
)))
7269 LOAD_IMGLIB_FN (library
, DGifCloseFile
);
7270 LOAD_IMGLIB_FN (library
, DGifSlurp
);
7271 LOAD_IMGLIB_FN (library
, DGifOpen
);
7272 LOAD_IMGLIB_FN (library
, DGifOpenFileName
);
7273 #if GIFLIB_MAJOR >= 5
7274 LOAD_IMGLIB_FN (library
, GifErrorString
);
7281 #define fn_DGifCloseFile DGifCloseFile
7282 #define fn_DGifSlurp DGifSlurp
7283 #define fn_DGifOpen DGifOpen
7284 #define fn_DGifOpenFileName DGifOpenFileName
7285 #if 5 <= GIFLIB_MAJOR
7286 # define fn_GifErrorString GifErrorString
7289 #endif /* WINDOWSNT */
7291 /* Reading a GIF image from memory
7292 Based on the PNG memory stuff to a certain extent. */
7296 unsigned char *bytes
;
7302 /* Make the current memory source available to gif_read_from_memory.
7303 It's done this way because not all versions of libungif support
7304 a UserData field in the GifFileType structure. */
7305 static gif_memory_source
*current_gif_memory_src
;
7308 gif_read_from_memory (GifFileType
*file
, GifByteType
*buf
, int len
)
7310 gif_memory_source
*src
= current_gif_memory_src
;
7312 if (len
> src
->len
- src
->index
)
7315 memcpy (buf
, src
->bytes
+ src
->index
, len
);
7321 /* Load GIF image IMG for use on frame F. Value is true if
7324 static const int interlace_start
[] = {0, 4, 2, 1};
7325 static const int interlace_increment
[] = {8, 8, 4, 2};
7327 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7330 gif_load (struct frame
*f
, struct image
*img
)
7333 int rc
, width
, height
, x
, y
, i
, j
;
7335 ColorMapObject
*gif_color_map
;
7336 unsigned long pixel_colors
[256];
7338 gif_memory_source memsrc
;
7339 Lisp_Object specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
7340 Lisp_Object specified_file
= image_spec_value (img
->spec
, QCfile
, NULL
);
7341 Lisp_Object specified_data
= image_spec_value (img
->spec
, QCdata
, NULL
);
7342 unsigned long bgcolor
= 0;
7344 #if GIFLIB_MAJOR >= 5
7348 if (NILP (specified_data
))
7350 file
= x_find_image_file (specified_file
);
7351 if (!STRINGP (file
))
7353 image_error ("Cannot find image file `%s'", specified_file
, Qnil
);
7357 /* Open the GIF file. */
7358 #if GIFLIB_MAJOR < 5
7359 gif
= fn_DGifOpenFileName (SSDATA (file
));
7362 image_error ("Cannot open `%s'", file
, Qnil
);
7366 gif
= fn_DGifOpenFileName (SSDATA (file
), &gif_err
);
7369 image_error ("Cannot open `%s': %s",
7370 file
, build_string (fn_GifErrorString (gif_err
)));
7377 if (!STRINGP (specified_data
))
7379 image_error ("Invalid image data `%s'", specified_data
, Qnil
);
7383 /* Read from memory! */
7384 current_gif_memory_src
= &memsrc
;
7385 memsrc
.bytes
= SDATA (specified_data
);
7386 memsrc
.len
= SBYTES (specified_data
);
7389 #if GIFLIB_MAJOR < 5
7390 gif
= fn_DGifOpen (&memsrc
, gif_read_from_memory
);
7393 image_error ("Cannot open memory source `%s'", img
->spec
, Qnil
);
7397 gif
= fn_DGifOpen (&memsrc
, gif_read_from_memory
, &gif_err
);
7400 image_error ("Cannot open memory source `%s': %s",
7401 img
->spec
, build_string (fn_GifErrorString (gif_err
)));
7407 /* Before reading entire contents, check the declared image size. */
7408 if (!check_image_size (f
, gif
->SWidth
, gif
->SHeight
))
7410 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
7411 fn_DGifCloseFile (gif
);
7415 /* Read entire contents. */
7416 rc
= fn_DGifSlurp (gif
);
7417 if (rc
== GIF_ERROR
|| gif
->ImageCount
<= 0)
7419 image_error ("Error reading `%s'", img
->spec
, Qnil
);
7420 fn_DGifCloseFile (gif
);
7424 /* Which sub-image are we to display? */
7426 Lisp_Object image_number
= image_spec_value (img
->spec
, QCindex
, NULL
);
7427 idx
= INTEGERP (image_number
) ? XFASTINT (image_number
) : 0;
7428 if (idx
< 0 || idx
>= gif
->ImageCount
)
7430 image_error ("Invalid image number `%s' in image `%s'",
7431 image_number
, img
->spec
);
7432 fn_DGifCloseFile (gif
);
7437 width
= img
->width
= gif
->SWidth
;
7438 height
= img
->height
= gif
->SHeight
;
7440 img
->corners
[TOP_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Top
;
7441 img
->corners
[LEFT_CORNER
] = gif
->SavedImages
[0].ImageDesc
.Left
;
7442 img
->corners
[BOT_CORNER
]
7443 = img
->corners
[TOP_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Height
;
7444 img
->corners
[RIGHT_CORNER
]
7445 = img
->corners
[LEFT_CORNER
] + gif
->SavedImages
[0].ImageDesc
.Width
;
7447 if (!check_image_size (f
, width
, height
))
7449 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
7450 fn_DGifCloseFile (gif
);
7454 /* Check that the selected subimages fit. It's not clear whether
7455 the GIF spec requires this, but Emacs can crash if they don't fit. */
7456 for (j
= 0; j
<= idx
; ++j
)
7458 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7459 int subimg_width
= subimage
->ImageDesc
.Width
;
7460 int subimg_height
= subimage
->ImageDesc
.Height
;
7461 int subimg_top
= subimage
->ImageDesc
.Top
;
7462 int subimg_left
= subimage
->ImageDesc
.Left
;
7463 if (! (0 <= subimg_width
&& 0 <= subimg_height
7464 && 0 <= subimg_top
&& subimg_top
<= height
- subimg_height
7465 && 0 <= subimg_left
&& subimg_left
<= width
- subimg_width
))
7467 image_error ("Subimage does not fit in image", Qnil
, Qnil
);
7468 fn_DGifCloseFile (gif
);
7473 /* Create the X image and pixmap. */
7474 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
7476 fn_DGifCloseFile (gif
);
7480 /* Clear the part of the screen image not covered by the image.
7481 Full animated GIF support requires more here (see the gif89 spec,
7482 disposal methods). Let's simply assume that the part not covered
7483 by a sub-image is in the frame's background color. */
7484 for (y
= 0; y
< img
->corners
[TOP_CORNER
]; ++y
)
7485 for (x
= 0; x
< width
; ++x
)
7486 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7488 for (y
= img
->corners
[BOT_CORNER
]; y
< height
; ++y
)
7489 for (x
= 0; x
< width
; ++x
)
7490 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7492 for (y
= img
->corners
[TOP_CORNER
]; y
< img
->corners
[BOT_CORNER
]; ++y
)
7494 for (x
= 0; x
< img
->corners
[LEFT_CORNER
]; ++x
)
7495 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7496 for (x
= img
->corners
[RIGHT_CORNER
]; x
< width
; ++x
)
7497 XPutPixel (ximg
, x
, y
, FRAME_BACKGROUND_PIXEL (f
));
7500 /* Read the GIF image into the X image. */
7502 /* FIXME: With the current implementation, loading an animated gif
7503 is quadratic in the number of animation frames, since each frame
7504 is a separate struct image. We must provide a way for a single
7505 gif_load call to construct and save all animation frames. */
7507 init_color_table ();
7508 if (STRINGP (specified_bg
))
7509 bgcolor
= x_alloc_image_color (f
, img
, specified_bg
,
7510 FRAME_BACKGROUND_PIXEL (f
));
7511 for (j
= 0; j
<= idx
; ++j
)
7513 /* We use a local variable `raster' here because RasterBits is a
7514 char *, which invites problems with bytes >= 0x80. */
7515 struct SavedImage
*subimage
= gif
->SavedImages
+ j
;
7516 unsigned char *raster
= (unsigned char *) subimage
->RasterBits
;
7517 int transparency_color_index
= -1;
7519 int subimg_width
= subimage
->ImageDesc
.Width
;
7520 int subimg_height
= subimage
->ImageDesc
.Height
;
7521 int subimg_top
= subimage
->ImageDesc
.Top
;
7522 int subimg_left
= subimage
->ImageDesc
.Left
;
7524 /* Find the Graphic Control Extension block for this sub-image.
7525 Extract the disposal method and transparency color. */
7526 for (i
= 0; i
< subimage
->ExtensionBlockCount
; i
++)
7528 ExtensionBlock
*extblock
= subimage
->ExtensionBlocks
+ i
;
7530 if ((extblock
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
)
7531 && extblock
->ByteCount
== 4
7532 && extblock
->Bytes
[0] & 1)
7534 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7535 to background". Treat any other value like 2. */
7536 disposal
= (extblock
->Bytes
[0] >> 2) & 7;
7537 transparency_color_index
= (unsigned char) extblock
->Bytes
[3];
7542 /* We can't "keep in place" the first subimage. */
7546 /* For disposal == 0, the spec says "No disposal specified. The
7547 decoder is not required to take any action." In practice, it
7548 seems we need to treat this like "keep in place", see e.g.
7549 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7553 /* Allocate subimage colors. */
7554 memset (pixel_colors
, 0, sizeof pixel_colors
);
7555 gif_color_map
= subimage
->ImageDesc
.ColorMap
;
7557 gif_color_map
= gif
->SColorMap
;
7560 for (i
= 0; i
< gif_color_map
->ColorCount
; ++i
)
7562 if (transparency_color_index
== i
)
7563 pixel_colors
[i
] = STRINGP (specified_bg
)
7564 ? bgcolor
: FRAME_BACKGROUND_PIXEL (f
);
7567 int r
= gif_color_map
->Colors
[i
].Red
<< 8;
7568 int g
= gif_color_map
->Colors
[i
].Green
<< 8;
7569 int b
= gif_color_map
->Colors
[i
].Blue
<< 8;
7570 pixel_colors
[i
] = lookup_rgb_color (f
, r
, g
, b
);
7574 /* Apply the pixel values. */
7575 if (gif
->SavedImages
[j
].ImageDesc
.Interlace
)
7579 for (y
= 0, row
= interlace_start
[0], pass
= 0;
7581 y
++, row
+= interlace_increment
[pass
])
7583 while (subimg_height
<= row
)
7584 row
= interlace_start
[++pass
];
7586 for (x
= 0; x
< subimg_width
; x
++)
7588 int c
= raster
[y
* subimg_width
+ x
];
7589 if (transparency_color_index
!= c
|| disposal
!= 1)
7590 XPutPixel (ximg
, x
+ subimg_left
, row
+ subimg_top
,
7597 for (y
= 0; y
< subimg_height
; ++y
)
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
, y
+ subimg_top
,
7608 #ifdef COLOR_TABLE_SUPPORT
7609 img
->colors
= colors_in_color_table (&img
->ncolors
);
7610 free_color_table ();
7611 #endif /* COLOR_TABLE_SUPPORT */
7613 /* Save GIF image extension data for `image-metadata'.
7614 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7615 img
->lisp_data
= Qnil
;
7616 if (gif
->SavedImages
[idx
].ExtensionBlockCount
> 0)
7619 ExtensionBlock
*ext
= gif
->SavedImages
[idx
].ExtensionBlocks
;
7620 for (i
= 0; i
< gif
->SavedImages
[idx
].ExtensionBlockCount
; i
++, ext
++)
7621 /* Append (... FUNCTION "BYTES") */
7624 = Fcons (make_number (ext
->Function
),
7625 Fcons (make_unibyte_string (ext
->Bytes
, ext
->ByteCount
),
7627 if (ext
->Function
== GIF_LOCAL_DESCRIPTOR_EXTENSION
7628 && ext
->ByteCount
== 4)
7630 delay
= ext
->Bytes
[2] << CHAR_BIT
;
7631 delay
|= ext
->Bytes
[1];
7634 img
->lisp_data
= list2 (Qextension_data
, img
->lisp_data
);
7638 Fcons (make_float (delay
/ 100.0),
7642 if (gif
->ImageCount
> 1)
7643 img
->lisp_data
= Fcons (Qcount
,
7644 Fcons (make_number (gif
->ImageCount
),
7647 fn_DGifCloseFile (gif
);
7649 /* Maybe fill in the background field while we have ximg handy. */
7650 if (NILP (image_spec_value (img
->spec
, QCbackground
, NULL
)))
7651 /* Casting avoids a GCC warning. */
7652 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
7654 /* Put ximg into the image. */
7655 image_put_x_image (f
, img
, ximg
, 0);
7660 #else /* !HAVE_GIF */
7664 gif_load (struct frame
*f
, struct image
*img
)
7666 return ns_load_image (f
, img
,
7667 image_spec_value (img
->spec
, QCfile
, NULL
),
7668 image_spec_value (img
->spec
, QCdata
, NULL
));
7670 #endif /* HAVE_NS */
7672 #endif /* HAVE_GIF */
7675 #ifdef HAVE_IMAGEMAGICK
7677 /***********************************************************************
7679 ***********************************************************************/
7681 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
7682 safely rounded and clipped to int range. */
7685 scale_image_size (int size
, size_t divisor
, size_t multiplier
)
7690 double scaled
= s
* multiplier
/ divisor
+ 0.5;
7691 if (scaled
< INT_MAX
)
7697 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
7698 Use SPEC to deduce the size. Store the desired size into
7699 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
7701 compute_image_size (size_t width
, size_t height
,
7703 int *d_width
, int *d_height
)
7706 int desired_width
, desired_height
;
7708 /* If width and/or height is set in the display spec assume we want
7709 to scale to those values. If either h or w is unspecified, the
7710 unspecified should be calculated from the specified to preserve
7712 value
= image_spec_value (spec
, QCwidth
, NULL
);
7713 desired_width
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
7714 value
= image_spec_value (spec
, QCheight
, NULL
);
7715 desired_height
= NATNUMP (value
) ? min (XFASTINT (value
), INT_MAX
) : -1;
7717 if (desired_width
== -1)
7719 value
= image_spec_value (spec
, QCmax_width
, NULL
);
7720 if (NATNUMP (value
))
7722 int max_width
= min (XFASTINT (value
), INT_MAX
);
7723 if (max_width
< width
)
7725 /* The image is wider than :max-width. */
7726 desired_width
= max_width
;
7727 if (desired_height
== -1)
7729 desired_height
= scale_image_size (desired_width
,
7731 value
= image_spec_value (spec
, QCmax_height
, NULL
);
7732 if (NATNUMP (value
))
7734 int max_height
= min (XFASTINT (value
), INT_MAX
);
7735 if (max_height
< desired_height
)
7737 desired_height
= max_height
;
7738 desired_width
= scale_image_size (desired_height
,
7747 if (desired_height
== -1)
7749 value
= image_spec_value (spec
, QCmax_height
, NULL
);
7750 if (NATNUMP (value
))
7752 int max_height
= min (XFASTINT (value
), INT_MAX
);
7753 if (max_height
< height
)
7754 desired_height
= max_height
;
7758 if (desired_width
!= -1 && desired_height
== -1)
7759 /* w known, calculate h. */
7760 desired_height
= scale_image_size (desired_width
, width
, height
);
7762 if (desired_width
== -1 && desired_height
!= -1)
7763 /* h known, calculate w. */
7764 desired_width
= scale_image_size (desired_height
, height
, width
);
7766 *d_width
= desired_width
;
7767 *d_height
= desired_height
;
7770 static Lisp_Object Qimagemagick
;
7772 static bool imagemagick_image_p (Lisp_Object
);
7773 static bool imagemagick_load (struct frame
*, struct image
*);
7774 static void imagemagick_clear_image (struct frame
*, struct image
*);
7776 /* Indices of image specification fields in imagemagick_format. */
7778 enum imagemagick_keyword_index
7786 IMAGEMAGICK_ALGORITHM
,
7787 IMAGEMAGICK_HEURISTIC_MASK
,
7789 IMAGEMAGICK_BACKGROUND
,
7792 IMAGEMAGICK_MAX_HEIGHT
,
7793 IMAGEMAGICK_MAX_WIDTH
,
7795 IMAGEMAGICK_ROTATION
,
7800 /* Vector of image_keyword structures describing the format
7801 of valid user-defined image specifications. */
7803 static struct image_keyword imagemagick_format
[IMAGEMAGICK_LAST
] =
7805 {":type", IMAGE_SYMBOL_VALUE
, 1},
7806 {":data", IMAGE_STRING_VALUE
, 0},
7807 {":file", IMAGE_STRING_VALUE
, 0},
7808 {":ascent", IMAGE_ASCENT_VALUE
, 0},
7809 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
7810 {":relief", IMAGE_INTEGER_VALUE
, 0},
7811 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7812 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7813 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
7814 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0},
7815 {":height", IMAGE_INTEGER_VALUE
, 0},
7816 {":width", IMAGE_INTEGER_VALUE
, 0},
7817 {":max-height", IMAGE_INTEGER_VALUE
, 0},
7818 {":max-width", IMAGE_INTEGER_VALUE
, 0},
7819 {":format", IMAGE_SYMBOL_VALUE
, 0},
7820 {":rotation", IMAGE_NUMBER_VALUE
, 0},
7821 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE
, 0}
7824 #if defined HAVE_NTGUI && defined WINDOWSNT
7825 static bool init_imagemagick_functions (void);
7827 #define init_imagemagick_functions NULL
7830 /* Structure describing the image type for any image handled via
7833 static struct image_type imagemagick_type
=
7836 imagemagick_image_p
,
7838 imagemagick_clear_image
,
7839 init_imagemagick_functions
,
7843 /* Free X resources of imagemagick image IMG which is used on frame F. */
7846 imagemagick_clear_image (struct frame
*f
,
7849 x_clear_image (f
, img
);
7852 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7853 this by calling parse_image_spec and supplying the keywords that
7854 identify the IMAGEMAGICK format. */
7857 imagemagick_image_p (Lisp_Object object
)
7859 struct image_keyword fmt
[IMAGEMAGICK_LAST
];
7860 memcpy (fmt
, imagemagick_format
, sizeof fmt
);
7862 if (!parse_image_spec (object
, fmt
, IMAGEMAGICK_LAST
, Qimagemagick
))
7865 /* Must specify either the :data or :file keyword. */
7866 return fmt
[IMAGEMAGICK_FILE
].count
+ fmt
[IMAGEMAGICK_DATA
].count
== 1;
7869 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7870 Therefore rename the function so it doesn't collide with ImageMagick. */
7871 #define DrawRectangle DrawRectangleGif
7872 #include <wand/MagickWand.h>
7874 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7875 Emacs seems to work fine with the hidden version, so unhide it. */
7876 #include <magick/version.h>
7877 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7878 extern WandExport
void PixelGetMagickColor (const PixelWand
*,
7879 MagickPixelPacket
*);
7882 /* Log ImageMagick error message.
7883 Useful when a ImageMagick function returns the status `MagickFalse'. */
7886 imagemagick_error (MagickWand
*wand
)
7889 ExceptionType severity
;
7891 description
= MagickGetException (wand
, &severity
);
7892 image_error ("ImageMagick error: %s",
7893 build_string (description
),
7895 description
= (char *) MagickRelinquishMemory (description
);
7898 /* Possibly give ImageMagick some extra help to determine the image
7899 type by supplying a "dummy" filename based on the Content-Type. */
7902 imagemagick_filename_hint (Lisp_Object spec
, char hint_buffer
[MaxTextExtent
])
7904 Lisp_Object symbol
= intern ("image-format-suffixes");
7905 Lisp_Object val
= find_symbol_value (symbol
);
7911 format
= image_spec_value (spec
, intern (":format"), NULL
);
7912 val
= Fcar_safe (Fcdr_safe (Fassq (format
, val
)));
7913 if (! STRINGP (val
))
7916 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
7917 as ImageMagick would ignore the extra bytes anyway. */
7918 snprintf (hint_buffer
, MaxTextExtent
, "/tmp/foo.%s", SSDATA (val
));
7922 /* Animated images (e.g., GIF89a) are composed from one "master image"
7923 (which is the first one, and then there's a number of images that
7924 follow. If following images have non-transparent colors, these are
7925 composed "on top" of the master image. So, in general, one has to
7926 compute ann the preceding images to be able to display a particular
7929 Computing all the preceding images is too slow, so we maintain a
7930 cache of previously computed images. We have to maintain a cache
7931 separate from the image cache, because the images may be scaled
7934 struct animation_cache
7938 struct timespec update_time
;
7939 struct animation_cache
*next
;
7940 char signature
[FLEXIBLE_ARRAY_MEMBER
];
7943 static struct animation_cache
*animation_cache
= NULL
;
7945 static struct animation_cache
*
7946 imagemagick_create_cache (char *signature
)
7948 struct animation_cache
*cache
7949 = xmalloc (offsetof (struct animation_cache
, signature
)
7950 + strlen (signature
) + 1);
7954 strcpy (cache
->signature
, signature
);
7958 /* Discard cached images that haven't been used for a minute. */
7960 imagemagick_prune_animation_cache (void)
7962 struct animation_cache
**pcache
= &animation_cache
;
7963 struct timespec old
= timespec_sub (current_timespec (),
7964 make_timespec (60, 0));
7968 struct animation_cache
*cache
= *pcache
;
7969 if (timespec_cmp (old
, cache
->update_time
) <= 0)
7970 pcache
= &cache
->next
;
7974 DestroyMagickWand (cache
->wand
);
7975 *pcache
= cache
->next
;
7981 static struct animation_cache
*
7982 imagemagick_get_animation_cache (MagickWand
*wand
)
7984 char *signature
= MagickGetImageSignature (wand
);
7985 struct animation_cache
*cache
;
7986 struct animation_cache
**pcache
= &animation_cache
;
7988 imagemagick_prune_animation_cache ();
7995 *pcache
= cache
= imagemagick_create_cache (signature
);
7998 if (strcmp (signature
, cache
->signature
) == 0)
8000 pcache
= &cache
->next
;
8003 DestroyString (signature
);
8004 cache
->update_time
= current_timespec ();
8009 imagemagick_compute_animated_image (MagickWand
*super_wand
, int ino
)
8012 MagickWand
*composite_wand
;
8013 size_t dest_width
, dest_height
;
8014 struct animation_cache
*cache
= imagemagick_get_animation_cache (super_wand
);
8016 MagickSetIteratorIndex (super_wand
, 0);
8018 if (ino
== 0 || cache
->wand
== NULL
|| cache
->index
> ino
)
8020 composite_wand
= MagickGetImage (super_wand
);
8022 DestroyMagickWand (cache
->wand
);
8025 composite_wand
= cache
->wand
;
8027 dest_width
= MagickGetImageWidth (composite_wand
);
8028 dest_height
= MagickGetImageHeight (composite_wand
);
8030 for (i
= max (1, cache
->index
+ 1); i
<= ino
; i
++)
8032 MagickWand
*sub_wand
;
8033 PixelIterator
*source_iterator
, *dest_iterator
;
8034 PixelWand
**source
, **dest
;
8035 size_t source_width
, source_height
;
8036 ssize_t source_left
, source_top
;
8037 MagickPixelPacket pixel
;
8038 DisposeType dispose
;
8039 ptrdiff_t lines
= 0;
8041 MagickSetIteratorIndex (super_wand
, i
);
8042 sub_wand
= MagickGetImage (super_wand
);
8044 MagickGetImagePage (sub_wand
, &source_width
, &source_height
,
8045 &source_left
, &source_top
);
8047 /* This flag says how to handle transparent pixels. */
8048 dispose
= MagickGetImageDispose (sub_wand
);
8050 source_iterator
= NewPixelIterator (sub_wand
);
8051 if (! source_iterator
)
8053 DestroyMagickWand (composite_wand
);
8054 DestroyMagickWand (sub_wand
);
8056 image_error ("Imagemagick pixel iterator creation failed",
8061 dest_iterator
= NewPixelIterator (composite_wand
);
8062 if (! dest_iterator
)
8064 DestroyMagickWand (composite_wand
);
8065 DestroyMagickWand (sub_wand
);
8066 DestroyPixelIterator (source_iterator
);
8068 image_error ("Imagemagick pixel iterator creation failed",
8073 /* The sub-image may not start at origin, so move the destination
8074 iterator to where the sub-image should start. */
8077 PixelSetIteratorRow (dest_iterator
, source_top
);
8081 while ((source
= PixelGetNextIteratorRow (source_iterator
, &source_width
))
8086 /* Sanity check. This shouldn't happen, but apparently
8087 does in some pictures. */
8088 if (++lines
>= dest_height
)
8091 dest
= PixelGetNextIteratorRow (dest_iterator
, &dest_width
);
8092 for (x
= 0; x
< source_width
; x
++)
8094 /* Sanity check. This shouldn't happen, but apparently
8095 also does in some pictures. */
8096 if (x
+ source_left
> dest_width
- 1)
8098 /* Normally we only copy over non-transparent pixels,
8099 but if the disposal method is "Background", then we
8100 copy over all pixels. */
8101 if (dispose
== BackgroundDispose
||
8102 PixelGetAlpha (source
[x
]))
8104 PixelGetMagickColor (source
[x
], &pixel
);
8105 PixelSetMagickColor (dest
[x
+ source_left
], &pixel
);
8108 PixelSyncIterator (dest_iterator
);
8111 DestroyPixelIterator (source_iterator
);
8112 DestroyPixelIterator (dest_iterator
);
8113 DestroyMagickWand (sub_wand
);
8116 /* Cache a copy for the next iteration. The current wand will be
8117 destroyed by the caller. */
8118 cache
->wand
= CloneMagickWand (composite_wand
);
8121 return composite_wand
;
8125 /* Helper function for imagemagick_load, which does the actual loading
8126 given contents and size, apart from frame and image structures,
8127 passed from imagemagick_load. Uses librimagemagick to do most of
8128 the image processing.
8130 F is a pointer to the Emacs frame; IMG to the image structure to
8131 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8132 be parsed; SIZE is the number of bytes of data; and FILENAME is
8133 either the file name or the image data.
8135 Return true if successful. */
8138 imagemagick_load_image (struct frame
*f
, struct image
*img
,
8139 unsigned char *contents
, unsigned int size
,
8142 size_t width
, height
;
8143 MagickBooleanType status
;
8146 MagickWand
*image_wand
;
8147 PixelIterator
*iterator
;
8148 PixelWand
**pixels
, *bg_wand
= NULL
;
8149 MagickPixelPacket pixel
;
8154 int desired_width
, desired_height
;
8157 char hint_buffer
[MaxTextExtent
];
8158 char *filename_hint
= NULL
;
8160 /* Handle image index for image types who can contain more than one image.
8161 Interface :index is same as for GIF. First we "ping" the image to see how
8162 many sub-images it contains. Pinging is faster than loading the image to
8163 find out things about it. */
8165 /* Initialize the imagemagick environment. */
8166 MagickWandGenesis ();
8167 image
= image_spec_value (img
->spec
, QCindex
, NULL
);
8168 ino
= INTEGERP (image
) ? XFASTINT (image
) : 0;
8169 image_wand
= NewMagickWand ();
8172 status
= MagickReadImage (image_wand
, filename
);
8175 filename_hint
= imagemagick_filename_hint (img
->spec
, hint_buffer
);
8176 MagickSetFilename (image_wand
, filename_hint
);
8177 status
= MagickReadImageBlob (image_wand
, contents
, size
);
8180 if (status
== MagickFalse
)
8182 imagemagick_error (image_wand
);
8183 DestroyMagickWand (image_wand
);
8187 if (ino
< 0 || ino
>= MagickGetNumberImages (image_wand
))
8189 image_error ("Invalid image number `%s' in image `%s'",
8191 DestroyMagickWand (image_wand
);
8195 if (MagickGetNumberImages (image_wand
) > 1)
8198 Fcons (make_number (MagickGetNumberImages (image_wand
)),
8201 /* If we have an animated image, get the new wand based on the
8203 if (MagickGetNumberImages (image_wand
) > 1)
8205 MagickWand
*super_wand
= image_wand
;
8206 image_wand
= imagemagick_compute_animated_image (super_wand
, ino
);
8208 image_wand
= super_wand
;
8210 DestroyMagickWand (super_wand
);
8213 /* Retrieve the frame's background color, for use later. */
8216 Lisp_Object specified_bg
;
8218 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8219 if (!STRINGP (specified_bg
)
8220 || !x_defined_color (f
, SSDATA (specified_bg
), &bgcolor
, 0))
8223 bgcolor
.pixel
= FRAME_BACKGROUND_PIXEL (f
);
8224 x_query_color (f
, &bgcolor
);
8226 ns_query_color (FRAME_BACKGROUND_COLOR (f
), &bgcolor
, 1);
8230 bg_wand
= NewPixelWand ();
8231 PixelSetRed (bg_wand
, (double) bgcolor
.red
/ 65535);
8232 PixelSetGreen (bg_wand
, (double) bgcolor
.green
/ 65535);
8233 PixelSetBlue (bg_wand
, (double) bgcolor
.blue
/ 65535);
8236 compute_image_size (MagickGetImageWidth (image_wand
),
8237 MagickGetImageHeight (image_wand
),
8238 img
->spec
, &desired_width
, &desired_height
);
8240 if (desired_width
!= -1 && desired_height
!= -1)
8242 status
= MagickScaleImage (image_wand
, desired_width
, desired_height
);
8243 if (status
== MagickFalse
)
8245 image_error ("Imagemagick scale failed", Qnil
, Qnil
);
8246 imagemagick_error (image_wand
);
8247 goto imagemagick_error
;
8251 /* crop behaves similar to image slicing in Emacs but is more memory
8253 crop
= image_spec_value (img
->spec
, QCcrop
, NULL
);
8255 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8257 /* After some testing, it seems MagickCropImage is the fastest crop
8258 function in ImageMagick. This crop function seems to do less copying
8259 than the alternatives, but it still reads the entire image into memory
8260 before cropping, which is apparently difficult to avoid when using
8262 size_t crop_width
= XINT (XCAR (crop
));
8264 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop
)))
8266 size_t crop_height
= XINT (XCAR (crop
));
8268 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8270 ssize_t crop_x
= XINT (XCAR (crop
));
8272 if (CONSP (crop
) && TYPE_RANGED_INTEGERP (ssize_t
, XCAR (crop
)))
8274 ssize_t crop_y
= XINT (XCAR (crop
));
8275 MagickCropImage (image_wand
, crop_width
, crop_height
,
8282 /* Furthermore :rotation. we need background color and angle for
8285 TODO background handling for rotation specified_bg =
8286 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8288 value
= image_spec_value (img
->spec
, QCrotation
, NULL
);
8291 rotation
= extract_float (value
);
8292 status
= MagickRotateImage (image_wand
, bg_wand
, rotation
);
8293 if (status
== MagickFalse
)
8295 image_error ("Imagemagick image rotate failed", Qnil
, Qnil
);
8296 imagemagick_error (image_wand
);
8297 goto imagemagick_error
;
8301 /* Set the canvas background color to the frame or specified
8302 background, and flatten the image. Note: as of ImageMagick
8303 6.6.0, SVG image transparency is not handled properly
8304 (e.g. etc/images/splash.svg shows a white background always). */
8306 MagickWand
*new_wand
;
8307 MagickSetImageBackgroundColor (image_wand
, bg_wand
);
8308 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8309 new_wand
= MagickMergeImageLayers (image_wand
, MergeLayer
);
8311 new_wand
= MagickFlattenImages (image_wand
);
8313 DestroyMagickWand (image_wand
);
8314 image_wand
= new_wand
;
8317 /* Finally we are done manipulating the image. Figure out the
8318 resulting width/height and transfer ownership to Emacs. */
8319 height
= MagickGetImageHeight (image_wand
);
8320 width
= MagickGetImageWidth (image_wand
);
8322 if (! (width
<= INT_MAX
&& height
<= INT_MAX
8323 && check_image_size (f
, width
, height
)))
8325 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
8326 goto imagemagick_error
;
8329 /* We can now get a valid pixel buffer from the imagemagick file, if all
8332 init_color_table ();
8334 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8335 if (imagemagick_render_type
!= 0)
8337 /* Magicexportimage is normally faster than pixelpushing. This
8338 method is also well tested. Some aspects of this method are
8339 ad-hoc and needs to be more researched. */
8340 int imagedepth
= 24; /*MagickGetImageDepth(image_wand);*/
8341 const char *exportdepth
= imagedepth
<= 8 ? "I" : "BGRP"; /*"RGBP";*/
8342 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8343 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, imagedepth
,
8346 #ifdef COLOR_TABLE_SUPPORT
8347 free_color_table ();
8349 image_error ("Imagemagick X bitmap allocation failure", Qnil
, Qnil
);
8350 goto imagemagick_error
;
8353 /* Oddly, the below code doesn't seem to work:*/
8354 /* switch(ximg->bitmap_unit){ */
8356 /* pixelwidth=CharPixel; */
8359 /* pixelwidth=ShortPixel; */
8362 /* pixelwidth=LongPixel; */
8366 Here im just guessing the format of the bitmap.
8367 happens to work fine for:
8370 seems about 3 times as fast as pixel pushing(not carefully measured)
8372 pixelwidth
= CharPixel
; /*??? TODO figure out*/
8373 MagickExportImagePixels (image_wand
, 0, 0, width
, height
,
8374 exportdepth
, pixelwidth
, ximg
->data
);
8377 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8379 size_t image_height
;
8381 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8382 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0,
8385 #ifdef COLOR_TABLE_SUPPORT
8386 free_color_table ();
8388 image_error ("Imagemagick X bitmap allocation failure", Qnil
, Qnil
);
8389 goto imagemagick_error
;
8392 /* Copy imagemagick image to x with primitive yet robust pixel
8393 pusher loop. This has been tested a lot with many different
8396 /* Copy pixels from the imagemagick image structure to the x image map. */
8397 iterator
= NewPixelIterator (image_wand
);
8400 #ifdef COLOR_TABLE_SUPPORT
8401 free_color_table ();
8403 x_destroy_x_image (ximg
);
8404 image_error ("Imagemagick pixel iterator creation failed",
8406 goto imagemagick_error
;
8409 image_height
= MagickGetImageHeight (image_wand
);
8410 for (y
= 0; y
< image_height
; y
++)
8412 pixels
= PixelGetNextIteratorRow (iterator
, &width
);
8415 for (x
= 0; x
< (long) width
; x
++)
8417 PixelGetMagickColor (pixels
[x
], &pixel
);
8418 XPutPixel (ximg
, x
, y
,
8419 lookup_rgb_color (f
,
8425 DestroyPixelIterator (iterator
);
8428 #ifdef COLOR_TABLE_SUPPORT
8429 /* Remember colors allocated for this image. */
8430 img
->colors
= colors_in_color_table (&img
->ncolors
);
8431 free_color_table ();
8432 #endif /* COLOR_TABLE_SUPPORT */
8435 img
->height
= height
;
8437 /* Put ximg into the image. */
8438 image_put_x_image (f
, img
, ximg
, 0);
8440 /* Final cleanup. image_wand should be the only resource left. */
8441 DestroyMagickWand (image_wand
);
8442 if (bg_wand
) DestroyPixelWand (bg_wand
);
8444 /* `MagickWandTerminus' terminates the imagemagick environment. */
8445 MagickWandTerminus ();
8450 DestroyMagickWand (image_wand
);
8451 if (bg_wand
) DestroyPixelWand (bg_wand
);
8453 MagickWandTerminus ();
8454 /* TODO more cleanup. */
8455 image_error ("Error parsing IMAGEMAGICK image `%s'", img
->spec
, Qnil
);
8460 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8461 successful. this function will go into the imagemagick_type structure, and
8462 the prototype thus needs to be compatible with that structure. */
8465 imagemagick_load (struct frame
*f
, struct image
*img
)
8468 Lisp_Object file_name
;
8470 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8471 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8472 if (STRINGP (file_name
))
8476 file
= x_find_image_file (file_name
);
8477 if (!STRINGP (file
))
8479 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
8482 success_p
= imagemagick_load_image (f
, img
, 0, 0, SSDATA (file
));
8484 /* Else its not a file, its a lisp object. Load the image from a
8485 lisp object rather than a file. */
8490 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8491 if (!STRINGP (data
))
8493 image_error ("Invalid image data `%s'", data
, Qnil
);
8496 success_p
= imagemagick_load_image (f
, img
, SDATA (data
),
8497 SBYTES (data
), NULL
);
8503 DEFUN ("imagemagick-types", Fimagemagick_types
, Simagemagick_types
, 0, 0, 0,
8504 doc
: /* Return a list of image types supported by ImageMagick.
8505 Each entry in this list is a symbol named after an ImageMagick format
8506 tag. See the ImageMagick manual for a list of ImageMagick formats and
8507 their descriptions (http://www.imagemagick.org/script/formats.php).
8508 You can also try the shell command: `identify -list format'.
8510 Note that ImageMagick recognizes many file-types that Emacs does not
8511 recognize as images, such as C. See `imagemagick-types-enable'
8512 and `imagemagick-types-inhibit'. */)
8515 Lisp_Object typelist
= Qnil
;
8520 Lisp_Object Qimagemagicktype
;
8522 GetExceptionInfo(&ex
);
8523 imtypes
= GetMagickList ("*", &numf
, &ex
);
8524 DestroyExceptionInfo(&ex
);
8526 for (i
= 0; i
< numf
; i
++)
8528 Qimagemagicktype
= intern (imtypes
[i
]);
8529 typelist
= Fcons (Qimagemagicktype
, typelist
);
8531 return Fnreverse (typelist
);
8534 #endif /* defined (HAVE_IMAGEMAGICK) */
8538 /***********************************************************************
8540 ***********************************************************************/
8542 #if defined (HAVE_RSVG)
8544 /* Function prototypes. */
8546 static bool svg_image_p (Lisp_Object object
);
8547 static bool svg_load (struct frame
*f
, struct image
*img
);
8549 static bool svg_load_image (struct frame
*, struct image
*,
8550 unsigned char *, ptrdiff_t);
8552 /* The symbol `svg' identifying images of this type. */
8554 static Lisp_Object Qsvg
;
8556 /* Indices of image specification fields in svg_format, below. */
8558 enum svg_keyword_index
8573 /* Vector of image_keyword structures describing the format
8574 of valid user-defined image specifications. */
8576 static const struct image_keyword svg_format
[SVG_LAST
] =
8578 {":type", IMAGE_SYMBOL_VALUE
, 1},
8579 {":data", IMAGE_STRING_VALUE
, 0},
8580 {":file", IMAGE_STRING_VALUE
, 0},
8581 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8582 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8583 {":relief", IMAGE_INTEGER_VALUE
, 0},
8584 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8585 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8586 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8587 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8590 #if defined HAVE_NTGUI && defined WINDOWSNT
8591 static bool init_svg_functions (void);
8593 #define init_svg_functions NULL
8596 /* Structure describing the image type `svg'. Its the same type of
8597 structure defined for all image formats, handled by emacs image
8598 functions. See struct image_type in dispextern.h. */
8600 static struct image_type svg_type
=
8611 /* Return true if OBJECT is a valid SVG image specification. Do
8612 this by calling parse_image_spec and supplying the keywords that
8613 identify the SVG format. */
8616 svg_image_p (Lisp_Object object
)
8618 struct image_keyword fmt
[SVG_LAST
];
8619 memcpy (fmt
, svg_format
, sizeof fmt
);
8621 if (!parse_image_spec (object
, fmt
, SVG_LAST
, Qsvg
))
8624 /* Must specify either the :data or :file keyword. */
8625 return fmt
[SVG_FILE
].count
+ fmt
[SVG_DATA
].count
== 1;
8628 #include <librsvg/rsvg.h>
8632 /* SVG library functions. */
8633 DEF_IMGLIB_FN (RsvgHandle
*, rsvg_handle_new
, (void));
8634 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions
, (RsvgHandle
*, RsvgDimensionData
*));
8635 DEF_IMGLIB_FN (gboolean
, rsvg_handle_write
, (RsvgHandle
*, const guchar
*, gsize
, GError
**));
8636 DEF_IMGLIB_FN (gboolean
, rsvg_handle_close
, (RsvgHandle
*, GError
**));
8637 DEF_IMGLIB_FN (GdkPixbuf
*, rsvg_handle_get_pixbuf
, (RsvgHandle
*));
8638 DEF_IMGLIB_FN (void *, rsvg_handle_set_size_callback
, (RsvgHandle
*, RsvgSizeFunc
, gpointer
, GDestroyNotify
));
8640 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width
, (const GdkPixbuf
*));
8641 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height
, (const GdkPixbuf
*));
8642 DEF_IMGLIB_FN (guchar
*, gdk_pixbuf_get_pixels
, (const GdkPixbuf
*));
8643 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride
, (const GdkPixbuf
*));
8644 DEF_IMGLIB_FN (GdkColorspace
, gdk_pixbuf_get_colorspace
, (const GdkPixbuf
*));
8645 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels
, (const GdkPixbuf
*));
8646 DEF_IMGLIB_FN (gboolean
, gdk_pixbuf_get_has_alpha
, (const GdkPixbuf
*));
8647 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample
, (const GdkPixbuf
*));
8649 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8650 DEF_IMGLIB_FN (void, g_type_init
, (void));
8652 DEF_IMGLIB_FN (void, g_object_unref
, (gpointer
));
8653 DEF_IMGLIB_FN (void, g_error_free
, (GError
*));
8655 Lisp_Object Qgdk_pixbuf
, Qglib
, Qgobject
;
8658 init_svg_functions (void)
8660 HMODULE library
, gdklib
, glib
, gobject
;
8662 if (!(glib
= w32_delayed_load (Qglib
))
8663 || !(gobject
= w32_delayed_load (Qgobject
))
8664 || !(gdklib
= w32_delayed_load (Qgdk_pixbuf
))
8665 || !(library
= w32_delayed_load (Qsvg
)))
8668 LOAD_IMGLIB_FN (library
, rsvg_handle_new
);
8669 LOAD_IMGLIB_FN (library
, rsvg_handle_get_dimensions
);
8670 LOAD_IMGLIB_FN (library
, rsvg_handle_write
);
8671 LOAD_IMGLIB_FN (library
, rsvg_handle_close
);
8672 LOAD_IMGLIB_FN (library
, rsvg_handle_get_pixbuf
);
8674 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_width
);
8675 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_height
);
8676 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_pixels
);
8677 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_rowstride
);
8678 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_colorspace
);
8679 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_n_channels
);
8680 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_has_alpha
);
8681 LOAD_IMGLIB_FN (gdklib
, gdk_pixbuf_get_bits_per_sample
);
8683 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8684 LOAD_IMGLIB_FN (gobject
, g_type_init
);
8686 LOAD_IMGLIB_FN (gobject
, g_object_unref
);
8687 LOAD_IMGLIB_FN (glib
, g_error_free
);
8693 /* The following aliases for library functions allow dynamic loading
8694 to be used on some platforms. */
8695 #define fn_rsvg_handle_new rsvg_handle_new
8696 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8697 #define fn_rsvg_handle_write rsvg_handle_write
8698 #define fn_rsvg_handle_close rsvg_handle_close
8699 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8701 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8702 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8703 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8704 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8705 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8706 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8707 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8708 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8710 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8711 #define fn_g_type_init g_type_init
8713 #define fn_g_object_unref g_object_unref
8714 #define fn_g_error_free g_error_free
8715 #endif /* !WINDOWSNT */
8717 /* Load SVG image IMG for use on frame F. Value is true if
8721 svg_load (struct frame
*f
, struct image
*img
)
8724 Lisp_Object file_name
;
8726 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8727 file_name
= image_spec_value (img
->spec
, QCfile
, NULL
);
8728 if (STRINGP (file_name
))
8731 unsigned char *contents
;
8734 file
= x_find_image_file (file_name
);
8735 if (!STRINGP (file
))
8737 image_error ("Cannot find image file `%s'", file_name
, Qnil
);
8741 /* Read the entire file into memory. */
8742 contents
= slurp_file (SSDATA (file
), &size
);
8743 if (contents
== NULL
)
8745 image_error ("Error loading SVG image `%s'", img
->spec
, Qnil
);
8748 /* If the file was slurped into memory properly, parse it. */
8749 success_p
= svg_load_image (f
, img
, contents
, size
);
8752 /* Else its not a file, its a lisp object. Load the image from a
8753 lisp object rather than a file. */
8758 data
= image_spec_value (img
->spec
, QCdata
, NULL
);
8759 if (!STRINGP (data
))
8761 image_error ("Invalid image data `%s'", data
, Qnil
);
8764 success_p
= svg_load_image (f
, img
, SDATA (data
), SBYTES (data
));
8770 /* svg_load_image is a helper function for svg_load, which does the
8771 actual loading given contents and size, apart from frame and image
8772 structures, passed from svg_load.
8774 Uses librsvg to do most of the image processing.
8776 Returns true when successful. */
8778 svg_load_image (struct frame
*f
, /* Pointer to emacs frame structure. */
8779 struct image
*img
, /* Pointer to emacs image structure. */
8780 unsigned char *contents
, /* String containing the SVG XML data to be parsed. */
8781 ptrdiff_t size
) /* Size of data in bytes. */
8783 RsvgHandle
*rsvg_handle
;
8784 RsvgDimensionData dimension_data
;
8789 const guint8
*pixels
;
8792 Lisp_Object specified_bg
;
8797 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8798 /* g_type_init is a glib function that must be called prior to
8799 using gnome type library functions (obsolete since 2.36.0). */
8803 /* Make a handle to a new rsvg object. */
8804 rsvg_handle
= fn_rsvg_handle_new ();
8806 /* Parse the contents argument and fill in the rsvg_handle. */
8807 fn_rsvg_handle_write (rsvg_handle
, contents
, size
, &err
);
8808 if (err
) goto rsvg_error
;
8810 /* The parsing is complete, rsvg_handle is ready to used, close it
8811 for further writes. */
8812 fn_rsvg_handle_close (rsvg_handle
, &err
);
8813 if (err
) goto rsvg_error
;
8815 fn_rsvg_handle_get_dimensions (rsvg_handle
, &dimension_data
);
8816 if (! check_image_size (f
, dimension_data
.width
, dimension_data
.height
))
8818 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
8822 /* We can now get a valid pixel buffer from the svg file, if all
8824 pixbuf
= fn_rsvg_handle_get_pixbuf (rsvg_handle
);
8825 if (!pixbuf
) goto rsvg_error
;
8826 fn_g_object_unref (rsvg_handle
);
8828 /* Extract some meta data from the svg handle. */
8829 width
= fn_gdk_pixbuf_get_width (pixbuf
);
8830 height
= fn_gdk_pixbuf_get_height (pixbuf
);
8831 pixels
= fn_gdk_pixbuf_get_pixels (pixbuf
);
8832 rowstride
= fn_gdk_pixbuf_get_rowstride (pixbuf
);
8834 /* Validate the svg meta data. */
8835 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf
) == GDK_COLORSPACE_RGB
);
8836 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf
) == 4);
8837 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf
));
8838 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf
) == 8);
8840 /* Try to create a x pixmap to hold the svg pixmap. */
8841 if (!image_create_x_image_and_pixmap (f
, img
, width
, height
, 0, &ximg
, 0))
8843 fn_g_object_unref (pixbuf
);
8847 init_color_table ();
8849 /* Handle alpha channel by combining the image with a background
8851 specified_bg
= image_spec_value (img
->spec
, QCbackground
, NULL
);
8852 if (!STRINGP (specified_bg
)
8853 || !x_defined_color (f
, SSDATA (specified_bg
), &background
, 0))
8856 background
.pixel
= FRAME_BACKGROUND_PIXEL (f
);
8857 x_query_color (f
, &background
);
8859 ns_query_color (FRAME_BACKGROUND_COLOR (f
), &background
, 1);
8863 /* SVG pixmaps specify transparency in the last byte, so right
8864 shift 8 bits to get rid of it, since emacs doesn't support
8866 background
.red
>>= 8;
8867 background
.green
>>= 8;
8868 background
.blue
>>= 8;
8870 /* This loop handles opacity values, since Emacs assumes
8871 non-transparent images. Each pixel must be "flattened" by
8872 calculating the resulting color, given the transparency of the
8873 pixel, and the image background color. */
8874 for (y
= 0; y
< height
; ++y
)
8876 for (x
= 0; x
< width
; ++x
)
8886 opacity
= *pixels
++;
8888 red
= ((red
* opacity
)
8889 + (background
.red
* ((1 << 8) - opacity
)));
8890 green
= ((green
* opacity
)
8891 + (background
.green
* ((1 << 8) - opacity
)));
8892 blue
= ((blue
* opacity
)
8893 + (background
.blue
* ((1 << 8) - opacity
)));
8895 XPutPixel (ximg
, x
, y
, lookup_rgb_color (f
, red
, green
, blue
));
8898 pixels
+= rowstride
- 4 * width
;
8901 #ifdef COLOR_TABLE_SUPPORT
8902 /* Remember colors allocated for this image. */
8903 img
->colors
= colors_in_color_table (&img
->ncolors
);
8904 free_color_table ();
8905 #endif /* COLOR_TABLE_SUPPORT */
8907 fn_g_object_unref (pixbuf
);
8910 img
->height
= height
;
8912 /* Maybe fill in the background field while we have ximg handy.
8913 Casting avoids a GCC warning. */
8914 IMAGE_BACKGROUND (img
, f
, (XImagePtr_or_DC
)ximg
);
8916 /* Put ximg into the image. */
8917 image_put_x_image (f
, img
, ximg
, 0);
8922 fn_g_object_unref (rsvg_handle
);
8923 /* FIXME: Use error->message so the user knows what is the actual
8924 problem with the image. */
8925 image_error ("Error parsing SVG image `%s'", img
->spec
, Qnil
);
8926 fn_g_error_free (err
);
8930 #endif /* defined (HAVE_RSVG) */
8935 /***********************************************************************
8937 ***********************************************************************/
8939 #ifdef HAVE_X_WINDOWS
8940 #define HAVE_GHOSTSCRIPT 1
8941 #endif /* HAVE_X_WINDOWS */
8943 #ifdef HAVE_GHOSTSCRIPT
8945 static bool gs_image_p (Lisp_Object object
);
8946 static bool gs_load (struct frame
*f
, struct image
*img
);
8947 static void gs_clear_image (struct frame
*f
, struct image
*img
);
8949 /* Keyword symbols. */
8951 static Lisp_Object QCloader
, QCbounding_box
, QCpt_width
, QCpt_height
;
8953 /* Indices of image specification fields in gs_format, below. */
8955 enum gs_keyword_index
8973 /* Vector of image_keyword structures describing the format
8974 of valid user-defined image specifications. */
8976 static const struct image_keyword gs_format
[GS_LAST
] =
8978 {":type", IMAGE_SYMBOL_VALUE
, 1},
8979 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
8980 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE
, 1},
8981 {":file", IMAGE_STRING_VALUE
, 1},
8982 {":loader", IMAGE_FUNCTION_VALUE
, 0},
8983 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE
, 1},
8984 {":ascent", IMAGE_ASCENT_VALUE
, 0},
8985 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR
, 0},
8986 {":relief", IMAGE_INTEGER_VALUE
, 0},
8987 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8988 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8989 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE
, 0},
8990 {":background", IMAGE_STRING_OR_NIL_VALUE
, 0}
8993 /* Structure describing the image type `ghostscript'. */
8995 static struct image_type gs_type
=
9006 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9009 gs_clear_image (struct frame
*f
, struct image
*img
)
9011 x_clear_image (f
, img
);
9015 /* Return true if OBJECT is a valid Ghostscript image
9019 gs_image_p (Lisp_Object object
)
9021 struct image_keyword fmt
[GS_LAST
];
9025 memcpy (fmt
, gs_format
, sizeof fmt
);
9027 if (!parse_image_spec (object
, fmt
, GS_LAST
, Qpostscript
))
9030 /* Bounding box must be a list or vector containing 4 integers. */
9031 tem
= fmt
[GS_BOUNDING_BOX
].value
;
9034 for (i
= 0; i
< 4; ++i
, tem
= XCDR (tem
))
9035 if (!CONSP (tem
) || !INTEGERP (XCAR (tem
)))
9040 else if (VECTORP (tem
))
9042 if (ASIZE (tem
) != 4)
9044 for (i
= 0; i
< 4; ++i
)
9045 if (!INTEGERP (AREF (tem
, i
)))
9055 /* Load Ghostscript image IMG for use on frame F. Value is true
9059 gs_load (struct frame
*f
, struct image
*img
)
9061 uprintmax_t printnum1
, printnum2
;
9062 char buffer
[sizeof " " + INT_STRLEN_BOUND (printmax_t
)];
9063 Lisp_Object window_and_pixmap_id
= Qnil
, loader
, pt_height
, pt_width
;
9065 double in_width
, in_height
;
9066 Lisp_Object pixel_colors
= Qnil
;
9068 /* Compute pixel size of pixmap needed from the given size in the
9069 image specification. Sizes in the specification are in pt. 1 pt
9070 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9072 pt_width
= image_spec_value (img
->spec
, QCpt_width
, NULL
);
9073 in_width
= INTEGERP (pt_width
) ? XFASTINT (pt_width
) / 72.0 : 0;
9074 in_width
*= FRAME_RES_X (f
);
9075 pt_height
= image_spec_value (img
->spec
, QCpt_height
, NULL
);
9076 in_height
= INTEGERP (pt_height
) ? XFASTINT (pt_height
) / 72.0 : 0;
9077 in_height
*= FRAME_RES_Y (f
);
9079 if (! (in_width
<= INT_MAX
&& in_height
<= INT_MAX
9080 && check_image_size (f
, in_width
, in_height
)))
9082 image_error ("Invalid image size (see `max-image-size')", Qnil
, Qnil
);
9085 img
->width
= in_width
;
9086 img
->height
= in_height
;
9088 /* Create the pixmap. */
9089 eassert (img
->pixmap
== NO_PIXMAP
);
9091 if (x_check_image_size (0, img
->width
, img
->height
))
9093 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9095 img
->pixmap
= XCreatePixmap (FRAME_X_DISPLAY (f
), FRAME_X_WINDOW (f
),
9096 img
->width
, img
->height
,
9097 DefaultDepthOfScreen (FRAME_X_SCREEN (f
)));
9103 image_error ("Unable to create pixmap for `%s'", img
->spec
, Qnil
);
9107 /* Call the loader to fill the pixmap. It returns a process object
9108 if successful. We do not record_unwind_protect here because
9109 other places in redisplay like calling window scroll functions
9110 don't either. Let the Lisp loader use `unwind-protect' instead. */
9111 printnum1
= FRAME_X_WINDOW (f
);
9112 printnum2
= img
->pixmap
;
9113 window_and_pixmap_id
9114 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9116 printnum1
= FRAME_FOREGROUND_PIXEL (f
);
9117 printnum2
= FRAME_BACKGROUND_PIXEL (f
);
9119 = make_formatted_string (buffer
, "%"pMu
" %"pMu
, printnum1
, printnum2
);
9121 XSETFRAME (frame
, f
);
9122 loader
= image_spec_value (img
->spec
, QCloader
, NULL
);
9124 loader
= intern ("gs-load-image");
9126 img
->lisp_data
= call6 (loader
, frame
, img
->spec
,
9127 make_number (img
->width
),
9128 make_number (img
->height
),
9129 window_and_pixmap_id
,
9131 return PROCESSP (img
->lisp_data
);
9135 /* Kill the Ghostscript process that was started to fill PIXMAP on
9136 frame F. Called from XTread_socket when receiving an event
9137 telling Emacs that Ghostscript has finished drawing. */
9140 x_kill_gs_process (Pixmap pixmap
, struct frame
*f
)
9142 struct image_cache
*c
= FRAME_IMAGE_CACHE (f
);
9147 /* Find the image containing PIXMAP. */
9148 for (i
= 0; i
< c
->used
; ++i
)
9149 if (c
->images
[i
]->pixmap
== pixmap
)
9152 /* Should someone in between have cleared the image cache, for
9153 instance, give up. */
9157 /* Kill the GS process. We should have found PIXMAP in the image
9158 cache and its image should contain a process object. */
9160 eassert (PROCESSP (img
->lisp_data
));
9161 Fkill_process (img
->lisp_data
, Qnil
);
9162 img
->lisp_data
= Qnil
;
9164 #if defined (HAVE_X_WINDOWS)
9166 /* On displays with a mutable colormap, figure out the colors
9167 allocated for the image by looking at the pixels of an XImage for
9169 class = FRAME_X_VISUAL (f
)->class;
9170 if (class != StaticColor
&& class != StaticGray
&& class != TrueColor
)
9176 /* Try to get an XImage for img->pixmep. */
9177 ximg
= XGetImage (FRAME_X_DISPLAY (f
), img
->pixmap
,
9178 0, 0, img
->width
, img
->height
, ~0, ZPixmap
);
9183 /* Initialize the color table. */
9184 init_color_table ();
9186 /* For each pixel of the image, look its color up in the
9187 color table. After having done so, the color table will
9188 contain an entry for each color used by the image. */
9189 for (y
= 0; y
< img
->height
; ++y
)
9190 for (x
= 0; x
< img
->width
; ++x
)
9192 unsigned long pixel
= XGetPixel (ximg
, x
, y
);
9193 lookup_pixel_color (f
, pixel
);
9196 /* Record colors in the image. Free color table and XImage. */
9197 #ifdef COLOR_TABLE_SUPPORT
9198 img
->colors
= colors_in_color_table (&img
->ncolors
);
9199 free_color_table ();
9201 XDestroyImage (ximg
);
9203 #if 0 /* This doesn't seem to be the case. If we free the colors
9204 here, we get a BadAccess later in x_clear_image when
9205 freeing the colors. */
9206 /* We have allocated colors once, but Ghostscript has also
9207 allocated colors on behalf of us. So, to get the
9208 reference counts right, free them once. */
9210 x_free_colors (f
, img
->colors
, img
->ncolors
);
9214 image_error ("Cannot get X image of `%s'; colors will not be freed",
9219 #endif /* HAVE_X_WINDOWS */
9221 /* Now that we have the pixmap, compute mask and transform the
9222 image if requested. */
9224 postprocess_image (f
, img
);
9228 #endif /* HAVE_GHOSTSCRIPT */
9231 /***********************************************************************
9233 ***********************************************************************/
9237 DEFUN ("imagep", Fimagep
, Simagep
, 1, 1, 0,
9238 doc
: /* Value is non-nil if SPEC is a valid image specification. */)
9241 return valid_image_p (spec
) ? Qt
: Qnil
;
9245 DEFUN ("lookup-image", Flookup_image
, Slookup_image
, 1, 1, 0, "")
9250 if (valid_image_p (spec
))
9251 id
= lookup_image (SELECTED_FRAME (), spec
);
9254 return make_number (id
);
9257 #endif /* GLYPH_DEBUG */
9260 /***********************************************************************
9262 ***********************************************************************/
9264 DEFUN ("init-image-library", Finit_image_library
, Sinit_image_library
, 1, 1, 0,
9265 doc
: /* Initialize image library implementing image type TYPE.
9266 Return non-nil if TYPE is a supported image type.
9268 If image libraries are loaded dynamically (currently only the case on
9269 MS-Windows), load the library for TYPE if it is not yet loaded, using
9270 the library file(s) specified by `dynamic-library-alist'. */)
9273 return lookup_image_type (type
) ? Qt
: Qnil
;
9276 /* Look up image type TYPE, and return a pointer to its image_type
9277 structure. Return 0 if TYPE is not a known image type. */
9279 static struct image_type
*
9280 lookup_image_type (Lisp_Object type
)
9282 /* Types pbm and xbm are built-in and always available. */
9283 if (EQ (type
, Qpbm
))
9284 return define_image_type (&pbm_type
);
9286 if (EQ (type
, Qxbm
))
9287 return define_image_type (&xbm_type
);
9289 #if defined (HAVE_XPM) || defined (HAVE_NS)
9290 if (EQ (type
, Qxpm
))
9291 return define_image_type (&xpm_type
);
9294 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9295 if (EQ (type
, Qjpeg
))
9296 return define_image_type (&jpeg_type
);
9299 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9300 if (EQ (type
, Qtiff
))
9301 return define_image_type (&tiff_type
);
9304 #if defined (HAVE_GIF) || defined (HAVE_NS)
9305 if (EQ (type
, Qgif
))
9306 return define_image_type (&gif_type
);
9309 #if defined (HAVE_PNG) || defined (HAVE_NS)
9310 if (EQ (type
, Qpng
))
9311 return define_image_type (&png_type
);
9314 #if defined (HAVE_RSVG)
9315 if (EQ (type
, Qsvg
))
9316 return define_image_type (&svg_type
);
9319 #if defined (HAVE_IMAGEMAGICK)
9320 if (EQ (type
, Qimagemagick
))
9321 return define_image_type (&imagemagick_type
);
9324 #ifdef HAVE_GHOSTSCRIPT
9325 if (EQ (type
, Qpostscript
))
9326 return define_image_type (&gs_type
);
9332 /* Reset image_types before dumping.
9333 Called from Fdump_emacs. */
9336 reset_image_types (void)
9340 struct image_type
*next
= image_types
->next
;
9341 xfree (image_types
);
9347 syms_of_image (void)
9349 /* Initialize this only once; it will be reset before dumping. */
9352 /* Must be defined now because we're going to update it below, while
9353 defining the supported image types. */
9354 DEFVAR_LISP ("image-types", Vimage_types
,
9355 doc
: /* List of potentially supported image types.
9356 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9357 To check whether it is really supported, use `image-type-available-p'. */);
9358 Vimage_types
= Qnil
;
9360 DEFVAR_LISP ("max-image-size", Vmax_image_size
,
9361 doc
: /* Maximum size of images.
9362 Emacs will not load an image into memory if its pixel width or
9363 pixel height exceeds this limit.
9365 If the value is an integer, it directly specifies the maximum
9366 image height and width, measured in pixels. If it is a floating
9367 point number, it specifies the maximum image height and width
9368 as a ratio to the frame height and width. If the value is
9369 non-numeric, there is no explicit limit on the size of images. */);
9370 Vmax_image_size
= make_float (MAX_IMAGE_SIZE
);
9372 DEFSYM (Qcount
, "count");
9373 DEFSYM (Qextension_data
, "extension-data");
9374 DEFSYM (Qdelay
, "delay");
9376 DEFSYM (QCascent
, ":ascent");
9377 DEFSYM (QCmargin
, ":margin");
9378 DEFSYM (QCrelief
, ":relief");
9379 DEFSYM (QCconversion
, ":conversion");
9380 DEFSYM (QCcolor_symbols
, ":color-symbols");
9381 DEFSYM (QCheuristic_mask
, ":heuristic-mask");
9382 DEFSYM (QCindex
, ":index");
9383 DEFSYM (QCgeometry
, ":geometry");
9384 DEFSYM (QCcrop
, ":crop");
9385 DEFSYM (QCrotation
, ":rotation");
9386 DEFSYM (QCmatrix
, ":matrix");
9387 DEFSYM (QCcolor_adjustment
, ":color-adjustment");
9388 DEFSYM (QCmask
, ":mask");
9390 DEFSYM (Qlaplace
, "laplace");
9391 DEFSYM (Qemboss
, "emboss");
9392 DEFSYM (Qedge_detection
, "edge-detection");
9393 DEFSYM (Qheuristic
, "heuristic");
9395 DEFSYM (Qpostscript
, "postscript");
9396 DEFSYM (QCmax_width
, ":max-width");
9397 DEFSYM (QCmax_height
, ":max-height");
9398 #ifdef HAVE_GHOSTSCRIPT
9399 ADD_IMAGE_TYPE (Qpostscript
);
9400 DEFSYM (QCloader
, ":loader");
9401 DEFSYM (QCbounding_box
, ":bounding-box");
9402 DEFSYM (QCpt_width
, ":pt-width");
9403 DEFSYM (QCpt_height
, ":pt-height");
9404 #endif /* HAVE_GHOSTSCRIPT */
9407 DEFSYM (Qlibpng_version
, "libpng-version");
9408 Fset (Qlibpng_version
,
9410 make_number (PNG_LIBPNG_VER
)
9415 DEFSYM (Qlibgif_version
, "libgif-version");
9416 Fset (Qlibgif_version
,
9418 make_number (GIFLIB_MAJOR
* 10000
9419 + GIFLIB_MINOR
* 100
9425 DEFSYM (Qlibjpeg_version
, "libjpeg-version");
9426 Fset (Qlibjpeg_version
,
9428 make_number (JPEG_LIB_VERSION
)
9435 DEFSYM (Qpbm
, "pbm");
9436 ADD_IMAGE_TYPE (Qpbm
);
9438 DEFSYM (Qxbm
, "xbm");
9439 ADD_IMAGE_TYPE (Qxbm
);
9441 #if defined (HAVE_XPM) || defined (HAVE_NS)
9442 DEFSYM (Qxpm
, "xpm");
9443 ADD_IMAGE_TYPE (Qxpm
);
9446 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9447 DEFSYM (Qjpeg
, "jpeg");
9448 ADD_IMAGE_TYPE (Qjpeg
);
9451 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9452 DEFSYM (Qtiff
, "tiff");
9453 ADD_IMAGE_TYPE (Qtiff
);
9456 #if defined (HAVE_GIF) || defined (HAVE_NS)
9457 DEFSYM (Qgif
, "gif");
9458 ADD_IMAGE_TYPE (Qgif
);
9461 #if defined (HAVE_PNG) || defined (HAVE_NS)
9462 DEFSYM (Qpng
, "png");
9463 ADD_IMAGE_TYPE (Qpng
);
9466 #if defined (HAVE_IMAGEMAGICK)
9467 DEFSYM (Qimagemagick
, "imagemagick");
9468 ADD_IMAGE_TYPE (Qimagemagick
);
9471 #if defined (HAVE_RSVG)
9472 DEFSYM (Qsvg
, "svg");
9473 ADD_IMAGE_TYPE (Qsvg
);
9475 /* Other libraries used directly by svg code. */
9476 DEFSYM (Qgdk_pixbuf
, "gdk-pixbuf");
9477 DEFSYM (Qglib
, "glib");
9478 DEFSYM (Qgobject
, "gobject");
9479 #endif /* HAVE_NTGUI */
9480 #endif /* HAVE_RSVG */
9482 defsubr (&Sinit_image_library
);
9483 #ifdef HAVE_IMAGEMAGICK
9484 defsubr (&Simagemagick_types
);
9486 defsubr (&Sclear_image_cache
);
9487 defsubr (&Simage_flush
);
9488 defsubr (&Simage_size
);
9489 defsubr (&Simage_mask_p
);
9490 defsubr (&Simage_metadata
);
9494 defsubr (&Slookup_image
);
9497 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images
,
9498 doc
: /* Non-nil means always draw a cross over disabled images.
9499 Disabled images are those having a `:conversion disabled' property.
9500 A cross is always drawn on black & white displays. */);
9501 cross_disabled_images
= 0;
9503 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path
,
9504 doc
: /* List of directories to search for window system bitmap files. */);
9505 Vx_bitmap_file_path
= decode_env_path (0, PATH_BITMAPS
, 0);
9507 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay
,
9508 doc
: /* Maximum time after which images are removed from the cache.
9509 When an image has not been displayed this many seconds, Emacs
9510 automatically removes it from the image cache. If the cache contains
9511 a large number of images, the actual eviction time may be shorter.
9512 The value can also be nil, meaning the cache is never cleared.
9514 The function `clear-image-cache' disregards this variable. */);
9515 Vimage_cache_eviction_delay
= make_number (300);
9516 #ifdef HAVE_IMAGEMAGICK
9517 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type
,
9518 doc
: /* Integer indicating which ImageMagick rendering method to use.
9520 0 -- the default method (pixel pushing)
9521 1 -- a newer method ("MagickExportImagePixels") that may perform
9522 better (speed etc) in some cases, but has not been as thoroughly
9523 tested with Emacs as the default method. This method requires
9524 ImageMagick version 6.4.6 (approximately) or later.
9526 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9527 imagemagick_render_type
= 0;