Auto-commit of generated files.
[emacs.git] / src / image.c
blob8a318c2f6ecd628f2a6179b75f749e4703d8206a
1 /* Functions for image support on window system.
3 Copyright (C) 1989, 1992-2012 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <stdio.h>
22 #include <math.h>
23 #include <ctype.h>
24 #include <unistd.h>
26 #ifdef HAVE_PNG
27 #if defined HAVE_LIBPNG_PNG_H
28 # include <libpng/png.h>
29 #else
30 # include <png.h>
31 #endif
32 #endif
34 #include <setjmp.h>
36 /* This makes the fields of a Display accessible, in Xlib header files. */
38 #define XLIB_ILLEGAL_ACCESS
40 #include "lisp.h"
41 #include "frame.h"
42 #include "window.h"
43 #include "dispextern.h"
44 #include "blockinput.h"
45 #include "systime.h"
46 #include <epaths.h>
47 #include "character.h"
48 #include "coding.h"
49 #include "termhooks.h"
50 #include "font.h"
52 #ifdef HAVE_X_WINDOWS
53 #include "xterm.h"
54 #include <sys/types.h>
55 #include <sys/stat.h>
57 #define COLOR_TABLE_SUPPORT 1
59 typedef struct x_bitmap_record Bitmap_Record;
60 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
61 #define NO_PIXMAP None
63 #define RGB_PIXEL_COLOR unsigned long
65 #define PIX_MASK_RETAIN 0
66 #define PIX_MASK_DRAW 1
67 #endif /* HAVE_X_WINDOWS */
70 #ifdef HAVE_NTGUI
71 #include "w32.h"
72 #include "w32term.h"
74 /* W32_TODO : Color tables on W32. */
75 #undef COLOR_TABLE_SUPPORT
77 typedef struct w32_bitmap_record Bitmap_Record;
78 #define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
79 #define NO_PIXMAP 0
81 #define RGB_PIXEL_COLOR COLORREF
83 #define PIX_MASK_RETAIN 0
84 #define PIX_MASK_DRAW 1
86 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
87 #define x_defined_color w32_defined_color
88 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
90 /* Functions from w32term.c that depend on XColor (so can't go in w32term.h
91 without modifying lots of files). */
92 extern void x_query_colors (struct frame *f, XColor *colors, int ncolors);
93 extern void x_query_color (struct frame *f, XColor *color);
95 /* Version of libpng that we were compiled with, or -1 if no PNG
96 support was compiled in. This is tested by w32-win.el to correctly
97 set up the alist used to search for PNG libraries. */
98 Lisp_Object Qlibpng_version;
99 #endif /* HAVE_NTGUI */
101 #ifdef HAVE_NS
102 #include "nsterm.h"
103 #include <sys/types.h>
104 #include <sys/stat.h>
106 #undef COLOR_TABLE_SUPPORT
108 typedef struct ns_bitmap_record Bitmap_Record;
110 #define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
111 #define NO_PIXMAP 0
113 #define RGB_PIXEL_COLOR unsigned long
114 #define ZPixmap 0
116 #define PIX_MASK_RETAIN 0
117 #define PIX_MASK_DRAW 1
119 #define FRAME_X_VISUAL FRAME_NS_DISPLAY_INFO (f)->visual
120 #define x_defined_color(f, name, color_def, alloc) \
121 ns_defined_color (f, name, color_def, alloc, 0)
122 #define FRAME_X_SCREEN(f) 0
123 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
124 #endif /* HAVE_NS */
127 /* The symbol `postscript' identifying images of this type. */
129 static Lisp_Object Qpostscript;
131 static void x_disable_image (struct frame *, struct image *);
132 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
133 Lisp_Object);
135 static void init_color_table (void);
136 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
137 #ifdef COLOR_TABLE_SUPPORT
138 static void free_color_table (void);
139 static unsigned long *colors_in_color_table (int *n);
140 #endif
142 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
143 id, which is just an int that this section returns. Bitmaps are
144 reference counted so they can be shared among frames.
146 Bitmap indices are guaranteed to be > 0, so a negative number can
147 be used to indicate no bitmap.
149 If you use x_create_bitmap_from_data, then you must keep track of
150 the bitmaps yourself. That is, creating a bitmap from the same
151 data more than once will not be caught. */
153 #ifdef HAVE_NS
154 XImagePtr
155 XGetImage (Display *display, Pixmap pixmap, int x, int y,
156 unsigned int width, unsigned int height,
157 unsigned long plane_mask, int format)
159 /* TODO: not sure what this function is supposed to do.. */
160 ns_retain_object (pixmap);
161 return pixmap;
164 /* use with imgs created by ns_image_for_XPM */
165 unsigned long
166 XGetPixel (XImagePtr ximage, int x, int y)
168 return ns_get_pixel (ximage, x, y);
171 /* use with imgs created by ns_image_for_XPM; alpha set to 1;
172 pixel is assumed to be in form RGB */
173 void
174 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
176 ns_put_pixel (ximage, x, y, pixel);
178 #endif /* HAVE_NS */
181 /* Functions to access the contents of a bitmap, given an id. */
184 x_bitmap_height (FRAME_PTR f, ptrdiff_t id)
186 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
190 x_bitmap_width (FRAME_PTR f, ptrdiff_t id)
192 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
195 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
197 x_bitmap_pixmap (FRAME_PTR f, ptrdiff_t id)
199 /* HAVE_NTGUI needs the explicit cast here. */
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, ptrdiff_t 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 ptrdiff_t
215 x_allocate_bitmap_record (FRAME_PTR f)
217 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
218 ptrdiff_t i;
220 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
221 return ++dpyinfo->bitmaps_last;
223 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
224 if (dpyinfo->bitmaps[i].refcount == 0)
225 return i + 1;
227 dpyinfo->bitmaps =
228 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
229 10, -1, sizeof *dpyinfo->bitmaps);
230 return ++dpyinfo->bitmaps_last;
233 /* Add one reference to the reference count of the bitmap with id ID. */
235 void
236 x_reference_bitmap (FRAME_PTR f, ptrdiff_t id)
238 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
241 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
243 ptrdiff_t
244 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
246 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
247 ptrdiff_t id;
249 #ifdef HAVE_X_WINDOWS
250 Pixmap bitmap;
251 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
252 bits, width, height);
253 if (! bitmap)
254 return -1;
255 #endif /* HAVE_X_WINDOWS */
257 #ifdef HAVE_NTGUI
258 Pixmap bitmap;
259 bitmap = CreateBitmap (width, height,
260 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
261 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
262 bits);
263 if (! bitmap)
264 return -1;
265 #endif /* HAVE_NTGUI */
267 #ifdef HAVE_NS
268 void *bitmap = ns_image_from_XBM (bits, width, height);
269 if (!bitmap)
270 return -1;
271 #endif
273 id = x_allocate_bitmap_record (f);
275 #ifdef HAVE_NS
276 dpyinfo->bitmaps[id - 1].img = bitmap;
277 dpyinfo->bitmaps[id - 1].depth = 1;
278 #endif
280 dpyinfo->bitmaps[id - 1].file = NULL;
281 dpyinfo->bitmaps[id - 1].height = height;
282 dpyinfo->bitmaps[id - 1].width = width;
283 dpyinfo->bitmaps[id - 1].refcount = 1;
285 #ifdef HAVE_X_WINDOWS
286 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
287 dpyinfo->bitmaps[id - 1].have_mask = 0;
288 dpyinfo->bitmaps[id - 1].depth = 1;
289 #endif /* HAVE_X_WINDOWS */
291 #ifdef HAVE_NTGUI
292 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
293 dpyinfo->bitmaps[id - 1].hinst = NULL;
294 dpyinfo->bitmaps[id - 1].depth = 1;
295 #endif /* HAVE_NTGUI */
297 return id;
300 /* Create bitmap from file FILE for frame F. */
302 ptrdiff_t
303 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
305 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
307 #ifdef HAVE_NTGUI
308 return -1; /* W32_TODO : bitmap support */
309 #endif /* HAVE_NTGUI */
311 #ifdef HAVE_NS
312 ptrdiff_t id;
313 void *bitmap = ns_image_from_file (file);
315 if (!bitmap)
316 return -1;
319 id = x_allocate_bitmap_record (f);
320 dpyinfo->bitmaps[id - 1].img = bitmap;
321 dpyinfo->bitmaps[id - 1].refcount = 1;
322 dpyinfo->bitmaps[id - 1].file = xmalloc (SBYTES (file) + 1);
323 dpyinfo->bitmaps[id - 1].depth = 1;
324 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
325 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
326 strcpy (dpyinfo->bitmaps[id - 1].file, SSDATA (file));
327 return id;
328 #endif
330 #ifdef HAVE_X_WINDOWS
331 unsigned int width, height;
332 Pixmap bitmap;
333 int xhot, yhot, result;
334 ptrdiff_t id;
335 Lisp_Object found;
336 int fd;
337 char *filename;
339 /* Look for an existing bitmap with the same name. */
340 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
342 if (dpyinfo->bitmaps[id].refcount
343 && dpyinfo->bitmaps[id].file
344 && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
346 ++dpyinfo->bitmaps[id].refcount;
347 return id + 1;
351 /* Search bitmap-file-path for the file, if appropriate. */
352 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
353 if (fd < 0)
354 return -1;
355 emacs_close (fd);
357 filename = SSDATA (found);
359 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
360 filename, &width, &height, &bitmap, &xhot, &yhot);
361 if (result != BitmapSuccess)
362 return -1;
364 id = x_allocate_bitmap_record (f);
365 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
366 dpyinfo->bitmaps[id - 1].have_mask = 0;
367 dpyinfo->bitmaps[id - 1].refcount = 1;
368 dpyinfo->bitmaps[id - 1].file = xmalloc (SBYTES (file) + 1);
369 dpyinfo->bitmaps[id - 1].depth = 1;
370 dpyinfo->bitmaps[id - 1].height = height;
371 dpyinfo->bitmaps[id - 1].width = width;
372 strcpy (dpyinfo->bitmaps[id - 1].file, SSDATA (file));
374 return id;
375 #endif /* HAVE_X_WINDOWS */
378 /* Free bitmap B. */
380 static void
381 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
383 #ifdef HAVE_X_WINDOWS
384 XFreePixmap (dpyinfo->display, bm->pixmap);
385 if (bm->have_mask)
386 XFreePixmap (dpyinfo->display, bm->mask);
387 #endif /* HAVE_X_WINDOWS */
389 #ifdef HAVE_NTGUI
390 DeleteObject (bm->pixmap);
391 #endif /* HAVE_NTGUI */
393 #ifdef HAVE_NS
394 ns_release_object (bm->img);
395 #endif
397 if (bm->file)
399 xfree (bm->file);
400 bm->file = NULL;
404 /* Remove reference to bitmap with id number ID. */
406 void
407 x_destroy_bitmap (FRAME_PTR f, ptrdiff_t id)
409 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
411 if (id > 0)
413 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
415 if (--bm->refcount == 0)
417 BLOCK_INPUT;
418 free_bitmap_record (dpyinfo, bm);
419 UNBLOCK_INPUT;
424 /* Free all the bitmaps for the display specified by DPYINFO. */
426 void
427 x_destroy_all_bitmaps (Display_Info *dpyinfo)
429 ptrdiff_t i;
430 Bitmap_Record *bm = dpyinfo->bitmaps;
432 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
433 if (bm->refcount > 0)
434 free_bitmap_record (dpyinfo, bm);
436 dpyinfo->bitmaps_last = 0;
440 #ifdef HAVE_X_WINDOWS
442 /* Useful functions defined in the section
443 `Image type independent image structures' below. */
445 static unsigned long four_corners_best (XImagePtr ximg,
446 int *corners,
447 unsigned long width,
448 unsigned long height);
450 static int x_create_x_image_and_pixmap (struct frame *f, int width, int height,
451 int depth, XImagePtr *ximg,
452 Pixmap *pixmap);
454 static void x_destroy_x_image (XImagePtr ximg);
457 /* Create a mask of a bitmap. Note is this not a perfect mask.
458 It's nicer with some borders in this context */
461 x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
463 Pixmap pixmap, mask;
464 XImagePtr ximg, mask_img;
465 unsigned long width, height;
466 int result;
467 unsigned long bg;
468 unsigned long x, y, xp, xm, yp, ym;
469 GC gc;
471 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
473 if (!(id > 0))
474 return -1;
476 pixmap = x_bitmap_pixmap (f, id);
477 width = x_bitmap_width (f, id);
478 height = x_bitmap_height (f, id);
480 BLOCK_INPUT;
481 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
482 ~0, ZPixmap);
484 if (!ximg)
486 UNBLOCK_INPUT;
487 return -1;
490 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
492 UNBLOCK_INPUT;
493 if (!result)
495 XDestroyImage (ximg);
496 return -1;
499 bg = four_corners_best (ximg, NULL, width, height);
501 for (y = 0; y < ximg->height; ++y)
503 for (x = 0; x < ximg->width; ++x)
505 xp = x != ximg->width - 1 ? x + 1 : 0;
506 xm = x != 0 ? x - 1 : ximg->width - 1;
507 yp = y != ximg->height - 1 ? y + 1 : 0;
508 ym = y != 0 ? y - 1 : ximg->height - 1;
509 if (XGetPixel (ximg, x, y) == bg
510 && XGetPixel (ximg, x, yp) == bg
511 && XGetPixel (ximg, x, ym) == bg
512 && XGetPixel (ximg, xp, y) == bg
513 && XGetPixel (ximg, xp, yp) == bg
514 && XGetPixel (ximg, xp, ym) == bg
515 && XGetPixel (ximg, xm, y) == bg
516 && XGetPixel (ximg, xm, yp) == bg
517 && XGetPixel (ximg, xm, ym) == bg)
518 XPutPixel (mask_img, x, y, 0);
519 else
520 XPutPixel (mask_img, x, y, 1);
524 eassert (interrupt_input_blocked);
525 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
526 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
527 width, height);
528 XFreeGC (FRAME_X_DISPLAY (f), gc);
530 dpyinfo->bitmaps[id - 1].have_mask = 1;
531 dpyinfo->bitmaps[id - 1].mask = mask;
533 XDestroyImage (ximg);
534 x_destroy_x_image (mask_img);
536 return 0;
539 #endif /* HAVE_X_WINDOWS */
542 /***********************************************************************
543 Image types
544 ***********************************************************************/
546 /* List of supported image types. Use define_image_type to add new
547 types. Use lookup_image_type to find a type for a given symbol. */
549 static struct image_type *image_types;
551 /* The symbol `xbm' which is used as the type symbol for XBM images. */
553 static Lisp_Object Qxbm;
555 /* Keywords. */
557 Lisp_Object QCascent, QCmargin, QCrelief;
558 Lisp_Object QCconversion;
559 static Lisp_Object QCheuristic_mask;
560 static Lisp_Object QCcolor_symbols;
561 static Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask, QCgeometry;
562 static Lisp_Object QCcrop, QCrotation;
564 /* Other symbols. */
566 static Lisp_Object Qcount, Qextension_data, Qdelay;
567 static Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
569 /* Function prototypes. */
571 static Lisp_Object define_image_type (struct image_type *type, int loaded);
572 static struct image_type *lookup_image_type (Lisp_Object symbol);
573 static void image_error (const char *format, Lisp_Object, Lisp_Object);
574 static void x_laplace (struct frame *, struct image *);
575 static void x_emboss (struct frame *, struct image *);
576 static int x_build_heuristic_mask (struct frame *, struct image *,
577 Lisp_Object);
578 #ifdef HAVE_NTGUI
579 #define CACHE_IMAGE_TYPE(type, status) \
580 do { Vlibrary_cache = Fcons (Fcons (type, status), Vlibrary_cache); } while (0)
581 #else
582 #define CACHE_IMAGE_TYPE(type, status)
583 #endif
585 #define ADD_IMAGE_TYPE(type) \
586 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
588 /* Define a new image type from TYPE. This adds a copy of TYPE to
589 image_types and caches the loading status of TYPE. */
591 static Lisp_Object
592 define_image_type (struct image_type *type, int loaded)
594 Lisp_Object success;
596 if (!loaded)
597 success = Qnil;
598 else
600 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
601 The initialized data segment is read-only. */
602 struct image_type *p = xmalloc (sizeof *p);
603 memcpy (p, type, sizeof *p);
604 p->next = image_types;
605 image_types = p;
606 success = Qt;
609 CACHE_IMAGE_TYPE (*type->type, success);
610 return success;
614 /* Look up image type SYMBOL, and return a pointer to its image_type
615 structure. Value is null if SYMBOL is not a known image type. */
617 static inline struct image_type *
618 lookup_image_type (Lisp_Object symbol)
620 struct image_type *type;
622 /* We must initialize the image-type if it hasn't been already. */
623 if (NILP (Finit_image_library (symbol, Vdynamic_library_alist)))
624 return 0; /* unimplemented */
626 for (type = image_types; type; type = type->next)
627 if (EQ (symbol, *type->type))
628 break;
630 return type;
634 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
635 valid image specification is a list whose car is the symbol
636 `image', and whose rest is a property list. The property list must
637 contain a value for key `:type'. That value must be the name of a
638 supported image type. The rest of the property list depends on the
639 image type. */
642 valid_image_p (Lisp_Object object)
644 int valid_p = 0;
646 if (IMAGEP (object))
648 Lisp_Object tem;
650 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
651 if (EQ (XCAR (tem), QCtype))
653 tem = XCDR (tem);
654 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
656 struct image_type *type;
657 type = lookup_image_type (XCAR (tem));
658 if (type)
659 valid_p = type->valid_p (object);
662 break;
666 return valid_p;
670 /* Log error message with format string FORMAT and argument ARG.
671 Signaling an error, e.g. when an image cannot be loaded, is not a
672 good idea because this would interrupt redisplay, and the error
673 message display would lead to another redisplay. This function
674 therefore simply displays a message. */
676 static void
677 image_error (const char *format, Lisp_Object arg1, Lisp_Object arg2)
679 add_to_log (format, arg1, arg2);
684 /***********************************************************************
685 Image specifications
686 ***********************************************************************/
688 enum image_value_type
690 IMAGE_DONT_CHECK_VALUE_TYPE,
691 IMAGE_STRING_VALUE,
692 IMAGE_STRING_OR_NIL_VALUE,
693 IMAGE_SYMBOL_VALUE,
694 IMAGE_POSITIVE_INTEGER_VALUE,
695 IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
696 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
697 IMAGE_ASCENT_VALUE,
698 IMAGE_INTEGER_VALUE,
699 IMAGE_FUNCTION_VALUE,
700 IMAGE_NUMBER_VALUE,
701 IMAGE_BOOL_VALUE
704 /* Structure used when parsing image specifications. */
706 struct image_keyword
708 /* Name of keyword. */
709 const char *name;
711 /* The type of value allowed. */
712 enum image_value_type type;
714 /* Non-zero means key must be present. */
715 int mandatory_p;
717 /* Used to recognize duplicate keywords in a property list. */
718 int count;
720 /* The value that was found. */
721 Lisp_Object value;
725 static int parse_image_spec (Lisp_Object, struct image_keyword *,
726 int, Lisp_Object);
727 static Lisp_Object image_spec_value (Lisp_Object, Lisp_Object, int *);
730 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
731 has the format (image KEYWORD VALUE ...). One of the keyword/
732 value pairs must be `:type TYPE'. KEYWORDS is a vector of
733 image_keywords structures of size NKEYWORDS describing other
734 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
736 static int
737 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
738 int nkeywords, Lisp_Object type)
740 int i;
741 Lisp_Object plist;
743 if (!IMAGEP (spec))
744 return 0;
746 plist = XCDR (spec);
747 while (CONSP (plist))
749 Lisp_Object key, value;
751 /* First element of a pair must be a symbol. */
752 key = XCAR (plist);
753 plist = XCDR (plist);
754 if (!SYMBOLP (key))
755 return 0;
757 /* There must follow a value. */
758 if (!CONSP (plist))
759 return 0;
760 value = XCAR (plist);
761 plist = XCDR (plist);
763 /* Find key in KEYWORDS. Error if not found. */
764 for (i = 0; i < nkeywords; ++i)
765 if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
766 break;
768 if (i == nkeywords)
769 continue;
771 /* Record that we recognized the keyword. If a keywords
772 was found more than once, it's an error. */
773 keywords[i].value = value;
774 if (keywords[i].count > 1)
775 return 0;
776 ++keywords[i].count;
778 /* Check type of value against allowed type. */
779 switch (keywords[i].type)
781 case IMAGE_STRING_VALUE:
782 if (!STRINGP (value))
783 return 0;
784 break;
786 case IMAGE_STRING_OR_NIL_VALUE:
787 if (!STRINGP (value) && !NILP (value))
788 return 0;
789 break;
791 case IMAGE_SYMBOL_VALUE:
792 if (!SYMBOLP (value))
793 return 0;
794 break;
796 case IMAGE_POSITIVE_INTEGER_VALUE:
797 if (! RANGED_INTEGERP (1, value, INT_MAX))
798 return 0;
799 break;
801 case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
802 if (RANGED_INTEGERP (0, value, INT_MAX))
803 break;
804 if (CONSP (value)
805 && RANGED_INTEGERP (0, XCAR (value), INT_MAX)
806 && RANGED_INTEGERP (0, XCDR (value), INT_MAX))
807 break;
808 return 0;
810 case IMAGE_ASCENT_VALUE:
811 if (SYMBOLP (value) && EQ (value, Qcenter))
812 break;
813 else if (RANGED_INTEGERP (0, value, 100))
814 break;
815 return 0;
817 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
818 /* Unlike the other integer-related cases, this one does not
819 verify that VALUE fits in 'int'. This is because callers
820 want EMACS_INT. */
821 if (!INTEGERP (value) || XINT (value) < 0)
822 return 0;
823 break;
825 case IMAGE_DONT_CHECK_VALUE_TYPE:
826 break;
828 case IMAGE_FUNCTION_VALUE:
829 value = indirect_function (value);
830 if (!NILP (Ffunctionp (value)))
831 break;
832 return 0;
834 case IMAGE_NUMBER_VALUE:
835 if (!INTEGERP (value) && !FLOATP (value))
836 return 0;
837 break;
839 case IMAGE_INTEGER_VALUE:
840 if (! TYPE_RANGED_INTEGERP (int, value))
841 return 0;
842 break;
844 case IMAGE_BOOL_VALUE:
845 if (!NILP (value) && !EQ (value, Qt))
846 return 0;
847 break;
849 default:
850 abort ();
851 break;
854 if (EQ (key, QCtype) && !EQ (type, value))
855 return 0;
858 /* Check that all mandatory fields are present. */
859 for (i = 0; i < nkeywords; ++i)
860 if (keywords[i].mandatory_p && keywords[i].count == 0)
861 return 0;
863 return NILP (plist);
867 /* Return the value of KEY in image specification SPEC. Value is nil
868 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
869 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
871 static Lisp_Object
872 image_spec_value (Lisp_Object spec, Lisp_Object key, int *found)
874 Lisp_Object tail;
876 eassert (valid_image_p (spec));
878 for (tail = XCDR (spec);
879 CONSP (tail) && CONSP (XCDR (tail));
880 tail = XCDR (XCDR (tail)))
882 if (EQ (XCAR (tail), key))
884 if (found)
885 *found = 1;
886 return XCAR (XCDR (tail));
890 if (found)
891 *found = 0;
892 return Qnil;
896 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
897 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
898 PIXELS non-nil means return the size in pixels, otherwise return the
899 size in canonical character units.
900 FRAME is the frame on which the image will be displayed. FRAME nil
901 or omitted means use the selected frame. */)
902 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
904 Lisp_Object size;
906 size = Qnil;
907 if (valid_image_p (spec))
909 struct frame *f = check_x_frame (frame);
910 ptrdiff_t id = lookup_image (f, spec);
911 struct image *img = IMAGE_FROM_ID (f, id);
912 int width = img->width + 2 * img->hmargin;
913 int height = img->height + 2 * img->vmargin;
915 if (NILP (pixels))
916 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
917 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
918 else
919 size = Fcons (make_number (width), make_number (height));
921 else
922 error ("Invalid image specification");
924 return size;
928 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
929 doc: /* Return t if image SPEC has a mask bitmap.
930 FRAME is the frame on which the image will be displayed. FRAME nil
931 or omitted means use the selected frame. */)
932 (Lisp_Object spec, Lisp_Object frame)
934 Lisp_Object mask;
936 mask = Qnil;
937 if (valid_image_p (spec))
939 struct frame *f = check_x_frame (frame);
940 ptrdiff_t id = lookup_image (f, spec);
941 struct image *img = IMAGE_FROM_ID (f, id);
942 if (img->mask)
943 mask = Qt;
945 else
946 error ("Invalid image specification");
948 return mask;
951 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
952 doc: /* Return metadata for image SPEC.
953 FRAME is the frame on which the image will be displayed. FRAME nil
954 or omitted means use the selected frame. */)
955 (Lisp_Object spec, Lisp_Object frame)
957 Lisp_Object ext;
959 ext = Qnil;
960 if (valid_image_p (spec))
962 struct frame *f = check_x_frame (frame);
963 ptrdiff_t id = lookup_image (f, spec);
964 struct image *img = IMAGE_FROM_ID (f, id);
965 ext = img->lisp_data;
968 return ext;
972 /***********************************************************************
973 Image type independent image structures
974 ***********************************************************************/
976 static void free_image (struct frame *f, struct image *img);
978 #define MAX_IMAGE_SIZE 10.0
979 /* Allocate and return a new image structure for image specification
980 SPEC. SPEC has a hash value of HASH. */
982 static struct image *
983 make_image (Lisp_Object spec, EMACS_UINT hash)
985 struct image *img = xzalloc (sizeof *img);
986 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
988 eassert (valid_image_p (spec));
989 img->dependencies = NILP (file) ? Qnil : list1 (file);
990 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
991 eassert (img->type != NULL);
992 img->spec = spec;
993 img->lisp_data = Qnil;
994 img->ascent = DEFAULT_IMAGE_ASCENT;
995 img->hash = hash;
996 img->corners[BOT_CORNER] = -1; /* Full image */
997 return img;
1001 /* Free image IMG which was used on frame F, including its resources. */
1003 static void
1004 free_image (struct frame *f, struct image *img)
1006 if (img)
1008 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1010 /* Remove IMG from the hash table of its cache. */
1011 if (img->prev)
1012 img->prev->next = img->next;
1013 else
1014 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1016 if (img->next)
1017 img->next->prev = img->prev;
1019 c->images[img->id] = NULL;
1021 /* Free resources, then free IMG. */
1022 img->type->free (f, img);
1023 xfree (img);
1027 /* Return 1 if the given widths and heights are valid for display;
1028 otherwise, return 0. */
1030 static int
1031 check_image_size (struct frame *f, int width, int height)
1033 int w, h;
1035 if (width <= 0 || height <= 0)
1036 return 0;
1038 if (INTEGERP (Vmax_image_size))
1039 return (width <= XINT (Vmax_image_size)
1040 && height <= XINT (Vmax_image_size));
1041 else if (FLOATP (Vmax_image_size))
1043 if (f != NULL)
1045 w = FRAME_PIXEL_WIDTH (f);
1046 h = FRAME_PIXEL_HEIGHT (f);
1048 else
1049 w = h = 1024; /* Arbitrary size for unknown frame. */
1050 return (width <= XFLOAT_DATA (Vmax_image_size) * w
1051 && height <= XFLOAT_DATA (Vmax_image_size) * h);
1053 else
1054 return 1;
1057 /* Prepare image IMG for display on frame F. Must be called before
1058 drawing an image. */
1060 void
1061 prepare_image_for_display (struct frame *f, struct image *img)
1063 /* We're about to display IMG, so set its timestamp to `now'. */
1064 img->timestamp = current_emacs_time ();
1066 /* If IMG doesn't have a pixmap yet, load it now, using the image
1067 type dependent loader function. */
1068 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1069 img->load_failed_p = img->type->load (f, img) == 0;
1074 /* Value is the number of pixels for the ascent of image IMG when
1075 drawn in face FACE. */
1078 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1080 int height;
1081 int ascent;
1083 if (slice->height == img->height)
1084 height = img->height + img->vmargin;
1085 else if (slice->y == 0)
1086 height = slice->height + img->vmargin;
1087 else
1088 height = slice->height;
1090 if (img->ascent == CENTERED_IMAGE_ASCENT)
1092 if (face->font)
1094 #ifdef HAVE_NTGUI
1095 /* W32 specific version. Why?. ++kfs */
1096 ascent = height / 2 - (FONT_DESCENT (face->font)
1097 - FONT_BASE (face->font)) / 2;
1098 #else
1099 /* This expression is arranged so that if the image can't be
1100 exactly centered, it will be moved slightly up. This is
1101 because a typical font is `top-heavy' (due to the presence
1102 uppercase letters), so the image placement should err towards
1103 being top-heavy too. It also just generally looks better. */
1104 ascent = (height + FONT_BASE (face->font)
1105 - FONT_DESCENT (face->font) + 1) / 2;
1106 #endif /* HAVE_NTGUI */
1108 else
1109 ascent = height / 2;
1111 else
1112 ascent = height * (img->ascent / 100.0);
1114 return ascent;
1118 /* Image background colors. */
1120 /* Find the "best" corner color of a bitmap.
1121 On W32, XIMG is assumed to a device context with the bitmap selected. */
1123 static RGB_PIXEL_COLOR
1124 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1125 unsigned long width, unsigned long height)
1127 RGB_PIXEL_COLOR corner_pixels[4], best IF_LINT (= 0);
1128 int i, best_count;
1130 if (corners && corners[BOT_CORNER] >= 0)
1132 /* Get the colors at the corner_pixels of ximg. */
1133 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1134 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1135 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1136 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1138 else
1140 /* Get the colors at the corner_pixels of ximg. */
1141 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1142 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1143 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1144 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1146 /* Choose the most frequently found color as background. */
1147 for (i = best_count = 0; i < 4; ++i)
1149 int j, n;
1151 for (j = n = 0; j < 4; ++j)
1152 if (corner_pixels[i] == corner_pixels[j])
1153 ++n;
1155 if (n > best_count)
1156 best = corner_pixels[i], best_count = n;
1159 return best;
1162 /* Portability macros */
1164 #ifdef HAVE_NTGUI
1166 #define Destroy_Image(img_dc, prev) \
1167 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1169 #define Free_Pixmap(display, pixmap) \
1170 DeleteObject (pixmap)
1172 #elif defined (HAVE_NS)
1174 #define Destroy_Image(ximg, dummy) \
1175 ns_release_object (ximg)
1177 #define Free_Pixmap(display, pixmap) \
1178 ns_release_object (pixmap)
1180 #else
1182 #define Destroy_Image(ximg, dummy) \
1183 XDestroyImage (ximg)
1185 #define Free_Pixmap(display, pixmap) \
1186 XFreePixmap (display, pixmap)
1188 #endif /* !HAVE_NTGUI && !HAVE_NS */
1191 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1192 it is guessed heuristically. If non-zero, XIMG is an existing
1193 XImage object (or device context with the image selected on W32) to
1194 use for the heuristic. */
1196 RGB_PIXEL_COLOR
1197 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1199 if (! img->background_valid)
1200 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1202 int free_ximg = !ximg;
1203 #ifdef HAVE_NTGUI
1204 HGDIOBJ prev;
1205 #endif /* HAVE_NTGUI */
1207 if (free_ximg)
1209 #ifndef HAVE_NTGUI
1210 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1211 0, 0, img->width, img->height, ~0, ZPixmap);
1212 #else
1213 HDC frame_dc = get_frame_dc (f);
1214 ximg = CreateCompatibleDC (frame_dc);
1215 release_frame_dc (f, frame_dc);
1216 prev = SelectObject (ximg, img->pixmap);
1217 #endif /* !HAVE_NTGUI */
1220 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1222 if (free_ximg)
1223 Destroy_Image (ximg, prev);
1225 img->background_valid = 1;
1228 return img->background;
1231 /* Return the `background_transparent' field of IMG. If IMG doesn't
1232 have one yet, it is guessed heuristically. If non-zero, MASK is an
1233 existing XImage object to use for the heuristic. */
1236 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1238 if (! img->background_transparent_valid)
1239 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1241 if (img->mask)
1243 int free_mask = !mask;
1244 #ifdef HAVE_NTGUI
1245 HGDIOBJ prev;
1246 #endif /* HAVE_NTGUI */
1248 if (free_mask)
1250 #ifndef HAVE_NTGUI
1251 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1252 0, 0, img->width, img->height, ~0, ZPixmap);
1253 #else
1254 HDC frame_dc = get_frame_dc (f);
1255 mask = CreateCompatibleDC (frame_dc);
1256 release_frame_dc (f, frame_dc);
1257 prev = SelectObject (mask, img->mask);
1258 #endif /* HAVE_NTGUI */
1261 img->background_transparent
1262 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1264 if (free_mask)
1265 Destroy_Image (mask, prev);
1267 else
1268 img->background_transparent = 0;
1270 img->background_transparent_valid = 1;
1273 return img->background_transparent;
1277 /***********************************************************************
1278 Helper functions for X image types
1279 ***********************************************************************/
1281 static void x_clear_image_1 (struct frame *, struct image *, int,
1282 int, int);
1283 static void x_clear_image (struct frame *f, struct image *img);
1284 static unsigned long x_alloc_image_color (struct frame *f,
1285 struct image *img,
1286 Lisp_Object color_name,
1287 unsigned long dflt);
1290 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1291 free the pixmap if any. MASK_P non-zero means clear the mask
1292 pixmap if any. COLORS_P non-zero means free colors allocated for
1293 the image, if any. */
1295 static void
1296 x_clear_image_1 (struct frame *f, struct image *img, int pixmap_p, int mask_p,
1297 int colors_p)
1299 if (pixmap_p && img->pixmap)
1301 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1302 img->pixmap = NO_PIXMAP;
1303 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1304 img->background_valid = 0;
1307 if (mask_p && img->mask)
1309 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1310 img->mask = NO_PIXMAP;
1311 img->background_transparent_valid = 0;
1314 if (colors_p && img->ncolors)
1316 /* W32_TODO: color table support. */
1317 #ifdef HAVE_X_WINDOWS
1318 x_free_colors (f, img->colors, img->ncolors);
1319 #endif /* HAVE_X_WINDOWS */
1320 xfree (img->colors);
1321 img->colors = NULL;
1322 img->ncolors = 0;
1327 /* Free X resources of image IMG which is used on frame F. */
1329 static void
1330 x_clear_image (struct frame *f, struct image *img)
1332 BLOCK_INPUT;
1333 x_clear_image_1 (f, img, 1, 1, 1);
1334 UNBLOCK_INPUT;
1338 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1339 cannot be allocated, use DFLT. Add a newly allocated color to
1340 IMG->colors, so that it can be freed again. Value is the pixel
1341 color. */
1343 static unsigned long
1344 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1345 unsigned long dflt)
1347 XColor color;
1348 unsigned long result;
1350 eassert (STRINGP (color_name));
1352 if (x_defined_color (f, SSDATA (color_name), &color, 1)
1353 && img->ncolors < min (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *img->colors,
1354 INT_MAX))
1356 /* This isn't called frequently so we get away with simply
1357 reallocating the color vector to the needed size, here. */
1358 ptrdiff_t ncolors = img->ncolors + 1;
1359 img->colors = xrealloc (img->colors, ncolors * sizeof *img->colors);
1360 img->colors[ncolors - 1] = color.pixel;
1361 img->ncolors = ncolors;
1362 result = color.pixel;
1364 else
1365 result = dflt;
1367 return result;
1372 /***********************************************************************
1373 Image Cache
1374 ***********************************************************************/
1376 static void cache_image (struct frame *f, struct image *img);
1377 static void postprocess_image (struct frame *, struct image *);
1379 /* Return a new, initialized image cache that is allocated from the
1380 heap. Call free_image_cache to free an image cache. */
1382 struct image_cache *
1383 make_image_cache (void)
1385 struct image_cache *c = xzalloc (sizeof *c);
1386 int size;
1388 size = 50;
1389 c->images = xmalloc (size * sizeof *c->images);
1390 c->size = size;
1391 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1392 c->buckets = xzalloc (size);
1393 return c;
1397 /* Find an image matching SPEC in the cache, and return it. If no
1398 image is found, return NULL. */
1399 static struct image *
1400 search_image_cache (struct frame *f, Lisp_Object spec, EMACS_UINT hash)
1402 struct image *img;
1403 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1404 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1406 if (!c) return NULL;
1408 /* If the image spec does not specify a background color, the cached
1409 image must have the same background color as the current frame.
1410 The foreground color must also match, for the sake of monochrome
1411 images.
1413 In fact, we could ignore the foreground color matching condition
1414 for color images, or if the image spec specifies :foreground;
1415 similarly we could ignore the background color matching condition
1416 for formats that don't use transparency (such as jpeg), or if the
1417 image spec specifies :background. However, the extra memory
1418 usage is probably negligible in practice, so we don't bother. */
1420 for (img = c->buckets[i]; img; img = img->next)
1421 if (img->hash == hash
1422 && !NILP (Fequal (img->spec, spec))
1423 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1424 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1425 break;
1426 return img;
1430 /* Search frame F for an image with spec SPEC, and free it. */
1432 static void
1433 uncache_image (struct frame *f, Lisp_Object spec)
1435 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1436 if (img)
1438 free_image (f, img);
1439 /* As display glyphs may still be referring to the image ID, we
1440 must garbage the frame (Bug#6426). */
1441 SET_FRAME_GARBAGED (f);
1446 /* Free image cache of frame F. Be aware that X frames share images
1447 caches. */
1449 void
1450 free_image_cache (struct frame *f)
1452 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1453 if (c)
1455 ptrdiff_t i;
1457 /* Cache should not be referenced by any frame when freed. */
1458 eassert (c->refcount == 0);
1460 for (i = 0; i < c->used; ++i)
1461 free_image (f, c->images[i]);
1462 xfree (c->images);
1463 xfree (c->buckets);
1464 xfree (c);
1465 FRAME_IMAGE_CACHE (f) = NULL;
1470 /* Clear image cache of frame F. FILTER=t means free all images.
1471 FILTER=nil means clear only images that haven't been
1472 displayed for some time.
1473 Else, only free the images which have FILTER in their `dependencies'.
1474 Should be called from time to time to reduce the number of loaded images.
1475 If image-cache-eviction-delay is non-nil, this frees images in the cache
1476 which weren't displayed for at least that many seconds. */
1478 static void
1479 clear_image_cache (struct frame *f, Lisp_Object filter)
1481 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1483 if (c)
1485 ptrdiff_t i, nfreed = 0;
1487 /* Block input so that we won't be interrupted by a SIGIO
1488 while being in an inconsistent state. */
1489 BLOCK_INPUT;
1491 if (!NILP (filter))
1493 /* Filter image cache. */
1494 for (i = 0; i < c->used; ++i)
1496 struct image *img = c->images[i];
1497 if (img && (EQ (Qt, filter)
1498 || !NILP (Fmember (filter, img->dependencies))))
1500 free_image (f, img);
1501 ++nfreed;
1505 else if (INTEGERP (Vimage_cache_eviction_delay))
1507 /* Free cache based on timestamp. */
1508 EMACS_TIME old, t;
1509 double delay;
1510 ptrdiff_t nimages = 0;
1512 for (i = 0; i < c->used; ++i)
1513 if (c->images[i])
1514 nimages++;
1516 /* If the number of cached images has grown unusually large,
1517 decrease the cache eviction delay (Bug#6230). */
1518 delay = XINT (Vimage_cache_eviction_delay);
1519 if (nimages > 40)
1520 delay = 1600 * delay / nimages / nimages;
1521 delay = max (delay, 1);
1523 t = current_emacs_time ();
1524 old = sub_emacs_time (t, EMACS_TIME_FROM_DOUBLE (delay));
1526 for (i = 0; i < c->used; ++i)
1528 struct image *img = c->images[i];
1529 if (img && EMACS_TIME_LT (img->timestamp, old))
1531 free_image (f, img);
1532 ++nfreed;
1537 /* We may be clearing the image cache because, for example,
1538 Emacs was iconified for a longer period of time. In that
1539 case, current matrices may still contain references to
1540 images freed above. So, clear these matrices. */
1541 if (nfreed)
1543 Lisp_Object tail, frame;
1545 FOR_EACH_FRAME (tail, frame)
1547 struct frame *fr = XFRAME (frame);
1548 if (FRAME_IMAGE_CACHE (fr) == c)
1549 clear_current_matrices (fr);
1552 ++windows_or_buffers_changed;
1555 UNBLOCK_INPUT;
1559 void
1560 clear_image_caches (Lisp_Object filter)
1562 /* FIXME: We want to do
1563 * struct terminal *t;
1564 * for (t = terminal_list; t; t = t->next_terminal)
1565 * clear_image_cache (t, filter); */
1566 Lisp_Object tail, frame;
1567 FOR_EACH_FRAME (tail, frame)
1568 if (FRAME_WINDOW_P (XFRAME (frame)))
1569 clear_image_cache (XFRAME (frame), filter);
1572 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1573 0, 1, 0,
1574 doc: /* Clear the image cache.
1575 FILTER nil or a frame means clear all images in the selected frame.
1576 FILTER t means clear the image caches of all frames.
1577 Anything else, means only clear those images which refer to FILTER,
1578 which is then usually a filename. */)
1579 (Lisp_Object filter)
1581 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1582 clear_image_caches (filter);
1583 else
1584 clear_image_cache (check_x_frame (filter), Qt);
1586 return Qnil;
1590 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1591 1, 2, 0,
1592 doc: /* Fush the image with specification SPEC on frame FRAME.
1593 This removes the image from the Emacs image cache. If SPEC specifies
1594 an image file, the next redisplay of this image will read from the
1595 current contents of that file.
1597 FRAME nil or omitted means use the selected frame.
1598 FRAME t means refresh the image on all frames. */)
1599 (Lisp_Object spec, Lisp_Object frame)
1601 if (!valid_image_p (spec))
1602 error ("Invalid image specification");
1604 if (EQ (frame, Qt))
1606 Lisp_Object tail;
1607 FOR_EACH_FRAME (tail, frame)
1609 struct frame *f = XFRAME (frame);
1610 if (FRAME_WINDOW_P (f))
1611 uncache_image (f, spec);
1614 else
1615 uncache_image (check_x_frame (frame), spec);
1617 return Qnil;
1621 /* Compute masks and transform image IMG on frame F, as specified
1622 by the image's specification, */
1624 static void
1625 postprocess_image (struct frame *f, struct image *img)
1627 /* Manipulation of the image's mask. */
1628 if (img->pixmap)
1630 Lisp_Object conversion, spec;
1631 Lisp_Object mask;
1633 spec = img->spec;
1635 /* `:heuristic-mask t'
1636 `:mask heuristic'
1637 means build a mask heuristically.
1638 `:heuristic-mask (R G B)'
1639 `:mask (heuristic (R G B))'
1640 means build a mask from color (R G B) in the
1641 image.
1642 `:mask nil'
1643 means remove a mask, if any. */
1645 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1646 if (!NILP (mask))
1647 x_build_heuristic_mask (f, img, mask);
1648 else
1650 int found_p;
1652 mask = image_spec_value (spec, QCmask, &found_p);
1654 if (EQ (mask, Qheuristic))
1655 x_build_heuristic_mask (f, img, Qt);
1656 else if (CONSP (mask)
1657 && EQ (XCAR (mask), Qheuristic))
1659 if (CONSP (XCDR (mask)))
1660 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1661 else
1662 x_build_heuristic_mask (f, img, XCDR (mask));
1664 else if (NILP (mask) && found_p && img->mask)
1666 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1667 img->mask = NO_PIXMAP;
1672 /* Should we apply an image transformation algorithm? */
1673 conversion = image_spec_value (spec, QCconversion, NULL);
1674 if (EQ (conversion, Qdisabled))
1675 x_disable_image (f, img);
1676 else if (EQ (conversion, Qlaplace))
1677 x_laplace (f, img);
1678 else if (EQ (conversion, Qemboss))
1679 x_emboss (f, img);
1680 else if (CONSP (conversion)
1681 && EQ (XCAR (conversion), Qedge_detection))
1683 Lisp_Object tem;
1684 tem = XCDR (conversion);
1685 if (CONSP (tem))
1686 x_edge_detection (f, img,
1687 Fplist_get (tem, QCmatrix),
1688 Fplist_get (tem, QCcolor_adjustment));
1694 /* Return the id of image with Lisp specification SPEC on frame F.
1695 SPEC must be a valid Lisp image specification (see valid_image_p). */
1697 ptrdiff_t
1698 lookup_image (struct frame *f, Lisp_Object spec)
1700 struct image *img;
1701 EMACS_UINT hash;
1703 /* F must be a window-system frame, and SPEC must be a valid image
1704 specification. */
1705 eassert (FRAME_WINDOW_P (f));
1706 eassert (valid_image_p (spec));
1708 /* Look up SPEC in the hash table of the image cache. */
1709 hash = sxhash (spec, 0);
1710 img = search_image_cache (f, spec, hash);
1711 if (img && img->load_failed_p)
1713 free_image (f, img);
1714 img = NULL;
1717 /* If not found, create a new image and cache it. */
1718 if (img == NULL)
1720 BLOCK_INPUT;
1721 img = make_image (spec, hash);
1722 cache_image (f, img);
1723 img->load_failed_p = img->type->load (f, img) == 0;
1724 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1725 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1727 /* If we can't load the image, and we don't have a width and
1728 height, use some arbitrary width and height so that we can
1729 draw a rectangle for it. */
1730 if (img->load_failed_p)
1732 Lisp_Object value;
1734 value = image_spec_value (spec, QCwidth, NULL);
1735 img->width = (INTEGERP (value)
1736 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1737 value = image_spec_value (spec, QCheight, NULL);
1738 img->height = (INTEGERP (value)
1739 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1741 else
1743 /* Handle image type independent image attributes
1744 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1745 `:background COLOR'. */
1746 Lisp_Object ascent, margin, relief, bg;
1747 int relief_bound;
1749 ascent = image_spec_value (spec, QCascent, NULL);
1750 if (INTEGERP (ascent))
1751 img->ascent = XFASTINT (ascent);
1752 else if (EQ (ascent, Qcenter))
1753 img->ascent = CENTERED_IMAGE_ASCENT;
1755 margin = image_spec_value (spec, QCmargin, NULL);
1756 if (INTEGERP (margin))
1757 img->vmargin = img->hmargin = XFASTINT (margin);
1758 else if (CONSP (margin))
1760 img->hmargin = XFASTINT (XCAR (margin));
1761 img->vmargin = XFASTINT (XCDR (margin));
1764 relief = image_spec_value (spec, QCrelief, NULL);
1765 relief_bound = INT_MAX - max (img->hmargin, img->vmargin);
1766 if (RANGED_INTEGERP (- relief_bound, relief, relief_bound))
1768 img->relief = XINT (relief);
1769 img->hmargin += eabs (img->relief);
1770 img->vmargin += eabs (img->relief);
1773 if (! img->background_valid)
1775 bg = image_spec_value (img->spec, QCbackground, NULL);
1776 if (!NILP (bg))
1778 img->background
1779 = x_alloc_image_color (f, img, bg,
1780 FRAME_BACKGROUND_PIXEL (f));
1781 img->background_valid = 1;
1785 /* Do image transformations and compute masks, unless we
1786 don't have the image yet. */
1787 if (!EQ (*img->type->type, Qpostscript))
1788 postprocess_image (f, img);
1791 UNBLOCK_INPUT;
1794 /* We're using IMG, so set its timestamp to `now'. */
1795 img->timestamp = current_emacs_time ();
1797 /* Value is the image id. */
1798 return img->id;
1802 /* Cache image IMG in the image cache of frame F. */
1804 static void
1805 cache_image (struct frame *f, struct image *img)
1807 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1808 ptrdiff_t i;
1810 /* Find a free slot in c->images. */
1811 for (i = 0; i < c->used; ++i)
1812 if (c->images[i] == NULL)
1813 break;
1815 /* If no free slot found, maybe enlarge c->images. */
1816 if (i == c->used && c->used == c->size)
1817 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1819 /* Add IMG to c->images, and assign IMG an id. */
1820 c->images[i] = img;
1821 img->id = i;
1822 if (i == c->used)
1823 ++c->used;
1825 /* Add IMG to the cache's hash table. */
1826 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1827 img->next = c->buckets[i];
1828 if (img->next)
1829 img->next->prev = img;
1830 img->prev = NULL;
1831 c->buckets[i] = img;
1835 /* Call FN on every image in the image cache of frame F. Used to mark
1836 Lisp Objects in the image cache. */
1838 /* Mark Lisp objects in image IMG. */
1840 static void
1841 mark_image (struct image *img)
1843 mark_object (img->spec);
1844 mark_object (img->dependencies);
1846 if (!NILP (img->lisp_data))
1847 mark_object (img->lisp_data);
1851 void
1852 mark_image_cache (struct image_cache *c)
1854 if (c)
1856 ptrdiff_t i;
1857 for (i = 0; i < c->used; ++i)
1858 if (c->images[i])
1859 mark_image (c->images[i]);
1865 /***********************************************************************
1866 X / NS / W32 support code
1867 ***********************************************************************/
1869 #ifdef HAVE_NTGUI
1871 /* Macro for defining functions that will be loaded from image DLLs. */
1872 #define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL *fn_##func)args
1874 /* Macro for loading those image functions from the library. */
1875 #define LOAD_IMGLIB_FN(lib,func) { \
1876 fn_##func = (void *) GetProcAddress (lib, #func); \
1877 if (!fn_##func) return 0; \
1880 #endif /* HAVE_NTGUI */
1882 static int x_create_x_image_and_pixmap (struct frame *, int, int, int,
1883 XImagePtr *, Pixmap *);
1884 static void x_destroy_x_image (XImagePtr);
1885 static void x_put_x_image (struct frame *, XImagePtr, Pixmap, int, int);
1887 /* Return nonzero if XIMG's size WIDTH x HEIGHT doesn't break the
1888 windowing system.
1889 WIDTH and HEIGHT must both be positive.
1890 If XIMG is null, assume it is a bitmap. */
1891 static int
1892 x_check_image_size (XImagePtr ximg, int width, int height)
1894 #ifdef HAVE_X_WINDOWS
1895 /* Respect Xlib's limits: it cannot deal with images that have more
1896 than INT_MAX (and/or UINT_MAX) bytes. And respect Emacs's limits
1897 of PTRDIFF_MAX (and/or SIZE_MAX) bytes for any object. */
1898 enum
1900 XLIB_BYTES_MAX = min (INT_MAX, UINT_MAX),
1901 X_IMAGE_BYTES_MAX = min (XLIB_BYTES_MAX, min (PTRDIFF_MAX, SIZE_MAX))
1904 int bitmap_pad, depth, bytes_per_line;
1905 if (ximg)
1907 bitmap_pad = ximg->bitmap_pad;
1908 depth = ximg->depth;
1909 bytes_per_line = ximg->bytes_per_line;
1911 else
1913 bitmap_pad = 8;
1914 depth = 1;
1915 bytes_per_line = (width >> 3) + ((width & 7) != 0);
1917 return (width <= (INT_MAX - (bitmap_pad - 1)) / depth
1918 && height <= X_IMAGE_BYTES_MAX / bytes_per_line);
1919 #else
1920 /* FIXME: Implement this check for the HAVE_NS and HAVE_NTGUI cases.
1921 For now, assume that every image size is allowed on these systems. */
1922 return 1;
1923 #endif
1926 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1927 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1928 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1929 via xmalloc. Print error messages via image_error if an error
1930 occurs. Value is non-zero if successful.
1932 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1933 should indicate the bit depth of the image. */
1935 static int
1936 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1937 XImagePtr *ximg, Pixmap *pixmap)
1939 #ifdef HAVE_X_WINDOWS
1940 Display *display = FRAME_X_DISPLAY (f);
1941 Window window = FRAME_X_WINDOW (f);
1942 Screen *screen = FRAME_X_SCREEN (f);
1944 eassert (interrupt_input_blocked);
1946 if (depth <= 0)
1947 depth = DefaultDepthOfScreen (screen);
1948 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1949 depth, ZPixmap, 0, NULL, width, height,
1950 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1951 if (*ximg == NULL)
1953 image_error ("Unable to allocate X image", Qnil, Qnil);
1954 return 0;
1957 if (! x_check_image_size (*ximg, width, height))
1959 x_destroy_x_image (*ximg);
1960 *ximg = NULL;
1961 image_error ("Image too large (%dx%d)",
1962 make_number (width), make_number (height));
1963 return 0;
1966 /* Allocate image raster. */
1967 (*ximg)->data = xmalloc ((*ximg)->bytes_per_line * height);
1969 /* Allocate a pixmap of the same size. */
1970 *pixmap = XCreatePixmap (display, window, width, height, depth);
1971 if (*pixmap == NO_PIXMAP)
1973 x_destroy_x_image (*ximg);
1974 *ximg = NULL;
1975 image_error ("Unable to create X pixmap", Qnil, Qnil);
1976 return 0;
1979 return 1;
1980 #endif /* HAVE_X_WINDOWS */
1982 #ifdef HAVE_NTGUI
1984 BITMAPINFOHEADER *header;
1985 HDC hdc;
1986 int scanline_width_bits;
1987 int remainder;
1988 int palette_colors = 0;
1990 if (depth == 0)
1991 depth = 24;
1993 if (depth != 1 && depth != 4 && depth != 8
1994 && depth != 16 && depth != 24 && depth != 32)
1996 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1997 return 0;
2000 scanline_width_bits = width * depth;
2001 remainder = scanline_width_bits % 32;
2003 if (remainder)
2004 scanline_width_bits += 32 - remainder;
2006 /* Bitmaps with a depth less than 16 need a palette. */
2007 /* BITMAPINFO structure already contains the first RGBQUAD. */
2008 if (depth < 16)
2009 palette_colors = 1 << (depth - 1);
2011 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2013 header = &(*ximg)->info.bmiHeader;
2014 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2015 header->biSize = sizeof (*header);
2016 header->biWidth = width;
2017 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2018 header->biPlanes = 1;
2019 header->biBitCount = depth;
2020 header->biCompression = BI_RGB;
2021 header->biClrUsed = palette_colors;
2023 /* TODO: fill in palette. */
2024 if (depth == 1)
2026 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2027 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2028 (*ximg)->info.bmiColors[0].rgbRed = 0;
2029 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2030 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2031 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2032 (*ximg)->info.bmiColors[1].rgbRed = 255;
2033 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2036 hdc = get_frame_dc (f);
2038 /* Create a DIBSection and raster array for the bitmap,
2039 and store its handle in *pixmap. */
2040 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2041 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2042 /* casting avoids a GCC warning */
2043 (void **)&((*ximg)->data), NULL, 0);
2045 /* Realize display palette and garbage all frames. */
2046 release_frame_dc (f, hdc);
2048 if (*pixmap == NULL)
2050 DWORD err = GetLastError ();
2051 Lisp_Object errcode;
2052 /* All system errors are < 10000, so the following is safe. */
2053 XSETINT (errcode, err);
2054 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2055 x_destroy_x_image (*ximg);
2056 return 0;
2059 return 1;
2061 #endif /* HAVE_NTGUI */
2063 #ifdef HAVE_NS
2064 *pixmap = ns_image_for_XPM (width, height, depth);
2065 if (*pixmap == 0)
2067 *ximg = NULL;
2068 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2069 return 0;
2071 *ximg = *pixmap;
2072 return 1;
2073 #endif
2077 /* Destroy XImage XIMG. Free XIMG->data. */
2079 static void
2080 x_destroy_x_image (XImagePtr ximg)
2082 eassert (interrupt_input_blocked);
2083 if (ximg)
2085 #ifdef HAVE_X_WINDOWS
2086 xfree (ximg->data);
2087 ximg->data = NULL;
2088 XDestroyImage (ximg);
2089 #endif /* HAVE_X_WINDOWS */
2090 #ifdef HAVE_NTGUI
2091 /* Data will be freed by DestroyObject. */
2092 ximg->data = NULL;
2093 xfree (ximg);
2094 #endif /* HAVE_NTGUI */
2095 #ifdef HAVE_NS
2096 ns_release_object (ximg);
2097 #endif /* HAVE_NS */
2102 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2103 are width and height of both the image and pixmap. */
2105 static void
2106 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2108 #ifdef HAVE_X_WINDOWS
2109 GC gc;
2111 eassert (interrupt_input_blocked);
2112 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2113 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2114 XFreeGC (FRAME_X_DISPLAY (f), gc);
2115 #endif /* HAVE_X_WINDOWS */
2117 #ifdef HAVE_NTGUI
2118 #if 0 /* I don't think this is necessary looking at where it is used. */
2119 HDC hdc = get_frame_dc (f);
2120 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2121 release_frame_dc (f, hdc);
2122 #endif
2123 #endif /* HAVE_NTGUI */
2125 #ifdef HAVE_NS
2126 eassert (ximg == pixmap);
2127 ns_retain_object (ximg);
2128 #endif
2132 /***********************************************************************
2133 File Handling
2134 ***********************************************************************/
2136 /* Find image file FILE. Look in data-directory/images, then
2137 x-bitmap-file-path. Value is the encoded full name of the file
2138 found, or nil if not found. */
2140 Lisp_Object
2141 x_find_image_file (Lisp_Object file)
2143 Lisp_Object file_found, search_path;
2144 int fd;
2146 /* TODO I think this should use something like image-load-path
2147 instead. Unfortunately, that can contain non-string elements. */
2148 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2149 Vdata_directory),
2150 Vx_bitmap_file_path);
2152 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2153 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2155 if (fd == -1)
2156 file_found = Qnil;
2157 else
2159 file_found = ENCODE_FILE (file_found);
2160 close (fd);
2163 return file_found;
2167 /* Read FILE into memory. Value is a pointer to a buffer allocated
2168 with xmalloc holding FILE's contents. Value is null if an error
2169 occurred. *SIZE is set to the size of the file. */
2171 static unsigned char *
2172 slurp_file (char *file, ptrdiff_t *size)
2174 FILE *fp = NULL;
2175 unsigned char *buf = NULL;
2176 struct stat st;
2178 if (stat (file, &st) == 0
2179 && (fp = fopen (file, "rb")) != NULL
2180 && 0 <= st.st_size && st.st_size <= min (PTRDIFF_MAX, SIZE_MAX)
2181 && (buf = xmalloc (st.st_size),
2182 fread (buf, 1, st.st_size, fp) == st.st_size))
2184 *size = st.st_size;
2185 fclose (fp);
2187 else
2189 if (fp)
2190 fclose (fp);
2191 if (buf)
2193 xfree (buf);
2194 buf = NULL;
2198 return buf;
2203 /***********************************************************************
2204 XBM images
2205 ***********************************************************************/
2207 static int xbm_scan (unsigned char **, unsigned char *, char *, int *);
2208 static int xbm_load (struct frame *f, struct image *img);
2209 static int xbm_load_image (struct frame *f, struct image *img,
2210 unsigned char *, unsigned char *);
2211 static int xbm_image_p (Lisp_Object object);
2212 static int xbm_read_bitmap_data (struct frame *f,
2213 unsigned char *, unsigned char *,
2214 int *, int *, char **, int);
2215 static int xbm_file_p (Lisp_Object);
2218 /* Indices of image specification fields in xbm_format, below. */
2220 enum xbm_keyword_index
2222 XBM_TYPE,
2223 XBM_FILE,
2224 XBM_WIDTH,
2225 XBM_HEIGHT,
2226 XBM_DATA,
2227 XBM_FOREGROUND,
2228 XBM_BACKGROUND,
2229 XBM_ASCENT,
2230 XBM_MARGIN,
2231 XBM_RELIEF,
2232 XBM_ALGORITHM,
2233 XBM_HEURISTIC_MASK,
2234 XBM_MASK,
2235 XBM_LAST
2238 /* Vector of image_keyword structures describing the format
2239 of valid XBM image specifications. */
2241 static const struct image_keyword xbm_format[XBM_LAST] =
2243 {":type", IMAGE_SYMBOL_VALUE, 1},
2244 {":file", IMAGE_STRING_VALUE, 0},
2245 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2246 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2247 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2248 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2249 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2250 {":ascent", IMAGE_ASCENT_VALUE, 0},
2251 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
2252 {":relief", IMAGE_INTEGER_VALUE, 0},
2253 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2254 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2255 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2258 /* Structure describing the image type XBM. */
2260 static struct image_type xbm_type =
2262 &Qxbm,
2263 xbm_image_p,
2264 xbm_load,
2265 x_clear_image,
2266 NULL
2269 /* Tokens returned from xbm_scan. */
2271 enum xbm_token
2273 XBM_TK_IDENT = 256,
2274 XBM_TK_NUMBER
2278 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2279 A valid specification is a list starting with the symbol `image'
2280 The rest of the list is a property list which must contain an
2281 entry `:type xbm..
2283 If the specification specifies a file to load, it must contain
2284 an entry `:file FILENAME' where FILENAME is a string.
2286 If the specification is for a bitmap loaded from memory it must
2287 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2288 WIDTH and HEIGHT are integers > 0. DATA may be:
2290 1. a string large enough to hold the bitmap data, i.e. it must
2291 have a size >= (WIDTH + 7) / 8 * HEIGHT
2293 2. a bool-vector of size >= WIDTH * HEIGHT
2295 3. a vector of strings or bool-vectors, one for each line of the
2296 bitmap.
2298 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2299 may not be specified in this case because they are defined in the
2300 XBM file.
2302 Both the file and data forms may contain the additional entries
2303 `:background COLOR' and `:foreground COLOR'. If not present,
2304 foreground and background of the frame on which the image is
2305 displayed is used. */
2307 static int
2308 xbm_image_p (Lisp_Object object)
2310 struct image_keyword kw[XBM_LAST];
2312 memcpy (kw, xbm_format, sizeof kw);
2313 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2314 return 0;
2316 eassert (EQ (kw[XBM_TYPE].value, Qxbm));
2318 if (kw[XBM_FILE].count)
2320 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2321 return 0;
2323 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2325 /* In-memory XBM file. */
2326 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2327 return 0;
2329 else
2331 Lisp_Object data;
2332 int width, height;
2334 /* Entries for `:width', `:height' and `:data' must be present. */
2335 if (!kw[XBM_WIDTH].count
2336 || !kw[XBM_HEIGHT].count
2337 || !kw[XBM_DATA].count)
2338 return 0;
2340 data = kw[XBM_DATA].value;
2341 width = XFASTINT (kw[XBM_WIDTH].value);
2342 height = XFASTINT (kw[XBM_HEIGHT].value);
2344 /* Check type of data, and width and height against contents of
2345 data. */
2346 if (VECTORP (data))
2348 EMACS_INT i;
2350 /* Number of elements of the vector must be >= height. */
2351 if (ASIZE (data) < height)
2352 return 0;
2354 /* Each string or bool-vector in data must be large enough
2355 for one line of the image. */
2356 for (i = 0; i < height; ++i)
2358 Lisp_Object elt = AREF (data, i);
2360 if (STRINGP (elt))
2362 if (SCHARS (elt)
2363 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2364 return 0;
2366 else if (BOOL_VECTOR_P (elt))
2368 if (XBOOL_VECTOR (elt)->size < width)
2369 return 0;
2371 else
2372 return 0;
2375 else if (STRINGP (data))
2377 if (SCHARS (data)
2378 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2379 return 0;
2381 else if (BOOL_VECTOR_P (data))
2383 if (XBOOL_VECTOR (data)->size / height < width)
2384 return 0;
2386 else
2387 return 0;
2390 return 1;
2394 /* Scan a bitmap file. FP is the stream to read from. Value is
2395 either an enumerator from enum xbm_token, or a character for a
2396 single-character token, or 0 at end of file. If scanning an
2397 identifier, store the lexeme of the identifier in SVAL. If
2398 scanning a number, store its value in *IVAL. */
2400 static int
2401 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2403 unsigned int c;
2405 loop:
2407 /* Skip white space. */
2408 while (*s < end && (c = *(*s)++, isspace (c)))
2411 if (*s >= end)
2412 c = 0;
2413 else if (isdigit (c))
2415 int value = 0, digit;
2417 if (c == '0' && *s < end)
2419 c = *(*s)++;
2420 if (c == 'x' || c == 'X')
2422 while (*s < end)
2424 c = *(*s)++;
2425 if (isdigit (c))
2426 digit = c - '0';
2427 else if (c >= 'a' && c <= 'f')
2428 digit = c - 'a' + 10;
2429 else if (c >= 'A' && c <= 'F')
2430 digit = c - 'A' + 10;
2431 else
2432 break;
2433 value = 16 * value + digit;
2436 else if (isdigit (c))
2438 value = c - '0';
2439 while (*s < end
2440 && (c = *(*s)++, isdigit (c)))
2441 value = 8 * value + c - '0';
2444 else
2446 value = c - '0';
2447 while (*s < end
2448 && (c = *(*s)++, isdigit (c)))
2449 value = 10 * value + c - '0';
2452 if (*s < end)
2453 *s = *s - 1;
2454 *ival = value;
2455 c = XBM_TK_NUMBER;
2457 else if (isalpha (c) || c == '_')
2459 *sval++ = c;
2460 while (*s < end
2461 && (c = *(*s)++, (isalnum (c) || c == '_')))
2462 *sval++ = c;
2463 *sval = 0;
2464 if (*s < end)
2465 *s = *s - 1;
2466 c = XBM_TK_IDENT;
2468 else if (c == '/' && **s == '*')
2470 /* C-style comment. */
2471 ++*s;
2472 while (**s && (**s != '*' || *(*s + 1) != '/'))
2473 ++*s;
2474 if (**s)
2476 *s += 2;
2477 goto loop;
2481 return c;
2484 #ifdef HAVE_NTGUI
2486 /* Create a Windows bitmap from X bitmap data. */
2487 static HBITMAP
2488 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2490 static unsigned char swap_nibble[16]
2491 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2492 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2493 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2494 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2495 int i, j, w1, w2;
2496 unsigned char *bits, *p;
2497 HBITMAP bmp;
2499 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2500 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2501 bits = alloca (height * w2);
2502 memset (bits, 0, height * w2);
2503 for (i = 0; i < height; i++)
2505 p = bits + i*w2;
2506 for (j = 0; j < w1; j++)
2508 /* Bitswap XBM bytes to match how Windows does things. */
2509 unsigned char c = *data++;
2510 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2511 | (swap_nibble[(c>>4) & 0xf]));
2514 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2516 return bmp;
2519 static void
2520 convert_mono_to_color_image (struct frame *f, struct image *img,
2521 COLORREF foreground, COLORREF background)
2523 HDC hdc, old_img_dc, new_img_dc;
2524 HGDIOBJ old_prev, new_prev;
2525 HBITMAP new_pixmap;
2527 hdc = get_frame_dc (f);
2528 old_img_dc = CreateCompatibleDC (hdc);
2529 new_img_dc = CreateCompatibleDC (hdc);
2530 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2531 release_frame_dc (f, hdc);
2532 old_prev = SelectObject (old_img_dc, img->pixmap);
2533 new_prev = SelectObject (new_img_dc, new_pixmap);
2534 /* Windows convention for mono bitmaps is black = background,
2535 white = foreground. */
2536 SetTextColor (new_img_dc, background);
2537 SetBkColor (new_img_dc, foreground);
2539 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2540 0, 0, SRCCOPY);
2542 SelectObject (old_img_dc, old_prev);
2543 SelectObject (new_img_dc, new_prev);
2544 DeleteDC (old_img_dc);
2545 DeleteDC (new_img_dc);
2546 DeleteObject (img->pixmap);
2547 if (new_pixmap == 0)
2548 fprintf (stderr, "Failed to convert image to color.\n");
2549 else
2550 img->pixmap = new_pixmap;
2553 #define XBM_BIT_SHUFFLE(b) (~(b))
2555 #else
2557 #define XBM_BIT_SHUFFLE(b) (b)
2559 #endif /* HAVE_NTGUI */
2562 static void
2563 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2564 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2565 int non_default_colors)
2567 #ifdef HAVE_NTGUI
2568 img->pixmap
2569 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2571 /* If colors were specified, transfer the bitmap to a color one. */
2572 if (non_default_colors)
2573 convert_mono_to_color_image (f, img, fg, bg);
2575 #elif defined (HAVE_NS)
2576 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2578 #else
2579 img->pixmap =
2580 (x_check_image_size (0, img->width, img->height)
2581 ? XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2582 FRAME_X_WINDOW (f),
2583 data,
2584 img->width, img->height,
2585 fg, bg,
2586 DefaultDepthOfScreen (FRAME_X_SCREEN (f)))
2587 : NO_PIXMAP);
2588 #endif /* !HAVE_NTGUI && !HAVE_NS */
2593 /* Replacement for XReadBitmapFileData which isn't available under old
2594 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2595 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2596 the image. Return in *DATA the bitmap data allocated with xmalloc.
2597 Value is non-zero if successful. DATA null means just test if
2598 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR
2599 is non-zero, inhibit the call to image_error when the image size is
2600 invalid (the bitmap remains unread). */
2602 static int
2603 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2604 int *width, int *height, char **data,
2605 int inhibit_image_error)
2607 unsigned char *s = contents;
2608 char buffer[BUFSIZ];
2609 int padding_p = 0;
2610 int v10 = 0;
2611 int bytes_per_line, i, nbytes;
2612 char *p;
2613 int value;
2614 int LA1;
2616 #define match() \
2617 LA1 = xbm_scan (&s, end, buffer, &value)
2619 #define expect(TOKEN) \
2620 if (LA1 != (TOKEN)) \
2621 goto failure; \
2622 else \
2623 match ()
2625 #define expect_ident(IDENT) \
2626 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2627 match (); \
2628 else \
2629 goto failure
2631 *width = *height = -1;
2632 if (data)
2633 *data = NULL;
2634 LA1 = xbm_scan (&s, end, buffer, &value);
2636 /* Parse defines for width, height and hot-spots. */
2637 while (LA1 == '#')
2639 match ();
2640 expect_ident ("define");
2641 expect (XBM_TK_IDENT);
2643 if (LA1 == XBM_TK_NUMBER)
2645 char *q = strrchr (buffer, '_');
2646 q = q ? q + 1 : buffer;
2647 if (strcmp (q, "width") == 0)
2648 *width = value;
2649 else if (strcmp (q, "height") == 0)
2650 *height = value;
2652 expect (XBM_TK_NUMBER);
2655 if (!check_image_size (f, *width, *height))
2657 if (!inhibit_image_error)
2658 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2659 goto failure;
2661 else if (data == NULL)
2662 goto success;
2664 /* Parse bits. Must start with `static'. */
2665 expect_ident ("static");
2666 if (LA1 == XBM_TK_IDENT)
2668 if (strcmp (buffer, "unsigned") == 0)
2670 match ();
2671 expect_ident ("char");
2673 else if (strcmp (buffer, "short") == 0)
2675 match ();
2676 v10 = 1;
2677 if (*width % 16 && *width % 16 < 9)
2678 padding_p = 1;
2680 else if (strcmp (buffer, "char") == 0)
2681 match ();
2682 else
2683 goto failure;
2685 else
2686 goto failure;
2688 expect (XBM_TK_IDENT);
2689 expect ('[');
2690 expect (']');
2691 expect ('=');
2692 expect ('{');
2694 if (! x_check_image_size (0, *width, *height))
2696 if (!inhibit_image_error)
2697 image_error ("Image too large (%dx%d)",
2698 make_number (*width), make_number (*height));
2699 goto failure;
2701 bytes_per_line = (*width + 7) / 8 + padding_p;
2702 nbytes = bytes_per_line * *height;
2703 p = *data = xmalloc (nbytes);
2705 if (v10)
2707 for (i = 0; i < nbytes; i += 2)
2709 int val = value;
2710 expect (XBM_TK_NUMBER);
2712 *p++ = XBM_BIT_SHUFFLE (val);
2713 if (!padding_p || ((i + 2) % bytes_per_line))
2714 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2716 if (LA1 == ',' || LA1 == '}')
2717 match ();
2718 else
2719 goto failure;
2722 else
2724 for (i = 0; i < nbytes; ++i)
2726 int val = value;
2727 expect (XBM_TK_NUMBER);
2729 *p++ = XBM_BIT_SHUFFLE (val);
2731 if (LA1 == ',' || LA1 == '}')
2732 match ();
2733 else
2734 goto failure;
2738 success:
2739 return 1;
2741 failure:
2743 if (data && *data)
2745 xfree (*data);
2746 *data = NULL;
2748 return 0;
2750 #undef match
2751 #undef expect
2752 #undef expect_ident
2756 /* Load XBM image IMG which will be displayed on frame F from buffer
2757 CONTENTS. END is the end of the buffer. Value is non-zero if
2758 successful. */
2760 static int
2761 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2762 unsigned char *end)
2764 int rc;
2765 char *data;
2766 int success_p = 0;
2768 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2769 &data, 0);
2770 if (rc)
2772 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2773 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2774 int non_default_colors = 0;
2775 Lisp_Object value;
2777 eassert (img->width > 0 && img->height > 0);
2779 /* Get foreground and background colors, maybe allocate colors. */
2780 value = image_spec_value (img->spec, QCforeground, NULL);
2781 if (!NILP (value))
2783 foreground = x_alloc_image_color (f, img, value, foreground);
2784 non_default_colors = 1;
2786 value = image_spec_value (img->spec, QCbackground, NULL);
2787 if (!NILP (value))
2789 background = x_alloc_image_color (f, img, value, background);
2790 img->background = background;
2791 img->background_valid = 1;
2792 non_default_colors = 1;
2795 Create_Pixmap_From_Bitmap_Data (f, img, data,
2796 foreground, background,
2797 non_default_colors);
2798 xfree (data);
2800 if (img->pixmap == NO_PIXMAP)
2802 x_clear_image (f, img);
2803 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2805 else
2806 success_p = 1;
2808 else
2809 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2811 return success_p;
2815 /* Value is non-zero if DATA looks like an in-memory XBM file. */
2817 static int
2818 xbm_file_p (Lisp_Object data)
2820 int w, h;
2821 return (STRINGP (data)
2822 && xbm_read_bitmap_data (NULL, SDATA (data),
2823 (SDATA (data) + SBYTES (data)),
2824 &w, &h, NULL, 1));
2828 /* Fill image IMG which is used on frame F with pixmap data. Value is
2829 non-zero if successful. */
2831 static int
2832 xbm_load (struct frame *f, struct image *img)
2834 int success_p = 0;
2835 Lisp_Object file_name;
2837 eassert (xbm_image_p (img->spec));
2839 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2840 file_name = image_spec_value (img->spec, QCfile, NULL);
2841 if (STRINGP (file_name))
2843 Lisp_Object file;
2844 unsigned char *contents;
2845 ptrdiff_t size;
2847 file = x_find_image_file (file_name);
2848 if (!STRINGP (file))
2850 image_error ("Cannot find image file `%s'", file_name, Qnil);
2851 return 0;
2854 contents = slurp_file (SSDATA (file), &size);
2855 if (contents == NULL)
2857 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2858 return 0;
2861 success_p = xbm_load_image (f, img, contents, contents + size);
2862 xfree (contents);
2864 else
2866 struct image_keyword fmt[XBM_LAST];
2867 Lisp_Object data;
2868 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2869 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2870 int non_default_colors = 0;
2871 char *bits;
2872 int parsed_p;
2873 int in_memory_file_p = 0;
2875 /* See if data looks like an in-memory XBM file. */
2876 data = image_spec_value (img->spec, QCdata, NULL);
2877 in_memory_file_p = xbm_file_p (data);
2879 /* Parse the image specification. */
2880 memcpy (fmt, xbm_format, sizeof fmt);
2881 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2882 (void) parsed_p;
2883 eassert (parsed_p);
2885 /* Get specified width, and height. */
2886 if (!in_memory_file_p)
2888 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2889 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2890 eassert (img->width > 0 && img->height > 0);
2891 if (!check_image_size (f, img->width, img->height))
2893 image_error ("Invalid image size (see `max-image-size')",
2894 Qnil, Qnil);
2895 return 0;
2899 /* Get foreground and background colors, maybe allocate colors. */
2900 if (fmt[XBM_FOREGROUND].count
2901 && STRINGP (fmt[XBM_FOREGROUND].value))
2903 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2904 foreground);
2905 non_default_colors = 1;
2908 if (fmt[XBM_BACKGROUND].count
2909 && STRINGP (fmt[XBM_BACKGROUND].value))
2911 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2912 background);
2913 non_default_colors = 1;
2916 if (in_memory_file_p)
2917 success_p = xbm_load_image (f, img, SDATA (data),
2918 (SDATA (data)
2919 + SBYTES (data)));
2920 else
2922 if (VECTORP (data))
2924 int i;
2925 char *p;
2926 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2928 p = bits = alloca (nbytes * img->height);
2929 for (i = 0; i < img->height; ++i, p += nbytes)
2931 Lisp_Object line = AREF (data, i);
2932 if (STRINGP (line))
2933 memcpy (p, SDATA (line), nbytes);
2934 else
2935 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
2938 else if (STRINGP (data))
2939 bits = SSDATA (data);
2940 else
2941 bits = (char *) XBOOL_VECTOR (data)->data;
2943 #ifdef WINDOWSNT
2945 char *invertedBits;
2946 int nbytes, i;
2947 /* Windows mono bitmaps are reversed compared with X. */
2948 invertedBits = bits;
2949 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
2950 * img->height;
2951 bits = alloca (nbytes);
2952 for (i = 0; i < nbytes; i++)
2953 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
2955 #endif
2956 /* Create the pixmap. */
2958 if (x_check_image_size (0, img->width, img->height))
2959 Create_Pixmap_From_Bitmap_Data (f, img, bits,
2960 foreground, background,
2961 non_default_colors);
2962 else
2963 img->pixmap = NO_PIXMAP;
2965 if (img->pixmap)
2966 success_p = 1;
2967 else
2969 image_error ("Unable to create pixmap for XBM image `%s'",
2970 img->spec, Qnil);
2971 x_clear_image (f, img);
2976 return success_p;
2981 /***********************************************************************
2982 XPM images
2983 ***********************************************************************/
2985 #if defined (HAVE_XPM) || defined (HAVE_NS)
2987 static int xpm_image_p (Lisp_Object object);
2988 static int xpm_load (struct frame *f, struct image *img);
2989 static int xpm_valid_color_symbols_p (Lisp_Object);
2991 #endif /* HAVE_XPM || HAVE_NS */
2993 #ifdef HAVE_XPM
2994 #ifdef HAVE_NTGUI
2995 /* Indicate to xpm.h that we don't have Xlib. */
2996 #define FOR_MSW
2997 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
2998 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
2999 #define XColor xpm_XColor
3000 #define XImage xpm_XImage
3001 #define Display xpm_Display
3002 #define PIXEL_ALREADY_TYPEDEFED
3003 #include "X11/xpm.h"
3004 #undef FOR_MSW
3005 #undef XColor
3006 #undef XImage
3007 #undef Display
3008 #undef PIXEL_ALREADY_TYPEDEFED
3009 #else
3010 #include "X11/xpm.h"
3011 #endif /* HAVE_NTGUI */
3012 #endif /* HAVE_XPM */
3014 #if defined (HAVE_XPM) || defined (HAVE_NS)
3015 /* The symbol `xpm' identifying XPM-format images. */
3017 static Lisp_Object Qxpm;
3019 /* Indices of image specification fields in xpm_format, below. */
3021 enum xpm_keyword_index
3023 XPM_TYPE,
3024 XPM_FILE,
3025 XPM_DATA,
3026 XPM_ASCENT,
3027 XPM_MARGIN,
3028 XPM_RELIEF,
3029 XPM_ALGORITHM,
3030 XPM_HEURISTIC_MASK,
3031 XPM_MASK,
3032 XPM_COLOR_SYMBOLS,
3033 XPM_BACKGROUND,
3034 XPM_LAST
3037 /* Vector of image_keyword structures describing the format
3038 of valid XPM image specifications. */
3040 static const struct image_keyword xpm_format[XPM_LAST] =
3042 {":type", IMAGE_SYMBOL_VALUE, 1},
3043 {":file", IMAGE_STRING_VALUE, 0},
3044 {":data", IMAGE_STRING_VALUE, 0},
3045 {":ascent", IMAGE_ASCENT_VALUE, 0},
3046 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
3047 {":relief", IMAGE_INTEGER_VALUE, 0},
3048 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3049 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3050 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3051 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3052 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3055 /* Structure describing the image type XPM. */
3057 static struct image_type xpm_type =
3059 &Qxpm,
3060 xpm_image_p,
3061 xpm_load,
3062 x_clear_image,
3063 NULL
3066 #ifdef HAVE_X_WINDOWS
3068 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3069 functions for allocating image colors. Our own functions handle
3070 color allocation failures more gracefully than the ones on the XPM
3071 lib. */
3073 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3074 #define ALLOC_XPM_COLORS
3075 #endif
3076 #endif /* HAVE_X_WINDOWS */
3078 #ifdef ALLOC_XPM_COLORS
3080 static void xpm_init_color_cache (struct frame *, XpmAttributes *);
3081 static void xpm_free_color_cache (void);
3082 static int xpm_lookup_color (struct frame *, char *, XColor *);
3083 static int xpm_color_bucket (char *);
3084 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3085 XColor *, int);
3087 /* An entry in a hash table used to cache color definitions of named
3088 colors. This cache is necessary to speed up XPM image loading in
3089 case we do color allocations ourselves. Without it, we would need
3090 a call to XParseColor per pixel in the image. */
3092 struct xpm_cached_color
3094 /* Next in collision chain. */
3095 struct xpm_cached_color *next;
3097 /* Color definition (RGB and pixel color). */
3098 XColor color;
3100 /* Color name. */
3101 char name[1];
3104 /* The hash table used for the color cache, and its bucket vector
3105 size. */
3107 #define XPM_COLOR_CACHE_BUCKETS 1001
3108 static struct xpm_cached_color **xpm_color_cache;
3110 /* Initialize the color cache. */
3112 static void
3113 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3115 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3116 xpm_color_cache = xzalloc (nbytes);
3117 init_color_table ();
3119 if (attrs->valuemask & XpmColorSymbols)
3121 int i;
3122 XColor color;
3124 for (i = 0; i < attrs->numsymbols; ++i)
3125 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3126 attrs->colorsymbols[i].value, &color))
3128 color.pixel = lookup_rgb_color (f, color.red, color.green,
3129 color.blue);
3130 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3135 /* Free the color cache. */
3137 static void
3138 xpm_free_color_cache (void)
3140 struct xpm_cached_color *p, *next;
3141 int i;
3143 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3144 for (p = xpm_color_cache[i]; p; p = next)
3146 next = p->next;
3147 xfree (p);
3150 xfree (xpm_color_cache);
3151 xpm_color_cache = NULL;
3152 free_color_table ();
3155 /* Return the bucket index for color named COLOR_NAME in the color
3156 cache. */
3158 static int
3159 xpm_color_bucket (char *color_name)
3161 EMACS_UINT hash = hash_string (color_name, strlen (color_name));
3162 return hash % XPM_COLOR_CACHE_BUCKETS;
3166 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3167 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3168 entry added. */
3170 static struct xpm_cached_color *
3171 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3173 size_t nbytes;
3174 struct xpm_cached_color *p;
3176 if (bucket < 0)
3177 bucket = xpm_color_bucket (color_name);
3179 nbytes = offsetof (struct xpm_cached_color, name) + strlen (color_name) + 1;
3180 p = xmalloc (nbytes);
3181 strcpy (p->name, color_name);
3182 p->color = *color;
3183 p->next = xpm_color_cache[bucket];
3184 xpm_color_cache[bucket] = p;
3185 return p;
3188 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3189 return the cached definition in *COLOR. Otherwise, make a new
3190 entry in the cache and allocate the color. Value is zero if color
3191 allocation failed. */
3193 static int
3194 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3196 struct xpm_cached_color *p;
3197 int h = xpm_color_bucket (color_name);
3199 for (p = xpm_color_cache[h]; p; p = p->next)
3200 if (strcmp (p->name, color_name) == 0)
3201 break;
3203 if (p != NULL)
3204 *color = p->color;
3205 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3206 color_name, color))
3208 color->pixel = lookup_rgb_color (f, color->red, color->green,
3209 color->blue);
3210 p = xpm_cache_color (f, color_name, color, h);
3212 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3213 with transparency, and it's useful. */
3214 else if (strcmp ("opaque", color_name) == 0)
3216 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3217 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3218 p = xpm_cache_color (f, color_name, color, h);
3221 return p != NULL;
3225 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3226 CLOSURE is a pointer to the frame on which we allocate the
3227 color. Return in *COLOR the allocated color. Value is non-zero
3228 if successful. */
3230 static int
3231 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3232 void *closure)
3234 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3238 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3239 is a pointer to the frame on which we allocate the color. Value is
3240 non-zero if successful. */
3242 static int
3243 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3245 return 1;
3248 #endif /* ALLOC_XPM_COLORS */
3251 #ifdef HAVE_NTGUI
3253 /* XPM library details. */
3255 DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
3256 DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage **,
3257 xpm_XImage **, XpmAttributes *));
3258 DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
3259 xpm_XImage **, XpmAttributes *));
3260 DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
3262 static int
3263 init_xpm_functions (Lisp_Object libraries)
3265 HMODULE library;
3267 if (!(library = w32_delayed_load (libraries, Qxpm)))
3268 return 0;
3270 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3271 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3272 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3273 LOAD_IMGLIB_FN (library, XImageFree);
3274 return 1;
3277 #endif /* HAVE_NTGUI */
3280 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3281 for XPM images. Such a list must consist of conses whose car and
3282 cdr are strings. */
3284 static int
3285 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3287 while (CONSP (color_symbols))
3289 Lisp_Object sym = XCAR (color_symbols);
3290 if (!CONSP (sym)
3291 || !STRINGP (XCAR (sym))
3292 || !STRINGP (XCDR (sym)))
3293 break;
3294 color_symbols = XCDR (color_symbols);
3297 return NILP (color_symbols);
3301 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3303 static int
3304 xpm_image_p (Lisp_Object object)
3306 struct image_keyword fmt[XPM_LAST];
3307 memcpy (fmt, xpm_format, sizeof fmt);
3308 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3309 /* Either `:file' or `:data' must be present. */
3310 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3311 /* Either no `:color-symbols' or it's a list of conses
3312 whose car and cdr are strings. */
3313 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3314 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3317 #endif /* HAVE_XPM || HAVE_NS */
3319 #if defined HAVE_XPM && defined HAVE_X_WINDOWS && !defined USE_GTK
3320 ptrdiff_t
3321 x_create_bitmap_from_xpm_data (struct frame *f, const char **bits)
3323 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3324 ptrdiff_t id;
3325 int rc;
3326 XpmAttributes attrs;
3327 Pixmap bitmap, mask;
3329 memset (&attrs, 0, sizeof attrs);
3331 attrs.visual = FRAME_X_VISUAL (f);
3332 attrs.colormap = FRAME_X_COLORMAP (f);
3333 attrs.valuemask |= XpmVisual;
3334 attrs.valuemask |= XpmColormap;
3336 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3337 (char **) bits, &bitmap, &mask, &attrs);
3338 if (rc != XpmSuccess)
3340 XpmFreeAttributes (&attrs);
3341 return -1;
3344 id = x_allocate_bitmap_record (f);
3345 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3346 dpyinfo->bitmaps[id - 1].have_mask = 1;
3347 dpyinfo->bitmaps[id - 1].mask = mask;
3348 dpyinfo->bitmaps[id - 1].file = NULL;
3349 dpyinfo->bitmaps[id - 1].height = attrs.height;
3350 dpyinfo->bitmaps[id - 1].width = attrs.width;
3351 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3352 dpyinfo->bitmaps[id - 1].refcount = 1;
3354 XpmFreeAttributes (&attrs);
3355 return id;
3357 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3359 /* Load image IMG which will be displayed on frame F. Value is
3360 non-zero if successful. */
3362 #ifdef HAVE_XPM
3364 static int
3365 xpm_load (struct frame *f, struct image *img)
3367 int rc;
3368 XpmAttributes attrs;
3369 Lisp_Object specified_file, color_symbols;
3370 #ifdef HAVE_NTGUI
3371 HDC hdc;
3372 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3373 #endif /* HAVE_NTGUI */
3375 /* Configure the XPM lib. Use the visual of frame F. Allocate
3376 close colors. Return colors allocated. */
3377 memset (&attrs, 0, sizeof attrs);
3379 #ifndef HAVE_NTGUI
3380 attrs.visual = FRAME_X_VISUAL (f);
3381 attrs.colormap = FRAME_X_COLORMAP (f);
3382 attrs.valuemask |= XpmVisual;
3383 attrs.valuemask |= XpmColormap;
3384 #endif /* HAVE_NTGUI */
3386 #ifdef ALLOC_XPM_COLORS
3387 /* Allocate colors with our own functions which handle
3388 failing color allocation more gracefully. */
3389 attrs.color_closure = f;
3390 attrs.alloc_color = xpm_alloc_color;
3391 attrs.free_colors = xpm_free_colors;
3392 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3393 #else /* not ALLOC_XPM_COLORS */
3394 /* Let the XPM lib allocate colors. */
3395 attrs.valuemask |= XpmReturnAllocPixels;
3396 #ifdef XpmAllocCloseColors
3397 attrs.alloc_close_colors = 1;
3398 attrs.valuemask |= XpmAllocCloseColors;
3399 #else /* not XpmAllocCloseColors */
3400 attrs.closeness = 600;
3401 attrs.valuemask |= XpmCloseness;
3402 #endif /* not XpmAllocCloseColors */
3403 #endif /* ALLOC_XPM_COLORS */
3405 /* If image specification contains symbolic color definitions, add
3406 these to `attrs'. */
3407 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3408 if (CONSP (color_symbols))
3410 Lisp_Object tail;
3411 XpmColorSymbol *xpm_syms;
3412 int i, size;
3414 attrs.valuemask |= XpmColorSymbols;
3416 /* Count number of symbols. */
3417 attrs.numsymbols = 0;
3418 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3419 ++attrs.numsymbols;
3421 /* Allocate an XpmColorSymbol array. */
3422 size = attrs.numsymbols * sizeof *xpm_syms;
3423 xpm_syms = alloca (size);
3424 memset (xpm_syms, 0, size);
3425 attrs.colorsymbols = xpm_syms;
3427 /* Fill the color symbol array. */
3428 for (tail = color_symbols, i = 0;
3429 CONSP (tail);
3430 ++i, tail = XCDR (tail))
3432 Lisp_Object name;
3433 Lisp_Object color;
3434 char *empty_string = (char *) "";
3436 if (!CONSP (XCAR (tail)))
3438 xpm_syms[i].name = empty_string;
3439 xpm_syms[i].value = empty_string;
3440 continue;
3442 name = XCAR (XCAR (tail));
3443 color = XCDR (XCAR (tail));
3444 if (STRINGP (name))
3446 xpm_syms[i].name = alloca (SCHARS (name) + 1);
3447 strcpy (xpm_syms[i].name, SSDATA (name));
3449 else
3450 xpm_syms[i].name = empty_string;
3451 if (STRINGP (color))
3453 xpm_syms[i].value = alloca (SCHARS (color) + 1);
3454 strcpy (xpm_syms[i].value, SSDATA (color));
3456 else
3457 xpm_syms[i].value = empty_string;
3461 /* Create a pixmap for the image, either from a file, or from a
3462 string buffer containing data in the same format as an XPM file. */
3463 #ifdef ALLOC_XPM_COLORS
3464 xpm_init_color_cache (f, &attrs);
3465 #endif
3467 specified_file = image_spec_value (img->spec, QCfile, NULL);
3469 #ifdef HAVE_NTGUI
3471 HDC frame_dc = get_frame_dc (f);
3472 hdc = CreateCompatibleDC (frame_dc);
3473 release_frame_dc (f, frame_dc);
3475 #endif /* HAVE_NTGUI */
3477 if (STRINGP (specified_file))
3479 Lisp_Object file = x_find_image_file (specified_file);
3480 if (!STRINGP (file))
3482 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3483 #ifdef ALLOC_XPM_COLORS
3484 xpm_free_color_cache ();
3485 #endif
3486 return 0;
3489 #ifdef HAVE_NTGUI
3490 /* XpmReadFileToPixmap is not available in the Windows port of
3491 libxpm. But XpmReadFileToImage almost does what we want. */
3492 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3493 &xpm_image, &xpm_mask,
3494 &attrs);
3495 #else
3496 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3497 SSDATA (file), &img->pixmap, &img->mask,
3498 &attrs);
3499 #endif /* HAVE_NTGUI */
3501 else
3503 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3504 if (!STRINGP (buffer))
3506 image_error ("Invalid image data `%s'", buffer, Qnil);
3507 #ifdef ALLOC_XPM_COLORS
3508 xpm_free_color_cache ();
3509 #endif
3510 return 0;
3512 #ifdef HAVE_NTGUI
3513 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3514 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3515 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3516 &xpm_image, &xpm_mask,
3517 &attrs);
3518 #else
3519 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3520 SSDATA (buffer),
3521 &img->pixmap, &img->mask,
3522 &attrs);
3523 #endif /* HAVE_NTGUI */
3526 if (rc == XpmSuccess)
3528 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3529 img->colors = colors_in_color_table (&img->ncolors);
3530 #else /* not ALLOC_XPM_COLORS */
3531 int i;
3533 #ifdef HAVE_NTGUI
3534 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3535 plus some duplicate attributes. */
3536 if (xpm_image && xpm_image->bitmap)
3538 img->pixmap = xpm_image->bitmap;
3539 /* XImageFree in libXpm frees XImage struct without destroying
3540 the bitmap, which is what we want. */
3541 fn_XImageFree (xpm_image);
3543 if (xpm_mask && xpm_mask->bitmap)
3545 /* The mask appears to be inverted compared with what we expect.
3546 TODO: invert our expectations. See other places where we
3547 have to invert bits because our idea of masks is backwards. */
3548 HGDIOBJ old_obj;
3549 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3551 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3552 SelectObject (hdc, old_obj);
3554 img->mask = xpm_mask->bitmap;
3555 fn_XImageFree (xpm_mask);
3556 DeleteDC (hdc);
3559 DeleteDC (hdc);
3560 #endif /* HAVE_NTGUI */
3562 /* Remember allocated colors. */
3563 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3564 img->ncolors = attrs.nalloc_pixels;
3565 for (i = 0; i < attrs.nalloc_pixels; ++i)
3567 img->colors[i] = attrs.alloc_pixels[i];
3568 #ifdef DEBUG_X_COLORS
3569 register_color (img->colors[i]);
3570 #endif
3572 #endif /* not ALLOC_XPM_COLORS */
3574 img->width = attrs.width;
3575 img->height = attrs.height;
3576 eassert (img->width > 0 && img->height > 0);
3578 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3579 #ifdef HAVE_NTGUI
3580 fn_XpmFreeAttributes (&attrs);
3581 #else
3582 XpmFreeAttributes (&attrs);
3583 #endif /* HAVE_NTGUI */
3585 else
3587 #ifdef HAVE_NTGUI
3588 DeleteDC (hdc);
3589 #endif /* HAVE_NTGUI */
3591 switch (rc)
3593 case XpmOpenFailed:
3594 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3595 break;
3597 case XpmFileInvalid:
3598 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3599 break;
3601 case XpmNoMemory:
3602 image_error ("Out of memory (%s)", img->spec, Qnil);
3603 break;
3605 case XpmColorFailed:
3606 image_error ("Color allocation error (%s)", img->spec, Qnil);
3607 break;
3609 default:
3610 image_error ("Unknown error (%s)", img->spec, Qnil);
3611 break;
3615 #ifdef ALLOC_XPM_COLORS
3616 xpm_free_color_cache ();
3617 #endif
3618 return rc == XpmSuccess;
3621 #endif /* HAVE_XPM */
3623 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3625 /* XPM support functions for NS where libxpm is not available.
3626 Only XPM version 3 (without any extensions) is supported. */
3628 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3629 int, Lisp_Object);
3630 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3631 const unsigned char *, int);
3632 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3633 int, Lisp_Object);
3634 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3635 const unsigned char *, int);
3637 /* Tokens returned from xpm_scan. */
3639 enum xpm_token
3641 XPM_TK_IDENT = 256,
3642 XPM_TK_STRING,
3643 XPM_TK_EOF
3646 /* Scan an XPM data and return a character (< 256) or a token defined
3647 by enum xpm_token above. *S and END are the start (inclusive) and
3648 the end (exclusive) addresses of the data, respectively. Advance
3649 *S while scanning. If token is either XPM_TK_IDENT or
3650 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3651 length of the corresponding token, respectively. */
3653 static int
3654 xpm_scan (const unsigned char **s,
3655 const unsigned char *end,
3656 const unsigned char **beg,
3657 ptrdiff_t *len)
3659 int c;
3661 while (*s < end)
3663 /* Skip white-space. */
3664 while (*s < end && (c = *(*s)++, isspace (c)))
3667 /* gnus-pointer.xpm uses '-' in its identifier.
3668 sb-dir-plus.xpm uses '+' in its identifier. */
3669 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3671 *beg = *s - 1;
3672 while (*s < end
3673 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3674 ++*s;
3675 *len = *s - *beg;
3676 return XPM_TK_IDENT;
3678 else if (c == '"')
3680 *beg = *s;
3681 while (*s < end && **s != '"')
3682 ++*s;
3683 *len = *s - *beg;
3684 if (*s < end)
3685 ++*s;
3686 return XPM_TK_STRING;
3688 else if (c == '/')
3690 if (*s < end && **s == '*')
3692 /* C-style comment. */
3693 ++*s;
3696 while (*s < end && *(*s)++ != '*')
3699 while (*s < end && **s != '/');
3700 if (*s < end)
3701 ++*s;
3703 else
3704 return c;
3706 else
3707 return c;
3710 return XPM_TK_EOF;
3713 /* Functions for color table lookup in XPM data. A key is a string
3714 specifying the color of each pixel in XPM data. A value is either
3715 an integer that specifies a pixel color, Qt that specifies
3716 transparency, or Qnil for the unspecified color. If the length of
3717 the key string is one, a vector is used as a table. Otherwise, a
3718 hash table is used. */
3720 static Lisp_Object
3721 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3722 const unsigned char *,
3723 int,
3724 Lisp_Object),
3725 Lisp_Object (**get_func) (Lisp_Object,
3726 const unsigned char *,
3727 int))
3729 *put_func = xpm_put_color_table_v;
3730 *get_func = xpm_get_color_table_v;
3731 return Fmake_vector (make_number (256), Qnil);
3734 static void
3735 xpm_put_color_table_v (Lisp_Object color_table,
3736 const unsigned char *chars_start,
3737 int chars_len,
3738 Lisp_Object color)
3740 ASET (color_table, *chars_start, color);
3743 static Lisp_Object
3744 xpm_get_color_table_v (Lisp_Object color_table,
3745 const unsigned char *chars_start,
3746 int chars_len)
3748 return AREF (color_table, *chars_start);
3751 static Lisp_Object
3752 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3753 const unsigned char *,
3754 int,
3755 Lisp_Object),
3756 Lisp_Object (**get_func) (Lisp_Object,
3757 const unsigned char *,
3758 int))
3760 *put_func = xpm_put_color_table_h;
3761 *get_func = xpm_get_color_table_h;
3762 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
3763 make_float (DEFAULT_REHASH_SIZE),
3764 make_float (DEFAULT_REHASH_THRESHOLD),
3765 Qnil, Qnil, Qnil);
3768 static void
3769 xpm_put_color_table_h (Lisp_Object color_table,
3770 const unsigned char *chars_start,
3771 int chars_len,
3772 Lisp_Object color)
3774 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3775 EMACS_UINT hash_code;
3776 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3778 hash_lookup (table, chars, &hash_code);
3779 hash_put (table, chars, color, hash_code);
3782 static Lisp_Object
3783 xpm_get_color_table_h (Lisp_Object color_table,
3784 const unsigned char *chars_start,
3785 int chars_len)
3787 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3788 ptrdiff_t i =
3789 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
3791 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3794 enum xpm_color_key {
3795 XPM_COLOR_KEY_S,
3796 XPM_COLOR_KEY_M,
3797 XPM_COLOR_KEY_G4,
3798 XPM_COLOR_KEY_G,
3799 XPM_COLOR_KEY_C
3802 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3804 static int
3805 xpm_str_to_color_key (const char *s)
3807 int i;
3809 for (i = 0;
3810 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3811 i++)
3812 if (strcmp (xpm_color_key_strings[i], s) == 0)
3813 return i;
3814 return -1;
3817 static int
3818 xpm_load_image (struct frame *f,
3819 struct image *img,
3820 const unsigned char *contents,
3821 const unsigned char *end)
3823 const unsigned char *s = contents, *beg, *str;
3824 unsigned char buffer[BUFSIZ];
3825 int width, height, x, y;
3826 int num_colors, chars_per_pixel;
3827 ptrdiff_t len;
3828 int LA1;
3829 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3830 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3831 Lisp_Object frame, color_symbols, color_table;
3832 int best_key, have_mask = 0;
3833 XImagePtr ximg = NULL, mask_img = NULL;
3835 #define match() \
3836 LA1 = xpm_scan (&s, end, &beg, &len)
3838 #define expect(TOKEN) \
3839 if (LA1 != (TOKEN)) \
3840 goto failure; \
3841 else \
3842 match ()
3844 #define expect_ident(IDENT) \
3845 if (LA1 == XPM_TK_IDENT \
3846 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3847 match (); \
3848 else \
3849 goto failure
3851 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3852 goto failure;
3853 s += 9;
3854 match ();
3855 expect_ident ("static");
3856 expect_ident ("char");
3857 expect ('*');
3858 expect (XPM_TK_IDENT);
3859 expect ('[');
3860 expect (']');
3861 expect ('=');
3862 expect ('{');
3863 expect (XPM_TK_STRING);
3864 if (len >= BUFSIZ)
3865 goto failure;
3866 memcpy (buffer, beg, len);
3867 buffer[len] = '\0';
3868 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3869 &num_colors, &chars_per_pixel) != 4
3870 || width <= 0 || height <= 0
3871 || num_colors <= 0 || chars_per_pixel <= 0)
3872 goto failure;
3874 if (!check_image_size (f, width, height))
3876 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
3877 goto failure;
3880 if (!x_create_x_image_and_pixmap (f, width, height, 0,
3881 &ximg, &img->pixmap)
3882 #ifndef HAVE_NS
3883 || !x_create_x_image_and_pixmap (f, width, height, 1,
3884 &mask_img, &img->mask)
3885 #endif
3888 image_error ("Image too large", Qnil, Qnil);
3889 goto failure;
3892 expect (',');
3894 XSETFRAME (frame, f);
3895 if (!NILP (Fxw_display_color_p (frame)))
3896 best_key = XPM_COLOR_KEY_C;
3897 else if (!NILP (Fx_display_grayscale_p (frame)))
3898 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
3899 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
3900 else
3901 best_key = XPM_COLOR_KEY_M;
3903 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3904 if (chars_per_pixel == 1)
3905 color_table = xpm_make_color_table_v (&put_color_table,
3906 &get_color_table);
3907 else
3908 color_table = xpm_make_color_table_h (&put_color_table,
3909 &get_color_table);
3911 while (num_colors-- > 0)
3913 char *color, *max_color;
3914 int key, next_key, max_key = 0;
3915 Lisp_Object symbol_color = Qnil, color_val;
3916 XColor cdef;
3918 expect (XPM_TK_STRING);
3919 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
3920 goto failure;
3921 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
3922 buffer[len - chars_per_pixel] = '\0';
3924 str = strtok (buffer, " \t");
3925 if (str == NULL)
3926 goto failure;
3927 key = xpm_str_to_color_key (str);
3928 if (key < 0)
3929 goto failure;
3932 color = strtok (NULL, " \t");
3933 if (color == NULL)
3934 goto failure;
3936 while ((str = strtok (NULL, " \t")) != NULL)
3938 next_key = xpm_str_to_color_key (str);
3939 if (next_key >= 0)
3940 break;
3941 color[strlen (color)] = ' ';
3944 if (key == XPM_COLOR_KEY_S)
3946 if (NILP (symbol_color))
3947 symbol_color = build_string (color);
3949 else if (max_key < key && key <= best_key)
3951 max_key = key;
3952 max_color = color;
3954 key = next_key;
3956 while (str);
3958 color_val = Qnil;
3959 if (!NILP (color_symbols) && !NILP (symbol_color))
3961 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
3963 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
3965 if (xstrcasecmp (SSDATA (XCDR (specified_color)), "None") == 0)
3966 color_val = Qt;
3967 else if (x_defined_color (f, SSDATA (XCDR (specified_color)),
3968 &cdef, 0))
3969 color_val = make_number (cdef.pixel);
3972 if (NILP (color_val) && max_key > 0)
3974 if (xstrcasecmp (max_color, "None") == 0)
3975 color_val = Qt;
3976 else if (x_defined_color (f, max_color, &cdef, 0))
3977 color_val = make_number (cdef.pixel);
3979 if (!NILP (color_val))
3980 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
3982 expect (',');
3985 for (y = 0; y < height; y++)
3987 expect (XPM_TK_STRING);
3988 str = beg;
3989 if (len < width * chars_per_pixel)
3990 goto failure;
3991 for (x = 0; x < width; x++, str += chars_per_pixel)
3993 Lisp_Object color_val =
3994 (*get_color_table) (color_table, str, chars_per_pixel);
3996 XPutPixel (ximg, x, y,
3997 (INTEGERP (color_val) ? XINT (color_val)
3998 : FRAME_FOREGROUND_PIXEL (f)));
3999 #ifndef HAVE_NS
4000 XPutPixel (mask_img, x, y,
4001 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4002 : (have_mask = 1, PIX_MASK_RETAIN)));
4003 #else
4004 if (EQ (color_val, Qt))
4005 ns_set_alpha (ximg, x, y, 0);
4006 #endif
4008 if (y + 1 < height)
4009 expect (',');
4012 img->width = width;
4013 img->height = height;
4015 /* Maybe fill in the background field while we have ximg handy. */
4016 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4017 IMAGE_BACKGROUND (img, f, ximg);
4019 x_put_x_image (f, ximg, img->pixmap, width, height);
4020 x_destroy_x_image (ximg);
4021 #ifndef HAVE_NS
4022 if (have_mask)
4024 /* Fill in the background_transparent field while we have the
4025 mask handy. */
4026 image_background_transparent (img, f, mask_img);
4028 x_put_x_image (f, mask_img, img->mask, width, height);
4029 x_destroy_x_image (mask_img);
4031 else
4033 x_destroy_x_image (mask_img);
4034 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4035 img->mask = NO_PIXMAP;
4037 #endif
4038 return 1;
4040 failure:
4041 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4042 x_destroy_x_image (ximg);
4043 x_destroy_x_image (mask_img);
4044 x_clear_image (f, img);
4045 return 0;
4047 #undef match
4048 #undef expect
4049 #undef expect_ident
4052 static int
4053 xpm_load (struct frame *f,
4054 struct image *img)
4056 int success_p = 0;
4057 Lisp_Object file_name;
4059 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4060 file_name = image_spec_value (img->spec, QCfile, NULL);
4061 if (STRINGP (file_name))
4063 Lisp_Object file;
4064 unsigned char *contents;
4065 ptrdiff_t size;
4067 file = x_find_image_file (file_name);
4068 if (!STRINGP (file))
4070 image_error ("Cannot find image file `%s'", file_name, Qnil);
4071 return 0;
4074 contents = slurp_file (SSDATA (file), &size);
4075 if (contents == NULL)
4077 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4078 return 0;
4081 success_p = xpm_load_image (f, img, contents, contents + size);
4082 xfree (contents);
4084 else
4086 Lisp_Object data;
4088 data = image_spec_value (img->spec, QCdata, NULL);
4089 if (!STRINGP (data))
4091 image_error ("Invalid image data `%s'", data, Qnil);
4092 return 0;
4094 success_p = xpm_load_image (f, img, SDATA (data),
4095 SDATA (data) + SBYTES (data));
4098 return success_p;
4101 #endif /* HAVE_NS && !HAVE_XPM */
4105 /***********************************************************************
4106 Color table
4107 ***********************************************************************/
4109 #ifdef COLOR_TABLE_SUPPORT
4111 /* An entry in the color table mapping an RGB color to a pixel color. */
4113 struct ct_color
4115 int r, g, b;
4116 unsigned long pixel;
4118 /* Next in color table collision list. */
4119 struct ct_color *next;
4122 /* The bucket vector size to use. Must be prime. */
4124 #define CT_SIZE 101
4126 /* Value is a hash of the RGB color given by R, G, and B. */
4128 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4130 /* The color hash table. */
4132 static struct ct_color **ct_table;
4134 /* Number of entries in the color table. */
4136 static int ct_colors_allocated;
4137 enum
4139 ct_colors_allocated_max =
4140 min (INT_MAX,
4141 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4144 /* Initialize the color table. */
4146 static void
4147 init_color_table (void)
4149 int size = CT_SIZE * sizeof (*ct_table);
4150 ct_table = xzalloc (size);
4151 ct_colors_allocated = 0;
4155 /* Free memory associated with the color table. */
4157 static void
4158 free_color_table (void)
4160 int i;
4161 struct ct_color *p, *next;
4163 for (i = 0; i < CT_SIZE; ++i)
4164 for (p = ct_table[i]; p; p = next)
4166 next = p->next;
4167 xfree (p);
4170 xfree (ct_table);
4171 ct_table = NULL;
4175 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4176 entry for that color already is in the color table, return the
4177 pixel color of that entry. Otherwise, allocate a new color for R,
4178 G, B, and make an entry in the color table. */
4180 static unsigned long
4181 lookup_rgb_color (struct frame *f, int r, int g, int b)
4183 unsigned hash = CT_HASH_RGB (r, g, b);
4184 int i = hash % CT_SIZE;
4185 struct ct_color *p;
4186 Display_Info *dpyinfo;
4188 /* Handle TrueColor visuals specially, which improves performance by
4189 two orders of magnitude. Freeing colors on TrueColor visuals is
4190 a nop, and pixel colors specify RGB values directly. See also
4191 the Xlib spec, chapter 3.1. */
4192 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4193 if (dpyinfo->red_bits > 0)
4195 unsigned long pr, pg, pb;
4197 /* Apply gamma-correction like normal color allocation does. */
4198 if (f->gamma)
4200 XColor color;
4201 color.red = r, color.green = g, color.blue = b;
4202 gamma_correct (f, &color);
4203 r = color.red, g = color.green, b = color.blue;
4206 /* Scale down RGB values to the visual's bits per RGB, and shift
4207 them to the right position in the pixel color. Note that the
4208 original RGB values are 16-bit values, as usual in X. */
4209 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4210 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4211 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4213 /* Assemble the pixel color. */
4214 return pr | pg | pb;
4217 for (p = ct_table[i]; p; p = p->next)
4218 if (p->r == r && p->g == g && p->b == b)
4219 break;
4221 if (p == NULL)
4224 #ifdef HAVE_X_WINDOWS
4225 XColor color;
4226 Colormap cmap;
4227 int rc;
4228 #else
4229 COLORREF color;
4230 #endif
4232 if (ct_colors_allocated_max <= ct_colors_allocated)
4233 return FRAME_FOREGROUND_PIXEL (f);
4235 #ifdef HAVE_X_WINDOWS
4236 color.red = r;
4237 color.green = g;
4238 color.blue = b;
4240 cmap = FRAME_X_COLORMAP (f);
4241 rc = x_alloc_nearest_color (f, cmap, &color);
4242 if (rc)
4244 ++ct_colors_allocated;
4245 p = xmalloc (sizeof *p);
4246 p->r = r;
4247 p->g = g;
4248 p->b = b;
4249 p->pixel = color.pixel;
4250 p->next = ct_table[i];
4251 ct_table[i] = p;
4253 else
4254 return FRAME_FOREGROUND_PIXEL (f);
4256 #else
4257 #ifdef HAVE_NTGUI
4258 color = PALETTERGB (r, g, b);
4259 #else
4260 color = RGB_TO_ULONG (r, g, b);
4261 #endif /* HAVE_NTGUI */
4262 ++ct_colors_allocated;
4263 p = xmalloc (sizeof *p);
4264 p->r = r;
4265 p->g = g;
4266 p->b = b;
4267 p->pixel = color;
4268 p->next = ct_table[i];
4269 ct_table[i] = p;
4270 #endif /* HAVE_X_WINDOWS */
4274 return p->pixel;
4278 /* Look up pixel color PIXEL which is used on frame F in the color
4279 table. If not already present, allocate it. Value is PIXEL. */
4281 static unsigned long
4282 lookup_pixel_color (struct frame *f, unsigned long pixel)
4284 int i = pixel % CT_SIZE;
4285 struct ct_color *p;
4287 for (p = ct_table[i]; p; p = p->next)
4288 if (p->pixel == pixel)
4289 break;
4291 if (p == NULL)
4293 XColor color;
4294 Colormap cmap;
4295 int rc;
4297 if (ct_colors_allocated_max <= ct_colors_allocated)
4298 return FRAME_FOREGROUND_PIXEL (f);
4300 #ifdef HAVE_X_WINDOWS
4301 cmap = FRAME_X_COLORMAP (f);
4302 color.pixel = pixel;
4303 x_query_color (f, &color);
4304 rc = x_alloc_nearest_color (f, cmap, &color);
4305 #else
4306 BLOCK_INPUT;
4307 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4308 color.pixel = pixel;
4309 XQueryColor (NULL, cmap, &color);
4310 rc = x_alloc_nearest_color (f, cmap, &color);
4311 UNBLOCK_INPUT;
4312 #endif /* HAVE_X_WINDOWS */
4314 if (rc)
4316 ++ct_colors_allocated;
4318 p = xmalloc (sizeof *p);
4319 p->r = color.red;
4320 p->g = color.green;
4321 p->b = color.blue;
4322 p->pixel = pixel;
4323 p->next = ct_table[i];
4324 ct_table[i] = p;
4326 else
4327 return FRAME_FOREGROUND_PIXEL (f);
4329 return p->pixel;
4333 /* Value is a vector of all pixel colors contained in the color table,
4334 allocated via xmalloc. Set *N to the number of colors. */
4336 static unsigned long *
4337 colors_in_color_table (int *n)
4339 int i, j;
4340 struct ct_color *p;
4341 unsigned long *colors;
4343 if (ct_colors_allocated == 0)
4345 *n = 0;
4346 colors = NULL;
4348 else
4350 colors = xmalloc (ct_colors_allocated * sizeof *colors);
4351 *n = ct_colors_allocated;
4353 for (i = j = 0; i < CT_SIZE; ++i)
4354 for (p = ct_table[i]; p; p = p->next)
4355 colors[j++] = p->pixel;
4358 return colors;
4361 #else /* COLOR_TABLE_SUPPORT */
4363 static unsigned long
4364 lookup_rgb_color (struct frame *f, int r, int g, int b)
4366 unsigned long pixel;
4368 #ifdef HAVE_NTGUI
4369 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4370 #endif /* HAVE_NTGUI */
4372 #ifdef HAVE_NS
4373 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4374 #endif /* HAVE_NS */
4375 return pixel;
4378 static void
4379 init_color_table (void)
4382 #endif /* COLOR_TABLE_SUPPORT */
4385 /***********************************************************************
4386 Algorithms
4387 ***********************************************************************/
4389 static XColor *x_to_xcolors (struct frame *, struct image *, int);
4390 static void x_from_xcolors (struct frame *, struct image *, XColor *);
4391 static void x_detect_edges (struct frame *, struct image *, int[9], int);
4393 #ifdef HAVE_NTGUI
4394 static void XPutPixel (XImagePtr , int, int, COLORREF);
4395 #endif /* HAVE_NTGUI */
4397 /* Edge detection matrices for different edge-detection
4398 strategies. */
4400 static int emboss_matrix[9] = {
4401 /* x - 1 x x + 1 */
4402 2, -1, 0, /* y - 1 */
4403 -1, 0, 1, /* y */
4404 0, 1, -2 /* y + 1 */
4407 static int laplace_matrix[9] = {
4408 /* x - 1 x x + 1 */
4409 1, 0, 0, /* y - 1 */
4410 0, 0, 0, /* y */
4411 0, 0, -1 /* y + 1 */
4414 /* Value is the intensity of the color whose red/green/blue values
4415 are R, G, and B. */
4417 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4420 /* On frame F, return an array of XColor structures describing image
4421 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4422 non-zero means also fill the red/green/blue members of the XColor
4423 structures. Value is a pointer to the array of XColors structures,
4424 allocated with xmalloc; it must be freed by the caller. */
4426 static XColor *
4427 x_to_xcolors (struct frame *f, struct image *img, int rgb_p)
4429 int x, y;
4430 XColor *colors, *p;
4431 XImagePtr_or_DC ximg;
4432 #ifdef HAVE_NTGUI
4433 HDC hdc;
4434 HGDIOBJ prev;
4435 #endif /* HAVE_NTGUI */
4437 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width < img->height)
4438 memory_full (SIZE_MAX);
4439 colors = xmalloc (sizeof *colors * img->width * img->height);
4441 #ifndef HAVE_NTGUI
4442 /* Get the X image IMG->pixmap. */
4443 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4444 0, 0, img->width, img->height, ~0, ZPixmap);
4445 #else
4446 /* Load the image into a memory device context. */
4447 hdc = get_frame_dc (f);
4448 ximg = CreateCompatibleDC (hdc);
4449 release_frame_dc (f, hdc);
4450 prev = SelectObject (ximg, img->pixmap);
4451 #endif /* HAVE_NTGUI */
4453 /* Fill the `pixel' members of the XColor array. I wished there
4454 were an easy and portable way to circumvent XGetPixel. */
4455 p = colors;
4456 for (y = 0; y < img->height; ++y)
4458 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4459 XColor *row = p;
4460 for (x = 0; x < img->width; ++x, ++p)
4461 p->pixel = GET_PIXEL (ximg, x, y);
4462 if (rgb_p)
4463 x_query_colors (f, row, img->width);
4465 #else
4467 for (x = 0; x < img->width; ++x, ++p)
4469 /* W32_TODO: palette support needed here? */
4470 p->pixel = GET_PIXEL (ximg, x, y);
4471 if (rgb_p)
4473 p->red = RED16_FROM_ULONG (p->pixel);
4474 p->green = GREEN16_FROM_ULONG (p->pixel);
4475 p->blue = BLUE16_FROM_ULONG (p->pixel);
4478 #endif /* HAVE_X_WINDOWS */
4481 Destroy_Image (ximg, prev);
4483 return colors;
4486 #ifdef HAVE_NTGUI
4488 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4489 created with CreateDIBSection, with the pointer to the bit values
4490 stored in ximg->data. */
4492 static void
4493 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4495 int width = ximg->info.bmiHeader.biWidth;
4496 unsigned char * pixel;
4498 /* True color images. */
4499 if (ximg->info.bmiHeader.biBitCount == 24)
4501 int rowbytes = width * 3;
4502 /* Ensure scanlines are aligned on 4 byte boundaries. */
4503 if (rowbytes % 4)
4504 rowbytes += 4 - (rowbytes % 4);
4506 pixel = ximg->data + y * rowbytes + x * 3;
4507 /* Windows bitmaps are in BGR order. */
4508 *pixel = GetBValue (color);
4509 *(pixel + 1) = GetGValue (color);
4510 *(pixel + 2) = GetRValue (color);
4512 /* Monochrome images. */
4513 else if (ximg->info.bmiHeader.biBitCount == 1)
4515 int rowbytes = width / 8;
4516 /* Ensure scanlines are aligned on 4 byte boundaries. */
4517 if (rowbytes % 4)
4518 rowbytes += 4 - (rowbytes % 4);
4519 pixel = ximg->data + y * rowbytes + x / 8;
4520 /* Filter out palette info. */
4521 if (color & 0x00ffffff)
4522 *pixel = *pixel | (1 << x % 8);
4523 else
4524 *pixel = *pixel & ~(1 << x % 8);
4526 else
4527 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4530 #endif /* HAVE_NTGUI */
4532 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4533 RGB members are set. F is the frame on which this all happens.
4534 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4536 static void
4537 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4539 int x, y;
4540 XImagePtr oimg = NULL;
4541 Pixmap pixmap;
4542 XColor *p;
4544 init_color_table ();
4546 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4547 &oimg, &pixmap);
4548 p = colors;
4549 for (y = 0; y < img->height; ++y)
4550 for (x = 0; x < img->width; ++x, ++p)
4552 unsigned long pixel;
4553 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4554 XPutPixel (oimg, x, y, pixel);
4557 xfree (colors);
4558 x_clear_image_1 (f, img, 1, 0, 1);
4560 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4561 x_destroy_x_image (oimg);
4562 img->pixmap = pixmap;
4563 #ifdef COLOR_TABLE_SUPPORT
4564 img->colors = colors_in_color_table (&img->ncolors);
4565 free_color_table ();
4566 #endif /* COLOR_TABLE_SUPPORT */
4570 /* On frame F, perform edge-detection on image IMG.
4572 MATRIX is a nine-element array specifying the transformation
4573 matrix. See emboss_matrix for an example.
4575 COLOR_ADJUST is a color adjustment added to each pixel of the
4576 outgoing image. */
4578 static void
4579 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4581 XColor *colors = x_to_xcolors (f, img, 1);
4582 XColor *new, *p;
4583 int x, y, i, sum;
4585 for (i = sum = 0; i < 9; ++i)
4586 sum += eabs (matrix[i]);
4588 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4590 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width < img->height)
4591 memory_full (SIZE_MAX);
4592 new = xmalloc (sizeof *new * img->width * img->height);
4594 for (y = 0; y < img->height; ++y)
4596 p = COLOR (new, 0, y);
4597 p->red = p->green = p->blue = 0xffff/2;
4598 p = COLOR (new, img->width - 1, y);
4599 p->red = p->green = p->blue = 0xffff/2;
4602 for (x = 1; x < img->width - 1; ++x)
4604 p = COLOR (new, x, 0);
4605 p->red = p->green = p->blue = 0xffff/2;
4606 p = COLOR (new, x, img->height - 1);
4607 p->red = p->green = p->blue = 0xffff/2;
4610 for (y = 1; y < img->height - 1; ++y)
4612 p = COLOR (new, 1, y);
4614 for (x = 1; x < img->width - 1; ++x, ++p)
4616 int r, g, b, yy, xx;
4618 r = g = b = i = 0;
4619 for (yy = y - 1; yy < y + 2; ++yy)
4620 for (xx = x - 1; xx < x + 2; ++xx, ++i)
4621 if (matrix[i])
4623 XColor *t = COLOR (colors, xx, yy);
4624 r += matrix[i] * t->red;
4625 g += matrix[i] * t->green;
4626 b += matrix[i] * t->blue;
4629 r = (r / sum + color_adjust) & 0xffff;
4630 g = (g / sum + color_adjust) & 0xffff;
4631 b = (b / sum + color_adjust) & 0xffff;
4632 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4636 xfree (colors);
4637 x_from_xcolors (f, img, new);
4639 #undef COLOR
4643 /* Perform the pre-defined `emboss' edge-detection on image IMG
4644 on frame F. */
4646 static void
4647 x_emboss (struct frame *f, struct image *img)
4649 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4653 /* Transform image IMG which is used on frame F with a Laplace
4654 edge-detection algorithm. The result is an image that can be used
4655 to draw disabled buttons, for example. */
4657 static void
4658 x_laplace (struct frame *f, struct image *img)
4660 x_detect_edges (f, img, laplace_matrix, 45000);
4664 /* Perform edge-detection on image IMG on frame F, with specified
4665 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4667 MATRIX must be either
4669 - a list of at least 9 numbers in row-major form
4670 - a vector of at least 9 numbers
4672 COLOR_ADJUST nil means use a default; otherwise it must be a
4673 number. */
4675 static void
4676 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4677 Lisp_Object color_adjust)
4679 int i = 0;
4680 int trans[9];
4682 if (CONSP (matrix))
4684 for (i = 0;
4685 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4686 ++i, matrix = XCDR (matrix))
4687 trans[i] = XFLOATINT (XCAR (matrix));
4689 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4691 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4692 trans[i] = XFLOATINT (AREF (matrix, i));
4695 if (NILP (color_adjust))
4696 color_adjust = make_number (0xffff / 2);
4698 if (i == 9 && NUMBERP (color_adjust))
4699 x_detect_edges (f, img, trans, XFLOATINT (color_adjust));
4703 /* Transform image IMG on frame F so that it looks disabled. */
4705 static void
4706 x_disable_image (struct frame *f, struct image *img)
4708 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4709 #ifdef HAVE_NTGUI
4710 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4711 #else
4712 int n_planes = dpyinfo->n_planes;
4713 #endif /* HAVE_NTGUI */
4715 if (n_planes >= 2)
4717 /* Color (or grayscale). Convert to gray, and equalize. Just
4718 drawing such images with a stipple can look very odd, so
4719 we're using this method instead. */
4720 XColor *colors = x_to_xcolors (f, img, 1);
4721 XColor *p, *end;
4722 const int h = 15000;
4723 const int l = 30000;
4725 for (p = colors, end = colors + img->width * img->height;
4726 p < end;
4727 ++p)
4729 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4730 int i2 = (0xffff - h - l) * i / 0xffff + l;
4731 p->red = p->green = p->blue = i2;
4734 x_from_xcolors (f, img, colors);
4737 /* Draw a cross over the disabled image, if we must or if we
4738 should. */
4739 if (n_planes < 2 || cross_disabled_images)
4741 #ifndef HAVE_NTGUI
4742 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4744 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4746 Display *dpy = FRAME_X_DISPLAY (f);
4747 GC gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4748 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4749 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4750 img->width - 1, img->height - 1);
4751 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4752 img->width - 1, 0);
4753 XFreeGC (dpy, gc);
4755 if (img->mask)
4757 gc = XCreateGC (dpy, img->mask, 0, NULL);
4758 XSetForeground (dpy, gc, MaskForeground (f));
4759 XDrawLine (dpy, img->mask, gc, 0, 0,
4760 img->width - 1, img->height - 1);
4761 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4762 img->width - 1, 0);
4763 XFreeGC (dpy, gc);
4765 #endif /* !HAVE_NS */
4766 #else
4767 HDC hdc, bmpdc;
4768 HGDIOBJ prev;
4770 hdc = get_frame_dc (f);
4771 bmpdc = CreateCompatibleDC (hdc);
4772 release_frame_dc (f, hdc);
4774 prev = SelectObject (bmpdc, img->pixmap);
4776 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4777 MoveToEx (bmpdc, 0, 0, NULL);
4778 LineTo (bmpdc, img->width - 1, img->height - 1);
4779 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4780 LineTo (bmpdc, img->width - 1, 0);
4782 if (img->mask)
4784 SelectObject (bmpdc, img->mask);
4785 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4786 MoveToEx (bmpdc, 0, 0, NULL);
4787 LineTo (bmpdc, img->width - 1, img->height - 1);
4788 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4789 LineTo (bmpdc, img->width - 1, 0);
4791 SelectObject (bmpdc, prev);
4792 DeleteDC (bmpdc);
4793 #endif /* HAVE_NTGUI */
4798 /* Build a mask for image IMG which is used on frame F. FILE is the
4799 name of an image file, for error messages. HOW determines how to
4800 determine the background color of IMG. If it is a list '(R G B)',
4801 with R, G, and B being integers >= 0, take that as the color of the
4802 background. Otherwise, determine the background color of IMG
4803 heuristically. Value is non-zero if successful. */
4805 static int
4806 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4808 XImagePtr_or_DC ximg;
4809 #ifndef HAVE_NTGUI
4810 XImagePtr mask_img;
4811 #else
4812 HDC frame_dc;
4813 HGDIOBJ prev;
4814 char *mask_img;
4815 int row_width;
4816 #endif /* HAVE_NTGUI */
4817 int x, y, rc, use_img_background;
4818 unsigned long bg = 0;
4820 if (img->mask)
4822 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4823 img->mask = NO_PIXMAP;
4824 img->background_transparent_valid = 0;
4827 #ifndef HAVE_NTGUI
4828 #ifndef HAVE_NS
4829 /* Create an image and pixmap serving as mask. */
4830 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4831 &mask_img, &img->mask);
4832 if (!rc)
4833 return 0;
4834 #endif /* !HAVE_NS */
4836 /* Get the X image of IMG->pixmap. */
4837 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4838 img->width, img->height,
4839 ~0, ZPixmap);
4840 #else
4841 /* Create the bit array serving as mask. */
4842 row_width = (img->width + 7) / 8;
4843 mask_img = xzalloc (row_width * img->height);
4845 /* Create a memory device context for IMG->pixmap. */
4846 frame_dc = get_frame_dc (f);
4847 ximg = CreateCompatibleDC (frame_dc);
4848 release_frame_dc (f, frame_dc);
4849 prev = SelectObject (ximg, img->pixmap);
4850 #endif /* HAVE_NTGUI */
4852 /* Determine the background color of ximg. If HOW is `(R G B)'
4853 take that as color. Otherwise, use the image's background color. */
4854 use_img_background = 1;
4856 if (CONSP (how))
4858 int rgb[3], i;
4860 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4862 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4863 how = XCDR (how);
4866 if (i == 3 && NILP (how))
4868 char color_name[30];
4869 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4870 bg = (
4871 #ifdef HAVE_NTGUI
4872 0x00ffffff & /* Filter out palette info. */
4873 #endif /* HAVE_NTGUI */
4874 x_alloc_image_color (f, img, build_string (color_name), 0));
4875 use_img_background = 0;
4879 if (use_img_background)
4880 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4882 /* Set all bits in mask_img to 1 whose color in ximg is different
4883 from the background color bg. */
4884 #ifndef HAVE_NTGUI
4885 for (y = 0; y < img->height; ++y)
4886 for (x = 0; x < img->width; ++x)
4887 #ifndef HAVE_NS
4888 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4889 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4890 #else
4891 if (XGetPixel (ximg, x, y) == bg)
4892 ns_set_alpha (ximg, x, y, 0);
4893 #endif /* HAVE_NS */
4894 #ifndef HAVE_NS
4895 /* Fill in the background_transparent field while we have the mask handy. */
4896 image_background_transparent (img, f, mask_img);
4898 /* Put mask_img into img->mask. */
4899 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4900 x_destroy_x_image (mask_img);
4901 #endif /* !HAVE_NS */
4902 #else
4903 for (y = 0; y < img->height; ++y)
4904 for (x = 0; x < img->width; ++x)
4906 COLORREF p = GetPixel (ximg, x, y);
4907 if (p != bg)
4908 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4911 /* Create the mask image. */
4912 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4913 mask_img);
4914 /* Fill in the background_transparent field while we have the mask handy. */
4915 SelectObject (ximg, img->mask);
4916 image_background_transparent (img, f, ximg);
4918 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4919 xfree (mask_img);
4920 #endif /* HAVE_NTGUI */
4922 Destroy_Image (ximg, prev);
4924 return 1;
4928 /***********************************************************************
4929 PBM (mono, gray, color)
4930 ***********************************************************************/
4932 static int pbm_image_p (Lisp_Object object);
4933 static int pbm_load (struct frame *f, struct image *img);
4934 static int pbm_scan_number (unsigned char **, unsigned char *);
4936 /* The symbol `pbm' identifying images of this type. */
4938 static Lisp_Object Qpbm;
4940 /* Indices of image specification fields in gs_format, below. */
4942 enum pbm_keyword_index
4944 PBM_TYPE,
4945 PBM_FILE,
4946 PBM_DATA,
4947 PBM_ASCENT,
4948 PBM_MARGIN,
4949 PBM_RELIEF,
4950 PBM_ALGORITHM,
4951 PBM_HEURISTIC_MASK,
4952 PBM_MASK,
4953 PBM_FOREGROUND,
4954 PBM_BACKGROUND,
4955 PBM_LAST
4958 /* Vector of image_keyword structures describing the format
4959 of valid user-defined image specifications. */
4961 static const struct image_keyword pbm_format[PBM_LAST] =
4963 {":type", IMAGE_SYMBOL_VALUE, 1},
4964 {":file", IMAGE_STRING_VALUE, 0},
4965 {":data", IMAGE_STRING_VALUE, 0},
4966 {":ascent", IMAGE_ASCENT_VALUE, 0},
4967 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
4968 {":relief", IMAGE_INTEGER_VALUE, 0},
4969 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4970 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4971 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4972 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4973 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4976 /* Structure describing the image type `pbm'. */
4978 static struct image_type pbm_type =
4980 &Qpbm,
4981 pbm_image_p,
4982 pbm_load,
4983 x_clear_image,
4984 NULL
4988 /* Return non-zero if OBJECT is a valid PBM image specification. */
4990 static int
4991 pbm_image_p (Lisp_Object object)
4993 struct image_keyword fmt[PBM_LAST];
4995 memcpy (fmt, pbm_format, sizeof fmt);
4997 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
4998 return 0;
5000 /* Must specify either :data or :file. */
5001 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5005 /* Scan a decimal number from *S and return it. Advance *S while
5006 reading the number. END is the end of the string. Value is -1 at
5007 end of input. */
5009 static int
5010 pbm_scan_number (unsigned char **s, unsigned char *end)
5012 int c = 0, val = -1;
5014 while (*s < end)
5016 /* Skip white-space. */
5017 while (*s < end && (c = *(*s)++, isspace (c)))
5020 if (c == '#')
5022 /* Skip comment to end of line. */
5023 while (*s < end && (c = *(*s)++, c != '\n'))
5026 else if (isdigit (c))
5028 /* Read decimal number. */
5029 val = c - '0';
5030 while (*s < end && (c = *(*s)++, isdigit (c)))
5031 val = 10 * val + c - '0';
5032 break;
5034 else
5035 break;
5038 return val;
5042 #ifdef HAVE_NTGUI
5043 #if 0 /* Unused. ++kfs */
5045 /* Read FILE into memory. Value is a pointer to a buffer allocated
5046 with xmalloc holding FILE's contents. Value is null if an error
5047 occurred. *SIZE is set to the size of the file. */
5049 static char *
5050 pbm_read_file (Lisp_Object file, int *size)
5052 FILE *fp = NULL;
5053 char *buf = NULL;
5054 struct stat st;
5056 if (stat (SDATA (file), &st) == 0
5057 && (fp = fopen (SDATA (file), "rb")) != NULL
5058 && 0 <= st.st_size && st.st_size <= min (PTRDIFF_MAX, SIZE_MAX)
5059 && (buf = xmalloc (st.st_size),
5060 fread (buf, 1, st.st_size, fp) == st.st_size))
5062 *size = st.st_size;
5063 fclose (fp);
5065 else
5067 if (fp)
5068 fclose (fp);
5069 if (buf)
5071 xfree (buf);
5072 buf = NULL;
5076 return buf;
5078 #endif
5079 #endif /* HAVE_NTGUI */
5081 /* Load PBM image IMG for use on frame F. */
5083 static int
5084 pbm_load (struct frame *f, struct image *img)
5086 int raw_p, x, y;
5087 int width, height, max_color_idx = 0;
5088 XImagePtr ximg;
5089 Lisp_Object file, specified_file;
5090 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5091 unsigned char *contents = NULL;
5092 unsigned char *end, *p;
5093 ptrdiff_t size;
5095 specified_file = image_spec_value (img->spec, QCfile, NULL);
5097 if (STRINGP (specified_file))
5099 file = x_find_image_file (specified_file);
5100 if (!STRINGP (file))
5102 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5103 return 0;
5106 contents = slurp_file (SSDATA (file), &size);
5107 if (contents == NULL)
5109 image_error ("Error reading `%s'", file, Qnil);
5110 return 0;
5113 p = contents;
5114 end = contents + size;
5116 else
5118 Lisp_Object data;
5119 data = image_spec_value (img->spec, QCdata, NULL);
5120 if (!STRINGP (data))
5122 image_error ("Invalid image data `%s'", data, Qnil);
5123 return 0;
5125 p = SDATA (data);
5126 end = p + SBYTES (data);
5129 /* Check magic number. */
5130 if (end - p < 2 || *p++ != 'P')
5132 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5133 error:
5134 xfree (contents);
5135 return 0;
5138 switch (*p++)
5140 case '1':
5141 raw_p = 0, type = PBM_MONO;
5142 break;
5144 case '2':
5145 raw_p = 0, type = PBM_GRAY;
5146 break;
5148 case '3':
5149 raw_p = 0, type = PBM_COLOR;
5150 break;
5152 case '4':
5153 raw_p = 1, type = PBM_MONO;
5154 break;
5156 case '5':
5157 raw_p = 1, type = PBM_GRAY;
5158 break;
5160 case '6':
5161 raw_p = 1, type = PBM_COLOR;
5162 break;
5164 default:
5165 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5166 goto error;
5169 /* Read width, height, maximum color-component. Characters
5170 starting with `#' up to the end of a line are ignored. */
5171 width = pbm_scan_number (&p, end);
5172 height = pbm_scan_number (&p, end);
5174 if (type != PBM_MONO)
5176 max_color_idx = pbm_scan_number (&p, end);
5177 if (max_color_idx > 65535 || max_color_idx < 0)
5179 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5180 goto error;
5184 if (!check_image_size (f, width, height))
5186 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5187 goto error;
5190 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5191 &ximg, &img->pixmap))
5192 goto error;
5194 /* Initialize the color hash table. */
5195 init_color_table ();
5197 if (type == PBM_MONO)
5199 int c = 0, g;
5200 struct image_keyword fmt[PBM_LAST];
5201 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5202 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5204 /* Parse the image specification. */
5205 memcpy (fmt, pbm_format, sizeof fmt);
5206 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5208 /* Get foreground and background colors, maybe allocate colors. */
5209 if (fmt[PBM_FOREGROUND].count
5210 && STRINGP (fmt[PBM_FOREGROUND].value))
5211 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5212 if (fmt[PBM_BACKGROUND].count
5213 && STRINGP (fmt[PBM_BACKGROUND].value))
5215 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5216 img->background = bg;
5217 img->background_valid = 1;
5220 for (y = 0; y < height; ++y)
5221 for (x = 0; x < width; ++x)
5223 if (raw_p)
5225 if ((x & 7) == 0)
5227 if (p >= end)
5229 x_destroy_x_image (ximg);
5230 x_clear_image (f, img);
5231 image_error ("Invalid image size in image `%s'",
5232 img->spec, Qnil);
5233 goto error;
5235 c = *p++;
5237 g = c & 0x80;
5238 c <<= 1;
5240 else
5241 g = pbm_scan_number (&p, end);
5243 XPutPixel (ximg, x, y, g ? fg : bg);
5246 else
5248 int expected_size = height * width;
5249 if (max_color_idx > 255)
5250 expected_size *= 2;
5251 if (type == PBM_COLOR)
5252 expected_size *= 3;
5254 if (raw_p && p + expected_size > end)
5256 x_destroy_x_image (ximg);
5257 x_clear_image (f, img);
5258 image_error ("Invalid image size in image `%s'",
5259 img->spec, Qnil);
5260 goto error;
5263 for (y = 0; y < height; ++y)
5264 for (x = 0; x < width; ++x)
5266 int r, g, b;
5268 if (type == PBM_GRAY && raw_p)
5270 r = g = b = *p++;
5271 if (max_color_idx > 255)
5272 r = g = b = r * 256 + *p++;
5274 else if (type == PBM_GRAY)
5275 r = g = b = pbm_scan_number (&p, end);
5276 else if (raw_p)
5278 r = *p++;
5279 if (max_color_idx > 255)
5280 r = r * 256 + *p++;
5281 g = *p++;
5282 if (max_color_idx > 255)
5283 g = g * 256 + *p++;
5284 b = *p++;
5285 if (max_color_idx > 255)
5286 b = b * 256 + *p++;
5288 else
5290 r = pbm_scan_number (&p, end);
5291 g = pbm_scan_number (&p, end);
5292 b = pbm_scan_number (&p, end);
5295 if (r < 0 || g < 0 || b < 0)
5297 x_destroy_x_image (ximg);
5298 image_error ("Invalid pixel value in image `%s'",
5299 img->spec, Qnil);
5300 goto error;
5303 /* RGB values are now in the range 0..max_color_idx.
5304 Scale this to the range 0..0xffff supported by X. */
5305 r = (double) r * 65535 / max_color_idx;
5306 g = (double) g * 65535 / max_color_idx;
5307 b = (double) b * 65535 / max_color_idx;
5308 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5312 #ifdef COLOR_TABLE_SUPPORT
5313 /* Store in IMG->colors the colors allocated for the image, and
5314 free the color table. */
5315 img->colors = colors_in_color_table (&img->ncolors);
5316 free_color_table ();
5317 #endif /* COLOR_TABLE_SUPPORT */
5319 img->width = width;
5320 img->height = height;
5322 /* Maybe fill in the background field while we have ximg handy. */
5324 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5325 /* Casting avoids a GCC warning. */
5326 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5328 /* Put the image into a pixmap. */
5329 x_put_x_image (f, ximg, img->pixmap, width, height);
5330 x_destroy_x_image (ximg);
5332 /* X and W32 versions did it here, MAC version above. ++kfs
5333 img->width = width;
5334 img->height = height; */
5336 xfree (contents);
5337 return 1;
5341 /***********************************************************************
5343 ***********************************************************************/
5345 #if defined (HAVE_PNG) || defined (HAVE_NS)
5347 /* Function prototypes. */
5349 static int png_image_p (Lisp_Object object);
5350 static int png_load (struct frame *f, struct image *img);
5352 /* The symbol `png' identifying images of this type. */
5354 static Lisp_Object Qpng;
5356 /* Indices of image specification fields in png_format, below. */
5358 enum png_keyword_index
5360 PNG_TYPE,
5361 PNG_DATA,
5362 PNG_FILE,
5363 PNG_ASCENT,
5364 PNG_MARGIN,
5365 PNG_RELIEF,
5366 PNG_ALGORITHM,
5367 PNG_HEURISTIC_MASK,
5368 PNG_MASK,
5369 PNG_BACKGROUND,
5370 PNG_LAST
5373 /* Vector of image_keyword structures describing the format
5374 of valid user-defined image specifications. */
5376 static const struct image_keyword png_format[PNG_LAST] =
5378 {":type", IMAGE_SYMBOL_VALUE, 1},
5379 {":data", IMAGE_STRING_VALUE, 0},
5380 {":file", IMAGE_STRING_VALUE, 0},
5381 {":ascent", IMAGE_ASCENT_VALUE, 0},
5382 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
5383 {":relief", IMAGE_INTEGER_VALUE, 0},
5384 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5385 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5386 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5387 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5390 /* Structure describing the image type `png'. */
5392 static struct image_type png_type =
5394 &Qpng,
5395 png_image_p,
5396 png_load,
5397 x_clear_image,
5398 NULL
5401 /* Return non-zero if OBJECT is a valid PNG image specification. */
5403 static int
5404 png_image_p (Lisp_Object object)
5406 struct image_keyword fmt[PNG_LAST];
5407 memcpy (fmt, png_format, sizeof fmt);
5409 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5410 return 0;
5412 /* Must specify either the :data or :file keyword. */
5413 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5416 #endif /* HAVE_PNG || HAVE_NS */
5419 #ifdef HAVE_PNG
5421 #ifdef HAVE_NTGUI
5422 /* PNG library details. */
5424 DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
5425 DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
5426 DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, png_voidp,
5427 png_error_ptr, png_error_ptr));
5428 DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
5429 DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, png_infopp));
5430 DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
5431 DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
5432 DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
5433 DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
5434 png_uint_32 *, png_uint_32 *,
5435 int *, int *, int *, int *, int *));
5436 DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
5437 DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
5438 DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
5439 DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
5440 DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
5441 int, int, double));
5442 DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, png_color_16p *));
5443 DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
5444 DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
5445 DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
5446 DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
5447 DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
5448 DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
5450 #if (PNG_LIBPNG_VER >= 10500)
5451 DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int));
5452 DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, size_t));
5453 #endif /* libpng version >= 1.5 */
5455 static int
5456 init_png_functions (Lisp_Object libraries)
5458 HMODULE library;
5460 if (!(library = w32_delayed_load (libraries, Qpng)))
5461 return 0;
5463 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5464 LOAD_IMGLIB_FN (library, png_sig_cmp);
5465 LOAD_IMGLIB_FN (library, png_create_read_struct);
5466 LOAD_IMGLIB_FN (library, png_create_info_struct);
5467 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5468 LOAD_IMGLIB_FN (library, png_set_read_fn);
5469 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5470 LOAD_IMGLIB_FN (library, png_read_info);
5471 LOAD_IMGLIB_FN (library, png_get_IHDR);
5472 LOAD_IMGLIB_FN (library, png_get_valid);
5473 LOAD_IMGLIB_FN (library, png_set_strip_16);
5474 LOAD_IMGLIB_FN (library, png_set_expand);
5475 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5476 LOAD_IMGLIB_FN (library, png_set_background);
5477 LOAD_IMGLIB_FN (library, png_get_bKGD);
5478 LOAD_IMGLIB_FN (library, png_read_update_info);
5479 LOAD_IMGLIB_FN (library, png_get_channels);
5480 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5481 LOAD_IMGLIB_FN (library, png_read_image);
5482 LOAD_IMGLIB_FN (library, png_read_end);
5483 LOAD_IMGLIB_FN (library, png_error);
5485 #if (PNG_LIBPNG_VER >= 10500)
5486 LOAD_IMGLIB_FN (library, png_longjmp);
5487 LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
5488 #endif /* libpng version >= 1.5 */
5490 return 1;
5492 #else
5494 #define fn_png_get_io_ptr png_get_io_ptr
5495 #define fn_png_sig_cmp png_sig_cmp
5496 #define fn_png_create_read_struct png_create_read_struct
5497 #define fn_png_create_info_struct png_create_info_struct
5498 #define fn_png_destroy_read_struct png_destroy_read_struct
5499 #define fn_png_set_read_fn png_set_read_fn
5500 #define fn_png_set_sig_bytes png_set_sig_bytes
5501 #define fn_png_read_info png_read_info
5502 #define fn_png_get_IHDR png_get_IHDR
5503 #define fn_png_get_valid png_get_valid
5504 #define fn_png_set_strip_16 png_set_strip_16
5505 #define fn_png_set_expand png_set_expand
5506 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5507 #define fn_png_set_background png_set_background
5508 #define fn_png_get_bKGD png_get_bKGD
5509 #define fn_png_read_update_info png_read_update_info
5510 #define fn_png_get_channels png_get_channels
5511 #define fn_png_get_rowbytes png_get_rowbytes
5512 #define fn_png_read_image png_read_image
5513 #define fn_png_read_end png_read_end
5514 #define fn_png_error png_error
5516 #if (PNG_LIBPNG_VER >= 10500)
5517 #define fn_png_longjmp png_longjmp
5518 #define fn_png_set_longjmp_fn png_set_longjmp_fn
5519 #endif /* libpng version >= 1.5 */
5521 #endif /* HAVE_NTGUI */
5524 #if (PNG_LIBPNG_VER < 10500)
5525 #define PNG_LONGJMP(ptr) (longjmp ((ptr)->jmpbuf, 1))
5526 #define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
5527 #else
5528 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908) */
5529 #define PNG_LONGJMP(ptr) (fn_png_longjmp ((ptr), 1))
5530 #define PNG_JMPBUF(ptr) \
5531 (*fn_png_set_longjmp_fn ((ptr), longjmp, sizeof (jmp_buf)))
5532 #endif
5534 /* Error and warning handlers installed when the PNG library
5535 is initialized. */
5537 static _Noreturn void
5538 my_png_error (png_struct *png_ptr, const char *msg)
5540 eassert (png_ptr != NULL);
5541 /* Avoid compiler warning about deprecated direct access to
5542 png_ptr's fields in libpng versions 1.4.x. */
5543 image_error ("PNG error: %s", build_string (msg), Qnil);
5544 PNG_LONGJMP (png_ptr);
5548 static void
5549 my_png_warning (png_struct *png_ptr, const char *msg)
5551 eassert (png_ptr != NULL);
5552 image_error ("PNG warning: %s", build_string (msg), Qnil);
5555 /* Memory source for PNG decoding. */
5557 struct png_memory_storage
5559 unsigned char *bytes; /* The data */
5560 ptrdiff_t len; /* How big is it? */
5561 ptrdiff_t index; /* Where are we? */
5565 /* Function set as reader function when reading PNG image from memory.
5566 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5567 bytes from the input to DATA. */
5569 static void
5570 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5572 struct png_memory_storage *tbr
5573 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5575 if (length > tbr->len - tbr->index)
5576 fn_png_error (png_ptr, "Read error");
5578 memcpy (data, tbr->bytes + tbr->index, length);
5579 tbr->index = tbr->index + length;
5583 /* Function set as reader function when reading PNG image from a file.
5584 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5585 bytes from the input to DATA. */
5587 static void
5588 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5590 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5592 if (fread (data, 1, length, fp) < length)
5593 fn_png_error (png_ptr, "Read error");
5597 /* Load PNG image IMG for use on frame F. Value is non-zero if
5598 successful. */
5600 static int
5601 png_load (struct frame *f, struct image *img)
5603 Lisp_Object file, specified_file;
5604 Lisp_Object specified_data;
5605 int x, y;
5606 ptrdiff_t i;
5607 XImagePtr ximg, mask_img = NULL;
5608 png_struct *png_ptr = NULL;
5609 png_info *info_ptr = NULL, *end_info = NULL;
5610 FILE *volatile fp = NULL;
5611 png_byte sig[8];
5612 png_byte * volatile pixels = NULL;
5613 png_byte ** volatile rows = NULL;
5614 png_uint_32 width, height;
5615 int bit_depth, color_type, interlace_type;
5616 png_byte channels;
5617 png_uint_32 row_bytes;
5618 int transparent_p;
5619 struct png_memory_storage tbr; /* Data to be read */
5621 /* Find out what file to load. */
5622 specified_file = image_spec_value (img->spec, QCfile, NULL);
5623 specified_data = image_spec_value (img->spec, QCdata, NULL);
5625 if (NILP (specified_data))
5627 file = x_find_image_file (specified_file);
5628 if (!STRINGP (file))
5630 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5631 return 0;
5634 /* Open the image file. */
5635 fp = fopen (SSDATA (file), "rb");
5636 if (!fp)
5638 image_error ("Cannot open image file `%s'", file, Qnil);
5639 return 0;
5642 /* Check PNG signature. */
5643 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5644 || fn_png_sig_cmp (sig, 0, sizeof sig))
5646 image_error ("Not a PNG file: `%s'", file, Qnil);
5647 fclose (fp);
5648 return 0;
5651 else
5653 if (!STRINGP (specified_data))
5655 image_error ("Invalid image data `%s'", specified_data, Qnil);
5656 return 0;
5659 /* Read from memory. */
5660 tbr.bytes = SDATA (specified_data);
5661 tbr.len = SBYTES (specified_data);
5662 tbr.index = 0;
5664 /* Check PNG signature. */
5665 if (tbr.len < sizeof sig
5666 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5668 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5669 return 0;
5672 /* Need to skip past the signature. */
5673 tbr.bytes += sizeof (sig);
5676 /* Initialize read and info structs for PNG lib. */
5677 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5678 NULL, my_png_error,
5679 my_png_warning);
5680 if (!png_ptr)
5682 if (fp) fclose (fp);
5683 return 0;
5686 info_ptr = fn_png_create_info_struct (png_ptr);
5687 if (!info_ptr)
5689 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5690 if (fp) fclose (fp);
5691 return 0;
5694 end_info = fn_png_create_info_struct (png_ptr);
5695 if (!end_info)
5697 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5698 if (fp) fclose (fp);
5699 return 0;
5702 /* Set error jump-back. We come back here when the PNG library
5703 detects an error. */
5704 if (setjmp (PNG_JMPBUF (png_ptr)))
5706 error:
5707 if (png_ptr)
5708 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5709 xfree (pixels);
5710 xfree (rows);
5711 if (fp) fclose (fp);
5712 return 0;
5715 /* Read image info. */
5716 if (!NILP (specified_data))
5717 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5718 else
5719 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5721 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5722 fn_png_read_info (png_ptr, info_ptr);
5723 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5724 &interlace_type, NULL, NULL);
5726 if (! (width <= INT_MAX && height <= INT_MAX
5727 && check_image_size (f, width, height)))
5729 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5730 goto error;
5733 /* Create the X image and pixmap now, so that the work below can be
5734 omitted if the image is too large for X. */
5735 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5736 &img->pixmap))
5737 goto error;
5739 /* If image contains simply transparency data, we prefer to
5740 construct a clipping mask. */
5741 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5742 transparent_p = 1;
5743 else
5744 transparent_p = 0;
5746 /* This function is easier to write if we only have to handle
5747 one data format: RGB or RGBA with 8 bits per channel. Let's
5748 transform other formats into that format. */
5750 /* Strip more than 8 bits per channel. */
5751 if (bit_depth == 16)
5752 fn_png_set_strip_16 (png_ptr);
5754 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5755 if available. */
5756 fn_png_set_expand (png_ptr);
5758 /* Convert grayscale images to RGB. */
5759 if (color_type == PNG_COLOR_TYPE_GRAY
5760 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5761 fn_png_set_gray_to_rgb (png_ptr);
5763 /* Handle alpha channel by combining the image with a background
5764 color. Do this only if a real alpha channel is supplied. For
5765 simple transparency, we prefer a clipping mask. */
5766 if (!transparent_p)
5768 /* png_color_16 *image_bg; */
5769 Lisp_Object specified_bg
5770 = image_spec_value (img->spec, QCbackground, NULL);
5771 int shift = (bit_depth == 16) ? 0 : 8;
5773 if (STRINGP (specified_bg))
5774 /* The user specified `:background', use that. */
5776 XColor color;
5777 if (x_defined_color (f, SSDATA (specified_bg), &color, 0))
5779 png_color_16 user_bg;
5781 memset (&user_bg, 0, sizeof user_bg);
5782 user_bg.red = color.red >> shift;
5783 user_bg.green = color.green >> shift;
5784 user_bg.blue = color.blue >> shift;
5786 fn_png_set_background (png_ptr, &user_bg,
5787 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5790 else
5792 /* We use the current frame background, ignoring any default
5793 background color set by the image. */
5794 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5795 XColor color;
5796 png_color_16 frame_background;
5798 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5799 x_query_color (f, &color);
5801 memset (&frame_background, 0, sizeof frame_background);
5802 frame_background.red = color.red >> shift;
5803 frame_background.green = color.green >> shift;
5804 frame_background.blue = color.blue >> shift;
5805 #endif /* HAVE_X_WINDOWS */
5807 fn_png_set_background (png_ptr, &frame_background,
5808 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5812 /* Update info structure. */
5813 fn_png_read_update_info (png_ptr, info_ptr);
5815 /* Get number of channels. Valid values are 1 for grayscale images
5816 and images with a palette, 2 for grayscale images with transparency
5817 information (alpha channel), 3 for RGB images, and 4 for RGB
5818 images with alpha channel, i.e. RGBA. If conversions above were
5819 sufficient we should only have 3 or 4 channels here. */
5820 channels = fn_png_get_channels (png_ptr, info_ptr);
5821 eassert (channels == 3 || channels == 4);
5823 /* Number of bytes needed for one row of the image. */
5824 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5826 /* Allocate memory for the image. */
5827 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows < height
5828 || min (PTRDIFF_MAX, SIZE_MAX) / sizeof *pixels / height < row_bytes)
5829 memory_full (SIZE_MAX);
5830 pixels = xmalloc (sizeof *pixels * row_bytes * height);
5831 rows = xmalloc (height * sizeof *rows);
5832 for (i = 0; i < height; ++i)
5833 rows[i] = pixels + i * row_bytes;
5835 /* Read the entire image. */
5836 fn_png_read_image (png_ptr, rows);
5837 fn_png_read_end (png_ptr, info_ptr);
5838 if (fp)
5840 fclose (fp);
5841 fp = NULL;
5844 /* Create an image and pixmap serving as mask if the PNG image
5845 contains an alpha channel. */
5846 if (channels == 4
5847 && !transparent_p
5848 && !x_create_x_image_and_pixmap (f, width, height, 1,
5849 &mask_img, &img->mask))
5851 x_destroy_x_image (ximg);
5852 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5853 img->pixmap = NO_PIXMAP;
5854 goto error;
5857 /* Fill the X image and mask from PNG data. */
5858 init_color_table ();
5860 for (y = 0; y < height; ++y)
5862 png_byte *p = rows[y];
5864 for (x = 0; x < width; ++x)
5866 int r, g, b;
5868 r = *p++ << 8;
5869 g = *p++ << 8;
5870 b = *p++ << 8;
5871 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5872 /* An alpha channel, aka mask channel, associates variable
5873 transparency with an image. Where other image formats
5874 support binary transparency---fully transparent or fully
5875 opaque---PNG allows up to 254 levels of partial transparency.
5876 The PNG library implements partial transparency by combining
5877 the image with a specified background color.
5879 I'm not sure how to handle this here nicely: because the
5880 background on which the image is displayed may change, for
5881 real alpha channel support, it would be necessary to create
5882 a new image for each possible background.
5884 What I'm doing now is that a mask is created if we have
5885 boolean transparency information. Otherwise I'm using
5886 the frame's background color to combine the image with. */
5888 if (channels == 4)
5890 if (mask_img)
5891 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5892 ++p;
5897 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5898 /* Set IMG's background color from the PNG image, unless the user
5899 overrode it. */
5901 png_color_16 *bg;
5902 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5904 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5905 img->background_valid = 1;
5909 #ifdef COLOR_TABLE_SUPPORT
5910 /* Remember colors allocated for this image. */
5911 img->colors = colors_in_color_table (&img->ncolors);
5912 free_color_table ();
5913 #endif /* COLOR_TABLE_SUPPORT */
5915 /* Clean up. */
5916 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5917 xfree (rows);
5918 xfree (pixels);
5920 img->width = width;
5921 img->height = height;
5923 /* Maybe fill in the background field while we have ximg handy.
5924 Casting avoids a GCC warning. */
5925 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5927 /* Put the image into the pixmap, then free the X image and its buffer. */
5928 x_put_x_image (f, ximg, img->pixmap, width, height);
5929 x_destroy_x_image (ximg);
5931 /* Same for the mask. */
5932 if (mask_img)
5934 /* Fill in the background_transparent field while we have the
5935 mask handy. Casting avoids a GCC warning. */
5936 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
5938 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5939 x_destroy_x_image (mask_img);
5942 return 1;
5945 #else /* HAVE_PNG */
5947 #ifdef HAVE_NS
5948 static int
5949 png_load (struct frame *f, struct image *img)
5951 return ns_load_image (f, img,
5952 image_spec_value (img->spec, QCfile, NULL),
5953 image_spec_value (img->spec, QCdata, NULL));
5955 #endif /* HAVE_NS */
5958 #endif /* !HAVE_PNG */
5962 /***********************************************************************
5963 JPEG
5964 ***********************************************************************/
5966 #if defined (HAVE_JPEG) || defined (HAVE_NS)
5968 static int jpeg_image_p (Lisp_Object object);
5969 static int jpeg_load (struct frame *f, struct image *img);
5971 /* The symbol `jpeg' identifying images of this type. */
5973 static Lisp_Object Qjpeg;
5975 /* Indices of image specification fields in gs_format, below. */
5977 enum jpeg_keyword_index
5979 JPEG_TYPE,
5980 JPEG_DATA,
5981 JPEG_FILE,
5982 JPEG_ASCENT,
5983 JPEG_MARGIN,
5984 JPEG_RELIEF,
5985 JPEG_ALGORITHM,
5986 JPEG_HEURISTIC_MASK,
5987 JPEG_MASK,
5988 JPEG_BACKGROUND,
5989 JPEG_LAST
5992 /* Vector of image_keyword structures describing the format
5993 of valid user-defined image specifications. */
5995 static const struct image_keyword jpeg_format[JPEG_LAST] =
5997 {":type", IMAGE_SYMBOL_VALUE, 1},
5998 {":data", IMAGE_STRING_VALUE, 0},
5999 {":file", IMAGE_STRING_VALUE, 0},
6000 {":ascent", IMAGE_ASCENT_VALUE, 0},
6001 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6002 {":relief", IMAGE_INTEGER_VALUE, 0},
6003 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6004 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6005 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6006 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6009 /* Structure describing the image type `jpeg'. */
6011 static struct image_type jpeg_type =
6013 &Qjpeg,
6014 jpeg_image_p,
6015 jpeg_load,
6016 x_clear_image,
6017 NULL
6020 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6022 static int
6023 jpeg_image_p (Lisp_Object object)
6025 struct image_keyword fmt[JPEG_LAST];
6027 memcpy (fmt, jpeg_format, sizeof fmt);
6029 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6030 return 0;
6032 /* Must specify either the :data or :file keyword. */
6033 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6036 #endif /* HAVE_JPEG || HAVE_NS */
6038 #ifdef HAVE_JPEG
6040 /* Work around a warning about HAVE_STDLIB_H being redefined in
6041 jconfig.h. */
6042 #ifdef HAVE_STDLIB_H
6043 #undef HAVE_STDLIB_H
6044 #endif /* HAVE_STLIB_H */
6046 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6047 /* In older releases of the jpeg library, jpeglib.h will define boolean
6048 differently depending on __WIN32__, so make sure it is defined. */
6049 #define __WIN32__ 1
6050 #endif
6052 #include <jpeglib.h>
6053 #include <jerror.h>
6055 #ifdef HAVE_STLIB_H_1
6056 #define HAVE_STDLIB_H 1
6057 #endif
6059 #ifdef HAVE_NTGUI
6061 /* JPEG library details. */
6062 DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
6063 DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
6064 DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
6065 DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
6066 DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
6067 DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
6068 DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr *));
6069 DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
6071 static int
6072 init_jpeg_functions (Lisp_Object libraries)
6074 HMODULE library;
6076 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6077 return 0;
6079 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6080 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6081 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6082 LOAD_IMGLIB_FN (library, jpeg_read_header);
6083 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6084 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6085 LOAD_IMGLIB_FN (library, jpeg_std_error);
6086 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6087 return 1;
6090 /* Wrapper since we can't directly assign the function pointer
6091 to another function pointer that was declared more completely easily. */
6092 static boolean
6093 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6095 return fn_jpeg_resync_to_restart (cinfo, desired);
6098 #else
6100 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress (a)
6101 #define fn_jpeg_start_decompress jpeg_start_decompress
6102 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6103 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6104 #define fn_jpeg_read_header jpeg_read_header
6105 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6106 #define fn_jpeg_std_error jpeg_std_error
6107 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6109 #endif /* HAVE_NTGUI */
6111 struct my_jpeg_error_mgr
6113 struct jpeg_error_mgr pub;
6114 jmp_buf setjmp_buffer;
6118 static _Noreturn void
6119 my_error_exit (j_common_ptr cinfo)
6121 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6122 longjmp (mgr->setjmp_buffer, 1);
6126 /* Init source method for JPEG data source manager. Called by
6127 jpeg_read_header() before any data is actually read. See
6128 libjpeg.doc from the JPEG lib distribution. */
6130 static void
6131 our_common_init_source (j_decompress_ptr cinfo)
6136 /* Method to terminate data source. Called by
6137 jpeg_finish_decompress() after all data has been processed. */
6139 static void
6140 our_common_term_source (j_decompress_ptr cinfo)
6145 /* Fill input buffer method for JPEG data source manager. Called
6146 whenever more data is needed. We read the whole image in one step,
6147 so this only adds a fake end of input marker at the end. */
6149 static JOCTET our_memory_buffer[2];
6151 static boolean
6152 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6154 /* Insert a fake EOI marker. */
6155 struct jpeg_source_mgr *src = cinfo->src;
6157 our_memory_buffer[0] = (JOCTET) 0xFF;
6158 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6160 src->next_input_byte = our_memory_buffer;
6161 src->bytes_in_buffer = 2;
6162 return 1;
6166 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6167 is the JPEG data source manager. */
6169 static void
6170 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6172 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6174 if (src)
6176 if (num_bytes > src->bytes_in_buffer)
6177 ERREXIT (cinfo, JERR_INPUT_EOF);
6179 src->bytes_in_buffer -= num_bytes;
6180 src->next_input_byte += num_bytes;
6185 /* Set up the JPEG lib for reading an image from DATA which contains
6186 LEN bytes. CINFO is the decompression info structure created for
6187 reading the image. */
6189 static void
6190 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, unsigned int len)
6192 struct jpeg_source_mgr *src;
6194 if (cinfo->src == NULL)
6196 /* First time for this JPEG object? */
6197 cinfo->src = (struct jpeg_source_mgr *)
6198 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6199 sizeof (struct jpeg_source_mgr));
6200 src = (struct jpeg_source_mgr *) cinfo->src;
6201 src->next_input_byte = data;
6204 src = (struct jpeg_source_mgr *) cinfo->src;
6205 src->init_source = our_common_init_source;
6206 src->fill_input_buffer = our_memory_fill_input_buffer;
6207 src->skip_input_data = our_memory_skip_input_data;
6208 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6209 src->term_source = our_common_term_source;
6210 src->bytes_in_buffer = len;
6211 src->next_input_byte = data;
6215 struct jpeg_stdio_mgr
6217 struct jpeg_source_mgr mgr;
6218 boolean finished;
6219 FILE *file;
6220 JOCTET *buffer;
6224 /* Size of buffer to read JPEG from file.
6225 Not too big, as we want to use alloc_small. */
6226 #define JPEG_STDIO_BUFFER_SIZE 8192
6229 /* Fill input buffer method for JPEG data source manager. Called
6230 whenever more data is needed. The data is read from a FILE *. */
6232 static boolean
6233 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6235 struct jpeg_stdio_mgr *src;
6237 src = (struct jpeg_stdio_mgr *) cinfo->src;
6238 if (!src->finished)
6240 ptrdiff_t bytes;
6242 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6243 if (bytes > 0)
6244 src->mgr.bytes_in_buffer = bytes;
6245 else
6247 WARNMS (cinfo, JWRN_JPEG_EOF);
6248 src->finished = 1;
6249 src->buffer[0] = (JOCTET) 0xFF;
6250 src->buffer[1] = (JOCTET) JPEG_EOI;
6251 src->mgr.bytes_in_buffer = 2;
6253 src->mgr.next_input_byte = src->buffer;
6256 return 1;
6260 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6261 is the JPEG data source manager. */
6263 static void
6264 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6266 struct jpeg_stdio_mgr *src;
6267 src = (struct jpeg_stdio_mgr *) cinfo->src;
6269 while (num_bytes > 0 && !src->finished)
6271 if (num_bytes <= src->mgr.bytes_in_buffer)
6273 src->mgr.bytes_in_buffer -= num_bytes;
6274 src->mgr.next_input_byte += num_bytes;
6275 break;
6277 else
6279 num_bytes -= src->mgr.bytes_in_buffer;
6280 src->mgr.bytes_in_buffer = 0;
6281 src->mgr.next_input_byte = NULL;
6283 our_stdio_fill_input_buffer (cinfo);
6289 /* Set up the JPEG lib for reading an image from a FILE *.
6290 CINFO is the decompression info structure created for
6291 reading the image. */
6293 static void
6294 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6296 struct jpeg_stdio_mgr *src;
6298 if (cinfo->src != NULL)
6299 src = (struct jpeg_stdio_mgr *) cinfo->src;
6300 else
6302 /* First time for this JPEG object? */
6303 cinfo->src = (struct jpeg_source_mgr *)
6304 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6305 sizeof (struct jpeg_stdio_mgr));
6306 src = (struct jpeg_stdio_mgr *) cinfo->src;
6307 src->buffer = (JOCTET *)
6308 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6309 JPEG_STDIO_BUFFER_SIZE);
6312 src->file = fp;
6313 src->finished = 0;
6314 src->mgr.init_source = our_common_init_source;
6315 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6316 src->mgr.skip_input_data = our_stdio_skip_input_data;
6317 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6318 src->mgr.term_source = our_common_term_source;
6319 src->mgr.bytes_in_buffer = 0;
6320 src->mgr.next_input_byte = NULL;
6324 /* Load image IMG for use on frame F. Patterned after example.c
6325 from the JPEG lib. */
6327 static int
6328 jpeg_load (struct frame *f, struct image *img)
6330 struct jpeg_decompress_struct cinfo;
6331 struct my_jpeg_error_mgr mgr;
6332 Lisp_Object file, specified_file;
6333 Lisp_Object specified_data;
6334 FILE * volatile fp = NULL;
6335 JSAMPARRAY buffer;
6336 int row_stride, x, y;
6337 XImagePtr ximg = NULL;
6338 int rc;
6339 unsigned long *colors;
6340 int width, height;
6342 /* Open the JPEG file. */
6343 specified_file = image_spec_value (img->spec, QCfile, NULL);
6344 specified_data = image_spec_value (img->spec, QCdata, NULL);
6346 if (NILP (specified_data))
6348 file = x_find_image_file (specified_file);
6349 if (!STRINGP (file))
6351 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6352 return 0;
6355 fp = fopen (SSDATA (file), "rb");
6356 if (fp == NULL)
6358 image_error ("Cannot open `%s'", file, Qnil);
6359 return 0;
6362 else if (!STRINGP (specified_data))
6364 image_error ("Invalid image data `%s'", specified_data, Qnil);
6365 return 0;
6368 /* Customize libjpeg's error handling to call my_error_exit when an
6369 error is detected. This function will perform a longjmp. */
6370 cinfo.err = fn_jpeg_std_error (&mgr.pub);
6371 mgr.pub.error_exit = my_error_exit;
6373 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6375 if (rc == 1)
6377 /* Called from my_error_exit. Display a JPEG error. */
6378 char buf[JMSG_LENGTH_MAX];
6379 cinfo.err->format_message ((j_common_ptr) &cinfo, buf);
6380 image_error ("Error reading JPEG image `%s': %s", img->spec,
6381 build_string (buf));
6384 /* Close the input file and destroy the JPEG object. */
6385 if (fp)
6386 fclose ((FILE *) fp);
6387 fn_jpeg_destroy_decompress (&cinfo);
6389 /* If we already have an XImage, free that. */
6390 x_destroy_x_image (ximg);
6392 /* Free pixmap and colors. */
6393 x_clear_image (f, img);
6394 return 0;
6397 /* Create the JPEG decompression object. Let it read from fp.
6398 Read the JPEG image header. */
6399 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6401 if (NILP (specified_data))
6402 jpeg_file_src (&cinfo, (FILE *) fp);
6403 else
6404 jpeg_memory_src (&cinfo, SDATA (specified_data),
6405 SBYTES (specified_data));
6407 fn_jpeg_read_header (&cinfo, 1);
6409 /* Customize decompression so that color quantization will be used.
6410 Start decompression. */
6411 cinfo.quantize_colors = 1;
6412 fn_jpeg_start_decompress (&cinfo);
6413 width = img->width = cinfo.output_width;
6414 height = img->height = cinfo.output_height;
6416 if (!check_image_size (f, width, height))
6418 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6419 longjmp (mgr.setjmp_buffer, 2);
6422 /* Create X image and pixmap. */
6423 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6424 longjmp (mgr.setjmp_buffer, 2);
6426 /* Allocate colors. When color quantization is used,
6427 cinfo.actual_number_of_colors has been set with the number of
6428 colors generated, and cinfo.colormap is a two-dimensional array
6429 of color indices in the range 0..cinfo.actual_number_of_colors.
6430 No more than 255 colors will be generated. */
6432 int i, ir, ig, ib;
6434 if (cinfo.out_color_components > 2)
6435 ir = 0, ig = 1, ib = 2;
6436 else if (cinfo.out_color_components > 1)
6437 ir = 0, ig = 1, ib = 0;
6438 else
6439 ir = 0, ig = 0, ib = 0;
6441 /* Use the color table mechanism because it handles colors that
6442 cannot be allocated nicely. Such colors will be replaced with
6443 a default color, and we don't have to care about which colors
6444 can be freed safely, and which can't. */
6445 init_color_table ();
6446 colors = alloca (cinfo.actual_number_of_colors * sizeof *colors);
6448 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6450 /* Multiply RGB values with 255 because X expects RGB values
6451 in the range 0..0xffff. */
6452 int r = cinfo.colormap[ir][i] << 8;
6453 int g = cinfo.colormap[ig][i] << 8;
6454 int b = cinfo.colormap[ib][i] << 8;
6455 colors[i] = lookup_rgb_color (f, r, g, b);
6458 #ifdef COLOR_TABLE_SUPPORT
6459 /* Remember those colors actually allocated. */
6460 img->colors = colors_in_color_table (&img->ncolors);
6461 free_color_table ();
6462 #endif /* COLOR_TABLE_SUPPORT */
6465 /* Read pixels. */
6466 row_stride = width * cinfo.output_components;
6467 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6468 row_stride, 1);
6469 for (y = 0; y < height; ++y)
6471 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6472 for (x = 0; x < cinfo.output_width; ++x)
6473 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6476 /* Clean up. */
6477 fn_jpeg_finish_decompress (&cinfo);
6478 fn_jpeg_destroy_decompress (&cinfo);
6479 if (fp)
6480 fclose ((FILE *) fp);
6482 /* Maybe fill in the background field while we have ximg handy. */
6483 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6484 /* Casting avoids a GCC warning. */
6485 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6487 /* Put the image into the pixmap. */
6488 x_put_x_image (f, ximg, img->pixmap, width, height);
6489 x_destroy_x_image (ximg);
6490 return 1;
6493 #else /* HAVE_JPEG */
6495 #ifdef HAVE_NS
6496 static int
6497 jpeg_load (struct frame *f, struct image *img)
6499 return ns_load_image (f, img,
6500 image_spec_value (img->spec, QCfile, NULL),
6501 image_spec_value (img->spec, QCdata, NULL));
6503 #endif /* HAVE_NS */
6505 #endif /* !HAVE_JPEG */
6509 /***********************************************************************
6510 TIFF
6511 ***********************************************************************/
6513 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6515 static int tiff_image_p (Lisp_Object object);
6516 static int tiff_load (struct frame *f, struct image *img);
6518 /* The symbol `tiff' identifying images of this type. */
6520 static Lisp_Object Qtiff;
6522 /* Indices of image specification fields in tiff_format, below. */
6524 enum tiff_keyword_index
6526 TIFF_TYPE,
6527 TIFF_DATA,
6528 TIFF_FILE,
6529 TIFF_ASCENT,
6530 TIFF_MARGIN,
6531 TIFF_RELIEF,
6532 TIFF_ALGORITHM,
6533 TIFF_HEURISTIC_MASK,
6534 TIFF_MASK,
6535 TIFF_BACKGROUND,
6536 TIFF_INDEX,
6537 TIFF_LAST
6540 /* Vector of image_keyword structures describing the format
6541 of valid user-defined image specifications. */
6543 static const struct image_keyword tiff_format[TIFF_LAST] =
6545 {":type", IMAGE_SYMBOL_VALUE, 1},
6546 {":data", IMAGE_STRING_VALUE, 0},
6547 {":file", IMAGE_STRING_VALUE, 0},
6548 {":ascent", IMAGE_ASCENT_VALUE, 0},
6549 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6550 {":relief", IMAGE_INTEGER_VALUE, 0},
6551 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6552 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6553 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6554 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6555 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6558 /* Structure describing the image type `tiff'. */
6560 static struct image_type tiff_type =
6562 &Qtiff,
6563 tiff_image_p,
6564 tiff_load,
6565 x_clear_image,
6566 NULL
6569 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6571 static int
6572 tiff_image_p (Lisp_Object object)
6574 struct image_keyword fmt[TIFF_LAST];
6575 memcpy (fmt, tiff_format, sizeof fmt);
6577 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6578 return 0;
6580 /* Must specify either the :data or :file keyword. */
6581 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6584 #endif /* HAVE_TIFF || HAVE_NS */
6586 #ifdef HAVE_TIFF
6588 #include <tiffio.h>
6590 #ifdef HAVE_NTGUI
6592 /* TIFF library details. */
6593 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
6594 DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
6595 DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
6596 DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
6597 TIFFReadWriteProc, TIFFReadWriteProc,
6598 TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
6599 TIFFMapFileProc, TIFFUnmapFileProc));
6600 DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
6601 DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
6602 DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
6603 DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
6605 static int
6606 init_tiff_functions (Lisp_Object libraries)
6608 HMODULE library;
6610 if (!(library = w32_delayed_load (libraries, Qtiff)))
6611 return 0;
6613 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6614 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6615 LOAD_IMGLIB_FN (library, TIFFOpen);
6616 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6617 LOAD_IMGLIB_FN (library, TIFFGetField);
6618 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6619 LOAD_IMGLIB_FN (library, TIFFClose);
6620 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6621 return 1;
6624 #else
6626 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6627 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6628 #define fn_TIFFOpen TIFFOpen
6629 #define fn_TIFFClientOpen TIFFClientOpen
6630 #define fn_TIFFGetField TIFFGetField
6631 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6632 #define fn_TIFFClose TIFFClose
6633 #define fn_TIFFSetDirectory TIFFSetDirectory
6634 #endif /* HAVE_NTGUI */
6637 /* Reading from a memory buffer for TIFF images Based on the PNG
6638 memory source, but we have to provide a lot of extra functions.
6639 Blah.
6641 We really only need to implement read and seek, but I am not
6642 convinced that the TIFF library is smart enough not to destroy
6643 itself if we only hand it the function pointers we need to
6644 override. */
6646 typedef struct
6648 unsigned char *bytes;
6649 ptrdiff_t len;
6650 ptrdiff_t index;
6652 tiff_memory_source;
6654 static tsize_t
6655 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6657 tiff_memory_source *src = (tiff_memory_source *) data;
6659 size = min (size, src->len - src->index);
6660 memcpy (buf, src->bytes + src->index, size);
6661 src->index += size;
6662 return size;
6665 static tsize_t
6666 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6668 return -1;
6671 static toff_t
6672 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6674 tiff_memory_source *src = (tiff_memory_source *) data;
6675 ptrdiff_t idx;
6677 switch (whence)
6679 case SEEK_SET: /* Go from beginning of source. */
6680 idx = off;
6681 break;
6683 case SEEK_END: /* Go from end of source. */
6684 idx = src->len + off;
6685 break;
6687 case SEEK_CUR: /* Go from current position. */
6688 idx = src->index + off;
6689 break;
6691 default: /* Invalid `whence'. */
6692 return -1;
6695 if (idx > src->len || idx < 0)
6696 return -1;
6698 src->index = idx;
6699 return src->index;
6702 static int
6703 tiff_close_memory (thandle_t data)
6705 /* NOOP */
6706 return 0;
6709 static int
6710 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6712 /* It is already _IN_ memory. */
6713 return 0;
6716 static void
6717 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6719 /* We don't need to do this. */
6722 static toff_t
6723 tiff_size_of_memory (thandle_t data)
6725 return ((tiff_memory_source *) data)->len;
6728 /* GCC 3.x on x86 Windows targets has a bug that triggers an internal
6729 compiler error compiling tiff_handler, see Bugzilla bug #17406
6730 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406). Declaring
6731 this function as external works around that problem. */
6732 #if defined (__MINGW32__) && __GNUC__ == 3
6733 # define MINGW_STATIC
6734 #else
6735 # define MINGW_STATIC static
6736 #endif
6738 MINGW_STATIC void
6739 tiff_handler (const char *, const char *, const char *, va_list)
6740 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6741 MINGW_STATIC void
6742 tiff_handler (const char *log_format, const char *title,
6743 const char *format, va_list ap)
6745 /* doprnt is not suitable here, as TIFF handlers are called from
6746 libtiff and are passed arbitrary printf directives. Instead, use
6747 vsnprintf, taking care to be portable to nonstandard environments
6748 where vsnprintf returns -1 on buffer overflow. Since it's just a
6749 log entry, it's OK to truncate it. */
6750 char buf[4000];
6751 int len = vsnprintf (buf, sizeof buf, format, ap);
6752 add_to_log (log_format, build_string (title),
6753 make_string (buf, max (0, min (len, sizeof buf - 1))));
6755 #undef MINGW_STATIC
6757 static void tiff_error_handler (const char *, const char *, va_list)
6758 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6759 static void
6760 tiff_error_handler (const char *title, const char *format, va_list ap)
6762 tiff_handler ("TIFF error: %s %s", title, format, ap);
6766 static void tiff_warning_handler (const char *, const char *, va_list)
6767 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6768 static void
6769 tiff_warning_handler (const char *title, const char *format, va_list ap)
6771 tiff_handler ("TIFF warning: %s %s", title, format, ap);
6775 /* Load TIFF image IMG for use on frame F. Value is non-zero if
6776 successful. */
6778 static int
6779 tiff_load (struct frame *f, struct image *img)
6781 Lisp_Object file, specified_file;
6782 Lisp_Object specified_data;
6783 TIFF *tiff;
6784 int width, height, x, y, count;
6785 uint32 *buf;
6786 int rc;
6787 XImagePtr ximg;
6788 tiff_memory_source memsrc;
6789 Lisp_Object image;
6791 specified_file = image_spec_value (img->spec, QCfile, NULL);
6792 specified_data = image_spec_value (img->spec, QCdata, NULL);
6794 fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
6795 fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
6797 if (NILP (specified_data))
6799 /* Read from a file */
6800 file = x_find_image_file (specified_file);
6801 if (!STRINGP (file))
6803 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6804 return 0;
6807 /* Try to open the image file. */
6808 tiff = fn_TIFFOpen (SSDATA (file), "r");
6809 if (tiff == NULL)
6811 image_error ("Cannot open `%s'", file, Qnil);
6812 return 0;
6815 else
6817 if (!STRINGP (specified_data))
6819 image_error ("Invalid image data `%s'", specified_data, Qnil);
6820 return 0;
6823 /* Memory source! */
6824 memsrc.bytes = SDATA (specified_data);
6825 memsrc.len = SBYTES (specified_data);
6826 memsrc.index = 0;
6828 tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
6829 tiff_read_from_memory,
6830 tiff_write_from_memory,
6831 tiff_seek_in_memory,
6832 tiff_close_memory,
6833 tiff_size_of_memory,
6834 tiff_mmap_memory,
6835 tiff_unmap_memory);
6837 if (!tiff)
6839 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6840 return 0;
6844 image = image_spec_value (img->spec, QCindex, NULL);
6845 if (INTEGERP (image))
6847 EMACS_INT ino = XFASTINT (image);
6848 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
6849 && fn_TIFFSetDirectory (tiff, ino)))
6851 image_error ("Invalid image number `%s' in image `%s'",
6852 image, img->spec);
6853 fn_TIFFClose (tiff);
6854 return 0;
6858 /* Get width and height of the image, and allocate a raster buffer
6859 of width x height 32-bit values. */
6860 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6861 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6863 if (!check_image_size (f, width, height))
6865 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6866 fn_TIFFClose (tiff);
6867 return 0;
6870 /* Create the X image and pixmap. */
6871 if (! (height <= min (PTRDIFF_MAX, SIZE_MAX) / sizeof *buf / width
6872 && x_create_x_image_and_pixmap (f, width, height, 0,
6873 &ximg, &img->pixmap)))
6875 fn_TIFFClose (tiff);
6876 return 0;
6879 buf = xmalloc (sizeof *buf * width * height);
6881 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
6883 /* Count the number of images in the file. */
6884 for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
6885 continue;
6887 if (count > 1)
6888 img->lisp_data = Fcons (Qcount,
6889 Fcons (make_number (count),
6890 img->lisp_data));
6892 fn_TIFFClose (tiff);
6893 if (!rc)
6895 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6896 xfree (buf);
6897 return 0;
6900 /* Initialize the color table. */
6901 init_color_table ();
6903 /* Process the pixel raster. Origin is in the lower-left corner. */
6904 for (y = 0; y < height; ++y)
6906 uint32 *row = buf + y * width;
6908 for (x = 0; x < width; ++x)
6910 uint32 abgr = row[x];
6911 int r = TIFFGetR (abgr) << 8;
6912 int g = TIFFGetG (abgr) << 8;
6913 int b = TIFFGetB (abgr) << 8;
6914 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6918 #ifdef COLOR_TABLE_SUPPORT
6919 /* Remember the colors allocated for the image. Free the color table. */
6920 img->colors = colors_in_color_table (&img->ncolors);
6921 free_color_table ();
6922 #endif /* COLOR_TABLE_SUPPORT */
6924 img->width = width;
6925 img->height = height;
6927 /* Maybe fill in the background field while we have ximg handy. */
6928 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6929 /* Casting avoids a GCC warning on W32. */
6930 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6932 /* Put the image into the pixmap, then free the X image and its buffer. */
6933 x_put_x_image (f, ximg, img->pixmap, width, height);
6934 x_destroy_x_image (ximg);
6935 xfree (buf);
6937 return 1;
6940 #else /* HAVE_TIFF */
6942 #ifdef HAVE_NS
6943 static int
6944 tiff_load (struct frame *f, struct image *img)
6946 return ns_load_image (f, img,
6947 image_spec_value (img->spec, QCfile, NULL),
6948 image_spec_value (img->spec, QCdata, NULL));
6950 #endif /* HAVE_NS */
6952 #endif /* !HAVE_TIFF */
6956 /***********************************************************************
6958 ***********************************************************************/
6960 #if defined (HAVE_GIF) || defined (HAVE_NS)
6962 static int gif_image_p (Lisp_Object object);
6963 static int gif_load (struct frame *f, struct image *img);
6964 static void gif_clear_image (struct frame *f, struct image *img);
6966 /* The symbol `gif' identifying images of this type. */
6968 static Lisp_Object Qgif;
6970 /* Indices of image specification fields in gif_format, below. */
6972 enum gif_keyword_index
6974 GIF_TYPE,
6975 GIF_DATA,
6976 GIF_FILE,
6977 GIF_ASCENT,
6978 GIF_MARGIN,
6979 GIF_RELIEF,
6980 GIF_ALGORITHM,
6981 GIF_HEURISTIC_MASK,
6982 GIF_MASK,
6983 GIF_IMAGE,
6984 GIF_BACKGROUND,
6985 GIF_LAST
6988 /* Vector of image_keyword structures describing the format
6989 of valid user-defined image specifications. */
6991 static const struct image_keyword gif_format[GIF_LAST] =
6993 {":type", IMAGE_SYMBOL_VALUE, 1},
6994 {":data", IMAGE_STRING_VALUE, 0},
6995 {":file", IMAGE_STRING_VALUE, 0},
6996 {":ascent", IMAGE_ASCENT_VALUE, 0},
6997 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
6998 {":relief", IMAGE_INTEGER_VALUE, 0},
6999 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7000 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7001 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7002 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7003 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7006 /* Structure describing the image type `gif'. */
7008 static struct image_type gif_type =
7010 &Qgif,
7011 gif_image_p,
7012 gif_load,
7013 gif_clear_image,
7014 NULL
7017 /* Free X resources of GIF image IMG which is used on frame F. */
7019 static void
7020 gif_clear_image (struct frame *f, struct image *img)
7022 img->lisp_data = Qnil;
7023 x_clear_image (f, img);
7026 /* Return non-zero if OBJECT is a valid GIF image specification. */
7028 static int
7029 gif_image_p (Lisp_Object object)
7031 struct image_keyword fmt[GIF_LAST];
7032 memcpy (fmt, gif_format, sizeof fmt);
7034 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7035 return 0;
7037 /* Must specify either the :data or :file keyword. */
7038 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7041 #endif /* HAVE_GIF */
7043 #ifdef HAVE_GIF
7045 #if defined (HAVE_NTGUI)
7046 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7047 Undefine before redefining to avoid a preprocessor warning. */
7048 #ifdef DrawText
7049 #undef DrawText
7050 #endif
7051 /* avoid conflict with QuickdrawText.h */
7052 #define DrawText gif_DrawText
7053 #include <gif_lib.h>
7054 #undef DrawText
7056 #else /* HAVE_NTGUI */
7058 #include <gif_lib.h>
7060 #endif /* HAVE_NTGUI */
7063 #ifdef HAVE_NTGUI
7065 /* GIF library details. */
7066 DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
7067 DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
7068 DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
7069 DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
7071 static int
7072 init_gif_functions (Lisp_Object libraries)
7074 HMODULE library;
7076 if (!(library = w32_delayed_load (libraries, Qgif)))
7077 return 0;
7079 LOAD_IMGLIB_FN (library, DGifCloseFile);
7080 LOAD_IMGLIB_FN (library, DGifSlurp);
7081 LOAD_IMGLIB_FN (library, DGifOpen);
7082 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7083 return 1;
7086 #else
7088 #define fn_DGifCloseFile DGifCloseFile
7089 #define fn_DGifSlurp DGifSlurp
7090 #define fn_DGifOpen DGifOpen
7091 #define fn_DGifOpenFileName DGifOpenFileName
7093 #endif /* HAVE_NTGUI */
7095 /* Reading a GIF image from memory
7096 Based on the PNG memory stuff to a certain extent. */
7098 typedef struct
7100 unsigned char *bytes;
7101 ptrdiff_t len;
7102 ptrdiff_t index;
7104 gif_memory_source;
7106 /* Make the current memory source available to gif_read_from_memory.
7107 It's done this way because not all versions of libungif support
7108 a UserData field in the GifFileType structure. */
7109 static gif_memory_source *current_gif_memory_src;
7111 static int
7112 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7114 gif_memory_source *src = current_gif_memory_src;
7116 if (len > src->len - src->index)
7117 return -1;
7119 memcpy (buf, src->bytes + src->index, len);
7120 src->index += len;
7121 return len;
7125 /* Load GIF image IMG for use on frame F. Value is non-zero if
7126 successful. */
7128 static const int interlace_start[] = {0, 4, 2, 1};
7129 static const int interlace_increment[] = {8, 8, 4, 2};
7131 #define GIF_LOCAL_DESCRIPTOR_EXTENSION 249
7133 static int
7134 gif_load (struct frame *f, struct image *img)
7136 Lisp_Object file;
7137 int rc, width, height, x, y, i, j;
7138 XImagePtr ximg;
7139 ColorMapObject *gif_color_map;
7140 unsigned long pixel_colors[256];
7141 GifFileType *gif;
7142 gif_memory_source memsrc;
7143 Lisp_Object specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7144 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7145 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7146 unsigned long bgcolor = 0;
7147 EMACS_INT idx;
7149 if (NILP (specified_data))
7151 file = x_find_image_file (specified_file);
7152 if (!STRINGP (file))
7154 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7155 return 0;
7158 /* Open the GIF file. */
7159 gif = fn_DGifOpenFileName (SSDATA (file));
7160 if (gif == NULL)
7162 image_error ("Cannot open `%s'", file, Qnil);
7163 return 0;
7166 else
7168 if (!STRINGP (specified_data))
7170 image_error ("Invalid image data `%s'", specified_data, Qnil);
7171 return 0;
7174 /* Read from memory! */
7175 current_gif_memory_src = &memsrc;
7176 memsrc.bytes = SDATA (specified_data);
7177 memsrc.len = SBYTES (specified_data);
7178 memsrc.index = 0;
7180 gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
7181 if (!gif)
7183 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7184 return 0;
7188 /* Before reading entire contents, check the declared image size. */
7189 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7191 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7192 fn_DGifCloseFile (gif);
7193 return 0;
7196 /* Read entire contents. */
7197 rc = fn_DGifSlurp (gif);
7198 if (rc == GIF_ERROR || gif->ImageCount <= 0)
7200 image_error ("Error reading `%s'", img->spec, Qnil);
7201 fn_DGifCloseFile (gif);
7202 return 0;
7205 /* Which sub-image are we to display? */
7207 Lisp_Object image_number = image_spec_value (img->spec, QCindex, NULL);
7208 idx = INTEGERP (image_number) ? XFASTINT (image_number) : 0;
7209 if (idx < 0 || idx >= gif->ImageCount)
7211 image_error ("Invalid image number `%s' in image `%s'",
7212 image_number, img->spec);
7213 fn_DGifCloseFile (gif);
7214 return 0;
7218 width = img->width = gif->SWidth;
7219 height = img->height = gif->SHeight;
7221 img->corners[TOP_CORNER] = gif->SavedImages[0].ImageDesc.Top;
7222 img->corners[LEFT_CORNER] = gif->SavedImages[0].ImageDesc.Left;
7223 img->corners[BOT_CORNER]
7224 = img->corners[TOP_CORNER] + gif->SavedImages[0].ImageDesc.Height;
7225 img->corners[RIGHT_CORNER]
7226 = img->corners[LEFT_CORNER] + gif->SavedImages[0].ImageDesc.Width;
7228 if (!check_image_size (f, width, height))
7230 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7231 fn_DGifCloseFile (gif);
7232 return 0;
7235 /* Create the X image and pixmap. */
7236 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7238 fn_DGifCloseFile (gif);
7239 return 0;
7242 /* Clear the part of the screen image not covered by the image.
7243 Full animated GIF support requires more here (see the gif89 spec,
7244 disposal methods). Let's simply assume that the part not covered
7245 by a sub-image is in the frame's background color. */
7246 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7247 for (x = 0; x < width; ++x)
7248 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7250 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7251 for (x = 0; x < width; ++x)
7252 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7254 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7256 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7257 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7258 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7259 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7262 /* Read the GIF image into the X image. */
7264 /* FIXME: With the current implementation, loading an animated gif
7265 is quadratic in the number of animation frames, since each frame
7266 is a separate struct image. We must provide a way for a single
7267 gif_load call to construct and save all animation frames. */
7269 init_color_table ();
7270 if (STRINGP (specified_bg))
7271 bgcolor = x_alloc_image_color (f, img, specified_bg,
7272 FRAME_BACKGROUND_PIXEL (f));
7273 for (j = 0; j <= idx; ++j)
7275 /* We use a local variable `raster' here because RasterBits is a
7276 char *, which invites problems with bytes >= 0x80. */
7277 struct SavedImage *subimage = gif->SavedImages + j;
7278 unsigned char *raster = (unsigned char *) subimage->RasterBits;
7279 int transparency_color_index = -1;
7280 int disposal = 0;
7281 int subimg_width = subimage->ImageDesc.Width;
7282 int subimg_height = subimage->ImageDesc.Height;
7283 int subimg_top = subimage->ImageDesc.Top;
7284 int subimg_left = subimage->ImageDesc.Left;
7286 /* Find the Graphic Control Extension block for this sub-image.
7287 Extract the disposal method and transparency color. */
7288 for (i = 0; i < subimage->ExtensionBlockCount; i++)
7290 ExtensionBlock *extblock = subimage->ExtensionBlocks + i;
7292 if ((extblock->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION)
7293 && extblock->ByteCount == 4
7294 && extblock->Bytes[0] & 1)
7296 /* From gif89a spec: 1 = "keep in place", 2 = "restore
7297 to background". Treat any other value like 2. */
7298 disposal = (extblock->Bytes[0] >> 2) & 7;
7299 transparency_color_index = (unsigned char) extblock->Bytes[3];
7300 break;
7304 /* We can't "keep in place" the first subimage. */
7305 if (j == 0)
7306 disposal = 2;
7308 /* For disposal == 0, the spec says "No disposal specified. The
7309 decoder is not required to take any action." In practice, it
7310 seems we need to treat this like "keep in place", see e.g.
7311 http://upload.wikimedia.org/wikipedia/commons/3/37/Clock.gif */
7312 if (disposal == 0)
7313 disposal = 1;
7315 /* Allocate subimage colors. */
7316 memset (pixel_colors, 0, sizeof pixel_colors);
7317 gif_color_map = subimage->ImageDesc.ColorMap;
7318 if (!gif_color_map)
7319 gif_color_map = gif->SColorMap;
7321 if (gif_color_map)
7322 for (i = 0; i < gif_color_map->ColorCount; ++i)
7324 if (transparency_color_index == i)
7325 pixel_colors[i] = STRINGP (specified_bg)
7326 ? bgcolor : FRAME_BACKGROUND_PIXEL (f);
7327 else
7329 int r = gif_color_map->Colors[i].Red << 8;
7330 int g = gif_color_map->Colors[i].Green << 8;
7331 int b = gif_color_map->Colors[i].Blue << 8;
7332 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7336 /* Apply the pixel values. */
7337 if (gif->SavedImages[j].ImageDesc.Interlace)
7339 int row, pass;
7341 for (y = 0, row = interlace_start[0], pass = 0;
7342 y < subimg_height;
7343 y++, row += interlace_increment[pass])
7345 if (row >= subimg_height)
7347 row = interlace_start[++pass];
7348 while (row >= subimg_height)
7349 row = interlace_start[++pass];
7352 for (x = 0; x < subimg_width; x++)
7354 int c = raster[y * subimg_width + x];
7355 if (transparency_color_index != c || disposal != 1)
7356 XPutPixel (ximg, x + subimg_left, row + subimg_top,
7357 pixel_colors[c]);
7361 else
7363 for (y = 0; y < subimg_height; ++y)
7364 for (x = 0; x < subimg_width; ++x)
7366 int c = raster[y * subimg_width + x];
7367 if (transparency_color_index != c || disposal != 1)
7368 XPutPixel (ximg, x + subimg_left, y + subimg_top,
7369 pixel_colors[c]);
7374 #ifdef COLOR_TABLE_SUPPORT
7375 img->colors = colors_in_color_table (&img->ncolors);
7376 free_color_table ();
7377 #endif /* COLOR_TABLE_SUPPORT */
7379 /* Save GIF image extension data for `image-metadata'.
7380 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7381 img->lisp_data = Qnil;
7382 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7384 int delay = 0;
7385 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7386 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7387 /* Append (... FUNCTION "BYTES") */
7389 img->lisp_data
7390 = Fcons (make_number (ext->Function),
7391 Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7392 img->lisp_data));
7393 if (ext->Function == GIF_LOCAL_DESCRIPTOR_EXTENSION
7394 && ext->ByteCount == 4)
7396 delay = ext->Bytes[2] << CHAR_BIT;
7397 delay |= ext->Bytes[1];
7400 img->lisp_data = Fcons (Qextension_data,
7401 Fcons (img->lisp_data, Qnil));
7402 if (delay)
7403 img->lisp_data
7404 = Fcons (Qdelay,
7405 Fcons (make_float (delay / 100.0),
7406 img->lisp_data));
7409 if (gif->ImageCount > 1)
7410 img->lisp_data = Fcons (Qcount,
7411 Fcons (make_number (gif->ImageCount),
7412 img->lisp_data));
7414 fn_DGifCloseFile (gif);
7416 /* Maybe fill in the background field while we have ximg handy. */
7417 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7418 /* Casting avoids a GCC warning. */
7419 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7421 /* Put the image into the pixmap, then free the X image and its buffer. */
7422 x_put_x_image (f, ximg, img->pixmap, width, height);
7423 x_destroy_x_image (ximg);
7425 return 1;
7428 #else /* !HAVE_GIF */
7430 #ifdef HAVE_NS
7431 static int
7432 gif_load (struct frame *f, struct image *img)
7434 return ns_load_image (f, img,
7435 image_spec_value (img->spec, QCfile, NULL),
7436 image_spec_value (img->spec, QCdata, NULL));
7438 #endif /* HAVE_NS */
7440 #endif /* HAVE_GIF */
7443 /***********************************************************************
7444 ImageMagick
7445 ***********************************************************************/
7446 #if defined (HAVE_IMAGEMAGICK)
7448 static Lisp_Object Qimagemagick;
7450 static int imagemagick_image_p (Lisp_Object);
7451 static int imagemagick_load (struct frame *, struct image *);
7452 static void imagemagick_clear_image (struct frame *, struct image *);
7454 /* Indices of image specification fields in imagemagick_format. */
7456 enum imagemagick_keyword_index
7458 IMAGEMAGICK_TYPE,
7459 IMAGEMAGICK_DATA,
7460 IMAGEMAGICK_FILE,
7461 IMAGEMAGICK_ASCENT,
7462 IMAGEMAGICK_MARGIN,
7463 IMAGEMAGICK_RELIEF,
7464 IMAGEMAGICK_ALGORITHM,
7465 IMAGEMAGICK_HEURISTIC_MASK,
7466 IMAGEMAGICK_MASK,
7467 IMAGEMAGICK_BACKGROUND,
7468 IMAGEMAGICK_HEIGHT,
7469 IMAGEMAGICK_WIDTH,
7470 IMAGEMAGICK_ROTATION,
7471 IMAGEMAGICK_CROP,
7472 IMAGEMAGICK_LAST
7475 /* Vector of image_keyword structures describing the format
7476 of valid user-defined image specifications. */
7478 static struct image_keyword imagemagick_format[IMAGEMAGICK_LAST] =
7480 {":type", IMAGE_SYMBOL_VALUE, 1},
7481 {":data", IMAGE_STRING_VALUE, 0},
7482 {":file", IMAGE_STRING_VALUE, 0},
7483 {":ascent", IMAGE_ASCENT_VALUE, 0},
7484 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
7485 {":relief", IMAGE_INTEGER_VALUE, 0},
7486 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7487 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7488 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7489 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
7490 {":height", IMAGE_INTEGER_VALUE, 0},
7491 {":width", IMAGE_INTEGER_VALUE, 0},
7492 {":rotation", IMAGE_NUMBER_VALUE, 0},
7493 {":crop", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
7496 /* Structure describing the image type for any image handled via
7497 ImageMagick. */
7499 static struct image_type imagemagick_type =
7501 &Qimagemagick,
7502 imagemagick_image_p,
7503 imagemagick_load,
7504 imagemagick_clear_image,
7505 NULL
7508 /* Free X resources of imagemagick image IMG which is used on frame F. */
7510 static void
7511 imagemagick_clear_image (struct frame *f,
7512 struct image *img)
7514 x_clear_image (f, img);
7517 /* Return non-zero if OBJECT is a valid IMAGEMAGICK image specification. Do
7518 this by calling parse_image_spec and supplying the keywords that
7519 identify the IMAGEMAGICK format. */
7521 static int
7522 imagemagick_image_p (Lisp_Object object)
7524 struct image_keyword fmt[IMAGEMAGICK_LAST];
7525 memcpy (fmt, imagemagick_format, sizeof fmt);
7527 if (!parse_image_spec (object, fmt, IMAGEMAGICK_LAST, Qimagemagick))
7528 return 0;
7530 /* Must specify either the :data or :file keyword. */
7531 return fmt[IMAGEMAGICK_FILE].count + fmt[IMAGEMAGICK_DATA].count == 1;
7534 /* The GIF library also defines DrawRectangle, but its never used in Emacs.
7535 Therefore rename the function so it doesn't collide with ImageMagick. */
7536 #define DrawRectangle DrawRectangleGif
7537 #include <wand/MagickWand.h>
7539 /* ImageMagick 6.5.3 through 6.6.5 hid PixelGetMagickColor for some reason.
7540 Emacs seems to work fine with the hidden version, so unhide it. */
7541 #include <magick/version.h>
7542 #if 0x653 <= MagickLibVersion && MagickLibVersion <= 0x665
7543 extern WandExport void PixelGetMagickColor (const PixelWand *,
7544 MagickPixelPacket *);
7545 #endif
7547 /* Log ImageMagick error message.
7548 Useful when a ImageMagick function returns the status `MagickFalse'. */
7550 static void
7551 imagemagick_error (MagickWand *wand)
7553 char *description;
7554 ExceptionType severity;
7556 description = MagickGetException (wand, &severity);
7557 image_error ("ImageMagick error: %s",
7558 build_string (description),
7559 Qnil);
7560 description = (char *) MagickRelinquishMemory (description);
7563 /* Helper function for imagemagick_load, which does the actual loading
7564 given contents and size, apart from frame and image structures,
7565 passed from imagemagick_load. Uses librimagemagick to do most of
7566 the image processing.
7568 F is a pointer to the Emacs frame; IMG to the image structure to
7569 prepare; CONTENTS is the string containing the IMAGEMAGICK data to
7570 be parsed; SIZE is the number of bytes of data; and FILENAME is
7571 either the file name or the image data.
7573 Return non-zero if successful. */
7575 static int
7576 imagemagick_load_image (struct frame *f, struct image *img,
7577 unsigned char *contents, unsigned int size,
7578 char *filename)
7580 size_t width, height;
7581 MagickBooleanType status;
7582 XImagePtr ximg;
7583 int x, y;
7584 MagickWand *image_wand;
7585 MagickWand *ping_wand;
7586 PixelIterator *iterator;
7587 PixelWand **pixels, *bg_wand = NULL;
7588 MagickPixelPacket pixel;
7589 Lisp_Object image;
7590 Lisp_Object value;
7591 Lisp_Object crop;
7592 EMACS_INT ino;
7593 int desired_width, desired_height;
7594 double rotation;
7595 int pixelwidth;
7597 /* Handle image index for image types who can contain more than one image.
7598 Interface :index is same as for GIF. First we "ping" the image to see how
7599 many sub-images it contains. Pinging is faster than loading the image to
7600 find out things about it. */
7602 /* Initialize the imagemagick environment. */
7603 MagickWandGenesis ();
7604 image = image_spec_value (img->spec, QCindex, NULL);
7605 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7606 ping_wand = NewMagickWand ();
7607 /* MagickSetResolution (ping_wand, 2, 2); (Bug#10112) */
7609 status = filename
7610 ? MagickPingImage (ping_wand, filename)
7611 : MagickPingImageBlob (ping_wand, contents, size);
7613 if (status == MagickFalse)
7615 imagemagick_error (ping_wand);
7616 DestroyMagickWand (ping_wand);
7617 return 0;
7620 if (ino < 0 || ino >= MagickGetNumberImages (ping_wand))
7622 image_error ("Invalid image number `%s' in image `%s'",
7623 image, img->spec);
7624 DestroyMagickWand (ping_wand);
7625 return 0;
7628 if (MagickGetNumberImages (ping_wand) > 1)
7629 img->lisp_data =
7630 Fcons (Qcount,
7631 Fcons (make_number (MagickGetNumberImages (ping_wand)),
7632 img->lisp_data));
7634 DestroyMagickWand (ping_wand);
7636 /* Now we know how many images are inside the file. If it's not a
7637 bundle, the number is one. Load the image data. */
7639 image_wand = NewMagickWand ();
7641 if ((filename
7642 ? MagickReadImage (image_wand, filename)
7643 : MagickReadImageBlob (image_wand, contents, size))
7644 == MagickFalse)
7646 imagemagick_error (image_wand);
7647 goto imagemagick_error;
7650 /* Retrieve the frame's background color, for use later. */
7652 XColor bgcolor;
7653 Lisp_Object specified_bg;
7655 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7656 if (!STRINGP (specified_bg)
7657 || !x_defined_color (f, SSDATA (specified_bg), &bgcolor, 0))
7659 #ifndef HAVE_NS
7660 bgcolor.pixel = FRAME_BACKGROUND_PIXEL (f);
7661 x_query_color (f, &bgcolor);
7662 #else
7663 ns_query_color (FRAME_BACKGROUND_COLOR (f), &bgcolor, 1);
7664 #endif
7667 bg_wand = NewPixelWand ();
7668 PixelSetRed (bg_wand, (double) bgcolor.red / 65535);
7669 PixelSetGreen (bg_wand, (double) bgcolor.green / 65535);
7670 PixelSetBlue (bg_wand, (double) bgcolor.blue / 65535);
7673 /* If width and/or height is set in the display spec assume we want
7674 to scale to those values. If either h or w is unspecified, the
7675 unspecified should be calculated from the specified to preserve
7676 aspect ratio. */
7677 value = image_spec_value (img->spec, QCwidth, NULL);
7678 desired_width = (INTEGERP (value) ? XFASTINT (value) : -1);
7679 value = image_spec_value (img->spec, QCheight, NULL);
7680 desired_height = (INTEGERP (value) ? XFASTINT (value) : -1);
7682 height = MagickGetImageHeight (image_wand);
7683 width = MagickGetImageWidth (image_wand);
7685 if (desired_width != -1 && desired_height == -1)
7686 /* w known, calculate h. */
7687 desired_height = (double) desired_width / width * height;
7688 if (desired_width == -1 && desired_height != -1)
7689 /* h known, calculate w. */
7690 desired_width = (double) desired_height / height * width;
7691 if (desired_width != -1 && desired_height != -1)
7693 status = MagickScaleImage (image_wand, desired_width, desired_height);
7694 if (status == MagickFalse)
7696 image_error ("Imagemagick scale failed", Qnil, Qnil);
7697 imagemagick_error (image_wand);
7698 goto imagemagick_error;
7702 /* crop behaves similar to image slicing in Emacs but is more memory
7703 efficient. */
7704 crop = image_spec_value (img->spec, QCcrop, NULL);
7706 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7708 /* After some testing, it seems MagickCropImage is the fastest crop
7709 function in ImageMagick. This crop function seems to do less copying
7710 than the alternatives, but it still reads the entire image into memory
7711 before cropping, which is apparently difficult to avoid when using
7712 imagemagick. */
7713 size_t crop_width = XINT (XCAR (crop));
7714 crop = XCDR (crop);
7715 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7717 size_t crop_height = XINT (XCAR (crop));
7718 crop = XCDR (crop);
7719 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7721 ssize_t crop_x = XINT (XCAR (crop));
7722 crop = XCDR (crop);
7723 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7725 ssize_t crop_y = XINT (XCAR (crop));
7726 MagickCropImage (image_wand, crop_width, crop_height,
7727 crop_x, crop_y);
7733 /* Furthermore :rotation. we need background color and angle for
7734 rotation. */
7736 TODO background handling for rotation specified_bg =
7737 image_spec_value (img->spec, QCbackground, NULL); if (!STRINGP
7738 (specified_bg). */
7739 value = image_spec_value (img->spec, QCrotation, NULL);
7740 if (FLOATP (value))
7742 rotation = extract_float (value);
7743 status = MagickRotateImage (image_wand, bg_wand, rotation);
7744 if (status == MagickFalse)
7746 image_error ("Imagemagick image rotate failed", Qnil, Qnil);
7747 imagemagick_error (image_wand);
7748 goto imagemagick_error;
7752 /* Finally we are done manipulating the image. Figure out the
7753 resulting width/height and transfer ownership to Emacs. */
7754 height = MagickGetImageHeight (image_wand);
7755 width = MagickGetImageWidth (image_wand);
7757 /* Set the canvas background color to the frame or specified
7758 background, and flatten the image. Note: as of ImageMagick
7759 6.6.0, SVG image transparency is not handled properly
7760 (e.g. etc/images/splash.svg shows a white background always). */
7762 MagickWand *new_wand;
7763 MagickSetImageBackgroundColor (image_wand, bg_wand);
7764 #ifdef HAVE_MAGICKMERGEIMAGELAYERS
7765 new_wand = MagickMergeImageLayers (image_wand, MergeLayer);
7766 #else
7767 new_wand = MagickFlattenImages (image_wand);
7768 #endif
7769 DestroyMagickWand (image_wand);
7770 image_wand = new_wand;
7773 if (! (width <= INT_MAX && height <= INT_MAX
7774 && check_image_size (f, width, height)))
7776 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7777 goto imagemagick_error;
7780 /* We can now get a valid pixel buffer from the imagemagick file, if all
7781 went ok. */
7783 init_color_table ();
7785 #ifdef HAVE_MAGICKEXPORTIMAGEPIXELS
7786 if (imagemagick_render_type != 0)
7788 /* Magicexportimage is normally faster than pixelpushing. This
7789 method is also well tested. Some aspects of this method are
7790 ad-hoc and needs to be more researched. */
7791 int imagedepth = 24; /*MagickGetImageDepth(image_wand);*/
7792 const char *exportdepth = imagedepth <= 8 ? "I" : "BGRP"; /*"RGBP";*/
7793 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7794 if (!x_create_x_image_and_pixmap (f, width, height, imagedepth,
7795 &ximg, &img->pixmap))
7797 #ifdef COLOR_TABLE_SUPPORT
7798 free_color_table ();
7799 #endif
7800 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7801 goto imagemagick_error;
7804 /* Oddly, the below code doesn't seem to work:*/
7805 /* switch(ximg->bitmap_unit){ */
7806 /* case 8: */
7807 /* pixelwidth=CharPixel; */
7808 /* break; */
7809 /* case 16: */
7810 /* pixelwidth=ShortPixel; */
7811 /* break; */
7812 /* case 32: */
7813 /* pixelwidth=LongPixel; */
7814 /* break; */
7815 /* } */
7817 Here im just guessing the format of the bitmap.
7818 happens to work fine for:
7819 - bw djvu images
7820 on rgb display.
7821 seems about 3 times as fast as pixel pushing(not carefully measured)
7823 pixelwidth = CharPixel; /*??? TODO figure out*/
7824 MagickExportImagePixels (image_wand, 0, 0, width, height,
7825 exportdepth, pixelwidth, ximg->data);
7827 else
7828 #endif /* HAVE_MAGICKEXPORTIMAGEPIXELS */
7830 size_t image_height;
7832 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7833 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7834 &ximg, &img->pixmap))
7836 #ifdef COLOR_TABLE_SUPPORT
7837 free_color_table ();
7838 #endif
7839 image_error ("Imagemagick X bitmap allocation failure", Qnil, Qnil);
7840 goto imagemagick_error;
7843 /* Copy imagemagick image to x with primitive yet robust pixel
7844 pusher loop. This has been tested a lot with many different
7845 images. */
7847 /* Copy pixels from the imagemagick image structure to the x image map. */
7848 iterator = NewPixelIterator (image_wand);
7849 if (iterator == (PixelIterator *) NULL)
7851 #ifdef COLOR_TABLE_SUPPORT
7852 free_color_table ();
7853 #endif
7854 x_destroy_x_image (ximg);
7855 image_error ("Imagemagick pixel iterator creation failed",
7856 Qnil, Qnil);
7857 goto imagemagick_error;
7860 image_height = MagickGetImageHeight (image_wand);
7861 for (y = 0; y < image_height; y++)
7863 pixels = PixelGetNextIteratorRow (iterator, &width);
7864 if (pixels == (PixelWand **) NULL)
7865 break;
7866 for (x = 0; x < (long) width; x++)
7868 PixelGetMagickColor (pixels[x], &pixel);
7869 XPutPixel (ximg, x, y,
7870 lookup_rgb_color (f,
7871 pixel.red,
7872 pixel.green,
7873 pixel.blue));
7876 DestroyPixelIterator (iterator);
7879 #ifdef COLOR_TABLE_SUPPORT
7880 /* Remember colors allocated for this image. */
7881 img->colors = colors_in_color_table (&img->ncolors);
7882 free_color_table ();
7883 #endif /* COLOR_TABLE_SUPPORT */
7885 img->width = width;
7886 img->height = height;
7888 /* Put the image into the pixmap, then free the X image and its
7889 buffer. */
7890 x_put_x_image (f, ximg, img->pixmap, width, height);
7891 x_destroy_x_image (ximg);
7893 /* Final cleanup. image_wand should be the only resource left. */
7894 DestroyMagickWand (image_wand);
7895 if (bg_wand) DestroyPixelWand (bg_wand);
7897 /* `MagickWandTerminus' terminates the imagemagick environment. */
7898 MagickWandTerminus ();
7900 return 1;
7902 imagemagick_error:
7903 DestroyMagickWand (image_wand);
7904 if (bg_wand) DestroyPixelWand (bg_wand);
7906 MagickWandTerminus ();
7907 /* TODO more cleanup. */
7908 image_error ("Error parsing IMAGEMAGICK image `%s'", img->spec, Qnil);
7909 return 0;
7913 /* Load IMAGEMAGICK image IMG for use on frame F. Value is non-zero if
7914 successful. this function will go into the imagemagick_type structure, and
7915 the prototype thus needs to be compatible with that structure. */
7917 static int
7918 imagemagick_load (struct frame *f, struct image *img)
7920 int success_p = 0;
7921 Lisp_Object file_name;
7923 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7924 file_name = image_spec_value (img->spec, QCfile, NULL);
7925 if (STRINGP (file_name))
7927 Lisp_Object file;
7929 file = x_find_image_file (file_name);
7930 if (!STRINGP (file))
7932 image_error ("Cannot find image file `%s'", file_name, Qnil);
7933 return 0;
7935 success_p = imagemagick_load_image (f, img, 0, 0, SSDATA (file));
7937 /* Else its not a file, its a lisp object. Load the image from a
7938 lisp object rather than a file. */
7939 else
7941 Lisp_Object data;
7943 data = image_spec_value (img->spec, QCdata, NULL);
7944 if (!STRINGP (data))
7946 image_error ("Invalid image data `%s'", data, Qnil);
7947 return 0;
7949 success_p = imagemagick_load_image (f, img, SDATA (data),
7950 SBYTES (data), NULL);
7953 return success_p;
7956 DEFUN ("imagemagick-types", Fimagemagick_types, Simagemagick_types, 0, 0, 0,
7957 doc: /* Return a list of image types supported by ImageMagick.
7958 Each entry in this list is a symbol named after an ImageMagick format
7959 tag. See the ImageMagick manual for a list of ImageMagick formats and
7960 their descriptions (http://www.imagemagick.org/script/formats.php).
7961 You can also try the shell command: `identify -list format'.
7963 Note that ImageMagick recognizes many file-types that Emacs does not
7964 recognize as images, such as C. See `imagemagick-types-enable'
7965 and `imagemagick-types-inhibit'. */)
7966 (void)
7968 Lisp_Object typelist = Qnil;
7969 size_t numf = 0;
7970 ExceptionInfo ex;
7971 char **imtypes;
7972 size_t i;
7973 Lisp_Object Qimagemagicktype;
7975 GetExceptionInfo(&ex);
7976 imtypes = GetMagickList ("*", &numf, &ex);
7977 DestroyExceptionInfo(&ex);
7979 for (i = 0; i < numf; i++)
7981 Qimagemagicktype = intern (imtypes[i]);
7982 typelist = Fcons (Qimagemagicktype, typelist);
7984 return Fnreverse (typelist);
7987 #endif /* defined (HAVE_IMAGEMAGICK) */
7991 /***********************************************************************
7993 ***********************************************************************/
7995 #if defined (HAVE_RSVG)
7997 /* Function prototypes. */
7999 static int svg_image_p (Lisp_Object object);
8000 static int svg_load (struct frame *f, struct image *img);
8002 static int svg_load_image (struct frame *, struct image *,
8003 unsigned char *, ptrdiff_t);
8005 /* The symbol `svg' identifying images of this type. */
8007 static Lisp_Object Qsvg;
8009 /* Indices of image specification fields in svg_format, below. */
8011 enum svg_keyword_index
8013 SVG_TYPE,
8014 SVG_DATA,
8015 SVG_FILE,
8016 SVG_ASCENT,
8017 SVG_MARGIN,
8018 SVG_RELIEF,
8019 SVG_ALGORITHM,
8020 SVG_HEURISTIC_MASK,
8021 SVG_MASK,
8022 SVG_BACKGROUND,
8023 SVG_LAST
8026 /* Vector of image_keyword structures describing the format
8027 of valid user-defined image specifications. */
8029 static const struct image_keyword svg_format[SVG_LAST] =
8031 {":type", IMAGE_SYMBOL_VALUE, 1},
8032 {":data", IMAGE_STRING_VALUE, 0},
8033 {":file", IMAGE_STRING_VALUE, 0},
8034 {":ascent", IMAGE_ASCENT_VALUE, 0},
8035 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8036 {":relief", IMAGE_INTEGER_VALUE, 0},
8037 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8038 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8039 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8040 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8043 /* Structure describing the image type `svg'. Its the same type of
8044 structure defined for all image formats, handled by emacs image
8045 functions. See struct image_type in dispextern.h. */
8047 static struct image_type svg_type =
8049 /* An identifier showing that this is an image structure for the SVG format. */
8050 &Qsvg,
8051 /* Handle to a function that can be used to identify a SVG file. */
8052 svg_image_p,
8053 /* Handle to function used to load a SVG file. */
8054 svg_load,
8055 /* Handle to function to free sresources for SVG. */
8056 x_clear_image,
8057 /* An internal field to link to the next image type in a list of
8058 image types, will be filled in when registering the format. */
8059 NULL
8063 /* Return non-zero if OBJECT is a valid SVG image specification. Do
8064 this by calling parse_image_spec and supplying the keywords that
8065 identify the SVG format. */
8067 static int
8068 svg_image_p (Lisp_Object object)
8070 struct image_keyword fmt[SVG_LAST];
8071 memcpy (fmt, svg_format, sizeof fmt);
8073 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8074 return 0;
8076 /* Must specify either the :data or :file keyword. */
8077 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8080 #include <librsvg/rsvg.h>
8082 #ifdef HAVE_NTGUI
8084 /* SVG library functions. */
8085 DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new);
8086 DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions);
8087 DEF_IMGLIB_FN (gboolean, rsvg_handle_write);
8088 DEF_IMGLIB_FN (gboolean, rsvg_handle_close);
8089 DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf);
8091 DEF_IMGLIB_FN (int, gdk_pixbuf_get_width);
8092 DEF_IMGLIB_FN (int, gdk_pixbuf_get_height);
8093 DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels);
8094 DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride);
8095 DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace);
8096 DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels);
8097 DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha);
8098 DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample);
8100 DEF_IMGLIB_FN (void, g_type_init);
8101 DEF_IMGLIB_FN (void, g_object_unref);
8102 DEF_IMGLIB_FN (void, g_error_free);
8104 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
8106 static int
8107 init_svg_functions (Lisp_Object libraries)
8109 HMODULE library, gdklib, glib, gobject;
8111 if (!(glib = w32_delayed_load (libraries, Qglib))
8112 || !(gobject = w32_delayed_load (libraries, Qgobject))
8113 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
8114 || !(library = w32_delayed_load (libraries, Qsvg)))
8115 return 0;
8117 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8118 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
8119 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8120 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8121 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8123 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8124 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8125 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8126 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8127 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8128 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8129 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8130 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8132 LOAD_IMGLIB_FN (gobject, g_type_init);
8133 LOAD_IMGLIB_FN (gobject, g_object_unref);
8134 LOAD_IMGLIB_FN (glib, g_error_free);
8136 return 1;
8139 #else
8140 /* The following aliases for library functions allow dynamic loading
8141 to be used on some platforms. */
8142 #define fn_rsvg_handle_new rsvg_handle_new
8143 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
8144 #define fn_rsvg_handle_write rsvg_handle_write
8145 #define fn_rsvg_handle_close rsvg_handle_close
8146 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8148 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8149 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8150 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8151 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8152 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8153 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8154 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8155 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8157 #define fn_g_type_init g_type_init
8158 #define fn_g_object_unref g_object_unref
8159 #define fn_g_error_free g_error_free
8160 #endif /* !HAVE_NTGUI */
8162 /* Load SVG image IMG for use on frame F. Value is non-zero if
8163 successful. this function will go into the svg_type structure, and
8164 the prototype thus needs to be compatible with that structure. */
8166 static int
8167 svg_load (struct frame *f, struct image *img)
8169 int success_p = 0;
8170 Lisp_Object file_name;
8172 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8173 file_name = image_spec_value (img->spec, QCfile, NULL);
8174 if (STRINGP (file_name))
8176 Lisp_Object file;
8177 unsigned char *contents;
8178 ptrdiff_t size;
8180 file = x_find_image_file (file_name);
8181 if (!STRINGP (file))
8183 image_error ("Cannot find image file `%s'", file_name, Qnil);
8184 return 0;
8187 /* Read the entire file into memory. */
8188 contents = slurp_file (SSDATA (file), &size);
8189 if (contents == NULL)
8191 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8192 return 0;
8194 /* If the file was slurped into memory properly, parse it. */
8195 success_p = svg_load_image (f, img, contents, size);
8196 xfree (contents);
8198 /* Else its not a file, its a lisp object. Load the image from a
8199 lisp object rather than a file. */
8200 else
8202 Lisp_Object data;
8204 data = image_spec_value (img->spec, QCdata, NULL);
8205 if (!STRINGP (data))
8207 image_error ("Invalid image data `%s'", data, Qnil);
8208 return 0;
8210 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8213 return success_p;
8216 /* svg_load_image is a helper function for svg_load, which does the
8217 actual loading given contents and size, apart from frame and image
8218 structures, passed from svg_load.
8220 Uses librsvg to do most of the image processing.
8222 Returns non-zero when successful. */
8223 static int
8224 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
8225 struct image *img, /* Pointer to emacs image structure. */
8226 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
8227 ptrdiff_t size) /* Size of data in bytes. */
8229 RsvgHandle *rsvg_handle;
8230 RsvgDimensionData dimension_data;
8231 GError *err = NULL;
8232 GdkPixbuf *pixbuf;
8233 int width;
8234 int height;
8235 const guint8 *pixels;
8236 int rowstride;
8237 XImagePtr ximg;
8238 Lisp_Object specified_bg;
8239 XColor background;
8240 int x;
8241 int y;
8243 /* g_type_init is a glib function that must be called prior to using
8244 gnome type library functions. */
8245 fn_g_type_init ();
8246 /* Make a handle to a new rsvg object. */
8247 rsvg_handle = fn_rsvg_handle_new ();
8249 /* Parse the contents argument and fill in the rsvg_handle. */
8250 fn_rsvg_handle_write (rsvg_handle, contents, size, &err);
8251 if (err) goto rsvg_error;
8253 /* The parsing is complete, rsvg_handle is ready to used, close it
8254 for further writes. */
8255 fn_rsvg_handle_close (rsvg_handle, &err);
8256 if (err) goto rsvg_error;
8258 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
8259 if (! check_image_size (f, dimension_data.width, dimension_data.height))
8261 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8262 goto rsvg_error;
8265 /* We can now get a valid pixel buffer from the svg file, if all
8266 went ok. */
8267 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8268 if (!pixbuf) goto rsvg_error;
8269 fn_g_object_unref (rsvg_handle);
8271 /* Extract some meta data from the svg handle. */
8272 width = fn_gdk_pixbuf_get_width (pixbuf);
8273 height = fn_gdk_pixbuf_get_height (pixbuf);
8274 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8275 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8277 /* Validate the svg meta data. */
8278 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8279 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8280 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8281 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8283 /* Try to create a x pixmap to hold the svg pixmap. */
8284 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8286 fn_g_object_unref (pixbuf);
8287 return 0;
8290 init_color_table ();
8292 /* Handle alpha channel by combining the image with a background
8293 color. */
8294 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8295 if (!STRINGP (specified_bg)
8296 || !x_defined_color (f, SSDATA (specified_bg), &background, 0))
8298 #ifndef HAVE_NS
8299 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8300 x_query_color (f, &background);
8301 #else
8302 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
8303 #endif
8306 /* SVG pixmaps specify transparency in the last byte, so right
8307 shift 8 bits to get rid of it, since emacs doesn't support
8308 transparency. */
8309 background.red >>= 8;
8310 background.green >>= 8;
8311 background.blue >>= 8;
8313 /* This loop handles opacity values, since Emacs assumes
8314 non-transparent images. Each pixel must be "flattened" by
8315 calculating the resulting color, given the transparency of the
8316 pixel, and the image background color. */
8317 for (y = 0; y < height; ++y)
8319 for (x = 0; x < width; ++x)
8321 int red;
8322 int green;
8323 int blue;
8324 int opacity;
8326 red = *pixels++;
8327 green = *pixels++;
8328 blue = *pixels++;
8329 opacity = *pixels++;
8331 red = ((red * opacity)
8332 + (background.red * ((1 << 8) - opacity)));
8333 green = ((green * opacity)
8334 + (background.green * ((1 << 8) - opacity)));
8335 blue = ((blue * opacity)
8336 + (background.blue * ((1 << 8) - opacity)));
8338 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8341 pixels += rowstride - 4 * width;
8344 #ifdef COLOR_TABLE_SUPPORT
8345 /* Remember colors allocated for this image. */
8346 img->colors = colors_in_color_table (&img->ncolors);
8347 free_color_table ();
8348 #endif /* COLOR_TABLE_SUPPORT */
8350 fn_g_object_unref (pixbuf);
8352 img->width = width;
8353 img->height = height;
8355 /* Maybe fill in the background field while we have ximg handy.
8356 Casting avoids a GCC warning. */
8357 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8359 /* Put the image into the pixmap, then free the X image and its
8360 buffer. */
8361 x_put_x_image (f, ximg, img->pixmap, width, height);
8362 x_destroy_x_image (ximg);
8364 return 1;
8366 rsvg_error:
8367 fn_g_object_unref (rsvg_handle);
8368 /* FIXME: Use error->message so the user knows what is the actual
8369 problem with the image. */
8370 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8371 fn_g_error_free (err);
8372 return 0;
8375 #endif /* defined (HAVE_RSVG) */
8380 /***********************************************************************
8381 Ghostscript
8382 ***********************************************************************/
8384 #ifdef HAVE_X_WINDOWS
8385 #define HAVE_GHOSTSCRIPT 1
8386 #endif /* HAVE_X_WINDOWS */
8388 #ifdef HAVE_GHOSTSCRIPT
8390 static int gs_image_p (Lisp_Object object);
8391 static int gs_load (struct frame *f, struct image *img);
8392 static void gs_clear_image (struct frame *f, struct image *img);
8394 /* Keyword symbols. */
8396 static Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8398 /* Indices of image specification fields in gs_format, below. */
8400 enum gs_keyword_index
8402 GS_TYPE,
8403 GS_PT_WIDTH,
8404 GS_PT_HEIGHT,
8405 GS_FILE,
8406 GS_LOADER,
8407 GS_BOUNDING_BOX,
8408 GS_ASCENT,
8409 GS_MARGIN,
8410 GS_RELIEF,
8411 GS_ALGORITHM,
8412 GS_HEURISTIC_MASK,
8413 GS_MASK,
8414 GS_BACKGROUND,
8415 GS_LAST
8418 /* Vector of image_keyword structures describing the format
8419 of valid user-defined image specifications. */
8421 static const struct image_keyword gs_format[GS_LAST] =
8423 {":type", IMAGE_SYMBOL_VALUE, 1},
8424 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8425 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8426 {":file", IMAGE_STRING_VALUE, 1},
8427 {":loader", IMAGE_FUNCTION_VALUE, 0},
8428 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8429 {":ascent", IMAGE_ASCENT_VALUE, 0},
8430 {":margin", IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR, 0},
8431 {":relief", IMAGE_INTEGER_VALUE, 0},
8432 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8433 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8434 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8435 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8438 /* Structure describing the image type `ghostscript'. */
8440 static struct image_type gs_type =
8442 &Qpostscript,
8443 gs_image_p,
8444 gs_load,
8445 gs_clear_image,
8446 NULL
8450 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8452 static void
8453 gs_clear_image (struct frame *f, struct image *img)
8455 x_clear_image (f, img);
8459 /* Return non-zero if OBJECT is a valid Ghostscript image
8460 specification. */
8462 static int
8463 gs_image_p (Lisp_Object object)
8465 struct image_keyword fmt[GS_LAST];
8466 Lisp_Object tem;
8467 int i;
8469 memcpy (fmt, gs_format, sizeof fmt);
8471 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8472 return 0;
8474 /* Bounding box must be a list or vector containing 4 integers. */
8475 tem = fmt[GS_BOUNDING_BOX].value;
8476 if (CONSP (tem))
8478 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8479 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8480 return 0;
8481 if (!NILP (tem))
8482 return 0;
8484 else if (VECTORP (tem))
8486 if (ASIZE (tem) != 4)
8487 return 0;
8488 for (i = 0; i < 4; ++i)
8489 if (!INTEGERP (AREF (tem, i)))
8490 return 0;
8492 else
8493 return 0;
8495 return 1;
8499 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8500 if successful. */
8502 static int
8503 gs_load (struct frame *f, struct image *img)
8505 uprintmax_t printnum1, printnum2;
8506 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
8507 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8508 Lisp_Object frame;
8509 double in_width, in_height;
8510 Lisp_Object pixel_colors = Qnil;
8512 /* Compute pixel size of pixmap needed from the given size in the
8513 image specification. Sizes in the specification are in pt. 1 pt
8514 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8515 info. */
8516 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8517 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
8518 in_width *= FRAME_X_DISPLAY_INFO (f)->resx;
8519 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8520 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
8521 in_height *= FRAME_X_DISPLAY_INFO (f)->resy;
8523 if (! (in_width <= INT_MAX && in_height <= INT_MAX
8524 && check_image_size (f, in_width, in_height)))
8526 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8527 return 0;
8529 img->width = in_width;
8530 img->height = in_height;
8532 /* Create the pixmap. */
8533 eassert (img->pixmap == NO_PIXMAP);
8535 if (x_check_image_size (0, img->width, img->height))
8537 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8538 BLOCK_INPUT;
8539 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8540 img->width, img->height,
8541 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8542 UNBLOCK_INPUT;
8545 if (!img->pixmap)
8547 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8548 return 0;
8551 /* Call the loader to fill the pixmap. It returns a process object
8552 if successful. We do not record_unwind_protect here because
8553 other places in redisplay like calling window scroll functions
8554 don't either. Let the Lisp loader use `unwind-protect' instead. */
8555 printnum1 = FRAME_X_WINDOW (f);
8556 printnum2 = img->pixmap;
8557 window_and_pixmap_id
8558 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
8560 printnum1 = FRAME_FOREGROUND_PIXEL (f);
8561 printnum2 = FRAME_BACKGROUND_PIXEL (f);
8562 pixel_colors
8563 = make_formatted_string (buffer, "%"pMu" %"pMu, printnum1, printnum2);
8565 XSETFRAME (frame, f);
8566 loader = image_spec_value (img->spec, QCloader, NULL);
8567 if (NILP (loader))
8568 loader = intern ("gs-load-image");
8570 img->lisp_data = call6 (loader, frame, img->spec,
8571 make_number (img->width),
8572 make_number (img->height),
8573 window_and_pixmap_id,
8574 pixel_colors);
8575 return PROCESSP (img->lisp_data);
8579 /* Kill the Ghostscript process that was started to fill PIXMAP on
8580 frame F. Called from XTread_socket when receiving an event
8581 telling Emacs that Ghostscript has finished drawing. */
8583 void
8584 x_kill_gs_process (Pixmap pixmap, struct frame *f)
8586 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8587 int class;
8588 ptrdiff_t i;
8589 struct image *img;
8591 /* Find the image containing PIXMAP. */
8592 for (i = 0; i < c->used; ++i)
8593 if (c->images[i]->pixmap == pixmap)
8594 break;
8596 /* Should someone in between have cleared the image cache, for
8597 instance, give up. */
8598 if (i == c->used)
8599 return;
8601 /* Kill the GS process. We should have found PIXMAP in the image
8602 cache and its image should contain a process object. */
8603 img = c->images[i];
8604 eassert (PROCESSP (img->lisp_data));
8605 Fkill_process (img->lisp_data, Qnil);
8606 img->lisp_data = Qnil;
8608 #if defined (HAVE_X_WINDOWS)
8610 /* On displays with a mutable colormap, figure out the colors
8611 allocated for the image by looking at the pixels of an XImage for
8612 img->pixmap. */
8613 class = FRAME_X_VISUAL (f)->class;
8614 if (class != StaticColor && class != StaticGray && class != TrueColor)
8616 XImagePtr ximg;
8618 BLOCK_INPUT;
8620 /* Try to get an XImage for img->pixmep. */
8621 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8622 0, 0, img->width, img->height, ~0, ZPixmap);
8623 if (ximg)
8625 int x, y;
8627 /* Initialize the color table. */
8628 init_color_table ();
8630 /* For each pixel of the image, look its color up in the
8631 color table. After having done so, the color table will
8632 contain an entry for each color used by the image. */
8633 for (y = 0; y < img->height; ++y)
8634 for (x = 0; x < img->width; ++x)
8636 unsigned long pixel = XGetPixel (ximg, x, y);
8637 lookup_pixel_color (f, pixel);
8640 /* Record colors in the image. Free color table and XImage. */
8641 #ifdef COLOR_TABLE_SUPPORT
8642 img->colors = colors_in_color_table (&img->ncolors);
8643 free_color_table ();
8644 #endif
8645 XDestroyImage (ximg);
8647 #if 0 /* This doesn't seem to be the case. If we free the colors
8648 here, we get a BadAccess later in x_clear_image when
8649 freeing the colors. */
8650 /* We have allocated colors once, but Ghostscript has also
8651 allocated colors on behalf of us. So, to get the
8652 reference counts right, free them once. */
8653 if (img->ncolors)
8654 x_free_colors (f, img->colors, img->ncolors);
8655 #endif
8657 else
8658 image_error ("Cannot get X image of `%s'; colors will not be freed",
8659 img->spec, Qnil);
8661 UNBLOCK_INPUT;
8663 #endif /* HAVE_X_WINDOWS */
8665 /* Now that we have the pixmap, compute mask and transform the
8666 image if requested. */
8667 BLOCK_INPUT;
8668 postprocess_image (f, img);
8669 UNBLOCK_INPUT;
8672 #endif /* HAVE_GHOSTSCRIPT */
8675 /***********************************************************************
8676 Tests
8677 ***********************************************************************/
8679 #ifdef GLYPH_DEBUG
8681 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8682 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8683 (Lisp_Object spec)
8685 return valid_image_p (spec) ? Qt : Qnil;
8689 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8690 (Lisp_Object spec)
8692 ptrdiff_t id = -1;
8694 if (valid_image_p (spec))
8695 id = lookup_image (SELECTED_FRAME (), spec);
8697 debug_print (spec);
8698 return make_number (id);
8701 #endif /* GLYPH_DEBUG */
8704 /***********************************************************************
8705 Initialization
8706 ***********************************************************************/
8708 #ifdef HAVE_NTGUI
8709 /* Image types that rely on external libraries are loaded dynamically
8710 if the library is available. */
8711 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8712 define_image_type (image_type, init_lib_fn (libraries))
8713 #else
8714 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8715 define_image_type (image_type, 1)
8716 #endif /* HAVE_NTGUI */
8718 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8719 doc: /* Initialize image library implementing image type TYPE.
8720 Return non-nil if TYPE is a supported image type.
8722 Image types pbm and xbm are prebuilt; other types are loaded here.
8723 Libraries to load are specified in alist LIBRARIES (usually, the value
8724 of `dynamic-library-alist', which see). */)
8725 (Lisp_Object type, Lisp_Object libraries)
8727 #ifdef HAVE_NTGUI
8728 /* Don't try to reload the library. */
8729 Lisp_Object tested = Fassq (type, Vlibrary_cache);
8730 if (CONSP (tested))
8731 return XCDR (tested);
8732 #endif
8734 /* Types pbm and xbm are built-in and always available. */
8735 if (EQ (type, Qpbm) || EQ (type, Qxbm))
8736 return Qt;
8738 #if defined (HAVE_XPM) || defined (HAVE_NS)
8739 if (EQ (type, Qxpm))
8740 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8741 #endif
8743 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8744 if (EQ (type, Qjpeg))
8745 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8746 #endif
8748 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8749 if (EQ (type, Qtiff))
8750 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8751 #endif
8753 #if defined (HAVE_GIF) || defined (HAVE_NS)
8754 if (EQ (type, Qgif))
8755 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8756 #endif
8758 #if defined (HAVE_PNG) || defined (HAVE_NS)
8759 if (EQ (type, Qpng))
8760 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8761 #endif
8763 #if defined (HAVE_RSVG)
8764 if (EQ (type, Qsvg))
8765 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
8766 #endif
8768 #if defined (HAVE_IMAGEMAGICK)
8769 if (EQ (type, Qimagemagick))
8770 return CHECK_LIB_AVAILABLE (&imagemagick_type, init_imagemagick_functions,
8771 libraries);
8772 #endif
8774 #ifdef HAVE_GHOSTSCRIPT
8775 if (EQ (type, Qpostscript))
8776 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8777 #endif
8779 /* If the type is not recognized, avoid testing it ever again. */
8780 CACHE_IMAGE_TYPE (type, Qnil);
8781 return Qnil;
8784 void
8785 syms_of_image (void)
8787 /* Initialize this only once, since that's what we do with Vimage_types
8788 and they are supposed to be in sync. Initializing here gives correct
8789 operation on GNU/Linux of calling dump-emacs after loading some images. */
8790 image_types = NULL;
8792 /* Must be defined now because we're going to update it below, while
8793 defining the supported image types. */
8794 DEFVAR_LISP ("image-types", Vimage_types,
8795 doc: /* List of potentially supported image types.
8796 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8797 To check whether it is really supported, use `image-type-available-p'. */);
8798 Vimage_types = Qnil;
8800 DEFVAR_LISP ("max-image-size", Vmax_image_size,
8801 doc: /* Maximum size of images.
8802 Emacs will not load an image into memory if its pixel width or
8803 pixel height exceeds this limit.
8805 If the value is an integer, it directly specifies the maximum
8806 image height and width, measured in pixels. If it is a floating
8807 point number, it specifies the maximum image height and width
8808 as a ratio to the frame height and width. If the value is
8809 non-numeric, there is no explicit limit on the size of images. */);
8810 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8812 DEFSYM (Qpbm, "pbm");
8813 ADD_IMAGE_TYPE (Qpbm);
8815 DEFSYM (Qxbm, "xbm");
8816 ADD_IMAGE_TYPE (Qxbm);
8818 define_image_type (&xbm_type, 1);
8819 define_image_type (&pbm_type, 1);
8821 DEFSYM (Qcount, "count");
8822 DEFSYM (Qextension_data, "extension-data");
8823 DEFSYM (Qdelay, "delay");
8825 DEFSYM (QCascent, ":ascent");
8826 DEFSYM (QCmargin, ":margin");
8827 DEFSYM (QCrelief, ":relief");
8828 DEFSYM (QCconversion, ":conversion");
8829 DEFSYM (QCcolor_symbols, ":color-symbols");
8830 DEFSYM (QCheuristic_mask, ":heuristic-mask");
8831 DEFSYM (QCindex, ":index");
8832 DEFSYM (QCgeometry, ":geometry");
8833 DEFSYM (QCcrop, ":crop");
8834 DEFSYM (QCrotation, ":rotation");
8835 DEFSYM (QCmatrix, ":matrix");
8836 DEFSYM (QCcolor_adjustment, ":color-adjustment");
8837 DEFSYM (QCmask, ":mask");
8839 DEFSYM (Qlaplace, "laplace");
8840 DEFSYM (Qemboss, "emboss");
8841 DEFSYM (Qedge_detection, "edge-detection");
8842 DEFSYM (Qheuristic, "heuristic");
8844 DEFSYM (Qpostscript, "postscript");
8845 #ifdef HAVE_GHOSTSCRIPT
8846 ADD_IMAGE_TYPE (Qpostscript);
8847 DEFSYM (QCloader, ":loader");
8848 DEFSYM (QCbounding_box, ":bounding-box");
8849 DEFSYM (QCpt_width, ":pt-width");
8850 DEFSYM (QCpt_height, ":pt-height");
8851 #endif /* HAVE_GHOSTSCRIPT */
8853 #ifdef HAVE_NTGUI
8854 DEFSYM (Qlibpng_version, "libpng-version");
8855 Fset (Qlibpng_version,
8856 #if HAVE_PNG
8857 make_number (PNG_LIBPNG_VER)
8858 #else
8859 make_number (-1)
8860 #endif
8862 #endif
8864 #if defined (HAVE_XPM) || defined (HAVE_NS)
8865 DEFSYM (Qxpm, "xpm");
8866 ADD_IMAGE_TYPE (Qxpm);
8867 #endif
8869 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8870 DEFSYM (Qjpeg, "jpeg");
8871 ADD_IMAGE_TYPE (Qjpeg);
8872 #endif
8874 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8875 DEFSYM (Qtiff, "tiff");
8876 ADD_IMAGE_TYPE (Qtiff);
8877 #endif
8879 #if defined (HAVE_GIF) || defined (HAVE_NS)
8880 DEFSYM (Qgif, "gif");
8881 ADD_IMAGE_TYPE (Qgif);
8882 #endif
8884 #if defined (HAVE_PNG) || defined (HAVE_NS)
8885 DEFSYM (Qpng, "png");
8886 ADD_IMAGE_TYPE (Qpng);
8887 #endif
8889 #if defined (HAVE_IMAGEMAGICK)
8890 DEFSYM (Qimagemagick, "imagemagick");
8891 ADD_IMAGE_TYPE (Qimagemagick);
8892 #endif
8894 #if defined (HAVE_RSVG)
8895 DEFSYM (Qsvg, "svg");
8896 ADD_IMAGE_TYPE (Qsvg);
8897 #ifdef HAVE_NTGUI
8898 /* Other libraries used directly by svg code. */
8899 DEFSYM (Qgdk_pixbuf, "gdk-pixbuf");
8900 DEFSYM (Qglib, "glib");
8901 DEFSYM (Qgobject, "gobject");
8902 #endif /* HAVE_NTGUI */
8903 #endif /* HAVE_RSVG */
8905 defsubr (&Sinit_image_library);
8906 #ifdef HAVE_IMAGEMAGICK
8907 defsubr (&Simagemagick_types);
8908 #endif
8909 defsubr (&Sclear_image_cache);
8910 defsubr (&Simage_flush);
8911 defsubr (&Simage_size);
8912 defsubr (&Simage_mask_p);
8913 defsubr (&Simage_metadata);
8915 #ifdef GLYPH_DEBUG
8916 defsubr (&Simagep);
8917 defsubr (&Slookup_image);
8918 #endif
8920 DEFVAR_BOOL ("cross-disabled-images", cross_disabled_images,
8921 doc: /* Non-nil means always draw a cross over disabled images.
8922 Disabled images are those having a `:conversion disabled' property.
8923 A cross is always drawn on black & white displays. */);
8924 cross_disabled_images = 0;
8926 DEFVAR_LISP ("x-bitmap-file-path", Vx_bitmap_file_path,
8927 doc: /* List of directories to search for window system bitmap files. */);
8928 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8930 DEFVAR_LISP ("image-cache-eviction-delay", Vimage_cache_eviction_delay,
8931 doc: /* Maximum time after which images are removed from the cache.
8932 When an image has not been displayed this many seconds, Emacs
8933 automatically removes it from the image cache. If the cache contains
8934 a large number of images, the actual eviction time may be shorter.
8935 The value can also be nil, meaning the cache is never cleared.
8937 The function `clear-image-cache' disregards this variable. */);
8938 Vimage_cache_eviction_delay = make_number (300);
8939 #ifdef HAVE_IMAGEMAGICK
8940 DEFVAR_INT ("imagemagick-render-type", imagemagick_render_type,
8941 doc: /* Integer indicating which ImageMagick rendering method to use.
8942 The options are:
8943 0 -- the default method (pixel pushing)
8944 1 -- a newer method ("MagickExportImagePixels") that may perform
8945 better (speed etc) in some cases, but has not been as thoroughly
8946 tested with Emacs as the default method. This method requires
8947 ImageMagick version 6.4.6 (approximately) or later.
8948 */);
8949 /* MagickExportImagePixels is in 6.4.6-9, but not 6.4.4-10. */
8950 imagemagick_render_type = 0;
8951 #endif