(rfn-eshadow-regexp): Remove.
[emacs.git] / src / image.c
blob08d2a9f98136b5cdad769b727164de72a2793118
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 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
22 #include <config.h>
23 #include <stdio.h>
24 #include <math.h>
25 #include <ctype.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
31 /* This makes the fields of a Display accessible, in Xlib header files. */
33 #define XLIB_ILLEGAL_ACCESS
35 #include "lisp.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "dispextern.h"
39 #include "blockinput.h"
40 #include "systime.h"
41 #include <epaths.h>
44 #ifdef HAVE_X_WINDOWS
45 #include "xterm.h"
46 #include <sys/types.h>
47 #include <sys/stat.h>
49 #define COLOR_TABLE_SUPPORT 1
51 typedef struct x_bitmap_record Bitmap_Record;
52 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
53 #define NO_PIXMAP None
55 #define RGB_PIXEL_COLOR unsigned long
57 #define PIX_MASK_RETAIN 0
58 #define PIX_MASK_DRAW 1
59 #endif /* HAVE_X_WINDOWS */
62 #ifdef HAVE_NTGUI
63 #include "w32term.h"
65 /* W32_TODO : Color tables on W32. */
66 #undef COLOR_TABLE_SUPPORT
68 typedef struct w32_bitmap_record Bitmap_Record;
69 #define GET_PIXEL(ximg, x, y) GetPixel(ximg, x, y)
70 #define NO_PIXMAP 0
72 #define RGB_PIXEL_COLOR COLORREF
74 #define PIX_MASK_RETAIN 0
75 #define PIX_MASK_DRAW 1
77 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
78 #define x_defined_color w32_defined_color
79 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
80 #endif /* HAVE_NTGUI */
83 #ifdef MAC_OS
84 #include "macterm.h"
85 #include <sys/stat.h>
86 #ifndef MAC_OSX
87 #include <alloca.h>
88 #include <sys/param.h>
89 #endif
90 #if TARGET_API_MAC_CARBON
91 #ifdef MAC_OSX
92 #include <QuickTime/QuickTime.h>
93 #else /* not MAC_OSX */
94 #include <QuickTime.h>
95 #endif /* not MAC_OSX */
96 #else /* not TARGET_API_MAC_CARBON */
97 #include <Windows.h>
98 #include <Gestalt.h>
99 #include <TextUtils.h>
100 #include <ImageCompression.h>
101 #include <QuickTimeComponents.h>
102 #endif /* not TARGET_API_MAC_CARBON */
104 /* MAC_TODO : Color tables on Mac. */
105 #undef COLOR_TABLE_SUPPORT
107 #define ZPixmap 0 /* arbitrary */
108 typedef struct mac_bitmap_record Bitmap_Record;
110 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
111 #define NO_PIXMAP 0
113 #define RGB_PIXEL_COLOR unsigned long
115 /* A black pixel in a mask bitmap/pixmap means ``draw a source
116 pixel''. A white pixel means ``retain the current pixel''. */
117 #define PIX_MASK_DRAW RGB_TO_ULONG(0,0,0)
118 #define PIX_MASK_RETAIN RGB_TO_ULONG(255,255,255)
120 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
121 #define x_defined_color mac_defined_color
122 #define DefaultDepthOfScreen(screen) (one_mac_display_info.n_planes)
123 #define XDrawLine(display, w, gc, x1, y1, x2, y2) \
124 mac_draw_line_to_pixmap(display, w, gc, x1, y1, x2, y2)
126 #endif /* MAC_OS */
129 /* Search path for bitmap files. */
131 Lisp_Object Vx_bitmap_file_path;
134 static void x_disable_image P_ ((struct frame *, struct image *));
135 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
136 Lisp_Object));
138 static void init_color_table P_ ((void));
139 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
140 #ifdef COLOR_TABLE_SUPPORT
141 static void free_color_table P_ ((void));
142 static unsigned long *colors_in_color_table P_ ((int *n));
143 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
144 #endif
146 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
147 id, which is just an int that this section returns. Bitmaps are
148 reference counted so they can be shared among frames.
150 Bitmap indices are guaranteed to be > 0, so a negative number can
151 be used to indicate no bitmap.
153 If you use x_create_bitmap_from_data, then you must keep track of
154 the bitmaps yourself. That is, creating a bitmap from the same
155 data more than once will not be caught. */
157 #ifdef MAC_OS
159 static XImagePtr
160 XGetImage (display, pixmap, x, y, width, height, plane_mask, format)
161 Display *display; /* not used */
162 Pixmap pixmap;
163 int x, y; /* not used */
164 unsigned int width, height; /* not used */
165 unsigned long plane_mask; /* not used */
166 int format; /* not used */
168 #if GLYPH_DEBUG
169 xassert (x == 0 && y == 0);
171 Rect ri, rp;
172 SetRect (&ri, 0, 0, width, height);
173 xassert (EqualRect (&ri, GetPixBounds (GetGWorldPixMap (pixmap), &rp)));
175 xassert (! (pixelsLocked & GetPixelsState (GetGWorldPixMap (pixmap))));
176 #endif
178 LockPixels (GetGWorldPixMap (pixmap));
180 return pixmap;
183 static void
184 XPutPixel (ximage, x, y, pixel)
185 XImagePtr ximage;
186 int x, y;
187 unsigned long pixel;
189 PixMapHandle pixmap = GetGWorldPixMap (ximage);
190 short depth = GetPixDepth (pixmap);
192 if (depth == 32)
194 char *base_addr = GetPixBaseAddr (pixmap);
195 short row_bytes = GetPixRowBytes (pixmap);
197 ((unsigned long *) (base_addr + y * row_bytes))[x] = pixel;
199 else if (depth == 1)
201 char *base_addr = GetPixBaseAddr (pixmap);
202 short row_bytes = GetPixRowBytes (pixmap);
204 if (pixel == PIX_MASK_DRAW)
205 base_addr[y * row_bytes + x / 8] |= (1 << 7) >> (x & 7);
206 else
207 base_addr[y * row_bytes + x / 8] &= ~((1 << 7) >> (x & 7));
209 else
211 CGrafPtr old_port;
212 GDHandle old_gdh;
213 RGBColor color;
215 GetGWorld (&old_port, &old_gdh);
216 SetGWorld (ximage, NULL);
218 color.red = RED16_FROM_ULONG (pixel);
219 color.green = GREEN16_FROM_ULONG (pixel);
220 color.blue = BLUE16_FROM_ULONG (pixel);
222 SetCPixel (x, y, &color);
224 SetGWorld (old_port, old_gdh);
228 static unsigned long
229 XGetPixel (ximage, x, y)
230 XImagePtr ximage;
231 int x, y;
233 PixMapHandle pixmap = GetGWorldPixMap (ximage);
234 short depth = GetPixDepth (pixmap);
236 if (depth == 32)
238 char *base_addr = GetPixBaseAddr (pixmap);
239 short row_bytes = GetPixRowBytes (pixmap);
241 return ((unsigned long *) (base_addr + y * row_bytes))[x];
243 else if (depth == 1)
245 char *base_addr = GetPixBaseAddr (pixmap);
246 short row_bytes = GetPixRowBytes (pixmap);
248 if (base_addr[y * row_bytes + x / 8] & (1 << (~x & 7)))
249 return PIX_MASK_DRAW;
250 else
251 return PIX_MASK_RETAIN;
253 else
255 CGrafPtr old_port;
256 GDHandle old_gdh;
257 RGBColor color;
259 GetGWorld (&old_port, &old_gdh);
260 SetGWorld (ximage, NULL);
262 GetCPixel (x, y, &color);
264 SetGWorld (old_port, old_gdh);
265 return RGB_TO_ULONG (color.red >> 8, color.green >> 8, color.blue >> 8);
269 static void
270 XDestroyImage (ximg)
271 XImagePtr ximg;
273 UnlockPixels (GetGWorldPixMap (ximg));
275 #endif /* MAC_OS */
278 /* Functions to access the contents of a bitmap, given an id. */
281 x_bitmap_height (f, id)
282 FRAME_PTR f;
283 int id;
285 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
289 x_bitmap_width (f, id)
290 FRAME_PTR f;
291 int id;
293 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
296 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
298 x_bitmap_pixmap (f, id)
299 FRAME_PTR f;
300 int id;
302 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
304 #endif
306 #ifdef HAVE_X_WINDOWS
308 x_bitmap_mask (f, id)
309 FRAME_PTR f;
310 int id;
312 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
314 #endif
316 /* Allocate a new bitmap record. Returns index of new record. */
318 static int
319 x_allocate_bitmap_record (f)
320 FRAME_PTR f;
322 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
323 int i;
325 if (dpyinfo->bitmaps == NULL)
327 dpyinfo->bitmaps_size = 10;
328 dpyinfo->bitmaps
329 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
330 dpyinfo->bitmaps_last = 1;
331 return 1;
334 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
335 return ++dpyinfo->bitmaps_last;
337 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
338 if (dpyinfo->bitmaps[i].refcount == 0)
339 return i + 1;
341 dpyinfo->bitmaps_size *= 2;
342 dpyinfo->bitmaps
343 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
344 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
345 return ++dpyinfo->bitmaps_last;
348 /* Add one reference to the reference count of the bitmap with id ID. */
350 void
351 x_reference_bitmap (f, id)
352 FRAME_PTR f;
353 int id;
355 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
358 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
361 x_create_bitmap_from_data (f, bits, width, height)
362 struct frame *f;
363 char *bits;
364 unsigned int width, height;
366 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
367 int id;
369 #ifdef HAVE_X_WINDOWS
370 Pixmap bitmap;
371 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
372 bits, width, height);
373 if (! bitmap)
374 return -1;
375 #endif /* HAVE_X_WINDOWS */
377 #ifdef HAVE_NTGUI
378 Pixmap bitmap;
379 bitmap = CreateBitmap (width, height,
380 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
381 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
382 bits);
383 if (! bitmap)
384 return -1;
385 #endif /* HAVE_NTGUI */
387 #ifdef MAC_OS
388 /* MAC_TODO: for now fail if width is not mod 16 (toolbox requires it) */
389 if (width % 16 != 0)
390 return -1;
391 #endif
393 id = x_allocate_bitmap_record (f);
394 #ifdef MAC_OS
395 dpyinfo->bitmaps[id - 1].bitmap_data = (char *) xmalloc (height * width);
396 if (! dpyinfo->bitmaps[id - 1].bitmap_data)
397 return -1;
398 bcopy (bits, dpyinfo->bitmaps[id - 1].bitmap_data, height * width);
399 #endif /* MAC_OS */
401 dpyinfo->bitmaps[id - 1].file = NULL;
402 dpyinfo->bitmaps[id - 1].height = height;
403 dpyinfo->bitmaps[id - 1].width = width;
404 dpyinfo->bitmaps[id - 1].refcount = 1;
406 #ifdef HAVE_X_WINDOWS
407 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
408 dpyinfo->bitmaps[id - 1].have_mask = 0;
409 dpyinfo->bitmaps[id - 1].depth = 1;
410 #endif /* HAVE_X_WINDOWS */
412 #ifdef HAVE_NTGUI
413 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
414 dpyinfo->bitmaps[id - 1].hinst = NULL;
415 dpyinfo->bitmaps[id - 1].depth = 1;
416 #endif /* HAVE_NTGUI */
418 return id;
421 /* Create bitmap from file FILE for frame F. */
424 x_create_bitmap_from_file (f, file)
425 struct frame *f;
426 Lisp_Object file;
428 #ifdef MAC_OS
429 return -1; /* MAC_TODO : bitmap support */
430 #endif /* MAC_OS */
432 #ifdef HAVE_NTGUI
433 return -1; /* W32_TODO : bitmap support */
434 #endif /* HAVE_NTGUI */
436 #ifdef HAVE_X_WINDOWS
437 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
438 unsigned int width, height;
439 Pixmap bitmap;
440 int xhot, yhot, result, id;
441 Lisp_Object found;
442 int fd;
443 char *filename;
445 /* Look for an existing bitmap with the same name. */
446 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
448 if (dpyinfo->bitmaps[id].refcount
449 && dpyinfo->bitmaps[id].file
450 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
452 ++dpyinfo->bitmaps[id].refcount;
453 return id + 1;
457 /* Search bitmap-file-path for the file, if appropriate. */
458 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
459 if (fd < 0)
460 return -1;
461 emacs_close (fd);
463 filename = (char *) SDATA (found);
465 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
466 filename, &width, &height, &bitmap, &xhot, &yhot);
467 if (result != BitmapSuccess)
468 return -1;
470 id = x_allocate_bitmap_record (f);
471 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
472 dpyinfo->bitmaps[id - 1].have_mask = 0;
473 dpyinfo->bitmaps[id - 1].refcount = 1;
474 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
475 dpyinfo->bitmaps[id - 1].depth = 1;
476 dpyinfo->bitmaps[id - 1].height = height;
477 dpyinfo->bitmaps[id - 1].width = width;
478 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
480 return id;
481 #endif /* HAVE_X_WINDOWS */
484 /* Free bitmap B. */
486 static void
487 Free_Bitmap_Record (dpyinfo, bm)
488 Display_Info *dpyinfo;
489 Bitmap_Record *bm;
491 #ifdef HAVE_X_WINDOWS
492 XFreePixmap (dpyinfo->display, bm->pixmap);
493 if (bm->have_mask)
494 XFreePixmap (dpyinfo->display, bm->mask);
495 #endif /* HAVE_X_WINDOWS */
497 #ifdef HAVE_NTGUI
498 DeleteObject (bm->pixmap);
499 #endif /* HAVE_NTGUI */
501 #ifdef MAC_OS
502 xfree (bm->bitmap_data); /* Added ++kfs */
503 bm->bitmap_data = NULL;
504 #endif /* MAC_OS */
506 if (bm->file)
508 xfree (bm->file);
509 bm->file = NULL;
513 /* Remove reference to bitmap with id number ID. */
515 void
516 x_destroy_bitmap (f, id)
517 FRAME_PTR f;
518 int id;
520 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
522 if (id > 0)
524 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
526 if (--bm->refcount == 0)
528 BLOCK_INPUT;
529 Free_Bitmap_Record (dpyinfo, bm);
530 UNBLOCK_INPUT;
535 /* Free all the bitmaps for the display specified by DPYINFO. */
537 void
538 x_destroy_all_bitmaps (dpyinfo)
539 Display_Info *dpyinfo;
541 int i;
542 Bitmap_Record *bm = dpyinfo->bitmaps;
544 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
545 if (bm->refcount > 0)
546 Free_Bitmap_Record (dpyinfo, bm);
548 dpyinfo->bitmaps_last = 0;
552 #ifdef HAVE_X_WINDOWS
554 /* Useful functions defined in the section
555 `Image type independent image structures' below. */
557 static unsigned long four_corners_best P_ ((XImagePtr ximg, unsigned long width,
558 unsigned long height));
560 static int x_create_x_image_and_pixmap P_ ((struct frame *f, int width, int height,
561 int depth, XImagePtr *ximg,
562 Pixmap *pixmap));
564 static void x_destroy_x_image P_ ((XImagePtr ximg));
567 /* Create a mask of a bitmap. Note is this not a perfect mask.
568 It's nicer with some borders in this context */
571 x_create_bitmap_mask (f, id)
572 struct frame *f;
573 int id;
575 Pixmap pixmap, mask;
576 XImagePtr ximg, mask_img;
577 unsigned long width, height;
578 int result;
579 unsigned long bg;
580 unsigned long x, y, xp, xm, yp, ym;
581 GC gc;
583 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
585 if (!(id > 0))
586 return -1;
588 pixmap = x_bitmap_pixmap (f, id);
589 width = x_bitmap_width (f, id);
590 height = x_bitmap_height (f, id);
592 BLOCK_INPUT;
593 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
594 ~0, ZPixmap);
596 if (!ximg)
598 UNBLOCK_INPUT;
599 return -1;
602 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
604 UNBLOCK_INPUT;
605 if (!result)
607 XDestroyImage (ximg);
608 return -1;
611 bg = four_corners_best (ximg, width, height);
613 for (y = 0; y < ximg->height; ++y)
615 for (x = 0; x < ximg->width; ++x)
617 xp = x != ximg->width - 1 ? x + 1 : 0;
618 xm = x != 0 ? x - 1 : ximg->width - 1;
619 yp = y != ximg->height - 1 ? y + 1 : 0;
620 ym = y != 0 ? y - 1 : ximg->height - 1;
621 if (XGetPixel (ximg, x, y) == bg
622 && XGetPixel (ximg, x, yp) == bg
623 && XGetPixel (ximg, x, ym) == bg
624 && XGetPixel (ximg, xp, y) == bg
625 && XGetPixel (ximg, xp, yp) == bg
626 && XGetPixel (ximg, xp, ym) == bg
627 && XGetPixel (ximg, xm, y) == bg
628 && XGetPixel (ximg, xm, yp) == bg
629 && XGetPixel (ximg, xm, ym) == bg)
630 XPutPixel (mask_img, x, y, 0);
631 else
632 XPutPixel (mask_img, x, y, 1);
636 xassert (interrupt_input_blocked);
637 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
638 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
639 width, height);
640 XFreeGC (FRAME_X_DISPLAY (f), gc);
642 dpyinfo->bitmaps[id - 1].have_mask = 1;
643 dpyinfo->bitmaps[id - 1].mask = mask;
645 XDestroyImage (ximg);
646 x_destroy_x_image (mask_img);
648 return 0;
651 #endif /* HAVE_X_WINDOWS */
654 /***********************************************************************
655 Image types
656 ***********************************************************************/
658 /* Value is the number of elements of vector VECTOR. */
660 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
662 /* List of supported image types. Use define_image_type to add new
663 types. Use lookup_image_type to find a type for a given symbol. */
665 static struct image_type *image_types;
667 /* A list of symbols, one for each supported image type. */
669 Lisp_Object Vimage_types;
671 /* An alist of image types and libraries that implement the type. */
673 Lisp_Object Vimage_library_alist;
675 /* Cache for delayed-loading image types. */
677 static Lisp_Object Vimage_type_cache;
679 /* The symbol `xbm' which is used as the type symbol for XBM images. */
681 Lisp_Object Qxbm;
683 /* Keywords. */
685 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
686 extern Lisp_Object QCdata, QCtype;
687 extern Lisp_Object Qcenter;
688 Lisp_Object QCascent, QCmargin, QCrelief;
689 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
690 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
692 /* Other symbols. */
694 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
696 /* Time in seconds after which images should be removed from the cache
697 if not displayed. */
699 Lisp_Object Vimage_cache_eviction_delay;
701 /* Function prototypes. */
703 static Lisp_Object define_image_type P_ ((struct image_type *type, int loaded));
704 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
705 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
706 static void x_laplace P_ ((struct frame *, struct image *));
707 static void x_emboss P_ ((struct frame *, struct image *));
708 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
709 Lisp_Object));
711 #define CACHE_IMAGE_TYPE(type, status) \
712 do { Vimage_type_cache = Fcons (Fcons (type, status), Vimage_type_cache); } while (0)
714 #define ADD_IMAGE_TYPE(type) \
715 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
717 /* Define a new image type from TYPE. This adds a copy of TYPE to
718 image_types and caches the loading status of TYPE. */
720 static Lisp_Object
721 define_image_type (type, loaded)
722 struct image_type *type;
723 int loaded;
725 Lisp_Object success;
727 if (!loaded)
728 success = Qnil;
729 else
731 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
732 The initialized data segment is read-only. */
733 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
734 bcopy (type, p, sizeof *p);
735 p->next = image_types;
736 image_types = p;
737 success = Qt;
740 CACHE_IMAGE_TYPE (*type->type, success);
741 return success;
745 /* Look up image type SYMBOL, and return a pointer to its image_type
746 structure. Value is null if SYMBOL is not a known image type. */
748 static INLINE struct image_type *
749 lookup_image_type (symbol)
750 Lisp_Object symbol;
752 struct image_type *type;
754 /* We must initialize the image-type if it hasn't been already. */
755 if (NILP (Finit_image_library (symbol, Vimage_library_alist)))
756 return 0; /* unimplemented */
758 for (type = image_types; type; type = type->next)
759 if (EQ (symbol, *type->type))
760 break;
762 return type;
766 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
767 valid image specification is a list whose car is the symbol
768 `image', and whose rest is a property list. The property list must
769 contain a value for key `:type'. That value must be the name of a
770 supported image type. The rest of the property list depends on the
771 image type. */
774 valid_image_p (object)
775 Lisp_Object object;
777 int valid_p = 0;
779 if (IMAGEP (object))
781 Lisp_Object tem;
783 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
784 if (EQ (XCAR (tem), QCtype))
786 tem = XCDR (tem);
787 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
789 struct image_type *type;
790 type = lookup_image_type (XCAR (tem));
791 if (type)
792 valid_p = type->valid_p (object);
795 break;
799 return valid_p;
803 /* Log error message with format string FORMAT and argument ARG.
804 Signaling an error, e.g. when an image cannot be loaded, is not a
805 good idea because this would interrupt redisplay, and the error
806 message display would lead to another redisplay. This function
807 therefore simply displays a message. */
809 static void
810 image_error (format, arg1, arg2)
811 char *format;
812 Lisp_Object arg1, arg2;
814 add_to_log (format, arg1, arg2);
819 /***********************************************************************
820 Image specifications
821 ***********************************************************************/
823 enum image_value_type
825 IMAGE_DONT_CHECK_VALUE_TYPE,
826 IMAGE_STRING_VALUE,
827 IMAGE_STRING_OR_NIL_VALUE,
828 IMAGE_SYMBOL_VALUE,
829 IMAGE_POSITIVE_INTEGER_VALUE,
830 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
831 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
832 IMAGE_ASCENT_VALUE,
833 IMAGE_INTEGER_VALUE,
834 IMAGE_FUNCTION_VALUE,
835 IMAGE_NUMBER_VALUE,
836 IMAGE_BOOL_VALUE
839 /* Structure used when parsing image specifications. */
841 struct image_keyword
843 /* Name of keyword. */
844 char *name;
846 /* The type of value allowed. */
847 enum image_value_type type;
849 /* Non-zero means key must be present. */
850 int mandatory_p;
852 /* Used to recognize duplicate keywords in a property list. */
853 int count;
855 /* The value that was found. */
856 Lisp_Object value;
860 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
861 int, Lisp_Object));
862 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
865 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
866 has the format (image KEYWORD VALUE ...). One of the keyword/
867 value pairs must be `:type TYPE'. KEYWORDS is a vector of
868 image_keywords structures of size NKEYWORDS describing other
869 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
871 static int
872 parse_image_spec (spec, keywords, nkeywords, type)
873 Lisp_Object spec;
874 struct image_keyword *keywords;
875 int nkeywords;
876 Lisp_Object type;
878 int i;
879 Lisp_Object plist;
881 if (!IMAGEP (spec))
882 return 0;
884 plist = XCDR (spec);
885 while (CONSP (plist))
887 Lisp_Object key, value;
889 /* First element of a pair must be a symbol. */
890 key = XCAR (plist);
891 plist = XCDR (plist);
892 if (!SYMBOLP (key))
893 return 0;
895 /* There must follow a value. */
896 if (!CONSP (plist))
897 return 0;
898 value = XCAR (plist);
899 plist = XCDR (plist);
901 /* Find key in KEYWORDS. Error if not found. */
902 for (i = 0; i < nkeywords; ++i)
903 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
904 break;
906 if (i == nkeywords)
907 continue;
909 /* Record that we recognized the keyword. If a keywords
910 was found more than once, it's an error. */
911 keywords[i].value = value;
912 ++keywords[i].count;
914 if (keywords[i].count > 1)
915 return 0;
917 /* Check type of value against allowed type. */
918 switch (keywords[i].type)
920 case IMAGE_STRING_VALUE:
921 if (!STRINGP (value))
922 return 0;
923 break;
925 case IMAGE_STRING_OR_NIL_VALUE:
926 if (!STRINGP (value) && !NILP (value))
927 return 0;
928 break;
930 case IMAGE_SYMBOL_VALUE:
931 if (!SYMBOLP (value))
932 return 0;
933 break;
935 case IMAGE_POSITIVE_INTEGER_VALUE:
936 if (!INTEGERP (value) || XINT (value) <= 0)
937 return 0;
938 break;
940 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
941 if (INTEGERP (value) && XINT (value) >= 0)
942 break;
943 if (CONSP (value)
944 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
945 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
946 break;
947 return 0;
949 case IMAGE_ASCENT_VALUE:
950 if (SYMBOLP (value) && EQ (value, Qcenter))
951 break;
952 else if (INTEGERP (value)
953 && XINT (value) >= 0
954 && XINT (value) <= 100)
955 break;
956 return 0;
958 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
959 if (!INTEGERP (value) || XINT (value) < 0)
960 return 0;
961 break;
963 case IMAGE_DONT_CHECK_VALUE_TYPE:
964 break;
966 case IMAGE_FUNCTION_VALUE:
967 value = indirect_function (value);
968 if (SUBRP (value)
969 || COMPILEDP (value)
970 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
971 break;
972 return 0;
974 case IMAGE_NUMBER_VALUE:
975 if (!INTEGERP (value) && !FLOATP (value))
976 return 0;
977 break;
979 case IMAGE_INTEGER_VALUE:
980 if (!INTEGERP (value))
981 return 0;
982 break;
984 case IMAGE_BOOL_VALUE:
985 if (!NILP (value) && !EQ (value, Qt))
986 return 0;
987 break;
989 default:
990 abort ();
991 break;
994 if (EQ (key, QCtype) && !EQ (type, value))
995 return 0;
998 /* Check that all mandatory fields are present. */
999 for (i = 0; i < nkeywords; ++i)
1000 if (keywords[i].mandatory_p && keywords[i].count == 0)
1001 return 0;
1003 return NILP (plist);
1007 /* Return the value of KEY in image specification SPEC. Value is nil
1008 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
1009 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
1011 static Lisp_Object
1012 image_spec_value (spec, key, found)
1013 Lisp_Object spec, key;
1014 int *found;
1016 Lisp_Object tail;
1018 xassert (valid_image_p (spec));
1020 for (tail = XCDR (spec);
1021 CONSP (tail) && CONSP (XCDR (tail));
1022 tail = XCDR (XCDR (tail)))
1024 if (EQ (XCAR (tail), key))
1026 if (found)
1027 *found = 1;
1028 return XCAR (XCDR (tail));
1032 if (found)
1033 *found = 0;
1034 return Qnil;
1038 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
1039 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
1040 PIXELS non-nil means return the size in pixels, otherwise return the
1041 size in canonical character units.
1042 FRAME is the frame on which the image will be displayed. FRAME nil
1043 or omitted means use the selected frame. */)
1044 (spec, pixels, frame)
1045 Lisp_Object spec, pixels, frame;
1047 Lisp_Object size;
1049 size = Qnil;
1050 if (valid_image_p (spec))
1052 struct frame *f = check_x_frame (frame);
1053 int id = lookup_image (f, spec);
1054 struct image *img = IMAGE_FROM_ID (f, id);
1055 int width = img->width + 2 * img->hmargin;
1056 int height = img->height + 2 * img->vmargin;
1058 if (NILP (pixels))
1059 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
1060 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
1061 else
1062 size = Fcons (make_number (width), make_number (height));
1064 else
1065 error ("Invalid image specification");
1067 return size;
1071 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
1072 doc: /* Return t if image SPEC has a mask bitmap.
1073 FRAME is the frame on which the image will be displayed. FRAME nil
1074 or omitted means use the selected frame. */)
1075 (spec, frame)
1076 Lisp_Object spec, frame;
1078 Lisp_Object mask;
1080 mask = Qnil;
1081 if (valid_image_p (spec))
1083 struct frame *f = check_x_frame (frame);
1084 int id = lookup_image (f, spec);
1085 struct image *img = IMAGE_FROM_ID (f, id);
1086 if (img->mask)
1087 mask = Qt;
1089 else
1090 error ("Invalid image specification");
1092 return mask;
1096 /***********************************************************************
1097 Image type independent image structures
1098 ***********************************************************************/
1100 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
1101 static void free_image P_ ((struct frame *f, struct image *img));
1102 static int check_image_size P_ ((struct frame *f, int width, int height));
1104 #define MAX_IMAGE_SIZE 6.0
1105 Lisp_Object Vmax_image_size;
1107 /* Allocate and return a new image structure for image specification
1108 SPEC. SPEC has a hash value of HASH. */
1110 static struct image *
1111 make_image (spec, hash)
1112 Lisp_Object spec;
1113 unsigned hash;
1115 struct image *img = (struct image *) xmalloc (sizeof *img);
1117 xassert (valid_image_p (spec));
1118 bzero (img, sizeof *img);
1119 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1120 xassert (img->type != NULL);
1121 img->spec = spec;
1122 img->data.lisp_val = Qnil;
1123 img->ascent = DEFAULT_IMAGE_ASCENT;
1124 img->hash = hash;
1125 return img;
1129 /* Free image IMG which was used on frame F, including its resources. */
1131 static void
1132 free_image (f, img)
1133 struct frame *f;
1134 struct image *img;
1136 if (img)
1138 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1140 /* Remove IMG from the hash table of its cache. */
1141 if (img->prev)
1142 img->prev->next = img->next;
1143 else
1144 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1146 if (img->next)
1147 img->next->prev = img->prev;
1149 c->images[img->id] = NULL;
1151 /* Free resources, then free IMG. */
1152 img->type->free (f, img);
1153 xfree (img);
1157 /* Return 1 if the given widths and heights are valid for display;
1158 otherwise, return 0. */
1161 check_image_size (f, width, height)
1162 struct frame *f;
1163 int width;
1164 int height;
1166 int w, h;
1168 if (width <= 0 || height <= 0)
1169 return 0;
1171 if (INTEGERP (Vmax_image_size))
1172 w = h = XINT (Vmax_image_size);
1173 else if (FLOATP (Vmax_image_size))
1175 if (f != NULL)
1177 w = FRAME_PIXEL_WIDTH (f);
1178 h = FRAME_PIXEL_HEIGHT (f);
1180 else
1181 w = h = 1024; /* Arbitrary size for unknown frame. */
1182 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1183 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1185 else
1186 return 1;
1188 return (width <= w && height <= h);
1191 /* Prepare image IMG for display on frame F. Must be called before
1192 drawing an image. */
1194 void
1195 prepare_image_for_display (f, img)
1196 struct frame *f;
1197 struct image *img;
1199 EMACS_TIME t;
1201 /* We're about to display IMG, so set its timestamp to `now'. */
1202 EMACS_GET_TIME (t);
1203 img->timestamp = EMACS_SECS (t);
1205 /* If IMG doesn't have a pixmap yet, load it now, using the image
1206 type dependent loader function. */
1207 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1208 img->load_failed_p = img->type->load (f, img) == 0;
1212 /* Value is the number of pixels for the ascent of image IMG when
1213 drawn in face FACE. */
1216 image_ascent (img, face, slice)
1217 struct image *img;
1218 struct face *face;
1219 struct glyph_slice *slice;
1221 int height;
1222 int ascent;
1224 if (slice->height == img->height)
1225 height = img->height + img->vmargin;
1226 else if (slice->y == 0)
1227 height = slice->height + img->vmargin;
1228 else
1229 height = slice->height;
1231 if (img->ascent == CENTERED_IMAGE_ASCENT)
1233 if (face->font)
1235 #ifdef HAVE_NTGUI
1236 /* W32 specific version. Why?. ++kfs */
1237 ascent = height / 2 - (FONT_DESCENT(face->font)
1238 - FONT_BASE(face->font)) / 2;
1239 #else
1240 /* This expression is arranged so that if the image can't be
1241 exactly centered, it will be moved slightly up. This is
1242 because a typical font is `top-heavy' (due to the presence
1243 uppercase letters), so the image placement should err towards
1244 being top-heavy too. It also just generally looks better. */
1245 ascent = (height + face->font->ascent - face->font->descent + 1) / 2;
1246 #endif /* HAVE_NTGUI */
1248 else
1249 ascent = height / 2;
1251 else
1252 ascent = (int) (height * img->ascent / 100.0);
1254 return ascent;
1258 /* Image background colors. */
1260 /* Find the "best" corner color of a bitmap.
1261 On W32, XIMG is assumed to a device context with the bitmap selected. */
1263 static RGB_PIXEL_COLOR
1264 four_corners_best (ximg, width, height)
1265 XImagePtr_or_DC ximg;
1266 unsigned long width, height;
1268 RGB_PIXEL_COLOR corners[4], best;
1269 int i, best_count;
1271 /* Get the colors at the corners of ximg. */
1272 corners[0] = GET_PIXEL (ximg, 0, 0);
1273 corners[1] = GET_PIXEL (ximg, width - 1, 0);
1274 corners[2] = GET_PIXEL (ximg, width - 1, height - 1);
1275 corners[3] = GET_PIXEL (ximg, 0, height - 1);
1277 /* Choose the most frequently found color as background. */
1278 for (i = best_count = 0; i < 4; ++i)
1280 int j, n;
1282 for (j = n = 0; j < 4; ++j)
1283 if (corners[i] == corners[j])
1284 ++n;
1286 if (n > best_count)
1287 best = corners[i], best_count = n;
1290 return best;
1293 /* Portability macros */
1295 #ifdef HAVE_NTGUI
1297 #define Destroy_Image(img_dc, prev) \
1298 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1300 #define Free_Pixmap(display, pixmap) \
1301 DeleteObject (pixmap)
1303 #else
1305 #define Destroy_Image(ximg, dummy) \
1306 XDestroyImage (ximg)
1308 #define Free_Pixmap(display, pixmap) \
1309 XFreePixmap (display, pixmap)
1311 #endif /* HAVE_NTGUI */
1314 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1315 it is guessed heuristically. If non-zero, XIMG is an existing
1316 XImage object (or device context with the image selected on W32) to
1317 use for the heuristic. */
1319 RGB_PIXEL_COLOR
1320 image_background (img, f, ximg)
1321 struct image *img;
1322 struct frame *f;
1323 XImagePtr_or_DC ximg;
1325 if (! img->background_valid)
1326 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1328 int free_ximg = !ximg;
1329 #ifdef HAVE_NTGUI
1330 HGDIOBJ prev;
1331 #endif /* HAVE_NTGUI */
1333 if (free_ximg)
1335 #ifndef HAVE_NTGUI
1336 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1337 0, 0, img->width, img->height, ~0, ZPixmap);
1338 #else
1339 HDC frame_dc = get_frame_dc (f);
1340 ximg = CreateCompatibleDC (frame_dc);
1341 release_frame_dc (f, frame_dc);
1342 prev = SelectObject (ximg, img->pixmap);
1343 #endif /* !HAVE_NTGUI */
1346 img->background = four_corners_best (ximg, img->width, img->height);
1348 if (free_ximg)
1349 Destroy_Image (ximg, prev);
1351 img->background_valid = 1;
1354 return img->background;
1357 /* Return the `background_transparent' field of IMG. If IMG doesn't
1358 have one yet, it is guessed heuristically. If non-zero, MASK is an
1359 existing XImage object to use for the heuristic. */
1362 image_background_transparent (img, f, mask)
1363 struct image *img;
1364 struct frame *f;
1365 XImagePtr_or_DC mask;
1367 if (! img->background_transparent_valid)
1368 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1370 if (img->mask)
1372 int free_mask = !mask;
1373 #ifdef HAVE_NTGUI
1374 HGDIOBJ prev;
1375 #endif /* HAVE_NTGUI */
1377 if (free_mask)
1379 #ifndef HAVE_NTGUI
1380 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1381 0, 0, img->width, img->height, ~0, ZPixmap);
1382 #else
1383 HDC frame_dc = get_frame_dc (f);
1384 mask = CreateCompatibleDC (frame_dc);
1385 release_frame_dc (f, frame_dc);
1386 prev = SelectObject (mask, img->mask);
1387 #endif /* HAVE_NTGUI */
1390 img->background_transparent
1391 = (four_corners_best (mask, img->width, img->height) == PIX_MASK_RETAIN);
1393 if (free_mask)
1394 Destroy_Image (mask, prev);
1396 else
1397 img->background_transparent = 0;
1399 img->background_transparent_valid = 1;
1402 return img->background_transparent;
1406 /***********************************************************************
1407 Helper functions for X image types
1408 ***********************************************************************/
1410 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
1411 int, int));
1412 static void x_clear_image P_ ((struct frame *f, struct image *img));
1413 static unsigned long x_alloc_image_color P_ ((struct frame *f,
1414 struct image *img,
1415 Lisp_Object color_name,
1416 unsigned long dflt));
1419 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1420 free the pixmap if any. MASK_P non-zero means clear the mask
1421 pixmap if any. COLORS_P non-zero means free colors allocated for
1422 the image, if any. */
1424 static void
1425 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
1426 struct frame *f;
1427 struct image *img;
1428 int pixmap_p, mask_p, colors_p;
1430 if (pixmap_p && img->pixmap)
1432 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1433 img->pixmap = NO_PIXMAP;
1434 img->background_valid = 0;
1437 if (mask_p && img->mask)
1439 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1440 img->mask = NO_PIXMAP;
1441 img->background_transparent_valid = 0;
1444 if (colors_p && img->ncolors)
1446 /* MAC_TODO: color table support. */
1447 /* W32_TODO: color table support. */
1448 #ifdef HAVE_X_WINDOWS
1449 x_free_colors (f, img->colors, img->ncolors);
1450 #endif /* HAVE_X_WINDOWS */
1451 xfree (img->colors);
1452 img->colors = NULL;
1453 img->ncolors = 0;
1457 /* Free X resources of image IMG which is used on frame F. */
1459 static void
1460 x_clear_image (f, img)
1461 struct frame *f;
1462 struct image *img;
1464 BLOCK_INPUT;
1465 x_clear_image_1 (f, img, 1, 1, 1);
1466 UNBLOCK_INPUT;
1470 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1471 cannot be allocated, use DFLT. Add a newly allocated color to
1472 IMG->colors, so that it can be freed again. Value is the pixel
1473 color. */
1475 static unsigned long
1476 x_alloc_image_color (f, img, color_name, dflt)
1477 struct frame *f;
1478 struct image *img;
1479 Lisp_Object color_name;
1480 unsigned long dflt;
1482 XColor color;
1483 unsigned long result;
1485 xassert (STRINGP (color_name));
1487 if (x_defined_color (f, SDATA (color_name), &color, 1))
1489 /* This isn't called frequently so we get away with simply
1490 reallocating the color vector to the needed size, here. */
1491 ++img->ncolors;
1492 img->colors =
1493 (unsigned long *) xrealloc (img->colors,
1494 img->ncolors * sizeof *img->colors);
1495 img->colors[img->ncolors - 1] = color.pixel;
1496 result = color.pixel;
1498 else
1499 result = dflt;
1501 return result;
1506 /***********************************************************************
1507 Image Cache
1508 ***********************************************************************/
1510 static void cache_image P_ ((struct frame *f, struct image *img));
1511 static void postprocess_image P_ ((struct frame *, struct image *));
1513 /* Return a new, initialized image cache that is allocated from the
1514 heap. Call free_image_cache to free an image cache. */
1516 struct image_cache *
1517 make_image_cache ()
1519 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1520 int size;
1522 bzero (c, sizeof *c);
1523 c->size = 50;
1524 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1525 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1526 c->buckets = (struct image **) xmalloc (size);
1527 bzero (c->buckets, size);
1528 return c;
1532 /* Free image cache of frame F. Be aware that X frames share images
1533 caches. */
1535 void
1536 free_image_cache (f)
1537 struct frame *f;
1539 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1540 if (c)
1542 int i;
1544 /* Cache should not be referenced by any frame when freed. */
1545 xassert (c->refcount == 0);
1547 for (i = 0; i < c->used; ++i)
1548 free_image (f, c->images[i]);
1549 xfree (c->images);
1550 xfree (c->buckets);
1551 xfree (c);
1552 FRAME_X_IMAGE_CACHE (f) = NULL;
1557 /* Clear image cache of frame F. FORCE_P non-zero means free all
1558 images. FORCE_P zero means clear only images that haven't been
1559 displayed for some time. Should be called from time to time to
1560 reduce the number of loaded images. If image-eviction-seconds is
1561 non-nil, this frees images in the cache which weren't displayed for
1562 at least that many seconds. */
1564 void
1565 clear_image_cache (f, force_p)
1566 struct frame *f;
1567 int force_p;
1569 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1571 if (c && INTEGERP (Vimage_cache_eviction_delay))
1573 EMACS_TIME t;
1574 unsigned long old;
1575 int i, nfreed;
1577 EMACS_GET_TIME (t);
1578 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
1580 /* Block input so that we won't be interrupted by a SIGIO
1581 while being in an inconsistent state. */
1582 BLOCK_INPUT;
1584 for (i = nfreed = 0; i < c->used; ++i)
1586 struct image *img = c->images[i];
1587 if (img != NULL
1588 && (force_p || img->timestamp < old))
1590 free_image (f, img);
1591 ++nfreed;
1595 /* We may be clearing the image cache because, for example,
1596 Emacs was iconified for a longer period of time. In that
1597 case, current matrices may still contain references to
1598 images freed above. So, clear these matrices. */
1599 if (nfreed)
1601 Lisp_Object tail, frame;
1603 FOR_EACH_FRAME (tail, frame)
1605 struct frame *f = XFRAME (frame);
1606 if (FRAME_WINDOW_P (f)
1607 && FRAME_X_IMAGE_CACHE (f) == c)
1608 clear_current_matrices (f);
1611 ++windows_or_buffers_changed;
1614 UNBLOCK_INPUT;
1619 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1620 0, 1, 0,
1621 doc: /* Clear the image cache of FRAME.
1622 FRAME nil or omitted means use the selected frame.
1623 FRAME t means clear the image caches of all frames. */)
1624 (frame)
1625 Lisp_Object frame;
1627 if (EQ (frame, Qt))
1629 Lisp_Object tail;
1631 FOR_EACH_FRAME (tail, frame)
1632 if (FRAME_WINDOW_P (XFRAME (frame)))
1633 clear_image_cache (XFRAME (frame), 1);
1635 else
1636 clear_image_cache (check_x_frame (frame), 1);
1638 return Qnil;
1642 /* Compute masks and transform image IMG on frame F, as specified
1643 by the image's specification, */
1645 static void
1646 postprocess_image (f, img)
1647 struct frame *f;
1648 struct image *img;
1650 /* Manipulation of the image's mask. */
1651 if (img->pixmap)
1653 Lisp_Object conversion, spec;
1654 Lisp_Object mask;
1656 spec = img->spec;
1658 /* `:heuristic-mask t'
1659 `:mask heuristic'
1660 means build a mask heuristically.
1661 `:heuristic-mask (R G B)'
1662 `:mask (heuristic (R G B))'
1663 means build a mask from color (R G B) in the
1664 image.
1665 `:mask nil'
1666 means remove a mask, if any. */
1668 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1669 if (!NILP (mask))
1670 x_build_heuristic_mask (f, img, mask);
1671 else
1673 int found_p;
1675 mask = image_spec_value (spec, QCmask, &found_p);
1677 if (EQ (mask, Qheuristic))
1678 x_build_heuristic_mask (f, img, Qt);
1679 else if (CONSP (mask)
1680 && EQ (XCAR (mask), Qheuristic))
1682 if (CONSP (XCDR (mask)))
1683 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1684 else
1685 x_build_heuristic_mask (f, img, XCDR (mask));
1687 else if (NILP (mask) && found_p && img->mask)
1689 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1690 img->mask = NO_PIXMAP;
1695 /* Should we apply an image transformation algorithm? */
1696 conversion = image_spec_value (spec, QCconversion, NULL);
1697 if (EQ (conversion, Qdisabled))
1698 x_disable_image (f, img);
1699 else if (EQ (conversion, Qlaplace))
1700 x_laplace (f, img);
1701 else if (EQ (conversion, Qemboss))
1702 x_emboss (f, img);
1703 else if (CONSP (conversion)
1704 && EQ (XCAR (conversion), Qedge_detection))
1706 Lisp_Object tem;
1707 tem = XCDR (conversion);
1708 if (CONSP (tem))
1709 x_edge_detection (f, img,
1710 Fplist_get (tem, QCmatrix),
1711 Fplist_get (tem, QCcolor_adjustment));
1717 /* Return the id of image with Lisp specification SPEC on frame F.
1718 SPEC must be a valid Lisp image specification (see valid_image_p). */
1721 lookup_image (f, spec)
1722 struct frame *f;
1723 Lisp_Object spec;
1725 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1726 struct image *img;
1727 int i;
1728 unsigned hash;
1729 struct gcpro gcpro1;
1730 EMACS_TIME now;
1732 /* F must be a window-system frame, and SPEC must be a valid image
1733 specification. */
1734 xassert (FRAME_WINDOW_P (f));
1735 xassert (valid_image_p (spec));
1737 GCPRO1 (spec);
1739 /* Look up SPEC in the hash table of the image cache. */
1740 hash = sxhash (spec, 0);
1741 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1743 for (img = c->buckets[i]; img; img = img->next)
1744 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
1745 break;
1747 if (img && img->load_failed_p)
1749 free_image (f, img);
1750 img = NULL;
1753 /* If not found, create a new image and cache it. */
1754 if (img == NULL)
1756 extern Lisp_Object Qpostscript;
1758 BLOCK_INPUT;
1759 img = make_image (spec, hash);
1760 cache_image (f, img);
1761 img->load_failed_p = img->type->load (f, img) == 0;
1763 /* If we can't load the image, and we don't have a width and
1764 height, use some arbitrary width and height so that we can
1765 draw a rectangle for it. */
1766 if (img->load_failed_p)
1768 Lisp_Object value;
1770 value = image_spec_value (spec, QCwidth, NULL);
1771 img->width = (INTEGERP (value)
1772 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1773 value = image_spec_value (spec, QCheight, NULL);
1774 img->height = (INTEGERP (value)
1775 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1777 else
1779 /* Handle image type independent image attributes
1780 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1781 `:background COLOR'. */
1782 Lisp_Object ascent, margin, relief, bg;
1784 ascent = image_spec_value (spec, QCascent, NULL);
1785 if (INTEGERP (ascent))
1786 img->ascent = XFASTINT (ascent);
1787 else if (EQ (ascent, Qcenter))
1788 img->ascent = CENTERED_IMAGE_ASCENT;
1790 margin = image_spec_value (spec, QCmargin, NULL);
1791 if (INTEGERP (margin) && XINT (margin) >= 0)
1792 img->vmargin = img->hmargin = XFASTINT (margin);
1793 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1794 && INTEGERP (XCDR (margin)))
1796 if (XINT (XCAR (margin)) > 0)
1797 img->hmargin = XFASTINT (XCAR (margin));
1798 if (XINT (XCDR (margin)) > 0)
1799 img->vmargin = XFASTINT (XCDR (margin));
1802 relief = image_spec_value (spec, QCrelief, NULL);
1803 if (INTEGERP (relief))
1805 img->relief = XINT (relief);
1806 img->hmargin += abs (img->relief);
1807 img->vmargin += abs (img->relief);
1810 if (! img->background_valid)
1812 bg = image_spec_value (img->spec, QCbackground, NULL);
1813 if (!NILP (bg))
1815 img->background
1816 = x_alloc_image_color (f, img, bg,
1817 FRAME_BACKGROUND_PIXEL (f));
1818 img->background_valid = 1;
1822 /* Do image transformations and compute masks, unless we
1823 don't have the image yet. */
1824 if (!EQ (*img->type->type, Qpostscript))
1825 postprocess_image (f, img);
1828 UNBLOCK_INPUT;
1831 /* We're using IMG, so set its timestamp to `now'. */
1832 EMACS_GET_TIME (now);
1833 img->timestamp = EMACS_SECS (now);
1835 UNGCPRO;
1837 /* Value is the image id. */
1838 return img->id;
1842 /* Cache image IMG in the image cache of frame F. */
1844 static void
1845 cache_image (f, img)
1846 struct frame *f;
1847 struct image *img;
1849 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1850 int i;
1852 /* Find a free slot in c->images. */
1853 for (i = 0; i < c->used; ++i)
1854 if (c->images[i] == NULL)
1855 break;
1857 /* If no free slot found, maybe enlarge c->images. */
1858 if (i == c->used && c->used == c->size)
1860 c->size *= 2;
1861 c->images = (struct image **) xrealloc (c->images,
1862 c->size * sizeof *c->images);
1865 /* Add IMG to c->images, and assign IMG an id. */
1866 c->images[i] = img;
1867 img->id = i;
1868 if (i == c->used)
1869 ++c->used;
1871 /* Add IMG to the cache's hash table. */
1872 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1873 img->next = c->buckets[i];
1874 if (img->next)
1875 img->next->prev = img;
1876 img->prev = NULL;
1877 c->buckets[i] = img;
1881 /* Call FN on every image in the image cache of frame F. Used to mark
1882 Lisp Objects in the image cache. */
1884 void
1885 forall_images_in_image_cache (f, fn)
1886 struct frame *f;
1887 void (*fn) P_ ((struct image *img));
1889 if (FRAME_LIVE_P (f) && FRAME_WINDOW_P (f))
1891 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1892 if (c)
1894 int i;
1895 for (i = 0; i < c->used; ++i)
1896 if (c->images[i])
1897 fn (c->images[i]);
1904 /***********************************************************************
1905 X / MAC / W32 support code
1906 ***********************************************************************/
1908 #ifdef HAVE_NTGUI
1910 /* Macro for defining functions that will be loaded from image DLLs. */
1911 #define DEF_IMGLIB_FN(func) int (FAR CDECL *fn_##func)()
1913 /* Macro for loading those image functions from the library. */
1914 #define LOAD_IMGLIB_FN(lib,func) { \
1915 fn_##func = (void *) GetProcAddress (lib, #func); \
1916 if (!fn_##func) return 0; \
1919 /* Load a DLL implementing an image type.
1920 The `image-library-alist' variable associates a symbol,
1921 identifying an image type, to a list of possible filenames.
1922 The function returns NULL if no library could be loaded for
1923 the given image type, or if the library was previously loaded;
1924 else the handle of the DLL. */
1925 static HMODULE
1926 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
1928 HMODULE library = NULL;
1930 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
1932 Lisp_Object dlls = Fassq (type, libraries);
1934 if (CONSP (dlls))
1935 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
1937 CHECK_STRING_CAR (dlls);
1938 if (library = LoadLibrary (SDATA (XCAR (dlls))))
1939 break;
1943 return library;
1946 #endif /* HAVE_NTGUI */
1948 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
1949 XImagePtr *, Pixmap *));
1950 static void x_destroy_x_image P_ ((XImagePtr));
1951 static void x_put_x_image P_ ((struct frame *, XImagePtr, Pixmap, int, int));
1954 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1955 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1956 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1957 via xmalloc. Print error messages via image_error if an error
1958 occurs. Value is non-zero if successful.
1960 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1961 should indicate the bit depth of the image. */
1963 static int
1964 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
1965 struct frame *f;
1966 int width, height, depth;
1967 XImagePtr *ximg;
1968 Pixmap *pixmap;
1970 #ifdef HAVE_X_WINDOWS
1971 Display *display = FRAME_X_DISPLAY (f);
1972 Window window = FRAME_X_WINDOW (f);
1973 Screen *screen = FRAME_X_SCREEN (f);
1975 xassert (interrupt_input_blocked);
1977 if (depth <= 0)
1978 depth = DefaultDepthOfScreen (screen);
1979 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1980 depth, ZPixmap, 0, NULL, width, height,
1981 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1982 if (*ximg == NULL)
1984 image_error ("Unable to allocate X image", Qnil, Qnil);
1985 return 0;
1988 /* Allocate image raster. */
1989 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
1991 /* Allocate a pixmap of the same size. */
1992 *pixmap = XCreatePixmap (display, window, width, height, depth);
1993 if (*pixmap == NO_PIXMAP)
1995 x_destroy_x_image (*ximg);
1996 *ximg = NULL;
1997 image_error ("Unable to create X pixmap", Qnil, Qnil);
1998 return 0;
2001 return 1;
2002 #endif /* HAVE_X_WINDOWS */
2004 #ifdef HAVE_NTGUI
2006 BITMAPINFOHEADER *header;
2007 HDC hdc;
2008 int scanline_width_bits;
2009 int remainder;
2010 int palette_colors = 0;
2012 if (depth == 0)
2013 depth = 24;
2015 if (depth != 1 && depth != 4 && depth != 8
2016 && depth != 16 && depth != 24 && depth != 32)
2018 image_error ("Invalid image bit depth specified", Qnil, Qnil);
2019 return 0;
2022 scanline_width_bits = width * depth;
2023 remainder = scanline_width_bits % 32;
2025 if (remainder)
2026 scanline_width_bits += 32 - remainder;
2028 /* Bitmaps with a depth less than 16 need a palette. */
2029 /* BITMAPINFO structure already contains the first RGBQUAD. */
2030 if (depth < 16)
2031 palette_colors = 1 << depth - 1;
2033 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2034 if (*ximg == NULL)
2036 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
2037 return 0;
2040 header = &((*ximg)->info.bmiHeader);
2041 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
2042 header->biSize = sizeof (*header);
2043 header->biWidth = width;
2044 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2045 header->biPlanes = 1;
2046 header->biBitCount = depth;
2047 header->biCompression = BI_RGB;
2048 header->biClrUsed = palette_colors;
2050 /* TODO: fill in palette. */
2051 if (depth == 1)
2053 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2054 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2055 (*ximg)->info.bmiColors[0].rgbRed = 0;
2056 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2057 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2058 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2059 (*ximg)->info.bmiColors[1].rgbRed = 255;
2060 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2063 hdc = get_frame_dc (f);
2065 /* Create a DIBSection and raster array for the bitmap,
2066 and store its handle in *pixmap. */
2067 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2068 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2069 /* casting avoids a GCC warning */
2070 (void **)&((*ximg)->data), NULL, 0);
2072 /* Realize display palette and garbage all frames. */
2073 release_frame_dc (f, hdc);
2075 if (*pixmap == NULL)
2077 DWORD err = GetLastError();
2078 Lisp_Object errcode;
2079 /* All system errors are < 10000, so the following is safe. */
2080 XSETINT (errcode, (int) err);
2081 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2082 x_destroy_x_image (*ximg);
2083 return 0;
2086 return 1;
2088 #endif /* HAVE_NTGUI */
2090 #ifdef MAC_OS
2091 Display *display = FRAME_X_DISPLAY (f);
2092 Window window = FRAME_X_WINDOW (f);
2094 xassert (interrupt_input_blocked);
2096 /* Allocate a pixmap of the same size. */
2097 *pixmap = XCreatePixmap (display, window, width, height, depth);
2098 if (*pixmap == NO_PIXMAP)
2100 *ximg = NULL;
2101 image_error ("Unable to create X pixmap", Qnil, Qnil);
2102 return 0;
2105 LockPixels (GetGWorldPixMap (*pixmap));
2106 *ximg = *pixmap;
2107 return 1;
2109 #endif /* MAC_OS */
2113 /* Destroy XImage XIMG. Free XIMG->data. */
2115 static void
2116 x_destroy_x_image (ximg)
2117 XImagePtr ximg;
2119 xassert (interrupt_input_blocked);
2120 if (ximg)
2122 #ifdef HAVE_X_WINDOWS
2123 xfree (ximg->data);
2124 ximg->data = NULL;
2125 XDestroyImage (ximg);
2126 #endif /* HAVE_X_WINDOWS */
2127 #ifdef HAVE_NTGUI
2128 /* Data will be freed by DestroyObject. */
2129 ximg->data = NULL;
2130 xfree (ximg);
2131 #endif /* HAVE_NTGUI */
2132 #ifdef MAC_OS
2133 XDestroyImage (ximg);
2134 #endif /* MAC_OS */
2139 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2140 are width and height of both the image and pixmap. */
2142 static void
2143 x_put_x_image (f, ximg, pixmap, width, height)
2144 struct frame *f;
2145 XImagePtr ximg;
2146 Pixmap pixmap;
2147 int width, height;
2149 #ifdef HAVE_X_WINDOWS
2150 GC gc;
2152 xassert (interrupt_input_blocked);
2153 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2154 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2155 XFreeGC (FRAME_X_DISPLAY (f), gc);
2156 #endif /* HAVE_X_WINDOWS */
2158 #ifdef HAVE_NTGUI
2159 #if 0 /* I don't think this is necessary looking at where it is used. */
2160 HDC hdc = get_frame_dc (f);
2161 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2162 release_frame_dc (f, hdc);
2163 #endif
2164 #endif /* HAVE_NTGUI */
2166 #ifdef MAC_OS
2167 xassert (ximg == pixmap);
2168 #endif /* MAC_OS */
2172 /***********************************************************************
2173 File Handling
2174 ***********************************************************************/
2176 static unsigned char *slurp_file P_ ((char *, int *));
2179 /* Find image file FILE. Look in data-directory, then
2180 x-bitmap-file-path. Value is the full name of the file found, or
2181 nil if not found. */
2183 Lisp_Object
2184 x_find_image_file (file)
2185 Lisp_Object file;
2187 Lisp_Object file_found, search_path;
2188 struct gcpro gcpro1, gcpro2;
2189 int fd;
2191 file_found = Qnil;
2192 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
2193 GCPRO2 (file_found, search_path);
2195 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
2196 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2198 if (fd == -1)
2199 file_found = Qnil;
2200 else
2201 close (fd);
2203 UNGCPRO;
2204 return file_found;
2208 /* Read FILE into memory. Value is a pointer to a buffer allocated
2209 with xmalloc holding FILE's contents. Value is null if an error
2210 occurred. *SIZE is set to the size of the file. */
2212 static unsigned char *
2213 slurp_file (file, size)
2214 char *file;
2215 int *size;
2217 FILE *fp = NULL;
2218 unsigned char *buf = NULL;
2219 struct stat st;
2221 if (stat (file, &st) == 0
2222 && (fp = fopen (file, "rb")) != NULL
2223 && (buf = (unsigned char *) xmalloc (st.st_size),
2224 fread (buf, 1, st.st_size, fp) == st.st_size))
2226 *size = st.st_size;
2227 fclose (fp);
2229 else
2231 if (fp)
2232 fclose (fp);
2233 if (buf)
2235 xfree (buf);
2236 buf = NULL;
2240 return buf;
2245 #ifdef MAC_OS
2247 /***********************************************************************
2248 MAC Image Load Functions
2249 ***********************************************************************/
2251 static int image_load_quicktime P_ ((struct frame *, struct image *img,
2252 OSType));
2253 #ifdef MAC_OSX
2254 static int image_load_quartz2d P_ ((struct frame *, struct image *img, int));
2255 #endif
2257 static OSErr
2258 find_image_fsspec (specified_file, file, fss)
2259 Lisp_Object specified_file, *file;
2260 FSSpec *fss;
2262 #if MAC_OSX
2263 FSRef fsr;
2264 #endif
2265 OSErr err;
2267 *file = x_find_image_file (specified_file);
2268 if (!STRINGP (*file))
2269 return fnfErr; /* file or directory not found;
2270 incomplete pathname */
2271 /* Try to open the image file. */
2272 #if MAC_OSX
2273 err = FSPathMakeRef (SDATA (*file), &fsr, NULL);
2274 if (err == noErr)
2275 err = FSGetCatalogInfo (&fsr, kFSCatInfoNone, NULL, NULL, fss, NULL);
2276 #else
2277 err = posix_pathname_to_fsspec (SDATA (*file), fss);
2278 #endif
2279 return err;
2282 static int
2283 image_load_qt_1 (f, img, type, fss, dh)
2284 struct frame *f;
2285 struct image *img;
2286 OSType type;
2287 FSSpec *fss;
2288 Handle dh;
2290 OSErr err;
2291 GraphicsImportComponent gi;
2292 Rect rect;
2293 int width, height;
2294 ImageDescriptionHandle desc_handle;
2295 short draw_all_pixels;
2296 Lisp_Object specified_bg;
2297 XColor color;
2298 XImagePtr ximg;
2299 RGBColor bg_color;
2301 err = OpenADefaultComponent (GraphicsImporterComponentType,
2302 type, &gi);
2303 if (err != noErr)
2305 image_error ("Cannot get importer component for `%s'", img->spec, Qnil);
2306 return 0;
2308 if (dh == NULL)
2310 /* read from file system spec */
2311 err = GraphicsImportSetDataFile (gi, fss);
2312 if (err != noErr)
2314 image_error ("Cannot set fsspec to graphics importer for '%s'",
2315 img->spec, Qnil);
2316 goto error;
2319 else
2321 /* read from data handle */
2322 err = GraphicsImportSetDataHandle (gi, dh);
2323 if (err != noErr)
2325 image_error ("Cannot set data handle to graphics importer for `%s'",
2326 img->spec, Qnil);
2327 goto error;
2330 err = GraphicsImportGetImageDescription (gi, &desc_handle);
2331 if (err != noErr || desc_handle == NULL)
2333 image_error ("Error reading `%s'", img->spec, Qnil);
2334 goto error;
2336 width = img->width = (*desc_handle)->width;
2337 height = img->height = (*desc_handle)->height;
2338 DisposeHandle ((Handle)desc_handle);
2340 if (!check_image_size (f, width, height))
2342 image_error ("Invalid image size", Qnil, Qnil);
2343 goto error;
2346 err = GraphicsImportDoesDrawAllPixels (gi, &draw_all_pixels);
2347 #if 0
2348 /* Don't check the error code here. It may have an undocumented
2349 value -32766. */
2350 if (err != noErr)
2352 image_error ("Error reading `%s'", img->spec, Qnil);
2353 goto error;
2355 #endif
2356 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2358 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2359 if (!STRINGP (specified_bg) ||
2360 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2362 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2363 color.red = RED16_FROM_ULONG (color.pixel);
2364 color.green = GREEN16_FROM_ULONG (color.pixel);
2365 color.blue = BLUE16_FROM_ULONG (color.pixel);
2369 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2370 goto error;
2371 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2373 CGrafPtr old_port;
2374 GDHandle old_gdh;
2376 GetGWorld (&old_port, &old_gdh);
2377 SetGWorld (ximg, NULL);
2378 bg_color.red = color.red;
2379 bg_color.green = color.green;
2380 bg_color.blue = color.blue;
2381 RGBBackColor (&bg_color);
2382 #if TARGET_API_MAC_CARBON
2383 GetPortBounds (ximg, &rect);
2384 EraseRect (&rect);
2385 #else
2386 EraseRect (&(ximg->portRect));
2387 #endif
2388 SetGWorld (old_port, old_gdh);
2390 GraphicsImportSetGWorld (gi, ximg, NULL);
2391 GraphicsImportDraw (gi);
2392 CloseComponent (gi);
2394 /* Maybe fill in the background field while we have ximg handy. */
2395 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2396 IMAGE_BACKGROUND (img, f, ximg);
2398 /* Put the image into the pixmap. */
2399 x_put_x_image (f, ximg, img->pixmap, width, height);
2400 x_destroy_x_image (ximg);
2401 return 1;
2403 error:
2404 CloseComponent (gi);
2405 return 0;
2409 /* Load an image using the QuickTime Graphics Importer.
2410 Note: The alpha channel does not work for PNG images. */
2411 static int
2412 image_load_quicktime (f, img, type)
2413 struct frame *f;
2414 struct image *img;
2415 OSType type;
2417 Lisp_Object specified_file;
2418 Lisp_Object specified_data;
2419 OSErr err;
2421 specified_file = image_spec_value (img->spec, QCfile, NULL);
2422 specified_data = image_spec_value (img->spec, QCdata, NULL);
2424 if (NILP (specified_data))
2426 /* Read from a file */
2427 Lisp_Object file;
2428 FSSpec fss;
2430 err = find_image_fsspec (specified_file, &file, &fss);
2431 if (err != noErr)
2433 if (err == fnfErr)
2434 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2435 else
2436 image_error ("Cannot open `%s'", file, Qnil);
2437 return 0;
2439 return image_load_qt_1 (f, img, type, &fss, NULL);
2441 else
2443 /* Memory source! */
2444 int success_p;
2445 Handle dh;
2447 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
2448 if (err != noErr)
2450 image_error ("Cannot allocate data handle for `%s'",
2451 img->spec, Qnil);
2452 return 0;
2454 success_p = image_load_qt_1 (f, img, type, NULL, dh);
2455 DisposeHandle (dh);
2456 return success_p;
2461 #ifdef MAC_OSX
2462 /* Load a PNG/JPEG image using Quartz 2D decoding routines.
2463 CGImageCreateWithPNGDataProvider is provided after Mac OS X 10.2.
2464 So don't use this function directly but determine at runtime
2465 whether it exists. */
2466 typedef CGImageRef (*CGImageCreateWithPNGDataProviderProcType)
2467 (CGDataProviderRef, const float [], bool, CGColorRenderingIntent);
2468 static CGImageCreateWithPNGDataProviderProcType MyCGImageCreateWithPNGDataProvider;
2471 static void
2472 init_image_func_pointer ()
2474 if (NSIsSymbolNameDefined ("_CGImageCreateWithPNGDataProvider"))
2476 MyCGImageCreateWithPNGDataProvider
2477 = (CGImageCreateWithPNGDataProviderProcType)
2478 NSAddressOfSymbol (NSLookupAndBindSymbol
2479 ("_CGImageCreateWithPNGDataProvider"));
2481 else
2482 MyCGImageCreateWithPNGDataProvider = NULL;
2486 static int
2487 image_load_quartz2d (f, img, png_p)
2488 struct frame *f;
2489 struct image *img;
2490 int png_p;
2492 Lisp_Object file, specified_file;
2493 Lisp_Object specified_data, specified_bg;
2494 struct gcpro gcpro1;
2495 CGDataProviderRef source;
2496 CGImageRef image;
2497 int width, height;
2498 XColor color;
2499 XImagePtr ximg = NULL;
2500 CGContextRef context;
2501 CGRect rectangle;
2503 /* Open the file. */
2504 specified_file = image_spec_value (img->spec, QCfile, NULL);
2505 specified_data = image_spec_value (img->spec, QCdata, NULL);
2507 file = Qnil;
2508 GCPRO1 (file);
2510 if (NILP (specified_data))
2512 CFStringRef path;
2513 CFURLRef url;
2515 file = x_find_image_file (specified_file);
2516 if (!STRINGP (file))
2518 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2519 UNGCPRO;
2520 return 0;
2522 path = cfstring_create_with_string (file);
2523 url = CFURLCreateWithFileSystemPath (NULL, path,
2524 kCFURLPOSIXPathStyle, 0);
2525 CFRelease (path);
2526 source = CGDataProviderCreateWithURL (url);
2527 CFRelease (url);
2529 else
2530 source = CGDataProviderCreateWithData (NULL, SDATA (specified_data),
2531 SBYTES (specified_data), NULL);
2533 if (png_p)
2534 image = (*MyCGImageCreateWithPNGDataProvider) (source, NULL, FALSE,
2535 kCGRenderingIntentDefault);
2536 else
2537 image = CGImageCreateWithJPEGDataProvider (source, NULL, FALSE,
2538 kCGRenderingIntentDefault);
2540 CGDataProviderRelease (source);
2541 if (image == NULL)
2543 UNGCPRO;
2544 image_error ("Error reading image `%s'", img->spec, Qnil);
2545 return 0;
2547 width = img->width = CGImageGetWidth (image);
2548 height = img->height = CGImageGetHeight (image);
2550 if (!check_image_size (f, width, height))
2552 CGImageRelease (image);
2553 UNGCPRO;
2554 image_error ("Invalid image size", Qnil, Qnil);
2555 return 0;
2558 if (png_p)
2560 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2561 if (!STRINGP (specified_bg) ||
2562 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2564 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2565 color.red = RED16_FROM_ULONG (color.pixel);
2566 color.green = GREEN16_FROM_ULONG (color.pixel);
2567 color.blue = BLUE16_FROM_ULONG (color.pixel);
2571 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2573 CGImageRelease (image);
2574 UNGCPRO;
2575 return 0;
2577 rectangle = CGRectMake (0, 0, width, height);
2578 QDBeginCGContext (ximg, &context);
2579 if (png_p)
2581 CGContextSetRGBFillColor (context, color.red / 65535.0,
2582 color.green / 65535.0,
2583 color.blue / 65535.0, 1.0);
2584 CGContextFillRect (context, rectangle);
2586 CGContextDrawImage (context, rectangle, image);
2587 QDEndCGContext (ximg, &context);
2588 CGImageRelease (image);
2590 /* Maybe fill in the background field while we have ximg handy. */
2591 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2592 IMAGE_BACKGROUND (img, f, ximg);
2594 /* Put the image into the pixmap. */
2595 x_put_x_image (f, ximg, img->pixmap, width, height);
2596 x_destroy_x_image (ximg);
2597 UNGCPRO;
2598 return 1;
2600 #endif
2602 #endif /* MAC_OS */
2605 /***********************************************************************
2606 XBM images
2607 ***********************************************************************/
2609 static int xbm_scan P_ ((unsigned char **, unsigned char *, char *, int *));
2610 static int xbm_load P_ ((struct frame *f, struct image *img));
2611 static int xbm_load_image P_ ((struct frame *f, struct image *img,
2612 unsigned char *, unsigned char *));
2613 static int xbm_image_p P_ ((Lisp_Object object));
2614 static int xbm_read_bitmap_data P_ ((struct frame *f,
2615 unsigned char *, unsigned char *,
2616 int *, int *, unsigned char **));
2617 static int xbm_file_p P_ ((Lisp_Object));
2620 /* Indices of image specification fields in xbm_format, below. */
2622 enum xbm_keyword_index
2624 XBM_TYPE,
2625 XBM_FILE,
2626 XBM_WIDTH,
2627 XBM_HEIGHT,
2628 XBM_DATA,
2629 XBM_FOREGROUND,
2630 XBM_BACKGROUND,
2631 XBM_ASCENT,
2632 XBM_MARGIN,
2633 XBM_RELIEF,
2634 XBM_ALGORITHM,
2635 XBM_HEURISTIC_MASK,
2636 XBM_MASK,
2637 XBM_LAST
2640 /* Vector of image_keyword structures describing the format
2641 of valid XBM image specifications. */
2643 static struct image_keyword xbm_format[XBM_LAST] =
2645 {":type", IMAGE_SYMBOL_VALUE, 1},
2646 {":file", IMAGE_STRING_VALUE, 0},
2647 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2648 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2649 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2650 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2651 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2652 {":ascent", IMAGE_ASCENT_VALUE, 0},
2653 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2654 {":relief", IMAGE_INTEGER_VALUE, 0},
2655 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2656 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2657 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2660 /* Structure describing the image type XBM. */
2662 static struct image_type xbm_type =
2664 &Qxbm,
2665 xbm_image_p,
2666 xbm_load,
2667 x_clear_image,
2668 NULL
2671 /* Tokens returned from xbm_scan. */
2673 enum xbm_token
2675 XBM_TK_IDENT = 256,
2676 XBM_TK_NUMBER
2680 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2681 A valid specification is a list starting with the symbol `image'
2682 The rest of the list is a property list which must contain an
2683 entry `:type xbm..
2685 If the specification specifies a file to load, it must contain
2686 an entry `:file FILENAME' where FILENAME is a string.
2688 If the specification is for a bitmap loaded from memory it must
2689 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2690 WIDTH and HEIGHT are integers > 0. DATA may be:
2692 1. a string large enough to hold the bitmap data, i.e. it must
2693 have a size >= (WIDTH + 7) / 8 * HEIGHT
2695 2. a bool-vector of size >= WIDTH * HEIGHT
2697 3. a vector of strings or bool-vectors, one for each line of the
2698 bitmap.
2700 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
2701 may not be specified in this case because they are defined in the
2702 XBM file.
2704 Both the file and data forms may contain the additional entries
2705 `:background COLOR' and `:foreground COLOR'. If not present,
2706 foreground and background of the frame on which the image is
2707 displayed is used. */
2709 static int
2710 xbm_image_p (object)
2711 Lisp_Object object;
2713 struct image_keyword kw[XBM_LAST];
2715 bcopy (xbm_format, kw, sizeof kw);
2716 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2717 return 0;
2719 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2721 if (kw[XBM_FILE].count)
2723 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2724 return 0;
2726 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2728 /* In-memory XBM file. */
2729 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2730 return 0;
2732 else
2734 Lisp_Object data;
2735 int width, height;
2737 /* Entries for `:width', `:height' and `:data' must be present. */
2738 if (!kw[XBM_WIDTH].count
2739 || !kw[XBM_HEIGHT].count
2740 || !kw[XBM_DATA].count)
2741 return 0;
2743 data = kw[XBM_DATA].value;
2744 width = XFASTINT (kw[XBM_WIDTH].value);
2745 height = XFASTINT (kw[XBM_HEIGHT].value);
2747 /* Check type of data, and width and height against contents of
2748 data. */
2749 if (VECTORP (data))
2751 int i;
2753 /* Number of elements of the vector must be >= height. */
2754 if (XVECTOR (data)->size < height)
2755 return 0;
2757 /* Each string or bool-vector in data must be large enough
2758 for one line of the image. */
2759 for (i = 0; i < height; ++i)
2761 Lisp_Object elt = XVECTOR (data)->contents[i];
2763 if (STRINGP (elt))
2765 if (SCHARS (elt)
2766 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2767 return 0;
2769 else if (BOOL_VECTOR_P (elt))
2771 if (XBOOL_VECTOR (elt)->size < width)
2772 return 0;
2774 else
2775 return 0;
2778 else if (STRINGP (data))
2780 if (SCHARS (data)
2781 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2782 return 0;
2784 else if (BOOL_VECTOR_P (data))
2786 if (XBOOL_VECTOR (data)->size < width * height)
2787 return 0;
2789 else
2790 return 0;
2793 return 1;
2797 /* Scan a bitmap file. FP is the stream to read from. Value is
2798 either an enumerator from enum xbm_token, or a character for a
2799 single-character token, or 0 at end of file. If scanning an
2800 identifier, store the lexeme of the identifier in SVAL. If
2801 scanning a number, store its value in *IVAL. */
2803 static int
2804 xbm_scan (s, end, sval, ival)
2805 unsigned char **s, *end;
2806 char *sval;
2807 int *ival;
2809 unsigned int c;
2811 loop:
2813 /* Skip white space. */
2814 while (*s < end && (c = *(*s)++, isspace (c)))
2817 if (*s >= end)
2818 c = 0;
2819 else if (isdigit (c))
2821 int value = 0, digit;
2823 if (c == '0' && *s < end)
2825 c = *(*s)++;
2826 if (c == 'x' || c == 'X')
2828 while (*s < end)
2830 c = *(*s)++;
2831 if (isdigit (c))
2832 digit = c - '0';
2833 else if (c >= 'a' && c <= 'f')
2834 digit = c - 'a' + 10;
2835 else if (c >= 'A' && c <= 'F')
2836 digit = c - 'A' + 10;
2837 else
2838 break;
2839 value = 16 * value + digit;
2842 else if (isdigit (c))
2844 value = c - '0';
2845 while (*s < end
2846 && (c = *(*s)++, isdigit (c)))
2847 value = 8 * value + c - '0';
2850 else
2852 value = c - '0';
2853 while (*s < end
2854 && (c = *(*s)++, isdigit (c)))
2855 value = 10 * value + c - '0';
2858 if (*s < end)
2859 *s = *s - 1;
2860 *ival = value;
2861 c = XBM_TK_NUMBER;
2863 else if (isalpha (c) || c == '_')
2865 *sval++ = c;
2866 while (*s < end
2867 && (c = *(*s)++, (isalnum (c) || c == '_')))
2868 *sval++ = c;
2869 *sval = 0;
2870 if (*s < end)
2871 *s = *s - 1;
2872 c = XBM_TK_IDENT;
2874 else if (c == '/' && **s == '*')
2876 /* C-style comment. */
2877 ++*s;
2878 while (**s && (**s != '*' || *(*s + 1) != '/'))
2879 ++*s;
2880 if (**s)
2882 *s += 2;
2883 goto loop;
2887 return c;
2890 #ifdef HAVE_NTGUI
2892 /* Create a Windows bitmap from X bitmap data. */
2893 static HBITMAP
2894 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2896 static unsigned char swap_nibble[16]
2897 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2898 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2899 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2900 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2901 int i, j, w1, w2;
2902 unsigned char *bits, *p;
2903 HBITMAP bmp;
2905 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2906 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2907 bits = (unsigned char *) alloca (height * w2);
2908 bzero (bits, height * w2);
2909 for (i = 0; i < height; i++)
2911 p = bits + i*w2;
2912 for (j = 0; j < w1; j++)
2914 /* Bitswap XBM bytes to match how Windows does things. */
2915 unsigned char c = *data++;
2916 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2917 | (swap_nibble[(c>>4) & 0xf]));
2920 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2922 return bmp;
2925 static void convert_mono_to_color_image (f, img, foreground, background)
2926 struct frame *f;
2927 struct image *img;
2928 COLORREF foreground, background;
2930 HDC hdc, old_img_dc, new_img_dc;
2931 HGDIOBJ old_prev, new_prev;
2932 HBITMAP new_pixmap;
2934 hdc = get_frame_dc (f);
2935 old_img_dc = CreateCompatibleDC (hdc);
2936 new_img_dc = CreateCompatibleDC (hdc);
2937 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2938 release_frame_dc (f, hdc);
2939 old_prev = SelectObject (old_img_dc, img->pixmap);
2940 new_prev = SelectObject (new_img_dc, new_pixmap);
2941 SetTextColor (new_img_dc, foreground);
2942 SetBkColor (new_img_dc, background);
2944 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2945 0, 0, SRCCOPY);
2947 SelectObject (old_img_dc, old_prev);
2948 SelectObject (new_img_dc, new_prev);
2949 DeleteDC (old_img_dc);
2950 DeleteDC (new_img_dc);
2951 DeleteObject (img->pixmap);
2952 if (new_pixmap == 0)
2953 fprintf (stderr, "Failed to convert image to color.\n");
2954 else
2955 img->pixmap = new_pixmap;
2958 #define XBM_BIT_SHUFFLE(b) (~(b))
2960 #else
2962 #define XBM_BIT_SHUFFLE(b) (b)
2964 #endif /* HAVE_NTGUI */
2967 static void
2968 Create_Pixmap_From_Bitmap_Data(f, img, data, fg, bg, non_default_colors)
2969 struct frame *f;
2970 struct image *img;
2971 char *data;
2972 RGB_PIXEL_COLOR fg, bg;
2973 int non_default_colors;
2975 #ifdef HAVE_NTGUI
2976 img->pixmap
2977 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2979 /* If colors were specified, transfer the bitmap to a color one. */
2980 if (non_default_colors)
2981 convert_mono_to_color_image (f, img, fg, bg);
2982 #else
2983 img->pixmap
2984 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2985 FRAME_X_WINDOW (f),
2986 data,
2987 img->width, img->height,
2988 fg, bg,
2989 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2990 #endif /* HAVE_NTGUI */
2995 /* Replacement for XReadBitmapFileData which isn't available under old
2996 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2997 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2998 the image. Return in *DATA the bitmap data allocated with xmalloc.
2999 Value is non-zero if successful. DATA null means just test if
3000 CONTENTS looks like an in-memory XBM file. */
3002 static int
3003 xbm_read_bitmap_data (f, contents, end, width, height, data)
3004 struct frame *f;
3005 unsigned char *contents, *end;
3006 int *width, *height;
3007 unsigned char **data;
3009 unsigned char *s = contents;
3010 char buffer[BUFSIZ];
3011 int padding_p = 0;
3012 int v10 = 0;
3013 int bytes_per_line, i, nbytes;
3014 unsigned char *p;
3015 int value;
3016 int LA1;
3018 #define match() \
3019 LA1 = xbm_scan (&s, end, buffer, &value)
3021 #define expect(TOKEN) \
3022 if (LA1 != (TOKEN)) \
3023 goto failure; \
3024 else \
3025 match ()
3027 #define expect_ident(IDENT) \
3028 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
3029 match (); \
3030 else \
3031 goto failure
3033 *width = *height = -1;
3034 if (data)
3035 *data = NULL;
3036 LA1 = xbm_scan (&s, end, buffer, &value);
3038 /* Parse defines for width, height and hot-spots. */
3039 while (LA1 == '#')
3041 match ();
3042 expect_ident ("define");
3043 expect (XBM_TK_IDENT);
3045 if (LA1 == XBM_TK_NUMBER);
3047 char *p = strrchr (buffer, '_');
3048 p = p ? p + 1 : buffer;
3049 if (strcmp (p, "width") == 0)
3050 *width = value;
3051 else if (strcmp (p, "height") == 0)
3052 *height = value;
3054 expect (XBM_TK_NUMBER);
3057 if (!check_image_size (f, *width, *height))
3058 goto failure;
3059 else if (data == NULL)
3060 goto success;
3062 /* Parse bits. Must start with `static'. */
3063 expect_ident ("static");
3064 if (LA1 == XBM_TK_IDENT)
3066 if (strcmp (buffer, "unsigned") == 0)
3068 match ();
3069 expect_ident ("char");
3071 else if (strcmp (buffer, "short") == 0)
3073 match ();
3074 v10 = 1;
3075 if (*width % 16 && *width % 16 < 9)
3076 padding_p = 1;
3078 else if (strcmp (buffer, "char") == 0)
3079 match ();
3080 else
3081 goto failure;
3083 else
3084 goto failure;
3086 expect (XBM_TK_IDENT);
3087 expect ('[');
3088 expect (']');
3089 expect ('=');
3090 expect ('{');
3092 bytes_per_line = (*width + 7) / 8 + padding_p;
3093 nbytes = bytes_per_line * *height;
3094 p = *data = (unsigned char *) xmalloc (nbytes);
3096 if (v10)
3098 for (i = 0; i < nbytes; i += 2)
3100 int val = value;
3101 expect (XBM_TK_NUMBER);
3103 *p++ = XBM_BIT_SHUFFLE (val);
3104 if (!padding_p || ((i + 2) % bytes_per_line))
3105 *p++ = XBM_BIT_SHUFFLE (value >> 8);
3107 if (LA1 == ',' || LA1 == '}')
3108 match ();
3109 else
3110 goto failure;
3113 else
3115 for (i = 0; i < nbytes; ++i)
3117 int val = value;
3118 expect (XBM_TK_NUMBER);
3120 *p++ = XBM_BIT_SHUFFLE (val);
3122 if (LA1 == ',' || LA1 == '}')
3123 match ();
3124 else
3125 goto failure;
3129 success:
3130 return 1;
3132 failure:
3134 if (data && *data)
3136 xfree (*data);
3137 *data = NULL;
3139 return 0;
3141 #undef match
3142 #undef expect
3143 #undef expect_ident
3147 /* Load XBM image IMG which will be displayed on frame F from buffer
3148 CONTENTS. END is the end of the buffer. Value is non-zero if
3149 successful. */
3151 static int
3152 xbm_load_image (f, img, contents, end)
3153 struct frame *f;
3154 struct image *img;
3155 unsigned char *contents, *end;
3157 int rc;
3158 unsigned char *data;
3159 int success_p = 0;
3161 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height, &data);
3162 if (rc)
3164 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3165 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3166 int non_default_colors = 0;
3167 Lisp_Object value;
3169 xassert (img->width > 0 && img->height > 0);
3171 /* Get foreground and background colors, maybe allocate colors. */
3172 value = image_spec_value (img->spec, QCforeground, NULL);
3173 if (!NILP (value))
3175 foreground = x_alloc_image_color (f, img, value, foreground);
3176 non_default_colors = 1;
3178 value = image_spec_value (img->spec, QCbackground, NULL);
3179 if (!NILP (value))
3181 background = x_alloc_image_color (f, img, value, background);
3182 img->background = background;
3183 img->background_valid = 1;
3184 non_default_colors = 1;
3187 Create_Pixmap_From_Bitmap_Data (f, img, data,
3188 foreground, background,
3189 non_default_colors);
3190 xfree (data);
3192 if (img->pixmap == NO_PIXMAP)
3194 x_clear_image (f, img);
3195 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
3197 else
3198 success_p = 1;
3200 else
3201 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3203 return success_p;
3207 /* Value is non-zero if DATA looks like an in-memory XBM file. */
3209 static int
3210 xbm_file_p (data)
3211 Lisp_Object data;
3213 int w, h;
3214 return (STRINGP (data)
3215 && xbm_read_bitmap_data (NULL, SDATA (data),
3216 (SDATA (data)
3217 + SBYTES (data)),
3218 &w, &h, NULL));
3222 /* Fill image IMG which is used on frame F with pixmap data. Value is
3223 non-zero if successful. */
3225 static int
3226 xbm_load (f, img)
3227 struct frame *f;
3228 struct image *img;
3230 int success_p = 0;
3231 Lisp_Object file_name;
3233 xassert (xbm_image_p (img->spec));
3235 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3236 file_name = image_spec_value (img->spec, QCfile, NULL);
3237 if (STRINGP (file_name))
3239 Lisp_Object file;
3240 unsigned char *contents;
3241 int size;
3242 struct gcpro gcpro1;
3244 file = x_find_image_file (file_name);
3245 GCPRO1 (file);
3246 if (!STRINGP (file))
3248 image_error ("Cannot find image file `%s'", file_name, Qnil);
3249 UNGCPRO;
3250 return 0;
3253 contents = slurp_file (SDATA (file), &size);
3254 if (contents == NULL)
3256 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3257 UNGCPRO;
3258 return 0;
3261 success_p = xbm_load_image (f, img, contents, contents + size);
3262 UNGCPRO;
3264 else
3266 struct image_keyword fmt[XBM_LAST];
3267 Lisp_Object data;
3268 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3269 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3270 int non_default_colors = 0;
3271 char *bits;
3272 int parsed_p;
3273 int in_memory_file_p = 0;
3275 /* See if data looks like an in-memory XBM file. */
3276 data = image_spec_value (img->spec, QCdata, NULL);
3277 in_memory_file_p = xbm_file_p (data);
3279 /* Parse the image specification. */
3280 bcopy (xbm_format, fmt, sizeof fmt);
3281 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3282 xassert (parsed_p);
3284 /* Get specified width, and height. */
3285 if (!in_memory_file_p)
3287 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3288 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3289 xassert (img->width > 0 && img->height > 0);
3292 /* Get foreground and background colors, maybe allocate colors. */
3293 if (fmt[XBM_FOREGROUND].count
3294 && STRINGP (fmt[XBM_FOREGROUND].value))
3296 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3297 foreground);
3298 non_default_colors = 1;
3301 if (fmt[XBM_BACKGROUND].count
3302 && STRINGP (fmt[XBM_BACKGROUND].value))
3304 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3305 background);
3306 non_default_colors = 1;
3309 if (in_memory_file_p)
3310 success_p = xbm_load_image (f, img, SDATA (data),
3311 (SDATA (data)
3312 + SBYTES (data)));
3313 else
3315 if (VECTORP (data))
3317 int i;
3318 char *p;
3319 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3321 p = bits = (char *) alloca (nbytes * img->height);
3322 for (i = 0; i < img->height; ++i, p += nbytes)
3324 Lisp_Object line = XVECTOR (data)->contents[i];
3325 if (STRINGP (line))
3326 bcopy (SDATA (line), p, nbytes);
3327 else
3328 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
3331 else if (STRINGP (data))
3332 bits = SDATA (data);
3333 else
3334 bits = XBOOL_VECTOR (data)->data;
3336 /* Create the pixmap. */
3338 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3339 foreground, background,
3340 non_default_colors);
3341 if (img->pixmap)
3342 success_p = 1;
3343 else
3345 image_error ("Unable to create pixmap for XBM image `%s'",
3346 img->spec, Qnil);
3347 x_clear_image (f, img);
3352 return success_p;
3357 /***********************************************************************
3358 XPM images
3359 ***********************************************************************/
3361 #if defined (HAVE_XPM) || defined (MAC_OS)
3363 static int xpm_image_p P_ ((Lisp_Object object));
3364 static int xpm_load P_ ((struct frame *f, struct image *img));
3365 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
3367 #endif /* HAVE_XPM || MAC_OS */
3369 #ifdef HAVE_XPM
3370 #ifdef HAVE_NTGUI
3371 /* Indicate to xpm.h that we don't have Xlib. */
3372 #define FOR_MSW
3373 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3374 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3375 #define XColor xpm_XColor
3376 #define XImage xpm_XImage
3377 #define Display xpm_Display
3378 #define PIXEL_ALREADY_TYPEDEFED
3379 #include "X11/xpm.h"
3380 #undef FOR_MSW
3381 #undef XColor
3382 #undef XImage
3383 #undef Display
3384 #undef PIXEL_ALREADY_TYPEDEFED
3385 #else
3386 #include "X11/xpm.h"
3387 #endif /* HAVE_NTGUI */
3388 #endif /* HAVE_XPM */
3390 #if defined (HAVE_XPM) || defined (MAC_OS)
3391 /* The symbol `xpm' identifying XPM-format images. */
3393 Lisp_Object Qxpm;
3395 /* Indices of image specification fields in xpm_format, below. */
3397 enum xpm_keyword_index
3399 XPM_TYPE,
3400 XPM_FILE,
3401 XPM_DATA,
3402 XPM_ASCENT,
3403 XPM_MARGIN,
3404 XPM_RELIEF,
3405 XPM_ALGORITHM,
3406 XPM_HEURISTIC_MASK,
3407 XPM_MASK,
3408 XPM_COLOR_SYMBOLS,
3409 XPM_BACKGROUND,
3410 XPM_LAST
3413 /* Vector of image_keyword structures describing the format
3414 of valid XPM image specifications. */
3416 static struct image_keyword xpm_format[XPM_LAST] =
3418 {":type", IMAGE_SYMBOL_VALUE, 1},
3419 {":file", IMAGE_STRING_VALUE, 0},
3420 {":data", IMAGE_STRING_VALUE, 0},
3421 {":ascent", IMAGE_ASCENT_VALUE, 0},
3422 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3423 {":relief", IMAGE_INTEGER_VALUE, 0},
3424 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3425 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3426 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3427 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3428 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3431 /* Structure describing the image type XPM. */
3433 static struct image_type xpm_type =
3435 &Qxpm,
3436 xpm_image_p,
3437 xpm_load,
3438 x_clear_image,
3439 NULL
3442 #ifdef HAVE_X_WINDOWS
3444 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3445 functions for allocating image colors. Our own functions handle
3446 color allocation failures more gracefully than the ones on the XPM
3447 lib. */
3449 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3450 #define ALLOC_XPM_COLORS
3451 #endif
3452 #endif /* HAVE_X_WINDOWS */
3454 #ifdef ALLOC_XPM_COLORS
3456 static void xpm_init_color_cache P_ ((struct frame *, XpmAttributes *));
3457 static void xpm_free_color_cache P_ ((void));
3458 static int xpm_lookup_color P_ ((struct frame *, char *, XColor *));
3459 static int xpm_color_bucket P_ ((char *));
3460 static struct xpm_cached_color *xpm_cache_color P_ ((struct frame *, char *,
3461 XColor *, int));
3463 /* An entry in a hash table used to cache color definitions of named
3464 colors. This cache is necessary to speed up XPM image loading in
3465 case we do color allocations ourselves. Without it, we would need
3466 a call to XParseColor per pixel in the image. */
3468 struct xpm_cached_color
3470 /* Next in collision chain. */
3471 struct xpm_cached_color *next;
3473 /* Color definition (RGB and pixel color). */
3474 XColor color;
3476 /* Color name. */
3477 char name[1];
3480 /* The hash table used for the color cache, and its bucket vector
3481 size. */
3483 #define XPM_COLOR_CACHE_BUCKETS 1001
3484 struct xpm_cached_color **xpm_color_cache;
3486 /* Initialize the color cache. */
3488 static void
3489 xpm_init_color_cache (f, attrs)
3490 struct frame *f;
3491 XpmAttributes *attrs;
3493 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3494 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3495 memset (xpm_color_cache, 0, nbytes);
3496 init_color_table ();
3498 if (attrs->valuemask & XpmColorSymbols)
3500 int i;
3501 XColor color;
3503 for (i = 0; i < attrs->numsymbols; ++i)
3504 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3505 attrs->colorsymbols[i].value, &color))
3507 color.pixel = lookup_rgb_color (f, color.red, color.green,
3508 color.blue);
3509 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3514 /* Free the color cache. */
3516 static void
3517 xpm_free_color_cache ()
3519 struct xpm_cached_color *p, *next;
3520 int i;
3522 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3523 for (p = xpm_color_cache[i]; p; p = next)
3525 next = p->next;
3526 xfree (p);
3529 xfree (xpm_color_cache);
3530 xpm_color_cache = NULL;
3531 free_color_table ();
3534 /* Return the bucket index for color named COLOR_NAME in the color
3535 cache. */
3537 static int
3538 xpm_color_bucket (color_name)
3539 char *color_name;
3541 unsigned h = 0;
3542 char *s;
3544 for (s = color_name; *s; ++s)
3545 h = (h << 2) ^ *s;
3546 return h %= XPM_COLOR_CACHE_BUCKETS;
3550 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3551 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3552 entry added. */
3554 static struct xpm_cached_color *
3555 xpm_cache_color (f, color_name, color, bucket)
3556 struct frame *f;
3557 char *color_name;
3558 XColor *color;
3559 int bucket;
3561 size_t nbytes;
3562 struct xpm_cached_color *p;
3564 if (bucket < 0)
3565 bucket = xpm_color_bucket (color_name);
3567 nbytes = sizeof *p + strlen (color_name);
3568 p = (struct xpm_cached_color *) xmalloc (nbytes);
3569 strcpy (p->name, color_name);
3570 p->color = *color;
3571 p->next = xpm_color_cache[bucket];
3572 xpm_color_cache[bucket] = p;
3573 return p;
3576 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3577 return the cached definition in *COLOR. Otherwise, make a new
3578 entry in the cache and allocate the color. Value is zero if color
3579 allocation failed. */
3581 static int
3582 xpm_lookup_color (f, color_name, color)
3583 struct frame *f;
3584 char *color_name;
3585 XColor *color;
3587 struct xpm_cached_color *p;
3588 int h = xpm_color_bucket (color_name);
3590 for (p = xpm_color_cache[h]; p; p = p->next)
3591 if (strcmp (p->name, color_name) == 0)
3592 break;
3594 if (p != NULL)
3595 *color = p->color;
3596 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3597 color_name, color))
3599 color->pixel = lookup_rgb_color (f, color->red, color->green,
3600 color->blue);
3601 p = xpm_cache_color (f, color_name, color, h);
3603 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3604 with transparency, and it's useful. */
3605 else if (strcmp ("opaque", color_name) == 0)
3607 bzero (color, sizeof (XColor)); /* Is this necessary/correct? */
3608 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3609 p = xpm_cache_color (f, color_name, color, h);
3612 return p != NULL;
3616 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3617 CLOSURE is a pointer to the frame on which we allocate the
3618 color. Return in *COLOR the allocated color. Value is non-zero
3619 if successful. */
3621 static int
3622 xpm_alloc_color (dpy, cmap, color_name, color, closure)
3623 Display *dpy;
3624 Colormap cmap;
3625 char *color_name;
3626 XColor *color;
3627 void *closure;
3629 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3633 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3634 is a pointer to the frame on which we allocate the color. Value is
3635 non-zero if successful. */
3637 static int
3638 xpm_free_colors (dpy, cmap, pixels, npixels, closure)
3639 Display *dpy;
3640 Colormap cmap;
3641 Pixel *pixels;
3642 int npixels;
3643 void *closure;
3645 return 1;
3648 #endif /* ALLOC_XPM_COLORS */
3651 #ifdef HAVE_NTGUI
3653 /* XPM library details. */
3655 DEF_IMGLIB_FN (XpmFreeAttributes);
3656 DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
3657 DEF_IMGLIB_FN (XpmReadFileToImage);
3658 DEF_IMGLIB_FN (XImageFree);
3660 static int
3661 init_xpm_functions (Lisp_Object libraries)
3663 HMODULE library;
3665 if (!(library = w32_delayed_load (libraries, Qxpm)))
3666 return 0;
3668 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3669 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3670 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3671 LOAD_IMGLIB_FN (library, XImageFree);
3672 return 1;
3675 #endif /* HAVE_NTGUI */
3678 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3679 for XPM images. Such a list must consist of conses whose car and
3680 cdr are strings. */
3682 static int
3683 xpm_valid_color_symbols_p (color_symbols)
3684 Lisp_Object color_symbols;
3686 while (CONSP (color_symbols))
3688 Lisp_Object sym = XCAR (color_symbols);
3689 if (!CONSP (sym)
3690 || !STRINGP (XCAR (sym))
3691 || !STRINGP (XCDR (sym)))
3692 break;
3693 color_symbols = XCDR (color_symbols);
3696 return NILP (color_symbols);
3700 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3702 static int
3703 xpm_image_p (object)
3704 Lisp_Object object;
3706 struct image_keyword fmt[XPM_LAST];
3707 bcopy (xpm_format, fmt, sizeof fmt);
3708 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3709 /* Either `:file' or `:data' must be present. */
3710 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3711 /* Either no `:color-symbols' or it's a list of conses
3712 whose car and cdr are strings. */
3713 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3714 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3717 #endif /* HAVE_XPM || MAC_OS */
3719 /* Load image IMG which will be displayed on frame F. Value is
3720 non-zero if successful. */
3722 #ifdef HAVE_XPM
3724 static int
3725 xpm_load (f, img)
3726 struct frame *f;
3727 struct image *img;
3729 int rc;
3730 XpmAttributes attrs;
3731 Lisp_Object specified_file, color_symbols;
3732 #ifdef HAVE_NTGUI
3733 HDC hdc;
3734 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3735 #endif /* HAVE_NTGUI */
3737 /* Configure the XPM lib. Use the visual of frame F. Allocate
3738 close colors. Return colors allocated. */
3739 bzero (&attrs, sizeof attrs);
3741 #ifndef HAVE_NTGUI
3742 attrs.visual = FRAME_X_VISUAL (f);
3743 attrs.colormap = FRAME_X_COLORMAP (f);
3744 attrs.valuemask |= XpmVisual;
3745 attrs.valuemask |= XpmColormap;
3746 #endif /* HAVE_NTGUI */
3748 #ifdef ALLOC_XPM_COLORS
3749 /* Allocate colors with our own functions which handle
3750 failing color allocation more gracefully. */
3751 attrs.color_closure = f;
3752 attrs.alloc_color = xpm_alloc_color;
3753 attrs.free_colors = xpm_free_colors;
3754 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3755 #else /* not ALLOC_XPM_COLORS */
3756 /* Let the XPM lib allocate colors. */
3757 attrs.valuemask |= XpmReturnAllocPixels;
3758 #ifdef XpmAllocCloseColors
3759 attrs.alloc_close_colors = 1;
3760 attrs.valuemask |= XpmAllocCloseColors;
3761 #else /* not XpmAllocCloseColors */
3762 attrs.closeness = 600;
3763 attrs.valuemask |= XpmCloseness;
3764 #endif /* not XpmAllocCloseColors */
3765 #endif /* ALLOC_XPM_COLORS */
3767 /* If image specification contains symbolic color definitions, add
3768 these to `attrs'. */
3769 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3770 if (CONSP (color_symbols))
3772 Lisp_Object tail;
3773 XpmColorSymbol *xpm_syms;
3774 int i, size;
3776 attrs.valuemask |= XpmColorSymbols;
3778 /* Count number of symbols. */
3779 attrs.numsymbols = 0;
3780 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3781 ++attrs.numsymbols;
3783 /* Allocate an XpmColorSymbol array. */
3784 size = attrs.numsymbols * sizeof *xpm_syms;
3785 xpm_syms = (XpmColorSymbol *) alloca (size);
3786 bzero (xpm_syms, size);
3787 attrs.colorsymbols = xpm_syms;
3789 /* Fill the color symbol array. */
3790 for (tail = color_symbols, i = 0;
3791 CONSP (tail);
3792 ++i, tail = XCDR (tail))
3794 Lisp_Object name = XCAR (XCAR (tail));
3795 Lisp_Object color = XCDR (XCAR (tail));
3796 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3797 strcpy (xpm_syms[i].name, SDATA (name));
3798 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3799 strcpy (xpm_syms[i].value, SDATA (color));
3803 /* Create a pixmap for the image, either from a file, or from a
3804 string buffer containing data in the same format as an XPM file. */
3805 #ifdef ALLOC_XPM_COLORS
3806 xpm_init_color_cache (f, &attrs);
3807 #endif
3809 specified_file = image_spec_value (img->spec, QCfile, NULL);
3811 #ifdef HAVE_NTGUI
3813 HDC frame_dc = get_frame_dc (f);
3814 hdc = CreateCompatibleDC (frame_dc);
3815 release_frame_dc (f, frame_dc);
3817 #endif /* HAVE_NTGUI */
3819 if (STRINGP (specified_file))
3821 Lisp_Object file = x_find_image_file (specified_file);
3822 if (!STRINGP (file))
3824 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3825 return 0;
3828 #ifdef HAVE_NTGUI
3829 /* XpmReadFileToPixmap is not available in the Windows port of
3830 libxpm. But XpmReadFileToImage almost does what we want. */
3831 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3832 &xpm_image, &xpm_mask,
3833 &attrs);
3834 #else
3835 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3836 SDATA (file), &img->pixmap, &img->mask,
3837 &attrs);
3838 #endif /* HAVE_NTGUI */
3840 else
3842 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3843 #ifdef HAVE_NTGUI
3844 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3845 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3846 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3847 &xpm_image, &xpm_mask,
3848 &attrs);
3849 #else
3850 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3851 SDATA (buffer),
3852 &img->pixmap, &img->mask,
3853 &attrs);
3854 #endif /* HAVE_NTGUI */
3857 if (rc == XpmSuccess)
3859 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3860 img->colors = colors_in_color_table (&img->ncolors);
3861 #else /* not ALLOC_XPM_COLORS */
3862 int i;
3864 #ifdef HAVE_NTGUI
3865 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3866 plus some duplicate attributes. */
3867 if (xpm_image && xpm_image->bitmap)
3869 img->pixmap = xpm_image->bitmap;
3870 /* XImageFree in libXpm frees XImage struct without destroying
3871 the bitmap, which is what we want. */
3872 fn_XImageFree (xpm_image);
3874 if (xpm_mask && xpm_mask->bitmap)
3876 /* The mask appears to be inverted compared with what we expect.
3877 TODO: invert our expectations. See other places where we
3878 have to invert bits because our idea of masks is backwards. */
3879 HGDIOBJ old_obj;
3880 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3882 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3883 SelectObject (hdc, old_obj);
3885 img->mask = xpm_mask->bitmap;
3886 fn_XImageFree (xpm_mask);
3887 DeleteDC (hdc);
3890 DeleteDC (hdc);
3891 #endif /* HAVE_NTGUI */
3893 /* Remember allocated colors. */
3894 img->ncolors = attrs.nalloc_pixels;
3895 img->colors = (unsigned long *) xmalloc (img->ncolors
3896 * sizeof *img->colors);
3897 for (i = 0; i < attrs.nalloc_pixels; ++i)
3899 img->colors[i] = attrs.alloc_pixels[i];
3900 #ifdef DEBUG_X_COLORS
3901 register_color (img->colors[i]);
3902 #endif
3904 #endif /* not ALLOC_XPM_COLORS */
3906 img->width = attrs.width;
3907 img->height = attrs.height;
3908 xassert (img->width > 0 && img->height > 0);
3910 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3911 #ifdef HAVE_NTGUI
3912 fn_XpmFreeAttributes (&attrs);
3913 #else
3914 XpmFreeAttributes (&attrs);
3915 #endif /* HAVE_NTGUI */
3917 else
3919 #ifdef HAVE_NTGUI
3920 DeleteDC (hdc);
3921 #endif /* HAVE_NTGUI */
3923 switch (rc)
3925 case XpmOpenFailed:
3926 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3927 break;
3929 case XpmFileInvalid:
3930 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3931 break;
3933 case XpmNoMemory:
3934 image_error ("Out of memory (%s)", img->spec, Qnil);
3935 break;
3937 case XpmColorFailed:
3938 image_error ("Color allocation error (%s)", img->spec, Qnil);
3939 break;
3941 default:
3942 image_error ("Unknown error (%s)", img->spec, Qnil);
3943 break;
3947 #ifdef ALLOC_XPM_COLORS
3948 xpm_free_color_cache ();
3949 #endif
3950 return rc == XpmSuccess;
3953 #endif /* HAVE_XPM */
3955 #ifdef MAC_OS
3957 /* XPM support functions for Mac OS where libxpm is not available.
3958 Only XPM version 3 (without any extensions) is supported. */
3960 static int xpm_scan P_ ((unsigned char **, unsigned char *,
3961 unsigned char **, int *));
3962 static Lisp_Object xpm_make_color_table_v
3963 P_ ((void (**) (Lisp_Object, unsigned char *, int, Lisp_Object),
3964 Lisp_Object (**) (Lisp_Object, unsigned char *, int)));
3965 static void xpm_put_color_table_v P_ ((Lisp_Object, unsigned char *,
3966 int, Lisp_Object));
3967 static Lisp_Object xpm_get_color_table_v P_ ((Lisp_Object,
3968 unsigned char *, int));
3969 static Lisp_Object xpm_make_color_table_h
3970 P_ ((void (**) (Lisp_Object, unsigned char *, int, Lisp_Object),
3971 Lisp_Object (**) (Lisp_Object, unsigned char *, int)));
3972 static void xpm_put_color_table_h P_ ((Lisp_Object, unsigned char *,
3973 int, Lisp_Object));
3974 static Lisp_Object xpm_get_color_table_h P_ ((Lisp_Object,
3975 unsigned char *, int));
3976 static int xpm_str_to_color_key P_ ((char *));
3977 static int xpm_load_image P_ ((struct frame *, struct image *,
3978 unsigned char *, unsigned char *));
3980 /* Tokens returned from xpm_scan. */
3982 enum xpm_token
3984 XPM_TK_IDENT = 256,
3985 XPM_TK_STRING,
3986 XPM_TK_EOF
3989 /* Scan an XPM data and return a character (< 256) or a token defined
3990 by enum xpm_token above. *S and END are the start (inclusive) and
3991 the end (exclusive) addresses of the data, respectively. Advance
3992 *S while scanning. If token is either XPM_TK_IDENT or
3993 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3994 length of the corresponding token, respectively. */
3996 static int
3997 xpm_scan (s, end, beg, len)
3998 unsigned char **s, *end, **beg;
3999 int *len;
4001 int c;
4003 while (*s < end)
4005 /* Skip white-space. */
4006 while (*s < end && (c = *(*s)++, isspace (c)))
4009 /* gnus-pointer.xpm uses '-' in its identifier.
4010 sb-dir-plus.xpm uses '+' in its identifier. */
4011 if (isalpha (c) || c == '_' || c == '-' || c == '+')
4013 *beg = *s - 1;
4014 while (*s < end &&
4015 (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
4016 ++*s;
4017 *len = *s - *beg;
4018 return XPM_TK_IDENT;
4020 else if (c == '"')
4022 *beg = *s;
4023 while (*s < end && **s != '"')
4024 ++*s;
4025 *len = *s - *beg;
4026 if (*s < end)
4027 ++*s;
4028 return XPM_TK_STRING;
4030 else if (c == '/')
4032 if (*s < end && **s == '*')
4034 /* C-style comment. */
4035 ++*s;
4038 while (*s < end && *(*s)++ != '*')
4041 while (*s < end && **s != '/');
4042 if (*s < end)
4043 ++*s;
4045 else
4046 return c;
4048 else
4049 return c;
4052 return XPM_TK_EOF;
4055 /* Functions for color table lookup in XPM data. A Key is a string
4056 specifying the color of each pixel in XPM data. A value is either
4057 an integer that specifies a pixel color, Qt that specifies
4058 transparency, or Qnil for the unspecified color. If the length of
4059 the key string is one, a vector is used as a table. Otherwise, a
4060 hash table is used. */
4062 static Lisp_Object
4063 xpm_make_color_table_v (put_func, get_func)
4064 void (**put_func) (Lisp_Object, unsigned char *, int, Lisp_Object);
4065 Lisp_Object (**get_func) (Lisp_Object, unsigned char *, int);
4067 *put_func = xpm_put_color_table_v;
4068 *get_func = xpm_get_color_table_v;
4069 return Fmake_vector (make_number (256), Qnil);
4072 static void
4073 xpm_put_color_table_v (color_table, chars_start, chars_len, color)
4074 Lisp_Object color_table;
4075 unsigned char *chars_start;
4076 int chars_len;
4077 Lisp_Object color;
4079 XVECTOR (color_table)->contents[*chars_start] = color;
4082 static Lisp_Object
4083 xpm_get_color_table_v (color_table, chars_start, chars_len)
4084 Lisp_Object color_table;
4085 unsigned char *chars_start;
4086 int chars_len;
4088 return XVECTOR (color_table)->contents[*chars_start];
4091 static Lisp_Object
4092 xpm_make_color_table_h (put_func, get_func)
4093 void (**put_func) (Lisp_Object, unsigned char *, int, Lisp_Object);
4094 Lisp_Object (**get_func) (Lisp_Object, unsigned char *, int);
4096 *put_func = xpm_put_color_table_h;
4097 *get_func = xpm_get_color_table_h;
4098 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
4099 make_float (DEFAULT_REHASH_SIZE),
4100 make_float (DEFAULT_REHASH_THRESHOLD),
4101 Qnil, Qnil, Qnil);
4104 static void
4105 xpm_put_color_table_h (color_table, chars_start, chars_len, color)
4106 Lisp_Object color_table;
4107 unsigned char *chars_start;
4108 int chars_len;
4109 Lisp_Object color;
4111 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4112 unsigned hash_code;
4113 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4115 hash_lookup (table, chars, &hash_code);
4116 hash_put (table, chars, color, hash_code);
4119 static Lisp_Object
4120 xpm_get_color_table_h (color_table, chars_start, chars_len)
4121 Lisp_Object color_table;
4122 unsigned char *chars_start;
4123 int chars_len;
4125 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4126 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
4127 NULL);
4129 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4132 enum xpm_color_key {
4133 XPM_COLOR_KEY_S,
4134 XPM_COLOR_KEY_M,
4135 XPM_COLOR_KEY_G4,
4136 XPM_COLOR_KEY_G,
4137 XPM_COLOR_KEY_C
4140 static char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4142 static int
4143 xpm_str_to_color_key (s)
4144 char *s;
4146 int i;
4148 for (i = 0;
4149 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
4150 i++)
4151 if (strcmp (xpm_color_key_strings[i], s) == 0)
4152 return i;
4153 return -1;
4156 static int
4157 xpm_load_image (f, img, contents, end)
4158 struct frame *f;
4159 struct image *img;
4160 unsigned char *contents, *end;
4162 unsigned char *s = contents, *beg, *str;
4163 unsigned char buffer[BUFSIZ];
4164 int width, height, x, y;
4165 int num_colors, chars_per_pixel;
4166 int len, LA1;
4167 void (*put_color_table) (Lisp_Object, unsigned char *, int, Lisp_Object);
4168 Lisp_Object (*get_color_table) (Lisp_Object, unsigned char *, int);
4169 Lisp_Object frame, color_symbols, color_table;
4170 int best_key, have_mask = 0;
4171 XImagePtr ximg = NULL, mask_img = NULL;
4173 #define match() \
4174 LA1 = xpm_scan (&s, end, &beg, &len)
4176 #define expect(TOKEN) \
4177 if (LA1 != (TOKEN)) \
4178 goto failure; \
4179 else \
4180 match ()
4182 #define expect_ident(IDENT) \
4183 if (LA1 == XPM_TK_IDENT \
4184 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4185 match (); \
4186 else \
4187 goto failure
4189 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4190 goto failure;
4191 s += 9;
4192 match();
4193 expect_ident ("static");
4194 expect_ident ("char");
4195 expect ('*');
4196 expect (XPM_TK_IDENT);
4197 expect ('[');
4198 expect (']');
4199 expect ('=');
4200 expect ('{');
4201 expect (XPM_TK_STRING);
4202 if (len >= BUFSIZ)
4203 goto failure;
4204 memcpy (buffer, beg, len);
4205 buffer[len] = '\0';
4206 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4207 &num_colors, &chars_per_pixel) != 4
4208 || width <= 0 || height <= 0
4209 || num_colors <= 0 || chars_per_pixel <= 0)
4210 goto failure;
4212 if (!check_image_size (f, width, height))
4214 image_error ("Invalid image size", Qnil, Qnil);
4215 goto failure;
4218 expect (',');
4220 XSETFRAME (frame, f);
4221 if (!NILP (Fxw_display_color_p (frame)))
4222 best_key = XPM_COLOR_KEY_C;
4223 else if (!NILP (Fx_display_grayscale_p (frame)))
4224 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4225 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4226 else
4227 best_key = XPM_COLOR_KEY_M;
4229 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4230 if (chars_per_pixel == 1)
4231 color_table = xpm_make_color_table_v (&put_color_table,
4232 &get_color_table);
4233 else
4234 color_table = xpm_make_color_table_h (&put_color_table,
4235 &get_color_table);
4237 while (num_colors-- > 0)
4239 unsigned char *color, *max_color;
4240 int key, next_key, max_key = 0;
4241 Lisp_Object symbol_color = Qnil, color_val;
4242 XColor cdef;
4244 expect (XPM_TK_STRING);
4245 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4246 goto failure;
4247 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4248 buffer[len - chars_per_pixel] = '\0';
4250 str = strtok (buffer, " \t");
4251 if (str == NULL)
4252 goto failure;
4253 key = xpm_str_to_color_key (str);
4254 if (key < 0)
4255 goto failure;
4258 color = strtok (NULL, " \t");
4259 if (color == NULL)
4260 goto failure;
4262 while (str = strtok (NULL, " \t"))
4264 next_key = xpm_str_to_color_key (str);
4265 if (next_key >= 0)
4266 break;
4267 color[strlen (color)] = ' ';
4270 if (key == XPM_COLOR_KEY_S)
4272 if (NILP (symbol_color))
4273 symbol_color = build_string (color);
4275 else if (max_key < key && key <= best_key)
4277 max_key = key;
4278 max_color = color;
4280 key = next_key;
4282 while (str);
4284 color_val = Qnil;
4285 if (!NILP (color_symbols) && !NILP (symbol_color))
4287 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4289 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4290 if (xstricmp (SDATA (XCDR (specified_color)), "None") == 0)
4291 color_val = Qt;
4292 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
4293 &cdef, 0))
4294 color_val = make_number (cdef.pixel);
4296 if (NILP (color_val) && max_key > 0)
4297 if (xstricmp (max_color, "None") == 0)
4298 color_val = Qt;
4299 else if (x_defined_color (f, max_color, &cdef, 0))
4300 color_val = make_number (cdef.pixel);
4301 if (!NILP (color_val))
4302 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4304 expect (',');
4307 if (!x_create_x_image_and_pixmap (f, width, height, 0,
4308 &ximg, &img->pixmap)
4309 || !x_create_x_image_and_pixmap (f, width, height, 1,
4310 &mask_img, &img->mask))
4312 image_error ("Out of memory (%s)", img->spec, Qnil);
4313 goto error;
4316 for (y = 0; y < height; y++)
4318 expect (XPM_TK_STRING);
4319 str = beg;
4320 if (len < width * chars_per_pixel)
4321 goto failure;
4322 for (x = 0; x < width; x++, str += chars_per_pixel)
4324 Lisp_Object color_val =
4325 (*get_color_table) (color_table, str, chars_per_pixel);
4327 XPutPixel (ximg, x, y,
4328 (INTEGERP (color_val) ? XINT (color_val)
4329 : FRAME_FOREGROUND_PIXEL (f)));
4330 XPutPixel (mask_img, x, y,
4331 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4332 : (have_mask = 1, PIX_MASK_RETAIN)));
4334 if (y + 1 < height)
4335 expect (',');
4338 img->width = width;
4339 img->height = height;
4341 x_put_x_image (f, ximg, img->pixmap, width, height);
4342 x_destroy_x_image (ximg);
4343 if (have_mask)
4345 /* Fill in the background_transparent field while we have the
4346 mask handy. */
4347 image_background_transparent (img, f, mask_img);
4349 x_put_x_image (f, mask_img, img->mask, width, height);
4350 x_destroy_x_image (mask_img);
4352 else
4354 x_destroy_x_image (mask_img);
4355 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4356 img->mask = NO_PIXMAP;
4359 return 1;
4361 failure:
4362 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4363 error:
4364 x_destroy_x_image (ximg);
4365 x_destroy_x_image (mask_img);
4366 x_clear_image (f, img);
4367 return 0;
4369 #undef match
4370 #undef expect
4371 #undef expect_ident
4374 static int
4375 xpm_load (f, img)
4376 struct frame *f;
4377 struct image *img;
4379 int success_p = 0;
4380 Lisp_Object file_name;
4382 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4383 file_name = image_spec_value (img->spec, QCfile, NULL);
4384 if (STRINGP (file_name))
4386 Lisp_Object file;
4387 unsigned char *contents;
4388 int size;
4389 struct gcpro gcpro1;
4391 file = x_find_image_file (file_name);
4392 GCPRO1 (file);
4393 if (!STRINGP (file))
4395 image_error ("Cannot find image file `%s'", file_name, Qnil);
4396 UNGCPRO;
4397 return 0;
4400 contents = slurp_file (SDATA (file), &size);
4401 if (contents == NULL)
4403 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4404 UNGCPRO;
4405 return 0;
4408 success_p = xpm_load_image (f, img, contents, contents + size);
4409 xfree (contents);
4410 UNGCPRO;
4412 else
4414 Lisp_Object data;
4416 data = image_spec_value (img->spec, QCdata, NULL);
4417 success_p = xpm_load_image (f, img, SDATA (data),
4418 SDATA (data) + SBYTES (data));
4421 return success_p;
4424 #endif /* MAC_OS */
4428 /***********************************************************************
4429 Color table
4430 ***********************************************************************/
4432 #ifdef COLOR_TABLE_SUPPORT
4434 /* An entry in the color table mapping an RGB color to a pixel color. */
4436 struct ct_color
4438 int r, g, b;
4439 unsigned long pixel;
4441 /* Next in color table collision list. */
4442 struct ct_color *next;
4445 /* The bucket vector size to use. Must be prime. */
4447 #define CT_SIZE 101
4449 /* Value is a hash of the RGB color given by R, G, and B. */
4451 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4453 /* The color hash table. */
4455 struct ct_color **ct_table;
4457 /* Number of entries in the color table. */
4459 int ct_colors_allocated;
4461 /* Initialize the color table. */
4463 static void
4464 init_color_table ()
4466 int size = CT_SIZE * sizeof (*ct_table);
4467 ct_table = (struct ct_color **) xmalloc (size);
4468 bzero (ct_table, size);
4469 ct_colors_allocated = 0;
4473 /* Free memory associated with the color table. */
4475 static void
4476 free_color_table ()
4478 int i;
4479 struct ct_color *p, *next;
4481 for (i = 0; i < CT_SIZE; ++i)
4482 for (p = ct_table[i]; p; p = next)
4484 next = p->next;
4485 xfree (p);
4488 xfree (ct_table);
4489 ct_table = NULL;
4493 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4494 entry for that color already is in the color table, return the
4495 pixel color of that entry. Otherwise, allocate a new color for R,
4496 G, B, and make an entry in the color table. */
4498 static unsigned long
4499 lookup_rgb_color (f, r, g, b)
4500 struct frame *f;
4501 int r, g, b;
4503 unsigned hash = CT_HASH_RGB (r, g, b);
4504 int i = hash % CT_SIZE;
4505 struct ct_color *p;
4506 Display_Info *dpyinfo;
4508 /* Handle TrueColor visuals specially, which improves performance by
4509 two orders of magnitude. Freeing colors on TrueColor visuals is
4510 a nop, and pixel colors specify RGB values directly. See also
4511 the Xlib spec, chapter 3.1. */
4512 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4513 if (dpyinfo->red_bits > 0)
4515 unsigned long pr, pg, pb;
4517 /* Apply gamma-correction like normal color allocation does. */
4518 if (f->gamma)
4520 XColor color;
4521 color.red = r, color.green = g, color.blue = b;
4522 gamma_correct (f, &color);
4523 r = color.red, g = color.green, b = color.blue;
4526 /* Scale down RGB values to the visual's bits per RGB, and shift
4527 them to the right position in the pixel color. Note that the
4528 original RGB values are 16-bit values, as usual in X. */
4529 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4530 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4531 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4533 /* Assemble the pixel color. */
4534 return pr | pg | pb;
4537 for (p = ct_table[i]; p; p = p->next)
4538 if (p->r == r && p->g == g && p->b == b)
4539 break;
4541 if (p == NULL)
4544 #ifdef HAVE_X_WINDOWS
4545 XColor color;
4546 Colormap cmap;
4547 int rc;
4549 color.red = r;
4550 color.green = g;
4551 color.blue = b;
4553 cmap = FRAME_X_COLORMAP (f);
4554 rc = x_alloc_nearest_color (f, cmap, &color);
4555 if (rc)
4557 ++ct_colors_allocated;
4558 p = (struct ct_color *) xmalloc (sizeof *p);
4559 p->r = r;
4560 p->g = g;
4561 p->b = b;
4562 p->pixel = color.pixel;
4563 p->next = ct_table[i];
4564 ct_table[i] = p;
4566 else
4567 return FRAME_FOREGROUND_PIXEL (f);
4569 #else
4570 COLORREF color;
4571 #ifdef HAVE_NTGUI
4572 color = PALETTERGB (r, g, b);
4573 #else
4574 color = RGB_TO_ULONG (r, g, b);
4575 #endif /* HAVE_NTGUI */
4576 ++ct_colors_allocated;
4577 p = (struct ct_color *) xmalloc (sizeof *p);
4578 p->r = r;
4579 p->g = g;
4580 p->b = b;
4581 p->pixel = color;
4582 p->next = ct_table[i];
4583 ct_table[i] = p;
4584 #endif /* HAVE_X_WINDOWS */
4588 return p->pixel;
4592 /* Look up pixel color PIXEL which is used on frame F in the color
4593 table. If not already present, allocate it. Value is PIXEL. */
4595 static unsigned long
4596 lookup_pixel_color (f, pixel)
4597 struct frame *f;
4598 unsigned long pixel;
4600 int i = pixel % CT_SIZE;
4601 struct ct_color *p;
4603 for (p = ct_table[i]; p; p = p->next)
4604 if (p->pixel == pixel)
4605 break;
4607 if (p == NULL)
4609 XColor color;
4610 Colormap cmap;
4611 int rc;
4613 #ifdef HAVE_X_WINDOWS
4614 cmap = FRAME_X_COLORMAP (f);
4615 color.pixel = pixel;
4616 x_query_color (f, &color);
4617 rc = x_alloc_nearest_color (f, cmap, &color);
4618 #else
4619 BLOCK_INPUT;
4620 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4621 color.pixel = pixel;
4622 XQueryColor (NULL, cmap, &color);
4623 rc = x_alloc_nearest_color (f, cmap, &color);
4624 UNBLOCK_INPUT;
4625 #endif /* HAVE_X_WINDOWS */
4627 if (rc)
4629 ++ct_colors_allocated;
4631 p = (struct ct_color *) xmalloc (sizeof *p);
4632 p->r = color.red;
4633 p->g = color.green;
4634 p->b = color.blue;
4635 p->pixel = pixel;
4636 p->next = ct_table[i];
4637 ct_table[i] = p;
4639 else
4640 return FRAME_FOREGROUND_PIXEL (f);
4642 return p->pixel;
4646 /* Value is a vector of all pixel colors contained in the color table,
4647 allocated via xmalloc. Set *N to the number of colors. */
4649 static unsigned long *
4650 colors_in_color_table (n)
4651 int *n;
4653 int i, j;
4654 struct ct_color *p;
4655 unsigned long *colors;
4657 if (ct_colors_allocated == 0)
4659 *n = 0;
4660 colors = NULL;
4662 else
4664 colors = (unsigned long *) xmalloc (ct_colors_allocated
4665 * sizeof *colors);
4666 *n = ct_colors_allocated;
4668 for (i = j = 0; i < CT_SIZE; ++i)
4669 for (p = ct_table[i]; p; p = p->next)
4670 colors[j++] = p->pixel;
4673 return colors;
4676 #else /* COLOR_TABLE_SUPPORT */
4678 static unsigned long
4679 lookup_rgb_color (f, r, g, b)
4680 struct frame *f;
4681 int r, g, b;
4683 unsigned long pixel;
4685 #ifdef MAC_OS
4686 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4687 gamma_correct (f, &pixel);
4688 #endif /* MAC_OS */
4690 #ifdef HAVE_NTGUI
4691 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4692 #endif /* HAVE_NTGUI */
4694 return pixel;
4697 static void
4698 init_color_table ()
4701 #endif /* COLOR_TABLE_SUPPORT */
4704 /***********************************************************************
4705 Algorithms
4706 ***********************************************************************/
4708 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
4709 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
4710 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
4712 #ifdef HAVE_NTGUI
4713 static void XPutPixel (XImagePtr , int, int, COLORREF);
4714 #endif /* HAVE_NTGUI */
4716 /* Non-zero means draw a cross on images having `:conversion
4717 disabled'. */
4719 int cross_disabled_images;
4721 /* Edge detection matrices for different edge-detection
4722 strategies. */
4724 static int emboss_matrix[9] = {
4725 /* x - 1 x x + 1 */
4726 2, -1, 0, /* y - 1 */
4727 -1, 0, 1, /* y */
4728 0, 1, -2 /* y + 1 */
4731 static int laplace_matrix[9] = {
4732 /* x - 1 x x + 1 */
4733 1, 0, 0, /* y - 1 */
4734 0, 0, 0, /* y */
4735 0, 0, -1 /* y + 1 */
4738 /* Value is the intensity of the color whose red/green/blue values
4739 are R, G, and B. */
4741 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4744 /* On frame F, return an array of XColor structures describing image
4745 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4746 non-zero means also fill the red/green/blue members of the XColor
4747 structures. Value is a pointer to the array of XColors structures,
4748 allocated with xmalloc; it must be freed by the caller. */
4750 static XColor *
4751 x_to_xcolors (f, img, rgb_p)
4752 struct frame *f;
4753 struct image *img;
4754 int rgb_p;
4756 int x, y;
4757 XColor *colors, *p;
4758 XImagePtr_or_DC ximg;
4759 #ifdef HAVE_NTGUI
4760 HDC hdc;
4761 HGDIOBJ prev;
4762 #endif /* HAVE_NTGUI */
4764 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4766 #ifndef HAVE_NTGUI
4767 /* Get the X image IMG->pixmap. */
4768 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4769 0, 0, img->width, img->height, ~0, ZPixmap);
4770 #else
4771 /* Load the image into a memory device context. */
4772 hdc = get_frame_dc (f);
4773 ximg = CreateCompatibleDC (hdc);
4774 release_frame_dc (f, hdc);
4775 prev = SelectObject (ximg, img->pixmap);
4776 #endif /* HAVE_NTGUI */
4778 /* Fill the `pixel' members of the XColor array. I wished there
4779 were an easy and portable way to circumvent XGetPixel. */
4780 p = colors;
4781 for (y = 0; y < img->height; ++y)
4783 XColor *row = p;
4785 #ifdef HAVE_X_WINDOWS
4786 for (x = 0; x < img->width; ++x, ++p)
4787 p->pixel = XGetPixel (ximg, x, y);
4788 if (rgb_p)
4789 x_query_colors (f, row, img->width);
4791 #else
4793 for (x = 0; x < img->width; ++x, ++p)
4795 /* W32_TODO: palette support needed here? */
4796 p->pixel = GET_PIXEL (ximg, x, y);
4797 if (rgb_p)
4799 #ifdef MAC_OS
4800 p->red = RED16_FROM_ULONG (p->pixel);
4801 p->green = GREEN16_FROM_ULONG (p->pixel);
4802 p->blue = BLUE16_FROM_ULONG (p->pixel);
4803 #endif /* MAC_OS */
4804 #ifdef HAVE_NTGUI
4805 p->red = 256 * GetRValue (p->pixel);
4806 p->green = 256 * GetGValue (p->pixel);
4807 p->blue = 256 * GetBValue (p->pixel);
4808 #endif /* HAVE_NTGUI */
4811 #endif /* HAVE_X_WINDOWS */
4814 Destroy_Image (ximg, prev);
4816 return colors;
4819 #ifdef HAVE_NTGUI
4821 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4822 created with CreateDIBSection, with the pointer to the bit values
4823 stored in ximg->data. */
4825 static void XPutPixel (ximg, x, y, color)
4826 XImagePtr ximg;
4827 int x, y;
4828 COLORREF color;
4830 int width = ximg->info.bmiHeader.biWidth;
4831 int height = ximg->info.bmiHeader.biHeight;
4832 unsigned char * pixel;
4834 /* True color images. */
4835 if (ximg->info.bmiHeader.biBitCount == 24)
4837 int rowbytes = width * 3;
4838 /* Ensure scanlines are aligned on 4 byte boundaries. */
4839 if (rowbytes % 4)
4840 rowbytes += 4 - (rowbytes % 4);
4842 pixel = ximg->data + y * rowbytes + x * 3;
4843 /* Windows bitmaps are in BGR order. */
4844 *pixel = GetBValue (color);
4845 *(pixel + 1) = GetGValue (color);
4846 *(pixel + 2) = GetRValue (color);
4848 /* Monochrome images. */
4849 else if (ximg->info.bmiHeader.biBitCount == 1)
4851 int rowbytes = width / 8;
4852 /* Ensure scanlines are aligned on 4 byte boundaries. */
4853 if (rowbytes % 4)
4854 rowbytes += 4 - (rowbytes % 4);
4855 pixel = ximg->data + y * rowbytes + x / 8;
4856 /* Filter out palette info. */
4857 if (color & 0x00ffffff)
4858 *pixel = *pixel | (1 << x % 8);
4859 else
4860 *pixel = *pixel & ~(1 << x % 8);
4862 else
4863 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4866 #endif /* HAVE_NTGUI */
4868 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4869 RGB members are set. F is the frame on which this all happens.
4870 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4872 static void
4873 x_from_xcolors (f, img, colors)
4874 struct frame *f;
4875 struct image *img;
4876 XColor *colors;
4878 int x, y;
4879 XImagePtr oimg;
4880 Pixmap pixmap;
4881 XColor *p;
4883 init_color_table ();
4885 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4886 &oimg, &pixmap);
4887 p = colors;
4888 for (y = 0; y < img->height; ++y)
4889 for (x = 0; x < img->width; ++x, ++p)
4891 unsigned long pixel;
4892 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4893 XPutPixel (oimg, x, y, pixel);
4896 xfree (colors);
4897 x_clear_image_1 (f, img, 1, 0, 1);
4899 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4900 x_destroy_x_image (oimg);
4901 img->pixmap = pixmap;
4902 #ifdef COLOR_TABLE_SUPPORT
4903 img->colors = colors_in_color_table (&img->ncolors);
4904 free_color_table ();
4905 #endif /* COLOR_TABLE_SUPPORT */
4909 /* On frame F, perform edge-detection on image IMG.
4911 MATRIX is a nine-element array specifying the transformation
4912 matrix. See emboss_matrix for an example.
4914 COLOR_ADJUST is a color adjustment added to each pixel of the
4915 outgoing image. */
4917 static void
4918 x_detect_edges (f, img, matrix, color_adjust)
4919 struct frame *f;
4920 struct image *img;
4921 int matrix[9], color_adjust;
4923 XColor *colors = x_to_xcolors (f, img, 1);
4924 XColor *new, *p;
4925 int x, y, i, sum;
4927 for (i = sum = 0; i < 9; ++i)
4928 sum += abs (matrix[i]);
4930 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4932 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4934 for (y = 0; y < img->height; ++y)
4936 p = COLOR (new, 0, y);
4937 p->red = p->green = p->blue = 0xffff/2;
4938 p = COLOR (new, img->width - 1, y);
4939 p->red = p->green = p->blue = 0xffff/2;
4942 for (x = 1; x < img->width - 1; ++x)
4944 p = COLOR (new, x, 0);
4945 p->red = p->green = p->blue = 0xffff/2;
4946 p = COLOR (new, x, img->height - 1);
4947 p->red = p->green = p->blue = 0xffff/2;
4950 for (y = 1; y < img->height - 1; ++y)
4952 p = COLOR (new, 1, y);
4954 for (x = 1; x < img->width - 1; ++x, ++p)
4956 int r, g, b, y1, x1;
4958 r = g = b = i = 0;
4959 for (y1 = y - 1; y1 < y + 2; ++y1)
4960 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
4961 if (matrix[i])
4963 XColor *t = COLOR (colors, x1, y1);
4964 r += matrix[i] * t->red;
4965 g += matrix[i] * t->green;
4966 b += matrix[i] * t->blue;
4969 r = (r / sum + color_adjust) & 0xffff;
4970 g = (g / sum + color_adjust) & 0xffff;
4971 b = (b / sum + color_adjust) & 0xffff;
4972 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4976 xfree (colors);
4977 x_from_xcolors (f, img, new);
4979 #undef COLOR
4983 /* Perform the pre-defined `emboss' edge-detection on image IMG
4984 on frame F. */
4986 static void
4987 x_emboss (f, img)
4988 struct frame *f;
4989 struct image *img;
4991 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4995 /* Transform image IMG which is used on frame F with a Laplace
4996 edge-detection algorithm. The result is an image that can be used
4997 to draw disabled buttons, for example. */
4999 static void
5000 x_laplace (f, img)
5001 struct frame *f;
5002 struct image *img;
5004 x_detect_edges (f, img, laplace_matrix, 45000);
5008 /* Perform edge-detection on image IMG on frame F, with specified
5009 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
5011 MATRIX must be either
5013 - a list of at least 9 numbers in row-major form
5014 - a vector of at least 9 numbers
5016 COLOR_ADJUST nil means use a default; otherwise it must be a
5017 number. */
5019 static void
5020 x_edge_detection (f, img, matrix, color_adjust)
5021 struct frame *f;
5022 struct image *img;
5023 Lisp_Object matrix, color_adjust;
5025 int i = 0;
5026 int trans[9];
5028 if (CONSP (matrix))
5030 for (i = 0;
5031 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
5032 ++i, matrix = XCDR (matrix))
5033 trans[i] = XFLOATINT (XCAR (matrix));
5035 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
5037 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
5038 trans[i] = XFLOATINT (AREF (matrix, i));
5041 if (NILP (color_adjust))
5042 color_adjust = make_number (0xffff / 2);
5044 if (i == 9 && NUMBERP (color_adjust))
5045 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
5049 /* Transform image IMG on frame F so that it looks disabled. */
5051 static void
5052 x_disable_image (f, img)
5053 struct frame *f;
5054 struct image *img;
5056 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
5057 #ifdef HAVE_NTGUI
5058 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
5059 #else
5060 int n_planes = dpyinfo->n_planes;
5061 #endif /* HAVE_NTGUI */
5063 if (n_planes >= 2)
5065 /* Color (or grayscale). Convert to gray, and equalize. Just
5066 drawing such images with a stipple can look very odd, so
5067 we're using this method instead. */
5068 XColor *colors = x_to_xcolors (f, img, 1);
5069 XColor *p, *end;
5070 const int h = 15000;
5071 const int l = 30000;
5073 for (p = colors, end = colors + img->width * img->height;
5074 p < end;
5075 ++p)
5077 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
5078 int i2 = (0xffff - h - l) * i / 0xffff + l;
5079 p->red = p->green = p->blue = i2;
5082 x_from_xcolors (f, img, colors);
5085 /* Draw a cross over the disabled image, if we must or if we
5086 should. */
5087 if (n_planes < 2 || cross_disabled_images)
5089 #ifndef HAVE_NTGUI
5090 Display *dpy = FRAME_X_DISPLAY (f);
5091 GC gc;
5093 #ifdef MAC_OS
5094 #define XCreateGC_pixmap(dpy, pixmap) XCreateGC (dpy, NULL, 0, NULL)
5095 #define MaskForeground(f) PIX_MASK_DRAW
5096 #else
5097 #define XCreateGC_pixmap(dpy, pixmap) XCreateGC (dpy, pixmap, 0, NULL)
5098 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
5099 #endif
5101 gc = XCreateGC_pixmap (dpy, img->pixmap);
5102 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
5103 XDrawLine (dpy, img->pixmap, gc, 0, 0,
5104 img->width - 1, img->height - 1);
5105 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
5106 img->width - 1, 0);
5107 XFreeGC (dpy, gc);
5109 if (img->mask)
5111 gc = XCreateGC_pixmap (dpy, img->mask);
5112 XSetForeground (dpy, gc, MaskForeground (f));
5113 XDrawLine (dpy, img->mask, gc, 0, 0,
5114 img->width - 1, img->height - 1);
5115 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
5116 img->width - 1, 0);
5117 XFreeGC (dpy, gc);
5119 #else
5120 HDC hdc, bmpdc;
5121 HGDIOBJ prev;
5123 hdc = get_frame_dc (f);
5124 bmpdc = CreateCompatibleDC (hdc);
5125 release_frame_dc (f, hdc);
5127 prev = SelectObject (bmpdc, img->pixmap);
5129 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5130 MoveToEx (bmpdc, 0, 0, NULL);
5131 LineTo (bmpdc, img->width - 1, img->height - 1);
5132 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5133 LineTo (bmpdc, img->width - 1, 0);
5135 if (img->mask)
5137 SelectObject (bmpdc, img->mask);
5138 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5139 MoveToEx (bmpdc, 0, 0, NULL);
5140 LineTo (bmpdc, img->width - 1, img->height - 1);
5141 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5142 LineTo (bmpdc, img->width - 1, 0);
5144 SelectObject (bmpdc, prev);
5145 DeleteDC (bmpdc);
5146 #endif /* HAVE_NTGUI */
5151 /* Build a mask for image IMG which is used on frame F. FILE is the
5152 name of an image file, for error messages. HOW determines how to
5153 determine the background color of IMG. If it is a list '(R G B)',
5154 with R, G, and B being integers >= 0, take that as the color of the
5155 background. Otherwise, determine the background color of IMG
5156 heuristically. Value is non-zero if successful. */
5158 static int
5159 x_build_heuristic_mask (f, img, how)
5160 struct frame *f;
5161 struct image *img;
5162 Lisp_Object how;
5164 XImagePtr_or_DC ximg;
5165 #ifndef HAVE_NTGUI
5166 XImagePtr mask_img;
5167 #else
5168 HDC frame_dc;
5169 HGDIOBJ prev;
5170 char *mask_img;
5171 int row_width;
5172 #endif /* HAVE_NTGUI */
5173 int x, y, rc, use_img_background;
5174 unsigned long bg = 0;
5176 if (img->mask)
5178 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
5179 img->mask = NO_PIXMAP;
5180 img->background_transparent_valid = 0;
5183 #ifndef HAVE_NTGUI
5184 /* Create an image and pixmap serving as mask. */
5185 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
5186 &mask_img, &img->mask);
5187 if (!rc)
5188 return 0;
5190 /* Get the X image of IMG->pixmap. */
5191 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
5192 img->width, img->height,
5193 ~0, ZPixmap);
5194 #else
5195 /* Create the bit array serving as mask. */
5196 row_width = (img->width + 7) / 8;
5197 mask_img = xmalloc (row_width * img->height);
5198 bzero (mask_img, row_width * img->height);
5200 /* Create a memory device context for IMG->pixmap. */
5201 frame_dc = get_frame_dc (f);
5202 ximg = CreateCompatibleDC (frame_dc);
5203 release_frame_dc (f, frame_dc);
5204 prev = SelectObject (ximg, img->pixmap);
5205 #endif /* HAVE_NTGUI */
5207 /* Determine the background color of ximg. If HOW is `(R G B)'
5208 take that as color. Otherwise, use the image's background color. */
5209 use_img_background = 1;
5211 if (CONSP (how))
5213 int rgb[3], i;
5215 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5217 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5218 how = XCDR (how);
5221 if (i == 3 && NILP (how))
5223 char color_name[30];
5224 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
5225 bg = (
5226 #ifdef HAVE_NTGUI
5227 0x00ffffff & /* Filter out palette info. */
5228 #endif /* HAVE_NTGUI */
5229 x_alloc_image_color (f, img, build_string (color_name), 0));
5230 use_img_background = 0;
5234 if (use_img_background)
5235 bg = four_corners_best (ximg, img->width, img->height);
5237 /* Set all bits in mask_img to 1 whose color in ximg is different
5238 from the background color bg. */
5239 #ifndef HAVE_NTGUI
5240 for (y = 0; y < img->height; ++y)
5241 for (x = 0; x < img->width; ++x)
5242 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5243 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5245 /* Fill in the background_transparent field while we have the mask handy. */
5246 image_background_transparent (img, f, mask_img);
5248 /* Put mask_img into img->mask. */
5249 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5250 x_destroy_x_image (mask_img);
5252 #else
5253 for (y = 0; y < img->height; ++y)
5254 for (x = 0; x < img->width; ++x)
5256 COLORREF p = GetPixel (ximg, x, y);
5257 if (p != bg)
5258 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5261 /* Create the mask image. */
5262 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5263 mask_img);
5264 /* Fill in the background_transparent field while we have the mask handy. */
5265 SelectObject (ximg, img->mask);
5266 image_background_transparent (img, f, ximg);
5268 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5269 xfree (mask_img);
5270 #endif /* HAVE_NTGUI */
5272 Destroy_Image (ximg, prev);
5274 return 1;
5278 /***********************************************************************
5279 PBM (mono, gray, color)
5280 ***********************************************************************/
5282 static int pbm_image_p P_ ((Lisp_Object object));
5283 static int pbm_load P_ ((struct frame *f, struct image *img));
5284 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
5286 /* The symbol `pbm' identifying images of this type. */
5288 Lisp_Object Qpbm;
5290 /* Indices of image specification fields in gs_format, below. */
5292 enum pbm_keyword_index
5294 PBM_TYPE,
5295 PBM_FILE,
5296 PBM_DATA,
5297 PBM_ASCENT,
5298 PBM_MARGIN,
5299 PBM_RELIEF,
5300 PBM_ALGORITHM,
5301 PBM_HEURISTIC_MASK,
5302 PBM_MASK,
5303 PBM_FOREGROUND,
5304 PBM_BACKGROUND,
5305 PBM_LAST
5308 /* Vector of image_keyword structures describing the format
5309 of valid user-defined image specifications. */
5311 static struct image_keyword pbm_format[PBM_LAST] =
5313 {":type", IMAGE_SYMBOL_VALUE, 1},
5314 {":file", IMAGE_STRING_VALUE, 0},
5315 {":data", IMAGE_STRING_VALUE, 0},
5316 {":ascent", IMAGE_ASCENT_VALUE, 0},
5317 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5318 {":relief", IMAGE_INTEGER_VALUE, 0},
5319 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5320 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5321 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5322 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5323 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5326 /* Structure describing the image type `pbm'. */
5328 static struct image_type pbm_type =
5330 &Qpbm,
5331 pbm_image_p,
5332 pbm_load,
5333 x_clear_image,
5334 NULL
5338 /* Return non-zero if OBJECT is a valid PBM image specification. */
5340 static int
5341 pbm_image_p (object)
5342 Lisp_Object object;
5344 struct image_keyword fmt[PBM_LAST];
5346 bcopy (pbm_format, fmt, sizeof fmt);
5348 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5349 return 0;
5351 /* Must specify either :data or :file. */
5352 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5356 /* Scan a decimal number from *S and return it. Advance *S while
5357 reading the number. END is the end of the string. Value is -1 at
5358 end of input. */
5360 static int
5361 pbm_scan_number (s, end)
5362 unsigned char **s, *end;
5364 int c = 0, val = -1;
5366 while (*s < end)
5368 /* Skip white-space. */
5369 while (*s < end && (c = *(*s)++, isspace (c)))
5372 if (c == '#')
5374 /* Skip comment to end of line. */
5375 while (*s < end && (c = *(*s)++, c != '\n'))
5378 else if (isdigit (c))
5380 /* Read decimal number. */
5381 val = c - '0';
5382 while (*s < end && (c = *(*s)++, isdigit (c)))
5383 val = 10 * val + c - '0';
5384 break;
5386 else
5387 break;
5390 return val;
5394 #ifdef HAVE_NTGUI
5395 #if 0 /* Unused. ++kfs */
5397 /* Read FILE into memory. Value is a pointer to a buffer allocated
5398 with xmalloc holding FILE's contents. Value is null if an error
5399 occurred. *SIZE is set to the size of the file. */
5401 static char *
5402 pbm_read_file (file, size)
5403 Lisp_Object file;
5404 int *size;
5406 FILE *fp = NULL;
5407 char *buf = NULL;
5408 struct stat st;
5410 if (stat (SDATA (file), &st) == 0
5411 && (fp = fopen (SDATA (file), "rb")) != NULL
5412 && (buf = (char *) xmalloc (st.st_size),
5413 fread (buf, 1, st.st_size, fp) == st.st_size))
5415 *size = st.st_size;
5416 fclose (fp);
5418 else
5420 if (fp)
5421 fclose (fp);
5422 if (buf)
5424 xfree (buf);
5425 buf = NULL;
5429 return buf;
5431 #endif
5432 #endif /* HAVE_NTGUI */
5434 /* Load PBM image IMG for use on frame F. */
5436 static int
5437 pbm_load (f, img)
5438 struct frame *f;
5439 struct image *img;
5441 int raw_p, x, y;
5442 int width, height, max_color_idx = 0;
5443 XImagePtr ximg;
5444 Lisp_Object file, specified_file;
5445 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5446 struct gcpro gcpro1;
5447 unsigned char *contents = NULL;
5448 unsigned char *end, *p;
5449 int size;
5451 specified_file = image_spec_value (img->spec, QCfile, NULL);
5452 file = Qnil;
5453 GCPRO1 (file);
5455 if (STRINGP (specified_file))
5457 file = x_find_image_file (specified_file);
5458 if (!STRINGP (file))
5460 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5461 UNGCPRO;
5462 return 0;
5465 contents = slurp_file (SDATA (file), &size);
5466 if (contents == NULL)
5468 image_error ("Error reading `%s'", file, Qnil);
5469 UNGCPRO;
5470 return 0;
5473 p = contents;
5474 end = contents + size;
5476 else
5478 Lisp_Object data;
5479 data = image_spec_value (img->spec, QCdata, NULL);
5480 p = SDATA (data);
5481 end = p + SBYTES (data);
5484 /* Check magic number. */
5485 if (end - p < 2 || *p++ != 'P')
5487 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5488 error:
5489 xfree (contents);
5490 UNGCPRO;
5491 return 0;
5494 switch (*p++)
5496 case '1':
5497 raw_p = 0, type = PBM_MONO;
5498 break;
5500 case '2':
5501 raw_p = 0, type = PBM_GRAY;
5502 break;
5504 case '3':
5505 raw_p = 0, type = PBM_COLOR;
5506 break;
5508 case '4':
5509 raw_p = 1, type = PBM_MONO;
5510 break;
5512 case '5':
5513 raw_p = 1, type = PBM_GRAY;
5514 break;
5516 case '6':
5517 raw_p = 1, type = PBM_COLOR;
5518 break;
5520 default:
5521 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5522 goto error;
5525 /* Read width, height, maximum color-component. Characters
5526 starting with `#' up to the end of a line are ignored. */
5527 width = pbm_scan_number (&p, end);
5528 height = pbm_scan_number (&p, end);
5530 if (type != PBM_MONO)
5532 max_color_idx = pbm_scan_number (&p, end);
5533 if (raw_p && max_color_idx > 255)
5534 max_color_idx = 255;
5537 if (!check_image_size (f, width, height)
5538 || (type != PBM_MONO && max_color_idx < 0))
5539 goto error;
5541 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5542 &ximg, &img->pixmap))
5543 goto error;
5545 /* Initialize the color hash table. */
5546 init_color_table ();
5548 if (type == PBM_MONO)
5550 int c = 0, g;
5551 struct image_keyword fmt[PBM_LAST];
5552 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5553 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5555 /* Parse the image specification. */
5556 bcopy (pbm_format, fmt, sizeof fmt);
5557 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5559 /* Get foreground and background colors, maybe allocate colors. */
5560 if (fmt[PBM_FOREGROUND].count
5561 && STRINGP (fmt[PBM_FOREGROUND].value))
5562 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5563 if (fmt[PBM_BACKGROUND].count
5564 && STRINGP (fmt[PBM_BACKGROUND].value))
5566 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5567 img->background = bg;
5568 img->background_valid = 1;
5571 for (y = 0; y < height; ++y)
5572 for (x = 0; x < width; ++x)
5574 if (raw_p)
5576 if ((x & 7) == 0)
5577 c = *p++;
5578 g = c & 0x80;
5579 c <<= 1;
5581 else
5582 g = pbm_scan_number (&p, end);
5584 XPutPixel (ximg, x, y, g ? fg : bg);
5587 else
5589 for (y = 0; y < height; ++y)
5590 for (x = 0; x < width; ++x)
5592 int r, g, b;
5594 if (type == PBM_GRAY)
5595 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
5596 else if (raw_p)
5598 r = *p++;
5599 g = *p++;
5600 b = *p++;
5602 else
5604 r = pbm_scan_number (&p, end);
5605 g = pbm_scan_number (&p, end);
5606 b = pbm_scan_number (&p, end);
5609 if (r < 0 || g < 0 || b < 0)
5611 x_destroy_x_image (ximg);
5612 image_error ("Invalid pixel value in image `%s'",
5613 img->spec, Qnil);
5614 goto error;
5617 /* RGB values are now in the range 0..max_color_idx.
5618 Scale this to the range 0..0xffff supported by X. */
5619 r = (double) r * 65535 / max_color_idx;
5620 g = (double) g * 65535 / max_color_idx;
5621 b = (double) b * 65535 / max_color_idx;
5622 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5626 #ifdef COLOR_TABLE_SUPPORT
5627 /* Store in IMG->colors the colors allocated for the image, and
5628 free the color table. */
5629 img->colors = colors_in_color_table (&img->ncolors);
5630 free_color_table ();
5631 #endif /* COLOR_TABLE_SUPPORT */
5633 img->width = width;
5634 img->height = height;
5636 /* Maybe fill in the background field while we have ximg handy. */
5638 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5639 /* Casting avoids a GCC warning. */
5640 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5642 /* Put the image into a pixmap. */
5643 x_put_x_image (f, ximg, img->pixmap, width, height);
5644 x_destroy_x_image (ximg);
5646 /* X and W32 versions did it here, MAC version above. ++kfs
5647 img->width = width;
5648 img->height = height; */
5650 UNGCPRO;
5651 xfree (contents);
5652 return 1;
5656 /***********************************************************************
5658 ***********************************************************************/
5660 #if defined (HAVE_PNG) || defined (MAC_OS)
5662 /* Function prototypes. */
5664 static int png_image_p P_ ((Lisp_Object object));
5665 static int png_load P_ ((struct frame *f, struct image *img));
5667 /* The symbol `png' identifying images of this type. */
5669 Lisp_Object Qpng;
5671 /* Indices of image specification fields in png_format, below. */
5673 enum png_keyword_index
5675 PNG_TYPE,
5676 PNG_DATA,
5677 PNG_FILE,
5678 PNG_ASCENT,
5679 PNG_MARGIN,
5680 PNG_RELIEF,
5681 PNG_ALGORITHM,
5682 PNG_HEURISTIC_MASK,
5683 PNG_MASK,
5684 PNG_BACKGROUND,
5685 PNG_LAST
5688 /* Vector of image_keyword structures describing the format
5689 of valid user-defined image specifications. */
5691 static struct image_keyword png_format[PNG_LAST] =
5693 {":type", IMAGE_SYMBOL_VALUE, 1},
5694 {":data", IMAGE_STRING_VALUE, 0},
5695 {":file", IMAGE_STRING_VALUE, 0},
5696 {":ascent", IMAGE_ASCENT_VALUE, 0},
5697 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5698 {":relief", IMAGE_INTEGER_VALUE, 0},
5699 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5700 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5701 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5702 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5705 /* Structure describing the image type `png'. */
5707 static struct image_type png_type =
5709 &Qpng,
5710 png_image_p,
5711 png_load,
5712 x_clear_image,
5713 NULL
5716 /* Return non-zero if OBJECT is a valid PNG image specification. */
5718 static int
5719 png_image_p (object)
5720 Lisp_Object object;
5722 struct image_keyword fmt[PNG_LAST];
5723 bcopy (png_format, fmt, sizeof fmt);
5725 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5726 return 0;
5728 /* Must specify either the :data or :file keyword. */
5729 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5732 #endif /* HAVE_PNG || MAC_OS */
5735 #ifdef HAVE_PNG
5737 #if defined HAVE_LIBPNG_PNG_H
5738 # include <libpng/png.h>
5739 #else
5740 # include <png.h>
5741 #endif
5743 #ifdef HAVE_NTGUI
5744 /* PNG library details. */
5746 DEF_IMGLIB_FN (png_get_io_ptr);
5747 DEF_IMGLIB_FN (png_check_sig);
5748 DEF_IMGLIB_FN (png_create_read_struct);
5749 DEF_IMGLIB_FN (png_create_info_struct);
5750 DEF_IMGLIB_FN (png_destroy_read_struct);
5751 DEF_IMGLIB_FN (png_set_read_fn);
5752 DEF_IMGLIB_FN (png_set_sig_bytes);
5753 DEF_IMGLIB_FN (png_read_info);
5754 DEF_IMGLIB_FN (png_get_IHDR);
5755 DEF_IMGLIB_FN (png_get_valid);
5756 DEF_IMGLIB_FN (png_set_strip_16);
5757 DEF_IMGLIB_FN (png_set_expand);
5758 DEF_IMGLIB_FN (png_set_gray_to_rgb);
5759 DEF_IMGLIB_FN (png_set_background);
5760 DEF_IMGLIB_FN (png_get_bKGD);
5761 DEF_IMGLIB_FN (png_read_update_info);
5762 DEF_IMGLIB_FN (png_get_channels);
5763 DEF_IMGLIB_FN (png_get_rowbytes);
5764 DEF_IMGLIB_FN (png_read_image);
5765 DEF_IMGLIB_FN (png_read_end);
5766 DEF_IMGLIB_FN (png_error);
5768 static int
5769 init_png_functions (Lisp_Object libraries)
5771 HMODULE library;
5773 /* Try loading libpng under probable names. */
5774 if (!(library = w32_delayed_load (libraries, Qpng)))
5775 return 0;
5777 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5778 LOAD_IMGLIB_FN (library, png_check_sig);
5779 LOAD_IMGLIB_FN (library, png_create_read_struct);
5780 LOAD_IMGLIB_FN (library, png_create_info_struct);
5781 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5782 LOAD_IMGLIB_FN (library, png_set_read_fn);
5783 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5784 LOAD_IMGLIB_FN (library, png_read_info);
5785 LOAD_IMGLIB_FN (library, png_get_IHDR);
5786 LOAD_IMGLIB_FN (library, png_get_valid);
5787 LOAD_IMGLIB_FN (library, png_set_strip_16);
5788 LOAD_IMGLIB_FN (library, png_set_expand);
5789 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5790 LOAD_IMGLIB_FN (library, png_set_background);
5791 LOAD_IMGLIB_FN (library, png_get_bKGD);
5792 LOAD_IMGLIB_FN (library, png_read_update_info);
5793 LOAD_IMGLIB_FN (library, png_get_channels);
5794 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5795 LOAD_IMGLIB_FN (library, png_read_image);
5796 LOAD_IMGLIB_FN (library, png_read_end);
5797 LOAD_IMGLIB_FN (library, png_error);
5798 return 1;
5800 #else
5802 #define fn_png_get_io_ptr png_get_io_ptr
5803 #define fn_png_check_sig png_check_sig
5804 #define fn_png_create_read_struct png_create_read_struct
5805 #define fn_png_create_info_struct png_create_info_struct
5806 #define fn_png_destroy_read_struct png_destroy_read_struct
5807 #define fn_png_set_read_fn png_set_read_fn
5808 #define fn_png_set_sig_bytes png_set_sig_bytes
5809 #define fn_png_read_info png_read_info
5810 #define fn_png_get_IHDR png_get_IHDR
5811 #define fn_png_get_valid png_get_valid
5812 #define fn_png_set_strip_16 png_set_strip_16
5813 #define fn_png_set_expand png_set_expand
5814 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5815 #define fn_png_set_background png_set_background
5816 #define fn_png_get_bKGD png_get_bKGD
5817 #define fn_png_read_update_info png_read_update_info
5818 #define fn_png_get_channels png_get_channels
5819 #define fn_png_get_rowbytes png_get_rowbytes
5820 #define fn_png_read_image png_read_image
5821 #define fn_png_read_end png_read_end
5822 #define fn_png_error png_error
5824 #endif /* HAVE_NTGUI */
5826 /* Error and warning handlers installed when the PNG library
5827 is initialized. */
5829 static void
5830 my_png_error (png_ptr, msg)
5831 png_struct *png_ptr;
5832 char *msg;
5834 xassert (png_ptr != NULL);
5835 image_error ("PNG error: %s", build_string (msg), Qnil);
5836 longjmp (png_ptr->jmpbuf, 1);
5840 static void
5841 my_png_warning (png_ptr, msg)
5842 png_struct *png_ptr;
5843 char *msg;
5845 xassert (png_ptr != NULL);
5846 image_error ("PNG warning: %s", build_string (msg), Qnil);
5849 /* Memory source for PNG decoding. */
5851 struct png_memory_storage
5853 unsigned char *bytes; /* The data */
5854 size_t len; /* How big is it? */
5855 int index; /* Where are we? */
5859 /* Function set as reader function when reading PNG image from memory.
5860 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5861 bytes from the input to DATA. */
5863 static void
5864 png_read_from_memory (png_ptr, data, length)
5865 png_structp png_ptr;
5866 png_bytep data;
5867 png_size_t length;
5869 struct png_memory_storage *tbr
5870 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5872 if (length > tbr->len - tbr->index)
5873 fn_png_error (png_ptr, "Read error");
5875 bcopy (tbr->bytes + tbr->index, data, length);
5876 tbr->index = tbr->index + length;
5880 /* Function set as reader function when reading PNG image from a file.
5881 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5882 bytes from the input to DATA. */
5884 static void
5885 png_read_from_file (png_ptr, data, length)
5886 png_structp png_ptr;
5887 png_bytep data;
5888 png_size_t length;
5890 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5892 if (fread (data, 1, length, fp) < length)
5893 fn_png_error (png_ptr, "Read error");
5897 /* Load PNG image IMG for use on frame F. Value is non-zero if
5898 successful. */
5900 static int
5901 png_load (f, img)
5902 struct frame *f;
5903 struct image *img;
5905 Lisp_Object file, specified_file;
5906 Lisp_Object specified_data;
5907 int x, y, i;
5908 XImagePtr ximg, mask_img = NULL;
5909 struct gcpro gcpro1;
5910 png_struct *png_ptr = NULL;
5911 png_info *info_ptr = NULL, *end_info = NULL;
5912 FILE *volatile fp = NULL;
5913 png_byte sig[8];
5914 png_byte * volatile pixels = NULL;
5915 png_byte ** volatile rows = NULL;
5916 png_uint_32 width, height;
5917 int bit_depth, color_type, interlace_type;
5918 png_byte channels;
5919 png_uint_32 row_bytes;
5920 int transparent_p;
5921 double screen_gamma;
5922 struct png_memory_storage tbr; /* Data to be read */
5924 /* Find out what file to load. */
5925 specified_file = image_spec_value (img->spec, QCfile, NULL);
5926 specified_data = image_spec_value (img->spec, QCdata, NULL);
5927 file = Qnil;
5928 GCPRO1 (file);
5930 if (NILP (specified_data))
5932 file = x_find_image_file (specified_file);
5933 if (!STRINGP (file))
5935 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5936 UNGCPRO;
5937 return 0;
5940 /* Open the image file. */
5941 fp = fopen (SDATA (file), "rb");
5942 if (!fp)
5944 image_error ("Cannot open image file `%s'", file, Qnil);
5945 UNGCPRO;
5946 fclose (fp);
5947 return 0;
5950 /* Check PNG signature. */
5951 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5952 || !fn_png_check_sig (sig, sizeof sig))
5954 image_error ("Not a PNG file: `%s'", file, Qnil);
5955 UNGCPRO;
5956 fclose (fp);
5957 return 0;
5960 else
5962 /* Read from memory. */
5963 tbr.bytes = SDATA (specified_data);
5964 tbr.len = SBYTES (specified_data);
5965 tbr.index = 0;
5967 /* Check PNG signature. */
5968 if (tbr.len < sizeof sig
5969 || !fn_png_check_sig (tbr.bytes, sizeof sig))
5971 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5972 UNGCPRO;
5973 return 0;
5976 /* Need to skip past the signature. */
5977 tbr.bytes += sizeof (sig);
5980 /* Initialize read and info structs for PNG lib. Casting return
5981 value avoids a GCC warning on W32. */
5982 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5983 NULL, my_png_error,
5984 my_png_warning);
5985 if (!png_ptr)
5987 if (fp) fclose (fp);
5988 UNGCPRO;
5989 return 0;
5992 /* Casting return value avoids a GCC warning on W32. */
5993 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
5994 if (!info_ptr)
5996 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5997 if (fp) fclose (fp);
5998 UNGCPRO;
5999 return 0;
6002 /* Casting return value avoids a GCC warning on W32. */
6003 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
6004 if (!end_info)
6006 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
6007 if (fp) fclose (fp);
6008 UNGCPRO;
6009 return 0;
6012 /* Set error jump-back. We come back here when the PNG library
6013 detects an error. */
6014 if (setjmp (png_ptr->jmpbuf))
6016 error:
6017 if (png_ptr)
6018 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6019 xfree (pixels);
6020 xfree (rows);
6021 if (fp) fclose (fp);
6022 UNGCPRO;
6023 return 0;
6026 /* Read image info. */
6027 if (!NILP (specified_data))
6028 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
6029 else
6030 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
6032 fn_png_set_sig_bytes (png_ptr, sizeof sig);
6033 fn_png_read_info (png_ptr, info_ptr);
6034 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6035 &interlace_type, NULL, NULL);
6037 if (!check_image_size (f, width, height))
6038 goto error;
6040 /* If image contains simply transparency data, we prefer to
6041 construct a clipping mask. */
6042 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6043 transparent_p = 1;
6044 else
6045 transparent_p = 0;
6047 /* This function is easier to write if we only have to handle
6048 one data format: RGB or RGBA with 8 bits per channel. Let's
6049 transform other formats into that format. */
6051 /* Strip more than 8 bits per channel. */
6052 if (bit_depth == 16)
6053 fn_png_set_strip_16 (png_ptr);
6055 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6056 if available. */
6057 fn_png_set_expand (png_ptr);
6059 /* Convert grayscale images to RGB. */
6060 if (color_type == PNG_COLOR_TYPE_GRAY
6061 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6062 fn_png_set_gray_to_rgb (png_ptr);
6064 screen_gamma = (f->gamma ? 1 / f->gamma / 0.45455 : 2.2);
6066 #if 0 /* Avoid double gamma correction for PNG images. */
6067 { /* Tell the PNG lib to handle gamma correction for us. */
6068 int intent;
6069 double image_gamma;
6070 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
6071 if (png_get_sRGB (png_ptr, info_ptr, &intent))
6072 /* The libpng documentation says this is right in this case. */
6073 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6074 else
6075 #endif
6076 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
6077 /* Image contains gamma information. */
6078 png_set_gamma (png_ptr, screen_gamma, image_gamma);
6079 else
6080 /* Use the standard default for the image gamma. */
6081 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6083 #endif /* if 0 */
6085 /* Handle alpha channel by combining the image with a background
6086 color. Do this only if a real alpha channel is supplied. For
6087 simple transparency, we prefer a clipping mask. */
6088 if (!transparent_p)
6090 png_color_16 *image_bg;
6091 Lisp_Object specified_bg
6092 = image_spec_value (img->spec, QCbackground, NULL);
6094 if (STRINGP (specified_bg))
6095 /* The user specified `:background', use that. */
6097 /* W32 version incorrectly used COLORREF here!! ++kfs */
6098 XColor color;
6099 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
6101 png_color_16 user_bg;
6103 bzero (&user_bg, sizeof user_bg);
6104 user_bg.red = color.red >> 8;
6105 user_bg.green = color.green >> 8;
6106 user_bg.blue = color.blue >> 8;
6108 fn_png_set_background (png_ptr, &user_bg,
6109 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6112 else if (fn_png_get_bKGD (png_ptr, info_ptr, &image_bg))
6113 /* Image contains a background color with which to
6114 combine the image. */
6115 fn_png_set_background (png_ptr, image_bg,
6116 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
6117 else
6119 /* Image does not contain a background color with which
6120 to combine the image data via an alpha channel. Use
6121 the frame's background instead. */
6122 #ifdef HAVE_X_WINDOWS
6123 XColor color;
6124 png_color_16 frame_background;
6126 color.pixel = FRAME_BACKGROUND_PIXEL (f);
6127 x_query_color (f, &color);
6129 bzero (&frame_background, sizeof frame_background);
6130 frame_background.red = color.red >> 8;
6131 frame_background.green = color.green >> 8;
6132 frame_background.blue = color.blue >> 8;
6133 #endif /* HAVE_X_WINDOWS */
6135 #ifdef HAVE_NTGUI
6136 COLORREF color;
6137 png_color_16 frame_background;
6138 color = FRAME_BACKGROUND_PIXEL (f);
6139 #if 0 /* W32 TODO : Colormap support. */
6140 x_query_color (f, &color);
6141 #endif
6142 bzero (&frame_background, sizeof frame_background);
6143 frame_background.red = GetRValue (color);
6144 frame_background.green = GetGValue (color);
6145 frame_background.blue = GetBValue (color);
6146 #endif /* HAVE_NTGUI */
6148 #ifdef MAC_OS
6149 unsigned long color;
6150 png_color_16 frame_background;
6151 color = FRAME_BACKGROUND_PIXEL (f);
6152 #if 0 /* MAC/W32 TODO : Colormap support. */
6153 x_query_color (f, &color);
6154 #endif
6155 bzero (&frame_background, sizeof frame_background);
6156 frame_background.red = RED_FROM_ULONG (color);
6157 frame_background.green = GREEN_FROM_ULONG (color);
6158 frame_background.blue = BLUE_FROM_ULONG (color);
6159 #endif /* MAC_OS */
6161 fn_png_set_background (png_ptr, &frame_background,
6162 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6166 /* Update info structure. */
6167 fn_png_read_update_info (png_ptr, info_ptr);
6169 /* Get number of channels. Valid values are 1 for grayscale images
6170 and images with a palette, 2 for grayscale images with transparency
6171 information (alpha channel), 3 for RGB images, and 4 for RGB
6172 images with alpha channel, i.e. RGBA. If conversions above were
6173 sufficient we should only have 3 or 4 channels here. */
6174 channels = fn_png_get_channels (png_ptr, info_ptr);
6175 xassert (channels == 3 || channels == 4);
6177 /* Number of bytes needed for one row of the image. */
6178 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
6180 /* Allocate memory for the image. */
6181 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
6182 rows = (png_byte **) xmalloc (height * sizeof *rows);
6183 for (i = 0; i < height; ++i)
6184 rows[i] = pixels + i * row_bytes;
6186 /* Read the entire image. */
6187 fn_png_read_image (png_ptr, rows);
6188 fn_png_read_end (png_ptr, info_ptr);
6189 if (fp)
6191 fclose (fp);
6192 fp = NULL;
6195 /* Create the X image and pixmap. */
6196 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
6197 &img->pixmap))
6198 goto error;
6200 /* Create an image and pixmap serving as mask if the PNG image
6201 contains an alpha channel. */
6202 if (channels == 4
6203 && !transparent_p
6204 && !x_create_x_image_and_pixmap (f, width, height, 1,
6205 &mask_img, &img->mask))
6207 x_destroy_x_image (ximg);
6208 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
6209 img->pixmap = NO_PIXMAP;
6210 goto error;
6213 /* Fill the X image and mask from PNG data. */
6214 init_color_table ();
6216 for (y = 0; y < height; ++y)
6218 png_byte *p = rows[y];
6220 for (x = 0; x < width; ++x)
6222 unsigned r, g, b;
6224 r = *p++ << 8;
6225 g = *p++ << 8;
6226 b = *p++ << 8;
6227 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6228 /* An alpha channel, aka mask channel, associates variable
6229 transparency with an image. Where other image formats
6230 support binary transparency---fully transparent or fully
6231 opaque---PNG allows up to 254 levels of partial transparency.
6232 The PNG library implements partial transparency by combining
6233 the image with a specified background color.
6235 I'm not sure how to handle this here nicely: because the
6236 background on which the image is displayed may change, for
6237 real alpha channel support, it would be necessary to create
6238 a new image for each possible background.
6240 What I'm doing now is that a mask is created if we have
6241 boolean transparency information. Otherwise I'm using
6242 the frame's background color to combine the image with. */
6244 if (channels == 4)
6246 if (mask_img)
6247 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6248 ++p;
6253 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6254 /* Set IMG's background color from the PNG image, unless the user
6255 overrode it. */
6257 png_color_16 *bg;
6258 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6260 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6261 img->background_valid = 1;
6265 #ifdef COLOR_TABLE_SUPPORT
6266 /* Remember colors allocated for this image. */
6267 img->colors = colors_in_color_table (&img->ncolors);
6268 free_color_table ();
6269 #endif /* COLOR_TABLE_SUPPORT */
6271 /* Clean up. */
6272 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6273 xfree (rows);
6274 xfree (pixels);
6276 img->width = width;
6277 img->height = height;
6279 /* Maybe fill in the background field while we have ximg handy.
6280 Casting avoids a GCC warning. */
6281 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6283 /* Put the image into the pixmap, then free the X image and its buffer. */
6284 x_put_x_image (f, ximg, img->pixmap, width, height);
6285 x_destroy_x_image (ximg);
6287 /* Same for the mask. */
6288 if (mask_img)
6290 /* Fill in the background_transparent field while we have the
6291 mask handy. Casting avoids a GCC warning. */
6292 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6294 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
6295 x_destroy_x_image (mask_img);
6298 UNGCPRO;
6299 return 1;
6302 #else /* HAVE_PNG */
6304 #ifdef MAC_OS
6305 static int
6306 png_load (f, img)
6307 struct frame *f;
6308 struct image *img;
6310 #ifdef MAC_OSX
6311 if (MyCGImageCreateWithPNGDataProvider)
6312 return image_load_quartz2d (f, img, 1);
6313 else
6314 #endif
6315 return image_load_quicktime (f, img, kQTFileTypePNG);
6317 #endif /* MAC_OS */
6319 #endif /* !HAVE_PNG */
6323 /***********************************************************************
6324 JPEG
6325 ***********************************************************************/
6327 #if defined (HAVE_JPEG) || defined (MAC_OS)
6329 static int jpeg_image_p P_ ((Lisp_Object object));
6330 static int jpeg_load P_ ((struct frame *f, struct image *img));
6332 /* The symbol `jpeg' identifying images of this type. */
6334 Lisp_Object Qjpeg;
6336 /* Indices of image specification fields in gs_format, below. */
6338 enum jpeg_keyword_index
6340 JPEG_TYPE,
6341 JPEG_DATA,
6342 JPEG_FILE,
6343 JPEG_ASCENT,
6344 JPEG_MARGIN,
6345 JPEG_RELIEF,
6346 JPEG_ALGORITHM,
6347 JPEG_HEURISTIC_MASK,
6348 JPEG_MASK,
6349 JPEG_BACKGROUND,
6350 JPEG_LAST
6353 /* Vector of image_keyword structures describing the format
6354 of valid user-defined image specifications. */
6356 static struct image_keyword jpeg_format[JPEG_LAST] =
6358 {":type", IMAGE_SYMBOL_VALUE, 1},
6359 {":data", IMAGE_STRING_VALUE, 0},
6360 {":file", IMAGE_STRING_VALUE, 0},
6361 {":ascent", IMAGE_ASCENT_VALUE, 0},
6362 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6363 {":relief", IMAGE_INTEGER_VALUE, 0},
6364 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6365 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6366 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6367 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6370 /* Structure describing the image type `jpeg'. */
6372 static struct image_type jpeg_type =
6374 &Qjpeg,
6375 jpeg_image_p,
6376 jpeg_load,
6377 x_clear_image,
6378 NULL
6381 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6383 static int
6384 jpeg_image_p (object)
6385 Lisp_Object object;
6387 struct image_keyword fmt[JPEG_LAST];
6389 bcopy (jpeg_format, fmt, sizeof fmt);
6391 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6392 return 0;
6394 /* Must specify either the :data or :file keyword. */
6395 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6398 #endif /* HAVE_JPEG || MAC_OS */
6400 #ifdef HAVE_JPEG
6402 /* Work around a warning about HAVE_STDLIB_H being redefined in
6403 jconfig.h. */
6404 #ifdef HAVE_STDLIB_H
6405 #define HAVE_STDLIB_H_1
6406 #undef HAVE_STDLIB_H
6407 #endif /* HAVE_STLIB_H */
6409 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6410 /* In older releases of the jpeg library, jpeglib.h will define boolean
6411 differently depending on __WIN32__, so make sure it is defined. */
6412 #define __WIN32__ 1
6413 #endif
6415 #include <jpeglib.h>
6416 #include <jerror.h>
6417 #include <setjmp.h>
6419 #ifdef HAVE_STLIB_H_1
6420 #define HAVE_STDLIB_H 1
6421 #endif
6423 #ifdef HAVE_NTGUI
6425 /* JPEG library details. */
6426 DEF_IMGLIB_FN (jpeg_CreateDecompress);
6427 DEF_IMGLIB_FN (jpeg_start_decompress);
6428 DEF_IMGLIB_FN (jpeg_finish_decompress);
6429 DEF_IMGLIB_FN (jpeg_destroy_decompress);
6430 DEF_IMGLIB_FN (jpeg_read_header);
6431 DEF_IMGLIB_FN (jpeg_read_scanlines);
6432 DEF_IMGLIB_FN (jpeg_std_error);
6433 DEF_IMGLIB_FN (jpeg_resync_to_restart);
6435 static int
6436 init_jpeg_functions (Lisp_Object libraries)
6438 HMODULE library;
6440 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6441 return 0;
6443 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6444 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6445 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6446 LOAD_IMGLIB_FN (library, jpeg_read_header);
6447 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6448 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6449 LOAD_IMGLIB_FN (library, jpeg_std_error);
6450 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6451 return 1;
6454 /* Wrapper since we can't directly assign the function pointer
6455 to another function pointer that was declared more completely easily. */
6456 static boolean
6457 jpeg_resync_to_restart_wrapper(cinfo, desired)
6458 j_decompress_ptr cinfo;
6459 int desired;
6461 return fn_jpeg_resync_to_restart (cinfo, desired);
6464 #else
6466 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6467 #define fn_jpeg_start_decompress jpeg_start_decompress
6468 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6469 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6470 #define fn_jpeg_read_header jpeg_read_header
6471 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6472 #define fn_jpeg_std_error jpeg_std_error
6473 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6475 #endif /* HAVE_NTGUI */
6477 struct my_jpeg_error_mgr
6479 struct jpeg_error_mgr pub;
6480 jmp_buf setjmp_buffer;
6484 static void
6485 my_error_exit (cinfo)
6486 j_common_ptr cinfo;
6488 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6489 longjmp (mgr->setjmp_buffer, 1);
6493 /* Init source method for JPEG data source manager. Called by
6494 jpeg_read_header() before any data is actually read. See
6495 libjpeg.doc from the JPEG lib distribution. */
6497 static void
6498 our_common_init_source (cinfo)
6499 j_decompress_ptr cinfo;
6504 /* Method to terminate data source. Called by
6505 jpeg_finish_decompress() after all data has been processed. */
6507 static void
6508 our_common_term_source (cinfo)
6509 j_decompress_ptr cinfo;
6514 /* Fill input buffer method for JPEG data source manager. Called
6515 whenever more data is needed. We read the whole image in one step,
6516 so this only adds a fake end of input marker at the end. */
6518 static boolean
6519 our_memory_fill_input_buffer (cinfo)
6520 j_decompress_ptr cinfo;
6522 /* Insert a fake EOI marker. */
6523 struct jpeg_source_mgr *src = cinfo->src;
6524 static JOCTET buffer[2];
6526 buffer[0] = (JOCTET) 0xFF;
6527 buffer[1] = (JOCTET) JPEG_EOI;
6529 src->next_input_byte = buffer;
6530 src->bytes_in_buffer = 2;
6531 return 1;
6535 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6536 is the JPEG data source manager. */
6538 static void
6539 our_memory_skip_input_data (cinfo, num_bytes)
6540 j_decompress_ptr cinfo;
6541 long num_bytes;
6543 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6545 if (src)
6547 if (num_bytes > src->bytes_in_buffer)
6548 ERREXIT (cinfo, JERR_INPUT_EOF);
6550 src->bytes_in_buffer -= num_bytes;
6551 src->next_input_byte += num_bytes;
6556 /* Set up the JPEG lib for reading an image from DATA which contains
6557 LEN bytes. CINFO is the decompression info structure created for
6558 reading the image. */
6560 static void
6561 jpeg_memory_src (cinfo, data, len)
6562 j_decompress_ptr cinfo;
6563 JOCTET *data;
6564 unsigned int len;
6566 struct jpeg_source_mgr *src;
6568 if (cinfo->src == NULL)
6570 /* First time for this JPEG object? */
6571 cinfo->src = (struct jpeg_source_mgr *)
6572 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6573 sizeof (struct jpeg_source_mgr));
6574 src = (struct jpeg_source_mgr *) cinfo->src;
6575 src->next_input_byte = data;
6578 src = (struct jpeg_source_mgr *) cinfo->src;
6579 src->init_source = our_common_init_source;
6580 src->fill_input_buffer = our_memory_fill_input_buffer;
6581 src->skip_input_data = our_memory_skip_input_data;
6582 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6583 src->term_source = our_common_term_source;
6584 src->bytes_in_buffer = len;
6585 src->next_input_byte = data;
6589 struct jpeg_stdio_mgr
6591 struct jpeg_source_mgr mgr;
6592 boolean finished;
6593 FILE *file;
6594 JOCTET *buffer;
6598 /* Size of buffer to read JPEG from file.
6599 Not too big, as we want to use alloc_small. */
6600 #define JPEG_STDIO_BUFFER_SIZE 8192
6603 /* Fill input buffer method for JPEG data source manager. Called
6604 whenever more data is needed. The data is read from a FILE *. */
6606 static boolean
6607 our_stdio_fill_input_buffer (cinfo)
6608 j_decompress_ptr cinfo;
6610 struct jpeg_stdio_mgr *src;
6612 src = (struct jpeg_stdio_mgr *) cinfo->src;
6613 if (!src->finished)
6615 size_t bytes;
6617 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6618 if (bytes > 0)
6619 src->mgr.bytes_in_buffer = bytes;
6620 else
6622 WARNMS (cinfo, JWRN_JPEG_EOF);
6623 src->finished = 1;
6624 src->buffer[0] = (JOCTET) 0xFF;
6625 src->buffer[1] = (JOCTET) JPEG_EOI;
6626 src->mgr.bytes_in_buffer = 2;
6628 src->mgr.next_input_byte = src->buffer;
6631 return 1;
6635 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6636 is the JPEG data source manager. */
6638 static void
6639 our_stdio_skip_input_data (cinfo, num_bytes)
6640 j_decompress_ptr cinfo;
6641 long num_bytes;
6643 struct jpeg_stdio_mgr *src;
6644 src = (struct jpeg_stdio_mgr *) cinfo->src;
6646 while (num_bytes > 0 && !src->finished)
6648 if (num_bytes <= src->mgr.bytes_in_buffer)
6650 src->mgr.bytes_in_buffer -= num_bytes;
6651 src->mgr.next_input_byte += num_bytes;
6652 break;
6654 else
6656 num_bytes -= src->mgr.bytes_in_buffer;
6657 src->mgr.bytes_in_buffer = 0;
6658 src->mgr.next_input_byte = NULL;
6660 our_stdio_fill_input_buffer (cinfo);
6666 /* Set up the JPEG lib for reading an image from a FILE *.
6667 CINFO is the decompression info structure created for
6668 reading the image. */
6670 static void
6671 jpeg_file_src (cinfo, fp)
6672 j_decompress_ptr cinfo;
6673 FILE *fp;
6675 struct jpeg_stdio_mgr *src;
6677 if (cinfo->src != NULL)
6678 src = (struct jpeg_stdio_mgr *) cinfo->src;
6679 else
6681 /* First time for this JPEG object? */
6682 cinfo->src = (struct jpeg_source_mgr *)
6683 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6684 sizeof (struct jpeg_stdio_mgr));
6685 src = (struct jpeg_stdio_mgr *) cinfo->src;
6686 src->buffer = (JOCTET *)
6687 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6688 JPEG_STDIO_BUFFER_SIZE);
6691 src->file = fp;
6692 src->finished = 0;
6693 src->mgr.init_source = our_common_init_source;
6694 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6695 src->mgr.skip_input_data = our_stdio_skip_input_data;
6696 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6697 src->mgr.term_source = our_common_term_source;
6698 src->mgr.bytes_in_buffer = 0;
6699 src->mgr.next_input_byte = NULL;
6703 /* Load image IMG for use on frame F. Patterned after example.c
6704 from the JPEG lib. */
6706 static int
6707 jpeg_load (f, img)
6708 struct frame *f;
6709 struct image *img;
6711 struct jpeg_decompress_struct cinfo;
6712 struct my_jpeg_error_mgr mgr;
6713 Lisp_Object file, specified_file;
6714 Lisp_Object specified_data;
6715 FILE * volatile fp = NULL;
6716 JSAMPARRAY buffer;
6717 int row_stride, x, y;
6718 XImagePtr ximg = NULL;
6719 int rc;
6720 unsigned long *colors;
6721 int width, height;
6722 struct gcpro gcpro1;
6724 /* Open the JPEG file. */
6725 specified_file = image_spec_value (img->spec, QCfile, NULL);
6726 specified_data = image_spec_value (img->spec, QCdata, NULL);
6727 file = Qnil;
6728 GCPRO1 (file);
6730 if (NILP (specified_data))
6732 file = x_find_image_file (specified_file);
6733 if (!STRINGP (file))
6735 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6736 UNGCPRO;
6737 return 0;
6740 fp = fopen (SDATA (file), "rb");
6741 if (fp == NULL)
6743 image_error ("Cannot open `%s'", file, Qnil);
6744 UNGCPRO;
6745 return 0;
6749 /* Customize libjpeg's error handling to call my_error_exit when an
6750 error is detected. This function will perform a longjmp.
6751 Casting return value avoids a GCC warning on W32. */
6752 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
6753 mgr.pub.error_exit = my_error_exit;
6755 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6757 if (rc == 1)
6759 /* Called from my_error_exit. Display a JPEG error. */
6760 char buffer[JMSG_LENGTH_MAX];
6761 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
6762 image_error ("Error reading JPEG image `%s': %s", img->spec,
6763 build_string (buffer));
6766 /* Close the input file and destroy the JPEG object. */
6767 if (fp)
6768 fclose ((FILE *) fp);
6769 fn_jpeg_destroy_decompress (&cinfo);
6771 /* If we already have an XImage, free that. */
6772 x_destroy_x_image (ximg);
6774 /* Free pixmap and colors. */
6775 x_clear_image (f, img);
6777 UNGCPRO;
6778 return 0;
6781 /* Create the JPEG decompression object. Let it read from fp.
6782 Read the JPEG image header. */
6783 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6785 if (NILP (specified_data))
6786 jpeg_file_src (&cinfo, (FILE *) fp);
6787 else
6788 jpeg_memory_src (&cinfo, SDATA (specified_data),
6789 SBYTES (specified_data));
6791 fn_jpeg_read_header (&cinfo, 1);
6793 /* Customize decompression so that color quantization will be used.
6794 Start decompression. */
6795 cinfo.quantize_colors = 1;
6796 fn_jpeg_start_decompress (&cinfo);
6797 width = img->width = cinfo.output_width;
6798 height = img->height = cinfo.output_height;
6800 if (!check_image_size (f, width, height))
6802 image_error ("Invalid image size", Qnil, Qnil);
6803 longjmp (mgr.setjmp_buffer, 2);
6806 /* Create X image and pixmap. */
6807 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6808 longjmp (mgr.setjmp_buffer, 2);
6810 /* Allocate colors. When color quantization is used,
6811 cinfo.actual_number_of_colors has been set with the number of
6812 colors generated, and cinfo.colormap is a two-dimensional array
6813 of color indices in the range 0..cinfo.actual_number_of_colors.
6814 No more than 255 colors will be generated. */
6816 int i, ir, ig, ib;
6818 if (cinfo.out_color_components > 2)
6819 ir = 0, ig = 1, ib = 2;
6820 else if (cinfo.out_color_components > 1)
6821 ir = 0, ig = 1, ib = 0;
6822 else
6823 ir = 0, ig = 0, ib = 0;
6825 /* Use the color table mechanism because it handles colors that
6826 cannot be allocated nicely. Such colors will be replaced with
6827 a default color, and we don't have to care about which colors
6828 can be freed safely, and which can't. */
6829 init_color_table ();
6830 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6831 * sizeof *colors);
6833 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6835 /* Multiply RGB values with 255 because X expects RGB values
6836 in the range 0..0xffff. */
6837 int r = cinfo.colormap[ir][i] << 8;
6838 int g = cinfo.colormap[ig][i] << 8;
6839 int b = cinfo.colormap[ib][i] << 8;
6840 colors[i] = lookup_rgb_color (f, r, g, b);
6843 #ifdef COLOR_TABLE_SUPPORT
6844 /* Remember those colors actually allocated. */
6845 img->colors = colors_in_color_table (&img->ncolors);
6846 free_color_table ();
6847 #endif /* COLOR_TABLE_SUPPORT */
6850 /* Read pixels. */
6851 row_stride = width * cinfo.output_components;
6852 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6853 row_stride, 1);
6854 for (y = 0; y < height; ++y)
6856 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6857 for (x = 0; x < cinfo.output_width; ++x)
6858 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6861 /* Clean up. */
6862 fn_jpeg_finish_decompress (&cinfo);
6863 fn_jpeg_destroy_decompress (&cinfo);
6864 if (fp)
6865 fclose ((FILE *) fp);
6867 /* Maybe fill in the background field while we have ximg handy. */
6868 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6869 /* Casting avoids a GCC warning. */
6870 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6872 /* Put the image into the pixmap. */
6873 x_put_x_image (f, ximg, img->pixmap, width, height);
6874 x_destroy_x_image (ximg);
6875 UNGCPRO;
6876 return 1;
6879 #else /* HAVE_JPEG */
6881 #ifdef MAC_OS
6882 static int
6883 jpeg_load (f, img)
6884 struct frame *f;
6885 struct image *img;
6887 #ifdef MAC_OSX
6888 return image_load_quartz2d (f, img, 0);
6889 #else
6890 return image_load_quicktime (f, img, kQTFileTypeJPEG);
6891 #endif
6893 #endif /* MAC_OS */
6895 #endif /* !HAVE_JPEG */
6899 /***********************************************************************
6900 TIFF
6901 ***********************************************************************/
6903 #if defined (HAVE_TIFF) || defined (MAC_OS)
6905 static int tiff_image_p P_ ((Lisp_Object object));
6906 static int tiff_load P_ ((struct frame *f, struct image *img));
6908 /* The symbol `tiff' identifying images of this type. */
6910 Lisp_Object Qtiff;
6912 /* Indices of image specification fields in tiff_format, below. */
6914 enum tiff_keyword_index
6916 TIFF_TYPE,
6917 TIFF_DATA,
6918 TIFF_FILE,
6919 TIFF_ASCENT,
6920 TIFF_MARGIN,
6921 TIFF_RELIEF,
6922 TIFF_ALGORITHM,
6923 TIFF_HEURISTIC_MASK,
6924 TIFF_MASK,
6925 TIFF_BACKGROUND,
6926 TIFF_LAST
6929 /* Vector of image_keyword structures describing the format
6930 of valid user-defined image specifications. */
6932 static struct image_keyword tiff_format[TIFF_LAST] =
6934 {":type", IMAGE_SYMBOL_VALUE, 1},
6935 {":data", IMAGE_STRING_VALUE, 0},
6936 {":file", IMAGE_STRING_VALUE, 0},
6937 {":ascent", IMAGE_ASCENT_VALUE, 0},
6938 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6939 {":relief", IMAGE_INTEGER_VALUE, 0},
6940 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6941 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6942 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6943 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6946 /* Structure describing the image type `tiff'. */
6948 static struct image_type tiff_type =
6950 &Qtiff,
6951 tiff_image_p,
6952 tiff_load,
6953 x_clear_image,
6954 NULL
6957 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6959 static int
6960 tiff_image_p (object)
6961 Lisp_Object object;
6963 struct image_keyword fmt[TIFF_LAST];
6964 bcopy (tiff_format, fmt, sizeof fmt);
6966 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6967 return 0;
6969 /* Must specify either the :data or :file keyword. */
6970 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6973 #endif /* HAVE_TIFF || MAC_OS */
6975 #ifdef HAVE_TIFF
6977 #include <tiffio.h>
6979 #ifdef HAVE_NTGUI
6981 /* TIFF library details. */
6982 DEF_IMGLIB_FN (TIFFSetErrorHandler);
6983 DEF_IMGLIB_FN (TIFFSetWarningHandler);
6984 DEF_IMGLIB_FN (TIFFOpen);
6985 DEF_IMGLIB_FN (TIFFClientOpen);
6986 DEF_IMGLIB_FN (TIFFGetField);
6987 DEF_IMGLIB_FN (TIFFReadRGBAImage);
6988 DEF_IMGLIB_FN (TIFFClose);
6990 static int
6991 init_tiff_functions (Lisp_Object libraries)
6993 HMODULE library;
6995 if (!(library = w32_delayed_load (libraries, Qtiff)))
6996 return 0;
6998 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6999 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
7000 LOAD_IMGLIB_FN (library, TIFFOpen);
7001 LOAD_IMGLIB_FN (library, TIFFClientOpen);
7002 LOAD_IMGLIB_FN (library, TIFFGetField);
7003 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
7004 LOAD_IMGLIB_FN (library, TIFFClose);
7005 return 1;
7008 #else
7010 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
7011 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
7012 #define fn_TIFFOpen TIFFOpen
7013 #define fn_TIFFClientOpen TIFFClientOpen
7014 #define fn_TIFFGetField TIFFGetField
7015 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
7016 #define fn_TIFFClose TIFFClose
7018 #endif /* HAVE_NTGUI */
7021 /* Reading from a memory buffer for TIFF images Based on the PNG
7022 memory source, but we have to provide a lot of extra functions.
7023 Blah.
7025 We really only need to implement read and seek, but I am not
7026 convinced that the TIFF library is smart enough not to destroy
7027 itself if we only hand it the function pointers we need to
7028 override. */
7030 typedef struct
7032 unsigned char *bytes;
7033 size_t len;
7034 int index;
7036 tiff_memory_source;
7038 static size_t
7039 tiff_read_from_memory (data, buf, size)
7040 thandle_t data;
7041 tdata_t buf;
7042 tsize_t size;
7044 tiff_memory_source *src = (tiff_memory_source *) data;
7046 if (size > src->len - src->index)
7047 return (size_t) -1;
7048 bcopy (src->bytes + src->index, buf, size);
7049 src->index += size;
7050 return size;
7053 static size_t
7054 tiff_write_from_memory (data, buf, size)
7055 thandle_t data;
7056 tdata_t buf;
7057 tsize_t size;
7059 return (size_t) -1;
7062 static toff_t
7063 tiff_seek_in_memory (data, off, whence)
7064 thandle_t data;
7065 toff_t off;
7066 int whence;
7068 tiff_memory_source *src = (tiff_memory_source *) data;
7069 int idx;
7071 switch (whence)
7073 case SEEK_SET: /* Go from beginning of source. */
7074 idx = off;
7075 break;
7077 case SEEK_END: /* Go from end of source. */
7078 idx = src->len + off;
7079 break;
7081 case SEEK_CUR: /* Go from current position. */
7082 idx = src->index + off;
7083 break;
7085 default: /* Invalid `whence'. */
7086 return -1;
7089 if (idx > src->len || idx < 0)
7090 return -1;
7092 src->index = idx;
7093 return src->index;
7096 static int
7097 tiff_close_memory (data)
7098 thandle_t data;
7100 /* NOOP */
7101 return 0;
7104 static int
7105 tiff_mmap_memory (data, pbase, psize)
7106 thandle_t data;
7107 tdata_t *pbase;
7108 toff_t *psize;
7110 /* It is already _IN_ memory. */
7111 return 0;
7114 static void
7115 tiff_unmap_memory (data, base, size)
7116 thandle_t data;
7117 tdata_t base;
7118 toff_t size;
7120 /* We don't need to do this. */
7123 static toff_t
7124 tiff_size_of_memory (data)
7125 thandle_t data;
7127 return ((tiff_memory_source *) data)->len;
7131 static void
7132 tiff_error_handler (title, format, ap)
7133 const char *title, *format;
7134 va_list ap;
7136 char buf[512];
7137 int len;
7139 len = sprintf (buf, "TIFF error: %s ", title);
7140 vsprintf (buf + len, format, ap);
7141 add_to_log (buf, Qnil, Qnil);
7145 static void
7146 tiff_warning_handler (title, format, ap)
7147 const char *title, *format;
7148 va_list ap;
7150 char buf[512];
7151 int len;
7153 len = sprintf (buf, "TIFF warning: %s ", title);
7154 vsprintf (buf + len, format, ap);
7155 add_to_log (buf, Qnil, Qnil);
7159 /* Load TIFF image IMG for use on frame F. Value is non-zero if
7160 successful. */
7162 static int
7163 tiff_load (f, img)
7164 struct frame *f;
7165 struct image *img;
7167 Lisp_Object file, specified_file;
7168 Lisp_Object specified_data;
7169 TIFF *tiff;
7170 int width, height, x, y;
7171 uint32 *buf;
7172 int rc;
7173 XImagePtr ximg;
7174 struct gcpro gcpro1;
7175 tiff_memory_source memsrc;
7177 specified_file = image_spec_value (img->spec, QCfile, NULL);
7178 specified_data = image_spec_value (img->spec, QCdata, NULL);
7179 file = Qnil;
7180 GCPRO1 (file);
7182 fn_TIFFSetErrorHandler (tiff_error_handler);
7183 fn_TIFFSetWarningHandler (tiff_warning_handler);
7185 if (NILP (specified_data))
7187 /* Read from a file */
7188 file = x_find_image_file (specified_file);
7189 if (!STRINGP (file))
7191 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7192 UNGCPRO;
7193 return 0;
7196 /* Try to open the image file. Casting return value avoids a
7197 GCC warning on W32. */
7198 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
7199 if (tiff == NULL)
7201 image_error ("Cannot open `%s'", file, Qnil);
7202 UNGCPRO;
7203 return 0;
7206 else
7208 /* Memory source! */
7209 memsrc.bytes = SDATA (specified_data);
7210 memsrc.len = SBYTES (specified_data);
7211 memsrc.index = 0;
7213 /* Casting return value avoids a GCC warning on W32. */
7214 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r", &memsrc,
7215 (TIFFReadWriteProc) tiff_read_from_memory,
7216 (TIFFReadWriteProc) tiff_write_from_memory,
7217 tiff_seek_in_memory,
7218 tiff_close_memory,
7219 tiff_size_of_memory,
7220 tiff_mmap_memory,
7221 tiff_unmap_memory);
7223 if (!tiff)
7225 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7226 UNGCPRO;
7227 return 0;
7231 /* Get width and height of the image, and allocate a raster buffer
7232 of width x height 32-bit values. */
7233 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7234 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7236 if (!check_image_size (f, width, height))
7238 image_error ("Invalid image size", Qnil, Qnil);
7239 UNGCPRO;
7240 return 0;
7243 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
7245 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7246 fn_TIFFClose (tiff);
7247 if (!rc)
7249 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7250 xfree (buf);
7251 UNGCPRO;
7252 return 0;
7255 /* Create the X image and pixmap. */
7256 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7258 xfree (buf);
7259 UNGCPRO;
7260 return 0;
7263 /* Initialize the color table. */
7264 init_color_table ();
7266 /* Process the pixel raster. Origin is in the lower-left corner. */
7267 for (y = 0; y < height; ++y)
7269 uint32 *row = buf + y * width;
7271 for (x = 0; x < width; ++x)
7273 uint32 abgr = row[x];
7274 int r = TIFFGetR (abgr) << 8;
7275 int g = TIFFGetG (abgr) << 8;
7276 int b = TIFFGetB (abgr) << 8;
7277 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7281 #ifdef COLOR_TABLE_SUPPORT
7282 /* Remember the colors allocated for the image. Free the color table. */
7283 img->colors = colors_in_color_table (&img->ncolors);
7284 free_color_table ();
7285 #endif /* COLOR_TABLE_SUPPORT */
7287 img->width = width;
7288 img->height = height;
7290 /* Maybe fill in the background field while we have ximg handy. */
7291 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7292 /* Casting avoids a GCC warning on W32. */
7293 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7295 /* Put the image into the pixmap, then free the X image and its buffer. */
7296 x_put_x_image (f, ximg, img->pixmap, width, height);
7297 x_destroy_x_image (ximg);
7298 xfree (buf);
7300 UNGCPRO;
7301 return 1;
7304 #else /* HAVE_TIFF */
7306 #ifdef MAC_OS
7307 static int
7308 tiff_load (f, img)
7309 struct frame *f;
7310 struct image *img;
7312 return image_load_quicktime (f, img, kQTFileTypeTIFF);
7314 #endif /* MAC_OS */
7316 #endif /* !HAVE_TIFF */
7320 /***********************************************************************
7322 ***********************************************************************/
7324 #if defined (HAVE_GIF) || defined (MAC_OS)
7326 static int gif_image_p P_ ((Lisp_Object object));
7327 static int gif_load P_ ((struct frame *f, struct image *img));
7329 /* The symbol `gif' identifying images of this type. */
7331 Lisp_Object Qgif;
7333 /* Indices of image specification fields in gif_format, below. */
7335 enum gif_keyword_index
7337 GIF_TYPE,
7338 GIF_DATA,
7339 GIF_FILE,
7340 GIF_ASCENT,
7341 GIF_MARGIN,
7342 GIF_RELIEF,
7343 GIF_ALGORITHM,
7344 GIF_HEURISTIC_MASK,
7345 GIF_MASK,
7346 GIF_IMAGE,
7347 GIF_BACKGROUND,
7348 GIF_LAST
7351 /* Vector of image_keyword structures describing the format
7352 of valid user-defined image specifications. */
7354 static struct image_keyword gif_format[GIF_LAST] =
7356 {":type", IMAGE_SYMBOL_VALUE, 1},
7357 {":data", IMAGE_STRING_VALUE, 0},
7358 {":file", IMAGE_STRING_VALUE, 0},
7359 {":ascent", IMAGE_ASCENT_VALUE, 0},
7360 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7361 {":relief", IMAGE_INTEGER_VALUE, 0},
7362 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7363 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7364 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7365 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7366 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7369 /* Structure describing the image type `gif'. */
7371 static struct image_type gif_type =
7373 &Qgif,
7374 gif_image_p,
7375 gif_load,
7376 x_clear_image,
7377 NULL
7380 /* Return non-zero if OBJECT is a valid GIF image specification. */
7382 static int
7383 gif_image_p (object)
7384 Lisp_Object object;
7386 struct image_keyword fmt[GIF_LAST];
7387 bcopy (gif_format, fmt, sizeof fmt);
7389 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7390 return 0;
7392 /* Must specify either the :data or :file keyword. */
7393 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7396 #endif /* HAVE_GIF || MAC_OS */
7398 #ifdef HAVE_GIF
7400 #if defined (HAVE_NTGUI) || defined (MAC_OS)
7401 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7402 Undefine before redefining to avoid a preprocessor warning. */
7403 #ifdef DrawText
7404 #undef DrawText
7405 #endif
7406 /* avoid conflict with QuickdrawText.h */
7407 #define DrawText gif_DrawText
7408 #include <gif_lib.h>
7409 #undef DrawText
7411 #else /* HAVE_NTGUI || MAC_OS */
7413 #include <gif_lib.h>
7415 #endif /* HAVE_NTGUI || MAC_OS */
7418 #ifdef HAVE_NTGUI
7420 /* GIF library details. */
7421 DEF_IMGLIB_FN (DGifCloseFile);
7422 DEF_IMGLIB_FN (DGifSlurp);
7423 DEF_IMGLIB_FN (DGifOpen);
7424 DEF_IMGLIB_FN (DGifOpenFileName);
7426 static int
7427 init_gif_functions (Lisp_Object libraries)
7429 HMODULE library;
7431 if (!(library = w32_delayed_load (libraries, Qgif)))
7432 return 0;
7434 LOAD_IMGLIB_FN (library, DGifCloseFile);
7435 LOAD_IMGLIB_FN (library, DGifSlurp);
7436 LOAD_IMGLIB_FN (library, DGifOpen);
7437 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7438 return 1;
7441 #else
7443 #define fn_DGifCloseFile DGifCloseFile
7444 #define fn_DGifSlurp DGifSlurp
7445 #define fn_DGifOpen DGifOpen
7446 #define fn_DGifOpenFileName DGifOpenFileName
7448 #endif /* HAVE_NTGUI */
7450 /* Reading a GIF image from memory
7451 Based on the PNG memory stuff to a certain extent. */
7453 typedef struct
7455 unsigned char *bytes;
7456 size_t len;
7457 int index;
7459 gif_memory_source;
7461 /* Make the current memory source available to gif_read_from_memory.
7462 It's done this way because not all versions of libungif support
7463 a UserData field in the GifFileType structure. */
7464 static gif_memory_source *current_gif_memory_src;
7466 static int
7467 gif_read_from_memory (file, buf, len)
7468 GifFileType *file;
7469 GifByteType *buf;
7470 int len;
7472 gif_memory_source *src = current_gif_memory_src;
7474 if (len > src->len - src->index)
7475 return -1;
7477 bcopy (src->bytes + src->index, buf, len);
7478 src->index += len;
7479 return len;
7483 /* Load GIF image IMG for use on frame F. Value is non-zero if
7484 successful. */
7486 static int
7487 gif_load (f, img)
7488 struct frame *f;
7489 struct image *img;
7491 Lisp_Object file, specified_file;
7492 Lisp_Object specified_data;
7493 int rc, width, height, x, y, i;
7494 XImagePtr ximg;
7495 ColorMapObject *gif_color_map;
7496 unsigned long pixel_colors[256];
7497 GifFileType *gif;
7498 struct gcpro gcpro1;
7499 Lisp_Object image;
7500 int ino, image_left, image_top, image_width, image_height;
7501 gif_memory_source memsrc;
7502 unsigned char *raster;
7504 specified_file = image_spec_value (img->spec, QCfile, NULL);
7505 specified_data = image_spec_value (img->spec, QCdata, NULL);
7506 file = Qnil;
7507 GCPRO1 (file);
7509 if (NILP (specified_data))
7511 file = x_find_image_file (specified_file);
7512 if (!STRINGP (file))
7514 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7515 UNGCPRO;
7516 return 0;
7519 /* Open the GIF file. Casting return value avoids a GCC warning
7520 on W32. */
7521 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
7522 if (gif == NULL)
7524 image_error ("Cannot open `%s'", file, Qnil);
7525 UNGCPRO;
7526 return 0;
7529 else
7531 /* Read from memory! */
7532 current_gif_memory_src = &memsrc;
7533 memsrc.bytes = SDATA (specified_data);
7534 memsrc.len = SBYTES (specified_data);
7535 memsrc.index = 0;
7537 /* Casting return value avoids a GCC warning on W32. */
7538 gif = (GifFileType *)fn_DGifOpen(&memsrc, gif_read_from_memory);
7539 if (!gif)
7541 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7542 UNGCPRO;
7543 return 0;
7547 /* Before reading entire contents, check the declared image size. */
7548 if (!check_image_size (f, gif->SWidth, gif->SHeight))
7550 image_error ("Invalid image size", Qnil, Qnil);
7551 fn_DGifCloseFile (gif);
7552 UNGCPRO;
7553 return 0;
7556 /* Read entire contents. */
7557 rc = fn_DGifSlurp (gif);
7558 if (rc == GIF_ERROR)
7560 image_error ("Error reading `%s'", img->spec, Qnil);
7561 fn_DGifCloseFile (gif);
7562 UNGCPRO;
7563 return 0;
7566 image = image_spec_value (img->spec, QCindex, NULL);
7567 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7568 if (ino >= gif->ImageCount)
7570 image_error ("Invalid image number `%s' in image `%s'",
7571 image, img->spec);
7572 fn_DGifCloseFile (gif);
7573 UNGCPRO;
7574 return 0;
7577 image_top = gif->SavedImages[ino].ImageDesc.Top;
7578 image_left = gif->SavedImages[ino].ImageDesc.Left;
7579 image_width = gif->SavedImages[ino].ImageDesc.Width;
7580 image_height = gif->SavedImages[ino].ImageDesc.Height;
7582 width = img->width = max (gif->SWidth,
7583 max (gif->Image.Left + gif->Image.Width,
7584 image_left + image_width));
7585 height = img->height = max (gif->SHeight,
7586 max (gif->Image.Top + gif->Image.Height,
7587 image_top + image_height));
7589 if (!check_image_size (f, width, height))
7591 image_error ("Invalid image size", Qnil, Qnil);
7592 fn_DGifCloseFile (gif);
7593 UNGCPRO;
7594 return 0;
7597 /* Create the X image and pixmap. */
7598 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7600 fn_DGifCloseFile (gif);
7601 UNGCPRO;
7602 return 0;
7605 /* Allocate colors. */
7606 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7607 if (!gif_color_map)
7608 gif_color_map = gif->SColorMap;
7609 init_color_table ();
7610 bzero (pixel_colors, sizeof pixel_colors);
7612 for (i = 0; i < gif_color_map->ColorCount; ++i)
7614 int r = gif_color_map->Colors[i].Red << 8;
7615 int g = gif_color_map->Colors[i].Green << 8;
7616 int b = gif_color_map->Colors[i].Blue << 8;
7617 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7620 #ifdef COLOR_TABLE_SUPPORT
7621 img->colors = colors_in_color_table (&img->ncolors);
7622 free_color_table ();
7623 #endif /* COLOR_TABLE_SUPPORT */
7625 /* Clear the part of the screen image that are not covered by
7626 the image from the GIF file. Full animated GIF support
7627 requires more than can be done here (see the gif89 spec,
7628 disposal methods). Let's simply assume that the part
7629 not covered by a sub-image is in the frame's background color. */
7630 for (y = 0; y < image_top; ++y)
7631 for (x = 0; x < width; ++x)
7632 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7634 for (y = image_top + image_height; y < height; ++y)
7635 for (x = 0; x < width; ++x)
7636 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7638 for (y = image_top; y < image_top + image_height; ++y)
7640 for (x = 0; x < image_left; ++x)
7641 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7642 for (x = image_left + image_width; x < width; ++x)
7643 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7646 /* Read the GIF image into the X image. We use a local variable
7647 `raster' here because RasterBits below is a char *, and invites
7648 problems with bytes >= 0x80. */
7649 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7651 if (gif->SavedImages[ino].ImageDesc.Interlace)
7653 static int interlace_start[] = {0, 4, 2, 1};
7654 static int interlace_increment[] = {8, 8, 4, 2};
7655 int pass;
7656 int row = interlace_start[0];
7658 pass = 0;
7660 for (y = 0; y < image_height; y++)
7662 if (row >= image_height)
7664 row = interlace_start[++pass];
7665 while (row >= image_height)
7666 row = interlace_start[++pass];
7669 for (x = 0; x < image_width; x++)
7671 int i = raster[(y * image_width) + x];
7672 XPutPixel (ximg, x + image_left, row + image_top,
7673 pixel_colors[i]);
7676 row += interlace_increment[pass];
7679 else
7681 for (y = 0; y < image_height; ++y)
7682 for (x = 0; x < image_width; ++x)
7684 int i = raster[y * image_width + x];
7685 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
7689 fn_DGifCloseFile (gif);
7691 /* Maybe fill in the background field while we have ximg handy. */
7692 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7693 /* Casting avoids a GCC warning. */
7694 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7696 /* Put the image into the pixmap, then free the X image and its buffer. */
7697 x_put_x_image (f, ximg, img->pixmap, width, height);
7698 x_destroy_x_image (ximg);
7700 UNGCPRO;
7701 return 1;
7704 #else /* !HAVE_GIF */
7706 #ifdef MAC_OS
7707 static int
7708 gif_load (f, img)
7709 struct frame *f;
7710 struct image *img;
7712 Lisp_Object specified_file, file;
7713 Lisp_Object specified_data;
7714 OSErr err;
7715 Boolean graphic_p, movie_p, prefer_graphic_p;
7716 Handle dh = NULL;
7717 Movie movie = NULL;
7718 Lisp_Object image;
7719 Track track = NULL;
7720 Media media = NULL;
7721 long nsamples;
7722 Rect rect;
7723 Lisp_Object specified_bg;
7724 XColor color;
7725 RGBColor bg_color;
7726 int width, height;
7727 XImagePtr ximg;
7728 TimeValue time;
7729 struct gcpro gcpro1;
7730 int ino;
7731 CGrafPtr old_port;
7732 GDHandle old_gdh;
7734 specified_file = image_spec_value (img->spec, QCfile, NULL);
7735 specified_data = image_spec_value (img->spec, QCdata, NULL);
7737 if (NILP (specified_data))
7739 /* Read from a file */
7740 FSSpec fss;
7741 short refnum;
7743 err = find_image_fsspec (specified_file, &file, &fss);
7744 if (err != noErr)
7746 if (err == fnfErr)
7747 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7748 else
7749 goto open_error;
7752 err = CanQuickTimeOpenFile (&fss, kQTFileTypeGIF, 0,
7753 &graphic_p, &movie_p, &prefer_graphic_p, 0);
7754 if (err != noErr)
7755 goto open_error;
7757 if (!graphic_p && !movie_p)
7758 goto open_error;
7759 if (prefer_graphic_p)
7760 return image_load_qt_1 (f, img, kQTFileTypeGIF, &fss, NULL);
7761 err = OpenMovieFile (&fss, &refnum, fsRdPerm);
7762 if (err != noErr)
7763 goto open_error;
7764 err = NewMovieFromFile (&movie, refnum, NULL, NULL, 0, NULL);
7765 CloseMovieFile (refnum);
7766 if (err != noErr)
7768 image_error ("Error reading `%s'", file, Qnil);
7769 return 0;
7772 else
7774 /* Memory source! */
7775 Handle dref = NULL;
7776 long file_type_atom[3];
7778 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
7779 if (err != noErr)
7781 image_error ("Cannot allocate data handle for `%s'",
7782 img->spec, Qnil);
7783 goto error;
7786 file_type_atom[0] = EndianU32_NtoB (sizeof (long) * 3);
7787 file_type_atom[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
7788 file_type_atom[2] = EndianU32_NtoB (kQTFileTypeGIF);
7789 err = PtrToHand (&dh, &dref, sizeof (Handle));
7790 if (err == noErr)
7791 /* no file name */
7792 err = PtrAndHand ("\p", dref, 1);
7793 if (err == noErr)
7794 err = PtrAndHand (file_type_atom, dref, sizeof (long) * 3);
7795 if (err != noErr)
7797 image_error ("Cannot allocate handle data ref for `%s'", img->spec, Qnil);
7798 goto error;
7800 err = CanQuickTimeOpenDataRef (dref, HandleDataHandlerSubType, &graphic_p,
7801 &movie_p, &prefer_graphic_p, 0);
7802 if (err != noErr)
7803 goto open_error;
7805 if (!graphic_p && !movie_p)
7806 goto open_error;
7807 if (prefer_graphic_p)
7809 int success_p;
7811 DisposeHandle (dref);
7812 success_p = image_load_qt_1 (f, img, kQTFileTypeGIF, NULL, dh);
7813 DisposeHandle (dh);
7814 return success_p;
7816 err = NewMovieFromDataRef (&movie, 0, NULL, dref,
7817 HandleDataHandlerSubType);
7818 DisposeHandle (dref);
7819 if (err != noErr)
7820 goto open_error;
7823 image = image_spec_value (img->spec, QCindex, NULL);
7824 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7825 track = GetMovieIndTrack (movie, 1);
7826 media = GetTrackMedia (track);
7827 nsamples = GetMediaSampleCount (media);
7828 if (ino >= nsamples)
7830 image_error ("Invalid image number `%s' in image `%s'",
7831 image, img->spec);
7832 goto error;
7835 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7836 if (!STRINGP (specified_bg) ||
7837 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
7839 color.pixel = FRAME_BACKGROUND_PIXEL (f);
7840 color.red = RED16_FROM_ULONG (color.pixel);
7841 color.green = GREEN16_FROM_ULONG (color.pixel);
7842 color.blue = BLUE16_FROM_ULONG (color.pixel);
7844 GetMovieBox (movie, &rect);
7845 width = img->width = rect.right - rect.left;
7846 height = img->height = rect.bottom - rect.top;
7847 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7848 goto error;
7850 GetGWorld (&old_port, &old_gdh);
7851 SetGWorld (ximg, NULL);
7852 bg_color.red = color.red;
7853 bg_color.green = color.green;
7854 bg_color.blue = color.blue;
7855 RGBBackColor (&bg_color);
7856 SetGWorld (old_port, old_gdh);
7857 SetMovieActive (movie, 1);
7858 SetMovieGWorld (movie, ximg, NULL);
7859 SampleNumToMediaTime (media, ino + 1, &time, NULL);
7860 SetMovieTimeValue (movie, time);
7861 MoviesTask (movie, 0L);
7862 DisposeTrackMedia (media);
7863 DisposeMovieTrack (track);
7864 DisposeMovie (movie);
7865 if (dh)
7866 DisposeHandle (dh);
7867 /* Maybe fill in the background field while we have ximg handy. */
7868 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7869 IMAGE_BACKGROUND (img, f, ximg);
7871 /* Put the image into the pixmap. */
7872 x_put_x_image (f, ximg, img->pixmap, width, height);
7873 x_destroy_x_image (ximg);
7874 return 1;
7876 open_error:
7877 image_error ("Cannot open `%s'", file, Qnil);
7878 error:
7879 if (media)
7880 DisposeTrackMedia (media);
7881 if (track)
7882 DisposeMovieTrack (track);
7883 if (movie)
7884 DisposeMovie (movie);
7885 if (dh)
7886 DisposeHandle (dh);
7887 return 0;
7889 #endif /* MAC_OS */
7891 #endif /* HAVE_GIF */
7895 /***********************************************************************
7896 Ghostscript
7897 ***********************************************************************/
7899 #ifdef HAVE_X_WINDOWS
7900 #define HAVE_GHOSTSCRIPT 1
7901 #endif /* HAVE_X_WINDOWS */
7903 /* The symbol `postscript' identifying images of this type. */
7905 Lisp_Object Qpostscript;
7907 #ifdef HAVE_GHOSTSCRIPT
7909 static int gs_image_p P_ ((Lisp_Object object));
7910 static int gs_load P_ ((struct frame *f, struct image *img));
7911 static void gs_clear_image P_ ((struct frame *f, struct image *img));
7913 /* Keyword symbols. */
7915 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
7917 /* Indices of image specification fields in gs_format, below. */
7919 enum gs_keyword_index
7921 GS_TYPE,
7922 GS_PT_WIDTH,
7923 GS_PT_HEIGHT,
7924 GS_FILE,
7925 GS_LOADER,
7926 GS_BOUNDING_BOX,
7927 GS_ASCENT,
7928 GS_MARGIN,
7929 GS_RELIEF,
7930 GS_ALGORITHM,
7931 GS_HEURISTIC_MASK,
7932 GS_MASK,
7933 GS_BACKGROUND,
7934 GS_LAST
7937 /* Vector of image_keyword structures describing the format
7938 of valid user-defined image specifications. */
7940 static struct image_keyword gs_format[GS_LAST] =
7942 {":type", IMAGE_SYMBOL_VALUE, 1},
7943 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7944 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7945 {":file", IMAGE_STRING_VALUE, 1},
7946 {":loader", IMAGE_FUNCTION_VALUE, 0},
7947 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
7948 {":ascent", IMAGE_ASCENT_VALUE, 0},
7949 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7950 {":relief", IMAGE_INTEGER_VALUE, 0},
7951 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7952 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7953 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7954 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7957 /* Structure describing the image type `ghostscript'. */
7959 static struct image_type gs_type =
7961 &Qpostscript,
7962 gs_image_p,
7963 gs_load,
7964 gs_clear_image,
7965 NULL
7969 /* Free X resources of Ghostscript image IMG which is used on frame F. */
7971 static void
7972 gs_clear_image (f, img)
7973 struct frame *f;
7974 struct image *img;
7976 /* IMG->data.ptr_val may contain a recorded colormap. */
7977 xfree (img->data.ptr_val);
7978 x_clear_image (f, img);
7982 /* Return non-zero if OBJECT is a valid Ghostscript image
7983 specification. */
7985 static int
7986 gs_image_p (object)
7987 Lisp_Object object;
7989 struct image_keyword fmt[GS_LAST];
7990 Lisp_Object tem;
7991 int i;
7993 bcopy (gs_format, fmt, sizeof fmt);
7995 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
7996 return 0;
7998 /* Bounding box must be a list or vector containing 4 integers. */
7999 tem = fmt[GS_BOUNDING_BOX].value;
8000 if (CONSP (tem))
8002 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8003 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8004 return 0;
8005 if (!NILP (tem))
8006 return 0;
8008 else if (VECTORP (tem))
8010 if (XVECTOR (tem)->size != 4)
8011 return 0;
8012 for (i = 0; i < 4; ++i)
8013 if (!INTEGERP (XVECTOR (tem)->contents[i]))
8014 return 0;
8016 else
8017 return 0;
8019 return 1;
8023 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8024 if successful. */
8026 static int
8027 gs_load (f, img)
8028 struct frame *f;
8029 struct image *img;
8031 char buffer[100];
8032 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8033 struct gcpro gcpro1, gcpro2;
8034 Lisp_Object frame;
8035 double in_width, in_height;
8036 Lisp_Object pixel_colors = Qnil;
8038 /* Compute pixel size of pixmap needed from the given size in the
8039 image specification. Sizes in the specification are in pt. 1 pt
8040 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8041 info. */
8042 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8043 in_width = XFASTINT (pt_width) / 72.0;
8044 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
8045 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8046 in_height = XFASTINT (pt_height) / 72.0;
8047 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
8049 if (!check_image_size (f, img->width, img->height))
8051 image_error ("Invalid image size", Qnil, Qnil);
8052 return 0;
8055 /* Create the pixmap. */
8056 xassert (img->pixmap == NO_PIXMAP);
8058 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8059 BLOCK_INPUT;
8060 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8061 img->width, img->height,
8062 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8063 UNBLOCK_INPUT;
8065 if (!img->pixmap)
8067 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8068 return 0;
8071 /* Call the loader to fill the pixmap. It returns a process object
8072 if successful. We do not record_unwind_protect here because
8073 other places in redisplay like calling window scroll functions
8074 don't either. Let the Lisp loader use `unwind-protect' instead. */
8075 GCPRO2 (window_and_pixmap_id, pixel_colors);
8077 sprintf (buffer, "%lu %lu",
8078 (unsigned long) FRAME_X_WINDOW (f),
8079 (unsigned long) img->pixmap);
8080 window_and_pixmap_id = build_string (buffer);
8082 sprintf (buffer, "%lu %lu",
8083 FRAME_FOREGROUND_PIXEL (f),
8084 FRAME_BACKGROUND_PIXEL (f));
8085 pixel_colors = build_string (buffer);
8087 XSETFRAME (frame, f);
8088 loader = image_spec_value (img->spec, QCloader, NULL);
8089 if (NILP (loader))
8090 loader = intern ("gs-load-image");
8092 img->data.lisp_val = call6 (loader, frame, img->spec,
8093 make_number (img->width),
8094 make_number (img->height),
8095 window_and_pixmap_id,
8096 pixel_colors);
8097 UNGCPRO;
8098 return PROCESSP (img->data.lisp_val);
8102 /* Kill the Ghostscript process that was started to fill PIXMAP on
8103 frame F. Called from XTread_socket when receiving an event
8104 telling Emacs that Ghostscript has finished drawing. */
8106 void
8107 x_kill_gs_process (pixmap, f)
8108 Pixmap pixmap;
8109 struct frame *f;
8111 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8112 int class, i;
8113 struct image *img;
8115 /* Find the image containing PIXMAP. */
8116 for (i = 0; i < c->used; ++i)
8117 if (c->images[i]->pixmap == pixmap)
8118 break;
8120 /* Should someone in between have cleared the image cache, for
8121 instance, give up. */
8122 if (i == c->used)
8123 return;
8125 /* Kill the GS process. We should have found PIXMAP in the image
8126 cache and its image should contain a process object. */
8127 img = c->images[i];
8128 xassert (PROCESSP (img->data.lisp_val));
8129 Fkill_process (img->data.lisp_val, Qnil);
8130 img->data.lisp_val = Qnil;
8132 #if defined (HAVE_X_WINDOWS)
8134 /* On displays with a mutable colormap, figure out the colors
8135 allocated for the image by looking at the pixels of an XImage for
8136 img->pixmap. */
8137 class = FRAME_X_VISUAL (f)->class;
8138 if (class != StaticColor && class != StaticGray && class != TrueColor)
8140 XImagePtr ximg;
8142 BLOCK_INPUT;
8144 /* Try to get an XImage for img->pixmep. */
8145 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8146 0, 0, img->width, img->height, ~0, ZPixmap);
8147 if (ximg)
8149 int x, y;
8151 /* Initialize the color table. */
8152 init_color_table ();
8154 /* For each pixel of the image, look its color up in the
8155 color table. After having done so, the color table will
8156 contain an entry for each color used by the image. */
8157 for (y = 0; y < img->height; ++y)
8158 for (x = 0; x < img->width; ++x)
8160 unsigned long pixel = XGetPixel (ximg, x, y);
8161 lookup_pixel_color (f, pixel);
8164 /* Record colors in the image. Free color table and XImage. */
8165 #ifdef COLOR_TABLE_SUPPORT
8166 img->colors = colors_in_color_table (&img->ncolors);
8167 free_color_table ();
8168 #endif
8169 XDestroyImage (ximg);
8171 #if 0 /* This doesn't seem to be the case. If we free the colors
8172 here, we get a BadAccess later in x_clear_image when
8173 freeing the colors. */
8174 /* We have allocated colors once, but Ghostscript has also
8175 allocated colors on behalf of us. So, to get the
8176 reference counts right, free them once. */
8177 if (img->ncolors)
8178 x_free_colors (f, img->colors, img->ncolors);
8179 #endif
8181 else
8182 image_error ("Cannot get X image of `%s'; colors will not be freed",
8183 img->spec, Qnil);
8185 UNBLOCK_INPUT;
8187 #endif /* HAVE_X_WINDOWS */
8189 /* Now that we have the pixmap, compute mask and transform the
8190 image if requested. */
8191 BLOCK_INPUT;
8192 postprocess_image (f, img);
8193 UNBLOCK_INPUT;
8196 #endif /* HAVE_GHOSTSCRIPT */
8199 /***********************************************************************
8200 Tests
8201 ***********************************************************************/
8203 #if GLYPH_DEBUG
8205 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8206 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8207 (spec)
8208 Lisp_Object spec;
8210 return valid_image_p (spec) ? Qt : Qnil;
8214 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8215 (spec)
8216 Lisp_Object spec;
8218 int id = -1;
8220 if (valid_image_p (spec))
8221 id = lookup_image (SELECTED_FRAME (), spec);
8223 debug_print (spec);
8224 return make_number (id);
8227 #endif /* GLYPH_DEBUG != 0 */
8230 /***********************************************************************
8231 Initialization
8232 ***********************************************************************/
8234 #ifdef HAVE_NTGUI
8235 /* Image types that rely on external libraries are loaded dynamically
8236 if the library is available. */
8237 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8238 define_image_type (image_type, init_lib_fn (libraries))
8239 #else
8240 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8241 define_image_type (image_type, 1)
8242 #endif /* HAVE_NTGUI */
8244 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8245 doc: /* Initialize image library implementing image type TYPE.
8246 Return non-nil if TYPE is a supported image type.
8248 Image types pbm and xbm are prebuilt; other types are loaded here.
8249 Libraries to load are specified in alist LIBRARIES (usually, the value
8250 of `image-library-alist', which see). */)
8251 (type, libraries)
8252 Lisp_Object type, libraries;
8254 Lisp_Object tested;
8256 /* Don't try to reload the library. */
8257 tested = Fassq (type, Vimage_type_cache);
8258 if (CONSP (tested))
8259 return XCDR (tested);
8261 #if defined (HAVE_XPM) || defined (MAC_OS)
8262 if (EQ (type, Qxpm))
8263 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8264 #endif
8266 #if defined (HAVE_JPEG) || defined (MAC_OS)
8267 if (EQ (type, Qjpeg))
8268 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8269 #endif
8271 #if defined (HAVE_TIFF) || defined (MAC_OS)
8272 if (EQ (type, Qtiff))
8273 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8274 #endif
8276 #if defined (HAVE_GIF) || defined (MAC_OS)
8277 if (EQ (type, Qgif))
8278 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8279 #endif
8281 #if defined (HAVE_PNG) || defined (MAC_OS)
8282 if (EQ (type, Qpng))
8283 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8284 #endif
8286 #ifdef HAVE_GHOSTSCRIPT
8287 if (EQ (type, Qpostscript))
8288 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8289 #endif
8291 /* If the type is not recognized, avoid testing it ever again. */
8292 CACHE_IMAGE_TYPE (type, Qnil);
8293 return Qnil;
8296 void
8297 syms_of_image ()
8299 extern Lisp_Object Qrisky_local_variable; /* Syms_of_xdisp has already run. */
8301 /* Initialize this only once, since that's what we do with Vimage_types
8302 and they are supposed to be in sync. Initializing here gives correct
8303 operation on GNU/Linux of calling dump-emacs after loading some images. */
8304 image_types = NULL;
8306 /* Must be defined now becase we're going to update it below, while
8307 defining the supported image types. */
8308 DEFVAR_LISP ("image-types", &Vimage_types,
8309 doc: /* List of potentially supported image types.
8310 Each element of the list is a symbol for a image type, like 'jpeg or 'png.
8311 To check whether it is really supported, use `image-type-available-p'. */);
8312 Vimage_types = Qnil;
8314 DEFVAR_LISP ("image-library-alist", &Vimage_library_alist,
8315 doc: /* Alist of image types vs external libraries needed to display them.
8317 Each element is a list (IMAGE-TYPE LIBRARY...), where the car is a symbol
8318 representing a supported image type, and the rest are strings giving
8319 alternate filenames for the corresponding external libraries.
8321 Emacs tries to load the libraries in the order they appear on the
8322 list; if none is loaded, the running session of Emacs won't
8323 support the image type. Types 'pbm and 'xbm don't need to be
8324 listed; they're always supported. */);
8325 Vimage_library_alist = Qnil;
8326 Fput (intern ("image-library-alist"), Qrisky_local_variable, Qt);
8328 DEFVAR_LISP ("max-image-size", &Vmax_image_size,
8329 doc: /* Maximum size of images.
8330 Emacs will not load an image into memory if its pixel width or
8331 pixel height exceeds this limit.
8333 If the value is an integer, it directly specifies the maximum
8334 image height and width, measured in pixels. If it is a floating
8335 point number, it specifies the maximum image height and width
8336 as a ratio to the frame height and width. If the value is
8337 non-numeric, there is no explicit limit on the size of images. */);
8338 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8340 Vimage_type_cache = Qnil;
8341 staticpro (&Vimage_type_cache);
8343 Qpbm = intern ("pbm");
8344 staticpro (&Qpbm);
8345 ADD_IMAGE_TYPE(Qpbm);
8347 Qxbm = intern ("xbm");
8348 staticpro (&Qxbm);
8349 ADD_IMAGE_TYPE(Qxbm);
8351 define_image_type (&xbm_type, 1);
8352 define_image_type (&pbm_type, 1);
8354 QCascent = intern (":ascent");
8355 staticpro (&QCascent);
8356 QCmargin = intern (":margin");
8357 staticpro (&QCmargin);
8358 QCrelief = intern (":relief");
8359 staticpro (&QCrelief);
8360 QCconversion = intern (":conversion");
8361 staticpro (&QCconversion);
8362 QCcolor_symbols = intern (":color-symbols");
8363 staticpro (&QCcolor_symbols);
8364 QCheuristic_mask = intern (":heuristic-mask");
8365 staticpro (&QCheuristic_mask);
8366 QCindex = intern (":index");
8367 staticpro (&QCindex);
8368 QCmatrix = intern (":matrix");
8369 staticpro (&QCmatrix);
8370 QCcolor_adjustment = intern (":color-adjustment");
8371 staticpro (&QCcolor_adjustment);
8372 QCmask = intern (":mask");
8373 staticpro (&QCmask);
8375 Qlaplace = intern ("laplace");
8376 staticpro (&Qlaplace);
8377 Qemboss = intern ("emboss");
8378 staticpro (&Qemboss);
8379 Qedge_detection = intern ("edge-detection");
8380 staticpro (&Qedge_detection);
8381 Qheuristic = intern ("heuristic");
8382 staticpro (&Qheuristic);
8384 Qpostscript = intern ("postscript");
8385 staticpro (&Qpostscript);
8386 #ifdef HAVE_GHOSTSCRIPT
8387 ADD_IMAGE_TYPE(Qpostscript);
8388 QCloader = intern (":loader");
8389 staticpro (&QCloader);
8390 QCbounding_box = intern (":bounding-box");
8391 staticpro (&QCbounding_box);
8392 QCpt_width = intern (":pt-width");
8393 staticpro (&QCpt_width);
8394 QCpt_height = intern (":pt-height");
8395 staticpro (&QCpt_height);
8396 #endif /* HAVE_GHOSTSCRIPT */
8398 #if defined (HAVE_XPM) || defined (MAC_OS)
8399 Qxpm = intern ("xpm");
8400 staticpro (&Qxpm);
8401 ADD_IMAGE_TYPE(Qxpm);
8402 #endif
8404 #if defined (HAVE_JPEG) || defined (MAC_OS)
8405 Qjpeg = intern ("jpeg");
8406 staticpro (&Qjpeg);
8407 ADD_IMAGE_TYPE(Qjpeg);
8408 #endif
8410 #if defined (HAVE_TIFF) || defined (MAC_OS)
8411 Qtiff = intern ("tiff");
8412 staticpro (&Qtiff);
8413 ADD_IMAGE_TYPE(Qtiff);
8414 #endif
8416 #if defined (HAVE_GIF) || defined (MAC_OS)
8417 Qgif = intern ("gif");
8418 staticpro (&Qgif);
8419 ADD_IMAGE_TYPE(Qgif);
8420 #endif
8422 #if defined (HAVE_PNG) || defined (MAC_OS)
8423 Qpng = intern ("png");
8424 staticpro (&Qpng);
8425 ADD_IMAGE_TYPE(Qpng);
8426 #endif
8428 defsubr (&Sinit_image_library);
8429 defsubr (&Sclear_image_cache);
8430 defsubr (&Simage_size);
8431 defsubr (&Simage_mask_p);
8433 #if GLYPH_DEBUG
8434 defsubr (&Simagep);
8435 defsubr (&Slookup_image);
8436 #endif
8438 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
8439 doc: /* Non-nil means always draw a cross over disabled images.
8440 Disabled images are those having an `:conversion disabled' property.
8441 A cross is always drawn on black & white displays. */);
8442 cross_disabled_images = 0;
8444 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
8445 doc: /* List of directories to search for window system bitmap files. */);
8446 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8448 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
8449 doc: /* Time after which cached images are removed from the cache.
8450 When an image has not been displayed this many seconds, remove it
8451 from the image cache. Value must be an integer or nil with nil
8452 meaning don't clear the cache. */);
8453 Vimage_cache_eviction_delay = make_number (30 * 60);
8456 void
8457 init_image ()
8459 #ifdef MAC_OS
8460 /* Animated gifs use QuickTime Movie Toolbox. So initialize it here. */
8461 if (!inhibit_window_system)
8462 EnterMovies ();
8463 #ifdef MAC_OSX
8464 init_image_func_pointer ();
8465 #endif
8466 #endif
8469 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
8470 (do not change this comment) */