* net/tramp.el (tramp-temp-buffer-file-name): Make it permanent-local.
[emacs.git] / src / image.c
blob828c2d319befecbdb9d14a836c7364aaeff7ddf3
1 /* Functions for image support on window system.
2 Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <stdio.h>
23 #include <math.h>
24 #include <ctype.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
30 #ifdef HAVE_PNG
31 #if defined HAVE_LIBPNG_PNG_H
32 # include <libpng/png.h>
33 #else
34 # include <png.h>
35 #endif
36 #endif
38 #include <setjmp.h>
40 /* This makes the fields of a Display accessible, in Xlib header files. */
42 #define XLIB_ILLEGAL_ACCESS
44 #include "lisp.h"
45 #include "frame.h"
46 #include "window.h"
47 #include "dispextern.h"
48 #include "blockinput.h"
49 #include "systime.h"
50 #include <epaths.h>
51 #include "character.h"
52 #include "coding.h"
53 #include "termhooks.h"
54 #include "font.h"
56 #ifdef HAVE_X_WINDOWS
57 #include "xterm.h"
58 #include <sys/types.h>
59 #include <sys/stat.h>
61 #define COLOR_TABLE_SUPPORT 1
63 typedef struct x_bitmap_record Bitmap_Record;
64 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
65 #define NO_PIXMAP None
67 #define RGB_PIXEL_COLOR unsigned long
69 #define PIX_MASK_RETAIN 0
70 #define PIX_MASK_DRAW 1
71 #endif /* HAVE_X_WINDOWS */
74 #ifdef HAVE_NTGUI
75 #include "w32term.h"
77 /* W32_TODO : Color tables on W32. */
78 #undef COLOR_TABLE_SUPPORT
80 typedef struct w32_bitmap_record Bitmap_Record;
81 #define GET_PIXEL(ximg, x, y) GetPixel(ximg, x, y)
82 #define NO_PIXMAP 0
84 #define RGB_PIXEL_COLOR COLORREF
86 #define PIX_MASK_RETAIN 0
87 #define PIX_MASK_DRAW 1
89 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
90 #define x_defined_color w32_defined_color
91 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
93 /* Functions from w32term.c that depend on XColor (so can't go in w32term.h
94 without modifying lots of files). */
95 extern void x_query_colors (struct frame *f, XColor *colors, int ncolors);
96 extern void x_query_color (struct frame *f, XColor *color);
97 #endif /* HAVE_NTGUI */
99 #ifdef HAVE_NS
100 #include "nsterm.h"
101 #include <sys/types.h>
102 #include <sys/stat.h>
104 #undef COLOR_TABLE_SUPPORT
106 typedef struct ns_bitmap_record Bitmap_Record;
108 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
109 #define NO_PIXMAP 0
111 #define RGB_PIXEL_COLOR unsigned long
112 #define ZPixmap 0
114 #define PIX_MASK_RETAIN 0
115 #define PIX_MASK_DRAW 1
117 #define FRAME_X_VISUAL FRAME_NS_DISPLAY_INFO(f)->visual
118 #define x_defined_color(f, name, color_def, alloc) \
119 ns_defined_color (f, name, color_def, alloc, 0)
120 #define FRAME_X_SCREEN(f) 0
121 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
122 #endif /* HAVE_NS */
125 /* Search path for bitmap files. */
127 Lisp_Object Vx_bitmap_file_path;
129 /* The symbol `postscript' identifying images of this type. */
131 Lisp_Object Qpostscript;
133 static void x_disable_image (struct frame *, struct image *);
134 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
135 Lisp_Object);
137 static void init_color_table (void);
138 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
139 #ifdef COLOR_TABLE_SUPPORT
140 static void free_color_table (void);
141 static unsigned long *colors_in_color_table (int *n);
142 static unsigned long lookup_pixel_color (struct frame *f, unsigned long p);
143 #endif
145 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
146 id, which is just an int that this section returns. Bitmaps are
147 reference counted so they can be shared among frames.
149 Bitmap indices are guaranteed to be > 0, so a negative number can
150 be used to indicate no bitmap.
152 If you use x_create_bitmap_from_data, then you must keep track of
153 the bitmaps yourself. That is, creating a bitmap from the same
154 data more than once will not be caught. */
156 #ifdef HAVE_NS
157 XImagePtr
158 XGetImage (Display *display, Pixmap pixmap, int x, int y,
159 unsigned int width, unsigned int height,
160 unsigned long plane_mask, int format)
162 /* TODO: not sure what this function is supposed to do.. */
163 ns_retain_object (pixmap);
164 return pixmap;
167 /* use with imgs created by ns_image_for_XPM */
168 unsigned long
169 XGetPixel (XImagePtr ximage, int x, int y)
171 return ns_get_pixel (ximage, x, y);
174 /* use with imgs created by ns_image_for_XPM; alpha set to 1;
175 pixel is assumed to be in form RGB */
176 void
177 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
179 ns_put_pixel (ximage, x, y, pixel);
181 #endif /* HAVE_NS */
184 /* Functions to access the contents of a bitmap, given an id. */
187 x_bitmap_height (FRAME_PTR f, int id)
189 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
193 x_bitmap_width (FRAME_PTR f, int id)
195 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
198 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
200 x_bitmap_pixmap (FRAME_PTR f, int id)
202 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
204 #endif
206 #ifdef HAVE_X_WINDOWS
208 x_bitmap_mask (FRAME_PTR f, int id)
210 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
212 #endif
214 /* Allocate a new bitmap record. Returns index of new record. */
216 static int
217 x_allocate_bitmap_record (FRAME_PTR f)
219 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
220 int i;
222 if (dpyinfo->bitmaps == NULL)
224 dpyinfo->bitmaps_size = 10;
225 dpyinfo->bitmaps
226 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
227 dpyinfo->bitmaps_last = 1;
228 return 1;
231 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
232 return ++dpyinfo->bitmaps_last;
234 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
235 if (dpyinfo->bitmaps[i].refcount == 0)
236 return i + 1;
238 dpyinfo->bitmaps_size *= 2;
239 dpyinfo->bitmaps
240 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
241 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
242 return ++dpyinfo->bitmaps_last;
245 /* Add one reference to the reference count of the bitmap with id ID. */
247 void
248 x_reference_bitmap (FRAME_PTR f, int id)
250 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
253 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
256 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
258 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
259 int id;
261 #ifdef HAVE_X_WINDOWS
262 Pixmap bitmap;
263 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
264 bits, width, height);
265 if (! bitmap)
266 return -1;
267 #endif /* HAVE_X_WINDOWS */
269 #ifdef HAVE_NTGUI
270 Pixmap bitmap;
271 bitmap = CreateBitmap (width, height,
272 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
273 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
274 bits);
275 if (! bitmap)
276 return -1;
277 #endif /* HAVE_NTGUI */
279 #ifdef HAVE_NS
280 void *bitmap = ns_image_from_XBM (bits, width, height);
281 if (!bitmap)
282 return -1;
283 #endif
285 id = x_allocate_bitmap_record (f);
287 #ifdef HAVE_NS
288 dpyinfo->bitmaps[id - 1].img = bitmap;
289 dpyinfo->bitmaps[id - 1].depth = 1;
290 #endif
292 dpyinfo->bitmaps[id - 1].file = NULL;
293 dpyinfo->bitmaps[id - 1].height = height;
294 dpyinfo->bitmaps[id - 1].width = width;
295 dpyinfo->bitmaps[id - 1].refcount = 1;
297 #ifdef HAVE_X_WINDOWS
298 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
299 dpyinfo->bitmaps[id - 1].have_mask = 0;
300 dpyinfo->bitmaps[id - 1].depth = 1;
301 #endif /* HAVE_X_WINDOWS */
303 #ifdef HAVE_NTGUI
304 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
305 dpyinfo->bitmaps[id - 1].hinst = NULL;
306 dpyinfo->bitmaps[id - 1].depth = 1;
307 #endif /* HAVE_NTGUI */
309 return id;
312 /* Create bitmap from file FILE for frame F. */
315 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
317 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
319 #ifdef HAVE_NTGUI
320 return -1; /* W32_TODO : bitmap support */
321 #endif /* HAVE_NTGUI */
323 #ifdef HAVE_NS
324 int id;
325 void *bitmap = ns_image_from_file (file);
327 if (!bitmap)
328 return -1;
331 id = x_allocate_bitmap_record (f);
332 dpyinfo->bitmaps[id - 1].img = bitmap;
333 dpyinfo->bitmaps[id - 1].refcount = 1;
334 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
335 dpyinfo->bitmaps[id - 1].depth = 1;
336 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
337 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
338 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
339 return id;
340 #endif
342 #ifdef HAVE_X_WINDOWS
343 unsigned int width, height;
344 Pixmap bitmap;
345 int xhot, yhot, result, id;
346 Lisp_Object found;
347 int fd;
348 char *filename;
350 /* Look for an existing bitmap with the same name. */
351 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
353 if (dpyinfo->bitmaps[id].refcount
354 && dpyinfo->bitmaps[id].file
355 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
357 ++dpyinfo->bitmaps[id].refcount;
358 return id + 1;
362 /* Search bitmap-file-path for the file, if appropriate. */
363 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
364 if (fd < 0)
365 return -1;
366 emacs_close (fd);
368 filename = (char *) SDATA (found);
370 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
371 filename, &width, &height, &bitmap, &xhot, &yhot);
372 if (result != BitmapSuccess)
373 return -1;
375 id = x_allocate_bitmap_record (f);
376 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
377 dpyinfo->bitmaps[id - 1].have_mask = 0;
378 dpyinfo->bitmaps[id - 1].refcount = 1;
379 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
380 dpyinfo->bitmaps[id - 1].depth = 1;
381 dpyinfo->bitmaps[id - 1].height = height;
382 dpyinfo->bitmaps[id - 1].width = width;
383 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
385 return id;
386 #endif /* HAVE_X_WINDOWS */
389 /* Free bitmap B. */
391 static void
392 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
394 #ifdef HAVE_X_WINDOWS
395 XFreePixmap (dpyinfo->display, bm->pixmap);
396 if (bm->have_mask)
397 XFreePixmap (dpyinfo->display, bm->mask);
398 #endif /* HAVE_X_WINDOWS */
400 #ifdef HAVE_NTGUI
401 DeleteObject (bm->pixmap);
402 #endif /* HAVE_NTGUI */
404 #ifdef HAVE_NS
405 ns_release_object (bm->img);
406 #endif
408 if (bm->file)
410 xfree (bm->file);
411 bm->file = NULL;
415 /* Remove reference to bitmap with id number ID. */
417 void
418 x_destroy_bitmap (FRAME_PTR f, int id)
420 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
422 if (id > 0)
424 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
426 if (--bm->refcount == 0)
428 BLOCK_INPUT;
429 free_bitmap_record (dpyinfo, bm);
430 UNBLOCK_INPUT;
435 /* Free all the bitmaps for the display specified by DPYINFO. */
437 void
438 x_destroy_all_bitmaps (Display_Info *dpyinfo)
440 int i;
441 Bitmap_Record *bm = dpyinfo->bitmaps;
443 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
444 if (bm->refcount > 0)
445 free_bitmap_record (dpyinfo, bm);
447 dpyinfo->bitmaps_last = 0;
451 #ifdef HAVE_X_WINDOWS
453 /* Useful functions defined in the section
454 `Image type independent image structures' below. */
456 static unsigned long four_corners_best (XImagePtr ximg,
457 int *corners,
458 unsigned long width,
459 unsigned long height);
461 static int x_create_x_image_and_pixmap (struct frame *f, int width, int height,
462 int depth, XImagePtr *ximg,
463 Pixmap *pixmap);
465 static void x_destroy_x_image (XImagePtr ximg);
468 /* Create a mask of a bitmap. Note is this not a perfect mask.
469 It's nicer with some borders in this context */
472 x_create_bitmap_mask (struct frame *f, int id)
474 Pixmap pixmap, mask;
475 XImagePtr ximg, mask_img;
476 unsigned long width, height;
477 int result;
478 unsigned long bg;
479 unsigned long x, y, xp, xm, yp, ym;
480 GC gc;
482 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
484 if (!(id > 0))
485 return -1;
487 pixmap = x_bitmap_pixmap (f, id);
488 width = x_bitmap_width (f, id);
489 height = x_bitmap_height (f, id);
491 BLOCK_INPUT;
492 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
493 ~0, ZPixmap);
495 if (!ximg)
497 UNBLOCK_INPUT;
498 return -1;
501 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
503 UNBLOCK_INPUT;
504 if (!result)
506 XDestroyImage (ximg);
507 return -1;
510 bg = four_corners_best (ximg, NULL, width, height);
512 for (y = 0; y < ximg->height; ++y)
514 for (x = 0; x < ximg->width; ++x)
516 xp = x != ximg->width - 1 ? x + 1 : 0;
517 xm = x != 0 ? x - 1 : ximg->width - 1;
518 yp = y != ximg->height - 1 ? y + 1 : 0;
519 ym = y != 0 ? y - 1 : ximg->height - 1;
520 if (XGetPixel (ximg, x, y) == bg
521 && XGetPixel (ximg, x, yp) == bg
522 && XGetPixel (ximg, x, ym) == bg
523 && XGetPixel (ximg, xp, y) == bg
524 && XGetPixel (ximg, xp, yp) == bg
525 && XGetPixel (ximg, xp, ym) == bg
526 && XGetPixel (ximg, xm, y) == bg
527 && XGetPixel (ximg, xm, yp) == bg
528 && XGetPixel (ximg, xm, ym) == bg)
529 XPutPixel (mask_img, x, y, 0);
530 else
531 XPutPixel (mask_img, x, y, 1);
535 xassert (interrupt_input_blocked);
536 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
537 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
538 width, height);
539 XFreeGC (FRAME_X_DISPLAY (f), gc);
541 dpyinfo->bitmaps[id - 1].have_mask = 1;
542 dpyinfo->bitmaps[id - 1].mask = mask;
544 XDestroyImage (ximg);
545 x_destroy_x_image (mask_img);
547 return 0;
550 #endif /* HAVE_X_WINDOWS */
553 /***********************************************************************
554 Image types
555 ***********************************************************************/
557 /* Value is the number of elements of vector VECTOR. */
559 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
561 /* List of supported image types. Use define_image_type to add new
562 types. Use lookup_image_type to find a type for a given symbol. */
564 static struct image_type *image_types;
566 /* A list of symbols, one for each supported image type. */
568 Lisp_Object Vimage_types;
570 /* Cache for delayed-loading image types. */
572 static Lisp_Object Vimage_type_cache;
574 /* The symbol `xbm' which is used as the type symbol for XBM images. */
576 Lisp_Object Qxbm;
578 /* Keywords. */
580 Lisp_Object QCascent, QCmargin, QCrelief, Qcount, Qextension_data;
581 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
582 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry, QCcrop, QCrotation;
584 /* Other symbols. */
586 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
588 /* Time in seconds after which images should be removed from the cache
589 if not displayed. */
591 Lisp_Object Vimage_cache_eviction_delay;
593 /* Function prototypes. */
595 static Lisp_Object define_image_type (struct image_type *type, int loaded);
596 static struct image_type *lookup_image_type (Lisp_Object symbol);
597 static void image_error (const char *format, Lisp_Object, Lisp_Object);
598 static void x_laplace (struct frame *, struct image *);
599 static void x_emboss (struct frame *, struct image *);
600 static int x_build_heuristic_mask (struct frame *, struct image *,
601 Lisp_Object);
603 #define CACHE_IMAGE_TYPE(type, status) \
604 do { Vimage_type_cache = Fcons (Fcons (type, status), Vimage_type_cache); } while (0)
606 #define ADD_IMAGE_TYPE(type) \
607 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
609 /* Define a new image type from TYPE. This adds a copy of TYPE to
610 image_types and caches the loading status of TYPE. */
612 static Lisp_Object
613 define_image_type (struct image_type *type, int loaded)
615 Lisp_Object success;
617 if (!loaded)
618 success = Qnil;
619 else
621 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
622 The initialized data segment is read-only. */
623 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
624 memcpy (p, type, sizeof *p);
625 p->next = image_types;
626 image_types = p;
627 success = Qt;
630 CACHE_IMAGE_TYPE (*type->type, success);
631 return success;
635 /* Look up image type SYMBOL, and return a pointer to its image_type
636 structure. Value is null if SYMBOL is not a known image type. */
638 static INLINE struct image_type *
639 lookup_image_type (Lisp_Object symbol)
641 struct image_type *type;
643 /* We must initialize the image-type if it hasn't been already. */
644 if (NILP (Finit_image_library (symbol, Vdynamic_library_alist)))
645 return 0; /* unimplemented */
647 for (type = image_types; type; type = type->next)
648 if (EQ (symbol, *type->type))
649 break;
651 return type;
655 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
656 valid image specification is a list whose car is the symbol
657 `image', and whose rest is a property list. The property list must
658 contain a value for key `:type'. That value must be the name of a
659 supported image type. The rest of the property list depends on the
660 image type. */
663 valid_image_p (Lisp_Object object)
665 int valid_p = 0;
667 if (IMAGEP (object))
669 Lisp_Object tem;
671 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
672 if (EQ (XCAR (tem), QCtype))
674 tem = XCDR (tem);
675 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
677 struct image_type *type;
678 type = lookup_image_type (XCAR (tem));
679 if (type)
680 valid_p = type->valid_p (object);
683 break;
687 return valid_p;
691 /* Log error message with format string FORMAT and argument ARG.
692 Signaling an error, e.g. when an image cannot be loaded, is not a
693 good idea because this would interrupt redisplay, and the error
694 message display would lead to another redisplay. This function
695 therefore simply displays a message. */
697 static void
698 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
700 add_to_log (format, arg1, arg2);
705 /***********************************************************************
706 Image specifications
707 ***********************************************************************/
709 enum image_value_type
711 IMAGE_DONT_CHECK_VALUE_TYPE,
712 IMAGE_STRING_VALUE,
713 IMAGE_STRING_OR_NIL_VALUE,
714 IMAGE_SYMBOL_VALUE,
715 IMAGE_POSITIVE_INTEGER_VALUE,
716 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
717 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
718 IMAGE_ASCENT_VALUE,
719 IMAGE_INTEGER_VALUE,
720 IMAGE_FUNCTION_VALUE,
721 IMAGE_NUMBER_VALUE,
722 IMAGE_BOOL_VALUE
725 /* Structure used when parsing image specifications. */
727 struct image_keyword
729 /* Name of keyword. */
730 const char *name;
732 /* The type of value allowed. */
733 enum image_value_type type;
735 /* Non-zero means key must be present. */
736 int mandatory_p;
738 /* Used to recognize duplicate keywords in a property list. */
739 int count;
741 /* The value that was found. */
742 Lisp_Object value;
746 static int parse_image_spec (Lisp_Object, struct image_keyword *,
747 int, Lisp_Object);
748 static Lisp_Object image_spec_value (Lisp_Object, Lisp_Object, int *);
751 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
752 has the format (image KEYWORD VALUE ...). One of the keyword/
753 value pairs must be `:type TYPE'. KEYWORDS is a vector of
754 image_keywords structures of size NKEYWORDS describing other
755 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
757 static int
758 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
759 int nkeywords, Lisp_Object type)
761 int i;
762 Lisp_Object plist;
764 if (!IMAGEP (spec))
765 return 0;
767 plist = XCDR (spec);
768 while (CONSP (plist))
770 Lisp_Object key, value;
772 /* First element of a pair must be a symbol. */
773 key = XCAR (plist);
774 plist = XCDR (plist);
775 if (!SYMBOLP (key))
776 return 0;
778 /* There must follow a value. */
779 if (!CONSP (plist))
780 return 0;
781 value = XCAR (plist);
782 plist = XCDR (plist);
784 /* Find key in KEYWORDS. Error if not found. */
785 for (i = 0; i < nkeywords; ++i)
786 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
787 break;
789 if (i == nkeywords)
790 continue;
792 /* Record that we recognized the keyword. If a keywords
793 was found more than once, it's an error. */
794 keywords[i].value = value;
795 ++keywords[i].count;
797 if (keywords[i].count > 1)
798 return 0;
800 /* Check type of value against allowed type. */
801 switch (keywords[i].type)
803 case IMAGE_STRING_VALUE:
804 if (!STRINGP (value))
805 return 0;
806 break;
808 case IMAGE_STRING_OR_NIL_VALUE:
809 if (!STRINGP (value) && !NILP (value))
810 return 0;
811 break;
813 case IMAGE_SYMBOL_VALUE:
814 if (!SYMBOLP (value))
815 return 0;
816 break;
818 case IMAGE_POSITIVE_INTEGER_VALUE:
819 if (!INTEGERP (value) || XINT (value) <= 0)
820 return 0;
821 break;
823 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
824 if (INTEGERP (value) && XINT (value) >= 0)
825 break;
826 if (CONSP (value)
827 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
828 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
829 break;
830 return 0;
832 case IMAGE_ASCENT_VALUE:
833 if (SYMBOLP (value) && EQ (value, Qcenter))
834 break;
835 else if (INTEGERP (value)
836 && XINT (value) >= 0
837 && XINT (value) <= 100)
838 break;
839 return 0;
841 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
842 if (!INTEGERP (value) || XINT (value) < 0)
843 return 0;
844 break;
846 case IMAGE_DONT_CHECK_VALUE_TYPE:
847 break;
849 case IMAGE_FUNCTION_VALUE:
850 value = indirect_function (value);
851 if (SUBRP (value)
852 || COMPILEDP (value)
853 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
854 break;
855 return 0;
857 case IMAGE_NUMBER_VALUE:
858 if (!INTEGERP (value) && !FLOATP (value))
859 return 0;
860 break;
862 case IMAGE_INTEGER_VALUE:
863 if (!INTEGERP (value))
864 return 0;
865 break;
867 case IMAGE_BOOL_VALUE:
868 if (!NILP (value) && !EQ (value, Qt))
869 return 0;
870 break;
872 default:
873 abort ();
874 break;
877 if (EQ (key, QCtype) && !EQ (type, value))
878 return 0;
881 /* Check that all mandatory fields are present. */
882 for (i = 0; i < nkeywords; ++i)
883 if (keywords[i].mandatory_p && keywords[i].count == 0)
884 return 0;
886 return NILP (plist);
890 /* Return the value of KEY in image specification SPEC. Value is nil
891 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
892 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
894 static Lisp_Object
895 image_spec_value (Lisp_Object spec, Lisp_Object key, int *found)
897 Lisp_Object tail;
899 xassert (valid_image_p (spec));
901 for (tail = XCDR (spec);
902 CONSP (tail) && CONSP (XCDR (tail));
903 tail = XCDR (XCDR (tail)))
905 if (EQ (XCAR (tail), key))
907 if (found)
908 *found = 1;
909 return XCAR (XCDR (tail));
913 if (found)
914 *found = 0;
915 return Qnil;
919 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
920 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
921 PIXELS non-nil means return the size in pixels, otherwise return the
922 size in canonical character units.
923 FRAME is the frame on which the image will be displayed. FRAME nil
924 or omitted means use the selected frame. */)
925 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
927 Lisp_Object size;
929 size = Qnil;
930 if (valid_image_p (spec))
932 struct frame *f = check_x_frame (frame);
933 int id = lookup_image (f, spec);
934 struct image *img = IMAGE_FROM_ID (f, id);
935 int width = img->width + 2 * img->hmargin;
936 int height = img->height + 2 * img->vmargin;
938 if (NILP (pixels))
939 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
940 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
941 else
942 size = Fcons (make_number (width), make_number (height));
944 else
945 error ("Invalid image specification");
947 return size;
951 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
952 doc: /* Return t if image SPEC has a mask bitmap.
953 FRAME is the frame on which the image will be displayed. FRAME nil
954 or omitted means use the selected frame. */)
955 (Lisp_Object spec, Lisp_Object frame)
957 Lisp_Object mask;
959 mask = Qnil;
960 if (valid_image_p (spec))
962 struct frame *f = check_x_frame (frame);
963 int id = lookup_image (f, spec);
964 struct image *img = IMAGE_FROM_ID (f, id);
965 if (img->mask)
966 mask = Qt;
968 else
969 error ("Invalid image specification");
971 return mask;
974 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
975 doc: /* Return metadata for image SPEC.
976 FRAME is the frame on which the image will be displayed. FRAME nil
977 or omitted means use the selected frame. */)
978 (Lisp_Object spec, Lisp_Object frame)
980 Lisp_Object ext;
982 ext = Qnil;
983 if (valid_image_p (spec))
985 struct frame *f = check_x_frame (frame);
986 int id = lookup_image (f, spec);
987 struct image *img = IMAGE_FROM_ID (f, id);
988 ext = img->data.lisp_val;
991 return ext;
995 /***********************************************************************
996 Image type independent image structures
997 ***********************************************************************/
999 static struct image *make_image (Lisp_Object spec, unsigned hash);
1000 static void free_image (struct frame *f, struct image *img);
1001 static int check_image_size (struct frame *f, int width, int height);
1003 #define MAX_IMAGE_SIZE 6.0
1004 Lisp_Object Vmax_image_size;
1006 /* Allocate and return a new image structure for image specification
1007 SPEC. SPEC has a hash value of HASH. */
1009 static struct image *
1010 make_image (Lisp_Object spec, unsigned int hash)
1012 struct image *img = (struct image *) xmalloc (sizeof *img);
1013 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
1015 xassert (valid_image_p (spec));
1016 memset (img, 0, sizeof *img);
1017 img->dependencies = NILP (file) ? Qnil : list1 (file);
1018 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1019 xassert (img->type != NULL);
1020 img->spec = spec;
1021 img->data.lisp_val = Qnil;
1022 img->ascent = DEFAULT_IMAGE_ASCENT;
1023 img->hash = hash;
1024 img->corners[BOT_CORNER] = -1; /* Full image */
1025 return img;
1029 /* Free image IMG which was used on frame F, including its resources. */
1031 static void
1032 free_image (struct frame *f, struct image *img)
1034 if (img)
1036 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1038 /* Remove IMG from the hash table of its cache. */
1039 if (img->prev)
1040 img->prev->next = img->next;
1041 else
1042 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1044 if (img->next)
1045 img->next->prev = img->prev;
1047 c->images[img->id] = NULL;
1049 /* Free resources, then free IMG. */
1050 img->type->free (f, img);
1051 xfree (img);
1055 /* Return 1 if the given widths and heights are valid for display;
1056 otherwise, return 0. */
1059 check_image_size (struct frame *f, int width, int height)
1061 int w, h;
1063 if (width <= 0 || height <= 0)
1064 return 0;
1066 if (INTEGERP (Vmax_image_size))
1067 w = h = XINT (Vmax_image_size);
1068 else if (FLOATP (Vmax_image_size))
1070 if (f != NULL)
1072 w = FRAME_PIXEL_WIDTH (f);
1073 h = FRAME_PIXEL_HEIGHT (f);
1075 else
1076 w = h = 1024; /* Arbitrary size for unknown frame. */
1077 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1078 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1080 else
1081 return 1;
1083 return (width <= w && height <= h);
1086 /* Prepare image IMG for display on frame F. Must be called before
1087 drawing an image. */
1089 void
1090 prepare_image_for_display (struct frame *f, struct image *img)
1092 EMACS_TIME t;
1094 /* We're about to display IMG, so set its timestamp to `now'. */
1095 EMACS_GET_TIME (t);
1096 img->timestamp = EMACS_SECS (t);
1098 /* If IMG doesn't have a pixmap yet, load it now, using the image
1099 type dependent loader function. */
1100 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1101 img->load_failed_p = img->type->load (f, img) == 0;
1106 /* Value is the number of pixels for the ascent of image IMG when
1107 drawn in face FACE. */
1110 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1112 int height;
1113 int ascent;
1115 if (slice->height == img->height)
1116 height = img->height + img->vmargin;
1117 else if (slice->y == 0)
1118 height = slice->height + img->vmargin;
1119 else
1120 height = slice->height;
1122 if (img->ascent == CENTERED_IMAGE_ASCENT)
1124 if (face->font)
1126 #ifdef HAVE_NTGUI
1127 /* W32 specific version. Why?. ++kfs */
1128 ascent = height / 2 - (FONT_DESCENT (face->font)
1129 - FONT_BASE (face->font)) / 2;
1130 #else
1131 /* This expression is arranged so that if the image can't be
1132 exactly centered, it will be moved slightly up. This is
1133 because a typical font is `top-heavy' (due to the presence
1134 uppercase letters), so the image placement should err towards
1135 being top-heavy too. It also just generally looks better. */
1136 ascent = (height + FONT_BASE(face->font)
1137 - FONT_DESCENT(face->font) + 1) / 2;
1138 #endif /* HAVE_NTGUI */
1140 else
1141 ascent = height / 2;
1143 else
1144 ascent = (int) (height * img->ascent / 100.0);
1146 return ascent;
1150 /* Image background colors. */
1152 /* Find the "best" corner color of a bitmap.
1153 On W32, XIMG is assumed to a device context with the bitmap selected. */
1155 static RGB_PIXEL_COLOR
1156 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1157 unsigned long width, unsigned long height)
1159 RGB_PIXEL_COLOR corner_pixels[4], best;
1160 int i, best_count;
1162 if (corners && corners[BOT_CORNER] >= 0)
1164 /* Get the colors at the corner_pixels of ximg. */
1165 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1166 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1167 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1168 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1170 else
1172 /* Get the colors at the corner_pixels of ximg. */
1173 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1174 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1175 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1176 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1178 /* Choose the most frequently found color as background. */
1179 for (i = best_count = 0; i < 4; ++i)
1181 int j, n;
1183 for (j = n = 0; j < 4; ++j)
1184 if (corner_pixels[i] == corner_pixels[j])
1185 ++n;
1187 if (n > best_count)
1188 best = corner_pixels[i], best_count = n;
1191 return best;
1194 /* Portability macros */
1196 #ifdef HAVE_NTGUI
1198 #define Destroy_Image(img_dc, prev) \
1199 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1201 #define Free_Pixmap(display, pixmap) \
1202 DeleteObject (pixmap)
1204 #elif defined (HAVE_NS)
1206 #define Destroy_Image(ximg, dummy) \
1207 ns_release_object (ximg)
1209 #define Free_Pixmap(display, pixmap) \
1210 ns_release_object (pixmap)
1212 #else
1214 #define Destroy_Image(ximg, dummy) \
1215 XDestroyImage (ximg)
1217 #define Free_Pixmap(display, pixmap) \
1218 XFreePixmap (display, pixmap)
1220 #endif /* !HAVE_NTGUI && !HAVE_NS */
1223 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1224 it is guessed heuristically. If non-zero, XIMG is an existing
1225 XImage object (or device context with the image selected on W32) to
1226 use for the heuristic. */
1228 RGB_PIXEL_COLOR
1229 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1231 if (! img->background_valid)
1232 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1234 int free_ximg = !ximg;
1235 #ifdef HAVE_NTGUI
1236 HGDIOBJ prev;
1237 #endif /* HAVE_NTGUI */
1239 if (free_ximg)
1241 #ifndef HAVE_NTGUI
1242 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1243 0, 0, img->width, img->height, ~0, ZPixmap);
1244 #else
1245 HDC frame_dc = get_frame_dc (f);
1246 ximg = CreateCompatibleDC (frame_dc);
1247 release_frame_dc (f, frame_dc);
1248 prev = SelectObject (ximg, img->pixmap);
1249 #endif /* !HAVE_NTGUI */
1252 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1254 if (free_ximg)
1255 Destroy_Image (ximg, prev);
1257 img->background_valid = 1;
1260 return img->background;
1263 /* Return the `background_transparent' field of IMG. If IMG doesn't
1264 have one yet, it is guessed heuristically. If non-zero, MASK is an
1265 existing XImage object to use for the heuristic. */
1268 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1270 if (! img->background_transparent_valid)
1271 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1273 if (img->mask)
1275 int free_mask = !mask;
1276 #ifdef HAVE_NTGUI
1277 HGDIOBJ prev;
1278 #endif /* HAVE_NTGUI */
1280 if (free_mask)
1282 #ifndef HAVE_NTGUI
1283 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1284 0, 0, img->width, img->height, ~0, ZPixmap);
1285 #else
1286 HDC frame_dc = get_frame_dc (f);
1287 mask = CreateCompatibleDC (frame_dc);
1288 release_frame_dc (f, frame_dc);
1289 prev = SelectObject (mask, img->mask);
1290 #endif /* HAVE_NTGUI */
1293 img->background_transparent
1294 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1296 if (free_mask)
1297 Destroy_Image (mask, prev);
1299 else
1300 img->background_transparent = 0;
1302 img->background_transparent_valid = 1;
1305 return img->background_transparent;
1309 /***********************************************************************
1310 Helper functions for X image types
1311 ***********************************************************************/
1313 static void x_clear_image_1 (struct frame *, struct image *, int,
1314 int, int);
1315 static void x_clear_image (struct frame *f, struct image *img);
1316 static unsigned long x_alloc_image_color (struct frame *f,
1317 struct image *img,
1318 Lisp_Object color_name,
1319 unsigned long dflt);
1322 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1323 free the pixmap if any. MASK_P non-zero means clear the mask
1324 pixmap if any. COLORS_P non-zero means free colors allocated for
1325 the image, if any. */
1327 static void
1328 x_clear_image_1 (struct frame *f, struct image *img, int pixmap_p, int mask_p,
1329 int colors_p)
1331 if (pixmap_p && img->pixmap)
1333 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1334 img->pixmap = NO_PIXMAP;
1335 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1336 img->background_valid = 0;
1339 if (mask_p && img->mask)
1341 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1342 img->mask = NO_PIXMAP;
1343 img->background_transparent_valid = 0;
1346 if (colors_p && img->ncolors)
1348 /* W32_TODO: color table support. */
1349 #ifdef HAVE_X_WINDOWS
1350 x_free_colors (f, img->colors, img->ncolors);
1351 #endif /* HAVE_X_WINDOWS */
1352 xfree (img->colors);
1353 img->colors = NULL;
1354 img->ncolors = 0;
1359 /* Free X resources of image IMG which is used on frame F. */
1361 static void
1362 x_clear_image (struct frame *f, struct image *img)
1364 BLOCK_INPUT;
1365 x_clear_image_1 (f, img, 1, 1, 1);
1366 UNBLOCK_INPUT;
1370 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1371 cannot be allocated, use DFLT. Add a newly allocated color to
1372 IMG->colors, so that it can be freed again. Value is the pixel
1373 color. */
1375 static unsigned long
1376 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1377 unsigned long dflt)
1379 XColor color;
1380 unsigned long result;
1382 xassert (STRINGP (color_name));
1384 if (x_defined_color (f, SDATA (color_name), &color, 1))
1386 /* This isn't called frequently so we get away with simply
1387 reallocating the color vector to the needed size, here. */
1388 ++img->ncolors;
1389 img->colors =
1390 (unsigned long *) xrealloc (img->colors,
1391 img->ncolors * sizeof *img->colors);
1392 img->colors[img->ncolors - 1] = color.pixel;
1393 result = color.pixel;
1395 else
1396 result = dflt;
1398 return result;
1403 /***********************************************************************
1404 Image Cache
1405 ***********************************************************************/
1407 static struct image *search_image_cache (struct frame *, Lisp_Object, unsigned);
1408 static void cache_image (struct frame *f, struct image *img);
1409 static void postprocess_image (struct frame *, struct image *);
1411 /* Return a new, initialized image cache that is allocated from the
1412 heap. Call free_image_cache to free an image cache. */
1414 struct image_cache *
1415 make_image_cache (void)
1417 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1418 int size;
1420 memset (c, 0, sizeof *c);
1421 c->size = 50;
1422 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1423 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1424 c->buckets = (struct image **) xmalloc (size);
1425 memset (c->buckets, 0, size);
1426 return c;
1430 /* Find an image matching SPEC in the cache, and return it. If no
1431 image is found, return NULL. */
1432 static struct image *
1433 search_image_cache (struct frame *f, Lisp_Object spec, unsigned int hash)
1435 struct image *img;
1436 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1437 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1439 if (!c) return NULL;
1441 /* If the image spec does not specify a background color, the cached
1442 image must have the same background color as the current frame.
1443 The foreground color must also match, for the sake of monochrome
1444 images.
1446 In fact, we could ignore the foreground color matching condition
1447 for color images, or if the image spec specifies :foreground;
1448 similarly we could ignore the background color matching condition
1449 for formats that don't use transparency (such as jpeg), or if the
1450 image spec specifies :background. However, the extra memory
1451 usage is probably negligible in practice, so we don't bother. */
1453 for (img = c->buckets[i]; img; img = img->next)
1454 if (img->hash == hash
1455 && !NILP (Fequal (img->spec, spec))
1456 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1457 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1458 break;
1459 return img;
1463 /* Search frame F for an image with spec SPEC, and free it. */
1465 static void
1466 uncache_image (struct frame *f, Lisp_Object spec)
1468 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1469 if (img)
1471 free_image (f, img);
1472 /* As display glyphs may still be referring to the image ID, we
1473 must garbage the frame (Bug#6426). */
1474 SET_FRAME_GARBAGED (f);
1479 /* Free image cache of frame F. Be aware that X frames share images
1480 caches. */
1482 void
1483 free_image_cache (struct frame *f)
1485 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1486 if (c)
1488 int i;
1490 /* Cache should not be referenced by any frame when freed. */
1491 xassert (c->refcount == 0);
1493 for (i = 0; i < c->used; ++i)
1494 free_image (f, c->images[i]);
1495 xfree (c->images);
1496 xfree (c->buckets);
1497 xfree (c);
1498 FRAME_IMAGE_CACHE (f) = NULL;
1503 /* Clear image cache of frame F. FILTER=t means free all images.
1504 FILTER=nil means clear only images that haven't been
1505 displayed for some time.
1506 Else, only free the images which have FILTER in their `dependencies'.
1507 Should be called from time to time to reduce the number of loaded images.
1508 If image-cache-eviction-delay is non-nil, this frees images in the cache
1509 which weren't displayed for at least that many seconds. */
1511 void
1512 clear_image_cache (struct frame *f, Lisp_Object filter)
1514 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1516 if (c)
1518 int i, nfreed = 0;
1520 /* Block input so that we won't be interrupted by a SIGIO
1521 while being in an inconsistent state. */
1522 BLOCK_INPUT;
1524 if (!NILP (filter))
1526 /* Filter image cache. */
1527 for (i = 0; i < c->used; ++i)
1529 struct image *img = c->images[i];
1530 if (img && (EQ (Qt, filter)
1531 || !NILP (Fmember (filter, img->dependencies))))
1533 free_image (f, img);
1534 ++nfreed;
1538 else if (INTEGERP (Vimage_cache_eviction_delay))
1540 /* Free cache based on timestamp. */
1541 EMACS_TIME t;
1542 unsigned long old;
1543 int delay, nimages = 0;
1545 for (i = 0; i < c->used; ++i)
1546 if (c->images[i])
1547 nimages++;
1549 /* If the number of cached images has grown unusually large,
1550 decrease the cache eviction delay (Bug#6230). */
1551 delay = XFASTINT (Vimage_cache_eviction_delay);
1552 if (nimages > 40)
1553 delay = max (1, 1600 * delay / (nimages*nimages));
1555 EMACS_GET_TIME (t);
1556 old = EMACS_SECS (t) - delay;
1558 for (i = 0; i < c->used; ++i)
1560 struct image *img = c->images[i];
1561 if (img && img->timestamp < old)
1563 free_image (f, img);
1564 ++nfreed;
1569 /* We may be clearing the image cache because, for example,
1570 Emacs was iconified for a longer period of time. In that
1571 case, current matrices may still contain references to
1572 images freed above. So, clear these matrices. */
1573 if (nfreed)
1575 Lisp_Object tail, frame;
1577 FOR_EACH_FRAME (tail, frame)
1579 struct frame *f = XFRAME (frame);
1580 if (FRAME_IMAGE_CACHE (f) == c)
1581 clear_current_matrices (f);
1584 ++windows_or_buffers_changed;
1587 UNBLOCK_INPUT;
1591 void
1592 clear_image_caches (Lisp_Object filter)
1594 /* FIXME: We want to do
1595 * struct terminal *t;
1596 * for (t = terminal_list; t; t = t->next_terminal)
1597 * clear_image_cache (t, filter); */
1598 Lisp_Object tail, frame;
1599 FOR_EACH_FRAME (tail, frame)
1600 if (FRAME_WINDOW_P (XFRAME (frame)))
1601 clear_image_cache (XFRAME (frame), filter);
1604 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1605 0, 1, 0,
1606 doc: /* Clear the image cache.
1607 FILTER nil or a frame means clear all images in the selected frame.
1608 FILTER t means clear the image caches of all frames.
1609 Anything else, means only clear those images which refer to FILTER,
1610 which is then usually a filename. */)
1611 (Lisp_Object filter)
1613 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1614 clear_image_caches (filter);
1615 else
1616 clear_image_cache (check_x_frame (filter), Qt);
1618 return Qnil;
1622 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1623 1, 2, 0,
1624 doc: /* Fush the image with specification SPEC on frame FRAME.
1625 This removes the image from the Emacs image cache. If SPEC specifies
1626 an image file, the next redisplay of this image will read from the
1627 current contents of that file.
1629 FRAME nil or omitted means use the selected frame.
1630 FRAME t means refresh the image on all frames. */)
1631 (Lisp_Object spec, Lisp_Object frame)
1633 if (!valid_image_p (spec))
1634 error ("Invalid image specification");
1636 if (EQ (frame, Qt))
1638 Lisp_Object tail;
1639 FOR_EACH_FRAME (tail, frame)
1641 struct frame *f = XFRAME (frame);
1642 if (FRAME_WINDOW_P (f))
1643 uncache_image (f, spec);
1646 else
1647 uncache_image (check_x_frame (frame), spec);
1649 return Qnil;
1653 /* Compute masks and transform image IMG on frame F, as specified
1654 by the image's specification, */
1656 static void
1657 postprocess_image (struct frame *f, struct image *img)
1659 /* Manipulation of the image's mask. */
1660 if (img->pixmap)
1662 Lisp_Object conversion, spec;
1663 Lisp_Object mask;
1665 spec = img->spec;
1667 /* `:heuristic-mask t'
1668 `:mask heuristic'
1669 means build a mask heuristically.
1670 `:heuristic-mask (R G B)'
1671 `:mask (heuristic (R G B))'
1672 means build a mask from color (R G B) in the
1673 image.
1674 `:mask nil'
1675 means remove a mask, if any. */
1677 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1678 if (!NILP (mask))
1679 x_build_heuristic_mask (f, img, mask);
1680 else
1682 int found_p;
1684 mask = image_spec_value (spec, QCmask, &found_p);
1686 if (EQ (mask, Qheuristic))
1687 x_build_heuristic_mask (f, img, Qt);
1688 else if (CONSP (mask)
1689 && EQ (XCAR (mask), Qheuristic))
1691 if (CONSP (XCDR (mask)))
1692 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1693 else
1694 x_build_heuristic_mask (f, img, XCDR (mask));
1696 else if (NILP (mask) && found_p && img->mask)
1698 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1699 img->mask = NO_PIXMAP;
1704 /* Should we apply an image transformation algorithm? */
1705 conversion = image_spec_value (spec, QCconversion, NULL);
1706 if (EQ (conversion, Qdisabled))
1707 x_disable_image (f, img);
1708 else if (EQ (conversion, Qlaplace))
1709 x_laplace (f, img);
1710 else if (EQ (conversion, Qemboss))
1711 x_emboss (f, img);
1712 else if (CONSP (conversion)
1713 && EQ (XCAR (conversion), Qedge_detection))
1715 Lisp_Object tem;
1716 tem = XCDR (conversion);
1717 if (CONSP (tem))
1718 x_edge_detection (f, img,
1719 Fplist_get (tem, QCmatrix),
1720 Fplist_get (tem, QCcolor_adjustment));
1726 /* Return the id of image with Lisp specification SPEC on frame F.
1727 SPEC must be a valid Lisp image specification (see valid_image_p). */
1730 lookup_image (struct frame *f, Lisp_Object spec)
1732 struct image_cache *c;
1733 struct image *img;
1734 unsigned hash;
1735 EMACS_TIME now;
1737 /* F must be a window-system frame, and SPEC must be a valid image
1738 specification. */
1739 xassert (FRAME_WINDOW_P (f));
1740 xassert (valid_image_p (spec));
1742 c = FRAME_IMAGE_CACHE (f);
1744 /* Look up SPEC in the hash table of the image cache. */
1745 hash = sxhash (spec, 0);
1746 img = search_image_cache (f, spec, hash);
1747 if (img && img->load_failed_p)
1749 free_image (f, img);
1750 img = NULL;
1753 /* If not found, create a new image and cache it. */
1754 if (img == NULL)
1756 BLOCK_INPUT;
1757 img = make_image (spec, hash);
1758 cache_image (f, img);
1759 img->load_failed_p = img->type->load (f, img) == 0;
1760 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1761 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1763 /* If we can't load the image, and we don't have a width and
1764 height, use some arbitrary width and height so that we can
1765 draw a rectangle for it. */
1766 if (img->load_failed_p)
1768 Lisp_Object value;
1770 value = image_spec_value (spec, QCwidth, NULL);
1771 img->width = (INTEGERP (value)
1772 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1773 value = image_spec_value (spec, QCheight, NULL);
1774 img->height = (INTEGERP (value)
1775 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1777 else
1779 /* Handle image type independent image attributes
1780 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1781 `:background COLOR'. */
1782 Lisp_Object ascent, margin, relief, bg;
1784 ascent = image_spec_value (spec, QCascent, NULL);
1785 if (INTEGERP (ascent))
1786 img->ascent = XFASTINT (ascent);
1787 else if (EQ (ascent, Qcenter))
1788 img->ascent = CENTERED_IMAGE_ASCENT;
1790 margin = image_spec_value (spec, QCmargin, NULL);
1791 if (INTEGERP (margin) && XINT (margin) >= 0)
1792 img->vmargin = img->hmargin = XFASTINT (margin);
1793 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1794 && INTEGERP (XCDR (margin)))
1796 if (XINT (XCAR (margin)) > 0)
1797 img->hmargin = XFASTINT (XCAR (margin));
1798 if (XINT (XCDR (margin)) > 0)
1799 img->vmargin = XFASTINT (XCDR (margin));
1802 relief = image_spec_value (spec, QCrelief, NULL);
1803 if (INTEGERP (relief))
1805 img->relief = XINT (relief);
1806 img->hmargin += eabs (img->relief);
1807 img->vmargin += eabs (img->relief);
1810 if (! img->background_valid)
1812 bg = image_spec_value (img->spec, QCbackground, NULL);
1813 if (!NILP (bg))
1815 img->background
1816 = x_alloc_image_color (f, img, bg,
1817 FRAME_BACKGROUND_PIXEL (f));
1818 img->background_valid = 1;
1822 /* Do image transformations and compute masks, unless we
1823 don't have the image yet. */
1824 if (!EQ (*img->type->type, Qpostscript))
1825 postprocess_image (f, img);
1828 UNBLOCK_INPUT;
1831 /* We're using IMG, so set its timestamp to `now'. */
1832 EMACS_GET_TIME (now);
1833 img->timestamp = EMACS_SECS (now);
1835 /* Value is the image id. */
1836 return img->id;
1840 /* Cache image IMG in the image cache of frame F. */
1842 static void
1843 cache_image (struct frame *f, struct image *img)
1845 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1846 int i;
1848 /* Find a free slot in c->images. */
1849 for (i = 0; i < c->used; ++i)
1850 if (c->images[i] == NULL)
1851 break;
1853 /* If no free slot found, maybe enlarge c->images. */
1854 if (i == c->used && c->used == c->size)
1856 c->size *= 2;
1857 c->images = (struct image **) xrealloc (c->images,
1858 c->size * sizeof *c->images);
1861 /* Add IMG to c->images, and assign IMG an id. */
1862 c->images[i] = img;
1863 img->id = i;
1864 if (i == c->used)
1865 ++c->used;
1867 /* Add IMG to the cache's hash table. */
1868 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1869 img->next = c->buckets[i];
1870 if (img->next)
1871 img->next->prev = img;
1872 img->prev = NULL;
1873 c->buckets[i] = img;
1877 /* Call FN on every image in the image cache of frame F. Used to mark
1878 Lisp Objects in the image cache. */
1880 /* Mark Lisp objects in image IMG. */
1882 static void
1883 mark_image (struct image *img)
1885 mark_object (img->spec);
1886 mark_object (img->dependencies);
1888 if (!NILP (img->data.lisp_val))
1889 mark_object (img->data.lisp_val);
1893 void
1894 mark_image_cache (struct image_cache *c)
1896 if (c)
1898 int i;
1899 for (i = 0; i < c->used; ++i)
1900 if (c->images[i])
1901 mark_image (c->images[i]);
1907 /***********************************************************************
1908 X / NS / W32 support code
1909 ***********************************************************************/
1911 #ifdef HAVE_NTGUI
1913 /* Macro for defining functions that will be loaded from image DLLs. */
1914 #define DEF_IMGLIB_FN(func,args) int (FAR CDECL *fn_##func)args
1916 /* Macro for loading those image functions from the library. */
1917 #define LOAD_IMGLIB_FN(lib,func) { \
1918 fn_##func = (void *) GetProcAddress (lib, #func); \
1919 if (!fn_##func) return 0; \
1922 /* Load a DLL implementing an image type.
1923 The argument LIBRARIES is usually the variable
1924 `dynamic-library-alist', which associates a symbol, identifying
1925 an external DLL library, to a list of possible filenames.
1926 The function returns NULL if no library could be loaded for
1927 the given symbol, or if the library was previously loaded;
1928 else the handle of the DLL. */
1929 static HMODULE
1930 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
1932 HMODULE library = NULL;
1934 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
1936 Lisp_Object dlls = Fassq (type, libraries);
1938 if (CONSP (dlls))
1939 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
1941 CHECK_STRING_CAR (dlls);
1942 if (library = LoadLibrary (SDATA (XCAR (dlls))))
1943 break;
1947 return library;
1950 #endif /* HAVE_NTGUI */
1952 static int x_create_x_image_and_pixmap (struct frame *, int, int, int,
1953 XImagePtr *, Pixmap *);
1954 static void x_destroy_x_image (XImagePtr);
1955 static void x_put_x_image (struct frame *, XImagePtr, Pixmap, int, int);
1958 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1959 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1960 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1961 via xmalloc. Print error messages via image_error if an error
1962 occurs. Value is non-zero if successful.
1964 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1965 should indicate the bit depth of the image. */
1967 static int
1968 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1969 XImagePtr *ximg, Pixmap *pixmap)
1971 #ifdef HAVE_X_WINDOWS
1972 Display *display = FRAME_X_DISPLAY (f);
1973 Window window = FRAME_X_WINDOW (f);
1974 Screen *screen = FRAME_X_SCREEN (f);
1976 xassert (interrupt_input_blocked);
1978 if (depth <= 0)
1979 depth = DefaultDepthOfScreen (screen);
1980 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1981 depth, ZPixmap, 0, NULL, width, height,
1982 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1983 if (*ximg == NULL)
1985 image_error ("Unable to allocate X image", Qnil, Qnil);
1986 return 0;
1989 /* Allocate image raster. */
1990 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
1992 /* Allocate a pixmap of the same size. */
1993 *pixmap = XCreatePixmap (display, window, width, height, depth);
1994 if (*pixmap == NO_PIXMAP)
1996 x_destroy_x_image (*ximg);
1997 *ximg = NULL;
1998 image_error ("Unable to create X pixmap", Qnil, Qnil);
1999 return 0;
2002 return 1;
2003 #endif /* HAVE_X_WINDOWS */
2005 #ifdef HAVE_NTGUI
2007 BITMAPINFOHEADER *header;
2008 HDC hdc;
2009 int scanline_width_bits;
2010 int remainder;
2011 int palette_colors = 0;
2013 if (depth == 0)
2014 depth = 24;
2016 if (depth != 1 && depth != 4 && depth != 8
2017 && depth != 16 && depth != 24 && depth != 32)
2019 image_error ("Invalid image bit depth specified", Qnil, Qnil);
2020 return 0;
2023 scanline_width_bits = width * depth;
2024 remainder = scanline_width_bits % 32;
2026 if (remainder)
2027 scanline_width_bits += 32 - remainder;
2029 /* Bitmaps with a depth less than 16 need a palette. */
2030 /* BITMAPINFO structure already contains the first RGBQUAD. */
2031 if (depth < 16)
2032 palette_colors = 1 << depth - 1;
2034 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2035 if (*ximg == NULL)
2037 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
2038 return 0;
2041 header = &(*ximg)->info.bmiHeader;
2042 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2043 header->biSize = sizeof (*header);
2044 header->biWidth = width;
2045 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2046 header->biPlanes = 1;
2047 header->biBitCount = depth;
2048 header->biCompression = BI_RGB;
2049 header->biClrUsed = palette_colors;
2051 /* TODO: fill in palette. */
2052 if (depth == 1)
2054 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2055 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2056 (*ximg)->info.bmiColors[0].rgbRed = 0;
2057 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2058 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2059 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2060 (*ximg)->info.bmiColors[1].rgbRed = 255;
2061 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2064 hdc = get_frame_dc (f);
2066 /* Create a DIBSection and raster array for the bitmap,
2067 and store its handle in *pixmap. */
2068 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2069 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2070 /* casting avoids a GCC warning */
2071 (void **)&((*ximg)->data), NULL, 0);
2073 /* Realize display palette and garbage all frames. */
2074 release_frame_dc (f, hdc);
2076 if (*pixmap == NULL)
2078 DWORD err = GetLastError ();
2079 Lisp_Object errcode;
2080 /* All system errors are < 10000, so the following is safe. */
2081 XSETINT (errcode, (int) err);
2082 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2083 x_destroy_x_image (*ximg);
2084 return 0;
2087 return 1;
2089 #endif /* HAVE_NTGUI */
2091 #ifdef HAVE_NS
2092 *pixmap = ns_image_for_XPM (width, height, depth);
2093 if (*pixmap == 0)
2095 *ximg = NULL;
2096 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2097 return 0;
2099 *ximg = *pixmap;
2100 return 1;
2101 #endif
2105 /* Destroy XImage XIMG. Free XIMG->data. */
2107 static void
2108 x_destroy_x_image (XImagePtr ximg)
2110 xassert (interrupt_input_blocked);
2111 if (ximg)
2113 #ifdef HAVE_X_WINDOWS
2114 xfree (ximg->data);
2115 ximg->data = NULL;
2116 XDestroyImage (ximg);
2117 #endif /* HAVE_X_WINDOWS */
2118 #ifdef HAVE_NTGUI
2119 /* Data will be freed by DestroyObject. */
2120 ximg->data = NULL;
2121 xfree (ximg);
2122 #endif /* HAVE_NTGUI */
2123 #ifdef HAVE_NS
2124 ns_release_object (ximg);
2125 #endif /* HAVE_NS */
2130 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2131 are width and height of both the image and pixmap. */
2133 static void
2134 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2136 #ifdef HAVE_X_WINDOWS
2137 GC gc;
2139 xassert (interrupt_input_blocked);
2140 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2141 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2142 XFreeGC (FRAME_X_DISPLAY (f), gc);
2143 #endif /* HAVE_X_WINDOWS */
2145 #ifdef HAVE_NTGUI
2146 #if 0 /* I don't think this is necessary looking at where it is used. */
2147 HDC hdc = get_frame_dc (f);
2148 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2149 release_frame_dc (f, hdc);
2150 #endif
2151 #endif /* HAVE_NTGUI */
2153 #ifdef HAVE_NS
2154 xassert (ximg == pixmap);
2155 ns_retain_object (ximg);
2156 #endif
2160 /***********************************************************************
2161 File Handling
2162 ***********************************************************************/
2164 static unsigned char *slurp_file (char *, int *);
2167 /* Find image file FILE. Look in data-directory/images, then
2168 x-bitmap-file-path. Value is the encoded full name of the file
2169 found, or nil if not found. */
2171 Lisp_Object
2172 x_find_image_file (Lisp_Object file)
2174 Lisp_Object file_found, search_path;
2175 int fd;
2177 /* TODO I think this should use something like image-load-path
2178 instead. Unfortunately, that can contain non-string elements. */
2179 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2180 Vdata_directory),
2181 Vx_bitmap_file_path);
2183 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2184 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2186 if (fd == -1)
2187 file_found = Qnil;
2188 else
2190 file_found = ENCODE_FILE (file_found);
2191 close (fd);
2194 return file_found;
2198 /* Read FILE into memory. Value is a pointer to a buffer allocated
2199 with xmalloc holding FILE's contents. Value is null if an error
2200 occurred. *SIZE is set to the size of the file. */
2202 static unsigned char *
2203 slurp_file (char *file, int *size)
2205 FILE *fp = NULL;
2206 unsigned char *buf = NULL;
2207 struct stat st;
2209 if (stat (file, &st) == 0
2210 && (fp = fopen (file, "rb")) != NULL
2211 && (buf = (unsigned char *) xmalloc (st.st_size),
2212 fread (buf, 1, st.st_size, fp) == st.st_size))
2214 *size = st.st_size;
2215 fclose (fp);
2217 else
2219 if (fp)
2220 fclose (fp);
2221 if (buf)
2223 xfree (buf);
2224 buf = NULL;
2228 return buf;
2233 /***********************************************************************
2234 XBM images
2235 ***********************************************************************/
2237 static int xbm_scan (unsigned char **, unsigned char *, char *, int *);
2238 static int xbm_load (struct frame *f, struct image *img);
2239 static int xbm_load_image (struct frame *f, struct image *img,
2240 unsigned char *, unsigned char *);
2241 static int xbm_image_p (Lisp_Object object);
2242 static int xbm_read_bitmap_data (struct frame *f,
2243 unsigned char *, unsigned char *,
2244 int *, int *, unsigned char **, int);
2245 static int xbm_file_p (Lisp_Object);
2248 /* Indices of image specification fields in xbm_format, below. */
2250 enum xbm_keyword_index
2252 XBM_TYPE,
2253 XBM_FILE,
2254 XBM_WIDTH,
2255 XBM_HEIGHT,
2256 XBM_DATA,
2257 XBM_FOREGROUND,
2258 XBM_BACKGROUND,
2259 XBM_ASCENT,
2260 XBM_MARGIN,
2261 XBM_RELIEF,
2262 XBM_ALGORITHM,
2263 XBM_HEURISTIC_MASK,
2264 XBM_MASK,
2265 XBM_LAST
2268 /* Vector of image_keyword structures describing the format
2269 of valid XBM image specifications. */
2271 static const struct image_keyword xbm_format[XBM_LAST] =
2273 {":type", IMAGE_SYMBOL_VALUE, 1},
2274 {":file", IMAGE_STRING_VALUE, 0},
2275 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2276 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2277 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2278 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2279 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2280 {":ascent", IMAGE_ASCENT_VALUE, 0},
2281 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2282 {":relief", IMAGE_INTEGER_VALUE, 0},
2283 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2284 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2285 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2288 /* Structure describing the image type XBM. */
2290 static struct image_type xbm_type =
2292 &Qxbm,
2293 xbm_image_p,
2294 xbm_load,
2295 x_clear_image,
2296 NULL
2299 /* Tokens returned from xbm_scan. */
2301 enum xbm_token
2303 XBM_TK_IDENT = 256,
2304 XBM_TK_NUMBER
2308 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2309 A valid specification is a list starting with the symbol `image'
2310 The rest of the list is a property list which must contain an
2311 entry `:type xbm..
2313 If the specification specifies a file to load, it must contain
2314 an entry `:file FILENAME' where FILENAME is a string.
2316 If the specification is for a bitmap loaded from memory it must
2317 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2318 WIDTH and HEIGHT are integers > 0. DATA may be:
2320 1. a string large enough to hold the bitmap data, i.e. it must
2321 have a size >= (WIDTH + 7) / 8 * HEIGHT
2323 2. a bool-vector of size >= WIDTH * HEIGHT
2325 3. a vector of strings or bool-vectors, one for each line of the
2326 bitmap.
2328 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2329 may not be specified in this case because they are defined in the
2330 XBM file.
2332 Both the file and data forms may contain the additional entries
2333 `:background COLOR' and `:foreground COLOR'. If not present,
2334 foreground and background of the frame on which the image is
2335 displayed is used. */
2337 static int
2338 xbm_image_p (Lisp_Object object)
2340 struct image_keyword kw[XBM_LAST];
2342 memcpy (kw, xbm_format, sizeof kw);
2343 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2344 return 0;
2346 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2348 if (kw[XBM_FILE].count)
2350 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2351 return 0;
2353 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2355 /* In-memory XBM file. */
2356 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2357 return 0;
2359 else
2361 Lisp_Object data;
2362 int width, height;
2364 /* Entries for `:width', `:height' and `:data' must be present. */
2365 if (!kw[XBM_WIDTH].count
2366 || !kw[XBM_HEIGHT].count
2367 || !kw[XBM_DATA].count)
2368 return 0;
2370 data = kw[XBM_DATA].value;
2371 width = XFASTINT (kw[XBM_WIDTH].value);
2372 height = XFASTINT (kw[XBM_HEIGHT].value);
2374 /* Check type of data, and width and height against contents of
2375 data. */
2376 if (VECTORP (data))
2378 int i;
2380 /* Number of elements of the vector must be >= height. */
2381 if (XVECTOR (data)->size < height)
2382 return 0;
2384 /* Each string or bool-vector in data must be large enough
2385 for one line of the image. */
2386 for (i = 0; i < height; ++i)
2388 Lisp_Object elt = XVECTOR (data)->contents[i];
2390 if (STRINGP (elt))
2392 if (SCHARS (elt)
2393 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2394 return 0;
2396 else if (BOOL_VECTOR_P (elt))
2398 if (XBOOL_VECTOR (elt)->size < width)
2399 return 0;
2401 else
2402 return 0;
2405 else if (STRINGP (data))
2407 if (SCHARS (data)
2408 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2409 return 0;
2411 else if (BOOL_VECTOR_P (data))
2413 if (XBOOL_VECTOR (data)->size < width * height)
2414 return 0;
2416 else
2417 return 0;
2420 return 1;
2424 /* Scan a bitmap file. FP is the stream to read from. Value is
2425 either an enumerator from enum xbm_token, or a character for a
2426 single-character token, or 0 at end of file. If scanning an
2427 identifier, store the lexeme of the identifier in SVAL. If
2428 scanning a number, store its value in *IVAL. */
2430 static int
2431 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2433 unsigned int c;
2435 loop:
2437 /* Skip white space. */
2438 while (*s < end && (c = *(*s)++, isspace (c)))
2441 if (*s >= end)
2442 c = 0;
2443 else if (isdigit (c))
2445 int value = 0, digit;
2447 if (c == '0' && *s < end)
2449 c = *(*s)++;
2450 if (c == 'x' || c == 'X')
2452 while (*s < end)
2454 c = *(*s)++;
2455 if (isdigit (c))
2456 digit = c - '0';
2457 else if (c >= 'a' && c <= 'f')
2458 digit = c - 'a' + 10;
2459 else if (c >= 'A' && c <= 'F')
2460 digit = c - 'A' + 10;
2461 else
2462 break;
2463 value = 16 * value + digit;
2466 else if (isdigit (c))
2468 value = c - '0';
2469 while (*s < end
2470 && (c = *(*s)++, isdigit (c)))
2471 value = 8 * value + c - '0';
2474 else
2476 value = c - '0';
2477 while (*s < end
2478 && (c = *(*s)++, isdigit (c)))
2479 value = 10 * value + c - '0';
2482 if (*s < end)
2483 *s = *s - 1;
2484 *ival = value;
2485 c = XBM_TK_NUMBER;
2487 else if (isalpha (c) || c == '_')
2489 *sval++ = c;
2490 while (*s < end
2491 && (c = *(*s)++, (isalnum (c) || c == '_')))
2492 *sval++ = c;
2493 *sval = 0;
2494 if (*s < end)
2495 *s = *s - 1;
2496 c = XBM_TK_IDENT;
2498 else if (c == '/' && **s == '*')
2500 /* C-style comment. */
2501 ++*s;
2502 while (**s && (**s != '*' || *(*s + 1) != '/'))
2503 ++*s;
2504 if (**s)
2506 *s += 2;
2507 goto loop;
2511 return c;
2514 #ifdef HAVE_NTGUI
2516 /* Create a Windows bitmap from X bitmap data. */
2517 static HBITMAP
2518 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2520 static unsigned char swap_nibble[16]
2521 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2522 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2523 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2524 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2525 int i, j, w1, w2;
2526 unsigned char *bits, *p;
2527 HBITMAP bmp;
2529 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2530 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2531 bits = (unsigned char *) alloca (height * w2);
2532 memset (bits, 0, height * w2);
2533 for (i = 0; i < height; i++)
2535 p = bits + i*w2;
2536 for (j = 0; j < w1; j++)
2538 /* Bitswap XBM bytes to match how Windows does things. */
2539 unsigned char c = *data++;
2540 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2541 | (swap_nibble[(c>>4) & 0xf]));
2544 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2546 return bmp;
2549 static void
2550 convert_mono_to_color_image (struct frame *f, struct image *img,
2551 COLORREF foreground, COLORREF background)
2553 HDC hdc, old_img_dc, new_img_dc;
2554 HGDIOBJ old_prev, new_prev;
2555 HBITMAP new_pixmap;
2557 hdc = get_frame_dc (f);
2558 old_img_dc = CreateCompatibleDC (hdc);
2559 new_img_dc = CreateCompatibleDC (hdc);
2560 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2561 release_frame_dc (f, hdc);
2562 old_prev = SelectObject (old_img_dc, img->pixmap);
2563 new_prev = SelectObject (new_img_dc, new_pixmap);
2564 /* Windows convention for mono bitmaps is black = background,
2565 white = foreground. */
2566 SetTextColor (new_img_dc, background);
2567 SetBkColor (new_img_dc, foreground);
2569 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2570 0, 0, SRCCOPY);
2572 SelectObject (old_img_dc, old_prev);
2573 SelectObject (new_img_dc, new_prev);
2574 DeleteDC (old_img_dc);
2575 DeleteDC (new_img_dc);
2576 DeleteObject (img->pixmap);
2577 if (new_pixmap == 0)
2578 fprintf (stderr, "Failed to convert image to color.\n");
2579 else
2580 img->pixmap = new_pixmap;
2583 #define XBM_BIT_SHUFFLE(b) (~(b))
2585 #else
2587 #define XBM_BIT_SHUFFLE(b) (b)
2589 #endif /* HAVE_NTGUI */
2592 static void
2593 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2594 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2595 int non_default_colors)
2597 #ifdef HAVE_NTGUI
2598 img->pixmap
2599 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2601 /* If colors were specified, transfer the bitmap to a color one. */
2602 if (non_default_colors)
2603 convert_mono_to_color_image (f, img, fg, bg);
2605 #elif defined (HAVE_NS)
2606 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2608 #else
2609 img->pixmap
2610 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2611 FRAME_X_WINDOW (f),
2612 data,
2613 img->width, img->height,
2614 fg, bg,
2615 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2616 #endif /* !HAVE_NTGUI && !HAVE_NS */
2621 /* Replacement for XReadBitmapFileData which isn't available under old
2622 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2623 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2624 the image. Return in *DATA the bitmap data allocated with xmalloc.
2625 Value is non-zero if successful. DATA null means just test if
2626 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR
2627 is non-zero, inhibit the call to image_error when the image size is
2628 invalid (the bitmap remains unread). */
2630 static int
2631 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2632 int *width, int *height, unsigned char **data,
2633 int inhibit_image_error)
2635 unsigned char *s = contents;
2636 char buffer[BUFSIZ];
2637 int padding_p = 0;
2638 int v10 = 0;
2639 int bytes_per_line, i, nbytes;
2640 unsigned char *p;
2641 int value;
2642 int LA1;
2644 #define match() \
2645 LA1 = xbm_scan (&s, end, buffer, &value)
2647 #define expect(TOKEN) \
2648 if (LA1 != (TOKEN)) \
2649 goto failure; \
2650 else \
2651 match ()
2653 #define expect_ident(IDENT) \
2654 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2655 match (); \
2656 else \
2657 goto failure
2659 *width = *height = -1;
2660 if (data)
2661 *data = NULL;
2662 LA1 = xbm_scan (&s, end, buffer, &value);
2664 /* Parse defines for width, height and hot-spots. */
2665 while (LA1 == '#')
2667 match ();
2668 expect_ident ("define");
2669 expect (XBM_TK_IDENT);
2671 if (LA1 == XBM_TK_NUMBER)
2673 char *p = strrchr (buffer, '_');
2674 p = p ? p + 1 : buffer;
2675 if (strcmp (p, "width") == 0)
2676 *width = value;
2677 else if (strcmp (p, "height") == 0)
2678 *height = value;
2680 expect (XBM_TK_NUMBER);
2683 if (!check_image_size (f, *width, *height))
2685 if (!inhibit_image_error)
2686 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2687 goto failure;
2689 else if (data == NULL)
2690 goto success;
2692 /* Parse bits. Must start with `static'. */
2693 expect_ident ("static");
2694 if (LA1 == XBM_TK_IDENT)
2696 if (strcmp (buffer, "unsigned") == 0)
2698 match ();
2699 expect_ident ("char");
2701 else if (strcmp (buffer, "short") == 0)
2703 match ();
2704 v10 = 1;
2705 if (*width % 16 && *width % 16 < 9)
2706 padding_p = 1;
2708 else if (strcmp (buffer, "char") == 0)
2709 match ();
2710 else
2711 goto failure;
2713 else
2714 goto failure;
2716 expect (XBM_TK_IDENT);
2717 expect ('[');
2718 expect (']');
2719 expect ('=');
2720 expect ('{');
2722 bytes_per_line = (*width + 7) / 8 + padding_p;
2723 nbytes = bytes_per_line * *height;
2724 p = *data = (unsigned char *) xmalloc (nbytes);
2726 if (v10)
2728 for (i = 0; i < nbytes; i += 2)
2730 int val = value;
2731 expect (XBM_TK_NUMBER);
2733 *p++ = XBM_BIT_SHUFFLE (val);
2734 if (!padding_p || ((i + 2) % bytes_per_line))
2735 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2737 if (LA1 == ',' || LA1 == '}')
2738 match ();
2739 else
2740 goto failure;
2743 else
2745 for (i = 0; i < nbytes; ++i)
2747 int val = value;
2748 expect (XBM_TK_NUMBER);
2750 *p++ = XBM_BIT_SHUFFLE (val);
2752 if (LA1 == ',' || LA1 == '}')
2753 match ();
2754 else
2755 goto failure;
2759 success:
2760 return 1;
2762 failure:
2764 if (data && *data)
2766 xfree (*data);
2767 *data = NULL;
2769 return 0;
2771 #undef match
2772 #undef expect
2773 #undef expect_ident
2777 /* Load XBM image IMG which will be displayed on frame F from buffer
2778 CONTENTS. END is the end of the buffer. Value is non-zero if
2779 successful. */
2781 static int
2782 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2783 unsigned char *end)
2785 int rc;
2786 unsigned char *data;
2787 int success_p = 0;
2789 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2790 &data, 0);
2791 if (rc)
2793 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2794 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2795 int non_default_colors = 0;
2796 Lisp_Object value;
2798 xassert (img->width > 0 && img->height > 0);
2800 /* Get foreground and background colors, maybe allocate colors. */
2801 value = image_spec_value (img->spec, QCforeground, NULL);
2802 if (!NILP (value))
2804 foreground = x_alloc_image_color (f, img, value, foreground);
2805 non_default_colors = 1;
2807 value = image_spec_value (img->spec, QCbackground, NULL);
2808 if (!NILP (value))
2810 background = x_alloc_image_color (f, img, value, background);
2811 img->background = background;
2812 img->background_valid = 1;
2813 non_default_colors = 1;
2816 Create_Pixmap_From_Bitmap_Data (f, img, data,
2817 foreground, background,
2818 non_default_colors);
2819 xfree (data);
2821 if (img->pixmap == NO_PIXMAP)
2823 x_clear_image (f, img);
2824 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2826 else
2827 success_p = 1;
2829 else
2830 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2832 return success_p;
2836 /* Value is non-zero if DATA looks like an in-memory XBM file. */
2838 static int
2839 xbm_file_p (Lisp_Object data)
2841 int w, h;
2842 return (STRINGP (data)
2843 && xbm_read_bitmap_data (NULL, SDATA (data),
2844 (SDATA (data) + SBYTES (data)),
2845 &w, &h, NULL, 1));
2849 /* Fill image IMG which is used on frame F with pixmap data. Value is
2850 non-zero if successful. */
2852 static int
2853 xbm_load (struct frame *f, struct image *img)
2855 int success_p = 0;
2856 Lisp_Object file_name;
2858 xassert (xbm_image_p (img->spec));
2860 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2861 file_name = image_spec_value (img->spec, QCfile, NULL);
2862 if (STRINGP (file_name))
2864 Lisp_Object file;
2865 unsigned char *contents;
2866 int size;
2868 file = x_find_image_file (file_name);
2869 if (!STRINGP (file))
2871 image_error ("Cannot find image file `%s'", file_name, Qnil);
2872 return 0;
2875 contents = slurp_file (SDATA (file), &size);
2876 if (contents == NULL)
2878 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2879 return 0;
2882 success_p = xbm_load_image (f, img, contents, contents + size);
2884 else
2886 struct image_keyword fmt[XBM_LAST];
2887 Lisp_Object data;
2888 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2889 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2890 int non_default_colors = 0;
2891 char *bits;
2892 int parsed_p;
2893 int in_memory_file_p = 0;
2895 /* See if data looks like an in-memory XBM file. */
2896 data = image_spec_value (img->spec, QCdata, NULL);
2897 in_memory_file_p = xbm_file_p (data);
2899 /* Parse the image specification. */
2900 memcpy (fmt, xbm_format, sizeof fmt);
2901 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2902 xassert (parsed_p);
2904 /* Get specified width, and height. */
2905 if (!in_memory_file_p)
2907 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2908 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2909 xassert (img->width > 0 && img->height > 0);
2912 /* Get foreground and background colors, maybe allocate colors. */
2913 if (fmt[XBM_FOREGROUND].count
2914 && STRINGP (fmt[XBM_FOREGROUND].value))
2916 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2917 foreground);
2918 non_default_colors = 1;
2921 if (fmt[XBM_BACKGROUND].count
2922 && STRINGP (fmt[XBM_BACKGROUND].value))
2924 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2925 background);
2926 non_default_colors = 1;
2929 if (in_memory_file_p)
2930 success_p = xbm_load_image (f, img, SDATA (data),
2931 (SDATA (data)
2932 + SBYTES (data)));
2933 else
2935 if (VECTORP (data))
2937 int i;
2938 char *p;
2939 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2941 p = bits = (char *) alloca (nbytes * img->height);
2942 for (i = 0; i < img->height; ++i, p += nbytes)
2944 Lisp_Object line = XVECTOR (data)->contents[i];
2945 if (STRINGP (line))
2946 memcpy (p, SDATA (line), nbytes);
2947 else
2948 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
2951 else if (STRINGP (data))
2952 bits = SDATA (data);
2953 else
2954 bits = XBOOL_VECTOR (data)->data;
2956 #ifdef WINDOWSNT
2958 char *invertedBits;
2959 int nbytes, i;
2960 /* Windows mono bitmaps are reversed compared with X. */
2961 invertedBits = bits;
2962 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
2963 * img->height;
2964 bits = (char *) alloca (nbytes);
2965 for (i = 0; i < nbytes; i++)
2966 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
2968 #endif
2969 /* Create the pixmap. */
2971 Create_Pixmap_From_Bitmap_Data (f, img, bits,
2972 foreground, background,
2973 non_default_colors);
2974 if (img->pixmap)
2975 success_p = 1;
2976 else
2978 image_error ("Unable to create pixmap for XBM image `%s'",
2979 img->spec, Qnil);
2980 x_clear_image (f, img);
2985 return success_p;
2990 /***********************************************************************
2991 XPM images
2992 ***********************************************************************/
2994 #if defined (HAVE_XPM) || defined (HAVE_NS)
2996 static int xpm_image_p (Lisp_Object object);
2997 static int xpm_load (struct frame *f, struct image *img);
2998 static int xpm_valid_color_symbols_p (Lisp_Object);
3000 #endif /* HAVE_XPM || HAVE_NS */
3002 #ifdef HAVE_XPM
3003 #ifdef HAVE_NTGUI
3004 /* Indicate to xpm.h that we don't have Xlib. */
3005 #define FOR_MSW
3006 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3007 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3008 #define XColor xpm_XColor
3009 #define XImage xpm_XImage
3010 #define Display xpm_Display
3011 #define PIXEL_ALREADY_TYPEDEFED
3012 #include "X11/xpm.h"
3013 #undef FOR_MSW
3014 #undef XColor
3015 #undef XImage
3016 #undef Display
3017 #undef PIXEL_ALREADY_TYPEDEFED
3018 #else
3019 #include "X11/xpm.h"
3020 #endif /* HAVE_NTGUI */
3021 #endif /* HAVE_XPM */
3023 #if defined (HAVE_XPM) || defined (HAVE_NS)
3024 /* The symbol `xpm' identifying XPM-format images. */
3026 Lisp_Object Qxpm;
3028 /* Indices of image specification fields in xpm_format, below. */
3030 enum xpm_keyword_index
3032 XPM_TYPE,
3033 XPM_FILE,
3034 XPM_DATA,
3035 XPM_ASCENT,
3036 XPM_MARGIN,
3037 XPM_RELIEF,
3038 XPM_ALGORITHM,
3039 XPM_HEURISTIC_MASK,
3040 XPM_MASK,
3041 XPM_COLOR_SYMBOLS,
3042 XPM_BACKGROUND,
3043 XPM_LAST
3046 /* Vector of image_keyword structures describing the format
3047 of valid XPM image specifications. */
3049 static const struct image_keyword xpm_format[XPM_LAST] =
3051 {":type", IMAGE_SYMBOL_VALUE, 1},
3052 {":file", IMAGE_STRING_VALUE, 0},
3053 {":data", IMAGE_STRING_VALUE, 0},
3054 {":ascent", IMAGE_ASCENT_VALUE, 0},
3055 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3056 {":relief", IMAGE_INTEGER_VALUE, 0},
3057 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3058 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3059 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3060 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3061 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3064 /* Structure describing the image type XPM. */
3066 static struct image_type xpm_type =
3068 &Qxpm,
3069 xpm_image_p,
3070 xpm_load,
3071 x_clear_image,
3072 NULL
3075 #ifdef HAVE_X_WINDOWS
3077 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3078 functions for allocating image colors. Our own functions handle
3079 color allocation failures more gracefully than the ones on the XPM
3080 lib. */
3082 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3083 #define ALLOC_XPM_COLORS
3084 #endif
3085 #endif /* HAVE_X_WINDOWS */
3087 #ifdef ALLOC_XPM_COLORS
3089 static void xpm_init_color_cache (struct frame *, XpmAttributes *);
3090 static void xpm_free_color_cache (void);
3091 static int xpm_lookup_color (struct frame *, char *, XColor *);
3092 static int xpm_color_bucket (char *);
3093 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3094 XColor *, int);
3096 /* An entry in a hash table used to cache color definitions of named
3097 colors. This cache is necessary to speed up XPM image loading in
3098 case we do color allocations ourselves. Without it, we would need
3099 a call to XParseColor per pixel in the image. */
3101 struct xpm_cached_color
3103 /* Next in collision chain. */
3104 struct xpm_cached_color *next;
3106 /* Color definition (RGB and pixel color). */
3107 XColor color;
3109 /* Color name. */
3110 char name[1];
3113 /* The hash table used for the color cache, and its bucket vector
3114 size. */
3116 #define XPM_COLOR_CACHE_BUCKETS 1001
3117 struct xpm_cached_color **xpm_color_cache;
3119 /* Initialize the color cache. */
3121 static void
3122 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3124 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3125 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3126 memset (xpm_color_cache, 0, nbytes);
3127 init_color_table ();
3129 if (attrs->valuemask & XpmColorSymbols)
3131 int i;
3132 XColor color;
3134 for (i = 0; i < attrs->numsymbols; ++i)
3135 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3136 attrs->colorsymbols[i].value, &color))
3138 color.pixel = lookup_rgb_color (f, color.red, color.green,
3139 color.blue);
3140 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3145 /* Free the color cache. */
3147 static void
3148 xpm_free_color_cache (void)
3150 struct xpm_cached_color *p, *next;
3151 int i;
3153 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3154 for (p = xpm_color_cache[i]; p; p = next)
3156 next = p->next;
3157 xfree (p);
3160 xfree (xpm_color_cache);
3161 xpm_color_cache = NULL;
3162 free_color_table ();
3165 /* Return the bucket index for color named COLOR_NAME in the color
3166 cache. */
3168 static int
3169 xpm_color_bucket (char *color_name)
3171 unsigned h = 0;
3172 char *s;
3174 for (s = color_name; *s; ++s)
3175 h = (h << 2) ^ *s;
3176 return h %= XPM_COLOR_CACHE_BUCKETS;
3180 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3181 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3182 entry added. */
3184 static struct xpm_cached_color *
3185 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3187 size_t nbytes;
3188 struct xpm_cached_color *p;
3190 if (bucket < 0)
3191 bucket = xpm_color_bucket (color_name);
3193 nbytes = sizeof *p + strlen (color_name);
3194 p = (struct xpm_cached_color *) xmalloc (nbytes);
3195 strcpy (p->name, color_name);
3196 p->color = *color;
3197 p->next = xpm_color_cache[bucket];
3198 xpm_color_cache[bucket] = p;
3199 return p;
3202 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3203 return the cached definition in *COLOR. Otherwise, make a new
3204 entry in the cache and allocate the color. Value is zero if color
3205 allocation failed. */
3207 static int
3208 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3210 struct xpm_cached_color *p;
3211 int h = xpm_color_bucket (color_name);
3213 for (p = xpm_color_cache[h]; p; p = p->next)
3214 if (strcmp (p->name, color_name) == 0)
3215 break;
3217 if (p != NULL)
3218 *color = p->color;
3219 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3220 color_name, color))
3222 color->pixel = lookup_rgb_color (f, color->red, color->green,
3223 color->blue);
3224 p = xpm_cache_color (f, color_name, color, h);
3226 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3227 with transparency, and it's useful. */
3228 else if (strcmp ("opaque", color_name) == 0)
3230 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3231 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3232 p = xpm_cache_color (f, color_name, color, h);
3235 return p != NULL;
3239 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3240 CLOSURE is a pointer to the frame on which we allocate the
3241 color. Return in *COLOR the allocated color. Value is non-zero
3242 if successful. */
3244 static int
3245 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3246 void *closure)
3248 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3252 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3253 is a pointer to the frame on which we allocate the color. Value is
3254 non-zero if successful. */
3256 static int
3257 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3259 return 1;
3262 #endif /* ALLOC_XPM_COLORS */
3265 #ifdef HAVE_NTGUI
3267 /* XPM library details. */
3269 DEF_IMGLIB_FN (XpmFreeAttributes, (XpmAttributes *));
3270 DEF_IMGLIB_FN (XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3271 xpm_XImage **, XpmAttributes *));
3272 DEF_IMGLIB_FN (XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3273 xpm_XImage **, XpmAttributes *));
3274 DEF_IMGLIB_FN (XImageFree, (xpm_XImage *));
3276 static int
3277 init_xpm_functions (Lisp_Object libraries)
3279 HMODULE library;
3281 if (!(library = w32_delayed_load (libraries, Qxpm)))
3282 return 0;
3284 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3285 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3286 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3287 LOAD_IMGLIB_FN (library, XImageFree);
3288 return 1;
3291 #endif /* HAVE_NTGUI */
3294 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3295 for XPM images. Such a list must consist of conses whose car and
3296 cdr are strings. */
3298 static int
3299 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3301 while (CONSP (color_symbols))
3303 Lisp_Object sym = XCAR (color_symbols);
3304 if (!CONSP (sym)
3305 || !STRINGP (XCAR (sym))
3306 || !STRINGP (XCDR (sym)))
3307 break;
3308 color_symbols = XCDR (color_symbols);
3311 return NILP (color_symbols);
3315 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3317 static int
3318 xpm_image_p (Lisp_Object object)
3320 struct image_keyword fmt[XPM_LAST];
3321 memcpy (fmt, xpm_format, sizeof fmt);
3322 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3323 /* Either `:file' or `:data' must be present. */
3324 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3325 /* Either no `:color-symbols' or it's a list of conses
3326 whose car and cdr are strings. */
3327 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3328 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3331 #endif /* HAVE_XPM || HAVE_NS */
3333 #if defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
3335 x_create_bitmap_from_xpm_data (struct frame *f, char **bits)
3337 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3338 int id, rc;
3339 XpmAttributes attrs;
3340 Pixmap bitmap, mask;
3342 memset (&attrs, 0, sizeof attrs);
3344 attrs.visual = FRAME_X_VISUAL (f);
3345 attrs.colormap = FRAME_X_COLORMAP (f);
3346 attrs.valuemask |= XpmVisual;
3347 attrs.valuemask |= XpmColormap;
3349 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3350 bits, &bitmap, &mask, &attrs);
3351 if (rc != XpmSuccess)
3353 XpmFreeAttributes (&attrs);
3354 return -1;
3357 id = x_allocate_bitmap_record (f);
3358 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3359 dpyinfo->bitmaps[id - 1].have_mask = 1;
3360 dpyinfo->bitmaps[id - 1].mask = mask;
3361 dpyinfo->bitmaps[id - 1].file = NULL;
3362 dpyinfo->bitmaps[id - 1].height = attrs.height;
3363 dpyinfo->bitmaps[id - 1].width = attrs.width;
3364 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3365 dpyinfo->bitmaps[id - 1].refcount = 1;
3367 XpmFreeAttributes (&attrs);
3368 return id;
3370 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3372 /* Load image IMG which will be displayed on frame F. Value is
3373 non-zero if successful. */
3375 #ifdef HAVE_XPM
3377 static int
3378 xpm_load (struct frame *f, struct image *img)
3380 int rc;
3381 XpmAttributes attrs;
3382 Lisp_Object specified_file, color_symbols;
3383 #ifdef HAVE_NTGUI
3384 HDC hdc;
3385 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3386 #endif /* HAVE_NTGUI */
3388 /* Configure the XPM lib. Use the visual of frame F. Allocate
3389 close colors. Return colors allocated. */
3390 memset (&attrs, 0, sizeof attrs);
3392 #ifndef HAVE_NTGUI
3393 attrs.visual = FRAME_X_VISUAL (f);
3394 attrs.colormap = FRAME_X_COLORMAP (f);
3395 attrs.valuemask |= XpmVisual;
3396 attrs.valuemask |= XpmColormap;
3397 #endif /* HAVE_NTGUI */
3399 #ifdef ALLOC_XPM_COLORS
3400 /* Allocate colors with our own functions which handle
3401 failing color allocation more gracefully. */
3402 attrs.color_closure = f;
3403 attrs.alloc_color = xpm_alloc_color;
3404 attrs.free_colors = xpm_free_colors;
3405 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3406 #else /* not ALLOC_XPM_COLORS */
3407 /* Let the XPM lib allocate colors. */
3408 attrs.valuemask |= XpmReturnAllocPixels;
3409 #ifdef XpmAllocCloseColors
3410 attrs.alloc_close_colors = 1;
3411 attrs.valuemask |= XpmAllocCloseColors;
3412 #else /* not XpmAllocCloseColors */
3413 attrs.closeness = 600;
3414 attrs.valuemask |= XpmCloseness;
3415 #endif /* not XpmAllocCloseColors */
3416 #endif /* ALLOC_XPM_COLORS */
3418 /* If image specification contains symbolic color definitions, add
3419 these to `attrs'. */
3420 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3421 if (CONSP (color_symbols))
3423 Lisp_Object tail;
3424 XpmColorSymbol *xpm_syms;
3425 int i, size;
3427 attrs.valuemask |= XpmColorSymbols;
3429 /* Count number of symbols. */
3430 attrs.numsymbols = 0;
3431 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3432 ++attrs.numsymbols;
3434 /* Allocate an XpmColorSymbol array. */
3435 size = attrs.numsymbols * sizeof *xpm_syms;
3436 xpm_syms = (XpmColorSymbol *) alloca (size);
3437 memset (xpm_syms, 0, size);
3438 attrs.colorsymbols = xpm_syms;
3440 /* Fill the color symbol array. */
3441 for (tail = color_symbols, i = 0;
3442 CONSP (tail);
3443 ++i, tail = XCDR (tail))
3445 Lisp_Object name;
3446 Lisp_Object color;
3448 if (!CONSP (XCAR (tail)))
3450 xpm_syms[i].name = "";
3451 xpm_syms[i].value = "";
3452 continue;
3454 name = XCAR (XCAR (tail));
3455 color = XCDR (XCAR (tail));
3456 if (STRINGP (name))
3458 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3459 strcpy (xpm_syms[i].name, SDATA (name));
3461 else
3462 xpm_syms[i].name = "";
3463 if (STRINGP (color))
3465 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3466 strcpy (xpm_syms[i].value, SDATA (color));
3468 else
3469 xpm_syms[i].value = "";
3473 /* Create a pixmap for the image, either from a file, or from a
3474 string buffer containing data in the same format as an XPM file. */
3475 #ifdef ALLOC_XPM_COLORS
3476 xpm_init_color_cache (f, &attrs);
3477 #endif
3479 specified_file = image_spec_value (img->spec, QCfile, NULL);
3481 #ifdef HAVE_NTGUI
3483 HDC frame_dc = get_frame_dc (f);
3484 hdc = CreateCompatibleDC (frame_dc);
3485 release_frame_dc (f, frame_dc);
3487 #endif /* HAVE_NTGUI */
3489 if (STRINGP (specified_file))
3491 Lisp_Object file = x_find_image_file (specified_file);
3492 if (!STRINGP (file))
3494 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3495 #ifdef ALLOC_XPM_COLORS
3496 xpm_free_color_cache ();
3497 #endif
3498 return 0;
3501 #ifdef HAVE_NTGUI
3502 /* XpmReadFileToPixmap is not available in the Windows port of
3503 libxpm. But XpmReadFileToImage almost does what we want. */
3504 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3505 &xpm_image, &xpm_mask,
3506 &attrs);
3507 #else
3508 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3509 SDATA (file), &img->pixmap, &img->mask,
3510 &attrs);
3511 #endif /* HAVE_NTGUI */
3513 else
3515 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3516 if (!STRINGP (buffer))
3518 image_error ("Invalid image data `%s'", buffer, Qnil);
3519 #ifdef ALLOC_XPM_COLORS
3520 xpm_free_color_cache ();
3521 #endif
3522 return 0;
3524 #ifdef HAVE_NTGUI
3525 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3526 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3527 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3528 &xpm_image, &xpm_mask,
3529 &attrs);
3530 #else
3531 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3532 SDATA (buffer),
3533 &img->pixmap, &img->mask,
3534 &attrs);
3535 #endif /* HAVE_NTGUI */
3538 if (rc == XpmSuccess)
3540 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3541 img->colors = colors_in_color_table (&img->ncolors);
3542 #else /* not ALLOC_XPM_COLORS */
3543 int i;
3545 #ifdef HAVE_NTGUI
3546 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3547 plus some duplicate attributes. */
3548 if (xpm_image && xpm_image->bitmap)
3550 img->pixmap = xpm_image->bitmap;
3551 /* XImageFree in libXpm frees XImage struct without destroying
3552 the bitmap, which is what we want. */
3553 fn_XImageFree (xpm_image);
3555 if (xpm_mask && xpm_mask->bitmap)
3557 /* The mask appears to be inverted compared with what we expect.
3558 TODO: invert our expectations. See other places where we
3559 have to invert bits because our idea of masks is backwards. */
3560 HGDIOBJ old_obj;
3561 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3563 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3564 SelectObject (hdc, old_obj);
3566 img->mask = xpm_mask->bitmap;
3567 fn_XImageFree (xpm_mask);
3568 DeleteDC (hdc);
3571 DeleteDC (hdc);
3572 #endif /* HAVE_NTGUI */
3574 /* Remember allocated colors. */
3575 img->ncolors = attrs.nalloc_pixels;
3576 img->colors = (unsigned long *) xmalloc (img->ncolors
3577 * sizeof *img->colors);
3578 for (i = 0; i < attrs.nalloc_pixels; ++i)
3580 img->colors[i] = attrs.alloc_pixels[i];
3581 #ifdef DEBUG_X_COLORS
3582 register_color (img->colors[i]);
3583 #endif
3585 #endif /* not ALLOC_XPM_COLORS */
3587 img->width = attrs.width;
3588 img->height = attrs.height;
3589 xassert (img->width > 0 && img->height > 0);
3591 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3592 #ifdef HAVE_NTGUI
3593 fn_XpmFreeAttributes (&attrs);
3594 #else
3595 XpmFreeAttributes (&attrs);
3596 #endif /* HAVE_NTGUI */
3598 else
3600 #ifdef HAVE_NTGUI
3601 DeleteDC (hdc);
3602 #endif /* HAVE_NTGUI */
3604 switch (rc)
3606 case XpmOpenFailed:
3607 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3608 break;
3610 case XpmFileInvalid:
3611 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3612 break;
3614 case XpmNoMemory:
3615 image_error ("Out of memory (%s)", img->spec, Qnil);
3616 break;
3618 case XpmColorFailed:
3619 image_error ("Color allocation error (%s)", img->spec, Qnil);
3620 break;
3622 default:
3623 image_error ("Unknown error (%s)", img->spec, Qnil);
3624 break;
3628 #ifdef ALLOC_XPM_COLORS
3629 xpm_free_color_cache ();
3630 #endif
3631 return rc == XpmSuccess;
3634 #endif /* HAVE_XPM */
3636 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3638 /* XPM support functions for NS where libxpm is not available.
3639 Only XPM version 3 (without any extensions) is supported. */
3641 static int xpm_scan (const unsigned char **, const unsigned char *,
3642 const unsigned char **, int *);
3643 static Lisp_Object xpm_make_color_table_v
3644 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3645 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3646 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3647 int, Lisp_Object);
3648 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3649 const unsigned char *, int);
3650 static Lisp_Object xpm_make_color_table_h
3651 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3652 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3653 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3654 int, Lisp_Object);
3655 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3656 const unsigned char *, int);
3657 static int xpm_str_to_color_key (const char *);
3658 static int xpm_load_image (struct frame *, struct image *,
3659 const unsigned char *, const unsigned char *);
3661 /* Tokens returned from xpm_scan. */
3663 enum xpm_token
3665 XPM_TK_IDENT = 256,
3666 XPM_TK_STRING,
3667 XPM_TK_EOF
3670 /* Scan an XPM data and return a character (< 256) or a token defined
3671 by enum xpm_token above. *S and END are the start (inclusive) and
3672 the end (exclusive) addresses of the data, respectively. Advance
3673 *S while scanning. If token is either XPM_TK_IDENT or
3674 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3675 length of the corresponding token, respectively. */
3677 static int
3678 xpm_scan (const unsigned char **s,
3679 const unsigned char *end,
3680 const unsigned char **beg,
3681 int *len)
3683 int c;
3685 while (*s < end)
3687 /* Skip white-space. */
3688 while (*s < end && (c = *(*s)++, isspace (c)))
3691 /* gnus-pointer.xpm uses '-' in its identifier.
3692 sb-dir-plus.xpm uses '+' in its identifier. */
3693 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3695 *beg = *s - 1;
3696 while (*s < end
3697 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3698 ++*s;
3699 *len = *s - *beg;
3700 return XPM_TK_IDENT;
3702 else if (c == '"')
3704 *beg = *s;
3705 while (*s < end && **s != '"')
3706 ++*s;
3707 *len = *s - *beg;
3708 if (*s < end)
3709 ++*s;
3710 return XPM_TK_STRING;
3712 else if (c == '/')
3714 if (*s < end && **s == '*')
3716 /* C-style comment. */
3717 ++*s;
3720 while (*s < end && *(*s)++ != '*')
3723 while (*s < end && **s != '/');
3724 if (*s < end)
3725 ++*s;
3727 else
3728 return c;
3730 else
3731 return c;
3734 return XPM_TK_EOF;
3737 /* Functions for color table lookup in XPM data. A key is a string
3738 specifying the color of each pixel in XPM data. A value is either
3739 an integer that specifies a pixel color, Qt that specifies
3740 transparency, or Qnil for the unspecified color. If the length of
3741 the key string is one, a vector is used as a table. Otherwise, a
3742 hash table is used. */
3744 static Lisp_Object
3745 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3746 const unsigned char *,
3747 int,
3748 Lisp_Object),
3749 Lisp_Object (**get_func) (Lisp_Object,
3750 const unsigned char *,
3751 int))
3753 *put_func = xpm_put_color_table_v;
3754 *get_func = xpm_get_color_table_v;
3755 return Fmake_vector (make_number (256), Qnil);
3758 static void
3759 xpm_put_color_table_v (Lisp_Object color_table,
3760 const unsigned char *chars_start,
3761 int chars_len,
3762 Lisp_Object color)
3764 XVECTOR (color_table)->contents[*chars_start] = color;
3767 static Lisp_Object
3768 xpm_get_color_table_v (Lisp_Object color_table,
3769 const unsigned char *chars_start,
3770 int chars_len)
3772 return XVECTOR (color_table)->contents[*chars_start];
3775 static Lisp_Object
3776 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3777 const unsigned char *,
3778 int,
3779 Lisp_Object),
3780 Lisp_Object (**get_func) (Lisp_Object,
3781 const unsigned char *,
3782 int))
3784 *put_func = xpm_put_color_table_h;
3785 *get_func = xpm_get_color_table_h;
3786 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
3787 make_float (DEFAULT_REHASH_SIZE),
3788 make_float (DEFAULT_REHASH_THRESHOLD),
3789 Qnil, Qnil, Qnil);
3792 static void
3793 xpm_put_color_table_h (Lisp_Object color_table,
3794 const unsigned char *chars_start,
3795 int chars_len,
3796 Lisp_Object color)
3798 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3799 unsigned hash_code;
3800 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3802 hash_lookup (table, chars, &hash_code);
3803 hash_put (table, chars, color, hash_code);
3806 static Lisp_Object
3807 xpm_get_color_table_h (Lisp_Object color_table,
3808 const unsigned char *chars_start,
3809 int chars_len)
3811 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3812 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
3813 NULL);
3815 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3818 enum xpm_color_key {
3819 XPM_COLOR_KEY_S,
3820 XPM_COLOR_KEY_M,
3821 XPM_COLOR_KEY_G4,
3822 XPM_COLOR_KEY_G,
3823 XPM_COLOR_KEY_C
3826 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3828 static int
3829 xpm_str_to_color_key (const char *s)
3831 int i;
3833 for (i = 0;
3834 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3835 i++)
3836 if (strcmp (xpm_color_key_strings[i], s) == 0)
3837 return i;
3838 return -1;
3841 static int
3842 xpm_load_image (struct frame *f,
3843 struct image *img,
3844 const unsigned char *contents,
3845 const unsigned char *end)
3847 const unsigned char *s = contents, *beg, *str;
3848 unsigned char buffer[BUFSIZ];
3849 int width, height, x, y;
3850 int num_colors, chars_per_pixel;
3851 int len, LA1;
3852 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3853 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3854 Lisp_Object frame, color_symbols, color_table;
3855 int best_key, have_mask = 0;
3856 XImagePtr ximg = NULL, mask_img = NULL;
3858 #define match() \
3859 LA1 = xpm_scan (&s, end, &beg, &len)
3861 #define expect(TOKEN) \
3862 if (LA1 != (TOKEN)) \
3863 goto failure; \
3864 else \
3865 match ()
3867 #define expect_ident(IDENT) \
3868 if (LA1 == XPM_TK_IDENT \
3869 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3870 match (); \
3871 else \
3872 goto failure
3874 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3875 goto failure;
3876 s += 9;
3877 match ();
3878 expect_ident ("static");
3879 expect_ident ("char");
3880 expect ('*');
3881 expect (XPM_TK_IDENT);
3882 expect ('[');
3883 expect (']');
3884 expect ('=');
3885 expect ('{');
3886 expect (XPM_TK_STRING);
3887 if (len >= BUFSIZ)
3888 goto failure;
3889 memcpy (buffer, beg, len);
3890 buffer[len] = '\0';
3891 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3892 &num_colors, &chars_per_pixel) != 4
3893 || width <= 0 || height <= 0
3894 || num_colors <= 0 || chars_per_pixel <= 0)
3895 goto failure;
3897 if (!check_image_size (f, width, height))
3899 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
3900 goto failure;
3903 expect (',');
3905 XSETFRAME (frame, f);
3906 if (!NILP (Fxw_display_color_p (frame)))
3907 best_key = XPM_COLOR_KEY_C;
3908 else if (!NILP (Fx_display_grayscale_p (frame)))
3909 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
3910 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
3911 else
3912 best_key = XPM_COLOR_KEY_M;
3914 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3915 if (chars_per_pixel == 1)
3916 color_table = xpm_make_color_table_v (&put_color_table,
3917 &get_color_table);
3918 else
3919 color_table = xpm_make_color_table_h (&put_color_table,
3920 &get_color_table);
3922 while (num_colors-- > 0)
3924 unsigned char *color, *max_color;
3925 int key, next_key, max_key = 0;
3926 Lisp_Object symbol_color = Qnil, color_val;
3927 XColor cdef;
3929 expect (XPM_TK_STRING);
3930 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
3931 goto failure;
3932 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
3933 buffer[len - chars_per_pixel] = '\0';
3935 str = strtok (buffer, " \t");
3936 if (str == NULL)
3937 goto failure;
3938 key = xpm_str_to_color_key (str);
3939 if (key < 0)
3940 goto failure;
3943 color = strtok (NULL, " \t");
3944 if (color == NULL)
3945 goto failure;
3947 while ((str = strtok (NULL, " \t")) != NULL)
3949 next_key = xpm_str_to_color_key (str);
3950 if (next_key >= 0)
3951 break;
3952 color[strlen (color)] = ' ';
3955 if (key == XPM_COLOR_KEY_S)
3957 if (NILP (symbol_color))
3958 symbol_color = build_string (color);
3960 else if (max_key < key && key <= best_key)
3962 max_key = key;
3963 max_color = color;
3965 key = next_key;
3967 while (str);
3969 color_val = Qnil;
3970 if (!NILP (color_symbols) && !NILP (symbol_color))
3972 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
3974 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
3976 if (xstrcasecmp (SDATA (XCDR (specified_color)), "None") == 0)
3977 color_val = Qt;
3978 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
3979 &cdef, 0))
3980 color_val = make_number (cdef.pixel);
3983 if (NILP (color_val) && max_key > 0)
3985 if (xstrcasecmp (max_color, "None") == 0)
3986 color_val = Qt;
3987 else if (x_defined_color (f, max_color, &cdef, 0))
3988 color_val = make_number (cdef.pixel);
3990 if (!NILP (color_val))
3991 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
3993 expect (',');
3996 if (!x_create_x_image_and_pixmap (f, width, height, 0,
3997 &ximg, &img->pixmap)
3998 #ifndef HAVE_NS
3999 || !x_create_x_image_and_pixmap (f, width, height, 1,
4000 &mask_img, &img->mask)
4001 #endif
4004 image_error ("Out of memory (%s)", img->spec, Qnil);
4005 goto error;
4008 for (y = 0; y < height; y++)
4010 expect (XPM_TK_STRING);
4011 str = beg;
4012 if (len < width * chars_per_pixel)
4013 goto failure;
4014 for (x = 0; x < width; x++, str += chars_per_pixel)
4016 Lisp_Object color_val =
4017 (*get_color_table) (color_table, str, chars_per_pixel);
4019 XPutPixel (ximg, x, y,
4020 (INTEGERP (color_val) ? XINT (color_val)
4021 : FRAME_FOREGROUND_PIXEL (f)));
4022 #ifndef HAVE_NS
4023 XPutPixel (mask_img, x, y,
4024 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4025 : (have_mask = 1, PIX_MASK_RETAIN)));
4026 #else
4027 if (EQ (color_val, Qt))
4028 ns_set_alpha (ximg, x, y, 0);
4029 #endif
4031 if (y + 1 < height)
4032 expect (',');
4035 img->width = width;
4036 img->height = height;
4038 /* Maybe fill in the background field while we have ximg handy. */
4039 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4040 IMAGE_BACKGROUND (img, f, ximg);
4042 x_put_x_image (f, ximg, img->pixmap, width, height);
4043 x_destroy_x_image (ximg);
4044 #ifndef HAVE_NS
4045 if (have_mask)
4047 /* Fill in the background_transparent field while we have the
4048 mask handy. */
4049 image_background_transparent (img, f, mask_img);
4051 x_put_x_image (f, mask_img, img->mask, width, height);
4052 x_destroy_x_image (mask_img);
4054 else
4056 x_destroy_x_image (mask_img);
4057 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4058 img->mask = NO_PIXMAP;
4060 #endif
4061 return 1;
4063 failure:
4064 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4065 error:
4066 x_destroy_x_image (ximg);
4067 x_destroy_x_image (mask_img);
4068 x_clear_image (f, img);
4069 return 0;
4071 #undef match
4072 #undef expect
4073 #undef expect_ident
4076 static int
4077 xpm_load (struct frame *f,
4078 struct image *img)
4080 int success_p = 0;
4081 Lisp_Object file_name;
4083 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4084 file_name = image_spec_value (img->spec, QCfile, NULL);
4085 if (STRINGP (file_name))
4087 Lisp_Object file;
4088 unsigned char *contents;
4089 int size;
4091 file = x_find_image_file (file_name);
4092 if (!STRINGP (file))
4094 image_error ("Cannot find image file `%s'", file_name, Qnil);
4095 return 0;
4098 contents = slurp_file (SDATA (file), &size);
4099 if (contents == NULL)
4101 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4102 return 0;
4105 success_p = xpm_load_image (f, img, contents, contents + size);
4106 xfree (contents);
4108 else
4110 Lisp_Object data;
4112 data = image_spec_value (img->spec, QCdata, NULL);
4113 if (!STRINGP (data))
4115 image_error ("Invalid image data `%s'", data, Qnil);
4116 return 0;
4118 success_p = xpm_load_image (f, img, SDATA (data),
4119 SDATA (data) + SBYTES (data));
4122 return success_p;
4125 #endif /* HAVE_NS && !HAVE_XPM */
4129 /***********************************************************************
4130 Color table
4131 ***********************************************************************/
4133 #ifdef COLOR_TABLE_SUPPORT
4135 /* An entry in the color table mapping an RGB color to a pixel color. */
4137 struct ct_color
4139 int r, g, b;
4140 unsigned long pixel;
4142 /* Next in color table collision list. */
4143 struct ct_color *next;
4146 /* The bucket vector size to use. Must be prime. */
4148 #define CT_SIZE 101
4150 /* Value is a hash of the RGB color given by R, G, and B. */
4152 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4154 /* The color hash table. */
4156 struct ct_color **ct_table;
4158 /* Number of entries in the color table. */
4160 int ct_colors_allocated;
4162 /* Initialize the color table. */
4164 static void
4165 init_color_table (void)
4167 int size = CT_SIZE * sizeof (*ct_table);
4168 ct_table = (struct ct_color **) xmalloc (size);
4169 memset (ct_table, 0, size);
4170 ct_colors_allocated = 0;
4174 /* Free memory associated with the color table. */
4176 static void
4177 free_color_table (void)
4179 int i;
4180 struct ct_color *p, *next;
4182 for (i = 0; i < CT_SIZE; ++i)
4183 for (p = ct_table[i]; p; p = next)
4185 next = p->next;
4186 xfree (p);
4189 xfree (ct_table);
4190 ct_table = NULL;
4194 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4195 entry for that color already is in the color table, return the
4196 pixel color of that entry. Otherwise, allocate a new color for R,
4197 G, B, and make an entry in the color table. */
4199 static unsigned long
4200 lookup_rgb_color (struct frame *f, int r, int g, int b)
4202 unsigned hash = CT_HASH_RGB (r, g, b);
4203 int i = hash % CT_SIZE;
4204 struct ct_color *p;
4205 Display_Info *dpyinfo;
4207 /* Handle TrueColor visuals specially, which improves performance by
4208 two orders of magnitude. Freeing colors on TrueColor visuals is
4209 a nop, and pixel colors specify RGB values directly. See also
4210 the Xlib spec, chapter 3.1. */
4211 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4212 if (dpyinfo->red_bits > 0)
4214 unsigned long pr, pg, pb;
4216 /* Apply gamma-correction like normal color allocation does. */
4217 if (f->gamma)
4219 XColor color;
4220 color.red = r, color.green = g, color.blue = b;
4221 gamma_correct (f, &color);
4222 r = color.red, g = color.green, b = color.blue;
4225 /* Scale down RGB values to the visual's bits per RGB, and shift
4226 them to the right position in the pixel color. Note that the
4227 original RGB values are 16-bit values, as usual in X. */
4228 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4229 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4230 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4232 /* Assemble the pixel color. */
4233 return pr | pg | pb;
4236 for (p = ct_table[i]; p; p = p->next)
4237 if (p->r == r && p->g == g && p->b == b)
4238 break;
4240 if (p == NULL)
4243 #ifdef HAVE_X_WINDOWS
4244 XColor color;
4245 Colormap cmap;
4246 int rc;
4248 color.red = r;
4249 color.green = g;
4250 color.blue = b;
4252 cmap = FRAME_X_COLORMAP (f);
4253 rc = x_alloc_nearest_color (f, cmap, &color);
4254 if (rc)
4256 ++ct_colors_allocated;
4257 p = (struct ct_color *) xmalloc (sizeof *p);
4258 p->r = r;
4259 p->g = g;
4260 p->b = b;
4261 p->pixel = color.pixel;
4262 p->next = ct_table[i];
4263 ct_table[i] = p;
4265 else
4266 return FRAME_FOREGROUND_PIXEL (f);
4268 #else
4269 COLORREF color;
4270 #ifdef HAVE_NTGUI
4271 color = PALETTERGB (r, g, b);
4272 #else
4273 color = RGB_TO_ULONG (r, g, b);
4274 #endif /* HAVE_NTGUI */
4275 ++ct_colors_allocated;
4276 p = (struct ct_color *) xmalloc (sizeof *p);
4277 p->r = r;
4278 p->g = g;
4279 p->b = b;
4280 p->pixel = color;
4281 p->next = ct_table[i];
4282 ct_table[i] = p;
4283 #endif /* HAVE_X_WINDOWS */
4287 return p->pixel;
4291 /* Look up pixel color PIXEL which is used on frame F in the color
4292 table. If not already present, allocate it. Value is PIXEL. */
4294 static unsigned long
4295 lookup_pixel_color (struct frame *f, unsigned long pixel)
4297 int i = pixel % CT_SIZE;
4298 struct ct_color *p;
4300 for (p = ct_table[i]; p; p = p->next)
4301 if (p->pixel == pixel)
4302 break;
4304 if (p == NULL)
4306 XColor color;
4307 Colormap cmap;
4308 int rc;
4310 #ifdef HAVE_X_WINDOWS
4311 cmap = FRAME_X_COLORMAP (f);
4312 color.pixel = pixel;
4313 x_query_color (f, &color);
4314 rc = x_alloc_nearest_color (f, cmap, &color);
4315 #else
4316 BLOCK_INPUT;
4317 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4318 color.pixel = pixel;
4319 XQueryColor (NULL, cmap, &color);
4320 rc = x_alloc_nearest_color (f, cmap, &color);
4321 UNBLOCK_INPUT;
4322 #endif /* HAVE_X_WINDOWS */
4324 if (rc)
4326 ++ct_colors_allocated;
4328 p = (struct ct_color *) xmalloc (sizeof *p);
4329 p->r = color.red;
4330 p->g = color.green;
4331 p->b = color.blue;
4332 p->pixel = pixel;
4333 p->next = ct_table[i];
4334 ct_table[i] = p;
4336 else
4337 return FRAME_FOREGROUND_PIXEL (f);
4339 return p->pixel;
4343 /* Value is a vector of all pixel colors contained in the color table,
4344 allocated via xmalloc. Set *N to the number of colors. */
4346 static unsigned long *
4347 colors_in_color_table (int *n)
4349 int i, j;
4350 struct ct_color *p;
4351 unsigned long *colors;
4353 if (ct_colors_allocated == 0)
4355 *n = 0;
4356 colors = NULL;
4358 else
4360 colors = (unsigned long *) xmalloc (ct_colors_allocated
4361 * sizeof *colors);
4362 *n = ct_colors_allocated;
4364 for (i = j = 0; i < CT_SIZE; ++i)
4365 for (p = ct_table[i]; p; p = p->next)
4366 colors[j++] = p->pixel;
4369 return colors;
4372 #else /* COLOR_TABLE_SUPPORT */
4374 static unsigned long
4375 lookup_rgb_color (struct frame *f, int r, int g, int b)
4377 unsigned long pixel;
4379 #ifdef HAVE_NTGUI
4380 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4381 #endif /* HAVE_NTGUI */
4383 #ifdef HAVE_NS
4384 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4385 #endif /* HAVE_NS */
4386 return pixel;
4389 static void
4390 init_color_table (void)
4393 #endif /* COLOR_TABLE_SUPPORT */
4396 /***********************************************************************
4397 Algorithms
4398 ***********************************************************************/
4400 static XColor *x_to_xcolors (struct frame *, struct image *, int);
4401 static void x_from_xcolors (struct frame *, struct image *, XColor *);
4402 static void x_detect_edges (struct frame *, struct image *, int[9], int);
4404 #ifdef HAVE_NTGUI
4405 static void XPutPixel (XImagePtr , int, int, COLORREF);
4406 #endif /* HAVE_NTGUI */
4408 /* Non-zero means draw a cross on images having `:conversion
4409 disabled'. */
4411 int cross_disabled_images;
4413 /* Edge detection matrices for different edge-detection
4414 strategies. */
4416 static int emboss_matrix[9] = {
4417 /* x - 1 x x + 1 */
4418 2, -1, 0, /* y - 1 */
4419 -1, 0, 1, /* y */
4420 0, 1, -2 /* y + 1 */
4423 static int laplace_matrix[9] = {
4424 /* x - 1 x x + 1 */
4425 1, 0, 0, /* y - 1 */
4426 0, 0, 0, /* y */
4427 0, 0, -1 /* y + 1 */
4430 /* Value is the intensity of the color whose red/green/blue values
4431 are R, G, and B. */
4433 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4436 /* On frame F, return an array of XColor structures describing image
4437 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4438 non-zero means also fill the red/green/blue members of the XColor
4439 structures. Value is a pointer to the array of XColors structures,
4440 allocated with xmalloc; it must be freed by the caller. */
4442 static XColor *
4443 x_to_xcolors (struct frame *f, struct image *img, int rgb_p)
4445 int x, y;
4446 XColor *colors, *p;
4447 XImagePtr_or_DC ximg;
4448 #ifdef HAVE_NTGUI
4449 HDC hdc;
4450 HGDIOBJ prev;
4451 #endif /* HAVE_NTGUI */
4453 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4455 #ifndef HAVE_NTGUI
4456 /* Get the X image IMG->pixmap. */
4457 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4458 0, 0, img->width, img->height, ~0, ZPixmap);
4459 #else
4460 /* Load the image into a memory device context. */
4461 hdc = get_frame_dc (f);
4462 ximg = CreateCompatibleDC (hdc);
4463 release_frame_dc (f, hdc);
4464 prev = SelectObject (ximg, img->pixmap);
4465 #endif /* HAVE_NTGUI */
4467 /* Fill the `pixel' members of the XColor array. I wished there
4468 were an easy and portable way to circumvent XGetPixel. */
4469 p = colors;
4470 for (y = 0; y < img->height; ++y)
4472 XColor *row = p;
4474 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4475 for (x = 0; x < img->width; ++x, ++p)
4476 p->pixel = GET_PIXEL (ximg, x, y);
4477 if (rgb_p)
4478 x_query_colors (f, row, img->width);
4480 #else
4482 for (x = 0; x < img->width; ++x, ++p)
4484 /* W32_TODO: palette support needed here? */
4485 p->pixel = GET_PIXEL (ximg, x, y);
4486 if (rgb_p)
4488 p->red = RED16_FROM_ULONG (p->pixel);
4489 p->green = GREEN16_FROM_ULONG (p->pixel);
4490 p->blue = BLUE16_FROM_ULONG (p->pixel);
4493 #endif /* HAVE_X_WINDOWS */
4496 Destroy_Image (ximg, prev);
4498 return colors;
4501 #ifdef HAVE_NTGUI
4503 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4504 created with CreateDIBSection, with the pointer to the bit values
4505 stored in ximg->data. */
4507 static void
4508 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4510 int width = ximg->info.bmiHeader.biWidth;
4511 int height = ximg->info.bmiHeader.biHeight;
4512 unsigned char * pixel;
4514 /* True color images. */
4515 if (ximg->info.bmiHeader.biBitCount == 24)
4517 int rowbytes = width * 3;
4518 /* Ensure scanlines are aligned on 4 byte boundaries. */
4519 if (rowbytes % 4)
4520 rowbytes += 4 - (rowbytes % 4);
4522 pixel = ximg->data + y * rowbytes + x * 3;
4523 /* Windows bitmaps are in BGR order. */
4524 *pixel = GetBValue (color);
4525 *(pixel + 1) = GetGValue (color);
4526 *(pixel + 2) = GetRValue (color);
4528 /* Monochrome images. */
4529 else if (ximg->info.bmiHeader.biBitCount == 1)
4531 int rowbytes = width / 8;
4532 /* Ensure scanlines are aligned on 4 byte boundaries. */
4533 if (rowbytes % 4)
4534 rowbytes += 4 - (rowbytes % 4);
4535 pixel = ximg->data + y * rowbytes + x / 8;
4536 /* Filter out palette info. */
4537 if (color & 0x00ffffff)
4538 *pixel = *pixel | (1 << x % 8);
4539 else
4540 *pixel = *pixel & ~(1 << x % 8);
4542 else
4543 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4546 #endif /* HAVE_NTGUI */
4548 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4549 RGB members are set. F is the frame on which this all happens.
4550 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4552 static void
4553 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4555 int x, y;
4556 XImagePtr oimg = NULL;
4557 Pixmap pixmap;
4558 XColor *p;
4560 init_color_table ();
4562 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4563 &oimg, &pixmap);
4564 p = colors;
4565 for (y = 0; y < img->height; ++y)
4566 for (x = 0; x < img->width; ++x, ++p)
4568 unsigned long pixel;
4569 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4570 XPutPixel (oimg, x, y, pixel);
4573 xfree (colors);
4574 x_clear_image_1 (f, img, 1, 0, 1);
4576 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4577 x_destroy_x_image (oimg);
4578 img->pixmap = pixmap;
4579 #ifdef COLOR_TABLE_SUPPORT
4580 img->colors = colors_in_color_table (&img->ncolors);
4581 free_color_table ();
4582 #endif /* COLOR_TABLE_SUPPORT */
4586 /* On frame F, perform edge-detection on image IMG.
4588 MATRIX is a nine-element array specifying the transformation
4589 matrix. See emboss_matrix for an example.
4591 COLOR_ADJUST is a color adjustment added to each pixel of the
4592 outgoing image. */
4594 static void
4595 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4597 XColor *colors = x_to_xcolors (f, img, 1);
4598 XColor *new, *p;
4599 int x, y, i, sum;
4601 for (i = sum = 0; i < 9; ++i)
4602 sum += eabs (matrix[i]);
4604 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4606 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4608 for (y = 0; y < img->height; ++y)
4610 p = COLOR (new, 0, y);
4611 p->red = p->green = p->blue = 0xffff/2;
4612 p = COLOR (new, img->width - 1, y);
4613 p->red = p->green = p->blue = 0xffff/2;
4616 for (x = 1; x < img->width - 1; ++x)
4618 p = COLOR (new, x, 0);
4619 p->red = p->green = p->blue = 0xffff/2;
4620 p = COLOR (new, x, img->height - 1);
4621 p->red = p->green = p->blue = 0xffff/2;
4624 for (y = 1; y < img->height - 1; ++y)
4626 p = COLOR (new, 1, y);
4628 for (x = 1; x < img->width - 1; ++x, ++p)
4630 int r, g, b, y1, x1;
4632 r = g = b = i = 0;
4633 for (y1 = y - 1; y1 < y + 2; ++y1)
4634 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
4635 if (matrix[i])
4637 XColor *t = COLOR (colors, x1, y1);
4638 r += matrix[i] * t->red;
4639 g += matrix[i] * t->green;
4640 b += matrix[i] * t->blue;
4643 r = (r / sum + color_adjust) & 0xffff;
4644 g = (g / sum + color_adjust) & 0xffff;
4645 b = (b / sum + color_adjust) & 0xffff;
4646 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4650 xfree (colors);
4651 x_from_xcolors (f, img, new);
4653 #undef COLOR
4657 /* Perform the pre-defined `emboss' edge-detection on image IMG
4658 on frame F. */
4660 static void
4661 x_emboss (struct frame *f, struct image *img)
4663 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4667 /* Transform image IMG which is used on frame F with a Laplace
4668 edge-detection algorithm. The result is an image that can be used
4669 to draw disabled buttons, for example. */
4671 static void
4672 x_laplace (struct frame *f, struct image *img)
4674 x_detect_edges (f, img, laplace_matrix, 45000);
4678 /* Perform edge-detection on image IMG on frame F, with specified
4679 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4681 MATRIX must be either
4683 - a list of at least 9 numbers in row-major form
4684 - a vector of at least 9 numbers
4686 COLOR_ADJUST nil means use a default; otherwise it must be a
4687 number. */
4689 static void
4690 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4691 Lisp_Object color_adjust)
4693 int i = 0;
4694 int trans[9];
4696 if (CONSP (matrix))
4698 for (i = 0;
4699 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4700 ++i, matrix = XCDR (matrix))
4701 trans[i] = XFLOATINT (XCAR (matrix));
4703 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4705 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4706 trans[i] = XFLOATINT (AREF (matrix, i));
4709 if (NILP (color_adjust))
4710 color_adjust = make_number (0xffff / 2);
4712 if (i == 9 && NUMBERP (color_adjust))
4713 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
4717 /* Transform image IMG on frame F so that it looks disabled. */
4719 static void
4720 x_disable_image (struct frame *f, struct image *img)
4722 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4723 #ifdef HAVE_NTGUI
4724 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4725 #else
4726 int n_planes = dpyinfo->n_planes;
4727 #endif /* HAVE_NTGUI */
4729 if (n_planes >= 2)
4731 /* Color (or grayscale). Convert to gray, and equalize. Just
4732 drawing such images with a stipple can look very odd, so
4733 we're using this method instead. */
4734 XColor *colors = x_to_xcolors (f, img, 1);
4735 XColor *p, *end;
4736 const int h = 15000;
4737 const int l = 30000;
4739 for (p = colors, end = colors + img->width * img->height;
4740 p < end;
4741 ++p)
4743 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4744 int i2 = (0xffff - h - l) * i / 0xffff + l;
4745 p->red = p->green = p->blue = i2;
4748 x_from_xcolors (f, img, colors);
4751 /* Draw a cross over the disabled image, if we must or if we
4752 should. */
4753 if (n_planes < 2 || cross_disabled_images)
4755 #ifndef HAVE_NTGUI
4756 Display *dpy = FRAME_X_DISPLAY (f);
4757 GC gc;
4759 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4761 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4763 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4764 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4765 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4766 img->width - 1, img->height - 1);
4767 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4768 img->width - 1, 0);
4769 XFreeGC (dpy, gc);
4771 if (img->mask)
4773 gc = XCreateGC (dpy, img->mask, 0, NULL);
4774 XSetForeground (dpy, gc, MaskForeground (f));
4775 XDrawLine (dpy, img->mask, gc, 0, 0,
4776 img->width - 1, img->height - 1);
4777 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4778 img->width - 1, 0);
4779 XFreeGC (dpy, gc);
4781 #endif /* !HAVE_NS */
4782 #else
4783 HDC hdc, bmpdc;
4784 HGDIOBJ prev;
4786 hdc = get_frame_dc (f);
4787 bmpdc = CreateCompatibleDC (hdc);
4788 release_frame_dc (f, hdc);
4790 prev = SelectObject (bmpdc, img->pixmap);
4792 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4793 MoveToEx (bmpdc, 0, 0, NULL);
4794 LineTo (bmpdc, img->width - 1, img->height - 1);
4795 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4796 LineTo (bmpdc, img->width - 1, 0);
4798 if (img->mask)
4800 SelectObject (bmpdc, img->mask);
4801 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4802 MoveToEx (bmpdc, 0, 0, NULL);
4803 LineTo (bmpdc, img->width - 1, img->height - 1);
4804 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4805 LineTo (bmpdc, img->width - 1, 0);
4807 SelectObject (bmpdc, prev);
4808 DeleteDC (bmpdc);
4809 #endif /* HAVE_NTGUI */
4814 /* Build a mask for image IMG which is used on frame F. FILE is the
4815 name of an image file, for error messages. HOW determines how to
4816 determine the background color of IMG. If it is a list '(R G B)',
4817 with R, G, and B being integers >= 0, take that as the color of the
4818 background. Otherwise, determine the background color of IMG
4819 heuristically. Value is non-zero if successful. */
4821 static int
4822 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4824 XImagePtr_or_DC ximg;
4825 #ifndef HAVE_NTGUI
4826 XImagePtr mask_img;
4827 #else
4828 HDC frame_dc;
4829 HGDIOBJ prev;
4830 char *mask_img;
4831 int row_width;
4832 #endif /* HAVE_NTGUI */
4833 int x, y, rc, use_img_background;
4834 unsigned long bg = 0;
4836 if (img->mask)
4838 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4839 img->mask = NO_PIXMAP;
4840 img->background_transparent_valid = 0;
4843 #ifndef HAVE_NTGUI
4844 #ifndef HAVE_NS
4845 /* Create an image and pixmap serving as mask. */
4846 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4847 &mask_img, &img->mask);
4848 if (!rc)
4849 return 0;
4850 #endif /* !HAVE_NS */
4852 /* Get the X image of IMG->pixmap. */
4853 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4854 img->width, img->height,
4855 ~0, ZPixmap);
4856 #else
4857 /* Create the bit array serving as mask. */
4858 row_width = (img->width + 7) / 8;
4859 mask_img = xmalloc (row_width * img->height);
4860 memset (mask_img, 0, row_width * img->height);
4862 /* Create a memory device context for IMG->pixmap. */
4863 frame_dc = get_frame_dc (f);
4864 ximg = CreateCompatibleDC (frame_dc);
4865 release_frame_dc (f, frame_dc);
4866 prev = SelectObject (ximg, img->pixmap);
4867 #endif /* HAVE_NTGUI */
4869 /* Determine the background color of ximg. If HOW is `(R G B)'
4870 take that as color. Otherwise, use the image's background color. */
4871 use_img_background = 1;
4873 if (CONSP (how))
4875 int rgb[3], i;
4877 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4879 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4880 how = XCDR (how);
4883 if (i == 3 && NILP (how))
4885 char color_name[30];
4886 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4887 bg = (
4888 #ifdef HAVE_NTGUI
4889 0x00ffffff & /* Filter out palette info. */
4890 #endif /* HAVE_NTGUI */
4891 x_alloc_image_color (f, img, build_string (color_name), 0));
4892 use_img_background = 0;
4896 if (use_img_background)
4897 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4899 /* Set all bits in mask_img to 1 whose color in ximg is different
4900 from the background color bg. */
4901 #ifndef HAVE_NTGUI
4902 for (y = 0; y < img->height; ++y)
4903 for (x = 0; x < img->width; ++x)
4904 #ifndef HAVE_NS
4905 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4906 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4907 #else
4908 if (XGetPixel (ximg, x, y) == bg)
4909 ns_set_alpha (ximg, x, y, 0);
4910 #endif /* HAVE_NS */
4911 #ifndef HAVE_NS
4912 /* Fill in the background_transparent field while we have the mask handy. */
4913 image_background_transparent (img, f, mask_img);
4915 /* Put mask_img into img->mask. */
4916 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4917 x_destroy_x_image (mask_img);
4918 #endif /* !HAVE_NS */
4919 #else
4920 for (y = 0; y < img->height; ++y)
4921 for (x = 0; x < img->width; ++x)
4923 COLORREF p = GetPixel (ximg, x, y);
4924 if (p != bg)
4925 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4928 /* Create the mask image. */
4929 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4930 mask_img);
4931 /* Fill in the background_transparent field while we have the mask handy. */
4932 SelectObject (ximg, img->mask);
4933 image_background_transparent (img, f, ximg);
4935 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4936 xfree (mask_img);
4937 #endif /* HAVE_NTGUI */
4939 Destroy_Image (ximg, prev);
4941 return 1;
4945 /***********************************************************************
4946 PBM (mono, gray, color)
4947 ***********************************************************************/
4949 static int pbm_image_p (Lisp_Object object);
4950 static int pbm_load (struct frame *f, struct image *img);
4951 static int pbm_scan_number (unsigned char **, unsigned char *);
4953 /* The symbol `pbm' identifying images of this type. */
4955 Lisp_Object Qpbm;
4957 /* Indices of image specification fields in gs_format, below. */
4959 enum pbm_keyword_index
4961 PBM_TYPE,
4962 PBM_FILE,
4963 PBM_DATA,
4964 PBM_ASCENT,
4965 PBM_MARGIN,
4966 PBM_RELIEF,
4967 PBM_ALGORITHM,
4968 PBM_HEURISTIC_MASK,
4969 PBM_MASK,
4970 PBM_FOREGROUND,
4971 PBM_BACKGROUND,
4972 PBM_LAST
4975 /* Vector of image_keyword structures describing the format
4976 of valid user-defined image specifications. */
4978 static const struct image_keyword pbm_format[PBM_LAST] =
4980 {":type", IMAGE_SYMBOL_VALUE, 1},
4981 {":file", IMAGE_STRING_VALUE, 0},
4982 {":data", IMAGE_STRING_VALUE, 0},
4983 {":ascent", IMAGE_ASCENT_VALUE, 0},
4984 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
4985 {":relief", IMAGE_INTEGER_VALUE, 0},
4986 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4987 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4988 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4989 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4990 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4993 /* Structure describing the image type `pbm'. */
4995 static struct image_type pbm_type =
4997 &Qpbm,
4998 pbm_image_p,
4999 pbm_load,
5000 x_clear_image,
5001 NULL
5005 /* Return non-zero if OBJECT is a valid PBM image specification. */
5007 static int
5008 pbm_image_p (Lisp_Object object)
5010 struct image_keyword fmt[PBM_LAST];
5012 memcpy (fmt, pbm_format, sizeof fmt);
5014 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5015 return 0;
5017 /* Must specify either :data or :file. */
5018 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5022 /* Scan a decimal number from *S and return it. Advance *S while
5023 reading the number. END is the end of the string. Value is -1 at
5024 end of input. */
5026 static int
5027 pbm_scan_number (unsigned char **s, unsigned char *end)
5029 int c = 0, val = -1;
5031 while (*s < end)
5033 /* Skip white-space. */
5034 while (*s < end && (c = *(*s)++, isspace (c)))
5037 if (c == '#')
5039 /* Skip comment to end of line. */
5040 while (*s < end && (c = *(*s)++, c != '\n'))
5043 else if (isdigit (c))
5045 /* Read decimal number. */
5046 val = c - '0';
5047 while (*s < end && (c = *(*s)++, isdigit (c)))
5048 val = 10 * val + c - '0';
5049 break;
5051 else
5052 break;
5055 return val;
5059 #ifdef HAVE_NTGUI
5060 #if 0 /* Unused. ++kfs */
5062 /* Read FILE into memory. Value is a pointer to a buffer allocated
5063 with xmalloc holding FILE's contents. Value is null if an error
5064 occurred. *SIZE is set to the size of the file. */
5066 static char *
5067 pbm_read_file (file, size)
5068 Lisp_Object file;
5069 int *size;
5071 FILE *fp = NULL;
5072 char *buf = NULL;
5073 struct stat st;
5075 if (stat (SDATA (file), &st) == 0
5076 && (fp = fopen (SDATA (file), "rb")) != NULL
5077 && (buf = (char *) xmalloc (st.st_size),
5078 fread (buf, 1, st.st_size, fp) == st.st_size))
5080 *size = st.st_size;
5081 fclose (fp);
5083 else
5085 if (fp)
5086 fclose (fp);
5087 if (buf)
5089 xfree (buf);
5090 buf = NULL;
5094 return buf;
5096 #endif
5097 #endif /* HAVE_NTGUI */
5099 /* Load PBM image IMG for use on frame F. */
5101 static int
5102 pbm_load (struct frame *f, struct image *img)
5104 int raw_p, x, y;
5105 int width, height, max_color_idx = 0;
5106 XImagePtr ximg;
5107 Lisp_Object file, specified_file;
5108 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5109 unsigned char *contents = NULL;
5110 unsigned char *end, *p;
5111 int size;
5113 specified_file = image_spec_value (img->spec, QCfile, NULL);
5115 if (STRINGP (specified_file))
5117 file = x_find_image_file (specified_file);
5118 if (!STRINGP (file))
5120 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5121 return 0;
5124 contents = slurp_file (SDATA (file), &size);
5125 if (contents == NULL)
5127 image_error ("Error reading `%s'", file, Qnil);
5128 return 0;
5131 p = contents;
5132 end = contents + size;
5134 else
5136 Lisp_Object data;
5137 data = image_spec_value (img->spec, QCdata, NULL);
5138 if (!STRINGP (data))
5140 image_error ("Invalid image data `%s'", data, Qnil);
5141 return 0;
5143 p = SDATA (data);
5144 end = p + SBYTES (data);
5147 /* Check magic number. */
5148 if (end - p < 2 || *p++ != 'P')
5150 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5151 error:
5152 xfree (contents);
5153 return 0;
5156 switch (*p++)
5158 case '1':
5159 raw_p = 0, type = PBM_MONO;
5160 break;
5162 case '2':
5163 raw_p = 0, type = PBM_GRAY;
5164 break;
5166 case '3':
5167 raw_p = 0, type = PBM_COLOR;
5168 break;
5170 case '4':
5171 raw_p = 1, type = PBM_MONO;
5172 break;
5174 case '5':
5175 raw_p = 1, type = PBM_GRAY;
5176 break;
5178 case '6':
5179 raw_p = 1, type = PBM_COLOR;
5180 break;
5182 default:
5183 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5184 goto error;
5187 /* Read width, height, maximum color-component. Characters
5188 starting with `#' up to the end of a line are ignored. */
5189 width = pbm_scan_number (&p, end);
5190 height = pbm_scan_number (&p, end);
5192 if (type != PBM_MONO)
5194 max_color_idx = pbm_scan_number (&p, end);
5195 if (max_color_idx > 65535 || max_color_idx < 0)
5197 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5198 goto error;
5202 if (!check_image_size (f, width, height))
5204 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5205 goto error;
5208 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5209 &ximg, &img->pixmap))
5210 goto error;
5212 /* Initialize the color hash table. */
5213 init_color_table ();
5215 if (type == PBM_MONO)
5217 int c = 0, g;
5218 struct image_keyword fmt[PBM_LAST];
5219 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5220 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5222 /* Parse the image specification. */
5223 memcpy (fmt, pbm_format, sizeof fmt);
5224 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5226 /* Get foreground and background colors, maybe allocate colors. */
5227 if (fmt[PBM_FOREGROUND].count
5228 && STRINGP (fmt[PBM_FOREGROUND].value))
5229 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5230 if (fmt[PBM_BACKGROUND].count
5231 && STRINGP (fmt[PBM_BACKGROUND].value))
5233 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5234 img->background = bg;
5235 img->background_valid = 1;
5238 for (y = 0; y < height; ++y)
5239 for (x = 0; x < width; ++x)
5241 if (raw_p)
5243 if ((x & 7) == 0)
5245 if (p >= end)
5247 x_destroy_x_image (ximg);
5248 x_clear_image (f, img);
5249 image_error ("Invalid image size in image `%s'",
5250 img->spec, Qnil);
5251 goto error;
5253 c = *p++;
5255 g = c & 0x80;
5256 c <<= 1;
5258 else
5259 g = pbm_scan_number (&p, end);
5261 XPutPixel (ximg, x, y, g ? fg : bg);
5264 else
5266 int expected_size = height * width;
5267 if (max_color_idx > 255)
5268 expected_size *= 2;
5269 if (type == PBM_COLOR)
5270 expected_size *= 3;
5272 if (raw_p && p + expected_size > end)
5274 x_destroy_x_image (ximg);
5275 x_clear_image (f, img);
5276 image_error ("Invalid image size in image `%s'",
5277 img->spec, Qnil);
5278 goto error;
5281 for (y = 0; y < height; ++y)
5282 for (x = 0; x < width; ++x)
5284 int r, g, b;
5286 if (type == PBM_GRAY && raw_p)
5288 r = g = b = *p++;
5289 if (max_color_idx > 255)
5290 r = g = b = r * 256 + *p++;
5292 else if (type == PBM_GRAY)
5293 r = g = b = pbm_scan_number (&p, end);
5294 else if (raw_p)
5296 r = *p++;
5297 if (max_color_idx > 255)
5298 r = r * 256 + *p++;
5299 g = *p++;
5300 if (max_color_idx > 255)
5301 g = g * 256 + *p++;
5302 b = *p++;
5303 if (max_color_idx > 255)
5304 b = b * 256 + *p++;
5306 else
5308 r = pbm_scan_number (&p, end);
5309 g = pbm_scan_number (&p, end);
5310 b = pbm_scan_number (&p, end);
5313 if (r < 0 || g < 0 || b < 0)
5315 x_destroy_x_image (ximg);
5316 image_error ("Invalid pixel value in image `%s'",
5317 img->spec, Qnil);
5318 goto error;
5321 /* RGB values are now in the range 0..max_color_idx.
5322 Scale this to the range 0..0xffff supported by X. */
5323 r = (double) r * 65535 / max_color_idx;
5324 g = (double) g * 65535 / max_color_idx;
5325 b = (double) b * 65535 / max_color_idx;
5326 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5330 #ifdef COLOR_TABLE_SUPPORT
5331 /* Store in IMG->colors the colors allocated for the image, and
5332 free the color table. */
5333 img->colors = colors_in_color_table (&img->ncolors);
5334 free_color_table ();
5335 #endif /* COLOR_TABLE_SUPPORT */
5337 img->width = width;
5338 img->height = height;
5340 /* Maybe fill in the background field while we have ximg handy. */
5342 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5343 /* Casting avoids a GCC warning. */
5344 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5346 /* Put the image into a pixmap. */
5347 x_put_x_image (f, ximg, img->pixmap, width, height);
5348 x_destroy_x_image (ximg);
5350 /* X and W32 versions did it here, MAC version above. ++kfs
5351 img->width = width;
5352 img->height = height; */
5354 xfree (contents);
5355 return 1;
5359 /***********************************************************************
5361 ***********************************************************************/
5363 #if defined (HAVE_PNG) || defined (HAVE_NS)
5365 /* Function prototypes. */
5367 static int png_image_p (Lisp_Object object);
5368 static int png_load (struct frame *f, struct image *img);
5370 /* The symbol `png' identifying images of this type. */
5372 Lisp_Object Qpng;
5374 /* Indices of image specification fields in png_format, below. */
5376 enum png_keyword_index
5378 PNG_TYPE,
5379 PNG_DATA,
5380 PNG_FILE,
5381 PNG_ASCENT,
5382 PNG_MARGIN,
5383 PNG_RELIEF,
5384 PNG_ALGORITHM,
5385 PNG_HEURISTIC_MASK,
5386 PNG_MASK,
5387 PNG_BACKGROUND,
5388 PNG_LAST
5391 /* Vector of image_keyword structures describing the format
5392 of valid user-defined image specifications. */
5394 static const struct image_keyword png_format[PNG_LAST] =
5396 {":type", IMAGE_SYMBOL_VALUE, 1},
5397 {":data", IMAGE_STRING_VALUE, 0},
5398 {":file", IMAGE_STRING_VALUE, 0},
5399 {":ascent", IMAGE_ASCENT_VALUE, 0},
5400 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5401 {":relief", IMAGE_INTEGER_VALUE, 0},
5402 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5403 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5404 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5405 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5408 /* Structure describing the image type `png'. */
5410 static struct image_type png_type =
5412 &Qpng,
5413 png_image_p,
5414 png_load,
5415 x_clear_image,
5416 NULL
5419 /* Return non-zero if OBJECT is a valid PNG image specification. */
5421 static int
5422 png_image_p (Lisp_Object object)
5424 struct image_keyword fmt[PNG_LAST];
5425 memcpy (fmt, png_format, sizeof fmt);
5427 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5428 return 0;
5430 /* Must specify either the :data or :file keyword. */
5431 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5434 #endif /* HAVE_PNG || HAVE_NS */
5437 #ifdef HAVE_PNG
5439 #ifdef HAVE_NTGUI
5440 /* PNG library details. */
5442 DEF_IMGLIB_FN (png_get_io_ptr, (png_structp));
5443 DEF_IMGLIB_FN (png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5444 DEF_IMGLIB_FN (png_create_read_struct, (png_const_charp, png_voidp,
5445 png_error_ptr, png_error_ptr));
5446 DEF_IMGLIB_FN (png_create_info_struct, (png_structp));
5447 DEF_IMGLIB_FN (png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5448 DEF_IMGLIB_FN (png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5449 DEF_IMGLIB_FN (png_set_sig_bytes, (png_structp, int));
5450 DEF_IMGLIB_FN (png_read_info, (png_structp, png_infop));
5451 DEF_IMGLIB_FN (png_get_IHDR, (png_structp, png_infop,
5452 png_uint_32 *, png_uint_32 *,
5453 int *, int *, int *, int *, int *));
5454 DEF_IMGLIB_FN (png_get_valid, (png_structp, png_infop, png_uint_32));
5455 DEF_IMGLIB_FN (png_set_strip_16, (png_structp));
5456 DEF_IMGLIB_FN (png_set_expand, (png_structp));
5457 DEF_IMGLIB_FN (png_set_gray_to_rgb, (png_structp));
5458 DEF_IMGLIB_FN (png_set_background, (png_structp, png_color_16p,
5459 int, int, double));
5460 DEF_IMGLIB_FN (png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5461 DEF_IMGLIB_FN (png_read_update_info, (png_structp, png_infop));
5462 DEF_IMGLIB_FN (png_get_channels, (png_structp, png_infop));
5463 DEF_IMGLIB_FN (png_get_rowbytes, (png_structp, png_infop));
5464 DEF_IMGLIB_FN (png_read_image, (png_structp, png_bytepp));
5465 DEF_IMGLIB_FN (png_read_end, (png_structp, png_infop));
5466 DEF_IMGLIB_FN (png_error, (png_structp, png_const_charp));
5468 static int
5469 init_png_functions (Lisp_Object libraries)
5471 HMODULE library;
5473 /* Try loading libpng under probable names. */
5474 if (!(library = w32_delayed_load (libraries, Qpng)))
5475 return 0;
5477 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5478 LOAD_IMGLIB_FN (library, png_sig_cmp);
5479 LOAD_IMGLIB_FN (library, png_create_read_struct);
5480 LOAD_IMGLIB_FN (library, png_create_info_struct);
5481 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5482 LOAD_IMGLIB_FN (library, png_set_read_fn);
5483 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5484 LOAD_IMGLIB_FN (library, png_read_info);
5485 LOAD_IMGLIB_FN (library, png_get_IHDR);
5486 LOAD_IMGLIB_FN (library, png_get_valid);
5487 LOAD_IMGLIB_FN (library, png_set_strip_16);
5488 LOAD_IMGLIB_FN (library, png_set_expand);
5489 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5490 LOAD_IMGLIB_FN (library, png_set_background);
5491 LOAD_IMGLIB_FN (library, png_get_bKGD);
5492 LOAD_IMGLIB_FN (library, png_read_update_info);
5493 LOAD_IMGLIB_FN (library, png_get_channels);
5494 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5495 LOAD_IMGLIB_FN (library, png_read_image);
5496 LOAD_IMGLIB_FN (library, png_read_end);
5497 LOAD_IMGLIB_FN (library, png_error);
5498 return 1;
5500 #else
5502 #define fn_png_get_io_ptr png_get_io_ptr
5503 #define fn_png_sig_cmp png_sig_cmp
5504 #define fn_png_create_read_struct png_create_read_struct
5505 #define fn_png_create_info_struct png_create_info_struct
5506 #define fn_png_destroy_read_struct png_destroy_read_struct
5507 #define fn_png_set_read_fn png_set_read_fn
5508 #define fn_png_set_sig_bytes png_set_sig_bytes
5509 #define fn_png_read_info png_read_info
5510 #define fn_png_get_IHDR png_get_IHDR
5511 #define fn_png_get_valid png_get_valid
5512 #define fn_png_set_strip_16 png_set_strip_16
5513 #define fn_png_set_expand png_set_expand
5514 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5515 #define fn_png_set_background png_set_background
5516 #define fn_png_get_bKGD png_get_bKGD
5517 #define fn_png_read_update_info png_read_update_info
5518 #define fn_png_get_channels png_get_channels
5519 #define fn_png_get_rowbytes png_get_rowbytes
5520 #define fn_png_read_image png_read_image
5521 #define fn_png_read_end png_read_end
5522 #define fn_png_error png_error
5524 #endif /* HAVE_NTGUI */
5526 /* Error and warning handlers installed when the PNG library
5527 is initialized. */
5529 static void
5530 my_png_error (png_struct *png_ptr, const char *msg)
5532 xassert (png_ptr != NULL);
5533 image_error ("PNG error: %s", build_string (msg), Qnil);
5534 longjmp (png_ptr->jmpbuf, 1);
5538 static void
5539 my_png_warning (png_struct *png_ptr, const char *msg)
5541 xassert (png_ptr != NULL);
5542 image_error ("PNG warning: %s", build_string (msg), Qnil);
5545 /* Memory source for PNG decoding. */
5547 struct png_memory_storage
5549 unsigned char *bytes; /* The data */
5550 size_t len; /* How big is it? */
5551 int index; /* Where are we? */
5555 /* Function set as reader function when reading PNG image from memory.
5556 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5557 bytes from the input to DATA. */
5559 static void
5560 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5562 struct png_memory_storage *tbr
5563 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5565 if (length > tbr->len - tbr->index)
5566 fn_png_error (png_ptr, "Read error");
5568 memcpy (data, tbr->bytes + tbr->index, length);
5569 tbr->index = tbr->index + length;
5573 /* Function set as reader function when reading PNG image from a file.
5574 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5575 bytes from the input to DATA. */
5577 static void
5578 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5580 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5582 if (fread (data, 1, length, fp) < length)
5583 fn_png_error (png_ptr, "Read error");
5587 /* Load PNG image IMG for use on frame F. Value is non-zero if
5588 successful. */
5590 static int
5591 png_load (struct frame *f, struct image *img)
5593 Lisp_Object file, specified_file;
5594 Lisp_Object specified_data;
5595 int x, y, i;
5596 XImagePtr ximg, mask_img = NULL;
5597 png_struct *png_ptr = NULL;
5598 png_info *info_ptr = NULL, *end_info = NULL;
5599 FILE *volatile fp = NULL;
5600 png_byte sig[8];
5601 png_byte * volatile pixels = NULL;
5602 png_byte ** volatile rows = NULL;
5603 png_uint_32 width, height;
5604 int bit_depth, color_type, interlace_type;
5605 png_byte channels;
5606 png_uint_32 row_bytes;
5607 int transparent_p;
5608 struct png_memory_storage tbr; /* Data to be read */
5610 /* Find out what file to load. */
5611 specified_file = image_spec_value (img->spec, QCfile, NULL);
5612 specified_data = image_spec_value (img->spec, QCdata, NULL);
5614 if (NILP (specified_data))
5616 file = x_find_image_file (specified_file);
5617 if (!STRINGP (file))
5619 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5620 return 0;
5623 /* Open the image file. */
5624 fp = fopen (SDATA (file), "rb");
5625 if (!fp)
5627 image_error ("Cannot open image file `%s'", file, Qnil);
5628 return 0;
5631 /* Check PNG signature. */
5632 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5633 || fn_png_sig_cmp (sig, 0, sizeof sig))
5635 image_error ("Not a PNG file: `%s'", file, Qnil);
5636 fclose (fp);
5637 return 0;
5640 else
5642 if (!STRINGP (specified_data))
5644 image_error ("Invalid image data `%s'", specified_data, Qnil);
5645 return 0;
5648 /* Read from memory. */
5649 tbr.bytes = SDATA (specified_data);
5650 tbr.len = SBYTES (specified_data);
5651 tbr.index = 0;
5653 /* Check PNG signature. */
5654 if (tbr.len < sizeof sig
5655 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5657 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5658 return 0;
5661 /* Need to skip past the signature. */
5662 tbr.bytes += sizeof (sig);
5665 /* Initialize read and info structs for PNG lib. Casting return
5666 value avoids a GCC warning on W32. */
5667 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5668 NULL, my_png_error,
5669 my_png_warning);
5670 if (!png_ptr)
5672 if (fp) fclose (fp);
5673 return 0;
5676 /* Casting return value avoids a GCC warning on W32. */
5677 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
5678 if (!info_ptr)
5680 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5681 if (fp) fclose (fp);
5682 return 0;
5685 /* Casting return value avoids a GCC warning on W32. */
5686 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
5687 if (!end_info)
5689 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5690 if (fp) fclose (fp);
5691 return 0;
5694 /* Set error jump-back. We come back here when the PNG library
5695 detects an error. */
5696 if (setjmp (png_ptr->jmpbuf))
5698 error:
5699 if (png_ptr)
5700 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5701 xfree (pixels);
5702 xfree (rows);
5703 if (fp) fclose (fp);
5704 return 0;
5707 /* Read image info. */
5708 if (!NILP (specified_data))
5709 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5710 else
5711 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5713 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5714 fn_png_read_info (png_ptr, info_ptr);
5715 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5716 &interlace_type, NULL, NULL);
5718 if (!check_image_size (f, width, height))
5720 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5721 goto error;
5723 /* If image contains simply transparency data, we prefer to
5724 construct a clipping mask. */
5725 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5726 transparent_p = 1;
5727 else
5728 transparent_p = 0;
5730 /* This function is easier to write if we only have to handle
5731 one data format: RGB or RGBA with 8 bits per channel. Let's
5732 transform other formats into that format. */
5734 /* Strip more than 8 bits per channel. */
5735 if (bit_depth == 16)
5736 fn_png_set_strip_16 (png_ptr);
5738 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5739 if available. */
5740 fn_png_set_expand (png_ptr);
5742 /* Convert grayscale images to RGB. */
5743 if (color_type == PNG_COLOR_TYPE_GRAY
5744 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5745 fn_png_set_gray_to_rgb (png_ptr);
5747 /* Handle alpha channel by combining the image with a background
5748 color. Do this only if a real alpha channel is supplied. For
5749 simple transparency, we prefer a clipping mask. */
5750 if (!transparent_p)
5752 /* png_color_16 *image_bg; */
5753 Lisp_Object specified_bg
5754 = image_spec_value (img->spec, QCbackground, NULL);
5755 int shift = (bit_depth == 16) ? 0 : 8;
5757 if (STRINGP (specified_bg))
5758 /* The user specified `:background', use that. */
5760 XColor color;
5761 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
5763 png_color_16 user_bg;
5765 memset (&user_bg, 0, sizeof user_bg);
5766 user_bg.red = color.red >> shift;
5767 user_bg.green = color.green >> shift;
5768 user_bg.blue = color.blue >> shift;
5770 fn_png_set_background (png_ptr, &user_bg,
5771 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5774 else
5776 /* We use the current frame background, ignoring any default
5777 background color set by the image. */
5778 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5779 XColor color;
5780 png_color_16 frame_background;
5782 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5783 x_query_color (f, &color);
5785 memset (&frame_background, 0, sizeof frame_background);
5786 frame_background.red = color.red >> shift;
5787 frame_background.green = color.green >> shift;
5788 frame_background.blue = color.blue >> shift;
5789 #endif /* HAVE_X_WINDOWS */
5791 fn_png_set_background (png_ptr, &frame_background,
5792 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5796 /* Update info structure. */
5797 fn_png_read_update_info (png_ptr, info_ptr);
5799 /* Get number of channels. Valid values are 1 for grayscale images
5800 and images with a palette, 2 for grayscale images with transparency
5801 information (alpha channel), 3 for RGB images, and 4 for RGB
5802 images with alpha channel, i.e. RGBA. If conversions above were
5803 sufficient we should only have 3 or 4 channels here. */
5804 channels = fn_png_get_channels (png_ptr, info_ptr);
5805 xassert (channels == 3 || channels == 4);
5807 /* Number of bytes needed for one row of the image. */
5808 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5810 /* Allocate memory for the image. */
5811 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
5812 rows = (png_byte **) xmalloc (height * sizeof *rows);
5813 for (i = 0; i < height; ++i)
5814 rows[i] = pixels + i * row_bytes;
5816 /* Read the entire image. */
5817 fn_png_read_image (png_ptr, rows);
5818 fn_png_read_end (png_ptr, info_ptr);
5819 if (fp)
5821 fclose (fp);
5822 fp = NULL;
5825 /* Create the X image and pixmap. */
5826 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5827 &img->pixmap))
5828 goto error;
5830 /* Create an image and pixmap serving as mask if the PNG image
5831 contains an alpha channel. */
5832 if (channels == 4
5833 && !transparent_p
5834 && !x_create_x_image_and_pixmap (f, width, height, 1,
5835 &mask_img, &img->mask))
5837 x_destroy_x_image (ximg);
5838 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5839 img->pixmap = NO_PIXMAP;
5840 goto error;
5843 /* Fill the X image and mask from PNG data. */
5844 init_color_table ();
5846 for (y = 0; y < height; ++y)
5848 png_byte *p = rows[y];
5850 for (x = 0; x < width; ++x)
5852 unsigned r, g, b;
5854 r = *p++ << 8;
5855 g = *p++ << 8;
5856 b = *p++ << 8;
5857 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5858 /* An alpha channel, aka mask channel, associates variable
5859 transparency with an image. Where other image formats
5860 support binary transparency---fully transparent or fully
5861 opaque---PNG allows up to 254 levels of partial transparency.
5862 The PNG library implements partial transparency by combining
5863 the image with a specified background color.
5865 I'm not sure how to handle this here nicely: because the
5866 background on which the image is displayed may change, for
5867 real alpha channel support, it would be necessary to create
5868 a new image for each possible background.
5870 What I'm doing now is that a mask is created if we have
5871 boolean transparency information. Otherwise I'm using
5872 the frame's background color to combine the image with. */
5874 if (channels == 4)
5876 if (mask_img)
5877 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5878 ++p;
5883 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5884 /* Set IMG's background color from the PNG image, unless the user
5885 overrode it. */
5887 png_color_16 *bg;
5888 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5890 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5891 img->background_valid = 1;
5895 #ifdef COLOR_TABLE_SUPPORT
5896 /* Remember colors allocated for this image. */
5897 img->colors = colors_in_color_table (&img->ncolors);
5898 free_color_table ();
5899 #endif /* COLOR_TABLE_SUPPORT */
5901 /* Clean up. */
5902 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5903 xfree (rows);
5904 xfree (pixels);
5906 img->width = width;
5907 img->height = height;
5909 /* Maybe fill in the background field while we have ximg handy.
5910 Casting avoids a GCC warning. */
5911 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5913 /* Put the image into the pixmap, then free the X image and its buffer. */
5914 x_put_x_image (f, ximg, img->pixmap, width, height);
5915 x_destroy_x_image (ximg);
5917 /* Same for the mask. */
5918 if (mask_img)
5920 /* Fill in the background_transparent field while we have the
5921 mask handy. Casting avoids a GCC warning. */
5922 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
5924 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5925 x_destroy_x_image (mask_img);
5928 return 1;
5931 #else /* HAVE_PNG */
5933 #ifdef HAVE_NS
5934 static int
5935 png_load (struct frame *f, struct image *img)
5937 return ns_load_image(f, img,
5938 image_spec_value (img->spec, QCfile, NULL),
5939 image_spec_value (img->spec, QCdata, NULL));
5941 #endif /* HAVE_NS */
5944 #endif /* !HAVE_PNG */
5948 /***********************************************************************
5949 JPEG
5950 ***********************************************************************/
5952 #if defined (HAVE_JPEG) || defined (HAVE_NS)
5954 static int jpeg_image_p (Lisp_Object object);
5955 static int jpeg_load (struct frame *f, struct image *img);
5957 /* The symbol `jpeg' identifying images of this type. */
5959 Lisp_Object Qjpeg;
5961 /* Indices of image specification fields in gs_format, below. */
5963 enum jpeg_keyword_index
5965 JPEG_TYPE,
5966 JPEG_DATA,
5967 JPEG_FILE,
5968 JPEG_ASCENT,
5969 JPEG_MARGIN,
5970 JPEG_RELIEF,
5971 JPEG_ALGORITHM,
5972 JPEG_HEURISTIC_MASK,
5973 JPEG_MASK,
5974 JPEG_BACKGROUND,
5975 JPEG_LAST
5978 /* Vector of image_keyword structures describing the format
5979 of valid user-defined image specifications. */
5981 static const struct image_keyword jpeg_format[JPEG_LAST] =
5983 {":type", IMAGE_SYMBOL_VALUE, 1},
5984 {":data", IMAGE_STRING_VALUE, 0},
5985 {":file", IMAGE_STRING_VALUE, 0},
5986 {":ascent", IMAGE_ASCENT_VALUE, 0},
5987 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5988 {":relief", IMAGE_INTEGER_VALUE, 0},
5989 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5990 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5991 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5992 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5995 /* Structure describing the image type `jpeg'. */
5997 static struct image_type jpeg_type =
5999 &Qjpeg,
6000 jpeg_image_p,
6001 jpeg_load,
6002 x_clear_image,
6003 NULL
6006 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6008 static int
6009 jpeg_image_p (Lisp_Object object)
6011 struct image_keyword fmt[JPEG_LAST];
6013 memcpy (fmt, jpeg_format, sizeof fmt);
6015 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6016 return 0;
6018 /* Must specify either the :data or :file keyword. */
6019 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6022 #endif /* HAVE_JPEG || HAVE_NS */
6024 #ifdef HAVE_JPEG
6026 /* Work around a warning about HAVE_STDLIB_H being redefined in
6027 jconfig.h. */
6028 #ifdef HAVE_STDLIB_H
6029 #define HAVE_STDLIB_H_1
6030 #undef HAVE_STDLIB_H
6031 #endif /* HAVE_STLIB_H */
6033 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6034 /* In older releases of the jpeg library, jpeglib.h will define boolean
6035 differently depending on __WIN32__, so make sure it is defined. */
6036 #define __WIN32__ 1
6037 #endif
6039 #include <jpeglib.h>
6040 #include <jerror.h>
6042 #ifdef HAVE_STLIB_H_1
6043 #define HAVE_STDLIB_H 1
6044 #endif
6046 #ifdef HAVE_NTGUI
6048 /* JPEG library details. */
6049 DEF_IMGLIB_FN (jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6050 DEF_IMGLIB_FN (jpeg_start_decompress, (j_decompress_ptr));
6051 DEF_IMGLIB_FN (jpeg_finish_decompress, (j_decompress_ptr));
6052 DEF_IMGLIB_FN (jpeg_destroy_decompress, (j_decompress_ptr));
6053 DEF_IMGLIB_FN (jpeg_read_header, (j_decompress_ptr, boolean));
6054 DEF_IMGLIB_FN (jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6055 DEF_IMGLIB_FN (jpeg_std_error, (struct jpeg_error_mgr *));
6056 DEF_IMGLIB_FN (jpeg_resync_to_restart, (j_decompress_ptr, int));
6058 static int
6059 init_jpeg_functions (Lisp_Object libraries)
6061 HMODULE library;
6063 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6064 return 0;
6066 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6067 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6068 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6069 LOAD_IMGLIB_FN (library, jpeg_read_header);
6070 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6071 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6072 LOAD_IMGLIB_FN (library, jpeg_std_error);
6073 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6074 return 1;
6077 /* Wrapper since we can't directly assign the function pointer
6078 to another function pointer that was declared more completely easily. */
6079 static boolean
6080 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6082 return fn_jpeg_resync_to_restart (cinfo, desired);
6085 #else
6087 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6088 #define fn_jpeg_start_decompress jpeg_start_decompress
6089 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6090 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6091 #define fn_jpeg_read_header jpeg_read_header
6092 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6093 #define fn_jpeg_std_error jpeg_std_error
6094 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6096 #endif /* HAVE_NTGUI */
6098 struct my_jpeg_error_mgr
6100 struct jpeg_error_mgr pub;
6101 jmp_buf setjmp_buffer;
6105 static void
6106 my_error_exit (j_common_ptr cinfo)
6108 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6109 longjmp (mgr->setjmp_buffer, 1);
6113 /* Init source method for JPEG data source manager. Called by
6114 jpeg_read_header() before any data is actually read. See
6115 libjpeg.doc from the JPEG lib distribution. */
6117 static void
6118 our_common_init_source (j_decompress_ptr cinfo)
6123 /* Method to terminate data source. Called by
6124 jpeg_finish_decompress() after all data has been processed. */
6126 static void
6127 our_common_term_source (j_decompress_ptr cinfo)
6132 /* Fill input buffer method for JPEG data source manager. Called
6133 whenever more data is needed. We read the whole image in one step,
6134 so this only adds a fake end of input marker at the end. */
6136 static JOCTET our_memory_buffer[2];
6138 static boolean
6139 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6141 /* Insert a fake EOI marker. */
6142 struct jpeg_source_mgr *src = cinfo->src;
6144 our_memory_buffer[0] = (JOCTET) 0xFF;
6145 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6147 src->next_input_byte = our_memory_buffer;
6148 src->bytes_in_buffer = 2;
6149 return 1;
6153 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6154 is the JPEG data source manager. */
6156 static void
6157 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6159 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6161 if (src)
6163 if (num_bytes > src->bytes_in_buffer)
6164 ERREXIT (cinfo, JERR_INPUT_EOF);
6166 src->bytes_in_buffer -= num_bytes;
6167 src->next_input_byte += num_bytes;
6172 /* Set up the JPEG lib for reading an image from DATA which contains
6173 LEN bytes. CINFO is the decompression info structure created for
6174 reading the image. */
6176 static void
6177 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, unsigned int len)
6179 struct jpeg_source_mgr *src;
6181 if (cinfo->src == NULL)
6183 /* First time for this JPEG object? */
6184 cinfo->src = (struct jpeg_source_mgr *)
6185 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6186 sizeof (struct jpeg_source_mgr));
6187 src = (struct jpeg_source_mgr *) cinfo->src;
6188 src->next_input_byte = data;
6191 src = (struct jpeg_source_mgr *) cinfo->src;
6192 src->init_source = our_common_init_source;
6193 src->fill_input_buffer = our_memory_fill_input_buffer;
6194 src->skip_input_data = our_memory_skip_input_data;
6195 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6196 src->term_source = our_common_term_source;
6197 src->bytes_in_buffer = len;
6198 src->next_input_byte = data;
6202 struct jpeg_stdio_mgr
6204 struct jpeg_source_mgr mgr;
6205 boolean finished;
6206 FILE *file;
6207 JOCTET *buffer;
6211 /* Size of buffer to read JPEG from file.
6212 Not too big, as we want to use alloc_small. */
6213 #define JPEG_STDIO_BUFFER_SIZE 8192
6216 /* Fill input buffer method for JPEG data source manager. Called
6217 whenever more data is needed. The data is read from a FILE *. */
6219 static boolean
6220 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6222 struct jpeg_stdio_mgr *src;
6224 src = (struct jpeg_stdio_mgr *) cinfo->src;
6225 if (!src->finished)
6227 size_t bytes;
6229 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6230 if (bytes > 0)
6231 src->mgr.bytes_in_buffer = bytes;
6232 else
6234 WARNMS (cinfo, JWRN_JPEG_EOF);
6235 src->finished = 1;
6236 src->buffer[0] = (JOCTET) 0xFF;
6237 src->buffer[1] = (JOCTET) JPEG_EOI;
6238 src->mgr.bytes_in_buffer = 2;
6240 src->mgr.next_input_byte = src->buffer;
6243 return 1;
6247 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6248 is the JPEG data source manager. */
6250 static void
6251 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6253 struct jpeg_stdio_mgr *src;
6254 src = (struct jpeg_stdio_mgr *) cinfo->src;
6256 while (num_bytes > 0 && !src->finished)
6258 if (num_bytes <= src->mgr.bytes_in_buffer)
6260 src->mgr.bytes_in_buffer -= num_bytes;
6261 src->mgr.next_input_byte += num_bytes;
6262 break;
6264 else
6266 num_bytes -= src->mgr.bytes_in_buffer;
6267 src->mgr.bytes_in_buffer = 0;
6268 src->mgr.next_input_byte = NULL;
6270 our_stdio_fill_input_buffer (cinfo);
6276 /* Set up the JPEG lib for reading an image from a FILE *.
6277 CINFO is the decompression info structure created for
6278 reading the image. */
6280 static void
6281 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6283 struct jpeg_stdio_mgr *src;
6285 if (cinfo->src != NULL)
6286 src = (struct jpeg_stdio_mgr *) cinfo->src;
6287 else
6289 /* First time for this JPEG object? */
6290 cinfo->src = (struct jpeg_source_mgr *)
6291 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6292 sizeof (struct jpeg_stdio_mgr));
6293 src = (struct jpeg_stdio_mgr *) cinfo->src;
6294 src->buffer = (JOCTET *)
6295 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6296 JPEG_STDIO_BUFFER_SIZE);
6299 src->file = fp;
6300 src->finished = 0;
6301 src->mgr.init_source = our_common_init_source;
6302 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6303 src->mgr.skip_input_data = our_stdio_skip_input_data;
6304 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6305 src->mgr.term_source = our_common_term_source;
6306 src->mgr.bytes_in_buffer = 0;
6307 src->mgr.next_input_byte = NULL;
6311 /* Load image IMG for use on frame F. Patterned after example.c
6312 from the JPEG lib. */
6314 static int
6315 jpeg_load (struct frame *f, struct image *img)
6317 struct jpeg_decompress_struct cinfo;
6318 struct my_jpeg_error_mgr mgr;
6319 Lisp_Object file, specified_file;
6320 Lisp_Object specified_data;
6321 FILE * volatile fp = NULL;
6322 JSAMPARRAY buffer;
6323 int row_stride, x, y;
6324 XImagePtr ximg = NULL;
6325 int rc;
6326 unsigned long *colors;
6327 int width, height;
6329 /* Open the JPEG file. */
6330 specified_file = image_spec_value (img->spec, QCfile, NULL);
6331 specified_data = image_spec_value (img->spec, QCdata, NULL);
6333 if (NILP (specified_data))
6335 file = x_find_image_file (specified_file);
6336 if (!STRINGP (file))
6338 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6339 return 0;
6342 fp = fopen (SDATA (file), "rb");
6343 if (fp == NULL)
6345 image_error ("Cannot open `%s'", file, Qnil);
6346 return 0;
6349 else if (!STRINGP (specified_data))
6351 image_error ("Invalid image data `%s'", specified_data, Qnil);
6352 return 0;
6355 /* Customize libjpeg's error handling to call my_error_exit when an
6356 error is detected. This function will perform a longjmp.
6357 Casting return value avoids a GCC warning on W32. */
6358 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
6359 mgr.pub.error_exit = my_error_exit;
6361 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6363 if (rc == 1)
6365 /* Called from my_error_exit. Display a JPEG error. */
6366 char buffer[JMSG_LENGTH_MAX];
6367 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
6368 image_error ("Error reading JPEG image `%s': %s", img->spec,
6369 build_string (buffer));
6372 /* Close the input file and destroy the JPEG object. */
6373 if (fp)
6374 fclose ((FILE *) fp);
6375 fn_jpeg_destroy_decompress (&cinfo);
6377 /* If we already have an XImage, free that. */
6378 x_destroy_x_image (ximg);
6380 /* Free pixmap and colors. */
6381 x_clear_image (f, img);
6382 return 0;
6385 /* Create the JPEG decompression object. Let it read from fp.
6386 Read the JPEG image header. */
6387 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6389 if (NILP (specified_data))
6390 jpeg_file_src (&cinfo, (FILE *) fp);
6391 else
6392 jpeg_memory_src (&cinfo, SDATA (specified_data),
6393 SBYTES (specified_data));
6395 fn_jpeg_read_header (&cinfo, 1);
6397 /* Customize decompression so that color quantization will be used.
6398 Start decompression. */
6399 cinfo.quantize_colors = 1;
6400 fn_jpeg_start_decompress (&cinfo);
6401 width = img->width = cinfo.output_width;
6402 height = img->height = cinfo.output_height;
6404 if (!check_image_size (f, width, height))
6406 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6407 longjmp (mgr.setjmp_buffer, 2);
6410 /* Create X image and pixmap. */
6411 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6412 longjmp (mgr.setjmp_buffer, 2);
6414 /* Allocate colors. When color quantization is used,
6415 cinfo.actual_number_of_colors has been set with the number of
6416 colors generated, and cinfo.colormap is a two-dimensional array
6417 of color indices in the range 0..cinfo.actual_number_of_colors.
6418 No more than 255 colors will be generated. */
6420 int i, ir, ig, ib;
6422 if (cinfo.out_color_components > 2)
6423 ir = 0, ig = 1, ib = 2;
6424 else if (cinfo.out_color_components > 1)
6425 ir = 0, ig = 1, ib = 0;
6426 else
6427 ir = 0, ig = 0, ib = 0;
6429 /* Use the color table mechanism because it handles colors that
6430 cannot be allocated nicely. Such colors will be replaced with
6431 a default color, and we don't have to care about which colors
6432 can be freed safely, and which can't. */
6433 init_color_table ();
6434 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6435 * sizeof *colors);
6437 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6439 /* Multiply RGB values with 255 because X expects RGB values
6440 in the range 0..0xffff. */
6441 int r = cinfo.colormap[ir][i] << 8;
6442 int g = cinfo.colormap[ig][i] << 8;
6443 int b = cinfo.colormap[ib][i] << 8;
6444 colors[i] = lookup_rgb_color (f, r, g, b);
6447 #ifdef COLOR_TABLE_SUPPORT
6448 /* Remember those colors actually allocated. */
6449 img->colors = colors_in_color_table (&img->ncolors);
6450 free_color_table ();
6451 #endif /* COLOR_TABLE_SUPPORT */
6454 /* Read pixels. */
6455 row_stride = width * cinfo.output_components;
6456 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6457 row_stride, 1);
6458 for (y = 0; y < height; ++y)
6460 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6461 for (x = 0; x < cinfo.output_width; ++x)
6462 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6465 /* Clean up. */
6466 fn_jpeg_finish_decompress (&cinfo);
6467 fn_jpeg_destroy_decompress (&cinfo);
6468 if (fp)
6469 fclose ((FILE *) fp);
6471 /* Maybe fill in the background field while we have ximg handy. */
6472 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6473 /* Casting avoids a GCC warning. */
6474 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6476 /* Put the image into the pixmap. */
6477 x_put_x_image (f, ximg, img->pixmap, width, height);
6478 x_destroy_x_image (ximg);
6479 return 1;
6482 #else /* HAVE_JPEG */
6484 #ifdef HAVE_NS
6485 static int
6486 jpeg_load (struct frame *f, struct image *img)
6488 return ns_load_image (f, img,
6489 image_spec_value (img->spec, QCfile, NULL),
6490 image_spec_value (img->spec, QCdata, NULL));
6492 #endif /* HAVE_NS */
6494 #endif /* !HAVE_JPEG */
6498 /***********************************************************************
6499 TIFF
6500 ***********************************************************************/
6502 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6504 static int tiff_image_p (Lisp_Object object);
6505 static int tiff_load (struct frame *f, struct image *img);
6507 /* The symbol `tiff' identifying images of this type. */
6509 Lisp_Object Qtiff;
6511 /* Indices of image specification fields in tiff_format, below. */
6513 enum tiff_keyword_index
6515 TIFF_TYPE,
6516 TIFF_DATA,
6517 TIFF_FILE,
6518 TIFF_ASCENT,
6519 TIFF_MARGIN,
6520 TIFF_RELIEF,
6521 TIFF_ALGORITHM,
6522 TIFF_HEURISTIC_MASK,
6523 TIFF_MASK,
6524 TIFF_BACKGROUND,
6525 TIFF_INDEX,
6526 TIFF_LAST
6529 /* Vector of image_keyword structures describing the format
6530 of valid user-defined image specifications. */
6532 static const struct image_keyword tiff_format[TIFF_LAST] =
6534 {":type", IMAGE_SYMBOL_VALUE, 1},
6535 {":data", IMAGE_STRING_VALUE, 0},
6536 {":file", IMAGE_STRING_VALUE, 0},
6537 {":ascent", IMAGE_ASCENT_VALUE, 0},
6538 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6539 {":relief", IMAGE_INTEGER_VALUE, 0},
6540 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6541 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6542 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6543 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6544 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6547 /* Structure describing the image type `tiff'. */
6549 static struct image_type tiff_type =
6551 &Qtiff,
6552 tiff_image_p,
6553 tiff_load,
6554 x_clear_image,
6555 NULL
6558 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6560 static int
6561 tiff_image_p (Lisp_Object object)
6563 struct image_keyword fmt[TIFF_LAST];
6564 memcpy (fmt, tiff_format, sizeof fmt);
6566 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6567 return 0;
6569 /* Must specify either the :data or :file keyword. */
6570 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6573 #endif /* HAVE_TIFF || HAVE_NS */
6575 #ifdef HAVE_TIFF
6577 #include <tiffio.h>
6579 #ifdef HAVE_NTGUI
6581 /* TIFF library details. */
6582 DEF_IMGLIB_FN (TIFFSetErrorHandler, (TIFFErrorHandler));
6583 DEF_IMGLIB_FN (TIFFSetWarningHandler, (TIFFErrorHandler));
6584 DEF_IMGLIB_FN (TIFFOpen, (const char *, const char *));
6585 DEF_IMGLIB_FN (TIFFClientOpen, (const char *, const char *, thandle_t,
6586 TIFFReadWriteProc, TIFFReadWriteProc,
6587 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6588 TIFFMapFileProc, TIFFUnmapFileProc));
6589 DEF_IMGLIB_FN (TIFFGetField, (TIFF *, ttag_t, ...));
6590 DEF_IMGLIB_FN (TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6591 DEF_IMGLIB_FN (TIFFClose, (TIFF *));
6592 DEF_IMGLIB_FN (TIFFSetDirectory, (TIFF *, tdir_t));
6594 static int
6595 init_tiff_functions (Lisp_Object libraries)
6597 HMODULE library;
6599 if (!(library = w32_delayed_load (libraries, Qtiff)))
6600 return 0;
6602 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6603 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6604 LOAD_IMGLIB_FN (library, TIFFOpen);
6605 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6606 LOAD_IMGLIB_FN (library, TIFFGetField);
6607 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6608 LOAD_IMGLIB_FN (library, TIFFClose);
6609 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6610 return 1;
6613 #else
6615 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6616 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6617 #define fn_TIFFOpen TIFFOpen
6618 #define fn_TIFFClientOpen TIFFClientOpen
6619 #define fn_TIFFGetField TIFFGetField
6620 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6621 #define fn_TIFFClose TIFFClose
6622 #define fn_TIFFSetDirectory TIFFSetDirectory
6623 #endif /* HAVE_NTGUI */
6626 /* Reading from a memory buffer for TIFF images Based on the PNG
6627 memory source, but we have to provide a lot of extra functions.
6628 Blah.
6630 We really only need to implement read and seek, but I am not
6631 convinced that the TIFF library is smart enough not to destroy
6632 itself if we only hand it the function pointers we need to
6633 override. */
6635 typedef struct
6637 unsigned char *bytes;
6638 size_t len;
6639 int index;
6641 tiff_memory_source;
6643 static size_t
6644 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6646 tiff_memory_source *src = (tiff_memory_source *) data;
6648 if (size > src->len - src->index)
6649 return (size_t) -1;
6650 memcpy (buf, src->bytes + src->index, size);
6651 src->index += size;
6652 return size;
6655 static size_t
6656 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6658 return (size_t) -1;
6661 static toff_t
6662 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6664 tiff_memory_source *src = (tiff_memory_source *) data;
6665 int idx;
6667 switch (whence)
6669 case SEEK_SET: /* Go from beginning of source. */
6670 idx = off;
6671 break;
6673 case SEEK_END: /* Go from end of source. */
6674 idx = src->len + off;
6675 break;
6677 case SEEK_CUR: /* Go from current position. */
6678 idx = src->index + off;
6679 break;
6681 default: /* Invalid `whence'. */
6682 return -1;
6685 if (idx > src->len || idx < 0)
6686 return -1;
6688 src->index = idx;
6689 return src->index;
6692 static int
6693 tiff_close_memory (thandle_t data)
6695 /* NOOP */
6696 return 0;
6699 static int
6700 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6702 /* It is already _IN_ memory. */
6703 return 0;
6706 static void
6707 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6709 /* We don't need to do this. */
6712 static toff_t
6713 tiff_size_of_memory (thandle_t data)
6715 return ((tiff_memory_source *) data)->len;
6719 static void
6720 tiff_error_handler (const char *title, const char *format, va_list ap)
6722 char buf[512];
6723 int len;
6725 len = sprintf (buf, "TIFF error: %s ", title);
6726 vsprintf (buf + len, format, ap);
6727 add_to_log (buf, Qnil, Qnil);
6731 static void
6732 tiff_warning_handler (const char *title, const char *format, va_list ap)
6734 char buf[512];
6735 int len;
6737 len = sprintf (buf, "TIFF warning: %s ", title);
6738 vsprintf (buf + len, format, ap);
6739 add_to_log (buf, Qnil, Qnil);
6743 /* Load TIFF image IMG for use on frame F. Value is non-zero if
6744 successful. */
6746 static int
6747 tiff_load (struct frame *f, struct image *img)
6749 Lisp_Object file, specified_file;
6750 Lisp_Object specified_data;
6751 TIFF *tiff;
6752 int width, height, x, y, count;
6753 uint32 *buf;
6754 int rc, rc2;
6755 XImagePtr ximg;
6756 tiff_memory_source memsrc;
6757 Lisp_Object image;
6759 specified_file = image_spec_value (img->spec, QCfile, NULL);
6760 specified_data = image_spec_value (img->spec, QCdata, NULL);
6762 fn_TIFFSetErrorHandler (tiff_error_handler);
6763 fn_TIFFSetWarningHandler (tiff_warning_handler);
6765 if (NILP (specified_data))
6767 /* Read from a file */
6768 file = x_find_image_file (specified_file);
6769 if (!STRINGP (file))
6771 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6772 return 0;
6775 /* Try to open the image file. Casting return value avoids a
6776 GCC warning on W32. */
6777 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
6778 if (tiff == NULL)
6780 image_error ("Cannot open `%s'", file, Qnil);
6781 return 0;
6784 else
6786 if (!STRINGP (specified_data))
6788 image_error ("Invalid image data `%s'", specified_data, Qnil);
6789 return 0;
6792 /* Memory source! */
6793 memsrc.bytes = SDATA (specified_data);
6794 memsrc.len = SBYTES (specified_data);
6795 memsrc.index = 0;
6797 /* Casting arguments return value avoids a GCC warning on W32. */
6798 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r",
6799 (thandle_t) &memsrc,
6800 (TIFFReadWriteProc) tiff_read_from_memory,
6801 (TIFFReadWriteProc) tiff_write_from_memory,
6802 tiff_seek_in_memory,
6803 tiff_close_memory,
6804 tiff_size_of_memory,
6805 tiff_mmap_memory,
6806 tiff_unmap_memory);
6808 if (!tiff)
6810 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6811 return 0;
6815 image = image_spec_value (img->spec, QCindex, NULL);
6816 if (INTEGERP (image))
6818 int ino = XFASTINT (image);
6819 if (!fn_TIFFSetDirectory (tiff, ino))
6821 image_error ("Invalid image number `%s' in image `%s'",
6822 image, img->spec);
6823 fn_TIFFClose (tiff);
6824 return 0;
6828 /* Get width and height of the image, and allocate a raster buffer
6829 of width x height 32-bit values. */
6830 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6831 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6833 if (!check_image_size (f, width, height))
6835 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6836 fn_TIFFClose (tiff);
6837 return 0;
6840 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
6842 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
6844 /* Count the number of images in the file. */
6845 for (count = 1, rc2 = 1; rc2; count++)
6846 rc2 = fn_TIFFSetDirectory (tiff, count);
6848 if (count > 1)
6849 img->data.lisp_val = Fcons (Qcount,
6850 Fcons (make_number (count),
6851 img->data.lisp_val));
6853 fn_TIFFClose (tiff);
6854 if (!rc)
6856 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6857 xfree (buf);
6858 return 0;
6861 /* Create the X image and pixmap. */
6862 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6864 xfree (buf);
6865 return 0;
6868 /* Initialize the color table. */
6869 init_color_table ();
6871 /* Process the pixel raster. Origin is in the lower-left corner. */
6872 for (y = 0; y < height; ++y)
6874 uint32 *row = buf + y * width;
6876 for (x = 0; x < width; ++x)
6878 uint32 abgr = row[x];
6879 int r = TIFFGetR (abgr) << 8;
6880 int g = TIFFGetG (abgr) << 8;
6881 int b = TIFFGetB (abgr) << 8;
6882 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6886 #ifdef COLOR_TABLE_SUPPORT
6887 /* Remember the colors allocated for the image. Free the color table. */
6888 img->colors = colors_in_color_table (&img->ncolors);
6889 free_color_table ();
6890 #endif /* COLOR_TABLE_SUPPORT */
6892 img->width = width;
6893 img->height = height;
6895 /* Maybe fill in the background field while we have ximg handy. */
6896 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6897 /* Casting avoids a GCC warning on W32. */
6898 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6900 /* Put the image into the pixmap, then free the X image and its buffer. */
6901 x_put_x_image (f, ximg, img->pixmap, width, height);
6902 x_destroy_x_image (ximg);
6903 xfree (buf);
6905 return 1;
6908 #else /* HAVE_TIFF */
6910 #ifdef HAVE_NS
6911 static int
6912 tiff_load (struct frame *f, struct image *img)
6914 return ns_load_image (f, img,
6915 image_spec_value (img->spec, QCfile, NULL),
6916 image_spec_value (img->spec, QCdata, NULL));
6918 #endif /* HAVE_NS */
6920 #endif /* !HAVE_TIFF */
6924 /***********************************************************************
6926 ***********************************************************************/
6928 #if defined (HAVE_GIF) || defined (HAVE_NS)
6930 static int gif_image_p (Lisp_Object object);
6931 static int gif_load (struct frame *f, struct image *img);
6932 static void gif_clear_image (struct frame *f, struct image *img);
6934 /* The symbol `gif' identifying images of this type. */
6936 Lisp_Object Qgif;
6938 /* Indices of image specification fields in gif_format, below. */
6940 enum gif_keyword_index
6942 GIF_TYPE,
6943 GIF_DATA,
6944 GIF_FILE,
6945 GIF_ASCENT,
6946 GIF_MARGIN,
6947 GIF_RELIEF,
6948 GIF_ALGORITHM,
6949 GIF_HEURISTIC_MASK,
6950 GIF_MASK,
6951 GIF_IMAGE,
6952 GIF_BACKGROUND,
6953 GIF_LAST
6956 /* Vector of image_keyword structures describing the format
6957 of valid user-defined image specifications. */
6959 static const struct image_keyword gif_format[GIF_LAST] =
6961 {":type", IMAGE_SYMBOL_VALUE, 1},
6962 {":data", IMAGE_STRING_VALUE, 0},
6963 {":file", IMAGE_STRING_VALUE, 0},
6964 {":ascent", IMAGE_ASCENT_VALUE, 0},
6965 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6966 {":relief", IMAGE_INTEGER_VALUE, 0},
6967 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6968 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6969 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6970 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
6971 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6974 /* Structure describing the image type `gif'. */
6976 static struct image_type gif_type =
6978 &Qgif,
6979 gif_image_p,
6980 gif_load,
6981 gif_clear_image,
6982 NULL
6985 /* Free X resources of GIF image IMG which is used on frame F. */
6987 static void
6988 gif_clear_image (struct frame *f, struct image *img)
6990 /* IMG->data.ptr_val may contain metadata with extension data. */
6991 img->data.lisp_val = Qnil;
6992 x_clear_image (f, img);
6995 /* Return non-zero if OBJECT is a valid GIF image specification. */
6997 static int
6998 gif_image_p (Lisp_Object object)
7000 struct image_keyword fmt[GIF_LAST];
7001 memcpy (fmt, gif_format, sizeof fmt);
7003 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7004 return 0;
7006 /* Must specify either the :data or :file keyword. */
7007 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7010 #endif /* HAVE_GIF */
7012 #ifdef HAVE_GIF
7014 #if defined (HAVE_NTGUI)
7015 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7016 Undefine before redefining to avoid a preprocessor warning. */
7017 #ifdef DrawText
7018 #undef DrawText
7019 #endif
7020 /* avoid conflict with QuickdrawText.h */
7021 #define DrawText gif_DrawText
7022 #include <gif_lib.h>
7023 #undef DrawText
7025 #else /* HAVE_NTGUI */
7027 #include <gif_lib.h>
7029 #endif /* HAVE_NTGUI */
7032 #ifdef HAVE_NTGUI
7034 /* GIF library details. */
7035 DEF_IMGLIB_FN (DGifCloseFile, (GifFileType *));
7036 DEF_IMGLIB_FN (DGifSlurp, (GifFileType *));
7037 DEF_IMGLIB_FN (DGifOpen, (void *, InputFunc));
7038 DEF_IMGLIB_FN (DGifOpenFileName, (const char *));
7040 static int
7041 init_gif_functions (Lisp_Object libraries)
7043 HMODULE library;
7045 if (!(library = w32_delayed_load (libraries, Qgif)))
7046 return 0;
7048 LOAD_IMGLIB_FN (library, DGifCloseFile);
7049 LOAD_IMGLIB_FN (library, DGifSlurp);
7050 LOAD_IMGLIB_FN (library, DGifOpen);
7051 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7052 return 1;
7055 #else
7057 #define fn_DGifCloseFile DGifCloseFile
7058 #define fn_DGifSlurp DGifSlurp
7059 #define fn_DGifOpen DGifOpen
7060 #define fn_DGifOpenFileName DGifOpenFileName
7062 #endif /* HAVE_NTGUI */
7064 /* Reading a GIF image from memory
7065 Based on the PNG memory stuff to a certain extent. */
7067 typedef struct
7069 unsigned char *bytes;
7070 size_t len;
7071 int index;
7073 gif_memory_source;
7075 /* Make the current memory source available to gif_read_from_memory.
7076 It's done this way because not all versions of libungif support
7077 a UserData field in the GifFileType structure. */
7078 static gif_memory_source *current_gif_memory_src;
7080 static int
7081 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7083 gif_memory_source *src = current_gif_memory_src;
7085 if (len > src->len - src->index)
7086 return -1;
7088 memcpy (buf, src->bytes + src->index, len);
7089 src->index += len;
7090 return len;
7094 /* Load GIF image IMG for use on frame F. Value is non-zero if
7095 successful. */
7097 static const int interlace_start[] = {0, 4, 2, 1};
7098 static const int interlace_increment[] = {8, 8, 4, 2};
7100 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7102 static int
7103 gif_load (struct frame *f, struct image *img)
7105 Lisp_Object file, specified_file;
7106 Lisp_Object specified_data;
7107 int rc, width, height, x, y, i;
7108 boolean transparent_p;
7109 XImagePtr ximg;
7110 ColorMapObject *gif_color_map;
7111 unsigned long pixel_colors[256];
7112 GifFileType *gif;
7113 Lisp_Object image;
7114 int ino, image_height, image_width;
7115 gif_memory_source memsrc;
7116 unsigned char *raster;
7117 unsigned int transparency_color_index;
7119 specified_file = image_spec_value (img->spec, QCfile, NULL);
7120 specified_data = image_spec_value (img->spec, QCdata, NULL);
7122 if (NILP (specified_data))
7124 file = x_find_image_file (specified_file);
7125 if (!STRINGP (file))
7127 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7128 return 0;
7131 /* Open the GIF file. Casting return value avoids a GCC warning
7132 on W32. */
7133 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
7134 if (gif == NULL)
7136 image_error ("Cannot open `%s'", file, Qnil);
7137 return 0;
7140 else
7142 if (!STRINGP (specified_data))
7144 image_error ("Invalid image data `%s'", specified_data, Qnil);
7145 return 0;
7148 /* Read from memory! */
7149 current_gif_memory_src = &memsrc;
7150 memsrc.bytes = SDATA (specified_data);
7151 memsrc.len = SBYTES (specified_data);
7152 memsrc.index = 0;
7154 /* Casting return value avoids a GCC warning on W32. */
7155 gif = (GifFileType *) fn_DGifOpen (&memsrc, gif_read_from_memory);
7156 if (!gif)
7158 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7159 return 0;
7163 /* Before reading entire contents, check the declared image size. */
7164 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7166 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7167 fn_DGifCloseFile (gif);
7168 return 0;
7171 /* Read entire contents. */
7172 rc = fn_DGifSlurp (gif);
7173 if (rc == GIF_ERROR)
7175 image_error ("Error reading `%s'", img->spec, Qnil);
7176 fn_DGifCloseFile (gif);
7177 return 0;
7180 image = image_spec_value (img->spec, QCindex, NULL);
7181 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7182 if (ino >= gif->ImageCount)
7184 image_error ("Invalid image number `%s' in image `%s'",
7185 image, img->spec);
7186 fn_DGifCloseFile (gif);
7187 return 0;
7190 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++)
7191 if ((gif->SavedImages[ino].ExtensionBlocks[i].Function
7192 == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7193 && gif->SavedImages[ino].ExtensionBlocks[i].ByteCount == 4
7194 /* Transparency enabled? */
7195 && gif->SavedImages[ino].ExtensionBlocks[i].Bytes[0] & 1)
7197 transparent_p = 1;
7198 transparency_color_index
7199 = (unsigned char) gif->SavedImages[ino].ExtensionBlocks[i].Bytes[3];
7202 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
7203 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
7204 image_height = gif->SavedImages[ino].ImageDesc.Height;
7205 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
7206 image_width = gif->SavedImages[ino].ImageDesc.Width;
7207 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
7209 width = img->width = max (gif->SWidth,
7210 max (gif->Image.Left + gif->Image.Width,
7211 img->corners[RIGHT_CORNER]));
7212 height = img->height = max (gif->SHeight,
7213 max (gif->Image.Top + gif->Image.Height,
7214 img->corners[BOT_CORNER]));
7216 if (!check_image_size (f, width, height))
7218 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7219 fn_DGifCloseFile (gif);
7220 return 0;
7223 /* Create the X image and pixmap. */
7224 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7226 fn_DGifCloseFile (gif);
7227 return 0;
7230 /* Allocate colors. */
7231 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7232 if (!gif_color_map)
7233 gif_color_map = gif->SColorMap;
7234 init_color_table ();
7235 memset (pixel_colors, 0, sizeof pixel_colors);
7237 if (gif_color_map)
7238 for (i = 0; i < gif_color_map->ColorCount; ++i)
7240 if (transparent_p && transparency_color_index == i)
7242 Lisp_Object specified_bg
7243 = image_spec_value (img->spec, QCbackground, NULL);
7244 pixel_colors[i] = STRINGP (specified_bg)
7245 ? x_alloc_image_color (f, img, specified_bg,
7246 FRAME_BACKGROUND_PIXEL (f))
7247 : FRAME_BACKGROUND_PIXEL (f);
7249 else
7251 int r = gif_color_map->Colors[i].Red << 8;
7252 int g = gif_color_map->Colors[i].Green << 8;
7253 int b = gif_color_map->Colors[i].Blue << 8;
7254 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7258 #ifdef COLOR_TABLE_SUPPORT
7259 img->colors = colors_in_color_table (&img->ncolors);
7260 free_color_table ();
7261 #endif /* COLOR_TABLE_SUPPORT */
7263 /* Clear the part of the screen image that are not covered by
7264 the image from the GIF file. Full animated GIF support
7265 requires more than can be done here (see the gif89 spec,
7266 disposal methods). Let's simply assume that the part
7267 not covered by a sub-image is in the frame's background color. */
7268 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7269 for (x = 0; x < width; ++x)
7270 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7272 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7273 for (x = 0; x < width; ++x)
7274 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7276 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7278 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7279 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7280 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7281 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7284 /* Read the GIF image into the X image. We use a local variable
7285 `raster' here because RasterBits below is a char *, and invites
7286 problems with bytes >= 0x80. */
7287 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7289 if (gif->SavedImages[ino].ImageDesc.Interlace)
7291 int pass;
7292 int row = interlace_start[0];
7294 pass = 0;
7296 for (y = 0; y < image_height; y++)
7298 if (row >= image_height)
7300 row = interlace_start[++pass];
7301 while (row >= image_height)
7302 row = interlace_start[++pass];
7305 for (x = 0; x < image_width; x++)
7307 int i = raster[(y * image_width) + x];
7308 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7309 row + img->corners[TOP_CORNER], pixel_colors[i]);
7312 row += interlace_increment[pass];
7315 else
7317 for (y = 0; y < image_height; ++y)
7318 for (x = 0; x < image_width; ++x)
7320 int i = raster[y * image_width + x];
7321 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7322 y + img->corners[TOP_CORNER], pixel_colors[i]);
7326 /* Save GIF image extension data for `image-metadata'.
7327 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7328 img->data.lisp_val = Qnil;
7329 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
7331 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
7332 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
7333 /* Append (... FUNCTION "BYTES") */
7334 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7335 Fcons (make_number (ext->Function),
7336 img->data.lisp_val));
7337 img->data.lisp_val = Fcons (Qextension_data,
7338 Fcons (Fnreverse (img->data.lisp_val),
7339 Qnil));
7341 if (gif->ImageCount > 1)
7342 img->data.lisp_val = Fcons (Qcount,
7343 Fcons (make_number (gif->ImageCount),
7344 img->data.lisp_val));
7346 fn_DGifCloseFile (gif);
7348 /* Maybe fill in the background field while we have ximg handy. */
7349 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7350 /* Casting avoids a GCC warning. */
7351 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7353 /* Put the image into the pixmap, then free the X image and its buffer. */
7354 x_put_x_image (f, ximg, img->pixmap, width, height);
7355 x_destroy_x_image (ximg);
7357 return 1;
7360 #else /* !HAVE_GIF */
7362 #ifdef HAVE_NS
7363 static int
7364 gif_load (struct frame *f, struct image *img)
7366 return ns_load_image (f, img,
7367 image_spec_value (img->spec, QCfile, NULL),
7368 image_spec_value (img->spec, QCdata, NULL));
7370 #endif /* HAVE_NS */
7372 #endif /* HAVE_GIF */
7375 /***********************************************************************
7376 imagemagick
7377 ***********************************************************************/
7378 #if defined (HAVE_IMAGEMAGICK)
7379 Lisp_Object Vimagemagick_render_type;
7381 /* The symbol `imagemagick' identifying images of this type. */
7383 Lisp_Object Qimagemagick;
7384 Lisp_Object Vimagemagick_render_type;
7386 /* Indices of image specification fields in imagemagick_format, below. */
7388 enum imagemagick_keyword_index
7390 IMAGEMAGICK_TYPE,
7391 IMAGEMAGICK_DATA,
7392 IMAGEMAGICK_FILE,
7393 IMAGEMAGICK_ASCENT,
7394 IMAGEMAGICK_MARGIN,
7395 IMAGEMAGICK_RELIEF,
7396 IMAGEMAGICK_ALGORITHM,
7397 IMAGEMAGICK_HEURISTIC_MASK,
7398 IMAGEMAGICK_MASK,
7399 IMAGEMAGICK_BACKGROUND,
7400 IMAGEMAGICK_HEIGHT,
7401 IMAGEMAGICK_WIDTH,
7402 IMAGEMAGICK_ROTATION,
7403 IMAGEMAGICK_CROP,
7404 IMAGEMAGICK_LAST
7407 /* Vector of image_keyword structures describing the format
7408 of valid user-defined image specifications. */
7410 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7412 {":type", IMAGE_SYMBOL_VALUE, 1},
7413 {":data", IMAGE_STRING_VALUE, 0},
7414 {":file", IMAGE_STRING_VALUE, 0},
7415 {":ascent", IMAGE_ASCENT_VALUE, 0},
7416 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7417 {":relief", IMAGE_INTEGER_VALUE, 0},
7418 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7419 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7420 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7421 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7422 {":height", IMAGE_INTEGER_VALUE, 0},
7423 {":width", IMAGE_INTEGER_VALUE, 0},
7424 {":rotation", IMAGE_NUMBER_VALUE, 0},
7425 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7427 /* Free X resources of imagemagick image IMG which is used on frame F. */
7429 static void
7430 imagemagick_clear_image (struct frame *f,
7431 struct image *img)
7433 x_clear_image (f, img);
7438 /* Return non-zero if OBJECT is a valid IMAGEMAGICK image specification. Do
7439 this by calling parse_image_spec and supplying the keywords that
7440 identify the IMAGEMAGICK format. */
7442 static int
7443 imagemagick_image_p (Lisp_Object object)
7445 struct image_keyword fmt[IMAGEMAGICK_LAST];
7446 memcpy (fmt, imagemagick_format, sizeof fmt);
7448 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7449 return 0;
7451 /* Must specify either the :data or :file keyword. */
7452 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7455 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7456 Therefore rename the function so it doesnt collide with ImageMagick. */
7457 #define DrawRectangle DrawRectangleGif
7458 #include <wand/MagickWand.h>
7460 /* imagemagick_load_image is a helper function for imagemagick_load,
7461 which does the actual loading given contents and size, apart from
7462 frame and image structures, passed from imagemagick_load.
7464 Uses librimagemagick to do most of the image processing.
7466 non-zero when successful.
7469 static int
7470 imagemagick_load_image (/* Pointer to emacs frame structure. */
7471 struct frame *f,
7472 /* Pointer to emacs image structure. */
7473 struct image *img,
7474 /* String containing the IMAGEMAGICK data to
7475 be parsed. */
7476 unsigned char *contents,
7477 /* Size of data in bytes. */
7478 unsigned int size,
7479 /* Filename, either pass filename or
7480 contents/size. */
7481 unsigned char *filename)
7483 unsigned long width;
7484 unsigned long height;
7486 MagickBooleanType
7487 status;
7489 XImagePtr ximg;
7490 Lisp_Object specified_bg;
7491 XColor background;
7492 int x;
7493 int y;
7495 MagickWand *image_wand;
7496 MagickWand *ping_wand;
7497 PixelIterator *iterator;
7498 PixelWand **pixels;
7499 MagickPixelPacket pixel;
7500 Lisp_Object image;
7501 Lisp_Object value;
7502 Lisp_Object crop, geometry;
7503 long ino;
7504 int desired_width, desired_height;
7505 double rotation;
7506 int imagemagick_rendermethod;
7507 int pixelwidth;
7508 ImageInfo *image_info;
7509 ExceptionInfo *exception;
7510 Image * im_image;
7513 /* Handle image index for image types who can contain more than one
7514 image. Interface :index is same as for GIF. First we "ping" the
7515 image to see how many sub-images it contains. Pinging is faster
7516 than loading the image to find out things about it. */
7517 image = image_spec_value (img->spec, QCindex, NULL);
7518 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7519 ping_wand = NewMagickWand ();
7520 MagickSetResolution (ping_wand, 2, 2);
7521 if (filename != NULL)
7523 status = MagickPingImage (ping_wand, filename);
7525 else
7527 status = MagickPingImageBlob (ping_wand, contents, size);
7530 if (ino >= MagickGetNumberImages (ping_wand))
7532 image_error ("Invalid image number `%s' in image `%s'",
7533 image, img->spec);
7534 DestroyMagickWand (ping_wand);
7535 return 0;
7538 if (MagickGetNumberImages(ping_wand) > 1)
7539 img->data.lisp_val =
7540 Fcons (Qcount,
7541 Fcons (make_number (MagickGetNumberImages (ping_wand)),
7542 img->data.lisp_val));
7544 DestroyMagickWand (ping_wand);
7545 /* Now, after pinging, we know how many images are inside the
7546 file. If its not a bundle, just one. */
7548 if (filename != NULL)
7550 image_info = CloneImageInfo ((ImageInfo *) NULL);
7551 (void) strcpy (image_info->filename, filename);
7552 image_info->number_scenes = 1;
7553 image_info->scene = ino;
7554 exception = AcquireExceptionInfo ();
7556 im_image = ReadImage (image_info, exception);
7557 CatchException (exception);
7559 image_wand = NewMagickWandFromImage (im_image);
7561 else
7563 image_wand = NewMagickWand ();
7564 status = MagickReadImageBlob (image_wand, contents, size);
7566 image_error ("im read failed", Qnil, Qnil);
7567 if (status == MagickFalse) goto imagemagick_error;
7569 /* If width and/or height is set in the display spec assume we want
7570 to scale to those values. if either h or w is unspecified, the
7571 unspecified should be calculated from the specified to preserve
7572 aspect ratio. */
7574 value = image_spec_value (img->spec, QCwidth, NULL);
7575 desired_width = (INTEGERP (value) ? XFASTINT (value) : -1);
7576 value = image_spec_value (img->spec, QCheight, NULL);
7577 desired_height = (INTEGERP (value) ? XFASTINT (value) : -1);
7579 height = MagickGetImageHeight (image_wand);
7580 width = MagickGetImageWidth (image_wand);
7582 if(desired_width != -1 && desired_height == -1)
7584 /* w known, calculate h. */
7585 desired_height = (double) desired_width / width * height;
7587 if(desired_width == -1 && desired_height != -1)
7589 /* h known, calculate w. */
7590 desired_width = (double) desired_height / height * width;
7592 if(desired_width != -1 && desired_height != -1)
7594 status = MagickScaleImage (image_wand, desired_width, desired_height);
7595 if (status == MagickFalse)
7597 image_error ("Imagemagick scale failed", Qnil, Qnil);
7598 goto imagemagick_error;
7603 /* crop behaves similar to image slicing in Emacs but is more memory
7604 efficient. */
7605 crop = image_spec_value (img->spec, QCcrop, NULL);
7607 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7609 /* After some testing, it seems MagickCropImage is the fastest
7610 crop function in ImageMagick. This crop function seems to do
7611 less copying than the alternatives, but it still reads the
7612 entire image into memory before croping, which is aparently
7613 difficult to avoid when using imagemagick. */
7615 int w, h, x, y;
7616 w = XFASTINT (XCAR (crop));
7617 crop = XCDR (crop);
7618 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7620 h = XFASTINT (XCAR (crop));
7621 crop = XCDR (crop);
7622 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7624 x = XFASTINT (XCAR (crop));
7625 crop = XCDR (crop);
7626 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7628 y = XFASTINT (XCAR (crop));
7629 MagickCropImage (image_wand, w, h, x, y);
7635 /* Furthermore :rotation. we need background color and angle for
7636 rotation. */
7638 TODO background handling for rotation specified_bg =
7639 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
7640 (specified_bg). */
7641 value = image_spec_value (img->spec, QCrotation, NULL);
7642 if (FLOATP (value))
7644 PixelWand* background = NewPixelWand ();
7645 PixelSetColor (background, "#ffffff");/*TODO remove hardcode*/
7647 rotation = extract_float (value);
7649 status = MagickRotateImage (image_wand, background, rotation);
7650 DestroyPixelWand (background);
7651 if (status == MagickFalse)
7653 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
7654 goto imagemagick_error;
7658 /* Finaly we are done manipulating the image, figure out resulting
7659 width, height, and then transfer ownerwship to Emacs. */
7660 height = MagickGetImageHeight (image_wand);
7661 width = MagickGetImageWidth (image_wand);
7662 if (status == MagickFalse)
7664 image_error ("Imagemagick image get size failed", Qnil, Qnil);
7665 goto imagemagick_error;
7668 if (! check_image_size (f, width, height))
7670 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7671 goto imagemagick_error;
7674 /* We can now get a valid pixel buffer from the imagemagick file, if all
7675 went ok. */
7677 init_color_table ();
7678 imagemagick_rendermethod = (INTEGERP (Vimagemagick_render_type)
7679 ? XFASTINT (Vimagemagick_render_type) : 0);
7680 if (imagemagick_rendermethod == 0)
7682 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7683 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7684 &ximg, &img->pixmap))
7686 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7687 goto imagemagick_error;
7690 /* Copy imagegmagick image to x with primitive yet robust pixel
7691 pusher loop. This has been tested a lot with many different
7692 images. */
7694 /* Copy pixels from the imagemagick image structure to the x image map. */
7695 iterator = NewPixelIterator (image_wand);
7696 if (iterator == (PixelIterator *) NULL)
7698 image_error ("Imagemagick pixel iterator creation failed",
7699 Qnil, Qnil);
7700 goto imagemagick_error;
7703 for (y = 0; y < (long) MagickGetImageHeight (image_wand); y++)
7705 pixels = PixelGetNextIteratorRow (iterator, &width);
7706 if (pixels == (PixelWand **) NULL)
7707 break;
7708 for (x = 0; x < (long) width; x++)
7710 PixelGetMagickColor (pixels[x], &pixel);
7711 XPutPixel (ximg, x, y,
7712 lookup_rgb_color (f,
7713 pixel.red,
7714 pixel.green,
7715 pixel.blue));
7718 DestroyPixelIterator (iterator);
7721 if (imagemagick_rendermethod == 1)
7723 /* Magicexportimage is normaly faster than pixelpushing. This
7724 method is also well tested. Some aspects of this method are
7725 ad-hoc and needs to be more researched. */
7726 int imagedepth = 24;/*MagickGetImageDepth(image_wand);*/
7727 char* exportdepth = imagedepth <= 8 ? "I" : "BGRP";/*"RGBP";*/
7728 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7729 if (!x_create_x_image_and_pixmap (f, width, height, imagedepth,
7730 &ximg, &img->pixmap))
7732 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7733 goto imagemagick_error;
7737 /* Oddly, the below code doesnt seem to work:*/
7738 /* switch(ximg->bitmap_unit){ */
7739 /* case 8: */
7740 /* pixelwidth=CharPixel; */
7741 /* break; */
7742 /* case 16: */
7743 /* pixelwidth=ShortPixel; */
7744 /* break; */
7745 /* case 32: */
7746 /* pixelwidth=LongPixel; */
7747 /* break; */
7748 /* } */
7750 Here im just guessing the format of the bitmap.
7751 happens to work fine for:
7752 - bw djvu images
7753 on rgb display.
7754 seems about 3 times as fast as pixel pushing(not carefully measured)
7756 pixelwidth = CharPixel;/*??? TODO figure out*/
7757 #ifdef HAVE_MAGICKEXPORTIMAGEPIXELS
7758 MagickExportImagePixels (image_wand,
7759 0, 0,
7760 width, height,
7761 exportdepth,
7762 pixelwidth,
7763 /*&(img->pixmap));*/
7764 ximg->data);
7765 #else
7766 image_error ("You dont have MagickExportImagePixels, upgrade ImageMagick!",
7767 Qnil, Qnil);
7768 #endif
7772 #ifdef COLOR_TABLE_SUPPORT
7773 /* Remember colors allocated for this image. */
7774 img->colors = colors_in_color_table (&img->ncolors);
7775 free_color_table ();
7776 #endif /* COLOR_TABLE_SUPPORT */
7779 img->width = width;
7780 img->height = height;
7782 /* Put the image into the pixmap, then free the X image and its
7783 buffer. */
7784 x_put_x_image (f, ximg, img->pixmap, width, height);
7785 x_destroy_x_image (ximg);
7788 /* Final cleanup. image_wand should be the only resource left. */
7789 DestroyMagickWand (image_wand);
7791 return 1;
7793 imagemagick_error:
7794 /* TODO more cleanup. */
7795 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
7796 return 0;
7800 /* Load IMAGEMAGICK image IMG for use on frame F. Value is non-zero if
7801 successful. this function will go into the imagemagick_type structure, and
7802 the prototype thus needs to be compatible with that structure. */
7804 static int
7805 imagemagick_load (struct frame *f,
7806 struct image *img)
7808 int success_p = 0;
7809 Lisp_Object file_name;
7811 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7812 file_name = image_spec_value (img->spec, QCfile, NULL);
7813 if (STRINGP (file_name))
7815 Lisp_Object file;
7817 file = x_find_image_file (file_name);
7818 if (!STRINGP (file))
7820 image_error ("Cannot find image file `%s'", file_name, Qnil);
7821 return 0;
7823 success_p = imagemagick_load_image (f, img, 0, 0, SDATA (file));
7825 /* Else its not a file, its a lisp object. Load the image from a
7826 lisp object rather than a file. */
7827 else
7829 Lisp_Object data;
7831 data = image_spec_value (img->spec, QCdata, NULL);
7832 if (!STRINGP (data))
7834 image_error ("Invalid image data `%s'", data, Qnil);
7835 return 0;
7837 success_p = imagemagick_load_image (f, img, SDATA (data),
7838 SBYTES (data), NULL);
7841 return success_p;
7844 /* Structure describing the image type `imagemagick'. Its the same
7845 type of structure defined for all image formats, handled by Emacs
7846 image functions. See struct image_type in dispextern.h. */
7848 static struct image_type imagemagick_type =
7850 /* An identifier showing that this is an image structure for the
7851 IMAGEMAGICK format. */
7852 &Qimagemagick,
7853 /* Handle to a function that can be used to identify a IMAGEMAGICK
7854 file. */
7855 imagemagick_image_p,
7856 /* Handle to function used to load a IMAGEMAGICK file. */
7857 imagemagick_load,
7858 /* Handle to function to free resources for IMAGEMAGICK. */
7859 imagemagick_clear_image,
7860 /* An internal field to link to the next image type in a list of
7861 image types, will be filled in when registering the format. */
7862 NULL
7868 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
7869 doc: /* Return image file types supported by ImageMagick.
7870 Since ImageMagick recognizes a lot of file-types that clash with Emacs,
7871 such as .c, we want to be able to alter the list at the lisp level. */)
7872 (void)
7874 Lisp_Object typelist = Qnil;
7875 unsigned long numf;
7876 ExceptionInfo ex;
7877 char **imtypes = GetMagickList ("*", &numf, &ex);
7878 int i;
7879 Lisp_Object Qimagemagicktype;
7880 for (i = 0; i < numf; i++)
7882 Qimagemagicktype = intern (imtypes[i]);
7883 typelist = Fcons (Qimagemagicktype, typelist);
7885 return typelist;
7888 #endif /* defined (HAVE_IMAGEMAGICK) */
7892 /***********************************************************************
7894 ***********************************************************************/
7896 #if defined (HAVE_RSVG)
7898 /* Function prototypes. */
7900 static int svg_image_p (Lisp_Object object);
7901 static int svg_load (struct frame *f, struct image *img);
7903 static int svg_load_image (struct frame *, struct image *,
7904 unsigned char *, unsigned int);
7906 /* The symbol `svg' identifying images of this type. */
7908 Lisp_Object Qsvg;
7910 /* Indices of image specification fields in svg_format, below. */
7912 enum svg_keyword_index
7914 SVG_TYPE,
7915 SVG_DATA,
7916 SVG_FILE,
7917 SVG_ASCENT,
7918 SVG_MARGIN,
7919 SVG_RELIEF,
7920 SVG_ALGORITHM,
7921 SVG_HEURISTIC_MASK,
7922 SVG_MASK,
7923 SVG_BACKGROUND,
7924 SVG_LAST
7927 /* Vector of image_keyword structures describing the format
7928 of valid user-defined image specifications. */
7930 static const struct image_keyword svg_format[SVG_LAST] =
7932 {":type", IMAGE_SYMBOL_VALUE, 1},
7933 {":data", IMAGE_STRING_VALUE, 0},
7934 {":file", IMAGE_STRING_VALUE, 0},
7935 {":ascent", IMAGE_ASCENT_VALUE, 0},
7936 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7937 {":relief", IMAGE_INTEGER_VALUE, 0},
7938 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7939 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7940 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7941 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7944 /* Structure describing the image type `svg'. Its the same type of
7945 structure defined for all image formats, handled by emacs image
7946 functions. See struct image_type in dispextern.h. */
7948 static struct image_type svg_type =
7950 /* An identifier showing that this is an image structure for the SVG format. */
7951 &Qsvg,
7952 /* Handle to a function that can be used to identify a SVG file. */
7953 svg_image_p,
7954 /* Handle to function used to load a SVG file. */
7955 svg_load,
7956 /* Handle to function to free sresources for SVG. */
7957 x_clear_image,
7958 /* An internal field to link to the next image type in a list of
7959 image types, will be filled in when registering the format. */
7960 NULL
7964 /* Return non-zero if OBJECT is a valid SVG image specification. Do
7965 this by calling parse_image_spec and supplying the keywords that
7966 identify the SVG format. */
7968 static int
7969 svg_image_p (Lisp_Object object)
7971 struct image_keyword fmt[SVG_LAST];
7972 memcpy (fmt, svg_format, sizeof fmt);
7974 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
7975 return 0;
7977 /* Must specify either the :data or :file keyword. */
7978 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
7981 #include <librsvg/rsvg.h>
7983 #ifdef HAVE_NTGUI
7985 /* SVG library functions. */
7986 DEF_IMGLIB_FN (rsvg_handle_new);
7987 DEF_IMGLIB_FN (rsvg_handle_get_dimensions);
7988 DEF_IMGLIB_FN (rsvg_handle_write);
7989 DEF_IMGLIB_FN (rsvg_handle_close);
7990 DEF_IMGLIB_FN (rsvg_handle_get_pixbuf);
7991 DEF_IMGLIB_FN (rsvg_handle_free);
7993 DEF_IMGLIB_FN (gdk_pixbuf_get_width);
7994 DEF_IMGLIB_FN (gdk_pixbuf_get_height);
7995 DEF_IMGLIB_FN (gdk_pixbuf_get_pixels);
7996 DEF_IMGLIB_FN (gdk_pixbuf_get_rowstride);
7997 DEF_IMGLIB_FN (gdk_pixbuf_get_colorspace);
7998 DEF_IMGLIB_FN (gdk_pixbuf_get_n_channels);
7999 DEF_IMGLIB_FN (gdk_pixbuf_get_has_alpha);
8000 DEF_IMGLIB_FN (gdk_pixbuf_get_bits_per_sample);
8002 DEF_IMGLIB_FN (g_type_init);
8003 DEF_IMGLIB_FN (g_object_unref);
8004 DEF_IMGLIB_FN (g_error_free);
8006 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8008 static int
8009 init_svg_functions (Lisp_Object libraries)
8011 HMODULE library, gdklib, glib, gobject;
8013 if (!(glib = w32_delayed_load (libraries, Qglib))
8014 || !(gobject = w32_delayed_load (libraries, Qgobject))
8015 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
8016 || !(library = w32_delayed_load (libraries, Qsvg)))
8017 return 0;
8019 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8020 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8021 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8022 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8023 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8024 LOAD_IMGLIB_FN (library, rsvg_handle_free);
8026 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8027 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8028 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8029 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8030 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8031 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8032 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8033 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8035 LOAD_IMGLIB_FN (gobject, g_type_init);
8036 LOAD_IMGLIB_FN (gobject, g_object_unref);
8037 LOAD_IMGLIB_FN (glib, g_error_free);
8039 return 1;
8042 #else
8043 /* The following aliases for library functions allow dynamic loading
8044 to be used on some platforms. */
8045 #define fn_rsvg_handle_new rsvg_handle_new
8046 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8047 #define fn_rsvg_handle_write rsvg_handle_write
8048 #define fn_rsvg_handle_close rsvg_handle_close
8049 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8050 #define fn_rsvg_handle_free rsvg_handle_free
8052 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8053 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8054 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8055 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8056 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8057 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8058 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8059 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8061 #define fn_g_type_init g_type_init
8062 #define fn_g_object_unref g_object_unref
8063 #define fn_g_error_free g_error_free
8064 #endif /* !HAVE_NTGUI */
8066 /* Load SVG image IMG for use on frame F. Value is non-zero if
8067 successful. this function will go into the svg_type structure, and
8068 the prototype thus needs to be compatible with that structure. */
8070 static int
8071 svg_load (struct frame *f, struct image *img)
8073 int success_p = 0;
8074 Lisp_Object file_name;
8076 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8077 file_name = image_spec_value (img->spec, QCfile, NULL);
8078 if (STRINGP (file_name))
8080 Lisp_Object file;
8081 unsigned char *contents;
8082 int size;
8084 file = x_find_image_file (file_name);
8085 if (!STRINGP (file))
8087 image_error ("Cannot find image file `%s'", file_name, Qnil);
8088 return 0;
8091 /* Read the entire file into memory. */
8092 contents = slurp_file (SDATA (file), &size);
8093 if (contents == NULL)
8095 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8096 return 0;
8098 /* If the file was slurped into memory properly, parse it. */
8099 success_p = svg_load_image (f, img, contents, size);
8100 xfree (contents);
8102 /* Else its not a file, its a lisp object. Load the image from a
8103 lisp object rather than a file. */
8104 else
8106 Lisp_Object data;
8108 data = image_spec_value (img->spec, QCdata, NULL);
8109 if (!STRINGP (data))
8111 image_error ("Invalid image data `%s'", data, Qnil);
8112 return 0;
8114 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8117 return success_p;
8120 /* svg_load_image is a helper function for svg_load, which does the
8121 actual loading given contents and size, apart from frame and image
8122 structures, passed from svg_load.
8124 Uses librsvg to do most of the image processing.
8126 Returns non-zero when successful. */
8127 static int
8128 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8129 struct image *img, /* Pointer to emacs image structure. */
8130 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8131 unsigned int size) /* Size of data in bytes. */
8133 RsvgHandle *rsvg_handle;
8134 RsvgDimensionData dimension_data;
8135 GError *error = NULL;
8136 GdkPixbuf *pixbuf;
8137 int width;
8138 int height;
8139 const guint8 *pixels;
8140 int rowstride;
8141 XImagePtr ximg;
8142 Lisp_Object specified_bg;
8143 XColor background;
8144 int x;
8145 int y;
8147 /* g_type_init is a glib function that must be called prior to using
8148 gnome type library functions. */
8149 fn_g_type_init ();
8150 /* Make a handle to a new rsvg object. */
8151 rsvg_handle = (RsvgHandle *) fn_rsvg_handle_new ();
8153 /* Parse the contents argument and fill in the rsvg_handle. */
8154 fn_rsvg_handle_write (rsvg_handle, contents, size, &error);
8155 if (error) goto rsvg_error;
8157 /* The parsing is complete, rsvg_handle is ready to used, close it
8158 for further writes. */
8159 fn_rsvg_handle_close (rsvg_handle, &error);
8160 if (error) goto rsvg_error;
8162 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8163 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8165 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8166 goto rsvg_error;
8169 /* We can now get a valid pixel buffer from the svg file, if all
8170 went ok. */
8171 pixbuf = (GdkPixbuf *) fn_rsvg_handle_get_pixbuf (rsvg_handle);
8172 if (!pixbuf) goto rsvg_error;
8173 fn_g_object_unref (rsvg_handle);
8175 /* Extract some meta data from the svg handle. */
8176 width = fn_gdk_pixbuf_get_width (pixbuf);
8177 height = fn_gdk_pixbuf_get_height (pixbuf);
8178 pixels = (const guint8 *) fn_gdk_pixbuf_get_pixels (pixbuf);
8179 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8181 /* Validate the svg meta data. */
8182 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8183 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8184 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8185 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8187 /* Try to create a x pixmap to hold the svg pixmap. */
8188 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8190 fn_g_object_unref (pixbuf);
8191 return 0;
8194 init_color_table ();
8196 /* Handle alpha channel by combining the image with a background
8197 color. */
8198 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8199 if (!STRINGP (specified_bg)
8200 || !x_defined_color (f, SDATA (specified_bg), &background, 0))
8202 #ifndef HAVE_NS
8203 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8204 x_query_color (f, &background);
8205 #else
8206 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8207 #endif
8210 /* SVG pixmaps specify transparency in the last byte, so right
8211 shift 8 bits to get rid of it, since emacs doesn't support
8212 transparency. */
8213 background.red >>= 8;
8214 background.green >>= 8;
8215 background.blue >>= 8;
8217 /* This loop handles opacity values, since Emacs assumes
8218 non-transparent images. Each pixel must be "flattened" by
8219 calculating the resulting color, given the transparency of the
8220 pixel, and the image background color. */
8221 for (y = 0; y < height; ++y)
8223 for (x = 0; x < width; ++x)
8225 unsigned red;
8226 unsigned green;
8227 unsigned blue;
8228 unsigned opacity;
8230 red = *pixels++;
8231 green = *pixels++;
8232 blue = *pixels++;
8233 opacity = *pixels++;
8235 red = ((red * opacity)
8236 + (background.red * ((1 << 8) - opacity)));
8237 green = ((green * opacity)
8238 + (background.green * ((1 << 8) - opacity)));
8239 blue = ((blue * opacity)
8240 + (background.blue * ((1 << 8) - opacity)));
8242 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8245 pixels += rowstride - 4 * width;
8248 #ifdef COLOR_TABLE_SUPPORT
8249 /* Remember colors allocated for this image. */
8250 img->colors = colors_in_color_table (&img->ncolors);
8251 free_color_table ();
8252 #endif /* COLOR_TABLE_SUPPORT */
8254 fn_g_object_unref (pixbuf);
8256 img->width = width;
8257 img->height = height;
8259 /* Maybe fill in the background field while we have ximg handy.
8260 Casting avoids a GCC warning. */
8261 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8263 /* Put the image into the pixmap, then free the X image and its
8264 buffer. */
8265 x_put_x_image (f, ximg, img->pixmap, width, height);
8266 x_destroy_x_image (ximg);
8268 return 1;
8270 rsvg_error:
8271 fn_g_object_unref (rsvg_handle);
8272 /* FIXME: Use error->message so the user knows what is the actual
8273 problem with the image. */
8274 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8275 fn_g_error_free (error);
8276 return 0;
8279 #endif /* defined (HAVE_RSVG) */
8284 /***********************************************************************
8285 Ghostscript
8286 ***********************************************************************/
8288 #ifdef HAVE_X_WINDOWS
8289 #define HAVE_GHOSTSCRIPT 1
8290 #endif /* HAVE_X_WINDOWS */
8292 #ifdef HAVE_GHOSTSCRIPT
8294 static int gs_image_p (Lisp_Object object);
8295 static int gs_load (struct frame *f, struct image *img);
8296 static void gs_clear_image (struct frame *f, struct image *img);
8298 /* Keyword symbols. */
8300 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8302 /* Indices of image specification fields in gs_format, below. */
8304 enum gs_keyword_index
8306 GS_TYPE,
8307 GS_PT_WIDTH,
8308 GS_PT_HEIGHT,
8309 GS_FILE,
8310 GS_LOADER,
8311 GS_BOUNDING_BOX,
8312 GS_ASCENT,
8313 GS_MARGIN,
8314 GS_RELIEF,
8315 GS_ALGORITHM,
8316 GS_HEURISTIC_MASK,
8317 GS_MASK,
8318 GS_BACKGROUND,
8319 GS_LAST
8322 /* Vector of image_keyword structures describing the format
8323 of valid user-defined image specifications. */
8325 static const struct image_keyword gs_format[GS_LAST] =
8327 {":type", IMAGE_SYMBOL_VALUE, 1},
8328 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8329 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8330 {":file", IMAGE_STRING_VALUE, 1},
8331 {":loader", IMAGE_FUNCTION_VALUE, 0},
8332 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8333 {":ascent", IMAGE_ASCENT_VALUE, 0},
8334 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8335 {":relief", IMAGE_INTEGER_VALUE, 0},
8336 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8337 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8338 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8339 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8342 /* Structure describing the image type `ghostscript'. */
8344 static struct image_type gs_type =
8346 &Qpostscript,
8347 gs_image_p,
8348 gs_load,
8349 gs_clear_image,
8350 NULL
8354 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8356 static void
8357 gs_clear_image (struct frame *f, struct image *img)
8359 /* IMG->data.ptr_val may contain a recorded colormap. */
8360 xfree (img->data.ptr_val);
8361 x_clear_image (f, img);
8365 /* Return non-zero if OBJECT is a valid Ghostscript image
8366 specification. */
8368 static int
8369 gs_image_p (Lisp_Object object)
8371 struct image_keyword fmt[GS_LAST];
8372 Lisp_Object tem;
8373 int i;
8375 memcpy (fmt, gs_format, sizeof fmt);
8377 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8378 return 0;
8380 /* Bounding box must be a list or vector containing 4 integers. */
8381 tem = fmt[GS_BOUNDING_BOX].value;
8382 if (CONSP (tem))
8384 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8385 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8386 return 0;
8387 if (!NILP (tem))
8388 return 0;
8390 else if (VECTORP (tem))
8392 if (XVECTOR (tem)->size != 4)
8393 return 0;
8394 for (i = 0; i < 4; ++i)
8395 if (!INTEGERP (XVECTOR (tem)->contents[i]))
8396 return 0;
8398 else
8399 return 0;
8401 return 1;
8405 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8406 if successful. */
8408 static int
8409 gs_load (struct frame *f, struct image *img)
8411 char buffer[100];
8412 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8413 Lisp_Object frame;
8414 double in_width, in_height;
8415 Lisp_Object pixel_colors = Qnil;
8417 /* Compute pixel size of pixmap needed from the given size in the
8418 image specification. Sizes in the specification are in pt. 1 pt
8419 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8420 info. */
8421 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8422 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
8423 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
8424 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8425 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
8426 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
8428 if (!check_image_size (f, img->width, img->height))
8430 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8431 return 0;
8434 /* Create the pixmap. */
8435 xassert (img->pixmap == NO_PIXMAP);
8437 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8438 BLOCK_INPUT;
8439 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8440 img->width, img->height,
8441 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8442 UNBLOCK_INPUT;
8444 if (!img->pixmap)
8446 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8447 return 0;
8450 /* Call the loader to fill the pixmap. It returns a process object
8451 if successful. We do not record_unwind_protect here because
8452 other places in redisplay like calling window scroll functions
8453 don't either. Let the Lisp loader use `unwind-protect' instead. */
8454 sprintf (buffer, "%lu %lu",
8455 (unsigned long) FRAME_X_WINDOW (f),
8456 (unsigned long) img->pixmap);
8457 window_and_pixmap_id = build_string (buffer);
8459 sprintf (buffer, "%lu %lu",
8460 FRAME_FOREGROUND_PIXEL (f),
8461 FRAME_BACKGROUND_PIXEL (f));
8462 pixel_colors = build_string (buffer);
8464 XSETFRAME (frame, f);
8465 loader = image_spec_value (img->spec, QCloader, NULL);
8466 if (NILP (loader))
8467 loader = intern ("gs-load-image");
8469 img->data.lisp_val = call6 (loader, frame, img->spec,
8470 make_number (img->width),
8471 make_number (img->height),
8472 window_and_pixmap_id,
8473 pixel_colors);
8474 return PROCESSP (img->data.lisp_val);
8478 /* Kill the Ghostscript process that was started to fill PIXMAP on
8479 frame F. Called from XTread_socket when receiving an event
8480 telling Emacs that Ghostscript has finished drawing. */
8482 void
8483 x_kill_gs_process (Pixmap pixmap, struct frame *f)
8485 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8486 int class, i;
8487 struct image *img;
8489 /* Find the image containing PIXMAP. */
8490 for (i = 0; i < c->used; ++i)
8491 if (c->images[i]->pixmap == pixmap)
8492 break;
8494 /* Should someone in between have cleared the image cache, for
8495 instance, give up. */
8496 if (i == c->used)
8497 return;
8499 /* Kill the GS process. We should have found PIXMAP in the image
8500 cache and its image should contain a process object. */
8501 img = c->images[i];
8502 xassert (PROCESSP (img->data.lisp_val));
8503 Fkill_process (img->data.lisp_val, Qnil);
8504 img->data.lisp_val = Qnil;
8506 #if defined (HAVE_X_WINDOWS)
8508 /* On displays with a mutable colormap, figure out the colors
8509 allocated for the image by looking at the pixels of an XImage for
8510 img->pixmap. */
8511 class = FRAME_X_VISUAL (f)->class;
8512 if (class != StaticColor && class != StaticGray && class != TrueColor)
8514 XImagePtr ximg;
8516 BLOCK_INPUT;
8518 /* Try to get an XImage for img->pixmep. */
8519 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8520 0, 0, img->width, img->height, ~0, ZPixmap);
8521 if (ximg)
8523 int x, y;
8525 /* Initialize the color table. */
8526 init_color_table ();
8528 /* For each pixel of the image, look its color up in the
8529 color table. After having done so, the color table will
8530 contain an entry for each color used by the image. */
8531 for (y = 0; y < img->height; ++y)
8532 for (x = 0; x < img->width; ++x)
8534 unsigned long pixel = XGetPixel (ximg, x, y);
8535 lookup_pixel_color (f, pixel);
8538 /* Record colors in the image. Free color table and XImage. */
8539 #ifdef COLOR_TABLE_SUPPORT
8540 img->colors = colors_in_color_table (&img->ncolors);
8541 free_color_table ();
8542 #endif
8543 XDestroyImage (ximg);
8545 #if 0 /* This doesn't seem to be the case. If we free the colors
8546 here, we get a BadAccess later in x_clear_image when
8547 freeing the colors. */
8548 /* We have allocated colors once, but Ghostscript has also
8549 allocated colors on behalf of us. So, to get the
8550 reference counts right, free them once. */
8551 if (img->ncolors)
8552 x_free_colors (f, img->colors, img->ncolors);
8553 #endif
8555 else
8556 image_error ("Cannot get X image of `%s'; colors will not be freed",
8557 img->spec, Qnil);
8559 UNBLOCK_INPUT;
8561 #endif /* HAVE_X_WINDOWS */
8563 /* Now that we have the pixmap, compute mask and transform the
8564 image if requested. */
8565 BLOCK_INPUT;
8566 postprocess_image (f, img);
8567 UNBLOCK_INPUT;
8570 #endif /* HAVE_GHOSTSCRIPT */
8573 /***********************************************************************
8574 Tests
8575 ***********************************************************************/
8577 #if GLYPH_DEBUG
8579 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8580 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8581 (Lisp_Object spec)
8583 return valid_image_p (spec) ? Qt : Qnil;
8587 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8588 (Lisp_Object spec)
8590 int id = -1;
8592 if (valid_image_p (spec))
8593 id = lookup_image (SELECTED_FRAME (), spec);
8595 debug_print (spec);
8596 return make_number (id);
8599 #endif /* GLYPH_DEBUG != 0 */
8602 /***********************************************************************
8603 Initialization
8604 ***********************************************************************/
8606 #ifdef HAVE_NTGUI
8607 /* Image types that rely on external libraries are loaded dynamically
8608 if the library is available. */
8609 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8610 define_image_type (image_type, init_lib_fn (libraries))
8611 #else
8612 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8613 define_image_type (image_type, 1)
8614 #endif /* HAVE_NTGUI */
8616 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8617 doc: /* Initialize image library implementing image type TYPE.
8618 Return non-nil if TYPE is a supported image type.
8620 Image types pbm and xbm are prebuilt; other types are loaded here.
8621 Libraries to load are specified in alist LIBRARIES (usually, the value
8622 of `dynamic-library-alist', which see). */)
8623 (Lisp_Object type, Lisp_Object libraries)
8625 Lisp_Object tested;
8627 /* Don't try to reload the library. */
8628 tested = Fassq (type, Vimage_type_cache);
8629 if (CONSP (tested))
8630 return XCDR (tested);
8632 #if defined (HAVE_XPM) || defined (HAVE_NS)
8633 if (EQ (type, Qxpm))
8634 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8635 #endif
8637 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8638 if (EQ (type, Qjpeg))
8639 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8640 #endif
8642 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8643 if (EQ (type, Qtiff))
8644 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8645 #endif
8647 #if defined (HAVE_GIF) || defined (HAVE_NS)
8648 if (EQ (type, Qgif))
8649 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8650 #endif
8652 #if defined (HAVE_PNG) || defined (HAVE_NS)
8653 if (EQ (type, Qpng))
8654 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8655 #endif
8657 #if defined (HAVE_RSVG)
8658 if (EQ (type, Qsvg))
8659 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
8660 #endif
8662 #if defined (HAVE_IMAGEMAGICK)
8663 if (EQ (type, Qimagemagick))
8665 /* MagickWandGenesis() initializes the imagemagick library. */
8666 MagickWandGenesis ();
8667 return CHECK_LIB_AVAILABLE (&imagemagick_type, init_imagemagick_functions,
8668 libraries);
8670 #endif
8672 #ifdef HAVE_GHOSTSCRIPT
8673 if (EQ (type, Qpostscript))
8674 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8675 #endif
8677 /* If the type is not recognized, avoid testing it ever again. */
8678 CACHE_IMAGE_TYPE (type, Qnil);
8679 return Qnil;
8682 void
8683 syms_of_image (void)
8685 /* Initialize this only once, since that's what we do with Vimage_types
8686 and they are supposed to be in sync. Initializing here gives correct
8687 operation on GNU/Linux of calling dump-emacs after loading some images. */
8688 image_types = NULL;
8690 /* Must be defined now becase we're going to update it below, while
8691 defining the supported image types. */
8692 DEFVAR_LISP ("image-types", &Vimage_types,
8693 doc: /* List of potentially supported image types.
8694 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8695 To check whether it is really supported, use `image-type-available-p'. */);
8696 Vimage_types = Qnil;
8698 DEFVAR_LISP ("max-image-size", &Vmax_image_size,
8699 doc: /* Maximum size of images.
8700 Emacs will not load an image into memory if its pixel width or
8701 pixel height exceeds this limit.
8703 If the value is an integer, it directly specifies the maximum
8704 image height and width, measured in pixels. If it is a floating
8705 point number, it specifies the maximum image height and width
8706 as a ratio to the frame height and width. If the value is
8707 non-numeric, there is no explicit limit on the size of images. */);
8708 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8710 Vimage_type_cache = Qnil;
8711 staticpro (&Vimage_type_cache);
8713 Qpbm = intern_c_string ("pbm");
8714 staticpro (&Qpbm);
8715 ADD_IMAGE_TYPE (Qpbm);
8717 Qxbm = intern_c_string ("xbm");
8718 staticpro (&Qxbm);
8719 ADD_IMAGE_TYPE (Qxbm);
8721 define_image_type (&xbm_type, 1);
8722 define_image_type (&pbm_type, 1);
8724 Qcount = intern_c_string ("count");
8725 staticpro (&Qcount);
8726 Qextension_data = intern_c_string ("extension-data");
8727 staticpro (&Qextension_data);
8729 QCascent = intern_c_string (":ascent");
8730 staticpro (&QCascent);
8731 QCmargin = intern_c_string (":margin");
8732 staticpro (&QCmargin);
8733 QCrelief = intern_c_string (":relief");
8734 staticpro (&QCrelief);
8735 QCconversion = intern_c_string (":conversion");
8736 staticpro (&QCconversion);
8737 QCcolor_symbols = intern_c_string (":color-symbols");
8738 staticpro (&QCcolor_symbols);
8739 QCheuristic_mask = intern_c_string (":heuristic-mask");
8740 staticpro (&QCheuristic_mask);
8741 QCindex = intern_c_string (":index");
8742 staticpro (&QCindex);
8743 QCgeometry = intern_c_string (":geometry");
8744 staticpro (&QCgeometry);
8745 QCcrop = intern_c_string (":crop");
8746 staticpro (&QCcrop);
8747 QCrotation = intern_c_string (":rotation");
8748 staticpro (&QCrotation);
8749 QCmatrix = intern_c_string (":matrix");
8750 staticpro (&QCmatrix);
8751 QCcolor_adjustment = intern_c_string (":color-adjustment");
8752 staticpro (&QCcolor_adjustment);
8753 QCmask = intern_c_string (":mask");
8754 staticpro (&QCmask);
8756 Qlaplace = intern_c_string ("laplace");
8757 staticpro (&Qlaplace);
8758 Qemboss = intern_c_string ("emboss");
8759 staticpro (&Qemboss);
8760 Qedge_detection = intern_c_string ("edge-detection");
8761 staticpro (&Qedge_detection);
8762 Qheuristic = intern_c_string ("heuristic");
8763 staticpro (&Qheuristic);
8765 Qpostscript = intern_c_string ("postscript");
8766 staticpro (&Qpostscript);
8767 #ifdef HAVE_GHOSTSCRIPT
8768 ADD_IMAGE_TYPE (Qpostscript);
8769 QCloader = intern_c_string (":loader");
8770 staticpro (&QCloader);
8771 QCbounding_box = intern_c_string (":bounding-box");
8772 staticpro (&QCbounding_box);
8773 QCpt_width = intern_c_string (":pt-width");
8774 staticpro (&QCpt_width);
8775 QCpt_height = intern_c_string (":pt-height");
8776 staticpro (&QCpt_height);
8777 #endif /* HAVE_GHOSTSCRIPT */
8779 #if defined (HAVE_XPM) || defined (HAVE_NS)
8780 Qxpm = intern_c_string ("xpm");
8781 staticpro (&Qxpm);
8782 ADD_IMAGE_TYPE (Qxpm);
8783 #endif
8785 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8786 Qjpeg = intern_c_string ("jpeg");
8787 staticpro (&Qjpeg);
8788 ADD_IMAGE_TYPE (Qjpeg);
8789 #endif
8791 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8792 Qtiff = intern_c_string ("tiff");
8793 staticpro (&Qtiff);
8794 ADD_IMAGE_TYPE (Qtiff);
8795 #endif
8797 #if defined (HAVE_GIF) || defined (HAVE_NS)
8798 Qgif = intern_c_string ("gif");
8799 staticpro (&Qgif);
8800 ADD_IMAGE_TYPE (Qgif);
8801 #endif
8803 #if defined (HAVE_PNG) || defined (HAVE_NS)
8804 Qpng = intern_c_string ("png");
8805 staticpro (&Qpng);
8806 ADD_IMAGE_TYPE (Qpng);
8807 #endif
8809 #if defined (HAVE_IMAGEMAGICK)
8810 Qimagemagick = intern_c_string ("imagemagick");
8811 staticpro (&Qimagemagick);
8812 ADD_IMAGE_TYPE (Qimagemagick);
8813 #endif
8815 #if defined (HAVE_RSVG)
8816 Qsvg = intern_c_string ("svg");
8817 staticpro (&Qsvg);
8818 ADD_IMAGE_TYPE (Qsvg);
8819 #ifdef HAVE_NTGUI
8820 /* Other libraries used directly by svg code. */
8821 Qgdk_pixbuf = intern_c_string ("gdk-pixbuf");
8822 staticpro (&Qgdk_pixbuf);
8823 Qglib = intern_c_string ("glib");
8824 staticpro (&Qglib);
8825 Qgobject = intern_c_string ("gobject");
8826 staticpro (&Qgobject);
8827 #endif /* HAVE_NTGUI */
8828 #endif /* HAVE_RSVG */
8830 defsubr (&Sinit_image_library);
8831 #ifdef HAVE_IMAGEMAGICK
8832 defsubr (&Simagemagick_types);
8833 #endif
8834 defsubr (&Sclear_image_cache);
8835 defsubr (&Simage_flush);
8836 defsubr (&Simage_size);
8837 defsubr (&Simage_mask_p);
8838 defsubr (&Simage_metadata);
8840 #if GLYPH_DEBUG
8841 defsubr (&Simagep);
8842 defsubr (&Slookup_image);
8843 #endif
8845 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
8846 doc: /* Non-nil means always draw a cross over disabled images.
8847 Disabled images are those having a `:conversion disabled' property.
8848 A cross is always drawn on black & white displays. */);
8849 cross_disabled_images = 0;
8851 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
8852 doc: /* List of directories to search for window system bitmap files. */);
8853 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8855 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
8856 doc: /* Maximum time after which images are removed from the cache.
8857 When an image has not been displayed this many seconds, Emacs
8858 automatically removes it from the image cache. If the cache contains
8859 a large number of images, the actual eviction time may be shorter.
8860 The value can also be nil, meaning the cache is never cleared.
8862 The function `clear-image-cache' disregards this variable. */);
8863 Vimage_cache_eviction_delay = make_number (300);
8864 #ifdef HAVE_IMAGEMAGICK
8865 DEFVAR_LISP ("imagemagick-render-type", &Vimagemagick_render_type,
8866 doc: /* Choose between ImageMagick render methods. */);
8867 #endif
8871 void
8872 init_image (void)
8876 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
8877 (do not change this comment) */