* NEWS: Mention --enable-checking is now supported on Windows.
[emacs.git] / src / image.c
blob6e75921414ba49d1ec95019f6afd41d2b1fe4236
1 /* Functions for image support on window system.
2 Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <stdio.h>
23 #include <math.h>
24 #include <ctype.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
30 #ifdef HAVE_PNG
31 #if defined HAVE_LIBPNG_PNG_H
32 # include <libpng/png.h>
33 #else
34 # include <png.h>
35 #endif
36 #endif
38 #include <setjmp.h>
40 /* This makes the fields of a Display accessible, in Xlib header files. */
42 #define XLIB_ILLEGAL_ACCESS
44 #include "lisp.h"
45 #include "frame.h"
46 #include "window.h"
47 #include "dispextern.h"
48 #include "blockinput.h"
49 #include "systime.h"
50 #include <epaths.h>
51 #include "character.h"
52 #include "coding.h"
53 #include "termhooks.h"
54 #include "font.h"
56 #ifdef HAVE_X_WINDOWS
57 #include "xterm.h"
58 #include <sys/types.h>
59 #include <sys/stat.h>
61 #define COLOR_TABLE_SUPPORT 1
63 typedef struct x_bitmap_record Bitmap_Record;
64 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
65 #define NO_PIXMAP None
67 #define RGB_PIXEL_COLOR unsigned long
69 #define PIX_MASK_RETAIN 0
70 #define PIX_MASK_DRAW 1
71 #endif /* HAVE_X_WINDOWS */
74 #ifdef HAVE_NTGUI
75 #include "w32term.h"
77 /* W32_TODO : Color tables on W32. */
78 #undef COLOR_TABLE_SUPPORT
80 typedef struct w32_bitmap_record Bitmap_Record;
81 #define GET_PIXEL(ximg, x, y) GetPixel(ximg, x, y)
82 #define NO_PIXMAP 0
84 #define RGB_PIXEL_COLOR COLORREF
86 #define PIX_MASK_RETAIN 0
87 #define PIX_MASK_DRAW 1
89 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
90 #define x_defined_color w32_defined_color
91 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
93 /* Functions from w32term.c that depend on XColor (so can't go in w32term.h
94 without modifying lots of files). */
95 extern void x_query_colors (struct frame *f, XColor *colors, int ncolors);
96 extern void x_query_color (struct frame *f, XColor *color);
97 #endif /* HAVE_NTGUI */
99 #ifdef HAVE_NS
100 #include "nsterm.h"
101 #include <sys/types.h>
102 #include <sys/stat.h>
104 #undef COLOR_TABLE_SUPPORT
106 typedef struct ns_bitmap_record Bitmap_Record;
108 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
109 #define NO_PIXMAP 0
111 #define RGB_PIXEL_COLOR unsigned long
112 #define ZPixmap 0
114 #define PIX_MASK_RETAIN 0
115 #define PIX_MASK_DRAW 1
117 #define FRAME_X_VISUAL FRAME_NS_DISPLAY_INFO(f)->visual
118 #define x_defined_color(f, name, color_def, alloc) \
119 ns_defined_color (f, name, color_def, alloc, 0)
120 #define FRAME_X_SCREEN(f) 0
121 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
122 #endif /* HAVE_NS */
125 /* Search path for bitmap files. */
127 Lisp_Object Vx_bitmap_file_path;
130 static void x_disable_image (struct frame *, struct image *);
131 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
132 Lisp_Object);
134 static void init_color_table (void);
135 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
136 #ifdef COLOR_TABLE_SUPPORT
137 static void free_color_table (void);
138 static unsigned long *colors_in_color_table (int *n);
139 static unsigned long lookup_pixel_color (struct frame *f, unsigned long p);
140 #endif
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, int id)
186 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
190 x_bitmap_width (FRAME_PTR f, int 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, int id)
199 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
201 #endif
203 #ifdef HAVE_X_WINDOWS
205 x_bitmap_mask (FRAME_PTR f, int id)
207 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
209 #endif
211 /* Allocate a new bitmap record. Returns index of new record. */
213 static int
214 x_allocate_bitmap_record (FRAME_PTR f)
216 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
217 int i;
219 if (dpyinfo->bitmaps == NULL)
221 dpyinfo->bitmaps_size = 10;
222 dpyinfo->bitmaps
223 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
224 dpyinfo->bitmaps_last = 1;
225 return 1;
228 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
229 return ++dpyinfo->bitmaps_last;
231 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
232 if (dpyinfo->bitmaps[i].refcount == 0)
233 return i + 1;
235 dpyinfo->bitmaps_size *= 2;
236 dpyinfo->bitmaps
237 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
238 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
239 return ++dpyinfo->bitmaps_last;
242 /* Add one reference to the reference count of the bitmap with id ID. */
244 void
245 x_reference_bitmap (FRAME_PTR f, int id)
247 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
250 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
253 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
255 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
256 int id;
258 #ifdef HAVE_X_WINDOWS
259 Pixmap bitmap;
260 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
261 bits, width, height);
262 if (! bitmap)
263 return -1;
264 #endif /* HAVE_X_WINDOWS */
266 #ifdef HAVE_NTGUI
267 Pixmap bitmap;
268 bitmap = CreateBitmap (width, height,
269 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
270 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
271 bits);
272 if (! bitmap)
273 return -1;
274 #endif /* HAVE_NTGUI */
276 #ifdef HAVE_NS
277 void *bitmap = ns_image_from_XBM (bits, width, height);
278 if (!bitmap)
279 return -1;
280 #endif
282 id = x_allocate_bitmap_record (f);
284 #ifdef HAVE_NS
285 dpyinfo->bitmaps[id - 1].img = bitmap;
286 dpyinfo->bitmaps[id - 1].depth = 1;
287 #endif
289 dpyinfo->bitmaps[id - 1].file = NULL;
290 dpyinfo->bitmaps[id - 1].height = height;
291 dpyinfo->bitmaps[id - 1].width = width;
292 dpyinfo->bitmaps[id - 1].refcount = 1;
294 #ifdef HAVE_X_WINDOWS
295 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
296 dpyinfo->bitmaps[id - 1].have_mask = 0;
297 dpyinfo->bitmaps[id - 1].depth = 1;
298 #endif /* HAVE_X_WINDOWS */
300 #ifdef HAVE_NTGUI
301 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
302 dpyinfo->bitmaps[id - 1].hinst = NULL;
303 dpyinfo->bitmaps[id - 1].depth = 1;
304 #endif /* HAVE_NTGUI */
306 return id;
309 /* Create bitmap from file FILE for frame F. */
312 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
314 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
316 #ifdef HAVE_NTGUI
317 return -1; /* W32_TODO : bitmap support */
318 #endif /* HAVE_NTGUI */
320 #ifdef HAVE_NS
321 int id;
322 void *bitmap = ns_image_from_file (file);
324 if (!bitmap)
325 return -1;
328 id = x_allocate_bitmap_record (f);
329 dpyinfo->bitmaps[id - 1].img = bitmap;
330 dpyinfo->bitmaps[id - 1].refcount = 1;
331 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
332 dpyinfo->bitmaps[id - 1].depth = 1;
333 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
334 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
335 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
336 return id;
337 #endif
339 #ifdef HAVE_X_WINDOWS
340 unsigned int width, height;
341 Pixmap bitmap;
342 int xhot, yhot, result, id;
343 Lisp_Object found;
344 int fd;
345 char *filename;
347 /* Look for an existing bitmap with the same name. */
348 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
350 if (dpyinfo->bitmaps[id].refcount
351 && dpyinfo->bitmaps[id].file
352 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
354 ++dpyinfo->bitmaps[id].refcount;
355 return id + 1;
359 /* Search bitmap-file-path for the file, if appropriate. */
360 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
361 if (fd < 0)
362 return -1;
363 emacs_close (fd);
365 filename = (char *) SDATA (found);
367 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
368 filename, &width, &height, &bitmap, &xhot, &yhot);
369 if (result != BitmapSuccess)
370 return -1;
372 id = x_allocate_bitmap_record (f);
373 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
374 dpyinfo->bitmaps[id - 1].have_mask = 0;
375 dpyinfo->bitmaps[id - 1].refcount = 1;
376 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
377 dpyinfo->bitmaps[id - 1].depth = 1;
378 dpyinfo->bitmaps[id - 1].height = height;
379 dpyinfo->bitmaps[id - 1].width = width;
380 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
382 return id;
383 #endif /* HAVE_X_WINDOWS */
386 /* Free bitmap B. */
388 static void
389 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
391 #ifdef HAVE_X_WINDOWS
392 XFreePixmap (dpyinfo->display, bm->pixmap);
393 if (bm->have_mask)
394 XFreePixmap (dpyinfo->display, bm->mask);
395 #endif /* HAVE_X_WINDOWS */
397 #ifdef HAVE_NTGUI
398 DeleteObject (bm->pixmap);
399 #endif /* HAVE_NTGUI */
401 #ifdef HAVE_NS
402 ns_release_object (bm->img);
403 #endif
405 if (bm->file)
407 xfree (bm->file);
408 bm->file = NULL;
412 /* Remove reference to bitmap with id number ID. */
414 void
415 x_destroy_bitmap (FRAME_PTR f, int id)
417 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
419 if (id > 0)
421 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
423 if (--bm->refcount == 0)
425 BLOCK_INPUT;
426 free_bitmap_record (dpyinfo, bm);
427 UNBLOCK_INPUT;
432 /* Free all the bitmaps for the display specified by DPYINFO. */
434 void
435 x_destroy_all_bitmaps (Display_Info *dpyinfo)
437 int i;
438 Bitmap_Record *bm = dpyinfo->bitmaps;
440 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
441 if (bm->refcount > 0)
442 free_bitmap_record (dpyinfo, bm);
444 dpyinfo->bitmaps_last = 0;
448 #ifdef HAVE_X_WINDOWS
450 /* Useful functions defined in the section
451 `Image type independent image structures' below. */
453 static unsigned long four_corners_best (XImagePtr ximg,
454 int *corners,
455 unsigned long width,
456 unsigned long height);
458 static int x_create_x_image_and_pixmap (struct frame *f, int width, int height,
459 int depth, XImagePtr *ximg,
460 Pixmap *pixmap);
462 static void x_destroy_x_image (XImagePtr ximg);
465 /* Create a mask of a bitmap. Note is this not a perfect mask.
466 It's nicer with some borders in this context */
469 x_create_bitmap_mask (struct frame *f, int id)
471 Pixmap pixmap, mask;
472 XImagePtr ximg, mask_img;
473 unsigned long width, height;
474 int result;
475 unsigned long bg;
476 unsigned long x, y, xp, xm, yp, ym;
477 GC gc;
479 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
481 if (!(id > 0))
482 return -1;
484 pixmap = x_bitmap_pixmap (f, id);
485 width = x_bitmap_width (f, id);
486 height = x_bitmap_height (f, id);
488 BLOCK_INPUT;
489 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
490 ~0, ZPixmap);
492 if (!ximg)
494 UNBLOCK_INPUT;
495 return -1;
498 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
500 UNBLOCK_INPUT;
501 if (!result)
503 XDestroyImage (ximg);
504 return -1;
507 bg = four_corners_best (ximg, NULL, width, height);
509 for (y = 0; y < ximg->height; ++y)
511 for (x = 0; x < ximg->width; ++x)
513 xp = x != ximg->width - 1 ? x + 1 : 0;
514 xm = x != 0 ? x - 1 : ximg->width - 1;
515 yp = y != ximg->height - 1 ? y + 1 : 0;
516 ym = y != 0 ? y - 1 : ximg->height - 1;
517 if (XGetPixel (ximg, x, y) == bg
518 && XGetPixel (ximg, x, yp) == bg
519 && XGetPixel (ximg, x, ym) == bg
520 && XGetPixel (ximg, xp, y) == bg
521 && XGetPixel (ximg, xp, yp) == bg
522 && XGetPixel (ximg, xp, ym) == bg
523 && XGetPixel (ximg, xm, y) == bg
524 && XGetPixel (ximg, xm, yp) == bg
525 && XGetPixel (ximg, xm, ym) == bg)
526 XPutPixel (mask_img, x, y, 0);
527 else
528 XPutPixel (mask_img, x, y, 1);
532 xassert (interrupt_input_blocked);
533 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
534 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
535 width, height);
536 XFreeGC (FRAME_X_DISPLAY (f), gc);
538 dpyinfo->bitmaps[id - 1].have_mask = 1;
539 dpyinfo->bitmaps[id - 1].mask = mask;
541 XDestroyImage (ximg);
542 x_destroy_x_image (mask_img);
544 return 0;
547 #endif /* HAVE_X_WINDOWS */
550 /***********************************************************************
551 Image types
552 ***********************************************************************/
554 /* Value is the number of elements of vector VECTOR. */
556 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
558 /* List of supported image types. Use define_image_type to add new
559 types. Use lookup_image_type to find a type for a given symbol. */
561 static struct image_type *image_types;
563 /* A list of symbols, one for each supported image type. */
565 Lisp_Object Vimage_types;
567 /* An alist of image types and libraries that implement the type. */
569 Lisp_Object Vimage_library_alist;
571 /* Cache for delayed-loading image types. */
573 static Lisp_Object Vimage_type_cache;
575 /* The symbol `xbm' which is used as the type symbol for XBM images. */
577 Lisp_Object Qxbm;
579 /* Keywords. */
581 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
582 extern Lisp_Object QCdata, QCtype;
583 extern Lisp_Object Qcenter;
584 Lisp_Object QCascent, QCmargin, QCrelief, Qcount, Qextension_data;
585 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
586 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
588 /* Other symbols. */
590 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
592 /* Time in seconds after which images should be removed from the cache
593 if not displayed. */
595 Lisp_Object Vimage_cache_eviction_delay;
597 /* Function prototypes. */
599 static Lisp_Object define_image_type (struct image_type *type, int loaded);
600 static struct image_type *lookup_image_type (Lisp_Object symbol);
601 static void image_error (char *format, Lisp_Object, Lisp_Object);
602 static void x_laplace (struct frame *, struct image *);
603 static void x_emboss (struct frame *, struct image *);
604 static int x_build_heuristic_mask (struct frame *, struct image *,
605 Lisp_Object);
607 #define CACHE_IMAGE_TYPE(type, status) \
608 do { Vimage_type_cache = Fcons (Fcons (type, status), Vimage_type_cache); } while (0)
610 #define ADD_IMAGE_TYPE(type) \
611 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
613 /* Define a new image type from TYPE. This adds a copy of TYPE to
614 image_types and caches the loading status of TYPE. */
616 static Lisp_Object
617 define_image_type (struct image_type *type, int loaded)
619 Lisp_Object success;
621 if (!loaded)
622 success = Qnil;
623 else
625 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
626 The initialized data segment is read-only. */
627 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
628 memcpy (p, type, sizeof *p);
629 p->next = image_types;
630 image_types = p;
631 success = Qt;
634 CACHE_IMAGE_TYPE (*type->type, success);
635 return success;
639 /* Look up image type SYMBOL, and return a pointer to its image_type
640 structure. Value is null if SYMBOL is not a known image type. */
642 static INLINE struct image_type *
643 lookup_image_type (Lisp_Object symbol)
645 struct image_type *type;
647 /* We must initialize the image-type if it hasn't been already. */
648 if (NILP (Finit_image_library (symbol, Vimage_library_alist)))
649 return 0; /* unimplemented */
651 for (type = image_types; type; type = type->next)
652 if (EQ (symbol, *type->type))
653 break;
655 return type;
659 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
660 valid image specification is a list whose car is the symbol
661 `image', and whose rest is a property list. The property list must
662 contain a value for key `:type'. That value must be the name of a
663 supported image type. The rest of the property list depends on the
664 image type. */
667 valid_image_p (Lisp_Object object)
669 int valid_p = 0;
671 if (IMAGEP (object))
673 Lisp_Object tem;
675 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
676 if (EQ (XCAR (tem), QCtype))
678 tem = XCDR (tem);
679 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
681 struct image_type *type;
682 type = lookup_image_type (XCAR (tem));
683 if (type)
684 valid_p = type->valid_p (object);
687 break;
691 return valid_p;
695 /* Log error message with format string FORMAT and argument ARG.
696 Signaling an error, e.g. when an image cannot be loaded, is not a
697 good idea because this would interrupt redisplay, and the error
698 message display would lead to another redisplay. This function
699 therefore simply displays a message. */
701 static void
702 image_error (char *format, Lisp_Object arg1, Lisp_Object arg2)
704 add_to_log (format, arg1, arg2);
709 /***********************************************************************
710 Image specifications
711 ***********************************************************************/
713 enum image_value_type
715 IMAGE_DONT_CHECK_VALUE_TYPE,
716 IMAGE_STRING_VALUE,
717 IMAGE_STRING_OR_NIL_VALUE,
718 IMAGE_SYMBOL_VALUE,
719 IMAGE_POSITIVE_INTEGER_VALUE,
720 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
721 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
722 IMAGE_ASCENT_VALUE,
723 IMAGE_INTEGER_VALUE,
724 IMAGE_FUNCTION_VALUE,
725 IMAGE_NUMBER_VALUE,
726 IMAGE_BOOL_VALUE
729 /* Structure used when parsing image specifications. */
731 struct image_keyword
733 /* Name of keyword. */
734 char *name;
736 /* The type of value allowed. */
737 enum image_value_type type;
739 /* Non-zero means key must be present. */
740 int mandatory_p;
742 /* Used to recognize duplicate keywords in a property list. */
743 int count;
745 /* The value that was found. */
746 Lisp_Object value;
750 static int parse_image_spec (Lisp_Object, struct image_keyword *,
751 int, Lisp_Object);
752 static Lisp_Object image_spec_value (Lisp_Object, Lisp_Object, int *);
755 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
756 has the format (image KEYWORD VALUE ...). One of the keyword/
757 value pairs must be `:type TYPE'. KEYWORDS is a vector of
758 image_keywords structures of size NKEYWORDS describing other
759 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
761 static int
762 parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
763 int nkeywords, Lisp_Object type)
765 int i;
766 Lisp_Object plist;
768 if (!IMAGEP (spec))
769 return 0;
771 plist = XCDR (spec);
772 while (CONSP (plist))
774 Lisp_Object key, value;
776 /* First element of a pair must be a symbol. */
777 key = XCAR (plist);
778 plist = XCDR (plist);
779 if (!SYMBOLP (key))
780 return 0;
782 /* There must follow a value. */
783 if (!CONSP (plist))
784 return 0;
785 value = XCAR (plist);
786 plist = XCDR (plist);
788 /* Find key in KEYWORDS. Error if not found. */
789 for (i = 0; i < nkeywords; ++i)
790 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
791 break;
793 if (i == nkeywords)
794 continue;
796 /* Record that we recognized the keyword. If a keywords
797 was found more than once, it's an error. */
798 keywords[i].value = value;
799 ++keywords[i].count;
801 if (keywords[i].count > 1)
802 return 0;
804 /* Check type of value against allowed type. */
805 switch (keywords[i].type)
807 case IMAGE_STRING_VALUE:
808 if (!STRINGP (value))
809 return 0;
810 break;
812 case IMAGE_STRING_OR_NIL_VALUE:
813 if (!STRINGP (value) && !NILP (value))
814 return 0;
815 break;
817 case IMAGE_SYMBOL_VALUE:
818 if (!SYMBOLP (value))
819 return 0;
820 break;
822 case IMAGE_POSITIVE_INTEGER_VALUE:
823 if (!INTEGERP (value) || XINT (value) <= 0)
824 return 0;
825 break;
827 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
828 if (INTEGERP (value) && XINT (value) >= 0)
829 break;
830 if (CONSP (value)
831 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
832 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
833 break;
834 return 0;
836 case IMAGE_ASCENT_VALUE:
837 if (SYMBOLP (value) && EQ (value, Qcenter))
838 break;
839 else if (INTEGERP (value)
840 && XINT (value) >= 0
841 && XINT (value) <= 100)
842 break;
843 return 0;
845 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
846 if (!INTEGERP (value) || XINT (value) < 0)
847 return 0;
848 break;
850 case IMAGE_DONT_CHECK_VALUE_TYPE:
851 break;
853 case IMAGE_FUNCTION_VALUE:
854 value = indirect_function (value);
855 if (SUBRP (value)
856 || COMPILEDP (value)
857 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
858 break;
859 return 0;
861 case IMAGE_NUMBER_VALUE:
862 if (!INTEGERP (value) && !FLOATP (value))
863 return 0;
864 break;
866 case IMAGE_INTEGER_VALUE:
867 if (!INTEGERP (value))
868 return 0;
869 break;
871 case IMAGE_BOOL_VALUE:
872 if (!NILP (value) && !EQ (value, Qt))
873 return 0;
874 break;
876 default:
877 abort ();
878 break;
881 if (EQ (key, QCtype) && !EQ (type, value))
882 return 0;
885 /* Check that all mandatory fields are present. */
886 for (i = 0; i < nkeywords; ++i)
887 if (keywords[i].mandatory_p && keywords[i].count == 0)
888 return 0;
890 return NILP (plist);
894 /* Return the value of KEY in image specification SPEC. Value is nil
895 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
896 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
898 static Lisp_Object
899 image_spec_value (Lisp_Object spec, Lisp_Object key, int *found)
901 Lisp_Object tail;
903 xassert (valid_image_p (spec));
905 for (tail = XCDR (spec);
906 CONSP (tail) && CONSP (XCDR (tail));
907 tail = XCDR (XCDR (tail)))
909 if (EQ (XCAR (tail), key))
911 if (found)
912 *found = 1;
913 return XCAR (XCDR (tail));
917 if (found)
918 *found = 0;
919 return Qnil;
923 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
924 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
925 PIXELS non-nil means return the size in pixels, otherwise return the
926 size in canonical character units.
927 FRAME is the frame on which the image will be displayed. FRAME nil
928 or omitted means use the selected frame. */)
929 (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
931 Lisp_Object size;
933 size = Qnil;
934 if (valid_image_p (spec))
936 struct frame *f = check_x_frame (frame);
937 int id = lookup_image (f, spec);
938 struct image *img = IMAGE_FROM_ID (f, id);
939 int width = img->width + 2 * img->hmargin;
940 int height = img->height + 2 * img->vmargin;
942 if (NILP (pixels))
943 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
944 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
945 else
946 size = Fcons (make_number (width), make_number (height));
948 else
949 error ("Invalid image specification");
951 return size;
955 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
956 doc: /* Return t if image SPEC has a mask bitmap.
957 FRAME is the frame on which the image will be displayed. FRAME nil
958 or omitted means use the selected frame. */)
959 (Lisp_Object spec, Lisp_Object frame)
961 Lisp_Object mask;
963 mask = Qnil;
964 if (valid_image_p (spec))
966 struct frame *f = check_x_frame (frame);
967 int id = lookup_image (f, spec);
968 struct image *img = IMAGE_FROM_ID (f, id);
969 if (img->mask)
970 mask = Qt;
972 else
973 error ("Invalid image specification");
975 return mask;
978 DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
979 doc: /* Return metadata for image SPEC.
980 FRAME is the frame on which the image will be displayed. FRAME nil
981 or omitted means use the selected frame. */)
982 (Lisp_Object spec, Lisp_Object frame)
984 Lisp_Object ext;
986 ext = Qnil;
987 if (valid_image_p (spec))
989 struct frame *f = check_x_frame (frame);
990 int id = lookup_image (f, spec);
991 struct image *img = IMAGE_FROM_ID (f, id);
992 ext = img->data.lisp_val;
995 return ext;
999 /***********************************************************************
1000 Image type independent image structures
1001 ***********************************************************************/
1003 static struct image *make_image (Lisp_Object spec, unsigned hash);
1004 static void free_image (struct frame *f, struct image *img);
1005 static int check_image_size (struct frame *f, int width, int height);
1007 #define MAX_IMAGE_SIZE 6.0
1008 Lisp_Object Vmax_image_size;
1010 /* Allocate and return a new image structure for image specification
1011 SPEC. SPEC has a hash value of HASH. */
1013 static struct image *
1014 make_image (Lisp_Object spec, unsigned int hash)
1016 struct image *img = (struct image *) xmalloc (sizeof *img);
1017 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
1019 xassert (valid_image_p (spec));
1020 memset (img, 0, sizeof *img);
1021 img->dependencies = NILP (file) ? Qnil : list1 (file);
1022 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1023 xassert (img->type != NULL);
1024 img->spec = spec;
1025 img->data.lisp_val = Qnil;
1026 img->ascent = DEFAULT_IMAGE_ASCENT;
1027 img->hash = hash;
1028 img->corners[BOT_CORNER] = -1; /* Full image */
1029 return img;
1033 /* Free image IMG which was used on frame F, including its resources. */
1035 static void
1036 free_image (struct frame *f, struct image *img)
1038 if (img)
1040 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1042 /* Remove IMG from the hash table of its cache. */
1043 if (img->prev)
1044 img->prev->next = img->next;
1045 else
1046 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1048 if (img->next)
1049 img->next->prev = img->prev;
1051 c->images[img->id] = NULL;
1053 /* Free resources, then free IMG. */
1054 img->type->free (f, img);
1055 xfree (img);
1057 /* As display glyphs may still be referring to the image ID, we
1058 must garbage the frame (Bug#6426). */
1059 SET_FRAME_GARBAGED (f);
1063 /* Return 1 if the given widths and heights are valid for display;
1064 otherwise, return 0. */
1067 check_image_size (struct frame *f, int width, int height)
1069 int w, h;
1071 if (width <= 0 || height <= 0)
1072 return 0;
1074 if (INTEGERP (Vmax_image_size))
1075 w = h = XINT (Vmax_image_size);
1076 else if (FLOATP (Vmax_image_size))
1078 if (f != NULL)
1080 w = FRAME_PIXEL_WIDTH (f);
1081 h = FRAME_PIXEL_HEIGHT (f);
1083 else
1084 w = h = 1024; /* Arbitrary size for unknown frame. */
1085 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1086 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1088 else
1089 return 1;
1091 return (width <= w && height <= h);
1094 /* Prepare image IMG for display on frame F. Must be called before
1095 drawing an image. */
1097 void
1098 prepare_image_for_display (struct frame *f, struct image *img)
1100 EMACS_TIME t;
1102 /* We're about to display IMG, so set its timestamp to `now'. */
1103 EMACS_GET_TIME (t);
1104 img->timestamp = EMACS_SECS (t);
1106 /* If IMG doesn't have a pixmap yet, load it now, using the image
1107 type dependent loader function. */
1108 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1109 img->load_failed_p = img->type->load (f, img) == 0;
1114 /* Value is the number of pixels for the ascent of image IMG when
1115 drawn in face FACE. */
1118 image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1120 int height;
1121 int ascent;
1123 if (slice->height == img->height)
1124 height = img->height + img->vmargin;
1125 else if (slice->y == 0)
1126 height = slice->height + img->vmargin;
1127 else
1128 height = slice->height;
1130 if (img->ascent == CENTERED_IMAGE_ASCENT)
1132 if (face->font)
1134 #ifdef HAVE_NTGUI
1135 /* W32 specific version. Why?. ++kfs */
1136 ascent = height / 2 - (FONT_DESCENT (face->font)
1137 - FONT_BASE (face->font)) / 2;
1138 #else
1139 /* This expression is arranged so that if the image can't be
1140 exactly centered, it will be moved slightly up. This is
1141 because a typical font is `top-heavy' (due to the presence
1142 uppercase letters), so the image placement should err towards
1143 being top-heavy too. It also just generally looks better. */
1144 ascent = (height + FONT_BASE(face->font)
1145 - FONT_DESCENT(face->font) + 1) / 2;
1146 #endif /* HAVE_NTGUI */
1148 else
1149 ascent = height / 2;
1151 else
1152 ascent = (int) (height * img->ascent / 100.0);
1154 return ascent;
1158 /* Image background colors. */
1160 /* Find the "best" corner color of a bitmap.
1161 On W32, XIMG is assumed to a device context with the bitmap selected. */
1163 static RGB_PIXEL_COLOR
1164 four_corners_best (XImagePtr_or_DC ximg, int *corners,
1165 unsigned long width, unsigned long height)
1167 RGB_PIXEL_COLOR corner_pixels[4], best;
1168 int i, best_count;
1170 if (corners && corners[BOT_CORNER] >= 0)
1172 /* Get the colors at the corner_pixels of ximg. */
1173 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1174 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1175 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1176 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1178 else
1180 /* Get the colors at the corner_pixels of ximg. */
1181 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1182 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1183 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1184 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1186 /* Choose the most frequently found color as background. */
1187 for (i = best_count = 0; i < 4; ++i)
1189 int j, n;
1191 for (j = n = 0; j < 4; ++j)
1192 if (corner_pixels[i] == corner_pixels[j])
1193 ++n;
1195 if (n > best_count)
1196 best = corner_pixels[i], best_count = n;
1199 return best;
1202 /* Portability macros */
1204 #ifdef HAVE_NTGUI
1206 #define Destroy_Image(img_dc, prev) \
1207 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1209 #define Free_Pixmap(display, pixmap) \
1210 DeleteObject (pixmap)
1212 #elif defined (HAVE_NS)
1214 #define Destroy_Image(ximg, dummy) \
1215 ns_release_object (ximg)
1217 #define Free_Pixmap(display, pixmap) \
1218 ns_release_object (pixmap)
1220 #else
1222 #define Destroy_Image(ximg, dummy) \
1223 XDestroyImage (ximg)
1225 #define Free_Pixmap(display, pixmap) \
1226 XFreePixmap (display, pixmap)
1228 #endif /* !HAVE_NTGUI && !HAVE_NS */
1231 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1232 it is guessed heuristically. If non-zero, XIMG is an existing
1233 XImage object (or device context with the image selected on W32) to
1234 use for the heuristic. */
1236 RGB_PIXEL_COLOR
1237 image_background (struct image *img, struct frame *f, XImagePtr_or_DC ximg)
1239 if (! img->background_valid)
1240 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1242 int free_ximg = !ximg;
1243 #ifdef HAVE_NTGUI
1244 HGDIOBJ prev;
1245 #endif /* HAVE_NTGUI */
1247 if (free_ximg)
1249 #ifndef HAVE_NTGUI
1250 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1251 0, 0, img->width, img->height, ~0, ZPixmap);
1252 #else
1253 HDC frame_dc = get_frame_dc (f);
1254 ximg = CreateCompatibleDC (frame_dc);
1255 release_frame_dc (f, frame_dc);
1256 prev = SelectObject (ximg, img->pixmap);
1257 #endif /* !HAVE_NTGUI */
1260 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1262 if (free_ximg)
1263 Destroy_Image (ximg, prev);
1265 img->background_valid = 1;
1268 return img->background;
1271 /* Return the `background_transparent' field of IMG. If IMG doesn't
1272 have one yet, it is guessed heuristically. If non-zero, MASK is an
1273 existing XImage object to use for the heuristic. */
1276 image_background_transparent (struct image *img, struct frame *f, XImagePtr_or_DC mask)
1278 if (! img->background_transparent_valid)
1279 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1281 if (img->mask)
1283 int free_mask = !mask;
1284 #ifdef HAVE_NTGUI
1285 HGDIOBJ prev;
1286 #endif /* HAVE_NTGUI */
1288 if (free_mask)
1290 #ifndef HAVE_NTGUI
1291 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1292 0, 0, img->width, img->height, ~0, ZPixmap);
1293 #else
1294 HDC frame_dc = get_frame_dc (f);
1295 mask = CreateCompatibleDC (frame_dc);
1296 release_frame_dc (f, frame_dc);
1297 prev = SelectObject (mask, img->mask);
1298 #endif /* HAVE_NTGUI */
1301 img->background_transparent
1302 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1304 if (free_mask)
1305 Destroy_Image (mask, prev);
1307 else
1308 img->background_transparent = 0;
1310 img->background_transparent_valid = 1;
1313 return img->background_transparent;
1317 /***********************************************************************
1318 Helper functions for X image types
1319 ***********************************************************************/
1321 static void x_clear_image_1 (struct frame *, struct image *, int,
1322 int, int);
1323 static void x_clear_image (struct frame *f, struct image *img);
1324 static unsigned long x_alloc_image_color (struct frame *f,
1325 struct image *img,
1326 Lisp_Object color_name,
1327 unsigned long dflt);
1330 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1331 free the pixmap if any. MASK_P non-zero means clear the mask
1332 pixmap if any. COLORS_P non-zero means free colors allocated for
1333 the image, if any. */
1335 static void
1336 x_clear_image_1 (struct frame *f, struct image *img, int pixmap_p, int mask_p,
1337 int colors_p)
1339 if (pixmap_p && img->pixmap)
1341 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1342 img->pixmap = NO_PIXMAP;
1343 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1344 img->background_valid = 0;
1347 if (mask_p && img->mask)
1349 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1350 img->mask = NO_PIXMAP;
1351 img->background_transparent_valid = 0;
1354 if (colors_p && img->ncolors)
1356 /* W32_TODO: color table support. */
1357 #ifdef HAVE_X_WINDOWS
1358 x_free_colors (f, img->colors, img->ncolors);
1359 #endif /* HAVE_X_WINDOWS */
1360 xfree (img->colors);
1361 img->colors = NULL;
1362 img->ncolors = 0;
1367 /* Free X resources of image IMG which is used on frame F. */
1369 static void
1370 x_clear_image (struct frame *f, struct image *img)
1372 BLOCK_INPUT;
1373 x_clear_image_1 (f, img, 1, 1, 1);
1374 UNBLOCK_INPUT;
1378 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1379 cannot be allocated, use DFLT. Add a newly allocated color to
1380 IMG->colors, so that it can be freed again. Value is the pixel
1381 color. */
1383 static unsigned long
1384 x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1385 unsigned long dflt)
1387 XColor color;
1388 unsigned long result;
1390 xassert (STRINGP (color_name));
1392 if (x_defined_color (f, SDATA (color_name), &color, 1))
1394 /* This isn't called frequently so we get away with simply
1395 reallocating the color vector to the needed size, here. */
1396 ++img->ncolors;
1397 img->colors =
1398 (unsigned long *) xrealloc (img->colors,
1399 img->ncolors * sizeof *img->colors);
1400 img->colors[img->ncolors - 1] = color.pixel;
1401 result = color.pixel;
1403 else
1404 result = dflt;
1406 return result;
1411 /***********************************************************************
1412 Image Cache
1413 ***********************************************************************/
1415 static struct image *search_image_cache (struct frame *, Lisp_Object, unsigned);
1416 static void cache_image (struct frame *f, struct image *img);
1417 static void postprocess_image (struct frame *, struct image *);
1419 /* Return a new, initialized image cache that is allocated from the
1420 heap. Call free_image_cache to free an image cache. */
1422 struct image_cache *
1423 make_image_cache (void)
1425 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1426 int size;
1428 memset (c, 0, sizeof *c);
1429 c->size = 50;
1430 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1431 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1432 c->buckets = (struct image **) xmalloc (size);
1433 memset (c->buckets, 0, size);
1434 return c;
1438 /* Find an image matching SPEC in the cache, and return it. If no
1439 image is found, return NULL. */
1440 static struct image *
1441 search_image_cache (struct frame *f, Lisp_Object spec, unsigned int hash)
1443 struct image *img;
1444 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1445 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1447 if (!c) return NULL;
1449 /* If the image spec does not specify a background color, the cached
1450 image must have the same background color as the current frame.
1451 The foreground color must also match, for the sake of monochrome
1452 images.
1454 In fact, we could ignore the foreground color matching condition
1455 for color images, or if the image spec specifies :foreground;
1456 similarly we could ignore the background color matching condition
1457 for formats that don't use transparency (such as jpeg), or if the
1458 image spec specifies :background. However, the extra memory
1459 usage is probably negligible in practice, so we don't bother. */
1461 for (img = c->buckets[i]; img; img = img->next)
1462 if (img->hash == hash
1463 && !NILP (Fequal (img->spec, spec))
1464 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1465 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1466 break;
1467 return img;
1471 /* Search frame F for an image with spec SPEC, and free it. */
1473 static void
1474 uncache_image (struct frame *f, Lisp_Object spec)
1476 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1477 if (img)
1478 free_image (f, img);
1482 /* Free image cache of frame F. Be aware that X frames share images
1483 caches. */
1485 void
1486 free_image_cache (struct frame *f)
1488 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1489 if (c)
1491 int i;
1493 /* Cache should not be referenced by any frame when freed. */
1494 xassert (c->refcount == 0);
1496 for (i = 0; i < c->used; ++i)
1497 free_image (f, c->images[i]);
1498 xfree (c->images);
1499 xfree (c->buckets);
1500 xfree (c);
1501 FRAME_IMAGE_CACHE (f) = NULL;
1506 /* Clear image cache of frame F. FILTER=t means free all images.
1507 FILTER=nil means clear only images that haven't been
1508 displayed for some time.
1509 Else, only free the images which have FILTER in their `dependencies'.
1510 Should be called from time to time to reduce the number of loaded images.
1511 If image-cache-eviction-delay is non-nil, this frees images in the cache
1512 which weren't displayed for at least that many seconds. */
1514 void
1515 clear_image_cache (struct frame *f, Lisp_Object filter)
1517 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1519 if (c)
1521 int i, nfreed = 0;
1523 /* Block input so that we won't be interrupted by a SIGIO
1524 while being in an inconsistent state. */
1525 BLOCK_INPUT;
1527 if (!NILP (filter))
1529 /* Filter image cache. */
1530 for (i = 0; i < c->used; ++i)
1532 struct image *img = c->images[i];
1533 if (img && (EQ (Qt, filter)
1534 || !NILP (Fmember (filter, img->dependencies))))
1536 free_image (f, img);
1537 ++nfreed;
1541 else if (INTEGERP (Vimage_cache_eviction_delay))
1543 /* Free cache based on timestamp. */
1544 EMACS_TIME t;
1545 unsigned long old;
1546 int delay, nimages = 0;
1548 for (i = 0; i < c->used; ++i)
1549 if (c->images[i])
1550 nimages++;
1552 /* If the number of cached images has grown unusually large,
1553 decrease the cache eviction delay (Bug#6230). */
1554 delay = XFASTINT (Vimage_cache_eviction_delay);
1555 if (nimages > 40)
1556 delay = max (1, 1600 * delay / (nimages*nimages));
1558 EMACS_GET_TIME (t);
1559 old = EMACS_SECS (t) - delay;
1561 for (i = 0; i < c->used; ++i)
1563 struct image *img = c->images[i];
1564 if (img && img->timestamp < old)
1566 free_image (f, img);
1567 ++nfreed;
1572 /* We may be clearing the image cache because, for example,
1573 Emacs was iconified for a longer period of time. In that
1574 case, current matrices may still contain references to
1575 images freed above. So, clear these matrices. */
1576 if (nfreed)
1578 Lisp_Object tail, frame;
1580 FOR_EACH_FRAME (tail, frame)
1582 struct frame *f = XFRAME (frame);
1583 if (FRAME_IMAGE_CACHE (f) == c)
1584 clear_current_matrices (f);
1587 ++windows_or_buffers_changed;
1590 UNBLOCK_INPUT;
1594 void
1595 clear_image_caches (Lisp_Object filter)
1597 /* FIXME: We want to do
1598 * struct terminal *t;
1599 * for (t = terminal_list; t; t = t->next_terminal)
1600 * clear_image_cache (t, filter); */
1601 Lisp_Object tail, frame;
1602 FOR_EACH_FRAME (tail, frame)
1603 if (FRAME_WINDOW_P (XFRAME (frame)))
1604 clear_image_cache (XFRAME (frame), filter);
1607 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1608 0, 1, 0,
1609 doc: /* Clear the image cache.
1610 FILTER nil or a frame means clear all images in the selected frame.
1611 FILTER t means clear the image caches of all frames.
1612 Anything else, means only clear those images which refer to FILTER,
1613 which is then usually a filename. */)
1614 (Lisp_Object filter)
1616 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1617 clear_image_caches (filter);
1618 else
1619 clear_image_cache (check_x_frame (filter), Qt);
1621 return Qnil;
1625 DEFUN ("image-flush", Fimage_flush, Simage_flush,
1626 1, 2, 0,
1627 doc: /* Fush the image with specification SPEC on frame FRAME.
1628 This removes the image from the Emacs image cache. If SPEC specifies
1629 an image file, the next redisplay of this image will read from the
1630 current contents of that file.
1632 FRAME nil or omitted means use the selected frame.
1633 FRAME t means refresh the image on all frames. */)
1634 (Lisp_Object spec, Lisp_Object frame)
1636 if (!valid_image_p (spec))
1637 error ("Invalid image specification");
1639 if (EQ (frame, Qt))
1641 Lisp_Object tail;
1642 FOR_EACH_FRAME (tail, frame)
1644 struct frame *f = XFRAME (frame);
1645 if (FRAME_WINDOW_P (f))
1646 uncache_image (f, spec);
1649 else
1650 uncache_image (check_x_frame (frame), spec);
1652 return Qnil;
1656 /* Compute masks and transform image IMG on frame F, as specified
1657 by the image's specification, */
1659 static void
1660 postprocess_image (struct frame *f, struct image *img)
1662 /* Manipulation of the image's mask. */
1663 if (img->pixmap)
1665 Lisp_Object conversion, spec;
1666 Lisp_Object mask;
1668 spec = img->spec;
1670 /* `:heuristic-mask t'
1671 `:mask heuristic'
1672 means build a mask heuristically.
1673 `:heuristic-mask (R G B)'
1674 `:mask (heuristic (R G B))'
1675 means build a mask from color (R G B) in the
1676 image.
1677 `:mask nil'
1678 means remove a mask, if any. */
1680 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1681 if (!NILP (mask))
1682 x_build_heuristic_mask (f, img, mask);
1683 else
1685 int found_p;
1687 mask = image_spec_value (spec, QCmask, &found_p);
1689 if (EQ (mask, Qheuristic))
1690 x_build_heuristic_mask (f, img, Qt);
1691 else if (CONSP (mask)
1692 && EQ (XCAR (mask), Qheuristic))
1694 if (CONSP (XCDR (mask)))
1695 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1696 else
1697 x_build_heuristic_mask (f, img, XCDR (mask));
1699 else if (NILP (mask) && found_p && img->mask)
1701 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1702 img->mask = NO_PIXMAP;
1707 /* Should we apply an image transformation algorithm? */
1708 conversion = image_spec_value (spec, QCconversion, NULL);
1709 if (EQ (conversion, Qdisabled))
1710 x_disable_image (f, img);
1711 else if (EQ (conversion, Qlaplace))
1712 x_laplace (f, img);
1713 else if (EQ (conversion, Qemboss))
1714 x_emboss (f, img);
1715 else if (CONSP (conversion)
1716 && EQ (XCAR (conversion), Qedge_detection))
1718 Lisp_Object tem;
1719 tem = XCDR (conversion);
1720 if (CONSP (tem))
1721 x_edge_detection (f, img,
1722 Fplist_get (tem, QCmatrix),
1723 Fplist_get (tem, QCcolor_adjustment));
1729 /* Return the id of image with Lisp specification SPEC on frame F.
1730 SPEC must be a valid Lisp image specification (see valid_image_p). */
1733 lookup_image (struct frame *f, Lisp_Object spec)
1735 struct image_cache *c;
1736 struct image *img;
1737 unsigned hash;
1738 struct gcpro gcpro1;
1739 EMACS_TIME now;
1741 /* F must be a window-system frame, and SPEC must be a valid image
1742 specification. */
1743 xassert (FRAME_WINDOW_P (f));
1744 xassert (valid_image_p (spec));
1746 c = FRAME_IMAGE_CACHE (f);
1748 GCPRO1 (spec);
1750 /* Look up SPEC in the hash table of the image cache. */
1751 hash = sxhash (spec, 0);
1752 img = search_image_cache (f, spec, hash);
1753 if (img && img->load_failed_p)
1755 free_image (f, img);
1756 img = NULL;
1759 /* If not found, create a new image and cache it. */
1760 if (img == NULL)
1762 extern Lisp_Object Qpostscript;
1764 BLOCK_INPUT;
1765 img = make_image (spec, hash);
1766 cache_image (f, img);
1767 img->load_failed_p = img->type->load (f, img) == 0;
1768 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1769 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1771 /* If we can't load the image, and we don't have a width and
1772 height, use some arbitrary width and height so that we can
1773 draw a rectangle for it. */
1774 if (img->load_failed_p)
1776 Lisp_Object value;
1778 value = image_spec_value (spec, QCwidth, NULL);
1779 img->width = (INTEGERP (value)
1780 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1781 value = image_spec_value (spec, QCheight, NULL);
1782 img->height = (INTEGERP (value)
1783 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1785 else
1787 /* Handle image type independent image attributes
1788 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1789 `:background COLOR'. */
1790 Lisp_Object ascent, margin, relief, bg;
1792 ascent = image_spec_value (spec, QCascent, NULL);
1793 if (INTEGERP (ascent))
1794 img->ascent = XFASTINT (ascent);
1795 else if (EQ (ascent, Qcenter))
1796 img->ascent = CENTERED_IMAGE_ASCENT;
1798 margin = image_spec_value (spec, QCmargin, NULL);
1799 if (INTEGERP (margin) && XINT (margin) >= 0)
1800 img->vmargin = img->hmargin = XFASTINT (margin);
1801 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1802 && INTEGERP (XCDR (margin)))
1804 if (XINT (XCAR (margin)) > 0)
1805 img->hmargin = XFASTINT (XCAR (margin));
1806 if (XINT (XCDR (margin)) > 0)
1807 img->vmargin = XFASTINT (XCDR (margin));
1810 relief = image_spec_value (spec, QCrelief, NULL);
1811 if (INTEGERP (relief))
1813 img->relief = XINT (relief);
1814 img->hmargin += eabs (img->relief);
1815 img->vmargin += eabs (img->relief);
1818 if (! img->background_valid)
1820 bg = image_spec_value (img->spec, QCbackground, NULL);
1821 if (!NILP (bg))
1823 img->background
1824 = x_alloc_image_color (f, img, bg,
1825 FRAME_BACKGROUND_PIXEL (f));
1826 img->background_valid = 1;
1830 /* Do image transformations and compute masks, unless we
1831 don't have the image yet. */
1832 if (!EQ (*img->type->type, Qpostscript))
1833 postprocess_image (f, img);
1836 UNBLOCK_INPUT;
1839 /* We're using IMG, so set its timestamp to `now'. */
1840 EMACS_GET_TIME (now);
1841 img->timestamp = EMACS_SECS (now);
1843 UNGCPRO;
1845 /* Value is the image id. */
1846 return img->id;
1850 /* Cache image IMG in the image cache of frame F. */
1852 static void
1853 cache_image (struct frame *f, struct image *img)
1855 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1856 int i;
1858 /* Find a free slot in c->images. */
1859 for (i = 0; i < c->used; ++i)
1860 if (c->images[i] == NULL)
1861 break;
1863 /* If no free slot found, maybe enlarge c->images. */
1864 if (i == c->used && c->used == c->size)
1866 c->size *= 2;
1867 c->images = (struct image **) xrealloc (c->images,
1868 c->size * sizeof *c->images);
1871 /* Add IMG to c->images, and assign IMG an id. */
1872 c->images[i] = img;
1873 img->id = i;
1874 if (i == c->used)
1875 ++c->used;
1877 /* Add IMG to the cache's hash table. */
1878 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1879 img->next = c->buckets[i];
1880 if (img->next)
1881 img->next->prev = img;
1882 img->prev = NULL;
1883 c->buckets[i] = img;
1887 /* Call FN on every image in the image cache of frame F. Used to mark
1888 Lisp Objects in the image cache. */
1890 /* Mark Lisp objects in image IMG. */
1892 static void
1893 mark_image (struct image *img)
1895 mark_object (img->spec);
1896 mark_object (img->dependencies);
1898 if (!NILP (img->data.lisp_val))
1899 mark_object (img->data.lisp_val);
1903 void
1904 mark_image_cache (struct image_cache *c)
1906 if (c)
1908 int i;
1909 for (i = 0; i < c->used; ++i)
1910 if (c->images[i])
1911 mark_image (c->images[i]);
1917 /***********************************************************************
1918 X / NS / W32 support code
1919 ***********************************************************************/
1921 #ifdef HAVE_NTGUI
1923 /* Macro for defining functions that will be loaded from image DLLs. */
1924 #define DEF_IMGLIB_FN(func) int (FAR CDECL *fn_##func)()
1926 /* Macro for loading those image functions from the library. */
1927 #define LOAD_IMGLIB_FN(lib,func) { \
1928 fn_##func = (void *) GetProcAddress (lib, #func); \
1929 if (!fn_##func) return 0; \
1932 /* Load a DLL implementing an image type.
1933 The `image-library-alist' variable associates a symbol,
1934 identifying an image type, to a list of possible filenames.
1935 The function returns NULL if no library could be loaded for
1936 the given image type, or if the library was previously loaded;
1937 else the handle of the DLL. */
1938 static HMODULE
1939 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
1941 HMODULE library = NULL;
1943 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
1945 Lisp_Object dlls = Fassq (type, libraries);
1947 if (CONSP (dlls))
1948 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
1950 CHECK_STRING_CAR (dlls);
1951 if (library = LoadLibrary (SDATA (XCAR (dlls))))
1952 break;
1956 return library;
1959 #endif /* HAVE_NTGUI */
1961 static int x_create_x_image_and_pixmap (struct frame *, int, int, int,
1962 XImagePtr *, Pixmap *);
1963 static void x_destroy_x_image (XImagePtr);
1964 static void x_put_x_image (struct frame *, XImagePtr, Pixmap, int, int);
1967 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1968 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1969 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1970 via xmalloc. Print error messages via image_error if an error
1971 occurs. Value is non-zero if successful.
1973 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1974 should indicate the bit depth of the image. */
1976 static int
1977 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1978 XImagePtr *ximg, Pixmap *pixmap)
1980 #ifdef HAVE_X_WINDOWS
1981 Display *display = FRAME_X_DISPLAY (f);
1982 Window window = FRAME_X_WINDOW (f);
1983 Screen *screen = FRAME_X_SCREEN (f);
1985 xassert (interrupt_input_blocked);
1987 if (depth <= 0)
1988 depth = DefaultDepthOfScreen (screen);
1989 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1990 depth, ZPixmap, 0, NULL, width, height,
1991 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1992 if (*ximg == NULL)
1994 image_error ("Unable to allocate X image", Qnil, Qnil);
1995 return 0;
1998 /* Allocate image raster. */
1999 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
2001 /* Allocate a pixmap of the same size. */
2002 *pixmap = XCreatePixmap (display, window, width, height, depth);
2003 if (*pixmap == NO_PIXMAP)
2005 x_destroy_x_image (*ximg);
2006 *ximg = NULL;
2007 image_error ("Unable to create X pixmap", Qnil, Qnil);
2008 return 0;
2011 return 1;
2012 #endif /* HAVE_X_WINDOWS */
2014 #ifdef HAVE_NTGUI
2016 BITMAPINFOHEADER *header;
2017 HDC hdc;
2018 int scanline_width_bits;
2019 int remainder;
2020 int palette_colors = 0;
2022 if (depth == 0)
2023 depth = 24;
2025 if (depth != 1 && depth != 4 && depth != 8
2026 && depth != 16 && depth != 24 && depth != 32)
2028 image_error ("Invalid image bit depth specified", Qnil, Qnil);
2029 return 0;
2032 scanline_width_bits = width * depth;
2033 remainder = scanline_width_bits % 32;
2035 if (remainder)
2036 scanline_width_bits += 32 - remainder;
2038 /* Bitmaps with a depth less than 16 need a palette. */
2039 /* BITMAPINFO structure already contains the first RGBQUAD. */
2040 if (depth < 16)
2041 palette_colors = 1 << depth - 1;
2043 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2044 if (*ximg == NULL)
2046 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
2047 return 0;
2050 header = &(*ximg)->info.bmiHeader;
2051 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2052 header->biSize = sizeof (*header);
2053 header->biWidth = width;
2054 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2055 header->biPlanes = 1;
2056 header->biBitCount = depth;
2057 header->biCompression = BI_RGB;
2058 header->biClrUsed = palette_colors;
2060 /* TODO: fill in palette. */
2061 if (depth == 1)
2063 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2064 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2065 (*ximg)->info.bmiColors[0].rgbRed = 0;
2066 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2067 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2068 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2069 (*ximg)->info.bmiColors[1].rgbRed = 255;
2070 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2073 hdc = get_frame_dc (f);
2075 /* Create a DIBSection and raster array for the bitmap,
2076 and store its handle in *pixmap. */
2077 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2078 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2079 /* casting avoids a GCC warning */
2080 (void **)&((*ximg)->data), NULL, 0);
2082 /* Realize display palette and garbage all frames. */
2083 release_frame_dc (f, hdc);
2085 if (*pixmap == NULL)
2087 DWORD err = GetLastError ();
2088 Lisp_Object errcode;
2089 /* All system errors are < 10000, so the following is safe. */
2090 XSETINT (errcode, (int) err);
2091 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2092 x_destroy_x_image (*ximg);
2093 return 0;
2096 return 1;
2098 #endif /* HAVE_NTGUI */
2100 #ifdef HAVE_NS
2101 *pixmap = ns_image_for_XPM (width, height, depth);
2102 if (*pixmap == 0)
2104 *ximg = NULL;
2105 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2106 return 0;
2108 *ximg = *pixmap;
2109 return 1;
2110 #endif
2114 /* Destroy XImage XIMG. Free XIMG->data. */
2116 static void
2117 x_destroy_x_image (XImagePtr ximg)
2119 xassert (interrupt_input_blocked);
2120 if (ximg)
2122 #ifdef HAVE_X_WINDOWS
2123 xfree (ximg->data);
2124 ximg->data = NULL;
2125 XDestroyImage (ximg);
2126 #endif /* HAVE_X_WINDOWS */
2127 #ifdef HAVE_NTGUI
2128 /* Data will be freed by DestroyObject. */
2129 ximg->data = NULL;
2130 xfree (ximg);
2131 #endif /* HAVE_NTGUI */
2132 #ifdef HAVE_NS
2133 ns_release_object (ximg);
2134 #endif /* HAVE_NS */
2139 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2140 are width and height of both the image and pixmap. */
2142 static void
2143 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2145 #ifdef HAVE_X_WINDOWS
2146 GC gc;
2148 xassert (interrupt_input_blocked);
2149 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2150 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2151 XFreeGC (FRAME_X_DISPLAY (f), gc);
2152 #endif /* HAVE_X_WINDOWS */
2154 #ifdef HAVE_NTGUI
2155 #if 0 /* I don't think this is necessary looking at where it is used. */
2156 HDC hdc = get_frame_dc (f);
2157 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2158 release_frame_dc (f, hdc);
2159 #endif
2160 #endif /* HAVE_NTGUI */
2162 #ifdef HAVE_NS
2163 xassert (ximg == pixmap);
2164 ns_retain_object (ximg);
2165 #endif
2169 /***********************************************************************
2170 File Handling
2171 ***********************************************************************/
2173 static unsigned char *slurp_file (char *, int *);
2176 /* Find image file FILE. Look in data-directory/images, then
2177 x-bitmap-file-path. Value is the encoded full name of the file
2178 found, or nil if not found. */
2180 Lisp_Object
2181 x_find_image_file (Lisp_Object file)
2183 Lisp_Object file_found, search_path;
2184 struct gcpro gcpro1, gcpro2;
2185 int fd;
2187 file_found = Qnil;
2188 /* TODO I think this should use something like image-load-path
2189 instead. Unfortunately, that can contain non-string elements. */
2190 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2191 Vdata_directory),
2192 Vx_bitmap_file_path);
2193 GCPRO2 (file_found, search_path);
2195 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2196 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2198 if (fd == -1)
2199 file_found = Qnil;
2200 else
2202 file_found = ENCODE_FILE (file_found);
2203 close (fd);
2206 UNGCPRO;
2207 return file_found;
2211 /* Read FILE into memory. Value is a pointer to a buffer allocated
2212 with xmalloc holding FILE's contents. Value is null if an error
2213 occurred. *SIZE is set to the size of the file. */
2215 static unsigned char *
2216 slurp_file (char *file, int *size)
2218 FILE *fp = NULL;
2219 unsigned char *buf = NULL;
2220 struct stat st;
2222 if (stat (file, &st) == 0
2223 && (fp = fopen (file, "rb")) != NULL
2224 && (buf = (unsigned char *) xmalloc (st.st_size),
2225 fread (buf, 1, st.st_size, fp) == st.st_size))
2227 *size = st.st_size;
2228 fclose (fp);
2230 else
2232 if (fp)
2233 fclose (fp);
2234 if (buf)
2236 xfree (buf);
2237 buf = NULL;
2241 return buf;
2246 /***********************************************************************
2247 XBM images
2248 ***********************************************************************/
2250 static int xbm_scan (unsigned char **, unsigned char *, char *, int *);
2251 static int xbm_load (struct frame *f, struct image *img);
2252 static int xbm_load_image (struct frame *f, struct image *img,
2253 unsigned char *, unsigned char *);
2254 static int xbm_image_p (Lisp_Object object);
2255 static int xbm_read_bitmap_data (struct frame *f,
2256 unsigned char *, unsigned char *,
2257 int *, int *, unsigned char **, int);
2258 static int xbm_file_p (Lisp_Object);
2261 /* Indices of image specification fields in xbm_format, below. */
2263 enum xbm_keyword_index
2265 XBM_TYPE,
2266 XBM_FILE,
2267 XBM_WIDTH,
2268 XBM_HEIGHT,
2269 XBM_DATA,
2270 XBM_FOREGROUND,
2271 XBM_BACKGROUND,
2272 XBM_ASCENT,
2273 XBM_MARGIN,
2274 XBM_RELIEF,
2275 XBM_ALGORITHM,
2276 XBM_HEURISTIC_MASK,
2277 XBM_MASK,
2278 XBM_LAST
2281 /* Vector of image_keyword structures describing the format
2282 of valid XBM image specifications. */
2284 static const struct image_keyword xbm_format[XBM_LAST] =
2286 {":type", IMAGE_SYMBOL_VALUE, 1},
2287 {":file", IMAGE_STRING_VALUE, 0},
2288 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2289 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2290 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2291 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2292 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2293 {":ascent", IMAGE_ASCENT_VALUE, 0},
2294 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2295 {":relief", IMAGE_INTEGER_VALUE, 0},
2296 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2297 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2298 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2301 /* Structure describing the image type XBM. */
2303 static struct image_type xbm_type =
2305 &Qxbm,
2306 xbm_image_p,
2307 xbm_load,
2308 x_clear_image,
2309 NULL
2312 /* Tokens returned from xbm_scan. */
2314 enum xbm_token
2316 XBM_TK_IDENT = 256,
2317 XBM_TK_NUMBER
2321 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2322 A valid specification is a list starting with the symbol `image'
2323 The rest of the list is a property list which must contain an
2324 entry `:type xbm..
2326 If the specification specifies a file to load, it must contain
2327 an entry `:file FILENAME' where FILENAME is a string.
2329 If the specification is for a bitmap loaded from memory it must
2330 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2331 WIDTH and HEIGHT are integers > 0. DATA may be:
2333 1. a string large enough to hold the bitmap data, i.e. it must
2334 have a size >= (WIDTH + 7) / 8 * HEIGHT
2336 2. a bool-vector of size >= WIDTH * HEIGHT
2338 3. a vector of strings or bool-vectors, one for each line of the
2339 bitmap.
2341 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2342 may not be specified in this case because they are defined in the
2343 XBM file.
2345 Both the file and data forms may contain the additional entries
2346 `:background COLOR' and `:foreground COLOR'. If not present,
2347 foreground and background of the frame on which the image is
2348 displayed is used. */
2350 static int
2351 xbm_image_p (Lisp_Object object)
2353 struct image_keyword kw[XBM_LAST];
2355 memcpy (kw, xbm_format, sizeof kw);
2356 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2357 return 0;
2359 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2361 if (kw[XBM_FILE].count)
2363 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2364 return 0;
2366 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2368 /* In-memory XBM file. */
2369 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2370 return 0;
2372 else
2374 Lisp_Object data;
2375 int width, height;
2377 /* Entries for `:width', `:height' and `:data' must be present. */
2378 if (!kw[XBM_WIDTH].count
2379 || !kw[XBM_HEIGHT].count
2380 || !kw[XBM_DATA].count)
2381 return 0;
2383 data = kw[XBM_DATA].value;
2384 width = XFASTINT (kw[XBM_WIDTH].value);
2385 height = XFASTINT (kw[XBM_HEIGHT].value);
2387 /* Check type of data, and width and height against contents of
2388 data. */
2389 if (VECTORP (data))
2391 int i;
2393 /* Number of elements of the vector must be >= height. */
2394 if (XVECTOR (data)->size < height)
2395 return 0;
2397 /* Each string or bool-vector in data must be large enough
2398 for one line of the image. */
2399 for (i = 0; i < height; ++i)
2401 Lisp_Object elt = XVECTOR (data)->contents[i];
2403 if (STRINGP (elt))
2405 if (SCHARS (elt)
2406 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2407 return 0;
2409 else if (BOOL_VECTOR_P (elt))
2411 if (XBOOL_VECTOR (elt)->size < width)
2412 return 0;
2414 else
2415 return 0;
2418 else if (STRINGP (data))
2420 if (SCHARS (data)
2421 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2422 return 0;
2424 else if (BOOL_VECTOR_P (data))
2426 if (XBOOL_VECTOR (data)->size < width * height)
2427 return 0;
2429 else
2430 return 0;
2433 return 1;
2437 /* Scan a bitmap file. FP is the stream to read from. Value is
2438 either an enumerator from enum xbm_token, or a character for a
2439 single-character token, or 0 at end of file. If scanning an
2440 identifier, store the lexeme of the identifier in SVAL. If
2441 scanning a number, store its value in *IVAL. */
2443 static int
2444 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2446 unsigned int c;
2448 loop:
2450 /* Skip white space. */
2451 while (*s < end && (c = *(*s)++, isspace (c)))
2454 if (*s >= end)
2455 c = 0;
2456 else if (isdigit (c))
2458 int value = 0, digit;
2460 if (c == '0' && *s < end)
2462 c = *(*s)++;
2463 if (c == 'x' || c == 'X')
2465 while (*s < end)
2467 c = *(*s)++;
2468 if (isdigit (c))
2469 digit = c - '0';
2470 else if (c >= 'a' && c <= 'f')
2471 digit = c - 'a' + 10;
2472 else if (c >= 'A' && c <= 'F')
2473 digit = c - 'A' + 10;
2474 else
2475 break;
2476 value = 16 * value + digit;
2479 else if (isdigit (c))
2481 value = c - '0';
2482 while (*s < end
2483 && (c = *(*s)++, isdigit (c)))
2484 value = 8 * value + c - '0';
2487 else
2489 value = c - '0';
2490 while (*s < end
2491 && (c = *(*s)++, isdigit (c)))
2492 value = 10 * value + c - '0';
2495 if (*s < end)
2496 *s = *s - 1;
2497 *ival = value;
2498 c = XBM_TK_NUMBER;
2500 else if (isalpha (c) || c == '_')
2502 *sval++ = c;
2503 while (*s < end
2504 && (c = *(*s)++, (isalnum (c) || c == '_')))
2505 *sval++ = c;
2506 *sval = 0;
2507 if (*s < end)
2508 *s = *s - 1;
2509 c = XBM_TK_IDENT;
2511 else if (c == '/' && **s == '*')
2513 /* C-style comment. */
2514 ++*s;
2515 while (**s && (**s != '*' || *(*s + 1) != '/'))
2516 ++*s;
2517 if (**s)
2519 *s += 2;
2520 goto loop;
2524 return c;
2527 #ifdef HAVE_NTGUI
2529 /* Create a Windows bitmap from X bitmap data. */
2530 static HBITMAP
2531 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2533 static unsigned char swap_nibble[16]
2534 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2535 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2536 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2537 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2538 int i, j, w1, w2;
2539 unsigned char *bits, *p;
2540 HBITMAP bmp;
2542 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2543 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2544 bits = (unsigned char *) alloca (height * w2);
2545 memset (bits, 0, height * w2);
2546 for (i = 0; i < height; i++)
2548 p = bits + i*w2;
2549 for (j = 0; j < w1; j++)
2551 /* Bitswap XBM bytes to match how Windows does things. */
2552 unsigned char c = *data++;
2553 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2554 | (swap_nibble[(c>>4) & 0xf]));
2557 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2559 return bmp;
2562 static void
2563 convert_mono_to_color_image (f, img, foreground, background)
2564 struct frame *f;
2565 struct image *img;
2566 COLORREF foreground, background;
2568 HDC hdc, old_img_dc, new_img_dc;
2569 HGDIOBJ old_prev, new_prev;
2570 HBITMAP new_pixmap;
2572 hdc = get_frame_dc (f);
2573 old_img_dc = CreateCompatibleDC (hdc);
2574 new_img_dc = CreateCompatibleDC (hdc);
2575 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2576 release_frame_dc (f, hdc);
2577 old_prev = SelectObject (old_img_dc, img->pixmap);
2578 new_prev = SelectObject (new_img_dc, new_pixmap);
2579 /* Windows convention for mono bitmaps is black = background,
2580 white = foreground. */
2581 SetTextColor (new_img_dc, background);
2582 SetBkColor (new_img_dc, foreground);
2584 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2585 0, 0, SRCCOPY);
2587 SelectObject (old_img_dc, old_prev);
2588 SelectObject (new_img_dc, new_prev);
2589 DeleteDC (old_img_dc);
2590 DeleteDC (new_img_dc);
2591 DeleteObject (img->pixmap);
2592 if (new_pixmap == 0)
2593 fprintf (stderr, "Failed to convert image to color.\n");
2594 else
2595 img->pixmap = new_pixmap;
2598 #define XBM_BIT_SHUFFLE(b) (~(b))
2600 #else
2602 #define XBM_BIT_SHUFFLE(b) (b)
2604 #endif /* HAVE_NTGUI */
2607 static void
2608 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2609 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2610 int non_default_colors)
2612 #ifdef HAVE_NTGUI
2613 img->pixmap
2614 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2616 /* If colors were specified, transfer the bitmap to a color one. */
2617 if (non_default_colors)
2618 convert_mono_to_color_image (f, img, fg, bg);
2620 #elif defined (HAVE_NS)
2621 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2623 #else
2624 img->pixmap
2625 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2626 FRAME_X_WINDOW (f),
2627 data,
2628 img->width, img->height,
2629 fg, bg,
2630 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2631 #endif /* !HAVE_NTGUI && !HAVE_NS */
2636 /* Replacement for XReadBitmapFileData which isn't available under old
2637 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2638 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2639 the image. Return in *DATA the bitmap data allocated with xmalloc.
2640 Value is non-zero if successful. DATA null means just test if
2641 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR
2642 is non-zero, inhibit the call to image_error when the image size is
2643 invalid (the bitmap remains unread). */
2645 static int
2646 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2647 int *width, int *height, unsigned char **data,
2648 int inhibit_image_error)
2650 unsigned char *s = contents;
2651 char buffer[BUFSIZ];
2652 int padding_p = 0;
2653 int v10 = 0;
2654 int bytes_per_line, i, nbytes;
2655 unsigned char *p;
2656 int value;
2657 int LA1;
2659 #define match() \
2660 LA1 = xbm_scan (&s, end, buffer, &value)
2662 #define expect(TOKEN) \
2663 if (LA1 != (TOKEN)) \
2664 goto failure; \
2665 else \
2666 match ()
2668 #define expect_ident(IDENT) \
2669 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2670 match (); \
2671 else \
2672 goto failure
2674 *width = *height = -1;
2675 if (data)
2676 *data = NULL;
2677 LA1 = xbm_scan (&s, end, buffer, &value);
2679 /* Parse defines for width, height and hot-spots. */
2680 while (LA1 == '#')
2682 match ();
2683 expect_ident ("define");
2684 expect (XBM_TK_IDENT);
2686 if (LA1 == XBM_TK_NUMBER)
2688 char *p = strrchr (buffer, '_');
2689 p = p ? p + 1 : buffer;
2690 if (strcmp (p, "width") == 0)
2691 *width = value;
2692 else if (strcmp (p, "height") == 0)
2693 *height = value;
2695 expect (XBM_TK_NUMBER);
2698 if (!check_image_size (f, *width, *height))
2700 if (!inhibit_image_error)
2701 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2702 goto failure;
2704 else if (data == NULL)
2705 goto success;
2707 /* Parse bits. Must start with `static'. */
2708 expect_ident ("static");
2709 if (LA1 == XBM_TK_IDENT)
2711 if (strcmp (buffer, "unsigned") == 0)
2713 match ();
2714 expect_ident ("char");
2716 else if (strcmp (buffer, "short") == 0)
2718 match ();
2719 v10 = 1;
2720 if (*width % 16 && *width % 16 < 9)
2721 padding_p = 1;
2723 else if (strcmp (buffer, "char") == 0)
2724 match ();
2725 else
2726 goto failure;
2728 else
2729 goto failure;
2731 expect (XBM_TK_IDENT);
2732 expect ('[');
2733 expect (']');
2734 expect ('=');
2735 expect ('{');
2737 bytes_per_line = (*width + 7) / 8 + padding_p;
2738 nbytes = bytes_per_line * *height;
2739 p = *data = (unsigned char *) xmalloc (nbytes);
2741 if (v10)
2743 for (i = 0; i < nbytes; i += 2)
2745 int val = value;
2746 expect (XBM_TK_NUMBER);
2748 *p++ = XBM_BIT_SHUFFLE (val);
2749 if (!padding_p || ((i + 2) % bytes_per_line))
2750 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2752 if (LA1 == ',' || LA1 == '}')
2753 match ();
2754 else
2755 goto failure;
2758 else
2760 for (i = 0; i < nbytes; ++i)
2762 int val = value;
2763 expect (XBM_TK_NUMBER);
2765 *p++ = XBM_BIT_SHUFFLE (val);
2767 if (LA1 == ',' || LA1 == '}')
2768 match ();
2769 else
2770 goto failure;
2774 success:
2775 return 1;
2777 failure:
2779 if (data && *data)
2781 xfree (*data);
2782 *data = NULL;
2784 return 0;
2786 #undef match
2787 #undef expect
2788 #undef expect_ident
2792 /* Load XBM image IMG which will be displayed on frame F from buffer
2793 CONTENTS. END is the end of the buffer. Value is non-zero if
2794 successful. */
2796 static int
2797 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2798 unsigned char *end)
2800 int rc;
2801 unsigned char *data;
2802 int success_p = 0;
2804 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2805 &data, 0);
2806 if (rc)
2808 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2809 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2810 int non_default_colors = 0;
2811 Lisp_Object value;
2813 xassert (img->width > 0 && img->height > 0);
2815 /* Get foreground and background colors, maybe allocate colors. */
2816 value = image_spec_value (img->spec, QCforeground, NULL);
2817 if (!NILP (value))
2819 foreground = x_alloc_image_color (f, img, value, foreground);
2820 non_default_colors = 1;
2822 value = image_spec_value (img->spec, QCbackground, NULL);
2823 if (!NILP (value))
2825 background = x_alloc_image_color (f, img, value, background);
2826 img->background = background;
2827 img->background_valid = 1;
2828 non_default_colors = 1;
2831 Create_Pixmap_From_Bitmap_Data (f, img, data,
2832 foreground, background,
2833 non_default_colors);
2834 xfree (data);
2836 if (img->pixmap == NO_PIXMAP)
2838 x_clear_image (f, img);
2839 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2841 else
2842 success_p = 1;
2844 else
2845 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2847 return success_p;
2851 /* Value is non-zero if DATA looks like an in-memory XBM file. */
2853 static int
2854 xbm_file_p (Lisp_Object data)
2856 int w, h;
2857 return (STRINGP (data)
2858 && xbm_read_bitmap_data (NULL, SDATA (data),
2859 (SDATA (data) + SBYTES (data)),
2860 &w, &h, NULL, 1));
2864 /* Fill image IMG which is used on frame F with pixmap data. Value is
2865 non-zero if successful. */
2867 static int
2868 xbm_load (struct frame *f, struct image *img)
2870 int success_p = 0;
2871 Lisp_Object file_name;
2873 xassert (xbm_image_p (img->spec));
2875 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2876 file_name = image_spec_value (img->spec, QCfile, NULL);
2877 if (STRINGP (file_name))
2879 Lisp_Object file;
2880 unsigned char *contents;
2881 int size;
2882 struct gcpro gcpro1;
2884 file = x_find_image_file (file_name);
2885 GCPRO1 (file);
2886 if (!STRINGP (file))
2888 image_error ("Cannot find image file `%s'", file_name, Qnil);
2889 UNGCPRO;
2890 return 0;
2893 contents = slurp_file (SDATA (file), &size);
2894 if (contents == NULL)
2896 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2897 UNGCPRO;
2898 return 0;
2901 success_p = xbm_load_image (f, img, contents, contents + size);
2902 UNGCPRO;
2904 else
2906 struct image_keyword fmt[XBM_LAST];
2907 Lisp_Object data;
2908 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2909 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2910 int non_default_colors = 0;
2911 char *bits;
2912 int parsed_p;
2913 int in_memory_file_p = 0;
2915 /* See if data looks like an in-memory XBM file. */
2916 data = image_spec_value (img->spec, QCdata, NULL);
2917 in_memory_file_p = xbm_file_p (data);
2919 /* Parse the image specification. */
2920 memcpy (fmt, xbm_format, sizeof fmt);
2921 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2922 xassert (parsed_p);
2924 /* Get specified width, and height. */
2925 if (!in_memory_file_p)
2927 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2928 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2929 xassert (img->width > 0 && img->height > 0);
2932 /* Get foreground and background colors, maybe allocate colors. */
2933 if (fmt[XBM_FOREGROUND].count
2934 && STRINGP (fmt[XBM_FOREGROUND].value))
2936 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2937 foreground);
2938 non_default_colors = 1;
2941 if (fmt[XBM_BACKGROUND].count
2942 && STRINGP (fmt[XBM_BACKGROUND].value))
2944 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2945 background);
2946 non_default_colors = 1;
2949 if (in_memory_file_p)
2950 success_p = xbm_load_image (f, img, SDATA (data),
2951 (SDATA (data)
2952 + SBYTES (data)));
2953 else
2955 if (VECTORP (data))
2957 int i;
2958 char *p;
2959 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2961 p = bits = (char *) alloca (nbytes * img->height);
2962 for (i = 0; i < img->height; ++i, p += nbytes)
2964 Lisp_Object line = XVECTOR (data)->contents[i];
2965 if (STRINGP (line))
2966 memcpy (p, SDATA (line), nbytes);
2967 else
2968 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
2971 else if (STRINGP (data))
2972 bits = SDATA (data);
2973 else
2974 bits = XBOOL_VECTOR (data)->data;
2976 #ifdef WINDOWSNT
2978 char *invertedBits;
2979 int nbytes, i;
2980 /* Windows mono bitmaps are reversed compared with X. */
2981 invertedBits = bits;
2982 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
2983 * img->height;
2984 bits = (char *) alloca (nbytes);
2985 for (i = 0; i < nbytes; i++)
2986 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
2988 #endif
2989 /* Create the pixmap. */
2991 Create_Pixmap_From_Bitmap_Data (f, img, bits,
2992 foreground, background,
2993 non_default_colors);
2994 if (img->pixmap)
2995 success_p = 1;
2996 else
2998 image_error ("Unable to create pixmap for XBM image `%s'",
2999 img->spec, Qnil);
3000 x_clear_image (f, img);
3005 return success_p;
3010 /***********************************************************************
3011 XPM images
3012 ***********************************************************************/
3014 #if defined (HAVE_XPM) || defined (HAVE_NS)
3016 static int xpm_image_p (Lisp_Object object);
3017 static int xpm_load (struct frame *f, struct image *img);
3018 static int xpm_valid_color_symbols_p (Lisp_Object);
3020 #endif /* HAVE_XPM || HAVE_NS */
3022 #ifdef HAVE_XPM
3023 #ifdef HAVE_NTGUI
3024 /* Indicate to xpm.h that we don't have Xlib. */
3025 #define FOR_MSW
3026 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3027 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3028 #define XColor xpm_XColor
3029 #define XImage xpm_XImage
3030 #define Display xpm_Display
3031 #define PIXEL_ALREADY_TYPEDEFED
3032 #include "X11/xpm.h"
3033 #undef FOR_MSW
3034 #undef XColor
3035 #undef XImage
3036 #undef Display
3037 #undef PIXEL_ALREADY_TYPEDEFED
3038 #else
3039 #include "X11/xpm.h"
3040 #endif /* HAVE_NTGUI */
3041 #endif /* HAVE_XPM */
3043 #if defined (HAVE_XPM) || defined (HAVE_NS)
3044 /* The symbol `xpm' identifying XPM-format images. */
3046 Lisp_Object Qxpm;
3048 /* Indices of image specification fields in xpm_format, below. */
3050 enum xpm_keyword_index
3052 XPM_TYPE,
3053 XPM_FILE,
3054 XPM_DATA,
3055 XPM_ASCENT,
3056 XPM_MARGIN,
3057 XPM_RELIEF,
3058 XPM_ALGORITHM,
3059 XPM_HEURISTIC_MASK,
3060 XPM_MASK,
3061 XPM_COLOR_SYMBOLS,
3062 XPM_BACKGROUND,
3063 XPM_LAST
3066 /* Vector of image_keyword structures describing the format
3067 of valid XPM image specifications. */
3069 static const struct image_keyword xpm_format[XPM_LAST] =
3071 {":type", IMAGE_SYMBOL_VALUE, 1},
3072 {":file", IMAGE_STRING_VALUE, 0},
3073 {":data", IMAGE_STRING_VALUE, 0},
3074 {":ascent", IMAGE_ASCENT_VALUE, 0},
3075 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3076 {":relief", IMAGE_INTEGER_VALUE, 0},
3077 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3078 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3079 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3080 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3081 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3084 /* Structure describing the image type XPM. */
3086 static struct image_type xpm_type =
3088 &Qxpm,
3089 xpm_image_p,
3090 xpm_load,
3091 x_clear_image,
3092 NULL
3095 #ifdef HAVE_X_WINDOWS
3097 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3098 functions for allocating image colors. Our own functions handle
3099 color allocation failures more gracefully than the ones on the XPM
3100 lib. */
3102 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3103 #define ALLOC_XPM_COLORS
3104 #endif
3105 #endif /* HAVE_X_WINDOWS */
3107 #ifdef ALLOC_XPM_COLORS
3109 static void xpm_init_color_cache (struct frame *, XpmAttributes *);
3110 static void xpm_free_color_cache (void);
3111 static int xpm_lookup_color (struct frame *, char *, XColor *);
3112 static int xpm_color_bucket (char *);
3113 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3114 XColor *, int);
3116 /* An entry in a hash table used to cache color definitions of named
3117 colors. This cache is necessary to speed up XPM image loading in
3118 case we do color allocations ourselves. Without it, we would need
3119 a call to XParseColor per pixel in the image. */
3121 struct xpm_cached_color
3123 /* Next in collision chain. */
3124 struct xpm_cached_color *next;
3126 /* Color definition (RGB and pixel color). */
3127 XColor color;
3129 /* Color name. */
3130 char name[1];
3133 /* The hash table used for the color cache, and its bucket vector
3134 size. */
3136 #define XPM_COLOR_CACHE_BUCKETS 1001
3137 struct xpm_cached_color **xpm_color_cache;
3139 /* Initialize the color cache. */
3141 static void
3142 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3144 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3145 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3146 memset (xpm_color_cache, 0, nbytes);
3147 init_color_table ();
3149 if (attrs->valuemask & XpmColorSymbols)
3151 int i;
3152 XColor color;
3154 for (i = 0; i < attrs->numsymbols; ++i)
3155 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3156 attrs->colorsymbols[i].value, &color))
3158 color.pixel = lookup_rgb_color (f, color.red, color.green,
3159 color.blue);
3160 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3165 /* Free the color cache. */
3167 static void
3168 xpm_free_color_cache (void)
3170 struct xpm_cached_color *p, *next;
3171 int i;
3173 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3174 for (p = xpm_color_cache[i]; p; p = next)
3176 next = p->next;
3177 xfree (p);
3180 xfree (xpm_color_cache);
3181 xpm_color_cache = NULL;
3182 free_color_table ();
3185 /* Return the bucket index for color named COLOR_NAME in the color
3186 cache. */
3188 static int
3189 xpm_color_bucket (char *color_name)
3191 unsigned h = 0;
3192 char *s;
3194 for (s = color_name; *s; ++s)
3195 h = (h << 2) ^ *s;
3196 return h %= XPM_COLOR_CACHE_BUCKETS;
3200 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3201 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3202 entry added. */
3204 static struct xpm_cached_color *
3205 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3207 size_t nbytes;
3208 struct xpm_cached_color *p;
3210 if (bucket < 0)
3211 bucket = xpm_color_bucket (color_name);
3213 nbytes = sizeof *p + strlen (color_name);
3214 p = (struct xpm_cached_color *) xmalloc (nbytes);
3215 strcpy (p->name, color_name);
3216 p->color = *color;
3217 p->next = xpm_color_cache[bucket];
3218 xpm_color_cache[bucket] = p;
3219 return p;
3222 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3223 return the cached definition in *COLOR. Otherwise, make a new
3224 entry in the cache and allocate the color. Value is zero if color
3225 allocation failed. */
3227 static int
3228 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3230 struct xpm_cached_color *p;
3231 int h = xpm_color_bucket (color_name);
3233 for (p = xpm_color_cache[h]; p; p = p->next)
3234 if (strcmp (p->name, color_name) == 0)
3235 break;
3237 if (p != NULL)
3238 *color = p->color;
3239 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3240 color_name, color))
3242 color->pixel = lookup_rgb_color (f, color->red, color->green,
3243 color->blue);
3244 p = xpm_cache_color (f, color_name, color, h);
3246 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3247 with transparency, and it's useful. */
3248 else if (strcmp ("opaque", color_name) == 0)
3250 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3251 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3252 p = xpm_cache_color (f, color_name, color, h);
3255 return p != NULL;
3259 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3260 CLOSURE is a pointer to the frame on which we allocate the
3261 color. Return in *COLOR the allocated color. Value is non-zero
3262 if successful. */
3264 static int
3265 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3266 void *closure)
3268 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3272 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3273 is a pointer to the frame on which we allocate the color. Value is
3274 non-zero if successful. */
3276 static int
3277 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3279 return 1;
3282 #endif /* ALLOC_XPM_COLORS */
3285 #ifdef HAVE_NTGUI
3287 /* XPM library details. */
3289 DEF_IMGLIB_FN (XpmFreeAttributes);
3290 DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
3291 DEF_IMGLIB_FN (XpmReadFileToImage);
3292 DEF_IMGLIB_FN (XImageFree);
3294 static int
3295 init_xpm_functions (Lisp_Object libraries)
3297 HMODULE library;
3299 if (!(library = w32_delayed_load (libraries, Qxpm)))
3300 return 0;
3302 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3303 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3304 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3305 LOAD_IMGLIB_FN (library, XImageFree);
3306 return 1;
3309 #endif /* HAVE_NTGUI */
3312 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3313 for XPM images. Such a list must consist of conses whose car and
3314 cdr are strings. */
3316 static int
3317 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3319 while (CONSP (color_symbols))
3321 Lisp_Object sym = XCAR (color_symbols);
3322 if (!CONSP (sym)
3323 || !STRINGP (XCAR (sym))
3324 || !STRINGP (XCDR (sym)))
3325 break;
3326 color_symbols = XCDR (color_symbols);
3329 return NILP (color_symbols);
3333 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3335 static int
3336 xpm_image_p (Lisp_Object object)
3338 struct image_keyword fmt[XPM_LAST];
3339 memcpy (fmt, xpm_format, sizeof fmt);
3340 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3341 /* Either `:file' or `:data' must be present. */
3342 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3343 /* Either no `:color-symbols' or it's a list of conses
3344 whose car and cdr are strings. */
3345 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3346 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3349 #endif /* HAVE_XPM || HAVE_NS */
3351 #if defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
3353 x_create_bitmap_from_xpm_data (struct frame *f, char **bits)
3355 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3356 int id, rc;
3357 XpmAttributes attrs;
3358 Pixmap bitmap, mask;
3360 memset (&attrs, 0, sizeof attrs);
3362 attrs.visual = FRAME_X_VISUAL (f);
3363 attrs.colormap = FRAME_X_COLORMAP (f);
3364 attrs.valuemask |= XpmVisual;
3365 attrs.valuemask |= XpmColormap;
3367 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3368 bits, &bitmap, &mask, &attrs);
3369 if (rc != XpmSuccess)
3371 XpmFreeAttributes (&attrs);
3372 return -1;
3375 id = x_allocate_bitmap_record (f);
3376 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3377 dpyinfo->bitmaps[id - 1].have_mask = 1;
3378 dpyinfo->bitmaps[id - 1].mask = mask;
3379 dpyinfo->bitmaps[id - 1].file = NULL;
3380 dpyinfo->bitmaps[id - 1].height = attrs.height;
3381 dpyinfo->bitmaps[id - 1].width = attrs.width;
3382 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3383 dpyinfo->bitmaps[id - 1].refcount = 1;
3385 XpmFreeAttributes (&attrs);
3386 return id;
3388 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3390 /* Load image IMG which will be displayed on frame F. Value is
3391 non-zero if successful. */
3393 #ifdef HAVE_XPM
3395 static int
3396 xpm_load (struct frame *f, struct image *img)
3398 int rc;
3399 XpmAttributes attrs;
3400 Lisp_Object specified_file, color_symbols;
3401 #ifdef HAVE_NTGUI
3402 HDC hdc;
3403 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3404 #endif /* HAVE_NTGUI */
3406 /* Configure the XPM lib. Use the visual of frame F. Allocate
3407 close colors. Return colors allocated. */
3408 memset (&attrs, 0, sizeof attrs);
3410 #ifndef HAVE_NTGUI
3411 attrs.visual = FRAME_X_VISUAL (f);
3412 attrs.colormap = FRAME_X_COLORMAP (f);
3413 attrs.valuemask |= XpmVisual;
3414 attrs.valuemask |= XpmColormap;
3415 #endif /* HAVE_NTGUI */
3417 #ifdef ALLOC_XPM_COLORS
3418 /* Allocate colors with our own functions which handle
3419 failing color allocation more gracefully. */
3420 attrs.color_closure = f;
3421 attrs.alloc_color = xpm_alloc_color;
3422 attrs.free_colors = xpm_free_colors;
3423 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3424 #else /* not ALLOC_XPM_COLORS */
3425 /* Let the XPM lib allocate colors. */
3426 attrs.valuemask |= XpmReturnAllocPixels;
3427 #ifdef XpmAllocCloseColors
3428 attrs.alloc_close_colors = 1;
3429 attrs.valuemask |= XpmAllocCloseColors;
3430 #else /* not XpmAllocCloseColors */
3431 attrs.closeness = 600;
3432 attrs.valuemask |= XpmCloseness;
3433 #endif /* not XpmAllocCloseColors */
3434 #endif /* ALLOC_XPM_COLORS */
3436 /* If image specification contains symbolic color definitions, add
3437 these to `attrs'. */
3438 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3439 if (CONSP (color_symbols))
3441 Lisp_Object tail;
3442 XpmColorSymbol *xpm_syms;
3443 int i, size;
3445 attrs.valuemask |= XpmColorSymbols;
3447 /* Count number of symbols. */
3448 attrs.numsymbols = 0;
3449 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3450 ++attrs.numsymbols;
3452 /* Allocate an XpmColorSymbol array. */
3453 size = attrs.numsymbols * sizeof *xpm_syms;
3454 xpm_syms = (XpmColorSymbol *) alloca (size);
3455 memset (xpm_syms, 0, size);
3456 attrs.colorsymbols = xpm_syms;
3458 /* Fill the color symbol array. */
3459 for (tail = color_symbols, i = 0;
3460 CONSP (tail);
3461 ++i, tail = XCDR (tail))
3463 Lisp_Object name = XCAR (XCAR (tail));
3464 Lisp_Object color = XCDR (XCAR (tail));
3465 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3466 strcpy (xpm_syms[i].name, SDATA (name));
3467 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3468 strcpy (xpm_syms[i].value, SDATA (color));
3472 /* Create a pixmap for the image, either from a file, or from a
3473 string buffer containing data in the same format as an XPM file. */
3474 #ifdef ALLOC_XPM_COLORS
3475 xpm_init_color_cache (f, &attrs);
3476 #endif
3478 specified_file = image_spec_value (img->spec, QCfile, NULL);
3480 #ifdef HAVE_NTGUI
3482 HDC frame_dc = get_frame_dc (f);
3483 hdc = CreateCompatibleDC (frame_dc);
3484 release_frame_dc (f, frame_dc);
3486 #endif /* HAVE_NTGUI */
3488 if (STRINGP (specified_file))
3490 Lisp_Object file = x_find_image_file (specified_file);
3491 if (!STRINGP (file))
3493 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3494 return 0;
3497 #ifdef HAVE_NTGUI
3498 /* XpmReadFileToPixmap is not available in the Windows port of
3499 libxpm. But XpmReadFileToImage almost does what we want. */
3500 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3501 &xpm_image, &xpm_mask,
3502 &attrs);
3503 #else
3504 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3505 SDATA (file), &img->pixmap, &img->mask,
3506 &attrs);
3507 #endif /* HAVE_NTGUI */
3509 else
3511 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
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 SDATA (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->ncolors = attrs.nalloc_pixels;
3564 img->colors = (unsigned long *) xmalloc (img->ncolors
3565 * sizeof *img->colors);
3566 for (i = 0; i < attrs.nalloc_pixels; ++i)
3568 img->colors[i] = attrs.alloc_pixels[i];
3569 #ifdef DEBUG_X_COLORS
3570 register_color (img->colors[i]);
3571 #endif
3573 #endif /* not ALLOC_XPM_COLORS */
3575 img->width = attrs.width;
3576 img->height = attrs.height;
3577 xassert (img->width > 0 && img->height > 0);
3579 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3580 #ifdef HAVE_NTGUI
3581 fn_XpmFreeAttributes (&attrs);
3582 #else
3583 XpmFreeAttributes (&attrs);
3584 #endif /* HAVE_NTGUI */
3586 else
3588 #ifdef HAVE_NTGUI
3589 DeleteDC (hdc);
3590 #endif /* HAVE_NTGUI */
3592 switch (rc)
3594 case XpmOpenFailed:
3595 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3596 break;
3598 case XpmFileInvalid:
3599 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3600 break;
3602 case XpmNoMemory:
3603 image_error ("Out of memory (%s)", img->spec, Qnil);
3604 break;
3606 case XpmColorFailed:
3607 image_error ("Color allocation error (%s)", img->spec, Qnil);
3608 break;
3610 default:
3611 image_error ("Unknown error (%s)", img->spec, Qnil);
3612 break;
3616 #ifdef ALLOC_XPM_COLORS
3617 xpm_free_color_cache ();
3618 #endif
3619 return rc == XpmSuccess;
3622 #endif /* HAVE_XPM */
3624 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3626 /* XPM support functions for NS where libxpm is not available.
3627 Only XPM version 3 (without any extensions) is supported. */
3629 static int xpm_scan (const unsigned char **, const unsigned char *,
3630 const unsigned char **, int *);
3631 static Lisp_Object xpm_make_color_table_v
3632 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3633 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3634 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3635 int, Lisp_Object);
3636 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3637 const unsigned char *, int);
3638 static Lisp_Object xpm_make_color_table_h
3639 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3640 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3641 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3642 int, Lisp_Object);
3643 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3644 const unsigned char *, int);
3645 static int xpm_str_to_color_key (const char *);
3646 static int xpm_load_image (struct frame *, struct image *,
3647 const unsigned char *, const unsigned char *);
3649 /* Tokens returned from xpm_scan. */
3651 enum xpm_token
3653 XPM_TK_IDENT = 256,
3654 XPM_TK_STRING,
3655 XPM_TK_EOF
3658 /* Scan an XPM data and return a character (< 256) or a token defined
3659 by enum xpm_token above. *S and END are the start (inclusive) and
3660 the end (exclusive) addresses of the data, respectively. Advance
3661 *S while scanning. If token is either XPM_TK_IDENT or
3662 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3663 length of the corresponding token, respectively. */
3665 static int
3666 xpm_scan (s, end, beg, len)
3667 const unsigned char **s, *end, **beg;
3668 int *len;
3670 int c;
3672 while (*s < end)
3674 /* Skip white-space. */
3675 while (*s < end && (c = *(*s)++, isspace (c)))
3678 /* gnus-pointer.xpm uses '-' in its identifier.
3679 sb-dir-plus.xpm uses '+' in its identifier. */
3680 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3682 *beg = *s - 1;
3683 while (*s < end
3684 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3685 ++*s;
3686 *len = *s - *beg;
3687 return XPM_TK_IDENT;
3689 else if (c == '"')
3691 *beg = *s;
3692 while (*s < end && **s != '"')
3693 ++*s;
3694 *len = *s - *beg;
3695 if (*s < end)
3696 ++*s;
3697 return XPM_TK_STRING;
3699 else if (c == '/')
3701 if (*s < end && **s == '*')
3703 /* C-style comment. */
3704 ++*s;
3707 while (*s < end && *(*s)++ != '*')
3710 while (*s < end && **s != '/');
3711 if (*s < end)
3712 ++*s;
3714 else
3715 return c;
3717 else
3718 return c;
3721 return XPM_TK_EOF;
3724 /* Functions for color table lookup in XPM data. A key is a string
3725 specifying the color of each pixel in XPM data. A value is either
3726 an integer that specifies a pixel color, Qt that specifies
3727 transparency, or Qnil for the unspecified color. If the length of
3728 the key string is one, a vector is used as a table. Otherwise, a
3729 hash table is used. */
3731 static Lisp_Object
3732 xpm_make_color_table_v (put_func, get_func)
3733 void (**put_func) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3734 Lisp_Object (**get_func) (Lisp_Object, const unsigned char *, int);
3736 *put_func = xpm_put_color_table_v;
3737 *get_func = xpm_get_color_table_v;
3738 return Fmake_vector (make_number (256), Qnil);
3741 static void
3742 xpm_put_color_table_v (color_table, chars_start, chars_len, color)
3743 Lisp_Object color_table;
3744 const unsigned char *chars_start;
3745 int chars_len;
3746 Lisp_Object color;
3748 XVECTOR (color_table)->contents[*chars_start] = color;
3751 static Lisp_Object
3752 xpm_get_color_table_v (color_table, chars_start, chars_len)
3753 Lisp_Object color_table;
3754 const unsigned char *chars_start;
3755 int chars_len;
3757 return XVECTOR (color_table)->contents[*chars_start];
3760 static Lisp_Object
3761 xpm_make_color_table_h (put_func, get_func)
3762 void (**put_func) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3763 Lisp_Object (**get_func) (Lisp_Object, const unsigned char *, int);
3765 *put_func = xpm_put_color_table_h;
3766 *get_func = xpm_get_color_table_h;
3767 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
3768 make_float (DEFAULT_REHASH_SIZE),
3769 make_float (DEFAULT_REHASH_THRESHOLD),
3770 Qnil, Qnil, Qnil);
3773 static void
3774 xpm_put_color_table_h (color_table, chars_start, chars_len, color)
3775 Lisp_Object color_table;
3776 const unsigned char *chars_start;
3777 int chars_len;
3778 Lisp_Object color;
3780 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3781 unsigned hash_code;
3782 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3784 hash_lookup (table, chars, &hash_code);
3785 hash_put (table, chars, color, hash_code);
3788 static Lisp_Object
3789 xpm_get_color_table_h (color_table, chars_start, chars_len)
3790 Lisp_Object color_table;
3791 const unsigned char *chars_start;
3792 int chars_len;
3794 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3795 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
3796 NULL);
3798 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3801 enum xpm_color_key {
3802 XPM_COLOR_KEY_S,
3803 XPM_COLOR_KEY_M,
3804 XPM_COLOR_KEY_G4,
3805 XPM_COLOR_KEY_G,
3806 XPM_COLOR_KEY_C
3809 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3811 static int
3812 xpm_str_to_color_key (s)
3813 const char *s;
3815 int i;
3817 for (i = 0;
3818 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3819 i++)
3820 if (strcmp (xpm_color_key_strings[i], s) == 0)
3821 return i;
3822 return -1;
3825 static int
3826 xpm_load_image (f, img, contents, end)
3827 struct frame *f;
3828 struct image *img;
3829 const unsigned char *contents, *end;
3831 const unsigned char *s = contents, *beg, *str;
3832 unsigned char buffer[BUFSIZ];
3833 int width, height, x, y;
3834 int num_colors, chars_per_pixel;
3835 int len, LA1;
3836 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3837 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3838 Lisp_Object frame, color_symbols, color_table;
3839 int best_key, have_mask = 0;
3840 XImagePtr ximg = NULL, mask_img = NULL;
3842 #define match() \
3843 LA1 = xpm_scan (&s, end, &beg, &len)
3845 #define expect(TOKEN) \
3846 if (LA1 != (TOKEN)) \
3847 goto failure; \
3848 else \
3849 match ()
3851 #define expect_ident(IDENT) \
3852 if (LA1 == XPM_TK_IDENT \
3853 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3854 match (); \
3855 else \
3856 goto failure
3858 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3859 goto failure;
3860 s += 9;
3861 match ();
3862 expect_ident ("static");
3863 expect_ident ("char");
3864 expect ('*');
3865 expect (XPM_TK_IDENT);
3866 expect ('[');
3867 expect (']');
3868 expect ('=');
3869 expect ('{');
3870 expect (XPM_TK_STRING);
3871 if (len >= BUFSIZ)
3872 goto failure;
3873 memcpy (buffer, beg, len);
3874 buffer[len] = '\0';
3875 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3876 &num_colors, &chars_per_pixel) != 4
3877 || width <= 0 || height <= 0
3878 || num_colors <= 0 || chars_per_pixel <= 0)
3879 goto failure;
3881 if (!check_image_size (f, width, height))
3883 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
3884 goto failure;
3887 expect (',');
3889 XSETFRAME (frame, f);
3890 if (!NILP (Fxw_display_color_p (frame)))
3891 best_key = XPM_COLOR_KEY_C;
3892 else if (!NILP (Fx_display_grayscale_p (frame)))
3893 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
3894 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
3895 else
3896 best_key = XPM_COLOR_KEY_M;
3898 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3899 if (chars_per_pixel == 1)
3900 color_table = xpm_make_color_table_v (&put_color_table,
3901 &get_color_table);
3902 else
3903 color_table = xpm_make_color_table_h (&put_color_table,
3904 &get_color_table);
3906 while (num_colors-- > 0)
3908 unsigned char *color, *max_color;
3909 int key, next_key, max_key = 0;
3910 Lisp_Object symbol_color = Qnil, color_val;
3911 XColor cdef;
3913 expect (XPM_TK_STRING);
3914 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
3915 goto failure;
3916 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
3917 buffer[len - chars_per_pixel] = '\0';
3919 str = strtok (buffer, " \t");
3920 if (str == NULL)
3921 goto failure;
3922 key = xpm_str_to_color_key (str);
3923 if (key < 0)
3924 goto failure;
3927 color = strtok (NULL, " \t");
3928 if (color == NULL)
3929 goto failure;
3931 while ((str = strtok (NULL, " \t")) != NULL)
3933 next_key = xpm_str_to_color_key (str);
3934 if (next_key >= 0)
3935 break;
3936 color[strlen (color)] = ' ';
3939 if (key == XPM_COLOR_KEY_S)
3941 if (NILP (symbol_color))
3942 symbol_color = build_string (color);
3944 else if (max_key < key && key <= best_key)
3946 max_key = key;
3947 max_color = color;
3949 key = next_key;
3951 while (str);
3953 color_val = Qnil;
3954 if (!NILP (color_symbols) && !NILP (symbol_color))
3956 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
3958 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
3960 if (xstrcasecmp (SDATA (XCDR (specified_color)), "None") == 0)
3961 color_val = Qt;
3962 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
3963 &cdef, 0))
3964 color_val = make_number (cdef.pixel);
3967 if (NILP (color_val) && max_key > 0)
3969 if (xstrcasecmp (max_color, "None") == 0)
3970 color_val = Qt;
3971 else if (x_defined_color (f, max_color, &cdef, 0))
3972 color_val = make_number (cdef.pixel);
3974 if (!NILP (color_val))
3975 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
3977 expect (',');
3980 if (!x_create_x_image_and_pixmap (f, width, height, 0,
3981 &ximg, &img->pixmap)
3982 #ifndef HAVE_NS
3983 || !x_create_x_image_and_pixmap (f, width, height, 1,
3984 &mask_img, &img->mask)
3985 #endif
3988 image_error ("Out of memory (%s)", img->spec, Qnil);
3989 goto error;
3992 for (y = 0; y < height; y++)
3994 expect (XPM_TK_STRING);
3995 str = beg;
3996 if (len < width * chars_per_pixel)
3997 goto failure;
3998 for (x = 0; x < width; x++, str += chars_per_pixel)
4000 Lisp_Object color_val =
4001 (*get_color_table) (color_table, str, chars_per_pixel);
4003 XPutPixel (ximg, x, y,
4004 (INTEGERP (color_val) ? XINT (color_val)
4005 : FRAME_FOREGROUND_PIXEL (f)));
4006 #ifndef HAVE_NS
4007 XPutPixel (mask_img, x, y,
4008 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4009 : (have_mask = 1, PIX_MASK_RETAIN)));
4010 #else
4011 if (EQ (color_val, Qt))
4012 ns_set_alpha (ximg, x, y, 0);
4013 #endif
4015 if (y + 1 < height)
4016 expect (',');
4019 img->width = width;
4020 img->height = height;
4022 /* Maybe fill in the background field while we have ximg handy. */
4023 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4024 IMAGE_BACKGROUND (img, f, ximg);
4026 x_put_x_image (f, ximg, img->pixmap, width, height);
4027 x_destroy_x_image (ximg);
4028 #ifndef HAVE_NS
4029 if (have_mask)
4031 /* Fill in the background_transparent field while we have the
4032 mask handy. */
4033 image_background_transparent (img, f, mask_img);
4035 x_put_x_image (f, mask_img, img->mask, width, height);
4036 x_destroy_x_image (mask_img);
4038 else
4040 x_destroy_x_image (mask_img);
4041 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4042 img->mask = NO_PIXMAP;
4044 #endif
4045 return 1;
4047 failure:
4048 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4049 error:
4050 x_destroy_x_image (ximg);
4051 x_destroy_x_image (mask_img);
4052 x_clear_image (f, img);
4053 return 0;
4055 #undef match
4056 #undef expect
4057 #undef expect_ident
4060 static int
4061 xpm_load (f, img)
4062 struct frame *f;
4063 struct image *img;
4065 int success_p = 0;
4066 Lisp_Object file_name;
4068 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4069 file_name = image_spec_value (img->spec, QCfile, NULL);
4070 if (STRINGP (file_name))
4072 Lisp_Object file;
4073 unsigned char *contents;
4074 int size;
4075 struct gcpro gcpro1;
4077 file = x_find_image_file (file_name);
4078 GCPRO1 (file);
4079 if (!STRINGP (file))
4081 image_error ("Cannot find image file `%s'", file_name, Qnil);
4082 UNGCPRO;
4083 return 0;
4086 contents = slurp_file (SDATA (file), &size);
4087 if (contents == NULL)
4089 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4090 UNGCPRO;
4091 return 0;
4094 success_p = xpm_load_image (f, img, contents, contents + size);
4095 xfree (contents);
4096 UNGCPRO;
4098 else
4100 Lisp_Object data;
4102 data = image_spec_value (img->spec, QCdata, NULL);
4103 success_p = xpm_load_image (f, img, SDATA (data),
4104 SDATA (data) + SBYTES (data));
4107 return success_p;
4110 #endif /* HAVE_NS && !HAVE_XPM */
4114 /***********************************************************************
4115 Color table
4116 ***********************************************************************/
4118 #ifdef COLOR_TABLE_SUPPORT
4120 /* An entry in the color table mapping an RGB color to a pixel color. */
4122 struct ct_color
4124 int r, g, b;
4125 unsigned long pixel;
4127 /* Next in color table collision list. */
4128 struct ct_color *next;
4131 /* The bucket vector size to use. Must be prime. */
4133 #define CT_SIZE 101
4135 /* Value is a hash of the RGB color given by R, G, and B. */
4137 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4139 /* The color hash table. */
4141 struct ct_color **ct_table;
4143 /* Number of entries in the color table. */
4145 int ct_colors_allocated;
4147 /* Initialize the color table. */
4149 static void
4150 init_color_table (void)
4152 int size = CT_SIZE * sizeof (*ct_table);
4153 ct_table = (struct ct_color **) xmalloc (size);
4154 memset (ct_table, 0, size);
4155 ct_colors_allocated = 0;
4159 /* Free memory associated with the color table. */
4161 static void
4162 free_color_table (void)
4164 int i;
4165 struct ct_color *p, *next;
4167 for (i = 0; i < CT_SIZE; ++i)
4168 for (p = ct_table[i]; p; p = next)
4170 next = p->next;
4171 xfree (p);
4174 xfree (ct_table);
4175 ct_table = NULL;
4179 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4180 entry for that color already is in the color table, return the
4181 pixel color of that entry. Otherwise, allocate a new color for R,
4182 G, B, and make an entry in the color table. */
4184 static unsigned long
4185 lookup_rgb_color (struct frame *f, int r, int g, int b)
4187 unsigned hash = CT_HASH_RGB (r, g, b);
4188 int i = hash % CT_SIZE;
4189 struct ct_color *p;
4190 Display_Info *dpyinfo;
4192 /* Handle TrueColor visuals specially, which improves performance by
4193 two orders of magnitude. Freeing colors on TrueColor visuals is
4194 a nop, and pixel colors specify RGB values directly. See also
4195 the Xlib spec, chapter 3.1. */
4196 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4197 if (dpyinfo->red_bits > 0)
4199 unsigned long pr, pg, pb;
4201 /* Apply gamma-correction like normal color allocation does. */
4202 if (f->gamma)
4204 XColor color;
4205 color.red = r, color.green = g, color.blue = b;
4206 gamma_correct (f, &color);
4207 r = color.red, g = color.green, b = color.blue;
4210 /* Scale down RGB values to the visual's bits per RGB, and shift
4211 them to the right position in the pixel color. Note that the
4212 original RGB values are 16-bit values, as usual in X. */
4213 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4214 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4215 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4217 /* Assemble the pixel color. */
4218 return pr | pg | pb;
4221 for (p = ct_table[i]; p; p = p->next)
4222 if (p->r == r && p->g == g && p->b == b)
4223 break;
4225 if (p == NULL)
4228 #ifdef HAVE_X_WINDOWS
4229 XColor color;
4230 Colormap cmap;
4231 int rc;
4233 color.red = r;
4234 color.green = g;
4235 color.blue = b;
4237 cmap = FRAME_X_COLORMAP (f);
4238 rc = x_alloc_nearest_color (f, cmap, &color);
4239 if (rc)
4241 ++ct_colors_allocated;
4242 p = (struct ct_color *) xmalloc (sizeof *p);
4243 p->r = r;
4244 p->g = g;
4245 p->b = b;
4246 p->pixel = color.pixel;
4247 p->next = ct_table[i];
4248 ct_table[i] = p;
4250 else
4251 return FRAME_FOREGROUND_PIXEL (f);
4253 #else
4254 COLORREF color;
4255 #ifdef HAVE_NTGUI
4256 color = PALETTERGB (r, g, b);
4257 #else
4258 color = RGB_TO_ULONG (r, g, b);
4259 #endif /* HAVE_NTGUI */
4260 ++ct_colors_allocated;
4261 p = (struct ct_color *) xmalloc (sizeof *p);
4262 p->r = r;
4263 p->g = g;
4264 p->b = b;
4265 p->pixel = color;
4266 p->next = ct_table[i];
4267 ct_table[i] = p;
4268 #endif /* HAVE_X_WINDOWS */
4272 return p->pixel;
4276 /* Look up pixel color PIXEL which is used on frame F in the color
4277 table. If not already present, allocate it. Value is PIXEL. */
4279 static unsigned long
4280 lookup_pixel_color (struct frame *f, unsigned long pixel)
4282 int i = pixel % CT_SIZE;
4283 struct ct_color *p;
4285 for (p = ct_table[i]; p; p = p->next)
4286 if (p->pixel == pixel)
4287 break;
4289 if (p == NULL)
4291 XColor color;
4292 Colormap cmap;
4293 int rc;
4295 #ifdef HAVE_X_WINDOWS
4296 cmap = FRAME_X_COLORMAP (f);
4297 color.pixel = pixel;
4298 x_query_color (f, &color);
4299 rc = x_alloc_nearest_color (f, cmap, &color);
4300 #else
4301 BLOCK_INPUT;
4302 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4303 color.pixel = pixel;
4304 XQueryColor (NULL, cmap, &color);
4305 rc = x_alloc_nearest_color (f, cmap, &color);
4306 UNBLOCK_INPUT;
4307 #endif /* HAVE_X_WINDOWS */
4309 if (rc)
4311 ++ct_colors_allocated;
4313 p = (struct ct_color *) xmalloc (sizeof *p);
4314 p->r = color.red;
4315 p->g = color.green;
4316 p->b = color.blue;
4317 p->pixel = pixel;
4318 p->next = ct_table[i];
4319 ct_table[i] = p;
4321 else
4322 return FRAME_FOREGROUND_PIXEL (f);
4324 return p->pixel;
4328 /* Value is a vector of all pixel colors contained in the color table,
4329 allocated via xmalloc. Set *N to the number of colors. */
4331 static unsigned long *
4332 colors_in_color_table (int *n)
4334 int i, j;
4335 struct ct_color *p;
4336 unsigned long *colors;
4338 if (ct_colors_allocated == 0)
4340 *n = 0;
4341 colors = NULL;
4343 else
4345 colors = (unsigned long *) xmalloc (ct_colors_allocated
4346 * sizeof *colors);
4347 *n = ct_colors_allocated;
4349 for (i = j = 0; i < CT_SIZE; ++i)
4350 for (p = ct_table[i]; p; p = p->next)
4351 colors[j++] = p->pixel;
4354 return colors;
4357 #else /* COLOR_TABLE_SUPPORT */
4359 static unsigned long
4360 lookup_rgb_color (f, r, g, b)
4361 struct frame *f;
4362 int r, g, b;
4364 unsigned long pixel;
4366 #ifdef HAVE_NTGUI
4367 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4368 #endif /* HAVE_NTGUI */
4370 #ifdef HAVE_NS
4371 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4372 #endif /* HAVE_NS */
4373 return pixel;
4376 static void
4377 init_color_table ()
4380 #endif /* COLOR_TABLE_SUPPORT */
4383 /***********************************************************************
4384 Algorithms
4385 ***********************************************************************/
4387 static XColor *x_to_xcolors (struct frame *, struct image *, int);
4388 static void x_from_xcolors (struct frame *, struct image *, XColor *);
4389 static void x_detect_edges (struct frame *, struct image *, int[9], int);
4391 #ifdef HAVE_NTGUI
4392 static void XPutPixel (XImagePtr , int, int, COLORREF);
4393 #endif /* HAVE_NTGUI */
4395 /* Non-zero means draw a cross on images having `:conversion
4396 disabled'. */
4398 int cross_disabled_images;
4400 /* Edge detection matrices for different edge-detection
4401 strategies. */
4403 static int emboss_matrix[9] = {
4404 /* x - 1 x x + 1 */
4405 2, -1, 0, /* y - 1 */
4406 -1, 0, 1, /* y */
4407 0, 1, -2 /* y + 1 */
4410 static int laplace_matrix[9] = {
4411 /* x - 1 x x + 1 */
4412 1, 0, 0, /* y - 1 */
4413 0, 0, 0, /* y */
4414 0, 0, -1 /* y + 1 */
4417 /* Value is the intensity of the color whose red/green/blue values
4418 are R, G, and B. */
4420 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4423 /* On frame F, return an array of XColor structures describing image
4424 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4425 non-zero means also fill the red/green/blue members of the XColor
4426 structures. Value is a pointer to the array of XColors structures,
4427 allocated with xmalloc; it must be freed by the caller. */
4429 static XColor *
4430 x_to_xcolors (struct frame *f, struct image *img, int rgb_p)
4432 int x, y;
4433 XColor *colors, *p;
4434 XImagePtr_or_DC ximg;
4435 #ifdef HAVE_NTGUI
4436 HDC hdc;
4437 HGDIOBJ prev;
4438 #endif /* HAVE_NTGUI */
4440 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4442 #ifndef HAVE_NTGUI
4443 /* Get the X image IMG->pixmap. */
4444 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4445 0, 0, img->width, img->height, ~0, ZPixmap);
4446 #else
4447 /* Load the image into a memory device context. */
4448 hdc = get_frame_dc (f);
4449 ximg = CreateCompatibleDC (hdc);
4450 release_frame_dc (f, hdc);
4451 prev = SelectObject (ximg, img->pixmap);
4452 #endif /* HAVE_NTGUI */
4454 /* Fill the `pixel' members of the XColor array. I wished there
4455 were an easy and portable way to circumvent XGetPixel. */
4456 p = colors;
4457 for (y = 0; y < img->height; ++y)
4459 XColor *row = p;
4461 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4462 for (x = 0; x < img->width; ++x, ++p)
4463 p->pixel = GET_PIXEL (ximg, x, y);
4464 if (rgb_p)
4465 x_query_colors (f, row, img->width);
4467 #else
4469 for (x = 0; x < img->width; ++x, ++p)
4471 /* W32_TODO: palette support needed here? */
4472 p->pixel = GET_PIXEL (ximg, x, y);
4473 if (rgb_p)
4475 p->red = RED16_FROM_ULONG (p->pixel);
4476 p->green = GREEN16_FROM_ULONG (p->pixel);
4477 p->blue = BLUE16_FROM_ULONG (p->pixel);
4480 #endif /* HAVE_X_WINDOWS */
4483 Destroy_Image (ximg, prev);
4485 return colors;
4488 #ifdef HAVE_NTGUI
4490 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4491 created with CreateDIBSection, with the pointer to the bit values
4492 stored in ximg->data. */
4494 static void
4495 XPutPixel (ximg, x, y, color)
4496 XImagePtr ximg;
4497 int x, y;
4498 COLORREF color;
4500 int width = ximg->info.bmiHeader.biWidth;
4501 int height = ximg->info.bmiHeader.biHeight;
4502 unsigned char * pixel;
4504 /* True color images. */
4505 if (ximg->info.bmiHeader.biBitCount == 24)
4507 int rowbytes = width * 3;
4508 /* Ensure scanlines are aligned on 4 byte boundaries. */
4509 if (rowbytes % 4)
4510 rowbytes += 4 - (rowbytes % 4);
4512 pixel = ximg->data + y * rowbytes + x * 3;
4513 /* Windows bitmaps are in BGR order. */
4514 *pixel = GetBValue (color);
4515 *(pixel + 1) = GetGValue (color);
4516 *(pixel + 2) = GetRValue (color);
4518 /* Monochrome images. */
4519 else if (ximg->info.bmiHeader.biBitCount == 1)
4521 int rowbytes = width / 8;
4522 /* Ensure scanlines are aligned on 4 byte boundaries. */
4523 if (rowbytes % 4)
4524 rowbytes += 4 - (rowbytes % 4);
4525 pixel = ximg->data + y * rowbytes + x / 8;
4526 /* Filter out palette info. */
4527 if (color & 0x00ffffff)
4528 *pixel = *pixel | (1 << x % 8);
4529 else
4530 *pixel = *pixel & ~(1 << x % 8);
4532 else
4533 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4536 #endif /* HAVE_NTGUI */
4538 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4539 RGB members are set. F is the frame on which this all happens.
4540 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4542 static void
4543 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4545 int x, y;
4546 XImagePtr oimg = NULL;
4547 Pixmap pixmap;
4548 XColor *p;
4550 init_color_table ();
4552 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4553 &oimg, &pixmap);
4554 p = colors;
4555 for (y = 0; y < img->height; ++y)
4556 for (x = 0; x < img->width; ++x, ++p)
4558 unsigned long pixel;
4559 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4560 XPutPixel (oimg, x, y, pixel);
4563 xfree (colors);
4564 x_clear_image_1 (f, img, 1, 0, 1);
4566 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4567 x_destroy_x_image (oimg);
4568 img->pixmap = pixmap;
4569 #ifdef COLOR_TABLE_SUPPORT
4570 img->colors = colors_in_color_table (&img->ncolors);
4571 free_color_table ();
4572 #endif /* COLOR_TABLE_SUPPORT */
4576 /* On frame F, perform edge-detection on image IMG.
4578 MATRIX is a nine-element array specifying the transformation
4579 matrix. See emboss_matrix for an example.
4581 COLOR_ADJUST is a color adjustment added to each pixel of the
4582 outgoing image. */
4584 static void
4585 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4587 XColor *colors = x_to_xcolors (f, img, 1);
4588 XColor *new, *p;
4589 int x, y, i, sum;
4591 for (i = sum = 0; i < 9; ++i)
4592 sum += eabs (matrix[i]);
4594 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4596 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4598 for (y = 0; y < img->height; ++y)
4600 p = COLOR (new, 0, y);
4601 p->red = p->green = p->blue = 0xffff/2;
4602 p = COLOR (new, img->width - 1, y);
4603 p->red = p->green = p->blue = 0xffff/2;
4606 for (x = 1; x < img->width - 1; ++x)
4608 p = COLOR (new, x, 0);
4609 p->red = p->green = p->blue = 0xffff/2;
4610 p = COLOR (new, x, img->height - 1);
4611 p->red = p->green = p->blue = 0xffff/2;
4614 for (y = 1; y < img->height - 1; ++y)
4616 p = COLOR (new, 1, y);
4618 for (x = 1; x < img->width - 1; ++x, ++p)
4620 int r, g, b, y1, x1;
4622 r = g = b = i = 0;
4623 for (y1 = y - 1; y1 < y + 2; ++y1)
4624 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
4625 if (matrix[i])
4627 XColor *t = COLOR (colors, x1, y1);
4628 r += matrix[i] * t->red;
4629 g += matrix[i] * t->green;
4630 b += matrix[i] * t->blue;
4633 r = (r / sum + color_adjust) & 0xffff;
4634 g = (g / sum + color_adjust) & 0xffff;
4635 b = (b / sum + color_adjust) & 0xffff;
4636 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4640 xfree (colors);
4641 x_from_xcolors (f, img, new);
4643 #undef COLOR
4647 /* Perform the pre-defined `emboss' edge-detection on image IMG
4648 on frame F. */
4650 static void
4651 x_emboss (struct frame *f, struct image *img)
4653 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4657 /* Transform image IMG which is used on frame F with a Laplace
4658 edge-detection algorithm. The result is an image that can be used
4659 to draw disabled buttons, for example. */
4661 static void
4662 x_laplace (struct frame *f, struct image *img)
4664 x_detect_edges (f, img, laplace_matrix, 45000);
4668 /* Perform edge-detection on image IMG on frame F, with specified
4669 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4671 MATRIX must be either
4673 - a list of at least 9 numbers in row-major form
4674 - a vector of at least 9 numbers
4676 COLOR_ADJUST nil means use a default; otherwise it must be a
4677 number. */
4679 static void
4680 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4681 Lisp_Object color_adjust)
4683 int i = 0;
4684 int trans[9];
4686 if (CONSP (matrix))
4688 for (i = 0;
4689 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4690 ++i, matrix = XCDR (matrix))
4691 trans[i] = XFLOATINT (XCAR (matrix));
4693 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4695 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4696 trans[i] = XFLOATINT (AREF (matrix, i));
4699 if (NILP (color_adjust))
4700 color_adjust = make_number (0xffff / 2);
4702 if (i == 9 && NUMBERP (color_adjust))
4703 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
4707 /* Transform image IMG on frame F so that it looks disabled. */
4709 static void
4710 x_disable_image (struct frame *f, struct image *img)
4712 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4713 #ifdef HAVE_NTGUI
4714 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4715 #else
4716 int n_planes = dpyinfo->n_planes;
4717 #endif /* HAVE_NTGUI */
4719 if (n_planes >= 2)
4721 /* Color (or grayscale). Convert to gray, and equalize. Just
4722 drawing such images with a stipple can look very odd, so
4723 we're using this method instead. */
4724 XColor *colors = x_to_xcolors (f, img, 1);
4725 XColor *p, *end;
4726 const int h = 15000;
4727 const int l = 30000;
4729 for (p = colors, end = colors + img->width * img->height;
4730 p < end;
4731 ++p)
4733 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4734 int i2 = (0xffff - h - l) * i / 0xffff + l;
4735 p->red = p->green = p->blue = i2;
4738 x_from_xcolors (f, img, colors);
4741 /* Draw a cross over the disabled image, if we must or if we
4742 should. */
4743 if (n_planes < 2 || cross_disabled_images)
4745 #ifndef HAVE_NTGUI
4746 Display *dpy = FRAME_X_DISPLAY (f);
4747 GC gc;
4749 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4751 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4753 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4754 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4755 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4756 img->width - 1, img->height - 1);
4757 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4758 img->width - 1, 0);
4759 XFreeGC (dpy, gc);
4761 if (img->mask)
4763 gc = XCreateGC (dpy, img->mask, 0, NULL);
4764 XSetForeground (dpy, gc, MaskForeground (f));
4765 XDrawLine (dpy, img->mask, gc, 0, 0,
4766 img->width - 1, img->height - 1);
4767 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4768 img->width - 1, 0);
4769 XFreeGC (dpy, gc);
4771 #endif /* !HAVE_NS */
4772 #else
4773 HDC hdc, bmpdc;
4774 HGDIOBJ prev;
4776 hdc = get_frame_dc (f);
4777 bmpdc = CreateCompatibleDC (hdc);
4778 release_frame_dc (f, hdc);
4780 prev = SelectObject (bmpdc, img->pixmap);
4782 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4783 MoveToEx (bmpdc, 0, 0, NULL);
4784 LineTo (bmpdc, img->width - 1, img->height - 1);
4785 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4786 LineTo (bmpdc, img->width - 1, 0);
4788 if (img->mask)
4790 SelectObject (bmpdc, img->mask);
4791 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4792 MoveToEx (bmpdc, 0, 0, NULL);
4793 LineTo (bmpdc, img->width - 1, img->height - 1);
4794 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4795 LineTo (bmpdc, img->width - 1, 0);
4797 SelectObject (bmpdc, prev);
4798 DeleteDC (bmpdc);
4799 #endif /* HAVE_NTGUI */
4804 /* Build a mask for image IMG which is used on frame F. FILE is the
4805 name of an image file, for error messages. HOW determines how to
4806 determine the background color of IMG. If it is a list '(R G B)',
4807 with R, G, and B being integers >= 0, take that as the color of the
4808 background. Otherwise, determine the background color of IMG
4809 heuristically. Value is non-zero if successful. */
4811 static int
4812 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4814 XImagePtr_or_DC ximg;
4815 #ifndef HAVE_NTGUI
4816 XImagePtr mask_img;
4817 #else
4818 HDC frame_dc;
4819 HGDIOBJ prev;
4820 char *mask_img;
4821 int row_width;
4822 #endif /* HAVE_NTGUI */
4823 int x, y, rc, use_img_background;
4824 unsigned long bg = 0;
4826 if (img->mask)
4828 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4829 img->mask = NO_PIXMAP;
4830 img->background_transparent_valid = 0;
4833 #ifndef HAVE_NTGUI
4834 #ifndef HAVE_NS
4835 /* Create an image and pixmap serving as mask. */
4836 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4837 &mask_img, &img->mask);
4838 if (!rc)
4839 return 0;
4840 #endif /* !HAVE_NS */
4842 /* Get the X image of IMG->pixmap. */
4843 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4844 img->width, img->height,
4845 ~0, ZPixmap);
4846 #else
4847 /* Create the bit array serving as mask. */
4848 row_width = (img->width + 7) / 8;
4849 mask_img = xmalloc (row_width * img->height);
4850 memset (mask_img, 0, row_width * img->height);
4852 /* Create a memory device context for IMG->pixmap. */
4853 frame_dc = get_frame_dc (f);
4854 ximg = CreateCompatibleDC (frame_dc);
4855 release_frame_dc (f, frame_dc);
4856 prev = SelectObject (ximg, img->pixmap);
4857 #endif /* HAVE_NTGUI */
4859 /* Determine the background color of ximg. If HOW is `(R G B)'
4860 take that as color. Otherwise, use the image's background color. */
4861 use_img_background = 1;
4863 if (CONSP (how))
4865 int rgb[3], i;
4867 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4869 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4870 how = XCDR (how);
4873 if (i == 3 && NILP (how))
4875 char color_name[30];
4876 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4877 bg = (
4878 #ifdef HAVE_NTGUI
4879 0x00ffffff & /* Filter out palette info. */
4880 #endif /* HAVE_NTGUI */
4881 x_alloc_image_color (f, img, build_string (color_name), 0));
4882 use_img_background = 0;
4886 if (use_img_background)
4887 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4889 /* Set all bits in mask_img to 1 whose color in ximg is different
4890 from the background color bg. */
4891 #ifndef HAVE_NTGUI
4892 for (y = 0; y < img->height; ++y)
4893 for (x = 0; x < img->width; ++x)
4894 #ifndef HAVE_NS
4895 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4896 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4897 #else
4898 if (XGetPixel (ximg, x, y) == bg)
4899 ns_set_alpha (ximg, x, y, 0);
4900 #endif /* HAVE_NS */
4901 #ifndef HAVE_NS
4902 /* Fill in the background_transparent field while we have the mask handy. */
4903 image_background_transparent (img, f, mask_img);
4905 /* Put mask_img into img->mask. */
4906 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4907 x_destroy_x_image (mask_img);
4908 #endif /* !HAVE_NS */
4909 #else
4910 for (y = 0; y < img->height; ++y)
4911 for (x = 0; x < img->width; ++x)
4913 COLORREF p = GetPixel (ximg, x, y);
4914 if (p != bg)
4915 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4918 /* Create the mask image. */
4919 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4920 mask_img);
4921 /* Fill in the background_transparent field while we have the mask handy. */
4922 SelectObject (ximg, img->mask);
4923 image_background_transparent (img, f, ximg);
4925 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4926 xfree (mask_img);
4927 #endif /* HAVE_NTGUI */
4929 Destroy_Image (ximg, prev);
4931 return 1;
4935 /***********************************************************************
4936 PBM (mono, gray, color)
4937 ***********************************************************************/
4939 static int pbm_image_p (Lisp_Object object);
4940 static int pbm_load (struct frame *f, struct image *img);
4941 static int pbm_scan_number (unsigned char **, unsigned char *);
4943 /* The symbol `pbm' identifying images of this type. */
4945 Lisp_Object Qpbm;
4947 /* Indices of image specification fields in gs_format, below. */
4949 enum pbm_keyword_index
4951 PBM_TYPE,
4952 PBM_FILE,
4953 PBM_DATA,
4954 PBM_ASCENT,
4955 PBM_MARGIN,
4956 PBM_RELIEF,
4957 PBM_ALGORITHM,
4958 PBM_HEURISTIC_MASK,
4959 PBM_MASK,
4960 PBM_FOREGROUND,
4961 PBM_BACKGROUND,
4962 PBM_LAST
4965 /* Vector of image_keyword structures describing the format
4966 of valid user-defined image specifications. */
4968 static const struct image_keyword pbm_format[PBM_LAST] =
4970 {":type", IMAGE_SYMBOL_VALUE, 1},
4971 {":file", IMAGE_STRING_VALUE, 0},
4972 {":data", IMAGE_STRING_VALUE, 0},
4973 {":ascent", IMAGE_ASCENT_VALUE, 0},
4974 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
4975 {":relief", IMAGE_INTEGER_VALUE, 0},
4976 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4977 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4978 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4979 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4980 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4983 /* Structure describing the image type `pbm'. */
4985 static struct image_type pbm_type =
4987 &Qpbm,
4988 pbm_image_p,
4989 pbm_load,
4990 x_clear_image,
4991 NULL
4995 /* Return non-zero if OBJECT is a valid PBM image specification. */
4997 static int
4998 pbm_image_p (Lisp_Object object)
5000 struct image_keyword fmt[PBM_LAST];
5002 memcpy (fmt, pbm_format, sizeof fmt);
5004 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5005 return 0;
5007 /* Must specify either :data or :file. */
5008 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5012 /* Scan a decimal number from *S and return it. Advance *S while
5013 reading the number. END is the end of the string. Value is -1 at
5014 end of input. */
5016 static int
5017 pbm_scan_number (unsigned char **s, unsigned char *end)
5019 int c = 0, val = -1;
5021 while (*s < end)
5023 /* Skip white-space. */
5024 while (*s < end && (c = *(*s)++, isspace (c)))
5027 if (c == '#')
5029 /* Skip comment to end of line. */
5030 while (*s < end && (c = *(*s)++, c != '\n'))
5033 else if (isdigit (c))
5035 /* Read decimal number. */
5036 val = c - '0';
5037 while (*s < end && (c = *(*s)++, isdigit (c)))
5038 val = 10 * val + c - '0';
5039 break;
5041 else
5042 break;
5045 return val;
5049 #ifdef HAVE_NTGUI
5050 #if 0 /* Unused. ++kfs */
5052 /* Read FILE into memory. Value is a pointer to a buffer allocated
5053 with xmalloc holding FILE's contents. Value is null if an error
5054 occurred. *SIZE is set to the size of the file. */
5056 static char *
5057 pbm_read_file (file, size)
5058 Lisp_Object file;
5059 int *size;
5061 FILE *fp = NULL;
5062 char *buf = NULL;
5063 struct stat st;
5065 if (stat (SDATA (file), &st) == 0
5066 && (fp = fopen (SDATA (file), "rb")) != NULL
5067 && (buf = (char *) xmalloc (st.st_size),
5068 fread (buf, 1, st.st_size, fp) == st.st_size))
5070 *size = st.st_size;
5071 fclose (fp);
5073 else
5075 if (fp)
5076 fclose (fp);
5077 if (buf)
5079 xfree (buf);
5080 buf = NULL;
5084 return buf;
5086 #endif
5087 #endif /* HAVE_NTGUI */
5089 /* Load PBM image IMG for use on frame F. */
5091 static int
5092 pbm_load (struct frame *f, struct image *img)
5094 int raw_p, x, y;
5095 int width, height, max_color_idx = 0;
5096 XImagePtr ximg;
5097 Lisp_Object file, specified_file;
5098 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5099 struct gcpro gcpro1;
5100 unsigned char *contents = NULL;
5101 unsigned char *end, *p;
5102 int size;
5104 specified_file = image_spec_value (img->spec, QCfile, NULL);
5105 file = Qnil;
5106 GCPRO1 (file);
5108 if (STRINGP (specified_file))
5110 file = x_find_image_file (specified_file);
5111 if (!STRINGP (file))
5113 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5114 UNGCPRO;
5115 return 0;
5118 contents = slurp_file (SDATA (file), &size);
5119 if (contents == NULL)
5121 image_error ("Error reading `%s'", file, Qnil);
5122 UNGCPRO;
5123 return 0;
5126 p = contents;
5127 end = contents + size;
5129 else
5131 Lisp_Object data;
5132 data = image_spec_value (img->spec, QCdata, NULL);
5133 p = SDATA (data);
5134 end = p + SBYTES (data);
5137 /* Check magic number. */
5138 if (end - p < 2 || *p++ != 'P')
5140 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5141 error:
5142 xfree (contents);
5143 UNGCPRO;
5144 return 0;
5147 switch (*p++)
5149 case '1':
5150 raw_p = 0, type = PBM_MONO;
5151 break;
5153 case '2':
5154 raw_p = 0, type = PBM_GRAY;
5155 break;
5157 case '3':
5158 raw_p = 0, type = PBM_COLOR;
5159 break;
5161 case '4':
5162 raw_p = 1, type = PBM_MONO;
5163 break;
5165 case '5':
5166 raw_p = 1, type = PBM_GRAY;
5167 break;
5169 case '6':
5170 raw_p = 1, type = PBM_COLOR;
5171 break;
5173 default:
5174 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5175 goto error;
5178 /* Read width, height, maximum color-component. Characters
5179 starting with `#' up to the end of a line are ignored. */
5180 width = pbm_scan_number (&p, end);
5181 height = pbm_scan_number (&p, end);
5183 if (type != PBM_MONO)
5185 max_color_idx = pbm_scan_number (&p, end);
5186 if (max_color_idx > 65535 || max_color_idx < 0)
5188 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5189 goto error;
5193 if (!check_image_size (f, width, height))
5195 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5196 goto error;
5199 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5200 &ximg, &img->pixmap))
5201 goto error;
5203 /* Initialize the color hash table. */
5204 init_color_table ();
5206 if (type == PBM_MONO)
5208 int c = 0, g;
5209 struct image_keyword fmt[PBM_LAST];
5210 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5211 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5213 /* Parse the image specification. */
5214 memcpy (fmt, pbm_format, sizeof fmt);
5215 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5217 /* Get foreground and background colors, maybe allocate colors. */
5218 if (fmt[PBM_FOREGROUND].count
5219 && STRINGP (fmt[PBM_FOREGROUND].value))
5220 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5221 if (fmt[PBM_BACKGROUND].count
5222 && STRINGP (fmt[PBM_BACKGROUND].value))
5224 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5225 img->background = bg;
5226 img->background_valid = 1;
5229 for (y = 0; y < height; ++y)
5230 for (x = 0; x < width; ++x)
5232 if (raw_p)
5234 if ((x & 7) == 0)
5236 if (p >= end)
5238 x_destroy_x_image (ximg);
5239 x_clear_image (f, img);
5240 image_error ("Invalid image size in image `%s'",
5241 img->spec, Qnil);
5242 goto error;
5244 c = *p++;
5246 g = c & 0x80;
5247 c <<= 1;
5249 else
5250 g = pbm_scan_number (&p, end);
5252 XPutPixel (ximg, x, y, g ? fg : bg);
5255 else
5257 int expected_size = height * width;
5258 if (max_color_idx > 255)
5259 expected_size *= 2;
5260 if (type == PBM_COLOR)
5261 expected_size *= 3;
5263 if (raw_p && p + expected_size > end)
5265 x_destroy_x_image (ximg);
5266 x_clear_image (f, img);
5267 image_error ("Invalid image size in image `%s'",
5268 img->spec, Qnil);
5269 goto error;
5272 for (y = 0; y < height; ++y)
5273 for (x = 0; x < width; ++x)
5275 int r, g, b;
5277 if (type == PBM_GRAY && raw_p)
5279 r = g = b = *p++;
5280 if (max_color_idx > 255)
5281 r = g = b = r * 256 + *p++;
5283 else if (type == PBM_GRAY)
5284 r = g = b = pbm_scan_number (&p, end);
5285 else if (raw_p)
5287 r = *p++;
5288 if (max_color_idx > 255)
5289 r = r * 256 + *p++;
5290 g = *p++;
5291 if (max_color_idx > 255)
5292 g = g * 256 + *p++;
5293 b = *p++;
5294 if (max_color_idx > 255)
5295 b = b * 256 + *p++;
5297 else
5299 r = pbm_scan_number (&p, end);
5300 g = pbm_scan_number (&p, end);
5301 b = pbm_scan_number (&p, end);
5304 if (r < 0 || g < 0 || b < 0)
5306 x_destroy_x_image (ximg);
5307 image_error ("Invalid pixel value in image `%s'",
5308 img->spec, Qnil);
5309 goto error;
5312 /* RGB values are now in the range 0..max_color_idx.
5313 Scale this to the range 0..0xffff supported by X. */
5314 r = (double) r * 65535 / max_color_idx;
5315 g = (double) g * 65535 / max_color_idx;
5316 b = (double) b * 65535 / max_color_idx;
5317 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5321 #ifdef COLOR_TABLE_SUPPORT
5322 /* Store in IMG->colors the colors allocated for the image, and
5323 free the color table. */
5324 img->colors = colors_in_color_table (&img->ncolors);
5325 free_color_table ();
5326 #endif /* COLOR_TABLE_SUPPORT */
5328 img->width = width;
5329 img->height = height;
5331 /* Maybe fill in the background field while we have ximg handy. */
5333 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5334 /* Casting avoids a GCC warning. */
5335 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5337 /* Put the image into a pixmap. */
5338 x_put_x_image (f, ximg, img->pixmap, width, height);
5339 x_destroy_x_image (ximg);
5341 /* X and W32 versions did it here, MAC version above. ++kfs
5342 img->width = width;
5343 img->height = height; */
5345 UNGCPRO;
5346 xfree (contents);
5347 return 1;
5351 /***********************************************************************
5353 ***********************************************************************/
5355 #if defined (HAVE_PNG) || defined (HAVE_NS)
5357 /* Function prototypes. */
5359 static int png_image_p (Lisp_Object object);
5360 static int png_load (struct frame *f, struct image *img);
5362 /* The symbol `png' identifying images of this type. */
5364 Lisp_Object Qpng;
5366 /* Indices of image specification fields in png_format, below. */
5368 enum png_keyword_index
5370 PNG_TYPE,
5371 PNG_DATA,
5372 PNG_FILE,
5373 PNG_ASCENT,
5374 PNG_MARGIN,
5375 PNG_RELIEF,
5376 PNG_ALGORITHM,
5377 PNG_HEURISTIC_MASK,
5378 PNG_MASK,
5379 PNG_BACKGROUND,
5380 PNG_LAST
5383 /* Vector of image_keyword structures describing the format
5384 of valid user-defined image specifications. */
5386 static const struct image_keyword png_format[PNG_LAST] =
5388 {":type", IMAGE_SYMBOL_VALUE, 1},
5389 {":data", IMAGE_STRING_VALUE, 0},
5390 {":file", IMAGE_STRING_VALUE, 0},
5391 {":ascent", IMAGE_ASCENT_VALUE, 0},
5392 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5393 {":relief", IMAGE_INTEGER_VALUE, 0},
5394 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5395 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5396 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5397 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5400 /* Structure describing the image type `png'. */
5402 static struct image_type png_type =
5404 &Qpng,
5405 png_image_p,
5406 png_load,
5407 x_clear_image,
5408 NULL
5411 /* Return non-zero if OBJECT is a valid PNG image specification. */
5413 static int
5414 png_image_p (Lisp_Object object)
5416 struct image_keyword fmt[PNG_LAST];
5417 memcpy (fmt, png_format, sizeof fmt);
5419 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5420 return 0;
5422 /* Must specify either the :data or :file keyword. */
5423 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5426 #endif /* HAVE_PNG || HAVE_NS */
5429 #ifdef HAVE_PNG
5431 #ifdef HAVE_NTGUI
5432 /* PNG library details. */
5434 DEF_IMGLIB_FN (png_get_io_ptr);
5435 DEF_IMGLIB_FN (png_sig_cmp);
5436 DEF_IMGLIB_FN (png_create_read_struct);
5437 DEF_IMGLIB_FN (png_create_info_struct);
5438 DEF_IMGLIB_FN (png_destroy_read_struct);
5439 DEF_IMGLIB_FN (png_set_read_fn);
5440 DEF_IMGLIB_FN (png_set_sig_bytes);
5441 DEF_IMGLIB_FN (png_read_info);
5442 DEF_IMGLIB_FN (png_get_IHDR);
5443 DEF_IMGLIB_FN (png_get_valid);
5444 DEF_IMGLIB_FN (png_set_strip_16);
5445 DEF_IMGLIB_FN (png_set_expand);
5446 DEF_IMGLIB_FN (png_set_gray_to_rgb);
5447 DEF_IMGLIB_FN (png_set_background);
5448 DEF_IMGLIB_FN (png_get_bKGD);
5449 DEF_IMGLIB_FN (png_read_update_info);
5450 DEF_IMGLIB_FN (png_get_channels);
5451 DEF_IMGLIB_FN (png_get_rowbytes);
5452 DEF_IMGLIB_FN (png_read_image);
5453 DEF_IMGLIB_FN (png_read_end);
5454 DEF_IMGLIB_FN (png_error);
5456 static int
5457 init_png_functions (Lisp_Object libraries)
5459 HMODULE library;
5461 /* Try loading libpng under probable names. */
5462 if (!(library = w32_delayed_load (libraries, Qpng)))
5463 return 0;
5465 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5466 LOAD_IMGLIB_FN (library, png_sig_cmp);
5467 LOAD_IMGLIB_FN (library, png_create_read_struct);
5468 LOAD_IMGLIB_FN (library, png_create_info_struct);
5469 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5470 LOAD_IMGLIB_FN (library, png_set_read_fn);
5471 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5472 LOAD_IMGLIB_FN (library, png_read_info);
5473 LOAD_IMGLIB_FN (library, png_get_IHDR);
5474 LOAD_IMGLIB_FN (library, png_get_valid);
5475 LOAD_IMGLIB_FN (library, png_set_strip_16);
5476 LOAD_IMGLIB_FN (library, png_set_expand);
5477 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5478 LOAD_IMGLIB_FN (library, png_set_background);
5479 LOAD_IMGLIB_FN (library, png_get_bKGD);
5480 LOAD_IMGLIB_FN (library, png_read_update_info);
5481 LOAD_IMGLIB_FN (library, png_get_channels);
5482 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5483 LOAD_IMGLIB_FN (library, png_read_image);
5484 LOAD_IMGLIB_FN (library, png_read_end);
5485 LOAD_IMGLIB_FN (library, png_error);
5486 return 1;
5488 #else
5490 #define fn_png_get_io_ptr png_get_io_ptr
5491 #define fn_png_sig_cmp png_sig_cmp
5492 #define fn_png_create_read_struct png_create_read_struct
5493 #define fn_png_create_info_struct png_create_info_struct
5494 #define fn_png_destroy_read_struct png_destroy_read_struct
5495 #define fn_png_set_read_fn png_set_read_fn
5496 #define fn_png_set_sig_bytes png_set_sig_bytes
5497 #define fn_png_read_info png_read_info
5498 #define fn_png_get_IHDR png_get_IHDR
5499 #define fn_png_get_valid png_get_valid
5500 #define fn_png_set_strip_16 png_set_strip_16
5501 #define fn_png_set_expand png_set_expand
5502 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5503 #define fn_png_set_background png_set_background
5504 #define fn_png_get_bKGD png_get_bKGD
5505 #define fn_png_read_update_info png_read_update_info
5506 #define fn_png_get_channels png_get_channels
5507 #define fn_png_get_rowbytes png_get_rowbytes
5508 #define fn_png_read_image png_read_image
5509 #define fn_png_read_end png_read_end
5510 #define fn_png_error png_error
5512 #endif /* HAVE_NTGUI */
5514 /* Error and warning handlers installed when the PNG library
5515 is initialized. */
5517 static void
5518 my_png_error (png_struct *png_ptr, const char *msg)
5520 xassert (png_ptr != NULL);
5521 image_error ("PNG error: %s", build_string (msg), Qnil);
5522 longjmp (png_ptr->jmpbuf, 1);
5526 static void
5527 my_png_warning (png_struct *png_ptr, const char *msg)
5529 xassert (png_ptr != NULL);
5530 image_error ("PNG warning: %s", build_string (msg), Qnil);
5533 /* Memory source for PNG decoding. */
5535 struct png_memory_storage
5537 unsigned char *bytes; /* The data */
5538 size_t len; /* How big is it? */
5539 int index; /* Where are we? */
5543 /* Function set as reader function when reading PNG image from memory.
5544 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5545 bytes from the input to DATA. */
5547 static void
5548 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5550 struct png_memory_storage *tbr
5551 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5553 if (length > tbr->len - tbr->index)
5554 fn_png_error (png_ptr, "Read error");
5556 memcpy (data, tbr->bytes + tbr->index, length);
5557 tbr->index = tbr->index + length;
5561 /* Function set as reader function when reading PNG image from a file.
5562 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5563 bytes from the input to DATA. */
5565 static void
5566 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5568 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5570 if (fread (data, 1, length, fp) < length)
5571 fn_png_error (png_ptr, "Read error");
5575 /* Load PNG image IMG for use on frame F. Value is non-zero if
5576 successful. */
5578 static int
5579 png_load (struct frame *f, struct image *img)
5581 Lisp_Object file, specified_file;
5582 Lisp_Object specified_data;
5583 int x, y, i;
5584 XImagePtr ximg, mask_img = NULL;
5585 struct gcpro gcpro1;
5586 png_struct *png_ptr = NULL;
5587 png_info *info_ptr = NULL, *end_info = NULL;
5588 FILE *volatile fp = NULL;
5589 png_byte sig[8];
5590 png_byte * volatile pixels = NULL;
5591 png_byte ** volatile rows = NULL;
5592 png_uint_32 width, height;
5593 int bit_depth, color_type, interlace_type;
5594 png_byte channels;
5595 png_uint_32 row_bytes;
5596 int transparent_p;
5597 struct png_memory_storage tbr; /* Data to be read */
5599 /* Find out what file to load. */
5600 specified_file = image_spec_value (img->spec, QCfile, NULL);
5601 specified_data = image_spec_value (img->spec, QCdata, NULL);
5602 file = Qnil;
5603 GCPRO1 (file);
5605 if (NILP (specified_data))
5607 file = x_find_image_file (specified_file);
5608 if (!STRINGP (file))
5610 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5611 UNGCPRO;
5612 return 0;
5615 /* Open the image file. */
5616 fp = fopen (SDATA (file), "rb");
5617 if (!fp)
5619 image_error ("Cannot open image file `%s'", file, Qnil);
5620 UNGCPRO;
5621 return 0;
5624 /* Check PNG signature. */
5625 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5626 || fn_png_sig_cmp (sig, 0, sizeof sig))
5628 image_error ("Not a PNG file: `%s'", file, Qnil);
5629 UNGCPRO;
5630 fclose (fp);
5631 return 0;
5634 else
5636 /* Read from memory. */
5637 tbr.bytes = SDATA (specified_data);
5638 tbr.len = SBYTES (specified_data);
5639 tbr.index = 0;
5641 /* Check PNG signature. */
5642 if (tbr.len < sizeof sig
5643 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5645 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5646 UNGCPRO;
5647 return 0;
5650 /* Need to skip past the signature. */
5651 tbr.bytes += sizeof (sig);
5654 /* Initialize read and info structs for PNG lib. Casting return
5655 value avoids a GCC warning on W32. */
5656 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5657 NULL, my_png_error,
5658 my_png_warning);
5659 if (!png_ptr)
5661 if (fp) fclose (fp);
5662 UNGCPRO;
5663 return 0;
5666 /* Casting return value avoids a GCC warning on W32. */
5667 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
5668 if (!info_ptr)
5670 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5671 if (fp) fclose (fp);
5672 UNGCPRO;
5673 return 0;
5676 /* Casting return value avoids a GCC warning on W32. */
5677 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
5678 if (!end_info)
5680 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5681 if (fp) fclose (fp);
5682 UNGCPRO;
5683 return 0;
5686 /* Set error jump-back. We come back here when the PNG library
5687 detects an error. */
5688 if (setjmp (png_ptr->jmpbuf))
5690 error:
5691 if (png_ptr)
5692 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5693 xfree (pixels);
5694 xfree (rows);
5695 if (fp) fclose (fp);
5696 UNGCPRO;
5697 return 0;
5700 /* Read image info. */
5701 if (!NILP (specified_data))
5702 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5703 else
5704 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5706 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5707 fn_png_read_info (png_ptr, info_ptr);
5708 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5709 &interlace_type, NULL, NULL);
5711 if (!check_image_size (f, width, height))
5713 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5714 goto error;
5716 /* If image contains simply transparency data, we prefer to
5717 construct a clipping mask. */
5718 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5719 transparent_p = 1;
5720 else
5721 transparent_p = 0;
5723 /* This function is easier to write if we only have to handle
5724 one data format: RGB or RGBA with 8 bits per channel. Let's
5725 transform other formats into that format. */
5727 /* Strip more than 8 bits per channel. */
5728 if (bit_depth == 16)
5729 fn_png_set_strip_16 (png_ptr);
5731 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5732 if available. */
5733 fn_png_set_expand (png_ptr);
5735 /* Convert grayscale images to RGB. */
5736 if (color_type == PNG_COLOR_TYPE_GRAY
5737 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5738 fn_png_set_gray_to_rgb (png_ptr);
5740 /* Handle alpha channel by combining the image with a background
5741 color. Do this only if a real alpha channel is supplied. For
5742 simple transparency, we prefer a clipping mask. */
5743 if (!transparent_p)
5745 /* png_color_16 *image_bg; */
5746 Lisp_Object specified_bg
5747 = image_spec_value (img->spec, QCbackground, NULL);
5748 int shift = (bit_depth == 16) ? 0 : 8;
5750 if (STRINGP (specified_bg))
5751 /* The user specified `:background', use that. */
5753 XColor color;
5754 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
5756 png_color_16 user_bg;
5758 memset (&user_bg, 0, sizeof user_bg);
5759 user_bg.red = color.red >> shift;
5760 user_bg.green = color.green >> shift;
5761 user_bg.blue = color.blue >> shift;
5763 fn_png_set_background (png_ptr, &user_bg,
5764 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5767 else
5769 /* We use the current frame background, ignoring any default
5770 background color set by the image. */
5771 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5772 XColor color;
5773 png_color_16 frame_background;
5775 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5776 x_query_color (f, &color);
5778 memset (&frame_background, 0, sizeof frame_background);
5779 frame_background.red = color.red >> shift;
5780 frame_background.green = color.green >> shift;
5781 frame_background.blue = color.blue >> shift;
5782 #endif /* HAVE_X_WINDOWS */
5784 fn_png_set_background (png_ptr, &frame_background,
5785 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5789 /* Update info structure. */
5790 fn_png_read_update_info (png_ptr, info_ptr);
5792 /* Get number of channels. Valid values are 1 for grayscale images
5793 and images with a palette, 2 for grayscale images with transparency
5794 information (alpha channel), 3 for RGB images, and 4 for RGB
5795 images with alpha channel, i.e. RGBA. If conversions above were
5796 sufficient we should only have 3 or 4 channels here. */
5797 channels = fn_png_get_channels (png_ptr, info_ptr);
5798 xassert (channels == 3 || channels == 4);
5800 /* Number of bytes needed for one row of the image. */
5801 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5803 /* Allocate memory for the image. */
5804 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
5805 rows = (png_byte **) xmalloc (height * sizeof *rows);
5806 for (i = 0; i < height; ++i)
5807 rows[i] = pixels + i * row_bytes;
5809 /* Read the entire image. */
5810 fn_png_read_image (png_ptr, rows);
5811 fn_png_read_end (png_ptr, info_ptr);
5812 if (fp)
5814 fclose (fp);
5815 fp = NULL;
5818 /* Create the X image and pixmap. */
5819 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5820 &img->pixmap))
5821 goto error;
5823 /* Create an image and pixmap serving as mask if the PNG image
5824 contains an alpha channel. */
5825 if (channels == 4
5826 && !transparent_p
5827 && !x_create_x_image_and_pixmap (f, width, height, 1,
5828 &mask_img, &img->mask))
5830 x_destroy_x_image (ximg);
5831 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5832 img->pixmap = NO_PIXMAP;
5833 goto error;
5836 /* Fill the X image and mask from PNG data. */
5837 init_color_table ();
5839 for (y = 0; y < height; ++y)
5841 png_byte *p = rows[y];
5843 for (x = 0; x < width; ++x)
5845 unsigned r, g, b;
5847 r = *p++ << 8;
5848 g = *p++ << 8;
5849 b = *p++ << 8;
5850 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5851 /* An alpha channel, aka mask channel, associates variable
5852 transparency with an image. Where other image formats
5853 support binary transparency---fully transparent or fully
5854 opaque---PNG allows up to 254 levels of partial transparency.
5855 The PNG library implements partial transparency by combining
5856 the image with a specified background color.
5858 I'm not sure how to handle this here nicely: because the
5859 background on which the image is displayed may change, for
5860 real alpha channel support, it would be necessary to create
5861 a new image for each possible background.
5863 What I'm doing now is that a mask is created if we have
5864 boolean transparency information. Otherwise I'm using
5865 the frame's background color to combine the image with. */
5867 if (channels == 4)
5869 if (mask_img)
5870 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5871 ++p;
5876 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5877 /* Set IMG's background color from the PNG image, unless the user
5878 overrode it. */
5880 png_color_16 *bg;
5881 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5883 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5884 img->background_valid = 1;
5888 #ifdef COLOR_TABLE_SUPPORT
5889 /* Remember colors allocated for this image. */
5890 img->colors = colors_in_color_table (&img->ncolors);
5891 free_color_table ();
5892 #endif /* COLOR_TABLE_SUPPORT */
5894 /* Clean up. */
5895 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5896 xfree (rows);
5897 xfree (pixels);
5899 img->width = width;
5900 img->height = height;
5902 /* Maybe fill in the background field while we have ximg handy.
5903 Casting avoids a GCC warning. */
5904 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5906 /* Put the image into the pixmap, then free the X image and its buffer. */
5907 x_put_x_image (f, ximg, img->pixmap, width, height);
5908 x_destroy_x_image (ximg);
5910 /* Same for the mask. */
5911 if (mask_img)
5913 /* Fill in the background_transparent field while we have the
5914 mask handy. Casting avoids a GCC warning. */
5915 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
5917 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5918 x_destroy_x_image (mask_img);
5921 UNGCPRO;
5922 return 1;
5925 #else /* HAVE_PNG */
5927 #ifdef HAVE_NS
5928 static int
5929 png_load (struct frame *f, struct image *img)
5931 return ns_load_image(f, img,
5932 image_spec_value (img->spec, QCfile, NULL),
5933 image_spec_value (img->spec, QCdata, NULL));
5935 #endif /* HAVE_NS */
5938 #endif /* !HAVE_PNG */
5942 /***********************************************************************
5943 JPEG
5944 ***********************************************************************/
5946 #if defined (HAVE_JPEG) || defined (HAVE_NS)
5948 static int jpeg_image_p (Lisp_Object object);
5949 static int jpeg_load (struct frame *f, struct image *img);
5951 /* The symbol `jpeg' identifying images of this type. */
5953 Lisp_Object Qjpeg;
5955 /* Indices of image specification fields in gs_format, below. */
5957 enum jpeg_keyword_index
5959 JPEG_TYPE,
5960 JPEG_DATA,
5961 JPEG_FILE,
5962 JPEG_ASCENT,
5963 JPEG_MARGIN,
5964 JPEG_RELIEF,
5965 JPEG_ALGORITHM,
5966 JPEG_HEURISTIC_MASK,
5967 JPEG_MASK,
5968 JPEG_BACKGROUND,
5969 JPEG_LAST
5972 /* Vector of image_keyword structures describing the format
5973 of valid user-defined image specifications. */
5975 static const struct image_keyword jpeg_format[JPEG_LAST] =
5977 {":type", IMAGE_SYMBOL_VALUE, 1},
5978 {":data", IMAGE_STRING_VALUE, 0},
5979 {":file", IMAGE_STRING_VALUE, 0},
5980 {":ascent", IMAGE_ASCENT_VALUE, 0},
5981 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5982 {":relief", IMAGE_INTEGER_VALUE, 0},
5983 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5984 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5985 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5986 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5989 /* Structure describing the image type `jpeg'. */
5991 static struct image_type jpeg_type =
5993 &Qjpeg,
5994 jpeg_image_p,
5995 jpeg_load,
5996 x_clear_image,
5997 NULL
6000 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6002 static int
6003 jpeg_image_p (Lisp_Object object)
6005 struct image_keyword fmt[JPEG_LAST];
6007 memcpy (fmt, jpeg_format, sizeof fmt);
6009 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6010 return 0;
6012 /* Must specify either the :data or :file keyword. */
6013 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6016 #endif /* HAVE_JPEG || HAVE_NS */
6018 #ifdef HAVE_JPEG
6020 /* Work around a warning about HAVE_STDLIB_H being redefined in
6021 jconfig.h. */
6022 #ifdef HAVE_STDLIB_H
6023 #define HAVE_STDLIB_H_1
6024 #undef HAVE_STDLIB_H
6025 #endif /* HAVE_STLIB_H */
6027 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6028 /* In older releases of the jpeg library, jpeglib.h will define boolean
6029 differently depending on __WIN32__, so make sure it is defined. */
6030 #define __WIN32__ 1
6031 #endif
6033 #include <jpeglib.h>
6034 #include <jerror.h>
6036 #ifdef HAVE_STLIB_H_1
6037 #define HAVE_STDLIB_H 1
6038 #endif
6040 #ifdef HAVE_NTGUI
6042 /* JPEG library details. */
6043 DEF_IMGLIB_FN (jpeg_CreateDecompress);
6044 DEF_IMGLIB_FN (jpeg_start_decompress);
6045 DEF_IMGLIB_FN (jpeg_finish_decompress);
6046 DEF_IMGLIB_FN (jpeg_destroy_decompress);
6047 DEF_IMGLIB_FN (jpeg_read_header);
6048 DEF_IMGLIB_FN (jpeg_read_scanlines);
6049 DEF_IMGLIB_FN (jpeg_std_error);
6050 DEF_IMGLIB_FN (jpeg_resync_to_restart);
6052 static int
6053 init_jpeg_functions (Lisp_Object libraries)
6055 HMODULE library;
6057 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6058 return 0;
6060 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6061 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6062 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6063 LOAD_IMGLIB_FN (library, jpeg_read_header);
6064 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6065 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6066 LOAD_IMGLIB_FN (library, jpeg_std_error);
6067 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6068 return 1;
6071 /* Wrapper since we can't directly assign the function pointer
6072 to another function pointer that was declared more completely easily. */
6073 static boolean
6074 jpeg_resync_to_restart_wrapper (cinfo, desired)
6075 j_decompress_ptr cinfo;
6076 int desired;
6078 return fn_jpeg_resync_to_restart (cinfo, desired);
6081 #else
6083 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6084 #define fn_jpeg_start_decompress jpeg_start_decompress
6085 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6086 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6087 #define fn_jpeg_read_header jpeg_read_header
6088 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6089 #define fn_jpeg_std_error jpeg_std_error
6090 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6092 #endif /* HAVE_NTGUI */
6094 struct my_jpeg_error_mgr
6096 struct jpeg_error_mgr pub;
6097 jmp_buf setjmp_buffer;
6101 static void
6102 my_error_exit (j_common_ptr cinfo)
6104 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6105 longjmp (mgr->setjmp_buffer, 1);
6109 /* Init source method for JPEG data source manager. Called by
6110 jpeg_read_header() before any data is actually read. See
6111 libjpeg.doc from the JPEG lib distribution. */
6113 static void
6114 our_common_init_source (j_decompress_ptr cinfo)
6119 /* Method to terminate data source. Called by
6120 jpeg_finish_decompress() after all data has been processed. */
6122 static void
6123 our_common_term_source (j_decompress_ptr cinfo)
6128 /* Fill input buffer method for JPEG data source manager. Called
6129 whenever more data is needed. We read the whole image in one step,
6130 so this only adds a fake end of input marker at the end. */
6132 static JOCTET our_memory_buffer[2];
6134 static boolean
6135 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6137 /* Insert a fake EOI marker. */
6138 struct jpeg_source_mgr *src = cinfo->src;
6140 our_memory_buffer[0] = (JOCTET) 0xFF;
6141 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6143 src->next_input_byte = our_memory_buffer;
6144 src->bytes_in_buffer = 2;
6145 return 1;
6149 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6150 is the JPEG data source manager. */
6152 static void
6153 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6155 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6157 if (src)
6159 if (num_bytes > src->bytes_in_buffer)
6160 ERREXIT (cinfo, JERR_INPUT_EOF);
6162 src->bytes_in_buffer -= num_bytes;
6163 src->next_input_byte += num_bytes;
6168 /* Set up the JPEG lib for reading an image from DATA which contains
6169 LEN bytes. CINFO is the decompression info structure created for
6170 reading the image. */
6172 static void
6173 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, unsigned int len)
6175 struct jpeg_source_mgr *src;
6177 if (cinfo->src == NULL)
6179 /* First time for this JPEG object? */
6180 cinfo->src = (struct jpeg_source_mgr *)
6181 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6182 sizeof (struct jpeg_source_mgr));
6183 src = (struct jpeg_source_mgr *) cinfo->src;
6184 src->next_input_byte = data;
6187 src = (struct jpeg_source_mgr *) cinfo->src;
6188 src->init_source = our_common_init_source;
6189 src->fill_input_buffer = our_memory_fill_input_buffer;
6190 src->skip_input_data = our_memory_skip_input_data;
6191 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6192 src->term_source = our_common_term_source;
6193 src->bytes_in_buffer = len;
6194 src->next_input_byte = data;
6198 struct jpeg_stdio_mgr
6200 struct jpeg_source_mgr mgr;
6201 boolean finished;
6202 FILE *file;
6203 JOCTET *buffer;
6207 /* Size of buffer to read JPEG from file.
6208 Not too big, as we want to use alloc_small. */
6209 #define JPEG_STDIO_BUFFER_SIZE 8192
6212 /* Fill input buffer method for JPEG data source manager. Called
6213 whenever more data is needed. The data is read from a FILE *. */
6215 static boolean
6216 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6218 struct jpeg_stdio_mgr *src;
6220 src = (struct jpeg_stdio_mgr *) cinfo->src;
6221 if (!src->finished)
6223 size_t bytes;
6225 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6226 if (bytes > 0)
6227 src->mgr.bytes_in_buffer = bytes;
6228 else
6230 WARNMS (cinfo, JWRN_JPEG_EOF);
6231 src->finished = 1;
6232 src->buffer[0] = (JOCTET) 0xFF;
6233 src->buffer[1] = (JOCTET) JPEG_EOI;
6234 src->mgr.bytes_in_buffer = 2;
6236 src->mgr.next_input_byte = src->buffer;
6239 return 1;
6243 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6244 is the JPEG data source manager. */
6246 static void
6247 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6249 struct jpeg_stdio_mgr *src;
6250 src = (struct jpeg_stdio_mgr *) cinfo->src;
6252 while (num_bytes > 0 && !src->finished)
6254 if (num_bytes <= src->mgr.bytes_in_buffer)
6256 src->mgr.bytes_in_buffer -= num_bytes;
6257 src->mgr.next_input_byte += num_bytes;
6258 break;
6260 else
6262 num_bytes -= src->mgr.bytes_in_buffer;
6263 src->mgr.bytes_in_buffer = 0;
6264 src->mgr.next_input_byte = NULL;
6266 our_stdio_fill_input_buffer (cinfo);
6272 /* Set up the JPEG lib for reading an image from a FILE *.
6273 CINFO is the decompression info structure created for
6274 reading the image. */
6276 static void
6277 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6279 struct jpeg_stdio_mgr *src;
6281 if (cinfo->src != NULL)
6282 src = (struct jpeg_stdio_mgr *) cinfo->src;
6283 else
6285 /* First time for this JPEG object? */
6286 cinfo->src = (struct jpeg_source_mgr *)
6287 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6288 sizeof (struct jpeg_stdio_mgr));
6289 src = (struct jpeg_stdio_mgr *) cinfo->src;
6290 src->buffer = (JOCTET *)
6291 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6292 JPEG_STDIO_BUFFER_SIZE);
6295 src->file = fp;
6296 src->finished = 0;
6297 src->mgr.init_source = our_common_init_source;
6298 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6299 src->mgr.skip_input_data = our_stdio_skip_input_data;
6300 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6301 src->mgr.term_source = our_common_term_source;
6302 src->mgr.bytes_in_buffer = 0;
6303 src->mgr.next_input_byte = NULL;
6307 /* Load image IMG for use on frame F. Patterned after example.c
6308 from the JPEG lib. */
6310 static int
6311 jpeg_load (struct frame *f, struct image *img)
6313 struct jpeg_decompress_struct cinfo;
6314 struct my_jpeg_error_mgr mgr;
6315 Lisp_Object file, specified_file;
6316 Lisp_Object specified_data;
6317 FILE * volatile fp = NULL;
6318 JSAMPARRAY buffer;
6319 int row_stride, x, y;
6320 XImagePtr ximg = NULL;
6321 int rc;
6322 unsigned long *colors;
6323 int width, height;
6324 struct gcpro gcpro1;
6326 /* Open the JPEG file. */
6327 specified_file = image_spec_value (img->spec, QCfile, NULL);
6328 specified_data = image_spec_value (img->spec, QCdata, NULL);
6329 file = Qnil;
6330 GCPRO1 (file);
6332 if (NILP (specified_data))
6334 file = x_find_image_file (specified_file);
6335 if (!STRINGP (file))
6337 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6338 UNGCPRO;
6339 return 0;
6342 fp = fopen (SDATA (file), "rb");
6343 if (fp == NULL)
6345 image_error ("Cannot open `%s'", file, Qnil);
6346 UNGCPRO;
6347 return 0;
6351 /* Customize libjpeg's error handling to call my_error_exit when an
6352 error is detected. This function will perform a longjmp.
6353 Casting return value avoids a GCC warning on W32. */
6354 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
6355 mgr.pub.error_exit = my_error_exit;
6357 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6359 if (rc == 1)
6361 /* Called from my_error_exit. Display a JPEG error. */
6362 char buffer[JMSG_LENGTH_MAX];
6363 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
6364 image_error ("Error reading JPEG image `%s': %s", img->spec,
6365 build_string (buffer));
6368 /* Close the input file and destroy the JPEG object. */
6369 if (fp)
6370 fclose ((FILE *) fp);
6371 fn_jpeg_destroy_decompress (&cinfo);
6373 /* If we already have an XImage, free that. */
6374 x_destroy_x_image (ximg);
6376 /* Free pixmap and colors. */
6377 x_clear_image (f, img);
6379 UNGCPRO;
6380 return 0;
6383 /* Create the JPEG decompression object. Let it read from fp.
6384 Read the JPEG image header. */
6385 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6387 if (NILP (specified_data))
6388 jpeg_file_src (&cinfo, (FILE *) fp);
6389 else
6390 jpeg_memory_src (&cinfo, SDATA (specified_data),
6391 SBYTES (specified_data));
6393 fn_jpeg_read_header (&cinfo, 1);
6395 /* Customize decompression so that color quantization will be used.
6396 Start decompression. */
6397 cinfo.quantize_colors = 1;
6398 fn_jpeg_start_decompress (&cinfo);
6399 width = img->width = cinfo.output_width;
6400 height = img->height = cinfo.output_height;
6402 if (!check_image_size (f, width, height))
6404 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6405 longjmp (mgr.setjmp_buffer, 2);
6408 /* Create X image and pixmap. */
6409 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6410 longjmp (mgr.setjmp_buffer, 2);
6412 /* Allocate colors. When color quantization is used,
6413 cinfo.actual_number_of_colors has been set with the number of
6414 colors generated, and cinfo.colormap is a two-dimensional array
6415 of color indices in the range 0..cinfo.actual_number_of_colors.
6416 No more than 255 colors will be generated. */
6418 int i, ir, ig, ib;
6420 if (cinfo.out_color_components > 2)
6421 ir = 0, ig = 1, ib = 2;
6422 else if (cinfo.out_color_components > 1)
6423 ir = 0, ig = 1, ib = 0;
6424 else
6425 ir = 0, ig = 0, ib = 0;
6427 /* Use the color table mechanism because it handles colors that
6428 cannot be allocated nicely. Such colors will be replaced with
6429 a default color, and we don't have to care about which colors
6430 can be freed safely, and which can't. */
6431 init_color_table ();
6432 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6433 * sizeof *colors);
6435 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6437 /* Multiply RGB values with 255 because X expects RGB values
6438 in the range 0..0xffff. */
6439 int r = cinfo.colormap[ir][i] << 8;
6440 int g = cinfo.colormap[ig][i] << 8;
6441 int b = cinfo.colormap[ib][i] << 8;
6442 colors[i] = lookup_rgb_color (f, r, g, b);
6445 #ifdef COLOR_TABLE_SUPPORT
6446 /* Remember those colors actually allocated. */
6447 img->colors = colors_in_color_table (&img->ncolors);
6448 free_color_table ();
6449 #endif /* COLOR_TABLE_SUPPORT */
6452 /* Read pixels. */
6453 row_stride = width * cinfo.output_components;
6454 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6455 row_stride, 1);
6456 for (y = 0; y < height; ++y)
6458 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6459 for (x = 0; x < cinfo.output_width; ++x)
6460 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6463 /* Clean up. */
6464 fn_jpeg_finish_decompress (&cinfo);
6465 fn_jpeg_destroy_decompress (&cinfo);
6466 if (fp)
6467 fclose ((FILE *) fp);
6469 /* Maybe fill in the background field while we have ximg handy. */
6470 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6471 /* Casting avoids a GCC warning. */
6472 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6474 /* Put the image into the pixmap. */
6475 x_put_x_image (f, ximg, img->pixmap, width, height);
6476 x_destroy_x_image (ximg);
6477 UNGCPRO;
6478 return 1;
6481 #else /* HAVE_JPEG */
6483 #ifdef HAVE_NS
6484 static int
6485 jpeg_load (struct frame *f, struct image *img)
6487 return ns_load_image (f, img,
6488 image_spec_value (img->spec, QCfile, NULL),
6489 image_spec_value (img->spec, QCdata, NULL));
6491 #endif /* HAVE_NS */
6493 #endif /* !HAVE_JPEG */
6497 /***********************************************************************
6498 TIFF
6499 ***********************************************************************/
6501 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6503 static int tiff_image_p (Lisp_Object object);
6504 static int tiff_load (struct frame *f, struct image *img);
6506 /* The symbol `tiff' identifying images of this type. */
6508 Lisp_Object Qtiff;
6510 /* Indices of image specification fields in tiff_format, below. */
6512 enum tiff_keyword_index
6514 TIFF_TYPE,
6515 TIFF_DATA,
6516 TIFF_FILE,
6517 TIFF_ASCENT,
6518 TIFF_MARGIN,
6519 TIFF_RELIEF,
6520 TIFF_ALGORITHM,
6521 TIFF_HEURISTIC_MASK,
6522 TIFF_MASK,
6523 TIFF_BACKGROUND,
6524 TIFF_INDEX,
6525 TIFF_LAST
6528 /* Vector of image_keyword structures describing the format
6529 of valid user-defined image specifications. */
6531 static const struct image_keyword tiff_format[TIFF_LAST] =
6533 {":type", IMAGE_SYMBOL_VALUE, 1},
6534 {":data", IMAGE_STRING_VALUE, 0},
6535 {":file", IMAGE_STRING_VALUE, 0},
6536 {":ascent", IMAGE_ASCENT_VALUE, 0},
6537 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6538 {":relief", IMAGE_INTEGER_VALUE, 0},
6539 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6540 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6541 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6542 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6543 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6546 /* Structure describing the image type `tiff'. */
6548 static struct image_type tiff_type =
6550 &Qtiff,
6551 tiff_image_p,
6552 tiff_load,
6553 x_clear_image,
6554 NULL
6557 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6559 static int
6560 tiff_image_p (Lisp_Object object)
6562 struct image_keyword fmt[TIFF_LAST];
6563 memcpy (fmt, tiff_format, sizeof fmt);
6565 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6566 return 0;
6568 /* Must specify either the :data or :file keyword. */
6569 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6572 #endif /* HAVE_TIFF || HAVE_NS */
6574 #ifdef HAVE_TIFF
6576 #include <tiffio.h>
6578 #ifdef HAVE_NTGUI
6580 /* TIFF library details. */
6581 DEF_IMGLIB_FN (TIFFSetErrorHandler);
6582 DEF_IMGLIB_FN (TIFFSetWarningHandler);
6583 DEF_IMGLIB_FN (TIFFOpen);
6584 DEF_IMGLIB_FN (TIFFClientOpen);
6585 DEF_IMGLIB_FN (TIFFGetField);
6586 DEF_IMGLIB_FN (TIFFReadRGBAImage);
6587 DEF_IMGLIB_FN (TIFFClose);
6588 DEF_IMGLIB_FN (TIFFSetDirectory);
6590 static int
6591 init_tiff_functions (Lisp_Object libraries)
6593 HMODULE library;
6595 if (!(library = w32_delayed_load (libraries, Qtiff)))
6596 return 0;
6598 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6599 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6600 LOAD_IMGLIB_FN (library, TIFFOpen);
6601 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6602 LOAD_IMGLIB_FN (library, TIFFGetField);
6603 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6604 LOAD_IMGLIB_FN (library, TIFFClose);
6605 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6606 return 1;
6609 #else
6611 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6612 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6613 #define fn_TIFFOpen TIFFOpen
6614 #define fn_TIFFClientOpen TIFFClientOpen
6615 #define fn_TIFFGetField TIFFGetField
6616 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6617 #define fn_TIFFClose TIFFClose
6618 #define fn_TIFFSetDirectory TIFFSetDirectory
6619 #endif /* HAVE_NTGUI */
6622 /* Reading from a memory buffer for TIFF images Based on the PNG
6623 memory source, but we have to provide a lot of extra functions.
6624 Blah.
6626 We really only need to implement read and seek, but I am not
6627 convinced that the TIFF library is smart enough not to destroy
6628 itself if we only hand it the function pointers we need to
6629 override. */
6631 typedef struct
6633 unsigned char *bytes;
6634 size_t len;
6635 int index;
6637 tiff_memory_source;
6639 static size_t
6640 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6642 tiff_memory_source *src = (tiff_memory_source *) data;
6644 if (size > src->len - src->index)
6645 return (size_t) -1;
6646 memcpy (buf, src->bytes + src->index, size);
6647 src->index += size;
6648 return size;
6651 static size_t
6652 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6654 return (size_t) -1;
6657 static toff_t
6658 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6660 tiff_memory_source *src = (tiff_memory_source *) data;
6661 int idx;
6663 switch (whence)
6665 case SEEK_SET: /* Go from beginning of source. */
6666 idx = off;
6667 break;
6669 case SEEK_END: /* Go from end of source. */
6670 idx = src->len + off;
6671 break;
6673 case SEEK_CUR: /* Go from current position. */
6674 idx = src->index + off;
6675 break;
6677 default: /* Invalid `whence'. */
6678 return -1;
6681 if (idx > src->len || idx < 0)
6682 return -1;
6684 src->index = idx;
6685 return src->index;
6688 static int
6689 tiff_close_memory (thandle_t data)
6691 /* NOOP */
6692 return 0;
6695 static int
6696 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6698 /* It is already _IN_ memory. */
6699 return 0;
6702 static void
6703 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6705 /* We don't need to do this. */
6708 static toff_t
6709 tiff_size_of_memory (thandle_t data)
6711 return ((tiff_memory_source *) data)->len;
6715 static void
6716 tiff_error_handler (const char *title, const char *format, va_list ap)
6718 char buf[512];
6719 int len;
6721 len = sprintf (buf, "TIFF error: %s ", title);
6722 vsprintf (buf + len, format, ap);
6723 add_to_log (buf, Qnil, Qnil);
6727 static void
6728 tiff_warning_handler (const char *title, const char *format, va_list ap)
6730 char buf[512];
6731 int len;
6733 len = sprintf (buf, "TIFF warning: %s ", title);
6734 vsprintf (buf + len, format, ap);
6735 add_to_log (buf, Qnil, Qnil);
6739 /* Load TIFF image IMG for use on frame F. Value is non-zero if
6740 successful. */
6742 static int
6743 tiff_load (struct frame *f, struct image *img)
6745 Lisp_Object file, specified_file;
6746 Lisp_Object specified_data;
6747 TIFF *tiff;
6748 int width, height, x, y, count;
6749 uint32 *buf;
6750 int rc, rc2;
6751 XImagePtr ximg;
6752 struct gcpro gcpro1;
6753 tiff_memory_source memsrc;
6754 Lisp_Object image;
6756 specified_file = image_spec_value (img->spec, QCfile, NULL);
6757 specified_data = image_spec_value (img->spec, QCdata, NULL);
6758 file = Qnil;
6759 GCPRO1 (file);
6761 fn_TIFFSetErrorHandler (tiff_error_handler);
6762 fn_TIFFSetWarningHandler (tiff_warning_handler);
6764 if (NILP (specified_data))
6766 /* Read from a file */
6767 file = x_find_image_file (specified_file);
6768 if (!STRINGP (file))
6770 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6771 UNGCPRO;
6772 return 0;
6775 /* Try to open the image file. Casting return value avoids a
6776 GCC warning on W32. */
6777 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
6778 if (tiff == NULL)
6780 image_error ("Cannot open `%s'", file, Qnil);
6781 UNGCPRO;
6782 return 0;
6785 else
6787 /* Memory source! */
6788 memsrc.bytes = SDATA (specified_data);
6789 memsrc.len = SBYTES (specified_data);
6790 memsrc.index = 0;
6792 /* Casting return value avoids a GCC warning on W32. */
6793 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r", &memsrc,
6794 (TIFFReadWriteProc) tiff_read_from_memory,
6795 (TIFFReadWriteProc) tiff_write_from_memory,
6796 tiff_seek_in_memory,
6797 tiff_close_memory,
6798 tiff_size_of_memory,
6799 tiff_mmap_memory,
6800 tiff_unmap_memory);
6802 if (!tiff)
6804 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6805 UNGCPRO;
6806 return 0;
6810 image = image_spec_value (img->spec, QCindex, NULL);
6811 if (INTEGERP (image))
6813 int ino = XFASTINT (image);
6814 if (!fn_TIFFSetDirectory (tiff, ino))
6816 image_error ("Invalid image number `%s' in image `%s'",
6817 image, img->spec);
6818 fn_TIFFClose (tiff);
6819 UNGCPRO;
6820 return 0;
6824 /* Get width and height of the image, and allocate a raster buffer
6825 of width x height 32-bit values. */
6826 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6827 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6829 if (!check_image_size (f, width, height))
6831 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6832 fn_TIFFClose (tiff);
6833 UNGCPRO;
6834 return 0;
6837 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
6839 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
6841 /* Count the number of images in the file. */
6842 for (count = 1, rc2 = 1; rc2; count++)
6843 rc2 = fn_TIFFSetDirectory (tiff, count);
6845 if (count > 1)
6846 img->data.lisp_val = Fcons (Qcount,
6847 Fcons (make_number (count),
6848 img->data.lisp_val));
6850 fn_TIFFClose (tiff);
6851 if (!rc)
6853 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6854 xfree (buf);
6855 UNGCPRO;
6856 return 0;
6859 /* Create the X image and pixmap. */
6860 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6862 xfree (buf);
6863 UNGCPRO;
6864 return 0;
6867 /* Initialize the color table. */
6868 init_color_table ();
6870 /* Process the pixel raster. Origin is in the lower-left corner. */
6871 for (y = 0; y < height; ++y)
6873 uint32 *row = buf + y * width;
6875 for (x = 0; x < width; ++x)
6877 uint32 abgr = row[x];
6878 int r = TIFFGetR (abgr) << 8;
6879 int g = TIFFGetG (abgr) << 8;
6880 int b = TIFFGetB (abgr) << 8;
6881 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6885 #ifdef COLOR_TABLE_SUPPORT
6886 /* Remember the colors allocated for the image. Free the color table. */
6887 img->colors = colors_in_color_table (&img->ncolors);
6888 free_color_table ();
6889 #endif /* COLOR_TABLE_SUPPORT */
6891 img->width = width;
6892 img->height = height;
6894 /* Maybe fill in the background field while we have ximg handy. */
6895 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6896 /* Casting avoids a GCC warning on W32. */
6897 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6899 /* Put the image into the pixmap, then free the X image and its buffer. */
6900 x_put_x_image (f, ximg, img->pixmap, width, height);
6901 x_destroy_x_image (ximg);
6902 xfree (buf);
6904 UNGCPRO;
6905 return 1;
6908 #else /* HAVE_TIFF */
6910 #ifdef HAVE_NS
6911 static int
6912 tiff_load (struct frame *f, struct image *img)
6914 return ns_load_image (f, img,
6915 image_spec_value (img->spec, QCfile, NULL),
6916 image_spec_value (img->spec, QCdata, NULL));
6918 #endif /* HAVE_NS */
6920 #endif /* !HAVE_TIFF */
6924 /***********************************************************************
6926 ***********************************************************************/
6928 #if defined (HAVE_GIF) || defined (HAVE_NS)
6930 static int gif_image_p (Lisp_Object object);
6931 static int gif_load (struct frame *f, struct image *img);
6932 static void gif_clear_image (struct frame *f, struct image *img);
6934 /* The symbol `gif' identifying images of this type. */
6936 Lisp_Object Qgif;
6938 /* Indices of image specification fields in gif_format, below. */
6940 enum gif_keyword_index
6942 GIF_TYPE,
6943 GIF_DATA,
6944 GIF_FILE,
6945 GIF_ASCENT,
6946 GIF_MARGIN,
6947 GIF_RELIEF,
6948 GIF_ALGORITHM,
6949 GIF_HEURISTIC_MASK,
6950 GIF_MASK,
6951 GIF_IMAGE,
6952 GIF_BACKGROUND,
6953 GIF_LAST
6956 /* Vector of image_keyword structures describing the format
6957 of valid user-defined image specifications. */
6959 static const struct image_keyword gif_format[GIF_LAST] =
6961 {":type", IMAGE_SYMBOL_VALUE, 1},
6962 {":data", IMAGE_STRING_VALUE, 0},
6963 {":file", IMAGE_STRING_VALUE, 0},
6964 {":ascent", IMAGE_ASCENT_VALUE, 0},
6965 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6966 {":relief", IMAGE_INTEGER_VALUE, 0},
6967 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6968 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6969 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6970 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
6971 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6974 /* Structure describing the image type `gif'. */
6976 static struct image_type gif_type =
6978 &Qgif,
6979 gif_image_p,
6980 gif_load,
6981 gif_clear_image,
6982 NULL
6985 /* Free X resources of GIF image IMG which is used on frame F. */
6987 static void
6988 gif_clear_image (struct frame *f, struct image *img)
6990 /* IMG->data.ptr_val may contain metadata with extension data. */
6991 img->data.lisp_val = Qnil;
6992 x_clear_image (f, img);
6995 /* Return non-zero if OBJECT is a valid GIF image specification. */
6997 static int
6998 gif_image_p (Lisp_Object object)
7000 struct image_keyword fmt[GIF_LAST];
7001 memcpy (fmt, gif_format, sizeof fmt);
7003 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7004 return 0;
7006 /* Must specify either the :data or :file keyword. */
7007 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7010 #endif /* HAVE_GIF */
7012 #ifdef HAVE_GIF
7014 #if defined (HAVE_NTGUI)
7015 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7016 Undefine before redefining to avoid a preprocessor warning. */
7017 #ifdef DrawText
7018 #undef DrawText
7019 #endif
7020 /* avoid conflict with QuickdrawText.h */
7021 #define DrawText gif_DrawText
7022 #include <gif_lib.h>
7023 #undef DrawText
7025 #else /* HAVE_NTGUI */
7027 #include <gif_lib.h>
7029 #endif /* HAVE_NTGUI */
7032 #ifdef HAVE_NTGUI
7034 /* GIF library details. */
7035 DEF_IMGLIB_FN (DGifCloseFile);
7036 DEF_IMGLIB_FN (DGifSlurp);
7037 DEF_IMGLIB_FN (DGifOpen);
7038 DEF_IMGLIB_FN (DGifOpenFileName);
7040 static int
7041 init_gif_functions (Lisp_Object libraries)
7043 HMODULE library;
7045 if (!(library = w32_delayed_load (libraries, Qgif)))
7046 return 0;
7048 LOAD_IMGLIB_FN (library, DGifCloseFile);
7049 LOAD_IMGLIB_FN (library, DGifSlurp);
7050 LOAD_IMGLIB_FN (library, DGifOpen);
7051 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7052 return 1;
7055 #else
7057 #define fn_DGifCloseFile DGifCloseFile
7058 #define fn_DGifSlurp DGifSlurp
7059 #define fn_DGifOpen DGifOpen
7060 #define fn_DGifOpenFileName DGifOpenFileName
7062 #endif /* HAVE_NTGUI */
7064 /* Reading a GIF image from memory
7065 Based on the PNG memory stuff to a certain extent. */
7067 typedef struct
7069 unsigned char *bytes;
7070 size_t len;
7071 int index;
7073 gif_memory_source;
7075 /* Make the current memory source available to gif_read_from_memory.
7076 It's done this way because not all versions of libungif support
7077 a UserData field in the GifFileType structure. */
7078 static gif_memory_source *current_gif_memory_src;
7080 static int
7081 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7083 gif_memory_source *src = current_gif_memory_src;
7085 if (len > src->len - src->index)
7086 return -1;
7088 memcpy (buf, src->bytes + src->index, len);
7089 src->index += len;
7090 return len;
7094 /* Load GIF image IMG for use on frame F. Value is non-zero if
7095 successful. */
7097 static const int interlace_start[] = {0, 4, 2, 1};
7098 static const int interlace_increment[] = {8, 8, 4, 2};
7100 static int
7101 gif_load (struct frame *f, struct image *img)
7103 Lisp_Object file, specified_file;
7104 Lisp_Object specified_data;
7105 int rc, width, height, x, y, i;
7106 XImagePtr ximg;
7107 ColorMapObject *gif_color_map;
7108 unsigned long pixel_colors[256];
7109 GifFileType *gif;
7110 struct gcpro gcpro1;
7111 Lisp_Object image;
7112 int ino, image_height, image_width;
7113 gif_memory_source memsrc;
7114 unsigned char *raster;
7116 specified_file = image_spec_value (img->spec, QCfile, NULL);
7117 specified_data = image_spec_value (img->spec, QCdata, NULL);
7118 file = Qnil;
7119 GCPRO1 (file);
7121 if (NILP (specified_data))
7123 file = x_find_image_file (specified_file);
7124 if (!STRINGP (file))
7126 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7127 UNGCPRO;
7128 return 0;
7131 /* Open the GIF file. Casting return value avoids a GCC warning
7132 on W32. */
7133 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
7134 if (gif == NULL)
7136 image_error ("Cannot open `%s'", file, Qnil);
7137 UNGCPRO;
7138 return 0;
7141 else
7143 /* Read from memory! */
7144 current_gif_memory_src = &memsrc;
7145 memsrc.bytes = SDATA (specified_data);
7146 memsrc.len = SBYTES (specified_data);
7147 memsrc.index = 0;
7149 /* Casting return value avoids a GCC warning on W32. */
7150 gif = (GifFileType *) fn_DGifOpen (&memsrc, gif_read_from_memory);
7151 if (!gif)
7153 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7154 UNGCPRO;
7155 return 0;
7159 /* Before reading entire contents, check the declared image size. */
7160 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7162 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7163 fn_DGifCloseFile (gif);
7164 UNGCPRO;
7165 return 0;
7168 /* Read entire contents. */
7169 rc = fn_DGifSlurp (gif);
7170 if (rc == GIF_ERROR)
7172 image_error ("Error reading `%s'", img->spec, Qnil);
7173 fn_DGifCloseFile (gif);
7174 UNGCPRO;
7175 return 0;
7178 image = image_spec_value (img->spec, QCindex, NULL);
7179 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7180 if (ino >= gif->ImageCount)
7182 image_error ("Invalid image number `%s' in image `%s'",
7183 image, img->spec);
7184 fn_DGifCloseFile (gif);
7185 UNGCPRO;
7186 return 0;
7189 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
7190 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
7191 image_height = gif->SavedImages[ino].ImageDesc.Height;
7192 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
7193 image_width = gif->SavedImages[ino].ImageDesc.Width;
7194 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
7196 width = img->width = max (gif->SWidth,
7197 max (gif->Image.Left + gif->Image.Width,
7198 img->corners[RIGHT_CORNER]));
7199 height = img->height = max (gif->SHeight,
7200 max (gif->Image.Top + gif->Image.Height,
7201 img->corners[BOT_CORNER]));
7203 if (!check_image_size (f, width, height))
7205 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7206 fn_DGifCloseFile (gif);
7207 UNGCPRO;
7208 return 0;
7211 /* Create the X image and pixmap. */
7212 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7214 fn_DGifCloseFile (gif);
7215 UNGCPRO;
7216 return 0;
7219 /* Allocate colors. */
7220 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7221 if (!gif_color_map)
7222 gif_color_map = gif->SColorMap;
7223 init_color_table ();
7224 memset (pixel_colors, 0, sizeof pixel_colors);
7226 if (gif_color_map)
7227 for (i = 0; i < gif_color_map->ColorCount; ++i)
7229 int r = gif_color_map->Colors[i].Red << 8;
7230 int g = gif_color_map->Colors[i].Green << 8;
7231 int b = gif_color_map->Colors[i].Blue << 8;
7232 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7235 #ifdef COLOR_TABLE_SUPPORT
7236 img->colors = colors_in_color_table (&img->ncolors);
7237 free_color_table ();
7238 #endif /* COLOR_TABLE_SUPPORT */
7240 /* Clear the part of the screen image that are not covered by
7241 the image from the GIF file. Full animated GIF support
7242 requires more than can be done here (see the gif89 spec,
7243 disposal methods). Let's simply assume that the part
7244 not covered by a sub-image is in the frame's background color. */
7245 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7246 for (x = 0; x < width; ++x)
7247 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7249 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7250 for (x = 0; x < width; ++x)
7251 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7253 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7255 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7256 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7257 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7258 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7261 /* Read the GIF image into the X image. We use a local variable
7262 `raster' here because RasterBits below is a char *, and invites
7263 problems with bytes >= 0x80. */
7264 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7266 if (gif->SavedImages[ino].ImageDesc.Interlace)
7268 int pass;
7269 int row = interlace_start[0];
7271 pass = 0;
7273 for (y = 0; y < image_height; y++)
7275 if (row >= image_height)
7277 row = interlace_start[++pass];
7278 while (row >= image_height)
7279 row = interlace_start[++pass];
7282 for (x = 0; x < image_width; x++)
7284 int i = raster[(y * image_width) + x];
7285 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7286 row + img->corners[TOP_CORNER], pixel_colors[i]);
7289 row += interlace_increment[pass];
7292 else
7294 for (y = 0; y < image_height; ++y)
7295 for (x = 0; x < image_width; ++x)
7297 int i = raster[y * image_width + x];
7298 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7299 y + img->corners[TOP_CORNER], pixel_colors[i]);
7303 /* Save GIF image extension data for `image-metadata'.
7304 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7305 img->data.lisp_val = Qnil;
7306 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
7308 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
7309 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
7310 /* Append (... FUNCTION "BYTES") */
7311 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7312 Fcons (make_number (ext->Function),
7313 img->data.lisp_val));
7314 img->data.lisp_val = Fcons (Qextension_data,
7315 Fcons (Fnreverse (img->data.lisp_val),
7316 Qnil));
7318 if (gif->ImageCount > 1)
7319 img->data.lisp_val = Fcons (Qcount,
7320 Fcons (make_number (gif->ImageCount),
7321 img->data.lisp_val));
7323 fn_DGifCloseFile (gif);
7325 /* Maybe fill in the background field while we have ximg handy. */
7326 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7327 /* Casting avoids a GCC warning. */
7328 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7330 /* Put the image into the pixmap, then free the X image and its buffer. */
7331 x_put_x_image (f, ximg, img->pixmap, width, height);
7332 x_destroy_x_image (ximg);
7334 UNGCPRO;
7335 return 1;
7338 #else /* !HAVE_GIF */
7340 #ifdef HAVE_NS
7341 static int
7342 gif_load (struct frame *f, struct image *img)
7344 return ns_load_image (f, img,
7345 image_spec_value (img->spec, QCfile, NULL),
7346 image_spec_value (img->spec, QCdata, NULL));
7348 #endif /* HAVE_NS */
7350 #endif /* HAVE_GIF */
7354 /***********************************************************************
7356 ***********************************************************************/
7358 #if defined (HAVE_RSVG)
7360 /* Function prototypes. */
7362 static int svg_image_p (Lisp_Object object);
7363 static int svg_load (struct frame *f, struct image *img);
7365 static int svg_load_image (struct frame *, struct image *,
7366 unsigned char *, unsigned int);
7368 /* The symbol `svg' identifying images of this type. */
7370 Lisp_Object Qsvg;
7372 /* Indices of image specification fields in svg_format, below. */
7374 enum svg_keyword_index
7376 SVG_TYPE,
7377 SVG_DATA,
7378 SVG_FILE,
7379 SVG_ASCENT,
7380 SVG_MARGIN,
7381 SVG_RELIEF,
7382 SVG_ALGORITHM,
7383 SVG_HEURISTIC_MASK,
7384 SVG_MASK,
7385 SVG_BACKGROUND,
7386 SVG_LAST
7389 /* Vector of image_keyword structures describing the format
7390 of valid user-defined image specifications. */
7392 static const struct image_keyword svg_format[SVG_LAST] =
7394 {":type", IMAGE_SYMBOL_VALUE, 1},
7395 {":data", IMAGE_STRING_VALUE, 0},
7396 {":file", IMAGE_STRING_VALUE, 0},
7397 {":ascent", IMAGE_ASCENT_VALUE, 0},
7398 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7399 {":relief", IMAGE_INTEGER_VALUE, 0},
7400 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7401 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7402 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7403 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7406 /* Structure describing the image type `svg'. Its the same type of
7407 structure defined for all image formats, handled by emacs image
7408 functions. See struct image_type in dispextern.h. */
7410 static struct image_type svg_type =
7412 /* An identifier showing that this is an image structure for the SVG format. */
7413 &Qsvg,
7414 /* Handle to a function that can be used to identify a SVG file. */
7415 svg_image_p,
7416 /* Handle to function used to load a SVG file. */
7417 svg_load,
7418 /* Handle to function to free sresources for SVG. */
7419 x_clear_image,
7420 /* An internal field to link to the next image type in a list of
7421 image types, will be filled in when registering the format. */
7422 NULL
7426 /* Return non-zero if OBJECT is a valid SVG image specification. Do
7427 this by calling parse_image_spec and supplying the keywords that
7428 identify the SVG format. */
7430 static int
7431 svg_image_p (Lisp_Object object)
7433 struct image_keyword fmt[SVG_LAST];
7434 memcpy (fmt, svg_format, sizeof fmt);
7436 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
7437 return 0;
7439 /* Must specify either the :data or :file keyword. */
7440 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
7443 #include <librsvg/rsvg.h>
7445 #ifdef HAVE_NTGUI
7447 /* SVG library functions. */
7448 DEF_IMGLIB_FN (rsvg_handle_new);
7449 DEF_IMGLIB_FN (rsvg_handle_get_dimensions);
7450 DEF_IMGLIB_FN (rsvg_handle_write);
7451 DEF_IMGLIB_FN (rsvg_handle_close);
7452 DEF_IMGLIB_FN (rsvg_handle_get_pixbuf);
7453 DEF_IMGLIB_FN (rsvg_handle_free);
7455 DEF_IMGLIB_FN (gdk_pixbuf_get_width);
7456 DEF_IMGLIB_FN (gdk_pixbuf_get_height);
7457 DEF_IMGLIB_FN (gdk_pixbuf_get_pixels);
7458 DEF_IMGLIB_FN (gdk_pixbuf_get_rowstride);
7459 DEF_IMGLIB_FN (gdk_pixbuf_get_colorspace);
7460 DEF_IMGLIB_FN (gdk_pixbuf_get_n_channels);
7461 DEF_IMGLIB_FN (gdk_pixbuf_get_has_alpha);
7462 DEF_IMGLIB_FN (gdk_pixbuf_get_bits_per_sample);
7464 DEF_IMGLIB_FN (g_type_init);
7465 DEF_IMGLIB_FN (g_object_unref);
7466 DEF_IMGLIB_FN (g_error_free);
7468 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
7470 static int
7471 init_svg_functions (Lisp_Object libraries)
7473 HMODULE library, gdklib, glib, gobject;
7475 if (!(glib = w32_delayed_load (libraries, Qglib))
7476 || !(gobject = w32_delayed_load (libraries, Qgobject))
7477 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
7478 || !(library = w32_delayed_load (libraries, Qsvg)))
7479 return 0;
7481 LOAD_IMGLIB_FN (library, rsvg_handle_new);
7482 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
7483 LOAD_IMGLIB_FN (library, rsvg_handle_write);
7484 LOAD_IMGLIB_FN (library, rsvg_handle_close);
7485 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
7486 LOAD_IMGLIB_FN (library, rsvg_handle_free);
7488 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
7489 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
7490 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
7491 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
7492 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
7493 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
7494 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
7495 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
7497 LOAD_IMGLIB_FN (gobject, g_type_init);
7498 LOAD_IMGLIB_FN (gobject, g_object_unref);
7499 LOAD_IMGLIB_FN (glib, g_error_free);
7501 return 1;
7504 #else
7505 /* The following aliases for library functions allow dynamic loading
7506 to be used on some platforms. */
7507 #define fn_rsvg_handle_new rsvg_handle_new
7508 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
7509 #define fn_rsvg_handle_write rsvg_handle_write
7510 #define fn_rsvg_handle_close rsvg_handle_close
7511 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
7512 #define fn_rsvg_handle_free rsvg_handle_free
7514 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
7515 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
7516 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
7517 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
7518 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
7519 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
7520 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
7521 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
7523 #define fn_g_type_init g_type_init
7524 #define fn_g_object_unref g_object_unref
7525 #define fn_g_error_free g_error_free
7526 #endif /* !HAVE_NTGUI */
7528 /* Load SVG image IMG for use on frame F. Value is non-zero if
7529 successful. this function will go into the svg_type structure, and
7530 the prototype thus needs to be compatible with that structure. */
7532 static int
7533 svg_load (struct frame *f, struct image *img)
7535 int success_p = 0;
7536 Lisp_Object file_name;
7538 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7539 file_name = image_spec_value (img->spec, QCfile, NULL);
7540 if (STRINGP (file_name))
7542 Lisp_Object file;
7543 unsigned char *contents;
7544 int size;
7545 struct gcpro gcpro1;
7547 file = x_find_image_file (file_name);
7548 GCPRO1 (file);
7549 if (!STRINGP (file))
7551 image_error ("Cannot find image file `%s'", file_name, Qnil);
7552 UNGCPRO;
7553 return 0;
7556 /* Read the entire file into memory. */
7557 contents = slurp_file (SDATA (file), &size);
7558 if (contents == NULL)
7560 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
7561 UNGCPRO;
7562 return 0;
7564 /* If the file was slurped into memory properly, parse it. */
7565 success_p = svg_load_image (f, img, contents, size);
7566 xfree (contents);
7567 UNGCPRO;
7569 /* Else its not a file, its a lisp object. Load the image from a
7570 lisp object rather than a file. */
7571 else
7573 Lisp_Object data;
7575 data = image_spec_value (img->spec, QCdata, NULL);
7576 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
7579 return success_p;
7582 /* svg_load_image is a helper function for svg_load, which does the
7583 actual loading given contents and size, apart from frame and image
7584 structures, passed from svg_load.
7586 Uses librsvg to do most of the image processing.
7588 Returns non-zero when successful. */
7589 static int
7590 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
7591 struct image *img, /* Pointer to emacs image structure. */
7592 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
7593 unsigned int size) /* Size of data in bytes. */
7595 RsvgHandle *rsvg_handle;
7596 RsvgDimensionData dimension_data;
7597 GError *error = NULL;
7598 GdkPixbuf *pixbuf;
7599 int width;
7600 int height;
7601 const guint8 *pixels;
7602 int rowstride;
7603 XImagePtr ximg;
7604 Lisp_Object specified_bg;
7605 XColor background;
7606 int x;
7607 int y;
7609 /* g_type_init is a glib function that must be called prior to using
7610 gnome type library functions. */
7611 fn_g_type_init ();
7612 /* Make a handle to a new rsvg object. */
7613 rsvg_handle = (RsvgHandle *) fn_rsvg_handle_new ();
7615 /* Parse the contents argument and fill in the rsvg_handle. */
7616 fn_rsvg_handle_write (rsvg_handle, contents, size, &error);
7617 if (error) goto rsvg_error;
7619 /* The parsing is complete, rsvg_handle is ready to used, close it
7620 for further writes. */
7621 fn_rsvg_handle_close (rsvg_handle, &error);
7622 if (error) goto rsvg_error;
7624 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
7625 if (! check_image_size (f, dimension_data.width, dimension_data.height))
7627 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7628 goto rsvg_error;
7631 /* We can now get a valid pixel buffer from the svg file, if all
7632 went ok. */
7633 pixbuf = (GdkPixbuf *) fn_rsvg_handle_get_pixbuf (rsvg_handle);
7634 if (!pixbuf) goto rsvg_error;
7635 fn_g_object_unref (rsvg_handle);
7637 /* Extract some meta data from the svg handle. */
7638 width = fn_gdk_pixbuf_get_width (pixbuf);
7639 height = fn_gdk_pixbuf_get_height (pixbuf);
7640 pixels = (const guint8 *) fn_gdk_pixbuf_get_pixels (pixbuf);
7641 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
7643 /* Validate the svg meta data. */
7644 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
7645 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
7646 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
7647 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
7649 /* Try to create a x pixmap to hold the svg pixmap. */
7650 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7652 fn_g_object_unref (pixbuf);
7653 return 0;
7656 init_color_table ();
7658 /* Handle alpha channel by combining the image with a background
7659 color. */
7660 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7661 if (!STRINGP (specified_bg)
7662 || !x_defined_color (f, SDATA (specified_bg), &background, 0))
7664 #ifndef HAVE_NS
7665 background.pixel = FRAME_BACKGROUND_PIXEL (f);
7666 x_query_color (f, &background);
7667 #else
7668 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
7669 #endif
7672 /* SVG pixmaps specify transparency in the last byte, so right
7673 shift 8 bits to get rid of it, since emacs doesn't support
7674 transparency. */
7675 background.red >>= 8;
7676 background.green >>= 8;
7677 background.blue >>= 8;
7679 /* This loop handles opacity values, since Emacs assumes
7680 non-transparent images. Each pixel must be "flattened" by
7681 calculating the resulting color, given the transparency of the
7682 pixel, and the image background color. */
7683 for (y = 0; y < height; ++y)
7685 for (x = 0; x < width; ++x)
7687 unsigned red;
7688 unsigned green;
7689 unsigned blue;
7690 unsigned opacity;
7692 red = *pixels++;
7693 green = *pixels++;
7694 blue = *pixels++;
7695 opacity = *pixels++;
7697 red = ((red * opacity)
7698 + (background.red * ((1 << 8) - opacity)));
7699 green = ((green * opacity)
7700 + (background.green * ((1 << 8) - opacity)));
7701 blue = ((blue * opacity)
7702 + (background.blue * ((1 << 8) - opacity)));
7704 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
7707 pixels += rowstride - 4 * width;
7710 #ifdef COLOR_TABLE_SUPPORT
7711 /* Remember colors allocated for this image. */
7712 img->colors = colors_in_color_table (&img->ncolors);
7713 free_color_table ();
7714 #endif /* COLOR_TABLE_SUPPORT */
7716 fn_g_object_unref (pixbuf);
7718 img->width = width;
7719 img->height = height;
7721 /* Maybe fill in the background field while we have ximg handy.
7722 Casting avoids a GCC warning. */
7723 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7725 /* Put the image into the pixmap, then free the X image and its
7726 buffer. */
7727 x_put_x_image (f, ximg, img->pixmap, width, height);
7728 x_destroy_x_image (ximg);
7730 return 1;
7732 rsvg_error:
7733 fn_g_object_unref (rsvg_handle);
7734 /* FIXME: Use error->message so the user knows what is the actual
7735 problem with the image. */
7736 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
7737 fn_g_error_free (error);
7738 return 0;
7741 #endif /* defined (HAVE_RSVG) */
7746 /***********************************************************************
7747 Ghostscript
7748 ***********************************************************************/
7750 #ifdef HAVE_X_WINDOWS
7751 #define HAVE_GHOSTSCRIPT 1
7752 #endif /* HAVE_X_WINDOWS */
7754 /* The symbol `postscript' identifying images of this type. */
7756 Lisp_Object Qpostscript;
7758 #ifdef HAVE_GHOSTSCRIPT
7760 static int gs_image_p (Lisp_Object object);
7761 static int gs_load (struct frame *f, struct image *img);
7762 static void gs_clear_image (struct frame *f, struct image *img);
7764 /* Keyword symbols. */
7766 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
7768 /* Indices of image specification fields in gs_format, below. */
7770 enum gs_keyword_index
7772 GS_TYPE,
7773 GS_PT_WIDTH,
7774 GS_PT_HEIGHT,
7775 GS_FILE,
7776 GS_LOADER,
7777 GS_BOUNDING_BOX,
7778 GS_ASCENT,
7779 GS_MARGIN,
7780 GS_RELIEF,
7781 GS_ALGORITHM,
7782 GS_HEURISTIC_MASK,
7783 GS_MASK,
7784 GS_BACKGROUND,
7785 GS_LAST
7788 /* Vector of image_keyword structures describing the format
7789 of valid user-defined image specifications. */
7791 static const struct image_keyword gs_format[GS_LAST] =
7793 {":type", IMAGE_SYMBOL_VALUE, 1},
7794 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7795 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7796 {":file", IMAGE_STRING_VALUE, 1},
7797 {":loader", IMAGE_FUNCTION_VALUE, 0},
7798 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
7799 {":ascent", IMAGE_ASCENT_VALUE, 0},
7800 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7801 {":relief", IMAGE_INTEGER_VALUE, 0},
7802 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7803 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7804 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7805 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7808 /* Structure describing the image type `ghostscript'. */
7810 static struct image_type gs_type =
7812 &Qpostscript,
7813 gs_image_p,
7814 gs_load,
7815 gs_clear_image,
7816 NULL
7820 /* Free X resources of Ghostscript image IMG which is used on frame F. */
7822 static void
7823 gs_clear_image (struct frame *f, struct image *img)
7825 /* IMG->data.ptr_val may contain a recorded colormap. */
7826 xfree (img->data.ptr_val);
7827 x_clear_image (f, img);
7831 /* Return non-zero if OBJECT is a valid Ghostscript image
7832 specification. */
7834 static int
7835 gs_image_p (Lisp_Object object)
7837 struct image_keyword fmt[GS_LAST];
7838 Lisp_Object tem;
7839 int i;
7841 memcpy (fmt, gs_format, sizeof fmt);
7843 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
7844 return 0;
7846 /* Bounding box must be a list or vector containing 4 integers. */
7847 tem = fmt[GS_BOUNDING_BOX].value;
7848 if (CONSP (tem))
7850 for (i = 0; i < 4; ++i, tem = XCDR (tem))
7851 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
7852 return 0;
7853 if (!NILP (tem))
7854 return 0;
7856 else if (VECTORP (tem))
7858 if (XVECTOR (tem)->size != 4)
7859 return 0;
7860 for (i = 0; i < 4; ++i)
7861 if (!INTEGERP (XVECTOR (tem)->contents[i]))
7862 return 0;
7864 else
7865 return 0;
7867 return 1;
7871 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
7872 if successful. */
7874 static int
7875 gs_load (struct frame *f, struct image *img)
7877 char buffer[100];
7878 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
7879 struct gcpro gcpro1, gcpro2;
7880 Lisp_Object frame;
7881 double in_width, in_height;
7882 Lisp_Object pixel_colors = Qnil;
7884 /* Compute pixel size of pixmap needed from the given size in the
7885 image specification. Sizes in the specification are in pt. 1 pt
7886 = 1/72 in, xdpi and ydpi are stored in the frame's X display
7887 info. */
7888 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
7889 in_width = XFASTINT (pt_width) / 72.0;
7890 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
7891 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
7892 in_height = XFASTINT (pt_height) / 72.0;
7893 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
7895 if (!check_image_size (f, img->width, img->height))
7897 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7898 return 0;
7901 /* Create the pixmap. */
7902 xassert (img->pixmap == NO_PIXMAP);
7904 /* Only W32 version did BLOCK_INPUT here. ++kfs */
7905 BLOCK_INPUT;
7906 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7907 img->width, img->height,
7908 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
7909 UNBLOCK_INPUT;
7911 if (!img->pixmap)
7913 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
7914 return 0;
7917 /* Call the loader to fill the pixmap. It returns a process object
7918 if successful. We do not record_unwind_protect here because
7919 other places in redisplay like calling window scroll functions
7920 don't either. Let the Lisp loader use `unwind-protect' instead. */
7921 GCPRO2 (window_and_pixmap_id, pixel_colors);
7923 sprintf (buffer, "%lu %lu",
7924 (unsigned long) FRAME_X_WINDOW (f),
7925 (unsigned long) img->pixmap);
7926 window_and_pixmap_id = build_string (buffer);
7928 sprintf (buffer, "%lu %lu",
7929 FRAME_FOREGROUND_PIXEL (f),
7930 FRAME_BACKGROUND_PIXEL (f));
7931 pixel_colors = build_string (buffer);
7933 XSETFRAME (frame, f);
7934 loader = image_spec_value (img->spec, QCloader, NULL);
7935 if (NILP (loader))
7936 loader = intern ("gs-load-image");
7938 img->data.lisp_val = call6 (loader, frame, img->spec,
7939 make_number (img->width),
7940 make_number (img->height),
7941 window_and_pixmap_id,
7942 pixel_colors);
7943 UNGCPRO;
7944 return PROCESSP (img->data.lisp_val);
7948 /* Kill the Ghostscript process that was started to fill PIXMAP on
7949 frame F. Called from XTread_socket when receiving an event
7950 telling Emacs that Ghostscript has finished drawing. */
7952 void
7953 x_kill_gs_process (Pixmap pixmap, struct frame *f)
7955 struct image_cache *c = FRAME_IMAGE_CACHE (f);
7956 int class, i;
7957 struct image *img;
7959 /* Find the image containing PIXMAP. */
7960 for (i = 0; i < c->used; ++i)
7961 if (c->images[i]->pixmap == pixmap)
7962 break;
7964 /* Should someone in between have cleared the image cache, for
7965 instance, give up. */
7966 if (i == c->used)
7967 return;
7969 /* Kill the GS process. We should have found PIXMAP in the image
7970 cache and its image should contain a process object. */
7971 img = c->images[i];
7972 xassert (PROCESSP (img->data.lisp_val));
7973 Fkill_process (img->data.lisp_val, Qnil);
7974 img->data.lisp_val = Qnil;
7976 #if defined (HAVE_X_WINDOWS)
7978 /* On displays with a mutable colormap, figure out the colors
7979 allocated for the image by looking at the pixels of an XImage for
7980 img->pixmap. */
7981 class = FRAME_X_VISUAL (f)->class;
7982 if (class != StaticColor && class != StaticGray && class != TrueColor)
7984 XImagePtr ximg;
7986 BLOCK_INPUT;
7988 /* Try to get an XImage for img->pixmep. */
7989 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
7990 0, 0, img->width, img->height, ~0, ZPixmap);
7991 if (ximg)
7993 int x, y;
7995 /* Initialize the color table. */
7996 init_color_table ();
7998 /* For each pixel of the image, look its color up in the
7999 color table. After having done so, the color table will
8000 contain an entry for each color used by the image. */
8001 for (y = 0; y < img->height; ++y)
8002 for (x = 0; x < img->width; ++x)
8004 unsigned long pixel = XGetPixel (ximg, x, y);
8005 lookup_pixel_color (f, pixel);
8008 /* Record colors in the image. Free color table and XImage. */
8009 #ifdef COLOR_TABLE_SUPPORT
8010 img->colors = colors_in_color_table (&img->ncolors);
8011 free_color_table ();
8012 #endif
8013 XDestroyImage (ximg);
8015 #if 0 /* This doesn't seem to be the case. If we free the colors
8016 here, we get a BadAccess later in x_clear_image when
8017 freeing the colors. */
8018 /* We have allocated colors once, but Ghostscript has also
8019 allocated colors on behalf of us. So, to get the
8020 reference counts right, free them once. */
8021 if (img->ncolors)
8022 x_free_colors (f, img->colors, img->ncolors);
8023 #endif
8025 else
8026 image_error ("Cannot get X image of `%s'; colors will not be freed",
8027 img->spec, Qnil);
8029 UNBLOCK_INPUT;
8031 #endif /* HAVE_X_WINDOWS */
8033 /* Now that we have the pixmap, compute mask and transform the
8034 image if requested. */
8035 BLOCK_INPUT;
8036 postprocess_image (f, img);
8037 UNBLOCK_INPUT;
8040 #endif /* HAVE_GHOSTSCRIPT */
8043 /***********************************************************************
8044 Tests
8045 ***********************************************************************/
8047 #if GLYPH_DEBUG
8049 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8050 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8051 (Lisp_Object spec)
8053 return valid_image_p (spec) ? Qt : Qnil;
8057 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8058 (Lisp_Object spec)
8060 int id = -1;
8062 if (valid_image_p (spec))
8063 id = lookup_image (SELECTED_FRAME (), spec);
8065 debug_print (spec);
8066 return make_number (id);
8069 #endif /* GLYPH_DEBUG != 0 */
8072 /***********************************************************************
8073 Initialization
8074 ***********************************************************************/
8076 #ifdef HAVE_NTGUI
8077 /* Image types that rely on external libraries are loaded dynamically
8078 if the library is available. */
8079 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8080 define_image_type (image_type, init_lib_fn (libraries))
8081 #else
8082 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8083 define_image_type (image_type, 1)
8084 #endif /* HAVE_NTGUI */
8086 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8087 doc: /* Initialize image library implementing image type TYPE.
8088 Return non-nil if TYPE is a supported image type.
8090 Image types pbm and xbm are prebuilt; other types are loaded here.
8091 Libraries to load are specified in alist LIBRARIES (usually, the value
8092 of `image-library-alist', which see). */)
8093 (Lisp_Object type, Lisp_Object libraries)
8095 Lisp_Object tested;
8097 /* Don't try to reload the library. */
8098 tested = Fassq (type, Vimage_type_cache);
8099 if (CONSP (tested))
8100 return XCDR (tested);
8102 #if defined (HAVE_XPM) || defined (HAVE_NS)
8103 if (EQ (type, Qxpm))
8104 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8105 #endif
8107 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8108 if (EQ (type, Qjpeg))
8109 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8110 #endif
8112 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8113 if (EQ (type, Qtiff))
8114 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8115 #endif
8117 #if defined (HAVE_GIF) || defined (HAVE_NS)
8118 if (EQ (type, Qgif))
8119 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8120 #endif
8122 #if defined (HAVE_PNG) || defined (HAVE_NS)
8123 if (EQ (type, Qpng))
8124 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8125 #endif
8127 #if defined (HAVE_RSVG)
8128 if (EQ (type, Qsvg))
8129 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
8130 #endif
8132 #ifdef HAVE_GHOSTSCRIPT
8133 if (EQ (type, Qpostscript))
8134 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8135 #endif
8137 /* If the type is not recognized, avoid testing it ever again. */
8138 CACHE_IMAGE_TYPE (type, Qnil);
8139 return Qnil;
8142 void
8143 syms_of_image (void)
8145 extern Lisp_Object Qrisky_local_variable; /* Syms_of_xdisp has already run. */
8147 /* Initialize this only once, since that's what we do with Vimage_types
8148 and they are supposed to be in sync. Initializing here gives correct
8149 operation on GNU/Linux of calling dump-emacs after loading some images. */
8150 image_types = NULL;
8152 /* Must be defined now becase we're going to update it below, while
8153 defining the supported image types. */
8154 DEFVAR_LISP ("image-types", &Vimage_types,
8155 doc: /* List of potentially supported image types.
8156 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8157 To check whether it is really supported, use `image-type-available-p'. */);
8158 Vimage_types = Qnil;
8160 DEFVAR_LISP ("image-library-alist", &Vimage_library_alist,
8161 doc: /* Alist of image types vs external libraries needed to display them.
8163 Each element is a list (IMAGE-TYPE LIBRARY...), where the car is a symbol
8164 representing a supported image type, and the rest are strings giving
8165 alternate filenames for the corresponding external libraries.
8167 Emacs tries to load the libraries in the order they appear on the
8168 list; if none is loaded, the running session of Emacs won't
8169 support the image type. Types 'pbm and 'xbm don't need to be
8170 listed; they are always supported. */);
8171 Vimage_library_alist = Qnil;
8172 Fput (intern_c_string ("image-library-alist"), Qrisky_local_variable, Qt);
8174 DEFVAR_LISP ("max-image-size", &Vmax_image_size,
8175 doc: /* Maximum size of images.
8176 Emacs will not load an image into memory if its pixel width or
8177 pixel height exceeds this limit.
8179 If the value is an integer, it directly specifies the maximum
8180 image height and width, measured in pixels. If it is a floating
8181 point number, it specifies the maximum image height and width
8182 as a ratio to the frame height and width. If the value is
8183 non-numeric, there is no explicit limit on the size of images. */);
8184 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8186 Vimage_type_cache = Qnil;
8187 staticpro (&Vimage_type_cache);
8189 Qpbm = intern_c_string ("pbm");
8190 staticpro (&Qpbm);
8191 ADD_IMAGE_TYPE (Qpbm);
8193 Qxbm = intern_c_string ("xbm");
8194 staticpro (&Qxbm);
8195 ADD_IMAGE_TYPE (Qxbm);
8197 define_image_type (&xbm_type, 1);
8198 define_image_type (&pbm_type, 1);
8200 Qcount = intern_c_string ("count");
8201 staticpro (&Qcount);
8202 Qextension_data = intern_c_string ("extension-data");
8203 staticpro (&Qextension_data);
8205 QCascent = intern_c_string (":ascent");
8206 staticpro (&QCascent);
8207 QCmargin = intern_c_string (":margin");
8208 staticpro (&QCmargin);
8209 QCrelief = intern_c_string (":relief");
8210 staticpro (&QCrelief);
8211 QCconversion = intern_c_string (":conversion");
8212 staticpro (&QCconversion);
8213 QCcolor_symbols = intern_c_string (":color-symbols");
8214 staticpro (&QCcolor_symbols);
8215 QCheuristic_mask = intern_c_string (":heuristic-mask");
8216 staticpro (&QCheuristic_mask);
8217 QCindex = intern_c_string (":index");
8218 staticpro (&QCindex);
8219 QCmatrix = intern_c_string (":matrix");
8220 staticpro (&QCmatrix);
8221 QCcolor_adjustment = intern_c_string (":color-adjustment");
8222 staticpro (&QCcolor_adjustment);
8223 QCmask = intern_c_string (":mask");
8224 staticpro (&QCmask);
8226 Qlaplace = intern_c_string ("laplace");
8227 staticpro (&Qlaplace);
8228 Qemboss = intern_c_string ("emboss");
8229 staticpro (&Qemboss);
8230 Qedge_detection = intern_c_string ("edge-detection");
8231 staticpro (&Qedge_detection);
8232 Qheuristic = intern_c_string ("heuristic");
8233 staticpro (&Qheuristic);
8235 Qpostscript = intern_c_string ("postscript");
8236 staticpro (&Qpostscript);
8237 #ifdef HAVE_GHOSTSCRIPT
8238 ADD_IMAGE_TYPE (Qpostscript);
8239 QCloader = intern_c_string (":loader");
8240 staticpro (&QCloader);
8241 QCbounding_box = intern_c_string (":bounding-box");
8242 staticpro (&QCbounding_box);
8243 QCpt_width = intern_c_string (":pt-width");
8244 staticpro (&QCpt_width);
8245 QCpt_height = intern_c_string (":pt-height");
8246 staticpro (&QCpt_height);
8247 #endif /* HAVE_GHOSTSCRIPT */
8249 #if defined (HAVE_XPM) || defined (HAVE_NS)
8250 Qxpm = intern_c_string ("xpm");
8251 staticpro (&Qxpm);
8252 ADD_IMAGE_TYPE (Qxpm);
8253 #endif
8255 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8256 Qjpeg = intern_c_string ("jpeg");
8257 staticpro (&Qjpeg);
8258 ADD_IMAGE_TYPE (Qjpeg);
8259 #endif
8261 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8262 Qtiff = intern_c_string ("tiff");
8263 staticpro (&Qtiff);
8264 ADD_IMAGE_TYPE (Qtiff);
8265 #endif
8267 #if defined (HAVE_GIF) || defined (HAVE_NS)
8268 Qgif = intern_c_string ("gif");
8269 staticpro (&Qgif);
8270 ADD_IMAGE_TYPE (Qgif);
8271 #endif
8273 #if defined (HAVE_PNG) || defined (HAVE_NS)
8274 Qpng = intern_c_string ("png");
8275 staticpro (&Qpng);
8276 ADD_IMAGE_TYPE (Qpng);
8277 #endif
8279 #if defined (HAVE_RSVG)
8280 Qsvg = intern_c_string ("svg");
8281 staticpro (&Qsvg);
8282 ADD_IMAGE_TYPE (Qsvg);
8283 #ifdef HAVE_NTGUI
8284 /* Other libraries used directly by svg code. */
8285 Qgdk_pixbuf = intern_c_string ("gdk-pixbuf");
8286 staticpro (&Qgdk_pixbuf);
8287 Qglib = intern_c_string ("glib");
8288 staticpro (&Qglib);
8289 Qgobject = intern_c_string ("gobject");
8290 staticpro (&Qgobject);
8291 #endif /* HAVE_NTGUI */
8292 #endif /* HAVE_RSVG */
8294 defsubr (&Sinit_image_library);
8295 defsubr (&Sclear_image_cache);
8296 defsubr (&Simage_flush);
8297 defsubr (&Simage_size);
8298 defsubr (&Simage_mask_p);
8299 defsubr (&Simage_metadata);
8301 #if GLYPH_DEBUG
8302 defsubr (&Simagep);
8303 defsubr (&Slookup_image);
8304 #endif
8306 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
8307 doc: /* Non-nil means always draw a cross over disabled images.
8308 Disabled images are those having a `:conversion disabled' property.
8309 A cross is always drawn on black & white displays. */);
8310 cross_disabled_images = 0;
8312 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
8313 doc: /* List of directories to search for window system bitmap files. */);
8314 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8316 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
8317 doc: /* Maximum time after which images are removed from the cache.
8318 When an image has not been displayed this many seconds, Emacs
8319 automatically removes it from the image cache. If the cache contains
8320 a large number of images, the actual eviction time may be shorter.
8321 The value can also be nil, meaning the cache is never cleared.
8323 The function `clear-image-cache' disregards this variable. */);
8324 Vimage_cache_eviction_delay = make_number (300);
8327 void
8328 init_image (void)
8332 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
8333 (do not change this comment) */