(Progress, Defining Faces):
[emacs.git] / src / image.c
blob2463c24a33af2b430f1c7a39096f860f0b725e7c
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));
1104 /* Allocate and return a new image structure for image specification
1105 SPEC. SPEC has a hash value of HASH. */
1107 static struct image *
1108 make_image (spec, hash)
1109 Lisp_Object spec;
1110 unsigned hash;
1112 struct image *img = (struct image *) xmalloc (sizeof *img);
1114 xassert (valid_image_p (spec));
1115 bzero (img, sizeof *img);
1116 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1117 xassert (img->type != NULL);
1118 img->spec = spec;
1119 img->data.lisp_val = Qnil;
1120 img->ascent = DEFAULT_IMAGE_ASCENT;
1121 img->hash = hash;
1122 return img;
1126 /* Free image IMG which was used on frame F, including its resources. */
1128 static void
1129 free_image (f, img)
1130 struct frame *f;
1131 struct image *img;
1133 if (img)
1135 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1137 /* Remove IMG from the hash table of its cache. */
1138 if (img->prev)
1139 img->prev->next = img->next;
1140 else
1141 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1143 if (img->next)
1144 img->next->prev = img->prev;
1146 c->images[img->id] = NULL;
1148 /* Free resources, then free IMG. */
1149 img->type->free (f, img);
1150 xfree (img);
1155 /* Prepare image IMG for display on frame F. Must be called before
1156 drawing an image. */
1158 void
1159 prepare_image_for_display (f, img)
1160 struct frame *f;
1161 struct image *img;
1163 EMACS_TIME t;
1165 /* We're about to display IMG, so set its timestamp to `now'. */
1166 EMACS_GET_TIME (t);
1167 img->timestamp = EMACS_SECS (t);
1169 /* If IMG doesn't have a pixmap yet, load it now, using the image
1170 type dependent loader function. */
1171 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1172 img->load_failed_p = img->type->load (f, img) == 0;
1176 /* Value is the number of pixels for the ascent of image IMG when
1177 drawn in face FACE. */
1180 image_ascent (img, face, slice)
1181 struct image *img;
1182 struct face *face;
1183 struct glyph_slice *slice;
1185 int height;
1186 int ascent;
1188 if (slice->height == img->height)
1189 height = img->height + img->vmargin;
1190 else if (slice->y == 0)
1191 height = slice->height + img->vmargin;
1192 else
1193 height = slice->height;
1195 if (img->ascent == CENTERED_IMAGE_ASCENT)
1197 if (face->font)
1199 #ifdef HAVE_NTGUI
1200 /* W32 specific version. Why?. ++kfs */
1201 ascent = height / 2 - (FONT_DESCENT(face->font)
1202 - FONT_BASE(face->font)) / 2;
1203 #else
1204 /* This expression is arranged so that if the image can't be
1205 exactly centered, it will be moved slightly up. This is
1206 because a typical font is `top-heavy' (due to the presence
1207 uppercase letters), so the image placement should err towards
1208 being top-heavy too. It also just generally looks better. */
1209 ascent = (height + face->font->ascent - face->font->descent + 1) / 2;
1210 #endif /* HAVE_NTGUI */
1212 else
1213 ascent = height / 2;
1215 else
1216 ascent = (int) (height * img->ascent / 100.0);
1218 return ascent;
1222 /* Image background colors. */
1224 /* Find the "best" corner color of a bitmap.
1225 On W32, XIMG is assumed to a device context with the bitmap selected. */
1227 static RGB_PIXEL_COLOR
1228 four_corners_best (ximg, width, height)
1229 XImagePtr_or_DC ximg;
1230 unsigned long width, height;
1232 RGB_PIXEL_COLOR corners[4], best;
1233 int i, best_count;
1235 /* Get the colors at the corners of ximg. */
1236 corners[0] = GET_PIXEL (ximg, 0, 0);
1237 corners[1] = GET_PIXEL (ximg, width - 1, 0);
1238 corners[2] = GET_PIXEL (ximg, width - 1, height - 1);
1239 corners[3] = GET_PIXEL (ximg, 0, height - 1);
1241 /* Choose the most frequently found color as background. */
1242 for (i = best_count = 0; i < 4; ++i)
1244 int j, n;
1246 for (j = n = 0; j < 4; ++j)
1247 if (corners[i] == corners[j])
1248 ++n;
1250 if (n > best_count)
1251 best = corners[i], best_count = n;
1254 return best;
1257 /* Portability macros */
1259 #ifdef HAVE_NTGUI
1261 #define Destroy_Image(img_dc, prev) \
1262 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1264 #define Free_Pixmap(display, pixmap) \
1265 DeleteObject (pixmap)
1267 #else
1269 #define Destroy_Image(ximg, dummy) \
1270 XDestroyImage (ximg)
1272 #define Free_Pixmap(display, pixmap) \
1273 XFreePixmap (display, pixmap)
1275 #endif /* HAVE_NTGUI */
1278 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1279 it is guessed heuristically. If non-zero, XIMG is an existing
1280 XImage object (or device context with the image selected on W32) to
1281 use for the heuristic. */
1283 RGB_PIXEL_COLOR
1284 image_background (img, f, ximg)
1285 struct image *img;
1286 struct frame *f;
1287 XImagePtr_or_DC ximg;
1289 if (! img->background_valid)
1290 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1292 int free_ximg = !ximg;
1293 #ifdef HAVE_NTGUI
1294 HGDIOBJ prev;
1295 #endif /* HAVE_NTGUI */
1297 if (free_ximg)
1299 #ifndef HAVE_NTGUI
1300 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1301 0, 0, img->width, img->height, ~0, ZPixmap);
1302 #else
1303 HDC frame_dc = get_frame_dc (f);
1304 ximg = CreateCompatibleDC (frame_dc);
1305 release_frame_dc (f, frame_dc);
1306 prev = SelectObject (ximg, img->pixmap);
1307 #endif /* !HAVE_NTGUI */
1310 img->background = four_corners_best (ximg, img->width, img->height);
1312 if (free_ximg)
1313 Destroy_Image (ximg, prev);
1315 img->background_valid = 1;
1318 return img->background;
1321 /* Return the `background_transparent' field of IMG. If IMG doesn't
1322 have one yet, it is guessed heuristically. If non-zero, MASK is an
1323 existing XImage object to use for the heuristic. */
1326 image_background_transparent (img, f, mask)
1327 struct image *img;
1328 struct frame *f;
1329 XImagePtr_or_DC mask;
1331 if (! img->background_transparent_valid)
1332 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1334 if (img->mask)
1336 int free_mask = !mask;
1337 #ifdef HAVE_NTGUI
1338 HGDIOBJ prev;
1339 #endif /* HAVE_NTGUI */
1341 if (free_mask)
1343 #ifndef HAVE_NTGUI
1344 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1345 0, 0, img->width, img->height, ~0, ZPixmap);
1346 #else
1347 HDC frame_dc = get_frame_dc (f);
1348 mask = CreateCompatibleDC (frame_dc);
1349 release_frame_dc (f, frame_dc);
1350 prev = SelectObject (mask, img->mask);
1351 #endif /* HAVE_NTGUI */
1354 img->background_transparent
1355 = (four_corners_best (mask, img->width, img->height) == PIX_MASK_RETAIN);
1357 if (free_mask)
1358 Destroy_Image (mask, prev);
1360 else
1361 img->background_transparent = 0;
1363 img->background_transparent_valid = 1;
1366 return img->background_transparent;
1370 /***********************************************************************
1371 Helper functions for X image types
1372 ***********************************************************************/
1374 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
1375 int, int));
1376 static void x_clear_image P_ ((struct frame *f, struct image *img));
1377 static unsigned long x_alloc_image_color P_ ((struct frame *f,
1378 struct image *img,
1379 Lisp_Object color_name,
1380 unsigned long dflt));
1383 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1384 free the pixmap if any. MASK_P non-zero means clear the mask
1385 pixmap if any. COLORS_P non-zero means free colors allocated for
1386 the image, if any. */
1388 static void
1389 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
1390 struct frame *f;
1391 struct image *img;
1392 int pixmap_p, mask_p, colors_p;
1394 if (pixmap_p && img->pixmap)
1396 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1397 img->pixmap = NO_PIXMAP;
1398 img->background_valid = 0;
1401 if (mask_p && img->mask)
1403 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1404 img->mask = NO_PIXMAP;
1405 img->background_transparent_valid = 0;
1408 if (colors_p && img->ncolors)
1410 /* MAC_TODO: color table support. */
1411 /* W32_TODO: color table support. */
1412 #ifdef HAVE_X_WINDOWS
1413 x_free_colors (f, img->colors, img->ncolors);
1414 #endif /* HAVE_X_WINDOWS */
1415 xfree (img->colors);
1416 img->colors = NULL;
1417 img->ncolors = 0;
1421 /* Free X resources of image IMG which is used on frame F. */
1423 static void
1424 x_clear_image (f, img)
1425 struct frame *f;
1426 struct image *img;
1428 BLOCK_INPUT;
1429 x_clear_image_1 (f, img, 1, 1, 1);
1430 UNBLOCK_INPUT;
1434 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1435 cannot be allocated, use DFLT. Add a newly allocated color to
1436 IMG->colors, so that it can be freed again. Value is the pixel
1437 color. */
1439 static unsigned long
1440 x_alloc_image_color (f, img, color_name, dflt)
1441 struct frame *f;
1442 struct image *img;
1443 Lisp_Object color_name;
1444 unsigned long dflt;
1446 XColor color;
1447 unsigned long result;
1449 xassert (STRINGP (color_name));
1451 if (x_defined_color (f, SDATA (color_name), &color, 1))
1453 /* This isn't called frequently so we get away with simply
1454 reallocating the color vector to the needed size, here. */
1455 ++img->ncolors;
1456 img->colors =
1457 (unsigned long *) xrealloc (img->colors,
1458 img->ncolors * sizeof *img->colors);
1459 img->colors[img->ncolors - 1] = color.pixel;
1460 result = color.pixel;
1462 else
1463 result = dflt;
1465 return result;
1470 /***********************************************************************
1471 Image Cache
1472 ***********************************************************************/
1474 static void cache_image P_ ((struct frame *f, struct image *img));
1475 static void postprocess_image P_ ((struct frame *, struct image *));
1477 /* Return a new, initialized image cache that is allocated from the
1478 heap. Call free_image_cache to free an image cache. */
1480 struct image_cache *
1481 make_image_cache ()
1483 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1484 int size;
1486 bzero (c, sizeof *c);
1487 c->size = 50;
1488 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1489 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1490 c->buckets = (struct image **) xmalloc (size);
1491 bzero (c->buckets, size);
1492 return c;
1496 /* Free image cache of frame F. Be aware that X frames share images
1497 caches. */
1499 void
1500 free_image_cache (f)
1501 struct frame *f;
1503 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1504 if (c)
1506 int i;
1508 /* Cache should not be referenced by any frame when freed. */
1509 xassert (c->refcount == 0);
1511 for (i = 0; i < c->used; ++i)
1512 free_image (f, c->images[i]);
1513 xfree (c->images);
1514 xfree (c->buckets);
1515 xfree (c);
1516 FRAME_X_IMAGE_CACHE (f) = NULL;
1521 /* Clear image cache of frame F. FORCE_P non-zero means free all
1522 images. FORCE_P zero means clear only images that haven't been
1523 displayed for some time. Should be called from time to time to
1524 reduce the number of loaded images. If image-eviction-seconds is
1525 non-nil, this frees images in the cache which weren't displayed for
1526 at least that many seconds. */
1528 void
1529 clear_image_cache (f, force_p)
1530 struct frame *f;
1531 int force_p;
1533 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1535 if (c && INTEGERP (Vimage_cache_eviction_delay))
1537 EMACS_TIME t;
1538 unsigned long old;
1539 int i, nfreed;
1541 EMACS_GET_TIME (t);
1542 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
1544 /* Block input so that we won't be interrupted by a SIGIO
1545 while being in an inconsistent state. */
1546 BLOCK_INPUT;
1548 for (i = nfreed = 0; i < c->used; ++i)
1550 struct image *img = c->images[i];
1551 if (img != NULL
1552 && (force_p || img->timestamp < old))
1554 free_image (f, img);
1555 ++nfreed;
1559 /* We may be clearing the image cache because, for example,
1560 Emacs was iconified for a longer period of time. In that
1561 case, current matrices may still contain references to
1562 images freed above. So, clear these matrices. */
1563 if (nfreed)
1565 Lisp_Object tail, frame;
1567 FOR_EACH_FRAME (tail, frame)
1569 struct frame *f = XFRAME (frame);
1570 if (FRAME_WINDOW_P (f)
1571 && FRAME_X_IMAGE_CACHE (f) == c)
1572 clear_current_matrices (f);
1575 ++windows_or_buffers_changed;
1578 UNBLOCK_INPUT;
1583 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1584 0, 1, 0,
1585 doc: /* Clear the image cache of FRAME.
1586 FRAME nil or omitted means use the selected frame.
1587 FRAME t means clear the image caches of all frames. */)
1588 (frame)
1589 Lisp_Object frame;
1591 if (EQ (frame, Qt))
1593 Lisp_Object tail;
1595 FOR_EACH_FRAME (tail, frame)
1596 if (FRAME_WINDOW_P (XFRAME (frame)))
1597 clear_image_cache (XFRAME (frame), 1);
1599 else
1600 clear_image_cache (check_x_frame (frame), 1);
1602 return Qnil;
1606 /* Compute masks and transform image IMG on frame F, as specified
1607 by the image's specification, */
1609 static void
1610 postprocess_image (f, img)
1611 struct frame *f;
1612 struct image *img;
1614 /* Manipulation of the image's mask. */
1615 if (img->pixmap)
1617 Lisp_Object conversion, spec;
1618 Lisp_Object mask;
1620 spec = img->spec;
1622 /* `:heuristic-mask t'
1623 `:mask heuristic'
1624 means build a mask heuristically.
1625 `:heuristic-mask (R G B)'
1626 `:mask (heuristic (R G B))'
1627 means build a mask from color (R G B) in the
1628 image.
1629 `:mask nil'
1630 means remove a mask, if any. */
1632 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1633 if (!NILP (mask))
1634 x_build_heuristic_mask (f, img, mask);
1635 else
1637 int found_p;
1639 mask = image_spec_value (spec, QCmask, &found_p);
1641 if (EQ (mask, Qheuristic))
1642 x_build_heuristic_mask (f, img, Qt);
1643 else if (CONSP (mask)
1644 && EQ (XCAR (mask), Qheuristic))
1646 if (CONSP (XCDR (mask)))
1647 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1648 else
1649 x_build_heuristic_mask (f, img, XCDR (mask));
1651 else if (NILP (mask) && found_p && img->mask)
1653 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1654 img->mask = NO_PIXMAP;
1659 /* Should we apply an image transformation algorithm? */
1660 conversion = image_spec_value (spec, QCconversion, NULL);
1661 if (EQ (conversion, Qdisabled))
1662 x_disable_image (f, img);
1663 else if (EQ (conversion, Qlaplace))
1664 x_laplace (f, img);
1665 else if (EQ (conversion, Qemboss))
1666 x_emboss (f, img);
1667 else if (CONSP (conversion)
1668 && EQ (XCAR (conversion), Qedge_detection))
1670 Lisp_Object tem;
1671 tem = XCDR (conversion);
1672 if (CONSP (tem))
1673 x_edge_detection (f, img,
1674 Fplist_get (tem, QCmatrix),
1675 Fplist_get (tem, QCcolor_adjustment));
1681 /* Return the id of image with Lisp specification SPEC on frame F.
1682 SPEC must be a valid Lisp image specification (see valid_image_p). */
1685 lookup_image (f, spec)
1686 struct frame *f;
1687 Lisp_Object spec;
1689 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1690 struct image *img;
1691 int i;
1692 unsigned hash;
1693 struct gcpro gcpro1;
1694 EMACS_TIME now;
1696 /* F must be a window-system frame, and SPEC must be a valid image
1697 specification. */
1698 xassert (FRAME_WINDOW_P (f));
1699 xassert (valid_image_p (spec));
1701 GCPRO1 (spec);
1703 /* Look up SPEC in the hash table of the image cache. */
1704 hash = sxhash (spec, 0);
1705 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1707 for (img = c->buckets[i]; img; img = img->next)
1708 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
1709 break;
1711 /* If not found, create a new image and cache it. */
1712 if (img == NULL)
1714 extern Lisp_Object Qpostscript;
1716 BLOCK_INPUT;
1717 img = make_image (spec, hash);
1718 cache_image (f, img);
1719 img->load_failed_p = img->type->load (f, img) == 0;
1721 /* If we can't load the image, and we don't have a width and
1722 height, use some arbitrary width and height so that we can
1723 draw a rectangle for it. */
1724 if (img->load_failed_p)
1726 Lisp_Object value;
1728 value = image_spec_value (spec, QCwidth, NULL);
1729 img->width = (INTEGERP (value)
1730 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1731 value = image_spec_value (spec, QCheight, NULL);
1732 img->height = (INTEGERP (value)
1733 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1735 else
1737 /* Handle image type independent image attributes
1738 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1739 `:background COLOR'. */
1740 Lisp_Object ascent, margin, relief, bg;
1742 ascent = image_spec_value (spec, QCascent, NULL);
1743 if (INTEGERP (ascent))
1744 img->ascent = XFASTINT (ascent);
1745 else if (EQ (ascent, Qcenter))
1746 img->ascent = CENTERED_IMAGE_ASCENT;
1748 margin = image_spec_value (spec, QCmargin, NULL);
1749 if (INTEGERP (margin) && XINT (margin) >= 0)
1750 img->vmargin = img->hmargin = XFASTINT (margin);
1751 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1752 && INTEGERP (XCDR (margin)))
1754 if (XINT (XCAR (margin)) > 0)
1755 img->hmargin = XFASTINT (XCAR (margin));
1756 if (XINT (XCDR (margin)) > 0)
1757 img->vmargin = XFASTINT (XCDR (margin));
1760 relief = image_spec_value (spec, QCrelief, NULL);
1761 if (INTEGERP (relief))
1763 img->relief = XINT (relief);
1764 img->hmargin += abs (img->relief);
1765 img->vmargin += abs (img->relief);
1768 if (! img->background_valid)
1770 bg = image_spec_value (img->spec, QCbackground, NULL);
1771 if (!NILP (bg))
1773 img->background
1774 = x_alloc_image_color (f, img, bg,
1775 FRAME_BACKGROUND_PIXEL (f));
1776 img->background_valid = 1;
1780 /* Do image transformations and compute masks, unless we
1781 don't have the image yet. */
1782 if (!EQ (*img->type->type, Qpostscript))
1783 postprocess_image (f, img);
1786 UNBLOCK_INPUT;
1789 /* We're using IMG, so set its timestamp to `now'. */
1790 EMACS_GET_TIME (now);
1791 img->timestamp = EMACS_SECS (now);
1793 UNGCPRO;
1795 /* Value is the image id. */
1796 return img->id;
1800 /* Cache image IMG in the image cache of frame F. */
1802 static void
1803 cache_image (f, img)
1804 struct frame *f;
1805 struct image *img;
1807 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1808 int i;
1810 /* Find a free slot in c->images. */
1811 for (i = 0; i < c->used; ++i)
1812 if (c->images[i] == NULL)
1813 break;
1815 /* If no free slot found, maybe enlarge c->images. */
1816 if (i == c->used && c->used == c->size)
1818 c->size *= 2;
1819 c->images = (struct image **) xrealloc (c->images,
1820 c->size * sizeof *c->images);
1823 /* Add IMG to c->images, and assign IMG an id. */
1824 c->images[i] = img;
1825 img->id = i;
1826 if (i == c->used)
1827 ++c->used;
1829 /* Add IMG to the cache's hash table. */
1830 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1831 img->next = c->buckets[i];
1832 if (img->next)
1833 img->next->prev = img;
1834 img->prev = NULL;
1835 c->buckets[i] = img;
1839 /* Call FN on every image in the image cache of frame F. Used to mark
1840 Lisp Objects in the image cache. */
1842 void
1843 forall_images_in_image_cache (f, fn)
1844 struct frame *f;
1845 void (*fn) P_ ((struct image *img));
1847 if (FRAME_LIVE_P (f) && FRAME_WINDOW_P (f))
1849 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1850 if (c)
1852 int i;
1853 for (i = 0; i < c->used; ++i)
1854 if (c->images[i])
1855 fn (c->images[i]);
1862 /***********************************************************************
1863 X / MAC / W32 support code
1864 ***********************************************************************/
1866 #ifdef HAVE_NTGUI
1868 /* Macro for defining functions that will be loaded from image DLLs. */
1869 #define DEF_IMGLIB_FN(func) int (FAR CDECL *fn_##func)()
1871 /* Macro for loading those image functions from the library. */
1872 #define LOAD_IMGLIB_FN(lib,func) { \
1873 fn_##func = (void *) GetProcAddress (lib, #func); \
1874 if (!fn_##func) return 0; \
1877 /* Load a DLL implementing an image type.
1878 The `image-library-alist' variable associates a symbol,
1879 identifying an image type, to a list of possible filenames.
1880 The function returns NULL if no library could be loaded for
1881 the given image type, or if the library was previously loaded;
1882 else the handle of the DLL. */
1883 static HMODULE
1884 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
1886 HMODULE library = NULL;
1888 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
1890 Lisp_Object dlls = Fassq (type, libraries);
1892 if (CONSP (dlls))
1893 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
1895 CHECK_STRING_CAR (dlls);
1896 if (library = LoadLibrary (SDATA (XCAR (dlls))))
1897 break;
1901 return library;
1904 #endif /* HAVE_NTGUI */
1906 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
1907 XImagePtr *, Pixmap *));
1908 static void x_destroy_x_image P_ ((XImagePtr));
1909 static void x_put_x_image P_ ((struct frame *, XImagePtr, Pixmap, int, int));
1912 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1913 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1914 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1915 via xmalloc. Print error messages via image_error if an error
1916 occurs. Value is non-zero if successful.
1918 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1919 should indicate the bit depth of the image. */
1921 static int
1922 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
1923 struct frame *f;
1924 int width, height, depth;
1925 XImagePtr *ximg;
1926 Pixmap *pixmap;
1928 #ifdef HAVE_X_WINDOWS
1929 Display *display = FRAME_X_DISPLAY (f);
1930 Window window = FRAME_X_WINDOW (f);
1931 Screen *screen = FRAME_X_SCREEN (f);
1933 xassert (interrupt_input_blocked);
1935 if (depth <= 0)
1936 depth = DefaultDepthOfScreen (screen);
1937 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1938 depth, ZPixmap, 0, NULL, width, height,
1939 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1940 if (*ximg == NULL)
1942 image_error ("Unable to allocate X image", Qnil, Qnil);
1943 return 0;
1946 /* Allocate image raster. */
1947 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
1949 /* Allocate a pixmap of the same size. */
1950 *pixmap = XCreatePixmap (display, window, width, height, depth);
1951 if (*pixmap == NO_PIXMAP)
1953 x_destroy_x_image (*ximg);
1954 *ximg = NULL;
1955 image_error ("Unable to create X pixmap", Qnil, Qnil);
1956 return 0;
1959 return 1;
1960 #endif /* HAVE_X_WINDOWS */
1962 #ifdef HAVE_NTGUI
1964 BITMAPINFOHEADER *header;
1965 HDC hdc;
1966 int scanline_width_bits;
1967 int remainder;
1968 int palette_colors = 0;
1970 if (depth == 0)
1971 depth = 24;
1973 if (depth != 1 && depth != 4 && depth != 8
1974 && depth != 16 && depth != 24 && depth != 32)
1976 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1977 return 0;
1980 scanline_width_bits = width * depth;
1981 remainder = scanline_width_bits % 32;
1983 if (remainder)
1984 scanline_width_bits += 32 - remainder;
1986 /* Bitmaps with a depth less than 16 need a palette. */
1987 /* BITMAPINFO structure already contains the first RGBQUAD. */
1988 if (depth < 16)
1989 palette_colors = 1 << depth - 1;
1991 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1992 if (*ximg == NULL)
1994 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
1995 return 0;
1998 header = &((*ximg)->info.bmiHeader);
1999 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
2000 header->biSize = sizeof (*header);
2001 header->biWidth = width;
2002 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2003 header->biPlanes = 1;
2004 header->biBitCount = depth;
2005 header->biCompression = BI_RGB;
2006 header->biClrUsed = palette_colors;
2008 /* TODO: fill in palette. */
2009 if (depth == 1)
2011 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2012 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2013 (*ximg)->info.bmiColors[0].rgbRed = 0;
2014 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2015 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2016 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2017 (*ximg)->info.bmiColors[1].rgbRed = 255;
2018 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2021 hdc = get_frame_dc (f);
2023 /* Create a DIBSection and raster array for the bitmap,
2024 and store its handle in *pixmap. */
2025 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2026 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2027 /* casting avoids a GCC warning */
2028 (void **)&((*ximg)->data), NULL, 0);
2030 /* Realize display palette and garbage all frames. */
2031 release_frame_dc (f, hdc);
2033 if (*pixmap == NULL)
2035 DWORD err = GetLastError();
2036 Lisp_Object errcode;
2037 /* All system errors are < 10000, so the following is safe. */
2038 XSETINT (errcode, (int) err);
2039 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2040 x_destroy_x_image (*ximg);
2041 return 0;
2044 return 1;
2046 #endif /* HAVE_NTGUI */
2048 #ifdef MAC_OS
2049 Display *display = FRAME_X_DISPLAY (f);
2050 Window window = FRAME_X_WINDOW (f);
2052 xassert (interrupt_input_blocked);
2054 /* Allocate a pixmap of the same size. */
2055 *pixmap = XCreatePixmap (display, window, width, height, depth);
2056 if (*pixmap == NO_PIXMAP)
2058 *ximg = NULL;
2059 image_error ("Unable to create X pixmap", Qnil, Qnil);
2060 return 0;
2063 LockPixels (GetGWorldPixMap (*pixmap));
2064 *ximg = *pixmap;
2065 return 1;
2067 #endif /* MAC_OS */
2071 /* Destroy XImage XIMG. Free XIMG->data. */
2073 static void
2074 x_destroy_x_image (ximg)
2075 XImagePtr ximg;
2077 xassert (interrupt_input_blocked);
2078 if (ximg)
2080 #ifdef HAVE_X_WINDOWS
2081 xfree (ximg->data);
2082 ximg->data = NULL;
2083 XDestroyImage (ximg);
2084 #endif /* HAVE_X_WINDOWS */
2085 #ifdef HAVE_NTGUI
2086 /* Data will be freed by DestroyObject. */
2087 ximg->data = NULL;
2088 xfree (ximg);
2089 #endif /* HAVE_NTGUI */
2090 #ifdef MAC_OS
2091 XDestroyImage (ximg);
2092 #endif /* MAC_OS */
2097 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2098 are width and height of both the image and pixmap. */
2100 static void
2101 x_put_x_image (f, ximg, pixmap, width, height)
2102 struct frame *f;
2103 XImagePtr ximg;
2104 Pixmap pixmap;
2105 int width, height;
2107 #ifdef HAVE_X_WINDOWS
2108 GC gc;
2110 xassert (interrupt_input_blocked);
2111 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2112 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2113 XFreeGC (FRAME_X_DISPLAY (f), gc);
2114 #endif /* HAVE_X_WINDOWS */
2116 #ifdef HAVE_NTGUI
2117 #if 0 /* I don't think this is necessary looking at where it is used. */
2118 HDC hdc = get_frame_dc (f);
2119 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2120 release_frame_dc (f, hdc);
2121 #endif
2122 #endif /* HAVE_NTGUI */
2124 #ifdef MAC_OS
2125 xassert (ximg == pixmap);
2126 #endif /* MAC_OS */
2130 /***********************************************************************
2131 File Handling
2132 ***********************************************************************/
2134 static unsigned char *slurp_file P_ ((char *, int *));
2137 /* Find image file FILE. Look in data-directory, then
2138 x-bitmap-file-path. Value is the full name of the file found, or
2139 nil if not found. */
2141 Lisp_Object
2142 x_find_image_file (file)
2143 Lisp_Object file;
2145 Lisp_Object file_found, search_path;
2146 struct gcpro gcpro1, gcpro2;
2147 int fd;
2149 file_found = Qnil;
2150 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
2151 GCPRO2 (file_found, search_path);
2153 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
2154 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2156 if (fd == -1)
2157 file_found = Qnil;
2158 else
2159 close (fd);
2161 UNGCPRO;
2162 return file_found;
2166 /* Read FILE into memory. Value is a pointer to a buffer allocated
2167 with xmalloc holding FILE's contents. Value is null if an error
2168 occurred. *SIZE is set to the size of the file. */
2170 static unsigned char *
2171 slurp_file (file, size)
2172 char *file;
2173 int *size;
2175 FILE *fp = NULL;
2176 unsigned char *buf = NULL;
2177 struct stat st;
2179 if (stat (file, &st) == 0
2180 && (fp = fopen (file, "rb")) != NULL
2181 && (buf = (unsigned char *) xmalloc (st.st_size),
2182 fread (buf, 1, st.st_size, fp) == st.st_size))
2184 *size = st.st_size;
2185 fclose (fp);
2187 else
2189 if (fp)
2190 fclose (fp);
2191 if (buf)
2193 xfree (buf);
2194 buf = NULL;
2198 return buf;
2203 #ifdef MAC_OS
2205 /***********************************************************************
2206 MAC Image Load Functions
2207 ***********************************************************************/
2209 static int image_load_quicktime P_ ((struct frame *, struct image *img,
2210 OSType));
2211 #ifdef MAC_OSX
2212 static int image_load_quartz2d P_ ((struct frame *, struct image *img, int));
2213 #endif
2215 static OSErr
2216 find_image_fsspec (specified_file, file, fss)
2217 Lisp_Object specified_file, *file;
2218 FSSpec *fss;
2220 #if MAC_OSX
2221 FSRef fsr;
2222 #endif
2223 OSErr err;
2225 *file = x_find_image_file (specified_file);
2226 if (!STRINGP (*file))
2227 return fnfErr; /* file or directory not found;
2228 incomplete pathname */
2229 /* Try to open the image file. */
2230 #if MAC_OSX
2231 err = FSPathMakeRef (SDATA (*file), &fsr, NULL);
2232 if (err == noErr)
2233 err = FSGetCatalogInfo (&fsr, kFSCatInfoNone, NULL, NULL, fss, NULL);
2234 #else
2235 err = posix_pathname_to_fsspec (SDATA (*file), fss);
2236 #endif
2237 return err;
2240 static int
2241 image_load_qt_1 (f, img, type, fss, dh)
2242 struct frame *f;
2243 struct image *img;
2244 OSType type;
2245 FSSpec *fss;
2246 Handle dh;
2248 OSErr err;
2249 GraphicsImportComponent gi;
2250 Rect rect;
2251 int width, height;
2252 short draw_all_pixels;
2253 Lisp_Object specified_bg;
2254 XColor color;
2255 XImagePtr ximg;
2256 RGBColor bg_color;
2258 err = OpenADefaultComponent (GraphicsImporterComponentType,
2259 type, &gi);
2260 if (err != noErr)
2262 image_error ("Cannot get importer component for `%s'", img->spec, Qnil);
2263 return 0;
2265 if (dh == NULL)
2267 /* read from file system spec */
2268 err = GraphicsImportSetDataFile (gi, fss);
2269 if (err != noErr)
2271 image_error ("Cannot set fsspec to graphics importer for '%s'",
2272 img->spec, Qnil);
2273 goto error;
2276 else
2278 /* read from data handle */
2279 err = GraphicsImportSetDataHandle (gi, dh);
2280 if (err != noErr)
2282 image_error ("Cannot set data handle to graphics importer for `%s'",
2283 img->spec, Qnil);
2284 goto error;
2287 err = GraphicsImportGetNaturalBounds (gi, &rect);
2288 if (err != noErr)
2290 image_error ("Error reading `%s'", img->spec, Qnil);
2291 goto error;
2293 width = img->width = rect.right - rect.left;
2294 height = img->height = rect.bottom - rect.top;
2295 err = GraphicsImportDoesDrawAllPixels (gi, &draw_all_pixels);
2296 #if 0
2297 /* Don't check the error code here. It may have an undocumented
2298 value -32766. */
2299 if (err != noErr)
2301 image_error ("Error reading `%s'", img->spec, Qnil);
2302 goto error;
2304 #endif
2305 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2307 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2308 if (!STRINGP (specified_bg) ||
2309 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2311 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2312 color.red = RED16_FROM_ULONG (color.pixel);
2313 color.green = GREEN16_FROM_ULONG (color.pixel);
2314 color.blue = BLUE16_FROM_ULONG (color.pixel);
2318 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2319 goto error;
2320 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2322 CGrafPtr old_port;
2323 GDHandle old_gdh;
2325 GetGWorld (&old_port, &old_gdh);
2326 SetGWorld (ximg, NULL);
2327 bg_color.red = color.red;
2328 bg_color.green = color.green;
2329 bg_color.blue = color.blue;
2330 RGBBackColor (&bg_color);
2331 #if TARGET_API_MAC_CARBON
2332 GetPortBounds (ximg, &rect);
2333 EraseRect (&rect);
2334 #else
2335 EraseRect (&(ximg->portRect));
2336 #endif
2337 SetGWorld (old_port, old_gdh);
2339 GraphicsImportSetGWorld (gi, ximg, NULL);
2340 GraphicsImportDraw (gi);
2341 CloseComponent (gi);
2343 /* Maybe fill in the background field while we have ximg handy. */
2344 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2345 IMAGE_BACKGROUND (img, f, ximg);
2347 /* Put the image into the pixmap. */
2348 x_put_x_image (f, ximg, img->pixmap, width, height);
2349 x_destroy_x_image (ximg);
2350 return 1;
2352 error:
2353 CloseComponent (gi);
2354 return 0;
2358 /* Load an image using the QuickTime Graphics Importer.
2359 Note: The alpha channel does not work for PNG images. */
2360 static int
2361 image_load_quicktime (f, img, type)
2362 struct frame *f;
2363 struct image *img;
2364 OSType type;
2366 Lisp_Object specified_file;
2367 Lisp_Object specified_data;
2368 OSErr err;
2370 specified_file = image_spec_value (img->spec, QCfile, NULL);
2371 specified_data = image_spec_value (img->spec, QCdata, NULL);
2373 if (NILP (specified_data))
2375 /* Read from a file */
2376 Lisp_Object file;
2377 FSSpec fss;
2379 err = find_image_fsspec (specified_file, &file, &fss);
2380 if (err != noErr)
2382 if (err == fnfErr)
2383 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2384 else
2385 image_error ("Cannot open `%s'", file, Qnil);
2386 return 0;
2388 return image_load_qt_1 (f, img, type, &fss, NULL);
2390 else
2392 /* Memory source! */
2393 int success_p;
2394 Handle dh;
2396 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
2397 if (err != noErr)
2399 image_error ("Cannot allocate data handle for `%s'",
2400 img->spec, Qnil);
2401 return 0;
2403 success_p = image_load_qt_1 (f, img, type, NULL, dh);
2404 DisposeHandle (dh);
2405 return success_p;
2410 #ifdef MAC_OSX
2411 /* Load a PNG/JPEG image using Quartz 2D decoding routines.
2412 CGImageCreateWithPNGDataProvider is provided after Mac OS X 10.2.
2413 So don't use this function directly but determine at runtime
2414 whether it exists. */
2415 typedef CGImageRef (*CGImageCreateWithPNGDataProviderProcType)
2416 (CGDataProviderRef, const float [], bool, CGColorRenderingIntent);
2417 static CGImageCreateWithPNGDataProviderProcType MyCGImageCreateWithPNGDataProvider;
2420 static void
2421 init_image_func_pointer ()
2423 if (NSIsSymbolNameDefined ("_CGImageCreateWithPNGDataProvider"))
2425 MyCGImageCreateWithPNGDataProvider
2426 = (CGImageCreateWithPNGDataProviderProcType)
2427 NSAddressOfSymbol (NSLookupAndBindSymbol
2428 ("_CGImageCreateWithPNGDataProvider"));
2430 else
2431 MyCGImageCreateWithPNGDataProvider = NULL;
2435 static int
2436 image_load_quartz2d (f, img, png_p)
2437 struct frame *f;
2438 struct image *img;
2439 int png_p;
2441 Lisp_Object file, specified_file;
2442 Lisp_Object specified_data, specified_bg;
2443 struct gcpro gcpro1;
2444 CGDataProviderRef source;
2445 CGImageRef image;
2446 int width, height;
2447 XColor color;
2448 XImagePtr ximg = NULL;
2449 CGContextRef context;
2450 CGRect rectangle;
2452 /* Open the file. */
2453 specified_file = image_spec_value (img->spec, QCfile, NULL);
2454 specified_data = image_spec_value (img->spec, QCdata, NULL);
2456 file = Qnil;
2457 GCPRO1 (file);
2459 if (NILP (specified_data))
2461 CFStringRef path;
2462 CFURLRef url;
2464 file = x_find_image_file (specified_file);
2465 if (!STRINGP (file))
2467 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2468 UNGCPRO;
2469 return 0;
2471 path = cfstring_create_with_string (file);
2472 url = CFURLCreateWithFileSystemPath (NULL, path,
2473 kCFURLPOSIXPathStyle, 0);
2474 CFRelease (path);
2475 source = CGDataProviderCreateWithURL (url);
2476 CFRelease (url);
2478 else
2479 source = CGDataProviderCreateWithData (NULL, SDATA (specified_data),
2480 SBYTES (specified_data), NULL);
2482 if (png_p)
2483 image = (*MyCGImageCreateWithPNGDataProvider) (source, NULL, FALSE,
2484 kCGRenderingIntentDefault);
2485 else
2486 image = CGImageCreateWithJPEGDataProvider (source, NULL, FALSE,
2487 kCGRenderingIntentDefault);
2489 CGDataProviderRelease (source);
2490 if (image == NULL)
2492 UNGCPRO;
2493 image_error ("Error reading image `%s'", img->spec, Qnil);
2494 return 0;
2497 if (png_p)
2499 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2500 if (!STRINGP (specified_bg) ||
2501 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2503 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2504 color.red = RED16_FROM_ULONG (color.pixel);
2505 color.green = GREEN16_FROM_ULONG (color.pixel);
2506 color.blue = BLUE16_FROM_ULONG (color.pixel);
2509 width = img->width = CGImageGetWidth (image);
2510 height = img->height = CGImageGetHeight (image);
2511 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2513 CGImageRelease (image);
2514 UNGCPRO;
2515 return 0;
2517 rectangle = CGRectMake (0, 0, width, height);
2518 QDBeginCGContext (ximg, &context);
2519 if (png_p)
2521 CGContextSetRGBFillColor (context, color.red / 65535.0,
2522 color.green / 65535.0,
2523 color.blue / 65535.0, 1.0);
2524 CGContextFillRect (context, rectangle);
2526 CGContextDrawImage (context, rectangle, image);
2527 QDEndCGContext (ximg, &context);
2528 CGImageRelease (image);
2530 /* Maybe fill in the background field while we have ximg handy. */
2531 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2532 IMAGE_BACKGROUND (img, f, ximg);
2534 /* Put the image into the pixmap. */
2535 x_put_x_image (f, ximg, img->pixmap, width, height);
2536 x_destroy_x_image (ximg);
2537 UNGCPRO;
2538 return 1;
2540 #endif
2542 #endif /* MAC_OS */
2545 /***********************************************************************
2546 XBM images
2547 ***********************************************************************/
2549 static int xbm_scan P_ ((unsigned char **, unsigned char *, char *, int *));
2550 static int xbm_load P_ ((struct frame *f, struct image *img));
2551 static int xbm_load_image P_ ((struct frame *f, struct image *img,
2552 unsigned char *, unsigned char *));
2553 static int xbm_image_p P_ ((Lisp_Object object));
2554 static int xbm_read_bitmap_data P_ ((unsigned char *, unsigned char *,
2555 int *, int *, unsigned char **));
2556 static int xbm_file_p P_ ((Lisp_Object));
2559 /* Indices of image specification fields in xbm_format, below. */
2561 enum xbm_keyword_index
2563 XBM_TYPE,
2564 XBM_FILE,
2565 XBM_WIDTH,
2566 XBM_HEIGHT,
2567 XBM_DATA,
2568 XBM_FOREGROUND,
2569 XBM_BACKGROUND,
2570 XBM_ASCENT,
2571 XBM_MARGIN,
2572 XBM_RELIEF,
2573 XBM_ALGORITHM,
2574 XBM_HEURISTIC_MASK,
2575 XBM_MASK,
2576 XBM_LAST
2579 /* Vector of image_keyword structures describing the format
2580 of valid XBM image specifications. */
2582 static struct image_keyword xbm_format[XBM_LAST] =
2584 {":type", IMAGE_SYMBOL_VALUE, 1},
2585 {":file", IMAGE_STRING_VALUE, 0},
2586 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2587 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2588 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2589 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2590 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2591 {":ascent", IMAGE_ASCENT_VALUE, 0},
2592 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2593 {":relief", IMAGE_INTEGER_VALUE, 0},
2594 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2595 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2596 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2599 /* Structure describing the image type XBM. */
2601 static struct image_type xbm_type =
2603 &Qxbm,
2604 xbm_image_p,
2605 xbm_load,
2606 x_clear_image,
2607 NULL
2610 /* Tokens returned from xbm_scan. */
2612 enum xbm_token
2614 XBM_TK_IDENT = 256,
2615 XBM_TK_NUMBER
2619 /* Return non-zero if OBJECT is a valid XBM-type image specification.
2620 A valid specification is a list starting with the symbol `image'
2621 The rest of the list is a property list which must contain an
2622 entry `:type xbm..
2624 If the specification specifies a file to load, it must contain
2625 an entry `:file FILENAME' where FILENAME is a string.
2627 If the specification is for a bitmap loaded from memory it must
2628 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2629 WIDTH and HEIGHT are integers > 0. DATA may be:
2631 1. a string large enough to hold the bitmap data, i.e. it must
2632 have a size >= (WIDTH + 7) / 8 * HEIGHT
2634 2. a bool-vector of size >= WIDTH * HEIGHT
2636 3. a vector of strings or bool-vectors, one for each line of the
2637 bitmap.
2639 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
2640 may not be specified in this case because they are defined in the
2641 XBM file.
2643 Both the file and data forms may contain the additional entries
2644 `:background COLOR' and `:foreground COLOR'. If not present,
2645 foreground and background of the frame on which the image is
2646 displayed is used. */
2648 static int
2649 xbm_image_p (object)
2650 Lisp_Object object;
2652 struct image_keyword kw[XBM_LAST];
2654 bcopy (xbm_format, kw, sizeof kw);
2655 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2656 return 0;
2658 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2660 if (kw[XBM_FILE].count)
2662 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2663 return 0;
2665 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2667 /* In-memory XBM file. */
2668 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2669 return 0;
2671 else
2673 Lisp_Object data;
2674 int width, height;
2676 /* Entries for `:width', `:height' and `:data' must be present. */
2677 if (!kw[XBM_WIDTH].count
2678 || !kw[XBM_HEIGHT].count
2679 || !kw[XBM_DATA].count)
2680 return 0;
2682 data = kw[XBM_DATA].value;
2683 width = XFASTINT (kw[XBM_WIDTH].value);
2684 height = XFASTINT (kw[XBM_HEIGHT].value);
2686 /* Check type of data, and width and height against contents of
2687 data. */
2688 if (VECTORP (data))
2690 int i;
2692 /* Number of elements of the vector must be >= height. */
2693 if (XVECTOR (data)->size < height)
2694 return 0;
2696 /* Each string or bool-vector in data must be large enough
2697 for one line of the image. */
2698 for (i = 0; i < height; ++i)
2700 Lisp_Object elt = XVECTOR (data)->contents[i];
2702 if (STRINGP (elt))
2704 if (SCHARS (elt)
2705 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2706 return 0;
2708 else if (BOOL_VECTOR_P (elt))
2710 if (XBOOL_VECTOR (elt)->size < width)
2711 return 0;
2713 else
2714 return 0;
2717 else if (STRINGP (data))
2719 if (SCHARS (data)
2720 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2721 return 0;
2723 else if (BOOL_VECTOR_P (data))
2725 if (XBOOL_VECTOR (data)->size < width * height)
2726 return 0;
2728 else
2729 return 0;
2732 return 1;
2736 /* Scan a bitmap file. FP is the stream to read from. Value is
2737 either an enumerator from enum xbm_token, or a character for a
2738 single-character token, or 0 at end of file. If scanning an
2739 identifier, store the lexeme of the identifier in SVAL. If
2740 scanning a number, store its value in *IVAL. */
2742 static int
2743 xbm_scan (s, end, sval, ival)
2744 unsigned char **s, *end;
2745 char *sval;
2746 int *ival;
2748 unsigned int c;
2750 loop:
2752 /* Skip white space. */
2753 while (*s < end && (c = *(*s)++, isspace (c)))
2756 if (*s >= end)
2757 c = 0;
2758 else if (isdigit (c))
2760 int value = 0, digit;
2762 if (c == '0' && *s < end)
2764 c = *(*s)++;
2765 if (c == 'x' || c == 'X')
2767 while (*s < end)
2769 c = *(*s)++;
2770 if (isdigit (c))
2771 digit = c - '0';
2772 else if (c >= 'a' && c <= 'f')
2773 digit = c - 'a' + 10;
2774 else if (c >= 'A' && c <= 'F')
2775 digit = c - 'A' + 10;
2776 else
2777 break;
2778 value = 16 * value + digit;
2781 else if (isdigit (c))
2783 value = c - '0';
2784 while (*s < end
2785 && (c = *(*s)++, isdigit (c)))
2786 value = 8 * value + c - '0';
2789 else
2791 value = c - '0';
2792 while (*s < end
2793 && (c = *(*s)++, isdigit (c)))
2794 value = 10 * value + c - '0';
2797 if (*s < end)
2798 *s = *s - 1;
2799 *ival = value;
2800 c = XBM_TK_NUMBER;
2802 else if (isalpha (c) || c == '_')
2804 *sval++ = c;
2805 while (*s < end
2806 && (c = *(*s)++, (isalnum (c) || c == '_')))
2807 *sval++ = c;
2808 *sval = 0;
2809 if (*s < end)
2810 *s = *s - 1;
2811 c = XBM_TK_IDENT;
2813 else if (c == '/' && **s == '*')
2815 /* C-style comment. */
2816 ++*s;
2817 while (**s && (**s != '*' || *(*s + 1) != '/'))
2818 ++*s;
2819 if (**s)
2821 *s += 2;
2822 goto loop;
2826 return c;
2829 #ifdef HAVE_NTGUI
2831 /* Create a Windows bitmap from X bitmap data. */
2832 static HBITMAP
2833 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2835 static unsigned char swap_nibble[16]
2836 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2837 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2838 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2839 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2840 int i, j, w1, w2;
2841 unsigned char *bits, *p;
2842 HBITMAP bmp;
2844 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2845 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2846 bits = (unsigned char *) alloca (height * w2);
2847 bzero (bits, height * w2);
2848 for (i = 0; i < height; i++)
2850 p = bits + i*w2;
2851 for (j = 0; j < w1; j++)
2853 /* Bitswap XBM bytes to match how Windows does things. */
2854 unsigned char c = *data++;
2855 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2856 | (swap_nibble[(c>>4) & 0xf]));
2859 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2861 return bmp;
2864 static void convert_mono_to_color_image (f, img, foreground, background)
2865 struct frame *f;
2866 struct image *img;
2867 COLORREF foreground, background;
2869 HDC hdc, old_img_dc, new_img_dc;
2870 HGDIOBJ old_prev, new_prev;
2871 HBITMAP new_pixmap;
2873 hdc = get_frame_dc (f);
2874 old_img_dc = CreateCompatibleDC (hdc);
2875 new_img_dc = CreateCompatibleDC (hdc);
2876 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2877 release_frame_dc (f, hdc);
2878 old_prev = SelectObject (old_img_dc, img->pixmap);
2879 new_prev = SelectObject (new_img_dc, new_pixmap);
2880 SetTextColor (new_img_dc, foreground);
2881 SetBkColor (new_img_dc, background);
2883 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2884 0, 0, SRCCOPY);
2886 SelectObject (old_img_dc, old_prev);
2887 SelectObject (new_img_dc, new_prev);
2888 DeleteDC (old_img_dc);
2889 DeleteDC (new_img_dc);
2890 DeleteObject (img->pixmap);
2891 if (new_pixmap == 0)
2892 fprintf (stderr, "Failed to convert image to color.\n");
2893 else
2894 img->pixmap = new_pixmap;
2897 #define XBM_BIT_SHUFFLE(b) (~(b))
2899 #else
2901 #define XBM_BIT_SHUFFLE(b) (b)
2903 #endif /* HAVE_NTGUI */
2906 static void
2907 Create_Pixmap_From_Bitmap_Data(f, img, data, fg, bg, non_default_colors)
2908 struct frame *f;
2909 struct image *img;
2910 char *data;
2911 RGB_PIXEL_COLOR fg, bg;
2912 int non_default_colors;
2914 #ifdef HAVE_NTGUI
2915 img->pixmap
2916 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2918 /* If colors were specified, transfer the bitmap to a color one. */
2919 if (non_default_colors)
2920 convert_mono_to_color_image (f, img, fg, bg);
2921 #else
2922 img->pixmap
2923 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2924 FRAME_X_WINDOW (f),
2925 data,
2926 img->width, img->height,
2927 fg, bg,
2928 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2929 #endif /* HAVE_NTGUI */
2934 /* Replacement for XReadBitmapFileData which isn't available under old
2935 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2936 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2937 the image. Return in *DATA the bitmap data allocated with xmalloc.
2938 Value is non-zero if successful. DATA null means just test if
2939 CONTENTS looks like an in-memory XBM file. */
2941 static int
2942 xbm_read_bitmap_data (contents, end, width, height, data)
2943 unsigned char *contents, *end;
2944 int *width, *height;
2945 unsigned char **data;
2947 unsigned char *s = contents;
2948 char buffer[BUFSIZ];
2949 int padding_p = 0;
2950 int v10 = 0;
2951 int bytes_per_line, i, nbytes;
2952 unsigned char *p;
2953 int value;
2954 int LA1;
2956 #define match() \
2957 LA1 = xbm_scan (&s, end, buffer, &value)
2959 #define expect(TOKEN) \
2960 if (LA1 != (TOKEN)) \
2961 goto failure; \
2962 else \
2963 match ()
2965 #define expect_ident(IDENT) \
2966 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2967 match (); \
2968 else \
2969 goto failure
2971 *width = *height = -1;
2972 if (data)
2973 *data = NULL;
2974 LA1 = xbm_scan (&s, end, buffer, &value);
2976 /* Parse defines for width, height and hot-spots. */
2977 while (LA1 == '#')
2979 match ();
2980 expect_ident ("define");
2981 expect (XBM_TK_IDENT);
2983 if (LA1 == XBM_TK_NUMBER);
2985 char *p = strrchr (buffer, '_');
2986 p = p ? p + 1 : buffer;
2987 if (strcmp (p, "width") == 0)
2988 *width = value;
2989 else if (strcmp (p, "height") == 0)
2990 *height = value;
2992 expect (XBM_TK_NUMBER);
2995 if (*width < 0 || *height < 0)
2996 goto failure;
2997 else if (data == NULL)
2998 goto success;
3000 /* Parse bits. Must start with `static'. */
3001 expect_ident ("static");
3002 if (LA1 == XBM_TK_IDENT)
3004 if (strcmp (buffer, "unsigned") == 0)
3006 match ();
3007 expect_ident ("char");
3009 else if (strcmp (buffer, "short") == 0)
3011 match ();
3012 v10 = 1;
3013 if (*width % 16 && *width % 16 < 9)
3014 padding_p = 1;
3016 else if (strcmp (buffer, "char") == 0)
3017 match ();
3018 else
3019 goto failure;
3021 else
3022 goto failure;
3024 expect (XBM_TK_IDENT);
3025 expect ('[');
3026 expect (']');
3027 expect ('=');
3028 expect ('{');
3030 bytes_per_line = (*width + 7) / 8 + padding_p;
3031 nbytes = bytes_per_line * *height;
3032 p = *data = (unsigned char *) xmalloc (nbytes);
3034 if (v10)
3036 for (i = 0; i < nbytes; i += 2)
3038 int val = value;
3039 expect (XBM_TK_NUMBER);
3041 *p++ = XBM_BIT_SHUFFLE (val);
3042 if (!padding_p || ((i + 2) % bytes_per_line))
3043 *p++ = XBM_BIT_SHUFFLE (value >> 8);
3045 if (LA1 == ',' || LA1 == '}')
3046 match ();
3047 else
3048 goto failure;
3051 else
3053 for (i = 0; i < nbytes; ++i)
3055 int val = value;
3056 expect (XBM_TK_NUMBER);
3058 *p++ = XBM_BIT_SHUFFLE (val);
3060 if (LA1 == ',' || LA1 == '}')
3061 match ();
3062 else
3063 goto failure;
3067 success:
3068 return 1;
3070 failure:
3072 if (data && *data)
3074 xfree (*data);
3075 *data = NULL;
3077 return 0;
3079 #undef match
3080 #undef expect
3081 #undef expect_ident
3085 /* Load XBM image IMG which will be displayed on frame F from buffer
3086 CONTENTS. END is the end of the buffer. Value is non-zero if
3087 successful. */
3089 static int
3090 xbm_load_image (f, img, contents, end)
3091 struct frame *f;
3092 struct image *img;
3093 unsigned char *contents, *end;
3095 int rc;
3096 unsigned char *data;
3097 int success_p = 0;
3099 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
3100 if (rc)
3102 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3103 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3104 int non_default_colors = 0;
3105 Lisp_Object value;
3107 xassert (img->width > 0 && img->height > 0);
3109 /* Get foreground and background colors, maybe allocate colors. */
3110 value = image_spec_value (img->spec, QCforeground, NULL);
3111 if (!NILP (value))
3113 foreground = x_alloc_image_color (f, img, value, foreground);
3114 non_default_colors = 1;
3116 value = image_spec_value (img->spec, QCbackground, NULL);
3117 if (!NILP (value))
3119 background = x_alloc_image_color (f, img, value, background);
3120 img->background = background;
3121 img->background_valid = 1;
3122 non_default_colors = 1;
3125 Create_Pixmap_From_Bitmap_Data (f, img, data,
3126 foreground, background,
3127 non_default_colors);
3128 xfree (data);
3130 if (img->pixmap == NO_PIXMAP)
3132 x_clear_image (f, img);
3133 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
3135 else
3136 success_p = 1;
3138 else
3139 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3141 return success_p;
3145 /* Value is non-zero if DATA looks like an in-memory XBM file. */
3147 static int
3148 xbm_file_p (data)
3149 Lisp_Object data;
3151 int w, h;
3152 return (STRINGP (data)
3153 && xbm_read_bitmap_data (SDATA (data),
3154 (SDATA (data)
3155 + SBYTES (data)),
3156 &w, &h, NULL));
3160 /* Fill image IMG which is used on frame F with pixmap data. Value is
3161 non-zero if successful. */
3163 static int
3164 xbm_load (f, img)
3165 struct frame *f;
3166 struct image *img;
3168 int success_p = 0;
3169 Lisp_Object file_name;
3171 xassert (xbm_image_p (img->spec));
3173 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3174 file_name = image_spec_value (img->spec, QCfile, NULL);
3175 if (STRINGP (file_name))
3177 Lisp_Object file;
3178 unsigned char *contents;
3179 int size;
3180 struct gcpro gcpro1;
3182 file = x_find_image_file (file_name);
3183 GCPRO1 (file);
3184 if (!STRINGP (file))
3186 image_error ("Cannot find image file `%s'", file_name, Qnil);
3187 UNGCPRO;
3188 return 0;
3191 contents = slurp_file (SDATA (file), &size);
3192 if (contents == NULL)
3194 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3195 UNGCPRO;
3196 return 0;
3199 success_p = xbm_load_image (f, img, contents, contents + size);
3200 UNGCPRO;
3202 else
3204 struct image_keyword fmt[XBM_LAST];
3205 Lisp_Object data;
3206 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3207 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3208 int non_default_colors = 0;
3209 char *bits;
3210 int parsed_p;
3211 int in_memory_file_p = 0;
3213 /* See if data looks like an in-memory XBM file. */
3214 data = image_spec_value (img->spec, QCdata, NULL);
3215 in_memory_file_p = xbm_file_p (data);
3217 /* Parse the image specification. */
3218 bcopy (xbm_format, fmt, sizeof fmt);
3219 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3220 xassert (parsed_p);
3222 /* Get specified width, and height. */
3223 if (!in_memory_file_p)
3225 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3226 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3227 xassert (img->width > 0 && img->height > 0);
3230 /* Get foreground and background colors, maybe allocate colors. */
3231 if (fmt[XBM_FOREGROUND].count
3232 && STRINGP (fmt[XBM_FOREGROUND].value))
3234 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3235 foreground);
3236 non_default_colors = 1;
3239 if (fmt[XBM_BACKGROUND].count
3240 && STRINGP (fmt[XBM_BACKGROUND].value))
3242 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3243 background);
3244 non_default_colors = 1;
3247 if (in_memory_file_p)
3248 success_p = xbm_load_image (f, img, SDATA (data),
3249 (SDATA (data)
3250 + SBYTES (data)));
3251 else
3253 if (VECTORP (data))
3255 int i;
3256 char *p;
3257 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3259 p = bits = (char *) alloca (nbytes * img->height);
3260 for (i = 0; i < img->height; ++i, p += nbytes)
3262 Lisp_Object line = XVECTOR (data)->contents[i];
3263 if (STRINGP (line))
3264 bcopy (SDATA (line), p, nbytes);
3265 else
3266 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
3269 else if (STRINGP (data))
3270 bits = SDATA (data);
3271 else
3272 bits = XBOOL_VECTOR (data)->data;
3274 /* Create the pixmap. */
3276 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3277 foreground, background,
3278 non_default_colors);
3279 if (img->pixmap)
3280 success_p = 1;
3281 else
3283 image_error ("Unable to create pixmap for XBM image `%s'",
3284 img->spec, Qnil);
3285 x_clear_image (f, img);
3290 return success_p;
3295 /***********************************************************************
3296 XPM images
3297 ***********************************************************************/
3299 #if defined (HAVE_XPM) || defined (MAC_OS)
3301 static int xpm_image_p P_ ((Lisp_Object object));
3302 static int xpm_load P_ ((struct frame *f, struct image *img));
3303 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
3305 #endif /* HAVE_XPM || MAC_OS */
3307 #ifdef HAVE_XPM
3308 #ifdef HAVE_NTGUI
3309 /* Indicate to xpm.h that we don't have Xlib. */
3310 #define FOR_MSW
3311 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3312 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3313 #define XColor xpm_XColor
3314 #define XImage xpm_XImage
3315 #define Display xpm_Display
3316 #define PIXEL_ALREADY_TYPEDEFED
3317 #include "X11/xpm.h"
3318 #undef FOR_MSW
3319 #undef XColor
3320 #undef XImage
3321 #undef Display
3322 #undef PIXEL_ALREADY_TYPEDEFED
3323 #else
3324 #include "X11/xpm.h"
3325 #endif /* HAVE_NTGUI */
3326 #endif /* HAVE_XPM */
3328 #if defined (HAVE_XPM) || defined (MAC_OS)
3329 /* The symbol `xpm' identifying XPM-format images. */
3331 Lisp_Object Qxpm;
3333 /* Indices of image specification fields in xpm_format, below. */
3335 enum xpm_keyword_index
3337 XPM_TYPE,
3338 XPM_FILE,
3339 XPM_DATA,
3340 XPM_ASCENT,
3341 XPM_MARGIN,
3342 XPM_RELIEF,
3343 XPM_ALGORITHM,
3344 XPM_HEURISTIC_MASK,
3345 XPM_MASK,
3346 XPM_COLOR_SYMBOLS,
3347 XPM_BACKGROUND,
3348 XPM_LAST
3351 /* Vector of image_keyword structures describing the format
3352 of valid XPM image specifications. */
3354 static struct image_keyword xpm_format[XPM_LAST] =
3356 {":type", IMAGE_SYMBOL_VALUE, 1},
3357 {":file", IMAGE_STRING_VALUE, 0},
3358 {":data", IMAGE_STRING_VALUE, 0},
3359 {":ascent", IMAGE_ASCENT_VALUE, 0},
3360 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3361 {":relief", IMAGE_INTEGER_VALUE, 0},
3362 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3363 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3364 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3365 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3366 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3369 /* Structure describing the image type XPM. */
3371 static struct image_type xpm_type =
3373 &Qxpm,
3374 xpm_image_p,
3375 xpm_load,
3376 x_clear_image,
3377 NULL
3380 #ifdef HAVE_X_WINDOWS
3382 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3383 functions for allocating image colors. Our own functions handle
3384 color allocation failures more gracefully than the ones on the XPM
3385 lib. */
3387 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3388 #define ALLOC_XPM_COLORS
3389 #endif
3390 #endif /* HAVE_X_WINDOWS */
3392 #ifdef ALLOC_XPM_COLORS
3394 static void xpm_init_color_cache P_ ((struct frame *, XpmAttributes *));
3395 static void xpm_free_color_cache P_ ((void));
3396 static int xpm_lookup_color P_ ((struct frame *, char *, XColor *));
3397 static int xpm_color_bucket P_ ((char *));
3398 static struct xpm_cached_color *xpm_cache_color P_ ((struct frame *, char *,
3399 XColor *, int));
3401 /* An entry in a hash table used to cache color definitions of named
3402 colors. This cache is necessary to speed up XPM image loading in
3403 case we do color allocations ourselves. Without it, we would need
3404 a call to XParseColor per pixel in the image. */
3406 struct xpm_cached_color
3408 /* Next in collision chain. */
3409 struct xpm_cached_color *next;
3411 /* Color definition (RGB and pixel color). */
3412 XColor color;
3414 /* Color name. */
3415 char name[1];
3418 /* The hash table used for the color cache, and its bucket vector
3419 size. */
3421 #define XPM_COLOR_CACHE_BUCKETS 1001
3422 struct xpm_cached_color **xpm_color_cache;
3424 /* Initialize the color cache. */
3426 static void
3427 xpm_init_color_cache (f, attrs)
3428 struct frame *f;
3429 XpmAttributes *attrs;
3431 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3432 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3433 memset (xpm_color_cache, 0, nbytes);
3434 init_color_table ();
3436 if (attrs->valuemask & XpmColorSymbols)
3438 int i;
3439 XColor color;
3441 for (i = 0; i < attrs->numsymbols; ++i)
3442 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3443 attrs->colorsymbols[i].value, &color))
3445 color.pixel = lookup_rgb_color (f, color.red, color.green,
3446 color.blue);
3447 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3452 /* Free the color cache. */
3454 static void
3455 xpm_free_color_cache ()
3457 struct xpm_cached_color *p, *next;
3458 int i;
3460 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3461 for (p = xpm_color_cache[i]; p; p = next)
3463 next = p->next;
3464 xfree (p);
3467 xfree (xpm_color_cache);
3468 xpm_color_cache = NULL;
3469 free_color_table ();
3472 /* Return the bucket index for color named COLOR_NAME in the color
3473 cache. */
3475 static int
3476 xpm_color_bucket (color_name)
3477 char *color_name;
3479 unsigned h = 0;
3480 char *s;
3482 for (s = color_name; *s; ++s)
3483 h = (h << 2) ^ *s;
3484 return h %= XPM_COLOR_CACHE_BUCKETS;
3488 /* On frame F, cache values COLOR for color with name COLOR_NAME.
3489 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3490 entry added. */
3492 static struct xpm_cached_color *
3493 xpm_cache_color (f, color_name, color, bucket)
3494 struct frame *f;
3495 char *color_name;
3496 XColor *color;
3497 int bucket;
3499 size_t nbytes;
3500 struct xpm_cached_color *p;
3502 if (bucket < 0)
3503 bucket = xpm_color_bucket (color_name);
3505 nbytes = sizeof *p + strlen (color_name);
3506 p = (struct xpm_cached_color *) xmalloc (nbytes);
3507 strcpy (p->name, color_name);
3508 p->color = *color;
3509 p->next = xpm_color_cache[bucket];
3510 xpm_color_cache[bucket] = p;
3511 return p;
3514 /* Look up color COLOR_NAME for frame F in the color cache. If found,
3515 return the cached definition in *COLOR. Otherwise, make a new
3516 entry in the cache and allocate the color. Value is zero if color
3517 allocation failed. */
3519 static int
3520 xpm_lookup_color (f, color_name, color)
3521 struct frame *f;
3522 char *color_name;
3523 XColor *color;
3525 struct xpm_cached_color *p;
3526 int h = xpm_color_bucket (color_name);
3528 for (p = xpm_color_cache[h]; p; p = p->next)
3529 if (strcmp (p->name, color_name) == 0)
3530 break;
3532 if (p != NULL)
3533 *color = p->color;
3534 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3535 color_name, color))
3537 color->pixel = lookup_rgb_color (f, color->red, color->green,
3538 color->blue);
3539 p = xpm_cache_color (f, color_name, color, h);
3541 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3542 with transparency, and it's useful. */
3543 else if (strcmp ("opaque", color_name) == 0)
3545 bzero (color, sizeof (XColor)); /* Is this necessary/correct? */
3546 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3547 p = xpm_cache_color (f, color_name, color, h);
3550 return p != NULL;
3554 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3555 CLOSURE is a pointer to the frame on which we allocate the
3556 color. Return in *COLOR the allocated color. Value is non-zero
3557 if successful. */
3559 static int
3560 xpm_alloc_color (dpy, cmap, color_name, color, closure)
3561 Display *dpy;
3562 Colormap cmap;
3563 char *color_name;
3564 XColor *color;
3565 void *closure;
3567 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3571 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3572 is a pointer to the frame on which we allocate the color. Value is
3573 non-zero if successful. */
3575 static int
3576 xpm_free_colors (dpy, cmap, pixels, npixels, closure)
3577 Display *dpy;
3578 Colormap cmap;
3579 Pixel *pixels;
3580 int npixels;
3581 void *closure;
3583 return 1;
3586 #endif /* ALLOC_XPM_COLORS */
3589 #ifdef HAVE_NTGUI
3591 /* XPM library details. */
3593 DEF_IMGLIB_FN (XpmFreeAttributes);
3594 DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
3595 DEF_IMGLIB_FN (XpmReadFileToImage);
3596 DEF_IMGLIB_FN (XImageFree);
3598 static int
3599 init_xpm_functions (Lisp_Object libraries)
3601 HMODULE library;
3603 if (!(library = w32_delayed_load (libraries, Qxpm)))
3604 return 0;
3606 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3607 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3608 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3609 LOAD_IMGLIB_FN (library, XImageFree);
3610 return 1;
3613 #endif /* HAVE_NTGUI */
3616 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3617 for XPM images. Such a list must consist of conses whose car and
3618 cdr are strings. */
3620 static int
3621 xpm_valid_color_symbols_p (color_symbols)
3622 Lisp_Object color_symbols;
3624 while (CONSP (color_symbols))
3626 Lisp_Object sym = XCAR (color_symbols);
3627 if (!CONSP (sym)
3628 || !STRINGP (XCAR (sym))
3629 || !STRINGP (XCDR (sym)))
3630 break;
3631 color_symbols = XCDR (color_symbols);
3634 return NILP (color_symbols);
3638 /* Value is non-zero if OBJECT is a valid XPM image specification. */
3640 static int
3641 xpm_image_p (object)
3642 Lisp_Object object;
3644 struct image_keyword fmt[XPM_LAST];
3645 bcopy (xpm_format, fmt, sizeof fmt);
3646 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3647 /* Either `:file' or `:data' must be present. */
3648 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3649 /* Either no `:color-symbols' or it's a list of conses
3650 whose car and cdr are strings. */
3651 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3652 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3655 #endif /* HAVE_XPM || MAC_OS */
3657 /* Load image IMG which will be displayed on frame F. Value is
3658 non-zero if successful. */
3660 #ifdef HAVE_XPM
3662 static int
3663 xpm_load (f, img)
3664 struct frame *f;
3665 struct image *img;
3667 int rc;
3668 XpmAttributes attrs;
3669 Lisp_Object specified_file, color_symbols;
3670 #ifdef HAVE_NTGUI
3671 HDC hdc;
3672 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3673 #endif /* HAVE_NTGUI */
3675 /* Configure the XPM lib. Use the visual of frame F. Allocate
3676 close colors. Return colors allocated. */
3677 bzero (&attrs, sizeof attrs);
3679 #ifndef HAVE_NTGUI
3680 attrs.visual = FRAME_X_VISUAL (f);
3681 attrs.colormap = FRAME_X_COLORMAP (f);
3682 attrs.valuemask |= XpmVisual;
3683 attrs.valuemask |= XpmColormap;
3684 #endif /* HAVE_NTGUI */
3686 #ifdef ALLOC_XPM_COLORS
3687 /* Allocate colors with our own functions which handle
3688 failing color allocation more gracefully. */
3689 attrs.color_closure = f;
3690 attrs.alloc_color = xpm_alloc_color;
3691 attrs.free_colors = xpm_free_colors;
3692 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3693 #else /* not ALLOC_XPM_COLORS */
3694 /* Let the XPM lib allocate colors. */
3695 attrs.valuemask |= XpmReturnAllocPixels;
3696 #ifdef XpmAllocCloseColors
3697 attrs.alloc_close_colors = 1;
3698 attrs.valuemask |= XpmAllocCloseColors;
3699 #else /* not XpmAllocCloseColors */
3700 attrs.closeness = 600;
3701 attrs.valuemask |= XpmCloseness;
3702 #endif /* not XpmAllocCloseColors */
3703 #endif /* ALLOC_XPM_COLORS */
3705 /* If image specification contains symbolic color definitions, add
3706 these to `attrs'. */
3707 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3708 if (CONSP (color_symbols))
3710 Lisp_Object tail;
3711 XpmColorSymbol *xpm_syms;
3712 int i, size;
3714 attrs.valuemask |= XpmColorSymbols;
3716 /* Count number of symbols. */
3717 attrs.numsymbols = 0;
3718 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3719 ++attrs.numsymbols;
3721 /* Allocate an XpmColorSymbol array. */
3722 size = attrs.numsymbols * sizeof *xpm_syms;
3723 xpm_syms = (XpmColorSymbol *) alloca (size);
3724 bzero (xpm_syms, size);
3725 attrs.colorsymbols = xpm_syms;
3727 /* Fill the color symbol array. */
3728 for (tail = color_symbols, i = 0;
3729 CONSP (tail);
3730 ++i, tail = XCDR (tail))
3732 Lisp_Object name = XCAR (XCAR (tail));
3733 Lisp_Object color = XCDR (XCAR (tail));
3734 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3735 strcpy (xpm_syms[i].name, SDATA (name));
3736 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3737 strcpy (xpm_syms[i].value, SDATA (color));
3741 /* Create a pixmap for the image, either from a file, or from a
3742 string buffer containing data in the same format as an XPM file. */
3743 #ifdef ALLOC_XPM_COLORS
3744 xpm_init_color_cache (f, &attrs);
3745 #endif
3747 specified_file = image_spec_value (img->spec, QCfile, NULL);
3749 #ifdef HAVE_NTGUI
3751 HDC frame_dc = get_frame_dc (f);
3752 hdc = CreateCompatibleDC (frame_dc);
3753 release_frame_dc (f, frame_dc);
3755 #endif /* HAVE_NTGUI */
3757 if (STRINGP (specified_file))
3759 Lisp_Object file = x_find_image_file (specified_file);
3760 if (!STRINGP (file))
3762 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3763 return 0;
3766 #ifdef HAVE_NTGUI
3767 /* XpmReadFileToPixmap is not available in the Windows port of
3768 libxpm. But XpmReadFileToImage almost does what we want. */
3769 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3770 &xpm_image, &xpm_mask,
3771 &attrs);
3772 #else
3773 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3774 SDATA (file), &img->pixmap, &img->mask,
3775 &attrs);
3776 #endif /* HAVE_NTGUI */
3778 else
3780 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3781 #ifdef HAVE_NTGUI
3782 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3783 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3784 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3785 &xpm_image, &xpm_mask,
3786 &attrs);
3787 #else
3788 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3789 SDATA (buffer),
3790 &img->pixmap, &img->mask,
3791 &attrs);
3792 #endif /* HAVE_NTGUI */
3795 if (rc == XpmSuccess)
3797 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3798 img->colors = colors_in_color_table (&img->ncolors);
3799 #else /* not ALLOC_XPM_COLORS */
3800 int i;
3802 #ifdef HAVE_NTGUI
3803 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3804 plus some duplicate attributes. */
3805 if (xpm_image && xpm_image->bitmap)
3807 img->pixmap = xpm_image->bitmap;
3808 /* XImageFree in libXpm frees XImage struct without destroying
3809 the bitmap, which is what we want. */
3810 fn_XImageFree (xpm_image);
3812 if (xpm_mask && xpm_mask->bitmap)
3814 /* The mask appears to be inverted compared with what we expect.
3815 TODO: invert our expectations. See other places where we
3816 have to invert bits because our idea of masks is backwards. */
3817 HGDIOBJ old_obj;
3818 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3820 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3821 SelectObject (hdc, old_obj);
3823 img->mask = xpm_mask->bitmap;
3824 fn_XImageFree (xpm_mask);
3825 DeleteDC (hdc);
3828 DeleteDC (hdc);
3829 #endif /* HAVE_NTGUI */
3831 /* Remember allocated colors. */
3832 img->ncolors = attrs.nalloc_pixels;
3833 img->colors = (unsigned long *) xmalloc (img->ncolors
3834 * sizeof *img->colors);
3835 for (i = 0; i < attrs.nalloc_pixels; ++i)
3837 img->colors[i] = attrs.alloc_pixels[i];
3838 #ifdef DEBUG_X_COLORS
3839 register_color (img->colors[i]);
3840 #endif
3842 #endif /* not ALLOC_XPM_COLORS */
3844 img->width = attrs.width;
3845 img->height = attrs.height;
3846 xassert (img->width > 0 && img->height > 0);
3848 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3849 #ifdef HAVE_NTGUI
3850 fn_XpmFreeAttributes (&attrs);
3851 #else
3852 XpmFreeAttributes (&attrs);
3853 #endif /* HAVE_NTGUI */
3855 else
3857 #ifdef HAVE_NTGUI
3858 DeleteDC (hdc);
3859 #endif /* HAVE_NTGUI */
3861 switch (rc)
3863 case XpmOpenFailed:
3864 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3865 break;
3867 case XpmFileInvalid:
3868 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3869 break;
3871 case XpmNoMemory:
3872 image_error ("Out of memory (%s)", img->spec, Qnil);
3873 break;
3875 case XpmColorFailed:
3876 image_error ("Color allocation error (%s)", img->spec, Qnil);
3877 break;
3879 default:
3880 image_error ("Unknown error (%s)", img->spec, Qnil);
3881 break;
3885 #ifdef ALLOC_XPM_COLORS
3886 xpm_free_color_cache ();
3887 #endif
3888 return rc == XpmSuccess;
3891 #endif /* HAVE_XPM */
3893 #ifdef MAC_OS
3895 /* XPM support functions for Mac OS where libxpm is not available.
3896 Only XPM version 3 (without any extensions) is supported. */
3898 static int xpm_scan P_ ((unsigned char **, unsigned char *,
3899 unsigned char **, int *));
3900 static Lisp_Object xpm_make_color_table_v
3901 P_ ((void (**) (Lisp_Object, unsigned char *, int, Lisp_Object),
3902 Lisp_Object (**) (Lisp_Object, unsigned char *, int)));
3903 static void xpm_put_color_table_v P_ ((Lisp_Object, unsigned char *,
3904 int, Lisp_Object));
3905 static Lisp_Object xpm_get_color_table_v P_ ((Lisp_Object,
3906 unsigned char *, int));
3907 static Lisp_Object xpm_make_color_table_h
3908 P_ ((void (**) (Lisp_Object, unsigned char *, int, Lisp_Object),
3909 Lisp_Object (**) (Lisp_Object, unsigned char *, int)));
3910 static void xpm_put_color_table_h P_ ((Lisp_Object, unsigned char *,
3911 int, Lisp_Object));
3912 static Lisp_Object xpm_get_color_table_h P_ ((Lisp_Object,
3913 unsigned char *, int));
3914 static int xpm_str_to_color_key P_ ((char *));
3915 static int xpm_load_image P_ ((struct frame *, struct image *,
3916 unsigned char *, unsigned char *));
3918 /* Tokens returned from xpm_scan. */
3920 enum xpm_token
3922 XPM_TK_IDENT = 256,
3923 XPM_TK_STRING,
3924 XPM_TK_EOF
3927 /* Scan an XPM data and return a character (< 256) or a token defined
3928 by enum xpm_token above. *S and END are the start (inclusive) and
3929 the end (exclusive) addresses of the data, respectively. Advance
3930 *S while scanning. If token is either XPM_TK_IDENT or
3931 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3932 length of the corresponding token, respectively. */
3934 static int
3935 xpm_scan (s, end, beg, len)
3936 unsigned char **s, *end, **beg;
3937 int *len;
3939 int c;
3941 while (*s < end)
3943 /* Skip white-space. */
3944 while (*s < end && (c = *(*s)++, isspace (c)))
3947 /* gnus-pointer.xpm uses '-' in its identifier.
3948 sb-dir-plus.xpm uses '+' in its identifier. */
3949 if (isalpha (c) || c == '_' || c == '-' || c == '+')
3951 *beg = *s - 1;
3952 while (*s < end &&
3953 (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3954 ++*s;
3955 *len = *s - *beg;
3956 return XPM_TK_IDENT;
3958 else if (c == '"')
3960 *beg = *s;
3961 while (*s < end && **s != '"')
3962 ++*s;
3963 *len = *s - *beg;
3964 if (*s < end)
3965 ++*s;
3966 return XPM_TK_STRING;
3968 else if (c == '/')
3970 if (*s < end && **s == '*')
3972 /* C-style comment. */
3973 ++*s;
3976 while (*s < end && *(*s)++ != '*')
3979 while (*s < end && **s != '/');
3980 if (*s < end)
3981 ++*s;
3983 else
3984 return c;
3986 else
3987 return c;
3990 return XPM_TK_EOF;
3993 /* Functions for color table lookup in XPM data. A Key is a string
3994 specifying the color of each pixel in XPM data. A value is either
3995 an integer that specifies a pixel color, Qt that specifies
3996 transparency, or Qnil for the unspecified color. If the length of
3997 the key string is one, a vector is used as a table. Otherwise, a
3998 hash table is used. */
4000 static Lisp_Object
4001 xpm_make_color_table_v (put_func, get_func)
4002 void (**put_func) (Lisp_Object, unsigned char *, int, Lisp_Object);
4003 Lisp_Object (**get_func) (Lisp_Object, unsigned char *, int);
4005 *put_func = xpm_put_color_table_v;
4006 *get_func = xpm_get_color_table_v;
4007 return Fmake_vector (make_number (256), Qnil);
4010 static void
4011 xpm_put_color_table_v (color_table, chars_start, chars_len, color)
4012 Lisp_Object color_table;
4013 unsigned char *chars_start;
4014 int chars_len;
4015 Lisp_Object color;
4017 XVECTOR (color_table)->contents[*chars_start] = color;
4020 static Lisp_Object
4021 xpm_get_color_table_v (color_table, chars_start, chars_len)
4022 Lisp_Object color_table;
4023 unsigned char *chars_start;
4024 int chars_len;
4026 return XVECTOR (color_table)->contents[*chars_start];
4029 static Lisp_Object
4030 xpm_make_color_table_h (put_func, get_func)
4031 void (**put_func) (Lisp_Object, unsigned char *, int, Lisp_Object);
4032 Lisp_Object (**get_func) (Lisp_Object, unsigned char *, int);
4034 *put_func = xpm_put_color_table_h;
4035 *get_func = xpm_get_color_table_h;
4036 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
4037 make_float (DEFAULT_REHASH_SIZE),
4038 make_float (DEFAULT_REHASH_THRESHOLD),
4039 Qnil, Qnil, Qnil);
4042 static void
4043 xpm_put_color_table_h (color_table, chars_start, chars_len, color)
4044 Lisp_Object color_table;
4045 unsigned char *chars_start;
4046 int chars_len;
4047 Lisp_Object color;
4049 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4050 unsigned hash_code;
4051 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4053 hash_lookup (table, chars, &hash_code);
4054 hash_put (table, chars, color, hash_code);
4057 static Lisp_Object
4058 xpm_get_color_table_h (color_table, chars_start, chars_len)
4059 Lisp_Object color_table;
4060 unsigned char *chars_start;
4061 int chars_len;
4063 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4064 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
4065 NULL);
4067 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4070 enum xpm_color_key {
4071 XPM_COLOR_KEY_S,
4072 XPM_COLOR_KEY_M,
4073 XPM_COLOR_KEY_G4,
4074 XPM_COLOR_KEY_G,
4075 XPM_COLOR_KEY_C
4078 static char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4080 static int
4081 xpm_str_to_color_key (s)
4082 char *s;
4084 int i;
4086 for (i = 0;
4087 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
4088 i++)
4089 if (strcmp (xpm_color_key_strings[i], s) == 0)
4090 return i;
4091 return -1;
4094 static int
4095 xpm_load_image (f, img, contents, end)
4096 struct frame *f;
4097 struct image *img;
4098 unsigned char *contents, *end;
4100 unsigned char *s = contents, *beg, *str;
4101 unsigned char buffer[BUFSIZ];
4102 int width, height, x, y;
4103 int num_colors, chars_per_pixel;
4104 int len, LA1;
4105 void (*put_color_table) (Lisp_Object, unsigned char *, int, Lisp_Object);
4106 Lisp_Object (*get_color_table) (Lisp_Object, unsigned char *, int);
4107 Lisp_Object frame, color_symbols, color_table;
4108 int best_key, have_mask = 0;
4109 XImagePtr ximg = NULL, mask_img = NULL;
4111 #define match() \
4112 LA1 = xpm_scan (&s, end, &beg, &len)
4114 #define expect(TOKEN) \
4115 if (LA1 != (TOKEN)) \
4116 goto failure; \
4117 else \
4118 match ()
4120 #define expect_ident(IDENT) \
4121 if (LA1 == XPM_TK_IDENT \
4122 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4123 match (); \
4124 else \
4125 goto failure
4127 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4128 goto failure;
4129 s += 9;
4130 match();
4131 expect_ident ("static");
4132 expect_ident ("char");
4133 expect ('*');
4134 expect (XPM_TK_IDENT);
4135 expect ('[');
4136 expect (']');
4137 expect ('=');
4138 expect ('{');
4139 expect (XPM_TK_STRING);
4140 if (len >= BUFSIZ)
4141 goto failure;
4142 memcpy (buffer, beg, len);
4143 buffer[len] = '\0';
4144 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4145 &num_colors, &chars_per_pixel) != 4
4146 || width <= 0 || height <= 0
4147 || num_colors <= 0 || chars_per_pixel <= 0)
4148 goto failure;
4149 expect (',');
4151 XSETFRAME (frame, f);
4152 if (!NILP (Fxw_display_color_p (frame)))
4153 best_key = XPM_COLOR_KEY_C;
4154 else if (!NILP (Fx_display_grayscale_p (frame)))
4155 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4156 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4157 else
4158 best_key = XPM_COLOR_KEY_M;
4160 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4161 if (chars_per_pixel == 1)
4162 color_table = xpm_make_color_table_v (&put_color_table,
4163 &get_color_table);
4164 else
4165 color_table = xpm_make_color_table_h (&put_color_table,
4166 &get_color_table);
4168 while (num_colors-- > 0)
4170 unsigned char *color, *max_color;
4171 int key, next_key, max_key = 0;
4172 Lisp_Object symbol_color = Qnil, color_val;
4173 XColor cdef;
4175 expect (XPM_TK_STRING);
4176 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4177 goto failure;
4178 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4179 buffer[len - chars_per_pixel] = '\0';
4181 str = strtok (buffer, " \t");
4182 if (str == NULL)
4183 goto failure;
4184 key = xpm_str_to_color_key (str);
4185 if (key < 0)
4186 goto failure;
4189 color = strtok (NULL, " \t");
4190 if (color == NULL)
4191 goto failure;
4193 while (str = strtok (NULL, " \t"))
4195 next_key = xpm_str_to_color_key (str);
4196 if (next_key >= 0)
4197 break;
4198 color[strlen (color)] = ' ';
4201 if (key == XPM_COLOR_KEY_S)
4203 if (NILP (symbol_color))
4204 symbol_color = build_string (color);
4206 else if (max_key < key && key <= best_key)
4208 max_key = key;
4209 max_color = color;
4211 key = next_key;
4213 while (str);
4215 color_val = Qnil;
4216 if (!NILP (color_symbols) && !NILP (symbol_color))
4218 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4220 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4221 if (xstricmp (SDATA (XCDR (specified_color)), "None") == 0)
4222 color_val = Qt;
4223 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
4224 &cdef, 0))
4225 color_val = make_number (cdef.pixel);
4227 if (NILP (color_val) && max_key > 0)
4228 if (xstricmp (max_color, "None") == 0)
4229 color_val = Qt;
4230 else if (x_defined_color (f, max_color, &cdef, 0))
4231 color_val = make_number (cdef.pixel);
4232 if (!NILP (color_val))
4233 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4235 expect (',');
4238 if (!x_create_x_image_and_pixmap (f, width, height, 0,
4239 &ximg, &img->pixmap)
4240 || !x_create_x_image_and_pixmap (f, width, height, 1,
4241 &mask_img, &img->mask))
4243 image_error ("Out of memory (%s)", img->spec, Qnil);
4244 goto error;
4247 for (y = 0; y < height; y++)
4249 expect (XPM_TK_STRING);
4250 str = beg;
4251 if (len < width * chars_per_pixel)
4252 goto failure;
4253 for (x = 0; x < width; x++, str += chars_per_pixel)
4255 Lisp_Object color_val =
4256 (*get_color_table) (color_table, str, chars_per_pixel);
4258 XPutPixel (ximg, x, y,
4259 (INTEGERP (color_val) ? XINT (color_val)
4260 : FRAME_FOREGROUND_PIXEL (f)));
4261 XPutPixel (mask_img, x, y,
4262 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4263 : (have_mask = 1, PIX_MASK_RETAIN)));
4265 if (y + 1 < height)
4266 expect (',');
4269 img->width = width;
4270 img->height = height;
4272 x_put_x_image (f, ximg, img->pixmap, width, height);
4273 x_destroy_x_image (ximg);
4274 if (have_mask)
4276 /* Fill in the background_transparent field while we have the
4277 mask handy. */
4278 image_background_transparent (img, f, mask_img);
4280 x_put_x_image (f, mask_img, img->mask, width, height);
4281 x_destroy_x_image (mask_img);
4283 else
4285 x_destroy_x_image (mask_img);
4286 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4287 img->mask = NO_PIXMAP;
4290 return 1;
4292 failure:
4293 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4294 error:
4295 x_destroy_x_image (ximg);
4296 x_destroy_x_image (mask_img);
4297 x_clear_image (f, img);
4298 return 0;
4300 #undef match
4301 #undef expect
4302 #undef expect_ident
4305 static int
4306 xpm_load (f, img)
4307 struct frame *f;
4308 struct image *img;
4310 int success_p = 0;
4311 Lisp_Object file_name;
4313 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4314 file_name = image_spec_value (img->spec, QCfile, NULL);
4315 if (STRINGP (file_name))
4317 Lisp_Object file;
4318 unsigned char *contents;
4319 int size;
4320 struct gcpro gcpro1;
4322 file = x_find_image_file (file_name);
4323 GCPRO1 (file);
4324 if (!STRINGP (file))
4326 image_error ("Cannot find image file `%s'", file_name, Qnil);
4327 UNGCPRO;
4328 return 0;
4331 contents = slurp_file (SDATA (file), &size);
4332 if (contents == NULL)
4334 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4335 UNGCPRO;
4336 return 0;
4339 success_p = xpm_load_image (f, img, contents, contents + size);
4340 xfree (contents);
4341 UNGCPRO;
4343 else
4345 Lisp_Object data;
4347 data = image_spec_value (img->spec, QCdata, NULL);
4348 success_p = xpm_load_image (f, img, SDATA (data),
4349 SDATA (data) + SBYTES (data));
4352 return success_p;
4355 #endif /* MAC_OS */
4359 /***********************************************************************
4360 Color table
4361 ***********************************************************************/
4363 #ifdef COLOR_TABLE_SUPPORT
4365 /* An entry in the color table mapping an RGB color to a pixel color. */
4367 struct ct_color
4369 int r, g, b;
4370 unsigned long pixel;
4372 /* Next in color table collision list. */
4373 struct ct_color *next;
4376 /* The bucket vector size to use. Must be prime. */
4378 #define CT_SIZE 101
4380 /* Value is a hash of the RGB color given by R, G, and B. */
4382 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4384 /* The color hash table. */
4386 struct ct_color **ct_table;
4388 /* Number of entries in the color table. */
4390 int ct_colors_allocated;
4392 /* Initialize the color table. */
4394 static void
4395 init_color_table ()
4397 int size = CT_SIZE * sizeof (*ct_table);
4398 ct_table = (struct ct_color **) xmalloc (size);
4399 bzero (ct_table, size);
4400 ct_colors_allocated = 0;
4404 /* Free memory associated with the color table. */
4406 static void
4407 free_color_table ()
4409 int i;
4410 struct ct_color *p, *next;
4412 for (i = 0; i < CT_SIZE; ++i)
4413 for (p = ct_table[i]; p; p = next)
4415 next = p->next;
4416 xfree (p);
4419 xfree (ct_table);
4420 ct_table = NULL;
4424 /* Value is a pixel color for RGB color R, G, B on frame F. If an
4425 entry for that color already is in the color table, return the
4426 pixel color of that entry. Otherwise, allocate a new color for R,
4427 G, B, and make an entry in the color table. */
4429 static unsigned long
4430 lookup_rgb_color (f, r, g, b)
4431 struct frame *f;
4432 int r, g, b;
4434 unsigned hash = CT_HASH_RGB (r, g, b);
4435 int i = hash % CT_SIZE;
4436 struct ct_color *p;
4437 Display_Info *dpyinfo;
4439 /* Handle TrueColor visuals specially, which improves performance by
4440 two orders of magnitude. Freeing colors on TrueColor visuals is
4441 a nop, and pixel colors specify RGB values directly. See also
4442 the Xlib spec, chapter 3.1. */
4443 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4444 if (dpyinfo->red_bits > 0)
4446 unsigned long pr, pg, pb;
4448 /* Apply gamma-correction like normal color allocation does. */
4449 if (f->gamma)
4451 XColor color;
4452 color.red = r, color.green = g, color.blue = b;
4453 gamma_correct (f, &color);
4454 r = color.red, g = color.green, b = color.blue;
4457 /* Scale down RGB values to the visual's bits per RGB, and shift
4458 them to the right position in the pixel color. Note that the
4459 original RGB values are 16-bit values, as usual in X. */
4460 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4461 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4462 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4464 /* Assemble the pixel color. */
4465 return pr | pg | pb;
4468 for (p = ct_table[i]; p; p = p->next)
4469 if (p->r == r && p->g == g && p->b == b)
4470 break;
4472 if (p == NULL)
4475 #ifdef HAVE_X_WINDOWS
4476 XColor color;
4477 Colormap cmap;
4478 int rc;
4480 color.red = r;
4481 color.green = g;
4482 color.blue = b;
4484 cmap = FRAME_X_COLORMAP (f);
4485 rc = x_alloc_nearest_color (f, cmap, &color);
4486 if (rc)
4488 ++ct_colors_allocated;
4489 p = (struct ct_color *) xmalloc (sizeof *p);
4490 p->r = r;
4491 p->g = g;
4492 p->b = b;
4493 p->pixel = color.pixel;
4494 p->next = ct_table[i];
4495 ct_table[i] = p;
4497 else
4498 return FRAME_FOREGROUND_PIXEL (f);
4500 #else
4501 COLORREF color;
4502 #ifdef HAVE_NTGUI
4503 color = PALETTERGB (r, g, b);
4504 #else
4505 color = RGB_TO_ULONG (r, g, b);
4506 #endif /* HAVE_NTGUI */
4507 ++ct_colors_allocated;
4508 p = (struct ct_color *) xmalloc (sizeof *p);
4509 p->r = r;
4510 p->g = g;
4511 p->b = b;
4512 p->pixel = color;
4513 p->next = ct_table[i];
4514 ct_table[i] = p;
4515 #endif /* HAVE_X_WINDOWS */
4519 return p->pixel;
4523 /* Look up pixel color PIXEL which is used on frame F in the color
4524 table. If not already present, allocate it. Value is PIXEL. */
4526 static unsigned long
4527 lookup_pixel_color (f, pixel)
4528 struct frame *f;
4529 unsigned long pixel;
4531 int i = pixel % CT_SIZE;
4532 struct ct_color *p;
4534 for (p = ct_table[i]; p; p = p->next)
4535 if (p->pixel == pixel)
4536 break;
4538 if (p == NULL)
4540 XColor color;
4541 Colormap cmap;
4542 int rc;
4544 #ifdef HAVE_X_WINDOWS
4545 cmap = FRAME_X_COLORMAP (f);
4546 color.pixel = pixel;
4547 x_query_color (f, &color);
4548 rc = x_alloc_nearest_color (f, cmap, &color);
4549 #else
4550 BLOCK_INPUT;
4551 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4552 color.pixel = pixel;
4553 XQueryColor (NULL, cmap, &color);
4554 rc = x_alloc_nearest_color (f, cmap, &color);
4555 UNBLOCK_INPUT;
4556 #endif /* HAVE_X_WINDOWS */
4558 if (rc)
4560 ++ct_colors_allocated;
4562 p = (struct ct_color *) xmalloc (sizeof *p);
4563 p->r = color.red;
4564 p->g = color.green;
4565 p->b = color.blue;
4566 p->pixel = pixel;
4567 p->next = ct_table[i];
4568 ct_table[i] = p;
4570 else
4571 return FRAME_FOREGROUND_PIXEL (f);
4573 return p->pixel;
4577 /* Value is a vector of all pixel colors contained in the color table,
4578 allocated via xmalloc. Set *N to the number of colors. */
4580 static unsigned long *
4581 colors_in_color_table (n)
4582 int *n;
4584 int i, j;
4585 struct ct_color *p;
4586 unsigned long *colors;
4588 if (ct_colors_allocated == 0)
4590 *n = 0;
4591 colors = NULL;
4593 else
4595 colors = (unsigned long *) xmalloc (ct_colors_allocated
4596 * sizeof *colors);
4597 *n = ct_colors_allocated;
4599 for (i = j = 0; i < CT_SIZE; ++i)
4600 for (p = ct_table[i]; p; p = p->next)
4601 colors[j++] = p->pixel;
4604 return colors;
4607 #else /* COLOR_TABLE_SUPPORT */
4609 static unsigned long
4610 lookup_rgb_color (f, r, g, b)
4611 struct frame *f;
4612 int r, g, b;
4614 unsigned long pixel;
4616 #ifdef MAC_OS
4617 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4618 gamma_correct (f, &pixel);
4619 #endif /* MAC_OS */
4621 #ifdef HAVE_NTGUI
4622 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4623 #endif /* HAVE_NTGUI */
4625 return pixel;
4628 static void
4629 init_color_table ()
4632 #endif /* COLOR_TABLE_SUPPORT */
4635 /***********************************************************************
4636 Algorithms
4637 ***********************************************************************/
4639 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
4640 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
4641 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
4643 #ifdef HAVE_NTGUI
4644 static void XPutPixel (XImagePtr , int, int, COLORREF);
4645 #endif /* HAVE_NTGUI */
4647 /* Non-zero means draw a cross on images having `:conversion
4648 disabled'. */
4650 int cross_disabled_images;
4652 /* Edge detection matrices for different edge-detection
4653 strategies. */
4655 static int emboss_matrix[9] = {
4656 /* x - 1 x x + 1 */
4657 2, -1, 0, /* y - 1 */
4658 -1, 0, 1, /* y */
4659 0, 1, -2 /* y + 1 */
4662 static int laplace_matrix[9] = {
4663 /* x - 1 x x + 1 */
4664 1, 0, 0, /* y - 1 */
4665 0, 0, 0, /* y */
4666 0, 0, -1 /* y + 1 */
4669 /* Value is the intensity of the color whose red/green/blue values
4670 are R, G, and B. */
4672 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4675 /* On frame F, return an array of XColor structures describing image
4676 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4677 non-zero means also fill the red/green/blue members of the XColor
4678 structures. Value is a pointer to the array of XColors structures,
4679 allocated with xmalloc; it must be freed by the caller. */
4681 static XColor *
4682 x_to_xcolors (f, img, rgb_p)
4683 struct frame *f;
4684 struct image *img;
4685 int rgb_p;
4687 int x, y;
4688 XColor *colors, *p;
4689 XImagePtr_or_DC ximg;
4690 #ifdef HAVE_NTGUI
4691 HDC hdc;
4692 HGDIOBJ prev;
4693 #endif /* HAVE_NTGUI */
4695 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4697 #ifndef HAVE_NTGUI
4698 /* Get the X image IMG->pixmap. */
4699 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4700 0, 0, img->width, img->height, ~0, ZPixmap);
4701 #else
4702 /* Load the image into a memory device context. */
4703 hdc = get_frame_dc (f);
4704 ximg = CreateCompatibleDC (hdc);
4705 release_frame_dc (f, hdc);
4706 prev = SelectObject (ximg, img->pixmap);
4707 #endif /* HAVE_NTGUI */
4709 /* Fill the `pixel' members of the XColor array. I wished there
4710 were an easy and portable way to circumvent XGetPixel. */
4711 p = colors;
4712 for (y = 0; y < img->height; ++y)
4714 XColor *row = p;
4716 #ifdef HAVE_X_WINDOWS
4717 for (x = 0; x < img->width; ++x, ++p)
4718 p->pixel = XGetPixel (ximg, x, y);
4719 if (rgb_p)
4720 x_query_colors (f, row, img->width);
4722 #else
4724 for (x = 0; x < img->width; ++x, ++p)
4726 /* W32_TODO: palette support needed here? */
4727 p->pixel = GET_PIXEL (ximg, x, y);
4728 if (rgb_p)
4730 #ifdef MAC_OS
4731 p->red = RED16_FROM_ULONG (p->pixel);
4732 p->green = GREEN16_FROM_ULONG (p->pixel);
4733 p->blue = BLUE16_FROM_ULONG (p->pixel);
4734 #endif /* MAC_OS */
4735 #ifdef HAVE_NTGUI
4736 p->red = 256 * GetRValue (p->pixel);
4737 p->green = 256 * GetGValue (p->pixel);
4738 p->blue = 256 * GetBValue (p->pixel);
4739 #endif /* HAVE_NTGUI */
4742 #endif /* HAVE_X_WINDOWS */
4745 Destroy_Image (ximg, prev);
4747 return colors;
4750 #ifdef HAVE_NTGUI
4752 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4753 created with CreateDIBSection, with the pointer to the bit values
4754 stored in ximg->data. */
4756 static void XPutPixel (ximg, x, y, color)
4757 XImagePtr ximg;
4758 int x, y;
4759 COLORREF color;
4761 int width = ximg->info.bmiHeader.biWidth;
4762 int height = ximg->info.bmiHeader.biHeight;
4763 unsigned char * pixel;
4765 /* True color images. */
4766 if (ximg->info.bmiHeader.biBitCount == 24)
4768 int rowbytes = width * 3;
4769 /* Ensure scanlines are aligned on 4 byte boundaries. */
4770 if (rowbytes % 4)
4771 rowbytes += 4 - (rowbytes % 4);
4773 pixel = ximg->data + y * rowbytes + x * 3;
4774 /* Windows bitmaps are in BGR order. */
4775 *pixel = GetBValue (color);
4776 *(pixel + 1) = GetGValue (color);
4777 *(pixel + 2) = GetRValue (color);
4779 /* Monochrome images. */
4780 else if (ximg->info.bmiHeader.biBitCount == 1)
4782 int rowbytes = width / 8;
4783 /* Ensure scanlines are aligned on 4 byte boundaries. */
4784 if (rowbytes % 4)
4785 rowbytes += 4 - (rowbytes % 4);
4786 pixel = ximg->data + y * rowbytes + x / 8;
4787 /* Filter out palette info. */
4788 if (color & 0x00ffffff)
4789 *pixel = *pixel | (1 << x % 8);
4790 else
4791 *pixel = *pixel & ~(1 << x % 8);
4793 else
4794 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4797 #endif /* HAVE_NTGUI */
4799 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
4800 RGB members are set. F is the frame on which this all happens.
4801 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4803 static void
4804 x_from_xcolors (f, img, colors)
4805 struct frame *f;
4806 struct image *img;
4807 XColor *colors;
4809 int x, y;
4810 XImagePtr oimg;
4811 Pixmap pixmap;
4812 XColor *p;
4814 init_color_table ();
4816 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4817 &oimg, &pixmap);
4818 p = colors;
4819 for (y = 0; y < img->height; ++y)
4820 for (x = 0; x < img->width; ++x, ++p)
4822 unsigned long pixel;
4823 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4824 XPutPixel (oimg, x, y, pixel);
4827 xfree (colors);
4828 x_clear_image_1 (f, img, 1, 0, 1);
4830 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4831 x_destroy_x_image (oimg);
4832 img->pixmap = pixmap;
4833 #ifdef COLOR_TABLE_SUPPORT
4834 img->colors = colors_in_color_table (&img->ncolors);
4835 free_color_table ();
4836 #endif /* COLOR_TABLE_SUPPORT */
4840 /* On frame F, perform edge-detection on image IMG.
4842 MATRIX is a nine-element array specifying the transformation
4843 matrix. See emboss_matrix for an example.
4845 COLOR_ADJUST is a color adjustment added to each pixel of the
4846 outgoing image. */
4848 static void
4849 x_detect_edges (f, img, matrix, color_adjust)
4850 struct frame *f;
4851 struct image *img;
4852 int matrix[9], color_adjust;
4854 XColor *colors = x_to_xcolors (f, img, 1);
4855 XColor *new, *p;
4856 int x, y, i, sum;
4858 for (i = sum = 0; i < 9; ++i)
4859 sum += abs (matrix[i]);
4861 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4863 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4865 for (y = 0; y < img->height; ++y)
4867 p = COLOR (new, 0, y);
4868 p->red = p->green = p->blue = 0xffff/2;
4869 p = COLOR (new, img->width - 1, y);
4870 p->red = p->green = p->blue = 0xffff/2;
4873 for (x = 1; x < img->width - 1; ++x)
4875 p = COLOR (new, x, 0);
4876 p->red = p->green = p->blue = 0xffff/2;
4877 p = COLOR (new, x, img->height - 1);
4878 p->red = p->green = p->blue = 0xffff/2;
4881 for (y = 1; y < img->height - 1; ++y)
4883 p = COLOR (new, 1, y);
4885 for (x = 1; x < img->width - 1; ++x, ++p)
4887 int r, g, b, y1, x1;
4889 r = g = b = i = 0;
4890 for (y1 = y - 1; y1 < y + 2; ++y1)
4891 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
4892 if (matrix[i])
4894 XColor *t = COLOR (colors, x1, y1);
4895 r += matrix[i] * t->red;
4896 g += matrix[i] * t->green;
4897 b += matrix[i] * t->blue;
4900 r = (r / sum + color_adjust) & 0xffff;
4901 g = (g / sum + color_adjust) & 0xffff;
4902 b = (b / sum + color_adjust) & 0xffff;
4903 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4907 xfree (colors);
4908 x_from_xcolors (f, img, new);
4910 #undef COLOR
4914 /* Perform the pre-defined `emboss' edge-detection on image IMG
4915 on frame F. */
4917 static void
4918 x_emboss (f, img)
4919 struct frame *f;
4920 struct image *img;
4922 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4926 /* Transform image IMG which is used on frame F with a Laplace
4927 edge-detection algorithm. The result is an image that can be used
4928 to draw disabled buttons, for example. */
4930 static void
4931 x_laplace (f, img)
4932 struct frame *f;
4933 struct image *img;
4935 x_detect_edges (f, img, laplace_matrix, 45000);
4939 /* Perform edge-detection on image IMG on frame F, with specified
4940 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4942 MATRIX must be either
4944 - a list of at least 9 numbers in row-major form
4945 - a vector of at least 9 numbers
4947 COLOR_ADJUST nil means use a default; otherwise it must be a
4948 number. */
4950 static void
4951 x_edge_detection (f, img, matrix, color_adjust)
4952 struct frame *f;
4953 struct image *img;
4954 Lisp_Object matrix, color_adjust;
4956 int i = 0;
4957 int trans[9];
4959 if (CONSP (matrix))
4961 for (i = 0;
4962 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4963 ++i, matrix = XCDR (matrix))
4964 trans[i] = XFLOATINT (XCAR (matrix));
4966 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4968 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4969 trans[i] = XFLOATINT (AREF (matrix, i));
4972 if (NILP (color_adjust))
4973 color_adjust = make_number (0xffff / 2);
4975 if (i == 9 && NUMBERP (color_adjust))
4976 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
4980 /* Transform image IMG on frame F so that it looks disabled. */
4982 static void
4983 x_disable_image (f, img)
4984 struct frame *f;
4985 struct image *img;
4987 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4988 #ifdef HAVE_NTGUI
4989 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4990 #else
4991 int n_planes = dpyinfo->n_planes;
4992 #endif /* HAVE_NTGUI */
4994 if (n_planes >= 2)
4996 /* Color (or grayscale). Convert to gray, and equalize. Just
4997 drawing such images with a stipple can look very odd, so
4998 we're using this method instead. */
4999 XColor *colors = x_to_xcolors (f, img, 1);
5000 XColor *p, *end;
5001 const int h = 15000;
5002 const int l = 30000;
5004 for (p = colors, end = colors + img->width * img->height;
5005 p < end;
5006 ++p)
5008 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
5009 int i2 = (0xffff - h - l) * i / 0xffff + l;
5010 p->red = p->green = p->blue = i2;
5013 x_from_xcolors (f, img, colors);
5016 /* Draw a cross over the disabled image, if we must or if we
5017 should. */
5018 if (n_planes < 2 || cross_disabled_images)
5020 #ifndef HAVE_NTGUI
5021 Display *dpy = FRAME_X_DISPLAY (f);
5022 GC gc;
5024 #ifdef MAC_OS
5025 #define XCreateGC_pixmap(dpy, pixmap) XCreateGC (dpy, NULL, 0, NULL)
5026 #define MaskForeground(f) PIX_MASK_DRAW
5027 #else
5028 #define XCreateGC_pixmap(dpy, pixmap) XCreateGC (dpy, pixmap, 0, NULL)
5029 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
5030 #endif
5032 gc = XCreateGC_pixmap (dpy, img->pixmap);
5033 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
5034 XDrawLine (dpy, img->pixmap, gc, 0, 0,
5035 img->width - 1, img->height - 1);
5036 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
5037 img->width - 1, 0);
5038 XFreeGC (dpy, gc);
5040 if (img->mask)
5042 gc = XCreateGC_pixmap (dpy, img->mask);
5043 XSetForeground (dpy, gc, MaskForeground (f));
5044 XDrawLine (dpy, img->mask, gc, 0, 0,
5045 img->width - 1, img->height - 1);
5046 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
5047 img->width - 1, 0);
5048 XFreeGC (dpy, gc);
5050 #else
5051 HDC hdc, bmpdc;
5052 HGDIOBJ prev;
5054 hdc = get_frame_dc (f);
5055 bmpdc = CreateCompatibleDC (hdc);
5056 release_frame_dc (f, hdc);
5058 prev = SelectObject (bmpdc, img->pixmap);
5060 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5061 MoveToEx (bmpdc, 0, 0, NULL);
5062 LineTo (bmpdc, img->width - 1, img->height - 1);
5063 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5064 LineTo (bmpdc, img->width - 1, 0);
5066 if (img->mask)
5068 SelectObject (bmpdc, img->mask);
5069 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5070 MoveToEx (bmpdc, 0, 0, NULL);
5071 LineTo (bmpdc, img->width - 1, img->height - 1);
5072 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5073 LineTo (bmpdc, img->width - 1, 0);
5075 SelectObject (bmpdc, prev);
5076 DeleteDC (bmpdc);
5077 #endif /* HAVE_NTGUI */
5082 /* Build a mask for image IMG which is used on frame F. FILE is the
5083 name of an image file, for error messages. HOW determines how to
5084 determine the background color of IMG. If it is a list '(R G B)',
5085 with R, G, and B being integers >= 0, take that as the color of the
5086 background. Otherwise, determine the background color of IMG
5087 heuristically. Value is non-zero if successful. */
5089 static int
5090 x_build_heuristic_mask (f, img, how)
5091 struct frame *f;
5092 struct image *img;
5093 Lisp_Object how;
5095 XImagePtr_or_DC ximg;
5096 #ifndef HAVE_NTGUI
5097 XImagePtr mask_img;
5098 #else
5099 HDC frame_dc;
5100 HGDIOBJ prev;
5101 char *mask_img;
5102 int row_width;
5103 #endif /* HAVE_NTGUI */
5104 int x, y, rc, use_img_background;
5105 unsigned long bg = 0;
5107 if (img->mask)
5109 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
5110 img->mask = NO_PIXMAP;
5111 img->background_transparent_valid = 0;
5114 #ifndef HAVE_NTGUI
5115 /* Create an image and pixmap serving as mask. */
5116 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
5117 &mask_img, &img->mask);
5118 if (!rc)
5119 return 0;
5121 /* Get the X image of IMG->pixmap. */
5122 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
5123 img->width, img->height,
5124 ~0, ZPixmap);
5125 #else
5126 /* Create the bit array serving as mask. */
5127 row_width = (img->width + 7) / 8;
5128 mask_img = xmalloc (row_width * img->height);
5129 bzero (mask_img, row_width * img->height);
5131 /* Create a memory device context for IMG->pixmap. */
5132 frame_dc = get_frame_dc (f);
5133 ximg = CreateCompatibleDC (frame_dc);
5134 release_frame_dc (f, frame_dc);
5135 prev = SelectObject (ximg, img->pixmap);
5136 #endif /* HAVE_NTGUI */
5138 /* Determine the background color of ximg. If HOW is `(R G B)'
5139 take that as color. Otherwise, use the image's background color. */
5140 use_img_background = 1;
5142 if (CONSP (how))
5144 int rgb[3], i;
5146 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5148 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5149 how = XCDR (how);
5152 if (i == 3 && NILP (how))
5154 char color_name[30];
5155 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
5156 bg = (
5157 #ifdef HAVE_NTGUI
5158 0x00ffffff & /* Filter out palette info. */
5159 #endif /* HAVE_NTGUI */
5160 x_alloc_image_color (f, img, build_string (color_name), 0));
5161 use_img_background = 0;
5165 if (use_img_background)
5166 bg = four_corners_best (ximg, img->width, img->height);
5168 /* Set all bits in mask_img to 1 whose color in ximg is different
5169 from the background color bg. */
5170 #ifndef HAVE_NTGUI
5171 for (y = 0; y < img->height; ++y)
5172 for (x = 0; x < img->width; ++x)
5173 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5174 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5176 /* Fill in the background_transparent field while we have the mask handy. */
5177 image_background_transparent (img, f, mask_img);
5179 /* Put mask_img into img->mask. */
5180 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5181 x_destroy_x_image (mask_img);
5183 #else
5184 for (y = 0; y < img->height; ++y)
5185 for (x = 0; x < img->width; ++x)
5187 COLORREF p = GetPixel (ximg, x, y);
5188 if (p != bg)
5189 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5192 /* Create the mask image. */
5193 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5194 mask_img);
5195 /* Fill in the background_transparent field while we have the mask handy. */
5196 SelectObject (ximg, img->mask);
5197 image_background_transparent (img, f, ximg);
5199 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5200 xfree (mask_img);
5201 #endif /* HAVE_NTGUI */
5203 Destroy_Image (ximg, prev);
5205 return 1;
5209 /***********************************************************************
5210 PBM (mono, gray, color)
5211 ***********************************************************************/
5213 static int pbm_image_p P_ ((Lisp_Object object));
5214 static int pbm_load P_ ((struct frame *f, struct image *img));
5215 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
5217 /* The symbol `pbm' identifying images of this type. */
5219 Lisp_Object Qpbm;
5221 /* Indices of image specification fields in gs_format, below. */
5223 enum pbm_keyword_index
5225 PBM_TYPE,
5226 PBM_FILE,
5227 PBM_DATA,
5228 PBM_ASCENT,
5229 PBM_MARGIN,
5230 PBM_RELIEF,
5231 PBM_ALGORITHM,
5232 PBM_HEURISTIC_MASK,
5233 PBM_MASK,
5234 PBM_FOREGROUND,
5235 PBM_BACKGROUND,
5236 PBM_LAST
5239 /* Vector of image_keyword structures describing the format
5240 of valid user-defined image specifications. */
5242 static struct image_keyword pbm_format[PBM_LAST] =
5244 {":type", IMAGE_SYMBOL_VALUE, 1},
5245 {":file", IMAGE_STRING_VALUE, 0},
5246 {":data", IMAGE_STRING_VALUE, 0},
5247 {":ascent", IMAGE_ASCENT_VALUE, 0},
5248 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5249 {":relief", IMAGE_INTEGER_VALUE, 0},
5250 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5251 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5252 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5253 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5254 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5257 /* Structure describing the image type `pbm'. */
5259 static struct image_type pbm_type =
5261 &Qpbm,
5262 pbm_image_p,
5263 pbm_load,
5264 x_clear_image,
5265 NULL
5269 /* Return non-zero if OBJECT is a valid PBM image specification. */
5271 static int
5272 pbm_image_p (object)
5273 Lisp_Object object;
5275 struct image_keyword fmt[PBM_LAST];
5277 bcopy (pbm_format, fmt, sizeof fmt);
5279 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5280 return 0;
5282 /* Must specify either :data or :file. */
5283 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5287 /* Scan a decimal number from *S and return it. Advance *S while
5288 reading the number. END is the end of the string. Value is -1 at
5289 end of input. */
5291 static int
5292 pbm_scan_number (s, end)
5293 unsigned char **s, *end;
5295 int c = 0, val = -1;
5297 while (*s < end)
5299 /* Skip white-space. */
5300 while (*s < end && (c = *(*s)++, isspace (c)))
5303 if (c == '#')
5305 /* Skip comment to end of line. */
5306 while (*s < end && (c = *(*s)++, c != '\n'))
5309 else if (isdigit (c))
5311 /* Read decimal number. */
5312 val = c - '0';
5313 while (*s < end && (c = *(*s)++, isdigit (c)))
5314 val = 10 * val + c - '0';
5315 break;
5317 else
5318 break;
5321 return val;
5325 #ifdef HAVE_NTGUI
5326 #if 0 /* Unused. ++kfs */
5328 /* Read FILE into memory. Value is a pointer to a buffer allocated
5329 with xmalloc holding FILE's contents. Value is null if an error
5330 occurred. *SIZE is set to the size of the file. */
5332 static char *
5333 pbm_read_file (file, size)
5334 Lisp_Object file;
5335 int *size;
5337 FILE *fp = NULL;
5338 char *buf = NULL;
5339 struct stat st;
5341 if (stat (SDATA (file), &st) == 0
5342 && (fp = fopen (SDATA (file), "rb")) != NULL
5343 && (buf = (char *) xmalloc (st.st_size),
5344 fread (buf, 1, st.st_size, fp) == st.st_size))
5346 *size = st.st_size;
5347 fclose (fp);
5349 else
5351 if (fp)
5352 fclose (fp);
5353 if (buf)
5355 xfree (buf);
5356 buf = NULL;
5360 return buf;
5362 #endif
5363 #endif /* HAVE_NTGUI */
5365 /* Load PBM image IMG for use on frame F. */
5367 static int
5368 pbm_load (f, img)
5369 struct frame *f;
5370 struct image *img;
5372 int raw_p, x, y;
5373 int width, height, max_color_idx = 0;
5374 XImagePtr ximg;
5375 Lisp_Object file, specified_file;
5376 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5377 struct gcpro gcpro1;
5378 unsigned char *contents = NULL;
5379 unsigned char *end, *p;
5380 int size;
5382 specified_file = image_spec_value (img->spec, QCfile, NULL);
5383 file = Qnil;
5384 GCPRO1 (file);
5386 if (STRINGP (specified_file))
5388 file = x_find_image_file (specified_file);
5389 if (!STRINGP (file))
5391 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5392 UNGCPRO;
5393 return 0;
5396 contents = slurp_file (SDATA (file), &size);
5397 if (contents == NULL)
5399 image_error ("Error reading `%s'", file, Qnil);
5400 UNGCPRO;
5401 return 0;
5404 p = contents;
5405 end = contents + size;
5407 else
5409 Lisp_Object data;
5410 data = image_spec_value (img->spec, QCdata, NULL);
5411 p = SDATA (data);
5412 end = p + SBYTES (data);
5415 /* Check magic number. */
5416 if (end - p < 2 || *p++ != 'P')
5418 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5419 error:
5420 xfree (contents);
5421 UNGCPRO;
5422 return 0;
5425 switch (*p++)
5427 case '1':
5428 raw_p = 0, type = PBM_MONO;
5429 break;
5431 case '2':
5432 raw_p = 0, type = PBM_GRAY;
5433 break;
5435 case '3':
5436 raw_p = 0, type = PBM_COLOR;
5437 break;
5439 case '4':
5440 raw_p = 1, type = PBM_MONO;
5441 break;
5443 case '5':
5444 raw_p = 1, type = PBM_GRAY;
5445 break;
5447 case '6':
5448 raw_p = 1, type = PBM_COLOR;
5449 break;
5451 default:
5452 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5453 goto error;
5456 /* Read width, height, maximum color-component. Characters
5457 starting with `#' up to the end of a line are ignored. */
5458 width = pbm_scan_number (&p, end);
5459 height = pbm_scan_number (&p, end);
5461 if (type != PBM_MONO)
5463 max_color_idx = pbm_scan_number (&p, end);
5464 if (raw_p && max_color_idx > 255)
5465 max_color_idx = 255;
5468 if (width < 0
5469 || height < 0
5470 || (type != PBM_MONO && max_color_idx < 0))
5471 goto error;
5473 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5474 &ximg, &img->pixmap))
5475 goto error;
5477 /* Initialize the color hash table. */
5478 init_color_table ();
5480 if (type == PBM_MONO)
5482 int c = 0, g;
5483 struct image_keyword fmt[PBM_LAST];
5484 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5485 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5487 /* Parse the image specification. */
5488 bcopy (pbm_format, fmt, sizeof fmt);
5489 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5491 /* Get foreground and background colors, maybe allocate colors. */
5492 if (fmt[PBM_FOREGROUND].count
5493 && STRINGP (fmt[PBM_FOREGROUND].value))
5494 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5495 if (fmt[PBM_BACKGROUND].count
5496 && STRINGP (fmt[PBM_BACKGROUND].value))
5498 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5499 img->background = bg;
5500 img->background_valid = 1;
5503 for (y = 0; y < height; ++y)
5504 for (x = 0; x < width; ++x)
5506 if (raw_p)
5508 if ((x & 7) == 0)
5509 c = *p++;
5510 g = c & 0x80;
5511 c <<= 1;
5513 else
5514 g = pbm_scan_number (&p, end);
5516 XPutPixel (ximg, x, y, g ? fg : bg);
5519 else
5521 for (y = 0; y < height; ++y)
5522 for (x = 0; x < width; ++x)
5524 int r, g, b;
5526 if (type == PBM_GRAY)
5527 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
5528 else if (raw_p)
5530 r = *p++;
5531 g = *p++;
5532 b = *p++;
5534 else
5536 r = pbm_scan_number (&p, end);
5537 g = pbm_scan_number (&p, end);
5538 b = pbm_scan_number (&p, end);
5541 if (r < 0 || g < 0 || b < 0)
5543 x_destroy_x_image (ximg);
5544 image_error ("Invalid pixel value in image `%s'",
5545 img->spec, Qnil);
5546 goto error;
5549 /* RGB values are now in the range 0..max_color_idx.
5550 Scale this to the range 0..0xffff supported by X. */
5551 r = (double) r * 65535 / max_color_idx;
5552 g = (double) g * 65535 / max_color_idx;
5553 b = (double) b * 65535 / max_color_idx;
5554 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5558 #ifdef COLOR_TABLE_SUPPORT
5559 /* Store in IMG->colors the colors allocated for the image, and
5560 free the color table. */
5561 img->colors = colors_in_color_table (&img->ncolors);
5562 free_color_table ();
5563 #endif /* COLOR_TABLE_SUPPORT */
5565 img->width = width;
5566 img->height = height;
5568 /* Maybe fill in the background field while we have ximg handy. */
5570 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
5571 /* Casting avoids a GCC warning. */
5572 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
5574 /* Put the image into a pixmap. */
5575 x_put_x_image (f, ximg, img->pixmap, width, height);
5576 x_destroy_x_image (ximg);
5578 /* X and W32 versions did it here, MAC version above. ++kfs
5579 img->width = width;
5580 img->height = height; */
5582 UNGCPRO;
5583 xfree (contents);
5584 return 1;
5588 /***********************************************************************
5590 ***********************************************************************/
5592 #if defined (HAVE_PNG) || defined (MAC_OS)
5594 /* Function prototypes. */
5596 static int png_image_p P_ ((Lisp_Object object));
5597 static int png_load P_ ((struct frame *f, struct image *img));
5599 /* The symbol `png' identifying images of this type. */
5601 Lisp_Object Qpng;
5603 /* Indices of image specification fields in png_format, below. */
5605 enum png_keyword_index
5607 PNG_TYPE,
5608 PNG_DATA,
5609 PNG_FILE,
5610 PNG_ASCENT,
5611 PNG_MARGIN,
5612 PNG_RELIEF,
5613 PNG_ALGORITHM,
5614 PNG_HEURISTIC_MASK,
5615 PNG_MASK,
5616 PNG_BACKGROUND,
5617 PNG_LAST
5620 /* Vector of image_keyword structures describing the format
5621 of valid user-defined image specifications. */
5623 static struct image_keyword png_format[PNG_LAST] =
5625 {":type", IMAGE_SYMBOL_VALUE, 1},
5626 {":data", IMAGE_STRING_VALUE, 0},
5627 {":file", IMAGE_STRING_VALUE, 0},
5628 {":ascent", IMAGE_ASCENT_VALUE, 0},
5629 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5630 {":relief", IMAGE_INTEGER_VALUE, 0},
5631 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5632 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5633 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5634 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5637 /* Structure describing the image type `png'. */
5639 static struct image_type png_type =
5641 &Qpng,
5642 png_image_p,
5643 png_load,
5644 x_clear_image,
5645 NULL
5648 /* Return non-zero if OBJECT is a valid PNG image specification. */
5650 static int
5651 png_image_p (object)
5652 Lisp_Object object;
5654 struct image_keyword fmt[PNG_LAST];
5655 bcopy (png_format, fmt, sizeof fmt);
5657 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5658 return 0;
5660 /* Must specify either the :data or :file keyword. */
5661 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5664 #endif /* HAVE_PNG || MAC_OS */
5667 #ifdef HAVE_PNG
5669 #if defined HAVE_LIBPNG_PNG_H
5670 # include <libpng/png.h>
5671 #else
5672 # include <png.h>
5673 #endif
5675 #ifdef HAVE_NTGUI
5676 /* PNG library details. */
5678 DEF_IMGLIB_FN (png_get_io_ptr);
5679 DEF_IMGLIB_FN (png_check_sig);
5680 DEF_IMGLIB_FN (png_create_read_struct);
5681 DEF_IMGLIB_FN (png_create_info_struct);
5682 DEF_IMGLIB_FN (png_destroy_read_struct);
5683 DEF_IMGLIB_FN (png_set_read_fn);
5684 DEF_IMGLIB_FN (png_set_sig_bytes);
5685 DEF_IMGLIB_FN (png_read_info);
5686 DEF_IMGLIB_FN (png_get_IHDR);
5687 DEF_IMGLIB_FN (png_get_valid);
5688 DEF_IMGLIB_FN (png_set_strip_16);
5689 DEF_IMGLIB_FN (png_set_expand);
5690 DEF_IMGLIB_FN (png_set_gray_to_rgb);
5691 DEF_IMGLIB_FN (png_set_background);
5692 DEF_IMGLIB_FN (png_get_bKGD);
5693 DEF_IMGLIB_FN (png_read_update_info);
5694 DEF_IMGLIB_FN (png_get_channels);
5695 DEF_IMGLIB_FN (png_get_rowbytes);
5696 DEF_IMGLIB_FN (png_read_image);
5697 DEF_IMGLIB_FN (png_read_end);
5698 DEF_IMGLIB_FN (png_error);
5700 static int
5701 init_png_functions (Lisp_Object libraries)
5703 HMODULE library;
5705 /* Try loading libpng under probable names. */
5706 if (!(library = w32_delayed_load (libraries, Qpng)))
5707 return 0;
5709 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5710 LOAD_IMGLIB_FN (library, png_check_sig);
5711 LOAD_IMGLIB_FN (library, png_create_read_struct);
5712 LOAD_IMGLIB_FN (library, png_create_info_struct);
5713 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5714 LOAD_IMGLIB_FN (library, png_set_read_fn);
5715 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5716 LOAD_IMGLIB_FN (library, png_read_info);
5717 LOAD_IMGLIB_FN (library, png_get_IHDR);
5718 LOAD_IMGLIB_FN (library, png_get_valid);
5719 LOAD_IMGLIB_FN (library, png_set_strip_16);
5720 LOAD_IMGLIB_FN (library, png_set_expand);
5721 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5722 LOAD_IMGLIB_FN (library, png_set_background);
5723 LOAD_IMGLIB_FN (library, png_get_bKGD);
5724 LOAD_IMGLIB_FN (library, png_read_update_info);
5725 LOAD_IMGLIB_FN (library, png_get_channels);
5726 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5727 LOAD_IMGLIB_FN (library, png_read_image);
5728 LOAD_IMGLIB_FN (library, png_read_end);
5729 LOAD_IMGLIB_FN (library, png_error);
5730 return 1;
5732 #else
5734 #define fn_png_get_io_ptr png_get_io_ptr
5735 #define fn_png_check_sig png_check_sig
5736 #define fn_png_create_read_struct png_create_read_struct
5737 #define fn_png_create_info_struct png_create_info_struct
5738 #define fn_png_destroy_read_struct png_destroy_read_struct
5739 #define fn_png_set_read_fn png_set_read_fn
5740 #define fn_png_set_sig_bytes png_set_sig_bytes
5741 #define fn_png_read_info png_read_info
5742 #define fn_png_get_IHDR png_get_IHDR
5743 #define fn_png_get_valid png_get_valid
5744 #define fn_png_set_strip_16 png_set_strip_16
5745 #define fn_png_set_expand png_set_expand
5746 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5747 #define fn_png_set_background png_set_background
5748 #define fn_png_get_bKGD png_get_bKGD
5749 #define fn_png_read_update_info png_read_update_info
5750 #define fn_png_get_channels png_get_channels
5751 #define fn_png_get_rowbytes png_get_rowbytes
5752 #define fn_png_read_image png_read_image
5753 #define fn_png_read_end png_read_end
5754 #define fn_png_error png_error
5756 #endif /* HAVE_NTGUI */
5758 /* Error and warning handlers installed when the PNG library
5759 is initialized. */
5761 static void
5762 my_png_error (png_ptr, msg)
5763 png_struct *png_ptr;
5764 char *msg;
5766 xassert (png_ptr != NULL);
5767 image_error ("PNG error: %s", build_string (msg), Qnil);
5768 longjmp (png_ptr->jmpbuf, 1);
5772 static void
5773 my_png_warning (png_ptr, msg)
5774 png_struct *png_ptr;
5775 char *msg;
5777 xassert (png_ptr != NULL);
5778 image_error ("PNG warning: %s", build_string (msg), Qnil);
5781 /* Memory source for PNG decoding. */
5783 struct png_memory_storage
5785 unsigned char *bytes; /* The data */
5786 size_t len; /* How big is it? */
5787 int index; /* Where are we? */
5791 /* Function set as reader function when reading PNG image from memory.
5792 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5793 bytes from the input to DATA. */
5795 static void
5796 png_read_from_memory (png_ptr, data, length)
5797 png_structp png_ptr;
5798 png_bytep data;
5799 png_size_t length;
5801 struct png_memory_storage *tbr
5802 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5804 if (length > tbr->len - tbr->index)
5805 fn_png_error (png_ptr, "Read error");
5807 bcopy (tbr->bytes + tbr->index, data, length);
5808 tbr->index = tbr->index + length;
5812 /* Function set as reader function when reading PNG image from a file.
5813 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5814 bytes from the input to DATA. */
5816 static void
5817 png_read_from_file (png_ptr, data, length)
5818 png_structp png_ptr;
5819 png_bytep data;
5820 png_size_t length;
5822 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5824 if (fread (data, 1, length, fp) < length)
5825 fn_png_error (png_ptr, "Read error");
5829 /* Load PNG image IMG for use on frame F. Value is non-zero if
5830 successful. */
5832 static int
5833 png_load (f, img)
5834 struct frame *f;
5835 struct image *img;
5837 Lisp_Object file, specified_file;
5838 Lisp_Object specified_data;
5839 int x, y, i;
5840 XImagePtr ximg, mask_img = NULL;
5841 struct gcpro gcpro1;
5842 png_struct *png_ptr = NULL;
5843 png_info *info_ptr = NULL, *end_info = NULL;
5844 FILE *volatile fp = NULL;
5845 png_byte sig[8];
5846 png_byte * volatile pixels = NULL;
5847 png_byte ** volatile rows = NULL;
5848 png_uint_32 width, height;
5849 int bit_depth, color_type, interlace_type;
5850 png_byte channels;
5851 png_uint_32 row_bytes;
5852 int transparent_p;
5853 double screen_gamma;
5854 struct png_memory_storage tbr; /* Data to be read */
5856 /* Find out what file to load. */
5857 specified_file = image_spec_value (img->spec, QCfile, NULL);
5858 specified_data = image_spec_value (img->spec, QCdata, NULL);
5859 file = Qnil;
5860 GCPRO1 (file);
5862 if (NILP (specified_data))
5864 file = x_find_image_file (specified_file);
5865 if (!STRINGP (file))
5867 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5868 UNGCPRO;
5869 return 0;
5872 /* Open the image file. */
5873 fp = fopen (SDATA (file), "rb");
5874 if (!fp)
5876 image_error ("Cannot open image file `%s'", file, Qnil);
5877 UNGCPRO;
5878 fclose (fp);
5879 return 0;
5882 /* Check PNG signature. */
5883 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5884 || !fn_png_check_sig (sig, sizeof sig))
5886 image_error ("Not a PNG file: `%s'", file, Qnil);
5887 UNGCPRO;
5888 fclose (fp);
5889 return 0;
5892 else
5894 /* Read from memory. */
5895 tbr.bytes = SDATA (specified_data);
5896 tbr.len = SBYTES (specified_data);
5897 tbr.index = 0;
5899 /* Check PNG signature. */
5900 if (tbr.len < sizeof sig
5901 || !fn_png_check_sig (tbr.bytes, sizeof sig))
5903 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5904 UNGCPRO;
5905 return 0;
5908 /* Need to skip past the signature. */
5909 tbr.bytes += sizeof (sig);
5912 /* Initialize read and info structs for PNG lib. Casting return
5913 value avoids a GCC warning on W32. */
5914 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5915 NULL, my_png_error,
5916 my_png_warning);
5917 if (!png_ptr)
5919 if (fp) fclose (fp);
5920 UNGCPRO;
5921 return 0;
5924 /* Casting return value avoids a GCC warning on W32. */
5925 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
5926 if (!info_ptr)
5928 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5929 if (fp) fclose (fp);
5930 UNGCPRO;
5931 return 0;
5934 /* Casting return value avoids a GCC warning on W32. */
5935 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
5936 if (!end_info)
5938 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5939 if (fp) fclose (fp);
5940 UNGCPRO;
5941 return 0;
5944 /* Set error jump-back. We come back here when the PNG library
5945 detects an error. */
5946 if (setjmp (png_ptr->jmpbuf))
5948 error:
5949 if (png_ptr)
5950 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5951 xfree (pixels);
5952 xfree (rows);
5953 if (fp) fclose (fp);
5954 UNGCPRO;
5955 return 0;
5958 /* Read image info. */
5959 if (!NILP (specified_data))
5960 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5961 else
5962 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
5964 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5965 fn_png_read_info (png_ptr, info_ptr);
5966 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5967 &interlace_type, NULL, NULL);
5969 /* If image contains simply transparency data, we prefer to
5970 construct a clipping mask. */
5971 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5972 transparent_p = 1;
5973 else
5974 transparent_p = 0;
5976 /* This function is easier to write if we only have to handle
5977 one data format: RGB or RGBA with 8 bits per channel. Let's
5978 transform other formats into that format. */
5980 /* Strip more than 8 bits per channel. */
5981 if (bit_depth == 16)
5982 fn_png_set_strip_16 (png_ptr);
5984 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5985 if available. */
5986 fn_png_set_expand (png_ptr);
5988 /* Convert grayscale images to RGB. */
5989 if (color_type == PNG_COLOR_TYPE_GRAY
5990 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5991 fn_png_set_gray_to_rgb (png_ptr);
5993 screen_gamma = (f->gamma ? 1 / f->gamma / 0.45455 : 2.2);
5995 #if 0 /* Avoid double gamma correction for PNG images. */
5996 { /* Tell the PNG lib to handle gamma correction for us. */
5997 int intent;
5998 double image_gamma;
5999 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
6000 if (png_get_sRGB (png_ptr, info_ptr, &intent))
6001 /* The libpng documentation says this is right in this case. */
6002 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6003 else
6004 #endif
6005 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
6006 /* Image contains gamma information. */
6007 png_set_gamma (png_ptr, screen_gamma, image_gamma);
6008 else
6009 /* Use the standard default for the image gamma. */
6010 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6012 #endif /* if 0 */
6014 /* Handle alpha channel by combining the image with a background
6015 color. Do this only if a real alpha channel is supplied. For
6016 simple transparency, we prefer a clipping mask. */
6017 if (!transparent_p)
6019 png_color_16 *image_bg;
6020 Lisp_Object specified_bg
6021 = image_spec_value (img->spec, QCbackground, NULL);
6023 if (STRINGP (specified_bg))
6024 /* The user specified `:background', use that. */
6026 /* W32 version incorrectly used COLORREF here!! ++kfs */
6027 XColor color;
6028 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
6030 png_color_16 user_bg;
6032 bzero (&user_bg, sizeof user_bg);
6033 user_bg.red = color.red >> 8;
6034 user_bg.green = color.green >> 8;
6035 user_bg.blue = color.blue >> 8;
6037 fn_png_set_background (png_ptr, &user_bg,
6038 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6041 else if (fn_png_get_bKGD (png_ptr, info_ptr, &image_bg))
6042 /* Image contains a background color with which to
6043 combine the image. */
6044 fn_png_set_background (png_ptr, image_bg,
6045 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
6046 else
6048 /* Image does not contain a background color with which
6049 to combine the image data via an alpha channel. Use
6050 the frame's background instead. */
6051 #ifdef HAVE_X_WINDOWS
6052 XColor color;
6053 png_color_16 frame_background;
6055 color.pixel = FRAME_BACKGROUND_PIXEL (f);
6056 x_query_color (f, &color);
6058 bzero (&frame_background, sizeof frame_background);
6059 frame_background.red = color.red >> 8;
6060 frame_background.green = color.green >> 8;
6061 frame_background.blue = color.blue >> 8;
6062 #endif /* HAVE_X_WINDOWS */
6064 #ifdef HAVE_NTGUI
6065 COLORREF color;
6066 png_color_16 frame_background;
6067 color = FRAME_BACKGROUND_PIXEL (f);
6068 #if 0 /* W32 TODO : Colormap support. */
6069 x_query_color (f, &color);
6070 #endif
6071 bzero (&frame_background, sizeof frame_background);
6072 frame_background.red = GetRValue (color);
6073 frame_background.green = GetGValue (color);
6074 frame_background.blue = GetBValue (color);
6075 #endif /* HAVE_NTGUI */
6077 #ifdef MAC_OS
6078 unsigned long color;
6079 png_color_16 frame_background;
6080 color = FRAME_BACKGROUND_PIXEL (f);
6081 #if 0 /* MAC/W32 TODO : Colormap support. */
6082 x_query_color (f, &color);
6083 #endif
6084 bzero (&frame_background, sizeof frame_background);
6085 frame_background.red = RED_FROM_ULONG (color);
6086 frame_background.green = GREEN_FROM_ULONG (color);
6087 frame_background.blue = BLUE_FROM_ULONG (color);
6088 #endif /* MAC_OS */
6090 fn_png_set_background (png_ptr, &frame_background,
6091 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6095 /* Update info structure. */
6096 fn_png_read_update_info (png_ptr, info_ptr);
6098 /* Get number of channels. Valid values are 1 for grayscale images
6099 and images with a palette, 2 for grayscale images with transparency
6100 information (alpha channel), 3 for RGB images, and 4 for RGB
6101 images with alpha channel, i.e. RGBA. If conversions above were
6102 sufficient we should only have 3 or 4 channels here. */
6103 channels = fn_png_get_channels (png_ptr, info_ptr);
6104 xassert (channels == 3 || channels == 4);
6106 /* Number of bytes needed for one row of the image. */
6107 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
6109 /* Allocate memory for the image. */
6110 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
6111 rows = (png_byte **) xmalloc (height * sizeof *rows);
6112 for (i = 0; i < height; ++i)
6113 rows[i] = pixels + i * row_bytes;
6115 /* Read the entire image. */
6116 fn_png_read_image (png_ptr, rows);
6117 fn_png_read_end (png_ptr, info_ptr);
6118 if (fp)
6120 fclose (fp);
6121 fp = NULL;
6124 /* Create the X image and pixmap. */
6125 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
6126 &img->pixmap))
6127 goto error;
6129 /* Create an image and pixmap serving as mask if the PNG image
6130 contains an alpha channel. */
6131 if (channels == 4
6132 && !transparent_p
6133 && !x_create_x_image_and_pixmap (f, width, height, 1,
6134 &mask_img, &img->mask))
6136 x_destroy_x_image (ximg);
6137 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
6138 img->pixmap = NO_PIXMAP;
6139 goto error;
6142 /* Fill the X image and mask from PNG data. */
6143 init_color_table ();
6145 for (y = 0; y < height; ++y)
6147 png_byte *p = rows[y];
6149 for (x = 0; x < width; ++x)
6151 unsigned r, g, b;
6153 r = *p++ << 8;
6154 g = *p++ << 8;
6155 b = *p++ << 8;
6156 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6157 /* An alpha channel, aka mask channel, associates variable
6158 transparency with an image. Where other image formats
6159 support binary transparency---fully transparent or fully
6160 opaque---PNG allows up to 254 levels of partial transparency.
6161 The PNG library implements partial transparency by combining
6162 the image with a specified background color.
6164 I'm not sure how to handle this here nicely: because the
6165 background on which the image is displayed may change, for
6166 real alpha channel support, it would be necessary to create
6167 a new image for each possible background.
6169 What I'm doing now is that a mask is created if we have
6170 boolean transparency information. Otherwise I'm using
6171 the frame's background color to combine the image with. */
6173 if (channels == 4)
6175 if (mask_img)
6176 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6177 ++p;
6182 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6183 /* Set IMG's background color from the PNG image, unless the user
6184 overrode it. */
6186 png_color_16 *bg;
6187 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6189 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6190 img->background_valid = 1;
6194 #ifdef COLOR_TABLE_SUPPORT
6195 /* Remember colors allocated for this image. */
6196 img->colors = colors_in_color_table (&img->ncolors);
6197 free_color_table ();
6198 #endif /* COLOR_TABLE_SUPPORT */
6200 /* Clean up. */
6201 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6202 xfree (rows);
6203 xfree (pixels);
6205 img->width = width;
6206 img->height = height;
6208 /* Maybe fill in the background field while we have ximg handy.
6209 Casting avoids a GCC warning. */
6210 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6212 /* Put the image into the pixmap, then free the X image and its buffer. */
6213 x_put_x_image (f, ximg, img->pixmap, width, height);
6214 x_destroy_x_image (ximg);
6216 /* Same for the mask. */
6217 if (mask_img)
6219 /* Fill in the background_transparent field while we have the
6220 mask handy. Casting avoids a GCC warning. */
6221 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6223 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
6224 x_destroy_x_image (mask_img);
6227 UNGCPRO;
6228 return 1;
6231 #else /* HAVE_PNG */
6233 #ifdef MAC_OS
6234 static int
6235 png_load (f, img)
6236 struct frame *f;
6237 struct image *img;
6239 #ifdef MAC_OSX
6240 if (MyCGImageCreateWithPNGDataProvider)
6241 return image_load_quartz2d (f, img, 1);
6242 else
6243 #endif
6244 return image_load_quicktime (f, img, kQTFileTypePNG);
6246 #endif /* MAC_OS */
6248 #endif /* !HAVE_PNG */
6252 /***********************************************************************
6253 JPEG
6254 ***********************************************************************/
6256 #if defined (HAVE_JPEG) || defined (MAC_OS)
6258 static int jpeg_image_p P_ ((Lisp_Object object));
6259 static int jpeg_load P_ ((struct frame *f, struct image *img));
6261 /* The symbol `jpeg' identifying images of this type. */
6263 Lisp_Object Qjpeg;
6265 /* Indices of image specification fields in gs_format, below. */
6267 enum jpeg_keyword_index
6269 JPEG_TYPE,
6270 JPEG_DATA,
6271 JPEG_FILE,
6272 JPEG_ASCENT,
6273 JPEG_MARGIN,
6274 JPEG_RELIEF,
6275 JPEG_ALGORITHM,
6276 JPEG_HEURISTIC_MASK,
6277 JPEG_MASK,
6278 JPEG_BACKGROUND,
6279 JPEG_LAST
6282 /* Vector of image_keyword structures describing the format
6283 of valid user-defined image specifications. */
6285 static struct image_keyword jpeg_format[JPEG_LAST] =
6287 {":type", IMAGE_SYMBOL_VALUE, 1},
6288 {":data", IMAGE_STRING_VALUE, 0},
6289 {":file", IMAGE_STRING_VALUE, 0},
6290 {":ascent", IMAGE_ASCENT_VALUE, 0},
6291 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6292 {":relief", IMAGE_INTEGER_VALUE, 0},
6293 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6294 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6295 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6296 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6299 /* Structure describing the image type `jpeg'. */
6301 static struct image_type jpeg_type =
6303 &Qjpeg,
6304 jpeg_image_p,
6305 jpeg_load,
6306 x_clear_image,
6307 NULL
6310 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6312 static int
6313 jpeg_image_p (object)
6314 Lisp_Object object;
6316 struct image_keyword fmt[JPEG_LAST];
6318 bcopy (jpeg_format, fmt, sizeof fmt);
6320 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6321 return 0;
6323 /* Must specify either the :data or :file keyword. */
6324 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6327 #endif /* HAVE_JPEG || MAC_OS */
6329 #ifdef HAVE_JPEG
6331 /* Work around a warning about HAVE_STDLIB_H being redefined in
6332 jconfig.h. */
6333 #ifdef HAVE_STDLIB_H
6334 #define HAVE_STDLIB_H_1
6335 #undef HAVE_STDLIB_H
6336 #endif /* HAVE_STLIB_H */
6338 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6339 /* In older releases of the jpeg library, jpeglib.h will define boolean
6340 differently depending on __WIN32__, so make sure it is defined. */
6341 #define __WIN32__ 1
6342 #endif
6344 #include <jpeglib.h>
6345 #include <jerror.h>
6346 #include <setjmp.h>
6348 #ifdef HAVE_STLIB_H_1
6349 #define HAVE_STDLIB_H 1
6350 #endif
6352 #ifdef HAVE_NTGUI
6354 /* JPEG library details. */
6355 DEF_IMGLIB_FN (jpeg_CreateDecompress);
6356 DEF_IMGLIB_FN (jpeg_start_decompress);
6357 DEF_IMGLIB_FN (jpeg_finish_decompress);
6358 DEF_IMGLIB_FN (jpeg_destroy_decompress);
6359 DEF_IMGLIB_FN (jpeg_read_header);
6360 DEF_IMGLIB_FN (jpeg_read_scanlines);
6361 DEF_IMGLIB_FN (jpeg_std_error);
6362 DEF_IMGLIB_FN (jpeg_resync_to_restart);
6364 static int
6365 init_jpeg_functions (Lisp_Object libraries)
6367 HMODULE library;
6369 if (!(library = w32_delayed_load (libraries, Qjpeg)))
6370 return 0;
6372 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6373 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6374 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6375 LOAD_IMGLIB_FN (library, jpeg_read_header);
6376 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6377 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6378 LOAD_IMGLIB_FN (library, jpeg_std_error);
6379 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6380 return 1;
6383 /* Wrapper since we can't directly assign the function pointer
6384 to another function pointer that was declared more completely easily. */
6385 static boolean
6386 jpeg_resync_to_restart_wrapper(cinfo, desired)
6387 j_decompress_ptr cinfo;
6388 int desired;
6390 return fn_jpeg_resync_to_restart (cinfo, desired);
6393 #else
6395 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6396 #define fn_jpeg_start_decompress jpeg_start_decompress
6397 #define fn_jpeg_finish_decompress jpeg_finish_decompress
6398 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6399 #define fn_jpeg_read_header jpeg_read_header
6400 #define fn_jpeg_read_scanlines jpeg_read_scanlines
6401 #define fn_jpeg_std_error jpeg_std_error
6402 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6404 #endif /* HAVE_NTGUI */
6406 struct my_jpeg_error_mgr
6408 struct jpeg_error_mgr pub;
6409 jmp_buf setjmp_buffer;
6413 static void
6414 my_error_exit (cinfo)
6415 j_common_ptr cinfo;
6417 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6418 longjmp (mgr->setjmp_buffer, 1);
6422 /* Init source method for JPEG data source manager. Called by
6423 jpeg_read_header() before any data is actually read. See
6424 libjpeg.doc from the JPEG lib distribution. */
6426 static void
6427 our_common_init_source (cinfo)
6428 j_decompress_ptr cinfo;
6433 /* Method to terminate data source. Called by
6434 jpeg_finish_decompress() after all data has been processed. */
6436 static void
6437 our_common_term_source (cinfo)
6438 j_decompress_ptr cinfo;
6443 /* Fill input buffer method for JPEG data source manager. Called
6444 whenever more data is needed. We read the whole image in one step,
6445 so this only adds a fake end of input marker at the end. */
6447 static boolean
6448 our_memory_fill_input_buffer (cinfo)
6449 j_decompress_ptr cinfo;
6451 /* Insert a fake EOI marker. */
6452 struct jpeg_source_mgr *src = cinfo->src;
6453 static JOCTET buffer[2];
6455 buffer[0] = (JOCTET) 0xFF;
6456 buffer[1] = (JOCTET) JPEG_EOI;
6458 src->next_input_byte = buffer;
6459 src->bytes_in_buffer = 2;
6460 return 1;
6464 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6465 is the JPEG data source manager. */
6467 static void
6468 our_memory_skip_input_data (cinfo, num_bytes)
6469 j_decompress_ptr cinfo;
6470 long num_bytes;
6472 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6474 if (src)
6476 if (num_bytes > src->bytes_in_buffer)
6477 ERREXIT (cinfo, JERR_INPUT_EOF);
6479 src->bytes_in_buffer -= num_bytes;
6480 src->next_input_byte += num_bytes;
6485 /* Set up the JPEG lib for reading an image from DATA which contains
6486 LEN bytes. CINFO is the decompression info structure created for
6487 reading the image. */
6489 static void
6490 jpeg_memory_src (cinfo, data, len)
6491 j_decompress_ptr cinfo;
6492 JOCTET *data;
6493 unsigned int len;
6495 struct jpeg_source_mgr *src;
6497 if (cinfo->src == NULL)
6499 /* First time for this JPEG object? */
6500 cinfo->src = (struct jpeg_source_mgr *)
6501 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6502 sizeof (struct jpeg_source_mgr));
6503 src = (struct jpeg_source_mgr *) cinfo->src;
6504 src->next_input_byte = data;
6507 src = (struct jpeg_source_mgr *) cinfo->src;
6508 src->init_source = our_common_init_source;
6509 src->fill_input_buffer = our_memory_fill_input_buffer;
6510 src->skip_input_data = our_memory_skip_input_data;
6511 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6512 src->term_source = our_common_term_source;
6513 src->bytes_in_buffer = len;
6514 src->next_input_byte = data;
6518 struct jpeg_stdio_mgr
6520 struct jpeg_source_mgr mgr;
6521 boolean finished;
6522 FILE *file;
6523 JOCTET *buffer;
6527 /* Size of buffer to read JPEG from file.
6528 Not too big, as we want to use alloc_small. */
6529 #define JPEG_STDIO_BUFFER_SIZE 8192
6532 /* Fill input buffer method for JPEG data source manager. Called
6533 whenever more data is needed. The data is read from a FILE *. */
6535 static boolean
6536 our_stdio_fill_input_buffer (cinfo)
6537 j_decompress_ptr cinfo;
6539 struct jpeg_stdio_mgr *src;
6541 src = (struct jpeg_stdio_mgr *) cinfo->src;
6542 if (!src->finished)
6544 size_t bytes;
6546 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
6547 if (bytes > 0)
6548 src->mgr.bytes_in_buffer = bytes;
6549 else
6551 WARNMS (cinfo, JWRN_JPEG_EOF);
6552 src->finished = 1;
6553 src->buffer[0] = (JOCTET) 0xFF;
6554 src->buffer[1] = (JOCTET) JPEG_EOI;
6555 src->mgr.bytes_in_buffer = 2;
6557 src->mgr.next_input_byte = src->buffer;
6560 return 1;
6564 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6565 is the JPEG data source manager. */
6567 static void
6568 our_stdio_skip_input_data (cinfo, num_bytes)
6569 j_decompress_ptr cinfo;
6570 long num_bytes;
6572 struct jpeg_stdio_mgr *src;
6573 src = (struct jpeg_stdio_mgr *) cinfo->src;
6575 while (num_bytes > 0 && !src->finished)
6577 if (num_bytes <= src->mgr.bytes_in_buffer)
6579 src->mgr.bytes_in_buffer -= num_bytes;
6580 src->mgr.next_input_byte += num_bytes;
6581 break;
6583 else
6585 num_bytes -= src->mgr.bytes_in_buffer;
6586 src->mgr.bytes_in_buffer = 0;
6587 src->mgr.next_input_byte = NULL;
6589 our_stdio_fill_input_buffer (cinfo);
6595 /* Set up the JPEG lib for reading an image from a FILE *.
6596 CINFO is the decompression info structure created for
6597 reading the image. */
6599 static void
6600 jpeg_file_src (cinfo, fp)
6601 j_decompress_ptr cinfo;
6602 FILE *fp;
6604 struct jpeg_stdio_mgr *src;
6606 if (cinfo->src != NULL)
6607 src = (struct jpeg_stdio_mgr *) cinfo->src;
6608 else
6610 /* First time for this JPEG object? */
6611 cinfo->src = (struct jpeg_source_mgr *)
6612 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6613 sizeof (struct jpeg_stdio_mgr));
6614 src = (struct jpeg_stdio_mgr *) cinfo->src;
6615 src->buffer = (JOCTET *)
6616 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6617 JPEG_STDIO_BUFFER_SIZE);
6620 src->file = fp;
6621 src->finished = 0;
6622 src->mgr.init_source = our_common_init_source;
6623 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
6624 src->mgr.skip_input_data = our_stdio_skip_input_data;
6625 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6626 src->mgr.term_source = our_common_term_source;
6627 src->mgr.bytes_in_buffer = 0;
6628 src->mgr.next_input_byte = NULL;
6632 /* Load image IMG for use on frame F. Patterned after example.c
6633 from the JPEG lib. */
6635 static int
6636 jpeg_load (f, img)
6637 struct frame *f;
6638 struct image *img;
6640 struct jpeg_decompress_struct cinfo;
6641 struct my_jpeg_error_mgr mgr;
6642 Lisp_Object file, specified_file;
6643 Lisp_Object specified_data;
6644 FILE * volatile fp = NULL;
6645 JSAMPARRAY buffer;
6646 int row_stride, x, y;
6647 XImagePtr ximg = NULL;
6648 int rc;
6649 unsigned long *colors;
6650 int width, height;
6651 struct gcpro gcpro1;
6653 /* Open the JPEG file. */
6654 specified_file = image_spec_value (img->spec, QCfile, NULL);
6655 specified_data = image_spec_value (img->spec, QCdata, NULL);
6656 file = Qnil;
6657 GCPRO1 (file);
6659 if (NILP (specified_data))
6661 file = x_find_image_file (specified_file);
6662 if (!STRINGP (file))
6664 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6665 UNGCPRO;
6666 return 0;
6669 fp = fopen (SDATA (file), "rb");
6670 if (fp == NULL)
6672 image_error ("Cannot open `%s'", file, Qnil);
6673 UNGCPRO;
6674 return 0;
6678 /* Customize libjpeg's error handling to call my_error_exit when an
6679 error is detected. This function will perform a longjmp.
6680 Casting return value avoids a GCC warning on W32. */
6681 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
6682 mgr.pub.error_exit = my_error_exit;
6684 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6686 if (rc == 1)
6688 /* Called from my_error_exit. Display a JPEG error. */
6689 char buffer[JMSG_LENGTH_MAX];
6690 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
6691 image_error ("Error reading JPEG image `%s': %s", img->spec,
6692 build_string (buffer));
6695 /* Close the input file and destroy the JPEG object. */
6696 if (fp)
6697 fclose ((FILE *) fp);
6698 fn_jpeg_destroy_decompress (&cinfo);
6700 /* If we already have an XImage, free that. */
6701 x_destroy_x_image (ximg);
6703 /* Free pixmap and colors. */
6704 x_clear_image (f, img);
6706 UNGCPRO;
6707 return 0;
6710 /* Create the JPEG decompression object. Let it read from fp.
6711 Read the JPEG image header. */
6712 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6714 if (NILP (specified_data))
6715 jpeg_file_src (&cinfo, (FILE *) fp);
6716 else
6717 jpeg_memory_src (&cinfo, SDATA (specified_data),
6718 SBYTES (specified_data));
6720 fn_jpeg_read_header (&cinfo, 1);
6722 /* Customize decompression so that color quantization will be used.
6723 Start decompression. */
6724 cinfo.quantize_colors = 1;
6725 fn_jpeg_start_decompress (&cinfo);
6726 width = img->width = cinfo.output_width;
6727 height = img->height = cinfo.output_height;
6729 /* Create X image and pixmap. */
6730 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6731 longjmp (mgr.setjmp_buffer, 2);
6733 /* Allocate colors. When color quantization is used,
6734 cinfo.actual_number_of_colors has been set with the number of
6735 colors generated, and cinfo.colormap is a two-dimensional array
6736 of color indices in the range 0..cinfo.actual_number_of_colors.
6737 No more than 255 colors will be generated. */
6739 int i, ir, ig, ib;
6741 if (cinfo.out_color_components > 2)
6742 ir = 0, ig = 1, ib = 2;
6743 else if (cinfo.out_color_components > 1)
6744 ir = 0, ig = 1, ib = 0;
6745 else
6746 ir = 0, ig = 0, ib = 0;
6748 /* Use the color table mechanism because it handles colors that
6749 cannot be allocated nicely. Such colors will be replaced with
6750 a default color, and we don't have to care about which colors
6751 can be freed safely, and which can't. */
6752 init_color_table ();
6753 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6754 * sizeof *colors);
6756 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6758 /* Multiply RGB values with 255 because X expects RGB values
6759 in the range 0..0xffff. */
6760 int r = cinfo.colormap[ir][i] << 8;
6761 int g = cinfo.colormap[ig][i] << 8;
6762 int b = cinfo.colormap[ib][i] << 8;
6763 colors[i] = lookup_rgb_color (f, r, g, b);
6766 #ifdef COLOR_TABLE_SUPPORT
6767 /* Remember those colors actually allocated. */
6768 img->colors = colors_in_color_table (&img->ncolors);
6769 free_color_table ();
6770 #endif /* COLOR_TABLE_SUPPORT */
6773 /* Read pixels. */
6774 row_stride = width * cinfo.output_components;
6775 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6776 row_stride, 1);
6777 for (y = 0; y < height; ++y)
6779 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6780 for (x = 0; x < cinfo.output_width; ++x)
6781 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6784 /* Clean up. */
6785 fn_jpeg_finish_decompress (&cinfo);
6786 fn_jpeg_destroy_decompress (&cinfo);
6787 if (fp)
6788 fclose ((FILE *) fp);
6790 /* Maybe fill in the background field while we have ximg handy. */
6791 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6792 /* Casting avoids a GCC warning. */
6793 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6795 /* Put the image into the pixmap. */
6796 x_put_x_image (f, ximg, img->pixmap, width, height);
6797 x_destroy_x_image (ximg);
6798 UNGCPRO;
6799 return 1;
6802 #else /* HAVE_JPEG */
6804 #ifdef MAC_OS
6805 static int
6806 jpeg_load (f, img)
6807 struct frame *f;
6808 struct image *img;
6810 #ifdef MAC_OSX
6811 return image_load_quartz2d (f, img, 0);
6812 #else
6813 return image_load_quicktime (f, img, kQTFileTypeJPEG);
6814 #endif
6816 #endif /* MAC_OS */
6818 #endif /* !HAVE_JPEG */
6822 /***********************************************************************
6823 TIFF
6824 ***********************************************************************/
6826 #if defined (HAVE_TIFF) || defined (MAC_OS)
6828 static int tiff_image_p P_ ((Lisp_Object object));
6829 static int tiff_load P_ ((struct frame *f, struct image *img));
6831 /* The symbol `tiff' identifying images of this type. */
6833 Lisp_Object Qtiff;
6835 /* Indices of image specification fields in tiff_format, below. */
6837 enum tiff_keyword_index
6839 TIFF_TYPE,
6840 TIFF_DATA,
6841 TIFF_FILE,
6842 TIFF_ASCENT,
6843 TIFF_MARGIN,
6844 TIFF_RELIEF,
6845 TIFF_ALGORITHM,
6846 TIFF_HEURISTIC_MASK,
6847 TIFF_MASK,
6848 TIFF_BACKGROUND,
6849 TIFF_LAST
6852 /* Vector of image_keyword structures describing the format
6853 of valid user-defined image specifications. */
6855 static struct image_keyword tiff_format[TIFF_LAST] =
6857 {":type", IMAGE_SYMBOL_VALUE, 1},
6858 {":data", IMAGE_STRING_VALUE, 0},
6859 {":file", IMAGE_STRING_VALUE, 0},
6860 {":ascent", IMAGE_ASCENT_VALUE, 0},
6861 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6862 {":relief", IMAGE_INTEGER_VALUE, 0},
6863 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6864 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6865 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6866 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6869 /* Structure describing the image type `tiff'. */
6871 static struct image_type tiff_type =
6873 &Qtiff,
6874 tiff_image_p,
6875 tiff_load,
6876 x_clear_image,
6877 NULL
6880 /* Return non-zero if OBJECT is a valid TIFF image specification. */
6882 static int
6883 tiff_image_p (object)
6884 Lisp_Object object;
6886 struct image_keyword fmt[TIFF_LAST];
6887 bcopy (tiff_format, fmt, sizeof fmt);
6889 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6890 return 0;
6892 /* Must specify either the :data or :file keyword. */
6893 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6896 #endif /* HAVE_TIFF || MAC_OS */
6898 #ifdef HAVE_TIFF
6900 #include <tiffio.h>
6902 #ifdef HAVE_NTGUI
6904 /* TIFF library details. */
6905 DEF_IMGLIB_FN (TIFFSetErrorHandler);
6906 DEF_IMGLIB_FN (TIFFSetWarningHandler);
6907 DEF_IMGLIB_FN (TIFFOpen);
6908 DEF_IMGLIB_FN (TIFFClientOpen);
6909 DEF_IMGLIB_FN (TIFFGetField);
6910 DEF_IMGLIB_FN (TIFFReadRGBAImage);
6911 DEF_IMGLIB_FN (TIFFClose);
6913 static int
6914 init_tiff_functions (Lisp_Object libraries)
6916 HMODULE library;
6918 if (!(library = w32_delayed_load (libraries, Qtiff)))
6919 return 0;
6921 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6922 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6923 LOAD_IMGLIB_FN (library, TIFFOpen);
6924 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6925 LOAD_IMGLIB_FN (library, TIFFGetField);
6926 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6927 LOAD_IMGLIB_FN (library, TIFFClose);
6928 return 1;
6931 #else
6933 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6934 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6935 #define fn_TIFFOpen TIFFOpen
6936 #define fn_TIFFClientOpen TIFFClientOpen
6937 #define fn_TIFFGetField TIFFGetField
6938 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6939 #define fn_TIFFClose TIFFClose
6941 #endif /* HAVE_NTGUI */
6944 /* Reading from a memory buffer for TIFF images Based on the PNG
6945 memory source, but we have to provide a lot of extra functions.
6946 Blah.
6948 We really only need to implement read and seek, but I am not
6949 convinced that the TIFF library is smart enough not to destroy
6950 itself if we only hand it the function pointers we need to
6951 override. */
6953 typedef struct
6955 unsigned char *bytes;
6956 size_t len;
6957 int index;
6959 tiff_memory_source;
6961 static size_t
6962 tiff_read_from_memory (data, buf, size)
6963 thandle_t data;
6964 tdata_t buf;
6965 tsize_t size;
6967 tiff_memory_source *src = (tiff_memory_source *) data;
6969 if (size > src->len - src->index)
6970 return (size_t) -1;
6971 bcopy (src->bytes + src->index, buf, size);
6972 src->index += size;
6973 return size;
6976 static size_t
6977 tiff_write_from_memory (data, buf, size)
6978 thandle_t data;
6979 tdata_t buf;
6980 tsize_t size;
6982 return (size_t) -1;
6985 static toff_t
6986 tiff_seek_in_memory (data, off, whence)
6987 thandle_t data;
6988 toff_t off;
6989 int whence;
6991 tiff_memory_source *src = (tiff_memory_source *) data;
6992 int idx;
6994 switch (whence)
6996 case SEEK_SET: /* Go from beginning of source. */
6997 idx = off;
6998 break;
7000 case SEEK_END: /* Go from end of source. */
7001 idx = src->len + off;
7002 break;
7004 case SEEK_CUR: /* Go from current position. */
7005 idx = src->index + off;
7006 break;
7008 default: /* Invalid `whence'. */
7009 return -1;
7012 if (idx > src->len || idx < 0)
7013 return -1;
7015 src->index = idx;
7016 return src->index;
7019 static int
7020 tiff_close_memory (data)
7021 thandle_t data;
7023 /* NOOP */
7024 return 0;
7027 static int
7028 tiff_mmap_memory (data, pbase, psize)
7029 thandle_t data;
7030 tdata_t *pbase;
7031 toff_t *psize;
7033 /* It is already _IN_ memory. */
7034 return 0;
7037 static void
7038 tiff_unmap_memory (data, base, size)
7039 thandle_t data;
7040 tdata_t base;
7041 toff_t size;
7043 /* We don't need to do this. */
7046 static toff_t
7047 tiff_size_of_memory (data)
7048 thandle_t data;
7050 return ((tiff_memory_source *) data)->len;
7054 static void
7055 tiff_error_handler (title, format, ap)
7056 const char *title, *format;
7057 va_list ap;
7059 char buf[512];
7060 int len;
7062 len = sprintf (buf, "TIFF error: %s ", title);
7063 vsprintf (buf + len, format, ap);
7064 add_to_log (buf, Qnil, Qnil);
7068 static void
7069 tiff_warning_handler (title, format, ap)
7070 const char *title, *format;
7071 va_list ap;
7073 char buf[512];
7074 int len;
7076 len = sprintf (buf, "TIFF warning: %s ", title);
7077 vsprintf (buf + len, format, ap);
7078 add_to_log (buf, Qnil, Qnil);
7082 /* Load TIFF image IMG for use on frame F. Value is non-zero if
7083 successful. */
7085 static int
7086 tiff_load (f, img)
7087 struct frame *f;
7088 struct image *img;
7090 Lisp_Object file, specified_file;
7091 Lisp_Object specified_data;
7092 TIFF *tiff;
7093 int width, height, x, y;
7094 uint32 *buf;
7095 int rc;
7096 XImagePtr ximg;
7097 struct gcpro gcpro1;
7098 tiff_memory_source memsrc;
7100 specified_file = image_spec_value (img->spec, QCfile, NULL);
7101 specified_data = image_spec_value (img->spec, QCdata, NULL);
7102 file = Qnil;
7103 GCPRO1 (file);
7105 fn_TIFFSetErrorHandler (tiff_error_handler);
7106 fn_TIFFSetWarningHandler (tiff_warning_handler);
7108 if (NILP (specified_data))
7110 /* Read from a file */
7111 file = x_find_image_file (specified_file);
7112 if (!STRINGP (file))
7114 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7115 UNGCPRO;
7116 return 0;
7119 /* Try to open the image file. Casting return value avoids a
7120 GCC warning on W32. */
7121 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
7122 if (tiff == NULL)
7124 image_error ("Cannot open `%s'", file, Qnil);
7125 UNGCPRO;
7126 return 0;
7129 else
7131 /* Memory source! */
7132 memsrc.bytes = SDATA (specified_data);
7133 memsrc.len = SBYTES (specified_data);
7134 memsrc.index = 0;
7136 /* Casting return value avoids a GCC warning on W32. */
7137 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r", &memsrc,
7138 (TIFFReadWriteProc) tiff_read_from_memory,
7139 (TIFFReadWriteProc) tiff_write_from_memory,
7140 tiff_seek_in_memory,
7141 tiff_close_memory,
7142 tiff_size_of_memory,
7143 tiff_mmap_memory,
7144 tiff_unmap_memory);
7146 if (!tiff)
7148 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7149 UNGCPRO;
7150 return 0;
7154 /* Get width and height of the image, and allocate a raster buffer
7155 of width x height 32-bit values. */
7156 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7157 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7158 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
7160 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7161 fn_TIFFClose (tiff);
7162 if (!rc)
7164 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7165 xfree (buf);
7166 UNGCPRO;
7167 return 0;
7170 /* Create the X image and pixmap. */
7171 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7173 xfree (buf);
7174 UNGCPRO;
7175 return 0;
7178 /* Initialize the color table. */
7179 init_color_table ();
7181 /* Process the pixel raster. Origin is in the lower-left corner. */
7182 for (y = 0; y < height; ++y)
7184 uint32 *row = buf + y * width;
7186 for (x = 0; x < width; ++x)
7188 uint32 abgr = row[x];
7189 int r = TIFFGetR (abgr) << 8;
7190 int g = TIFFGetG (abgr) << 8;
7191 int b = TIFFGetB (abgr) << 8;
7192 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7196 #ifdef COLOR_TABLE_SUPPORT
7197 /* Remember the colors allocated for the image. Free the color table. */
7198 img->colors = colors_in_color_table (&img->ncolors);
7199 free_color_table ();
7200 #endif /* COLOR_TABLE_SUPPORT */
7202 img->width = width;
7203 img->height = height;
7205 /* Maybe fill in the background field while we have ximg handy. */
7206 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7207 /* Casting avoids a GCC warning on W32. */
7208 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7210 /* Put the image into the pixmap, then free the X image and its buffer. */
7211 x_put_x_image (f, ximg, img->pixmap, width, height);
7212 x_destroy_x_image (ximg);
7213 xfree (buf);
7215 UNGCPRO;
7216 return 1;
7219 #else /* HAVE_TIFF */
7221 #ifdef MAC_OS
7222 static int
7223 tiff_load (f, img)
7224 struct frame *f;
7225 struct image *img;
7227 return image_load_quicktime (f, img, kQTFileTypeTIFF);
7229 #endif /* MAC_OS */
7231 #endif /* !HAVE_TIFF */
7235 /***********************************************************************
7237 ***********************************************************************/
7239 #if defined (HAVE_GIF) || defined (MAC_OS)
7241 static int gif_image_p P_ ((Lisp_Object object));
7242 static int gif_load P_ ((struct frame *f, struct image *img));
7244 /* The symbol `gif' identifying images of this type. */
7246 Lisp_Object Qgif;
7248 /* Indices of image specification fields in gif_format, below. */
7250 enum gif_keyword_index
7252 GIF_TYPE,
7253 GIF_DATA,
7254 GIF_FILE,
7255 GIF_ASCENT,
7256 GIF_MARGIN,
7257 GIF_RELIEF,
7258 GIF_ALGORITHM,
7259 GIF_HEURISTIC_MASK,
7260 GIF_MASK,
7261 GIF_IMAGE,
7262 GIF_BACKGROUND,
7263 GIF_LAST
7266 /* Vector of image_keyword structures describing the format
7267 of valid user-defined image specifications. */
7269 static struct image_keyword gif_format[GIF_LAST] =
7271 {":type", IMAGE_SYMBOL_VALUE, 1},
7272 {":data", IMAGE_STRING_VALUE, 0},
7273 {":file", IMAGE_STRING_VALUE, 0},
7274 {":ascent", IMAGE_ASCENT_VALUE, 0},
7275 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7276 {":relief", IMAGE_INTEGER_VALUE, 0},
7277 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7278 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7279 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7280 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7281 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7284 /* Structure describing the image type `gif'. */
7286 static struct image_type gif_type =
7288 &Qgif,
7289 gif_image_p,
7290 gif_load,
7291 x_clear_image,
7292 NULL
7295 /* Return non-zero if OBJECT is a valid GIF image specification. */
7297 static int
7298 gif_image_p (object)
7299 Lisp_Object object;
7301 struct image_keyword fmt[GIF_LAST];
7302 bcopy (gif_format, fmt, sizeof fmt);
7304 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7305 return 0;
7307 /* Must specify either the :data or :file keyword. */
7308 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7311 #endif /* HAVE_GIF || MAC_OS */
7313 #ifdef HAVE_GIF
7315 #if defined (HAVE_NTGUI) || defined (MAC_OS)
7316 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7317 Undefine before redefining to avoid a preprocessor warning. */
7318 #ifdef DrawText
7319 #undef DrawText
7320 #endif
7321 /* avoid conflict with QuickdrawText.h */
7322 #define DrawText gif_DrawText
7323 #include <gif_lib.h>
7324 #undef DrawText
7326 #else /* HAVE_NTGUI || MAC_OS */
7328 #include <gif_lib.h>
7330 #endif /* HAVE_NTGUI || MAC_OS */
7333 #ifdef HAVE_NTGUI
7335 /* GIF library details. */
7336 DEF_IMGLIB_FN (DGifCloseFile);
7337 DEF_IMGLIB_FN (DGifSlurp);
7338 DEF_IMGLIB_FN (DGifOpen);
7339 DEF_IMGLIB_FN (DGifOpenFileName);
7341 static int
7342 init_gif_functions (Lisp_Object libraries)
7344 HMODULE library;
7346 if (!(library = w32_delayed_load (libraries, Qgif)))
7347 return 0;
7349 LOAD_IMGLIB_FN (library, DGifCloseFile);
7350 LOAD_IMGLIB_FN (library, DGifSlurp);
7351 LOAD_IMGLIB_FN (library, DGifOpen);
7352 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7353 return 1;
7356 #else
7358 #define fn_DGifCloseFile DGifCloseFile
7359 #define fn_DGifSlurp DGifSlurp
7360 #define fn_DGifOpen DGifOpen
7361 #define fn_DGifOpenFileName DGifOpenFileName
7363 #endif /* HAVE_NTGUI */
7365 /* Reading a GIF image from memory
7366 Based on the PNG memory stuff to a certain extent. */
7368 typedef struct
7370 unsigned char *bytes;
7371 size_t len;
7372 int index;
7374 gif_memory_source;
7376 /* Make the current memory source available to gif_read_from_memory.
7377 It's done this way because not all versions of libungif support
7378 a UserData field in the GifFileType structure. */
7379 static gif_memory_source *current_gif_memory_src;
7381 static int
7382 gif_read_from_memory (file, buf, len)
7383 GifFileType *file;
7384 GifByteType *buf;
7385 int len;
7387 gif_memory_source *src = current_gif_memory_src;
7389 if (len > src->len - src->index)
7390 return -1;
7392 bcopy (src->bytes + src->index, buf, len);
7393 src->index += len;
7394 return len;
7398 /* Load GIF image IMG for use on frame F. Value is non-zero if
7399 successful. */
7401 static int
7402 gif_load (f, img)
7403 struct frame *f;
7404 struct image *img;
7406 Lisp_Object file, specified_file;
7407 Lisp_Object specified_data;
7408 int rc, width, height, x, y, i;
7409 XImagePtr ximg;
7410 ColorMapObject *gif_color_map;
7411 unsigned long pixel_colors[256];
7412 GifFileType *gif;
7413 struct gcpro gcpro1;
7414 Lisp_Object image;
7415 int ino, image_left, image_top, image_width, image_height;
7416 gif_memory_source memsrc;
7417 unsigned char *raster;
7419 specified_file = image_spec_value (img->spec, QCfile, NULL);
7420 specified_data = image_spec_value (img->spec, QCdata, NULL);
7421 file = Qnil;
7422 GCPRO1 (file);
7424 if (NILP (specified_data))
7426 file = x_find_image_file (specified_file);
7427 if (!STRINGP (file))
7429 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7430 UNGCPRO;
7431 return 0;
7434 /* Open the GIF file. Casting return value avoids a GCC warning
7435 on W32. */
7436 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
7437 if (gif == NULL)
7439 image_error ("Cannot open `%s'", file, Qnil);
7440 UNGCPRO;
7441 return 0;
7444 else
7446 /* Read from memory! */
7447 current_gif_memory_src = &memsrc;
7448 memsrc.bytes = SDATA (specified_data);
7449 memsrc.len = SBYTES (specified_data);
7450 memsrc.index = 0;
7452 /* Casting return value avoids a GCC warning on W32. */
7453 gif = (GifFileType *)fn_DGifOpen(&memsrc, gif_read_from_memory);
7454 if (!gif)
7456 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7457 UNGCPRO;
7458 return 0;
7462 /* Read entire contents. */
7463 rc = fn_DGifSlurp (gif);
7464 if (rc == GIF_ERROR)
7466 image_error ("Error reading `%s'", img->spec, Qnil);
7467 fn_DGifCloseFile (gif);
7468 UNGCPRO;
7469 return 0;
7472 image = image_spec_value (img->spec, QCindex, NULL);
7473 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7474 if (ino >= gif->ImageCount)
7476 image_error ("Invalid image number `%s' in image `%s'",
7477 image, img->spec);
7478 fn_DGifCloseFile (gif);
7479 UNGCPRO;
7480 return 0;
7483 image_top = gif->SavedImages[ino].ImageDesc.Top;
7484 image_left = gif->SavedImages[ino].ImageDesc.Left;
7485 image_width = gif->SavedImages[ino].ImageDesc.Width;
7486 image_height = gif->SavedImages[ino].ImageDesc.Height;
7488 width = img->width = max (gif->SWidth,
7489 max (gif->Image.Left + gif->Image.Width,
7490 image_left + image_width));
7491 height = img->height = max (gif->SHeight,
7492 max (gif->Image.Top + gif->Image.Height,
7493 image_top + image_height));
7495 /* Create the X image and pixmap. */
7496 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7498 fn_DGifCloseFile (gif);
7499 UNGCPRO;
7500 return 0;
7503 /* Allocate colors. */
7504 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7505 if (!gif_color_map)
7506 gif_color_map = gif->SColorMap;
7507 init_color_table ();
7508 bzero (pixel_colors, sizeof pixel_colors);
7510 for (i = 0; i < gif_color_map->ColorCount; ++i)
7512 int r = gif_color_map->Colors[i].Red << 8;
7513 int g = gif_color_map->Colors[i].Green << 8;
7514 int b = gif_color_map->Colors[i].Blue << 8;
7515 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7518 #ifdef COLOR_TABLE_SUPPORT
7519 img->colors = colors_in_color_table (&img->ncolors);
7520 free_color_table ();
7521 #endif /* COLOR_TABLE_SUPPORT */
7523 /* Clear the part of the screen image that are not covered by
7524 the image from the GIF file. Full animated GIF support
7525 requires more than can be done here (see the gif89 spec,
7526 disposal methods). Let's simply assume that the part
7527 not covered by a sub-image is in the frame's background color. */
7528 for (y = 0; y < image_top; ++y)
7529 for (x = 0; x < width; ++x)
7530 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7532 for (y = image_top + image_height; y < height; ++y)
7533 for (x = 0; x < width; ++x)
7534 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7536 for (y = image_top; y < image_top + image_height; ++y)
7538 for (x = 0; x < image_left; ++x)
7539 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7540 for (x = image_left + image_width; x < width; ++x)
7541 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7544 /* Read the GIF image into the X image. We use a local variable
7545 `raster' here because RasterBits below is a char *, and invites
7546 problems with bytes >= 0x80. */
7547 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7549 if (gif->SavedImages[ino].ImageDesc.Interlace)
7551 static int interlace_start[] = {0, 4, 2, 1};
7552 static int interlace_increment[] = {8, 8, 4, 2};
7553 int pass;
7554 int row = interlace_start[0];
7556 pass = 0;
7558 for (y = 0; y < image_height; y++)
7560 if (row >= image_height)
7562 row = interlace_start[++pass];
7563 while (row >= image_height)
7564 row = interlace_start[++pass];
7567 for (x = 0; x < image_width; x++)
7569 int i = raster[(y * image_width) + x];
7570 XPutPixel (ximg, x + image_left, row + image_top,
7571 pixel_colors[i]);
7574 row += interlace_increment[pass];
7577 else
7579 for (y = 0; y < image_height; ++y)
7580 for (x = 0; x < image_width; ++x)
7582 int i = raster[y * image_width + x];
7583 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
7587 fn_DGifCloseFile (gif);
7589 /* Maybe fill in the background field while we have ximg handy. */
7590 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7591 /* Casting avoids a GCC warning. */
7592 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7594 /* Put the image into the pixmap, then free the X image and its buffer. */
7595 x_put_x_image (f, ximg, img->pixmap, width, height);
7596 x_destroy_x_image (ximg);
7598 UNGCPRO;
7599 return 1;
7602 #else /* !HAVE_GIF */
7604 #ifdef MAC_OS
7605 static int
7606 gif_load (f, img)
7607 struct frame *f;
7608 struct image *img;
7610 Lisp_Object specified_file, file;
7611 Lisp_Object specified_data;
7612 OSErr err;
7613 Boolean graphic_p, movie_p, prefer_graphic_p;
7614 Handle dh = NULL;
7615 Movie movie = NULL;
7616 Lisp_Object image;
7617 Track track = NULL;
7618 Media media = NULL;
7619 long nsamples;
7620 Rect rect;
7621 Lisp_Object specified_bg;
7622 XColor color;
7623 RGBColor bg_color;
7624 int width, height;
7625 XImagePtr ximg;
7626 TimeValue time;
7627 struct gcpro gcpro1;
7628 int ino;
7629 CGrafPtr old_port;
7630 GDHandle old_gdh;
7632 specified_file = image_spec_value (img->spec, QCfile, NULL);
7633 specified_data = image_spec_value (img->spec, QCdata, NULL);
7635 if (NILP (specified_data))
7637 /* Read from a file */
7638 FSSpec fss;
7639 short refnum;
7641 err = find_image_fsspec (specified_file, &file, &fss);
7642 if (err != noErr)
7644 if (err == fnfErr)
7645 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7646 else
7647 goto open_error;
7650 err = CanQuickTimeOpenFile (&fss, kQTFileTypeGIF, 0,
7651 &graphic_p, &movie_p, &prefer_graphic_p, 0);
7652 if (err != noErr)
7653 goto open_error;
7655 if (!graphic_p && !movie_p)
7656 goto open_error;
7657 if (prefer_graphic_p)
7658 return image_load_qt_1 (f, img, kQTFileTypeGIF, &fss, NULL);
7659 err = OpenMovieFile (&fss, &refnum, fsRdPerm);
7660 if (err != noErr)
7661 goto open_error;
7662 err = NewMovieFromFile (&movie, refnum, NULL, NULL, 0, NULL);
7663 CloseMovieFile (refnum);
7664 if (err != noErr)
7666 image_error ("Error reading `%s'", file, Qnil);
7667 return 0;
7670 else
7672 /* Memory source! */
7673 Handle dref = NULL;
7674 long file_type_atom[3];
7676 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
7677 if (err != noErr)
7679 image_error ("Cannot allocate data handle for `%s'",
7680 img->spec, Qnil);
7681 goto error;
7684 file_type_atom[0] = EndianU32_NtoB (sizeof (long) * 3);
7685 file_type_atom[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
7686 file_type_atom[2] = EndianU32_NtoB (kQTFileTypeGIF);
7687 err = PtrToHand (&dh, &dref, sizeof (Handle));
7688 if (err == noErr)
7689 /* no file name */
7690 err = PtrAndHand ("\p", dref, 1);
7691 if (err == noErr)
7692 err = PtrAndHand (file_type_atom, dref, sizeof (long) * 3);
7693 if (err != noErr)
7695 image_error ("Cannot allocate handle data ref for `%s'", img->spec, Qnil);
7696 goto error;
7698 err = CanQuickTimeOpenDataRef (dref, HandleDataHandlerSubType, &graphic_p,
7699 &movie_p, &prefer_graphic_p, 0);
7700 if (err != noErr)
7701 goto open_error;
7703 if (!graphic_p && !movie_p)
7704 goto open_error;
7705 if (prefer_graphic_p)
7707 int success_p;
7709 DisposeHandle (dref);
7710 success_p = image_load_qt_1 (f, img, kQTFileTypeGIF, NULL, dh);
7711 DisposeHandle (dh);
7712 return success_p;
7714 err = NewMovieFromDataRef (&movie, 0, NULL, dref,
7715 HandleDataHandlerSubType);
7716 DisposeHandle (dref);
7717 if (err != noErr)
7718 goto open_error;
7721 image = image_spec_value (img->spec, QCindex, NULL);
7722 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7723 track = GetMovieIndTrack (movie, 1);
7724 media = GetTrackMedia (track);
7725 nsamples = GetMediaSampleCount (media);
7726 if (ino >= nsamples)
7728 image_error ("Invalid image number `%s' in image `%s'",
7729 image, img->spec);
7730 goto error;
7733 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7734 if (!STRINGP (specified_bg) ||
7735 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
7737 color.pixel = FRAME_BACKGROUND_PIXEL (f);
7738 color.red = RED16_FROM_ULONG (color.pixel);
7739 color.green = GREEN16_FROM_ULONG (color.pixel);
7740 color.blue = BLUE16_FROM_ULONG (color.pixel);
7742 GetMovieBox (movie, &rect);
7743 width = img->width = rect.right - rect.left;
7744 height = img->height = rect.bottom - rect.top;
7745 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7746 goto error;
7748 GetGWorld (&old_port, &old_gdh);
7749 SetGWorld (ximg, NULL);
7750 bg_color.red = color.red;
7751 bg_color.green = color.green;
7752 bg_color.blue = color.blue;
7753 RGBBackColor (&bg_color);
7754 SetGWorld (old_port, old_gdh);
7755 SetMovieActive (movie, 1);
7756 SetMovieGWorld (movie, ximg, NULL);
7757 SampleNumToMediaTime (media, ino + 1, &time, NULL);
7758 SetMovieTimeValue (movie, time);
7759 MoviesTask (movie, 0L);
7760 DisposeTrackMedia (media);
7761 DisposeMovieTrack (track);
7762 DisposeMovie (movie);
7763 if (dh)
7764 DisposeHandle (dh);
7765 /* Maybe fill in the background field while we have ximg handy. */
7766 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7767 IMAGE_BACKGROUND (img, f, ximg);
7769 /* Put the image into the pixmap. */
7770 x_put_x_image (f, ximg, img->pixmap, width, height);
7771 x_destroy_x_image (ximg);
7772 return 1;
7774 open_error:
7775 image_error ("Cannot open `%s'", file, Qnil);
7776 error:
7777 if (media)
7778 DisposeTrackMedia (media);
7779 if (track)
7780 DisposeMovieTrack (track);
7781 if (movie)
7782 DisposeMovie (movie);
7783 if (dh)
7784 DisposeHandle (dh);
7785 return 0;
7787 #endif /* MAC_OS */
7789 #endif /* HAVE_GIF */
7793 /***********************************************************************
7794 Ghostscript
7795 ***********************************************************************/
7797 #ifdef HAVE_X_WINDOWS
7798 #define HAVE_GHOSTSCRIPT 1
7799 #endif /* HAVE_X_WINDOWS */
7801 /* The symbol `postscript' identifying images of this type. */
7803 Lisp_Object Qpostscript;
7805 #ifdef HAVE_GHOSTSCRIPT
7807 static int gs_image_p P_ ((Lisp_Object object));
7808 static int gs_load P_ ((struct frame *f, struct image *img));
7809 static void gs_clear_image P_ ((struct frame *f, struct image *img));
7811 /* Keyword symbols. */
7813 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
7815 /* Indices of image specification fields in gs_format, below. */
7817 enum gs_keyword_index
7819 GS_TYPE,
7820 GS_PT_WIDTH,
7821 GS_PT_HEIGHT,
7822 GS_FILE,
7823 GS_LOADER,
7824 GS_BOUNDING_BOX,
7825 GS_ASCENT,
7826 GS_MARGIN,
7827 GS_RELIEF,
7828 GS_ALGORITHM,
7829 GS_HEURISTIC_MASK,
7830 GS_MASK,
7831 GS_BACKGROUND,
7832 GS_LAST
7835 /* Vector of image_keyword structures describing the format
7836 of valid user-defined image specifications. */
7838 static struct image_keyword gs_format[GS_LAST] =
7840 {":type", IMAGE_SYMBOL_VALUE, 1},
7841 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7842 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7843 {":file", IMAGE_STRING_VALUE, 1},
7844 {":loader", IMAGE_FUNCTION_VALUE, 0},
7845 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
7846 {":ascent", IMAGE_ASCENT_VALUE, 0},
7847 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7848 {":relief", IMAGE_INTEGER_VALUE, 0},
7849 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7850 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7851 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7852 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7855 /* Structure describing the image type `ghostscript'. */
7857 static struct image_type gs_type =
7859 &Qpostscript,
7860 gs_image_p,
7861 gs_load,
7862 gs_clear_image,
7863 NULL
7867 /* Free X resources of Ghostscript image IMG which is used on frame F. */
7869 static void
7870 gs_clear_image (f, img)
7871 struct frame *f;
7872 struct image *img;
7874 /* IMG->data.ptr_val may contain a recorded colormap. */
7875 xfree (img->data.ptr_val);
7876 x_clear_image (f, img);
7880 /* Return non-zero if OBJECT is a valid Ghostscript image
7881 specification. */
7883 static int
7884 gs_image_p (object)
7885 Lisp_Object object;
7887 struct image_keyword fmt[GS_LAST];
7888 Lisp_Object tem;
7889 int i;
7891 bcopy (gs_format, fmt, sizeof fmt);
7893 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
7894 return 0;
7896 /* Bounding box must be a list or vector containing 4 integers. */
7897 tem = fmt[GS_BOUNDING_BOX].value;
7898 if (CONSP (tem))
7900 for (i = 0; i < 4; ++i, tem = XCDR (tem))
7901 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
7902 return 0;
7903 if (!NILP (tem))
7904 return 0;
7906 else if (VECTORP (tem))
7908 if (XVECTOR (tem)->size != 4)
7909 return 0;
7910 for (i = 0; i < 4; ++i)
7911 if (!INTEGERP (XVECTOR (tem)->contents[i]))
7912 return 0;
7914 else
7915 return 0;
7917 return 1;
7921 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
7922 if successful. */
7924 static int
7925 gs_load (f, img)
7926 struct frame *f;
7927 struct image *img;
7929 char buffer[100];
7930 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
7931 struct gcpro gcpro1, gcpro2;
7932 Lisp_Object frame;
7933 double in_width, in_height;
7934 Lisp_Object pixel_colors = Qnil;
7936 /* Compute pixel size of pixmap needed from the given size in the
7937 image specification. Sizes in the specification are in pt. 1 pt
7938 = 1/72 in, xdpi and ydpi are stored in the frame's X display
7939 info. */
7940 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
7941 in_width = XFASTINT (pt_width) / 72.0;
7942 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
7943 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
7944 in_height = XFASTINT (pt_height) / 72.0;
7945 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
7947 /* Create the pixmap. */
7948 xassert (img->pixmap == NO_PIXMAP);
7950 /* Only W32 version did BLOCK_INPUT here. ++kfs */
7951 BLOCK_INPUT;
7952 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7953 img->width, img->height,
7954 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
7955 UNBLOCK_INPUT;
7957 if (!img->pixmap)
7959 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
7960 return 0;
7963 /* Call the loader to fill the pixmap. It returns a process object
7964 if successful. We do not record_unwind_protect here because
7965 other places in redisplay like calling window scroll functions
7966 don't either. Let the Lisp loader use `unwind-protect' instead. */
7967 GCPRO2 (window_and_pixmap_id, pixel_colors);
7969 sprintf (buffer, "%lu %lu",
7970 (unsigned long) FRAME_X_WINDOW (f),
7971 (unsigned long) img->pixmap);
7972 window_and_pixmap_id = build_string (buffer);
7974 sprintf (buffer, "%lu %lu",
7975 FRAME_FOREGROUND_PIXEL (f),
7976 FRAME_BACKGROUND_PIXEL (f));
7977 pixel_colors = build_string (buffer);
7979 XSETFRAME (frame, f);
7980 loader = image_spec_value (img->spec, QCloader, NULL);
7981 if (NILP (loader))
7982 loader = intern ("gs-load-image");
7984 img->data.lisp_val = call6 (loader, frame, img->spec,
7985 make_number (img->width),
7986 make_number (img->height),
7987 window_and_pixmap_id,
7988 pixel_colors);
7989 UNGCPRO;
7990 return PROCESSP (img->data.lisp_val);
7994 /* Kill the Ghostscript process that was started to fill PIXMAP on
7995 frame F. Called from XTread_socket when receiving an event
7996 telling Emacs that Ghostscript has finished drawing. */
7998 void
7999 x_kill_gs_process (pixmap, f)
8000 Pixmap pixmap;
8001 struct frame *f;
8003 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8004 int class, i;
8005 struct image *img;
8007 /* Find the image containing PIXMAP. */
8008 for (i = 0; i < c->used; ++i)
8009 if (c->images[i]->pixmap == pixmap)
8010 break;
8012 /* Should someone in between have cleared the image cache, for
8013 instance, give up. */
8014 if (i == c->used)
8015 return;
8017 /* Kill the GS process. We should have found PIXMAP in the image
8018 cache and its image should contain a process object. */
8019 img = c->images[i];
8020 xassert (PROCESSP (img->data.lisp_val));
8021 Fkill_process (img->data.lisp_val, Qnil);
8022 img->data.lisp_val = Qnil;
8024 #if defined (HAVE_X_WINDOWS)
8026 /* On displays with a mutable colormap, figure out the colors
8027 allocated for the image by looking at the pixels of an XImage for
8028 img->pixmap. */
8029 class = FRAME_X_VISUAL (f)->class;
8030 if (class != StaticColor && class != StaticGray && class != TrueColor)
8032 XImagePtr ximg;
8034 BLOCK_INPUT;
8036 /* Try to get an XImage for img->pixmep. */
8037 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8038 0, 0, img->width, img->height, ~0, ZPixmap);
8039 if (ximg)
8041 int x, y;
8043 /* Initialize the color table. */
8044 init_color_table ();
8046 /* For each pixel of the image, look its color up in the
8047 color table. After having done so, the color table will
8048 contain an entry for each color used by the image. */
8049 for (y = 0; y < img->height; ++y)
8050 for (x = 0; x < img->width; ++x)
8052 unsigned long pixel = XGetPixel (ximg, x, y);
8053 lookup_pixel_color (f, pixel);
8056 /* Record colors in the image. Free color table and XImage. */
8057 #ifdef COLOR_TABLE_SUPPORT
8058 img->colors = colors_in_color_table (&img->ncolors);
8059 free_color_table ();
8060 #endif
8061 XDestroyImage (ximg);
8063 #if 0 /* This doesn't seem to be the case. If we free the colors
8064 here, we get a BadAccess later in x_clear_image when
8065 freeing the colors. */
8066 /* We have allocated colors once, but Ghostscript has also
8067 allocated colors on behalf of us. So, to get the
8068 reference counts right, free them once. */
8069 if (img->ncolors)
8070 x_free_colors (f, img->colors, img->ncolors);
8071 #endif
8073 else
8074 image_error ("Cannot get X image of `%s'; colors will not be freed",
8075 img->spec, Qnil);
8077 UNBLOCK_INPUT;
8079 #endif /* HAVE_X_WINDOWS */
8081 /* Now that we have the pixmap, compute mask and transform the
8082 image if requested. */
8083 BLOCK_INPUT;
8084 postprocess_image (f, img);
8085 UNBLOCK_INPUT;
8088 #endif /* HAVE_GHOSTSCRIPT */
8091 /***********************************************************************
8092 Tests
8093 ***********************************************************************/
8095 #if GLYPH_DEBUG
8097 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8098 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8099 (spec)
8100 Lisp_Object spec;
8102 return valid_image_p (spec) ? Qt : Qnil;
8106 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8107 (spec)
8108 Lisp_Object spec;
8110 int id = -1;
8112 if (valid_image_p (spec))
8113 id = lookup_image (SELECTED_FRAME (), spec);
8115 debug_print (spec);
8116 return make_number (id);
8119 #endif /* GLYPH_DEBUG != 0 */
8122 /***********************************************************************
8123 Initialization
8124 ***********************************************************************/
8126 #ifdef HAVE_NTGUI
8127 /* Image types that rely on external libraries are loaded dynamically
8128 if the library is available. */
8129 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8130 define_image_type (image_type, init_lib_fn (libraries))
8131 #else
8132 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8133 define_image_type (image_type, 1)
8134 #endif /* HAVE_NTGUI */
8136 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8137 doc: /* Initialize image library implementing image type TYPE.
8138 Return non-nil if TYPE is a supported image type.
8140 Image types pbm and xbm are prebuilt; other types are loaded here.
8141 Libraries to load are specified in alist LIBRARIES (usually, the value
8142 of `image-library-alist', which see). */)
8143 (type, libraries)
8144 Lisp_Object type, libraries;
8146 Lisp_Object tested;
8148 /* Don't try to reload the library. */
8149 tested = Fassq (type, Vimage_type_cache);
8150 if (CONSP (tested))
8151 return XCDR (tested);
8153 #if defined (HAVE_XPM) || defined (MAC_OS)
8154 if (EQ (type, Qxpm))
8155 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8156 #endif
8158 #if defined (HAVE_JPEG) || defined (MAC_OS)
8159 if (EQ (type, Qjpeg))
8160 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8161 #endif
8163 #if defined (HAVE_TIFF) || defined (MAC_OS)
8164 if (EQ (type, Qtiff))
8165 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8166 #endif
8168 #if defined (HAVE_GIF) || defined (MAC_OS)
8169 if (EQ (type, Qgif))
8170 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8171 #endif
8173 #if defined (HAVE_PNG) || defined (MAC_OS)
8174 if (EQ (type, Qpng))
8175 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8176 #endif
8178 #ifdef HAVE_GHOSTSCRIPT
8179 if (EQ (type, Qpostscript))
8180 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8181 #endif
8183 /* If the type is not recognized, avoid testing it ever again. */
8184 CACHE_IMAGE_TYPE (type, Qnil);
8185 return Qnil;
8188 void
8189 syms_of_image ()
8191 extern Lisp_Object Qrisky_local_variable; /* Syms_of_xdisp has already run. */
8193 /* Initialize this only once, since that's what we do with Vimage_types
8194 and they are supposed to be in sync. Initializing here gives correct
8195 operation on GNU/Linux of calling dump-emacs after loading some images. */
8196 image_types = NULL;
8198 /* Must be defined now becase we're going to update it below, while
8199 defining the supported image types. */
8200 DEFVAR_LISP ("image-types", &Vimage_types,
8201 doc: /* List of potentially supported image types.
8202 Each element of the list is a symbol for a image type, like 'jpeg or 'png.
8203 To check whether it is really supported, use `image-type-available-p'. */);
8204 Vimage_types = Qnil;
8206 DEFVAR_LISP ("image-library-alist", &Vimage_library_alist,
8207 doc: /* Alist of image types vs external libraries needed to display them.
8209 Each element is a list (IMAGE-TYPE LIBRARY...), where the car is a symbol
8210 representing a supported image type, and the rest are strings giving
8211 alternate filenames for the corresponding external libraries.
8213 Emacs tries to load the libraries in the order they appear on the
8214 list; if none is loaded, the running session of Emacs won't
8215 support the image type. Types 'pbm and 'xbm don't need to be
8216 listed; they're always supported. */);
8217 Vimage_library_alist = Qnil;
8218 Fput (intern ("image-library-alist"), Qrisky_local_variable, Qt);
8220 Vimage_type_cache = Qnil;
8221 staticpro (&Vimage_type_cache);
8223 Qpbm = intern ("pbm");
8224 staticpro (&Qpbm);
8225 ADD_IMAGE_TYPE(Qpbm);
8227 Qxbm = intern ("xbm");
8228 staticpro (&Qxbm);
8229 ADD_IMAGE_TYPE(Qxbm);
8231 define_image_type (&xbm_type, 1);
8232 define_image_type (&pbm_type, 1);
8234 QCascent = intern (":ascent");
8235 staticpro (&QCascent);
8236 QCmargin = intern (":margin");
8237 staticpro (&QCmargin);
8238 QCrelief = intern (":relief");
8239 staticpro (&QCrelief);
8240 QCconversion = intern (":conversion");
8241 staticpro (&QCconversion);
8242 QCcolor_symbols = intern (":color-symbols");
8243 staticpro (&QCcolor_symbols);
8244 QCheuristic_mask = intern (":heuristic-mask");
8245 staticpro (&QCheuristic_mask);
8246 QCindex = intern (":index");
8247 staticpro (&QCindex);
8248 QCmatrix = intern (":matrix");
8249 staticpro (&QCmatrix);
8250 QCcolor_adjustment = intern (":color-adjustment");
8251 staticpro (&QCcolor_adjustment);
8252 QCmask = intern (":mask");
8253 staticpro (&QCmask);
8255 Qlaplace = intern ("laplace");
8256 staticpro (&Qlaplace);
8257 Qemboss = intern ("emboss");
8258 staticpro (&Qemboss);
8259 Qedge_detection = intern ("edge-detection");
8260 staticpro (&Qedge_detection);
8261 Qheuristic = intern ("heuristic");
8262 staticpro (&Qheuristic);
8264 Qpostscript = intern ("postscript");
8265 staticpro (&Qpostscript);
8266 #ifdef HAVE_GHOSTSCRIPT
8267 ADD_IMAGE_TYPE(Qpostscript);
8268 QCloader = intern (":loader");
8269 staticpro (&QCloader);
8270 QCbounding_box = intern (":bounding-box");
8271 staticpro (&QCbounding_box);
8272 QCpt_width = intern (":pt-width");
8273 staticpro (&QCpt_width);
8274 QCpt_height = intern (":pt-height");
8275 staticpro (&QCpt_height);
8276 #endif /* HAVE_GHOSTSCRIPT */
8278 #if defined (HAVE_XPM) || defined (MAC_OS)
8279 Qxpm = intern ("xpm");
8280 staticpro (&Qxpm);
8281 ADD_IMAGE_TYPE(Qxpm);
8282 #endif
8284 #if defined (HAVE_JPEG) || defined (MAC_OS)
8285 Qjpeg = intern ("jpeg");
8286 staticpro (&Qjpeg);
8287 ADD_IMAGE_TYPE(Qjpeg);
8288 #endif
8290 #if defined (HAVE_TIFF) || defined (MAC_OS)
8291 Qtiff = intern ("tiff");
8292 staticpro (&Qtiff);
8293 ADD_IMAGE_TYPE(Qtiff);
8294 #endif
8296 #if defined (HAVE_GIF) || defined (MAC_OS)
8297 Qgif = intern ("gif");
8298 staticpro (&Qgif);
8299 ADD_IMAGE_TYPE(Qgif);
8300 #endif
8302 #if defined (HAVE_PNG) || defined (MAC_OS)
8303 Qpng = intern ("png");
8304 staticpro (&Qpng);
8305 ADD_IMAGE_TYPE(Qpng);
8306 #endif
8308 defsubr (&Sinit_image_library);
8309 defsubr (&Sclear_image_cache);
8310 defsubr (&Simage_size);
8311 defsubr (&Simage_mask_p);
8313 #if GLYPH_DEBUG
8314 defsubr (&Simagep);
8315 defsubr (&Slookup_image);
8316 #endif
8318 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
8319 doc: /* Non-nil means always draw a cross over disabled images.
8320 Disabled images are those having an `:conversion disabled' property.
8321 A cross is always drawn on black & white displays. */);
8322 cross_disabled_images = 0;
8324 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
8325 doc: /* List of directories to search for window system bitmap files. */);
8326 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8328 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
8329 doc: /* Time after which cached images are removed from the cache.
8330 When an image has not been displayed this many seconds, remove it
8331 from the image cache. Value must be an integer or nil with nil
8332 meaning don't clear the cache. */);
8333 Vimage_cache_eviction_delay = make_number (30 * 60);
8336 void
8337 init_image ()
8339 #ifdef MAC_OS
8340 /* Animated gifs use QuickTime Movie Toolbox. So initialize it here. */
8341 EnterMovies ();
8342 #ifdef MAC_OSX
8343 init_image_func_pointer ();
8344 #endif
8345 #endif
8348 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
8349 (do not change this comment) */