Record "safe themes" as sha1 hashes, as suggested by Stefan Monnier.
[emacs.git] / src / image.c
blobfd1b921056cba47ac58f83670e6116a7d6f46f47
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 2011 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);
98 /* Version of libpng that we were compiled with, or -1 if no PNG
99 support was compiled in. This is tested by w32-win.el to correctly
100 set up the alist used to search for PNG libraries. */
101 Lisp_Object Qlibpng_version;
102 #endif /* HAVE_NTGUI */
104 #ifdef HAVE_NS
105 #include "nsterm.h"
106 #include <sys/types.h>
107 #include <sys/stat.h>
109 #undef COLOR_TABLE_SUPPORT
111 typedef struct ns_bitmap_record Bitmap_Record;
113 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
114 #define NO_PIXMAP 0
116 #define RGB_PIXEL_COLOR unsigned long
117 #define ZPixmap 0
119 #define PIX_MASK_RETAIN 0
120 #define PIX_MASK_DRAW 1
122 #define FRAME_X_VISUAL FRAME_NS_DISPLAY_INFO(f)->visual
123 #define x_defined_color(f, name, color_def, alloc) \
124 ns_defined_color (f, name, color_def, alloc, 0)
125 #define FRAME_X_SCREEN(f) 0
126 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
127 #endif /* HAVE_NS */
130 /* Search path for bitmap files. */
132 Lisp_Object Vx_bitmap_file_path;
134 /* The symbol `postscript' identifying images of this type. */
136 Lisp_Object Qpostscript;
138 static void x_disable_image (struct frame *, struct image *);
139 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
140 Lisp_Object);
142 static void init_color_table (void);
143 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
144 #ifdef COLOR_TABLE_SUPPORT
145 static void free_color_table (void);
146 static unsigned long *colors_in_color_table (int *n);
147 static unsigned long lookup_pixel_color (struct frame *f, unsigned long p);
148 #endif
150 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
151 id, which is just an int that this section returns. Bitmaps are
152 reference counted so they can be shared among frames.
154 Bitmap indices are guaranteed to be > 0, so a negative number can
155 be used to indicate no bitmap.
157 If you use x_create_bitmap_from_data, then you must keep track of
158 the bitmaps yourself. That is, creating a bitmap from the same
159 data more than once will not be caught. */
161 #ifdef HAVE_NS
162 XImagePtr
163 XGetImage (Display *display, Pixmap pixmap, int x, int y,
164 unsigned int width, unsigned int height,
165 unsigned long plane_mask, int format)
167 /* TODO: not sure what this function is supposed to do.. */
168 ns_retain_object (pixmap);
169 return pixmap;
172 /* use with imgs created by ns_image_for_XPM */
173 unsigned long
174 XGetPixel (XImagePtr ximage, int x, int y)
176 return ns_get_pixel (ximage, x, y);
179 /* use with imgs created by ns_image_for_XPM; alpha set to 1;
180 pixel is assumed to be in form RGB */
181 void
182 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
184 ns_put_pixel (ximage, x, y, pixel);
186 #endif /* HAVE_NS */
189 /* Functions to access the contents of a bitmap, given an id. */
192 x_bitmap_height (FRAME_PTR f, int id)
194 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
198 x_bitmap_width (FRAME_PTR f, int id)
200 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
203 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
205 x_bitmap_pixmap (FRAME_PTR f, int id)
207 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
209 #endif
211 #ifdef HAVE_X_WINDOWS
213 x_bitmap_mask (FRAME_PTR f, int id)
215 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
217 #endif
219 /* Allocate a new bitmap record. Returns index of new record. */
221 static int
222 x_allocate_bitmap_record (FRAME_PTR f)
224 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
225 int i;
227 if (dpyinfo->bitmaps == NULL)
229 dpyinfo->bitmaps_size = 10;
230 dpyinfo->bitmaps
231 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
232 dpyinfo->bitmaps_last = 1;
233 return 1;
236 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
237 return ++dpyinfo->bitmaps_last;
239 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
240 if (dpyinfo->bitmaps[i].refcount == 0)
241 return i + 1;
243 dpyinfo->bitmaps_size *= 2;
244 dpyinfo->bitmaps
245 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
246 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
247 return ++dpyinfo->bitmaps_last;
250 /* Add one reference to the reference count of the bitmap with id ID. */
252 void
253 x_reference_bitmap (FRAME_PTR f, int id)
255 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
258 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
261 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
263 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
264 int id;
266 #ifdef HAVE_X_WINDOWS
267 Pixmap bitmap;
268 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
269 bits, width, height);
270 if (! bitmap)
271 return -1;
272 #endif /* HAVE_X_WINDOWS */
274 #ifdef HAVE_NTGUI
275 Pixmap bitmap;
276 bitmap = CreateBitmap (width, height,
277 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
278 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
279 bits);
280 if (! bitmap)
281 return -1;
282 #endif /* HAVE_NTGUI */
284 #ifdef HAVE_NS
285 void *bitmap = ns_image_from_XBM (bits, width, height);
286 if (!bitmap)
287 return -1;
288 #endif
290 id = x_allocate_bitmap_record (f);
292 #ifdef HAVE_NS
293 dpyinfo->bitmaps[id - 1].img = bitmap;
294 dpyinfo->bitmaps[id - 1].depth = 1;
295 #endif
297 dpyinfo->bitmaps[id - 1].file = NULL;
298 dpyinfo->bitmaps[id - 1].height = height;
299 dpyinfo->bitmaps[id - 1].width = width;
300 dpyinfo->bitmaps[id - 1].refcount = 1;
302 #ifdef HAVE_X_WINDOWS
303 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
304 dpyinfo->bitmaps[id - 1].have_mask = 0;
305 dpyinfo->bitmaps[id - 1].depth = 1;
306 #endif /* HAVE_X_WINDOWS */
308 #ifdef HAVE_NTGUI
309 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
310 dpyinfo->bitmaps[id - 1].hinst = NULL;
311 dpyinfo->bitmaps[id - 1].depth = 1;
312 #endif /* HAVE_NTGUI */
314 return id;
317 /* Create bitmap from file FILE for frame F. */
320 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
322 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
324 #ifdef HAVE_NTGUI
325 return -1; /* W32_TODO : bitmap support */
326 #endif /* HAVE_NTGUI */
328 #ifdef HAVE_NS
329 int id;
330 void *bitmap = ns_image_from_file (file);
332 if (!bitmap)
333 return -1;
336 id = x_allocate_bitmap_record (f);
337 dpyinfo->bitmaps[id - 1].img = bitmap;
338 dpyinfo->bitmaps[id - 1].refcount = 1;
339 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
340 dpyinfo->bitmaps[id - 1].depth = 1;
341 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
342 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
343 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
344 return id;
345 #endif
347 #ifdef HAVE_X_WINDOWS
348 unsigned int width, height;
349 Pixmap bitmap;
350 int xhot, yhot, result, id;
351 Lisp_Object found;
352 int fd;
353 char *filename;
355 /* Look for an existing bitmap with the same name. */
356 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
358 if (dpyinfo->bitmaps[id].refcount
359 && dpyinfo->bitmaps[id].file
360 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
362 ++dpyinfo->bitmaps[id].refcount;
363 return id + 1;
367 /* Search bitmap-file-path for the file, if appropriate. */
368 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
369 if (fd < 0)
370 return -1;
371 emacs_close (fd);
373 filename = (char *) SDATA (found);
375 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
376 filename, &width, &height, &bitmap, &xhot, &yhot);
377 if (result != BitmapSuccess)
378 return -1;
380 id = x_allocate_bitmap_record (f);
381 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
382 dpyinfo->bitmaps[id - 1].have_mask = 0;
383 dpyinfo->bitmaps[id - 1].refcount = 1;
384 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
385 dpyinfo->bitmaps[id - 1].depth = 1;
386 dpyinfo->bitmaps[id - 1].height = height;
387 dpyinfo->bitmaps[id - 1].width = width;
388 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
390 return id;
391 #endif /* HAVE_X_WINDOWS */
394 /* Free bitmap B. */
396 static void
397 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
399 #ifdef HAVE_X_WINDOWS
400 XFreePixmap (dpyinfo->display, bm->pixmap);
401 if (bm->have_mask)
402 XFreePixmap (dpyinfo->display, bm->mask);
403 #endif /* HAVE_X_WINDOWS */
405 #ifdef HAVE_NTGUI
406 DeleteObject (bm->pixmap);
407 #endif /* HAVE_NTGUI */
409 #ifdef HAVE_NS
410 ns_release_object (bm->img);
411 #endif
413 if (bm->file)
415 xfree (bm->file);
416 bm->file = NULL;
420 /* Remove reference to bitmap with id number ID. */
422 void
423 x_destroy_bitmap (FRAME_PTR f, int id)
425 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
427 if (id > 0)
429 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
431 if (--bm->refcount == 0)
433 BLOCK_INPUT;
434 free_bitmap_record (dpyinfo, bm);
435 UNBLOCK_INPUT;
440 /* Free all the bitmaps for the display specified by DPYINFO. */
442 void
443 x_destroy_all_bitmaps (Display_Info *dpyinfo)
445 int i;
446 Bitmap_Record *bm = dpyinfo->bitmaps;
448 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
449 if (bm->refcount > 0)
450 free_bitmap_record (dpyinfo, bm);
452 dpyinfo->bitmaps_last = 0;
456 #ifdef HAVE_X_WINDOWS
458 /* Useful functions defined in the section
459 `Image type independent image structures' below. */
461 static unsigned long four_corners_best (XImagePtr ximg,
462 int *corners,
463 unsigned long width,
464 unsigned long height);
466 static int x_create_x_image_and_pixmap (struct frame *f, int width, int height,
467 int depth, XImagePtr *ximg,
468 Pixmap *pixmap);
470 static void x_destroy_x_image (XImagePtr ximg);
473 /* Create a mask of a bitmap. Note is this not a perfect mask.
474 It's nicer with some borders in this context */
477 x_create_bitmap_mask (struct frame *f, int id)
479 Pixmap pixmap, mask;
480 XImagePtr ximg, mask_img;
481 unsigned long width, height;
482 int result;
483 unsigned long bg;
484 unsigned long x, y, xp, xm, yp, ym;
485 GC gc;
487 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
489 if (!(id > 0))
490 return -1;
492 pixmap = x_bitmap_pixmap (f, id);
493 width = x_bitmap_width (f, id);
494 height = x_bitmap_height (f, id);
496 BLOCK_INPUT;
497 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
498 ~0, ZPixmap);
500 if (!ximg)
502 UNBLOCK_INPUT;
503 return -1;
506 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
508 UNBLOCK_INPUT;
509 if (!result)
511 XDestroyImage (ximg);
512 return -1;
515 bg = four_corners_best (ximg, NULL, width, height);
517 for (y = 0; y < ximg->height; ++y)
519 for (x = 0; x < ximg->width; ++x)
521 xp = x != ximg->width - 1 ? x + 1 : 0;
522 xm = x != 0 ? x - 1 : ximg->width - 1;
523 yp = y != ximg->height - 1 ? y + 1 : 0;
524 ym = y != 0 ? y - 1 : ximg->height - 1;
525 if (XGetPixel (ximg, x, y) == bg
526 && XGetPixel (ximg, x, yp) == bg
527 && XGetPixel (ximg, x, ym) == bg
528 && XGetPixel (ximg, xp, y) == bg
529 && XGetPixel (ximg, xp, yp) == bg
530 && XGetPixel (ximg, xp, ym) == bg
531 && XGetPixel (ximg, xm, y) == bg
532 && XGetPixel (ximg, xm, yp) == bg
533 && XGetPixel (ximg, xm, ym) == bg)
534 XPutPixel (mask_img, x, y, 0);
535 else
536 XPutPixel (mask_img, x, y, 1);
540 xassert (interrupt_input_blocked);
541 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
542 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
543 width, height);
544 XFreeGC (FRAME_X_DISPLAY (f), gc);
546 dpyinfo->bitmaps[id - 1].have_mask = 1;
547 dpyinfo->bitmaps[id - 1].mask = mask;
549 XDestroyImage (ximg);
550 x_destroy_x_image (mask_img);
552 return 0;
555 #endif /* HAVE_X_WINDOWS */
558 /***********************************************************************
559 Image types
560 ***********************************************************************/
562 /* Value is the number of elements of vector VECTOR. */
564 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
566 /* List of supported image types. Use define_image_type to add new
567 types. Use lookup_image_type to find a type for a given symbol. */
569 static struct image_type *image_types;
571 /* A list of symbols, one for each supported image type. */
573 Lisp_Object Vimage_types;
575 /* Cache for delayed-loading image types. */
577 static Lisp_Object Vimage_type_cache;
579 /* The symbol `xbm' which is used as the type symbol for XBM images. */
581 Lisp_Object Qxbm;
583 /* Keywords. */
585 Lisp_Object QCascent, QCmargin, QCrelief, Qcount, Qextension_data;
586 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
587 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry, QCcrop, QCrotation;
589 /* Other symbols. */
591 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
593 /* Time in seconds after which images should be removed from the cache
594 if not displayed. */
596 Lisp_Object Vimage_cache_eviction_delay;
598 /* Function prototypes. */
600 static Lisp_Object define_image_type (struct image_type *type, int loaded);
601 static struct image_type *lookup_image_type (Lisp_Object symbol);
602 static void image_error (const char *format, Lisp_Object, Lisp_Object);
603 static void x_laplace (struct frame *, struct image *);
604 static void x_emboss (struct frame *, struct image *);
605 static int x_build_heuristic_mask (struct frame *, struct image *,
606 Lisp_Object);
608 #define CACHE_IMAGE_TYPE(type, status) \
609 do { Vimage_type_cache = Fcons (Fcons (type, status), Vimage_type_cache); } while (0)
611 #define ADD_IMAGE_TYPE(type) \
612 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
614 /* Define a new image type from TYPE. This adds a copy of TYPE to
615 image_types and caches the loading status of TYPE. */
617 static Lisp_Object
618 define_image_type (struct image_type *type, int loaded)
620 Lisp_Object success;
622 if (!loaded)
623 success = Qnil;
624 else
626 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
627 The initialized data segment is read-only. */
628 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
629 memcpy (p, type, sizeof *p);
630 p->next = image_types;
631 image_types = p;
632 success = Qt;
635 CACHE_IMAGE_TYPE (*type->type, success);
636 return success;
640 /* Look up image type SYMBOL, and return a pointer to its image_type
641 structure. Value is null if SYMBOL is not a known image type. */
643 static INLINE struct image_type *
644 lookup_image_type (Lisp_Object symbol)
646 struct image_type *type;
648 /* We must initialize the image-type if it hasn't been already. */
649 if (NILP (Finit_image_library (symbol, Vdynamic_library_alist)))
650 return 0; /* unimplemented */
652 for (type = image_types; type; type = type->next)
653 if (EQ (symbol, *type->type))
654 break;
656 return type;
660 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
661 valid image specification is a list whose car is the symbol
662 `image', and whose rest is a property list. The property list must
663 contain a value for key `:type'. That value must be the name of a
664 supported image type. The rest of the property list depends on the
665 image type. */
668 valid_image_p (Lisp_Object object)
670 int valid_p = 0;
672 if (IMAGEP (object))
674 Lisp_Object tem;
676 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
677 if (EQ (XCAR (tem), QCtype))
679 tem = XCDR (tem);
680 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
682 struct image_type *type;
683 type = lookup_image_type (XCAR (tem));
684 if (type)
685 valid_p = type->valid_p (object);
688 break;
692 return valid_p;
696 /* Log error message with format string FORMAT and argument ARG.
697 Signaling an error, e.g. when an image cannot be loaded, is not a
698 good idea because this would interrupt redisplay, and the error
699 message display would lead to another redisplay. This function
700 therefore simply displays a message. */
702 static void
703 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
705 add_to_log (format, arg1, arg2);
710 /***********************************************************************
711 Image specifications
712 ***********************************************************************/
714 enum image_value_type
716 IMAGE_DONT_CHECK_VALUE_TYPE,
717 IMAGE_STRING_VALUE,
718 IMAGE_STRING_OR_NIL_VALUE,
719 IMAGE_SYMBOL_VALUE,
720 IMAGE_POSITIVE_INTEGER_VALUE,
721 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
722 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
723 IMAGE_ASCENT_VALUE,
724 IMAGE_INTEGER_VALUE,
725 IMAGE_FUNCTION_VALUE,
726 IMAGE_NUMBER_VALUE,
727 IMAGE_BOOL_VALUE
730 /* Structure used when parsing image specifications. */
732 struct image_keyword
734 /* Name of keyword. */
735 const char *name;
737 /* The type of value allowed. */
738 enum image_value_type type;
740 /* Non-zero means key must be present. */
741 int mandatory_p;
743 /* Used to recognize duplicate keywords in a property list. */
744 int count;
746 /* The value that was found. */
747 Lisp_Object value;
751 static int parse_image_spec (Lisp_Object, struct image_keyword *,
752 int, Lisp_Object);
753 static Lisp_Object image_spec_value (Lisp_Object, Lisp_Object, int *);
756 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
757 has the format (image KEYWORD VALUE ...). One of the keyword/
758 value pairs must be `:type TYPE'. KEYWORDS is a vector of
759 image_keywords structures of size NKEYWORDS describing other
760 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
762 static int
763 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
764 int nkeywords, Lisp_Object type)
766 int i;
767 Lisp_Object plist;
769 if (!IMAGEP (spec))
770 return 0;
772 plist = XCDR (spec);
773 while (CONSP (plist))
775 Lisp_Object key, value;
777 /* First element of a pair must be a symbol. */
778 key = XCAR (plist);
779 plist = XCDR (plist);
780 if (!SYMBOLP (key))
781 return 0;
783 /* There must follow a value. */
784 if (!CONSP (plist))
785 return 0;
786 value = XCAR (plist);
787 plist = XCDR (plist);
789 /* Find key in KEYWORDS. Error if not found. */
790 for (i = 0; i < nkeywords; ++i)
791 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
792 break;
794 if (i == nkeywords)
795 continue;
797 /* Record that we recognized the keyword. If a keywords
798 was found more than once, it's an error. */
799 keywords[i].value = value;
800 ++keywords[i].count;
802 if (keywords[i].count > 1)
803 return 0;
805 /* Check type of value against allowed type. */
806 switch (keywords[i].type)
808 case IMAGE_STRING_VALUE:
809 if (!STRINGP (value))
810 return 0;
811 break;
813 case IMAGE_STRING_OR_NIL_VALUE:
814 if (!STRINGP (value) && !NILP (value))
815 return 0;
816 break;
818 case IMAGE_SYMBOL_VALUE:
819 if (!SYMBOLP (value))
820 return 0;
821 break;
823 case IMAGE_POSITIVE_INTEGER_VALUE:
824 if (!INTEGERP (value) || XINT (value) <= 0)
825 return 0;
826 break;
828 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
829 if (INTEGERP (value) && XINT (value) >= 0)
830 break;
831 if (CONSP (value)
832 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
833 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
834 break;
835 return 0;
837 case IMAGE_ASCENT_VALUE:
838 if (SYMBOLP (value) && EQ (value, Qcenter))
839 break;
840 else if (INTEGERP (value)
841 && XINT (value) >= 0
842 && XINT (value) <= 100)
843 break;
844 return 0;
846 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
847 if (!INTEGERP (value) || XINT (value) < 0)
848 return 0;
849 break;
851 case IMAGE_DONT_CHECK_VALUE_TYPE:
852 break;
854 case IMAGE_FUNCTION_VALUE:
855 value = indirect_function (value);
856 if (SUBRP (value)
857 || COMPILEDP (value)
858 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
859 break;
860 return 0;
862 case IMAGE_NUMBER_VALUE:
863 if (!INTEGERP (value) && !FLOATP (value))
864 return 0;
865 break;
867 case IMAGE_INTEGER_VALUE:
868 if (!INTEGERP (value))
869 return 0;
870 break;
872 case IMAGE_BOOL_VALUE:
873 if (!NILP (value) && !EQ (value, Qt))
874 return 0;
875 break;
877 default:
878 abort ();
879 break;
882 if (EQ (key, QCtype) && !EQ (type, value))
883 return 0;
886 /* Check that all mandatory fields are present. */
887 for (i = 0; i < nkeywords; ++i)
888 if (keywords[i].mandatory_p && keywords[i].count == 0)
889 return 0;
891 return NILP (plist);
895 /* Return the value of KEY in image specification SPEC. Value is nil
896 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
897 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
899 static Lisp_Object
900 image_spec_value (Lisp_Object spec, Lisp_Object key, int *found)
902 Lisp_Object tail;
904 xassert (valid_image_p (spec));
906 for (tail = XCDR (spec);
907 CONSP (tail) && CONSP (XCDR (tail));
908 tail = XCDR (XCDR (tail)))
910 if (EQ (XCAR (tail), key))
912 if (found)
913 *found = 1;
914 return XCAR (XCDR (tail));
918 if (found)
919 *found = 0;
920 return Qnil;
924 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
925 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
926 PIXELS non-nil means return the size in pixels, otherwise return the
927 size in canonical character units.
928 FRAME is the frame on which the image will be displayed. FRAME nil
929 or omitted means use the selected frame. */)
930 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
932 Lisp_Object size;
934 size = Qnil;
935 if (valid_image_p (spec))
937 struct frame *f = check_x_frame (frame);
938 int id = lookup_image (f, spec);
939 struct image *img = IMAGE_FROM_ID (f, id);
940 int width = img->width + 2 * img->hmargin;
941 int height = img->height + 2 * img->vmargin;
943 if (NILP (pixels))
944 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
945 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
946 else
947 size = Fcons (make_number (width), make_number (height));
949 else
950 error ("Invalid image specification");
952 return size;
956 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
957 doc: /* Return t if image SPEC has a mask bitmap.
958 FRAME is the frame on which the image will be displayed. FRAME nil
959 or omitted means use the selected frame. */)
960 (Lisp_Object spec, Lisp_Object frame)
962 Lisp_Object mask;
964 mask = Qnil;
965 if (valid_image_p (spec))
967 struct frame *f = check_x_frame (frame);
968 int id = lookup_image (f, spec);
969 struct image *img = IMAGE_FROM_ID (f, id);
970 if (img->mask)
971 mask = Qt;
973 else
974 error ("Invalid image specification");
976 return mask;
979 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
980 doc: /* Return metadata for image SPEC.
981 FRAME is the frame on which the image will be displayed. FRAME nil
982 or omitted means use the selected frame. */)
983 (Lisp_Object spec, Lisp_Object frame)
985 Lisp_Object ext;
987 ext = Qnil;
988 if (valid_image_p (spec))
990 struct frame *f = check_x_frame (frame);
991 int id = lookup_image (f, spec);
992 struct image *img = IMAGE_FROM_ID (f, id);
993 ext = img->data.lisp_val;
996 return ext;
1000 /***********************************************************************
1001 Image type independent image structures
1002 ***********************************************************************/
1004 static struct image *make_image (Lisp_Object spec, unsigned hash);
1005 static void free_image (struct frame *f, struct image *img);
1006 static int check_image_size (struct frame *f, int width, int height);
1008 #define MAX_IMAGE_SIZE 6.0
1009 Lisp_Object Vmax_image_size;
1011 /* Allocate and return a new image structure for image specification
1012 SPEC. SPEC has a hash value of HASH. */
1014 static struct image *
1015 make_image (Lisp_Object spec, unsigned int hash)
1017 struct image *img = (struct image *) xmalloc (sizeof *img);
1018 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
1020 xassert (valid_image_p (spec));
1021 memset (img, 0, sizeof *img);
1022 img->dependencies = NILP (file) ? Qnil : list1 (file);
1023 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1024 xassert (img->type != NULL);
1025 img->spec = spec;
1026 img->data.lisp_val = Qnil;
1027 img->ascent = DEFAULT_IMAGE_ASCENT;
1028 img->hash = hash;
1029 img->corners[BOT_CORNER] = -1; /* Full image */
1030 return img;
1034 /* Free image IMG which was used on frame F, including its resources. */
1036 static void
1037 free_image (struct frame *f, struct image *img)
1039 if (img)
1041 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1043 /* Remove IMG from the hash table of its cache. */
1044 if (img->prev)
1045 img->prev->next = img->next;
1046 else
1047 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1049 if (img->next)
1050 img->next->prev = img->prev;
1052 c->images[img->id] = NULL;
1054 /* Free resources, then free IMG. */
1055 img->type->free (f, img);
1056 xfree (img);
1060 /* Return 1 if the given widths and heights are valid for display;
1061 otherwise, return 0. */
1064 check_image_size (struct frame *f, int width, int height)
1066 int w, h;
1068 if (width <= 0 || height <= 0)
1069 return 0;
1071 if (INTEGERP (Vmax_image_size))
1072 w = h = XINT (Vmax_image_size);
1073 else if (FLOATP (Vmax_image_size))
1075 if (f != NULL)
1077 w = FRAME_PIXEL_WIDTH (f);
1078 h = FRAME_PIXEL_HEIGHT (f);
1080 else
1081 w = h = 1024; /* Arbitrary size for unknown frame. */
1082 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1083 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1085 else
1086 return 1;
1088 return (width <= w && height <= h);
1091 /* Prepare image IMG for display on frame F. Must be called before
1092 drawing an image. */
1094 void
1095 prepare_image_for_display (struct frame *f, struct image *img)
1097 EMACS_TIME t;
1099 /* We're about to display IMG, so set its timestamp to `now'. */
1100 EMACS_GET_TIME (t);
1101 img->timestamp = EMACS_SECS (t);
1103 /* If IMG doesn't have a pixmap yet, load it now, using the image
1104 type dependent loader function. */
1105 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1106 img->load_failed_p = img->type->load (f, img) == 0;
1111 /* Value is the number of pixels for the ascent of image IMG when
1112 drawn in face FACE. */
1115 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1117 int height;
1118 int ascent;
1120 if (slice->height == img->height)
1121 height = img->height + img->vmargin;
1122 else if (slice->y == 0)
1123 height = slice->height + img->vmargin;
1124 else
1125 height = slice->height;
1127 if (img->ascent == CENTERED_IMAGE_ASCENT)
1129 if (face->font)
1131 #ifdef HAVE_NTGUI
1132 /* W32 specific version. Why?. ++kfs */
1133 ascent = height / 2 - (FONT_DESCENT (face->font)
1134 - FONT_BASE (face->font)) / 2;
1135 #else
1136 /* This expression is arranged so that if the image can't be
1137 exactly centered, it will be moved slightly up. This is
1138 because a typical font is `top-heavy' (due to the presence
1139 uppercase letters), so the image placement should err towards
1140 being top-heavy too. It also just generally looks better. */
1141 ascent = (height + FONT_BASE(face->font)
1142 - FONT_DESCENT(face->font) + 1) / 2;
1143 #endif /* HAVE_NTGUI */
1145 else
1146 ascent = height / 2;
1148 else
1149 ascent = (int) (height * img->ascent / 100.0);
1151 return ascent;
1155 /* Image background colors. */
1157 /* Find the "best" corner color of a bitmap.
1158 On W32, XIMG is assumed to a device context with the bitmap selected. */
1160 static RGB_PIXEL_COLOR
1161 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1162 unsigned long width, unsigned long height)
1164 RGB_PIXEL_COLOR corner_pixels[4], best;
1165 int i, best_count;
1167 if (corners && corners[BOT_CORNER] >= 0)
1169 /* Get the colors at the corner_pixels of ximg. */
1170 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1171 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1172 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1173 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1175 else
1177 /* Get the colors at the corner_pixels of ximg. */
1178 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1179 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1180 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1181 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1183 /* Choose the most frequently found color as background. */
1184 for (i = best_count = 0; i < 4; ++i)
1186 int j, n;
1188 for (j = n = 0; j < 4; ++j)
1189 if (corner_pixels[i] == corner_pixels[j])
1190 ++n;
1192 if (n > best_count)
1193 best = corner_pixels[i], best_count = n;
1196 return best;
1199 /* Portability macros */
1201 #ifdef HAVE_NTGUI
1203 #define Destroy_Image(img_dc, prev) \
1204 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1206 #define Free_Pixmap(display, pixmap) \
1207 DeleteObject (pixmap)
1209 #elif defined (HAVE_NS)
1211 #define Destroy_Image(ximg, dummy) \
1212 ns_release_object (ximg)
1214 #define Free_Pixmap(display, pixmap) \
1215 ns_release_object (pixmap)
1217 #else
1219 #define Destroy_Image(ximg, dummy) \
1220 XDestroyImage (ximg)
1222 #define Free_Pixmap(display, pixmap) \
1223 XFreePixmap (display, pixmap)
1225 #endif /* !HAVE_NTGUI && !HAVE_NS */
1228 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1229 it is guessed heuristically. If non-zero, XIMG is an existing
1230 XImage object (or device context with the image selected on W32) to
1231 use for the heuristic. */
1233 RGB_PIXEL_COLOR
1234 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1236 if (! img->background_valid)
1237 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1239 int free_ximg = !ximg;
1240 #ifdef HAVE_NTGUI
1241 HGDIOBJ prev;
1242 #endif /* HAVE_NTGUI */
1244 if (free_ximg)
1246 #ifndef HAVE_NTGUI
1247 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1248 0, 0, img->width, img->height, ~0, ZPixmap);
1249 #else
1250 HDC frame_dc = get_frame_dc (f);
1251 ximg = CreateCompatibleDC (frame_dc);
1252 release_frame_dc (f, frame_dc);
1253 prev = SelectObject (ximg, img->pixmap);
1254 #endif /* !HAVE_NTGUI */
1257 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1259 if (free_ximg)
1260 Destroy_Image (ximg, prev);
1262 img->background_valid = 1;
1265 return img->background;
1268 /* Return the `background_transparent' field of IMG. If IMG doesn't
1269 have one yet, it is guessed heuristically. If non-zero, MASK is an
1270 existing XImage object to use for the heuristic. */
1273 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1275 if (! img->background_transparent_valid)
1276 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1278 if (img->mask)
1280 int free_mask = !mask;
1281 #ifdef HAVE_NTGUI
1282 HGDIOBJ prev;
1283 #endif /* HAVE_NTGUI */
1285 if (free_mask)
1287 #ifndef HAVE_NTGUI
1288 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1289 0, 0, img->width, img->height, ~0, ZPixmap);
1290 #else
1291 HDC frame_dc = get_frame_dc (f);
1292 mask = CreateCompatibleDC (frame_dc);
1293 release_frame_dc (f, frame_dc);
1294 prev = SelectObject (mask, img->mask);
1295 #endif /* HAVE_NTGUI */
1298 img->background_transparent
1299 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1301 if (free_mask)
1302 Destroy_Image (mask, prev);
1304 else
1305 img->background_transparent = 0;
1307 img->background_transparent_valid = 1;
1310 return img->background_transparent;
1314 /***********************************************************************
1315 Helper functions for X image types
1316 ***********************************************************************/
1318 static void x_clear_image_1 (struct frame *, struct image *, int,
1319 int, int);
1320 static void x_clear_image (struct frame *f, struct image *img);
1321 static unsigned long x_alloc_image_color (struct frame *f,
1322 struct image *img,
1323 Lisp_Object color_name,
1324 unsigned long dflt);
1327 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1328 free the pixmap if any. MASK_P non-zero means clear the mask
1329 pixmap if any. COLORS_P non-zero means free colors allocated for
1330 the image, if any. */
1332 static void
1333 x_clear_image_1 (struct frame *f, struct image *img, int pixmap_p, int mask_p,
1334 int colors_p)
1336 if (pixmap_p && img->pixmap)
1338 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1339 img->pixmap = NO_PIXMAP;
1340 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1341 img->background_valid = 0;
1344 if (mask_p && img->mask)
1346 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1347 img->mask = NO_PIXMAP;
1348 img->background_transparent_valid = 0;
1351 if (colors_p && img->ncolors)
1353 /* W32_TODO: color table support. */
1354 #ifdef HAVE_X_WINDOWS
1355 x_free_colors (f, img->colors, img->ncolors);
1356 #endif /* HAVE_X_WINDOWS */
1357 xfree (img->colors);
1358 img->colors = NULL;
1359 img->ncolors = 0;
1364 /* Free X resources of image IMG which is used on frame F. */
1366 static void
1367 x_clear_image (struct frame *f, struct image *img)
1369 BLOCK_INPUT;
1370 x_clear_image_1 (f, img, 1, 1, 1);
1371 UNBLOCK_INPUT;
1375 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1376 cannot be allocated, use DFLT. Add a newly allocated color to
1377 IMG->colors, so that it can be freed again. Value is the pixel
1378 color. */
1380 static unsigned long
1381 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1382 unsigned long dflt)
1384 XColor color;
1385 unsigned long result;
1387 xassert (STRINGP (color_name));
1389 if (x_defined_color (f, SDATA (color_name), &color, 1))
1391 /* This isn't called frequently so we get away with simply
1392 reallocating the color vector to the needed size, here. */
1393 ++img->ncolors;
1394 img->colors =
1395 (unsigned long *) xrealloc (img->colors,
1396 img->ncolors * sizeof *img->colors);
1397 img->colors[img->ncolors - 1] = color.pixel;
1398 result = color.pixel;
1400 else
1401 result = dflt;
1403 return result;
1408 /***********************************************************************
1409 Image Cache
1410 ***********************************************************************/
1412 static struct image *search_image_cache (struct frame *, Lisp_Object, unsigned);
1413 static void cache_image (struct frame *f, struct image *img);
1414 static void postprocess_image (struct frame *, struct image *);
1416 /* Return a new, initialized image cache that is allocated from the
1417 heap. Call free_image_cache to free an image cache. */
1419 struct image_cache *
1420 make_image_cache (void)
1422 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1423 int size;
1425 memset (c, 0, sizeof *c);
1426 c->size = 50;
1427 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1428 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1429 c->buckets = (struct image **) xmalloc (size);
1430 memset (c->buckets, 0, size);
1431 return c;
1435 /* Find an image matching SPEC in the cache, and return it. If no
1436 image is found, return NULL. */
1437 static struct image *
1438 search_image_cache (struct frame *f, Lisp_Object spec, unsigned int hash)
1440 struct image *img;
1441 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1442 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1444 if (!c) return NULL;
1446 /* If the image spec does not specify a background color, the cached
1447 image must have the same background color as the current frame.
1448 The foreground color must also match, for the sake of monochrome
1449 images.
1451 In fact, we could ignore the foreground color matching condition
1452 for color images, or if the image spec specifies :foreground;
1453 similarly we could ignore the background color matching condition
1454 for formats that don't use transparency (such as jpeg), or if the
1455 image spec specifies :background. However, the extra memory
1456 usage is probably negligible in practice, so we don't bother. */
1458 for (img = c->buckets[i]; img; img = img->next)
1459 if (img->hash == hash
1460 && !NILP (Fequal (img->spec, spec))
1461 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1462 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1463 break;
1464 return img;
1468 /* Search frame F for an image with spec SPEC, and free it. */
1470 static void
1471 uncache_image (struct frame *f, Lisp_Object spec)
1473 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1474 if (img)
1476 free_image (f, img);
1477 /* As display glyphs may still be referring to the image ID, we
1478 must garbage the frame (Bug#6426). */
1479 SET_FRAME_GARBAGED (f);
1484 /* Free image cache of frame F. Be aware that X frames share images
1485 caches. */
1487 void
1488 free_image_cache (struct frame *f)
1490 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1491 if (c)
1493 int i;
1495 /* Cache should not be referenced by any frame when freed. */
1496 xassert (c->refcount == 0);
1498 for (i = 0; i < c->used; ++i)
1499 free_image (f, c->images[i]);
1500 xfree (c->images);
1501 xfree (c->buckets);
1502 xfree (c);
1503 FRAME_IMAGE_CACHE (f) = NULL;
1508 /* Clear image cache of frame F. FILTER=t means free all images.
1509 FILTER=nil means clear only images that haven't been
1510 displayed for some time.
1511 Else, only free the images which have FILTER in their `dependencies'.
1512 Should be called from time to time to reduce the number of loaded images.
1513 If image-cache-eviction-delay is non-nil, this frees images in the cache
1514 which weren't displayed for at least that many seconds. */
1516 void
1517 clear_image_cache (struct frame *f, Lisp_Object filter)
1519 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1521 if (c)
1523 int i, nfreed = 0;
1525 /* Block input so that we won't be interrupted by a SIGIO
1526 while being in an inconsistent state. */
1527 BLOCK_INPUT;
1529 if (!NILP (filter))
1531 /* Filter image cache. */
1532 for (i = 0; i < c->used; ++i)
1534 struct image *img = c->images[i];
1535 if (img && (EQ (Qt, filter)
1536 || !NILP (Fmember (filter, img->dependencies))))
1538 free_image (f, img);
1539 ++nfreed;
1543 else if (INTEGERP (Vimage_cache_eviction_delay))
1545 /* Free cache based on timestamp. */
1546 EMACS_TIME t;
1547 unsigned long old;
1548 int delay, nimages = 0;
1550 for (i = 0; i < c->used; ++i)
1551 if (c->images[i])
1552 nimages++;
1554 /* If the number of cached images has grown unusually large,
1555 decrease the cache eviction delay (Bug#6230). */
1556 delay = XFASTINT (Vimage_cache_eviction_delay);
1557 if (nimages > 40)
1558 delay = max (1, 1600 * delay / (nimages*nimages));
1560 EMACS_GET_TIME (t);
1561 old = EMACS_SECS (t) - delay;
1563 for (i = 0; i < c->used; ++i)
1565 struct image *img = c->images[i];
1566 if (img && img->timestamp < old)
1568 free_image (f, img);
1569 ++nfreed;
1574 /* We may be clearing the image cache because, for example,
1575 Emacs was iconified for a longer period of time. In that
1576 case, current matrices may still contain references to
1577 images freed above. So, clear these matrices. */
1578 if (nfreed)
1580 Lisp_Object tail, frame;
1582 FOR_EACH_FRAME (tail, frame)
1584 struct frame *f = XFRAME (frame);
1585 if (FRAME_IMAGE_CACHE (f) == c)
1586 clear_current_matrices (f);
1589 ++windows_or_buffers_changed;
1592 UNBLOCK_INPUT;
1596 void
1597 clear_image_caches (Lisp_Object filter)
1599 /* FIXME: We want to do
1600 * struct terminal *t;
1601 * for (t = terminal_list; t; t = t->next_terminal)
1602 * clear_image_cache (t, filter); */
1603 Lisp_Object tail, frame;
1604 FOR_EACH_FRAME (tail, frame)
1605 if (FRAME_WINDOW_P (XFRAME (frame)))
1606 clear_image_cache (XFRAME (frame), filter);
1609 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1610 0, 1, 0,
1611 doc: /* Clear the image cache.
1612 FILTER nil or a frame means clear all images in the selected frame.
1613 FILTER t means clear the image caches of all frames.
1614 Anything else, means only clear those images which refer to FILTER,
1615 which is then usually a filename. */)
1616 (Lisp_Object filter)
1618 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1619 clear_image_caches (filter);
1620 else
1621 clear_image_cache (check_x_frame (filter), Qt);
1623 return Qnil;
1627 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1628 1, 2, 0,
1629 doc: /* Fush the image with specification SPEC on frame FRAME.
1630 This removes the image from the Emacs image cache. If SPEC specifies
1631 an image file, the next redisplay of this image will read from the
1632 current contents of that file.
1634 FRAME nil or omitted means use the selected frame.
1635 FRAME t means refresh the image on all frames. */)
1636 (Lisp_Object spec, Lisp_Object frame)
1638 if (!valid_image_p (spec))
1639 error ("Invalid image specification");
1641 if (EQ (frame, Qt))
1643 Lisp_Object tail;
1644 FOR_EACH_FRAME (tail, frame)
1646 struct frame *f = XFRAME (frame);
1647 if (FRAME_WINDOW_P (f))
1648 uncache_image (f, spec);
1651 else
1652 uncache_image (check_x_frame (frame), spec);
1654 return Qnil;
1658 /* Compute masks and transform image IMG on frame F, as specified
1659 by the image's specification, */
1661 static void
1662 postprocess_image (struct frame *f, struct image *img)
1664 /* Manipulation of the image's mask. */
1665 if (img->pixmap)
1667 Lisp_Object conversion, spec;
1668 Lisp_Object mask;
1670 spec = img->spec;
1672 /* `:heuristic-mask t'
1673 `:mask heuristic'
1674 means build a mask heuristically.
1675 `:heuristic-mask (R G B)'
1676 `:mask (heuristic (R G B))'
1677 means build a mask from color (R G B) in the
1678 image.
1679 `:mask nil'
1680 means remove a mask, if any. */
1682 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1683 if (!NILP (mask))
1684 x_build_heuristic_mask (f, img, mask);
1685 else
1687 int found_p;
1689 mask = image_spec_value (spec, QCmask, &found_p);
1691 if (EQ (mask, Qheuristic))
1692 x_build_heuristic_mask (f, img, Qt);
1693 else if (CONSP (mask)
1694 && EQ (XCAR (mask), Qheuristic))
1696 if (CONSP (XCDR (mask)))
1697 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1698 else
1699 x_build_heuristic_mask (f, img, XCDR (mask));
1701 else if (NILP (mask) && found_p && img->mask)
1703 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1704 img->mask = NO_PIXMAP;
1709 /* Should we apply an image transformation algorithm? */
1710 conversion = image_spec_value (spec, QCconversion, NULL);
1711 if (EQ (conversion, Qdisabled))
1712 x_disable_image (f, img);
1713 else if (EQ (conversion, Qlaplace))
1714 x_laplace (f, img);
1715 else if (EQ (conversion, Qemboss))
1716 x_emboss (f, img);
1717 else if (CONSP (conversion)
1718 && EQ (XCAR (conversion), Qedge_detection))
1720 Lisp_Object tem;
1721 tem = XCDR (conversion);
1722 if (CONSP (tem))
1723 x_edge_detection (f, img,
1724 Fplist_get (tem, QCmatrix),
1725 Fplist_get (tem, QCcolor_adjustment));
1731 /* Return the id of image with Lisp specification SPEC on frame F.
1732 SPEC must be a valid Lisp image specification (see valid_image_p). */
1735 lookup_image (struct frame *f, Lisp_Object spec)
1737 struct image_cache *c;
1738 struct image *img;
1739 unsigned hash;
1740 EMACS_TIME now;
1742 /* F must be a window-system frame, and SPEC must be a valid image
1743 specification. */
1744 xassert (FRAME_WINDOW_P (f));
1745 xassert (valid_image_p (spec));
1747 c = FRAME_IMAGE_CACHE (f);
1749 /* Look up SPEC in the hash table of the image cache. */
1750 hash = sxhash (spec, 0);
1751 img = search_image_cache (f, spec, hash);
1752 if (img && img->load_failed_p)
1754 free_image (f, img);
1755 img = NULL;
1758 /* If not found, create a new image and cache it. */
1759 if (img == NULL)
1761 BLOCK_INPUT;
1762 img = make_image (spec, hash);
1763 cache_image (f, img);
1764 img->load_failed_p = img->type->load (f, img) == 0;
1765 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1766 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1768 /* If we can't load the image, and we don't have a width and
1769 height, use some arbitrary width and height so that we can
1770 draw a rectangle for it. */
1771 if (img->load_failed_p)
1773 Lisp_Object value;
1775 value = image_spec_value (spec, QCwidth, NULL);
1776 img->width = (INTEGERP (value)
1777 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1778 value = image_spec_value (spec, QCheight, NULL);
1779 img->height = (INTEGERP (value)
1780 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1782 else
1784 /* Handle image type independent image attributes
1785 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1786 `:background COLOR'. */
1787 Lisp_Object ascent, margin, relief, bg;
1789 ascent = image_spec_value (spec, QCascent, NULL);
1790 if (INTEGERP (ascent))
1791 img->ascent = XFASTINT (ascent);
1792 else if (EQ (ascent, Qcenter))
1793 img->ascent = CENTERED_IMAGE_ASCENT;
1795 margin = image_spec_value (spec, QCmargin, NULL);
1796 if (INTEGERP (margin) && XINT (margin) >= 0)
1797 img->vmargin = img->hmargin = XFASTINT (margin);
1798 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1799 && INTEGERP (XCDR (margin)))
1801 if (XINT (XCAR (margin)) > 0)
1802 img->hmargin = XFASTINT (XCAR (margin));
1803 if (XINT (XCDR (margin)) > 0)
1804 img->vmargin = XFASTINT (XCDR (margin));
1807 relief = image_spec_value (spec, QCrelief, NULL);
1808 if (INTEGERP (relief))
1810 img->relief = XINT (relief);
1811 img->hmargin += eabs (img->relief);
1812 img->vmargin += eabs (img->relief);
1815 if (! img->background_valid)
1817 bg = image_spec_value (img->spec, QCbackground, NULL);
1818 if (!NILP (bg))
1820 img->background
1821 = x_alloc_image_color (f, img, bg,
1822 FRAME_BACKGROUND_PIXEL (f));
1823 img->background_valid = 1;
1827 /* Do image transformations and compute masks, unless we
1828 don't have the image yet. */
1829 if (!EQ (*img->type->type, Qpostscript))
1830 postprocess_image (f, img);
1833 UNBLOCK_INPUT;
1836 /* We're using IMG, so set its timestamp to `now'. */
1837 EMACS_GET_TIME (now);
1838 img->timestamp = EMACS_SECS (now);
1840 /* Value is the image id. */
1841 return img->id;
1845 /* Cache image IMG in the image cache of frame F. */
1847 static void
1848 cache_image (struct frame *f, struct image *img)
1850 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1851 int i;
1853 /* Find a free slot in c->images. */
1854 for (i = 0; i < c->used; ++i)
1855 if (c->images[i] == NULL)
1856 break;
1858 /* If no free slot found, maybe enlarge c->images. */
1859 if (i == c->used && c->used == c->size)
1861 c->size *= 2;
1862 c->images = (struct image **) xrealloc (c->images,
1863 c->size * sizeof *c->images);
1866 /* Add IMG to c->images, and assign IMG an id. */
1867 c->images[i] = img;
1868 img->id = i;
1869 if (i == c->used)
1870 ++c->used;
1872 /* Add IMG to the cache's hash table. */
1873 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1874 img->next = c->buckets[i];
1875 if (img->next)
1876 img->next->prev = img;
1877 img->prev = NULL;
1878 c->buckets[i] = img;
1882 /* Call FN on every image in the image cache of frame F. Used to mark
1883 Lisp Objects in the image cache. */
1885 /* Mark Lisp objects in image IMG. */
1887 static void
1888 mark_image (struct image *img)
1890 mark_object (img->spec);
1891 mark_object (img->dependencies);
1893 if (!NILP (img->data.lisp_val))
1894 mark_object (img->data.lisp_val);
1898 void
1899 mark_image_cache (struct image_cache *c)
1901 if (c)
1903 int i;
1904 for (i = 0; i < c->used; ++i)
1905 if (c->images[i])
1906 mark_image (c->images[i]);
1912 /***********************************************************************
1913 X / NS / W32 support code
1914 ***********************************************************************/
1916 #ifdef HAVE_NTGUI
1918 /* Macro for defining functions that will be loaded from image DLLs. */
1919 #define DEF_IMGLIB_FN(func,args) int (FAR CDECL *fn_##func)args
1921 /* Macro for loading those image functions from the library. */
1922 #define LOAD_IMGLIB_FN(lib,func) { \
1923 fn_##func = (void *) GetProcAddress (lib, #func); \
1924 if (!fn_##func) return 0; \
1927 /* Load a DLL implementing an image type.
1928 The argument LIBRARIES is usually the variable
1929 `dynamic-library-alist', which associates a symbol, identifying
1930 an external DLL library, to a list of possible filenames.
1931 The function returns NULL if no library could be loaded for
1932 the given symbol, or if the library was previously loaded;
1933 else the handle of the DLL. */
1934 static HMODULE
1935 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
1937 HMODULE library = NULL;
1939 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
1941 Lisp_Object dlls = Fassq (type, libraries);
1943 if (CONSP (dlls))
1944 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
1946 CHECK_STRING_CAR (dlls);
1947 if (library = LoadLibrary (SDATA (XCAR (dlls))))
1948 break;
1952 return library;
1955 #endif /* HAVE_NTGUI */
1957 static int x_create_x_image_and_pixmap (struct frame *, int, int, int,
1958 XImagePtr *, Pixmap *);
1959 static void x_destroy_x_image (XImagePtr);
1960 static void x_put_x_image (struct frame *, XImagePtr, Pixmap, int, int);
1963 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1964 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1965 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1966 via xmalloc. Print error messages via image_error if an error
1967 occurs. Value is non-zero if successful.
1969 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1970 should indicate the bit depth of the image. */
1972 static int
1973 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1974 XImagePtr *ximg, Pixmap *pixmap)
1976 #ifdef HAVE_X_WINDOWS
1977 Display *display = FRAME_X_DISPLAY (f);
1978 Window window = FRAME_X_WINDOW (f);
1979 Screen *screen = FRAME_X_SCREEN (f);
1981 xassert (interrupt_input_blocked);
1983 if (depth <= 0)
1984 depth = DefaultDepthOfScreen (screen);
1985 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1986 depth, ZPixmap, 0, NULL, width, height,
1987 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1988 if (*ximg == NULL)
1990 image_error ("Unable to allocate X image", Qnil, Qnil);
1991 return 0;
1994 /* Allocate image raster. */
1995 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
1997 /* Allocate a pixmap of the same size. */
1998 *pixmap = XCreatePixmap (display, window, width, height, depth);
1999 if (*pixmap == NO_PIXMAP)
2001 x_destroy_x_image (*ximg);
2002 *ximg = NULL;
2003 image_error ("Unable to create X pixmap", Qnil, Qnil);
2004 return 0;
2007 return 1;
2008 #endif /* HAVE_X_WINDOWS */
2010 #ifdef HAVE_NTGUI
2012 BITMAPINFOHEADER *header;
2013 HDC hdc;
2014 int scanline_width_bits;
2015 int remainder;
2016 int palette_colors = 0;
2018 if (depth == 0)
2019 depth = 24;
2021 if (depth != 1 && depth != 4 && depth != 8
2022 && depth != 16 && depth != 24 && depth != 32)
2024 image_error ("Invalid image bit depth specified", Qnil, Qnil);
2025 return 0;
2028 scanline_width_bits = width * depth;
2029 remainder = scanline_width_bits % 32;
2031 if (remainder)
2032 scanline_width_bits += 32 - remainder;
2034 /* Bitmaps with a depth less than 16 need a palette. */
2035 /* BITMAPINFO structure already contains the first RGBQUAD. */
2036 if (depth < 16)
2037 palette_colors = 1 << depth - 1;
2039 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2040 if (*ximg == NULL)
2042 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
2043 return 0;
2046 header = &(*ximg)->info.bmiHeader;
2047 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2048 header->biSize = sizeof (*header);
2049 header->biWidth = width;
2050 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2051 header->biPlanes = 1;
2052 header->biBitCount = depth;
2053 header->biCompression = BI_RGB;
2054 header->biClrUsed = palette_colors;
2056 /* TODO: fill in palette. */
2057 if (depth == 1)
2059 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2060 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2061 (*ximg)->info.bmiColors[0].rgbRed = 0;
2062 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2063 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2064 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2065 (*ximg)->info.bmiColors[1].rgbRed = 255;
2066 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2069 hdc = get_frame_dc (f);
2071 /* Create a DIBSection and raster array for the bitmap,
2072 and store its handle in *pixmap. */
2073 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2074 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2075 /* casting avoids a GCC warning */
2076 (void **)&((*ximg)->data), NULL, 0);
2078 /* Realize display palette and garbage all frames. */
2079 release_frame_dc (f, hdc);
2081 if (*pixmap == NULL)
2083 DWORD err = GetLastError ();
2084 Lisp_Object errcode;
2085 /* All system errors are < 10000, so the following is safe. */
2086 XSETINT (errcode, (int) err);
2087 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2088 x_destroy_x_image (*ximg);
2089 return 0;
2092 return 1;
2094 #endif /* HAVE_NTGUI */
2096 #ifdef HAVE_NS
2097 *pixmap = ns_image_for_XPM (width, height, depth);
2098 if (*pixmap == 0)
2100 *ximg = NULL;
2101 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2102 return 0;
2104 *ximg = *pixmap;
2105 return 1;
2106 #endif
2110 /* Destroy XImage XIMG. Free XIMG->data. */
2112 static void
2113 x_destroy_x_image (XImagePtr ximg)
2115 xassert (interrupt_input_blocked);
2116 if (ximg)
2118 #ifdef HAVE_X_WINDOWS
2119 xfree (ximg->data);
2120 ximg->data = NULL;
2121 XDestroyImage (ximg);
2122 #endif /* HAVE_X_WINDOWS */
2123 #ifdef HAVE_NTGUI
2124 /* Data will be freed by DestroyObject. */
2125 ximg->data = NULL;
2126 xfree (ximg);
2127 #endif /* HAVE_NTGUI */
2128 #ifdef HAVE_NS
2129 ns_release_object (ximg);
2130 #endif /* HAVE_NS */
2135 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2136 are width and height of both the image and pixmap. */
2138 static void
2139 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2141 #ifdef HAVE_X_WINDOWS
2142 GC gc;
2144 xassert (interrupt_input_blocked);
2145 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2146 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2147 XFreeGC (FRAME_X_DISPLAY (f), gc);
2148 #endif /* HAVE_X_WINDOWS */
2150 #ifdef HAVE_NTGUI
2151 #if 0 /* I don't think this is necessary looking at where it is used. */
2152 HDC hdc = get_frame_dc (f);
2153 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2154 release_frame_dc (f, hdc);
2155 #endif
2156 #endif /* HAVE_NTGUI */
2158 #ifdef HAVE_NS
2159 xassert (ximg == pixmap);
2160 ns_retain_object (ximg);
2161 #endif
2165 /***********************************************************************
2166 File Handling
2167 ***********************************************************************/
2169 static unsigned char *slurp_file (char *, int *);
2172 /* Find image file FILE. Look in data-directory/images, then
2173 x-bitmap-file-path. Value is the encoded full name of the file
2174 found, or nil if not found. */
2176 Lisp_Object
2177 x_find_image_file (Lisp_Object file)
2179 Lisp_Object file_found, search_path;
2180 int fd;
2182 /* TODO I think this should use something like image-load-path
2183 instead. Unfortunately, that can contain non-string elements. */
2184 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2185 Vdata_directory),
2186 Vx_bitmap_file_path);
2188 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2189 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2191 if (fd == -1)
2192 file_found = Qnil;
2193 else
2195 file_found = ENCODE_FILE (file_found);
2196 close (fd);
2199 return file_found;
2203 /* Read FILE into memory. Value is a pointer to a buffer allocated
2204 with xmalloc holding FILE's contents. Value is null if an error
2205 occurred. *SIZE is set to the size of the file. */
2207 static unsigned char *
2208 slurp_file (char *file, int *size)
2210 FILE *fp = NULL;
2211 unsigned char *buf = NULL;
2212 struct stat st;
2214 if (stat (file, &st) == 0
2215 && (fp = fopen (file, "rb")) != NULL
2216 && (buf = (unsigned char *) xmalloc (st.st_size),
2217 fread (buf, 1, st.st_size, fp) == st.st_size))
2219 *size = st.st_size;
2220 fclose (fp);
2222 else
2224 if (fp)
2225 fclose (fp);
2226 if (buf)
2228 xfree (buf);
2229 buf = NULL;
2233 return buf;
2238 /***********************************************************************
2239 XBM images
2240 ***********************************************************************/
2242 static int xbm_scan (unsigned char **, unsigned char *, char *, int *);
2243 static int xbm_load (struct frame *f, struct image *img);
2244 static int xbm_load_image (struct frame *f, struct image *img,
2245 unsigned char *, unsigned char *);
2246 static int xbm_image_p (Lisp_Object object);
2247 static int xbm_read_bitmap_data (struct frame *f,
2248 unsigned char *, unsigned char *,
2249 int *, int *, unsigned char **, int);
2250 static int xbm_file_p (Lisp_Object);
2253 /* Indices of image specification fields in xbm_format, below. */
2255 enum xbm_keyword_index
2257 XBM_TYPE,
2258 XBM_FILE,
2259 XBM_WIDTH,
2260 XBM_HEIGHT,
2261 XBM_DATA,
2262 XBM_FOREGROUND,
2263 XBM_BACKGROUND,
2264 XBM_ASCENT,
2265 XBM_MARGIN,
2266 XBM_RELIEF,
2267 XBM_ALGORITHM,
2268 XBM_HEURISTIC_MASK,
2269 XBM_MASK,
2270 XBM_LAST
2273 /* Vector of image_keyword structures describing the format
2274 of valid XBM image specifications. */
2276 static const struct image_keyword xbm_format[XBM_LAST] =
2278 {":type", IMAGE_SYMBOL_VALUE, 1},
2279 {":file", IMAGE_STRING_VALUE, 0},
2280 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2281 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2282 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2283 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2284 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2285 {":ascent", IMAGE_ASCENT_VALUE, 0},
2286 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2287 {":relief", IMAGE_INTEGER_VALUE, 0},
2288 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2289 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2290 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2293 /* Structure describing the image type XBM. */
2295 static struct image_type xbm_type =
2297 &Qxbm,
2298 xbm_image_p,
2299 xbm_load,
2300 x_clear_image,
2301 NULL
2304 /* Tokens returned from xbm_scan. */
2306 enum xbm_token
2308 XBM_TK_IDENT = 256,
2309 XBM_TK_NUMBER
2313 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2314 A valid specification is a list starting with the symbol `image'
2315 The rest of the list is a property list which must contain an
2316 entry `:type xbm..
2318 If the specification specifies a file to load, it must contain
2319 an entry `:file FILENAME' where FILENAME is a string.
2321 If the specification is for a bitmap loaded from memory it must
2322 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2323 WIDTH and HEIGHT are integers > 0. DATA may be:
2325 1. a string large enough to hold the bitmap data, i.e. it must
2326 have a size >= (WIDTH + 7) / 8 * HEIGHT
2328 2. a bool-vector of size >= WIDTH * HEIGHT
2330 3. a vector of strings or bool-vectors, one for each line of the
2331 bitmap.
2333 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2334 may not be specified in this case because they are defined in the
2335 XBM file.
2337 Both the file and data forms may contain the additional entries
2338 `:background COLOR' and `:foreground COLOR'. If not present,
2339 foreground and background of the frame on which the image is
2340 displayed is used. */
2342 static int
2343 xbm_image_p (Lisp_Object object)
2345 struct image_keyword kw[XBM_LAST];
2347 memcpy (kw, xbm_format, sizeof kw);
2348 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2349 return 0;
2351 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2353 if (kw[XBM_FILE].count)
2355 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2356 return 0;
2358 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2360 /* In-memory XBM file. */
2361 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2362 return 0;
2364 else
2366 Lisp_Object data;
2367 int width, height;
2369 /* Entries for `:width', `:height' and `:data' must be present. */
2370 if (!kw[XBM_WIDTH].count
2371 || !kw[XBM_HEIGHT].count
2372 || !kw[XBM_DATA].count)
2373 return 0;
2375 data = kw[XBM_DATA].value;
2376 width = XFASTINT (kw[XBM_WIDTH].value);
2377 height = XFASTINT (kw[XBM_HEIGHT].value);
2379 /* Check type of data, and width and height against contents of
2380 data. */
2381 if (VECTORP (data))
2383 int i;
2385 /* Number of elements of the vector must be >= height. */
2386 if (XVECTOR (data)->size < height)
2387 return 0;
2389 /* Each string or bool-vector in data must be large enough
2390 for one line of the image. */
2391 for (i = 0; i < height; ++i)
2393 Lisp_Object elt = XVECTOR (data)->contents[i];
2395 if (STRINGP (elt))
2397 if (SCHARS (elt)
2398 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2399 return 0;
2401 else if (BOOL_VECTOR_P (elt))
2403 if (XBOOL_VECTOR (elt)->size < width)
2404 return 0;
2406 else
2407 return 0;
2410 else if (STRINGP (data))
2412 if (SCHARS (data)
2413 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2414 return 0;
2416 else if (BOOL_VECTOR_P (data))
2418 if (XBOOL_VECTOR (data)->size < width * height)
2419 return 0;
2421 else
2422 return 0;
2425 return 1;
2429 /* Scan a bitmap file. FP is the stream to read from. Value is
2430 either an enumerator from enum xbm_token, or a character for a
2431 single-character token, or 0 at end of file. If scanning an
2432 identifier, store the lexeme of the identifier in SVAL. If
2433 scanning a number, store its value in *IVAL. */
2435 static int
2436 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2438 unsigned int c;
2440 loop:
2442 /* Skip white space. */
2443 while (*s < end && (c = *(*s)++, isspace (c)))
2446 if (*s >= end)
2447 c = 0;
2448 else if (isdigit (c))
2450 int value = 0, digit;
2452 if (c == '0' && *s < end)
2454 c = *(*s)++;
2455 if (c == 'x' || c == 'X')
2457 while (*s < end)
2459 c = *(*s)++;
2460 if (isdigit (c))
2461 digit = c - '0';
2462 else if (c >= 'a' && c <= 'f')
2463 digit = c - 'a' + 10;
2464 else if (c >= 'A' && c <= 'F')
2465 digit = c - 'A' + 10;
2466 else
2467 break;
2468 value = 16 * value + digit;
2471 else if (isdigit (c))
2473 value = c - '0';
2474 while (*s < end
2475 && (c = *(*s)++, isdigit (c)))
2476 value = 8 * value + c - '0';
2479 else
2481 value = c - '0';
2482 while (*s < end
2483 && (c = *(*s)++, isdigit (c)))
2484 value = 10 * value + c - '0';
2487 if (*s < end)
2488 *s = *s - 1;
2489 *ival = value;
2490 c = XBM_TK_NUMBER;
2492 else if (isalpha (c) || c == '_')
2494 *sval++ = c;
2495 while (*s < end
2496 && (c = *(*s)++, (isalnum (c) || c == '_')))
2497 *sval++ = c;
2498 *sval = 0;
2499 if (*s < end)
2500 *s = *s - 1;
2501 c = XBM_TK_IDENT;
2503 else if (c == '/' && **s == '*')
2505 /* C-style comment. */
2506 ++*s;
2507 while (**s && (**s != '*' || *(*s + 1) != '/'))
2508 ++*s;
2509 if (**s)
2511 *s += 2;
2512 goto loop;
2516 return c;
2519 #ifdef HAVE_NTGUI
2521 /* Create a Windows bitmap from X bitmap data. */
2522 static HBITMAP
2523 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2525 static unsigned char swap_nibble[16]
2526 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2527 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2528 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2529 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2530 int i, j, w1, w2;
2531 unsigned char *bits, *p;
2532 HBITMAP bmp;
2534 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2535 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2536 bits = (unsigned char *) alloca (height * w2);
2537 memset (bits, 0, height * w2);
2538 for (i = 0; i < height; i++)
2540 p = bits + i*w2;
2541 for (j = 0; j < w1; j++)
2543 /* Bitswap XBM bytes to match how Windows does things. */
2544 unsigned char c = *data++;
2545 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2546 | (swap_nibble[(c>>4) & 0xf]));
2549 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2551 return bmp;
2554 static void
2555 convert_mono_to_color_image (struct frame *f, struct image *img,
2556 COLORREF foreground, COLORREF background)
2558 HDC hdc, old_img_dc, new_img_dc;
2559 HGDIOBJ old_prev, new_prev;
2560 HBITMAP new_pixmap;
2562 hdc = get_frame_dc (f);
2563 old_img_dc = CreateCompatibleDC (hdc);
2564 new_img_dc = CreateCompatibleDC (hdc);
2565 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2566 release_frame_dc (f, hdc);
2567 old_prev = SelectObject (old_img_dc, img->pixmap);
2568 new_prev = SelectObject (new_img_dc, new_pixmap);
2569 /* Windows convention for mono bitmaps is black = background,
2570 white = foreground. */
2571 SetTextColor (new_img_dc, background);
2572 SetBkColor (new_img_dc, foreground);
2574 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2575 0, 0, SRCCOPY);
2577 SelectObject (old_img_dc, old_prev);
2578 SelectObject (new_img_dc, new_prev);
2579 DeleteDC (old_img_dc);
2580 DeleteDC (new_img_dc);
2581 DeleteObject (img->pixmap);
2582 if (new_pixmap == 0)
2583 fprintf (stderr, "Failed to convert image to color.\n");
2584 else
2585 img->pixmap = new_pixmap;
2588 #define XBM_BIT_SHUFFLE(b) (~(b))
2590 #else
2592 #define XBM_BIT_SHUFFLE(b) (b)
2594 #endif /* HAVE_NTGUI */
2597 static void
2598 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2599 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2600 int non_default_colors)
2602 #ifdef HAVE_NTGUI
2603 img->pixmap
2604 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2606 /* If colors were specified, transfer the bitmap to a color one. */
2607 if (non_default_colors)
2608 convert_mono_to_color_image (f, img, fg, bg);
2610 #elif defined (HAVE_NS)
2611 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2613 #else
2614 img->pixmap
2615 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2616 FRAME_X_WINDOW (f),
2617 data,
2618 img->width, img->height,
2619 fg, bg,
2620 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2621 #endif /* !HAVE_NTGUI && !HAVE_NS */
2626 /* Replacement for XReadBitmapFileData which isn't available under old
2627 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2628 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2629 the image. Return in *DATA the bitmap data allocated with xmalloc.
2630 Value is non-zero if successful. DATA null means just test if
2631 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR
2632 is non-zero, inhibit the call to image_error when the image size is
2633 invalid (the bitmap remains unread). */
2635 static int
2636 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2637 int *width, int *height, unsigned char **data,
2638 int inhibit_image_error)
2640 unsigned char *s = contents;
2641 char buffer[BUFSIZ];
2642 int padding_p = 0;
2643 int v10 = 0;
2644 int bytes_per_line, i, nbytes;
2645 unsigned char *p;
2646 int value;
2647 int LA1;
2649 #define match() \
2650 LA1 = xbm_scan (&s, end, buffer, &value)
2652 #define expect(TOKEN) \
2653 if (LA1 != (TOKEN)) \
2654 goto failure; \
2655 else \
2656 match ()
2658 #define expect_ident(IDENT) \
2659 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2660 match (); \
2661 else \
2662 goto failure
2664 *width = *height = -1;
2665 if (data)
2666 *data = NULL;
2667 LA1 = xbm_scan (&s, end, buffer, &value);
2669 /* Parse defines for width, height and hot-spots. */
2670 while (LA1 == '#')
2672 match ();
2673 expect_ident ("define");
2674 expect (XBM_TK_IDENT);
2676 if (LA1 == XBM_TK_NUMBER)
2678 char *p = strrchr (buffer, '_');
2679 p = p ? p + 1 : buffer;
2680 if (strcmp (p, "width") == 0)
2681 *width = value;
2682 else if (strcmp (p, "height") == 0)
2683 *height = value;
2685 expect (XBM_TK_NUMBER);
2688 if (!check_image_size (f, *width, *height))
2690 if (!inhibit_image_error)
2691 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2692 goto failure;
2694 else if (data == NULL)
2695 goto success;
2697 /* Parse bits. Must start with `static'. */
2698 expect_ident ("static");
2699 if (LA1 == XBM_TK_IDENT)
2701 if (strcmp (buffer, "unsigned") == 0)
2703 match ();
2704 expect_ident ("char");
2706 else if (strcmp (buffer, "short") == 0)
2708 match ();
2709 v10 = 1;
2710 if (*width % 16 && *width % 16 < 9)
2711 padding_p = 1;
2713 else if (strcmp (buffer, "char") == 0)
2714 match ();
2715 else
2716 goto failure;
2718 else
2719 goto failure;
2721 expect (XBM_TK_IDENT);
2722 expect ('[');
2723 expect (']');
2724 expect ('=');
2725 expect ('{');
2727 bytes_per_line = (*width + 7) / 8 + padding_p;
2728 nbytes = bytes_per_line * *height;
2729 p = *data = (unsigned char *) xmalloc (nbytes);
2731 if (v10)
2733 for (i = 0; i < nbytes; i += 2)
2735 int val = value;
2736 expect (XBM_TK_NUMBER);
2738 *p++ = XBM_BIT_SHUFFLE (val);
2739 if (!padding_p || ((i + 2) % bytes_per_line))
2740 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2742 if (LA1 == ',' || LA1 == '}')
2743 match ();
2744 else
2745 goto failure;
2748 else
2750 for (i = 0; i < nbytes; ++i)
2752 int val = value;
2753 expect (XBM_TK_NUMBER);
2755 *p++ = XBM_BIT_SHUFFLE (val);
2757 if (LA1 == ',' || LA1 == '}')
2758 match ();
2759 else
2760 goto failure;
2764 success:
2765 return 1;
2767 failure:
2769 if (data && *data)
2771 xfree (*data);
2772 *data = NULL;
2774 return 0;
2776 #undef match
2777 #undef expect
2778 #undef expect_ident
2782 /* Load XBM image IMG which will be displayed on frame F from buffer
2783 CONTENTS. END is the end of the buffer. Value is non-zero if
2784 successful. */
2786 static int
2787 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2788 unsigned char *end)
2790 int rc;
2791 unsigned char *data;
2792 int success_p = 0;
2794 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2795 &data, 0);
2796 if (rc)
2798 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2799 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2800 int non_default_colors = 0;
2801 Lisp_Object value;
2803 xassert (img->width > 0 && img->height > 0);
2805 /* Get foreground and background colors, maybe allocate colors. */
2806 value = image_spec_value (img->spec, QCforeground, NULL);
2807 if (!NILP (value))
2809 foreground = x_alloc_image_color (f, img, value, foreground);
2810 non_default_colors = 1;
2812 value = image_spec_value (img->spec, QCbackground, NULL);
2813 if (!NILP (value))
2815 background = x_alloc_image_color (f, img, value, background);
2816 img->background = background;
2817 img->background_valid = 1;
2818 non_default_colors = 1;
2821 Create_Pixmap_From_Bitmap_Data (f, img, data,
2822 foreground, background,
2823 non_default_colors);
2824 xfree (data);
2826 if (img->pixmap == NO_PIXMAP)
2828 x_clear_image (f, img);
2829 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2831 else
2832 success_p = 1;
2834 else
2835 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2837 return success_p;
2841 /* Value is non-zero if DATA looks like an in-memory XBM file. */
2843 static int
2844 xbm_file_p (Lisp_Object data)
2846 int w, h;
2847 return (STRINGP (data)
2848 && xbm_read_bitmap_data (NULL, SDATA (data),
2849 (SDATA (data) + SBYTES (data)),
2850 &w, &h, NULL, 1));
2854 /* Fill image IMG which is used on frame F with pixmap data. Value is
2855 non-zero if successful. */
2857 static int
2858 xbm_load (struct frame *f, struct image *img)
2860 int success_p = 0;
2861 Lisp_Object file_name;
2863 xassert (xbm_image_p (img->spec));
2865 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2866 file_name = image_spec_value (img->spec, QCfile, NULL);
2867 if (STRINGP (file_name))
2869 Lisp_Object file;
2870 unsigned char *contents;
2871 int size;
2873 file = x_find_image_file (file_name);
2874 if (!STRINGP (file))
2876 image_error ("Cannot find image file `%s'", file_name, Qnil);
2877 return 0;
2880 contents = slurp_file (SDATA (file), &size);
2881 if (contents == NULL)
2883 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2884 return 0;
2887 success_p = xbm_load_image (f, img, contents, contents + size);
2889 else
2891 struct image_keyword fmt[XBM_LAST];
2892 Lisp_Object data;
2893 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2894 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2895 int non_default_colors = 0;
2896 char *bits;
2897 int parsed_p;
2898 int in_memory_file_p = 0;
2900 /* See if data looks like an in-memory XBM file. */
2901 data = image_spec_value (img->spec, QCdata, NULL);
2902 in_memory_file_p = xbm_file_p (data);
2904 /* Parse the image specification. */
2905 memcpy (fmt, xbm_format, sizeof fmt);
2906 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2907 xassert (parsed_p);
2909 /* Get specified width, and height. */
2910 if (!in_memory_file_p)
2912 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2913 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2914 xassert (img->width > 0 && img->height > 0);
2917 /* Get foreground and background colors, maybe allocate colors. */
2918 if (fmt[XBM_FOREGROUND].count
2919 && STRINGP (fmt[XBM_FOREGROUND].value))
2921 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2922 foreground);
2923 non_default_colors = 1;
2926 if (fmt[XBM_BACKGROUND].count
2927 && STRINGP (fmt[XBM_BACKGROUND].value))
2929 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2930 background);
2931 non_default_colors = 1;
2934 if (in_memory_file_p)
2935 success_p = xbm_load_image (f, img, SDATA (data),
2936 (SDATA (data)
2937 + SBYTES (data)));
2938 else
2940 if (VECTORP (data))
2942 int i;
2943 char *p;
2944 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2946 p = bits = (char *) alloca (nbytes * img->height);
2947 for (i = 0; i < img->height; ++i, p += nbytes)
2949 Lisp_Object line = XVECTOR (data)->contents[i];
2950 if (STRINGP (line))
2951 memcpy (p, SDATA (line), nbytes);
2952 else
2953 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
2956 else if (STRINGP (data))
2957 bits = SDATA (data);
2958 else
2959 bits = XBOOL_VECTOR (data)->data;
2961 #ifdef WINDOWSNT
2963 char *invertedBits;
2964 int nbytes, i;
2965 /* Windows mono bitmaps are reversed compared with X. */
2966 invertedBits = bits;
2967 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
2968 * img->height;
2969 bits = (char *) alloca (nbytes);
2970 for (i = 0; i < nbytes; i++)
2971 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
2973 #endif
2974 /* Create the pixmap. */
2976 Create_Pixmap_From_Bitmap_Data (f, img, bits,
2977 foreground, background,
2978 non_default_colors);
2979 if (img->pixmap)
2980 success_p = 1;
2981 else
2983 image_error ("Unable to create pixmap for XBM image `%s'",
2984 img->spec, Qnil);
2985 x_clear_image (f, img);
2990 return success_p;
2995 /***********************************************************************
2996 XPM images
2997 ***********************************************************************/
2999 #if defined (HAVE_XPM) || defined (HAVE_NS)
3001 static int xpm_image_p (Lisp_Object object);
3002 static int xpm_load (struct frame *f, struct image *img);
3003 static int xpm_valid_color_symbols_p (Lisp_Object);
3005 #endif /* HAVE_XPM || HAVE_NS */
3007 #ifdef HAVE_XPM
3008 #ifdef HAVE_NTGUI
3009 /* Indicate to xpm.h that we don't have Xlib. */
3010 #define FOR_MSW
3011 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3012 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3013 #define XColor xpm_XColor
3014 #define XImage xpm_XImage
3015 #define Display xpm_Display
3016 #define PIXEL_ALREADY_TYPEDEFED
3017 #include "X11/xpm.h"
3018 #undef FOR_MSW
3019 #undef XColor
3020 #undef XImage
3021 #undef Display
3022 #undef PIXEL_ALREADY_TYPEDEFED
3023 #else
3024 #include "X11/xpm.h"
3025 #endif /* HAVE_NTGUI */
3026 #endif /* HAVE_XPM */
3028 #if defined (HAVE_XPM) || defined (HAVE_NS)
3029 /* The symbol `xpm' identifying XPM-format images. */
3031 Lisp_Object Qxpm;
3033 /* Indices of image specification fields in xpm_format, below. */
3035 enum xpm_keyword_index
3037 XPM_TYPE,
3038 XPM_FILE,
3039 XPM_DATA,
3040 XPM_ASCENT,
3041 XPM_MARGIN,
3042 XPM_RELIEF,
3043 XPM_ALGORITHM,
3044 XPM_HEURISTIC_MASK,
3045 XPM_MASK,
3046 XPM_COLOR_SYMBOLS,
3047 XPM_BACKGROUND,
3048 XPM_LAST
3051 /* Vector of image_keyword structures describing the format
3052 of valid XPM image specifications. */
3054 static const struct image_keyword xpm_format[XPM_LAST] =
3056 {":type", IMAGE_SYMBOL_VALUE, 1},
3057 {":file", IMAGE_STRING_VALUE, 0},
3058 {":data", IMAGE_STRING_VALUE, 0},
3059 {":ascent", IMAGE_ASCENT_VALUE, 0},
3060 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3061 {":relief", IMAGE_INTEGER_VALUE, 0},
3062 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3063 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3064 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3065 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3066 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3069 /* Structure describing the image type XPM. */
3071 static struct image_type xpm_type =
3073 &Qxpm,
3074 xpm_image_p,
3075 xpm_load,
3076 x_clear_image,
3077 NULL
3080 #ifdef HAVE_X_WINDOWS
3082 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3083 functions for allocating image colors. Our own functions handle
3084 color allocation failures more gracefully than the ones on the XPM
3085 lib. */
3087 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3088 #define ALLOC_XPM_COLORS
3089 #endif
3090 #endif /* HAVE_X_WINDOWS */
3092 #ifdef ALLOC_XPM_COLORS
3094 static void xpm_init_color_cache (struct frame *, XpmAttributes *);
3095 static void xpm_free_color_cache (void);
3096 static int xpm_lookup_color (struct frame *, char *, XColor *);
3097 static int xpm_color_bucket (char *);
3098 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3099 XColor *, int);
3101 /* An entry in a hash table used to cache color definitions of named
3102 colors. This cache is necessary to speed up XPM image loading in
3103 case we do color allocations ourselves. Without it, we would need
3104 a call to XParseColor per pixel in the image. */
3106 struct xpm_cached_color
3108 /* Next in collision chain. */
3109 struct xpm_cached_color *next;
3111 /* Color definition (RGB and pixel color). */
3112 XColor color;
3114 /* Color name. */
3115 char name[1];
3118 /* The hash table used for the color cache, and its bucket vector
3119 size. */
3121 #define XPM_COLOR_CACHE_BUCKETS 1001
3122 struct xpm_cached_color **xpm_color_cache;
3124 /* Initialize the color cache. */
3126 static void
3127 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3129 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3130 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3131 memset (xpm_color_cache, 0, nbytes);
3132 init_color_table ();
3134 if (attrs->valuemask & XpmColorSymbols)
3136 int i;
3137 XColor color;
3139 for (i = 0; i < attrs->numsymbols; ++i)
3140 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3141 attrs->colorsymbols[i].value, &color))
3143 color.pixel = lookup_rgb_color (f, color.red, color.green,
3144 color.blue);
3145 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3150 /* Free the color cache. */
3152 static void
3153 xpm_free_color_cache (void)
3155 struct xpm_cached_color *p, *next;
3156 int i;
3158 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3159 for (p = xpm_color_cache[i]; p; p = next)
3161 next = p->next;
3162 xfree (p);
3165 xfree (xpm_color_cache);
3166 xpm_color_cache = NULL;
3167 free_color_table ();
3170 /* Return the bucket index for color named COLOR_NAME in the color
3171 cache. */
3173 static int
3174 xpm_color_bucket (char *color_name)
3176 unsigned h = 0;
3177 char *s;
3179 for (s = color_name; *s; ++s)
3180 h = (h << 2) ^ *s;
3181 return h %= XPM_COLOR_CACHE_BUCKETS;
3185 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3186 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3187 entry added. */
3189 static struct xpm_cached_color *
3190 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3192 size_t nbytes;
3193 struct xpm_cached_color *p;
3195 if (bucket < 0)
3196 bucket = xpm_color_bucket (color_name);
3198 nbytes = sizeof *p + strlen (color_name);
3199 p = (struct xpm_cached_color *) xmalloc (nbytes);
3200 strcpy (p->name, color_name);
3201 p->color = *color;
3202 p->next = xpm_color_cache[bucket];
3203 xpm_color_cache[bucket] = p;
3204 return p;
3207 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3208 return the cached definition in *COLOR. Otherwise, make a new
3209 entry in the cache and allocate the color. Value is zero if color
3210 allocation failed. */
3212 static int
3213 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3215 struct xpm_cached_color *p;
3216 int h = xpm_color_bucket (color_name);
3218 for (p = xpm_color_cache[h]; p; p = p->next)
3219 if (strcmp (p->name, color_name) == 0)
3220 break;
3222 if (p != NULL)
3223 *color = p->color;
3224 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3225 color_name, color))
3227 color->pixel = lookup_rgb_color (f, color->red, color->green,
3228 color->blue);
3229 p = xpm_cache_color (f, color_name, color, h);
3231 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3232 with transparency, and it's useful. */
3233 else if (strcmp ("opaque", color_name) == 0)
3235 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3236 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3237 p = xpm_cache_color (f, color_name, color, h);
3240 return p != NULL;
3244 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3245 CLOSURE is a pointer to the frame on which we allocate the
3246 color. Return in *COLOR the allocated color. Value is non-zero
3247 if successful. */
3249 static int
3250 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3251 void *closure)
3253 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3257 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3258 is a pointer to the frame on which we allocate the color. Value is
3259 non-zero if successful. */
3261 static int
3262 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3264 return 1;
3267 #endif /* ALLOC_XPM_COLORS */
3270 #ifdef HAVE_NTGUI
3272 /* XPM library details. */
3274 DEF_IMGLIB_FN (XpmFreeAttributes, (XpmAttributes *));
3275 DEF_IMGLIB_FN (XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3276 xpm_XImage **, XpmAttributes *));
3277 DEF_IMGLIB_FN (XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3278 xpm_XImage **, XpmAttributes *));
3279 DEF_IMGLIB_FN (XImageFree, (xpm_XImage *));
3281 static int
3282 init_xpm_functions (Lisp_Object libraries)
3284 HMODULE library;
3286 if (!(library = w32_delayed_load (libraries, Qxpm)))
3287 return 0;
3289 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3290 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3291 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3292 LOAD_IMGLIB_FN (library, XImageFree);
3293 return 1;
3296 #endif /* HAVE_NTGUI */
3299 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3300 for XPM images. Such a list must consist of conses whose car and
3301 cdr are strings. */
3303 static int
3304 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3306 while (CONSP (color_symbols))
3308 Lisp_Object sym = XCAR (color_symbols);
3309 if (!CONSP (sym)
3310 || !STRINGP (XCAR (sym))
3311 || !STRINGP (XCDR (sym)))
3312 break;
3313 color_symbols = XCDR (color_symbols);
3316 return NILP (color_symbols);
3320 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3322 static int
3323 xpm_image_p (Lisp_Object object)
3325 struct image_keyword fmt[XPM_LAST];
3326 memcpy (fmt, xpm_format, sizeof fmt);
3327 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3328 /* Either `:file' or `:data' must be present. */
3329 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3330 /* Either no `:color-symbols' or it's a list of conses
3331 whose car and cdr are strings. */
3332 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3333 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3336 #endif /* HAVE_XPM || HAVE_NS */
3338 #if defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
3340 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3342 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3343 int id, rc;
3344 XpmAttributes attrs;
3345 Pixmap bitmap, mask;
3347 memset (&attrs, 0, sizeof attrs);
3349 attrs.visual = FRAME_X_VISUAL (f);
3350 attrs.colormap = FRAME_X_COLORMAP (f);
3351 attrs.valuemask |= XpmVisual;
3352 attrs.valuemask |= XpmColormap;
3354 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3355 bits, &bitmap, &mask, &attrs);
3356 if (rc != XpmSuccess)
3358 XpmFreeAttributes (&attrs);
3359 return -1;
3362 id = x_allocate_bitmap_record (f);
3363 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3364 dpyinfo->bitmaps[id - 1].have_mask = 1;
3365 dpyinfo->bitmaps[id - 1].mask = mask;
3366 dpyinfo->bitmaps[id - 1].file = NULL;
3367 dpyinfo->bitmaps[id - 1].height = attrs.height;
3368 dpyinfo->bitmaps[id - 1].width = attrs.width;
3369 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3370 dpyinfo->bitmaps[id - 1].refcount = 1;
3372 XpmFreeAttributes (&attrs);
3373 return id;
3375 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3377 /* Load image IMG which will be displayed on frame F. Value is
3378 non-zero if successful. */
3380 #ifdef HAVE_XPM
3382 static int
3383 xpm_load (struct frame *f, struct image *img)
3385 int rc;
3386 XpmAttributes attrs;
3387 Lisp_Object specified_file, color_symbols;
3388 #ifdef HAVE_NTGUI
3389 HDC hdc;
3390 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3391 #endif /* HAVE_NTGUI */
3393 /* Configure the XPM lib. Use the visual of frame F. Allocate
3394 close colors. Return colors allocated. */
3395 memset (&attrs, 0, sizeof attrs);
3397 #ifndef HAVE_NTGUI
3398 attrs.visual = FRAME_X_VISUAL (f);
3399 attrs.colormap = FRAME_X_COLORMAP (f);
3400 attrs.valuemask |= XpmVisual;
3401 attrs.valuemask |= XpmColormap;
3402 #endif /* HAVE_NTGUI */
3404 #ifdef ALLOC_XPM_COLORS
3405 /* Allocate colors with our own functions which handle
3406 failing color allocation more gracefully. */
3407 attrs.color_closure = f;
3408 attrs.alloc_color = xpm_alloc_color;
3409 attrs.free_colors = xpm_free_colors;
3410 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3411 #else /* not ALLOC_XPM_COLORS */
3412 /* Let the XPM lib allocate colors. */
3413 attrs.valuemask |= XpmReturnAllocPixels;
3414 #ifdef XpmAllocCloseColors
3415 attrs.alloc_close_colors = 1;
3416 attrs.valuemask |= XpmAllocCloseColors;
3417 #else /* not XpmAllocCloseColors */
3418 attrs.closeness = 600;
3419 attrs.valuemask |= XpmCloseness;
3420 #endif /* not XpmAllocCloseColors */
3421 #endif /* ALLOC_XPM_COLORS */
3423 /* If image specification contains symbolic color definitions, add
3424 these to `attrs'. */
3425 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3426 if (CONSP (color_symbols))
3428 Lisp_Object tail;
3429 XpmColorSymbol *xpm_syms;
3430 int i, size;
3432 attrs.valuemask |= XpmColorSymbols;
3434 /* Count number of symbols. */
3435 attrs.numsymbols = 0;
3436 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3437 ++attrs.numsymbols;
3439 /* Allocate an XpmColorSymbol array. */
3440 size = attrs.numsymbols * sizeof *xpm_syms;
3441 xpm_syms = (XpmColorSymbol *) alloca (size);
3442 memset (xpm_syms, 0, size);
3443 attrs.colorsymbols = xpm_syms;
3445 /* Fill the color symbol array. */
3446 for (tail = color_symbols, i = 0;
3447 CONSP (tail);
3448 ++i, tail = XCDR (tail))
3450 Lisp_Object name;
3451 Lisp_Object color;
3453 if (!CONSP (XCAR (tail)))
3455 xpm_syms[i].name = "";
3456 xpm_syms[i].value = "";
3457 continue;
3459 name = XCAR (XCAR (tail));
3460 color = XCDR (XCAR (tail));
3461 if (STRINGP (name))
3463 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3464 strcpy (xpm_syms[i].name, SDATA (name));
3466 else
3467 xpm_syms[i].name = "";
3468 if (STRINGP (color))
3470 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3471 strcpy (xpm_syms[i].value, SDATA (color));
3473 else
3474 xpm_syms[i].value = "";
3478 /* Create a pixmap for the image, either from a file, or from a
3479 string buffer containing data in the same format as an XPM file. */
3480 #ifdef ALLOC_XPM_COLORS
3481 xpm_init_color_cache (f, &attrs);
3482 #endif
3484 specified_file = image_spec_value (img->spec, QCfile, NULL);
3486 #ifdef HAVE_NTGUI
3488 HDC frame_dc = get_frame_dc (f);
3489 hdc = CreateCompatibleDC (frame_dc);
3490 release_frame_dc (f, frame_dc);
3492 #endif /* HAVE_NTGUI */
3494 if (STRINGP (specified_file))
3496 Lisp_Object file = x_find_image_file (specified_file);
3497 if (!STRINGP (file))
3499 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3500 #ifdef ALLOC_XPM_COLORS
3501 xpm_free_color_cache ();
3502 #endif
3503 return 0;
3506 #ifdef HAVE_NTGUI
3507 /* XpmReadFileToPixmap is not available in the Windows port of
3508 libxpm. But XpmReadFileToImage almost does what we want. */
3509 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3510 &xpm_image, &xpm_mask,
3511 &attrs);
3512 #else
3513 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3514 SDATA (file), &img->pixmap, &img->mask,
3515 &attrs);
3516 #endif /* HAVE_NTGUI */
3518 else
3520 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3521 if (!STRINGP (buffer))
3523 image_error ("Invalid image data `%s'", buffer, Qnil);
3524 #ifdef ALLOC_XPM_COLORS
3525 xpm_free_color_cache ();
3526 #endif
3527 return 0;
3529 #ifdef HAVE_NTGUI
3530 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3531 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3532 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3533 &xpm_image, &xpm_mask,
3534 &attrs);
3535 #else
3536 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3537 SDATA (buffer),
3538 &img->pixmap, &img->mask,
3539 &attrs);
3540 #endif /* HAVE_NTGUI */
3543 if (rc == XpmSuccess)
3545 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3546 img->colors = colors_in_color_table (&img->ncolors);
3547 #else /* not ALLOC_XPM_COLORS */
3548 int i;
3550 #ifdef HAVE_NTGUI
3551 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3552 plus some duplicate attributes. */
3553 if (xpm_image && xpm_image->bitmap)
3555 img->pixmap = xpm_image->bitmap;
3556 /* XImageFree in libXpm frees XImage struct without destroying
3557 the bitmap, which is what we want. */
3558 fn_XImageFree (xpm_image);
3560 if (xpm_mask && xpm_mask->bitmap)
3562 /* The mask appears to be inverted compared with what we expect.
3563 TODO: invert our expectations. See other places where we
3564 have to invert bits because our idea of masks is backwards. */
3565 HGDIOBJ old_obj;
3566 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3568 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3569 SelectObject (hdc, old_obj);
3571 img->mask = xpm_mask->bitmap;
3572 fn_XImageFree (xpm_mask);
3573 DeleteDC (hdc);
3576 DeleteDC (hdc);
3577 #endif /* HAVE_NTGUI */
3579 /* Remember allocated colors. */
3580 img->ncolors = attrs.nalloc_pixels;
3581 img->colors = (unsigned long *) xmalloc (img->ncolors
3582 * sizeof *img->colors);
3583 for (i = 0; i < attrs.nalloc_pixels; ++i)
3585 img->colors[i] = attrs.alloc_pixels[i];
3586 #ifdef DEBUG_X_COLORS
3587 register_color (img->colors[i]);
3588 #endif
3590 #endif /* not ALLOC_XPM_COLORS */
3592 img->width = attrs.width;
3593 img->height = attrs.height;
3594 xassert (img->width > 0 && img->height > 0);
3596 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3597 #ifdef HAVE_NTGUI
3598 fn_XpmFreeAttributes (&attrs);
3599 #else
3600 XpmFreeAttributes (&attrs);
3601 #endif /* HAVE_NTGUI */
3603 else
3605 #ifdef HAVE_NTGUI
3606 DeleteDC (hdc);
3607 #endif /* HAVE_NTGUI */
3609 switch (rc)
3611 case XpmOpenFailed:
3612 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3613 break;
3615 case XpmFileInvalid:
3616 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3617 break;
3619 case XpmNoMemory:
3620 image_error ("Out of memory (%s)", img->spec, Qnil);
3621 break;
3623 case XpmColorFailed:
3624 image_error ("Color allocation error (%s)", img->spec, Qnil);
3625 break;
3627 default:
3628 image_error ("Unknown error (%s)", img->spec, Qnil);
3629 break;
3633 #ifdef ALLOC_XPM_COLORS
3634 xpm_free_color_cache ();
3635 #endif
3636 return rc == XpmSuccess;
3639 #endif /* HAVE_XPM */
3641 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3643 /* XPM support functions for NS where libxpm is not available.
3644 Only XPM version 3 (without any extensions) is supported. */
3646 static int xpm_scan (const unsigned char **, const unsigned char *,
3647 const unsigned char **, int *);
3648 static Lisp_Object xpm_make_color_table_v
3649 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3650 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3651 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3652 int, Lisp_Object);
3653 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3654 const unsigned char *, int);
3655 static Lisp_Object xpm_make_color_table_h
3656 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3657 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3658 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3659 int, Lisp_Object);
3660 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3661 const unsigned char *, int);
3662 static int xpm_str_to_color_key (const char *);
3663 static int xpm_load_image (struct frame *, struct image *,
3664 const unsigned char *, const unsigned char *);
3666 /* Tokens returned from xpm_scan. */
3668 enum xpm_token
3670 XPM_TK_IDENT = 256,
3671 XPM_TK_STRING,
3672 XPM_TK_EOF
3675 /* Scan an XPM data and return a character (< 256) or a token defined
3676 by enum xpm_token above. *S and END are the start (inclusive) and
3677 the end (exclusive) addresses of the data, respectively. Advance
3678 *S while scanning. If token is either XPM_TK_IDENT or
3679 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3680 length of the corresponding token, respectively. */
3682 static int
3683 xpm_scan (const unsigned char **s,
3684 const unsigned char *end,
3685 const unsigned char **beg,
3686 int *len)
3688 int c;
3690 while (*s < end)
3692 /* Skip white-space. */
3693 while (*s < end && (c = *(*s)++, isspace (c)))
3696 /* gnus-pointer.xpm uses '-' in its identifier.
3697 sb-dir-plus.xpm uses '+' in its identifier. */
3698 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3700 *beg = *s - 1;
3701 while (*s < end
3702 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3703 ++*s;
3704 *len = *s - *beg;
3705 return XPM_TK_IDENT;
3707 else if (c == '"')
3709 *beg = *s;
3710 while (*s < end && **s != '"')
3711 ++*s;
3712 *len = *s - *beg;
3713 if (*s < end)
3714 ++*s;
3715 return XPM_TK_STRING;
3717 else if (c == '/')
3719 if (*s < end && **s == '*')
3721 /* C-style comment. */
3722 ++*s;
3725 while (*s < end && *(*s)++ != '*')
3728 while (*s < end && **s != '/');
3729 if (*s < end)
3730 ++*s;
3732 else
3733 return c;
3735 else
3736 return c;
3739 return XPM_TK_EOF;
3742 /* Functions for color table lookup in XPM data. A key is a string
3743 specifying the color of each pixel in XPM data. A value is either
3744 an integer that specifies a pixel color, Qt that specifies
3745 transparency, or Qnil for the unspecified color. If the length of
3746 the key string is one, a vector is used as a table. Otherwise, a
3747 hash table is used. */
3749 static Lisp_Object
3750 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3751 const unsigned char *,
3752 int,
3753 Lisp_Object),
3754 Lisp_Object (**get_func) (Lisp_Object,
3755 const unsigned char *,
3756 int))
3758 *put_func = xpm_put_color_table_v;
3759 *get_func = xpm_get_color_table_v;
3760 return Fmake_vector (make_number (256), Qnil);
3763 static void
3764 xpm_put_color_table_v (Lisp_Object color_table,
3765 const unsigned char *chars_start,
3766 int chars_len,
3767 Lisp_Object color)
3769 XVECTOR (color_table)->contents[*chars_start] = color;
3772 static Lisp_Object
3773 xpm_get_color_table_v (Lisp_Object color_table,
3774 const unsigned char *chars_start,
3775 int chars_len)
3777 return XVECTOR (color_table)->contents[*chars_start];
3780 static Lisp_Object
3781 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3782 const unsigned char *,
3783 int,
3784 Lisp_Object),
3785 Lisp_Object (**get_func) (Lisp_Object,
3786 const unsigned char *,
3787 int))
3789 *put_func = xpm_put_color_table_h;
3790 *get_func = xpm_get_color_table_h;
3791 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
3792 make_float (DEFAULT_REHASH_SIZE),
3793 make_float (DEFAULT_REHASH_THRESHOLD),
3794 Qnil, Qnil, Qnil);
3797 static void
3798 xpm_put_color_table_h (Lisp_Object color_table,
3799 const unsigned char *chars_start,
3800 int chars_len,
3801 Lisp_Object color)
3803 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3804 unsigned hash_code;
3805 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3807 hash_lookup (table, chars, &hash_code);
3808 hash_put (table, chars, color, hash_code);
3811 static Lisp_Object
3812 xpm_get_color_table_h (Lisp_Object color_table,
3813 const unsigned char *chars_start,
3814 int chars_len)
3816 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3817 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
3818 NULL);
3820 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3823 enum xpm_color_key {
3824 XPM_COLOR_KEY_S,
3825 XPM_COLOR_KEY_M,
3826 XPM_COLOR_KEY_G4,
3827 XPM_COLOR_KEY_G,
3828 XPM_COLOR_KEY_C
3831 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3833 static int
3834 xpm_str_to_color_key (const char *s)
3836 int i;
3838 for (i = 0;
3839 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3840 i++)
3841 if (strcmp (xpm_color_key_strings[i], s) == 0)
3842 return i;
3843 return -1;
3846 static int
3847 xpm_load_image (struct frame *f,
3848 struct image *img,
3849 const unsigned char *contents,
3850 const unsigned char *end)
3852 const unsigned char *s = contents, *beg, *str;
3853 unsigned char buffer[BUFSIZ];
3854 int width, height, x, y;
3855 int num_colors, chars_per_pixel;
3856 int len, LA1;
3857 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3858 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3859 Lisp_Object frame, color_symbols, color_table;
3860 int best_key, have_mask = 0;
3861 XImagePtr ximg = NULL, mask_img = NULL;
3863 #define match() \
3864 LA1 = xpm_scan (&s, end, &beg, &len)
3866 #define expect(TOKEN) \
3867 if (LA1 != (TOKEN)) \
3868 goto failure; \
3869 else \
3870 match ()
3872 #define expect_ident(IDENT) \
3873 if (LA1 == XPM_TK_IDENT \
3874 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3875 match (); \
3876 else \
3877 goto failure
3879 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3880 goto failure;
3881 s += 9;
3882 match ();
3883 expect_ident ("static");
3884 expect_ident ("char");
3885 expect ('*');
3886 expect (XPM_TK_IDENT);
3887 expect ('[');
3888 expect (']');
3889 expect ('=');
3890 expect ('{');
3891 expect (XPM_TK_STRING);
3892 if (len >= BUFSIZ)
3893 goto failure;
3894 memcpy (buffer, beg, len);
3895 buffer[len] = '\0';
3896 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3897 &num_colors, &chars_per_pixel) != 4
3898 || width <= 0 || height <= 0
3899 || num_colors <= 0 || chars_per_pixel <= 0)
3900 goto failure;
3902 if (!check_image_size (f, width, height))
3904 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
3905 goto failure;
3908 expect (',');
3910 XSETFRAME (frame, f);
3911 if (!NILP (Fxw_display_color_p (frame)))
3912 best_key = XPM_COLOR_KEY_C;
3913 else if (!NILP (Fx_display_grayscale_p (frame)))
3914 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
3915 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
3916 else
3917 best_key = XPM_COLOR_KEY_M;
3919 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3920 if (chars_per_pixel == 1)
3921 color_table = xpm_make_color_table_v (&put_color_table,
3922 &get_color_table);
3923 else
3924 color_table = xpm_make_color_table_h (&put_color_table,
3925 &get_color_table);
3927 while (num_colors-- > 0)
3929 unsigned char *color, *max_color;
3930 int key, next_key, max_key = 0;
3931 Lisp_Object symbol_color = Qnil, color_val;
3932 XColor cdef;
3934 expect (XPM_TK_STRING);
3935 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
3936 goto failure;
3937 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
3938 buffer[len - chars_per_pixel] = '\0';
3940 str = strtok (buffer, " \t");
3941 if (str == NULL)
3942 goto failure;
3943 key = xpm_str_to_color_key (str);
3944 if (key < 0)
3945 goto failure;
3948 color = strtok (NULL, " \t");
3949 if (color == NULL)
3950 goto failure;
3952 while ((str = strtok (NULL, " \t")) != NULL)
3954 next_key = xpm_str_to_color_key (str);
3955 if (next_key >= 0)
3956 break;
3957 color[strlen (color)] = ' ';
3960 if (key == XPM_COLOR_KEY_S)
3962 if (NILP (symbol_color))
3963 symbol_color = build_string (color);
3965 else if (max_key < key && key <= best_key)
3967 max_key = key;
3968 max_color = color;
3970 key = next_key;
3972 while (str);
3974 color_val = Qnil;
3975 if (!NILP (color_symbols) && !NILP (symbol_color))
3977 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
3979 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
3981 if (xstrcasecmp (SDATA (XCDR (specified_color)), "None") == 0)
3982 color_val = Qt;
3983 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
3984 &cdef, 0))
3985 color_val = make_number (cdef.pixel);
3988 if (NILP (color_val) && max_key > 0)
3990 if (xstrcasecmp (max_color, "None") == 0)
3991 color_val = Qt;
3992 else if (x_defined_color (f, max_color, &cdef, 0))
3993 color_val = make_number (cdef.pixel);
3995 if (!NILP (color_val))
3996 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
3998 expect (',');
4001 if (!x_create_x_image_and_pixmap (f, width, height, 0,
4002 &ximg, &img->pixmap)
4003 #ifndef HAVE_NS
4004 || !x_create_x_image_and_pixmap (f, width, height, 1,
4005 &mask_img, &img->mask)
4006 #endif
4009 image_error ("Out of memory (%s)", img->spec, Qnil);
4010 goto error;
4013 for (y = 0; y < height; y++)
4015 expect (XPM_TK_STRING);
4016 str = beg;
4017 if (len < width * chars_per_pixel)
4018 goto failure;
4019 for (x = 0; x < width; x++, str += chars_per_pixel)
4021 Lisp_Object color_val =
4022 (*get_color_table) (color_table, str, chars_per_pixel);
4024 XPutPixel (ximg, x, y,
4025 (INTEGERP (color_val) ? XINT (color_val)
4026 : FRAME_FOREGROUND_PIXEL (f)));
4027 #ifndef HAVE_NS
4028 XPutPixel (mask_img, x, y,
4029 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4030 : (have_mask = 1, PIX_MASK_RETAIN)));
4031 #else
4032 if (EQ (color_val, Qt))
4033 ns_set_alpha (ximg, x, y, 0);
4034 #endif
4036 if (y + 1 < height)
4037 expect (',');
4040 img->width = width;
4041 img->height = height;
4043 /* Maybe fill in the background field while we have ximg handy. */
4044 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4045 IMAGE_BACKGROUND (img, f, ximg);
4047 x_put_x_image (f, ximg, img->pixmap, width, height);
4048 x_destroy_x_image (ximg);
4049 #ifndef HAVE_NS
4050 if (have_mask)
4052 /* Fill in the background_transparent field while we have the
4053 mask handy. */
4054 image_background_transparent (img, f, mask_img);
4056 x_put_x_image (f, mask_img, img->mask, width, height);
4057 x_destroy_x_image (mask_img);
4059 else
4061 x_destroy_x_image (mask_img);
4062 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4063 img->mask = NO_PIXMAP;
4065 #endif
4066 return 1;
4068 failure:
4069 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4070 error:
4071 x_destroy_x_image (ximg);
4072 x_destroy_x_image (mask_img);
4073 x_clear_image (f, img);
4074 return 0;
4076 #undef match
4077 #undef expect
4078 #undef expect_ident
4081 static int
4082 xpm_load (struct frame *f,
4083 struct image *img)
4085 int success_p = 0;
4086 Lisp_Object file_name;
4088 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4089 file_name = image_spec_value (img->spec, QCfile, NULL);
4090 if (STRINGP (file_name))
4092 Lisp_Object file;
4093 unsigned char *contents;
4094 int size;
4096 file = x_find_image_file (file_name);
4097 if (!STRINGP (file))
4099 image_error ("Cannot find image file `%s'", file_name, Qnil);
4100 return 0;
4103 contents = slurp_file (SDATA (file), &size);
4104 if (contents == NULL)
4106 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4107 return 0;
4110 success_p = xpm_load_image (f, img, contents, contents + size);
4111 xfree (contents);
4113 else
4115 Lisp_Object data;
4117 data = image_spec_value (img->spec, QCdata, NULL);
4118 if (!STRINGP (data))
4120 image_error ("Invalid image data `%s'", data, Qnil);
4121 return 0;
4123 success_p = xpm_load_image (f, img, SDATA (data),
4124 SDATA (data) + SBYTES (data));
4127 return success_p;
4130 #endif /* HAVE_NS && !HAVE_XPM */
4134 /***********************************************************************
4135 Color table
4136 ***********************************************************************/
4138 #ifdef COLOR_TABLE_SUPPORT
4140 /* An entry in the color table mapping an RGB color to a pixel color. */
4142 struct ct_color
4144 int r, g, b;
4145 unsigned long pixel;
4147 /* Next in color table collision list. */
4148 struct ct_color *next;
4151 /* The bucket vector size to use. Must be prime. */
4153 #define CT_SIZE 101
4155 /* Value is a hash of the RGB color given by R, G, and B. */
4157 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4159 /* The color hash table. */
4161 struct ct_color **ct_table;
4163 /* Number of entries in the color table. */
4165 int ct_colors_allocated;
4167 /* Initialize the color table. */
4169 static void
4170 init_color_table (void)
4172 int size = CT_SIZE * sizeof (*ct_table);
4173 ct_table = (struct ct_color **) xmalloc (size);
4174 memset (ct_table, 0, size);
4175 ct_colors_allocated = 0;
4179 /* Free memory associated with the color table. */
4181 static void
4182 free_color_table (void)
4184 int i;
4185 struct ct_color *p, *next;
4187 for (i = 0; i < CT_SIZE; ++i)
4188 for (p = ct_table[i]; p; p = next)
4190 next = p->next;
4191 xfree (p);
4194 xfree (ct_table);
4195 ct_table = NULL;
4199 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4200 entry for that color already is in the color table, return the
4201 pixel color of that entry. Otherwise, allocate a new color for R,
4202 G, B, and make an entry in the color table. */
4204 static unsigned long
4205 lookup_rgb_color (struct frame *f, int r, int g, int b)
4207 unsigned hash = CT_HASH_RGB (r, g, b);
4208 int i = hash % CT_SIZE;
4209 struct ct_color *p;
4210 Display_Info *dpyinfo;
4212 /* Handle TrueColor visuals specially, which improves performance by
4213 two orders of magnitude. Freeing colors on TrueColor visuals is
4214 a nop, and pixel colors specify RGB values directly. See also
4215 the Xlib spec, chapter 3.1. */
4216 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4217 if (dpyinfo->red_bits > 0)
4219 unsigned long pr, pg, pb;
4221 /* Apply gamma-correction like normal color allocation does. */
4222 if (f->gamma)
4224 XColor color;
4225 color.red = r, color.green = g, color.blue = b;
4226 gamma_correct (f, &color);
4227 r = color.red, g = color.green, b = color.blue;
4230 /* Scale down RGB values to the visual's bits per RGB, and shift
4231 them to the right position in the pixel color. Note that the
4232 original RGB values are 16-bit values, as usual in X. */
4233 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4234 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4235 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4237 /* Assemble the pixel color. */
4238 return pr | pg | pb;
4241 for (p = ct_table[i]; p; p = p->next)
4242 if (p->r == r && p->g == g && p->b == b)
4243 break;
4245 if (p == NULL)
4248 #ifdef HAVE_X_WINDOWS
4249 XColor color;
4250 Colormap cmap;
4251 int rc;
4253 color.red = r;
4254 color.green = g;
4255 color.blue = b;
4257 cmap = FRAME_X_COLORMAP (f);
4258 rc = x_alloc_nearest_color (f, cmap, &color);
4259 if (rc)
4261 ++ct_colors_allocated;
4262 p = (struct ct_color *) xmalloc (sizeof *p);
4263 p->r = r;
4264 p->g = g;
4265 p->b = b;
4266 p->pixel = color.pixel;
4267 p->next = ct_table[i];
4268 ct_table[i] = p;
4270 else
4271 return FRAME_FOREGROUND_PIXEL (f);
4273 #else
4274 COLORREF color;
4275 #ifdef HAVE_NTGUI
4276 color = PALETTERGB (r, g, b);
4277 #else
4278 color = RGB_TO_ULONG (r, g, b);
4279 #endif /* HAVE_NTGUI */
4280 ++ct_colors_allocated;
4281 p = (struct ct_color *) xmalloc (sizeof *p);
4282 p->r = r;
4283 p->g = g;
4284 p->b = b;
4285 p->pixel = color;
4286 p->next = ct_table[i];
4287 ct_table[i] = p;
4288 #endif /* HAVE_X_WINDOWS */
4292 return p->pixel;
4296 /* Look up pixel color PIXEL which is used on frame F in the color
4297 table. If not already present, allocate it. Value is PIXEL. */
4299 static unsigned long
4300 lookup_pixel_color (struct frame *f, unsigned long pixel)
4302 int i = pixel % CT_SIZE;
4303 struct ct_color *p;
4305 for (p = ct_table[i]; p; p = p->next)
4306 if (p->pixel == pixel)
4307 break;
4309 if (p == NULL)
4311 XColor color;
4312 Colormap cmap;
4313 int rc;
4315 #ifdef HAVE_X_WINDOWS
4316 cmap = FRAME_X_COLORMAP (f);
4317 color.pixel = pixel;
4318 x_query_color (f, &color);
4319 rc = x_alloc_nearest_color (f, cmap, &color);
4320 #else
4321 BLOCK_INPUT;
4322 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4323 color.pixel = pixel;
4324 XQueryColor (NULL, cmap, &color);
4325 rc = x_alloc_nearest_color (f, cmap, &color);
4326 UNBLOCK_INPUT;
4327 #endif /* HAVE_X_WINDOWS */
4329 if (rc)
4331 ++ct_colors_allocated;
4333 p = (struct ct_color *) xmalloc (sizeof *p);
4334 p->r = color.red;
4335 p->g = color.green;
4336 p->b = color.blue;
4337 p->pixel = pixel;
4338 p->next = ct_table[i];
4339 ct_table[i] = p;
4341 else
4342 return FRAME_FOREGROUND_PIXEL (f);
4344 return p->pixel;
4348 /* Value is a vector of all pixel colors contained in the color table,
4349 allocated via xmalloc. Set *N to the number of colors. */
4351 static unsigned long *
4352 colors_in_color_table (int *n)
4354 int i, j;
4355 struct ct_color *p;
4356 unsigned long *colors;
4358 if (ct_colors_allocated == 0)
4360 *n = 0;
4361 colors = NULL;
4363 else
4365 colors = (unsigned long *) xmalloc (ct_colors_allocated
4366 * sizeof *colors);
4367 *n = ct_colors_allocated;
4369 for (i = j = 0; i < CT_SIZE; ++i)
4370 for (p = ct_table[i]; p; p = p->next)
4371 colors[j++] = p->pixel;
4374 return colors;
4377 #else /* COLOR_TABLE_SUPPORT */
4379 static unsigned long
4380 lookup_rgb_color (struct frame *f, int r, int g, int b)
4382 unsigned long pixel;
4384 #ifdef HAVE_NTGUI
4385 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4386 #endif /* HAVE_NTGUI */
4388 #ifdef HAVE_NS
4389 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4390 #endif /* HAVE_NS */
4391 return pixel;
4394 static void
4395 init_color_table (void)
4398 #endif /* COLOR_TABLE_SUPPORT */
4401 /***********************************************************************
4402 Algorithms
4403 ***********************************************************************/
4405 static XColor *x_to_xcolors (struct frame *, struct image *, int);
4406 static void x_from_xcolors (struct frame *, struct image *, XColor *);
4407 static void x_detect_edges (struct frame *, struct image *, int[9], int);
4409 #ifdef HAVE_NTGUI
4410 static void XPutPixel (XImagePtr , int, int, COLORREF);
4411 #endif /* HAVE_NTGUI */
4413 /* Non-zero means draw a cross on images having `:conversion
4414 disabled'. */
4416 int cross_disabled_images;
4418 /* Edge detection matrices for different edge-detection
4419 strategies. */
4421 static int emboss_matrix[9] = {
4422 /* x - 1 x x + 1 */
4423 2, -1, 0, /* y - 1 */
4424 -1, 0, 1, /* y */
4425 0, 1, -2 /* y + 1 */
4428 static int laplace_matrix[9] = {
4429 /* x - 1 x x + 1 */
4430 1, 0, 0, /* y - 1 */
4431 0, 0, 0, /* y */
4432 0, 0, -1 /* y + 1 */
4435 /* Value is the intensity of the color whose red/green/blue values
4436 are R, G, and B. */
4438 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4441 /* On frame F, return an array of XColor structures describing image
4442 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4443 non-zero means also fill the red/green/blue members of the XColor
4444 structures. Value is a pointer to the array of XColors structures,
4445 allocated with xmalloc; it must be freed by the caller. */
4447 static XColor *
4448 x_to_xcolors (struct frame *f, struct image *img, int rgb_p)
4450 int x, y;
4451 XColor *colors, *p;
4452 XImagePtr_or_DC ximg;
4453 #ifdef HAVE_NTGUI
4454 HDC hdc;
4455 HGDIOBJ prev;
4456 #endif /* HAVE_NTGUI */
4458 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4460 #ifndef HAVE_NTGUI
4461 /* Get the X image IMG->pixmap. */
4462 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4463 0, 0, img->width, img->height, ~0, ZPixmap);
4464 #else
4465 /* Load the image into a memory device context. */
4466 hdc = get_frame_dc (f);
4467 ximg = CreateCompatibleDC (hdc);
4468 release_frame_dc (f, hdc);
4469 prev = SelectObject (ximg, img->pixmap);
4470 #endif /* HAVE_NTGUI */
4472 /* Fill the `pixel' members of the XColor array. I wished there
4473 were an easy and portable way to circumvent XGetPixel. */
4474 p = colors;
4475 for (y = 0; y < img->height; ++y)
4477 XColor *row = p;
4479 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4480 for (x = 0; x < img->width; ++x, ++p)
4481 p->pixel = GET_PIXEL (ximg, x, y);
4482 if (rgb_p)
4483 x_query_colors (f, row, img->width);
4485 #else
4487 for (x = 0; x < img->width; ++x, ++p)
4489 /* W32_TODO: palette support needed here? */
4490 p->pixel = GET_PIXEL (ximg, x, y);
4491 if (rgb_p)
4493 p->red = RED16_FROM_ULONG (p->pixel);
4494 p->green = GREEN16_FROM_ULONG (p->pixel);
4495 p->blue = BLUE16_FROM_ULONG (p->pixel);
4498 #endif /* HAVE_X_WINDOWS */
4501 Destroy_Image (ximg, prev);
4503 return colors;
4506 #ifdef HAVE_NTGUI
4508 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4509 created with CreateDIBSection, with the pointer to the bit values
4510 stored in ximg->data. */
4512 static void
4513 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4515 int width = ximg->info.bmiHeader.biWidth;
4516 int height = ximg->info.bmiHeader.biHeight;
4517 unsigned char * pixel;
4519 /* True color images. */
4520 if (ximg->info.bmiHeader.biBitCount == 24)
4522 int rowbytes = width * 3;
4523 /* Ensure scanlines are aligned on 4 byte boundaries. */
4524 if (rowbytes % 4)
4525 rowbytes += 4 - (rowbytes % 4);
4527 pixel = ximg->data + y * rowbytes + x * 3;
4528 /* Windows bitmaps are in BGR order. */
4529 *pixel = GetBValue (color);
4530 *(pixel + 1) = GetGValue (color);
4531 *(pixel + 2) = GetRValue (color);
4533 /* Monochrome images. */
4534 else if (ximg->info.bmiHeader.biBitCount == 1)
4536 int rowbytes = width / 8;
4537 /* Ensure scanlines are aligned on 4 byte boundaries. */
4538 if (rowbytes % 4)
4539 rowbytes += 4 - (rowbytes % 4);
4540 pixel = ximg->data + y * rowbytes + x / 8;
4541 /* Filter out palette info. */
4542 if (color & 0x00ffffff)
4543 *pixel = *pixel | (1 << x % 8);
4544 else
4545 *pixel = *pixel & ~(1 << x % 8);
4547 else
4548 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4551 #endif /* HAVE_NTGUI */
4553 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4554 RGB members are set. F is the frame on which this all happens.
4555 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4557 static void
4558 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4560 int x, y;
4561 XImagePtr oimg = NULL;
4562 Pixmap pixmap;
4563 XColor *p;
4565 init_color_table ();
4567 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4568 &oimg, &pixmap);
4569 p = colors;
4570 for (y = 0; y < img->height; ++y)
4571 for (x = 0; x < img->width; ++x, ++p)
4573 unsigned long pixel;
4574 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4575 XPutPixel (oimg, x, y, pixel);
4578 xfree (colors);
4579 x_clear_image_1 (f, img, 1, 0, 1);
4581 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4582 x_destroy_x_image (oimg);
4583 img->pixmap = pixmap;
4584 #ifdef COLOR_TABLE_SUPPORT
4585 img->colors = colors_in_color_table (&img->ncolors);
4586 free_color_table ();
4587 #endif /* COLOR_TABLE_SUPPORT */
4591 /* On frame F, perform edge-detection on image IMG.
4593 MATRIX is a nine-element array specifying the transformation
4594 matrix. See emboss_matrix for an example.
4596 COLOR_ADJUST is a color adjustment added to each pixel of the
4597 outgoing image. */
4599 static void
4600 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4602 XColor *colors = x_to_xcolors (f, img, 1);
4603 XColor *new, *p;
4604 int x, y, i, sum;
4606 for (i = sum = 0; i < 9; ++i)
4607 sum += eabs (matrix[i]);
4609 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4611 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4613 for (y = 0; y < img->height; ++y)
4615 p = COLOR (new, 0, y);
4616 p->red = p->green = p->blue = 0xffff/2;
4617 p = COLOR (new, img->width - 1, y);
4618 p->red = p->green = p->blue = 0xffff/2;
4621 for (x = 1; x < img->width - 1; ++x)
4623 p = COLOR (new, x, 0);
4624 p->red = p->green = p->blue = 0xffff/2;
4625 p = COLOR (new, x, img->height - 1);
4626 p->red = p->green = p->blue = 0xffff/2;
4629 for (y = 1; y < img->height - 1; ++y)
4631 p = COLOR (new, 1, y);
4633 for (x = 1; x < img->width - 1; ++x, ++p)
4635 int r, g, b, y1, x1;
4637 r = g = b = i = 0;
4638 for (y1 = y - 1; y1 < y + 2; ++y1)
4639 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
4640 if (matrix[i])
4642 XColor *t = COLOR (colors, x1, y1);
4643 r += matrix[i] * t->red;
4644 g += matrix[i] * t->green;
4645 b += matrix[i] * t->blue;
4648 r = (r / sum + color_adjust) & 0xffff;
4649 g = (g / sum + color_adjust) & 0xffff;
4650 b = (b / sum + color_adjust) & 0xffff;
4651 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4655 xfree (colors);
4656 x_from_xcolors (f, img, new);
4658 #undef COLOR
4662 /* Perform the pre-defined `emboss' edge-detection on image IMG
4663 on frame F. */
4665 static void
4666 x_emboss (struct frame *f, struct image *img)
4668 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4672 /* Transform image IMG which is used on frame F with a Laplace
4673 edge-detection algorithm. The result is an image that can be used
4674 to draw disabled buttons, for example. */
4676 static void
4677 x_laplace (struct frame *f, struct image *img)
4679 x_detect_edges (f, img, laplace_matrix, 45000);
4683 /* Perform edge-detection on image IMG on frame F, with specified
4684 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4686 MATRIX must be either
4688 - a list of at least 9 numbers in row-major form
4689 - a vector of at least 9 numbers
4691 COLOR_ADJUST nil means use a default; otherwise it must be a
4692 number. */
4694 static void
4695 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4696 Lisp_Object color_adjust)
4698 int i = 0;
4699 int trans[9];
4701 if (CONSP (matrix))
4703 for (i = 0;
4704 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4705 ++i, matrix = XCDR (matrix))
4706 trans[i] = XFLOATINT (XCAR (matrix));
4708 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4710 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4711 trans[i] = XFLOATINT (AREF (matrix, i));
4714 if (NILP (color_adjust))
4715 color_adjust = make_number (0xffff / 2);
4717 if (i == 9 && NUMBERP (color_adjust))
4718 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
4722 /* Transform image IMG on frame F so that it looks disabled. */
4724 static void
4725 x_disable_image (struct frame *f, struct image *img)
4727 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4728 #ifdef HAVE_NTGUI
4729 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4730 #else
4731 int n_planes = dpyinfo->n_planes;
4732 #endif /* HAVE_NTGUI */
4734 if (n_planes >= 2)
4736 /* Color (or grayscale). Convert to gray, and equalize. Just
4737 drawing such images with a stipple can look very odd, so
4738 we're using this method instead. */
4739 XColor *colors = x_to_xcolors (f, img, 1);
4740 XColor *p, *end;
4741 const int h = 15000;
4742 const int l = 30000;
4744 for (p = colors, end = colors + img->width * img->height;
4745 p < end;
4746 ++p)
4748 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4749 int i2 = (0xffff - h - l) * i / 0xffff + l;
4750 p->red = p->green = p->blue = i2;
4753 x_from_xcolors (f, img, colors);
4756 /* Draw a cross over the disabled image, if we must or if we
4757 should. */
4758 if (n_planes < 2 || cross_disabled_images)
4760 #ifndef HAVE_NTGUI
4761 Display *dpy = FRAME_X_DISPLAY (f);
4762 GC gc;
4764 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4766 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4768 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4769 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4770 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4771 img->width - 1, img->height - 1);
4772 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4773 img->width - 1, 0);
4774 XFreeGC (dpy, gc);
4776 if (img->mask)
4778 gc = XCreateGC (dpy, img->mask, 0, NULL);
4779 XSetForeground (dpy, gc, MaskForeground (f));
4780 XDrawLine (dpy, img->mask, gc, 0, 0,
4781 img->width - 1, img->height - 1);
4782 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4783 img->width - 1, 0);
4784 XFreeGC (dpy, gc);
4786 #endif /* !HAVE_NS */
4787 #else
4788 HDC hdc, bmpdc;
4789 HGDIOBJ prev;
4791 hdc = get_frame_dc (f);
4792 bmpdc = CreateCompatibleDC (hdc);
4793 release_frame_dc (f, hdc);
4795 prev = SelectObject (bmpdc, img->pixmap);
4797 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4798 MoveToEx (bmpdc, 0, 0, NULL);
4799 LineTo (bmpdc, img->width - 1, img->height - 1);
4800 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4801 LineTo (bmpdc, img->width - 1, 0);
4803 if (img->mask)
4805 SelectObject (bmpdc, img->mask);
4806 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4807 MoveToEx (bmpdc, 0, 0, NULL);
4808 LineTo (bmpdc, img->width - 1, img->height - 1);
4809 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4810 LineTo (bmpdc, img->width - 1, 0);
4812 SelectObject (bmpdc, prev);
4813 DeleteDC (bmpdc);
4814 #endif /* HAVE_NTGUI */
4819 /* Build a mask for image IMG which is used on frame F. FILE is the
4820 name of an image file, for error messages. HOW determines how to
4821 determine the background color of IMG. If it is a list '(R G B)',
4822 with R, G, and B being integers >= 0, take that as the color of the
4823 background. Otherwise, determine the background color of IMG
4824 heuristically. Value is non-zero if successful. */
4826 static int
4827 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4829 XImagePtr_or_DC ximg;
4830 #ifndef HAVE_NTGUI
4831 XImagePtr mask_img;
4832 #else
4833 HDC frame_dc;
4834 HGDIOBJ prev;
4835 char *mask_img;
4836 int row_width;
4837 #endif /* HAVE_NTGUI */
4838 int x, y, rc, use_img_background;
4839 unsigned long bg = 0;
4841 if (img->mask)
4843 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4844 img->mask = NO_PIXMAP;
4845 img->background_transparent_valid = 0;
4848 #ifndef HAVE_NTGUI
4849 #ifndef HAVE_NS
4850 /* Create an image and pixmap serving as mask. */
4851 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4852 &mask_img, &img->mask);
4853 if (!rc)
4854 return 0;
4855 #endif /* !HAVE_NS */
4857 /* Get the X image of IMG->pixmap. */
4858 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4859 img->width, img->height,
4860 ~0, ZPixmap);
4861 #else
4862 /* Create the bit array serving as mask. */
4863 row_width = (img->width + 7) / 8;
4864 mask_img = xmalloc (row_width * img->height);
4865 memset (mask_img, 0, row_width * img->height);
4867 /* Create a memory device context for IMG->pixmap. */
4868 frame_dc = get_frame_dc (f);
4869 ximg = CreateCompatibleDC (frame_dc);
4870 release_frame_dc (f, frame_dc);
4871 prev = SelectObject (ximg, img->pixmap);
4872 #endif /* HAVE_NTGUI */
4874 /* Determine the background color of ximg. If HOW is `(R G B)'
4875 take that as color. Otherwise, use the image's background color. */
4876 use_img_background = 1;
4878 if (CONSP (how))
4880 int rgb[3], i;
4882 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4884 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4885 how = XCDR (how);
4888 if (i == 3 && NILP (how))
4890 char color_name[30];
4891 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4892 bg = (
4893 #ifdef HAVE_NTGUI
4894 0x00ffffff & /* Filter out palette info. */
4895 #endif /* HAVE_NTGUI */
4896 x_alloc_image_color (f, img, build_string (color_name), 0));
4897 use_img_background = 0;
4901 if (use_img_background)
4902 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4904 /* Set all bits in mask_img to 1 whose color in ximg is different
4905 from the background color bg. */
4906 #ifndef HAVE_NTGUI
4907 for (y = 0; y < img->height; ++y)
4908 for (x = 0; x < img->width; ++x)
4909 #ifndef HAVE_NS
4910 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4911 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4912 #else
4913 if (XGetPixel (ximg, x, y) == bg)
4914 ns_set_alpha (ximg, x, y, 0);
4915 #endif /* HAVE_NS */
4916 #ifndef HAVE_NS
4917 /* Fill in the background_transparent field while we have the mask handy. */
4918 image_background_transparent (img, f, mask_img);
4920 /* Put mask_img into img->mask. */
4921 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4922 x_destroy_x_image (mask_img);
4923 #endif /* !HAVE_NS */
4924 #else
4925 for (y = 0; y < img->height; ++y)
4926 for (x = 0; x < img->width; ++x)
4928 COLORREF p = GetPixel (ximg, x, y);
4929 if (p != bg)
4930 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4933 /* Create the mask image. */
4934 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4935 mask_img);
4936 /* Fill in the background_transparent field while we have the mask handy. */
4937 SelectObject (ximg, img->mask);
4938 image_background_transparent (img, f, ximg);
4940 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4941 xfree (mask_img);
4942 #endif /* HAVE_NTGUI */
4944 Destroy_Image (ximg, prev);
4946 return 1;
4950 /***********************************************************************
4951 PBM (mono, gray, color)
4952 ***********************************************************************/
4954 static int pbm_image_p (Lisp_Object object);
4955 static int pbm_load (struct frame *f, struct image *img);
4956 static int pbm_scan_number (unsigned char **, unsigned char *);
4958 /* The symbol `pbm' identifying images of this type. */
4960 Lisp_Object Qpbm;
4962 /* Indices of image specification fields in gs_format, below. */
4964 enum pbm_keyword_index
4966 PBM_TYPE,
4967 PBM_FILE,
4968 PBM_DATA,
4969 PBM_ASCENT,
4970 PBM_MARGIN,
4971 PBM_RELIEF,
4972 PBM_ALGORITHM,
4973 PBM_HEURISTIC_MASK,
4974 PBM_MASK,
4975 PBM_FOREGROUND,
4976 PBM_BACKGROUND,
4977 PBM_LAST
4980 /* Vector of image_keyword structures describing the format
4981 of valid user-defined image specifications. */
4983 static const struct image_keyword pbm_format[PBM_LAST] =
4985 {":type", IMAGE_SYMBOL_VALUE, 1},
4986 {":file", IMAGE_STRING_VALUE, 0},
4987 {":data", IMAGE_STRING_VALUE, 0},
4988 {":ascent", IMAGE_ASCENT_VALUE, 0},
4989 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
4990 {":relief", IMAGE_INTEGER_VALUE, 0},
4991 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4992 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4993 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4994 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4995 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4998 /* Structure describing the image type `pbm'. */
5000 static struct image_type pbm_type =
5002 &Qpbm,
5003 pbm_image_p,
5004 pbm_load,
5005 x_clear_image,
5006 NULL
5010 /* Return non-zero if OBJECT is a valid PBM image specification. */
5012 static int
5013 pbm_image_p (Lisp_Object object)
5015 struct image_keyword fmt[PBM_LAST];
5017 memcpy (fmt, pbm_format, sizeof fmt);
5019 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5020 return 0;
5022 /* Must specify either :data or :file. */
5023 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5027 /* Scan a decimal number from *S and return it. Advance *S while
5028 reading the number. END is the end of the string. Value is -1 at
5029 end of input. */
5031 static int
5032 pbm_scan_number (unsigned char **s, unsigned char *end)
5034 int c = 0, val = -1;
5036 while (*s < end)
5038 /* Skip white-space. */
5039 while (*s < end && (c = *(*s)++, isspace (c)))
5042 if (c == '#')
5044 /* Skip comment to end of line. */
5045 while (*s < end && (c = *(*s)++, c != '\n'))
5048 else if (isdigit (c))
5050 /* Read decimal number. */
5051 val = c - '0';
5052 while (*s < end && (c = *(*s)++, isdigit (c)))
5053 val = 10 * val + c - '0';
5054 break;
5056 else
5057 break;
5060 return val;
5064 #ifdef HAVE_NTGUI
5065 #if 0 /* Unused. ++kfs */
5067 /* Read FILE into memory. Value is a pointer to a buffer allocated
5068 with xmalloc holding FILE's contents. Value is null if an error
5069 occurred. *SIZE is set to the size of the file. */
5071 static char *
5072 pbm_read_file (file, size)
5073 Lisp_Object file;
5074 int *size;
5076 FILE *fp = NULL;
5077 char *buf = NULL;
5078 struct stat st;
5080 if (stat (SDATA (file), &st) == 0
5081 && (fp = fopen (SDATA (file), "rb")) != NULL
5082 && (buf = (char *) xmalloc (st.st_size),
5083 fread (buf, 1, st.st_size, fp) == st.st_size))
5085 *size = st.st_size;
5086 fclose (fp);
5088 else
5090 if (fp)
5091 fclose (fp);
5092 if (buf)
5094 xfree (buf);
5095 buf = NULL;
5099 return buf;
5101 #endif
5102 #endif /* HAVE_NTGUI */
5104 /* Load PBM image IMG for use on frame F. */
5106 static int
5107 pbm_load (struct frame *f, struct image *img)
5109 int raw_p, x, y;
5110 int width, height, max_color_idx = 0;
5111 XImagePtr ximg;
5112 Lisp_Object file, specified_file;
5113 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5114 unsigned char *contents = NULL;
5115 unsigned char *end, *p;
5116 int size;
5118 specified_file = image_spec_value (img->spec, QCfile, NULL);
5120 if (STRINGP (specified_file))
5122 file = x_find_image_file (specified_file);
5123 if (!STRINGP (file))
5125 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5126 return 0;
5129 contents = slurp_file (SDATA (file), &size);
5130 if (contents == NULL)
5132 image_error ("Error reading `%s'", file, Qnil);
5133 return 0;
5136 p = contents;
5137 end = contents + size;
5139 else
5141 Lisp_Object data;
5142 data = image_spec_value (img->spec, QCdata, NULL);
5143 if (!STRINGP (data))
5145 image_error ("Invalid image data `%s'", data, Qnil);
5146 return 0;
5148 p = SDATA (data);
5149 end = p + SBYTES (data);
5152 /* Check magic number. */
5153 if (end - p < 2 || *p++ != 'P')
5155 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5156 error:
5157 xfree (contents);
5158 return 0;
5161 switch (*p++)
5163 case '1':
5164 raw_p = 0, type = PBM_MONO;
5165 break;
5167 case '2':
5168 raw_p = 0, type = PBM_GRAY;
5169 break;
5171 case '3':
5172 raw_p = 0, type = PBM_COLOR;
5173 break;
5175 case '4':
5176 raw_p = 1, type = PBM_MONO;
5177 break;
5179 case '5':
5180 raw_p = 1, type = PBM_GRAY;
5181 break;
5183 case '6':
5184 raw_p = 1, type = PBM_COLOR;
5185 break;
5187 default:
5188 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5189 goto error;
5192 /* Read width, height, maximum color-component. Characters
5193 starting with `#' up to the end of a line are ignored. */
5194 width = pbm_scan_number (&p, end);
5195 height = pbm_scan_number (&p, end);
5197 if (type != PBM_MONO)
5199 max_color_idx = pbm_scan_number (&p, end);
5200 if (max_color_idx > 65535 || max_color_idx < 0)
5202 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5203 goto error;
5207 if (!check_image_size (f, width, height))
5209 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5210 goto error;
5213 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5214 &ximg, &img->pixmap))
5215 goto error;
5217 /* Initialize the color hash table. */
5218 init_color_table ();
5220 if (type == PBM_MONO)
5222 int c = 0, g;
5223 struct image_keyword fmt[PBM_LAST];
5224 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5225 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5227 /* Parse the image specification. */
5228 memcpy (fmt, pbm_format, sizeof fmt);
5229 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5231 /* Get foreground and background colors, maybe allocate colors. */
5232 if (fmt[PBM_FOREGROUND].count
5233 && STRINGP (fmt[PBM_FOREGROUND].value))
5234 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5235 if (fmt[PBM_BACKGROUND].count
5236 && STRINGP (fmt[PBM_BACKGROUND].value))
5238 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5239 img->background = bg;
5240 img->background_valid = 1;
5243 for (y = 0; y < height; ++y)
5244 for (x = 0; x < width; ++x)
5246 if (raw_p)
5248 if ((x & 7) == 0)
5250 if (p >= end)
5252 x_destroy_x_image (ximg);
5253 x_clear_image (f, img);
5254 image_error ("Invalid image size in image `%s'",
5255 img->spec, Qnil);
5256 goto error;
5258 c = *p++;
5260 g = c & 0x80;
5261 c <<= 1;
5263 else
5264 g = pbm_scan_number (&p, end);
5266 XPutPixel (ximg, x, y, g ? fg : bg);
5269 else
5271 int expected_size = height * width;
5272 if (max_color_idx > 255)
5273 expected_size *= 2;
5274 if (type == PBM_COLOR)
5275 expected_size *= 3;
5277 if (raw_p && p + expected_size > end)
5279 x_destroy_x_image (ximg);
5280 x_clear_image (f, img);
5281 image_error ("Invalid image size in image `%s'",
5282 img->spec, Qnil);
5283 goto error;
5286 for (y = 0; y < height; ++y)
5287 for (x = 0; x < width; ++x)
5289 int r, g, b;
5291 if (type == PBM_GRAY && raw_p)
5293 r = g = b = *p++;
5294 if (max_color_idx > 255)
5295 r = g = b = r * 256 + *p++;
5297 else if (type == PBM_GRAY)
5298 r = g = b = pbm_scan_number (&p, end);
5299 else if (raw_p)
5301 r = *p++;
5302 if (max_color_idx > 255)
5303 r = r * 256 + *p++;
5304 g = *p++;
5305 if (max_color_idx > 255)
5306 g = g * 256 + *p++;
5307 b = *p++;
5308 if (max_color_idx > 255)
5309 b = b * 256 + *p++;
5311 else
5313 r = pbm_scan_number (&p, end);
5314 g = pbm_scan_number (&p, end);
5315 b = pbm_scan_number (&p, end);
5318 if (r < 0 || g < 0 || b < 0)
5320 x_destroy_x_image (ximg);
5321 image_error ("Invalid pixel value in image `%s'",
5322 img->spec, Qnil);
5323 goto error;
5326 /* RGB values are now in the range 0..max_color_idx.
5327 Scale this to the range 0..0xffff supported by X. */
5328 r = (double) r * 65535 / max_color_idx;
5329 g = (double) g * 65535 / max_color_idx;
5330 b = (double) b * 65535 / max_color_idx;
5331 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5335 #ifdef COLOR_TABLE_SUPPORT
5336 /* Store in IMG->colors the colors allocated for the image, and
5337 free the color table. */
5338 img->colors = colors_in_color_table (&img->ncolors);
5339 free_color_table ();
5340 #endif /* COLOR_TABLE_SUPPORT */
5342 img->width = width;
5343 img->height = height;
5345 /* Maybe fill in the background field while we have ximg handy. */
5347 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5348 /* Casting avoids a GCC warning. */
5349 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5351 /* Put the image into a pixmap. */
5352 x_put_x_image (f, ximg, img->pixmap, width, height);
5353 x_destroy_x_image (ximg);
5355 /* X and W32 versions did it here, MAC version above. ++kfs
5356 img->width = width;
5357 img->height = height; */
5359 xfree (contents);
5360 return 1;
5364 /***********************************************************************
5366 ***********************************************************************/
5368 #if defined (HAVE_PNG) || defined (HAVE_NS)
5370 /* Function prototypes. */
5372 static int png_image_p (Lisp_Object object);
5373 static int png_load (struct frame *f, struct image *img);
5375 /* The symbol `png' identifying images of this type. */
5377 Lisp_Object Qpng;
5379 /* Indices of image specification fields in png_format, below. */
5381 enum png_keyword_index
5383 PNG_TYPE,
5384 PNG_DATA,
5385 PNG_FILE,
5386 PNG_ASCENT,
5387 PNG_MARGIN,
5388 PNG_RELIEF,
5389 PNG_ALGORITHM,
5390 PNG_HEURISTIC_MASK,
5391 PNG_MASK,
5392 PNG_BACKGROUND,
5393 PNG_LAST
5396 /* Vector of image_keyword structures describing the format
5397 of valid user-defined image specifications. */
5399 static const struct image_keyword png_format[PNG_LAST] =
5401 {":type", IMAGE_SYMBOL_VALUE, 1},
5402 {":data", IMAGE_STRING_VALUE, 0},
5403 {":file", IMAGE_STRING_VALUE, 0},
5404 {":ascent", IMAGE_ASCENT_VALUE, 0},
5405 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5406 {":relief", IMAGE_INTEGER_VALUE, 0},
5407 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5408 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5409 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5410 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5413 /* Structure describing the image type `png'. */
5415 static struct image_type png_type =
5417 &Qpng,
5418 png_image_p,
5419 png_load,
5420 x_clear_image,
5421 NULL
5424 /* Return non-zero if OBJECT is a valid PNG image specification. */
5426 static int
5427 png_image_p (Lisp_Object object)
5429 struct image_keyword fmt[PNG_LAST];
5430 memcpy (fmt, png_format, sizeof fmt);
5432 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5433 return 0;
5435 /* Must specify either the :data or :file keyword. */
5436 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5439 #endif /* HAVE_PNG || HAVE_NS */
5442 #ifdef HAVE_PNG
5444 #ifdef HAVE_NTGUI
5445 /* PNG library details. */
5447 DEF_IMGLIB_FN (png_get_io_ptr, (png_structp));
5448 DEF_IMGLIB_FN (png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5449 DEF_IMGLIB_FN (png_create_read_struct, (png_const_charp, png_voidp,
5450 png_error_ptr, png_error_ptr));
5451 DEF_IMGLIB_FN (png_create_info_struct, (png_structp));
5452 DEF_IMGLIB_FN (png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5453 DEF_IMGLIB_FN (png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5454 DEF_IMGLIB_FN (png_set_sig_bytes, (png_structp, int));
5455 DEF_IMGLIB_FN (png_read_info, (png_structp, png_infop));
5456 DEF_IMGLIB_FN (png_get_IHDR, (png_structp, png_infop,
5457 png_uint_32 *, png_uint_32 *,
5458 int *, int *, int *, int *, int *));
5459 DEF_IMGLIB_FN (png_get_valid, (png_structp, png_infop, png_uint_32));
5460 DEF_IMGLIB_FN (png_set_strip_16, (png_structp));
5461 DEF_IMGLIB_FN (png_set_expand, (png_structp));
5462 DEF_IMGLIB_FN (png_set_gray_to_rgb, (png_structp));
5463 DEF_IMGLIB_FN (png_set_background, (png_structp, png_color_16p,
5464 int, int, double));
5465 DEF_IMGLIB_FN (png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5466 DEF_IMGLIB_FN (png_read_update_info, (png_structp, png_infop));
5467 DEF_IMGLIB_FN (png_get_channels, (png_structp, png_infop));
5468 DEF_IMGLIB_FN (png_get_rowbytes, (png_structp, png_infop));
5469 DEF_IMGLIB_FN (png_read_image, (png_structp, png_bytepp));
5470 DEF_IMGLIB_FN (png_read_end, (png_structp, png_infop));
5471 DEF_IMGLIB_FN (png_error, (png_structp, png_const_charp));
5473 static int
5474 init_png_functions (Lisp_Object libraries)
5476 HMODULE library;
5478 /* Try loading libpng under probable names. */
5479 if (!(library = w32_delayed_load (libraries, Qpng)))
5480 return 0;
5482 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5483 LOAD_IMGLIB_FN (library, png_sig_cmp);
5484 LOAD_IMGLIB_FN (library, png_create_read_struct);
5485 LOAD_IMGLIB_FN (library, png_create_info_struct);
5486 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5487 LOAD_IMGLIB_FN (library, png_set_read_fn);
5488 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5489 LOAD_IMGLIB_FN (library, png_read_info);
5490 LOAD_IMGLIB_FN (library, png_get_IHDR);
5491 LOAD_IMGLIB_FN (library, png_get_valid);
5492 LOAD_IMGLIB_FN (library, png_set_strip_16);
5493 LOAD_IMGLIB_FN (library, png_set_expand);
5494 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5495 LOAD_IMGLIB_FN (library, png_set_background);
5496 LOAD_IMGLIB_FN (library, png_get_bKGD);
5497 LOAD_IMGLIB_FN (library, png_read_update_info);
5498 LOAD_IMGLIB_FN (library, png_get_channels);
5499 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5500 LOAD_IMGLIB_FN (library, png_read_image);
5501 LOAD_IMGLIB_FN (library, png_read_end);
5502 LOAD_IMGLIB_FN (library, png_error);
5503 return 1;
5505 #else
5507 #define fn_png_get_io_ptr png_get_io_ptr
5508 #define fn_png_sig_cmp png_sig_cmp
5509 #define fn_png_create_read_struct png_create_read_struct
5510 #define fn_png_create_info_struct png_create_info_struct
5511 #define fn_png_destroy_read_struct png_destroy_read_struct
5512 #define fn_png_set_read_fn png_set_read_fn
5513 #define fn_png_set_sig_bytes png_set_sig_bytes
5514 #define fn_png_read_info png_read_info
5515 #define fn_png_get_IHDR png_get_IHDR
5516 #define fn_png_get_valid png_get_valid
5517 #define fn_png_set_strip_16 png_set_strip_16
5518 #define fn_png_set_expand png_set_expand
5519 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5520 #define fn_png_set_background png_set_background
5521 #define fn_png_get_bKGD png_get_bKGD
5522 #define fn_png_read_update_info png_read_update_info
5523 #define fn_png_get_channels png_get_channels
5524 #define fn_png_get_rowbytes png_get_rowbytes
5525 #define fn_png_read_image png_read_image
5526 #define fn_png_read_end png_read_end
5527 #define fn_png_error png_error
5529 #endif /* HAVE_NTGUI */
5531 /* Error and warning handlers installed when the PNG library
5532 is initialized. */
5534 static void
5535 my_png_error (png_struct *png_ptr, const char *msg)
5537 xassert (png_ptr != NULL);
5538 /* Avoid compiler warning about deprecated direct access to
5539 png_ptr's fields in libpng versions 1.4.x. */
5540 image_error ("PNG error: %s", build_string (msg), Qnil);
5541 longjmp (png_ptr->jmpbuf, 1);
5545 static void
5546 my_png_warning (png_struct *png_ptr, const char *msg)
5548 xassert (png_ptr != NULL);
5549 image_error ("PNG warning: %s", build_string (msg), Qnil);
5552 /* Memory source for PNG decoding. */
5554 struct png_memory_storage
5556 unsigned char *bytes; /* The data */
5557 size_t len; /* How big is it? */
5558 int index; /* Where are we? */
5562 /* Function set as reader function when reading PNG image from memory.
5563 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5564 bytes from the input to DATA. */
5566 static void
5567 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5569 struct png_memory_storage *tbr
5570 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5572 if (length > tbr->len - tbr->index)
5573 fn_png_error (png_ptr, "Read error");
5575 memcpy (data, tbr->bytes + tbr->index, length);
5576 tbr->index = tbr->index + length;
5580 /* Function set as reader function when reading PNG image from a file.
5581 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5582 bytes from the input to DATA. */
5584 static void
5585 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5587 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5589 if (fread (data, 1, length, fp) < length)
5590 fn_png_error (png_ptr, "Read error");
5594 /* Load PNG image IMG for use on frame F. Value is non-zero if
5595 successful. */
5597 static int
5598 png_load (struct frame *f, struct image *img)
5600 Lisp_Object file, specified_file;
5601 Lisp_Object specified_data;
5602 int x, y, i;
5603 XImagePtr ximg, mask_img = NULL;
5604 png_struct *png_ptr = NULL;
5605 png_info *info_ptr = NULL, *end_info = NULL;
5606 FILE *volatile fp = NULL;
5607 png_byte sig[8];
5608 png_byte * volatile pixels = NULL;
5609 png_byte ** volatile rows = NULL;
5610 png_uint_32 width, height;
5611 int bit_depth, color_type, interlace_type;
5612 png_byte channels;
5613 png_uint_32 row_bytes;
5614 int transparent_p;
5615 struct png_memory_storage tbr; /* Data to be read */
5617 /* Find out what file to load. */
5618 specified_file = image_spec_value (img->spec, QCfile, NULL);
5619 specified_data = image_spec_value (img->spec, QCdata, NULL);
5621 if (NILP (specified_data))
5623 file = x_find_image_file (specified_file);
5624 if (!STRINGP (file))
5626 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5627 return 0;
5630 /* Open the image file. */
5631 fp = fopen (SDATA (file), "rb");
5632 if (!fp)
5634 image_error ("Cannot open image file `%s'", file, Qnil);
5635 return 0;
5638 /* Check PNG signature. */
5639 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5640 || fn_png_sig_cmp (sig, 0, sizeof sig))
5642 image_error ("Not a PNG file: `%s'", file, Qnil);
5643 fclose (fp);
5644 return 0;
5647 else
5649 if (!STRINGP (specified_data))
5651 image_error ("Invalid image data `%s'", specified_data, Qnil);
5652 return 0;
5655 /* Read from memory. */
5656 tbr.bytes = SDATA (specified_data);
5657 tbr.len = SBYTES (specified_data);
5658 tbr.index = 0;
5660 /* Check PNG signature. */
5661 if (tbr.len < sizeof sig
5662 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5664 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5665 return 0;
5668 /* Need to skip past the signature. */
5669 tbr.bytes += sizeof (sig);
5672 /* Initialize read and info structs for PNG lib. Casting return
5673 value avoids a GCC warning on W32. */
5674 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5675 NULL, my_png_error,
5676 my_png_warning);
5677 if (!png_ptr)
5679 if (fp) fclose (fp);
5680 return 0;
5683 /* Casting return value avoids a GCC warning on W32. */
5684 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
5685 if (!info_ptr)
5687 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5688 if (fp) fclose (fp);
5689 return 0;
5692 /* Casting return value avoids a GCC warning on W32. */
5693 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
5694 if (!end_info)
5696 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5697 if (fp) fclose (fp);
5698 return 0;
5701 /* Set error jump-back. We come back here when the PNG library
5702 detects an error. */
5703 if (setjmp (png_ptr->jmpbuf))
5705 error:
5706 if (png_ptr)
5707 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5708 xfree (pixels);
5709 xfree (rows);
5710 if (fp) fclose (fp);
5711 return 0;
5714 /* Read image info. */
5715 if (!NILP (specified_data))
5716 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5717 else
5718 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5720 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5721 fn_png_read_info (png_ptr, info_ptr);
5722 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5723 &interlace_type, NULL, NULL);
5725 if (!check_image_size (f, width, height))
5727 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5728 goto error;
5730 /* If image contains simply transparency data, we prefer to
5731 construct a clipping mask. */
5732 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5733 transparent_p = 1;
5734 else
5735 transparent_p = 0;
5737 /* This function is easier to write if we only have to handle
5738 one data format: RGB or RGBA with 8 bits per channel. Let's
5739 transform other formats into that format. */
5741 /* Strip more than 8 bits per channel. */
5742 if (bit_depth == 16)
5743 fn_png_set_strip_16 (png_ptr);
5745 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5746 if available. */
5747 fn_png_set_expand (png_ptr);
5749 /* Convert grayscale images to RGB. */
5750 if (color_type == PNG_COLOR_TYPE_GRAY
5751 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5752 fn_png_set_gray_to_rgb (png_ptr);
5754 /* Handle alpha channel by combining the image with a background
5755 color. Do this only if a real alpha channel is supplied. For
5756 simple transparency, we prefer a clipping mask. */
5757 if (!transparent_p)
5759 /* png_color_16 *image_bg; */
5760 Lisp_Object specified_bg
5761 = image_spec_value (img->spec, QCbackground, NULL);
5762 int shift = (bit_depth == 16) ? 0 : 8;
5764 if (STRINGP (specified_bg))
5765 /* The user specified `:background', use that. */
5767 XColor color;
5768 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
5770 png_color_16 user_bg;
5772 memset (&user_bg, 0, sizeof user_bg);
5773 user_bg.red = color.red >> shift;
5774 user_bg.green = color.green >> shift;
5775 user_bg.blue = color.blue >> shift;
5777 fn_png_set_background (png_ptr, &user_bg,
5778 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5781 else
5783 /* We use the current frame background, ignoring any default
5784 background color set by the image. */
5785 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5786 XColor color;
5787 png_color_16 frame_background;
5789 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5790 x_query_color (f, &color);
5792 memset (&frame_background, 0, sizeof frame_background);
5793 frame_background.red = color.red >> shift;
5794 frame_background.green = color.green >> shift;
5795 frame_background.blue = color.blue >> shift;
5796 #endif /* HAVE_X_WINDOWS */
5798 fn_png_set_background (png_ptr, &frame_background,
5799 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5803 /* Update info structure. */
5804 fn_png_read_update_info (png_ptr, info_ptr);
5806 /* Get number of channels. Valid values are 1 for grayscale images
5807 and images with a palette, 2 for grayscale images with transparency
5808 information (alpha channel), 3 for RGB images, and 4 for RGB
5809 images with alpha channel, i.e. RGBA. If conversions above were
5810 sufficient we should only have 3 or 4 channels here. */
5811 channels = fn_png_get_channels (png_ptr, info_ptr);
5812 xassert (channels == 3 || channels == 4);
5814 /* Number of bytes needed for one row of the image. */
5815 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5817 /* Allocate memory for the image. */
5818 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
5819 rows = (png_byte **) xmalloc (height * sizeof *rows);
5820 for (i = 0; i < height; ++i)
5821 rows[i] = pixels + i * row_bytes;
5823 /* Read the entire image. */
5824 fn_png_read_image (png_ptr, rows);
5825 fn_png_read_end (png_ptr, info_ptr);
5826 if (fp)
5828 fclose (fp);
5829 fp = NULL;
5832 /* Create the X image and pixmap. */
5833 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5834 &img->pixmap))
5835 goto error;
5837 /* Create an image and pixmap serving as mask if the PNG image
5838 contains an alpha channel. */
5839 if (channels == 4
5840 && !transparent_p
5841 && !x_create_x_image_and_pixmap (f, width, height, 1,
5842 &mask_img, &img->mask))
5844 x_destroy_x_image (ximg);
5845 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5846 img->pixmap = NO_PIXMAP;
5847 goto error;
5850 /* Fill the X image and mask from PNG data. */
5851 init_color_table ();
5853 for (y = 0; y < height; ++y)
5855 png_byte *p = rows[y];
5857 for (x = 0; x < width; ++x)
5859 unsigned r, g, b;
5861 r = *p++ << 8;
5862 g = *p++ << 8;
5863 b = *p++ << 8;
5864 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5865 /* An alpha channel, aka mask channel, associates variable
5866 transparency with an image. Where other image formats
5867 support binary transparency---fully transparent or fully
5868 opaque---PNG allows up to 254 levels of partial transparency.
5869 The PNG library implements partial transparency by combining
5870 the image with a specified background color.
5872 I'm not sure how to handle this here nicely: because the
5873 background on which the image is displayed may change, for
5874 real alpha channel support, it would be necessary to create
5875 a new image for each possible background.
5877 What I'm doing now is that a mask is created if we have
5878 boolean transparency information. Otherwise I'm using
5879 the frame's background color to combine the image with. */
5881 if (channels == 4)
5883 if (mask_img)
5884 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5885 ++p;
5890 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5891 /* Set IMG's background color from the PNG image, unless the user
5892 overrode it. */
5894 png_color_16 *bg;
5895 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5897 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5898 img->background_valid = 1;
5902 #ifdef COLOR_TABLE_SUPPORT
5903 /* Remember colors allocated for this image. */
5904 img->colors = colors_in_color_table (&img->ncolors);
5905 free_color_table ();
5906 #endif /* COLOR_TABLE_SUPPORT */
5908 /* Clean up. */
5909 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5910 xfree (rows);
5911 xfree (pixels);
5913 img->width = width;
5914 img->height = height;
5916 /* Maybe fill in the background field while we have ximg handy.
5917 Casting avoids a GCC warning. */
5918 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5920 /* Put the image into the pixmap, then free the X image and its buffer. */
5921 x_put_x_image (f, ximg, img->pixmap, width, height);
5922 x_destroy_x_image (ximg);
5924 /* Same for the mask. */
5925 if (mask_img)
5927 /* Fill in the background_transparent field while we have the
5928 mask handy. Casting avoids a GCC warning. */
5929 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
5931 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5932 x_destroy_x_image (mask_img);
5935 return 1;
5938 #else /* HAVE_PNG */
5940 #ifdef HAVE_NS
5941 static int
5942 png_load (struct frame *f, struct image *img)
5944 return ns_load_image(f, img,
5945 image_spec_value (img->spec, QCfile, NULL),
5946 image_spec_value (img->spec, QCdata, NULL));
5948 #endif /* HAVE_NS */
5951 #endif /* !HAVE_PNG */
5955 /***********************************************************************
5956 JPEG
5957 ***********************************************************************/
5959 #if defined (HAVE_JPEG) || defined (HAVE_NS)
5961 static int jpeg_image_p (Lisp_Object object);
5962 static int jpeg_load (struct frame *f, struct image *img);
5964 /* The symbol `jpeg' identifying images of this type. */
5966 Lisp_Object Qjpeg;
5968 /* Indices of image specification fields in gs_format, below. */
5970 enum jpeg_keyword_index
5972 JPEG_TYPE,
5973 JPEG_DATA,
5974 JPEG_FILE,
5975 JPEG_ASCENT,
5976 JPEG_MARGIN,
5977 JPEG_RELIEF,
5978 JPEG_ALGORITHM,
5979 JPEG_HEURISTIC_MASK,
5980 JPEG_MASK,
5981 JPEG_BACKGROUND,
5982 JPEG_LAST
5985 /* Vector of image_keyword structures describing the format
5986 of valid user-defined image specifications. */
5988 static const struct image_keyword jpeg_format[JPEG_LAST] =
5990 {":type", IMAGE_SYMBOL_VALUE, 1},
5991 {":data", IMAGE_STRING_VALUE, 0},
5992 {":file", IMAGE_STRING_VALUE, 0},
5993 {":ascent", IMAGE_ASCENT_VALUE, 0},
5994 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5995 {":relief", IMAGE_INTEGER_VALUE, 0},
5996 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5997 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5998 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5999 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6002 /* Structure describing the image type `jpeg'. */
6004 static struct image_type jpeg_type =
6006 &Qjpeg,
6007 jpeg_image_p,
6008 jpeg_load,
6009 x_clear_image,
6010 NULL
6013 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6015 static int
6016 jpeg_image_p (Lisp_Object object)
6018 struct image_keyword fmt[JPEG_LAST];
6020 memcpy (fmt, jpeg_format, sizeof fmt);
6022 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6023 return 0;
6025 /* Must specify either the :data or :file keyword. */
6026 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6029 #endif /* HAVE_JPEG || HAVE_NS */
6031 #ifdef HAVE_JPEG
6033 /* Work around a warning about HAVE_STDLIB_H being redefined in
6034 jconfig.h. */
6035 #ifdef HAVE_STDLIB_H
6036 #define HAVE_STDLIB_H_1
6037 #undef HAVE_STDLIB_H
6038 #endif /* HAVE_STLIB_H */
6040 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6041 /* In older releases of the jpeg library, jpeglib.h will define boolean
6042 differently depending on __WIN32__, so make sure it is defined. */
6043 #define __WIN32__ 1
6044 #endif
6046 #include <jpeglib.h>
6047 #include <jerror.h>
6049 #ifdef HAVE_STLIB_H_1
6050 #define HAVE_STDLIB_H 1
6051 #endif
6053 #ifdef HAVE_NTGUI
6055 /* JPEG library details. */
6056 DEF_IMGLIB_FN (jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6057 DEF_IMGLIB_FN (jpeg_start_decompress, (j_decompress_ptr));
6058 DEF_IMGLIB_FN (jpeg_finish_decompress, (j_decompress_ptr));
6059 DEF_IMGLIB_FN (jpeg_destroy_decompress, (j_decompress_ptr));
6060 DEF_IMGLIB_FN (jpeg_read_header, (j_decompress_ptr, boolean));
6061 DEF_IMGLIB_FN (jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6062 DEF_IMGLIB_FN (jpeg_std_error, (struct jpeg_error_mgr *));
6063 DEF_IMGLIB_FN (jpeg_resync_to_restart, (j_decompress_ptr, int));
6065 static int
6066 init_jpeg_functions (Lisp_Object libraries)
6068 HMODULE library;
6070 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6071 return 0;
6073 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6074 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6075 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6076 LOAD_IMGLIB_FN (library, jpeg_read_header);
6077 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6078 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6079 LOAD_IMGLIB_FN (library, jpeg_std_error);
6080 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6081 return 1;
6084 /* Wrapper since we can't directly assign the function pointer
6085 to another function pointer that was declared more completely easily. */
6086 static boolean
6087 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6089 return fn_jpeg_resync_to_restart (cinfo, desired);
6092 #else
6094 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6095 #define fn_jpeg_start_decompress jpeg_start_decompress
6096 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6097 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6098 #define fn_jpeg_read_header jpeg_read_header
6099 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6100 #define fn_jpeg_std_error jpeg_std_error
6101 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6103 #endif /* HAVE_NTGUI */
6105 struct my_jpeg_error_mgr
6107 struct jpeg_error_mgr pub;
6108 jmp_buf setjmp_buffer;
6112 static void
6113 my_error_exit (j_common_ptr cinfo)
6115 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6116 longjmp (mgr->setjmp_buffer, 1);
6120 /* Init source method for JPEG data source manager. Called by
6121 jpeg_read_header() before any data is actually read. See
6122 libjpeg.doc from the JPEG lib distribution. */
6124 static void
6125 our_common_init_source (j_decompress_ptr cinfo)
6130 /* Method to terminate data source. Called by
6131 jpeg_finish_decompress() after all data has been processed. */
6133 static void
6134 our_common_term_source (j_decompress_ptr cinfo)
6139 /* Fill input buffer method for JPEG data source manager. Called
6140 whenever more data is needed. We read the whole image in one step,
6141 so this only adds a fake end of input marker at the end. */
6143 static JOCTET our_memory_buffer[2];
6145 static boolean
6146 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6148 /* Insert a fake EOI marker. */
6149 struct jpeg_source_mgr *src = cinfo->src;
6151 our_memory_buffer[0] = (JOCTET) 0xFF;
6152 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6154 src->next_input_byte = our_memory_buffer;
6155 src->bytes_in_buffer = 2;
6156 return 1;
6160 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6161 is the JPEG data source manager. */
6163 static void
6164 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6166 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6168 if (src)
6170 if (num_bytes > src->bytes_in_buffer)
6171 ERREXIT (cinfo, JERR_INPUT_EOF);
6173 src->bytes_in_buffer -= num_bytes;
6174 src->next_input_byte += num_bytes;
6179 /* Set up the JPEG lib for reading an image from DATA which contains
6180 LEN bytes. CINFO is the decompression info structure created for
6181 reading the image. */
6183 static void
6184 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, unsigned int len)
6186 struct jpeg_source_mgr *src;
6188 if (cinfo->src == NULL)
6190 /* First time for this JPEG object? */
6191 cinfo->src = (struct jpeg_source_mgr *)
6192 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6193 sizeof (struct jpeg_source_mgr));
6194 src = (struct jpeg_source_mgr *) cinfo->src;
6195 src->next_input_byte = data;
6198 src = (struct jpeg_source_mgr *) cinfo->src;
6199 src->init_source = our_common_init_source;
6200 src->fill_input_buffer = our_memory_fill_input_buffer;
6201 src->skip_input_data = our_memory_skip_input_data;
6202 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6203 src->term_source = our_common_term_source;
6204 src->bytes_in_buffer = len;
6205 src->next_input_byte = data;
6209 struct jpeg_stdio_mgr
6211 struct jpeg_source_mgr mgr;
6212 boolean finished;
6213 FILE *file;
6214 JOCTET *buffer;
6218 /* Size of buffer to read JPEG from file.
6219 Not too big, as we want to use alloc_small. */
6220 #define JPEG_STDIO_BUFFER_SIZE 8192
6223 /* Fill input buffer method for JPEG data source manager. Called
6224 whenever more data is needed. The data is read from a FILE *. */
6226 static boolean
6227 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6229 struct jpeg_stdio_mgr *src;
6231 src = (struct jpeg_stdio_mgr *) cinfo->src;
6232 if (!src->finished)
6234 size_t bytes;
6236 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6237 if (bytes > 0)
6238 src->mgr.bytes_in_buffer = bytes;
6239 else
6241 WARNMS (cinfo, JWRN_JPEG_EOF);
6242 src->finished = 1;
6243 src->buffer[0] = (JOCTET) 0xFF;
6244 src->buffer[1] = (JOCTET) JPEG_EOI;
6245 src->mgr.bytes_in_buffer = 2;
6247 src->mgr.next_input_byte = src->buffer;
6250 return 1;
6254 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6255 is the JPEG data source manager. */
6257 static void
6258 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6260 struct jpeg_stdio_mgr *src;
6261 src = (struct jpeg_stdio_mgr *) cinfo->src;
6263 while (num_bytes > 0 && !src->finished)
6265 if (num_bytes <= src->mgr.bytes_in_buffer)
6267 src->mgr.bytes_in_buffer -= num_bytes;
6268 src->mgr.next_input_byte += num_bytes;
6269 break;
6271 else
6273 num_bytes -= src->mgr.bytes_in_buffer;
6274 src->mgr.bytes_in_buffer = 0;
6275 src->mgr.next_input_byte = NULL;
6277 our_stdio_fill_input_buffer (cinfo);
6283 /* Set up the JPEG lib for reading an image from a FILE *.
6284 CINFO is the decompression info structure created for
6285 reading the image. */
6287 static void
6288 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6290 struct jpeg_stdio_mgr *src;
6292 if (cinfo->src != NULL)
6293 src = (struct jpeg_stdio_mgr *) cinfo->src;
6294 else
6296 /* First time for this JPEG object? */
6297 cinfo->src = (struct jpeg_source_mgr *)
6298 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6299 sizeof (struct jpeg_stdio_mgr));
6300 src = (struct jpeg_stdio_mgr *) cinfo->src;
6301 src->buffer = (JOCTET *)
6302 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6303 JPEG_STDIO_BUFFER_SIZE);
6306 src->file = fp;
6307 src->finished = 0;
6308 src->mgr.init_source = our_common_init_source;
6309 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6310 src->mgr.skip_input_data = our_stdio_skip_input_data;
6311 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6312 src->mgr.term_source = our_common_term_source;
6313 src->mgr.bytes_in_buffer = 0;
6314 src->mgr.next_input_byte = NULL;
6318 /* Load image IMG for use on frame F. Patterned after example.c
6319 from the JPEG lib. */
6321 static int
6322 jpeg_load (struct frame *f, struct image *img)
6324 struct jpeg_decompress_struct cinfo;
6325 struct my_jpeg_error_mgr mgr;
6326 Lisp_Object file, specified_file;
6327 Lisp_Object specified_data;
6328 FILE * volatile fp = NULL;
6329 JSAMPARRAY buffer;
6330 int row_stride, x, y;
6331 XImagePtr ximg = NULL;
6332 int rc;
6333 unsigned long *colors;
6334 int width, height;
6336 /* Open the JPEG file. */
6337 specified_file = image_spec_value (img->spec, QCfile, NULL);
6338 specified_data = image_spec_value (img->spec, QCdata, NULL);
6340 if (NILP (specified_data))
6342 file = x_find_image_file (specified_file);
6343 if (!STRINGP (file))
6345 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6346 return 0;
6349 fp = fopen (SDATA (file), "rb");
6350 if (fp == NULL)
6352 image_error ("Cannot open `%s'", file, Qnil);
6353 return 0;
6356 else if (!STRINGP (specified_data))
6358 image_error ("Invalid image data `%s'", specified_data, Qnil);
6359 return 0;
6362 /* Customize libjpeg's error handling to call my_error_exit when an
6363 error is detected. This function will perform a longjmp.
6364 Casting return value avoids a GCC warning on W32. */
6365 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
6366 mgr.pub.error_exit = my_error_exit;
6368 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6370 if (rc == 1)
6372 /* Called from my_error_exit. Display a JPEG error. */
6373 char buffer[JMSG_LENGTH_MAX];
6374 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
6375 image_error ("Error reading JPEG image `%s': %s", img->spec,
6376 build_string (buffer));
6379 /* Close the input file and destroy the JPEG object. */
6380 if (fp)
6381 fclose ((FILE *) fp);
6382 fn_jpeg_destroy_decompress (&cinfo);
6384 /* If we already have an XImage, free that. */
6385 x_destroy_x_image (ximg);
6387 /* Free pixmap and colors. */
6388 x_clear_image (f, img);
6389 return 0;
6392 /* Create the JPEG decompression object. Let it read from fp.
6393 Read the JPEG image header. */
6394 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6396 if (NILP (specified_data))
6397 jpeg_file_src (&cinfo, (FILE *) fp);
6398 else
6399 jpeg_memory_src (&cinfo, SDATA (specified_data),
6400 SBYTES (specified_data));
6402 fn_jpeg_read_header (&cinfo, 1);
6404 /* Customize decompression so that color quantization will be used.
6405 Start decompression. */
6406 cinfo.quantize_colors = 1;
6407 fn_jpeg_start_decompress (&cinfo);
6408 width = img->width = cinfo.output_width;
6409 height = img->height = cinfo.output_height;
6411 if (!check_image_size (f, width, height))
6413 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6414 longjmp (mgr.setjmp_buffer, 2);
6417 /* Create X image and pixmap. */
6418 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6419 longjmp (mgr.setjmp_buffer, 2);
6421 /* Allocate colors. When color quantization is used,
6422 cinfo.actual_number_of_colors has been set with the number of
6423 colors generated, and cinfo.colormap is a two-dimensional array
6424 of color indices in the range 0..cinfo.actual_number_of_colors.
6425 No more than 255 colors will be generated. */
6427 int i, ir, ig, ib;
6429 if (cinfo.out_color_components > 2)
6430 ir = 0, ig = 1, ib = 2;
6431 else if (cinfo.out_color_components > 1)
6432 ir = 0, ig = 1, ib = 0;
6433 else
6434 ir = 0, ig = 0, ib = 0;
6436 /* Use the color table mechanism because it handles colors that
6437 cannot be allocated nicely. Such colors will be replaced with
6438 a default color, and we don't have to care about which colors
6439 can be freed safely, and which can't. */
6440 init_color_table ();
6441 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6442 * sizeof *colors);
6444 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6446 /* Multiply RGB values with 255 because X expects RGB values
6447 in the range 0..0xffff. */
6448 int r = cinfo.colormap[ir][i] << 8;
6449 int g = cinfo.colormap[ig][i] << 8;
6450 int b = cinfo.colormap[ib][i] << 8;
6451 colors[i] = lookup_rgb_color (f, r, g, b);
6454 #ifdef COLOR_TABLE_SUPPORT
6455 /* Remember those colors actually allocated. */
6456 img->colors = colors_in_color_table (&img->ncolors);
6457 free_color_table ();
6458 #endif /* COLOR_TABLE_SUPPORT */
6461 /* Read pixels. */
6462 row_stride = width * cinfo.output_components;
6463 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6464 row_stride, 1);
6465 for (y = 0; y < height; ++y)
6467 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6468 for (x = 0; x < cinfo.output_width; ++x)
6469 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6472 /* Clean up. */
6473 fn_jpeg_finish_decompress (&cinfo);
6474 fn_jpeg_destroy_decompress (&cinfo);
6475 if (fp)
6476 fclose ((FILE *) fp);
6478 /* Maybe fill in the background field while we have ximg handy. */
6479 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6480 /* Casting avoids a GCC warning. */
6481 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6483 /* Put the image into the pixmap. */
6484 x_put_x_image (f, ximg, img->pixmap, width, height);
6485 x_destroy_x_image (ximg);
6486 return 1;
6489 #else /* HAVE_JPEG */
6491 #ifdef HAVE_NS
6492 static int
6493 jpeg_load (struct frame *f, struct image *img)
6495 return ns_load_image (f, img,
6496 image_spec_value (img->spec, QCfile, NULL),
6497 image_spec_value (img->spec, QCdata, NULL));
6499 #endif /* HAVE_NS */
6501 #endif /* !HAVE_JPEG */
6505 /***********************************************************************
6506 TIFF
6507 ***********************************************************************/
6509 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6511 static int tiff_image_p (Lisp_Object object);
6512 static int tiff_load (struct frame *f, struct image *img);
6514 /* The symbol `tiff' identifying images of this type. */
6516 Lisp_Object Qtiff;
6518 /* Indices of image specification fields in tiff_format, below. */
6520 enum tiff_keyword_index
6522 TIFF_TYPE,
6523 TIFF_DATA,
6524 TIFF_FILE,
6525 TIFF_ASCENT,
6526 TIFF_MARGIN,
6527 TIFF_RELIEF,
6528 TIFF_ALGORITHM,
6529 TIFF_HEURISTIC_MASK,
6530 TIFF_MASK,
6531 TIFF_BACKGROUND,
6532 TIFF_INDEX,
6533 TIFF_LAST
6536 /* Vector of image_keyword structures describing the format
6537 of valid user-defined image specifications. */
6539 static const struct image_keyword tiff_format[TIFF_LAST] =
6541 {":type", IMAGE_SYMBOL_VALUE, 1},
6542 {":data", IMAGE_STRING_VALUE, 0},
6543 {":file", IMAGE_STRING_VALUE, 0},
6544 {":ascent", IMAGE_ASCENT_VALUE, 0},
6545 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6546 {":relief", IMAGE_INTEGER_VALUE, 0},
6547 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6548 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6549 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6550 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6551 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6554 /* Structure describing the image type `tiff'. */
6556 static struct image_type tiff_type =
6558 &Qtiff,
6559 tiff_image_p,
6560 tiff_load,
6561 x_clear_image,
6562 NULL
6565 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6567 static int
6568 tiff_image_p (Lisp_Object object)
6570 struct image_keyword fmt[TIFF_LAST];
6571 memcpy (fmt, tiff_format, sizeof fmt);
6573 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6574 return 0;
6576 /* Must specify either the :data or :file keyword. */
6577 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6580 #endif /* HAVE_TIFF || HAVE_NS */
6582 #ifdef HAVE_TIFF
6584 #include <tiffio.h>
6586 #ifdef HAVE_NTGUI
6588 /* TIFF library details. */
6589 DEF_IMGLIB_FN (TIFFSetErrorHandler, (TIFFErrorHandler));
6590 DEF_IMGLIB_FN (TIFFSetWarningHandler, (TIFFErrorHandler));
6591 DEF_IMGLIB_FN (TIFFOpen, (const char *, const char *));
6592 DEF_IMGLIB_FN (TIFFClientOpen, (const char *, const char *, thandle_t,
6593 TIFFReadWriteProc, TIFFReadWriteProc,
6594 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6595 TIFFMapFileProc, TIFFUnmapFileProc));
6596 DEF_IMGLIB_FN (TIFFGetField, (TIFF *, ttag_t, ...));
6597 DEF_IMGLIB_FN (TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6598 DEF_IMGLIB_FN (TIFFClose, (TIFF *));
6599 DEF_IMGLIB_FN (TIFFSetDirectory, (TIFF *, tdir_t));
6601 static int
6602 init_tiff_functions (Lisp_Object libraries)
6604 HMODULE library;
6606 if (!(library = w32_delayed_load (libraries, Qtiff)))
6607 return 0;
6609 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6610 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6611 LOAD_IMGLIB_FN (library, TIFFOpen);
6612 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6613 LOAD_IMGLIB_FN (library, TIFFGetField);
6614 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6615 LOAD_IMGLIB_FN (library, TIFFClose);
6616 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6617 return 1;
6620 #else
6622 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6623 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6624 #define fn_TIFFOpen TIFFOpen
6625 #define fn_TIFFClientOpen TIFFClientOpen
6626 #define fn_TIFFGetField TIFFGetField
6627 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6628 #define fn_TIFFClose TIFFClose
6629 #define fn_TIFFSetDirectory TIFFSetDirectory
6630 #endif /* HAVE_NTGUI */
6633 /* Reading from a memory buffer for TIFF images Based on the PNG
6634 memory source, but we have to provide a lot of extra functions.
6635 Blah.
6637 We really only need to implement read and seek, but I am not
6638 convinced that the TIFF library is smart enough not to destroy
6639 itself if we only hand it the function pointers we need to
6640 override. */
6642 typedef struct
6644 unsigned char *bytes;
6645 size_t len;
6646 int index;
6648 tiff_memory_source;
6650 static size_t
6651 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6653 tiff_memory_source *src = (tiff_memory_source *) data;
6655 if (size > src->len - src->index)
6656 return (size_t) -1;
6657 memcpy (buf, src->bytes + src->index, size);
6658 src->index += size;
6659 return size;
6662 static size_t
6663 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6665 return (size_t) -1;
6668 static toff_t
6669 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6671 tiff_memory_source *src = (tiff_memory_source *) data;
6672 int idx;
6674 switch (whence)
6676 case SEEK_SET: /* Go from beginning of source. */
6677 idx = off;
6678 break;
6680 case SEEK_END: /* Go from end of source. */
6681 idx = src->len + off;
6682 break;
6684 case SEEK_CUR: /* Go from current position. */
6685 idx = src->index + off;
6686 break;
6688 default: /* Invalid `whence'. */
6689 return -1;
6692 if (idx > src->len || idx < 0)
6693 return -1;
6695 src->index = idx;
6696 return src->index;
6699 static int
6700 tiff_close_memory (thandle_t data)
6702 /* NOOP */
6703 return 0;
6706 static int
6707 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6709 /* It is already _IN_ memory. */
6710 return 0;
6713 static void
6714 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6716 /* We don't need to do this. */
6719 static toff_t
6720 tiff_size_of_memory (thandle_t data)
6722 return ((tiff_memory_source *) data)->len;
6726 static void
6727 tiff_error_handler (const char *title, const char *format, va_list ap)
6729 char buf[512];
6730 int len;
6732 len = sprintf (buf, "TIFF error: %s ", title);
6733 vsprintf (buf + len, format, ap);
6734 add_to_log (buf, Qnil, Qnil);
6738 static void
6739 tiff_warning_handler (const char *title, const char *format, va_list ap)
6741 char buf[512];
6742 int len;
6744 len = sprintf (buf, "TIFF warning: %s ", title);
6745 vsprintf (buf + len, format, ap);
6746 add_to_log (buf, Qnil, Qnil);
6750 /* Load TIFF image IMG for use on frame F. Value is non-zero if
6751 successful. */
6753 static int
6754 tiff_load (struct frame *f, struct image *img)
6756 Lisp_Object file, specified_file;
6757 Lisp_Object specified_data;
6758 TIFF *tiff;
6759 int width, height, x, y, count;
6760 uint32 *buf;
6761 int rc, rc2;
6762 XImagePtr ximg;
6763 tiff_memory_source memsrc;
6764 Lisp_Object image;
6766 specified_file = image_spec_value (img->spec, QCfile, NULL);
6767 specified_data = image_spec_value (img->spec, QCdata, NULL);
6769 fn_TIFFSetErrorHandler (tiff_error_handler);
6770 fn_TIFFSetWarningHandler (tiff_warning_handler);
6772 if (NILP (specified_data))
6774 /* Read from a file */
6775 file = x_find_image_file (specified_file);
6776 if (!STRINGP (file))
6778 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6779 return 0;
6782 /* Try to open the image file. Casting return value avoids a
6783 GCC warning on W32. */
6784 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
6785 if (tiff == NULL)
6787 image_error ("Cannot open `%s'", file, Qnil);
6788 return 0;
6791 else
6793 if (!STRINGP (specified_data))
6795 image_error ("Invalid image data `%s'", specified_data, Qnil);
6796 return 0;
6799 /* Memory source! */
6800 memsrc.bytes = SDATA (specified_data);
6801 memsrc.len = SBYTES (specified_data);
6802 memsrc.index = 0;
6804 /* Casting arguments return value avoids a GCC warning on W32. */
6805 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r",
6806 (thandle_t) &memsrc,
6807 (TIFFReadWriteProc) tiff_read_from_memory,
6808 (TIFFReadWriteProc) tiff_write_from_memory,
6809 tiff_seek_in_memory,
6810 tiff_close_memory,
6811 tiff_size_of_memory,
6812 tiff_mmap_memory,
6813 tiff_unmap_memory);
6815 if (!tiff)
6817 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6818 return 0;
6822 image = image_spec_value (img->spec, QCindex, NULL);
6823 if (INTEGERP (image))
6825 int ino = XFASTINT (image);
6826 if (!fn_TIFFSetDirectory (tiff, ino))
6828 image_error ("Invalid image number `%s' in image `%s'",
6829 image, img->spec);
6830 fn_TIFFClose (tiff);
6831 return 0;
6835 /* Get width and height of the image, and allocate a raster buffer
6836 of width x height 32-bit values. */
6837 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6838 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6840 if (!check_image_size (f, width, height))
6842 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6843 fn_TIFFClose (tiff);
6844 return 0;
6847 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
6849 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
6851 /* Count the number of images in the file. */
6852 for (count = 1, rc2 = 1; rc2; count++)
6853 rc2 = fn_TIFFSetDirectory (tiff, count);
6855 if (count > 1)
6856 img->data.lisp_val = Fcons (Qcount,
6857 Fcons (make_number (count),
6858 img->data.lisp_val));
6860 fn_TIFFClose (tiff);
6861 if (!rc)
6863 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6864 xfree (buf);
6865 return 0;
6868 /* Create the X image and pixmap. */
6869 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6871 xfree (buf);
6872 return 0;
6875 /* Initialize the color table. */
6876 init_color_table ();
6878 /* Process the pixel raster. Origin is in the lower-left corner. */
6879 for (y = 0; y < height; ++y)
6881 uint32 *row = buf + y * width;
6883 for (x = 0; x < width; ++x)
6885 uint32 abgr = row[x];
6886 int r = TIFFGetR (abgr) << 8;
6887 int g = TIFFGetG (abgr) << 8;
6888 int b = TIFFGetB (abgr) << 8;
6889 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6893 #ifdef COLOR_TABLE_SUPPORT
6894 /* Remember the colors allocated for the image. Free the color table. */
6895 img->colors = colors_in_color_table (&img->ncolors);
6896 free_color_table ();
6897 #endif /* COLOR_TABLE_SUPPORT */
6899 img->width = width;
6900 img->height = height;
6902 /* Maybe fill in the background field while we have ximg handy. */
6903 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6904 /* Casting avoids a GCC warning on W32. */
6905 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6907 /* Put the image into the pixmap, then free the X image and its buffer. */
6908 x_put_x_image (f, ximg, img->pixmap, width, height);
6909 x_destroy_x_image (ximg);
6910 xfree (buf);
6912 return 1;
6915 #else /* HAVE_TIFF */
6917 #ifdef HAVE_NS
6918 static int
6919 tiff_load (struct frame *f, struct image *img)
6921 return ns_load_image (f, img,
6922 image_spec_value (img->spec, QCfile, NULL),
6923 image_spec_value (img->spec, QCdata, NULL));
6925 #endif /* HAVE_NS */
6927 #endif /* !HAVE_TIFF */
6931 /***********************************************************************
6933 ***********************************************************************/
6935 #if defined (HAVE_GIF) || defined (HAVE_NS)
6937 static int gif_image_p (Lisp_Object object);
6938 static int gif_load (struct frame *f, struct image *img);
6939 static void gif_clear_image (struct frame *f, struct image *img);
6941 /* The symbol `gif' identifying images of this type. */
6943 Lisp_Object Qgif;
6945 /* Indices of image specification fields in gif_format, below. */
6947 enum gif_keyword_index
6949 GIF_TYPE,
6950 GIF_DATA,
6951 GIF_FILE,
6952 GIF_ASCENT,
6953 GIF_MARGIN,
6954 GIF_RELIEF,
6955 GIF_ALGORITHM,
6956 GIF_HEURISTIC_MASK,
6957 GIF_MASK,
6958 GIF_IMAGE,
6959 GIF_BACKGROUND,
6960 GIF_LAST
6963 /* Vector of image_keyword structures describing the format
6964 of valid user-defined image specifications. */
6966 static const struct image_keyword gif_format[GIF_LAST] =
6968 {":type", IMAGE_SYMBOL_VALUE, 1},
6969 {":data", IMAGE_STRING_VALUE, 0},
6970 {":file", IMAGE_STRING_VALUE, 0},
6971 {":ascent", IMAGE_ASCENT_VALUE, 0},
6972 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6973 {":relief", IMAGE_INTEGER_VALUE, 0},
6974 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6975 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6976 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6977 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
6978 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6981 /* Structure describing the image type `gif'. */
6983 static struct image_type gif_type =
6985 &Qgif,
6986 gif_image_p,
6987 gif_load,
6988 gif_clear_image,
6989 NULL
6992 /* Free X resources of GIF image IMG which is used on frame F. */
6994 static void
6995 gif_clear_image (struct frame *f, struct image *img)
6997 /* IMG->data.ptr_val may contain metadata with extension data. */
6998 img->data.lisp_val = Qnil;
6999 x_clear_image (f, img);
7002 /* Return non-zero if OBJECT is a valid GIF image specification. */
7004 static int
7005 gif_image_p (Lisp_Object object)
7007 struct image_keyword fmt[GIF_LAST];
7008 memcpy (fmt, gif_format, sizeof fmt);
7010 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7011 return 0;
7013 /* Must specify either the :data or :file keyword. */
7014 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7017 #endif /* HAVE_GIF */
7019 #ifdef HAVE_GIF
7021 #if defined (HAVE_NTGUI)
7022 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7023 Undefine before redefining to avoid a preprocessor warning. */
7024 #ifdef DrawText
7025 #undef DrawText
7026 #endif
7027 /* avoid conflict with QuickdrawText.h */
7028 #define DrawText gif_DrawText
7029 #include <gif_lib.h>
7030 #undef DrawText
7032 #else /* HAVE_NTGUI */
7034 #include <gif_lib.h>
7036 #endif /* HAVE_NTGUI */
7039 #ifdef HAVE_NTGUI
7041 /* GIF library details. */
7042 DEF_IMGLIB_FN (DGifCloseFile, (GifFileType *));
7043 DEF_IMGLIB_FN (DGifSlurp, (GifFileType *));
7044 DEF_IMGLIB_FN (DGifOpen, (void *, InputFunc));
7045 DEF_IMGLIB_FN (DGifOpenFileName, (const char *));
7047 static int
7048 init_gif_functions (Lisp_Object libraries)
7050 HMODULE library;
7052 if (!(library = w32_delayed_load (libraries, Qgif)))
7053 return 0;
7055 LOAD_IMGLIB_FN (library, DGifCloseFile);
7056 LOAD_IMGLIB_FN (library, DGifSlurp);
7057 LOAD_IMGLIB_FN (library, DGifOpen);
7058 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7059 return 1;
7062 #else
7064 #define fn_DGifCloseFile DGifCloseFile
7065 #define fn_DGifSlurp DGifSlurp
7066 #define fn_DGifOpen DGifOpen
7067 #define fn_DGifOpenFileName DGifOpenFileName
7069 #endif /* HAVE_NTGUI */
7071 /* Reading a GIF image from memory
7072 Based on the PNG memory stuff to a certain extent. */
7074 typedef struct
7076 unsigned char *bytes;
7077 size_t len;
7078 int index;
7080 gif_memory_source;
7082 /* Make the current memory source available to gif_read_from_memory.
7083 It's done this way because not all versions of libungif support
7084 a UserData field in the GifFileType structure. */
7085 static gif_memory_source *current_gif_memory_src;
7087 static int
7088 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7090 gif_memory_source *src = current_gif_memory_src;
7092 if (len > src->len - src->index)
7093 return -1;
7095 memcpy (buf, src->bytes + src->index, len);
7096 src->index += len;
7097 return len;
7101 /* Load GIF image IMG for use on frame F. Value is non-zero if
7102 successful. */
7104 static const int interlace_start[] = {0, 4, 2, 1};
7105 static const int interlace_increment[] = {8, 8, 4, 2};
7107 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7109 static int
7110 gif_load (struct frame *f, struct image *img)
7112 Lisp_Object file, specified_file;
7113 Lisp_Object specified_data;
7114 int rc, width, height, x, y, i;
7115 boolean transparent_p;
7116 XImagePtr ximg;
7117 ColorMapObject *gif_color_map;
7118 unsigned long pixel_colors[256];
7119 GifFileType *gif;
7120 Lisp_Object image;
7121 int ino, image_height, image_width;
7122 gif_memory_source memsrc;
7123 unsigned char *raster;
7124 unsigned int transparency_color_index;
7126 specified_file = image_spec_value (img->spec, QCfile, NULL);
7127 specified_data = image_spec_value (img->spec, QCdata, NULL);
7129 if (NILP (specified_data))
7131 file = x_find_image_file (specified_file);
7132 if (!STRINGP (file))
7134 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7135 return 0;
7138 /* Open the GIF file. Casting return value avoids a GCC warning
7139 on W32. */
7140 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
7141 if (gif == NULL)
7143 image_error ("Cannot open `%s'", file, Qnil);
7144 return 0;
7147 else
7149 if (!STRINGP (specified_data))
7151 image_error ("Invalid image data `%s'", specified_data, Qnil);
7152 return 0;
7155 /* Read from memory! */
7156 current_gif_memory_src = &memsrc;
7157 memsrc.bytes = SDATA (specified_data);
7158 memsrc.len = SBYTES (specified_data);
7159 memsrc.index = 0;
7161 /* Casting return value avoids a GCC warning on W32. */
7162 gif = (GifFileType *) fn_DGifOpen (&memsrc, gif_read_from_memory);
7163 if (!gif)
7165 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7166 return 0;
7170 /* Before reading entire contents, check the declared image size. */
7171 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7173 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7174 fn_DGifCloseFile (gif);
7175 return 0;
7178 /* Read entire contents. */
7179 rc = fn_DGifSlurp (gif);
7180 if (rc == GIF_ERROR)
7182 image_error ("Error reading `%s'", img->spec, Qnil);
7183 fn_DGifCloseFile (gif);
7184 return 0;
7187 image = image_spec_value (img->spec, QCindex, NULL);
7188 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7189 if (ino >= gif->ImageCount)
7191 image_error ("Invalid image number `%s' in image `%s'",
7192 image, img->spec);
7193 fn_DGifCloseFile (gif);
7194 return 0;
7197 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++)
7198 if ((gif->SavedImages[ino].ExtensionBlocks[i].Function
7199 == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7200 && gif->SavedImages[ino].ExtensionBlocks[i].ByteCount == 4
7201 /* Transparency enabled? */
7202 && gif->SavedImages[ino].ExtensionBlocks[i].Bytes[0] & 1)
7204 transparent_p = 1;
7205 transparency_color_index
7206 = (unsigned char) gif->SavedImages[ino].ExtensionBlocks[i].Bytes[3];
7209 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
7210 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
7211 image_height = gif->SavedImages[ino].ImageDesc.Height;
7212 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
7213 image_width = gif->SavedImages[ino].ImageDesc.Width;
7214 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
7216 width = img->width = max (gif->SWidth,
7217 max (gif->Image.Left + gif->Image.Width,
7218 img->corners[RIGHT_CORNER]));
7219 height = img->height = max (gif->SHeight,
7220 max (gif->Image.Top + gif->Image.Height,
7221 img->corners[BOT_CORNER]));
7223 if (!check_image_size (f, width, height))
7225 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7226 fn_DGifCloseFile (gif);
7227 return 0;
7230 /* Create the X image and pixmap. */
7231 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7233 fn_DGifCloseFile (gif);
7234 return 0;
7237 /* Allocate colors. */
7238 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7239 if (!gif_color_map)
7240 gif_color_map = gif->SColorMap;
7241 init_color_table ();
7242 memset (pixel_colors, 0, sizeof pixel_colors);
7244 if (gif_color_map)
7245 for (i = 0; i < gif_color_map->ColorCount; ++i)
7247 if (transparent_p && transparency_color_index == i)
7249 Lisp_Object specified_bg
7250 = image_spec_value (img->spec, QCbackground, NULL);
7251 pixel_colors[i] = STRINGP (specified_bg)
7252 ? x_alloc_image_color (f, img, specified_bg,
7253 FRAME_BACKGROUND_PIXEL (f))
7254 : FRAME_BACKGROUND_PIXEL (f);
7256 else
7258 int r = gif_color_map->Colors[i].Red << 8;
7259 int g = gif_color_map->Colors[i].Green << 8;
7260 int b = gif_color_map->Colors[i].Blue << 8;
7261 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7265 #ifdef COLOR_TABLE_SUPPORT
7266 img->colors = colors_in_color_table (&img->ncolors);
7267 free_color_table ();
7268 #endif /* COLOR_TABLE_SUPPORT */
7270 /* Clear the part of the screen image that are not covered by
7271 the image from the GIF file. Full animated GIF support
7272 requires more than can be done here (see the gif89 spec,
7273 disposal methods). Let's simply assume that the part
7274 not covered by a sub-image is in the frame's background color. */
7275 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7276 for (x = 0; x < width; ++x)
7277 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7279 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7280 for (x = 0; x < width; ++x)
7281 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7283 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7285 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7286 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7287 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7288 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7291 /* Read the GIF image into the X image. We use a local variable
7292 `raster' here because RasterBits below is a char *, and invites
7293 problems with bytes >= 0x80. */
7294 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7296 if (gif->SavedImages[ino].ImageDesc.Interlace)
7298 int pass;
7299 int row = interlace_start[0];
7301 pass = 0;
7303 for (y = 0; y < image_height; y++)
7305 if (row >= image_height)
7307 row = interlace_start[++pass];
7308 while (row >= image_height)
7309 row = interlace_start[++pass];
7312 for (x = 0; x < image_width; x++)
7314 int i = raster[(y * image_width) + x];
7315 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7316 row + img->corners[TOP_CORNER], pixel_colors[i]);
7319 row += interlace_increment[pass];
7322 else
7324 for (y = 0; y < image_height; ++y)
7325 for (x = 0; x < image_width; ++x)
7327 int i = raster[y * image_width + x];
7328 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7329 y + img->corners[TOP_CORNER], pixel_colors[i]);
7333 /* Save GIF image extension data for `image-metadata'.
7334 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7335 img->data.lisp_val = Qnil;
7336 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
7338 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
7339 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
7340 /* Append (... FUNCTION "BYTES") */
7341 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7342 Fcons (make_number (ext->Function),
7343 img->data.lisp_val));
7344 img->data.lisp_val = Fcons (Qextension_data,
7345 Fcons (Fnreverse (img->data.lisp_val),
7346 Qnil));
7348 if (gif->ImageCount > 1)
7349 img->data.lisp_val = Fcons (Qcount,
7350 Fcons (make_number (gif->ImageCount),
7351 img->data.lisp_val));
7353 fn_DGifCloseFile (gif);
7355 /* Maybe fill in the background field while we have ximg handy. */
7356 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7357 /* Casting avoids a GCC warning. */
7358 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7360 /* Put the image into the pixmap, then free the X image and its buffer. */
7361 x_put_x_image (f, ximg, img->pixmap, width, height);
7362 x_destroy_x_image (ximg);
7364 return 1;
7367 #else /* !HAVE_GIF */
7369 #ifdef HAVE_NS
7370 static int
7371 gif_load (struct frame *f, struct image *img)
7373 return ns_load_image (f, img,
7374 image_spec_value (img->spec, QCfile, NULL),
7375 image_spec_value (img->spec, QCdata, NULL));
7377 #endif /* HAVE_NS */
7379 #endif /* HAVE_GIF */
7382 /***********************************************************************
7383 imagemagick
7384 ***********************************************************************/
7385 #if defined (HAVE_IMAGEMAGICK)
7386 Lisp_Object Vimagemagick_render_type;
7388 /* The symbol `imagemagick' identifying images of this type. */
7390 Lisp_Object Qimagemagick;
7391 Lisp_Object Vimagemagick_render_type;
7393 /* Indices of image specification fields in imagemagick_format, below. */
7395 enum imagemagick_keyword_index
7397 IMAGEMAGICK_TYPE,
7398 IMAGEMAGICK_DATA,
7399 IMAGEMAGICK_FILE,
7400 IMAGEMAGICK_ASCENT,
7401 IMAGEMAGICK_MARGIN,
7402 IMAGEMAGICK_RELIEF,
7403 IMAGEMAGICK_ALGORITHM,
7404 IMAGEMAGICK_HEURISTIC_MASK,
7405 IMAGEMAGICK_MASK,
7406 IMAGEMAGICK_BACKGROUND,
7407 IMAGEMAGICK_HEIGHT,
7408 IMAGEMAGICK_WIDTH,
7409 IMAGEMAGICK_ROTATION,
7410 IMAGEMAGICK_CROP,
7411 IMAGEMAGICK_LAST
7414 /* Vector of image_keyword structures describing the format
7415 of valid user-defined image specifications. */
7417 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7419 {":type", IMAGE_SYMBOL_VALUE, 1},
7420 {":data", IMAGE_STRING_VALUE, 0},
7421 {":file", IMAGE_STRING_VALUE, 0},
7422 {":ascent", IMAGE_ASCENT_VALUE, 0},
7423 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7424 {":relief", IMAGE_INTEGER_VALUE, 0},
7425 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7426 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7427 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7428 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7429 {":height", IMAGE_INTEGER_VALUE, 0},
7430 {":width", IMAGE_INTEGER_VALUE, 0},
7431 {":rotation", IMAGE_NUMBER_VALUE, 0},
7432 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7434 /* Free X resources of imagemagick image IMG which is used on frame F. */
7436 static void
7437 imagemagick_clear_image (struct frame *f,
7438 struct image *img)
7440 x_clear_image (f, img);
7445 /* Return non-zero if OBJECT is a valid IMAGEMAGICK image specification. Do
7446 this by calling parse_image_spec and supplying the keywords that
7447 identify the IMAGEMAGICK format. */
7449 static int
7450 imagemagick_image_p (Lisp_Object object)
7452 struct image_keyword fmt[IMAGEMAGICK_LAST];
7453 memcpy (fmt, imagemagick_format, sizeof fmt);
7455 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7456 return 0;
7458 /* Must specify either the :data or :file keyword. */
7459 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7462 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7463 Therefore rename the function so it doesnt collide with ImageMagick. */
7464 #define DrawRectangle DrawRectangleGif
7465 #include <wand/MagickWand.h>
7467 /* imagemagick_load_image is a helper function for imagemagick_load,
7468 which does the actual loading given contents and size, apart from
7469 frame and image structures, passed from imagemagick_load.
7471 Uses librimagemagick to do most of the image processing.
7473 non-zero when successful.
7476 static int
7477 imagemagick_load_image (/* Pointer to emacs frame structure. */
7478 struct frame *f,
7479 /* Pointer to emacs image structure. */
7480 struct image *img,
7481 /* String containing the IMAGEMAGICK data to
7482 be parsed. */
7483 unsigned char *contents,
7484 /* Size of data in bytes. */
7485 unsigned int size,
7486 /* Filename, either pass filename or
7487 contents/size. */
7488 unsigned char *filename)
7490 unsigned long width;
7491 unsigned long height;
7493 MagickBooleanType
7494 status;
7496 XImagePtr ximg;
7497 Lisp_Object specified_bg;
7498 XColor background;
7499 int x;
7500 int y;
7502 MagickWand *image_wand;
7503 MagickWand *ping_wand;
7504 PixelIterator *iterator;
7505 PixelWand **pixels;
7506 MagickPixelPacket pixel;
7507 Lisp_Object image;
7508 Lisp_Object value;
7509 Lisp_Object crop, geometry;
7510 long ino;
7511 int desired_width, desired_height;
7512 double rotation;
7513 int imagemagick_rendermethod;
7514 int pixelwidth;
7515 ImageInfo *image_info;
7516 ExceptionInfo *exception;
7517 Image * im_image;
7520 /* Handle image index for image types who can contain more than one
7521 image. Interface :index is same as for GIF. First we "ping" the
7522 image to see how many sub-images it contains. Pinging is faster
7523 than loading the image to find out things about it. */
7524 image = image_spec_value (img->spec, QCindex, NULL);
7525 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7526 ping_wand = NewMagickWand ();
7527 MagickSetResolution (ping_wand, 2, 2);
7528 if (filename != NULL)
7530 status = MagickPingImage (ping_wand, filename);
7532 else
7534 status = MagickPingImageBlob (ping_wand, contents, size);
7537 if (ino >= MagickGetNumberImages (ping_wand))
7539 image_error ("Invalid image number `%s' in image `%s'",
7540 image, img->spec);
7541 DestroyMagickWand (ping_wand);
7542 return 0;
7545 if (MagickGetNumberImages(ping_wand) > 1)
7546 img->data.lisp_val =
7547 Fcons (Qcount,
7548 Fcons (make_number (MagickGetNumberImages (ping_wand)),
7549 img->data.lisp_val));
7551 DestroyMagickWand (ping_wand);
7552 /* Now, after pinging, we know how many images are inside the
7553 file. If its not a bundle, just one. */
7555 if (filename != NULL)
7557 image_info = CloneImageInfo ((ImageInfo *) NULL);
7558 (void) strcpy (image_info->filename, filename);
7559 image_info->number_scenes = 1;
7560 image_info->scene = ino;
7561 exception = AcquireExceptionInfo ();
7563 im_image = ReadImage (image_info, exception);
7564 DestroyExceptionInfo (exception);
7566 if (im_image != NULL)
7568 image_wand = NewMagickWandFromImage (im_image);
7569 status = MagickTrue;
7571 else
7572 status = MagickFalse;
7574 else
7576 image_wand = NewMagickWand ();
7577 status = MagickReadImageBlob (image_wand, contents, size);
7579 image_error ("im read failed", Qnil, Qnil);
7580 if (status == MagickFalse) goto imagemagick_error;
7582 /* If width and/or height is set in the display spec assume we want
7583 to scale to those values. if either h or w is unspecified, the
7584 unspecified should be calculated from the specified to preserve
7585 aspect ratio. */
7587 value = image_spec_value (img->spec, QCwidth, NULL);
7588 desired_width = (INTEGERP (value) ? XFASTINT (value) : -1);
7589 value = image_spec_value (img->spec, QCheight, NULL);
7590 desired_height = (INTEGERP (value) ? XFASTINT (value) : -1);
7592 height = MagickGetImageHeight (image_wand);
7593 width = MagickGetImageWidth (image_wand);
7595 if(desired_width != -1 && desired_height == -1)
7597 /* w known, calculate h. */
7598 desired_height = (double) desired_width / width * height;
7600 if(desired_width == -1 && desired_height != -1)
7602 /* h known, calculate w. */
7603 desired_width = (double) desired_height / height * width;
7605 if(desired_width != -1 && desired_height != -1)
7607 status = MagickScaleImage (image_wand, desired_width, desired_height);
7608 if (status == MagickFalse)
7610 image_error ("Imagemagick scale failed", Qnil, Qnil);
7611 goto imagemagick_error;
7616 /* crop behaves similar to image slicing in Emacs but is more memory
7617 efficient. */
7618 crop = image_spec_value (img->spec, QCcrop, NULL);
7620 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7622 /* After some testing, it seems MagickCropImage is the fastest
7623 crop function in ImageMagick. This crop function seems to do
7624 less copying than the alternatives, but it still reads the
7625 entire image into memory before croping, which is aparently
7626 difficult to avoid when using imagemagick. */
7628 int w, h, x, y;
7629 w = XFASTINT (XCAR (crop));
7630 crop = XCDR (crop);
7631 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7633 h = XFASTINT (XCAR (crop));
7634 crop = XCDR (crop);
7635 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7637 x = XFASTINT (XCAR (crop));
7638 crop = XCDR (crop);
7639 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7641 y = XFASTINT (XCAR (crop));
7642 MagickCropImage (image_wand, w, h, x, y);
7648 /* Furthermore :rotation. we need background color and angle for
7649 rotation. */
7651 TODO background handling for rotation specified_bg =
7652 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
7653 (specified_bg). */
7654 value = image_spec_value (img->spec, QCrotation, NULL);
7655 if (FLOATP (value))
7657 PixelWand* background = NewPixelWand ();
7658 PixelSetColor (background, "#ffffff");/*TODO remove hardcode*/
7660 rotation = extract_float (value);
7662 status = MagickRotateImage (image_wand, background, rotation);
7663 DestroyPixelWand (background);
7664 if (status == MagickFalse)
7666 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
7667 goto imagemagick_error;
7671 /* Finaly we are done manipulating the image, figure out resulting
7672 width, height, and then transfer ownerwship to Emacs. */
7673 height = MagickGetImageHeight (image_wand);
7674 width = MagickGetImageWidth (image_wand);
7676 if (! check_image_size (f, width, height))
7678 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7679 goto imagemagick_error;
7682 /* We can now get a valid pixel buffer from the imagemagick file, if all
7683 went ok. */
7685 init_color_table ();
7686 imagemagick_rendermethod = (INTEGERP (Vimagemagick_render_type)
7687 ? XFASTINT (Vimagemagick_render_type) : 0);
7688 if (imagemagick_rendermethod == 0)
7690 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7691 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7692 &ximg, &img->pixmap))
7694 #ifdef COLOR_TABLE_SUPPORT
7695 free_color_table ();
7696 #endif
7697 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7698 goto imagemagick_error;
7701 /* Copy imagegmagick image to x with primitive yet robust pixel
7702 pusher loop. This has been tested a lot with many different
7703 images. */
7705 /* Copy pixels from the imagemagick image structure to the x image map. */
7706 iterator = NewPixelIterator (image_wand);
7707 if (iterator == (PixelIterator *) NULL)
7709 #ifdef COLOR_TABLE_SUPPORT
7710 free_color_table ();
7711 #endif
7712 x_destroy_x_image (ximg);
7713 image_error ("Imagemagick pixel iterator creation failed",
7714 Qnil, Qnil);
7715 goto imagemagick_error;
7718 for (y = 0; y < (long) MagickGetImageHeight (image_wand); y++)
7720 pixels = PixelGetNextIteratorRow (iterator, &width);
7721 if (pixels == (PixelWand **) NULL)
7722 break;
7723 for (x = 0; x < (long) width; x++)
7725 PixelGetMagickColor (pixels[x], &pixel);
7726 XPutPixel (ximg, x, y,
7727 lookup_rgb_color (f,
7728 pixel.red,
7729 pixel.green,
7730 pixel.blue));
7733 DestroyPixelIterator (iterator);
7736 if (imagemagick_rendermethod == 1)
7738 /* Magicexportimage is normaly faster than pixelpushing. This
7739 method is also well tested. Some aspects of this method are
7740 ad-hoc and needs to be more researched. */
7741 int imagedepth = 24;/*MagickGetImageDepth(image_wand);*/
7742 char* exportdepth = imagedepth <= 8 ? "I" : "BGRP";/*"RGBP";*/
7743 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7744 if (!x_create_x_image_and_pixmap (f, width, height, imagedepth,
7745 &ximg, &img->pixmap))
7747 #ifdef COLOR_TABLE_SUPPORT
7748 free_color_table ();
7749 #endif
7750 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7751 goto imagemagick_error;
7755 /* Oddly, the below code doesnt seem to work:*/
7756 /* switch(ximg->bitmap_unit){ */
7757 /* case 8: */
7758 /* pixelwidth=CharPixel; */
7759 /* break; */
7760 /* case 16: */
7761 /* pixelwidth=ShortPixel; */
7762 /* break; */
7763 /* case 32: */
7764 /* pixelwidth=LongPixel; */
7765 /* break; */
7766 /* } */
7768 Here im just guessing the format of the bitmap.
7769 happens to work fine for:
7770 - bw djvu images
7771 on rgb display.
7772 seems about 3 times as fast as pixel pushing(not carefully measured)
7774 pixelwidth = CharPixel;/*??? TODO figure out*/
7775 #ifdef HAVE_MAGICKEXPORTIMAGEPIXELS
7776 MagickExportImagePixels (image_wand,
7777 0, 0,
7778 width, height,
7779 exportdepth,
7780 pixelwidth,
7781 /*&(img->pixmap));*/
7782 ximg->data);
7783 #else
7784 image_error ("You dont have MagickExportImagePixels, upgrade ImageMagick!",
7785 Qnil, Qnil);
7786 #endif
7790 #ifdef COLOR_TABLE_SUPPORT
7791 /* Remember colors allocated for this image. */
7792 img->colors = colors_in_color_table (&img->ncolors);
7793 free_color_table ();
7794 #endif /* COLOR_TABLE_SUPPORT */
7797 img->width = width;
7798 img->height = height;
7800 /* Put the image into the pixmap, then free the X image and its
7801 buffer. */
7802 x_put_x_image (f, ximg, img->pixmap, width, height);
7803 x_destroy_x_image (ximg);
7806 /* Final cleanup. image_wand should be the only resource left. */
7807 DestroyMagickWand (image_wand);
7809 return 1;
7811 imagemagick_error:
7812 DestroyMagickWand (image_wand);
7813 /* TODO more cleanup. */
7814 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
7815 return 0;
7819 /* Load IMAGEMAGICK image IMG for use on frame F. Value is non-zero if
7820 successful. this function will go into the imagemagick_type structure, and
7821 the prototype thus needs to be compatible with that structure. */
7823 static int
7824 imagemagick_load (struct frame *f,
7825 struct image *img)
7827 int success_p = 0;
7828 Lisp_Object file_name;
7830 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7831 file_name = image_spec_value (img->spec, QCfile, NULL);
7832 if (STRINGP (file_name))
7834 Lisp_Object file;
7836 file = x_find_image_file (file_name);
7837 if (!STRINGP (file))
7839 image_error ("Cannot find image file `%s'", file_name, Qnil);
7840 return 0;
7842 success_p = imagemagick_load_image (f, img, 0, 0, SDATA (file));
7844 /* Else its not a file, its a lisp object. Load the image from a
7845 lisp object rather than a file. */
7846 else
7848 Lisp_Object data;
7850 data = image_spec_value (img->spec, QCdata, NULL);
7851 if (!STRINGP (data))
7853 image_error ("Invalid image data `%s'", data, Qnil);
7854 return 0;
7856 success_p = imagemagick_load_image (f, img, SDATA (data),
7857 SBYTES (data), NULL);
7860 return success_p;
7863 /* Structure describing the image type `imagemagick'. Its the same
7864 type of structure defined for all image formats, handled by Emacs
7865 image functions. See struct image_type in dispextern.h. */
7867 static struct image_type imagemagick_type =
7869 /* An identifier showing that this is an image structure for the
7870 IMAGEMAGICK format. */
7871 &Qimagemagick,
7872 /* Handle to a function that can be used to identify a IMAGEMAGICK
7873 file. */
7874 imagemagick_image_p,
7875 /* Handle to function used to load a IMAGEMAGICK file. */
7876 imagemagick_load,
7877 /* Handle to function to free resources for IMAGEMAGICK. */
7878 imagemagick_clear_image,
7879 /* An internal field to link to the next image type in a list of
7880 image types, will be filled in when registering the format. */
7881 NULL
7887 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
7888 doc: /* Return image file types supported by ImageMagick.
7889 Since ImageMagick recognizes a lot of file-types that clash with Emacs,
7890 such as .c, we want to be able to alter the list at the lisp level. */)
7891 (void)
7893 Lisp_Object typelist = Qnil;
7894 unsigned long numf;
7895 ExceptionInfo ex;
7896 char **imtypes = GetMagickList ("*", &numf, &ex);
7897 int i;
7898 Lisp_Object Qimagemagicktype;
7899 for (i = 0; i < numf; i++)
7901 Qimagemagicktype = intern (imtypes[i]);
7902 typelist = Fcons (Qimagemagicktype, typelist);
7904 return typelist;
7907 #endif /* defined (HAVE_IMAGEMAGICK) */
7911 /***********************************************************************
7913 ***********************************************************************/
7915 #if defined (HAVE_RSVG)
7917 /* Function prototypes. */
7919 static int svg_image_p (Lisp_Object object);
7920 static int svg_load (struct frame *f, struct image *img);
7922 static int svg_load_image (struct frame *, struct image *,
7923 unsigned char *, unsigned int);
7925 /* The symbol `svg' identifying images of this type. */
7927 Lisp_Object Qsvg;
7929 /* Indices of image specification fields in svg_format, below. */
7931 enum svg_keyword_index
7933 SVG_TYPE,
7934 SVG_DATA,
7935 SVG_FILE,
7936 SVG_ASCENT,
7937 SVG_MARGIN,
7938 SVG_RELIEF,
7939 SVG_ALGORITHM,
7940 SVG_HEURISTIC_MASK,
7941 SVG_MASK,
7942 SVG_BACKGROUND,
7943 SVG_LAST
7946 /* Vector of image_keyword structures describing the format
7947 of valid user-defined image specifications. */
7949 static const struct image_keyword svg_format[SVG_LAST] =
7951 {":type", IMAGE_SYMBOL_VALUE, 1},
7952 {":data", IMAGE_STRING_VALUE, 0},
7953 {":file", IMAGE_STRING_VALUE, 0},
7954 {":ascent", IMAGE_ASCENT_VALUE, 0},
7955 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7956 {":relief", IMAGE_INTEGER_VALUE, 0},
7957 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7958 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7959 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7960 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7963 /* Structure describing the image type `svg'. Its the same type of
7964 structure defined for all image formats, handled by emacs image
7965 functions. See struct image_type in dispextern.h. */
7967 static struct image_type svg_type =
7969 /* An identifier showing that this is an image structure for the SVG format. */
7970 &Qsvg,
7971 /* Handle to a function that can be used to identify a SVG file. */
7972 svg_image_p,
7973 /* Handle to function used to load a SVG file. */
7974 svg_load,
7975 /* Handle to function to free sresources for SVG. */
7976 x_clear_image,
7977 /* An internal field to link to the next image type in a list of
7978 image types, will be filled in when registering the format. */
7979 NULL
7983 /* Return non-zero if OBJECT is a valid SVG image specification. Do
7984 this by calling parse_image_spec and supplying the keywords that
7985 identify the SVG format. */
7987 static int
7988 svg_image_p (Lisp_Object object)
7990 struct image_keyword fmt[SVG_LAST];
7991 memcpy (fmt, svg_format, sizeof fmt);
7993 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
7994 return 0;
7996 /* Must specify either the :data or :file keyword. */
7997 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8000 #include <librsvg/rsvg.h>
8002 #ifdef HAVE_NTGUI
8004 /* SVG library functions. */
8005 DEF_IMGLIB_FN (rsvg_handle_new);
8006 DEF_IMGLIB_FN (rsvg_handle_get_dimensions);
8007 DEF_IMGLIB_FN (rsvg_handle_write);
8008 DEF_IMGLIB_FN (rsvg_handle_close);
8009 DEF_IMGLIB_FN (rsvg_handle_get_pixbuf);
8010 DEF_IMGLIB_FN (rsvg_handle_free);
8012 DEF_IMGLIB_FN (gdk_pixbuf_get_width);
8013 DEF_IMGLIB_FN (gdk_pixbuf_get_height);
8014 DEF_IMGLIB_FN (gdk_pixbuf_get_pixels);
8015 DEF_IMGLIB_FN (gdk_pixbuf_get_rowstride);
8016 DEF_IMGLIB_FN (gdk_pixbuf_get_colorspace);
8017 DEF_IMGLIB_FN (gdk_pixbuf_get_n_channels);
8018 DEF_IMGLIB_FN (gdk_pixbuf_get_has_alpha);
8019 DEF_IMGLIB_FN (gdk_pixbuf_get_bits_per_sample);
8021 DEF_IMGLIB_FN (g_type_init);
8022 DEF_IMGLIB_FN (g_object_unref);
8023 DEF_IMGLIB_FN (g_error_free);
8025 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8027 static int
8028 init_svg_functions (Lisp_Object libraries)
8030 HMODULE library, gdklib, glib, gobject;
8032 if (!(glib = w32_delayed_load (libraries, Qglib))
8033 || !(gobject = w32_delayed_load (libraries, Qgobject))
8034 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
8035 || !(library = w32_delayed_load (libraries, Qsvg)))
8036 return 0;
8038 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8039 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8040 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8041 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8042 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8043 LOAD_IMGLIB_FN (library, rsvg_handle_free);
8045 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8046 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8047 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8048 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8049 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8050 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8051 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8052 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8054 LOAD_IMGLIB_FN (gobject, g_type_init);
8055 LOAD_IMGLIB_FN (gobject, g_object_unref);
8056 LOAD_IMGLIB_FN (glib, g_error_free);
8058 return 1;
8061 #else
8062 /* The following aliases for library functions allow dynamic loading
8063 to be used on some platforms. */
8064 #define fn_rsvg_handle_new rsvg_handle_new
8065 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8066 #define fn_rsvg_handle_write rsvg_handle_write
8067 #define fn_rsvg_handle_close rsvg_handle_close
8068 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8069 #define fn_rsvg_handle_free rsvg_handle_free
8071 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8072 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8073 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8074 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8075 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8076 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8077 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8078 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8080 #define fn_g_type_init g_type_init
8081 #define fn_g_object_unref g_object_unref
8082 #define fn_g_error_free g_error_free
8083 #endif /* !HAVE_NTGUI */
8085 /* Load SVG image IMG for use on frame F. Value is non-zero if
8086 successful. this function will go into the svg_type structure, and
8087 the prototype thus needs to be compatible with that structure. */
8089 static int
8090 svg_load (struct frame *f, struct image *img)
8092 int success_p = 0;
8093 Lisp_Object file_name;
8095 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8096 file_name = image_spec_value (img->spec, QCfile, NULL);
8097 if (STRINGP (file_name))
8099 Lisp_Object file;
8100 unsigned char *contents;
8101 int size;
8103 file = x_find_image_file (file_name);
8104 if (!STRINGP (file))
8106 image_error ("Cannot find image file `%s'", file_name, Qnil);
8107 return 0;
8110 /* Read the entire file into memory. */
8111 contents = slurp_file (SDATA (file), &size);
8112 if (contents == NULL)
8114 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8115 return 0;
8117 /* If the file was slurped into memory properly, parse it. */
8118 success_p = svg_load_image (f, img, contents, size);
8119 xfree (contents);
8121 /* Else its not a file, its a lisp object. Load the image from a
8122 lisp object rather than a file. */
8123 else
8125 Lisp_Object data;
8127 data = image_spec_value (img->spec, QCdata, NULL);
8128 if (!STRINGP (data))
8130 image_error ("Invalid image data `%s'", data, Qnil);
8131 return 0;
8133 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8136 return success_p;
8139 /* svg_load_image is a helper function for svg_load, which does the
8140 actual loading given contents and size, apart from frame and image
8141 structures, passed from svg_load.
8143 Uses librsvg to do most of the image processing.
8145 Returns non-zero when successful. */
8146 static int
8147 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8148 struct image *img, /* Pointer to emacs image structure. */
8149 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8150 unsigned int size) /* Size of data in bytes. */
8152 RsvgHandle *rsvg_handle;
8153 RsvgDimensionData dimension_data;
8154 GError *error = NULL;
8155 GdkPixbuf *pixbuf;
8156 int width;
8157 int height;
8158 const guint8 *pixels;
8159 int rowstride;
8160 XImagePtr ximg;
8161 Lisp_Object specified_bg;
8162 XColor background;
8163 int x;
8164 int y;
8166 /* g_type_init is a glib function that must be called prior to using
8167 gnome type library functions. */
8168 fn_g_type_init ();
8169 /* Make a handle to a new rsvg object. */
8170 rsvg_handle = (RsvgHandle *) fn_rsvg_handle_new ();
8172 /* Parse the contents argument and fill in the rsvg_handle. */
8173 fn_rsvg_handle_write (rsvg_handle, contents, size, &error);
8174 if (error) goto rsvg_error;
8176 /* The parsing is complete, rsvg_handle is ready to used, close it
8177 for further writes. */
8178 fn_rsvg_handle_close (rsvg_handle, &error);
8179 if (error) goto rsvg_error;
8181 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8182 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8184 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8185 goto rsvg_error;
8188 /* We can now get a valid pixel buffer from the svg file, if all
8189 went ok. */
8190 pixbuf = (GdkPixbuf *) fn_rsvg_handle_get_pixbuf (rsvg_handle);
8191 if (!pixbuf) goto rsvg_error;
8192 fn_g_object_unref (rsvg_handle);
8194 /* Extract some meta data from the svg handle. */
8195 width = fn_gdk_pixbuf_get_width (pixbuf);
8196 height = fn_gdk_pixbuf_get_height (pixbuf);
8197 pixels = (const guint8 *) fn_gdk_pixbuf_get_pixels (pixbuf);
8198 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8200 /* Validate the svg meta data. */
8201 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8202 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8203 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8204 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8206 /* Try to create a x pixmap to hold the svg pixmap. */
8207 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8209 fn_g_object_unref (pixbuf);
8210 return 0;
8213 init_color_table ();
8215 /* Handle alpha channel by combining the image with a background
8216 color. */
8217 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8218 if (!STRINGP (specified_bg)
8219 || !x_defined_color (f, SDATA (specified_bg), &background, 0))
8221 #ifndef HAVE_NS
8222 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8223 x_query_color (f, &background);
8224 #else
8225 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8226 #endif
8229 /* SVG pixmaps specify transparency in the last byte, so right
8230 shift 8 bits to get rid of it, since emacs doesn't support
8231 transparency. */
8232 background.red >>= 8;
8233 background.green >>= 8;
8234 background.blue >>= 8;
8236 /* This loop handles opacity values, since Emacs assumes
8237 non-transparent images. Each pixel must be "flattened" by
8238 calculating the resulting color, given the transparency of the
8239 pixel, and the image background color. */
8240 for (y = 0; y < height; ++y)
8242 for (x = 0; x < width; ++x)
8244 unsigned red;
8245 unsigned green;
8246 unsigned blue;
8247 unsigned opacity;
8249 red = *pixels++;
8250 green = *pixels++;
8251 blue = *pixels++;
8252 opacity = *pixels++;
8254 red = ((red * opacity)
8255 + (background.red * ((1 << 8) - opacity)));
8256 green = ((green * opacity)
8257 + (background.green * ((1 << 8) - opacity)));
8258 blue = ((blue * opacity)
8259 + (background.blue * ((1 << 8) - opacity)));
8261 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8264 pixels += rowstride - 4 * width;
8267 #ifdef COLOR_TABLE_SUPPORT
8268 /* Remember colors allocated for this image. */
8269 img->colors = colors_in_color_table (&img->ncolors);
8270 free_color_table ();
8271 #endif /* COLOR_TABLE_SUPPORT */
8273 fn_g_object_unref (pixbuf);
8275 img->width = width;
8276 img->height = height;
8278 /* Maybe fill in the background field while we have ximg handy.
8279 Casting avoids a GCC warning. */
8280 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8282 /* Put the image into the pixmap, then free the X image and its
8283 buffer. */
8284 x_put_x_image (f, ximg, img->pixmap, width, height);
8285 x_destroy_x_image (ximg);
8287 return 1;
8289 rsvg_error:
8290 fn_g_object_unref (rsvg_handle);
8291 /* FIXME: Use error->message so the user knows what is the actual
8292 problem with the image. */
8293 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8294 fn_g_error_free (error);
8295 return 0;
8298 #endif /* defined (HAVE_RSVG) */
8303 /***********************************************************************
8304 Ghostscript
8305 ***********************************************************************/
8307 #ifdef HAVE_X_WINDOWS
8308 #define HAVE_GHOSTSCRIPT 1
8309 #endif /* HAVE_X_WINDOWS */
8311 #ifdef HAVE_GHOSTSCRIPT
8313 static int gs_image_p (Lisp_Object object);
8314 static int gs_load (struct frame *f, struct image *img);
8315 static void gs_clear_image (struct frame *f, struct image *img);
8317 /* Keyword symbols. */
8319 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8321 /* Indices of image specification fields in gs_format, below. */
8323 enum gs_keyword_index
8325 GS_TYPE,
8326 GS_PT_WIDTH,
8327 GS_PT_HEIGHT,
8328 GS_FILE,
8329 GS_LOADER,
8330 GS_BOUNDING_BOX,
8331 GS_ASCENT,
8332 GS_MARGIN,
8333 GS_RELIEF,
8334 GS_ALGORITHM,
8335 GS_HEURISTIC_MASK,
8336 GS_MASK,
8337 GS_BACKGROUND,
8338 GS_LAST
8341 /* Vector of image_keyword structures describing the format
8342 of valid user-defined image specifications. */
8344 static const struct image_keyword gs_format[GS_LAST] =
8346 {":type", IMAGE_SYMBOL_VALUE, 1},
8347 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8348 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8349 {":file", IMAGE_STRING_VALUE, 1},
8350 {":loader", IMAGE_FUNCTION_VALUE, 0},
8351 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8352 {":ascent", IMAGE_ASCENT_VALUE, 0},
8353 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8354 {":relief", IMAGE_INTEGER_VALUE, 0},
8355 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8356 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8357 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8358 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8361 /* Structure describing the image type `ghostscript'. */
8363 static struct image_type gs_type =
8365 &Qpostscript,
8366 gs_image_p,
8367 gs_load,
8368 gs_clear_image,
8369 NULL
8373 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8375 static void
8376 gs_clear_image (struct frame *f, struct image *img)
8378 /* IMG->data.ptr_val may contain a recorded colormap. */
8379 xfree (img->data.ptr_val);
8380 x_clear_image (f, img);
8384 /* Return non-zero if OBJECT is a valid Ghostscript image
8385 specification. */
8387 static int
8388 gs_image_p (Lisp_Object object)
8390 struct image_keyword fmt[GS_LAST];
8391 Lisp_Object tem;
8392 int i;
8394 memcpy (fmt, gs_format, sizeof fmt);
8396 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8397 return 0;
8399 /* Bounding box must be a list or vector containing 4 integers. */
8400 tem = fmt[GS_BOUNDING_BOX].value;
8401 if (CONSP (tem))
8403 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8404 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8405 return 0;
8406 if (!NILP (tem))
8407 return 0;
8409 else if (VECTORP (tem))
8411 if (XVECTOR (tem)->size != 4)
8412 return 0;
8413 for (i = 0; i < 4; ++i)
8414 if (!INTEGERP (XVECTOR (tem)->contents[i]))
8415 return 0;
8417 else
8418 return 0;
8420 return 1;
8424 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8425 if successful. */
8427 static int
8428 gs_load (struct frame *f, struct image *img)
8430 char buffer[100];
8431 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8432 Lisp_Object frame;
8433 double in_width, in_height;
8434 Lisp_Object pixel_colors = Qnil;
8436 /* Compute pixel size of pixmap needed from the given size in the
8437 image specification. Sizes in the specification are in pt. 1 pt
8438 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8439 info. */
8440 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8441 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
8442 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
8443 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8444 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
8445 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
8447 if (!check_image_size (f, img->width, img->height))
8449 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8450 return 0;
8453 /* Create the pixmap. */
8454 xassert (img->pixmap == NO_PIXMAP);
8456 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8457 BLOCK_INPUT;
8458 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8459 img->width, img->height,
8460 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8461 UNBLOCK_INPUT;
8463 if (!img->pixmap)
8465 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8466 return 0;
8469 /* Call the loader to fill the pixmap. It returns a process object
8470 if successful. We do not record_unwind_protect here because
8471 other places in redisplay like calling window scroll functions
8472 don't either. Let the Lisp loader use `unwind-protect' instead. */
8473 sprintf (buffer, "%lu %lu",
8474 (unsigned long) FRAME_X_WINDOW (f),
8475 (unsigned long) img->pixmap);
8476 window_and_pixmap_id = build_string (buffer);
8478 sprintf (buffer, "%lu %lu",
8479 FRAME_FOREGROUND_PIXEL (f),
8480 FRAME_BACKGROUND_PIXEL (f));
8481 pixel_colors = build_string (buffer);
8483 XSETFRAME (frame, f);
8484 loader = image_spec_value (img->spec, QCloader, NULL);
8485 if (NILP (loader))
8486 loader = intern ("gs-load-image");
8488 img->data.lisp_val = call6 (loader, frame, img->spec,
8489 make_number (img->width),
8490 make_number (img->height),
8491 window_and_pixmap_id,
8492 pixel_colors);
8493 return PROCESSP (img->data.lisp_val);
8497 /* Kill the Ghostscript process that was started to fill PIXMAP on
8498 frame F. Called from XTread_socket when receiving an event
8499 telling Emacs that Ghostscript has finished drawing. */
8501 void
8502 x_kill_gs_process (Pixmap pixmap, struct frame *f)
8504 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8505 int class, i;
8506 struct image *img;
8508 /* Find the image containing PIXMAP. */
8509 for (i = 0; i < c->used; ++i)
8510 if (c->images[i]->pixmap == pixmap)
8511 break;
8513 /* Should someone in between have cleared the image cache, for
8514 instance, give up. */
8515 if (i == c->used)
8516 return;
8518 /* Kill the GS process. We should have found PIXMAP in the image
8519 cache and its image should contain a process object. */
8520 img = c->images[i];
8521 xassert (PROCESSP (img->data.lisp_val));
8522 Fkill_process (img->data.lisp_val, Qnil);
8523 img->data.lisp_val = Qnil;
8525 #if defined (HAVE_X_WINDOWS)
8527 /* On displays with a mutable colormap, figure out the colors
8528 allocated for the image by looking at the pixels of an XImage for
8529 img->pixmap. */
8530 class = FRAME_X_VISUAL (f)->class;
8531 if (class != StaticColor && class != StaticGray && class != TrueColor)
8533 XImagePtr ximg;
8535 BLOCK_INPUT;
8537 /* Try to get an XImage for img->pixmep. */
8538 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8539 0, 0, img->width, img->height, ~0, ZPixmap);
8540 if (ximg)
8542 int x, y;
8544 /* Initialize the color table. */
8545 init_color_table ();
8547 /* For each pixel of the image, look its color up in the
8548 color table. After having done so, the color table will
8549 contain an entry for each color used by the image. */
8550 for (y = 0; y < img->height; ++y)
8551 for (x = 0; x < img->width; ++x)
8553 unsigned long pixel = XGetPixel (ximg, x, y);
8554 lookup_pixel_color (f, pixel);
8557 /* Record colors in the image. Free color table and XImage. */
8558 #ifdef COLOR_TABLE_SUPPORT
8559 img->colors = colors_in_color_table (&img->ncolors);
8560 free_color_table ();
8561 #endif
8562 XDestroyImage (ximg);
8564 #if 0 /* This doesn't seem to be the case. If we free the colors
8565 here, we get a BadAccess later in x_clear_image when
8566 freeing the colors. */
8567 /* We have allocated colors once, but Ghostscript has also
8568 allocated colors on behalf of us. So, to get the
8569 reference counts right, free them once. */
8570 if (img->ncolors)
8571 x_free_colors (f, img->colors, img->ncolors);
8572 #endif
8574 else
8575 image_error ("Cannot get X image of `%s'; colors will not be freed",
8576 img->spec, Qnil);
8578 UNBLOCK_INPUT;
8580 #endif /* HAVE_X_WINDOWS */
8582 /* Now that we have the pixmap, compute mask and transform the
8583 image if requested. */
8584 BLOCK_INPUT;
8585 postprocess_image (f, img);
8586 UNBLOCK_INPUT;
8589 #endif /* HAVE_GHOSTSCRIPT */
8592 /***********************************************************************
8593 Tests
8594 ***********************************************************************/
8596 #if GLYPH_DEBUG
8598 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8599 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8600 (Lisp_Object spec)
8602 return valid_image_p (spec) ? Qt : Qnil;
8606 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8607 (Lisp_Object spec)
8609 int id = -1;
8611 if (valid_image_p (spec))
8612 id = lookup_image (SELECTED_FRAME (), spec);
8614 debug_print (spec);
8615 return make_number (id);
8618 #endif /* GLYPH_DEBUG != 0 */
8621 /***********************************************************************
8622 Initialization
8623 ***********************************************************************/
8625 #ifdef HAVE_NTGUI
8626 /* Image types that rely on external libraries are loaded dynamically
8627 if the library is available. */
8628 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8629 define_image_type (image_type, init_lib_fn (libraries))
8630 #else
8631 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8632 define_image_type (image_type, 1)
8633 #endif /* HAVE_NTGUI */
8635 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8636 doc: /* Initialize image library implementing image type TYPE.
8637 Return non-nil if TYPE is a supported image type.
8639 Image types pbm and xbm are prebuilt; other types are loaded here.
8640 Libraries to load are specified in alist LIBRARIES (usually, the value
8641 of `dynamic-library-alist', which see). */)
8642 (Lisp_Object type, Lisp_Object libraries)
8644 Lisp_Object tested;
8646 /* Don't try to reload the library. */
8647 tested = Fassq (type, Vimage_type_cache);
8648 if (CONSP (tested))
8649 return XCDR (tested);
8651 #if defined (HAVE_XPM) || defined (HAVE_NS)
8652 if (EQ (type, Qxpm))
8653 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8654 #endif
8656 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8657 if (EQ (type, Qjpeg))
8658 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8659 #endif
8661 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8662 if (EQ (type, Qtiff))
8663 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8664 #endif
8666 #if defined (HAVE_GIF) || defined (HAVE_NS)
8667 if (EQ (type, Qgif))
8668 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8669 #endif
8671 #if defined (HAVE_PNG) || defined (HAVE_NS)
8672 if (EQ (type, Qpng))
8673 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8674 #endif
8676 #if defined (HAVE_RSVG)
8677 if (EQ (type, Qsvg))
8678 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
8679 #endif
8681 #if defined (HAVE_IMAGEMAGICK)
8682 if (EQ (type, Qimagemagick))
8684 /* MagickWandGenesis() initializes the imagemagick library. */
8685 MagickWandGenesis ();
8686 return CHECK_LIB_AVAILABLE (&imagemagick_type, init_imagemagick_functions,
8687 libraries);
8689 #endif
8691 #ifdef HAVE_GHOSTSCRIPT
8692 if (EQ (type, Qpostscript))
8693 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8694 #endif
8696 /* If the type is not recognized, avoid testing it ever again. */
8697 CACHE_IMAGE_TYPE (type, Qnil);
8698 return Qnil;
8701 void
8702 syms_of_image (void)
8704 /* Initialize this only once, since that's what we do with Vimage_types
8705 and they are supposed to be in sync. Initializing here gives correct
8706 operation on GNU/Linux of calling dump-emacs after loading some images. */
8707 image_types = NULL;
8709 /* Must be defined now becase we're going to update it below, while
8710 defining the supported image types. */
8711 DEFVAR_LISP ("image-types", &Vimage_types,
8712 doc: /* List of potentially supported image types.
8713 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8714 To check whether it is really supported, use `image-type-available-p'. */);
8715 Vimage_types = Qnil;
8717 DEFVAR_LISP ("max-image-size", &Vmax_image_size,
8718 doc: /* Maximum size of images.
8719 Emacs will not load an image into memory if its pixel width or
8720 pixel height exceeds this limit.
8722 If the value is an integer, it directly specifies the maximum
8723 image height and width, measured in pixels. If it is a floating
8724 point number, it specifies the maximum image height and width
8725 as a ratio to the frame height and width. If the value is
8726 non-numeric, there is no explicit limit on the size of images. */);
8727 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8729 Vimage_type_cache = Qnil;
8730 staticpro (&Vimage_type_cache);
8732 Qpbm = intern_c_string ("pbm");
8733 staticpro (&Qpbm);
8734 ADD_IMAGE_TYPE (Qpbm);
8736 Qxbm = intern_c_string ("xbm");
8737 staticpro (&Qxbm);
8738 ADD_IMAGE_TYPE (Qxbm);
8740 define_image_type (&xbm_type, 1);
8741 define_image_type (&pbm_type, 1);
8743 Qcount = intern_c_string ("count");
8744 staticpro (&Qcount);
8745 Qextension_data = intern_c_string ("extension-data");
8746 staticpro (&Qextension_data);
8748 QCascent = intern_c_string (":ascent");
8749 staticpro (&QCascent);
8750 QCmargin = intern_c_string (":margin");
8751 staticpro (&QCmargin);
8752 QCrelief = intern_c_string (":relief");
8753 staticpro (&QCrelief);
8754 QCconversion = intern_c_string (":conversion");
8755 staticpro (&QCconversion);
8756 QCcolor_symbols = intern_c_string (":color-symbols");
8757 staticpro (&QCcolor_symbols);
8758 QCheuristic_mask = intern_c_string (":heuristic-mask");
8759 staticpro (&QCheuristic_mask);
8760 QCindex = intern_c_string (":index");
8761 staticpro (&QCindex);
8762 QCgeometry = intern_c_string (":geometry");
8763 staticpro (&QCgeometry);
8764 QCcrop = intern_c_string (":crop");
8765 staticpro (&QCcrop);
8766 QCrotation = intern_c_string (":rotation");
8767 staticpro (&QCrotation);
8768 QCmatrix = intern_c_string (":matrix");
8769 staticpro (&QCmatrix);
8770 QCcolor_adjustment = intern_c_string (":color-adjustment");
8771 staticpro (&QCcolor_adjustment);
8772 QCmask = intern_c_string (":mask");
8773 staticpro (&QCmask);
8775 Qlaplace = intern_c_string ("laplace");
8776 staticpro (&Qlaplace);
8777 Qemboss = intern_c_string ("emboss");
8778 staticpro (&Qemboss);
8779 Qedge_detection = intern_c_string ("edge-detection");
8780 staticpro (&Qedge_detection);
8781 Qheuristic = intern_c_string ("heuristic");
8782 staticpro (&Qheuristic);
8784 Qpostscript = intern_c_string ("postscript");
8785 staticpro (&Qpostscript);
8786 #ifdef HAVE_GHOSTSCRIPT
8787 ADD_IMAGE_TYPE (Qpostscript);
8788 QCloader = intern_c_string (":loader");
8789 staticpro (&QCloader);
8790 QCbounding_box = intern_c_string (":bounding-box");
8791 staticpro (&QCbounding_box);
8792 QCpt_width = intern_c_string (":pt-width");
8793 staticpro (&QCpt_width);
8794 QCpt_height = intern_c_string (":pt-height");
8795 staticpro (&QCpt_height);
8796 #endif /* HAVE_GHOSTSCRIPT */
8798 #ifdef HAVE_NTGUI
8799 Qlibpng_version = intern_c_string ("libpng-version");
8800 staticpro (&Qlibpng_version);
8801 #if HAVE_PNG
8802 SET_SYMBOL_VAL (XSYMBOL (Qlibpng_version), make_number (PNG_LIBPNG_VER));
8803 #else
8804 SET_SYMBOL_VAL (XSYMBOL (Qlibpng_version), make_number (-1));
8805 #endif
8806 #endif
8808 #if defined (HAVE_XPM) || defined (HAVE_NS)
8809 Qxpm = intern_c_string ("xpm");
8810 staticpro (&Qxpm);
8811 ADD_IMAGE_TYPE (Qxpm);
8812 #endif
8814 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8815 Qjpeg = intern_c_string ("jpeg");
8816 staticpro (&Qjpeg);
8817 ADD_IMAGE_TYPE (Qjpeg);
8818 #endif
8820 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8821 Qtiff = intern_c_string ("tiff");
8822 staticpro (&Qtiff);
8823 ADD_IMAGE_TYPE (Qtiff);
8824 #endif
8826 #if defined (HAVE_GIF) || defined (HAVE_NS)
8827 Qgif = intern_c_string ("gif");
8828 staticpro (&Qgif);
8829 ADD_IMAGE_TYPE (Qgif);
8830 #endif
8832 #if defined (HAVE_PNG) || defined (HAVE_NS)
8833 Qpng = intern_c_string ("png");
8834 staticpro (&Qpng);
8835 ADD_IMAGE_TYPE (Qpng);
8836 #endif
8838 #if defined (HAVE_IMAGEMAGICK)
8839 Qimagemagick = intern_c_string ("imagemagick");
8840 staticpro (&Qimagemagick);
8841 ADD_IMAGE_TYPE (Qimagemagick);
8842 #endif
8844 #if defined (HAVE_RSVG)
8845 Qsvg = intern_c_string ("svg");
8846 staticpro (&Qsvg);
8847 ADD_IMAGE_TYPE (Qsvg);
8848 #ifdef HAVE_NTGUI
8849 /* Other libraries used directly by svg code. */
8850 Qgdk_pixbuf = intern_c_string ("gdk-pixbuf");
8851 staticpro (&Qgdk_pixbuf);
8852 Qglib = intern_c_string ("glib");
8853 staticpro (&Qglib);
8854 Qgobject = intern_c_string ("gobject");
8855 staticpro (&Qgobject);
8856 #endif /* HAVE_NTGUI */
8857 #endif /* HAVE_RSVG */
8859 defsubr (&Sinit_image_library);
8860 #ifdef HAVE_IMAGEMAGICK
8861 defsubr (&Simagemagick_types);
8862 #endif
8863 defsubr (&Sclear_image_cache);
8864 defsubr (&Simage_flush);
8865 defsubr (&Simage_size);
8866 defsubr (&Simage_mask_p);
8867 defsubr (&Simage_metadata);
8869 #if GLYPH_DEBUG
8870 defsubr (&Simagep);
8871 defsubr (&Slookup_image);
8872 #endif
8874 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
8875 doc: /* Non-nil means always draw a cross over disabled images.
8876 Disabled images are those having a `:conversion disabled' property.
8877 A cross is always drawn on black & white displays. */);
8878 cross_disabled_images = 0;
8880 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
8881 doc: /* List of directories to search for window system bitmap files. */);
8882 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8884 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
8885 doc: /* Maximum time after which images are removed from the cache.
8886 When an image has not been displayed this many seconds, Emacs
8887 automatically removes it from the image cache. If the cache contains
8888 a large number of images, the actual eviction time may be shorter.
8889 The value can also be nil, meaning the cache is never cleared.
8891 The function `clear-image-cache' disregards this variable. */);
8892 Vimage_cache_eviction_delay = make_number (300);
8893 #ifdef HAVE_IMAGEMAGICK
8894 DEFVAR_LISP ("imagemagick-render-type", &Vimagemagick_render_type,
8895 doc: /* Choose between ImageMagick render methods. */);
8896 #endif
8900 void
8901 init_image (void)
8905 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
8906 (do not change this comment) */