Implement dynamic loading of GnuTLS on Windows.
[emacs.git] / src / image.c
blob2377b41735db6da3079cd01fa9a54dd97f1b5abf
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);
588 #define CACHE_IMAGE_TYPE(type, status) \
589 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
591 #define ADD_IMAGE_TYPE(type) \
592 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
594 /* Define a new image type from TYPE. This adds a copy of TYPE to
595 image_types and caches the loading status of TYPE. */
597 static Lisp_Object
598 define_image_type (struct image_type *type, int loaded)
600 Lisp_Object success;
602 if (!loaded)
603 success = Qnil;
604 else
606 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
607 The initialized data segment is read-only. */
608 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
609 memcpy (p, type, sizeof *p);
610 p->next = image_types;
611 image_types = p;
612 success = Qt;
615 CACHE_IMAGE_TYPE (*type->type, success);
616 return success;
620 /* Look up image type SYMBOL, and return a pointer to its image_type
621 structure. Value is null if SYMBOL is not a known image type. */
623 static INLINE struct image_type *
624 lookup_image_type (Lisp_Object symbol)
626 struct image_type *type;
628 /* We must initialize the image-type if it hasn't been already. */
629 if (NILP (Finit_image_library (symbol, Vdynamic_library_alist)))
630 return 0; /* unimplemented */
632 for (type = image_types; type; type = type->next)
633 if (EQ (symbol, *type->type))
634 break;
636 return type;
640 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
641 valid image specification is a list whose car is the symbol
642 `image', and whose rest is a property list. The property list must
643 contain a value for key `:type'. That value must be the name of a
644 supported image type. The rest of the property list depends on the
645 image type. */
648 valid_image_p (Lisp_Object object)
650 int valid_p = 0;
652 if (IMAGEP (object))
654 Lisp_Object tem;
656 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
657 if (EQ (XCAR (tem), QCtype))
659 tem = XCDR (tem);
660 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
662 struct image_type *type;
663 type = lookup_image_type (XCAR (tem));
664 if (type)
665 valid_p = type->valid_p (object);
668 break;
672 return valid_p;
676 /* Log error message with format string FORMAT and argument ARG.
677 Signaling an error, e.g. when an image cannot be loaded, is not a
678 good idea because this would interrupt redisplay, and the error
679 message display would lead to another redisplay. This function
680 therefore simply displays a message. */
682 static void
683 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
685 add_to_log (format, arg1, arg2);
690 /***********************************************************************
691 Image specifications
692 ***********************************************************************/
694 enum image_value_type
696 IMAGE_DONT_CHECK_VALUE_TYPE,
697 IMAGE_STRING_VALUE,
698 IMAGE_STRING_OR_NIL_VALUE,
699 IMAGE_SYMBOL_VALUE,
700 IMAGE_POSITIVE_INTEGER_VALUE,
701 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
702 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
703 IMAGE_ASCENT_VALUE,
704 IMAGE_INTEGER_VALUE,
705 IMAGE_FUNCTION_VALUE,
706 IMAGE_NUMBER_VALUE,
707 IMAGE_BOOL_VALUE
710 /* Structure used when parsing image specifications. */
712 struct image_keyword
714 /* Name of keyword. */
715 const char *name;
717 /* The type of value allowed. */
718 enum image_value_type type;
720 /* Non-zero means key must be present. */
721 int mandatory_p;
723 /* Used to recognize duplicate keywords in a property list. */
724 int count;
726 /* The value that was found. */
727 Lisp_Object value;
731 static int parse_image_spec (Lisp_Object, struct image_keyword *,
732 int, Lisp_Object);
733 static Lisp_Object image_spec_value (Lisp_Object, Lisp_Object, int *);
736 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
737 has the format (image KEYWORD VALUE ...). One of the keyword/
738 value pairs must be `:type TYPE'. KEYWORDS is a vector of
739 image_keywords structures of size NKEYWORDS describing other
740 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
742 static int
743 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
744 int nkeywords, Lisp_Object type)
746 int i;
747 Lisp_Object plist;
749 if (!IMAGEP (spec))
750 return 0;
752 plist = XCDR (spec);
753 while (CONSP (plist))
755 Lisp_Object key, value;
757 /* First element of a pair must be a symbol. */
758 key = XCAR (plist);
759 plist = XCDR (plist);
760 if (!SYMBOLP (key))
761 return 0;
763 /* There must follow a value. */
764 if (!CONSP (plist))
765 return 0;
766 value = XCAR (plist);
767 plist = XCDR (plist);
769 /* Find key in KEYWORDS. Error if not found. */
770 for (i = 0; i < nkeywords; ++i)
771 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
772 break;
774 if (i == nkeywords)
775 continue;
777 /* Record that we recognized the keyword. If a keywords
778 was found more than once, it's an error. */
779 keywords[i].value = value;
780 ++keywords[i].count;
782 if (keywords[i].count > 1)
783 return 0;
785 /* Check type of value against allowed type. */
786 switch (keywords[i].type)
788 case IMAGE_STRING_VALUE:
789 if (!STRINGP (value))
790 return 0;
791 break;
793 case IMAGE_STRING_OR_NIL_VALUE:
794 if (!STRINGP (value) && !NILP (value))
795 return 0;
796 break;
798 case IMAGE_SYMBOL_VALUE:
799 if (!SYMBOLP (value))
800 return 0;
801 break;
803 case IMAGE_POSITIVE_INTEGER_VALUE:
804 if (!INTEGERP (value) || XINT (value) <= 0)
805 return 0;
806 break;
808 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
809 if (INTEGERP (value) && XINT (value) >= 0)
810 break;
811 if (CONSP (value)
812 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
813 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
814 break;
815 return 0;
817 case IMAGE_ASCENT_VALUE:
818 if (SYMBOLP (value) && EQ (value, Qcenter))
819 break;
820 else if (INTEGERP (value)
821 && XINT (value) >= 0
822 && XINT (value) <= 100)
823 break;
824 return 0;
826 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
827 if (!INTEGERP (value) || XINT (value) < 0)
828 return 0;
829 break;
831 case IMAGE_DONT_CHECK_VALUE_TYPE:
832 break;
834 case IMAGE_FUNCTION_VALUE:
835 value = indirect_function (value);
836 if (!NILP (Ffunctionp (value)))
837 break;
838 return 0;
840 case IMAGE_NUMBER_VALUE:
841 if (!INTEGERP (value) && !FLOATP (value))
842 return 0;
843 break;
845 case IMAGE_INTEGER_VALUE:
846 if (!INTEGERP (value))
847 return 0;
848 break;
850 case IMAGE_BOOL_VALUE:
851 if (!NILP (value) && !EQ (value, Qt))
852 return 0;
853 break;
855 default:
856 abort ();
857 break;
860 if (EQ (key, QCtype) && !EQ (type, value))
861 return 0;
864 /* Check that all mandatory fields are present. */
865 for (i = 0; i < nkeywords; ++i)
866 if (keywords[i].mandatory_p && keywords[i].count == 0)
867 return 0;
869 return NILP (plist);
873 /* Return the value of KEY in image specification SPEC. Value is nil
874 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
875 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
877 static Lisp_Object
878 image_spec_value (Lisp_Object spec, Lisp_Object key, int *found)
880 Lisp_Object tail;
882 xassert (valid_image_p (spec));
884 for (tail = XCDR (spec);
885 CONSP (tail) && CONSP (XCDR (tail));
886 tail = XCDR (XCDR (tail)))
888 if (EQ (XCAR (tail), key))
890 if (found)
891 *found = 1;
892 return XCAR (XCDR (tail));
896 if (found)
897 *found = 0;
898 return Qnil;
902 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
903 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
904 PIXELS non-nil means return the size in pixels, otherwise return the
905 size in canonical character units.
906 FRAME is the frame on which the image will be displayed. FRAME nil
907 or omitted means use the selected frame. */)
908 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
910 Lisp_Object size;
912 size = Qnil;
913 if (valid_image_p (spec))
915 struct frame *f = check_x_frame (frame);
916 int id = lookup_image (f, spec);
917 struct image *img = IMAGE_FROM_ID (f, id);
918 int width = img->width + 2 * img->hmargin;
919 int height = img->height + 2 * img->vmargin;
921 if (NILP (pixels))
922 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
923 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
924 else
925 size = Fcons (make_number (width), make_number (height));
927 else
928 error ("Invalid image specification");
930 return size;
934 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
935 doc: /* Return t if image SPEC has a mask bitmap.
936 FRAME is the frame on which the image will be displayed. FRAME nil
937 or omitted means use the selected frame. */)
938 (Lisp_Object spec, Lisp_Object frame)
940 Lisp_Object mask;
942 mask = Qnil;
943 if (valid_image_p (spec))
945 struct frame *f = check_x_frame (frame);
946 int id = lookup_image (f, spec);
947 struct image *img = IMAGE_FROM_ID (f, id);
948 if (img->mask)
949 mask = Qt;
951 else
952 error ("Invalid image specification");
954 return mask;
957 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
958 doc: /* Return metadata for image SPEC.
959 FRAME is the frame on which the image will be displayed. FRAME nil
960 or omitted means use the selected frame. */)
961 (Lisp_Object spec, Lisp_Object frame)
963 Lisp_Object ext;
965 ext = Qnil;
966 if (valid_image_p (spec))
968 struct frame *f = check_x_frame (frame);
969 int id = lookup_image (f, spec);
970 struct image *img = IMAGE_FROM_ID (f, id);
971 ext = img->data.lisp_val;
974 return ext;
978 /***********************************************************************
979 Image type independent image structures
980 ***********************************************************************/
982 static struct image *make_image (Lisp_Object spec, unsigned hash);
983 static void free_image (struct frame *f, struct image *img);
984 static int check_image_size (struct frame *f, int width, int height);
986 #define MAX_IMAGE_SIZE 6.0
987 /* Allocate and return a new image structure for image specification
988 SPEC. SPEC has a hash value of HASH. */
990 static struct image *
991 make_image (Lisp_Object spec, unsigned int hash)
993 struct image *img = (struct image *) xmalloc (sizeof *img);
994 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
996 xassert (valid_image_p (spec));
997 memset (img, 0, sizeof *img);
998 img->dependencies = NILP (file) ? Qnil : list1 (file);
999 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1000 xassert (img->type != NULL);
1001 img->spec = spec;
1002 img->data.lisp_val = Qnil;
1003 img->ascent = DEFAULT_IMAGE_ASCENT;
1004 img->hash = hash;
1005 img->corners[BOT_CORNER] = -1; /* Full image */
1006 return img;
1010 /* Free image IMG which was used on frame F, including its resources. */
1012 static void
1013 free_image (struct frame *f, struct image *img)
1015 if (img)
1017 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1019 /* Remove IMG from the hash table of its cache. */
1020 if (img->prev)
1021 img->prev->next = img->next;
1022 else
1023 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1025 if (img->next)
1026 img->next->prev = img->prev;
1028 c->images[img->id] = NULL;
1030 /* Free resources, then free IMG. */
1031 img->type->free (f, img);
1032 xfree (img);
1036 /* Return 1 if the given widths and heights are valid for display;
1037 otherwise, return 0. */
1040 check_image_size (struct frame *f, int width, int height)
1042 int w, h;
1044 if (width <= 0 || height <= 0)
1045 return 0;
1047 if (INTEGERP (Vmax_image_size))
1048 w = h = XINT (Vmax_image_size);
1049 else if (FLOATP (Vmax_image_size))
1051 if (f != NULL)
1053 w = FRAME_PIXEL_WIDTH (f);
1054 h = FRAME_PIXEL_HEIGHT (f);
1056 else
1057 w = h = 1024; /* Arbitrary size for unknown frame. */
1058 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1059 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1061 else
1062 return 1;
1064 return (width <= w && height <= h);
1067 /* Prepare image IMG for display on frame F. Must be called before
1068 drawing an image. */
1070 void
1071 prepare_image_for_display (struct frame *f, struct image *img)
1073 EMACS_TIME t;
1075 /* We're about to display IMG, so set its timestamp to `now'. */
1076 EMACS_GET_TIME (t);
1077 img->timestamp = EMACS_SECS (t);
1079 /* If IMG doesn't have a pixmap yet, load it now, using the image
1080 type dependent loader function. */
1081 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1082 img->load_failed_p = img->type->load (f, img) == 0;
1087 /* Value is the number of pixels for the ascent of image IMG when
1088 drawn in face FACE. */
1091 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1093 int height;
1094 int ascent;
1096 if (slice->height == img->height)
1097 height = img->height + img->vmargin;
1098 else if (slice->y == 0)
1099 height = slice->height + img->vmargin;
1100 else
1101 height = slice->height;
1103 if (img->ascent == CENTERED_IMAGE_ASCENT)
1105 if (face->font)
1107 #ifdef HAVE_NTGUI
1108 /* W32 specific version. Why?. ++kfs */
1109 ascent = height / 2 - (FONT_DESCENT (face->font)
1110 - FONT_BASE (face->font)) / 2;
1111 #else
1112 /* This expression is arranged so that if the image can't be
1113 exactly centered, it will be moved slightly up. This is
1114 because a typical font is `top-heavy' (due to the presence
1115 uppercase letters), so the image placement should err towards
1116 being top-heavy too. It also just generally looks better. */
1117 ascent = (height + FONT_BASE(face->font)
1118 - FONT_DESCENT(face->font) + 1) / 2;
1119 #endif /* HAVE_NTGUI */
1121 else
1122 ascent = height / 2;
1124 else
1125 ascent = (int) (height * img->ascent / 100.0);
1127 return ascent;
1131 /* Image background colors. */
1133 /* Find the "best" corner color of a bitmap.
1134 On W32, XIMG is assumed to a device context with the bitmap selected. */
1136 static RGB_PIXEL_COLOR
1137 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1138 unsigned long width, unsigned long height)
1140 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1141 int i, best_count;
1143 if (corners && corners[BOT_CORNER] >= 0)
1145 /* Get the colors at the corner_pixels of ximg. */
1146 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1147 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1148 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1149 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1151 else
1153 /* Get the colors at the corner_pixels of ximg. */
1154 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1155 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1156 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1157 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1159 /* Choose the most frequently found color as background. */
1160 for (i = best_count = 0; i < 4; ++i)
1162 int j, n;
1164 for (j = n = 0; j < 4; ++j)
1165 if (corner_pixels[i] == corner_pixels[j])
1166 ++n;
1168 if (n > best_count)
1169 best = corner_pixels[i], best_count = n;
1172 return best;
1175 /* Portability macros */
1177 #ifdef HAVE_NTGUI
1179 #define Destroy_Image(img_dc, prev) \
1180 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1182 #define Free_Pixmap(display, pixmap) \
1183 DeleteObject (pixmap)
1185 #elif defined (HAVE_NS)
1187 #define Destroy_Image(ximg, dummy) \
1188 ns_release_object (ximg)
1190 #define Free_Pixmap(display, pixmap) \
1191 ns_release_object (pixmap)
1193 #else
1195 #define Destroy_Image(ximg, dummy) \
1196 XDestroyImage (ximg)
1198 #define Free_Pixmap(display, pixmap) \
1199 XFreePixmap (display, pixmap)
1201 #endif /* !HAVE_NTGUI && !HAVE_NS */
1204 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1205 it is guessed heuristically. If non-zero, XIMG is an existing
1206 XImage object (or device context with the image selected on W32) to
1207 use for the heuristic. */
1209 RGB_PIXEL_COLOR
1210 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1212 if (! img->background_valid)
1213 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1215 int free_ximg = !ximg;
1216 #ifdef HAVE_NTGUI
1217 HGDIOBJ prev;
1218 #endif /* HAVE_NTGUI */
1220 if (free_ximg)
1222 #ifndef HAVE_NTGUI
1223 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1224 0, 0, img->width, img->height, ~0, ZPixmap);
1225 #else
1226 HDC frame_dc = get_frame_dc (f);
1227 ximg = CreateCompatibleDC (frame_dc);
1228 release_frame_dc (f, frame_dc);
1229 prev = SelectObject (ximg, img->pixmap);
1230 #endif /* !HAVE_NTGUI */
1233 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1235 if (free_ximg)
1236 Destroy_Image (ximg, prev);
1238 img->background_valid = 1;
1241 return img->background;
1244 /* Return the `background_transparent' field of IMG. If IMG doesn't
1245 have one yet, it is guessed heuristically. If non-zero, MASK is an
1246 existing XImage object to use for the heuristic. */
1249 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1251 if (! img->background_transparent_valid)
1252 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1254 if (img->mask)
1256 int free_mask = !mask;
1257 #ifdef HAVE_NTGUI
1258 HGDIOBJ prev;
1259 #endif /* HAVE_NTGUI */
1261 if (free_mask)
1263 #ifndef HAVE_NTGUI
1264 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1265 0, 0, img->width, img->height, ~0, ZPixmap);
1266 #else
1267 HDC frame_dc = get_frame_dc (f);
1268 mask = CreateCompatibleDC (frame_dc);
1269 release_frame_dc (f, frame_dc);
1270 prev = SelectObject (mask, img->mask);
1271 #endif /* HAVE_NTGUI */
1274 img->background_transparent
1275 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1277 if (free_mask)
1278 Destroy_Image (mask, prev);
1280 else
1281 img->background_transparent = 0;
1283 img->background_transparent_valid = 1;
1286 return img->background_transparent;
1290 /***********************************************************************
1291 Helper functions for X image types
1292 ***********************************************************************/
1294 static void x_clear_image_1 (struct frame *, struct image *, int,
1295 int, int);
1296 static void x_clear_image (struct frame *f, struct image *img);
1297 static unsigned long x_alloc_image_color (struct frame *f,
1298 struct image *img,
1299 Lisp_Object color_name,
1300 unsigned long dflt);
1303 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1304 free the pixmap if any. MASK_P non-zero means clear the mask
1305 pixmap if any. COLORS_P non-zero means free colors allocated for
1306 the image, if any. */
1308 static void
1309 x_clear_image_1 (struct frame *f, struct image *img, int pixmap_p, int mask_p,
1310 int colors_p)
1312 if (pixmap_p && img->pixmap)
1314 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1315 img->pixmap = NO_PIXMAP;
1316 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1317 img->background_valid = 0;
1320 if (mask_p && img->mask)
1322 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1323 img->mask = NO_PIXMAP;
1324 img->background_transparent_valid = 0;
1327 if (colors_p && img->ncolors)
1329 /* W32_TODO: color table support. */
1330 #ifdef HAVE_X_WINDOWS
1331 x_free_colors (f, img->colors, img->ncolors);
1332 #endif /* HAVE_X_WINDOWS */
1333 xfree (img->colors);
1334 img->colors = NULL;
1335 img->ncolors = 0;
1340 /* Free X resources of image IMG which is used on frame F. */
1342 static void
1343 x_clear_image (struct frame *f, struct image *img)
1345 BLOCK_INPUT;
1346 x_clear_image_1 (f, img, 1, 1, 1);
1347 UNBLOCK_INPUT;
1351 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1352 cannot be allocated, use DFLT. Add a newly allocated color to
1353 IMG->colors, so that it can be freed again. Value is the pixel
1354 color. */
1356 static unsigned long
1357 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1358 unsigned long dflt)
1360 XColor color;
1361 unsigned long result;
1363 xassert (STRINGP (color_name));
1365 if (x_defined_color (f, SSDATA (color_name), &color, 1))
1367 /* This isn't called frequently so we get away with simply
1368 reallocating the color vector to the needed size, here. */
1369 ++img->ncolors;
1370 img->colors =
1371 (unsigned long *) xrealloc (img->colors,
1372 img->ncolors * sizeof *img->colors);
1373 img->colors[img->ncolors - 1] = color.pixel;
1374 result = color.pixel;
1376 else
1377 result = dflt;
1379 return result;
1384 /***********************************************************************
1385 Image Cache
1386 ***********************************************************************/
1388 static struct image *search_image_cache (struct frame *, Lisp_Object, unsigned);
1389 static void cache_image (struct frame *f, struct image *img);
1390 static void postprocess_image (struct frame *, struct image *);
1392 /* Return a new, initialized image cache that is allocated from the
1393 heap. Call free_image_cache to free an image cache. */
1395 struct image_cache *
1396 make_image_cache (void)
1398 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1399 int size;
1401 memset (c, 0, sizeof *c);
1402 c->size = 50;
1403 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1404 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1405 c->buckets = (struct image **) xmalloc (size);
1406 memset (c->buckets, 0, size);
1407 return c;
1411 /* Find an image matching SPEC in the cache, and return it. If no
1412 image is found, return NULL. */
1413 static struct image *
1414 search_image_cache (struct frame *f, Lisp_Object spec, unsigned int hash)
1416 struct image *img;
1417 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1418 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1420 if (!c) return NULL;
1422 /* If the image spec does not specify a background color, the cached
1423 image must have the same background color as the current frame.
1424 The foreground color must also match, for the sake of monochrome
1425 images.
1427 In fact, we could ignore the foreground color matching condition
1428 for color images, or if the image spec specifies :foreground;
1429 similarly we could ignore the background color matching condition
1430 for formats that don't use transparency (such as jpeg), or if the
1431 image spec specifies :background. However, the extra memory
1432 usage is probably negligible in practice, so we don't bother. */
1434 for (img = c->buckets[i]; img; img = img->next)
1435 if (img->hash == hash
1436 && !NILP (Fequal (img->spec, spec))
1437 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1438 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1439 break;
1440 return img;
1444 /* Search frame F for an image with spec SPEC, and free it. */
1446 static void
1447 uncache_image (struct frame *f, Lisp_Object spec)
1449 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1450 if (img)
1452 free_image (f, img);
1453 /* As display glyphs may still be referring to the image ID, we
1454 must garbage the frame (Bug#6426). */
1455 SET_FRAME_GARBAGED (f);
1460 /* Free image cache of frame F. Be aware that X frames share images
1461 caches. */
1463 void
1464 free_image_cache (struct frame *f)
1466 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1467 if (c)
1469 int i;
1471 /* Cache should not be referenced by any frame when freed. */
1472 xassert (c->refcount == 0);
1474 for (i = 0; i < c->used; ++i)
1475 free_image (f, c->images[i]);
1476 xfree (c->images);
1477 xfree (c->buckets);
1478 xfree (c);
1479 FRAME_IMAGE_CACHE (f) = NULL;
1484 /* Clear image cache of frame F. FILTER=t means free all images.
1485 FILTER=nil means clear only images that haven't been
1486 displayed for some time.
1487 Else, only free the images which have FILTER in their `dependencies'.
1488 Should be called from time to time to reduce the number of loaded images.
1489 If image-cache-eviction-delay is non-nil, this frees images in the cache
1490 which weren't displayed for at least that many seconds. */
1492 static void
1493 clear_image_cache (struct frame *f, Lisp_Object filter)
1495 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1497 if (c)
1499 int i, nfreed = 0;
1501 /* Block input so that we won't be interrupted by a SIGIO
1502 while being in an inconsistent state. */
1503 BLOCK_INPUT;
1505 if (!NILP (filter))
1507 /* Filter image cache. */
1508 for (i = 0; i < c->used; ++i)
1510 struct image *img = c->images[i];
1511 if (img && (EQ (Qt, filter)
1512 || !NILP (Fmember (filter, img->dependencies))))
1514 free_image (f, img);
1515 ++nfreed;
1519 else if (INTEGERP (Vimage_cache_eviction_delay))
1521 /* Free cache based on timestamp. */
1522 EMACS_TIME t;
1523 unsigned long old;
1524 int delay, nimages = 0;
1526 for (i = 0; i < c->used; ++i)
1527 if (c->images[i])
1528 nimages++;
1530 /* If the number of cached images has grown unusually large,
1531 decrease the cache eviction delay (Bug#6230). */
1532 delay = XFASTINT (Vimage_cache_eviction_delay);
1533 if (nimages > 40)
1534 delay = max (1, 1600 * delay / (nimages*nimages));
1536 EMACS_GET_TIME (t);
1537 old = EMACS_SECS (t) - delay;
1539 for (i = 0; i < c->used; ++i)
1541 struct image *img = c->images[i];
1542 if (img && img->timestamp < old)
1544 free_image (f, img);
1545 ++nfreed;
1550 /* We may be clearing the image cache because, for example,
1551 Emacs was iconified for a longer period of time. In that
1552 case, current matrices may still contain references to
1553 images freed above. So, clear these matrices. */
1554 if (nfreed)
1556 Lisp_Object tail, frame;
1558 FOR_EACH_FRAME (tail, frame)
1560 struct frame *fr = XFRAME (frame);
1561 if (FRAME_IMAGE_CACHE (fr) == c)
1562 clear_current_matrices (fr);
1565 ++windows_or_buffers_changed;
1568 UNBLOCK_INPUT;
1572 void
1573 clear_image_caches (Lisp_Object filter)
1575 /* FIXME: We want to do
1576 * struct terminal *t;
1577 * for (t = terminal_list; t; t = t->next_terminal)
1578 * clear_image_cache (t, filter); */
1579 Lisp_Object tail, frame;
1580 FOR_EACH_FRAME (tail, frame)
1581 if (FRAME_WINDOW_P (XFRAME (frame)))
1582 clear_image_cache (XFRAME (frame), filter);
1585 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1586 0, 1, 0,
1587 doc: /* Clear the image cache.
1588 FILTER nil or a frame means clear all images in the selected frame.
1589 FILTER t means clear the image caches of all frames.
1590 Anything else, means only clear those images which refer to FILTER,
1591 which is then usually a filename. */)
1592 (Lisp_Object filter)
1594 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1595 clear_image_caches (filter);
1596 else
1597 clear_image_cache (check_x_frame (filter), Qt);
1599 return Qnil;
1603 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1604 1, 2, 0,
1605 doc: /* Fush the image with specification SPEC on frame FRAME.
1606 This removes the image from the Emacs image cache. If SPEC specifies
1607 an image file, the next redisplay of this image will read from the
1608 current contents of that file.
1610 FRAME nil or omitted means use the selected frame.
1611 FRAME t means refresh the image on all frames. */)
1612 (Lisp_Object spec, Lisp_Object frame)
1614 if (!valid_image_p (spec))
1615 error ("Invalid image specification");
1617 if (EQ (frame, Qt))
1619 Lisp_Object tail;
1620 FOR_EACH_FRAME (tail, frame)
1622 struct frame *f = XFRAME (frame);
1623 if (FRAME_WINDOW_P (f))
1624 uncache_image (f, spec);
1627 else
1628 uncache_image (check_x_frame (frame), spec);
1630 return Qnil;
1634 /* Compute masks and transform image IMG on frame F, as specified
1635 by the image's specification, */
1637 static void
1638 postprocess_image (struct frame *f, struct image *img)
1640 /* Manipulation of the image's mask. */
1641 if (img->pixmap)
1643 Lisp_Object conversion, spec;
1644 Lisp_Object mask;
1646 spec = img->spec;
1648 /* `:heuristic-mask t'
1649 `:mask heuristic'
1650 means build a mask heuristically.
1651 `:heuristic-mask (R G B)'
1652 `:mask (heuristic (R G B))'
1653 means build a mask from color (R G B) in the
1654 image.
1655 `:mask nil'
1656 means remove a mask, if any. */
1658 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1659 if (!NILP (mask))
1660 x_build_heuristic_mask (f, img, mask);
1661 else
1663 int found_p;
1665 mask = image_spec_value (spec, QCmask, &found_p);
1667 if (EQ (mask, Qheuristic))
1668 x_build_heuristic_mask (f, img, Qt);
1669 else if (CONSP (mask)
1670 && EQ (XCAR (mask), Qheuristic))
1672 if (CONSP (XCDR (mask)))
1673 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1674 else
1675 x_build_heuristic_mask (f, img, XCDR (mask));
1677 else if (NILP (mask) && found_p && img->mask)
1679 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1680 img->mask = NO_PIXMAP;
1685 /* Should we apply an image transformation algorithm? */
1686 conversion = image_spec_value (spec, QCconversion, NULL);
1687 if (EQ (conversion, Qdisabled))
1688 x_disable_image (f, img);
1689 else if (EQ (conversion, Qlaplace))
1690 x_laplace (f, img);
1691 else if (EQ (conversion, Qemboss))
1692 x_emboss (f, img);
1693 else if (CONSP (conversion)
1694 && EQ (XCAR (conversion), Qedge_detection))
1696 Lisp_Object tem;
1697 tem = XCDR (conversion);
1698 if (CONSP (tem))
1699 x_edge_detection (f, img,
1700 Fplist_get (tem, QCmatrix),
1701 Fplist_get (tem, QCcolor_adjustment));
1707 /* Return the id of image with Lisp specification SPEC on frame F.
1708 SPEC must be a valid Lisp image specification (see valid_image_p). */
1711 lookup_image (struct frame *f, Lisp_Object spec)
1713 struct image *img;
1714 unsigned hash;
1715 EMACS_TIME now;
1717 /* F must be a window-system frame, and SPEC must be a valid image
1718 specification. */
1719 xassert (FRAME_WINDOW_P (f));
1720 xassert (valid_image_p (spec));
1722 /* Look up SPEC in the hash table of the image cache. */
1723 hash = sxhash (spec, 0);
1724 img = search_image_cache (f, spec, hash);
1725 if (img && img->load_failed_p)
1727 free_image (f, img);
1728 img = NULL;
1731 /* If not found, create a new image and cache it. */
1732 if (img == NULL)
1734 BLOCK_INPUT;
1735 img = make_image (spec, hash);
1736 cache_image (f, img);
1737 img->load_failed_p = img->type->load (f, img) == 0;
1738 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1739 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1741 /* If we can't load the image, and we don't have a width and
1742 height, use some arbitrary width and height so that we can
1743 draw a rectangle for it. */
1744 if (img->load_failed_p)
1746 Lisp_Object value;
1748 value = image_spec_value (spec, QCwidth, NULL);
1749 img->width = (INTEGERP (value)
1750 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1751 value = image_spec_value (spec, QCheight, NULL);
1752 img->height = (INTEGERP (value)
1753 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1755 else
1757 /* Handle image type independent image attributes
1758 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1759 `:background COLOR'. */
1760 Lisp_Object ascent, margin, relief, bg;
1762 ascent = image_spec_value (spec, QCascent, NULL);
1763 if (INTEGERP (ascent))
1764 img->ascent = XFASTINT (ascent);
1765 else if (EQ (ascent, Qcenter))
1766 img->ascent = CENTERED_IMAGE_ASCENT;
1768 margin = image_spec_value (spec, QCmargin, NULL);
1769 if (INTEGERP (margin) && XINT (margin) >= 0)
1770 img->vmargin = img->hmargin = XFASTINT (margin);
1771 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1772 && INTEGERP (XCDR (margin)))
1774 if (XINT (XCAR (margin)) > 0)
1775 img->hmargin = XFASTINT (XCAR (margin));
1776 if (XINT (XCDR (margin)) > 0)
1777 img->vmargin = XFASTINT (XCDR (margin));
1780 relief = image_spec_value (spec, QCrelief, NULL);
1781 if (INTEGERP (relief))
1783 img->relief = XINT (relief);
1784 img->hmargin += eabs (img->relief);
1785 img->vmargin += eabs (img->relief);
1788 if (! img->background_valid)
1790 bg = image_spec_value (img->spec, QCbackground, NULL);
1791 if (!NILP (bg))
1793 img->background
1794 = x_alloc_image_color (f, img, bg,
1795 FRAME_BACKGROUND_PIXEL (f));
1796 img->background_valid = 1;
1800 /* Do image transformations and compute masks, unless we
1801 don't have the image yet. */
1802 if (!EQ (*img->type->type, Qpostscript))
1803 postprocess_image (f, img);
1806 UNBLOCK_INPUT;
1809 /* We're using IMG, so set its timestamp to `now'. */
1810 EMACS_GET_TIME (now);
1811 img->timestamp = EMACS_SECS (now);
1813 /* Value is the image id. */
1814 return img->id;
1818 /* Cache image IMG in the image cache of frame F. */
1820 static void
1821 cache_image (struct frame *f, struct image *img)
1823 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1824 int i;
1826 /* Find a free slot in c->images. */
1827 for (i = 0; i < c->used; ++i)
1828 if (c->images[i] == NULL)
1829 break;
1831 /* If no free slot found, maybe enlarge c->images. */
1832 if (i == c->used && c->used == c->size)
1834 c->size *= 2;
1835 c->images = (struct image **) xrealloc (c->images,
1836 c->size * sizeof *c->images);
1839 /* Add IMG to c->images, and assign IMG an id. */
1840 c->images[i] = img;
1841 img->id = i;
1842 if (i == c->used)
1843 ++c->used;
1845 /* Add IMG to the cache's hash table. */
1846 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1847 img->next = c->buckets[i];
1848 if (img->next)
1849 img->next->prev = img;
1850 img->prev = NULL;
1851 c->buckets[i] = img;
1855 /* Call FN on every image in the image cache of frame F. Used to mark
1856 Lisp Objects in the image cache. */
1858 /* Mark Lisp objects in image IMG. */
1860 static void
1861 mark_image (struct image *img)
1863 mark_object (img->spec);
1864 mark_object (img->dependencies);
1866 if (!NILP (img->data.lisp_val))
1867 mark_object (img->data.lisp_val);
1871 void
1872 mark_image_cache (struct image_cache *c)
1874 if (c)
1876 int i;
1877 for (i = 0; i < c->used; ++i)
1878 if (c->images[i])
1879 mark_image (c->images[i]);
1885 /***********************************************************************
1886 X / NS / W32 support code
1887 ***********************************************************************/
1889 #ifdef HAVE_NTGUI
1891 /* Macro for defining functions that will be loaded from image DLLs. */
1892 #define DEF_IMGLIB_FN(rettype,func,args) rettype (FAR CDECL *fn_##func)args
1894 /* Macro for loading those image functions from the library. */
1895 #define LOAD_IMGLIB_FN(lib,func) { \
1896 fn_##func = (void *) GetProcAddress (lib, #func); \
1897 if (!fn_##func) return 0; \
1900 #endif /* HAVE_NTGUI */
1902 static int x_create_x_image_and_pixmap (struct frame *, int, int, int,
1903 XImagePtr *, Pixmap *);
1904 static void x_destroy_x_image (XImagePtr);
1905 static void x_put_x_image (struct frame *, XImagePtr, Pixmap, int, int);
1908 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1909 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1910 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1911 via xmalloc. Print error messages via image_error if an error
1912 occurs. Value is non-zero if successful.
1914 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1915 should indicate the bit depth of the image. */
1917 static int
1918 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1919 XImagePtr *ximg, Pixmap *pixmap)
1921 #ifdef HAVE_X_WINDOWS
1922 Display *display = FRAME_X_DISPLAY (f);
1923 Window window = FRAME_X_WINDOW (f);
1924 Screen *screen = FRAME_X_SCREEN (f);
1926 xassert (interrupt_input_blocked);
1928 if (depth <= 0)
1929 depth = DefaultDepthOfScreen (screen);
1930 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1931 depth, ZPixmap, 0, NULL, width, height,
1932 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1933 if (*ximg == NULL)
1935 image_error ("Unable to allocate X image", Qnil, Qnil);
1936 return 0;
1939 /* Allocate image raster. */
1940 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
1942 /* Allocate a pixmap of the same size. */
1943 *pixmap = XCreatePixmap (display, window, width, height, depth);
1944 if (*pixmap == NO_PIXMAP)
1946 x_destroy_x_image (*ximg);
1947 *ximg = NULL;
1948 image_error ("Unable to create X pixmap", Qnil, Qnil);
1949 return 0;
1952 return 1;
1953 #endif /* HAVE_X_WINDOWS */
1955 #ifdef HAVE_NTGUI
1957 BITMAPINFOHEADER *header;
1958 HDC hdc;
1959 int scanline_width_bits;
1960 int remainder;
1961 int palette_colors = 0;
1963 if (depth == 0)
1964 depth = 24;
1966 if (depth != 1 && depth != 4 && depth != 8
1967 && depth != 16 && depth != 24 && depth != 32)
1969 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1970 return 0;
1973 scanline_width_bits = width * depth;
1974 remainder = scanline_width_bits % 32;
1976 if (remainder)
1977 scanline_width_bits += 32 - remainder;
1979 /* Bitmaps with a depth less than 16 need a palette. */
1980 /* BITMAPINFO structure already contains the first RGBQUAD. */
1981 if (depth < 16)
1982 palette_colors = 1 << depth - 1;
1984 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1985 if (*ximg == NULL)
1987 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
1988 return 0;
1991 header = &(*ximg)->info.bmiHeader;
1992 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
1993 header->biSize = sizeof (*header);
1994 header->biWidth = width;
1995 header->biHeight = -height; /* negative indicates a top-down bitmap. */
1996 header->biPlanes = 1;
1997 header->biBitCount = depth;
1998 header->biCompression = BI_RGB;
1999 header->biClrUsed = palette_colors;
2001 /* TODO: fill in palette. */
2002 if (depth == 1)
2004 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2005 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2006 (*ximg)->info.bmiColors[0].rgbRed = 0;
2007 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2008 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2009 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2010 (*ximg)->info.bmiColors[1].rgbRed = 255;
2011 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2014 hdc = get_frame_dc (f);
2016 /* Create a DIBSection and raster array for the bitmap,
2017 and store its handle in *pixmap. */
2018 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2019 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2020 /* casting avoids a GCC warning */
2021 (void **)&((*ximg)->data), NULL, 0);
2023 /* Realize display palette and garbage all frames. */
2024 release_frame_dc (f, hdc);
2026 if (*pixmap == NULL)
2028 DWORD err = GetLastError ();
2029 Lisp_Object errcode;
2030 /* All system errors are < 10000, so the following is safe. */
2031 XSETINT (errcode, (int) err);
2032 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2033 x_destroy_x_image (*ximg);
2034 return 0;
2037 return 1;
2039 #endif /* HAVE_NTGUI */
2041 #ifdef HAVE_NS
2042 *pixmap = ns_image_for_XPM (width, height, depth);
2043 if (*pixmap == 0)
2045 *ximg = NULL;
2046 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2047 return 0;
2049 *ximg = *pixmap;
2050 return 1;
2051 #endif
2055 /* Destroy XImage XIMG. Free XIMG->data. */
2057 static void
2058 x_destroy_x_image (XImagePtr ximg)
2060 xassert (interrupt_input_blocked);
2061 if (ximg)
2063 #ifdef HAVE_X_WINDOWS
2064 xfree (ximg->data);
2065 ximg->data = NULL;
2066 XDestroyImage (ximg);
2067 #endif /* HAVE_X_WINDOWS */
2068 #ifdef HAVE_NTGUI
2069 /* Data will be freed by DestroyObject. */
2070 ximg->data = NULL;
2071 xfree (ximg);
2072 #endif /* HAVE_NTGUI */
2073 #ifdef HAVE_NS
2074 ns_release_object (ximg);
2075 #endif /* HAVE_NS */
2080 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2081 are width and height of both the image and pixmap. */
2083 static void
2084 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2086 #ifdef HAVE_X_WINDOWS
2087 GC gc;
2089 xassert (interrupt_input_blocked);
2090 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2091 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2092 XFreeGC (FRAME_X_DISPLAY (f), gc);
2093 #endif /* HAVE_X_WINDOWS */
2095 #ifdef HAVE_NTGUI
2096 #if 0 /* I don't think this is necessary looking at where it is used. */
2097 HDC hdc = get_frame_dc (f);
2098 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2099 release_frame_dc (f, hdc);
2100 #endif
2101 #endif /* HAVE_NTGUI */
2103 #ifdef HAVE_NS
2104 xassert (ximg == pixmap);
2105 ns_retain_object (ximg);
2106 #endif
2110 /***********************************************************************
2111 File Handling
2112 ***********************************************************************/
2114 static unsigned char *slurp_file (char *, int *);
2117 /* Find image file FILE. Look in data-directory/images, then
2118 x-bitmap-file-path. Value is the encoded full name of the file
2119 found, or nil if not found. */
2121 Lisp_Object
2122 x_find_image_file (Lisp_Object file)
2124 Lisp_Object file_found, search_path;
2125 int fd;
2127 /* TODO I think this should use something like image-load-path
2128 instead. Unfortunately, that can contain non-string elements. */
2129 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2130 Vdata_directory),
2131 Vx_bitmap_file_path);
2133 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2134 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2136 if (fd == -1)
2137 file_found = Qnil;
2138 else
2140 file_found = ENCODE_FILE (file_found);
2141 close (fd);
2144 return file_found;
2148 /* Read FILE into memory. Value is a pointer to a buffer allocated
2149 with xmalloc holding FILE's contents. Value is null if an error
2150 occurred. *SIZE is set to the size of the file. */
2152 static unsigned char *
2153 slurp_file (char *file, int *size)
2155 FILE *fp = NULL;
2156 unsigned char *buf = NULL;
2157 struct stat st;
2159 if (stat (file, &st) == 0
2160 && (fp = fopen (file, "rb")) != NULL
2161 && (buf = (unsigned char *) xmalloc (st.st_size),
2162 fread (buf, 1, st.st_size, fp) == st.st_size))
2164 *size = st.st_size;
2165 fclose (fp);
2167 else
2169 if (fp)
2170 fclose (fp);
2171 if (buf)
2173 xfree (buf);
2174 buf = NULL;
2178 return buf;
2183 /***********************************************************************
2184 XBM images
2185 ***********************************************************************/
2187 static int xbm_scan (unsigned char **, unsigned char *, char *, int *);
2188 static int xbm_load (struct frame *f, struct image *img);
2189 static int xbm_load_image (struct frame *f, struct image *img,
2190 unsigned char *, unsigned char *);
2191 static int xbm_image_p (Lisp_Object object);
2192 static int xbm_read_bitmap_data (struct frame *f,
2193 unsigned char *, unsigned char *,
2194 int *, int *, char **, int);
2195 static int xbm_file_p (Lisp_Object);
2198 /* Indices of image specification fields in xbm_format, below. */
2200 enum xbm_keyword_index
2202 XBM_TYPE,
2203 XBM_FILE,
2204 XBM_WIDTH,
2205 XBM_HEIGHT,
2206 XBM_DATA,
2207 XBM_FOREGROUND,
2208 XBM_BACKGROUND,
2209 XBM_ASCENT,
2210 XBM_MARGIN,
2211 XBM_RELIEF,
2212 XBM_ALGORITHM,
2213 XBM_HEURISTIC_MASK,
2214 XBM_MASK,
2215 XBM_LAST
2218 /* Vector of image_keyword structures describing the format
2219 of valid XBM image specifications. */
2221 static const struct image_keyword xbm_format[XBM_LAST] =
2223 {":type", IMAGE_SYMBOL_VALUE, 1},
2224 {":file", IMAGE_STRING_VALUE, 0},
2225 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2226 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2227 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2228 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2229 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2230 {":ascent", IMAGE_ASCENT_VALUE, 0},
2231 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2232 {":relief", IMAGE_INTEGER_VALUE, 0},
2233 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2234 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2235 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2238 /* Structure describing the image type XBM. */
2240 static struct image_type xbm_type =
2242 &Qxbm,
2243 xbm_image_p,
2244 xbm_load,
2245 x_clear_image,
2246 NULL
2249 /* Tokens returned from xbm_scan. */
2251 enum xbm_token
2253 XBM_TK_IDENT = 256,
2254 XBM_TK_NUMBER
2258 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2259 A valid specification is a list starting with the symbol `image'
2260 The rest of the list is a property list which must contain an
2261 entry `:type xbm..
2263 If the specification specifies a file to load, it must contain
2264 an entry `:file FILENAME' where FILENAME is a string.
2266 If the specification is for a bitmap loaded from memory it must
2267 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2268 WIDTH and HEIGHT are integers > 0. DATA may be:
2270 1. a string large enough to hold the bitmap data, i.e. it must
2271 have a size >= (WIDTH + 7) / 8 * HEIGHT
2273 2. a bool-vector of size >= WIDTH * HEIGHT
2275 3. a vector of strings or bool-vectors, one for each line of the
2276 bitmap.
2278 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2279 may not be specified in this case because they are defined in the
2280 XBM file.
2282 Both the file and data forms may contain the additional entries
2283 `:background COLOR' and `:foreground COLOR'. If not present,
2284 foreground and background of the frame on which the image is
2285 displayed is used. */
2287 static int
2288 xbm_image_p (Lisp_Object object)
2290 struct image_keyword kw[XBM_LAST];
2292 memcpy (kw, xbm_format, sizeof kw);
2293 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2294 return 0;
2296 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2298 if (kw[XBM_FILE].count)
2300 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2301 return 0;
2303 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2305 /* In-memory XBM file. */
2306 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2307 return 0;
2309 else
2311 Lisp_Object data;
2312 int width, height;
2314 /* Entries for `:width', `:height' and `:data' must be present. */
2315 if (!kw[XBM_WIDTH].count
2316 || !kw[XBM_HEIGHT].count
2317 || !kw[XBM_DATA].count)
2318 return 0;
2320 data = kw[XBM_DATA].value;
2321 width = XFASTINT (kw[XBM_WIDTH].value);
2322 height = XFASTINT (kw[XBM_HEIGHT].value);
2324 /* Check type of data, and width and height against contents of
2325 data. */
2326 if (VECTORP (data))
2328 int i;
2330 /* Number of elements of the vector must be >= height. */
2331 if (ASIZE (data) < height)
2332 return 0;
2334 /* Each string or bool-vector in data must be large enough
2335 for one line of the image. */
2336 for (i = 0; i < height; ++i)
2338 Lisp_Object elt = XVECTOR (data)->contents[i];
2340 if (STRINGP (elt))
2342 if (SCHARS (elt)
2343 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2344 return 0;
2346 else if (BOOL_VECTOR_P (elt))
2348 if (XBOOL_VECTOR (elt)->size < width)
2349 return 0;
2351 else
2352 return 0;
2355 else if (STRINGP (data))
2357 if (SCHARS (data)
2358 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2359 return 0;
2361 else if (BOOL_VECTOR_P (data))
2363 if (XBOOL_VECTOR (data)->size < width * height)
2364 return 0;
2366 else
2367 return 0;
2370 return 1;
2374 /* Scan a bitmap file. FP is the stream to read from. Value is
2375 either an enumerator from enum xbm_token, or a character for a
2376 single-character token, or 0 at end of file. If scanning an
2377 identifier, store the lexeme of the identifier in SVAL. If
2378 scanning a number, store its value in *IVAL. */
2380 static int
2381 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2383 unsigned int c;
2385 loop:
2387 /* Skip white space. */
2388 while (*s < end && (c = *(*s)++, isspace (c)))
2391 if (*s >= end)
2392 c = 0;
2393 else if (isdigit (c))
2395 int value = 0, digit;
2397 if (c == '0' && *s < end)
2399 c = *(*s)++;
2400 if (c == 'x' || c == 'X')
2402 while (*s < end)
2404 c = *(*s)++;
2405 if (isdigit (c))
2406 digit = c - '0';
2407 else if (c >= 'a' && c <= 'f')
2408 digit = c - 'a' + 10;
2409 else if (c >= 'A' && c <= 'F')
2410 digit = c - 'A' + 10;
2411 else
2412 break;
2413 value = 16 * value + digit;
2416 else if (isdigit (c))
2418 value = c - '0';
2419 while (*s < end
2420 && (c = *(*s)++, isdigit (c)))
2421 value = 8 * value + c - '0';
2424 else
2426 value = c - '0';
2427 while (*s < end
2428 && (c = *(*s)++, isdigit (c)))
2429 value = 10 * value + c - '0';
2432 if (*s < end)
2433 *s = *s - 1;
2434 *ival = value;
2435 c = XBM_TK_NUMBER;
2437 else if (isalpha (c) || c == '_')
2439 *sval++ = c;
2440 while (*s < end
2441 && (c = *(*s)++, (isalnum (c) || c == '_')))
2442 *sval++ = c;
2443 *sval = 0;
2444 if (*s < end)
2445 *s = *s - 1;
2446 c = XBM_TK_IDENT;
2448 else if (c == '/' && **s == '*')
2450 /* C-style comment. */
2451 ++*s;
2452 while (**s && (**s != '*' || *(*s + 1) != '/'))
2453 ++*s;
2454 if (**s)
2456 *s += 2;
2457 goto loop;
2461 return c;
2464 #ifdef HAVE_NTGUI
2466 /* Create a Windows bitmap from X bitmap data. */
2467 static HBITMAP
2468 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2470 static unsigned char swap_nibble[16]
2471 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2472 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2473 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2474 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2475 int i, j, w1, w2;
2476 unsigned char *bits, *p;
2477 HBITMAP bmp;
2479 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2480 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2481 bits = (unsigned char *) alloca (height * w2);
2482 memset (bits, 0, height * w2);
2483 for (i = 0; i < height; i++)
2485 p = bits + i*w2;
2486 for (j = 0; j < w1; j++)
2488 /* Bitswap XBM bytes to match how Windows does things. */
2489 unsigned char c = *data++;
2490 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2491 | (swap_nibble[(c>>4) & 0xf]));
2494 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2496 return bmp;
2499 static void
2500 convert_mono_to_color_image (struct frame *f, struct image *img,
2501 COLORREF foreground, COLORREF background)
2503 HDC hdc, old_img_dc, new_img_dc;
2504 HGDIOBJ old_prev, new_prev;
2505 HBITMAP new_pixmap;
2507 hdc = get_frame_dc (f);
2508 old_img_dc = CreateCompatibleDC (hdc);
2509 new_img_dc = CreateCompatibleDC (hdc);
2510 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2511 release_frame_dc (f, hdc);
2512 old_prev = SelectObject (old_img_dc, img->pixmap);
2513 new_prev = SelectObject (new_img_dc, new_pixmap);
2514 /* Windows convention for mono bitmaps is black = background,
2515 white = foreground. */
2516 SetTextColor (new_img_dc, background);
2517 SetBkColor (new_img_dc, foreground);
2519 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2520 0, 0, SRCCOPY);
2522 SelectObject (old_img_dc, old_prev);
2523 SelectObject (new_img_dc, new_prev);
2524 DeleteDC (old_img_dc);
2525 DeleteDC (new_img_dc);
2526 DeleteObject (img->pixmap);
2527 if (new_pixmap == 0)
2528 fprintf (stderr, "Failed to convert image to color.\n");
2529 else
2530 img->pixmap = new_pixmap;
2533 #define XBM_BIT_SHUFFLE(b) (~(b))
2535 #else
2537 #define XBM_BIT_SHUFFLE(b) (b)
2539 #endif /* HAVE_NTGUI */
2542 static void
2543 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2544 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2545 int non_default_colors)
2547 #ifdef HAVE_NTGUI
2548 img->pixmap
2549 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2551 /* If colors were specified, transfer the bitmap to a color one. */
2552 if (non_default_colors)
2553 convert_mono_to_color_image (f, img, fg, bg);
2555 #elif defined (HAVE_NS)
2556 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2558 #else
2559 img->pixmap
2560 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2561 FRAME_X_WINDOW (f),
2562 data,
2563 img->width, img->height,
2564 fg, bg,
2565 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2566 #endif /* !HAVE_NTGUI && !HAVE_NS */
2571 /* Replacement for XReadBitmapFileData which isn't available under old
2572 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2573 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2574 the image. Return in *DATA the bitmap data allocated with xmalloc.
2575 Value is non-zero if successful. DATA null means just test if
2576 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR
2577 is non-zero, inhibit the call to image_error when the image size is
2578 invalid (the bitmap remains unread). */
2580 static int
2581 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2582 int *width, int *height, char **data,
2583 int inhibit_image_error)
2585 unsigned char *s = contents;
2586 char buffer[BUFSIZ];
2587 int padding_p = 0;
2588 int v10 = 0;
2589 int bytes_per_line, i, nbytes;
2590 char *p;
2591 int value;
2592 int LA1;
2594 #define match() \
2595 LA1 = xbm_scan (&s, end, buffer, &value)
2597 #define expect(TOKEN) \
2598 if (LA1 != (TOKEN)) \
2599 goto failure; \
2600 else \
2601 match ()
2603 #define expect_ident(IDENT) \
2604 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2605 match (); \
2606 else \
2607 goto failure
2609 *width = *height = -1;
2610 if (data)
2611 *data = NULL;
2612 LA1 = xbm_scan (&s, end, buffer, &value);
2614 /* Parse defines for width, height and hot-spots. */
2615 while (LA1 == '#')
2617 match ();
2618 expect_ident ("define");
2619 expect (XBM_TK_IDENT);
2621 if (LA1 == XBM_TK_NUMBER)
2623 char *q = strrchr (buffer, '_');
2624 q = q ? q + 1 : buffer;
2625 if (strcmp (q, "width") == 0)
2626 *width = value;
2627 else if (strcmp (q, "height") == 0)
2628 *height = value;
2630 expect (XBM_TK_NUMBER);
2633 if (!check_image_size (f, *width, *height))
2635 if (!inhibit_image_error)
2636 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2637 goto failure;
2639 else if (data == NULL)
2640 goto success;
2642 /* Parse bits. Must start with `static'. */
2643 expect_ident ("static");
2644 if (LA1 == XBM_TK_IDENT)
2646 if (strcmp (buffer, "unsigned") == 0)
2648 match ();
2649 expect_ident ("char");
2651 else if (strcmp (buffer, "short") == 0)
2653 match ();
2654 v10 = 1;
2655 if (*width % 16 && *width % 16 < 9)
2656 padding_p = 1;
2658 else if (strcmp (buffer, "char") == 0)
2659 match ();
2660 else
2661 goto failure;
2663 else
2664 goto failure;
2666 expect (XBM_TK_IDENT);
2667 expect ('[');
2668 expect (']');
2669 expect ('=');
2670 expect ('{');
2672 bytes_per_line = (*width + 7) / 8 + padding_p;
2673 nbytes = bytes_per_line * *height;
2674 p = *data = (char *) xmalloc (nbytes);
2676 if (v10)
2678 for (i = 0; i < nbytes; i += 2)
2680 int val = value;
2681 expect (XBM_TK_NUMBER);
2683 *p++ = XBM_BIT_SHUFFLE (val);
2684 if (!padding_p || ((i + 2) % bytes_per_line))
2685 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2687 if (LA1 == ',' || LA1 == '}')
2688 match ();
2689 else
2690 goto failure;
2693 else
2695 for (i = 0; i < nbytes; ++i)
2697 int val = value;
2698 expect (XBM_TK_NUMBER);
2700 *p++ = XBM_BIT_SHUFFLE (val);
2702 if (LA1 == ',' || LA1 == '}')
2703 match ();
2704 else
2705 goto failure;
2709 success:
2710 return 1;
2712 failure:
2714 if (data && *data)
2716 xfree (*data);
2717 *data = NULL;
2719 return 0;
2721 #undef match
2722 #undef expect
2723 #undef expect_ident
2727 /* Load XBM image IMG which will be displayed on frame F from buffer
2728 CONTENTS. END is the end of the buffer. Value is non-zero if
2729 successful. */
2731 static int
2732 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2733 unsigned char *end)
2735 int rc;
2736 char *data;
2737 int success_p = 0;
2739 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2740 &data, 0);
2741 if (rc)
2743 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2744 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2745 int non_default_colors = 0;
2746 Lisp_Object value;
2748 xassert (img->width > 0 && img->height > 0);
2750 /* Get foreground and background colors, maybe allocate colors. */
2751 value = image_spec_value (img->spec, QCforeground, NULL);
2752 if (!NILP (value))
2754 foreground = x_alloc_image_color (f, img, value, foreground);
2755 non_default_colors = 1;
2757 value = image_spec_value (img->spec, QCbackground, NULL);
2758 if (!NILP (value))
2760 background = x_alloc_image_color (f, img, value, background);
2761 img->background = background;
2762 img->background_valid = 1;
2763 non_default_colors = 1;
2766 Create_Pixmap_From_Bitmap_Data (f, img, data,
2767 foreground, background,
2768 non_default_colors);
2769 xfree (data);
2771 if (img->pixmap == NO_PIXMAP)
2773 x_clear_image (f, img);
2774 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2776 else
2777 success_p = 1;
2779 else
2780 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2782 return success_p;
2786 /* Value is non-zero if DATA looks like an in-memory XBM file. */
2788 static int
2789 xbm_file_p (Lisp_Object data)
2791 int w, h;
2792 return (STRINGP (data)
2793 && xbm_read_bitmap_data (NULL, SDATA (data),
2794 (SDATA (data) + SBYTES (data)),
2795 &w, &h, NULL, 1));
2799 /* Fill image IMG which is used on frame F with pixmap data. Value is
2800 non-zero if successful. */
2802 static int
2803 xbm_load (struct frame *f, struct image *img)
2805 int success_p = 0;
2806 Lisp_Object file_name;
2808 xassert (xbm_image_p (img->spec));
2810 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2811 file_name = image_spec_value (img->spec, QCfile, NULL);
2812 if (STRINGP (file_name))
2814 Lisp_Object file;
2815 unsigned char *contents;
2816 int size;
2818 file = x_find_image_file (file_name);
2819 if (!STRINGP (file))
2821 image_error ("Cannot find image file `%s'", file_name, Qnil);
2822 return 0;
2825 contents = slurp_file (SSDATA (file), &size);
2826 if (contents == NULL)
2828 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2829 return 0;
2832 success_p = xbm_load_image (f, img, contents, contents + size);
2834 else
2836 struct image_keyword fmt[XBM_LAST];
2837 Lisp_Object data;
2838 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2839 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2840 int non_default_colors = 0;
2841 char *bits;
2842 int parsed_p;
2843 int in_memory_file_p = 0;
2845 /* See if data looks like an in-memory XBM file. */
2846 data = image_spec_value (img->spec, QCdata, NULL);
2847 in_memory_file_p = xbm_file_p (data);
2849 /* Parse the image specification. */
2850 memcpy (fmt, xbm_format, sizeof fmt);
2851 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2852 (void) parsed_p;
2853 xassert (parsed_p);
2855 /* Get specified width, and height. */
2856 if (!in_memory_file_p)
2858 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2859 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2860 xassert (img->width > 0 && img->height > 0);
2863 /* Get foreground and background colors, maybe allocate colors. */
2864 if (fmt[XBM_FOREGROUND].count
2865 && STRINGP (fmt[XBM_FOREGROUND].value))
2867 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2868 foreground);
2869 non_default_colors = 1;
2872 if (fmt[XBM_BACKGROUND].count
2873 && STRINGP (fmt[XBM_BACKGROUND].value))
2875 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2876 background);
2877 non_default_colors = 1;
2880 if (in_memory_file_p)
2881 success_p = xbm_load_image (f, img, SDATA (data),
2882 (SDATA (data)
2883 + SBYTES (data)));
2884 else
2886 if (VECTORP (data))
2888 int i;
2889 char *p;
2890 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2892 p = bits = (char *) alloca (nbytes * img->height);
2893 for (i = 0; i < img->height; ++i, p += nbytes)
2895 Lisp_Object line = XVECTOR (data)->contents[i];
2896 if (STRINGP (line))
2897 memcpy (p, SDATA (line), nbytes);
2898 else
2899 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
2902 else if (STRINGP (data))
2903 bits = SSDATA (data);
2904 else
2905 bits = (char *) XBOOL_VECTOR (data)->data;
2907 #ifdef WINDOWSNT
2909 char *invertedBits;
2910 int nbytes, i;
2911 /* Windows mono bitmaps are reversed compared with X. */
2912 invertedBits = bits;
2913 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
2914 * img->height;
2915 bits = (char *) alloca (nbytes);
2916 for (i = 0; i < nbytes; i++)
2917 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
2919 #endif
2920 /* Create the pixmap. */
2922 Create_Pixmap_From_Bitmap_Data (f, img, bits,
2923 foreground, background,
2924 non_default_colors);
2925 if (img->pixmap)
2926 success_p = 1;
2927 else
2929 image_error ("Unable to create pixmap for XBM image `%s'",
2930 img->spec, Qnil);
2931 x_clear_image (f, img);
2936 return success_p;
2941 /***********************************************************************
2942 XPM images
2943 ***********************************************************************/
2945 #if defined (HAVE_XPM) || defined (HAVE_NS)
2947 static int xpm_image_p (Lisp_Object object);
2948 static int xpm_load (struct frame *f, struct image *img);
2949 static int xpm_valid_color_symbols_p (Lisp_Object);
2951 #endif /* HAVE_XPM || HAVE_NS */
2953 #ifdef HAVE_XPM
2954 #ifdef HAVE_NTGUI
2955 /* Indicate to xpm.h that we don't have Xlib. */
2956 #define FOR_MSW
2957 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
2958 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
2959 #define XColor xpm_XColor
2960 #define XImage xpm_XImage
2961 #define Display xpm_Display
2962 #define PIXEL_ALREADY_TYPEDEFED
2963 #include "X11/xpm.h"
2964 #undef FOR_MSW
2965 #undef XColor
2966 #undef XImage
2967 #undef Display
2968 #undef PIXEL_ALREADY_TYPEDEFED
2969 #else
2970 #include "X11/xpm.h"
2971 #endif /* HAVE_NTGUI */
2972 #endif /* HAVE_XPM */
2974 #if defined (HAVE_XPM) || defined (HAVE_NS)
2975 /* The symbol `xpm' identifying XPM-format images. */
2977 static Lisp_Object Qxpm;
2979 /* Indices of image specification fields in xpm_format, below. */
2981 enum xpm_keyword_index
2983 XPM_TYPE,
2984 XPM_FILE,
2985 XPM_DATA,
2986 XPM_ASCENT,
2987 XPM_MARGIN,
2988 XPM_RELIEF,
2989 XPM_ALGORITHM,
2990 XPM_HEURISTIC_MASK,
2991 XPM_MASK,
2992 XPM_COLOR_SYMBOLS,
2993 XPM_BACKGROUND,
2994 XPM_LAST
2997 /* Vector of image_keyword structures describing the format
2998 of valid XPM image specifications. */
3000 static const struct image_keyword xpm_format[XPM_LAST] =
3002 {":type", IMAGE_SYMBOL_VALUE, 1},
3003 {":file", IMAGE_STRING_VALUE, 0},
3004 {":data", IMAGE_STRING_VALUE, 0},
3005 {":ascent", IMAGE_ASCENT_VALUE, 0},
3006 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3007 {":relief", IMAGE_INTEGER_VALUE, 0},
3008 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3009 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3010 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3011 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3012 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3015 /* Structure describing the image type XPM. */
3017 static struct image_type xpm_type =
3019 &Qxpm,
3020 xpm_image_p,
3021 xpm_load,
3022 x_clear_image,
3023 NULL
3026 #ifdef HAVE_X_WINDOWS
3028 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3029 functions for allocating image colors. Our own functions handle
3030 color allocation failures more gracefully than the ones on the XPM
3031 lib. */
3033 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3034 #define ALLOC_XPM_COLORS
3035 #endif
3036 #endif /* HAVE_X_WINDOWS */
3038 #ifdef ALLOC_XPM_COLORS
3040 static void xpm_init_color_cache (struct frame *, XpmAttributes *);
3041 static void xpm_free_color_cache (void);
3042 static int xpm_lookup_color (struct frame *, char *, XColor *);
3043 static int xpm_color_bucket (char *);
3044 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3045 XColor *, int);
3047 /* An entry in a hash table used to cache color definitions of named
3048 colors. This cache is necessary to speed up XPM image loading in
3049 case we do color allocations ourselves. Without it, we would need
3050 a call to XParseColor per pixel in the image. */
3052 struct xpm_cached_color
3054 /* Next in collision chain. */
3055 struct xpm_cached_color *next;
3057 /* Color definition (RGB and pixel color). */
3058 XColor color;
3060 /* Color name. */
3061 char name[1];
3064 /* The hash table used for the color cache, and its bucket vector
3065 size. */
3067 #define XPM_COLOR_CACHE_BUCKETS 1001
3068 static struct xpm_cached_color **xpm_color_cache;
3070 /* Initialize the color cache. */
3072 static void
3073 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3075 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3076 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3077 memset (xpm_color_cache, 0, nbytes);
3078 init_color_table ();
3080 if (attrs->valuemask & XpmColorSymbols)
3082 int i;
3083 XColor color;
3085 for (i = 0; i < attrs->numsymbols; ++i)
3086 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3087 attrs->colorsymbols[i].value, &color))
3089 color.pixel = lookup_rgb_color (f, color.red, color.green,
3090 color.blue);
3091 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3096 /* Free the color cache. */
3098 static void
3099 xpm_free_color_cache (void)
3101 struct xpm_cached_color *p, *next;
3102 int i;
3104 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3105 for (p = xpm_color_cache[i]; p; p = next)
3107 next = p->next;
3108 xfree (p);
3111 xfree (xpm_color_cache);
3112 xpm_color_cache = NULL;
3113 free_color_table ();
3116 /* Return the bucket index for color named COLOR_NAME in the color
3117 cache. */
3119 static int
3120 xpm_color_bucket (char *color_name)
3122 unsigned h = 0;
3123 char *s;
3125 for (s = color_name; *s; ++s)
3126 h = (h << 2) ^ *s;
3127 return h %= XPM_COLOR_CACHE_BUCKETS;
3131 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3132 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3133 entry added. */
3135 static struct xpm_cached_color *
3136 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3138 size_t nbytes;
3139 struct xpm_cached_color *p;
3141 if (bucket < 0)
3142 bucket = xpm_color_bucket (color_name);
3144 nbytes = sizeof *p + strlen (color_name);
3145 p = (struct xpm_cached_color *) xmalloc (nbytes);
3146 strcpy (p->name, color_name);
3147 p->color = *color;
3148 p->next = xpm_color_cache[bucket];
3149 xpm_color_cache[bucket] = p;
3150 return p;
3153 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3154 return the cached definition in *COLOR. Otherwise, make a new
3155 entry in the cache and allocate the color. Value is zero if color
3156 allocation failed. */
3158 static int
3159 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3161 struct xpm_cached_color *p;
3162 int h = xpm_color_bucket (color_name);
3164 for (p = xpm_color_cache[h]; p; p = p->next)
3165 if (strcmp (p->name, color_name) == 0)
3166 break;
3168 if (p != NULL)
3169 *color = p->color;
3170 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3171 color_name, color))
3173 color->pixel = lookup_rgb_color (f, color->red, color->green,
3174 color->blue);
3175 p = xpm_cache_color (f, color_name, color, h);
3177 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3178 with transparency, and it's useful. */
3179 else if (strcmp ("opaque", color_name) == 0)
3181 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3182 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3183 p = xpm_cache_color (f, color_name, color, h);
3186 return p != NULL;
3190 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3191 CLOSURE is a pointer to the frame on which we allocate the
3192 color. Return in *COLOR the allocated color. Value is non-zero
3193 if successful. */
3195 static int
3196 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3197 void *closure)
3199 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3203 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3204 is a pointer to the frame on which we allocate the color. Value is
3205 non-zero if successful. */
3207 static int
3208 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3210 return 1;
3213 #endif /* ALLOC_XPM_COLORS */
3216 #ifdef HAVE_NTGUI
3218 /* XPM library details. */
3220 DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
3221 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3222 xpm_XImage **, XpmAttributes *));
3223 DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3224 xpm_XImage **, XpmAttributes *));
3225 DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
3227 static int
3228 init_xpm_functions (Lisp_Object libraries)
3230 HMODULE library;
3232 if (!(library = w32_delayed_load (libraries, Qxpm)))
3233 return 0;
3235 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3236 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3237 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3238 LOAD_IMGLIB_FN (library, XImageFree);
3239 return 1;
3242 #endif /* HAVE_NTGUI */
3245 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3246 for XPM images. Such a list must consist of conses whose car and
3247 cdr are strings. */
3249 static int
3250 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3252 while (CONSP (color_symbols))
3254 Lisp_Object sym = XCAR (color_symbols);
3255 if (!CONSP (sym)
3256 || !STRINGP (XCAR (sym))
3257 || !STRINGP (XCDR (sym)))
3258 break;
3259 color_symbols = XCDR (color_symbols);
3262 return NILP (color_symbols);
3266 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3268 static int
3269 xpm_image_p (Lisp_Object object)
3271 struct image_keyword fmt[XPM_LAST];
3272 memcpy (fmt, xpm_format, sizeof fmt);
3273 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3274 /* Either `:file' or `:data' must be present. */
3275 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3276 /* Either no `:color-symbols' or it's a list of conses
3277 whose car and cdr are strings. */
3278 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3279 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3282 #endif /* HAVE_XPM || HAVE_NS */
3284 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3286 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3288 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3289 int id, rc;
3290 XpmAttributes attrs;
3291 Pixmap bitmap, mask;
3293 memset (&attrs, 0, sizeof attrs);
3295 attrs.visual = FRAME_X_VISUAL (f);
3296 attrs.colormap = FRAME_X_COLORMAP (f);
3297 attrs.valuemask |= XpmVisual;
3298 attrs.valuemask |= XpmColormap;
3300 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3301 (char **) bits, &bitmap, &mask, &attrs);
3302 if (rc != XpmSuccess)
3304 XpmFreeAttributes (&attrs);
3305 return -1;
3308 id = x_allocate_bitmap_record (f);
3309 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3310 dpyinfo->bitmaps[id - 1].have_mask = 1;
3311 dpyinfo->bitmaps[id - 1].mask = mask;
3312 dpyinfo->bitmaps[id - 1].file = NULL;
3313 dpyinfo->bitmaps[id - 1].height = attrs.height;
3314 dpyinfo->bitmaps[id - 1].width = attrs.width;
3315 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3316 dpyinfo->bitmaps[id - 1].refcount = 1;
3318 XpmFreeAttributes (&attrs);
3319 return id;
3321 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3323 /* Load image IMG which will be displayed on frame F. Value is
3324 non-zero if successful. */
3326 #ifdef HAVE_XPM
3328 static int
3329 xpm_load (struct frame *f, struct image *img)
3331 int rc;
3332 XpmAttributes attrs;
3333 Lisp_Object specified_file, color_symbols;
3334 #ifdef HAVE_NTGUI
3335 HDC hdc;
3336 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3337 #endif /* HAVE_NTGUI */
3339 /* Configure the XPM lib. Use the visual of frame F. Allocate
3340 close colors. Return colors allocated. */
3341 memset (&attrs, 0, sizeof attrs);
3343 #ifndef HAVE_NTGUI
3344 attrs.visual = FRAME_X_VISUAL (f);
3345 attrs.colormap = FRAME_X_COLORMAP (f);
3346 attrs.valuemask |= XpmVisual;
3347 attrs.valuemask |= XpmColormap;
3348 #endif /* HAVE_NTGUI */
3350 #ifdef ALLOC_XPM_COLORS
3351 /* Allocate colors with our own functions which handle
3352 failing color allocation more gracefully. */
3353 attrs.color_closure = f;
3354 attrs.alloc_color = xpm_alloc_color;
3355 attrs.free_colors = xpm_free_colors;
3356 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3357 #else /* not ALLOC_XPM_COLORS */
3358 /* Let the XPM lib allocate colors. */
3359 attrs.valuemask |= XpmReturnAllocPixels;
3360 #ifdef XpmAllocCloseColors
3361 attrs.alloc_close_colors = 1;
3362 attrs.valuemask |= XpmAllocCloseColors;
3363 #else /* not XpmAllocCloseColors */
3364 attrs.closeness = 600;
3365 attrs.valuemask |= XpmCloseness;
3366 #endif /* not XpmAllocCloseColors */
3367 #endif /* ALLOC_XPM_COLORS */
3369 /* If image specification contains symbolic color definitions, add
3370 these to `attrs'. */
3371 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3372 if (CONSP (color_symbols))
3374 Lisp_Object tail;
3375 XpmColorSymbol *xpm_syms;
3376 int i, size;
3378 attrs.valuemask |= XpmColorSymbols;
3380 /* Count number of symbols. */
3381 attrs.numsymbols = 0;
3382 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3383 ++attrs.numsymbols;
3385 /* Allocate an XpmColorSymbol array. */
3386 size = attrs.numsymbols * sizeof *xpm_syms;
3387 xpm_syms = (XpmColorSymbol *) alloca (size);
3388 memset (xpm_syms, 0, size);
3389 attrs.colorsymbols = xpm_syms;
3391 /* Fill the color symbol array. */
3392 for (tail = color_symbols, i = 0;
3393 CONSP (tail);
3394 ++i, tail = XCDR (tail))
3396 Lisp_Object name;
3397 Lisp_Object color;
3398 char *empty_string = (char *) "";
3400 if (!CONSP (XCAR (tail)))
3402 xpm_syms[i].name = empty_string;
3403 xpm_syms[i].value = empty_string;
3404 continue;
3406 name = XCAR (XCAR (tail));
3407 color = XCDR (XCAR (tail));
3408 if (STRINGP (name))
3410 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3411 strcpy (xpm_syms[i].name, SSDATA (name));
3413 else
3414 xpm_syms[i].name = empty_string;
3415 if (STRINGP (color))
3417 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3418 strcpy (xpm_syms[i].value, SSDATA (color));
3420 else
3421 xpm_syms[i].value = empty_string;
3425 /* Create a pixmap for the image, either from a file, or from a
3426 string buffer containing data in the same format as an XPM file. */
3427 #ifdef ALLOC_XPM_COLORS
3428 xpm_init_color_cache (f, &attrs);
3429 #endif
3431 specified_file = image_spec_value (img->spec, QCfile, NULL);
3433 #ifdef HAVE_NTGUI
3435 HDC frame_dc = get_frame_dc (f);
3436 hdc = CreateCompatibleDC (frame_dc);
3437 release_frame_dc (f, frame_dc);
3439 #endif /* HAVE_NTGUI */
3441 if (STRINGP (specified_file))
3443 Lisp_Object file = x_find_image_file (specified_file);
3444 if (!STRINGP (file))
3446 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3447 #ifdef ALLOC_XPM_COLORS
3448 xpm_free_color_cache ();
3449 #endif
3450 return 0;
3453 #ifdef HAVE_NTGUI
3454 /* XpmReadFileToPixmap is not available in the Windows port of
3455 libxpm. But XpmReadFileToImage almost does what we want. */
3456 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3457 &xpm_image, &xpm_mask,
3458 &attrs);
3459 #else
3460 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3461 SSDATA (file), &img->pixmap, &img->mask,
3462 &attrs);
3463 #endif /* HAVE_NTGUI */
3465 else
3467 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3468 if (!STRINGP (buffer))
3470 image_error ("Invalid image data `%s'", buffer, Qnil);
3471 #ifdef ALLOC_XPM_COLORS
3472 xpm_free_color_cache ();
3473 #endif
3474 return 0;
3476 #ifdef HAVE_NTGUI
3477 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3478 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3479 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3480 &xpm_image, &xpm_mask,
3481 &attrs);
3482 #else
3483 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3484 SSDATA (buffer),
3485 &img->pixmap, &img->mask,
3486 &attrs);
3487 #endif /* HAVE_NTGUI */
3490 if (rc == XpmSuccess)
3492 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3493 img->colors = colors_in_color_table (&img->ncolors);
3494 #else /* not ALLOC_XPM_COLORS */
3495 int i;
3497 #ifdef HAVE_NTGUI
3498 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3499 plus some duplicate attributes. */
3500 if (xpm_image && xpm_image->bitmap)
3502 img->pixmap = xpm_image->bitmap;
3503 /* XImageFree in libXpm frees XImage struct without destroying
3504 the bitmap, which is what we want. */
3505 fn_XImageFree (xpm_image);
3507 if (xpm_mask && xpm_mask->bitmap)
3509 /* The mask appears to be inverted compared with what we expect.
3510 TODO: invert our expectations. See other places where we
3511 have to invert bits because our idea of masks is backwards. */
3512 HGDIOBJ old_obj;
3513 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3515 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3516 SelectObject (hdc, old_obj);
3518 img->mask = xpm_mask->bitmap;
3519 fn_XImageFree (xpm_mask);
3520 DeleteDC (hdc);
3523 DeleteDC (hdc);
3524 #endif /* HAVE_NTGUI */
3526 /* Remember allocated colors. */
3527 img->ncolors = attrs.nalloc_pixels;
3528 img->colors = (unsigned long *) xmalloc (img->ncolors
3529 * sizeof *img->colors);
3530 for (i = 0; i < attrs.nalloc_pixels; ++i)
3532 img->colors[i] = attrs.alloc_pixels[i];
3533 #ifdef DEBUG_X_COLORS
3534 register_color (img->colors[i]);
3535 #endif
3537 #endif /* not ALLOC_XPM_COLORS */
3539 img->width = attrs.width;
3540 img->height = attrs.height;
3541 xassert (img->width > 0 && img->height > 0);
3543 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3544 #ifdef HAVE_NTGUI
3545 fn_XpmFreeAttributes (&attrs);
3546 #else
3547 XpmFreeAttributes (&attrs);
3548 #endif /* HAVE_NTGUI */
3550 else
3552 #ifdef HAVE_NTGUI
3553 DeleteDC (hdc);
3554 #endif /* HAVE_NTGUI */
3556 switch (rc)
3558 case XpmOpenFailed:
3559 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3560 break;
3562 case XpmFileInvalid:
3563 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3564 break;
3566 case XpmNoMemory:
3567 image_error ("Out of memory (%s)", img->spec, Qnil);
3568 break;
3570 case XpmColorFailed:
3571 image_error ("Color allocation error (%s)", img->spec, Qnil);
3572 break;
3574 default:
3575 image_error ("Unknown error (%s)", img->spec, Qnil);
3576 break;
3580 #ifdef ALLOC_XPM_COLORS
3581 xpm_free_color_cache ();
3582 #endif
3583 return rc == XpmSuccess;
3586 #endif /* HAVE_XPM */
3588 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3590 /* XPM support functions for NS where libxpm is not available.
3591 Only XPM version 3 (without any extensions) is supported. */
3593 static int xpm_scan (const unsigned char **, const unsigned char *,
3594 const unsigned char **, int *);
3595 static Lisp_Object xpm_make_color_table_v
3596 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3597 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3598 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3599 int, Lisp_Object);
3600 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3601 const unsigned char *, int);
3602 static Lisp_Object xpm_make_color_table_h
3603 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3604 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3605 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3606 int, Lisp_Object);
3607 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3608 const unsigned char *, int);
3609 static int xpm_str_to_color_key (const char *);
3610 static int xpm_load_image (struct frame *, struct image *,
3611 const unsigned char *, const unsigned char *);
3613 /* Tokens returned from xpm_scan. */
3615 enum xpm_token
3617 XPM_TK_IDENT = 256,
3618 XPM_TK_STRING,
3619 XPM_TK_EOF
3622 /* Scan an XPM data and return a character (< 256) or a token defined
3623 by enum xpm_token above. *S and END are the start (inclusive) and
3624 the end (exclusive) addresses of the data, respectively. Advance
3625 *S while scanning. If token is either XPM_TK_IDENT or
3626 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3627 length of the corresponding token, respectively. */
3629 static int
3630 xpm_scan (const unsigned char **s,
3631 const unsigned char *end,
3632 const unsigned char **beg,
3633 int *len)
3635 int c;
3637 while (*s < end)
3639 /* Skip white-space. */
3640 while (*s < end && (c = *(*s)++, isspace (c)))
3643 /* gnus-pointer.xpm uses '-' in its identifier.
3644 sb-dir-plus.xpm uses '+' in its identifier. */
3645 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3647 *beg = *s - 1;
3648 while (*s < end
3649 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3650 ++*s;
3651 *len = *s - *beg;
3652 return XPM_TK_IDENT;
3654 else if (c == '"')
3656 *beg = *s;
3657 while (*s < end && **s != '"')
3658 ++*s;
3659 *len = *s - *beg;
3660 if (*s < end)
3661 ++*s;
3662 return XPM_TK_STRING;
3664 else if (c == '/')
3666 if (*s < end && **s == '*')
3668 /* C-style comment. */
3669 ++*s;
3672 while (*s < end && *(*s)++ != '*')
3675 while (*s < end && **s != '/');
3676 if (*s < end)
3677 ++*s;
3679 else
3680 return c;
3682 else
3683 return c;
3686 return XPM_TK_EOF;
3689 /* Functions for color table lookup in XPM data. A key is a string
3690 specifying the color of each pixel in XPM data. A value is either
3691 an integer that specifies a pixel color, Qt that specifies
3692 transparency, or Qnil for the unspecified color. If the length of
3693 the key string is one, a vector is used as a table. Otherwise, a
3694 hash table is used. */
3696 static Lisp_Object
3697 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3698 const unsigned char *,
3699 int,
3700 Lisp_Object),
3701 Lisp_Object (**get_func) (Lisp_Object,
3702 const unsigned char *,
3703 int))
3705 *put_func = xpm_put_color_table_v;
3706 *get_func = xpm_get_color_table_v;
3707 return Fmake_vector (make_number (256), Qnil);
3710 static void
3711 xpm_put_color_table_v (Lisp_Object color_table,
3712 const unsigned char *chars_start,
3713 int chars_len,
3714 Lisp_Object color)
3716 XVECTOR (color_table)->contents[*chars_start] = color;
3719 static Lisp_Object
3720 xpm_get_color_table_v (Lisp_Object color_table,
3721 const unsigned char *chars_start,
3722 int chars_len)
3724 return XVECTOR (color_table)->contents[*chars_start];
3727 static Lisp_Object
3728 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3729 const unsigned char *,
3730 int,
3731 Lisp_Object),
3732 Lisp_Object (**get_func) (Lisp_Object,
3733 const unsigned char *,
3734 int))
3736 *put_func = xpm_put_color_table_h;
3737 *get_func = xpm_get_color_table_h;
3738 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
3739 make_float (DEFAULT_REHASH_SIZE),
3740 make_float (DEFAULT_REHASH_THRESHOLD),
3741 Qnil, Qnil, Qnil);
3744 static void
3745 xpm_put_color_table_h (Lisp_Object color_table,
3746 const unsigned char *chars_start,
3747 int chars_len,
3748 Lisp_Object color)
3750 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3751 unsigned hash_code;
3752 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3754 hash_lookup (table, chars, &hash_code);
3755 hash_put (table, chars, color, hash_code);
3758 static Lisp_Object
3759 xpm_get_color_table_h (Lisp_Object color_table,
3760 const unsigned char *chars_start,
3761 int chars_len)
3763 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3764 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
3765 NULL);
3767 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3770 enum xpm_color_key {
3771 XPM_COLOR_KEY_S,
3772 XPM_COLOR_KEY_M,
3773 XPM_COLOR_KEY_G4,
3774 XPM_COLOR_KEY_G,
3775 XPM_COLOR_KEY_C
3778 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3780 static int
3781 xpm_str_to_color_key (const char *s)
3783 int i;
3785 for (i = 0;
3786 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3787 i++)
3788 if (strcmp (xpm_color_key_strings[i], s) == 0)
3789 return i;
3790 return -1;
3793 static int
3794 xpm_load_image (struct frame *f,
3795 struct image *img,
3796 const unsigned char *contents,
3797 const unsigned char *end)
3799 const unsigned char *s = contents, *beg, *str;
3800 unsigned char buffer[BUFSIZ];
3801 int width, height, x, y;
3802 int num_colors, chars_per_pixel;
3803 int len, LA1;
3804 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3805 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3806 Lisp_Object frame, color_symbols, color_table;
3807 int best_key, have_mask = 0;
3808 XImagePtr ximg = NULL, mask_img = NULL;
3810 #define match() \
3811 LA1 = xpm_scan (&s, end, &beg, &len)
3813 #define expect(TOKEN) \
3814 if (LA1 != (TOKEN)) \
3815 goto failure; \
3816 else \
3817 match ()
3819 #define expect_ident(IDENT) \
3820 if (LA1 == XPM_TK_IDENT \
3821 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3822 match (); \
3823 else \
3824 goto failure
3826 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3827 goto failure;
3828 s += 9;
3829 match ();
3830 expect_ident ("static");
3831 expect_ident ("char");
3832 expect ('*');
3833 expect (XPM_TK_IDENT);
3834 expect ('[');
3835 expect (']');
3836 expect ('=');
3837 expect ('{');
3838 expect (XPM_TK_STRING);
3839 if (len >= BUFSIZ)
3840 goto failure;
3841 memcpy (buffer, beg, len);
3842 buffer[len] = '\0';
3843 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3844 &num_colors, &chars_per_pixel) != 4
3845 || width <= 0 || height <= 0
3846 || num_colors <= 0 || chars_per_pixel <= 0)
3847 goto failure;
3849 if (!check_image_size (f, width, height))
3851 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
3852 goto failure;
3855 expect (',');
3857 XSETFRAME (frame, f);
3858 if (!NILP (Fxw_display_color_p (frame)))
3859 best_key = XPM_COLOR_KEY_C;
3860 else if (!NILP (Fx_display_grayscale_p (frame)))
3861 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
3862 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
3863 else
3864 best_key = XPM_COLOR_KEY_M;
3866 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3867 if (chars_per_pixel == 1)
3868 color_table = xpm_make_color_table_v (&put_color_table,
3869 &get_color_table);
3870 else
3871 color_table = xpm_make_color_table_h (&put_color_table,
3872 &get_color_table);
3874 while (num_colors-- > 0)
3876 char *color, *max_color;
3877 int key, next_key, max_key = 0;
3878 Lisp_Object symbol_color = Qnil, color_val;
3879 XColor cdef;
3881 expect (XPM_TK_STRING);
3882 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
3883 goto failure;
3884 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
3885 buffer[len - chars_per_pixel] = '\0';
3887 str = strtok (buffer, " \t");
3888 if (str == NULL)
3889 goto failure;
3890 key = xpm_str_to_color_key (str);
3891 if (key < 0)
3892 goto failure;
3895 color = strtok (NULL, " \t");
3896 if (color == NULL)
3897 goto failure;
3899 while ((str = strtok (NULL, " \t")) != NULL)
3901 next_key = xpm_str_to_color_key (str);
3902 if (next_key >= 0)
3903 break;
3904 color[strlen (color)] = ' ';
3907 if (key == XPM_COLOR_KEY_S)
3909 if (NILP (symbol_color))
3910 symbol_color = build_string (color);
3912 else if (max_key < key && key <= best_key)
3914 max_key = key;
3915 max_color = color;
3917 key = next_key;
3919 while (str);
3921 color_val = Qnil;
3922 if (!NILP (color_symbols) && !NILP (symbol_color))
3924 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
3926 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
3928 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
3929 color_val = Qt;
3930 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
3931 &cdef, 0))
3932 color_val = make_number (cdef.pixel);
3935 if (NILP (color_val) && max_key > 0)
3937 if (xstrcasecmp (max_color, "None") == 0)
3938 color_val = Qt;
3939 else if (x_defined_color (f, max_color, &cdef, 0))
3940 color_val = make_number (cdef.pixel);
3942 if (!NILP (color_val))
3943 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
3945 expect (',');
3948 if (!x_create_x_image_and_pixmap (f, width, height, 0,
3949 &ximg, &img->pixmap)
3950 #ifndef HAVE_NS
3951 || !x_create_x_image_and_pixmap (f, width, height, 1,
3952 &mask_img, &img->mask)
3953 #endif
3956 image_error ("Out of memory (%s)", img->spec, Qnil);
3957 goto error;
3960 for (y = 0; y < height; y++)
3962 expect (XPM_TK_STRING);
3963 str = beg;
3964 if (len < width * chars_per_pixel)
3965 goto failure;
3966 for (x = 0; x < width; x++, str += chars_per_pixel)
3968 Lisp_Object color_val =
3969 (*get_color_table) (color_table, str, chars_per_pixel);
3971 XPutPixel (ximg, x, y,
3972 (INTEGERP (color_val) ? XINT (color_val)
3973 : FRAME_FOREGROUND_PIXEL (f)));
3974 #ifndef HAVE_NS
3975 XPutPixel (mask_img, x, y,
3976 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
3977 : (have_mask = 1, PIX_MASK_RETAIN)));
3978 #else
3979 if (EQ (color_val, Qt))
3980 ns_set_alpha (ximg, x, y, 0);
3981 #endif
3983 if (y + 1 < height)
3984 expect (',');
3987 img->width = width;
3988 img->height = height;
3990 /* Maybe fill in the background field while we have ximg handy. */
3991 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
3992 IMAGE_BACKGROUND (img, f, ximg);
3994 x_put_x_image (f, ximg, img->pixmap, width, height);
3995 x_destroy_x_image (ximg);
3996 #ifndef HAVE_NS
3997 if (have_mask)
3999 /* Fill in the background_transparent field while we have the
4000 mask handy. */
4001 image_background_transparent (img, f, mask_img);
4003 x_put_x_image (f, mask_img, img->mask, width, height);
4004 x_destroy_x_image (mask_img);
4006 else
4008 x_destroy_x_image (mask_img);
4009 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4010 img->mask = NO_PIXMAP;
4012 #endif
4013 return 1;
4015 failure:
4016 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4017 error:
4018 x_destroy_x_image (ximg);
4019 x_destroy_x_image (mask_img);
4020 x_clear_image (f, img);
4021 return 0;
4023 #undef match
4024 #undef expect
4025 #undef expect_ident
4028 static int
4029 xpm_load (struct frame *f,
4030 struct image *img)
4032 int success_p = 0;
4033 Lisp_Object file_name;
4035 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4036 file_name = image_spec_value (img->spec, QCfile, NULL);
4037 if (STRINGP (file_name))
4039 Lisp_Object file;
4040 unsigned char *contents;
4041 int size;
4043 file = x_find_image_file (file_name);
4044 if (!STRINGP (file))
4046 image_error ("Cannot find image file `%s'", file_name, Qnil);
4047 return 0;
4050 contents = slurp_file (SDATA (file), &size);
4051 if (contents == NULL)
4053 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4054 return 0;
4057 success_p = xpm_load_image (f, img, contents, contents + size);
4058 xfree (contents);
4060 else
4062 Lisp_Object data;
4064 data = image_spec_value (img->spec, QCdata, NULL);
4065 if (!STRINGP (data))
4067 image_error ("Invalid image data `%s'", data, Qnil);
4068 return 0;
4070 success_p = xpm_load_image (f, img, SDATA (data),
4071 SDATA (data) + SBYTES (data));
4074 return success_p;
4077 #endif /* HAVE_NS && !HAVE_XPM */
4081 /***********************************************************************
4082 Color table
4083 ***********************************************************************/
4085 #ifdef COLOR_TABLE_SUPPORT
4087 /* An entry in the color table mapping an RGB color to a pixel color. */
4089 struct ct_color
4091 int r, g, b;
4092 unsigned long pixel;
4094 /* Next in color table collision list. */
4095 struct ct_color *next;
4098 /* The bucket vector size to use. Must be prime. */
4100 #define CT_SIZE 101
4102 /* Value is a hash of the RGB color given by R, G, and B. */
4104 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4106 /* The color hash table. */
4108 static struct ct_color **ct_table;
4110 /* Number of entries in the color table. */
4112 static int ct_colors_allocated;
4114 /* Initialize the color table. */
4116 static void
4117 init_color_table (void)
4119 int size = CT_SIZE * sizeof (*ct_table);
4120 ct_table = (struct ct_color **) xmalloc (size);
4121 memset (ct_table, 0, size);
4122 ct_colors_allocated = 0;
4126 /* Free memory associated with the color table. */
4128 static void
4129 free_color_table (void)
4131 int i;
4132 struct ct_color *p, *next;
4134 for (i = 0; i < CT_SIZE; ++i)
4135 for (p = ct_table[i]; p; p = next)
4137 next = p->next;
4138 xfree (p);
4141 xfree (ct_table);
4142 ct_table = NULL;
4146 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4147 entry for that color already is in the color table, return the
4148 pixel color of that entry. Otherwise, allocate a new color for R,
4149 G, B, and make an entry in the color table. */
4151 static unsigned long
4152 lookup_rgb_color (struct frame *f, int r, int g, int b)
4154 unsigned hash = CT_HASH_RGB (r, g, b);
4155 int i = hash % CT_SIZE;
4156 struct ct_color *p;
4157 Display_Info *dpyinfo;
4159 /* Handle TrueColor visuals specially, which improves performance by
4160 two orders of magnitude. Freeing colors on TrueColor visuals is
4161 a nop, and pixel colors specify RGB values directly. See also
4162 the Xlib spec, chapter 3.1. */
4163 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4164 if (dpyinfo->red_bits > 0)
4166 unsigned long pr, pg, pb;
4168 /* Apply gamma-correction like normal color allocation does. */
4169 if (f->gamma)
4171 XColor color;
4172 color.red = r, color.green = g, color.blue = b;
4173 gamma_correct (f, &color);
4174 r = color.red, g = color.green, b = color.blue;
4177 /* Scale down RGB values to the visual's bits per RGB, and shift
4178 them to the right position in the pixel color. Note that the
4179 original RGB values are 16-bit values, as usual in X. */
4180 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4181 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4182 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4184 /* Assemble the pixel color. */
4185 return pr | pg | pb;
4188 for (p = ct_table[i]; p; p = p->next)
4189 if (p->r == r && p->g == g && p->b == b)
4190 break;
4192 if (p == NULL)
4195 #ifdef HAVE_X_WINDOWS
4196 XColor color;
4197 Colormap cmap;
4198 int rc;
4200 color.red = r;
4201 color.green = g;
4202 color.blue = b;
4204 cmap = FRAME_X_COLORMAP (f);
4205 rc = x_alloc_nearest_color (f, cmap, &color);
4206 if (rc)
4208 ++ct_colors_allocated;
4209 p = (struct ct_color *) xmalloc (sizeof *p);
4210 p->r = r;
4211 p->g = g;
4212 p->b = b;
4213 p->pixel = color.pixel;
4214 p->next = ct_table[i];
4215 ct_table[i] = p;
4217 else
4218 return FRAME_FOREGROUND_PIXEL (f);
4220 #else
4221 COLORREF color;
4222 #ifdef HAVE_NTGUI
4223 color = PALETTERGB (r, g, b);
4224 #else
4225 color = RGB_TO_ULONG (r, g, b);
4226 #endif /* HAVE_NTGUI */
4227 ++ct_colors_allocated;
4228 p = (struct ct_color *) xmalloc (sizeof *p);
4229 p->r = r;
4230 p->g = g;
4231 p->b = b;
4232 p->pixel = color;
4233 p->next = ct_table[i];
4234 ct_table[i] = p;
4235 #endif /* HAVE_X_WINDOWS */
4239 return p->pixel;
4243 /* Look up pixel color PIXEL which is used on frame F in the color
4244 table. If not already present, allocate it. Value is PIXEL. */
4246 static unsigned long
4247 lookup_pixel_color (struct frame *f, unsigned long pixel)
4249 int i = pixel % CT_SIZE;
4250 struct ct_color *p;
4252 for (p = ct_table[i]; p; p = p->next)
4253 if (p->pixel == pixel)
4254 break;
4256 if (p == NULL)
4258 XColor color;
4259 Colormap cmap;
4260 int rc;
4262 #ifdef HAVE_X_WINDOWS
4263 cmap = FRAME_X_COLORMAP (f);
4264 color.pixel = pixel;
4265 x_query_color (f, &color);
4266 rc = x_alloc_nearest_color (f, cmap, &color);
4267 #else
4268 BLOCK_INPUT;
4269 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4270 color.pixel = pixel;
4271 XQueryColor (NULL, cmap, &color);
4272 rc = x_alloc_nearest_color (f, cmap, &color);
4273 UNBLOCK_INPUT;
4274 #endif /* HAVE_X_WINDOWS */
4276 if (rc)
4278 ++ct_colors_allocated;
4280 p = (struct ct_color *) xmalloc (sizeof *p);
4281 p->r = color.red;
4282 p->g = color.green;
4283 p->b = color.blue;
4284 p->pixel = pixel;
4285 p->next = ct_table[i];
4286 ct_table[i] = p;
4288 else
4289 return FRAME_FOREGROUND_PIXEL (f);
4291 return p->pixel;
4295 /* Value is a vector of all pixel colors contained in the color table,
4296 allocated via xmalloc. Set *N to the number of colors. */
4298 static unsigned long *
4299 colors_in_color_table (int *n)
4301 int i, j;
4302 struct ct_color *p;
4303 unsigned long *colors;
4305 if (ct_colors_allocated == 0)
4307 *n = 0;
4308 colors = NULL;
4310 else
4312 colors = (unsigned long *) xmalloc (ct_colors_allocated
4313 * sizeof *colors);
4314 *n = ct_colors_allocated;
4316 for (i = j = 0; i < CT_SIZE; ++i)
4317 for (p = ct_table[i]; p; p = p->next)
4318 colors[j++] = p->pixel;
4321 return colors;
4324 #else /* COLOR_TABLE_SUPPORT */
4326 static unsigned long
4327 lookup_rgb_color (struct frame *f, int r, int g, int b)
4329 unsigned long pixel;
4331 #ifdef HAVE_NTGUI
4332 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4333 #endif /* HAVE_NTGUI */
4335 #ifdef HAVE_NS
4336 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4337 #endif /* HAVE_NS */
4338 return pixel;
4341 static void
4342 init_color_table (void)
4345 #endif /* COLOR_TABLE_SUPPORT */
4348 /***********************************************************************
4349 Algorithms
4350 ***********************************************************************/
4352 static XColor *x_to_xcolors (struct frame *, struct image *, int);
4353 static void x_from_xcolors (struct frame *, struct image *, XColor *);
4354 static void x_detect_edges (struct frame *, struct image *, int[9], int);
4356 #ifdef HAVE_NTGUI
4357 static void XPutPixel (XImagePtr , int, int, COLORREF);
4358 #endif /* HAVE_NTGUI */
4360 /* Edge detection matrices for different edge-detection
4361 strategies. */
4363 static int emboss_matrix[9] = {
4364 /* x - 1 x x + 1 */
4365 2, -1, 0, /* y - 1 */
4366 -1, 0, 1, /* y */
4367 0, 1, -2 /* y + 1 */
4370 static int laplace_matrix[9] = {
4371 /* x - 1 x x + 1 */
4372 1, 0, 0, /* y - 1 */
4373 0, 0, 0, /* y */
4374 0, 0, -1 /* y + 1 */
4377 /* Value is the intensity of the color whose red/green/blue values
4378 are R, G, and B. */
4380 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4383 /* On frame F, return an array of XColor structures describing image
4384 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4385 non-zero means also fill the red/green/blue members of the XColor
4386 structures. Value is a pointer to the array of XColors structures,
4387 allocated with xmalloc; it must be freed by the caller. */
4389 static XColor *
4390 x_to_xcolors (struct frame *f, struct image *img, int rgb_p)
4392 int x, y;
4393 XColor *colors, *p;
4394 XImagePtr_or_DC ximg;
4395 #ifdef HAVE_NTGUI
4396 HDC hdc;
4397 HGDIOBJ prev;
4398 #endif /* HAVE_NTGUI */
4400 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4402 #ifndef HAVE_NTGUI
4403 /* Get the X image IMG->pixmap. */
4404 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4405 0, 0, img->width, img->height, ~0, ZPixmap);
4406 #else
4407 /* Load the image into a memory device context. */
4408 hdc = get_frame_dc (f);
4409 ximg = CreateCompatibleDC (hdc);
4410 release_frame_dc (f, hdc);
4411 prev = SelectObject (ximg, img->pixmap);
4412 #endif /* HAVE_NTGUI */
4414 /* Fill the `pixel' members of the XColor array. I wished there
4415 were an easy and portable way to circumvent XGetPixel. */
4416 p = colors;
4417 for (y = 0; y < img->height; ++y)
4419 XColor *row = p;
4421 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4422 for (x = 0; x < img->width; ++x, ++p)
4423 p->pixel = GET_PIXEL (ximg, x, y);
4424 if (rgb_p)
4425 x_query_colors (f, row, img->width);
4427 #else
4429 for (x = 0; x < img->width; ++x, ++p)
4431 /* W32_TODO: palette support needed here? */
4432 p->pixel = GET_PIXEL (ximg, x, y);
4433 if (rgb_p)
4435 p->red = RED16_FROM_ULONG (p->pixel);
4436 p->green = GREEN16_FROM_ULONG (p->pixel);
4437 p->blue = BLUE16_FROM_ULONG (p->pixel);
4440 #endif /* HAVE_X_WINDOWS */
4443 Destroy_Image (ximg, prev);
4445 return colors;
4448 #ifdef HAVE_NTGUI
4450 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4451 created with CreateDIBSection, with the pointer to the bit values
4452 stored in ximg->data. */
4454 static void
4455 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4457 int width = ximg->info.bmiHeader.biWidth;
4458 unsigned char * pixel;
4460 /* True color images. */
4461 if (ximg->info.bmiHeader.biBitCount == 24)
4463 int rowbytes = width * 3;
4464 /* Ensure scanlines are aligned on 4 byte boundaries. */
4465 if (rowbytes % 4)
4466 rowbytes += 4 - (rowbytes % 4);
4468 pixel = ximg->data + y * rowbytes + x * 3;
4469 /* Windows bitmaps are in BGR order. */
4470 *pixel = GetBValue (color);
4471 *(pixel + 1) = GetGValue (color);
4472 *(pixel + 2) = GetRValue (color);
4474 /* Monochrome images. */
4475 else if (ximg->info.bmiHeader.biBitCount == 1)
4477 int rowbytes = width / 8;
4478 /* Ensure scanlines are aligned on 4 byte boundaries. */
4479 if (rowbytes % 4)
4480 rowbytes += 4 - (rowbytes % 4);
4481 pixel = ximg->data + y * rowbytes + x / 8;
4482 /* Filter out palette info. */
4483 if (color & 0x00ffffff)
4484 *pixel = *pixel | (1 << x % 8);
4485 else
4486 *pixel = *pixel & ~(1 << x % 8);
4488 else
4489 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4492 #endif /* HAVE_NTGUI */
4494 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4495 RGB members are set. F is the frame on which this all happens.
4496 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4498 static void
4499 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4501 int x, y;
4502 XImagePtr oimg = NULL;
4503 Pixmap pixmap;
4504 XColor *p;
4506 init_color_table ();
4508 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4509 &oimg, &pixmap);
4510 p = colors;
4511 for (y = 0; y < img->height; ++y)
4512 for (x = 0; x < img->width; ++x, ++p)
4514 unsigned long pixel;
4515 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4516 XPutPixel (oimg, x, y, pixel);
4519 xfree (colors);
4520 x_clear_image_1 (f, img, 1, 0, 1);
4522 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4523 x_destroy_x_image (oimg);
4524 img->pixmap = pixmap;
4525 #ifdef COLOR_TABLE_SUPPORT
4526 img->colors = colors_in_color_table (&img->ncolors);
4527 free_color_table ();
4528 #endif /* COLOR_TABLE_SUPPORT */
4532 /* On frame F, perform edge-detection on image IMG.
4534 MATRIX is a nine-element array specifying the transformation
4535 matrix. See emboss_matrix for an example.
4537 COLOR_ADJUST is a color adjustment added to each pixel of the
4538 outgoing image. */
4540 static void
4541 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4543 XColor *colors = x_to_xcolors (f, img, 1);
4544 XColor *new, *p;
4545 int x, y, i, sum;
4547 for (i = sum = 0; i < 9; ++i)
4548 sum += eabs (matrix[i]);
4550 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4552 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4554 for (y = 0; y < img->height; ++y)
4556 p = COLOR (new, 0, y);
4557 p->red = p->green = p->blue = 0xffff/2;
4558 p = COLOR (new, img->width - 1, y);
4559 p->red = p->green = p->blue = 0xffff/2;
4562 for (x = 1; x < img->width - 1; ++x)
4564 p = COLOR (new, x, 0);
4565 p->red = p->green = p->blue = 0xffff/2;
4566 p = COLOR (new, x, img->height - 1);
4567 p->red = p->green = p->blue = 0xffff/2;
4570 for (y = 1; y < img->height - 1; ++y)
4572 p = COLOR (new, 1, y);
4574 for (x = 1; x < img->width - 1; ++x, ++p)
4576 int r, g, b, yy, xx;
4578 r = g = b = i = 0;
4579 for (yy = y - 1; yy < y + 2; ++yy)
4580 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4581 if (matrix[i])
4583 XColor *t = COLOR (colors, xx, yy);
4584 r += matrix[i] * t->red;
4585 g += matrix[i] * t->green;
4586 b += matrix[i] * t->blue;
4589 r = (r / sum + color_adjust) & 0xffff;
4590 g = (g / sum + color_adjust) & 0xffff;
4591 b = (b / sum + color_adjust) & 0xffff;
4592 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4596 xfree (colors);
4597 x_from_xcolors (f, img, new);
4599 #undef COLOR
4603 /* Perform the pre-defined `emboss' edge-detection on image IMG
4604 on frame F. */
4606 static void
4607 x_emboss (struct frame *f, struct image *img)
4609 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4613 /* Transform image IMG which is used on frame F with a Laplace
4614 edge-detection algorithm. The result is an image that can be used
4615 to draw disabled buttons, for example. */
4617 static void
4618 x_laplace (struct frame *f, struct image *img)
4620 x_detect_edges (f, img, laplace_matrix, 45000);
4624 /* Perform edge-detection on image IMG on frame F, with specified
4625 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4627 MATRIX must be either
4629 - a list of at least 9 numbers in row-major form
4630 - a vector of at least 9 numbers
4632 COLOR_ADJUST nil means use a default; otherwise it must be a
4633 number. */
4635 static void
4636 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4637 Lisp_Object color_adjust)
4639 int i = 0;
4640 int trans[9];
4642 if (CONSP (matrix))
4644 for (i = 0;
4645 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4646 ++i, matrix = XCDR (matrix))
4647 trans[i] = XFLOATINT (XCAR (matrix));
4649 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4651 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4652 trans[i] = XFLOATINT (AREF (matrix, i));
4655 if (NILP (color_adjust))
4656 color_adjust = make_number (0xffff / 2);
4658 if (i == 9 && NUMBERP (color_adjust))
4659 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4663 /* Transform image IMG on frame F so that it looks disabled. */
4665 static void
4666 x_disable_image (struct frame *f, struct image *img)
4668 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4669 #ifdef HAVE_NTGUI
4670 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4671 #else
4672 int n_planes = dpyinfo->n_planes;
4673 #endif /* HAVE_NTGUI */
4675 if (n_planes >= 2)
4677 /* Color (or grayscale). Convert to gray, and equalize. Just
4678 drawing such images with a stipple can look very odd, so
4679 we're using this method instead. */
4680 XColor *colors = x_to_xcolors (f, img, 1);
4681 XColor *p, *end;
4682 const int h = 15000;
4683 const int l = 30000;
4685 for (p = colors, end = colors + img->width * img->height;
4686 p < end;
4687 ++p)
4689 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4690 int i2 = (0xffff - h - l) * i / 0xffff + l;
4691 p->red = p->green = p->blue = i2;
4694 x_from_xcolors (f, img, colors);
4697 /* Draw a cross over the disabled image, if we must or if we
4698 should. */
4699 if (n_planes < 2 || cross_disabled_images)
4701 #ifndef HAVE_NTGUI
4702 Display *dpy = FRAME_X_DISPLAY (f);
4703 GC gc;
4705 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4707 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4709 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4710 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4711 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4712 img->width - 1, img->height - 1);
4713 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4714 img->width - 1, 0);
4715 XFreeGC (dpy, gc);
4717 if (img->mask)
4719 gc = XCreateGC (dpy, img->mask, 0, NULL);
4720 XSetForeground (dpy, gc, MaskForeground (f));
4721 XDrawLine (dpy, img->mask, gc, 0, 0,
4722 img->width - 1, img->height - 1);
4723 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4724 img->width - 1, 0);
4725 XFreeGC (dpy, gc);
4727 #endif /* !HAVE_NS */
4728 #else
4729 HDC hdc, bmpdc;
4730 HGDIOBJ prev;
4732 hdc = get_frame_dc (f);
4733 bmpdc = CreateCompatibleDC (hdc);
4734 release_frame_dc (f, hdc);
4736 prev = SelectObject (bmpdc, img->pixmap);
4738 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4739 MoveToEx (bmpdc, 0, 0, NULL);
4740 LineTo (bmpdc, img->width - 1, img->height - 1);
4741 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4742 LineTo (bmpdc, img->width - 1, 0);
4744 if (img->mask)
4746 SelectObject (bmpdc, img->mask);
4747 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4748 MoveToEx (bmpdc, 0, 0, NULL);
4749 LineTo (bmpdc, img->width - 1, img->height - 1);
4750 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4751 LineTo (bmpdc, img->width - 1, 0);
4753 SelectObject (bmpdc, prev);
4754 DeleteDC (bmpdc);
4755 #endif /* HAVE_NTGUI */
4760 /* Build a mask for image IMG which is used on frame F. FILE is the
4761 name of an image file, for error messages. HOW determines how to
4762 determine the background color of IMG. If it is a list '(R G B)',
4763 with R, G, and B being integers >= 0, take that as the color of the
4764 background. Otherwise, determine the background color of IMG
4765 heuristically. Value is non-zero if successful. */
4767 static int
4768 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4770 XImagePtr_or_DC ximg;
4771 #ifndef HAVE_NTGUI
4772 XImagePtr mask_img;
4773 #else
4774 HDC frame_dc;
4775 HGDIOBJ prev;
4776 char *mask_img;
4777 int row_width;
4778 #endif /* HAVE_NTGUI */
4779 int x, y, rc, use_img_background;
4780 unsigned long bg = 0;
4782 if (img->mask)
4784 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4785 img->mask = NO_PIXMAP;
4786 img->background_transparent_valid = 0;
4789 #ifndef HAVE_NTGUI
4790 #ifndef HAVE_NS
4791 /* Create an image and pixmap serving as mask. */
4792 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4793 &mask_img, &img->mask);
4794 if (!rc)
4795 return 0;
4796 #endif /* !HAVE_NS */
4798 /* Get the X image of IMG->pixmap. */
4799 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4800 img->width, img->height,
4801 ~0, ZPixmap);
4802 #else
4803 /* Create the bit array serving as mask. */
4804 row_width = (img->width + 7) / 8;
4805 mask_img = xmalloc (row_width * img->height);
4806 memset (mask_img, 0, row_width * img->height);
4808 /* Create a memory device context for IMG->pixmap. */
4809 frame_dc = get_frame_dc (f);
4810 ximg = CreateCompatibleDC (frame_dc);
4811 release_frame_dc (f, frame_dc);
4812 prev = SelectObject (ximg, img->pixmap);
4813 #endif /* HAVE_NTGUI */
4815 /* Determine the background color of ximg. If HOW is `(R G B)'
4816 take that as color. Otherwise, use the image's background color. */
4817 use_img_background = 1;
4819 if (CONSP (how))
4821 int rgb[3], i;
4823 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4825 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4826 how = XCDR (how);
4829 if (i == 3 && NILP (how))
4831 char color_name[30];
4832 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4833 bg = (
4834 #ifdef HAVE_NTGUI
4835 0x00ffffff & /* Filter out palette info. */
4836 #endif /* HAVE_NTGUI */
4837 x_alloc_image_color (f, img, build_string (color_name), 0));
4838 use_img_background = 0;
4842 if (use_img_background)
4843 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4845 /* Set all bits in mask_img to 1 whose color in ximg is different
4846 from the background color bg. */
4847 #ifndef HAVE_NTGUI
4848 for (y = 0; y < img->height; ++y)
4849 for (x = 0; x < img->width; ++x)
4850 #ifndef HAVE_NS
4851 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4852 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4853 #else
4854 if (XGetPixel (ximg, x, y) == bg)
4855 ns_set_alpha (ximg, x, y, 0);
4856 #endif /* HAVE_NS */
4857 #ifndef HAVE_NS
4858 /* Fill in the background_transparent field while we have the mask handy. */
4859 image_background_transparent (img, f, mask_img);
4861 /* Put mask_img into img->mask. */
4862 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4863 x_destroy_x_image (mask_img);
4864 #endif /* !HAVE_NS */
4865 #else
4866 for (y = 0; y < img->height; ++y)
4867 for (x = 0; x < img->width; ++x)
4869 COLORREF p = GetPixel (ximg, x, y);
4870 if (p != bg)
4871 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4874 /* Create the mask image. */
4875 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4876 mask_img);
4877 /* Fill in the background_transparent field while we have the mask handy. */
4878 SelectObject (ximg, img->mask);
4879 image_background_transparent (img, f, ximg);
4881 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4882 xfree (mask_img);
4883 #endif /* HAVE_NTGUI */
4885 Destroy_Image (ximg, prev);
4887 return 1;
4891 /***********************************************************************
4892 PBM (mono, gray, color)
4893 ***********************************************************************/
4895 static int pbm_image_p (Lisp_Object object);
4896 static int pbm_load (struct frame *f, struct image *img);
4897 static int pbm_scan_number (unsigned char **, unsigned char *);
4899 /* The symbol `pbm' identifying images of this type. */
4901 static Lisp_Object Qpbm;
4903 /* Indices of image specification fields in gs_format, below. */
4905 enum pbm_keyword_index
4907 PBM_TYPE,
4908 PBM_FILE,
4909 PBM_DATA,
4910 PBM_ASCENT,
4911 PBM_MARGIN,
4912 PBM_RELIEF,
4913 PBM_ALGORITHM,
4914 PBM_HEURISTIC_MASK,
4915 PBM_MASK,
4916 PBM_FOREGROUND,
4917 PBM_BACKGROUND,
4918 PBM_LAST
4921 /* Vector of image_keyword structures describing the format
4922 of valid user-defined image specifications. */
4924 static const struct image_keyword pbm_format[PBM_LAST] =
4926 {":type", IMAGE_SYMBOL_VALUE, 1},
4927 {":file", IMAGE_STRING_VALUE, 0},
4928 {":data", IMAGE_STRING_VALUE, 0},
4929 {":ascent", IMAGE_ASCENT_VALUE, 0},
4930 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
4931 {":relief", IMAGE_INTEGER_VALUE, 0},
4932 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4933 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4934 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4935 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4936 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4939 /* Structure describing the image type `pbm'. */
4941 static struct image_type pbm_type =
4943 &Qpbm,
4944 pbm_image_p,
4945 pbm_load,
4946 x_clear_image,
4947 NULL
4951 /* Return non-zero if OBJECT is a valid PBM image specification. */
4953 static int
4954 pbm_image_p (Lisp_Object object)
4956 struct image_keyword fmt[PBM_LAST];
4958 memcpy (fmt, pbm_format, sizeof fmt);
4960 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
4961 return 0;
4963 /* Must specify either :data or :file. */
4964 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
4968 /* Scan a decimal number from *S and return it. Advance *S while
4969 reading the number. END is the end of the string. Value is -1 at
4970 end of input. */
4972 static int
4973 pbm_scan_number (unsigned char **s, unsigned char *end)
4975 int c = 0, val = -1;
4977 while (*s < end)
4979 /* Skip white-space. */
4980 while (*s < end && (c = *(*s)++, isspace (c)))
4983 if (c == '#')
4985 /* Skip comment to end of line. */
4986 while (*s < end && (c = *(*s)++, c != '\n'))
4989 else if (isdigit (c))
4991 /* Read decimal number. */
4992 val = c - '0';
4993 while (*s < end && (c = *(*s)++, isdigit (c)))
4994 val = 10 * val + c - '0';
4995 break;
4997 else
4998 break;
5001 return val;
5005 #ifdef HAVE_NTGUI
5006 #if 0 /* Unused. ++kfs */
5008 /* Read FILE into memory. Value is a pointer to a buffer allocated
5009 with xmalloc holding FILE's contents. Value is null if an error
5010 occurred. *SIZE is set to the size of the file. */
5012 static char *
5013 pbm_read_file (file, size)
5014 Lisp_Object file;
5015 int *size;
5017 FILE *fp = NULL;
5018 char *buf = NULL;
5019 struct stat st;
5021 if (stat (SDATA (file), &st) == 0
5022 && (fp = fopen (SDATA (file), "rb")) != NULL
5023 && (buf = (char *) xmalloc (st.st_size),
5024 fread (buf, 1, st.st_size, fp) == st.st_size))
5026 *size = st.st_size;
5027 fclose (fp);
5029 else
5031 if (fp)
5032 fclose (fp);
5033 if (buf)
5035 xfree (buf);
5036 buf = NULL;
5040 return buf;
5042 #endif
5043 #endif /* HAVE_NTGUI */
5045 /* Load PBM image IMG for use on frame F. */
5047 static int
5048 pbm_load (struct frame *f, struct image *img)
5050 int raw_p, x, y;
5051 int width, height, max_color_idx = 0;
5052 XImagePtr ximg;
5053 Lisp_Object file, specified_file;
5054 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5055 unsigned char *contents = NULL;
5056 unsigned char *end, *p;
5057 int size;
5059 specified_file = image_spec_value (img->spec, QCfile, NULL);
5061 if (STRINGP (specified_file))
5063 file = x_find_image_file (specified_file);
5064 if (!STRINGP (file))
5066 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5067 return 0;
5070 contents = slurp_file (SSDATA (file), &size);
5071 if (contents == NULL)
5073 image_error ("Error reading `%s'", file, Qnil);
5074 return 0;
5077 p = contents;
5078 end = contents + size;
5080 else
5082 Lisp_Object data;
5083 data = image_spec_value (img->spec, QCdata, NULL);
5084 if (!STRINGP (data))
5086 image_error ("Invalid image data `%s'", data, Qnil);
5087 return 0;
5089 p = SDATA (data);
5090 end = p + SBYTES (data);
5093 /* Check magic number. */
5094 if (end - p < 2 || *p++ != 'P')
5096 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5097 error:
5098 xfree (contents);
5099 return 0;
5102 switch (*p++)
5104 case '1':
5105 raw_p = 0, type = PBM_MONO;
5106 break;
5108 case '2':
5109 raw_p = 0, type = PBM_GRAY;
5110 break;
5112 case '3':
5113 raw_p = 0, type = PBM_COLOR;
5114 break;
5116 case '4':
5117 raw_p = 1, type = PBM_MONO;
5118 break;
5120 case '5':
5121 raw_p = 1, type = PBM_GRAY;
5122 break;
5124 case '6':
5125 raw_p = 1, type = PBM_COLOR;
5126 break;
5128 default:
5129 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5130 goto error;
5133 /* Read width, height, maximum color-component. Characters
5134 starting with `#' up to the end of a line are ignored. */
5135 width = pbm_scan_number (&p, end);
5136 height = pbm_scan_number (&p, end);
5138 if (type != PBM_MONO)
5140 max_color_idx = pbm_scan_number (&p, end);
5141 if (max_color_idx > 65535 || max_color_idx < 0)
5143 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5144 goto error;
5148 if (!check_image_size (f, width, height))
5150 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5151 goto error;
5154 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5155 &ximg, &img->pixmap))
5156 goto error;
5158 /* Initialize the color hash table. */
5159 init_color_table ();
5161 if (type == PBM_MONO)
5163 int c = 0, g;
5164 struct image_keyword fmt[PBM_LAST];
5165 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5166 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5168 /* Parse the image specification. */
5169 memcpy (fmt, pbm_format, sizeof fmt);
5170 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5172 /* Get foreground and background colors, maybe allocate colors. */
5173 if (fmt[PBM_FOREGROUND].count
5174 && STRINGP (fmt[PBM_FOREGROUND].value))
5175 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5176 if (fmt[PBM_BACKGROUND].count
5177 && STRINGP (fmt[PBM_BACKGROUND].value))
5179 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5180 img->background = bg;
5181 img->background_valid = 1;
5184 for (y = 0; y < height; ++y)
5185 for (x = 0; x < width; ++x)
5187 if (raw_p)
5189 if ((x & 7) == 0)
5191 if (p >= end)
5193 x_destroy_x_image (ximg);
5194 x_clear_image (f, img);
5195 image_error ("Invalid image size in image `%s'",
5196 img->spec, Qnil);
5197 goto error;
5199 c = *p++;
5201 g = c & 0x80;
5202 c <<= 1;
5204 else
5205 g = pbm_scan_number (&p, end);
5207 XPutPixel (ximg, x, y, g ? fg : bg);
5210 else
5212 int expected_size = height * width;
5213 if (max_color_idx > 255)
5214 expected_size *= 2;
5215 if (type == PBM_COLOR)
5216 expected_size *= 3;
5218 if (raw_p && p + expected_size > end)
5220 x_destroy_x_image (ximg);
5221 x_clear_image (f, img);
5222 image_error ("Invalid image size in image `%s'",
5223 img->spec, Qnil);
5224 goto error;
5227 for (y = 0; y < height; ++y)
5228 for (x = 0; x < width; ++x)
5230 int r, g, b;
5232 if (type == PBM_GRAY && raw_p)
5234 r = g = b = *p++;
5235 if (max_color_idx > 255)
5236 r = g = b = r * 256 + *p++;
5238 else if (type == PBM_GRAY)
5239 r = g = b = pbm_scan_number (&p, end);
5240 else if (raw_p)
5242 r = *p++;
5243 if (max_color_idx > 255)
5244 r = r * 256 + *p++;
5245 g = *p++;
5246 if (max_color_idx > 255)
5247 g = g * 256 + *p++;
5248 b = *p++;
5249 if (max_color_idx > 255)
5250 b = b * 256 + *p++;
5252 else
5254 r = pbm_scan_number (&p, end);
5255 g = pbm_scan_number (&p, end);
5256 b = pbm_scan_number (&p, end);
5259 if (r < 0 || g < 0 || b < 0)
5261 x_destroy_x_image (ximg);
5262 image_error ("Invalid pixel value in image `%s'",
5263 img->spec, Qnil);
5264 goto error;
5267 /* RGB values are now in the range 0..max_color_idx.
5268 Scale this to the range 0..0xffff supported by X. */
5269 r = (double) r * 65535 / max_color_idx;
5270 g = (double) g * 65535 / max_color_idx;
5271 b = (double) b * 65535 / max_color_idx;
5272 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5276 #ifdef COLOR_TABLE_SUPPORT
5277 /* Store in IMG->colors the colors allocated for the image, and
5278 free the color table. */
5279 img->colors = colors_in_color_table (&img->ncolors);
5280 free_color_table ();
5281 #endif /* COLOR_TABLE_SUPPORT */
5283 img->width = width;
5284 img->height = height;
5286 /* Maybe fill in the background field while we have ximg handy. */
5288 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5289 /* Casting avoids a GCC warning. */
5290 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5292 /* Put the image into a pixmap. */
5293 x_put_x_image (f, ximg, img->pixmap, width, height);
5294 x_destroy_x_image (ximg);
5296 /* X and W32 versions did it here, MAC version above. ++kfs
5297 img->width = width;
5298 img->height = height; */
5300 xfree (contents);
5301 return 1;
5305 /***********************************************************************
5307 ***********************************************************************/
5309 #if defined (HAVE_PNG) || defined (HAVE_NS)
5311 /* Function prototypes. */
5313 static int png_image_p (Lisp_Object object);
5314 static int png_load (struct frame *f, struct image *img);
5316 /* The symbol `png' identifying images of this type. */
5318 static Lisp_Object Qpng;
5320 /* Indices of image specification fields in png_format, below. */
5322 enum png_keyword_index
5324 PNG_TYPE,
5325 PNG_DATA,
5326 PNG_FILE,
5327 PNG_ASCENT,
5328 PNG_MARGIN,
5329 PNG_RELIEF,
5330 PNG_ALGORITHM,
5331 PNG_HEURISTIC_MASK,
5332 PNG_MASK,
5333 PNG_BACKGROUND,
5334 PNG_LAST
5337 /* Vector of image_keyword structures describing the format
5338 of valid user-defined image specifications. */
5340 static const struct image_keyword png_format[PNG_LAST] =
5342 {":type", IMAGE_SYMBOL_VALUE, 1},
5343 {":data", IMAGE_STRING_VALUE, 0},
5344 {":file", IMAGE_STRING_VALUE, 0},
5345 {":ascent", IMAGE_ASCENT_VALUE, 0},
5346 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5347 {":relief", IMAGE_INTEGER_VALUE, 0},
5348 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5349 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5350 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5351 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5354 /* Structure describing the image type `png'. */
5356 static struct image_type png_type =
5358 &Qpng,
5359 png_image_p,
5360 png_load,
5361 x_clear_image,
5362 NULL
5365 /* Return non-zero if OBJECT is a valid PNG image specification. */
5367 static int
5368 png_image_p (Lisp_Object object)
5370 struct image_keyword fmt[PNG_LAST];
5371 memcpy (fmt, png_format, sizeof fmt);
5373 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5374 return 0;
5376 /* Must specify either the :data or :file keyword. */
5377 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5380 #endif /* HAVE_PNG || HAVE_NS */
5383 #ifdef HAVE_PNG
5385 #ifdef HAVE_NTGUI
5386 /* PNG library details. */
5388 DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5389 DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5390 DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5391 png_error_ptr, png_error_ptr));
5392 DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5393 DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5394 DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5395 DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5396 DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5397 DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
5398 png_uint_32 *, png_uint_32 *,
5399 int *, int *, int *, int *, int *));
5400 DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5401 DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5402 DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5403 DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5404 DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
5405 int, int, double));
5406 DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5407 DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5408 DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5409 DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5410 DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5411 DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5412 DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
5414 #if (PNG_LIBPNG_VER >= 10500)
5415 DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int));
5416 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
5417 #endif /* libpng version >= 1.5 */
5419 static int
5420 init_png_functions (Lisp_Object libraries)
5422 HMODULE library;
5424 if (!(library = w32_delayed_load (libraries, Qpng)))
5425 return 0;
5427 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5428 LOAD_IMGLIB_FN (library, png_sig_cmp);
5429 LOAD_IMGLIB_FN (library, png_create_read_struct);
5430 LOAD_IMGLIB_FN (library, png_create_info_struct);
5431 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5432 LOAD_IMGLIB_FN (library, png_set_read_fn);
5433 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5434 LOAD_IMGLIB_FN (library, png_read_info);
5435 LOAD_IMGLIB_FN (library, png_get_IHDR);
5436 LOAD_IMGLIB_FN (library, png_get_valid);
5437 LOAD_IMGLIB_FN (library, png_set_strip_16);
5438 LOAD_IMGLIB_FN (library, png_set_expand);
5439 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5440 LOAD_IMGLIB_FN (library, png_set_background);
5441 LOAD_IMGLIB_FN (library, png_get_bKGD);
5442 LOAD_IMGLIB_FN (library, png_read_update_info);
5443 LOAD_IMGLIB_FN (library, png_get_channels);
5444 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5445 LOAD_IMGLIB_FN (library, png_read_image);
5446 LOAD_IMGLIB_FN (library, png_read_end);
5447 LOAD_IMGLIB_FN (library, png_error);
5449 #if (PNG_LIBPNG_VER >= 10500)
5450 LOAD_IMGLIB_FN (library, png_longjmp);
5451 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5452 #endif /* libpng version >= 1.5 */
5454 return 1;
5456 #else
5458 #define fn_png_get_io_ptr png_get_io_ptr
5459 #define fn_png_sig_cmp png_sig_cmp
5460 #define fn_png_create_read_struct png_create_read_struct
5461 #define fn_png_create_info_struct png_create_info_struct
5462 #define fn_png_destroy_read_struct png_destroy_read_struct
5463 #define fn_png_set_read_fn png_set_read_fn
5464 #define fn_png_set_sig_bytes png_set_sig_bytes
5465 #define fn_png_read_info png_read_info
5466 #define fn_png_get_IHDR png_get_IHDR
5467 #define fn_png_get_valid png_get_valid
5468 #define fn_png_set_strip_16 png_set_strip_16
5469 #define fn_png_set_expand png_set_expand
5470 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5471 #define fn_png_set_background png_set_background
5472 #define fn_png_get_bKGD png_get_bKGD
5473 #define fn_png_read_update_info png_read_update_info
5474 #define fn_png_get_channels png_get_channels
5475 #define fn_png_get_rowbytes png_get_rowbytes
5476 #define fn_png_read_image png_read_image
5477 #define fn_png_read_end png_read_end
5478 #define fn_png_error png_error
5480 #if (PNG_LIBPNG_VER >= 10500)
5481 #define fn_png_longjmp png_longjmp
5482 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5483 #endif /* libpng version >= 1.5 */
5485 #endif /* HAVE_NTGUI */
5488 #if (PNG_LIBPNG_VER < 10500)
5489 #define PNG_LONGJMP(ptr) (longjmp ((ptr)->jmpbuf, 1))
5490 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5491 #else
5492 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5493 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5494 #define PNG_JMPBUF(ptr) \
5495 (*fn_png_set_longjmp_fn((ptr), longjmp, sizeof (jmp_buf)))
5496 #endif
5498 /* Error and warning handlers installed when the PNG library
5499 is initialized. */
5501 static void my_png_error (png_struct *, const char *) NO_RETURN;
5502 static void
5503 my_png_error (png_struct *png_ptr, const char *msg)
5505 xassert (png_ptr != NULL);
5506 /* Avoid compiler warning about deprecated direct access to
5507 png_ptr's fields in libpng versions 1.4.x. */
5508 image_error ("PNG error: %s", build_string (msg), Qnil);
5509 PNG_LONGJMP (png_ptr);
5513 static void
5514 my_png_warning (png_struct *png_ptr, const char *msg)
5516 xassert (png_ptr != NULL);
5517 image_error ("PNG warning: %s", build_string (msg), Qnil);
5520 /* Memory source for PNG decoding. */
5522 struct png_memory_storage
5524 unsigned char *bytes; /* The data */
5525 size_t len; /* How big is it? */
5526 int index; /* Where are we? */
5530 /* Function set as reader function when reading PNG image from memory.
5531 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5532 bytes from the input to DATA. */
5534 static void
5535 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5537 struct png_memory_storage *tbr
5538 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5540 if (length > tbr->len - tbr->index)
5541 fn_png_error (png_ptr, "Read error");
5543 memcpy (data, tbr->bytes + tbr->index, length);
5544 tbr->index = tbr->index + length;
5548 /* Function set as reader function when reading PNG image from a file.
5549 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5550 bytes from the input to DATA. */
5552 static void
5553 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5555 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5557 if (fread (data, 1, length, fp) < length)
5558 fn_png_error (png_ptr, "Read error");
5562 /* Load PNG image IMG for use on frame F. Value is non-zero if
5563 successful. */
5565 static int
5566 png_load (struct frame *f, struct image *img)
5568 Lisp_Object file, specified_file;
5569 Lisp_Object specified_data;
5570 int x, y, i;
5571 XImagePtr ximg, mask_img = NULL;
5572 png_struct *png_ptr = NULL;
5573 png_info *info_ptr = NULL, *end_info = NULL;
5574 FILE *volatile fp = NULL;
5575 png_byte sig[8];
5576 png_byte * volatile pixels = NULL;
5577 png_byte ** volatile rows = NULL;
5578 png_uint_32 width, height;
5579 int bit_depth, color_type, interlace_type;
5580 png_byte channels;
5581 png_uint_32 row_bytes;
5582 int transparent_p;
5583 struct png_memory_storage tbr; /* Data to be read */
5585 /* Find out what file to load. */
5586 specified_file = image_spec_value (img->spec, QCfile, NULL);
5587 specified_data = image_spec_value (img->spec, QCdata, NULL);
5589 if (NILP (specified_data))
5591 file = x_find_image_file (specified_file);
5592 if (!STRINGP (file))
5594 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5595 return 0;
5598 /* Open the image file. */
5599 fp = fopen (SSDATA (file), "rb");
5600 if (!fp)
5602 image_error ("Cannot open image file `%s'", file, Qnil);
5603 return 0;
5606 /* Check PNG signature. */
5607 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5608 || fn_png_sig_cmp (sig, 0, sizeof sig))
5610 image_error ("Not a PNG file: `%s'", file, Qnil);
5611 fclose (fp);
5612 return 0;
5615 else
5617 if (!STRINGP (specified_data))
5619 image_error ("Invalid image data `%s'", specified_data, Qnil);
5620 return 0;
5623 /* Read from memory. */
5624 tbr.bytes = SDATA (specified_data);
5625 tbr.len = SBYTES (specified_data);
5626 tbr.index = 0;
5628 /* Check PNG signature. */
5629 if (tbr.len < sizeof sig
5630 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5632 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5633 return 0;
5636 /* Need to skip past the signature. */
5637 tbr.bytes += sizeof (sig);
5640 /* Initialize read and info structs for PNG lib. */
5641 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5642 NULL, my_png_error,
5643 my_png_warning);
5644 if (!png_ptr)
5646 if (fp) fclose (fp);
5647 return 0;
5650 info_ptr = fn_png_create_info_struct (png_ptr);
5651 if (!info_ptr)
5653 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5654 if (fp) fclose (fp);
5655 return 0;
5658 end_info = fn_png_create_info_struct (png_ptr);
5659 if (!end_info)
5661 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5662 if (fp) fclose (fp);
5663 return 0;
5666 /* Set error jump-back. We come back here when the PNG library
5667 detects an error. */
5668 if (setjmp (PNG_JMPBUF (png_ptr)))
5670 error:
5671 if (png_ptr)
5672 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5673 xfree (pixels);
5674 xfree (rows);
5675 if (fp) fclose (fp);
5676 return 0;
5679 /* Read image info. */
5680 if (!NILP (specified_data))
5681 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5682 else
5683 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5685 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5686 fn_png_read_info (png_ptr, info_ptr);
5687 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5688 &interlace_type, NULL, NULL);
5690 if (!check_image_size (f, width, height))
5692 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5693 goto error;
5695 /* If image contains simply transparency data, we prefer to
5696 construct a clipping mask. */
5697 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5698 transparent_p = 1;
5699 else
5700 transparent_p = 0;
5702 /* This function is easier to write if we only have to handle
5703 one data format: RGB or RGBA with 8 bits per channel. Let's
5704 transform other formats into that format. */
5706 /* Strip more than 8 bits per channel. */
5707 if (bit_depth == 16)
5708 fn_png_set_strip_16 (png_ptr);
5710 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5711 if available. */
5712 fn_png_set_expand (png_ptr);
5714 /* Convert grayscale images to RGB. */
5715 if (color_type == PNG_COLOR_TYPE_GRAY
5716 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5717 fn_png_set_gray_to_rgb (png_ptr);
5719 /* Handle alpha channel by combining the image with a background
5720 color. Do this only if a real alpha channel is supplied. For
5721 simple transparency, we prefer a clipping mask. */
5722 if (!transparent_p)
5724 /* png_color_16 *image_bg; */
5725 Lisp_Object specified_bg
5726 = image_spec_value (img->spec, QCbackground, NULL);
5727 int shift = (bit_depth == 16) ? 0 : 8;
5729 if (STRINGP (specified_bg))
5730 /* The user specified `:background', use that. */
5732 XColor color;
5733 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
5735 png_color_16 user_bg;
5737 memset (&user_bg, 0, sizeof user_bg);
5738 user_bg.red = color.red >> shift;
5739 user_bg.green = color.green >> shift;
5740 user_bg.blue = color.blue >> shift;
5742 fn_png_set_background (png_ptr, &user_bg,
5743 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5746 else
5748 /* We use the current frame background, ignoring any default
5749 background color set by the image. */
5750 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5751 XColor color;
5752 png_color_16 frame_background;
5754 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5755 x_query_color (f, &color);
5757 memset (&frame_background, 0, sizeof frame_background);
5758 frame_background.red = color.red >> shift;
5759 frame_background.green = color.green >> shift;
5760 frame_background.blue = color.blue >> shift;
5761 #endif /* HAVE_X_WINDOWS */
5763 fn_png_set_background (png_ptr, &frame_background,
5764 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5768 /* Update info structure. */
5769 fn_png_read_update_info (png_ptr, info_ptr);
5771 /* Get number of channels. Valid values are 1 for grayscale images
5772 and images with a palette, 2 for grayscale images with transparency
5773 information (alpha channel), 3 for RGB images, and 4 for RGB
5774 images with alpha channel, i.e. RGBA. If conversions above were
5775 sufficient we should only have 3 or 4 channels here. */
5776 channels = fn_png_get_channels (png_ptr, info_ptr);
5777 xassert (channels == 3 || channels == 4);
5779 /* Number of bytes needed for one row of the image. */
5780 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5782 /* Allocate memory for the image. */
5783 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
5784 rows = (png_byte **) xmalloc (height * sizeof *rows);
5785 for (i = 0; i < height; ++i)
5786 rows[i] = pixels + i * row_bytes;
5788 /* Read the entire image. */
5789 fn_png_read_image (png_ptr, rows);
5790 fn_png_read_end (png_ptr, info_ptr);
5791 if (fp)
5793 fclose (fp);
5794 fp = NULL;
5797 /* Create the X image and pixmap. */
5798 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5799 &img->pixmap))
5800 goto error;
5802 /* Create an image and pixmap serving as mask if the PNG image
5803 contains an alpha channel. */
5804 if (channels == 4
5805 && !transparent_p
5806 && !x_create_x_image_and_pixmap (f, width, height, 1,
5807 &mask_img, &img->mask))
5809 x_destroy_x_image (ximg);
5810 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5811 img->pixmap = NO_PIXMAP;
5812 goto error;
5815 /* Fill the X image and mask from PNG data. */
5816 init_color_table ();
5818 for (y = 0; y < height; ++y)
5820 png_byte *p = rows[y];
5822 for (x = 0; x < width; ++x)
5824 unsigned r, g, b;
5826 r = *p++ << 8;
5827 g = *p++ << 8;
5828 b = *p++ << 8;
5829 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5830 /* An alpha channel, aka mask channel, associates variable
5831 transparency with an image. Where other image formats
5832 support binary transparency---fully transparent or fully
5833 opaque---PNG allows up to 254 levels of partial transparency.
5834 The PNG library implements partial transparency by combining
5835 the image with a specified background color.
5837 I'm not sure how to handle this here nicely: because the
5838 background on which the image is displayed may change, for
5839 real alpha channel support, it would be necessary to create
5840 a new image for each possible background.
5842 What I'm doing now is that a mask is created if we have
5843 boolean transparency information. Otherwise I'm using
5844 the frame's background color to combine the image with. */
5846 if (channels == 4)
5848 if (mask_img)
5849 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5850 ++p;
5855 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5856 /* Set IMG's background color from the PNG image, unless the user
5857 overrode it. */
5859 png_color_16 *bg;
5860 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5862 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5863 img->background_valid = 1;
5867 #ifdef COLOR_TABLE_SUPPORT
5868 /* Remember colors allocated for this image. */
5869 img->colors = colors_in_color_table (&img->ncolors);
5870 free_color_table ();
5871 #endif /* COLOR_TABLE_SUPPORT */
5873 /* Clean up. */
5874 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5875 xfree (rows);
5876 xfree (pixels);
5878 img->width = width;
5879 img->height = height;
5881 /* Maybe fill in the background field while we have ximg handy.
5882 Casting avoids a GCC warning. */
5883 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5885 /* Put the image into the pixmap, then free the X image and its buffer. */
5886 x_put_x_image (f, ximg, img->pixmap, width, height);
5887 x_destroy_x_image (ximg);
5889 /* Same for the mask. */
5890 if (mask_img)
5892 /* Fill in the background_transparent field while we have the
5893 mask handy. Casting avoids a GCC warning. */
5894 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
5896 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5897 x_destroy_x_image (mask_img);
5900 return 1;
5903 #else /* HAVE_PNG */
5905 #ifdef HAVE_NS
5906 static int
5907 png_load (struct frame *f, struct image *img)
5909 return ns_load_image(f, img,
5910 image_spec_value (img->spec, QCfile, NULL),
5911 image_spec_value (img->spec, QCdata, NULL));
5913 #endif /* HAVE_NS */
5916 #endif /* !HAVE_PNG */
5920 /***********************************************************************
5921 JPEG
5922 ***********************************************************************/
5924 #if defined (HAVE_JPEG) || defined (HAVE_NS)
5926 static int jpeg_image_p (Lisp_Object object);
5927 static int jpeg_load (struct frame *f, struct image *img);
5929 /* The symbol `jpeg' identifying images of this type. */
5931 static Lisp_Object Qjpeg;
5933 /* Indices of image specification fields in gs_format, below. */
5935 enum jpeg_keyword_index
5937 JPEG_TYPE,
5938 JPEG_DATA,
5939 JPEG_FILE,
5940 JPEG_ASCENT,
5941 JPEG_MARGIN,
5942 JPEG_RELIEF,
5943 JPEG_ALGORITHM,
5944 JPEG_HEURISTIC_MASK,
5945 JPEG_MASK,
5946 JPEG_BACKGROUND,
5947 JPEG_LAST
5950 /* Vector of image_keyword structures describing the format
5951 of valid user-defined image specifications. */
5953 static const struct image_keyword jpeg_format[JPEG_LAST] =
5955 {":type", IMAGE_SYMBOL_VALUE, 1},
5956 {":data", IMAGE_STRING_VALUE, 0},
5957 {":file", IMAGE_STRING_VALUE, 0},
5958 {":ascent", IMAGE_ASCENT_VALUE, 0},
5959 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5960 {":relief", IMAGE_INTEGER_VALUE, 0},
5961 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5962 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5963 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5964 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5967 /* Structure describing the image type `jpeg'. */
5969 static struct image_type jpeg_type =
5971 &Qjpeg,
5972 jpeg_image_p,
5973 jpeg_load,
5974 x_clear_image,
5975 NULL
5978 /* Return non-zero if OBJECT is a valid JPEG image specification. */
5980 static int
5981 jpeg_image_p (Lisp_Object object)
5983 struct image_keyword fmt[JPEG_LAST];
5985 memcpy (fmt, jpeg_format, sizeof fmt);
5987 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
5988 return 0;
5990 /* Must specify either the :data or :file keyword. */
5991 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
5994 #endif /* HAVE_JPEG || HAVE_NS */
5996 #ifdef HAVE_JPEG
5998 /* Work around a warning about HAVE_STDLIB_H being redefined in
5999 jconfig.h. */
6000 #ifdef HAVE_STDLIB_H
6001 #undef HAVE_STDLIB_H
6002 #endif /* HAVE_STLIB_H */
6004 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6005 /* In older releases of the jpeg library, jpeglib.h will define boolean
6006 differently depending on __WIN32__, so make sure it is defined. */
6007 #define __WIN32__ 1
6008 #endif
6010 #include <jpeglib.h>
6011 #include <jerror.h>
6013 #ifdef HAVE_STLIB_H_1
6014 #define HAVE_STDLIB_H 1
6015 #endif
6017 #ifdef HAVE_NTGUI
6019 /* JPEG library details. */
6020 DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6021 DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6022 DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6023 DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6024 DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6025 DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6026 DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6027 DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6029 static int
6030 init_jpeg_functions (Lisp_Object libraries)
6032 HMODULE library;
6034 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6035 return 0;
6037 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6038 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6039 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6040 LOAD_IMGLIB_FN (library, jpeg_read_header);
6041 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6042 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6043 LOAD_IMGLIB_FN (library, jpeg_std_error);
6044 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6045 return 1;
6048 /* Wrapper since we can't directly assign the function pointer
6049 to another function pointer that was declared more completely easily. */
6050 static boolean
6051 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6053 return fn_jpeg_resync_to_restart (cinfo, desired);
6056 #else
6058 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6059 #define fn_jpeg_start_decompress jpeg_start_decompress
6060 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6061 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6062 #define fn_jpeg_read_header jpeg_read_header
6063 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6064 #define fn_jpeg_std_error jpeg_std_error
6065 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6067 #endif /* HAVE_NTGUI */
6069 struct my_jpeg_error_mgr
6071 struct jpeg_error_mgr pub;
6072 jmp_buf setjmp_buffer;
6076 static void my_error_exit (j_common_ptr) NO_RETURN;
6077 static void
6078 my_error_exit (j_common_ptr cinfo)
6080 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6081 longjmp (mgr->setjmp_buffer, 1);
6085 /* Init source method for JPEG data source manager. Called by
6086 jpeg_read_header() before any data is actually read. See
6087 libjpeg.doc from the JPEG lib distribution. */
6089 static void
6090 our_common_init_source (j_decompress_ptr cinfo)
6095 /* Method to terminate data source. Called by
6096 jpeg_finish_decompress() after all data has been processed. */
6098 static void
6099 our_common_term_source (j_decompress_ptr cinfo)
6104 /* Fill input buffer method for JPEG data source manager. Called
6105 whenever more data is needed. We read the whole image in one step,
6106 so this only adds a fake end of input marker at the end. */
6108 static JOCTET our_memory_buffer[2];
6110 static boolean
6111 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6113 /* Insert a fake EOI marker. */
6114 struct jpeg_source_mgr *src = cinfo->src;
6116 our_memory_buffer[0] = (JOCTET) 0xFF;
6117 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6119 src->next_input_byte = our_memory_buffer;
6120 src->bytes_in_buffer = 2;
6121 return 1;
6125 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6126 is the JPEG data source manager. */
6128 static void
6129 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6131 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6133 if (src)
6135 if (num_bytes > src->bytes_in_buffer)
6136 ERREXIT (cinfo, JERR_INPUT_EOF);
6138 src->bytes_in_buffer -= num_bytes;
6139 src->next_input_byte += num_bytes;
6144 /* Set up the JPEG lib for reading an image from DATA which contains
6145 LEN bytes. CINFO is the decompression info structure created for
6146 reading the image. */
6148 static void
6149 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, unsigned int len)
6151 struct jpeg_source_mgr *src;
6153 if (cinfo->src == NULL)
6155 /* First time for this JPEG object? */
6156 cinfo->src = (struct jpeg_source_mgr *)
6157 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6158 sizeof (struct jpeg_source_mgr));
6159 src = (struct jpeg_source_mgr *) cinfo->src;
6160 src->next_input_byte = data;
6163 src = (struct jpeg_source_mgr *) cinfo->src;
6164 src->init_source = our_common_init_source;
6165 src->fill_input_buffer = our_memory_fill_input_buffer;
6166 src->skip_input_data = our_memory_skip_input_data;
6167 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6168 src->term_source = our_common_term_source;
6169 src->bytes_in_buffer = len;
6170 src->next_input_byte = data;
6174 struct jpeg_stdio_mgr
6176 struct jpeg_source_mgr mgr;
6177 boolean finished;
6178 FILE *file;
6179 JOCTET *buffer;
6183 /* Size of buffer to read JPEG from file.
6184 Not too big, as we want to use alloc_small. */
6185 #define JPEG_STDIO_BUFFER_SIZE 8192
6188 /* Fill input buffer method for JPEG data source manager. Called
6189 whenever more data is needed. The data is read from a FILE *. */
6191 static boolean
6192 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6194 struct jpeg_stdio_mgr *src;
6196 src = (struct jpeg_stdio_mgr *) cinfo->src;
6197 if (!src->finished)
6199 size_t bytes;
6201 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6202 if (bytes > 0)
6203 src->mgr.bytes_in_buffer = bytes;
6204 else
6206 WARNMS (cinfo, JWRN_JPEG_EOF);
6207 src->finished = 1;
6208 src->buffer[0] = (JOCTET) 0xFF;
6209 src->buffer[1] = (JOCTET) JPEG_EOI;
6210 src->mgr.bytes_in_buffer = 2;
6212 src->mgr.next_input_byte = src->buffer;
6215 return 1;
6219 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6220 is the JPEG data source manager. */
6222 static void
6223 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6225 struct jpeg_stdio_mgr *src;
6226 src = (struct jpeg_stdio_mgr *) cinfo->src;
6228 while (num_bytes > 0 && !src->finished)
6230 if (num_bytes <= src->mgr.bytes_in_buffer)
6232 src->mgr.bytes_in_buffer -= num_bytes;
6233 src->mgr.next_input_byte += num_bytes;
6234 break;
6236 else
6238 num_bytes -= src->mgr.bytes_in_buffer;
6239 src->mgr.bytes_in_buffer = 0;
6240 src->mgr.next_input_byte = NULL;
6242 our_stdio_fill_input_buffer (cinfo);
6248 /* Set up the JPEG lib for reading an image from a FILE *.
6249 CINFO is the decompression info structure created for
6250 reading the image. */
6252 static void
6253 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6255 struct jpeg_stdio_mgr *src;
6257 if (cinfo->src != NULL)
6258 src = (struct jpeg_stdio_mgr *) cinfo->src;
6259 else
6261 /* First time for this JPEG object? */
6262 cinfo->src = (struct jpeg_source_mgr *)
6263 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6264 sizeof (struct jpeg_stdio_mgr));
6265 src = (struct jpeg_stdio_mgr *) cinfo->src;
6266 src->buffer = (JOCTET *)
6267 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6268 JPEG_STDIO_BUFFER_SIZE);
6271 src->file = fp;
6272 src->finished = 0;
6273 src->mgr.init_source = our_common_init_source;
6274 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6275 src->mgr.skip_input_data = our_stdio_skip_input_data;
6276 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6277 src->mgr.term_source = our_common_term_source;
6278 src->mgr.bytes_in_buffer = 0;
6279 src->mgr.next_input_byte = NULL;
6283 /* Load image IMG for use on frame F. Patterned after example.c
6284 from the JPEG lib. */
6286 static int
6287 jpeg_load (struct frame *f, struct image *img)
6289 struct jpeg_decompress_struct cinfo;
6290 struct my_jpeg_error_mgr mgr;
6291 Lisp_Object file, specified_file;
6292 Lisp_Object specified_data;
6293 FILE * volatile fp = NULL;
6294 JSAMPARRAY buffer;
6295 int row_stride, x, y;
6296 XImagePtr ximg = NULL;
6297 int rc;
6298 unsigned long *colors;
6299 int width, height;
6301 /* Open the JPEG file. */
6302 specified_file = image_spec_value (img->spec, QCfile, NULL);
6303 specified_data = image_spec_value (img->spec, QCdata, NULL);
6305 if (NILP (specified_data))
6307 file = x_find_image_file (specified_file);
6308 if (!STRINGP (file))
6310 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6311 return 0;
6314 fp = fopen (SSDATA (file), "rb");
6315 if (fp == NULL)
6317 image_error ("Cannot open `%s'", file, Qnil);
6318 return 0;
6321 else if (!STRINGP (specified_data))
6323 image_error ("Invalid image data `%s'", specified_data, Qnil);
6324 return 0;
6327 /* Customize libjpeg's error handling to call my_error_exit when an
6328 error is detected. This function will perform a longjmp. */
6329 cinfo.err = fn_jpeg_std_error (&mgr.pub);
6330 mgr.pub.error_exit = my_error_exit;
6332 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6334 if (rc == 1)
6336 /* Called from my_error_exit. Display a JPEG error. */
6337 char buf[JMSG_LENGTH_MAX];
6338 cinfo.err->format_message ((j_common_ptr) &cinfo, buf);
6339 image_error ("Error reading JPEG image `%s': %s", img->spec,
6340 build_string (buf));
6343 /* Close the input file and destroy the JPEG object. */
6344 if (fp)
6345 fclose ((FILE *) fp);
6346 fn_jpeg_destroy_decompress (&cinfo);
6348 /* If we already have an XImage, free that. */
6349 x_destroy_x_image (ximg);
6351 /* Free pixmap and colors. */
6352 x_clear_image (f, img);
6353 return 0;
6356 /* Create the JPEG decompression object. Let it read from fp.
6357 Read the JPEG image header. */
6358 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6360 if (NILP (specified_data))
6361 jpeg_file_src (&cinfo, (FILE *) fp);
6362 else
6363 jpeg_memory_src (&cinfo, SDATA (specified_data),
6364 SBYTES (specified_data));
6366 fn_jpeg_read_header (&cinfo, 1);
6368 /* Customize decompression so that color quantization will be used.
6369 Start decompression. */
6370 cinfo.quantize_colors = 1;
6371 fn_jpeg_start_decompress (&cinfo);
6372 width = img->width = cinfo.output_width;
6373 height = img->height = cinfo.output_height;
6375 if (!check_image_size (f, width, height))
6377 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6378 longjmp (mgr.setjmp_buffer, 2);
6381 /* Create X image and pixmap. */
6382 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6383 longjmp (mgr.setjmp_buffer, 2);
6385 /* Allocate colors. When color quantization is used,
6386 cinfo.actual_number_of_colors has been set with the number of
6387 colors generated, and cinfo.colormap is a two-dimensional array
6388 of color indices in the range 0..cinfo.actual_number_of_colors.
6389 No more than 255 colors will be generated. */
6391 int i, ir, ig, ib;
6393 if (cinfo.out_color_components > 2)
6394 ir = 0, ig = 1, ib = 2;
6395 else if (cinfo.out_color_components > 1)
6396 ir = 0, ig = 1, ib = 0;
6397 else
6398 ir = 0, ig = 0, ib = 0;
6400 /* Use the color table mechanism because it handles colors that
6401 cannot be allocated nicely. Such colors will be replaced with
6402 a default color, and we don't have to care about which colors
6403 can be freed safely, and which can't. */
6404 init_color_table ();
6405 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6406 * sizeof *colors);
6408 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6410 /* Multiply RGB values with 255 because X expects RGB values
6411 in the range 0..0xffff. */
6412 int r = cinfo.colormap[ir][i] << 8;
6413 int g = cinfo.colormap[ig][i] << 8;
6414 int b = cinfo.colormap[ib][i] << 8;
6415 colors[i] = lookup_rgb_color (f, r, g, b);
6418 #ifdef COLOR_TABLE_SUPPORT
6419 /* Remember those colors actually allocated. */
6420 img->colors = colors_in_color_table (&img->ncolors);
6421 free_color_table ();
6422 #endif /* COLOR_TABLE_SUPPORT */
6425 /* Read pixels. */
6426 row_stride = width * cinfo.output_components;
6427 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6428 row_stride, 1);
6429 for (y = 0; y < height; ++y)
6431 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6432 for (x = 0; x < cinfo.output_width; ++x)
6433 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6436 /* Clean up. */
6437 fn_jpeg_finish_decompress (&cinfo);
6438 fn_jpeg_destroy_decompress (&cinfo);
6439 if (fp)
6440 fclose ((FILE *) fp);
6442 /* Maybe fill in the background field while we have ximg handy. */
6443 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6444 /* Casting avoids a GCC warning. */
6445 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6447 /* Put the image into the pixmap. */
6448 x_put_x_image (f, ximg, img->pixmap, width, height);
6449 x_destroy_x_image (ximg);
6450 return 1;
6453 #else /* HAVE_JPEG */
6455 #ifdef HAVE_NS
6456 static int
6457 jpeg_load (struct frame *f, struct image *img)
6459 return ns_load_image (f, img,
6460 image_spec_value (img->spec, QCfile, NULL),
6461 image_spec_value (img->spec, QCdata, NULL));
6463 #endif /* HAVE_NS */
6465 #endif /* !HAVE_JPEG */
6469 /***********************************************************************
6470 TIFF
6471 ***********************************************************************/
6473 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6475 static int tiff_image_p (Lisp_Object object);
6476 static int tiff_load (struct frame *f, struct image *img);
6478 /* The symbol `tiff' identifying images of this type. */
6480 static Lisp_Object Qtiff;
6482 /* Indices of image specification fields in tiff_format, below. */
6484 enum tiff_keyword_index
6486 TIFF_TYPE,
6487 TIFF_DATA,
6488 TIFF_FILE,
6489 TIFF_ASCENT,
6490 TIFF_MARGIN,
6491 TIFF_RELIEF,
6492 TIFF_ALGORITHM,
6493 TIFF_HEURISTIC_MASK,
6494 TIFF_MASK,
6495 TIFF_BACKGROUND,
6496 TIFF_INDEX,
6497 TIFF_LAST
6500 /* Vector of image_keyword structures describing the format
6501 of valid user-defined image specifications. */
6503 static const struct image_keyword tiff_format[TIFF_LAST] =
6505 {":type", IMAGE_SYMBOL_VALUE, 1},
6506 {":data", IMAGE_STRING_VALUE, 0},
6507 {":file", IMAGE_STRING_VALUE, 0},
6508 {":ascent", IMAGE_ASCENT_VALUE, 0},
6509 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6510 {":relief", IMAGE_INTEGER_VALUE, 0},
6511 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6512 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6513 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6514 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6515 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6518 /* Structure describing the image type `tiff'. */
6520 static struct image_type tiff_type =
6522 &Qtiff,
6523 tiff_image_p,
6524 tiff_load,
6525 x_clear_image,
6526 NULL
6529 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6531 static int
6532 tiff_image_p (Lisp_Object object)
6534 struct image_keyword fmt[TIFF_LAST];
6535 memcpy (fmt, tiff_format, sizeof fmt);
6537 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6538 return 0;
6540 /* Must specify either the :data or :file keyword. */
6541 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6544 #endif /* HAVE_TIFF || HAVE_NS */
6546 #ifdef HAVE_TIFF
6548 #include <tiffio.h>
6550 #ifdef HAVE_NTGUI
6552 /* TIFF library details. */
6553 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6554 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6555 DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6556 DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
6557 TIFFReadWriteProc, TIFFReadWriteProc,
6558 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6559 TIFFMapFileProc, TIFFUnmapFileProc));
6560 DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6561 DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6562 DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6563 DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6565 static int
6566 init_tiff_functions (Lisp_Object libraries)
6568 HMODULE library;
6570 if (!(library = w32_delayed_load (libraries, Qtiff)))
6571 return 0;
6573 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6574 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6575 LOAD_IMGLIB_FN (library, TIFFOpen);
6576 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6577 LOAD_IMGLIB_FN (library, TIFFGetField);
6578 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6579 LOAD_IMGLIB_FN (library, TIFFClose);
6580 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6581 return 1;
6584 #else
6586 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6587 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6588 #define fn_TIFFOpen TIFFOpen
6589 #define fn_TIFFClientOpen TIFFClientOpen
6590 #define fn_TIFFGetField TIFFGetField
6591 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6592 #define fn_TIFFClose TIFFClose
6593 #define fn_TIFFSetDirectory TIFFSetDirectory
6594 #endif /* HAVE_NTGUI */
6597 /* Reading from a memory buffer for TIFF images Based on the PNG
6598 memory source, but we have to provide a lot of extra functions.
6599 Blah.
6601 We really only need to implement read and seek, but I am not
6602 convinced that the TIFF library is smart enough not to destroy
6603 itself if we only hand it the function pointers we need to
6604 override. */
6606 typedef struct
6608 unsigned char *bytes;
6609 size_t len;
6610 int index;
6612 tiff_memory_source;
6614 static size_t
6615 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6617 tiff_memory_source *src = (tiff_memory_source *) data;
6619 if (size > src->len - src->index)
6620 return (size_t) -1;
6621 memcpy (buf, src->bytes + src->index, size);
6622 src->index += size;
6623 return size;
6626 static size_t
6627 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6629 return (size_t) -1;
6632 static toff_t
6633 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6635 tiff_memory_source *src = (tiff_memory_source *) data;
6636 int idx;
6638 switch (whence)
6640 case SEEK_SET: /* Go from beginning of source. */
6641 idx = off;
6642 break;
6644 case SEEK_END: /* Go from end of source. */
6645 idx = src->len + off;
6646 break;
6648 case SEEK_CUR: /* Go from current position. */
6649 idx = src->index + off;
6650 break;
6652 default: /* Invalid `whence'. */
6653 return -1;
6656 if (idx > src->len || idx < 0)
6657 return -1;
6659 src->index = idx;
6660 return src->index;
6663 static int
6664 tiff_close_memory (thandle_t data)
6666 /* NOOP */
6667 return 0;
6670 static int
6671 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6673 /* It is already _IN_ memory. */
6674 return 0;
6677 static void
6678 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6680 /* We don't need to do this. */
6683 static toff_t
6684 tiff_size_of_memory (thandle_t data)
6686 return ((tiff_memory_source *) data)->len;
6690 static void tiff_error_handler (const char *, const char *, va_list)
6691 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6692 static void
6693 tiff_error_handler (const char *title, const char *format, va_list ap)
6695 char buf[512];
6696 int len;
6698 len = sprintf (buf, "TIFF error: %s ", title);
6699 vsprintf (buf + len, format, ap);
6700 add_to_log (buf, Qnil, Qnil);
6704 static void tiff_warning_handler (const char *, const char *, va_list)
6705 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6706 static void
6707 tiff_warning_handler (const char *title, const char *format, va_list ap)
6709 char buf[512];
6710 int len;
6712 len = sprintf (buf, "TIFF warning: %s ", title);
6713 vsprintf (buf + len, format, ap);
6714 add_to_log (buf, Qnil, Qnil);
6718 /* Load TIFF image IMG for use on frame F. Value is non-zero if
6719 successful. */
6721 static int
6722 tiff_load (struct frame *f, struct image *img)
6724 Lisp_Object file, specified_file;
6725 Lisp_Object specified_data;
6726 TIFF *tiff;
6727 int width, height, x, y, count;
6728 uint32 *buf;
6729 int rc;
6730 XImagePtr ximg;
6731 tiff_memory_source memsrc;
6732 Lisp_Object image;
6734 specified_file = image_spec_value (img->spec, QCfile, NULL);
6735 specified_data = image_spec_value (img->spec, QCdata, NULL);
6737 fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6738 fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
6740 if (NILP (specified_data))
6742 /* Read from a file */
6743 file = x_find_image_file (specified_file);
6744 if (!STRINGP (file))
6746 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6747 return 0;
6750 /* Try to open the image file. */
6751 tiff = fn_TIFFOpen (SSDATA (file), "r");
6752 if (tiff == NULL)
6754 image_error ("Cannot open `%s'", file, Qnil);
6755 return 0;
6758 else
6760 if (!STRINGP (specified_data))
6762 image_error ("Invalid image data `%s'", specified_data, Qnil);
6763 return 0;
6766 /* Memory source! */
6767 memsrc.bytes = SDATA (specified_data);
6768 memsrc.len = SBYTES (specified_data);
6769 memsrc.index = 0;
6771 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
6772 (TIFFReadWriteProc) tiff_read_from_memory,
6773 (TIFFReadWriteProc) tiff_write_from_memory,
6774 tiff_seek_in_memory,
6775 tiff_close_memory,
6776 tiff_size_of_memory,
6777 tiff_mmap_memory,
6778 tiff_unmap_memory);
6780 if (!tiff)
6782 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6783 return 0;
6787 image = image_spec_value (img->spec, QCindex, NULL);
6788 if (INTEGERP (image))
6790 int ino = XFASTINT (image);
6791 if (!fn_TIFFSetDirectory (tiff, ino))
6793 image_error ("Invalid image number `%s' in image `%s'",
6794 image, img->spec);
6795 fn_TIFFClose (tiff);
6796 return 0;
6800 /* Get width and height of the image, and allocate a raster buffer
6801 of width x height 32-bit values. */
6802 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6803 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6805 if (!check_image_size (f, width, height))
6807 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6808 fn_TIFFClose (tiff);
6809 return 0;
6812 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
6814 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
6816 /* Count the number of images in the file. */
6817 for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
6818 continue;
6820 if (count > 1)
6821 img->data.lisp_val = Fcons (Qcount,
6822 Fcons (make_number (count),
6823 img->data.lisp_val));
6825 fn_TIFFClose (tiff);
6826 if (!rc)
6828 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6829 xfree (buf);
6830 return 0;
6833 /* Create the X image and pixmap. */
6834 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6836 xfree (buf);
6837 return 0;
6840 /* Initialize the color table. */
6841 init_color_table ();
6843 /* Process the pixel raster. Origin is in the lower-left corner. */
6844 for (y = 0; y < height; ++y)
6846 uint32 *row = buf + y * width;
6848 for (x = 0; x < width; ++x)
6850 uint32 abgr = row[x];
6851 int r = TIFFGetR (abgr) << 8;
6852 int g = TIFFGetG (abgr) << 8;
6853 int b = TIFFGetB (abgr) << 8;
6854 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6858 #ifdef COLOR_TABLE_SUPPORT
6859 /* Remember the colors allocated for the image. Free the color table. */
6860 img->colors = colors_in_color_table (&img->ncolors);
6861 free_color_table ();
6862 #endif /* COLOR_TABLE_SUPPORT */
6864 img->width = width;
6865 img->height = height;
6867 /* Maybe fill in the background field while we have ximg handy. */
6868 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6869 /* Casting avoids a GCC warning on W32. */
6870 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6872 /* Put the image into the pixmap, then free the X image and its buffer. */
6873 x_put_x_image (f, ximg, img->pixmap, width, height);
6874 x_destroy_x_image (ximg);
6875 xfree (buf);
6877 return 1;
6880 #else /* HAVE_TIFF */
6882 #ifdef HAVE_NS
6883 static int
6884 tiff_load (struct frame *f, struct image *img)
6886 return ns_load_image (f, img,
6887 image_spec_value (img->spec, QCfile, NULL),
6888 image_spec_value (img->spec, QCdata, NULL));
6890 #endif /* HAVE_NS */
6892 #endif /* !HAVE_TIFF */
6896 /***********************************************************************
6898 ***********************************************************************/
6900 #if defined (HAVE_GIF) || defined (HAVE_NS)
6902 static int gif_image_p (Lisp_Object object);
6903 static int gif_load (struct frame *f, struct image *img);
6904 static void gif_clear_image (struct frame *f, struct image *img);
6906 /* The symbol `gif' identifying images of this type. */
6908 static Lisp_Object Qgif;
6910 /* Indices of image specification fields in gif_format, below. */
6912 enum gif_keyword_index
6914 GIF_TYPE,
6915 GIF_DATA,
6916 GIF_FILE,
6917 GIF_ASCENT,
6918 GIF_MARGIN,
6919 GIF_RELIEF,
6920 GIF_ALGORITHM,
6921 GIF_HEURISTIC_MASK,
6922 GIF_MASK,
6923 GIF_IMAGE,
6924 GIF_BACKGROUND,
6925 GIF_LAST
6928 /* Vector of image_keyword structures describing the format
6929 of valid user-defined image specifications. */
6931 static const struct image_keyword gif_format[GIF_LAST] =
6933 {":type", IMAGE_SYMBOL_VALUE, 1},
6934 {":data", IMAGE_STRING_VALUE, 0},
6935 {":file", IMAGE_STRING_VALUE, 0},
6936 {":ascent", IMAGE_ASCENT_VALUE, 0},
6937 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6938 {":relief", IMAGE_INTEGER_VALUE, 0},
6939 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6940 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6941 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6942 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
6943 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6946 /* Structure describing the image type `gif'. */
6948 static struct image_type gif_type =
6950 &Qgif,
6951 gif_image_p,
6952 gif_load,
6953 gif_clear_image,
6954 NULL
6957 /* Free X resources of GIF image IMG which is used on frame F. */
6959 static void
6960 gif_clear_image (struct frame *f, struct image *img)
6962 /* IMG->data.ptr_val may contain metadata with extension data. */
6963 img->data.lisp_val = Qnil;
6964 x_clear_image (f, img);
6967 /* Return non-zero if OBJECT is a valid GIF image specification. */
6969 static int
6970 gif_image_p (Lisp_Object object)
6972 struct image_keyword fmt[GIF_LAST];
6973 memcpy (fmt, gif_format, sizeof fmt);
6975 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
6976 return 0;
6978 /* Must specify either the :data or :file keyword. */
6979 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
6982 #endif /* HAVE_GIF */
6984 #ifdef HAVE_GIF
6986 #if defined (HAVE_NTGUI)
6987 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
6988 Undefine before redefining to avoid a preprocessor warning. */
6989 #ifdef DrawText
6990 #undef DrawText
6991 #endif
6992 /* avoid conflict with QuickdrawText.h */
6993 #define DrawText gif_DrawText
6994 #include <gif_lib.h>
6995 #undef DrawText
6997 #else /* HAVE_NTGUI */
6999 #include <gif_lib.h>
7001 #endif /* HAVE_NTGUI */
7004 #ifdef HAVE_NTGUI
7006 /* GIF library details. */
7007 DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7008 DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7009 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7010 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
7012 static int
7013 init_gif_functions (Lisp_Object libraries)
7015 HMODULE library;
7017 if (!(library = w32_delayed_load (libraries, Qgif)))
7018 return 0;
7020 LOAD_IMGLIB_FN (library, DGifCloseFile);
7021 LOAD_IMGLIB_FN (library, DGifSlurp);
7022 LOAD_IMGLIB_FN (library, DGifOpen);
7023 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7024 return 1;
7027 #else
7029 #define fn_DGifCloseFile DGifCloseFile
7030 #define fn_DGifSlurp DGifSlurp
7031 #define fn_DGifOpen DGifOpen
7032 #define fn_DGifOpenFileName DGifOpenFileName
7034 #endif /* HAVE_NTGUI */
7036 /* Reading a GIF image from memory
7037 Based on the PNG memory stuff to a certain extent. */
7039 typedef struct
7041 unsigned char *bytes;
7042 size_t len;
7043 int index;
7045 gif_memory_source;
7047 /* Make the current memory source available to gif_read_from_memory.
7048 It's done this way because not all versions of libungif support
7049 a UserData field in the GifFileType structure. */
7050 static gif_memory_source *current_gif_memory_src;
7052 static int
7053 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7055 gif_memory_source *src = current_gif_memory_src;
7057 if (len > src->len - src->index)
7058 return -1;
7060 memcpy (buf, src->bytes + src->index, len);
7061 src->index += len;
7062 return len;
7066 /* Load GIF image IMG for use on frame F. Value is non-zero if
7067 successful. */
7069 static const int interlace_start[] = {0, 4, 2, 1};
7070 static const int interlace_increment[] = {8, 8, 4, 2};
7072 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7074 static int
7075 gif_load (struct frame *f, struct image *img)
7077 Lisp_Object file, specified_file;
7078 Lisp_Object specified_data;
7079 int rc, width, height, x, y, i;
7080 boolean transparent_p = 0;
7081 XImagePtr ximg;
7082 ColorMapObject *gif_color_map;
7083 unsigned long pixel_colors[256];
7084 GifFileType *gif;
7085 Lisp_Object image;
7086 int ino, image_height, image_width;
7087 gif_memory_source memsrc;
7088 unsigned char *raster;
7089 unsigned int transparency_color_index IF_LINT (= 0);
7091 specified_file = image_spec_value (img->spec, QCfile, NULL);
7092 specified_data = image_spec_value (img->spec, QCdata, NULL);
7094 if (NILP (specified_data))
7096 file = x_find_image_file (specified_file);
7097 if (!STRINGP (file))
7099 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7100 return 0;
7103 /* Open the GIF file. */
7104 gif = fn_DGifOpenFileName (SSDATA (file));
7105 if (gif == NULL)
7107 image_error ("Cannot open `%s'", file, Qnil);
7108 return 0;
7111 else
7113 if (!STRINGP (specified_data))
7115 image_error ("Invalid image data `%s'", specified_data, Qnil);
7116 return 0;
7119 /* Read from memory! */
7120 current_gif_memory_src = &memsrc;
7121 memsrc.bytes = SDATA (specified_data);
7122 memsrc.len = SBYTES (specified_data);
7123 memsrc.index = 0;
7125 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
7126 if (!gif)
7128 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7129 return 0;
7133 /* Before reading entire contents, check the declared image size. */
7134 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7136 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7137 fn_DGifCloseFile (gif);
7138 return 0;
7141 /* Read entire contents. */
7142 rc = fn_DGifSlurp (gif);
7143 if (rc == GIF_ERROR)
7145 image_error ("Error reading `%s'", img->spec, Qnil);
7146 fn_DGifCloseFile (gif);
7147 return 0;
7150 image = image_spec_value (img->spec, QCindex, NULL);
7151 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7152 if (ino >= gif->ImageCount)
7154 image_error ("Invalid image number `%s' in image `%s'",
7155 image, img->spec);
7156 fn_DGifCloseFile (gif);
7157 return 0;
7160 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++)
7161 if ((gif->SavedImages[ino].ExtensionBlocks[i].Function
7162 == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7163 && gif->SavedImages[ino].ExtensionBlocks[i].ByteCount == 4
7164 /* Transparency enabled? */
7165 && gif->SavedImages[ino].ExtensionBlocks[i].Bytes[0] & 1)
7167 transparent_p = 1;
7168 transparency_color_index
7169 = (unsigned char) gif->SavedImages[ino].ExtensionBlocks[i].Bytes[3];
7172 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
7173 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
7174 image_height = gif->SavedImages[ino].ImageDesc.Height;
7175 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
7176 image_width = gif->SavedImages[ino].ImageDesc.Width;
7177 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
7179 width = img->width = max (gif->SWidth,
7180 max (gif->Image.Left + gif->Image.Width,
7181 img->corners[RIGHT_CORNER]));
7182 height = img->height = max (gif->SHeight,
7183 max (gif->Image.Top + gif->Image.Height,
7184 img->corners[BOT_CORNER]));
7186 if (!check_image_size (f, width, height))
7188 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7189 fn_DGifCloseFile (gif);
7190 return 0;
7193 /* Create the X image and pixmap. */
7194 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7196 fn_DGifCloseFile (gif);
7197 return 0;
7200 /* Allocate colors. */
7201 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7202 if (!gif_color_map)
7203 gif_color_map = gif->SColorMap;
7204 init_color_table ();
7205 memset (pixel_colors, 0, sizeof pixel_colors);
7207 if (gif_color_map)
7208 for (i = 0; i < gif_color_map->ColorCount; ++i)
7210 if (transparent_p && transparency_color_index == i)
7212 Lisp_Object specified_bg
7213 = image_spec_value (img->spec, QCbackground, NULL);
7214 pixel_colors[i] = STRINGP (specified_bg)
7215 ? x_alloc_image_color (f, img, specified_bg,
7216 FRAME_BACKGROUND_PIXEL (f))
7217 : FRAME_BACKGROUND_PIXEL (f);
7219 else
7221 int r = gif_color_map->Colors[i].Red << 8;
7222 int g = gif_color_map->Colors[i].Green << 8;
7223 int b = gif_color_map->Colors[i].Blue << 8;
7224 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7228 #ifdef COLOR_TABLE_SUPPORT
7229 img->colors = colors_in_color_table (&img->ncolors);
7230 free_color_table ();
7231 #endif /* COLOR_TABLE_SUPPORT */
7233 /* Clear the part of the screen image that are not covered by
7234 the image from the GIF file. Full animated GIF support
7235 requires more than can be done here (see the gif89 spec,
7236 disposal methods). Let's simply assume that the part
7237 not covered by a sub-image is in the frame's background color. */
7238 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7239 for (x = 0; x < width; ++x)
7240 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7242 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7243 for (x = 0; x < width; ++x)
7244 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7246 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7248 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7249 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7250 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7251 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7254 /* Read the GIF image into the X image. We use a local variable
7255 `raster' here because RasterBits below is a char *, and invites
7256 problems with bytes >= 0x80. */
7257 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7259 if (gif->SavedImages[ino].ImageDesc.Interlace)
7261 int pass;
7262 int row = interlace_start[0];
7264 pass = 0;
7266 for (y = 0; y < image_height; y++)
7268 if (row >= image_height)
7270 row = interlace_start[++pass];
7271 while (row >= image_height)
7272 row = interlace_start[++pass];
7275 for (x = 0; x < image_width; x++)
7277 int c = raster[(y * image_width) + x];
7278 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7279 row + img->corners[TOP_CORNER], pixel_colors[c]);
7282 row += interlace_increment[pass];
7285 else
7287 for (y = 0; y < image_height; ++y)
7288 for (x = 0; x < image_width; ++x)
7290 int c = raster[y * image_width + x];
7291 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7292 y + img->corners[TOP_CORNER], pixel_colors[c]);
7296 /* Save GIF image extension data for `image-metadata'.
7297 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7298 img->data.lisp_val = Qnil;
7299 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
7301 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
7302 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
7303 /* Append (... FUNCTION "BYTES") */
7304 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7305 Fcons (make_number (ext->Function),
7306 img->data.lisp_val));
7307 img->data.lisp_val = Fcons (Qextension_data,
7308 Fcons (Fnreverse (img->data.lisp_val),
7309 Qnil));
7311 if (gif->ImageCount > 1)
7312 img->data.lisp_val = Fcons (Qcount,
7313 Fcons (make_number (gif->ImageCount),
7314 img->data.lisp_val));
7316 fn_DGifCloseFile (gif);
7318 /* Maybe fill in the background field while we have ximg handy. */
7319 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7320 /* Casting avoids a GCC warning. */
7321 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7323 /* Put the image into the pixmap, then free the X image and its buffer. */
7324 x_put_x_image (f, ximg, img->pixmap, width, height);
7325 x_destroy_x_image (ximg);
7327 return 1;
7330 #else /* !HAVE_GIF */
7332 #ifdef HAVE_NS
7333 static int
7334 gif_load (struct frame *f, struct image *img)
7336 return ns_load_image (f, img,
7337 image_spec_value (img->spec, QCfile, NULL),
7338 image_spec_value (img->spec, QCdata, NULL));
7340 #endif /* HAVE_NS */
7342 #endif /* HAVE_GIF */
7345 /***********************************************************************
7346 ImageMagick
7347 ***********************************************************************/
7348 #if defined (HAVE_IMAGEMAGICK)
7350 Lisp_Object Qimagemagick;
7352 /* Indices of image specification fields in imagemagick_format. */
7354 enum imagemagick_keyword_index
7356 IMAGEMAGICK_TYPE,
7357 IMAGEMAGICK_DATA,
7358 IMAGEMAGICK_FILE,
7359 IMAGEMAGICK_ASCENT,
7360 IMAGEMAGICK_MARGIN,
7361 IMAGEMAGICK_RELIEF,
7362 IMAGEMAGICK_ALGORITHM,
7363 IMAGEMAGICK_HEURISTIC_MASK,
7364 IMAGEMAGICK_MASK,
7365 IMAGEMAGICK_BACKGROUND,
7366 IMAGEMAGICK_HEIGHT,
7367 IMAGEMAGICK_WIDTH,
7368 IMAGEMAGICK_ROTATION,
7369 IMAGEMAGICK_CROP,
7370 IMAGEMAGICK_LAST
7373 /* Vector of image_keyword structures describing the format
7374 of valid user-defined image specifications. */
7376 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7378 {":type", IMAGE_SYMBOL_VALUE, 1},
7379 {":data", IMAGE_STRING_VALUE, 0},
7380 {":file", IMAGE_STRING_VALUE, 0},
7381 {":ascent", IMAGE_ASCENT_VALUE, 0},
7382 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7383 {":relief", IMAGE_INTEGER_VALUE, 0},
7384 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7385 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7386 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7387 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7388 {":height", IMAGE_INTEGER_VALUE, 0},
7389 {":width", IMAGE_INTEGER_VALUE, 0},
7390 {":rotation", IMAGE_NUMBER_VALUE, 0},
7391 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7394 /* Free X resources of imagemagick image IMG which is used on frame F. */
7396 static void
7397 imagemagick_clear_image (struct frame *f,
7398 struct image *img)
7400 x_clear_image (f, img);
7403 /* Return non-zero if OBJECT is a valid IMAGEMAGICK image specification. Do
7404 this by calling parse_image_spec and supplying the keywords that
7405 identify the IMAGEMAGICK format. */
7407 static int
7408 imagemagick_image_p (Lisp_Object object)
7410 struct image_keyword fmt[IMAGEMAGICK_LAST];
7411 memcpy (fmt, imagemagick_format, sizeof fmt);
7413 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7414 return 0;
7416 /* Must specify either the :data or :file keyword. */
7417 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7420 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7421 Therefore rename the function so it doesnt collide with ImageMagick. */
7422 #define DrawRectangle DrawRectangleGif
7423 #include <wand/MagickWand.h>
7425 /* imagemagick_load_image is a helper function for imagemagick_load,
7426 which does the actual loading given contents and size, apart from
7427 frame and image structures, passed from imagemagick_load.
7429 Uses librimagemagick to do most of the image processing.
7431 Return non-zero if successful.
7434 static int
7435 imagemagick_load_image (/* Pointer to emacs frame structure. */
7436 struct frame *f,
7437 /* Pointer to emacs image structure. */
7438 struct image *img,
7439 /* String containing the IMAGEMAGICK data to
7440 be parsed. */
7441 unsigned char *contents,
7442 /* Size of data in bytes. */
7443 unsigned int size,
7444 /* Filename, either pass filename or
7445 contents/size. */
7446 unsigned char *filename)
7448 unsigned long width;
7449 unsigned long height;
7451 MagickBooleanType
7452 status;
7454 XImagePtr ximg;
7455 Lisp_Object specified_bg;
7456 XColor background;
7457 int x;
7458 int y;
7460 MagickWand *image_wand;
7461 MagickWand *ping_wand;
7462 PixelIterator *iterator;
7463 PixelWand **pixels;
7464 MagickPixelPacket pixel;
7465 Lisp_Object image;
7466 Lisp_Object value;
7467 Lisp_Object crop, geometry;
7468 long ino;
7469 int desired_width, desired_height;
7470 double rotation;
7471 int imagemagick_rendermethod;
7472 int pixelwidth;
7473 ImageInfo *image_info;
7474 ExceptionInfo *exception;
7475 Image * im_image;
7478 /* Handle image index for image types who can contain more than one image.
7479 Interface :index is same as for GIF. First we "ping" the image to see how
7480 many sub-images it contains. Pinging is faster than loading the image to
7481 find out things about it. */
7483 /* Initialize the imagemagick environment. */
7484 MagickWandGenesis ();
7485 image = image_spec_value (img->spec, QCindex, NULL);
7486 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7487 ping_wand = NewMagickWand ();
7488 MagickSetResolution (ping_wand, 2, 2);
7489 if (filename != NULL)
7491 status = MagickPingImage (ping_wand, filename);
7493 else
7495 status = MagickPingImageBlob (ping_wand, contents, size);
7498 if (ino >= MagickGetNumberImages (ping_wand))
7500 image_error ("Invalid image number `%s' in image `%s'",
7501 image, img->spec);
7502 DestroyMagickWand (ping_wand);
7503 return 0;
7506 if (MagickGetNumberImages(ping_wand) > 1)
7507 img->data.lisp_val =
7508 Fcons (Qcount,
7509 Fcons (make_number (MagickGetNumberImages (ping_wand)),
7510 img->data.lisp_val));
7512 DestroyMagickWand (ping_wand);
7514 /* Now, after pinging, we know how many images are inside the
7515 file. If it's not a bundle, the number is one. */
7517 if (filename != NULL)
7519 image_info = CloneImageInfo ((ImageInfo *) NULL);
7520 (void) strcpy (image_info->filename, filename);
7521 image_info->number_scenes = 1;
7522 image_info->scene = ino;
7523 exception = AcquireExceptionInfo ();
7525 im_image = ReadImage (image_info, exception);
7526 DestroyExceptionInfo (exception);
7528 if (im_image != NULL)
7530 image_wand = NewMagickWandFromImage (im_image);
7531 DestroyImage(im_image);
7532 status = MagickTrue;
7534 else
7535 status = MagickFalse;
7537 else
7539 image_wand = NewMagickWand ();
7540 status = MagickReadImageBlob (image_wand, contents, size);
7543 if (status == MagickFalse) goto imagemagick_error;
7545 /* If width and/or height is set in the display spec assume we want
7546 to scale to those values. If either h or w is unspecified, the
7547 unspecified should be calculated from the specified to preserve
7548 aspect ratio. */
7550 value = image_spec_value (img->spec, QCwidth, NULL);
7551 desired_width = (INTEGERP (value) ? XFASTINT (value) : -1);
7552 value = image_spec_value (img->spec, QCheight, NULL);
7553 desired_height = (INTEGERP (value) ? XFASTINT (value) : -1);
7555 height = MagickGetImageHeight (image_wand);
7556 width = MagickGetImageWidth (image_wand);
7558 if (desired_width != -1 && desired_height == -1)
7559 /* w known, calculate h. */
7560 desired_height = (double) desired_width / width * height;
7561 if (desired_width == -1 && desired_height != -1)
7562 /* h known, calculate w. */
7563 desired_width = (double) desired_height / height * width;
7564 if (desired_width != -1 && desired_height != -1)
7566 status = MagickScaleImage (image_wand, desired_width, desired_height);
7567 if (status == MagickFalse)
7569 image_error ("Imagemagick scale failed", Qnil, Qnil);
7570 goto imagemagick_error;
7574 /* crop behaves similar to image slicing in Emacs but is more memory
7575 efficient. */
7576 crop = image_spec_value (img->spec, QCcrop, NULL);
7578 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7580 /* After some testing, it seems MagickCropImage is the fastest crop
7581 function in ImageMagick. This crop function seems to do less copying
7582 than the alternatives, but it still reads the entire image into memory
7583 before croping, which is aparently difficult to avoid when using
7584 imagemagick. */
7585 int w, h, x, y;
7586 w = XFASTINT (XCAR (crop));
7587 crop = XCDR (crop);
7588 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7590 h = XFASTINT (XCAR (crop));
7591 crop = XCDR (crop);
7592 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7594 x = XFASTINT (XCAR (crop));
7595 crop = XCDR (crop);
7596 if (CONSP (crop) && INTEGERP (XCAR (crop)))
7598 y = XFASTINT (XCAR (crop));
7599 MagickCropImage (image_wand, w, h, x, y);
7605 /* Furthermore :rotation. we need background color and angle for
7606 rotation. */
7608 TODO background handling for rotation specified_bg =
7609 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
7610 (specified_bg). */
7611 value = image_spec_value (img->spec, QCrotation, NULL);
7612 if (FLOATP (value))
7614 PixelWand* background = NewPixelWand ();
7615 PixelSetColor (background, "#ffffff");/*TODO remove hardcode*/
7617 rotation = extract_float (value);
7619 status = MagickRotateImage (image_wand, background, rotation);
7620 DestroyPixelWand (background);
7621 if (status == MagickFalse)
7623 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
7624 goto imagemagick_error;
7628 /* Finaly we are done manipulating the image, figure out resulting
7629 width, height, and then transfer ownerwship to Emacs. */
7630 height = MagickGetImageHeight (image_wand);
7631 width = MagickGetImageWidth (image_wand);
7633 if (! check_image_size (f, width, height))
7635 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7636 goto imagemagick_error;
7639 /* We can now get a valid pixel buffer from the imagemagick file, if all
7640 went ok. */
7642 init_color_table ();
7643 imagemagick_rendermethod = (INTEGERP (Vimagemagick_render_type)
7644 ? XFASTINT (Vimagemagick_render_type) : 0);
7645 if (imagemagick_rendermethod == 0)
7647 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7648 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7649 &ximg, &img->pixmap))
7651 #ifdef COLOR_TABLE_SUPPORT
7652 free_color_table ();
7653 #endif
7654 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7655 goto imagemagick_error;
7658 /* Copy imagegmagick image to x with primitive yet robust pixel
7659 pusher loop. This has been tested a lot with many different
7660 images. */
7662 /* Copy pixels from the imagemagick image structure to the x image map. */
7663 iterator = NewPixelIterator (image_wand);
7664 if (iterator == (PixelIterator *) NULL)
7666 #ifdef COLOR_TABLE_SUPPORT
7667 free_color_table ();
7668 #endif
7669 x_destroy_x_image (ximg);
7670 image_error ("Imagemagick pixel iterator creation failed",
7671 Qnil, Qnil);
7672 goto imagemagick_error;
7675 for (y = 0; y < (long) MagickGetImageHeight (image_wand); y++)
7677 pixels = PixelGetNextIteratorRow (iterator, &width);
7678 if (pixels == (PixelWand **) NULL)
7679 break;
7680 for (x = 0; x < (long) width; x++)
7682 PixelGetMagickColor (pixels[x], &pixel);
7683 XPutPixel (ximg, x, y,
7684 lookup_rgb_color (f,
7685 pixel.red,
7686 pixel.green,
7687 pixel.blue));
7690 DestroyPixelIterator (iterator);
7693 if (imagemagick_rendermethod == 1)
7695 /* Magicexportimage is normaly faster than pixelpushing. This
7696 method is also well tested. Some aspects of this method are
7697 ad-hoc and needs to be more researched. */
7698 int imagedepth = 24;/*MagickGetImageDepth(image_wand);*/
7699 char* exportdepth = imagedepth <= 8 ? "I" : "BGRP";/*"RGBP";*/
7700 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7701 if (!x_create_x_image_and_pixmap (f, width, height, imagedepth,
7702 &ximg, &img->pixmap))
7704 #ifdef COLOR_TABLE_SUPPORT
7705 free_color_table ();
7706 #endif
7707 image_error("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7708 goto imagemagick_error;
7712 /* Oddly, the below code doesnt seem to work:*/
7713 /* switch(ximg->bitmap_unit){ */
7714 /* case 8: */
7715 /* pixelwidth=CharPixel; */
7716 /* break; */
7717 /* case 16: */
7718 /* pixelwidth=ShortPixel; */
7719 /* break; */
7720 /* case 32: */
7721 /* pixelwidth=LongPixel; */
7722 /* break; */
7723 /* } */
7725 Here im just guessing the format of the bitmap.
7726 happens to work fine for:
7727 - bw djvu images
7728 on rgb display.
7729 seems about 3 times as fast as pixel pushing(not carefully measured)
7731 pixelwidth = CharPixel;/*??? TODO figure out*/
7732 #ifdef HAVE_MAGICKEXPORTIMAGEPIXELS
7733 MagickExportImagePixels (image_wand,
7734 0, 0,
7735 width, height,
7736 exportdepth,
7737 pixelwidth,
7738 /*&(img->pixmap));*/
7739 ximg->data);
7740 #else
7741 image_error ("You dont have MagickExportImagePixels, upgrade ImageMagick!",
7742 Qnil, Qnil);
7743 #endif
7747 #ifdef COLOR_TABLE_SUPPORT
7748 /* Remember colors allocated for this image. */
7749 img->colors = colors_in_color_table (&img->ncolors);
7750 free_color_table ();
7751 #endif /* COLOR_TABLE_SUPPORT */
7754 img->width = width;
7755 img->height = height;
7757 /* Put the image into the pixmap, then free the X image and its
7758 buffer. */
7759 x_put_x_image (f, ximg, img->pixmap, width, height);
7760 x_destroy_x_image (ximg);
7763 /* Final cleanup. image_wand should be the only resource left. */
7764 DestroyMagickWand (image_wand);
7765 /* `MagickWandTerminus' terminates the imagemagick environment. */
7766 MagickWandTerminus ();
7768 return 1;
7770 imagemagick_error:
7771 DestroyMagickWand (image_wand);
7772 MagickWandTerminus ();
7773 /* TODO more cleanup. */
7774 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
7775 return 0;
7779 /* Load IMAGEMAGICK image IMG for use on frame F. Value is non-zero if
7780 successful. this function will go into the imagemagick_type structure, and
7781 the prototype thus needs to be compatible with that structure. */
7783 static int
7784 imagemagick_load (struct frame *f,
7785 struct image *img)
7787 int success_p = 0;
7788 Lisp_Object file_name;
7790 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7791 file_name = image_spec_value (img->spec, QCfile, NULL);
7792 if (STRINGP (file_name))
7794 Lisp_Object file;
7796 file = x_find_image_file (file_name);
7797 if (!STRINGP (file))
7799 image_error ("Cannot find image file `%s'", file_name, Qnil);
7800 return 0;
7802 success_p = imagemagick_load_image (f, img, 0, 0, SDATA (file));
7804 /* Else its not a file, its a lisp object. Load the image from a
7805 lisp object rather than a file. */
7806 else
7808 Lisp_Object data;
7810 data = image_spec_value (img->spec, QCdata, NULL);
7811 if (!STRINGP (data))
7813 image_error ("Invalid image data `%s'", data, Qnil);
7814 return 0;
7816 success_p = imagemagick_load_image (f, img, SDATA (data),
7817 SBYTES (data), NULL);
7820 return success_p;
7823 /* Structure describing the image type `imagemagick'. Its the same
7824 type of structure defined for all image formats, handled by Emacs
7825 image functions. See struct image_type in dispextern.h. */
7827 static struct image_type imagemagick_type =
7829 /* An identifier showing that this is an image structure for the
7830 IMAGEMAGICK format. */
7831 &Qimagemagick,
7832 /* Handle to a function that can be used to identify a IMAGEMAGICK
7833 file. */
7834 imagemagick_image_p,
7835 /* Handle to function used to load a IMAGEMAGICK file. */
7836 imagemagick_load,
7837 /* Handle to function to free resources for IMAGEMAGICK. */
7838 imagemagick_clear_image,
7839 /* An internal field to link to the next image type in a list of
7840 image types, will be filled in when registering the format. */
7841 NULL
7845 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
7846 doc: /* Return the image types supported by ImageMagick.
7847 Note that ImageMagick recognizes many file-types that Emacs does not recognize
7848 as images, such as .c. */)
7849 (void)
7851 Lisp_Object typelist = Qnil;
7852 unsigned long numf;
7853 ExceptionInfo ex;
7854 char **imtypes = GetMagickList ("*", &numf, &ex);
7855 int i;
7856 Lisp_Object Qimagemagicktype;
7857 for (i = 0; i < numf; i++)
7859 Qimagemagicktype = intern (imtypes[i]);
7860 typelist = Fcons (Qimagemagicktype, typelist);
7862 return typelist;
7865 #endif /* defined (HAVE_IMAGEMAGICK) */
7869 /***********************************************************************
7871 ***********************************************************************/
7873 #if defined (HAVE_RSVG)
7875 /* Function prototypes. */
7877 static int svg_image_p (Lisp_Object object);
7878 static int svg_load (struct frame *f, struct image *img);
7880 static int svg_load_image (struct frame *, struct image *,
7881 unsigned char *, unsigned int);
7883 /* The symbol `svg' identifying images of this type. */
7885 Lisp_Object Qsvg;
7887 /* Indices of image specification fields in svg_format, below. */
7889 enum svg_keyword_index
7891 SVG_TYPE,
7892 SVG_DATA,
7893 SVG_FILE,
7894 SVG_ASCENT,
7895 SVG_MARGIN,
7896 SVG_RELIEF,
7897 SVG_ALGORITHM,
7898 SVG_HEURISTIC_MASK,
7899 SVG_MASK,
7900 SVG_BACKGROUND,
7901 SVG_LAST
7904 /* Vector of image_keyword structures describing the format
7905 of valid user-defined image specifications. */
7907 static const struct image_keyword svg_format[SVG_LAST] =
7909 {":type", IMAGE_SYMBOL_VALUE, 1},
7910 {":data", IMAGE_STRING_VALUE, 0},
7911 {":file", IMAGE_STRING_VALUE, 0},
7912 {":ascent", IMAGE_ASCENT_VALUE, 0},
7913 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7914 {":relief", IMAGE_INTEGER_VALUE, 0},
7915 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7916 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7917 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7918 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7921 /* Structure describing the image type `svg'. Its the same type of
7922 structure defined for all image formats, handled by emacs image
7923 functions. See struct image_type in dispextern.h. */
7925 static struct image_type svg_type =
7927 /* An identifier showing that this is an image structure for the SVG format. */
7928 &Qsvg,
7929 /* Handle to a function that can be used to identify a SVG file. */
7930 svg_image_p,
7931 /* Handle to function used to load a SVG file. */
7932 svg_load,
7933 /* Handle to function to free sresources for SVG. */
7934 x_clear_image,
7935 /* An internal field to link to the next image type in a list of
7936 image types, will be filled in when registering the format. */
7937 NULL
7941 /* Return non-zero if OBJECT is a valid SVG image specification. Do
7942 this by calling parse_image_spec and supplying the keywords that
7943 identify the SVG format. */
7945 static int
7946 svg_image_p (Lisp_Object object)
7948 struct image_keyword fmt[SVG_LAST];
7949 memcpy (fmt, svg_format, sizeof fmt);
7951 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
7952 return 0;
7954 /* Must specify either the :data or :file keyword. */
7955 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
7958 #include <librsvg/rsvg.h>
7960 #ifdef HAVE_NTGUI
7962 /* SVG library functions. */
7963 DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new);
7964 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions);
7965 DEF_IMGLIB_FN (gboolean, rsvg_handle_write);
7966 DEF_IMGLIB_FN (gboolean, rsvg_handle_close);
7967 DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf);
7968 DEF_IMGLIB_FN (void, rsvg_handle_free);
7970 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width);
7971 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height);
7972 DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels);
7973 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride);
7974 DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace);
7975 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels);
7976 DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha);
7977 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample);
7979 DEF_IMGLIB_FN (void, g_type_init);
7980 DEF_IMGLIB_FN (void, g_object_unref);
7981 DEF_IMGLIB_FN (void, g_error_free);
7983 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
7985 static int
7986 init_svg_functions (Lisp_Object libraries)
7988 HMODULE library, gdklib, glib, gobject;
7990 if (!(glib = w32_delayed_load (libraries, Qglib))
7991 || !(gobject = w32_delayed_load (libraries, Qgobject))
7992 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
7993 || !(library = w32_delayed_load (libraries, Qsvg)))
7994 return 0;
7996 LOAD_IMGLIB_FN (library, rsvg_handle_new);
7997 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
7998 LOAD_IMGLIB_FN (library, rsvg_handle_write);
7999 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8000 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8001 LOAD_IMGLIB_FN (library, rsvg_handle_free);
8003 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8004 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8005 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8006 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8007 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8008 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8009 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8010 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8012 LOAD_IMGLIB_FN (gobject, g_type_init);
8013 LOAD_IMGLIB_FN (gobject, g_object_unref);
8014 LOAD_IMGLIB_FN (glib, g_error_free);
8016 return 1;
8019 #else
8020 /* The following aliases for library functions allow dynamic loading
8021 to be used on some platforms. */
8022 #define fn_rsvg_handle_new rsvg_handle_new
8023 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8024 #define fn_rsvg_handle_write rsvg_handle_write
8025 #define fn_rsvg_handle_close rsvg_handle_close
8026 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8027 #define fn_rsvg_handle_free rsvg_handle_free
8029 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8030 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8031 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8032 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8033 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8034 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8035 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8036 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8038 #define fn_g_type_init g_type_init
8039 #define fn_g_object_unref g_object_unref
8040 #define fn_g_error_free g_error_free
8041 #endif /* !HAVE_NTGUI */
8043 /* Load SVG image IMG for use on frame F. Value is non-zero if
8044 successful. this function will go into the svg_type structure, and
8045 the prototype thus needs to be compatible with that structure. */
8047 static int
8048 svg_load (struct frame *f, struct image *img)
8050 int success_p = 0;
8051 Lisp_Object file_name;
8053 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8054 file_name = image_spec_value (img->spec, QCfile, NULL);
8055 if (STRINGP (file_name))
8057 Lisp_Object file;
8058 unsigned char *contents;
8059 int size;
8061 file = x_find_image_file (file_name);
8062 if (!STRINGP (file))
8064 image_error ("Cannot find image file `%s'", file_name, Qnil);
8065 return 0;
8068 /* Read the entire file into memory. */
8069 contents = slurp_file (SDATA (file), &size);
8070 if (contents == NULL)
8072 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8073 return 0;
8075 /* If the file was slurped into memory properly, parse it. */
8076 success_p = svg_load_image (f, img, contents, size);
8077 xfree (contents);
8079 /* Else its not a file, its a lisp object. Load the image from a
8080 lisp object rather than a file. */
8081 else
8083 Lisp_Object data;
8085 data = image_spec_value (img->spec, QCdata, NULL);
8086 if (!STRINGP (data))
8088 image_error ("Invalid image data `%s'", data, Qnil);
8089 return 0;
8091 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8094 return success_p;
8097 /* svg_load_image is a helper function for svg_load, which does the
8098 actual loading given contents and size, apart from frame and image
8099 structures, passed from svg_load.
8101 Uses librsvg to do most of the image processing.
8103 Returns non-zero when successful. */
8104 static int
8105 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8106 struct image *img, /* Pointer to emacs image structure. */
8107 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8108 unsigned int size) /* Size of data in bytes. */
8110 RsvgHandle *rsvg_handle;
8111 RsvgDimensionData dimension_data;
8112 GError *error = NULL;
8113 GdkPixbuf *pixbuf;
8114 int width;
8115 int height;
8116 const guint8 *pixels;
8117 int rowstride;
8118 XImagePtr ximg;
8119 Lisp_Object specified_bg;
8120 XColor background;
8121 int x;
8122 int y;
8124 /* g_type_init is a glib function that must be called prior to using
8125 gnome type library functions. */
8126 fn_g_type_init ();
8127 /* Make a handle to a new rsvg object. */
8128 rsvg_handle = fn_rsvg_handle_new ();
8130 /* Parse the contents argument and fill in the rsvg_handle. */
8131 fn_rsvg_handle_write (rsvg_handle, contents, size, &error);
8132 if (error) goto rsvg_error;
8134 /* The parsing is complete, rsvg_handle is ready to used, close it
8135 for further writes. */
8136 fn_rsvg_handle_close (rsvg_handle, &error);
8137 if (error) goto rsvg_error;
8139 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8140 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8142 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8143 goto rsvg_error;
8146 /* We can now get a valid pixel buffer from the svg file, if all
8147 went ok. */
8148 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8149 if (!pixbuf) goto rsvg_error;
8150 fn_g_object_unref (rsvg_handle);
8152 /* Extract some meta data from the svg handle. */
8153 width = fn_gdk_pixbuf_get_width (pixbuf);
8154 height = fn_gdk_pixbuf_get_height (pixbuf);
8155 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8156 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8158 /* Validate the svg meta data. */
8159 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8160 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8161 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8162 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8164 /* Try to create a x pixmap to hold the svg pixmap. */
8165 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8167 fn_g_object_unref (pixbuf);
8168 return 0;
8171 init_color_table ();
8173 /* Handle alpha channel by combining the image with a background
8174 color. */
8175 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8176 if (!STRINGP (specified_bg)
8177 || !x_defined_color (f, SDATA (specified_bg), &background, 0))
8179 #ifndef HAVE_NS
8180 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8181 x_query_color (f, &background);
8182 #else
8183 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8184 #endif
8187 /* SVG pixmaps specify transparency in the last byte, so right
8188 shift 8 bits to get rid of it, since emacs doesn't support
8189 transparency. */
8190 background.red >>= 8;
8191 background.green >>= 8;
8192 background.blue >>= 8;
8194 /* This loop handles opacity values, since Emacs assumes
8195 non-transparent images. Each pixel must be "flattened" by
8196 calculating the resulting color, given the transparency of the
8197 pixel, and the image background color. */
8198 for (y = 0; y < height; ++y)
8200 for (x = 0; x < width; ++x)
8202 unsigned red;
8203 unsigned green;
8204 unsigned blue;
8205 unsigned opacity;
8207 red = *pixels++;
8208 green = *pixels++;
8209 blue = *pixels++;
8210 opacity = *pixels++;
8212 red = ((red * opacity)
8213 + (background.red * ((1 << 8) - opacity)));
8214 green = ((green * opacity)
8215 + (background.green * ((1 << 8) - opacity)));
8216 blue = ((blue * opacity)
8217 + (background.blue * ((1 << 8) - opacity)));
8219 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8222 pixels += rowstride - 4 * width;
8225 #ifdef COLOR_TABLE_SUPPORT
8226 /* Remember colors allocated for this image. */
8227 img->colors = colors_in_color_table (&img->ncolors);
8228 free_color_table ();
8229 #endif /* COLOR_TABLE_SUPPORT */
8231 fn_g_object_unref (pixbuf);
8233 img->width = width;
8234 img->height = height;
8236 /* Maybe fill in the background field while we have ximg handy.
8237 Casting avoids a GCC warning. */
8238 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8240 /* Put the image into the pixmap, then free the X image and its
8241 buffer. */
8242 x_put_x_image (f, ximg, img->pixmap, width, height);
8243 x_destroy_x_image (ximg);
8245 return 1;
8247 rsvg_error:
8248 fn_g_object_unref (rsvg_handle);
8249 /* FIXME: Use error->message so the user knows what is the actual
8250 problem with the image. */
8251 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8252 fn_g_error_free (error);
8253 return 0;
8256 #endif /* defined (HAVE_RSVG) */
8261 /***********************************************************************
8262 Ghostscript
8263 ***********************************************************************/
8265 #ifdef HAVE_X_WINDOWS
8266 #define HAVE_GHOSTSCRIPT 1
8267 #endif /* HAVE_X_WINDOWS */
8269 #ifdef HAVE_GHOSTSCRIPT
8271 static int gs_image_p (Lisp_Object object);
8272 static int gs_load (struct frame *f, struct image *img);
8273 static void gs_clear_image (struct frame *f, struct image *img);
8275 /* Keyword symbols. */
8277 static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8279 /* Indices of image specification fields in gs_format, below. */
8281 enum gs_keyword_index
8283 GS_TYPE,
8284 GS_PT_WIDTH,
8285 GS_PT_HEIGHT,
8286 GS_FILE,
8287 GS_LOADER,
8288 GS_BOUNDING_BOX,
8289 GS_ASCENT,
8290 GS_MARGIN,
8291 GS_RELIEF,
8292 GS_ALGORITHM,
8293 GS_HEURISTIC_MASK,
8294 GS_MASK,
8295 GS_BACKGROUND,
8296 GS_LAST
8299 /* Vector of image_keyword structures describing the format
8300 of valid user-defined image specifications. */
8302 static const struct image_keyword gs_format[GS_LAST] =
8304 {":type", IMAGE_SYMBOL_VALUE, 1},
8305 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8306 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8307 {":file", IMAGE_STRING_VALUE, 1},
8308 {":loader", IMAGE_FUNCTION_VALUE, 0},
8309 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8310 {":ascent", IMAGE_ASCENT_VALUE, 0},
8311 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8312 {":relief", IMAGE_INTEGER_VALUE, 0},
8313 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8314 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8315 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8316 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8319 /* Structure describing the image type `ghostscript'. */
8321 static struct image_type gs_type =
8323 &Qpostscript,
8324 gs_image_p,
8325 gs_load,
8326 gs_clear_image,
8327 NULL
8331 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8333 static void
8334 gs_clear_image (struct frame *f, struct image *img)
8336 /* IMG->data.ptr_val may contain a recorded colormap. */
8337 xfree (img->data.ptr_val);
8338 x_clear_image (f, img);
8342 /* Return non-zero if OBJECT is a valid Ghostscript image
8343 specification. */
8345 static int
8346 gs_image_p (Lisp_Object object)
8348 struct image_keyword fmt[GS_LAST];
8349 Lisp_Object tem;
8350 int i;
8352 memcpy (fmt, gs_format, sizeof fmt);
8354 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8355 return 0;
8357 /* Bounding box must be a list or vector containing 4 integers. */
8358 tem = fmt[GS_BOUNDING_BOX].value;
8359 if (CONSP (tem))
8361 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8362 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8363 return 0;
8364 if (!NILP (tem))
8365 return 0;
8367 else if (VECTORP (tem))
8369 if (ASIZE (tem) != 4)
8370 return 0;
8371 for (i = 0; i < 4; ++i)
8372 if (!INTEGERP (XVECTOR (tem)->contents[i]))
8373 return 0;
8375 else
8376 return 0;
8378 return 1;
8382 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8383 if successful. */
8385 static int
8386 gs_load (struct frame *f, struct image *img)
8388 char buffer[100];
8389 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8390 Lisp_Object frame;
8391 double in_width, in_height;
8392 Lisp_Object pixel_colors = Qnil;
8394 /* Compute pixel size of pixmap needed from the given size in the
8395 image specification. Sizes in the specification are in pt. 1 pt
8396 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8397 info. */
8398 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8399 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
8400 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
8401 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8402 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
8403 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
8405 if (!check_image_size (f, img->width, img->height))
8407 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8408 return 0;
8411 /* Create the pixmap. */
8412 xassert (img->pixmap == NO_PIXMAP);
8414 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8415 BLOCK_INPUT;
8416 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8417 img->width, img->height,
8418 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8419 UNBLOCK_INPUT;
8421 if (!img->pixmap)
8423 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8424 return 0;
8427 /* Call the loader to fill the pixmap. It returns a process object
8428 if successful. We do not record_unwind_protect here because
8429 other places in redisplay like calling window scroll functions
8430 don't either. Let the Lisp loader use `unwind-protect' instead. */
8431 sprintf (buffer, "%lu %lu",
8432 (unsigned long) FRAME_X_WINDOW (f),
8433 (unsigned long) img->pixmap);
8434 window_and_pixmap_id = build_string (buffer);
8436 sprintf (buffer, "%lu %lu",
8437 FRAME_FOREGROUND_PIXEL (f),
8438 FRAME_BACKGROUND_PIXEL (f));
8439 pixel_colors = build_string (buffer);
8441 XSETFRAME (frame, f);
8442 loader = image_spec_value (img->spec, QCloader, NULL);
8443 if (NILP (loader))
8444 loader = intern ("gs-load-image");
8446 img->data.lisp_val = call6 (loader, frame, img->spec,
8447 make_number (img->width),
8448 make_number (img->height),
8449 window_and_pixmap_id,
8450 pixel_colors);
8451 return PROCESSP (img->data.lisp_val);
8455 /* Kill the Ghostscript process that was started to fill PIXMAP on
8456 frame F. Called from XTread_socket when receiving an event
8457 telling Emacs that Ghostscript has finished drawing. */
8459 void
8460 x_kill_gs_process (Pixmap pixmap, struct frame *f)
8462 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8463 int class, i;
8464 struct image *img;
8466 /* Find the image containing PIXMAP. */
8467 for (i = 0; i < c->used; ++i)
8468 if (c->images[i]->pixmap == pixmap)
8469 break;
8471 /* Should someone in between have cleared the image cache, for
8472 instance, give up. */
8473 if (i == c->used)
8474 return;
8476 /* Kill the GS process. We should have found PIXMAP in the image
8477 cache and its image should contain a process object. */
8478 img = c->images[i];
8479 xassert (PROCESSP (img->data.lisp_val));
8480 Fkill_process (img->data.lisp_val, Qnil);
8481 img->data.lisp_val = Qnil;
8483 #if defined (HAVE_X_WINDOWS)
8485 /* On displays with a mutable colormap, figure out the colors
8486 allocated for the image by looking at the pixels of an XImage for
8487 img->pixmap. */
8488 class = FRAME_X_VISUAL (f)->class;
8489 if (class != StaticColor && class != StaticGray && class != TrueColor)
8491 XImagePtr ximg;
8493 BLOCK_INPUT;
8495 /* Try to get an XImage for img->pixmep. */
8496 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8497 0, 0, img->width, img->height, ~0, ZPixmap);
8498 if (ximg)
8500 int x, y;
8502 /* Initialize the color table. */
8503 init_color_table ();
8505 /* For each pixel of the image, look its color up in the
8506 color table. After having done so, the color table will
8507 contain an entry for each color used by the image. */
8508 for (y = 0; y < img->height; ++y)
8509 for (x = 0; x < img->width; ++x)
8511 unsigned long pixel = XGetPixel (ximg, x, y);
8512 lookup_pixel_color (f, pixel);
8515 /* Record colors in the image. Free color table and XImage. */
8516 #ifdef COLOR_TABLE_SUPPORT
8517 img->colors = colors_in_color_table (&img->ncolors);
8518 free_color_table ();
8519 #endif
8520 XDestroyImage (ximg);
8522 #if 0 /* This doesn't seem to be the case. If we free the colors
8523 here, we get a BadAccess later in x_clear_image when
8524 freeing the colors. */
8525 /* We have allocated colors once, but Ghostscript has also
8526 allocated colors on behalf of us. So, to get the
8527 reference counts right, free them once. */
8528 if (img->ncolors)
8529 x_free_colors (f, img->colors, img->ncolors);
8530 #endif
8532 else
8533 image_error ("Cannot get X image of `%s'; colors will not be freed",
8534 img->spec, Qnil);
8536 UNBLOCK_INPUT;
8538 #endif /* HAVE_X_WINDOWS */
8540 /* Now that we have the pixmap, compute mask and transform the
8541 image if requested. */
8542 BLOCK_INPUT;
8543 postprocess_image (f, img);
8544 UNBLOCK_INPUT;
8547 #endif /* HAVE_GHOSTSCRIPT */
8550 /***********************************************************************
8551 Tests
8552 ***********************************************************************/
8554 #if GLYPH_DEBUG
8556 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8557 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8558 (Lisp_Object spec)
8560 return valid_image_p (spec) ? Qt : Qnil;
8564 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8565 (Lisp_Object spec)
8567 int id = -1;
8569 if (valid_image_p (spec))
8570 id = lookup_image (SELECTED_FRAME (), spec);
8572 debug_print (spec);
8573 return make_number (id);
8576 #endif /* GLYPH_DEBUG != 0 */
8579 /***********************************************************************
8580 Initialization
8581 ***********************************************************************/
8583 #ifdef HAVE_NTGUI
8584 /* Image types that rely on external libraries are loaded dynamically
8585 if the library is available. */
8586 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8587 define_image_type (image_type, init_lib_fn (libraries))
8588 #else
8589 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8590 define_image_type (image_type, 1)
8591 #endif /* HAVE_NTGUI */
8593 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8594 doc: /* Initialize image library implementing image type TYPE.
8595 Return non-nil if TYPE is a supported image type.
8597 Image types pbm and xbm are prebuilt; other types are loaded here.
8598 Libraries to load are specified in alist LIBRARIES (usually, the value
8599 of `dynamic-library-alist', which see). */)
8600 (Lisp_Object type, Lisp_Object libraries)
8602 Lisp_Object tested;
8604 /* Don't try to reload the library. */
8605 tested = Fassq (type, Vlibrary_cache);
8606 if (CONSP (tested))
8607 return XCDR (tested);
8609 #if defined (HAVE_XPM) || defined (HAVE_NS)
8610 if (EQ (type, Qxpm))
8611 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8612 #endif
8614 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8615 if (EQ (type, Qjpeg))
8616 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8617 #endif
8619 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8620 if (EQ (type, Qtiff))
8621 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8622 #endif
8624 #if defined (HAVE_GIF) || defined (HAVE_NS)
8625 if (EQ (type, Qgif))
8626 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8627 #endif
8629 #if defined (HAVE_PNG) || defined (HAVE_NS)
8630 if (EQ (type, Qpng))
8631 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8632 #endif
8634 #if defined (HAVE_RSVG)
8635 if (EQ (type, Qsvg))
8636 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
8637 #endif
8639 #if defined (HAVE_IMAGEMAGICK)
8640 if (EQ (type, Qimagemagick))
8642 return CHECK_LIB_AVAILABLE (&imagemagick_type, init_imagemagick_functions,
8643 libraries);
8645 #endif
8647 #ifdef HAVE_GHOSTSCRIPT
8648 if (EQ (type, Qpostscript))
8649 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8650 #endif
8652 /* If the type is not recognized, avoid testing it ever again. */
8653 CACHE_IMAGE_TYPE (type, Qnil);
8654 return Qnil;
8657 void
8658 syms_of_image (void)
8660 /* Initialize this only once, since that's what we do with Vimage_types
8661 and they are supposed to be in sync. Initializing here gives correct
8662 operation on GNU/Linux of calling dump-emacs after loading some images. */
8663 image_types = NULL;
8665 /* Must be defined now becase we're going to update it below, while
8666 defining the supported image types. */
8667 DEFVAR_LISP ("image-types", Vimage_types,
8668 doc: /* List of potentially supported image types.
8669 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8670 To check whether it is really supported, use `image-type-available-p'. */);
8671 Vimage_types = Qnil;
8673 DEFVAR_LISP ("max-image-size", Vmax_image_size,
8674 doc: /* Maximum size of images.
8675 Emacs will not load an image into memory if its pixel width or
8676 pixel height exceeds this limit.
8678 If the value is an integer, it directly specifies the maximum
8679 image height and width, measured in pixels. If it is a floating
8680 point number, it specifies the maximum image height and width
8681 as a ratio to the frame height and width. If the value is
8682 non-numeric, there is no explicit limit on the size of images. */);
8683 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8685 Qpbm = intern_c_string ("pbm");
8686 staticpro (&Qpbm);
8687 ADD_IMAGE_TYPE (Qpbm);
8689 Qxbm = intern_c_string ("xbm");
8690 staticpro (&Qxbm);
8691 ADD_IMAGE_TYPE (Qxbm);
8693 define_image_type (&xbm_type, 1);
8694 define_image_type (&pbm_type, 1);
8696 Qcount = intern_c_string ("count");
8697 staticpro (&Qcount);
8698 Qextension_data = intern_c_string ("extension-data");
8699 staticpro (&Qextension_data);
8701 QCascent = intern_c_string (":ascent");
8702 staticpro (&QCascent);
8703 QCmargin = intern_c_string (":margin");
8704 staticpro (&QCmargin);
8705 QCrelief = intern_c_string (":relief");
8706 staticpro (&QCrelief);
8707 QCconversion = intern_c_string (":conversion");
8708 staticpro (&QCconversion);
8709 QCcolor_symbols = intern_c_string (":color-symbols");
8710 staticpro (&QCcolor_symbols);
8711 QCheuristic_mask = intern_c_string (":heuristic-mask");
8712 staticpro (&QCheuristic_mask);
8713 QCindex = intern_c_string (":index");
8714 staticpro (&QCindex);
8715 QCgeometry = intern_c_string (":geometry");
8716 staticpro (&QCgeometry);
8717 QCcrop = intern_c_string (":crop");
8718 staticpro (&QCcrop);
8719 QCrotation = intern_c_string (":rotation");
8720 staticpro (&QCrotation);
8721 QCmatrix = intern_c_string (":matrix");
8722 staticpro (&QCmatrix);
8723 QCcolor_adjustment = intern_c_string (":color-adjustment");
8724 staticpro (&QCcolor_adjustment);
8725 QCmask = intern_c_string (":mask");
8726 staticpro (&QCmask);
8728 Qlaplace = intern_c_string ("laplace");
8729 staticpro (&Qlaplace);
8730 Qemboss = intern_c_string ("emboss");
8731 staticpro (&Qemboss);
8732 Qedge_detection = intern_c_string ("edge-detection");
8733 staticpro (&Qedge_detection);
8734 Qheuristic = intern_c_string ("heuristic");
8735 staticpro (&Qheuristic);
8737 Qpostscript = intern_c_string ("postscript");
8738 staticpro (&Qpostscript);
8739 #ifdef HAVE_GHOSTSCRIPT
8740 ADD_IMAGE_TYPE (Qpostscript);
8741 QCloader = intern_c_string (":loader");
8742 staticpro (&QCloader);
8743 QCbounding_box = intern_c_string (":bounding-box");
8744 staticpro (&QCbounding_box);
8745 QCpt_width = intern_c_string (":pt-width");
8746 staticpro (&QCpt_width);
8747 QCpt_height = intern_c_string (":pt-height");
8748 staticpro (&QCpt_height);
8749 #endif /* HAVE_GHOSTSCRIPT */
8751 #ifdef HAVE_NTGUI
8752 Qlibpng_version = intern_c_string ("libpng-version");
8753 staticpro (&Qlibpng_version);
8754 Fset (Qlibpng_version,
8755 #if HAVE_PNG
8756 make_number (PNG_LIBPNG_VER)
8757 #else
8758 make_number (-1)
8759 #endif
8761 #endif
8763 #if defined (HAVE_XPM) || defined (HAVE_NS)
8764 Qxpm = intern_c_string ("xpm");
8765 staticpro (&Qxpm);
8766 ADD_IMAGE_TYPE (Qxpm);
8767 #endif
8769 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8770 Qjpeg = intern_c_string ("jpeg");
8771 staticpro (&Qjpeg);
8772 ADD_IMAGE_TYPE (Qjpeg);
8773 #endif
8775 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8776 Qtiff = intern_c_string ("tiff");
8777 staticpro (&Qtiff);
8778 ADD_IMAGE_TYPE (Qtiff);
8779 #endif
8781 #if defined (HAVE_GIF) || defined (HAVE_NS)
8782 Qgif = intern_c_string ("gif");
8783 staticpro (&Qgif);
8784 ADD_IMAGE_TYPE (Qgif);
8785 #endif
8787 #if defined (HAVE_PNG) || defined (HAVE_NS)
8788 Qpng = intern_c_string ("png");
8789 staticpro (&Qpng);
8790 ADD_IMAGE_TYPE (Qpng);
8791 #endif
8793 #if defined (HAVE_IMAGEMAGICK)
8794 Qimagemagick = intern_c_string ("imagemagick");
8795 staticpro (&Qimagemagick);
8796 ADD_IMAGE_TYPE (Qimagemagick);
8797 #endif
8799 #if defined (HAVE_RSVG)
8800 Qsvg = intern_c_string ("svg");
8801 staticpro (&Qsvg);
8802 ADD_IMAGE_TYPE (Qsvg);
8803 #ifdef HAVE_NTGUI
8804 /* Other libraries used directly by svg code. */
8805 Qgdk_pixbuf = intern_c_string ("gdk-pixbuf");
8806 staticpro (&Qgdk_pixbuf);
8807 Qglib = intern_c_string ("glib");
8808 staticpro (&Qglib);
8809 Qgobject = intern_c_string ("gobject");
8810 staticpro (&Qgobject);
8811 #endif /* HAVE_NTGUI */
8812 #endif /* HAVE_RSVG */
8814 defsubr (&Sinit_image_library);
8815 #ifdef HAVE_IMAGEMAGICK
8816 defsubr (&Simagemagick_types);
8817 #endif
8818 defsubr (&Sclear_image_cache);
8819 defsubr (&Simage_flush);
8820 defsubr (&Simage_size);
8821 defsubr (&Simage_mask_p);
8822 defsubr (&Simage_metadata);
8824 #if GLYPH_DEBUG
8825 defsubr (&Simagep);
8826 defsubr (&Slookup_image);
8827 #endif
8829 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
8830 doc: /* Non-nil means always draw a cross over disabled images.
8831 Disabled images are those having a `:conversion disabled' property.
8832 A cross is always drawn on black & white displays. */);
8833 cross_disabled_images = 0;
8835 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
8836 doc: /* List of directories to search for window system bitmap files. */);
8837 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8839 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
8840 doc: /* Maximum time after which images are removed from the cache.
8841 When an image has not been displayed this many seconds, Emacs
8842 automatically removes it from the image cache. If the cache contains
8843 a large number of images, the actual eviction time may be shorter.
8844 The value can also be nil, meaning the cache is never cleared.
8846 The function `clear-image-cache' disregards this variable. */);
8847 Vimage_cache_eviction_delay = make_number (300);
8848 #ifdef HAVE_IMAGEMAGICK
8849 DEFVAR_LISP ("imagemagick-render-type", Vimagemagick_render_type,
8850 doc: /* Choose between ImageMagick render methods. */);
8851 #endif
8855 void
8856 init_image (void)