Merge from trunk
[emacs.git] / src / image.c
blob916fcfe8178e891444088d4d3a544bea40b1dbcc
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;
129 /* The symbol `postscript' identifying images of this type. */
131 Lisp_Object Qpostscript;
133 static void x_disable_image (struct frame *, struct image *);
134 static void x_edge_detection (struct frame *, struct image *, Lisp_Object,
135 Lisp_Object);
137 static void init_color_table (void);
138 static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
139 #ifdef COLOR_TABLE_SUPPORT
140 static void free_color_table (void);
141 static unsigned long *colors_in_color_table (int *n);
142 static unsigned long lookup_pixel_color (struct frame *f, unsigned long p);
143 #endif
145 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
146 id, which is just an int that this section returns. Bitmaps are
147 reference counted so they can be shared among frames.
149 Bitmap indices are guaranteed to be > 0, so a negative number can
150 be used to indicate no bitmap.
152 If you use x_create_bitmap_from_data, then you must keep track of
153 the bitmaps yourself. That is, creating a bitmap from the same
154 data more than once will not be caught. */
156 #ifdef HAVE_NS
157 XImagePtr
158 XGetImage (Display *display, Pixmap pixmap, int x, int y,
159 unsigned int width, unsigned int height,
160 unsigned long plane_mask, int format)
162 /* TODO: not sure what this function is supposed to do.. */
163 ns_retain_object (pixmap);
164 return pixmap;
167 /* use with imgs created by ns_image_for_XPM */
168 unsigned long
169 XGetPixel (XImagePtr ximage, int x, int y)
171 return ns_get_pixel (ximage, x, y);
174 /* use with imgs created by ns_image_for_XPM; alpha set to 1;
175 pixel is assumed to be in form RGB */
176 void
177 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
179 ns_put_pixel (ximage, x, y, pixel);
181 #endif /* HAVE_NS */
184 /* Functions to access the contents of a bitmap, given an id. */
187 x_bitmap_height (FRAME_PTR f, int id)
189 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
193 x_bitmap_width (FRAME_PTR f, int id)
195 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
198 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
200 x_bitmap_pixmap (FRAME_PTR f, int id)
202 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
204 #endif
206 #ifdef HAVE_X_WINDOWS
208 x_bitmap_mask (FRAME_PTR f, int id)
210 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
212 #endif
214 /* Allocate a new bitmap record. Returns index of new record. */
216 static int
217 x_allocate_bitmap_record (FRAME_PTR f)
219 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
220 int i;
222 if (dpyinfo->bitmaps == NULL)
224 dpyinfo->bitmaps_size = 10;
225 dpyinfo->bitmaps
226 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
227 dpyinfo->bitmaps_last = 1;
228 return 1;
231 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
232 return ++dpyinfo->bitmaps_last;
234 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
235 if (dpyinfo->bitmaps[i].refcount == 0)
236 return i + 1;
238 dpyinfo->bitmaps_size *= 2;
239 dpyinfo->bitmaps
240 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
241 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
242 return ++dpyinfo->bitmaps_last;
245 /* Add one reference to the reference count of the bitmap with id ID. */
247 void
248 x_reference_bitmap (FRAME_PTR f, int id)
250 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
253 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
256 x_create_bitmap_from_data (struct frame *f, char *bits, unsigned int width, unsigned int height)
258 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
259 int id;
261 #ifdef HAVE_X_WINDOWS
262 Pixmap bitmap;
263 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
264 bits, width, height);
265 if (! bitmap)
266 return -1;
267 #endif /* HAVE_X_WINDOWS */
269 #ifdef HAVE_NTGUI
270 Pixmap bitmap;
271 bitmap = CreateBitmap (width, height,
272 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
273 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
274 bits);
275 if (! bitmap)
276 return -1;
277 #endif /* HAVE_NTGUI */
279 #ifdef HAVE_NS
280 void *bitmap = ns_image_from_XBM (bits, width, height);
281 if (!bitmap)
282 return -1;
283 #endif
285 id = x_allocate_bitmap_record (f);
287 #ifdef HAVE_NS
288 dpyinfo->bitmaps[id - 1].img = bitmap;
289 dpyinfo->bitmaps[id - 1].depth = 1;
290 #endif
292 dpyinfo->bitmaps[id - 1].file = NULL;
293 dpyinfo->bitmaps[id - 1].height = height;
294 dpyinfo->bitmaps[id - 1].width = width;
295 dpyinfo->bitmaps[id - 1].refcount = 1;
297 #ifdef HAVE_X_WINDOWS
298 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
299 dpyinfo->bitmaps[id - 1].have_mask = 0;
300 dpyinfo->bitmaps[id - 1].depth = 1;
301 #endif /* HAVE_X_WINDOWS */
303 #ifdef HAVE_NTGUI
304 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
305 dpyinfo->bitmaps[id - 1].hinst = NULL;
306 dpyinfo->bitmaps[id - 1].depth = 1;
307 #endif /* HAVE_NTGUI */
309 return id;
312 /* Create bitmap from file FILE for frame F. */
315 x_create_bitmap_from_file (struct frame *f, Lisp_Object file)
317 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
319 #ifdef HAVE_NTGUI
320 return -1; /* W32_TODO : bitmap support */
321 #endif /* HAVE_NTGUI */
323 #ifdef HAVE_NS
324 int id;
325 void *bitmap = ns_image_from_file (file);
327 if (!bitmap)
328 return -1;
331 id = x_allocate_bitmap_record (f);
332 dpyinfo->bitmaps[id - 1].img = bitmap;
333 dpyinfo->bitmaps[id - 1].refcount = 1;
334 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
335 dpyinfo->bitmaps[id - 1].depth = 1;
336 dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
337 dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
338 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
339 return id;
340 #endif
342 #ifdef HAVE_X_WINDOWS
343 unsigned int width, height;
344 Pixmap bitmap;
345 int xhot, yhot, result, id;
346 Lisp_Object found;
347 int fd;
348 char *filename;
350 /* Look for an existing bitmap with the same name. */
351 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
353 if (dpyinfo->bitmaps[id].refcount
354 && dpyinfo->bitmaps[id].file
355 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
357 ++dpyinfo->bitmaps[id].refcount;
358 return id + 1;
362 /* Search bitmap-file-path for the file, if appropriate. */
363 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
364 if (fd < 0)
365 return -1;
366 emacs_close (fd);
368 filename = (char *) SDATA (found);
370 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
371 filename, &width, &height, &bitmap, &xhot, &yhot);
372 if (result != BitmapSuccess)
373 return -1;
375 id = x_allocate_bitmap_record (f);
376 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
377 dpyinfo->bitmaps[id - 1].have_mask = 0;
378 dpyinfo->bitmaps[id - 1].refcount = 1;
379 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
380 dpyinfo->bitmaps[id - 1].depth = 1;
381 dpyinfo->bitmaps[id - 1].height = height;
382 dpyinfo->bitmaps[id - 1].width = width;
383 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
385 return id;
386 #endif /* HAVE_X_WINDOWS */
389 /* Free bitmap B. */
391 static void
392 free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
394 #ifdef HAVE_X_WINDOWS
395 XFreePixmap (dpyinfo->display, bm->pixmap);
396 if (bm->have_mask)
397 XFreePixmap (dpyinfo->display, bm->mask);
398 #endif /* HAVE_X_WINDOWS */
400 #ifdef HAVE_NTGUI
401 DeleteObject (bm->pixmap);
402 #endif /* HAVE_NTGUI */
404 #ifdef HAVE_NS
405 ns_release_object (bm->img);
406 #endif
408 if (bm->file)
410 xfree (bm->file);
411 bm->file = NULL;
415 /* Remove reference to bitmap with id number ID. */
417 void
418 x_destroy_bitmap (FRAME_PTR f, int id)
420 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
422 if (id > 0)
424 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
426 if (--bm->refcount == 0)
428 BLOCK_INPUT;
429 free_bitmap_record (dpyinfo, bm);
430 UNBLOCK_INPUT;
435 /* Free all the bitmaps for the display specified by DPYINFO. */
437 void
438 x_destroy_all_bitmaps (Display_Info *dpyinfo)
440 int i;
441 Bitmap_Record *bm = dpyinfo->bitmaps;
443 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
444 if (bm->refcount > 0)
445 free_bitmap_record (dpyinfo, bm);
447 dpyinfo->bitmaps_last = 0;
451 #ifdef HAVE_X_WINDOWS
453 /* Useful functions defined in the section
454 `Image type independent image structures' below. */
456 static unsigned long four_corners_best (XImagePtr ximg,
457 int *corners,
458 unsigned long width,
459 unsigned long height);
461 static int x_create_x_image_and_pixmap (struct frame *f, int width, int height,
462 int depth, XImagePtr *ximg,
463 Pixmap *pixmap);
465 static void x_destroy_x_image (XImagePtr ximg);
468 /* Create a mask of a bitmap. Note is this not a perfect mask.
469 It's nicer with some borders in this context */
472 x_create_bitmap_mask (struct frame *f, int id)
474 Pixmap pixmap, mask;
475 XImagePtr ximg, mask_img;
476 unsigned long width, height;
477 int result;
478 unsigned long bg;
479 unsigned long x, y, xp, xm, yp, ym;
480 GC gc;
482 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
484 if (!(id > 0))
485 return -1;
487 pixmap = x_bitmap_pixmap (f, id);
488 width = x_bitmap_width (f, id);
489 height = x_bitmap_height (f, id);
491 BLOCK_INPUT;
492 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
493 ~0, ZPixmap);
495 if (!ximg)
497 UNBLOCK_INPUT;
498 return -1;
501 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
503 UNBLOCK_INPUT;
504 if (!result)
506 XDestroyImage (ximg);
507 return -1;
510 bg = four_corners_best (ximg, NULL, width, height);
512 for (y = 0; y < ximg->height; ++y)
514 for (x = 0; x < ximg->width; ++x)
516 xp = x != ximg->width - 1 ? x + 1 : 0;
517 xm = x != 0 ? x - 1 : ximg->width - 1;
518 yp = y != ximg->height - 1 ? y + 1 : 0;
519 ym = y != 0 ? y - 1 : ximg->height - 1;
520 if (XGetPixel (ximg, x, y) == bg
521 && XGetPixel (ximg, x, yp) == bg
522 && XGetPixel (ximg, x, ym) == bg
523 && XGetPixel (ximg, xp, y) == bg
524 && XGetPixel (ximg, xp, yp) == bg
525 && XGetPixel (ximg, xp, ym) == bg
526 && XGetPixel (ximg, xm, y) == bg
527 && XGetPixel (ximg, xm, yp) == bg
528 && XGetPixel (ximg, xm, ym) == bg)
529 XPutPixel (mask_img, x, y, 0);
530 else
531 XPutPixel (mask_img, x, y, 1);
535 xassert (interrupt_input_blocked);
536 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
537 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
538 width, height);
539 XFreeGC (FRAME_X_DISPLAY (f), gc);
541 dpyinfo->bitmaps[id - 1].have_mask = 1;
542 dpyinfo->bitmaps[id - 1].mask = mask;
544 XDestroyImage (ximg);
545 x_destroy_x_image (mask_img);
547 return 0;
550 #endif /* HAVE_X_WINDOWS */
553 /***********************************************************************
554 Image types
555 ***********************************************************************/
557 /* Value is the number of elements of vector VECTOR. */
559 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
561 /* List of supported image types. Use define_image_type to add new
562 types. Use lookup_image_type to find a type for a given symbol. */
564 static struct image_type *image_types;
566 /* A list of symbols, one for each supported image type. */
568 Lisp_Object Vimage_types;
570 /* An alist of image types and libraries that implement the type. */
572 Lisp_Object Vimage_library_alist;
574 /* Cache for delayed-loading image types. */
576 static Lisp_Object Vimage_type_cache;
578 /* The symbol `xbm' which is used as the type symbol for XBM images. */
580 Lisp_Object Qxbm;
582 /* Keywords. */
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 (const 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 (const 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 const 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 || FUNVECP (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 BLOCK_INPUT;
1763 img = make_image (spec, hash);
1764 cache_image (f, img);
1765 img->load_failed_p = img->type->load (f, img) == 0;
1766 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1767 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1769 /* If we can't load the image, and we don't have a width and
1770 height, use some arbitrary width and height so that we can
1771 draw a rectangle for it. */
1772 if (img->load_failed_p)
1774 Lisp_Object value;
1776 value = image_spec_value (spec, QCwidth, NULL);
1777 img->width = (INTEGERP (value)
1778 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1779 value = image_spec_value (spec, QCheight, NULL);
1780 img->height = (INTEGERP (value)
1781 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1783 else
1785 /* Handle image type independent image attributes
1786 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1787 `:background COLOR'. */
1788 Lisp_Object ascent, margin, relief, bg;
1790 ascent = image_spec_value (spec, QCascent, NULL);
1791 if (INTEGERP (ascent))
1792 img->ascent = XFASTINT (ascent);
1793 else if (EQ (ascent, Qcenter))
1794 img->ascent = CENTERED_IMAGE_ASCENT;
1796 margin = image_spec_value (spec, QCmargin, NULL);
1797 if (INTEGERP (margin) && XINT (margin) >= 0)
1798 img->vmargin = img->hmargin = XFASTINT (margin);
1799 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1800 && INTEGERP (XCDR (margin)))
1802 if (XINT (XCAR (margin)) > 0)
1803 img->hmargin = XFASTINT (XCAR (margin));
1804 if (XINT (XCDR (margin)) > 0)
1805 img->vmargin = XFASTINT (XCDR (margin));
1808 relief = image_spec_value (spec, QCrelief, NULL);
1809 if (INTEGERP (relief))
1811 img->relief = XINT (relief);
1812 img->hmargin += eabs (img->relief);
1813 img->vmargin += eabs (img->relief);
1816 if (! img->background_valid)
1818 bg = image_spec_value (img->spec, QCbackground, NULL);
1819 if (!NILP (bg))
1821 img->background
1822 = x_alloc_image_color (f, img, bg,
1823 FRAME_BACKGROUND_PIXEL (f));
1824 img->background_valid = 1;
1828 /* Do image transformations and compute masks, unless we
1829 don't have the image yet. */
1830 if (!EQ (*img->type->type, Qpostscript))
1831 postprocess_image (f, img);
1834 UNBLOCK_INPUT;
1837 /* We're using IMG, so set its timestamp to `now'. */
1838 EMACS_GET_TIME (now);
1839 img->timestamp = EMACS_SECS (now);
1841 UNGCPRO;
1843 /* Value is the image id. */
1844 return img->id;
1848 /* Cache image IMG in the image cache of frame F. */
1850 static void
1851 cache_image (struct frame *f, struct image *img)
1853 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1854 int i;
1856 /* Find a free slot in c->images. */
1857 for (i = 0; i < c->used; ++i)
1858 if (c->images[i] == NULL)
1859 break;
1861 /* If no free slot found, maybe enlarge c->images. */
1862 if (i == c->used && c->used == c->size)
1864 c->size *= 2;
1865 c->images = (struct image **) xrealloc (c->images,
1866 c->size * sizeof *c->images);
1869 /* Add IMG to c->images, and assign IMG an id. */
1870 c->images[i] = img;
1871 img->id = i;
1872 if (i == c->used)
1873 ++c->used;
1875 /* Add IMG to the cache's hash table. */
1876 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1877 img->next = c->buckets[i];
1878 if (img->next)
1879 img->next->prev = img;
1880 img->prev = NULL;
1881 c->buckets[i] = img;
1885 /* Call FN on every image in the image cache of frame F. Used to mark
1886 Lisp Objects in the image cache. */
1888 /* Mark Lisp objects in image IMG. */
1890 static void
1891 mark_image (struct image *img)
1893 mark_object (img->spec);
1894 mark_object (img->dependencies);
1896 if (!NILP (img->data.lisp_val))
1897 mark_object (img->data.lisp_val);
1901 void
1902 mark_image_cache (struct image_cache *c)
1904 if (c)
1906 int i;
1907 for (i = 0; i < c->used; ++i)
1908 if (c->images[i])
1909 mark_image (c->images[i]);
1915 /***********************************************************************
1916 X / NS / W32 support code
1917 ***********************************************************************/
1919 #ifdef HAVE_NTGUI
1921 /* Macro for defining functions that will be loaded from image DLLs. */
1922 #define DEF_IMGLIB_FN(func) int (FAR CDECL *fn_##func)()
1924 /* Macro for loading those image functions from the library. */
1925 #define LOAD_IMGLIB_FN(lib,func) { \
1926 fn_##func = (void *) GetProcAddress (lib, #func); \
1927 if (!fn_##func) return 0; \
1930 /* Load a DLL implementing an image type.
1931 The `image-library-alist' variable associates a symbol,
1932 identifying an image type, to a list of possible filenames.
1933 The function returns NULL if no library could be loaded for
1934 the given image type, or if the library was previously loaded;
1935 else the handle of the DLL. */
1936 static HMODULE
1937 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
1939 HMODULE library = NULL;
1941 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
1943 Lisp_Object dlls = Fassq (type, libraries);
1945 if (CONSP (dlls))
1946 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
1948 CHECK_STRING_CAR (dlls);
1949 if (library = LoadLibrary (SDATA (XCAR (dlls))))
1950 break;
1954 return library;
1957 #endif /* HAVE_NTGUI */
1959 static int x_create_x_image_and_pixmap (struct frame *, int, int, int,
1960 XImagePtr *, Pixmap *);
1961 static void x_destroy_x_image (XImagePtr);
1962 static void x_put_x_image (struct frame *, XImagePtr, Pixmap, int, int);
1965 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1966 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1967 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1968 via xmalloc. Print error messages via image_error if an error
1969 occurs. Value is non-zero if successful.
1971 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1972 should indicate the bit depth of the image. */
1974 static int
1975 x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
1976 XImagePtr *ximg, Pixmap *pixmap)
1978 #ifdef HAVE_X_WINDOWS
1979 Display *display = FRAME_X_DISPLAY (f);
1980 Window window = FRAME_X_WINDOW (f);
1981 Screen *screen = FRAME_X_SCREEN (f);
1983 xassert (interrupt_input_blocked);
1985 if (depth <= 0)
1986 depth = DefaultDepthOfScreen (screen);
1987 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1988 depth, ZPixmap, 0, NULL, width, height,
1989 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1990 if (*ximg == NULL)
1992 image_error ("Unable to allocate X image", Qnil, Qnil);
1993 return 0;
1996 /* Allocate image raster. */
1997 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
1999 /* Allocate a pixmap of the same size. */
2000 *pixmap = XCreatePixmap (display, window, width, height, depth);
2001 if (*pixmap == NO_PIXMAP)
2003 x_destroy_x_image (*ximg);
2004 *ximg = NULL;
2005 image_error ("Unable to create X pixmap", Qnil, Qnil);
2006 return 0;
2009 return 1;
2010 #endif /* HAVE_X_WINDOWS */
2012 #ifdef HAVE_NTGUI
2014 BITMAPINFOHEADER *header;
2015 HDC hdc;
2016 int scanline_width_bits;
2017 int remainder;
2018 int palette_colors = 0;
2020 if (depth == 0)
2021 depth = 24;
2023 if (depth != 1 && depth != 4 && depth != 8
2024 && depth != 16 && depth != 24 && depth != 32)
2026 image_error ("Invalid image bit depth specified", Qnil, Qnil);
2027 return 0;
2030 scanline_width_bits = width * depth;
2031 remainder = scanline_width_bits % 32;
2033 if (remainder)
2034 scanline_width_bits += 32 - remainder;
2036 /* Bitmaps with a depth less than 16 need a palette. */
2037 /* BITMAPINFO structure already contains the first RGBQUAD. */
2038 if (depth < 16)
2039 palette_colors = 1 << depth - 1;
2041 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2042 if (*ximg == NULL)
2044 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
2045 return 0;
2048 header = &(*ximg)->info.bmiHeader;
2049 memset (&(*ximg)->info, 0, sizeof (BITMAPINFO));
2050 header->biSize = sizeof (*header);
2051 header->biWidth = width;
2052 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2053 header->biPlanes = 1;
2054 header->biBitCount = depth;
2055 header->biCompression = BI_RGB;
2056 header->biClrUsed = palette_colors;
2058 /* TODO: fill in palette. */
2059 if (depth == 1)
2061 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2062 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2063 (*ximg)->info.bmiColors[0].rgbRed = 0;
2064 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2065 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2066 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2067 (*ximg)->info.bmiColors[1].rgbRed = 255;
2068 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2071 hdc = get_frame_dc (f);
2073 /* Create a DIBSection and raster array for the bitmap,
2074 and store its handle in *pixmap. */
2075 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2076 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2077 /* casting avoids a GCC warning */
2078 (void **)&((*ximg)->data), NULL, 0);
2080 /* Realize display palette and garbage all frames. */
2081 release_frame_dc (f, hdc);
2083 if (*pixmap == NULL)
2085 DWORD err = GetLastError ();
2086 Lisp_Object errcode;
2087 /* All system errors are < 10000, so the following is safe. */
2088 XSETINT (errcode, (int) err);
2089 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2090 x_destroy_x_image (*ximg);
2091 return 0;
2094 return 1;
2096 #endif /* HAVE_NTGUI */
2098 #ifdef HAVE_NS
2099 *pixmap = ns_image_for_XPM (width, height, depth);
2100 if (*pixmap == 0)
2102 *ximg = NULL;
2103 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2104 return 0;
2106 *ximg = *pixmap;
2107 return 1;
2108 #endif
2112 /* Destroy XImage XIMG. Free XIMG->data. */
2114 static void
2115 x_destroy_x_image (XImagePtr ximg)
2117 xassert (interrupt_input_blocked);
2118 if (ximg)
2120 #ifdef HAVE_X_WINDOWS
2121 xfree (ximg->data);
2122 ximg->data = NULL;
2123 XDestroyImage (ximg);
2124 #endif /* HAVE_X_WINDOWS */
2125 #ifdef HAVE_NTGUI
2126 /* Data will be freed by DestroyObject. */
2127 ximg->data = NULL;
2128 xfree (ximg);
2129 #endif /* HAVE_NTGUI */
2130 #ifdef HAVE_NS
2131 ns_release_object (ximg);
2132 #endif /* HAVE_NS */
2137 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2138 are width and height of both the image and pixmap. */
2140 static void
2141 x_put_x_image (struct frame *f, XImagePtr ximg, Pixmap pixmap, int width, int height)
2143 #ifdef HAVE_X_WINDOWS
2144 GC gc;
2146 xassert (interrupt_input_blocked);
2147 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2148 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2149 XFreeGC (FRAME_X_DISPLAY (f), gc);
2150 #endif /* HAVE_X_WINDOWS */
2152 #ifdef HAVE_NTGUI
2153 #if 0 /* I don't think this is necessary looking at where it is used. */
2154 HDC hdc = get_frame_dc (f);
2155 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2156 release_frame_dc (f, hdc);
2157 #endif
2158 #endif /* HAVE_NTGUI */
2160 #ifdef HAVE_NS
2161 xassert (ximg == pixmap);
2162 ns_retain_object (ximg);
2163 #endif
2167 /***********************************************************************
2168 File Handling
2169 ***********************************************************************/
2171 static unsigned char *slurp_file (char *, int *);
2174 /* Find image file FILE. Look in data-directory/images, then
2175 x-bitmap-file-path. Value is the encoded full name of the file
2176 found, or nil if not found. */
2178 Lisp_Object
2179 x_find_image_file (Lisp_Object file)
2181 Lisp_Object file_found, search_path;
2182 struct gcpro gcpro1, gcpro2;
2183 int fd;
2185 file_found = Qnil;
2186 /* TODO I think this should use something like image-load-path
2187 instead. Unfortunately, that can contain non-string elements. */
2188 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2189 Vdata_directory),
2190 Vx_bitmap_file_path);
2191 GCPRO2 (file_found, search_path);
2193 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2194 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2196 if (fd == -1)
2197 file_found = Qnil;
2198 else
2200 file_found = ENCODE_FILE (file_found);
2201 close (fd);
2204 UNGCPRO;
2205 return file_found;
2209 /* Read FILE into memory. Value is a pointer to a buffer allocated
2210 with xmalloc holding FILE's contents. Value is null if an error
2211 occurred. *SIZE is set to the size of the file. */
2213 static unsigned char *
2214 slurp_file (char *file, int *size)
2216 FILE *fp = NULL;
2217 unsigned char *buf = NULL;
2218 struct stat st;
2220 if (stat (file, &st) == 0
2221 && (fp = fopen (file, "rb")) != NULL
2222 && (buf = (unsigned char *) xmalloc (st.st_size),
2223 fread (buf, 1, st.st_size, fp) == st.st_size))
2225 *size = st.st_size;
2226 fclose (fp);
2228 else
2230 if (fp)
2231 fclose (fp);
2232 if (buf)
2234 xfree (buf);
2235 buf = NULL;
2239 return buf;
2244 /***********************************************************************
2245 XBM images
2246 ***********************************************************************/
2248 static int xbm_scan (unsigned char **, unsigned char *, char *, int *);
2249 static int xbm_load (struct frame *f, struct image *img);
2250 static int xbm_load_image (struct frame *f, struct image *img,
2251 unsigned char *, unsigned char *);
2252 static int xbm_image_p (Lisp_Object object);
2253 static int xbm_read_bitmap_data (struct frame *f,
2254 unsigned char *, unsigned char *,
2255 int *, int *, unsigned char **, int);
2256 static int xbm_file_p (Lisp_Object);
2259 /* Indices of image specification fields in xbm_format, below. */
2261 enum xbm_keyword_index
2263 XBM_TYPE,
2264 XBM_FILE,
2265 XBM_WIDTH,
2266 XBM_HEIGHT,
2267 XBM_DATA,
2268 XBM_FOREGROUND,
2269 XBM_BACKGROUND,
2270 XBM_ASCENT,
2271 XBM_MARGIN,
2272 XBM_RELIEF,
2273 XBM_ALGORITHM,
2274 XBM_HEURISTIC_MASK,
2275 XBM_MASK,
2276 XBM_LAST
2279 /* Vector of image_keyword structures describing the format
2280 of valid XBM image specifications. */
2282 static const struct image_keyword xbm_format[XBM_LAST] =
2284 {":type", IMAGE_SYMBOL_VALUE, 1},
2285 {":file", IMAGE_STRING_VALUE, 0},
2286 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2287 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2288 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2289 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2290 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2291 {":ascent", IMAGE_ASCENT_VALUE, 0},
2292 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2293 {":relief", IMAGE_INTEGER_VALUE, 0},
2294 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2295 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2296 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2299 /* Structure describing the image type XBM. */
2301 static struct image_type xbm_type =
2303 &Qxbm,
2304 xbm_image_p,
2305 xbm_load,
2306 x_clear_image,
2307 NULL
2310 /* Tokens returned from xbm_scan. */
2312 enum xbm_token
2314 XBM_TK_IDENT = 256,
2315 XBM_TK_NUMBER
2319 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2320 A valid specification is a list starting with the symbol `image'
2321 The rest of the list is a property list which must contain an
2322 entry `:type xbm..
2324 If the specification specifies a file to load, it must contain
2325 an entry `:file FILENAME' where FILENAME is a string.
2327 If the specification is for a bitmap loaded from memory it must
2328 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2329 WIDTH and HEIGHT are integers > 0. DATA may be:
2331 1. a string large enough to hold the bitmap data, i.e. it must
2332 have a size >= (WIDTH + 7) / 8 * HEIGHT
2334 2. a bool-vector of size >= WIDTH * HEIGHT
2336 3. a vector of strings or bool-vectors, one for each line of the
2337 bitmap.
2339 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2340 may not be specified in this case because they are defined in the
2341 XBM file.
2343 Both the file and data forms may contain the additional entries
2344 `:background COLOR' and `:foreground COLOR'. If not present,
2345 foreground and background of the frame on which the image is
2346 displayed is used. */
2348 static int
2349 xbm_image_p (Lisp_Object object)
2351 struct image_keyword kw[XBM_LAST];
2353 memcpy (kw, xbm_format, sizeof kw);
2354 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2355 return 0;
2357 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2359 if (kw[XBM_FILE].count)
2361 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2362 return 0;
2364 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2366 /* In-memory XBM file. */
2367 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2368 return 0;
2370 else
2372 Lisp_Object data;
2373 int width, height;
2375 /* Entries for `:width', `:height' and `:data' must be present. */
2376 if (!kw[XBM_WIDTH].count
2377 || !kw[XBM_HEIGHT].count
2378 || !kw[XBM_DATA].count)
2379 return 0;
2381 data = kw[XBM_DATA].value;
2382 width = XFASTINT (kw[XBM_WIDTH].value);
2383 height = XFASTINT (kw[XBM_HEIGHT].value);
2385 /* Check type of data, and width and height against contents of
2386 data. */
2387 if (VECTORP (data))
2389 int i;
2391 /* Number of elements of the vector must be >= height. */
2392 if (XVECTOR (data)->size < height)
2393 return 0;
2395 /* Each string or bool-vector in data must be large enough
2396 for one line of the image. */
2397 for (i = 0; i < height; ++i)
2399 Lisp_Object elt = XVECTOR (data)->contents[i];
2401 if (STRINGP (elt))
2403 if (SCHARS (elt)
2404 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2405 return 0;
2407 else if (BOOL_VECTOR_P (elt))
2409 if (XBOOL_VECTOR (elt)->size < width)
2410 return 0;
2412 else
2413 return 0;
2416 else if (STRINGP (data))
2418 if (SCHARS (data)
2419 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2420 return 0;
2422 else if (BOOL_VECTOR_P (data))
2424 if (XBOOL_VECTOR (data)->size < width * height)
2425 return 0;
2427 else
2428 return 0;
2431 return 1;
2435 /* Scan a bitmap file. FP is the stream to read from. Value is
2436 either an enumerator from enum xbm_token, or a character for a
2437 single-character token, or 0 at end of file. If scanning an
2438 identifier, store the lexeme of the identifier in SVAL. If
2439 scanning a number, store its value in *IVAL. */
2441 static int
2442 xbm_scan (unsigned char **s, unsigned char *end, char *sval, int *ival)
2444 unsigned int c;
2446 loop:
2448 /* Skip white space. */
2449 while (*s < end && (c = *(*s)++, isspace (c)))
2452 if (*s >= end)
2453 c = 0;
2454 else if (isdigit (c))
2456 int value = 0, digit;
2458 if (c == '0' && *s < end)
2460 c = *(*s)++;
2461 if (c == 'x' || c == 'X')
2463 while (*s < end)
2465 c = *(*s)++;
2466 if (isdigit (c))
2467 digit = c - '0';
2468 else if (c >= 'a' && c <= 'f')
2469 digit = c - 'a' + 10;
2470 else if (c >= 'A' && c <= 'F')
2471 digit = c - 'A' + 10;
2472 else
2473 break;
2474 value = 16 * value + digit;
2477 else if (isdigit (c))
2479 value = c - '0';
2480 while (*s < end
2481 && (c = *(*s)++, isdigit (c)))
2482 value = 8 * value + c - '0';
2485 else
2487 value = c - '0';
2488 while (*s < end
2489 && (c = *(*s)++, isdigit (c)))
2490 value = 10 * value + c - '0';
2493 if (*s < end)
2494 *s = *s - 1;
2495 *ival = value;
2496 c = XBM_TK_NUMBER;
2498 else if (isalpha (c) || c == '_')
2500 *sval++ = c;
2501 while (*s < end
2502 && (c = *(*s)++, (isalnum (c) || c == '_')))
2503 *sval++ = c;
2504 *sval = 0;
2505 if (*s < end)
2506 *s = *s - 1;
2507 c = XBM_TK_IDENT;
2509 else if (c == '/' && **s == '*')
2511 /* C-style comment. */
2512 ++*s;
2513 while (**s && (**s != '*' || *(*s + 1) != '/'))
2514 ++*s;
2515 if (**s)
2517 *s += 2;
2518 goto loop;
2522 return c;
2525 #ifdef HAVE_NTGUI
2527 /* Create a Windows bitmap from X bitmap data. */
2528 static HBITMAP
2529 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2531 static unsigned char swap_nibble[16]
2532 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2533 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2534 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2535 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2536 int i, j, w1, w2;
2537 unsigned char *bits, *p;
2538 HBITMAP bmp;
2540 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2541 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2542 bits = (unsigned char *) alloca (height * w2);
2543 memset (bits, 0, height * w2);
2544 for (i = 0; i < height; i++)
2546 p = bits + i*w2;
2547 for (j = 0; j < w1; j++)
2549 /* Bitswap XBM bytes to match how Windows does things. */
2550 unsigned char c = *data++;
2551 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2552 | (swap_nibble[(c>>4) & 0xf]));
2555 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2557 return bmp;
2560 static void
2561 convert_mono_to_color_image (struct frame *f, struct image *img,
2562 COLORREF foreground, COLORREF background)
2564 HDC hdc, old_img_dc, new_img_dc;
2565 HGDIOBJ old_prev, new_prev;
2566 HBITMAP new_pixmap;
2568 hdc = get_frame_dc (f);
2569 old_img_dc = CreateCompatibleDC (hdc);
2570 new_img_dc = CreateCompatibleDC (hdc);
2571 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2572 release_frame_dc (f, hdc);
2573 old_prev = SelectObject (old_img_dc, img->pixmap);
2574 new_prev = SelectObject (new_img_dc, new_pixmap);
2575 /* Windows convention for mono bitmaps is black = background,
2576 white = foreground. */
2577 SetTextColor (new_img_dc, background);
2578 SetBkColor (new_img_dc, foreground);
2580 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2581 0, 0, SRCCOPY);
2583 SelectObject (old_img_dc, old_prev);
2584 SelectObject (new_img_dc, new_prev);
2585 DeleteDC (old_img_dc);
2586 DeleteDC (new_img_dc);
2587 DeleteObject (img->pixmap);
2588 if (new_pixmap == 0)
2589 fprintf (stderr, "Failed to convert image to color.\n");
2590 else
2591 img->pixmap = new_pixmap;
2594 #define XBM_BIT_SHUFFLE(b) (~(b))
2596 #else
2598 #define XBM_BIT_SHUFFLE(b) (b)
2600 #endif /* HAVE_NTGUI */
2603 static void
2604 Create_Pixmap_From_Bitmap_Data (struct frame *f, struct image *img, char *data,
2605 RGB_PIXEL_COLOR fg, RGB_PIXEL_COLOR bg,
2606 int non_default_colors)
2608 #ifdef HAVE_NTGUI
2609 img->pixmap
2610 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2612 /* If colors were specified, transfer the bitmap to a color one. */
2613 if (non_default_colors)
2614 convert_mono_to_color_image (f, img, fg, bg);
2616 #elif defined (HAVE_NS)
2617 img->pixmap = ns_image_from_XBM (data, img->width, img->height);
2619 #else
2620 img->pixmap
2621 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2622 FRAME_X_WINDOW (f),
2623 data,
2624 img->width, img->height,
2625 fg, bg,
2626 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2627 #endif /* !HAVE_NTGUI && !HAVE_NS */
2632 /* Replacement for XReadBitmapFileData which isn't available under old
2633 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2634 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2635 the image. Return in *DATA the bitmap data allocated with xmalloc.
2636 Value is non-zero if successful. DATA null means just test if
2637 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR
2638 is non-zero, inhibit the call to image_error when the image size is
2639 invalid (the bitmap remains unread). */
2641 static int
2642 xbm_read_bitmap_data (struct frame *f, unsigned char *contents, unsigned char *end,
2643 int *width, int *height, unsigned char **data,
2644 int inhibit_image_error)
2646 unsigned char *s = contents;
2647 char buffer[BUFSIZ];
2648 int padding_p = 0;
2649 int v10 = 0;
2650 int bytes_per_line, i, nbytes;
2651 unsigned char *p;
2652 int value;
2653 int LA1;
2655 #define match() \
2656 LA1 = xbm_scan (&s, end, buffer, &value)
2658 #define expect(TOKEN) \
2659 if (LA1 != (TOKEN)) \
2660 goto failure; \
2661 else \
2662 match ()
2664 #define expect_ident(IDENT) \
2665 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2666 match (); \
2667 else \
2668 goto failure
2670 *width = *height = -1;
2671 if (data)
2672 *data = NULL;
2673 LA1 = xbm_scan (&s, end, buffer, &value);
2675 /* Parse defines for width, height and hot-spots. */
2676 while (LA1 == '#')
2678 match ();
2679 expect_ident ("define");
2680 expect (XBM_TK_IDENT);
2682 if (LA1 == XBM_TK_NUMBER)
2684 char *p = strrchr (buffer, '_');
2685 p = p ? p + 1 : buffer;
2686 if (strcmp (p, "width") == 0)
2687 *width = value;
2688 else if (strcmp (p, "height") == 0)
2689 *height = value;
2691 expect (XBM_TK_NUMBER);
2694 if (!check_image_size (f, *width, *height))
2696 if (!inhibit_image_error)
2697 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2698 goto failure;
2700 else if (data == NULL)
2701 goto success;
2703 /* Parse bits. Must start with `static'. */
2704 expect_ident ("static");
2705 if (LA1 == XBM_TK_IDENT)
2707 if (strcmp (buffer, "unsigned") == 0)
2709 match ();
2710 expect_ident ("char");
2712 else if (strcmp (buffer, "short") == 0)
2714 match ();
2715 v10 = 1;
2716 if (*width % 16 && *width % 16 < 9)
2717 padding_p = 1;
2719 else if (strcmp (buffer, "char") == 0)
2720 match ();
2721 else
2722 goto failure;
2724 else
2725 goto failure;
2727 expect (XBM_TK_IDENT);
2728 expect ('[');
2729 expect (']');
2730 expect ('=');
2731 expect ('{');
2733 bytes_per_line = (*width + 7) / 8 + padding_p;
2734 nbytes = bytes_per_line * *height;
2735 p = *data = (unsigned char *) xmalloc (nbytes);
2737 if (v10)
2739 for (i = 0; i < nbytes; i += 2)
2741 int val = value;
2742 expect (XBM_TK_NUMBER);
2744 *p++ = XBM_BIT_SHUFFLE (val);
2745 if (!padding_p || ((i + 2) % bytes_per_line))
2746 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2748 if (LA1 == ',' || LA1 == '}')
2749 match ();
2750 else
2751 goto failure;
2754 else
2756 for (i = 0; i < nbytes; ++i)
2758 int val = value;
2759 expect (XBM_TK_NUMBER);
2761 *p++ = XBM_BIT_SHUFFLE (val);
2763 if (LA1 == ',' || LA1 == '}')
2764 match ();
2765 else
2766 goto failure;
2770 success:
2771 return 1;
2773 failure:
2775 if (data && *data)
2777 xfree (*data);
2778 *data = NULL;
2780 return 0;
2782 #undef match
2783 #undef expect
2784 #undef expect_ident
2788 /* Load XBM image IMG which will be displayed on frame F from buffer
2789 CONTENTS. END is the end of the buffer. Value is non-zero if
2790 successful. */
2792 static int
2793 xbm_load_image (struct frame *f, struct image *img, unsigned char *contents,
2794 unsigned char *end)
2796 int rc;
2797 unsigned char *data;
2798 int success_p = 0;
2800 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2801 &data, 0);
2802 if (rc)
2804 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2805 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2806 int non_default_colors = 0;
2807 Lisp_Object value;
2809 xassert (img->width > 0 && img->height > 0);
2811 /* Get foreground and background colors, maybe allocate colors. */
2812 value = image_spec_value (img->spec, QCforeground, NULL);
2813 if (!NILP (value))
2815 foreground = x_alloc_image_color (f, img, value, foreground);
2816 non_default_colors = 1;
2818 value = image_spec_value (img->spec, QCbackground, NULL);
2819 if (!NILP (value))
2821 background = x_alloc_image_color (f, img, value, background);
2822 img->background = background;
2823 img->background_valid = 1;
2824 non_default_colors = 1;
2827 Create_Pixmap_From_Bitmap_Data (f, img, data,
2828 foreground, background,
2829 non_default_colors);
2830 xfree (data);
2832 if (img->pixmap == NO_PIXMAP)
2834 x_clear_image (f, img);
2835 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2837 else
2838 success_p = 1;
2840 else
2841 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2843 return success_p;
2847 /* Value is non-zero if DATA looks like an in-memory XBM file. */
2849 static int
2850 xbm_file_p (Lisp_Object data)
2852 int w, h;
2853 return (STRINGP (data)
2854 && xbm_read_bitmap_data (NULL, SDATA (data),
2855 (SDATA (data) + SBYTES (data)),
2856 &w, &h, NULL, 1));
2860 /* Fill image IMG which is used on frame F with pixmap data. Value is
2861 non-zero if successful. */
2863 static int
2864 xbm_load (struct frame *f, struct image *img)
2866 int success_p = 0;
2867 Lisp_Object file_name;
2869 xassert (xbm_image_p (img->spec));
2871 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2872 file_name = image_spec_value (img->spec, QCfile, NULL);
2873 if (STRINGP (file_name))
2875 Lisp_Object file;
2876 unsigned char *contents;
2877 int size;
2878 struct gcpro gcpro1;
2880 file = x_find_image_file (file_name);
2881 GCPRO1 (file);
2882 if (!STRINGP (file))
2884 image_error ("Cannot find image file `%s'", file_name, Qnil);
2885 UNGCPRO;
2886 return 0;
2889 contents = slurp_file (SDATA (file), &size);
2890 if (contents == NULL)
2892 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2893 UNGCPRO;
2894 return 0;
2897 success_p = xbm_load_image (f, img, contents, contents + size);
2898 UNGCPRO;
2900 else
2902 struct image_keyword fmt[XBM_LAST];
2903 Lisp_Object data;
2904 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2905 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2906 int non_default_colors = 0;
2907 char *bits;
2908 int parsed_p;
2909 int in_memory_file_p = 0;
2911 /* See if data looks like an in-memory XBM file. */
2912 data = image_spec_value (img->spec, QCdata, NULL);
2913 in_memory_file_p = xbm_file_p (data);
2915 /* Parse the image specification. */
2916 memcpy (fmt, xbm_format, sizeof fmt);
2917 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2918 xassert (parsed_p);
2920 /* Get specified width, and height. */
2921 if (!in_memory_file_p)
2923 img->width = XFASTINT (fmt[XBM_WIDTH].value);
2924 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
2925 xassert (img->width > 0 && img->height > 0);
2928 /* Get foreground and background colors, maybe allocate colors. */
2929 if (fmt[XBM_FOREGROUND].count
2930 && STRINGP (fmt[XBM_FOREGROUND].value))
2932 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
2933 foreground);
2934 non_default_colors = 1;
2937 if (fmt[XBM_BACKGROUND].count
2938 && STRINGP (fmt[XBM_BACKGROUND].value))
2940 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
2941 background);
2942 non_default_colors = 1;
2945 if (in_memory_file_p)
2946 success_p = xbm_load_image (f, img, SDATA (data),
2947 (SDATA (data)
2948 + SBYTES (data)));
2949 else
2951 if (VECTORP (data))
2953 int i;
2954 char *p;
2955 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2957 p = bits = (char *) alloca (nbytes * img->height);
2958 for (i = 0; i < img->height; ++i, p += nbytes)
2960 Lisp_Object line = XVECTOR (data)->contents[i];
2961 if (STRINGP (line))
2962 memcpy (p, SDATA (line), nbytes);
2963 else
2964 memcpy (p, XBOOL_VECTOR (line)->data, nbytes);
2967 else if (STRINGP (data))
2968 bits = SDATA (data);
2969 else
2970 bits = XBOOL_VECTOR (data)->data;
2972 #ifdef WINDOWSNT
2974 char *invertedBits;
2975 int nbytes, i;
2976 /* Windows mono bitmaps are reversed compared with X. */
2977 invertedBits = bits;
2978 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
2979 * img->height;
2980 bits = (char *) alloca (nbytes);
2981 for (i = 0; i < nbytes; i++)
2982 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
2984 #endif
2985 /* Create the pixmap. */
2987 Create_Pixmap_From_Bitmap_Data (f, img, bits,
2988 foreground, background,
2989 non_default_colors);
2990 if (img->pixmap)
2991 success_p = 1;
2992 else
2994 image_error ("Unable to create pixmap for XBM image `%s'",
2995 img->spec, Qnil);
2996 x_clear_image (f, img);
3001 return success_p;
3006 /***********************************************************************
3007 XPM images
3008 ***********************************************************************/
3010 #if defined (HAVE_XPM) || defined (HAVE_NS)
3012 static int xpm_image_p (Lisp_Object object);
3013 static int xpm_load (struct frame *f, struct image *img);
3014 static int xpm_valid_color_symbols_p (Lisp_Object);
3016 #endif /* HAVE_XPM || HAVE_NS */
3018 #ifdef HAVE_XPM
3019 #ifdef HAVE_NTGUI
3020 /* Indicate to xpm.h that we don't have Xlib. */
3021 #define FOR_MSW
3022 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3023 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3024 #define XColor xpm_XColor
3025 #define XImage xpm_XImage
3026 #define Display xpm_Display
3027 #define PIXEL_ALREADY_TYPEDEFED
3028 #include "X11/xpm.h"
3029 #undef FOR_MSW
3030 #undef XColor
3031 #undef XImage
3032 #undef Display
3033 #undef PIXEL_ALREADY_TYPEDEFED
3034 #else
3035 #include "X11/xpm.h"
3036 #endif /* HAVE_NTGUI */
3037 #endif /* HAVE_XPM */
3039 #if defined (HAVE_XPM) || defined (HAVE_NS)
3040 /* The symbol `xpm' identifying XPM-format images. */
3042 Lisp_Object Qxpm;
3044 /* Indices of image specification fields in xpm_format, below. */
3046 enum xpm_keyword_index
3048 XPM_TYPE,
3049 XPM_FILE,
3050 XPM_DATA,
3051 XPM_ASCENT,
3052 XPM_MARGIN,
3053 XPM_RELIEF,
3054 XPM_ALGORITHM,
3055 XPM_HEURISTIC_MASK,
3056 XPM_MASK,
3057 XPM_COLOR_SYMBOLS,
3058 XPM_BACKGROUND,
3059 XPM_LAST
3062 /* Vector of image_keyword structures describing the format
3063 of valid XPM image specifications. */
3065 static const struct image_keyword xpm_format[XPM_LAST] =
3067 {":type", IMAGE_SYMBOL_VALUE, 1},
3068 {":file", IMAGE_STRING_VALUE, 0},
3069 {":data", IMAGE_STRING_VALUE, 0},
3070 {":ascent", IMAGE_ASCENT_VALUE, 0},
3071 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3072 {":relief", IMAGE_INTEGER_VALUE, 0},
3073 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3074 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3075 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3076 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3077 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3080 /* Structure describing the image type XPM. */
3082 static struct image_type xpm_type =
3084 &Qxpm,
3085 xpm_image_p,
3086 xpm_load,
3087 x_clear_image,
3088 NULL
3091 #ifdef HAVE_X_WINDOWS
3093 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3094 functions for allocating image colors. Our own functions handle
3095 color allocation failures more gracefully than the ones on the XPM
3096 lib. */
3098 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3099 #define ALLOC_XPM_COLORS
3100 #endif
3101 #endif /* HAVE_X_WINDOWS */
3103 #ifdef ALLOC_XPM_COLORS
3105 static void xpm_init_color_cache (struct frame *, XpmAttributes *);
3106 static void xpm_free_color_cache (void);
3107 static int xpm_lookup_color (struct frame *, char *, XColor *);
3108 static int xpm_color_bucket (char *);
3109 static struct xpm_cached_color *xpm_cache_color (struct frame *, char *,
3110 XColor *, int);
3112 /* An entry in a hash table used to cache color definitions of named
3113 colors. This cache is necessary to speed up XPM image loading in
3114 case we do color allocations ourselves. Without it, we would need
3115 a call to XParseColor per pixel in the image. */
3117 struct xpm_cached_color
3119 /* Next in collision chain. */
3120 struct xpm_cached_color *next;
3122 /* Color definition (RGB and pixel color). */
3123 XColor color;
3125 /* Color name. */
3126 char name[1];
3129 /* The hash table used for the color cache, and its bucket vector
3130 size. */
3132 #define XPM_COLOR_CACHE_BUCKETS 1001
3133 struct xpm_cached_color **xpm_color_cache;
3135 /* Initialize the color cache. */
3137 static void
3138 xpm_init_color_cache (struct frame *f, XpmAttributes *attrs)
3140 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3141 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3142 memset (xpm_color_cache, 0, nbytes);
3143 init_color_table ();
3145 if (attrs->valuemask & XpmColorSymbols)
3147 int i;
3148 XColor color;
3150 for (i = 0; i < attrs->numsymbols; ++i)
3151 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3152 attrs->colorsymbols[i].value, &color))
3154 color.pixel = lookup_rgb_color (f, color.red, color.green,
3155 color.blue);
3156 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3161 /* Free the color cache. */
3163 static void
3164 xpm_free_color_cache (void)
3166 struct xpm_cached_color *p, *next;
3167 int i;
3169 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3170 for (p = xpm_color_cache[i]; p; p = next)
3172 next = p->next;
3173 xfree (p);
3176 xfree (xpm_color_cache);
3177 xpm_color_cache = NULL;
3178 free_color_table ();
3181 /* Return the bucket index for color named COLOR_NAME in the color
3182 cache. */
3184 static int
3185 xpm_color_bucket (char *color_name)
3187 unsigned h = 0;
3188 char *s;
3190 for (s = color_name; *s; ++s)
3191 h = (h << 2) ^ *s;
3192 return h %= XPM_COLOR_CACHE_BUCKETS;
3196 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3197 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3198 entry added. */
3200 static struct xpm_cached_color *
3201 xpm_cache_color (struct frame *f, char *color_name, XColor *color, int bucket)
3203 size_t nbytes;
3204 struct xpm_cached_color *p;
3206 if (bucket < 0)
3207 bucket = xpm_color_bucket (color_name);
3209 nbytes = sizeof *p + strlen (color_name);
3210 p = (struct xpm_cached_color *) xmalloc (nbytes);
3211 strcpy (p->name, color_name);
3212 p->color = *color;
3213 p->next = xpm_color_cache[bucket];
3214 xpm_color_cache[bucket] = p;
3215 return p;
3218 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3219 return the cached definition in *COLOR. Otherwise, make a new
3220 entry in the cache and allocate the color. Value is zero if color
3221 allocation failed. */
3223 static int
3224 xpm_lookup_color (struct frame *f, char *color_name, XColor *color)
3226 struct xpm_cached_color *p;
3227 int h = xpm_color_bucket (color_name);
3229 for (p = xpm_color_cache[h]; p; p = p->next)
3230 if (strcmp (p->name, color_name) == 0)
3231 break;
3233 if (p != NULL)
3234 *color = p->color;
3235 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3236 color_name, color))
3238 color->pixel = lookup_rgb_color (f, color->red, color->green,
3239 color->blue);
3240 p = xpm_cache_color (f, color_name, color, h);
3242 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3243 with transparency, and it's useful. */
3244 else if (strcmp ("opaque", color_name) == 0)
3246 memset (color, 0, sizeof (XColor)); /* Is this necessary/correct? */
3247 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3248 p = xpm_cache_color (f, color_name, color, h);
3251 return p != NULL;
3255 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3256 CLOSURE is a pointer to the frame on which we allocate the
3257 color. Return in *COLOR the allocated color. Value is non-zero
3258 if successful. */
3260 static int
3261 xpm_alloc_color (Display *dpy, Colormap cmap, char *color_name, XColor *color,
3262 void *closure)
3264 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3268 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3269 is a pointer to the frame on which we allocate the color. Value is
3270 non-zero if successful. */
3272 static int
3273 xpm_free_colors (Display *dpy, Colormap cmap, Pixel *pixels, int npixels, void *closure)
3275 return 1;
3278 #endif /* ALLOC_XPM_COLORS */
3281 #ifdef HAVE_NTGUI
3283 /* XPM library details. */
3285 DEF_IMGLIB_FN (XpmFreeAttributes);
3286 DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
3287 DEF_IMGLIB_FN (XpmReadFileToImage);
3288 DEF_IMGLIB_FN (XImageFree);
3290 static int
3291 init_xpm_functions (Lisp_Object libraries)
3293 HMODULE library;
3295 if (!(library = w32_delayed_load (libraries, Qxpm)))
3296 return 0;
3298 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3299 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3300 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3301 LOAD_IMGLIB_FN (library, XImageFree);
3302 return 1;
3305 #endif /* HAVE_NTGUI */
3308 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3309 for XPM images. Such a list must consist of conses whose car and
3310 cdr are strings. */
3312 static int
3313 xpm_valid_color_symbols_p (Lisp_Object color_symbols)
3315 while (CONSP (color_symbols))
3317 Lisp_Object sym = XCAR (color_symbols);
3318 if (!CONSP (sym)
3319 || !STRINGP (XCAR (sym))
3320 || !STRINGP (XCDR (sym)))
3321 break;
3322 color_symbols = XCDR (color_symbols);
3325 return NILP (color_symbols);
3329 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3331 static int
3332 xpm_image_p (Lisp_Object object)
3334 struct image_keyword fmt[XPM_LAST];
3335 memcpy (fmt, xpm_format, sizeof fmt);
3336 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3337 /* Either `:file' or `:data' must be present. */
3338 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3339 /* Either no `:color-symbols' or it's a list of conses
3340 whose car and cdr are strings. */
3341 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3342 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3345 #endif /* HAVE_XPM || HAVE_NS */
3347 #if defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
3349 x_create_bitmap_from_xpm_data (struct frame *f, char **bits)
3351 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3352 int id, rc;
3353 XpmAttributes attrs;
3354 Pixmap bitmap, mask;
3356 memset (&attrs, 0, sizeof attrs);
3358 attrs.visual = FRAME_X_VISUAL (f);
3359 attrs.colormap = FRAME_X_COLORMAP (f);
3360 attrs.valuemask |= XpmVisual;
3361 attrs.valuemask |= XpmColormap;
3363 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3364 bits, &bitmap, &mask, &attrs);
3365 if (rc != XpmSuccess)
3367 XpmFreeAttributes (&attrs);
3368 return -1;
3371 id = x_allocate_bitmap_record (f);
3372 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3373 dpyinfo->bitmaps[id - 1].have_mask = 1;
3374 dpyinfo->bitmaps[id - 1].mask = mask;
3375 dpyinfo->bitmaps[id - 1].file = NULL;
3376 dpyinfo->bitmaps[id - 1].height = attrs.height;
3377 dpyinfo->bitmaps[id - 1].width = attrs.width;
3378 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3379 dpyinfo->bitmaps[id - 1].refcount = 1;
3381 XpmFreeAttributes (&attrs);
3382 return id;
3384 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3386 /* Load image IMG which will be displayed on frame F. Value is
3387 non-zero if successful. */
3389 #ifdef HAVE_XPM
3391 static int
3392 xpm_load (struct frame *f, struct image *img)
3394 int rc;
3395 XpmAttributes attrs;
3396 Lisp_Object specified_file, color_symbols;
3397 #ifdef HAVE_NTGUI
3398 HDC hdc;
3399 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3400 #endif /* HAVE_NTGUI */
3402 /* Configure the XPM lib. Use the visual of frame F. Allocate
3403 close colors. Return colors allocated. */
3404 memset (&attrs, 0, sizeof attrs);
3406 #ifndef HAVE_NTGUI
3407 attrs.visual = FRAME_X_VISUAL (f);
3408 attrs.colormap = FRAME_X_COLORMAP (f);
3409 attrs.valuemask |= XpmVisual;
3410 attrs.valuemask |= XpmColormap;
3411 #endif /* HAVE_NTGUI */
3413 #ifdef ALLOC_XPM_COLORS
3414 /* Allocate colors with our own functions which handle
3415 failing color allocation more gracefully. */
3416 attrs.color_closure = f;
3417 attrs.alloc_color = xpm_alloc_color;
3418 attrs.free_colors = xpm_free_colors;
3419 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3420 #else /* not ALLOC_XPM_COLORS */
3421 /* Let the XPM lib allocate colors. */
3422 attrs.valuemask |= XpmReturnAllocPixels;
3423 #ifdef XpmAllocCloseColors
3424 attrs.alloc_close_colors = 1;
3425 attrs.valuemask |= XpmAllocCloseColors;
3426 #else /* not XpmAllocCloseColors */
3427 attrs.closeness = 600;
3428 attrs.valuemask |= XpmCloseness;
3429 #endif /* not XpmAllocCloseColors */
3430 #endif /* ALLOC_XPM_COLORS */
3432 /* If image specification contains symbolic color definitions, add
3433 these to `attrs'. */
3434 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3435 if (CONSP (color_symbols))
3437 Lisp_Object tail;
3438 XpmColorSymbol *xpm_syms;
3439 int i, size;
3441 attrs.valuemask |= XpmColorSymbols;
3443 /* Count number of symbols. */
3444 attrs.numsymbols = 0;
3445 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3446 ++attrs.numsymbols;
3448 /* Allocate an XpmColorSymbol array. */
3449 size = attrs.numsymbols * sizeof *xpm_syms;
3450 xpm_syms = (XpmColorSymbol *) alloca (size);
3451 memset (xpm_syms, 0, size);
3452 attrs.colorsymbols = xpm_syms;
3454 /* Fill the color symbol array. */
3455 for (tail = color_symbols, i = 0;
3456 CONSP (tail);
3457 ++i, tail = XCDR (tail))
3459 Lisp_Object name = XCAR (XCAR (tail));
3460 Lisp_Object color = XCDR (XCAR (tail));
3461 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3462 strcpy (xpm_syms[i].name, SDATA (name));
3463 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3464 strcpy (xpm_syms[i].value, SDATA (color));
3468 /* Create a pixmap for the image, either from a file, or from a
3469 string buffer containing data in the same format as an XPM file. */
3470 #ifdef ALLOC_XPM_COLORS
3471 xpm_init_color_cache (f, &attrs);
3472 #endif
3474 specified_file = image_spec_value (img->spec, QCfile, NULL);
3476 #ifdef HAVE_NTGUI
3478 HDC frame_dc = get_frame_dc (f);
3479 hdc = CreateCompatibleDC (frame_dc);
3480 release_frame_dc (f, frame_dc);
3482 #endif /* HAVE_NTGUI */
3484 if (STRINGP (specified_file))
3486 Lisp_Object file = x_find_image_file (specified_file);
3487 if (!STRINGP (file))
3489 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3490 return 0;
3493 #ifdef HAVE_NTGUI
3494 /* XpmReadFileToPixmap is not available in the Windows port of
3495 libxpm. But XpmReadFileToImage almost does what we want. */
3496 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3497 &xpm_image, &xpm_mask,
3498 &attrs);
3499 #else
3500 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3501 SDATA (file), &img->pixmap, &img->mask,
3502 &attrs);
3503 #endif /* HAVE_NTGUI */
3505 else
3507 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3508 #ifdef HAVE_NTGUI
3509 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3510 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3511 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3512 &xpm_image, &xpm_mask,
3513 &attrs);
3514 #else
3515 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3516 SDATA (buffer),
3517 &img->pixmap, &img->mask,
3518 &attrs);
3519 #endif /* HAVE_NTGUI */
3522 if (rc == XpmSuccess)
3524 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3525 img->colors = colors_in_color_table (&img->ncolors);
3526 #else /* not ALLOC_XPM_COLORS */
3527 int i;
3529 #ifdef HAVE_NTGUI
3530 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3531 plus some duplicate attributes. */
3532 if (xpm_image && xpm_image->bitmap)
3534 img->pixmap = xpm_image->bitmap;
3535 /* XImageFree in libXpm frees XImage struct without destroying
3536 the bitmap, which is what we want. */
3537 fn_XImageFree (xpm_image);
3539 if (xpm_mask && xpm_mask->bitmap)
3541 /* The mask appears to be inverted compared with what we expect.
3542 TODO: invert our expectations. See other places where we
3543 have to invert bits because our idea of masks is backwards. */
3544 HGDIOBJ old_obj;
3545 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3547 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3548 SelectObject (hdc, old_obj);
3550 img->mask = xpm_mask->bitmap;
3551 fn_XImageFree (xpm_mask);
3552 DeleteDC (hdc);
3555 DeleteDC (hdc);
3556 #endif /* HAVE_NTGUI */
3558 /* Remember allocated colors. */
3559 img->ncolors = attrs.nalloc_pixels;
3560 img->colors = (unsigned long *) xmalloc (img->ncolors
3561 * sizeof *img->colors);
3562 for (i = 0; i < attrs.nalloc_pixels; ++i)
3564 img->colors[i] = attrs.alloc_pixels[i];
3565 #ifdef DEBUG_X_COLORS
3566 register_color (img->colors[i]);
3567 #endif
3569 #endif /* not ALLOC_XPM_COLORS */
3571 img->width = attrs.width;
3572 img->height = attrs.height;
3573 xassert (img->width > 0 && img->height > 0);
3575 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3576 #ifdef HAVE_NTGUI
3577 fn_XpmFreeAttributes (&attrs);
3578 #else
3579 XpmFreeAttributes (&attrs);
3580 #endif /* HAVE_NTGUI */
3582 else
3584 #ifdef HAVE_NTGUI
3585 DeleteDC (hdc);
3586 #endif /* HAVE_NTGUI */
3588 switch (rc)
3590 case XpmOpenFailed:
3591 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3592 break;
3594 case XpmFileInvalid:
3595 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3596 break;
3598 case XpmNoMemory:
3599 image_error ("Out of memory (%s)", img->spec, Qnil);
3600 break;
3602 case XpmColorFailed:
3603 image_error ("Color allocation error (%s)", img->spec, Qnil);
3604 break;
3606 default:
3607 image_error ("Unknown error (%s)", img->spec, Qnil);
3608 break;
3612 #ifdef ALLOC_XPM_COLORS
3613 xpm_free_color_cache ();
3614 #endif
3615 return rc == XpmSuccess;
3618 #endif /* HAVE_XPM */
3620 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3622 /* XPM support functions for NS where libxpm is not available.
3623 Only XPM version 3 (without any extensions) is supported. */
3625 static int xpm_scan (const unsigned char **, const unsigned char *,
3626 const unsigned char **, int *);
3627 static Lisp_Object xpm_make_color_table_v
3628 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3629 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3630 static void xpm_put_color_table_v (Lisp_Object, const unsigned char *,
3631 int, Lisp_Object);
3632 static Lisp_Object xpm_get_color_table_v (Lisp_Object,
3633 const unsigned char *, int);
3634 static Lisp_Object xpm_make_color_table_h
3635 (void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3636 Lisp_Object (**) (Lisp_Object, const unsigned char *, int));
3637 static void xpm_put_color_table_h (Lisp_Object, const unsigned char *,
3638 int, Lisp_Object);
3639 static Lisp_Object xpm_get_color_table_h (Lisp_Object,
3640 const unsigned char *, int);
3641 static int xpm_str_to_color_key (const char *);
3642 static int xpm_load_image (struct frame *, struct image *,
3643 const unsigned char *, const unsigned char *);
3645 /* Tokens returned from xpm_scan. */
3647 enum xpm_token
3649 XPM_TK_IDENT = 256,
3650 XPM_TK_STRING,
3651 XPM_TK_EOF
3654 /* Scan an XPM data and return a character (< 256) or a token defined
3655 by enum xpm_token above. *S and END are the start (inclusive) and
3656 the end (exclusive) addresses of the data, respectively. Advance
3657 *S while scanning. If token is either XPM_TK_IDENT or
3658 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3659 length of the corresponding token, respectively. */
3661 static int
3662 xpm_scan (const unsigned char **s,
3663 const unsigned char *end,
3664 const unsigned char **beg,
3665 int *len)
3667 int c;
3669 while (*s < end)
3671 /* Skip white-space. */
3672 while (*s < end && (c = *(*s)++, isspace (c)))
3675 /* gnus-pointer.xpm uses '-' in its identifier.
3676 sb-dir-plus.xpm uses '+' in its identifier. */
3677 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3679 *beg = *s - 1;
3680 while (*s < end
3681 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3682 ++*s;
3683 *len = *s - *beg;
3684 return XPM_TK_IDENT;
3686 else if (c == '"')
3688 *beg = *s;
3689 while (*s < end && **s != '"')
3690 ++*s;
3691 *len = *s - *beg;
3692 if (*s < end)
3693 ++*s;
3694 return XPM_TK_STRING;
3696 else if (c == '/')
3698 if (*s < end && **s == '*')
3700 /* C-style comment. */
3701 ++*s;
3704 while (*s < end && *(*s)++ != '*')
3707 while (*s < end && **s != '/');
3708 if (*s < end)
3709 ++*s;
3711 else
3712 return c;
3714 else
3715 return c;
3718 return XPM_TK_EOF;
3721 /* Functions for color table lookup in XPM data. A key is a string
3722 specifying the color of each pixel in XPM data. A value is either
3723 an integer that specifies a pixel color, Qt that specifies
3724 transparency, or Qnil for the unspecified color. If the length of
3725 the key string is one, a vector is used as a table. Otherwise, a
3726 hash table is used. */
3728 static Lisp_Object
3729 xpm_make_color_table_v (void (**put_func) (Lisp_Object,
3730 const unsigned char *,
3731 int,
3732 Lisp_Object),
3733 Lisp_Object (**get_func) (Lisp_Object,
3734 const unsigned char *,
3735 int))
3737 *put_func = xpm_put_color_table_v;
3738 *get_func = xpm_get_color_table_v;
3739 return Fmake_vector (make_number (256), Qnil);
3742 static void
3743 xpm_put_color_table_v (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 (Lisp_Object color_table,
3753 const unsigned char *chars_start,
3754 int chars_len)
3756 return XVECTOR (color_table)->contents[*chars_start];
3759 static Lisp_Object
3760 xpm_make_color_table_h (void (**put_func) (Lisp_Object,
3761 const unsigned char *,
3762 int,
3763 Lisp_Object),
3764 Lisp_Object (**get_func) (Lisp_Object,
3765 const unsigned char *,
3766 int))
3768 *put_func = xpm_put_color_table_h;
3769 *get_func = xpm_get_color_table_h;
3770 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
3771 make_float (DEFAULT_REHASH_SIZE),
3772 make_float (DEFAULT_REHASH_THRESHOLD),
3773 Qnil, Qnil, Qnil);
3776 static void
3777 xpm_put_color_table_h (Lisp_Object color_table,
3778 const unsigned char *chars_start,
3779 int chars_len,
3780 Lisp_Object color)
3782 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3783 unsigned hash_code;
3784 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3786 hash_lookup (table, chars, &hash_code);
3787 hash_put (table, chars, color, hash_code);
3790 static Lisp_Object
3791 xpm_get_color_table_h (Lisp_Object color_table,
3792 const unsigned char *chars_start,
3793 int chars_len)
3795 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3796 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
3797 NULL);
3799 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3802 enum xpm_color_key {
3803 XPM_COLOR_KEY_S,
3804 XPM_COLOR_KEY_M,
3805 XPM_COLOR_KEY_G4,
3806 XPM_COLOR_KEY_G,
3807 XPM_COLOR_KEY_C
3810 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3812 static int
3813 xpm_str_to_color_key (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 (struct frame *f,
3827 struct image *img,
3828 const unsigned char *contents,
3829 const unsigned char *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 (struct frame *f,
4062 struct image *img)
4064 int success_p = 0;
4065 Lisp_Object file_name;
4067 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4068 file_name = image_spec_value (img->spec, QCfile, NULL);
4069 if (STRINGP (file_name))
4071 Lisp_Object file;
4072 unsigned char *contents;
4073 int size;
4074 struct gcpro gcpro1;
4076 file = x_find_image_file (file_name);
4077 GCPRO1 (file);
4078 if (!STRINGP (file))
4080 image_error ("Cannot find image file `%s'", file_name, Qnil);
4081 UNGCPRO;
4082 return 0;
4085 contents = slurp_file (SDATA (file), &size);
4086 if (contents == NULL)
4088 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4089 UNGCPRO;
4090 return 0;
4093 success_p = xpm_load_image (f, img, contents, contents + size);
4094 xfree (contents);
4095 UNGCPRO;
4097 else
4099 Lisp_Object data;
4101 data = image_spec_value (img->spec, QCdata, NULL);
4102 success_p = xpm_load_image (f, img, SDATA (data),
4103 SDATA (data) + SBYTES (data));
4106 return success_p;
4109 #endif /* HAVE_NS && !HAVE_XPM */
4113 /***********************************************************************
4114 Color table
4115 ***********************************************************************/
4117 #ifdef COLOR_TABLE_SUPPORT
4119 /* An entry in the color table mapping an RGB color to a pixel color. */
4121 struct ct_color
4123 int r, g, b;
4124 unsigned long pixel;
4126 /* Next in color table collision list. */
4127 struct ct_color *next;
4130 /* The bucket vector size to use. Must be prime. */
4132 #define CT_SIZE 101
4134 /* Value is a hash of the RGB color given by R, G, and B. */
4136 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4138 /* The color hash table. */
4140 struct ct_color **ct_table;
4142 /* Number of entries in the color table. */
4144 int ct_colors_allocated;
4146 /* Initialize the color table. */
4148 static void
4149 init_color_table (void)
4151 int size = CT_SIZE * sizeof (*ct_table);
4152 ct_table = (struct ct_color **) xmalloc (size);
4153 memset (ct_table, 0, size);
4154 ct_colors_allocated = 0;
4158 /* Free memory associated with the color table. */
4160 static void
4161 free_color_table (void)
4163 int i;
4164 struct ct_color *p, *next;
4166 for (i = 0; i < CT_SIZE; ++i)
4167 for (p = ct_table[i]; p; p = next)
4169 next = p->next;
4170 xfree (p);
4173 xfree (ct_table);
4174 ct_table = NULL;
4178 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4179 entry for that color already is in the color table, return the
4180 pixel color of that entry. Otherwise, allocate a new color for R,
4181 G, B, and make an entry in the color table. */
4183 static unsigned long
4184 lookup_rgb_color (struct frame *f, int r, int g, int b)
4186 unsigned hash = CT_HASH_RGB (r, g, b);
4187 int i = hash % CT_SIZE;
4188 struct ct_color *p;
4189 Display_Info *dpyinfo;
4191 /* Handle TrueColor visuals specially, which improves performance by
4192 two orders of magnitude. Freeing colors on TrueColor visuals is
4193 a nop, and pixel colors specify RGB values directly. See also
4194 the Xlib spec, chapter 3.1. */
4195 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4196 if (dpyinfo->red_bits > 0)
4198 unsigned long pr, pg, pb;
4200 /* Apply gamma-correction like normal color allocation does. */
4201 if (f->gamma)
4203 XColor color;
4204 color.red = r, color.green = g, color.blue = b;
4205 gamma_correct (f, &color);
4206 r = color.red, g = color.green, b = color.blue;
4209 /* Scale down RGB values to the visual's bits per RGB, and shift
4210 them to the right position in the pixel color. Note that the
4211 original RGB values are 16-bit values, as usual in X. */
4212 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4213 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4214 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4216 /* Assemble the pixel color. */
4217 return pr | pg | pb;
4220 for (p = ct_table[i]; p; p = p->next)
4221 if (p->r == r && p->g == g && p->b == b)
4222 break;
4224 if (p == NULL)
4227 #ifdef HAVE_X_WINDOWS
4228 XColor color;
4229 Colormap cmap;
4230 int rc;
4232 color.red = r;
4233 color.green = g;
4234 color.blue = b;
4236 cmap = FRAME_X_COLORMAP (f);
4237 rc = x_alloc_nearest_color (f, cmap, &color);
4238 if (rc)
4240 ++ct_colors_allocated;
4241 p = (struct ct_color *) xmalloc (sizeof *p);
4242 p->r = r;
4243 p->g = g;
4244 p->b = b;
4245 p->pixel = color.pixel;
4246 p->next = ct_table[i];
4247 ct_table[i] = p;
4249 else
4250 return FRAME_FOREGROUND_PIXEL (f);
4252 #else
4253 COLORREF color;
4254 #ifdef HAVE_NTGUI
4255 color = PALETTERGB (r, g, b);
4256 #else
4257 color = RGB_TO_ULONG (r, g, b);
4258 #endif /* HAVE_NTGUI */
4259 ++ct_colors_allocated;
4260 p = (struct ct_color *) xmalloc (sizeof *p);
4261 p->r = r;
4262 p->g = g;
4263 p->b = b;
4264 p->pixel = color;
4265 p->next = ct_table[i];
4266 ct_table[i] = p;
4267 #endif /* HAVE_X_WINDOWS */
4271 return p->pixel;
4275 /* Look up pixel color PIXEL which is used on frame F in the color
4276 table. If not already present, allocate it. Value is PIXEL. */
4278 static unsigned long
4279 lookup_pixel_color (struct frame *f, unsigned long pixel)
4281 int i = pixel % CT_SIZE;
4282 struct ct_color *p;
4284 for (p = ct_table[i]; p; p = p->next)
4285 if (p->pixel == pixel)
4286 break;
4288 if (p == NULL)
4290 XColor color;
4291 Colormap cmap;
4292 int rc;
4294 #ifdef HAVE_X_WINDOWS
4295 cmap = FRAME_X_COLORMAP (f);
4296 color.pixel = pixel;
4297 x_query_color (f, &color);
4298 rc = x_alloc_nearest_color (f, cmap, &color);
4299 #else
4300 BLOCK_INPUT;
4301 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4302 color.pixel = pixel;
4303 XQueryColor (NULL, cmap, &color);
4304 rc = x_alloc_nearest_color (f, cmap, &color);
4305 UNBLOCK_INPUT;
4306 #endif /* HAVE_X_WINDOWS */
4308 if (rc)
4310 ++ct_colors_allocated;
4312 p = (struct ct_color *) xmalloc (sizeof *p);
4313 p->r = color.red;
4314 p->g = color.green;
4315 p->b = color.blue;
4316 p->pixel = pixel;
4317 p->next = ct_table[i];
4318 ct_table[i] = p;
4320 else
4321 return FRAME_FOREGROUND_PIXEL (f);
4323 return p->pixel;
4327 /* Value is a vector of all pixel colors contained in the color table,
4328 allocated via xmalloc. Set *N to the number of colors. */
4330 static unsigned long *
4331 colors_in_color_table (int *n)
4333 int i, j;
4334 struct ct_color *p;
4335 unsigned long *colors;
4337 if (ct_colors_allocated == 0)
4339 *n = 0;
4340 colors = NULL;
4342 else
4344 colors = (unsigned long *) xmalloc (ct_colors_allocated
4345 * sizeof *colors);
4346 *n = ct_colors_allocated;
4348 for (i = j = 0; i < CT_SIZE; ++i)
4349 for (p = ct_table[i]; p; p = p->next)
4350 colors[j++] = p->pixel;
4353 return colors;
4356 #else /* COLOR_TABLE_SUPPORT */
4358 static unsigned long
4359 lookup_rgb_color (struct frame *f, int r, int g, int b)
4361 unsigned long pixel;
4363 #ifdef HAVE_NTGUI
4364 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4365 #endif /* HAVE_NTGUI */
4367 #ifdef HAVE_NS
4368 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4369 #endif /* HAVE_NS */
4370 return pixel;
4373 static void
4374 init_color_table (void)
4377 #endif /* COLOR_TABLE_SUPPORT */
4380 /***********************************************************************
4381 Algorithms
4382 ***********************************************************************/
4384 static XColor *x_to_xcolors (struct frame *, struct image *, int);
4385 static void x_from_xcolors (struct frame *, struct image *, XColor *);
4386 static void x_detect_edges (struct frame *, struct image *, int[9], int);
4388 #ifdef HAVE_NTGUI
4389 static void XPutPixel (XImagePtr , int, int, COLORREF);
4390 #endif /* HAVE_NTGUI */
4392 /* Non-zero means draw a cross on images having `:conversion
4393 disabled'. */
4395 int cross_disabled_images;
4397 /* Edge detection matrices for different edge-detection
4398 strategies. */
4400 static int emboss_matrix[9] = {
4401 /* x - 1 x x + 1 */
4402 2, -1, 0, /* y - 1 */
4403 -1, 0, 1, /* y */
4404 0, 1, -2 /* y + 1 */
4407 static int laplace_matrix[9] = {
4408 /* x - 1 x x + 1 */
4409 1, 0, 0, /* y - 1 */
4410 0, 0, 0, /* y */
4411 0, 0, -1 /* y + 1 */
4414 /* Value is the intensity of the color whose red/green/blue values
4415 are R, G, and B. */
4417 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4420 /* On frame F, return an array of XColor structures describing image
4421 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4422 non-zero means also fill the red/green/blue members of the XColor
4423 structures. Value is a pointer to the array of XColors structures,
4424 allocated with xmalloc; it must be freed by the caller. */
4426 static XColor *
4427 x_to_xcolors (struct frame *f, struct image *img, int rgb_p)
4429 int x, y;
4430 XColor *colors, *p;
4431 XImagePtr_or_DC ximg;
4432 #ifdef HAVE_NTGUI
4433 HDC hdc;
4434 HGDIOBJ prev;
4435 #endif /* HAVE_NTGUI */
4437 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4439 #ifndef HAVE_NTGUI
4440 /* Get the X image IMG->pixmap. */
4441 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4442 0, 0, img->width, img->height, ~0, ZPixmap);
4443 #else
4444 /* Load the image into a memory device context. */
4445 hdc = get_frame_dc (f);
4446 ximg = CreateCompatibleDC (hdc);
4447 release_frame_dc (f, hdc);
4448 prev = SelectObject (ximg, img->pixmap);
4449 #endif /* HAVE_NTGUI */
4451 /* Fill the `pixel' members of the XColor array. I wished there
4452 were an easy and portable way to circumvent XGetPixel. */
4453 p = colors;
4454 for (y = 0; y < img->height; ++y)
4456 XColor *row = p;
4458 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4459 for (x = 0; x < img->width; ++x, ++p)
4460 p->pixel = GET_PIXEL (ximg, x, y);
4461 if (rgb_p)
4462 x_query_colors (f, row, img->width);
4464 #else
4466 for (x = 0; x < img->width; ++x, ++p)
4468 /* W32_TODO: palette support needed here? */
4469 p->pixel = GET_PIXEL (ximg, x, y);
4470 if (rgb_p)
4472 p->red = RED16_FROM_ULONG (p->pixel);
4473 p->green = GREEN16_FROM_ULONG (p->pixel);
4474 p->blue = BLUE16_FROM_ULONG (p->pixel);
4477 #endif /* HAVE_X_WINDOWS */
4480 Destroy_Image (ximg, prev);
4482 return colors;
4485 #ifdef HAVE_NTGUI
4487 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4488 created with CreateDIBSection, with the pointer to the bit values
4489 stored in ximg->data. */
4491 static void
4492 XPutPixel (XImagePtr ximg, int x, int y, COLORREF color)
4494 int width = ximg->info.bmiHeader.biWidth;
4495 int height = ximg->info.bmiHeader.biHeight;
4496 unsigned char * pixel;
4498 /* True color images. */
4499 if (ximg->info.bmiHeader.biBitCount == 24)
4501 int rowbytes = width * 3;
4502 /* Ensure scanlines are aligned on 4 byte boundaries. */
4503 if (rowbytes % 4)
4504 rowbytes += 4 - (rowbytes % 4);
4506 pixel = ximg->data + y * rowbytes + x * 3;
4507 /* Windows bitmaps are in BGR order. */
4508 *pixel = GetBValue (color);
4509 *(pixel + 1) = GetGValue (color);
4510 *(pixel + 2) = GetRValue (color);
4512 /* Monochrome images. */
4513 else if (ximg->info.bmiHeader.biBitCount == 1)
4515 int rowbytes = width / 8;
4516 /* Ensure scanlines are aligned on 4 byte boundaries. */
4517 if (rowbytes % 4)
4518 rowbytes += 4 - (rowbytes % 4);
4519 pixel = ximg->data + y * rowbytes + x / 8;
4520 /* Filter out palette info. */
4521 if (color & 0x00ffffff)
4522 *pixel = *pixel | (1 << x % 8);
4523 else
4524 *pixel = *pixel & ~(1 << x % 8);
4526 else
4527 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4530 #endif /* HAVE_NTGUI */
4532 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4533 RGB members are set. F is the frame on which this all happens.
4534 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4536 static void
4537 x_from_xcolors (struct frame *f, struct image *img, XColor *colors)
4539 int x, y;
4540 XImagePtr oimg = NULL;
4541 Pixmap pixmap;
4542 XColor *p;
4544 init_color_table ();
4546 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4547 &oimg, &pixmap);
4548 p = colors;
4549 for (y = 0; y < img->height; ++y)
4550 for (x = 0; x < img->width; ++x, ++p)
4552 unsigned long pixel;
4553 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4554 XPutPixel (oimg, x, y, pixel);
4557 xfree (colors);
4558 x_clear_image_1 (f, img, 1, 0, 1);
4560 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4561 x_destroy_x_image (oimg);
4562 img->pixmap = pixmap;
4563 #ifdef COLOR_TABLE_SUPPORT
4564 img->colors = colors_in_color_table (&img->ncolors);
4565 free_color_table ();
4566 #endif /* COLOR_TABLE_SUPPORT */
4570 /* On frame F, perform edge-detection on image IMG.
4572 MATRIX is a nine-element array specifying the transformation
4573 matrix. See emboss_matrix for an example.
4575 COLOR_ADJUST is a color adjustment added to each pixel of the
4576 outgoing image. */
4578 static void
4579 x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjust)
4581 XColor *colors = x_to_xcolors (f, img, 1);
4582 XColor *new, *p;
4583 int x, y, i, sum;
4585 for (i = sum = 0; i < 9; ++i)
4586 sum += eabs (matrix[i]);
4588 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4590 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4592 for (y = 0; y < img->height; ++y)
4594 p = COLOR (new, 0, y);
4595 p->red = p->green = p->blue = 0xffff/2;
4596 p = COLOR (new, img->width - 1, y);
4597 p->red = p->green = p->blue = 0xffff/2;
4600 for (x = 1; x < img->width - 1; ++x)
4602 p = COLOR (new, x, 0);
4603 p->red = p->green = p->blue = 0xffff/2;
4604 p = COLOR (new, x, img->height - 1);
4605 p->red = p->green = p->blue = 0xffff/2;
4608 for (y = 1; y < img->height - 1; ++y)
4610 p = COLOR (new, 1, y);
4612 for (x = 1; x < img->width - 1; ++x, ++p)
4614 int r, g, b, y1, x1;
4616 r = g = b = i = 0;
4617 for (y1 = y - 1; y1 < y + 2; ++y1)
4618 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
4619 if (matrix[i])
4621 XColor *t = COLOR (colors, x1, y1);
4622 r += matrix[i] * t->red;
4623 g += matrix[i] * t->green;
4624 b += matrix[i] * t->blue;
4627 r = (r / sum + color_adjust) & 0xffff;
4628 g = (g / sum + color_adjust) & 0xffff;
4629 b = (b / sum + color_adjust) & 0xffff;
4630 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4634 xfree (colors);
4635 x_from_xcolors (f, img, new);
4637 #undef COLOR
4641 /* Perform the pre-defined `emboss' edge-detection on image IMG
4642 on frame F. */
4644 static void
4645 x_emboss (struct frame *f, struct image *img)
4647 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4651 /* Transform image IMG which is used on frame F with a Laplace
4652 edge-detection algorithm. The result is an image that can be used
4653 to draw disabled buttons, for example. */
4655 static void
4656 x_laplace (struct frame *f, struct image *img)
4658 x_detect_edges (f, img, laplace_matrix, 45000);
4662 /* Perform edge-detection on image IMG on frame F, with specified
4663 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4665 MATRIX must be either
4667 - a list of at least 9 numbers in row-major form
4668 - a vector of at least 9 numbers
4670 COLOR_ADJUST nil means use a default; otherwise it must be a
4671 number. */
4673 static void
4674 x_edge_detection (struct frame *f, struct image *img, Lisp_Object matrix,
4675 Lisp_Object color_adjust)
4677 int i = 0;
4678 int trans[9];
4680 if (CONSP (matrix))
4682 for (i = 0;
4683 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4684 ++i, matrix = XCDR (matrix))
4685 trans[i] = XFLOATINT (XCAR (matrix));
4687 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4689 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4690 trans[i] = XFLOATINT (AREF (matrix, i));
4693 if (NILP (color_adjust))
4694 color_adjust = make_number (0xffff / 2);
4696 if (i == 9 && NUMBERP (color_adjust))
4697 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
4701 /* Transform image IMG on frame F so that it looks disabled. */
4703 static void
4704 x_disable_image (struct frame *f, struct image *img)
4706 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4707 #ifdef HAVE_NTGUI
4708 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4709 #else
4710 int n_planes = dpyinfo->n_planes;
4711 #endif /* HAVE_NTGUI */
4713 if (n_planes >= 2)
4715 /* Color (or grayscale). Convert to gray, and equalize. Just
4716 drawing such images with a stipple can look very odd, so
4717 we're using this method instead. */
4718 XColor *colors = x_to_xcolors (f, img, 1);
4719 XColor *p, *end;
4720 const int h = 15000;
4721 const int l = 30000;
4723 for (p = colors, end = colors + img->width * img->height;
4724 p < end;
4725 ++p)
4727 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4728 int i2 = (0xffff - h - l) * i / 0xffff + l;
4729 p->red = p->green = p->blue = i2;
4732 x_from_xcolors (f, img, colors);
4735 /* Draw a cross over the disabled image, if we must or if we
4736 should. */
4737 if (n_planes < 2 || cross_disabled_images)
4739 #ifndef HAVE_NTGUI
4740 Display *dpy = FRAME_X_DISPLAY (f);
4741 GC gc;
4743 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4745 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4747 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4748 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4749 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4750 img->width - 1, img->height - 1);
4751 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4752 img->width - 1, 0);
4753 XFreeGC (dpy, gc);
4755 if (img->mask)
4757 gc = XCreateGC (dpy, img->mask, 0, NULL);
4758 XSetForeground (dpy, gc, MaskForeground (f));
4759 XDrawLine (dpy, img->mask, gc, 0, 0,
4760 img->width - 1, img->height - 1);
4761 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4762 img->width - 1, 0);
4763 XFreeGC (dpy, gc);
4765 #endif /* !HAVE_NS */
4766 #else
4767 HDC hdc, bmpdc;
4768 HGDIOBJ prev;
4770 hdc = get_frame_dc (f);
4771 bmpdc = CreateCompatibleDC (hdc);
4772 release_frame_dc (f, hdc);
4774 prev = SelectObject (bmpdc, img->pixmap);
4776 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4777 MoveToEx (bmpdc, 0, 0, NULL);
4778 LineTo (bmpdc, img->width - 1, img->height - 1);
4779 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4780 LineTo (bmpdc, img->width - 1, 0);
4782 if (img->mask)
4784 SelectObject (bmpdc, img->mask);
4785 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4786 MoveToEx (bmpdc, 0, 0, NULL);
4787 LineTo (bmpdc, img->width - 1, img->height - 1);
4788 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4789 LineTo (bmpdc, img->width - 1, 0);
4791 SelectObject (bmpdc, prev);
4792 DeleteDC (bmpdc);
4793 #endif /* HAVE_NTGUI */
4798 /* Build a mask for image IMG which is used on frame F. FILE is the
4799 name of an image file, for error messages. HOW determines how to
4800 determine the background color of IMG. If it is a list '(R G B)',
4801 with R, G, and B being integers >= 0, take that as the color of the
4802 background. Otherwise, determine the background color of IMG
4803 heuristically. Value is non-zero if successful. */
4805 static int
4806 x_build_heuristic_mask (struct frame *f, struct image *img, Lisp_Object how)
4808 XImagePtr_or_DC ximg;
4809 #ifndef HAVE_NTGUI
4810 XImagePtr mask_img;
4811 #else
4812 HDC frame_dc;
4813 HGDIOBJ prev;
4814 char *mask_img;
4815 int row_width;
4816 #endif /* HAVE_NTGUI */
4817 int x, y, rc, use_img_background;
4818 unsigned long bg = 0;
4820 if (img->mask)
4822 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4823 img->mask = NO_PIXMAP;
4824 img->background_transparent_valid = 0;
4827 #ifndef HAVE_NTGUI
4828 #ifndef HAVE_NS
4829 /* Create an image and pixmap serving as mask. */
4830 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4831 &mask_img, &img->mask);
4832 if (!rc)
4833 return 0;
4834 #endif /* !HAVE_NS */
4836 /* Get the X image of IMG->pixmap. */
4837 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4838 img->width, img->height,
4839 ~0, ZPixmap);
4840 #else
4841 /* Create the bit array serving as mask. */
4842 row_width = (img->width + 7) / 8;
4843 mask_img = xmalloc (row_width * img->height);
4844 memset (mask_img, 0, row_width * img->height);
4846 /* Create a memory device context for IMG->pixmap. */
4847 frame_dc = get_frame_dc (f);
4848 ximg = CreateCompatibleDC (frame_dc);
4849 release_frame_dc (f, frame_dc);
4850 prev = SelectObject (ximg, img->pixmap);
4851 #endif /* HAVE_NTGUI */
4853 /* Determine the background color of ximg. If HOW is `(R G B)'
4854 take that as color. Otherwise, use the image's background color. */
4855 use_img_background = 1;
4857 if (CONSP (how))
4859 int rgb[3], i;
4861 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4863 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4864 how = XCDR (how);
4867 if (i == 3 && NILP (how))
4869 char color_name[30];
4870 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
4871 bg = (
4872 #ifdef HAVE_NTGUI
4873 0x00ffffff & /* Filter out palette info. */
4874 #endif /* HAVE_NTGUI */
4875 x_alloc_image_color (f, img, build_string (color_name), 0));
4876 use_img_background = 0;
4880 if (use_img_background)
4881 bg = four_corners_best (ximg, img->corners, img->width, img->height);
4883 /* Set all bits in mask_img to 1 whose color in ximg is different
4884 from the background color bg. */
4885 #ifndef HAVE_NTGUI
4886 for (y = 0; y < img->height; ++y)
4887 for (x = 0; x < img->width; ++x)
4888 #ifndef HAVE_NS
4889 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
4890 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4891 #else
4892 if (XGetPixel (ximg, x, y) == bg)
4893 ns_set_alpha (ximg, x, y, 0);
4894 #endif /* HAVE_NS */
4895 #ifndef HAVE_NS
4896 /* Fill in the background_transparent field while we have the mask handy. */
4897 image_background_transparent (img, f, mask_img);
4899 /* Put mask_img into img->mask. */
4900 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
4901 x_destroy_x_image (mask_img);
4902 #endif /* !HAVE_NS */
4903 #else
4904 for (y = 0; y < img->height; ++y)
4905 for (x = 0; x < img->width; ++x)
4907 COLORREF p = GetPixel (ximg, x, y);
4908 if (p != bg)
4909 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
4912 /* Create the mask image. */
4913 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
4914 mask_img);
4915 /* Fill in the background_transparent field while we have the mask handy. */
4916 SelectObject (ximg, img->mask);
4917 image_background_transparent (img, f, ximg);
4919 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
4920 xfree (mask_img);
4921 #endif /* HAVE_NTGUI */
4923 Destroy_Image (ximg, prev);
4925 return 1;
4929 /***********************************************************************
4930 PBM (mono, gray, color)
4931 ***********************************************************************/
4933 static int pbm_image_p (Lisp_Object object);
4934 static int pbm_load (struct frame *f, struct image *img);
4935 static int pbm_scan_number (unsigned char **, unsigned char *);
4937 /* The symbol `pbm' identifying images of this type. */
4939 Lisp_Object Qpbm;
4941 /* Indices of image specification fields in gs_format, below. */
4943 enum pbm_keyword_index
4945 PBM_TYPE,
4946 PBM_FILE,
4947 PBM_DATA,
4948 PBM_ASCENT,
4949 PBM_MARGIN,
4950 PBM_RELIEF,
4951 PBM_ALGORITHM,
4952 PBM_HEURISTIC_MASK,
4953 PBM_MASK,
4954 PBM_FOREGROUND,
4955 PBM_BACKGROUND,
4956 PBM_LAST
4959 /* Vector of image_keyword structures describing the format
4960 of valid user-defined image specifications. */
4962 static const struct image_keyword pbm_format[PBM_LAST] =
4964 {":type", IMAGE_SYMBOL_VALUE, 1},
4965 {":file", IMAGE_STRING_VALUE, 0},
4966 {":data", IMAGE_STRING_VALUE, 0},
4967 {":ascent", IMAGE_ASCENT_VALUE, 0},
4968 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
4969 {":relief", IMAGE_INTEGER_VALUE, 0},
4970 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4971 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4972 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
4973 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
4974 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
4977 /* Structure describing the image type `pbm'. */
4979 static struct image_type pbm_type =
4981 &Qpbm,
4982 pbm_image_p,
4983 pbm_load,
4984 x_clear_image,
4985 NULL
4989 /* Return non-zero if OBJECT is a valid PBM image specification. */
4991 static int
4992 pbm_image_p (Lisp_Object object)
4994 struct image_keyword fmt[PBM_LAST];
4996 memcpy (fmt, pbm_format, sizeof fmt);
4998 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
4999 return 0;
5001 /* Must specify either :data or :file. */
5002 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5006 /* Scan a decimal number from *S and return it. Advance *S while
5007 reading the number. END is the end of the string. Value is -1 at
5008 end of input. */
5010 static int
5011 pbm_scan_number (unsigned char **s, unsigned char *end)
5013 int c = 0, val = -1;
5015 while (*s < end)
5017 /* Skip white-space. */
5018 while (*s < end && (c = *(*s)++, isspace (c)))
5021 if (c == '#')
5023 /* Skip comment to end of line. */
5024 while (*s < end && (c = *(*s)++, c != '\n'))
5027 else if (isdigit (c))
5029 /* Read decimal number. */
5030 val = c - '0';
5031 while (*s < end && (c = *(*s)++, isdigit (c)))
5032 val = 10 * val + c - '0';
5033 break;
5035 else
5036 break;
5039 return val;
5043 #ifdef HAVE_NTGUI
5044 #if 0 /* Unused. ++kfs */
5046 /* Read FILE into memory. Value is a pointer to a buffer allocated
5047 with xmalloc holding FILE's contents. Value is null if an error
5048 occurred. *SIZE is set to the size of the file. */
5050 static char *
5051 pbm_read_file (file, size)
5052 Lisp_Object file;
5053 int *size;
5055 FILE *fp = NULL;
5056 char *buf = NULL;
5057 struct stat st;
5059 if (stat (SDATA (file), &st) == 0
5060 && (fp = fopen (SDATA (file), "rb")) != NULL
5061 && (buf = (char *) xmalloc (st.st_size),
5062 fread (buf, 1, st.st_size, fp) == st.st_size))
5064 *size = st.st_size;
5065 fclose (fp);
5067 else
5069 if (fp)
5070 fclose (fp);
5071 if (buf)
5073 xfree (buf);
5074 buf = NULL;
5078 return buf;
5080 #endif
5081 #endif /* HAVE_NTGUI */
5083 /* Load PBM image IMG for use on frame F. */
5085 static int
5086 pbm_load (struct frame *f, struct image *img)
5088 int raw_p, x, y;
5089 int width, height, max_color_idx = 0;
5090 XImagePtr ximg;
5091 Lisp_Object file, specified_file;
5092 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5093 struct gcpro gcpro1;
5094 unsigned char *contents = NULL;
5095 unsigned char *end, *p;
5096 int size;
5098 specified_file = image_spec_value (img->spec, QCfile, NULL);
5099 file = Qnil;
5100 GCPRO1 (file);
5102 if (STRINGP (specified_file))
5104 file = x_find_image_file (specified_file);
5105 if (!STRINGP (file))
5107 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5108 UNGCPRO;
5109 return 0;
5112 contents = slurp_file (SDATA (file), &size);
5113 if (contents == NULL)
5115 image_error ("Error reading `%s'", file, Qnil);
5116 UNGCPRO;
5117 return 0;
5120 p = contents;
5121 end = contents + size;
5123 else
5125 Lisp_Object data;
5126 data = image_spec_value (img->spec, QCdata, NULL);
5127 p = SDATA (data);
5128 end = p + SBYTES (data);
5131 /* Check magic number. */
5132 if (end - p < 2 || *p++ != 'P')
5134 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5135 error:
5136 xfree (contents);
5137 UNGCPRO;
5138 return 0;
5141 switch (*p++)
5143 case '1':
5144 raw_p = 0, type = PBM_MONO;
5145 break;
5147 case '2':
5148 raw_p = 0, type = PBM_GRAY;
5149 break;
5151 case '3':
5152 raw_p = 0, type = PBM_COLOR;
5153 break;
5155 case '4':
5156 raw_p = 1, type = PBM_MONO;
5157 break;
5159 case '5':
5160 raw_p = 1, type = PBM_GRAY;
5161 break;
5163 case '6':
5164 raw_p = 1, type = PBM_COLOR;
5165 break;
5167 default:
5168 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5169 goto error;
5172 /* Read width, height, maximum color-component. Characters
5173 starting with `#' up to the end of a line are ignored. */
5174 width = pbm_scan_number (&p, end);
5175 height = pbm_scan_number (&p, end);
5177 if (type != PBM_MONO)
5179 max_color_idx = pbm_scan_number (&p, end);
5180 if (max_color_idx > 65535 || max_color_idx < 0)
5182 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5183 goto error;
5187 if (!check_image_size (f, width, height))
5189 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5190 goto error;
5193 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5194 &ximg, &img->pixmap))
5195 goto error;
5197 /* Initialize the color hash table. */
5198 init_color_table ();
5200 if (type == PBM_MONO)
5202 int c = 0, g;
5203 struct image_keyword fmt[PBM_LAST];
5204 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5205 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5207 /* Parse the image specification. */
5208 memcpy (fmt, pbm_format, sizeof fmt);
5209 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5211 /* Get foreground and background colors, maybe allocate colors. */
5212 if (fmt[PBM_FOREGROUND].count
5213 && STRINGP (fmt[PBM_FOREGROUND].value))
5214 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5215 if (fmt[PBM_BACKGROUND].count
5216 && STRINGP (fmt[PBM_BACKGROUND].value))
5218 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5219 img->background = bg;
5220 img->background_valid = 1;
5223 for (y = 0; y < height; ++y)
5224 for (x = 0; x < width; ++x)
5226 if (raw_p)
5228 if ((x & 7) == 0)
5230 if (p >= end)
5232 x_destroy_x_image (ximg);
5233 x_clear_image (f, img);
5234 image_error ("Invalid image size in image `%s'",
5235 img->spec, Qnil);
5236 goto error;
5238 c = *p++;
5240 g = c & 0x80;
5241 c <<= 1;
5243 else
5244 g = pbm_scan_number (&p, end);
5246 XPutPixel (ximg, x, y, g ? fg : bg);
5249 else
5251 int expected_size = height * width;
5252 if (max_color_idx > 255)
5253 expected_size *= 2;
5254 if (type == PBM_COLOR)
5255 expected_size *= 3;
5257 if (raw_p && p + expected_size > end)
5259 x_destroy_x_image (ximg);
5260 x_clear_image (f, img);
5261 image_error ("Invalid image size in image `%s'",
5262 img->spec, Qnil);
5263 goto error;
5266 for (y = 0; y < height; ++y)
5267 for (x = 0; x < width; ++x)
5269 int r, g, b;
5271 if (type == PBM_GRAY && raw_p)
5273 r = g = b = *p++;
5274 if (max_color_idx > 255)
5275 r = g = b = r * 256 + *p++;
5277 else if (type == PBM_GRAY)
5278 r = g = b = pbm_scan_number (&p, end);
5279 else if (raw_p)
5281 r = *p++;
5282 if (max_color_idx > 255)
5283 r = r * 256 + *p++;
5284 g = *p++;
5285 if (max_color_idx > 255)
5286 g = g * 256 + *p++;
5287 b = *p++;
5288 if (max_color_idx > 255)
5289 b = b * 256 + *p++;
5291 else
5293 r = pbm_scan_number (&p, end);
5294 g = pbm_scan_number (&p, end);
5295 b = pbm_scan_number (&p, end);
5298 if (r < 0 || g < 0 || b < 0)
5300 x_destroy_x_image (ximg);
5301 image_error ("Invalid pixel value in image `%s'",
5302 img->spec, Qnil);
5303 goto error;
5306 /* RGB values are now in the range 0..max_color_idx.
5307 Scale this to the range 0..0xffff supported by X. */
5308 r = (double) r * 65535 / max_color_idx;
5309 g = (double) g * 65535 / max_color_idx;
5310 b = (double) b * 65535 / max_color_idx;
5311 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5315 #ifdef COLOR_TABLE_SUPPORT
5316 /* Store in IMG->colors the colors allocated for the image, and
5317 free the color table. */
5318 img->colors = colors_in_color_table (&img->ncolors);
5319 free_color_table ();
5320 #endif /* COLOR_TABLE_SUPPORT */
5322 img->width = width;
5323 img->height = height;
5325 /* Maybe fill in the background field while we have ximg handy. */
5327 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5328 /* Casting avoids a GCC warning. */
5329 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5331 /* Put the image into a pixmap. */
5332 x_put_x_image (f, ximg, img->pixmap, width, height);
5333 x_destroy_x_image (ximg);
5335 /* X and W32 versions did it here, MAC version above. ++kfs
5336 img->width = width;
5337 img->height = height; */
5339 UNGCPRO;
5340 xfree (contents);
5341 return 1;
5345 /***********************************************************************
5347 ***********************************************************************/
5349 #if defined (HAVE_PNG) || defined (HAVE_NS)
5351 /* Function prototypes. */
5353 static int png_image_p (Lisp_Object object);
5354 static int png_load (struct frame *f, struct image *img);
5356 /* The symbol `png' identifying images of this type. */
5358 Lisp_Object Qpng;
5360 /* Indices of image specification fields in png_format, below. */
5362 enum png_keyword_index
5364 PNG_TYPE,
5365 PNG_DATA,
5366 PNG_FILE,
5367 PNG_ASCENT,
5368 PNG_MARGIN,
5369 PNG_RELIEF,
5370 PNG_ALGORITHM,
5371 PNG_HEURISTIC_MASK,
5372 PNG_MASK,
5373 PNG_BACKGROUND,
5374 PNG_LAST
5377 /* Vector of image_keyword structures describing the format
5378 of valid user-defined image specifications. */
5380 static const struct image_keyword png_format[PNG_LAST] =
5382 {":type", IMAGE_SYMBOL_VALUE, 1},
5383 {":data", IMAGE_STRING_VALUE, 0},
5384 {":file", IMAGE_STRING_VALUE, 0},
5385 {":ascent", IMAGE_ASCENT_VALUE, 0},
5386 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5387 {":relief", IMAGE_INTEGER_VALUE, 0},
5388 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5389 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5390 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5391 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5394 /* Structure describing the image type `png'. */
5396 static struct image_type png_type =
5398 &Qpng,
5399 png_image_p,
5400 png_load,
5401 x_clear_image,
5402 NULL
5405 /* Return non-zero if OBJECT is a valid PNG image specification. */
5407 static int
5408 png_image_p (Lisp_Object object)
5410 struct image_keyword fmt[PNG_LAST];
5411 memcpy (fmt, png_format, sizeof fmt);
5413 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5414 return 0;
5416 /* Must specify either the :data or :file keyword. */
5417 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5420 #endif /* HAVE_PNG || HAVE_NS */
5423 #ifdef HAVE_PNG
5425 #ifdef HAVE_NTGUI
5426 /* PNG library details. */
5428 DEF_IMGLIB_FN (png_get_io_ptr);
5429 DEF_IMGLIB_FN (png_sig_cmp);
5430 DEF_IMGLIB_FN (png_create_read_struct);
5431 DEF_IMGLIB_FN (png_create_info_struct);
5432 DEF_IMGLIB_FN (png_destroy_read_struct);
5433 DEF_IMGLIB_FN (png_set_read_fn);
5434 DEF_IMGLIB_FN (png_set_sig_bytes);
5435 DEF_IMGLIB_FN (png_read_info);
5436 DEF_IMGLIB_FN (png_get_IHDR);
5437 DEF_IMGLIB_FN (png_get_valid);
5438 DEF_IMGLIB_FN (png_set_strip_16);
5439 DEF_IMGLIB_FN (png_set_expand);
5440 DEF_IMGLIB_FN (png_set_gray_to_rgb);
5441 DEF_IMGLIB_FN (png_set_background);
5442 DEF_IMGLIB_FN (png_get_bKGD);
5443 DEF_IMGLIB_FN (png_read_update_info);
5444 DEF_IMGLIB_FN (png_get_channels);
5445 DEF_IMGLIB_FN (png_get_rowbytes);
5446 DEF_IMGLIB_FN (png_read_image);
5447 DEF_IMGLIB_FN (png_read_end);
5448 DEF_IMGLIB_FN (png_error);
5450 static int
5451 init_png_functions (Lisp_Object libraries)
5453 HMODULE library;
5455 /* Try loading libpng under probable names. */
5456 if (!(library = w32_delayed_load (libraries, Qpng)))
5457 return 0;
5459 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5460 LOAD_IMGLIB_FN (library, png_sig_cmp);
5461 LOAD_IMGLIB_FN (library, png_create_read_struct);
5462 LOAD_IMGLIB_FN (library, png_create_info_struct);
5463 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5464 LOAD_IMGLIB_FN (library, png_set_read_fn);
5465 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5466 LOAD_IMGLIB_FN (library, png_read_info);
5467 LOAD_IMGLIB_FN (library, png_get_IHDR);
5468 LOAD_IMGLIB_FN (library, png_get_valid);
5469 LOAD_IMGLIB_FN (library, png_set_strip_16);
5470 LOAD_IMGLIB_FN (library, png_set_expand);
5471 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5472 LOAD_IMGLIB_FN (library, png_set_background);
5473 LOAD_IMGLIB_FN (library, png_get_bKGD);
5474 LOAD_IMGLIB_FN (library, png_read_update_info);
5475 LOAD_IMGLIB_FN (library, png_get_channels);
5476 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5477 LOAD_IMGLIB_FN (library, png_read_image);
5478 LOAD_IMGLIB_FN (library, png_read_end);
5479 LOAD_IMGLIB_FN (library, png_error);
5480 return 1;
5482 #else
5484 #define fn_png_get_io_ptr png_get_io_ptr
5485 #define fn_png_sig_cmp png_sig_cmp
5486 #define fn_png_create_read_struct png_create_read_struct
5487 #define fn_png_create_info_struct png_create_info_struct
5488 #define fn_png_destroy_read_struct png_destroy_read_struct
5489 #define fn_png_set_read_fn png_set_read_fn
5490 #define fn_png_set_sig_bytes png_set_sig_bytes
5491 #define fn_png_read_info png_read_info
5492 #define fn_png_get_IHDR png_get_IHDR
5493 #define fn_png_get_valid png_get_valid
5494 #define fn_png_set_strip_16 png_set_strip_16
5495 #define fn_png_set_expand png_set_expand
5496 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5497 #define fn_png_set_background png_set_background
5498 #define fn_png_get_bKGD png_get_bKGD
5499 #define fn_png_read_update_info png_read_update_info
5500 #define fn_png_get_channels png_get_channels
5501 #define fn_png_get_rowbytes png_get_rowbytes
5502 #define fn_png_read_image png_read_image
5503 #define fn_png_read_end png_read_end
5504 #define fn_png_error png_error
5506 #endif /* HAVE_NTGUI */
5508 /* Error and warning handlers installed when the PNG library
5509 is initialized. */
5511 static void
5512 my_png_error (png_struct *png_ptr, const char *msg)
5514 xassert (png_ptr != NULL);
5515 image_error ("PNG error: %s", build_string (msg), Qnil);
5516 longjmp (png_ptr->jmpbuf, 1);
5520 static void
5521 my_png_warning (png_struct *png_ptr, const char *msg)
5523 xassert (png_ptr != NULL);
5524 image_error ("PNG warning: %s", build_string (msg), Qnil);
5527 /* Memory source for PNG decoding. */
5529 struct png_memory_storage
5531 unsigned char *bytes; /* The data */
5532 size_t len; /* How big is it? */
5533 int index; /* Where are we? */
5537 /* Function set as reader function when reading PNG image from memory.
5538 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5539 bytes from the input to DATA. */
5541 static void
5542 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
5544 struct png_memory_storage *tbr
5545 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5547 if (length > tbr->len - tbr->index)
5548 fn_png_error (png_ptr, "Read error");
5550 memcpy (data, tbr->bytes + tbr->index, length);
5551 tbr->index = tbr->index + length;
5555 /* Function set as reader function when reading PNG image from a file.
5556 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5557 bytes from the input to DATA. */
5559 static void
5560 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
5562 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5564 if (fread (data, 1, length, fp) < length)
5565 fn_png_error (png_ptr, "Read error");
5569 /* Load PNG image IMG for use on frame F. Value is non-zero if
5570 successful. */
5572 static int
5573 png_load (struct frame *f, struct image *img)
5575 Lisp_Object file, specified_file;
5576 Lisp_Object specified_data;
5577 int x, y, i;
5578 XImagePtr ximg, mask_img = NULL;
5579 struct gcpro gcpro1;
5580 png_struct *png_ptr = NULL;
5581 png_info *info_ptr = NULL, *end_info = NULL;
5582 FILE *volatile fp = NULL;
5583 png_byte sig[8];
5584 png_byte * volatile pixels = NULL;
5585 png_byte ** volatile rows = NULL;
5586 png_uint_32 width, height;
5587 int bit_depth, color_type, interlace_type;
5588 png_byte channels;
5589 png_uint_32 row_bytes;
5590 int transparent_p;
5591 struct png_memory_storage tbr; /* Data to be read */
5593 /* Find out what file to load. */
5594 specified_file = image_spec_value (img->spec, QCfile, NULL);
5595 specified_data = image_spec_value (img->spec, QCdata, NULL);
5596 file = Qnil;
5597 GCPRO1 (file);
5599 if (NILP (specified_data))
5601 file = x_find_image_file (specified_file);
5602 if (!STRINGP (file))
5604 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5605 UNGCPRO;
5606 return 0;
5609 /* Open the image file. */
5610 fp = fopen (SDATA (file), "rb");
5611 if (!fp)
5613 image_error ("Cannot open image file `%s'", file, Qnil);
5614 UNGCPRO;
5615 return 0;
5618 /* Check PNG signature. */
5619 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5620 || fn_png_sig_cmp (sig, 0, sizeof sig))
5622 image_error ("Not a PNG file: `%s'", file, Qnil);
5623 UNGCPRO;
5624 fclose (fp);
5625 return 0;
5628 else
5630 /* Read from memory. */
5631 tbr.bytes = SDATA (specified_data);
5632 tbr.len = SBYTES (specified_data);
5633 tbr.index = 0;
5635 /* Check PNG signature. */
5636 if (tbr.len < sizeof sig
5637 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5639 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5640 UNGCPRO;
5641 return 0;
5644 /* Need to skip past the signature. */
5645 tbr.bytes += sizeof (sig);
5648 /* Initialize read and info structs for PNG lib. Casting return
5649 value avoids a GCC warning on W32. */
5650 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5651 NULL, my_png_error,
5652 my_png_warning);
5653 if (!png_ptr)
5655 if (fp) fclose (fp);
5656 UNGCPRO;
5657 return 0;
5660 /* Casting return value avoids a GCC warning on W32. */
5661 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
5662 if (!info_ptr)
5664 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5665 if (fp) fclose (fp);
5666 UNGCPRO;
5667 return 0;
5670 /* Casting return value avoids a GCC warning on W32. */
5671 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
5672 if (!end_info)
5674 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5675 if (fp) fclose (fp);
5676 UNGCPRO;
5677 return 0;
5680 /* Set error jump-back. We come back here when the PNG library
5681 detects an error. */
5682 if (setjmp (png_ptr->jmpbuf))
5684 error:
5685 if (png_ptr)
5686 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5687 xfree (pixels);
5688 xfree (rows);
5689 if (fp) fclose (fp);
5690 UNGCPRO;
5691 return 0;
5694 /* Read image info. */
5695 if (!NILP (specified_data))
5696 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5697 else
5698 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5700 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5701 fn_png_read_info (png_ptr, info_ptr);
5702 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5703 &interlace_type, NULL, NULL);
5705 if (!check_image_size (f, width, height))
5707 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5708 goto error;
5710 /* If image contains simply transparency data, we prefer to
5711 construct a clipping mask. */
5712 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5713 transparent_p = 1;
5714 else
5715 transparent_p = 0;
5717 /* This function is easier to write if we only have to handle
5718 one data format: RGB or RGBA with 8 bits per channel. Let's
5719 transform other formats into that format. */
5721 /* Strip more than 8 bits per channel. */
5722 if (bit_depth == 16)
5723 fn_png_set_strip_16 (png_ptr);
5725 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5726 if available. */
5727 fn_png_set_expand (png_ptr);
5729 /* Convert grayscale images to RGB. */
5730 if (color_type == PNG_COLOR_TYPE_GRAY
5731 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5732 fn_png_set_gray_to_rgb (png_ptr);
5734 /* Handle alpha channel by combining the image with a background
5735 color. Do this only if a real alpha channel is supplied. For
5736 simple transparency, we prefer a clipping mask. */
5737 if (!transparent_p)
5739 /* png_color_16 *image_bg; */
5740 Lisp_Object specified_bg
5741 = image_spec_value (img->spec, QCbackground, NULL);
5742 int shift = (bit_depth == 16) ? 0 : 8;
5744 if (STRINGP (specified_bg))
5745 /* The user specified `:background', use that. */
5747 XColor color;
5748 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
5750 png_color_16 user_bg;
5752 memset (&user_bg, 0, sizeof user_bg);
5753 user_bg.red = color.red >> shift;
5754 user_bg.green = color.green >> shift;
5755 user_bg.blue = color.blue >> shift;
5757 fn_png_set_background (png_ptr, &user_bg,
5758 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5761 else
5763 /* We use the current frame background, ignoring any default
5764 background color set by the image. */
5765 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5766 XColor color;
5767 png_color_16 frame_background;
5769 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5770 x_query_color (f, &color);
5772 memset (&frame_background, 0, sizeof frame_background);
5773 frame_background.red = color.red >> shift;
5774 frame_background.green = color.green >> shift;
5775 frame_background.blue = color.blue >> shift;
5776 #endif /* HAVE_X_WINDOWS */
5778 fn_png_set_background (png_ptr, &frame_background,
5779 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5783 /* Update info structure. */
5784 fn_png_read_update_info (png_ptr, info_ptr);
5786 /* Get number of channels. Valid values are 1 for grayscale images
5787 and images with a palette, 2 for grayscale images with transparency
5788 information (alpha channel), 3 for RGB images, and 4 for RGB
5789 images with alpha channel, i.e. RGBA. If conversions above were
5790 sufficient we should only have 3 or 4 channels here. */
5791 channels = fn_png_get_channels (png_ptr, info_ptr);
5792 xassert (channels == 3 || channels == 4);
5794 /* Number of bytes needed for one row of the image. */
5795 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5797 /* Allocate memory for the image. */
5798 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
5799 rows = (png_byte **) xmalloc (height * sizeof *rows);
5800 for (i = 0; i < height; ++i)
5801 rows[i] = pixels + i * row_bytes;
5803 /* Read the entire image. */
5804 fn_png_read_image (png_ptr, rows);
5805 fn_png_read_end (png_ptr, info_ptr);
5806 if (fp)
5808 fclose (fp);
5809 fp = NULL;
5812 /* Create the X image and pixmap. */
5813 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5814 &img->pixmap))
5815 goto error;
5817 /* Create an image and pixmap serving as mask if the PNG image
5818 contains an alpha channel. */
5819 if (channels == 4
5820 && !transparent_p
5821 && !x_create_x_image_and_pixmap (f, width, height, 1,
5822 &mask_img, &img->mask))
5824 x_destroy_x_image (ximg);
5825 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5826 img->pixmap = NO_PIXMAP;
5827 goto error;
5830 /* Fill the X image and mask from PNG data. */
5831 init_color_table ();
5833 for (y = 0; y < height; ++y)
5835 png_byte *p = rows[y];
5837 for (x = 0; x < width; ++x)
5839 unsigned r, g, b;
5841 r = *p++ << 8;
5842 g = *p++ << 8;
5843 b = *p++ << 8;
5844 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5845 /* An alpha channel, aka mask channel, associates variable
5846 transparency with an image. Where other image formats
5847 support binary transparency---fully transparent or fully
5848 opaque---PNG allows up to 254 levels of partial transparency.
5849 The PNG library implements partial transparency by combining
5850 the image with a specified background color.
5852 I'm not sure how to handle this here nicely: because the
5853 background on which the image is displayed may change, for
5854 real alpha channel support, it would be necessary to create
5855 a new image for each possible background.
5857 What I'm doing now is that a mask is created if we have
5858 boolean transparency information. Otherwise I'm using
5859 the frame's background color to combine the image with. */
5861 if (channels == 4)
5863 if (mask_img)
5864 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
5865 ++p;
5870 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5871 /* Set IMG's background color from the PNG image, unless the user
5872 overrode it. */
5874 png_color_16 *bg;
5875 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
5877 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
5878 img->background_valid = 1;
5882 #ifdef COLOR_TABLE_SUPPORT
5883 /* Remember colors allocated for this image. */
5884 img->colors = colors_in_color_table (&img->ncolors);
5885 free_color_table ();
5886 #endif /* COLOR_TABLE_SUPPORT */
5888 /* Clean up. */
5889 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5890 xfree (rows);
5891 xfree (pixels);
5893 img->width = width;
5894 img->height = height;
5896 /* Maybe fill in the background field while we have ximg handy.
5897 Casting avoids a GCC warning. */
5898 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5900 /* Put the image into the pixmap, then free the X image and its buffer. */
5901 x_put_x_image (f, ximg, img->pixmap, width, height);
5902 x_destroy_x_image (ximg);
5904 /* Same for the mask. */
5905 if (mask_img)
5907 /* Fill in the background_transparent field while we have the
5908 mask handy. Casting avoids a GCC warning. */
5909 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
5911 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5912 x_destroy_x_image (mask_img);
5915 UNGCPRO;
5916 return 1;
5919 #else /* HAVE_PNG */
5921 #ifdef HAVE_NS
5922 static int
5923 png_load (struct frame *f, struct image *img)
5925 return ns_load_image(f, img,
5926 image_spec_value (img->spec, QCfile, NULL),
5927 image_spec_value (img->spec, QCdata, NULL));
5929 #endif /* HAVE_NS */
5932 #endif /* !HAVE_PNG */
5936 /***********************************************************************
5937 JPEG
5938 ***********************************************************************/
5940 #if defined (HAVE_JPEG) || defined (HAVE_NS)
5942 static int jpeg_image_p (Lisp_Object object);
5943 static int jpeg_load (struct frame *f, struct image *img);
5945 /* The symbol `jpeg' identifying images of this type. */
5947 Lisp_Object Qjpeg;
5949 /* Indices of image specification fields in gs_format, below. */
5951 enum jpeg_keyword_index
5953 JPEG_TYPE,
5954 JPEG_DATA,
5955 JPEG_FILE,
5956 JPEG_ASCENT,
5957 JPEG_MARGIN,
5958 JPEG_RELIEF,
5959 JPEG_ALGORITHM,
5960 JPEG_HEURISTIC_MASK,
5961 JPEG_MASK,
5962 JPEG_BACKGROUND,
5963 JPEG_LAST
5966 /* Vector of image_keyword structures describing the format
5967 of valid user-defined image specifications. */
5969 static const struct image_keyword jpeg_format[JPEG_LAST] =
5971 {":type", IMAGE_SYMBOL_VALUE, 1},
5972 {":data", IMAGE_STRING_VALUE, 0},
5973 {":file", IMAGE_STRING_VALUE, 0},
5974 {":ascent", IMAGE_ASCENT_VALUE, 0},
5975 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5976 {":relief", IMAGE_INTEGER_VALUE, 0},
5977 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5978 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5979 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5980 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5983 /* Structure describing the image type `jpeg'. */
5985 static struct image_type jpeg_type =
5987 &Qjpeg,
5988 jpeg_image_p,
5989 jpeg_load,
5990 x_clear_image,
5991 NULL
5994 /* Return non-zero if OBJECT is a valid JPEG image specification. */
5996 static int
5997 jpeg_image_p (Lisp_Object object)
5999 struct image_keyword fmt[JPEG_LAST];
6001 memcpy (fmt, jpeg_format, sizeof fmt);
6003 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6004 return 0;
6006 /* Must specify either the :data or :file keyword. */
6007 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6010 #endif /* HAVE_JPEG || HAVE_NS */
6012 #ifdef HAVE_JPEG
6014 /* Work around a warning about HAVE_STDLIB_H being redefined in
6015 jconfig.h. */
6016 #ifdef HAVE_STDLIB_H
6017 #define HAVE_STDLIB_H_1
6018 #undef HAVE_STDLIB_H
6019 #endif /* HAVE_STLIB_H */
6021 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6022 /* In older releases of the jpeg library, jpeglib.h will define boolean
6023 differently depending on __WIN32__, so make sure it is defined. */
6024 #define __WIN32__ 1
6025 #endif
6027 #include <jpeglib.h>
6028 #include <jerror.h>
6030 #ifdef HAVE_STLIB_H_1
6031 #define HAVE_STDLIB_H 1
6032 #endif
6034 #ifdef HAVE_NTGUI
6036 /* JPEG library details. */
6037 DEF_IMGLIB_FN (jpeg_CreateDecompress);
6038 DEF_IMGLIB_FN (jpeg_start_decompress);
6039 DEF_IMGLIB_FN (jpeg_finish_decompress);
6040 DEF_IMGLIB_FN (jpeg_destroy_decompress);
6041 DEF_IMGLIB_FN (jpeg_read_header);
6042 DEF_IMGLIB_FN (jpeg_read_scanlines);
6043 DEF_IMGLIB_FN (jpeg_std_error);
6044 DEF_IMGLIB_FN (jpeg_resync_to_restart);
6046 static int
6047 init_jpeg_functions (Lisp_Object libraries)
6049 HMODULE library;
6051 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6052 return 0;
6054 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6055 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6056 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6057 LOAD_IMGLIB_FN (library, jpeg_read_header);
6058 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6059 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6060 LOAD_IMGLIB_FN (library, jpeg_std_error);
6061 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6062 return 1;
6065 /* Wrapper since we can't directly assign the function pointer
6066 to another function pointer that was declared more completely easily. */
6067 static boolean
6068 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
6070 return fn_jpeg_resync_to_restart (cinfo, desired);
6073 #else
6075 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6076 #define fn_jpeg_start_decompress jpeg_start_decompress
6077 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6078 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6079 #define fn_jpeg_read_header jpeg_read_header
6080 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6081 #define fn_jpeg_std_error jpeg_std_error
6082 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6084 #endif /* HAVE_NTGUI */
6086 struct my_jpeg_error_mgr
6088 struct jpeg_error_mgr pub;
6089 jmp_buf setjmp_buffer;
6093 static void
6094 my_error_exit (j_common_ptr cinfo)
6096 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6097 longjmp (mgr->setjmp_buffer, 1);
6101 /* Init source method for JPEG data source manager. Called by
6102 jpeg_read_header() before any data is actually read. See
6103 libjpeg.doc from the JPEG lib distribution. */
6105 static void
6106 our_common_init_source (j_decompress_ptr cinfo)
6111 /* Method to terminate data source. Called by
6112 jpeg_finish_decompress() after all data has been processed. */
6114 static void
6115 our_common_term_source (j_decompress_ptr cinfo)
6120 /* Fill input buffer method for JPEG data source manager. Called
6121 whenever more data is needed. We read the whole image in one step,
6122 so this only adds a fake end of input marker at the end. */
6124 static JOCTET our_memory_buffer[2];
6126 static boolean
6127 our_memory_fill_input_buffer (j_decompress_ptr cinfo)
6129 /* Insert a fake EOI marker. */
6130 struct jpeg_source_mgr *src = cinfo->src;
6132 our_memory_buffer[0] = (JOCTET) 0xFF;
6133 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6135 src->next_input_byte = our_memory_buffer;
6136 src->bytes_in_buffer = 2;
6137 return 1;
6141 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6142 is the JPEG data source manager. */
6144 static void
6145 our_memory_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6147 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6149 if (src)
6151 if (num_bytes > src->bytes_in_buffer)
6152 ERREXIT (cinfo, JERR_INPUT_EOF);
6154 src->bytes_in_buffer -= num_bytes;
6155 src->next_input_byte += num_bytes;
6160 /* Set up the JPEG lib for reading an image from DATA which contains
6161 LEN bytes. CINFO is the decompression info structure created for
6162 reading the image. */
6164 static void
6165 jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, unsigned int len)
6167 struct jpeg_source_mgr *src;
6169 if (cinfo->src == NULL)
6171 /* First time for this JPEG object? */
6172 cinfo->src = (struct jpeg_source_mgr *)
6173 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6174 sizeof (struct jpeg_source_mgr));
6175 src = (struct jpeg_source_mgr *) cinfo->src;
6176 src->next_input_byte = data;
6179 src = (struct jpeg_source_mgr *) cinfo->src;
6180 src->init_source = our_common_init_source;
6181 src->fill_input_buffer = our_memory_fill_input_buffer;
6182 src->skip_input_data = our_memory_skip_input_data;
6183 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6184 src->term_source = our_common_term_source;
6185 src->bytes_in_buffer = len;
6186 src->next_input_byte = data;
6190 struct jpeg_stdio_mgr
6192 struct jpeg_source_mgr mgr;
6193 boolean finished;
6194 FILE *file;
6195 JOCTET *buffer;
6199 /* Size of buffer to read JPEG from file.
6200 Not too big, as we want to use alloc_small. */
6201 #define JPEG_STDIO_BUFFER_SIZE 8192
6204 /* Fill input buffer method for JPEG data source manager. Called
6205 whenever more data is needed. The data is read from a FILE *. */
6207 static boolean
6208 our_stdio_fill_input_buffer (j_decompress_ptr cinfo)
6210 struct jpeg_stdio_mgr *src;
6212 src = (struct jpeg_stdio_mgr *) cinfo->src;
6213 if (!src->finished)
6215 size_t bytes;
6217 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6218 if (bytes > 0)
6219 src->mgr.bytes_in_buffer = bytes;
6220 else
6222 WARNMS (cinfo, JWRN_JPEG_EOF);
6223 src->finished = 1;
6224 src->buffer[0] = (JOCTET) 0xFF;
6225 src->buffer[1] = (JOCTET) JPEG_EOI;
6226 src->mgr.bytes_in_buffer = 2;
6228 src->mgr.next_input_byte = src->buffer;
6231 return 1;
6235 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6236 is the JPEG data source manager. */
6238 static void
6239 our_stdio_skip_input_data (j_decompress_ptr cinfo, long int num_bytes)
6241 struct jpeg_stdio_mgr *src;
6242 src = (struct jpeg_stdio_mgr *) cinfo->src;
6244 while (num_bytes > 0 && !src->finished)
6246 if (num_bytes <= src->mgr.bytes_in_buffer)
6248 src->mgr.bytes_in_buffer -= num_bytes;
6249 src->mgr.next_input_byte += num_bytes;
6250 break;
6252 else
6254 num_bytes -= src->mgr.bytes_in_buffer;
6255 src->mgr.bytes_in_buffer = 0;
6256 src->mgr.next_input_byte = NULL;
6258 our_stdio_fill_input_buffer (cinfo);
6264 /* Set up the JPEG lib for reading an image from a FILE *.
6265 CINFO is the decompression info structure created for
6266 reading the image. */
6268 static void
6269 jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
6271 struct jpeg_stdio_mgr *src;
6273 if (cinfo->src != NULL)
6274 src = (struct jpeg_stdio_mgr *) cinfo->src;
6275 else
6277 /* First time for this JPEG object? */
6278 cinfo->src = (struct jpeg_source_mgr *)
6279 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6280 sizeof (struct jpeg_stdio_mgr));
6281 src = (struct jpeg_stdio_mgr *) cinfo->src;
6282 src->buffer = (JOCTET *)
6283 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6284 JPEG_STDIO_BUFFER_SIZE);
6287 src->file = fp;
6288 src->finished = 0;
6289 src->mgr.init_source = our_common_init_source;
6290 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6291 src->mgr.skip_input_data = our_stdio_skip_input_data;
6292 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6293 src->mgr.term_source = our_common_term_source;
6294 src->mgr.bytes_in_buffer = 0;
6295 src->mgr.next_input_byte = NULL;
6299 /* Load image IMG for use on frame F. Patterned after example.c
6300 from the JPEG lib. */
6302 static int
6303 jpeg_load (struct frame *f, struct image *img)
6305 struct jpeg_decompress_struct cinfo;
6306 struct my_jpeg_error_mgr mgr;
6307 Lisp_Object file, specified_file;
6308 Lisp_Object specified_data;
6309 FILE * volatile fp = NULL;
6310 JSAMPARRAY buffer;
6311 int row_stride, x, y;
6312 XImagePtr ximg = NULL;
6313 int rc;
6314 unsigned long *colors;
6315 int width, height;
6316 struct gcpro gcpro1;
6318 /* Open the JPEG file. */
6319 specified_file = image_spec_value (img->spec, QCfile, NULL);
6320 specified_data = image_spec_value (img->spec, QCdata, NULL);
6321 file = Qnil;
6322 GCPRO1 (file);
6324 if (NILP (specified_data))
6326 file = x_find_image_file (specified_file);
6327 if (!STRINGP (file))
6329 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6330 UNGCPRO;
6331 return 0;
6334 fp = fopen (SDATA (file), "rb");
6335 if (fp == NULL)
6337 image_error ("Cannot open `%s'", file, Qnil);
6338 UNGCPRO;
6339 return 0;
6343 /* Customize libjpeg's error handling to call my_error_exit when an
6344 error is detected. This function will perform a longjmp.
6345 Casting return value avoids a GCC warning on W32. */
6346 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
6347 mgr.pub.error_exit = my_error_exit;
6349 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6351 if (rc == 1)
6353 /* Called from my_error_exit. Display a JPEG error. */
6354 char buffer[JMSG_LENGTH_MAX];
6355 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
6356 image_error ("Error reading JPEG image `%s': %s", img->spec,
6357 build_string (buffer));
6360 /* Close the input file and destroy the JPEG object. */
6361 if (fp)
6362 fclose ((FILE *) fp);
6363 fn_jpeg_destroy_decompress (&cinfo);
6365 /* If we already have an XImage, free that. */
6366 x_destroy_x_image (ximg);
6368 /* Free pixmap and colors. */
6369 x_clear_image (f, img);
6371 UNGCPRO;
6372 return 0;
6375 /* Create the JPEG decompression object. Let it read from fp.
6376 Read the JPEG image header. */
6377 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6379 if (NILP (specified_data))
6380 jpeg_file_src (&cinfo, (FILE *) fp);
6381 else
6382 jpeg_memory_src (&cinfo, SDATA (specified_data),
6383 SBYTES (specified_data));
6385 fn_jpeg_read_header (&cinfo, 1);
6387 /* Customize decompression so that color quantization will be used.
6388 Start decompression. */
6389 cinfo.quantize_colors = 1;
6390 fn_jpeg_start_decompress (&cinfo);
6391 width = img->width = cinfo.output_width;
6392 height = img->height = cinfo.output_height;
6394 if (!check_image_size (f, width, height))
6396 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6397 longjmp (mgr.setjmp_buffer, 2);
6400 /* Create X image and pixmap. */
6401 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6402 longjmp (mgr.setjmp_buffer, 2);
6404 /* Allocate colors. When color quantization is used,
6405 cinfo.actual_number_of_colors has been set with the number of
6406 colors generated, and cinfo.colormap is a two-dimensional array
6407 of color indices in the range 0..cinfo.actual_number_of_colors.
6408 No more than 255 colors will be generated. */
6410 int i, ir, ig, ib;
6412 if (cinfo.out_color_components > 2)
6413 ir = 0, ig = 1, ib = 2;
6414 else if (cinfo.out_color_components > 1)
6415 ir = 0, ig = 1, ib = 0;
6416 else
6417 ir = 0, ig = 0, ib = 0;
6419 /* Use the color table mechanism because it handles colors that
6420 cannot be allocated nicely. Such colors will be replaced with
6421 a default color, and we don't have to care about which colors
6422 can be freed safely, and which can't. */
6423 init_color_table ();
6424 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6425 * sizeof *colors);
6427 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6429 /* Multiply RGB values with 255 because X expects RGB values
6430 in the range 0..0xffff. */
6431 int r = cinfo.colormap[ir][i] << 8;
6432 int g = cinfo.colormap[ig][i] << 8;
6433 int b = cinfo.colormap[ib][i] << 8;
6434 colors[i] = lookup_rgb_color (f, r, g, b);
6437 #ifdef COLOR_TABLE_SUPPORT
6438 /* Remember those colors actually allocated. */
6439 img->colors = colors_in_color_table (&img->ncolors);
6440 free_color_table ();
6441 #endif /* COLOR_TABLE_SUPPORT */
6444 /* Read pixels. */
6445 row_stride = width * cinfo.output_components;
6446 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6447 row_stride, 1);
6448 for (y = 0; y < height; ++y)
6450 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6451 for (x = 0; x < cinfo.output_width; ++x)
6452 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6455 /* Clean up. */
6456 fn_jpeg_finish_decompress (&cinfo);
6457 fn_jpeg_destroy_decompress (&cinfo);
6458 if (fp)
6459 fclose ((FILE *) fp);
6461 /* Maybe fill in the background field while we have ximg handy. */
6462 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6463 /* Casting avoids a GCC warning. */
6464 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6466 /* Put the image into the pixmap. */
6467 x_put_x_image (f, ximg, img->pixmap, width, height);
6468 x_destroy_x_image (ximg);
6469 UNGCPRO;
6470 return 1;
6473 #else /* HAVE_JPEG */
6475 #ifdef HAVE_NS
6476 static int
6477 jpeg_load (struct frame *f, struct image *img)
6479 return ns_load_image (f, img,
6480 image_spec_value (img->spec, QCfile, NULL),
6481 image_spec_value (img->spec, QCdata, NULL));
6483 #endif /* HAVE_NS */
6485 #endif /* !HAVE_JPEG */
6489 /***********************************************************************
6490 TIFF
6491 ***********************************************************************/
6493 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6495 static int tiff_image_p (Lisp_Object object);
6496 static int tiff_load (struct frame *f, struct image *img);
6498 /* The symbol `tiff' identifying images of this type. */
6500 Lisp_Object Qtiff;
6502 /* Indices of image specification fields in tiff_format, below. */
6504 enum tiff_keyword_index
6506 TIFF_TYPE,
6507 TIFF_DATA,
6508 TIFF_FILE,
6509 TIFF_ASCENT,
6510 TIFF_MARGIN,
6511 TIFF_RELIEF,
6512 TIFF_ALGORITHM,
6513 TIFF_HEURISTIC_MASK,
6514 TIFF_MASK,
6515 TIFF_BACKGROUND,
6516 TIFF_INDEX,
6517 TIFF_LAST
6520 /* Vector of image_keyword structures describing the format
6521 of valid user-defined image specifications. */
6523 static const struct image_keyword tiff_format[TIFF_LAST] =
6525 {":type", IMAGE_SYMBOL_VALUE, 1},
6526 {":data", IMAGE_STRING_VALUE, 0},
6527 {":file", IMAGE_STRING_VALUE, 0},
6528 {":ascent", IMAGE_ASCENT_VALUE, 0},
6529 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6530 {":relief", IMAGE_INTEGER_VALUE, 0},
6531 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6532 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6533 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6534 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6535 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6538 /* Structure describing the image type `tiff'. */
6540 static struct image_type tiff_type =
6542 &Qtiff,
6543 tiff_image_p,
6544 tiff_load,
6545 x_clear_image,
6546 NULL
6549 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6551 static int
6552 tiff_image_p (Lisp_Object object)
6554 struct image_keyword fmt[TIFF_LAST];
6555 memcpy (fmt, tiff_format, sizeof fmt);
6557 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6558 return 0;
6560 /* Must specify either the :data or :file keyword. */
6561 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6564 #endif /* HAVE_TIFF || HAVE_NS */
6566 #ifdef HAVE_TIFF
6568 #include <tiffio.h>
6570 #ifdef HAVE_NTGUI
6572 /* TIFF library details. */
6573 DEF_IMGLIB_FN (TIFFSetErrorHandler);
6574 DEF_IMGLIB_FN (TIFFSetWarningHandler);
6575 DEF_IMGLIB_FN (TIFFOpen);
6576 DEF_IMGLIB_FN (TIFFClientOpen);
6577 DEF_IMGLIB_FN (TIFFGetField);
6578 DEF_IMGLIB_FN (TIFFReadRGBAImage);
6579 DEF_IMGLIB_FN (TIFFClose);
6580 DEF_IMGLIB_FN (TIFFSetDirectory);
6582 static int
6583 init_tiff_functions (Lisp_Object libraries)
6585 HMODULE library;
6587 if (!(library = w32_delayed_load (libraries, Qtiff)))
6588 return 0;
6590 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6591 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6592 LOAD_IMGLIB_FN (library, TIFFOpen);
6593 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6594 LOAD_IMGLIB_FN (library, TIFFGetField);
6595 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6596 LOAD_IMGLIB_FN (library, TIFFClose);
6597 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6598 return 1;
6601 #else
6603 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6604 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6605 #define fn_TIFFOpen TIFFOpen
6606 #define fn_TIFFClientOpen TIFFClientOpen
6607 #define fn_TIFFGetField TIFFGetField
6608 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6609 #define fn_TIFFClose TIFFClose
6610 #define fn_TIFFSetDirectory TIFFSetDirectory
6611 #endif /* HAVE_NTGUI */
6614 /* Reading from a memory buffer for TIFF images Based on the PNG
6615 memory source, but we have to provide a lot of extra functions.
6616 Blah.
6618 We really only need to implement read and seek, but I am not
6619 convinced that the TIFF library is smart enough not to destroy
6620 itself if we only hand it the function pointers we need to
6621 override. */
6623 typedef struct
6625 unsigned char *bytes;
6626 size_t len;
6627 int index;
6629 tiff_memory_source;
6631 static size_t
6632 tiff_read_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6634 tiff_memory_source *src = (tiff_memory_source *) data;
6636 if (size > src->len - src->index)
6637 return (size_t) -1;
6638 memcpy (buf, src->bytes + src->index, size);
6639 src->index += size;
6640 return size;
6643 static size_t
6644 tiff_write_from_memory (thandle_t data, tdata_t buf, tsize_t size)
6646 return (size_t) -1;
6649 static toff_t
6650 tiff_seek_in_memory (thandle_t data, toff_t off, int whence)
6652 tiff_memory_source *src = (tiff_memory_source *) data;
6653 int idx;
6655 switch (whence)
6657 case SEEK_SET: /* Go from beginning of source. */
6658 idx = off;
6659 break;
6661 case SEEK_END: /* Go from end of source. */
6662 idx = src->len + off;
6663 break;
6665 case SEEK_CUR: /* Go from current position. */
6666 idx = src->index + off;
6667 break;
6669 default: /* Invalid `whence'. */
6670 return -1;
6673 if (idx > src->len || idx < 0)
6674 return -1;
6676 src->index = idx;
6677 return src->index;
6680 static int
6681 tiff_close_memory (thandle_t data)
6683 /* NOOP */
6684 return 0;
6687 static int
6688 tiff_mmap_memory (thandle_t data, tdata_t *pbase, toff_t *psize)
6690 /* It is already _IN_ memory. */
6691 return 0;
6694 static void
6695 tiff_unmap_memory (thandle_t data, tdata_t base, toff_t size)
6697 /* We don't need to do this. */
6700 static toff_t
6701 tiff_size_of_memory (thandle_t data)
6703 return ((tiff_memory_source *) data)->len;
6707 static void
6708 tiff_error_handler (const char *title, const char *format, va_list ap)
6710 char buf[512];
6711 int len;
6713 len = sprintf (buf, "TIFF error: %s ", title);
6714 vsprintf (buf + len, format, ap);
6715 add_to_log (buf, Qnil, Qnil);
6719 static void
6720 tiff_warning_handler (const char *title, const char *format, va_list ap)
6722 char buf[512];
6723 int len;
6725 len = sprintf (buf, "TIFF warning: %s ", title);
6726 vsprintf (buf + len, format, ap);
6727 add_to_log (buf, Qnil, Qnil);
6731 /* Load TIFF image IMG for use on frame F. Value is non-zero if
6732 successful. */
6734 static int
6735 tiff_load (struct frame *f, struct image *img)
6737 Lisp_Object file, specified_file;
6738 Lisp_Object specified_data;
6739 TIFF *tiff;
6740 int width, height, x, y, count;
6741 uint32 *buf;
6742 int rc, rc2;
6743 XImagePtr ximg;
6744 struct gcpro gcpro1;
6745 tiff_memory_source memsrc;
6746 Lisp_Object image;
6748 specified_file = image_spec_value (img->spec, QCfile, NULL);
6749 specified_data = image_spec_value (img->spec, QCdata, NULL);
6750 file = Qnil;
6751 GCPRO1 (file);
6753 fn_TIFFSetErrorHandler (tiff_error_handler);
6754 fn_TIFFSetWarningHandler (tiff_warning_handler);
6756 if (NILP (specified_data))
6758 /* Read from a file */
6759 file = x_find_image_file (specified_file);
6760 if (!STRINGP (file))
6762 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6763 UNGCPRO;
6764 return 0;
6767 /* Try to open the image file. Casting return value avoids a
6768 GCC warning on W32. */
6769 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
6770 if (tiff == NULL)
6772 image_error ("Cannot open `%s'", file, Qnil);
6773 UNGCPRO;
6774 return 0;
6777 else
6779 /* Memory source! */
6780 memsrc.bytes = SDATA (specified_data);
6781 memsrc.len = SBYTES (specified_data);
6782 memsrc.index = 0;
6784 /* Casting return value avoids a GCC warning on W32. */
6785 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r", &memsrc,
6786 (TIFFReadWriteProc) tiff_read_from_memory,
6787 (TIFFReadWriteProc) tiff_write_from_memory,
6788 tiff_seek_in_memory,
6789 tiff_close_memory,
6790 tiff_size_of_memory,
6791 tiff_mmap_memory,
6792 tiff_unmap_memory);
6794 if (!tiff)
6796 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6797 UNGCPRO;
6798 return 0;
6802 image = image_spec_value (img->spec, QCindex, NULL);
6803 if (INTEGERP (image))
6805 int ino = XFASTINT (image);
6806 if (!fn_TIFFSetDirectory (tiff, ino))
6808 image_error ("Invalid image number `%s' in image `%s'",
6809 image, img->spec);
6810 fn_TIFFClose (tiff);
6811 UNGCPRO;
6812 return 0;
6816 /* Get width and height of the image, and allocate a raster buffer
6817 of width x height 32-bit values. */
6818 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
6819 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6821 if (!check_image_size (f, width, height))
6823 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6824 fn_TIFFClose (tiff);
6825 UNGCPRO;
6826 return 0;
6829 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
6831 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
6833 /* Count the number of images in the file. */
6834 for (count = 1, rc2 = 1; rc2; count++)
6835 rc2 = fn_TIFFSetDirectory (tiff, count);
6837 if (count > 1)
6838 img->data.lisp_val = Fcons (Qcount,
6839 Fcons (make_number (count),
6840 img->data.lisp_val));
6842 fn_TIFFClose (tiff);
6843 if (!rc)
6845 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
6846 xfree (buf);
6847 UNGCPRO;
6848 return 0;
6851 /* Create the X image and pixmap. */
6852 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6854 xfree (buf);
6855 UNGCPRO;
6856 return 0;
6859 /* Initialize the color table. */
6860 init_color_table ();
6862 /* Process the pixel raster. Origin is in the lower-left corner. */
6863 for (y = 0; y < height; ++y)
6865 uint32 *row = buf + y * width;
6867 for (x = 0; x < width; ++x)
6869 uint32 abgr = row[x];
6870 int r = TIFFGetR (abgr) << 8;
6871 int g = TIFFGetG (abgr) << 8;
6872 int b = TIFFGetB (abgr) << 8;
6873 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
6877 #ifdef COLOR_TABLE_SUPPORT
6878 /* Remember the colors allocated for the image. Free the color table. */
6879 img->colors = colors_in_color_table (&img->ncolors);
6880 free_color_table ();
6881 #endif /* COLOR_TABLE_SUPPORT */
6883 img->width = width;
6884 img->height = height;
6886 /* Maybe fill in the background field while we have ximg handy. */
6887 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6888 /* Casting avoids a GCC warning on W32. */
6889 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6891 /* Put the image into the pixmap, then free the X image and its buffer. */
6892 x_put_x_image (f, ximg, img->pixmap, width, height);
6893 x_destroy_x_image (ximg);
6894 xfree (buf);
6896 UNGCPRO;
6897 return 1;
6900 #else /* HAVE_TIFF */
6902 #ifdef HAVE_NS
6903 static int
6904 tiff_load (struct frame *f, struct image *img)
6906 return ns_load_image (f, img,
6907 image_spec_value (img->spec, QCfile, NULL),
6908 image_spec_value (img->spec, QCdata, NULL));
6910 #endif /* HAVE_NS */
6912 #endif /* !HAVE_TIFF */
6916 /***********************************************************************
6918 ***********************************************************************/
6920 #if defined (HAVE_GIF) || defined (HAVE_NS)
6922 static int gif_image_p (Lisp_Object object);
6923 static int gif_load (struct frame *f, struct image *img);
6924 static void gif_clear_image (struct frame *f, struct image *img);
6926 /* The symbol `gif' identifying images of this type. */
6928 Lisp_Object Qgif;
6930 /* Indices of image specification fields in gif_format, below. */
6932 enum gif_keyword_index
6934 GIF_TYPE,
6935 GIF_DATA,
6936 GIF_FILE,
6937 GIF_ASCENT,
6938 GIF_MARGIN,
6939 GIF_RELIEF,
6940 GIF_ALGORITHM,
6941 GIF_HEURISTIC_MASK,
6942 GIF_MASK,
6943 GIF_IMAGE,
6944 GIF_BACKGROUND,
6945 GIF_LAST
6948 /* Vector of image_keyword structures describing the format
6949 of valid user-defined image specifications. */
6951 static const struct image_keyword gif_format[GIF_LAST] =
6953 {":type", IMAGE_SYMBOL_VALUE, 1},
6954 {":data", IMAGE_STRING_VALUE, 0},
6955 {":file", IMAGE_STRING_VALUE, 0},
6956 {":ascent", IMAGE_ASCENT_VALUE, 0},
6957 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6958 {":relief", IMAGE_INTEGER_VALUE, 0},
6959 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6960 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6961 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6962 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
6963 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6966 /* Structure describing the image type `gif'. */
6968 static struct image_type gif_type =
6970 &Qgif,
6971 gif_image_p,
6972 gif_load,
6973 gif_clear_image,
6974 NULL
6977 /* Free X resources of GIF image IMG which is used on frame F. */
6979 static void
6980 gif_clear_image (struct frame *f, struct image *img)
6982 /* IMG->data.ptr_val may contain metadata with extension data. */
6983 img->data.lisp_val = Qnil;
6984 x_clear_image (f, img);
6987 /* Return non-zero if OBJECT is a valid GIF image specification. */
6989 static int
6990 gif_image_p (Lisp_Object object)
6992 struct image_keyword fmt[GIF_LAST];
6993 memcpy (fmt, gif_format, sizeof fmt);
6995 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
6996 return 0;
6998 /* Must specify either the :data or :file keyword. */
6999 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7002 #endif /* HAVE_GIF */
7004 #ifdef HAVE_GIF
7006 #if defined (HAVE_NTGUI)
7007 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7008 Undefine before redefining to avoid a preprocessor warning. */
7009 #ifdef DrawText
7010 #undef DrawText
7011 #endif
7012 /* avoid conflict with QuickdrawText.h */
7013 #define DrawText gif_DrawText
7014 #include <gif_lib.h>
7015 #undef DrawText
7017 #else /* HAVE_NTGUI */
7019 #include <gif_lib.h>
7021 #endif /* HAVE_NTGUI */
7024 #ifdef HAVE_NTGUI
7026 /* GIF library details. */
7027 DEF_IMGLIB_FN (DGifCloseFile);
7028 DEF_IMGLIB_FN (DGifSlurp);
7029 DEF_IMGLIB_FN (DGifOpen);
7030 DEF_IMGLIB_FN (DGifOpenFileName);
7032 static int
7033 init_gif_functions (Lisp_Object libraries)
7035 HMODULE library;
7037 if (!(library = w32_delayed_load (libraries, Qgif)))
7038 return 0;
7040 LOAD_IMGLIB_FN (library, DGifCloseFile);
7041 LOAD_IMGLIB_FN (library, DGifSlurp);
7042 LOAD_IMGLIB_FN (library, DGifOpen);
7043 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7044 return 1;
7047 #else
7049 #define fn_DGifCloseFile DGifCloseFile
7050 #define fn_DGifSlurp DGifSlurp
7051 #define fn_DGifOpen DGifOpen
7052 #define fn_DGifOpenFileName DGifOpenFileName
7054 #endif /* HAVE_NTGUI */
7056 /* Reading a GIF image from memory
7057 Based on the PNG memory stuff to a certain extent. */
7059 typedef struct
7061 unsigned char *bytes;
7062 size_t len;
7063 int index;
7065 gif_memory_source;
7067 /* Make the current memory source available to gif_read_from_memory.
7068 It's done this way because not all versions of libungif support
7069 a UserData field in the GifFileType structure. */
7070 static gif_memory_source *current_gif_memory_src;
7072 static int
7073 gif_read_from_memory (GifFileType *file, GifByteType *buf, int len)
7075 gif_memory_source *src = current_gif_memory_src;
7077 if (len > src->len - src->index)
7078 return -1;
7080 memcpy (buf, src->bytes + src->index, len);
7081 src->index += len;
7082 return len;
7086 /* Load GIF image IMG for use on frame F. Value is non-zero if
7087 successful. */
7089 static const int interlace_start[] = {0, 4, 2, 1};
7090 static const int interlace_increment[] = {8, 8, 4, 2};
7092 static int
7093 gif_load (struct frame *f, struct image *img)
7095 Lisp_Object file, specified_file;
7096 Lisp_Object specified_data;
7097 int rc, width, height, x, y, i;
7098 XImagePtr ximg;
7099 ColorMapObject *gif_color_map;
7100 unsigned long pixel_colors[256];
7101 GifFileType *gif;
7102 struct gcpro gcpro1;
7103 Lisp_Object image;
7104 int ino, image_height, image_width;
7105 gif_memory_source memsrc;
7106 unsigned char *raster;
7108 specified_file = image_spec_value (img->spec, QCfile, NULL);
7109 specified_data = image_spec_value (img->spec, QCdata, NULL);
7110 file = Qnil;
7111 GCPRO1 (file);
7113 if (NILP (specified_data))
7115 file = x_find_image_file (specified_file);
7116 if (!STRINGP (file))
7118 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7119 UNGCPRO;
7120 return 0;
7123 /* Open the GIF file. Casting return value avoids a GCC warning
7124 on W32. */
7125 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
7126 if (gif == NULL)
7128 image_error ("Cannot open `%s'", file, Qnil);
7129 UNGCPRO;
7130 return 0;
7133 else
7135 /* Read from memory! */
7136 current_gif_memory_src = &memsrc;
7137 memsrc.bytes = SDATA (specified_data);
7138 memsrc.len = SBYTES (specified_data);
7139 memsrc.index = 0;
7141 /* Casting return value avoids a GCC warning on W32. */
7142 gif = (GifFileType *) fn_DGifOpen (&memsrc, gif_read_from_memory);
7143 if (!gif)
7145 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7146 UNGCPRO;
7147 return 0;
7151 /* Before reading entire contents, check the declared image size. */
7152 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7154 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7155 fn_DGifCloseFile (gif);
7156 UNGCPRO;
7157 return 0;
7160 /* Read entire contents. */
7161 rc = fn_DGifSlurp (gif);
7162 if (rc == GIF_ERROR)
7164 image_error ("Error reading `%s'", img->spec, Qnil);
7165 fn_DGifCloseFile (gif);
7166 UNGCPRO;
7167 return 0;
7170 image = image_spec_value (img->spec, QCindex, NULL);
7171 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7172 if (ino >= gif->ImageCount)
7174 image_error ("Invalid image number `%s' in image `%s'",
7175 image, img->spec);
7176 fn_DGifCloseFile (gif);
7177 UNGCPRO;
7178 return 0;
7181 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
7182 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
7183 image_height = gif->SavedImages[ino].ImageDesc.Height;
7184 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
7185 image_width = gif->SavedImages[ino].ImageDesc.Width;
7186 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
7188 width = img->width = max (gif->SWidth,
7189 max (gif->Image.Left + gif->Image.Width,
7190 img->corners[RIGHT_CORNER]));
7191 height = img->height = max (gif->SHeight,
7192 max (gif->Image.Top + gif->Image.Height,
7193 img->corners[BOT_CORNER]));
7195 if (!check_image_size (f, width, height))
7197 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7198 fn_DGifCloseFile (gif);
7199 UNGCPRO;
7200 return 0;
7203 /* Create the X image and pixmap. */
7204 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7206 fn_DGifCloseFile (gif);
7207 UNGCPRO;
7208 return 0;
7211 /* Allocate colors. */
7212 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7213 if (!gif_color_map)
7214 gif_color_map = gif->SColorMap;
7215 init_color_table ();
7216 memset (pixel_colors, 0, sizeof pixel_colors);
7218 if (gif_color_map)
7219 for (i = 0; i < gif_color_map->ColorCount; ++i)
7221 int r = gif_color_map->Colors[i].Red << 8;
7222 int g = gif_color_map->Colors[i].Green << 8;
7223 int b = gif_color_map->Colors[i].Blue << 8;
7224 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7227 #ifdef COLOR_TABLE_SUPPORT
7228 img->colors = colors_in_color_table (&img->ncolors);
7229 free_color_table ();
7230 #endif /* COLOR_TABLE_SUPPORT */
7232 /* Clear the part of the screen image that are not covered by
7233 the image from the GIF file. Full animated GIF support
7234 requires more than can be done here (see the gif89 spec,
7235 disposal methods). Let's simply assume that the part
7236 not covered by a sub-image is in the frame's background color. */
7237 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7238 for (x = 0; x < width; ++x)
7239 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7241 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7242 for (x = 0; x < width; ++x)
7243 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7245 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7247 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7248 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7249 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7250 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7253 /* Read the GIF image into the X image. We use a local variable
7254 `raster' here because RasterBits below is a char *, and invites
7255 problems with bytes >= 0x80. */
7256 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7258 if (gif->SavedImages[ino].ImageDesc.Interlace)
7260 int pass;
7261 int row = interlace_start[0];
7263 pass = 0;
7265 for (y = 0; y < image_height; y++)
7267 if (row >= image_height)
7269 row = interlace_start[++pass];
7270 while (row >= image_height)
7271 row = interlace_start[++pass];
7274 for (x = 0; x < image_width; x++)
7276 int i = raster[(y * image_width) + x];
7277 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7278 row + img->corners[TOP_CORNER], pixel_colors[i]);
7281 row += interlace_increment[pass];
7284 else
7286 for (y = 0; y < image_height; ++y)
7287 for (x = 0; x < image_width; ++x)
7289 int i = raster[y * image_width + x];
7290 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7291 y + img->corners[TOP_CORNER], pixel_colors[i]);
7295 /* Save GIF image extension data for `image-metadata'.
7296 Format is (count IMAGES extension-data (FUNCTION "BYTES" ...)). */
7297 img->data.lisp_val = Qnil;
7298 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
7300 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
7301 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
7302 /* Append (... FUNCTION "BYTES") */
7303 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7304 Fcons (make_number (ext->Function),
7305 img->data.lisp_val));
7306 img->data.lisp_val = Fcons (Qextension_data,
7307 Fcons (Fnreverse (img->data.lisp_val),
7308 Qnil));
7310 if (gif->ImageCount > 1)
7311 img->data.lisp_val = Fcons (Qcount,
7312 Fcons (make_number (gif->ImageCount),
7313 img->data.lisp_val));
7315 fn_DGifCloseFile (gif);
7317 /* Maybe fill in the background field while we have ximg handy. */
7318 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7319 /* Casting avoids a GCC warning. */
7320 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7322 /* Put the image into the pixmap, then free the X image and its buffer. */
7323 x_put_x_image (f, ximg, img->pixmap, width, height);
7324 x_destroy_x_image (ximg);
7326 UNGCPRO;
7327 return 1;
7330 #else /* !HAVE_GIF */
7332 #ifdef HAVE_NS
7333 static int
7334 gif_load (struct frame *f, struct image *img)
7336 return ns_load_image (f, img,
7337 image_spec_value (img->spec, QCfile, NULL),
7338 image_spec_value (img->spec, QCdata, NULL));
7340 #endif /* HAVE_NS */
7342 #endif /* HAVE_GIF */
7346 /***********************************************************************
7348 ***********************************************************************/
7350 #if defined (HAVE_RSVG)
7352 /* Function prototypes. */
7354 static int svg_image_p (Lisp_Object object);
7355 static int svg_load (struct frame *f, struct image *img);
7357 static int svg_load_image (struct frame *, struct image *,
7358 unsigned char *, unsigned int);
7360 /* The symbol `svg' identifying images of this type. */
7362 Lisp_Object Qsvg;
7364 /* Indices of image specification fields in svg_format, below. */
7366 enum svg_keyword_index
7368 SVG_TYPE,
7369 SVG_DATA,
7370 SVG_FILE,
7371 SVG_ASCENT,
7372 SVG_MARGIN,
7373 SVG_RELIEF,
7374 SVG_ALGORITHM,
7375 SVG_HEURISTIC_MASK,
7376 SVG_MASK,
7377 SVG_BACKGROUND,
7378 SVG_LAST
7381 /* Vector of image_keyword structures describing the format
7382 of valid user-defined image specifications. */
7384 static const struct image_keyword svg_format[SVG_LAST] =
7386 {":type", IMAGE_SYMBOL_VALUE, 1},
7387 {":data", IMAGE_STRING_VALUE, 0},
7388 {":file", IMAGE_STRING_VALUE, 0},
7389 {":ascent", IMAGE_ASCENT_VALUE, 0},
7390 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7391 {":relief", IMAGE_INTEGER_VALUE, 0},
7392 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7393 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7394 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7395 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7398 /* Structure describing the image type `svg'. Its the same type of
7399 structure defined for all image formats, handled by emacs image
7400 functions. See struct image_type in dispextern.h. */
7402 static struct image_type svg_type =
7404 /* An identifier showing that this is an image structure for the SVG format. */
7405 &Qsvg,
7406 /* Handle to a function that can be used to identify a SVG file. */
7407 svg_image_p,
7408 /* Handle to function used to load a SVG file. */
7409 svg_load,
7410 /* Handle to function to free sresources for SVG. */
7411 x_clear_image,
7412 /* An internal field to link to the next image type in a list of
7413 image types, will be filled in when registering the format. */
7414 NULL
7418 /* Return non-zero if OBJECT is a valid SVG image specification. Do
7419 this by calling parse_image_spec and supplying the keywords that
7420 identify the SVG format. */
7422 static int
7423 svg_image_p (Lisp_Object object)
7425 struct image_keyword fmt[SVG_LAST];
7426 memcpy (fmt, svg_format, sizeof fmt);
7428 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
7429 return 0;
7431 /* Must specify either the :data or :file keyword. */
7432 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
7435 #include <librsvg/rsvg.h>
7437 #ifdef HAVE_NTGUI
7439 /* SVG library functions. */
7440 DEF_IMGLIB_FN (rsvg_handle_new);
7441 DEF_IMGLIB_FN (rsvg_handle_get_dimensions);
7442 DEF_IMGLIB_FN (rsvg_handle_write);
7443 DEF_IMGLIB_FN (rsvg_handle_close);
7444 DEF_IMGLIB_FN (rsvg_handle_get_pixbuf);
7445 DEF_IMGLIB_FN (rsvg_handle_free);
7447 DEF_IMGLIB_FN (gdk_pixbuf_get_width);
7448 DEF_IMGLIB_FN (gdk_pixbuf_get_height);
7449 DEF_IMGLIB_FN (gdk_pixbuf_get_pixels);
7450 DEF_IMGLIB_FN (gdk_pixbuf_get_rowstride);
7451 DEF_IMGLIB_FN (gdk_pixbuf_get_colorspace);
7452 DEF_IMGLIB_FN (gdk_pixbuf_get_n_channels);
7453 DEF_IMGLIB_FN (gdk_pixbuf_get_has_alpha);
7454 DEF_IMGLIB_FN (gdk_pixbuf_get_bits_per_sample);
7456 DEF_IMGLIB_FN (g_type_init);
7457 DEF_IMGLIB_FN (g_object_unref);
7458 DEF_IMGLIB_FN (g_error_free);
7460 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
7462 static int
7463 init_svg_functions (Lisp_Object libraries)
7465 HMODULE library, gdklib, glib, gobject;
7467 if (!(glib = w32_delayed_load (libraries, Qglib))
7468 || !(gobject = w32_delayed_load (libraries, Qgobject))
7469 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
7470 || !(library = w32_delayed_load (libraries, Qsvg)))
7471 return 0;
7473 LOAD_IMGLIB_FN (library, rsvg_handle_new);
7474 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
7475 LOAD_IMGLIB_FN (library, rsvg_handle_write);
7476 LOAD_IMGLIB_FN (library, rsvg_handle_close);
7477 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
7478 LOAD_IMGLIB_FN (library, rsvg_handle_free);
7480 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
7481 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
7482 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
7483 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
7484 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
7485 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
7486 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
7487 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
7489 LOAD_IMGLIB_FN (gobject, g_type_init);
7490 LOAD_IMGLIB_FN (gobject, g_object_unref);
7491 LOAD_IMGLIB_FN (glib, g_error_free);
7493 return 1;
7496 #else
7497 /* The following aliases for library functions allow dynamic loading
7498 to be used on some platforms. */
7499 #define fn_rsvg_handle_new rsvg_handle_new
7500 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
7501 #define fn_rsvg_handle_write rsvg_handle_write
7502 #define fn_rsvg_handle_close rsvg_handle_close
7503 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
7504 #define fn_rsvg_handle_free rsvg_handle_free
7506 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
7507 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
7508 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
7509 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
7510 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
7511 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
7512 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
7513 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
7515 #define fn_g_type_init g_type_init
7516 #define fn_g_object_unref g_object_unref
7517 #define fn_g_error_free g_error_free
7518 #endif /* !HAVE_NTGUI */
7520 /* Load SVG image IMG for use on frame F. Value is non-zero if
7521 successful. this function will go into the svg_type structure, and
7522 the prototype thus needs to be compatible with that structure. */
7524 static int
7525 svg_load (struct frame *f, struct image *img)
7527 int success_p = 0;
7528 Lisp_Object file_name;
7530 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7531 file_name = image_spec_value (img->spec, QCfile, NULL);
7532 if (STRINGP (file_name))
7534 Lisp_Object file;
7535 unsigned char *contents;
7536 int size;
7537 struct gcpro gcpro1;
7539 file = x_find_image_file (file_name);
7540 GCPRO1 (file);
7541 if (!STRINGP (file))
7543 image_error ("Cannot find image file `%s'", file_name, Qnil);
7544 UNGCPRO;
7545 return 0;
7548 /* Read the entire file into memory. */
7549 contents = slurp_file (SDATA (file), &size);
7550 if (contents == NULL)
7552 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
7553 UNGCPRO;
7554 return 0;
7556 /* If the file was slurped into memory properly, parse it. */
7557 success_p = svg_load_image (f, img, contents, size);
7558 xfree (contents);
7559 UNGCPRO;
7561 /* Else its not a file, its a lisp object. Load the image from a
7562 lisp object rather than a file. */
7563 else
7565 Lisp_Object data;
7567 data = image_spec_value (img->spec, QCdata, NULL);
7568 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
7571 return success_p;
7574 /* svg_load_image is a helper function for svg_load, which does the
7575 actual loading given contents and size, apart from frame and image
7576 structures, passed from svg_load.
7578 Uses librsvg to do most of the image processing.
7580 Returns non-zero when successful. */
7581 static int
7582 svg_load_image (struct frame *f, /* Pointer to emacs frame structure. */
7583 struct image *img, /* Pointer to emacs image structure. */
7584 unsigned char *contents, /* String containing the SVG XML data to be parsed. */
7585 unsigned int size) /* Size of data in bytes. */
7587 RsvgHandle *rsvg_handle;
7588 RsvgDimensionData dimension_data;
7589 GError *error = NULL;
7590 GdkPixbuf *pixbuf;
7591 int width;
7592 int height;
7593 const guint8 *pixels;
7594 int rowstride;
7595 XImagePtr ximg;
7596 Lisp_Object specified_bg;
7597 XColor background;
7598 int x;
7599 int y;
7601 /* g_type_init is a glib function that must be called prior to using
7602 gnome type library functions. */
7603 fn_g_type_init ();
7604 /* Make a handle to a new rsvg object. */
7605 rsvg_handle = (RsvgHandle *) fn_rsvg_handle_new ();
7607 /* Parse the contents argument and fill in the rsvg_handle. */
7608 fn_rsvg_handle_write (rsvg_handle, contents, size, &error);
7609 if (error) goto rsvg_error;
7611 /* The parsing is complete, rsvg_handle is ready to used, close it
7612 for further writes. */
7613 fn_rsvg_handle_close (rsvg_handle, &error);
7614 if (error) goto rsvg_error;
7616 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
7617 if (! check_image_size (f, dimension_data.width, dimension_data.height))
7619 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7620 goto rsvg_error;
7623 /* We can now get a valid pixel buffer from the svg file, if all
7624 went ok. */
7625 pixbuf = (GdkPixbuf *) fn_rsvg_handle_get_pixbuf (rsvg_handle);
7626 if (!pixbuf) goto rsvg_error;
7627 fn_g_object_unref (rsvg_handle);
7629 /* Extract some meta data from the svg handle. */
7630 width = fn_gdk_pixbuf_get_width (pixbuf);
7631 height = fn_gdk_pixbuf_get_height (pixbuf);
7632 pixels = (const guint8 *) fn_gdk_pixbuf_get_pixels (pixbuf);
7633 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
7635 /* Validate the svg meta data. */
7636 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
7637 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
7638 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
7639 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
7641 /* Try to create a x pixmap to hold the svg pixmap. */
7642 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7644 fn_g_object_unref (pixbuf);
7645 return 0;
7648 init_color_table ();
7650 /* Handle alpha channel by combining the image with a background
7651 color. */
7652 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7653 if (!STRINGP (specified_bg)
7654 || !x_defined_color (f, SDATA (specified_bg), &background, 0))
7656 #ifndef HAVE_NS
7657 background.pixel = FRAME_BACKGROUND_PIXEL (f);
7658 x_query_color (f, &background);
7659 #else
7660 ns_query_color (FRAME_BACKGROUND_COLOR (f), &background, 1);
7661 #endif
7664 /* SVG pixmaps specify transparency in the last byte, so right
7665 shift 8 bits to get rid of it, since emacs doesn't support
7666 transparency. */
7667 background.red >>= 8;
7668 background.green >>= 8;
7669 background.blue >>= 8;
7671 /* This loop handles opacity values, since Emacs assumes
7672 non-transparent images. Each pixel must be "flattened" by
7673 calculating the resulting color, given the transparency of the
7674 pixel, and the image background color. */
7675 for (y = 0; y < height; ++y)
7677 for (x = 0; x < width; ++x)
7679 unsigned red;
7680 unsigned green;
7681 unsigned blue;
7682 unsigned opacity;
7684 red = *pixels++;
7685 green = *pixels++;
7686 blue = *pixels++;
7687 opacity = *pixels++;
7689 red = ((red * opacity)
7690 + (background.red * ((1 << 8) - opacity)));
7691 green = ((green * opacity)
7692 + (background.green * ((1 << 8) - opacity)));
7693 blue = ((blue * opacity)
7694 + (background.blue * ((1 << 8) - opacity)));
7696 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
7699 pixels += rowstride - 4 * width;
7702 #ifdef COLOR_TABLE_SUPPORT
7703 /* Remember colors allocated for this image. */
7704 img->colors = colors_in_color_table (&img->ncolors);
7705 free_color_table ();
7706 #endif /* COLOR_TABLE_SUPPORT */
7708 fn_g_object_unref (pixbuf);
7710 img->width = width;
7711 img->height = height;
7713 /* Maybe fill in the background field while we have ximg handy.
7714 Casting avoids a GCC warning. */
7715 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7717 /* Put the image into the pixmap, then free the X image and its
7718 buffer. */
7719 x_put_x_image (f, ximg, img->pixmap, width, height);
7720 x_destroy_x_image (ximg);
7722 return 1;
7724 rsvg_error:
7725 fn_g_object_unref (rsvg_handle);
7726 /* FIXME: Use error->message so the user knows what is the actual
7727 problem with the image. */
7728 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
7729 fn_g_error_free (error);
7730 return 0;
7733 #endif /* defined (HAVE_RSVG) */
7738 /***********************************************************************
7739 Ghostscript
7740 ***********************************************************************/
7742 #ifdef HAVE_X_WINDOWS
7743 #define HAVE_GHOSTSCRIPT 1
7744 #endif /* HAVE_X_WINDOWS */
7746 #ifdef HAVE_GHOSTSCRIPT
7748 static int gs_image_p (Lisp_Object object);
7749 static int gs_load (struct frame *f, struct image *img);
7750 static void gs_clear_image (struct frame *f, struct image *img);
7752 /* Keyword symbols. */
7754 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
7756 /* Indices of image specification fields in gs_format, below. */
7758 enum gs_keyword_index
7760 GS_TYPE,
7761 GS_PT_WIDTH,
7762 GS_PT_HEIGHT,
7763 GS_FILE,
7764 GS_LOADER,
7765 GS_BOUNDING_BOX,
7766 GS_ASCENT,
7767 GS_MARGIN,
7768 GS_RELIEF,
7769 GS_ALGORITHM,
7770 GS_HEURISTIC_MASK,
7771 GS_MASK,
7772 GS_BACKGROUND,
7773 GS_LAST
7776 /* Vector of image_keyword structures describing the format
7777 of valid user-defined image specifications. */
7779 static const struct image_keyword gs_format[GS_LAST] =
7781 {":type", IMAGE_SYMBOL_VALUE, 1},
7782 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7783 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7784 {":file", IMAGE_STRING_VALUE, 1},
7785 {":loader", IMAGE_FUNCTION_VALUE, 0},
7786 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
7787 {":ascent", IMAGE_ASCENT_VALUE, 0},
7788 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7789 {":relief", IMAGE_INTEGER_VALUE, 0},
7790 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7791 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7792 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7793 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7796 /* Structure describing the image type `ghostscript'. */
7798 static struct image_type gs_type =
7800 &Qpostscript,
7801 gs_image_p,
7802 gs_load,
7803 gs_clear_image,
7804 NULL
7808 /* Free X resources of Ghostscript image IMG which is used on frame F. */
7810 static void
7811 gs_clear_image (struct frame *f, struct image *img)
7813 /* IMG->data.ptr_val may contain a recorded colormap. */
7814 xfree (img->data.ptr_val);
7815 x_clear_image (f, img);
7819 /* Return non-zero if OBJECT is a valid Ghostscript image
7820 specification. */
7822 static int
7823 gs_image_p (Lisp_Object object)
7825 struct image_keyword fmt[GS_LAST];
7826 Lisp_Object tem;
7827 int i;
7829 memcpy (fmt, gs_format, sizeof fmt);
7831 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
7832 return 0;
7834 /* Bounding box must be a list or vector containing 4 integers. */
7835 tem = fmt[GS_BOUNDING_BOX].value;
7836 if (CONSP (tem))
7838 for (i = 0; i < 4; ++i, tem = XCDR (tem))
7839 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
7840 return 0;
7841 if (!NILP (tem))
7842 return 0;
7844 else if (VECTORP (tem))
7846 if (XVECTOR (tem)->size != 4)
7847 return 0;
7848 for (i = 0; i < 4; ++i)
7849 if (!INTEGERP (XVECTOR (tem)->contents[i]))
7850 return 0;
7852 else
7853 return 0;
7855 return 1;
7859 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
7860 if successful. */
7862 static int
7863 gs_load (struct frame *f, struct image *img)
7865 char buffer[100];
7866 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
7867 struct gcpro gcpro1, gcpro2;
7868 Lisp_Object frame;
7869 double in_width, in_height;
7870 Lisp_Object pixel_colors = Qnil;
7872 /* Compute pixel size of pixmap needed from the given size in the
7873 image specification. Sizes in the specification are in pt. 1 pt
7874 = 1/72 in, xdpi and ydpi are stored in the frame's X display
7875 info. */
7876 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
7877 in_width = XFASTINT (pt_width) / 72.0;
7878 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
7879 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
7880 in_height = XFASTINT (pt_height) / 72.0;
7881 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
7883 if (!check_image_size (f, img->width, img->height))
7885 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7886 return 0;
7889 /* Create the pixmap. */
7890 xassert (img->pixmap == NO_PIXMAP);
7892 /* Only W32 version did BLOCK_INPUT here. ++kfs */
7893 BLOCK_INPUT;
7894 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7895 img->width, img->height,
7896 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
7897 UNBLOCK_INPUT;
7899 if (!img->pixmap)
7901 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
7902 return 0;
7905 /* Call the loader to fill the pixmap. It returns a process object
7906 if successful. We do not record_unwind_protect here because
7907 other places in redisplay like calling window scroll functions
7908 don't either. Let the Lisp loader use `unwind-protect' instead. */
7909 GCPRO2 (window_and_pixmap_id, pixel_colors);
7911 sprintf (buffer, "%lu %lu",
7912 (unsigned long) FRAME_X_WINDOW (f),
7913 (unsigned long) img->pixmap);
7914 window_and_pixmap_id = build_string (buffer);
7916 sprintf (buffer, "%lu %lu",
7917 FRAME_FOREGROUND_PIXEL (f),
7918 FRAME_BACKGROUND_PIXEL (f));
7919 pixel_colors = build_string (buffer);
7921 XSETFRAME (frame, f);
7922 loader = image_spec_value (img->spec, QCloader, NULL);
7923 if (NILP (loader))
7924 loader = intern ("gs-load-image");
7926 img->data.lisp_val = call6 (loader, frame, img->spec,
7927 make_number (img->width),
7928 make_number (img->height),
7929 window_and_pixmap_id,
7930 pixel_colors);
7931 UNGCPRO;
7932 return PROCESSP (img->data.lisp_val);
7936 /* Kill the Ghostscript process that was started to fill PIXMAP on
7937 frame F. Called from XTread_socket when receiving an event
7938 telling Emacs that Ghostscript has finished drawing. */
7940 void
7941 x_kill_gs_process (Pixmap pixmap, struct frame *f)
7943 struct image_cache *c = FRAME_IMAGE_CACHE (f);
7944 int class, i;
7945 struct image *img;
7947 /* Find the image containing PIXMAP. */
7948 for (i = 0; i < c->used; ++i)
7949 if (c->images[i]->pixmap == pixmap)
7950 break;
7952 /* Should someone in between have cleared the image cache, for
7953 instance, give up. */
7954 if (i == c->used)
7955 return;
7957 /* Kill the GS process. We should have found PIXMAP in the image
7958 cache and its image should contain a process object. */
7959 img = c->images[i];
7960 xassert (PROCESSP (img->data.lisp_val));
7961 Fkill_process (img->data.lisp_val, Qnil);
7962 img->data.lisp_val = Qnil;
7964 #if defined (HAVE_X_WINDOWS)
7966 /* On displays with a mutable colormap, figure out the colors
7967 allocated for the image by looking at the pixels of an XImage for
7968 img->pixmap. */
7969 class = FRAME_X_VISUAL (f)->class;
7970 if (class != StaticColor && class != StaticGray && class != TrueColor)
7972 XImagePtr ximg;
7974 BLOCK_INPUT;
7976 /* Try to get an XImage for img->pixmep. */
7977 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
7978 0, 0, img->width, img->height, ~0, ZPixmap);
7979 if (ximg)
7981 int x, y;
7983 /* Initialize the color table. */
7984 init_color_table ();
7986 /* For each pixel of the image, look its color up in the
7987 color table. After having done so, the color table will
7988 contain an entry for each color used by the image. */
7989 for (y = 0; y < img->height; ++y)
7990 for (x = 0; x < img->width; ++x)
7992 unsigned long pixel = XGetPixel (ximg, x, y);
7993 lookup_pixel_color (f, pixel);
7996 /* Record colors in the image. Free color table and XImage. */
7997 #ifdef COLOR_TABLE_SUPPORT
7998 img->colors = colors_in_color_table (&img->ncolors);
7999 free_color_table ();
8000 #endif
8001 XDestroyImage (ximg);
8003 #if 0 /* This doesn't seem to be the case. If we free the colors
8004 here, we get a BadAccess later in x_clear_image when
8005 freeing the colors. */
8006 /* We have allocated colors once, but Ghostscript has also
8007 allocated colors on behalf of us. So, to get the
8008 reference counts right, free them once. */
8009 if (img->ncolors)
8010 x_free_colors (f, img->colors, img->ncolors);
8011 #endif
8013 else
8014 image_error ("Cannot get X image of `%s'; colors will not be freed",
8015 img->spec, Qnil);
8017 UNBLOCK_INPUT;
8019 #endif /* HAVE_X_WINDOWS */
8021 /* Now that we have the pixmap, compute mask and transform the
8022 image if requested. */
8023 BLOCK_INPUT;
8024 postprocess_image (f, img);
8025 UNBLOCK_INPUT;
8028 #endif /* HAVE_GHOSTSCRIPT */
8031 /***********************************************************************
8032 Tests
8033 ***********************************************************************/
8035 #if GLYPH_DEBUG
8037 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8038 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8039 (Lisp_Object spec)
8041 return valid_image_p (spec) ? Qt : Qnil;
8045 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8046 (Lisp_Object spec)
8048 int id = -1;
8050 if (valid_image_p (spec))
8051 id = lookup_image (SELECTED_FRAME (), spec);
8053 debug_print (spec);
8054 return make_number (id);
8057 #endif /* GLYPH_DEBUG != 0 */
8060 /***********************************************************************
8061 Initialization
8062 ***********************************************************************/
8064 #ifdef HAVE_NTGUI
8065 /* Image types that rely on external libraries are loaded dynamically
8066 if the library is available. */
8067 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8068 define_image_type (image_type, init_lib_fn (libraries))
8069 #else
8070 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8071 define_image_type (image_type, 1)
8072 #endif /* HAVE_NTGUI */
8074 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8075 doc: /* Initialize image library implementing image type TYPE.
8076 Return non-nil if TYPE is a supported image type.
8078 Image types pbm and xbm are prebuilt; other types are loaded here.
8079 Libraries to load are specified in alist LIBRARIES (usually, the value
8080 of `image-library-alist', which see). */)
8081 (Lisp_Object type, Lisp_Object libraries)
8083 Lisp_Object tested;
8085 /* Don't try to reload the library. */
8086 tested = Fassq (type, Vimage_type_cache);
8087 if (CONSP (tested))
8088 return XCDR (tested);
8090 #if defined (HAVE_XPM) || defined (HAVE_NS)
8091 if (EQ (type, Qxpm))
8092 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8093 #endif
8095 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8096 if (EQ (type, Qjpeg))
8097 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8098 #endif
8100 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8101 if (EQ (type, Qtiff))
8102 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8103 #endif
8105 #if defined (HAVE_GIF) || defined (HAVE_NS)
8106 if (EQ (type, Qgif))
8107 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8108 #endif
8110 #if defined (HAVE_PNG) || defined (HAVE_NS)
8111 if (EQ (type, Qpng))
8112 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8113 #endif
8115 #if defined (HAVE_RSVG)
8116 if (EQ (type, Qsvg))
8117 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
8118 #endif
8120 #ifdef HAVE_GHOSTSCRIPT
8121 if (EQ (type, Qpostscript))
8122 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8123 #endif
8125 /* If the type is not recognized, avoid testing it ever again. */
8126 CACHE_IMAGE_TYPE (type, Qnil);
8127 return Qnil;
8130 void
8131 syms_of_image (void)
8133 /* Initialize this only once, since that's what we do with Vimage_types
8134 and they are supposed to be in sync. Initializing here gives correct
8135 operation on GNU/Linux of calling dump-emacs after loading some images. */
8136 image_types = NULL;
8138 /* Must be defined now becase we're going to update it below, while
8139 defining the supported image types. */
8140 DEFVAR_LISP ("image-types", &Vimage_types,
8141 doc: /* List of potentially supported image types.
8142 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8143 To check whether it is really supported, use `image-type-available-p'. */);
8144 Vimage_types = Qnil;
8146 DEFVAR_LISP ("image-library-alist", &Vimage_library_alist,
8147 doc: /* Alist of image types vs external libraries needed to display them.
8149 Each element is a list (IMAGE-TYPE LIBRARY...), where the car is a symbol
8150 representing a supported image type, and the rest are strings giving
8151 alternate filenames for the corresponding external libraries.
8153 Emacs tries to load the libraries in the order they appear on the
8154 list; if none is loaded, the running session of Emacs won't
8155 support the image type. Types 'pbm and 'xbm don't need to be
8156 listed; they are always supported. */);
8157 Vimage_library_alist = Qnil;
8158 Fput (intern_c_string ("image-library-alist"), Qrisky_local_variable, Qt);
8160 DEFVAR_LISP ("max-image-size", &Vmax_image_size,
8161 doc: /* Maximum size of images.
8162 Emacs will not load an image into memory if its pixel width or
8163 pixel height exceeds this limit.
8165 If the value is an integer, it directly specifies the maximum
8166 image height and width, measured in pixels. If it is a floating
8167 point number, it specifies the maximum image height and width
8168 as a ratio to the frame height and width. If the value is
8169 non-numeric, there is no explicit limit on the size of images. */);
8170 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8172 Vimage_type_cache = Qnil;
8173 staticpro (&Vimage_type_cache);
8175 Qpbm = intern_c_string ("pbm");
8176 staticpro (&Qpbm);
8177 ADD_IMAGE_TYPE (Qpbm);
8179 Qxbm = intern_c_string ("xbm");
8180 staticpro (&Qxbm);
8181 ADD_IMAGE_TYPE (Qxbm);
8183 define_image_type (&xbm_type, 1);
8184 define_image_type (&pbm_type, 1);
8186 Qcount = intern_c_string ("count");
8187 staticpro (&Qcount);
8188 Qextension_data = intern_c_string ("extension-data");
8189 staticpro (&Qextension_data);
8191 QCascent = intern_c_string (":ascent");
8192 staticpro (&QCascent);
8193 QCmargin = intern_c_string (":margin");
8194 staticpro (&QCmargin);
8195 QCrelief = intern_c_string (":relief");
8196 staticpro (&QCrelief);
8197 QCconversion = intern_c_string (":conversion");
8198 staticpro (&QCconversion);
8199 QCcolor_symbols = intern_c_string (":color-symbols");
8200 staticpro (&QCcolor_symbols);
8201 QCheuristic_mask = intern_c_string (":heuristic-mask");
8202 staticpro (&QCheuristic_mask);
8203 QCindex = intern_c_string (":index");
8204 staticpro (&QCindex);
8205 QCmatrix = intern_c_string (":matrix");
8206 staticpro (&QCmatrix);
8207 QCcolor_adjustment = intern_c_string (":color-adjustment");
8208 staticpro (&QCcolor_adjustment);
8209 QCmask = intern_c_string (":mask");
8210 staticpro (&QCmask);
8212 Qlaplace = intern_c_string ("laplace");
8213 staticpro (&Qlaplace);
8214 Qemboss = intern_c_string ("emboss");
8215 staticpro (&Qemboss);
8216 Qedge_detection = intern_c_string ("edge-detection");
8217 staticpro (&Qedge_detection);
8218 Qheuristic = intern_c_string ("heuristic");
8219 staticpro (&Qheuristic);
8221 Qpostscript = intern_c_string ("postscript");
8222 staticpro (&Qpostscript);
8223 #ifdef HAVE_GHOSTSCRIPT
8224 ADD_IMAGE_TYPE (Qpostscript);
8225 QCloader = intern_c_string (":loader");
8226 staticpro (&QCloader);
8227 QCbounding_box = intern_c_string (":bounding-box");
8228 staticpro (&QCbounding_box);
8229 QCpt_width = intern_c_string (":pt-width");
8230 staticpro (&QCpt_width);
8231 QCpt_height = intern_c_string (":pt-height");
8232 staticpro (&QCpt_height);
8233 #endif /* HAVE_GHOSTSCRIPT */
8235 #if defined (HAVE_XPM) || defined (HAVE_NS)
8236 Qxpm = intern_c_string ("xpm");
8237 staticpro (&Qxpm);
8238 ADD_IMAGE_TYPE (Qxpm);
8239 #endif
8241 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8242 Qjpeg = intern_c_string ("jpeg");
8243 staticpro (&Qjpeg);
8244 ADD_IMAGE_TYPE (Qjpeg);
8245 #endif
8247 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8248 Qtiff = intern_c_string ("tiff");
8249 staticpro (&Qtiff);
8250 ADD_IMAGE_TYPE (Qtiff);
8251 #endif
8253 #if defined (HAVE_GIF) || defined (HAVE_NS)
8254 Qgif = intern_c_string ("gif");
8255 staticpro (&Qgif);
8256 ADD_IMAGE_TYPE (Qgif);
8257 #endif
8259 #if defined (HAVE_PNG) || defined (HAVE_NS)
8260 Qpng = intern_c_string ("png");
8261 staticpro (&Qpng);
8262 ADD_IMAGE_TYPE (Qpng);
8263 #endif
8265 #if defined (HAVE_RSVG)
8266 Qsvg = intern_c_string ("svg");
8267 staticpro (&Qsvg);
8268 ADD_IMAGE_TYPE (Qsvg);
8269 #ifdef HAVE_NTGUI
8270 /* Other libraries used directly by svg code. */
8271 Qgdk_pixbuf = intern_c_string ("gdk-pixbuf");
8272 staticpro (&Qgdk_pixbuf);
8273 Qglib = intern_c_string ("glib");
8274 staticpro (&Qglib);
8275 Qgobject = intern_c_string ("gobject");
8276 staticpro (&Qgobject);
8277 #endif /* HAVE_NTGUI */
8278 #endif /* HAVE_RSVG */
8280 defsubr (&Sinit_image_library);
8281 defsubr (&Sclear_image_cache);
8282 defsubr (&Simage_flush);
8283 defsubr (&Simage_size);
8284 defsubr (&Simage_mask_p);
8285 defsubr (&Simage_metadata);
8287 #if GLYPH_DEBUG
8288 defsubr (&Simagep);
8289 defsubr (&Slookup_image);
8290 #endif
8292 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
8293 doc: /* Non-nil means always draw a cross over disabled images.
8294 Disabled images are those having a `:conversion disabled' property.
8295 A cross is always drawn on black & white displays. */);
8296 cross_disabled_images = 0;
8298 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
8299 doc: /* List of directories to search for window system bitmap files. */);
8300 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8302 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
8303 doc: /* Maximum time after which images are removed from the cache.
8304 When an image has not been displayed this many seconds, Emacs
8305 automatically removes it from the image cache. If the cache contains
8306 a large number of images, the actual eviction time may be shorter.
8307 The value can also be nil, meaning the cache is never cleared.
8309 The function `clear-image-cache' disregards this variable. */);
8310 Vimage_cache_eviction_delay = make_number (300);
8313 void
8314 init_image (void)
8318 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
8319 (do not change this comment) */