Fix typos.
[emacs.git] / src / image.c
blobf9f6ce7004024ee54a700092ed8282ac72ad8056
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2013 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <stdio.h>
22 #include <unistd.h>
24 #ifdef HAVE_PNG
25 #if defined HAVE_LIBPNG_PNG_H
26 # include <libpng/png.h>
27 #else
28 # include <png.h>
29 #endif
30 #endif
32 #include <setjmp.h>
34 #include <c-ctype.h>
36 /* This makes the fields of a Display accessible, in Xlib header files. */
38 #define XLIB_ILLEGAL_ACCESS
40 #include "lisp.h"
41 #include "frame.h"
42 #include "window.h"
43 #include "dispextern.h"
44 #include "blockinput.h"
45 #include "systime.h"
46 #include <epaths.h>
47 #include "character.h"
48 #include "coding.h"
49 #include "termhooks.h"
50 #include "font.h"
52 #ifdef HAVE_SYS_STAT_H
53 #include <sys/stat.h>
54 #endif /* HAVE_SYS_STAT_H */
56 #ifdef HAVE_SYS_TYPES_H
57 #include <sys/types.h>
58 #endif /* HAVE_SYS_TYPES_H */
60 #ifdef HAVE_WINDOW_SYSTEM
61 #include TERM_HEADER
62 #endif /* HAVE_WINDOW_SYSTEM */
64 #ifdef HAVE_X_WINDOWS
65 #define COLOR_TABLE_SUPPORT 1
67 typedef struct x_bitmap_record Bitmap_Record;
68 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
69 #define NO_PIXMAP None
71 #define PIX_MASK_RETAIN 0
72 #define PIX_MASK_DRAW 1
73 #endif /* HAVE_X_WINDOWS */
75 #ifdef HAVE_NTGUI
77 /* We need (or want) w32.h only when we're _not_ compiling for Cygwin. */
78 #ifdef WINDOWSNT
79 # include "w32.h"
80 #endif
82 /* W32_TODO : Color tables on W32. */
83 #undef COLOR_TABLE_SUPPORT
85 typedef struct w32_bitmap_record Bitmap_Record;
86 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
87 #define NO_PIXMAP 0
89 #define PIX_MASK_RETAIN 0
90 #define PIX_MASK_DRAW 1
92 #define x_defined_color w32_defined_color
93 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
95 /* Version of libpng that we were compiled with, or -1 if no PNG
96 support was compiled in. This is tested by w32-win.el to correctly
97 set up the alist used to search for PNG libraries. */
98 Lisp_Object Qlibpng_version;
99 #endif /* HAVE_NTGUI */
101 #ifdef HAVE_NS
102 #undef COLOR_TABLE_SUPPORT
104 typedef struct ns_bitmap_record Bitmap_Record;
106 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
107 #define NO_PIXMAP 0
109 #define ZPixmap 0
111 #define PIX_MASK_RETAIN 0
112 #define PIX_MASK_DRAW 1
114 #define x_defined_color(f, name, color_def, alloc) \
115 ns_defined_color (f, name, color_def, alloc, 0)
116 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
117 #endif /* HAVE_NS */
120 /* The symbol `postscript' identifying images of this type. */
122 static Lisp_Object Qpostscript;
124 static void x_disable_image (struct frame *, struct image *);
125 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
126 Lisp_Object);
128 static void init_color_table (void);
129 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
130 #ifdef COLOR_TABLE_SUPPORT
131 static void free_color_table (void);
132 static unsigned long *colors_in_color_table (int *n);
133 #endif
135 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
136 id, which is just an int that this section returns. Bitmaps are
137 reference counted so they can be shared among frames.
139 Bitmap indices are guaranteed to be > 0, so a negative number can
140 be used to indicate no bitmap.
142 If you use x_create_bitmap_from_data, then you must keep track of
143 the bitmaps yourself. That is, creating a bitmap from the same
144 data more than once will not be caught. */
146 #ifdef HAVE_NS
147 XImagePtr
148 XGetImage (Display *display, Pixmap pixmap, int x, int y,
149 unsigned int width, unsigned int height,
150 unsigned long plane_mask, int format)
152 /* TODO: not sure what this function is supposed to do.. */
153 ns_retain_object (pixmap);
154 return pixmap;
157 /* Use with images created by ns_image_for_XPM. */
158 unsigned long
159 XGetPixel (XImagePtr ximage, int x, int y)
161 return ns_get_pixel (ximage, x, y);
164 /* Use with images created by ns_image_for_XPM; alpha set to 1;
165 pixel is assumed to be in RGB form. */
166 void
167 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
169 ns_put_pixel (ximage, x, y, pixel);
171 #endif /* HAVE_NS */
174 /* Functions to access the contents of a bitmap, given an id. */
177 x_bitmap_height (FRAME_PTR f, ptrdiff_t id)
179 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
183 x_bitmap_width (FRAME_PTR f, ptrdiff_t id)
185 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
188 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
189 ptrdiff_t
190 x_bitmap_pixmap (FRAME_PTR f, ptrdiff_t id)
192 /* HAVE_NTGUI needs the explicit cast here. */
193 return (ptrdiff_t) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
195 #endif
197 #ifdef HAVE_X_WINDOWS
199 x_bitmap_mask (FRAME_PTR f, ptrdiff_t id)
201 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
203 #endif
205 /* Allocate a new bitmap record. Returns index of new record. */
207 static ptrdiff_t
208 x_allocate_bitmap_record (FRAME_PTR f)
210 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
211 ptrdiff_t i;
213 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
214 return ++dpyinfo->bitmaps_last;
216 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
217 if (dpyinfo->bitmaps[i].refcount == 0)
218 return i + 1;
220 dpyinfo->bitmaps =
221 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
222 10, -1, sizeof *dpyinfo->bitmaps);
223 return ++dpyinfo->bitmaps_last;
226 /* Add one reference to the reference count of the bitmap with id ID. */
228 void
229 x_reference_bitmap (FRAME_PTR f, ptrdiff_t id)
231 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
234 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
236 ptrdiff_t
237 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
239 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
240 ptrdiff_t id;
242 #ifdef HAVE_X_WINDOWS
243 Pixmap bitmap;
244 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
245 bits, width, height);
246 if (! bitmap)
247 return -1;
248 #endif /* HAVE_X_WINDOWS */
250 #ifdef HAVE_NTGUI
251 Pixmap bitmap;
252 bitmap = CreateBitmap (width, height,
253 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
254 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
255 bits);
256 if (! bitmap)
257 return -1;
258 #endif /* HAVE_NTGUI */
260 #ifdef HAVE_NS
261 void *bitmap = ns_image_from_XBM (bits, width, height);
262 if (!bitmap)
263 return -1;
264 #endif
266 id = x_allocate_bitmap_record (f);
268 #ifdef HAVE_NS
269 dpyinfo->bitmaps[id - 1].img = bitmap;
270 dpyinfo->bitmaps[id - 1].depth = 1;
271 #endif
273 dpyinfo->bitmaps[id - 1].file = NULL;
274 dpyinfo->bitmaps[id - 1].height = height;
275 dpyinfo->bitmaps[id - 1].width = width;
276 dpyinfo->bitmaps[id - 1].refcount = 1;
278 #ifdef HAVE_X_WINDOWS
279 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
280 dpyinfo->bitmaps[id - 1].have_mask = 0;
281 dpyinfo->bitmaps[id - 1].depth = 1;
282 #endif /* HAVE_X_WINDOWS */
284 #ifdef HAVE_NTGUI
285 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
286 dpyinfo->bitmaps[id - 1].hinst = NULL;
287 dpyinfo->bitmaps[id - 1].depth = 1;
288 #endif /* HAVE_NTGUI */
290 return id;
293 /* Create bitmap from file FILE for frame F. */
295 ptrdiff_t
296 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
298 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
300 #ifdef HAVE_NTGUI
301 return -1; /* W32_TODO : bitmap support */
302 #endif /* HAVE_NTGUI */
304 #ifdef HAVE_NS
305 ptrdiff_t id;
306 void *bitmap = ns_image_from_file (file);
308 if (!bitmap)
309 return -1;
312 id = x_allocate_bitmap_record (f);
313 dpyinfo->bitmaps[id - 1].img = bitmap;
314 dpyinfo->bitmaps[id - 1].refcount = 1;
315 dpyinfo->bitmaps[id - 1].file = xmalloc (SBYTES (file) + 1);
316 dpyinfo->bitmaps[id - 1].depth = 1;
317 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
318 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
319 strcpy (dpyinfo->bitmaps[id - 1].file, SSDATA (file));
320 return id;
321 #endif
323 #ifdef HAVE_X_WINDOWS
324 unsigned int width, height;
325 Pixmap bitmap;
326 int xhot, yhot, result;
327 ptrdiff_t id;
328 Lisp_Object found;
329 int fd;
330 char *filename;
332 /* Look for an existing bitmap with the same name. */
333 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
335 if (dpyinfo->bitmaps[id].refcount
336 && dpyinfo->bitmaps[id].file
337 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
339 ++dpyinfo->bitmaps[id].refcount;
340 return id + 1;
344 /* Search bitmap-file-path for the file, if appropriate. */
345 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
346 if (fd < 0)
347 return -1;
348 emacs_close (fd);
350 filename = SSDATA (found);
352 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
353 filename, &width, &height, &bitmap, &xhot, &yhot);
354 if (result != BitmapSuccess)
355 return -1;
357 id = x_allocate_bitmap_record (f);
358 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
359 dpyinfo->bitmaps[id - 1].have_mask = 0;
360 dpyinfo->bitmaps[id - 1].refcount = 1;
361 dpyinfo->bitmaps[id - 1].file = xmalloc (SBYTES (file) + 1);
362 dpyinfo->bitmaps[id - 1].depth = 1;
363 dpyinfo->bitmaps[id - 1].height = height;
364 dpyinfo->bitmaps[id - 1].width = width;
365 strcpy (dpyinfo->bitmaps[id - 1].file, SSDATA (file));
367 return id;
368 #endif /* HAVE_X_WINDOWS */
371 /* Free bitmap B. */
373 static void
374 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
376 #ifdef HAVE_X_WINDOWS
377 XFreePixmap (dpyinfo->display, bm->pixmap);
378 if (bm->have_mask)
379 XFreePixmap (dpyinfo->display, bm->mask);
380 #endif /* HAVE_X_WINDOWS */
382 #ifdef HAVE_NTGUI
383 DeleteObject (bm->pixmap);
384 #endif /* HAVE_NTGUI */
386 #ifdef HAVE_NS
387 ns_release_object (bm->img);
388 #endif
390 if (bm->file)
392 xfree (bm->file);
393 bm->file = NULL;
397 /* Remove reference to bitmap with id number ID. */
399 void
400 x_destroy_bitmap (FRAME_PTR f, ptrdiff_t id)
402 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
404 if (id > 0)
406 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
408 if (--bm->refcount == 0)
410 block_input ();
411 free_bitmap_record (dpyinfo, bm);
412 unblock_input ();
417 /* Free all the bitmaps for the display specified by DPYINFO. */
419 void
420 x_destroy_all_bitmaps (Display_Info *dpyinfo)
422 ptrdiff_t i;
423 Bitmap_Record *bm = dpyinfo->bitmaps;
425 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
426 if (bm->refcount > 0)
427 free_bitmap_record (dpyinfo, bm);
429 dpyinfo->bitmaps_last = 0;
432 static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
433 XImagePtr *, Pixmap *);
434 static void x_destroy_x_image (XImagePtr ximg);
436 #ifdef HAVE_X_WINDOWS
438 /* Useful functions defined in the section
439 `Image type independent image structures' below. */
441 static unsigned long four_corners_best (XImagePtr ximg,
442 int *corners,
443 unsigned long width,
444 unsigned long height);
447 /* Create a mask of a bitmap. Note is this not a perfect mask.
448 It's nicer with some borders in this context */
450 void
451 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
453 Pixmap pixmap, mask;
454 XImagePtr ximg, mask_img;
455 unsigned long width, height;
456 bool result;
457 unsigned long bg;
458 unsigned long x, y, xp, xm, yp, ym;
459 GC gc;
461 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
463 if (!(id > 0))
464 return;
466 pixmap = x_bitmap_pixmap (f, id);
467 width = x_bitmap_width (f, id);
468 height = x_bitmap_height (f, id);
470 block_input ();
471 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
472 ~0, ZPixmap);
474 if (!ximg)
476 unblock_input ();
477 return;
480 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
482 unblock_input ();
483 if (!result)
485 XDestroyImage (ximg);
486 return;
489 bg = four_corners_best (ximg, NULL, width, height);
491 for (y = 0; y < ximg->height; ++y)
493 for (x = 0; x < ximg->width; ++x)
495 xp = x != ximg->width - 1 ? x + 1 : 0;
496 xm = x != 0 ? x - 1 : ximg->width - 1;
497 yp = y != ximg->height - 1 ? y + 1 : 0;
498 ym = y != 0 ? y - 1 : ximg->height - 1;
499 if (XGetPixel (ximg, x, y) == bg
500 && XGetPixel (ximg, x, yp) == bg
501 && XGetPixel (ximg, x, ym) == bg
502 && XGetPixel (ximg, xp, y) == bg
503 && XGetPixel (ximg, xp, yp) == bg
504 && XGetPixel (ximg, xp, ym) == bg
505 && XGetPixel (ximg, xm, y) == bg
506 && XGetPixel (ximg, xm, yp) == bg
507 && XGetPixel (ximg, xm, ym) == bg)
508 XPutPixel (mask_img, x, y, 0);
509 else
510 XPutPixel (mask_img, x, y, 1);
514 eassert (input_blocked_p ());
515 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
516 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
517 width, height);
518 XFreeGC (FRAME_X_DISPLAY (f), gc);
520 dpyinfo->bitmaps[id - 1].have_mask = 1;
521 dpyinfo->bitmaps[id - 1].mask = mask;
523 XDestroyImage (ximg);
524 x_destroy_x_image (mask_img);
527 #endif /* HAVE_X_WINDOWS */
530 /***********************************************************************
531 Image types
532 ***********************************************************************/
534 /* List of supported image types. Use define_image_type to add new
535 types. Use lookup_image_type to find a type for a given symbol. */
537 static struct image_type *image_types;
539 /* The symbol `xbm' which is used as the type symbol for XBM images. */
541 static Lisp_Object Qxbm;
543 /* Keywords. */
545 Lisp_Object QCascent, QCmargin, QCrelief;
546 Lisp_Object QCconversion;
547 static Lisp_Object QCheuristic_mask;
548 static Lisp_Object QCcolor_symbols;
549 static Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry;
550 static Lisp_Object QCcrop, QCrotation;
552 /* Other symbols. */
554 static Lisp_Object Qcount, Qextension_data, Qdelay;
555 static Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
557 /* Forward function prototypes. */
559 static struct image_type *lookup_image_type (Lisp_Object);
560 static void x_laplace (struct frame *, struct image *);
561 static void x_emboss (struct frame *, struct image *);
562 static void x_build_heuristic_mask (struct frame *, struct image *,
563 Lisp_Object);
564 #ifdef WINDOWSNT
565 extern Lisp_Object Vlibrary_cache;
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 /* Free resources, then free IMG. */
1003 img->type->free (f, img);
1004 xfree (img);
1008 /* Return true if the given widths and heights are valid for display. */
1010 static bool
1011 check_image_size (struct frame *f, int width, int height)
1013 int w, h;
1015 if (width <= 0 || height <= 0)
1016 return 0;
1018 if (INTEGERP (Vmax_image_size))
1019 return (width <= XINT (Vmax_image_size)
1020 && height <= XINT (Vmax_image_size));
1021 else if (FLOATP (Vmax_image_size))
1023 if (f != NULL)
1025 w = FRAME_PIXEL_WIDTH (f);
1026 h = FRAME_PIXEL_HEIGHT (f);
1028 else
1029 w = h = 1024; /* Arbitrary size for unknown frame. */
1030 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1031 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1033 else
1034 return 1;
1037 /* Prepare image IMG for display on frame F. Must be called before
1038 drawing an image. */
1040 void
1041 prepare_image_for_display (struct frame *f, struct image *img)
1043 /* We're about to display IMG, so set its timestamp to `now'. */
1044 img->timestamp = current_emacs_time ();
1046 /* If IMG doesn't have a pixmap yet, load it now, using the image
1047 type dependent loader function. */
1048 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1049 img->load_failed_p = ! img->type->load (f, img);
1054 /* Value is the number of pixels for the ascent of image IMG when
1055 drawn in face FACE. */
1058 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1060 int height;
1061 int ascent;
1063 if (slice->height == img->height)
1064 height = img->height + img->vmargin;
1065 else if (slice->y == 0)
1066 height = slice->height + img->vmargin;
1067 else
1068 height = slice->height;
1070 if (img->ascent == CENTERED_IMAGE_ASCENT)
1072 if (face->font)
1074 #ifdef HAVE_NTGUI
1075 /* W32 specific version. Why?. ++kfs */
1076 ascent = height / 2 - (FONT_DESCENT (face->font)
1077 - FONT_BASE (face->font)) / 2;
1078 #else
1079 /* This expression is arranged so that if the image can't be
1080 exactly centered, it will be moved slightly up. This is
1081 because a typical font is `top-heavy' (due to the presence
1082 uppercase letters), so the image placement should err towards
1083 being top-heavy too. It also just generally looks better. */
1084 ascent = (height + FONT_BASE (face->font)
1085 - FONT_DESCENT (face->font) + 1) / 2;
1086 #endif /* HAVE_NTGUI */
1088 else
1089 ascent = height / 2;
1091 else
1092 ascent = height * (img->ascent / 100.0);
1094 return ascent;
1098 /* Image background colors. */
1100 /* Find the "best" corner color of a bitmap.
1101 On W32, XIMG is assumed to a device context with the bitmap selected. */
1103 static RGB_PIXEL_COLOR
1104 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1105 unsigned long width, unsigned long height)
1107 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1108 int i, best_count;
1110 if (corners && corners[BOT_CORNER] >= 0)
1112 /* Get the colors at the corner_pixels of ximg. */
1113 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1114 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1115 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1116 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1118 else
1120 /* Get the colors at the corner_pixels of ximg. */
1121 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1122 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1123 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1124 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1126 /* Choose the most frequently found color as background. */
1127 for (i = best_count = 0; i < 4; ++i)
1129 int j, n;
1131 for (j = n = 0; j < 4; ++j)
1132 if (corner_pixels[i] == corner_pixels[j])
1133 ++n;
1135 if (n > best_count)
1136 best = corner_pixels[i], best_count = n;
1139 return best;
1142 /* Portability macros */
1144 #ifdef HAVE_NTGUI
1146 #define Destroy_Image(img_dc, prev) \
1147 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1149 #define Free_Pixmap(display, pixmap) \
1150 DeleteObject (pixmap)
1152 #elif defined (HAVE_NS)
1154 #define Destroy_Image(ximg, dummy) \
1155 ns_release_object (ximg)
1157 #define Free_Pixmap(display, pixmap) \
1158 ns_release_object (pixmap)
1160 #else
1162 #define Destroy_Image(ximg, dummy) \
1163 XDestroyImage (ximg)
1165 #define Free_Pixmap(display, pixmap) \
1166 XFreePixmap (display, pixmap)
1168 #endif /* !HAVE_NTGUI && !HAVE_NS */
1171 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1172 it is guessed heuristically. If non-zero, XIMG is an existing
1173 XImage object (or device context with the image selected on W32) to
1174 use for the heuristic. */
1176 RGB_PIXEL_COLOR
1177 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1179 if (! img->background_valid)
1180 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1182 bool free_ximg = !ximg;
1183 #ifdef HAVE_NTGUI
1184 HGDIOBJ prev;
1185 #endif /* HAVE_NTGUI */
1187 if (free_ximg)
1189 #ifndef HAVE_NTGUI
1190 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1191 0, 0, img->width, img->height, ~0, ZPixmap);
1192 #else
1193 HDC frame_dc = get_frame_dc (f);
1194 ximg = CreateCompatibleDC (frame_dc);
1195 release_frame_dc (f, frame_dc);
1196 prev = SelectObject (ximg, img->pixmap);
1197 #endif /* !HAVE_NTGUI */
1200 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1202 if (free_ximg)
1203 Destroy_Image (ximg, prev);
1205 img->background_valid = 1;
1208 return img->background;
1211 /* Return the `background_transparent' field of IMG. If IMG doesn't
1212 have one yet, it is guessed heuristically. If non-zero, MASK is an
1213 existing XImage object to use for the heuristic. */
1216 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1218 if (! img->background_transparent_valid)
1219 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1221 if (img->mask)
1223 bool free_mask = !mask;
1224 #ifdef HAVE_NTGUI
1225 HGDIOBJ prev;
1226 #endif /* HAVE_NTGUI */
1228 if (free_mask)
1230 #ifndef HAVE_NTGUI
1231 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1232 0, 0, img->width, img->height, ~0, ZPixmap);
1233 #else
1234 HDC frame_dc = get_frame_dc (f);
1235 mask = CreateCompatibleDC (frame_dc);
1236 release_frame_dc (f, frame_dc);
1237 prev = SelectObject (mask, img->mask);
1238 #endif /* HAVE_NTGUI */
1241 img->background_transparent
1242 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1244 if (free_mask)
1245 Destroy_Image (mask, prev);
1247 else
1248 img->background_transparent = 0;
1250 img->background_transparent_valid = 1;
1253 return img->background_transparent;
1257 /***********************************************************************
1258 Helper functions for X image types
1259 ***********************************************************************/
1261 /* Clear X resources of image IMG on frame F. PIXMAP_P means free the
1262 pixmap if any. MASK_P means clear the mask pixmap if any.
1263 COLORS_P means free colors allocated for the image, if any. */
1265 static void
1266 x_clear_image_1 (struct frame *f, struct image *img, bool pixmap_p,
1267 bool mask_p, bool colors_p)
1269 if (pixmap_p && img->pixmap)
1271 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1272 img->pixmap = NO_PIXMAP;
1273 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1274 img->background_valid = 0;
1277 if (mask_p && img->mask)
1279 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1280 img->mask = NO_PIXMAP;
1281 img->background_transparent_valid = 0;
1284 if (colors_p && img->ncolors)
1286 /* W32_TODO: color table support. */
1287 #ifdef HAVE_X_WINDOWS
1288 x_free_colors (f, img->colors, img->ncolors);
1289 #endif /* HAVE_X_WINDOWS */
1290 xfree (img->colors);
1291 img->colors = NULL;
1292 img->ncolors = 0;
1297 /* Free X resources of image IMG which is used on frame F. */
1299 static void
1300 x_clear_image (struct frame *f, struct image *img)
1302 block_input ();
1303 x_clear_image_1 (f, img, 1, 1, 1);
1304 unblock_input ();
1308 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1309 cannot be allocated, use DFLT. Add a newly allocated color to
1310 IMG->colors, so that it can be freed again. Value is the pixel
1311 color. */
1313 static unsigned long
1314 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1315 unsigned long dflt)
1317 XColor color;
1318 unsigned long result;
1320 eassert (STRINGP (color_name));
1322 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1323 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1324 INT_MAX))
1326 /* This isn't called frequently so we get away with simply
1327 reallocating the color vector to the needed size, here. */
1328 ptrdiff_t ncolors = img->ncolors + 1;
1329 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1330 img->colors[ncolors - 1] = color.pixel;
1331 img->ncolors = ncolors;
1332 result = color.pixel;
1334 else
1335 result = dflt;
1337 return result;
1342 /***********************************************************************
1343 Image Cache
1344 ***********************************************************************/
1346 static void cache_image (struct frame *f, struct image *img);
1348 /* Return a new, initialized image cache that is allocated from the
1349 heap. Call free_image_cache to free an image cache. */
1351 struct image_cache *
1352 make_image_cache (void)
1354 struct image_cache *c = xzalloc (sizeof *c);
1355 int size;
1357 size = 50;
1358 c->images = xmalloc (size * sizeof *c->images);
1359 c->size = size;
1360 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1361 c->buckets = xzalloc (size);
1362 return c;
1366 /* Find an image matching SPEC in the cache, and return it. If no
1367 image is found, return NULL. */
1368 static struct image *
1369 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1371 struct image *img;
1372 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1373 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1375 if (!c) return NULL;
1377 /* If the image spec does not specify a background color, the cached
1378 image must have the same background color as the current frame.
1379 The foreground color must also match, for the sake of monochrome
1380 images.
1382 In fact, we could ignore the foreground color matching condition
1383 for color images, or if the image spec specifies :foreground;
1384 similarly we could ignore the background color matching condition
1385 for formats that don't use transparency (such as jpeg), or if the
1386 image spec specifies :background. However, the extra memory
1387 usage is probably negligible in practice, so we don't bother. */
1389 for (img = c->buckets[i]; img; img = img->next)
1390 if (img->hash == hash
1391 && !NILP (Fequal (img->spec, spec))
1392 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1393 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1394 break;
1395 return img;
1399 /* Search frame F for an image with spec SPEC, and free it. */
1401 static void
1402 uncache_image (struct frame *f, Lisp_Object spec)
1404 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1405 if (img)
1407 free_image (f, img);
1408 /* As display glyphs may still be referring to the image ID, we
1409 must garbage the frame (Bug#6426). */
1410 SET_FRAME_GARBAGED (f);
1415 /* Free image cache of frame F. Be aware that X frames share images
1416 caches. */
1418 void
1419 free_image_cache (struct frame *f)
1421 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1422 if (c)
1424 ptrdiff_t i;
1426 /* Cache should not be referenced by any frame when freed. */
1427 eassert (c->refcount == 0);
1429 for (i = 0; i < c->used; ++i)
1430 free_image (f, c->images[i]);
1431 xfree (c->images);
1432 xfree (c->buckets);
1433 xfree (c);
1434 FRAME_IMAGE_CACHE (f) = NULL;
1439 /* Clear image cache of frame F. FILTER=t means free all images.
1440 FILTER=nil means clear only images that haven't been
1441 displayed for some time.
1442 Else, only free the images which have FILTER in their `dependencies'.
1443 Should be called from time to time to reduce the number of loaded images.
1444 If image-cache-eviction-delay is non-nil, this frees images in the cache
1445 which weren't displayed for at least that many seconds. */
1447 static void
1448 clear_image_cache (struct frame *f, Lisp_Object filter)
1450 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1452 if (c)
1454 ptrdiff_t i, nfreed = 0;
1456 /* Block input so that we won't be interrupted by a SIGIO
1457 while being in an inconsistent state. */
1458 block_input ();
1460 if (!NILP (filter))
1462 /* Filter image cache. */
1463 for (i = 0; i < c->used; ++i)
1465 struct image *img = c->images[i];
1466 if (img && (EQ (Qt, filter)
1467 || !NILP (Fmember (filter, img->dependencies))))
1469 free_image (f, img);
1470 ++nfreed;
1474 else if (INTEGERP (Vimage_cache_eviction_delay))
1476 /* Free cache based on timestamp. */
1477 EMACS_TIME old, t;
1478 double delay;
1479 ptrdiff_t nimages = 0;
1481 for (i = 0; i < c->used; ++i)
1482 if (c->images[i])
1483 nimages++;
1485 /* If the number of cached images has grown unusually large,
1486 decrease the cache eviction delay (Bug#6230). */
1487 delay = XINT (Vimage_cache_eviction_delay);
1488 if (nimages > 40)
1489 delay = 1600 * delay / nimages / nimages;
1490 delay = max (delay, 1);
1492 t = current_emacs_time ();
1493 old = sub_emacs_time (t, EMACS_TIME_FROM_DOUBLE (delay));
1495 for (i = 0; i < c->used; ++i)
1497 struct image *img = c->images[i];
1498 if (img && EMACS_TIME_LT (img->timestamp, old))
1500 free_image (f, img);
1501 ++nfreed;
1506 /* We may be clearing the image cache because, for example,
1507 Emacs was iconified for a longer period of time. In that
1508 case, current matrices may still contain references to
1509 images freed above. So, clear these matrices. */
1510 if (nfreed)
1512 Lisp_Object tail, frame;
1514 FOR_EACH_FRAME (tail, frame)
1516 struct frame *fr = XFRAME (frame);
1517 if (FRAME_IMAGE_CACHE (fr) == c)
1518 clear_current_matrices (fr);
1521 ++windows_or_buffers_changed;
1524 unblock_input ();
1528 void
1529 clear_image_caches (Lisp_Object filter)
1531 /* FIXME: We want to do
1532 * struct terminal *t;
1533 * for (t = terminal_list; t; t = t->next_terminal)
1534 * clear_image_cache (t, filter); */
1535 Lisp_Object tail, frame;
1536 FOR_EACH_FRAME (tail, frame)
1537 if (FRAME_WINDOW_P (XFRAME (frame)))
1538 clear_image_cache (XFRAME (frame), filter);
1541 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1542 0, 1, 0,
1543 doc: /* Clear the image cache.
1544 FILTER nil or a frame means clear all images in the selected frame.
1545 FILTER t means clear the image caches of all frames.
1546 Anything else, means only clear those images which refer to FILTER,
1547 which is then usually a filename. */)
1548 (Lisp_Object filter)
1550 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1551 clear_image_caches (filter);
1552 else
1553 clear_image_cache (decode_window_system_frame (filter), Qt);
1555 return Qnil;
1559 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1560 1, 2, 0,
1561 doc: /* Fush the image with specification SPEC on frame FRAME.
1562 This removes the image from the Emacs image cache. If SPEC specifies
1563 an image file, the next redisplay of this image will read from the
1564 current contents of that file.
1566 FRAME nil or omitted means use the selected frame.
1567 FRAME t means refresh the image on all frames. */)
1568 (Lisp_Object spec, Lisp_Object frame)
1570 if (!valid_image_p (spec))
1571 error ("Invalid image specification");
1573 if (EQ (frame, Qt))
1575 Lisp_Object tail;
1576 FOR_EACH_FRAME (tail, frame)
1578 struct frame *f = XFRAME (frame);
1579 if (FRAME_WINDOW_P (f))
1580 uncache_image (f, spec);
1583 else
1584 uncache_image (decode_window_system_frame (frame), spec);
1586 return Qnil;
1590 /* Compute masks and transform image IMG on frame F, as specified
1591 by the image's specification, */
1593 static void
1594 postprocess_image (struct frame *f, struct image *img)
1596 /* Manipulation of the image's mask. */
1597 if (img->pixmap)
1599 Lisp_Object conversion, spec;
1600 Lisp_Object mask;
1602 spec = img->spec;
1604 /* `:heuristic-mask t'
1605 `:mask heuristic'
1606 means build a mask heuristically.
1607 `:heuristic-mask (R G B)'
1608 `:mask (heuristic (R G B))'
1609 means build a mask from color (R G B) in the
1610 image.
1611 `:mask nil'
1612 means remove a mask, if any. */
1614 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1615 if (!NILP (mask))
1616 x_build_heuristic_mask (f, img, mask);
1617 else
1619 bool found_p;
1621 mask = image_spec_value (spec, QCmask, &found_p);
1623 if (EQ (mask, Qheuristic))
1624 x_build_heuristic_mask (f, img, Qt);
1625 else if (CONSP (mask)
1626 && EQ (XCAR (mask), Qheuristic))
1628 if (CONSP (XCDR (mask)))
1629 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1630 else
1631 x_build_heuristic_mask (f, img, XCDR (mask));
1633 else if (NILP (mask) && found_p && img->mask)
1635 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1636 img->mask = NO_PIXMAP;
1641 /* Should we apply an image transformation algorithm? */
1642 conversion = image_spec_value (spec, QCconversion, NULL);
1643 if (EQ (conversion, Qdisabled))
1644 x_disable_image (f, img);
1645 else if (EQ (conversion, Qlaplace))
1646 x_laplace (f, img);
1647 else if (EQ (conversion, Qemboss))
1648 x_emboss (f, img);
1649 else if (CONSP (conversion)
1650 && EQ (XCAR (conversion), Qedge_detection))
1652 Lisp_Object tem;
1653 tem = XCDR (conversion);
1654 if (CONSP (tem))
1655 x_edge_detection (f, img,
1656 Fplist_get (tem, QCmatrix),
1657 Fplist_get (tem, QCcolor_adjustment));
1663 /* Return the id of image with Lisp specification SPEC on frame F.
1664 SPEC must be a valid Lisp image specification (see valid_image_p). */
1666 ptrdiff_t
1667 lookup_image (struct frame *f, Lisp_Object spec)
1669 struct image *img;
1670 EMACS_UINT hash;
1672 /* F must be a window-system frame, and SPEC must be a valid image
1673 specification. */
1674 eassert (FRAME_WINDOW_P (f));
1675 eassert (valid_image_p (spec));
1677 /* Look up SPEC in the hash table of the image cache. */
1678 hash = sxhash (spec, 0);
1679 img = search_image_cache (f, spec, hash);
1680 if (img && img->load_failed_p)
1682 free_image (f, img);
1683 img = NULL;
1686 /* If not found, create a new image and cache it. */
1687 if (img == NULL)
1689 block_input ();
1690 img = make_image (spec, hash);
1691 cache_image (f, img);
1692 img->load_failed_p = ! img->type->load (f, img);
1693 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1694 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1696 /* If we can't load the image, and we don't have a width and
1697 height, use some arbitrary width and height so that we can
1698 draw a rectangle for it. */
1699 if (img->load_failed_p)
1701 Lisp_Object value;
1703 value = image_spec_value (spec, QCwidth, NULL);
1704 img->width = (INTEGERP (value)
1705 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1706 value = image_spec_value (spec, QCheight, NULL);
1707 img->height = (INTEGERP (value)
1708 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1710 else
1712 /* Handle image type independent image attributes
1713 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1714 `:background COLOR'. */
1715 Lisp_Object ascent, margin, relief, bg;
1716 int relief_bound;
1718 ascent = image_spec_value (spec, QCascent, NULL);
1719 if (INTEGERP (ascent))
1720 img->ascent = XFASTINT (ascent);
1721 else if (EQ (ascent, Qcenter))
1722 img->ascent = CENTERED_IMAGE_ASCENT;
1724 margin = image_spec_value (spec, QCmargin, NULL);
1725 if (INTEGERP (margin))
1726 img->vmargin = img->hmargin = XFASTINT (margin);
1727 else if (CONSP (margin))
1729 img->hmargin = XFASTINT (XCAR (margin));
1730 img->vmargin = XFASTINT (XCDR (margin));
1733 relief = image_spec_value (spec, QCrelief, NULL);
1734 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1735 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1737 img->relief = XINT (relief);
1738 img->hmargin += eabs (img->relief);
1739 img->vmargin += eabs (img->relief);
1742 if (! img->background_valid)
1744 bg = image_spec_value (img->spec, QCbackground, NULL);
1745 if (!NILP (bg))
1747 img->background
1748 = x_alloc_image_color (f, img, bg,
1749 FRAME_BACKGROUND_PIXEL (f));
1750 img->background_valid = 1;
1754 /* Do image transformations and compute masks, unless we
1755 don't have the image yet. */
1756 if (!EQ (*img->type->type, Qpostscript))
1757 postprocess_image (f, img);
1760 unblock_input ();
1763 /* We're using IMG, so set its timestamp to `now'. */
1764 img->timestamp = current_emacs_time ();
1766 /* Value is the image id. */
1767 return img->id;
1771 /* Cache image IMG in the image cache of frame F. */
1773 static void
1774 cache_image (struct frame *f, struct image *img)
1776 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1777 ptrdiff_t i;
1779 /* Find a free slot in c->images. */
1780 for (i = 0; i < c->used; ++i)
1781 if (c->images[i] == NULL)
1782 break;
1784 /* If no free slot found, maybe enlarge c->images. */
1785 if (i == c->used && c->used == c->size)
1786 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1788 /* Add IMG to c->images, and assign IMG an id. */
1789 c->images[i] = img;
1790 img->id = i;
1791 if (i == c->used)
1792 ++c->used;
1794 /* Add IMG to the cache's hash table. */
1795 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1796 img->next = c->buckets[i];
1797 if (img->next)
1798 img->next->prev = img;
1799 img->prev = NULL;
1800 c->buckets[i] = img;
1804 /* Call FN on every image in the image cache of frame F. Used to mark
1805 Lisp Objects in the image cache. */
1807 /* Mark Lisp objects in image IMG. */
1809 static void
1810 mark_image (struct image *img)
1812 mark_object (img->spec);
1813 mark_object (img->dependencies);
1815 if (!NILP (img->lisp_data))
1816 mark_object (img->lisp_data);
1820 void
1821 mark_image_cache (struct image_cache *c)
1823 if (c)
1825 ptrdiff_t i;
1826 for (i = 0; i < c->used; ++i)
1827 if (c->images[i])
1828 mark_image (c->images[i]);
1834 /***********************************************************************
1835 X / NS / W32 support code
1836 ***********************************************************************/
1838 #ifdef WINDOWSNT
1840 /* Macro for defining functions that will be loaded from image DLLs. */
1841 #define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
1843 /* Macro for loading those image functions from the library. */
1844 #define LOAD_IMGLIB_FN(lib,func) { \
1845 fn_##func = (void *) GetProcAddress (lib, #func); \
1846 if (!fn_##func) return 0; \
1849 #endif /* WINDOWSNT */
1851 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
1852 windowing system.
1853 WIDTH and HEIGHT must both be positive.
1854 If XIMG is null, assume it is a bitmap. */
1855 static bool
1856 x_check_image_size (XImagePtr ximg, int width, int height)
1858 #ifdef HAVE_X_WINDOWS
1859 /* Respect Xlib's limits: it cannot deal with images that have more
1860 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1861 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1862 enum
1864 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1865 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1868 int bitmap_pad, depth, bytes_per_line;
1869 if (ximg)
1871 bitmap_pad = ximg->bitmap_pad;
1872 depth = ximg->depth;
1873 bytes_per_line = ximg->bytes_per_line;
1875 else
1877 bitmap_pad = 8;
1878 depth = 1;
1879 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1881 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1882 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1883 #else
1884 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1885 For now, assume that every image size is allowed on these systems. */
1886 return 1;
1887 #endif
1890 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1891 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1892 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1893 via xmalloc. Print error messages via image_error if an error
1894 occurs. Value is true if successful.
1896 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1897 should indicate the bit depth of the image. */
1899 static bool
1900 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1901 XImagePtr *ximg, Pixmap *pixmap)
1903 #ifdef HAVE_X_WINDOWS
1904 Display *display = FRAME_X_DISPLAY (f);
1905 Window window = FRAME_X_WINDOW (f);
1906 Screen *screen = FRAME_X_SCREEN (f);
1908 eassert (input_blocked_p ());
1910 if (depth <= 0)
1911 depth = DefaultDepthOfScreen (screen);
1912 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1913 depth, ZPixmap, 0, NULL, width, height,
1914 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1915 if (*ximg == NULL)
1917 image_error ("Unable to allocate X image", Qnil, Qnil);
1918 return 0;
1921 if (! x_check_image_size (*ximg, width, height))
1923 x_destroy_x_image (*ximg);
1924 *ximg = NULL;
1925 image_error ("Image too large (%dx%d)",
1926 make_number (width), make_number (height));
1927 return 0;
1930 /* Allocate image raster. */
1931 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1933 /* Allocate a pixmap of the same size. */
1934 *pixmap = XCreatePixmap (display, window, width, height, depth);
1935 if (*pixmap == NO_PIXMAP)
1937 x_destroy_x_image (*ximg);
1938 *ximg = NULL;
1939 image_error ("Unable to create X pixmap", Qnil, Qnil);
1940 return 0;
1943 return 1;
1944 #endif /* HAVE_X_WINDOWS */
1946 #ifdef HAVE_NTGUI
1948 BITMAPINFOHEADER *header;
1949 HDC hdc;
1950 int scanline_width_bits;
1951 int remainder;
1952 int palette_colors = 0;
1954 if (depth == 0)
1955 depth = 24;
1957 if (depth != 1 && depth != 4 && depth != 8
1958 && depth != 16 && depth != 24 && depth != 32)
1960 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1961 return 0;
1964 scanline_width_bits = width * depth;
1965 remainder = scanline_width_bits % 32;
1967 if (remainder)
1968 scanline_width_bits += 32 - remainder;
1970 /* Bitmaps with a depth less than 16 need a palette. */
1971 /* BITMAPINFO structure already contains the first RGBQUAD. */
1972 if (depth < 16)
1973 palette_colors = 1 << (depth - 1);
1975 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1977 header = &(*ximg)->info.bmiHeader;
1978 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
1979 header->biSize = sizeof (*header);
1980 header->biWidth = width;
1981 header->biHeight = -height; /* negative indicates a top-down bitmap. */
1982 header->biPlanes = 1;
1983 header->biBitCount = depth;
1984 header->biCompression = BI_RGB;
1985 header->biClrUsed = palette_colors;
1987 /* TODO: fill in palette. */
1988 if (depth == 1)
1990 (*ximg)->info.bmiColors[0].rgbBlue = 0;
1991 (*ximg)->info.bmiColors[0].rgbGreen = 0;
1992 (*ximg)->info.bmiColors[0].rgbRed = 0;
1993 (*ximg)->info.bmiColors[0].rgbReserved = 0;
1994 (*ximg)->info.bmiColors[1].rgbBlue = 255;
1995 (*ximg)->info.bmiColors[1].rgbGreen = 255;
1996 (*ximg)->info.bmiColors[1].rgbRed = 255;
1997 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2000 hdc = get_frame_dc (f);
2002 /* Create a DIBSection and raster array for the bitmap,
2003 and store its handle in *pixmap. */
2004 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2005 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2006 /* casting avoids a GCC warning */
2007 (void **)&((*ximg)->data), NULL, 0);
2009 /* Realize display palette and garbage all frames. */
2010 release_frame_dc (f, hdc);
2012 if (*pixmap == NULL)
2014 DWORD err = GetLastError ();
2015 Lisp_Object errcode;
2016 /* All system errors are < 10000, so the following is safe. */
2017 XSETINT (errcode, err);
2018 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2019 x_destroy_x_image (*ximg);
2020 return 0;
2023 return 1;
2025 #endif /* HAVE_NTGUI */
2027 #ifdef HAVE_NS
2028 *pixmap = ns_image_for_XPM (width, height, depth);
2029 if (*pixmap == 0)
2031 *ximg = NULL;
2032 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2033 return 0;
2035 *ximg = *pixmap;
2036 return 1;
2037 #endif
2041 /* Destroy XImage XIMG. Free XIMG->data. */
2043 static void
2044 x_destroy_x_image (XImagePtr ximg)
2046 eassert (input_blocked_p ());
2047 if (ximg)
2049 #ifdef HAVE_X_WINDOWS
2050 xfree (ximg->data);
2051 ximg->data = NULL;
2052 XDestroyImage (ximg);
2053 #endif /* HAVE_X_WINDOWS */
2054 #ifdef HAVE_NTGUI
2055 /* Data will be freed by DestroyObject. */
2056 ximg->data = NULL;
2057 xfree (ximg);
2058 #endif /* HAVE_NTGUI */
2059 #ifdef HAVE_NS
2060 ns_release_object (ximg);
2061 #endif /* HAVE_NS */
2066 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2067 are width and height of both the image and pixmap. */
2069 static void
2070 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2072 #ifdef HAVE_X_WINDOWS
2073 GC gc;
2075 eassert (input_blocked_p ());
2076 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2077 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2078 XFreeGC (FRAME_X_DISPLAY (f), gc);
2079 #endif /* HAVE_X_WINDOWS */
2081 #ifdef HAVE_NTGUI
2082 #if 0 /* I don't think this is necessary looking at where it is used. */
2083 HDC hdc = get_frame_dc (f);
2084 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2085 release_frame_dc (f, hdc);
2086 #endif
2087 #endif /* HAVE_NTGUI */
2089 #ifdef HAVE_NS
2090 eassert (ximg == pixmap);
2091 ns_retain_object (ximg);
2092 #endif
2096 /***********************************************************************
2097 File Handling
2098 ***********************************************************************/
2100 /* Find image file FILE. Look in data-directory/images, then
2101 x-bitmap-file-path. Value is the encoded full name of the file
2102 found, or nil if not found. */
2104 Lisp_Object
2105 x_find_image_file (Lisp_Object file)
2107 Lisp_Object file_found, search_path;
2108 int fd;
2110 /* TODO I think this should use something like image-load-path
2111 instead. Unfortunately, that can contain non-string elements. */
2112 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2113 Vdata_directory),
2114 Vx_bitmap_file_path);
2116 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2117 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2119 if (fd == -1)
2120 file_found = Qnil;
2121 else
2123 file_found = ENCODE_FILE (file_found);
2124 close (fd);
2127 return file_found;
2131 /* Read FILE into memory. Value is a pointer to a buffer allocated
2132 with xmalloc holding FILE's contents. Value is null if an error
2133 occurred. *SIZE is set to the size of the file. */
2135 static unsigned char *
2136 slurp_file (char *file, ptrdiff_t *size)
2138 FILE *fp = fopen (file, "rb");
2139 unsigned char *buf = NULL;
2140 struct stat st;
2142 if (fp && fstat (fileno (fp), &st) == 0
2143 && 0 <= st.st_size && st.st_size <= min (PTRDIFF_MAX, SIZE_MAX)
2144 && (buf = xmalloc (st.st_size),
2145 fread (buf, 1, st.st_size, fp) == st.st_size))
2147 *size = st.st_size;
2148 fclose (fp);
2150 else
2152 if (fp)
2153 fclose (fp);
2154 if (buf)
2156 xfree (buf);
2157 buf = NULL;
2161 return buf;
2166 /***********************************************************************
2167 XBM images
2168 ***********************************************************************/
2170 static bool xbm_load (struct frame *f, struct image *img);
2171 static bool xbm_image_p (Lisp_Object object);
2172 static bool xbm_file_p (Lisp_Object);
2175 /* Indices of image specification fields in xbm_format, below. */
2177 enum xbm_keyword_index
2179 XBM_TYPE,
2180 XBM_FILE,
2181 XBM_WIDTH,
2182 XBM_HEIGHT,
2183 XBM_DATA,
2184 XBM_FOREGROUND,
2185 XBM_BACKGROUND,
2186 XBM_ASCENT,
2187 XBM_MARGIN,
2188 XBM_RELIEF,
2189 XBM_ALGORITHM,
2190 XBM_HEURISTIC_MASK,
2191 XBM_MASK,
2192 XBM_LAST
2195 /* Vector of image_keyword structures describing the format
2196 of valid XBM image specifications. */
2198 static const struct image_keyword xbm_format[XBM_LAST] =
2200 {":type", IMAGE_SYMBOL_VALUE, 1},
2201 {":file", IMAGE_STRING_VALUE, 0},
2202 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2203 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2204 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2205 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2206 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2207 {":ascent", IMAGE_ASCENT_VALUE, 0},
2208 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2209 {":relief", IMAGE_INTEGER_VALUE, 0},
2210 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2211 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2212 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2215 /* Structure describing the image type XBM. */
2217 static struct image_type xbm_type =
2219 &Qxbm,
2220 xbm_image_p,
2221 xbm_load,
2222 x_clear_image,
2223 NULL,
2224 NULL
2227 /* Tokens returned from xbm_scan. */
2229 enum xbm_token
2231 XBM_TK_IDENT = 256,
2232 XBM_TK_NUMBER
2236 /* Return true if OBJECT is a valid XBM-type image specification.
2237 A valid specification is a list starting with the symbol `image'
2238 The rest of the list is a property list which must contain an
2239 entry `:type xbm'.
2241 If the specification specifies a file to load, it must contain
2242 an entry `:file FILENAME' where FILENAME is a string.
2244 If the specification is for a bitmap loaded from memory it must
2245 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2246 WIDTH and HEIGHT are integers > 0. DATA may be:
2248 1. a string large enough to hold the bitmap data, i.e. it must
2249 have a size >= (WIDTH + 7) / 8 * HEIGHT
2251 2. a bool-vector of size >= WIDTH * HEIGHT
2253 3. a vector of strings or bool-vectors, one for each line of the
2254 bitmap.
2256 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2257 may not be specified in this case because they are defined in the
2258 XBM file.
2260 Both the file and data forms may contain the additional entries
2261 `:background COLOR' and `:foreground COLOR'. If not present,
2262 foreground and background of the frame on which the image is
2263 displayed is used. */
2265 static bool
2266 xbm_image_p (Lisp_Object object)
2268 struct image_keyword kw[XBM_LAST];
2270 memcpy (kw, xbm_format, sizeof kw);
2271 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2272 return 0;
2274 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2276 if (kw[XBM_FILE].count)
2278 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2279 return 0;
2281 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2283 /* In-memory XBM file. */
2284 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2285 return 0;
2287 else
2289 Lisp_Object data;
2290 int width, height;
2292 /* Entries for `:width', `:height' and `:data' must be present. */
2293 if (!kw[XBM_WIDTH].count
2294 || !kw[XBM_HEIGHT].count
2295 || !kw[XBM_DATA].count)
2296 return 0;
2298 data = kw[XBM_DATA].value;
2299 width = XFASTINT (kw[XBM_WIDTH].value);
2300 height = XFASTINT (kw[XBM_HEIGHT].value);
2302 /* Check type of data, and width and height against contents of
2303 data. */
2304 if (VECTORP (data))
2306 EMACS_INT i;
2308 /* Number of elements of the vector must be >= height. */
2309 if (ASIZE (data) < height)
2310 return 0;
2312 /* Each string or bool-vector in data must be large enough
2313 for one line of the image. */
2314 for (i = 0; i < height; ++i)
2316 Lisp_Object elt = AREF (data, i);
2318 if (STRINGP (elt))
2320 if (SCHARS (elt)
2321 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2322 return 0;
2324 else if (BOOL_VECTOR_P (elt))
2326 if (XBOOL_VECTOR (elt)->size < width)
2327 return 0;
2329 else
2330 return 0;
2333 else if (STRINGP (data))
2335 if (SCHARS (data)
2336 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2337 return 0;
2339 else if (BOOL_VECTOR_P (data))
2341 if (XBOOL_VECTOR (data)->size / height < width)
2342 return 0;
2344 else
2345 return 0;
2348 return 1;
2352 /* Scan a bitmap file. FP is the stream to read from. Value is
2353 either an enumerator from enum xbm_token, or a character for a
2354 single-character token, or 0 at end of file. If scanning an
2355 identifier, store the lexeme of the identifier in SVAL. If
2356 scanning a number, store its value in *IVAL. */
2358 static int
2359 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2361 unsigned int c;
2363 loop:
2365 /* Skip white space. */
2366 while (*s < end && (c = *(*s)++, c_isspace (c)))
2369 if (*s >= end)
2370 c = 0;
2371 else if (c_isdigit (c))
2373 int value = 0, digit;
2375 if (c == '0' && *s < end)
2377 c = *(*s)++;
2378 if (c == 'x' || c == 'X')
2380 while (*s < end)
2382 c = *(*s)++;
2383 if (c_isdigit (c))
2384 digit = c - '0';
2385 else if (c >= 'a' && c <= 'f')
2386 digit = c - 'a' + 10;
2387 else if (c >= 'A' && c <= 'F')
2388 digit = c - 'A' + 10;
2389 else
2390 break;
2391 value = 16 * value + digit;
2394 else if (c_isdigit (c))
2396 value = c - '0';
2397 while (*s < end
2398 && (c = *(*s)++, c_isdigit (c)))
2399 value = 8 * value + c - '0';
2402 else
2404 value = c - '0';
2405 while (*s < end
2406 && (c = *(*s)++, c_isdigit (c)))
2407 value = 10 * value + c - '0';
2410 if (*s < end)
2411 *s = *s - 1;
2412 *ival = value;
2413 c = XBM_TK_NUMBER;
2415 else if (c_isalpha (c) || c == '_')
2417 *sval++ = c;
2418 while (*s < end
2419 && (c = *(*s)++, (c_isalnum (c) || c == '_')))
2420 *sval++ = c;
2421 *sval = 0;
2422 if (*s < end)
2423 *s = *s - 1;
2424 c = XBM_TK_IDENT;
2426 else if (c == '/' && **s == '*')
2428 /* C-style comment. */
2429 ++*s;
2430 while (**s && (**s != '*' || *(*s + 1) != '/'))
2431 ++*s;
2432 if (**s)
2434 *s += 2;
2435 goto loop;
2439 return c;
2442 #ifdef HAVE_NTGUI
2444 /* Create a Windows bitmap from X bitmap data. */
2445 static HBITMAP
2446 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2448 static unsigned char swap_nibble[16]
2449 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2450 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2451 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2452 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2453 int i, j, w1, w2;
2454 unsigned char *bits, *p;
2455 HBITMAP bmp;
2457 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2458 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2459 bits = alloca (height * w2);
2460 memset (bits, 0, height * w2);
2461 for (i = 0; i < height; i++)
2463 p = bits + i*w2;
2464 for (j = 0; j < w1; j++)
2466 /* Bitswap XBM bytes to match how Windows does things. */
2467 unsigned char c = *data++;
2468 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2469 | (swap_nibble[(c>>4) & 0xf]));
2472 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2474 return bmp;
2477 static void
2478 convert_mono_to_color_image (struct frame *f, struct image *img,
2479 COLORREF foreground, COLORREF background)
2481 HDC hdc, old_img_dc, new_img_dc;
2482 HGDIOBJ old_prev, new_prev;
2483 HBITMAP new_pixmap;
2485 hdc = get_frame_dc (f);
2486 old_img_dc = CreateCompatibleDC (hdc);
2487 new_img_dc = CreateCompatibleDC (hdc);
2488 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2489 release_frame_dc (f, hdc);
2490 old_prev = SelectObject (old_img_dc, img->pixmap);
2491 new_prev = SelectObject (new_img_dc, new_pixmap);
2492 /* Windows convention for mono bitmaps is black = background,
2493 white = foreground. */
2494 SetTextColor (new_img_dc, background);
2495 SetBkColor (new_img_dc, foreground);
2497 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2498 0, 0, SRCCOPY);
2500 SelectObject (old_img_dc, old_prev);
2501 SelectObject (new_img_dc, new_prev);
2502 DeleteDC (old_img_dc);
2503 DeleteDC (new_img_dc);
2504 DeleteObject (img->pixmap);
2505 if (new_pixmap == 0)
2506 fprintf (stderr, "Failed to convert image to color.\n");
2507 else
2508 img->pixmap = new_pixmap;
2511 #define XBM_BIT_SHUFFLE(b) (~(b))
2513 #else
2515 #define XBM_BIT_SHUFFLE(b) (b)
2517 #endif /* HAVE_NTGUI */
2520 static void
2521 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2522 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2523 bool non_default_colors)
2525 #ifdef HAVE_NTGUI
2526 img->pixmap
2527 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2529 /* If colors were specified, transfer the bitmap to a color one. */
2530 if (non_default_colors)
2531 convert_mono_to_color_image (f, img, fg, bg);
2533 #elif defined (HAVE_NS)
2534 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2536 #else
2537 img->pixmap =
2538 (x_check_image_size (0, img->width, img->height)
2539 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2540 FRAME_X_WINDOW (f),
2541 data,
2542 img->width, img->height,
2543 fg, bg,
2544 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2545 : NO_PIXMAP);
2546 #endif /* !HAVE_NTGUI && !HAVE_NS */
2551 /* Replacement for XReadBitmapFileData which isn't available under old
2552 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2553 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2554 the image. Return in *DATA the bitmap data allocated with xmalloc.
2555 Value is true if successful. DATA null means just test if
2556 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR,
2557 inhibit the call to image_error when the image size is invalid (the
2558 bitmap remains unread). */
2560 static bool
2561 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2562 int *width, int *height, char **data,
2563 bool inhibit_image_error)
2565 unsigned char *s = contents;
2566 char buffer[BUFSIZ];
2567 bool padding_p = 0;
2568 bool v10 = 0;
2569 int bytes_per_line, i, nbytes;
2570 char *p;
2571 int value;
2572 int LA1;
2574 #define match() \
2575 LA1 = xbm_scan (&s, end, buffer, &value)
2577 #define expect(TOKEN) \
2578 if (LA1 != (TOKEN)) \
2579 goto failure; \
2580 else \
2581 match ()
2583 #define expect_ident(IDENT) \
2584 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2585 match (); \
2586 else \
2587 goto failure
2589 *width = *height = -1;
2590 if (data)
2591 *data = NULL;
2592 LA1 = xbm_scan (&s, end, buffer, &value);
2594 /* Parse defines for width, height and hot-spots. */
2595 while (LA1 == '#')
2597 match ();
2598 expect_ident ("define");
2599 expect (XBM_TK_IDENT);
2601 if (LA1 == XBM_TK_NUMBER)
2603 char *q = strrchr (buffer, '_');
2604 q = q ? q + 1 : buffer;
2605 if (strcmp (q, "width") == 0)
2606 *width = value;
2607 else if (strcmp (q, "height") == 0)
2608 *height = value;
2610 expect (XBM_TK_NUMBER);
2613 if (!check_image_size (f, *width, *height))
2615 if (!inhibit_image_error)
2616 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2617 goto failure;
2619 else if (data == NULL)
2620 goto success;
2622 /* Parse bits. Must start with `static'. */
2623 expect_ident ("static");
2624 if (LA1 == XBM_TK_IDENT)
2626 if (strcmp (buffer, "unsigned") == 0)
2628 match ();
2629 expect_ident ("char");
2631 else if (strcmp (buffer, "short") == 0)
2633 match ();
2634 v10 = 1;
2635 if (*width % 16 && *width % 16 < 9)
2636 padding_p = 1;
2638 else if (strcmp (buffer, "char") == 0)
2639 match ();
2640 else
2641 goto failure;
2643 else
2644 goto failure;
2646 expect (XBM_TK_IDENT);
2647 expect ('[');
2648 expect (']');
2649 expect ('=');
2650 expect ('{');
2652 if (! x_check_image_size (0, *width, *height))
2654 if (!inhibit_image_error)
2655 image_error ("Image too large (%dx%d)",
2656 make_number (*width), make_number (*height));
2657 goto failure;
2659 bytes_per_line = (*width + 7) / 8 + padding_p;
2660 nbytes = bytes_per_line * *height;
2661 p = *data = xmalloc (nbytes);
2663 if (v10)
2665 for (i = 0; i < nbytes; i += 2)
2667 int val = value;
2668 expect (XBM_TK_NUMBER);
2670 *p++ = XBM_BIT_SHUFFLE (val);
2671 if (!padding_p || ((i + 2) % bytes_per_line))
2672 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2674 if (LA1 == ',' || LA1 == '}')
2675 match ();
2676 else
2677 goto failure;
2680 else
2682 for (i = 0; i < nbytes; ++i)
2684 int val = value;
2685 expect (XBM_TK_NUMBER);
2687 *p++ = XBM_BIT_SHUFFLE (val);
2689 if (LA1 == ',' || LA1 == '}')
2690 match ();
2691 else
2692 goto failure;
2696 success:
2697 return 1;
2699 failure:
2701 if (data && *data)
2703 xfree (*data);
2704 *data = NULL;
2706 return 0;
2708 #undef match
2709 #undef expect
2710 #undef expect_ident
2714 /* Load XBM image IMG which will be displayed on frame F from buffer
2715 CONTENTS. END is the end of the buffer. Value is true if
2716 successful. */
2718 static bool
2719 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2720 unsigned char *end)
2722 bool rc;
2723 char *data;
2724 bool success_p = 0;
2726 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2727 &data, 0);
2728 if (rc)
2730 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2731 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2732 bool non_default_colors = 0;
2733 Lisp_Object value;
2735 eassert (img->width > 0 && img->height > 0);
2737 /* Get foreground and background colors, maybe allocate colors. */
2738 value = image_spec_value (img->spec, QCforeground, NULL);
2739 if (!NILP (value))
2741 foreground = x_alloc_image_color (f, img, value, foreground);
2742 non_default_colors = 1;
2744 value = image_spec_value (img->spec, QCbackground, NULL);
2745 if (!NILP (value))
2747 background = x_alloc_image_color (f, img, value, background);
2748 img->background = background;
2749 img->background_valid = 1;
2750 non_default_colors = 1;
2753 Create_Pixmap_From_Bitmap_Data (f, img, data,
2754 foreground, background,
2755 non_default_colors);
2756 xfree (data);
2758 if (img->pixmap == NO_PIXMAP)
2760 x_clear_image (f, img);
2761 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2763 else
2764 success_p = 1;
2766 else
2767 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2769 return success_p;
2773 /* Value is true if DATA looks like an in-memory XBM file. */
2775 static bool
2776 xbm_file_p (Lisp_Object data)
2778 int w, h;
2779 return (STRINGP (data)
2780 && xbm_read_bitmap_data (NULL, SDATA (data),
2781 (SDATA (data) + SBYTES (data)),
2782 &w, &h, NULL, 1));
2786 /* Fill image IMG which is used on frame F with pixmap data. Value is
2787 true if successful. */
2789 static bool
2790 xbm_load (struct frame *f, struct image *img)
2792 bool success_p = 0;
2793 Lisp_Object file_name;
2795 eassert (xbm_image_p (img->spec));
2797 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2798 file_name = image_spec_value (img->spec, QCfile, NULL);
2799 if (STRINGP (file_name))
2801 Lisp_Object file;
2802 unsigned char *contents;
2803 ptrdiff_t size;
2805 file = x_find_image_file (file_name);
2806 if (!STRINGP (file))
2808 image_error ("Cannot find image file `%s'", file_name, Qnil);
2809 return 0;
2812 contents = slurp_file (SSDATA (file), &size);
2813 if (contents == NULL)
2815 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2816 return 0;
2819 success_p = xbm_load_image (f, img, contents, contents + size);
2820 xfree (contents);
2822 else
2824 struct image_keyword fmt[XBM_LAST];
2825 Lisp_Object data;
2826 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2827 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2828 bool non_default_colors = 0;
2829 char *bits;
2830 bool parsed_p;
2831 bool in_memory_file_p = 0;
2833 /* See if data looks like an in-memory XBM file. */
2834 data = image_spec_value (img->spec, QCdata, NULL);
2835 in_memory_file_p = xbm_file_p (data);
2837 /* Parse the image specification. */
2838 memcpy (fmt, xbm_format, sizeof fmt);
2839 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2840 eassert (parsed_p);
2842 /* Get specified width, and height. */
2843 if (!in_memory_file_p)
2845 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2846 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2847 eassert (img->width > 0 && img->height > 0);
2848 if (!check_image_size (f, img->width, img->height))
2850 image_error ("Invalid image size (see `max-image-size')",
2851 Qnil, Qnil);
2852 return 0;
2856 /* Get foreground and background colors, maybe allocate colors. */
2857 if (fmt[XBM_FOREGROUND].count
2858 && STRINGP (fmt[XBM_FOREGROUND].value))
2860 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2861 foreground);
2862 non_default_colors = 1;
2865 if (fmt[XBM_BACKGROUND].count
2866 && STRINGP (fmt[XBM_BACKGROUND].value))
2868 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2869 background);
2870 non_default_colors = 1;
2873 if (in_memory_file_p)
2874 success_p = xbm_load_image (f, img, SDATA (data),
2875 (SDATA (data)
2876 + SBYTES (data)));
2877 else
2879 if (VECTORP (data))
2881 int i;
2882 char *p;
2883 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2885 p = bits = alloca (nbytes * img->height);
2886 for (i = 0; i < img->height; ++i, p += nbytes)
2888 Lisp_Object line = AREF (data, i);
2889 if (STRINGP (line))
2890 memcpy (p, SDATA (line), nbytes);
2891 else
2892 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
2895 else if (STRINGP (data))
2896 bits = SSDATA (data);
2897 else
2898 bits = (char *) XBOOL_VECTOR (data)->data;
2900 #ifdef HAVE_NTGUI
2902 char *invertedBits;
2903 int nbytes, i;
2904 /* Windows mono bitmaps are reversed compared with X. */
2905 invertedBits = bits;
2906 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
2907 * img->height;
2908 bits = alloca (nbytes);
2909 for (i = 0; i < nbytes; i++)
2910 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
2912 #endif
2913 /* Create the pixmap. */
2915 if (x_check_image_size (0, img->width, img->height))
2916 Create_Pixmap_From_Bitmap_Data (f, img, bits,
2917 foreground, background,
2918 non_default_colors);
2919 else
2920 img->pixmap = NO_PIXMAP;
2922 if (img->pixmap)
2923 success_p = 1;
2924 else
2926 image_error ("Unable to create pixmap for XBM image `%s'",
2927 img->spec, Qnil);
2928 x_clear_image (f, img);
2933 return success_p;
2938 /***********************************************************************
2939 XPM images
2940 ***********************************************************************/
2942 #if defined (HAVE_XPM) || defined (HAVE_NS)
2944 static bool xpm_image_p (Lisp_Object object);
2945 static bool xpm_load (struct frame *f, struct image *img);
2947 #endif /* HAVE_XPM || HAVE_NS */
2949 #ifdef HAVE_XPM
2950 #ifdef HAVE_NTGUI
2951 /* Indicate to xpm.h that we don't have Xlib. */
2952 #define FOR_MSW
2953 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
2954 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
2955 #define XColor xpm_XColor
2956 #define XImage xpm_XImage
2957 #define Display xpm_Display
2958 #define PIXEL_ALREADY_TYPEDEFED
2959 #include "X11/xpm.h"
2960 #undef FOR_MSW
2961 #undef XColor
2962 #undef XImage
2963 #undef Display
2964 #undef PIXEL_ALREADY_TYPEDEFED
2965 #else
2966 #include "X11/xpm.h"
2967 #endif /* HAVE_NTGUI */
2968 #endif /* HAVE_XPM */
2970 #if defined (HAVE_XPM) || defined (HAVE_NS)
2971 /* The symbol `xpm' identifying XPM-format images. */
2973 static Lisp_Object Qxpm;
2975 /* Indices of image specification fields in xpm_format, below. */
2977 enum xpm_keyword_index
2979 XPM_TYPE,
2980 XPM_FILE,
2981 XPM_DATA,
2982 XPM_ASCENT,
2983 XPM_MARGIN,
2984 XPM_RELIEF,
2985 XPM_ALGORITHM,
2986 XPM_HEURISTIC_MASK,
2987 XPM_MASK,
2988 XPM_COLOR_SYMBOLS,
2989 XPM_BACKGROUND,
2990 XPM_LAST
2993 /* Vector of image_keyword structures describing the format
2994 of valid XPM image specifications. */
2996 static const struct image_keyword xpm_format[XPM_LAST] =
2998 {":type", IMAGE_SYMBOL_VALUE, 1},
2999 {":file", IMAGE_STRING_VALUE, 0},
3000 {":data", IMAGE_STRING_VALUE, 0},
3001 {":ascent", IMAGE_ASCENT_VALUE, 0},
3002 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3003 {":relief", IMAGE_INTEGER_VALUE, 0},
3004 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3005 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3006 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3007 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3008 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3011 #if defined HAVE_NTGUI && defined WINDOWSNT
3012 static bool init_xpm_functions (void);
3013 #else
3014 #define init_xpm_functions NULL
3015 #endif
3017 /* Structure describing the image type XPM. */
3019 static struct image_type xpm_type =
3021 &Qxpm,
3022 xpm_image_p,
3023 xpm_load,
3024 x_clear_image,
3025 init_xpm_functions,
3026 NULL
3029 #ifdef HAVE_X_WINDOWS
3031 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3032 functions for allocating image colors. Our own functions handle
3033 color allocation failures more gracefully than the ones on the XPM
3034 lib. */
3036 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3037 #define ALLOC_XPM_COLORS
3038 #endif
3039 #endif /* HAVE_X_WINDOWS */
3041 #ifdef ALLOC_XPM_COLORS
3043 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3044 XColor *, int);
3046 /* An entry in a hash table used to cache color definitions of named
3047 colors. This cache is necessary to speed up XPM image loading in
3048 case we do color allocations ourselves. Without it, we would need
3049 a call to XParseColor per pixel in the image. */
3051 struct xpm_cached_color
3053 /* Next in collision chain. */
3054 struct xpm_cached_color *next;
3056 /* Color definition (RGB and pixel color). */
3057 XColor color;
3059 /* Color name. */
3060 char name[1];
3063 /* The hash table used for the color cache, and its bucket vector
3064 size. */
3066 #define XPM_COLOR_CACHE_BUCKETS 1001
3067 static struct xpm_cached_color **xpm_color_cache;
3069 /* Initialize the color cache. */
3071 static void
3072 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3074 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3075 xpm_color_cache = xzalloc (nbytes);
3076 init_color_table ();
3078 if (attrs->valuemask & XpmColorSymbols)
3080 int i;
3081 XColor color;
3083 for (i = 0; i < attrs->numsymbols; ++i)
3084 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3085 attrs->colorsymbols[i].value, &color))
3087 color.pixel = lookup_rgb_color (f, color.red, color.green,
3088 color.blue);
3089 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3094 /* Free the color cache. */
3096 static void
3097 xpm_free_color_cache (void)
3099 struct xpm_cached_color *p, *next;
3100 int i;
3102 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3103 for (p = xpm_color_cache[i]; p; p = next)
3105 next = p->next;
3106 xfree (p);
3109 xfree (xpm_color_cache);
3110 xpm_color_cache = NULL;
3111 free_color_table ();
3114 /* Return the bucket index for color named COLOR_NAME in the color
3115 cache. */
3117 static int
3118 xpm_color_bucket (char *color_name)
3120 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3121 return hash % XPM_COLOR_CACHE_BUCKETS;
3125 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3126 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3127 entry added. */
3129 static struct xpm_cached_color *
3130 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3132 size_t nbytes;
3133 struct xpm_cached_color *p;
3135 if (bucket < 0)
3136 bucket = xpm_color_bucket (color_name);
3138 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3139 p = xmalloc (nbytes);
3140 strcpy (p->name, color_name);
3141 p->color = *color;
3142 p->next = xpm_color_cache[bucket];
3143 xpm_color_cache[bucket] = p;
3144 return p;
3147 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3148 return the cached definition in *COLOR. Otherwise, make a new
3149 entry in the cache and allocate the color. Value is false if color
3150 allocation failed. */
3152 static bool
3153 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3155 struct xpm_cached_color *p;
3156 int h = xpm_color_bucket (color_name);
3158 for (p = xpm_color_cache[h]; p; p = p->next)
3159 if (strcmp (p->name, color_name) == 0)
3160 break;
3162 if (p != NULL)
3163 *color = p->color;
3164 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3165 color_name, color))
3167 color->pixel = lookup_rgb_color (f, color->red, color->green,
3168 color->blue);
3169 p = xpm_cache_color (f, color_name, color, h);
3171 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3172 with transparency, and it's useful. */
3173 else if (strcmp ("opaque", color_name) == 0)
3175 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3176 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3177 p = xpm_cache_color (f, color_name, color, h);
3180 return p != NULL;
3184 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3185 CLOSURE is a pointer to the frame on which we allocate the
3186 color. Return in *COLOR the allocated color. Value is non-zero
3187 if successful. */
3189 static int
3190 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3191 void *closure)
3193 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3197 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3198 is a pointer to the frame on which we allocate the color. Value is
3199 non-zero if successful. */
3201 static int
3202 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3204 return 1;
3207 #endif /* ALLOC_XPM_COLORS */
3210 #ifdef WINDOWSNT
3212 /* XPM library details. */
3214 DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
3215 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3216 xpm_XImage **, XpmAttributes *));
3217 DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3218 xpm_XImage **, XpmAttributes *));
3219 DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
3221 static bool
3222 init_xpm_functions (void)
3224 HMODULE library;
3226 if (!(library = w32_delayed_load (Qxpm)))
3227 return 0;
3229 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3230 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3231 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3232 LOAD_IMGLIB_FN (library, XImageFree);
3233 return 1;
3236 #endif /* WINDOWSNT */
3238 #if defined HAVE_NTGUI && !defined WINDOWSNT
3239 /* Glue for code below */
3240 #define fn_XpmReadFileToImage XpmReadFileToImage
3241 #define fn_XpmCreateImageFromBuffer XpmCreateImageFromBuffer
3242 #define fn_XImageFree XImageFree
3243 #define fn_XpmFreeAttributes XpmFreeAttributes
3244 #endif /* HAVE_NTGUI && !WINDOWSNT */
3246 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
3247 for XPM images. Such a list must consist of conses whose car and
3248 cdr are strings. */
3250 static bool
3251 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3253 while (CONSP (color_symbols))
3255 Lisp_Object sym = XCAR (color_symbols);
3256 if (!CONSP (sym)
3257 || !STRINGP (XCAR (sym))
3258 || !STRINGP (XCDR (sym)))
3259 break;
3260 color_symbols = XCDR (color_symbols);
3263 return NILP (color_symbols);
3267 /* Value is true if OBJECT is a valid XPM image specification. */
3269 static bool
3270 xpm_image_p (Lisp_Object object)
3272 struct image_keyword fmt[XPM_LAST];
3273 memcpy (fmt, xpm_format, sizeof fmt);
3274 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3275 /* Either `:file' or `:data' must be present. */
3276 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3277 /* Either no `:color-symbols' or it's a list of conses
3278 whose car and cdr are strings. */
3279 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3280 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3283 #endif /* HAVE_XPM || HAVE_NS */
3285 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3286 ptrdiff_t
3287 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3289 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3290 ptrdiff_t id;
3291 int rc;
3292 XpmAttributes attrs;
3293 Pixmap bitmap, mask;
3295 memset (&attrs, 0, sizeof attrs);
3297 attrs.visual = FRAME_X_VISUAL (f);
3298 attrs.colormap = FRAME_X_COLORMAP (f);
3299 attrs.valuemask |= XpmVisual;
3300 attrs.valuemask |= XpmColormap;
3302 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3303 (char **) bits, &bitmap, &mask, &attrs);
3304 if (rc != XpmSuccess)
3306 XpmFreeAttributes (&attrs);
3307 return -1;
3310 id = x_allocate_bitmap_record (f);
3311 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3312 dpyinfo->bitmaps[id - 1].have_mask = 1;
3313 dpyinfo->bitmaps[id - 1].mask = mask;
3314 dpyinfo->bitmaps[id - 1].file = NULL;
3315 dpyinfo->bitmaps[id - 1].height = attrs.height;
3316 dpyinfo->bitmaps[id - 1].width = attrs.width;
3317 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3318 dpyinfo->bitmaps[id - 1].refcount = 1;
3320 XpmFreeAttributes (&attrs);
3321 return id;
3323 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3325 /* Load image IMG which will be displayed on frame F. Value is
3326 true if successful. */
3328 #ifdef HAVE_XPM
3330 static bool
3331 xpm_load (struct frame *f, struct image *img)
3333 int rc;
3334 XpmAttributes attrs;
3335 Lisp_Object specified_file, color_symbols;
3336 #ifdef HAVE_NTGUI
3337 HDC hdc;
3338 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3339 #endif /* HAVE_NTGUI */
3341 /* Configure the XPM lib. Use the visual of frame F. Allocate
3342 close colors. Return colors allocated. */
3343 memset (&attrs, 0, sizeof attrs);
3345 #ifndef HAVE_NTGUI
3346 attrs.visual = FRAME_X_VISUAL (f);
3347 attrs.colormap = FRAME_X_COLORMAP (f);
3348 attrs.valuemask |= XpmVisual;
3349 attrs.valuemask |= XpmColormap;
3350 #endif /* HAVE_NTGUI */
3352 #ifdef ALLOC_XPM_COLORS
3353 /* Allocate colors with our own functions which handle
3354 failing color allocation more gracefully. */
3355 attrs.color_closure = f;
3356 attrs.alloc_color = xpm_alloc_color;
3357 attrs.free_colors = xpm_free_colors;
3358 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3359 #else /* not ALLOC_XPM_COLORS */
3360 /* Let the XPM lib allocate colors. */
3361 attrs.valuemask |= XpmReturnAllocPixels;
3362 #ifdef XpmAllocCloseColors
3363 attrs.alloc_close_colors = 1;
3364 attrs.valuemask |= XpmAllocCloseColors;
3365 #else /* not XpmAllocCloseColors */
3366 attrs.closeness = 600;
3367 attrs.valuemask |= XpmCloseness;
3368 #endif /* not XpmAllocCloseColors */
3369 #endif /* ALLOC_XPM_COLORS */
3371 /* If image specification contains symbolic color definitions, add
3372 these to `attrs'. */
3373 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3374 if (CONSP (color_symbols))
3376 Lisp_Object tail;
3377 XpmColorSymbol *xpm_syms;
3378 int i, size;
3380 attrs.valuemask |= XpmColorSymbols;
3382 /* Count number of symbols. */
3383 attrs.numsymbols = 0;
3384 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3385 ++attrs.numsymbols;
3387 /* Allocate an XpmColorSymbol array. */
3388 size = attrs.numsymbols * sizeof *xpm_syms;
3389 xpm_syms = alloca (size);
3390 memset (xpm_syms, 0, size);
3391 attrs.colorsymbols = xpm_syms;
3393 /* Fill the color symbol array. */
3394 for (tail = color_symbols, i = 0;
3395 CONSP (tail);
3396 ++i, tail = XCDR (tail))
3398 Lisp_Object name;
3399 Lisp_Object color;
3400 char *empty_string = (char *) "";
3402 if (!CONSP (XCAR (tail)))
3404 xpm_syms[i].name = empty_string;
3405 xpm_syms[i].value = empty_string;
3406 continue;
3408 name = XCAR (XCAR (tail));
3409 color = XCDR (XCAR (tail));
3410 if (STRINGP (name))
3412 xpm_syms[i].name = alloca (SCHARS (name) + 1);
3413 strcpy (xpm_syms[i].name, SSDATA (name));
3415 else
3416 xpm_syms[i].name = empty_string;
3417 if (STRINGP (color))
3419 xpm_syms[i].value = alloca (SCHARS (color) + 1);
3420 strcpy (xpm_syms[i].value, SSDATA (color));
3422 else
3423 xpm_syms[i].value = empty_string;
3427 /* Create a pixmap for the image, either from a file, or from a
3428 string buffer containing data in the same format as an XPM file. */
3429 #ifdef ALLOC_XPM_COLORS
3430 xpm_init_color_cache (f, &attrs);
3431 #endif
3433 specified_file = image_spec_value (img->spec, QCfile, NULL);
3435 #ifdef HAVE_NTGUI
3437 HDC frame_dc = get_frame_dc (f);
3438 hdc = CreateCompatibleDC (frame_dc);
3439 release_frame_dc (f, frame_dc);
3441 #endif /* HAVE_NTGUI */
3443 if (STRINGP (specified_file))
3445 Lisp_Object file = x_find_image_file (specified_file);
3446 if (!STRINGP (file))
3448 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3449 #ifdef ALLOC_XPM_COLORS
3450 xpm_free_color_cache ();
3451 #endif
3452 return 0;
3455 #ifdef HAVE_NTGUI
3456 /* XpmReadFileToPixmap is not available in the Windows port of
3457 libxpm. But XpmReadFileToImage almost does what we want. */
3458 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3459 &xpm_image, &xpm_mask,
3460 &attrs);
3461 #else
3462 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3463 SSDATA (file), &img->pixmap, &img->mask,
3464 &attrs);
3465 #endif /* HAVE_NTGUI */
3467 else
3469 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3470 if (!STRINGP (buffer))
3472 image_error ("Invalid image data `%s'", buffer, Qnil);
3473 #ifdef ALLOC_XPM_COLORS
3474 xpm_free_color_cache ();
3475 #endif
3476 return 0;
3478 #ifdef HAVE_NTGUI
3479 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3480 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3481 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3482 &xpm_image, &xpm_mask,
3483 &attrs);
3484 #else
3485 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3486 SSDATA (buffer),
3487 &img->pixmap, &img->mask,
3488 &attrs);
3489 #endif /* HAVE_NTGUI */
3492 if (rc == XpmSuccess)
3494 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3495 img->colors = colors_in_color_table (&img->ncolors);
3496 #else /* not ALLOC_XPM_COLORS */
3497 int i;
3499 #ifdef HAVE_NTGUI
3500 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3501 plus some duplicate attributes. */
3502 if (xpm_image && xpm_image->bitmap)
3504 img->pixmap = xpm_image->bitmap;
3505 /* XImageFree in libXpm frees XImage struct without destroying
3506 the bitmap, which is what we want. */
3507 fn_XImageFree (xpm_image);
3509 if (xpm_mask && xpm_mask->bitmap)
3511 /* The mask appears to be inverted compared with what we expect.
3512 TODO: invert our expectations. See other places where we
3513 have to invert bits because our idea of masks is backwards. */
3514 HGDIOBJ old_obj;
3515 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3517 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3518 SelectObject (hdc, old_obj);
3520 img->mask = xpm_mask->bitmap;
3521 fn_XImageFree (xpm_mask);
3522 DeleteDC (hdc);
3525 DeleteDC (hdc);
3526 #endif /* HAVE_NTGUI */
3528 /* Remember allocated colors. */
3529 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3530 img->ncolors = attrs.nalloc_pixels;
3531 for (i = 0; i < attrs.nalloc_pixels; ++i)
3533 img->colors[i] = attrs.alloc_pixels[i];
3534 #ifdef DEBUG_X_COLORS
3535 register_color (img->colors[i]);
3536 #endif
3538 #endif /* not ALLOC_XPM_COLORS */
3540 img->width = attrs.width;
3541 img->height = attrs.height;
3542 eassert (img->width > 0 && img->height > 0);
3544 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3545 #ifdef HAVE_NTGUI
3546 fn_XpmFreeAttributes (&attrs);
3547 #else
3548 XpmFreeAttributes (&attrs);
3549 #endif /* HAVE_NTGUI */
3551 else
3553 #ifdef HAVE_NTGUI
3554 DeleteDC (hdc);
3555 #endif /* HAVE_NTGUI */
3557 switch (rc)
3559 case XpmOpenFailed:
3560 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3561 break;
3563 case XpmFileInvalid:
3564 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3565 break;
3567 case XpmNoMemory:
3568 image_error ("Out of memory (%s)", img->spec, Qnil);
3569 break;
3571 case XpmColorFailed:
3572 image_error ("Color allocation error (%s)", img->spec, Qnil);
3573 break;
3575 default:
3576 image_error ("Unknown error (%s)", img->spec, Qnil);
3577 break;
3581 #ifdef ALLOC_XPM_COLORS
3582 xpm_free_color_cache ();
3583 #endif
3584 return rc == XpmSuccess;
3587 #endif /* HAVE_XPM */
3589 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3591 /* XPM support functions for NS where libxpm is not available.
3592 Only XPM version 3 (without any extensions) is supported. */
3594 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3595 int, Lisp_Object);
3596 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3597 const unsigned char *, int);
3598 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3599 int, Lisp_Object);
3600 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3601 const unsigned char *, int);
3603 /* Tokens returned from xpm_scan. */
3605 enum xpm_token
3607 XPM_TK_IDENT = 256,
3608 XPM_TK_STRING,
3609 XPM_TK_EOF
3612 /* Scan an XPM data and return a character (< 256) or a token defined
3613 by enum xpm_token above. *S and END are the start (inclusive) and
3614 the end (exclusive) addresses of the data, respectively. Advance
3615 *S while scanning. If token is either XPM_TK_IDENT or
3616 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3617 length of the corresponding token, respectively. */
3619 static int
3620 xpm_scan (const unsigned char **s,
3621 const unsigned char *end,
3622 const unsigned char **beg,
3623 ptrdiff_t *len)
3625 int c;
3627 while (*s < end)
3629 /* Skip white-space. */
3630 while (*s < end && (c = *(*s)++, c_isspace (c)))
3633 /* gnus-pointer.xpm uses '-' in its identifier.
3634 sb-dir-plus.xpm uses '+' in its identifier. */
3635 if (c_isalpha (c) || c == '_' || c == '-' || c == '+')
3637 *beg = *s - 1;
3638 while (*s < end
3639 && (c = **s, c_isalnum (c)
3640 || c == '_' || c == '-' || c == '+'))
3641 ++*s;
3642 *len = *s - *beg;
3643 return XPM_TK_IDENT;
3645 else if (c == '"')
3647 *beg = *s;
3648 while (*s < end && **s != '"')
3649 ++*s;
3650 *len = *s - *beg;
3651 if (*s < end)
3652 ++*s;
3653 return XPM_TK_STRING;
3655 else if (c == '/')
3657 if (*s < end && **s == '*')
3659 /* C-style comment. */
3660 ++*s;
3663 while (*s < end && *(*s)++ != '*')
3666 while (*s < end && **s != '/');
3667 if (*s < end)
3668 ++*s;
3670 else
3671 return c;
3673 else
3674 return c;
3677 return XPM_TK_EOF;
3680 /* Functions for color table lookup in XPM data. A key is a string
3681 specifying the color of each pixel in XPM data. A value is either
3682 an integer that specifies a pixel color, Qt that specifies
3683 transparency, or Qnil for the unspecified color. If the length of
3684 the key string is one, a vector is used as a table. Otherwise, a
3685 hash table is used. */
3687 static Lisp_Object
3688 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3689 const unsigned char *,
3690 int,
3691 Lisp_Object),
3692 Lisp_Object (**get_func) (Lisp_Object,
3693 const unsigned char *,
3694 int))
3696 *put_func = xpm_put_color_table_v;
3697 *get_func = xpm_get_color_table_v;
3698 return Fmake_vector (make_number (256), Qnil);
3701 static void
3702 xpm_put_color_table_v (Lisp_Object color_table,
3703 const unsigned char *chars_start,
3704 int chars_len,
3705 Lisp_Object color)
3707 ASET (color_table, *chars_start, color);
3710 static Lisp_Object
3711 xpm_get_color_table_v (Lisp_Object color_table,
3712 const unsigned char *chars_start,
3713 int chars_len)
3715 return AREF (color_table, *chars_start);
3718 static Lisp_Object
3719 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3720 const unsigned char *,
3721 int,
3722 Lisp_Object),
3723 Lisp_Object (**get_func) (Lisp_Object,
3724 const unsigned char *,
3725 int))
3727 *put_func = xpm_put_color_table_h;
3728 *get_func = xpm_get_color_table_h;
3729 return make_hash_table (hashtest_equal, make_number (DEFAULT_HASH_SIZE),
3730 make_float (DEFAULT_REHASH_SIZE),
3731 make_float (DEFAULT_REHASH_THRESHOLD),
3732 Qnil);
3735 static void
3736 xpm_put_color_table_h (Lisp_Object color_table,
3737 const unsigned char *chars_start,
3738 int chars_len,
3739 Lisp_Object color)
3741 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3742 EMACS_UINT hash_code;
3743 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3745 hash_lookup (table, chars, &hash_code);
3746 hash_put (table, chars, color, hash_code);
3749 static Lisp_Object
3750 xpm_get_color_table_h (Lisp_Object color_table,
3751 const unsigned char *chars_start,
3752 int chars_len)
3754 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3755 ptrdiff_t i =
3756 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
3758 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3761 enum xpm_color_key {
3762 XPM_COLOR_KEY_S,
3763 XPM_COLOR_KEY_M,
3764 XPM_COLOR_KEY_G4,
3765 XPM_COLOR_KEY_G,
3766 XPM_COLOR_KEY_C
3769 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3771 static int
3772 xpm_str_to_color_key (const char *s)
3774 int i;
3776 for (i = 0;
3777 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3778 i++)
3779 if (strcmp (xpm_color_key_strings[i], s) == 0)
3780 return i;
3781 return -1;
3784 static bool
3785 xpm_load_image (struct frame *f,
3786 struct image *img,
3787 const unsigned char *contents,
3788 const unsigned char *end)
3790 const unsigned char *s = contents, *beg, *str;
3791 unsigned char buffer[BUFSIZ];
3792 int width, height, x, y;
3793 int num_colors, chars_per_pixel;
3794 ptrdiff_t len;
3795 int LA1;
3796 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3797 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3798 Lisp_Object frame, color_symbols, color_table;
3799 int best_key;
3800 bool have_mask = 0;
3801 XImagePtr ximg = NULL, mask_img = NULL;
3803 #define match() \
3804 LA1 = xpm_scan (&s, end, &beg, &len)
3806 #define expect(TOKEN) \
3807 if (LA1 != (TOKEN)) \
3808 goto failure; \
3809 else \
3810 match ()
3812 #define expect_ident(IDENT) \
3813 if (LA1 == XPM_TK_IDENT \
3814 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3815 match (); \
3816 else \
3817 goto failure
3819 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3820 goto failure;
3821 s += 9;
3822 match ();
3823 expect_ident ("static");
3824 expect_ident ("char");
3825 expect ('*');
3826 expect (XPM_TK_IDENT);
3827 expect ('[');
3828 expect (']');
3829 expect ('=');
3830 expect ('{');
3831 expect (XPM_TK_STRING);
3832 if (len >= BUFSIZ)
3833 goto failure;
3834 memcpy (buffer, beg, len);
3835 buffer[len] = '\0';
3836 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3837 &num_colors, &chars_per_pixel) != 4
3838 || width <= 0 || height <= 0
3839 || num_colors <= 0 || chars_per_pixel <= 0)
3840 goto failure;
3842 if (!check_image_size (f, width, height))
3844 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
3845 goto failure;
3848 if (!x_create_x_image_and_pixmap (f, width, height, 0,
3849 &ximg, &img->pixmap)
3850 #ifndef HAVE_NS
3851 || !x_create_x_image_and_pixmap (f, width, height, 1,
3852 &mask_img, &img->mask)
3853 #endif
3856 image_error ("Image too large", Qnil, Qnil);
3857 goto failure;
3860 expect (',');
3862 XSETFRAME (frame, f);
3863 if (!NILP (Fxw_display_color_p (frame)))
3864 best_key = XPM_COLOR_KEY_C;
3865 else if (!NILP (Fx_display_grayscale_p (frame)))
3866 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
3867 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
3868 else
3869 best_key = XPM_COLOR_KEY_M;
3871 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3872 if (chars_per_pixel == 1)
3873 color_table = xpm_make_color_table_v (&put_color_table,
3874 &get_color_table);
3875 else
3876 color_table = xpm_make_color_table_h (&put_color_table,
3877 &get_color_table);
3879 while (num_colors-- > 0)
3881 char *color, *max_color;
3882 int key, next_key, max_key = 0;
3883 Lisp_Object symbol_color = Qnil, color_val;
3884 XColor cdef;
3886 expect (XPM_TK_STRING);
3887 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
3888 goto failure;
3889 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
3890 buffer[len - chars_per_pixel] = '\0';
3892 str = strtok (buffer, " \t");
3893 if (str == NULL)
3894 goto failure;
3895 key = xpm_str_to_color_key (str);
3896 if (key < 0)
3897 goto failure;
3900 color = strtok (NULL, " \t");
3901 if (color == NULL)
3902 goto failure;
3904 while ((str = strtok (NULL, " \t")) != NULL)
3906 next_key = xpm_str_to_color_key (str);
3907 if (next_key >= 0)
3908 break;
3909 color[strlen (color)] = ' ';
3912 if (key == XPM_COLOR_KEY_S)
3914 if (NILP (symbol_color))
3915 symbol_color = build_string (color);
3917 else if (max_key < key && key <= best_key)
3919 max_key = key;
3920 max_color = color;
3922 key = next_key;
3924 while (str);
3926 color_val = Qnil;
3927 if (!NILP (color_symbols) && !NILP (symbol_color))
3929 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
3931 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
3933 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
3934 color_val = Qt;
3935 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
3936 &cdef, 0))
3937 color_val = make_number (cdef.pixel);
3940 if (NILP (color_val) && max_key > 0)
3942 if (xstrcasecmp (max_color, "None") == 0)
3943 color_val = Qt;
3944 else if (x_defined_color (f, max_color, &cdef, 0))
3945 color_val = make_number (cdef.pixel);
3947 if (!NILP (color_val))
3948 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
3950 expect (',');
3953 for (y = 0; y < height; y++)
3955 expect (XPM_TK_STRING);
3956 str = beg;
3957 if (len < width * chars_per_pixel)
3958 goto failure;
3959 for (x = 0; x < width; x++, str += chars_per_pixel)
3961 Lisp_Object color_val =
3962 (*get_color_table) (color_table, str, chars_per_pixel);
3964 XPutPixel (ximg, x, y,
3965 (INTEGERP (color_val) ? XINT (color_val)
3966 : FRAME_FOREGROUND_PIXEL (f)));
3967 #ifndef HAVE_NS
3968 XPutPixel (mask_img, x, y,
3969 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
3970 : (have_mask = 1, PIX_MASK_RETAIN)));
3971 #else
3972 if (EQ (color_val, Qt))
3973 ns_set_alpha (ximg, x, y, 0);
3974 #endif
3976 if (y + 1 < height)
3977 expect (',');
3980 img->width = width;
3981 img->height = height;
3983 /* Maybe fill in the background field while we have ximg handy. */
3984 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
3985 IMAGE_BACKGROUND (img, f, ximg);
3987 x_put_x_image (f, ximg, img->pixmap, width, height);
3988 x_destroy_x_image (ximg);
3989 #ifndef HAVE_NS
3990 if (have_mask)
3992 /* Fill in the background_transparent field while we have the
3993 mask handy. */
3994 image_background_transparent (img, f, mask_img);
3996 x_put_x_image (f, mask_img, img->mask, width, height);
3997 x_destroy_x_image (mask_img);
3999 else
4001 x_destroy_x_image (mask_img);
4002 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4003 img->mask = NO_PIXMAP;
4005 #endif
4006 return 1;
4008 failure:
4009 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4010 x_destroy_x_image (ximg);
4011 x_destroy_x_image (mask_img);
4012 x_clear_image (f, img);
4013 return 0;
4015 #undef match
4016 #undef expect
4017 #undef expect_ident
4020 static bool
4021 xpm_load (struct frame *f,
4022 struct image *img)
4024 bool success_p = 0;
4025 Lisp_Object file_name;
4027 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4028 file_name = image_spec_value (img->spec, QCfile, NULL);
4029 if (STRINGP (file_name))
4031 Lisp_Object file;
4032 unsigned char *contents;
4033 ptrdiff_t size;
4035 file = x_find_image_file (file_name);
4036 if (!STRINGP (file))
4038 image_error ("Cannot find image file `%s'", file_name, Qnil);
4039 return 0;
4042 contents = slurp_file (SSDATA (file), &size);
4043 if (contents == NULL)
4045 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4046 return 0;
4049 success_p = xpm_load_image (f, img, contents, contents + size);
4050 xfree (contents);
4052 else
4054 Lisp_Object data;
4056 data = image_spec_value (img->spec, QCdata, NULL);
4057 if (!STRINGP (data))
4059 image_error ("Invalid image data `%s'", data, Qnil);
4060 return 0;
4062 success_p = xpm_load_image (f, img, SDATA (data),
4063 SDATA (data) + SBYTES (data));
4066 return success_p;
4069 #endif /* HAVE_NS && !HAVE_XPM */
4073 /***********************************************************************
4074 Color table
4075 ***********************************************************************/
4077 #ifdef COLOR_TABLE_SUPPORT
4079 /* An entry in the color table mapping an RGB color to a pixel color. */
4081 struct ct_color
4083 int r, g, b;
4084 unsigned long pixel;
4086 /* Next in color table collision list. */
4087 struct ct_color *next;
4090 /* The bucket vector size to use. Must be prime. */
4092 #define CT_SIZE 101
4094 /* Value is a hash of the RGB color given by R, G, and B. */
4096 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4098 /* The color hash table. */
4100 static struct ct_color **ct_table;
4102 /* Number of entries in the color table. */
4104 static int ct_colors_allocated;
4105 enum
4107 ct_colors_allocated_max =
4108 min (INT_MAX,
4109 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4112 /* Initialize the color table. */
4114 static void
4115 init_color_table (void)
4117 int size = CT_SIZE * sizeof (*ct_table);
4118 ct_table = xzalloc (size);
4119 ct_colors_allocated = 0;
4123 /* Free memory associated with the color table. */
4125 static void
4126 free_color_table (void)
4128 int i;
4129 struct ct_color *p, *next;
4131 for (i = 0; i < CT_SIZE; ++i)
4132 for (p = ct_table[i]; p; p = next)
4134 next = p->next;
4135 xfree (p);
4138 xfree (ct_table);
4139 ct_table = NULL;
4143 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4144 entry for that color already is in the color table, return the
4145 pixel color of that entry. Otherwise, allocate a new color for R,
4146 G, B, and make an entry in the color table. */
4148 static unsigned long
4149 lookup_rgb_color (struct frame *f, int r, int g, int b)
4151 unsigned hash = CT_HASH_RGB (r, g, b);
4152 int i = hash % CT_SIZE;
4153 struct ct_color *p;
4154 Display_Info *dpyinfo;
4156 /* Handle TrueColor visuals specially, which improves performance by
4157 two orders of magnitude. Freeing colors on TrueColor visuals is
4158 a nop, and pixel colors specify RGB values directly. See also
4159 the Xlib spec, chapter 3.1. */
4160 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4161 if (dpyinfo->red_bits > 0)
4163 unsigned long pr, pg, pb;
4165 /* Apply gamma-correction like normal color allocation does. */
4166 if (f->gamma)
4168 XColor color;
4169 color.red = r, color.green = g, color.blue = b;
4170 gamma_correct (f, &color);
4171 r = color.red, g = color.green, b = color.blue;
4174 /* Scale down RGB values to the visual's bits per RGB, and shift
4175 them to the right position in the pixel color. Note that the
4176 original RGB values are 16-bit values, as usual in X. */
4177 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4178 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4179 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4181 /* Assemble the pixel color. */
4182 return pr | pg | pb;
4185 for (p = ct_table[i]; p; p = p->next)
4186 if (p->r == r && p->g == g && p->b == b)
4187 break;
4189 if (p == NULL)
4192 #ifdef HAVE_X_WINDOWS
4193 XColor color;
4194 Colormap cmap;
4195 bool rc;
4196 #else
4197 COLORREF color;
4198 #endif
4200 if (ct_colors_allocated_max <= ct_colors_allocated)
4201 return FRAME_FOREGROUND_PIXEL (f);
4203 #ifdef HAVE_X_WINDOWS
4204 color.red = r;
4205 color.green = g;
4206 color.blue = b;
4208 cmap = FRAME_X_COLORMAP (f);
4209 rc = x_alloc_nearest_color (f, cmap, &color);
4210 if (rc)
4212 ++ct_colors_allocated;
4213 p = xmalloc (sizeof *p);
4214 p->r = r;
4215 p->g = g;
4216 p->b = b;
4217 p->pixel = color.pixel;
4218 p->next = ct_table[i];
4219 ct_table[i] = p;
4221 else
4222 return FRAME_FOREGROUND_PIXEL (f);
4224 #else
4225 #ifdef HAVE_NTGUI
4226 color = PALETTERGB (r, g, b);
4227 #else
4228 color = RGB_TO_ULONG (r, g, b);
4229 #endif /* HAVE_NTGUI */
4230 ++ct_colors_allocated;
4231 p = xmalloc (sizeof *p);
4232 p->r = r;
4233 p->g = g;
4234 p->b = b;
4235 p->pixel = color;
4236 p->next = ct_table[i];
4237 ct_table[i] = p;
4238 #endif /* HAVE_X_WINDOWS */
4242 return p->pixel;
4246 /* Look up pixel color PIXEL which is used on frame F in the color
4247 table. If not already present, allocate it. Value is PIXEL. */
4249 static unsigned long
4250 lookup_pixel_color (struct frame *f, unsigned long pixel)
4252 int i = pixel % CT_SIZE;
4253 struct ct_color *p;
4255 for (p = ct_table[i]; p; p = p->next)
4256 if (p->pixel == pixel)
4257 break;
4259 if (p == NULL)
4261 XColor color;
4262 Colormap cmap;
4263 bool rc;
4265 if (ct_colors_allocated_max <= ct_colors_allocated)
4266 return FRAME_FOREGROUND_PIXEL (f);
4268 #ifdef HAVE_X_WINDOWS
4269 cmap = FRAME_X_COLORMAP (f);
4270 color.pixel = pixel;
4271 x_query_color (f, &color);
4272 rc = x_alloc_nearest_color (f, cmap, &color);
4273 #else
4274 block_input ();
4275 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4276 color.pixel = pixel;
4277 XQueryColor (NULL, cmap, &color);
4278 rc = x_alloc_nearest_color (f, cmap, &color);
4279 unblock_input ();
4280 #endif /* HAVE_X_WINDOWS */
4282 if (rc)
4284 ++ct_colors_allocated;
4286 p = xmalloc (sizeof *p);
4287 p->r = color.red;
4288 p->g = color.green;
4289 p->b = color.blue;
4290 p->pixel = pixel;
4291 p->next = ct_table[i];
4292 ct_table[i] = p;
4294 else
4295 return FRAME_FOREGROUND_PIXEL (f);
4297 return p->pixel;
4301 /* Value is a vector of all pixel colors contained in the color table,
4302 allocated via xmalloc. Set *N to the number of colors. */
4304 static unsigned long *
4305 colors_in_color_table (int *n)
4307 int i, j;
4308 struct ct_color *p;
4309 unsigned long *colors;
4311 if (ct_colors_allocated == 0)
4313 *n = 0;
4314 colors = NULL;
4316 else
4318 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4319 *n = ct_colors_allocated;
4321 for (i = j = 0; i < CT_SIZE; ++i)
4322 for (p = ct_table[i]; p; p = p->next)
4323 colors[j++] = p->pixel;
4326 return colors;
4329 #else /* COLOR_TABLE_SUPPORT */
4331 static unsigned long
4332 lookup_rgb_color (struct frame *f, int r, int g, int b)
4334 unsigned long pixel;
4336 #ifdef HAVE_NTGUI
4337 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4338 #endif /* HAVE_NTGUI */
4340 #ifdef HAVE_NS
4341 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4342 #endif /* HAVE_NS */
4343 return pixel;
4346 static void
4347 init_color_table (void)
4350 #endif /* COLOR_TABLE_SUPPORT */
4353 /***********************************************************************
4354 Algorithms
4355 ***********************************************************************/
4357 /* Edge detection matrices for different edge-detection
4358 strategies. */
4360 static int emboss_matrix[9] = {
4361 /* x - 1 x x + 1 */
4362 2, -1, 0, /* y - 1 */
4363 -1, 0, 1, /* y */
4364 0, 1, -2 /* y + 1 */
4367 static int laplace_matrix[9] = {
4368 /* x - 1 x x + 1 */
4369 1, 0, 0, /* y - 1 */
4370 0, 0, 0, /* y */
4371 0, 0, -1 /* y + 1 */
4374 /* Value is the intensity of the color whose red/green/blue values
4375 are R, G, and B. */
4377 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4380 /* On frame F, return an array of XColor structures describing image
4381 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4382 means also fill the red/green/blue members of the XColor
4383 structures. Value is a pointer to the array of XColors structures,
4384 allocated with xmalloc; it must be freed by the caller. */
4386 static XColor *
4387 x_to_xcolors (struct frame *f, struct image *img, bool rgb_p)
4389 int x, y;
4390 XColor *colors, *p;
4391 XImagePtr_or_DC ximg;
4392 #ifdef HAVE_NTGUI
4393 HDC hdc;
4394 HGDIOBJ prev;
4395 #endif /* HAVE_NTGUI */
4397 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width < img->height)
4398 memory_full (SIZE_MAX);
4399 colors = xmalloc (sizeof *colors * img->width * img->height);
4401 #ifndef HAVE_NTGUI
4402 /* Get the X image IMG->pixmap. */
4403 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4404 0, 0, img->width, img->height, ~0, ZPixmap);
4405 #else
4406 /* Load the image into a memory device context. */
4407 hdc = get_frame_dc (f);
4408 ximg = CreateCompatibleDC (hdc);
4409 release_frame_dc (f, hdc);
4410 prev = SelectObject (ximg, img->pixmap);
4411 #endif /* HAVE_NTGUI */
4413 /* Fill the `pixel' members of the XColor array. I wished there
4414 were an easy and portable way to circumvent XGetPixel. */
4415 p = colors;
4416 for (y = 0; y < img->height; ++y)
4418 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4419 XColor *row = p;
4420 for (x = 0; x < img->width; ++x, ++p)
4421 p->pixel = GET_PIXEL (ximg, x, y);
4422 if (rgb_p)
4423 x_query_colors (f, row, img->width);
4425 #else
4427 for (x = 0; x < img->width; ++x, ++p)
4429 /* W32_TODO: palette support needed here? */
4430 p->pixel = GET_PIXEL (ximg, x, y);
4431 if (rgb_p)
4433 p->red = RED16_FROM_ULONG (p->pixel);
4434 p->green = GREEN16_FROM_ULONG (p->pixel);
4435 p->blue = BLUE16_FROM_ULONG (p->pixel);
4438 #endif /* HAVE_X_WINDOWS */
4441 Destroy_Image (ximg, prev);
4443 return colors;
4446 #ifdef HAVE_NTGUI
4448 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4449 created with CreateDIBSection, with the pointer to the bit values
4450 stored in ximg->data. */
4452 static void
4453 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4455 int width = ximg->info.bmiHeader.biWidth;
4456 unsigned char * pixel;
4458 /* True color images. */
4459 if (ximg->info.bmiHeader.biBitCount == 24)
4461 int rowbytes = width * 3;
4462 /* Ensure scanlines are aligned on 4 byte boundaries. */
4463 if (rowbytes % 4)
4464 rowbytes += 4 - (rowbytes % 4);
4466 pixel = ximg->data + y * rowbytes + x * 3;
4467 /* Windows bitmaps are in BGR order. */
4468 *pixel = GetBValue (color);
4469 *(pixel + 1) = GetGValue (color);
4470 *(pixel + 2) = GetRValue (color);
4472 /* Monochrome images. */
4473 else if (ximg->info.bmiHeader.biBitCount == 1)
4475 int rowbytes = width / 8;
4476 /* Ensure scanlines are aligned on 4 byte boundaries. */
4477 if (rowbytes % 4)
4478 rowbytes += 4 - (rowbytes % 4);
4479 pixel = ximg->data + y * rowbytes + x / 8;
4480 /* Filter out palette info. */
4481 if (color & 0x00ffffff)
4482 *pixel = *pixel | (1 << x % 8);
4483 else
4484 *pixel = *pixel & ~(1 << x % 8);
4486 else
4487 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4490 #endif /* HAVE_NTGUI */
4492 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4493 RGB members are set. F is the frame on which this all happens.
4494 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4496 static void
4497 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4499 int x, y;
4500 XImagePtr oimg = NULL;
4501 Pixmap pixmap;
4502 XColor *p;
4504 init_color_table ();
4506 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4507 &oimg, &pixmap);
4508 p = colors;
4509 for (y = 0; y < img->height; ++y)
4510 for (x = 0; x < img->width; ++x, ++p)
4512 unsigned long pixel;
4513 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4514 XPutPixel (oimg, x, y, pixel);
4517 xfree (colors);
4518 x_clear_image_1 (f, img, 1, 0, 1);
4520 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4521 x_destroy_x_image (oimg);
4522 img->pixmap = pixmap;
4523 #ifdef COLOR_TABLE_SUPPORT
4524 img->colors = colors_in_color_table (&img->ncolors);
4525 free_color_table ();
4526 #endif /* COLOR_TABLE_SUPPORT */
4530 /* On frame F, perform edge-detection on image IMG.
4532 MATRIX is a nine-element array specifying the transformation
4533 matrix. See emboss_matrix for an example.
4535 COLOR_ADJUST is a color adjustment added to each pixel of the
4536 outgoing image. */
4538 static void
4539 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4541 XColor *colors = x_to_xcolors (f, img, 1);
4542 XColor *new, *p;
4543 int x, y, i, sum;
4545 for (i = sum = 0; i < 9; ++i)
4546 sum += eabs (matrix[i]);
4548 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4550 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width < img->height)
4551 memory_full (SIZE_MAX);
4552 new = xmalloc (sizeof *new * img->width * img->height);
4554 for (y = 0; y < img->height; ++y)
4556 p = COLOR (new, 0, y);
4557 p->red = p->green = p->blue = 0xffff/2;
4558 p = COLOR (new, img->width - 1, y);
4559 p->red = p->green = p->blue = 0xffff/2;
4562 for (x = 1; x < img->width - 1; ++x)
4564 p = COLOR (new, x, 0);
4565 p->red = p->green = p->blue = 0xffff/2;
4566 p = COLOR (new, x, img->height - 1);
4567 p->red = p->green = p->blue = 0xffff/2;
4570 for (y = 1; y < img->height - 1; ++y)
4572 p = COLOR (new, 1, y);
4574 for (x = 1; x < img->width - 1; ++x, ++p)
4576 int r, g, b, yy, xx;
4578 r = g = b = i = 0;
4579 for (yy = y - 1; yy < y + 2; ++yy)
4580 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4581 if (matrix[i])
4583 XColor *t = COLOR (colors, xx, yy);
4584 r += matrix[i] * t->red;
4585 g += matrix[i] * t->green;
4586 b += matrix[i] * t->blue;
4589 r = (r / sum + color_adjust) & 0xffff;
4590 g = (g / sum + color_adjust) & 0xffff;
4591 b = (b / sum + color_adjust) & 0xffff;
4592 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4596 xfree (colors);
4597 x_from_xcolors (f, img, new);
4599 #undef COLOR
4603 /* Perform the pre-defined `emboss' edge-detection on image IMG
4604 on frame F. */
4606 static void
4607 x_emboss (struct frame *f, struct image *img)
4609 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4613 /* Transform image IMG which is used on frame F with a Laplace
4614 edge-detection algorithm. The result is an image that can be used
4615 to draw disabled buttons, for example. */
4617 static void
4618 x_laplace (struct frame *f, struct image *img)
4620 x_detect_edges (f, img, laplace_matrix, 45000);
4624 /* Perform edge-detection on image IMG on frame F, with specified
4625 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4627 MATRIX must be either
4629 - a list of at least 9 numbers in row-major form
4630 - a vector of at least 9 numbers
4632 COLOR_ADJUST nil means use a default; otherwise it must be a
4633 number. */
4635 static void
4636 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4637 Lisp_Object color_adjust)
4639 int i = 0;
4640 int trans[9];
4642 if (CONSP (matrix))
4644 for (i = 0;
4645 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4646 ++i, matrix = XCDR (matrix))
4647 trans[i] = XFLOATINT (XCAR (matrix));
4649 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4651 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4652 trans[i] = XFLOATINT (AREF (matrix, i));
4655 if (NILP (color_adjust))
4656 color_adjust = make_number (0xffff / 2);
4658 if (i == 9 && NUMBERP (color_adjust))
4659 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4663 /* Transform image IMG on frame F so that it looks disabled. */
4665 static void
4666 x_disable_image (struct frame *f, struct image *img)
4668 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4669 #ifdef HAVE_NTGUI
4670 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4671 #else
4672 int n_planes = dpyinfo->n_planes;
4673 #endif /* HAVE_NTGUI */
4675 if (n_planes >= 2)
4677 /* Color (or grayscale). Convert to gray, and equalize. Just
4678 drawing such images with a stipple can look very odd, so
4679 we're using this method instead. */
4680 XColor *colors = x_to_xcolors (f, img, 1);
4681 XColor *p, *end;
4682 const int h = 15000;
4683 const int l = 30000;
4685 for (p = colors, end = colors + img->width * img->height;
4686 p < end;
4687 ++p)
4689 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4690 int i2 = (0xffff - h - l) * i / 0xffff + l;
4691 p->red = p->green = p->blue = i2;
4694 x_from_xcolors (f, img, colors);
4697 /* Draw a cross over the disabled image, if we must or if we
4698 should. */
4699 if (n_planes < 2 || cross_disabled_images)
4701 #ifndef HAVE_NTGUI
4702 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4704 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4706 Display *dpy = FRAME_X_DISPLAY (f);
4707 GC gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4708 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4709 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4710 img->width - 1, img->height - 1);
4711 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4712 img->width - 1, 0);
4713 XFreeGC (dpy, gc);
4715 if (img->mask)
4717 gc = XCreateGC (dpy, img->mask, 0, NULL);
4718 XSetForeground (dpy, gc, MaskForeground (f));
4719 XDrawLine (dpy, img->mask, gc, 0, 0,
4720 img->width - 1, img->height - 1);
4721 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4722 img->width - 1, 0);
4723 XFreeGC (dpy, gc);
4725 #endif /* !HAVE_NS */
4726 #else
4727 HDC hdc, bmpdc;
4728 HGDIOBJ prev;
4730 hdc = get_frame_dc (f);
4731 bmpdc = CreateCompatibleDC (hdc);
4732 release_frame_dc (f, hdc);
4734 prev = SelectObject (bmpdc, img->pixmap);
4736 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4737 MoveToEx (bmpdc, 0, 0, NULL);
4738 LineTo (bmpdc, img->width - 1, img->height - 1);
4739 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4740 LineTo (bmpdc, img->width - 1, 0);
4742 if (img->mask)
4744 SelectObject (bmpdc, img->mask);
4745 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4746 MoveToEx (bmpdc, 0, 0, NULL);
4747 LineTo (bmpdc, img->width - 1, img->height - 1);
4748 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4749 LineTo (bmpdc, img->width - 1, 0);
4751 SelectObject (bmpdc, prev);
4752 DeleteDC (bmpdc);
4753 #endif /* HAVE_NTGUI */
4758 /* Build a mask for image IMG which is used on frame F. FILE is the
4759 name of an image file, for error messages. HOW determines how to
4760 determine the background color of IMG. If it is a list '(R G B)',
4761 with R, G, and B being integers >= 0, take that as the color of the
4762 background. Otherwise, determine the background color of IMG
4763 heuristically. */
4765 static void
4766 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4768 XImagePtr_or_DC ximg;
4769 #ifndef HAVE_NTGUI
4770 XImagePtr mask_img;
4771 #else
4772 HDC frame_dc;
4773 HGDIOBJ prev;
4774 char *mask_img;
4775 int row_width;
4776 #endif /* HAVE_NTGUI */
4777 int x, y;
4778 bool rc, use_img_background;
4779 unsigned long bg = 0;
4781 if (img->mask)
4783 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4784 img->mask = NO_PIXMAP;
4785 img->background_transparent_valid = 0;
4788 #ifndef HAVE_NTGUI
4789 #ifndef HAVE_NS
4790 /* Create an image and pixmap serving as mask. */
4791 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4792 &mask_img, &img->mask);
4793 if (!rc)
4794 return;
4795 #endif /* !HAVE_NS */
4797 /* Get the X image of IMG->pixmap. */
4798 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4799 img->width, img->height,
4800 ~0, ZPixmap);
4801 #else
4802 /* Create the bit array serving as mask. */
4803 row_width = (img->width + 7) / 8;
4804 mask_img = xzalloc (row_width * img->height);
4806 /* Create a memory device context for IMG->pixmap. */
4807 frame_dc = get_frame_dc (f);
4808 ximg = CreateCompatibleDC (frame_dc);
4809 release_frame_dc (f, frame_dc);
4810 prev = SelectObject (ximg, img->pixmap);
4811 #endif /* HAVE_NTGUI */
4813 /* Determine the background color of ximg. If HOW is `(R G B)'
4814 take that as color. Otherwise, use the image's background color. */
4815 use_img_background = 1;
4817 if (CONSP (how))
4819 int rgb[3], i;
4821 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4823 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4824 how = XCDR (how);
4827 if (i == 3 && NILP (how))
4829 char color_name[30];
4830 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4831 bg = (
4832 #ifdef HAVE_NTGUI
4833 0x00ffffff & /* Filter out palette info. */
4834 #endif /* HAVE_NTGUI */
4835 x_alloc_image_color (f, img, build_string (color_name), 0));
4836 use_img_background = 0;
4840 if (use_img_background)
4841 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4843 /* Set all bits in mask_img to 1 whose color in ximg is different
4844 from the background color bg. */
4845 #ifndef HAVE_NTGUI
4846 for (y = 0; y < img->height; ++y)
4847 for (x = 0; x < img->width; ++x)
4848 #ifndef HAVE_NS
4849 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4850 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4851 #else
4852 if (XGetPixel (ximg, x, y) == bg)
4853 ns_set_alpha (ximg, x, y, 0);
4854 #endif /* HAVE_NS */
4855 #ifndef HAVE_NS
4856 /* Fill in the background_transparent field while we have the mask handy. */
4857 image_background_transparent (img, f, mask_img);
4859 /* Put mask_img into img->mask. */
4860 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4861 x_destroy_x_image (mask_img);
4862 #endif /* !HAVE_NS */
4863 #else
4864 for (y = 0; y < img->height; ++y)
4865 for (x = 0; x < img->width; ++x)
4867 COLORREF p = GetPixel (ximg, x, y);
4868 if (p != bg)
4869 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4872 /* Create the mask image. */
4873 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4874 mask_img);
4875 /* Fill in the background_transparent field while we have the mask handy. */
4876 SelectObject (ximg, img->mask);
4877 image_background_transparent (img, f, ximg);
4879 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4880 xfree (mask_img);
4881 #endif /* HAVE_NTGUI */
4883 Destroy_Image (ximg, prev);
4887 /***********************************************************************
4888 PBM (mono, gray, color)
4889 ***********************************************************************/
4891 static bool pbm_image_p (Lisp_Object object);
4892 static bool pbm_load (struct frame *f, struct image *img);
4894 /* The symbol `pbm' identifying images of this type. */
4896 static Lisp_Object Qpbm;
4898 /* Indices of image specification fields in gs_format, below. */
4900 enum pbm_keyword_index
4902 PBM_TYPE,
4903 PBM_FILE,
4904 PBM_DATA,
4905 PBM_ASCENT,
4906 PBM_MARGIN,
4907 PBM_RELIEF,
4908 PBM_ALGORITHM,
4909 PBM_HEURISTIC_MASK,
4910 PBM_MASK,
4911 PBM_FOREGROUND,
4912 PBM_BACKGROUND,
4913 PBM_LAST
4916 /* Vector of image_keyword structures describing the format
4917 of valid user-defined image specifications. */
4919 static const struct image_keyword pbm_format[PBM_LAST] =
4921 {":type", IMAGE_SYMBOL_VALUE, 1},
4922 {":file", IMAGE_STRING_VALUE, 0},
4923 {":data", IMAGE_STRING_VALUE, 0},
4924 {":ascent", IMAGE_ASCENT_VALUE, 0},
4925 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4926 {":relief", IMAGE_INTEGER_VALUE, 0},
4927 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4928 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4929 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4930 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4931 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4934 /* Structure describing the image type `pbm'. */
4936 static struct image_type pbm_type =
4938 &Qpbm,
4939 pbm_image_p,
4940 pbm_load,
4941 x_clear_image,
4942 NULL,
4943 NULL
4947 /* Return true if OBJECT is a valid PBM image specification. */
4949 static bool
4950 pbm_image_p (Lisp_Object object)
4952 struct image_keyword fmt[PBM_LAST];
4954 memcpy (fmt, pbm_format, sizeof fmt);
4956 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
4957 return 0;
4959 /* Must specify either :data or :file. */
4960 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
4964 /* Scan a decimal number from *S and return it. Advance *S while
4965 reading the number. END is the end of the string. Value is -1 at
4966 end of input. */
4968 static int
4969 pbm_scan_number (unsigned char **s, unsigned char *end)
4971 int c = 0, val = -1;
4973 while (*s < end)
4975 /* Skip white-space. */
4976 while (*s < end && (c = *(*s)++, c_isspace (c)))
4979 if (c == '#')
4981 /* Skip comment to end of line. */
4982 while (*s < end && (c = *(*s)++, c != '\n'))
4985 else if (c_isdigit (c))
4987 /* Read decimal number. */
4988 val = c - '0';
4989 while (*s < end && (c = *(*s)++, c_isdigit (c)))
4990 val = 10 * val + c - '0';
4991 break;
4993 else
4994 break;
4997 return val;
5001 /* Load PBM image IMG for use on frame F. */
5003 static bool
5004 pbm_load (struct frame *f, struct image *img)
5006 bool raw_p;
5007 int x, y;
5008 int width, height, max_color_idx = 0;
5009 XImagePtr ximg;
5010 Lisp_Object file, specified_file;
5011 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5012 unsigned char *contents = NULL;
5013 unsigned char *end, *p;
5014 ptrdiff_t size;
5016 specified_file = image_spec_value (img->spec, QCfile, NULL);
5018 if (STRINGP (specified_file))
5020 file = x_find_image_file (specified_file);
5021 if (!STRINGP (file))
5023 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5024 return 0;
5027 contents = slurp_file (SSDATA (file), &size);
5028 if (contents == NULL)
5030 image_error ("Error reading `%s'", file, Qnil);
5031 return 0;
5034 p = contents;
5035 end = contents + size;
5037 else
5039 Lisp_Object data;
5040 data = image_spec_value (img->spec, QCdata, NULL);
5041 if (!STRINGP (data))
5043 image_error ("Invalid image data `%s'", data, Qnil);
5044 return 0;
5046 p = SDATA (data);
5047 end = p + SBYTES (data);
5050 /* Check magic number. */
5051 if (end - p < 2 || *p++ != 'P')
5053 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5054 error:
5055 xfree (contents);
5056 return 0;
5059 switch (*p++)
5061 case '1':
5062 raw_p = 0, type = PBM_MONO;
5063 break;
5065 case '2':
5066 raw_p = 0, type = PBM_GRAY;
5067 break;
5069 case '3':
5070 raw_p = 0, type = PBM_COLOR;
5071 break;
5073 case '4':
5074 raw_p = 1, type = PBM_MONO;
5075 break;
5077 case '5':
5078 raw_p = 1, type = PBM_GRAY;
5079 break;
5081 case '6':
5082 raw_p = 1, type = PBM_COLOR;
5083 break;
5085 default:
5086 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5087 goto error;
5090 /* Read width, height, maximum color-component. Characters
5091 starting with `#' up to the end of a line are ignored. */
5092 width = pbm_scan_number (&p, end);
5093 height = pbm_scan_number (&p, end);
5095 if (type != PBM_MONO)
5097 max_color_idx = pbm_scan_number (&p, end);
5098 if (max_color_idx > 65535 || max_color_idx < 0)
5100 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5101 goto error;
5105 if (!check_image_size (f, width, height))
5107 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5108 goto error;
5111 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5112 &ximg, &img->pixmap))
5113 goto error;
5115 /* Initialize the color hash table. */
5116 init_color_table ();
5118 if (type == PBM_MONO)
5120 int c = 0, g;
5121 struct image_keyword fmt[PBM_LAST];
5122 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5123 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5125 /* Parse the image specification. */
5126 memcpy (fmt, pbm_format, sizeof fmt);
5127 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5129 /* Get foreground and background colors, maybe allocate colors. */
5130 if (fmt[PBM_FOREGROUND].count
5131 && STRINGP (fmt[PBM_FOREGROUND].value))
5132 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5133 if (fmt[PBM_BACKGROUND].count
5134 && STRINGP (fmt[PBM_BACKGROUND].value))
5136 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5137 img->background = bg;
5138 img->background_valid = 1;
5141 for (y = 0; y < height; ++y)
5142 for (x = 0; x < width; ++x)
5144 if (raw_p)
5146 if ((x & 7) == 0)
5148 if (p >= end)
5150 x_destroy_x_image (ximg);
5151 x_clear_image (f, img);
5152 image_error ("Invalid image size in image `%s'",
5153 img->spec, Qnil);
5154 goto error;
5156 c = *p++;
5158 g = c & 0x80;
5159 c <<= 1;
5161 else
5162 g = pbm_scan_number (&p, end);
5164 XPutPixel (ximg, x, y, g ? fg : bg);
5167 else
5169 int expected_size = height * width;
5170 if (max_color_idx > 255)
5171 expected_size *= 2;
5172 if (type == PBM_COLOR)
5173 expected_size *= 3;
5175 if (raw_p && p + expected_size > end)
5177 x_destroy_x_image (ximg);
5178 x_clear_image (f, img);
5179 image_error ("Invalid image size in image `%s'",
5180 img->spec, Qnil);
5181 goto error;
5184 for (y = 0; y < height; ++y)
5185 for (x = 0; x < width; ++x)
5187 int r, g, b;
5189 if (type == PBM_GRAY && raw_p)
5191 r = g = b = *p++;
5192 if (max_color_idx > 255)
5193 r = g = b = r * 256 + *p++;
5195 else if (type == PBM_GRAY)
5196 r = g = b = pbm_scan_number (&p, end);
5197 else if (raw_p)
5199 r = *p++;
5200 if (max_color_idx > 255)
5201 r = r * 256 + *p++;
5202 g = *p++;
5203 if (max_color_idx > 255)
5204 g = g * 256 + *p++;
5205 b = *p++;
5206 if (max_color_idx > 255)
5207 b = b * 256 + *p++;
5209 else
5211 r = pbm_scan_number (&p, end);
5212 g = pbm_scan_number (&p, end);
5213 b = pbm_scan_number (&p, end);
5216 if (r < 0 || g < 0 || b < 0)
5218 x_destroy_x_image (ximg);
5219 image_error ("Invalid pixel value in image `%s'",
5220 img->spec, Qnil);
5221 goto error;
5224 /* RGB values are now in the range 0..max_color_idx.
5225 Scale this to the range 0..0xffff supported by X. */
5226 r = (double) r * 65535 / max_color_idx;
5227 g = (double) g * 65535 / max_color_idx;
5228 b = (double) b * 65535 / max_color_idx;
5229 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5233 #ifdef COLOR_TABLE_SUPPORT
5234 /* Store in IMG->colors the colors allocated for the image, and
5235 free the color table. */
5236 img->colors = colors_in_color_table (&img->ncolors);
5237 free_color_table ();
5238 #endif /* COLOR_TABLE_SUPPORT */
5240 img->width = width;
5241 img->height = height;
5243 /* Maybe fill in the background field while we have ximg handy. */
5245 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5246 /* Casting avoids a GCC warning. */
5247 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5249 /* Put the image into a pixmap. */
5250 x_put_x_image (f, ximg, img->pixmap, width, height);
5251 x_destroy_x_image (ximg);
5253 /* X and W32 versions did it here, MAC version above. ++kfs
5254 img->width = width;
5255 img->height = height; */
5257 xfree (contents);
5258 return 1;
5262 /***********************************************************************
5264 ***********************************************************************/
5266 #if defined (HAVE_PNG) || defined (HAVE_NS)
5268 /* Function prototypes. */
5270 static bool png_image_p (Lisp_Object object);
5271 static bool png_load (struct frame *f, struct image *img);
5273 /* The symbol `png' identifying images of this type. */
5275 static Lisp_Object Qpng;
5277 /* Indices of image specification fields in png_format, below. */
5279 enum png_keyword_index
5281 PNG_TYPE,
5282 PNG_DATA,
5283 PNG_FILE,
5284 PNG_ASCENT,
5285 PNG_MARGIN,
5286 PNG_RELIEF,
5287 PNG_ALGORITHM,
5288 PNG_HEURISTIC_MASK,
5289 PNG_MASK,
5290 PNG_BACKGROUND,
5291 PNG_LAST
5294 /* Vector of image_keyword structures describing the format
5295 of valid user-defined image specifications. */
5297 static const struct image_keyword png_format[PNG_LAST] =
5299 {":type", IMAGE_SYMBOL_VALUE, 1},
5300 {":data", IMAGE_STRING_VALUE, 0},
5301 {":file", IMAGE_STRING_VALUE, 0},
5302 {":ascent", IMAGE_ASCENT_VALUE, 0},
5303 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5304 {":relief", IMAGE_INTEGER_VALUE, 0},
5305 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5306 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5307 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5308 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5311 #if defined HAVE_NTGUI && defined WINDOWSNT
5312 static bool init_png_functions (void);
5313 #else
5314 #define init_png_functions NULL
5315 #endif
5317 /* Structure describing the image type `png'. */
5319 static struct image_type png_type =
5321 &Qpng,
5322 png_image_p,
5323 png_load,
5324 x_clear_image,
5325 init_png_functions,
5326 NULL
5329 /* Return true if OBJECT is a valid PNG image specification. */
5331 static bool
5332 png_image_p (Lisp_Object object)
5334 struct image_keyword fmt[PNG_LAST];
5335 memcpy (fmt, png_format, sizeof fmt);
5337 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5338 return 0;
5340 /* Must specify either the :data or :file keyword. */
5341 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5344 #endif /* HAVE_PNG || HAVE_NS */
5347 #ifdef HAVE_PNG
5349 #ifdef WINDOWSNT
5350 /* PNG library details. */
5352 DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5353 DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5354 DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5355 png_error_ptr, png_error_ptr));
5356 DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5357 DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5358 DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5359 DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5360 DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5361 DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
5362 png_uint_32 *, png_uint_32 *,
5363 int *, int *, int *, int *, int *));
5364 DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5365 DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5366 DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5367 DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5368 DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
5369 int, int, double));
5370 DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5371 DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5372 DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5373 DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5374 DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5375 DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5376 DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
5378 #if (PNG_LIBPNG_VER >= 10500)
5379 DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int));
5380 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
5381 #endif /* libpng version >= 1.5 */
5383 static bool
5384 init_png_functions (void)
5386 HMODULE library;
5388 if (!(library = w32_delayed_load (Qpng)))
5389 return 0;
5391 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5392 LOAD_IMGLIB_FN (library, png_sig_cmp);
5393 LOAD_IMGLIB_FN (library, png_create_read_struct);
5394 LOAD_IMGLIB_FN (library, png_create_info_struct);
5395 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5396 LOAD_IMGLIB_FN (library, png_set_read_fn);
5397 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5398 LOAD_IMGLIB_FN (library, png_read_info);
5399 LOAD_IMGLIB_FN (library, png_get_IHDR);
5400 LOAD_IMGLIB_FN (library, png_get_valid);
5401 LOAD_IMGLIB_FN (library, png_set_strip_16);
5402 LOAD_IMGLIB_FN (library, png_set_expand);
5403 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5404 LOAD_IMGLIB_FN (library, png_set_background);
5405 LOAD_IMGLIB_FN (library, png_get_bKGD);
5406 LOAD_IMGLIB_FN (library, png_read_update_info);
5407 LOAD_IMGLIB_FN (library, png_get_channels);
5408 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5409 LOAD_IMGLIB_FN (library, png_read_image);
5410 LOAD_IMGLIB_FN (library, png_read_end);
5411 LOAD_IMGLIB_FN (library, png_error);
5413 #if (PNG_LIBPNG_VER >= 10500)
5414 LOAD_IMGLIB_FN (library, png_longjmp);
5415 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5416 #endif /* libpng version >= 1.5 */
5418 return 1;
5420 #else
5422 #define fn_png_get_io_ptr png_get_io_ptr
5423 #define fn_png_sig_cmp png_sig_cmp
5424 #define fn_png_create_read_struct png_create_read_struct
5425 #define fn_png_create_info_struct png_create_info_struct
5426 #define fn_png_destroy_read_struct png_destroy_read_struct
5427 #define fn_png_set_read_fn png_set_read_fn
5428 #define fn_png_set_sig_bytes png_set_sig_bytes
5429 #define fn_png_read_info png_read_info
5430 #define fn_png_get_IHDR png_get_IHDR
5431 #define fn_png_get_valid png_get_valid
5432 #define fn_png_set_strip_16 png_set_strip_16
5433 #define fn_png_set_expand png_set_expand
5434 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5435 #define fn_png_set_background png_set_background
5436 #define fn_png_get_bKGD png_get_bKGD
5437 #define fn_png_read_update_info png_read_update_info
5438 #define fn_png_get_channels png_get_channels
5439 #define fn_png_get_rowbytes png_get_rowbytes
5440 #define fn_png_read_image png_read_image
5441 #define fn_png_read_end png_read_end
5442 #define fn_png_error png_error
5444 #if (PNG_LIBPNG_VER >= 10500)
5445 #define fn_png_longjmp png_longjmp
5446 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5447 #endif /* libpng version >= 1.5 */
5449 #endif /* WINDOWSNT */
5451 /* Possibly inefficient/inexact substitutes for _setjmp and _longjmp.
5452 Do not use sys_setjmp, as PNG supports only jmp_buf. The _longjmp
5453 substitute may munge the signal mask, but that should be OK here.
5454 MinGW (MS-Windows) uses _setjmp and defines setjmp to _setjmp in
5455 the system header setjmp.h; don't mess up that. */
5456 #ifndef HAVE__SETJMP
5457 # define _setjmp(j) setjmp (j)
5458 # define _longjmp longjmp
5459 #endif
5461 #if (PNG_LIBPNG_VER < 10500)
5462 #define PNG_LONGJMP(ptr) (_longjmp ((ptr)->jmpbuf, 1))
5463 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5464 #else
5465 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5466 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5467 #define PNG_JMPBUF(ptr) \
5468 (*fn_png_set_longjmp_fn ((ptr), _longjmp, sizeof (jmp_buf)))
5469 #endif
5471 /* Error and warning handlers installed when the PNG library
5472 is initialized. */
5474 static _Noreturn void
5475 my_png_error (png_struct *png_ptr, const char *msg)
5477 eassert (png_ptr != NULL);
5478 /* Avoid compiler warning about deprecated direct access to
5479 png_ptr's fields in libpng versions 1.4.x. */
5480 image_error ("PNG error: %s", build_string (msg), Qnil);
5481 PNG_LONGJMP (png_ptr);
5485 static void
5486 my_png_warning (png_struct *png_ptr, const char *msg)
5488 eassert (png_ptr != NULL);
5489 image_error ("PNG warning: %s", build_string (msg), Qnil);
5492 /* Memory source for PNG decoding. */
5494 struct png_memory_storage
5496 unsigned char *bytes; /* The data */
5497 ptrdiff_t len; /* How big is it? */
5498 ptrdiff_t index; /* Where are we? */
5502 /* Function set as reader function when reading PNG image from memory.
5503 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5504 bytes from the input to DATA. */
5506 static void
5507 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5509 struct png_memory_storage *tbr
5510 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5512 if (length > tbr->len - tbr->index)
5513 fn_png_error (png_ptr, "Read error");
5515 memcpy (data, tbr->bytes + tbr->index, length);
5516 tbr->index = tbr->index + length;
5520 /* Function set as reader function when reading PNG image from a file.
5521 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5522 bytes from the input to DATA. */
5524 static void
5525 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5527 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5529 if (fread (data, 1, length, fp) < length)
5530 fn_png_error (png_ptr, "Read error");
5534 /* Load PNG image IMG for use on frame F. Value is true if
5535 successful. */
5537 struct png_load_context
5539 /* These are members so that longjmp doesn't munge local variables. */
5540 png_struct *png_ptr;
5541 png_info *info_ptr;
5542 png_info *end_info;
5543 FILE *fp;
5544 png_byte *pixels;
5545 png_byte **rows;
5548 static bool
5549 png_load_body (struct frame *f, struct image *img, struct png_load_context *c)
5551 Lisp_Object file, specified_file;
5552 Lisp_Object specified_data;
5553 int x, y;
5554 ptrdiff_t i;
5555 XImagePtr ximg, mask_img = NULL;
5556 png_struct *png_ptr;
5557 png_info *info_ptr = NULL, *end_info = NULL;
5558 FILE *fp = NULL;
5559 png_byte sig[8];
5560 png_byte *pixels = NULL;
5561 png_byte **rows = NULL;
5562 png_uint_32 width, height;
5563 int bit_depth, color_type, interlace_type;
5564 png_byte channels;
5565 png_uint_32 row_bytes;
5566 bool transparent_p;
5567 struct png_memory_storage tbr; /* Data to be read */
5569 /* Find out what file to load. */
5570 specified_file = image_spec_value (img->spec, QCfile, NULL);
5571 specified_data = image_spec_value (img->spec, QCdata, NULL);
5573 if (NILP (specified_data))
5575 file = x_find_image_file (specified_file);
5576 if (!STRINGP (file))
5578 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5579 return 0;
5582 /* Open the image file. */
5583 fp = fopen (SSDATA (file), "rb");
5584 if (!fp)
5586 image_error ("Cannot open image file `%s'", file, Qnil);
5587 return 0;
5590 /* Check PNG signature. */
5591 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5592 || fn_png_sig_cmp (sig, 0, sizeof sig))
5594 image_error ("Not a PNG file: `%s'", file, Qnil);
5595 fclose (fp);
5596 return 0;
5599 else
5601 if (!STRINGP (specified_data))
5603 image_error ("Invalid image data `%s'", specified_data, Qnil);
5604 return 0;
5607 /* Read from memory. */
5608 tbr.bytes = SDATA (specified_data);
5609 tbr.len = SBYTES (specified_data);
5610 tbr.index = 0;
5612 /* Check PNG signature. */
5613 if (tbr.len < sizeof sig
5614 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5616 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5617 return 0;
5620 /* Need to skip past the signature. */
5621 tbr.bytes += sizeof (sig);
5624 /* Initialize read and info structs for PNG lib. */
5625 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5626 NULL, my_png_error,
5627 my_png_warning);
5628 if (png_ptr)
5630 info_ptr = fn_png_create_info_struct (png_ptr);
5631 end_info = fn_png_create_info_struct (png_ptr);
5634 c->png_ptr = png_ptr;
5635 c->info_ptr = info_ptr;
5636 c->end_info = end_info;
5637 c->fp = fp;
5638 c->pixels = pixels;
5639 c->rows = rows;
5641 if (! (info_ptr && end_info))
5643 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5644 png_ptr = 0;
5646 if (! png_ptr)
5648 if (fp) fclose (fp);
5649 return 0;
5652 /* Set error jump-back. We come back here when the PNG library
5653 detects an error. */
5654 if (_setjmp (PNG_JMPBUF (png_ptr)))
5656 error:
5657 if (c->png_ptr)
5658 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5659 xfree (c->pixels);
5660 xfree (c->rows);
5661 if (c->fp)
5662 fclose (c->fp);
5663 return 0;
5666 /* Silence a bogus diagnostic; see GCC bug 54561. */
5667 IF_LINT (fp = c->fp);
5669 /* Read image info. */
5670 if (!NILP (specified_data))
5671 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5672 else
5673 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5675 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5676 fn_png_read_info (png_ptr, info_ptr);
5677 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5678 &interlace_type, NULL, NULL);
5680 if (! (width <= INT_MAX && height <= INT_MAX
5681 && check_image_size (f, width, height)))
5683 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5684 goto error;
5687 /* Create the X image and pixmap now, so that the work below can be
5688 omitted if the image is too large for X. */
5689 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5690 &img->pixmap))
5691 goto error;
5693 /* If image contains simply transparency data, we prefer to
5694 construct a clipping mask. */
5695 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5696 transparent_p = 1;
5697 else
5698 transparent_p = 0;
5700 /* This function is easier to write if we only have to handle
5701 one data format: RGB or RGBA with 8 bits per channel. Let's
5702 transform other formats into that format. */
5704 /* Strip more than 8 bits per channel. */
5705 if (bit_depth == 16)
5706 fn_png_set_strip_16 (png_ptr);
5708 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5709 if available. */
5710 fn_png_set_expand (png_ptr);
5712 /* Convert grayscale images to RGB. */
5713 if (color_type == PNG_COLOR_TYPE_GRAY
5714 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5715 fn_png_set_gray_to_rgb (png_ptr);
5717 /* Handle alpha channel by combining the image with a background
5718 color. Do this only if a real alpha channel is supplied. For
5719 simple transparency, we prefer a clipping mask. */
5720 if (!transparent_p)
5722 /* png_color_16 *image_bg; */
5723 Lisp_Object specified_bg
5724 = image_spec_value (img->spec, QCbackground, NULL);
5725 int shift = (bit_depth == 16) ? 0 : 8;
5727 if (STRINGP (specified_bg))
5728 /* The user specified `:background', use that. */
5730 XColor color;
5731 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
5733 png_color_16 user_bg;
5735 memset (&user_bg, 0, sizeof user_bg);
5736 user_bg.red = color.red >> shift;
5737 user_bg.green = color.green >> shift;
5738 user_bg.blue = color.blue >> shift;
5740 fn_png_set_background (png_ptr, &user_bg,
5741 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5744 else
5746 /* We use the current frame background, ignoring any default
5747 background color set by the image. */
5748 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5749 XColor color;
5750 png_color_16 frame_background;
5752 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5753 x_query_color (f, &color);
5755 memset (&frame_background, 0, sizeof frame_background);
5756 frame_background.red = color.red >> shift;
5757 frame_background.green = color.green >> shift;
5758 frame_background.blue = color.blue >> shift;
5759 #endif /* HAVE_X_WINDOWS */
5761 fn_png_set_background (png_ptr, &frame_background,
5762 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5766 /* Update info structure. */
5767 fn_png_read_update_info (png_ptr, info_ptr);
5769 /* Get number of channels. Valid values are 1 for grayscale images
5770 and images with a palette, 2 for grayscale images with transparency
5771 information (alpha channel), 3 for RGB images, and 4 for RGB
5772 images with alpha channel, i.e. RGBA. If conversions above were
5773 sufficient we should only have 3 or 4 channels here. */
5774 channels = fn_png_get_channels (png_ptr, info_ptr);
5775 eassert (channels == 3 || channels == 4);
5777 /* Number of bytes needed for one row of the image. */
5778 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5780 /* Allocate memory for the image. */
5781 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows < height
5782 || min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height < row_bytes)
5783 memory_full (SIZE_MAX);
5784 c->pixels = pixels = xmalloc (sizeof *pixels * row_bytes * height);
5785 c->rows = rows = xmalloc (height * sizeof *rows);
5786 for (i = 0; i < height; ++i)
5787 rows[i] = pixels + i * row_bytes;
5789 /* Read the entire image. */
5790 fn_png_read_image (png_ptr, rows);
5791 fn_png_read_end (png_ptr, info_ptr);
5792 if (fp)
5794 fclose (fp);
5795 c->fp = NULL;
5798 /* Create an image and pixmap serving as mask if the PNG image
5799 contains an alpha channel. */
5800 if (channels == 4
5801 && !transparent_p
5802 && !x_create_x_image_and_pixmap (f, width, height, 1,
5803 &mask_img, &img->mask))
5805 x_destroy_x_image (ximg);
5806 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5807 img->pixmap = NO_PIXMAP;
5808 goto error;
5811 /* Fill the X image and mask from PNG data. */
5812 init_color_table ();
5814 for (y = 0; y < height; ++y)
5816 png_byte *p = rows[y];
5818 for (x = 0; x < width; ++x)
5820 int r, g, b;
5822 r = *p++ << 8;
5823 g = *p++ << 8;
5824 b = *p++ << 8;
5825 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5826 /* An alpha channel, aka mask channel, associates variable
5827 transparency with an image. Where other image formats
5828 support binary transparency---fully transparent or fully
5829 opaque---PNG allows up to 254 levels of partial transparency.
5830 The PNG library implements partial transparency by combining
5831 the image with a specified background color.
5833 I'm not sure how to handle this here nicely: because the
5834 background on which the image is displayed may change, for
5835 real alpha channel support, it would be necessary to create
5836 a new image for each possible background.
5838 What I'm doing now is that a mask is created if we have
5839 boolean transparency information. Otherwise I'm using
5840 the frame's background color to combine the image with. */
5842 if (channels == 4)
5844 if (mask_img)
5845 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5846 ++p;
5851 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5852 /* Set IMG's background color from the PNG image, unless the user
5853 overrode it. */
5855 png_color_16 *bg;
5856 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5858 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5859 img->background_valid = 1;
5863 #ifdef COLOR_TABLE_SUPPORT
5864 /* Remember colors allocated for this image. */
5865 img->colors = colors_in_color_table (&img->ncolors);
5866 free_color_table ();
5867 #endif /* COLOR_TABLE_SUPPORT */
5869 /* Clean up. */
5870 fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
5871 xfree (rows);
5872 xfree (pixels);
5874 img->width = width;
5875 img->height = height;
5877 /* Maybe fill in the background field while we have ximg handy.
5878 Casting avoids a GCC warning. */
5879 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5881 /* Put the image into the pixmap, then free the X image and its buffer. */
5882 x_put_x_image (f, ximg, img->pixmap, width, height);
5883 x_destroy_x_image (ximg);
5885 /* Same for the mask. */
5886 if (mask_img)
5888 /* Fill in the background_transparent field while we have the
5889 mask handy. Casting avoids a GCC warning. */
5890 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
5892 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5893 x_destroy_x_image (mask_img);
5896 return 1;
5899 static bool
5900 png_load (struct frame *f, struct image *img)
5902 struct png_load_context c;
5903 return png_load_body (f, img, &c);
5906 #else /* HAVE_PNG */
5908 #ifdef HAVE_NS
5909 static bool
5910 png_load (struct frame *f, struct image *img)
5912 return ns_load_image (f, img,
5913 image_spec_value (img->spec, QCfile, NULL),
5914 image_spec_value (img->spec, QCdata, NULL));
5916 #endif /* HAVE_NS */
5919 #endif /* !HAVE_PNG */
5923 /***********************************************************************
5924 JPEG
5925 ***********************************************************************/
5927 #if defined (HAVE_JPEG) || defined (HAVE_NS)
5929 static bool jpeg_image_p (Lisp_Object object);
5930 static bool jpeg_load (struct frame *f, struct image *img);
5932 /* The symbol `jpeg' identifying images of this type. */
5934 static Lisp_Object Qjpeg;
5936 /* Indices of image specification fields in gs_format, below. */
5938 enum jpeg_keyword_index
5940 JPEG_TYPE,
5941 JPEG_DATA,
5942 JPEG_FILE,
5943 JPEG_ASCENT,
5944 JPEG_MARGIN,
5945 JPEG_RELIEF,
5946 JPEG_ALGORITHM,
5947 JPEG_HEURISTIC_MASK,
5948 JPEG_MASK,
5949 JPEG_BACKGROUND,
5950 JPEG_LAST
5953 /* Vector of image_keyword structures describing the format
5954 of valid user-defined image specifications. */
5956 static const struct image_keyword jpeg_format[JPEG_LAST] =
5958 {":type", IMAGE_SYMBOL_VALUE, 1},
5959 {":data", IMAGE_STRING_VALUE, 0},
5960 {":file", IMAGE_STRING_VALUE, 0},
5961 {":ascent", IMAGE_ASCENT_VALUE, 0},
5962 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5963 {":relief", IMAGE_INTEGER_VALUE, 0},
5964 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5965 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5966 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5967 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5970 #if defined HAVE_NTGUI && defined WINDOWSNT
5971 static bool init_jpeg_functions (void);
5972 #else
5973 #define init_jpeg_functions NULL
5974 #endif
5976 /* Structure describing the image type `jpeg'. */
5978 static struct image_type jpeg_type =
5980 &Qjpeg,
5981 jpeg_image_p,
5982 jpeg_load,
5983 x_clear_image,
5984 init_jpeg_functions,
5985 NULL
5988 /* Return true if OBJECT is a valid JPEG image specification. */
5990 static bool
5991 jpeg_image_p (Lisp_Object object)
5993 struct image_keyword fmt[JPEG_LAST];
5995 memcpy (fmt, jpeg_format, sizeof fmt);
5997 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
5998 return 0;
6000 /* Must specify either the :data or :file keyword. */
6001 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6004 #endif /* HAVE_JPEG || HAVE_NS */
6006 #ifdef HAVE_JPEG
6008 /* Work around a warning about HAVE_STDLIB_H being redefined in
6009 jconfig.h. */
6010 #ifdef HAVE_STDLIB_H
6011 #undef HAVE_STDLIB_H
6012 #endif /* HAVE_STLIB_H */
6014 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6015 /* In older releases of the jpeg library, jpeglib.h will define boolean
6016 differently depending on __WIN32__, so make sure it is defined. */
6017 #define __WIN32__ 1
6018 #endif
6020 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
6021 Some versions of jpeglib try to detect whether rpcndr.h is loaded,
6022 using the Windows boolean type instead of the jpeglib boolean type
6023 if so. Cygwin jpeglib, however, doesn't try to detect whether its
6024 headers are included along with windows.h, so under Cygwin, jpeglib
6025 attempts to define a conflicting boolean type. Worse, forcing
6026 Cygwin jpeglib headers to use the Windows boolean type doesn't work
6027 because it created an ABI incompatibility between the
6028 already-compiled jpeg library and the header interface definition.
6030 The best we can do is to define jpeglib's boolean type to a
6031 different name. This name, jpeg_boolean, remains in effect through
6032 the rest of image.c.
6034 #if defined CYGWIN && defined HAVE_NTGUI
6035 #define boolean jpeg_boolean
6036 #endif
6037 #include <jpeglib.h>
6038 #include <jerror.h>
6040 #ifdef WINDOWSNT
6042 /* JPEG library details. */
6043 DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6044 DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6045 DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6046 DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6047 DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6048 DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6049 DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6050 DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6052 static bool
6053 init_jpeg_functions (void)
6055 HMODULE library;
6057 if (!(library = w32_delayed_load (Qjpeg)))
6058 return 0;
6060 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6061 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6062 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6063 LOAD_IMGLIB_FN (library, jpeg_read_header);
6064 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6065 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6066 LOAD_IMGLIB_FN (library, jpeg_std_error);
6067 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6068 return 1;
6071 /* Wrapper since we can't directly assign the function pointer
6072 to another function pointer that was declared more completely easily. */
6073 static boolean
6074 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6076 return fn_jpeg_resync_to_restart (cinfo, desired);
6079 #else
6081 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
6082 #define fn_jpeg_start_decompress jpeg_start_decompress
6083 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6084 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6085 #define fn_jpeg_read_header jpeg_read_header
6086 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6087 #define fn_jpeg_std_error jpeg_std_error
6088 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6090 #endif /* WINDOWSNT */
6092 struct my_jpeg_error_mgr
6094 struct jpeg_error_mgr pub;
6095 sys_jmp_buf setjmp_buffer;
6097 /* The remaining members are so that longjmp doesn't munge local
6098 variables. */
6099 struct jpeg_decompress_struct cinfo;
6100 enum
6102 MY_JPEG_ERROR_EXIT,
6103 MY_JPEG_INVALID_IMAGE_SIZE,
6104 MY_JPEG_CANNOT_CREATE_X
6105 } failure_code;
6106 #ifdef lint
6107 FILE *fp;
6108 #endif
6112 static _Noreturn void
6113 my_error_exit (j_common_ptr cinfo)
6115 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6116 mgr->failure_code = MY_JPEG_ERROR_EXIT;
6117 sys_longjmp (mgr->setjmp_buffer, 1);
6121 /* Init source method for JPEG data source manager. Called by
6122 jpeg_read_header() before any data is actually read. See
6123 libjpeg.doc from the JPEG lib distribution. */
6125 static void
6126 our_common_init_source (j_decompress_ptr cinfo)
6131 /* Method to terminate data source. Called by
6132 jpeg_finish_decompress() after all data has been processed. */
6134 static void
6135 our_common_term_source (j_decompress_ptr cinfo)
6140 /* Fill input buffer method for JPEG data source manager. Called
6141 whenever more data is needed. We read the whole image in one step,
6142 so this only adds a fake end of input marker at the end. */
6144 static JOCTET our_memory_buffer[2];
6146 static boolean
6147 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6149 /* Insert a fake EOI marker. */
6150 struct jpeg_source_mgr *src = cinfo->src;
6152 our_memory_buffer[0] = (JOCTET) 0xFF;
6153 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6155 src->next_input_byte = our_memory_buffer;
6156 src->bytes_in_buffer = 2;
6157 return 1;
6161 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6162 is the JPEG data source manager. */
6164 static void
6165 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6167 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6169 if (src)
6171 if (num_bytes > src->bytes_in_buffer)
6172 ERREXIT (cinfo, JERR_INPUT_EOF);
6174 src->bytes_in_buffer -= num_bytes;
6175 src->next_input_byte += num_bytes;
6180 /* Set up the JPEG lib for reading an image from DATA which contains
6181 LEN bytes. CINFO is the decompression info structure created for
6182 reading the image. */
6184 static void
6185 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, ptrdiff_t len)
6187 struct jpeg_source_mgr *src;
6189 if (cinfo->src == NULL)
6191 /* First time for this JPEG object? */
6192 cinfo->src = (struct jpeg_source_mgr *)
6193 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6194 sizeof (struct jpeg_source_mgr));
6195 src = (struct jpeg_source_mgr *) cinfo->src;
6196 src->next_input_byte = data;
6199 src = (struct jpeg_source_mgr *) cinfo->src;
6200 src->init_source = our_common_init_source;
6201 src->fill_input_buffer = our_memory_fill_input_buffer;
6202 src->skip_input_data = our_memory_skip_input_data;
6203 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6204 src->term_source = our_common_term_source;
6205 src->bytes_in_buffer = len;
6206 src->next_input_byte = data;
6210 struct jpeg_stdio_mgr
6212 struct jpeg_source_mgr mgr;
6213 boolean finished;
6214 FILE *file;
6215 JOCTET *buffer;
6219 /* Size of buffer to read JPEG from file.
6220 Not too big, as we want to use alloc_small. */
6221 #define JPEG_STDIO_BUFFER_SIZE 8192
6224 /* Fill input buffer method for JPEG data source manager. Called
6225 whenever more data is needed. The data is read from a FILE *. */
6227 static boolean
6228 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6230 struct jpeg_stdio_mgr *src;
6232 src = (struct jpeg_stdio_mgr *) cinfo->src;
6233 if (!src->finished)
6235 ptrdiff_t bytes;
6237 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6238 if (bytes > 0)
6239 src->mgr.bytes_in_buffer = bytes;
6240 else
6242 WARNMS (cinfo, JWRN_JPEG_EOF);
6243 src->finished = 1;
6244 src->buffer[0] = (JOCTET) 0xFF;
6245 src->buffer[1] = (JOCTET) JPEG_EOI;
6246 src->mgr.bytes_in_buffer = 2;
6248 src->mgr.next_input_byte = src->buffer;
6251 return 1;
6255 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6256 is the JPEG data source manager. */
6258 static void
6259 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6261 struct jpeg_stdio_mgr *src;
6262 src = (struct jpeg_stdio_mgr *) cinfo->src;
6264 while (num_bytes > 0 && !src->finished)
6266 if (num_bytes <= src->mgr.bytes_in_buffer)
6268 src->mgr.bytes_in_buffer -= num_bytes;
6269 src->mgr.next_input_byte += num_bytes;
6270 break;
6272 else
6274 num_bytes -= src->mgr.bytes_in_buffer;
6275 src->mgr.bytes_in_buffer = 0;
6276 src->mgr.next_input_byte = NULL;
6278 our_stdio_fill_input_buffer (cinfo);
6284 /* Set up the JPEG lib for reading an image from a FILE *.
6285 CINFO is the decompression info structure created for
6286 reading the image. */
6288 static void
6289 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6291 struct jpeg_stdio_mgr *src;
6293 if (cinfo->src != NULL)
6294 src = (struct jpeg_stdio_mgr *) cinfo->src;
6295 else
6297 /* First time for this JPEG object? */
6298 cinfo->src = (struct jpeg_source_mgr *)
6299 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6300 sizeof (struct jpeg_stdio_mgr));
6301 src = (struct jpeg_stdio_mgr *) cinfo->src;
6302 src->buffer = (JOCTET *)
6303 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6304 JPEG_STDIO_BUFFER_SIZE);
6307 src->file = fp;
6308 src->finished = 0;
6309 src->mgr.init_source = our_common_init_source;
6310 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6311 src->mgr.skip_input_data = our_stdio_skip_input_data;
6312 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6313 src->mgr.term_source = our_common_term_source;
6314 src->mgr.bytes_in_buffer = 0;
6315 src->mgr.next_input_byte = NULL;
6319 /* Load image IMG for use on frame F. Patterned after example.c
6320 from the JPEG lib. */
6322 static bool
6323 jpeg_load_body (struct frame *f, struct image *img,
6324 struct my_jpeg_error_mgr *mgr)
6326 Lisp_Object file, specified_file;
6327 Lisp_Object specified_data;
6328 FILE *fp = NULL;
6329 JSAMPARRAY buffer;
6330 int row_stride, x, y;
6331 XImagePtr ximg = NULL;
6332 unsigned long *colors;
6333 int width, height;
6335 /* Open the JPEG file. */
6336 specified_file = image_spec_value (img->spec, QCfile, NULL);
6337 specified_data = image_spec_value (img->spec, QCdata, NULL);
6339 if (NILP (specified_data))
6341 file = x_find_image_file (specified_file);
6342 if (!STRINGP (file))
6344 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6345 return 0;
6348 fp = fopen (SSDATA (file), "rb");
6349 if (fp == NULL)
6351 image_error ("Cannot open `%s'", file, Qnil);
6352 return 0;
6355 else if (!STRINGP (specified_data))
6357 image_error ("Invalid image data `%s'", specified_data, Qnil);
6358 return 0;
6361 IF_LINT (mgr->fp = fp);
6363 /* Customize libjpeg's error handling to call my_error_exit when an
6364 error is detected. This function will perform a longjmp. */
6365 mgr->cinfo.err = fn_jpeg_std_error (&mgr->pub);
6366 mgr->pub.error_exit = my_error_exit;
6367 if (sys_setjmp (mgr->setjmp_buffer))
6369 switch (mgr->failure_code)
6371 case MY_JPEG_ERROR_EXIT:
6373 char buf[JMSG_LENGTH_MAX];
6374 mgr->cinfo.err->format_message ((j_common_ptr) &mgr->cinfo, buf);
6375 image_error ("Error reading JPEG image `%s': %s", img->spec,
6376 build_string (buf));
6377 break;
6380 case MY_JPEG_INVALID_IMAGE_SIZE:
6381 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6382 break;
6384 case MY_JPEG_CANNOT_CREATE_X:
6385 break;
6388 /* Close the input file and destroy the JPEG object. */
6389 if (fp)
6390 fclose (fp);
6391 fn_jpeg_destroy_decompress (&mgr->cinfo);
6393 /* If we already have an XImage, free that. */
6394 x_destroy_x_image (ximg);
6396 /* Free pixmap and colors. */
6397 x_clear_image (f, img);
6398 return 0;
6401 /* Silence a bogus diagnostic; see GCC bug 54561. */
6402 IF_LINT (fp = mgr->fp);
6404 /* Create the JPEG decompression object. Let it read from fp.
6405 Read the JPEG image header. */
6406 fn_jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
6408 if (NILP (specified_data))
6409 jpeg_file_src (&mgr->cinfo, fp);
6410 else
6411 jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
6412 SBYTES (specified_data));
6414 fn_jpeg_read_header (&mgr->cinfo, 1);
6416 /* Customize decompression so that color quantization will be used.
6417 Start decompression. */
6418 mgr->cinfo.quantize_colors = 1;
6419 fn_jpeg_start_decompress (&mgr->cinfo);
6420 width = img->width = mgr->cinfo.output_width;
6421 height = img->height = mgr->cinfo.output_height;
6423 if (!check_image_size (f, width, height))
6425 mgr->failure_code = MY_JPEG_INVALID_IMAGE_SIZE;
6426 sys_longjmp (mgr->setjmp_buffer, 1);
6429 /* Create X image and pixmap. */
6430 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6432 mgr->failure_code = MY_JPEG_CANNOT_CREATE_X;
6433 sys_longjmp (mgr->setjmp_buffer, 1);
6436 /* Allocate colors. When color quantization is used,
6437 mgr->cinfo.actual_number_of_colors has been set with the number of
6438 colors generated, and mgr->cinfo.colormap is a two-dimensional array
6439 of color indices in the range 0..mgr->cinfo.actual_number_of_colors.
6440 No more than 255 colors will be generated. */
6442 int i, ir, ig, ib;
6444 if (mgr->cinfo.out_color_components > 2)
6445 ir = 0, ig = 1, ib = 2;
6446 else if (mgr->cinfo.out_color_components > 1)
6447 ir = 0, ig = 1, ib = 0;
6448 else
6449 ir = 0, ig = 0, ib = 0;
6451 /* Use the color table mechanism because it handles colors that
6452 cannot be allocated nicely. Such colors will be replaced with
6453 a default color, and we don't have to care about which colors
6454 can be freed safely, and which can't. */
6455 init_color_table ();
6456 colors = alloca (mgr->cinfo.actual_number_of_colors * sizeof *colors);
6458 for (i = 0; i < mgr->cinfo.actual_number_of_colors; ++i)
6460 /* Multiply RGB values with 255 because X expects RGB values
6461 in the range 0..0xffff. */
6462 int r = mgr->cinfo.colormap[ir][i] << 8;
6463 int g = mgr->cinfo.colormap[ig][i] << 8;
6464 int b = mgr->cinfo.colormap[ib][i] << 8;
6465 colors[i] = lookup_rgb_color (f, r, g, b);
6468 #ifdef COLOR_TABLE_SUPPORT
6469 /* Remember those colors actually allocated. */
6470 img->colors = colors_in_color_table (&img->ncolors);
6471 free_color_table ();
6472 #endif /* COLOR_TABLE_SUPPORT */
6475 /* Read pixels. */
6476 row_stride = width * mgr->cinfo.output_components;
6477 buffer = mgr->cinfo.mem->alloc_sarray ((j_common_ptr) &mgr->cinfo,
6478 JPOOL_IMAGE, row_stride, 1);
6479 for (y = 0; y < height; ++y)
6481 fn_jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
6482 for (x = 0; x < mgr->cinfo.output_width; ++x)
6483 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6486 /* Clean up. */
6487 fn_jpeg_finish_decompress (&mgr->cinfo);
6488 fn_jpeg_destroy_decompress (&mgr->cinfo);
6489 if (fp)
6490 fclose (fp);
6492 /* Maybe fill in the background field while we have ximg handy. */
6493 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6494 /* Casting avoids a GCC warning. */
6495 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6497 /* Put the image into the pixmap. */
6498 x_put_x_image (f, ximg, img->pixmap, width, height);
6499 x_destroy_x_image (ximg);
6500 return 1;
6503 static bool
6504 jpeg_load (struct frame *f, struct image *img)
6506 struct my_jpeg_error_mgr mgr;
6507 return jpeg_load_body (f, img, &mgr);
6510 #else /* HAVE_JPEG */
6512 #ifdef HAVE_NS
6513 static bool
6514 jpeg_load (struct frame *f, struct image *img)
6516 return ns_load_image (f, img,
6517 image_spec_value (img->spec, QCfile, NULL),
6518 image_spec_value (img->spec, QCdata, NULL));
6520 #endif /* HAVE_NS */
6522 #endif /* !HAVE_JPEG */
6526 /***********************************************************************
6527 TIFF
6528 ***********************************************************************/
6530 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6532 static bool tiff_image_p (Lisp_Object object);
6533 static bool tiff_load (struct frame *f, struct image *img);
6535 /* The symbol `tiff' identifying images of this type. */
6537 static Lisp_Object Qtiff;
6539 /* Indices of image specification fields in tiff_format, below. */
6541 enum tiff_keyword_index
6543 TIFF_TYPE,
6544 TIFF_DATA,
6545 TIFF_FILE,
6546 TIFF_ASCENT,
6547 TIFF_MARGIN,
6548 TIFF_RELIEF,
6549 TIFF_ALGORITHM,
6550 TIFF_HEURISTIC_MASK,
6551 TIFF_MASK,
6552 TIFF_BACKGROUND,
6553 TIFF_INDEX,
6554 TIFF_LAST
6557 /* Vector of image_keyword structures describing the format
6558 of valid user-defined image specifications. */
6560 static const struct image_keyword tiff_format[TIFF_LAST] =
6562 {":type", IMAGE_SYMBOL_VALUE, 1},
6563 {":data", IMAGE_STRING_VALUE, 0},
6564 {":file", IMAGE_STRING_VALUE, 0},
6565 {":ascent", IMAGE_ASCENT_VALUE, 0},
6566 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6567 {":relief", IMAGE_INTEGER_VALUE, 0},
6568 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6569 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6570 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6571 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6572 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6575 #if defined HAVE_NTGUI && defined WINDOWSNT
6576 static bool init_tiff_functions (void);
6577 #else
6578 #define init_tiff_functions NULL
6579 #endif
6581 /* Structure describing the image type `tiff'. */
6583 static struct image_type tiff_type =
6585 &Qtiff,
6586 tiff_image_p,
6587 tiff_load,
6588 x_clear_image,
6589 init_tiff_functions,
6590 NULL
6593 /* Return true if OBJECT is a valid TIFF image specification. */
6595 static bool
6596 tiff_image_p (Lisp_Object object)
6598 struct image_keyword fmt[TIFF_LAST];
6599 memcpy (fmt, tiff_format, sizeof fmt);
6601 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6602 return 0;
6604 /* Must specify either the :data or :file keyword. */
6605 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6608 #endif /* HAVE_TIFF || HAVE_NS */
6610 #ifdef HAVE_TIFF
6612 #include <tiffio.h>
6614 #ifdef WINDOWSNT
6616 /* TIFF library details. */
6617 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6618 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6619 DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6620 DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
6621 TIFFReadWriteProc, TIFFReadWriteProc,
6622 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6623 TIFFMapFileProc, TIFFUnmapFileProc));
6624 DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6625 DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6626 DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6627 DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6629 static bool
6630 init_tiff_functions (void)
6632 HMODULE library;
6634 if (!(library = w32_delayed_load (Qtiff)))
6635 return 0;
6637 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6638 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6639 LOAD_IMGLIB_FN (library, TIFFOpen);
6640 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6641 LOAD_IMGLIB_FN (library, TIFFGetField);
6642 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6643 LOAD_IMGLIB_FN (library, TIFFClose);
6644 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6645 return 1;
6648 #else
6650 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6651 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6652 #define fn_TIFFOpen TIFFOpen
6653 #define fn_TIFFClientOpen TIFFClientOpen
6654 #define fn_TIFFGetField TIFFGetField
6655 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6656 #define fn_TIFFClose TIFFClose
6657 #define fn_TIFFSetDirectory TIFFSetDirectory
6658 #endif /* WINDOWSNT */
6661 /* Reading from a memory buffer for TIFF images Based on the PNG
6662 memory source, but we have to provide a lot of extra functions.
6663 Blah.
6665 We really only need to implement read and seek, but I am not
6666 convinced that the TIFF library is smart enough not to destroy
6667 itself if we only hand it the function pointers we need to
6668 override. */
6670 typedef struct
6672 unsigned char *bytes;
6673 ptrdiff_t len;
6674 ptrdiff_t index;
6676 tiff_memory_source;
6678 static tsize_t
6679 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6681 tiff_memory_source *src = (tiff_memory_source *) data;
6683 size = min (size, src->len - src->index);
6684 memcpy (buf, src->bytes + src->index, size);
6685 src->index += size;
6686 return size;
6689 static tsize_t
6690 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6692 return -1;
6695 static toff_t
6696 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6698 tiff_memory_source *src = (tiff_memory_source *) data;
6699 ptrdiff_t idx;
6701 switch (whence)
6703 case SEEK_SET: /* Go from beginning of source. */
6704 idx = off;
6705 break;
6707 case SEEK_END: /* Go from end of source. */
6708 idx = src->len + off;
6709 break;
6711 case SEEK_CUR: /* Go from current position. */
6712 idx = src->index + off;
6713 break;
6715 default: /* Invalid `whence'. */
6716 return -1;
6719 if (idx > src->len || idx < 0)
6720 return -1;
6722 src->index = idx;
6723 return src->index;
6726 static int
6727 tiff_close_memory (thandle_t data)
6729 /* NOOP */
6730 return 0;
6733 static int
6734 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6736 /* It is already _IN_ memory. */
6737 return 0;
6740 static void
6741 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6743 /* We don't need to do this. */
6746 static toff_t
6747 tiff_size_of_memory (thandle_t data)
6749 return ((tiff_memory_source *) data)->len;
6752 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6753 compiler error compiling tiff_handler, see Bugzilla bug #17406
6754 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6755 this function as external works around that problem. */
6756 #if defined (__MINGW32__) && __GNUC__ == 3
6757 # define MINGW_STATIC
6758 #else
6759 # define MINGW_STATIC static
6760 #endif
6762 MINGW_STATIC void
6763 tiff_handler (const char *, const char *, const char *, va_list)
6764 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6765 MINGW_STATIC void
6766 tiff_handler (const char *log_format, const char *title,
6767 const char *format, va_list ap)
6769 /* doprnt is not suitable here, as TIFF handlers are called from
6770 libtiff and are passed arbitrary printf directives. Instead, use
6771 vsnprintf, taking care to be portable to nonstandard environments
6772 where vsnprintf returns -1 on buffer overflow. Since it's just a
6773 log entry, it's OK to truncate it. */
6774 char buf[4000];
6775 int len = vsnprintf (buf, sizeof buf, format, ap);
6776 add_to_log (log_format, build_string (title),
6777 make_string (buf, max (0, min (len, sizeof buf - 1))));
6779 #undef MINGW_STATIC
6781 static void tiff_error_handler (const char *, const char *, va_list)
6782 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6783 static void
6784 tiff_error_handler (const char *title, const char *format, va_list ap)
6786 tiff_handler ("TIFF error: %s %s", title, format, ap);
6790 static void tiff_warning_handler (const char *, const char *, va_list)
6791 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6792 static void
6793 tiff_warning_handler (const char *title, const char *format, va_list ap)
6795 tiff_handler ("TIFF warning: %s %s", title, format, ap);
6799 /* Load TIFF image IMG for use on frame F. Value is true if
6800 successful. */
6802 static bool
6803 tiff_load (struct frame *f, struct image *img)
6805 Lisp_Object file, specified_file;
6806 Lisp_Object specified_data;
6807 TIFF *tiff;
6808 int width, height, x, y, count;
6809 uint32 *buf;
6810 int rc;
6811 XImagePtr ximg;
6812 tiff_memory_source memsrc;
6813 Lisp_Object image;
6815 specified_file = image_spec_value (img->spec, QCfile, NULL);
6816 specified_data = image_spec_value (img->spec, QCdata, NULL);
6818 fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6819 fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
6821 if (NILP (specified_data))
6823 /* Read from a file */
6824 file = x_find_image_file (specified_file);
6825 if (!STRINGP (file))
6827 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6828 return 0;
6831 /* Try to open the image file. */
6832 tiff = fn_TIFFOpen (SSDATA (file), "r");
6833 if (tiff == NULL)
6835 image_error ("Cannot open `%s'", file, Qnil);
6836 return 0;
6839 else
6841 if (!STRINGP (specified_data))
6843 image_error ("Invalid image data `%s'", specified_data, Qnil);
6844 return 0;
6847 /* Memory source! */
6848 memsrc.bytes = SDATA (specified_data);
6849 memsrc.len = SBYTES (specified_data);
6850 memsrc.index = 0;
6852 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
6853 tiff_read_from_memory,
6854 tiff_write_from_memory,
6855 tiff_seek_in_memory,
6856 tiff_close_memory,
6857 tiff_size_of_memory,
6858 tiff_mmap_memory,
6859 tiff_unmap_memory);
6861 if (!tiff)
6863 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6864 return 0;
6868 image = image_spec_value (img->spec, QCindex, NULL);
6869 if (INTEGERP (image))
6871 EMACS_INT ino = XFASTINT (image);
6872 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
6873 && fn_TIFFSetDirectory (tiff, ino)))
6875 image_error ("Invalid image number `%s' in image `%s'",
6876 image, img->spec);
6877 fn_TIFFClose (tiff);
6878 return 0;
6882 /* Get width and height of the image, and allocate a raster buffer
6883 of width x height 32-bit values. */
6884 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6885 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6887 if (!check_image_size (f, width, height))
6889 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6890 fn_TIFFClose (tiff);
6891 return 0;
6894 /* Create the X image and pixmap. */
6895 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
6896 && x_create_x_image_and_pixmap (f, width, height, 0,
6897 &ximg, &img->pixmap)))
6899 fn_TIFFClose (tiff);
6900 return 0;
6903 buf = xmalloc (sizeof *buf * width * height);
6905 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
6907 /* Count the number of images in the file. */
6908 for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
6909 continue;
6911 if (count > 1)
6912 img->lisp_data = Fcons (Qcount,
6913 Fcons (make_number (count),
6914 img->lisp_data));
6916 fn_TIFFClose (tiff);
6917 if (!rc)
6919 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6920 xfree (buf);
6921 return 0;
6924 /* Initialize the color table. */
6925 init_color_table ();
6927 /* Process the pixel raster. Origin is in the lower-left corner. */
6928 for (y = 0; y < height; ++y)
6930 uint32 *row = buf + y * width;
6932 for (x = 0; x < width; ++x)
6934 uint32 abgr = row[x];
6935 int r = TIFFGetR (abgr) << 8;
6936 int g = TIFFGetG (abgr) << 8;
6937 int b = TIFFGetB (abgr) << 8;
6938 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6942 #ifdef COLOR_TABLE_SUPPORT
6943 /* Remember the colors allocated for the image. Free the color table. */
6944 img->colors = colors_in_color_table (&img->ncolors);
6945 free_color_table ();
6946 #endif /* COLOR_TABLE_SUPPORT */
6948 img->width = width;
6949 img->height = height;
6951 /* Maybe fill in the background field while we have ximg handy. */
6952 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6953 /* Casting avoids a GCC warning on W32. */
6954 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6956 /* Put the image into the pixmap, then free the X image and its buffer. */
6957 x_put_x_image (f, ximg, img->pixmap, width, height);
6958 x_destroy_x_image (ximg);
6959 xfree (buf);
6961 return 1;
6964 #else /* HAVE_TIFF */
6966 #ifdef HAVE_NS
6967 static bool
6968 tiff_load (struct frame *f, struct image *img)
6970 return ns_load_image (f, img,
6971 image_spec_value (img->spec, QCfile, NULL),
6972 image_spec_value (img->spec, QCdata, NULL));
6974 #endif /* HAVE_NS */
6976 #endif /* !HAVE_TIFF */
6980 /***********************************************************************
6982 ***********************************************************************/
6984 #if defined (HAVE_GIF) || defined (HAVE_NS)
6986 static bool gif_image_p (Lisp_Object object);
6987 static bool gif_load (struct frame *f, struct image *img);
6988 static void gif_clear_image (struct frame *f, struct image *img);
6990 /* The symbol `gif' identifying images of this type. */
6992 static Lisp_Object Qgif;
6994 /* Indices of image specification fields in gif_format, below. */
6996 enum gif_keyword_index
6998 GIF_TYPE,
6999 GIF_DATA,
7000 GIF_FILE,
7001 GIF_ASCENT,
7002 GIF_MARGIN,
7003 GIF_RELIEF,
7004 GIF_ALGORITHM,
7005 GIF_HEURISTIC_MASK,
7006 GIF_MASK,
7007 GIF_IMAGE,
7008 GIF_BACKGROUND,
7009 GIF_LAST
7012 /* Vector of image_keyword structures describing the format
7013 of valid user-defined image specifications. */
7015 static const struct image_keyword gif_format[GIF_LAST] =
7017 {":type", IMAGE_SYMBOL_VALUE, 1},
7018 {":data", IMAGE_STRING_VALUE, 0},
7019 {":file", IMAGE_STRING_VALUE, 0},
7020 {":ascent", IMAGE_ASCENT_VALUE, 0},
7021 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7022 {":relief", IMAGE_INTEGER_VALUE, 0},
7023 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7024 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7025 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7026 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7027 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7030 #if defined HAVE_NTGUI && defined WINDOWSNT
7031 static bool init_gif_functions (void);
7032 #else
7033 #define init_gif_functions NULL
7034 #endif
7036 /* Structure describing the image type `gif'. */
7038 static struct image_type gif_type =
7040 &Qgif,
7041 gif_image_p,
7042 gif_load,
7043 gif_clear_image,
7044 init_gif_functions,
7045 NULL
7048 /* Free X resources of GIF image IMG which is used on frame F. */
7050 static void
7051 gif_clear_image (struct frame *f, struct image *img)
7053 img->lisp_data = Qnil;
7054 x_clear_image (f, img);
7057 /* Return true if OBJECT is a valid GIF image specification. */
7059 static bool
7060 gif_image_p (Lisp_Object object)
7062 struct image_keyword fmt[GIF_LAST];
7063 memcpy (fmt, gif_format, sizeof fmt);
7065 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7066 return 0;
7068 /* Must specify either the :data or :file keyword. */
7069 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7072 #endif /* HAVE_GIF */
7074 #ifdef HAVE_GIF
7076 #if defined (HAVE_NTGUI)
7077 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7078 Undefine before redefining to avoid a preprocessor warning. */
7079 #ifdef DrawText
7080 #undef DrawText
7081 #endif
7082 /* avoid conflict with QuickdrawText.h */
7083 #define DrawText gif_DrawText
7084 #include <gif_lib.h>
7085 #undef DrawText
7087 #else /* HAVE_NTGUI */
7089 #include <gif_lib.h>
7091 #endif /* HAVE_NTGUI */
7094 #ifdef WINDOWSNT
7096 /* GIF library details. */
7097 DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7098 DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7099 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7100 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
7102 static bool
7103 init_gif_functions (void)
7105 HMODULE library;
7107 if (!(library = w32_delayed_load (Qgif)))
7108 return 0;
7110 LOAD_IMGLIB_FN (library, DGifCloseFile);
7111 LOAD_IMGLIB_FN (library, DGifSlurp);
7112 LOAD_IMGLIB_FN (library, DGifOpen);
7113 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7114 return 1;
7117 #else
7119 #define fn_DGifCloseFile DGifCloseFile
7120 #define fn_DGifSlurp DGifSlurp
7121 #define fn_DGifOpen DGifOpen
7122 #define fn_DGifOpenFileName DGifOpenFileName
7124 #endif /* WINDOWSNT */
7126 /* Reading a GIF image from memory
7127 Based on the PNG memory stuff to a certain extent. */
7129 typedef struct
7131 unsigned char *bytes;
7132 ptrdiff_t len;
7133 ptrdiff_t index;
7135 gif_memory_source;
7137 /* Make the current memory source available to gif_read_from_memory.
7138 It's done this way because not all versions of libungif support
7139 a UserData field in the GifFileType structure. */
7140 static gif_memory_source *current_gif_memory_src;
7142 static int
7143 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7145 gif_memory_source *src = current_gif_memory_src;
7147 if (len > src->len - src->index)
7148 return -1;
7150 memcpy (buf, src->bytes + src->index, len);
7151 src->index += len;
7152 return len;
7156 /* Load GIF image IMG for use on frame F. Value is true if
7157 successful. */
7159 static const int interlace_start[] = {0, 4, 2, 1};
7160 static const int interlace_increment[] = {8, 8, 4, 2};
7162 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7164 static bool
7165 gif_load (struct frame *f, struct image *img)
7167 Lisp_Object file;
7168 int rc, width, height, x, y, i, j;
7169 XImagePtr ximg;
7170 ColorMapObject *gif_color_map;
7171 unsigned long pixel_colors[256];
7172 GifFileType *gif;
7173 gif_memory_source memsrc;
7174 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7175 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7176 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7177 unsigned long bgcolor = 0;
7178 EMACS_INT idx;
7180 if (NILP (specified_data))
7182 file = x_find_image_file (specified_file);
7183 if (!STRINGP (file))
7185 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7186 return 0;
7189 /* Open the GIF file. */
7190 gif = fn_DGifOpenFileName (SSDATA (file));
7191 if (gif == NULL)
7193 image_error ("Cannot open `%s'", file, Qnil);
7194 return 0;
7197 else
7199 if (!STRINGP (specified_data))
7201 image_error ("Invalid image data `%s'", specified_data, Qnil);
7202 return 0;
7205 /* Read from memory! */
7206 current_gif_memory_src = &memsrc;
7207 memsrc.bytes = SDATA (specified_data);
7208 memsrc.len = SBYTES (specified_data);
7209 memsrc.index = 0;
7211 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
7212 if (!gif)
7214 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7215 return 0;
7219 /* Before reading entire contents, check the declared image size. */
7220 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7222 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7223 fn_DGifCloseFile (gif);
7224 return 0;
7227 /* Read entire contents. */
7228 rc = fn_DGifSlurp (gif);
7229 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7231 image_error ("Error reading `%s'", img->spec, Qnil);
7232 fn_DGifCloseFile (gif);
7233 return 0;
7236 /* Which sub-image are we to display? */
7238 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7239 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7240 if (idx < 0 || idx >= gif->ImageCount)
7242 image_error ("Invalid image number `%s' in image `%s'",
7243 image_number, img->spec);
7244 fn_DGifCloseFile (gif);
7245 return 0;
7249 width = img->width = gif->SWidth;
7250 height = img->height = gif->SHeight;
7252 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7253 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7254 img->corners[BOT_CORNER]
7255 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7256 img->corners[RIGHT_CORNER]
7257 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7259 if (!check_image_size (f, width, height))
7261 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7262 fn_DGifCloseFile (gif);
7263 return 0;
7266 /* Check that the selected subimages fit. It's not clear whether
7267 the GIF spec requires this, but Emacs can crash if they don't fit. */
7268 for (j = 0; j <= idx; ++j)
7270 struct SavedImage *subimage = gif->SavedImages + j;
7271 int subimg_width = subimage->ImageDesc.Width;
7272 int subimg_height = subimage->ImageDesc.Height;
7273 int subimg_top = subimage->ImageDesc.Top;
7274 int subimg_left = subimage->ImageDesc.Left;
7275 if (! (0 <= subimg_width && 0 <= subimg_height
7276 && 0 <= subimg_top && subimg_top <= height - subimg_height
7277 && 0 <= subimg_left && subimg_left <= width - subimg_width))
7279 image_error ("Subimage does not fit in image", Qnil, Qnil);
7280 fn_DGifCloseFile (gif);
7281 return 0;
7285 /* Create the X image and pixmap. */
7286 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7288 fn_DGifCloseFile (gif);
7289 return 0;
7292 /* Clear the part of the screen image not covered by the image.
7293 Full animated GIF support requires more here (see the gif89 spec,
7294 disposal methods). Let's simply assume that the part not covered
7295 by a sub-image is in the frame's background color. */
7296 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7297 for (x = 0; x < width; ++x)
7298 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7300 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7301 for (x = 0; x < width; ++x)
7302 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7304 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7306 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7307 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7308 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7309 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7312 /* Read the GIF image into the X image. */
7314 /* FIXME: With the current implementation, loading an animated gif
7315 is quadratic in the number of animation frames, since each frame
7316 is a separate struct image. We must provide a way for a single
7317 gif_load call to construct and save all animation frames. */
7319 init_color_table ();
7320 if (STRINGP (specified_bg))
7321 bgcolor = x_alloc_image_color (f, img, specified_bg,
7322 FRAME_BACKGROUND_PIXEL (f));
7323 for (j = 0; j <= idx; ++j)
7325 /* We use a local variable `raster' here because RasterBits is a
7326 char *, which invites problems with bytes >= 0x80. */
7327 struct SavedImage *subimage = gif->SavedImages + j;
7328 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7329 int transparency_color_index = -1;
7330 int disposal = 0;
7331 int subimg_width = subimage->ImageDesc.Width;
7332 int subimg_height = subimage->ImageDesc.Height;
7333 int subimg_top = subimage->ImageDesc.Top;
7334 int subimg_left = subimage->ImageDesc.Left;
7336 /* Find the Graphic Control Extension block for this sub-image.
7337 Extract the disposal method and transparency color. */
7338 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7340 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7342 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7343 && extblock->ByteCount == 4
7344 && extblock->Bytes[0] & 1)
7346 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7347 to background". Treat any other value like 2. */
7348 disposal = (extblock->Bytes[0] >> 2) & 7;
7349 transparency_color_index = (unsigned char) extblock->Bytes[3];
7350 break;
7354 /* We can't "keep in place" the first subimage. */
7355 if (j == 0)
7356 disposal = 2;
7358 /* For disposal == 0, the spec says "No disposal specified. The
7359 decoder is not required to take any action." In practice, it
7360 seems we need to treat this like "keep in place", see e.g.
7361 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7362 if (disposal == 0)
7363 disposal = 1;
7365 /* Allocate subimage colors. */
7366 memset (pixel_colors, 0, sizeof pixel_colors);
7367 gif_color_map = subimage->ImageDesc.ColorMap;
7368 if (!gif_color_map)
7369 gif_color_map = gif->SColorMap;
7371 if (gif_color_map)
7372 for (i = 0; i < gif_color_map->ColorCount; ++i)
7374 if (transparency_color_index == i)
7375 pixel_colors[i] = STRINGP (specified_bg)
7376 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7377 else
7379 int r = gif_color_map->Colors[i].Red << 8;
7380 int g = gif_color_map->Colors[i].Green << 8;
7381 int b = gif_color_map->Colors[i].Blue << 8;
7382 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7386 /* Apply the pixel values. */
7387 if (gif->SavedImages[j].ImageDesc.Interlace)
7389 int row, pass;
7391 for (y = 0, row = interlace_start[0], pass = 0;
7392 y < subimg_height;
7393 y++, row += interlace_increment[pass])
7395 while (subimg_height <= row)
7397 lint_assume (pass < 3);
7398 row = interlace_start[++pass];
7401 for (x = 0; x < subimg_width; x++)
7403 int c = raster[y * subimg_width + x];
7404 if (transparency_color_index != c || disposal != 1)
7405 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7406 pixel_colors[c]);
7410 else
7412 for (y = 0; y < subimg_height; ++y)
7413 for (x = 0; x < subimg_width; ++x)
7415 int c = raster[y * subimg_width + x];
7416 if (transparency_color_index != c || disposal != 1)
7417 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7418 pixel_colors[c]);
7423 #ifdef COLOR_TABLE_SUPPORT
7424 img->colors = colors_in_color_table (&img->ncolors);
7425 free_color_table ();
7426 #endif /* COLOR_TABLE_SUPPORT */
7428 /* Save GIF image extension data for `image-metadata'.
7429 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7430 img->lisp_data = Qnil;
7431 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7433 int delay = 0;
7434 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7435 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7436 /* Append (... FUNCTION "BYTES") */
7438 img->lisp_data
7439 = Fcons (make_number (ext->Function),
7440 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7441 img->lisp_data));
7442 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7443 && ext->ByteCount == 4)
7445 delay = ext->Bytes[2] << CHAR_BIT;
7446 delay |= ext->Bytes[1];
7449 img->lisp_data = Fcons (Qextension_data,
7450 Fcons (img->lisp_data, Qnil));
7451 if (delay)
7452 img->lisp_data
7453 = Fcons (Qdelay,
7454 Fcons (make_float (delay / 100.0),
7455 img->lisp_data));
7458 if (gif->ImageCount > 1)
7459 img->lisp_data = Fcons (Qcount,
7460 Fcons (make_number (gif->ImageCount),
7461 img->lisp_data));
7463 fn_DGifCloseFile (gif);
7465 /* Maybe fill in the background field while we have ximg handy. */
7466 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7467 /* Casting avoids a GCC warning. */
7468 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7470 /* Put the image into the pixmap, then free the X image and its buffer. */
7471 x_put_x_image (f, ximg, img->pixmap, width, height);
7472 x_destroy_x_image (ximg);
7474 return 1;
7477 #else /* !HAVE_GIF */
7479 #ifdef HAVE_NS
7480 static bool
7481 gif_load (struct frame *f, struct image *img)
7483 return ns_load_image (f, img,
7484 image_spec_value (img->spec, QCfile, NULL),
7485 image_spec_value (img->spec, QCdata, NULL));
7487 #endif /* HAVE_NS */
7489 #endif /* HAVE_GIF */
7492 /***********************************************************************
7493 ImageMagick
7494 ***********************************************************************/
7495 #if defined (HAVE_IMAGEMAGICK)
7497 static Lisp_Object Qimagemagick;
7499 static bool imagemagick_image_p (Lisp_Object);
7500 static bool imagemagick_load (struct frame *, struct image *);
7501 static void imagemagick_clear_image (struct frame *, struct image *);
7503 /* Indices of image specification fields in imagemagick_format. */
7505 enum imagemagick_keyword_index
7507 IMAGEMAGICK_TYPE,
7508 IMAGEMAGICK_DATA,
7509 IMAGEMAGICK_FILE,
7510 IMAGEMAGICK_ASCENT,
7511 IMAGEMAGICK_MARGIN,
7512 IMAGEMAGICK_RELIEF,
7513 IMAGEMAGICK_ALGORITHM,
7514 IMAGEMAGICK_HEURISTIC_MASK,
7515 IMAGEMAGICK_MASK,
7516 IMAGEMAGICK_BACKGROUND,
7517 IMAGEMAGICK_HEIGHT,
7518 IMAGEMAGICK_WIDTH,
7519 IMAGEMAGICK_ROTATION,
7520 IMAGEMAGICK_CROP,
7521 IMAGEMAGICK_LAST
7524 /* Vector of image_keyword structures describing the format
7525 of valid user-defined image specifications. */
7527 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7529 {":type", IMAGE_SYMBOL_VALUE, 1},
7530 {":data", IMAGE_STRING_VALUE, 0},
7531 {":file", IMAGE_STRING_VALUE, 0},
7532 {":ascent", IMAGE_ASCENT_VALUE, 0},
7533 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7534 {":relief", IMAGE_INTEGER_VALUE, 0},
7535 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7536 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7537 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7538 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7539 {":height", IMAGE_INTEGER_VALUE, 0},
7540 {":width", IMAGE_INTEGER_VALUE, 0},
7541 {":rotation", IMAGE_NUMBER_VALUE, 0},
7542 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7545 #if defined HAVE_NTGUI && defined WINDOWSNT
7546 static bool init_imagemagick_functions (void);
7547 #else
7548 #define init_imagemagick_functions NULL
7549 #endif
7551 /* Structure describing the image type for any image handled via
7552 ImageMagick. */
7554 static struct image_type imagemagick_type =
7556 &Qimagemagick,
7557 imagemagick_image_p,
7558 imagemagick_load,
7559 imagemagick_clear_image,
7560 init_imagemagick_functions,
7561 NULL
7564 /* Free X resources of imagemagick image IMG which is used on frame F. */
7566 static void
7567 imagemagick_clear_image (struct frame *f,
7568 struct image *img)
7570 x_clear_image (f, img);
7573 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7574 this by calling parse_image_spec and supplying the keywords that
7575 identify the IMAGEMAGICK format. */
7577 static bool
7578 imagemagick_image_p (Lisp_Object object)
7580 struct image_keyword fmt[IMAGEMAGICK_LAST];
7581 memcpy (fmt, imagemagick_format, sizeof fmt);
7583 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7584 return 0;
7586 /* Must specify either the :data or :file keyword. */
7587 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7590 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7591 Therefore rename the function so it doesn't collide with ImageMagick. */
7592 #define DrawRectangle DrawRectangleGif
7593 #include <wand/MagickWand.h>
7595 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7596 Emacs seems to work fine with the hidden version, so unhide it. */
7597 #include <magick/version.h>
7598 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7599 extern WandExport void PixelGetMagickColor (const PixelWand *,
7600 MagickPixelPacket *);
7601 #endif
7603 /* Log ImageMagick error message.
7604 Useful when a ImageMagick function returns the status `MagickFalse'. */
7606 static void
7607 imagemagick_error (MagickWand *wand)
7609 char *description;
7610 ExceptionType severity;
7612 description = MagickGetException (wand, &severity);
7613 image_error ("ImageMagick error: %s",
7614 build_string (description),
7615 Qnil);
7616 description = (char *) MagickRelinquishMemory (description);
7619 /* Helper function for imagemagick_load, which does the actual loading
7620 given contents and size, apart from frame and image structures,
7621 passed from imagemagick_load. Uses librimagemagick to do most of
7622 the image processing.
7624 F is a pointer to the Emacs frame; IMG to the image structure to
7625 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
7626 be parsed; SIZE is the number of bytes of data; and FILENAME is
7627 either the file name or the image data.
7629 Return true if successful. */
7631 static bool
7632 imagemagick_load_image (struct frame *f, struct image *img,
7633 unsigned char *contents, unsigned int size,
7634 char *filename)
7636 size_t width, height;
7637 MagickBooleanType status;
7638 XImagePtr ximg;
7639 int x, y;
7640 MagickWand *image_wand;
7641 MagickWand *ping_wand;
7642 PixelIterator *iterator;
7643 PixelWand **pixels, *bg_wand = NULL;
7644 MagickPixelPacket pixel;
7645 Lisp_Object image;
7646 Lisp_Object value;
7647 Lisp_Object crop;
7648 EMACS_INT ino;
7649 int desired_width, desired_height;
7650 double rotation;
7651 int pixelwidth;
7653 /* Handle image index for image types who can contain more than one image.
7654 Interface :index is same as for GIF. First we "ping" the image to see how
7655 many sub-images it contains. Pinging is faster than loading the image to
7656 find out things about it. */
7658 /* Initialize the imagemagick environment. */
7659 MagickWandGenesis ();
7660 image = image_spec_value (img->spec, QCindex, NULL);
7661 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7662 ping_wand = NewMagickWand ();
7663 /* MagickSetResolution (ping_wand, 2, 2); (Bug#10112) */
7665 status = filename
7666 ? MagickPingImage (ping_wand, filename)
7667 : MagickPingImageBlob (ping_wand, contents, size);
7669 if (status == MagickFalse)
7671 imagemagick_error (ping_wand);
7672 DestroyMagickWand (ping_wand);
7673 return 0;
7676 if (ino < 0 || ino >= MagickGetNumberImages (ping_wand))
7678 image_error ("Invalid image number `%s' in image `%s'",
7679 image, img->spec);
7680 DestroyMagickWand (ping_wand);
7681 return 0;
7684 if (MagickGetNumberImages (ping_wand) > 1)
7685 img->lisp_data =
7686 Fcons (Qcount,
7687 Fcons (make_number (MagickGetNumberImages (ping_wand)),
7688 img->lisp_data));
7690 DestroyMagickWand (ping_wand);
7692 /* Now we know how many images are inside the file. If it's not a
7693 bundle, the number is one. Load the image data. */
7695 image_wand = NewMagickWand ();
7697 if ((filename
7698 ? MagickReadImage (image_wand, filename)
7699 : MagickReadImageBlob (image_wand, contents, size))
7700 == MagickFalse)
7702 imagemagick_error (image_wand);
7703 goto imagemagick_error;
7706 /* Retrieve the frame's background color, for use later. */
7708 XColor bgcolor;
7709 Lisp_Object specified_bg;
7711 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7712 if (!STRINGP (specified_bg)
7713 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
7715 #ifndef HAVE_NS
7716 bgcolor.pixel = FRAME_BACKGROUND_PIXEL (f);
7717 x_query_color (f, &bgcolor);
7718 #else
7719 ns_query_color (FRAME_BACKGROUND_COLOR (f), &bgcolor, 1);
7720 #endif
7723 bg_wand = NewPixelWand ();
7724 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
7725 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
7726 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
7729 /* If width and/or height is set in the display spec assume we want
7730 to scale to those values. If either h or w is unspecified, the
7731 unspecified should be calculated from the specified to preserve
7732 aspect ratio. */
7733 value = image_spec_value (img->spec, QCwidth, NULL);
7734 desired_width = (INTEGERP (value) ? XFASTINT (value) : -1);
7735 value = image_spec_value (img->spec, QCheight, NULL);
7736 desired_height = (INTEGERP (value) ? XFASTINT (value) : -1);
7738 height = MagickGetImageHeight (image_wand);
7739 width = MagickGetImageWidth (image_wand);
7741 if (desired_width != -1 && desired_height == -1)
7742 /* w known, calculate h. */
7743 desired_height = (double) desired_width / width * height;
7744 if (desired_width == -1 && desired_height != -1)
7745 /* h known, calculate w. */
7746 desired_width = (double) desired_height / height * width;
7747 if (desired_width != -1 && desired_height != -1)
7749 status = MagickScaleImage (image_wand, desired_width, desired_height);
7750 if (status == MagickFalse)
7752 image_error ("Imagemagick scale failed", Qnil, Qnil);
7753 imagemagick_error (image_wand);
7754 goto imagemagick_error;
7758 /* crop behaves similar to image slicing in Emacs but is more memory
7759 efficient. */
7760 crop = image_spec_value (img->spec, QCcrop, NULL);
7762 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7764 /* After some testing, it seems MagickCropImage is the fastest crop
7765 function in ImageMagick. This crop function seems to do less copying
7766 than the alternatives, but it still reads the entire image into memory
7767 before cropping, which is apparently difficult to avoid when using
7768 imagemagick. */
7769 size_t crop_width = XINT (XCAR (crop));
7770 crop = XCDR (crop);
7771 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7773 size_t crop_height = XINT (XCAR (crop));
7774 crop = XCDR (crop);
7775 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7777 ssize_t crop_x = XINT (XCAR (crop));
7778 crop = XCDR (crop);
7779 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7781 ssize_t crop_y = XINT (XCAR (crop));
7782 MagickCropImage (image_wand, crop_width, crop_height,
7783 crop_x, crop_y);
7789 /* Furthermore :rotation. we need background color and angle for
7790 rotation. */
7792 TODO background handling for rotation specified_bg =
7793 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
7794 (specified_bg). */
7795 value = image_spec_value (img->spec, QCrotation, NULL);
7796 if (FLOATP (value))
7798 rotation = extract_float (value);
7799 status = MagickRotateImage (image_wand, bg_wand, rotation);
7800 if (status == MagickFalse)
7802 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
7803 imagemagick_error (image_wand);
7804 goto imagemagick_error;
7808 /* Set the canvas background color to the frame or specified
7809 background, and flatten the image. Note: as of ImageMagick
7810 6.6.0, SVG image transparency is not handled properly
7811 (e.g. etc/images/splash.svg shows a white background always). */
7813 MagickWand *new_wand;
7814 MagickSetImageBackgroundColor (image_wand, bg_wand);
7815 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
7816 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
7817 #else
7818 new_wand = MagickFlattenImages (image_wand);
7819 #endif
7820 DestroyMagickWand (image_wand);
7821 image_wand = new_wand;
7824 /* Finally we are done manipulating the image. Figure out the
7825 resulting width/height and transfer ownership to Emacs. */
7826 height = MagickGetImageHeight (image_wand);
7827 width = MagickGetImageWidth (image_wand);
7829 if (! (width <= INT_MAX && height <= INT_MAX
7830 && check_image_size (f, width, height)))
7832 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7833 goto imagemagick_error;
7836 /* We can now get a valid pixel buffer from the imagemagick file, if all
7837 went ok. */
7839 init_color_table ();
7841 #ifdef HAVE_MAGICKEXPORTIMAGEPIXELS
7842 if (imagemagick_render_type != 0)
7844 /* Magicexportimage is normally faster than pixelpushing. This
7845 method is also well tested. Some aspects of this method are
7846 ad-hoc and needs to be more researched. */
7847 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
7848 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
7849 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7850 if (!x_create_x_image_and_pixmap (f, width, height, imagedepth,
7851 &ximg, &img->pixmap))
7853 #ifdef COLOR_TABLE_SUPPORT
7854 free_color_table ();
7855 #endif
7856 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7857 goto imagemagick_error;
7860 /* Oddly, the below code doesn't seem to work:*/
7861 /* switch(ximg->bitmap_unit){ */
7862 /* case 8: */
7863 /* pixelwidth=CharPixel; */
7864 /* break; */
7865 /* case 16: */
7866 /* pixelwidth=ShortPixel; */
7867 /* break; */
7868 /* case 32: */
7869 /* pixelwidth=LongPixel; */
7870 /* break; */
7871 /* } */
7873 Here im just guessing the format of the bitmap.
7874 happens to work fine for:
7875 - bw djvu images
7876 on rgb display.
7877 seems about 3 times as fast as pixel pushing(not carefully measured)
7879 pixelwidth = CharPixel; /*??? TODO figure out*/
7880 MagickExportImagePixels (image_wand, 0, 0, width, height,
7881 exportdepth, pixelwidth, ximg->data);
7883 else
7884 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
7886 size_t image_height;
7888 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7889 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7890 &ximg, &img->pixmap))
7892 #ifdef COLOR_TABLE_SUPPORT
7893 free_color_table ();
7894 #endif
7895 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7896 goto imagemagick_error;
7899 /* Copy imagemagick image to x with primitive yet robust pixel
7900 pusher loop. This has been tested a lot with many different
7901 images. */
7903 /* Copy pixels from the imagemagick image structure to the x image map. */
7904 iterator = NewPixelIterator (image_wand);
7905 if (iterator == (PixelIterator *) NULL)
7907 #ifdef COLOR_TABLE_SUPPORT
7908 free_color_table ();
7909 #endif
7910 x_destroy_x_image (ximg);
7911 image_error ("Imagemagick pixel iterator creation failed",
7912 Qnil, Qnil);
7913 goto imagemagick_error;
7916 image_height = MagickGetImageHeight (image_wand);
7917 for (y = 0; y < image_height; y++)
7919 pixels = PixelGetNextIteratorRow (iterator, &width);
7920 if (pixels == (PixelWand **) NULL)
7921 break;
7922 for (x = 0; x < (long) width; x++)
7924 PixelGetMagickColor (pixels[x], &pixel);
7925 XPutPixel (ximg, x, y,
7926 lookup_rgb_color (f,
7927 pixel.red,
7928 pixel.green,
7929 pixel.blue));
7932 DestroyPixelIterator (iterator);
7935 #ifdef COLOR_TABLE_SUPPORT
7936 /* Remember colors allocated for this image. */
7937 img->colors = colors_in_color_table (&img->ncolors);
7938 free_color_table ();
7939 #endif /* COLOR_TABLE_SUPPORT */
7941 img->width = width;
7942 img->height = height;
7944 /* Put the image into the pixmap, then free the X image and its
7945 buffer. */
7946 x_put_x_image (f, ximg, img->pixmap, width, height);
7947 x_destroy_x_image (ximg);
7949 /* Final cleanup. image_wand should be the only resource left. */
7950 DestroyMagickWand (image_wand);
7951 if (bg_wand) DestroyPixelWand (bg_wand);
7953 /* `MagickWandTerminus' terminates the imagemagick environment. */
7954 MagickWandTerminus ();
7956 return 1;
7958 imagemagick_error:
7959 DestroyMagickWand (image_wand);
7960 if (bg_wand) DestroyPixelWand (bg_wand);
7962 MagickWandTerminus ();
7963 /* TODO more cleanup. */
7964 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
7965 return 0;
7969 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
7970 successful. this function will go into the imagemagick_type structure, and
7971 the prototype thus needs to be compatible with that structure. */
7973 static bool
7974 imagemagick_load (struct frame *f, struct image *img)
7976 bool success_p = 0;
7977 Lisp_Object file_name;
7979 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7980 file_name = image_spec_value (img->spec, QCfile, NULL);
7981 if (STRINGP (file_name))
7983 Lisp_Object file;
7985 file = x_find_image_file (file_name);
7986 if (!STRINGP (file))
7988 image_error ("Cannot find image file `%s'", file_name, Qnil);
7989 return 0;
7991 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
7993 /* Else its not a file, its a lisp object. Load the image from a
7994 lisp object rather than a file. */
7995 else
7997 Lisp_Object data;
7999 data = image_spec_value (img->spec, QCdata, NULL);
8000 if (!STRINGP (data))
8002 image_error ("Invalid image data `%s'", data, Qnil);
8003 return 0;
8005 success_p = imagemagick_load_image (f, img, SDATA (data),
8006 SBYTES (data), NULL);
8009 return success_p;
8012 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
8013 doc: /* Return a list of image types supported by ImageMagick.
8014 Each entry in this list is a symbol named after an ImageMagick format
8015 tag. See the ImageMagick manual for a list of ImageMagick formats and
8016 their descriptions (http://www.imagemagick.org/script/formats.php).
8017 You can also try the shell command: `identify -list format'.
8019 Note that ImageMagick recognizes many file-types that Emacs does not
8020 recognize as images, such as C. See `imagemagick-types-enable'
8021 and `imagemagick-types-inhibit'. */)
8022 (void)
8024 Lisp_Object typelist = Qnil;
8025 size_t numf = 0;
8026 ExceptionInfo ex;
8027 char **imtypes;
8028 size_t i;
8029 Lisp_Object Qimagemagicktype;
8031 GetExceptionInfo(&ex);
8032 imtypes = GetMagickList ("*", &numf, &ex);
8033 DestroyExceptionInfo(&ex);
8035 for (i = 0; i < numf; i++)
8037 Qimagemagicktype = intern (imtypes[i]);
8038 typelist = Fcons (Qimagemagicktype, typelist);
8040 return Fnreverse (typelist);
8043 #endif /* defined (HAVE_IMAGEMAGICK) */
8047 /***********************************************************************
8049 ***********************************************************************/
8051 #if defined (HAVE_RSVG)
8053 /* Function prototypes. */
8055 static bool svg_image_p (Lisp_Object object);
8056 static bool svg_load (struct frame *f, struct image *img);
8058 static bool svg_load_image (struct frame *, struct image *,
8059 unsigned char *, ptrdiff_t);
8061 /* The symbol `svg' identifying images of this type. */
8063 static Lisp_Object Qsvg;
8065 /* Indices of image specification fields in svg_format, below. */
8067 enum svg_keyword_index
8069 SVG_TYPE,
8070 SVG_DATA,
8071 SVG_FILE,
8072 SVG_ASCENT,
8073 SVG_MARGIN,
8074 SVG_RELIEF,
8075 SVG_ALGORITHM,
8076 SVG_HEURISTIC_MASK,
8077 SVG_MASK,
8078 SVG_BACKGROUND,
8079 SVG_LAST
8082 /* Vector of image_keyword structures describing the format
8083 of valid user-defined image specifications. */
8085 static const struct image_keyword svg_format[SVG_LAST] =
8087 {":type", IMAGE_SYMBOL_VALUE, 1},
8088 {":data", IMAGE_STRING_VALUE, 0},
8089 {":file", IMAGE_STRING_VALUE, 0},
8090 {":ascent", IMAGE_ASCENT_VALUE, 0},
8091 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8092 {":relief", IMAGE_INTEGER_VALUE, 0},
8093 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8094 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8095 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8096 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8099 #if defined HAVE_NTGUI && defined WINDOWSNT
8100 static bool init_svg_functions (void);
8101 #else
8102 #define init_svg_functions NULL
8103 #endif
8105 /* Structure describing the image type `svg'. Its the same type of
8106 structure defined for all image formats, handled by emacs image
8107 functions. See struct image_type in dispextern.h. */
8109 static struct image_type svg_type =
8111 &Qsvg,
8112 svg_image_p,
8113 svg_load,
8114 x_clear_image,
8115 init_svg_functions,
8116 NULL
8120 /* Return true if OBJECT is a valid SVG image specification. Do
8121 this by calling parse_image_spec and supplying the keywords that
8122 identify the SVG format. */
8124 static bool
8125 svg_image_p (Lisp_Object object)
8127 struct image_keyword fmt[SVG_LAST];
8128 memcpy (fmt, svg_format, sizeof fmt);
8130 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8131 return 0;
8133 /* Must specify either the :data or :file keyword. */
8134 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8137 #include <librsvg/rsvg.h>
8139 #ifdef WINDOWSNT
8141 /* SVG library functions. */
8142 DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new, (void));
8143 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions, (RsvgHandle *, RsvgDimensionData *));
8144 DEF_IMGLIB_FN (gboolean, rsvg_handle_write, (RsvgHandle *, const guchar *, gsize, GError **));
8145 DEF_IMGLIB_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
8146 DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
8147 DEF_IMGLIB_FN (void *, rsvg_handle_set_size_callback, (RsvgHandle *, RsvgSizeFunc, gpointer, GDestroyNotify));
8149 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
8150 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
8151 DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
8152 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
8153 DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
8154 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
8155 DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
8156 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
8158 DEF_IMGLIB_FN (void, g_type_init, (void));
8159 DEF_IMGLIB_FN (void, g_object_unref, (gpointer));
8160 DEF_IMGLIB_FN (void, g_error_free, (GError *));
8162 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8164 static bool
8165 init_svg_functions (void)
8167 HMODULE library, gdklib, glib, gobject;
8169 if (!(glib = w32_delayed_load (Qglib))
8170 || !(gobject = w32_delayed_load (Qgobject))
8171 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
8172 || !(library = w32_delayed_load (Qsvg)))
8173 return 0;
8175 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8176 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8177 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8178 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8179 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8181 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8182 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8183 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8184 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8185 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8186 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8187 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8188 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8190 LOAD_IMGLIB_FN (gobject, g_type_init);
8191 LOAD_IMGLIB_FN (gobject, g_object_unref);
8192 LOAD_IMGLIB_FN (glib, g_error_free);
8194 return 1;
8197 #else
8198 /* The following aliases for library functions allow dynamic loading
8199 to be used on some platforms. */
8200 #define fn_rsvg_handle_new rsvg_handle_new
8201 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8202 #define fn_rsvg_handle_write rsvg_handle_write
8203 #define fn_rsvg_handle_close rsvg_handle_close
8204 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8206 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8207 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8208 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8209 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8210 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8211 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8212 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8213 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8215 #define fn_g_type_init g_type_init
8216 #define fn_g_object_unref g_object_unref
8217 #define fn_g_error_free g_error_free
8218 #endif /* !WINDOWSNT */
8220 /* Load SVG image IMG for use on frame F. Value is true if
8221 successful. */
8223 static bool
8224 svg_load (struct frame *f, struct image *img)
8226 bool success_p = 0;
8227 Lisp_Object file_name;
8229 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8230 file_name = image_spec_value (img->spec, QCfile, NULL);
8231 if (STRINGP (file_name))
8233 Lisp_Object file;
8234 unsigned char *contents;
8235 ptrdiff_t size;
8237 file = x_find_image_file (file_name);
8238 if (!STRINGP (file))
8240 image_error ("Cannot find image file `%s'", file_name, Qnil);
8241 return 0;
8244 /* Read the entire file into memory. */
8245 contents = slurp_file (SSDATA (file), &size);
8246 if (contents == NULL)
8248 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8249 return 0;
8251 /* If the file was slurped into memory properly, parse it. */
8252 success_p = svg_load_image (f, img, contents, size);
8253 xfree (contents);
8255 /* Else its not a file, its a lisp object. Load the image from a
8256 lisp object rather than a file. */
8257 else
8259 Lisp_Object data;
8261 data = image_spec_value (img->spec, QCdata, NULL);
8262 if (!STRINGP (data))
8264 image_error ("Invalid image data `%s'", data, Qnil);
8265 return 0;
8267 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8270 return success_p;
8273 /* svg_load_image is a helper function for svg_load, which does the
8274 actual loading given contents and size, apart from frame and image
8275 structures, passed from svg_load.
8277 Uses librsvg to do most of the image processing.
8279 Returns true when successful. */
8280 static bool
8281 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8282 struct image *img, /* Pointer to emacs image structure. */
8283 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8284 ptrdiff_t size) /* Size of data in bytes. */
8286 RsvgHandle *rsvg_handle;
8287 RsvgDimensionData dimension_data;
8288 GError *err = NULL;
8289 GdkPixbuf *pixbuf;
8290 int width;
8291 int height;
8292 const guint8 *pixels;
8293 int rowstride;
8294 XImagePtr ximg;
8295 Lisp_Object specified_bg;
8296 XColor background;
8297 int x;
8298 int y;
8300 /* g_type_init is a glib function that must be called prior to using
8301 gnome type library functions. */
8302 fn_g_type_init ();
8303 /* Make a handle to a new rsvg object. */
8304 rsvg_handle = fn_rsvg_handle_new ();
8306 /* Parse the contents argument and fill in the rsvg_handle. */
8307 fn_rsvg_handle_write (rsvg_handle, contents, size, &err);
8308 if (err) goto rsvg_error;
8310 /* The parsing is complete, rsvg_handle is ready to used, close it
8311 for further writes. */
8312 fn_rsvg_handle_close (rsvg_handle, &err);
8313 if (err) goto rsvg_error;
8315 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8316 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8318 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8319 goto rsvg_error;
8322 /* We can now get a valid pixel buffer from the svg file, if all
8323 went ok. */
8324 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8325 if (!pixbuf) goto rsvg_error;
8326 fn_g_object_unref (rsvg_handle);
8328 /* Extract some meta data from the svg handle. */
8329 width = fn_gdk_pixbuf_get_width (pixbuf);
8330 height = fn_gdk_pixbuf_get_height (pixbuf);
8331 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8332 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8334 /* Validate the svg meta data. */
8335 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8336 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8337 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8338 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8340 /* Try to create a x pixmap to hold the svg pixmap. */
8341 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8343 fn_g_object_unref (pixbuf);
8344 return 0;
8347 init_color_table ();
8349 /* Handle alpha channel by combining the image with a background
8350 color. */
8351 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8352 if (!STRINGP (specified_bg)
8353 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
8355 #ifndef HAVE_NS
8356 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8357 x_query_color (f, &background);
8358 #else
8359 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8360 #endif
8363 /* SVG pixmaps specify transparency in the last byte, so right
8364 shift 8 bits to get rid of it, since emacs doesn't support
8365 transparency. */
8366 background.red >>= 8;
8367 background.green >>= 8;
8368 background.blue >>= 8;
8370 /* This loop handles opacity values, since Emacs assumes
8371 non-transparent images. Each pixel must be "flattened" by
8372 calculating the resulting color, given the transparency of the
8373 pixel, and the image background color. */
8374 for (y = 0; y < height; ++y)
8376 for (x = 0; x < width; ++x)
8378 int red;
8379 int green;
8380 int blue;
8381 int opacity;
8383 red = *pixels++;
8384 green = *pixels++;
8385 blue = *pixels++;
8386 opacity = *pixels++;
8388 red = ((red * opacity)
8389 + (background.red * ((1 << 8) - opacity)));
8390 green = ((green * opacity)
8391 + (background.green * ((1 << 8) - opacity)));
8392 blue = ((blue * opacity)
8393 + (background.blue * ((1 << 8) - opacity)));
8395 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8398 pixels += rowstride - 4 * width;
8401 #ifdef COLOR_TABLE_SUPPORT
8402 /* Remember colors allocated for this image. */
8403 img->colors = colors_in_color_table (&img->ncolors);
8404 free_color_table ();
8405 #endif /* COLOR_TABLE_SUPPORT */
8407 fn_g_object_unref (pixbuf);
8409 img->width = width;
8410 img->height = height;
8412 /* Maybe fill in the background field while we have ximg handy.
8413 Casting avoids a GCC warning. */
8414 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8416 /* Put the image into the pixmap, then free the X image and its
8417 buffer. */
8418 x_put_x_image (f, ximg, img->pixmap, width, height);
8419 x_destroy_x_image (ximg);
8421 return 1;
8423 rsvg_error:
8424 fn_g_object_unref (rsvg_handle);
8425 /* FIXME: Use error->message so the user knows what is the actual
8426 problem with the image. */
8427 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8428 fn_g_error_free (err);
8429 return 0;
8432 #endif /* defined (HAVE_RSVG) */
8437 /***********************************************************************
8438 Ghostscript
8439 ***********************************************************************/
8441 #ifdef HAVE_X_WINDOWS
8442 #define HAVE_GHOSTSCRIPT 1
8443 #endif /* HAVE_X_WINDOWS */
8445 #ifdef HAVE_GHOSTSCRIPT
8447 static bool gs_image_p (Lisp_Object object);
8448 static bool gs_load (struct frame *f, struct image *img);
8449 static void gs_clear_image (struct frame *f, struct image *img);
8451 /* Keyword symbols. */
8453 static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8455 /* Indices of image specification fields in gs_format, below. */
8457 enum gs_keyword_index
8459 GS_TYPE,
8460 GS_PT_WIDTH,
8461 GS_PT_HEIGHT,
8462 GS_FILE,
8463 GS_LOADER,
8464 GS_BOUNDING_BOX,
8465 GS_ASCENT,
8466 GS_MARGIN,
8467 GS_RELIEF,
8468 GS_ALGORITHM,
8469 GS_HEURISTIC_MASK,
8470 GS_MASK,
8471 GS_BACKGROUND,
8472 GS_LAST
8475 /* Vector of image_keyword structures describing the format
8476 of valid user-defined image specifications. */
8478 static const struct image_keyword gs_format[GS_LAST] =
8480 {":type", IMAGE_SYMBOL_VALUE, 1},
8481 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8482 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8483 {":file", IMAGE_STRING_VALUE, 1},
8484 {":loader", IMAGE_FUNCTION_VALUE, 0},
8485 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8486 {":ascent", IMAGE_ASCENT_VALUE, 0},
8487 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8488 {":relief", IMAGE_INTEGER_VALUE, 0},
8489 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8490 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8491 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8492 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8495 /* Structure describing the image type `ghostscript'. */
8497 static struct image_type gs_type =
8499 &Qpostscript,
8500 gs_image_p,
8501 gs_load,
8502 gs_clear_image,
8503 NULL,
8504 NULL
8508 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8510 static void
8511 gs_clear_image (struct frame *f, struct image *img)
8513 x_clear_image (f, img);
8517 /* Return true if OBJECT is a valid Ghostscript image
8518 specification. */
8520 static bool
8521 gs_image_p (Lisp_Object object)
8523 struct image_keyword fmt[GS_LAST];
8524 Lisp_Object tem;
8525 int i;
8527 memcpy (fmt, gs_format, sizeof fmt);
8529 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8530 return 0;
8532 /* Bounding box must be a list or vector containing 4 integers. */
8533 tem = fmt[GS_BOUNDING_BOX].value;
8534 if (CONSP (tem))
8536 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8537 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8538 return 0;
8539 if (!NILP (tem))
8540 return 0;
8542 else if (VECTORP (tem))
8544 if (ASIZE (tem) != 4)
8545 return 0;
8546 for (i = 0; i < 4; ++i)
8547 if (!INTEGERP (AREF (tem, i)))
8548 return 0;
8550 else
8551 return 0;
8553 return 1;
8557 /* Load Ghostscript image IMG for use on frame F. Value is true
8558 if successful. */
8560 static bool
8561 gs_load (struct frame *f, struct image *img)
8563 uprintmax_t printnum1, printnum2;
8564 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
8565 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8566 Lisp_Object frame;
8567 double in_width, in_height;
8568 Lisp_Object pixel_colors = Qnil;
8570 /* Compute pixel size of pixmap needed from the given size in the
8571 image specification. Sizes in the specification are in pt. 1 pt
8572 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8573 info. */
8574 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8575 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
8576 in_width *= FRAME_RES_X (f);
8577 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8578 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
8579 in_height *= FRAME_RES_Y (f);
8581 if (! (in_width <= INT_MAX && in_height <= INT_MAX
8582 && check_image_size (f, in_width, in_height)))
8584 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8585 return 0;
8587 img->width = in_width;
8588 img->height = in_height;
8590 /* Create the pixmap. */
8591 eassert (img->pixmap == NO_PIXMAP);
8593 if (x_check_image_size (0, img->width, img->height))
8595 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8596 block_input ();
8597 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8598 img->width, img->height,
8599 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8600 unblock_input ();
8603 if (!img->pixmap)
8605 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8606 return 0;
8609 /* Call the loader to fill the pixmap. It returns a process object
8610 if successful. We do not record_unwind_protect here because
8611 other places in redisplay like calling window scroll functions
8612 don't either. Let the Lisp loader use `unwind-protect' instead. */
8613 printnum1 = FRAME_X_WINDOW (f);
8614 printnum2 = img->pixmap;
8615 window_and_pixmap_id
8616 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
8618 printnum1 = FRAME_FOREGROUND_PIXEL (f);
8619 printnum2 = FRAME_BACKGROUND_PIXEL (f);
8620 pixel_colors
8621 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
8623 XSETFRAME (frame, f);
8624 loader = image_spec_value (img->spec, QCloader, NULL);
8625 if (NILP (loader))
8626 loader = intern ("gs-load-image");
8628 img->lisp_data = call6 (loader, frame, img->spec,
8629 make_number (img->width),
8630 make_number (img->height),
8631 window_and_pixmap_id,
8632 pixel_colors);
8633 return PROCESSP (img->lisp_data);
8637 /* Kill the Ghostscript process that was started to fill PIXMAP on
8638 frame F. Called from XTread_socket when receiving an event
8639 telling Emacs that Ghostscript has finished drawing. */
8641 void
8642 x_kill_gs_process (Pixmap pixmap, struct frame *f)
8644 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8645 int class;
8646 ptrdiff_t i;
8647 struct image *img;
8649 /* Find the image containing PIXMAP. */
8650 for (i = 0; i < c->used; ++i)
8651 if (c->images[i]->pixmap == pixmap)
8652 break;
8654 /* Should someone in between have cleared the image cache, for
8655 instance, give up. */
8656 if (i == c->used)
8657 return;
8659 /* Kill the GS process. We should have found PIXMAP in the image
8660 cache and its image should contain a process object. */
8661 img = c->images[i];
8662 eassert (PROCESSP (img->lisp_data));
8663 Fkill_process (img->lisp_data, Qnil);
8664 img->lisp_data = Qnil;
8666 #if defined (HAVE_X_WINDOWS)
8668 /* On displays with a mutable colormap, figure out the colors
8669 allocated for the image by looking at the pixels of an XImage for
8670 img->pixmap. */
8671 class = FRAME_X_VISUAL (f)->class;
8672 if (class != StaticColor && class != StaticGray && class != TrueColor)
8674 XImagePtr ximg;
8676 block_input ();
8678 /* Try to get an XImage for img->pixmep. */
8679 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8680 0, 0, img->width, img->height, ~0, ZPixmap);
8681 if (ximg)
8683 int x, y;
8685 /* Initialize the color table. */
8686 init_color_table ();
8688 /* For each pixel of the image, look its color up in the
8689 color table. After having done so, the color table will
8690 contain an entry for each color used by the image. */
8691 for (y = 0; y < img->height; ++y)
8692 for (x = 0; x < img->width; ++x)
8694 unsigned long pixel = XGetPixel (ximg, x, y);
8695 lookup_pixel_color (f, pixel);
8698 /* Record colors in the image. Free color table and XImage. */
8699 #ifdef COLOR_TABLE_SUPPORT
8700 img->colors = colors_in_color_table (&img->ncolors);
8701 free_color_table ();
8702 #endif
8703 XDestroyImage (ximg);
8705 #if 0 /* This doesn't seem to be the case. If we free the colors
8706 here, we get a BadAccess later in x_clear_image when
8707 freeing the colors. */
8708 /* We have allocated colors once, but Ghostscript has also
8709 allocated colors on behalf of us. So, to get the
8710 reference counts right, free them once. */
8711 if (img->ncolors)
8712 x_free_colors (f, img->colors, img->ncolors);
8713 #endif
8715 else
8716 image_error ("Cannot get X image of `%s'; colors will not be freed",
8717 img->spec, Qnil);
8719 unblock_input ();
8721 #endif /* HAVE_X_WINDOWS */
8723 /* Now that we have the pixmap, compute mask and transform the
8724 image if requested. */
8725 block_input ();
8726 postprocess_image (f, img);
8727 unblock_input ();
8730 #endif /* HAVE_GHOSTSCRIPT */
8733 /***********************************************************************
8734 Tests
8735 ***********************************************************************/
8737 #ifdef GLYPH_DEBUG
8739 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8740 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8741 (Lisp_Object spec)
8743 return valid_image_p (spec) ? Qt : Qnil;
8747 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8748 (Lisp_Object spec)
8750 ptrdiff_t id = -1;
8752 if (valid_image_p (spec))
8753 id = lookup_image (SELECTED_FRAME (), spec);
8755 debug_print (spec);
8756 return make_number (id);
8759 #endif /* GLYPH_DEBUG */
8762 /***********************************************************************
8763 Initialization
8764 ***********************************************************************/
8766 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
8767 doc: /* Initialize image library implementing image type TYPE.
8768 Return non-nil if TYPE is a supported image type.
8770 If image libraries are loaded dynamically (currently only the case on
8771 MS-Windows), load the library for TYPE if it is not yet loaded, using
8772 the library file(s) specified by `dynamic-library-alist'. */)
8773 (Lisp_Object type)
8775 return lookup_image_type (type) ? Qt : Qnil;
8778 /* Look up image type TYPE, and return a pointer to its image_type
8779 structure. Return 0 if TYPE is not a known image type. */
8781 static struct image_type *
8782 lookup_image_type (Lisp_Object type)
8784 /* Types pbm and xbm are built-in and always available. */
8785 if (EQ (type, Qpbm))
8786 return define_image_type (&pbm_type);
8788 if (EQ (type, Qxbm))
8789 return define_image_type (&xbm_type);
8791 #if defined (HAVE_XPM) || defined (HAVE_NS)
8792 if (EQ (type, Qxpm))
8793 return define_image_type (&xpm_type);
8794 #endif
8796 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8797 if (EQ (type, Qjpeg))
8798 return define_image_type (&jpeg_type);
8799 #endif
8801 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8802 if (EQ (type, Qtiff))
8803 return define_image_type (&tiff_type);
8804 #endif
8806 #if defined (HAVE_GIF) || defined (HAVE_NS)
8807 if (EQ (type, Qgif))
8808 return define_image_type (&gif_type);
8809 #endif
8811 #if defined (HAVE_PNG) || defined (HAVE_NS)
8812 if (EQ (type, Qpng))
8813 return define_image_type (&png_type);
8814 #endif
8816 #if defined (HAVE_RSVG)
8817 if (EQ (type, Qsvg))
8818 return define_image_type (&svg_type);
8819 #endif
8821 #if defined (HAVE_IMAGEMAGICK)
8822 if (EQ (type, Qimagemagick))
8823 return define_image_type (&imagemagick_type);
8824 #endif
8826 #ifdef HAVE_GHOSTSCRIPT
8827 if (EQ (type, Qpostscript))
8828 return define_image_type (&gs_type);
8829 #endif
8831 return NULL;
8834 /* Reset image_types before dumping.
8835 Called from Fdump_emacs. */
8837 void
8838 reset_image_types (void)
8840 while (image_types)
8842 struct image_type *next = image_types->next;
8843 xfree (image_types);
8844 image_types = next;
8848 void
8849 syms_of_image (void)
8851 /* Initialize this only once; it will be reset before dumping. */
8852 image_types = NULL;
8854 /* Must be defined now because we're going to update it below, while
8855 defining the supported image types. */
8856 DEFVAR_LISP ("image-types", Vimage_types,
8857 doc: /* List of potentially supported image types.
8858 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8859 To check whether it is really supported, use `image-type-available-p'. */);
8860 Vimage_types = Qnil;
8862 DEFVAR_LISP ("max-image-size", Vmax_image_size,
8863 doc: /* Maximum size of images.
8864 Emacs will not load an image into memory if its pixel width or
8865 pixel height exceeds this limit.
8867 If the value is an integer, it directly specifies the maximum
8868 image height and width, measured in pixels. If it is a floating
8869 point number, it specifies the maximum image height and width
8870 as a ratio to the frame height and width. If the value is
8871 non-numeric, there is no explicit limit on the size of images. */);
8872 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8874 DEFSYM (Qcount, "count");
8875 DEFSYM (Qextension_data, "extension-data");
8876 DEFSYM (Qdelay, "delay");
8878 DEFSYM (QCascent, ":ascent");
8879 DEFSYM (QCmargin, ":margin");
8880 DEFSYM (QCrelief, ":relief");
8881 DEFSYM (QCconversion, ":conversion");
8882 DEFSYM (QCcolor_symbols, ":color-symbols");
8883 DEFSYM (QCheuristic_mask, ":heuristic-mask");
8884 DEFSYM (QCindex, ":index");
8885 DEFSYM (QCgeometry, ":geometry");
8886 DEFSYM (QCcrop, ":crop");
8887 DEFSYM (QCrotation, ":rotation");
8888 DEFSYM (QCmatrix, ":matrix");
8889 DEFSYM (QCcolor_adjustment, ":color-adjustment");
8890 DEFSYM (QCmask, ":mask");
8892 DEFSYM (Qlaplace, "laplace");
8893 DEFSYM (Qemboss, "emboss");
8894 DEFSYM (Qedge_detection, "edge-detection");
8895 DEFSYM (Qheuristic, "heuristic");
8897 DEFSYM (Qpostscript, "postscript");
8898 #ifdef HAVE_GHOSTSCRIPT
8899 ADD_IMAGE_TYPE (Qpostscript);
8900 DEFSYM (QCloader, ":loader");
8901 DEFSYM (QCbounding_box, ":bounding-box");
8902 DEFSYM (QCpt_width, ":pt-width");
8903 DEFSYM (QCpt_height, ":pt-height");
8904 #endif /* HAVE_GHOSTSCRIPT */
8906 #ifdef HAVE_NTGUI
8907 DEFSYM (Qlibpng_version, "libpng-version");
8908 Fset (Qlibpng_version,
8909 #if HAVE_PNG
8910 make_number (PNG_LIBPNG_VER)
8911 #else
8912 make_number (-1)
8913 #endif
8915 #endif
8917 DEFSYM (Qpbm, "pbm");
8918 ADD_IMAGE_TYPE (Qpbm);
8920 DEFSYM (Qxbm, "xbm");
8921 ADD_IMAGE_TYPE (Qxbm);
8923 #if defined (HAVE_XPM) || defined (HAVE_NS)
8924 DEFSYM (Qxpm, "xpm");
8925 ADD_IMAGE_TYPE (Qxpm);
8926 #endif
8928 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8929 DEFSYM (Qjpeg, "jpeg");
8930 ADD_IMAGE_TYPE (Qjpeg);
8931 #endif
8933 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8934 DEFSYM (Qtiff, "tiff");
8935 ADD_IMAGE_TYPE (Qtiff);
8936 #endif
8938 #if defined (HAVE_GIF) || defined (HAVE_NS)
8939 DEFSYM (Qgif, "gif");
8940 ADD_IMAGE_TYPE (Qgif);
8941 #endif
8943 #if defined (HAVE_PNG) || defined (HAVE_NS)
8944 DEFSYM (Qpng, "png");
8945 ADD_IMAGE_TYPE (Qpng);
8946 #endif
8948 #if defined (HAVE_IMAGEMAGICK)
8949 DEFSYM (Qimagemagick, "imagemagick");
8950 ADD_IMAGE_TYPE (Qimagemagick);
8951 #endif
8953 #if defined (HAVE_RSVG)
8954 DEFSYM (Qsvg, "svg");
8955 ADD_IMAGE_TYPE (Qsvg);
8956 #ifdef HAVE_NTGUI
8957 /* Other libraries used directly by svg code. */
8958 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
8959 DEFSYM (Qglib, "glib");
8960 DEFSYM (Qgobject, "gobject");
8961 #endif /* HAVE_NTGUI */
8962 #endif /* HAVE_RSVG */
8964 defsubr (&Sinit_image_library);
8965 #ifdef HAVE_IMAGEMAGICK
8966 defsubr (&Simagemagick_types);
8967 #endif
8968 defsubr (&Sclear_image_cache);
8969 defsubr (&Simage_flush);
8970 defsubr (&Simage_size);
8971 defsubr (&Simage_mask_p);
8972 defsubr (&Simage_metadata);
8974 #ifdef GLYPH_DEBUG
8975 defsubr (&Simagep);
8976 defsubr (&Slookup_image);
8977 #endif
8979 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
8980 doc: /* Non-nil means always draw a cross over disabled images.
8981 Disabled images are those having a `:conversion disabled' property.
8982 A cross is always drawn on black & white displays. */);
8983 cross_disabled_images = 0;
8985 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
8986 doc: /* List of directories to search for window system bitmap files. */);
8987 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8989 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
8990 doc: /* Maximum time after which images are removed from the cache.
8991 When an image has not been displayed this many seconds, Emacs
8992 automatically removes it from the image cache. If the cache contains
8993 a large number of images, the actual eviction time may be shorter.
8994 The value can also be nil, meaning the cache is never cleared.
8996 The function `clear-image-cache' disregards this variable. */);
8997 Vimage_cache_eviction_delay = make_number (300);
8998 #ifdef HAVE_IMAGEMAGICK
8999 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
9000 doc: /* Integer indicating which ImageMagick rendering method to use.
9001 The options are:
9002 0 -- the default method (pixel pushing)
9003 1 -- a newer method ("MagickExportImagePixels") that may perform
9004 better (speed etc) in some cases, but has not been as thoroughly
9005 tested with Emacs as the default method. This method requires
9006 ImageMagick version 6.4.6 (approximately) or later.
9007 */);
9008 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
9009 imagemagick_render_type = 0;
9010 #endif