deps.mk: Update for recent changes: gnutls, gnulib imports, globals.h.
[emacs.git] / src / image.c
blob8303fac4c98626ac70adf1a43a80849c687f853e
1 /* Functions for image support on window system.
2 Copyright (C) 1989, 1992-2011 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <math.h>
22 #include <ctype.h>
23 #include <unistd.h>
25 #ifdef HAVE_PNG
26 #if defined HAVE_LIBPNG_PNG_H
27 # include <libpng/png.h>
28 #else
29 # include <png.h>
30 #endif
31 #endif
33 #include <setjmp.h>
35 /* This makes the fields of a Display accessible, in Xlib header files. */
37 #define XLIB_ILLEGAL_ACCESS
39 #include "lisp.h"
40 #include "frame.h"
41 #include "window.h"
42 #include "dispextern.h"
43 #include "blockinput.h"
44 #include "systime.h"
45 #include <epaths.h>
46 #include "character.h"
47 #include "coding.h"
48 #include "termhooks.h"
49 #include "font.h"
51 #ifdef HAVE_X_WINDOWS
52 #include "xterm.h"
53 #include <sys/types.h>
54 #include <sys/stat.h>
56 #define COLOR_TABLE_SUPPORT 1
58 typedef struct x_bitmap_record Bitmap_Record;
59 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
60 #define NO_PIXMAP None
62 #define RGB_PIXEL_COLOR unsigned long
64 #define PIX_MASK_RETAIN 0
65 #define PIX_MASK_DRAW 1
66 #endif /* HAVE_X_WINDOWS */
69 #ifdef HAVE_NTGUI
70 #include "w32term.h"
72 /* W32_TODO : Color tables on W32. */
73 #undef COLOR_TABLE_SUPPORT
75 typedef struct w32_bitmap_record Bitmap_Record;
76 #define GET_PIXEL(ximg, x, y) GetPixel(ximg, x, y)
77 #define NO_PIXMAP 0
79 #define RGB_PIXEL_COLOR COLORREF
81 #define PIX_MASK_RETAIN 0
82 #define PIX_MASK_DRAW 1
84 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
85 #define x_defined_color w32_defined_color
86 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
88 /* Functions from w32term.c that depend on XColor (so can't go in w32term.h
89 without modifying lots of files). */
90 extern void x_query_colors (struct frame *f, XColor *colors, int ncolors);
91 extern void x_query_color (struct frame *f, XColor *color);
93 /* Version of libpng that we were compiled with, or -1 if no PNG
94 support was compiled in. This is tested by w32-win.el to correctly
95 set up the alist used to search for PNG libraries. */
96 Lisp_Object Qlibpng_version;
97 #endif /* HAVE_NTGUI */
99 #ifdef HAVE_NS
100 #include "nsterm.h"
101 #include <sys/types.h>
102 #include <sys/stat.h>
104 #undef COLOR_TABLE_SUPPORT
106 typedef struct ns_bitmap_record Bitmap_Record;
108 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
109 #define NO_PIXMAP 0
111 #define RGB_PIXEL_COLOR unsigned long
112 #define ZPixmap 0
114 #define PIX_MASK_RETAIN 0
115 #define PIX_MASK_DRAW 1
117 #define FRAME_X_VISUAL FRAME_NS_DISPLAY_INFO(f)->visual
118 #define x_defined_color(f, name, color_def, alloc) \
119 ns_defined_color (f, name, color_def, alloc, 0)
120 #define FRAME_X_SCREEN(f) 0
121 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
122 #endif /* HAVE_NS */
125 /* The symbol `postscript' identifying images of this type. */
127 Lisp_Object Qpostscript;
129 static void x_disable_image (struct frame *, struct image *);
130 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
131 Lisp_Object);
133 static void init_color_table (void);
134 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
135 #ifdef COLOR_TABLE_SUPPORT
136 static void free_color_table (void);
137 static unsigned long *colors_in_color_table (int *n);
138 static unsigned long lookup_pixel_color (struct frame *f, unsigned long p);
139 #endif
141 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
142 id, which is just an int that this section returns. Bitmaps are
143 reference counted so they can be shared among frames.
145 Bitmap indices are guaranteed to be > 0, so a negative number can
146 be used to indicate no bitmap.
148 If you use x_create_bitmap_from_data, then you must keep track of
149 the bitmaps yourself. That is, creating a bitmap from the same
150 data more than once will not be caught. */
152 #ifdef HAVE_NS
153 XImagePtr
154 XGetImage (Display *display, Pixmap pixmap, int x, int y,
155 unsigned int width, unsigned int height,
156 unsigned long plane_mask, int format)
158 /* TODO: not sure what this function is supposed to do.. */
159 ns_retain_object (pixmap);
160 return pixmap;
163 /* use with imgs created by ns_image_for_XPM */
164 unsigned long
165 XGetPixel (XImagePtr ximage, int x, int y)
167 return ns_get_pixel (ximage, x, y);
170 /* use with imgs created by ns_image_for_XPM; alpha set to 1;
171 pixel is assumed to be in form RGB */
172 void
173 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
175 ns_put_pixel (ximage, x, y, pixel);
177 #endif /* HAVE_NS */
180 /* Functions to access the contents of a bitmap, given an id. */
183 x_bitmap_height (FRAME_PTR f, int id)
185 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
189 x_bitmap_width (FRAME_PTR f, int id)
191 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
194 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
196 x_bitmap_pixmap (FRAME_PTR f, int id)
198 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
200 #endif
202 #ifdef HAVE_X_WINDOWS
204 x_bitmap_mask (FRAME_PTR f, int id)
206 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
208 #endif
210 /* Allocate a new bitmap record. Returns index of new record. */
212 static int
213 x_allocate_bitmap_record (FRAME_PTR f)
215 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
216 int i;
218 if (dpyinfo->bitmaps == NULL)
220 dpyinfo->bitmaps_size = 10;
221 dpyinfo->bitmaps
222 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
223 dpyinfo->bitmaps_last = 1;
224 return 1;
227 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
228 return ++dpyinfo->bitmaps_last;
230 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
231 if (dpyinfo->bitmaps[i].refcount == 0)
232 return i + 1;
234 dpyinfo->bitmaps_size *= 2;
235 dpyinfo->bitmaps
236 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
237 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
238 return ++dpyinfo->bitmaps_last;
241 /* Add one reference to the reference count of the bitmap with id ID. */
243 void
244 x_reference_bitmap (FRAME_PTR f, int id)
246 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
249 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
252 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
254 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
255 int id;
257 #ifdef HAVE_X_WINDOWS
258 Pixmap bitmap;
259 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
260 bits, width, height);
261 if (! bitmap)
262 return -1;
263 #endif /* HAVE_X_WINDOWS */
265 #ifdef HAVE_NTGUI
266 Pixmap bitmap;
267 bitmap = CreateBitmap (width, height,
268 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
269 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
270 bits);
271 if (! bitmap)
272 return -1;
273 #endif /* HAVE_NTGUI */
275 #ifdef HAVE_NS
276 void *bitmap = ns_image_from_XBM (bits, width, height);
277 if (!bitmap)
278 return -1;
279 #endif
281 id = x_allocate_bitmap_record (f);
283 #ifdef HAVE_NS
284 dpyinfo->bitmaps[id - 1].img = bitmap;
285 dpyinfo->bitmaps[id - 1].depth = 1;
286 #endif
288 dpyinfo->bitmaps[id - 1].file = NULL;
289 dpyinfo->bitmaps[id - 1].height = height;
290 dpyinfo->bitmaps[id - 1].width = width;
291 dpyinfo->bitmaps[id - 1].refcount = 1;
293 #ifdef HAVE_X_WINDOWS
294 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
295 dpyinfo->bitmaps[id - 1].have_mask = 0;
296 dpyinfo->bitmaps[id - 1].depth = 1;
297 #endif /* HAVE_X_WINDOWS */
299 #ifdef HAVE_NTGUI
300 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
301 dpyinfo->bitmaps[id - 1].hinst = NULL;
302 dpyinfo->bitmaps[id - 1].depth = 1;
303 #endif /* HAVE_NTGUI */
305 return id;
308 /* Create bitmap from file FILE for frame F. */
311 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
313 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
315 #ifdef HAVE_NTGUI
316 return -1; /* W32_TODO : bitmap support */
317 #endif /* HAVE_NTGUI */
319 #ifdef HAVE_NS
320 int id;
321 void *bitmap = ns_image_from_file (file);
323 if (!bitmap)
324 return -1;
327 id = x_allocate_bitmap_record (f);
328 dpyinfo->bitmaps[id - 1].img = bitmap;
329 dpyinfo->bitmaps[id - 1].refcount = 1;
330 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
331 dpyinfo->bitmaps[id - 1].depth = 1;
332 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
333 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
334 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
335 return id;
336 #endif
338 #ifdef HAVE_X_WINDOWS
339 unsigned int width, height;
340 Pixmap bitmap;
341 int xhot, yhot, result, id;
342 Lisp_Object found;
343 int fd;
344 char *filename;
346 /* Look for an existing bitmap with the same name. */
347 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
349 if (dpyinfo->bitmaps[id].refcount
350 && dpyinfo->bitmaps[id].file
351 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
353 ++dpyinfo->bitmaps[id].refcount;
354 return id + 1;
358 /* Search bitmap-file-path for the file, if appropriate. */
359 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
360 if (fd < 0)
361 return -1;
362 emacs_close (fd);
364 filename = SSDATA (found);
366 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
367 filename, &width, &height, &bitmap, &xhot, &yhot);
368 if (result != BitmapSuccess)
369 return -1;
371 id = x_allocate_bitmap_record (f);
372 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
373 dpyinfo->bitmaps[id - 1].have_mask = 0;
374 dpyinfo->bitmaps[id - 1].refcount = 1;
375 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
376 dpyinfo->bitmaps[id - 1].depth = 1;
377 dpyinfo->bitmaps[id - 1].height = height;
378 dpyinfo->bitmaps[id - 1].width = width;
379 strcpy (dpyinfo->bitmaps[id - 1].file, SSDATA (file));
381 return id;
382 #endif /* HAVE_X_WINDOWS */
385 /* Free bitmap B. */
387 static void
388 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
390 #ifdef HAVE_X_WINDOWS
391 XFreePixmap (dpyinfo->display, bm->pixmap);
392 if (bm->have_mask)
393 XFreePixmap (dpyinfo->display, bm->mask);
394 #endif /* HAVE_X_WINDOWS */
396 #ifdef HAVE_NTGUI
397 DeleteObject (bm->pixmap);
398 #endif /* HAVE_NTGUI */
400 #ifdef HAVE_NS
401 ns_release_object (bm->img);
402 #endif
404 if (bm->file)
406 xfree (bm->file);
407 bm->file = NULL;
411 /* Remove reference to bitmap with id number ID. */
413 void
414 x_destroy_bitmap (FRAME_PTR f, int id)
416 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
418 if (id > 0)
420 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
422 if (--bm->refcount == 0)
424 BLOCK_INPUT;
425 free_bitmap_record (dpyinfo, bm);
426 UNBLOCK_INPUT;
431 /* Free all the bitmaps for the display specified by DPYINFO. */
433 void
434 x_destroy_all_bitmaps (Display_Info *dpyinfo)
436 int i;
437 Bitmap_Record *bm = dpyinfo->bitmaps;
439 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
440 if (bm->refcount > 0)
441 free_bitmap_record (dpyinfo, bm);
443 dpyinfo->bitmaps_last = 0;
447 #ifdef HAVE_X_WINDOWS
449 /* Useful functions defined in the section
450 `Image type independent image structures' below. */
452 static unsigned long four_corners_best (XImagePtr ximg,
453 int *corners,
454 unsigned long width,
455 unsigned long height);
457 static int x_create_x_image_and_pixmap (struct frame *f, int width, int height,
458 int depth, XImagePtr *ximg,
459 Pixmap *pixmap);
461 static void x_destroy_x_image (XImagePtr ximg);
464 /* Create a mask of a bitmap. Note is this not a perfect mask.
465 It's nicer with some borders in this context */
468 x_create_bitmap_mask (struct frame *f, int id)
470 Pixmap pixmap, mask;
471 XImagePtr ximg, mask_img;
472 unsigned long width, height;
473 int result;
474 unsigned long bg;
475 unsigned long x, y, xp, xm, yp, ym;
476 GC gc;
478 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
480 if (!(id > 0))
481 return -1;
483 pixmap = x_bitmap_pixmap (f, id);
484 width = x_bitmap_width (f, id);
485 height = x_bitmap_height (f, id);
487 BLOCK_INPUT;
488 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
489 ~0, ZPixmap);
491 if (!ximg)
493 UNBLOCK_INPUT;
494 return -1;
497 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
499 UNBLOCK_INPUT;
500 if (!result)
502 XDestroyImage (ximg);
503 return -1;
506 bg = four_corners_best (ximg, NULL, width, height);
508 for (y = 0; y < ximg->height; ++y)
510 for (x = 0; x < ximg->width; ++x)
512 xp = x != ximg->width - 1 ? x + 1 : 0;
513 xm = x != 0 ? x - 1 : ximg->width - 1;
514 yp = y != ximg->height - 1 ? y + 1 : 0;
515 ym = y != 0 ? y - 1 : ximg->height - 1;
516 if (XGetPixel (ximg, x, y) == bg
517 && XGetPixel (ximg, x, yp) == bg
518 && XGetPixel (ximg, x, ym) == bg
519 && XGetPixel (ximg, xp, y) == bg
520 && XGetPixel (ximg, xp, yp) == bg
521 && XGetPixel (ximg, xp, ym) == bg
522 && XGetPixel (ximg, xm, y) == bg
523 && XGetPixel (ximg, xm, yp) == bg
524 && XGetPixel (ximg, xm, ym) == bg)
525 XPutPixel (mask_img, x, y, 0);
526 else
527 XPutPixel (mask_img, x, y, 1);
531 xassert (interrupt_input_blocked);
532 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
533 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
534 width, height);
535 XFreeGC (FRAME_X_DISPLAY (f), gc);
537 dpyinfo->bitmaps[id - 1].have_mask = 1;
538 dpyinfo->bitmaps[id - 1].mask = mask;
540 XDestroyImage (ximg);
541 x_destroy_x_image (mask_img);
543 return 0;
546 #endif /* HAVE_X_WINDOWS */
549 /***********************************************************************
550 Image types
551 ***********************************************************************/
553 /* Value is the number of elements of vector VECTOR. */
555 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
557 /* List of supported image types. Use define_image_type to add new
558 types. Use lookup_image_type to find a type for a given symbol. */
560 static struct image_type *image_types;
562 /* Cache for delayed-loading image types. */
564 static Lisp_Object Vimage_type_cache;
566 /* The symbol `xbm' which is used as the type symbol for XBM images. */
568 Lisp_Object Qxbm;
570 /* Keywords. */
572 Lisp_Object QCascent, QCmargin, QCrelief, Qcount, Qextension_data;
573 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
574 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry, QCcrop, QCrotation;
576 /* Other symbols. */
578 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
580 /* Function prototypes. */
582 static Lisp_Object define_image_type (struct image_type *type, int loaded);
583 static struct image_type *lookup_image_type (Lisp_Object symbol);
584 static void image_error (const char *format, Lisp_Object, Lisp_Object);
585 static void x_laplace (struct frame *, struct image *);
586 static void x_emboss (struct frame *, struct image *);
587 static int x_build_heuristic_mask (struct frame *, struct image *,
588 Lisp_Object);
590 #define CACHE_IMAGE_TYPE(type, status) \
591 do { Vimage_type_cache = Fcons (Fcons (type, status), Vimage_type_cache); } while (0)
593 #define ADD_IMAGE_TYPE(type) \
594 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
596 /* Define a new image type from TYPE. This adds a copy of TYPE to
597 image_types and caches the loading status of TYPE. */
599 static Lisp_Object
600 define_image_type (struct image_type *type, int loaded)
602 Lisp_Object success;
604 if (!loaded)
605 success = Qnil;
606 else
608 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
609 The initialized data segment is read-only. */
610 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
611 memcpy (p, type, sizeof *p);
612 p->next = image_types;
613 image_types = p;
614 success = Qt;
617 CACHE_IMAGE_TYPE (*type->type, success);
618 return success;
622 /* Look up image type SYMBOL, and return a pointer to its image_type
623 structure. Value is null if SYMBOL is not a known image type. */
625 static INLINE struct image_type *
626 lookup_image_type (Lisp_Object symbol)
628 struct image_type *type;
630 /* We must initialize the image-type if it hasn't been already. */
631 if (NILP (Finit_image_library (symbol, Vdynamic_library_alist)))
632 return 0; /* unimplemented */
634 for (type = image_types; type; type = type->next)
635 if (EQ (symbol, *type->type))
636 break;
638 return type;
642 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
643 valid image specification is a list whose car is the symbol
644 `image', and whose rest is a property list. The property list must
645 contain a value for key `:type'. That value must be the name of a
646 supported image type. The rest of the property list depends on the
647 image type. */
650 valid_image_p (Lisp_Object object)
652 int valid_p = 0;
654 if (IMAGEP (object))
656 Lisp_Object tem;
658 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
659 if (EQ (XCAR (tem), QCtype))
661 tem = XCDR (tem);
662 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
664 struct image_type *type;
665 type = lookup_image_type (XCAR (tem));
666 if (type)
667 valid_p = type->valid_p (object);
670 break;
674 return valid_p;
678 /* Log error message with format string FORMAT and argument ARG.
679 Signaling an error, e.g. when an image cannot be loaded, is not a
680 good idea because this would interrupt redisplay, and the error
681 message display would lead to another redisplay. This function
682 therefore simply displays a message. */
684 static void
685 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
687 add_to_log (format, arg1, arg2);
692 /***********************************************************************
693 Image specifications
694 ***********************************************************************/
696 enum image_value_type
698 IMAGE_DONT_CHECK_VALUE_TYPE,
699 IMAGE_STRING_VALUE,
700 IMAGE_STRING_OR_NIL_VALUE,
701 IMAGE_SYMBOL_VALUE,
702 IMAGE_POSITIVE_INTEGER_VALUE,
703 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
704 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
705 IMAGE_ASCENT_VALUE,
706 IMAGE_INTEGER_VALUE,
707 IMAGE_FUNCTION_VALUE,
708 IMAGE_NUMBER_VALUE,
709 IMAGE_BOOL_VALUE
712 /* Structure used when parsing image specifications. */
714 struct image_keyword
716 /* Name of keyword. */
717 const char *name;
719 /* The type of value allowed. */
720 enum image_value_type type;
722 /* Non-zero means key must be present. */
723 int mandatory_p;
725 /* Used to recognize duplicate keywords in a property list. */
726 int count;
728 /* The value that was found. */
729 Lisp_Object value;
733 static int parse_image_spec (Lisp_Object, struct image_keyword *,
734 int, Lisp_Object);
735 static Lisp_Object image_spec_value (Lisp_Object, Lisp_Object, int *);
738 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
739 has the format (image KEYWORD VALUE ...). One of the keyword/
740 value pairs must be `:type TYPE'. KEYWORDS is a vector of
741 image_keywords structures of size NKEYWORDS describing other
742 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
744 static int
745 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
746 int nkeywords, Lisp_Object type)
748 int i;
749 Lisp_Object plist;
751 if (!IMAGEP (spec))
752 return 0;
754 plist = XCDR (spec);
755 while (CONSP (plist))
757 Lisp_Object key, value;
759 /* First element of a pair must be a symbol. */
760 key = XCAR (plist);
761 plist = XCDR (plist);
762 if (!SYMBOLP (key))
763 return 0;
765 /* There must follow a value. */
766 if (!CONSP (plist))
767 return 0;
768 value = XCAR (plist);
769 plist = XCDR (plist);
771 /* Find key in KEYWORDS. Error if not found. */
772 for (i = 0; i < nkeywords; ++i)
773 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
774 break;
776 if (i == nkeywords)
777 continue;
779 /* Record that we recognized the keyword. If a keywords
780 was found more than once, it's an error. */
781 keywords[i].value = value;
782 ++keywords[i].count;
784 if (keywords[i].count > 1)
785 return 0;
787 /* Check type of value against allowed type. */
788 switch (keywords[i].type)
790 case IMAGE_STRING_VALUE:
791 if (!STRINGP (value))
792 return 0;
793 break;
795 case IMAGE_STRING_OR_NIL_VALUE:
796 if (!STRINGP (value) && !NILP (value))
797 return 0;
798 break;
800 case IMAGE_SYMBOL_VALUE:
801 if (!SYMBOLP (value))
802 return 0;
803 break;
805 case IMAGE_POSITIVE_INTEGER_VALUE:
806 if (!INTEGERP (value) || XINT (value) <= 0)
807 return 0;
808 break;
810 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
811 if (INTEGERP (value) && XINT (value) >= 0)
812 break;
813 if (CONSP (value)
814 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
815 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
816 break;
817 return 0;
819 case IMAGE_ASCENT_VALUE:
820 if (SYMBOLP (value) && EQ (value, Qcenter))
821 break;
822 else if (INTEGERP (value)
823 && XINT (value) >= 0
824 && XINT (value) <= 100)
825 break;
826 return 0;
828 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
829 if (!INTEGERP (value) || XINT (value) < 0)
830 return 0;
831 break;
833 case IMAGE_DONT_CHECK_VALUE_TYPE:
834 break;
836 case IMAGE_FUNCTION_VALUE:
837 value = indirect_function (value);
838 if (SUBRP (value)
839 || COMPILEDP (value)
840 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
841 break;
842 return 0;
844 case IMAGE_NUMBER_VALUE:
845 if (!INTEGERP (value) && !FLOATP (value))
846 return 0;
847 break;
849 case IMAGE_INTEGER_VALUE:
850 if (!INTEGERP (value))
851 return 0;
852 break;
854 case IMAGE_BOOL_VALUE:
855 if (!NILP (value) && !EQ (value, Qt))
856 return 0;
857 break;
859 default:
860 abort ();
861 break;
864 if (EQ (key, QCtype) && !EQ (type, value))
865 return 0;
868 /* Check that all mandatory fields are present. */
869 for (i = 0; i < nkeywords; ++i)
870 if (keywords[i].mandatory_p && keywords[i].count == 0)
871 return 0;
873 return NILP (plist);
877 /* Return the value of KEY in image specification SPEC. Value is nil
878 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
879 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
881 static Lisp_Object
882 image_spec_value (Lisp_Object spec, Lisp_Object key, int *found)
884 Lisp_Object tail;
886 xassert (valid_image_p (spec));
888 for (tail = XCDR (spec);
889 CONSP (tail) && CONSP (XCDR (tail));
890 tail = XCDR (XCDR (tail)))
892 if (EQ (XCAR (tail), key))
894 if (found)
895 *found = 1;
896 return XCAR (XCDR (tail));
900 if (found)
901 *found = 0;
902 return Qnil;
906 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
907 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
908 PIXELS non-nil means return the size in pixels, otherwise return the
909 size in canonical character units.
910 FRAME is the frame on which the image will be displayed. FRAME nil
911 or omitted means use the selected frame. */)
912 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
914 Lisp_Object size;
916 size = Qnil;
917 if (valid_image_p (spec))
919 struct frame *f = check_x_frame (frame);
920 int id = lookup_image (f, spec);
921 struct image *img = IMAGE_FROM_ID (f, id);
922 int width = img->width + 2 * img->hmargin;
923 int height = img->height + 2 * img->vmargin;
925 if (NILP (pixels))
926 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
927 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
928 else
929 size = Fcons (make_number (width), make_number (height));
931 else
932 error ("Invalid image specification");
934 return size;
938 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
939 doc: /* Return t if image SPEC has a mask bitmap.
940 FRAME is the frame on which the image will be displayed. FRAME nil
941 or omitted means use the selected frame. */)
942 (Lisp_Object spec, Lisp_Object frame)
944 Lisp_Object mask;
946 mask = Qnil;
947 if (valid_image_p (spec))
949 struct frame *f = check_x_frame (frame);
950 int id = lookup_image (f, spec);
951 struct image *img = IMAGE_FROM_ID (f, id);
952 if (img->mask)
953 mask = Qt;
955 else
956 error ("Invalid image specification");
958 return mask;
961 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
962 doc: /* Return metadata for image SPEC.
963 FRAME is the frame on which the image will be displayed. FRAME nil
964 or omitted means use the selected frame. */)
965 (Lisp_Object spec, Lisp_Object frame)
967 Lisp_Object ext;
969 ext = Qnil;
970 if (valid_image_p (spec))
972 struct frame *f = check_x_frame (frame);
973 int id = lookup_image (f, spec);
974 struct image *img = IMAGE_FROM_ID (f, id);
975 ext = img->data.lisp_val;
978 return ext;
982 /***********************************************************************
983 Image type independent image structures
984 ***********************************************************************/
986 static struct image *make_image (Lisp_Object spec, unsigned hash);
987 static void free_image (struct frame *f, struct image *img);
988 static int check_image_size (struct frame *f, int width, int height);
990 #define MAX_IMAGE_SIZE 6.0
991 /* Allocate and return a new image structure for image specification
992 SPEC. SPEC has a hash value of HASH. */
994 static struct image *
995 make_image (Lisp_Object spec, unsigned int hash)
997 struct image *img = (struct image *) xmalloc (sizeof *img);
998 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
1000 xassert (valid_image_p (spec));
1001 memset (img, 0, sizeof *img);
1002 img->dependencies = NILP (file) ? Qnil : list1 (file);
1003 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1004 xassert (img->type != NULL);
1005 img->spec = spec;
1006 img->data.lisp_val = Qnil;
1007 img->ascent = DEFAULT_IMAGE_ASCENT;
1008 img->hash = hash;
1009 img->corners[BOT_CORNER] = -1; /* Full image */
1010 return img;
1014 /* Free image IMG which was used on frame F, including its resources. */
1016 static void
1017 free_image (struct frame *f, struct image *img)
1019 if (img)
1021 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1023 /* Remove IMG from the hash table of its cache. */
1024 if (img->prev)
1025 img->prev->next = img->next;
1026 else
1027 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1029 if (img->next)
1030 img->next->prev = img->prev;
1032 c->images[img->id] = NULL;
1034 /* Free resources, then free IMG. */
1035 img->type->free (f, img);
1036 xfree (img);
1040 /* Return 1 if the given widths and heights are valid for display;
1041 otherwise, return 0. */
1044 check_image_size (struct frame *f, int width, int height)
1046 int w, h;
1048 if (width <= 0 || height <= 0)
1049 return 0;
1051 if (INTEGERP (Vmax_image_size))
1052 w = h = XINT (Vmax_image_size);
1053 else if (FLOATP (Vmax_image_size))
1055 if (f != NULL)
1057 w = FRAME_PIXEL_WIDTH (f);
1058 h = FRAME_PIXEL_HEIGHT (f);
1060 else
1061 w = h = 1024; /* Arbitrary size for unknown frame. */
1062 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1063 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1065 else
1066 return 1;
1068 return (width <= w && height <= h);
1071 /* Prepare image IMG for display on frame F. Must be called before
1072 drawing an image. */
1074 void
1075 prepare_image_for_display (struct frame *f, struct image *img)
1077 EMACS_TIME t;
1079 /* We're about to display IMG, so set its timestamp to `now'. */
1080 EMACS_GET_TIME (t);
1081 img->timestamp = EMACS_SECS (t);
1083 /* If IMG doesn't have a pixmap yet, load it now, using the image
1084 type dependent loader function. */
1085 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1086 img->load_failed_p = img->type->load (f, img) == 0;
1091 /* Value is the number of pixels for the ascent of image IMG when
1092 drawn in face FACE. */
1095 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1097 int height;
1098 int ascent;
1100 if (slice->height == img->height)
1101 height = img->height + img->vmargin;
1102 else if (slice->y == 0)
1103 height = slice->height + img->vmargin;
1104 else
1105 height = slice->height;
1107 if (img->ascent == CENTERED_IMAGE_ASCENT)
1109 if (face->font)
1111 #ifdef HAVE_NTGUI
1112 /* W32 specific version. Why?. ++kfs */
1113 ascent = height / 2 - (FONT_DESCENT (face->font)
1114 - FONT_BASE (face->font)) / 2;
1115 #else
1116 /* This expression is arranged so that if the image can't be
1117 exactly centered, it will be moved slightly up. This is
1118 because a typical font is `top-heavy' (due to the presence
1119 uppercase letters), so the image placement should err towards
1120 being top-heavy too. It also just generally looks better. */
1121 ascent = (height + FONT_BASE(face->font)
1122 - FONT_DESCENT(face->font) + 1) / 2;
1123 #endif /* HAVE_NTGUI */
1125 else
1126 ascent = height / 2;
1128 else
1129 ascent = (int) (height * img->ascent / 100.0);
1131 return ascent;
1135 /* Image background colors. */
1137 /* Find the "best" corner color of a bitmap.
1138 On W32, XIMG is assumed to a device context with the bitmap selected. */
1140 static RGB_PIXEL_COLOR
1141 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1142 unsigned long width, unsigned long height)
1144 RGB_PIXEL_COLOR corner_pixels[4], best;
1145 int i, best_count;
1147 if (corners && corners[BOT_CORNER] >= 0)
1149 /* Get the colors at the corner_pixels of ximg. */
1150 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1151 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1152 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1153 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1155 else
1157 /* Get the colors at the corner_pixels of ximg. */
1158 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1159 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1160 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1161 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1163 /* Choose the most frequently found color as background. */
1164 for (i = best_count = 0; i < 4; ++i)
1166 int j, n;
1168 for (j = n = 0; j < 4; ++j)
1169 if (corner_pixels[i] == corner_pixels[j])
1170 ++n;
1172 if (n > best_count)
1173 best = corner_pixels[i], best_count = n;
1176 return best;
1179 /* Portability macros */
1181 #ifdef HAVE_NTGUI
1183 #define Destroy_Image(img_dc, prev) \
1184 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1186 #define Free_Pixmap(display, pixmap) \
1187 DeleteObject (pixmap)
1189 #elif defined (HAVE_NS)
1191 #define Destroy_Image(ximg, dummy) \
1192 ns_release_object (ximg)
1194 #define Free_Pixmap(display, pixmap) \
1195 ns_release_object (pixmap)
1197 #else
1199 #define Destroy_Image(ximg, dummy) \
1200 XDestroyImage (ximg)
1202 #define Free_Pixmap(display, pixmap) \
1203 XFreePixmap (display, pixmap)
1205 #endif /* !HAVE_NTGUI && !HAVE_NS */
1208 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1209 it is guessed heuristically. If non-zero, XIMG is an existing
1210 XImage object (or device context with the image selected on W32) to
1211 use for the heuristic. */
1213 RGB_PIXEL_COLOR
1214 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1216 if (! img->background_valid)
1217 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1219 int free_ximg = !ximg;
1220 #ifdef HAVE_NTGUI
1221 HGDIOBJ prev;
1222 #endif /* HAVE_NTGUI */
1224 if (free_ximg)
1226 #ifndef HAVE_NTGUI
1227 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1228 0, 0, img->width, img->height, ~0, ZPixmap);
1229 #else
1230 HDC frame_dc = get_frame_dc (f);
1231 ximg = CreateCompatibleDC (frame_dc);
1232 release_frame_dc (f, frame_dc);
1233 prev = SelectObject (ximg, img->pixmap);
1234 #endif /* !HAVE_NTGUI */
1237 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1239 if (free_ximg)
1240 Destroy_Image (ximg, prev);
1242 img->background_valid = 1;
1245 return img->background;
1248 /* Return the `background_transparent' field of IMG. If IMG doesn't
1249 have one yet, it is guessed heuristically. If non-zero, MASK is an
1250 existing XImage object to use for the heuristic. */
1253 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1255 if (! img->background_transparent_valid)
1256 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1258 if (img->mask)
1260 int free_mask = !mask;
1261 #ifdef HAVE_NTGUI
1262 HGDIOBJ prev;
1263 #endif /* HAVE_NTGUI */
1265 if (free_mask)
1267 #ifndef HAVE_NTGUI
1268 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1269 0, 0, img->width, img->height, ~0, ZPixmap);
1270 #else
1271 HDC frame_dc = get_frame_dc (f);
1272 mask = CreateCompatibleDC (frame_dc);
1273 release_frame_dc (f, frame_dc);
1274 prev = SelectObject (mask, img->mask);
1275 #endif /* HAVE_NTGUI */
1278 img->background_transparent
1279 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1281 if (free_mask)
1282 Destroy_Image (mask, prev);
1284 else
1285 img->background_transparent = 0;
1287 img->background_transparent_valid = 1;
1290 return img->background_transparent;
1294 /***********************************************************************
1295 Helper functions for X image types
1296 ***********************************************************************/
1298 static void x_clear_image_1 (struct frame *, struct image *, int,
1299 int, int);
1300 static void x_clear_image (struct frame *f, struct image *img);
1301 static unsigned long x_alloc_image_color (struct frame *f,
1302 struct image *img,
1303 Lisp_Object color_name,
1304 unsigned long dflt);
1307 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1308 free the pixmap if any. MASK_P non-zero means clear the mask
1309 pixmap if any. COLORS_P non-zero means free colors allocated for
1310 the image, if any. */
1312 static void
1313 x_clear_image_1 (struct frame *f, struct image *img, int pixmap_p, int mask_p,
1314 int colors_p)
1316 if (pixmap_p && img->pixmap)
1318 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1319 img->pixmap = NO_PIXMAP;
1320 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1321 img->background_valid = 0;
1324 if (mask_p && img->mask)
1326 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1327 img->mask = NO_PIXMAP;
1328 img->background_transparent_valid = 0;
1331 if (colors_p && img->ncolors)
1333 /* W32_TODO: color table support. */
1334 #ifdef HAVE_X_WINDOWS
1335 x_free_colors (f, img->colors, img->ncolors);
1336 #endif /* HAVE_X_WINDOWS */
1337 xfree (img->colors);
1338 img->colors = NULL;
1339 img->ncolors = 0;
1344 /* Free X resources of image IMG which is used on frame F. */
1346 static void
1347 x_clear_image (struct frame *f, struct image *img)
1349 BLOCK_INPUT;
1350 x_clear_image_1 (f, img, 1, 1, 1);
1351 UNBLOCK_INPUT;
1355 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1356 cannot be allocated, use DFLT. Add a newly allocated color to
1357 IMG->colors, so that it can be freed again. Value is the pixel
1358 color. */
1360 static unsigned long
1361 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1362 unsigned long dflt)
1364 XColor color;
1365 unsigned long result;
1367 xassert (STRINGP (color_name));
1369 if (x_defined_color (f, SSDATA (color_name), &color, 1))
1371 /* This isn't called frequently so we get away with simply
1372 reallocating the color vector to the needed size, here. */
1373 ++img->ncolors;
1374 img->colors =
1375 (unsigned long *) xrealloc (img->colors,
1376 img->ncolors * sizeof *img->colors);
1377 img->colors[img->ncolors - 1] = color.pixel;
1378 result = color.pixel;
1380 else
1381 result = dflt;
1383 return result;
1388 /***********************************************************************
1389 Image Cache
1390 ***********************************************************************/
1392 static struct image *search_image_cache (struct frame *, Lisp_Object, unsigned);
1393 static void cache_image (struct frame *f, struct image *img);
1394 static void postprocess_image (struct frame *, struct image *);
1396 /* Return a new, initialized image cache that is allocated from the
1397 heap. Call free_image_cache to free an image cache. */
1399 struct image_cache *
1400 make_image_cache (void)
1402 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1403 int size;
1405 memset (c, 0, sizeof *c);
1406 c->size = 50;
1407 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1408 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1409 c->buckets = (struct image **) xmalloc (size);
1410 memset (c->buckets, 0, size);
1411 return c;
1415 /* Find an image matching SPEC in the cache, and return it. If no
1416 image is found, return NULL. */
1417 static struct image *
1418 search_image_cache (struct frame *f, Lisp_Object spec, unsigned int hash)
1420 struct image *img;
1421 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1422 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1424 if (!c) return NULL;
1426 /* If the image spec does not specify a background color, the cached
1427 image must have the same background color as the current frame.
1428 The foreground color must also match, for the sake of monochrome
1429 images.
1431 In fact, we could ignore the foreground color matching condition
1432 for color images, or if the image spec specifies :foreground;
1433 similarly we could ignore the background color matching condition
1434 for formats that don't use transparency (such as jpeg), or if the
1435 image spec specifies :background. However, the extra memory
1436 usage is probably negligible in practice, so we don't bother. */
1438 for (img = c->buckets[i]; img; img = img->next)
1439 if (img->hash == hash
1440 && !NILP (Fequal (img->spec, spec))
1441 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1442 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1443 break;
1444 return img;
1448 /* Search frame F for an image with spec SPEC, and free it. */
1450 static void
1451 uncache_image (struct frame *f, Lisp_Object spec)
1453 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1454 if (img)
1456 free_image (f, img);
1457 /* As display glyphs may still be referring to the image ID, we
1458 must garbage the frame (Bug#6426). */
1459 SET_FRAME_GARBAGED (f);
1464 /* Free image cache of frame F. Be aware that X frames share images
1465 caches. */
1467 void
1468 free_image_cache (struct frame *f)
1470 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1471 if (c)
1473 int i;
1475 /* Cache should not be referenced by any frame when freed. */
1476 xassert (c->refcount == 0);
1478 for (i = 0; i < c->used; ++i)
1479 free_image (f, c->images[i]);
1480 xfree (c->images);
1481 xfree (c->buckets);
1482 xfree (c);
1483 FRAME_IMAGE_CACHE (f) = NULL;
1488 /* Clear image cache of frame F. FILTER=t means free all images.
1489 FILTER=nil means clear only images that haven't been
1490 displayed for some time.
1491 Else, only free the images which have FILTER in their `dependencies'.
1492 Should be called from time to time to reduce the number of loaded images.
1493 If image-cache-eviction-delay is non-nil, this frees images in the cache
1494 which weren't displayed for at least that many seconds. */
1496 void
1497 clear_image_cache (struct frame *f, Lisp_Object filter)
1499 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1501 if (c)
1503 int i, nfreed = 0;
1505 /* Block input so that we won't be interrupted by a SIGIO
1506 while being in an inconsistent state. */
1507 BLOCK_INPUT;
1509 if (!NILP (filter))
1511 /* Filter image cache. */
1512 for (i = 0; i < c->used; ++i)
1514 struct image *img = c->images[i];
1515 if (img && (EQ (Qt, filter)
1516 || !NILP (Fmember (filter, img->dependencies))))
1518 free_image (f, img);
1519 ++nfreed;
1523 else if (INTEGERP (Vimage_cache_eviction_delay))
1525 /* Free cache based on timestamp. */
1526 EMACS_TIME t;
1527 unsigned long old;
1528 int delay, nimages = 0;
1530 for (i = 0; i < c->used; ++i)
1531 if (c->images[i])
1532 nimages++;
1534 /* If the number of cached images has grown unusually large,
1535 decrease the cache eviction delay (Bug#6230). */
1536 delay = XFASTINT (Vimage_cache_eviction_delay);
1537 if (nimages > 40)
1538 delay = max (1, 1600 * delay / (nimages*nimages));
1540 EMACS_GET_TIME (t);
1541 old = EMACS_SECS (t) - delay;
1543 for (i = 0; i < c->used; ++i)
1545 struct image *img = c->images[i];
1546 if (img && img->timestamp < old)
1548 free_image (f, img);
1549 ++nfreed;
1554 /* We may be clearing the image cache because, for example,
1555 Emacs was iconified for a longer period of time. In that
1556 case, current matrices may still contain references to
1557 images freed above. So, clear these matrices. */
1558 if (nfreed)
1560 Lisp_Object tail, frame;
1562 FOR_EACH_FRAME (tail, frame)
1564 struct frame *f = XFRAME (frame);
1565 if (FRAME_IMAGE_CACHE (f) == c)
1566 clear_current_matrices (f);
1569 ++windows_or_buffers_changed;
1572 UNBLOCK_INPUT;
1576 void
1577 clear_image_caches (Lisp_Object filter)
1579 /* FIXME: We want to do
1580 * struct terminal *t;
1581 * for (t = terminal_list; t; t = t->next_terminal)
1582 * clear_image_cache (t, filter); */
1583 Lisp_Object tail, frame;
1584 FOR_EACH_FRAME (tail, frame)
1585 if (FRAME_WINDOW_P (XFRAME (frame)))
1586 clear_image_cache (XFRAME (frame), filter);
1589 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1590 0, 1, 0,
1591 doc: /* Clear the image cache.
1592 FILTER nil or a frame means clear all images in the selected frame.
1593 FILTER t means clear the image caches of all frames.
1594 Anything else, means only clear those images which refer to FILTER,
1595 which is then usually a filename. */)
1596 (Lisp_Object filter)
1598 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1599 clear_image_caches (filter);
1600 else
1601 clear_image_cache (check_x_frame (filter), Qt);
1603 return Qnil;
1607 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1608 1, 2, 0,
1609 doc: /* Fush the image with specification SPEC on frame FRAME.
1610 This removes the image from the Emacs image cache. If SPEC specifies
1611 an image file, the next redisplay of this image will read from the
1612 current contents of that file.
1614 FRAME nil or omitted means use the selected frame.
1615 FRAME t means refresh the image on all frames. */)
1616 (Lisp_Object spec, Lisp_Object frame)
1618 if (!valid_image_p (spec))
1619 error ("Invalid image specification");
1621 if (EQ (frame, Qt))
1623 Lisp_Object tail;
1624 FOR_EACH_FRAME (tail, frame)
1626 struct frame *f = XFRAME (frame);
1627 if (FRAME_WINDOW_P (f))
1628 uncache_image (f, spec);
1631 else
1632 uncache_image (check_x_frame (frame), spec);
1634 return Qnil;
1638 /* Compute masks and transform image IMG on frame F, as specified
1639 by the image's specification, */
1641 static void
1642 postprocess_image (struct frame *f, struct image *img)
1644 /* Manipulation of the image's mask. */
1645 if (img->pixmap)
1647 Lisp_Object conversion, spec;
1648 Lisp_Object mask;
1650 spec = img->spec;
1652 /* `:heuristic-mask t'
1653 `:mask heuristic'
1654 means build a mask heuristically.
1655 `:heuristic-mask (R G B)'
1656 `:mask (heuristic (R G B))'
1657 means build a mask from color (R G B) in the
1658 image.
1659 `:mask nil'
1660 means remove a mask, if any. */
1662 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1663 if (!NILP (mask))
1664 x_build_heuristic_mask (f, img, mask);
1665 else
1667 int found_p;
1669 mask = image_spec_value (spec, QCmask, &found_p);
1671 if (EQ (mask, Qheuristic))
1672 x_build_heuristic_mask (f, img, Qt);
1673 else if (CONSP (mask)
1674 && EQ (XCAR (mask), Qheuristic))
1676 if (CONSP (XCDR (mask)))
1677 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1678 else
1679 x_build_heuristic_mask (f, img, XCDR (mask));
1681 else if (NILP (mask) && found_p && img->mask)
1683 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1684 img->mask = NO_PIXMAP;
1689 /* Should we apply an image transformation algorithm? */
1690 conversion = image_spec_value (spec, QCconversion, NULL);
1691 if (EQ (conversion, Qdisabled))
1692 x_disable_image (f, img);
1693 else if (EQ (conversion, Qlaplace))
1694 x_laplace (f, img);
1695 else if (EQ (conversion, Qemboss))
1696 x_emboss (f, img);
1697 else if (CONSP (conversion)
1698 && EQ (XCAR (conversion), Qedge_detection))
1700 Lisp_Object tem;
1701 tem = XCDR (conversion);
1702 if (CONSP (tem))
1703 x_edge_detection (f, img,
1704 Fplist_get (tem, QCmatrix),
1705 Fplist_get (tem, QCcolor_adjustment));
1711 /* Return the id of image with Lisp specification SPEC on frame F.
1712 SPEC must be a valid Lisp image specification (see valid_image_p). */
1715 lookup_image (struct frame *f, Lisp_Object spec)
1717 struct image_cache *c;
1718 struct image *img;
1719 unsigned hash;
1720 EMACS_TIME now;
1722 /* F must be a window-system frame, and SPEC must be a valid image
1723 specification. */
1724 xassert (FRAME_WINDOW_P (f));
1725 xassert (valid_image_p (spec));
1727 c = FRAME_IMAGE_CACHE (f);
1729 /* Look up SPEC in the hash table of the image cache. */
1730 hash = sxhash (spec, 0);
1731 img = search_image_cache (f, spec, hash);
1732 if (img && img->load_failed_p)
1734 free_image (f, img);
1735 img = NULL;
1738 /* If not found, create a new image and cache it. */
1739 if (img == NULL)
1741 BLOCK_INPUT;
1742 img = make_image (spec, hash);
1743 cache_image (f, img);
1744 img->load_failed_p = img->type->load (f, img) == 0;
1745 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1746 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1748 /* If we can't load the image, and we don't have a width and
1749 height, use some arbitrary width and height so that we can
1750 draw a rectangle for it. */
1751 if (img->load_failed_p)
1753 Lisp_Object value;
1755 value = image_spec_value (spec, QCwidth, NULL);
1756 img->width = (INTEGERP (value)
1757 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1758 value = image_spec_value (spec, QCheight, NULL);
1759 img->height = (INTEGERP (value)
1760 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1762 else
1764 /* Handle image type independent image attributes
1765 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1766 `:background COLOR'. */
1767 Lisp_Object ascent, margin, relief, bg;
1769 ascent = image_spec_value (spec, QCascent, NULL);
1770 if (INTEGERP (ascent))
1771 img->ascent = XFASTINT (ascent);
1772 else if (EQ (ascent, Qcenter))
1773 img->ascent = CENTERED_IMAGE_ASCENT;
1775 margin = image_spec_value (spec, QCmargin, NULL);
1776 if (INTEGERP (margin) && XINT (margin) >= 0)
1777 img->vmargin = img->hmargin = XFASTINT (margin);
1778 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1779 && INTEGERP (XCDR (margin)))
1781 if (XINT (XCAR (margin)) > 0)
1782 img->hmargin = XFASTINT (XCAR (margin));
1783 if (XINT (XCDR (margin)) > 0)
1784 img->vmargin = XFASTINT (XCDR (margin));
1787 relief = image_spec_value (spec, QCrelief, NULL);
1788 if (INTEGERP (relief))
1790 img->relief = XINT (relief);
1791 img->hmargin += eabs (img->relief);
1792 img->vmargin += eabs (img->relief);
1795 if (! img->background_valid)
1797 bg = image_spec_value (img->spec, QCbackground, NULL);
1798 if (!NILP (bg))
1800 img->background
1801 = x_alloc_image_color (f, img, bg,
1802 FRAME_BACKGROUND_PIXEL (f));
1803 img->background_valid = 1;
1807 /* Do image transformations and compute masks, unless we
1808 don't have the image yet. */
1809 if (!EQ (*img->type->type, Qpostscript))
1810 postprocess_image (f, img);
1813 UNBLOCK_INPUT;
1816 /* We're using IMG, so set its timestamp to `now'. */
1817 EMACS_GET_TIME (now);
1818 img->timestamp = EMACS_SECS (now);
1820 /* Value is the image id. */
1821 return img->id;
1825 /* Cache image IMG in the image cache of frame F. */
1827 static void
1828 cache_image (struct frame *f, struct image *img)
1830 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1831 int i;
1833 /* Find a free slot in c->images. */
1834 for (i = 0; i < c->used; ++i)
1835 if (c->images[i] == NULL)
1836 break;
1838 /* If no free slot found, maybe enlarge c->images. */
1839 if (i == c->used && c->used == c->size)
1841 c->size *= 2;
1842 c->images = (struct image **) xrealloc (c->images,
1843 c->size * sizeof *c->images);
1846 /* Add IMG to c->images, and assign IMG an id. */
1847 c->images[i] = img;
1848 img->id = i;
1849 if (i == c->used)
1850 ++c->used;
1852 /* Add IMG to the cache's hash table. */
1853 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1854 img->next = c->buckets[i];
1855 if (img->next)
1856 img->next->prev = img;
1857 img->prev = NULL;
1858 c->buckets[i] = img;
1862 /* Call FN on every image in the image cache of frame F. Used to mark
1863 Lisp Objects in the image cache. */
1865 /* Mark Lisp objects in image IMG. */
1867 static void
1868 mark_image (struct image *img)
1870 mark_object (img->spec);
1871 mark_object (img->dependencies);
1873 if (!NILP (img->data.lisp_val))
1874 mark_object (img->data.lisp_val);
1878 void
1879 mark_image_cache (struct image_cache *c)
1881 if (c)
1883 int i;
1884 for (i = 0; i < c->used; ++i)
1885 if (c->images[i])
1886 mark_image (c->images[i]);
1892 /***********************************************************************
1893 X / NS / W32 support code
1894 ***********************************************************************/
1896 #ifdef HAVE_NTGUI
1898 /* Macro for defining functions that will be loaded from image DLLs. */
1899 #define DEF_IMGLIB_FN(rettype,func,args) rettype (FAR CDECL *fn_##func)args
1901 /* Macro for loading those image functions from the library. */
1902 #define LOAD_IMGLIB_FN(lib,func) { \
1903 fn_##func = (void *) GetProcAddress (lib, #func); \
1904 if (!fn_##func) return 0; \
1907 /* Load a DLL implementing an image type.
1908 The argument LIBRARIES is usually the variable
1909 `dynamic-library-alist', which associates a symbol, identifying
1910 an external DLL library, to a list of possible filenames.
1911 The function returns NULL if no library could be loaded for
1912 the given symbol, or if the library was previously loaded;
1913 else the handle of the DLL. */
1914 static HMODULE
1915 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
1917 HMODULE library = NULL;
1919 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
1921 Lisp_Object dlls = Fassq (type, libraries);
1923 if (CONSP (dlls))
1924 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
1926 CHECK_STRING_CAR (dlls);
1927 if (library = LoadLibrary (SDATA (XCAR (dlls))))
1928 break;
1932 return library;
1935 #endif /* HAVE_NTGUI */
1937 static int x_create_x_image_and_pixmap (struct frame *, int, int, int,
1938 XImagePtr *, Pixmap *);
1939 static void x_destroy_x_image (XImagePtr);
1940 static void x_put_x_image (struct frame *, XImagePtr, Pixmap, int, int);
1943 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1944 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1945 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1946 via xmalloc. Print error messages via image_error if an error
1947 occurs. Value is non-zero if successful.
1949 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1950 should indicate the bit depth of the image. */
1952 static int
1953 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1954 XImagePtr *ximg, Pixmap *pixmap)
1956 #ifdef HAVE_X_WINDOWS
1957 Display *display = FRAME_X_DISPLAY (f);
1958 Window window = FRAME_X_WINDOW (f);
1959 Screen *screen = FRAME_X_SCREEN (f);
1961 xassert (interrupt_input_blocked);
1963 if (depth <= 0)
1964 depth = DefaultDepthOfScreen (screen);
1965 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1966 depth, ZPixmap, 0, NULL, width, height,
1967 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1968 if (*ximg == NULL)
1970 image_error ("Unable to allocate X image", Qnil, Qnil);
1971 return 0;
1974 /* Allocate image raster. */
1975 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
1977 /* Allocate a pixmap of the same size. */
1978 *pixmap = XCreatePixmap (display, window, width, height, depth);
1979 if (*pixmap == NO_PIXMAP)
1981 x_destroy_x_image (*ximg);
1982 *ximg = NULL;
1983 image_error ("Unable to create X pixmap", Qnil, Qnil);
1984 return 0;
1987 return 1;
1988 #endif /* HAVE_X_WINDOWS */
1990 #ifdef HAVE_NTGUI
1992 BITMAPINFOHEADER *header;
1993 HDC hdc;
1994 int scanline_width_bits;
1995 int remainder;
1996 int palette_colors = 0;
1998 if (depth == 0)
1999 depth = 24;
2001 if (depth != 1 && depth != 4 && depth != 8
2002 && depth != 16 && depth != 24 && depth != 32)
2004 image_error ("Invalid image bit depth specified", Qnil, Qnil);
2005 return 0;
2008 scanline_width_bits = width * depth;
2009 remainder = scanline_width_bits % 32;
2011 if (remainder)
2012 scanline_width_bits += 32 - remainder;
2014 /* Bitmaps with a depth less than 16 need a palette. */
2015 /* BITMAPINFO structure already contains the first RGBQUAD. */
2016 if (depth < 16)
2017 palette_colors = 1 << depth - 1;
2019 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2020 if (*ximg == NULL)
2022 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
2023 return 0;
2026 header = &(*ximg)->info.bmiHeader;
2027 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2028 header->biSize = sizeof (*header);
2029 header->biWidth = width;
2030 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2031 header->biPlanes = 1;
2032 header->biBitCount = depth;
2033 header->biCompression = BI_RGB;
2034 header->biClrUsed = palette_colors;
2036 /* TODO: fill in palette. */
2037 if (depth == 1)
2039 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2040 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2041 (*ximg)->info.bmiColors[0].rgbRed = 0;
2042 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2043 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2044 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2045 (*ximg)->info.bmiColors[1].rgbRed = 255;
2046 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2049 hdc = get_frame_dc (f);
2051 /* Create a DIBSection and raster array for the bitmap,
2052 and store its handle in *pixmap. */
2053 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2054 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2055 /* casting avoids a GCC warning */
2056 (void **)&((*ximg)->data), NULL, 0);
2058 /* Realize display palette and garbage all frames. */
2059 release_frame_dc (f, hdc);
2061 if (*pixmap == NULL)
2063 DWORD err = GetLastError ();
2064 Lisp_Object errcode;
2065 /* All system errors are < 10000, so the following is safe. */
2066 XSETINT (errcode, (int) err);
2067 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2068 x_destroy_x_image (*ximg);
2069 return 0;
2072 return 1;
2074 #endif /* HAVE_NTGUI */
2076 #ifdef HAVE_NS
2077 *pixmap = ns_image_for_XPM (width, height, depth);
2078 if (*pixmap == 0)
2080 *ximg = NULL;
2081 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2082 return 0;
2084 *ximg = *pixmap;
2085 return 1;
2086 #endif
2090 /* Destroy XImage XIMG. Free XIMG->data. */
2092 static void
2093 x_destroy_x_image (XImagePtr ximg)
2095 xassert (interrupt_input_blocked);
2096 if (ximg)
2098 #ifdef HAVE_X_WINDOWS
2099 xfree (ximg->data);
2100 ximg->data = NULL;
2101 XDestroyImage (ximg);
2102 #endif /* HAVE_X_WINDOWS */
2103 #ifdef HAVE_NTGUI
2104 /* Data will be freed by DestroyObject. */
2105 ximg->data = NULL;
2106 xfree (ximg);
2107 #endif /* HAVE_NTGUI */
2108 #ifdef HAVE_NS
2109 ns_release_object (ximg);
2110 #endif /* HAVE_NS */
2115 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2116 are width and height of both the image and pixmap. */
2118 static void
2119 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2121 #ifdef HAVE_X_WINDOWS
2122 GC gc;
2124 xassert (interrupt_input_blocked);
2125 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2126 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2127 XFreeGC (FRAME_X_DISPLAY (f), gc);
2128 #endif /* HAVE_X_WINDOWS */
2130 #ifdef HAVE_NTGUI
2131 #if 0 /* I don't think this is necessary looking at where it is used. */
2132 HDC hdc = get_frame_dc (f);
2133 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2134 release_frame_dc (f, hdc);
2135 #endif
2136 #endif /* HAVE_NTGUI */
2138 #ifdef HAVE_NS
2139 xassert (ximg == pixmap);
2140 ns_retain_object (ximg);
2141 #endif
2145 /***********************************************************************
2146 File Handling
2147 ***********************************************************************/
2149 static unsigned char *slurp_file (char *, int *);
2152 /* Find image file FILE. Look in data-directory/images, then
2153 x-bitmap-file-path. Value is the encoded full name of the file
2154 found, or nil if not found. */
2156 Lisp_Object
2157 x_find_image_file (Lisp_Object file)
2159 Lisp_Object file_found, search_path;
2160 int fd;
2162 /* TODO I think this should use something like image-load-path
2163 instead. Unfortunately, that can contain non-string elements. */
2164 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2165 Vdata_directory),
2166 Vx_bitmap_file_path);
2168 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2169 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2171 if (fd == -1)
2172 file_found = Qnil;
2173 else
2175 file_found = ENCODE_FILE (file_found);
2176 close (fd);
2179 return file_found;
2183 /* Read FILE into memory. Value is a pointer to a buffer allocated
2184 with xmalloc holding FILE's contents. Value is null if an error
2185 occurred. *SIZE is set to the size of the file. */
2187 static unsigned char *
2188 slurp_file (char *file, int *size)
2190 FILE *fp = NULL;
2191 unsigned char *buf = NULL;
2192 struct stat st;
2194 if (stat (file, &st) == 0
2195 && (fp = fopen (file, "rb")) != NULL
2196 && (buf = (unsigned char *) xmalloc (st.st_size),
2197 fread (buf, 1, st.st_size, fp) == st.st_size))
2199 *size = st.st_size;
2200 fclose (fp);
2202 else
2204 if (fp)
2205 fclose (fp);
2206 if (buf)
2208 xfree (buf);
2209 buf = NULL;
2213 return buf;
2218 /***********************************************************************
2219 XBM images
2220 ***********************************************************************/
2222 static int xbm_scan (unsigned char **, unsigned char *, char *, int *);
2223 static int xbm_load (struct frame *f, struct image *img);
2224 static int xbm_load_image (struct frame *f, struct image *img,
2225 unsigned char *, unsigned char *);
2226 static int xbm_image_p (Lisp_Object object);
2227 static int xbm_read_bitmap_data (struct frame *f,
2228 unsigned char *, unsigned char *,
2229 int *, int *, unsigned char **, int);
2230 static int xbm_file_p (Lisp_Object);
2233 /* Indices of image specification fields in xbm_format, below. */
2235 enum xbm_keyword_index
2237 XBM_TYPE,
2238 XBM_FILE,
2239 XBM_WIDTH,
2240 XBM_HEIGHT,
2241 XBM_DATA,
2242 XBM_FOREGROUND,
2243 XBM_BACKGROUND,
2244 XBM_ASCENT,
2245 XBM_MARGIN,
2246 XBM_RELIEF,
2247 XBM_ALGORITHM,
2248 XBM_HEURISTIC_MASK,
2249 XBM_MASK,
2250 XBM_LAST
2253 /* Vector of image_keyword structures describing the format
2254 of valid XBM image specifications. */
2256 static const struct image_keyword xbm_format[XBM_LAST] =
2258 {":type", IMAGE_SYMBOL_VALUE, 1},
2259 {":file", IMAGE_STRING_VALUE, 0},
2260 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2261 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2262 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2263 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2264 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2265 {":ascent", IMAGE_ASCENT_VALUE, 0},
2266 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2267 {":relief", IMAGE_INTEGER_VALUE, 0},
2268 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2269 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2270 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2273 /* Structure describing the image type XBM. */
2275 static struct image_type xbm_type =
2277 &Qxbm,
2278 xbm_image_p,
2279 xbm_load,
2280 x_clear_image,
2281 NULL
2284 /* Tokens returned from xbm_scan. */
2286 enum xbm_token
2288 XBM_TK_IDENT = 256,
2289 XBM_TK_NUMBER
2293 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2294 A valid specification is a list starting with the symbol `image'
2295 The rest of the list is a property list which must contain an
2296 entry `:type xbm..
2298 If the specification specifies a file to load, it must contain
2299 an entry `:file FILENAME' where FILENAME is a string.
2301 If the specification is for a bitmap loaded from memory it must
2302 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2303 WIDTH and HEIGHT are integers > 0. DATA may be:
2305 1. a string large enough to hold the bitmap data, i.e. it must
2306 have a size >= (WIDTH + 7) / 8 * HEIGHT
2308 2. a bool-vector of size >= WIDTH * HEIGHT
2310 3. a vector of strings or bool-vectors, one for each line of the
2311 bitmap.
2313 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2314 may not be specified in this case because they are defined in the
2315 XBM file.
2317 Both the file and data forms may contain the additional entries
2318 `:background COLOR' and `:foreground COLOR'. If not present,
2319 foreground and background of the frame on which the image is
2320 displayed is used. */
2322 static int
2323 xbm_image_p (Lisp_Object object)
2325 struct image_keyword kw[XBM_LAST];
2327 memcpy (kw, xbm_format, sizeof kw);
2328 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2329 return 0;
2331 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2333 if (kw[XBM_FILE].count)
2335 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2336 return 0;
2338 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2340 /* In-memory XBM file. */
2341 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2342 return 0;
2344 else
2346 Lisp_Object data;
2347 int width, height;
2349 /* Entries for `:width', `:height' and `:data' must be present. */
2350 if (!kw[XBM_WIDTH].count
2351 || !kw[XBM_HEIGHT].count
2352 || !kw[XBM_DATA].count)
2353 return 0;
2355 data = kw[XBM_DATA].value;
2356 width = XFASTINT (kw[XBM_WIDTH].value);
2357 height = XFASTINT (kw[XBM_HEIGHT].value);
2359 /* Check type of data, and width and height against contents of
2360 data. */
2361 if (VECTORP (data))
2363 int i;
2365 /* Number of elements of the vector must be >= height. */
2366 if (XVECTOR (data)->size < height)
2367 return 0;
2369 /* Each string or bool-vector in data must be large enough
2370 for one line of the image. */
2371 for (i = 0; i < height; ++i)
2373 Lisp_Object elt = XVECTOR (data)->contents[i];
2375 if (STRINGP (elt))
2377 if (SCHARS (elt)
2378 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2379 return 0;
2381 else if (BOOL_VECTOR_P (elt))
2383 if (XBOOL_VECTOR (elt)->size < width)
2384 return 0;
2386 else
2387 return 0;
2390 else if (STRINGP (data))
2392 if (SCHARS (data)
2393 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2394 return 0;
2396 else if (BOOL_VECTOR_P (data))
2398 if (XBOOL_VECTOR (data)->size < width * height)
2399 return 0;
2401 else
2402 return 0;
2405 return 1;
2409 /* Scan a bitmap file. FP is the stream to read from. Value is
2410 either an enumerator from enum xbm_token, or a character for a
2411 single-character token, or 0 at end of file. If scanning an
2412 identifier, store the lexeme of the identifier in SVAL. If
2413 scanning a number, store its value in *IVAL. */
2415 static int
2416 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2418 unsigned int c;
2420 loop:
2422 /* Skip white space. */
2423 while (*s < end && (c = *(*s)++, isspace (c)))
2426 if (*s >= end)
2427 c = 0;
2428 else if (isdigit (c))
2430 int value = 0, digit;
2432 if (c == '0' && *s < end)
2434 c = *(*s)++;
2435 if (c == 'x' || c == 'X')
2437 while (*s < end)
2439 c = *(*s)++;
2440 if (isdigit (c))
2441 digit = c - '0';
2442 else if (c >= 'a' && c <= 'f')
2443 digit = c - 'a' + 10;
2444 else if (c >= 'A' && c <= 'F')
2445 digit = c - 'A' + 10;
2446 else
2447 break;
2448 value = 16 * value + digit;
2451 else if (isdigit (c))
2453 value = c - '0';
2454 while (*s < end
2455 && (c = *(*s)++, isdigit (c)))
2456 value = 8 * value + c - '0';
2459 else
2461 value = c - '0';
2462 while (*s < end
2463 && (c = *(*s)++, isdigit (c)))
2464 value = 10 * value + c - '0';
2467 if (*s < end)
2468 *s = *s - 1;
2469 *ival = value;
2470 c = XBM_TK_NUMBER;
2472 else if (isalpha (c) || c == '_')
2474 *sval++ = c;
2475 while (*s < end
2476 && (c = *(*s)++, (isalnum (c) || c == '_')))
2477 *sval++ = c;
2478 *sval = 0;
2479 if (*s < end)
2480 *s = *s - 1;
2481 c = XBM_TK_IDENT;
2483 else if (c == '/' && **s == '*')
2485 /* C-style comment. */
2486 ++*s;
2487 while (**s && (**s != '*' || *(*s + 1) != '/'))
2488 ++*s;
2489 if (**s)
2491 *s += 2;
2492 goto loop;
2496 return c;
2499 #ifdef HAVE_NTGUI
2501 /* Create a Windows bitmap from X bitmap data. */
2502 static HBITMAP
2503 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2505 static unsigned char swap_nibble[16]
2506 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2507 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2508 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2509 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2510 int i, j, w1, w2;
2511 unsigned char *bits, *p;
2512 HBITMAP bmp;
2514 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2515 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2516 bits = (unsigned char *) alloca (height * w2);
2517 memset (bits, 0, height * w2);
2518 for (i = 0; i < height; i++)
2520 p = bits + i*w2;
2521 for (j = 0; j < w1; j++)
2523 /* Bitswap XBM bytes to match how Windows does things. */
2524 unsigned char c = *data++;
2525 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2526 | (swap_nibble[(c>>4) & 0xf]));
2529 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2531 return bmp;
2534 static void
2535 convert_mono_to_color_image (struct frame *f, struct image *img,
2536 COLORREF foreground, COLORREF background)
2538 HDC hdc, old_img_dc, new_img_dc;
2539 HGDIOBJ old_prev, new_prev;
2540 HBITMAP new_pixmap;
2542 hdc = get_frame_dc (f);
2543 old_img_dc = CreateCompatibleDC (hdc);
2544 new_img_dc = CreateCompatibleDC (hdc);
2545 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2546 release_frame_dc (f, hdc);
2547 old_prev = SelectObject (old_img_dc, img->pixmap);
2548 new_prev = SelectObject (new_img_dc, new_pixmap);
2549 /* Windows convention for mono bitmaps is black = background,
2550 white = foreground. */
2551 SetTextColor (new_img_dc, background);
2552 SetBkColor (new_img_dc, foreground);
2554 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2555 0, 0, SRCCOPY);
2557 SelectObject (old_img_dc, old_prev);
2558 SelectObject (new_img_dc, new_prev);
2559 DeleteDC (old_img_dc);
2560 DeleteDC (new_img_dc);
2561 DeleteObject (img->pixmap);
2562 if (new_pixmap == 0)
2563 fprintf (stderr, "Failed to convert image to color.\n");
2564 else
2565 img->pixmap = new_pixmap;
2568 #define XBM_BIT_SHUFFLE(b) (~(b))
2570 #else
2572 #define XBM_BIT_SHUFFLE(b) (b)
2574 #endif /* HAVE_NTGUI */
2577 static void
2578 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2579 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2580 int non_default_colors)
2582 #ifdef HAVE_NTGUI
2583 img->pixmap
2584 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2586 /* If colors were specified, transfer the bitmap to a color one. */
2587 if (non_default_colors)
2588 convert_mono_to_color_image (f, img, fg, bg);
2590 #elif defined (HAVE_NS)
2591 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2593 #else
2594 img->pixmap
2595 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2596 FRAME_X_WINDOW (f),
2597 data,
2598 img->width, img->height,
2599 fg, bg,
2600 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2601 #endif /* !HAVE_NTGUI && !HAVE_NS */
2606 /* Replacement for XReadBitmapFileData which isn't available under old
2607 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2608 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2609 the image. Return in *DATA the bitmap data allocated with xmalloc.
2610 Value is non-zero if successful. DATA null means just test if
2611 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR
2612 is non-zero, inhibit the call to image_error when the image size is
2613 invalid (the bitmap remains unread). */
2615 static int
2616 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2617 int *width, int *height, unsigned char **data,
2618 int inhibit_image_error)
2620 unsigned char *s = contents;
2621 char buffer[BUFSIZ];
2622 int padding_p = 0;
2623 int v10 = 0;
2624 int bytes_per_line, i, nbytes;
2625 unsigned char *p;
2626 int value;
2627 int LA1;
2629 #define match() \
2630 LA1 = xbm_scan (&s, end, buffer, &value)
2632 #define expect(TOKEN) \
2633 if (LA1 != (TOKEN)) \
2634 goto failure; \
2635 else \
2636 match ()
2638 #define expect_ident(IDENT) \
2639 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2640 match (); \
2641 else \
2642 goto failure
2644 *width = *height = -1;
2645 if (data)
2646 *data = NULL;
2647 LA1 = xbm_scan (&s, end, buffer, &value);
2649 /* Parse defines for width, height and hot-spots. */
2650 while (LA1 == '#')
2652 match ();
2653 expect_ident ("define");
2654 expect (XBM_TK_IDENT);
2656 if (LA1 == XBM_TK_NUMBER)
2658 char *p = strrchr (buffer, '_');
2659 p = p ? p + 1 : buffer;
2660 if (strcmp (p, "width") == 0)
2661 *width = value;
2662 else if (strcmp (p, "height") == 0)
2663 *height = value;
2665 expect (XBM_TK_NUMBER);
2668 if (!check_image_size (f, *width, *height))
2670 if (!inhibit_image_error)
2671 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2672 goto failure;
2674 else if (data == NULL)
2675 goto success;
2677 /* Parse bits. Must start with `static'. */
2678 expect_ident ("static");
2679 if (LA1 == XBM_TK_IDENT)
2681 if (strcmp (buffer, "unsigned") == 0)
2683 match ();
2684 expect_ident ("char");
2686 else if (strcmp (buffer, "short") == 0)
2688 match ();
2689 v10 = 1;
2690 if (*width % 16 && *width % 16 < 9)
2691 padding_p = 1;
2693 else if (strcmp (buffer, "char") == 0)
2694 match ();
2695 else
2696 goto failure;
2698 else
2699 goto failure;
2701 expect (XBM_TK_IDENT);
2702 expect ('[');
2703 expect (']');
2704 expect ('=');
2705 expect ('{');
2707 bytes_per_line = (*width + 7) / 8 + padding_p;
2708 nbytes = bytes_per_line * *height;
2709 p = *data = (unsigned char *) xmalloc (nbytes);
2711 if (v10)
2713 for (i = 0; i < nbytes; i += 2)
2715 int val = value;
2716 expect (XBM_TK_NUMBER);
2718 *p++ = XBM_BIT_SHUFFLE (val);
2719 if (!padding_p || ((i + 2) % bytes_per_line))
2720 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2722 if (LA1 == ',' || LA1 == '}')
2723 match ();
2724 else
2725 goto failure;
2728 else
2730 for (i = 0; i < nbytes; ++i)
2732 int val = value;
2733 expect (XBM_TK_NUMBER);
2735 *p++ = XBM_BIT_SHUFFLE (val);
2737 if (LA1 == ',' || LA1 == '}')
2738 match ();
2739 else
2740 goto failure;
2744 success:
2745 return 1;
2747 failure:
2749 if (data && *data)
2751 xfree (*data);
2752 *data = NULL;
2754 return 0;
2756 #undef match
2757 #undef expect
2758 #undef expect_ident
2762 /* Load XBM image IMG which will be displayed on frame F from buffer
2763 CONTENTS. END is the end of the buffer. Value is non-zero if
2764 successful. */
2766 static int
2767 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2768 unsigned char *end)
2770 int rc;
2771 unsigned char *data;
2772 int success_p = 0;
2774 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2775 &data, 0);
2776 if (rc)
2778 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2779 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2780 int non_default_colors = 0;
2781 Lisp_Object value;
2783 xassert (img->width > 0 && img->height > 0);
2785 /* Get foreground and background colors, maybe allocate colors. */
2786 value = image_spec_value (img->spec, QCforeground, NULL);
2787 if (!NILP (value))
2789 foreground = x_alloc_image_color (f, img, value, foreground);
2790 non_default_colors = 1;
2792 value = image_spec_value (img->spec, QCbackground, NULL);
2793 if (!NILP (value))
2795 background = x_alloc_image_color (f, img, value, background);
2796 img->background = background;
2797 img->background_valid = 1;
2798 non_default_colors = 1;
2801 Create_Pixmap_From_Bitmap_Data (f, img, data,
2802 foreground, background,
2803 non_default_colors);
2804 xfree (data);
2806 if (img->pixmap == NO_PIXMAP)
2808 x_clear_image (f, img);
2809 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2811 else
2812 success_p = 1;
2814 else
2815 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2817 return success_p;
2821 /* Value is non-zero if DATA looks like an in-memory XBM file. */
2823 static int
2824 xbm_file_p (Lisp_Object data)
2826 int w, h;
2827 return (STRINGP (data)
2828 && xbm_read_bitmap_data (NULL, SDATA (data),
2829 (SDATA (data) + SBYTES (data)),
2830 &w, &h, NULL, 1));
2834 /* Fill image IMG which is used on frame F with pixmap data. Value is
2835 non-zero if successful. */
2837 static int
2838 xbm_load (struct frame *f, struct image *img)
2840 int success_p = 0;
2841 Lisp_Object file_name;
2843 xassert (xbm_image_p (img->spec));
2845 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2846 file_name = image_spec_value (img->spec, QCfile, NULL);
2847 if (STRINGP (file_name))
2849 Lisp_Object file;
2850 unsigned char *contents;
2851 int size;
2853 file = x_find_image_file (file_name);
2854 if (!STRINGP (file))
2856 image_error ("Cannot find image file `%s'", file_name, Qnil);
2857 return 0;
2860 contents = slurp_file (SSDATA (file), &size);
2861 if (contents == NULL)
2863 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2864 return 0;
2867 success_p = xbm_load_image (f, img, contents, contents + size);
2869 else
2871 struct image_keyword fmt[XBM_LAST];
2872 Lisp_Object data;
2873 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2874 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2875 int non_default_colors = 0;
2876 char *bits;
2877 int parsed_p;
2878 int in_memory_file_p = 0;
2880 /* See if data looks like an in-memory XBM file. */
2881 data = image_spec_value (img->spec, QCdata, NULL);
2882 in_memory_file_p = xbm_file_p (data);
2884 /* Parse the image specification. */
2885 memcpy (fmt, xbm_format, sizeof fmt);
2886 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2887 xassert (parsed_p);
2889 /* Get specified width, and height. */
2890 if (!in_memory_file_p)
2892 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2893 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2894 xassert (img->width > 0 && img->height > 0);
2897 /* Get foreground and background colors, maybe allocate colors. */
2898 if (fmt[XBM_FOREGROUND].count
2899 && STRINGP (fmt[XBM_FOREGROUND].value))
2901 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2902 foreground);
2903 non_default_colors = 1;
2906 if (fmt[XBM_BACKGROUND].count
2907 && STRINGP (fmt[XBM_BACKGROUND].value))
2909 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2910 background);
2911 non_default_colors = 1;
2914 if (in_memory_file_p)
2915 success_p = xbm_load_image (f, img, SDATA (data),
2916 (SDATA (data)
2917 + SBYTES (data)));
2918 else
2920 if (VECTORP (data))
2922 int i;
2923 char *p;
2924 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2926 p = bits = (char *) alloca (nbytes * img->height);
2927 for (i = 0; i < img->height; ++i, p += nbytes)
2929 Lisp_Object line = XVECTOR (data)->contents[i];
2930 if (STRINGP (line))
2931 memcpy (p, SDATA (line), nbytes);
2932 else
2933 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
2936 else if (STRINGP (data))
2937 bits = SSDATA (data);
2938 else
2939 bits = XBOOL_VECTOR (data)->data;
2941 #ifdef WINDOWSNT
2943 char *invertedBits;
2944 int nbytes, i;
2945 /* Windows mono bitmaps are reversed compared with X. */
2946 invertedBits = bits;
2947 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
2948 * img->height;
2949 bits = (char *) alloca (nbytes);
2950 for (i = 0; i < nbytes; i++)
2951 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
2953 #endif
2954 /* Create the pixmap. */
2956 Create_Pixmap_From_Bitmap_Data (f, img, bits,
2957 foreground, background,
2958 non_default_colors);
2959 if (img->pixmap)
2960 success_p = 1;
2961 else
2963 image_error ("Unable to create pixmap for XBM image `%s'",
2964 img->spec, Qnil);
2965 x_clear_image (f, img);
2970 return success_p;
2975 /***********************************************************************
2976 XPM images
2977 ***********************************************************************/
2979 #if defined (HAVE_XPM) || defined (HAVE_NS)
2981 static int xpm_image_p (Lisp_Object object);
2982 static int xpm_load (struct frame *f, struct image *img);
2983 static int xpm_valid_color_symbols_p (Lisp_Object);
2985 #endif /* HAVE_XPM || HAVE_NS */
2987 #ifdef HAVE_XPM
2988 #ifdef HAVE_NTGUI
2989 /* Indicate to xpm.h that we don't have Xlib. */
2990 #define FOR_MSW
2991 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
2992 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
2993 #define XColor xpm_XColor
2994 #define XImage xpm_XImage
2995 #define Display xpm_Display
2996 #define PIXEL_ALREADY_TYPEDEFED
2997 #include "X11/xpm.h"
2998 #undef FOR_MSW
2999 #undef XColor
3000 #undef XImage
3001 #undef Display
3002 #undef PIXEL_ALREADY_TYPEDEFED
3003 #else
3004 #include "X11/xpm.h"
3005 #endif /* HAVE_NTGUI */
3006 #endif /* HAVE_XPM */
3008 #if defined (HAVE_XPM) || defined (HAVE_NS)
3009 /* The symbol `xpm' identifying XPM-format images. */
3011 Lisp_Object Qxpm;
3013 /* Indices of image specification fields in xpm_format, below. */
3015 enum xpm_keyword_index
3017 XPM_TYPE,
3018 XPM_FILE,
3019 XPM_DATA,
3020 XPM_ASCENT,
3021 XPM_MARGIN,
3022 XPM_RELIEF,
3023 XPM_ALGORITHM,
3024 XPM_HEURISTIC_MASK,
3025 XPM_MASK,
3026 XPM_COLOR_SYMBOLS,
3027 XPM_BACKGROUND,
3028 XPM_LAST
3031 /* Vector of image_keyword structures describing the format
3032 of valid XPM image specifications. */
3034 static const struct image_keyword xpm_format[XPM_LAST] =
3036 {":type", IMAGE_SYMBOL_VALUE, 1},
3037 {":file", IMAGE_STRING_VALUE, 0},
3038 {":data", IMAGE_STRING_VALUE, 0},
3039 {":ascent", IMAGE_ASCENT_VALUE, 0},
3040 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3041 {":relief", IMAGE_INTEGER_VALUE, 0},
3042 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3043 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3044 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3045 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3046 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3049 /* Structure describing the image type XPM. */
3051 static struct image_type xpm_type =
3053 &Qxpm,
3054 xpm_image_p,
3055 xpm_load,
3056 x_clear_image,
3057 NULL
3060 #ifdef HAVE_X_WINDOWS
3062 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3063 functions for allocating image colors. Our own functions handle
3064 color allocation failures more gracefully than the ones on the XPM
3065 lib. */
3067 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3068 #define ALLOC_XPM_COLORS
3069 #endif
3070 #endif /* HAVE_X_WINDOWS */
3072 #ifdef ALLOC_XPM_COLORS
3074 static void xpm_init_color_cache (struct frame *, XpmAttributes *);
3075 static void xpm_free_color_cache (void);
3076 static int xpm_lookup_color (struct frame *, char *, XColor *);
3077 static int xpm_color_bucket (char *);
3078 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3079 XColor *, int);
3081 /* An entry in a hash table used to cache color definitions of named
3082 colors. This cache is necessary to speed up XPM image loading in
3083 case we do color allocations ourselves. Without it, we would need
3084 a call to XParseColor per pixel in the image. */
3086 struct xpm_cached_color
3088 /* Next in collision chain. */
3089 struct xpm_cached_color *next;
3091 /* Color definition (RGB and pixel color). */
3092 XColor color;
3094 /* Color name. */
3095 char name[1];
3098 /* The hash table used for the color cache, and its bucket vector
3099 size. */
3101 #define XPM_COLOR_CACHE_BUCKETS 1001
3102 struct xpm_cached_color **xpm_color_cache;
3104 /* Initialize the color cache. */
3106 static void
3107 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3109 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3110 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3111 memset (xpm_color_cache, 0, nbytes);
3112 init_color_table ();
3114 if (attrs->valuemask & XpmColorSymbols)
3116 int i;
3117 XColor color;
3119 for (i = 0; i < attrs->numsymbols; ++i)
3120 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3121 attrs->colorsymbols[i].value, &color))
3123 color.pixel = lookup_rgb_color (f, color.red, color.green,
3124 color.blue);
3125 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3130 /* Free the color cache. */
3132 static void
3133 xpm_free_color_cache (void)
3135 struct xpm_cached_color *p, *next;
3136 int i;
3138 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3139 for (p = xpm_color_cache[i]; p; p = next)
3141 next = p->next;
3142 xfree (p);
3145 xfree (xpm_color_cache);
3146 xpm_color_cache = NULL;
3147 free_color_table ();
3150 /* Return the bucket index for color named COLOR_NAME in the color
3151 cache. */
3153 static int
3154 xpm_color_bucket (char *color_name)
3156 unsigned h = 0;
3157 char *s;
3159 for (s = color_name; *s; ++s)
3160 h = (h << 2) ^ *s;
3161 return h %= XPM_COLOR_CACHE_BUCKETS;
3165 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3166 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3167 entry added. */
3169 static struct xpm_cached_color *
3170 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3172 size_t nbytes;
3173 struct xpm_cached_color *p;
3175 if (bucket < 0)
3176 bucket = xpm_color_bucket (color_name);
3178 nbytes = sizeof *p + strlen (color_name);
3179 p = (struct xpm_cached_color *) xmalloc (nbytes);
3180 strcpy (p->name, color_name);
3181 p->color = *color;
3182 p->next = xpm_color_cache[bucket];
3183 xpm_color_cache[bucket] = p;
3184 return p;
3187 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3188 return the cached definition in *COLOR. Otherwise, make a new
3189 entry in the cache and allocate the color. Value is zero if color
3190 allocation failed. */
3192 static int
3193 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3195 struct xpm_cached_color *p;
3196 int h = xpm_color_bucket (color_name);
3198 for (p = xpm_color_cache[h]; p; p = p->next)
3199 if (strcmp (p->name, color_name) == 0)
3200 break;
3202 if (p != NULL)
3203 *color = p->color;
3204 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3205 color_name, color))
3207 color->pixel = lookup_rgb_color (f, color->red, color->green,
3208 color->blue);
3209 p = xpm_cache_color (f, color_name, color, h);
3211 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3212 with transparency, and it's useful. */
3213 else if (strcmp ("opaque", color_name) == 0)
3215 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3216 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3217 p = xpm_cache_color (f, color_name, color, h);
3220 return p != NULL;
3224 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3225 CLOSURE is a pointer to the frame on which we allocate the
3226 color. Return in *COLOR the allocated color. Value is non-zero
3227 if successful. */
3229 static int
3230 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3231 void *closure)
3233 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3237 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3238 is a pointer to the frame on which we allocate the color. Value is
3239 non-zero if successful. */
3241 static int
3242 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3244 return 1;
3247 #endif /* ALLOC_XPM_COLORS */
3250 #ifdef HAVE_NTGUI
3252 /* XPM library details. */
3254 DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
3255 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3256 xpm_XImage **, XpmAttributes *));
3257 DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3258 xpm_XImage **, XpmAttributes *));
3259 DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
3261 static int
3262 init_xpm_functions (Lisp_Object libraries)
3264 HMODULE library;
3266 if (!(library = w32_delayed_load (libraries, Qxpm)))
3267 return 0;
3269 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3270 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3271 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3272 LOAD_IMGLIB_FN (library, XImageFree);
3273 return 1;
3276 #endif /* HAVE_NTGUI */
3279 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3280 for XPM images. Such a list must consist of conses whose car and
3281 cdr are strings. */
3283 static int
3284 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3286 while (CONSP (color_symbols))
3288 Lisp_Object sym = XCAR (color_symbols);
3289 if (!CONSP (sym)
3290 || !STRINGP (XCAR (sym))
3291 || !STRINGP (XCDR (sym)))
3292 break;
3293 color_symbols = XCDR (color_symbols);
3296 return NILP (color_symbols);
3300 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3302 static int
3303 xpm_image_p (Lisp_Object object)
3305 struct image_keyword fmt[XPM_LAST];
3306 memcpy (fmt, xpm_format, sizeof fmt);
3307 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3308 /* Either `:file' or `:data' must be present. */
3309 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3310 /* Either no `:color-symbols' or it's a list of conses
3311 whose car and cdr are strings. */
3312 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3313 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3316 #endif /* HAVE_XPM || HAVE_NS */
3318 #if defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
3320 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3322 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3323 int id, rc;
3324 XpmAttributes attrs;
3325 Pixmap bitmap, mask;
3327 memset (&attrs, 0, sizeof attrs);
3329 attrs.visual = FRAME_X_VISUAL (f);
3330 attrs.colormap = FRAME_X_COLORMAP (f);
3331 attrs.valuemask |= XpmVisual;
3332 attrs.valuemask |= XpmColormap;
3334 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3335 (char **) bits, &bitmap, &mask, &attrs);
3336 if (rc != XpmSuccess)
3338 XpmFreeAttributes (&attrs);
3339 return -1;
3342 id = x_allocate_bitmap_record (f);
3343 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3344 dpyinfo->bitmaps[id - 1].have_mask = 1;
3345 dpyinfo->bitmaps[id - 1].mask = mask;
3346 dpyinfo->bitmaps[id - 1].file = NULL;
3347 dpyinfo->bitmaps[id - 1].height = attrs.height;
3348 dpyinfo->bitmaps[id - 1].width = attrs.width;
3349 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3350 dpyinfo->bitmaps[id - 1].refcount = 1;
3352 XpmFreeAttributes (&attrs);
3353 return id;
3355 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3357 /* Load image IMG which will be displayed on frame F. Value is
3358 non-zero if successful. */
3360 #ifdef HAVE_XPM
3362 static int
3363 xpm_load (struct frame *f, struct image *img)
3365 int rc;
3366 XpmAttributes attrs;
3367 Lisp_Object specified_file, color_symbols;
3368 #ifdef HAVE_NTGUI
3369 HDC hdc;
3370 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3371 #endif /* HAVE_NTGUI */
3373 /* Configure the XPM lib. Use the visual of frame F. Allocate
3374 close colors. Return colors allocated. */
3375 memset (&attrs, 0, sizeof attrs);
3377 #ifndef HAVE_NTGUI
3378 attrs.visual = FRAME_X_VISUAL (f);
3379 attrs.colormap = FRAME_X_COLORMAP (f);
3380 attrs.valuemask |= XpmVisual;
3381 attrs.valuemask |= XpmColormap;
3382 #endif /* HAVE_NTGUI */
3384 #ifdef ALLOC_XPM_COLORS
3385 /* Allocate colors with our own functions which handle
3386 failing color allocation more gracefully. */
3387 attrs.color_closure = f;
3388 attrs.alloc_color = xpm_alloc_color;
3389 attrs.free_colors = xpm_free_colors;
3390 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3391 #else /* not ALLOC_XPM_COLORS */
3392 /* Let the XPM lib allocate colors. */
3393 attrs.valuemask |= XpmReturnAllocPixels;
3394 #ifdef XpmAllocCloseColors
3395 attrs.alloc_close_colors = 1;
3396 attrs.valuemask |= XpmAllocCloseColors;
3397 #else /* not XpmAllocCloseColors */
3398 attrs.closeness = 600;
3399 attrs.valuemask |= XpmCloseness;
3400 #endif /* not XpmAllocCloseColors */
3401 #endif /* ALLOC_XPM_COLORS */
3403 /* If image specification contains symbolic color definitions, add
3404 these to `attrs'. */
3405 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3406 if (CONSP (color_symbols))
3408 Lisp_Object tail;
3409 XpmColorSymbol *xpm_syms;
3410 int i, size;
3412 attrs.valuemask |= XpmColorSymbols;
3414 /* Count number of symbols. */
3415 attrs.numsymbols = 0;
3416 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3417 ++attrs.numsymbols;
3419 /* Allocate an XpmColorSymbol array. */
3420 size = attrs.numsymbols * sizeof *xpm_syms;
3421 xpm_syms = (XpmColorSymbol *) alloca (size);
3422 memset (xpm_syms, 0, size);
3423 attrs.colorsymbols = xpm_syms;
3425 /* Fill the color symbol array. */
3426 for (tail = color_symbols, i = 0;
3427 CONSP (tail);
3428 ++i, tail = XCDR (tail))
3430 Lisp_Object name;
3431 Lisp_Object color;
3433 if (!CONSP (XCAR (tail)))
3435 xpm_syms[i].name = "";
3436 xpm_syms[i].value = "";
3437 continue;
3439 name = XCAR (XCAR (tail));
3440 color = XCDR (XCAR (tail));
3441 if (STRINGP (name))
3443 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3444 strcpy (xpm_syms[i].name, SSDATA (name));
3446 else
3447 xpm_syms[i].name = "";
3448 if (STRINGP (color))
3450 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3451 strcpy (xpm_syms[i].value, SSDATA (color));
3453 else
3454 xpm_syms[i].value = "";
3458 /* Create a pixmap for the image, either from a file, or from a
3459 string buffer containing data in the same format as an XPM file. */
3460 #ifdef ALLOC_XPM_COLORS
3461 xpm_init_color_cache (f, &attrs);
3462 #endif
3464 specified_file = image_spec_value (img->spec, QCfile, NULL);
3466 #ifdef HAVE_NTGUI
3468 HDC frame_dc = get_frame_dc (f);
3469 hdc = CreateCompatibleDC (frame_dc);
3470 release_frame_dc (f, frame_dc);
3472 #endif /* HAVE_NTGUI */
3474 if (STRINGP (specified_file))
3476 Lisp_Object file = x_find_image_file (specified_file);
3477 if (!STRINGP (file))
3479 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3480 #ifdef ALLOC_XPM_COLORS
3481 xpm_free_color_cache ();
3482 #endif
3483 return 0;
3486 #ifdef HAVE_NTGUI
3487 /* XpmReadFileToPixmap is not available in the Windows port of
3488 libxpm. But XpmReadFileToImage almost does what we want. */
3489 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3490 &xpm_image, &xpm_mask,
3491 &attrs);
3492 #else
3493 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3494 SSDATA (file), &img->pixmap, &img->mask,
3495 &attrs);
3496 #endif /* HAVE_NTGUI */
3498 else
3500 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3501 if (!STRINGP (buffer))
3503 image_error ("Invalid image data `%s'", buffer, Qnil);
3504 #ifdef ALLOC_XPM_COLORS
3505 xpm_free_color_cache ();
3506 #endif
3507 return 0;
3509 #ifdef HAVE_NTGUI
3510 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3511 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3512 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3513 &xpm_image, &xpm_mask,
3514 &attrs);
3515 #else
3516 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3517 SSDATA (buffer),
3518 &img->pixmap, &img->mask,
3519 &attrs);
3520 #endif /* HAVE_NTGUI */
3523 if (rc == XpmSuccess)
3525 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3526 img->colors = colors_in_color_table (&img->ncolors);
3527 #else /* not ALLOC_XPM_COLORS */
3528 int i;
3530 #ifdef HAVE_NTGUI
3531 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3532 plus some duplicate attributes. */
3533 if (xpm_image && xpm_image->bitmap)
3535 img->pixmap = xpm_image->bitmap;
3536 /* XImageFree in libXpm frees XImage struct without destroying
3537 the bitmap, which is what we want. */
3538 fn_XImageFree (xpm_image);
3540 if (xpm_mask && xpm_mask->bitmap)
3542 /* The mask appears to be inverted compared with what we expect.
3543 TODO: invert our expectations. See other places where we
3544 have to invert bits because our idea of masks is backwards. */
3545 HGDIOBJ old_obj;
3546 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3548 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3549 SelectObject (hdc, old_obj);
3551 img->mask = xpm_mask->bitmap;
3552 fn_XImageFree (xpm_mask);
3553 DeleteDC (hdc);
3556 DeleteDC (hdc);
3557 #endif /* HAVE_NTGUI */
3559 /* Remember allocated colors. */
3560 img->ncolors = attrs.nalloc_pixels;
3561 img->colors = (unsigned long *) xmalloc (img->ncolors
3562 * sizeof *img->colors);
3563 for (i = 0; i < attrs.nalloc_pixels; ++i)
3565 img->colors[i] = attrs.alloc_pixels[i];
3566 #ifdef DEBUG_X_COLORS
3567 register_color (img->colors[i]);
3568 #endif
3570 #endif /* not ALLOC_XPM_COLORS */
3572 img->width = attrs.width;
3573 img->height = attrs.height;
3574 xassert (img->width > 0 && img->height > 0);
3576 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3577 #ifdef HAVE_NTGUI
3578 fn_XpmFreeAttributes (&attrs);
3579 #else
3580 XpmFreeAttributes (&attrs);
3581 #endif /* HAVE_NTGUI */
3583 else
3585 #ifdef HAVE_NTGUI
3586 DeleteDC (hdc);
3587 #endif /* HAVE_NTGUI */
3589 switch (rc)
3591 case XpmOpenFailed:
3592 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3593 break;
3595 case XpmFileInvalid:
3596 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3597 break;
3599 case XpmNoMemory:
3600 image_error ("Out of memory (%s)", img->spec, Qnil);
3601 break;
3603 case XpmColorFailed:
3604 image_error ("Color allocation error (%s)", img->spec, Qnil);
3605 break;
3607 default:
3608 image_error ("Unknown error (%s)", img->spec, Qnil);
3609 break;
3613 #ifdef ALLOC_XPM_COLORS
3614 xpm_free_color_cache ();
3615 #endif
3616 return rc == XpmSuccess;
3619 #endif /* HAVE_XPM */
3621 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3623 /* XPM support functions for NS where libxpm is not available.
3624 Only XPM version 3 (without any extensions) is supported. */
3626 static int xpm_scan (const unsigned char **, const unsigned char *,
3627 const unsigned char **, int *);
3628 static Lisp_Object xpm_make_color_table_v
3629 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3630 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3631 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3632 int, Lisp_Object);
3633 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3634 const unsigned char *, int);
3635 static Lisp_Object xpm_make_color_table_h
3636 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3637 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3638 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3639 int, Lisp_Object);
3640 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3641 const unsigned char *, int);
3642 static int xpm_str_to_color_key (const char *);
3643 static int xpm_load_image (struct frame *, struct image *,
3644 const unsigned char *, const unsigned char *);
3646 /* Tokens returned from xpm_scan. */
3648 enum xpm_token
3650 XPM_TK_IDENT = 256,
3651 XPM_TK_STRING,
3652 XPM_TK_EOF
3655 /* Scan an XPM data and return a character (< 256) or a token defined
3656 by enum xpm_token above. *S and END are the start (inclusive) and
3657 the end (exclusive) addresses of the data, respectively. Advance
3658 *S while scanning. If token is either XPM_TK_IDENT or
3659 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3660 length of the corresponding token, respectively. */
3662 static int
3663 xpm_scan (const unsigned char **s,
3664 const unsigned char *end,
3665 const unsigned char **beg,
3666 int *len)
3668 int c;
3670 while (*s < end)
3672 /* Skip white-space. */
3673 while (*s < end && (c = *(*s)++, isspace (c)))
3676 /* gnus-pointer.xpm uses '-' in its identifier.
3677 sb-dir-plus.xpm uses '+' in its identifier. */
3678 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3680 *beg = *s - 1;
3681 while (*s < end
3682 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3683 ++*s;
3684 *len = *s - *beg;
3685 return XPM_TK_IDENT;
3687 else if (c == '"')
3689 *beg = *s;
3690 while (*s < end && **s != '"')
3691 ++*s;
3692 *len = *s - *beg;
3693 if (*s < end)
3694 ++*s;
3695 return XPM_TK_STRING;
3697 else if (c == '/')
3699 if (*s < end && **s == '*')
3701 /* C-style comment. */
3702 ++*s;
3705 while (*s < end && *(*s)++ != '*')
3708 while (*s < end && **s != '/');
3709 if (*s < end)
3710 ++*s;
3712 else
3713 return c;
3715 else
3716 return c;
3719 return XPM_TK_EOF;
3722 /* Functions for color table lookup in XPM data. A key is a string
3723 specifying the color of each pixel in XPM data. A value is either
3724 an integer that specifies a pixel color, Qt that specifies
3725 transparency, or Qnil for the unspecified color. If the length of
3726 the key string is one, a vector is used as a table. Otherwise, a
3727 hash table is used. */
3729 static Lisp_Object
3730 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3731 const unsigned char *,
3732 int,
3733 Lisp_Object),
3734 Lisp_Object (**get_func) (Lisp_Object,
3735 const unsigned char *,
3736 int))
3738 *put_func = xpm_put_color_table_v;
3739 *get_func = xpm_get_color_table_v;
3740 return Fmake_vector (make_number (256), Qnil);
3743 static void
3744 xpm_put_color_table_v (Lisp_Object color_table,
3745 const unsigned char *chars_start,
3746 int chars_len,
3747 Lisp_Object color)
3749 XVECTOR (color_table)->contents[*chars_start] = color;
3752 static Lisp_Object
3753 xpm_get_color_table_v (Lisp_Object color_table,
3754 const unsigned char *chars_start,
3755 int chars_len)
3757 return XVECTOR (color_table)->contents[*chars_start];
3760 static Lisp_Object
3761 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3762 const unsigned char *,
3763 int,
3764 Lisp_Object),
3765 Lisp_Object (**get_func) (Lisp_Object,
3766 const unsigned char *,
3767 int))
3769 *put_func = xpm_put_color_table_h;
3770 *get_func = xpm_get_color_table_h;
3771 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
3772 make_float (DEFAULT_REHASH_SIZE),
3773 make_float (DEFAULT_REHASH_THRESHOLD),
3774 Qnil, Qnil, Qnil);
3777 static void
3778 xpm_put_color_table_h (Lisp_Object color_table,
3779 const unsigned char *chars_start,
3780 int chars_len,
3781 Lisp_Object color)
3783 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3784 unsigned hash_code;
3785 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3787 hash_lookup (table, chars, &hash_code);
3788 hash_put (table, chars, color, hash_code);
3791 static Lisp_Object
3792 xpm_get_color_table_h (Lisp_Object color_table,
3793 const unsigned char *chars_start,
3794 int chars_len)
3796 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3797 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
3798 NULL);
3800 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3803 enum xpm_color_key {
3804 XPM_COLOR_KEY_S,
3805 XPM_COLOR_KEY_M,
3806 XPM_COLOR_KEY_G4,
3807 XPM_COLOR_KEY_G,
3808 XPM_COLOR_KEY_C
3811 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3813 static int
3814 xpm_str_to_color_key (const char *s)
3816 int i;
3818 for (i = 0;
3819 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3820 i++)
3821 if (strcmp (xpm_color_key_strings[i], s) == 0)
3822 return i;
3823 return -1;
3826 static int
3827 xpm_load_image (struct frame *f,
3828 struct image *img,
3829 const unsigned char *contents,
3830 const unsigned char *end)
3832 const unsigned char *s = contents, *beg, *str;
3833 unsigned char buffer[BUFSIZ];
3834 int width, height, x, y;
3835 int num_colors, chars_per_pixel;
3836 int len, LA1;
3837 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3838 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3839 Lisp_Object frame, color_symbols, color_table;
3840 int best_key, have_mask = 0;
3841 XImagePtr ximg = NULL, mask_img = NULL;
3843 #define match() \
3844 LA1 = xpm_scan (&s, end, &beg, &len)
3846 #define expect(TOKEN) \
3847 if (LA1 != (TOKEN)) \
3848 goto failure; \
3849 else \
3850 match ()
3852 #define expect_ident(IDENT) \
3853 if (LA1 == XPM_TK_IDENT \
3854 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3855 match (); \
3856 else \
3857 goto failure
3859 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3860 goto failure;
3861 s += 9;
3862 match ();
3863 expect_ident ("static");
3864 expect_ident ("char");
3865 expect ('*');
3866 expect (XPM_TK_IDENT);
3867 expect ('[');
3868 expect (']');
3869 expect ('=');
3870 expect ('{');
3871 expect (XPM_TK_STRING);
3872 if (len >= BUFSIZ)
3873 goto failure;
3874 memcpy (buffer, beg, len);
3875 buffer[len] = '\0';
3876 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3877 &num_colors, &chars_per_pixel) != 4
3878 || width <= 0 || height <= 0
3879 || num_colors <= 0 || chars_per_pixel <= 0)
3880 goto failure;
3882 if (!check_image_size (f, width, height))
3884 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
3885 goto failure;
3888 expect (',');
3890 XSETFRAME (frame, f);
3891 if (!NILP (Fxw_display_color_p (frame)))
3892 best_key = XPM_COLOR_KEY_C;
3893 else if (!NILP (Fx_display_grayscale_p (frame)))
3894 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
3895 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
3896 else
3897 best_key = XPM_COLOR_KEY_M;
3899 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3900 if (chars_per_pixel == 1)
3901 color_table = xpm_make_color_table_v (&put_color_table,
3902 &get_color_table);
3903 else
3904 color_table = xpm_make_color_table_h (&put_color_table,
3905 &get_color_table);
3907 while (num_colors-- > 0)
3909 unsigned char *color, *max_color;
3910 int key, next_key, max_key = 0;
3911 Lisp_Object symbol_color = Qnil, color_val;
3912 XColor cdef;
3914 expect (XPM_TK_STRING);
3915 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
3916 goto failure;
3917 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
3918 buffer[len - chars_per_pixel] = '\0';
3920 str = strtok (buffer, " \t");
3921 if (str == NULL)
3922 goto failure;
3923 key = xpm_str_to_color_key (str);
3924 if (key < 0)
3925 goto failure;
3928 color = strtok (NULL, " \t");
3929 if (color == NULL)
3930 goto failure;
3932 while ((str = strtok (NULL, " \t")) != NULL)
3934 next_key = xpm_str_to_color_key (str);
3935 if (next_key >= 0)
3936 break;
3937 color[strlen (color)] = ' ';
3940 if (key == XPM_COLOR_KEY_S)
3942 if (NILP (symbol_color))
3943 symbol_color = build_string (color);
3945 else if (max_key < key && key <= best_key)
3947 max_key = key;
3948 max_color = color;
3950 key = next_key;
3952 while (str);
3954 color_val = Qnil;
3955 if (!NILP (color_symbols) && !NILP (symbol_color))
3957 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
3959 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
3961 if (xstrcasecmp (SDATA (XCDR (specified_color)), "None") == 0)
3962 color_val = Qt;
3963 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
3964 &cdef, 0))
3965 color_val = make_number (cdef.pixel);
3968 if (NILP (color_val) && max_key > 0)
3970 if (xstrcasecmp (max_color, "None") == 0)
3971 color_val = Qt;
3972 else if (x_defined_color (f, max_color, &cdef, 0))
3973 color_val = make_number (cdef.pixel);
3975 if (!NILP (color_val))
3976 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
3978 expect (',');
3981 if (!x_create_x_image_and_pixmap (f, width, height, 0,
3982 &ximg, &img->pixmap)
3983 #ifndef HAVE_NS
3984 || !x_create_x_image_and_pixmap (f, width, height, 1,
3985 &mask_img, &img->mask)
3986 #endif
3989 image_error ("Out of memory (%s)", img->spec, Qnil);
3990 goto error;
3993 for (y = 0; y < height; y++)
3995 expect (XPM_TK_STRING);
3996 str = beg;
3997 if (len < width * chars_per_pixel)
3998 goto failure;
3999 for (x = 0; x < width; x++, str += chars_per_pixel)
4001 Lisp_Object color_val =
4002 (*get_color_table) (color_table, str, chars_per_pixel);
4004 XPutPixel (ximg, x, y,
4005 (INTEGERP (color_val) ? XINT (color_val)
4006 : FRAME_FOREGROUND_PIXEL (f)));
4007 #ifndef HAVE_NS
4008 XPutPixel (mask_img, x, y,
4009 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4010 : (have_mask = 1, PIX_MASK_RETAIN)));
4011 #else
4012 if (EQ (color_val, Qt))
4013 ns_set_alpha (ximg, x, y, 0);
4014 #endif
4016 if (y + 1 < height)
4017 expect (',');
4020 img->width = width;
4021 img->height = height;
4023 /* Maybe fill in the background field while we have ximg handy. */
4024 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4025 IMAGE_BACKGROUND (img, f, ximg);
4027 x_put_x_image (f, ximg, img->pixmap, width, height);
4028 x_destroy_x_image (ximg);
4029 #ifndef HAVE_NS
4030 if (have_mask)
4032 /* Fill in the background_transparent field while we have the
4033 mask handy. */
4034 image_background_transparent (img, f, mask_img);
4036 x_put_x_image (f, mask_img, img->mask, width, height);
4037 x_destroy_x_image (mask_img);
4039 else
4041 x_destroy_x_image (mask_img);
4042 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4043 img->mask = NO_PIXMAP;
4045 #endif
4046 return 1;
4048 failure:
4049 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4050 error:
4051 x_destroy_x_image (ximg);
4052 x_destroy_x_image (mask_img);
4053 x_clear_image (f, img);
4054 return 0;
4056 #undef match
4057 #undef expect
4058 #undef expect_ident
4061 static int
4062 xpm_load (struct frame *f,
4063 struct image *img)
4065 int success_p = 0;
4066 Lisp_Object file_name;
4068 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4069 file_name = image_spec_value (img->spec, QCfile, NULL);
4070 if (STRINGP (file_name))
4072 Lisp_Object file;
4073 unsigned char *contents;
4074 int size;
4076 file = x_find_image_file (file_name);
4077 if (!STRINGP (file))
4079 image_error ("Cannot find image file `%s'", file_name, Qnil);
4080 return 0;
4083 contents = slurp_file (SDATA (file), &size);
4084 if (contents == NULL)
4086 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4087 return 0;
4090 success_p = xpm_load_image (f, img, contents, contents + size);
4091 xfree (contents);
4093 else
4095 Lisp_Object data;
4097 data = image_spec_value (img->spec, QCdata, NULL);
4098 if (!STRINGP (data))
4100 image_error ("Invalid image data `%s'", data, Qnil);
4101 return 0;
4103 success_p = xpm_load_image (f, img, SDATA (data),
4104 SDATA (data) + SBYTES (data));
4107 return success_p;
4110 #endif /* HAVE_NS && !HAVE_XPM */
4114 /***********************************************************************
4115 Color table
4116 ***********************************************************************/
4118 #ifdef COLOR_TABLE_SUPPORT
4120 /* An entry in the color table mapping an RGB color to a pixel color. */
4122 struct ct_color
4124 int r, g, b;
4125 unsigned long pixel;
4127 /* Next in color table collision list. */
4128 struct ct_color *next;
4131 /* The bucket vector size to use. Must be prime. */
4133 #define CT_SIZE 101
4135 /* Value is a hash of the RGB color given by R, G, and B. */
4137 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4139 /* The color hash table. */
4141 struct ct_color **ct_table;
4143 /* Number of entries in the color table. */
4145 int ct_colors_allocated;
4147 /* Initialize the color table. */
4149 static void
4150 init_color_table (void)
4152 int size = CT_SIZE * sizeof (*ct_table);
4153 ct_table = (struct ct_color **) xmalloc (size);
4154 memset (ct_table, 0, size);
4155 ct_colors_allocated = 0;
4159 /* Free memory associated with the color table. */
4161 static void
4162 free_color_table (void)
4164 int i;
4165 struct ct_color *p, *next;
4167 for (i = 0; i < CT_SIZE; ++i)
4168 for (p = ct_table[i]; p; p = next)
4170 next = p->next;
4171 xfree (p);
4174 xfree (ct_table);
4175 ct_table = NULL;
4179 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4180 entry for that color already is in the color table, return the
4181 pixel color of that entry. Otherwise, allocate a new color for R,
4182 G, B, and make an entry in the color table. */
4184 static unsigned long
4185 lookup_rgb_color (struct frame *f, int r, int g, int b)
4187 unsigned hash = CT_HASH_RGB (r, g, b);
4188 int i = hash % CT_SIZE;
4189 struct ct_color *p;
4190 Display_Info *dpyinfo;
4192 /* Handle TrueColor visuals specially, which improves performance by
4193 two orders of magnitude. Freeing colors on TrueColor visuals is
4194 a nop, and pixel colors specify RGB values directly. See also
4195 the Xlib spec, chapter 3.1. */
4196 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4197 if (dpyinfo->red_bits > 0)
4199 unsigned long pr, pg, pb;
4201 /* Apply gamma-correction like normal color allocation does. */
4202 if (f->gamma)
4204 XColor color;
4205 color.red = r, color.green = g, color.blue = b;
4206 gamma_correct (f, &color);
4207 r = color.red, g = color.green, b = color.blue;
4210 /* Scale down RGB values to the visual's bits per RGB, and shift
4211 them to the right position in the pixel color. Note that the
4212 original RGB values are 16-bit values, as usual in X. */
4213 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4214 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4215 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4217 /* Assemble the pixel color. */
4218 return pr | pg | pb;
4221 for (p = ct_table[i]; p; p = p->next)
4222 if (p->r == r && p->g == g && p->b == b)
4223 break;
4225 if (p == NULL)
4228 #ifdef HAVE_X_WINDOWS
4229 XColor color;
4230 Colormap cmap;
4231 int rc;
4233 color.red = r;
4234 color.green = g;
4235 color.blue = b;
4237 cmap = FRAME_X_COLORMAP (f);
4238 rc = x_alloc_nearest_color (f, cmap, &color);
4239 if (rc)
4241 ++ct_colors_allocated;
4242 p = (struct ct_color *) xmalloc (sizeof *p);
4243 p->r = r;
4244 p->g = g;
4245 p->b = b;
4246 p->pixel = color.pixel;
4247 p->next = ct_table[i];
4248 ct_table[i] = p;
4250 else
4251 return FRAME_FOREGROUND_PIXEL (f);
4253 #else
4254 COLORREF color;
4255 #ifdef HAVE_NTGUI
4256 color = PALETTERGB (r, g, b);
4257 #else
4258 color = RGB_TO_ULONG (r, g, b);
4259 #endif /* HAVE_NTGUI */
4260 ++ct_colors_allocated;
4261 p = (struct ct_color *) xmalloc (sizeof *p);
4262 p->r = r;
4263 p->g = g;
4264 p->b = b;
4265 p->pixel = color;
4266 p->next = ct_table[i];
4267 ct_table[i] = p;
4268 #endif /* HAVE_X_WINDOWS */
4272 return p->pixel;
4276 /* Look up pixel color PIXEL which is used on frame F in the color
4277 table. If not already present, allocate it. Value is PIXEL. */
4279 static unsigned long
4280 lookup_pixel_color (struct frame *f, unsigned long pixel)
4282 int i = pixel % CT_SIZE;
4283 struct ct_color *p;
4285 for (p = ct_table[i]; p; p = p->next)
4286 if (p->pixel == pixel)
4287 break;
4289 if (p == NULL)
4291 XColor color;
4292 Colormap cmap;
4293 int rc;
4295 #ifdef HAVE_X_WINDOWS
4296 cmap = FRAME_X_COLORMAP (f);
4297 color.pixel = pixel;
4298 x_query_color (f, &color);
4299 rc = x_alloc_nearest_color (f, cmap, &color);
4300 #else
4301 BLOCK_INPUT;
4302 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4303 color.pixel = pixel;
4304 XQueryColor (NULL, cmap, &color);
4305 rc = x_alloc_nearest_color (f, cmap, &color);
4306 UNBLOCK_INPUT;
4307 #endif /* HAVE_X_WINDOWS */
4309 if (rc)
4311 ++ct_colors_allocated;
4313 p = (struct ct_color *) xmalloc (sizeof *p);
4314 p->r = color.red;
4315 p->g = color.green;
4316 p->b = color.blue;
4317 p->pixel = pixel;
4318 p->next = ct_table[i];
4319 ct_table[i] = p;
4321 else
4322 return FRAME_FOREGROUND_PIXEL (f);
4324 return p->pixel;
4328 /* Value is a vector of all pixel colors contained in the color table,
4329 allocated via xmalloc. Set *N to the number of colors. */
4331 static unsigned long *
4332 colors_in_color_table (int *n)
4334 int i, j;
4335 struct ct_color *p;
4336 unsigned long *colors;
4338 if (ct_colors_allocated == 0)
4340 *n = 0;
4341 colors = NULL;
4343 else
4345 colors = (unsigned long *) xmalloc (ct_colors_allocated
4346 * sizeof *colors);
4347 *n = ct_colors_allocated;
4349 for (i = j = 0; i < CT_SIZE; ++i)
4350 for (p = ct_table[i]; p; p = p->next)
4351 colors[j++] = p->pixel;
4354 return colors;
4357 #else /* COLOR_TABLE_SUPPORT */
4359 static unsigned long
4360 lookup_rgb_color (struct frame *f, int r, int g, int b)
4362 unsigned long pixel;
4364 #ifdef HAVE_NTGUI
4365 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4366 #endif /* HAVE_NTGUI */
4368 #ifdef HAVE_NS
4369 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4370 #endif /* HAVE_NS */
4371 return pixel;
4374 static void
4375 init_color_table (void)
4378 #endif /* COLOR_TABLE_SUPPORT */
4381 /***********************************************************************
4382 Algorithms
4383 ***********************************************************************/
4385 static XColor *x_to_xcolors (struct frame *, struct image *, int);
4386 static void x_from_xcolors (struct frame *, struct image *, XColor *);
4387 static void x_detect_edges (struct frame *, struct image *, int[9], int);
4389 #ifdef HAVE_NTGUI
4390 static void XPutPixel (XImagePtr , int, int, COLORREF);
4391 #endif /* HAVE_NTGUI */
4393 /* Edge detection matrices for different edge-detection
4394 strategies. */
4396 static int emboss_matrix[9] = {
4397 /* x - 1 x x + 1 */
4398 2, -1, 0, /* y - 1 */
4399 -1, 0, 1, /* y */
4400 0, 1, -2 /* y + 1 */
4403 static int laplace_matrix[9] = {
4404 /* x - 1 x x + 1 */
4405 1, 0, 0, /* y - 1 */
4406 0, 0, 0, /* y */
4407 0, 0, -1 /* y + 1 */
4410 /* Value is the intensity of the color whose red/green/blue values
4411 are R, G, and B. */
4413 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4416 /* On frame F, return an array of XColor structures describing image
4417 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4418 non-zero means also fill the red/green/blue members of the XColor
4419 structures. Value is a pointer to the array of XColors structures,
4420 allocated with xmalloc; it must be freed by the caller. */
4422 static XColor *
4423 x_to_xcolors (struct frame *f, struct image *img, int rgb_p)
4425 int x, y;
4426 XColor *colors, *p;
4427 XImagePtr_or_DC ximg;
4428 #ifdef HAVE_NTGUI
4429 HDC hdc;
4430 HGDIOBJ prev;
4431 #endif /* HAVE_NTGUI */
4433 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4435 #ifndef HAVE_NTGUI
4436 /* Get the X image IMG->pixmap. */
4437 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4438 0, 0, img->width, img->height, ~0, ZPixmap);
4439 #else
4440 /* Load the image into a memory device context. */
4441 hdc = get_frame_dc (f);
4442 ximg = CreateCompatibleDC (hdc);
4443 release_frame_dc (f, hdc);
4444 prev = SelectObject (ximg, img->pixmap);
4445 #endif /* HAVE_NTGUI */
4447 /* Fill the `pixel' members of the XColor array. I wished there
4448 were an easy and portable way to circumvent XGetPixel. */
4449 p = colors;
4450 for (y = 0; y < img->height; ++y)
4452 XColor *row = p;
4454 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4455 for (x = 0; x < img->width; ++x, ++p)
4456 p->pixel = GET_PIXEL (ximg, x, y);
4457 if (rgb_p)
4458 x_query_colors (f, row, img->width);
4460 #else
4462 for (x = 0; x < img->width; ++x, ++p)
4464 /* W32_TODO: palette support needed here? */
4465 p->pixel = GET_PIXEL (ximg, x, y);
4466 if (rgb_p)
4468 p->red = RED16_FROM_ULONG (p->pixel);
4469 p->green = GREEN16_FROM_ULONG (p->pixel);
4470 p->blue = BLUE16_FROM_ULONG (p->pixel);
4473 #endif /* HAVE_X_WINDOWS */
4476 Destroy_Image (ximg, prev);
4478 return colors;
4481 #ifdef HAVE_NTGUI
4483 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4484 created with CreateDIBSection, with the pointer to the bit values
4485 stored in ximg->data. */
4487 static void
4488 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4490 int width = ximg->info.bmiHeader.biWidth;
4491 int height = ximg->info.bmiHeader.biHeight;
4492 unsigned char * pixel;
4494 /* True color images. */
4495 if (ximg->info.bmiHeader.biBitCount == 24)
4497 int rowbytes = width * 3;
4498 /* Ensure scanlines are aligned on 4 byte boundaries. */
4499 if (rowbytes % 4)
4500 rowbytes += 4 - (rowbytes % 4);
4502 pixel = ximg->data + y * rowbytes + x * 3;
4503 /* Windows bitmaps are in BGR order. */
4504 *pixel = GetBValue (color);
4505 *(pixel + 1) = GetGValue (color);
4506 *(pixel + 2) = GetRValue (color);
4508 /* Monochrome images. */
4509 else if (ximg->info.bmiHeader.biBitCount == 1)
4511 int rowbytes = width / 8;
4512 /* Ensure scanlines are aligned on 4 byte boundaries. */
4513 if (rowbytes % 4)
4514 rowbytes += 4 - (rowbytes % 4);
4515 pixel = ximg->data + y * rowbytes + x / 8;
4516 /* Filter out palette info. */
4517 if (color & 0x00ffffff)
4518 *pixel = *pixel | (1 << x % 8);
4519 else
4520 *pixel = *pixel & ~(1 << x % 8);
4522 else
4523 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4526 #endif /* HAVE_NTGUI */
4528 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4529 RGB members are set. F is the frame on which this all happens.
4530 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4532 static void
4533 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4535 int x, y;
4536 XImagePtr oimg = NULL;
4537 Pixmap pixmap;
4538 XColor *p;
4540 init_color_table ();
4542 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4543 &oimg, &pixmap);
4544 p = colors;
4545 for (y = 0; y < img->height; ++y)
4546 for (x = 0; x < img->width; ++x, ++p)
4548 unsigned long pixel;
4549 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4550 XPutPixel (oimg, x, y, pixel);
4553 xfree (colors);
4554 x_clear_image_1 (f, img, 1, 0, 1);
4556 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4557 x_destroy_x_image (oimg);
4558 img->pixmap = pixmap;
4559 #ifdef COLOR_TABLE_SUPPORT
4560 img->colors = colors_in_color_table (&img->ncolors);
4561 free_color_table ();
4562 #endif /* COLOR_TABLE_SUPPORT */
4566 /* On frame F, perform edge-detection on image IMG.
4568 MATRIX is a nine-element array specifying the transformation
4569 matrix. See emboss_matrix for an example.
4571 COLOR_ADJUST is a color adjustment added to each pixel of the
4572 outgoing image. */
4574 static void
4575 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4577 XColor *colors = x_to_xcolors (f, img, 1);
4578 XColor *new, *p;
4579 int x, y, i, sum;
4581 for (i = sum = 0; i < 9; ++i)
4582 sum += eabs (matrix[i]);
4584 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4586 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4588 for (y = 0; y < img->height; ++y)
4590 p = COLOR (new, 0, y);
4591 p->red = p->green = p->blue = 0xffff/2;
4592 p = COLOR (new, img->width - 1, y);
4593 p->red = p->green = p->blue = 0xffff/2;
4596 for (x = 1; x < img->width - 1; ++x)
4598 p = COLOR (new, x, 0);
4599 p->red = p->green = p->blue = 0xffff/2;
4600 p = COLOR (new, x, img->height - 1);
4601 p->red = p->green = p->blue = 0xffff/2;
4604 for (y = 1; y < img->height - 1; ++y)
4606 p = COLOR (new, 1, y);
4608 for (x = 1; x < img->width - 1; ++x, ++p)
4610 int r, g, b, y1, x1;
4612 r = g = b = i = 0;
4613 for (y1 = y - 1; y1 < y + 2; ++y1)
4614 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
4615 if (matrix[i])
4617 XColor *t = COLOR (colors, x1, y1);
4618 r += matrix[i] * t->red;
4619 g += matrix[i] * t->green;
4620 b += matrix[i] * t->blue;
4623 r = (r / sum + color_adjust) & 0xffff;
4624 g = (g / sum + color_adjust) & 0xffff;
4625 b = (b / sum + color_adjust) & 0xffff;
4626 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4630 xfree (colors);
4631 x_from_xcolors (f, img, new);
4633 #undef COLOR
4637 /* Perform the pre-defined `emboss' edge-detection on image IMG
4638 on frame F. */
4640 static void
4641 x_emboss (struct frame *f, struct image *img)
4643 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4647 /* Transform image IMG which is used on frame F with a Laplace
4648 edge-detection algorithm. The result is an image that can be used
4649 to draw disabled buttons, for example. */
4651 static void
4652 x_laplace (struct frame *f, struct image *img)
4654 x_detect_edges (f, img, laplace_matrix, 45000);
4658 /* Perform edge-detection on image IMG on frame F, with specified
4659 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4661 MATRIX must be either
4663 - a list of at least 9 numbers in row-major form
4664 - a vector of at least 9 numbers
4666 COLOR_ADJUST nil means use a default; otherwise it must be a
4667 number. */
4669 static void
4670 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4671 Lisp_Object color_adjust)
4673 int i = 0;
4674 int trans[9];
4676 if (CONSP (matrix))
4678 for (i = 0;
4679 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4680 ++i, matrix = XCDR (matrix))
4681 trans[i] = XFLOATINT (XCAR (matrix));
4683 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4685 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4686 trans[i] = XFLOATINT (AREF (matrix, i));
4689 if (NILP (color_adjust))
4690 color_adjust = make_number (0xffff / 2);
4692 if (i == 9 && NUMBERP (color_adjust))
4693 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
4697 /* Transform image IMG on frame F so that it looks disabled. */
4699 static void
4700 x_disable_image (struct frame *f, struct image *img)
4702 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4703 #ifdef HAVE_NTGUI
4704 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4705 #else
4706 int n_planes = dpyinfo->n_planes;
4707 #endif /* HAVE_NTGUI */
4709 if (n_planes >= 2)
4711 /* Color (or grayscale). Convert to gray, and equalize. Just
4712 drawing such images with a stipple can look very odd, so
4713 we're using this method instead. */
4714 XColor *colors = x_to_xcolors (f, img, 1);
4715 XColor *p, *end;
4716 const int h = 15000;
4717 const int l = 30000;
4719 for (p = colors, end = colors + img->width * img->height;
4720 p < end;
4721 ++p)
4723 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4724 int i2 = (0xffff - h - l) * i / 0xffff + l;
4725 p->red = p->green = p->blue = i2;
4728 x_from_xcolors (f, img, colors);
4731 /* Draw a cross over the disabled image, if we must or if we
4732 should. */
4733 if (n_planes < 2 || cross_disabled_images)
4735 #ifndef HAVE_NTGUI
4736 Display *dpy = FRAME_X_DISPLAY (f);
4737 GC gc;
4739 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4741 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4743 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4744 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4745 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4746 img->width - 1, img->height - 1);
4747 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4748 img->width - 1, 0);
4749 XFreeGC (dpy, gc);
4751 if (img->mask)
4753 gc = XCreateGC (dpy, img->mask, 0, NULL);
4754 XSetForeground (dpy, gc, MaskForeground (f));
4755 XDrawLine (dpy, img->mask, gc, 0, 0,
4756 img->width - 1, img->height - 1);
4757 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4758 img->width - 1, 0);
4759 XFreeGC (dpy, gc);
4761 #endif /* !HAVE_NS */
4762 #else
4763 HDC hdc, bmpdc;
4764 HGDIOBJ prev;
4766 hdc = get_frame_dc (f);
4767 bmpdc = CreateCompatibleDC (hdc);
4768 release_frame_dc (f, hdc);
4770 prev = SelectObject (bmpdc, img->pixmap);
4772 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4773 MoveToEx (bmpdc, 0, 0, NULL);
4774 LineTo (bmpdc, img->width - 1, img->height - 1);
4775 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4776 LineTo (bmpdc, img->width - 1, 0);
4778 if (img->mask)
4780 SelectObject (bmpdc, img->mask);
4781 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4782 MoveToEx (bmpdc, 0, 0, NULL);
4783 LineTo (bmpdc, img->width - 1, img->height - 1);
4784 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4785 LineTo (bmpdc, img->width - 1, 0);
4787 SelectObject (bmpdc, prev);
4788 DeleteDC (bmpdc);
4789 #endif /* HAVE_NTGUI */
4794 /* Build a mask for image IMG which is used on frame F. FILE is the
4795 name of an image file, for error messages. HOW determines how to
4796 determine the background color of IMG. If it is a list '(R G B)',
4797 with R, G, and B being integers >= 0, take that as the color of the
4798 background. Otherwise, determine the background color of IMG
4799 heuristically. Value is non-zero if successful. */
4801 static int
4802 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4804 XImagePtr_or_DC ximg;
4805 #ifndef HAVE_NTGUI
4806 XImagePtr mask_img;
4807 #else
4808 HDC frame_dc;
4809 HGDIOBJ prev;
4810 char *mask_img;
4811 int row_width;
4812 #endif /* HAVE_NTGUI */
4813 int x, y, rc, use_img_background;
4814 unsigned long bg = 0;
4816 if (img->mask)
4818 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4819 img->mask = NO_PIXMAP;
4820 img->background_transparent_valid = 0;
4823 #ifndef HAVE_NTGUI
4824 #ifndef HAVE_NS
4825 /* Create an image and pixmap serving as mask. */
4826 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4827 &mask_img, &img->mask);
4828 if (!rc)
4829 return 0;
4830 #endif /* !HAVE_NS */
4832 /* Get the X image of IMG->pixmap. */
4833 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4834 img->width, img->height,
4835 ~0, ZPixmap);
4836 #else
4837 /* Create the bit array serving as mask. */
4838 row_width = (img->width + 7) / 8;
4839 mask_img = xmalloc (row_width * img->height);
4840 memset (mask_img, 0, row_width * img->height);
4842 /* Create a memory device context for IMG->pixmap. */
4843 frame_dc = get_frame_dc (f);
4844 ximg = CreateCompatibleDC (frame_dc);
4845 release_frame_dc (f, frame_dc);
4846 prev = SelectObject (ximg, img->pixmap);
4847 #endif /* HAVE_NTGUI */
4849 /* Determine the background color of ximg. If HOW is `(R G B)'
4850 take that as color. Otherwise, use the image's background color. */
4851 use_img_background = 1;
4853 if (CONSP (how))
4855 int rgb[3], i;
4857 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4859 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4860 how = XCDR (how);
4863 if (i == 3 && NILP (how))
4865 char color_name[30];
4866 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4867 bg = (
4868 #ifdef HAVE_NTGUI
4869 0x00ffffff & /* Filter out palette info. */
4870 #endif /* HAVE_NTGUI */
4871 x_alloc_image_color (f, img, build_string (color_name), 0));
4872 use_img_background = 0;
4876 if (use_img_background)
4877 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4879 /* Set all bits in mask_img to 1 whose color in ximg is different
4880 from the background color bg. */
4881 #ifndef HAVE_NTGUI
4882 for (y = 0; y < img->height; ++y)
4883 for (x = 0; x < img->width; ++x)
4884 #ifndef HAVE_NS
4885 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4886 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4887 #else
4888 if (XGetPixel (ximg, x, y) == bg)
4889 ns_set_alpha (ximg, x, y, 0);
4890 #endif /* HAVE_NS */
4891 #ifndef HAVE_NS
4892 /* Fill in the background_transparent field while we have the mask handy. */
4893 image_background_transparent (img, f, mask_img);
4895 /* Put mask_img into img->mask. */
4896 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4897 x_destroy_x_image (mask_img);
4898 #endif /* !HAVE_NS */
4899 #else
4900 for (y = 0; y < img->height; ++y)
4901 for (x = 0; x < img->width; ++x)
4903 COLORREF p = GetPixel (ximg, x, y);
4904 if (p != bg)
4905 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4908 /* Create the mask image. */
4909 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4910 mask_img);
4911 /* Fill in the background_transparent field while we have the mask handy. */
4912 SelectObject (ximg, img->mask);
4913 image_background_transparent (img, f, ximg);
4915 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4916 xfree (mask_img);
4917 #endif /* HAVE_NTGUI */
4919 Destroy_Image (ximg, prev);
4921 return 1;
4925 /***********************************************************************
4926 PBM (mono, gray, color)
4927 ***********************************************************************/
4929 static int pbm_image_p (Lisp_Object object);
4930 static int pbm_load (struct frame *f, struct image *img);
4931 static int pbm_scan_number (unsigned char **, unsigned char *);
4933 /* The symbol `pbm' identifying images of this type. */
4935 Lisp_Object Qpbm;
4937 /* Indices of image specification fields in gs_format, below. */
4939 enum pbm_keyword_index
4941 PBM_TYPE,
4942 PBM_FILE,
4943 PBM_DATA,
4944 PBM_ASCENT,
4945 PBM_MARGIN,
4946 PBM_RELIEF,
4947 PBM_ALGORITHM,
4948 PBM_HEURISTIC_MASK,
4949 PBM_MASK,
4950 PBM_FOREGROUND,
4951 PBM_BACKGROUND,
4952 PBM_LAST
4955 /* Vector of image_keyword structures describing the format
4956 of valid user-defined image specifications. */
4958 static const struct image_keyword pbm_format[PBM_LAST] =
4960 {":type", IMAGE_SYMBOL_VALUE, 1},
4961 {":file", IMAGE_STRING_VALUE, 0},
4962 {":data", IMAGE_STRING_VALUE, 0},
4963 {":ascent", IMAGE_ASCENT_VALUE, 0},
4964 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
4965 {":relief", IMAGE_INTEGER_VALUE, 0},
4966 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4967 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4968 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4969 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4970 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4973 /* Structure describing the image type `pbm'. */
4975 static struct image_type pbm_type =
4977 &Qpbm,
4978 pbm_image_p,
4979 pbm_load,
4980 x_clear_image,
4981 NULL
4985 /* Return non-zero if OBJECT is a valid PBM image specification. */
4987 static int
4988 pbm_image_p (Lisp_Object object)
4990 struct image_keyword fmt[PBM_LAST];
4992 memcpy (fmt, pbm_format, sizeof fmt);
4994 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
4995 return 0;
4997 /* Must specify either :data or :file. */
4998 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5002 /* Scan a decimal number from *S and return it. Advance *S while
5003 reading the number. END is the end of the string. Value is -1 at
5004 end of input. */
5006 static int
5007 pbm_scan_number (unsigned char **s, unsigned char *end)
5009 int c = 0, val = -1;
5011 while (*s < end)
5013 /* Skip white-space. */
5014 while (*s < end && (c = *(*s)++, isspace (c)))
5017 if (c == '#')
5019 /* Skip comment to end of line. */
5020 while (*s < end && (c = *(*s)++, c != '\n'))
5023 else if (isdigit (c))
5025 /* Read decimal number. */
5026 val = c - '0';
5027 while (*s < end && (c = *(*s)++, isdigit (c)))
5028 val = 10 * val + c - '0';
5029 break;
5031 else
5032 break;
5035 return val;
5039 #ifdef HAVE_NTGUI
5040 #if 0 /* Unused. ++kfs */
5042 /* Read FILE into memory. Value is a pointer to a buffer allocated
5043 with xmalloc holding FILE's contents. Value is null if an error
5044 occurred. *SIZE is set to the size of the file. */
5046 static char *
5047 pbm_read_file (file, size)
5048 Lisp_Object file;
5049 int *size;
5051 FILE *fp = NULL;
5052 char *buf = NULL;
5053 struct stat st;
5055 if (stat (SDATA (file), &st) == 0
5056 && (fp = fopen (SDATA (file), "rb")) != NULL
5057 && (buf = (char *) xmalloc (st.st_size),
5058 fread (buf, 1, st.st_size, fp) == st.st_size))
5060 *size = st.st_size;
5061 fclose (fp);
5063 else
5065 if (fp)
5066 fclose (fp);
5067 if (buf)
5069 xfree (buf);
5070 buf = NULL;
5074 return buf;
5076 #endif
5077 #endif /* HAVE_NTGUI */
5079 /* Load PBM image IMG for use on frame F. */
5081 static int
5082 pbm_load (struct frame *f, struct image *img)
5084 int raw_p, x, y;
5085 int width, height, max_color_idx = 0;
5086 XImagePtr ximg;
5087 Lisp_Object file, specified_file;
5088 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5089 unsigned char *contents = NULL;
5090 unsigned char *end, *p;
5091 int size;
5093 specified_file = image_spec_value (img->spec, QCfile, NULL);
5095 if (STRINGP (specified_file))
5097 file = x_find_image_file (specified_file);
5098 if (!STRINGP (file))
5100 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5101 return 0;
5104 contents = slurp_file (SSDATA (file), &size);
5105 if (contents == NULL)
5107 image_error ("Error reading `%s'", file, Qnil);
5108 return 0;
5111 p = contents;
5112 end = contents + size;
5114 else
5116 Lisp_Object data;
5117 data = image_spec_value (img->spec, QCdata, NULL);
5118 if (!STRINGP (data))
5120 image_error ("Invalid image data `%s'", data, Qnil);
5121 return 0;
5123 p = SDATA (data);
5124 end = p + SBYTES (data);
5127 /* Check magic number. */
5128 if (end - p < 2 || *p++ != 'P')
5130 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5131 error:
5132 xfree (contents);
5133 return 0;
5136 switch (*p++)
5138 case '1':
5139 raw_p = 0, type = PBM_MONO;
5140 break;
5142 case '2':
5143 raw_p = 0, type = PBM_GRAY;
5144 break;
5146 case '3':
5147 raw_p = 0, type = PBM_COLOR;
5148 break;
5150 case '4':
5151 raw_p = 1, type = PBM_MONO;
5152 break;
5154 case '5':
5155 raw_p = 1, type = PBM_GRAY;
5156 break;
5158 case '6':
5159 raw_p = 1, type = PBM_COLOR;
5160 break;
5162 default:
5163 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5164 goto error;
5167 /* Read width, height, maximum color-component. Characters
5168 starting with `#' up to the end of a line are ignored. */
5169 width = pbm_scan_number (&p, end);
5170 height = pbm_scan_number (&p, end);
5172 if (type != PBM_MONO)
5174 max_color_idx = pbm_scan_number (&p, end);
5175 if (max_color_idx > 65535 || max_color_idx < 0)
5177 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5178 goto error;
5182 if (!check_image_size (f, width, height))
5184 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5185 goto error;
5188 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5189 &ximg, &img->pixmap))
5190 goto error;
5192 /* Initialize the color hash table. */
5193 init_color_table ();
5195 if (type == PBM_MONO)
5197 int c = 0, g;
5198 struct image_keyword fmt[PBM_LAST];
5199 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5200 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5202 /* Parse the image specification. */
5203 memcpy (fmt, pbm_format, sizeof fmt);
5204 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5206 /* Get foreground and background colors, maybe allocate colors. */
5207 if (fmt[PBM_FOREGROUND].count
5208 && STRINGP (fmt[PBM_FOREGROUND].value))
5209 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5210 if (fmt[PBM_BACKGROUND].count
5211 && STRINGP (fmt[PBM_BACKGROUND].value))
5213 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5214 img->background = bg;
5215 img->background_valid = 1;
5218 for (y = 0; y < height; ++y)
5219 for (x = 0; x < width; ++x)
5221 if (raw_p)
5223 if ((x & 7) == 0)
5225 if (p >= end)
5227 x_destroy_x_image (ximg);
5228 x_clear_image (f, img);
5229 image_error ("Invalid image size in image `%s'",
5230 img->spec, Qnil);
5231 goto error;
5233 c = *p++;
5235 g = c & 0x80;
5236 c <<= 1;
5238 else
5239 g = pbm_scan_number (&p, end);
5241 XPutPixel (ximg, x, y, g ? fg : bg);
5244 else
5246 int expected_size = height * width;
5247 if (max_color_idx > 255)
5248 expected_size *= 2;
5249 if (type == PBM_COLOR)
5250 expected_size *= 3;
5252 if (raw_p && p + expected_size > end)
5254 x_destroy_x_image (ximg);
5255 x_clear_image (f, img);
5256 image_error ("Invalid image size in image `%s'",
5257 img->spec, Qnil);
5258 goto error;
5261 for (y = 0; y < height; ++y)
5262 for (x = 0; x < width; ++x)
5264 int r, g, b;
5266 if (type == PBM_GRAY && raw_p)
5268 r = g = b = *p++;
5269 if (max_color_idx > 255)
5270 r = g = b = r * 256 + *p++;
5272 else if (type == PBM_GRAY)
5273 r = g = b = pbm_scan_number (&p, end);
5274 else if (raw_p)
5276 r = *p++;
5277 if (max_color_idx > 255)
5278 r = r * 256 + *p++;
5279 g = *p++;
5280 if (max_color_idx > 255)
5281 g = g * 256 + *p++;
5282 b = *p++;
5283 if (max_color_idx > 255)
5284 b = b * 256 + *p++;
5286 else
5288 r = pbm_scan_number (&p, end);
5289 g = pbm_scan_number (&p, end);
5290 b = pbm_scan_number (&p, end);
5293 if (r < 0 || g < 0 || b < 0)
5295 x_destroy_x_image (ximg);
5296 image_error ("Invalid pixel value in image `%s'",
5297 img->spec, Qnil);
5298 goto error;
5301 /* RGB values are now in the range 0..max_color_idx.
5302 Scale this to the range 0..0xffff supported by X. */
5303 r = (double) r * 65535 / max_color_idx;
5304 g = (double) g * 65535 / max_color_idx;
5305 b = (double) b * 65535 / max_color_idx;
5306 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5310 #ifdef COLOR_TABLE_SUPPORT
5311 /* Store in IMG->colors the colors allocated for the image, and
5312 free the color table. */
5313 img->colors = colors_in_color_table (&img->ncolors);
5314 free_color_table ();
5315 #endif /* COLOR_TABLE_SUPPORT */
5317 img->width = width;
5318 img->height = height;
5320 /* Maybe fill in the background field while we have ximg handy. */
5322 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5323 /* Casting avoids a GCC warning. */
5324 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5326 /* Put the image into a pixmap. */
5327 x_put_x_image (f, ximg, img->pixmap, width, height);
5328 x_destroy_x_image (ximg);
5330 /* X and W32 versions did it here, MAC version above. ++kfs
5331 img->width = width;
5332 img->height = height; */
5334 xfree (contents);
5335 return 1;
5339 /***********************************************************************
5341 ***********************************************************************/
5343 #if defined (HAVE_PNG) || defined (HAVE_NS)
5345 /* Function prototypes. */
5347 static int png_image_p (Lisp_Object object);
5348 static int png_load (struct frame *f, struct image *img);
5350 /* The symbol `png' identifying images of this type. */
5352 Lisp_Object Qpng;
5354 /* Indices of image specification fields in png_format, below. */
5356 enum png_keyword_index
5358 PNG_TYPE,
5359 PNG_DATA,
5360 PNG_FILE,
5361 PNG_ASCENT,
5362 PNG_MARGIN,
5363 PNG_RELIEF,
5364 PNG_ALGORITHM,
5365 PNG_HEURISTIC_MASK,
5366 PNG_MASK,
5367 PNG_BACKGROUND,
5368 PNG_LAST
5371 /* Vector of image_keyword structures describing the format
5372 of valid user-defined image specifications. */
5374 static const struct image_keyword png_format[PNG_LAST] =
5376 {":type", IMAGE_SYMBOL_VALUE, 1},
5377 {":data", IMAGE_STRING_VALUE, 0},
5378 {":file", IMAGE_STRING_VALUE, 0},
5379 {":ascent", IMAGE_ASCENT_VALUE, 0},
5380 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5381 {":relief", IMAGE_INTEGER_VALUE, 0},
5382 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5383 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5384 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5385 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5388 /* Structure describing the image type `png'. */
5390 static struct image_type png_type =
5392 &Qpng,
5393 png_image_p,
5394 png_load,
5395 x_clear_image,
5396 NULL
5399 /* Return non-zero if OBJECT is a valid PNG image specification. */
5401 static int
5402 png_image_p (Lisp_Object object)
5404 struct image_keyword fmt[PNG_LAST];
5405 memcpy (fmt, png_format, sizeof fmt);
5407 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5408 return 0;
5410 /* Must specify either the :data or :file keyword. */
5411 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5414 #endif /* HAVE_PNG || HAVE_NS */
5417 #ifdef HAVE_PNG
5419 #ifdef HAVE_NTGUI
5420 /* PNG library details. */
5422 DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5423 DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5424 DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5425 png_error_ptr, png_error_ptr));
5426 DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5427 DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5428 DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5429 DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5430 DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5431 DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
5432 png_uint_32 *, png_uint_32 *,
5433 int *, int *, int *, int *, int *));
5434 DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5435 DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5436 DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5437 DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5438 DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
5439 int, int, double));
5440 DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5441 DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5442 DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5443 DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5444 DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5445 DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5446 DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
5448 #if (PNG_LIBPNG_VER >= 10500)
5449 DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int));
5450 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
5451 #endif /* libpng version >= 1.5 */
5453 static int
5454 init_png_functions (Lisp_Object libraries)
5456 HMODULE library;
5458 /* Try loading libpng under probable names. */
5459 if (!(library = w32_delayed_load (libraries, Qpng)))
5460 return 0;
5462 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5463 LOAD_IMGLIB_FN (library, png_sig_cmp);
5464 LOAD_IMGLIB_FN (library, png_create_read_struct);
5465 LOAD_IMGLIB_FN (library, png_create_info_struct);
5466 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5467 LOAD_IMGLIB_FN (library, png_set_read_fn);
5468 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5469 LOAD_IMGLIB_FN (library, png_read_info);
5470 LOAD_IMGLIB_FN (library, png_get_IHDR);
5471 LOAD_IMGLIB_FN (library, png_get_valid);
5472 LOAD_IMGLIB_FN (library, png_set_strip_16);
5473 LOAD_IMGLIB_FN (library, png_set_expand);
5474 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5475 LOAD_IMGLIB_FN (library, png_set_background);
5476 LOAD_IMGLIB_FN (library, png_get_bKGD);
5477 LOAD_IMGLIB_FN (library, png_read_update_info);
5478 LOAD_IMGLIB_FN (library, png_get_channels);
5479 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5480 LOAD_IMGLIB_FN (library, png_read_image);
5481 LOAD_IMGLIB_FN (library, png_read_end);
5482 LOAD_IMGLIB_FN (library, png_error);
5484 #if (PNG_LIBPNG_VER >= 10500)
5485 LOAD_IMGLIB_FN (library, png_longjmp);
5486 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5487 #endif /* libpng version >= 1.5 */
5489 return 1;
5491 #else
5493 #define fn_png_get_io_ptr png_get_io_ptr
5494 #define fn_png_sig_cmp png_sig_cmp
5495 #define fn_png_create_read_struct png_create_read_struct
5496 #define fn_png_create_info_struct png_create_info_struct
5497 #define fn_png_destroy_read_struct png_destroy_read_struct
5498 #define fn_png_set_read_fn png_set_read_fn
5499 #define fn_png_set_sig_bytes png_set_sig_bytes
5500 #define fn_png_read_info png_read_info
5501 #define fn_png_get_IHDR png_get_IHDR
5502 #define fn_png_get_valid png_get_valid
5503 #define fn_png_set_strip_16 png_set_strip_16
5504 #define fn_png_set_expand png_set_expand
5505 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5506 #define fn_png_set_background png_set_background
5507 #define fn_png_get_bKGD png_get_bKGD
5508 #define fn_png_read_update_info png_read_update_info
5509 #define fn_png_get_channels png_get_channels
5510 #define fn_png_get_rowbytes png_get_rowbytes
5511 #define fn_png_read_image png_read_image
5512 #define fn_png_read_end png_read_end
5513 #define fn_png_error png_error
5515 #if (PNG_LIBPNG_VER >= 10500)
5516 #define fn_png_longjmp png_longjmp
5517 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5518 #endif /* libpng version >= 1.5 */
5520 #endif /* HAVE_NTGUI */
5523 #if (PNG_LIBPNG_VER < 10500)
5524 #define PNG_LONGJMP(ptr) (longjmp ((ptr)->jmpbuf, 1))
5525 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5526 #else
5527 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5528 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5529 #define PNG_JMPBUF(ptr) \
5530 (*fn_png_set_longjmp_fn((ptr), longjmp, sizeof (jmp_buf)))
5531 #endif
5533 /* Error and warning handlers installed when the PNG library
5534 is initialized. */
5536 static void
5537 my_png_error (png_struct *png_ptr, const char *msg)
5539 xassert (png_ptr != NULL);
5540 /* Avoid compiler warning about deprecated direct access to
5541 png_ptr's fields in libpng versions 1.4.x. */
5542 image_error ("PNG error: %s", build_string (msg), Qnil);
5543 PNG_LONGJMP (png_ptr);
5547 static void
5548 my_png_warning (png_struct *png_ptr, const char *msg)
5550 xassert (png_ptr != NULL);
5551 image_error ("PNG warning: %s", build_string (msg), Qnil);
5554 /* Memory source for PNG decoding. */
5556 struct png_memory_storage
5558 unsigned char *bytes; /* The data */
5559 size_t len; /* How big is it? */
5560 int index; /* Where are we? */
5564 /* Function set as reader function when reading PNG image from memory.
5565 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5566 bytes from the input to DATA. */
5568 static void
5569 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5571 struct png_memory_storage *tbr
5572 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5574 if (length > tbr->len - tbr->index)
5575 fn_png_error (png_ptr, "Read error");
5577 memcpy (data, tbr->bytes + tbr->index, length);
5578 tbr->index = tbr->index + length;
5582 /* Function set as reader function when reading PNG image from a file.
5583 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5584 bytes from the input to DATA. */
5586 static void
5587 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5589 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5591 if (fread (data, 1, length, fp) < length)
5592 fn_png_error (png_ptr, "Read error");
5596 /* Load PNG image IMG for use on frame F. Value is non-zero if
5597 successful. */
5599 static int
5600 png_load (struct frame *f, struct image *img)
5602 Lisp_Object file, specified_file;
5603 Lisp_Object specified_data;
5604 int x, y, i;
5605 XImagePtr ximg, mask_img = NULL;
5606 png_struct *png_ptr = NULL;
5607 png_info *info_ptr = NULL, *end_info = NULL;
5608 FILE *volatile fp = NULL;
5609 png_byte sig[8];
5610 png_byte * volatile pixels = NULL;
5611 png_byte ** volatile rows = NULL;
5612 png_uint_32 width, height;
5613 int bit_depth, color_type, interlace_type;
5614 png_byte channels;
5615 png_uint_32 row_bytes;
5616 int transparent_p;
5617 struct png_memory_storage tbr; /* Data to be read */
5619 /* Find out what file to load. */
5620 specified_file = image_spec_value (img->spec, QCfile, NULL);
5621 specified_data = image_spec_value (img->spec, QCdata, NULL);
5623 if (NILP (specified_data))
5625 file = x_find_image_file (specified_file);
5626 if (!STRINGP (file))
5628 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5629 return 0;
5632 /* Open the image file. */
5633 fp = fopen (SSDATA (file), "rb");
5634 if (!fp)
5636 image_error ("Cannot open image file `%s'", file, Qnil);
5637 return 0;
5640 /* Check PNG signature. */
5641 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5642 || fn_png_sig_cmp (sig, 0, sizeof sig))
5644 image_error ("Not a PNG file: `%s'", file, Qnil);
5645 fclose (fp);
5646 return 0;
5649 else
5651 if (!STRINGP (specified_data))
5653 image_error ("Invalid image data `%s'", specified_data, Qnil);
5654 return 0;
5657 /* Read from memory. */
5658 tbr.bytes = SDATA (specified_data);
5659 tbr.len = SBYTES (specified_data);
5660 tbr.index = 0;
5662 /* Check PNG signature. */
5663 if (tbr.len < sizeof sig
5664 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5666 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5667 return 0;
5670 /* Need to skip past the signature. */
5671 tbr.bytes += sizeof (sig);
5674 /* Initialize read and info structs for PNG lib. */
5675 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5676 NULL, my_png_error,
5677 my_png_warning);
5678 if (!png_ptr)
5680 if (fp) fclose (fp);
5681 return 0;
5684 info_ptr = 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 end_info = fn_png_create_info_struct (png_ptr);
5693 if (!end_info)
5695 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5696 if (fp) fclose (fp);
5697 return 0;
5700 /* Set error jump-back. We come back here when the PNG library
5701 detects an error. */
5702 if (setjmp (PNG_JMPBUF (png_ptr)))
5704 error:
5705 if (png_ptr)
5706 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5707 xfree (pixels);
5708 xfree (rows);
5709 if (fp) fclose (fp);
5710 return 0;
5713 /* Read image info. */
5714 if (!NILP (specified_data))
5715 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5716 else
5717 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5719 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5720 fn_png_read_info (png_ptr, info_ptr);
5721 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5722 &interlace_type, NULL, NULL);
5724 if (!check_image_size (f, width, height))
5726 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5727 goto error;
5729 /* If image contains simply transparency data, we prefer to
5730 construct a clipping mask. */
5731 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5732 transparent_p = 1;
5733 else
5734 transparent_p = 0;
5736 /* This function is easier to write if we only have to handle
5737 one data format: RGB or RGBA with 8 bits per channel. Let's
5738 transform other formats into that format. */
5740 /* Strip more than 8 bits per channel. */
5741 if (bit_depth == 16)
5742 fn_png_set_strip_16 (png_ptr);
5744 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5745 if available. */
5746 fn_png_set_expand (png_ptr);
5748 /* Convert grayscale images to RGB. */
5749 if (color_type == PNG_COLOR_TYPE_GRAY
5750 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5751 fn_png_set_gray_to_rgb (png_ptr);
5753 /* Handle alpha channel by combining the image with a background
5754 color. Do this only if a real alpha channel is supplied. For
5755 simple transparency, we prefer a clipping mask. */
5756 if (!transparent_p)
5758 /* png_color_16 *image_bg; */
5759 Lisp_Object specified_bg
5760 = image_spec_value (img->spec, QCbackground, NULL);
5761 int shift = (bit_depth == 16) ? 0 : 8;
5763 if (STRINGP (specified_bg))
5764 /* The user specified `:background', use that. */
5766 XColor color;
5767 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
5769 png_color_16 user_bg;
5771 memset (&user_bg, 0, sizeof user_bg);
5772 user_bg.red = color.red >> shift;
5773 user_bg.green = color.green >> shift;
5774 user_bg.blue = color.blue >> shift;
5776 fn_png_set_background (png_ptr, &user_bg,
5777 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5780 else
5782 /* We use the current frame background, ignoring any default
5783 background color set by the image. */
5784 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5785 XColor color;
5786 png_color_16 frame_background;
5788 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5789 x_query_color (f, &color);
5791 memset (&frame_background, 0, sizeof frame_background);
5792 frame_background.red = color.red >> shift;
5793 frame_background.green = color.green >> shift;
5794 frame_background.blue = color.blue >> shift;
5795 #endif /* HAVE_X_WINDOWS */
5797 fn_png_set_background (png_ptr, &frame_background,
5798 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5802 /* Update info structure. */
5803 fn_png_read_update_info (png_ptr, info_ptr);
5805 /* Get number of channels. Valid values are 1 for grayscale images
5806 and images with a palette, 2 for grayscale images with transparency
5807 information (alpha channel), 3 for RGB images, and 4 for RGB
5808 images with alpha channel, i.e. RGBA. If conversions above were
5809 sufficient we should only have 3 or 4 channels here. */
5810 channels = fn_png_get_channels (png_ptr, info_ptr);
5811 xassert (channels == 3 || channels == 4);
5813 /* Number of bytes needed for one row of the image. */
5814 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5816 /* Allocate memory for the image. */
5817 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
5818 rows = (png_byte **) xmalloc (height * sizeof *rows);
5819 for (i = 0; i < height; ++i)
5820 rows[i] = pixels + i * row_bytes;
5822 /* Read the entire image. */
5823 fn_png_read_image (png_ptr, rows);
5824 fn_png_read_end (png_ptr, info_ptr);
5825 if (fp)
5827 fclose (fp);
5828 fp = NULL;
5831 /* Create the X image and pixmap. */
5832 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5833 &img->pixmap))
5834 goto error;
5836 /* Create an image and pixmap serving as mask if the PNG image
5837 contains an alpha channel. */
5838 if (channels == 4
5839 && !transparent_p
5840 && !x_create_x_image_and_pixmap (f, width, height, 1,
5841 &mask_img, &img->mask))
5843 x_destroy_x_image (ximg);
5844 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5845 img->pixmap = NO_PIXMAP;
5846 goto error;
5849 /* Fill the X image and mask from PNG data. */
5850 init_color_table ();
5852 for (y = 0; y < height; ++y)
5854 png_byte *p = rows[y];
5856 for (x = 0; x < width; ++x)
5858 unsigned r, g, b;
5860 r = *p++ << 8;
5861 g = *p++ << 8;
5862 b = *p++ << 8;
5863 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5864 /* An alpha channel, aka mask channel, associates variable
5865 transparency with an image. Where other image formats
5866 support binary transparency---fully transparent or fully
5867 opaque---PNG allows up to 254 levels of partial transparency.
5868 The PNG library implements partial transparency by combining
5869 the image with a specified background color.
5871 I'm not sure how to handle this here nicely: because the
5872 background on which the image is displayed may change, for
5873 real alpha channel support, it would be necessary to create
5874 a new image for each possible background.
5876 What I'm doing now is that a mask is created if we have
5877 boolean transparency information. Otherwise I'm using
5878 the frame's background color to combine the image with. */
5880 if (channels == 4)
5882 if (mask_img)
5883 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5884 ++p;
5889 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5890 /* Set IMG's background color from the PNG image, unless the user
5891 overrode it. */
5893 png_color_16 *bg;
5894 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5896 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5897 img->background_valid = 1;
5901 #ifdef COLOR_TABLE_SUPPORT
5902 /* Remember colors allocated for this image. */
5903 img->colors = colors_in_color_table (&img->ncolors);
5904 free_color_table ();
5905 #endif /* COLOR_TABLE_SUPPORT */
5907 /* Clean up. */
5908 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5909 xfree (rows);
5910 xfree (pixels);
5912 img->width = width;
5913 img->height = height;
5915 /* Maybe fill in the background field while we have ximg handy.
5916 Casting avoids a GCC warning. */
5917 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5919 /* Put the image into the pixmap, then free the X image and its buffer. */
5920 x_put_x_image (f, ximg, img->pixmap, width, height);
5921 x_destroy_x_image (ximg);
5923 /* Same for the mask. */
5924 if (mask_img)
5926 /* Fill in the background_transparent field while we have the
5927 mask handy. Casting avoids a GCC warning. */
5928 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
5930 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5931 x_destroy_x_image (mask_img);
5934 return 1;
5937 #else /* HAVE_PNG */
5939 #ifdef HAVE_NS
5940 static int
5941 png_load (struct frame *f, struct image *img)
5943 return ns_load_image(f, img,
5944 image_spec_value (img->spec, QCfile, NULL),
5945 image_spec_value (img->spec, QCdata, NULL));
5947 #endif /* HAVE_NS */
5950 #endif /* !HAVE_PNG */
5954 /***********************************************************************
5955 JPEG
5956 ***********************************************************************/
5958 #if defined (HAVE_JPEG) || defined (HAVE_NS)
5960 static int jpeg_image_p (Lisp_Object object);
5961 static int jpeg_load (struct frame *f, struct image *img);
5963 /* The symbol `jpeg' identifying images of this type. */
5965 Lisp_Object Qjpeg;
5967 /* Indices of image specification fields in gs_format, below. */
5969 enum jpeg_keyword_index
5971 JPEG_TYPE,
5972 JPEG_DATA,
5973 JPEG_FILE,
5974 JPEG_ASCENT,
5975 JPEG_MARGIN,
5976 JPEG_RELIEF,
5977 JPEG_ALGORITHM,
5978 JPEG_HEURISTIC_MASK,
5979 JPEG_MASK,
5980 JPEG_BACKGROUND,
5981 JPEG_LAST
5984 /* Vector of image_keyword structures describing the format
5985 of valid user-defined image specifications. */
5987 static const struct image_keyword jpeg_format[JPEG_LAST] =
5989 {":type", IMAGE_SYMBOL_VALUE, 1},
5990 {":data", IMAGE_STRING_VALUE, 0},
5991 {":file", IMAGE_STRING_VALUE, 0},
5992 {":ascent", IMAGE_ASCENT_VALUE, 0},
5993 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5994 {":relief", IMAGE_INTEGER_VALUE, 0},
5995 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5996 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5997 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5998 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6001 /* Structure describing the image type `jpeg'. */
6003 static struct image_type jpeg_type =
6005 &Qjpeg,
6006 jpeg_image_p,
6007 jpeg_load,
6008 x_clear_image,
6009 NULL
6012 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6014 static int
6015 jpeg_image_p (Lisp_Object object)
6017 struct image_keyword fmt[JPEG_LAST];
6019 memcpy (fmt, jpeg_format, sizeof fmt);
6021 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6022 return 0;
6024 /* Must specify either the :data or :file keyword. */
6025 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6028 #endif /* HAVE_JPEG || HAVE_NS */
6030 #ifdef HAVE_JPEG
6032 /* Work around a warning about HAVE_STDLIB_H being redefined in
6033 jconfig.h. */
6034 #ifdef HAVE_STDLIB_H
6035 #define HAVE_STDLIB_H_1
6036 #undef HAVE_STDLIB_H
6037 #endif /* HAVE_STLIB_H */
6039 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6040 /* In older releases of the jpeg library, jpeglib.h will define boolean
6041 differently depending on __WIN32__, so make sure it is defined. */
6042 #define __WIN32__ 1
6043 #endif
6045 #include <jpeglib.h>
6046 #include <jerror.h>
6048 #ifdef HAVE_STLIB_H_1
6049 #define HAVE_STDLIB_H 1
6050 #endif
6052 #ifdef HAVE_NTGUI
6054 /* JPEG library details. */
6055 DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6056 DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6057 DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6058 DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6059 DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6060 DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6061 DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6062 DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6064 static int
6065 init_jpeg_functions (Lisp_Object libraries)
6067 HMODULE library;
6069 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6070 return 0;
6072 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6073 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6074 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6075 LOAD_IMGLIB_FN (library, jpeg_read_header);
6076 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6077 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6078 LOAD_IMGLIB_FN (library, jpeg_std_error);
6079 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6080 return 1;
6083 /* Wrapper since we can't directly assign the function pointer
6084 to another function pointer that was declared more completely easily. */
6085 static boolean
6086 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6088 return fn_jpeg_resync_to_restart (cinfo, desired);
6091 #else
6093 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6094 #define fn_jpeg_start_decompress jpeg_start_decompress
6095 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6096 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6097 #define fn_jpeg_read_header jpeg_read_header
6098 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6099 #define fn_jpeg_std_error jpeg_std_error
6100 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6102 #endif /* HAVE_NTGUI */
6104 struct my_jpeg_error_mgr
6106 struct jpeg_error_mgr pub;
6107 jmp_buf setjmp_buffer;
6111 static void
6112 my_error_exit (j_common_ptr cinfo)
6114 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6115 longjmp (mgr->setjmp_buffer, 1);
6119 /* Init source method for JPEG data source manager. Called by
6120 jpeg_read_header() before any data is actually read. See
6121 libjpeg.doc from the JPEG lib distribution. */
6123 static void
6124 our_common_init_source (j_decompress_ptr cinfo)
6129 /* Method to terminate data source. Called by
6130 jpeg_finish_decompress() after all data has been processed. */
6132 static void
6133 our_common_term_source (j_decompress_ptr cinfo)
6138 /* Fill input buffer method for JPEG data source manager. Called
6139 whenever more data is needed. We read the whole image in one step,
6140 so this only adds a fake end of input marker at the end. */
6142 static JOCTET our_memory_buffer[2];
6144 static boolean
6145 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6147 /* Insert a fake EOI marker. */
6148 struct jpeg_source_mgr *src = cinfo->src;
6150 our_memory_buffer[0] = (JOCTET) 0xFF;
6151 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6153 src->next_input_byte = our_memory_buffer;
6154 src->bytes_in_buffer = 2;
6155 return 1;
6159 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6160 is the JPEG data source manager. */
6162 static void
6163 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6165 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6167 if (src)
6169 if (num_bytes > src->bytes_in_buffer)
6170 ERREXIT (cinfo, JERR_INPUT_EOF);
6172 src->bytes_in_buffer -= num_bytes;
6173 src->next_input_byte += num_bytes;
6178 /* Set up the JPEG lib for reading an image from DATA which contains
6179 LEN bytes. CINFO is the decompression info structure created for
6180 reading the image. */
6182 static void
6183 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, unsigned int len)
6185 struct jpeg_source_mgr *src;
6187 if (cinfo->src == NULL)
6189 /* First time for this JPEG object? */
6190 cinfo->src = (struct jpeg_source_mgr *)
6191 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6192 sizeof (struct jpeg_source_mgr));
6193 src = (struct jpeg_source_mgr *) cinfo->src;
6194 src->next_input_byte = data;
6197 src = (struct jpeg_source_mgr *) cinfo->src;
6198 src->init_source = our_common_init_source;
6199 src->fill_input_buffer = our_memory_fill_input_buffer;
6200 src->skip_input_data = our_memory_skip_input_data;
6201 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6202 src->term_source = our_common_term_source;
6203 src->bytes_in_buffer = len;
6204 src->next_input_byte = data;
6208 struct jpeg_stdio_mgr
6210 struct jpeg_source_mgr mgr;
6211 boolean finished;
6212 FILE *file;
6213 JOCTET *buffer;
6217 /* Size of buffer to read JPEG from file.
6218 Not too big, as we want to use alloc_small. */
6219 #define JPEG_STDIO_BUFFER_SIZE 8192
6222 /* Fill input buffer method for JPEG data source manager. Called
6223 whenever more data is needed. The data is read from a FILE *. */
6225 static boolean
6226 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6228 struct jpeg_stdio_mgr *src;
6230 src = (struct jpeg_stdio_mgr *) cinfo->src;
6231 if (!src->finished)
6233 size_t bytes;
6235 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6236 if (bytes > 0)
6237 src->mgr.bytes_in_buffer = bytes;
6238 else
6240 WARNMS (cinfo, JWRN_JPEG_EOF);
6241 src->finished = 1;
6242 src->buffer[0] = (JOCTET) 0xFF;
6243 src->buffer[1] = (JOCTET) JPEG_EOI;
6244 src->mgr.bytes_in_buffer = 2;
6246 src->mgr.next_input_byte = src->buffer;
6249 return 1;
6253 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6254 is the JPEG data source manager. */
6256 static void
6257 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6259 struct jpeg_stdio_mgr *src;
6260 src = (struct jpeg_stdio_mgr *) cinfo->src;
6262 while (num_bytes > 0 && !src->finished)
6264 if (num_bytes <= src->mgr.bytes_in_buffer)
6266 src->mgr.bytes_in_buffer -= num_bytes;
6267 src->mgr.next_input_byte += num_bytes;
6268 break;
6270 else
6272 num_bytes -= src->mgr.bytes_in_buffer;
6273 src->mgr.bytes_in_buffer = 0;
6274 src->mgr.next_input_byte = NULL;
6276 our_stdio_fill_input_buffer (cinfo);
6282 /* Set up the JPEG lib for reading an image from a FILE *.
6283 CINFO is the decompression info structure created for
6284 reading the image. */
6286 static void
6287 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6289 struct jpeg_stdio_mgr *src;
6291 if (cinfo->src != NULL)
6292 src = (struct jpeg_stdio_mgr *) cinfo->src;
6293 else
6295 /* First time for this JPEG object? */
6296 cinfo->src = (struct jpeg_source_mgr *)
6297 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6298 sizeof (struct jpeg_stdio_mgr));
6299 src = (struct jpeg_stdio_mgr *) cinfo->src;
6300 src->buffer = (JOCTET *)
6301 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6302 JPEG_STDIO_BUFFER_SIZE);
6305 src->file = fp;
6306 src->finished = 0;
6307 src->mgr.init_source = our_common_init_source;
6308 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6309 src->mgr.skip_input_data = our_stdio_skip_input_data;
6310 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6311 src->mgr.term_source = our_common_term_source;
6312 src->mgr.bytes_in_buffer = 0;
6313 src->mgr.next_input_byte = NULL;
6317 /* Load image IMG for use on frame F. Patterned after example.c
6318 from the JPEG lib. */
6320 static int
6321 jpeg_load (struct frame *f, struct image *img)
6323 struct jpeg_decompress_struct cinfo;
6324 struct my_jpeg_error_mgr mgr;
6325 Lisp_Object file, specified_file;
6326 Lisp_Object specified_data;
6327 FILE * volatile fp = NULL;
6328 JSAMPARRAY buffer;
6329 int row_stride, x, y;
6330 XImagePtr ximg = NULL;
6331 int rc;
6332 unsigned long *colors;
6333 int width, height;
6335 /* Open the JPEG file. */
6336 specified_file = image_spec_value (img->spec, QCfile, NULL);
6337 specified_data = image_spec_value (img->spec, QCdata, NULL);
6339 if (NILP (specified_data))
6341 file = x_find_image_file (specified_file);
6342 if (!STRINGP (file))
6344 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6345 return 0;
6348 fp = fopen (SSDATA (file), "rb");
6349 if (fp == NULL)
6351 image_error ("Cannot open `%s'", file, Qnil);
6352 return 0;
6355 else if (!STRINGP (specified_data))
6357 image_error ("Invalid image data `%s'", specified_data, Qnil);
6358 return 0;
6361 /* Customize libjpeg's error handling to call my_error_exit when an
6362 error is detected. This function will perform a longjmp. */
6363 cinfo.err = fn_jpeg_std_error (&mgr.pub);
6364 mgr.pub.error_exit = my_error_exit;
6366 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6368 if (rc == 1)
6370 /* Called from my_error_exit. Display a JPEG error. */
6371 char buffer[JMSG_LENGTH_MAX];
6372 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
6373 image_error ("Error reading JPEG image `%s': %s", img->spec,
6374 build_string (buffer));
6377 /* Close the input file and destroy the JPEG object. */
6378 if (fp)
6379 fclose ((FILE *) fp);
6380 fn_jpeg_destroy_decompress (&cinfo);
6382 /* If we already have an XImage, free that. */
6383 x_destroy_x_image (ximg);
6385 /* Free pixmap and colors. */
6386 x_clear_image (f, img);
6387 return 0;
6390 /* Create the JPEG decompression object. Let it read from fp.
6391 Read the JPEG image header. */
6392 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6394 if (NILP (specified_data))
6395 jpeg_file_src (&cinfo, (FILE *) fp);
6396 else
6397 jpeg_memory_src (&cinfo, SDATA (specified_data),
6398 SBYTES (specified_data));
6400 fn_jpeg_read_header (&cinfo, 1);
6402 /* Customize decompression so that color quantization will be used.
6403 Start decompression. */
6404 cinfo.quantize_colors = 1;
6405 fn_jpeg_start_decompress (&cinfo);
6406 width = img->width = cinfo.output_width;
6407 height = img->height = cinfo.output_height;
6409 if (!check_image_size (f, width, height))
6411 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6412 longjmp (mgr.setjmp_buffer, 2);
6415 /* Create X image and pixmap. */
6416 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6417 longjmp (mgr.setjmp_buffer, 2);
6419 /* Allocate colors. When color quantization is used,
6420 cinfo.actual_number_of_colors has been set with the number of
6421 colors generated, and cinfo.colormap is a two-dimensional array
6422 of color indices in the range 0..cinfo.actual_number_of_colors.
6423 No more than 255 colors will be generated. */
6425 int i, ir, ig, ib;
6427 if (cinfo.out_color_components > 2)
6428 ir = 0, ig = 1, ib = 2;
6429 else if (cinfo.out_color_components > 1)
6430 ir = 0, ig = 1, ib = 0;
6431 else
6432 ir = 0, ig = 0, ib = 0;
6434 /* Use the color table mechanism because it handles colors that
6435 cannot be allocated nicely. Such colors will be replaced with
6436 a default color, and we don't have to care about which colors
6437 can be freed safely, and which can't. */
6438 init_color_table ();
6439 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6440 * sizeof *colors);
6442 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6444 /* Multiply RGB values with 255 because X expects RGB values
6445 in the range 0..0xffff. */
6446 int r = cinfo.colormap[ir][i] << 8;
6447 int g = cinfo.colormap[ig][i] << 8;
6448 int b = cinfo.colormap[ib][i] << 8;
6449 colors[i] = lookup_rgb_color (f, r, g, b);
6452 #ifdef COLOR_TABLE_SUPPORT
6453 /* Remember those colors actually allocated. */
6454 img->colors = colors_in_color_table (&img->ncolors);
6455 free_color_table ();
6456 #endif /* COLOR_TABLE_SUPPORT */
6459 /* Read pixels. */
6460 row_stride = width * cinfo.output_components;
6461 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6462 row_stride, 1);
6463 for (y = 0; y < height; ++y)
6465 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6466 for (x = 0; x < cinfo.output_width; ++x)
6467 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6470 /* Clean up. */
6471 fn_jpeg_finish_decompress (&cinfo);
6472 fn_jpeg_destroy_decompress (&cinfo);
6473 if (fp)
6474 fclose ((FILE *) fp);
6476 /* Maybe fill in the background field while we have ximg handy. */
6477 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6478 /* Casting avoids a GCC warning. */
6479 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6481 /* Put the image into the pixmap. */
6482 x_put_x_image (f, ximg, img->pixmap, width, height);
6483 x_destroy_x_image (ximg);
6484 return 1;
6487 #else /* HAVE_JPEG */
6489 #ifdef HAVE_NS
6490 static int
6491 jpeg_load (struct frame *f, struct image *img)
6493 return ns_load_image (f, img,
6494 image_spec_value (img->spec, QCfile, NULL),
6495 image_spec_value (img->spec, QCdata, NULL));
6497 #endif /* HAVE_NS */
6499 #endif /* !HAVE_JPEG */
6503 /***********************************************************************
6504 TIFF
6505 ***********************************************************************/
6507 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6509 static int tiff_image_p (Lisp_Object object);
6510 static int tiff_load (struct frame *f, struct image *img);
6512 /* The symbol `tiff' identifying images of this type. */
6514 Lisp_Object Qtiff;
6516 /* Indices of image specification fields in tiff_format, below. */
6518 enum tiff_keyword_index
6520 TIFF_TYPE,
6521 TIFF_DATA,
6522 TIFF_FILE,
6523 TIFF_ASCENT,
6524 TIFF_MARGIN,
6525 TIFF_RELIEF,
6526 TIFF_ALGORITHM,
6527 TIFF_HEURISTIC_MASK,
6528 TIFF_MASK,
6529 TIFF_BACKGROUND,
6530 TIFF_INDEX,
6531 TIFF_LAST
6534 /* Vector of image_keyword structures describing the format
6535 of valid user-defined image specifications. */
6537 static const struct image_keyword tiff_format[TIFF_LAST] =
6539 {":type", IMAGE_SYMBOL_VALUE, 1},
6540 {":data", IMAGE_STRING_VALUE, 0},
6541 {":file", IMAGE_STRING_VALUE, 0},
6542 {":ascent", IMAGE_ASCENT_VALUE, 0},
6543 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6544 {":relief", IMAGE_INTEGER_VALUE, 0},
6545 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6546 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6547 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6548 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6549 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6552 /* Structure describing the image type `tiff'. */
6554 static struct image_type tiff_type =
6556 &Qtiff,
6557 tiff_image_p,
6558 tiff_load,
6559 x_clear_image,
6560 NULL
6563 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6565 static int
6566 tiff_image_p (Lisp_Object object)
6568 struct image_keyword fmt[TIFF_LAST];
6569 memcpy (fmt, tiff_format, sizeof fmt);
6571 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6572 return 0;
6574 /* Must specify either the :data or :file keyword. */
6575 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6578 #endif /* HAVE_TIFF || HAVE_NS */
6580 #ifdef HAVE_TIFF
6582 #include <tiffio.h>
6584 #ifdef HAVE_NTGUI
6586 /* TIFF library details. */
6587 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6588 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6589 DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6590 DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
6591 TIFFReadWriteProc, TIFFReadWriteProc,
6592 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6593 TIFFMapFileProc, TIFFUnmapFileProc));
6594 DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6595 DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6596 DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6597 DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6599 static int
6600 init_tiff_functions (Lisp_Object libraries)
6602 HMODULE library;
6604 if (!(library = w32_delayed_load (libraries, Qtiff)))
6605 return 0;
6607 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6608 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6609 LOAD_IMGLIB_FN (library, TIFFOpen);
6610 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6611 LOAD_IMGLIB_FN (library, TIFFGetField);
6612 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6613 LOAD_IMGLIB_FN (library, TIFFClose);
6614 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6615 return 1;
6618 #else
6620 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6621 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6622 #define fn_TIFFOpen TIFFOpen
6623 #define fn_TIFFClientOpen TIFFClientOpen
6624 #define fn_TIFFGetField TIFFGetField
6625 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6626 #define fn_TIFFClose TIFFClose
6627 #define fn_TIFFSetDirectory TIFFSetDirectory
6628 #endif /* HAVE_NTGUI */
6631 /* Reading from a memory buffer for TIFF images Based on the PNG
6632 memory source, but we have to provide a lot of extra functions.
6633 Blah.
6635 We really only need to implement read and seek, but I am not
6636 convinced that the TIFF library is smart enough not to destroy
6637 itself if we only hand it the function pointers we need to
6638 override. */
6640 typedef struct
6642 unsigned char *bytes;
6643 size_t len;
6644 int index;
6646 tiff_memory_source;
6648 static size_t
6649 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6651 tiff_memory_source *src = (tiff_memory_source *) data;
6653 if (size > src->len - src->index)
6654 return (size_t) -1;
6655 memcpy (buf, src->bytes + src->index, size);
6656 src->index += size;
6657 return size;
6660 static size_t
6661 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6663 return (size_t) -1;
6666 static toff_t
6667 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6669 tiff_memory_source *src = (tiff_memory_source *) data;
6670 int idx;
6672 switch (whence)
6674 case SEEK_SET: /* Go from beginning of source. */
6675 idx = off;
6676 break;
6678 case SEEK_END: /* Go from end of source. */
6679 idx = src->len + off;
6680 break;
6682 case SEEK_CUR: /* Go from current position. */
6683 idx = src->index + off;
6684 break;
6686 default: /* Invalid `whence'. */
6687 return -1;
6690 if (idx > src->len || idx < 0)
6691 return -1;
6693 src->index = idx;
6694 return src->index;
6697 static int
6698 tiff_close_memory (thandle_t data)
6700 /* NOOP */
6701 return 0;
6704 static int
6705 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6707 /* It is already _IN_ memory. */
6708 return 0;
6711 static void
6712 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6714 /* We don't need to do this. */
6717 static toff_t
6718 tiff_size_of_memory (thandle_t data)
6720 return ((tiff_memory_source *) data)->len;
6724 static void
6725 tiff_error_handler (const char *title, const char *format, va_list ap)
6727 char buf[512];
6728 int len;
6730 len = sprintf (buf, "TIFF error: %s ", title);
6731 vsprintf (buf + len, format, ap);
6732 add_to_log (buf, Qnil, Qnil);
6736 static void
6737 tiff_warning_handler (const char *title, const char *format, va_list ap)
6739 char buf[512];
6740 int len;
6742 len = sprintf (buf, "TIFF warning: %s ", title);
6743 vsprintf (buf + len, format, ap);
6744 add_to_log (buf, Qnil, Qnil);
6748 /* Load TIFF image IMG for use on frame F. Value is non-zero if
6749 successful. */
6751 static int
6752 tiff_load (struct frame *f, struct image *img)
6754 Lisp_Object file, specified_file;
6755 Lisp_Object specified_data;
6756 TIFF *tiff;
6757 int width, height, x, y, count;
6758 uint32 *buf;
6759 int rc, rc2;
6760 XImagePtr ximg;
6761 tiff_memory_source memsrc;
6762 Lisp_Object image;
6764 specified_file = image_spec_value (img->spec, QCfile, NULL);
6765 specified_data = image_spec_value (img->spec, QCdata, NULL);
6767 fn_TIFFSetErrorHandler (tiff_error_handler);
6768 fn_TIFFSetWarningHandler (tiff_warning_handler);
6770 if (NILP (specified_data))
6772 /* Read from a file */
6773 file = x_find_image_file (specified_file);
6774 if (!STRINGP (file))
6776 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6777 return 0;
6780 /* Try to open the image file. */
6781 tiff = fn_TIFFOpen (SDATA (file), "r");
6782 if (tiff == NULL)
6784 image_error ("Cannot open `%s'", file, Qnil);
6785 return 0;
6788 else
6790 if (!STRINGP (specified_data))
6792 image_error ("Invalid image data `%s'", specified_data, Qnil);
6793 return 0;
6796 /* Memory source! */
6797 memsrc.bytes = SDATA (specified_data);
6798 memsrc.len = SBYTES (specified_data);
6799 memsrc.index = 0;
6801 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
6802 (TIFFReadWriteProc) tiff_read_from_memory,
6803 (TIFFReadWriteProc) tiff_write_from_memory,
6804 tiff_seek_in_memory,
6805 tiff_close_memory,
6806 tiff_size_of_memory,
6807 tiff_mmap_memory,
6808 tiff_unmap_memory);
6810 if (!tiff)
6812 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6813 return 0;
6817 image = image_spec_value (img->spec, QCindex, NULL);
6818 if (INTEGERP (image))
6820 int ino = XFASTINT (image);
6821 if (!fn_TIFFSetDirectory (tiff, ino))
6823 image_error ("Invalid image number `%s' in image `%s'",
6824 image, img->spec);
6825 fn_TIFFClose (tiff);
6826 return 0;
6830 /* Get width and height of the image, and allocate a raster buffer
6831 of width x height 32-bit values. */
6832 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6833 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6835 if (!check_image_size (f, width, height))
6837 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6838 fn_TIFFClose (tiff);
6839 return 0;
6842 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
6844 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
6846 /* Count the number of images in the file. */
6847 for (count = 1, rc2 = 1; rc2; count++)
6848 rc2 = fn_TIFFSetDirectory (tiff, count);
6850 if (count > 1)
6851 img->data.lisp_val = Fcons (Qcount,
6852 Fcons (make_number (count),
6853 img->data.lisp_val));
6855 fn_TIFFClose (tiff);
6856 if (!rc)
6858 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6859 xfree (buf);
6860 return 0;
6863 /* Create the X image and pixmap. */
6864 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6866 xfree (buf);
6867 return 0;
6870 /* Initialize the color table. */
6871 init_color_table ();
6873 /* Process the pixel raster. Origin is in the lower-left corner. */
6874 for (y = 0; y < height; ++y)
6876 uint32 *row = buf + y * width;
6878 for (x = 0; x < width; ++x)
6880 uint32 abgr = row[x];
6881 int r = TIFFGetR (abgr) << 8;
6882 int g = TIFFGetG (abgr) << 8;
6883 int b = TIFFGetB (abgr) << 8;
6884 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6888 #ifdef COLOR_TABLE_SUPPORT
6889 /* Remember the colors allocated for the image. Free the color table. */
6890 img->colors = colors_in_color_table (&img->ncolors);
6891 free_color_table ();
6892 #endif /* COLOR_TABLE_SUPPORT */
6894 img->width = width;
6895 img->height = height;
6897 /* Maybe fill in the background field while we have ximg handy. */
6898 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6899 /* Casting avoids a GCC warning on W32. */
6900 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6902 /* Put the image into the pixmap, then free the X image and its buffer. */
6903 x_put_x_image (f, ximg, img->pixmap, width, height);
6904 x_destroy_x_image (ximg);
6905 xfree (buf);
6907 return 1;
6910 #else /* HAVE_TIFF */
6912 #ifdef HAVE_NS
6913 static int
6914 tiff_load (struct frame *f, struct image *img)
6916 return ns_load_image (f, img,
6917 image_spec_value (img->spec, QCfile, NULL),
6918 image_spec_value (img->spec, QCdata, NULL));
6920 #endif /* HAVE_NS */
6922 #endif /* !HAVE_TIFF */
6926 /***********************************************************************
6928 ***********************************************************************/
6930 #if defined (HAVE_GIF) || defined (HAVE_NS)
6932 static int gif_image_p (Lisp_Object object);
6933 static int gif_load (struct frame *f, struct image *img);
6934 static void gif_clear_image (struct frame *f, struct image *img);
6936 /* The symbol `gif' identifying images of this type. */
6938 Lisp_Object Qgif;
6940 /* Indices of image specification fields in gif_format, below. */
6942 enum gif_keyword_index
6944 GIF_TYPE,
6945 GIF_DATA,
6946 GIF_FILE,
6947 GIF_ASCENT,
6948 GIF_MARGIN,
6949 GIF_RELIEF,
6950 GIF_ALGORITHM,
6951 GIF_HEURISTIC_MASK,
6952 GIF_MASK,
6953 GIF_IMAGE,
6954 GIF_BACKGROUND,
6955 GIF_LAST
6958 /* Vector of image_keyword structures describing the format
6959 of valid user-defined image specifications. */
6961 static const struct image_keyword gif_format[GIF_LAST] =
6963 {":type", IMAGE_SYMBOL_VALUE, 1},
6964 {":data", IMAGE_STRING_VALUE, 0},
6965 {":file", IMAGE_STRING_VALUE, 0},
6966 {":ascent", IMAGE_ASCENT_VALUE, 0},
6967 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6968 {":relief", IMAGE_INTEGER_VALUE, 0},
6969 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6970 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6971 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6972 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
6973 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6976 /* Structure describing the image type `gif'. */
6978 static struct image_type gif_type =
6980 &Qgif,
6981 gif_image_p,
6982 gif_load,
6983 gif_clear_image,
6984 NULL
6987 /* Free X resources of GIF image IMG which is used on frame F. */
6989 static void
6990 gif_clear_image (struct frame *f, struct image *img)
6992 /* IMG->data.ptr_val may contain metadata with extension data. */
6993 img->data.lisp_val = Qnil;
6994 x_clear_image (f, img);
6997 /* Return non-zero if OBJECT is a valid GIF image specification. */
6999 static int
7000 gif_image_p (Lisp_Object object)
7002 struct image_keyword fmt[GIF_LAST];
7003 memcpy (fmt, gif_format, sizeof fmt);
7005 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7006 return 0;
7008 /* Must specify either the :data or :file keyword. */
7009 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7012 #endif /* HAVE_GIF */
7014 #ifdef HAVE_GIF
7016 #if defined (HAVE_NTGUI)
7017 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7018 Undefine before redefining to avoid a preprocessor warning. */
7019 #ifdef DrawText
7020 #undef DrawText
7021 #endif
7022 /* avoid conflict with QuickdrawText.h */
7023 #define DrawText gif_DrawText
7024 #include <gif_lib.h>
7025 #undef DrawText
7027 #else /* HAVE_NTGUI */
7029 #include <gif_lib.h>
7031 #endif /* HAVE_NTGUI */
7034 #ifdef HAVE_NTGUI
7036 /* GIF library details. */
7037 DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7038 DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7039 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7040 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
7042 static int
7043 init_gif_functions (Lisp_Object libraries)
7045 HMODULE library;
7047 if (!(library = w32_delayed_load (libraries, Qgif)))
7048 return 0;
7050 LOAD_IMGLIB_FN (library, DGifCloseFile);
7051 LOAD_IMGLIB_FN (library, DGifSlurp);
7052 LOAD_IMGLIB_FN (library, DGifOpen);
7053 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7054 return 1;
7057 #else
7059 #define fn_DGifCloseFile DGifCloseFile
7060 #define fn_DGifSlurp DGifSlurp
7061 #define fn_DGifOpen DGifOpen
7062 #define fn_DGifOpenFileName DGifOpenFileName
7064 #endif /* HAVE_NTGUI */
7066 /* Reading a GIF image from memory
7067 Based on the PNG memory stuff to a certain extent. */
7069 typedef struct
7071 unsigned char *bytes;
7072 size_t len;
7073 int index;
7075 gif_memory_source;
7077 /* Make the current memory source available to gif_read_from_memory.
7078 It's done this way because not all versions of libungif support
7079 a UserData field in the GifFileType structure. */
7080 static gif_memory_source *current_gif_memory_src;
7082 static int
7083 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7085 gif_memory_source *src = current_gif_memory_src;
7087 if (len > src->len - src->index)
7088 return -1;
7090 memcpy (buf, src->bytes + src->index, len);
7091 src->index += len;
7092 return len;
7096 /* Load GIF image IMG for use on frame F. Value is non-zero if
7097 successful. */
7099 static const int interlace_start[] = {0, 4, 2, 1};
7100 static const int interlace_increment[] = {8, 8, 4, 2};
7102 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7104 static int
7105 gif_load (struct frame *f, struct image *img)
7107 Lisp_Object file, specified_file;
7108 Lisp_Object specified_data;
7109 int rc, width, height, x, y, i;
7110 boolean transparent_p;
7111 XImagePtr ximg;
7112 ColorMapObject *gif_color_map;
7113 unsigned long pixel_colors[256];
7114 GifFileType *gif;
7115 Lisp_Object image;
7116 int ino, image_height, image_width;
7117 gif_memory_source memsrc;
7118 unsigned char *raster;
7119 unsigned int transparency_color_index;
7121 specified_file = image_spec_value (img->spec, QCfile, NULL);
7122 specified_data = image_spec_value (img->spec, QCdata, NULL);
7124 if (NILP (specified_data))
7126 file = x_find_image_file (specified_file);
7127 if (!STRINGP (file))
7129 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7130 return 0;
7133 /* Open the GIF file. */
7134 gif = fn_DGifOpenFileName (SDATA (file));
7135 if (gif == NULL)
7137 image_error ("Cannot open `%s'", file, Qnil);
7138 return 0;
7141 else
7143 if (!STRINGP (specified_data))
7145 image_error ("Invalid image data `%s'", specified_data, Qnil);
7146 return 0;
7149 /* Read from memory! */
7150 current_gif_memory_src = &memsrc;
7151 memsrc.bytes = SDATA (specified_data);
7152 memsrc.len = SBYTES (specified_data);
7153 memsrc.index = 0;
7155 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
7156 if (!gif)
7158 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7159 return 0;
7163 /* Before reading entire contents, check the declared image size. */
7164 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7166 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7167 fn_DGifCloseFile (gif);
7168 return 0;
7171 /* Read entire contents. */
7172 rc = fn_DGifSlurp (gif);
7173 if (rc == GIF_ERROR)
7175 image_error ("Error reading `%s'", img->spec, Qnil);
7176 fn_DGifCloseFile (gif);
7177 return 0;
7180 image = image_spec_value (img->spec, QCindex, NULL);
7181 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7182 if (ino >= gif->ImageCount)
7184 image_error ("Invalid image number `%s' in image `%s'",
7185 image, img->spec);
7186 fn_DGifCloseFile (gif);
7187 return 0;
7190 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++)
7191 if ((gif->SavedImages[ino].ExtensionBlocks[i].Function
7192 == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7193 && gif->SavedImages[ino].ExtensionBlocks[i].ByteCount == 4
7194 /* Transparency enabled? */
7195 && gif->SavedImages[ino].ExtensionBlocks[i].Bytes[0] & 1)
7197 transparent_p = 1;
7198 transparency_color_index
7199 = (unsigned char) gif->SavedImages[ino].ExtensionBlocks[i].Bytes[3];
7202 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
7203 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
7204 image_height = gif->SavedImages[ino].ImageDesc.Height;
7205 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
7206 image_width = gif->SavedImages[ino].ImageDesc.Width;
7207 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
7209 width = img->width = max (gif->SWidth,
7210 max (gif->Image.Left + gif->Image.Width,
7211 img->corners[RIGHT_CORNER]));
7212 height = img->height = max (gif->SHeight,
7213 max (gif->Image.Top + gif->Image.Height,
7214 img->corners[BOT_CORNER]));
7216 if (!check_image_size (f, width, height))
7218 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7219 fn_DGifCloseFile (gif);
7220 return 0;
7223 /* Create the X image and pixmap. */
7224 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7226 fn_DGifCloseFile (gif);
7227 return 0;
7230 /* Allocate colors. */
7231 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7232 if (!gif_color_map)
7233 gif_color_map = gif->SColorMap;
7234 init_color_table ();
7235 memset (pixel_colors, 0, sizeof pixel_colors);
7237 if (gif_color_map)
7238 for (i = 0; i < gif_color_map->ColorCount; ++i)
7240 if (transparent_p && transparency_color_index == i)
7242 Lisp_Object specified_bg
7243 = image_spec_value (img->spec, QCbackground, NULL);
7244 pixel_colors[i] = STRINGP (specified_bg)
7245 ? x_alloc_image_color (f, img, specified_bg,
7246 FRAME_BACKGROUND_PIXEL (f))
7247 : FRAME_BACKGROUND_PIXEL (f);
7249 else
7251 int r = gif_color_map->Colors[i].Red << 8;
7252 int g = gif_color_map->Colors[i].Green << 8;
7253 int b = gif_color_map->Colors[i].Blue << 8;
7254 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7258 #ifdef COLOR_TABLE_SUPPORT
7259 img->colors = colors_in_color_table (&img->ncolors);
7260 free_color_table ();
7261 #endif /* COLOR_TABLE_SUPPORT */
7263 /* Clear the part of the screen image that are not covered by
7264 the image from the GIF file. Full animated GIF support
7265 requires more than can be done here (see the gif89 spec,
7266 disposal methods). Let's simply assume that the part
7267 not covered by a sub-image is in the frame's background color. */
7268 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7269 for (x = 0; x < width; ++x)
7270 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7272 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7273 for (x = 0; x < width; ++x)
7274 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7276 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7278 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7279 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7280 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7281 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7284 /* Read the GIF image into the X image. We use a local variable
7285 `raster' here because RasterBits below is a char *, and invites
7286 problems with bytes >= 0x80. */
7287 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7289 if (gif->SavedImages[ino].ImageDesc.Interlace)
7291 int pass;
7292 int row = interlace_start[0];
7294 pass = 0;
7296 for (y = 0; y < image_height; y++)
7298 if (row >= image_height)
7300 row = interlace_start[++pass];
7301 while (row >= image_height)
7302 row = interlace_start[++pass];
7305 for (x = 0; x < image_width; x++)
7307 int i = raster[(y * image_width) + x];
7308 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7309 row + img->corners[TOP_CORNER], pixel_colors[i]);
7312 row += interlace_increment[pass];
7315 else
7317 for (y = 0; y < image_height; ++y)
7318 for (x = 0; x < image_width; ++x)
7320 int i = raster[y * image_width + x];
7321 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7322 y + img->corners[TOP_CORNER], pixel_colors[i]);
7326 /* Save GIF image extension data for `image-metadata'.
7327 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7328 img->data.lisp_val = Qnil;
7329 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
7331 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
7332 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
7333 /* Append (... FUNCTION "BYTES") */
7334 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7335 Fcons (make_number (ext->Function),
7336 img->data.lisp_val));
7337 img->data.lisp_val = Fcons (Qextension_data,
7338 Fcons (Fnreverse (img->data.lisp_val),
7339 Qnil));
7341 if (gif->ImageCount > 1)
7342 img->data.lisp_val = Fcons (Qcount,
7343 Fcons (make_number (gif->ImageCount),
7344 img->data.lisp_val));
7346 fn_DGifCloseFile (gif);
7348 /* Maybe fill in the background field while we have ximg handy. */
7349 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7350 /* Casting avoids a GCC warning. */
7351 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7353 /* Put the image into the pixmap, then free the X image and its buffer. */
7354 x_put_x_image (f, ximg, img->pixmap, width, height);
7355 x_destroy_x_image (ximg);
7357 return 1;
7360 #else /* !HAVE_GIF */
7362 #ifdef HAVE_NS
7363 static int
7364 gif_load (struct frame *f, struct image *img)
7366 return ns_load_image (f, img,
7367 image_spec_value (img->spec, QCfile, NULL),
7368 image_spec_value (img->spec, QCdata, NULL));
7370 #endif /* HAVE_NS */
7372 #endif /* HAVE_GIF */
7375 /***********************************************************************
7376 imagemagick
7377 ***********************************************************************/
7378 #if defined (HAVE_IMAGEMAGICK)
7380 /* The symbol `imagemagick' identifying images of this type. */
7382 Lisp_Object Qimagemagick;
7383 /* Indices of image specification fields in imagemagick_format, below. */
7385 enum imagemagick_keyword_index
7387 IMAGEMAGICK_TYPE,
7388 IMAGEMAGICK_DATA,
7389 IMAGEMAGICK_FILE,
7390 IMAGEMAGICK_ASCENT,
7391 IMAGEMAGICK_MARGIN,
7392 IMAGEMAGICK_RELIEF,
7393 IMAGEMAGICK_ALGORITHM,
7394 IMAGEMAGICK_HEURISTIC_MASK,
7395 IMAGEMAGICK_MASK,
7396 IMAGEMAGICK_BACKGROUND,
7397 IMAGEMAGICK_HEIGHT,
7398 IMAGEMAGICK_WIDTH,
7399 IMAGEMAGICK_ROTATION,
7400 IMAGEMAGICK_CROP,
7401 IMAGEMAGICK_LAST
7404 /* Vector of image_keyword structures describing the format
7405 of valid user-defined image specifications. */
7407 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7409 {":type", IMAGE_SYMBOL_VALUE, 1},
7410 {":data", IMAGE_STRING_VALUE, 0},
7411 {":file", IMAGE_STRING_VALUE, 0},
7412 {":ascent", IMAGE_ASCENT_VALUE, 0},
7413 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7414 {":relief", IMAGE_INTEGER_VALUE, 0},
7415 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7416 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7417 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7418 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7419 {":height", IMAGE_INTEGER_VALUE, 0},
7420 {":width", IMAGE_INTEGER_VALUE, 0},
7421 {":rotation", IMAGE_NUMBER_VALUE, 0},
7422 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7424 /* Free X resources of imagemagick image IMG which is used on frame F. */
7426 static void
7427 imagemagick_clear_image (struct frame *f,
7428 struct image *img)
7430 x_clear_image (f, img);
7435 /* Return non-zero if OBJECT is a valid IMAGEMAGICK image specification. Do
7436 this by calling parse_image_spec and supplying the keywords that
7437 identify the IMAGEMAGICK format. */
7439 static int
7440 imagemagick_image_p (Lisp_Object object)
7442 struct image_keyword fmt[IMAGEMAGICK_LAST];
7443 memcpy (fmt, imagemagick_format, sizeof fmt);
7445 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7446 return 0;
7448 /* Must specify either the :data or :file keyword. */
7449 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7452 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7453 Therefore rename the function so it doesnt collide with ImageMagick. */
7454 #define DrawRectangle DrawRectangleGif
7455 #include <wand/MagickWand.h>
7457 /* imagemagick_load_image is a helper function for imagemagick_load,
7458 which does the actual loading given contents and size, apart from
7459 frame and image structures, passed from imagemagick_load.
7461 Uses librimagemagick to do most of the image processing.
7463 non-zero when successful.
7466 static int
7467 imagemagick_load_image (/* Pointer to emacs frame structure. */
7468 struct frame *f,
7469 /* Pointer to emacs image structure. */
7470 struct image *img,
7471 /* String containing the IMAGEMAGICK data to
7472 be parsed. */
7473 unsigned char *contents,
7474 /* Size of data in bytes. */
7475 unsigned int size,
7476 /* Filename, either pass filename or
7477 contents/size. */
7478 unsigned char *filename)
7480 unsigned long width;
7481 unsigned long height;
7483 MagickBooleanType
7484 status;
7486 XImagePtr ximg;
7487 Lisp_Object specified_bg;
7488 XColor background;
7489 int x;
7490 int y;
7492 MagickWand *image_wand;
7493 MagickWand *ping_wand;
7494 PixelIterator *iterator;
7495 PixelWand **pixels;
7496 MagickPixelPacket pixel;
7497 Lisp_Object image;
7498 Lisp_Object value;
7499 Lisp_Object crop, geometry;
7500 long ino;
7501 int desired_width, desired_height;
7502 double rotation;
7503 int imagemagick_rendermethod;
7504 int pixelwidth;
7505 ImageInfo *image_info;
7506 ExceptionInfo *exception;
7507 Image * im_image;
7510 /* Handle image index for image types who can contain more than one
7511 image. Interface :index is same as for GIF. First we "ping" the
7512 image to see how many sub-images it contains. Pinging is faster
7513 than loading the image to find out things about it. */
7515 /* `MagickWandGenesis' initializes the imagemagick environment. */
7516 MagickWandGenesis ();
7517 image = image_spec_value (img->spec, QCindex, NULL);
7518 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7519 ping_wand = NewMagickWand ();
7520 MagickSetResolution (ping_wand, 2, 2);
7521 if (filename != NULL)
7523 status = MagickPingImage (ping_wand, filename);
7525 else
7527 status = MagickPingImageBlob (ping_wand, contents, size);
7530 if (ino >= MagickGetNumberImages (ping_wand))
7532 image_error ("Invalid image number `%s' in image `%s'",
7533 image, img->spec);
7534 DestroyMagickWand (ping_wand);
7535 return 0;
7538 if (MagickGetNumberImages(ping_wand) > 1)
7539 img->data.lisp_val =
7540 Fcons (Qcount,
7541 Fcons (make_number (MagickGetNumberImages (ping_wand)),
7542 img->data.lisp_val));
7544 DestroyMagickWand (ping_wand);
7546 /* Now, after pinging, we know how many images are inside the
7547 file. If its not a bundle, just one. */
7549 if (filename != NULL)
7551 image_info = CloneImageInfo ((ImageInfo *) NULL);
7552 (void) strcpy (image_info->filename, filename);
7553 image_info->number_scenes = 1;
7554 image_info->scene = ino;
7555 exception = AcquireExceptionInfo ();
7557 im_image = ReadImage (image_info, exception);
7558 DestroyExceptionInfo (exception);
7560 if (im_image != NULL)
7562 image_wand = NewMagickWandFromImage (im_image);
7563 DestroyImage(im_image);
7564 status = MagickTrue;
7566 else
7567 status = MagickFalse;
7569 else
7571 image_wand = NewMagickWand ();
7572 status = MagickReadImageBlob (image_wand, contents, size);
7575 if (status == MagickFalse) goto imagemagick_error;
7577 /* If width and/or height is set in the display spec assume we want
7578 to scale to those values. if either h or w is unspecified, the
7579 unspecified should be calculated from the specified to preserve
7580 aspect ratio. */
7582 value = image_spec_value (img->spec, QCwidth, NULL);
7583 desired_width = (INTEGERP (value) ? XFASTINT (value) : -1);
7584 value = image_spec_value (img->spec, QCheight, NULL);
7585 desired_height = (INTEGERP (value) ? XFASTINT (value) : -1);
7587 height = MagickGetImageHeight (image_wand);
7588 width = MagickGetImageWidth (image_wand);
7590 if(desired_width != -1 && desired_height == -1)
7592 /* w known, calculate h. */
7593 desired_height = (double) desired_width / width * height;
7595 if(desired_width == -1 && desired_height != -1)
7597 /* h known, calculate w. */
7598 desired_width = (double) desired_height / height * width;
7600 if(desired_width != -1 && desired_height != -1)
7602 status = MagickScaleImage (image_wand, desired_width, desired_height);
7603 if (status == MagickFalse)
7605 image_error ("Imagemagick scale failed", Qnil, Qnil);
7606 goto imagemagick_error;
7611 /* crop behaves similar to image slicing in Emacs but is more memory
7612 efficient. */
7613 crop = image_spec_value (img->spec, QCcrop, NULL);
7615 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7617 /* After some testing, it seems MagickCropImage is the fastest
7618 crop function in ImageMagick. This crop function seems to do
7619 less copying than the alternatives, but it still reads the
7620 entire image into memory before croping, which is aparently
7621 difficult to avoid when using imagemagick. */
7623 int w, h, x, y;
7624 w = XFASTINT (XCAR (crop));
7625 crop = XCDR (crop);
7626 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7628 h = XFASTINT (XCAR (crop));
7629 crop = XCDR (crop);
7630 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7632 x = XFASTINT (XCAR (crop));
7633 crop = XCDR (crop);
7634 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7636 y = XFASTINT (XCAR (crop));
7637 MagickCropImage (image_wand, w, h, x, y);
7643 /* Furthermore :rotation. we need background color and angle for
7644 rotation. */
7646 TODO background handling for rotation specified_bg =
7647 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
7648 (specified_bg). */
7649 value = image_spec_value (img->spec, QCrotation, NULL);
7650 if (FLOATP (value))
7652 PixelWand* background = NewPixelWand ();
7653 PixelSetColor (background, "#ffffff");/*TODO remove hardcode*/
7655 rotation = extract_float (value);
7657 status = MagickRotateImage (image_wand, background, rotation);
7658 DestroyPixelWand (background);
7659 if (status == MagickFalse)
7661 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
7662 goto imagemagick_error;
7666 /* Finaly we are done manipulating the image, figure out resulting
7667 width, height, and then transfer ownerwship to Emacs. */
7668 height = MagickGetImageHeight (image_wand);
7669 width = MagickGetImageWidth (image_wand);
7671 if (! check_image_size (f, width, height))
7673 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7674 goto imagemagick_error;
7677 /* We can now get a valid pixel buffer from the imagemagick file, if all
7678 went ok. */
7680 init_color_table ();
7681 imagemagick_rendermethod = (INTEGERP (Vimagemagick_render_type)
7682 ? XFASTINT (Vimagemagick_render_type) : 0);
7683 if (imagemagick_rendermethod == 0)
7685 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7686 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7687 &ximg, &img->pixmap))
7689 #ifdef COLOR_TABLE_SUPPORT
7690 free_color_table ();
7691 #endif
7692 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7693 goto imagemagick_error;
7696 /* Copy imagegmagick image to x with primitive yet robust pixel
7697 pusher loop. This has been tested a lot with many different
7698 images. */
7700 /* Copy pixels from the imagemagick image structure to the x image map. */
7701 iterator = NewPixelIterator (image_wand);
7702 if (iterator == (PixelIterator *) NULL)
7704 #ifdef COLOR_TABLE_SUPPORT
7705 free_color_table ();
7706 #endif
7707 x_destroy_x_image (ximg);
7708 image_error ("Imagemagick pixel iterator creation failed",
7709 Qnil, Qnil);
7710 goto imagemagick_error;
7713 for (y = 0; y < (long) MagickGetImageHeight (image_wand); y++)
7715 pixels = PixelGetNextIteratorRow (iterator, &width);
7716 if (pixels == (PixelWand **) NULL)
7717 break;
7718 for (x = 0; x < (long) width; x++)
7720 PixelGetMagickColor (pixels[x], &pixel);
7721 XPutPixel (ximg, x, y,
7722 lookup_rgb_color (f,
7723 pixel.red,
7724 pixel.green,
7725 pixel.blue));
7728 DestroyPixelIterator (iterator);
7731 if (imagemagick_rendermethod == 1)
7733 /* Magicexportimage is normaly faster than pixelpushing. This
7734 method is also well tested. Some aspects of this method are
7735 ad-hoc and needs to be more researched. */
7736 int imagedepth = 24;/*MagickGetImageDepth(image_wand);*/
7737 char* exportdepth = imagedepth <= 8 ? "I" : "BGRP";/*"RGBP";*/
7738 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7739 if (!x_create_x_image_and_pixmap (f, width, height, imagedepth,
7740 &ximg, &img->pixmap))
7742 #ifdef COLOR_TABLE_SUPPORT
7743 free_color_table ();
7744 #endif
7745 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7746 goto imagemagick_error;
7750 /* Oddly, the below code doesnt seem to work:*/
7751 /* switch(ximg->bitmap_unit){ */
7752 /* case 8: */
7753 /* pixelwidth=CharPixel; */
7754 /* break; */
7755 /* case 16: */
7756 /* pixelwidth=ShortPixel; */
7757 /* break; */
7758 /* case 32: */
7759 /* pixelwidth=LongPixel; */
7760 /* break; */
7761 /* } */
7763 Here im just guessing the format of the bitmap.
7764 happens to work fine for:
7765 - bw djvu images
7766 on rgb display.
7767 seems about 3 times as fast as pixel pushing(not carefully measured)
7769 pixelwidth = CharPixel;/*??? TODO figure out*/
7770 #ifdef HAVE_MAGICKEXPORTIMAGEPIXELS
7771 MagickExportImagePixels (image_wand,
7772 0, 0,
7773 width, height,
7774 exportdepth,
7775 pixelwidth,
7776 /*&(img->pixmap));*/
7777 ximg->data);
7778 #else
7779 image_error ("You dont have MagickExportImagePixels, upgrade ImageMagick!",
7780 Qnil, Qnil);
7781 #endif
7785 #ifdef COLOR_TABLE_SUPPORT
7786 /* Remember colors allocated for this image. */
7787 img->colors = colors_in_color_table (&img->ncolors);
7788 free_color_table ();
7789 #endif /* COLOR_TABLE_SUPPORT */
7792 img->width = width;
7793 img->height = height;
7795 /* Put the image into the pixmap, then free the X image and its
7796 buffer. */
7797 x_put_x_image (f, ximg, img->pixmap, width, height);
7798 x_destroy_x_image (ximg);
7801 /* Final cleanup. image_wand should be the only resource left. */
7802 DestroyMagickWand (image_wand);
7803 /* `MagickWandTerminus' terminates the imagemagick environment. */
7804 MagickWandTerminus ();
7806 return 1;
7808 imagemagick_error:
7809 DestroyMagickWand (image_wand);
7810 MagickWandTerminus ();
7811 /* TODO more cleanup. */
7812 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
7813 return 0;
7817 /* Load IMAGEMAGICK image IMG for use on frame F. Value is non-zero if
7818 successful. this function will go into the imagemagick_type structure, and
7819 the prototype thus needs to be compatible with that structure. */
7821 static int
7822 imagemagick_load (struct frame *f,
7823 struct image *img)
7825 int success_p = 0;
7826 Lisp_Object file_name;
7828 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7829 file_name = image_spec_value (img->spec, QCfile, NULL);
7830 if (STRINGP (file_name))
7832 Lisp_Object file;
7834 file = x_find_image_file (file_name);
7835 if (!STRINGP (file))
7837 image_error ("Cannot find image file `%s'", file_name, Qnil);
7838 return 0;
7840 success_p = imagemagick_load_image (f, img, 0, 0, SDATA (file));
7842 /* Else its not a file, its a lisp object. Load the image from a
7843 lisp object rather than a file. */
7844 else
7846 Lisp_Object data;
7848 data = image_spec_value (img->spec, QCdata, NULL);
7849 if (!STRINGP (data))
7851 image_error ("Invalid image data `%s'", data, Qnil);
7852 return 0;
7854 success_p = imagemagick_load_image (f, img, SDATA (data),
7855 SBYTES (data), NULL);
7858 return success_p;
7861 /* Structure describing the image type `imagemagick'. Its the same
7862 type of structure defined for all image formats, handled by Emacs
7863 image functions. See struct image_type in dispextern.h. */
7865 static struct image_type imagemagick_type =
7867 /* An identifier showing that this is an image structure for the
7868 IMAGEMAGICK format. */
7869 &Qimagemagick,
7870 /* Handle to a function that can be used to identify a IMAGEMAGICK
7871 file. */
7872 imagemagick_image_p,
7873 /* Handle to function used to load a IMAGEMAGICK file. */
7874 imagemagick_load,
7875 /* Handle to function to free resources for IMAGEMAGICK. */
7876 imagemagick_clear_image,
7877 /* An internal field to link to the next image type in a list of
7878 image types, will be filled in when registering the format. */
7879 NULL
7885 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
7886 doc: /* Return image file types supported by ImageMagick.
7887 Since ImageMagick recognizes a lot of file-types that clash with Emacs,
7888 such as .c, we want to be able to alter the list at the lisp level. */)
7889 (void)
7891 Lisp_Object typelist = Qnil;
7892 unsigned long numf;
7893 ExceptionInfo ex;
7894 char **imtypes = GetMagickList ("*", &numf, &ex);
7895 int i;
7896 Lisp_Object Qimagemagicktype;
7897 for (i = 0; i < numf; i++)
7899 Qimagemagicktype = intern (imtypes[i]);
7900 typelist = Fcons (Qimagemagicktype, typelist);
7902 return typelist;
7905 #endif /* defined (HAVE_IMAGEMAGICK) */
7909 /***********************************************************************
7911 ***********************************************************************/
7913 #if defined (HAVE_RSVG)
7915 /* Function prototypes. */
7917 static int svg_image_p (Lisp_Object object);
7918 static int svg_load (struct frame *f, struct image *img);
7920 static int svg_load_image (struct frame *, struct image *,
7921 unsigned char *, unsigned int);
7923 /* The symbol `svg' identifying images of this type. */
7925 Lisp_Object Qsvg;
7927 /* Indices of image specification fields in svg_format, below. */
7929 enum svg_keyword_index
7931 SVG_TYPE,
7932 SVG_DATA,
7933 SVG_FILE,
7934 SVG_ASCENT,
7935 SVG_MARGIN,
7936 SVG_RELIEF,
7937 SVG_ALGORITHM,
7938 SVG_HEURISTIC_MASK,
7939 SVG_MASK,
7940 SVG_BACKGROUND,
7941 SVG_LAST
7944 /* Vector of image_keyword structures describing the format
7945 of valid user-defined image specifications. */
7947 static const struct image_keyword svg_format[SVG_LAST] =
7949 {":type", IMAGE_SYMBOL_VALUE, 1},
7950 {":data", IMAGE_STRING_VALUE, 0},
7951 {":file", IMAGE_STRING_VALUE, 0},
7952 {":ascent", IMAGE_ASCENT_VALUE, 0},
7953 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7954 {":relief", IMAGE_INTEGER_VALUE, 0},
7955 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7956 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7957 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7958 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7961 /* Structure describing the image type `svg'. Its the same type of
7962 structure defined for all image formats, handled by emacs image
7963 functions. See struct image_type in dispextern.h. */
7965 static struct image_type svg_type =
7967 /* An identifier showing that this is an image structure for the SVG format. */
7968 &Qsvg,
7969 /* Handle to a function that can be used to identify a SVG file. */
7970 svg_image_p,
7971 /* Handle to function used to load a SVG file. */
7972 svg_load,
7973 /* Handle to function to free sresources for SVG. */
7974 x_clear_image,
7975 /* An internal field to link to the next image type in a list of
7976 image types, will be filled in when registering the format. */
7977 NULL
7981 /* Return non-zero if OBJECT is a valid SVG image specification. Do
7982 this by calling parse_image_spec and supplying the keywords that
7983 identify the SVG format. */
7985 static int
7986 svg_image_p (Lisp_Object object)
7988 struct image_keyword fmt[SVG_LAST];
7989 memcpy (fmt, svg_format, sizeof fmt);
7991 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
7992 return 0;
7994 /* Must specify either the :data or :file keyword. */
7995 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
7998 #include <librsvg/rsvg.h>
8000 #ifdef HAVE_NTGUI
8002 /* SVG library functions. */
8003 DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new);
8004 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions);
8005 DEF_IMGLIB_FN (gboolean, rsvg_handle_write);
8006 DEF_IMGLIB_FN (gboolean, rsvg_handle_close);
8007 DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf);
8008 DEF_IMGLIB_FN (void, rsvg_handle_free);
8010 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width);
8011 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height);
8012 DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels);
8013 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride);
8014 DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace);
8015 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels);
8016 DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha);
8017 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample);
8019 DEF_IMGLIB_FN (void, g_type_init);
8020 DEF_IMGLIB_FN (void, g_object_unref);
8021 DEF_IMGLIB_FN (void, g_error_free);
8023 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8025 static int
8026 init_svg_functions (Lisp_Object libraries)
8028 HMODULE library, gdklib, glib, gobject;
8030 if (!(glib = w32_delayed_load (libraries, Qglib))
8031 || !(gobject = w32_delayed_load (libraries, Qgobject))
8032 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
8033 || !(library = w32_delayed_load (libraries, Qsvg)))
8034 return 0;
8036 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8037 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8038 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8039 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8040 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8041 LOAD_IMGLIB_FN (library, rsvg_handle_free);
8043 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8044 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8045 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8046 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8047 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8048 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8049 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8050 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8052 LOAD_IMGLIB_FN (gobject, g_type_init);
8053 LOAD_IMGLIB_FN (gobject, g_object_unref);
8054 LOAD_IMGLIB_FN (glib, g_error_free);
8056 return 1;
8059 #else
8060 /* The following aliases for library functions allow dynamic loading
8061 to be used on some platforms. */
8062 #define fn_rsvg_handle_new rsvg_handle_new
8063 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8064 #define fn_rsvg_handle_write rsvg_handle_write
8065 #define fn_rsvg_handle_close rsvg_handle_close
8066 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8067 #define fn_rsvg_handle_free rsvg_handle_free
8069 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8070 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8071 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8072 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8073 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8074 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8075 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8076 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8078 #define fn_g_type_init g_type_init
8079 #define fn_g_object_unref g_object_unref
8080 #define fn_g_error_free g_error_free
8081 #endif /* !HAVE_NTGUI */
8083 /* Load SVG image IMG for use on frame F. Value is non-zero if
8084 successful. this function will go into the svg_type structure, and
8085 the prototype thus needs to be compatible with that structure. */
8087 static int
8088 svg_load (struct frame *f, struct image *img)
8090 int success_p = 0;
8091 Lisp_Object file_name;
8093 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8094 file_name = image_spec_value (img->spec, QCfile, NULL);
8095 if (STRINGP (file_name))
8097 Lisp_Object file;
8098 unsigned char *contents;
8099 int size;
8101 file = x_find_image_file (file_name);
8102 if (!STRINGP (file))
8104 image_error ("Cannot find image file `%s'", file_name, Qnil);
8105 return 0;
8108 /* Read the entire file into memory. */
8109 contents = slurp_file (SDATA (file), &size);
8110 if (contents == NULL)
8112 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8113 return 0;
8115 /* If the file was slurped into memory properly, parse it. */
8116 success_p = svg_load_image (f, img, contents, size);
8117 xfree (contents);
8119 /* Else its not a file, its a lisp object. Load the image from a
8120 lisp object rather than a file. */
8121 else
8123 Lisp_Object data;
8125 data = image_spec_value (img->spec, QCdata, NULL);
8126 if (!STRINGP (data))
8128 image_error ("Invalid image data `%s'", data, Qnil);
8129 return 0;
8131 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8134 return success_p;
8137 /* svg_load_image is a helper function for svg_load, which does the
8138 actual loading given contents and size, apart from frame and image
8139 structures, passed from svg_load.
8141 Uses librsvg to do most of the image processing.
8143 Returns non-zero when successful. */
8144 static int
8145 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8146 struct image *img, /* Pointer to emacs image structure. */
8147 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8148 unsigned int size) /* Size of data in bytes. */
8150 RsvgHandle *rsvg_handle;
8151 RsvgDimensionData dimension_data;
8152 GError *error = NULL;
8153 GdkPixbuf *pixbuf;
8154 int width;
8155 int height;
8156 const guint8 *pixels;
8157 int rowstride;
8158 XImagePtr ximg;
8159 Lisp_Object specified_bg;
8160 XColor background;
8161 int x;
8162 int y;
8164 /* g_type_init is a glib function that must be called prior to using
8165 gnome type library functions. */
8166 fn_g_type_init ();
8167 /* Make a handle to a new rsvg object. */
8168 rsvg_handle = fn_rsvg_handle_new ();
8170 /* Parse the contents argument and fill in the rsvg_handle. */
8171 fn_rsvg_handle_write (rsvg_handle, contents, size, &error);
8172 if (error) goto rsvg_error;
8174 /* The parsing is complete, rsvg_handle is ready to used, close it
8175 for further writes. */
8176 fn_rsvg_handle_close (rsvg_handle, &error);
8177 if (error) goto rsvg_error;
8179 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8180 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8182 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8183 goto rsvg_error;
8186 /* We can now get a valid pixel buffer from the svg file, if all
8187 went ok. */
8188 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8189 if (!pixbuf) goto rsvg_error;
8190 fn_g_object_unref (rsvg_handle);
8192 /* Extract some meta data from the svg handle. */
8193 width = fn_gdk_pixbuf_get_width (pixbuf);
8194 height = fn_gdk_pixbuf_get_height (pixbuf);
8195 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8196 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8198 /* Validate the svg meta data. */
8199 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8200 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8201 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8202 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8204 /* Try to create a x pixmap to hold the svg pixmap. */
8205 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8207 fn_g_object_unref (pixbuf);
8208 return 0;
8211 init_color_table ();
8213 /* Handle alpha channel by combining the image with a background
8214 color. */
8215 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8216 if (!STRINGP (specified_bg)
8217 || !x_defined_color (f, SDATA (specified_bg), &background, 0))
8219 #ifndef HAVE_NS
8220 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8221 x_query_color (f, &background);
8222 #else
8223 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8224 #endif
8227 /* SVG pixmaps specify transparency in the last byte, so right
8228 shift 8 bits to get rid of it, since emacs doesn't support
8229 transparency. */
8230 background.red >>= 8;
8231 background.green >>= 8;
8232 background.blue >>= 8;
8234 /* This loop handles opacity values, since Emacs assumes
8235 non-transparent images. Each pixel must be "flattened" by
8236 calculating the resulting color, given the transparency of the
8237 pixel, and the image background color. */
8238 for (y = 0; y < height; ++y)
8240 for (x = 0; x < width; ++x)
8242 unsigned red;
8243 unsigned green;
8244 unsigned blue;
8245 unsigned opacity;
8247 red = *pixels++;
8248 green = *pixels++;
8249 blue = *pixels++;
8250 opacity = *pixels++;
8252 red = ((red * opacity)
8253 + (background.red * ((1 << 8) - opacity)));
8254 green = ((green * opacity)
8255 + (background.green * ((1 << 8) - opacity)));
8256 blue = ((blue * opacity)
8257 + (background.blue * ((1 << 8) - opacity)));
8259 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8262 pixels += rowstride - 4 * width;
8265 #ifdef COLOR_TABLE_SUPPORT
8266 /* Remember colors allocated for this image. */
8267 img->colors = colors_in_color_table (&img->ncolors);
8268 free_color_table ();
8269 #endif /* COLOR_TABLE_SUPPORT */
8271 fn_g_object_unref (pixbuf);
8273 img->width = width;
8274 img->height = height;
8276 /* Maybe fill in the background field while we have ximg handy.
8277 Casting avoids a GCC warning. */
8278 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8280 /* Put the image into the pixmap, then free the X image and its
8281 buffer. */
8282 x_put_x_image (f, ximg, img->pixmap, width, height);
8283 x_destroy_x_image (ximg);
8285 return 1;
8287 rsvg_error:
8288 fn_g_object_unref (rsvg_handle);
8289 /* FIXME: Use error->message so the user knows what is the actual
8290 problem with the image. */
8291 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8292 fn_g_error_free (error);
8293 return 0;
8296 #endif /* defined (HAVE_RSVG) */
8301 /***********************************************************************
8302 Ghostscript
8303 ***********************************************************************/
8305 #ifdef HAVE_X_WINDOWS
8306 #define HAVE_GHOSTSCRIPT 1
8307 #endif /* HAVE_X_WINDOWS */
8309 #ifdef HAVE_GHOSTSCRIPT
8311 static int gs_image_p (Lisp_Object object);
8312 static int gs_load (struct frame *f, struct image *img);
8313 static void gs_clear_image (struct frame *f, struct image *img);
8315 /* Keyword symbols. */
8317 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8319 /* Indices of image specification fields in gs_format, below. */
8321 enum gs_keyword_index
8323 GS_TYPE,
8324 GS_PT_WIDTH,
8325 GS_PT_HEIGHT,
8326 GS_FILE,
8327 GS_LOADER,
8328 GS_BOUNDING_BOX,
8329 GS_ASCENT,
8330 GS_MARGIN,
8331 GS_RELIEF,
8332 GS_ALGORITHM,
8333 GS_HEURISTIC_MASK,
8334 GS_MASK,
8335 GS_BACKGROUND,
8336 GS_LAST
8339 /* Vector of image_keyword structures describing the format
8340 of valid user-defined image specifications. */
8342 static const struct image_keyword gs_format[GS_LAST] =
8344 {":type", IMAGE_SYMBOL_VALUE, 1},
8345 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8346 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8347 {":file", IMAGE_STRING_VALUE, 1},
8348 {":loader", IMAGE_FUNCTION_VALUE, 0},
8349 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8350 {":ascent", IMAGE_ASCENT_VALUE, 0},
8351 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8352 {":relief", IMAGE_INTEGER_VALUE, 0},
8353 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8354 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8355 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8356 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8359 /* Structure describing the image type `ghostscript'. */
8361 static struct image_type gs_type =
8363 &Qpostscript,
8364 gs_image_p,
8365 gs_load,
8366 gs_clear_image,
8367 NULL
8371 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8373 static void
8374 gs_clear_image (struct frame *f, struct image *img)
8376 /* IMG->data.ptr_val may contain a recorded colormap. */
8377 xfree (img->data.ptr_val);
8378 x_clear_image (f, img);
8382 /* Return non-zero if OBJECT is a valid Ghostscript image
8383 specification. */
8385 static int
8386 gs_image_p (Lisp_Object object)
8388 struct image_keyword fmt[GS_LAST];
8389 Lisp_Object tem;
8390 int i;
8392 memcpy (fmt, gs_format, sizeof fmt);
8394 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8395 return 0;
8397 /* Bounding box must be a list or vector containing 4 integers. */
8398 tem = fmt[GS_BOUNDING_BOX].value;
8399 if (CONSP (tem))
8401 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8402 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8403 return 0;
8404 if (!NILP (tem))
8405 return 0;
8407 else if (VECTORP (tem))
8409 if (XVECTOR (tem)->size != 4)
8410 return 0;
8411 for (i = 0; i < 4; ++i)
8412 if (!INTEGERP (XVECTOR (tem)->contents[i]))
8413 return 0;
8415 else
8416 return 0;
8418 return 1;
8422 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8423 if successful. */
8425 static int
8426 gs_load (struct frame *f, struct image *img)
8428 char buffer[100];
8429 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8430 Lisp_Object frame;
8431 double in_width, in_height;
8432 Lisp_Object pixel_colors = Qnil;
8434 /* Compute pixel size of pixmap needed from the given size in the
8435 image specification. Sizes in the specification are in pt. 1 pt
8436 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8437 info. */
8438 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8439 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
8440 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
8441 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8442 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
8443 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
8445 if (!check_image_size (f, img->width, img->height))
8447 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8448 return 0;
8451 /* Create the pixmap. */
8452 xassert (img->pixmap == NO_PIXMAP);
8454 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8455 BLOCK_INPUT;
8456 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8457 img->width, img->height,
8458 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8459 UNBLOCK_INPUT;
8461 if (!img->pixmap)
8463 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8464 return 0;
8467 /* Call the loader to fill the pixmap. It returns a process object
8468 if successful. We do not record_unwind_protect here because
8469 other places in redisplay like calling window scroll functions
8470 don't either. Let the Lisp loader use `unwind-protect' instead. */
8471 sprintf (buffer, "%lu %lu",
8472 (unsigned long) FRAME_X_WINDOW (f),
8473 (unsigned long) img->pixmap);
8474 window_and_pixmap_id = build_string (buffer);
8476 sprintf (buffer, "%lu %lu",
8477 FRAME_FOREGROUND_PIXEL (f),
8478 FRAME_BACKGROUND_PIXEL (f));
8479 pixel_colors = build_string (buffer);
8481 XSETFRAME (frame, f);
8482 loader = image_spec_value (img->spec, QCloader, NULL);
8483 if (NILP (loader))
8484 loader = intern ("gs-load-image");
8486 img->data.lisp_val = call6 (loader, frame, img->spec,
8487 make_number (img->width),
8488 make_number (img->height),
8489 window_and_pixmap_id,
8490 pixel_colors);
8491 return PROCESSP (img->data.lisp_val);
8495 /* Kill the Ghostscript process that was started to fill PIXMAP on
8496 frame F. Called from XTread_socket when receiving an event
8497 telling Emacs that Ghostscript has finished drawing. */
8499 void
8500 x_kill_gs_process (Pixmap pixmap, struct frame *f)
8502 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8503 int class, i;
8504 struct image *img;
8506 /* Find the image containing PIXMAP. */
8507 for (i = 0; i < c->used; ++i)
8508 if (c->images[i]->pixmap == pixmap)
8509 break;
8511 /* Should someone in between have cleared the image cache, for
8512 instance, give up. */
8513 if (i == c->used)
8514 return;
8516 /* Kill the GS process. We should have found PIXMAP in the image
8517 cache and its image should contain a process object. */
8518 img = c->images[i];
8519 xassert (PROCESSP (img->data.lisp_val));
8520 Fkill_process (img->data.lisp_val, Qnil);
8521 img->data.lisp_val = Qnil;
8523 #if defined (HAVE_X_WINDOWS)
8525 /* On displays with a mutable colormap, figure out the colors
8526 allocated for the image by looking at the pixels of an XImage for
8527 img->pixmap. */
8528 class = FRAME_X_VISUAL (f)->class;
8529 if (class != StaticColor && class != StaticGray && class != TrueColor)
8531 XImagePtr ximg;
8533 BLOCK_INPUT;
8535 /* Try to get an XImage for img->pixmep. */
8536 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8537 0, 0, img->width, img->height, ~0, ZPixmap);
8538 if (ximg)
8540 int x, y;
8542 /* Initialize the color table. */
8543 init_color_table ();
8545 /* For each pixel of the image, look its color up in the
8546 color table. After having done so, the color table will
8547 contain an entry for each color used by the image. */
8548 for (y = 0; y < img->height; ++y)
8549 for (x = 0; x < img->width; ++x)
8551 unsigned long pixel = XGetPixel (ximg, x, y);
8552 lookup_pixel_color (f, pixel);
8555 /* Record colors in the image. Free color table and XImage. */
8556 #ifdef COLOR_TABLE_SUPPORT
8557 img->colors = colors_in_color_table (&img->ncolors);
8558 free_color_table ();
8559 #endif
8560 XDestroyImage (ximg);
8562 #if 0 /* This doesn't seem to be the case. If we free the colors
8563 here, we get a BadAccess later in x_clear_image when
8564 freeing the colors. */
8565 /* We have allocated colors once, but Ghostscript has also
8566 allocated colors on behalf of us. So, to get the
8567 reference counts right, free them once. */
8568 if (img->ncolors)
8569 x_free_colors (f, img->colors, img->ncolors);
8570 #endif
8572 else
8573 image_error ("Cannot get X image of `%s'; colors will not be freed",
8574 img->spec, Qnil);
8576 UNBLOCK_INPUT;
8578 #endif /* HAVE_X_WINDOWS */
8580 /* Now that we have the pixmap, compute mask and transform the
8581 image if requested. */
8582 BLOCK_INPUT;
8583 postprocess_image (f, img);
8584 UNBLOCK_INPUT;
8587 #endif /* HAVE_GHOSTSCRIPT */
8590 /***********************************************************************
8591 Tests
8592 ***********************************************************************/
8594 #if GLYPH_DEBUG
8596 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8597 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8598 (Lisp_Object spec)
8600 return valid_image_p (spec) ? Qt : Qnil;
8604 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8605 (Lisp_Object spec)
8607 int id = -1;
8609 if (valid_image_p (spec))
8610 id = lookup_image (SELECTED_FRAME (), spec);
8612 debug_print (spec);
8613 return make_number (id);
8616 #endif /* GLYPH_DEBUG != 0 */
8619 /***********************************************************************
8620 Initialization
8621 ***********************************************************************/
8623 #ifdef HAVE_NTGUI
8624 /* Image types that rely on external libraries are loaded dynamically
8625 if the library is available. */
8626 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8627 define_image_type (image_type, init_lib_fn (libraries))
8628 #else
8629 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8630 define_image_type (image_type, 1)
8631 #endif /* HAVE_NTGUI */
8633 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8634 doc: /* Initialize image library implementing image type TYPE.
8635 Return non-nil if TYPE is a supported image type.
8637 Image types pbm and xbm are prebuilt; other types are loaded here.
8638 Libraries to load are specified in alist LIBRARIES (usually, the value
8639 of `dynamic-library-alist', which see). */)
8640 (Lisp_Object type, Lisp_Object libraries)
8642 Lisp_Object tested;
8644 /* Don't try to reload the library. */
8645 tested = Fassq (type, Vimage_type_cache);
8646 if (CONSP (tested))
8647 return XCDR (tested);
8649 #if defined (HAVE_XPM) || defined (HAVE_NS)
8650 if (EQ (type, Qxpm))
8651 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8652 #endif
8654 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8655 if (EQ (type, Qjpeg))
8656 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8657 #endif
8659 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8660 if (EQ (type, Qtiff))
8661 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8662 #endif
8664 #if defined (HAVE_GIF) || defined (HAVE_NS)
8665 if (EQ (type, Qgif))
8666 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8667 #endif
8669 #if defined (HAVE_PNG) || defined (HAVE_NS)
8670 if (EQ (type, Qpng))
8671 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8672 #endif
8674 #if defined (HAVE_RSVG)
8675 if (EQ (type, Qsvg))
8676 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
8677 #endif
8679 #if defined (HAVE_IMAGEMAGICK)
8680 if (EQ (type, Qimagemagick))
8682 return CHECK_LIB_AVAILABLE (&imagemagick_type, init_imagemagick_functions,
8683 libraries);
8685 #endif
8687 #ifdef HAVE_GHOSTSCRIPT
8688 if (EQ (type, Qpostscript))
8689 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8690 #endif
8692 /* If the type is not recognized, avoid testing it ever again. */
8693 CACHE_IMAGE_TYPE (type, Qnil);
8694 return Qnil;
8697 void
8698 syms_of_image (void)
8700 /* Initialize this only once, since that's what we do with Vimage_types
8701 and they are supposed to be in sync. Initializing here gives correct
8702 operation on GNU/Linux of calling dump-emacs after loading some images. */
8703 image_types = NULL;
8705 /* Must be defined now becase we're going to update it below, while
8706 defining the supported image types. */
8707 DEFVAR_LISP ("image-types", Vimage_types,
8708 doc: /* List of potentially supported image types.
8709 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8710 To check whether it is really supported, use `image-type-available-p'. */);
8711 Vimage_types = Qnil;
8713 DEFVAR_LISP ("max-image-size", Vmax_image_size,
8714 doc: /* Maximum size of images.
8715 Emacs will not load an image into memory if its pixel width or
8716 pixel height exceeds this limit.
8718 If the value is an integer, it directly specifies the maximum
8719 image height and width, measured in pixels. If it is a floating
8720 point number, it specifies the maximum image height and width
8721 as a ratio to the frame height and width. If the value is
8722 non-numeric, there is no explicit limit on the size of images. */);
8723 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8725 Vimage_type_cache = Qnil;
8726 staticpro (&Vimage_type_cache);
8728 Qpbm = intern_c_string ("pbm");
8729 staticpro (&Qpbm);
8730 ADD_IMAGE_TYPE (Qpbm);
8732 Qxbm = intern_c_string ("xbm");
8733 staticpro (&Qxbm);
8734 ADD_IMAGE_TYPE (Qxbm);
8736 define_image_type (&xbm_type, 1);
8737 define_image_type (&pbm_type, 1);
8739 Qcount = intern_c_string ("count");
8740 staticpro (&Qcount);
8741 Qextension_data = intern_c_string ("extension-data");
8742 staticpro (&Qextension_data);
8744 QCascent = intern_c_string (":ascent");
8745 staticpro (&QCascent);
8746 QCmargin = intern_c_string (":margin");
8747 staticpro (&QCmargin);
8748 QCrelief = intern_c_string (":relief");
8749 staticpro (&QCrelief);
8750 QCconversion = intern_c_string (":conversion");
8751 staticpro (&QCconversion);
8752 QCcolor_symbols = intern_c_string (":color-symbols");
8753 staticpro (&QCcolor_symbols);
8754 QCheuristic_mask = intern_c_string (":heuristic-mask");
8755 staticpro (&QCheuristic_mask);
8756 QCindex = intern_c_string (":index");
8757 staticpro (&QCindex);
8758 QCgeometry = intern_c_string (":geometry");
8759 staticpro (&QCgeometry);
8760 QCcrop = intern_c_string (":crop");
8761 staticpro (&QCcrop);
8762 QCrotation = intern_c_string (":rotation");
8763 staticpro (&QCrotation);
8764 QCmatrix = intern_c_string (":matrix");
8765 staticpro (&QCmatrix);
8766 QCcolor_adjustment = intern_c_string (":color-adjustment");
8767 staticpro (&QCcolor_adjustment);
8768 QCmask = intern_c_string (":mask");
8769 staticpro (&QCmask);
8771 Qlaplace = intern_c_string ("laplace");
8772 staticpro (&Qlaplace);
8773 Qemboss = intern_c_string ("emboss");
8774 staticpro (&Qemboss);
8775 Qedge_detection = intern_c_string ("edge-detection");
8776 staticpro (&Qedge_detection);
8777 Qheuristic = intern_c_string ("heuristic");
8778 staticpro (&Qheuristic);
8780 Qpostscript = intern_c_string ("postscript");
8781 staticpro (&Qpostscript);
8782 #ifdef HAVE_GHOSTSCRIPT
8783 ADD_IMAGE_TYPE (Qpostscript);
8784 QCloader = intern_c_string (":loader");
8785 staticpro (&QCloader);
8786 QCbounding_box = intern_c_string (":bounding-box");
8787 staticpro (&QCbounding_box);
8788 QCpt_width = intern_c_string (":pt-width");
8789 staticpro (&QCpt_width);
8790 QCpt_height = intern_c_string (":pt-height");
8791 staticpro (&QCpt_height);
8792 #endif /* HAVE_GHOSTSCRIPT */
8794 #ifdef HAVE_NTGUI
8795 Qlibpng_version = intern_c_string ("libpng-version");
8796 staticpro (&Qlibpng_version);
8797 Fset (Qlibpng_version,
8798 #if HAVE_PNG
8799 make_number (PNG_LIBPNG_VER)
8800 #else
8801 make_number (-1)
8802 #endif
8804 #endif
8806 #if defined (HAVE_XPM) || defined (HAVE_NS)
8807 Qxpm = intern_c_string ("xpm");
8808 staticpro (&Qxpm);
8809 ADD_IMAGE_TYPE (Qxpm);
8810 #endif
8812 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8813 Qjpeg = intern_c_string ("jpeg");
8814 staticpro (&Qjpeg);
8815 ADD_IMAGE_TYPE (Qjpeg);
8816 #endif
8818 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8819 Qtiff = intern_c_string ("tiff");
8820 staticpro (&Qtiff);
8821 ADD_IMAGE_TYPE (Qtiff);
8822 #endif
8824 #if defined (HAVE_GIF) || defined (HAVE_NS)
8825 Qgif = intern_c_string ("gif");
8826 staticpro (&Qgif);
8827 ADD_IMAGE_TYPE (Qgif);
8828 #endif
8830 #if defined (HAVE_PNG) || defined (HAVE_NS)
8831 Qpng = intern_c_string ("png");
8832 staticpro (&Qpng);
8833 ADD_IMAGE_TYPE (Qpng);
8834 #endif
8836 #if defined (HAVE_IMAGEMAGICK)
8837 Qimagemagick = intern_c_string ("imagemagick");
8838 staticpro (&Qimagemagick);
8839 ADD_IMAGE_TYPE (Qimagemagick);
8840 #endif
8842 #if defined (HAVE_RSVG)
8843 Qsvg = intern_c_string ("svg");
8844 staticpro (&Qsvg);
8845 ADD_IMAGE_TYPE (Qsvg);
8846 #ifdef HAVE_NTGUI
8847 /* Other libraries used directly by svg code. */
8848 Qgdk_pixbuf = intern_c_string ("gdk-pixbuf");
8849 staticpro (&Qgdk_pixbuf);
8850 Qglib = intern_c_string ("glib");
8851 staticpro (&Qglib);
8852 Qgobject = intern_c_string ("gobject");
8853 staticpro (&Qgobject);
8854 #endif /* HAVE_NTGUI */
8855 #endif /* HAVE_RSVG */
8857 defsubr (&Sinit_image_library);
8858 #ifdef HAVE_IMAGEMAGICK
8859 defsubr (&Simagemagick_types);
8860 #endif
8861 defsubr (&Sclear_image_cache);
8862 defsubr (&Simage_flush);
8863 defsubr (&Simage_size);
8864 defsubr (&Simage_mask_p);
8865 defsubr (&Simage_metadata);
8867 #if GLYPH_DEBUG
8868 defsubr (&Simagep);
8869 defsubr (&Slookup_image);
8870 #endif
8872 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
8873 doc: /* Non-nil means always draw a cross over disabled images.
8874 Disabled images are those having a `:conversion disabled' property.
8875 A cross is always drawn on black & white displays. */);
8876 cross_disabled_images = 0;
8878 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
8879 doc: /* List of directories to search for window system bitmap files. */);
8880 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8882 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
8883 doc: /* Maximum time after which images are removed from the cache.
8884 When an image has not been displayed this many seconds, Emacs
8885 automatically removes it from the image cache. If the cache contains
8886 a large number of images, the actual eviction time may be shorter.
8887 The value can also be nil, meaning the cache is never cleared.
8889 The function `clear-image-cache' disregards this variable. */);
8890 Vimage_cache_eviction_delay = make_number (300);
8891 #ifdef HAVE_IMAGEMAGICK
8892 DEFVAR_LISP ("imagemagick-render-type", Vimagemagick_render_type,
8893 doc: /* Choose between ImageMagick render methods. */);
8894 #endif
8898 void
8899 init_image (void)