src/image.c (Finit_image_library): Return t for built-in image types (bug#8640).
[emacs.git] / src / image.c
blob23da03b6264bfac91e4e557cdd56ed5acce081fe
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 "w32.h"
71 #include "w32term.h"
73 /* W32_TODO : Color tables on W32. */
74 #undef COLOR_TABLE_SUPPORT
76 typedef struct w32_bitmap_record Bitmap_Record;
77 #define GET_PIXEL(ximg, x, y) GetPixel(ximg, x, y)
78 #define NO_PIXMAP 0
80 #define RGB_PIXEL_COLOR COLORREF
82 #define PIX_MASK_RETAIN 0
83 #define PIX_MASK_DRAW 1
85 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
86 #define x_defined_color w32_defined_color
87 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
89 /* Functions from w32term.c that depend on XColor (so can't go in w32term.h
90 without modifying lots of files). */
91 extern void x_query_colors (struct frame *f, XColor *colors, int ncolors);
92 extern void x_query_color (struct frame *f, XColor *color);
94 /* Version of libpng that we were compiled with, or -1 if no PNG
95 support was compiled in. This is tested by w32-win.el to correctly
96 set up the alist used to search for PNG libraries. */
97 Lisp_Object Qlibpng_version;
98 #endif /* HAVE_NTGUI */
100 #ifdef HAVE_NS
101 #include "nsterm.h"
102 #include <sys/types.h>
103 #include <sys/stat.h>
105 #undef COLOR_TABLE_SUPPORT
107 typedef struct ns_bitmap_record Bitmap_Record;
109 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
110 #define NO_PIXMAP 0
112 #define RGB_PIXEL_COLOR unsigned long
113 #define ZPixmap 0
115 #define PIX_MASK_RETAIN 0
116 #define PIX_MASK_DRAW 1
118 #define FRAME_X_VISUAL FRAME_NS_DISPLAY_INFO(f)->visual
119 #define x_defined_color(f, name, color_def, alloc) \
120 ns_defined_color (f, name, color_def, alloc, 0)
121 #define FRAME_X_SCREEN(f) 0
122 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
123 #endif /* HAVE_NS */
126 /* The symbol `postscript' identifying images of this type. */
128 static Lisp_Object Qpostscript;
130 static void x_disable_image (struct frame *, struct image *);
131 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
132 Lisp_Object);
134 static void init_color_table (void);
135 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
136 #ifdef COLOR_TABLE_SUPPORT
137 static void free_color_table (void);
138 static unsigned long *colors_in_color_table (int *n);
139 static unsigned long lookup_pixel_color (struct frame *f, unsigned long p);
140 #endif
141 static Lisp_Object Finit_image_library (Lisp_Object, Lisp_Object);
143 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
144 id, which is just an int that this section returns. Bitmaps are
145 reference counted so they can be shared among frames.
147 Bitmap indices are guaranteed to be > 0, so a negative number can
148 be used to indicate no bitmap.
150 If you use x_create_bitmap_from_data, then you must keep track of
151 the bitmaps yourself. That is, creating a bitmap from the same
152 data more than once will not be caught. */
154 #ifdef HAVE_NS
155 XImagePtr
156 XGetImage (Display *display, Pixmap pixmap, int x, int y,
157 unsigned int width, unsigned int height,
158 unsigned long plane_mask, int format)
160 /* TODO: not sure what this function is supposed to do.. */
161 ns_retain_object (pixmap);
162 return pixmap;
165 /* use with imgs created by ns_image_for_XPM */
166 unsigned long
167 XGetPixel (XImagePtr ximage, int x, int y)
169 return ns_get_pixel (ximage, x, y);
172 /* use with imgs created by ns_image_for_XPM; alpha set to 1;
173 pixel is assumed to be in form RGB */
174 void
175 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
177 ns_put_pixel (ximage, x, y, pixel);
179 #endif /* HAVE_NS */
182 /* Functions to access the contents of a bitmap, given an id. */
185 x_bitmap_height (FRAME_PTR f, int id)
187 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
191 x_bitmap_width (FRAME_PTR f, int id)
193 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
196 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
198 x_bitmap_pixmap (FRAME_PTR f, int id)
200 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
202 #endif
204 #ifdef HAVE_X_WINDOWS
206 x_bitmap_mask (FRAME_PTR f, int id)
208 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
210 #endif
212 /* Allocate a new bitmap record. Returns index of new record. */
214 static int
215 x_allocate_bitmap_record (FRAME_PTR f)
217 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
218 int i;
220 if (dpyinfo->bitmaps == NULL)
222 dpyinfo->bitmaps_size = 10;
223 dpyinfo->bitmaps
224 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
225 dpyinfo->bitmaps_last = 1;
226 return 1;
229 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
230 return ++dpyinfo->bitmaps_last;
232 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
233 if (dpyinfo->bitmaps[i].refcount == 0)
234 return i + 1;
236 dpyinfo->bitmaps_size *= 2;
237 dpyinfo->bitmaps
238 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
239 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
240 return ++dpyinfo->bitmaps_last;
243 /* Add one reference to the reference count of the bitmap with id ID. */
245 void
246 x_reference_bitmap (FRAME_PTR f, int id)
248 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
251 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
254 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
256 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
257 int id;
259 #ifdef HAVE_X_WINDOWS
260 Pixmap bitmap;
261 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
262 bits, width, height);
263 if (! bitmap)
264 return -1;
265 #endif /* HAVE_X_WINDOWS */
267 #ifdef HAVE_NTGUI
268 Pixmap bitmap;
269 bitmap = CreateBitmap (width, height,
270 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
271 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
272 bits);
273 if (! bitmap)
274 return -1;
275 #endif /* HAVE_NTGUI */
277 #ifdef HAVE_NS
278 void *bitmap = ns_image_from_XBM (bits, width, height);
279 if (!bitmap)
280 return -1;
281 #endif
283 id = x_allocate_bitmap_record (f);
285 #ifdef HAVE_NS
286 dpyinfo->bitmaps[id - 1].img = bitmap;
287 dpyinfo->bitmaps[id - 1].depth = 1;
288 #endif
290 dpyinfo->bitmaps[id - 1].file = NULL;
291 dpyinfo->bitmaps[id - 1].height = height;
292 dpyinfo->bitmaps[id - 1].width = width;
293 dpyinfo->bitmaps[id - 1].refcount = 1;
295 #ifdef HAVE_X_WINDOWS
296 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
297 dpyinfo->bitmaps[id - 1].have_mask = 0;
298 dpyinfo->bitmaps[id - 1].depth = 1;
299 #endif /* HAVE_X_WINDOWS */
301 #ifdef HAVE_NTGUI
302 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
303 dpyinfo->bitmaps[id - 1].hinst = NULL;
304 dpyinfo->bitmaps[id - 1].depth = 1;
305 #endif /* HAVE_NTGUI */
307 return id;
310 /* Create bitmap from file FILE for frame F. */
313 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
315 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
317 #ifdef HAVE_NTGUI
318 return -1; /* W32_TODO : bitmap support */
319 #endif /* HAVE_NTGUI */
321 #ifdef HAVE_NS
322 int id;
323 void *bitmap = ns_image_from_file (file);
325 if (!bitmap)
326 return -1;
329 id = x_allocate_bitmap_record (f);
330 dpyinfo->bitmaps[id - 1].img = bitmap;
331 dpyinfo->bitmaps[id - 1].refcount = 1;
332 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
333 dpyinfo->bitmaps[id - 1].depth = 1;
334 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
335 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
336 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
337 return id;
338 #endif
340 #ifdef HAVE_X_WINDOWS
341 unsigned int width, height;
342 Pixmap bitmap;
343 int xhot, yhot, result, id;
344 Lisp_Object found;
345 int fd;
346 char *filename;
348 /* Look for an existing bitmap with the same name. */
349 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
351 if (dpyinfo->bitmaps[id].refcount
352 && dpyinfo->bitmaps[id].file
353 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
355 ++dpyinfo->bitmaps[id].refcount;
356 return id + 1;
360 /* Search bitmap-file-path for the file, if appropriate. */
361 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
362 if (fd < 0)
363 return -1;
364 emacs_close (fd);
366 filename = SSDATA (found);
368 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
369 filename, &width, &height, &bitmap, &xhot, &yhot);
370 if (result != BitmapSuccess)
371 return -1;
373 id = x_allocate_bitmap_record (f);
374 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
375 dpyinfo->bitmaps[id - 1].have_mask = 0;
376 dpyinfo->bitmaps[id - 1].refcount = 1;
377 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
378 dpyinfo->bitmaps[id - 1].depth = 1;
379 dpyinfo->bitmaps[id - 1].height = height;
380 dpyinfo->bitmaps[id - 1].width = width;
381 strcpy (dpyinfo->bitmaps[id - 1].file, SSDATA (file));
383 return id;
384 #endif /* HAVE_X_WINDOWS */
387 /* Free bitmap B. */
389 static void
390 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
392 #ifdef HAVE_X_WINDOWS
393 XFreePixmap (dpyinfo->display, bm->pixmap);
394 if (bm->have_mask)
395 XFreePixmap (dpyinfo->display, bm->mask);
396 #endif /* HAVE_X_WINDOWS */
398 #ifdef HAVE_NTGUI
399 DeleteObject (bm->pixmap);
400 #endif /* HAVE_NTGUI */
402 #ifdef HAVE_NS
403 ns_release_object (bm->img);
404 #endif
406 if (bm->file)
408 xfree (bm->file);
409 bm->file = NULL;
413 /* Remove reference to bitmap with id number ID. */
415 void
416 x_destroy_bitmap (FRAME_PTR f, int id)
418 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
420 if (id > 0)
422 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
424 if (--bm->refcount == 0)
426 BLOCK_INPUT;
427 free_bitmap_record (dpyinfo, bm);
428 UNBLOCK_INPUT;
433 /* Free all the bitmaps for the display specified by DPYINFO. */
435 void
436 x_destroy_all_bitmaps (Display_Info *dpyinfo)
438 int i;
439 Bitmap_Record *bm = dpyinfo->bitmaps;
441 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
442 if (bm->refcount > 0)
443 free_bitmap_record (dpyinfo, bm);
445 dpyinfo->bitmaps_last = 0;
449 #ifdef HAVE_X_WINDOWS
451 /* Useful functions defined in the section
452 `Image type independent image structures' below. */
454 static unsigned long four_corners_best (XImagePtr ximg,
455 int *corners,
456 unsigned long width,
457 unsigned long height);
459 static int x_create_x_image_and_pixmap (struct frame *f, int width, int height,
460 int depth, XImagePtr *ximg,
461 Pixmap *pixmap);
463 static void x_destroy_x_image (XImagePtr ximg);
466 /* Create a mask of a bitmap. Note is this not a perfect mask.
467 It's nicer with some borders in this context */
470 x_create_bitmap_mask (struct frame *f, int id)
472 Pixmap pixmap, mask;
473 XImagePtr ximg, mask_img;
474 unsigned long width, height;
475 int result;
476 unsigned long bg;
477 unsigned long x, y, xp, xm, yp, ym;
478 GC gc;
480 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
482 if (!(id > 0))
483 return -1;
485 pixmap = x_bitmap_pixmap (f, id);
486 width = x_bitmap_width (f, id);
487 height = x_bitmap_height (f, id);
489 BLOCK_INPUT;
490 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
491 ~0, ZPixmap);
493 if (!ximg)
495 UNBLOCK_INPUT;
496 return -1;
499 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
501 UNBLOCK_INPUT;
502 if (!result)
504 XDestroyImage (ximg);
505 return -1;
508 bg = four_corners_best (ximg, NULL, width, height);
510 for (y = 0; y < ximg->height; ++y)
512 for (x = 0; x < ximg->width; ++x)
514 xp = x != ximg->width - 1 ? x + 1 : 0;
515 xm = x != 0 ? x - 1 : ximg->width - 1;
516 yp = y != ximg->height - 1 ? y + 1 : 0;
517 ym = y != 0 ? y - 1 : ximg->height - 1;
518 if (XGetPixel (ximg, x, y) == bg
519 && XGetPixel (ximg, x, yp) == bg
520 && XGetPixel (ximg, x, ym) == bg
521 && XGetPixel (ximg, xp, y) == bg
522 && XGetPixel (ximg, xp, yp) == bg
523 && XGetPixel (ximg, xp, ym) == bg
524 && XGetPixel (ximg, xm, y) == bg
525 && XGetPixel (ximg, xm, yp) == bg
526 && XGetPixel (ximg, xm, ym) == bg)
527 XPutPixel (mask_img, x, y, 0);
528 else
529 XPutPixel (mask_img, x, y, 1);
533 xassert (interrupt_input_blocked);
534 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
535 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
536 width, height);
537 XFreeGC (FRAME_X_DISPLAY (f), gc);
539 dpyinfo->bitmaps[id - 1].have_mask = 1;
540 dpyinfo->bitmaps[id - 1].mask = mask;
542 XDestroyImage (ximg);
543 x_destroy_x_image (mask_img);
545 return 0;
548 #endif /* HAVE_X_WINDOWS */
551 /***********************************************************************
552 Image types
553 ***********************************************************************/
555 /* List of supported image types. Use define_image_type to add new
556 types. Use lookup_image_type to find a type for a given symbol. */
558 static struct image_type *image_types;
560 /* The symbol `xbm' which is used as the type symbol for XBM images. */
562 static Lisp_Object Qxbm;
564 /* Keywords. */
566 Lisp_Object QCascent, QCmargin, QCrelief;
567 static Lisp_Object Qcount, Qextension_data;
568 Lisp_Object QCconversion;
569 static Lisp_Object QCheuristic_mask;
570 static Lisp_Object QCcolor_symbols;
571 static Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry;
572 static Lisp_Object QCcrop, QCrotation;
574 /* Other symbols. */
576 static Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
578 /* Function prototypes. */
580 static Lisp_Object define_image_type (struct image_type *type, int loaded);
581 static struct image_type *lookup_image_type (Lisp_Object symbol);
582 static void image_error (const char *format, Lisp_Object, Lisp_Object);
583 static void x_laplace (struct frame *, struct image *);
584 static void x_emboss (struct frame *, struct image *);
585 static int x_build_heuristic_mask (struct frame *, struct image *,
586 Lisp_Object);
587 #ifdef HAVE_NTGUI
588 #define CACHE_IMAGE_TYPE(type, status) \
589 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
590 #else
591 #define CACHE_IMAGE_TYPE(type, status)
592 #endif
594 #define ADD_IMAGE_TYPE(type) \
595 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
597 /* Define a new image type from TYPE. This adds a copy of TYPE to
598 image_types and caches the loading status of TYPE. */
600 static Lisp_Object
601 define_image_type (struct image_type *type, int loaded)
603 Lisp_Object success;
605 if (!loaded)
606 success = Qnil;
607 else
609 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
610 The initialized data segment is read-only. */
611 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
612 memcpy (p, type, sizeof *p);
613 p->next = image_types;
614 image_types = p;
615 success = Qt;
618 CACHE_IMAGE_TYPE (*type->type, success);
619 return success;
623 /* Look up image type SYMBOL, and return a pointer to its image_type
624 structure. Value is null if SYMBOL is not a known image type. */
626 static INLINE struct image_type *
627 lookup_image_type (Lisp_Object symbol)
629 struct image_type *type;
631 /* We must initialize the image-type if it hasn't been already. */
632 if (NILP (Finit_image_library (symbol, Vdynamic_library_alist)))
633 return 0; /* unimplemented */
635 for (type = image_types; type; type = type->next)
636 if (EQ (symbol, *type->type))
637 break;
639 return type;
643 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
644 valid image specification is a list whose car is the symbol
645 `image', and whose rest is a property list. The property list must
646 contain a value for key `:type'. That value must be the name of a
647 supported image type. The rest of the property list depends on the
648 image type. */
651 valid_image_p (Lisp_Object object)
653 int valid_p = 0;
655 if (IMAGEP (object))
657 Lisp_Object tem;
659 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
660 if (EQ (XCAR (tem), QCtype))
662 tem = XCDR (tem);
663 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
665 struct image_type *type;
666 type = lookup_image_type (XCAR (tem));
667 if (type)
668 valid_p = type->valid_p (object);
671 break;
675 return valid_p;
679 /* Log error message with format string FORMAT and argument ARG.
680 Signaling an error, e.g. when an image cannot be loaded, is not a
681 good idea because this would interrupt redisplay, and the error
682 message display would lead to another redisplay. This function
683 therefore simply displays a message. */
685 static void
686 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
688 add_to_log (format, arg1, arg2);
693 /***********************************************************************
694 Image specifications
695 ***********************************************************************/
697 enum image_value_type
699 IMAGE_DONT_CHECK_VALUE_TYPE,
700 IMAGE_STRING_VALUE,
701 IMAGE_STRING_OR_NIL_VALUE,
702 IMAGE_SYMBOL_VALUE,
703 IMAGE_POSITIVE_INTEGER_VALUE,
704 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
705 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
706 IMAGE_ASCENT_VALUE,
707 IMAGE_INTEGER_VALUE,
708 IMAGE_FUNCTION_VALUE,
709 IMAGE_NUMBER_VALUE,
710 IMAGE_BOOL_VALUE
713 /* Structure used when parsing image specifications. */
715 struct image_keyword
717 /* Name of keyword. */
718 const char *name;
720 /* The type of value allowed. */
721 enum image_value_type type;
723 /* Non-zero means key must be present. */
724 int mandatory_p;
726 /* Used to recognize duplicate keywords in a property list. */
727 int count;
729 /* The value that was found. */
730 Lisp_Object value;
734 static int parse_image_spec (Lisp_Object, struct image_keyword *,
735 int, Lisp_Object);
736 static Lisp_Object image_spec_value (Lisp_Object, Lisp_Object, int *);
739 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
740 has the format (image KEYWORD VALUE ...). One of the keyword/
741 value pairs must be `:type TYPE'. KEYWORDS is a vector of
742 image_keywords structures of size NKEYWORDS describing other
743 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
745 static int
746 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
747 int nkeywords, Lisp_Object type)
749 int i;
750 Lisp_Object plist;
752 if (!IMAGEP (spec))
753 return 0;
755 plist = XCDR (spec);
756 while (CONSP (plist))
758 Lisp_Object key, value;
760 /* First element of a pair must be a symbol. */
761 key = XCAR (plist);
762 plist = XCDR (plist);
763 if (!SYMBOLP (key))
764 return 0;
766 /* There must follow a value. */
767 if (!CONSP (plist))
768 return 0;
769 value = XCAR (plist);
770 plist = XCDR (plist);
772 /* Find key in KEYWORDS. Error if not found. */
773 for (i = 0; i < nkeywords; ++i)
774 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
775 break;
777 if (i == nkeywords)
778 continue;
780 /* Record that we recognized the keyword. If a keywords
781 was found more than once, it's an error. */
782 keywords[i].value = value;
783 ++keywords[i].count;
785 if (keywords[i].count > 1)
786 return 0;
788 /* Check type of value against allowed type. */
789 switch (keywords[i].type)
791 case IMAGE_STRING_VALUE:
792 if (!STRINGP (value))
793 return 0;
794 break;
796 case IMAGE_STRING_OR_NIL_VALUE:
797 if (!STRINGP (value) && !NILP (value))
798 return 0;
799 break;
801 case IMAGE_SYMBOL_VALUE:
802 if (!SYMBOLP (value))
803 return 0;
804 break;
806 case IMAGE_POSITIVE_INTEGER_VALUE:
807 if (!INTEGERP (value) || XINT (value) <= 0)
808 return 0;
809 break;
811 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
812 if (INTEGERP (value) && XINT (value) >= 0)
813 break;
814 if (CONSP (value)
815 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
816 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
817 break;
818 return 0;
820 case IMAGE_ASCENT_VALUE:
821 if (SYMBOLP (value) && EQ (value, Qcenter))
822 break;
823 else if (INTEGERP (value)
824 && XINT (value) >= 0
825 && XINT (value) <= 100)
826 break;
827 return 0;
829 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
830 if (!INTEGERP (value) || XINT (value) < 0)
831 return 0;
832 break;
834 case IMAGE_DONT_CHECK_VALUE_TYPE:
835 break;
837 case IMAGE_FUNCTION_VALUE:
838 value = indirect_function (value);
839 if (!NILP (Ffunctionp (value)))
840 break;
841 return 0;
843 case IMAGE_NUMBER_VALUE:
844 if (!INTEGERP (value) && !FLOATP (value))
845 return 0;
846 break;
848 case IMAGE_INTEGER_VALUE:
849 if (!INTEGERP (value))
850 return 0;
851 break;
853 case IMAGE_BOOL_VALUE:
854 if (!NILP (value) && !EQ (value, Qt))
855 return 0;
856 break;
858 default:
859 abort ();
860 break;
863 if (EQ (key, QCtype) && !EQ (type, value))
864 return 0;
867 /* Check that all mandatory fields are present. */
868 for (i = 0; i < nkeywords; ++i)
869 if (keywords[i].mandatory_p && keywords[i].count == 0)
870 return 0;
872 return NILP (plist);
876 /* Return the value of KEY in image specification SPEC. Value is nil
877 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
878 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
880 static Lisp_Object
881 image_spec_value (Lisp_Object spec, Lisp_Object key, int *found)
883 Lisp_Object tail;
885 xassert (valid_image_p (spec));
887 for (tail = XCDR (spec);
888 CONSP (tail) && CONSP (XCDR (tail));
889 tail = XCDR (XCDR (tail)))
891 if (EQ (XCAR (tail), key))
893 if (found)
894 *found = 1;
895 return XCAR (XCDR (tail));
899 if (found)
900 *found = 0;
901 return Qnil;
905 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
906 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
907 PIXELS non-nil means return the size in pixels, otherwise return the
908 size in canonical character units.
909 FRAME is the frame on which the image will be displayed. FRAME nil
910 or omitted means use the selected frame. */)
911 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
913 Lisp_Object size;
915 size = Qnil;
916 if (valid_image_p (spec))
918 struct frame *f = check_x_frame (frame);
919 int id = lookup_image (f, spec);
920 struct image *img = IMAGE_FROM_ID (f, id);
921 int width = img->width + 2 * img->hmargin;
922 int height = img->height + 2 * img->vmargin;
924 if (NILP (pixels))
925 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
926 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
927 else
928 size = Fcons (make_number (width), make_number (height));
930 else
931 error ("Invalid image specification");
933 return size;
937 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
938 doc: /* Return t if image SPEC has a mask bitmap.
939 FRAME is the frame on which the image will be displayed. FRAME nil
940 or omitted means use the selected frame. */)
941 (Lisp_Object spec, Lisp_Object frame)
943 Lisp_Object mask;
945 mask = Qnil;
946 if (valid_image_p (spec))
948 struct frame *f = check_x_frame (frame);
949 int id = lookup_image (f, spec);
950 struct image *img = IMAGE_FROM_ID (f, id);
951 if (img->mask)
952 mask = Qt;
954 else
955 error ("Invalid image specification");
957 return mask;
960 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
961 doc: /* Return metadata for image SPEC.
962 FRAME is the frame on which the image will be displayed. FRAME nil
963 or omitted means use the selected frame. */)
964 (Lisp_Object spec, Lisp_Object frame)
966 Lisp_Object ext;
968 ext = Qnil;
969 if (valid_image_p (spec))
971 struct frame *f = check_x_frame (frame);
972 int id = lookup_image (f, spec);
973 struct image *img = IMAGE_FROM_ID (f, id);
974 ext = img->data.lisp_val;
977 return ext;
981 /***********************************************************************
982 Image type independent image structures
983 ***********************************************************************/
985 static struct image *make_image (Lisp_Object spec, unsigned hash);
986 static void free_image (struct frame *f, struct image *img);
987 static int check_image_size (struct frame *f, int width, int height);
989 #define MAX_IMAGE_SIZE 6.0
990 /* Allocate and return a new image structure for image specification
991 SPEC. SPEC has a hash value of HASH. */
993 static struct image *
994 make_image (Lisp_Object spec, unsigned int hash)
996 struct image *img = (struct image *) xmalloc (sizeof *img);
997 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
999 xassert (valid_image_p (spec));
1000 memset (img, 0, sizeof *img);
1001 img->dependencies = NILP (file) ? Qnil : list1 (file);
1002 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1003 xassert (img->type != NULL);
1004 img->spec = spec;
1005 img->data.lisp_val = Qnil;
1006 img->ascent = DEFAULT_IMAGE_ASCENT;
1007 img->hash = hash;
1008 img->corners[BOT_CORNER] = -1; /* Full image */
1009 return img;
1013 /* Free image IMG which was used on frame F, including its resources. */
1015 static void
1016 free_image (struct frame *f, struct image *img)
1018 if (img)
1020 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1022 /* Remove IMG from the hash table of its cache. */
1023 if (img->prev)
1024 img->prev->next = img->next;
1025 else
1026 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1028 if (img->next)
1029 img->next->prev = img->prev;
1031 c->images[img->id] = NULL;
1033 /* Free resources, then free IMG. */
1034 img->type->free (f, img);
1035 xfree (img);
1039 /* Return 1 if the given widths and heights are valid for display;
1040 otherwise, return 0. */
1043 check_image_size (struct frame *f, int width, int height)
1045 int w, h;
1047 if (width <= 0 || height <= 0)
1048 return 0;
1050 if (INTEGERP (Vmax_image_size))
1051 w = h = XINT (Vmax_image_size);
1052 else if (FLOATP (Vmax_image_size))
1054 if (f != NULL)
1056 w = FRAME_PIXEL_WIDTH (f);
1057 h = FRAME_PIXEL_HEIGHT (f);
1059 else
1060 w = h = 1024; /* Arbitrary size for unknown frame. */
1061 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1062 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1064 else
1065 return 1;
1067 return (width <= w && height <= h);
1070 /* Prepare image IMG for display on frame F. Must be called before
1071 drawing an image. */
1073 void
1074 prepare_image_for_display (struct frame *f, struct image *img)
1076 EMACS_TIME t;
1078 /* We're about to display IMG, so set its timestamp to `now'. */
1079 EMACS_GET_TIME (t);
1080 img->timestamp = EMACS_SECS (t);
1082 /* If IMG doesn't have a pixmap yet, load it now, using the image
1083 type dependent loader function. */
1084 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1085 img->load_failed_p = img->type->load (f, img) == 0;
1090 /* Value is the number of pixels for the ascent of image IMG when
1091 drawn in face FACE. */
1094 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1096 int height;
1097 int ascent;
1099 if (slice->height == img->height)
1100 height = img->height + img->vmargin;
1101 else if (slice->y == 0)
1102 height = slice->height + img->vmargin;
1103 else
1104 height = slice->height;
1106 if (img->ascent == CENTERED_IMAGE_ASCENT)
1108 if (face->font)
1110 #ifdef HAVE_NTGUI
1111 /* W32 specific version. Why?. ++kfs */
1112 ascent = height / 2 - (FONT_DESCENT (face->font)
1113 - FONT_BASE (face->font)) / 2;
1114 #else
1115 /* This expression is arranged so that if the image can't be
1116 exactly centered, it will be moved slightly up. This is
1117 because a typical font is `top-heavy' (due to the presence
1118 uppercase letters), so the image placement should err towards
1119 being top-heavy too. It also just generally looks better. */
1120 ascent = (height + FONT_BASE(face->font)
1121 - FONT_DESCENT(face->font) + 1) / 2;
1122 #endif /* HAVE_NTGUI */
1124 else
1125 ascent = height / 2;
1127 else
1128 ascent = (int) (height * img->ascent / 100.0);
1130 return ascent;
1134 /* Image background colors. */
1136 /* Find the "best" corner color of a bitmap.
1137 On W32, XIMG is assumed to a device context with the bitmap selected. */
1139 static RGB_PIXEL_COLOR
1140 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1141 unsigned long width, unsigned long height)
1143 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1144 int i, best_count;
1146 if (corners && corners[BOT_CORNER] >= 0)
1148 /* Get the colors at the corner_pixels of ximg. */
1149 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1150 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1151 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1152 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1154 else
1156 /* Get the colors at the corner_pixels of ximg. */
1157 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1158 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1159 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1160 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1162 /* Choose the most frequently found color as background. */
1163 for (i = best_count = 0; i < 4; ++i)
1165 int j, n;
1167 for (j = n = 0; j < 4; ++j)
1168 if (corner_pixels[i] == corner_pixels[j])
1169 ++n;
1171 if (n > best_count)
1172 best = corner_pixels[i], best_count = n;
1175 return best;
1178 /* Portability macros */
1180 #ifdef HAVE_NTGUI
1182 #define Destroy_Image(img_dc, prev) \
1183 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1185 #define Free_Pixmap(display, pixmap) \
1186 DeleteObject (pixmap)
1188 #elif defined (HAVE_NS)
1190 #define Destroy_Image(ximg, dummy) \
1191 ns_release_object (ximg)
1193 #define Free_Pixmap(display, pixmap) \
1194 ns_release_object (pixmap)
1196 #else
1198 #define Destroy_Image(ximg, dummy) \
1199 XDestroyImage (ximg)
1201 #define Free_Pixmap(display, pixmap) \
1202 XFreePixmap (display, pixmap)
1204 #endif /* !HAVE_NTGUI && !HAVE_NS */
1207 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1208 it is guessed heuristically. If non-zero, XIMG is an existing
1209 XImage object (or device context with the image selected on W32) to
1210 use for the heuristic. */
1212 RGB_PIXEL_COLOR
1213 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1215 if (! img->background_valid)
1216 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1218 int free_ximg = !ximg;
1219 #ifdef HAVE_NTGUI
1220 HGDIOBJ prev;
1221 #endif /* HAVE_NTGUI */
1223 if (free_ximg)
1225 #ifndef HAVE_NTGUI
1226 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1227 0, 0, img->width, img->height, ~0, ZPixmap);
1228 #else
1229 HDC frame_dc = get_frame_dc (f);
1230 ximg = CreateCompatibleDC (frame_dc);
1231 release_frame_dc (f, frame_dc);
1232 prev = SelectObject (ximg, img->pixmap);
1233 #endif /* !HAVE_NTGUI */
1236 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1238 if (free_ximg)
1239 Destroy_Image (ximg, prev);
1241 img->background_valid = 1;
1244 return img->background;
1247 /* Return the `background_transparent' field of IMG. If IMG doesn't
1248 have one yet, it is guessed heuristically. If non-zero, MASK is an
1249 existing XImage object to use for the heuristic. */
1252 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1254 if (! img->background_transparent_valid)
1255 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1257 if (img->mask)
1259 int free_mask = !mask;
1260 #ifdef HAVE_NTGUI
1261 HGDIOBJ prev;
1262 #endif /* HAVE_NTGUI */
1264 if (free_mask)
1266 #ifndef HAVE_NTGUI
1267 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1268 0, 0, img->width, img->height, ~0, ZPixmap);
1269 #else
1270 HDC frame_dc = get_frame_dc (f);
1271 mask = CreateCompatibleDC (frame_dc);
1272 release_frame_dc (f, frame_dc);
1273 prev = SelectObject (mask, img->mask);
1274 #endif /* HAVE_NTGUI */
1277 img->background_transparent
1278 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1280 if (free_mask)
1281 Destroy_Image (mask, prev);
1283 else
1284 img->background_transparent = 0;
1286 img->background_transparent_valid = 1;
1289 return img->background_transparent;
1293 /***********************************************************************
1294 Helper functions for X image types
1295 ***********************************************************************/
1297 static void x_clear_image_1 (struct frame *, struct image *, int,
1298 int, int);
1299 static void x_clear_image (struct frame *f, struct image *img);
1300 static unsigned long x_alloc_image_color (struct frame *f,
1301 struct image *img,
1302 Lisp_Object color_name,
1303 unsigned long dflt);
1306 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1307 free the pixmap if any. MASK_P non-zero means clear the mask
1308 pixmap if any. COLORS_P non-zero means free colors allocated for
1309 the image, if any. */
1311 static void
1312 x_clear_image_1 (struct frame *f, struct image *img, int pixmap_p, int mask_p,
1313 int colors_p)
1315 if (pixmap_p && img->pixmap)
1317 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1318 img->pixmap = NO_PIXMAP;
1319 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1320 img->background_valid = 0;
1323 if (mask_p && img->mask)
1325 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1326 img->mask = NO_PIXMAP;
1327 img->background_transparent_valid = 0;
1330 if (colors_p && img->ncolors)
1332 /* W32_TODO: color table support. */
1333 #ifdef HAVE_X_WINDOWS
1334 x_free_colors (f, img->colors, img->ncolors);
1335 #endif /* HAVE_X_WINDOWS */
1336 xfree (img->colors);
1337 img->colors = NULL;
1338 img->ncolors = 0;
1343 /* Free X resources of image IMG which is used on frame F. */
1345 static void
1346 x_clear_image (struct frame *f, struct image *img)
1348 BLOCK_INPUT;
1349 x_clear_image_1 (f, img, 1, 1, 1);
1350 UNBLOCK_INPUT;
1354 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1355 cannot be allocated, use DFLT. Add a newly allocated color to
1356 IMG->colors, so that it can be freed again. Value is the pixel
1357 color. */
1359 static unsigned long
1360 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1361 unsigned long dflt)
1363 XColor color;
1364 unsigned long result;
1366 xassert (STRINGP (color_name));
1368 if (x_defined_color (f, SSDATA (color_name), &color, 1))
1370 /* This isn't called frequently so we get away with simply
1371 reallocating the color vector to the needed size, here. */
1372 ++img->ncolors;
1373 img->colors =
1374 (unsigned long *) xrealloc (img->colors,
1375 img->ncolors * sizeof *img->colors);
1376 img->colors[img->ncolors - 1] = color.pixel;
1377 result = color.pixel;
1379 else
1380 result = dflt;
1382 return result;
1387 /***********************************************************************
1388 Image Cache
1389 ***********************************************************************/
1391 static struct image *search_image_cache (struct frame *, Lisp_Object, unsigned);
1392 static void cache_image (struct frame *f, struct image *img);
1393 static void postprocess_image (struct frame *, struct image *);
1395 /* Return a new, initialized image cache that is allocated from the
1396 heap. Call free_image_cache to free an image cache. */
1398 struct image_cache *
1399 make_image_cache (void)
1401 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1402 int size;
1404 memset (c, 0, sizeof *c);
1405 c->size = 50;
1406 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1407 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1408 c->buckets = (struct image **) xmalloc (size);
1409 memset (c->buckets, 0, size);
1410 return c;
1414 /* Find an image matching SPEC in the cache, and return it. If no
1415 image is found, return NULL. */
1416 static struct image *
1417 search_image_cache (struct frame *f, Lisp_Object spec, unsigned int hash)
1419 struct image *img;
1420 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1421 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1423 if (!c) return NULL;
1425 /* If the image spec does not specify a background color, the cached
1426 image must have the same background color as the current frame.
1427 The foreground color must also match, for the sake of monochrome
1428 images.
1430 In fact, we could ignore the foreground color matching condition
1431 for color images, or if the image spec specifies :foreground;
1432 similarly we could ignore the background color matching condition
1433 for formats that don't use transparency (such as jpeg), or if the
1434 image spec specifies :background. However, the extra memory
1435 usage is probably negligible in practice, so we don't bother. */
1437 for (img = c->buckets[i]; img; img = img->next)
1438 if (img->hash == hash
1439 && !NILP (Fequal (img->spec, spec))
1440 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1441 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1442 break;
1443 return img;
1447 /* Search frame F for an image with spec SPEC, and free it. */
1449 static void
1450 uncache_image (struct frame *f, Lisp_Object spec)
1452 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1453 if (img)
1455 free_image (f, img);
1456 /* As display glyphs may still be referring to the image ID, we
1457 must garbage the frame (Bug#6426). */
1458 SET_FRAME_GARBAGED (f);
1463 /* Free image cache of frame F. Be aware that X frames share images
1464 caches. */
1466 void
1467 free_image_cache (struct frame *f)
1469 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1470 if (c)
1472 int i;
1474 /* Cache should not be referenced by any frame when freed. */
1475 xassert (c->refcount == 0);
1477 for (i = 0; i < c->used; ++i)
1478 free_image (f, c->images[i]);
1479 xfree (c->images);
1480 xfree (c->buckets);
1481 xfree (c);
1482 FRAME_IMAGE_CACHE (f) = NULL;
1487 /* Clear image cache of frame F. FILTER=t means free all images.
1488 FILTER=nil means clear only images that haven't been
1489 displayed for some time.
1490 Else, only free the images which have FILTER in their `dependencies'.
1491 Should be called from time to time to reduce the number of loaded images.
1492 If image-cache-eviction-delay is non-nil, this frees images in the cache
1493 which weren't displayed for at least that many seconds. */
1495 static void
1496 clear_image_cache (struct frame *f, Lisp_Object filter)
1498 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1500 if (c)
1502 int i, nfreed = 0;
1504 /* Block input so that we won't be interrupted by a SIGIO
1505 while being in an inconsistent state. */
1506 BLOCK_INPUT;
1508 if (!NILP (filter))
1510 /* Filter image cache. */
1511 for (i = 0; i < c->used; ++i)
1513 struct image *img = c->images[i];
1514 if (img && (EQ (Qt, filter)
1515 || !NILP (Fmember (filter, img->dependencies))))
1517 free_image (f, img);
1518 ++nfreed;
1522 else if (INTEGERP (Vimage_cache_eviction_delay))
1524 /* Free cache based on timestamp. */
1525 EMACS_TIME t;
1526 unsigned long old;
1527 int delay, nimages = 0;
1529 for (i = 0; i < c->used; ++i)
1530 if (c->images[i])
1531 nimages++;
1533 /* If the number of cached images has grown unusually large,
1534 decrease the cache eviction delay (Bug#6230). */
1535 delay = XFASTINT (Vimage_cache_eviction_delay);
1536 if (nimages > 40)
1537 delay = max (1, 1600 * delay / (nimages*nimages));
1539 EMACS_GET_TIME (t);
1540 old = EMACS_SECS (t) - delay;
1542 for (i = 0; i < c->used; ++i)
1544 struct image *img = c->images[i];
1545 if (img && img->timestamp < old)
1547 free_image (f, img);
1548 ++nfreed;
1553 /* We may be clearing the image cache because, for example,
1554 Emacs was iconified for a longer period of time. In that
1555 case, current matrices may still contain references to
1556 images freed above. So, clear these matrices. */
1557 if (nfreed)
1559 Lisp_Object tail, frame;
1561 FOR_EACH_FRAME (tail, frame)
1563 struct frame *fr = XFRAME (frame);
1564 if (FRAME_IMAGE_CACHE (fr) == c)
1565 clear_current_matrices (fr);
1568 ++windows_or_buffers_changed;
1571 UNBLOCK_INPUT;
1575 void
1576 clear_image_caches (Lisp_Object filter)
1578 /* FIXME: We want to do
1579 * struct terminal *t;
1580 * for (t = terminal_list; t; t = t->next_terminal)
1581 * clear_image_cache (t, filter); */
1582 Lisp_Object tail, frame;
1583 FOR_EACH_FRAME (tail, frame)
1584 if (FRAME_WINDOW_P (XFRAME (frame)))
1585 clear_image_cache (XFRAME (frame), filter);
1588 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1589 0, 1, 0,
1590 doc: /* Clear the image cache.
1591 FILTER nil or a frame means clear all images in the selected frame.
1592 FILTER t means clear the image caches of all frames.
1593 Anything else, means only clear those images which refer to FILTER,
1594 which is then usually a filename. */)
1595 (Lisp_Object filter)
1597 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1598 clear_image_caches (filter);
1599 else
1600 clear_image_cache (check_x_frame (filter), Qt);
1602 return Qnil;
1606 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1607 1, 2, 0,
1608 doc: /* Fush the image with specification SPEC on frame FRAME.
1609 This removes the image from the Emacs image cache. If SPEC specifies
1610 an image file, the next redisplay of this image will read from the
1611 current contents of that file.
1613 FRAME nil or omitted means use the selected frame.
1614 FRAME t means refresh the image on all frames. */)
1615 (Lisp_Object spec, Lisp_Object frame)
1617 if (!valid_image_p (spec))
1618 error ("Invalid image specification");
1620 if (EQ (frame, Qt))
1622 Lisp_Object tail;
1623 FOR_EACH_FRAME (tail, frame)
1625 struct frame *f = XFRAME (frame);
1626 if (FRAME_WINDOW_P (f))
1627 uncache_image (f, spec);
1630 else
1631 uncache_image (check_x_frame (frame), spec);
1633 return Qnil;
1637 /* Compute masks and transform image IMG on frame F, as specified
1638 by the image's specification, */
1640 static void
1641 postprocess_image (struct frame *f, struct image *img)
1643 /* Manipulation of the image's mask. */
1644 if (img->pixmap)
1646 Lisp_Object conversion, spec;
1647 Lisp_Object mask;
1649 spec = img->spec;
1651 /* `:heuristic-mask t'
1652 `:mask heuristic'
1653 means build a mask heuristically.
1654 `:heuristic-mask (R G B)'
1655 `:mask (heuristic (R G B))'
1656 means build a mask from color (R G B) in the
1657 image.
1658 `:mask nil'
1659 means remove a mask, if any. */
1661 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1662 if (!NILP (mask))
1663 x_build_heuristic_mask (f, img, mask);
1664 else
1666 int found_p;
1668 mask = image_spec_value (spec, QCmask, &found_p);
1670 if (EQ (mask, Qheuristic))
1671 x_build_heuristic_mask (f, img, Qt);
1672 else if (CONSP (mask)
1673 && EQ (XCAR (mask), Qheuristic))
1675 if (CONSP (XCDR (mask)))
1676 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1677 else
1678 x_build_heuristic_mask (f, img, XCDR (mask));
1680 else if (NILP (mask) && found_p && img->mask)
1682 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1683 img->mask = NO_PIXMAP;
1688 /* Should we apply an image transformation algorithm? */
1689 conversion = image_spec_value (spec, QCconversion, NULL);
1690 if (EQ (conversion, Qdisabled))
1691 x_disable_image (f, img);
1692 else if (EQ (conversion, Qlaplace))
1693 x_laplace (f, img);
1694 else if (EQ (conversion, Qemboss))
1695 x_emboss (f, img);
1696 else if (CONSP (conversion)
1697 && EQ (XCAR (conversion), Qedge_detection))
1699 Lisp_Object tem;
1700 tem = XCDR (conversion);
1701 if (CONSP (tem))
1702 x_edge_detection (f, img,
1703 Fplist_get (tem, QCmatrix),
1704 Fplist_get (tem, QCcolor_adjustment));
1710 /* Return the id of image with Lisp specification SPEC on frame F.
1711 SPEC must be a valid Lisp image specification (see valid_image_p). */
1714 lookup_image (struct frame *f, Lisp_Object spec)
1716 struct image *img;
1717 unsigned hash;
1718 EMACS_TIME now;
1720 /* F must be a window-system frame, and SPEC must be a valid image
1721 specification. */
1722 xassert (FRAME_WINDOW_P (f));
1723 xassert (valid_image_p (spec));
1725 /* Look up SPEC in the hash table of the image cache. */
1726 hash = sxhash (spec, 0);
1727 img = search_image_cache (f, spec, hash);
1728 if (img && img->load_failed_p)
1730 free_image (f, img);
1731 img = NULL;
1734 /* If not found, create a new image and cache it. */
1735 if (img == NULL)
1737 BLOCK_INPUT;
1738 img = make_image (spec, hash);
1739 cache_image (f, img);
1740 img->load_failed_p = img->type->load (f, img) == 0;
1741 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1742 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1744 /* If we can't load the image, and we don't have a width and
1745 height, use some arbitrary width and height so that we can
1746 draw a rectangle for it. */
1747 if (img->load_failed_p)
1749 Lisp_Object value;
1751 value = image_spec_value (spec, QCwidth, NULL);
1752 img->width = (INTEGERP (value)
1753 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1754 value = image_spec_value (spec, QCheight, NULL);
1755 img->height = (INTEGERP (value)
1756 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1758 else
1760 /* Handle image type independent image attributes
1761 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1762 `:background COLOR'. */
1763 Lisp_Object ascent, margin, relief, bg;
1765 ascent = image_spec_value (spec, QCascent, NULL);
1766 if (INTEGERP (ascent))
1767 img->ascent = XFASTINT (ascent);
1768 else if (EQ (ascent, Qcenter))
1769 img->ascent = CENTERED_IMAGE_ASCENT;
1771 margin = image_spec_value (spec, QCmargin, NULL);
1772 if (INTEGERP (margin) && XINT (margin) >= 0)
1773 img->vmargin = img->hmargin = XFASTINT (margin);
1774 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1775 && INTEGERP (XCDR (margin)))
1777 if (XINT (XCAR (margin)) > 0)
1778 img->hmargin = XFASTINT (XCAR (margin));
1779 if (XINT (XCDR (margin)) > 0)
1780 img->vmargin = XFASTINT (XCDR (margin));
1783 relief = image_spec_value (spec, QCrelief, NULL);
1784 if (INTEGERP (relief))
1786 img->relief = XINT (relief);
1787 img->hmargin += eabs (img->relief);
1788 img->vmargin += eabs (img->relief);
1791 if (! img->background_valid)
1793 bg = image_spec_value (img->spec, QCbackground, NULL);
1794 if (!NILP (bg))
1796 img->background
1797 = x_alloc_image_color (f, img, bg,
1798 FRAME_BACKGROUND_PIXEL (f));
1799 img->background_valid = 1;
1803 /* Do image transformations and compute masks, unless we
1804 don't have the image yet. */
1805 if (!EQ (*img->type->type, Qpostscript))
1806 postprocess_image (f, img);
1809 UNBLOCK_INPUT;
1812 /* We're using IMG, so set its timestamp to `now'. */
1813 EMACS_GET_TIME (now);
1814 img->timestamp = EMACS_SECS (now);
1816 /* Value is the image id. */
1817 return img->id;
1821 /* Cache image IMG in the image cache of frame F. */
1823 static void
1824 cache_image (struct frame *f, struct image *img)
1826 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1827 int i;
1829 /* Find a free slot in c->images. */
1830 for (i = 0; i < c->used; ++i)
1831 if (c->images[i] == NULL)
1832 break;
1834 /* If no free slot found, maybe enlarge c->images. */
1835 if (i == c->used && c->used == c->size)
1837 c->size *= 2;
1838 c->images = (struct image **) xrealloc (c->images,
1839 c->size * sizeof *c->images);
1842 /* Add IMG to c->images, and assign IMG an id. */
1843 c->images[i] = img;
1844 img->id = i;
1845 if (i == c->used)
1846 ++c->used;
1848 /* Add IMG to the cache's hash table. */
1849 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1850 img->next = c->buckets[i];
1851 if (img->next)
1852 img->next->prev = img;
1853 img->prev = NULL;
1854 c->buckets[i] = img;
1858 /* Call FN on every image in the image cache of frame F. Used to mark
1859 Lisp Objects in the image cache. */
1861 /* Mark Lisp objects in image IMG. */
1863 static void
1864 mark_image (struct image *img)
1866 mark_object (img->spec);
1867 mark_object (img->dependencies);
1869 if (!NILP (img->data.lisp_val))
1870 mark_object (img->data.lisp_val);
1874 void
1875 mark_image_cache (struct image_cache *c)
1877 if (c)
1879 int i;
1880 for (i = 0; i < c->used; ++i)
1881 if (c->images[i])
1882 mark_image (c->images[i]);
1888 /***********************************************************************
1889 X / NS / W32 support code
1890 ***********************************************************************/
1892 #ifdef HAVE_NTGUI
1894 /* Macro for defining functions that will be loaded from image DLLs. */
1895 #define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
1897 /* Macro for loading those image functions from the library. */
1898 #define LOAD_IMGLIB_FN(lib,func) { \
1899 fn_##func = (void *) GetProcAddress (lib, #func); \
1900 if (!fn_##func) return 0; \
1903 #endif /* HAVE_NTGUI */
1905 static int x_create_x_image_and_pixmap (struct frame *, int, int, int,
1906 XImagePtr *, Pixmap *);
1907 static void x_destroy_x_image (XImagePtr);
1908 static void x_put_x_image (struct frame *, XImagePtr, Pixmap, int, int);
1911 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1912 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1913 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1914 via xmalloc. Print error messages via image_error if an error
1915 occurs. Value is non-zero if successful.
1917 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1918 should indicate the bit depth of the image. */
1920 static int
1921 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1922 XImagePtr *ximg, Pixmap *pixmap)
1924 #ifdef HAVE_X_WINDOWS
1925 Display *display = FRAME_X_DISPLAY (f);
1926 Window window = FRAME_X_WINDOW (f);
1927 Screen *screen = FRAME_X_SCREEN (f);
1929 xassert (interrupt_input_blocked);
1931 if (depth <= 0)
1932 depth = DefaultDepthOfScreen (screen);
1933 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1934 depth, ZPixmap, 0, NULL, width, height,
1935 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1936 if (*ximg == NULL)
1938 image_error ("Unable to allocate X image", Qnil, Qnil);
1939 return 0;
1942 /* Allocate image raster. */
1943 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
1945 /* Allocate a pixmap of the same size. */
1946 *pixmap = XCreatePixmap (display, window, width, height, depth);
1947 if (*pixmap == NO_PIXMAP)
1949 x_destroy_x_image (*ximg);
1950 *ximg = NULL;
1951 image_error ("Unable to create X pixmap", Qnil, Qnil);
1952 return 0;
1955 return 1;
1956 #endif /* HAVE_X_WINDOWS */
1958 #ifdef HAVE_NTGUI
1960 BITMAPINFOHEADER *header;
1961 HDC hdc;
1962 int scanline_width_bits;
1963 int remainder;
1964 int palette_colors = 0;
1966 if (depth == 0)
1967 depth = 24;
1969 if (depth != 1 && depth != 4 && depth != 8
1970 && depth != 16 && depth != 24 && depth != 32)
1972 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1973 return 0;
1976 scanline_width_bits = width * depth;
1977 remainder = scanline_width_bits % 32;
1979 if (remainder)
1980 scanline_width_bits += 32 - remainder;
1982 /* Bitmaps with a depth less than 16 need a palette. */
1983 /* BITMAPINFO structure already contains the first RGBQUAD. */
1984 if (depth < 16)
1985 palette_colors = 1 << depth - 1;
1987 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1988 if (*ximg == NULL)
1990 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
1991 return 0;
1994 header = &(*ximg)->info.bmiHeader;
1995 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
1996 header->biSize = sizeof (*header);
1997 header->biWidth = width;
1998 header->biHeight = -height; /* negative indicates a top-down bitmap. */
1999 header->biPlanes = 1;
2000 header->biBitCount = depth;
2001 header->biCompression = BI_RGB;
2002 header->biClrUsed = palette_colors;
2004 /* TODO: fill in palette. */
2005 if (depth == 1)
2007 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2008 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2009 (*ximg)->info.bmiColors[0].rgbRed = 0;
2010 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2011 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2012 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2013 (*ximg)->info.bmiColors[1].rgbRed = 255;
2014 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2017 hdc = get_frame_dc (f);
2019 /* Create a DIBSection and raster array for the bitmap,
2020 and store its handle in *pixmap. */
2021 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2022 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2023 /* casting avoids a GCC warning */
2024 (void **)&((*ximg)->data), NULL, 0);
2026 /* Realize display palette and garbage all frames. */
2027 release_frame_dc (f, hdc);
2029 if (*pixmap == NULL)
2031 DWORD err = GetLastError ();
2032 Lisp_Object errcode;
2033 /* All system errors are < 10000, so the following is safe. */
2034 XSETINT (errcode, (int) err);
2035 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2036 x_destroy_x_image (*ximg);
2037 return 0;
2040 return 1;
2042 #endif /* HAVE_NTGUI */
2044 #ifdef HAVE_NS
2045 *pixmap = ns_image_for_XPM (width, height, depth);
2046 if (*pixmap == 0)
2048 *ximg = NULL;
2049 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2050 return 0;
2052 *ximg = *pixmap;
2053 return 1;
2054 #endif
2058 /* Destroy XImage XIMG. Free XIMG->data. */
2060 static void
2061 x_destroy_x_image (XImagePtr ximg)
2063 xassert (interrupt_input_blocked);
2064 if (ximg)
2066 #ifdef HAVE_X_WINDOWS
2067 xfree (ximg->data);
2068 ximg->data = NULL;
2069 XDestroyImage (ximg);
2070 #endif /* HAVE_X_WINDOWS */
2071 #ifdef HAVE_NTGUI
2072 /* Data will be freed by DestroyObject. */
2073 ximg->data = NULL;
2074 xfree (ximg);
2075 #endif /* HAVE_NTGUI */
2076 #ifdef HAVE_NS
2077 ns_release_object (ximg);
2078 #endif /* HAVE_NS */
2083 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2084 are width and height of both the image and pixmap. */
2086 static void
2087 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2089 #ifdef HAVE_X_WINDOWS
2090 GC gc;
2092 xassert (interrupt_input_blocked);
2093 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2094 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2095 XFreeGC (FRAME_X_DISPLAY (f), gc);
2096 #endif /* HAVE_X_WINDOWS */
2098 #ifdef HAVE_NTGUI
2099 #if 0 /* I don't think this is necessary looking at where it is used. */
2100 HDC hdc = get_frame_dc (f);
2101 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2102 release_frame_dc (f, hdc);
2103 #endif
2104 #endif /* HAVE_NTGUI */
2106 #ifdef HAVE_NS
2107 xassert (ximg == pixmap);
2108 ns_retain_object (ximg);
2109 #endif
2113 /***********************************************************************
2114 File Handling
2115 ***********************************************************************/
2117 static unsigned char *slurp_file (char *, int *);
2120 /* Find image file FILE. Look in data-directory/images, then
2121 x-bitmap-file-path. Value is the encoded full name of the file
2122 found, or nil if not found. */
2124 Lisp_Object
2125 x_find_image_file (Lisp_Object file)
2127 Lisp_Object file_found, search_path;
2128 int fd;
2130 /* TODO I think this should use something like image-load-path
2131 instead. Unfortunately, that can contain non-string elements. */
2132 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2133 Vdata_directory),
2134 Vx_bitmap_file_path);
2136 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2137 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2139 if (fd == -1)
2140 file_found = Qnil;
2141 else
2143 file_found = ENCODE_FILE (file_found);
2144 close (fd);
2147 return file_found;
2151 /* Read FILE into memory. Value is a pointer to a buffer allocated
2152 with xmalloc holding FILE's contents. Value is null if an error
2153 occurred. *SIZE is set to the size of the file. */
2155 static unsigned char *
2156 slurp_file (char *file, int *size)
2158 FILE *fp = NULL;
2159 unsigned char *buf = NULL;
2160 struct stat st;
2162 if (stat (file, &st) == 0
2163 && (fp = fopen (file, "rb")) != NULL
2164 && (buf = (unsigned char *) xmalloc (st.st_size),
2165 fread (buf, 1, st.st_size, fp) == st.st_size))
2167 *size = st.st_size;
2168 fclose (fp);
2170 else
2172 if (fp)
2173 fclose (fp);
2174 if (buf)
2176 xfree (buf);
2177 buf = NULL;
2181 return buf;
2186 /***********************************************************************
2187 XBM images
2188 ***********************************************************************/
2190 static int xbm_scan (unsigned char **, unsigned char *, char *, int *);
2191 static int xbm_load (struct frame *f, struct image *img);
2192 static int xbm_load_image (struct frame *f, struct image *img,
2193 unsigned char *, unsigned char *);
2194 static int xbm_image_p (Lisp_Object object);
2195 static int xbm_read_bitmap_data (struct frame *f,
2196 unsigned char *, unsigned char *,
2197 int *, int *, char **, int);
2198 static int xbm_file_p (Lisp_Object);
2201 /* Indices of image specification fields in xbm_format, below. */
2203 enum xbm_keyword_index
2205 XBM_TYPE,
2206 XBM_FILE,
2207 XBM_WIDTH,
2208 XBM_HEIGHT,
2209 XBM_DATA,
2210 XBM_FOREGROUND,
2211 XBM_BACKGROUND,
2212 XBM_ASCENT,
2213 XBM_MARGIN,
2214 XBM_RELIEF,
2215 XBM_ALGORITHM,
2216 XBM_HEURISTIC_MASK,
2217 XBM_MASK,
2218 XBM_LAST
2221 /* Vector of image_keyword structures describing the format
2222 of valid XBM image specifications. */
2224 static const struct image_keyword xbm_format[XBM_LAST] =
2226 {":type", IMAGE_SYMBOL_VALUE, 1},
2227 {":file", IMAGE_STRING_VALUE, 0},
2228 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2229 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2230 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2231 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2232 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2233 {":ascent", IMAGE_ASCENT_VALUE, 0},
2234 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2235 {":relief", IMAGE_INTEGER_VALUE, 0},
2236 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2237 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2238 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2241 /* Structure describing the image type XBM. */
2243 static struct image_type xbm_type =
2245 &Qxbm,
2246 xbm_image_p,
2247 xbm_load,
2248 x_clear_image,
2249 NULL
2252 /* Tokens returned from xbm_scan. */
2254 enum xbm_token
2256 XBM_TK_IDENT = 256,
2257 XBM_TK_NUMBER
2261 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2262 A valid specification is a list starting with the symbol `image'
2263 The rest of the list is a property list which must contain an
2264 entry `:type xbm..
2266 If the specification specifies a file to load, it must contain
2267 an entry `:file FILENAME' where FILENAME is a string.
2269 If the specification is for a bitmap loaded from memory it must
2270 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2271 WIDTH and HEIGHT are integers > 0. DATA may be:
2273 1. a string large enough to hold the bitmap data, i.e. it must
2274 have a size >= (WIDTH + 7) / 8 * HEIGHT
2276 2. a bool-vector of size >= WIDTH * HEIGHT
2278 3. a vector of strings or bool-vectors, one for each line of the
2279 bitmap.
2281 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2282 may not be specified in this case because they are defined in the
2283 XBM file.
2285 Both the file and data forms may contain the additional entries
2286 `:background COLOR' and `:foreground COLOR'. If not present,
2287 foreground and background of the frame on which the image is
2288 displayed is used. */
2290 static int
2291 xbm_image_p (Lisp_Object object)
2293 struct image_keyword kw[XBM_LAST];
2295 memcpy (kw, xbm_format, sizeof kw);
2296 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2297 return 0;
2299 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2301 if (kw[XBM_FILE].count)
2303 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2304 return 0;
2306 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2308 /* In-memory XBM file. */
2309 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2310 return 0;
2312 else
2314 Lisp_Object data;
2315 int width, height;
2317 /* Entries for `:width', `:height' and `:data' must be present. */
2318 if (!kw[XBM_WIDTH].count
2319 || !kw[XBM_HEIGHT].count
2320 || !kw[XBM_DATA].count)
2321 return 0;
2323 data = kw[XBM_DATA].value;
2324 width = XFASTINT (kw[XBM_WIDTH].value);
2325 height = XFASTINT (kw[XBM_HEIGHT].value);
2327 /* Check type of data, and width and height against contents of
2328 data. */
2329 if (VECTORP (data))
2331 int i;
2333 /* Number of elements of the vector must be >= height. */
2334 if (ASIZE (data) < height)
2335 return 0;
2337 /* Each string or bool-vector in data must be large enough
2338 for one line of the image. */
2339 for (i = 0; i < height; ++i)
2341 Lisp_Object elt = XVECTOR (data)->contents[i];
2343 if (STRINGP (elt))
2345 if (SCHARS (elt)
2346 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2347 return 0;
2349 else if (BOOL_VECTOR_P (elt))
2351 if (XBOOL_VECTOR (elt)->size < width)
2352 return 0;
2354 else
2355 return 0;
2358 else if (STRINGP (data))
2360 if (SCHARS (data)
2361 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2362 return 0;
2364 else if (BOOL_VECTOR_P (data))
2366 if (XBOOL_VECTOR (data)->size < width * height)
2367 return 0;
2369 else
2370 return 0;
2373 return 1;
2377 /* Scan a bitmap file. FP is the stream to read from. Value is
2378 either an enumerator from enum xbm_token, or a character for a
2379 single-character token, or 0 at end of file. If scanning an
2380 identifier, store the lexeme of the identifier in SVAL. If
2381 scanning a number, store its value in *IVAL. */
2383 static int
2384 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2386 unsigned int c;
2388 loop:
2390 /* Skip white space. */
2391 while (*s < end && (c = *(*s)++, isspace (c)))
2394 if (*s >= end)
2395 c = 0;
2396 else if (isdigit (c))
2398 int value = 0, digit;
2400 if (c == '0' && *s < end)
2402 c = *(*s)++;
2403 if (c == 'x' || c == 'X')
2405 while (*s < end)
2407 c = *(*s)++;
2408 if (isdigit (c))
2409 digit = c - '0';
2410 else if (c >= 'a' && c <= 'f')
2411 digit = c - 'a' + 10;
2412 else if (c >= 'A' && c <= 'F')
2413 digit = c - 'A' + 10;
2414 else
2415 break;
2416 value = 16 * value + digit;
2419 else if (isdigit (c))
2421 value = c - '0';
2422 while (*s < end
2423 && (c = *(*s)++, isdigit (c)))
2424 value = 8 * value + c - '0';
2427 else
2429 value = c - '0';
2430 while (*s < end
2431 && (c = *(*s)++, isdigit (c)))
2432 value = 10 * value + c - '0';
2435 if (*s < end)
2436 *s = *s - 1;
2437 *ival = value;
2438 c = XBM_TK_NUMBER;
2440 else if (isalpha (c) || c == '_')
2442 *sval++ = c;
2443 while (*s < end
2444 && (c = *(*s)++, (isalnum (c) || c == '_')))
2445 *sval++ = c;
2446 *sval = 0;
2447 if (*s < end)
2448 *s = *s - 1;
2449 c = XBM_TK_IDENT;
2451 else if (c == '/' && **s == '*')
2453 /* C-style comment. */
2454 ++*s;
2455 while (**s && (**s != '*' || *(*s + 1) != '/'))
2456 ++*s;
2457 if (**s)
2459 *s += 2;
2460 goto loop;
2464 return c;
2467 #ifdef HAVE_NTGUI
2469 /* Create a Windows bitmap from X bitmap data. */
2470 static HBITMAP
2471 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2473 static unsigned char swap_nibble[16]
2474 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2475 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2476 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2477 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2478 int i, j, w1, w2;
2479 unsigned char *bits, *p;
2480 HBITMAP bmp;
2482 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2483 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2484 bits = (unsigned char *) alloca (height * w2);
2485 memset (bits, 0, height * w2);
2486 for (i = 0; i < height; i++)
2488 p = bits + i*w2;
2489 for (j = 0; j < w1; j++)
2491 /* Bitswap XBM bytes to match how Windows does things. */
2492 unsigned char c = *data++;
2493 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2494 | (swap_nibble[(c>>4) & 0xf]));
2497 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2499 return bmp;
2502 static void
2503 convert_mono_to_color_image (struct frame *f, struct image *img,
2504 COLORREF foreground, COLORREF background)
2506 HDC hdc, old_img_dc, new_img_dc;
2507 HGDIOBJ old_prev, new_prev;
2508 HBITMAP new_pixmap;
2510 hdc = get_frame_dc (f);
2511 old_img_dc = CreateCompatibleDC (hdc);
2512 new_img_dc = CreateCompatibleDC (hdc);
2513 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2514 release_frame_dc (f, hdc);
2515 old_prev = SelectObject (old_img_dc, img->pixmap);
2516 new_prev = SelectObject (new_img_dc, new_pixmap);
2517 /* Windows convention for mono bitmaps is black = background,
2518 white = foreground. */
2519 SetTextColor (new_img_dc, background);
2520 SetBkColor (new_img_dc, foreground);
2522 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2523 0, 0, SRCCOPY);
2525 SelectObject (old_img_dc, old_prev);
2526 SelectObject (new_img_dc, new_prev);
2527 DeleteDC (old_img_dc);
2528 DeleteDC (new_img_dc);
2529 DeleteObject (img->pixmap);
2530 if (new_pixmap == 0)
2531 fprintf (stderr, "Failed to convert image to color.\n");
2532 else
2533 img->pixmap = new_pixmap;
2536 #define XBM_BIT_SHUFFLE(b) (~(b))
2538 #else
2540 #define XBM_BIT_SHUFFLE(b) (b)
2542 #endif /* HAVE_NTGUI */
2545 static void
2546 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2547 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2548 int non_default_colors)
2550 #ifdef HAVE_NTGUI
2551 img->pixmap
2552 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2554 /* If colors were specified, transfer the bitmap to a color one. */
2555 if (non_default_colors)
2556 convert_mono_to_color_image (f, img, fg, bg);
2558 #elif defined (HAVE_NS)
2559 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2561 #else
2562 img->pixmap
2563 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2564 FRAME_X_WINDOW (f),
2565 data,
2566 img->width, img->height,
2567 fg, bg,
2568 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2569 #endif /* !HAVE_NTGUI && !HAVE_NS */
2574 /* Replacement for XReadBitmapFileData which isn't available under old
2575 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2576 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2577 the image. Return in *DATA the bitmap data allocated with xmalloc.
2578 Value is non-zero if successful. DATA null means just test if
2579 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR
2580 is non-zero, inhibit the call to image_error when the image size is
2581 invalid (the bitmap remains unread). */
2583 static int
2584 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2585 int *width, int *height, char **data,
2586 int inhibit_image_error)
2588 unsigned char *s = contents;
2589 char buffer[BUFSIZ];
2590 int padding_p = 0;
2591 int v10 = 0;
2592 int bytes_per_line, i, nbytes;
2593 char *p;
2594 int value;
2595 int LA1;
2597 #define match() \
2598 LA1 = xbm_scan (&s, end, buffer, &value)
2600 #define expect(TOKEN) \
2601 if (LA1 != (TOKEN)) \
2602 goto failure; \
2603 else \
2604 match ()
2606 #define expect_ident(IDENT) \
2607 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2608 match (); \
2609 else \
2610 goto failure
2612 *width = *height = -1;
2613 if (data)
2614 *data = NULL;
2615 LA1 = xbm_scan (&s, end, buffer, &value);
2617 /* Parse defines for width, height and hot-spots. */
2618 while (LA1 == '#')
2620 match ();
2621 expect_ident ("define");
2622 expect (XBM_TK_IDENT);
2624 if (LA1 == XBM_TK_NUMBER)
2626 char *q = strrchr (buffer, '_');
2627 q = q ? q + 1 : buffer;
2628 if (strcmp (q, "width") == 0)
2629 *width = value;
2630 else if (strcmp (q, "height") == 0)
2631 *height = value;
2633 expect (XBM_TK_NUMBER);
2636 if (!check_image_size (f, *width, *height))
2638 if (!inhibit_image_error)
2639 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2640 goto failure;
2642 else if (data == NULL)
2643 goto success;
2645 /* Parse bits. Must start with `static'. */
2646 expect_ident ("static");
2647 if (LA1 == XBM_TK_IDENT)
2649 if (strcmp (buffer, "unsigned") == 0)
2651 match ();
2652 expect_ident ("char");
2654 else if (strcmp (buffer, "short") == 0)
2656 match ();
2657 v10 = 1;
2658 if (*width % 16 && *width % 16 < 9)
2659 padding_p = 1;
2661 else if (strcmp (buffer, "char") == 0)
2662 match ();
2663 else
2664 goto failure;
2666 else
2667 goto failure;
2669 expect (XBM_TK_IDENT);
2670 expect ('[');
2671 expect (']');
2672 expect ('=');
2673 expect ('{');
2675 bytes_per_line = (*width + 7) / 8 + padding_p;
2676 nbytes = bytes_per_line * *height;
2677 p = *data = (char *) xmalloc (nbytes);
2679 if (v10)
2681 for (i = 0; i < nbytes; i += 2)
2683 int val = value;
2684 expect (XBM_TK_NUMBER);
2686 *p++ = XBM_BIT_SHUFFLE (val);
2687 if (!padding_p || ((i + 2) % bytes_per_line))
2688 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2690 if (LA1 == ',' || LA1 == '}')
2691 match ();
2692 else
2693 goto failure;
2696 else
2698 for (i = 0; i < nbytes; ++i)
2700 int val = value;
2701 expect (XBM_TK_NUMBER);
2703 *p++ = XBM_BIT_SHUFFLE (val);
2705 if (LA1 == ',' || LA1 == '}')
2706 match ();
2707 else
2708 goto failure;
2712 success:
2713 return 1;
2715 failure:
2717 if (data && *data)
2719 xfree (*data);
2720 *data = NULL;
2722 return 0;
2724 #undef match
2725 #undef expect
2726 #undef expect_ident
2730 /* Load XBM image IMG which will be displayed on frame F from buffer
2731 CONTENTS. END is the end of the buffer. Value is non-zero if
2732 successful. */
2734 static int
2735 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2736 unsigned char *end)
2738 int rc;
2739 char *data;
2740 int success_p = 0;
2742 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2743 &data, 0);
2744 if (rc)
2746 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2747 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2748 int non_default_colors = 0;
2749 Lisp_Object value;
2751 xassert (img->width > 0 && img->height > 0);
2753 /* Get foreground and background colors, maybe allocate colors. */
2754 value = image_spec_value (img->spec, QCforeground, NULL);
2755 if (!NILP (value))
2757 foreground = x_alloc_image_color (f, img, value, foreground);
2758 non_default_colors = 1;
2760 value = image_spec_value (img->spec, QCbackground, NULL);
2761 if (!NILP (value))
2763 background = x_alloc_image_color (f, img, value, background);
2764 img->background = background;
2765 img->background_valid = 1;
2766 non_default_colors = 1;
2769 Create_Pixmap_From_Bitmap_Data (f, img, data,
2770 foreground, background,
2771 non_default_colors);
2772 xfree (data);
2774 if (img->pixmap == NO_PIXMAP)
2776 x_clear_image (f, img);
2777 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2779 else
2780 success_p = 1;
2782 else
2783 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2785 return success_p;
2789 /* Value is non-zero if DATA looks like an in-memory XBM file. */
2791 static int
2792 xbm_file_p (Lisp_Object data)
2794 int w, h;
2795 return (STRINGP (data)
2796 && xbm_read_bitmap_data (NULL, SDATA (data),
2797 (SDATA (data) + SBYTES (data)),
2798 &w, &h, NULL, 1));
2802 /* Fill image IMG which is used on frame F with pixmap data. Value is
2803 non-zero if successful. */
2805 static int
2806 xbm_load (struct frame *f, struct image *img)
2808 int success_p = 0;
2809 Lisp_Object file_name;
2811 xassert (xbm_image_p (img->spec));
2813 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2814 file_name = image_spec_value (img->spec, QCfile, NULL);
2815 if (STRINGP (file_name))
2817 Lisp_Object file;
2818 unsigned char *contents;
2819 int size;
2821 file = x_find_image_file (file_name);
2822 if (!STRINGP (file))
2824 image_error ("Cannot find image file `%s'", file_name, Qnil);
2825 return 0;
2828 contents = slurp_file (SSDATA (file), &size);
2829 if (contents == NULL)
2831 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2832 return 0;
2835 success_p = xbm_load_image (f, img, contents, contents + size);
2837 else
2839 struct image_keyword fmt[XBM_LAST];
2840 Lisp_Object data;
2841 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2842 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2843 int non_default_colors = 0;
2844 char *bits;
2845 int parsed_p;
2846 int in_memory_file_p = 0;
2848 /* See if data looks like an in-memory XBM file. */
2849 data = image_spec_value (img->spec, QCdata, NULL);
2850 in_memory_file_p = xbm_file_p (data);
2852 /* Parse the image specification. */
2853 memcpy (fmt, xbm_format, sizeof fmt);
2854 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2855 (void) parsed_p;
2856 xassert (parsed_p);
2858 /* Get specified width, and height. */
2859 if (!in_memory_file_p)
2861 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2862 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2863 xassert (img->width > 0 && img->height > 0);
2866 /* Get foreground and background colors, maybe allocate colors. */
2867 if (fmt[XBM_FOREGROUND].count
2868 && STRINGP (fmt[XBM_FOREGROUND].value))
2870 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2871 foreground);
2872 non_default_colors = 1;
2875 if (fmt[XBM_BACKGROUND].count
2876 && STRINGP (fmt[XBM_BACKGROUND].value))
2878 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2879 background);
2880 non_default_colors = 1;
2883 if (in_memory_file_p)
2884 success_p = xbm_load_image (f, img, SDATA (data),
2885 (SDATA (data)
2886 + SBYTES (data)));
2887 else
2889 if (VECTORP (data))
2891 int i;
2892 char *p;
2893 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2895 p = bits = (char *) alloca (nbytes * img->height);
2896 for (i = 0; i < img->height; ++i, p += nbytes)
2898 Lisp_Object line = XVECTOR (data)->contents[i];
2899 if (STRINGP (line))
2900 memcpy (p, SDATA (line), nbytes);
2901 else
2902 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
2905 else if (STRINGP (data))
2906 bits = SSDATA (data);
2907 else
2908 bits = (char *) XBOOL_VECTOR (data)->data;
2910 #ifdef WINDOWSNT
2912 char *invertedBits;
2913 int nbytes, i;
2914 /* Windows mono bitmaps are reversed compared with X. */
2915 invertedBits = bits;
2916 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
2917 * img->height;
2918 bits = (char *) alloca (nbytes);
2919 for (i = 0; i < nbytes; i++)
2920 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
2922 #endif
2923 /* Create the pixmap. */
2925 Create_Pixmap_From_Bitmap_Data (f, img, bits,
2926 foreground, background,
2927 non_default_colors);
2928 if (img->pixmap)
2929 success_p = 1;
2930 else
2932 image_error ("Unable to create pixmap for XBM image `%s'",
2933 img->spec, Qnil);
2934 x_clear_image (f, img);
2939 return success_p;
2944 /***********************************************************************
2945 XPM images
2946 ***********************************************************************/
2948 #if defined (HAVE_XPM) || defined (HAVE_NS)
2950 static int xpm_image_p (Lisp_Object object);
2951 static int xpm_load (struct frame *f, struct image *img);
2952 static int xpm_valid_color_symbols_p (Lisp_Object);
2954 #endif /* HAVE_XPM || HAVE_NS */
2956 #ifdef HAVE_XPM
2957 #ifdef HAVE_NTGUI
2958 /* Indicate to xpm.h that we don't have Xlib. */
2959 #define FOR_MSW
2960 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
2961 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
2962 #define XColor xpm_XColor
2963 #define XImage xpm_XImage
2964 #define Display xpm_Display
2965 #define PIXEL_ALREADY_TYPEDEFED
2966 #include "X11/xpm.h"
2967 #undef FOR_MSW
2968 #undef XColor
2969 #undef XImage
2970 #undef Display
2971 #undef PIXEL_ALREADY_TYPEDEFED
2972 #else
2973 #include "X11/xpm.h"
2974 #endif /* HAVE_NTGUI */
2975 #endif /* HAVE_XPM */
2977 #if defined (HAVE_XPM) || defined (HAVE_NS)
2978 /* The symbol `xpm' identifying XPM-format images. */
2980 static Lisp_Object Qxpm;
2982 /* Indices of image specification fields in xpm_format, below. */
2984 enum xpm_keyword_index
2986 XPM_TYPE,
2987 XPM_FILE,
2988 XPM_DATA,
2989 XPM_ASCENT,
2990 XPM_MARGIN,
2991 XPM_RELIEF,
2992 XPM_ALGORITHM,
2993 XPM_HEURISTIC_MASK,
2994 XPM_MASK,
2995 XPM_COLOR_SYMBOLS,
2996 XPM_BACKGROUND,
2997 XPM_LAST
3000 /* Vector of image_keyword structures describing the format
3001 of valid XPM image specifications. */
3003 static const struct image_keyword xpm_format[XPM_LAST] =
3005 {":type", IMAGE_SYMBOL_VALUE, 1},
3006 {":file", IMAGE_STRING_VALUE, 0},
3007 {":data", IMAGE_STRING_VALUE, 0},
3008 {":ascent", IMAGE_ASCENT_VALUE, 0},
3009 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3010 {":relief", IMAGE_INTEGER_VALUE, 0},
3011 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3012 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3013 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3014 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3015 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3018 /* Structure describing the image type XPM. */
3020 static struct image_type xpm_type =
3022 &Qxpm,
3023 xpm_image_p,
3024 xpm_load,
3025 x_clear_image,
3026 NULL
3029 #ifdef HAVE_X_WINDOWS
3031 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3032 functions for allocating image colors. Our own functions handle
3033 color allocation failures more gracefully than the ones on the XPM
3034 lib. */
3036 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3037 #define ALLOC_XPM_COLORS
3038 #endif
3039 #endif /* HAVE_X_WINDOWS */
3041 #ifdef ALLOC_XPM_COLORS
3043 static void xpm_init_color_cache (struct frame *, XpmAttributes *);
3044 static void xpm_free_color_cache (void);
3045 static int xpm_lookup_color (struct frame *, char *, XColor *);
3046 static int xpm_color_bucket (char *);
3047 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3048 XColor *, int);
3050 /* An entry in a hash table used to cache color definitions of named
3051 colors. This cache is necessary to speed up XPM image loading in
3052 case we do color allocations ourselves. Without it, we would need
3053 a call to XParseColor per pixel in the image. */
3055 struct xpm_cached_color
3057 /* Next in collision chain. */
3058 struct xpm_cached_color *next;
3060 /* Color definition (RGB and pixel color). */
3061 XColor color;
3063 /* Color name. */
3064 char name[1];
3067 /* The hash table used for the color cache, and its bucket vector
3068 size. */
3070 #define XPM_COLOR_CACHE_BUCKETS 1001
3071 static struct xpm_cached_color **xpm_color_cache;
3073 /* Initialize the color cache. */
3075 static void
3076 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3078 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3079 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3080 memset (xpm_color_cache, 0, nbytes);
3081 init_color_table ();
3083 if (attrs->valuemask & XpmColorSymbols)
3085 int i;
3086 XColor color;
3088 for (i = 0; i < attrs->numsymbols; ++i)
3089 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3090 attrs->colorsymbols[i].value, &color))
3092 color.pixel = lookup_rgb_color (f, color.red, color.green,
3093 color.blue);
3094 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3099 /* Free the color cache. */
3101 static void
3102 xpm_free_color_cache (void)
3104 struct xpm_cached_color *p, *next;
3105 int i;
3107 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3108 for (p = xpm_color_cache[i]; p; p = next)
3110 next = p->next;
3111 xfree (p);
3114 xfree (xpm_color_cache);
3115 xpm_color_cache = NULL;
3116 free_color_table ();
3119 /* Return the bucket index for color named COLOR_NAME in the color
3120 cache. */
3122 static int
3123 xpm_color_bucket (char *color_name)
3125 unsigned h = 0;
3126 char *s;
3128 for (s = color_name; *s; ++s)
3129 h = (h << 2) ^ *s;
3130 return h %= XPM_COLOR_CACHE_BUCKETS;
3134 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3135 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3136 entry added. */
3138 static struct xpm_cached_color *
3139 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3141 size_t nbytes;
3142 struct xpm_cached_color *p;
3144 if (bucket < 0)
3145 bucket = xpm_color_bucket (color_name);
3147 nbytes = sizeof *p + strlen (color_name);
3148 p = (struct xpm_cached_color *) xmalloc (nbytes);
3149 strcpy (p->name, color_name);
3150 p->color = *color;
3151 p->next = xpm_color_cache[bucket];
3152 xpm_color_cache[bucket] = p;
3153 return p;
3156 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3157 return the cached definition in *COLOR. Otherwise, make a new
3158 entry in the cache and allocate the color. Value is zero if color
3159 allocation failed. */
3161 static int
3162 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3164 struct xpm_cached_color *p;
3165 int h = xpm_color_bucket (color_name);
3167 for (p = xpm_color_cache[h]; p; p = p->next)
3168 if (strcmp (p->name, color_name) == 0)
3169 break;
3171 if (p != NULL)
3172 *color = p->color;
3173 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3174 color_name, color))
3176 color->pixel = lookup_rgb_color (f, color->red, color->green,
3177 color->blue);
3178 p = xpm_cache_color (f, color_name, color, h);
3180 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3181 with transparency, and it's useful. */
3182 else if (strcmp ("opaque", color_name) == 0)
3184 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3185 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3186 p = xpm_cache_color (f, color_name, color, h);
3189 return p != NULL;
3193 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3194 CLOSURE is a pointer to the frame on which we allocate the
3195 color. Return in *COLOR the allocated color. Value is non-zero
3196 if successful. */
3198 static int
3199 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3200 void *closure)
3202 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3206 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3207 is a pointer to the frame on which we allocate the color. Value is
3208 non-zero if successful. */
3210 static int
3211 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3213 return 1;
3216 #endif /* ALLOC_XPM_COLORS */
3219 #ifdef HAVE_NTGUI
3221 /* XPM library details. */
3223 DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
3224 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3225 xpm_XImage **, XpmAttributes *));
3226 DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3227 xpm_XImage **, XpmAttributes *));
3228 DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
3230 static int
3231 init_xpm_functions (Lisp_Object libraries)
3233 HMODULE library;
3235 if (!(library = w32_delayed_load (libraries, Qxpm)))
3236 return 0;
3238 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3239 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3240 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3241 LOAD_IMGLIB_FN (library, XImageFree);
3242 return 1;
3245 #endif /* HAVE_NTGUI */
3248 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3249 for XPM images. Such a list must consist of conses whose car and
3250 cdr are strings. */
3252 static int
3253 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3255 while (CONSP (color_symbols))
3257 Lisp_Object sym = XCAR (color_symbols);
3258 if (!CONSP (sym)
3259 || !STRINGP (XCAR (sym))
3260 || !STRINGP (XCDR (sym)))
3261 break;
3262 color_symbols = XCDR (color_symbols);
3265 return NILP (color_symbols);
3269 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3271 static int
3272 xpm_image_p (Lisp_Object object)
3274 struct image_keyword fmt[XPM_LAST];
3275 memcpy (fmt, xpm_format, sizeof fmt);
3276 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3277 /* Either `:file' or `:data' must be present. */
3278 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3279 /* Either no `:color-symbols' or it's a list of conses
3280 whose car and cdr are strings. */
3281 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3282 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3285 #endif /* HAVE_XPM || HAVE_NS */
3287 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3289 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3291 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3292 int id, rc;
3293 XpmAttributes attrs;
3294 Pixmap bitmap, mask;
3296 memset (&attrs, 0, sizeof attrs);
3298 attrs.visual = FRAME_X_VISUAL (f);
3299 attrs.colormap = FRAME_X_COLORMAP (f);
3300 attrs.valuemask |= XpmVisual;
3301 attrs.valuemask |= XpmColormap;
3303 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3304 (char **) bits, &bitmap, &mask, &attrs);
3305 if (rc != XpmSuccess)
3307 XpmFreeAttributes (&attrs);
3308 return -1;
3311 id = x_allocate_bitmap_record (f);
3312 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3313 dpyinfo->bitmaps[id - 1].have_mask = 1;
3314 dpyinfo->bitmaps[id - 1].mask = mask;
3315 dpyinfo->bitmaps[id - 1].file = NULL;
3316 dpyinfo->bitmaps[id - 1].height = attrs.height;
3317 dpyinfo->bitmaps[id - 1].width = attrs.width;
3318 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3319 dpyinfo->bitmaps[id - 1].refcount = 1;
3321 XpmFreeAttributes (&attrs);
3322 return id;
3324 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3326 /* Load image IMG which will be displayed on frame F. Value is
3327 non-zero if successful. */
3329 #ifdef HAVE_XPM
3331 static int
3332 xpm_load (struct frame *f, struct image *img)
3334 int rc;
3335 XpmAttributes attrs;
3336 Lisp_Object specified_file, color_symbols;
3337 #ifdef HAVE_NTGUI
3338 HDC hdc;
3339 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3340 #endif /* HAVE_NTGUI */
3342 /* Configure the XPM lib. Use the visual of frame F. Allocate
3343 close colors. Return colors allocated. */
3344 memset (&attrs, 0, sizeof attrs);
3346 #ifndef HAVE_NTGUI
3347 attrs.visual = FRAME_X_VISUAL (f);
3348 attrs.colormap = FRAME_X_COLORMAP (f);
3349 attrs.valuemask |= XpmVisual;
3350 attrs.valuemask |= XpmColormap;
3351 #endif /* HAVE_NTGUI */
3353 #ifdef ALLOC_XPM_COLORS
3354 /* Allocate colors with our own functions which handle
3355 failing color allocation more gracefully. */
3356 attrs.color_closure = f;
3357 attrs.alloc_color = xpm_alloc_color;
3358 attrs.free_colors = xpm_free_colors;
3359 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3360 #else /* not ALLOC_XPM_COLORS */
3361 /* Let the XPM lib allocate colors. */
3362 attrs.valuemask |= XpmReturnAllocPixels;
3363 #ifdef XpmAllocCloseColors
3364 attrs.alloc_close_colors = 1;
3365 attrs.valuemask |= XpmAllocCloseColors;
3366 #else /* not XpmAllocCloseColors */
3367 attrs.closeness = 600;
3368 attrs.valuemask |= XpmCloseness;
3369 #endif /* not XpmAllocCloseColors */
3370 #endif /* ALLOC_XPM_COLORS */
3372 /* If image specification contains symbolic color definitions, add
3373 these to `attrs'. */
3374 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3375 if (CONSP (color_symbols))
3377 Lisp_Object tail;
3378 XpmColorSymbol *xpm_syms;
3379 int i, size;
3381 attrs.valuemask |= XpmColorSymbols;
3383 /* Count number of symbols. */
3384 attrs.numsymbols = 0;
3385 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3386 ++attrs.numsymbols;
3388 /* Allocate an XpmColorSymbol array. */
3389 size = attrs.numsymbols * sizeof *xpm_syms;
3390 xpm_syms = (XpmColorSymbol *) alloca (size);
3391 memset (xpm_syms, 0, size);
3392 attrs.colorsymbols = xpm_syms;
3394 /* Fill the color symbol array. */
3395 for (tail = color_symbols, i = 0;
3396 CONSP (tail);
3397 ++i, tail = XCDR (tail))
3399 Lisp_Object name;
3400 Lisp_Object color;
3401 char *empty_string = (char *) "";
3403 if (!CONSP (XCAR (tail)))
3405 xpm_syms[i].name = empty_string;
3406 xpm_syms[i].value = empty_string;
3407 continue;
3409 name = XCAR (XCAR (tail));
3410 color = XCDR (XCAR (tail));
3411 if (STRINGP (name))
3413 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3414 strcpy (xpm_syms[i].name, SSDATA (name));
3416 else
3417 xpm_syms[i].name = empty_string;
3418 if (STRINGP (color))
3420 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3421 strcpy (xpm_syms[i].value, SSDATA (color));
3423 else
3424 xpm_syms[i].value = empty_string;
3428 /* Create a pixmap for the image, either from a file, or from a
3429 string buffer containing data in the same format as an XPM file. */
3430 #ifdef ALLOC_XPM_COLORS
3431 xpm_init_color_cache (f, &attrs);
3432 #endif
3434 specified_file = image_spec_value (img->spec, QCfile, NULL);
3436 #ifdef HAVE_NTGUI
3438 HDC frame_dc = get_frame_dc (f);
3439 hdc = CreateCompatibleDC (frame_dc);
3440 release_frame_dc (f, frame_dc);
3442 #endif /* HAVE_NTGUI */
3444 if (STRINGP (specified_file))
3446 Lisp_Object file = x_find_image_file (specified_file);
3447 if (!STRINGP (file))
3449 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3450 #ifdef ALLOC_XPM_COLORS
3451 xpm_free_color_cache ();
3452 #endif
3453 return 0;
3456 #ifdef HAVE_NTGUI
3457 /* XpmReadFileToPixmap is not available in the Windows port of
3458 libxpm. But XpmReadFileToImage almost does what we want. */
3459 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3460 &xpm_image, &xpm_mask,
3461 &attrs);
3462 #else
3463 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3464 SSDATA (file), &img->pixmap, &img->mask,
3465 &attrs);
3466 #endif /* HAVE_NTGUI */
3468 else
3470 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3471 if (!STRINGP (buffer))
3473 image_error ("Invalid image data `%s'", buffer, Qnil);
3474 #ifdef ALLOC_XPM_COLORS
3475 xpm_free_color_cache ();
3476 #endif
3477 return 0;
3479 #ifdef HAVE_NTGUI
3480 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3481 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3482 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3483 &xpm_image, &xpm_mask,
3484 &attrs);
3485 #else
3486 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3487 SSDATA (buffer),
3488 &img->pixmap, &img->mask,
3489 &attrs);
3490 #endif /* HAVE_NTGUI */
3493 if (rc == XpmSuccess)
3495 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3496 img->colors = colors_in_color_table (&img->ncolors);
3497 #else /* not ALLOC_XPM_COLORS */
3498 int i;
3500 #ifdef HAVE_NTGUI
3501 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3502 plus some duplicate attributes. */
3503 if (xpm_image && xpm_image->bitmap)
3505 img->pixmap = xpm_image->bitmap;
3506 /* XImageFree in libXpm frees XImage struct without destroying
3507 the bitmap, which is what we want. */
3508 fn_XImageFree (xpm_image);
3510 if (xpm_mask && xpm_mask->bitmap)
3512 /* The mask appears to be inverted compared with what we expect.
3513 TODO: invert our expectations. See other places where we
3514 have to invert bits because our idea of masks is backwards. */
3515 HGDIOBJ old_obj;
3516 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3518 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3519 SelectObject (hdc, old_obj);
3521 img->mask = xpm_mask->bitmap;
3522 fn_XImageFree (xpm_mask);
3523 DeleteDC (hdc);
3526 DeleteDC (hdc);
3527 #endif /* HAVE_NTGUI */
3529 /* Remember allocated colors. */
3530 img->ncolors = attrs.nalloc_pixels;
3531 img->colors = (unsigned long *) xmalloc (img->ncolors
3532 * sizeof *img->colors);
3533 for (i = 0; i < attrs.nalloc_pixels; ++i)
3535 img->colors[i] = attrs.alloc_pixels[i];
3536 #ifdef DEBUG_X_COLORS
3537 register_color (img->colors[i]);
3538 #endif
3540 #endif /* not ALLOC_XPM_COLORS */
3542 img->width = attrs.width;
3543 img->height = attrs.height;
3544 xassert (img->width > 0 && img->height > 0);
3546 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3547 #ifdef HAVE_NTGUI
3548 fn_XpmFreeAttributes (&attrs);
3549 #else
3550 XpmFreeAttributes (&attrs);
3551 #endif /* HAVE_NTGUI */
3553 else
3555 #ifdef HAVE_NTGUI
3556 DeleteDC (hdc);
3557 #endif /* HAVE_NTGUI */
3559 switch (rc)
3561 case XpmOpenFailed:
3562 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3563 break;
3565 case XpmFileInvalid:
3566 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3567 break;
3569 case XpmNoMemory:
3570 image_error ("Out of memory (%s)", img->spec, Qnil);
3571 break;
3573 case XpmColorFailed:
3574 image_error ("Color allocation error (%s)", img->spec, Qnil);
3575 break;
3577 default:
3578 image_error ("Unknown error (%s)", img->spec, Qnil);
3579 break;
3583 #ifdef ALLOC_XPM_COLORS
3584 xpm_free_color_cache ();
3585 #endif
3586 return rc == XpmSuccess;
3589 #endif /* HAVE_XPM */
3591 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3593 /* XPM support functions for NS where libxpm is not available.
3594 Only XPM version 3 (without any extensions) is supported. */
3596 static int xpm_scan (const unsigned char **, const unsigned char *,
3597 const unsigned char **, int *);
3598 static Lisp_Object xpm_make_color_table_v
3599 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3600 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3601 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3602 int, Lisp_Object);
3603 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3604 const unsigned char *, int);
3605 static Lisp_Object xpm_make_color_table_h
3606 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3607 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3608 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3609 int, Lisp_Object);
3610 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3611 const unsigned char *, int);
3612 static int xpm_str_to_color_key (const char *);
3613 static int xpm_load_image (struct frame *, struct image *,
3614 const unsigned char *, const unsigned char *);
3616 /* Tokens returned from xpm_scan. */
3618 enum xpm_token
3620 XPM_TK_IDENT = 256,
3621 XPM_TK_STRING,
3622 XPM_TK_EOF
3625 /* Scan an XPM data and return a character (< 256) or a token defined
3626 by enum xpm_token above. *S and END are the start (inclusive) and
3627 the end (exclusive) addresses of the data, respectively. Advance
3628 *S while scanning. If token is either XPM_TK_IDENT or
3629 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3630 length of the corresponding token, respectively. */
3632 static int
3633 xpm_scan (const unsigned char **s,
3634 const unsigned char *end,
3635 const unsigned char **beg,
3636 int *len)
3638 int c;
3640 while (*s < end)
3642 /* Skip white-space. */
3643 while (*s < end && (c = *(*s)++, isspace (c)))
3646 /* gnus-pointer.xpm uses '-' in its identifier.
3647 sb-dir-plus.xpm uses '+' in its identifier. */
3648 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3650 *beg = *s - 1;
3651 while (*s < end
3652 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3653 ++*s;
3654 *len = *s - *beg;
3655 return XPM_TK_IDENT;
3657 else if (c == '"')
3659 *beg = *s;
3660 while (*s < end && **s != '"')
3661 ++*s;
3662 *len = *s - *beg;
3663 if (*s < end)
3664 ++*s;
3665 return XPM_TK_STRING;
3667 else if (c == '/')
3669 if (*s < end && **s == '*')
3671 /* C-style comment. */
3672 ++*s;
3675 while (*s < end && *(*s)++ != '*')
3678 while (*s < end && **s != '/');
3679 if (*s < end)
3680 ++*s;
3682 else
3683 return c;
3685 else
3686 return c;
3689 return XPM_TK_EOF;
3692 /* Functions for color table lookup in XPM data. A key is a string
3693 specifying the color of each pixel in XPM data. A value is either
3694 an integer that specifies a pixel color, Qt that specifies
3695 transparency, or Qnil for the unspecified color. If the length of
3696 the key string is one, a vector is used as a table. Otherwise, a
3697 hash table is used. */
3699 static Lisp_Object
3700 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3701 const unsigned char *,
3702 int,
3703 Lisp_Object),
3704 Lisp_Object (**get_func) (Lisp_Object,
3705 const unsigned char *,
3706 int))
3708 *put_func = xpm_put_color_table_v;
3709 *get_func = xpm_get_color_table_v;
3710 return Fmake_vector (make_number (256), Qnil);
3713 static void
3714 xpm_put_color_table_v (Lisp_Object color_table,
3715 const unsigned char *chars_start,
3716 int chars_len,
3717 Lisp_Object color)
3719 XVECTOR (color_table)->contents[*chars_start] = color;
3722 static Lisp_Object
3723 xpm_get_color_table_v (Lisp_Object color_table,
3724 const unsigned char *chars_start,
3725 int chars_len)
3727 return XVECTOR (color_table)->contents[*chars_start];
3730 static Lisp_Object
3731 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3732 const unsigned char *,
3733 int,
3734 Lisp_Object),
3735 Lisp_Object (**get_func) (Lisp_Object,
3736 const unsigned char *,
3737 int))
3739 *put_func = xpm_put_color_table_h;
3740 *get_func = xpm_get_color_table_h;
3741 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
3742 make_float (DEFAULT_REHASH_SIZE),
3743 make_float (DEFAULT_REHASH_THRESHOLD),
3744 Qnil, Qnil, Qnil);
3747 static void
3748 xpm_put_color_table_h (Lisp_Object color_table,
3749 const unsigned char *chars_start,
3750 int chars_len,
3751 Lisp_Object color)
3753 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3754 unsigned hash_code;
3755 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3757 hash_lookup (table, chars, &hash_code);
3758 hash_put (table, chars, color, hash_code);
3761 static Lisp_Object
3762 xpm_get_color_table_h (Lisp_Object color_table,
3763 const unsigned char *chars_start,
3764 int chars_len)
3766 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3767 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
3768 NULL);
3770 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3773 enum xpm_color_key {
3774 XPM_COLOR_KEY_S,
3775 XPM_COLOR_KEY_M,
3776 XPM_COLOR_KEY_G4,
3777 XPM_COLOR_KEY_G,
3778 XPM_COLOR_KEY_C
3781 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3783 static int
3784 xpm_str_to_color_key (const char *s)
3786 int i;
3788 for (i = 0;
3789 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3790 i++)
3791 if (strcmp (xpm_color_key_strings[i], s) == 0)
3792 return i;
3793 return -1;
3796 static int
3797 xpm_load_image (struct frame *f,
3798 struct image *img,
3799 const unsigned char *contents,
3800 const unsigned char *end)
3802 const unsigned char *s = contents, *beg, *str;
3803 unsigned char buffer[BUFSIZ];
3804 int width, height, x, y;
3805 int num_colors, chars_per_pixel;
3806 int len, LA1;
3807 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3808 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3809 Lisp_Object frame, color_symbols, color_table;
3810 int best_key, have_mask = 0;
3811 XImagePtr ximg = NULL, mask_img = NULL;
3813 #define match() \
3814 LA1 = xpm_scan (&s, end, &beg, &len)
3816 #define expect(TOKEN) \
3817 if (LA1 != (TOKEN)) \
3818 goto failure; \
3819 else \
3820 match ()
3822 #define expect_ident(IDENT) \
3823 if (LA1 == XPM_TK_IDENT \
3824 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3825 match (); \
3826 else \
3827 goto failure
3829 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3830 goto failure;
3831 s += 9;
3832 match ();
3833 expect_ident ("static");
3834 expect_ident ("char");
3835 expect ('*');
3836 expect (XPM_TK_IDENT);
3837 expect ('[');
3838 expect (']');
3839 expect ('=');
3840 expect ('{');
3841 expect (XPM_TK_STRING);
3842 if (len >= BUFSIZ)
3843 goto failure;
3844 memcpy (buffer, beg, len);
3845 buffer[len] = '\0';
3846 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3847 &num_colors, &chars_per_pixel) != 4
3848 || width <= 0 || height <= 0
3849 || num_colors <= 0 || chars_per_pixel <= 0)
3850 goto failure;
3852 if (!check_image_size (f, width, height))
3854 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
3855 goto failure;
3858 expect (',');
3860 XSETFRAME (frame, f);
3861 if (!NILP (Fxw_display_color_p (frame)))
3862 best_key = XPM_COLOR_KEY_C;
3863 else if (!NILP (Fx_display_grayscale_p (frame)))
3864 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
3865 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
3866 else
3867 best_key = XPM_COLOR_KEY_M;
3869 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3870 if (chars_per_pixel == 1)
3871 color_table = xpm_make_color_table_v (&put_color_table,
3872 &get_color_table);
3873 else
3874 color_table = xpm_make_color_table_h (&put_color_table,
3875 &get_color_table);
3877 while (num_colors-- > 0)
3879 char *color, *max_color;
3880 int key, next_key, max_key = 0;
3881 Lisp_Object symbol_color = Qnil, color_val;
3882 XColor cdef;
3884 expect (XPM_TK_STRING);
3885 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
3886 goto failure;
3887 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
3888 buffer[len - chars_per_pixel] = '\0';
3890 str = strtok (buffer, " \t");
3891 if (str == NULL)
3892 goto failure;
3893 key = xpm_str_to_color_key (str);
3894 if (key < 0)
3895 goto failure;
3898 color = strtok (NULL, " \t");
3899 if (color == NULL)
3900 goto failure;
3902 while ((str = strtok (NULL, " \t")) != NULL)
3904 next_key = xpm_str_to_color_key (str);
3905 if (next_key >= 0)
3906 break;
3907 color[strlen (color)] = ' ';
3910 if (key == XPM_COLOR_KEY_S)
3912 if (NILP (symbol_color))
3913 symbol_color = build_string (color);
3915 else if (max_key < key && key <= best_key)
3917 max_key = key;
3918 max_color = color;
3920 key = next_key;
3922 while (str);
3924 color_val = Qnil;
3925 if (!NILP (color_symbols) && !NILP (symbol_color))
3927 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
3929 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
3931 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
3932 color_val = Qt;
3933 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
3934 &cdef, 0))
3935 color_val = make_number (cdef.pixel);
3938 if (NILP (color_val) && max_key > 0)
3940 if (xstrcasecmp (max_color, "None") == 0)
3941 color_val = Qt;
3942 else if (x_defined_color (f, max_color, &cdef, 0))
3943 color_val = make_number (cdef.pixel);
3945 if (!NILP (color_val))
3946 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
3948 expect (',');
3951 if (!x_create_x_image_and_pixmap (f, width, height, 0,
3952 &ximg, &img->pixmap)
3953 #ifndef HAVE_NS
3954 || !x_create_x_image_and_pixmap (f, width, height, 1,
3955 &mask_img, &img->mask)
3956 #endif
3959 image_error ("Out of memory (%s)", img->spec, Qnil);
3960 goto error;
3963 for (y = 0; y < height; y++)
3965 expect (XPM_TK_STRING);
3966 str = beg;
3967 if (len < width * chars_per_pixel)
3968 goto failure;
3969 for (x = 0; x < width; x++, str += chars_per_pixel)
3971 Lisp_Object color_val =
3972 (*get_color_table) (color_table, str, chars_per_pixel);
3974 XPutPixel (ximg, x, y,
3975 (INTEGERP (color_val) ? XINT (color_val)
3976 : FRAME_FOREGROUND_PIXEL (f)));
3977 #ifndef HAVE_NS
3978 XPutPixel (mask_img, x, y,
3979 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
3980 : (have_mask = 1, PIX_MASK_RETAIN)));
3981 #else
3982 if (EQ (color_val, Qt))
3983 ns_set_alpha (ximg, x, y, 0);
3984 #endif
3986 if (y + 1 < height)
3987 expect (',');
3990 img->width = width;
3991 img->height = height;
3993 /* Maybe fill in the background field while we have ximg handy. */
3994 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
3995 IMAGE_BACKGROUND (img, f, ximg);
3997 x_put_x_image (f, ximg, img->pixmap, width, height);
3998 x_destroy_x_image (ximg);
3999 #ifndef HAVE_NS
4000 if (have_mask)
4002 /* Fill in the background_transparent field while we have the
4003 mask handy. */
4004 image_background_transparent (img, f, mask_img);
4006 x_put_x_image (f, mask_img, img->mask, width, height);
4007 x_destroy_x_image (mask_img);
4009 else
4011 x_destroy_x_image (mask_img);
4012 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4013 img->mask = NO_PIXMAP;
4015 #endif
4016 return 1;
4018 failure:
4019 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4020 error:
4021 x_destroy_x_image (ximg);
4022 x_destroy_x_image (mask_img);
4023 x_clear_image (f, img);
4024 return 0;
4026 #undef match
4027 #undef expect
4028 #undef expect_ident
4031 static int
4032 xpm_load (struct frame *f,
4033 struct image *img)
4035 int success_p = 0;
4036 Lisp_Object file_name;
4038 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4039 file_name = image_spec_value (img->spec, QCfile, NULL);
4040 if (STRINGP (file_name))
4042 Lisp_Object file;
4043 unsigned char *contents;
4044 int size;
4046 file = x_find_image_file (file_name);
4047 if (!STRINGP (file))
4049 image_error ("Cannot find image file `%s'", file_name, Qnil);
4050 return 0;
4053 contents = slurp_file (SDATA (file), &size);
4054 if (contents == NULL)
4056 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4057 return 0;
4060 success_p = xpm_load_image (f, img, contents, contents + size);
4061 xfree (contents);
4063 else
4065 Lisp_Object data;
4067 data = image_spec_value (img->spec, QCdata, NULL);
4068 if (!STRINGP (data))
4070 image_error ("Invalid image data `%s'", data, Qnil);
4071 return 0;
4073 success_p = xpm_load_image (f, img, SDATA (data),
4074 SDATA (data) + SBYTES (data));
4077 return success_p;
4080 #endif /* HAVE_NS && !HAVE_XPM */
4084 /***********************************************************************
4085 Color table
4086 ***********************************************************************/
4088 #ifdef COLOR_TABLE_SUPPORT
4090 /* An entry in the color table mapping an RGB color to a pixel color. */
4092 struct ct_color
4094 int r, g, b;
4095 unsigned long pixel;
4097 /* Next in color table collision list. */
4098 struct ct_color *next;
4101 /* The bucket vector size to use. Must be prime. */
4103 #define CT_SIZE 101
4105 /* Value is a hash of the RGB color given by R, G, and B. */
4107 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4109 /* The color hash table. */
4111 static struct ct_color **ct_table;
4113 /* Number of entries in the color table. */
4115 static int ct_colors_allocated;
4117 /* Initialize the color table. */
4119 static void
4120 init_color_table (void)
4122 int size = CT_SIZE * sizeof (*ct_table);
4123 ct_table = (struct ct_color **) xmalloc (size);
4124 memset (ct_table, 0, size);
4125 ct_colors_allocated = 0;
4129 /* Free memory associated with the color table. */
4131 static void
4132 free_color_table (void)
4134 int i;
4135 struct ct_color *p, *next;
4137 for (i = 0; i < CT_SIZE; ++i)
4138 for (p = ct_table[i]; p; p = next)
4140 next = p->next;
4141 xfree (p);
4144 xfree (ct_table);
4145 ct_table = NULL;
4149 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4150 entry for that color already is in the color table, return the
4151 pixel color of that entry. Otherwise, allocate a new color for R,
4152 G, B, and make an entry in the color table. */
4154 static unsigned long
4155 lookup_rgb_color (struct frame *f, int r, int g, int b)
4157 unsigned hash = CT_HASH_RGB (r, g, b);
4158 int i = hash % CT_SIZE;
4159 struct ct_color *p;
4160 Display_Info *dpyinfo;
4162 /* Handle TrueColor visuals specially, which improves performance by
4163 two orders of magnitude. Freeing colors on TrueColor visuals is
4164 a nop, and pixel colors specify RGB values directly. See also
4165 the Xlib spec, chapter 3.1. */
4166 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4167 if (dpyinfo->red_bits > 0)
4169 unsigned long pr, pg, pb;
4171 /* Apply gamma-correction like normal color allocation does. */
4172 if (f->gamma)
4174 XColor color;
4175 color.red = r, color.green = g, color.blue = b;
4176 gamma_correct (f, &color);
4177 r = color.red, g = color.green, b = color.blue;
4180 /* Scale down RGB values to the visual's bits per RGB, and shift
4181 them to the right position in the pixel color. Note that the
4182 original RGB values are 16-bit values, as usual in X. */
4183 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4184 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4185 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4187 /* Assemble the pixel color. */
4188 return pr | pg | pb;
4191 for (p = ct_table[i]; p; p = p->next)
4192 if (p->r == r && p->g == g && p->b == b)
4193 break;
4195 if (p == NULL)
4198 #ifdef HAVE_X_WINDOWS
4199 XColor color;
4200 Colormap cmap;
4201 int rc;
4203 color.red = r;
4204 color.green = g;
4205 color.blue = b;
4207 cmap = FRAME_X_COLORMAP (f);
4208 rc = x_alloc_nearest_color (f, cmap, &color);
4209 if (rc)
4211 ++ct_colors_allocated;
4212 p = (struct ct_color *) xmalloc (sizeof *p);
4213 p->r = r;
4214 p->g = g;
4215 p->b = b;
4216 p->pixel = color.pixel;
4217 p->next = ct_table[i];
4218 ct_table[i] = p;
4220 else
4221 return FRAME_FOREGROUND_PIXEL (f);
4223 #else
4224 COLORREF color;
4225 #ifdef HAVE_NTGUI
4226 color = PALETTERGB (r, g, b);
4227 #else
4228 color = RGB_TO_ULONG (r, g, b);
4229 #endif /* HAVE_NTGUI */
4230 ++ct_colors_allocated;
4231 p = (struct ct_color *) xmalloc (sizeof *p);
4232 p->r = r;
4233 p->g = g;
4234 p->b = b;
4235 p->pixel = color;
4236 p->next = ct_table[i];
4237 ct_table[i] = p;
4238 #endif /* HAVE_X_WINDOWS */
4242 return p->pixel;
4246 /* Look up pixel color PIXEL which is used on frame F in the color
4247 table. If not already present, allocate it. Value is PIXEL. */
4249 static unsigned long
4250 lookup_pixel_color (struct frame *f, unsigned long pixel)
4252 int i = pixel % CT_SIZE;
4253 struct ct_color *p;
4255 for (p = ct_table[i]; p; p = p->next)
4256 if (p->pixel == pixel)
4257 break;
4259 if (p == NULL)
4261 XColor color;
4262 Colormap cmap;
4263 int rc;
4265 #ifdef HAVE_X_WINDOWS
4266 cmap = FRAME_X_COLORMAP (f);
4267 color.pixel = pixel;
4268 x_query_color (f, &color);
4269 rc = x_alloc_nearest_color (f, cmap, &color);
4270 #else
4271 BLOCK_INPUT;
4272 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4273 color.pixel = pixel;
4274 XQueryColor (NULL, cmap, &color);
4275 rc = x_alloc_nearest_color (f, cmap, &color);
4276 UNBLOCK_INPUT;
4277 #endif /* HAVE_X_WINDOWS */
4279 if (rc)
4281 ++ct_colors_allocated;
4283 p = (struct ct_color *) xmalloc (sizeof *p);
4284 p->r = color.red;
4285 p->g = color.green;
4286 p->b = color.blue;
4287 p->pixel = pixel;
4288 p->next = ct_table[i];
4289 ct_table[i] = p;
4291 else
4292 return FRAME_FOREGROUND_PIXEL (f);
4294 return p->pixel;
4298 /* Value is a vector of all pixel colors contained in the color table,
4299 allocated via xmalloc. Set *N to the number of colors. */
4301 static unsigned long *
4302 colors_in_color_table (int *n)
4304 int i, j;
4305 struct ct_color *p;
4306 unsigned long *colors;
4308 if (ct_colors_allocated == 0)
4310 *n = 0;
4311 colors = NULL;
4313 else
4315 colors = (unsigned long *) xmalloc (ct_colors_allocated
4316 * sizeof *colors);
4317 *n = ct_colors_allocated;
4319 for (i = j = 0; i < CT_SIZE; ++i)
4320 for (p = ct_table[i]; p; p = p->next)
4321 colors[j++] = p->pixel;
4324 return colors;
4327 #else /* COLOR_TABLE_SUPPORT */
4329 static unsigned long
4330 lookup_rgb_color (struct frame *f, int r, int g, int b)
4332 unsigned long pixel;
4334 #ifdef HAVE_NTGUI
4335 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4336 #endif /* HAVE_NTGUI */
4338 #ifdef HAVE_NS
4339 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4340 #endif /* HAVE_NS */
4341 return pixel;
4344 static void
4345 init_color_table (void)
4348 #endif /* COLOR_TABLE_SUPPORT */
4351 /***********************************************************************
4352 Algorithms
4353 ***********************************************************************/
4355 static XColor *x_to_xcolors (struct frame *, struct image *, int);
4356 static void x_from_xcolors (struct frame *, struct image *, XColor *);
4357 static void x_detect_edges (struct frame *, struct image *, int[9], int);
4359 #ifdef HAVE_NTGUI
4360 static void XPutPixel (XImagePtr , int, int, COLORREF);
4361 #endif /* HAVE_NTGUI */
4363 /* Edge detection matrices for different edge-detection
4364 strategies. */
4366 static int emboss_matrix[9] = {
4367 /* x - 1 x x + 1 */
4368 2, -1, 0, /* y - 1 */
4369 -1, 0, 1, /* y */
4370 0, 1, -2 /* y + 1 */
4373 static int laplace_matrix[9] = {
4374 /* x - 1 x x + 1 */
4375 1, 0, 0, /* y - 1 */
4376 0, 0, 0, /* y */
4377 0, 0, -1 /* y + 1 */
4380 /* Value is the intensity of the color whose red/green/blue values
4381 are R, G, and B. */
4383 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4386 /* On frame F, return an array of XColor structures describing image
4387 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4388 non-zero means also fill the red/green/blue members of the XColor
4389 structures. Value is a pointer to the array of XColors structures,
4390 allocated with xmalloc; it must be freed by the caller. */
4392 static XColor *
4393 x_to_xcolors (struct frame *f, struct image *img, int rgb_p)
4395 int x, y;
4396 XColor *colors, *p;
4397 XImagePtr_or_DC ximg;
4398 #ifdef HAVE_NTGUI
4399 HDC hdc;
4400 HGDIOBJ prev;
4401 #endif /* HAVE_NTGUI */
4403 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4405 #ifndef HAVE_NTGUI
4406 /* Get the X image IMG->pixmap. */
4407 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4408 0, 0, img->width, img->height, ~0, ZPixmap);
4409 #else
4410 /* Load the image into a memory device context. */
4411 hdc = get_frame_dc (f);
4412 ximg = CreateCompatibleDC (hdc);
4413 release_frame_dc (f, hdc);
4414 prev = SelectObject (ximg, img->pixmap);
4415 #endif /* HAVE_NTGUI */
4417 /* Fill the `pixel' members of the XColor array. I wished there
4418 were an easy and portable way to circumvent XGetPixel. */
4419 p = colors;
4420 for (y = 0; y < img->height; ++y)
4422 XColor *row = p;
4424 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4425 for (x = 0; x < img->width; ++x, ++p)
4426 p->pixel = GET_PIXEL (ximg, x, y);
4427 if (rgb_p)
4428 x_query_colors (f, row, img->width);
4430 #else
4432 for (x = 0; x < img->width; ++x, ++p)
4434 /* W32_TODO: palette support needed here? */
4435 p->pixel = GET_PIXEL (ximg, x, y);
4436 if (rgb_p)
4438 p->red = RED16_FROM_ULONG (p->pixel);
4439 p->green = GREEN16_FROM_ULONG (p->pixel);
4440 p->blue = BLUE16_FROM_ULONG (p->pixel);
4443 #endif /* HAVE_X_WINDOWS */
4446 Destroy_Image (ximg, prev);
4448 return colors;
4451 #ifdef HAVE_NTGUI
4453 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4454 created with CreateDIBSection, with the pointer to the bit values
4455 stored in ximg->data. */
4457 static void
4458 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4460 int width = ximg->info.bmiHeader.biWidth;
4461 unsigned char * pixel;
4463 /* True color images. */
4464 if (ximg->info.bmiHeader.biBitCount == 24)
4466 int rowbytes = width * 3;
4467 /* Ensure scanlines are aligned on 4 byte boundaries. */
4468 if (rowbytes % 4)
4469 rowbytes += 4 - (rowbytes % 4);
4471 pixel = ximg->data + y * rowbytes + x * 3;
4472 /* Windows bitmaps are in BGR order. */
4473 *pixel = GetBValue (color);
4474 *(pixel + 1) = GetGValue (color);
4475 *(pixel + 2) = GetRValue (color);
4477 /* Monochrome images. */
4478 else if (ximg->info.bmiHeader.biBitCount == 1)
4480 int rowbytes = width / 8;
4481 /* Ensure scanlines are aligned on 4 byte boundaries. */
4482 if (rowbytes % 4)
4483 rowbytes += 4 - (rowbytes % 4);
4484 pixel = ximg->data + y * rowbytes + x / 8;
4485 /* Filter out palette info. */
4486 if (color & 0x00ffffff)
4487 *pixel = *pixel | (1 << x % 8);
4488 else
4489 *pixel = *pixel & ~(1 << x % 8);
4491 else
4492 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4495 #endif /* HAVE_NTGUI */
4497 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4498 RGB members are set. F is the frame on which this all happens.
4499 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4501 static void
4502 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4504 int x, y;
4505 XImagePtr oimg = NULL;
4506 Pixmap pixmap;
4507 XColor *p;
4509 init_color_table ();
4511 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4512 &oimg, &pixmap);
4513 p = colors;
4514 for (y = 0; y < img->height; ++y)
4515 for (x = 0; x < img->width; ++x, ++p)
4517 unsigned long pixel;
4518 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4519 XPutPixel (oimg, x, y, pixel);
4522 xfree (colors);
4523 x_clear_image_1 (f, img, 1, 0, 1);
4525 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4526 x_destroy_x_image (oimg);
4527 img->pixmap = pixmap;
4528 #ifdef COLOR_TABLE_SUPPORT
4529 img->colors = colors_in_color_table (&img->ncolors);
4530 free_color_table ();
4531 #endif /* COLOR_TABLE_SUPPORT */
4535 /* On frame F, perform edge-detection on image IMG.
4537 MATRIX is a nine-element array specifying the transformation
4538 matrix. See emboss_matrix for an example.
4540 COLOR_ADJUST is a color adjustment added to each pixel of the
4541 outgoing image. */
4543 static void
4544 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4546 XColor *colors = x_to_xcolors (f, img, 1);
4547 XColor *new, *p;
4548 int x, y, i, sum;
4550 for (i = sum = 0; i < 9; ++i)
4551 sum += eabs (matrix[i]);
4553 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4555 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4557 for (y = 0; y < img->height; ++y)
4559 p = COLOR (new, 0, y);
4560 p->red = p->green = p->blue = 0xffff/2;
4561 p = COLOR (new, img->width - 1, y);
4562 p->red = p->green = p->blue = 0xffff/2;
4565 for (x = 1; x < img->width - 1; ++x)
4567 p = COLOR (new, x, 0);
4568 p->red = p->green = p->blue = 0xffff/2;
4569 p = COLOR (new, x, img->height - 1);
4570 p->red = p->green = p->blue = 0xffff/2;
4573 for (y = 1; y < img->height - 1; ++y)
4575 p = COLOR (new, 1, y);
4577 for (x = 1; x < img->width - 1; ++x, ++p)
4579 int r, g, b, yy, xx;
4581 r = g = b = i = 0;
4582 for (yy = y - 1; yy < y + 2; ++yy)
4583 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4584 if (matrix[i])
4586 XColor *t = COLOR (colors, xx, yy);
4587 r += matrix[i] * t->red;
4588 g += matrix[i] * t->green;
4589 b += matrix[i] * t->blue;
4592 r = (r / sum + color_adjust) & 0xffff;
4593 g = (g / sum + color_adjust) & 0xffff;
4594 b = (b / sum + color_adjust) & 0xffff;
4595 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4599 xfree (colors);
4600 x_from_xcolors (f, img, new);
4602 #undef COLOR
4606 /* Perform the pre-defined `emboss' edge-detection on image IMG
4607 on frame F. */
4609 static void
4610 x_emboss (struct frame *f, struct image *img)
4612 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4616 /* Transform image IMG which is used on frame F with a Laplace
4617 edge-detection algorithm. The result is an image that can be used
4618 to draw disabled buttons, for example. */
4620 static void
4621 x_laplace (struct frame *f, struct image *img)
4623 x_detect_edges (f, img, laplace_matrix, 45000);
4627 /* Perform edge-detection on image IMG on frame F, with specified
4628 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4630 MATRIX must be either
4632 - a list of at least 9 numbers in row-major form
4633 - a vector of at least 9 numbers
4635 COLOR_ADJUST nil means use a default; otherwise it must be a
4636 number. */
4638 static void
4639 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4640 Lisp_Object color_adjust)
4642 int i = 0;
4643 int trans[9];
4645 if (CONSP (matrix))
4647 for (i = 0;
4648 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4649 ++i, matrix = XCDR (matrix))
4650 trans[i] = XFLOATINT (XCAR (matrix));
4652 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4654 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4655 trans[i] = XFLOATINT (AREF (matrix, i));
4658 if (NILP (color_adjust))
4659 color_adjust = make_number (0xffff / 2);
4661 if (i == 9 && NUMBERP (color_adjust))
4662 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4666 /* Transform image IMG on frame F so that it looks disabled. */
4668 static void
4669 x_disable_image (struct frame *f, struct image *img)
4671 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4672 #ifdef HAVE_NTGUI
4673 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4674 #else
4675 int n_planes = dpyinfo->n_planes;
4676 #endif /* HAVE_NTGUI */
4678 if (n_planes >= 2)
4680 /* Color (or grayscale). Convert to gray, and equalize. Just
4681 drawing such images with a stipple can look very odd, so
4682 we're using this method instead. */
4683 XColor *colors = x_to_xcolors (f, img, 1);
4684 XColor *p, *end;
4685 const int h = 15000;
4686 const int l = 30000;
4688 for (p = colors, end = colors + img->width * img->height;
4689 p < end;
4690 ++p)
4692 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4693 int i2 = (0xffff - h - l) * i / 0xffff + l;
4694 p->red = p->green = p->blue = i2;
4697 x_from_xcolors (f, img, colors);
4700 /* Draw a cross over the disabled image, if we must or if we
4701 should. */
4702 if (n_planes < 2 || cross_disabled_images)
4704 #ifndef HAVE_NTGUI
4705 Display *dpy = FRAME_X_DISPLAY (f);
4706 GC gc;
4708 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4710 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4712 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4713 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4714 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4715 img->width - 1, img->height - 1);
4716 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4717 img->width - 1, 0);
4718 XFreeGC (dpy, gc);
4720 if (img->mask)
4722 gc = XCreateGC (dpy, img->mask, 0, NULL);
4723 XSetForeground (dpy, gc, MaskForeground (f));
4724 XDrawLine (dpy, img->mask, gc, 0, 0,
4725 img->width - 1, img->height - 1);
4726 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4727 img->width - 1, 0);
4728 XFreeGC (dpy, gc);
4730 #endif /* !HAVE_NS */
4731 #else
4732 HDC hdc, bmpdc;
4733 HGDIOBJ prev;
4735 hdc = get_frame_dc (f);
4736 bmpdc = CreateCompatibleDC (hdc);
4737 release_frame_dc (f, hdc);
4739 prev = SelectObject (bmpdc, img->pixmap);
4741 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4742 MoveToEx (bmpdc, 0, 0, NULL);
4743 LineTo (bmpdc, img->width - 1, img->height - 1);
4744 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4745 LineTo (bmpdc, img->width - 1, 0);
4747 if (img->mask)
4749 SelectObject (bmpdc, img->mask);
4750 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4751 MoveToEx (bmpdc, 0, 0, NULL);
4752 LineTo (bmpdc, img->width - 1, img->height - 1);
4753 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4754 LineTo (bmpdc, img->width - 1, 0);
4756 SelectObject (bmpdc, prev);
4757 DeleteDC (bmpdc);
4758 #endif /* HAVE_NTGUI */
4763 /* Build a mask for image IMG which is used on frame F. FILE is the
4764 name of an image file, for error messages. HOW determines how to
4765 determine the background color of IMG. If it is a list '(R G B)',
4766 with R, G, and B being integers >= 0, take that as the color of the
4767 background. Otherwise, determine the background color of IMG
4768 heuristically. Value is non-zero if successful. */
4770 static int
4771 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4773 XImagePtr_or_DC ximg;
4774 #ifndef HAVE_NTGUI
4775 XImagePtr mask_img;
4776 #else
4777 HDC frame_dc;
4778 HGDIOBJ prev;
4779 char *mask_img;
4780 int row_width;
4781 #endif /* HAVE_NTGUI */
4782 int x, y, rc, use_img_background;
4783 unsigned long bg = 0;
4785 if (img->mask)
4787 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4788 img->mask = NO_PIXMAP;
4789 img->background_transparent_valid = 0;
4792 #ifndef HAVE_NTGUI
4793 #ifndef HAVE_NS
4794 /* Create an image and pixmap serving as mask. */
4795 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4796 &mask_img, &img->mask);
4797 if (!rc)
4798 return 0;
4799 #endif /* !HAVE_NS */
4801 /* Get the X image of IMG->pixmap. */
4802 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4803 img->width, img->height,
4804 ~0, ZPixmap);
4805 #else
4806 /* Create the bit array serving as mask. */
4807 row_width = (img->width + 7) / 8;
4808 mask_img = xmalloc (row_width * img->height);
4809 memset (mask_img, 0, row_width * img->height);
4811 /* Create a memory device context for IMG->pixmap. */
4812 frame_dc = get_frame_dc (f);
4813 ximg = CreateCompatibleDC (frame_dc);
4814 release_frame_dc (f, frame_dc);
4815 prev = SelectObject (ximg, img->pixmap);
4816 #endif /* HAVE_NTGUI */
4818 /* Determine the background color of ximg. If HOW is `(R G B)'
4819 take that as color. Otherwise, use the image's background color. */
4820 use_img_background = 1;
4822 if (CONSP (how))
4824 int rgb[3], i;
4826 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4828 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4829 how = XCDR (how);
4832 if (i == 3 && NILP (how))
4834 char color_name[30];
4835 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4836 bg = (
4837 #ifdef HAVE_NTGUI
4838 0x00ffffff & /* Filter out palette info. */
4839 #endif /* HAVE_NTGUI */
4840 x_alloc_image_color (f, img, build_string (color_name), 0));
4841 use_img_background = 0;
4845 if (use_img_background)
4846 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4848 /* Set all bits in mask_img to 1 whose color in ximg is different
4849 from the background color bg. */
4850 #ifndef HAVE_NTGUI
4851 for (y = 0; y < img->height; ++y)
4852 for (x = 0; x < img->width; ++x)
4853 #ifndef HAVE_NS
4854 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4855 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4856 #else
4857 if (XGetPixel (ximg, x, y) == bg)
4858 ns_set_alpha (ximg, x, y, 0);
4859 #endif /* HAVE_NS */
4860 #ifndef HAVE_NS
4861 /* Fill in the background_transparent field while we have the mask handy. */
4862 image_background_transparent (img, f, mask_img);
4864 /* Put mask_img into img->mask. */
4865 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4866 x_destroy_x_image (mask_img);
4867 #endif /* !HAVE_NS */
4868 #else
4869 for (y = 0; y < img->height; ++y)
4870 for (x = 0; x < img->width; ++x)
4872 COLORREF p = GetPixel (ximg, x, y);
4873 if (p != bg)
4874 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4877 /* Create the mask image. */
4878 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4879 mask_img);
4880 /* Fill in the background_transparent field while we have the mask handy. */
4881 SelectObject (ximg, img->mask);
4882 image_background_transparent (img, f, ximg);
4884 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4885 xfree (mask_img);
4886 #endif /* HAVE_NTGUI */
4888 Destroy_Image (ximg, prev);
4890 return 1;
4894 /***********************************************************************
4895 PBM (mono, gray, color)
4896 ***********************************************************************/
4898 static int pbm_image_p (Lisp_Object object);
4899 static int pbm_load (struct frame *f, struct image *img);
4900 static int pbm_scan_number (unsigned char **, unsigned char *);
4902 /* The symbol `pbm' identifying images of this type. */
4904 static Lisp_Object Qpbm;
4906 /* Indices of image specification fields in gs_format, below. */
4908 enum pbm_keyword_index
4910 PBM_TYPE,
4911 PBM_FILE,
4912 PBM_DATA,
4913 PBM_ASCENT,
4914 PBM_MARGIN,
4915 PBM_RELIEF,
4916 PBM_ALGORITHM,
4917 PBM_HEURISTIC_MASK,
4918 PBM_MASK,
4919 PBM_FOREGROUND,
4920 PBM_BACKGROUND,
4921 PBM_LAST
4924 /* Vector of image_keyword structures describing the format
4925 of valid user-defined image specifications. */
4927 static const struct image_keyword pbm_format[PBM_LAST] =
4929 {":type", IMAGE_SYMBOL_VALUE, 1},
4930 {":file", IMAGE_STRING_VALUE, 0},
4931 {":data", IMAGE_STRING_VALUE, 0},
4932 {":ascent", IMAGE_ASCENT_VALUE, 0},
4933 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
4934 {":relief", IMAGE_INTEGER_VALUE, 0},
4935 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4936 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4937 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4938 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4939 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4942 /* Structure describing the image type `pbm'. */
4944 static struct image_type pbm_type =
4946 &Qpbm,
4947 pbm_image_p,
4948 pbm_load,
4949 x_clear_image,
4950 NULL
4954 /* Return non-zero if OBJECT is a valid PBM image specification. */
4956 static int
4957 pbm_image_p (Lisp_Object object)
4959 struct image_keyword fmt[PBM_LAST];
4961 memcpy (fmt, pbm_format, sizeof fmt);
4963 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
4964 return 0;
4966 /* Must specify either :data or :file. */
4967 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
4971 /* Scan a decimal number from *S and return it. Advance *S while
4972 reading the number. END is the end of the string. Value is -1 at
4973 end of input. */
4975 static int
4976 pbm_scan_number (unsigned char **s, unsigned char *end)
4978 int c = 0, val = -1;
4980 while (*s < end)
4982 /* Skip white-space. */
4983 while (*s < end && (c = *(*s)++, isspace (c)))
4986 if (c == '#')
4988 /* Skip comment to end of line. */
4989 while (*s < end && (c = *(*s)++, c != '\n'))
4992 else if (isdigit (c))
4994 /* Read decimal number. */
4995 val = c - '0';
4996 while (*s < end && (c = *(*s)++, isdigit (c)))
4997 val = 10 * val + c - '0';
4998 break;
5000 else
5001 break;
5004 return val;
5008 #ifdef HAVE_NTGUI
5009 #if 0 /* Unused. ++kfs */
5011 /* Read FILE into memory. Value is a pointer to a buffer allocated
5012 with xmalloc holding FILE's contents. Value is null if an error
5013 occurred. *SIZE is set to the size of the file. */
5015 static char *
5016 pbm_read_file (file, size)
5017 Lisp_Object file;
5018 int *size;
5020 FILE *fp = NULL;
5021 char *buf = NULL;
5022 struct stat st;
5024 if (stat (SDATA (file), &st) == 0
5025 && (fp = fopen (SDATA (file), "rb")) != NULL
5026 && (buf = (char *) xmalloc (st.st_size),
5027 fread (buf, 1, st.st_size, fp) == st.st_size))
5029 *size = st.st_size;
5030 fclose (fp);
5032 else
5034 if (fp)
5035 fclose (fp);
5036 if (buf)
5038 xfree (buf);
5039 buf = NULL;
5043 return buf;
5045 #endif
5046 #endif /* HAVE_NTGUI */
5048 /* Load PBM image IMG for use on frame F. */
5050 static int
5051 pbm_load (struct frame *f, struct image *img)
5053 int raw_p, x, y;
5054 int width, height, max_color_idx = 0;
5055 XImagePtr ximg;
5056 Lisp_Object file, specified_file;
5057 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5058 unsigned char *contents = NULL;
5059 unsigned char *end, *p;
5060 int size;
5062 specified_file = image_spec_value (img->spec, QCfile, NULL);
5064 if (STRINGP (specified_file))
5066 file = x_find_image_file (specified_file);
5067 if (!STRINGP (file))
5069 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5070 return 0;
5073 contents = slurp_file (SSDATA (file), &size);
5074 if (contents == NULL)
5076 image_error ("Error reading `%s'", file, Qnil);
5077 return 0;
5080 p = contents;
5081 end = contents + size;
5083 else
5085 Lisp_Object data;
5086 data = image_spec_value (img->spec, QCdata, NULL);
5087 if (!STRINGP (data))
5089 image_error ("Invalid image data `%s'", data, Qnil);
5090 return 0;
5092 p = SDATA (data);
5093 end = p + SBYTES (data);
5096 /* Check magic number. */
5097 if (end - p < 2 || *p++ != 'P')
5099 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5100 error:
5101 xfree (contents);
5102 return 0;
5105 switch (*p++)
5107 case '1':
5108 raw_p = 0, type = PBM_MONO;
5109 break;
5111 case '2':
5112 raw_p = 0, type = PBM_GRAY;
5113 break;
5115 case '3':
5116 raw_p = 0, type = PBM_COLOR;
5117 break;
5119 case '4':
5120 raw_p = 1, type = PBM_MONO;
5121 break;
5123 case '5':
5124 raw_p = 1, type = PBM_GRAY;
5125 break;
5127 case '6':
5128 raw_p = 1, type = PBM_COLOR;
5129 break;
5131 default:
5132 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5133 goto error;
5136 /* Read width, height, maximum color-component. Characters
5137 starting with `#' up to the end of a line are ignored. */
5138 width = pbm_scan_number (&p, end);
5139 height = pbm_scan_number (&p, end);
5141 if (type != PBM_MONO)
5143 max_color_idx = pbm_scan_number (&p, end);
5144 if (max_color_idx > 65535 || max_color_idx < 0)
5146 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5147 goto error;
5151 if (!check_image_size (f, width, height))
5153 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5154 goto error;
5157 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5158 &ximg, &img->pixmap))
5159 goto error;
5161 /* Initialize the color hash table. */
5162 init_color_table ();
5164 if (type == PBM_MONO)
5166 int c = 0, g;
5167 struct image_keyword fmt[PBM_LAST];
5168 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5169 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5171 /* Parse the image specification. */
5172 memcpy (fmt, pbm_format, sizeof fmt);
5173 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5175 /* Get foreground and background colors, maybe allocate colors. */
5176 if (fmt[PBM_FOREGROUND].count
5177 && STRINGP (fmt[PBM_FOREGROUND].value))
5178 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5179 if (fmt[PBM_BACKGROUND].count
5180 && STRINGP (fmt[PBM_BACKGROUND].value))
5182 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5183 img->background = bg;
5184 img->background_valid = 1;
5187 for (y = 0; y < height; ++y)
5188 for (x = 0; x < width; ++x)
5190 if (raw_p)
5192 if ((x & 7) == 0)
5194 if (p >= end)
5196 x_destroy_x_image (ximg);
5197 x_clear_image (f, img);
5198 image_error ("Invalid image size in image `%s'",
5199 img->spec, Qnil);
5200 goto error;
5202 c = *p++;
5204 g = c & 0x80;
5205 c <<= 1;
5207 else
5208 g = pbm_scan_number (&p, end);
5210 XPutPixel (ximg, x, y, g ? fg : bg);
5213 else
5215 int expected_size = height * width;
5216 if (max_color_idx > 255)
5217 expected_size *= 2;
5218 if (type == PBM_COLOR)
5219 expected_size *= 3;
5221 if (raw_p && p + expected_size > end)
5223 x_destroy_x_image (ximg);
5224 x_clear_image (f, img);
5225 image_error ("Invalid image size in image `%s'",
5226 img->spec, Qnil);
5227 goto error;
5230 for (y = 0; y < height; ++y)
5231 for (x = 0; x < width; ++x)
5233 int r, g, b;
5235 if (type == PBM_GRAY && raw_p)
5237 r = g = b = *p++;
5238 if (max_color_idx > 255)
5239 r = g = b = r * 256 + *p++;
5241 else if (type == PBM_GRAY)
5242 r = g = b = pbm_scan_number (&p, end);
5243 else if (raw_p)
5245 r = *p++;
5246 if (max_color_idx > 255)
5247 r = r * 256 + *p++;
5248 g = *p++;
5249 if (max_color_idx > 255)
5250 g = g * 256 + *p++;
5251 b = *p++;
5252 if (max_color_idx > 255)
5253 b = b * 256 + *p++;
5255 else
5257 r = pbm_scan_number (&p, end);
5258 g = pbm_scan_number (&p, end);
5259 b = pbm_scan_number (&p, end);
5262 if (r < 0 || g < 0 || b < 0)
5264 x_destroy_x_image (ximg);
5265 image_error ("Invalid pixel value in image `%s'",
5266 img->spec, Qnil);
5267 goto error;
5270 /* RGB values are now in the range 0..max_color_idx.
5271 Scale this to the range 0..0xffff supported by X. */
5272 r = (double) r * 65535 / max_color_idx;
5273 g = (double) g * 65535 / max_color_idx;
5274 b = (double) b * 65535 / max_color_idx;
5275 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5279 #ifdef COLOR_TABLE_SUPPORT
5280 /* Store in IMG->colors the colors allocated for the image, and
5281 free the color table. */
5282 img->colors = colors_in_color_table (&img->ncolors);
5283 free_color_table ();
5284 #endif /* COLOR_TABLE_SUPPORT */
5286 img->width = width;
5287 img->height = height;
5289 /* Maybe fill in the background field while we have ximg handy. */
5291 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5292 /* Casting avoids a GCC warning. */
5293 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5295 /* Put the image into a pixmap. */
5296 x_put_x_image (f, ximg, img->pixmap, width, height);
5297 x_destroy_x_image (ximg);
5299 /* X and W32 versions did it here, MAC version above. ++kfs
5300 img->width = width;
5301 img->height = height; */
5303 xfree (contents);
5304 return 1;
5308 /***********************************************************************
5310 ***********************************************************************/
5312 #if defined (HAVE_PNG) || defined (HAVE_NS)
5314 /* Function prototypes. */
5316 static int png_image_p (Lisp_Object object);
5317 static int png_load (struct frame *f, struct image *img);
5319 /* The symbol `png' identifying images of this type. */
5321 static Lisp_Object Qpng;
5323 /* Indices of image specification fields in png_format, below. */
5325 enum png_keyword_index
5327 PNG_TYPE,
5328 PNG_DATA,
5329 PNG_FILE,
5330 PNG_ASCENT,
5331 PNG_MARGIN,
5332 PNG_RELIEF,
5333 PNG_ALGORITHM,
5334 PNG_HEURISTIC_MASK,
5335 PNG_MASK,
5336 PNG_BACKGROUND,
5337 PNG_LAST
5340 /* Vector of image_keyword structures describing the format
5341 of valid user-defined image specifications. */
5343 static const struct image_keyword png_format[PNG_LAST] =
5345 {":type", IMAGE_SYMBOL_VALUE, 1},
5346 {":data", IMAGE_STRING_VALUE, 0},
5347 {":file", IMAGE_STRING_VALUE, 0},
5348 {":ascent", IMAGE_ASCENT_VALUE, 0},
5349 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5350 {":relief", IMAGE_INTEGER_VALUE, 0},
5351 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5352 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5353 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5354 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5357 /* Structure describing the image type `png'. */
5359 static struct image_type png_type =
5361 &Qpng,
5362 png_image_p,
5363 png_load,
5364 x_clear_image,
5365 NULL
5368 /* Return non-zero if OBJECT is a valid PNG image specification. */
5370 static int
5371 png_image_p (Lisp_Object object)
5373 struct image_keyword fmt[PNG_LAST];
5374 memcpy (fmt, png_format, sizeof fmt);
5376 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5377 return 0;
5379 /* Must specify either the :data or :file keyword. */
5380 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5383 #endif /* HAVE_PNG || HAVE_NS */
5386 #ifdef HAVE_PNG
5388 #ifdef HAVE_NTGUI
5389 /* PNG library details. */
5391 DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5392 DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5393 DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5394 png_error_ptr, png_error_ptr));
5395 DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5396 DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5397 DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5398 DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5399 DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5400 DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
5401 png_uint_32 *, png_uint_32 *,
5402 int *, int *, int *, int *, int *));
5403 DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5404 DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5405 DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5406 DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5407 DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
5408 int, int, double));
5409 DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5410 DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5411 DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5412 DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5413 DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5414 DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5415 DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
5417 #if (PNG_LIBPNG_VER >= 10500)
5418 DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int));
5419 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
5420 #endif /* libpng version >= 1.5 */
5422 static int
5423 init_png_functions (Lisp_Object libraries)
5425 HMODULE library;
5427 if (!(library = w32_delayed_load (libraries, Qpng)))
5428 return 0;
5430 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5431 LOAD_IMGLIB_FN (library, png_sig_cmp);
5432 LOAD_IMGLIB_FN (library, png_create_read_struct);
5433 LOAD_IMGLIB_FN (library, png_create_info_struct);
5434 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5435 LOAD_IMGLIB_FN (library, png_set_read_fn);
5436 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5437 LOAD_IMGLIB_FN (library, png_read_info);
5438 LOAD_IMGLIB_FN (library, png_get_IHDR);
5439 LOAD_IMGLIB_FN (library, png_get_valid);
5440 LOAD_IMGLIB_FN (library, png_set_strip_16);
5441 LOAD_IMGLIB_FN (library, png_set_expand);
5442 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5443 LOAD_IMGLIB_FN (library, png_set_background);
5444 LOAD_IMGLIB_FN (library, png_get_bKGD);
5445 LOAD_IMGLIB_FN (library, png_read_update_info);
5446 LOAD_IMGLIB_FN (library, png_get_channels);
5447 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5448 LOAD_IMGLIB_FN (library, png_read_image);
5449 LOAD_IMGLIB_FN (library, png_read_end);
5450 LOAD_IMGLIB_FN (library, png_error);
5452 #if (PNG_LIBPNG_VER >= 10500)
5453 LOAD_IMGLIB_FN (library, png_longjmp);
5454 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5455 #endif /* libpng version >= 1.5 */
5457 return 1;
5459 #else
5461 #define fn_png_get_io_ptr png_get_io_ptr
5462 #define fn_png_sig_cmp png_sig_cmp
5463 #define fn_png_create_read_struct png_create_read_struct
5464 #define fn_png_create_info_struct png_create_info_struct
5465 #define fn_png_destroy_read_struct png_destroy_read_struct
5466 #define fn_png_set_read_fn png_set_read_fn
5467 #define fn_png_set_sig_bytes png_set_sig_bytes
5468 #define fn_png_read_info png_read_info
5469 #define fn_png_get_IHDR png_get_IHDR
5470 #define fn_png_get_valid png_get_valid
5471 #define fn_png_set_strip_16 png_set_strip_16
5472 #define fn_png_set_expand png_set_expand
5473 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5474 #define fn_png_set_background png_set_background
5475 #define fn_png_get_bKGD png_get_bKGD
5476 #define fn_png_read_update_info png_read_update_info
5477 #define fn_png_get_channels png_get_channels
5478 #define fn_png_get_rowbytes png_get_rowbytes
5479 #define fn_png_read_image png_read_image
5480 #define fn_png_read_end png_read_end
5481 #define fn_png_error png_error
5483 #if (PNG_LIBPNG_VER >= 10500)
5484 #define fn_png_longjmp png_longjmp
5485 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5486 #endif /* libpng version >= 1.5 */
5488 #endif /* HAVE_NTGUI */
5491 #if (PNG_LIBPNG_VER < 10500)
5492 #define PNG_LONGJMP(ptr) (longjmp ((ptr)->jmpbuf, 1))
5493 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5494 #else
5495 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5496 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5497 #define PNG_JMPBUF(ptr) \
5498 (*fn_png_set_longjmp_fn((ptr), longjmp, sizeof (jmp_buf)))
5499 #endif
5501 /* Error and warning handlers installed when the PNG library
5502 is initialized. */
5504 static void my_png_error (png_struct *, const char *) NO_RETURN;
5505 static void
5506 my_png_error (png_struct *png_ptr, const char *msg)
5508 xassert (png_ptr != NULL);
5509 /* Avoid compiler warning about deprecated direct access to
5510 png_ptr's fields in libpng versions 1.4.x. */
5511 image_error ("PNG error: %s", build_string (msg), Qnil);
5512 PNG_LONGJMP (png_ptr);
5516 static void
5517 my_png_warning (png_struct *png_ptr, const char *msg)
5519 xassert (png_ptr != NULL);
5520 image_error ("PNG warning: %s", build_string (msg), Qnil);
5523 /* Memory source for PNG decoding. */
5525 struct png_memory_storage
5527 unsigned char *bytes; /* The data */
5528 size_t len; /* How big is it? */
5529 int index; /* Where are we? */
5533 /* Function set as reader function when reading PNG image from memory.
5534 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5535 bytes from the input to DATA. */
5537 static void
5538 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5540 struct png_memory_storage *tbr
5541 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5543 if (length > tbr->len - tbr->index)
5544 fn_png_error (png_ptr, "Read error");
5546 memcpy (data, tbr->bytes + tbr->index, length);
5547 tbr->index = tbr->index + length;
5551 /* Function set as reader function when reading PNG image from a file.
5552 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5553 bytes from the input to DATA. */
5555 static void
5556 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5558 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5560 if (fread (data, 1, length, fp) < length)
5561 fn_png_error (png_ptr, "Read error");
5565 /* Load PNG image IMG for use on frame F. Value is non-zero if
5566 successful. */
5568 static int
5569 png_load (struct frame *f, struct image *img)
5571 Lisp_Object file, specified_file;
5572 Lisp_Object specified_data;
5573 int x, y, i;
5574 XImagePtr ximg, mask_img = NULL;
5575 png_struct *png_ptr = NULL;
5576 png_info *info_ptr = NULL, *end_info = NULL;
5577 FILE *volatile fp = NULL;
5578 png_byte sig[8];
5579 png_byte * volatile pixels = NULL;
5580 png_byte ** volatile rows = NULL;
5581 png_uint_32 width, height;
5582 int bit_depth, color_type, interlace_type;
5583 png_byte channels;
5584 png_uint_32 row_bytes;
5585 int transparent_p;
5586 struct png_memory_storage tbr; /* Data to be read */
5588 /* Find out what file to load. */
5589 specified_file = image_spec_value (img->spec, QCfile, NULL);
5590 specified_data = image_spec_value (img->spec, QCdata, NULL);
5592 if (NILP (specified_data))
5594 file = x_find_image_file (specified_file);
5595 if (!STRINGP (file))
5597 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5598 return 0;
5601 /* Open the image file. */
5602 fp = fopen (SSDATA (file), "rb");
5603 if (!fp)
5605 image_error ("Cannot open image file `%s'", file, Qnil);
5606 return 0;
5609 /* Check PNG signature. */
5610 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5611 || fn_png_sig_cmp (sig, 0, sizeof sig))
5613 image_error ("Not a PNG file: `%s'", file, Qnil);
5614 fclose (fp);
5615 return 0;
5618 else
5620 if (!STRINGP (specified_data))
5622 image_error ("Invalid image data `%s'", specified_data, Qnil);
5623 return 0;
5626 /* Read from memory. */
5627 tbr.bytes = SDATA (specified_data);
5628 tbr.len = SBYTES (specified_data);
5629 tbr.index = 0;
5631 /* Check PNG signature. */
5632 if (tbr.len < sizeof sig
5633 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5635 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5636 return 0;
5639 /* Need to skip past the signature. */
5640 tbr.bytes += sizeof (sig);
5643 /* Initialize read and info structs for PNG lib. */
5644 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5645 NULL, my_png_error,
5646 my_png_warning);
5647 if (!png_ptr)
5649 if (fp) fclose (fp);
5650 return 0;
5653 info_ptr = fn_png_create_info_struct (png_ptr);
5654 if (!info_ptr)
5656 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5657 if (fp) fclose (fp);
5658 return 0;
5661 end_info = fn_png_create_info_struct (png_ptr);
5662 if (!end_info)
5664 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5665 if (fp) fclose (fp);
5666 return 0;
5669 /* Set error jump-back. We come back here when the PNG library
5670 detects an error. */
5671 if (setjmp (PNG_JMPBUF (png_ptr)))
5673 error:
5674 if (png_ptr)
5675 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5676 xfree (pixels);
5677 xfree (rows);
5678 if (fp) fclose (fp);
5679 return 0;
5682 /* Read image info. */
5683 if (!NILP (specified_data))
5684 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5685 else
5686 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5688 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5689 fn_png_read_info (png_ptr, info_ptr);
5690 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5691 &interlace_type, NULL, NULL);
5693 if (!check_image_size (f, width, height))
5695 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5696 goto error;
5698 /* If image contains simply transparency data, we prefer to
5699 construct a clipping mask. */
5700 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5701 transparent_p = 1;
5702 else
5703 transparent_p = 0;
5705 /* This function is easier to write if we only have to handle
5706 one data format: RGB or RGBA with 8 bits per channel. Let's
5707 transform other formats into that format. */
5709 /* Strip more than 8 bits per channel. */
5710 if (bit_depth == 16)
5711 fn_png_set_strip_16 (png_ptr);
5713 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5714 if available. */
5715 fn_png_set_expand (png_ptr);
5717 /* Convert grayscale images to RGB. */
5718 if (color_type == PNG_COLOR_TYPE_GRAY
5719 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5720 fn_png_set_gray_to_rgb (png_ptr);
5722 /* Handle alpha channel by combining the image with a background
5723 color. Do this only if a real alpha channel is supplied. For
5724 simple transparency, we prefer a clipping mask. */
5725 if (!transparent_p)
5727 /* png_color_16 *image_bg; */
5728 Lisp_Object specified_bg
5729 = image_spec_value (img->spec, QCbackground, NULL);
5730 int shift = (bit_depth == 16) ? 0 : 8;
5732 if (STRINGP (specified_bg))
5733 /* The user specified `:background', use that. */
5735 XColor color;
5736 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
5738 png_color_16 user_bg;
5740 memset (&user_bg, 0, sizeof user_bg);
5741 user_bg.red = color.red >> shift;
5742 user_bg.green = color.green >> shift;
5743 user_bg.blue = color.blue >> shift;
5745 fn_png_set_background (png_ptr, &user_bg,
5746 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5749 else
5751 /* We use the current frame background, ignoring any default
5752 background color set by the image. */
5753 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5754 XColor color;
5755 png_color_16 frame_background;
5757 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5758 x_query_color (f, &color);
5760 memset (&frame_background, 0, sizeof frame_background);
5761 frame_background.red = color.red >> shift;
5762 frame_background.green = color.green >> shift;
5763 frame_background.blue = color.blue >> shift;
5764 #endif /* HAVE_X_WINDOWS */
5766 fn_png_set_background (png_ptr, &frame_background,
5767 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5771 /* Update info structure. */
5772 fn_png_read_update_info (png_ptr, info_ptr);
5774 /* Get number of channels. Valid values are 1 for grayscale images
5775 and images with a palette, 2 for grayscale images with transparency
5776 information (alpha channel), 3 for RGB images, and 4 for RGB
5777 images with alpha channel, i.e. RGBA. If conversions above were
5778 sufficient we should only have 3 or 4 channels here. */
5779 channels = fn_png_get_channels (png_ptr, info_ptr);
5780 xassert (channels == 3 || channels == 4);
5782 /* Number of bytes needed for one row of the image. */
5783 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5785 /* Allocate memory for the image. */
5786 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
5787 rows = (png_byte **) xmalloc (height * sizeof *rows);
5788 for (i = 0; i < height; ++i)
5789 rows[i] = pixels + i * row_bytes;
5791 /* Read the entire image. */
5792 fn_png_read_image (png_ptr, rows);
5793 fn_png_read_end (png_ptr, info_ptr);
5794 if (fp)
5796 fclose (fp);
5797 fp = NULL;
5800 /* Create the X image and pixmap. */
5801 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5802 &img->pixmap))
5803 goto error;
5805 /* Create an image and pixmap serving as mask if the PNG image
5806 contains an alpha channel. */
5807 if (channels == 4
5808 && !transparent_p
5809 && !x_create_x_image_and_pixmap (f, width, height, 1,
5810 &mask_img, &img->mask))
5812 x_destroy_x_image (ximg);
5813 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5814 img->pixmap = NO_PIXMAP;
5815 goto error;
5818 /* Fill the X image and mask from PNG data. */
5819 init_color_table ();
5821 for (y = 0; y < height; ++y)
5823 png_byte *p = rows[y];
5825 for (x = 0; x < width; ++x)
5827 unsigned r, g, b;
5829 r = *p++ << 8;
5830 g = *p++ << 8;
5831 b = *p++ << 8;
5832 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5833 /* An alpha channel, aka mask channel, associates variable
5834 transparency with an image. Where other image formats
5835 support binary transparency---fully transparent or fully
5836 opaque---PNG allows up to 254 levels of partial transparency.
5837 The PNG library implements partial transparency by combining
5838 the image with a specified background color.
5840 I'm not sure how to handle this here nicely: because the
5841 background on which the image is displayed may change, for
5842 real alpha channel support, it would be necessary to create
5843 a new image for each possible background.
5845 What I'm doing now is that a mask is created if we have
5846 boolean transparency information. Otherwise I'm using
5847 the frame's background color to combine the image with. */
5849 if (channels == 4)
5851 if (mask_img)
5852 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5853 ++p;
5858 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5859 /* Set IMG's background color from the PNG image, unless the user
5860 overrode it. */
5862 png_color_16 *bg;
5863 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5865 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5866 img->background_valid = 1;
5870 #ifdef COLOR_TABLE_SUPPORT
5871 /* Remember colors allocated for this image. */
5872 img->colors = colors_in_color_table (&img->ncolors);
5873 free_color_table ();
5874 #endif /* COLOR_TABLE_SUPPORT */
5876 /* Clean up. */
5877 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5878 xfree (rows);
5879 xfree (pixels);
5881 img->width = width;
5882 img->height = height;
5884 /* Maybe fill in the background field while we have ximg handy.
5885 Casting avoids a GCC warning. */
5886 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5888 /* Put the image into the pixmap, then free the X image and its buffer. */
5889 x_put_x_image (f, ximg, img->pixmap, width, height);
5890 x_destroy_x_image (ximg);
5892 /* Same for the mask. */
5893 if (mask_img)
5895 /* Fill in the background_transparent field while we have the
5896 mask handy. Casting avoids a GCC warning. */
5897 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
5899 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5900 x_destroy_x_image (mask_img);
5903 return 1;
5906 #else /* HAVE_PNG */
5908 #ifdef HAVE_NS
5909 static int
5910 png_load (struct frame *f, struct image *img)
5912 return ns_load_image(f, img,
5913 image_spec_value (img->spec, QCfile, NULL),
5914 image_spec_value (img->spec, QCdata, NULL));
5916 #endif /* HAVE_NS */
5919 #endif /* !HAVE_PNG */
5923 /***********************************************************************
5924 JPEG
5925 ***********************************************************************/
5927 #if defined (HAVE_JPEG) || defined (HAVE_NS)
5929 static int jpeg_image_p (Lisp_Object object);
5930 static int jpeg_load (struct frame *f, struct image *img);
5932 /* The symbol `jpeg' identifying images of this type. */
5934 static Lisp_Object Qjpeg;
5936 /* Indices of image specification fields in gs_format, below. */
5938 enum jpeg_keyword_index
5940 JPEG_TYPE,
5941 JPEG_DATA,
5942 JPEG_FILE,
5943 JPEG_ASCENT,
5944 JPEG_MARGIN,
5945 JPEG_RELIEF,
5946 JPEG_ALGORITHM,
5947 JPEG_HEURISTIC_MASK,
5948 JPEG_MASK,
5949 JPEG_BACKGROUND,
5950 JPEG_LAST
5953 /* Vector of image_keyword structures describing the format
5954 of valid user-defined image specifications. */
5956 static const struct image_keyword jpeg_format[JPEG_LAST] =
5958 {":type", IMAGE_SYMBOL_VALUE, 1},
5959 {":data", IMAGE_STRING_VALUE, 0},
5960 {":file", IMAGE_STRING_VALUE, 0},
5961 {":ascent", IMAGE_ASCENT_VALUE, 0},
5962 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5963 {":relief", IMAGE_INTEGER_VALUE, 0},
5964 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5965 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5966 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5967 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5970 /* Structure describing the image type `jpeg'. */
5972 static struct image_type jpeg_type =
5974 &Qjpeg,
5975 jpeg_image_p,
5976 jpeg_load,
5977 x_clear_image,
5978 NULL
5981 /* Return non-zero if OBJECT is a valid JPEG image specification. */
5983 static int
5984 jpeg_image_p (Lisp_Object object)
5986 struct image_keyword fmt[JPEG_LAST];
5988 memcpy (fmt, jpeg_format, sizeof fmt);
5990 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
5991 return 0;
5993 /* Must specify either the :data or :file keyword. */
5994 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
5997 #endif /* HAVE_JPEG || HAVE_NS */
5999 #ifdef HAVE_JPEG
6001 /* Work around a warning about HAVE_STDLIB_H being redefined in
6002 jconfig.h. */
6003 #ifdef HAVE_STDLIB_H
6004 #undef HAVE_STDLIB_H
6005 #endif /* HAVE_STLIB_H */
6007 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6008 /* In older releases of the jpeg library, jpeglib.h will define boolean
6009 differently depending on __WIN32__, so make sure it is defined. */
6010 #define __WIN32__ 1
6011 #endif
6013 #include <jpeglib.h>
6014 #include <jerror.h>
6016 #ifdef HAVE_STLIB_H_1
6017 #define HAVE_STDLIB_H 1
6018 #endif
6020 #ifdef HAVE_NTGUI
6022 /* JPEG library details. */
6023 DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6024 DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6025 DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6026 DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6027 DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6028 DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6029 DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6030 DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6032 static int
6033 init_jpeg_functions (Lisp_Object libraries)
6035 HMODULE library;
6037 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6038 return 0;
6040 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6041 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6042 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6043 LOAD_IMGLIB_FN (library, jpeg_read_header);
6044 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6045 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6046 LOAD_IMGLIB_FN (library, jpeg_std_error);
6047 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6048 return 1;
6051 /* Wrapper since we can't directly assign the function pointer
6052 to another function pointer that was declared more completely easily. */
6053 static boolean
6054 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6056 return fn_jpeg_resync_to_restart (cinfo, desired);
6059 #else
6061 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6062 #define fn_jpeg_start_decompress jpeg_start_decompress
6063 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6064 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6065 #define fn_jpeg_read_header jpeg_read_header
6066 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6067 #define fn_jpeg_std_error jpeg_std_error
6068 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6070 #endif /* HAVE_NTGUI */
6072 struct my_jpeg_error_mgr
6074 struct jpeg_error_mgr pub;
6075 jmp_buf setjmp_buffer;
6079 static void my_error_exit (j_common_ptr) NO_RETURN;
6080 static void
6081 my_error_exit (j_common_ptr cinfo)
6083 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6084 longjmp (mgr->setjmp_buffer, 1);
6088 /* Init source method for JPEG data source manager. Called by
6089 jpeg_read_header() before any data is actually read. See
6090 libjpeg.doc from the JPEG lib distribution. */
6092 static void
6093 our_common_init_source (j_decompress_ptr cinfo)
6098 /* Method to terminate data source. Called by
6099 jpeg_finish_decompress() after all data has been processed. */
6101 static void
6102 our_common_term_source (j_decompress_ptr cinfo)
6107 /* Fill input buffer method for JPEG data source manager. Called
6108 whenever more data is needed. We read the whole image in one step,
6109 so this only adds a fake end of input marker at the end. */
6111 static JOCTET our_memory_buffer[2];
6113 static boolean
6114 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6116 /* Insert a fake EOI marker. */
6117 struct jpeg_source_mgr *src = cinfo->src;
6119 our_memory_buffer[0] = (JOCTET) 0xFF;
6120 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6122 src->next_input_byte = our_memory_buffer;
6123 src->bytes_in_buffer = 2;
6124 return 1;
6128 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6129 is the JPEG data source manager. */
6131 static void
6132 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6134 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6136 if (src)
6138 if (num_bytes > src->bytes_in_buffer)
6139 ERREXIT (cinfo, JERR_INPUT_EOF);
6141 src->bytes_in_buffer -= num_bytes;
6142 src->next_input_byte += num_bytes;
6147 /* Set up the JPEG lib for reading an image from DATA which contains
6148 LEN bytes. CINFO is the decompression info structure created for
6149 reading the image. */
6151 static void
6152 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, unsigned int len)
6154 struct jpeg_source_mgr *src;
6156 if (cinfo->src == NULL)
6158 /* First time for this JPEG object? */
6159 cinfo->src = (struct jpeg_source_mgr *)
6160 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6161 sizeof (struct jpeg_source_mgr));
6162 src = (struct jpeg_source_mgr *) cinfo->src;
6163 src->next_input_byte = data;
6166 src = (struct jpeg_source_mgr *) cinfo->src;
6167 src->init_source = our_common_init_source;
6168 src->fill_input_buffer = our_memory_fill_input_buffer;
6169 src->skip_input_data = our_memory_skip_input_data;
6170 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6171 src->term_source = our_common_term_source;
6172 src->bytes_in_buffer = len;
6173 src->next_input_byte = data;
6177 struct jpeg_stdio_mgr
6179 struct jpeg_source_mgr mgr;
6180 boolean finished;
6181 FILE *file;
6182 JOCTET *buffer;
6186 /* Size of buffer to read JPEG from file.
6187 Not too big, as we want to use alloc_small. */
6188 #define JPEG_STDIO_BUFFER_SIZE 8192
6191 /* Fill input buffer method for JPEG data source manager. Called
6192 whenever more data is needed. The data is read from a FILE *. */
6194 static boolean
6195 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6197 struct jpeg_stdio_mgr *src;
6199 src = (struct jpeg_stdio_mgr *) cinfo->src;
6200 if (!src->finished)
6202 size_t bytes;
6204 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6205 if (bytes > 0)
6206 src->mgr.bytes_in_buffer = bytes;
6207 else
6209 WARNMS (cinfo, JWRN_JPEG_EOF);
6210 src->finished = 1;
6211 src->buffer[0] = (JOCTET) 0xFF;
6212 src->buffer[1] = (JOCTET) JPEG_EOI;
6213 src->mgr.bytes_in_buffer = 2;
6215 src->mgr.next_input_byte = src->buffer;
6218 return 1;
6222 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6223 is the JPEG data source manager. */
6225 static void
6226 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6228 struct jpeg_stdio_mgr *src;
6229 src = (struct jpeg_stdio_mgr *) cinfo->src;
6231 while (num_bytes > 0 && !src->finished)
6233 if (num_bytes <= src->mgr.bytes_in_buffer)
6235 src->mgr.bytes_in_buffer -= num_bytes;
6236 src->mgr.next_input_byte += num_bytes;
6237 break;
6239 else
6241 num_bytes -= src->mgr.bytes_in_buffer;
6242 src->mgr.bytes_in_buffer = 0;
6243 src->mgr.next_input_byte = NULL;
6245 our_stdio_fill_input_buffer (cinfo);
6251 /* Set up the JPEG lib for reading an image from a FILE *.
6252 CINFO is the decompression info structure created for
6253 reading the image. */
6255 static void
6256 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6258 struct jpeg_stdio_mgr *src;
6260 if (cinfo->src != NULL)
6261 src = (struct jpeg_stdio_mgr *) cinfo->src;
6262 else
6264 /* First time for this JPEG object? */
6265 cinfo->src = (struct jpeg_source_mgr *)
6266 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6267 sizeof (struct jpeg_stdio_mgr));
6268 src = (struct jpeg_stdio_mgr *) cinfo->src;
6269 src->buffer = (JOCTET *)
6270 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6271 JPEG_STDIO_BUFFER_SIZE);
6274 src->file = fp;
6275 src->finished = 0;
6276 src->mgr.init_source = our_common_init_source;
6277 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6278 src->mgr.skip_input_data = our_stdio_skip_input_data;
6279 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6280 src->mgr.term_source = our_common_term_source;
6281 src->mgr.bytes_in_buffer = 0;
6282 src->mgr.next_input_byte = NULL;
6286 /* Load image IMG for use on frame F. Patterned after example.c
6287 from the JPEG lib. */
6289 static int
6290 jpeg_load (struct frame *f, struct image *img)
6292 struct jpeg_decompress_struct cinfo;
6293 struct my_jpeg_error_mgr mgr;
6294 Lisp_Object file, specified_file;
6295 Lisp_Object specified_data;
6296 FILE * volatile fp = NULL;
6297 JSAMPARRAY buffer;
6298 int row_stride, x, y;
6299 XImagePtr ximg = NULL;
6300 int rc;
6301 unsigned long *colors;
6302 int width, height;
6304 /* Open the JPEG file. */
6305 specified_file = image_spec_value (img->spec, QCfile, NULL);
6306 specified_data = image_spec_value (img->spec, QCdata, NULL);
6308 if (NILP (specified_data))
6310 file = x_find_image_file (specified_file);
6311 if (!STRINGP (file))
6313 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6314 return 0;
6317 fp = fopen (SSDATA (file), "rb");
6318 if (fp == NULL)
6320 image_error ("Cannot open `%s'", file, Qnil);
6321 return 0;
6324 else if (!STRINGP (specified_data))
6326 image_error ("Invalid image data `%s'", specified_data, Qnil);
6327 return 0;
6330 /* Customize libjpeg's error handling to call my_error_exit when an
6331 error is detected. This function will perform a longjmp. */
6332 cinfo.err = fn_jpeg_std_error (&mgr.pub);
6333 mgr.pub.error_exit = my_error_exit;
6335 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6337 if (rc == 1)
6339 /* Called from my_error_exit. Display a JPEG error. */
6340 char buf[JMSG_LENGTH_MAX];
6341 cinfo.err->format_message ((j_common_ptr) &cinfo, buf);
6342 image_error ("Error reading JPEG image `%s': %s", img->spec,
6343 build_string (buf));
6346 /* Close the input file and destroy the JPEG object. */
6347 if (fp)
6348 fclose ((FILE *) fp);
6349 fn_jpeg_destroy_decompress (&cinfo);
6351 /* If we already have an XImage, free that. */
6352 x_destroy_x_image (ximg);
6354 /* Free pixmap and colors. */
6355 x_clear_image (f, img);
6356 return 0;
6359 /* Create the JPEG decompression object. Let it read from fp.
6360 Read the JPEG image header. */
6361 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6363 if (NILP (specified_data))
6364 jpeg_file_src (&cinfo, (FILE *) fp);
6365 else
6366 jpeg_memory_src (&cinfo, SDATA (specified_data),
6367 SBYTES (specified_data));
6369 fn_jpeg_read_header (&cinfo, 1);
6371 /* Customize decompression so that color quantization will be used.
6372 Start decompression. */
6373 cinfo.quantize_colors = 1;
6374 fn_jpeg_start_decompress (&cinfo);
6375 width = img->width = cinfo.output_width;
6376 height = img->height = cinfo.output_height;
6378 if (!check_image_size (f, width, height))
6380 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6381 longjmp (mgr.setjmp_buffer, 2);
6384 /* Create X image and pixmap. */
6385 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6386 longjmp (mgr.setjmp_buffer, 2);
6388 /* Allocate colors. When color quantization is used,
6389 cinfo.actual_number_of_colors has been set with the number of
6390 colors generated, and cinfo.colormap is a two-dimensional array
6391 of color indices in the range 0..cinfo.actual_number_of_colors.
6392 No more than 255 colors will be generated. */
6394 int i, ir, ig, ib;
6396 if (cinfo.out_color_components > 2)
6397 ir = 0, ig = 1, ib = 2;
6398 else if (cinfo.out_color_components > 1)
6399 ir = 0, ig = 1, ib = 0;
6400 else
6401 ir = 0, ig = 0, ib = 0;
6403 /* Use the color table mechanism because it handles colors that
6404 cannot be allocated nicely. Such colors will be replaced with
6405 a default color, and we don't have to care about which colors
6406 can be freed safely, and which can't. */
6407 init_color_table ();
6408 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6409 * sizeof *colors);
6411 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6413 /* Multiply RGB values with 255 because X expects RGB values
6414 in the range 0..0xffff. */
6415 int r = cinfo.colormap[ir][i] << 8;
6416 int g = cinfo.colormap[ig][i] << 8;
6417 int b = cinfo.colormap[ib][i] << 8;
6418 colors[i] = lookup_rgb_color (f, r, g, b);
6421 #ifdef COLOR_TABLE_SUPPORT
6422 /* Remember those colors actually allocated. */
6423 img->colors = colors_in_color_table (&img->ncolors);
6424 free_color_table ();
6425 #endif /* COLOR_TABLE_SUPPORT */
6428 /* Read pixels. */
6429 row_stride = width * cinfo.output_components;
6430 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6431 row_stride, 1);
6432 for (y = 0; y < height; ++y)
6434 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6435 for (x = 0; x < cinfo.output_width; ++x)
6436 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6439 /* Clean up. */
6440 fn_jpeg_finish_decompress (&cinfo);
6441 fn_jpeg_destroy_decompress (&cinfo);
6442 if (fp)
6443 fclose ((FILE *) fp);
6445 /* Maybe fill in the background field while we have ximg handy. */
6446 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6447 /* Casting avoids a GCC warning. */
6448 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6450 /* Put the image into the pixmap. */
6451 x_put_x_image (f, ximg, img->pixmap, width, height);
6452 x_destroy_x_image (ximg);
6453 return 1;
6456 #else /* HAVE_JPEG */
6458 #ifdef HAVE_NS
6459 static int
6460 jpeg_load (struct frame *f, struct image *img)
6462 return ns_load_image (f, img,
6463 image_spec_value (img->spec, QCfile, NULL),
6464 image_spec_value (img->spec, QCdata, NULL));
6466 #endif /* HAVE_NS */
6468 #endif /* !HAVE_JPEG */
6472 /***********************************************************************
6473 TIFF
6474 ***********************************************************************/
6476 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6478 static int tiff_image_p (Lisp_Object object);
6479 static int tiff_load (struct frame *f, struct image *img);
6481 /* The symbol `tiff' identifying images of this type. */
6483 static Lisp_Object Qtiff;
6485 /* Indices of image specification fields in tiff_format, below. */
6487 enum tiff_keyword_index
6489 TIFF_TYPE,
6490 TIFF_DATA,
6491 TIFF_FILE,
6492 TIFF_ASCENT,
6493 TIFF_MARGIN,
6494 TIFF_RELIEF,
6495 TIFF_ALGORITHM,
6496 TIFF_HEURISTIC_MASK,
6497 TIFF_MASK,
6498 TIFF_BACKGROUND,
6499 TIFF_INDEX,
6500 TIFF_LAST
6503 /* Vector of image_keyword structures describing the format
6504 of valid user-defined image specifications. */
6506 static const struct image_keyword tiff_format[TIFF_LAST] =
6508 {":type", IMAGE_SYMBOL_VALUE, 1},
6509 {":data", IMAGE_STRING_VALUE, 0},
6510 {":file", IMAGE_STRING_VALUE, 0},
6511 {":ascent", IMAGE_ASCENT_VALUE, 0},
6512 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6513 {":relief", IMAGE_INTEGER_VALUE, 0},
6514 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6515 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6516 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6517 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6518 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6521 /* Structure describing the image type `tiff'. */
6523 static struct image_type tiff_type =
6525 &Qtiff,
6526 tiff_image_p,
6527 tiff_load,
6528 x_clear_image,
6529 NULL
6532 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6534 static int
6535 tiff_image_p (Lisp_Object object)
6537 struct image_keyword fmt[TIFF_LAST];
6538 memcpy (fmt, tiff_format, sizeof fmt);
6540 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6541 return 0;
6543 /* Must specify either the :data or :file keyword. */
6544 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6547 #endif /* HAVE_TIFF || HAVE_NS */
6549 #ifdef HAVE_TIFF
6551 #include <tiffio.h>
6553 #ifdef HAVE_NTGUI
6555 /* TIFF library details. */
6556 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6557 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6558 DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6559 DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
6560 TIFFReadWriteProc, TIFFReadWriteProc,
6561 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6562 TIFFMapFileProc, TIFFUnmapFileProc));
6563 DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6564 DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6565 DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6566 DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6568 static int
6569 init_tiff_functions (Lisp_Object libraries)
6571 HMODULE library;
6573 if (!(library = w32_delayed_load (libraries, Qtiff)))
6574 return 0;
6576 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6577 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6578 LOAD_IMGLIB_FN (library, TIFFOpen);
6579 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6580 LOAD_IMGLIB_FN (library, TIFFGetField);
6581 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6582 LOAD_IMGLIB_FN (library, TIFFClose);
6583 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6584 return 1;
6587 #else
6589 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6590 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6591 #define fn_TIFFOpen TIFFOpen
6592 #define fn_TIFFClientOpen TIFFClientOpen
6593 #define fn_TIFFGetField TIFFGetField
6594 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6595 #define fn_TIFFClose TIFFClose
6596 #define fn_TIFFSetDirectory TIFFSetDirectory
6597 #endif /* HAVE_NTGUI */
6600 /* Reading from a memory buffer for TIFF images Based on the PNG
6601 memory source, but we have to provide a lot of extra functions.
6602 Blah.
6604 We really only need to implement read and seek, but I am not
6605 convinced that the TIFF library is smart enough not to destroy
6606 itself if we only hand it the function pointers we need to
6607 override. */
6609 typedef struct
6611 unsigned char *bytes;
6612 size_t len;
6613 int index;
6615 tiff_memory_source;
6617 static size_t
6618 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6620 tiff_memory_source *src = (tiff_memory_source *) data;
6622 if (size > src->len - src->index)
6623 return (size_t) -1;
6624 memcpy (buf, src->bytes + src->index, size);
6625 src->index += size;
6626 return size;
6629 static size_t
6630 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6632 return (size_t) -1;
6635 static toff_t
6636 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6638 tiff_memory_source *src = (tiff_memory_source *) data;
6639 int idx;
6641 switch (whence)
6643 case SEEK_SET: /* Go from beginning of source. */
6644 idx = off;
6645 break;
6647 case SEEK_END: /* Go from end of source. */
6648 idx = src->len + off;
6649 break;
6651 case SEEK_CUR: /* Go from current position. */
6652 idx = src->index + off;
6653 break;
6655 default: /* Invalid `whence'. */
6656 return -1;
6659 if (idx > src->len || idx < 0)
6660 return -1;
6662 src->index = idx;
6663 return src->index;
6666 static int
6667 tiff_close_memory (thandle_t data)
6669 /* NOOP */
6670 return 0;
6673 static int
6674 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6676 /* It is already _IN_ memory. */
6677 return 0;
6680 static void
6681 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6683 /* We don't need to do this. */
6686 static toff_t
6687 tiff_size_of_memory (thandle_t data)
6689 return ((tiff_memory_source *) data)->len;
6693 static void tiff_error_handler (const char *, const char *, va_list)
6694 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6695 static void
6696 tiff_error_handler (const char *title, const char *format, va_list ap)
6698 char buf[512];
6699 int len;
6701 len = sprintf (buf, "TIFF error: %s ", title);
6702 vsprintf (buf + len, format, ap);
6703 add_to_log (buf, Qnil, Qnil);
6707 static void tiff_warning_handler (const char *, const char *, va_list)
6708 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6709 static void
6710 tiff_warning_handler (const char *title, const char *format, va_list ap)
6712 char buf[512];
6713 int len;
6715 len = sprintf (buf, "TIFF warning: %s ", title);
6716 vsprintf (buf + len, format, ap);
6717 add_to_log (buf, Qnil, Qnil);
6721 /* Load TIFF image IMG for use on frame F. Value is non-zero if
6722 successful. */
6724 static int
6725 tiff_load (struct frame *f, struct image *img)
6727 Lisp_Object file, specified_file;
6728 Lisp_Object specified_data;
6729 TIFF *tiff;
6730 int width, height, x, y, count;
6731 uint32 *buf;
6732 int rc;
6733 XImagePtr ximg;
6734 tiff_memory_source memsrc;
6735 Lisp_Object image;
6737 specified_file = image_spec_value (img->spec, QCfile, NULL);
6738 specified_data = image_spec_value (img->spec, QCdata, NULL);
6740 fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6741 fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
6743 if (NILP (specified_data))
6745 /* Read from a file */
6746 file = x_find_image_file (specified_file);
6747 if (!STRINGP (file))
6749 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6750 return 0;
6753 /* Try to open the image file. */
6754 tiff = fn_TIFFOpen (SSDATA (file), "r");
6755 if (tiff == NULL)
6757 image_error ("Cannot open `%s'", file, Qnil);
6758 return 0;
6761 else
6763 if (!STRINGP (specified_data))
6765 image_error ("Invalid image data `%s'", specified_data, Qnil);
6766 return 0;
6769 /* Memory source! */
6770 memsrc.bytes = SDATA (specified_data);
6771 memsrc.len = SBYTES (specified_data);
6772 memsrc.index = 0;
6774 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
6775 (TIFFReadWriteProc) tiff_read_from_memory,
6776 (TIFFReadWriteProc) tiff_write_from_memory,
6777 tiff_seek_in_memory,
6778 tiff_close_memory,
6779 tiff_size_of_memory,
6780 tiff_mmap_memory,
6781 tiff_unmap_memory);
6783 if (!tiff)
6785 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6786 return 0;
6790 image = image_spec_value (img->spec, QCindex, NULL);
6791 if (INTEGERP (image))
6793 int ino = XFASTINT (image);
6794 if (!fn_TIFFSetDirectory (tiff, ino))
6796 image_error ("Invalid image number `%s' in image `%s'",
6797 image, img->spec);
6798 fn_TIFFClose (tiff);
6799 return 0;
6803 /* Get width and height of the image, and allocate a raster buffer
6804 of width x height 32-bit values. */
6805 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6806 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6808 if (!check_image_size (f, width, height))
6810 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6811 fn_TIFFClose (tiff);
6812 return 0;
6815 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
6817 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
6819 /* Count the number of images in the file. */
6820 for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
6821 continue;
6823 if (count > 1)
6824 img->data.lisp_val = Fcons (Qcount,
6825 Fcons (make_number (count),
6826 img->data.lisp_val));
6828 fn_TIFFClose (tiff);
6829 if (!rc)
6831 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6832 xfree (buf);
6833 return 0;
6836 /* Create the X image and pixmap. */
6837 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6839 xfree (buf);
6840 return 0;
6843 /* Initialize the color table. */
6844 init_color_table ();
6846 /* Process the pixel raster. Origin is in the lower-left corner. */
6847 for (y = 0; y < height; ++y)
6849 uint32 *row = buf + y * width;
6851 for (x = 0; x < width; ++x)
6853 uint32 abgr = row[x];
6854 int r = TIFFGetR (abgr) << 8;
6855 int g = TIFFGetG (abgr) << 8;
6856 int b = TIFFGetB (abgr) << 8;
6857 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6861 #ifdef COLOR_TABLE_SUPPORT
6862 /* Remember the colors allocated for the image. Free the color table. */
6863 img->colors = colors_in_color_table (&img->ncolors);
6864 free_color_table ();
6865 #endif /* COLOR_TABLE_SUPPORT */
6867 img->width = width;
6868 img->height = height;
6870 /* Maybe fill in the background field while we have ximg handy. */
6871 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6872 /* Casting avoids a GCC warning on W32. */
6873 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6875 /* Put the image into the pixmap, then free the X image and its buffer. */
6876 x_put_x_image (f, ximg, img->pixmap, width, height);
6877 x_destroy_x_image (ximg);
6878 xfree (buf);
6880 return 1;
6883 #else /* HAVE_TIFF */
6885 #ifdef HAVE_NS
6886 static int
6887 tiff_load (struct frame *f, struct image *img)
6889 return ns_load_image (f, img,
6890 image_spec_value (img->spec, QCfile, NULL),
6891 image_spec_value (img->spec, QCdata, NULL));
6893 #endif /* HAVE_NS */
6895 #endif /* !HAVE_TIFF */
6899 /***********************************************************************
6901 ***********************************************************************/
6903 #if defined (HAVE_GIF) || defined (HAVE_NS)
6905 static int gif_image_p (Lisp_Object object);
6906 static int gif_load (struct frame *f, struct image *img);
6907 static void gif_clear_image (struct frame *f, struct image *img);
6909 /* The symbol `gif' identifying images of this type. */
6911 static Lisp_Object Qgif;
6913 /* Indices of image specification fields in gif_format, below. */
6915 enum gif_keyword_index
6917 GIF_TYPE,
6918 GIF_DATA,
6919 GIF_FILE,
6920 GIF_ASCENT,
6921 GIF_MARGIN,
6922 GIF_RELIEF,
6923 GIF_ALGORITHM,
6924 GIF_HEURISTIC_MASK,
6925 GIF_MASK,
6926 GIF_IMAGE,
6927 GIF_BACKGROUND,
6928 GIF_LAST
6931 /* Vector of image_keyword structures describing the format
6932 of valid user-defined image specifications. */
6934 static const struct image_keyword gif_format[GIF_LAST] =
6936 {":type", IMAGE_SYMBOL_VALUE, 1},
6937 {":data", IMAGE_STRING_VALUE, 0},
6938 {":file", IMAGE_STRING_VALUE, 0},
6939 {":ascent", IMAGE_ASCENT_VALUE, 0},
6940 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6941 {":relief", IMAGE_INTEGER_VALUE, 0},
6942 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6943 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6944 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6945 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
6946 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6949 /* Structure describing the image type `gif'. */
6951 static struct image_type gif_type =
6953 &Qgif,
6954 gif_image_p,
6955 gif_load,
6956 gif_clear_image,
6957 NULL
6960 /* Free X resources of GIF image IMG which is used on frame F. */
6962 static void
6963 gif_clear_image (struct frame *f, struct image *img)
6965 /* IMG->data.ptr_val may contain metadata with extension data. */
6966 img->data.lisp_val = Qnil;
6967 x_clear_image (f, img);
6970 /* Return non-zero if OBJECT is a valid GIF image specification. */
6972 static int
6973 gif_image_p (Lisp_Object object)
6975 struct image_keyword fmt[GIF_LAST];
6976 memcpy (fmt, gif_format, sizeof fmt);
6978 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
6979 return 0;
6981 /* Must specify either the :data or :file keyword. */
6982 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
6985 #endif /* HAVE_GIF */
6987 #ifdef HAVE_GIF
6989 #if defined (HAVE_NTGUI)
6990 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
6991 Undefine before redefining to avoid a preprocessor warning. */
6992 #ifdef DrawText
6993 #undef DrawText
6994 #endif
6995 /* avoid conflict with QuickdrawText.h */
6996 #define DrawText gif_DrawText
6997 #include <gif_lib.h>
6998 #undef DrawText
7000 #else /* HAVE_NTGUI */
7002 #include <gif_lib.h>
7004 #endif /* HAVE_NTGUI */
7007 #ifdef HAVE_NTGUI
7009 /* GIF library details. */
7010 DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7011 DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7012 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7013 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
7015 static int
7016 init_gif_functions (Lisp_Object libraries)
7018 HMODULE library;
7020 if (!(library = w32_delayed_load (libraries, Qgif)))
7021 return 0;
7023 LOAD_IMGLIB_FN (library, DGifCloseFile);
7024 LOAD_IMGLIB_FN (library, DGifSlurp);
7025 LOAD_IMGLIB_FN (library, DGifOpen);
7026 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7027 return 1;
7030 #else
7032 #define fn_DGifCloseFile DGifCloseFile
7033 #define fn_DGifSlurp DGifSlurp
7034 #define fn_DGifOpen DGifOpen
7035 #define fn_DGifOpenFileName DGifOpenFileName
7037 #endif /* HAVE_NTGUI */
7039 /* Reading a GIF image from memory
7040 Based on the PNG memory stuff to a certain extent. */
7042 typedef struct
7044 unsigned char *bytes;
7045 size_t len;
7046 int index;
7048 gif_memory_source;
7050 /* Make the current memory source available to gif_read_from_memory.
7051 It's done this way because not all versions of libungif support
7052 a UserData field in the GifFileType structure. */
7053 static gif_memory_source *current_gif_memory_src;
7055 static int
7056 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7058 gif_memory_source *src = current_gif_memory_src;
7060 if (len > src->len - src->index)
7061 return -1;
7063 memcpy (buf, src->bytes + src->index, len);
7064 src->index += len;
7065 return len;
7069 /* Load GIF image IMG for use on frame F. Value is non-zero if
7070 successful. */
7072 static const int interlace_start[] = {0, 4, 2, 1};
7073 static const int interlace_increment[] = {8, 8, 4, 2};
7075 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7077 static int
7078 gif_load (struct frame *f, struct image *img)
7080 Lisp_Object file, specified_file;
7081 Lisp_Object specified_data;
7082 int rc, width, height, x, y, i;
7083 boolean transparent_p = 0;
7084 XImagePtr ximg;
7085 ColorMapObject *gif_color_map;
7086 unsigned long pixel_colors[256];
7087 GifFileType *gif;
7088 Lisp_Object image;
7089 int ino, image_height, image_width;
7090 gif_memory_source memsrc;
7091 unsigned char *raster;
7092 unsigned int transparency_color_index IF_LINT (= 0);
7094 specified_file = image_spec_value (img->spec, QCfile, NULL);
7095 specified_data = image_spec_value (img->spec, QCdata, NULL);
7097 if (NILP (specified_data))
7099 file = x_find_image_file (specified_file);
7100 if (!STRINGP (file))
7102 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7103 return 0;
7106 /* Open the GIF file. */
7107 gif = fn_DGifOpenFileName (SSDATA (file));
7108 if (gif == NULL)
7110 image_error ("Cannot open `%s'", file, Qnil);
7111 return 0;
7114 else
7116 if (!STRINGP (specified_data))
7118 image_error ("Invalid image data `%s'", specified_data, Qnil);
7119 return 0;
7122 /* Read from memory! */
7123 current_gif_memory_src = &memsrc;
7124 memsrc.bytes = SDATA (specified_data);
7125 memsrc.len = SBYTES (specified_data);
7126 memsrc.index = 0;
7128 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
7129 if (!gif)
7131 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7132 return 0;
7136 /* Before reading entire contents, check the declared image size. */
7137 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7139 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7140 fn_DGifCloseFile (gif);
7141 return 0;
7144 /* Read entire contents. */
7145 rc = fn_DGifSlurp (gif);
7146 if (rc == GIF_ERROR)
7148 image_error ("Error reading `%s'", img->spec, Qnil);
7149 fn_DGifCloseFile (gif);
7150 return 0;
7153 image = image_spec_value (img->spec, QCindex, NULL);
7154 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7155 if (ino >= gif->ImageCount)
7157 image_error ("Invalid image number `%s' in image `%s'",
7158 image, img->spec);
7159 fn_DGifCloseFile (gif);
7160 return 0;
7163 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++)
7164 if ((gif->SavedImages[ino].ExtensionBlocks[i].Function
7165 == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7166 && gif->SavedImages[ino].ExtensionBlocks[i].ByteCount == 4
7167 /* Transparency enabled? */
7168 && gif->SavedImages[ino].ExtensionBlocks[i].Bytes[0] & 1)
7170 transparent_p = 1;
7171 transparency_color_index
7172 = (unsigned char) gif->SavedImages[ino].ExtensionBlocks[i].Bytes[3];
7175 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
7176 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
7177 image_height = gif->SavedImages[ino].ImageDesc.Height;
7178 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
7179 image_width = gif->SavedImages[ino].ImageDesc.Width;
7180 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
7182 width = img->width = max (gif->SWidth,
7183 max (gif->Image.Left + gif->Image.Width,
7184 img->corners[RIGHT_CORNER]));
7185 height = img->height = max (gif->SHeight,
7186 max (gif->Image.Top + gif->Image.Height,
7187 img->corners[BOT_CORNER]));
7189 if (!check_image_size (f, width, height))
7191 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7192 fn_DGifCloseFile (gif);
7193 return 0;
7196 /* Create the X image and pixmap. */
7197 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7199 fn_DGifCloseFile (gif);
7200 return 0;
7203 /* Allocate colors. */
7204 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7205 if (!gif_color_map)
7206 gif_color_map = gif->SColorMap;
7207 init_color_table ();
7208 memset (pixel_colors, 0, sizeof pixel_colors);
7210 if (gif_color_map)
7211 for (i = 0; i < gif_color_map->ColorCount; ++i)
7213 if (transparent_p && transparency_color_index == i)
7215 Lisp_Object specified_bg
7216 = image_spec_value (img->spec, QCbackground, NULL);
7217 pixel_colors[i] = STRINGP (specified_bg)
7218 ? x_alloc_image_color (f, img, specified_bg,
7219 FRAME_BACKGROUND_PIXEL (f))
7220 : FRAME_BACKGROUND_PIXEL (f);
7222 else
7224 int r = gif_color_map->Colors[i].Red << 8;
7225 int g = gif_color_map->Colors[i].Green << 8;
7226 int b = gif_color_map->Colors[i].Blue << 8;
7227 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7231 #ifdef COLOR_TABLE_SUPPORT
7232 img->colors = colors_in_color_table (&img->ncolors);
7233 free_color_table ();
7234 #endif /* COLOR_TABLE_SUPPORT */
7236 /* Clear the part of the screen image that are not covered by
7237 the image from the GIF file. Full animated GIF support
7238 requires more than can be done here (see the gif89 spec,
7239 disposal methods). Let's simply assume that the part
7240 not covered by a sub-image is in the frame's background color. */
7241 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7242 for (x = 0; x < width; ++x)
7243 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7245 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7246 for (x = 0; x < width; ++x)
7247 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7249 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7251 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7252 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7253 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7254 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7257 /* Read the GIF image into the X image. We use a local variable
7258 `raster' here because RasterBits below is a char *, and invites
7259 problems with bytes >= 0x80. */
7260 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7262 if (gif->SavedImages[ino].ImageDesc.Interlace)
7264 int pass;
7265 int row = interlace_start[0];
7267 pass = 0;
7269 for (y = 0; y < image_height; y++)
7271 if (row >= image_height)
7273 row = interlace_start[++pass];
7274 while (row >= image_height)
7275 row = interlace_start[++pass];
7278 for (x = 0; x < image_width; x++)
7280 int c = raster[(y * image_width) + x];
7281 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7282 row + img->corners[TOP_CORNER], pixel_colors[c]);
7285 row += interlace_increment[pass];
7288 else
7290 for (y = 0; y < image_height; ++y)
7291 for (x = 0; x < image_width; ++x)
7293 int c = raster[y * image_width + x];
7294 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7295 y + img->corners[TOP_CORNER], pixel_colors[c]);
7299 /* Save GIF image extension data for `image-metadata'.
7300 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7301 img->data.lisp_val = Qnil;
7302 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
7304 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
7305 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
7306 /* Append (... FUNCTION "BYTES") */
7307 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7308 Fcons (make_number (ext->Function),
7309 img->data.lisp_val));
7310 img->data.lisp_val = Fcons (Qextension_data,
7311 Fcons (Fnreverse (img->data.lisp_val),
7312 Qnil));
7314 if (gif->ImageCount > 1)
7315 img->data.lisp_val = Fcons (Qcount,
7316 Fcons (make_number (gif->ImageCount),
7317 img->data.lisp_val));
7319 fn_DGifCloseFile (gif);
7321 /* Maybe fill in the background field while we have ximg handy. */
7322 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7323 /* Casting avoids a GCC warning. */
7324 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7326 /* Put the image into the pixmap, then free the X image and its buffer. */
7327 x_put_x_image (f, ximg, img->pixmap, width, height);
7328 x_destroy_x_image (ximg);
7330 return 1;
7333 #else /* !HAVE_GIF */
7335 #ifdef HAVE_NS
7336 static int
7337 gif_load (struct frame *f, struct image *img)
7339 return ns_load_image (f, img,
7340 image_spec_value (img->spec, QCfile, NULL),
7341 image_spec_value (img->spec, QCdata, NULL));
7343 #endif /* HAVE_NS */
7345 #endif /* HAVE_GIF */
7348 /***********************************************************************
7349 ImageMagick
7350 ***********************************************************************/
7351 #if defined (HAVE_IMAGEMAGICK)
7353 Lisp_Object Qimagemagick;
7355 /* Indices of image specification fields in imagemagick_format. */
7357 enum imagemagick_keyword_index
7359 IMAGEMAGICK_TYPE,
7360 IMAGEMAGICK_DATA,
7361 IMAGEMAGICK_FILE,
7362 IMAGEMAGICK_ASCENT,
7363 IMAGEMAGICK_MARGIN,
7364 IMAGEMAGICK_RELIEF,
7365 IMAGEMAGICK_ALGORITHM,
7366 IMAGEMAGICK_HEURISTIC_MASK,
7367 IMAGEMAGICK_MASK,
7368 IMAGEMAGICK_BACKGROUND,
7369 IMAGEMAGICK_HEIGHT,
7370 IMAGEMAGICK_WIDTH,
7371 IMAGEMAGICK_ROTATION,
7372 IMAGEMAGICK_CROP,
7373 IMAGEMAGICK_LAST
7376 /* Vector of image_keyword structures describing the format
7377 of valid user-defined image specifications. */
7379 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7381 {":type", IMAGE_SYMBOL_VALUE, 1},
7382 {":data", IMAGE_STRING_VALUE, 0},
7383 {":file", IMAGE_STRING_VALUE, 0},
7384 {":ascent", IMAGE_ASCENT_VALUE, 0},
7385 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7386 {":relief", IMAGE_INTEGER_VALUE, 0},
7387 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7388 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7389 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7390 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7391 {":height", IMAGE_INTEGER_VALUE, 0},
7392 {":width", IMAGE_INTEGER_VALUE, 0},
7393 {":rotation", IMAGE_NUMBER_VALUE, 0},
7394 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7397 /* Free X resources of imagemagick image IMG which is used on frame F. */
7399 static void
7400 imagemagick_clear_image (struct frame *f,
7401 struct image *img)
7403 x_clear_image (f, img);
7406 /* Return non-zero if OBJECT is a valid IMAGEMAGICK image specification. Do
7407 this by calling parse_image_spec and supplying the keywords that
7408 identify the IMAGEMAGICK format. */
7410 static int
7411 imagemagick_image_p (Lisp_Object object)
7413 struct image_keyword fmt[IMAGEMAGICK_LAST];
7414 memcpy (fmt, imagemagick_format, sizeof fmt);
7416 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7417 return 0;
7419 /* Must specify either the :data or :file keyword. */
7420 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7423 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7424 Therefore rename the function so it doesnt collide with ImageMagick. */
7425 #define DrawRectangle DrawRectangleGif
7426 #include <wand/MagickWand.h>
7428 /* imagemagick_load_image is a helper function for imagemagick_load,
7429 which does the actual loading given contents and size, apart from
7430 frame and image structures, passed from imagemagick_load.
7432 Uses librimagemagick to do most of the image processing.
7434 Return non-zero if successful.
7437 static int
7438 imagemagick_load_image (/* Pointer to emacs frame structure. */
7439 struct frame *f,
7440 /* Pointer to emacs image structure. */
7441 struct image *img,
7442 /* String containing the IMAGEMAGICK data to
7443 be parsed. */
7444 unsigned char *contents,
7445 /* Size of data in bytes. */
7446 unsigned int size,
7447 /* Filename, either pass filename or
7448 contents/size. */
7449 unsigned char *filename)
7451 unsigned long width;
7452 unsigned long height;
7454 MagickBooleanType
7455 status;
7457 XImagePtr ximg;
7458 Lisp_Object specified_bg;
7459 XColor background;
7460 int x;
7461 int y;
7463 MagickWand *image_wand;
7464 MagickWand *ping_wand;
7465 PixelIterator *iterator;
7466 PixelWand **pixels;
7467 MagickPixelPacket pixel;
7468 Lisp_Object image;
7469 Lisp_Object value;
7470 Lisp_Object crop, geometry;
7471 long ino;
7472 int desired_width, desired_height;
7473 double rotation;
7474 int imagemagick_rendermethod;
7475 int pixelwidth;
7476 ImageInfo *image_info;
7477 ExceptionInfo *exception;
7478 Image * im_image;
7481 /* Handle image index for image types who can contain more than one image.
7482 Interface :index is same as for GIF. First we "ping" the image to see how
7483 many sub-images it contains. Pinging is faster than loading the image to
7484 find out things about it. */
7486 /* Initialize the imagemagick environment. */
7487 MagickWandGenesis ();
7488 image = image_spec_value (img->spec, QCindex, NULL);
7489 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7490 ping_wand = NewMagickWand ();
7491 MagickSetResolution (ping_wand, 2, 2);
7492 if (filename != NULL)
7494 status = MagickPingImage (ping_wand, filename);
7496 else
7498 status = MagickPingImageBlob (ping_wand, contents, size);
7501 if (ino >= MagickGetNumberImages (ping_wand))
7503 image_error ("Invalid image number `%s' in image `%s'",
7504 image, img->spec);
7505 DestroyMagickWand (ping_wand);
7506 return 0;
7509 if (MagickGetNumberImages(ping_wand) > 1)
7510 img->data.lisp_val =
7511 Fcons (Qcount,
7512 Fcons (make_number (MagickGetNumberImages (ping_wand)),
7513 img->data.lisp_val));
7515 DestroyMagickWand (ping_wand);
7517 /* Now, after pinging, we know how many images are inside the
7518 file. If it's not a bundle, the number is one. */
7520 if (filename != NULL)
7522 image_info = CloneImageInfo ((ImageInfo *) NULL);
7523 (void) strcpy (image_info->filename, filename);
7524 image_info->number_scenes = 1;
7525 image_info->scene = ino;
7526 exception = AcquireExceptionInfo ();
7528 im_image = ReadImage (image_info, exception);
7529 DestroyExceptionInfo (exception);
7531 if (im_image != NULL)
7533 image_wand = NewMagickWandFromImage (im_image);
7534 DestroyImage(im_image);
7535 status = MagickTrue;
7537 else
7538 status = MagickFalse;
7540 else
7542 image_wand = NewMagickWand ();
7543 status = MagickReadImageBlob (image_wand, contents, size);
7546 if (status == MagickFalse) goto imagemagick_error;
7548 /* If width and/or height is set in the display spec assume we want
7549 to scale to those values. If either h or w is unspecified, the
7550 unspecified should be calculated from the specified to preserve
7551 aspect ratio. */
7553 value = image_spec_value (img->spec, QCwidth, NULL);
7554 desired_width = (INTEGERP (value) ? XFASTINT (value) : -1);
7555 value = image_spec_value (img->spec, QCheight, NULL);
7556 desired_height = (INTEGERP (value) ? XFASTINT (value) : -1);
7558 height = MagickGetImageHeight (image_wand);
7559 width = MagickGetImageWidth (image_wand);
7561 if (desired_width != -1 && desired_height == -1)
7562 /* w known, calculate h. */
7563 desired_height = (double) desired_width / width * height;
7564 if (desired_width == -1 && desired_height != -1)
7565 /* h known, calculate w. */
7566 desired_width = (double) desired_height / height * width;
7567 if (desired_width != -1 && desired_height != -1)
7569 status = MagickScaleImage (image_wand, desired_width, desired_height);
7570 if (status == MagickFalse)
7572 image_error ("Imagemagick scale failed", Qnil, Qnil);
7573 goto imagemagick_error;
7577 /* crop behaves similar to image slicing in Emacs but is more memory
7578 efficient. */
7579 crop = image_spec_value (img->spec, QCcrop, NULL);
7581 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7583 /* After some testing, it seems MagickCropImage is the fastest crop
7584 function in ImageMagick. This crop function seems to do less copying
7585 than the alternatives, but it still reads the entire image into memory
7586 before croping, which is aparently difficult to avoid when using
7587 imagemagick. */
7588 int w, h, x, y;
7589 w = XFASTINT (XCAR (crop));
7590 crop = XCDR (crop);
7591 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7593 h = XFASTINT (XCAR (crop));
7594 crop = XCDR (crop);
7595 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7597 x = XFASTINT (XCAR (crop));
7598 crop = XCDR (crop);
7599 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7601 y = XFASTINT (XCAR (crop));
7602 MagickCropImage (image_wand, w, h, x, y);
7608 /* Furthermore :rotation. we need background color and angle for
7609 rotation. */
7611 TODO background handling for rotation specified_bg =
7612 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
7613 (specified_bg). */
7614 value = image_spec_value (img->spec, QCrotation, NULL);
7615 if (FLOATP (value))
7617 PixelWand* background = NewPixelWand ();
7618 PixelSetColor (background, "#ffffff");/*TODO remove hardcode*/
7620 rotation = extract_float (value);
7622 status = MagickRotateImage (image_wand, background, rotation);
7623 DestroyPixelWand (background);
7624 if (status == MagickFalse)
7626 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
7627 goto imagemagick_error;
7631 /* Finaly we are done manipulating the image, figure out resulting
7632 width, height, and then transfer ownerwship to Emacs. */
7633 height = MagickGetImageHeight (image_wand);
7634 width = MagickGetImageWidth (image_wand);
7636 if (! check_image_size (f, width, height))
7638 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7639 goto imagemagick_error;
7642 /* We can now get a valid pixel buffer from the imagemagick file, if all
7643 went ok. */
7645 init_color_table ();
7646 imagemagick_rendermethod = (INTEGERP (Vimagemagick_render_type)
7647 ? XFASTINT (Vimagemagick_render_type) : 0);
7648 if (imagemagick_rendermethod == 0)
7650 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7651 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7652 &ximg, &img->pixmap))
7654 #ifdef COLOR_TABLE_SUPPORT
7655 free_color_table ();
7656 #endif
7657 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7658 goto imagemagick_error;
7661 /* Copy imagegmagick image to x with primitive yet robust pixel
7662 pusher loop. This has been tested a lot with many different
7663 images. */
7665 /* Copy pixels from the imagemagick image structure to the x image map. */
7666 iterator = NewPixelIterator (image_wand);
7667 if (iterator == (PixelIterator *) NULL)
7669 #ifdef COLOR_TABLE_SUPPORT
7670 free_color_table ();
7671 #endif
7672 x_destroy_x_image (ximg);
7673 image_error ("Imagemagick pixel iterator creation failed",
7674 Qnil, Qnil);
7675 goto imagemagick_error;
7678 for (y = 0; y < (long) MagickGetImageHeight (image_wand); y++)
7680 pixels = PixelGetNextIteratorRow (iterator, &width);
7681 if (pixels == (PixelWand **) NULL)
7682 break;
7683 for (x = 0; x < (long) width; x++)
7685 PixelGetMagickColor (pixels[x], &pixel);
7686 XPutPixel (ximg, x, y,
7687 lookup_rgb_color (f,
7688 pixel.red,
7689 pixel.green,
7690 pixel.blue));
7693 DestroyPixelIterator (iterator);
7696 if (imagemagick_rendermethod == 1)
7698 /* Magicexportimage is normaly faster than pixelpushing. This
7699 method is also well tested. Some aspects of this method are
7700 ad-hoc and needs to be more researched. */
7701 int imagedepth = 24;/*MagickGetImageDepth(image_wand);*/
7702 char* exportdepth = imagedepth <= 8 ? "I" : "BGRP";/*"RGBP";*/
7703 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7704 if (!x_create_x_image_and_pixmap (f, width, height, imagedepth,
7705 &ximg, &img->pixmap))
7707 #ifdef COLOR_TABLE_SUPPORT
7708 free_color_table ();
7709 #endif
7710 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7711 goto imagemagick_error;
7715 /* Oddly, the below code doesnt seem to work:*/
7716 /* switch(ximg->bitmap_unit){ */
7717 /* case 8: */
7718 /* pixelwidth=CharPixel; */
7719 /* break; */
7720 /* case 16: */
7721 /* pixelwidth=ShortPixel; */
7722 /* break; */
7723 /* case 32: */
7724 /* pixelwidth=LongPixel; */
7725 /* break; */
7726 /* } */
7728 Here im just guessing the format of the bitmap.
7729 happens to work fine for:
7730 - bw djvu images
7731 on rgb display.
7732 seems about 3 times as fast as pixel pushing(not carefully measured)
7734 pixelwidth = CharPixel;/*??? TODO figure out*/
7735 #ifdef HAVE_MAGICKEXPORTIMAGEPIXELS
7736 MagickExportImagePixels (image_wand,
7737 0, 0,
7738 width, height,
7739 exportdepth,
7740 pixelwidth,
7741 /*&(img->pixmap));*/
7742 ximg->data);
7743 #else
7744 image_error ("You dont have MagickExportImagePixels, upgrade ImageMagick!",
7745 Qnil, Qnil);
7746 #endif
7750 #ifdef COLOR_TABLE_SUPPORT
7751 /* Remember colors allocated for this image. */
7752 img->colors = colors_in_color_table (&img->ncolors);
7753 free_color_table ();
7754 #endif /* COLOR_TABLE_SUPPORT */
7757 img->width = width;
7758 img->height = height;
7760 /* Put the image into the pixmap, then free the X image and its
7761 buffer. */
7762 x_put_x_image (f, ximg, img->pixmap, width, height);
7763 x_destroy_x_image (ximg);
7766 /* Final cleanup. image_wand should be the only resource left. */
7767 DestroyMagickWand (image_wand);
7768 /* `MagickWandTerminus' terminates the imagemagick environment. */
7769 MagickWandTerminus ();
7771 return 1;
7773 imagemagick_error:
7774 DestroyMagickWand (image_wand);
7775 MagickWandTerminus ();
7776 /* TODO more cleanup. */
7777 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
7778 return 0;
7782 /* Load IMAGEMAGICK image IMG for use on frame F. Value is non-zero if
7783 successful. this function will go into the imagemagick_type structure, and
7784 the prototype thus needs to be compatible with that structure. */
7786 static int
7787 imagemagick_load (struct frame *f,
7788 struct image *img)
7790 int success_p = 0;
7791 Lisp_Object file_name;
7793 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7794 file_name = image_spec_value (img->spec, QCfile, NULL);
7795 if (STRINGP (file_name))
7797 Lisp_Object file;
7799 file = x_find_image_file (file_name);
7800 if (!STRINGP (file))
7802 image_error ("Cannot find image file `%s'", file_name, Qnil);
7803 return 0;
7805 success_p = imagemagick_load_image (f, img, 0, 0, SDATA (file));
7807 /* Else its not a file, its a lisp object. Load the image from a
7808 lisp object rather than a file. */
7809 else
7811 Lisp_Object data;
7813 data = image_spec_value (img->spec, QCdata, NULL);
7814 if (!STRINGP (data))
7816 image_error ("Invalid image data `%s'", data, Qnil);
7817 return 0;
7819 success_p = imagemagick_load_image (f, img, SDATA (data),
7820 SBYTES (data), NULL);
7823 return success_p;
7826 /* Structure describing the image type `imagemagick'. Its the same
7827 type of structure defined for all image formats, handled by Emacs
7828 image functions. See struct image_type in dispextern.h. */
7830 static struct image_type imagemagick_type =
7832 /* An identifier showing that this is an image structure for the
7833 IMAGEMAGICK format. */
7834 &Qimagemagick,
7835 /* Handle to a function that can be used to identify a IMAGEMAGICK
7836 file. */
7837 imagemagick_image_p,
7838 /* Handle to function used to load a IMAGEMAGICK file. */
7839 imagemagick_load,
7840 /* Handle to function to free resources for IMAGEMAGICK. */
7841 imagemagick_clear_image,
7842 /* An internal field to link to the next image type in a list of
7843 image types, will be filled in when registering the format. */
7844 NULL
7848 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
7849 doc: /* Return the image types supported by ImageMagick.
7850 Note that ImageMagick recognizes many file-types that Emacs does not recognize
7851 as images, such as .c. */)
7852 (void)
7854 Lisp_Object typelist = Qnil;
7855 unsigned long numf;
7856 ExceptionInfo ex;
7857 char **imtypes = GetMagickList ("*", &numf, &ex);
7858 int i;
7859 Lisp_Object Qimagemagicktype;
7860 for (i = 0; i < numf; i++)
7862 Qimagemagicktype = intern (imtypes[i]);
7863 typelist = Fcons (Qimagemagicktype, typelist);
7865 return typelist;
7868 #endif /* defined (HAVE_IMAGEMAGICK) */
7872 /***********************************************************************
7874 ***********************************************************************/
7876 #if defined (HAVE_RSVG)
7878 /* Function prototypes. */
7880 static int svg_image_p (Lisp_Object object);
7881 static int svg_load (struct frame *f, struct image *img);
7883 static int svg_load_image (struct frame *, struct image *,
7884 unsigned char *, unsigned int);
7886 /* The symbol `svg' identifying images of this type. */
7888 Lisp_Object Qsvg;
7890 /* Indices of image specification fields in svg_format, below. */
7892 enum svg_keyword_index
7894 SVG_TYPE,
7895 SVG_DATA,
7896 SVG_FILE,
7897 SVG_ASCENT,
7898 SVG_MARGIN,
7899 SVG_RELIEF,
7900 SVG_ALGORITHM,
7901 SVG_HEURISTIC_MASK,
7902 SVG_MASK,
7903 SVG_BACKGROUND,
7904 SVG_LAST
7907 /* Vector of image_keyword structures describing the format
7908 of valid user-defined image specifications. */
7910 static const struct image_keyword svg_format[SVG_LAST] =
7912 {":type", IMAGE_SYMBOL_VALUE, 1},
7913 {":data", IMAGE_STRING_VALUE, 0},
7914 {":file", IMAGE_STRING_VALUE, 0},
7915 {":ascent", IMAGE_ASCENT_VALUE, 0},
7916 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7917 {":relief", IMAGE_INTEGER_VALUE, 0},
7918 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7919 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7920 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7921 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7924 /* Structure describing the image type `svg'. Its the same type of
7925 structure defined for all image formats, handled by emacs image
7926 functions. See struct image_type in dispextern.h. */
7928 static struct image_type svg_type =
7930 /* An identifier showing that this is an image structure for the SVG format. */
7931 &Qsvg,
7932 /* Handle to a function that can be used to identify a SVG file. */
7933 svg_image_p,
7934 /* Handle to function used to load a SVG file. */
7935 svg_load,
7936 /* Handle to function to free sresources for SVG. */
7937 x_clear_image,
7938 /* An internal field to link to the next image type in a list of
7939 image types, will be filled in when registering the format. */
7940 NULL
7944 /* Return non-zero if OBJECT is a valid SVG image specification. Do
7945 this by calling parse_image_spec and supplying the keywords that
7946 identify the SVG format. */
7948 static int
7949 svg_image_p (Lisp_Object object)
7951 struct image_keyword fmt[SVG_LAST];
7952 memcpy (fmt, svg_format, sizeof fmt);
7954 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
7955 return 0;
7957 /* Must specify either the :data or :file keyword. */
7958 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
7961 #include <librsvg/rsvg.h>
7963 #ifdef HAVE_NTGUI
7965 /* SVG library functions. */
7966 DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new);
7967 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions);
7968 DEF_IMGLIB_FN (gboolean, rsvg_handle_write);
7969 DEF_IMGLIB_FN (gboolean, rsvg_handle_close);
7970 DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf);
7971 DEF_IMGLIB_FN (void, rsvg_handle_free);
7973 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width);
7974 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height);
7975 DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels);
7976 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride);
7977 DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace);
7978 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels);
7979 DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha);
7980 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample);
7982 DEF_IMGLIB_FN (void, g_type_init);
7983 DEF_IMGLIB_FN (void, g_object_unref);
7984 DEF_IMGLIB_FN (void, g_error_free);
7986 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
7988 static int
7989 init_svg_functions (Lisp_Object libraries)
7991 HMODULE library, gdklib, glib, gobject;
7993 if (!(glib = w32_delayed_load (libraries, Qglib))
7994 || !(gobject = w32_delayed_load (libraries, Qgobject))
7995 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
7996 || !(library = w32_delayed_load (libraries, Qsvg)))
7997 return 0;
7999 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8000 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8001 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8002 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8003 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8004 LOAD_IMGLIB_FN (library, rsvg_handle_free);
8006 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8007 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8008 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8009 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8010 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8011 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8012 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8013 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8015 LOAD_IMGLIB_FN (gobject, g_type_init);
8016 LOAD_IMGLIB_FN (gobject, g_object_unref);
8017 LOAD_IMGLIB_FN (glib, g_error_free);
8019 return 1;
8022 #else
8023 /* The following aliases for library functions allow dynamic loading
8024 to be used on some platforms. */
8025 #define fn_rsvg_handle_new rsvg_handle_new
8026 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8027 #define fn_rsvg_handle_write rsvg_handle_write
8028 #define fn_rsvg_handle_close rsvg_handle_close
8029 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8030 #define fn_rsvg_handle_free rsvg_handle_free
8032 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8033 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8034 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8035 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8036 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8037 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8038 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8039 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8041 #define fn_g_type_init g_type_init
8042 #define fn_g_object_unref g_object_unref
8043 #define fn_g_error_free g_error_free
8044 #endif /* !HAVE_NTGUI */
8046 /* Load SVG image IMG for use on frame F. Value is non-zero if
8047 successful. this function will go into the svg_type structure, and
8048 the prototype thus needs to be compatible with that structure. */
8050 static int
8051 svg_load (struct frame *f, struct image *img)
8053 int success_p = 0;
8054 Lisp_Object file_name;
8056 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8057 file_name = image_spec_value (img->spec, QCfile, NULL);
8058 if (STRINGP (file_name))
8060 Lisp_Object file;
8061 unsigned char *contents;
8062 int size;
8064 file = x_find_image_file (file_name);
8065 if (!STRINGP (file))
8067 image_error ("Cannot find image file `%s'", file_name, Qnil);
8068 return 0;
8071 /* Read the entire file into memory. */
8072 contents = slurp_file (SDATA (file), &size);
8073 if (contents == NULL)
8075 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8076 return 0;
8078 /* If the file was slurped into memory properly, parse it. */
8079 success_p = svg_load_image (f, img, contents, size);
8080 xfree (contents);
8082 /* Else its not a file, its a lisp object. Load the image from a
8083 lisp object rather than a file. */
8084 else
8086 Lisp_Object data;
8088 data = image_spec_value (img->spec, QCdata, NULL);
8089 if (!STRINGP (data))
8091 image_error ("Invalid image data `%s'", data, Qnil);
8092 return 0;
8094 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8097 return success_p;
8100 /* svg_load_image is a helper function for svg_load, which does the
8101 actual loading given contents and size, apart from frame and image
8102 structures, passed from svg_load.
8104 Uses librsvg to do most of the image processing.
8106 Returns non-zero when successful. */
8107 static int
8108 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8109 struct image *img, /* Pointer to emacs image structure. */
8110 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8111 unsigned int size) /* Size of data in bytes. */
8113 RsvgHandle *rsvg_handle;
8114 RsvgDimensionData dimension_data;
8115 GError *error = NULL;
8116 GdkPixbuf *pixbuf;
8117 int width;
8118 int height;
8119 const guint8 *pixels;
8120 int rowstride;
8121 XImagePtr ximg;
8122 Lisp_Object specified_bg;
8123 XColor background;
8124 int x;
8125 int y;
8127 /* g_type_init is a glib function that must be called prior to using
8128 gnome type library functions. */
8129 fn_g_type_init ();
8130 /* Make a handle to a new rsvg object. */
8131 rsvg_handle = fn_rsvg_handle_new ();
8133 /* Parse the contents argument and fill in the rsvg_handle. */
8134 fn_rsvg_handle_write (rsvg_handle, contents, size, &error);
8135 if (error) goto rsvg_error;
8137 /* The parsing is complete, rsvg_handle is ready to used, close it
8138 for further writes. */
8139 fn_rsvg_handle_close (rsvg_handle, &error);
8140 if (error) goto rsvg_error;
8142 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8143 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8145 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8146 goto rsvg_error;
8149 /* We can now get a valid pixel buffer from the svg file, if all
8150 went ok. */
8151 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8152 if (!pixbuf) goto rsvg_error;
8153 fn_g_object_unref (rsvg_handle);
8155 /* Extract some meta data from the svg handle. */
8156 width = fn_gdk_pixbuf_get_width (pixbuf);
8157 height = fn_gdk_pixbuf_get_height (pixbuf);
8158 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8159 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8161 /* Validate the svg meta data. */
8162 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8163 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8164 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8165 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8167 /* Try to create a x pixmap to hold the svg pixmap. */
8168 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8170 fn_g_object_unref (pixbuf);
8171 return 0;
8174 init_color_table ();
8176 /* Handle alpha channel by combining the image with a background
8177 color. */
8178 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8179 if (!STRINGP (specified_bg)
8180 || !x_defined_color (f, SDATA (specified_bg), &background, 0))
8182 #ifndef HAVE_NS
8183 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8184 x_query_color (f, &background);
8185 #else
8186 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8187 #endif
8190 /* SVG pixmaps specify transparency in the last byte, so right
8191 shift 8 bits to get rid of it, since emacs doesn't support
8192 transparency. */
8193 background.red >>= 8;
8194 background.green >>= 8;
8195 background.blue >>= 8;
8197 /* This loop handles opacity values, since Emacs assumes
8198 non-transparent images. Each pixel must be "flattened" by
8199 calculating the resulting color, given the transparency of the
8200 pixel, and the image background color. */
8201 for (y = 0; y < height; ++y)
8203 for (x = 0; x < width; ++x)
8205 unsigned red;
8206 unsigned green;
8207 unsigned blue;
8208 unsigned opacity;
8210 red = *pixels++;
8211 green = *pixels++;
8212 blue = *pixels++;
8213 opacity = *pixels++;
8215 red = ((red * opacity)
8216 + (background.red * ((1 << 8) - opacity)));
8217 green = ((green * opacity)
8218 + (background.green * ((1 << 8) - opacity)));
8219 blue = ((blue * opacity)
8220 + (background.blue * ((1 << 8) - opacity)));
8222 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8225 pixels += rowstride - 4 * width;
8228 #ifdef COLOR_TABLE_SUPPORT
8229 /* Remember colors allocated for this image. */
8230 img->colors = colors_in_color_table (&img->ncolors);
8231 free_color_table ();
8232 #endif /* COLOR_TABLE_SUPPORT */
8234 fn_g_object_unref (pixbuf);
8236 img->width = width;
8237 img->height = height;
8239 /* Maybe fill in the background field while we have ximg handy.
8240 Casting avoids a GCC warning. */
8241 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8243 /* Put the image into the pixmap, then free the X image and its
8244 buffer. */
8245 x_put_x_image (f, ximg, img->pixmap, width, height);
8246 x_destroy_x_image (ximg);
8248 return 1;
8250 rsvg_error:
8251 fn_g_object_unref (rsvg_handle);
8252 /* FIXME: Use error->message so the user knows what is the actual
8253 problem with the image. */
8254 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8255 fn_g_error_free (error);
8256 return 0;
8259 #endif /* defined (HAVE_RSVG) */
8264 /***********************************************************************
8265 Ghostscript
8266 ***********************************************************************/
8268 #ifdef HAVE_X_WINDOWS
8269 #define HAVE_GHOSTSCRIPT 1
8270 #endif /* HAVE_X_WINDOWS */
8272 #ifdef HAVE_GHOSTSCRIPT
8274 static int gs_image_p (Lisp_Object object);
8275 static int gs_load (struct frame *f, struct image *img);
8276 static void gs_clear_image (struct frame *f, struct image *img);
8278 /* Keyword symbols. */
8280 static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8282 /* Indices of image specification fields in gs_format, below. */
8284 enum gs_keyword_index
8286 GS_TYPE,
8287 GS_PT_WIDTH,
8288 GS_PT_HEIGHT,
8289 GS_FILE,
8290 GS_LOADER,
8291 GS_BOUNDING_BOX,
8292 GS_ASCENT,
8293 GS_MARGIN,
8294 GS_RELIEF,
8295 GS_ALGORITHM,
8296 GS_HEURISTIC_MASK,
8297 GS_MASK,
8298 GS_BACKGROUND,
8299 GS_LAST
8302 /* Vector of image_keyword structures describing the format
8303 of valid user-defined image specifications. */
8305 static const struct image_keyword gs_format[GS_LAST] =
8307 {":type", IMAGE_SYMBOL_VALUE, 1},
8308 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8309 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8310 {":file", IMAGE_STRING_VALUE, 1},
8311 {":loader", IMAGE_FUNCTION_VALUE, 0},
8312 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8313 {":ascent", IMAGE_ASCENT_VALUE, 0},
8314 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8315 {":relief", IMAGE_INTEGER_VALUE, 0},
8316 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8317 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8318 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8319 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8322 /* Structure describing the image type `ghostscript'. */
8324 static struct image_type gs_type =
8326 &Qpostscript,
8327 gs_image_p,
8328 gs_load,
8329 gs_clear_image,
8330 NULL
8334 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8336 static void
8337 gs_clear_image (struct frame *f, struct image *img)
8339 /* IMG->data.ptr_val may contain a recorded colormap. */
8340 xfree (img->data.ptr_val);
8341 x_clear_image (f, img);
8345 /* Return non-zero if OBJECT is a valid Ghostscript image
8346 specification. */
8348 static int
8349 gs_image_p (Lisp_Object object)
8351 struct image_keyword fmt[GS_LAST];
8352 Lisp_Object tem;
8353 int i;
8355 memcpy (fmt, gs_format, sizeof fmt);
8357 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8358 return 0;
8360 /* Bounding box must be a list or vector containing 4 integers. */
8361 tem = fmt[GS_BOUNDING_BOX].value;
8362 if (CONSP (tem))
8364 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8365 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8366 return 0;
8367 if (!NILP (tem))
8368 return 0;
8370 else if (VECTORP (tem))
8372 if (ASIZE (tem) != 4)
8373 return 0;
8374 for (i = 0; i < 4; ++i)
8375 if (!INTEGERP (XVECTOR (tem)->contents[i]))
8376 return 0;
8378 else
8379 return 0;
8381 return 1;
8385 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8386 if successful. */
8388 static int
8389 gs_load (struct frame *f, struct image *img)
8391 char buffer[100];
8392 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8393 Lisp_Object frame;
8394 double in_width, in_height;
8395 Lisp_Object pixel_colors = Qnil;
8397 /* Compute pixel size of pixmap needed from the given size in the
8398 image specification. Sizes in the specification are in pt. 1 pt
8399 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8400 info. */
8401 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8402 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
8403 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
8404 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8405 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
8406 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
8408 if (!check_image_size (f, img->width, img->height))
8410 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8411 return 0;
8414 /* Create the pixmap. */
8415 xassert (img->pixmap == NO_PIXMAP);
8417 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8418 BLOCK_INPUT;
8419 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8420 img->width, img->height,
8421 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8422 UNBLOCK_INPUT;
8424 if (!img->pixmap)
8426 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8427 return 0;
8430 /* Call the loader to fill the pixmap. It returns a process object
8431 if successful. We do not record_unwind_protect here because
8432 other places in redisplay like calling window scroll functions
8433 don't either. Let the Lisp loader use `unwind-protect' instead. */
8434 sprintf (buffer, "%lu %lu",
8435 (unsigned long) FRAME_X_WINDOW (f),
8436 (unsigned long) img->pixmap);
8437 window_and_pixmap_id = build_string (buffer);
8439 sprintf (buffer, "%lu %lu",
8440 FRAME_FOREGROUND_PIXEL (f),
8441 FRAME_BACKGROUND_PIXEL (f));
8442 pixel_colors = build_string (buffer);
8444 XSETFRAME (frame, f);
8445 loader = image_spec_value (img->spec, QCloader, NULL);
8446 if (NILP (loader))
8447 loader = intern ("gs-load-image");
8449 img->data.lisp_val = call6 (loader, frame, img->spec,
8450 make_number (img->width),
8451 make_number (img->height),
8452 window_and_pixmap_id,
8453 pixel_colors);
8454 return PROCESSP (img->data.lisp_val);
8458 /* Kill the Ghostscript process that was started to fill PIXMAP on
8459 frame F. Called from XTread_socket when receiving an event
8460 telling Emacs that Ghostscript has finished drawing. */
8462 void
8463 x_kill_gs_process (Pixmap pixmap, struct frame *f)
8465 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8466 int class, i;
8467 struct image *img;
8469 /* Find the image containing PIXMAP. */
8470 for (i = 0; i < c->used; ++i)
8471 if (c->images[i]->pixmap == pixmap)
8472 break;
8474 /* Should someone in between have cleared the image cache, for
8475 instance, give up. */
8476 if (i == c->used)
8477 return;
8479 /* Kill the GS process. We should have found PIXMAP in the image
8480 cache and its image should contain a process object. */
8481 img = c->images[i];
8482 xassert (PROCESSP (img->data.lisp_val));
8483 Fkill_process (img->data.lisp_val, Qnil);
8484 img->data.lisp_val = Qnil;
8486 #if defined (HAVE_X_WINDOWS)
8488 /* On displays with a mutable colormap, figure out the colors
8489 allocated for the image by looking at the pixels of an XImage for
8490 img->pixmap. */
8491 class = FRAME_X_VISUAL (f)->class;
8492 if (class != StaticColor && class != StaticGray && class != TrueColor)
8494 XImagePtr ximg;
8496 BLOCK_INPUT;
8498 /* Try to get an XImage for img->pixmep. */
8499 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8500 0, 0, img->width, img->height, ~0, ZPixmap);
8501 if (ximg)
8503 int x, y;
8505 /* Initialize the color table. */
8506 init_color_table ();
8508 /* For each pixel of the image, look its color up in the
8509 color table. After having done so, the color table will
8510 contain an entry for each color used by the image. */
8511 for (y = 0; y < img->height; ++y)
8512 for (x = 0; x < img->width; ++x)
8514 unsigned long pixel = XGetPixel (ximg, x, y);
8515 lookup_pixel_color (f, pixel);
8518 /* Record colors in the image. Free color table and XImage. */
8519 #ifdef COLOR_TABLE_SUPPORT
8520 img->colors = colors_in_color_table (&img->ncolors);
8521 free_color_table ();
8522 #endif
8523 XDestroyImage (ximg);
8525 #if 0 /* This doesn't seem to be the case. If we free the colors
8526 here, we get a BadAccess later in x_clear_image when
8527 freeing the colors. */
8528 /* We have allocated colors once, but Ghostscript has also
8529 allocated colors on behalf of us. So, to get the
8530 reference counts right, free them once. */
8531 if (img->ncolors)
8532 x_free_colors (f, img->colors, img->ncolors);
8533 #endif
8535 else
8536 image_error ("Cannot get X image of `%s'; colors will not be freed",
8537 img->spec, Qnil);
8539 UNBLOCK_INPUT;
8541 #endif /* HAVE_X_WINDOWS */
8543 /* Now that we have the pixmap, compute mask and transform the
8544 image if requested. */
8545 BLOCK_INPUT;
8546 postprocess_image (f, img);
8547 UNBLOCK_INPUT;
8550 #endif /* HAVE_GHOSTSCRIPT */
8553 /***********************************************************************
8554 Tests
8555 ***********************************************************************/
8557 #if GLYPH_DEBUG
8559 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8560 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8561 (Lisp_Object spec)
8563 return valid_image_p (spec) ? Qt : Qnil;
8567 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8568 (Lisp_Object spec)
8570 int id = -1;
8572 if (valid_image_p (spec))
8573 id = lookup_image (SELECTED_FRAME (), spec);
8575 debug_print (spec);
8576 return make_number (id);
8579 #endif /* GLYPH_DEBUG != 0 */
8582 /***********************************************************************
8583 Initialization
8584 ***********************************************************************/
8586 #ifdef HAVE_NTGUI
8587 /* Image types that rely on external libraries are loaded dynamically
8588 if the library is available. */
8589 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8590 define_image_type (image_type, init_lib_fn (libraries))
8591 #else
8592 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8593 define_image_type (image_type, 1)
8594 #endif /* HAVE_NTGUI */
8596 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8597 doc: /* Initialize image library implementing image type TYPE.
8598 Return non-nil if TYPE is a supported image type.
8600 Image types pbm and xbm are prebuilt; other types are loaded here.
8601 Libraries to load are specified in alist LIBRARIES (usually, the value
8602 of `dynamic-library-alist', which see). */)
8603 (Lisp_Object type, Lisp_Object libraries)
8605 #ifdef HAVE_NTGUI
8606 /* Don't try to reload the library. */
8607 Lisp_Object tested = Fassq (type, Vlibrary_cache);
8608 if (CONSP (tested))
8609 return XCDR (tested);
8610 #endif
8612 /* Types pbm and xbm are built-in and always available. */
8613 if (EQ (type, Qpbm) || EQ (type, Qxbm))
8614 return Qt;
8616 #if defined (HAVE_XPM) || defined (HAVE_NS)
8617 if (EQ (type, Qxpm))
8618 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8619 #endif
8621 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8622 if (EQ (type, Qjpeg))
8623 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8624 #endif
8626 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8627 if (EQ (type, Qtiff))
8628 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8629 #endif
8631 #if defined (HAVE_GIF) || defined (HAVE_NS)
8632 if (EQ (type, Qgif))
8633 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8634 #endif
8636 #if defined (HAVE_PNG) || defined (HAVE_NS)
8637 if (EQ (type, Qpng))
8638 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8639 #endif
8641 #if defined (HAVE_RSVG)
8642 if (EQ (type, Qsvg))
8643 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
8644 #endif
8646 #if defined (HAVE_IMAGEMAGICK)
8647 if (EQ (type, Qimagemagick))
8648 return CHECK_LIB_AVAILABLE (&imagemagick_type, init_imagemagick_functions,
8649 libraries);
8650 #endif
8652 #ifdef HAVE_GHOSTSCRIPT
8653 if (EQ (type, Qpostscript))
8654 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8655 #endif
8657 /* If the type is not recognized, avoid testing it ever again. */
8658 CACHE_IMAGE_TYPE (type, Qnil);
8659 return Qnil;
8662 void
8663 syms_of_image (void)
8665 /* Initialize this only once, since that's what we do with Vimage_types
8666 and they are supposed to be in sync. Initializing here gives correct
8667 operation on GNU/Linux of calling dump-emacs after loading some images. */
8668 image_types = NULL;
8670 /* Must be defined now becase we're going to update it below, while
8671 defining the supported image types. */
8672 DEFVAR_LISP ("image-types", Vimage_types,
8673 doc: /* List of potentially supported image types.
8674 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8675 To check whether it is really supported, use `image-type-available-p'. */);
8676 Vimage_types = Qnil;
8678 DEFVAR_LISP ("max-image-size", Vmax_image_size,
8679 doc: /* Maximum size of images.
8680 Emacs will not load an image into memory if its pixel width or
8681 pixel height exceeds this limit.
8683 If the value is an integer, it directly specifies the maximum
8684 image height and width, measured in pixels. If it is a floating
8685 point number, it specifies the maximum image height and width
8686 as a ratio to the frame height and width. If the value is
8687 non-numeric, there is no explicit limit on the size of images. */);
8688 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8690 Qpbm = intern_c_string ("pbm");
8691 staticpro (&Qpbm);
8692 ADD_IMAGE_TYPE (Qpbm);
8694 Qxbm = intern_c_string ("xbm");
8695 staticpro (&Qxbm);
8696 ADD_IMAGE_TYPE (Qxbm);
8698 define_image_type (&xbm_type, 1);
8699 define_image_type (&pbm_type, 1);
8701 Qcount = intern_c_string ("count");
8702 staticpro (&Qcount);
8703 Qextension_data = intern_c_string ("extension-data");
8704 staticpro (&Qextension_data);
8706 QCascent = intern_c_string (":ascent");
8707 staticpro (&QCascent);
8708 QCmargin = intern_c_string (":margin");
8709 staticpro (&QCmargin);
8710 QCrelief = intern_c_string (":relief");
8711 staticpro (&QCrelief);
8712 QCconversion = intern_c_string (":conversion");
8713 staticpro (&QCconversion);
8714 QCcolor_symbols = intern_c_string (":color-symbols");
8715 staticpro (&QCcolor_symbols);
8716 QCheuristic_mask = intern_c_string (":heuristic-mask");
8717 staticpro (&QCheuristic_mask);
8718 QCindex = intern_c_string (":index");
8719 staticpro (&QCindex);
8720 QCgeometry = intern_c_string (":geometry");
8721 staticpro (&QCgeometry);
8722 QCcrop = intern_c_string (":crop");
8723 staticpro (&QCcrop);
8724 QCrotation = intern_c_string (":rotation");
8725 staticpro (&QCrotation);
8726 QCmatrix = intern_c_string (":matrix");
8727 staticpro (&QCmatrix);
8728 QCcolor_adjustment = intern_c_string (":color-adjustment");
8729 staticpro (&QCcolor_adjustment);
8730 QCmask = intern_c_string (":mask");
8731 staticpro (&QCmask);
8733 Qlaplace = intern_c_string ("laplace");
8734 staticpro (&Qlaplace);
8735 Qemboss = intern_c_string ("emboss");
8736 staticpro (&Qemboss);
8737 Qedge_detection = intern_c_string ("edge-detection");
8738 staticpro (&Qedge_detection);
8739 Qheuristic = intern_c_string ("heuristic");
8740 staticpro (&Qheuristic);
8742 Qpostscript = intern_c_string ("postscript");
8743 staticpro (&Qpostscript);
8744 #ifdef HAVE_GHOSTSCRIPT
8745 ADD_IMAGE_TYPE (Qpostscript);
8746 QCloader = intern_c_string (":loader");
8747 staticpro (&QCloader);
8748 QCbounding_box = intern_c_string (":bounding-box");
8749 staticpro (&QCbounding_box);
8750 QCpt_width = intern_c_string (":pt-width");
8751 staticpro (&QCpt_width);
8752 QCpt_height = intern_c_string (":pt-height");
8753 staticpro (&QCpt_height);
8754 #endif /* HAVE_GHOSTSCRIPT */
8756 #ifdef HAVE_NTGUI
8757 Qlibpng_version = intern_c_string ("libpng-version");
8758 staticpro (&Qlibpng_version);
8759 Fset (Qlibpng_version,
8760 #if HAVE_PNG
8761 make_number (PNG_LIBPNG_VER)
8762 #else
8763 make_number (-1)
8764 #endif
8766 #endif
8768 #if defined (HAVE_XPM) || defined (HAVE_NS)
8769 Qxpm = intern_c_string ("xpm");
8770 staticpro (&Qxpm);
8771 ADD_IMAGE_TYPE (Qxpm);
8772 #endif
8774 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8775 Qjpeg = intern_c_string ("jpeg");
8776 staticpro (&Qjpeg);
8777 ADD_IMAGE_TYPE (Qjpeg);
8778 #endif
8780 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8781 Qtiff = intern_c_string ("tiff");
8782 staticpro (&Qtiff);
8783 ADD_IMAGE_TYPE (Qtiff);
8784 #endif
8786 #if defined (HAVE_GIF) || defined (HAVE_NS)
8787 Qgif = intern_c_string ("gif");
8788 staticpro (&Qgif);
8789 ADD_IMAGE_TYPE (Qgif);
8790 #endif
8792 #if defined (HAVE_PNG) || defined (HAVE_NS)
8793 Qpng = intern_c_string ("png");
8794 staticpro (&Qpng);
8795 ADD_IMAGE_TYPE (Qpng);
8796 #endif
8798 #if defined (HAVE_IMAGEMAGICK)
8799 Qimagemagick = intern_c_string ("imagemagick");
8800 staticpro (&Qimagemagick);
8801 ADD_IMAGE_TYPE (Qimagemagick);
8802 #endif
8804 #if defined (HAVE_RSVG)
8805 Qsvg = intern_c_string ("svg");
8806 staticpro (&Qsvg);
8807 ADD_IMAGE_TYPE (Qsvg);
8808 #ifdef HAVE_NTGUI
8809 /* Other libraries used directly by svg code. */
8810 Qgdk_pixbuf = intern_c_string ("gdk-pixbuf");
8811 staticpro (&Qgdk_pixbuf);
8812 Qglib = intern_c_string ("glib");
8813 staticpro (&Qglib);
8814 Qgobject = intern_c_string ("gobject");
8815 staticpro (&Qgobject);
8816 #endif /* HAVE_NTGUI */
8817 #endif /* HAVE_RSVG */
8819 defsubr (&Sinit_image_library);
8820 #ifdef HAVE_IMAGEMAGICK
8821 defsubr (&Simagemagick_types);
8822 #endif
8823 defsubr (&Sclear_image_cache);
8824 defsubr (&Simage_flush);
8825 defsubr (&Simage_size);
8826 defsubr (&Simage_mask_p);
8827 defsubr (&Simage_metadata);
8829 #if GLYPH_DEBUG
8830 defsubr (&Simagep);
8831 defsubr (&Slookup_image);
8832 #endif
8834 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
8835 doc: /* Non-nil means always draw a cross over disabled images.
8836 Disabled images are those having a `:conversion disabled' property.
8837 A cross is always drawn on black & white displays. */);
8838 cross_disabled_images = 0;
8840 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
8841 doc: /* List of directories to search for window system bitmap files. */);
8842 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8844 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
8845 doc: /* Maximum time after which images are removed from the cache.
8846 When an image has not been displayed this many seconds, Emacs
8847 automatically removes it from the image cache. If the cache contains
8848 a large number of images, the actual eviction time may be shorter.
8849 The value can also be nil, meaning the cache is never cleared.
8851 The function `clear-image-cache' disregards this variable. */);
8852 Vimage_cache_eviction_delay = make_number (300);
8853 #ifdef HAVE_IMAGEMAGICK
8854 DEFVAR_LISP ("imagemagick-render-type", Vimagemagick_render_type,
8855 doc: /* Choose between ImageMagick render methods. */);
8856 #endif
8860 void
8861 init_image (void)