Update copyright year to 2015
[emacs.git] / src / image.c
blob6240c64b201465e69ce6a003be10f7d257240c16
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include "sysstdio.h"
22 #include <unistd.h>
24 /* Include this before including <setjmp.h> to work around bugs with
25 older libpng; see Bug#17429. */
26 #if defined HAVE_PNG && !defined HAVE_NS
27 # include <png.h>
28 #endif
30 #include <setjmp.h>
31 #include <c-ctype.h>
33 #include "lisp.h"
34 #include "frame.h"
35 #include "window.h"
36 #include "buffer.h"
37 #include "dispextern.h"
38 #include "blockinput.h"
39 #include "systime.h"
40 #include <epaths.h>
41 #include "character.h"
42 #include "coding.h"
43 #include "termhooks.h"
44 #include "font.h"
46 #ifdef HAVE_SYS_STAT_H
47 #include <sys/stat.h>
48 #endif /* HAVE_SYS_STAT_H */
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
52 #endif /* HAVE_SYS_TYPES_H */
54 #ifdef HAVE_WINDOW_SYSTEM
55 #include TERM_HEADER
56 #endif /* HAVE_WINDOW_SYSTEM */
58 #ifdef HAVE_X_WINDOWS
59 #define COLOR_TABLE_SUPPORT 1
61 typedef struct x_bitmap_record Bitmap_Record;
62 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
63 #define NO_PIXMAP None
65 #define PIX_MASK_RETAIN 0
66 #define PIX_MASK_DRAW 1
67 #endif /* HAVE_X_WINDOWS */
69 #ifdef HAVE_NTGUI
71 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
72 #ifdef WINDOWSNT
73 # include "w32.h"
74 #endif
76 /* W32_TODO : Color tables on W32. */
77 #undef COLOR_TABLE_SUPPORT
79 typedef struct w32_bitmap_record Bitmap_Record;
80 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
81 #define NO_PIXMAP 0
83 #define PIX_MASK_RETAIN 0
84 #define PIX_MASK_DRAW 1
86 #define x_defined_color w32_defined_color
87 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
89 /* Versions of libpng, libgif, and libjpeg that we were compiled with,
90 or -1 if no PNG/GIF support was compiled in. This is tested by
91 w32-win.el to correctly set up the alist used to search for the
92 respective image libraries. */
93 Lisp_Object Qlibpng_version, Qlibgif_version, Qlibjpeg_version;
95 #endif /* HAVE_NTGUI */
97 #ifdef HAVE_NS
98 #undef COLOR_TABLE_SUPPORT
100 typedef struct ns_bitmap_record Bitmap_Record;
102 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
103 #define NO_PIXMAP 0
105 #define PIX_MASK_RETAIN 0
106 #define PIX_MASK_DRAW 1
108 #define x_defined_color(f, name, color_def, alloc) \
109 ns_defined_color (f, name, color_def, alloc, 0)
110 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
111 #endif /* HAVE_NS */
114 /* The symbol `postscript' identifying images of this type. */
116 static Lisp_Object Qpostscript;
118 static void x_disable_image (struct frame *, struct image *);
119 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
120 Lisp_Object);
122 static void init_color_table (void);
123 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
124 #ifdef COLOR_TABLE_SUPPORT
125 static void free_color_table (void);
126 static unsigned long *colors_in_color_table (int *n);
127 #endif
129 static Lisp_Object QCmax_width, QCmax_height;
131 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
132 id, which is just an int that this section returns. Bitmaps are
133 reference counted so they can be shared among frames.
135 Bitmap indices are guaranteed to be > 0, so a negative number can
136 be used to indicate no bitmap.
138 If you use x_create_bitmap_from_data, then you must keep track of
139 the bitmaps yourself. That is, creating a bitmap from the same
140 data more than once will not be caught. */
142 #ifdef HAVE_NS
143 /* Use with images created by ns_image_for_XPM. */
144 static unsigned long
145 XGetPixel (XImagePtr ximage, int x, int y)
147 return ns_get_pixel (ximage, x, y);
150 /* Use with images created by ns_image_for_XPM; alpha set to 1;
151 pixel is assumed to be in RGB form. */
152 static void
153 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
155 ns_put_pixel (ximage, x, y, pixel);
157 #endif /* HAVE_NS */
160 /* Functions to access the contents of a bitmap, given an id. */
162 #ifdef HAVE_X_WINDOWS
163 static int
164 x_bitmap_height (struct frame *f, ptrdiff_t id)
166 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
169 static int
170 x_bitmap_width (struct frame *f, ptrdiff_t id)
172 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
174 #endif
176 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
177 ptrdiff_t
178 x_bitmap_pixmap (struct frame *f, ptrdiff_t id)
180 /* HAVE_NTGUI needs the explicit cast here. */
181 return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
183 #endif
185 #ifdef HAVE_X_WINDOWS
187 x_bitmap_mask (struct frame *f, ptrdiff_t id)
189 return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
191 #endif
193 /* Allocate a new bitmap record. Returns index of new record. */
195 static ptrdiff_t
196 x_allocate_bitmap_record (struct frame *f)
198 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
199 ptrdiff_t i;
201 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
202 return ++dpyinfo->bitmaps_last;
204 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
205 if (dpyinfo->bitmaps[i].refcount == 0)
206 return i + 1;
208 dpyinfo->bitmaps =
209 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
210 10, -1, sizeof *dpyinfo->bitmaps);
211 return ++dpyinfo->bitmaps_last;
214 /* Add one reference to the reference count of the bitmap with id ID. */
216 void
217 x_reference_bitmap (struct frame *f, ptrdiff_t id)
219 ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
222 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
224 ptrdiff_t
225 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
227 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
228 ptrdiff_t id;
230 #ifdef HAVE_X_WINDOWS
231 Pixmap bitmap;
232 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
233 bits, width, height);
234 if (! bitmap)
235 return -1;
236 #endif /* HAVE_X_WINDOWS */
238 #ifdef HAVE_NTGUI
239 Pixmap bitmap;
240 bitmap = CreateBitmap (width, height,
241 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
242 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
243 bits);
244 if (! bitmap)
245 return -1;
246 #endif /* HAVE_NTGUI */
248 #ifdef HAVE_NS
249 void *bitmap = ns_image_from_XBM (bits, width, height);
250 if (!bitmap)
251 return -1;
252 #endif
254 id = x_allocate_bitmap_record (f);
256 #ifdef HAVE_NS
257 dpyinfo->bitmaps[id - 1].img = bitmap;
258 dpyinfo->bitmaps[id - 1].depth = 1;
259 #endif
261 dpyinfo->bitmaps[id - 1].file = NULL;
262 dpyinfo->bitmaps[id - 1].height = height;
263 dpyinfo->bitmaps[id - 1].width = width;
264 dpyinfo->bitmaps[id - 1].refcount = 1;
266 #ifdef HAVE_X_WINDOWS
267 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
268 dpyinfo->bitmaps[id - 1].have_mask = false;
269 dpyinfo->bitmaps[id - 1].depth = 1;
270 #endif /* HAVE_X_WINDOWS */
272 #ifdef HAVE_NTGUI
273 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
274 dpyinfo->bitmaps[id - 1].hinst = NULL;
275 dpyinfo->bitmaps[id - 1].depth = 1;
276 #endif /* HAVE_NTGUI */
278 return id;
281 /* Create bitmap from file FILE for frame F. */
283 ptrdiff_t
284 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
286 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
288 #ifdef HAVE_NTGUI
289 return -1; /* W32_TODO : bitmap support */
290 #endif /* HAVE_NTGUI */
292 #ifdef HAVE_NS
293 ptrdiff_t id;
294 void *bitmap = ns_image_from_file (file);
296 if (!bitmap)
297 return -1;
300 id = x_allocate_bitmap_record (f);
301 dpyinfo->bitmaps[id - 1].img = bitmap;
302 dpyinfo->bitmaps[id - 1].refcount = 1;
303 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
304 dpyinfo->bitmaps[id - 1].depth = 1;
305 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
306 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
307 return id;
308 #endif
310 #ifdef HAVE_X_WINDOWS
311 unsigned int width, height;
312 Pixmap bitmap;
313 int xhot, yhot, result;
314 ptrdiff_t id;
315 Lisp_Object found;
316 char *filename;
318 /* Look for an existing bitmap with the same name. */
319 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
321 if (dpyinfo->bitmaps[id].refcount
322 && dpyinfo->bitmaps[id].file
323 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
325 ++dpyinfo->bitmaps[id].refcount;
326 return id + 1;
330 /* Search bitmap-file-path for the file, if appropriate. */
331 if (openp (Vx_bitmap_file_path, file, Qnil, &found,
332 make_number (R_OK), false)
333 < 0)
334 return -1;
336 filename = SSDATA (found);
338 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
339 filename, &width, &height, &bitmap, &xhot, &yhot);
340 if (result != BitmapSuccess)
341 return -1;
343 id = x_allocate_bitmap_record (f);
344 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
345 dpyinfo->bitmaps[id - 1].have_mask = false;
346 dpyinfo->bitmaps[id - 1].refcount = 1;
347 dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
348 dpyinfo->bitmaps[id - 1].depth = 1;
349 dpyinfo->bitmaps[id - 1].height = height;
350 dpyinfo->bitmaps[id - 1].width = width;
352 return id;
353 #endif /* HAVE_X_WINDOWS */
356 /* Free bitmap B. */
358 static void
359 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
361 #ifdef HAVE_X_WINDOWS
362 XFreePixmap (dpyinfo->display, bm->pixmap);
363 if (bm->have_mask)
364 XFreePixmap (dpyinfo->display, bm->mask);
365 #endif /* HAVE_X_WINDOWS */
367 #ifdef HAVE_NTGUI
368 DeleteObject (bm->pixmap);
369 #endif /* HAVE_NTGUI */
371 #ifdef HAVE_NS
372 ns_release_object (bm->img);
373 #endif
375 if (bm->file)
377 xfree (bm->file);
378 bm->file = NULL;
382 /* Remove reference to bitmap with id number ID. */
384 void
385 x_destroy_bitmap (struct frame *f, ptrdiff_t id)
387 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
389 if (id > 0)
391 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
393 if (--bm->refcount == 0)
395 block_input ();
396 free_bitmap_record (dpyinfo, bm);
397 unblock_input ();
402 /* Free all the bitmaps for the display specified by DPYINFO. */
404 void
405 x_destroy_all_bitmaps (Display_Info *dpyinfo)
407 ptrdiff_t i;
408 Bitmap_Record *bm = dpyinfo->bitmaps;
410 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
411 if (bm->refcount > 0)
412 free_bitmap_record (dpyinfo, bm);
414 dpyinfo->bitmaps_last = 0;
417 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
418 XImagePtr *, Pixmap *);
419 static void x_destroy_x_image (XImagePtr ximg);
421 #ifdef HAVE_NTGUI
422 static XImagePtr_or_DC image_get_x_image_or_dc (struct frame *, struct image *,
423 bool, HGDIOBJ *);
424 static void image_unget_x_image_or_dc (struct image *, bool, XImagePtr_or_DC,
425 HGDIOBJ);
426 #else
427 static XImagePtr image_get_x_image (struct frame *, struct image *, bool);
428 static void image_unget_x_image (struct image *, bool, XImagePtr);
429 #define image_get_x_image_or_dc(f, img, mask_p, dummy) \
430 image_get_x_image (f, img, mask_p)
431 #define image_unget_x_image_or_dc(img, mask_p, ximg, dummy) \
432 image_unget_x_image (img, mask_p, ximg)
433 #endif
435 #ifdef HAVE_X_WINDOWS
437 static void image_sync_to_pixmaps (struct frame *, struct image *);
439 /* Useful functions defined in the section
440 `Image type independent image structures' below. */
442 static unsigned long four_corners_best (XImagePtr ximg,
443 int *corners,
444 unsigned long width,
445 unsigned long height);
448 /* Create a mask of a bitmap. Note is this not a perfect mask.
449 It's nicer with some borders in this context */
451 void
452 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
454 Pixmap pixmap, mask;
455 XImagePtr ximg, mask_img;
456 unsigned long width, height;
457 bool result;
458 unsigned long bg;
459 unsigned long x, y, xp, xm, yp, ym;
460 GC gc;
462 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
464 if (!(id > 0))
465 return;
467 pixmap = x_bitmap_pixmap (f, id);
468 width = x_bitmap_width (f, id);
469 height = x_bitmap_height (f, id);
471 block_input ();
472 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
473 ~0, ZPixmap);
475 if (!ximg)
477 unblock_input ();
478 return;
481 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
483 unblock_input ();
484 if (!result)
486 XDestroyImage (ximg);
487 return;
490 bg = four_corners_best (ximg, NULL, width, height);
492 for (y = 0; y < ximg->height; ++y)
494 for (x = 0; x < ximg->width; ++x)
496 xp = x != ximg->width - 1 ? x + 1 : 0;
497 xm = x != 0 ? x - 1 : ximg->width - 1;
498 yp = y != ximg->height - 1 ? y + 1 : 0;
499 ym = y != 0 ? y - 1 : ximg->height - 1;
500 if (XGetPixel (ximg, x, y) == bg
501 && XGetPixel (ximg, x, yp) == bg
502 && XGetPixel (ximg, x, ym) == bg
503 && XGetPixel (ximg, xp, y) == bg
504 && XGetPixel (ximg, xp, yp) == bg
505 && XGetPixel (ximg, xp, ym) == bg
506 && XGetPixel (ximg, xm, y) == bg
507 && XGetPixel (ximg, xm, yp) == bg
508 && XGetPixel (ximg, xm, ym) == bg)
509 XPutPixel (mask_img, x, y, 0);
510 else
511 XPutPixel (mask_img, x, y, 1);
515 eassert (input_blocked_p ());
516 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
517 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
518 width, height);
519 XFreeGC (FRAME_X_DISPLAY (f), gc);
521 dpyinfo->bitmaps[id - 1].have_mask = true;
522 dpyinfo->bitmaps[id - 1].mask = mask;
524 XDestroyImage (ximg);
525 x_destroy_x_image (mask_img);
528 #endif /* HAVE_X_WINDOWS */
531 /***********************************************************************
532 Image types
533 ***********************************************************************/
535 /* List of supported image types. Use define_image_type to add new
536 types. Use lookup_image_type to find a type for a given symbol. */
538 static struct image_type *image_types;
540 /* The symbol `xbm' which is used as the type symbol for XBM images. */
542 static Lisp_Object Qxbm;
544 /* Keywords. */
546 Lisp_Object QCascent, QCmargin, QCrelief;
547 Lisp_Object QCconversion;
548 static Lisp_Object QCheuristic_mask;
549 static Lisp_Object QCcolor_symbols;
550 static Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry;
551 static Lisp_Object QCcrop, QCrotation;
553 /* Other symbols. */
555 static Lisp_Object Qcount, Qextension_data, Qdelay;
556 static Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
558 /* Forward function prototypes. */
560 static struct image_type *lookup_image_type (Lisp_Object);
561 static void x_laplace (struct frame *, struct image *);
562 static void x_emboss (struct frame *, struct image *);
563 static void x_build_heuristic_mask (struct frame *, struct image *,
564 Lisp_Object);
565 #ifdef WINDOWSNT
566 #define CACHE_IMAGE_TYPE(type, status) \
567 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
568 #else
569 #define CACHE_IMAGE_TYPE(type, status)
570 #endif
572 #define ADD_IMAGE_TYPE(type) \
573 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
575 /* Define a new image type from TYPE. This adds a copy of TYPE to
576 image_types and caches the loading status of TYPE. */
578 static struct image_type *
579 define_image_type (struct image_type *type)
581 struct image_type *p = NULL;
582 Lisp_Object target_type = *type->type;
583 bool type_valid = 1;
585 block_input ();
587 for (p = image_types; p; p = p->next)
588 if (EQ (*p->type, target_type))
589 goto done;
591 if (type->init)
593 #if defined HAVE_NTGUI && defined WINDOWSNT
594 /* If we failed to load the library before, don't try again. */
595 Lisp_Object tested = Fassq (target_type, Vlibrary_cache);
596 if (CONSP (tested) && NILP (XCDR (tested)))
597 type_valid = 0;
598 else
599 #endif
601 type_valid = type->init ();
602 CACHE_IMAGE_TYPE (target_type, type_valid ? Qt : Qnil);
606 if (type_valid)
608 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
609 The initialized data segment is read-only. */
610 p = xmalloc (sizeof *p);
611 *p = *type;
612 p->next = image_types;
613 image_types = p;
616 done:
617 unblock_input ();
618 return p;
622 /* Value is true if OBJECT is a valid Lisp image specification. A
623 valid image specification is a list whose car is the symbol
624 `image', and whose rest is a property list. The property list must
625 contain a value for key `:type'. That value must be the name of a
626 supported image type. The rest of the property list depends on the
627 image type. */
629 bool
630 valid_image_p (Lisp_Object object)
632 bool valid_p = 0;
634 if (IMAGEP (object))
636 Lisp_Object tem;
638 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
639 if (EQ (XCAR (tem), QCtype))
641 tem = XCDR (tem);
642 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
644 struct image_type *type;
645 type = lookup_image_type (XCAR (tem));
646 if (type)
647 valid_p = type->valid_p (object);
650 break;
654 return valid_p;
658 /* Log error message with format string FORMAT and argument ARG.
659 Signaling an error, e.g. when an image cannot be loaded, is not a
660 good idea because this would interrupt redisplay, and the error
661 message display would lead to another redisplay. This function
662 therefore simply displays a message. */
664 static void
665 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
667 add_to_log (format, arg1, arg2);
672 /***********************************************************************
673 Image specifications
674 ***********************************************************************/
676 enum image_value_type
678 IMAGE_DONT_CHECK_VALUE_TYPE,
679 IMAGE_STRING_VALUE,
680 IMAGE_STRING_OR_NIL_VALUE,
681 IMAGE_SYMBOL_VALUE,
682 IMAGE_POSITIVE_INTEGER_VALUE,
683 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
684 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
685 IMAGE_ASCENT_VALUE,
686 IMAGE_INTEGER_VALUE,
687 IMAGE_FUNCTION_VALUE,
688 IMAGE_NUMBER_VALUE,
689 IMAGE_BOOL_VALUE
692 /* Structure used when parsing image specifications. */
694 struct image_keyword
696 /* Name of keyword. */
697 const char *name;
699 /* The type of value allowed. */
700 enum image_value_type type;
702 /* True means key must be present. */
703 bool mandatory_p;
705 /* Used to recognize duplicate keywords in a property list. */
706 int count;
708 /* The value that was found. */
709 Lisp_Object value;
713 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
714 has the format (image KEYWORD VALUE ...). One of the keyword/
715 value pairs must be `:type TYPE'. KEYWORDS is a vector of
716 image_keywords structures of size NKEYWORDS describing other
717 allowed keyword/value pairs. Value is true if SPEC is valid. */
719 static bool
720 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
721 int nkeywords, Lisp_Object type)
723 int i;
724 Lisp_Object plist;
726 if (!IMAGEP (spec))
727 return 0;
729 plist = XCDR (spec);
730 while (CONSP (plist))
732 Lisp_Object key, value;
734 /* First element of a pair must be a symbol. */
735 key = XCAR (plist);
736 plist = XCDR (plist);
737 if (!SYMBOLP (key))
738 return 0;
740 /* There must follow a value. */
741 if (!CONSP (plist))
742 return 0;
743 value = XCAR (plist);
744 plist = XCDR (plist);
746 /* Find key in KEYWORDS. Error if not found. */
747 for (i = 0; i < nkeywords; ++i)
748 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
749 break;
751 if (i == nkeywords)
752 continue;
754 /* Record that we recognized the keyword. If a keywords
755 was found more than once, it's an error. */
756 keywords[i].value = value;
757 if (keywords[i].count > 1)
758 return 0;
759 ++keywords[i].count;
761 /* Check type of value against allowed type. */
762 switch (keywords[i].type)
764 case IMAGE_STRING_VALUE:
765 if (!STRINGP (value))
766 return 0;
767 break;
769 case IMAGE_STRING_OR_NIL_VALUE:
770 if (!STRINGP (value) && !NILP (value))
771 return 0;
772 break;
774 case IMAGE_SYMBOL_VALUE:
775 if (!SYMBOLP (value))
776 return 0;
777 break;
779 case IMAGE_POSITIVE_INTEGER_VALUE:
780 if (! RANGED_INTEGERP (1, value, INT_MAX))
781 return 0;
782 break;
784 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
785 if (RANGED_INTEGERP (0, value, INT_MAX))
786 break;
787 if (CONSP (value)
788 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
789 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
790 break;
791 return 0;
793 case IMAGE_ASCENT_VALUE:
794 if (SYMBOLP (value) && EQ (value, Qcenter))
795 break;
796 else if (RANGED_INTEGERP (0, value, 100))
797 break;
798 return 0;
800 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
801 /* Unlike the other integer-related cases, this one does not
802 verify that VALUE fits in 'int'. This is because callers
803 want EMACS_INT. */
804 if (!INTEGERP (value) || XINT (value) < 0)
805 return 0;
806 break;
808 case IMAGE_DONT_CHECK_VALUE_TYPE:
809 break;
811 case IMAGE_FUNCTION_VALUE:
812 value = indirect_function (value);
813 if (!NILP (Ffunctionp (value)))
814 break;
815 return 0;
817 case IMAGE_NUMBER_VALUE:
818 if (!INTEGERP (value) && !FLOATP (value))
819 return 0;
820 break;
822 case IMAGE_INTEGER_VALUE:
823 if (! TYPE_RANGED_INTEGERP (int, value))
824 return 0;
825 break;
827 case IMAGE_BOOL_VALUE:
828 if (!NILP (value) && !EQ (value, Qt))
829 return 0;
830 break;
832 default:
833 emacs_abort ();
834 break;
837 if (EQ (key, QCtype) && !EQ (type, value))
838 return 0;
841 /* Check that all mandatory fields are present. */
842 for (i = 0; i < nkeywords; ++i)
843 if (keywords[i].mandatory_p && keywords[i].count == 0)
844 return 0;
846 return NILP (plist);
850 /* Return the value of KEY in image specification SPEC. Value is nil
851 if KEY is not present in SPEC. Set *FOUND depending on whether KEY
852 was found in SPEC. */
854 static Lisp_Object
855 image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
857 Lisp_Object tail;
859 eassert (valid_image_p (spec));
861 for (tail = XCDR (spec);
862 CONSP (tail) && CONSP (XCDR (tail));
863 tail = XCDR (XCDR (tail)))
865 if (EQ (XCAR (tail), key))
867 if (found)
868 *found = 1;
869 return XCAR (XCDR (tail));
873 if (found)
874 *found = 0;
875 return Qnil;
879 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
880 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
881 PIXELS non-nil means return the size in pixels, otherwise return the
882 size in canonical character units.
883 FRAME is the frame on which the image will be displayed. FRAME nil
884 or omitted means use the selected frame. */)
885 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
887 Lisp_Object size;
889 size = Qnil;
890 if (valid_image_p (spec))
892 struct frame *f = decode_window_system_frame (frame);
893 ptrdiff_t id = lookup_image (f, spec);
894 struct image *img = IMAGE_FROM_ID (f, id);
895 int width = img->width + 2 * img->hmargin;
896 int height = img->height + 2 * img->vmargin;
898 if (NILP (pixels))
899 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
900 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
901 else
902 size = Fcons (make_number (width), make_number (height));
904 else
905 error ("Invalid image specification");
907 return size;
911 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
912 doc: /* Return t if image SPEC has a mask bitmap.
913 FRAME is the frame on which the image will be displayed. FRAME nil
914 or omitted means use the selected frame. */)
915 (Lisp_Object spec, Lisp_Object frame)
917 Lisp_Object mask;
919 mask = Qnil;
920 if (valid_image_p (spec))
922 struct frame *f = decode_window_system_frame (frame);
923 ptrdiff_t id = lookup_image (f, spec);
924 struct image *img = IMAGE_FROM_ID (f, id);
925 if (img->mask)
926 mask = Qt;
928 else
929 error ("Invalid image specification");
931 return mask;
934 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
935 doc: /* Return metadata for image SPEC.
936 FRAME is the frame on which the image will be displayed. FRAME nil
937 or omitted means use the selected frame. */)
938 (Lisp_Object spec, Lisp_Object frame)
940 Lisp_Object ext;
942 ext = Qnil;
943 if (valid_image_p (spec))
945 struct frame *f = decode_window_system_frame (frame);
946 ptrdiff_t id = lookup_image (f, spec);
947 struct image *img = IMAGE_FROM_ID (f, id);
948 ext = img->lisp_data;
951 return ext;
955 /***********************************************************************
956 Image type independent image structures
957 ***********************************************************************/
959 #define MAX_IMAGE_SIZE 10.0
960 /* Allocate and return a new image structure for image specification
961 SPEC. SPEC has a hash value of HASH. */
963 static struct image *
964 make_image (Lisp_Object spec, EMACS_UINT hash)
966 struct image *img = xzalloc (sizeof *img);
967 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
969 eassert (valid_image_p (spec));
970 img->dependencies = NILP (file) ? Qnil : list1 (file);
971 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
972 eassert (img->type != NULL);
973 img->spec = spec;
974 img->lisp_data = Qnil;
975 img->ascent = DEFAULT_IMAGE_ASCENT;
976 img->hash = hash;
977 img->corners[BOT_CORNER] = -1; /* Full image */
978 return img;
982 /* Free image IMG which was used on frame F, including its resources. */
984 static void
985 free_image (struct frame *f, struct image *img)
987 if (img)
989 struct image_cache *c = FRAME_IMAGE_CACHE (f);
991 /* Remove IMG from the hash table of its cache. */
992 if (img->prev)
993 img->prev->next = img->next;
994 else
995 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
997 if (img->next)
998 img->next->prev = img->prev;
1000 c->images[img->id] = NULL;
1002 /* Windows NT redefines 'free', but in this file, we need to
1003 avoid the redefinition. */
1004 #ifdef WINDOWSNT
1005 #undef free
1006 #endif
1007 /* Free resources, then free IMG. */
1008 img->type->free (f, img);
1009 xfree (img);
1013 /* Return true if the given widths and heights are valid for display. */
1015 static bool
1016 check_image_size (struct frame *f, int width, int height)
1018 int w, h;
1020 if (width <= 0 || height <= 0)
1021 return 0;
1023 if (INTEGERP (Vmax_image_size))
1024 return (width <= XINT (Vmax_image_size)
1025 && height <= XINT (Vmax_image_size));
1026 else if (FLOATP (Vmax_image_size))
1028 if (f != NULL)
1030 w = FRAME_PIXEL_WIDTH (f);
1031 h = FRAME_PIXEL_HEIGHT (f);
1033 else
1034 w = h = 1024; /* Arbitrary size for unknown frame. */
1035 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1036 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1038 else
1039 return 1;
1042 /* Prepare image IMG for display on frame F. Must be called before
1043 drawing an image. */
1045 void
1046 prepare_image_for_display (struct frame *f, struct image *img)
1048 /* We're about to display IMG, so set its timestamp to `now'. */
1049 img->timestamp = current_timespec ();
1051 /* If IMG doesn't have a pixmap yet, load it now, using the image
1052 type dependent loader function. */
1053 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1054 img->load_failed_p = ! img->type->load (f, img);
1056 #ifdef HAVE_X_WINDOWS
1057 if (!img->load_failed_p)
1059 block_input ();
1060 image_sync_to_pixmaps (f, img);
1061 unblock_input ();
1063 #endif
1067 /* Value is the number of pixels for the ascent of image IMG when
1068 drawn in face FACE. */
1071 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1073 int height;
1074 int ascent;
1076 if (slice->height == img->height)
1077 height = img->height + img->vmargin;
1078 else if (slice->y == 0)
1079 height = slice->height + img->vmargin;
1080 else
1081 height = slice->height;
1083 if (img->ascent == CENTERED_IMAGE_ASCENT)
1085 if (face->font)
1087 #ifdef HAVE_NTGUI
1088 /* W32 specific version. Why?. ++kfs */
1089 ascent = height / 2 - (FONT_DESCENT (face->font)
1090 - FONT_BASE (face->font)) / 2;
1091 #else
1092 /* This expression is arranged so that if the image can't be
1093 exactly centered, it will be moved slightly up. This is
1094 because a typical font is `top-heavy' (due to the presence
1095 uppercase letters), so the image placement should err towards
1096 being top-heavy too. It also just generally looks better. */
1097 ascent = (height + FONT_BASE (face->font)
1098 - FONT_DESCENT (face->font) + 1) / 2;
1099 #endif /* HAVE_NTGUI */
1101 else
1102 ascent = height / 2;
1104 else
1105 ascent = height * (img->ascent / 100.0);
1107 return ascent;
1111 /* Image background colors. */
1113 /* Find the "best" corner color of a bitmap.
1114 On W32, XIMG is assumed to a device context with the bitmap selected. */
1116 static RGB_PIXEL_COLOR
1117 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1118 unsigned long width, unsigned long height)
1120 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1121 int i, best_count;
1123 if (corners && corners[BOT_CORNER] >= 0)
1125 /* Get the colors at the corner_pixels of ximg. */
1126 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1127 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1128 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1129 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1131 else
1133 /* Get the colors at the corner_pixels of ximg. */
1134 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1135 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1136 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1137 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1139 /* Choose the most frequently found color as background. */
1140 for (i = best_count = 0; i < 4; ++i)
1142 int j, n;
1144 for (j = n = 0; j < 4; ++j)
1145 if (corner_pixels[i] == corner_pixels[j])
1146 ++n;
1148 if (n > best_count)
1149 best = corner_pixels[i], best_count = n;
1152 return best;
1155 /* Portability macros */
1157 #ifdef HAVE_NTGUI
1159 #define Free_Pixmap(display, pixmap) \
1160 DeleteObject (pixmap)
1162 #elif defined (HAVE_NS)
1164 #define Free_Pixmap(display, pixmap) \
1165 ns_release_object (pixmap)
1167 #else
1169 #define Free_Pixmap(display, pixmap) \
1170 XFreePixmap (display, pixmap)
1172 #endif /* !HAVE_NTGUI && !HAVE_NS */
1175 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1176 it is guessed heuristically. If non-zero, XIMG is an existing
1177 XImage object (or device context with the image selected on W32) to
1178 use for the heuristic. */
1180 RGB_PIXEL_COLOR
1181 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1183 if (! img->background_valid)
1184 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1186 bool free_ximg = !ximg;
1187 #ifdef HAVE_NTGUI
1188 HGDIOBJ prev;
1189 #endif /* HAVE_NTGUI */
1191 if (free_ximg)
1192 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
1194 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1196 if (free_ximg)
1197 image_unget_x_image_or_dc (img, 0, ximg, prev);
1199 img->background_valid = 1;
1202 return img->background;
1205 /* Return the `background_transparent' field of IMG. If IMG doesn't
1206 have one yet, it is guessed heuristically. If non-zero, MASK is an
1207 existing XImage object to use for the heuristic. */
1210 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1212 if (! img->background_transparent_valid)
1213 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1215 if (img->mask)
1217 bool free_mask = !mask;
1218 #ifdef HAVE_NTGUI
1219 HGDIOBJ prev;
1220 #endif /* HAVE_NTGUI */
1222 if (free_mask)
1223 mask = image_get_x_image_or_dc (f, img, 1, &prev);
1225 img->background_transparent
1226 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1228 if (free_mask)
1229 image_unget_x_image_or_dc (img, 1, mask, prev);
1231 else
1232 img->background_transparent = 0;
1234 img->background_transparent_valid = 1;
1237 return img->background_transparent;
1240 #if defined (HAVE_PNG) || defined (HAVE_NS) \
1241 || defined (HAVE_IMAGEMAGICK) || defined (HAVE_RSVG)
1243 /* Store F's background color into *BGCOLOR. */
1244 static void
1245 x_query_frame_background_color (struct frame *f, XColor *bgcolor)
1247 #ifndef HAVE_NS
1248 bgcolor->pixel = FRAME_BACKGROUND_PIXEL (f);
1249 x_query_color (f, bgcolor);
1250 #else
1251 ns_query_color (FRAME_BACKGROUND_COLOR (f), bgcolor, 1);
1252 #endif
1255 #endif /* HAVE_PNG || HAVE_NS || HAVE_IMAGEMAGICK || HAVE_RSVG */
1257 /***********************************************************************
1258 Helper functions for X image types
1259 ***********************************************************************/
1261 /* Clear X resources of image IMG on frame F according to FLAGS.
1262 FLAGS is bitwise-or of the following masks:
1263 CLEAR_IMAGE_PIXMAP free the pixmap if any.
1264 CLEAR_IMAGE_MASK means clear the mask pixmap if any.
1265 CLEAR_IMAGE_COLORS means free colors allocated for the image, if
1266 any. */
1268 #define CLEAR_IMAGE_PIXMAP (1 << 0)
1269 #define CLEAR_IMAGE_MASK (1 << 1)
1270 #define CLEAR_IMAGE_COLORS (1 << 2)
1272 static void
1273 x_clear_image_1 (struct frame *f, struct image *img, int flags)
1275 if (flags & CLEAR_IMAGE_PIXMAP)
1277 if (img->pixmap)
1279 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1280 img->pixmap = NO_PIXMAP;
1281 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1282 img->background_valid = 0;
1284 #ifdef HAVE_X_WINDOWS
1285 if (img->ximg)
1287 x_destroy_x_image (img->ximg);
1288 img->ximg = NULL;
1289 img->background_valid = 0;
1291 #endif
1294 if (flags & CLEAR_IMAGE_MASK)
1296 if (img->mask)
1298 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1299 img->mask = NO_PIXMAP;
1300 img->background_transparent_valid = 0;
1302 #ifdef HAVE_X_WINDOWS
1303 if (img->mask_img)
1305 x_destroy_x_image (img->mask_img);
1306 img->mask_img = NULL;
1307 img->background_transparent_valid = 0;
1309 #endif
1312 if ((flags & CLEAR_IMAGE_COLORS) && img->ncolors)
1314 /* W32_TODO: color table support. */
1315 #ifdef HAVE_X_WINDOWS
1316 x_free_colors (f, img->colors, img->ncolors);
1317 #endif /* HAVE_X_WINDOWS */
1318 xfree (img->colors);
1319 img->colors = NULL;
1320 img->ncolors = 0;
1325 /* Free X resources of image IMG which is used on frame F. */
1327 static void
1328 x_clear_image (struct frame *f, struct image *img)
1330 block_input ();
1331 x_clear_image_1 (f, img,
1332 CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_MASK | CLEAR_IMAGE_COLORS);
1333 unblock_input ();
1337 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1338 cannot be allocated, use DFLT. Add a newly allocated color to
1339 IMG->colors, so that it can be freed again. Value is the pixel
1340 color. */
1342 static unsigned long
1343 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1344 unsigned long dflt)
1346 XColor color;
1347 unsigned long result;
1349 eassert (STRINGP (color_name));
1351 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1352 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1353 INT_MAX))
1355 /* This isn't called frequently so we get away with simply
1356 reallocating the color vector to the needed size, here. */
1357 ptrdiff_t ncolors = img->ncolors + 1;
1358 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1359 img->colors[ncolors - 1] = color.pixel;
1360 img->ncolors = ncolors;
1361 result = color.pixel;
1363 else
1364 result = dflt;
1366 return result;
1371 /***********************************************************************
1372 Image Cache
1373 ***********************************************************************/
1375 static void cache_image (struct frame *f, struct image *img);
1377 /* Return a new, initialized image cache that is allocated from the
1378 heap. Call free_image_cache to free an image cache. */
1380 struct image_cache *
1381 make_image_cache (void)
1383 struct image_cache *c = xmalloc (sizeof *c);
1385 c->size = 50;
1386 c->used = c->refcount = 0;
1387 c->images = xmalloc (c->size * sizeof *c->images);
1388 c->buckets = xzalloc (IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets);
1389 return c;
1393 /* Find an image matching SPEC in the cache, and return it. If no
1394 image is found, return NULL. */
1395 static struct image *
1396 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1398 struct image *img;
1399 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1400 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1402 if (!c) return NULL;
1404 /* If the image spec does not specify a background color, the cached
1405 image must have the same background color as the current frame.
1406 The foreground color must also match, for the sake of monochrome
1407 images.
1409 In fact, we could ignore the foreground color matching condition
1410 for color images, or if the image spec specifies :foreground;
1411 similarly we could ignore the background color matching condition
1412 for formats that don't use transparency (such as jpeg), or if the
1413 image spec specifies :background. However, the extra memory
1414 usage is probably negligible in practice, so we don't bother. */
1416 for (img = c->buckets[i]; img; img = img->next)
1417 if (img->hash == hash
1418 && !NILP (Fequal (img->spec, spec))
1419 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1420 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1421 break;
1422 return img;
1426 /* Search frame F for an image with spec SPEC, and free it. */
1428 static void
1429 uncache_image (struct frame *f, Lisp_Object spec)
1431 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1432 if (img)
1434 free_image (f, img);
1435 /* As display glyphs may still be referring to the image ID, we
1436 must garbage the frame (Bug#6426). */
1437 SET_FRAME_GARBAGED (f);
1442 /* Free image cache of frame F. Be aware that X frames share images
1443 caches. */
1445 void
1446 free_image_cache (struct frame *f)
1448 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1449 if (c)
1451 ptrdiff_t i;
1453 /* Cache should not be referenced by any frame when freed. */
1454 eassert (c->refcount == 0);
1456 for (i = 0; i < c->used; ++i)
1457 free_image (f, c->images[i]);
1458 xfree (c->images);
1459 xfree (c->buckets);
1460 xfree (c);
1461 FRAME_IMAGE_CACHE (f) = NULL;
1466 /* Clear image cache of frame F. FILTER=t means free all images.
1467 FILTER=nil means clear only images that haven't been
1468 displayed for some time.
1469 Else, only free the images which have FILTER in their `dependencies'.
1470 Should be called from time to time to reduce the number of loaded images.
1471 If image-cache-eviction-delay is non-nil, this frees images in the cache
1472 which weren't displayed for at least that many seconds. */
1474 static void
1475 clear_image_cache (struct frame *f, Lisp_Object filter)
1477 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1479 if (c)
1481 ptrdiff_t i, nfreed = 0;
1483 /* Block input so that we won't be interrupted by a SIGIO
1484 while being in an inconsistent state. */
1485 block_input ();
1487 if (!NILP (filter))
1489 /* Filter image cache. */
1490 for (i = 0; i < c->used; ++i)
1492 struct image *img = c->images[i];
1493 if (img && (EQ (Qt, filter)
1494 || !NILP (Fmember (filter, img->dependencies))))
1496 free_image (f, img);
1497 ++nfreed;
1501 else if (INTEGERP (Vimage_cache_eviction_delay))
1503 /* Free cache based on timestamp. */
1504 struct timespec old, t;
1505 double delay;
1506 ptrdiff_t nimages = 0;
1508 for (i = 0; i < c->used; ++i)
1509 if (c->images[i])
1510 nimages++;
1512 /* If the number of cached images has grown unusually large,
1513 decrease the cache eviction delay (Bug#6230). */
1514 delay = XINT (Vimage_cache_eviction_delay);
1515 if (nimages > 40)
1516 delay = 1600 * delay / nimages / nimages;
1517 delay = max (delay, 1);
1519 t = current_timespec ();
1520 old = timespec_sub (t, dtotimespec (delay));
1522 for (i = 0; i < c->used; ++i)
1524 struct image *img = c->images[i];
1525 if (img && timespec_cmp (img->timestamp, old) < 0)
1527 free_image (f, img);
1528 ++nfreed;
1533 /* We may be clearing the image cache because, for example,
1534 Emacs was iconified for a longer period of time. In that
1535 case, current matrices may still contain references to
1536 images freed above. So, clear these matrices. */
1537 if (nfreed)
1539 Lisp_Object tail, frame;
1541 FOR_EACH_FRAME (tail, frame)
1543 struct frame *fr = XFRAME (frame);
1544 if (FRAME_IMAGE_CACHE (fr) == c)
1545 clear_current_matrices (fr);
1548 windows_or_buffers_changed = 19;
1551 unblock_input ();
1555 void
1556 clear_image_caches (Lisp_Object filter)
1558 /* FIXME: We want to do
1559 * struct terminal *t;
1560 * for (t = terminal_list; t; t = t->next_terminal)
1561 * clear_image_cache (t, filter); */
1562 Lisp_Object tail, frame;
1563 FOR_EACH_FRAME (tail, frame)
1564 if (FRAME_WINDOW_P (XFRAME (frame)))
1565 clear_image_cache (XFRAME (frame), filter);
1568 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1569 0, 1, 0,
1570 doc: /* Clear the image cache.
1571 FILTER nil or a frame means clear all images in the selected frame.
1572 FILTER t means clear the image caches of all frames.
1573 Anything else, means only clear those images which refer to FILTER,
1574 which is then usually a filename. */)
1575 (Lisp_Object filter)
1577 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1578 clear_image_caches (filter);
1579 else
1580 clear_image_cache (decode_window_system_frame (filter), Qt);
1582 return Qnil;
1586 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1587 1, 2, 0,
1588 doc: /* Flush the image with specification SPEC on frame FRAME.
1589 This removes the image from the Emacs image cache. If SPEC specifies
1590 an image file, the next redisplay of this image will read from the
1591 current contents of that file.
1593 FRAME nil or omitted means use the selected frame.
1594 FRAME t means refresh the image on all frames. */)
1595 (Lisp_Object spec, Lisp_Object frame)
1597 if (!valid_image_p (spec))
1598 error ("Invalid image specification");
1600 if (EQ (frame, Qt))
1602 Lisp_Object tail;
1603 FOR_EACH_FRAME (tail, frame)
1605 struct frame *f = XFRAME (frame);
1606 if (FRAME_WINDOW_P (f))
1607 uncache_image (f, spec);
1610 else
1611 uncache_image (decode_window_system_frame (frame), spec);
1613 return Qnil;
1617 /* Compute masks and transform image IMG on frame F, as specified
1618 by the image's specification, */
1620 static void
1621 postprocess_image (struct frame *f, struct image *img)
1623 /* Manipulation of the image's mask. */
1624 if (img->pixmap)
1626 Lisp_Object conversion, spec;
1627 Lisp_Object mask;
1629 spec = img->spec;
1631 /* `:heuristic-mask t'
1632 `:mask heuristic'
1633 means build a mask heuristically.
1634 `:heuristic-mask (R G B)'
1635 `:mask (heuristic (R G B))'
1636 means build a mask from color (R G B) in the
1637 image.
1638 `:mask nil'
1639 means remove a mask, if any. */
1641 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1642 if (!NILP (mask))
1643 x_build_heuristic_mask (f, img, mask);
1644 else
1646 bool found_p;
1648 mask = image_spec_value (spec, QCmask, &found_p);
1650 if (EQ (mask, Qheuristic))
1651 x_build_heuristic_mask (f, img, Qt);
1652 else if (CONSP (mask)
1653 && EQ (XCAR (mask), Qheuristic))
1655 if (CONSP (XCDR (mask)))
1656 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1657 else
1658 x_build_heuristic_mask (f, img, XCDR (mask));
1660 else if (NILP (mask) && found_p && img->mask)
1661 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
1665 /* Should we apply an image transformation algorithm? */
1666 conversion = image_spec_value (spec, QCconversion, NULL);
1667 if (EQ (conversion, Qdisabled))
1668 x_disable_image (f, img);
1669 else if (EQ (conversion, Qlaplace))
1670 x_laplace (f, img);
1671 else if (EQ (conversion, Qemboss))
1672 x_emboss (f, img);
1673 else if (CONSP (conversion)
1674 && EQ (XCAR (conversion), Qedge_detection))
1676 Lisp_Object tem;
1677 tem = XCDR (conversion);
1678 if (CONSP (tem))
1679 x_edge_detection (f, img,
1680 Fplist_get (tem, QCmatrix),
1681 Fplist_get (tem, QCcolor_adjustment));
1687 /* Return the id of image with Lisp specification SPEC on frame F.
1688 SPEC must be a valid Lisp image specification (see valid_image_p). */
1690 ptrdiff_t
1691 lookup_image (struct frame *f, Lisp_Object spec)
1693 struct image *img;
1694 EMACS_UINT hash;
1696 /* F must be a window-system frame, and SPEC must be a valid image
1697 specification. */
1698 eassert (FRAME_WINDOW_P (f));
1699 eassert (valid_image_p (spec));
1701 /* Look up SPEC in the hash table of the image cache. */
1702 hash = sxhash (spec, 0);
1703 img = search_image_cache (f, spec, hash);
1704 if (img && img->load_failed_p)
1706 free_image (f, img);
1707 img = NULL;
1710 /* If not found, create a new image and cache it. */
1711 if (img == NULL)
1713 block_input ();
1714 img = make_image (spec, hash);
1715 cache_image (f, img);
1716 img->load_failed_p = ! img->type->load (f, img);
1717 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1718 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1720 /* If we can't load the image, and we don't have a width and
1721 height, use some arbitrary width and height so that we can
1722 draw a rectangle for it. */
1723 if (img->load_failed_p)
1725 Lisp_Object value;
1727 value = image_spec_value (spec, QCwidth, NULL);
1728 img->width = (INTEGERP (value)
1729 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1730 value = image_spec_value (spec, QCheight, NULL);
1731 img->height = (INTEGERP (value)
1732 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1734 else
1736 /* Handle image type independent image attributes
1737 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1738 `:background COLOR'. */
1739 Lisp_Object ascent, margin, relief, bg;
1740 int relief_bound;
1742 ascent = image_spec_value (spec, QCascent, NULL);
1743 if (INTEGERP (ascent))
1744 img->ascent = XFASTINT (ascent);
1745 else if (EQ (ascent, Qcenter))
1746 img->ascent = CENTERED_IMAGE_ASCENT;
1748 margin = image_spec_value (spec, QCmargin, NULL);
1749 if (INTEGERP (margin))
1750 img->vmargin = img->hmargin = XFASTINT (margin);
1751 else if (CONSP (margin))
1753 img->hmargin = XFASTINT (XCAR (margin));
1754 img->vmargin = XFASTINT (XCDR (margin));
1757 relief = image_spec_value (spec, QCrelief, NULL);
1758 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1759 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1761 img->relief = XINT (relief);
1762 img->hmargin += eabs (img->relief);
1763 img->vmargin += eabs (img->relief);
1766 if (! img->background_valid)
1768 bg = image_spec_value (img->spec, QCbackground, NULL);
1769 if (!NILP (bg))
1771 img->background
1772 = x_alloc_image_color (f, img, bg,
1773 FRAME_BACKGROUND_PIXEL (f));
1774 img->background_valid = 1;
1778 /* Do image transformations and compute masks, unless we
1779 don't have the image yet. */
1780 if (!EQ (*img->type->type, Qpostscript))
1781 postprocess_image (f, img);
1784 unblock_input ();
1787 /* We're using IMG, so set its timestamp to `now'. */
1788 img->timestamp = current_timespec ();
1790 /* Value is the image id. */
1791 return img->id;
1795 /* Cache image IMG in the image cache of frame F. */
1797 static void
1798 cache_image (struct frame *f, struct image *img)
1800 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1801 ptrdiff_t i;
1803 /* Find a free slot in c->images. */
1804 for (i = 0; i < c->used; ++i)
1805 if (c->images[i] == NULL)
1806 break;
1808 /* If no free slot found, maybe enlarge c->images. */
1809 if (i == c->used && c->used == c->size)
1810 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1812 /* Add IMG to c->images, and assign IMG an id. */
1813 c->images[i] = img;
1814 img->id = i;
1815 if (i == c->used)
1816 ++c->used;
1818 /* Add IMG to the cache's hash table. */
1819 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1820 img->next = c->buckets[i];
1821 if (img->next)
1822 img->next->prev = img;
1823 img->prev = NULL;
1824 c->buckets[i] = img;
1828 /* Call FN on every image in the image cache of frame F. Used to mark
1829 Lisp Objects in the image cache. */
1831 /* Mark Lisp objects in image IMG. */
1833 static void
1834 mark_image (struct image *img)
1836 mark_object (img->spec);
1837 mark_object (img->dependencies);
1839 if (!NILP (img->lisp_data))
1840 mark_object (img->lisp_data);
1844 void
1845 mark_image_cache (struct image_cache *c)
1847 if (c)
1849 ptrdiff_t i;
1850 for (i = 0; i < c->used; ++i)
1851 if (c->images[i])
1852 mark_image (c->images[i]);
1858 /***********************************************************************
1859 X / NS / W32 support code
1860 ***********************************************************************/
1862 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1863 windowing system.
1864 WIDTH and HEIGHT must both be positive.
1865 If XIMG is null, assume it is a bitmap. */
1866 static bool
1867 x_check_image_size (XImagePtr ximg, int width, int height)
1869 #ifdef HAVE_X_WINDOWS
1870 /* Respect Xlib's limits: it cannot deal with images that have more
1871 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1872 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1873 enum
1875 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1876 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1879 int bitmap_pad, depth, bytes_per_line;
1880 if (ximg)
1882 bitmap_pad = ximg->bitmap_pad;
1883 depth = ximg->depth;
1884 bytes_per_line = ximg->bytes_per_line;
1886 else
1888 bitmap_pad = 8;
1889 depth = 1;
1890 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1892 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1893 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1894 #else
1895 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1896 For now, assume that every image size is allowed on these systems. */
1897 return 1;
1898 #endif
1901 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1902 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1903 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1904 via xmalloc. Print error messages via image_error if an error
1905 occurs. Value is true if successful.
1907 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1908 should indicate the bit depth of the image. */
1910 static bool
1911 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1912 XImagePtr *ximg, Pixmap *pixmap)
1914 #ifdef HAVE_X_WINDOWS
1915 Display *display = FRAME_X_DISPLAY (f);
1916 Window window = FRAME_X_WINDOW (f);
1917 Screen *screen = FRAME_X_SCREEN (f);
1919 eassert (input_blocked_p ());
1921 if (depth <= 0)
1922 depth = DefaultDepthOfScreen (screen);
1923 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1924 depth, ZPixmap, 0, NULL, width, height,
1925 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1926 if (*ximg == NULL)
1928 image_error ("Unable to allocate X image", Qnil, Qnil);
1929 return 0;
1932 if (! x_check_image_size (*ximg, width, height))
1934 x_destroy_x_image (*ximg);
1935 *ximg = NULL;
1936 image_error ("Image too large (%dx%d)",
1937 make_number (width), make_number (height));
1938 return 0;
1941 /* Allocate image raster. */
1942 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1944 /* Allocate a pixmap of the same size. */
1945 *pixmap = XCreatePixmap (display, window, width, height, depth);
1946 if (*pixmap == NO_PIXMAP)
1948 x_destroy_x_image (*ximg);
1949 *ximg = NULL;
1950 image_error ("Unable to create X pixmap", Qnil, Qnil);
1951 return 0;
1954 return 1;
1955 #endif /* HAVE_X_WINDOWS */
1957 #ifdef HAVE_NTGUI
1959 BITMAPINFOHEADER *header;
1960 HDC hdc;
1961 int scanline_width_bits;
1962 int remainder;
1963 int palette_colors = 0;
1965 if (depth == 0)
1966 depth = 24;
1968 if (depth != 1 && depth != 4 && depth != 8
1969 && depth != 16 && depth != 24 && depth != 32)
1971 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1972 return 0;
1975 scanline_width_bits = width * depth;
1976 remainder = scanline_width_bits % 32;
1978 if (remainder)
1979 scanline_width_bits += 32 - remainder;
1981 /* Bitmaps with a depth less than 16 need a palette. */
1982 /* BITMAPINFO structure already contains the first RGBQUAD. */
1983 if (depth < 16)
1984 palette_colors = 1 << (depth - 1);
1986 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1988 header = &(*ximg)->info.bmiHeader;
1989 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
1990 header->biSize = sizeof (*header);
1991 header->biWidth = width;
1992 header->biHeight = -height; /* negative indicates a top-down bitmap. */
1993 header->biPlanes = 1;
1994 header->biBitCount = depth;
1995 header->biCompression = BI_RGB;
1996 header->biClrUsed = palette_colors;
1998 /* TODO: fill in palette. */
1999 if (depth == 1)
2001 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2002 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2003 (*ximg)->info.bmiColors[0].rgbRed = 0;
2004 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2005 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2006 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2007 (*ximg)->info.bmiColors[1].rgbRed = 255;
2008 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2011 hdc = get_frame_dc (f);
2013 /* Create a DIBSection and raster array for the bitmap,
2014 and store its handle in *pixmap. */
2015 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2016 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2017 /* casting avoids a GCC warning */
2018 (void **)&((*ximg)->data), NULL, 0);
2020 /* Realize display palette and garbage all frames. */
2021 release_frame_dc (f, hdc);
2023 if (*pixmap == NULL)
2025 DWORD err = GetLastError ();
2026 Lisp_Object errcode;
2027 /* All system errors are < 10000, so the following is safe. */
2028 XSETINT (errcode, err);
2029 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2030 x_destroy_x_image (*ximg);
2031 *ximg = NULL;
2032 return 0;
2035 return 1;
2037 #endif /* HAVE_NTGUI */
2039 #ifdef HAVE_NS
2040 *pixmap = ns_image_for_XPM (width, height, depth);
2041 if (*pixmap == 0)
2043 *ximg = NULL;
2044 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2045 return 0;
2047 *ximg = *pixmap;
2048 return 1;
2049 #endif
2053 /* Destroy XImage XIMG. Free XIMG->data. */
2055 static void
2056 x_destroy_x_image (XImagePtr ximg)
2058 eassert (input_blocked_p ());
2059 if (ximg)
2061 #ifdef HAVE_X_WINDOWS
2062 xfree (ximg->data);
2063 ximg->data = NULL;
2064 XDestroyImage (ximg);
2065 #endif /* HAVE_X_WINDOWS */
2066 #ifdef HAVE_NTGUI
2067 /* Data will be freed by DestroyObject. */
2068 ximg->data = NULL;
2069 xfree (ximg);
2070 #endif /* HAVE_NTGUI */
2071 #ifdef HAVE_NS
2072 ns_release_object (ximg);
2073 #endif /* HAVE_NS */
2078 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2079 are width and height of both the image and pixmap. */
2081 static void
2082 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2084 #ifdef HAVE_X_WINDOWS
2085 GC gc;
2087 eassert (input_blocked_p ());
2088 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2089 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2090 XFreeGC (FRAME_X_DISPLAY (f), gc);
2091 #endif /* HAVE_X_WINDOWS */
2093 #ifdef HAVE_NTGUI
2094 #if 0 /* I don't think this is necessary looking at where it is used. */
2095 HDC hdc = get_frame_dc (f);
2096 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2097 release_frame_dc (f, hdc);
2098 #endif
2099 #endif /* HAVE_NTGUI */
2101 #ifdef HAVE_NS
2102 eassert (ximg == pixmap);
2103 ns_retain_object (ximg);
2104 #endif
2107 /* Thin wrapper for x_create_x_image_and_pixmap, so that it matches
2108 with image_put_x_image. */
2110 static bool
2111 image_create_x_image_and_pixmap (struct frame *f, struct image *img,
2112 int width, int height, int depth,
2113 XImagePtr *ximg, bool mask_p)
2115 eassert ((!mask_p ? img->pixmap : img->mask) == NO_PIXMAP);
2117 return x_create_x_image_and_pixmap (f, width, height, depth, ximg,
2118 !mask_p ? &img->pixmap : &img->mask);
2121 /* Put X image XIMG into image IMG on frame F, as a mask if and only
2122 if MASK_P. On X, this simply records XIMG on a member of IMG, so
2123 it can be put into the pixmap afterwards via image_sync_to_pixmaps.
2124 On the other platforms, it puts XIMG into the pixmap, then frees
2125 the X image and its buffer. */
2127 static void
2128 image_put_x_image (struct frame *f, struct image *img, XImagePtr ximg,
2129 bool mask_p)
2131 #ifdef HAVE_X_WINDOWS
2132 if (!mask_p)
2134 eassert (img->ximg == NULL);
2135 img->ximg = ximg;
2137 else
2139 eassert (img->mask_img == NULL);
2140 img->mask_img = ximg;
2142 #else
2143 x_put_x_image (f, ximg, !mask_p ? img->pixmap : img->mask,
2144 img->width, img->height);
2145 x_destroy_x_image (ximg);
2146 #endif
2149 #ifdef HAVE_X_WINDOWS
2150 /* Put the X images recorded in IMG on frame F into pixmaps, then free
2151 the X images and their buffers. */
2153 static void
2154 image_sync_to_pixmaps (struct frame *f, struct image *img)
2156 if (img->ximg)
2158 x_put_x_image (f, img->ximg, img->pixmap, img->width, img->height);
2159 x_destroy_x_image (img->ximg);
2160 img->ximg = NULL;
2162 if (img->mask_img)
2164 x_put_x_image (f, img->mask_img, img->mask, img->width, img->height);
2165 x_destroy_x_image (img->mask_img);
2166 img->mask_img = NULL;
2169 #endif
2171 #ifdef HAVE_NTGUI
2172 /* Create a memory device context for IMG on frame F. It stores the
2173 currently selected GDI object into *PREV for future restoration by
2174 image_unget_x_image_or_dc. */
2176 static XImagePtr_or_DC
2177 image_get_x_image_or_dc (struct frame *f, struct image *img, bool mask_p,
2178 HGDIOBJ *prev)
2180 HDC frame_dc = get_frame_dc (f);
2181 XImagePtr_or_DC ximg = CreateCompatibleDC (frame_dc);
2183 release_frame_dc (f, frame_dc);
2184 *prev = SelectObject (ximg, !mask_p ? img->pixmap : img->mask);
2186 return ximg;
2189 static void
2190 image_unget_x_image_or_dc (struct image *img, bool mask_p,
2191 XImagePtr_or_DC ximg, HGDIOBJ prev)
2193 SelectObject (ximg, prev);
2194 DeleteDC (ximg);
2196 #else /* !HAVE_NTGUI */
2197 /* Get the X image for IMG on frame F. The resulting X image data
2198 should be treated as read-only at least on X. */
2200 static XImagePtr
2201 image_get_x_image (struct frame *f, struct image *img, bool mask_p)
2203 #ifdef HAVE_X_WINDOWS
2204 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2206 if (ximg_in_img)
2207 return ximg_in_img;
2208 else
2209 return XGetImage (FRAME_X_DISPLAY (f), !mask_p ? img->pixmap : img->mask,
2210 0, 0, img->width, img->height, ~0, ZPixmap);
2211 #elif defined (HAVE_NS)
2212 XImagePtr pixmap = !mask_p ? img->pixmap : img->mask;
2214 ns_retain_object (pixmap);
2215 return pixmap;
2216 #endif
2219 static void
2220 image_unget_x_image (struct image *img, bool mask_p, XImagePtr ximg)
2222 #ifdef HAVE_X_WINDOWS
2223 XImagePtr ximg_in_img = !mask_p ? img->ximg : img->mask_img;
2225 if (ximg_in_img)
2226 eassert (ximg == ximg_in_img);
2227 else
2228 XDestroyImage (ximg);
2229 #elif defined (HAVE_NS)
2230 ns_release_object (ximg);
2231 #endif
2233 #endif /* !HAVE_NTGUI */
2236 /***********************************************************************
2237 File Handling
2238 ***********************************************************************/
2240 /* Find image file FILE. Look in data-directory/images, then
2241 x-bitmap-file-path. Value is the encoded full name of the file
2242 found, or nil if not found. */
2244 Lisp_Object
2245 x_find_image_file (Lisp_Object file)
2247 Lisp_Object file_found, search_path;
2248 int fd;
2250 /* TODO I think this should use something like image-load-path
2251 instead. Unfortunately, that can contain non-string elements. */
2252 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2253 Vdata_directory),
2254 Vx_bitmap_file_path);
2256 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2257 fd = openp (search_path, file, Qnil, &file_found, Qnil, false);
2259 if (fd == -1)
2260 file_found = Qnil;
2261 else
2263 file_found = ENCODE_FILE (file_found);
2264 if (fd != -2)
2265 emacs_close (fd);
2268 return file_found;
2272 /* Read FILE into memory. Value is a pointer to a buffer allocated
2273 with xmalloc holding FILE's contents. Value is null if an error
2274 occurred. *SIZE is set to the size of the file. */
2276 static unsigned char *
2277 slurp_file (char *file, ptrdiff_t *size)
2279 FILE *fp = emacs_fopen (file, "rb");
2280 unsigned char *buf = NULL;
2281 struct stat st;
2283 if (fp)
2285 ptrdiff_t count = SPECPDL_INDEX ();
2286 record_unwind_protect_ptr (fclose_unwind, fp);
2288 if (fstat (fileno (fp), &st) == 0
2289 && 0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX))
2291 /* Report an error if we read past the purported EOF.
2292 This can happen if the file grows as we read it. */
2293 ptrdiff_t buflen = st.st_size;
2294 buf = xmalloc (buflen + 1);
2295 if (fread (buf, 1, buflen + 1, fp) == buflen)
2296 *size = buflen;
2297 else
2299 xfree (buf);
2300 buf = NULL;
2304 unbind_to (count, Qnil);
2307 return buf;
2312 /***********************************************************************
2313 XBM images
2314 ***********************************************************************/
2316 static bool xbm_load (struct frame *f, struct image *img);
2317 static bool xbm_image_p (Lisp_Object object);
2318 static bool xbm_file_p (Lisp_Object);
2321 /* Indices of image specification fields in xbm_format, below. */
2323 enum xbm_keyword_index
2325 XBM_TYPE,
2326 XBM_FILE,
2327 XBM_WIDTH,
2328 XBM_HEIGHT,
2329 XBM_DATA,
2330 XBM_FOREGROUND,
2331 XBM_BACKGROUND,
2332 XBM_ASCENT,
2333 XBM_MARGIN,
2334 XBM_RELIEF,
2335 XBM_ALGORITHM,
2336 XBM_HEURISTIC_MASK,
2337 XBM_MASK,
2338 XBM_LAST
2341 /* Vector of image_keyword structures describing the format
2342 of valid XBM image specifications. */
2344 static const struct image_keyword xbm_format[XBM_LAST] =
2346 {":type", IMAGE_SYMBOL_VALUE, 1},
2347 {":file", IMAGE_STRING_VALUE, 0},
2348 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2349 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2350 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2351 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2352 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2353 {":ascent", IMAGE_ASCENT_VALUE, 0},
2354 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2355 {":relief", IMAGE_INTEGER_VALUE, 0},
2356 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2357 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2358 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2361 /* Structure describing the image type XBM. */
2363 static struct image_type xbm_type =
2365 &Qxbm,
2366 xbm_image_p,
2367 xbm_load,
2368 x_clear_image,
2369 NULL,
2370 NULL
2373 /* Tokens returned from xbm_scan. */
2375 enum xbm_token
2377 XBM_TK_IDENT = 256,
2378 XBM_TK_NUMBER
2382 /* Return true if OBJECT is a valid XBM-type image specification.
2383 A valid specification is a list starting with the symbol `image'
2384 The rest of the list is a property list which must contain an
2385 entry `:type xbm'.
2387 If the specification specifies a file to load, it must contain
2388 an entry `:file FILENAME' where FILENAME is a string.
2390 If the specification is for a bitmap loaded from memory it must
2391 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2392 WIDTH and HEIGHT are integers > 0. DATA may be:
2394 1. a string large enough to hold the bitmap data, i.e. it must
2395 have a size >= (WIDTH + 7) / 8 * HEIGHT
2397 2. a bool-vector of size >= WIDTH * HEIGHT
2399 3. a vector of strings or bool-vectors, one for each line of the
2400 bitmap.
2402 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2403 may not be specified in this case because they are defined in the
2404 XBM file.
2406 Both the file and data forms may contain the additional entries
2407 `:background COLOR' and `:foreground COLOR'. If not present,
2408 foreground and background of the frame on which the image is
2409 displayed is used. */
2411 static bool
2412 xbm_image_p (Lisp_Object object)
2414 struct image_keyword kw[XBM_LAST];
2416 memcpy (kw, xbm_format, sizeof kw);
2417 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2418 return 0;
2420 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2422 if (kw[XBM_FILE].count)
2424 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2425 return 0;
2427 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2429 /* In-memory XBM file. */
2430 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2431 return 0;
2433 else
2435 Lisp_Object data;
2436 int width, height;
2438 /* Entries for `:width', `:height' and `:data' must be present. */
2439 if (!kw[XBM_WIDTH].count
2440 || !kw[XBM_HEIGHT].count
2441 || !kw[XBM_DATA].count)
2442 return 0;
2444 data = kw[XBM_DATA].value;
2445 width = XFASTINT (kw[XBM_WIDTH].value);
2446 height = XFASTINT (kw[XBM_HEIGHT].value);
2448 /* Check type of data, and width and height against contents of
2449 data. */
2450 if (VECTORP (data))
2452 EMACS_INT i;
2454 /* Number of elements of the vector must be >= height. */
2455 if (ASIZE (data) < height)
2456 return 0;
2458 /* Each string or bool-vector in data must be large enough
2459 for one line of the image. */
2460 for (i = 0; i < height; ++i)
2462 Lisp_Object elt = AREF (data, i);
2464 if (STRINGP (elt))
2466 if (SCHARS (elt)
2467 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2468 return 0;
2470 else if (BOOL_VECTOR_P (elt))
2472 if (bool_vector_size (elt) < width)
2473 return 0;
2475 else
2476 return 0;
2479 else if (STRINGP (data))
2481 if (SCHARS (data)
2482 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2483 return 0;
2485 else if (BOOL_VECTOR_P (data))
2487 if (bool_vector_size (data) / height < width)
2488 return 0;
2490 else
2491 return 0;
2494 return 1;
2498 /* Scan a bitmap file. FP is the stream to read from. Value is
2499 either an enumerator from enum xbm_token, or a character for a
2500 single-character token, or 0 at end of file. If scanning an
2501 identifier, store the lexeme of the identifier in SVAL. If
2502 scanning a number, store its value in *IVAL. */
2504 static int
2505 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2507 unsigned int c;
2509 loop:
2511 /* Skip white space. */
2512 while (*s < end && (c = *(*s)++, c_isspace (c)))
2515 if (*s >= end)
2516 c = 0;
2517 else if (c_isdigit (c))
2519 int value = 0, digit;
2521 if (c == '0' && *s < end)
2523 c = *(*s)++;
2524 if (c == 'x' || c == 'X')
2526 while (*s < end)
2528 c = *(*s)++;
2529 if (c_isdigit (c))
2530 digit = c - '0';
2531 else if (c >= 'a' && c <= 'f')
2532 digit = c - 'a' + 10;
2533 else if (c >= 'A' && c <= 'F')
2534 digit = c - 'A' + 10;
2535 else
2536 break;
2537 value = 16 * value + digit;
2540 else if (c_isdigit (c))
2542 value = c - '0';
2543 while (*s < end
2544 && (c = *(*s)++, c_isdigit (c)))
2545 value = 8 * value + c - '0';
2548 else
2550 value = c - '0';
2551 while (*s < end
2552 && (c = *(*s)++, c_isdigit (c)))
2553 value = 10 * value + c - '0';
2556 if (*s < end)
2557 *s = *s - 1;
2558 *ival = value;
2559 c = XBM_TK_NUMBER;
2561 else if (c_isalpha (c) || c == '_')
2563 *sval++ = c;
2564 while (*s < end
2565 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2566 *sval++ = c;
2567 *sval = 0;
2568 if (*s < end)
2569 *s = *s - 1;
2570 c = XBM_TK_IDENT;
2572 else if (c == '/' && **s == '*')
2574 /* C-style comment. */
2575 ++*s;
2576 while (**s && (**s != '*' || *(*s + 1) != '/'))
2577 ++*s;
2578 if (**s)
2580 *s += 2;
2581 goto loop;
2585 return c;
2588 #ifdef HAVE_NTGUI
2590 /* Create a Windows bitmap from X bitmap data. */
2591 static HBITMAP
2592 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2594 static unsigned char swap_nibble[16]
2595 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2596 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2597 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2598 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2599 int i, j, w1, w2;
2600 unsigned char *bits, *p;
2601 HBITMAP bmp;
2603 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2604 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2605 bits = alloca (height * w2);
2606 memset (bits, 0, height * w2);
2607 for (i = 0; i < height; i++)
2609 p = bits + i*w2;
2610 for (j = 0; j < w1; j++)
2612 /* Bitswap XBM bytes to match how Windows does things. */
2613 unsigned char c = *data++;
2614 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2615 | (swap_nibble[(c>>4) & 0xf]));
2618 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2620 return bmp;
2623 static void
2624 convert_mono_to_color_image (struct frame *f, struct image *img,
2625 COLORREF foreground, COLORREF background)
2627 HDC hdc, old_img_dc, new_img_dc;
2628 HGDIOBJ old_prev, new_prev;
2629 HBITMAP new_pixmap;
2631 hdc = get_frame_dc (f);
2632 old_img_dc = CreateCompatibleDC (hdc);
2633 new_img_dc = CreateCompatibleDC (hdc);
2634 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2635 release_frame_dc (f, hdc);
2636 old_prev = SelectObject (old_img_dc, img->pixmap);
2637 new_prev = SelectObject (new_img_dc, new_pixmap);
2638 /* Windows convention for mono bitmaps is black = background,
2639 white = foreground. */
2640 SetTextColor (new_img_dc, background);
2641 SetBkColor (new_img_dc, foreground);
2643 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2644 0, 0, SRCCOPY);
2646 SelectObject (old_img_dc, old_prev);
2647 SelectObject (new_img_dc, new_prev);
2648 DeleteDC (old_img_dc);
2649 DeleteDC (new_img_dc);
2650 DeleteObject (img->pixmap);
2651 if (new_pixmap == 0)
2652 fprintf (stderr, "Failed to convert image to color.\n");
2653 else
2654 img->pixmap = new_pixmap;
2657 #define XBM_BIT_SHUFFLE(b) (~(b))
2659 #else
2661 #define XBM_BIT_SHUFFLE(b) (b)
2663 #endif /* HAVE_NTGUI */
2666 static void
2667 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2668 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2669 bool non_default_colors)
2671 #ifdef HAVE_NTGUI
2672 img->pixmap
2673 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2675 /* If colors were specified, transfer the bitmap to a color one. */
2676 if (non_default_colors)
2677 convert_mono_to_color_image (f, img, fg, bg);
2679 #elif defined (HAVE_NS)
2680 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2682 #else
2683 img->pixmap =
2684 (x_check_image_size (0, img->width, img->height)
2685 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2686 FRAME_X_WINDOW (f),
2687 data,
2688 img->width, img->height,
2689 fg, bg,
2690 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2691 : NO_PIXMAP);
2692 #endif /* !HAVE_NTGUI && !HAVE_NS */
2697 /* Replacement for XReadBitmapFileData which isn't available under old
2698 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2699 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2700 the image. Return in *DATA the bitmap data allocated with xmalloc.
2701 Value is true if successful. DATA null means just test if
2702 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2703 inhibit the call to image_error when the image size is invalid (the
2704 bitmap remains unread). */
2706 static bool
2707 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2708 int *width, int *height, char **data,
2709 bool inhibit_image_error)
2711 unsigned char *s = contents;
2712 char buffer[BUFSIZ];
2713 bool padding_p = 0;
2714 bool v10 = 0;
2715 int bytes_per_line, i, nbytes;
2716 char *p;
2717 int value;
2718 int LA1;
2720 #define match() \
2721 LA1 = xbm_scan (&s, end, buffer, &value)
2723 #define expect(TOKEN) \
2724 do \
2726 if (LA1 != (TOKEN)) \
2727 goto failure; \
2728 match (); \
2730 while (0)
2732 #define expect_ident(IDENT) \
2733 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2734 match (); \
2735 else \
2736 goto failure
2738 *width = *height = -1;
2739 if (data)
2740 *data = NULL;
2741 LA1 = xbm_scan (&s, end, buffer, &value);
2743 /* Parse defines for width, height and hot-spots. */
2744 while (LA1 == '#')
2746 match ();
2747 expect_ident ("define");
2748 expect (XBM_TK_IDENT);
2750 if (LA1 == XBM_TK_NUMBER)
2752 char *q = strrchr (buffer, '_');
2753 q = q ? q + 1 : buffer;
2754 if (strcmp (q, "width") == 0)
2755 *width = value;
2756 else if (strcmp (q, "height") == 0)
2757 *height = value;
2759 expect (XBM_TK_NUMBER);
2762 if (!check_image_size (f, *width, *height))
2764 if (!inhibit_image_error)
2765 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2766 goto failure;
2768 else if (data == NULL)
2769 goto success;
2771 /* Parse bits. Must start with `static'. */
2772 expect_ident ("static");
2773 if (LA1 == XBM_TK_IDENT)
2775 if (strcmp (buffer, "unsigned") == 0)
2777 match ();
2778 expect_ident ("char");
2780 else if (strcmp (buffer, "short") == 0)
2782 match ();
2783 v10 = 1;
2784 if (*width % 16 && *width % 16 < 9)
2785 padding_p = 1;
2787 else if (strcmp (buffer, "char") == 0)
2788 match ();
2789 else
2790 goto failure;
2792 else
2793 goto failure;
2795 expect (XBM_TK_IDENT);
2796 expect ('[');
2797 expect (']');
2798 expect ('=');
2799 expect ('{');
2801 if (! x_check_image_size (0, *width, *height))
2803 if (!inhibit_image_error)
2804 image_error ("Image too large (%dx%d)",
2805 make_number (*width), make_number (*height));
2806 goto failure;
2808 bytes_per_line = (*width + 7) / 8 + padding_p;
2809 nbytes = bytes_per_line * *height;
2810 p = *data = xmalloc (nbytes);
2812 if (v10)
2814 for (i = 0; i < nbytes; i += 2)
2816 int val = value;
2817 expect (XBM_TK_NUMBER);
2819 *p++ = XBM_BIT_SHUFFLE (val);
2820 if (!padding_p || ((i + 2) % bytes_per_line))
2821 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2823 if (LA1 == ',' || LA1 == '}')
2824 match ();
2825 else
2826 goto failure;
2829 else
2831 for (i = 0; i < nbytes; ++i)
2833 int val = value;
2834 expect (XBM_TK_NUMBER);
2836 *p++ = XBM_BIT_SHUFFLE (val);
2838 if (LA1 == ',' || LA1 == '}')
2839 match ();
2840 else
2841 goto failure;
2845 success:
2846 return 1;
2848 failure:
2850 if (data && *data)
2852 xfree (*data);
2853 *data = NULL;
2855 return 0;
2857 #undef match
2858 #undef expect
2859 #undef expect_ident
2863 /* Load XBM image IMG which will be displayed on frame F from buffer
2864 CONTENTS. END is the end of the buffer. Value is true if
2865 successful. */
2867 static bool
2868 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2869 unsigned char *end)
2871 bool rc;
2872 char *data;
2873 bool success_p = 0;
2875 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2876 &data, 0);
2877 if (rc)
2879 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2880 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2881 bool non_default_colors = 0;
2882 Lisp_Object value;
2884 eassert (img->width > 0 && img->height > 0);
2886 /* Get foreground and background colors, maybe allocate colors. */
2887 value = image_spec_value (img->spec, QCforeground, NULL);
2888 if (!NILP (value))
2890 foreground = x_alloc_image_color (f, img, value, foreground);
2891 non_default_colors = 1;
2893 value = image_spec_value (img->spec, QCbackground, NULL);
2894 if (!NILP (value))
2896 background = x_alloc_image_color (f, img, value, background);
2897 img->background = background;
2898 img->background_valid = 1;
2899 non_default_colors = 1;
2902 Create_Pixmap_From_Bitmap_Data (f, img, data,
2903 foreground, background,
2904 non_default_colors);
2905 xfree (data);
2907 if (img->pixmap == NO_PIXMAP)
2909 x_clear_image (f, img);
2910 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2912 else
2913 success_p = 1;
2915 else
2916 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2918 return success_p;
2922 /* Value is true if DATA looks like an in-memory XBM file. */
2924 static bool
2925 xbm_file_p (Lisp_Object data)
2927 int w, h;
2928 return (STRINGP (data)
2929 && xbm_read_bitmap_data (NULL, SDATA (data),
2930 (SDATA (data) + SBYTES (data)),
2931 &w, &h, NULL, 1));
2935 /* Fill image IMG which is used on frame F with pixmap data. Value is
2936 true if successful. */
2938 static bool
2939 xbm_load (struct frame *f, struct image *img)
2941 bool success_p = 0;
2942 Lisp_Object file_name;
2944 eassert (xbm_image_p (img->spec));
2946 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2947 file_name = image_spec_value (img->spec, QCfile, NULL);
2948 if (STRINGP (file_name))
2950 Lisp_Object file;
2951 unsigned char *contents;
2952 ptrdiff_t size;
2954 file = x_find_image_file (file_name);
2955 if (!STRINGP (file))
2957 image_error ("Cannot find image file `%s'", file_name, Qnil);
2958 return 0;
2961 contents = slurp_file (SSDATA (file), &size);
2962 if (contents == NULL)
2964 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2965 return 0;
2968 success_p = xbm_load_image (f, img, contents, contents + size);
2969 xfree (contents);
2971 else
2973 struct image_keyword fmt[XBM_LAST];
2974 Lisp_Object data;
2975 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2976 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2977 bool non_default_colors = 0;
2978 char *bits;
2979 bool parsed_p;
2980 bool in_memory_file_p = 0;
2982 /* See if data looks like an in-memory XBM file. */
2983 data = image_spec_value (img->spec, QCdata, NULL);
2984 in_memory_file_p = xbm_file_p (data);
2986 /* Parse the image specification. */
2987 memcpy (fmt, xbm_format, sizeof fmt);
2988 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2989 eassert (parsed_p);
2991 /* Get specified width, and height. */
2992 if (!in_memory_file_p)
2994 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2995 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2996 eassert (img->width > 0 && img->height > 0);
2997 if (!check_image_size (f, img->width, img->height))
2999 image_error ("Invalid image size (see `max-image-size')",
3000 Qnil, Qnil);
3001 return 0;
3005 /* Get foreground and background colors, maybe allocate colors. */
3006 if (fmt[XBM_FOREGROUND].count
3007 && STRINGP (fmt[XBM_FOREGROUND].value))
3009 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3010 foreground);
3011 non_default_colors = 1;
3014 if (fmt[XBM_BACKGROUND].count
3015 && STRINGP (fmt[XBM_BACKGROUND].value))
3017 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3018 background);
3019 non_default_colors = 1;
3022 if (in_memory_file_p)
3023 success_p = xbm_load_image (f, img, SDATA (data),
3024 (SDATA (data)
3025 + SBYTES (data)));
3026 else
3028 USE_SAFE_ALLOCA;
3030 if (VECTORP (data))
3032 int i;
3033 char *p;
3034 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3036 SAFE_NALLOCA (bits, nbytes, img->height);
3037 p = bits;
3038 for (i = 0; i < img->height; ++i, p += nbytes)
3040 Lisp_Object line = AREF (data, i);
3041 if (STRINGP (line))
3042 memcpy (p, SDATA (line), nbytes);
3043 else
3044 memcpy (p, bool_vector_data (line), nbytes);
3047 else if (STRINGP (data))
3048 bits = SSDATA (data);
3049 else
3050 bits = (char *) bool_vector_data (data);
3052 #ifdef HAVE_NTGUI
3054 char *invertedBits;
3055 int nbytes, i;
3056 /* Windows mono bitmaps are reversed compared with X. */
3057 invertedBits = bits;
3058 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3059 SAFE_NALLOCA (bits, nbytes, img->height);
3060 for (i = 0; i < nbytes; i++)
3061 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3063 #endif
3064 /* Create the pixmap. */
3066 if (x_check_image_size (0, img->width, img->height))
3067 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3068 foreground, background,
3069 non_default_colors);
3070 else
3071 img->pixmap = NO_PIXMAP;
3073 if (img->pixmap)
3074 success_p = 1;
3075 else
3077 image_error ("Unable to create pixmap for XBM image `%s'",
3078 img->spec, Qnil);
3079 x_clear_image (f, img);
3082 SAFE_FREE ();
3086 return success_p;
3091 /***********************************************************************
3092 XPM images
3093 ***********************************************************************/
3095 #if defined (HAVE_XPM) || defined (HAVE_NS)
3097 static bool xpm_image_p (Lisp_Object object);
3098 static bool xpm_load (struct frame *f, struct image *img);
3100 #endif /* HAVE_XPM || HAVE_NS */
3102 #ifdef HAVE_XPM
3103 #ifdef HAVE_NTGUI
3104 /* Indicate to xpm.h that we don't have Xlib. */
3105 #define FOR_MSW
3106 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3107 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3108 #define XColor xpm_XColor
3109 #define XImage xpm_XImage
3110 #define Display xpm_Display
3111 #define PIXEL_ALREADY_TYPEDEFED
3112 #include "X11/xpm.h"
3113 #undef FOR_MSW
3114 #undef XColor
3115 #undef XImage
3116 #undef Display
3117 #undef PIXEL_ALREADY_TYPEDEFED
3118 #else
3119 #include "X11/xpm.h"
3120 #endif /* HAVE_NTGUI */
3121 #endif /* HAVE_XPM */
3123 #if defined (HAVE_XPM) || defined (HAVE_NS)
3124 /* The symbol `xpm' identifying XPM-format images. */
3126 static Lisp_Object Qxpm;
3128 /* Indices of image specification fields in xpm_format, below. */
3130 enum xpm_keyword_index
3132 XPM_TYPE,
3133 XPM_FILE,
3134 XPM_DATA,
3135 XPM_ASCENT,
3136 XPM_MARGIN,
3137 XPM_RELIEF,
3138 XPM_ALGORITHM,
3139 XPM_HEURISTIC_MASK,
3140 XPM_MASK,
3141 XPM_COLOR_SYMBOLS,
3142 XPM_BACKGROUND,
3143 XPM_LAST
3146 /* Vector of image_keyword structures describing the format
3147 of valid XPM image specifications. */
3149 static const struct image_keyword xpm_format[XPM_LAST] =
3151 {":type", IMAGE_SYMBOL_VALUE, 1},
3152 {":file", IMAGE_STRING_VALUE, 0},
3153 {":data", IMAGE_STRING_VALUE, 0},
3154 {":ascent", IMAGE_ASCENT_VALUE, 0},
3155 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3156 {":relief", IMAGE_INTEGER_VALUE, 0},
3157 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3158 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3159 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3160 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3161 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3164 #if defined HAVE_NTGUI && defined WINDOWSNT
3165 static bool init_xpm_functions (void);
3166 #else
3167 #define init_xpm_functions NULL
3168 #endif
3170 /* Structure describing the image type XPM. */
3172 static struct image_type xpm_type =
3174 &Qxpm,
3175 xpm_image_p,
3176 xpm_load,
3177 x_clear_image,
3178 init_xpm_functions,
3179 NULL
3182 #ifdef HAVE_X_WINDOWS
3184 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3185 functions for allocating image colors. Our own functions handle
3186 color allocation failures more gracefully than the ones on the XPM
3187 lib. */
3189 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3190 #define ALLOC_XPM_COLORS
3191 #endif
3192 #endif /* HAVE_X_WINDOWS */
3194 #ifdef ALLOC_XPM_COLORS
3196 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3197 XColor *, int);
3199 /* An entry in a hash table used to cache color definitions of named
3200 colors. This cache is necessary to speed up XPM image loading in
3201 case we do color allocations ourselves. Without it, we would need
3202 a call to XParseColor per pixel in the image. */
3204 struct xpm_cached_color
3206 /* Next in collision chain. */
3207 struct xpm_cached_color *next;
3209 /* Color definition (RGB and pixel color). */
3210 XColor color;
3212 /* Color name. */
3213 char name[FLEXIBLE_ARRAY_MEMBER];
3216 /* The hash table used for the color cache, and its bucket vector
3217 size. */
3219 #define XPM_COLOR_CACHE_BUCKETS 1001
3220 static struct xpm_cached_color **xpm_color_cache;
3222 /* Initialize the color cache. */
3224 static void
3225 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3227 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3228 xpm_color_cache = xzalloc (nbytes);
3229 init_color_table ();
3231 if (attrs->valuemask & XpmColorSymbols)
3233 int i;
3234 XColor color;
3236 for (i = 0; i < attrs->numsymbols; ++i)
3237 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3238 attrs->colorsymbols[i].value, &color))
3240 color.pixel = lookup_rgb_color (f, color.red, color.green,
3241 color.blue);
3242 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3247 /* Free the color cache. */
3249 static void
3250 xpm_free_color_cache (void)
3252 struct xpm_cached_color *p, *next;
3253 int i;
3255 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3256 for (p = xpm_color_cache[i]; p; p = next)
3258 next = p->next;
3259 xfree (p);
3262 xfree (xpm_color_cache);
3263 xpm_color_cache = NULL;
3264 free_color_table ();
3267 /* Return the bucket index for color named COLOR_NAME in the color
3268 cache. */
3270 static int
3271 xpm_color_bucket (char *color_name)
3273 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3274 return hash % XPM_COLOR_CACHE_BUCKETS;
3278 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3279 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3280 entry added. */
3282 static struct xpm_cached_color *
3283 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3285 size_t nbytes;
3286 struct xpm_cached_color *p;
3288 if (bucket < 0)
3289 bucket = xpm_color_bucket (color_name);
3291 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3292 p = xmalloc (nbytes);
3293 strcpy (p->name, color_name);
3294 p->color = *color;
3295 p->next = xpm_color_cache[bucket];
3296 xpm_color_cache[bucket] = p;
3297 return p;
3300 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3301 return the cached definition in *COLOR. Otherwise, make a new
3302 entry in the cache and allocate the color. Value is false if color
3303 allocation failed. */
3305 static bool
3306 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3308 struct xpm_cached_color *p;
3309 int h = xpm_color_bucket (color_name);
3311 for (p = xpm_color_cache[h]; p; p = p->next)
3312 if (strcmp (p->name, color_name) == 0)
3313 break;
3315 if (p != NULL)
3316 *color = p->color;
3317 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3318 color_name, color))
3320 color->pixel = lookup_rgb_color (f, color->red, color->green,
3321 color->blue);
3322 p = xpm_cache_color (f, color_name, color, h);
3324 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3325 with transparency, and it's useful. */
3326 else if (strcmp ("opaque", color_name) == 0)
3328 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3329 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3330 p = xpm_cache_color (f, color_name, color, h);
3333 return p != NULL;
3337 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3338 CLOSURE is a pointer to the frame on which we allocate the
3339 color. Return in *COLOR the allocated color. Value is non-zero
3340 if successful. */
3342 static int
3343 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3344 void *closure)
3346 return xpm_lookup_color (closure, color_name, color);
3350 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3351 is a pointer to the frame on which we allocate the color. Value is
3352 non-zero if successful. */
3354 static int
3355 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3357 return 1;
3360 #endif /* ALLOC_XPM_COLORS */
3363 #ifdef WINDOWSNT
3365 /* XPM library details. */
3367 DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
3368 DEF_DLL_FN (int, XpmCreateImageFromBuffer,
3369 (Display *, char *, xpm_XImage **,
3370 xpm_XImage **, XpmAttributes *));
3371 DEF_DLL_FN (int, XpmReadFileToImage,
3372 (Display *, char *, xpm_XImage **,
3373 xpm_XImage **, XpmAttributes *));
3374 DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
3376 static bool
3377 init_xpm_functions (void)
3379 HMODULE library;
3381 if (!(library = w32_delayed_load (Qxpm)))
3382 return 0;
3384 LOAD_DLL_FN (library, XpmFreeAttributes);
3385 LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
3386 LOAD_DLL_FN (library, XpmReadFileToImage);
3387 LOAD_DLL_FN (library, XImageFree);
3388 return 1;
3391 # undef XImageFree
3392 # undef XpmCreateImageFromBuffer
3393 # undef XpmFreeAttributes
3394 # undef XpmReadFileToImage
3396 # define XImageFree fn_XImageFree
3397 # define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
3398 # define XpmFreeAttributes fn_XpmFreeAttributes
3399 # define XpmReadFileToImage fn_XpmReadFileToImage
3401 #endif /* WINDOWSNT */
3403 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3404 for XPM images. Such a list must consist of conses whose car and
3405 cdr are strings. */
3407 static bool
3408 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3410 while (CONSP (color_symbols))
3412 Lisp_Object sym = XCAR (color_symbols);
3413 if (!CONSP (sym)
3414 || !STRINGP (XCAR (sym))
3415 || !STRINGP (XCDR (sym)))
3416 break;
3417 color_symbols = XCDR (color_symbols);
3420 return NILP (color_symbols);
3424 /* Value is true if OBJECT is a valid XPM image specification. */
3426 static bool
3427 xpm_image_p (Lisp_Object object)
3429 struct image_keyword fmt[XPM_LAST];
3430 memcpy (fmt, xpm_format, sizeof fmt);
3431 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3432 /* Either `:file' or `:data' must be present. */
3433 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3434 /* Either no `:color-symbols' or it's a list of conses
3435 whose car and cdr are strings. */
3436 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3437 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3440 #endif /* HAVE_XPM || HAVE_NS */
3442 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3443 ptrdiff_t
3444 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3446 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
3447 ptrdiff_t id;
3448 int rc;
3449 XpmAttributes attrs;
3450 Pixmap bitmap, mask;
3452 memset (&attrs, 0, sizeof attrs);
3454 attrs.visual = FRAME_X_VISUAL (f);
3455 attrs.colormap = FRAME_X_COLORMAP (f);
3456 attrs.valuemask |= XpmVisual;
3457 attrs.valuemask |= XpmColormap;
3459 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3460 (char **) bits, &bitmap, &mask, &attrs);
3461 if (rc != XpmSuccess)
3463 XpmFreeAttributes (&attrs);
3464 return -1;
3467 id = x_allocate_bitmap_record (f);
3468 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3469 dpyinfo->bitmaps[id - 1].have_mask = true;
3470 dpyinfo->bitmaps[id - 1].mask = mask;
3471 dpyinfo->bitmaps[id - 1].file = NULL;
3472 dpyinfo->bitmaps[id - 1].height = attrs.height;
3473 dpyinfo->bitmaps[id - 1].width = attrs.width;
3474 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3475 dpyinfo->bitmaps[id - 1].refcount = 1;
3477 XpmFreeAttributes (&attrs);
3478 return id;
3480 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3482 /* Load image IMG which will be displayed on frame F. Value is
3483 true if successful. */
3485 #ifdef HAVE_XPM
3487 static bool
3488 xpm_load (struct frame *f, struct image *img)
3490 int rc;
3491 XpmAttributes attrs;
3492 Lisp_Object specified_file, color_symbols;
3493 USE_SAFE_ALLOCA;
3495 #ifdef HAVE_NTGUI
3496 HDC hdc;
3497 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3498 #endif /* HAVE_NTGUI */
3500 /* Configure the XPM lib. Use the visual of frame F. Allocate
3501 close colors. Return colors allocated. */
3502 memset (&attrs, 0, sizeof attrs);
3504 #ifndef HAVE_NTGUI
3505 attrs.visual = FRAME_X_VISUAL (f);
3506 attrs.colormap = FRAME_X_COLORMAP (f);
3507 attrs.valuemask |= XpmVisual;
3508 attrs.valuemask |= XpmColormap;
3509 #endif /* HAVE_NTGUI */
3511 #ifdef ALLOC_XPM_COLORS
3512 /* Allocate colors with our own functions which handle
3513 failing color allocation more gracefully. */
3514 attrs.color_closure = f;
3515 attrs.alloc_color = xpm_alloc_color;
3516 attrs.free_colors = xpm_free_colors;
3517 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3518 #else /* not ALLOC_XPM_COLORS */
3519 /* Let the XPM lib allocate colors. */
3520 attrs.valuemask |= XpmReturnAllocPixels;
3521 #ifdef XpmAllocCloseColors
3522 attrs.alloc_close_colors = 1;
3523 attrs.valuemask |= XpmAllocCloseColors;
3524 #else /* not XpmAllocCloseColors */
3525 attrs.closeness = 600;
3526 attrs.valuemask |= XpmCloseness;
3527 #endif /* not XpmAllocCloseColors */
3528 #endif /* ALLOC_XPM_COLORS */
3530 /* If image specification contains symbolic color definitions, add
3531 these to `attrs'. */
3532 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3533 if (CONSP (color_symbols))
3535 Lisp_Object tail;
3536 XpmColorSymbol *xpm_syms;
3537 ptrdiff_t i, size;
3539 attrs.valuemask |= XpmColorSymbols;
3541 /* Count number of symbols. */
3542 attrs.numsymbols = 0;
3543 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3544 ++attrs.numsymbols;
3546 /* Allocate an XpmColorSymbol array. */
3547 SAFE_NALLOCA (xpm_syms, 1, attrs.numsymbols);
3548 size = attrs.numsymbols * sizeof *xpm_syms;
3549 memset (xpm_syms, 0, size);
3550 attrs.colorsymbols = xpm_syms;
3552 /* Fill the color symbol array. */
3553 for (tail = color_symbols, i = 0;
3554 CONSP (tail);
3555 ++i, tail = XCDR (tail))
3557 Lisp_Object name;
3558 Lisp_Object color;
3559 char *empty_string = (char *) "";
3561 if (!CONSP (XCAR (tail)))
3563 xpm_syms[i].name = empty_string;
3564 xpm_syms[i].value = empty_string;
3565 continue;
3567 name = XCAR (XCAR (tail));
3568 color = XCDR (XCAR (tail));
3569 if (STRINGP (name))
3570 SAFE_ALLOCA_STRING (xpm_syms[i].name, name);
3571 else
3572 xpm_syms[i].name = empty_string;
3573 if (STRINGP (color))
3574 SAFE_ALLOCA_STRING (xpm_syms[i].value, color);
3575 else
3576 xpm_syms[i].value = empty_string;
3580 /* Create a pixmap for the image, either from a file, or from a
3581 string buffer containing data in the same format as an XPM file. */
3582 #ifdef ALLOC_XPM_COLORS
3583 xpm_init_color_cache (f, &attrs);
3584 #endif
3586 specified_file = image_spec_value (img->spec, QCfile, NULL);
3588 #ifdef HAVE_NTGUI
3590 HDC frame_dc = get_frame_dc (f);
3591 hdc = CreateCompatibleDC (frame_dc);
3592 release_frame_dc (f, frame_dc);
3594 #endif /* HAVE_NTGUI */
3596 if (STRINGP (specified_file))
3598 Lisp_Object file = x_find_image_file (specified_file);
3599 if (!STRINGP (file))
3601 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3602 #ifdef ALLOC_XPM_COLORS
3603 xpm_free_color_cache ();
3604 #endif
3605 SAFE_FREE ();
3606 return 0;
3609 #ifdef HAVE_NTGUI
3610 #ifdef WINDOWSNT
3611 /* FILE is encoded in UTF-8, but image libraries on Windows
3612 support neither UTF-8 nor UTF-16 encoded file names. So we
3613 need to re-encode it in ANSI. */
3614 file = ansi_encode_filename (file);
3615 #endif
3616 /* XpmReadFileToPixmap is not available in the Windows port of
3617 libxpm. But XpmReadFileToImage almost does what we want. */
3618 rc = XpmReadFileToImage (&hdc, SDATA (file),
3619 &xpm_image, &xpm_mask,
3620 &attrs);
3621 #else
3622 rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
3623 &img->ximg, &img->mask_img,
3624 &attrs);
3625 #endif /* HAVE_NTGUI */
3627 else
3629 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3630 if (!STRINGP (buffer))
3632 image_error ("Invalid image data `%s'", buffer, Qnil);
3633 #ifdef ALLOC_XPM_COLORS
3634 xpm_free_color_cache ();
3635 #endif
3636 SAFE_FREE ();
3637 return 0;
3639 #ifdef HAVE_NTGUI
3640 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3641 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3642 rc = XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3643 &xpm_image, &xpm_mask,
3644 &attrs);
3645 #else
3646 rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
3647 &img->ximg, &img->mask_img,
3648 &attrs);
3649 #endif /* HAVE_NTGUI */
3652 #ifdef HAVE_X_WINDOWS
3653 if (rc == XpmSuccess)
3655 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3656 img->ximg->width, img->ximg->height,
3657 img->ximg->depth);
3658 if (img->pixmap == NO_PIXMAP)
3660 x_clear_image (f, img);
3661 rc = XpmNoMemory;
3663 else if (img->mask_img)
3665 img->mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3666 img->mask_img->width,
3667 img->mask_img->height,
3668 img->mask_img->depth);
3669 if (img->mask == NO_PIXMAP)
3671 x_clear_image (f, img);
3672 rc = XpmNoMemory;
3676 #endif
3678 if (rc == XpmSuccess)
3680 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3681 img->colors = colors_in_color_table (&img->ncolors);
3682 #else /* not ALLOC_XPM_COLORS */
3683 int i;
3685 #ifdef HAVE_NTGUI
3686 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3687 plus some duplicate attributes. */
3688 if (xpm_image && xpm_image->bitmap)
3690 img->pixmap = xpm_image->bitmap;
3691 /* XImageFree in libXpm frees XImage struct without destroying
3692 the bitmap, which is what we want. */
3693 XImageFree (xpm_image);
3695 if (xpm_mask && xpm_mask->bitmap)
3697 /* The mask appears to be inverted compared with what we expect.
3698 TODO: invert our expectations. See other places where we
3699 have to invert bits because our idea of masks is backwards. */
3700 HGDIOBJ old_obj;
3701 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3703 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3704 SelectObject (hdc, old_obj);
3706 img->mask = xpm_mask->bitmap;
3707 XImageFree (xpm_mask);
3708 DeleteDC (hdc);
3711 DeleteDC (hdc);
3712 #endif /* HAVE_NTGUI */
3714 /* Remember allocated colors. */
3715 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3716 img->ncolors = attrs.nalloc_pixels;
3717 for (i = 0; i < attrs.nalloc_pixels; ++i)
3719 img->colors[i] = attrs.alloc_pixels[i];
3720 #ifdef DEBUG_X_COLORS
3721 register_color (img->colors[i]);
3722 #endif
3724 #endif /* not ALLOC_XPM_COLORS */
3726 img->width = attrs.width;
3727 img->height = attrs.height;
3728 eassert (img->width > 0 && img->height > 0);
3730 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3731 XpmFreeAttributes (&attrs);
3733 #ifdef HAVE_X_WINDOWS
3734 /* Maybe fill in the background field while we have ximg handy. */
3735 IMAGE_BACKGROUND (img, f, img->ximg);
3736 if (img->mask_img)
3737 /* Fill in the background_transparent field while we have the
3738 mask handy. */
3739 image_background_transparent (img, f, img->mask_img);
3740 #endif
3742 else
3744 #ifdef HAVE_NTGUI
3745 DeleteDC (hdc);
3746 #endif /* HAVE_NTGUI */
3748 switch (rc)
3750 case XpmOpenFailed:
3751 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3752 break;
3754 case XpmFileInvalid:
3755 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3756 break;
3758 case XpmNoMemory:
3759 image_error ("Out of memory (%s)", img->spec, Qnil);
3760 break;
3762 case XpmColorFailed:
3763 image_error ("Color allocation error (%s)", img->spec, Qnil);
3764 break;
3766 default:
3767 image_error ("Unknown error (%s)", img->spec, Qnil);
3768 break;
3772 #ifdef ALLOC_XPM_COLORS
3773 xpm_free_color_cache ();
3774 #endif
3775 SAFE_FREE ();
3776 return rc == XpmSuccess;
3779 #endif /* HAVE_XPM */
3781 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3783 /* XPM support functions for NS where libxpm is not available.
3784 Only XPM version 3 (without any extensions) is supported. */
3786 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3787 int, Lisp_Object);
3788 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3789 const unsigned char *, int);
3790 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3791 int, Lisp_Object);
3792 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3793 const unsigned char *, int);
3795 /* Tokens returned from xpm_scan. */
3797 enum xpm_token
3799 XPM_TK_IDENT = 256,
3800 XPM_TK_STRING,
3801 XPM_TK_EOF
3804 /* Scan an XPM data and return a character (< 256) or a token defined
3805 by enum xpm_token above. *S and END are the start (inclusive) and
3806 the end (exclusive) addresses of the data, respectively. Advance
3807 *S while scanning. If token is either XPM_TK_IDENT or
3808 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3809 length of the corresponding token, respectively. */
3811 static int
3812 xpm_scan (const unsigned char **s,
3813 const unsigned char *end,
3814 const unsigned char **beg,
3815 ptrdiff_t *len)
3817 int c;
3819 while (*s < end)
3821 /* Skip white-space. */
3822 while (*s < end && (c = *(*s)++, c_isspace (c)))
3825 /* gnus-pointer.xpm uses '-' in its identifier.
3826 sb-dir-plus.xpm uses '+' in its identifier. */
3827 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3829 *beg = *s - 1;
3830 while (*s < end
3831 && (c = **s, c_isalnum (c)
3832 || c == '_' || c == '-' || c == '+'))
3833 ++*s;
3834 *len = *s - *beg;
3835 return XPM_TK_IDENT;
3837 else if (c == '"')
3839 *beg = *s;
3840 while (*s < end && **s != '"')
3841 ++*s;
3842 *len = *s - *beg;
3843 if (*s < end)
3844 ++*s;
3845 return XPM_TK_STRING;
3847 else if (c == '/')
3849 if (*s < end && **s == '*')
3851 /* C-style comment. */
3852 ++*s;
3855 while (*s < end && *(*s)++ != '*')
3858 while (*s < end && **s != '/');
3859 if (*s < end)
3860 ++*s;
3862 else
3863 return c;
3865 else
3866 return c;
3869 return XPM_TK_EOF;
3872 /* Functions for color table lookup in XPM data. A key is a string
3873 specifying the color of each pixel in XPM data. A value is either
3874 an integer that specifies a pixel color, Qt that specifies
3875 transparency, or Qnil for the unspecified color. If the length of
3876 the key string is one, a vector is used as a table. Otherwise, a
3877 hash table is used. */
3879 static Lisp_Object
3880 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3881 const unsigned char *,
3882 int,
3883 Lisp_Object),
3884 Lisp_Object (**get_func) (Lisp_Object,
3885 const unsigned char *,
3886 int))
3888 *put_func = xpm_put_color_table_v;
3889 *get_func = xpm_get_color_table_v;
3890 return Fmake_vector (make_number (256), Qnil);
3893 static void
3894 xpm_put_color_table_v (Lisp_Object color_table,
3895 const unsigned char *chars_start,
3896 int chars_len,
3897 Lisp_Object color)
3899 ASET (color_table, *chars_start, color);
3902 static Lisp_Object
3903 xpm_get_color_table_v (Lisp_Object color_table,
3904 const unsigned char *chars_start,
3905 int chars_len)
3907 return AREF (color_table, *chars_start);
3910 static Lisp_Object
3911 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3912 const unsigned char *,
3913 int,
3914 Lisp_Object),
3915 Lisp_Object (**get_func) (Lisp_Object,
3916 const unsigned char *,
3917 int))
3919 *put_func = xpm_put_color_table_h;
3920 *get_func = xpm_get_color_table_h;
3921 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
3922 make_float (DEFAULT_REHASH_SIZE),
3923 make_float (DEFAULT_REHASH_THRESHOLD),
3924 Qnil);
3927 static void
3928 xpm_put_color_table_h (Lisp_Object color_table,
3929 const unsigned char *chars_start,
3930 int chars_len,
3931 Lisp_Object color)
3933 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3934 EMACS_UINT hash_code;
3935 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3937 hash_lookup (table, chars, &hash_code);
3938 hash_put (table, chars, color, hash_code);
3941 static Lisp_Object
3942 xpm_get_color_table_h (Lisp_Object color_table,
3943 const unsigned char *chars_start,
3944 int chars_len)
3946 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3947 ptrdiff_t i =
3948 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
3950 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3953 enum xpm_color_key {
3954 XPM_COLOR_KEY_S,
3955 XPM_COLOR_KEY_M,
3956 XPM_COLOR_KEY_G4,
3957 XPM_COLOR_KEY_G,
3958 XPM_COLOR_KEY_C
3961 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3963 static int
3964 xpm_str_to_color_key (const char *s)
3966 int i;
3968 for (i = 0; i < ARRAYELTS (xpm_color_key_strings); i++)
3969 if (strcmp (xpm_color_key_strings[i], s) == 0)
3970 return i;
3971 return -1;
3974 static bool
3975 xpm_load_image (struct frame *f,
3976 struct image *img,
3977 const unsigned char *contents,
3978 const unsigned char *end)
3980 const unsigned char *s = contents, *beg, *str;
3981 unsigned char buffer[BUFSIZ];
3982 int width, height, x, y;
3983 int num_colors, chars_per_pixel;
3984 ptrdiff_t len;
3985 int LA1;
3986 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3987 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3988 Lisp_Object frame, color_symbols, color_table;
3989 int best_key;
3990 bool have_mask = false;
3991 XImagePtr ximg = NULL, mask_img = NULL;
3993 #define match() \
3994 LA1 = xpm_scan (&s, end, &beg, &len)
3996 #define expect(TOKEN) \
3997 do \
3999 if (LA1 != (TOKEN)) \
4000 goto failure; \
4001 match (); \
4003 while (0)
4005 #define expect_ident(IDENT) \
4006 if (LA1 == XPM_TK_IDENT \
4007 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4008 match (); \
4009 else \
4010 goto failure
4012 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4013 goto failure;
4014 s += 9;
4015 match ();
4016 expect_ident ("static");
4017 expect_ident ("char");
4018 expect ('*');
4019 expect (XPM_TK_IDENT);
4020 expect ('[');
4021 expect (']');
4022 expect ('=');
4023 expect ('{');
4024 expect (XPM_TK_STRING);
4025 if (len >= BUFSIZ)
4026 goto failure;
4027 memcpy (buffer, beg, len);
4028 buffer[len] = '\0';
4029 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4030 &num_colors, &chars_per_pixel) != 4
4031 || width <= 0 || height <= 0
4032 || num_colors <= 0 || chars_per_pixel <= 0)
4033 goto failure;
4035 if (!check_image_size (f, width, height))
4037 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
4038 goto failure;
4041 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0)
4042 #ifndef HAVE_NS
4043 || !image_create_x_image_and_pixmap (f, img, width, height, 1,
4044 &mask_img, 1)
4045 #endif
4048 image_error ("Image too large", Qnil, Qnil);
4049 goto failure;
4052 expect (',');
4054 XSETFRAME (frame, f);
4055 if (!NILP (Fxw_display_color_p (frame)))
4056 best_key = XPM_COLOR_KEY_C;
4057 else if (!NILP (Fx_display_grayscale_p (frame)))
4058 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4059 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4060 else
4061 best_key = XPM_COLOR_KEY_M;
4063 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4064 if (chars_per_pixel == 1)
4065 color_table = xpm_make_color_table_v (&put_color_table,
4066 &get_color_table);
4067 else
4068 color_table = xpm_make_color_table_h (&put_color_table,
4069 &get_color_table);
4071 while (num_colors-- > 0)
4073 char *color, *max_color;
4074 int key, next_key, max_key = 0;
4075 Lisp_Object symbol_color = Qnil, color_val;
4076 XColor cdef;
4078 expect (XPM_TK_STRING);
4079 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4080 goto failure;
4081 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4082 buffer[len - chars_per_pixel] = '\0';
4084 str = strtok (buffer, " \t");
4085 if (str == NULL)
4086 goto failure;
4087 key = xpm_str_to_color_key (str);
4088 if (key < 0)
4089 goto failure;
4092 color = strtok (NULL, " \t");
4093 if (color == NULL)
4094 goto failure;
4096 while ((str = strtok (NULL, " \t")) != NULL)
4098 next_key = xpm_str_to_color_key (str);
4099 if (next_key >= 0)
4100 break;
4101 color[strlen (color)] = ' ';
4104 if (key == XPM_COLOR_KEY_S)
4106 if (NILP (symbol_color))
4107 symbol_color = build_string (color);
4109 else if (max_key < key && key <= best_key)
4111 max_key = key;
4112 max_color = color;
4114 key = next_key;
4116 while (str);
4118 color_val = Qnil;
4119 if (!NILP (color_symbols) && !NILP (symbol_color))
4121 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4123 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4125 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
4126 color_val = Qt;
4127 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
4128 &cdef, 0))
4129 color_val = make_number (cdef.pixel);
4132 if (NILP (color_val) && max_key > 0)
4134 if (xstrcasecmp (max_color, "None") == 0)
4135 color_val = Qt;
4136 else if (x_defined_color (f, max_color, &cdef, 0))
4137 color_val = make_number (cdef.pixel);
4139 if (!NILP (color_val))
4140 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4142 expect (',');
4145 for (y = 0; y < height; y++)
4147 expect (XPM_TK_STRING);
4148 str = beg;
4149 if (len < width * chars_per_pixel)
4150 goto failure;
4151 for (x = 0; x < width; x++, str += chars_per_pixel)
4153 Lisp_Object color_val =
4154 (*get_color_table) (color_table, str, chars_per_pixel);
4156 XPutPixel (ximg, x, y,
4157 (INTEGERP (color_val) ? XINT (color_val)
4158 : FRAME_FOREGROUND_PIXEL (f)));
4159 #ifndef HAVE_NS
4160 XPutPixel (mask_img, x, y,
4161 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4162 : (have_mask = true, PIX_MASK_RETAIN)));
4163 #else
4164 if (EQ (color_val, Qt))
4165 ns_set_alpha (ximg, x, y, 0);
4166 #endif
4168 if (y + 1 < height)
4169 expect (',');
4172 img->width = width;
4173 img->height = height;
4175 /* Maybe fill in the background field while we have ximg handy. */
4176 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4177 IMAGE_BACKGROUND (img, f, ximg);
4179 image_put_x_image (f, img, ximg, 0);
4180 #ifndef HAVE_NS
4181 if (have_mask)
4183 /* Fill in the background_transparent field while we have the
4184 mask handy. */
4185 image_background_transparent (img, f, mask_img);
4187 image_put_x_image (f, img, mask_img, 1);
4189 else
4191 x_destroy_x_image (mask_img);
4192 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4194 #endif
4195 return 1;
4197 failure:
4198 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4199 x_destroy_x_image (ximg);
4200 x_destroy_x_image (mask_img);
4201 x_clear_image (f, img);
4202 return 0;
4204 #undef match
4205 #undef expect
4206 #undef expect_ident
4209 static bool
4210 xpm_load (struct frame *f,
4211 struct image *img)
4213 bool success_p = 0;
4214 Lisp_Object file_name;
4216 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4217 file_name = image_spec_value (img->spec, QCfile, NULL);
4218 if (STRINGP (file_name))
4220 Lisp_Object file;
4221 unsigned char *contents;
4222 ptrdiff_t size;
4224 file = x_find_image_file (file_name);
4225 if (!STRINGP (file))
4227 image_error ("Cannot find image file `%s'", file_name, Qnil);
4228 return 0;
4231 contents = slurp_file (SSDATA (file), &size);
4232 if (contents == NULL)
4234 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4235 return 0;
4238 success_p = xpm_load_image (f, img, contents, contents + size);
4239 xfree (contents);
4241 else
4243 Lisp_Object data;
4245 data = image_spec_value (img->spec, QCdata, NULL);
4246 if (!STRINGP (data))
4248 image_error ("Invalid image data `%s'", data, Qnil);
4249 return 0;
4251 success_p = xpm_load_image (f, img, SDATA (data),
4252 SDATA (data) + SBYTES (data));
4255 return success_p;
4258 #endif /* HAVE_NS && !HAVE_XPM */
4262 /***********************************************************************
4263 Color table
4264 ***********************************************************************/
4266 #ifdef COLOR_TABLE_SUPPORT
4268 /* An entry in the color table mapping an RGB color to a pixel color. */
4270 struct ct_color
4272 int r, g, b;
4273 unsigned long pixel;
4275 /* Next in color table collision list. */
4276 struct ct_color *next;
4279 /* The bucket vector size to use. Must be prime. */
4281 #define CT_SIZE 101
4283 /* Value is a hash of the RGB color given by R, G, and B. */
4285 static unsigned
4286 ct_hash_rgb (unsigned r, unsigned g, unsigned b)
4288 return (r << 16) ^ (g << 8) ^ b;
4291 /* The color hash table. */
4293 static struct ct_color **ct_table;
4295 /* Number of entries in the color table. */
4297 static int ct_colors_allocated;
4298 enum
4300 ct_colors_allocated_max =
4301 min (INT_MAX,
4302 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4305 /* Initialize the color table. */
4307 static void
4308 init_color_table (void)
4310 int size = CT_SIZE * sizeof (*ct_table);
4311 ct_table = xzalloc (size);
4312 ct_colors_allocated = 0;
4316 /* Free memory associated with the color table. */
4318 static void
4319 free_color_table (void)
4321 int i;
4322 struct ct_color *p, *next;
4324 for (i = 0; i < CT_SIZE; ++i)
4325 for (p = ct_table[i]; p; p = next)
4327 next = p->next;
4328 xfree (p);
4331 xfree (ct_table);
4332 ct_table = NULL;
4336 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4337 entry for that color already is in the color table, return the
4338 pixel color of that entry. Otherwise, allocate a new color for R,
4339 G, B, and make an entry in the color table. */
4341 static unsigned long
4342 lookup_rgb_color (struct frame *f, int r, int g, int b)
4344 unsigned hash = ct_hash_rgb (r, g, b);
4345 int i = hash % CT_SIZE;
4346 struct ct_color *p;
4347 Display_Info *dpyinfo;
4349 /* Handle TrueColor visuals specially, which improves performance by
4350 two orders of magnitude. Freeing colors on TrueColor visuals is
4351 a nop, and pixel colors specify RGB values directly. See also
4352 the Xlib spec, chapter 3.1. */
4353 dpyinfo = FRAME_DISPLAY_INFO (f);
4354 if (dpyinfo->red_bits > 0)
4356 unsigned long pr, pg, pb;
4358 /* Apply gamma-correction like normal color allocation does. */
4359 if (f->gamma)
4361 XColor color;
4362 color.red = r, color.green = g, color.blue = b;
4363 gamma_correct (f, &color);
4364 r = color.red, g = color.green, b = color.blue;
4367 /* Scale down RGB values to the visual's bits per RGB, and shift
4368 them to the right position in the pixel color. Note that the
4369 original RGB values are 16-bit values, as usual in X. */
4370 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4371 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4372 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4374 /* Assemble the pixel color. */
4375 return pr | pg | pb;
4378 for (p = ct_table[i]; p; p = p->next)
4379 if (p->r == r && p->g == g && p->b == b)
4380 break;
4382 if (p == NULL)
4385 #ifdef HAVE_X_WINDOWS
4386 XColor color;
4387 Colormap cmap;
4388 bool rc;
4389 #else
4390 COLORREF color;
4391 #endif
4393 if (ct_colors_allocated_max <= ct_colors_allocated)
4394 return FRAME_FOREGROUND_PIXEL (f);
4396 #ifdef HAVE_X_WINDOWS
4397 color.red = r;
4398 color.green = g;
4399 color.blue = b;
4401 cmap = FRAME_X_COLORMAP (f);
4402 rc = x_alloc_nearest_color (f, cmap, &color);
4403 if (rc)
4405 ++ct_colors_allocated;
4406 p = xmalloc (sizeof *p);
4407 p->r = r;
4408 p->g = g;
4409 p->b = b;
4410 p->pixel = color.pixel;
4411 p->next = ct_table[i];
4412 ct_table[i] = p;
4414 else
4415 return FRAME_FOREGROUND_PIXEL (f);
4417 #else
4418 #ifdef HAVE_NTGUI
4419 color = PALETTERGB (r, g, b);
4420 #else
4421 color = RGB_TO_ULONG (r, g, b);
4422 #endif /* HAVE_NTGUI */
4423 ++ct_colors_allocated;
4424 p = xmalloc (sizeof *p);
4425 p->r = r;
4426 p->g = g;
4427 p->b = b;
4428 p->pixel = color;
4429 p->next = ct_table[i];
4430 ct_table[i] = p;
4431 #endif /* HAVE_X_WINDOWS */
4435 return p->pixel;
4439 /* Look up pixel color PIXEL which is used on frame F in the color
4440 table. If not already present, allocate it. Value is PIXEL. */
4442 static unsigned long
4443 lookup_pixel_color (struct frame *f, unsigned long pixel)
4445 int i = pixel % CT_SIZE;
4446 struct ct_color *p;
4448 for (p = ct_table[i]; p; p = p->next)
4449 if (p->pixel == pixel)
4450 break;
4452 if (p == NULL)
4454 XColor color;
4455 Colormap cmap;
4456 bool rc;
4458 if (ct_colors_allocated_max <= ct_colors_allocated)
4459 return FRAME_FOREGROUND_PIXEL (f);
4461 #ifdef HAVE_X_WINDOWS
4462 cmap = FRAME_X_COLORMAP (f);
4463 color.pixel = pixel;
4464 x_query_color (f, &color);
4465 rc = x_alloc_nearest_color (f, cmap, &color);
4466 #else
4467 block_input ();
4468 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4469 color.pixel = pixel;
4470 XQueryColor (NULL, cmap, &color);
4471 rc = x_alloc_nearest_color (f, cmap, &color);
4472 unblock_input ();
4473 #endif /* HAVE_X_WINDOWS */
4475 if (rc)
4477 ++ct_colors_allocated;
4479 p = xmalloc (sizeof *p);
4480 p->r = color.red;
4481 p->g = color.green;
4482 p->b = color.blue;
4483 p->pixel = pixel;
4484 p->next = ct_table[i];
4485 ct_table[i] = p;
4487 else
4488 return FRAME_FOREGROUND_PIXEL (f);
4490 return p->pixel;
4494 /* Value is a vector of all pixel colors contained in the color table,
4495 allocated via xmalloc. Set *N to the number of colors. */
4497 static unsigned long *
4498 colors_in_color_table (int *n)
4500 int i, j;
4501 struct ct_color *p;
4502 unsigned long *colors;
4504 if (ct_colors_allocated == 0)
4506 *n = 0;
4507 colors = NULL;
4509 else
4511 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4512 *n = ct_colors_allocated;
4514 for (i = j = 0; i < CT_SIZE; ++i)
4515 for (p = ct_table[i]; p; p = p->next)
4516 colors[j++] = p->pixel;
4519 return colors;
4522 #else /* COLOR_TABLE_SUPPORT */
4524 static unsigned long
4525 lookup_rgb_color (struct frame *f, int r, int g, int b)
4527 unsigned long pixel;
4529 #ifdef HAVE_NTGUI
4530 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4531 #endif /* HAVE_NTGUI */
4533 #ifdef HAVE_NS
4534 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4535 #endif /* HAVE_NS */
4536 return pixel;
4539 static void
4540 init_color_table (void)
4543 #endif /* COLOR_TABLE_SUPPORT */
4546 /***********************************************************************
4547 Algorithms
4548 ***********************************************************************/
4550 /* Edge detection matrices for different edge-detection
4551 strategies. */
4553 static int emboss_matrix[9] = {
4554 /* x - 1 x x + 1 */
4555 2, -1, 0, /* y - 1 */
4556 -1, 0, 1, /* y */
4557 0, 1, -2 /* y + 1 */
4560 static int laplace_matrix[9] = {
4561 /* x - 1 x x + 1 */
4562 1, 0, 0, /* y - 1 */
4563 0, 0, 0, /* y */
4564 0, 0, -1 /* y + 1 */
4567 /* Value is the intensity of the color whose red/green/blue values
4568 are R, G, and B. */
4570 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4573 /* On frame F, return an array of XColor structures describing image
4574 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4575 means also fill the red/green/blue members of the XColor
4576 structures. Value is a pointer to the array of XColors structures,
4577 allocated with xmalloc; it must be freed by the caller. */
4579 static XColor *
4580 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4582 int x, y;
4583 XColor *colors, *p;
4584 XImagePtr_or_DC ximg;
4585 #ifdef HAVE_NTGUI
4586 HGDIOBJ prev;
4587 #endif /* HAVE_NTGUI */
4589 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width < img->height)
4590 memory_full (SIZE_MAX);
4591 colors = xmalloc (sizeof *colors * img->width * img->height);
4593 /* Get the X image or create a memory device context for IMG. */
4594 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4596 /* Fill the `pixel' members of the XColor array. I wished there
4597 were an easy and portable way to circumvent XGetPixel. */
4598 p = colors;
4599 for (y = 0; y < img->height; ++y)
4601 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4602 XColor *row = p;
4603 for (x = 0; x < img->width; ++x, ++p)
4604 p->pixel = GET_PIXEL (ximg, x, y);
4605 if (rgb_p)
4606 x_query_colors (f, row, img->width);
4608 #else
4610 for (x = 0; x < img->width; ++x, ++p)
4612 /* W32_TODO: palette support needed here? */
4613 p->pixel = GET_PIXEL (ximg, x, y);
4614 if (rgb_p)
4616 p->red = RED16_FROM_ULONG (p->pixel);
4617 p->green = GREEN16_FROM_ULONG (p->pixel);
4618 p->blue = BLUE16_FROM_ULONG (p->pixel);
4621 #endif /* HAVE_X_WINDOWS */
4624 image_unget_x_image_or_dc (img, 0, ximg, prev);
4626 return colors;
4629 #ifdef HAVE_NTGUI
4631 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4632 created with CreateDIBSection, with the pointer to the bit values
4633 stored in ximg->data. */
4635 static void
4636 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4638 int width = ximg->info.bmiHeader.biWidth;
4639 unsigned char * pixel;
4641 /* True color images. */
4642 if (ximg->info.bmiHeader.biBitCount == 24)
4644 int rowbytes = width * 3;
4645 /* Ensure scanlines are aligned on 4 byte boundaries. */
4646 if (rowbytes % 4)
4647 rowbytes += 4 - (rowbytes % 4);
4649 pixel = ximg->data + y * rowbytes + x * 3;
4650 /* Windows bitmaps are in BGR order. */
4651 *pixel = GetBValue (color);
4652 *(pixel + 1) = GetGValue (color);
4653 *(pixel + 2) = GetRValue (color);
4655 /* Monochrome images. */
4656 else if (ximg->info.bmiHeader.biBitCount == 1)
4658 int rowbytes = width / 8;
4659 /* Ensure scanlines are aligned on 4 byte boundaries. */
4660 if (rowbytes % 4)
4661 rowbytes += 4 - (rowbytes % 4);
4662 pixel = ximg->data + y * rowbytes + x / 8;
4663 /* Filter out palette info. */
4664 if (color & 0x00ffffff)
4665 *pixel = *pixel | (1 << x % 8);
4666 else
4667 *pixel = *pixel & ~(1 << x % 8);
4669 else
4670 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4673 #endif /* HAVE_NTGUI */
4675 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4676 RGB members are set. F is the frame on which this all happens.
4677 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4679 static void
4680 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4682 int x, y;
4683 XImagePtr oimg = NULL;
4684 XColor *p;
4686 init_color_table ();
4688 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP | CLEAR_IMAGE_COLORS);
4689 image_create_x_image_and_pixmap (f, img, img->width, img->height, 0,
4690 &oimg, 0);
4691 p = colors;
4692 for (y = 0; y < img->height; ++y)
4693 for (x = 0; x < img->width; ++x, ++p)
4695 unsigned long pixel;
4696 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4697 XPutPixel (oimg, x, y, pixel);
4700 xfree (colors);
4702 image_put_x_image (f, img, oimg, 0);
4703 #ifdef COLOR_TABLE_SUPPORT
4704 img->colors = colors_in_color_table (&img->ncolors);
4705 free_color_table ();
4706 #endif /* COLOR_TABLE_SUPPORT */
4710 /* On frame F, perform edge-detection on image IMG.
4712 MATRIX is a nine-element array specifying the transformation
4713 matrix. See emboss_matrix for an example.
4715 COLOR_ADJUST is a color adjustment added to each pixel of the
4716 outgoing image. */
4718 static void
4719 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4721 XColor *colors = x_to_xcolors (f, img, 1);
4722 XColor *new, *p;
4723 int x, y, i, sum;
4725 for (i = sum = 0; i < 9; ++i)
4726 sum += eabs (matrix[i]);
4728 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4730 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width < img->height)
4731 memory_full (SIZE_MAX);
4732 new = xmalloc (sizeof *new * img->width * img->height);
4734 for (y = 0; y < img->height; ++y)
4736 p = COLOR (new, 0, y);
4737 p->red = p->green = p->blue = 0xffff/2;
4738 p = COLOR (new, img->width - 1, y);
4739 p->red = p->green = p->blue = 0xffff/2;
4742 for (x = 1; x < img->width - 1; ++x)
4744 p = COLOR (new, x, 0);
4745 p->red = p->green = p->blue = 0xffff/2;
4746 p = COLOR (new, x, img->height - 1);
4747 p->red = p->green = p->blue = 0xffff/2;
4750 for (y = 1; y < img->height - 1; ++y)
4752 p = COLOR (new, 1, y);
4754 for (x = 1; x < img->width - 1; ++x, ++p)
4756 int r, g, b, yy, xx;
4758 r = g = b = i = 0;
4759 for (yy = y - 1; yy < y + 2; ++yy)
4760 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4761 if (matrix[i])
4763 XColor *t = COLOR (colors, xx, yy);
4764 r += matrix[i] * t->red;
4765 g += matrix[i] * t->green;
4766 b += matrix[i] * t->blue;
4769 r = (r / sum + color_adjust) & 0xffff;
4770 g = (g / sum + color_adjust) & 0xffff;
4771 b = (b / sum + color_adjust) & 0xffff;
4772 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4776 xfree (colors);
4777 x_from_xcolors (f, img, new);
4779 #undef COLOR
4783 /* Perform the pre-defined `emboss' edge-detection on image IMG
4784 on frame F. */
4786 static void
4787 x_emboss (struct frame *f, struct image *img)
4789 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4793 /* Transform image IMG which is used on frame F with a Laplace
4794 edge-detection algorithm. The result is an image that can be used
4795 to draw disabled buttons, for example. */
4797 static void
4798 x_laplace (struct frame *f, struct image *img)
4800 x_detect_edges (f, img, laplace_matrix, 45000);
4804 /* Perform edge-detection on image IMG on frame F, with specified
4805 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4807 MATRIX must be either
4809 - a list of at least 9 numbers in row-major form
4810 - a vector of at least 9 numbers
4812 COLOR_ADJUST nil means use a default; otherwise it must be a
4813 number. */
4815 static void
4816 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4817 Lisp_Object color_adjust)
4819 int i = 0;
4820 int trans[9];
4822 if (CONSP (matrix))
4824 for (i = 0;
4825 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4826 ++i, matrix = XCDR (matrix))
4827 trans[i] = XFLOATINT (XCAR (matrix));
4829 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4831 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4832 trans[i] = XFLOATINT (AREF (matrix, i));
4835 if (NILP (color_adjust))
4836 color_adjust = make_number (0xffff / 2);
4838 if (i == 9 && NUMBERP (color_adjust))
4839 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4843 /* Transform image IMG on frame F so that it looks disabled. */
4845 static void
4846 x_disable_image (struct frame *f, struct image *img)
4848 Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
4849 #ifdef HAVE_NTGUI
4850 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4851 #else
4852 int n_planes = dpyinfo->n_planes;
4853 #endif /* HAVE_NTGUI */
4855 if (n_planes >= 2)
4857 /* Color (or grayscale). Convert to gray, and equalize. Just
4858 drawing such images with a stipple can look very odd, so
4859 we're using this method instead. */
4860 XColor *colors = x_to_xcolors (f, img, 1);
4861 XColor *p, *end;
4862 const int h = 15000;
4863 const int l = 30000;
4865 for (p = colors, end = colors + img->width * img->height;
4866 p < end;
4867 ++p)
4869 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4870 int i2 = (0xffff - h - l) * i / 0xffff + l;
4871 p->red = p->green = p->blue = i2;
4874 x_from_xcolors (f, img, colors);
4877 /* Draw a cross over the disabled image, if we must or if we
4878 should. */
4879 if (n_planes < 2 || cross_disabled_images)
4881 #ifndef HAVE_NTGUI
4882 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4884 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4886 Display *dpy = FRAME_X_DISPLAY (f);
4887 GC gc;
4889 image_sync_to_pixmaps (f, img);
4890 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4891 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4892 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4893 img->width - 1, img->height - 1);
4894 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4895 img->width - 1, 0);
4896 XFreeGC (dpy, gc);
4898 if (img->mask)
4900 gc = XCreateGC (dpy, img->mask, 0, NULL);
4901 XSetForeground (dpy, gc, MaskForeground (f));
4902 XDrawLine (dpy, img->mask, gc, 0, 0,
4903 img->width - 1, img->height - 1);
4904 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4905 img->width - 1, 0);
4906 XFreeGC (dpy, gc);
4908 #endif /* !HAVE_NS */
4909 #else
4910 HDC hdc, bmpdc;
4911 HGDIOBJ prev;
4913 hdc = get_frame_dc (f);
4914 bmpdc = CreateCompatibleDC (hdc);
4915 release_frame_dc (f, hdc);
4917 prev = SelectObject (bmpdc, img->pixmap);
4919 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4920 MoveToEx (bmpdc, 0, 0, NULL);
4921 LineTo (bmpdc, img->width - 1, img->height - 1);
4922 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4923 LineTo (bmpdc, img->width - 1, 0);
4925 if (img->mask)
4927 SelectObject (bmpdc, img->mask);
4928 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4929 MoveToEx (bmpdc, 0, 0, NULL);
4930 LineTo (bmpdc, img->width - 1, img->height - 1);
4931 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4932 LineTo (bmpdc, img->width - 1, 0);
4934 SelectObject (bmpdc, prev);
4935 DeleteDC (bmpdc);
4936 #endif /* HAVE_NTGUI */
4941 /* Build a mask for image IMG which is used on frame F. FILE is the
4942 name of an image file, for error messages. HOW determines how to
4943 determine the background color of IMG. If it is a list '(R G B)',
4944 with R, G, and B being integers >= 0, take that as the color of the
4945 background. Otherwise, determine the background color of IMG
4946 heuristically. */
4948 static void
4949 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4951 XImagePtr_or_DC ximg;
4952 #ifndef HAVE_NTGUI
4953 XImagePtr mask_img;
4954 #else
4955 HGDIOBJ prev;
4956 char *mask_img;
4957 int row_width;
4958 #endif /* HAVE_NTGUI */
4959 int x, y;
4960 bool use_img_background;
4961 unsigned long bg = 0;
4963 if (img->mask)
4964 x_clear_image_1 (f, img, CLEAR_IMAGE_MASK);
4966 #ifndef HAVE_NTGUI
4967 #ifndef HAVE_NS
4968 /* Create an image and pixmap serving as mask. */
4969 if (! image_create_x_image_and_pixmap (f, img, img->width, img->height, 1,
4970 &mask_img, 1))
4971 return;
4972 #endif /* !HAVE_NS */
4973 #else
4974 /* Create the bit array serving as mask. */
4975 row_width = (img->width + 7) / 8;
4976 mask_img = xzalloc (row_width * img->height);
4977 #endif /* HAVE_NTGUI */
4979 /* Get the X image or create a memory device context for IMG. */
4980 ximg = image_get_x_image_or_dc (f, img, 0, &prev);
4982 /* Determine the background color of ximg. If HOW is `(R G B)'
4983 take that as color. Otherwise, use the image's background color. */
4984 use_img_background = 1;
4986 if (CONSP (how))
4988 int rgb[3], i;
4990 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4992 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4993 how = XCDR (how);
4996 if (i == 3 && NILP (how))
4998 char color_name[30];
4999 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
5000 bg = (
5001 #ifdef HAVE_NTGUI
5002 0x00ffffff & /* Filter out palette info. */
5003 #endif /* HAVE_NTGUI */
5004 x_alloc_image_color (f, img, build_string (color_name), 0));
5005 use_img_background = 0;
5009 if (use_img_background)
5010 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5012 /* Set all bits in mask_img to 1 whose color in ximg is different
5013 from the background color bg. */
5014 #ifndef HAVE_NTGUI
5015 for (y = 0; y < img->height; ++y)
5016 for (x = 0; x < img->width; ++x)
5017 #ifndef HAVE_NS
5018 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5019 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5020 #else
5021 if (XGetPixel (ximg, x, y) == bg)
5022 ns_set_alpha (ximg, x, y, 0);
5023 #endif /* HAVE_NS */
5024 #ifndef HAVE_NS
5025 /* Fill in the background_transparent field while we have the mask handy. */
5026 image_background_transparent (img, f, mask_img);
5028 /* Put mask_img into the image. */
5029 image_put_x_image (f, img, mask_img, 1);
5030 #endif /* !HAVE_NS */
5031 #else
5032 for (y = 0; y < img->height; ++y)
5033 for (x = 0; x < img->width; ++x)
5035 COLORREF p = GetPixel (ximg, x, y);
5036 if (p != bg)
5037 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5040 /* Create the mask image. */
5041 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5042 mask_img);
5043 /* Fill in the background_transparent field while we have the mask handy. */
5044 SelectObject (ximg, img->mask);
5045 image_background_transparent (img, f, ximg);
5047 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5048 xfree (mask_img);
5049 #endif /* HAVE_NTGUI */
5051 image_unget_x_image_or_dc (img, 0, ximg, prev);
5055 /***********************************************************************
5056 PBM (mono, gray, color)
5057 ***********************************************************************/
5059 static bool pbm_image_p (Lisp_Object object);
5060 static bool pbm_load (struct frame *f, struct image *img);
5062 /* The symbol `pbm' identifying images of this type. */
5064 static Lisp_Object Qpbm;
5066 /* Indices of image specification fields in gs_format, below. */
5068 enum pbm_keyword_index
5070 PBM_TYPE,
5071 PBM_FILE,
5072 PBM_DATA,
5073 PBM_ASCENT,
5074 PBM_MARGIN,
5075 PBM_RELIEF,
5076 PBM_ALGORITHM,
5077 PBM_HEURISTIC_MASK,
5078 PBM_MASK,
5079 PBM_FOREGROUND,
5080 PBM_BACKGROUND,
5081 PBM_LAST
5084 /* Vector of image_keyword structures describing the format
5085 of valid user-defined image specifications. */
5087 static const struct image_keyword pbm_format[PBM_LAST] =
5089 {":type", IMAGE_SYMBOL_VALUE, 1},
5090 {":file", IMAGE_STRING_VALUE, 0},
5091 {":data", IMAGE_STRING_VALUE, 0},
5092 {":ascent", IMAGE_ASCENT_VALUE, 0},
5093 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5094 {":relief", IMAGE_INTEGER_VALUE, 0},
5095 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5096 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5097 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5098 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5099 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5102 /* Structure describing the image type `pbm'. */
5104 static struct image_type pbm_type =
5106 &Qpbm,
5107 pbm_image_p,
5108 pbm_load,
5109 x_clear_image,
5110 NULL,
5111 NULL
5115 /* Return true if OBJECT is a valid PBM image specification. */
5117 static bool
5118 pbm_image_p (Lisp_Object object)
5120 struct image_keyword fmt[PBM_LAST];
5122 memcpy (fmt, pbm_format, sizeof fmt);
5124 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5125 return 0;
5127 /* Must specify either :data or :file. */
5128 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5132 /* Get next char skipping comments in Netpbm header. Returns -1 at
5133 end of input. */
5135 static int
5136 pbm_next_char (unsigned char **s, unsigned char *end)
5138 int c = -1;
5140 while (*s < end && (c = *(*s)++, c == '#'))
5142 /* Skip to the next line break. */
5143 while (*s < end && (c = *(*s)++, c != '\n' && c != '\r'))
5146 c = -1;
5149 return c;
5153 /* Scan a decimal number from *S and return it. Advance *S while
5154 reading the number. END is the end of the string. Value is -1 at
5155 end of input. */
5157 static int
5158 pbm_scan_number (unsigned char **s, unsigned char *end)
5160 int c = 0, val = -1;
5162 /* Skip white-space. */
5163 while ((c = pbm_next_char (s, end)) != -1 && c_isspace (c))
5166 if (c_isdigit (c))
5168 /* Read decimal number. */
5169 val = c - '0';
5170 while ((c = pbm_next_char (s, end)) != -1 && c_isdigit (c))
5171 val = 10 * val + c - '0';
5174 return val;
5178 /* Load PBM image IMG for use on frame F. */
5180 static bool
5181 pbm_load (struct frame *f, struct image *img)
5183 bool raw_p;
5184 int x, y;
5185 int width, height, max_color_idx = 0;
5186 XImagePtr ximg;
5187 Lisp_Object file, specified_file;
5188 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5189 unsigned char *contents = NULL;
5190 unsigned char *end, *p;
5191 ptrdiff_t size;
5193 specified_file = image_spec_value (img->spec, QCfile, NULL);
5195 if (STRINGP (specified_file))
5197 file = x_find_image_file (specified_file);
5198 if (!STRINGP (file))
5200 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5201 return 0;
5204 contents = slurp_file (SSDATA (file), &size);
5205 if (contents == NULL)
5207 image_error ("Error reading `%s'", file, Qnil);
5208 return 0;
5211 p = contents;
5212 end = contents + size;
5214 else
5216 Lisp_Object data;
5217 data = image_spec_value (img->spec, QCdata, NULL);
5218 if (!STRINGP (data))
5220 image_error ("Invalid image data `%s'", data, Qnil);
5221 return 0;
5223 p = SDATA (data);
5224 end = p + SBYTES (data);
5227 /* Check magic number. */
5228 if (end - p < 2 || *p++ != 'P')
5230 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5231 error:
5232 xfree (contents);
5233 img->pixmap = NO_PIXMAP;
5234 return 0;
5237 switch (*p++)
5239 case '1':
5240 raw_p = 0, type = PBM_MONO;
5241 break;
5243 case '2':
5244 raw_p = 0, type = PBM_GRAY;
5245 break;
5247 case '3':
5248 raw_p = 0, type = PBM_COLOR;
5249 break;
5251 case '4':
5252 raw_p = 1, type = PBM_MONO;
5253 break;
5255 case '5':
5256 raw_p = 1, type = PBM_GRAY;
5257 break;
5259 case '6':
5260 raw_p = 1, type = PBM_COLOR;
5261 break;
5263 default:
5264 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5265 goto error;
5268 /* Read width, height, maximum color-component. Characters
5269 starting with `#' up to the end of a line are ignored. */
5270 width = pbm_scan_number (&p, end);
5271 height = pbm_scan_number (&p, end);
5273 if (type != PBM_MONO)
5275 max_color_idx = pbm_scan_number (&p, end);
5276 if (max_color_idx > 65535 || max_color_idx < 0)
5278 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5279 goto error;
5283 if (!check_image_size (f, width, height))
5285 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5286 goto error;
5289 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5290 goto error;
5292 /* Initialize the color hash table. */
5293 init_color_table ();
5295 if (type == PBM_MONO)
5297 int c = 0, g;
5298 struct image_keyword fmt[PBM_LAST];
5299 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5300 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5302 /* Parse the image specification. */
5303 memcpy (fmt, pbm_format, sizeof fmt);
5304 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5306 /* Get foreground and background colors, maybe allocate colors. */
5307 if (fmt[PBM_FOREGROUND].count
5308 && STRINGP (fmt[PBM_FOREGROUND].value))
5309 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5310 if (fmt[PBM_BACKGROUND].count
5311 && STRINGP (fmt[PBM_BACKGROUND].value))
5313 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5314 img->background = bg;
5315 img->background_valid = 1;
5318 for (y = 0; y < height; ++y)
5319 for (x = 0; x < width; ++x)
5321 if (raw_p)
5323 if ((x & 7) == 0)
5325 if (p >= end)
5327 x_destroy_x_image (ximg);
5328 x_clear_image (f, img);
5329 image_error ("Invalid image size in image `%s'",
5330 img->spec, Qnil);
5331 goto error;
5333 c = *p++;
5335 g = c & 0x80;
5336 c <<= 1;
5338 else
5339 g = pbm_scan_number (&p, end);
5341 XPutPixel (ximg, x, y, g ? fg : bg);
5344 else
5346 int expected_size = height * width;
5347 if (max_color_idx > 255)
5348 expected_size *= 2;
5349 if (type == PBM_COLOR)
5350 expected_size *= 3;
5352 if (raw_p && p + expected_size > end)
5354 x_destroy_x_image (ximg);
5355 x_clear_image (f, img);
5356 image_error ("Invalid image size in image `%s'",
5357 img->spec, Qnil);
5358 goto error;
5361 for (y = 0; y < height; ++y)
5362 for (x = 0; x < width; ++x)
5364 int r, g, b;
5366 if (type == PBM_GRAY && raw_p)
5368 r = g = b = *p++;
5369 if (max_color_idx > 255)
5370 r = g = b = r * 256 + *p++;
5372 else if (type == PBM_GRAY)
5373 r = g = b = pbm_scan_number (&p, end);
5374 else if (raw_p)
5376 r = *p++;
5377 if (max_color_idx > 255)
5378 r = r * 256 + *p++;
5379 g = *p++;
5380 if (max_color_idx > 255)
5381 g = g * 256 + *p++;
5382 b = *p++;
5383 if (max_color_idx > 255)
5384 b = b * 256 + *p++;
5386 else
5388 r = pbm_scan_number (&p, end);
5389 g = pbm_scan_number (&p, end);
5390 b = pbm_scan_number (&p, end);
5393 if (r < 0 || g < 0 || b < 0)
5395 x_destroy_x_image (ximg);
5396 image_error ("Invalid pixel value in image `%s'",
5397 img->spec, Qnil);
5398 goto error;
5401 /* RGB values are now in the range 0..max_color_idx.
5402 Scale this to the range 0..0xffff supported by X. */
5403 r = (double) r * 65535 / max_color_idx;
5404 g = (double) g * 65535 / max_color_idx;
5405 b = (double) b * 65535 / max_color_idx;
5406 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5410 #ifdef COLOR_TABLE_SUPPORT
5411 /* Store in IMG->colors the colors allocated for the image, and
5412 free the color table. */
5413 img->colors = colors_in_color_table (&img->ncolors);
5414 free_color_table ();
5415 #endif /* COLOR_TABLE_SUPPORT */
5417 img->width = width;
5418 img->height = height;
5420 /* Maybe fill in the background field while we have ximg handy. */
5422 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5423 /* Casting avoids a GCC warning. */
5424 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5426 /* Put ximg into the image. */
5427 image_put_x_image (f, img, ximg, 0);
5429 /* X and W32 versions did it here, MAC version above. ++kfs
5430 img->width = width;
5431 img->height = height; */
5433 xfree (contents);
5434 return 1;
5438 /***********************************************************************
5440 ***********************************************************************/
5442 #if defined (HAVE_PNG) || defined (HAVE_NS)
5444 /* Function prototypes. */
5446 static bool png_image_p (Lisp_Object object);
5447 static bool png_load (struct frame *f, struct image *img);
5449 /* The symbol `png' identifying images of this type. */
5451 static Lisp_Object Qpng;
5453 /* Indices of image specification fields in png_format, below. */
5455 enum png_keyword_index
5457 PNG_TYPE,
5458 PNG_DATA,
5459 PNG_FILE,
5460 PNG_ASCENT,
5461 PNG_MARGIN,
5462 PNG_RELIEF,
5463 PNG_ALGORITHM,
5464 PNG_HEURISTIC_MASK,
5465 PNG_MASK,
5466 PNG_BACKGROUND,
5467 PNG_LAST
5470 /* Vector of image_keyword structures describing the format
5471 of valid user-defined image specifications. */
5473 static const struct image_keyword png_format[PNG_LAST] =
5475 {":type", IMAGE_SYMBOL_VALUE, 1},
5476 {":data", IMAGE_STRING_VALUE, 0},
5477 {":file", IMAGE_STRING_VALUE, 0},
5478 {":ascent", IMAGE_ASCENT_VALUE, 0},
5479 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5480 {":relief", IMAGE_INTEGER_VALUE, 0},
5481 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5482 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5483 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5484 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5487 #if defined HAVE_NTGUI && defined WINDOWSNT
5488 static bool init_png_functions (void);
5489 #else
5490 #define init_png_functions NULL
5491 #endif
5493 /* Structure describing the image type `png'. */
5495 static struct image_type png_type =
5497 &Qpng,
5498 png_image_p,
5499 png_load,
5500 x_clear_image,
5501 init_png_functions,
5502 NULL
5505 /* Return true if OBJECT is a valid PNG image specification. */
5507 static bool
5508 png_image_p (Lisp_Object object)
5510 struct image_keyword fmt[PNG_LAST];
5511 memcpy (fmt, png_format, sizeof fmt);
5513 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5514 return 0;
5516 /* Must specify either the :data or :file keyword. */
5517 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5520 #endif /* HAVE_PNG || HAVE_NS */
5523 #if defined HAVE_PNG && !defined HAVE_NS
5525 # ifdef WINDOWSNT
5526 /* PNG library details. */
5528 DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
5529 DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5530 DEF_DLL_FN (png_structp, png_create_read_struct,
5531 (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
5532 DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
5533 DEF_DLL_FN (void, png_destroy_read_struct,
5534 (png_structpp, png_infopp, png_infopp));
5535 DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5536 DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
5537 DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
5538 DEF_DLL_FN (png_uint_32, png_get_IHDR,
5539 (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
5540 int *, int *, int *, int *, int *));
5541 DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5542 DEF_DLL_FN (void, png_set_strip_16, (png_structp));
5543 DEF_DLL_FN (void, png_set_expand, (png_structp));
5544 DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
5545 DEF_DLL_FN (void, png_set_background,
5546 (png_structp, png_color_16p, int, int, double));
5547 DEF_DLL_FN (png_uint_32, png_get_bKGD,
5548 (png_structp, png_infop, png_color_16p *));
5549 DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
5550 DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
5551 DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5552 DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
5553 DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
5554 DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
5556 # if (PNG_LIBPNG_VER >= 10500)
5557 DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
5558 DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
5559 (png_structp, png_longjmp_ptr, size_t));
5560 # endif /* libpng version >= 1.5 */
5562 static bool
5563 init_png_functions (void)
5565 HMODULE library;
5567 if (!(library = w32_delayed_load (Qpng)))
5568 return 0;
5570 LOAD_DLL_FN (library, png_get_io_ptr);
5571 LOAD_DLL_FN (library, png_sig_cmp);
5572 LOAD_DLL_FN (library, png_create_read_struct);
5573 LOAD_DLL_FN (library, png_create_info_struct);
5574 LOAD_DLL_FN (library, png_destroy_read_struct);
5575 LOAD_DLL_FN (library, png_set_read_fn);
5576 LOAD_DLL_FN (library, png_set_sig_bytes);
5577 LOAD_DLL_FN (library, png_read_info);
5578 LOAD_DLL_FN (library, png_get_IHDR);
5579 LOAD_DLL_FN (library, png_get_valid);
5580 LOAD_DLL_FN (library, png_set_strip_16);
5581 LOAD_DLL_FN (library, png_set_expand);
5582 LOAD_DLL_FN (library, png_set_gray_to_rgb);
5583 LOAD_DLL_FN (library, png_set_background);
5584 LOAD_DLL_FN (library, png_get_bKGD);
5585 LOAD_DLL_FN (library, png_read_update_info);
5586 LOAD_DLL_FN (library, png_get_channels);
5587 LOAD_DLL_FN (library, png_get_rowbytes);
5588 LOAD_DLL_FN (library, png_read_image);
5589 LOAD_DLL_FN (library, png_read_end);
5590 LOAD_DLL_FN (library, png_error);
5592 # if (PNG_LIBPNG_VER >= 10500)
5593 LOAD_DLL_FN (library, png_longjmp);
5594 LOAD_DLL_FN (library, png_set_longjmp_fn);
5595 # endif /* libpng version >= 1.5 */
5597 return 1;
5600 # undef png_create_info_struct
5601 # undef png_create_read_struct
5602 # undef png_destroy_read_struct
5603 # undef png_error
5604 # undef png_get_bKGD
5605 # undef png_get_channels
5606 # undef png_get_IHDR
5607 # undef png_get_io_ptr
5608 # undef png_get_rowbytes
5609 # undef png_get_valid
5610 # undef png_longjmp
5611 # undef png_read_end
5612 # undef png_read_image
5613 # undef png_read_info
5614 # undef png_read_update_info
5615 # undef png_set_background
5616 # undef png_set_expand
5617 # undef png_set_gray_to_rgb
5618 # undef png_set_longjmp_fn
5619 # undef png_set_read_fn
5620 # undef png_set_sig_bytes
5621 # undef png_set_strip_16
5622 # undef png_sig_cmp
5624 # define png_create_info_struct fn_png_create_info_struct
5625 # define png_create_read_struct fn_png_create_read_struct
5626 # define png_destroy_read_struct fn_png_destroy_read_struct
5627 # define png_error fn_png_error
5628 # define png_get_bKGD fn_png_get_bKGD
5629 # define png_get_channels fn_png_get_channels
5630 # define png_get_IHDR fn_png_get_IHDR
5631 # define png_get_io_ptr fn_png_get_io_ptr
5632 # define png_get_rowbytes fn_png_get_rowbytes
5633 # define png_get_valid fn_png_get_valid
5634 # define png_longjmp fn_png_longjmp
5635 # define png_read_end fn_png_read_end
5636 # define png_read_image fn_png_read_image
5637 # define png_read_info fn_png_read_info
5638 # define png_read_update_info fn_png_read_update_info
5639 # define png_set_background fn_png_set_background
5640 # define png_set_expand fn_png_set_expand
5641 # define png_set_gray_to_rgb fn_png_set_gray_to_rgb
5642 # define png_set_longjmp_fn fn_png_set_longjmp_fn
5643 # define png_set_read_fn fn_png_set_read_fn
5644 # define png_set_sig_bytes fn_png_set_sig_bytes
5645 # define png_set_strip_16 fn_png_set_strip_16
5646 # define png_sig_cmp fn_png_sig_cmp
5648 # endif /* WINDOWSNT */
5650 /* Fast implementations of setjmp and longjmp. Although setjmp and longjmp
5651 will do, POSIX _setjmp and _longjmp (if available) are often faster.
5652 Do not use sys_setjmp, as PNG supports only jmp_buf.
5653 It's OK if the longjmp substitute restores the signal mask. */
5654 # ifdef HAVE__SETJMP
5655 # define FAST_SETJMP(j) _setjmp (j)
5656 # define FAST_LONGJMP _longjmp
5657 # else
5658 # define FAST_SETJMP(j) setjmp (j)
5659 # define FAST_LONGJMP longjmp
5660 # endif
5662 # if PNG_LIBPNG_VER < 10500
5663 # define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
5664 # define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5665 # else
5666 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5667 # define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
5668 # define PNG_JMPBUF(ptr) \
5669 (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
5670 # endif
5672 /* Error and warning handlers installed when the PNG library
5673 is initialized. */
5675 static _Noreturn void
5676 my_png_error (png_struct *png_ptr, const char *msg)
5678 eassert (png_ptr != NULL);
5679 /* Avoid compiler warning about deprecated direct access to
5680 png_ptr's fields in libpng versions 1.4.x. */
5681 image_error ("PNG error: %s", build_string (msg), Qnil);
5682 PNG_LONGJMP (png_ptr);
5686 static void
5687 my_png_warning (png_struct *png_ptr, const char *msg)
5689 eassert (png_ptr != NULL);
5690 image_error ("PNG warning: %s", build_string (msg), Qnil);
5693 /* Memory source for PNG decoding. */
5695 struct png_memory_storage
5697 unsigned char *bytes; /* The data */
5698 ptrdiff_t len; /* How big is it? */
5699 ptrdiff_t index; /* Where are we? */
5703 /* Function set as reader function when reading PNG image from memory.
5704 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5705 bytes from the input to DATA. */
5707 static void
5708 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5710 struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
5712 if (length > tbr->len - tbr->index)
5713 png_error (png_ptr, "Read error");
5715 memcpy (data, tbr->bytes + tbr->index, length);
5716 tbr->index = tbr->index + length;
5720 /* Function set as reader function when reading PNG image from a file.
5721 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5722 bytes from the input to DATA. */
5724 static void
5725 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5727 FILE *fp = png_get_io_ptr (png_ptr);
5729 if (fread (data, 1, length, fp) < length)
5730 png_error (png_ptr, "Read error");
5734 /* Load PNG image IMG for use on frame F. Value is true if
5735 successful. */
5737 struct png_load_context
5739 /* These are members so that longjmp doesn't munge local variables. */
5740 png_struct *png_ptr;
5741 png_info *info_ptr;
5742 png_info *end_info;
5743 FILE *fp;
5744 png_byte *pixels;
5745 png_byte **rows;
5748 static bool
5749 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5751 Lisp_Object file, specified_file;
5752 Lisp_Object specified_data;
5753 int x, y;
5754 ptrdiff_t i;
5755 XImagePtr ximg, mask_img = NULL;
5756 png_struct *png_ptr;
5757 png_info *info_ptr = NULL, *end_info = NULL;
5758 FILE *fp = NULL;
5759 png_byte sig[8];
5760 png_byte *pixels = NULL;
5761 png_byte **rows = NULL;
5762 png_uint_32 width, height;
5763 int bit_depth, color_type, interlace_type;
5764 png_byte channels;
5765 png_uint_32 row_bytes;
5766 bool transparent_p;
5767 struct png_memory_storage tbr; /* Data to be read */
5769 /* Find out what file to load. */
5770 specified_file = image_spec_value (img->spec, QCfile, NULL);
5771 specified_data = image_spec_value (img->spec, QCdata, NULL);
5773 if (NILP (specified_data))
5775 file = x_find_image_file (specified_file);
5776 if (!STRINGP (file))
5778 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5779 return 0;
5782 /* Open the image file. */
5783 fp = emacs_fopen (SSDATA (file), "rb");
5784 if (!fp)
5786 image_error ("Cannot open image file `%s'", file, Qnil);
5787 return 0;
5790 /* Check PNG signature. */
5791 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5792 || png_sig_cmp (sig, 0, sizeof sig))
5794 fclose (fp);
5795 image_error ("Not a PNG file: `%s'", file, Qnil);
5796 return 0;
5799 else
5801 if (!STRINGP (specified_data))
5803 image_error ("Invalid image data `%s'", specified_data, Qnil);
5804 return 0;
5807 /* Read from memory. */
5808 tbr.bytes = SDATA (specified_data);
5809 tbr.len = SBYTES (specified_data);
5810 tbr.index = 0;
5812 /* Check PNG signature. */
5813 if (tbr.len < sizeof sig
5814 || png_sig_cmp (tbr.bytes, 0, sizeof sig))
5816 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5817 return 0;
5820 /* Need to skip past the signature. */
5821 tbr.bytes += sizeof (sig);
5824 /* Initialize read and info structs for PNG lib. */
5825 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
5826 NULL, my_png_error,
5827 my_png_warning);
5828 if (png_ptr)
5830 info_ptr = png_create_info_struct (png_ptr);
5831 end_info = png_create_info_struct (png_ptr);
5834 c->png_ptr = png_ptr;
5835 c->info_ptr = info_ptr;
5836 c->end_info = end_info;
5837 c->fp = fp;
5838 c->pixels = pixels;
5839 c->rows = rows;
5841 if (! (info_ptr && end_info))
5843 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5844 png_ptr = 0;
5846 if (! png_ptr)
5848 if (fp) fclose (fp);
5849 return 0;
5852 /* Set error jump-back. We come back here when the PNG library
5853 detects an error. */
5854 if (FAST_SETJMP (PNG_JMPBUF (png_ptr)))
5856 error:
5857 if (c->png_ptr)
5858 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5859 xfree (c->pixels);
5860 xfree (c->rows);
5861 if (c->fp)
5862 fclose (c->fp);
5863 return 0;
5866 /* Silence a bogus diagnostic; see GCC bug 54561. */
5867 IF_LINT (fp = c->fp);
5869 /* Read image info. */
5870 if (!NILP (specified_data))
5871 png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
5872 else
5873 png_set_read_fn (png_ptr, fp, png_read_from_file);
5875 png_set_sig_bytes (png_ptr, sizeof sig);
5876 png_read_info (png_ptr, info_ptr);
5877 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5878 &interlace_type, NULL, NULL);
5880 if (! (width <= INT_MAX && height <= INT_MAX
5881 && check_image_size (f, width, height)))
5883 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5884 goto error;
5887 /* Create the X image and pixmap now, so that the work below can be
5888 omitted if the image is too large for X. */
5889 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
5890 goto error;
5892 /* If image contains simply transparency data, we prefer to
5893 construct a clipping mask. */
5894 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5895 transparent_p = 1;
5896 else
5897 transparent_p = 0;
5899 /* This function is easier to write if we only have to handle
5900 one data format: RGB or RGBA with 8 bits per channel. Let's
5901 transform other formats into that format. */
5903 /* Strip more than 8 bits per channel. */
5904 if (bit_depth == 16)
5905 png_set_strip_16 (png_ptr);
5907 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5908 if available. */
5909 png_set_expand (png_ptr);
5911 /* Convert grayscale images to RGB. */
5912 if (color_type == PNG_COLOR_TYPE_GRAY
5913 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5914 png_set_gray_to_rgb (png_ptr);
5916 /* Handle alpha channel by combining the image with a background
5917 color. Do this only if a real alpha channel is supplied. For
5918 simple transparency, we prefer a clipping mask. */
5919 if (!transparent_p)
5921 /* png_color_16 *image_bg; */
5922 Lisp_Object specified_bg
5923 = image_spec_value (img->spec, QCbackground, NULL);
5924 XColor color;
5926 /* If the user specified a color, try to use it; if not, use the
5927 current frame background, ignoring any default background
5928 color set by the image. */
5929 if (STRINGP (specified_bg)
5930 ? x_defined_color (f, SSDATA (specified_bg), &color, false)
5931 : (x_query_frame_background_color (f, &color), true))
5932 /* The user specified `:background', use that. */
5934 int shift = bit_depth == 16 ? 0 : 8;
5935 png_color_16 bg = { 0 };
5936 bg.red = color.red >> shift;
5937 bg.green = color.green >> shift;
5938 bg.blue = color.blue >> shift;
5940 png_set_background (png_ptr, &bg,
5941 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5945 /* Update info structure. */
5946 png_read_update_info (png_ptr, info_ptr);
5948 /* Get number of channels. Valid values are 1 for grayscale images
5949 and images with a palette, 2 for grayscale images with transparency
5950 information (alpha channel), 3 for RGB images, and 4 for RGB
5951 images with alpha channel, i.e. RGBA. If conversions above were
5952 sufficient we should only have 3 or 4 channels here. */
5953 channels = png_get_channels (png_ptr, info_ptr);
5954 eassert (channels == 3 || channels == 4);
5956 /* Number of bytes needed for one row of the image. */
5957 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
5959 /* Allocate memory for the image. */
5960 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows < height
5961 || min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height < row_bytes)
5962 memory_full (SIZE_MAX);
5963 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
5964 c->rows = rows = xmalloc (height * sizeof *rows);
5965 for (i = 0; i < height; ++i)
5966 rows[i] = pixels + i * row_bytes;
5968 /* Read the entire image. */
5969 png_read_image (png_ptr, rows);
5970 png_read_end (png_ptr, info_ptr);
5971 if (fp)
5973 fclose (fp);
5974 c->fp = NULL;
5977 /* Create an image and pixmap serving as mask if the PNG image
5978 contains an alpha channel. */
5979 if (channels == 4
5980 && !transparent_p
5981 && !image_create_x_image_and_pixmap (f, img, width, height, 1,
5982 &mask_img, 1))
5984 x_destroy_x_image (ximg);
5985 x_clear_image_1 (f, img, CLEAR_IMAGE_PIXMAP);
5986 goto error;
5989 /* Fill the X image and mask from PNG data. */
5990 init_color_table ();
5992 for (y = 0; y < height; ++y)
5994 png_byte *p = rows[y];
5996 for (x = 0; x < width; ++x)
5998 int r, g, b;
6000 r = *p++ << 8;
6001 g = *p++ << 8;
6002 b = *p++ << 8;
6003 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6004 /* An alpha channel, aka mask channel, associates variable
6005 transparency with an image. Where other image formats
6006 support binary transparency---fully transparent or fully
6007 opaque---PNG allows up to 254 levels of partial transparency.
6008 The PNG library implements partial transparency by combining
6009 the image with a specified background color.
6011 I'm not sure how to handle this here nicely: because the
6012 background on which the image is displayed may change, for
6013 real alpha channel support, it would be necessary to create
6014 a new image for each possible background.
6016 What I'm doing now is that a mask is created if we have
6017 boolean transparency information. Otherwise I'm using
6018 the frame's background color to combine the image with. */
6020 if (channels == 4)
6022 if (mask_img)
6023 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6024 ++p;
6029 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6030 /* Set IMG's background color from the PNG image, unless the user
6031 overrode it. */
6033 png_color_16 *bg;
6034 if (png_get_bKGD (png_ptr, info_ptr, &bg))
6036 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6037 img->background_valid = 1;
6041 # ifdef COLOR_TABLE_SUPPORT
6042 /* Remember colors allocated for this image. */
6043 img->colors = colors_in_color_table (&img->ncolors);
6044 free_color_table ();
6045 # endif /* COLOR_TABLE_SUPPORT */
6047 /* Clean up. */
6048 png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
6049 xfree (rows);
6050 xfree (pixels);
6052 img->width = width;
6053 img->height = height;
6055 /* Maybe fill in the background field while we have ximg handy.
6056 Casting avoids a GCC warning. */
6057 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6059 /* Put ximg into the image. */
6060 image_put_x_image (f, img, ximg, 0);
6062 /* Same for the mask. */
6063 if (mask_img)
6065 /* Fill in the background_transparent field while we have the
6066 mask handy. Casting avoids a GCC warning. */
6067 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6069 image_put_x_image (f, img, mask_img, 1);
6072 return 1;
6075 static bool
6076 png_load (struct frame *f, struct image *img)
6078 struct png_load_context c;
6079 return png_load_body (f, img, &c);
6082 #elif defined HAVE_NS
6084 static bool
6085 png_load (struct frame *f, struct image *img)
6087 return ns_load_image (f, img,
6088 image_spec_value (img->spec, QCfile, NULL),
6089 image_spec_value (img->spec, QCdata, NULL));
6092 #endif /* HAVE_NS */
6096 /***********************************************************************
6097 JPEG
6098 ***********************************************************************/
6100 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6102 static bool jpeg_image_p (Lisp_Object object);
6103 static bool jpeg_load (struct frame *f, struct image *img);
6105 /* The symbol `jpeg' identifying images of this type. */
6107 static Lisp_Object Qjpeg;
6109 /* Indices of image specification fields in gs_format, below. */
6111 enum jpeg_keyword_index
6113 JPEG_TYPE,
6114 JPEG_DATA,
6115 JPEG_FILE,
6116 JPEG_ASCENT,
6117 JPEG_MARGIN,
6118 JPEG_RELIEF,
6119 JPEG_ALGORITHM,
6120 JPEG_HEURISTIC_MASK,
6121 JPEG_MASK,
6122 JPEG_BACKGROUND,
6123 JPEG_LAST
6126 /* Vector of image_keyword structures describing the format
6127 of valid user-defined image specifications. */
6129 static const struct image_keyword jpeg_format[JPEG_LAST] =
6131 {":type", IMAGE_SYMBOL_VALUE, 1},
6132 {":data", IMAGE_STRING_VALUE, 0},
6133 {":file", IMAGE_STRING_VALUE, 0},
6134 {":ascent", IMAGE_ASCENT_VALUE, 0},
6135 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6136 {":relief", IMAGE_INTEGER_VALUE, 0},
6137 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6138 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6139 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6140 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6143 #if defined HAVE_NTGUI && defined WINDOWSNT
6144 static bool init_jpeg_functions (void);
6145 #else
6146 #define init_jpeg_functions NULL
6147 #endif
6149 /* Structure describing the image type `jpeg'. */
6151 static struct image_type jpeg_type =
6153 &Qjpeg,
6154 jpeg_image_p,
6155 jpeg_load,
6156 x_clear_image,
6157 init_jpeg_functions,
6158 NULL
6161 /* Return true if OBJECT is a valid JPEG image specification. */
6163 static bool
6164 jpeg_image_p (Lisp_Object object)
6166 struct image_keyword fmt[JPEG_LAST];
6168 memcpy (fmt, jpeg_format, sizeof fmt);
6170 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6171 return 0;
6173 /* Must specify either the :data or :file keyword. */
6174 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6177 #endif /* HAVE_JPEG || HAVE_NS */
6179 #ifdef HAVE_JPEG
6181 /* Work around a warning about HAVE_STDLIB_H being redefined in
6182 jconfig.h. */
6183 # ifdef HAVE_STDLIB_H
6184 # undef HAVE_STDLIB_H
6185 # endif
6187 # if defined (HAVE_NTGUI) && !defined (__WIN32__)
6188 /* In older releases of the jpeg library, jpeglib.h will define boolean
6189 differently depending on __WIN32__, so make sure it is defined. */
6190 # define __WIN32__ 1
6191 # endif
6193 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6194 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6195 using the Windows boolean type instead of the jpeglib boolean type
6196 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6197 headers are included along with windows.h, so under Cygwin, jpeglib
6198 attempts to define a conflicting boolean type. Worse, forcing
6199 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6200 because it created an ABI incompatibility between the
6201 already-compiled jpeg library and the header interface definition.
6203 The best we can do is to define jpeglib's boolean type to a
6204 different name. This name, jpeg_boolean, remains in effect through
6205 the rest of image.c.
6207 # if defined CYGWIN && defined HAVE_NTGUI
6208 # define boolean jpeg_boolean
6209 # endif
6210 # include <jpeglib.h>
6211 # include <jerror.h>
6213 # ifdef WINDOWSNT
6215 /* JPEG library details. */
6216 DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6217 DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6218 DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6219 DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6220 DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6221 DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
6222 (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6223 DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
6224 (struct jpeg_error_mgr *));
6225 DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6227 static bool
6228 init_jpeg_functions (void)
6230 HMODULE library;
6232 if (!(library = w32_delayed_load (Qjpeg)))
6233 return 0;
6235 LOAD_DLL_FN (library, jpeg_finish_decompress);
6236 LOAD_DLL_FN (library, jpeg_read_scanlines);
6237 LOAD_DLL_FN (library, jpeg_start_decompress);
6238 LOAD_DLL_FN (library, jpeg_read_header);
6239 LOAD_DLL_FN (library, jpeg_CreateDecompress);
6240 LOAD_DLL_FN (library, jpeg_destroy_decompress);
6241 LOAD_DLL_FN (library, jpeg_std_error);
6242 LOAD_DLL_FN (library, jpeg_resync_to_restart);
6243 return 1;
6246 # undef jpeg_CreateDecompress
6247 # undef jpeg_destroy_decompress
6248 # undef jpeg_finish_decompress
6249 # undef jpeg_read_header
6250 # undef jpeg_read_scanlines
6251 # undef jpeg_resync_to_restart
6252 # undef jpeg_start_decompress
6253 # undef jpeg_std_error
6255 # define jpeg_CreateDecompress fn_jpeg_CreateDecompress
6256 # define jpeg_destroy_decompress fn_jpeg_destroy_decompress
6257 # define jpeg_finish_decompress fn_jpeg_finish_decompress
6258 # define jpeg_read_header fn_jpeg_read_header
6259 # define jpeg_read_scanlines fn_jpeg_read_scanlines
6260 # define jpeg_resync_to_restart fn_jpeg_resync_to_restart
6261 # define jpeg_start_decompress fn_jpeg_start_decompress
6262 # define jpeg_std_error fn_jpeg_std_error
6264 /* Wrapper since we can't directly assign the function pointer
6265 to another function pointer that was declared more completely easily. */
6266 static boolean
6267 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6269 return jpeg_resync_to_restart (cinfo, desired);
6271 # undef jpeg_resync_to_restart
6272 # define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
6274 # endif /* WINDOWSNT */
6276 struct my_jpeg_error_mgr
6278 struct jpeg_error_mgr pub;
6279 sys_jmp_buf setjmp_buffer;
6281 /* The remaining members are so that longjmp doesn't munge local
6282 variables. */
6283 struct jpeg_decompress_struct cinfo;
6284 enum
6286 MY_JPEG_ERROR_EXIT,
6287 MY_JPEG_INVALID_IMAGE_SIZE,
6288 MY_JPEG_CANNOT_CREATE_X
6289 } failure_code;
6293 static _Noreturn void
6294 my_error_exit (j_common_ptr cinfo)
6296 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6297 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6298 sys_longjmp (mgr->setjmp_buffer, 1);
6302 /* Init source method for JPEG data source manager. Called by
6303 jpeg_read_header() before any data is actually read. See
6304 libjpeg.doc from the JPEG lib distribution. */
6306 static void
6307 our_common_init_source (j_decompress_ptr cinfo)
6312 /* Method to terminate data source. Called by
6313 jpeg_finish_decompress() after all data has been processed. */
6315 static void
6316 our_common_term_source (j_decompress_ptr cinfo)
6321 /* Fill input buffer method for JPEG data source manager. Called
6322 whenever more data is needed. We read the whole image in one step,
6323 so this only adds a fake end of input marker at the end. */
6325 static JOCTET our_memory_buffer[2];
6327 static boolean
6328 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6330 /* Insert a fake EOI marker. */
6331 struct jpeg_source_mgr *src = cinfo->src;
6333 our_memory_buffer[0] = (JOCTET) 0xFF;
6334 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6336 src->next_input_byte = our_memory_buffer;
6337 src->bytes_in_buffer = 2;
6338 return 1;
6342 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6343 is the JPEG data source manager. */
6345 static void
6346 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6348 struct jpeg_source_mgr *src = cinfo->src;
6350 if (src)
6352 if (num_bytes > src->bytes_in_buffer)
6353 ERREXIT (cinfo, JERR_INPUT_EOF);
6355 src->bytes_in_buffer -= num_bytes;
6356 src->next_input_byte += num_bytes;
6361 /* Set up the JPEG lib for reading an image from DATA which contains
6362 LEN bytes. CINFO is the decompression info structure created for
6363 reading the image. */
6365 static void
6366 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6368 struct jpeg_source_mgr *src = cinfo->src;
6370 if (! src)
6372 /* First time for this JPEG object? */
6373 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6374 JPOOL_PERMANENT, sizeof *src);
6375 cinfo->src = src;
6376 src->next_input_byte = data;
6379 src->init_source = our_common_init_source;
6380 src->fill_input_buffer = our_memory_fill_input_buffer;
6381 src->skip_input_data = our_memory_skip_input_data;
6382 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
6383 src->term_source = our_common_term_source;
6384 src->bytes_in_buffer = len;
6385 src->next_input_byte = data;
6389 struct jpeg_stdio_mgr
6391 struct jpeg_source_mgr mgr;
6392 boolean finished;
6393 FILE *file;
6394 JOCTET *buffer;
6398 /* Size of buffer to read JPEG from file.
6399 Not too big, as we want to use alloc_small. */
6400 #define JPEG_STDIO_BUFFER_SIZE 8192
6403 /* Fill input buffer method for JPEG data source manager. Called
6404 whenever more data is needed. The data is read from a FILE *. */
6406 static boolean
6407 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6409 struct jpeg_stdio_mgr *src;
6411 src = (struct jpeg_stdio_mgr *) cinfo->src;
6412 if (!src->finished)
6414 ptrdiff_t bytes;
6416 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6417 if (bytes > 0)
6418 src->mgr.bytes_in_buffer = bytes;
6419 else
6421 WARNMS (cinfo, JWRN_JPEG_EOF);
6422 src->finished = 1;
6423 src->buffer[0] = (JOCTET) 0xFF;
6424 src->buffer[1] = (JOCTET) JPEG_EOI;
6425 src->mgr.bytes_in_buffer = 2;
6427 src->mgr.next_input_byte = src->buffer;
6430 return 1;
6434 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6435 is the JPEG data source manager. */
6437 static void
6438 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6440 struct jpeg_stdio_mgr *src;
6441 src = (struct jpeg_stdio_mgr *) cinfo->src;
6443 while (num_bytes > 0 && !src->finished)
6445 if (num_bytes <= src->mgr.bytes_in_buffer)
6447 src->mgr.bytes_in_buffer -= num_bytes;
6448 src->mgr.next_input_byte += num_bytes;
6449 break;
6451 else
6453 num_bytes -= src->mgr.bytes_in_buffer;
6454 src->mgr.bytes_in_buffer = 0;
6455 src->mgr.next_input_byte = NULL;
6457 our_stdio_fill_input_buffer (cinfo);
6463 /* Set up the JPEG lib for reading an image from a FILE *.
6464 CINFO is the decompression info structure created for
6465 reading the image. */
6467 static void
6468 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6470 struct jpeg_stdio_mgr *src = (struct jpeg_stdio_mgr *) cinfo->src;
6472 if (! src)
6474 /* First time for this JPEG object? */
6475 src = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6476 JPOOL_PERMANENT, sizeof *src);
6477 cinfo->src = (struct jpeg_source_mgr *) src;
6478 src->buffer = cinfo->mem->alloc_small ((j_common_ptr) cinfo,
6479 JPOOL_PERMANENT,
6480 JPEG_STDIO_BUFFER_SIZE);
6483 src->file = fp;
6484 src->finished = 0;
6485 src->mgr.init_source = our_common_init_source;
6486 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6487 src->mgr.skip_input_data = our_stdio_skip_input_data;
6488 src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default. */
6489 src->mgr.term_source = our_common_term_source;
6490 src->mgr.bytes_in_buffer = 0;
6491 src->mgr.next_input_byte = NULL;
6494 /* Load image IMG for use on frame F. Patterned after example.c
6495 from the JPEG lib. */
6497 static bool
6498 jpeg_load_body (struct frame *f, struct image *img,
6499 struct my_jpeg_error_mgr *mgr)
6501 Lisp_Object file, specified_file;
6502 Lisp_Object specified_data;
6503 /* The 'volatile' silences a bogus diagnostic; see GCC bug 54561. */
6504 FILE * IF_LINT (volatile) fp = NULL;
6505 JSAMPARRAY buffer;
6506 int row_stride, x, y;
6507 XImagePtr ximg = NULL;
6508 unsigned long *colors;
6509 int width, height;
6511 /* Open the JPEG file. */
6512 specified_file = image_spec_value (img->spec, QCfile, NULL);
6513 specified_data = image_spec_value (img->spec, QCdata, NULL);
6515 if (NILP (specified_data))
6517 file = x_find_image_file (specified_file);
6518 if (!STRINGP (file))
6520 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6521 return 0;
6524 fp = emacs_fopen (SSDATA (file), "rb");
6525 if (fp == NULL)
6527 image_error ("Cannot open `%s'", file, Qnil);
6528 return 0;
6531 else if (!STRINGP (specified_data))
6533 image_error ("Invalid image data `%s'", specified_data, Qnil);
6534 return 0;
6537 /* Customize libjpeg's error handling to call my_error_exit when an
6538 error is detected. This function will perform a longjmp. */
6539 mgr->cinfo.err = jpeg_std_error (&mgr->pub);
6540 mgr->pub.error_exit = my_error_exit;
6541 if (sys_setjmp (mgr->setjmp_buffer))
6543 switch (mgr->failure_code)
6545 case MY_JPEG_ERROR_EXIT:
6547 char buf[JMSG_LENGTH_MAX];
6548 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6549 image_error ("Error reading JPEG image `%s': %s", img->spec,
6550 build_string (buf));
6551 break;
6554 case MY_JPEG_INVALID_IMAGE_SIZE:
6555 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6556 break;
6558 case MY_JPEG_CANNOT_CREATE_X:
6559 break;
6562 /* Close the input file and destroy the JPEG object. */
6563 if (fp)
6564 fclose (fp);
6565 jpeg_destroy_decompress (&mgr->cinfo);
6567 /* If we already have an XImage, free that. */
6568 x_destroy_x_image (ximg);
6570 /* Free pixmap and colors. */
6571 x_clear_image (f, img);
6572 return 0;
6575 /* Create the JPEG decompression object. Let it read from fp.
6576 Read the JPEG image header. */
6577 jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6579 if (NILP (specified_data))
6580 jpeg_file_src (&mgr->cinfo, fp);
6581 else
6582 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6583 SBYTES (specified_data));
6585 jpeg_read_header (&mgr->cinfo, 1);
6587 /* Customize decompression so that color quantization will be used.
6588 Start decompression. */
6589 mgr->cinfo.quantize_colors = 1;
6590 jpeg_start_decompress (&mgr->cinfo);
6591 width = img->width = mgr->cinfo.output_width;
6592 height = img->height = mgr->cinfo.output_height;
6594 if (!check_image_size (f, width, height))
6596 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6597 sys_longjmp (mgr->setjmp_buffer, 1);
6600 /* Create X image and pixmap. */
6601 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
6603 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6604 sys_longjmp (mgr->setjmp_buffer, 1);
6607 /* Allocate colors. When color quantization is used,
6608 mgr->cinfo.actual_number_of_colors has been set with the number of
6609 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6610 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6611 No more than 255 colors will be generated. */
6612 USE_SAFE_ALLOCA;
6614 int i, ir, ig, ib;
6616 if (mgr->cinfo.out_color_components > 2)
6617 ir = 0, ig = 1, ib = 2;
6618 else if (mgr->cinfo.out_color_components > 1)
6619 ir = 0, ig = 1, ib = 0;
6620 else
6621 ir = 0, ig = 0, ib = 0;
6623 /* Use the color table mechanism because it handles colors that
6624 cannot be allocated nicely. Such colors will be replaced with
6625 a default color, and we don't have to care about which colors
6626 can be freed safely, and which can't. */
6627 init_color_table ();
6628 SAFE_NALLOCA (colors, 1, mgr->cinfo.actual_number_of_colors);
6630 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6632 /* Multiply RGB values with 255 because X expects RGB values
6633 in the range 0..0xffff. */
6634 int r = mgr->cinfo.colormap[ir][i] << 8;
6635 int g = mgr->cinfo.colormap[ig][i] << 8;
6636 int b = mgr->cinfo.colormap[ib][i] << 8;
6637 colors[i] = lookup_rgb_color (f, r, g, b);
6640 #ifdef COLOR_TABLE_SUPPORT
6641 /* Remember those colors actually allocated. */
6642 img->colors = colors_in_color_table (&img->ncolors);
6643 free_color_table ();
6644 #endif /* COLOR_TABLE_SUPPORT */
6647 /* Read pixels. */
6648 row_stride = width * mgr->cinfo.output_components;
6649 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6650 JPOOL_IMAGE, row_stride, 1);
6651 for (y = 0; y < height; ++y)
6653 jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6654 for (x = 0; x < mgr->cinfo.output_width; ++x)
6655 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6658 /* Clean up. */
6659 jpeg_finish_decompress (&mgr->cinfo);
6660 jpeg_destroy_decompress (&mgr->cinfo);
6661 if (fp)
6662 fclose (fp);
6664 /* Maybe fill in the background field while we have ximg handy. */
6665 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6666 /* Casting avoids a GCC warning. */
6667 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6669 /* Put ximg into the image. */
6670 image_put_x_image (f, img, ximg, 0);
6671 SAFE_FREE ();
6672 return 1;
6675 static bool
6676 jpeg_load (struct frame *f, struct image *img)
6678 struct my_jpeg_error_mgr mgr;
6679 return jpeg_load_body (f, img, &mgr);
6682 #else /* HAVE_JPEG */
6684 #ifdef HAVE_NS
6685 static bool
6686 jpeg_load (struct frame *f, struct image *img)
6688 return ns_load_image (f, img,
6689 image_spec_value (img->spec, QCfile, NULL),
6690 image_spec_value (img->spec, QCdata, NULL));
6692 #endif /* HAVE_NS */
6694 #endif /* !HAVE_JPEG */
6698 /***********************************************************************
6699 TIFF
6700 ***********************************************************************/
6702 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6704 static bool tiff_image_p (Lisp_Object object);
6705 static bool tiff_load (struct frame *f, struct image *img);
6707 /* The symbol `tiff' identifying images of this type. */
6709 static Lisp_Object Qtiff;
6711 /* Indices of image specification fields in tiff_format, below. */
6713 enum tiff_keyword_index
6715 TIFF_TYPE,
6716 TIFF_DATA,
6717 TIFF_FILE,
6718 TIFF_ASCENT,
6719 TIFF_MARGIN,
6720 TIFF_RELIEF,
6721 TIFF_ALGORITHM,
6722 TIFF_HEURISTIC_MASK,
6723 TIFF_MASK,
6724 TIFF_BACKGROUND,
6725 TIFF_INDEX,
6726 TIFF_LAST
6729 /* Vector of image_keyword structures describing the format
6730 of valid user-defined image specifications. */
6732 static const struct image_keyword tiff_format[TIFF_LAST] =
6734 {":type", IMAGE_SYMBOL_VALUE, 1},
6735 {":data", IMAGE_STRING_VALUE, 0},
6736 {":file", IMAGE_STRING_VALUE, 0},
6737 {":ascent", IMAGE_ASCENT_VALUE, 0},
6738 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6739 {":relief", IMAGE_INTEGER_VALUE, 0},
6740 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6741 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6742 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6743 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6744 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6747 #if defined HAVE_NTGUI && defined WINDOWSNT
6748 static bool init_tiff_functions (void);
6749 #else
6750 #define init_tiff_functions NULL
6751 #endif
6753 /* Structure describing the image type `tiff'. */
6755 static struct image_type tiff_type =
6757 &Qtiff,
6758 tiff_image_p,
6759 tiff_load,
6760 x_clear_image,
6761 init_tiff_functions,
6762 NULL
6765 /* Return true if OBJECT is a valid TIFF image specification. */
6767 static bool
6768 tiff_image_p (Lisp_Object object)
6770 struct image_keyword fmt[TIFF_LAST];
6771 memcpy (fmt, tiff_format, sizeof fmt);
6773 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6774 return 0;
6776 /* Must specify either the :data or :file keyword. */
6777 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6780 #endif /* HAVE_TIFF || HAVE_NS */
6782 #ifdef HAVE_TIFF
6784 # include <tiffio.h>
6786 # ifdef WINDOWSNT
6788 /* TIFF library details. */
6789 DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6790 DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6791 DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
6792 DEF_DLL_FN (TIFF *, TIFFClientOpen,
6793 (const char *, const char *, thandle_t, TIFFReadWriteProc,
6794 TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6795 TIFFMapFileProc, TIFFUnmapFileProc));
6796 DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6797 DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6798 DEF_DLL_FN (void, TIFFClose, (TIFF *));
6799 DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6801 static bool
6802 init_tiff_functions (void)
6804 HMODULE library;
6806 if (!(library = w32_delayed_load (Qtiff)))
6807 return 0;
6809 LOAD_DLL_FN (library, TIFFSetErrorHandler);
6810 LOAD_DLL_FN (library, TIFFSetWarningHandler);
6811 LOAD_DLL_FN (library, TIFFOpen);
6812 LOAD_DLL_FN (library, TIFFClientOpen);
6813 LOAD_DLL_FN (library, TIFFGetField);
6814 LOAD_DLL_FN (library, TIFFReadRGBAImage);
6815 LOAD_DLL_FN (library, TIFFClose);
6816 LOAD_DLL_FN (library, TIFFSetDirectory);
6817 return 1;
6820 # undef TIFFClientOpen
6821 # undef TIFFClose
6822 # undef TIFFGetField
6823 # undef TIFFOpen
6824 # undef TIFFReadRGBAImage
6825 # undef TIFFSetDirectory
6826 # undef TIFFSetErrorHandler
6827 # undef TIFFSetWarningHandler
6829 # define TIFFClientOpen fn_TIFFClientOpen
6830 # define TIFFClose fn_TIFFClose
6831 # define TIFFGetField fn_TIFFGetField
6832 # define TIFFOpen fn_TIFFOpen
6833 # define TIFFReadRGBAImage fn_TIFFReadRGBAImage
6834 # define TIFFSetDirectory fn_TIFFSetDirectory
6835 # define TIFFSetErrorHandler fn_TIFFSetErrorHandler
6836 # define TIFFSetWarningHandler fn_TIFFSetWarningHandler
6838 # endif /* WINDOWSNT */
6841 /* Reading from a memory buffer for TIFF images Based on the PNG
6842 memory source, but we have to provide a lot of extra functions.
6843 Blah.
6845 We really only need to implement read and seek, but I am not
6846 convinced that the TIFF library is smart enough not to destroy
6847 itself if we only hand it the function pointers we need to
6848 override. */
6850 typedef struct
6852 unsigned char *bytes;
6853 ptrdiff_t len;
6854 ptrdiff_t index;
6856 tiff_memory_source;
6858 static tsize_t
6859 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6861 tiff_memory_source *src = (tiff_memory_source *) data;
6863 size = min (size, src->len - src->index);
6864 memcpy (buf, src->bytes + src->index, size);
6865 src->index += size;
6866 return size;
6869 static tsize_t
6870 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6872 return -1;
6875 static toff_t
6876 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6878 tiff_memory_source *src = (tiff_memory_source *) data;
6879 ptrdiff_t idx;
6881 switch (whence)
6883 case SEEK_SET: /* Go from beginning of source. */
6884 idx = off;
6885 break;
6887 case SEEK_END: /* Go from end of source. */
6888 idx = src->len + off;
6889 break;
6891 case SEEK_CUR: /* Go from current position. */
6892 idx = src->index + off;
6893 break;
6895 default: /* Invalid `whence'. */
6896 return -1;
6899 if (idx > src->len || idx < 0)
6900 return -1;
6902 src->index = idx;
6903 return src->index;
6906 static int
6907 tiff_close_memory (thandle_t data)
6909 /* NOOP */
6910 return 0;
6913 static int
6914 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6916 /* It is already _IN_ memory. */
6917 return 0;
6920 static void
6921 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6923 /* We don't need to do this. */
6926 static toff_t
6927 tiff_size_of_memory (thandle_t data)
6929 return ((tiff_memory_source *) data)->len;
6932 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6933 compiler error compiling tiff_handler, see Bugzilla bug #17406
6934 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6935 this function as external works around that problem. */
6936 # if defined (__MINGW32__) && __GNUC__ == 3
6937 # define MINGW_STATIC
6938 # else
6939 # define MINGW_STATIC static
6940 # endif
6942 MINGW_STATIC void
6943 tiff_handler (const char *, const char *, const char *, va_list)
6944 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6945 MINGW_STATIC void
6946 tiff_handler (const char *log_format, const char *title,
6947 const char *format, va_list ap)
6949 /* doprnt is not suitable here, as TIFF handlers are called from
6950 libtiff and are passed arbitrary printf directives. Instead, use
6951 vsnprintf, taking care to be portable to nonstandard environments
6952 where vsnprintf returns -1 on buffer overflow. Since it's just a
6953 log entry, it's OK to truncate it. */
6954 char buf[4000];
6955 int len = vsnprintf (buf, sizeof buf, format, ap);
6956 add_to_log (log_format, build_string (title),
6957 make_string (buf, max (0, min (len, sizeof buf - 1))));
6959 # undef MINGW_STATIC
6961 static void tiff_error_handler (const char *, const char *, va_list)
6962 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6963 static void
6964 tiff_error_handler (const char *title, const char *format, va_list ap)
6966 tiff_handler ("TIFF error: %s %s", title, format, ap);
6970 static void tiff_warning_handler (const char *, const char *, va_list)
6971 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6972 static void
6973 tiff_warning_handler (const char *title, const char *format, va_list ap)
6975 tiff_handler ("TIFF warning: %s %s", title, format, ap);
6979 /* Load TIFF image IMG for use on frame F. Value is true if
6980 successful. */
6982 static bool
6983 tiff_load (struct frame *f, struct image *img)
6985 Lisp_Object file, specified_file;
6986 Lisp_Object specified_data;
6987 TIFF *tiff;
6988 int width, height, x, y, count;
6989 uint32 *buf;
6990 int rc;
6991 XImagePtr ximg;
6992 tiff_memory_source memsrc;
6993 Lisp_Object image;
6995 specified_file = image_spec_value (img->spec, QCfile, NULL);
6996 specified_data = image_spec_value (img->spec, QCdata, NULL);
6998 TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6999 TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
7001 if (NILP (specified_data))
7003 /* Read from a file */
7004 file = x_find_image_file (specified_file);
7005 if (!STRINGP (file))
7007 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7008 return 0;
7010 # ifdef WINDOWSNT
7011 file = ansi_encode_filename (file);
7012 # endif
7014 /* Try to open the image file. */
7015 tiff = TIFFOpen (SSDATA (file), "r");
7016 if (tiff == NULL)
7018 image_error ("Cannot open `%s'", file, Qnil);
7019 return 0;
7022 else
7024 if (!STRINGP (specified_data))
7026 image_error ("Invalid image data `%s'", specified_data, Qnil);
7027 return 0;
7030 /* Memory source! */
7031 memsrc.bytes = SDATA (specified_data);
7032 memsrc.len = SBYTES (specified_data);
7033 memsrc.index = 0;
7035 tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
7036 tiff_read_from_memory,
7037 tiff_write_from_memory,
7038 tiff_seek_in_memory,
7039 tiff_close_memory,
7040 tiff_size_of_memory,
7041 tiff_mmap_memory,
7042 tiff_unmap_memory);
7044 if (!tiff)
7046 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7047 return 0;
7051 image = image_spec_value (img->spec, QCindex, NULL);
7052 if (INTEGERP (image))
7054 EMACS_INT ino = XFASTINT (image);
7055 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
7056 && TIFFSetDirectory (tiff, ino)))
7058 image_error ("Invalid image number `%s' in image `%s'",
7059 image, img->spec);
7060 TIFFClose (tiff);
7061 return 0;
7065 /* Get width and height of the image, and allocate a raster buffer
7066 of width x height 32-bit values. */
7067 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7068 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7070 if (!check_image_size (f, width, height))
7072 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7073 TIFFClose (tiff);
7074 return 0;
7077 /* Create the X image and pixmap. */
7078 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
7079 && image_create_x_image_and_pixmap (f, img, width, height, 0,
7080 &ximg, 0)))
7082 TIFFClose (tiff);
7083 return 0;
7086 buf = xmalloc (sizeof *buf * width * height);
7088 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
7090 /* Count the number of images in the file. */
7091 for (count = 1; TIFFSetDirectory (tiff, count); count++)
7092 continue;
7094 if (count > 1)
7095 img->lisp_data = Fcons (Qcount,
7096 Fcons (make_number (count),
7097 img->lisp_data));
7099 TIFFClose (tiff);
7100 if (!rc)
7102 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7103 xfree (buf);
7104 return 0;
7107 /* Initialize the color table. */
7108 init_color_table ();
7110 /* Process the pixel raster. Origin is in the lower-left corner. */
7111 for (y = 0; y < height; ++y)
7113 uint32 *row = buf + y * width;
7115 for (x = 0; x < width; ++x)
7117 uint32 abgr = row[x];
7118 int r = TIFFGetR (abgr) << 8;
7119 int g = TIFFGetG (abgr) << 8;
7120 int b = TIFFGetB (abgr) << 8;
7121 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7125 # ifdef COLOR_TABLE_SUPPORT
7126 /* Remember the colors allocated for the image. Free the color table. */
7127 img->colors = colors_in_color_table (&img->ncolors);
7128 free_color_table ();
7129 # endif /* COLOR_TABLE_SUPPORT */
7131 img->width = width;
7132 img->height = height;
7134 /* Maybe fill in the background field while we have ximg handy. */
7135 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7136 /* Casting avoids a GCC warning on W32. */
7137 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7139 /* Put ximg into the image. */
7140 image_put_x_image (f, img, ximg, 0);
7141 xfree (buf);
7143 return 1;
7146 #elif defined HAVE_NS
7148 static bool
7149 tiff_load (struct frame *f, struct image *img)
7151 return ns_load_image (f, img,
7152 image_spec_value (img->spec, QCfile, NULL),
7153 image_spec_value (img->spec, QCdata, NULL));
7156 #endif
7160 /***********************************************************************
7162 ***********************************************************************/
7164 #if defined (HAVE_GIF) || defined (HAVE_NS)
7166 static bool gif_image_p (Lisp_Object object);
7167 static bool gif_load (struct frame *f, struct image *img);
7168 static void gif_clear_image (struct frame *f, struct image *img);
7170 /* The symbol `gif' identifying images of this type. */
7172 static Lisp_Object Qgif;
7174 /* Indices of image specification fields in gif_format, below. */
7176 enum gif_keyword_index
7178 GIF_TYPE,
7179 GIF_DATA,
7180 GIF_FILE,
7181 GIF_ASCENT,
7182 GIF_MARGIN,
7183 GIF_RELIEF,
7184 GIF_ALGORITHM,
7185 GIF_HEURISTIC_MASK,
7186 GIF_MASK,
7187 GIF_IMAGE,
7188 GIF_BACKGROUND,
7189 GIF_LAST
7192 /* Vector of image_keyword structures describing the format
7193 of valid user-defined image specifications. */
7195 static const struct image_keyword gif_format[GIF_LAST] =
7197 {":type", IMAGE_SYMBOL_VALUE, 1},
7198 {":data", IMAGE_STRING_VALUE, 0},
7199 {":file", IMAGE_STRING_VALUE, 0},
7200 {":ascent", IMAGE_ASCENT_VALUE, 0},
7201 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7202 {":relief", IMAGE_INTEGER_VALUE, 0},
7203 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7204 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7205 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7206 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7207 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7210 #if defined HAVE_NTGUI && defined WINDOWSNT
7211 static bool init_gif_functions (void);
7212 #else
7213 #define init_gif_functions NULL
7214 #endif
7216 /* Structure describing the image type `gif'. */
7218 static struct image_type gif_type =
7220 &Qgif,
7221 gif_image_p,
7222 gif_load,
7223 gif_clear_image,
7224 init_gif_functions,
7225 NULL
7228 /* Free X resources of GIF image IMG which is used on frame F. */
7230 static void
7231 gif_clear_image (struct frame *f, struct image *img)
7233 img->lisp_data = Qnil;
7234 x_clear_image (f, img);
7237 /* Return true if OBJECT is a valid GIF image specification. */
7239 static bool
7240 gif_image_p (Lisp_Object object)
7242 struct image_keyword fmt[GIF_LAST];
7243 memcpy (fmt, gif_format, sizeof fmt);
7245 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7246 return 0;
7248 /* Must specify either the :data or :file keyword. */
7249 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7252 #endif /* HAVE_GIF */
7254 #ifdef HAVE_GIF
7256 # ifdef HAVE_NTGUI
7258 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7259 Undefine before redefining to avoid a preprocessor warning. */
7260 # ifdef DrawText
7261 # undef DrawText
7262 # endif
7263 /* avoid conflict with QuickdrawText.h */
7264 # define DrawText gif_DrawText
7265 # include <gif_lib.h>
7266 # undef DrawText
7268 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI). */
7269 # ifndef GIFLIB_MINOR
7270 # define GIFLIB_MINOR 0
7271 # endif
7272 # ifndef GIFLIB_RELEASE
7273 # define GIFLIB_RELEASE 0
7274 # endif
7276 # else /* HAVE_NTGUI */
7278 # include <gif_lib.h>
7280 # endif /* HAVE_NTGUI */
7282 /* Giflib before 5.0 didn't define these macros. */
7283 # ifndef GIFLIB_MAJOR
7284 # define GIFLIB_MAJOR 4
7285 # endif
7287 # ifdef WINDOWSNT
7289 /* GIF library details. */
7290 # if 5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR)
7291 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
7292 # else
7293 DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
7294 # endif
7295 DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
7296 # if GIFLIB_MAJOR < 5
7297 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7298 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
7299 # else
7300 DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
7301 DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
7302 DEF_DLL_FN (char *, GifErrorString, (int));
7303 # endif
7305 static bool
7306 init_gif_functions (void)
7308 HMODULE library;
7310 if (!(library = w32_delayed_load (Qgif)))
7311 return 0;
7313 LOAD_DLL_FN (library, DGifCloseFile);
7314 LOAD_DLL_FN (library, DGifSlurp);
7315 LOAD_DLL_FN (library, DGifOpen);
7316 LOAD_DLL_FN (library, DGifOpenFileName);
7317 # if GIFLIB_MAJOR >= 5
7318 LOAD_DLL_FN (library, GifErrorString);
7319 # endif
7320 return 1;
7323 # undef DGifCloseFile
7324 # undef DGifOpen
7325 # undef DGifOpenFileName
7326 # undef DGifSlurp
7327 # undef GifErrorString
7329 # define DGifCloseFile fn_DGifCloseFile
7330 # define DGifOpen fn_DGifOpen
7331 # define DGifOpenFileName fn_DGifOpenFileName
7332 # define DGifSlurp fn_DGifSlurp
7333 # define GifErrorString fn_GifErrorString
7335 # endif /* WINDOWSNT */
7337 /* Reading a GIF image from memory
7338 Based on the PNG memory stuff to a certain extent. */
7340 typedef struct
7342 unsigned char *bytes;
7343 ptrdiff_t len;
7344 ptrdiff_t index;
7346 gif_memory_source;
7348 /* Make the current memory source available to gif_read_from_memory.
7349 It's done this way because not all versions of libungif support
7350 a UserData field in the GifFileType structure. */
7351 static gif_memory_source *current_gif_memory_src;
7353 static int
7354 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7356 gif_memory_source *src = current_gif_memory_src;
7358 if (len > src->len - src->index)
7359 return -1;
7361 memcpy (buf, src->bytes + src->index, len);
7362 src->index += len;
7363 return len;
7366 static int
7367 gif_close (GifFileType *gif, int *err)
7369 int retval;
7371 #if 5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR)
7372 retval = DGifCloseFile (gif, err);
7373 #else
7374 retval = DGifCloseFile (gif);
7375 #if GIFLIB_MAJOR >= 5
7376 if (err)
7377 *err = gif->Error;
7378 #endif
7379 #endif
7380 return retval;
7383 /* Load GIF image IMG for use on frame F. Value is true if
7384 successful. */
7386 static const int interlace_start[] = {0, 4, 2, 1};
7387 static const int interlace_increment[] = {8, 8, 4, 2};
7389 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7391 static bool
7392 gif_load (struct frame *f, struct image *img)
7394 Lisp_Object file;
7395 int rc, width, height, x, y, i, j;
7396 XImagePtr ximg;
7397 ColorMapObject *gif_color_map;
7398 unsigned long pixel_colors[256];
7399 GifFileType *gif;
7400 gif_memory_source memsrc;
7401 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7402 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7403 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7404 unsigned long bgcolor = 0;
7405 EMACS_INT idx;
7406 int gif_err;
7408 if (NILP (specified_data))
7410 file = x_find_image_file (specified_file);
7411 if (!STRINGP (file))
7413 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7414 return 0;
7416 #ifdef WINDOWSNT
7417 file = ansi_encode_filename (file);
7418 #endif
7420 /* Open the GIF file. */
7421 #if GIFLIB_MAJOR < 5
7422 gif = DGifOpenFileName (SSDATA (file));
7423 if (gif == NULL)
7425 image_error ("Cannot open `%s'", file, Qnil);
7426 return 0;
7428 #else
7429 gif = DGifOpenFileName (SSDATA (file), &gif_err);
7430 if (gif == NULL)
7432 image_error ("Cannot open `%s': %s",
7433 file, build_string (GifErrorString (gif_err)));
7434 return 0;
7436 #endif
7438 else
7440 if (!STRINGP (specified_data))
7442 image_error ("Invalid image data `%s'", specified_data, Qnil);
7443 return 0;
7446 /* Read from memory! */
7447 current_gif_memory_src = &memsrc;
7448 memsrc.bytes = SDATA (specified_data);
7449 memsrc.len = SBYTES (specified_data);
7450 memsrc.index = 0;
7452 #if GIFLIB_MAJOR < 5
7453 gif = DGifOpen (&memsrc, gif_read_from_memory);
7454 if (!gif)
7456 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7457 return 0;
7459 #else
7460 gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
7461 if (!gif)
7463 image_error ("Cannot open memory source `%s': %s",
7464 img->spec, build_string (GifErrorString (gif_err)));
7465 return 0;
7467 #endif
7470 /* Before reading entire contents, check the declared image size. */
7471 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7473 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7474 gif_close (gif, NULL);
7475 return 0;
7478 /* Read entire contents. */
7479 rc = DGifSlurp (gif);
7480 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7482 image_error ("Error reading `%s'", img->spec, Qnil);
7483 gif_close (gif, NULL);
7484 return 0;
7487 /* Which sub-image are we to display? */
7489 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7490 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7491 if (idx < 0 || idx >= gif->ImageCount)
7493 image_error ("Invalid image number `%s' in image `%s'",
7494 image_number, img->spec);
7495 gif_close (gif, NULL);
7496 return 0;
7500 width = img->width = gif->SWidth;
7501 height = img->height = gif->SHeight;
7503 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7504 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7505 img->corners[BOT_CORNER]
7506 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7507 img->corners[RIGHT_CORNER]
7508 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7510 if (!check_image_size (f, width, height))
7512 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7513 gif_close (gif, NULL);
7514 return 0;
7517 /* Check that the selected subimages fit. It's not clear whether
7518 the GIF spec requires this, but Emacs can crash if they don't fit. */
7519 for (j = 0; j <= idx; ++j)
7521 struct SavedImage *subimage = gif->SavedImages + j;
7522 int subimg_width = subimage->ImageDesc.Width;
7523 int subimg_height = subimage->ImageDesc.Height;
7524 int subimg_top = subimage->ImageDesc.Top;
7525 int subimg_left = subimage->ImageDesc.Left;
7526 if (! (0 <= subimg_width && 0 <= subimg_height
7527 && 0 <= subimg_top && subimg_top <= height - subimg_height
7528 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7530 image_error ("Subimage does not fit in image", Qnil, Qnil);
7531 gif_close (gif, NULL);
7532 return 0;
7536 /* Create the X image and pixmap. */
7537 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
7539 gif_close (gif, NULL);
7540 return 0;
7543 /* Clear the part of the screen image not covered by the image.
7544 Full animated GIF support requires more here (see the gif89 spec,
7545 disposal methods). Let's simply assume that the part not covered
7546 by a sub-image is in the frame's background color. */
7547 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7548 for (x = 0; x < width; ++x)
7549 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7551 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7552 for (x = 0; x < width; ++x)
7553 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7555 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7557 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7558 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7559 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7560 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7563 /* Read the GIF image into the X image. */
7565 /* FIXME: With the current implementation, loading an animated gif
7566 is quadratic in the number of animation frames, since each frame
7567 is a separate struct image. We must provide a way for a single
7568 gif_load call to construct and save all animation frames. */
7570 init_color_table ();
7571 if (STRINGP (specified_bg))
7572 bgcolor = x_alloc_image_color (f, img, specified_bg,
7573 FRAME_BACKGROUND_PIXEL (f));
7574 for (j = 0; j <= idx; ++j)
7576 /* We use a local variable `raster' here because RasterBits is a
7577 char *, which invites problems with bytes >= 0x80. */
7578 struct SavedImage *subimage = gif->SavedImages + j;
7579 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7580 int transparency_color_index = -1;
7581 int disposal = 0;
7582 int subimg_width = subimage->ImageDesc.Width;
7583 int subimg_height = subimage->ImageDesc.Height;
7584 int subimg_top = subimage->ImageDesc.Top;
7585 int subimg_left = subimage->ImageDesc.Left;
7587 /* Find the Graphic Control Extension block for this sub-image.
7588 Extract the disposal method and transparency color. */
7589 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7591 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7593 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7594 && extblock->ByteCount == 4
7595 && extblock->Bytes[0] & 1)
7597 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7598 to background". Treat any other value like 2. */
7599 disposal = (extblock->Bytes[0] >> 2) & 7;
7600 transparency_color_index = (unsigned char) extblock->Bytes[3];
7601 break;
7605 /* We can't "keep in place" the first subimage. */
7606 if (j == 0)
7607 disposal = 2;
7609 /* For disposal == 0, the spec says "No disposal specified. The
7610 decoder is not required to take any action." In practice, it
7611 seems we need to treat this like "keep in place", see e.g.
7612 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7613 if (disposal == 0)
7614 disposal = 1;
7616 /* Allocate subimage colors. */
7617 memset (pixel_colors, 0, sizeof pixel_colors);
7618 gif_color_map = subimage->ImageDesc.ColorMap;
7619 if (!gif_color_map)
7620 gif_color_map = gif->SColorMap;
7622 if (gif_color_map)
7623 for (i = 0; i < gif_color_map->ColorCount; ++i)
7625 if (transparency_color_index == i)
7626 pixel_colors[i] = STRINGP (specified_bg)
7627 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7628 else
7630 int r = gif_color_map->Colors[i].Red << 8;
7631 int g = gif_color_map->Colors[i].Green << 8;
7632 int b = gif_color_map->Colors[i].Blue << 8;
7633 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7637 /* Apply the pixel values. */
7638 if (GIFLIB_MAJOR < 5 && gif->SavedImages[j].ImageDesc.Interlace)
7640 int row, pass;
7642 for (y = 0, row = interlace_start[0], pass = 0;
7643 y < subimg_height;
7644 y++, row += interlace_increment[pass])
7646 while (subimg_height <= row)
7647 row = interlace_start[++pass];
7649 for (x = 0; x < subimg_width; x++)
7651 int c = raster[y * subimg_width + x];
7652 if (transparency_color_index != c || disposal != 1)
7653 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7654 pixel_colors[c]);
7658 else
7660 for (y = 0; y < subimg_height; ++y)
7661 for (x = 0; x < subimg_width; ++x)
7663 int c = raster[y * subimg_width + x];
7664 if (transparency_color_index != c || disposal != 1)
7665 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7666 pixel_colors[c]);
7671 #ifdef COLOR_TABLE_SUPPORT
7672 img->colors = colors_in_color_table (&img->ncolors);
7673 free_color_table ();
7674 #endif /* COLOR_TABLE_SUPPORT */
7676 /* Save GIF image extension data for `image-metadata'.
7677 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7678 img->lisp_data = Qnil;
7679 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7681 int delay = 0;
7682 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7683 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7684 /* Append (... FUNCTION "BYTES") */
7686 img->lisp_data
7687 = Fcons (make_number (ext->Function),
7688 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7689 img->lisp_data));
7690 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7691 && ext->ByteCount == 4)
7693 delay = ext->Bytes[2] << CHAR_BIT;
7694 delay |= ext->Bytes[1];
7697 img->lisp_data = list2 (Qextension_data, img->lisp_data);
7698 if (delay)
7699 img->lisp_data
7700 = Fcons (Qdelay,
7701 Fcons (make_float (delay / 100.0),
7702 img->lisp_data));
7705 if (gif->ImageCount > 1)
7706 img->lisp_data = Fcons (Qcount,
7707 Fcons (make_number (gif->ImageCount),
7708 img->lisp_data));
7710 if (gif_close (gif, &gif_err) == GIF_ERROR)
7712 #if 5 <= GIFLIB_MAJOR
7713 char *error_text = GifErrorString (gif_err);
7715 if (error_text)
7716 image_error ("Error closing `%s': %s",
7717 img->spec, build_string (error_text));
7718 #else
7719 image_error ("Error closing `%s'", img->spec, Qnil);
7720 #endif
7723 /* Maybe fill in the background field while we have ximg handy. */
7724 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7725 /* Casting avoids a GCC warning. */
7726 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7728 /* Put ximg into the image. */
7729 image_put_x_image (f, img, ximg, 0);
7731 return 1;
7734 #else /* !HAVE_GIF */
7736 #ifdef HAVE_NS
7737 static bool
7738 gif_load (struct frame *f, struct image *img)
7740 return ns_load_image (f, img,
7741 image_spec_value (img->spec, QCfile, NULL),
7742 image_spec_value (img->spec, QCdata, NULL));
7744 #endif /* HAVE_NS */
7746 #endif /* HAVE_GIF */
7749 #ifdef HAVE_IMAGEMAGICK
7751 /***********************************************************************
7752 ImageMagick
7753 ***********************************************************************/
7755 /* Scale an image size by returning SIZE / DIVISOR * MULTIPLIER,
7756 safely rounded and clipped to int range. */
7758 static int
7759 scale_image_size (int size, size_t divisor, size_t multiplier)
7761 if (divisor != 0)
7763 double s = size;
7764 double scaled = s * multiplier / divisor + 0.5;
7765 if (scaled < INT_MAX)
7766 return scaled;
7768 return INT_MAX;
7771 /* Compute the desired size of an image with native size WIDTH x HEIGHT.
7772 Use SPEC to deduce the size. Store the desired size into
7773 *D_WIDTH x *D_HEIGHT. Store -1 x -1 if the native size is OK. */
7774 static void
7775 compute_image_size (size_t width, size_t height,
7776 Lisp_Object spec,
7777 int *d_width, int *d_height)
7779 Lisp_Object value;
7780 int desired_width, desired_height;
7782 /* If width and/or height is set in the display spec assume we want
7783 to scale to those values. If either h or w is unspecified, the
7784 unspecified should be calculated from the specified to preserve
7785 aspect ratio. */
7786 value = image_spec_value (spec, QCwidth, NULL);
7787 desired_width = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7788 value = image_spec_value (spec, QCheight, NULL);
7789 desired_height = NATNUMP (value) ? min (XFASTINT (value), INT_MAX) : -1;
7791 if (desired_width == -1)
7793 value = image_spec_value (spec, QCmax_width, NULL);
7794 if (NATNUMP (value))
7796 int max_width = min (XFASTINT (value), INT_MAX);
7797 if (max_width < width)
7799 /* The image is wider than :max-width. */
7800 desired_width = max_width;
7801 if (desired_height == -1)
7803 desired_height = scale_image_size (desired_width,
7804 width, height);
7805 value = image_spec_value (spec, QCmax_height, NULL);
7806 if (NATNUMP (value))
7808 int max_height = min (XFASTINT (value), INT_MAX);
7809 if (max_height < desired_height)
7811 desired_height = max_height;
7812 desired_width = scale_image_size (desired_height,
7813 height, width);
7821 if (desired_height == -1)
7823 value = image_spec_value (spec, QCmax_height, NULL);
7824 if (NATNUMP (value))
7826 int max_height = min (XFASTINT (value), INT_MAX);
7827 if (max_height < height)
7828 desired_height = max_height;
7832 if (desired_width != -1 && desired_height == -1)
7833 /* w known, calculate h. */
7834 desired_height = scale_image_size (desired_width, width, height);
7836 if (desired_width == -1 && desired_height != -1)
7837 /* h known, calculate w. */
7838 desired_width = scale_image_size (desired_height, height, width);
7840 *d_width = desired_width;
7841 *d_height = desired_height;
7844 static Lisp_Object Qimagemagick;
7846 static bool imagemagick_image_p (Lisp_Object);
7847 static bool imagemagick_load (struct frame *, struct image *);
7848 static void imagemagick_clear_image (struct frame *, struct image *);
7850 /* Indices of image specification fields in imagemagick_format. */
7852 enum imagemagick_keyword_index
7854 IMAGEMAGICK_TYPE,
7855 IMAGEMAGICK_DATA,
7856 IMAGEMAGICK_FILE,
7857 IMAGEMAGICK_ASCENT,
7858 IMAGEMAGICK_MARGIN,
7859 IMAGEMAGICK_RELIEF,
7860 IMAGEMAGICK_ALGORITHM,
7861 IMAGEMAGICK_HEURISTIC_MASK,
7862 IMAGEMAGICK_MASK,
7863 IMAGEMAGICK_BACKGROUND,
7864 IMAGEMAGICK_HEIGHT,
7865 IMAGEMAGICK_WIDTH,
7866 IMAGEMAGICK_MAX_HEIGHT,
7867 IMAGEMAGICK_MAX_WIDTH,
7868 IMAGEMAGICK_FORMAT,
7869 IMAGEMAGICK_ROTATION,
7870 IMAGEMAGICK_CROP,
7871 IMAGEMAGICK_LAST
7874 /* Vector of image_keyword structures describing the format
7875 of valid user-defined image specifications. */
7877 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7879 {":type", IMAGE_SYMBOL_VALUE, 1},
7880 {":data", IMAGE_STRING_VALUE, 0},
7881 {":file", IMAGE_STRING_VALUE, 0},
7882 {":ascent", IMAGE_ASCENT_VALUE, 0},
7883 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7884 {":relief", IMAGE_INTEGER_VALUE, 0},
7885 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7886 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7887 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7888 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7889 {":height", IMAGE_INTEGER_VALUE, 0},
7890 {":width", IMAGE_INTEGER_VALUE, 0},
7891 {":max-height", IMAGE_INTEGER_VALUE, 0},
7892 {":max-width", IMAGE_INTEGER_VALUE, 0},
7893 {":format", IMAGE_SYMBOL_VALUE, 0},
7894 {":rotation", IMAGE_NUMBER_VALUE, 0},
7895 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7898 #if defined HAVE_NTGUI && defined WINDOWSNT
7899 static bool init_imagemagick_functions (void);
7900 #else
7901 #define init_imagemagick_functions NULL
7902 #endif
7904 /* Structure describing the image type for any image handled via
7905 ImageMagick. */
7907 static struct image_type imagemagick_type =
7909 &Qimagemagick,
7910 imagemagick_image_p,
7911 imagemagick_load,
7912 imagemagick_clear_image,
7913 init_imagemagick_functions,
7914 NULL
7917 /* Free X resources of imagemagick image IMG which is used on frame F. */
7919 static void
7920 imagemagick_clear_image (struct frame *f,
7921 struct image *img)
7923 x_clear_image (f, img);
7926 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7927 this by calling parse_image_spec and supplying the keywords that
7928 identify the IMAGEMAGICK format. */
7930 static bool
7931 imagemagick_image_p (Lisp_Object object)
7933 struct image_keyword fmt[IMAGEMAGICK_LAST];
7934 memcpy (fmt, imagemagick_format, sizeof fmt);
7936 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7937 return 0;
7939 /* Must specify either the :data or :file keyword. */
7940 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7943 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7944 Therefore rename the function so it doesn't collide with ImageMagick. */
7945 #define DrawRectangle DrawRectangleGif
7946 #include <wand/MagickWand.h>
7948 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7949 Emacs seems to work fine with the hidden version, so unhide it. */
7950 #include <magick/version.h>
7951 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7952 extern WandExport void PixelGetMagickColor (const PixelWand *,
7953 MagickPixelPacket *);
7954 #endif
7956 /* Log ImageMagick error message.
7957 Useful when a ImageMagick function returns the status `MagickFalse'. */
7959 static void
7960 imagemagick_error (MagickWand *wand)
7962 char *description;
7963 ExceptionType severity;
7965 description = MagickGetException (wand, &severity);
7966 image_error ("ImageMagick error: %s",
7967 build_string (description),
7968 Qnil);
7969 MagickRelinquishMemory (description);
7972 /* Possibly give ImageMagick some extra help to determine the image
7973 type by supplying a "dummy" filename based on the Content-Type. */
7975 static char *
7976 imagemagick_filename_hint (Lisp_Object spec, char hint_buffer[MaxTextExtent])
7978 Lisp_Object symbol = intern ("image-format-suffixes");
7979 Lisp_Object val = find_symbol_value (symbol);
7980 Lisp_Object format;
7982 if (! CONSP (val))
7983 return NULL;
7985 format = image_spec_value (spec, intern (":format"), NULL);
7986 val = Fcar_safe (Fcdr_safe (Fassq (format, val)));
7987 if (! STRINGP (val))
7988 return NULL;
7990 /* It's OK to truncate the hint if it has MaxTextExtent or more bytes,
7991 as ImageMagick would ignore the extra bytes anyway. */
7992 snprintf (hint_buffer, MaxTextExtent, "/tmp/foo.%s", SSDATA (val));
7993 return hint_buffer;
7996 /* Animated images (e.g., GIF89a) are composed from one "master image"
7997 (which is the first one, and then there's a number of images that
7998 follow. If following images have non-transparent colors, these are
7999 composed "on top" of the master image. So, in general, one has to
8000 compute ann the preceding images to be able to display a particular
8001 sub-image.
8003 Computing all the preceding images is too slow, so we maintain a
8004 cache of previously computed images. We have to maintain a cache
8005 separate from the image cache, because the images may be scaled
8006 before display. */
8008 struct animation_cache
8010 MagickWand *wand;
8011 int index;
8012 struct timespec update_time;
8013 struct animation_cache *next;
8014 char signature[FLEXIBLE_ARRAY_MEMBER];
8017 static struct animation_cache *animation_cache = NULL;
8019 static struct animation_cache *
8020 imagemagick_create_cache (char *signature)
8022 struct animation_cache *cache
8023 = xmalloc (offsetof (struct animation_cache, signature)
8024 + strlen (signature) + 1);
8025 cache->wand = 0;
8026 cache->index = 0;
8027 cache->next = 0;
8028 strcpy (cache->signature, signature);
8029 return cache;
8032 /* Discard cached images that haven't been used for a minute. */
8033 static void
8034 imagemagick_prune_animation_cache (void)
8036 struct animation_cache **pcache = &animation_cache;
8037 struct timespec old = timespec_sub (current_timespec (),
8038 make_timespec (60, 0));
8040 while (*pcache)
8042 struct animation_cache *cache = *pcache;
8043 if (timespec_cmp (old, cache->update_time) <= 0)
8044 pcache = &cache->next;
8045 else
8047 if (cache->wand)
8048 DestroyMagickWand (cache->wand);
8049 *pcache = cache->next;
8050 xfree (cache);
8055 static struct animation_cache *
8056 imagemagick_get_animation_cache (MagickWand *wand)
8058 char *signature = MagickGetImageSignature (wand);
8059 struct animation_cache *cache;
8060 struct animation_cache **pcache = &animation_cache;
8062 imagemagick_prune_animation_cache ();
8064 while (1)
8066 cache = *pcache;
8067 if (! cache)
8069 *pcache = cache = imagemagick_create_cache (signature);
8070 break;
8072 if (strcmp (signature, cache->signature) == 0)
8073 break;
8074 pcache = &cache->next;
8077 DestroyString (signature);
8078 cache->update_time = current_timespec ();
8079 return cache;
8082 static MagickWand *
8083 imagemagick_compute_animated_image (MagickWand *super_wand, int ino)
8085 int i;
8086 MagickWand *composite_wand;
8087 size_t dest_width, dest_height;
8088 struct animation_cache *cache = imagemagick_get_animation_cache (super_wand);
8090 MagickSetIteratorIndex (super_wand, 0);
8092 if (ino == 0 || cache->wand == NULL || cache->index > ino)
8094 composite_wand = MagickGetImage (super_wand);
8095 if (cache->wand)
8096 DestroyMagickWand (cache->wand);
8098 else
8099 composite_wand = cache->wand;
8101 dest_height = MagickGetImageHeight (composite_wand);
8103 for (i = max (1, cache->index + 1); i <= ino; i++)
8105 MagickWand *sub_wand;
8106 PixelIterator *source_iterator, *dest_iterator;
8107 PixelWand **source, **dest;
8108 size_t source_width, source_height;
8109 ssize_t source_left, source_top;
8110 MagickPixelPacket pixel;
8111 DisposeType dispose;
8112 ptrdiff_t lines = 0;
8114 MagickSetIteratorIndex (super_wand, i);
8115 sub_wand = MagickGetImage (super_wand);
8117 MagickGetImagePage (sub_wand, &source_width, &source_height,
8118 &source_left, &source_top);
8120 /* This flag says how to handle transparent pixels. */
8121 dispose = MagickGetImageDispose (sub_wand);
8123 source_iterator = NewPixelIterator (sub_wand);
8124 if (! source_iterator)
8126 DestroyMagickWand (composite_wand);
8127 DestroyMagickWand (sub_wand);
8128 cache->wand = NULL;
8129 image_error ("Imagemagick pixel iterator creation failed",
8130 Qnil, Qnil);
8131 return NULL;
8134 dest_iterator = NewPixelIterator (composite_wand);
8135 if (! dest_iterator)
8137 DestroyMagickWand (composite_wand);
8138 DestroyMagickWand (sub_wand);
8139 DestroyPixelIterator (source_iterator);
8140 cache->wand = NULL;
8141 image_error ("Imagemagick pixel iterator creation failed",
8142 Qnil, Qnil);
8143 return NULL;
8146 /* The sub-image may not start at origin, so move the destination
8147 iterator to where the sub-image should start. */
8148 if (source_top > 0)
8150 PixelSetIteratorRow (dest_iterator, source_top);
8151 lines = source_top;
8154 while ((source = PixelGetNextIteratorRow (source_iterator, &source_width))
8155 != NULL)
8157 ptrdiff_t x;
8159 /* Sanity check. This shouldn't happen, but apparently
8160 does in some pictures. */
8161 if (++lines >= dest_height)
8162 break;
8164 dest = PixelGetNextIteratorRow (dest_iterator, &dest_width);
8165 for (x = 0; x < source_width; x++)
8167 /* Sanity check. This shouldn't happen, but apparently
8168 also does in some pictures. */
8169 if (x + source_left >= dest_width)
8170 break;
8171 /* Normally we only copy over non-transparent pixels,
8172 but if the disposal method is "Background", then we
8173 copy over all pixels. */
8174 if (dispose == BackgroundDispose || PixelGetAlpha (source[x]))
8176 PixelGetMagickColor (source[x], &pixel);
8177 PixelSetMagickColor (dest[x + source_left], &pixel);
8180 PixelSyncIterator (dest_iterator);
8183 DestroyPixelIterator (source_iterator);
8184 DestroyPixelIterator (dest_iterator);
8185 DestroyMagickWand (sub_wand);
8188 /* Cache a copy for the next iteration. The current wand will be
8189 destroyed by the caller. */
8190 cache->wand = CloneMagickWand (composite_wand);
8191 cache->index = ino;
8193 return composite_wand;
8197 /* Helper function for imagemagick_load, which does the actual loading
8198 given contents and size, apart from frame and image structures,
8199 passed from imagemagick_load. Uses librimagemagick to do most of
8200 the image processing.
8202 F is a pointer to the Emacs frame; IMG to the image structure to
8203 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
8204 be parsed; SIZE is the number of bytes of data; and FILENAME is
8205 either the file name or the image data.
8207 Return true if successful. */
8209 static bool
8210 imagemagick_load_image (struct frame *f, struct image *img,
8211 unsigned char *contents, unsigned int size,
8212 char *filename)
8214 int width, height;
8215 size_t image_width, image_height;
8216 MagickBooleanType status;
8217 XImagePtr ximg;
8218 int x, y;
8219 MagickWand *image_wand;
8220 PixelIterator *iterator;
8221 PixelWand **pixels, *bg_wand = NULL;
8222 MagickPixelPacket pixel;
8223 Lisp_Object image;
8224 Lisp_Object value;
8225 Lisp_Object crop;
8226 EMACS_INT ino;
8227 int desired_width, desired_height;
8228 double rotation;
8229 int pixelwidth;
8230 char hint_buffer[MaxTextExtent];
8231 char *filename_hint = NULL;
8233 /* Handle image index for image types who can contain more than one image.
8234 Interface :index is same as for GIF. First we "ping" the image to see how
8235 many sub-images it contains. Pinging is faster than loading the image to
8236 find out things about it. */
8238 /* Initialize the imagemagick environment. */
8239 MagickWandGenesis ();
8240 image = image_spec_value (img->spec, QCindex, NULL);
8241 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8242 image_wand = NewMagickWand ();
8244 if (filename)
8245 status = MagickReadImage (image_wand, filename);
8246 else
8248 filename_hint = imagemagick_filename_hint (img->spec, hint_buffer);
8249 MagickSetFilename (image_wand, filename_hint);
8250 status = MagickReadImageBlob (image_wand, contents, size);
8253 if (status == MagickFalse)
8255 imagemagick_error (image_wand);
8256 DestroyMagickWand (image_wand);
8257 return 0;
8260 if (ino < 0 || ino >= MagickGetNumberImages (image_wand))
8262 image_error ("Invalid image number `%s' in image `%s'",
8263 image, img->spec);
8264 DestroyMagickWand (image_wand);
8265 return 0;
8268 if (MagickGetImageDelay (image_wand) > 0)
8269 img->lisp_data =
8270 Fcons (Qdelay,
8271 Fcons (make_float (MagickGetImageDelay (image_wand) / 100.0),
8272 img->lisp_data));
8274 if (MagickGetNumberImages (image_wand) > 1)
8275 img->lisp_data =
8276 Fcons (Qcount,
8277 Fcons (make_number (MagickGetNumberImages (image_wand)),
8278 img->lisp_data));
8280 /* If we have an animated image, get the new wand based on the
8281 "super-wand". */
8282 if (MagickGetNumberImages (image_wand) > 1)
8284 MagickWand *super_wand = image_wand;
8285 image_wand = imagemagick_compute_animated_image (super_wand, ino);
8286 if (! image_wand)
8287 image_wand = super_wand;
8288 else
8289 DestroyMagickWand (super_wand);
8292 /* Retrieve the frame's background color, for use later. */
8294 XColor bgcolor;
8295 Lisp_Object specified_bg;
8297 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8298 if (!STRINGP (specified_bg)
8299 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
8300 x_query_frame_background_color (f, &bgcolor);
8302 bg_wand = NewPixelWand ();
8303 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
8304 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
8305 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
8308 compute_image_size (MagickGetImageWidth (image_wand),
8309 MagickGetImageHeight (image_wand),
8310 img->spec, &desired_width, &desired_height);
8312 if (desired_width != -1 && desired_height != -1)
8314 status = MagickScaleImage (image_wand, desired_width, desired_height);
8315 if (status == MagickFalse)
8317 image_error ("Imagemagick scale failed", Qnil, Qnil);
8318 imagemagick_error (image_wand);
8319 goto imagemagick_error;
8323 /* crop behaves similar to image slicing in Emacs but is more memory
8324 efficient. */
8325 crop = image_spec_value (img->spec, QCcrop, NULL);
8327 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8329 /* After some testing, it seems MagickCropImage is the fastest crop
8330 function in ImageMagick. This crop function seems to do less copying
8331 than the alternatives, but it still reads the entire image into memory
8332 before cropping, which is apparently difficult to avoid when using
8333 imagemagick. */
8334 size_t crop_width = XINT (XCAR (crop));
8335 crop = XCDR (crop);
8336 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
8338 size_t crop_height = XINT (XCAR (crop));
8339 crop = XCDR (crop);
8340 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8342 ssize_t crop_x = XINT (XCAR (crop));
8343 crop = XCDR (crop);
8344 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
8346 ssize_t crop_y = XINT (XCAR (crop));
8347 MagickCropImage (image_wand, crop_width, crop_height,
8348 crop_x, crop_y);
8354 /* Furthermore :rotation. we need background color and angle for
8355 rotation. */
8357 TODO background handling for rotation specified_bg =
8358 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
8359 (specified_bg). */
8360 value = image_spec_value (img->spec, QCrotation, NULL);
8361 if (FLOATP (value))
8363 rotation = extract_float (value);
8364 status = MagickRotateImage (image_wand, bg_wand, rotation);
8365 if (status == MagickFalse)
8367 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
8368 imagemagick_error (image_wand);
8369 goto imagemagick_error;
8373 /* Set the canvas background color to the frame or specified
8374 background, and flatten the image. Note: as of ImageMagick
8375 6.6.0, SVG image transparency is not handled properly
8376 (e.g. etc/images/splash.svg shows a white background always). */
8378 MagickWand *new_wand;
8379 MagickSetImageBackgroundColor (image_wand, bg_wand);
8380 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
8381 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
8382 #else
8383 new_wand = MagickFlattenImages (image_wand);
8384 #endif
8385 DestroyMagickWand (image_wand);
8386 image_wand = new_wand;
8389 /* Finally we are done manipulating the image. Figure out the
8390 resulting width/height and transfer ownership to Emacs. */
8391 image_height = MagickGetImageHeight (image_wand);
8392 image_width = MagickGetImageWidth (image_wand);
8394 if (! (image_width <= INT_MAX && image_height <= INT_MAX
8395 && check_image_size (f, image_width, image_height)))
8397 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8398 goto imagemagick_error;
8401 width = image_width;
8402 height = image_height;
8404 /* We can now get a valid pixel buffer from the imagemagick file, if all
8405 went ok. */
8407 init_color_table ();
8409 #if defined (HAVE_MAGICKEXPORTIMAGEPIXELS) && ! defined (HAVE_NS)
8410 if (imagemagick_render_type != 0)
8412 /* Magicexportimage is normally faster than pixelpushing. This
8413 method is also well tested. Some aspects of this method are
8414 ad-hoc and needs to be more researched. */
8415 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
8416 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
8417 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8418 if (!image_create_x_image_and_pixmap (f, img, width, height, imagedepth,
8419 &ximg, 0))
8421 #ifdef COLOR_TABLE_SUPPORT
8422 free_color_table ();
8423 #endif
8424 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8425 goto imagemagick_error;
8428 /* Oddly, the below code doesn't seem to work:*/
8429 /* switch(ximg->bitmap_unit){ */
8430 /* case 8: */
8431 /* pixelwidth=CharPixel; */
8432 /* break; */
8433 /* case 16: */
8434 /* pixelwidth=ShortPixel; */
8435 /* break; */
8436 /* case 32: */
8437 /* pixelwidth=LongPixel; */
8438 /* break; */
8439 /* } */
8441 Here im just guessing the format of the bitmap.
8442 happens to work fine for:
8443 - bw djvu images
8444 on rgb display.
8445 seems about 3 times as fast as pixel pushing(not carefully measured)
8447 pixelwidth = CharPixel; /*??? TODO figure out*/
8448 MagickExportImagePixels (image_wand, 0, 0, width, height,
8449 exportdepth, pixelwidth, ximg->data);
8451 else
8452 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
8454 size_t image_height;
8455 MagickRealType color_scale = 65535.0 / QuantumRange;
8457 /* Try to create a x pixmap to hold the imagemagick pixmap. */
8458 if (!image_create_x_image_and_pixmap (f, img, width, height, 0,
8459 &ximg, 0))
8461 #ifdef COLOR_TABLE_SUPPORT
8462 free_color_table ();
8463 #endif
8464 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
8465 goto imagemagick_error;
8468 /* Copy imagemagick image to x with primitive yet robust pixel
8469 pusher loop. This has been tested a lot with many different
8470 images. */
8472 /* Copy pixels from the imagemagick image structure to the x image map. */
8473 iterator = NewPixelIterator (image_wand);
8474 if (! iterator)
8476 #ifdef COLOR_TABLE_SUPPORT
8477 free_color_table ();
8478 #endif
8479 x_destroy_x_image (ximg);
8480 image_error ("Imagemagick pixel iterator creation failed",
8481 Qnil, Qnil);
8482 goto imagemagick_error;
8485 image_height = MagickGetImageHeight (image_wand);
8486 for (y = 0; y < image_height; y++)
8488 size_t row_width;
8489 pixels = PixelGetNextIteratorRow (iterator, &row_width);
8490 if (! pixels)
8491 break;
8492 int xlim = min (row_width, width);
8493 for (x = 0; x < xlim; x++)
8495 PixelGetMagickColor (pixels[x], &pixel);
8496 XPutPixel (ximg, x, y,
8497 lookup_rgb_color (f,
8498 color_scale * pixel.red,
8499 color_scale * pixel.green,
8500 color_scale * pixel.blue));
8503 DestroyPixelIterator (iterator);
8506 #ifdef COLOR_TABLE_SUPPORT
8507 /* Remember colors allocated for this image. */
8508 img->colors = colors_in_color_table (&img->ncolors);
8509 free_color_table ();
8510 #endif /* COLOR_TABLE_SUPPORT */
8512 img->width = width;
8513 img->height = height;
8515 /* Put ximg into the image. */
8516 image_put_x_image (f, img, ximg, 0);
8518 /* Final cleanup. image_wand should be the only resource left. */
8519 DestroyMagickWand (image_wand);
8520 if (bg_wand) DestroyPixelWand (bg_wand);
8522 /* `MagickWandTerminus' terminates the imagemagick environment. */
8523 MagickWandTerminus ();
8525 return 1;
8527 imagemagick_error:
8528 DestroyMagickWand (image_wand);
8529 if (bg_wand) DestroyPixelWand (bg_wand);
8531 MagickWandTerminus ();
8532 /* TODO more cleanup. */
8533 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
8534 return 0;
8538 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
8539 successful. this function will go into the imagemagick_type structure, and
8540 the prototype thus needs to be compatible with that structure. */
8542 static bool
8543 imagemagick_load (struct frame *f, struct image *img)
8545 bool success_p = 0;
8546 Lisp_Object file_name;
8548 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8549 file_name = image_spec_value (img->spec, QCfile, NULL);
8550 if (STRINGP (file_name))
8552 Lisp_Object file;
8554 file = x_find_image_file (file_name);
8555 if (!STRINGP (file))
8557 image_error ("Cannot find image file `%s'", file_name, Qnil);
8558 return 0;
8560 #ifdef WINDOWSNT
8561 file = ansi_encode_filename (file);
8562 #endif
8563 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
8565 /* Else its not a file, its a lisp object. Load the image from a
8566 lisp object rather than a file. */
8567 else
8569 Lisp_Object data;
8571 data = image_spec_value (img->spec, QCdata, NULL);
8572 if (!STRINGP (data))
8574 image_error ("Invalid image data `%s'", data, Qnil);
8575 return 0;
8577 success_p = imagemagick_load_image (f, img, SDATA (data),
8578 SBYTES (data), NULL);
8581 return success_p;
8584 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8585 doc: /* Return a list of image types supported by ImageMagick.
8586 Each entry in this list is a symbol named after an ImageMagick format
8587 tag. See the ImageMagick manual for a list of ImageMagick formats and
8588 their descriptions (http://www.imagemagick.org/script/formats.php).
8589 You can also try the shell command: `identify -list format'.
8591 Note that ImageMagick recognizes many file-types that Emacs does not
8592 recognize as images, such as C. See `imagemagick-types-enable'
8593 and `imagemagick-types-inhibit'. */)
8594 (void)
8596 Lisp_Object typelist = Qnil;
8597 size_t numf = 0;
8598 ExceptionInfo ex;
8599 char **imtypes;
8600 size_t i;
8602 GetExceptionInfo(&ex);
8603 imtypes = GetMagickList ("*", &numf, &ex);
8604 DestroyExceptionInfo(&ex);
8606 for (i = 0; i < numf; i++)
8608 Lisp_Object imagemagicktype = intern (imtypes[i]);
8609 typelist = Fcons (imagemagicktype, typelist);
8610 imtypes[i] = MagickRelinquishMemory (imtypes[i]);
8613 MagickRelinquishMemory (imtypes);
8614 return Fnreverse (typelist);
8617 #endif /* defined (HAVE_IMAGEMAGICK) */
8621 /***********************************************************************
8623 ***********************************************************************/
8625 #ifdef HAVE_RSVG
8627 /* Function prototypes. */
8629 static bool svg_image_p (Lisp_Object object);
8630 static bool svg_load (struct frame *f, struct image *img);
8632 static bool svg_load_image (struct frame *, struct image *,
8633 unsigned char *, ptrdiff_t, char *);
8635 /* The symbol `svg' identifying images of this type. */
8637 static Lisp_Object Qsvg;
8639 /* Indices of image specification fields in svg_format, below. */
8641 enum svg_keyword_index
8643 SVG_TYPE,
8644 SVG_DATA,
8645 SVG_FILE,
8646 SVG_ASCENT,
8647 SVG_MARGIN,
8648 SVG_RELIEF,
8649 SVG_ALGORITHM,
8650 SVG_HEURISTIC_MASK,
8651 SVG_MASK,
8652 SVG_BACKGROUND,
8653 SVG_LAST
8656 /* Vector of image_keyword structures describing the format
8657 of valid user-defined image specifications. */
8659 static const struct image_keyword svg_format[SVG_LAST] =
8661 {":type", IMAGE_SYMBOL_VALUE, 1},
8662 {":data", IMAGE_STRING_VALUE, 0},
8663 {":file", IMAGE_STRING_VALUE, 0},
8664 {":ascent", IMAGE_ASCENT_VALUE, 0},
8665 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8666 {":relief", IMAGE_INTEGER_VALUE, 0},
8667 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8668 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8669 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8670 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8673 # if defined HAVE_NTGUI && defined WINDOWSNT
8674 static bool init_svg_functions (void);
8675 # else
8676 #define init_svg_functions NULL
8677 # endif
8679 /* Structure describing the image type `svg'. Its the same type of
8680 structure defined for all image formats, handled by emacs image
8681 functions. See struct image_type in dispextern.h. */
8683 static struct image_type svg_type =
8685 &Qsvg,
8686 svg_image_p,
8687 svg_load,
8688 x_clear_image,
8689 init_svg_functions,
8690 NULL
8694 /* Return true if OBJECT is a valid SVG image specification. Do
8695 this by calling parse_image_spec and supplying the keywords that
8696 identify the SVG format. */
8698 static bool
8699 svg_image_p (Lisp_Object object)
8701 struct image_keyword fmt[SVG_LAST];
8702 memcpy (fmt, svg_format, sizeof fmt);
8704 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8705 return 0;
8707 /* Must specify either the :data or :file keyword. */
8708 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8711 # include <librsvg/rsvg.h>
8713 # ifdef WINDOWSNT
8715 /* SVG library functions. */
8716 DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
8717 DEF_DLL_FN (void, rsvg_handle_get_dimensions,
8718 (RsvgHandle *, RsvgDimensionData *));
8719 DEF_DLL_FN (gboolean, rsvg_handle_write,
8720 (RsvgHandle *, const guchar *, gsize, GError **));
8721 DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8722 DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8723 DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
8725 DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8726 DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8727 DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8728 DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8729 DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8730 DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8731 DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8732 DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8734 # if ! GLIB_CHECK_VERSION (2, 36, 0)
8735 DEF_DLL_FN (void, g_type_init, (void));
8736 # endif
8737 DEF_DLL_FN (void, g_object_unref, (gpointer));
8738 DEF_DLL_FN (void, g_error_free, (GError *));
8740 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8742 static bool
8743 init_svg_functions (void)
8745 HMODULE library, gdklib = NULL, glib = NULL, gobject = NULL;
8747 if (!(glib = w32_delayed_load (Qglib))
8748 || !(gobject = w32_delayed_load (Qgobject))
8749 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
8750 || !(library = w32_delayed_load (Qsvg)))
8752 if (gdklib) FreeLibrary (gdklib);
8753 if (gobject) FreeLibrary (gobject);
8754 if (glib) FreeLibrary (glib);
8755 return 0;
8758 LOAD_DLL_FN (library, rsvg_handle_new);
8759 LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
8760 LOAD_DLL_FN (library, rsvg_handle_write);
8761 LOAD_DLL_FN (library, rsvg_handle_close);
8762 LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
8763 LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
8765 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
8766 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
8767 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
8768 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
8769 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
8770 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
8771 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
8772 LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8774 # if ! GLIB_CHECK_VERSION (2, 36, 0)
8775 LOAD_DLL_FN (gobject, g_type_init);
8776 # endif
8777 LOAD_DLL_FN (gobject, g_object_unref);
8778 LOAD_DLL_FN (glib, g_error_free);
8780 return 1;
8783 /* The following aliases for library functions allow dynamic loading
8784 to be used on some platforms. */
8786 # undef gdk_pixbuf_get_bits_per_sample
8787 # undef gdk_pixbuf_get_colorspace
8788 # undef gdk_pixbuf_get_has_alpha
8789 # undef gdk_pixbuf_get_height
8790 # undef gdk_pixbuf_get_n_channels
8791 # undef gdk_pixbuf_get_pixels
8792 # undef gdk_pixbuf_get_rowstride
8793 # undef gdk_pixbuf_get_width
8794 # undef g_error_free
8795 # undef g_object_unref
8796 # undef g_type_init
8797 # undef rsvg_handle_close
8798 # undef rsvg_handle_get_dimensions
8799 # undef rsvg_handle_get_pixbuf
8800 # undef rsvg_handle_new
8801 # undef rsvg_handle_set_base_uri
8802 # undef rsvg_handle_write
8804 # define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
8805 # define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
8806 # define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
8807 # define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
8808 # define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
8809 # define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
8810 # define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
8811 # define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
8812 # define g_error_free fn_g_error_free
8813 # define g_object_unref fn_g_object_unref
8814 # define g_type_init fn_g_type_init
8815 # define rsvg_handle_close fn_rsvg_handle_close
8816 # define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
8817 # define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
8818 # define rsvg_handle_new fn_rsvg_handle_new
8819 # define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
8820 # define rsvg_handle_write fn_rsvg_handle_write
8822 # endif /* !WINDOWSNT */
8824 /* Load SVG image IMG for use on frame F. Value is true if
8825 successful. */
8827 static bool
8828 svg_load (struct frame *f, struct image *img)
8830 bool success_p = 0;
8831 Lisp_Object file_name;
8833 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8834 file_name = image_spec_value (img->spec, QCfile, NULL);
8835 if (STRINGP (file_name))
8837 Lisp_Object file;
8838 unsigned char *contents;
8839 ptrdiff_t size;
8841 file = x_find_image_file (file_name);
8842 if (!STRINGP (file))
8844 image_error ("Cannot find image file `%s'", file_name, Qnil);
8845 return 0;
8848 /* Read the entire file into memory. */
8849 contents = slurp_file (SSDATA (file), &size);
8850 if (contents == NULL)
8852 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8853 return 0;
8855 /* If the file was slurped into memory properly, parse it. */
8856 success_p = svg_load_image (f, img, contents, size, SSDATA (file));
8857 xfree (contents);
8859 /* Else its not a file, its a lisp object. Load the image from a
8860 lisp object rather than a file. */
8861 else
8863 Lisp_Object data, original_filename;
8865 data = image_spec_value (img->spec, QCdata, NULL);
8866 if (!STRINGP (data))
8868 image_error ("Invalid image data `%s'", data, Qnil);
8869 return 0;
8871 original_filename = BVAR (current_buffer, filename);
8872 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data),
8873 (NILP (original_filename) ? NULL
8874 : SSDATA (original_filename)));
8877 return success_p;
8880 /* svg_load_image is a helper function for svg_load, which does the
8881 actual loading given contents and size, apart from frame and image
8882 structures, passed from svg_load.
8884 Uses librsvg to do most of the image processing.
8886 Returns true when successful. */
8887 static bool
8888 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8889 struct image *img, /* Pointer to emacs image structure. */
8890 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8891 ptrdiff_t size, /* Size of data in bytes. */
8892 char *filename) /* Name of SVG file being loaded. */
8894 RsvgHandle *rsvg_handle;
8895 RsvgDimensionData dimension_data;
8896 GError *err = NULL;
8897 GdkPixbuf *pixbuf;
8898 int width;
8899 int height;
8900 const guint8 *pixels;
8901 int rowstride;
8902 XImagePtr ximg;
8903 Lisp_Object specified_bg;
8904 XColor background;
8905 int x;
8906 int y;
8908 #if ! GLIB_CHECK_VERSION (2, 36, 0)
8909 /* g_type_init is a glib function that must be called prior to
8910 using gnome type library functions (obsolete since 2.36.0). */
8911 g_type_init ();
8912 #endif
8914 /* Make a handle to a new rsvg object. */
8915 rsvg_handle = rsvg_handle_new ();
8917 /* Set base_uri for properly handling referenced images (via 'href').
8918 See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
8919 (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
8920 if (filename)
8921 rsvg_handle_set_base_uri(rsvg_handle, filename);
8923 /* Parse the contents argument and fill in the rsvg_handle. */
8924 rsvg_handle_write (rsvg_handle, contents, size, &err);
8925 if (err) goto rsvg_error;
8927 /* The parsing is complete, rsvg_handle is ready to used, close it
8928 for further writes. */
8929 rsvg_handle_close (rsvg_handle, &err);
8930 if (err) goto rsvg_error;
8932 rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8933 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8935 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8936 goto rsvg_error;
8939 /* We can now get a valid pixel buffer from the svg file, if all
8940 went ok. */
8941 pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
8942 if (!pixbuf) goto rsvg_error;
8943 g_object_unref (rsvg_handle);
8945 /* Extract some meta data from the svg handle. */
8946 width = gdk_pixbuf_get_width (pixbuf);
8947 height = gdk_pixbuf_get_height (pixbuf);
8948 pixels = gdk_pixbuf_get_pixels (pixbuf);
8949 rowstride = gdk_pixbuf_get_rowstride (pixbuf);
8951 /* Validate the svg meta data. */
8952 eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8953 eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
8954 eassert (gdk_pixbuf_get_has_alpha (pixbuf));
8955 eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8957 /* Try to create a x pixmap to hold the svg pixmap. */
8958 if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
8960 g_object_unref (pixbuf);
8961 return 0;
8964 init_color_table ();
8966 /* Handle alpha channel by combining the image with a background
8967 color. */
8968 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8969 if (!STRINGP (specified_bg)
8970 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
8971 x_query_frame_background_color (f, &background);
8973 /* SVG pixmaps specify transparency in the last byte, so right
8974 shift 8 bits to get rid of it, since emacs doesn't support
8975 transparency. */
8976 background.red >>= 8;
8977 background.green >>= 8;
8978 background.blue >>= 8;
8980 /* This loop handles opacity values, since Emacs assumes
8981 non-transparent images. Each pixel must be "flattened" by
8982 calculating the resulting color, given the transparency of the
8983 pixel, and the image background color. */
8984 for (y = 0; y < height; ++y)
8986 for (x = 0; x < width; ++x)
8988 int red;
8989 int green;
8990 int blue;
8991 int opacity;
8993 red = *pixels++;
8994 green = *pixels++;
8995 blue = *pixels++;
8996 opacity = *pixels++;
8998 red = ((red * opacity)
8999 + (background.red * ((1 << 8) - opacity)));
9000 green = ((green * opacity)
9001 + (background.green * ((1 << 8) - opacity)));
9002 blue = ((blue * opacity)
9003 + (background.blue * ((1 << 8) - opacity)));
9005 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
9008 pixels += rowstride - 4 * width;
9011 #ifdef COLOR_TABLE_SUPPORT
9012 /* Remember colors allocated for this image. */
9013 img->colors = colors_in_color_table (&img->ncolors);
9014 free_color_table ();
9015 #endif /* COLOR_TABLE_SUPPORT */
9017 g_object_unref (pixbuf);
9019 img->width = width;
9020 img->height = height;
9022 /* Maybe fill in the background field while we have ximg handy.
9023 Casting avoids a GCC warning. */
9024 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
9026 /* Put ximg into the image. */
9027 image_put_x_image (f, img, ximg, 0);
9029 return 1;
9031 rsvg_error:
9032 g_object_unref (rsvg_handle);
9033 /* FIXME: Use error->message so the user knows what is the actual
9034 problem with the image. */
9035 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
9036 g_error_free (err);
9037 return 0;
9040 #endif /* defined (HAVE_RSVG) */
9045 /***********************************************************************
9046 Ghostscript
9047 ***********************************************************************/
9049 #ifdef HAVE_X_WINDOWS
9050 #define HAVE_GHOSTSCRIPT 1
9051 #endif /* HAVE_X_WINDOWS */
9053 #ifdef HAVE_GHOSTSCRIPT
9055 static bool gs_image_p (Lisp_Object object);
9056 static bool gs_load (struct frame *f, struct image *img);
9057 static void gs_clear_image (struct frame *f, struct image *img);
9059 /* Keyword symbols. */
9061 static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
9063 /* Indices of image specification fields in gs_format, below. */
9065 enum gs_keyword_index
9067 GS_TYPE,
9068 GS_PT_WIDTH,
9069 GS_PT_HEIGHT,
9070 GS_FILE,
9071 GS_LOADER,
9072 GS_BOUNDING_BOX,
9073 GS_ASCENT,
9074 GS_MARGIN,
9075 GS_RELIEF,
9076 GS_ALGORITHM,
9077 GS_HEURISTIC_MASK,
9078 GS_MASK,
9079 GS_BACKGROUND,
9080 GS_LAST
9083 /* Vector of image_keyword structures describing the format
9084 of valid user-defined image specifications. */
9086 static const struct image_keyword gs_format[GS_LAST] =
9088 {":type", IMAGE_SYMBOL_VALUE, 1},
9089 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9090 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9091 {":file", IMAGE_STRING_VALUE, 1},
9092 {":loader", IMAGE_FUNCTION_VALUE, 0},
9093 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9094 {":ascent", IMAGE_ASCENT_VALUE, 0},
9095 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
9096 {":relief", IMAGE_INTEGER_VALUE, 0},
9097 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9098 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9099 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9100 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9103 /* Structure describing the image type `ghostscript'. */
9105 static struct image_type gs_type =
9107 &Qpostscript,
9108 gs_image_p,
9109 gs_load,
9110 gs_clear_image,
9111 NULL,
9112 NULL
9116 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9118 static void
9119 gs_clear_image (struct frame *f, struct image *img)
9121 x_clear_image (f, img);
9125 /* Return true if OBJECT is a valid Ghostscript image
9126 specification. */
9128 static bool
9129 gs_image_p (Lisp_Object object)
9131 struct image_keyword fmt[GS_LAST];
9132 Lisp_Object tem;
9133 int i;
9135 memcpy (fmt, gs_format, sizeof fmt);
9137 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9138 return 0;
9140 /* Bounding box must be a list or vector containing 4 integers. */
9141 tem = fmt[GS_BOUNDING_BOX].value;
9142 if (CONSP (tem))
9144 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9145 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9146 return 0;
9147 if (!NILP (tem))
9148 return 0;
9150 else if (VECTORP (tem))
9152 if (ASIZE (tem) != 4)
9153 return 0;
9154 for (i = 0; i < 4; ++i)
9155 if (!INTEGERP (AREF (tem, i)))
9156 return 0;
9158 else
9159 return 0;
9161 return 1;
9165 /* Load Ghostscript image IMG for use on frame F. Value is true
9166 if successful. */
9168 static bool
9169 gs_load (struct frame *f, struct image *img)
9171 uprintmax_t printnum1, printnum2;
9172 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
9173 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9174 Lisp_Object frame;
9175 double in_width, in_height;
9176 Lisp_Object pixel_colors = Qnil;
9178 /* Compute pixel size of pixmap needed from the given size in the
9179 image specification. Sizes in the specification are in pt. 1 pt
9180 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9181 info. */
9182 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9183 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
9184 in_width *= FRAME_RES_X (f);
9185 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9186 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
9187 in_height *= FRAME_RES_Y (f);
9189 if (! (in_width <= INT_MAX && in_height <= INT_MAX
9190 && check_image_size (f, in_width, in_height)))
9192 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
9193 return 0;
9195 img->width = in_width;
9196 img->height = in_height;
9198 /* Create the pixmap. */
9199 eassert (img->pixmap == NO_PIXMAP);
9201 if (x_check_image_size (0, img->width, img->height))
9203 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9204 block_input ();
9205 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9206 img->width, img->height,
9207 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9208 unblock_input ();
9211 if (!img->pixmap)
9213 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
9214 return 0;
9217 /* Call the loader to fill the pixmap. It returns a process object
9218 if successful. We do not record_unwind_protect here because
9219 other places in redisplay like calling window scroll functions
9220 don't either. Let the Lisp loader use `unwind-protect' instead. */
9221 printnum1 = FRAME_X_WINDOW (f);
9222 printnum2 = img->pixmap;
9223 window_and_pixmap_id
9224 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9226 printnum1 = FRAME_FOREGROUND_PIXEL (f);
9227 printnum2 = FRAME_BACKGROUND_PIXEL (f);
9228 pixel_colors
9229 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
9231 XSETFRAME (frame, f);
9232 loader = image_spec_value (img->spec, QCloader, NULL);
9233 if (NILP (loader))
9234 loader = intern ("gs-load-image");
9236 img->lisp_data = call6 (loader, frame, img->spec,
9237 make_number (img->width),
9238 make_number (img->height),
9239 window_and_pixmap_id,
9240 pixel_colors);
9241 return PROCESSP (img->lisp_data);
9245 /* Kill the Ghostscript process that was started to fill PIXMAP on
9246 frame F. Called from XTread_socket when receiving an event
9247 telling Emacs that Ghostscript has finished drawing. */
9249 void
9250 x_kill_gs_process (Pixmap pixmap, struct frame *f)
9252 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9253 int class;
9254 ptrdiff_t i;
9255 struct image *img;
9257 /* Find the image containing PIXMAP. */
9258 for (i = 0; i < c->used; ++i)
9259 if (c->images[i]->pixmap == pixmap)
9260 break;
9262 /* Should someone in between have cleared the image cache, for
9263 instance, give up. */
9264 if (i == c->used)
9265 return;
9267 /* Kill the GS process. We should have found PIXMAP in the image
9268 cache and its image should contain a process object. */
9269 img = c->images[i];
9270 eassert (PROCESSP (img->lisp_data));
9271 Fkill_process (img->lisp_data, Qnil);
9272 img->lisp_data = Qnil;
9274 #if defined (HAVE_X_WINDOWS)
9276 /* On displays with a mutable colormap, figure out the colors
9277 allocated for the image by looking at the pixels of an XImage for
9278 img->pixmap. */
9279 class = FRAME_X_VISUAL (f)->class;
9280 if (class != StaticColor && class != StaticGray && class != TrueColor)
9282 XImagePtr ximg;
9284 block_input ();
9286 /* Try to get an XImage for img->pixmep. */
9287 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9288 0, 0, img->width, img->height, ~0, ZPixmap);
9289 if (ximg)
9291 int x, y;
9293 /* Initialize the color table. */
9294 init_color_table ();
9296 /* For each pixel of the image, look its color up in the
9297 color table. After having done so, the color table will
9298 contain an entry for each color used by the image. */
9299 for (y = 0; y < img->height; ++y)
9300 for (x = 0; x < img->width; ++x)
9302 unsigned long pixel = XGetPixel (ximg, x, y);
9303 lookup_pixel_color (f, pixel);
9306 /* Record colors in the image. Free color table and XImage. */
9307 #ifdef COLOR_TABLE_SUPPORT
9308 img->colors = colors_in_color_table (&img->ncolors);
9309 free_color_table ();
9310 #endif
9311 XDestroyImage (ximg);
9313 #if 0 /* This doesn't seem to be the case. If we free the colors
9314 here, we get a BadAccess later in x_clear_image when
9315 freeing the colors. */
9316 /* We have allocated colors once, but Ghostscript has also
9317 allocated colors on behalf of us. So, to get the
9318 reference counts right, free them once. */
9319 if (img->ncolors)
9320 x_free_colors (f, img->colors, img->ncolors);
9321 #endif
9323 else
9324 image_error ("Cannot get X image of `%s'; colors will not be freed",
9325 img->spec, Qnil);
9327 unblock_input ();
9329 #endif /* HAVE_X_WINDOWS */
9331 /* Now that we have the pixmap, compute mask and transform the
9332 image if requested. */
9333 block_input ();
9334 postprocess_image (f, img);
9335 unblock_input ();
9338 #endif /* HAVE_GHOSTSCRIPT */
9341 /***********************************************************************
9342 Tests
9343 ***********************************************************************/
9345 #ifdef GLYPH_DEBUG
9347 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9348 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9349 (Lisp_Object spec)
9351 return valid_image_p (spec) ? Qt : Qnil;
9355 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
9356 (Lisp_Object spec)
9358 ptrdiff_t id = -1;
9360 if (valid_image_p (spec))
9361 id = lookup_image (SELECTED_FRAME (), spec);
9363 debug_print (spec);
9364 return make_number (id);
9367 #endif /* GLYPH_DEBUG */
9370 /***********************************************************************
9371 Initialization
9372 ***********************************************************************/
9374 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
9375 doc: /* Initialize image library implementing image type TYPE.
9376 Return non-nil if TYPE is a supported image type.
9378 If image libraries are loaded dynamically (currently only the case on
9379 MS-Windows), load the library for TYPE if it is not yet loaded, using
9380 the library file(s) specified by `dynamic-library-alist'. */)
9381 (Lisp_Object type)
9383 return lookup_image_type (type) ? Qt : Qnil;
9386 /* Look up image type TYPE, and return a pointer to its image_type
9387 structure. Return 0 if TYPE is not a known image type. */
9389 static struct image_type *
9390 lookup_image_type (Lisp_Object type)
9392 /* Types pbm and xbm are built-in and always available. */
9393 if (EQ (type, Qpbm))
9394 return define_image_type (&pbm_type);
9396 if (EQ (type, Qxbm))
9397 return define_image_type (&xbm_type);
9399 #if defined (HAVE_XPM) || defined (HAVE_NS)
9400 if (EQ (type, Qxpm))
9401 return define_image_type (&xpm_type);
9402 #endif
9404 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9405 if (EQ (type, Qjpeg))
9406 return define_image_type (&jpeg_type);
9407 #endif
9409 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9410 if (EQ (type, Qtiff))
9411 return define_image_type (&tiff_type);
9412 #endif
9414 #if defined (HAVE_GIF) || defined (HAVE_NS)
9415 if (EQ (type, Qgif))
9416 return define_image_type (&gif_type);
9417 #endif
9419 #if defined (HAVE_PNG) || defined (HAVE_NS)
9420 if (EQ (type, Qpng))
9421 return define_image_type (&png_type);
9422 #endif
9424 #if defined (HAVE_RSVG)
9425 if (EQ (type, Qsvg))
9426 return define_image_type (&svg_type);
9427 #endif
9429 #if defined (HAVE_IMAGEMAGICK)
9430 if (EQ (type, Qimagemagick))
9431 return define_image_type (&imagemagick_type);
9432 #endif
9434 #ifdef HAVE_GHOSTSCRIPT
9435 if (EQ (type, Qpostscript))
9436 return define_image_type (&gs_type);
9437 #endif
9439 return NULL;
9442 /* Reset image_types before dumping.
9443 Called from Fdump_emacs. */
9445 void
9446 reset_image_types (void)
9448 while (image_types)
9450 struct image_type *next = image_types->next;
9451 xfree (image_types);
9452 image_types = next;
9456 void
9457 syms_of_image (void)
9459 /* Initialize this only once; it will be reset before dumping. */
9460 image_types = NULL;
9462 /* Must be defined now because we're going to update it below, while
9463 defining the supported image types. */
9464 DEFVAR_LISP ("image-types", Vimage_types,
9465 doc: /* List of potentially supported image types.
9466 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9467 To check whether it is really supported, use `image-type-available-p'. */);
9468 Vimage_types = Qnil;
9470 DEFVAR_LISP ("max-image-size", Vmax_image_size,
9471 doc: /* Maximum size of images.
9472 Emacs will not load an image into memory if its pixel width or
9473 pixel height exceeds this limit.
9475 If the value is an integer, it directly specifies the maximum
9476 image height and width, measured in pixels. If it is a floating
9477 point number, it specifies the maximum image height and width
9478 as a ratio to the frame height and width. If the value is
9479 non-numeric, there is no explicit limit on the size of images. */);
9480 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9482 DEFSYM (Qcount, "count");
9483 DEFSYM (Qextension_data, "extension-data");
9484 DEFSYM (Qdelay, "delay");
9486 DEFSYM (QCascent, ":ascent");
9487 DEFSYM (QCmargin, ":margin");
9488 DEFSYM (QCrelief, ":relief");
9489 DEFSYM (QCconversion, ":conversion");
9490 DEFSYM (QCcolor_symbols, ":color-symbols");
9491 DEFSYM (QCheuristic_mask, ":heuristic-mask");
9492 DEFSYM (QCindex, ":index");
9493 DEFSYM (QCgeometry, ":geometry");
9494 DEFSYM (QCcrop, ":crop");
9495 DEFSYM (QCrotation, ":rotation");
9496 DEFSYM (QCmatrix, ":matrix");
9497 DEFSYM (QCcolor_adjustment, ":color-adjustment");
9498 DEFSYM (QCmask, ":mask");
9500 DEFSYM (Qlaplace, "laplace");
9501 DEFSYM (Qemboss, "emboss");
9502 DEFSYM (Qedge_detection, "edge-detection");
9503 DEFSYM (Qheuristic, "heuristic");
9505 DEFSYM (Qpostscript, "postscript");
9506 DEFSYM (QCmax_width, ":max-width");
9507 DEFSYM (QCmax_height, ":max-height");
9508 #ifdef HAVE_GHOSTSCRIPT
9509 ADD_IMAGE_TYPE (Qpostscript);
9510 DEFSYM (QCloader, ":loader");
9511 DEFSYM (QCbounding_box, ":bounding-box");
9512 DEFSYM (QCpt_width, ":pt-width");
9513 DEFSYM (QCpt_height, ":pt-height");
9514 #endif /* HAVE_GHOSTSCRIPT */
9516 #ifdef HAVE_NTGUI
9517 DEFSYM (Qlibpng_version, "libpng-version");
9518 Fset (Qlibpng_version,
9519 #if HAVE_PNG
9520 make_number (PNG_LIBPNG_VER)
9521 #else
9522 make_number (-1)
9523 #endif
9525 DEFSYM (Qlibgif_version, "libgif-version");
9526 Fset (Qlibgif_version,
9527 #ifdef HAVE_GIF
9528 make_number (GIFLIB_MAJOR * 10000
9529 + GIFLIB_MINOR * 100
9530 + GIFLIB_RELEASE)
9531 #else
9532 make_number (-1)
9533 #endif
9535 DEFSYM (Qlibjpeg_version, "libjpeg-version");
9536 Fset (Qlibjpeg_version,
9537 #if HAVE_JPEG
9538 make_number (JPEG_LIB_VERSION)
9539 #else
9540 make_number (-1)
9541 #endif
9543 #endif
9545 DEFSYM (Qpbm, "pbm");
9546 ADD_IMAGE_TYPE (Qpbm);
9548 DEFSYM (Qxbm, "xbm");
9549 ADD_IMAGE_TYPE (Qxbm);
9551 #if defined (HAVE_XPM) || defined (HAVE_NS)
9552 DEFSYM (Qxpm, "xpm");
9553 ADD_IMAGE_TYPE (Qxpm);
9554 #endif
9556 #if defined (HAVE_JPEG) || defined (HAVE_NS)
9557 DEFSYM (Qjpeg, "jpeg");
9558 ADD_IMAGE_TYPE (Qjpeg);
9559 #endif
9561 #if defined (HAVE_TIFF) || defined (HAVE_NS)
9562 DEFSYM (Qtiff, "tiff");
9563 ADD_IMAGE_TYPE (Qtiff);
9564 #endif
9566 #if defined (HAVE_GIF) || defined (HAVE_NS)
9567 DEFSYM (Qgif, "gif");
9568 ADD_IMAGE_TYPE (Qgif);
9569 #endif
9571 #if defined (HAVE_PNG) || defined (HAVE_NS)
9572 DEFSYM (Qpng, "png");
9573 ADD_IMAGE_TYPE (Qpng);
9574 #endif
9576 #if defined (HAVE_IMAGEMAGICK)
9577 DEFSYM (Qimagemagick, "imagemagick");
9578 ADD_IMAGE_TYPE (Qimagemagick);
9579 #endif
9581 #if defined (HAVE_RSVG)
9582 DEFSYM (Qsvg, "svg");
9583 ADD_IMAGE_TYPE (Qsvg);
9584 #ifdef HAVE_NTGUI
9585 /* Other libraries used directly by svg code. */
9586 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
9587 DEFSYM (Qglib, "glib");
9588 DEFSYM (Qgobject, "gobject");
9589 #endif /* HAVE_NTGUI */
9590 #endif /* HAVE_RSVG */
9592 defsubr (&Sinit_image_library);
9593 #ifdef HAVE_IMAGEMAGICK
9594 defsubr (&Simagemagick_types);
9595 #endif
9596 defsubr (&Sclear_image_cache);
9597 defsubr (&Simage_flush);
9598 defsubr (&Simage_size);
9599 defsubr (&Simage_mask_p);
9600 defsubr (&Simage_metadata);
9602 #ifdef GLYPH_DEBUG
9603 defsubr (&Simagep);
9604 defsubr (&Slookup_image);
9605 #endif
9607 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
9608 doc: /* Non-nil means always draw a cross over disabled images.
9609 Disabled images are those having a `:conversion disabled' property.
9610 A cross is always drawn on black & white displays. */);
9611 cross_disabled_images = 0;
9613 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
9614 doc: /* List of directories to search for window system bitmap files. */);
9615 Vx_bitmap_file_path = decode_env_path (0, PATH_BITMAPS, 0);
9617 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
9618 doc: /* Maximum time after which images are removed from the cache.
9619 When an image has not been displayed this many seconds, Emacs
9620 automatically removes it from the image cache. If the cache contains
9621 a large number of images, the actual eviction time may be shorter.
9622 The value can also be nil, meaning the cache is never cleared.
9624 The function `clear-image-cache' disregards this variable. */);
9625 Vimage_cache_eviction_delay = make_number (300);
9626 #ifdef HAVE_IMAGEMAGICK
9627 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9628 doc: /* Integer indicating which ImageMagick rendering method to use.
9629 The options are:
9630 0 -- the default method (pixel pushing)
9631 1 -- a newer method ("MagickExportImagePixels") that may perform
9632 better (speed etc) in some cases, but has not been as thoroughly
9633 tested with Emacs as the default method. This method requires
9634 ImageMagick version 6.4.6 (approximately) or later.
9635 */);
9636 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9637 imagemagick_render_type = 0;
9638 #endif