* window.c (window_resize_check, window_resize_apply)
[emacs/old-mirror.git] / src / image.c
blob0d4bc82f3b40dd74bc73d1c69e38852f25b5e4a2
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 imgs 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 imgs created by ns_image_for_XPM; alpha set to 1;
165 pixel is assumed to be in form RGB */
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 = check_x_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 = check_x_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 = check_x_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 (check_x_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 (check_x_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 /* Create the X image and pixmap. */
7267 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7269 fn_DGifCloseFile (gif);
7270 return 0;
7273 /* Clear the part of the screen image not covered by the image.
7274 Full animated GIF support requires more here (see the gif89 spec,
7275 disposal methods). Let's simply assume that the part not covered
7276 by a sub-image is in the frame's background color. */
7277 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7278 for (x = 0; x < width; ++x)
7279 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7281 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7282 for (x = 0; x < width; ++x)
7283 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7285 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7287 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7288 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7289 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7290 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7293 /* Read the GIF image into the X image. */
7295 /* FIXME: With the current implementation, loading an animated gif
7296 is quadratic in the number of animation frames, since each frame
7297 is a separate struct image. We must provide a way for a single
7298 gif_load call to construct and save all animation frames. */
7300 init_color_table ();
7301 if (STRINGP (specified_bg))
7302 bgcolor = x_alloc_image_color (f, img, specified_bg,
7303 FRAME_BACKGROUND_PIXEL (f));
7304 for (j = 0; j <= idx; ++j)
7306 /* We use a local variable `raster' here because RasterBits is a
7307 char *, which invites problems with bytes >= 0x80. */
7308 struct SavedImage *subimage = gif->SavedImages + j;
7309 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7310 int transparency_color_index = -1;
7311 int disposal = 0;
7312 int subimg_width = subimage->ImageDesc.Width;
7313 int subimg_height = subimage->ImageDesc.Height;
7314 int subimg_top = subimage->ImageDesc.Top;
7315 int subimg_left = subimage->ImageDesc.Left;
7317 /* Find the Graphic Control Extension block for this sub-image.
7318 Extract the disposal method and transparency color. */
7319 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7321 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7323 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7324 && extblock->ByteCount == 4
7325 && extblock->Bytes[0] & 1)
7327 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7328 to background". Treat any other value like 2. */
7329 disposal = (extblock->Bytes[0] >> 2) & 7;
7330 transparency_color_index = (unsigned char) extblock->Bytes[3];
7331 break;
7335 /* We can't "keep in place" the first subimage. */
7336 if (j == 0)
7337 disposal = 2;
7339 /* For disposal == 0, the spec says "No disposal specified. The
7340 decoder is not required to take any action." In practice, it
7341 seems we need to treat this like "keep in place", see e.g.
7342 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7343 if (disposal == 0)
7344 disposal = 1;
7346 /* Allocate subimage colors. */
7347 memset (pixel_colors, 0, sizeof pixel_colors);
7348 gif_color_map = subimage->ImageDesc.ColorMap;
7349 if (!gif_color_map)
7350 gif_color_map = gif->SColorMap;
7352 if (gif_color_map)
7353 for (i = 0; i < gif_color_map->ColorCount; ++i)
7355 if (transparency_color_index == i)
7356 pixel_colors[i] = STRINGP (specified_bg)
7357 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7358 else
7360 int r = gif_color_map->Colors[i].Red << 8;
7361 int g = gif_color_map->Colors[i].Green << 8;
7362 int b = gif_color_map->Colors[i].Blue << 8;
7363 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7367 /* Apply the pixel values. */
7368 if (gif->SavedImages[j].ImageDesc.Interlace)
7370 int row, pass;
7372 for (y = 0, row = interlace_start[0], pass = 0;
7373 y < subimg_height;
7374 y++, row += interlace_increment[pass])
7376 if (row >= subimg_height)
7378 row = interlace_start[++pass];
7379 while (row >= subimg_height)
7380 row = interlace_start[++pass];
7383 for (x = 0; x < subimg_width; x++)
7385 int c = raster[y * subimg_width + x];
7386 if (transparency_color_index != c || disposal != 1)
7387 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7388 pixel_colors[c]);
7392 else
7394 for (y = 0; y < subimg_height; ++y)
7395 for (x = 0; x < subimg_width; ++x)
7397 int c = raster[y * subimg_width + x];
7398 if (transparency_color_index != c || disposal != 1)
7399 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7400 pixel_colors[c]);
7405 #ifdef COLOR_TABLE_SUPPORT
7406 img->colors = colors_in_color_table (&img->ncolors);
7407 free_color_table ();
7408 #endif /* COLOR_TABLE_SUPPORT */
7410 /* Save GIF image extension data for `image-metadata'.
7411 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7412 img->lisp_data = Qnil;
7413 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7415 int delay = 0;
7416 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7417 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7418 /* Append (... FUNCTION "BYTES") */
7420 img->lisp_data
7421 = Fcons (make_number (ext->Function),
7422 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7423 img->lisp_data));
7424 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7425 && ext->ByteCount == 4)
7427 delay = ext->Bytes[2] << CHAR_BIT;
7428 delay |= ext->Bytes[1];
7431 img->lisp_data = Fcons (Qextension_data,
7432 Fcons (img->lisp_data, Qnil));
7433 if (delay)
7434 img->lisp_data
7435 = Fcons (Qdelay,
7436 Fcons (make_float (delay / 100.0),
7437 img->lisp_data));
7440 if (gif->ImageCount > 1)
7441 img->lisp_data = Fcons (Qcount,
7442 Fcons (make_number (gif->ImageCount),
7443 img->lisp_data));
7445 fn_DGifCloseFile (gif);
7447 /* Maybe fill in the background field while we have ximg handy. */
7448 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7449 /* Casting avoids a GCC warning. */
7450 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7452 /* Put the image into the pixmap, then free the X image and its buffer. */
7453 x_put_x_image (f, ximg, img->pixmap, width, height);
7454 x_destroy_x_image (ximg);
7456 return 1;
7459 #else /* !HAVE_GIF */
7461 #ifdef HAVE_NS
7462 static bool
7463 gif_load (struct frame *f, struct image *img)
7465 return ns_load_image (f, img,
7466 image_spec_value (img->spec, QCfile, NULL),
7467 image_spec_value (img->spec, QCdata, NULL));
7469 #endif /* HAVE_NS */
7471 #endif /* HAVE_GIF */
7474 /***********************************************************************
7475 ImageMagick
7476 ***********************************************************************/
7477 #if defined (HAVE_IMAGEMAGICK)
7479 static Lisp_Object Qimagemagick;
7481 static bool imagemagick_image_p (Lisp_Object);
7482 static bool imagemagick_load (struct frame *, struct image *);
7483 static void imagemagick_clear_image (struct frame *, struct image *);
7485 /* Indices of image specification fields in imagemagick_format. */
7487 enum imagemagick_keyword_index
7489 IMAGEMAGICK_TYPE,
7490 IMAGEMAGICK_DATA,
7491 IMAGEMAGICK_FILE,
7492 IMAGEMAGICK_ASCENT,
7493 IMAGEMAGICK_MARGIN,
7494 IMAGEMAGICK_RELIEF,
7495 IMAGEMAGICK_ALGORITHM,
7496 IMAGEMAGICK_HEURISTIC_MASK,
7497 IMAGEMAGICK_MASK,
7498 IMAGEMAGICK_BACKGROUND,
7499 IMAGEMAGICK_HEIGHT,
7500 IMAGEMAGICK_WIDTH,
7501 IMAGEMAGICK_ROTATION,
7502 IMAGEMAGICK_CROP,
7503 IMAGEMAGICK_LAST
7506 /* Vector of image_keyword structures describing the format
7507 of valid user-defined image specifications. */
7509 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7511 {":type", IMAGE_SYMBOL_VALUE, 1},
7512 {":data", IMAGE_STRING_VALUE, 0},
7513 {":file", IMAGE_STRING_VALUE, 0},
7514 {":ascent", IMAGE_ASCENT_VALUE, 0},
7515 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7516 {":relief", IMAGE_INTEGER_VALUE, 0},
7517 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7518 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7519 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7520 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7521 {":height", IMAGE_INTEGER_VALUE, 0},
7522 {":width", IMAGE_INTEGER_VALUE, 0},
7523 {":rotation", IMAGE_NUMBER_VALUE, 0},
7524 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7527 #if defined HAVE_NTGUI && defined WINDOWSNT
7528 static bool init_imagemagick_functions (void);
7529 #else
7530 #define init_imagemagick_functions NULL
7531 #endif
7533 /* Structure describing the image type for any image handled via
7534 ImageMagick. */
7536 static struct image_type imagemagick_type =
7538 &Qimagemagick,
7539 imagemagick_image_p,
7540 imagemagick_load,
7541 imagemagick_clear_image,
7542 init_imagemagick_functions,
7543 NULL
7546 /* Free X resources of imagemagick image IMG which is used on frame F. */
7548 static void
7549 imagemagick_clear_image (struct frame *f,
7550 struct image *img)
7552 x_clear_image (f, img);
7555 /* Return true if OBJECT is a valid IMAGEMAGICK image specification. Do
7556 this by calling parse_image_spec and supplying the keywords that
7557 identify the IMAGEMAGICK format. */
7559 static bool
7560 imagemagick_image_p (Lisp_Object object)
7562 struct image_keyword fmt[IMAGEMAGICK_LAST];
7563 memcpy (fmt, imagemagick_format, sizeof fmt);
7565 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7566 return 0;
7568 /* Must specify either the :data or :file keyword. */
7569 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7572 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7573 Therefore rename the function so it doesn't collide with ImageMagick. */
7574 #define DrawRectangle DrawRectangleGif
7575 #include <wand/MagickWand.h>
7577 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7578 Emacs seems to work fine with the hidden version, so unhide it. */
7579 #include <magick/version.h>
7580 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7581 extern WandExport void PixelGetMagickColor (const PixelWand *,
7582 MagickPixelPacket *);
7583 #endif
7585 /* Log ImageMagick error message.
7586 Useful when a ImageMagick function returns the status `MagickFalse'. */
7588 static void
7589 imagemagick_error (MagickWand *wand)
7591 char *description;
7592 ExceptionType severity;
7594 description = MagickGetException (wand, &severity);
7595 image_error ("ImageMagick error: %s",
7596 build_string (description),
7597 Qnil);
7598 description = (char *) MagickRelinquishMemory (description);
7601 /* Helper function for imagemagick_load, which does the actual loading
7602 given contents and size, apart from frame and image structures,
7603 passed from imagemagick_load. Uses librimagemagick to do most of
7604 the image processing.
7606 F is a pointer to the Emacs frame; IMG to the image structure to
7607 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
7608 be parsed; SIZE is the number of bytes of data; and FILENAME is
7609 either the file name or the image data.
7611 Return true if successful. */
7613 static bool
7614 imagemagick_load_image (struct frame *f, struct image *img,
7615 unsigned char *contents, unsigned int size,
7616 char *filename)
7618 size_t width, height;
7619 MagickBooleanType status;
7620 XImagePtr ximg;
7621 int x, y;
7622 MagickWand *image_wand;
7623 MagickWand *ping_wand;
7624 PixelIterator *iterator;
7625 PixelWand **pixels, *bg_wand = NULL;
7626 MagickPixelPacket pixel;
7627 Lisp_Object image;
7628 Lisp_Object value;
7629 Lisp_Object crop;
7630 EMACS_INT ino;
7631 int desired_width, desired_height;
7632 double rotation;
7633 int pixelwidth;
7635 /* Handle image index for image types who can contain more than one image.
7636 Interface :index is same as for GIF. First we "ping" the image to see how
7637 many sub-images it contains. Pinging is faster than loading the image to
7638 find out things about it. */
7640 /* Initialize the imagemagick environment. */
7641 MagickWandGenesis ();
7642 image = image_spec_value (img->spec, QCindex, NULL);
7643 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7644 ping_wand = NewMagickWand ();
7645 /* MagickSetResolution (ping_wand, 2, 2); (Bug#10112) */
7647 status = filename
7648 ? MagickPingImage (ping_wand, filename)
7649 : MagickPingImageBlob (ping_wand, contents, size);
7651 if (status == MagickFalse)
7653 imagemagick_error (ping_wand);
7654 DestroyMagickWand (ping_wand);
7655 return 0;
7658 if (ino < 0 || ino >= MagickGetNumberImages (ping_wand))
7660 image_error ("Invalid image number `%s' in image `%s'",
7661 image, img->spec);
7662 DestroyMagickWand (ping_wand);
7663 return 0;
7666 if (MagickGetNumberImages (ping_wand) > 1)
7667 img->lisp_data =
7668 Fcons (Qcount,
7669 Fcons (make_number (MagickGetNumberImages (ping_wand)),
7670 img->lisp_data));
7672 DestroyMagickWand (ping_wand);
7674 /* Now we know how many images are inside the file. If it's not a
7675 bundle, the number is one. Load the image data. */
7677 image_wand = NewMagickWand ();
7679 if ((filename
7680 ? MagickReadImage (image_wand, filename)
7681 : MagickReadImageBlob (image_wand, contents, size))
7682 == MagickFalse)
7684 imagemagick_error (image_wand);
7685 goto imagemagick_error;
7688 /* Retrieve the frame's background color, for use later. */
7690 XColor bgcolor;
7691 Lisp_Object specified_bg;
7693 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7694 if (!STRINGP (specified_bg)
7695 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
7697 #ifndef HAVE_NS
7698 bgcolor.pixel = FRAME_BACKGROUND_PIXEL (f);
7699 x_query_color (f, &bgcolor);
7700 #else
7701 ns_query_color (FRAME_BACKGROUND_COLOR (f), &bgcolor, 1);
7702 #endif
7705 bg_wand = NewPixelWand ();
7706 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
7707 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
7708 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
7711 /* If width and/or height is set in the display spec assume we want
7712 to scale to those values. If either h or w is unspecified, the
7713 unspecified should be calculated from the specified to preserve
7714 aspect ratio. */
7715 value = image_spec_value (img->spec, QCwidth, NULL);
7716 desired_width = (INTEGERP (value) ? XFASTINT (value) : -1);
7717 value = image_spec_value (img->spec, QCheight, NULL);
7718 desired_height = (INTEGERP (value) ? XFASTINT (value) : -1);
7720 height = MagickGetImageHeight (image_wand);
7721 width = MagickGetImageWidth (image_wand);
7723 if (desired_width != -1 && desired_height == -1)
7724 /* w known, calculate h. */
7725 desired_height = (double) desired_width / width * height;
7726 if (desired_width == -1 && desired_height != -1)
7727 /* h known, calculate w. */
7728 desired_width = (double) desired_height / height * width;
7729 if (desired_width != -1 && desired_height != -1)
7731 status = MagickScaleImage (image_wand, desired_width, desired_height);
7732 if (status == MagickFalse)
7734 image_error ("Imagemagick scale failed", Qnil, Qnil);
7735 imagemagick_error (image_wand);
7736 goto imagemagick_error;
7740 /* crop behaves similar to image slicing in Emacs but is more memory
7741 efficient. */
7742 crop = image_spec_value (img->spec, QCcrop, NULL);
7744 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7746 /* After some testing, it seems MagickCropImage is the fastest crop
7747 function in ImageMagick. This crop function seems to do less copying
7748 than the alternatives, but it still reads the entire image into memory
7749 before cropping, which is apparently difficult to avoid when using
7750 imagemagick. */
7751 size_t crop_width = XINT (XCAR (crop));
7752 crop = XCDR (crop);
7753 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7755 size_t crop_height = XINT (XCAR (crop));
7756 crop = XCDR (crop);
7757 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7759 ssize_t crop_x = XINT (XCAR (crop));
7760 crop = XCDR (crop);
7761 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7763 ssize_t crop_y = XINT (XCAR (crop));
7764 MagickCropImage (image_wand, crop_width, crop_height,
7765 crop_x, crop_y);
7771 /* Furthermore :rotation. we need background color and angle for
7772 rotation. */
7774 TODO background handling for rotation specified_bg =
7775 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
7776 (specified_bg). */
7777 value = image_spec_value (img->spec, QCrotation, NULL);
7778 if (FLOATP (value))
7780 rotation = extract_float (value);
7781 status = MagickRotateImage (image_wand, bg_wand, rotation);
7782 if (status == MagickFalse)
7784 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
7785 imagemagick_error (image_wand);
7786 goto imagemagick_error;
7790 /* Set the canvas background color to the frame or specified
7791 background, and flatten the image. Note: as of ImageMagick
7792 6.6.0, SVG image transparency is not handled properly
7793 (e.g. etc/images/splash.svg shows a white background always). */
7795 MagickWand *new_wand;
7796 MagickSetImageBackgroundColor (image_wand, bg_wand);
7797 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
7798 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
7799 #else
7800 new_wand = MagickFlattenImages (image_wand);
7801 #endif
7802 DestroyMagickWand (image_wand);
7803 image_wand = new_wand;
7806 /* Finally we are done manipulating the image. Figure out the
7807 resulting width/height and transfer ownership to Emacs. */
7808 height = MagickGetImageHeight (image_wand);
7809 width = MagickGetImageWidth (image_wand);
7811 if (! (width <= INT_MAX && height <= INT_MAX
7812 && check_image_size (f, width, height)))
7814 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7815 goto imagemagick_error;
7818 /* We can now get a valid pixel buffer from the imagemagick file, if all
7819 went ok. */
7821 init_color_table ();
7823 #ifdef HAVE_MAGICKEXPORTIMAGEPIXELS
7824 if (imagemagick_render_type != 0)
7826 /* Magicexportimage is normally faster than pixelpushing. This
7827 method is also well tested. Some aspects of this method are
7828 ad-hoc and needs to be more researched. */
7829 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
7830 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
7831 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7832 if (!x_create_x_image_and_pixmap (f, width, height, imagedepth,
7833 &ximg, &img->pixmap))
7835 #ifdef COLOR_TABLE_SUPPORT
7836 free_color_table ();
7837 #endif
7838 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7839 goto imagemagick_error;
7842 /* Oddly, the below code doesn't seem to work:*/
7843 /* switch(ximg->bitmap_unit){ */
7844 /* case 8: */
7845 /* pixelwidth=CharPixel; */
7846 /* break; */
7847 /* case 16: */
7848 /* pixelwidth=ShortPixel; */
7849 /* break; */
7850 /* case 32: */
7851 /* pixelwidth=LongPixel; */
7852 /* break; */
7853 /* } */
7855 Here im just guessing the format of the bitmap.
7856 happens to work fine for:
7857 - bw djvu images
7858 on rgb display.
7859 seems about 3 times as fast as pixel pushing(not carefully measured)
7861 pixelwidth = CharPixel; /*??? TODO figure out*/
7862 MagickExportImagePixels (image_wand, 0, 0, width, height,
7863 exportdepth, pixelwidth, ximg->data);
7865 else
7866 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
7868 size_t image_height;
7870 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7871 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7872 &ximg, &img->pixmap))
7874 #ifdef COLOR_TABLE_SUPPORT
7875 free_color_table ();
7876 #endif
7877 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7878 goto imagemagick_error;
7881 /* Copy imagemagick image to x with primitive yet robust pixel
7882 pusher loop. This has been tested a lot with many different
7883 images. */
7885 /* Copy pixels from the imagemagick image structure to the x image map. */
7886 iterator = NewPixelIterator (image_wand);
7887 if (iterator == (PixelIterator *) NULL)
7889 #ifdef COLOR_TABLE_SUPPORT
7890 free_color_table ();
7891 #endif
7892 x_destroy_x_image (ximg);
7893 image_error ("Imagemagick pixel iterator creation failed",
7894 Qnil, Qnil);
7895 goto imagemagick_error;
7898 image_height = MagickGetImageHeight (image_wand);
7899 for (y = 0; y < image_height; y++)
7901 pixels = PixelGetNextIteratorRow (iterator, &width);
7902 if (pixels == (PixelWand **) NULL)
7903 break;
7904 for (x = 0; x < (long) width; x++)
7906 PixelGetMagickColor (pixels[x], &pixel);
7907 XPutPixel (ximg, x, y,
7908 lookup_rgb_color (f,
7909 pixel.red,
7910 pixel.green,
7911 pixel.blue));
7914 DestroyPixelIterator (iterator);
7917 #ifdef COLOR_TABLE_SUPPORT
7918 /* Remember colors allocated for this image. */
7919 img->colors = colors_in_color_table (&img->ncolors);
7920 free_color_table ();
7921 #endif /* COLOR_TABLE_SUPPORT */
7923 img->width = width;
7924 img->height = height;
7926 /* Put the image into the pixmap, then free the X image and its
7927 buffer. */
7928 x_put_x_image (f, ximg, img->pixmap, width, height);
7929 x_destroy_x_image (ximg);
7931 /* Final cleanup. image_wand should be the only resource left. */
7932 DestroyMagickWand (image_wand);
7933 if (bg_wand) DestroyPixelWand (bg_wand);
7935 /* `MagickWandTerminus' terminates the imagemagick environment. */
7936 MagickWandTerminus ();
7938 return 1;
7940 imagemagick_error:
7941 DestroyMagickWand (image_wand);
7942 if (bg_wand) DestroyPixelWand (bg_wand);
7944 MagickWandTerminus ();
7945 /* TODO more cleanup. */
7946 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
7947 return 0;
7951 /* Load IMAGEMAGICK image IMG for use on frame F. Value is true if
7952 successful. this function will go into the imagemagick_type structure, and
7953 the prototype thus needs to be compatible with that structure. */
7955 static bool
7956 imagemagick_load (struct frame *f, struct image *img)
7958 bool success_p = 0;
7959 Lisp_Object file_name;
7961 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7962 file_name = image_spec_value (img->spec, QCfile, NULL);
7963 if (STRINGP (file_name))
7965 Lisp_Object file;
7967 file = x_find_image_file (file_name);
7968 if (!STRINGP (file))
7970 image_error ("Cannot find image file `%s'", file_name, Qnil);
7971 return 0;
7973 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
7975 /* Else its not a file, its a lisp object. Load the image from a
7976 lisp object rather than a file. */
7977 else
7979 Lisp_Object data;
7981 data = image_spec_value (img->spec, QCdata, NULL);
7982 if (!STRINGP (data))
7984 image_error ("Invalid image data `%s'", data, Qnil);
7985 return 0;
7987 success_p = imagemagick_load_image (f, img, SDATA (data),
7988 SBYTES (data), NULL);
7991 return success_p;
7994 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
7995 doc: /* Return a list of image types supported by ImageMagick.
7996 Each entry in this list is a symbol named after an ImageMagick format
7997 tag. See the ImageMagick manual for a list of ImageMagick formats and
7998 their descriptions (http://www.imagemagick.org/script/formats.php).
7999 You can also try the shell command: `identify -list format'.
8001 Note that ImageMagick recognizes many file-types that Emacs does not
8002 recognize as images, such as C. See `imagemagick-types-enable'
8003 and `imagemagick-types-inhibit'. */)
8004 (void)
8006 Lisp_Object typelist = Qnil;
8007 size_t numf = 0;
8008 ExceptionInfo ex;
8009 char **imtypes;
8010 size_t i;
8011 Lisp_Object Qimagemagicktype;
8013 GetExceptionInfo(&ex);
8014 imtypes = GetMagickList ("*", &numf, &ex);
8015 DestroyExceptionInfo(&ex);
8017 for (i = 0; i < numf; i++)
8019 Qimagemagicktype = intern (imtypes[i]);
8020 typelist = Fcons (Qimagemagicktype, typelist);
8022 return Fnreverse (typelist);
8025 #endif /* defined (HAVE_IMAGEMAGICK) */
8029 /***********************************************************************
8031 ***********************************************************************/
8033 #if defined (HAVE_RSVG)
8035 /* Function prototypes. */
8037 static bool svg_image_p (Lisp_Object object);
8038 static bool svg_load (struct frame *f, struct image *img);
8040 static bool svg_load_image (struct frame *, struct image *,
8041 unsigned char *, ptrdiff_t);
8043 /* The symbol `svg' identifying images of this type. */
8045 static Lisp_Object Qsvg;
8047 /* Indices of image specification fields in svg_format, below. */
8049 enum svg_keyword_index
8051 SVG_TYPE,
8052 SVG_DATA,
8053 SVG_FILE,
8054 SVG_ASCENT,
8055 SVG_MARGIN,
8056 SVG_RELIEF,
8057 SVG_ALGORITHM,
8058 SVG_HEURISTIC_MASK,
8059 SVG_MASK,
8060 SVG_BACKGROUND,
8061 SVG_LAST
8064 /* Vector of image_keyword structures describing the format
8065 of valid user-defined image specifications. */
8067 static const struct image_keyword svg_format[SVG_LAST] =
8069 {":type", IMAGE_SYMBOL_VALUE, 1},
8070 {":data", IMAGE_STRING_VALUE, 0},
8071 {":file", IMAGE_STRING_VALUE, 0},
8072 {":ascent", IMAGE_ASCENT_VALUE, 0},
8073 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8074 {":relief", IMAGE_INTEGER_VALUE, 0},
8075 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8076 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8077 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8078 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8081 #if defined HAVE_NTGUI && defined WINDOWSNT
8082 static bool init_svg_functions (void);
8083 #else
8084 #define init_svg_functions NULL
8085 #endif
8087 /* Structure describing the image type `svg'. Its the same type of
8088 structure defined for all image formats, handled by emacs image
8089 functions. See struct image_type in dispextern.h. */
8091 static struct image_type svg_type =
8093 &Qsvg,
8094 svg_image_p,
8095 svg_load,
8096 x_clear_image,
8097 init_svg_functions,
8098 NULL
8102 /* Return true if OBJECT is a valid SVG image specification. Do
8103 this by calling parse_image_spec and supplying the keywords that
8104 identify the SVG format. */
8106 static bool
8107 svg_image_p (Lisp_Object object)
8109 struct image_keyword fmt[SVG_LAST];
8110 memcpy (fmt, svg_format, sizeof fmt);
8112 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8113 return 0;
8115 /* Must specify either the :data or :file keyword. */
8116 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8119 #include <librsvg/rsvg.h>
8121 #ifdef WINDOWSNT
8123 /* SVG library functions. */
8124 DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new);
8125 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions);
8126 DEF_IMGLIB_FN (gboolean, rsvg_handle_write);
8127 DEF_IMGLIB_FN (gboolean, rsvg_handle_close);
8128 DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf);
8130 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width);
8131 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height);
8132 DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels);
8133 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride);
8134 DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace);
8135 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels);
8136 DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha);
8137 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample);
8139 DEF_IMGLIB_FN (void, g_type_init);
8140 DEF_IMGLIB_FN (void, g_object_unref);
8141 DEF_IMGLIB_FN (void, g_error_free);
8143 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8145 static bool
8146 init_svg_functions (void)
8148 HMODULE library, gdklib, glib, gobject;
8150 if (!(glib = w32_delayed_load (Qglib))
8151 || !(gobject = w32_delayed_load (Qgobject))
8152 || !(gdklib = w32_delayed_load (Qgdk_pixbuf))
8153 || !(library = w32_delayed_load (Qsvg)))
8154 return 0;
8156 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8157 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8158 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8159 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8160 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8162 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8163 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8164 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8165 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8166 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8167 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8168 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8169 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8171 LOAD_IMGLIB_FN (gobject, g_type_init);
8172 LOAD_IMGLIB_FN (gobject, g_object_unref);
8173 LOAD_IMGLIB_FN (glib, g_error_free);
8175 return 1;
8178 #else
8179 /* The following aliases for library functions allow dynamic loading
8180 to be used on some platforms. */
8181 #define fn_rsvg_handle_new rsvg_handle_new
8182 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8183 #define fn_rsvg_handle_write rsvg_handle_write
8184 #define fn_rsvg_handle_close rsvg_handle_close
8185 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8187 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8188 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8189 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8190 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8191 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8192 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8193 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8194 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8196 #define fn_g_type_init g_type_init
8197 #define fn_g_object_unref g_object_unref
8198 #define fn_g_error_free g_error_free
8199 #endif /* !WINDOWSNT */
8201 /* Load SVG image IMG for use on frame F. Value is true if
8202 successful. */
8204 static bool
8205 svg_load (struct frame *f, struct image *img)
8207 bool success_p = 0;
8208 Lisp_Object file_name;
8210 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8211 file_name = image_spec_value (img->spec, QCfile, NULL);
8212 if (STRINGP (file_name))
8214 Lisp_Object file;
8215 unsigned char *contents;
8216 ptrdiff_t size;
8218 file = x_find_image_file (file_name);
8219 if (!STRINGP (file))
8221 image_error ("Cannot find image file `%s'", file_name, Qnil);
8222 return 0;
8225 /* Read the entire file into memory. */
8226 contents = slurp_file (SSDATA (file), &size);
8227 if (contents == NULL)
8229 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8230 return 0;
8232 /* If the file was slurped into memory properly, parse it. */
8233 success_p = svg_load_image (f, img, contents, size);
8234 xfree (contents);
8236 /* Else its not a file, its a lisp object. Load the image from a
8237 lisp object rather than a file. */
8238 else
8240 Lisp_Object data;
8242 data = image_spec_value (img->spec, QCdata, NULL);
8243 if (!STRINGP (data))
8245 image_error ("Invalid image data `%s'", data, Qnil);
8246 return 0;
8248 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8251 return success_p;
8254 /* svg_load_image is a helper function for svg_load, which does the
8255 actual loading given contents and size, apart from frame and image
8256 structures, passed from svg_load.
8258 Uses librsvg to do most of the image processing.
8260 Returns true when successful. */
8261 static bool
8262 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8263 struct image *img, /* Pointer to emacs image structure. */
8264 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8265 ptrdiff_t size) /* Size of data in bytes. */
8267 RsvgHandle *rsvg_handle;
8268 RsvgDimensionData dimension_data;
8269 GError *err = NULL;
8270 GdkPixbuf *pixbuf;
8271 int width;
8272 int height;
8273 const guint8 *pixels;
8274 int rowstride;
8275 XImagePtr ximg;
8276 Lisp_Object specified_bg;
8277 XColor background;
8278 int x;
8279 int y;
8281 /* g_type_init is a glib function that must be called prior to using
8282 gnome type library functions. */
8283 fn_g_type_init ();
8284 /* Make a handle to a new rsvg object. */
8285 rsvg_handle = fn_rsvg_handle_new ();
8287 /* Parse the contents argument and fill in the rsvg_handle. */
8288 fn_rsvg_handle_write (rsvg_handle, contents, size, &err);
8289 if (err) goto rsvg_error;
8291 /* The parsing is complete, rsvg_handle is ready to used, close it
8292 for further writes. */
8293 fn_rsvg_handle_close (rsvg_handle, &err);
8294 if (err) goto rsvg_error;
8296 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8297 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8299 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8300 goto rsvg_error;
8303 /* We can now get a valid pixel buffer from the svg file, if all
8304 went ok. */
8305 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8306 if (!pixbuf) goto rsvg_error;
8307 fn_g_object_unref (rsvg_handle);
8309 /* Extract some meta data from the svg handle. */
8310 width = fn_gdk_pixbuf_get_width (pixbuf);
8311 height = fn_gdk_pixbuf_get_height (pixbuf);
8312 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8313 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8315 /* Validate the svg meta data. */
8316 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8317 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8318 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8319 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8321 /* Try to create a x pixmap to hold the svg pixmap. */
8322 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8324 fn_g_object_unref (pixbuf);
8325 return 0;
8328 init_color_table ();
8330 /* Handle alpha channel by combining the image with a background
8331 color. */
8332 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8333 if (!STRINGP (specified_bg)
8334 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
8336 #ifndef HAVE_NS
8337 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8338 x_query_color (f, &background);
8339 #else
8340 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8341 #endif
8344 /* SVG pixmaps specify transparency in the last byte, so right
8345 shift 8 bits to get rid of it, since emacs doesn't support
8346 transparency. */
8347 background.red >>= 8;
8348 background.green >>= 8;
8349 background.blue >>= 8;
8351 /* This loop handles opacity values, since Emacs assumes
8352 non-transparent images. Each pixel must be "flattened" by
8353 calculating the resulting color, given the transparency of the
8354 pixel, and the image background color. */
8355 for (y = 0; y < height; ++y)
8357 for (x = 0; x < width; ++x)
8359 int red;
8360 int green;
8361 int blue;
8362 int opacity;
8364 red = *pixels++;
8365 green = *pixels++;
8366 blue = *pixels++;
8367 opacity = *pixels++;
8369 red = ((red * opacity)
8370 + (background.red * ((1 << 8) - opacity)));
8371 green = ((green * opacity)
8372 + (background.green * ((1 << 8) - opacity)));
8373 blue = ((blue * opacity)
8374 + (background.blue * ((1 << 8) - opacity)));
8376 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8379 pixels += rowstride - 4 * width;
8382 #ifdef COLOR_TABLE_SUPPORT
8383 /* Remember colors allocated for this image. */
8384 img->colors = colors_in_color_table (&img->ncolors);
8385 free_color_table ();
8386 #endif /* COLOR_TABLE_SUPPORT */
8388 fn_g_object_unref (pixbuf);
8390 img->width = width;
8391 img->height = height;
8393 /* Maybe fill in the background field while we have ximg handy.
8394 Casting avoids a GCC warning. */
8395 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8397 /* Put the image into the pixmap, then free the X image and its
8398 buffer. */
8399 x_put_x_image (f, ximg, img->pixmap, width, height);
8400 x_destroy_x_image (ximg);
8402 return 1;
8404 rsvg_error:
8405 fn_g_object_unref (rsvg_handle);
8406 /* FIXME: Use error->message so the user knows what is the actual
8407 problem with the image. */
8408 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8409 fn_g_error_free (err);
8410 return 0;
8413 #endif /* defined (HAVE_RSVG) */
8418 /***********************************************************************
8419 Ghostscript
8420 ***********************************************************************/
8422 #ifdef HAVE_X_WINDOWS
8423 #define HAVE_GHOSTSCRIPT 1
8424 #endif /* HAVE_X_WINDOWS */
8426 #ifdef HAVE_GHOSTSCRIPT
8428 static bool gs_image_p (Lisp_Object object);
8429 static bool gs_load (struct frame *f, struct image *img);
8430 static void gs_clear_image (struct frame *f, struct image *img);
8432 /* Keyword symbols. */
8434 static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8436 /* Indices of image specification fields in gs_format, below. */
8438 enum gs_keyword_index
8440 GS_TYPE,
8441 GS_PT_WIDTH,
8442 GS_PT_HEIGHT,
8443 GS_FILE,
8444 GS_LOADER,
8445 GS_BOUNDING_BOX,
8446 GS_ASCENT,
8447 GS_MARGIN,
8448 GS_RELIEF,
8449 GS_ALGORITHM,
8450 GS_HEURISTIC_MASK,
8451 GS_MASK,
8452 GS_BACKGROUND,
8453 GS_LAST
8456 /* Vector of image_keyword structures describing the format
8457 of valid user-defined image specifications. */
8459 static const struct image_keyword gs_format[GS_LAST] =
8461 {":type", IMAGE_SYMBOL_VALUE, 1},
8462 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8463 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8464 {":file", IMAGE_STRING_VALUE, 1},
8465 {":loader", IMAGE_FUNCTION_VALUE, 0},
8466 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8467 {":ascent", IMAGE_ASCENT_VALUE, 0},
8468 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8469 {":relief", IMAGE_INTEGER_VALUE, 0},
8470 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8471 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8472 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8473 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8476 /* Structure describing the image type `ghostscript'. */
8478 static struct image_type gs_type =
8480 &Qpostscript,
8481 gs_image_p,
8482 gs_load,
8483 gs_clear_image,
8484 NULL,
8485 NULL
8489 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8491 static void
8492 gs_clear_image (struct frame *f, struct image *img)
8494 x_clear_image (f, img);
8498 /* Return true if OBJECT is a valid Ghostscript image
8499 specification. */
8501 static bool
8502 gs_image_p (Lisp_Object object)
8504 struct image_keyword fmt[GS_LAST];
8505 Lisp_Object tem;
8506 int i;
8508 memcpy (fmt, gs_format, sizeof fmt);
8510 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8511 return 0;
8513 /* Bounding box must be a list or vector containing 4 integers. */
8514 tem = fmt[GS_BOUNDING_BOX].value;
8515 if (CONSP (tem))
8517 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8518 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8519 return 0;
8520 if (!NILP (tem))
8521 return 0;
8523 else if (VECTORP (tem))
8525 if (ASIZE (tem) != 4)
8526 return 0;
8527 for (i = 0; i < 4; ++i)
8528 if (!INTEGERP (AREF (tem, i)))
8529 return 0;
8531 else
8532 return 0;
8534 return 1;
8538 /* Load Ghostscript image IMG for use on frame F. Value is true
8539 if successful. */
8541 static bool
8542 gs_load (struct frame *f, struct image *img)
8544 uprintmax_t printnum1, printnum2;
8545 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
8546 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8547 Lisp_Object frame;
8548 double in_width, in_height;
8549 Lisp_Object pixel_colors = Qnil;
8551 /* Compute pixel size of pixmap needed from the given size in the
8552 image specification. Sizes in the specification are in pt. 1 pt
8553 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8554 info. */
8555 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8556 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
8557 in_width *= FRAME_X_DISPLAY_INFO (f)->resx;
8558 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8559 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
8560 in_height *= FRAME_X_DISPLAY_INFO (f)->resy;
8562 if (! (in_width <= INT_MAX && in_height <= INT_MAX
8563 && check_image_size (f, in_width, in_height)))
8565 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8566 return 0;
8568 img->width = in_width;
8569 img->height = in_height;
8571 /* Create the pixmap. */
8572 eassert (img->pixmap == NO_PIXMAP);
8574 if (x_check_image_size (0, img->width, img->height))
8576 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8577 block_input ();
8578 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8579 img->width, img->height,
8580 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8581 unblock_input ();
8584 if (!img->pixmap)
8586 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8587 return 0;
8590 /* Call the loader to fill the pixmap. It returns a process object
8591 if successful. We do not record_unwind_protect here because
8592 other places in redisplay like calling window scroll functions
8593 don't either. Let the Lisp loader use `unwind-protect' instead. */
8594 printnum1 = FRAME_X_WINDOW (f);
8595 printnum2 = img->pixmap;
8596 window_and_pixmap_id
8597 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
8599 printnum1 = FRAME_FOREGROUND_PIXEL (f);
8600 printnum2 = FRAME_BACKGROUND_PIXEL (f);
8601 pixel_colors
8602 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
8604 XSETFRAME (frame, f);
8605 loader = image_spec_value (img->spec, QCloader, NULL);
8606 if (NILP (loader))
8607 loader = intern ("gs-load-image");
8609 img->lisp_data = call6 (loader, frame, img->spec,
8610 make_number (img->width),
8611 make_number (img->height),
8612 window_and_pixmap_id,
8613 pixel_colors);
8614 return PROCESSP (img->lisp_data);
8618 /* Kill the Ghostscript process that was started to fill PIXMAP on
8619 frame F. Called from XTread_socket when receiving an event
8620 telling Emacs that Ghostscript has finished drawing. */
8622 void
8623 x_kill_gs_process (Pixmap pixmap, struct frame *f)
8625 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8626 int class;
8627 ptrdiff_t i;
8628 struct image *img;
8630 /* Find the image containing PIXMAP. */
8631 for (i = 0; i < c->used; ++i)
8632 if (c->images[i]->pixmap == pixmap)
8633 break;
8635 /* Should someone in between have cleared the image cache, for
8636 instance, give up. */
8637 if (i == c->used)
8638 return;
8640 /* Kill the GS process. We should have found PIXMAP in the image
8641 cache and its image should contain a process object. */
8642 img = c->images[i];
8643 eassert (PROCESSP (img->lisp_data));
8644 Fkill_process (img->lisp_data, Qnil);
8645 img->lisp_data = Qnil;
8647 #if defined (HAVE_X_WINDOWS)
8649 /* On displays with a mutable colormap, figure out the colors
8650 allocated for the image by looking at the pixels of an XImage for
8651 img->pixmap. */
8652 class = FRAME_X_VISUAL (f)->class;
8653 if (class != StaticColor && class != StaticGray && class != TrueColor)
8655 XImagePtr ximg;
8657 block_input ();
8659 /* Try to get an XImage for img->pixmep. */
8660 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8661 0, 0, img->width, img->height, ~0, ZPixmap);
8662 if (ximg)
8664 int x, y;
8666 /* Initialize the color table. */
8667 init_color_table ();
8669 /* For each pixel of the image, look its color up in the
8670 color table. After having done so, the color table will
8671 contain an entry for each color used by the image. */
8672 for (y = 0; y < img->height; ++y)
8673 for (x = 0; x < img->width; ++x)
8675 unsigned long pixel = XGetPixel (ximg, x, y);
8676 lookup_pixel_color (f, pixel);
8679 /* Record colors in the image. Free color table and XImage. */
8680 #ifdef COLOR_TABLE_SUPPORT
8681 img->colors = colors_in_color_table (&img->ncolors);
8682 free_color_table ();
8683 #endif
8684 XDestroyImage (ximg);
8686 #if 0 /* This doesn't seem to be the case. If we free the colors
8687 here, we get a BadAccess later in x_clear_image when
8688 freeing the colors. */
8689 /* We have allocated colors once, but Ghostscript has also
8690 allocated colors on behalf of us. So, to get the
8691 reference counts right, free them once. */
8692 if (img->ncolors)
8693 x_free_colors (f, img->colors, img->ncolors);
8694 #endif
8696 else
8697 image_error ("Cannot get X image of `%s'; colors will not be freed",
8698 img->spec, Qnil);
8700 unblock_input ();
8702 #endif /* HAVE_X_WINDOWS */
8704 /* Now that we have the pixmap, compute mask and transform the
8705 image if requested. */
8706 block_input ();
8707 postprocess_image (f, img);
8708 unblock_input ();
8711 #endif /* HAVE_GHOSTSCRIPT */
8714 /***********************************************************************
8715 Tests
8716 ***********************************************************************/
8718 #ifdef GLYPH_DEBUG
8720 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8721 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8722 (Lisp_Object spec)
8724 return valid_image_p (spec) ? Qt : Qnil;
8728 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8729 (Lisp_Object spec)
8731 ptrdiff_t id = -1;
8733 if (valid_image_p (spec))
8734 id = lookup_image (SELECTED_FRAME (), spec);
8736 debug_print (spec);
8737 return make_number (id);
8740 #endif /* GLYPH_DEBUG */
8743 /***********************************************************************
8744 Initialization
8745 ***********************************************************************/
8747 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 1, 1, 0,
8748 doc: /* Initialize image library implementing image type TYPE.
8749 Return non-nil if TYPE is a supported image type.
8751 If image libraries are loaded dynamically (currently only the case on
8752 MS-Windows), load the library for TYPE if it is not yet loaded, using
8753 the library file(s) specified by `dynamic-library-alist'. */)
8754 (Lisp_Object type)
8756 return lookup_image_type (type) ? Qt : Qnil;
8759 /* Look up image type TYPE, and return a pointer to its image_type
8760 structure. Return 0 if TYPE is not a known image type. */
8762 static struct image_type *
8763 lookup_image_type (Lisp_Object type)
8765 /* Types pbm and xbm are built-in and always available. */
8766 if (EQ (type, Qpbm))
8767 return define_image_type (&pbm_type);
8769 if (EQ (type, Qxbm))
8770 return define_image_type (&xbm_type);
8772 #if defined (HAVE_XPM) || defined (HAVE_NS)
8773 if (EQ (type, Qxpm))
8774 return define_image_type (&xpm_type);
8775 #endif
8777 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8778 if (EQ (type, Qjpeg))
8779 return define_image_type (&jpeg_type);
8780 #endif
8782 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8783 if (EQ (type, Qtiff))
8784 return define_image_type (&tiff_type);
8785 #endif
8787 #if defined (HAVE_GIF) || defined (HAVE_NS)
8788 if (EQ (type, Qgif))
8789 return define_image_type (&gif_type);
8790 #endif
8792 #if defined (HAVE_PNG) || defined (HAVE_NS)
8793 if (EQ (type, Qpng))
8794 return define_image_type (&png_type);
8795 #endif
8797 #if defined (HAVE_RSVG)
8798 if (EQ (type, Qsvg))
8799 return define_image_type (&svg_type);
8800 #endif
8802 #if defined (HAVE_IMAGEMAGICK)
8803 if (EQ (type, Qimagemagick))
8804 return define_image_type (&imagemagick_type);
8805 #endif
8807 #ifdef HAVE_GHOSTSCRIPT
8808 if (EQ (type, Qpostscript))
8809 return define_image_type (&gs_type);
8810 #endif
8812 return NULL;
8815 /* Reset image_types before dumping.
8816 Called from Fdump_emacs. */
8818 void
8819 reset_image_types (void)
8821 while (image_types)
8823 struct image_type *next = image_types->next;
8824 xfree (image_types);
8825 image_types = next;
8829 void
8830 syms_of_image (void)
8832 /* Initialize this only once; it will be reset before dumping. */
8833 image_types = NULL;
8835 /* Must be defined now because we're going to update it below, while
8836 defining the supported image types. */
8837 DEFVAR_LISP ("image-types", Vimage_types,
8838 doc: /* List of potentially supported image types.
8839 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8840 To check whether it is really supported, use `image-type-available-p'. */);
8841 Vimage_types = Qnil;
8843 DEFVAR_LISP ("max-image-size", Vmax_image_size,
8844 doc: /* Maximum size of images.
8845 Emacs will not load an image into memory if its pixel width or
8846 pixel height exceeds this limit.
8848 If the value is an integer, it directly specifies the maximum
8849 image height and width, measured in pixels. If it is a floating
8850 point number, it specifies the maximum image height and width
8851 as a ratio to the frame height and width. If the value is
8852 non-numeric, there is no explicit limit on the size of images. */);
8853 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8855 DEFSYM (Qcount, "count");
8856 DEFSYM (Qextension_data, "extension-data");
8857 DEFSYM (Qdelay, "delay");
8859 DEFSYM (QCascent, ":ascent");
8860 DEFSYM (QCmargin, ":margin");
8861 DEFSYM (QCrelief, ":relief");
8862 DEFSYM (QCconversion, ":conversion");
8863 DEFSYM (QCcolor_symbols, ":color-symbols");
8864 DEFSYM (QCheuristic_mask, ":heuristic-mask");
8865 DEFSYM (QCindex, ":index");
8866 DEFSYM (QCgeometry, ":geometry");
8867 DEFSYM (QCcrop, ":crop");
8868 DEFSYM (QCrotation, ":rotation");
8869 DEFSYM (QCmatrix, ":matrix");
8870 DEFSYM (QCcolor_adjustment, ":color-adjustment");
8871 DEFSYM (QCmask, ":mask");
8873 DEFSYM (Qlaplace, "laplace");
8874 DEFSYM (Qemboss, "emboss");
8875 DEFSYM (Qedge_detection, "edge-detection");
8876 DEFSYM (Qheuristic, "heuristic");
8878 DEFSYM (Qpostscript, "postscript");
8879 #ifdef HAVE_GHOSTSCRIPT
8880 ADD_IMAGE_TYPE (Qpostscript);
8881 DEFSYM (QCloader, ":loader");
8882 DEFSYM (QCbounding_box, ":bounding-box");
8883 DEFSYM (QCpt_width, ":pt-width");
8884 DEFSYM (QCpt_height, ":pt-height");
8885 #endif /* HAVE_GHOSTSCRIPT */
8887 #ifdef HAVE_NTGUI
8888 DEFSYM (Qlibpng_version, "libpng-version");
8889 Fset (Qlibpng_version,
8890 #if HAVE_PNG
8891 make_number (PNG_LIBPNG_VER)
8892 #else
8893 make_number (-1)
8894 #endif
8896 #endif
8898 DEFSYM (Qpbm, "pbm");
8899 ADD_IMAGE_TYPE (Qpbm);
8901 DEFSYM (Qxbm, "xbm");
8902 ADD_IMAGE_TYPE (Qxbm);
8904 #if defined (HAVE_XPM) || defined (HAVE_NS)
8905 DEFSYM (Qxpm, "xpm");
8906 ADD_IMAGE_TYPE (Qxpm);
8907 #endif
8909 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8910 DEFSYM (Qjpeg, "jpeg");
8911 ADD_IMAGE_TYPE (Qjpeg);
8912 #endif
8914 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8915 DEFSYM (Qtiff, "tiff");
8916 ADD_IMAGE_TYPE (Qtiff);
8917 #endif
8919 #if defined (HAVE_GIF) || defined (HAVE_NS)
8920 DEFSYM (Qgif, "gif");
8921 ADD_IMAGE_TYPE (Qgif);
8922 #endif
8924 #if defined (HAVE_PNG) || defined (HAVE_NS)
8925 DEFSYM (Qpng, "png");
8926 ADD_IMAGE_TYPE (Qpng);
8927 #endif
8929 #if defined (HAVE_IMAGEMAGICK)
8930 DEFSYM (Qimagemagick, "imagemagick");
8931 ADD_IMAGE_TYPE (Qimagemagick);
8932 #endif
8934 #if defined (HAVE_RSVG)
8935 DEFSYM (Qsvg, "svg");
8936 ADD_IMAGE_TYPE (Qsvg);
8937 #ifdef HAVE_NTGUI
8938 /* Other libraries used directly by svg code. */
8939 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
8940 DEFSYM (Qglib, "glib");
8941 DEFSYM (Qgobject, "gobject");
8942 #endif /* HAVE_NTGUI */
8943 #endif /* HAVE_RSVG */
8945 defsubr (&Sinit_image_library);
8946 #ifdef HAVE_IMAGEMAGICK
8947 defsubr (&Simagemagick_types);
8948 #endif
8949 defsubr (&Sclear_image_cache);
8950 defsubr (&Simage_flush);
8951 defsubr (&Simage_size);
8952 defsubr (&Simage_mask_p);
8953 defsubr (&Simage_metadata);
8955 #ifdef GLYPH_DEBUG
8956 defsubr (&Simagep);
8957 defsubr (&Slookup_image);
8958 #endif
8960 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
8961 doc: /* Non-nil means always draw a cross over disabled images.
8962 Disabled images are those having a `:conversion disabled' property.
8963 A cross is always drawn on black & white displays. */);
8964 cross_disabled_images = 0;
8966 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
8967 doc: /* List of directories to search for window system bitmap files. */);
8968 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8970 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
8971 doc: /* Maximum time after which images are removed from the cache.
8972 When an image has not been displayed this many seconds, Emacs
8973 automatically removes it from the image cache. If the cache contains
8974 a large number of images, the actual eviction time may be shorter.
8975 The value can also be nil, meaning the cache is never cleared.
8977 The function `clear-image-cache' disregards this variable. */);
8978 Vimage_cache_eviction_delay = make_number (300);
8979 #ifdef HAVE_IMAGEMAGICK
8980 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
8981 doc: /* Integer indicating which ImageMagick rendering method to use.
8982 The options are:
8983 0 -- the default method (pixel pushing)
8984 1 -- a newer method ("MagickExportImagePixels") that may perform
8985 better (speed etc) in some cases, but has not been as thoroughly
8986 tested with Emacs as the default method. This method requires
8987 ImageMagick version 6.4.6 (approximately) or later.
8988 */);
8989 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
8990 imagemagick_render_type = 0;
8991 #endif