* lisp/help-fns.el (describe-variable): Don't emit trailing whitespace (Bug#7511).
[emacs.git] / src / image.c
blob0fa0a0cd064b6277014cb7b1be7ae1b037ac4b2f
1 /* Functions for image support on window system.
2 Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <stdio.h>
23 #include <math.h>
24 #include <ctype.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
30 #ifdef HAVE_PNG
31 #if defined HAVE_LIBPNG_PNG_H
32 # include <libpng/png.h>
33 #else
34 # include <png.h>
35 #endif
36 #endif
38 #include <setjmp.h>
40 /* This makes the fields of a Display accessible, in Xlib header files. */
42 #define XLIB_ILLEGAL_ACCESS
44 #include "lisp.h"
45 #include "frame.h"
46 #include "window.h"
47 #include "dispextern.h"
48 #include "blockinput.h"
49 #include "systime.h"
50 #include <epaths.h>
51 #include "character.h"
52 #include "coding.h"
53 #include "termhooks.h"
54 #include "font.h"
56 #ifdef HAVE_X_WINDOWS
57 #include "xterm.h"
58 #include <sys/types.h>
59 #include <sys/stat.h>
61 #define COLOR_TABLE_SUPPORT 1
63 typedef struct x_bitmap_record Bitmap_Record;
64 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
65 #define NO_PIXMAP None
67 #define RGB_PIXEL_COLOR unsigned long
69 #define PIX_MASK_RETAIN 0
70 #define PIX_MASK_DRAW 1
71 #endif /* HAVE_X_WINDOWS */
74 #ifdef HAVE_NTGUI
75 #include "w32term.h"
77 /* W32_TODO : Color tables on W32. */
78 #undef COLOR_TABLE_SUPPORT
80 typedef struct w32_bitmap_record Bitmap_Record;
81 #define GET_PIXEL(ximg, x, y) GetPixel(ximg, x, y)
82 #define NO_PIXMAP 0
84 #define RGB_PIXEL_COLOR COLORREF
86 #define PIX_MASK_RETAIN 0
87 #define PIX_MASK_DRAW 1
89 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
90 #define x_defined_color w32_defined_color
91 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
93 /* Functions from w32term.c that depend on XColor (so can't go in w32term.h
94 without modifying lots of files). */
95 extern void x_query_colors (struct frame *f, XColor *colors, int ncolors);
96 extern void x_query_color (struct frame *f, XColor *color);
97 #endif /* HAVE_NTGUI */
99 #ifdef HAVE_NS
100 #include "nsterm.h"
101 #include <sys/types.h>
102 #include <sys/stat.h>
104 #undef COLOR_TABLE_SUPPORT
106 typedef struct ns_bitmap_record Bitmap_Record;
108 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
109 #define NO_PIXMAP 0
111 #define RGB_PIXEL_COLOR unsigned long
112 #define ZPixmap 0
114 #define PIX_MASK_RETAIN 0
115 #define PIX_MASK_DRAW 1
117 #define FRAME_X_VISUAL FRAME_NS_DISPLAY_INFO(f)->visual
118 #define x_defined_color(f, name, color_def, alloc) \
119 ns_defined_color (f, name, color_def, alloc, 0)
120 #define FRAME_X_SCREEN(f) 0
121 #define DefaultDepthOfScreen(screen) x_display_list->n_planes
122 #endif /* HAVE_NS */
125 /* Search path for bitmap files. */
127 Lisp_Object Vx_bitmap_file_path;
130 static void x_disable_image P_ ((struct frame *, struct image *));
131 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
132 Lisp_Object));
134 static void init_color_table P_ ((void));
135 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
136 #ifdef COLOR_TABLE_SUPPORT
137 static void free_color_table P_ ((void));
138 static unsigned long *colors_in_color_table P_ ((int *n));
139 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
140 #endif
142 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
143 id, which is just an int that this section returns. Bitmaps are
144 reference counted so they can be shared among frames.
146 Bitmap indices are guaranteed to be > 0, so a negative number can
147 be used to indicate no bitmap.
149 If you use x_create_bitmap_from_data, then you must keep track of
150 the bitmaps yourself. That is, creating a bitmap from the same
151 data more than once will not be caught. */
153 #ifdef HAVE_NS
154 XImagePtr
155 XGetImage (Display *display, Pixmap pixmap, int x, int y,
156 unsigned int width, unsigned int height,
157 unsigned long plane_mask, int format)
159 /* TODO: not sure what this function is supposed to do.. */
160 ns_retain_object(pixmap);
161 return pixmap;
164 /* use with imgs created by ns_image_for_XPM */
165 unsigned long
166 XGetPixel (XImagePtr ximage, int x, int y)
168 return ns_get_pixel(ximage, x, y);
171 /* use with imgs created by ns_image_for_XPM; alpha set to 1;
172 pixel is assumed to be in form RGB */
173 void
174 XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
176 ns_put_pixel(ximage, x, y, pixel);
178 #endif /* HAVE_NS */
181 /* Functions to access the contents of a bitmap, given an id. */
184 x_bitmap_height (f, id)
185 FRAME_PTR f;
186 int id;
188 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
192 x_bitmap_width (f, id)
193 FRAME_PTR f;
194 int id;
196 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
199 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
201 x_bitmap_pixmap (f, id)
202 FRAME_PTR f;
203 int id;
205 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
207 #endif
209 #ifdef HAVE_X_WINDOWS
211 x_bitmap_mask (f, id)
212 FRAME_PTR f;
213 int id;
215 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
217 #endif
219 /* Allocate a new bitmap record. Returns index of new record. */
221 static int
222 x_allocate_bitmap_record (f)
223 FRAME_PTR f;
225 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
226 int i;
228 if (dpyinfo->bitmaps == NULL)
230 dpyinfo->bitmaps_size = 10;
231 dpyinfo->bitmaps
232 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
233 dpyinfo->bitmaps_last = 1;
234 return 1;
237 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
238 return ++dpyinfo->bitmaps_last;
240 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
241 if (dpyinfo->bitmaps[i].refcount == 0)
242 return i + 1;
244 dpyinfo->bitmaps_size *= 2;
245 dpyinfo->bitmaps
246 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
247 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
248 return ++dpyinfo->bitmaps_last;
251 /* Add one reference to the reference count of the bitmap with id ID. */
253 void
254 x_reference_bitmap (f, id)
255 FRAME_PTR f;
256 int id;
258 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
261 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
264 x_create_bitmap_from_data (f, bits, width, height)
265 struct frame *f;
266 char *bits;
267 unsigned int width, height;
269 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
270 int id;
272 #ifdef HAVE_X_WINDOWS
273 Pixmap bitmap;
274 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
275 bits, width, height);
276 if (! bitmap)
277 return -1;
278 #endif /* HAVE_X_WINDOWS */
280 #ifdef HAVE_NTGUI
281 Pixmap bitmap;
282 bitmap = CreateBitmap (width, height,
283 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
284 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
285 bits);
286 if (! bitmap)
287 return -1;
288 #endif /* HAVE_NTGUI */
290 #ifdef HAVE_NS
291 void *bitmap = ns_image_from_XBM(bits, width, height);
292 if (!bitmap)
293 return -1;
294 #endif
296 id = x_allocate_bitmap_record (f);
298 #ifdef HAVE_NS
299 dpyinfo->bitmaps[id - 1].img = bitmap;
300 dpyinfo->bitmaps[id - 1].depth = 1;
301 #endif
303 dpyinfo->bitmaps[id - 1].file = NULL;
304 dpyinfo->bitmaps[id - 1].height = height;
305 dpyinfo->bitmaps[id - 1].width = width;
306 dpyinfo->bitmaps[id - 1].refcount = 1;
308 #ifdef HAVE_X_WINDOWS
309 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
310 dpyinfo->bitmaps[id - 1].have_mask = 0;
311 dpyinfo->bitmaps[id - 1].depth = 1;
312 #endif /* HAVE_X_WINDOWS */
314 #ifdef HAVE_NTGUI
315 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
316 dpyinfo->bitmaps[id - 1].hinst = NULL;
317 dpyinfo->bitmaps[id - 1].depth = 1;
318 #endif /* HAVE_NTGUI */
320 return id;
323 /* Create bitmap from file FILE for frame F. */
326 x_create_bitmap_from_file (f, file)
327 struct frame *f;
328 Lisp_Object file;
330 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
332 #ifdef HAVE_NTGUI
333 return -1; /* W32_TODO : bitmap support */
334 #endif /* HAVE_NTGUI */
336 #ifdef HAVE_NS
337 int id;
338 void *bitmap = ns_image_from_file(file);
340 if (!bitmap)
341 return -1;
344 id = x_allocate_bitmap_record (f);
345 dpyinfo->bitmaps[id - 1].img = bitmap;
346 dpyinfo->bitmaps[id - 1].refcount = 1;
347 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
348 dpyinfo->bitmaps[id - 1].depth = 1;
349 dpyinfo->bitmaps[id - 1].height = ns_image_width(bitmap);
350 dpyinfo->bitmaps[id - 1].width = ns_image_height(bitmap);
351 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
352 return id;
353 #endif
355 #ifdef HAVE_X_WINDOWS
356 unsigned int width, height;
357 Pixmap bitmap;
358 int xhot, yhot, result, id;
359 Lisp_Object found;
360 int fd;
361 char *filename;
363 /* Look for an existing bitmap with the same name. */
364 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
366 if (dpyinfo->bitmaps[id].refcount
367 && dpyinfo->bitmaps[id].file
368 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
370 ++dpyinfo->bitmaps[id].refcount;
371 return id + 1;
375 /* Search bitmap-file-path for the file, if appropriate. */
376 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
377 if (fd < 0)
378 return -1;
379 emacs_close (fd);
381 filename = (char *) SDATA (found);
383 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
384 filename, &width, &height, &bitmap, &xhot, &yhot);
385 if (result != BitmapSuccess)
386 return -1;
388 id = x_allocate_bitmap_record (f);
389 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
390 dpyinfo->bitmaps[id - 1].have_mask = 0;
391 dpyinfo->bitmaps[id - 1].refcount = 1;
392 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
393 dpyinfo->bitmaps[id - 1].depth = 1;
394 dpyinfo->bitmaps[id - 1].height = height;
395 dpyinfo->bitmaps[id - 1].width = width;
396 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
398 return id;
399 #endif /* HAVE_X_WINDOWS */
402 /* Free bitmap B. */
404 static void
405 free_bitmap_record (dpyinfo, bm)
406 Display_Info *dpyinfo;
407 Bitmap_Record *bm;
409 #ifdef HAVE_X_WINDOWS
410 XFreePixmap (dpyinfo->display, bm->pixmap);
411 if (bm->have_mask)
412 XFreePixmap (dpyinfo->display, bm->mask);
413 #endif /* HAVE_X_WINDOWS */
415 #ifdef HAVE_NTGUI
416 DeleteObject (bm->pixmap);
417 #endif /* HAVE_NTGUI */
419 #ifdef HAVE_NS
420 ns_release_object(bm->img);
421 #endif
423 if (bm->file)
425 xfree (bm->file);
426 bm->file = NULL;
430 /* Remove reference to bitmap with id number ID. */
432 void
433 x_destroy_bitmap (f, id)
434 FRAME_PTR f;
435 int id;
437 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
439 if (id > 0)
441 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
443 if (--bm->refcount == 0)
445 BLOCK_INPUT;
446 free_bitmap_record (dpyinfo, bm);
447 UNBLOCK_INPUT;
452 /* Free all the bitmaps for the display specified by DPYINFO. */
454 void
455 x_destroy_all_bitmaps (dpyinfo)
456 Display_Info *dpyinfo;
458 int i;
459 Bitmap_Record *bm = dpyinfo->bitmaps;
461 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
462 if (bm->refcount > 0)
463 free_bitmap_record (dpyinfo, bm);
465 dpyinfo->bitmaps_last = 0;
469 #ifdef HAVE_X_WINDOWS
471 /* Useful functions defined in the section
472 `Image type independent image structures' below. */
474 static unsigned long four_corners_best P_ ((XImagePtr ximg,
475 int *corners,
476 unsigned long width,
477 unsigned long height));
479 static int x_create_x_image_and_pixmap P_ ((struct frame *f, int width, int height,
480 int depth, XImagePtr *ximg,
481 Pixmap *pixmap));
483 static void x_destroy_x_image P_ ((XImagePtr ximg));
486 /* Create a mask of a bitmap. Note is this not a perfect mask.
487 It's nicer with some borders in this context */
490 x_create_bitmap_mask (f, id)
491 struct frame *f;
492 int id;
494 Pixmap pixmap, mask;
495 XImagePtr ximg, mask_img;
496 unsigned long width, height;
497 int result;
498 unsigned long bg;
499 unsigned long x, y, xp, xm, yp, ym;
500 GC gc;
502 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
504 if (!(id > 0))
505 return -1;
507 pixmap = x_bitmap_pixmap (f, id);
508 width = x_bitmap_width (f, id);
509 height = x_bitmap_height (f, id);
511 BLOCK_INPUT;
512 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
513 ~0, ZPixmap);
515 if (!ximg)
517 UNBLOCK_INPUT;
518 return -1;
521 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
523 UNBLOCK_INPUT;
524 if (!result)
526 XDestroyImage (ximg);
527 return -1;
530 bg = four_corners_best (ximg, NULL, width, height);
532 for (y = 0; y < ximg->height; ++y)
534 for (x = 0; x < ximg->width; ++x)
536 xp = x != ximg->width - 1 ? x + 1 : 0;
537 xm = x != 0 ? x - 1 : ximg->width - 1;
538 yp = y != ximg->height - 1 ? y + 1 : 0;
539 ym = y != 0 ? y - 1 : ximg->height - 1;
540 if (XGetPixel (ximg, x, y) == bg
541 && XGetPixel (ximg, x, yp) == bg
542 && XGetPixel (ximg, x, ym) == bg
543 && XGetPixel (ximg, xp, y) == bg
544 && XGetPixel (ximg, xp, yp) == bg
545 && XGetPixel (ximg, xp, ym) == bg
546 && XGetPixel (ximg, xm, y) == bg
547 && XGetPixel (ximg, xm, yp) == bg
548 && XGetPixel (ximg, xm, ym) == bg)
549 XPutPixel (mask_img, x, y, 0);
550 else
551 XPutPixel (mask_img, x, y, 1);
555 xassert (interrupt_input_blocked);
556 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
557 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
558 width, height);
559 XFreeGC (FRAME_X_DISPLAY (f), gc);
561 dpyinfo->bitmaps[id - 1].have_mask = 1;
562 dpyinfo->bitmaps[id - 1].mask = mask;
564 XDestroyImage (ximg);
565 x_destroy_x_image (mask_img);
567 return 0;
570 #endif /* HAVE_X_WINDOWS */
573 /***********************************************************************
574 Image types
575 ***********************************************************************/
577 /* Value is the number of elements of vector VECTOR. */
579 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
581 /* List of supported image types. Use define_image_type to add new
582 types. Use lookup_image_type to find a type for a given symbol. */
584 static struct image_type *image_types;
586 /* A list of symbols, one for each supported image type. */
588 Lisp_Object Vimage_types;
590 /* An alist of image types and libraries that implement the type. */
592 Lisp_Object Vimage_library_alist;
594 /* Cache for delayed-loading image types. */
596 static Lisp_Object Vimage_type_cache;
598 /* The symbol `xbm' which is used as the type symbol for XBM images. */
600 Lisp_Object Qxbm;
602 /* Keywords. */
604 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
605 extern Lisp_Object QCdata, QCtype;
606 extern Lisp_Object Qcenter;
607 Lisp_Object QCascent, QCmargin, QCrelief, Qcount;
608 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
609 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
611 /* Other symbols. */
613 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
615 /* Time in seconds after which images should be removed from the cache
616 if not displayed. */
618 Lisp_Object Vimage_cache_eviction_delay;
620 /* Function prototypes. */
622 static Lisp_Object define_image_type P_ ((struct image_type *type, int loaded));
623 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
624 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
625 static void x_laplace P_ ((struct frame *, struct image *));
626 static void x_emboss P_ ((struct frame *, struct image *));
627 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
628 Lisp_Object));
630 #define CACHE_IMAGE_TYPE(type, status) \
631 do { Vimage_type_cache = Fcons (Fcons (type, status), Vimage_type_cache); } while (0)
633 #define ADD_IMAGE_TYPE(type) \
634 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
636 /* Define a new image type from TYPE. This adds a copy of TYPE to
637 image_types and caches the loading status of TYPE. */
639 static Lisp_Object
640 define_image_type (type, loaded)
641 struct image_type *type;
642 int loaded;
644 Lisp_Object success;
646 if (!loaded)
647 success = Qnil;
648 else
650 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
651 The initialized data segment is read-only. */
652 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
653 bcopy (type, p, sizeof *p);
654 p->next = image_types;
655 image_types = p;
656 success = Qt;
659 CACHE_IMAGE_TYPE (*type->type, success);
660 return success;
664 /* Look up image type SYMBOL, and return a pointer to its image_type
665 structure. Value is null if SYMBOL is not a known image type. */
667 static INLINE struct image_type *
668 lookup_image_type (symbol)
669 Lisp_Object symbol;
671 struct image_type *type;
673 /* We must initialize the image-type if it hasn't been already. */
674 if (NILP (Finit_image_library (symbol, Vimage_library_alist)))
675 return 0; /* unimplemented */
677 for (type = image_types; type; type = type->next)
678 if (EQ (symbol, *type->type))
679 break;
681 return type;
685 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
686 valid image specification is a list whose car is the symbol
687 `image', and whose rest is a property list. The property list must
688 contain a value for key `:type'. That value must be the name of a
689 supported image type. The rest of the property list depends on the
690 image type. */
693 valid_image_p (object)
694 Lisp_Object object;
696 int valid_p = 0;
698 if (IMAGEP (object))
700 Lisp_Object tem;
702 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
703 if (EQ (XCAR (tem), QCtype))
705 tem = XCDR (tem);
706 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
708 struct image_type *type;
709 type = lookup_image_type (XCAR (tem));
710 if (type)
711 valid_p = type->valid_p (object);
714 break;
718 return valid_p;
722 /* Log error message with format string FORMAT and argument ARG.
723 Signaling an error, e.g. when an image cannot be loaded, is not a
724 good idea because this would interrupt redisplay, and the error
725 message display would lead to another redisplay. This function
726 therefore simply displays a message. */
728 static void
729 image_error (format, arg1, arg2)
730 char *format;
731 Lisp_Object arg1, arg2;
733 add_to_log (format, arg1, arg2);
738 /***********************************************************************
739 Image specifications
740 ***********************************************************************/
742 enum image_value_type
744 IMAGE_DONT_CHECK_VALUE_TYPE,
745 IMAGE_STRING_VALUE,
746 IMAGE_STRING_OR_NIL_VALUE,
747 IMAGE_SYMBOL_VALUE,
748 IMAGE_POSITIVE_INTEGER_VALUE,
749 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
750 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
751 IMAGE_ASCENT_VALUE,
752 IMAGE_INTEGER_VALUE,
753 IMAGE_FUNCTION_VALUE,
754 IMAGE_NUMBER_VALUE,
755 IMAGE_BOOL_VALUE
758 /* Structure used when parsing image specifications. */
760 struct image_keyword
762 /* Name of keyword. */
763 char *name;
765 /* The type of value allowed. */
766 enum image_value_type type;
768 /* Non-zero means key must be present. */
769 int mandatory_p;
771 /* Used to recognize duplicate keywords in a property list. */
772 int count;
774 /* The value that was found. */
775 Lisp_Object value;
779 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
780 int, Lisp_Object));
781 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
784 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
785 has the format (image KEYWORD VALUE ...). One of the keyword/
786 value pairs must be `:type TYPE'. KEYWORDS is a vector of
787 image_keywords structures of size NKEYWORDS describing other
788 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
790 static int
791 parse_image_spec (spec, keywords, nkeywords, type)
792 Lisp_Object spec;
793 struct image_keyword *keywords;
794 int nkeywords;
795 Lisp_Object type;
797 int i;
798 Lisp_Object plist;
800 if (!IMAGEP (spec))
801 return 0;
803 plist = XCDR (spec);
804 while (CONSP (plist))
806 Lisp_Object key, value;
808 /* First element of a pair must be a symbol. */
809 key = XCAR (plist);
810 plist = XCDR (plist);
811 if (!SYMBOLP (key))
812 return 0;
814 /* There must follow a value. */
815 if (!CONSP (plist))
816 return 0;
817 value = XCAR (plist);
818 plist = XCDR (plist);
820 /* Find key in KEYWORDS. Error if not found. */
821 for (i = 0; i < nkeywords; ++i)
822 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
823 break;
825 if (i == nkeywords)
826 continue;
828 /* Record that we recognized the keyword. If a keywords
829 was found more than once, it's an error. */
830 keywords[i].value = value;
831 ++keywords[i].count;
833 if (keywords[i].count > 1)
834 return 0;
836 /* Check type of value against allowed type. */
837 switch (keywords[i].type)
839 case IMAGE_STRING_VALUE:
840 if (!STRINGP (value))
841 return 0;
842 break;
844 case IMAGE_STRING_OR_NIL_VALUE:
845 if (!STRINGP (value) && !NILP (value))
846 return 0;
847 break;
849 case IMAGE_SYMBOL_VALUE:
850 if (!SYMBOLP (value))
851 return 0;
852 break;
854 case IMAGE_POSITIVE_INTEGER_VALUE:
855 if (!INTEGERP (value) || XINT (value) <= 0)
856 return 0;
857 break;
859 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
860 if (INTEGERP (value) && XINT (value) >= 0)
861 break;
862 if (CONSP (value)
863 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
864 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
865 break;
866 return 0;
868 case IMAGE_ASCENT_VALUE:
869 if (SYMBOLP (value) && EQ (value, Qcenter))
870 break;
871 else if (INTEGERP (value)
872 && XINT (value) >= 0
873 && XINT (value) <= 100)
874 break;
875 return 0;
877 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
878 if (!INTEGERP (value) || XINT (value) < 0)
879 return 0;
880 break;
882 case IMAGE_DONT_CHECK_VALUE_TYPE:
883 break;
885 case IMAGE_FUNCTION_VALUE:
886 value = indirect_function (value);
887 if (SUBRP (value)
888 || COMPILEDP (value)
889 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
890 break;
891 return 0;
893 case IMAGE_NUMBER_VALUE:
894 if (!INTEGERP (value) && !FLOATP (value))
895 return 0;
896 break;
898 case IMAGE_INTEGER_VALUE:
899 if (!INTEGERP (value))
900 return 0;
901 break;
903 case IMAGE_BOOL_VALUE:
904 if (!NILP (value) && !EQ (value, Qt))
905 return 0;
906 break;
908 default:
909 abort ();
910 break;
913 if (EQ (key, QCtype) && !EQ (type, value))
914 return 0;
917 /* Check that all mandatory fields are present. */
918 for (i = 0; i < nkeywords; ++i)
919 if (keywords[i].mandatory_p && keywords[i].count == 0)
920 return 0;
922 return NILP (plist);
926 /* Return the value of KEY in image specification SPEC. Value is nil
927 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
928 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
930 static Lisp_Object
931 image_spec_value (spec, key, found)
932 Lisp_Object spec, key;
933 int *found;
935 Lisp_Object tail;
937 xassert (valid_image_p (spec));
939 for (tail = XCDR (spec);
940 CONSP (tail) && CONSP (XCDR (tail));
941 tail = XCDR (XCDR (tail)))
943 if (EQ (XCAR (tail), key))
945 if (found)
946 *found = 1;
947 return XCAR (XCDR (tail));
951 if (found)
952 *found = 0;
953 return Qnil;
957 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
958 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
959 PIXELS non-nil means return the size in pixels, otherwise return the
960 size in canonical character units.
961 FRAME is the frame on which the image will be displayed. FRAME nil
962 or omitted means use the selected frame. */)
963 (spec, pixels, frame)
964 Lisp_Object spec, pixels, frame;
966 Lisp_Object size;
968 size = Qnil;
969 if (valid_image_p (spec))
971 struct frame *f = check_x_frame (frame);
972 int id = lookup_image (f, spec);
973 struct image *img = IMAGE_FROM_ID (f, id);
974 int width = img->width + 2 * img->hmargin;
975 int height = img->height + 2 * img->vmargin;
977 if (NILP (pixels))
978 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
979 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
980 else
981 size = Fcons (make_number (width), make_number (height));
983 else
984 error ("Invalid image specification");
986 return size;
990 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
991 doc: /* Return t if image SPEC has a mask bitmap.
992 FRAME is the frame on which the image will be displayed. FRAME nil
993 or omitted means use the selected frame. */)
994 (spec, frame)
995 Lisp_Object spec, frame;
997 Lisp_Object mask;
999 mask = Qnil;
1000 if (valid_image_p (spec))
1002 struct frame *f = check_x_frame (frame);
1003 int id = lookup_image (f, spec);
1004 struct image *img = IMAGE_FROM_ID (f, id);
1005 if (img->mask)
1006 mask = Qt;
1008 else
1009 error ("Invalid image specification");
1011 return mask;
1014 DEFUN ("image-extension-data", Fimage_extension_data, Simage_extension_data, 1, 2, 0,
1015 doc: /* Return extension data for image SPEC.
1016 FRAME is the frame on which the image will be displayed. FRAME nil
1017 or omitted means use the selected frame. */)
1018 (spec, frame)
1019 Lisp_Object spec, frame;
1021 Lisp_Object ext;
1023 ext = Qnil;
1024 if (valid_image_p (spec))
1026 struct frame *f = check_x_frame (frame);
1027 int id = lookup_image (f, spec);
1028 struct image *img = IMAGE_FROM_ID (f, id);
1029 ext = img->data.lisp_val;
1032 return ext;
1036 /***********************************************************************
1037 Image type independent image structures
1038 ***********************************************************************/
1040 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
1041 static void free_image P_ ((struct frame *f, struct image *img));
1042 static int check_image_size P_ ((struct frame *f, int width, int height));
1044 #define MAX_IMAGE_SIZE 6.0
1045 Lisp_Object Vmax_image_size;
1047 /* Allocate and return a new image structure for image specification
1048 SPEC. SPEC has a hash value of HASH. */
1050 static struct image *
1051 make_image (spec, hash)
1052 Lisp_Object spec;
1053 unsigned hash;
1055 struct image *img = (struct image *) xmalloc (sizeof *img);
1056 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
1058 xassert (valid_image_p (spec));
1059 bzero (img, sizeof *img);
1060 img->dependencies = NILP (file) ? Qnil : list1 (file);
1061 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1062 xassert (img->type != NULL);
1063 img->spec = spec;
1064 img->data.lisp_val = Qnil;
1065 img->ascent = DEFAULT_IMAGE_ASCENT;
1066 img->hash = hash;
1067 img->corners[BOT_CORNER] = -1; /* Full image */
1068 return img;
1072 /* Free image IMG which was used on frame F, including its resources. */
1074 static void
1075 free_image (f, img)
1076 struct frame *f;
1077 struct image *img;
1079 if (img)
1081 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1083 /* Remove IMG from the hash table of its cache. */
1084 if (img->prev)
1085 img->prev->next = img->next;
1086 else
1087 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1089 if (img->next)
1090 img->next->prev = img->prev;
1092 c->images[img->id] = NULL;
1094 /* Free resources, then free IMG. */
1095 img->type->free (f, img);
1096 xfree (img);
1100 /* Return 1 if the given widths and heights are valid for display;
1101 otherwise, return 0. */
1104 check_image_size (f, width, height)
1105 struct frame *f;
1106 int width;
1107 int height;
1109 int w, h;
1111 if (width <= 0 || height <= 0)
1112 return 0;
1114 if (INTEGERP (Vmax_image_size))
1115 w = h = XINT (Vmax_image_size);
1116 else if (FLOATP (Vmax_image_size))
1118 if (f != NULL)
1120 w = FRAME_PIXEL_WIDTH (f);
1121 h = FRAME_PIXEL_HEIGHT (f);
1123 else
1124 w = h = 1024; /* Arbitrary size for unknown frame. */
1125 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1126 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1128 else
1129 return 1;
1131 return (width <= w && height <= h);
1134 /* Prepare image IMG for display on frame F. Must be called before
1135 drawing an image. */
1137 void
1138 prepare_image_for_display (f, img)
1139 struct frame *f;
1140 struct image *img;
1142 EMACS_TIME t;
1144 /* We're about to display IMG, so set its timestamp to `now'. */
1145 EMACS_GET_TIME (t);
1146 img->timestamp = EMACS_SECS (t);
1148 /* If IMG doesn't have a pixmap yet, load it now, using the image
1149 type dependent loader function. */
1150 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1151 img->load_failed_p = img->type->load (f, img) == 0;
1156 /* Value is the number of pixels for the ascent of image IMG when
1157 drawn in face FACE. */
1160 image_ascent (img, face, slice)
1161 struct image *img;
1162 struct face *face;
1163 struct glyph_slice *slice;
1165 int height;
1166 int ascent;
1168 if (slice->height == img->height)
1169 height = img->height + img->vmargin;
1170 else if (slice->y == 0)
1171 height = slice->height + img->vmargin;
1172 else
1173 height = slice->height;
1175 if (img->ascent == CENTERED_IMAGE_ASCENT)
1177 if (face->font)
1179 #ifdef HAVE_NTGUI
1180 /* W32 specific version. Why?. ++kfs */
1181 ascent = height / 2 - (FONT_DESCENT (face->font)
1182 - FONT_BASE (face->font)) / 2;
1183 #else
1184 /* This expression is arranged so that if the image can't be
1185 exactly centered, it will be moved slightly up. This is
1186 because a typical font is `top-heavy' (due to the presence
1187 uppercase letters), so the image placement should err towards
1188 being top-heavy too. It also just generally looks better. */
1189 ascent = (height + FONT_BASE(face->font)
1190 - FONT_DESCENT(face->font) + 1) / 2;
1191 #endif /* HAVE_NTGUI */
1193 else
1194 ascent = height / 2;
1196 else
1197 ascent = (int) (height * img->ascent / 100.0);
1199 return ascent;
1203 /* Image background colors. */
1205 /* Find the "best" corner color of a bitmap.
1206 On W32, XIMG is assumed to a device context with the bitmap selected. */
1208 static RGB_PIXEL_COLOR
1209 four_corners_best (ximg, corners, width, height)
1210 XImagePtr_or_DC ximg;
1211 int *corners;
1212 unsigned long width, height;
1214 RGB_PIXEL_COLOR corner_pixels[4], best;
1215 int i, best_count;
1217 if (corners && corners[BOT_CORNER] >= 0)
1219 /* Get the colors at the corner_pixels of ximg. */
1220 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1221 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1222 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1223 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1225 else
1227 /* Get the colors at the corner_pixels of ximg. */
1228 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1229 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1230 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1231 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1233 /* Choose the most frequently found color as background. */
1234 for (i = best_count = 0; i < 4; ++i)
1236 int j, n;
1238 for (j = n = 0; j < 4; ++j)
1239 if (corner_pixels[i] == corner_pixels[j])
1240 ++n;
1242 if (n > best_count)
1243 best = corner_pixels[i], best_count = n;
1246 return best;
1249 /* Portability macros */
1251 #ifdef HAVE_NTGUI
1253 #define Destroy_Image(img_dc, prev) \
1254 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1256 #define Free_Pixmap(display, pixmap) \
1257 DeleteObject (pixmap)
1259 #elif defined (HAVE_NS)
1261 #define Destroy_Image(ximg, dummy) \
1262 ns_release_object(ximg)
1264 #define Free_Pixmap(display, pixmap) \
1265 ns_release_object(pixmap)
1267 #else
1269 #define Destroy_Image(ximg, dummy) \
1270 XDestroyImage (ximg)
1272 #define Free_Pixmap(display, pixmap) \
1273 XFreePixmap (display, pixmap)
1275 #endif /* !HAVE_NTGUI && !HAVE_NS */
1278 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1279 it is guessed heuristically. If non-zero, XIMG is an existing
1280 XImage object (or device context with the image selected on W32) to
1281 use for the heuristic. */
1283 RGB_PIXEL_COLOR
1284 image_background (img, f, ximg)
1285 struct image *img;
1286 struct frame *f;
1287 XImagePtr_or_DC ximg;
1289 if (! img->background_valid)
1290 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1292 int free_ximg = !ximg;
1293 #ifdef HAVE_NTGUI
1294 HGDIOBJ prev;
1295 #endif /* HAVE_NTGUI */
1297 if (free_ximg)
1299 #ifndef HAVE_NTGUI
1300 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1301 0, 0, img->width, img->height, ~0, ZPixmap);
1302 #else
1303 HDC frame_dc = get_frame_dc (f);
1304 ximg = CreateCompatibleDC (frame_dc);
1305 release_frame_dc (f, frame_dc);
1306 prev = SelectObject (ximg, img->pixmap);
1307 #endif /* !HAVE_NTGUI */
1310 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1312 if (free_ximg)
1313 Destroy_Image (ximg, prev);
1315 img->background_valid = 1;
1318 return img->background;
1321 /* Return the `background_transparent' field of IMG. If IMG doesn't
1322 have one yet, it is guessed heuristically. If non-zero, MASK is an
1323 existing XImage object to use for the heuristic. */
1326 image_background_transparent (img, f, mask)
1327 struct image *img;
1328 struct frame *f;
1329 XImagePtr_or_DC mask;
1331 if (! img->background_transparent_valid)
1332 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1334 if (img->mask)
1336 int free_mask = !mask;
1337 #ifdef HAVE_NTGUI
1338 HGDIOBJ prev;
1339 #endif /* HAVE_NTGUI */
1341 if (free_mask)
1343 #ifndef HAVE_NTGUI
1344 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1345 0, 0, img->width, img->height, ~0, ZPixmap);
1346 #else
1347 HDC frame_dc = get_frame_dc (f);
1348 mask = CreateCompatibleDC (frame_dc);
1349 release_frame_dc (f, frame_dc);
1350 prev = SelectObject (mask, img->mask);
1351 #endif /* HAVE_NTGUI */
1354 img->background_transparent
1355 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1357 if (free_mask)
1358 Destroy_Image (mask, prev);
1360 else
1361 img->background_transparent = 0;
1363 img->background_transparent_valid = 1;
1366 return img->background_transparent;
1370 /***********************************************************************
1371 Helper functions for X image types
1372 ***********************************************************************/
1374 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
1375 int, int));
1376 static void x_clear_image P_ ((struct frame *f, struct image *img));
1377 static unsigned long x_alloc_image_color P_ ((struct frame *f,
1378 struct image *img,
1379 Lisp_Object color_name,
1380 unsigned long dflt));
1383 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1384 free the pixmap if any. MASK_P non-zero means clear the mask
1385 pixmap if any. COLORS_P non-zero means free colors allocated for
1386 the image, if any. */
1388 static void
1389 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
1390 struct frame *f;
1391 struct image *img;
1392 int pixmap_p, mask_p, colors_p;
1394 if (pixmap_p && img->pixmap)
1396 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1397 img->pixmap = NO_PIXMAP;
1398 /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1399 img->background_valid = 0;
1402 if (mask_p && img->mask)
1404 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1405 img->mask = NO_PIXMAP;
1406 img->background_transparent_valid = 0;
1409 if (colors_p && img->ncolors)
1411 /* W32_TODO: color table support. */
1412 #ifdef HAVE_X_WINDOWS
1413 x_free_colors (f, img->colors, img->ncolors);
1414 #endif /* HAVE_X_WINDOWS */
1415 xfree (img->colors);
1416 img->colors = NULL;
1417 img->ncolors = 0;
1422 /* Free X resources of image IMG which is used on frame F. */
1424 static void
1425 x_clear_image (f, img)
1426 struct frame *f;
1427 struct image *img;
1429 BLOCK_INPUT;
1430 x_clear_image_1 (f, img, 1, 1, 1);
1431 UNBLOCK_INPUT;
1435 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1436 cannot be allocated, use DFLT. Add a newly allocated color to
1437 IMG->colors, so that it can be freed again. Value is the pixel
1438 color. */
1440 static unsigned long
1441 x_alloc_image_color (f, img, color_name, dflt)
1442 struct frame *f;
1443 struct image *img;
1444 Lisp_Object color_name;
1445 unsigned long dflt;
1447 XColor color;
1448 unsigned long result;
1450 xassert (STRINGP (color_name));
1452 if (x_defined_color (f, SDATA (color_name), &color, 1))
1454 /* This isn't called frequently so we get away with simply
1455 reallocating the color vector to the needed size, here. */
1456 ++img->ncolors;
1457 img->colors =
1458 (unsigned long *) xrealloc (img->colors,
1459 img->ncolors * sizeof *img->colors);
1460 img->colors[img->ncolors - 1] = color.pixel;
1461 result = color.pixel;
1463 else
1464 result = dflt;
1466 return result;
1471 /***********************************************************************
1472 Image Cache
1473 ***********************************************************************/
1475 static struct image *search_image_cache P_ ((struct frame *, Lisp_Object, unsigned));
1476 static void cache_image P_ ((struct frame *f, struct image *img));
1477 static void postprocess_image P_ ((struct frame *, struct image *));
1479 /* Return a new, initialized image cache that is allocated from the
1480 heap. Call free_image_cache to free an image cache. */
1482 struct image_cache *
1483 make_image_cache ()
1485 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1486 int size;
1488 bzero (c, sizeof *c);
1489 c->size = 50;
1490 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1491 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1492 c->buckets = (struct image **) xmalloc (size);
1493 bzero (c->buckets, size);
1494 return c;
1498 /* Find an image matching SPEC in the cache, and return it. If no
1499 image is found, return NULL. */
1500 static struct image *
1501 search_image_cache (f, spec, hash)
1502 struct frame *f;
1503 Lisp_Object spec;
1504 unsigned hash;
1506 struct image *img;
1507 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1508 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1510 if (!c) return NULL;
1512 /* If the image spec does not specify a background color, the cached
1513 image must have the same background color as the current frame.
1514 The foreground color must also match, for the sake of monochrome
1515 images.
1517 In fact, we could ignore the foreground color matching condition
1518 for color images, or if the image spec specifies :foreground;
1519 similarly we could ignore the background color matching condition
1520 for formats that don't use transparency (such as jpeg), or if the
1521 image spec specifies :background. However, the extra memory
1522 usage is probably negligible in practice, so we don't bother. */
1524 for (img = c->buckets[i]; img; img = img->next)
1525 if (img->hash == hash
1526 && !NILP (Fequal (img->spec, spec))
1527 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1528 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1529 break;
1530 return img;
1534 /* Search frame F for an image with spec SPEC, and free it. */
1536 static void
1537 uncache_image (f, spec)
1538 struct frame *f;
1539 Lisp_Object spec;
1541 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1542 if (img)
1544 free_image (f, img);
1545 /* As display glyphs may still be referring to the image ID, we
1546 must garbage the frame (Bug#6426). */
1547 SET_FRAME_GARBAGED (f);
1552 /* Free image cache of frame F. Be aware that X frames share images
1553 caches. */
1555 void
1556 free_image_cache (f)
1557 struct frame *f;
1559 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1560 if (c)
1562 int i;
1564 /* Cache should not be referenced by any frame when freed. */
1565 xassert (c->refcount == 0);
1567 for (i = 0; i < c->used; ++i)
1568 free_image (f, c->images[i]);
1569 xfree (c->images);
1570 xfree (c->buckets);
1571 xfree (c);
1572 FRAME_IMAGE_CACHE (f) = NULL;
1577 /* Clear image cache of frame F. FILTER=t means free all images.
1578 FILTER=nil means clear only images that haven't been
1579 displayed for some time.
1580 Else, only free the images which have FILTER in their `dependencies'.
1581 Should be called from time to time to reduce the number of loaded images.
1582 If image-cache-eviction-delay is non-nil, this frees images in the cache
1583 which weren't displayed for at least that many seconds. */
1585 void
1586 clear_image_cache (struct frame *f, Lisp_Object filter)
1588 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1590 if (c && (!NILP (filter) || INTEGERP (Vimage_cache_eviction_delay)))
1592 EMACS_TIME t;
1593 unsigned long old;
1594 int i, nfreed;
1596 EMACS_GET_TIME (t);
1597 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
1599 /* Block input so that we won't be interrupted by a SIGIO
1600 while being in an inconsistent state. */
1601 BLOCK_INPUT;
1603 for (i = nfreed = 0; i < c->used; ++i)
1605 struct image *img = c->images[i];
1606 if (img != NULL
1607 && (NILP (filter) ? img->timestamp < old
1608 : (EQ (Qt, filter)
1609 || !NILP (Fmember (filter, img->dependencies)))))
1611 free_image (f, img);
1612 ++nfreed;
1616 /* We may be clearing the image cache because, for example,
1617 Emacs was iconified for a longer period of time. In that
1618 case, current matrices may still contain references to
1619 images freed above. So, clear these matrices. */
1620 if (nfreed)
1622 Lisp_Object tail, frame;
1624 FOR_EACH_FRAME (tail, frame)
1626 struct frame *f = XFRAME (frame);
1627 if (FRAME_IMAGE_CACHE (f) == c)
1628 clear_current_matrices (f);
1631 ++windows_or_buffers_changed;
1634 UNBLOCK_INPUT;
1638 void
1639 clear_image_caches (Lisp_Object filter)
1641 /* FIXME: We want to do
1642 * struct terminal *t;
1643 * for (t = terminal_list; t; t = t->next_terminal)
1644 * clear_image_cache (t, filter); */
1645 Lisp_Object tail, frame;
1646 FOR_EACH_FRAME (tail, frame)
1647 if (FRAME_WINDOW_P (XFRAME (frame)))
1648 clear_image_cache (XFRAME (frame), filter);
1651 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1652 0, 1, 0,
1653 doc: /* Clear the image cache.
1654 FILTER nil or a frame means clear all images in the selected frame.
1655 FILTER t means clear the image caches of all frames.
1656 Anything else, means only clear those images which refer to FILTER,
1657 which is then usually a filename. */)
1658 (filter)
1659 Lisp_Object filter;
1661 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1662 clear_image_caches (filter);
1663 else
1664 clear_image_cache (check_x_frame (filter), Qt);
1666 return Qnil;
1670 DEFUN ("image-refresh", Fimage_refresh, Simage_refresh,
1671 1, 2, 0,
1672 doc: /* Refresh the image with specification SPEC on frame FRAME.
1673 If SPEC specifies an image file, the displayed image is updated with
1674 the current contents of that file.
1675 FRAME nil or omitted means use the selected frame.
1676 FRAME t means refresh the image on all frames. */)
1677 (spec, frame)
1678 Lisp_Object spec, frame;
1680 if (!valid_image_p (spec))
1681 error ("Invalid image specification");
1683 if (EQ (frame, Qt))
1685 Lisp_Object tail;
1686 FOR_EACH_FRAME (tail, frame)
1688 struct frame *f = XFRAME (frame);
1689 if (FRAME_WINDOW_P (f))
1690 uncache_image (f, spec);
1693 else
1694 uncache_image (check_x_frame (frame), spec);
1696 return Qnil;
1700 /* Compute masks and transform image IMG on frame F, as specified
1701 by the image's specification, */
1703 static void
1704 postprocess_image (f, img)
1705 struct frame *f;
1706 struct image *img;
1708 /* Manipulation of the image's mask. */
1709 if (img->pixmap)
1711 Lisp_Object conversion, spec;
1712 Lisp_Object mask;
1714 spec = img->spec;
1716 /* `:heuristic-mask t'
1717 `:mask heuristic'
1718 means build a mask heuristically.
1719 `:heuristic-mask (R G B)'
1720 `:mask (heuristic (R G B))'
1721 means build a mask from color (R G B) in the
1722 image.
1723 `:mask nil'
1724 means remove a mask, if any. */
1726 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1727 if (!NILP (mask))
1728 x_build_heuristic_mask (f, img, mask);
1729 else
1731 int found_p;
1733 mask = image_spec_value (spec, QCmask, &found_p);
1735 if (EQ (mask, Qheuristic))
1736 x_build_heuristic_mask (f, img, Qt);
1737 else if (CONSP (mask)
1738 && EQ (XCAR (mask), Qheuristic))
1740 if (CONSP (XCDR (mask)))
1741 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1742 else
1743 x_build_heuristic_mask (f, img, XCDR (mask));
1745 else if (NILP (mask) && found_p && img->mask)
1747 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1748 img->mask = NO_PIXMAP;
1753 /* Should we apply an image transformation algorithm? */
1754 conversion = image_spec_value (spec, QCconversion, NULL);
1755 if (EQ (conversion, Qdisabled))
1756 x_disable_image (f, img);
1757 else if (EQ (conversion, Qlaplace))
1758 x_laplace (f, img);
1759 else if (EQ (conversion, Qemboss))
1760 x_emboss (f, img);
1761 else if (CONSP (conversion)
1762 && EQ (XCAR (conversion), Qedge_detection))
1764 Lisp_Object tem;
1765 tem = XCDR (conversion);
1766 if (CONSP (tem))
1767 x_edge_detection (f, img,
1768 Fplist_get (tem, QCmatrix),
1769 Fplist_get (tem, QCcolor_adjustment));
1775 /* Return the id of image with Lisp specification SPEC on frame F.
1776 SPEC must be a valid Lisp image specification (see valid_image_p). */
1779 lookup_image (f, spec)
1780 struct frame *f;
1781 Lisp_Object spec;
1783 struct image_cache *c;
1784 struct image *img;
1785 unsigned hash;
1786 struct gcpro gcpro1;
1787 EMACS_TIME now;
1789 /* F must be a window-system frame, and SPEC must be a valid image
1790 specification. */
1791 xassert (FRAME_WINDOW_P (f));
1792 xassert (valid_image_p (spec));
1794 c = FRAME_IMAGE_CACHE (f);
1796 GCPRO1 (spec);
1798 /* Look up SPEC in the hash table of the image cache. */
1799 hash = sxhash (spec, 0);
1800 img = search_image_cache (f, spec, hash);
1801 if (img && img->load_failed_p)
1803 free_image (f, img);
1804 img = NULL;
1807 /* If not found, create a new image and cache it. */
1808 if (img == NULL)
1810 extern Lisp_Object Qpostscript;
1812 BLOCK_INPUT;
1813 img = make_image (spec, hash);
1814 cache_image (f, img);
1815 img->load_failed_p = img->type->load (f, img) == 0;
1816 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
1817 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1819 /* If we can't load the image, and we don't have a width and
1820 height, use some arbitrary width and height so that we can
1821 draw a rectangle for it. */
1822 if (img->load_failed_p)
1824 Lisp_Object value;
1826 value = image_spec_value (spec, QCwidth, NULL);
1827 img->width = (INTEGERP (value)
1828 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1829 value = image_spec_value (spec, QCheight, NULL);
1830 img->height = (INTEGERP (value)
1831 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1833 else
1835 /* Handle image type independent image attributes
1836 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1837 `:background COLOR'. */
1838 Lisp_Object ascent, margin, relief, bg;
1840 ascent = image_spec_value (spec, QCascent, NULL);
1841 if (INTEGERP (ascent))
1842 img->ascent = XFASTINT (ascent);
1843 else if (EQ (ascent, Qcenter))
1844 img->ascent = CENTERED_IMAGE_ASCENT;
1846 margin = image_spec_value (spec, QCmargin, NULL);
1847 if (INTEGERP (margin) && XINT (margin) >= 0)
1848 img->vmargin = img->hmargin = XFASTINT (margin);
1849 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1850 && INTEGERP (XCDR (margin)))
1852 if (XINT (XCAR (margin)) > 0)
1853 img->hmargin = XFASTINT (XCAR (margin));
1854 if (XINT (XCDR (margin)) > 0)
1855 img->vmargin = XFASTINT (XCDR (margin));
1858 relief = image_spec_value (spec, QCrelief, NULL);
1859 if (INTEGERP (relief))
1861 img->relief = XINT (relief);
1862 img->hmargin += eabs (img->relief);
1863 img->vmargin += eabs (img->relief);
1866 if (! img->background_valid)
1868 bg = image_spec_value (img->spec, QCbackground, NULL);
1869 if (!NILP (bg))
1871 img->background
1872 = x_alloc_image_color (f, img, bg,
1873 FRAME_BACKGROUND_PIXEL (f));
1874 img->background_valid = 1;
1878 /* Do image transformations and compute masks, unless we
1879 don't have the image yet. */
1880 if (!EQ (*img->type->type, Qpostscript))
1881 postprocess_image (f, img);
1884 UNBLOCK_INPUT;
1887 /* We're using IMG, so set its timestamp to `now'. */
1888 EMACS_GET_TIME (now);
1889 img->timestamp = EMACS_SECS (now);
1891 UNGCPRO;
1893 /* Value is the image id. */
1894 return img->id;
1898 /* Cache image IMG in the image cache of frame F. */
1900 static void
1901 cache_image (f, img)
1902 struct frame *f;
1903 struct image *img;
1905 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1906 int i;
1908 /* Find a free slot in c->images. */
1909 for (i = 0; i < c->used; ++i)
1910 if (c->images[i] == NULL)
1911 break;
1913 /* If no free slot found, maybe enlarge c->images. */
1914 if (i == c->used && c->used == c->size)
1916 c->size *= 2;
1917 c->images = (struct image **) xrealloc (c->images,
1918 c->size * sizeof *c->images);
1921 /* Add IMG to c->images, and assign IMG an id. */
1922 c->images[i] = img;
1923 img->id = i;
1924 if (i == c->used)
1925 ++c->used;
1927 /* Add IMG to the cache's hash table. */
1928 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1929 img->next = c->buckets[i];
1930 if (img->next)
1931 img->next->prev = img;
1932 img->prev = NULL;
1933 c->buckets[i] = img;
1937 /* Call FN on every image in the image cache of frame F. Used to mark
1938 Lisp Objects in the image cache. */
1940 /* Mark Lisp objects in image IMG. */
1942 static void
1943 mark_image (img)
1944 struct image *img;
1946 mark_object (img->spec);
1947 mark_object (img->dependencies);
1949 if (!NILP (img->data.lisp_val))
1950 mark_object (img->data.lisp_val);
1954 void
1955 mark_image_cache (struct image_cache *c)
1957 if (c)
1959 int i;
1960 for (i = 0; i < c->used; ++i)
1961 if (c->images[i])
1962 mark_image (c->images[i]);
1968 /***********************************************************************
1969 X / NS / W32 support code
1970 ***********************************************************************/
1972 #ifdef HAVE_NTGUI
1974 /* Macro for defining functions that will be loaded from image DLLs. */
1975 #define DEF_IMGLIB_FN(func) int (FAR CDECL *fn_##func)()
1977 /* Macro for loading those image functions from the library. */
1978 #define LOAD_IMGLIB_FN(lib,func) { \
1979 fn_##func = (void *) GetProcAddress (lib, #func); \
1980 if (!fn_##func) return 0; \
1983 /* Load a DLL implementing an image type.
1984 The `image-library-alist' variable associates a symbol,
1985 identifying an image type, to a list of possible filenames.
1986 The function returns NULL if no library could be loaded for
1987 the given image type, or if the library was previously loaded;
1988 else the handle of the DLL. */
1989 static HMODULE
1990 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
1992 HMODULE library = NULL;
1994 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
1996 Lisp_Object dlls = Fassq (type, libraries);
1998 if (CONSP (dlls))
1999 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
2001 CHECK_STRING_CAR (dlls);
2002 if (library = LoadLibrary (SDATA (XCAR (dlls))))
2003 break;
2007 return library;
2010 #endif /* HAVE_NTGUI */
2012 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
2013 XImagePtr *, Pixmap *));
2014 static void x_destroy_x_image P_ ((XImagePtr));
2015 static void x_put_x_image P_ ((struct frame *, XImagePtr, Pixmap, int, int));
2018 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
2019 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
2020 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
2021 via xmalloc. Print error messages via image_error if an error
2022 occurs. Value is non-zero if successful.
2024 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
2025 should indicate the bit depth of the image. */
2027 static int
2028 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
2029 struct frame *f;
2030 int width, height, depth;
2031 XImagePtr *ximg;
2032 Pixmap *pixmap;
2034 #ifdef HAVE_X_WINDOWS
2035 Display *display = FRAME_X_DISPLAY (f);
2036 Window window = FRAME_X_WINDOW (f);
2037 Screen *screen = FRAME_X_SCREEN (f);
2039 xassert (interrupt_input_blocked);
2041 if (depth <= 0)
2042 depth = DefaultDepthOfScreen (screen);
2043 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
2044 depth, ZPixmap, 0, NULL, width, height,
2045 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
2046 if (*ximg == NULL)
2048 image_error ("Unable to allocate X image", Qnil, Qnil);
2049 return 0;
2052 /* Allocate image raster. */
2053 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
2055 /* Allocate a pixmap of the same size. */
2056 *pixmap = XCreatePixmap (display, window, width, height, depth);
2057 if (*pixmap == NO_PIXMAP)
2059 x_destroy_x_image (*ximg);
2060 *ximg = NULL;
2061 image_error ("Unable to create X pixmap", Qnil, Qnil);
2062 return 0;
2065 return 1;
2066 #endif /* HAVE_X_WINDOWS */
2068 #ifdef HAVE_NTGUI
2070 BITMAPINFOHEADER *header;
2071 HDC hdc;
2072 int scanline_width_bits;
2073 int remainder;
2074 int palette_colors = 0;
2076 if (depth == 0)
2077 depth = 24;
2079 if (depth != 1 && depth != 4 && depth != 8
2080 && depth != 16 && depth != 24 && depth != 32)
2082 image_error ("Invalid image bit depth specified", Qnil, Qnil);
2083 return 0;
2086 scanline_width_bits = width * depth;
2087 remainder = scanline_width_bits % 32;
2089 if (remainder)
2090 scanline_width_bits += 32 - remainder;
2092 /* Bitmaps with a depth less than 16 need a palette. */
2093 /* BITMAPINFO structure already contains the first RGBQUAD. */
2094 if (depth < 16)
2095 palette_colors = 1 << depth - 1;
2097 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2098 if (*ximg == NULL)
2100 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
2101 return 0;
2104 header = &((*ximg)->info.bmiHeader);
2105 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
2106 header->biSize = sizeof (*header);
2107 header->biWidth = width;
2108 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2109 header->biPlanes = 1;
2110 header->biBitCount = depth;
2111 header->biCompression = BI_RGB;
2112 header->biClrUsed = palette_colors;
2114 /* TODO: fill in palette. */
2115 if (depth == 1)
2117 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2118 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2119 (*ximg)->info.bmiColors[0].rgbRed = 0;
2120 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2121 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2122 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2123 (*ximg)->info.bmiColors[1].rgbRed = 255;
2124 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2127 hdc = get_frame_dc (f);
2129 /* Create a DIBSection and raster array for the bitmap,
2130 and store its handle in *pixmap. */
2131 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2132 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2133 /* casting avoids a GCC warning */
2134 (void **)&((*ximg)->data), NULL, 0);
2136 /* Realize display palette and garbage all frames. */
2137 release_frame_dc (f, hdc);
2139 if (*pixmap == NULL)
2141 DWORD err = GetLastError ();
2142 Lisp_Object errcode;
2143 /* All system errors are < 10000, so the following is safe. */
2144 XSETINT (errcode, (int) err);
2145 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2146 x_destroy_x_image (*ximg);
2147 return 0;
2150 return 1;
2152 #endif /* HAVE_NTGUI */
2154 #ifdef HAVE_NS
2155 *pixmap = ns_image_for_XPM(width, height, depth);
2156 if (*pixmap == 0)
2158 *ximg = NULL;
2159 image_error ("Unable to allocate NSImage for XPM pixmap", Qnil, Qnil);
2160 return 0;
2162 *ximg = *pixmap;
2163 return 1;
2164 #endif
2168 /* Destroy XImage XIMG. Free XIMG->data. */
2170 static void
2171 x_destroy_x_image (ximg)
2172 XImagePtr ximg;
2174 xassert (interrupt_input_blocked);
2175 if (ximg)
2177 #ifdef HAVE_X_WINDOWS
2178 xfree (ximg->data);
2179 ximg->data = NULL;
2180 XDestroyImage (ximg);
2181 #endif /* HAVE_X_WINDOWS */
2182 #ifdef HAVE_NTGUI
2183 /* Data will be freed by DestroyObject. */
2184 ximg->data = NULL;
2185 xfree (ximg);
2186 #endif /* HAVE_NTGUI */
2187 #ifdef HAVE_NS
2188 ns_release_object(ximg);
2189 #endif /* HAVE_NS */
2194 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2195 are width and height of both the image and pixmap. */
2197 static void
2198 x_put_x_image (f, ximg, pixmap, width, height)
2199 struct frame *f;
2200 XImagePtr ximg;
2201 Pixmap pixmap;
2202 int width, height;
2204 #ifdef HAVE_X_WINDOWS
2205 GC gc;
2207 xassert (interrupt_input_blocked);
2208 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2209 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2210 XFreeGC (FRAME_X_DISPLAY (f), gc);
2211 #endif /* HAVE_X_WINDOWS */
2213 #ifdef HAVE_NTGUI
2214 #if 0 /* I don't think this is necessary looking at where it is used. */
2215 HDC hdc = get_frame_dc (f);
2216 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2217 release_frame_dc (f, hdc);
2218 #endif
2219 #endif /* HAVE_NTGUI */
2221 #ifdef HAVE_NS
2222 xassert (ximg == pixmap);
2223 ns_retain_object(ximg);
2224 #endif
2228 /***********************************************************************
2229 File Handling
2230 ***********************************************************************/
2232 static unsigned char *slurp_file P_ ((char *, int *));
2235 /* Find image file FILE. Look in data-directory/images, then
2236 x-bitmap-file-path. Value is the encoded full name of the file
2237 found, or nil if not found. */
2239 Lisp_Object
2240 x_find_image_file (file)
2241 Lisp_Object file;
2243 Lisp_Object file_found, search_path;
2244 struct gcpro gcpro1, gcpro2;
2245 int fd;
2247 file_found = Qnil;
2248 /* TODO I think this should use something like image-load-path
2249 instead. Unfortunately, that can contain non-string elements. */
2250 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2251 Vdata_directory),
2252 Vx_bitmap_file_path);
2253 GCPRO2 (file_found, search_path);
2255 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2256 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2258 if (fd == -1)
2259 file_found = Qnil;
2260 else
2262 file_found = ENCODE_FILE (file_found);
2263 close (fd);
2266 UNGCPRO;
2267 return file_found;
2271 /* Read FILE into memory. Value is a pointer to a buffer allocated
2272 with xmalloc holding FILE's contents. Value is null if an error
2273 occurred. *SIZE is set to the size of the file. */
2275 static unsigned char *
2276 slurp_file (file, size)
2277 char *file;
2278 int *size;
2280 FILE *fp = NULL;
2281 unsigned char *buf = NULL;
2282 struct stat st;
2284 if (stat (file, &st) == 0
2285 && (fp = fopen (file, "rb")) != NULL
2286 && (buf = (unsigned char *) xmalloc (st.st_size),
2287 fread (buf, 1, st.st_size, fp) == st.st_size))
2289 *size = st.st_size;
2290 fclose (fp);
2292 else
2294 if (fp)
2295 fclose (fp);
2296 if (buf)
2298 xfree (buf);
2299 buf = NULL;
2303 return buf;
2308 /***********************************************************************
2309 XBM images
2310 ***********************************************************************/
2312 static int xbm_scan P_ ((unsigned char **, unsigned char *, char *, int *));
2313 static int xbm_load P_ ((struct frame *f, struct image *img));
2314 static int xbm_load_image P_ ((struct frame *f, struct image *img,
2315 unsigned char *, unsigned char *));
2316 static int xbm_image_p P_ ((Lisp_Object object));
2317 static int xbm_read_bitmap_data P_ ((struct frame *f,
2318 unsigned char *, unsigned char *,
2319 int *, int *, unsigned char **, int));
2320 static int xbm_file_p P_ ((Lisp_Object));
2323 /* Indices of image specification fields in xbm_format, below. */
2325 enum xbm_keyword_index
2327 XBM_TYPE,
2328 XBM_FILE,
2329 XBM_WIDTH,
2330 XBM_HEIGHT,
2331 XBM_DATA,
2332 XBM_FOREGROUND,
2333 XBM_BACKGROUND,
2334 XBM_ASCENT,
2335 XBM_MARGIN,
2336 XBM_RELIEF,
2337 XBM_ALGORITHM,
2338 XBM_HEURISTIC_MASK,
2339 XBM_MASK,
2340 XBM_LAST
2343 /* Vector of image_keyword structures describing the format
2344 of valid XBM image specifications. */
2346 static const struct image_keyword xbm_format[XBM_LAST] =
2348 {":type", IMAGE_SYMBOL_VALUE, 1},
2349 {":file", IMAGE_STRING_VALUE, 0},
2350 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2351 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2352 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2353 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2354 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2355 {":ascent", IMAGE_ASCENT_VALUE, 0},
2356 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2357 {":relief", IMAGE_INTEGER_VALUE, 0},
2358 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2359 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2360 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2363 /* Structure describing the image type XBM. */
2365 static struct image_type xbm_type =
2367 &Qxbm,
2368 xbm_image_p,
2369 xbm_load,
2370 x_clear_image,
2371 NULL
2374 /* Tokens returned from xbm_scan. */
2376 enum xbm_token
2378 XBM_TK_IDENT = 256,
2379 XBM_TK_NUMBER
2383 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2384 A valid specification is a list starting with the symbol `image'
2385 The rest of the list is a property list which must contain an
2386 entry `:type xbm..
2388 If the specification specifies a file to load, it must contain
2389 an entry `:file FILENAME' where FILENAME is a string.
2391 If the specification is for a bitmap loaded from memory it must
2392 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2393 WIDTH and HEIGHT are integers > 0. DATA may be:
2395 1. a string large enough to hold the bitmap data, i.e. it must
2396 have a size >= (WIDTH + 7) / 8 * HEIGHT
2398 2. a bool-vector of size >= WIDTH * HEIGHT
2400 3. a vector of strings or bool-vectors, one for each line of the
2401 bitmap.
2403 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
2404 may not be specified in this case because they are defined in the
2405 XBM file.
2407 Both the file and data forms may contain the additional entries
2408 `:background COLOR' and `:foreground COLOR'. If not present,
2409 foreground and background of the frame on which the image is
2410 displayed is used. */
2412 static int
2413 xbm_image_p (object)
2414 Lisp_Object object;
2416 struct image_keyword kw[XBM_LAST];
2418 bcopy (xbm_format, kw, sizeof kw);
2419 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2420 return 0;
2422 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2424 if (kw[XBM_FILE].count)
2426 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2427 return 0;
2429 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2431 /* In-memory XBM file. */
2432 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2433 return 0;
2435 else
2437 Lisp_Object data;
2438 int width, height;
2440 /* Entries for `:width', `:height' and `:data' must be present. */
2441 if (!kw[XBM_WIDTH].count
2442 || !kw[XBM_HEIGHT].count
2443 || !kw[XBM_DATA].count)
2444 return 0;
2446 data = kw[XBM_DATA].value;
2447 width = XFASTINT (kw[XBM_WIDTH].value);
2448 height = XFASTINT (kw[XBM_HEIGHT].value);
2450 /* Check type of data, and width and height against contents of
2451 data. */
2452 if (VECTORP (data))
2454 int i;
2456 /* Number of elements of the vector must be >= height. */
2457 if (XVECTOR (data)->size < height)
2458 return 0;
2460 /* Each string or bool-vector in data must be large enough
2461 for one line of the image. */
2462 for (i = 0; i < height; ++i)
2464 Lisp_Object elt = XVECTOR (data)->contents[i];
2466 if (STRINGP (elt))
2468 if (SCHARS (elt)
2469 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2470 return 0;
2472 else if (BOOL_VECTOR_P (elt))
2474 if (XBOOL_VECTOR (elt)->size < width)
2475 return 0;
2477 else
2478 return 0;
2481 else if (STRINGP (data))
2483 if (SCHARS (data)
2484 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2485 return 0;
2487 else if (BOOL_VECTOR_P (data))
2489 if (XBOOL_VECTOR (data)->size < width * height)
2490 return 0;
2492 else
2493 return 0;
2496 return 1;
2500 /* Scan a bitmap file. FP is the stream to read from. Value is
2501 either an enumerator from enum xbm_token, or a character for a
2502 single-character token, or 0 at end of file. If scanning an
2503 identifier, store the lexeme of the identifier in SVAL. If
2504 scanning a number, store its value in *IVAL. */
2506 static int
2507 xbm_scan (s, end, sval, ival)
2508 unsigned char **s, *end;
2509 char *sval;
2510 int *ival;
2512 unsigned int c;
2514 loop:
2516 /* Skip white space. */
2517 while (*s < end && (c = *(*s)++, isspace (c)))
2520 if (*s >= end)
2521 c = 0;
2522 else if (isdigit (c))
2524 int value = 0, digit;
2526 if (c == '0' && *s < end)
2528 c = *(*s)++;
2529 if (c == 'x' || c == 'X')
2531 while (*s < end)
2533 c = *(*s)++;
2534 if (isdigit (c))
2535 digit = c - '0';
2536 else if (c >= 'a' && c <= 'f')
2537 digit = c - 'a' + 10;
2538 else if (c >= 'A' && c <= 'F')
2539 digit = c - 'A' + 10;
2540 else
2541 break;
2542 value = 16 * value + digit;
2545 else if (isdigit (c))
2547 value = c - '0';
2548 while (*s < end
2549 && (c = *(*s)++, isdigit (c)))
2550 value = 8 * value + c - '0';
2553 else
2555 value = c - '0';
2556 while (*s < end
2557 && (c = *(*s)++, isdigit (c)))
2558 value = 10 * value + c - '0';
2561 if (*s < end)
2562 *s = *s - 1;
2563 *ival = value;
2564 c = XBM_TK_NUMBER;
2566 else if (isalpha (c) || c == '_')
2568 *sval++ = c;
2569 while (*s < end
2570 && (c = *(*s)++, (isalnum (c) || c == '_')))
2571 *sval++ = c;
2572 *sval = 0;
2573 if (*s < end)
2574 *s = *s - 1;
2575 c = XBM_TK_IDENT;
2577 else if (c == '/' && **s == '*')
2579 /* C-style comment. */
2580 ++*s;
2581 while (**s && (**s != '*' || *(*s + 1) != '/'))
2582 ++*s;
2583 if (**s)
2585 *s += 2;
2586 goto loop;
2590 return c;
2593 #ifdef HAVE_NTGUI
2595 /* Create a Windows bitmap from X bitmap data. */
2596 static HBITMAP
2597 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2599 static unsigned char swap_nibble[16]
2600 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2601 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2602 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2603 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2604 int i, j, w1, w2;
2605 unsigned char *bits, *p;
2606 HBITMAP bmp;
2608 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2609 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2610 bits = (unsigned char *) alloca (height * w2);
2611 bzero (bits, height * w2);
2612 for (i = 0; i < height; i++)
2614 p = bits + i*w2;
2615 for (j = 0; j < w1; j++)
2617 /* Bitswap XBM bytes to match how Windows does things. */
2618 unsigned char c = *data++;
2619 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2620 | (swap_nibble[(c>>4) & 0xf]));
2623 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2625 return bmp;
2628 static void
2629 convert_mono_to_color_image (f, img, foreground, background)
2630 struct frame *f;
2631 struct image *img;
2632 COLORREF foreground, background;
2634 HDC hdc, old_img_dc, new_img_dc;
2635 HGDIOBJ old_prev, new_prev;
2636 HBITMAP new_pixmap;
2638 hdc = get_frame_dc (f);
2639 old_img_dc = CreateCompatibleDC (hdc);
2640 new_img_dc = CreateCompatibleDC (hdc);
2641 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2642 release_frame_dc (f, hdc);
2643 old_prev = SelectObject (old_img_dc, img->pixmap);
2644 new_prev = SelectObject (new_img_dc, new_pixmap);
2645 /* Windows convention for mono bitmaps is black = background,
2646 white = foreground. */
2647 SetTextColor (new_img_dc, background);
2648 SetBkColor (new_img_dc, foreground);
2650 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2651 0, 0, SRCCOPY);
2653 SelectObject (old_img_dc, old_prev);
2654 SelectObject (new_img_dc, new_prev);
2655 DeleteDC (old_img_dc);
2656 DeleteDC (new_img_dc);
2657 DeleteObject (img->pixmap);
2658 if (new_pixmap == 0)
2659 fprintf (stderr, "Failed to convert image to color.\n");
2660 else
2661 img->pixmap = new_pixmap;
2664 #define XBM_BIT_SHUFFLE(b) (~(b))
2666 #else
2668 #define XBM_BIT_SHUFFLE(b) (b)
2670 #endif /* HAVE_NTGUI */
2673 static void
2674 Create_Pixmap_From_Bitmap_Data (f, img, data, fg, bg, non_default_colors)
2675 struct frame *f;
2676 struct image *img;
2677 char *data;
2678 RGB_PIXEL_COLOR fg, bg;
2679 int non_default_colors;
2681 #ifdef HAVE_NTGUI
2682 img->pixmap
2683 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2685 /* If colors were specified, transfer the bitmap to a color one. */
2686 if (non_default_colors)
2687 convert_mono_to_color_image (f, img, fg, bg);
2689 #elif defined (HAVE_NS)
2690 img->pixmap = ns_image_from_XBM(data, img->width, img->height);
2692 #else
2693 img->pixmap
2694 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2695 FRAME_X_WINDOW (f),
2696 data,
2697 img->width, img->height,
2698 fg, bg,
2699 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2700 #endif /* !HAVE_NTGUI && !HAVE_NS */
2705 /* Replacement for XReadBitmapFileData which isn't available under old
2706 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2707 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2708 the image. Return in *DATA the bitmap data allocated with xmalloc.
2709 Value is non-zero if successful. DATA null means just test if
2710 CONTENTS looks like an in-memory XBM file. If INHIBIT_IMAGE_ERROR
2711 is non-zero, inhibit the call to image_error when the image size is
2712 invalid (the bitmap remains unread). */
2714 static int
2715 xbm_read_bitmap_data (f, contents, end, width, height, data, inhibit_image_error)
2716 struct frame *f;
2717 unsigned char *contents, *end;
2718 int *width, *height;
2719 unsigned char **data;
2720 int inhibit_image_error;
2722 unsigned char *s = contents;
2723 char buffer[BUFSIZ];
2724 int padding_p = 0;
2725 int v10 = 0;
2726 int bytes_per_line, i, nbytes;
2727 unsigned char *p;
2728 int value;
2729 int LA1;
2731 #define match() \
2732 LA1 = xbm_scan (&s, end, buffer, &value)
2734 #define expect(TOKEN) \
2735 if (LA1 != (TOKEN)) \
2736 goto failure; \
2737 else \
2738 match ()
2740 #define expect_ident(IDENT) \
2741 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2742 match (); \
2743 else \
2744 goto failure
2746 *width = *height = -1;
2747 if (data)
2748 *data = NULL;
2749 LA1 = xbm_scan (&s, end, buffer, &value);
2751 /* Parse defines for width, height and hot-spots. */
2752 while (LA1 == '#')
2754 match ();
2755 expect_ident ("define");
2756 expect (XBM_TK_IDENT);
2758 if (LA1 == XBM_TK_NUMBER)
2760 char *p = strrchr (buffer, '_');
2761 p = p ? p + 1 : buffer;
2762 if (strcmp (p, "width") == 0)
2763 *width = value;
2764 else if (strcmp (p, "height") == 0)
2765 *height = value;
2767 expect (XBM_TK_NUMBER);
2770 if (!check_image_size (f, *width, *height))
2772 if (!inhibit_image_error)
2773 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
2774 goto failure;
2776 else if (data == NULL)
2777 goto success;
2779 /* Parse bits. Must start with `static'. */
2780 expect_ident ("static");
2781 if (LA1 == XBM_TK_IDENT)
2783 if (strcmp (buffer, "unsigned") == 0)
2785 match ();
2786 expect_ident ("char");
2788 else if (strcmp (buffer, "short") == 0)
2790 match ();
2791 v10 = 1;
2792 if (*width % 16 && *width % 16 < 9)
2793 padding_p = 1;
2795 else if (strcmp (buffer, "char") == 0)
2796 match ();
2797 else
2798 goto failure;
2800 else
2801 goto failure;
2803 expect (XBM_TK_IDENT);
2804 expect ('[');
2805 expect (']');
2806 expect ('=');
2807 expect ('{');
2809 bytes_per_line = (*width + 7) / 8 + padding_p;
2810 nbytes = bytes_per_line * *height;
2811 p = *data = (unsigned char *) xmalloc (nbytes);
2813 if (v10)
2815 for (i = 0; i < nbytes; i += 2)
2817 int val = value;
2818 expect (XBM_TK_NUMBER);
2820 *p++ = XBM_BIT_SHUFFLE (val);
2821 if (!padding_p || ((i + 2) % bytes_per_line))
2822 *p++ = XBM_BIT_SHUFFLE (value >> 8);
2824 if (LA1 == ',' || LA1 == '}')
2825 match ();
2826 else
2827 goto failure;
2830 else
2832 for (i = 0; i < nbytes; ++i)
2834 int val = value;
2835 expect (XBM_TK_NUMBER);
2837 *p++ = XBM_BIT_SHUFFLE (val);
2839 if (LA1 == ',' || LA1 == '}')
2840 match ();
2841 else
2842 goto failure;
2846 success:
2847 return 1;
2849 failure:
2851 if (data && *data)
2853 xfree (*data);
2854 *data = NULL;
2856 return 0;
2858 #undef match
2859 #undef expect
2860 #undef expect_ident
2864 /* Load XBM image IMG which will be displayed on frame F from buffer
2865 CONTENTS. END is the end of the buffer. Value is non-zero if
2866 successful. */
2868 static int
2869 xbm_load_image (f, img, contents, end)
2870 struct frame *f;
2871 struct image *img;
2872 unsigned char *contents, *end;
2874 int rc;
2875 unsigned char *data;
2876 int success_p = 0;
2878 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height,
2879 &data, 0);
2880 if (rc)
2882 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2883 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2884 int non_default_colors = 0;
2885 Lisp_Object value;
2887 xassert (img->width > 0 && img->height > 0);
2889 /* Get foreground and background colors, maybe allocate colors. */
2890 value = image_spec_value (img->spec, QCforeground, NULL);
2891 if (!NILP (value))
2893 foreground = x_alloc_image_color (f, img, value, foreground);
2894 non_default_colors = 1;
2896 value = image_spec_value (img->spec, QCbackground, NULL);
2897 if (!NILP (value))
2899 background = x_alloc_image_color (f, img, value, background);
2900 img->background = background;
2901 img->background_valid = 1;
2902 non_default_colors = 1;
2905 Create_Pixmap_From_Bitmap_Data (f, img, data,
2906 foreground, background,
2907 non_default_colors);
2908 xfree (data);
2910 if (img->pixmap == NO_PIXMAP)
2912 x_clear_image (f, img);
2913 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
2915 else
2916 success_p = 1;
2918 else
2919 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2921 return success_p;
2925 /* Value is non-zero if DATA looks like an in-memory XBM file. */
2927 static int
2928 xbm_file_p (data)
2929 Lisp_Object data;
2931 int w, h;
2932 return (STRINGP (data)
2933 && xbm_read_bitmap_data (NULL, SDATA (data),
2934 (SDATA (data) + SBYTES (data)),
2935 &w, &h, NULL, 1));
2939 /* Fill image IMG which is used on frame F with pixmap data. Value is
2940 non-zero if successful. */
2942 static int
2943 xbm_load (f, img)
2944 struct frame *f;
2945 struct image *img;
2947 int success_p = 0;
2948 Lisp_Object file_name;
2950 xassert (xbm_image_p (img->spec));
2952 /* If IMG->spec specifies a file name, create a non-file spec from it. */
2953 file_name = image_spec_value (img->spec, QCfile, NULL);
2954 if (STRINGP (file_name))
2956 Lisp_Object file;
2957 unsigned char *contents;
2958 int size;
2959 struct gcpro gcpro1;
2961 file = x_find_image_file (file_name);
2962 GCPRO1 (file);
2963 if (!STRINGP (file))
2965 image_error ("Cannot find image file `%s'", file_name, Qnil);
2966 UNGCPRO;
2967 return 0;
2970 contents = slurp_file (SDATA (file), &size);
2971 if (contents == NULL)
2973 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
2974 UNGCPRO;
2975 return 0;
2978 success_p = xbm_load_image (f, img, contents, contents + size);
2979 UNGCPRO;
2981 else
2983 struct image_keyword fmt[XBM_LAST];
2984 Lisp_Object data;
2985 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
2986 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
2987 int non_default_colors = 0;
2988 char *bits;
2989 int parsed_p;
2990 int in_memory_file_p = 0;
2992 /* See if data looks like an in-memory XBM file. */
2993 data = image_spec_value (img->spec, QCdata, NULL);
2994 in_memory_file_p = xbm_file_p (data);
2996 /* Parse the image specification. */
2997 bcopy (xbm_format, fmt, sizeof fmt);
2998 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
2999 xassert (parsed_p);
3001 /* Get specified width, and height. */
3002 if (!in_memory_file_p)
3004 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3005 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3006 xassert (img->width > 0 && img->height > 0);
3009 /* Get foreground and background colors, maybe allocate colors. */
3010 if (fmt[XBM_FOREGROUND].count
3011 && STRINGP (fmt[XBM_FOREGROUND].value))
3013 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3014 foreground);
3015 non_default_colors = 1;
3018 if (fmt[XBM_BACKGROUND].count
3019 && STRINGP (fmt[XBM_BACKGROUND].value))
3021 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3022 background);
3023 non_default_colors = 1;
3026 if (in_memory_file_p)
3027 success_p = xbm_load_image (f, img, SDATA (data),
3028 (SDATA (data)
3029 + SBYTES (data)));
3030 else
3032 if (VECTORP (data))
3034 int i;
3035 char *p;
3036 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3038 p = bits = (char *) alloca (nbytes * img->height);
3039 for (i = 0; i < img->height; ++i, p += nbytes)
3041 Lisp_Object line = XVECTOR (data)->contents[i];
3042 if (STRINGP (line))
3043 bcopy (SDATA (line), p, nbytes);
3044 else
3045 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
3048 else if (STRINGP (data))
3049 bits = SDATA (data);
3050 else
3051 bits = XBOOL_VECTOR (data)->data;
3053 #ifdef WINDOWSNT
3055 char *invertedBits;
3056 int nbytes, i;
3057 /* Windows mono bitmaps are reversed compared with X. */
3058 invertedBits = bits;
3059 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
3060 * img->height;
3061 bits = (char *) alloca(nbytes);
3062 for (i = 0; i < nbytes; i++)
3063 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3065 #endif
3066 /* Create the pixmap. */
3068 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3069 foreground, background,
3070 non_default_colors);
3071 if (img->pixmap)
3072 success_p = 1;
3073 else
3075 image_error ("Unable to create pixmap for XBM image `%s'",
3076 img->spec, Qnil);
3077 x_clear_image (f, img);
3082 return success_p;
3087 /***********************************************************************
3088 XPM images
3089 ***********************************************************************/
3091 #if defined (HAVE_XPM) || defined (HAVE_NS)
3093 static int xpm_image_p P_ ((Lisp_Object object));
3094 static int xpm_load P_ ((struct frame *f, struct image *img));
3095 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
3097 #endif /* HAVE_XPM || HAVE_NS */
3099 #ifdef HAVE_XPM
3100 #ifdef HAVE_NTGUI
3101 /* Indicate to xpm.h that we don't have Xlib. */
3102 #define FOR_MSW
3103 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3104 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3105 #define XColor xpm_XColor
3106 #define XImage xpm_XImage
3107 #define Display xpm_Display
3108 #define PIXEL_ALREADY_TYPEDEFED
3109 #include "X11/xpm.h"
3110 #undef FOR_MSW
3111 #undef XColor
3112 #undef XImage
3113 #undef Display
3114 #undef PIXEL_ALREADY_TYPEDEFED
3115 #else
3116 #include "X11/xpm.h"
3117 #endif /* HAVE_NTGUI */
3118 #endif /* HAVE_XPM */
3120 #if defined (HAVE_XPM) || defined (HAVE_NS)
3121 /* The symbol `xpm' identifying XPM-format images. */
3123 Lisp_Object Qxpm;
3125 /* Indices of image specification fields in xpm_format, below. */
3127 enum xpm_keyword_index
3129 XPM_TYPE,
3130 XPM_FILE,
3131 XPM_DATA,
3132 XPM_ASCENT,
3133 XPM_MARGIN,
3134 XPM_RELIEF,
3135 XPM_ALGORITHM,
3136 XPM_HEURISTIC_MASK,
3137 XPM_MASK,
3138 XPM_COLOR_SYMBOLS,
3139 XPM_BACKGROUND,
3140 XPM_LAST
3143 /* Vector of image_keyword structures describing the format
3144 of valid XPM image specifications. */
3146 static const struct image_keyword xpm_format[XPM_LAST] =
3148 {":type", IMAGE_SYMBOL_VALUE, 1},
3149 {":file", IMAGE_STRING_VALUE, 0},
3150 {":data", IMAGE_STRING_VALUE, 0},
3151 {":ascent", IMAGE_ASCENT_VALUE, 0},
3152 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3153 {":relief", IMAGE_INTEGER_VALUE, 0},
3154 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3155 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3156 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3157 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3158 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3161 /* Structure describing the image type XPM. */
3163 static struct image_type xpm_type =
3165 &Qxpm,
3166 xpm_image_p,
3167 xpm_load,
3168 x_clear_image,
3169 NULL
3172 #ifdef HAVE_X_WINDOWS
3174 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3175 functions for allocating image colors. Our own functions handle
3176 color allocation failures more gracefully than the ones on the XPM
3177 lib. */
3179 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3180 #define ALLOC_XPM_COLORS
3181 #endif
3182 #endif /* HAVE_X_WINDOWS */
3184 #ifdef ALLOC_XPM_COLORS
3186 static void xpm_init_color_cache P_ ((struct frame *, XpmAttributes *));
3187 static void xpm_free_color_cache P_ ((void));
3188 static int xpm_lookup_color P_ ((struct frame *, char *, XColor *));
3189 static int xpm_color_bucket P_ ((char *));
3190 static struct xpm_cached_color *xpm_cache_color P_ ((struct frame *, char *,
3191 XColor *, int));
3193 /* An entry in a hash table used to cache color definitions of named
3194 colors. This cache is necessary to speed up XPM image loading in
3195 case we do color allocations ourselves. Without it, we would need
3196 a call to XParseColor per pixel in the image. */
3198 struct xpm_cached_color
3200 /* Next in collision chain. */
3201 struct xpm_cached_color *next;
3203 /* Color definition (RGB and pixel color). */
3204 XColor color;
3206 /* Color name. */
3207 char name[1];
3210 /* The hash table used for the color cache, and its bucket vector
3211 size. */
3213 #define XPM_COLOR_CACHE_BUCKETS 1001
3214 struct xpm_cached_color **xpm_color_cache;
3216 /* Initialize the color cache. */
3218 static void
3219 xpm_init_color_cache (f, attrs)
3220 struct frame *f;
3221 XpmAttributes *attrs;
3223 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3224 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3225 memset (xpm_color_cache, 0, nbytes);
3226 init_color_table ();
3228 if (attrs->valuemask & XpmColorSymbols)
3230 int i;
3231 XColor color;
3233 for (i = 0; i < attrs->numsymbols; ++i)
3234 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3235 attrs->colorsymbols[i].value, &color))
3237 color.pixel = lookup_rgb_color (f, color.red, color.green,
3238 color.blue);
3239 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3244 /* Free the color cache. */
3246 static void
3247 xpm_free_color_cache ()
3249 struct xpm_cached_color *p, *next;
3250 int i;
3252 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3253 for (p = xpm_color_cache[i]; p; p = next)
3255 next = p->next;
3256 xfree (p);
3259 xfree (xpm_color_cache);
3260 xpm_color_cache = NULL;
3261 free_color_table ();
3264 /* Return the bucket index for color named COLOR_NAME in the color
3265 cache. */
3267 static int
3268 xpm_color_bucket (color_name)
3269 char *color_name;
3271 unsigned h = 0;
3272 char *s;
3274 for (s = color_name; *s; ++s)
3275 h = (h << 2) ^ *s;
3276 return h %= XPM_COLOR_CACHE_BUCKETS;
3280 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3281 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3282 entry added. */
3284 static struct xpm_cached_color *
3285 xpm_cache_color (f, color_name, color, bucket)
3286 struct frame *f;
3287 char *color_name;
3288 XColor *color;
3289 int bucket;
3291 size_t nbytes;
3292 struct xpm_cached_color *p;
3294 if (bucket < 0)
3295 bucket = xpm_color_bucket (color_name);
3297 nbytes = sizeof *p + strlen (color_name);
3298 p = (struct xpm_cached_color *) xmalloc (nbytes);
3299 strcpy (p->name, color_name);
3300 p->color = *color;
3301 p->next = xpm_color_cache[bucket];
3302 xpm_color_cache[bucket] = p;
3303 return p;
3306 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3307 return the cached definition in *COLOR. Otherwise, make a new
3308 entry in the cache and allocate the color. Value is zero if color
3309 allocation failed. */
3311 static int
3312 xpm_lookup_color (f, color_name, color)
3313 struct frame *f;
3314 char *color_name;
3315 XColor *color;
3317 struct xpm_cached_color *p;
3318 int h = xpm_color_bucket (color_name);
3320 for (p = xpm_color_cache[h]; p; p = p->next)
3321 if (strcmp (p->name, color_name) == 0)
3322 break;
3324 if (p != NULL)
3325 *color = p->color;
3326 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3327 color_name, color))
3329 color->pixel = lookup_rgb_color (f, color->red, color->green,
3330 color->blue);
3331 p = xpm_cache_color (f, color_name, color, h);
3333 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3334 with transparency, and it's useful. */
3335 else if (strcmp ("opaque", color_name) == 0)
3337 bzero (color, sizeof (XColor)); /* Is this necessary/correct? */
3338 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3339 p = xpm_cache_color (f, color_name, color, h);
3342 return p != NULL;
3346 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3347 CLOSURE is a pointer to the frame on which we allocate the
3348 color. Return in *COLOR the allocated color. Value is non-zero
3349 if successful. */
3351 static int
3352 xpm_alloc_color (dpy, cmap, color_name, color, closure)
3353 Display *dpy;
3354 Colormap cmap;
3355 char *color_name;
3356 XColor *color;
3357 void *closure;
3359 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3363 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3364 is a pointer to the frame on which we allocate the color. Value is
3365 non-zero if successful. */
3367 static int
3368 xpm_free_colors (dpy, cmap, pixels, npixels, closure)
3369 Display *dpy;
3370 Colormap cmap;
3371 Pixel *pixels;
3372 int npixels;
3373 void *closure;
3375 return 1;
3378 #endif /* ALLOC_XPM_COLORS */
3381 #ifdef HAVE_NTGUI
3383 /* XPM library details. */
3385 DEF_IMGLIB_FN (XpmFreeAttributes);
3386 DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
3387 DEF_IMGLIB_FN (XpmReadFileToImage);
3388 DEF_IMGLIB_FN (XImageFree);
3390 static int
3391 init_xpm_functions (Lisp_Object libraries)
3393 HMODULE library;
3395 if (!(library = w32_delayed_load (libraries, Qxpm)))
3396 return 0;
3398 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3399 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3400 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3401 LOAD_IMGLIB_FN (library, XImageFree);
3402 return 1;
3405 #endif /* HAVE_NTGUI */
3408 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3409 for XPM images. Such a list must consist of conses whose car and
3410 cdr are strings. */
3412 static int
3413 xpm_valid_color_symbols_p (color_symbols)
3414 Lisp_Object color_symbols;
3416 while (CONSP (color_symbols))
3418 Lisp_Object sym = XCAR (color_symbols);
3419 if (!CONSP (sym)
3420 || !STRINGP (XCAR (sym))
3421 || !STRINGP (XCDR (sym)))
3422 break;
3423 color_symbols = XCDR (color_symbols);
3426 return NILP (color_symbols);
3430 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3432 static int
3433 xpm_image_p (object)
3434 Lisp_Object object;
3436 struct image_keyword fmt[XPM_LAST];
3437 bcopy (xpm_format, fmt, sizeof fmt);
3438 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3439 /* Either `:file' or `:data' must be present. */
3440 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3441 /* Either no `:color-symbols' or it's a list of conses
3442 whose car and cdr are strings. */
3443 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3444 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3447 #endif /* HAVE_XPM || HAVE_NS */
3449 #if defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
3451 x_create_bitmap_from_xpm_data (f, bits)
3452 struct frame *f;
3453 char **bits;
3455 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3456 int id, rc;
3457 XpmAttributes attrs;
3458 Pixmap bitmap, mask;
3460 bzero (&attrs, sizeof attrs);
3462 attrs.visual = FRAME_X_VISUAL (f);
3463 attrs.colormap = FRAME_X_COLORMAP (f);
3464 attrs.valuemask |= XpmVisual;
3465 attrs.valuemask |= XpmColormap;
3467 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3468 bits, &bitmap, &mask, &attrs);
3469 if (rc != XpmSuccess)
3471 XpmFreeAttributes (&attrs);
3472 return -1;
3475 id = x_allocate_bitmap_record (f);
3476 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
3477 dpyinfo->bitmaps[id - 1].have_mask = 1;
3478 dpyinfo->bitmaps[id - 1].mask = mask;
3479 dpyinfo->bitmaps[id - 1].file = NULL;
3480 dpyinfo->bitmaps[id - 1].height = attrs.height;
3481 dpyinfo->bitmaps[id - 1].width = attrs.width;
3482 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
3483 dpyinfo->bitmaps[id - 1].refcount = 1;
3485 XpmFreeAttributes (&attrs);
3486 return id;
3488 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
3490 /* Load image IMG which will be displayed on frame F. Value is
3491 non-zero if successful. */
3493 #ifdef HAVE_XPM
3495 static int
3496 xpm_load (f, img)
3497 struct frame *f;
3498 struct image *img;
3500 int rc;
3501 XpmAttributes attrs;
3502 Lisp_Object specified_file, color_symbols;
3503 #ifdef HAVE_NTGUI
3504 HDC hdc;
3505 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3506 #endif /* HAVE_NTGUI */
3508 /* Configure the XPM lib. Use the visual of frame F. Allocate
3509 close colors. Return colors allocated. */
3510 bzero (&attrs, sizeof attrs);
3512 #ifndef HAVE_NTGUI
3513 attrs.visual = FRAME_X_VISUAL (f);
3514 attrs.colormap = FRAME_X_COLORMAP (f);
3515 attrs.valuemask |= XpmVisual;
3516 attrs.valuemask |= XpmColormap;
3517 #endif /* HAVE_NTGUI */
3519 #ifdef ALLOC_XPM_COLORS
3520 /* Allocate colors with our own functions which handle
3521 failing color allocation more gracefully. */
3522 attrs.color_closure = f;
3523 attrs.alloc_color = xpm_alloc_color;
3524 attrs.free_colors = xpm_free_colors;
3525 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3526 #else /* not ALLOC_XPM_COLORS */
3527 /* Let the XPM lib allocate colors. */
3528 attrs.valuemask |= XpmReturnAllocPixels;
3529 #ifdef XpmAllocCloseColors
3530 attrs.alloc_close_colors = 1;
3531 attrs.valuemask |= XpmAllocCloseColors;
3532 #else /* not XpmAllocCloseColors */
3533 attrs.closeness = 600;
3534 attrs.valuemask |= XpmCloseness;
3535 #endif /* not XpmAllocCloseColors */
3536 #endif /* ALLOC_XPM_COLORS */
3538 /* If image specification contains symbolic color definitions, add
3539 these to `attrs'. */
3540 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3541 if (CONSP (color_symbols))
3543 Lisp_Object tail;
3544 XpmColorSymbol *xpm_syms;
3545 int i, size;
3547 attrs.valuemask |= XpmColorSymbols;
3549 /* Count number of symbols. */
3550 attrs.numsymbols = 0;
3551 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3552 ++attrs.numsymbols;
3554 /* Allocate an XpmColorSymbol array. */
3555 size = attrs.numsymbols * sizeof *xpm_syms;
3556 xpm_syms = (XpmColorSymbol *) alloca (size);
3557 bzero (xpm_syms, size);
3558 attrs.colorsymbols = xpm_syms;
3560 /* Fill the color symbol array. */
3561 for (tail = color_symbols, i = 0;
3562 CONSP (tail);
3563 ++i, tail = XCDR (tail))
3565 Lisp_Object name = XCAR (XCAR (tail));
3566 Lisp_Object color = XCDR (XCAR (tail));
3567 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3568 strcpy (xpm_syms[i].name, SDATA (name));
3569 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3570 strcpy (xpm_syms[i].value, SDATA (color));
3574 /* Create a pixmap for the image, either from a file, or from a
3575 string buffer containing data in the same format as an XPM file. */
3576 #ifdef ALLOC_XPM_COLORS
3577 xpm_init_color_cache (f, &attrs);
3578 #endif
3580 specified_file = image_spec_value (img->spec, QCfile, NULL);
3582 #ifdef HAVE_NTGUI
3584 HDC frame_dc = get_frame_dc (f);
3585 hdc = CreateCompatibleDC (frame_dc);
3586 release_frame_dc (f, frame_dc);
3588 #endif /* HAVE_NTGUI */
3590 if (STRINGP (specified_file))
3592 Lisp_Object file = x_find_image_file (specified_file);
3593 if (!STRINGP (file))
3595 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3596 return 0;
3599 #ifdef HAVE_NTGUI
3600 /* XpmReadFileToPixmap is not available in the Windows port of
3601 libxpm. But XpmReadFileToImage almost does what we want. */
3602 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3603 &xpm_image, &xpm_mask,
3604 &attrs);
3605 #else
3606 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3607 SDATA (file), &img->pixmap, &img->mask,
3608 &attrs);
3609 #endif /* HAVE_NTGUI */
3611 else
3613 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3614 #ifdef HAVE_NTGUI
3615 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3616 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3617 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3618 &xpm_image, &xpm_mask,
3619 &attrs);
3620 #else
3621 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3622 SDATA (buffer),
3623 &img->pixmap, &img->mask,
3624 &attrs);
3625 #endif /* HAVE_NTGUI */
3628 if (rc == XpmSuccess)
3630 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3631 img->colors = colors_in_color_table (&img->ncolors);
3632 #else /* not ALLOC_XPM_COLORS */
3633 int i;
3635 #ifdef HAVE_NTGUI
3636 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3637 plus some duplicate attributes. */
3638 if (xpm_image && xpm_image->bitmap)
3640 img->pixmap = xpm_image->bitmap;
3641 /* XImageFree in libXpm frees XImage struct without destroying
3642 the bitmap, which is what we want. */
3643 fn_XImageFree (xpm_image);
3645 if (xpm_mask && xpm_mask->bitmap)
3647 /* The mask appears to be inverted compared with what we expect.
3648 TODO: invert our expectations. See other places where we
3649 have to invert bits because our idea of masks is backwards. */
3650 HGDIOBJ old_obj;
3651 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3653 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3654 SelectObject (hdc, old_obj);
3656 img->mask = xpm_mask->bitmap;
3657 fn_XImageFree (xpm_mask);
3658 DeleteDC (hdc);
3661 DeleteDC (hdc);
3662 #endif /* HAVE_NTGUI */
3664 /* Remember allocated colors. */
3665 img->ncolors = attrs.nalloc_pixels;
3666 img->colors = (unsigned long *) xmalloc (img->ncolors
3667 * sizeof *img->colors);
3668 for (i = 0; i < attrs.nalloc_pixels; ++i)
3670 img->colors[i] = attrs.alloc_pixels[i];
3671 #ifdef DEBUG_X_COLORS
3672 register_color (img->colors[i]);
3673 #endif
3675 #endif /* not ALLOC_XPM_COLORS */
3677 img->width = attrs.width;
3678 img->height = attrs.height;
3679 xassert (img->width > 0 && img->height > 0);
3681 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3682 #ifdef HAVE_NTGUI
3683 fn_XpmFreeAttributes (&attrs);
3684 #else
3685 XpmFreeAttributes (&attrs);
3686 #endif /* HAVE_NTGUI */
3688 else
3690 #ifdef HAVE_NTGUI
3691 DeleteDC (hdc);
3692 #endif /* HAVE_NTGUI */
3694 switch (rc)
3696 case XpmOpenFailed:
3697 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3698 break;
3700 case XpmFileInvalid:
3701 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3702 break;
3704 case XpmNoMemory:
3705 image_error ("Out of memory (%s)", img->spec, Qnil);
3706 break;
3708 case XpmColorFailed:
3709 image_error ("Color allocation error (%s)", img->spec, Qnil);
3710 break;
3712 default:
3713 image_error ("Unknown error (%s)", img->spec, Qnil);
3714 break;
3718 #ifdef ALLOC_XPM_COLORS
3719 xpm_free_color_cache ();
3720 #endif
3721 return rc == XpmSuccess;
3724 #endif /* HAVE_XPM */
3726 #if defined (HAVE_NS) && !defined (HAVE_XPM)
3728 /* XPM support functions for NS where libxpm is not available.
3729 Only XPM version 3 (without any extensions) is supported. */
3731 static int xpm_scan P_ ((const unsigned char **, const unsigned char *,
3732 const unsigned char **, int *));
3733 static Lisp_Object xpm_make_color_table_v
3734 P_ ((void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3735 Lisp_Object (**) (Lisp_Object, const unsigned char *, int)));
3736 static void xpm_put_color_table_v P_ ((Lisp_Object, const unsigned char *,
3737 int, Lisp_Object));
3738 static Lisp_Object xpm_get_color_table_v P_ ((Lisp_Object,
3739 const unsigned char *, int));
3740 static Lisp_Object xpm_make_color_table_h
3741 P_ ((void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
3742 Lisp_Object (**) (Lisp_Object, const unsigned char *, int)));
3743 static void xpm_put_color_table_h P_ ((Lisp_Object, const unsigned char *,
3744 int, Lisp_Object));
3745 static Lisp_Object xpm_get_color_table_h P_ ((Lisp_Object,
3746 const unsigned char *, int));
3747 static int xpm_str_to_color_key P_ ((const char *));
3748 static int xpm_load_image P_ ((struct frame *, struct image *,
3749 const unsigned char *, const unsigned char *));
3751 /* Tokens returned from xpm_scan. */
3753 enum xpm_token
3755 XPM_TK_IDENT = 256,
3756 XPM_TK_STRING,
3757 XPM_TK_EOF
3760 /* Scan an XPM data and return a character (< 256) or a token defined
3761 by enum xpm_token above. *S and END are the start (inclusive) and
3762 the end (exclusive) addresses of the data, respectively. Advance
3763 *S while scanning. If token is either XPM_TK_IDENT or
3764 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3765 length of the corresponding token, respectively. */
3767 static int
3768 xpm_scan (s, end, beg, len)
3769 const unsigned char **s, *end, **beg;
3770 int *len;
3772 int c;
3774 while (*s < end)
3776 /* Skip white-space. */
3777 while (*s < end && (c = *(*s)++, isspace (c)))
3780 /* gnus-pointer.xpm uses '-' in its identifier.
3781 sb-dir-plus.xpm uses '+' in its identifier. */
3782 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3784 *beg = *s - 1;
3785 while (*s < end
3786 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3787 ++*s;
3788 *len = *s - *beg;
3789 return XPM_TK_IDENT;
3791 else if (c == '"')
3793 *beg = *s;
3794 while (*s < end && **s != '"')
3795 ++*s;
3796 *len = *s - *beg;
3797 if (*s < end)
3798 ++*s;
3799 return XPM_TK_STRING;
3801 else if (c == '/')
3803 if (*s < end && **s == '*')
3805 /* C-style comment. */
3806 ++*s;
3809 while (*s < end && *(*s)++ != '*')
3812 while (*s < end && **s != '/');
3813 if (*s < end)
3814 ++*s;
3816 else
3817 return c;
3819 else
3820 return c;
3823 return XPM_TK_EOF;
3826 /* Functions for color table lookup in XPM data. A key is a string
3827 specifying the color of each pixel in XPM data. A value is either
3828 an integer that specifies a pixel color, Qt that specifies
3829 transparency, or Qnil for the unspecified color. If the length of
3830 the key string is one, a vector is used as a table. Otherwise, a
3831 hash table is used. */
3833 static Lisp_Object
3834 xpm_make_color_table_v (put_func, get_func)
3835 void (**put_func) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3836 Lisp_Object (**get_func) (Lisp_Object, const unsigned char *, int);
3838 *put_func = xpm_put_color_table_v;
3839 *get_func = xpm_get_color_table_v;
3840 return Fmake_vector (make_number (256), Qnil);
3843 static void
3844 xpm_put_color_table_v (color_table, chars_start, chars_len, color)
3845 Lisp_Object color_table;
3846 const unsigned char *chars_start;
3847 int chars_len;
3848 Lisp_Object color;
3850 XVECTOR (color_table)->contents[*chars_start] = color;
3853 static Lisp_Object
3854 xpm_get_color_table_v (color_table, chars_start, chars_len)
3855 Lisp_Object color_table;
3856 const unsigned char *chars_start;
3857 int chars_len;
3859 return XVECTOR (color_table)->contents[*chars_start];
3862 static Lisp_Object
3863 xpm_make_color_table_h (put_func, get_func)
3864 void (**put_func) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3865 Lisp_Object (**get_func) (Lisp_Object, const unsigned char *, int);
3867 *put_func = xpm_put_color_table_h;
3868 *get_func = xpm_get_color_table_h;
3869 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
3870 make_float (DEFAULT_REHASH_SIZE),
3871 make_float (DEFAULT_REHASH_THRESHOLD),
3872 Qnil, Qnil, Qnil);
3875 static void
3876 xpm_put_color_table_h (color_table, chars_start, chars_len, color)
3877 Lisp_Object color_table;
3878 const unsigned char *chars_start;
3879 int chars_len;
3880 Lisp_Object color;
3882 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3883 unsigned hash_code;
3884 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
3886 hash_lookup (table, chars, &hash_code);
3887 hash_put (table, chars, color, hash_code);
3890 static Lisp_Object
3891 xpm_get_color_table_h (color_table, chars_start, chars_len)
3892 Lisp_Object color_table;
3893 const unsigned char *chars_start;
3894 int chars_len;
3896 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3897 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
3898 NULL);
3900 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3903 enum xpm_color_key {
3904 XPM_COLOR_KEY_S,
3905 XPM_COLOR_KEY_M,
3906 XPM_COLOR_KEY_G4,
3907 XPM_COLOR_KEY_G,
3908 XPM_COLOR_KEY_C
3911 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
3913 static int
3914 xpm_str_to_color_key (s)
3915 const char *s;
3917 int i;
3919 for (i = 0;
3920 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
3921 i++)
3922 if (strcmp (xpm_color_key_strings[i], s) == 0)
3923 return i;
3924 return -1;
3927 static int
3928 xpm_load_image (f, img, contents, end)
3929 struct frame *f;
3930 struct image *img;
3931 const unsigned char *contents, *end;
3933 const unsigned char *s = contents, *beg, *str;
3934 unsigned char buffer[BUFSIZ];
3935 int width, height, x, y;
3936 int num_colors, chars_per_pixel;
3937 int len, LA1;
3938 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
3939 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
3940 Lisp_Object frame, color_symbols, color_table;
3941 int best_key, have_mask = 0;
3942 XImagePtr ximg = NULL, mask_img = NULL;
3944 #define match() \
3945 LA1 = xpm_scan (&s, end, &beg, &len)
3947 #define expect(TOKEN) \
3948 if (LA1 != (TOKEN)) \
3949 goto failure; \
3950 else \
3951 match ()
3953 #define expect_ident(IDENT) \
3954 if (LA1 == XPM_TK_IDENT \
3955 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
3956 match (); \
3957 else \
3958 goto failure
3960 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
3961 goto failure;
3962 s += 9;
3963 match();
3964 expect_ident ("static");
3965 expect_ident ("char");
3966 expect ('*');
3967 expect (XPM_TK_IDENT);
3968 expect ('[');
3969 expect (']');
3970 expect ('=');
3971 expect ('{');
3972 expect (XPM_TK_STRING);
3973 if (len >= BUFSIZ)
3974 goto failure;
3975 memcpy (buffer, beg, len);
3976 buffer[len] = '\0';
3977 if (sscanf (buffer, "%d %d %d %d", &width, &height,
3978 &num_colors, &chars_per_pixel) != 4
3979 || width <= 0 || height <= 0
3980 || num_colors <= 0 || chars_per_pixel <= 0)
3981 goto failure;
3983 if (!check_image_size (f, width, height))
3985 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
3986 goto failure;
3989 expect (',');
3991 XSETFRAME (frame, f);
3992 if (!NILP (Fxw_display_color_p (frame)))
3993 best_key = XPM_COLOR_KEY_C;
3994 else if (!NILP (Fx_display_grayscale_p (frame)))
3995 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
3996 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
3997 else
3998 best_key = XPM_COLOR_KEY_M;
4000 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4001 if (chars_per_pixel == 1)
4002 color_table = xpm_make_color_table_v (&put_color_table,
4003 &get_color_table);
4004 else
4005 color_table = xpm_make_color_table_h (&put_color_table,
4006 &get_color_table);
4008 while (num_colors-- > 0)
4010 unsigned char *color, *max_color;
4011 int key, next_key, max_key = 0;
4012 Lisp_Object symbol_color = Qnil, color_val;
4013 XColor cdef;
4015 expect (XPM_TK_STRING);
4016 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4017 goto failure;
4018 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4019 buffer[len - chars_per_pixel] = '\0';
4021 str = strtok (buffer, " \t");
4022 if (str == NULL)
4023 goto failure;
4024 key = xpm_str_to_color_key (str);
4025 if (key < 0)
4026 goto failure;
4029 color = strtok (NULL, " \t");
4030 if (color == NULL)
4031 goto failure;
4033 while ((str = strtok (NULL, " \t")) != NULL)
4035 next_key = xpm_str_to_color_key (str);
4036 if (next_key >= 0)
4037 break;
4038 color[strlen (color)] = ' ';
4041 if (key == XPM_COLOR_KEY_S)
4043 if (NILP (symbol_color))
4044 symbol_color = build_string (color);
4046 else if (max_key < key && key <= best_key)
4048 max_key = key;
4049 max_color = color;
4051 key = next_key;
4053 while (str);
4055 color_val = Qnil;
4056 if (!NILP (color_symbols) && !NILP (symbol_color))
4058 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4060 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4062 if (xstrcasecmp (SDATA (XCDR (specified_color)), "None") == 0)
4063 color_val = Qt;
4064 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
4065 &cdef, 0))
4066 color_val = make_number (cdef.pixel);
4069 if (NILP (color_val) && max_key > 0)
4071 if (xstrcasecmp (max_color, "None") == 0)
4072 color_val = Qt;
4073 else if (x_defined_color (f, max_color, &cdef, 0))
4074 color_val = make_number (cdef.pixel);
4076 if (!NILP (color_val))
4077 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4079 expect (',');
4082 if (!x_create_x_image_and_pixmap (f, width, height, 0,
4083 &ximg, &img->pixmap)
4084 #ifndef HAVE_NS
4085 || !x_create_x_image_and_pixmap (f, width, height, 1,
4086 &mask_img, &img->mask)
4087 #endif
4090 image_error ("Out of memory (%s)", img->spec, Qnil);
4091 goto error;
4094 for (y = 0; y < height; y++)
4096 expect (XPM_TK_STRING);
4097 str = beg;
4098 if (len < width * chars_per_pixel)
4099 goto failure;
4100 for (x = 0; x < width; x++, str += chars_per_pixel)
4102 Lisp_Object color_val =
4103 (*get_color_table) (color_table, str, chars_per_pixel);
4105 XPutPixel (ximg, x, y,
4106 (INTEGERP (color_val) ? XINT (color_val)
4107 : FRAME_FOREGROUND_PIXEL (f)));
4108 #ifndef HAVE_NS
4109 XPutPixel (mask_img, x, y,
4110 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4111 : (have_mask = 1, PIX_MASK_RETAIN)));
4112 #else
4113 if (EQ(color_val, Qt))
4114 ns_set_alpha(ximg, x, y, 0);
4115 #endif
4117 if (y + 1 < height)
4118 expect (',');
4121 img->width = width;
4122 img->height = height;
4124 /* Maybe fill in the background field while we have ximg handy. */
4125 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4126 IMAGE_BACKGROUND (img, f, ximg);
4128 x_put_x_image (f, ximg, img->pixmap, width, height);
4129 x_destroy_x_image (ximg);
4130 #ifndef HAVE_NS
4131 if (have_mask)
4133 /* Fill in the background_transparent field while we have the
4134 mask handy. */
4135 image_background_transparent (img, f, mask_img);
4137 x_put_x_image (f, mask_img, img->mask, width, height);
4138 x_destroy_x_image (mask_img);
4140 else
4142 x_destroy_x_image (mask_img);
4143 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4144 img->mask = NO_PIXMAP;
4146 #endif
4147 return 1;
4149 failure:
4150 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4151 error:
4152 x_destroy_x_image (ximg);
4153 x_destroy_x_image (mask_img);
4154 x_clear_image (f, img);
4155 return 0;
4157 #undef match
4158 #undef expect
4159 #undef expect_ident
4162 static int
4163 xpm_load (f, img)
4164 struct frame *f;
4165 struct image *img;
4167 int success_p = 0;
4168 Lisp_Object file_name;
4170 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4171 file_name = image_spec_value (img->spec, QCfile, NULL);
4172 if (STRINGP (file_name))
4174 Lisp_Object file;
4175 unsigned char *contents;
4176 int size;
4177 struct gcpro gcpro1;
4179 file = x_find_image_file (file_name);
4180 GCPRO1 (file);
4181 if (!STRINGP (file))
4183 image_error ("Cannot find image file `%s'", file_name, Qnil);
4184 UNGCPRO;
4185 return 0;
4188 contents = slurp_file (SDATA (file), &size);
4189 if (contents == NULL)
4191 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4192 UNGCPRO;
4193 return 0;
4196 success_p = xpm_load_image (f, img, contents, contents + size);
4197 xfree (contents);
4198 UNGCPRO;
4200 else
4202 Lisp_Object data;
4204 data = image_spec_value (img->spec, QCdata, NULL);
4205 success_p = xpm_load_image (f, img, SDATA (data),
4206 SDATA (data) + SBYTES (data));
4209 return success_p;
4212 #endif /* HAVE_NS && !HAVE_XPM */
4216 /***********************************************************************
4217 Color table
4218 ***********************************************************************/
4220 #ifdef COLOR_TABLE_SUPPORT
4222 /* An entry in the color table mapping an RGB color to a pixel color. */
4224 struct ct_color
4226 int r, g, b;
4227 unsigned long pixel;
4229 /* Next in color table collision list. */
4230 struct ct_color *next;
4233 /* The bucket vector size to use. Must be prime. */
4235 #define CT_SIZE 101
4237 /* Value is a hash of the RGB color given by R, G, and B. */
4239 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4241 /* The color hash table. */
4243 struct ct_color **ct_table;
4245 /* Number of entries in the color table. */
4247 int ct_colors_allocated;
4249 /* Initialize the color table. */
4251 static void
4252 init_color_table ()
4254 int size = CT_SIZE * sizeof (*ct_table);
4255 ct_table = (struct ct_color **) xmalloc (size);
4256 bzero (ct_table, size);
4257 ct_colors_allocated = 0;
4261 /* Free memory associated with the color table. */
4263 static void
4264 free_color_table ()
4266 int i;
4267 struct ct_color *p, *next;
4269 for (i = 0; i < CT_SIZE; ++i)
4270 for (p = ct_table[i]; p; p = next)
4272 next = p->next;
4273 xfree (p);
4276 xfree (ct_table);
4277 ct_table = NULL;
4281 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4282 entry for that color already is in the color table, return the
4283 pixel color of that entry. Otherwise, allocate a new color for R,
4284 G, B, and make an entry in the color table. */
4286 static unsigned long
4287 lookup_rgb_color (f, r, g, b)
4288 struct frame *f;
4289 int r, g, b;
4291 unsigned hash = CT_HASH_RGB (r, g, b);
4292 int i = hash % CT_SIZE;
4293 struct ct_color *p;
4294 Display_Info *dpyinfo;
4296 /* Handle TrueColor visuals specially, which improves performance by
4297 two orders of magnitude. Freeing colors on TrueColor visuals is
4298 a nop, and pixel colors specify RGB values directly. See also
4299 the Xlib spec, chapter 3.1. */
4300 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4301 if (dpyinfo->red_bits > 0)
4303 unsigned long pr, pg, pb;
4305 /* Apply gamma-correction like normal color allocation does. */
4306 if (f->gamma)
4308 XColor color;
4309 color.red = r, color.green = g, color.blue = b;
4310 gamma_correct (f, &color);
4311 r = color.red, g = color.green, b = color.blue;
4314 /* Scale down RGB values to the visual's bits per RGB, and shift
4315 them to the right position in the pixel color. Note that the
4316 original RGB values are 16-bit values, as usual in X. */
4317 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4318 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4319 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4321 /* Assemble the pixel color. */
4322 return pr | pg | pb;
4325 for (p = ct_table[i]; p; p = p->next)
4326 if (p->r == r && p->g == g && p->b == b)
4327 break;
4329 if (p == NULL)
4332 #ifdef HAVE_X_WINDOWS
4333 XColor color;
4334 Colormap cmap;
4335 int rc;
4337 color.red = r;
4338 color.green = g;
4339 color.blue = b;
4341 cmap = FRAME_X_COLORMAP (f);
4342 rc = x_alloc_nearest_color (f, cmap, &color);
4343 if (rc)
4345 ++ct_colors_allocated;
4346 p = (struct ct_color *) xmalloc (sizeof *p);
4347 p->r = r;
4348 p->g = g;
4349 p->b = b;
4350 p->pixel = color.pixel;
4351 p->next = ct_table[i];
4352 ct_table[i] = p;
4354 else
4355 return FRAME_FOREGROUND_PIXEL (f);
4357 #else
4358 COLORREF color;
4359 #ifdef HAVE_NTGUI
4360 color = PALETTERGB (r, g, b);
4361 #else
4362 color = RGB_TO_ULONG (r, g, b);
4363 #endif /* HAVE_NTGUI */
4364 ++ct_colors_allocated;
4365 p = (struct ct_color *) xmalloc (sizeof *p);
4366 p->r = r;
4367 p->g = g;
4368 p->b = b;
4369 p->pixel = color;
4370 p->next = ct_table[i];
4371 ct_table[i] = p;
4372 #endif /* HAVE_X_WINDOWS */
4376 return p->pixel;
4380 /* Look up pixel color PIXEL which is used on frame F in the color
4381 table. If not already present, allocate it. Value is PIXEL. */
4383 static unsigned long
4384 lookup_pixel_color (f, pixel)
4385 struct frame *f;
4386 unsigned long pixel;
4388 int i = pixel % CT_SIZE;
4389 struct ct_color *p;
4391 for (p = ct_table[i]; p; p = p->next)
4392 if (p->pixel == pixel)
4393 break;
4395 if (p == NULL)
4397 XColor color;
4398 Colormap cmap;
4399 int rc;
4401 #ifdef HAVE_X_WINDOWS
4402 cmap = FRAME_X_COLORMAP (f);
4403 color.pixel = pixel;
4404 x_query_color (f, &color);
4405 rc = x_alloc_nearest_color (f, cmap, &color);
4406 #else
4407 BLOCK_INPUT;
4408 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4409 color.pixel = pixel;
4410 XQueryColor (NULL, cmap, &color);
4411 rc = x_alloc_nearest_color (f, cmap, &color);
4412 UNBLOCK_INPUT;
4413 #endif /* HAVE_X_WINDOWS */
4415 if (rc)
4417 ++ct_colors_allocated;
4419 p = (struct ct_color *) xmalloc (sizeof *p);
4420 p->r = color.red;
4421 p->g = color.green;
4422 p->b = color.blue;
4423 p->pixel = pixel;
4424 p->next = ct_table[i];
4425 ct_table[i] = p;
4427 else
4428 return FRAME_FOREGROUND_PIXEL (f);
4430 return p->pixel;
4434 /* Value is a vector of all pixel colors contained in the color table,
4435 allocated via xmalloc. Set *N to the number of colors. */
4437 static unsigned long *
4438 colors_in_color_table (n)
4439 int *n;
4441 int i, j;
4442 struct ct_color *p;
4443 unsigned long *colors;
4445 if (ct_colors_allocated == 0)
4447 *n = 0;
4448 colors = NULL;
4450 else
4452 colors = (unsigned long *) xmalloc (ct_colors_allocated
4453 * sizeof *colors);
4454 *n = ct_colors_allocated;
4456 for (i = j = 0; i < CT_SIZE; ++i)
4457 for (p = ct_table[i]; p; p = p->next)
4458 colors[j++] = p->pixel;
4461 return colors;
4464 #else /* COLOR_TABLE_SUPPORT */
4466 static unsigned long
4467 lookup_rgb_color (f, r, g, b)
4468 struct frame *f;
4469 int r, g, b;
4471 unsigned long pixel;
4473 #ifdef HAVE_NTGUI
4474 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4475 #endif /* HAVE_NTGUI */
4477 #ifdef HAVE_NS
4478 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4479 #endif /* HAVE_NS */
4480 return pixel;
4483 static void
4484 init_color_table ()
4487 #endif /* COLOR_TABLE_SUPPORT */
4490 /***********************************************************************
4491 Algorithms
4492 ***********************************************************************/
4494 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
4495 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
4496 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
4498 #ifdef HAVE_NTGUI
4499 static void XPutPixel (XImagePtr , int, int, COLORREF);
4500 #endif /* HAVE_NTGUI */
4502 /* Non-zero means draw a cross on images having `:conversion
4503 disabled'. */
4505 int cross_disabled_images;
4507 /* Edge detection matrices for different edge-detection
4508 strategies. */
4510 static int emboss_matrix[9] = {
4511 /* x - 1 x x + 1 */
4512 2, -1, 0, /* y - 1 */
4513 -1, 0, 1, /* y */
4514 0, 1, -2 /* y + 1 */
4517 static int laplace_matrix[9] = {
4518 /* x - 1 x x + 1 */
4519 1, 0, 0, /* y - 1 */
4520 0, 0, 0, /* y */
4521 0, 0, -1 /* y + 1 */
4524 /* Value is the intensity of the color whose red/green/blue values
4525 are R, G, and B. */
4527 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4530 /* On frame F, return an array of XColor structures describing image
4531 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4532 non-zero means also fill the red/green/blue members of the XColor
4533 structures. Value is a pointer to the array of XColors structures,
4534 allocated with xmalloc; it must be freed by the caller. */
4536 static XColor *
4537 x_to_xcolors (f, img, rgb_p)
4538 struct frame *f;
4539 struct image *img;
4540 int rgb_p;
4542 int x, y;
4543 XColor *colors, *p;
4544 XImagePtr_or_DC ximg;
4545 #ifdef HAVE_NTGUI
4546 HDC hdc;
4547 HGDIOBJ prev;
4548 #endif /* HAVE_NTGUI */
4550 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4552 #ifndef HAVE_NTGUI
4553 /* Get the X image IMG->pixmap. */
4554 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4555 0, 0, img->width, img->height, ~0, ZPixmap);
4556 #else
4557 /* Load the image into a memory device context. */
4558 hdc = get_frame_dc (f);
4559 ximg = CreateCompatibleDC (hdc);
4560 release_frame_dc (f, hdc);
4561 prev = SelectObject (ximg, img->pixmap);
4562 #endif /* HAVE_NTGUI */
4564 /* Fill the `pixel' members of the XColor array. I wished there
4565 were an easy and portable way to circumvent XGetPixel. */
4566 p = colors;
4567 for (y = 0; y < img->height; ++y)
4569 XColor *row = p;
4571 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
4572 for (x = 0; x < img->width; ++x, ++p)
4573 p->pixel = GET_PIXEL (ximg, x, y);
4574 if (rgb_p)
4575 x_query_colors (f, row, img->width);
4577 #else
4579 for (x = 0; x < img->width; ++x, ++p)
4581 /* W32_TODO: palette support needed here? */
4582 p->pixel = GET_PIXEL (ximg, x, y);
4583 if (rgb_p)
4585 p->red = RED16_FROM_ULONG (p->pixel);
4586 p->green = GREEN16_FROM_ULONG (p->pixel);
4587 p->blue = BLUE16_FROM_ULONG (p->pixel);
4590 #endif /* HAVE_X_WINDOWS */
4593 Destroy_Image (ximg, prev);
4595 return colors;
4598 #ifdef HAVE_NTGUI
4600 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4601 created with CreateDIBSection, with the pointer to the bit values
4602 stored in ximg->data. */
4604 static void
4605 XPutPixel (ximg, x, y, color)
4606 XImagePtr ximg;
4607 int x, y;
4608 COLORREF color;
4610 int width = ximg->info.bmiHeader.biWidth;
4611 int height = ximg->info.bmiHeader.biHeight;
4612 unsigned char * pixel;
4614 /* True color images. */
4615 if (ximg->info.bmiHeader.biBitCount == 24)
4617 int rowbytes = width * 3;
4618 /* Ensure scanlines are aligned on 4 byte boundaries. */
4619 if (rowbytes % 4)
4620 rowbytes += 4 - (rowbytes % 4);
4622 pixel = ximg->data + y * rowbytes + x * 3;
4623 /* Windows bitmaps are in BGR order. */
4624 *pixel = GetBValue (color);
4625 *(pixel + 1) = GetGValue (color);
4626 *(pixel + 2) = GetRValue (color);
4628 /* Monochrome images. */
4629 else if (ximg->info.bmiHeader.biBitCount == 1)
4631 int rowbytes = width / 8;
4632 /* Ensure scanlines are aligned on 4 byte boundaries. */
4633 if (rowbytes % 4)
4634 rowbytes += 4 - (rowbytes % 4);
4635 pixel = ximg->data + y * rowbytes + x / 8;
4636 /* Filter out palette info. */
4637 if (color & 0x00ffffff)
4638 *pixel = *pixel | (1 << x % 8);
4639 else
4640 *pixel = *pixel & ~(1 << x % 8);
4642 else
4643 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4646 #endif /* HAVE_NTGUI */
4648 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4649 RGB members are set. F is the frame on which this all happens.
4650 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4652 static void
4653 x_from_xcolors (f, img, colors)
4654 struct frame *f;
4655 struct image *img;
4656 XColor *colors;
4658 int x, y;
4659 XImagePtr oimg = NULL;
4660 Pixmap pixmap;
4661 XColor *p;
4663 init_color_table ();
4665 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4666 &oimg, &pixmap);
4667 p = colors;
4668 for (y = 0; y < img->height; ++y)
4669 for (x = 0; x < img->width; ++x, ++p)
4671 unsigned long pixel;
4672 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4673 XPutPixel (oimg, x, y, pixel);
4676 xfree (colors);
4677 x_clear_image_1 (f, img, 1, 0, 1);
4679 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4680 x_destroy_x_image (oimg);
4681 img->pixmap = pixmap;
4682 #ifdef COLOR_TABLE_SUPPORT
4683 img->colors = colors_in_color_table (&img->ncolors);
4684 free_color_table ();
4685 #endif /* COLOR_TABLE_SUPPORT */
4689 /* On frame F, perform edge-detection on image IMG.
4691 MATRIX is a nine-element array specifying the transformation
4692 matrix. See emboss_matrix for an example.
4694 COLOR_ADJUST is a color adjustment added to each pixel of the
4695 outgoing image. */
4697 static void
4698 x_detect_edges (f, img, matrix, color_adjust)
4699 struct frame *f;
4700 struct image *img;
4701 int matrix[9], color_adjust;
4703 XColor *colors = x_to_xcolors (f, img, 1);
4704 XColor *new, *p;
4705 int x, y, i, sum;
4707 for (i = sum = 0; i < 9; ++i)
4708 sum += eabs (matrix[i]);
4710 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4712 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4714 for (y = 0; y < img->height; ++y)
4716 p = COLOR (new, 0, y);
4717 p->red = p->green = p->blue = 0xffff/2;
4718 p = COLOR (new, img->width - 1, y);
4719 p->red = p->green = p->blue = 0xffff/2;
4722 for (x = 1; x < img->width - 1; ++x)
4724 p = COLOR (new, x, 0);
4725 p->red = p->green = p->blue = 0xffff/2;
4726 p = COLOR (new, x, img->height - 1);
4727 p->red = p->green = p->blue = 0xffff/2;
4730 for (y = 1; y < img->height - 1; ++y)
4732 p = COLOR (new, 1, y);
4734 for (x = 1; x < img->width - 1; ++x, ++p)
4736 int r, g, b, y1, x1;
4738 r = g = b = i = 0;
4739 for (y1 = y - 1; y1 < y + 2; ++y1)
4740 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
4741 if (matrix[i])
4743 XColor *t = COLOR (colors, x1, y1);
4744 r += matrix[i] * t->red;
4745 g += matrix[i] * t->green;
4746 b += matrix[i] * t->blue;
4749 r = (r / sum + color_adjust) & 0xffff;
4750 g = (g / sum + color_adjust) & 0xffff;
4751 b = (b / sum + color_adjust) & 0xffff;
4752 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4756 xfree (colors);
4757 x_from_xcolors (f, img, new);
4759 #undef COLOR
4763 /* Perform the pre-defined `emboss' edge-detection on image IMG
4764 on frame F. */
4766 static void
4767 x_emboss (f, img)
4768 struct frame *f;
4769 struct image *img;
4771 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4775 /* Transform image IMG which is used on frame F with a Laplace
4776 edge-detection algorithm. The result is an image that can be used
4777 to draw disabled buttons, for example. */
4779 static void
4780 x_laplace (f, img)
4781 struct frame *f;
4782 struct image *img;
4784 x_detect_edges (f, img, laplace_matrix, 45000);
4788 /* Perform edge-detection on image IMG on frame F, with specified
4789 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4791 MATRIX must be either
4793 - a list of at least 9 numbers in row-major form
4794 - a vector of at least 9 numbers
4796 COLOR_ADJUST nil means use a default; otherwise it must be a
4797 number. */
4799 static void
4800 x_edge_detection (f, img, matrix, color_adjust)
4801 struct frame *f;
4802 struct image *img;
4803 Lisp_Object matrix, color_adjust;
4805 int i = 0;
4806 int trans[9];
4808 if (CONSP (matrix))
4810 for (i = 0;
4811 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4812 ++i, matrix = XCDR (matrix))
4813 trans[i] = XFLOATINT (XCAR (matrix));
4815 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4817 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4818 trans[i] = XFLOATINT (AREF (matrix, i));
4821 if (NILP (color_adjust))
4822 color_adjust = make_number (0xffff / 2);
4824 if (i == 9 && NUMBERP (color_adjust))
4825 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
4829 /* Transform image IMG on frame F so that it looks disabled. */
4831 static void
4832 x_disable_image (f, img)
4833 struct frame *f;
4834 struct image *img;
4836 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4837 #ifdef HAVE_NTGUI
4838 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4839 #else
4840 int n_planes = dpyinfo->n_planes;
4841 #endif /* HAVE_NTGUI */
4843 if (n_planes >= 2)
4845 /* Color (or grayscale). Convert to gray, and equalize. Just
4846 drawing such images with a stipple can look very odd, so
4847 we're using this method instead. */
4848 XColor *colors = x_to_xcolors (f, img, 1);
4849 XColor *p, *end;
4850 const int h = 15000;
4851 const int l = 30000;
4853 for (p = colors, end = colors + img->width * img->height;
4854 p < end;
4855 ++p)
4857 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
4858 int i2 = (0xffff - h - l) * i / 0xffff + l;
4859 p->red = p->green = p->blue = i2;
4862 x_from_xcolors (f, img, colors);
4865 /* Draw a cross over the disabled image, if we must or if we
4866 should. */
4867 if (n_planes < 2 || cross_disabled_images)
4869 #ifndef HAVE_NTGUI
4870 Display *dpy = FRAME_X_DISPLAY (f);
4871 GC gc;
4873 #ifndef HAVE_NS /* TODO: NS support, however this not needed for toolbars */
4875 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
4877 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
4878 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
4879 XDrawLine (dpy, img->pixmap, gc, 0, 0,
4880 img->width - 1, img->height - 1);
4881 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
4882 img->width - 1, 0);
4883 XFreeGC (dpy, gc);
4885 if (img->mask)
4887 gc = XCreateGC (dpy, img->mask, 0, NULL);
4888 XSetForeground (dpy, gc, MaskForeground (f));
4889 XDrawLine (dpy, img->mask, gc, 0, 0,
4890 img->width - 1, img->height - 1);
4891 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
4892 img->width - 1, 0);
4893 XFreeGC (dpy, gc);
4895 #endif /* !HAVE_NS */
4896 #else
4897 HDC hdc, bmpdc;
4898 HGDIOBJ prev;
4900 hdc = get_frame_dc (f);
4901 bmpdc = CreateCompatibleDC (hdc);
4902 release_frame_dc (f, hdc);
4904 prev = SelectObject (bmpdc, img->pixmap);
4906 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
4907 MoveToEx (bmpdc, 0, 0, NULL);
4908 LineTo (bmpdc, img->width - 1, img->height - 1);
4909 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4910 LineTo (bmpdc, img->width - 1, 0);
4912 if (img->mask)
4914 SelectObject (bmpdc, img->mask);
4915 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
4916 MoveToEx (bmpdc, 0, 0, NULL);
4917 LineTo (bmpdc, img->width - 1, img->height - 1);
4918 MoveToEx (bmpdc, 0, img->height - 1, NULL);
4919 LineTo (bmpdc, img->width - 1, 0);
4921 SelectObject (bmpdc, prev);
4922 DeleteDC (bmpdc);
4923 #endif /* HAVE_NTGUI */
4928 /* Build a mask for image IMG which is used on frame F. FILE is the
4929 name of an image file, for error messages. HOW determines how to
4930 determine the background color of IMG. If it is a list '(R G B)',
4931 with R, G, and B being integers >= 0, take that as the color of the
4932 background. Otherwise, determine the background color of IMG
4933 heuristically. Value is non-zero if successful. */
4935 static int
4936 x_build_heuristic_mask (f, img, how)
4937 struct frame *f;
4938 struct image *img;
4939 Lisp_Object how;
4941 XImagePtr_or_DC ximg;
4942 #ifndef HAVE_NTGUI
4943 XImagePtr mask_img;
4944 #else
4945 HDC frame_dc;
4946 HGDIOBJ prev;
4947 char *mask_img;
4948 int row_width;
4949 #endif /* HAVE_NTGUI */
4950 int x, y, rc, use_img_background;
4951 unsigned long bg = 0;
4953 if (img->mask)
4955 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4956 img->mask = NO_PIXMAP;
4957 img->background_transparent_valid = 0;
4960 #ifndef HAVE_NTGUI
4961 #ifndef HAVE_NS
4962 /* Create an image and pixmap serving as mask. */
4963 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
4964 &mask_img, &img->mask);
4965 if (!rc)
4966 return 0;
4967 #endif /* !HAVE_NS */
4969 /* Get the X image of IMG->pixmap. */
4970 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
4971 img->width, img->height,
4972 ~0, ZPixmap);
4973 #else
4974 /* Create the bit array serving as mask. */
4975 row_width = (img->width + 7) / 8;
4976 mask_img = xmalloc (row_width * img->height);
4977 bzero (mask_img, row_width * img->height);
4979 /* Create a memory device context for IMG->pixmap. */
4980 frame_dc = get_frame_dc (f);
4981 ximg = CreateCompatibleDC (frame_dc);
4982 release_frame_dc (f, frame_dc);
4983 prev = SelectObject (ximg, img->pixmap);
4984 #endif /* HAVE_NTGUI */
4986 /* Determine the background color of ximg. If HOW is `(R G B)'
4987 take that as color. Otherwise, use the image's background color. */
4988 use_img_background = 1;
4990 if (CONSP (how))
4992 int rgb[3], i;
4994 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
4996 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
4997 how = XCDR (how);
5000 if (i == 3 && NILP (how))
5002 char color_name[30];
5003 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
5004 bg = (
5005 #ifdef HAVE_NTGUI
5006 0x00ffffff & /* Filter out palette info. */
5007 #endif /* HAVE_NTGUI */
5008 x_alloc_image_color (f, img, build_string (color_name), 0));
5009 use_img_background = 0;
5013 if (use_img_background)
5014 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5016 /* Set all bits in mask_img to 1 whose color in ximg is different
5017 from the background color bg. */
5018 #ifndef HAVE_NTGUI
5019 for (y = 0; y < img->height; ++y)
5020 for (x = 0; x < img->width; ++x)
5021 #ifndef HAVE_NS
5022 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5023 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5024 #else
5025 if (XGetPixel (ximg, x, y) == bg)
5026 ns_set_alpha(ximg, x, y, 0);
5027 #endif /* HAVE_NS */
5028 #ifndef HAVE_NS
5029 /* Fill in the background_transparent field while we have the mask handy. */
5030 image_background_transparent (img, f, mask_img);
5032 /* Put mask_img into img->mask. */
5033 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5034 x_destroy_x_image (mask_img);
5035 #endif /* !HAVE_NS */
5036 #else
5037 for (y = 0; y < img->height; ++y)
5038 for (x = 0; x < img->width; ++x)
5040 COLORREF p = GetPixel (ximg, x, y);
5041 if (p != bg)
5042 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5045 /* Create the mask image. */
5046 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5047 mask_img);
5048 /* Fill in the background_transparent field while we have the mask handy. */
5049 SelectObject (ximg, img->mask);
5050 image_background_transparent (img, f, ximg);
5052 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5053 xfree (mask_img);
5054 #endif /* HAVE_NTGUI */
5056 Destroy_Image (ximg, prev);
5058 return 1;
5062 /***********************************************************************
5063 PBM (mono, gray, color)
5064 ***********************************************************************/
5066 static int pbm_image_p P_ ((Lisp_Object object));
5067 static int pbm_load P_ ((struct frame *f, struct image *img));
5068 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
5070 /* The symbol `pbm' identifying images of this type. */
5072 Lisp_Object Qpbm;
5074 /* Indices of image specification fields in gs_format, below. */
5076 enum pbm_keyword_index
5078 PBM_TYPE,
5079 PBM_FILE,
5080 PBM_DATA,
5081 PBM_ASCENT,
5082 PBM_MARGIN,
5083 PBM_RELIEF,
5084 PBM_ALGORITHM,
5085 PBM_HEURISTIC_MASK,
5086 PBM_MASK,
5087 PBM_FOREGROUND,
5088 PBM_BACKGROUND,
5089 PBM_LAST
5092 /* Vector of image_keyword structures describing the format
5093 of valid user-defined image specifications. */
5095 static const struct image_keyword pbm_format[PBM_LAST] =
5097 {":type", IMAGE_SYMBOL_VALUE, 1},
5098 {":file", IMAGE_STRING_VALUE, 0},
5099 {":data", IMAGE_STRING_VALUE, 0},
5100 {":ascent", IMAGE_ASCENT_VALUE, 0},
5101 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5102 {":relief", IMAGE_INTEGER_VALUE, 0},
5103 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5104 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5105 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5106 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5107 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5110 /* Structure describing the image type `pbm'. */
5112 static struct image_type pbm_type =
5114 &Qpbm,
5115 pbm_image_p,
5116 pbm_load,
5117 x_clear_image,
5118 NULL
5122 /* Return non-zero if OBJECT is a valid PBM image specification. */
5124 static int
5125 pbm_image_p (object)
5126 Lisp_Object object;
5128 struct image_keyword fmt[PBM_LAST];
5130 bcopy (pbm_format, fmt, sizeof fmt);
5132 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5133 return 0;
5135 /* Must specify either :data or :file. */
5136 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5140 /* Scan a decimal number from *S and return it. Advance *S while
5141 reading the number. END is the end of the string. Value is -1 at
5142 end of input. */
5144 static int
5145 pbm_scan_number (s, end)
5146 unsigned char **s, *end;
5148 int c = 0, val = -1;
5150 while (*s < end)
5152 /* Skip white-space. */
5153 while (*s < end && (c = *(*s)++, isspace (c)))
5156 if (c == '#')
5158 /* Skip comment to end of line. */
5159 while (*s < end && (c = *(*s)++, c != '\n'))
5162 else if (isdigit (c))
5164 /* Read decimal number. */
5165 val = c - '0';
5166 while (*s < end && (c = *(*s)++, isdigit (c)))
5167 val = 10 * val + c - '0';
5168 break;
5170 else
5171 break;
5174 return val;
5178 #ifdef HAVE_NTGUI
5179 #if 0 /* Unused. ++kfs */
5181 /* Read FILE into memory. Value is a pointer to a buffer allocated
5182 with xmalloc holding FILE's contents. Value is null if an error
5183 occurred. *SIZE is set to the size of the file. */
5185 static char *
5186 pbm_read_file (file, size)
5187 Lisp_Object file;
5188 int *size;
5190 FILE *fp = NULL;
5191 char *buf = NULL;
5192 struct stat st;
5194 if (stat (SDATA (file), &st) == 0
5195 && (fp = fopen (SDATA (file), "rb")) != NULL
5196 && (buf = (char *) xmalloc (st.st_size),
5197 fread (buf, 1, st.st_size, fp) == st.st_size))
5199 *size = st.st_size;
5200 fclose (fp);
5202 else
5204 if (fp)
5205 fclose (fp);
5206 if (buf)
5208 xfree (buf);
5209 buf = NULL;
5213 return buf;
5215 #endif
5216 #endif /* HAVE_NTGUI */
5218 /* Load PBM image IMG for use on frame F. */
5220 static int
5221 pbm_load (f, img)
5222 struct frame *f;
5223 struct image *img;
5225 int raw_p, x, y;
5226 int width, height, max_color_idx = 0;
5227 XImagePtr ximg;
5228 Lisp_Object file, specified_file;
5229 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5230 struct gcpro gcpro1;
5231 unsigned char *contents = NULL;
5232 unsigned char *end, *p;
5233 int size;
5235 specified_file = image_spec_value (img->spec, QCfile, NULL);
5236 file = Qnil;
5237 GCPRO1 (file);
5239 if (STRINGP (specified_file))
5241 file = x_find_image_file (specified_file);
5242 if (!STRINGP (file))
5244 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5245 UNGCPRO;
5246 return 0;
5249 contents = slurp_file (SDATA (file), &size);
5250 if (contents == NULL)
5252 image_error ("Error reading `%s'", file, Qnil);
5253 UNGCPRO;
5254 return 0;
5257 p = contents;
5258 end = contents + size;
5260 else
5262 Lisp_Object data;
5263 data = image_spec_value (img->spec, QCdata, NULL);
5264 p = SDATA (data);
5265 end = p + SBYTES (data);
5268 /* Check magic number. */
5269 if (end - p < 2 || *p++ != 'P')
5271 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5272 error:
5273 xfree (contents);
5274 UNGCPRO;
5275 return 0;
5278 switch (*p++)
5280 case '1':
5281 raw_p = 0, type = PBM_MONO;
5282 break;
5284 case '2':
5285 raw_p = 0, type = PBM_GRAY;
5286 break;
5288 case '3':
5289 raw_p = 0, type = PBM_COLOR;
5290 break;
5292 case '4':
5293 raw_p = 1, type = PBM_MONO;
5294 break;
5296 case '5':
5297 raw_p = 1, type = PBM_GRAY;
5298 break;
5300 case '6':
5301 raw_p = 1, type = PBM_COLOR;
5302 break;
5304 default:
5305 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5306 goto error;
5309 /* Read width, height, maximum color-component. Characters
5310 starting with `#' up to the end of a line are ignored. */
5311 width = pbm_scan_number (&p, end);
5312 height = pbm_scan_number (&p, end);
5314 if (type != PBM_MONO)
5316 max_color_idx = pbm_scan_number (&p, end);
5317 if (max_color_idx > 65535 || max_color_idx < 0)
5319 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
5320 goto error;
5324 if (!check_image_size (f, width, height))
5326 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5327 goto error;
5330 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5331 &ximg, &img->pixmap))
5332 goto error;
5334 /* Initialize the color hash table. */
5335 init_color_table ();
5337 if (type == PBM_MONO)
5339 int c = 0, g;
5340 struct image_keyword fmt[PBM_LAST];
5341 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5342 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5344 /* Parse the image specification. */
5345 bcopy (pbm_format, fmt, sizeof fmt);
5346 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5348 /* Get foreground and background colors, maybe allocate colors. */
5349 if (fmt[PBM_FOREGROUND].count
5350 && STRINGP (fmt[PBM_FOREGROUND].value))
5351 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5352 if (fmt[PBM_BACKGROUND].count
5353 && STRINGP (fmt[PBM_BACKGROUND].value))
5355 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5356 img->background = bg;
5357 img->background_valid = 1;
5360 for (y = 0; y < height; ++y)
5361 for (x = 0; x < width; ++x)
5363 if (raw_p)
5365 if ((x & 7) == 0)
5367 if (p >= end)
5369 x_destroy_x_image (ximg);
5370 x_clear_image (f, img);
5371 image_error ("Invalid image size in image `%s'",
5372 img->spec, Qnil);
5373 goto error;
5375 c = *p++;
5377 g = c & 0x80;
5378 c <<= 1;
5380 else
5381 g = pbm_scan_number (&p, end);
5383 XPutPixel (ximg, x, y, g ? fg : bg);
5386 else
5388 int expected_size = height * width;
5389 if (max_color_idx > 255)
5390 expected_size *= 2;
5391 if (type == PBM_COLOR)
5392 expected_size *= 3;
5394 if (raw_p && p + expected_size > end)
5396 x_destroy_x_image (ximg);
5397 x_clear_image (f, img);
5398 image_error ("Invalid image size in image `%s'",
5399 img->spec, Qnil);
5400 goto error;
5403 for (y = 0; y < height; ++y)
5404 for (x = 0; x < width; ++x)
5406 int r, g, b;
5408 if (type == PBM_GRAY && raw_p)
5410 r = g = b = *p++;
5411 if (max_color_idx > 255)
5412 r = g = b = r * 256 + *p++;
5414 else if (type == PBM_GRAY)
5415 r = g = b = pbm_scan_number (&p, end);
5416 else if (raw_p)
5418 r = *p++;
5419 if (max_color_idx > 255)
5420 r = r * 256 + *p++;
5421 g = *p++;
5422 if (max_color_idx > 255)
5423 g = g * 256 + *p++;
5424 b = *p++;
5425 if (max_color_idx > 255)
5426 b = b * 256 + *p++;
5428 else
5430 r = pbm_scan_number (&p, end);
5431 g = pbm_scan_number (&p, end);
5432 b = pbm_scan_number (&p, end);
5435 if (r < 0 || g < 0 || b < 0)
5437 x_destroy_x_image (ximg);
5438 image_error ("Invalid pixel value in image `%s'",
5439 img->spec, Qnil);
5440 goto error;
5443 /* RGB values are now in the range 0..max_color_idx.
5444 Scale this to the range 0..0xffff supported by X. */
5445 r = (double) r * 65535 / max_color_idx;
5446 g = (double) g * 65535 / max_color_idx;
5447 b = (double) b * 65535 / max_color_idx;
5448 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5452 #ifdef COLOR_TABLE_SUPPORT
5453 /* Store in IMG->colors the colors allocated for the image, and
5454 free the color table. */
5455 img->colors = colors_in_color_table (&img->ncolors);
5456 free_color_table ();
5457 #endif /* COLOR_TABLE_SUPPORT */
5459 img->width = width;
5460 img->height = height;
5462 /* Maybe fill in the background field while we have ximg handy. */
5464 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5465 /* Casting avoids a GCC warning. */
5466 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5468 /* Put the image into a pixmap. */
5469 x_put_x_image (f, ximg, img->pixmap, width, height);
5470 x_destroy_x_image (ximg);
5472 /* X and W32 versions did it here, MAC version above. ++kfs
5473 img->width = width;
5474 img->height = height; */
5476 UNGCPRO;
5477 xfree (contents);
5478 return 1;
5482 /***********************************************************************
5484 ***********************************************************************/
5486 #if defined (HAVE_PNG) || defined (HAVE_NS)
5488 /* Function prototypes. */
5490 static int png_image_p P_ ((Lisp_Object object));
5491 static int png_load P_ ((struct frame *f, struct image *img));
5493 /* The symbol `png' identifying images of this type. */
5495 Lisp_Object Qpng;
5497 /* Indices of image specification fields in png_format, below. */
5499 enum png_keyword_index
5501 PNG_TYPE,
5502 PNG_DATA,
5503 PNG_FILE,
5504 PNG_ASCENT,
5505 PNG_MARGIN,
5506 PNG_RELIEF,
5507 PNG_ALGORITHM,
5508 PNG_HEURISTIC_MASK,
5509 PNG_MASK,
5510 PNG_BACKGROUND,
5511 PNG_LAST
5514 /* Vector of image_keyword structures describing the format
5515 of valid user-defined image specifications. */
5517 static const struct image_keyword png_format[PNG_LAST] =
5519 {":type", IMAGE_SYMBOL_VALUE, 1},
5520 {":data", IMAGE_STRING_VALUE, 0},
5521 {":file", IMAGE_STRING_VALUE, 0},
5522 {":ascent", IMAGE_ASCENT_VALUE, 0},
5523 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5524 {":relief", IMAGE_INTEGER_VALUE, 0},
5525 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5526 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5527 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5528 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5531 /* Structure describing the image type `png'. */
5533 static struct image_type png_type =
5535 &Qpng,
5536 png_image_p,
5537 png_load,
5538 x_clear_image,
5539 NULL
5542 /* Return non-zero if OBJECT is a valid PNG image specification. */
5544 static int
5545 png_image_p (object)
5546 Lisp_Object object;
5548 struct image_keyword fmt[PNG_LAST];
5549 bcopy (png_format, fmt, sizeof fmt);
5551 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5552 return 0;
5554 /* Must specify either the :data or :file keyword. */
5555 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5558 #endif /* HAVE_PNG || HAVE_NS */
5561 #ifdef HAVE_PNG
5563 #ifdef HAVE_NTGUI
5564 /* PNG library details. */
5566 DEF_IMGLIB_FN (png_get_io_ptr);
5567 DEF_IMGLIB_FN (png_sig_cmp);
5568 DEF_IMGLIB_FN (png_create_read_struct);
5569 DEF_IMGLIB_FN (png_create_info_struct);
5570 DEF_IMGLIB_FN (png_destroy_read_struct);
5571 DEF_IMGLIB_FN (png_set_read_fn);
5572 DEF_IMGLIB_FN (png_set_sig_bytes);
5573 DEF_IMGLIB_FN (png_read_info);
5574 DEF_IMGLIB_FN (png_get_IHDR);
5575 DEF_IMGLIB_FN (png_get_valid);
5576 DEF_IMGLIB_FN (png_set_strip_16);
5577 DEF_IMGLIB_FN (png_set_expand);
5578 DEF_IMGLIB_FN (png_set_gray_to_rgb);
5579 DEF_IMGLIB_FN (png_set_background);
5580 DEF_IMGLIB_FN (png_get_bKGD);
5581 DEF_IMGLIB_FN (png_read_update_info);
5582 DEF_IMGLIB_FN (png_get_channels);
5583 DEF_IMGLIB_FN (png_get_rowbytes);
5584 DEF_IMGLIB_FN (png_read_image);
5585 DEF_IMGLIB_FN (png_read_end);
5586 DEF_IMGLIB_FN (png_error);
5588 static int
5589 init_png_functions (Lisp_Object libraries)
5591 HMODULE library;
5593 /* Try loading libpng under probable names. */
5594 if (!(library = w32_delayed_load (libraries, Qpng)))
5595 return 0;
5597 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5598 LOAD_IMGLIB_FN (library, png_sig_cmp);
5599 LOAD_IMGLIB_FN (library, png_create_read_struct);
5600 LOAD_IMGLIB_FN (library, png_create_info_struct);
5601 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5602 LOAD_IMGLIB_FN (library, png_set_read_fn);
5603 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5604 LOAD_IMGLIB_FN (library, png_read_info);
5605 LOAD_IMGLIB_FN (library, png_get_IHDR);
5606 LOAD_IMGLIB_FN (library, png_get_valid);
5607 LOAD_IMGLIB_FN (library, png_set_strip_16);
5608 LOAD_IMGLIB_FN (library, png_set_expand);
5609 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5610 LOAD_IMGLIB_FN (library, png_set_background);
5611 LOAD_IMGLIB_FN (library, png_get_bKGD);
5612 LOAD_IMGLIB_FN (library, png_read_update_info);
5613 LOAD_IMGLIB_FN (library, png_get_channels);
5614 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5615 LOAD_IMGLIB_FN (library, png_read_image);
5616 LOAD_IMGLIB_FN (library, png_read_end);
5617 LOAD_IMGLIB_FN (library, png_error);
5618 return 1;
5620 #else
5622 #define fn_png_get_io_ptr png_get_io_ptr
5623 #define fn_png_sig_cmp png_sig_cmp
5624 #define fn_png_create_read_struct png_create_read_struct
5625 #define fn_png_create_info_struct png_create_info_struct
5626 #define fn_png_destroy_read_struct png_destroy_read_struct
5627 #define fn_png_set_read_fn png_set_read_fn
5628 #define fn_png_set_sig_bytes png_set_sig_bytes
5629 #define fn_png_read_info png_read_info
5630 #define fn_png_get_IHDR png_get_IHDR
5631 #define fn_png_get_valid png_get_valid
5632 #define fn_png_set_strip_16 png_set_strip_16
5633 #define fn_png_set_expand png_set_expand
5634 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5635 #define fn_png_set_background png_set_background
5636 #define fn_png_get_bKGD png_get_bKGD
5637 #define fn_png_read_update_info png_read_update_info
5638 #define fn_png_get_channels png_get_channels
5639 #define fn_png_get_rowbytes png_get_rowbytes
5640 #define fn_png_read_image png_read_image
5641 #define fn_png_read_end png_read_end
5642 #define fn_png_error png_error
5644 #endif /* HAVE_NTGUI */
5646 /* Error and warning handlers installed when the PNG library
5647 is initialized. */
5649 static void
5650 my_png_error (png_ptr, msg)
5651 png_struct *png_ptr;
5652 char *msg;
5654 xassert (png_ptr != NULL);
5655 image_error ("PNG error: %s", build_string (msg), Qnil);
5656 longjmp (png_ptr->jmpbuf, 1);
5660 static void
5661 my_png_warning (png_ptr, msg)
5662 png_struct *png_ptr;
5663 char *msg;
5665 xassert (png_ptr != NULL);
5666 image_error ("PNG warning: %s", build_string (msg), Qnil);
5669 /* Memory source for PNG decoding. */
5671 struct png_memory_storage
5673 unsigned char *bytes; /* The data */
5674 size_t len; /* How big is it? */
5675 int index; /* Where are we? */
5679 /* Function set as reader function when reading PNG image from memory.
5680 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5681 bytes from the input to DATA. */
5683 static void
5684 png_read_from_memory (png_ptr, data, length)
5685 png_structp png_ptr;
5686 png_bytep data;
5687 png_size_t length;
5689 struct png_memory_storage *tbr
5690 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5692 if (length > tbr->len - tbr->index)
5693 fn_png_error (png_ptr, "Read error");
5695 bcopy (tbr->bytes + tbr->index, data, length);
5696 tbr->index = tbr->index + length;
5700 /* Function set as reader function when reading PNG image from a file.
5701 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5702 bytes from the input to DATA. */
5704 static void
5705 png_read_from_file (png_ptr, data, length)
5706 png_structp png_ptr;
5707 png_bytep data;
5708 png_size_t length;
5710 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5712 if (fread (data, 1, length, fp) < length)
5713 fn_png_error (png_ptr, "Read error");
5717 /* Load PNG image IMG for use on frame F. Value is non-zero if
5718 successful. */
5720 static int
5721 png_load (f, img)
5722 struct frame *f;
5723 struct image *img;
5725 Lisp_Object file, specified_file;
5726 Lisp_Object specified_data;
5727 int x, y, i;
5728 XImagePtr ximg, mask_img = NULL;
5729 struct gcpro gcpro1;
5730 png_struct *png_ptr = NULL;
5731 png_info *info_ptr = NULL, *end_info = NULL;
5732 FILE *volatile fp = NULL;
5733 png_byte sig[8];
5734 png_byte * volatile pixels = NULL;
5735 png_byte ** volatile rows = NULL;
5736 png_uint_32 width, height;
5737 int bit_depth, color_type, interlace_type;
5738 png_byte channels;
5739 png_uint_32 row_bytes;
5740 int transparent_p;
5741 struct png_memory_storage tbr; /* Data to be read */
5743 /* Find out what file to load. */
5744 specified_file = image_spec_value (img->spec, QCfile, NULL);
5745 specified_data = image_spec_value (img->spec, QCdata, NULL);
5746 file = Qnil;
5747 GCPRO1 (file);
5749 if (NILP (specified_data))
5751 file = x_find_image_file (specified_file);
5752 if (!STRINGP (file))
5754 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5755 UNGCPRO;
5756 return 0;
5759 /* Open the image file. */
5760 fp = fopen (SDATA (file), "rb");
5761 if (!fp)
5763 image_error ("Cannot open image file `%s'", file, Qnil);
5764 UNGCPRO;
5765 return 0;
5768 /* Check PNG signature. */
5769 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5770 || fn_png_sig_cmp (sig, 0, sizeof sig))
5772 image_error ("Not a PNG file: `%s'", file, Qnil);
5773 UNGCPRO;
5774 fclose (fp);
5775 return 0;
5778 else
5780 /* Read from memory. */
5781 tbr.bytes = SDATA (specified_data);
5782 tbr.len = SBYTES (specified_data);
5783 tbr.index = 0;
5785 /* Check PNG signature. */
5786 if (tbr.len < sizeof sig
5787 || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
5789 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5790 UNGCPRO;
5791 return 0;
5794 /* Need to skip past the signature. */
5795 tbr.bytes += sizeof (sig);
5798 /* Initialize read and info structs for PNG lib. Casting return
5799 value avoids a GCC warning on W32. */
5800 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5801 NULL, my_png_error,
5802 my_png_warning);
5803 if (!png_ptr)
5805 if (fp) fclose (fp);
5806 UNGCPRO;
5807 return 0;
5810 /* Casting return value avoids a GCC warning on W32. */
5811 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
5812 if (!info_ptr)
5814 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5815 if (fp) fclose (fp);
5816 UNGCPRO;
5817 return 0;
5820 /* Casting return value avoids a GCC warning on W32. */
5821 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
5822 if (!end_info)
5824 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5825 if (fp) fclose (fp);
5826 UNGCPRO;
5827 return 0;
5830 /* Set error jump-back. We come back here when the PNG library
5831 detects an error. */
5832 if (setjmp (png_ptr->jmpbuf))
5834 error:
5835 if (png_ptr)
5836 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5837 xfree (pixels);
5838 xfree (rows);
5839 if (fp) fclose (fp);
5840 UNGCPRO;
5841 return 0;
5844 /* Read image info. */
5845 if (!NILP (specified_data))
5846 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5847 else
5848 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5850 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5851 fn_png_read_info (png_ptr, info_ptr);
5852 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5853 &interlace_type, NULL, NULL);
5855 if (!check_image_size (f, width, height))
5857 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
5858 goto error;
5860 /* If image contains simply transparency data, we prefer to
5861 construct a clipping mask. */
5862 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5863 transparent_p = 1;
5864 else
5865 transparent_p = 0;
5867 /* This function is easier to write if we only have to handle
5868 one data format: RGB or RGBA with 8 bits per channel. Let's
5869 transform other formats into that format. */
5871 /* Strip more than 8 bits per channel. */
5872 if (bit_depth == 16)
5873 fn_png_set_strip_16 (png_ptr);
5875 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5876 if available. */
5877 fn_png_set_expand (png_ptr);
5879 /* Convert grayscale images to RGB. */
5880 if (color_type == PNG_COLOR_TYPE_GRAY
5881 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5882 fn_png_set_gray_to_rgb (png_ptr);
5884 /* Handle alpha channel by combining the image with a background
5885 color. Do this only if a real alpha channel is supplied. For
5886 simple transparency, we prefer a clipping mask. */
5887 if (!transparent_p)
5889 /* png_color_16 *image_bg; */
5890 Lisp_Object specified_bg
5891 = image_spec_value (img->spec, QCbackground, NULL);
5892 int shift = (bit_depth == 16) ? 0 : 8;
5894 if (STRINGP (specified_bg))
5895 /* The user specified `:background', use that. */
5897 XColor color;
5898 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
5900 png_color_16 user_bg;
5902 bzero (&user_bg, sizeof user_bg);
5903 user_bg.red = color.red >> shift;
5904 user_bg.green = color.green >> shift;
5905 user_bg.blue = color.blue >> shift;
5907 fn_png_set_background (png_ptr, &user_bg,
5908 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5911 else
5913 /* We use the current frame background, ignoring any default
5914 background color set by the image. */
5915 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
5916 XColor color;
5917 png_color_16 frame_background;
5919 color.pixel = FRAME_BACKGROUND_PIXEL (f);
5920 x_query_color (f, &color);
5922 bzero (&frame_background, sizeof frame_background);
5923 frame_background.red = color.red >> shift;
5924 frame_background.green = color.green >> shift;
5925 frame_background.blue = color.blue >> shift;
5926 #endif /* HAVE_X_WINDOWS */
5928 fn_png_set_background (png_ptr, &frame_background,
5929 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
5933 /* Update info structure. */
5934 fn_png_read_update_info (png_ptr, info_ptr);
5936 /* Get number of channels. Valid values are 1 for grayscale images
5937 and images with a palette, 2 for grayscale images with transparency
5938 information (alpha channel), 3 for RGB images, and 4 for RGB
5939 images with alpha channel, i.e. RGBA. If conversions above were
5940 sufficient we should only have 3 or 4 channels here. */
5941 channels = fn_png_get_channels (png_ptr, info_ptr);
5942 xassert (channels == 3 || channels == 4);
5944 /* Number of bytes needed for one row of the image. */
5945 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
5947 /* Allocate memory for the image. */
5948 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
5949 rows = (png_byte **) xmalloc (height * sizeof *rows);
5950 for (i = 0; i < height; ++i)
5951 rows[i] = pixels + i * row_bytes;
5953 /* Read the entire image. */
5954 fn_png_read_image (png_ptr, rows);
5955 fn_png_read_end (png_ptr, info_ptr);
5956 if (fp)
5958 fclose (fp);
5959 fp = NULL;
5962 /* Create the X image and pixmap. */
5963 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
5964 &img->pixmap))
5965 goto error;
5967 /* Create an image and pixmap serving as mask if the PNG image
5968 contains an alpha channel. */
5969 if (channels == 4
5970 && !transparent_p
5971 && !x_create_x_image_and_pixmap (f, width, height, 1,
5972 &mask_img, &img->mask))
5974 x_destroy_x_image (ximg);
5975 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
5976 img->pixmap = NO_PIXMAP;
5977 goto error;
5980 /* Fill the X image and mask from PNG data. */
5981 init_color_table ();
5983 for (y = 0; y < height; ++y)
5985 png_byte *p = rows[y];
5987 for (x = 0; x < width; ++x)
5989 unsigned r, g, b;
5991 r = *p++ << 8;
5992 g = *p++ << 8;
5993 b = *p++ << 8;
5994 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5995 /* An alpha channel, aka mask channel, associates variable
5996 transparency with an image. Where other image formats
5997 support binary transparency---fully transparent or fully
5998 opaque---PNG allows up to 254 levels of partial transparency.
5999 The PNG library implements partial transparency by combining
6000 the image with a specified background color.
6002 I'm not sure how to handle this here nicely: because the
6003 background on which the image is displayed may change, for
6004 real alpha channel support, it would be necessary to create
6005 a new image for each possible background.
6007 What I'm doing now is that a mask is created if we have
6008 boolean transparency information. Otherwise I'm using
6009 the frame's background color to combine the image with. */
6011 if (channels == 4)
6013 if (mask_img)
6014 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6015 ++p;
6020 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6021 /* Set IMG's background color from the PNG image, unless the user
6022 overrode it. */
6024 png_color_16 *bg;
6025 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6027 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6028 img->background_valid = 1;
6032 #ifdef COLOR_TABLE_SUPPORT
6033 /* Remember colors allocated for this image. */
6034 img->colors = colors_in_color_table (&img->ncolors);
6035 free_color_table ();
6036 #endif /* COLOR_TABLE_SUPPORT */
6038 /* Clean up. */
6039 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6040 xfree (rows);
6041 xfree (pixels);
6043 img->width = width;
6044 img->height = height;
6046 /* Maybe fill in the background field while we have ximg handy.
6047 Casting avoids a GCC warning. */
6048 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6050 /* Put the image into the pixmap, then free the X image and its buffer. */
6051 x_put_x_image (f, ximg, img->pixmap, width, height);
6052 x_destroy_x_image (ximg);
6054 /* Same for the mask. */
6055 if (mask_img)
6057 /* Fill in the background_transparent field while we have the
6058 mask handy. Casting avoids a GCC warning. */
6059 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6061 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
6062 x_destroy_x_image (mask_img);
6065 UNGCPRO;
6066 return 1;
6069 #else /* HAVE_PNG */
6071 #ifdef HAVE_NS
6072 static int
6073 png_load (struct frame *f, struct image *img)
6075 return ns_load_image(f, img,
6076 image_spec_value (img->spec, QCfile, NULL),
6077 image_spec_value (img->spec, QCdata, NULL));
6079 #endif /* HAVE_NS */
6082 #endif /* !HAVE_PNG */
6086 /***********************************************************************
6087 JPEG
6088 ***********************************************************************/
6090 #if defined (HAVE_JPEG) || defined (HAVE_NS)
6092 static int jpeg_image_p P_ ((Lisp_Object object));
6093 static int jpeg_load P_ ((struct frame *f, struct image *img));
6095 /* The symbol `jpeg' identifying images of this type. */
6097 Lisp_Object Qjpeg;
6099 /* Indices of image specification fields in gs_format, below. */
6101 enum jpeg_keyword_index
6103 JPEG_TYPE,
6104 JPEG_DATA,
6105 JPEG_FILE,
6106 JPEG_ASCENT,
6107 JPEG_MARGIN,
6108 JPEG_RELIEF,
6109 JPEG_ALGORITHM,
6110 JPEG_HEURISTIC_MASK,
6111 JPEG_MASK,
6112 JPEG_BACKGROUND,
6113 JPEG_LAST
6116 /* Vector of image_keyword structures describing the format
6117 of valid user-defined image specifications. */
6119 static const struct image_keyword jpeg_format[JPEG_LAST] =
6121 {":type", IMAGE_SYMBOL_VALUE, 1},
6122 {":data", IMAGE_STRING_VALUE, 0},
6123 {":file", IMAGE_STRING_VALUE, 0},
6124 {":ascent", IMAGE_ASCENT_VALUE, 0},
6125 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6126 {":relief", IMAGE_INTEGER_VALUE, 0},
6127 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6128 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6129 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6130 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6133 /* Structure describing the image type `jpeg'. */
6135 static struct image_type jpeg_type =
6137 &Qjpeg,
6138 jpeg_image_p,
6139 jpeg_load,
6140 x_clear_image,
6141 NULL
6144 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6146 static int
6147 jpeg_image_p (object)
6148 Lisp_Object object;
6150 struct image_keyword fmt[JPEG_LAST];
6152 bcopy (jpeg_format, fmt, sizeof fmt);
6154 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6155 return 0;
6157 /* Must specify either the :data or :file keyword. */
6158 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6161 #endif /* HAVE_JPEG || HAVE_NS */
6163 #ifdef HAVE_JPEG
6165 /* Work around a warning about HAVE_STDLIB_H being redefined in
6166 jconfig.h. */
6167 #ifdef HAVE_STDLIB_H
6168 #define HAVE_STDLIB_H_1
6169 #undef HAVE_STDLIB_H
6170 #endif /* HAVE_STLIB_H */
6172 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6173 /* In older releases of the jpeg library, jpeglib.h will define boolean
6174 differently depending on __WIN32__, so make sure it is defined. */
6175 #define __WIN32__ 1
6176 #endif
6178 #include <jpeglib.h>
6179 #include <jerror.h>
6181 #ifdef HAVE_STLIB_H_1
6182 #define HAVE_STDLIB_H 1
6183 #endif
6185 #ifdef HAVE_NTGUI
6187 /* JPEG library details. */
6188 DEF_IMGLIB_FN (jpeg_CreateDecompress);
6189 DEF_IMGLIB_FN (jpeg_start_decompress);
6190 DEF_IMGLIB_FN (jpeg_finish_decompress);
6191 DEF_IMGLIB_FN (jpeg_destroy_decompress);
6192 DEF_IMGLIB_FN (jpeg_read_header);
6193 DEF_IMGLIB_FN (jpeg_read_scanlines);
6194 DEF_IMGLIB_FN (jpeg_std_error);
6195 DEF_IMGLIB_FN (jpeg_resync_to_restart);
6197 static int
6198 init_jpeg_functions (Lisp_Object libraries)
6200 HMODULE library;
6202 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6203 return 0;
6205 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6206 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6207 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6208 LOAD_IMGLIB_FN (library, jpeg_read_header);
6209 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6210 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6211 LOAD_IMGLIB_FN (library, jpeg_std_error);
6212 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6213 return 1;
6216 /* Wrapper since we can't directly assign the function pointer
6217 to another function pointer that was declared more completely easily. */
6218 static boolean
6219 jpeg_resync_to_restart_wrapper (cinfo, desired)
6220 j_decompress_ptr cinfo;
6221 int desired;
6223 return fn_jpeg_resync_to_restart (cinfo, desired);
6226 #else
6228 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6229 #define fn_jpeg_start_decompress jpeg_start_decompress
6230 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6231 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6232 #define fn_jpeg_read_header jpeg_read_header
6233 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6234 #define fn_jpeg_std_error jpeg_std_error
6235 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6237 #endif /* HAVE_NTGUI */
6239 struct my_jpeg_error_mgr
6241 struct jpeg_error_mgr pub;
6242 jmp_buf setjmp_buffer;
6246 static void
6247 my_error_exit (cinfo)
6248 j_common_ptr cinfo;
6250 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6251 longjmp (mgr->setjmp_buffer, 1);
6255 /* Init source method for JPEG data source manager. Called by
6256 jpeg_read_header() before any data is actually read. See
6257 libjpeg.doc from the JPEG lib distribution. */
6259 static void
6260 our_common_init_source (cinfo)
6261 j_decompress_ptr cinfo;
6266 /* Method to terminate data source. Called by
6267 jpeg_finish_decompress() after all data has been processed. */
6269 static void
6270 our_common_term_source (cinfo)
6271 j_decompress_ptr cinfo;
6276 /* Fill input buffer method for JPEG data source manager. Called
6277 whenever more data is needed. We read the whole image in one step,
6278 so this only adds a fake end of input marker at the end. */
6280 static JOCTET our_memory_buffer[2];
6282 static boolean
6283 our_memory_fill_input_buffer (cinfo)
6284 j_decompress_ptr cinfo;
6286 /* Insert a fake EOI marker. */
6287 struct jpeg_source_mgr *src = cinfo->src;
6289 our_memory_buffer[0] = (JOCTET) 0xFF;
6290 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
6292 src->next_input_byte = our_memory_buffer;
6293 src->bytes_in_buffer = 2;
6294 return 1;
6298 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6299 is the JPEG data source manager. */
6301 static void
6302 our_memory_skip_input_data (cinfo, num_bytes)
6303 j_decompress_ptr cinfo;
6304 long num_bytes;
6306 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6308 if (src)
6310 if (num_bytes > src->bytes_in_buffer)
6311 ERREXIT (cinfo, JERR_INPUT_EOF);
6313 src->bytes_in_buffer -= num_bytes;
6314 src->next_input_byte += num_bytes;
6319 /* Set up the JPEG lib for reading an image from DATA which contains
6320 LEN bytes. CINFO is the decompression info structure created for
6321 reading the image. */
6323 static void
6324 jpeg_memory_src (cinfo, data, len)
6325 j_decompress_ptr cinfo;
6326 JOCTET *data;
6327 unsigned int len;
6329 struct jpeg_source_mgr *src;
6331 if (cinfo->src == NULL)
6333 /* First time for this JPEG object? */
6334 cinfo->src = (struct jpeg_source_mgr *)
6335 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6336 sizeof (struct jpeg_source_mgr));
6337 src = (struct jpeg_source_mgr *) cinfo->src;
6338 src->next_input_byte = data;
6341 src = (struct jpeg_source_mgr *) cinfo->src;
6342 src->init_source = our_common_init_source;
6343 src->fill_input_buffer = our_memory_fill_input_buffer;
6344 src->skip_input_data = our_memory_skip_input_data;
6345 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6346 src->term_source = our_common_term_source;
6347 src->bytes_in_buffer = len;
6348 src->next_input_byte = data;
6352 struct jpeg_stdio_mgr
6354 struct jpeg_source_mgr mgr;
6355 boolean finished;
6356 FILE *file;
6357 JOCTET *buffer;
6361 /* Size of buffer to read JPEG from file.
6362 Not too big, as we want to use alloc_small. */
6363 #define JPEG_STDIO_BUFFER_SIZE 8192
6366 /* Fill input buffer method for JPEG data source manager. Called
6367 whenever more data is needed. The data is read from a FILE *. */
6369 static boolean
6370 our_stdio_fill_input_buffer (cinfo)
6371 j_decompress_ptr cinfo;
6373 struct jpeg_stdio_mgr *src;
6375 src = (struct jpeg_stdio_mgr *) cinfo->src;
6376 if (!src->finished)
6378 size_t bytes;
6380 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6381 if (bytes > 0)
6382 src->mgr.bytes_in_buffer = bytes;
6383 else
6385 WARNMS (cinfo, JWRN_JPEG_EOF);
6386 src->finished = 1;
6387 src->buffer[0] = (JOCTET) 0xFF;
6388 src->buffer[1] = (JOCTET) JPEG_EOI;
6389 src->mgr.bytes_in_buffer = 2;
6391 src->mgr.next_input_byte = src->buffer;
6394 return 1;
6398 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6399 is the JPEG data source manager. */
6401 static void
6402 our_stdio_skip_input_data (cinfo, num_bytes)
6403 j_decompress_ptr cinfo;
6404 long num_bytes;
6406 struct jpeg_stdio_mgr *src;
6407 src = (struct jpeg_stdio_mgr *) cinfo->src;
6409 while (num_bytes > 0 && !src->finished)
6411 if (num_bytes <= src->mgr.bytes_in_buffer)
6413 src->mgr.bytes_in_buffer -= num_bytes;
6414 src->mgr.next_input_byte += num_bytes;
6415 break;
6417 else
6419 num_bytes -= src->mgr.bytes_in_buffer;
6420 src->mgr.bytes_in_buffer = 0;
6421 src->mgr.next_input_byte = NULL;
6423 our_stdio_fill_input_buffer (cinfo);
6429 /* Set up the JPEG lib for reading an image from a FILE *.
6430 CINFO is the decompression info structure created for
6431 reading the image. */
6433 static void
6434 jpeg_file_src (cinfo, fp)
6435 j_decompress_ptr cinfo;
6436 FILE *fp;
6438 struct jpeg_stdio_mgr *src;
6440 if (cinfo->src != NULL)
6441 src = (struct jpeg_stdio_mgr *) cinfo->src;
6442 else
6444 /* First time for this JPEG object? */
6445 cinfo->src = (struct jpeg_source_mgr *)
6446 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6447 sizeof (struct jpeg_stdio_mgr));
6448 src = (struct jpeg_stdio_mgr *) cinfo->src;
6449 src->buffer = (JOCTET *)
6450 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6451 JPEG_STDIO_BUFFER_SIZE);
6454 src->file = fp;
6455 src->finished = 0;
6456 src->mgr.init_source = our_common_init_source;
6457 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6458 src->mgr.skip_input_data = our_stdio_skip_input_data;
6459 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6460 src->mgr.term_source = our_common_term_source;
6461 src->mgr.bytes_in_buffer = 0;
6462 src->mgr.next_input_byte = NULL;
6466 /* Load image IMG for use on frame F. Patterned after example.c
6467 from the JPEG lib. */
6469 static int
6470 jpeg_load (f, img)
6471 struct frame *f;
6472 struct image *img;
6474 struct jpeg_decompress_struct cinfo;
6475 struct my_jpeg_error_mgr mgr;
6476 Lisp_Object file, specified_file;
6477 Lisp_Object specified_data;
6478 FILE * volatile fp = NULL;
6479 JSAMPARRAY buffer;
6480 int row_stride, x, y;
6481 XImagePtr ximg = NULL;
6482 int rc;
6483 unsigned long *colors;
6484 int width, height;
6485 struct gcpro gcpro1;
6487 /* Open the JPEG file. */
6488 specified_file = image_spec_value (img->spec, QCfile, NULL);
6489 specified_data = image_spec_value (img->spec, QCdata, NULL);
6490 file = Qnil;
6491 GCPRO1 (file);
6493 if (NILP (specified_data))
6495 file = x_find_image_file (specified_file);
6496 if (!STRINGP (file))
6498 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6499 UNGCPRO;
6500 return 0;
6503 fp = fopen (SDATA (file), "rb");
6504 if (fp == NULL)
6506 image_error ("Cannot open `%s'", file, Qnil);
6507 UNGCPRO;
6508 return 0;
6512 /* Customize libjpeg's error handling to call my_error_exit when an
6513 error is detected. This function will perform a longjmp.
6514 Casting return value avoids a GCC warning on W32. */
6515 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
6516 mgr.pub.error_exit = my_error_exit;
6518 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6520 if (rc == 1)
6522 /* Called from my_error_exit. Display a JPEG error. */
6523 char buffer[JMSG_LENGTH_MAX];
6524 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
6525 image_error ("Error reading JPEG image `%s': %s", img->spec,
6526 build_string (buffer));
6529 /* Close the input file and destroy the JPEG object. */
6530 if (fp)
6531 fclose ((FILE *) fp);
6532 fn_jpeg_destroy_decompress (&cinfo);
6534 /* If we already have an XImage, free that. */
6535 x_destroy_x_image (ximg);
6537 /* Free pixmap and colors. */
6538 x_clear_image (f, img);
6540 UNGCPRO;
6541 return 0;
6544 /* Create the JPEG decompression object. Let it read from fp.
6545 Read the JPEG image header. */
6546 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6548 if (NILP (specified_data))
6549 jpeg_file_src (&cinfo, (FILE *) fp);
6550 else
6551 jpeg_memory_src (&cinfo, SDATA (specified_data),
6552 SBYTES (specified_data));
6554 fn_jpeg_read_header (&cinfo, 1);
6556 /* Customize decompression so that color quantization will be used.
6557 Start decompression. */
6558 cinfo.quantize_colors = 1;
6559 fn_jpeg_start_decompress (&cinfo);
6560 width = img->width = cinfo.output_width;
6561 height = img->height = cinfo.output_height;
6563 if (!check_image_size (f, width, height))
6565 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
6566 longjmp (mgr.setjmp_buffer, 2);
6569 /* Create X image and pixmap. */
6570 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6571 longjmp (mgr.setjmp_buffer, 2);
6573 /* Allocate colors. When color quantization is used,
6574 cinfo.actual_number_of_colors has been set with the number of
6575 colors generated, and cinfo.colormap is a two-dimensional array
6576 of color indices in the range 0..cinfo.actual_number_of_colors.
6577 No more than 255 colors will be generated. */
6579 int i, ir, ig, ib;
6581 if (cinfo.out_color_components > 2)
6582 ir = 0, ig = 1, ib = 2;
6583 else if (cinfo.out_color_components > 1)
6584 ir = 0, ig = 1, ib = 0;
6585 else
6586 ir = 0, ig = 0, ib = 0;
6588 /* Use the color table mechanism because it handles colors that
6589 cannot be allocated nicely. Such colors will be replaced with
6590 a default color, and we don't have to care about which colors
6591 can be freed safely, and which can't. */
6592 init_color_table ();
6593 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6594 * sizeof *colors);
6596 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6598 /* Multiply RGB values with 255 because X expects RGB values
6599 in the range 0..0xffff. */
6600 int r = cinfo.colormap[ir][i] << 8;
6601 int g = cinfo.colormap[ig][i] << 8;
6602 int b = cinfo.colormap[ib][i] << 8;
6603 colors[i] = lookup_rgb_color (f, r, g, b);
6606 #ifdef COLOR_TABLE_SUPPORT
6607 /* Remember those colors actually allocated. */
6608 img->colors = colors_in_color_table (&img->ncolors);
6609 free_color_table ();
6610 #endif /* COLOR_TABLE_SUPPORT */
6613 /* Read pixels. */
6614 row_stride = width * cinfo.output_components;
6615 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6616 row_stride, 1);
6617 for (y = 0; y < height; ++y)
6619 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6620 for (x = 0; x < cinfo.output_width; ++x)
6621 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6624 /* Clean up. */
6625 fn_jpeg_finish_decompress (&cinfo);
6626 fn_jpeg_destroy_decompress (&cinfo);
6627 if (fp)
6628 fclose ((FILE *) fp);
6630 /* Maybe fill in the background field while we have ximg handy. */
6631 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6632 /* Casting avoids a GCC warning. */
6633 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6635 /* Put the image into the pixmap. */
6636 x_put_x_image (f, ximg, img->pixmap, width, height);
6637 x_destroy_x_image (ximg);
6638 UNGCPRO;
6639 return 1;
6642 #else /* HAVE_JPEG */
6644 #ifdef HAVE_NS
6645 static int
6646 jpeg_load (struct frame *f, struct image *img)
6648 return ns_load_image(f, img,
6649 image_spec_value (img->spec, QCfile, NULL),
6650 image_spec_value (img->spec, QCdata, NULL));
6652 #endif /* HAVE_NS */
6654 #endif /* !HAVE_JPEG */
6658 /***********************************************************************
6659 TIFF
6660 ***********************************************************************/
6662 #if defined (HAVE_TIFF) || defined (HAVE_NS)
6664 static int tiff_image_p P_ ((Lisp_Object object));
6665 static int tiff_load P_ ((struct frame *f, struct image *img));
6667 /* The symbol `tiff' identifying images of this type. */
6669 Lisp_Object Qtiff;
6671 /* Indices of image specification fields in tiff_format, below. */
6673 enum tiff_keyword_index
6675 TIFF_TYPE,
6676 TIFF_DATA,
6677 TIFF_FILE,
6678 TIFF_ASCENT,
6679 TIFF_MARGIN,
6680 TIFF_RELIEF,
6681 TIFF_ALGORITHM,
6682 TIFF_HEURISTIC_MASK,
6683 TIFF_MASK,
6684 TIFF_BACKGROUND,
6685 TIFF_INDEX,
6686 TIFF_LAST
6689 /* Vector of image_keyword structures describing the format
6690 of valid user-defined image specifications. */
6692 static const struct image_keyword tiff_format[TIFF_LAST] =
6694 {":type", IMAGE_SYMBOL_VALUE, 1},
6695 {":data", IMAGE_STRING_VALUE, 0},
6696 {":file", IMAGE_STRING_VALUE, 0},
6697 {":ascent", IMAGE_ASCENT_VALUE, 0},
6698 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6699 {":relief", IMAGE_INTEGER_VALUE, 0},
6700 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6701 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6702 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6703 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
6704 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
6707 /* Structure describing the image type `tiff'. */
6709 static struct image_type tiff_type =
6711 &Qtiff,
6712 tiff_image_p,
6713 tiff_load,
6714 x_clear_image,
6715 NULL
6718 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6720 static int
6721 tiff_image_p (object)
6722 Lisp_Object object;
6724 struct image_keyword fmt[TIFF_LAST];
6725 bcopy (tiff_format, fmt, sizeof fmt);
6727 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6728 return 0;
6730 /* Must specify either the :data or :file keyword. */
6731 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6734 #endif /* HAVE_TIFF || HAVE_NS */
6736 #ifdef HAVE_TIFF
6738 #include <tiffio.h>
6740 #ifdef HAVE_NTGUI
6742 /* TIFF library details. */
6743 DEF_IMGLIB_FN (TIFFSetErrorHandler);
6744 DEF_IMGLIB_FN (TIFFSetWarningHandler);
6745 DEF_IMGLIB_FN (TIFFOpen);
6746 DEF_IMGLIB_FN (TIFFClientOpen);
6747 DEF_IMGLIB_FN (TIFFGetField);
6748 DEF_IMGLIB_FN (TIFFReadRGBAImage);
6749 DEF_IMGLIB_FN (TIFFClose);
6750 DEF_IMGLIB_FN (TIFFSetDirectory);
6752 static int
6753 init_tiff_functions (Lisp_Object libraries)
6755 HMODULE library;
6757 if (!(library = w32_delayed_load (libraries, Qtiff)))
6758 return 0;
6760 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6761 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6762 LOAD_IMGLIB_FN (library, TIFFOpen);
6763 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6764 LOAD_IMGLIB_FN (library, TIFFGetField);
6765 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6766 LOAD_IMGLIB_FN (library, TIFFClose);
6767 LOAD_IMGLIB_FN (library, TIFFSetDirectory);
6768 return 1;
6771 #else
6773 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6774 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6775 #define fn_TIFFOpen TIFFOpen
6776 #define fn_TIFFClientOpen TIFFClientOpen
6777 #define fn_TIFFGetField TIFFGetField
6778 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6779 #define fn_TIFFClose TIFFClose
6780 #define fn_TIFFSetDirectory TIFFSetDirectory
6781 #endif /* HAVE_NTGUI */
6784 /* Reading from a memory buffer for TIFF images Based on the PNG
6785 memory source, but we have to provide a lot of extra functions.
6786 Blah.
6788 We really only need to implement read and seek, but I am not
6789 convinced that the TIFF library is smart enough not to destroy
6790 itself if we only hand it the function pointers we need to
6791 override. */
6793 typedef struct
6795 unsigned char *bytes;
6796 size_t len;
6797 int index;
6799 tiff_memory_source;
6801 static size_t
6802 tiff_read_from_memory (data, buf, size)
6803 thandle_t data;
6804 tdata_t buf;
6805 tsize_t size;
6807 tiff_memory_source *src = (tiff_memory_source *) data;
6809 if (size > src->len - src->index)
6810 return (size_t) -1;
6811 bcopy (src->bytes + src->index, buf, size);
6812 src->index += size;
6813 return size;
6816 static size_t
6817 tiff_write_from_memory (data, buf, size)
6818 thandle_t data;
6819 tdata_t buf;
6820 tsize_t size;
6822 return (size_t) -1;
6825 static toff_t
6826 tiff_seek_in_memory (data, off, whence)
6827 thandle_t data;
6828 toff_t off;
6829 int whence;
6831 tiff_memory_source *src = (tiff_memory_source *) data;
6832 int idx;
6834 switch (whence)
6836 case SEEK_SET: /* Go from beginning of source. */
6837 idx = off;
6838 break;
6840 case SEEK_END: /* Go from end of source. */
6841 idx = src->len + off;
6842 break;
6844 case SEEK_CUR: /* Go from current position. */
6845 idx = src->index + off;
6846 break;
6848 default: /* Invalid `whence'. */
6849 return -1;
6852 if (idx > src->len || idx < 0)
6853 return -1;
6855 src->index = idx;
6856 return src->index;
6859 static int
6860 tiff_close_memory (data)
6861 thandle_t data;
6863 /* NOOP */
6864 return 0;
6867 static int
6868 tiff_mmap_memory (data, pbase, psize)
6869 thandle_t data;
6870 tdata_t *pbase;
6871 toff_t *psize;
6873 /* It is already _IN_ memory. */
6874 return 0;
6877 static void
6878 tiff_unmap_memory (data, base, size)
6879 thandle_t data;
6880 tdata_t base;
6881 toff_t size;
6883 /* We don't need to do this. */
6886 static toff_t
6887 tiff_size_of_memory (data)
6888 thandle_t data;
6890 return ((tiff_memory_source *) data)->len;
6894 static void
6895 tiff_error_handler (title, format, ap)
6896 const char *title, *format;
6897 va_list ap;
6899 char buf[512];
6900 int len;
6902 len = sprintf (buf, "TIFF error: %s ", title);
6903 vsprintf (buf + len, format, ap);
6904 add_to_log (buf, Qnil, Qnil);
6908 static void
6909 tiff_warning_handler (title, format, ap)
6910 const char *title, *format;
6911 va_list ap;
6913 char buf[512];
6914 int len;
6916 len = sprintf (buf, "TIFF warning: %s ", title);
6917 vsprintf (buf + len, format, ap);
6918 add_to_log (buf, Qnil, Qnil);
6922 /* Load TIFF image IMG for use on frame F. Value is non-zero if
6923 successful. */
6925 static int
6926 tiff_load (f, img)
6927 struct frame *f;
6928 struct image *img;
6930 Lisp_Object file, specified_file;
6931 Lisp_Object specified_data;
6932 TIFF *tiff;
6933 int width, height, x, y, count;
6934 uint32 *buf;
6935 int rc, rc2;
6936 XImagePtr ximg;
6937 struct gcpro gcpro1;
6938 tiff_memory_source memsrc;
6939 Lisp_Object image;
6941 specified_file = image_spec_value (img->spec, QCfile, NULL);
6942 specified_data = image_spec_value (img->spec, QCdata, NULL);
6943 file = Qnil;
6944 GCPRO1 (file);
6946 fn_TIFFSetErrorHandler (tiff_error_handler);
6947 fn_TIFFSetWarningHandler (tiff_warning_handler);
6949 if (NILP (specified_data))
6951 /* Read from a file */
6952 file = x_find_image_file (specified_file);
6953 if (!STRINGP (file))
6955 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6956 UNGCPRO;
6957 return 0;
6960 /* Try to open the image file. Casting return value avoids a
6961 GCC warning on W32. */
6962 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
6963 if (tiff == NULL)
6965 image_error ("Cannot open `%s'", file, Qnil);
6966 UNGCPRO;
6967 return 0;
6970 else
6972 /* Memory source! */
6973 memsrc.bytes = SDATA (specified_data);
6974 memsrc.len = SBYTES (specified_data);
6975 memsrc.index = 0;
6977 /* Casting return value avoids a GCC warning on W32. */
6978 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r", &memsrc,
6979 (TIFFReadWriteProc) tiff_read_from_memory,
6980 (TIFFReadWriteProc) tiff_write_from_memory,
6981 tiff_seek_in_memory,
6982 tiff_close_memory,
6983 tiff_size_of_memory,
6984 tiff_mmap_memory,
6985 tiff_unmap_memory);
6987 if (!tiff)
6989 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
6990 UNGCPRO;
6991 return 0;
6995 image = image_spec_value (img->spec, QCindex, NULL);
6996 if (INTEGERP (image))
6998 int ino = XFASTINT (image);
6999 if (!fn_TIFFSetDirectory (tiff, ino))
7001 image_error ("Invalid image number `%s' in image `%s'",
7002 image, img->spec);
7003 fn_TIFFClose (tiff);
7004 UNGCPRO;
7005 return 0;
7009 /* Get width and height of the image, and allocate a raster buffer
7010 of width x height 32-bit values. */
7011 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7012 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7014 if (!check_image_size (f, width, height))
7016 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7017 fn_TIFFClose (tiff);
7018 UNGCPRO;
7019 return 0;
7022 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
7024 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7026 /* Count the number of images in the file. */
7027 for (count = 1, rc2 = 1; rc2; count++)
7028 rc2 = fn_TIFFSetDirectory (tiff, count);
7030 if (count > 1)
7031 img->data.lisp_val = Fcons (Qcount,
7032 Fcons (make_number (count),
7033 img->data.lisp_val));
7035 fn_TIFFClose (tiff);
7036 if (!rc)
7038 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7039 xfree (buf);
7040 UNGCPRO;
7041 return 0;
7044 /* Create the X image and pixmap. */
7045 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7047 xfree (buf);
7048 UNGCPRO;
7049 return 0;
7052 /* Initialize the color table. */
7053 init_color_table ();
7055 /* Process the pixel raster. Origin is in the lower-left corner. */
7056 for (y = 0; y < height; ++y)
7058 uint32 *row = buf + y * width;
7060 for (x = 0; x < width; ++x)
7062 uint32 abgr = row[x];
7063 int r = TIFFGetR (abgr) << 8;
7064 int g = TIFFGetG (abgr) << 8;
7065 int b = TIFFGetB (abgr) << 8;
7066 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7070 #ifdef COLOR_TABLE_SUPPORT
7071 /* Remember the colors allocated for the image. Free the color table. */
7072 img->colors = colors_in_color_table (&img->ncolors);
7073 free_color_table ();
7074 #endif /* COLOR_TABLE_SUPPORT */
7076 img->width = width;
7077 img->height = height;
7079 /* Maybe fill in the background field while we have ximg handy. */
7080 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7081 /* Casting avoids a GCC warning on W32. */
7082 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7084 /* Put the image into the pixmap, then free the X image and its buffer. */
7085 x_put_x_image (f, ximg, img->pixmap, width, height);
7086 x_destroy_x_image (ximg);
7087 xfree (buf);
7089 UNGCPRO;
7090 return 1;
7093 #else /* HAVE_TIFF */
7095 #ifdef HAVE_NS
7096 static int
7097 tiff_load (struct frame *f, struct image *img)
7099 return ns_load_image(f, img,
7100 image_spec_value (img->spec, QCfile, NULL),
7101 image_spec_value (img->spec, QCdata, NULL));
7103 #endif /* HAVE_NS */
7105 #endif /* !HAVE_TIFF */
7109 /***********************************************************************
7111 ***********************************************************************/
7113 #if defined (HAVE_GIF) || defined (HAVE_NS)
7115 static int gif_image_p P_ ((Lisp_Object object));
7116 static int gif_load P_ ((struct frame *f, struct image *img));
7117 static void gif_clear_image P_ ((struct frame *f, struct image *img));
7119 /* The symbol `gif' identifying images of this type. */
7121 Lisp_Object Qgif;
7123 /* Indices of image specification fields in gif_format, below. */
7125 enum gif_keyword_index
7127 GIF_TYPE,
7128 GIF_DATA,
7129 GIF_FILE,
7130 GIF_ASCENT,
7131 GIF_MARGIN,
7132 GIF_RELIEF,
7133 GIF_ALGORITHM,
7134 GIF_HEURISTIC_MASK,
7135 GIF_MASK,
7136 GIF_IMAGE,
7137 GIF_BACKGROUND,
7138 GIF_LAST
7141 /* Vector of image_keyword structures describing the format
7142 of valid user-defined image specifications. */
7144 static const struct image_keyword gif_format[GIF_LAST] =
7146 {":type", IMAGE_SYMBOL_VALUE, 1},
7147 {":data", IMAGE_STRING_VALUE, 0},
7148 {":file", IMAGE_STRING_VALUE, 0},
7149 {":ascent", IMAGE_ASCENT_VALUE, 0},
7150 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7151 {":relief", IMAGE_INTEGER_VALUE, 0},
7152 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7153 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7154 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7155 {":index", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7156 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7159 /* Structure describing the image type `gif'. */
7161 static struct image_type gif_type =
7163 &Qgif,
7164 gif_image_p,
7165 gif_load,
7166 gif_clear_image,
7167 NULL
7170 /* Free X resources of GIF image IMG which is used on frame F. */
7172 static void
7173 gif_clear_image (f, img)
7174 struct frame *f;
7175 struct image *img;
7177 /* IMG->data.ptr_val may contain extension data. */
7178 img->data.lisp_val = Qnil;
7179 x_clear_image (f, img);
7182 /* Return non-zero if OBJECT is a valid GIF image specification. */
7184 static int
7185 gif_image_p (object)
7186 Lisp_Object object;
7188 struct image_keyword fmt[GIF_LAST];
7189 bcopy (gif_format, fmt, sizeof fmt);
7191 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7192 return 0;
7194 /* Must specify either the :data or :file keyword. */
7195 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7198 #endif /* HAVE_GIF */
7200 #ifdef HAVE_GIF
7202 #if defined (HAVE_NTGUI)
7203 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7204 Undefine before redefining to avoid a preprocessor warning. */
7205 #ifdef DrawText
7206 #undef DrawText
7207 #endif
7208 /* avoid conflict with QuickdrawText.h */
7209 #define DrawText gif_DrawText
7210 #include <gif_lib.h>
7211 #undef DrawText
7213 #else /* HAVE_NTGUI */
7215 #include <gif_lib.h>
7217 #endif /* HAVE_NTGUI */
7220 #ifdef HAVE_NTGUI
7222 /* GIF library details. */
7223 DEF_IMGLIB_FN (DGifCloseFile);
7224 DEF_IMGLIB_FN (DGifSlurp);
7225 DEF_IMGLIB_FN (DGifOpen);
7226 DEF_IMGLIB_FN (DGifOpenFileName);
7228 static int
7229 init_gif_functions (Lisp_Object libraries)
7231 HMODULE library;
7233 if (!(library = w32_delayed_load (libraries, Qgif)))
7234 return 0;
7236 LOAD_IMGLIB_FN (library, DGifCloseFile);
7237 LOAD_IMGLIB_FN (library, DGifSlurp);
7238 LOAD_IMGLIB_FN (library, DGifOpen);
7239 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7240 return 1;
7243 #else
7245 #define fn_DGifCloseFile DGifCloseFile
7246 #define fn_DGifSlurp DGifSlurp
7247 #define fn_DGifOpen DGifOpen
7248 #define fn_DGifOpenFileName DGifOpenFileName
7250 #endif /* HAVE_NTGUI */
7252 /* Reading a GIF image from memory
7253 Based on the PNG memory stuff to a certain extent. */
7255 typedef struct
7257 unsigned char *bytes;
7258 size_t len;
7259 int index;
7261 gif_memory_source;
7263 /* Make the current memory source available to gif_read_from_memory.
7264 It's done this way because not all versions of libungif support
7265 a UserData field in the GifFileType structure. */
7266 static gif_memory_source *current_gif_memory_src;
7268 static int
7269 gif_read_from_memory (file, buf, len)
7270 GifFileType *file;
7271 GifByteType *buf;
7272 int len;
7274 gif_memory_source *src = current_gif_memory_src;
7276 if (len > src->len - src->index)
7277 return -1;
7279 bcopy (src->bytes + src->index, buf, len);
7280 src->index += len;
7281 return len;
7285 /* Load GIF image IMG for use on frame F. Value is non-zero if
7286 successful. */
7288 static const int interlace_start[] = {0, 4, 2, 1};
7289 static const int interlace_increment[] = {8, 8, 4, 2};
7291 static int
7292 gif_load (f, img)
7293 struct frame *f;
7294 struct image *img;
7296 Lisp_Object file, specified_file;
7297 Lisp_Object specified_data;
7298 int rc, width, height, x, y, i;
7299 XImagePtr ximg;
7300 ColorMapObject *gif_color_map;
7301 unsigned long pixel_colors[256];
7302 GifFileType *gif;
7303 struct gcpro gcpro1;
7304 Lisp_Object image;
7305 int ino, image_height, image_width;
7306 gif_memory_source memsrc;
7307 unsigned char *raster;
7309 specified_file = image_spec_value (img->spec, QCfile, NULL);
7310 specified_data = image_spec_value (img->spec, QCdata, NULL);
7311 file = Qnil;
7312 GCPRO1 (file);
7314 if (NILP (specified_data))
7316 file = x_find_image_file (specified_file);
7317 if (!STRINGP (file))
7319 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7320 UNGCPRO;
7321 return 0;
7324 /* Open the GIF file. Casting return value avoids a GCC warning
7325 on W32. */
7326 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
7327 if (gif == NULL)
7329 image_error ("Cannot open `%s'", file, Qnil);
7330 UNGCPRO;
7331 return 0;
7334 else
7336 /* Read from memory! */
7337 current_gif_memory_src = &memsrc;
7338 memsrc.bytes = SDATA (specified_data);
7339 memsrc.len = SBYTES (specified_data);
7340 memsrc.index = 0;
7342 /* Casting return value avoids a GCC warning on W32. */
7343 gif = (GifFileType *) fn_DGifOpen (&memsrc, gif_read_from_memory);
7344 if (!gif)
7346 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7347 UNGCPRO;
7348 return 0;
7352 /* Before reading entire contents, check the declared image size. */
7353 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7355 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7356 fn_DGifCloseFile (gif);
7357 UNGCPRO;
7358 return 0;
7361 /* Read entire contents. */
7362 rc = fn_DGifSlurp (gif);
7363 if (rc == GIF_ERROR)
7365 image_error ("Error reading `%s'", img->spec, Qnil);
7366 fn_DGifCloseFile (gif);
7367 UNGCPRO;
7368 return 0;
7371 image = image_spec_value (img->spec, QCindex, NULL);
7372 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7373 if (ino >= gif->ImageCount)
7375 image_error ("Invalid image number `%s' in image `%s'",
7376 image, img->spec);
7377 fn_DGifCloseFile (gif);
7378 UNGCPRO;
7379 return 0;
7382 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
7383 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
7384 image_height = gif->SavedImages[ino].ImageDesc.Height;
7385 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
7386 image_width = gif->SavedImages[ino].ImageDesc.Width;
7387 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
7389 width = img->width = max (gif->SWidth,
7390 max (gif->Image.Left + gif->Image.Width,
7391 img->corners[RIGHT_CORNER]));
7392 height = img->height = max (gif->SHeight,
7393 max (gif->Image.Top + gif->Image.Height,
7394 img->corners[BOT_CORNER]));
7396 if (!check_image_size (f, width, height))
7398 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7399 fn_DGifCloseFile (gif);
7400 UNGCPRO;
7401 return 0;
7404 /* Create the X image and pixmap. */
7405 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7407 fn_DGifCloseFile (gif);
7408 UNGCPRO;
7409 return 0;
7412 /* Allocate colors. */
7413 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7414 if (!gif_color_map)
7415 gif_color_map = gif->SColorMap;
7416 init_color_table ();
7417 bzero (pixel_colors, sizeof pixel_colors);
7419 if (gif_color_map)
7420 for (i = 0; i < gif_color_map->ColorCount; ++i)
7422 int r = gif_color_map->Colors[i].Red << 8;
7423 int g = gif_color_map->Colors[i].Green << 8;
7424 int b = gif_color_map->Colors[i].Blue << 8;
7425 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7428 #ifdef COLOR_TABLE_SUPPORT
7429 img->colors = colors_in_color_table (&img->ncolors);
7430 free_color_table ();
7431 #endif /* COLOR_TABLE_SUPPORT */
7433 /* Clear the part of the screen image that are not covered by
7434 the image from the GIF file. Full animated GIF support
7435 requires more than can be done here (see the gif89 spec,
7436 disposal methods). Let's simply assume that the part
7437 not covered by a sub-image is in the frame's background color. */
7438 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
7439 for (x = 0; x < width; ++x)
7440 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7442 for (y = img->corners[BOT_CORNER]; y < height; ++y)
7443 for (x = 0; x < width; ++x)
7444 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7446 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
7448 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
7449 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7450 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
7451 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7454 /* Read the GIF image into the X image. We use a local variable
7455 `raster' here because RasterBits below is a char *, and invites
7456 problems with bytes >= 0x80. */
7457 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7459 if (gif->SavedImages[ino].ImageDesc.Interlace)
7461 int pass;
7462 int row = interlace_start[0];
7464 pass = 0;
7466 for (y = 0; y < image_height; y++)
7468 if (row >= image_height)
7470 row = interlace_start[++pass];
7471 while (row >= image_height)
7472 row = interlace_start[++pass];
7475 for (x = 0; x < image_width; x++)
7477 int i = raster[(y * image_width) + x];
7478 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7479 row + img->corners[TOP_CORNER], pixel_colors[i]);
7482 row += interlace_increment[pass];
7485 else
7487 for (y = 0; y < image_height; ++y)
7488 for (x = 0; x < image_width; ++x)
7490 int i = raster[y * image_width + x];
7491 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
7492 y + img->corners[TOP_CORNER], pixel_colors[i]);
7496 /* Save GIF image extension data for `image-extension-data'.
7497 Format is (count IMAGES FUNCTION "BYTES" ...). */
7498 img->data.lisp_val = Qnil;
7499 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
7501 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
7502 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
7503 /* Append (... FUNCTION "BYTES") */
7504 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
7505 Fcons (make_number (ext->Function),
7506 img->data.lisp_val));
7507 img->data.lisp_val = Fnreverse (img->data.lisp_val);
7509 if (gif->ImageCount > 1)
7510 img->data.lisp_val = Fcons (Qcount,
7511 Fcons (make_number (gif->ImageCount),
7512 img->data.lisp_val));
7514 fn_DGifCloseFile (gif);
7516 /* Maybe fill in the background field while we have ximg handy. */
7517 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7518 /* Casting avoids a GCC warning. */
7519 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7521 /* Put the image into the pixmap, then free the X image and its buffer. */
7522 x_put_x_image (f, ximg, img->pixmap, width, height);
7523 x_destroy_x_image (ximg);
7525 UNGCPRO;
7526 return 1;
7529 #else /* !HAVE_GIF */
7531 #ifdef HAVE_NS
7532 static int
7533 gif_load (struct frame *f, struct image *img)
7535 return ns_load_image(f, img,
7536 image_spec_value (img->spec, QCfile, NULL),
7537 image_spec_value (img->spec, QCdata, NULL));
7539 #endif /* HAVE_NS */
7541 #endif /* HAVE_GIF */
7545 /***********************************************************************
7547 ***********************************************************************/
7549 #if defined (HAVE_RSVG)
7551 /* Function prototypes. */
7553 static int svg_image_p P_ ((Lisp_Object object));
7554 static int svg_load P_ ((struct frame *f, struct image *img));
7556 static int svg_load_image P_ ((struct frame *, struct image *,
7557 unsigned char *, unsigned int));
7559 /* The symbol `svg' identifying images of this type. */
7561 Lisp_Object Qsvg;
7563 /* Indices of image specification fields in svg_format, below. */
7565 enum svg_keyword_index
7567 SVG_TYPE,
7568 SVG_DATA,
7569 SVG_FILE,
7570 SVG_ASCENT,
7571 SVG_MARGIN,
7572 SVG_RELIEF,
7573 SVG_ALGORITHM,
7574 SVG_HEURISTIC_MASK,
7575 SVG_MASK,
7576 SVG_BACKGROUND,
7577 SVG_LAST
7580 /* Vector of image_keyword structures describing the format
7581 of valid user-defined image specifications. */
7583 static const struct image_keyword svg_format[SVG_LAST] =
7585 {":type", IMAGE_SYMBOL_VALUE, 1},
7586 {":data", IMAGE_STRING_VALUE, 0},
7587 {":file", IMAGE_STRING_VALUE, 0},
7588 {":ascent", IMAGE_ASCENT_VALUE, 0},
7589 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7590 {":relief", IMAGE_INTEGER_VALUE, 0},
7591 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7592 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7593 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7594 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7597 /* Structure describing the image type `svg'. Its the same type of
7598 structure defined for all image formats, handled by emacs image
7599 functions. See struct image_type in dispextern.h. */
7601 static struct image_type svg_type =
7603 /* An identifier showing that this is an image structure for the SVG format. */
7604 &Qsvg,
7605 /* Handle to a function that can be used to identify a SVG file. */
7606 svg_image_p,
7607 /* Handle to function used to load a SVG file. */
7608 svg_load,
7609 /* Handle to function to free sresources for SVG. */
7610 x_clear_image,
7611 /* An internal field to link to the next image type in a list of
7612 image types, will be filled in when registering the format. */
7613 NULL
7617 /* Return non-zero if OBJECT is a valid SVG image specification. Do
7618 this by calling parse_image_spec and supplying the keywords that
7619 identify the SVG format. */
7621 static int
7622 svg_image_p (object)
7623 Lisp_Object object;
7625 struct image_keyword fmt[SVG_LAST];
7626 bcopy (svg_format, fmt, sizeof fmt);
7628 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
7629 return 0;
7631 /* Must specify either the :data or :file keyword. */
7632 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
7635 #include <librsvg/rsvg.h>
7637 #ifdef HAVE_NTGUI
7639 /* SVG library functions. */
7640 DEF_IMGLIB_FN (rsvg_handle_new);
7641 DEF_IMGLIB_FN (rsvg_handle_get_dimensions);
7642 DEF_IMGLIB_FN (rsvg_handle_write);
7643 DEF_IMGLIB_FN (rsvg_handle_close);
7644 DEF_IMGLIB_FN (rsvg_handle_get_pixbuf);
7645 DEF_IMGLIB_FN (rsvg_handle_free);
7647 DEF_IMGLIB_FN (gdk_pixbuf_get_width);
7648 DEF_IMGLIB_FN (gdk_pixbuf_get_height);
7649 DEF_IMGLIB_FN (gdk_pixbuf_get_pixels);
7650 DEF_IMGLIB_FN (gdk_pixbuf_get_rowstride);
7651 DEF_IMGLIB_FN (gdk_pixbuf_get_colorspace);
7652 DEF_IMGLIB_FN (gdk_pixbuf_get_n_channels);
7653 DEF_IMGLIB_FN (gdk_pixbuf_get_has_alpha);
7654 DEF_IMGLIB_FN (gdk_pixbuf_get_bits_per_sample);
7656 DEF_IMGLIB_FN (g_type_init);
7657 DEF_IMGLIB_FN (g_object_unref);
7658 DEF_IMGLIB_FN (g_error_free);
7660 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
7662 static int
7663 init_svg_functions (Lisp_Object libraries)
7665 HMODULE library, gdklib, glib, gobject;
7667 if (!(glib = w32_delayed_load (libraries, Qglib))
7668 || !(gobject = w32_delayed_load (libraries, Qgobject))
7669 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
7670 || !(library = w32_delayed_load (libraries, Qsvg)))
7671 return 0;
7673 LOAD_IMGLIB_FN (library, rsvg_handle_new);
7674 LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
7675 LOAD_IMGLIB_FN (library, rsvg_handle_write);
7676 LOAD_IMGLIB_FN (library, rsvg_handle_close);
7677 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
7678 LOAD_IMGLIB_FN (library, rsvg_handle_free);
7680 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
7681 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
7682 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
7683 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
7684 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
7685 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
7686 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
7687 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
7689 LOAD_IMGLIB_FN (gobject, g_type_init);
7690 LOAD_IMGLIB_FN (gobject, g_object_unref);
7691 LOAD_IMGLIB_FN (glib, g_error_free);
7693 return 1;
7696 #else
7697 /* The following aliases for library functions allow dynamic loading
7698 to be used on some platforms. */
7699 #define fn_rsvg_handle_new rsvg_handle_new
7700 #define fn_rsvg_handle_get_dimensions rsvg_handle_get_dimensions
7701 #define fn_rsvg_handle_write rsvg_handle_write
7702 #define fn_rsvg_handle_close rsvg_handle_close
7703 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
7704 #define fn_rsvg_handle_free rsvg_handle_free
7706 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
7707 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
7708 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
7709 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
7710 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
7711 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
7712 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
7713 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
7715 #define fn_g_type_init g_type_init
7716 #define fn_g_object_unref g_object_unref
7717 #define fn_g_error_free g_error_free
7718 #endif /* !HAVE_NTGUI */
7720 /* Load SVG image IMG for use on frame F. Value is non-zero if
7721 successful. this function will go into the svg_type structure, and
7722 the prototype thus needs to be compatible with that structure. */
7724 static int
7725 svg_load (f, img)
7726 struct frame *f;
7727 struct image *img;
7729 int success_p = 0;
7730 Lisp_Object file_name;
7732 /* If IMG->spec specifies a file name, create a non-file spec from it. */
7733 file_name = image_spec_value (img->spec, QCfile, NULL);
7734 if (STRINGP (file_name))
7736 Lisp_Object file;
7737 unsigned char *contents;
7738 int size;
7739 struct gcpro gcpro1;
7741 file = x_find_image_file (file_name);
7742 GCPRO1 (file);
7743 if (!STRINGP (file))
7745 image_error ("Cannot find image file `%s'", file_name, Qnil);
7746 UNGCPRO;
7747 return 0;
7750 /* Read the entire file into memory. */
7751 contents = slurp_file (SDATA (file), &size);
7752 if (contents == NULL)
7754 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
7755 UNGCPRO;
7756 return 0;
7758 /* If the file was slurped into memory properly, parse it. */
7759 success_p = svg_load_image (f, img, contents, size);
7760 xfree (contents);
7761 UNGCPRO;
7763 /* Else its not a file, its a lisp object. Load the image from a
7764 lisp object rather than a file. */
7765 else
7767 Lisp_Object data;
7769 data = image_spec_value (img->spec, QCdata, NULL);
7770 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
7773 return success_p;
7776 /* svg_load_image is a helper function for svg_load, which does the
7777 actual loading given contents and size, apart from frame and image
7778 structures, passed from svg_load.
7780 Uses librsvg to do most of the image processing.
7782 Returns non-zero when successful. */
7783 static int
7784 svg_load_image (f, img, contents, size)
7785 /* Pointer to emacs frame structure. */
7786 struct frame *f;
7787 /* Pointer to emacs image structure. */
7788 struct image *img;
7789 /* String containing the SVG XML data to be parsed. */
7790 unsigned char *contents;
7791 /* Size of data in bytes. */
7792 unsigned int size;
7794 RsvgHandle *rsvg_handle;
7795 RsvgDimensionData dimension_data;
7796 GError *error = NULL;
7797 GdkPixbuf *pixbuf;
7798 int width;
7799 int height;
7800 const guint8 *pixels;
7801 int rowstride;
7802 XImagePtr ximg;
7803 Lisp_Object specified_bg;
7804 XColor background;
7805 int x;
7806 int y;
7808 /* g_type_init is a glib function that must be called prior to using
7809 gnome type library functions. */
7810 fn_g_type_init ();
7811 /* Make a handle to a new rsvg object. */
7812 rsvg_handle = (RsvgHandle *) fn_rsvg_handle_new ();
7814 /* Parse the contents argument and fill in the rsvg_handle. */
7815 fn_rsvg_handle_write (rsvg_handle, contents, size, &error);
7816 if (error) goto rsvg_error;
7818 /* The parsing is complete, rsvg_handle is ready to used, close it
7819 for further writes. */
7820 fn_rsvg_handle_close (rsvg_handle, &error);
7821 if (error) goto rsvg_error;
7823 fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
7824 if (! check_image_size (f, dimension_data.width, dimension_data.height))
7826 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
7827 goto rsvg_error;
7830 /* We can now get a valid pixel buffer from the svg file, if all
7831 went ok. */
7832 pixbuf = (GdkPixbuf *) fn_rsvg_handle_get_pixbuf (rsvg_handle);
7833 if (!pixbuf) goto rsvg_error;
7834 fn_g_object_unref (rsvg_handle);
7836 /* Extract some meta data from the svg handle. */
7837 width = fn_gdk_pixbuf_get_width (pixbuf);
7838 height = fn_gdk_pixbuf_get_height (pixbuf);
7839 pixels = (const guint8 *) fn_gdk_pixbuf_get_pixels (pixbuf);
7840 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
7842 /* Validate the svg meta data. */
7843 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
7844 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
7845 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
7846 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
7848 /* Try to create a x pixmap to hold the svg pixmap. */
7849 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7851 fn_g_object_unref (pixbuf);
7852 return 0;
7855 init_color_table ();
7857 /* Handle alpha channel by combining the image with a background
7858 color. */
7859 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7860 if (!STRINGP (specified_bg)
7861 || !x_defined_color (f, SDATA (specified_bg), &background, 0))
7863 #ifndef HAVE_NS
7864 background.pixel = FRAME_BACKGROUND_PIXEL (f);
7865 x_query_color (f, &background);
7866 #else
7867 ns_query_color(FRAME_BACKGROUND_COLOR (f), &background, 1);
7868 #endif
7871 /* SVG pixmaps specify transparency in the last byte, so right
7872 shift 8 bits to get rid of it, since emacs doesn't support
7873 transparency. */
7874 background.red >>= 8;
7875 background.green >>= 8;
7876 background.blue >>= 8;
7878 /* This loop handles opacity values, since Emacs assumes
7879 non-transparent images. Each pixel must be "flattened" by
7880 calculating the resulting color, given the transparency of the
7881 pixel, and the image background color. */
7882 for (y = 0; y < height; ++y)
7884 for (x = 0; x < width; ++x)
7886 unsigned red;
7887 unsigned green;
7888 unsigned blue;
7889 unsigned opacity;
7891 red = *pixels++;
7892 green = *pixels++;
7893 blue = *pixels++;
7894 opacity = *pixels++;
7896 red = ((red * opacity)
7897 + (background.red * ((1 << 8) - opacity)));
7898 green = ((green * opacity)
7899 + (background.green * ((1 << 8) - opacity)));
7900 blue = ((blue * opacity)
7901 + (background.blue * ((1 << 8) - opacity)));
7903 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
7906 pixels += rowstride - 4 * width;
7909 #ifdef COLOR_TABLE_SUPPORT
7910 /* Remember colors allocated for this image. */
7911 img->colors = colors_in_color_table (&img->ncolors);
7912 free_color_table ();
7913 #endif /* COLOR_TABLE_SUPPORT */
7915 fn_g_object_unref (pixbuf);
7917 img->width = width;
7918 img->height = height;
7920 /* Maybe fill in the background field while we have ximg handy.
7921 Casting avoids a GCC warning. */
7922 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7924 /* Put the image into the pixmap, then free the X image and its
7925 buffer. */
7926 x_put_x_image (f, ximg, img->pixmap, width, height);
7927 x_destroy_x_image (ximg);
7929 return 1;
7931 rsvg_error:
7932 fn_g_object_unref (rsvg_handle);
7933 /* FIXME: Use error->message so the user knows what is the actual
7934 problem with the image. */
7935 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
7936 fn_g_error_free (error);
7937 return 0;
7940 #endif /* defined (HAVE_RSVG) */
7945 /***********************************************************************
7946 Ghostscript
7947 ***********************************************************************/
7949 #ifdef HAVE_X_WINDOWS
7950 #define HAVE_GHOSTSCRIPT 1
7951 #endif /* HAVE_X_WINDOWS */
7953 /* The symbol `postscript' identifying images of this type. */
7955 Lisp_Object Qpostscript;
7957 #ifdef HAVE_GHOSTSCRIPT
7959 static int gs_image_p P_ ((Lisp_Object object));
7960 static int gs_load P_ ((struct frame *f, struct image *img));
7961 static void gs_clear_image P_ ((struct frame *f, struct image *img));
7963 /* Keyword symbols. */
7965 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
7967 /* Indices of image specification fields in gs_format, below. */
7969 enum gs_keyword_index
7971 GS_TYPE,
7972 GS_PT_WIDTH,
7973 GS_PT_HEIGHT,
7974 GS_FILE,
7975 GS_LOADER,
7976 GS_BOUNDING_BOX,
7977 GS_ASCENT,
7978 GS_MARGIN,
7979 GS_RELIEF,
7980 GS_ALGORITHM,
7981 GS_HEURISTIC_MASK,
7982 GS_MASK,
7983 GS_BACKGROUND,
7984 GS_LAST
7987 /* Vector of image_keyword structures describing the format
7988 of valid user-defined image specifications. */
7990 static const struct image_keyword gs_format[GS_LAST] =
7992 {":type", IMAGE_SYMBOL_VALUE, 1},
7993 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7994 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7995 {":file", IMAGE_STRING_VALUE, 1},
7996 {":loader", IMAGE_FUNCTION_VALUE, 0},
7997 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
7998 {":ascent", IMAGE_ASCENT_VALUE, 0},
7999 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8000 {":relief", IMAGE_INTEGER_VALUE, 0},
8001 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8002 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8003 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8004 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8007 /* Structure describing the image type `ghostscript'. */
8009 static struct image_type gs_type =
8011 &Qpostscript,
8012 gs_image_p,
8013 gs_load,
8014 gs_clear_image,
8015 NULL
8019 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8021 static void
8022 gs_clear_image (f, img)
8023 struct frame *f;
8024 struct image *img;
8026 /* IMG->data.ptr_val may contain a recorded colormap. */
8027 xfree (img->data.ptr_val);
8028 x_clear_image (f, img);
8032 /* Return non-zero if OBJECT is a valid Ghostscript image
8033 specification. */
8035 static int
8036 gs_image_p (object)
8037 Lisp_Object object;
8039 struct image_keyword fmt[GS_LAST];
8040 Lisp_Object tem;
8041 int i;
8043 bcopy (gs_format, fmt, sizeof fmt);
8045 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8046 return 0;
8048 /* Bounding box must be a list or vector containing 4 integers. */
8049 tem = fmt[GS_BOUNDING_BOX].value;
8050 if (CONSP (tem))
8052 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8053 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8054 return 0;
8055 if (!NILP (tem))
8056 return 0;
8058 else if (VECTORP (tem))
8060 if (XVECTOR (tem)->size != 4)
8061 return 0;
8062 for (i = 0; i < 4; ++i)
8063 if (!INTEGERP (XVECTOR (tem)->contents[i]))
8064 return 0;
8066 else
8067 return 0;
8069 return 1;
8073 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8074 if successful. */
8076 static int
8077 gs_load (f, img)
8078 struct frame *f;
8079 struct image *img;
8081 char buffer[100];
8082 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8083 struct gcpro gcpro1, gcpro2;
8084 Lisp_Object frame;
8085 double in_width, in_height;
8086 Lisp_Object pixel_colors = Qnil;
8088 /* Compute pixel size of pixmap needed from the given size in the
8089 image specification. Sizes in the specification are in pt. 1 pt
8090 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8091 info. */
8092 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8093 in_width = XFASTINT (pt_width) / 72.0;
8094 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
8095 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8096 in_height = XFASTINT (pt_height) / 72.0;
8097 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
8099 if (!check_image_size (f, img->width, img->height))
8101 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8102 return 0;
8105 /* Create the pixmap. */
8106 xassert (img->pixmap == NO_PIXMAP);
8108 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8109 BLOCK_INPUT;
8110 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8111 img->width, img->height,
8112 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8113 UNBLOCK_INPUT;
8115 if (!img->pixmap)
8117 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8118 return 0;
8121 /* Call the loader to fill the pixmap. It returns a process object
8122 if successful. We do not record_unwind_protect here because
8123 other places in redisplay like calling window scroll functions
8124 don't either. Let the Lisp loader use `unwind-protect' instead. */
8125 GCPRO2 (window_and_pixmap_id, pixel_colors);
8127 sprintf (buffer, "%lu %lu",
8128 (unsigned long) FRAME_X_WINDOW (f),
8129 (unsigned long) img->pixmap);
8130 window_and_pixmap_id = build_string (buffer);
8132 sprintf (buffer, "%lu %lu",
8133 FRAME_FOREGROUND_PIXEL (f),
8134 FRAME_BACKGROUND_PIXEL (f));
8135 pixel_colors = build_string (buffer);
8137 XSETFRAME (frame, f);
8138 loader = image_spec_value (img->spec, QCloader, NULL);
8139 if (NILP (loader))
8140 loader = intern ("gs-load-image");
8142 img->data.lisp_val = call6 (loader, frame, img->spec,
8143 make_number (img->width),
8144 make_number (img->height),
8145 window_and_pixmap_id,
8146 pixel_colors);
8147 UNGCPRO;
8148 return PROCESSP (img->data.lisp_val);
8152 /* Kill the Ghostscript process that was started to fill PIXMAP on
8153 frame F. Called from XTread_socket when receiving an event
8154 telling Emacs that Ghostscript has finished drawing. */
8156 void
8157 x_kill_gs_process (pixmap, f)
8158 Pixmap pixmap;
8159 struct frame *f;
8161 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8162 int class, i;
8163 struct image *img;
8165 /* Find the image containing PIXMAP. */
8166 for (i = 0; i < c->used; ++i)
8167 if (c->images[i]->pixmap == pixmap)
8168 break;
8170 /* Should someone in between have cleared the image cache, for
8171 instance, give up. */
8172 if (i == c->used)
8173 return;
8175 /* Kill the GS process. We should have found PIXMAP in the image
8176 cache and its image should contain a process object. */
8177 img = c->images[i];
8178 xassert (PROCESSP (img->data.lisp_val));
8179 Fkill_process (img->data.lisp_val, Qnil);
8180 img->data.lisp_val = Qnil;
8182 #if defined (HAVE_X_WINDOWS)
8184 /* On displays with a mutable colormap, figure out the colors
8185 allocated for the image by looking at the pixels of an XImage for
8186 img->pixmap. */
8187 class = FRAME_X_VISUAL (f)->class;
8188 if (class != StaticColor && class != StaticGray && class != TrueColor)
8190 XImagePtr ximg;
8192 BLOCK_INPUT;
8194 /* Try to get an XImage for img->pixmep. */
8195 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8196 0, 0, img->width, img->height, ~0, ZPixmap);
8197 if (ximg)
8199 int x, y;
8201 /* Initialize the color table. */
8202 init_color_table ();
8204 /* For each pixel of the image, look its color up in the
8205 color table. After having done so, the color table will
8206 contain an entry for each color used by the image. */
8207 for (y = 0; y < img->height; ++y)
8208 for (x = 0; x < img->width; ++x)
8210 unsigned long pixel = XGetPixel (ximg, x, y);
8211 lookup_pixel_color (f, pixel);
8214 /* Record colors in the image. Free color table and XImage. */
8215 #ifdef COLOR_TABLE_SUPPORT
8216 img->colors = colors_in_color_table (&img->ncolors);
8217 free_color_table ();
8218 #endif
8219 XDestroyImage (ximg);
8221 #if 0 /* This doesn't seem to be the case. If we free the colors
8222 here, we get a BadAccess later in x_clear_image when
8223 freeing the colors. */
8224 /* We have allocated colors once, but Ghostscript has also
8225 allocated colors on behalf of us. So, to get the
8226 reference counts right, free them once. */
8227 if (img->ncolors)
8228 x_free_colors (f, img->colors, img->ncolors);
8229 #endif
8231 else
8232 image_error ("Cannot get X image of `%s'; colors will not be freed",
8233 img->spec, Qnil);
8235 UNBLOCK_INPUT;
8237 #endif /* HAVE_X_WINDOWS */
8239 /* Now that we have the pixmap, compute mask and transform the
8240 image if requested. */
8241 BLOCK_INPUT;
8242 postprocess_image (f, img);
8243 UNBLOCK_INPUT;
8246 #endif /* HAVE_GHOSTSCRIPT */
8249 /***********************************************************************
8250 Tests
8251 ***********************************************************************/
8253 #if GLYPH_DEBUG
8255 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8256 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8257 (spec)
8258 Lisp_Object spec;
8260 return valid_image_p (spec) ? Qt : Qnil;
8264 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8265 (spec)
8266 Lisp_Object spec;
8268 int id = -1;
8270 if (valid_image_p (spec))
8271 id = lookup_image (SELECTED_FRAME (), spec);
8273 debug_print (spec);
8274 return make_number (id);
8277 #endif /* GLYPH_DEBUG != 0 */
8280 /***********************************************************************
8281 Initialization
8282 ***********************************************************************/
8284 #ifdef HAVE_NTGUI
8285 /* Image types that rely on external libraries are loaded dynamically
8286 if the library is available. */
8287 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8288 define_image_type (image_type, init_lib_fn (libraries))
8289 #else
8290 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8291 define_image_type (image_type, 1)
8292 #endif /* HAVE_NTGUI */
8294 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8295 doc: /* Initialize image library implementing image type TYPE.
8296 Return non-nil if TYPE is a supported image type.
8298 Image types pbm and xbm are prebuilt; other types are loaded here.
8299 Libraries to load are specified in alist LIBRARIES (usually, the value
8300 of `image-library-alist', which see). */)
8301 (type, libraries)
8302 Lisp_Object type, libraries;
8304 Lisp_Object tested;
8306 /* Don't try to reload the library. */
8307 tested = Fassq (type, Vimage_type_cache);
8308 if (CONSP (tested))
8309 return XCDR (tested);
8311 #if defined (HAVE_XPM) || defined (HAVE_NS)
8312 if (EQ (type, Qxpm))
8313 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8314 #endif
8316 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8317 if (EQ (type, Qjpeg))
8318 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8319 #endif
8321 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8322 if (EQ (type, Qtiff))
8323 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8324 #endif
8326 #if defined (HAVE_GIF) || defined (HAVE_NS)
8327 if (EQ (type, Qgif))
8328 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8329 #endif
8331 #if defined (HAVE_PNG) || defined (HAVE_NS)
8332 if (EQ (type, Qpng))
8333 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8334 #endif
8336 #if defined (HAVE_RSVG)
8337 if (EQ (type, Qsvg))
8338 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
8339 #endif
8341 #ifdef HAVE_GHOSTSCRIPT
8342 if (EQ (type, Qpostscript))
8343 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8344 #endif
8346 /* If the type is not recognized, avoid testing it ever again. */
8347 CACHE_IMAGE_TYPE (type, Qnil);
8348 return Qnil;
8351 void
8352 syms_of_image ()
8354 extern Lisp_Object Qrisky_local_variable; /* Syms_of_xdisp has already run. */
8356 /* Initialize this only once, since that's what we do with Vimage_types
8357 and they are supposed to be in sync. Initializing here gives correct
8358 operation on GNU/Linux of calling dump-emacs after loading some images. */
8359 image_types = NULL;
8361 /* Must be defined now becase we're going to update it below, while
8362 defining the supported image types. */
8363 DEFVAR_LISP ("image-types", &Vimage_types,
8364 doc: /* List of potentially supported image types.
8365 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8366 To check whether it is really supported, use `image-type-available-p'. */);
8367 Vimage_types = Qnil;
8369 DEFVAR_LISP ("image-library-alist", &Vimage_library_alist,
8370 doc: /* Alist of image types vs external libraries needed to display them.
8372 Each element is a list (IMAGE-TYPE LIBRARY...), where the car is a symbol
8373 representing a supported image type, and the rest are strings giving
8374 alternate filenames for the corresponding external libraries.
8376 Emacs tries to load the libraries in the order they appear on the
8377 list; if none is loaded, the running session of Emacs won't
8378 support the image type. Types 'pbm and 'xbm don't need to be
8379 listed; they are always supported. */);
8380 Vimage_library_alist = Qnil;
8381 Fput (intern_c_string ("image-library-alist"), Qrisky_local_variable, Qt);
8383 DEFVAR_LISP ("max-image-size", &Vmax_image_size,
8384 doc: /* Maximum size of images.
8385 Emacs will not load an image into memory if its pixel width or
8386 pixel height exceeds this limit.
8388 If the value is an integer, it directly specifies the maximum
8389 image height and width, measured in pixels. If it is a floating
8390 point number, it specifies the maximum image height and width
8391 as a ratio to the frame height and width. If the value is
8392 non-numeric, there is no explicit limit on the size of images. */);
8393 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8395 Vimage_type_cache = Qnil;
8396 staticpro (&Vimage_type_cache);
8398 Qpbm = intern_c_string ("pbm");
8399 staticpro (&Qpbm);
8400 ADD_IMAGE_TYPE (Qpbm);
8402 Qxbm = intern_c_string ("xbm");
8403 staticpro (&Qxbm);
8404 ADD_IMAGE_TYPE (Qxbm);
8406 define_image_type (&xbm_type, 1);
8407 define_image_type (&pbm_type, 1);
8409 Qcount = intern_c_string ("count");
8410 staticpro (&Qcount);
8412 QCascent = intern_c_string (":ascent");
8413 staticpro (&QCascent);
8414 QCmargin = intern_c_string (":margin");
8415 staticpro (&QCmargin);
8416 QCrelief = intern_c_string (":relief");
8417 staticpro (&QCrelief);
8418 QCconversion = intern_c_string (":conversion");
8419 staticpro (&QCconversion);
8420 QCcolor_symbols = intern_c_string (":color-symbols");
8421 staticpro (&QCcolor_symbols);
8422 QCheuristic_mask = intern_c_string (":heuristic-mask");
8423 staticpro (&QCheuristic_mask);
8424 QCindex = intern_c_string (":index");
8425 staticpro (&QCindex);
8426 QCmatrix = intern_c_string (":matrix");
8427 staticpro (&QCmatrix);
8428 QCcolor_adjustment = intern_c_string (":color-adjustment");
8429 staticpro (&QCcolor_adjustment);
8430 QCmask = intern_c_string (":mask");
8431 staticpro (&QCmask);
8433 Qlaplace = intern_c_string ("laplace");
8434 staticpro (&Qlaplace);
8435 Qemboss = intern_c_string ("emboss");
8436 staticpro (&Qemboss);
8437 Qedge_detection = intern_c_string ("edge-detection");
8438 staticpro (&Qedge_detection);
8439 Qheuristic = intern_c_string ("heuristic");
8440 staticpro (&Qheuristic);
8442 Qpostscript = intern_c_string ("postscript");
8443 staticpro (&Qpostscript);
8444 #ifdef HAVE_GHOSTSCRIPT
8445 ADD_IMAGE_TYPE (Qpostscript);
8446 QCloader = intern_c_string (":loader");
8447 staticpro (&QCloader);
8448 QCbounding_box = intern_c_string (":bounding-box");
8449 staticpro (&QCbounding_box);
8450 QCpt_width = intern_c_string (":pt-width");
8451 staticpro (&QCpt_width);
8452 QCpt_height = intern_c_string (":pt-height");
8453 staticpro (&QCpt_height);
8454 #endif /* HAVE_GHOSTSCRIPT */
8456 #if defined (HAVE_XPM) || defined (HAVE_NS)
8457 Qxpm = intern_c_string ("xpm");
8458 staticpro (&Qxpm);
8459 ADD_IMAGE_TYPE (Qxpm);
8460 #endif
8462 #if defined (HAVE_JPEG) || defined (HAVE_NS)
8463 Qjpeg = intern_c_string ("jpeg");
8464 staticpro (&Qjpeg);
8465 ADD_IMAGE_TYPE (Qjpeg);
8466 #endif
8468 #if defined (HAVE_TIFF) || defined (HAVE_NS)
8469 Qtiff = intern_c_string ("tiff");
8470 staticpro (&Qtiff);
8471 ADD_IMAGE_TYPE (Qtiff);
8472 #endif
8474 #if defined (HAVE_GIF) || defined (HAVE_NS)
8475 Qgif = intern_c_string ("gif");
8476 staticpro (&Qgif);
8477 ADD_IMAGE_TYPE (Qgif);
8478 #endif
8480 #if defined (HAVE_PNG) || defined (HAVE_NS)
8481 Qpng = intern_c_string ("png");
8482 staticpro (&Qpng);
8483 ADD_IMAGE_TYPE (Qpng);
8484 #endif
8486 #if defined (HAVE_RSVG)
8487 Qsvg = intern_c_string ("svg");
8488 staticpro (&Qsvg);
8489 ADD_IMAGE_TYPE (Qsvg);
8490 #ifdef HAVE_NTGUI
8491 /* Other libraries used directly by svg code. */
8492 Qgdk_pixbuf = intern_c_string ("gdk-pixbuf");
8493 staticpro (&Qgdk_pixbuf);
8494 Qglib = intern_c_string ("glib");
8495 staticpro (&Qglib);
8496 Qgobject = intern_c_string ("gobject");
8497 staticpro (&Qgobject);
8498 #endif /* HAVE_NTGUI */
8499 #endif /* HAVE_RSVG */
8501 defsubr (&Sinit_image_library);
8502 defsubr (&Sclear_image_cache);
8503 defsubr (&Simage_refresh);
8504 defsubr (&Simage_size);
8505 defsubr (&Simage_mask_p);
8506 defsubr (&Simage_extension_data);
8508 #if GLYPH_DEBUG
8509 defsubr (&Simagep);
8510 defsubr (&Slookup_image);
8511 #endif
8513 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
8514 doc: /* Non-nil means always draw a cross over disabled images.
8515 Disabled images are those having a `:conversion disabled' property.
8516 A cross is always drawn on black & white displays. */);
8517 cross_disabled_images = 0;
8519 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
8520 doc: /* List of directories to search for window system bitmap files. */);
8521 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8523 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
8524 doc: /* Time after which cached images are removed from the cache.
8525 When an image has not been displayed this many seconds, remove it
8526 from the image cache. Value must be an integer or nil with nil
8527 meaning don't clear the cache. */);
8528 Vimage_cache_eviction_delay = make_number (30 * 60);
8531 void
8532 init_image ()
8536 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
8537 (do not change this comment) */