(XDrawLine, XCreatePixmapFromBitmapData) [USE_MAC_IMAGE_IO]:
[emacs.git] / src / image.c
blob9981b21365a980b3c3d4d9fe9f37fce17ecce5eb
1 /* Functions for image support on window system.
2 Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs; see the file COPYING. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
23 #include <config.h>
24 #include <stdio.h>
25 #include <math.h>
26 #include <ctype.h>
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
32 /* This makes the fields of a Display accessible, in Xlib header files. */
34 #define XLIB_ILLEGAL_ACCESS
36 #include "lisp.h"
37 #include "frame.h"
38 #include "window.h"
39 #include "dispextern.h"
40 #include "blockinput.h"
41 #include "systime.h"
42 #include <epaths.h>
43 #include "charset.h"
44 #include "coding.h"
47 #ifdef HAVE_X_WINDOWS
48 #include "xterm.h"
49 #include <sys/types.h>
50 #include <sys/stat.h>
52 #define COLOR_TABLE_SUPPORT 1
54 typedef struct x_bitmap_record Bitmap_Record;
55 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
56 #define NO_PIXMAP None
58 #define RGB_PIXEL_COLOR unsigned long
60 #define PIX_MASK_RETAIN 0
61 #define PIX_MASK_DRAW 1
62 #endif /* HAVE_X_WINDOWS */
65 #ifdef HAVE_NTGUI
66 #include "w32term.h"
68 /* W32_TODO : Color tables on W32. */
69 #undef COLOR_TABLE_SUPPORT
71 typedef struct w32_bitmap_record Bitmap_Record;
72 #define GET_PIXEL(ximg, x, y) GetPixel(ximg, x, y)
73 #define NO_PIXMAP 0
75 #define RGB_PIXEL_COLOR COLORREF
77 #define PIX_MASK_RETAIN 0
78 #define PIX_MASK_DRAW 1
80 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
81 #define x_defined_color w32_defined_color
82 #define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
83 #endif /* HAVE_NTGUI */
86 #ifdef MAC_OS
87 #include "macterm.h"
88 #include <sys/stat.h>
89 #ifndef MAC_OSX
90 #include <alloca.h>
91 #include <sys/param.h>
92 #endif
93 #if TARGET_API_MAC_CARBON
94 #ifdef MAC_OSX
95 #include <QuickTime/QuickTime.h>
96 #else /* not MAC_OSX */
97 #include <QuickTime.h>
98 #endif /* not MAC_OSX */
99 #else /* not TARGET_API_MAC_CARBON */
100 #include <Windows.h>
101 #include <Gestalt.h>
102 #include <TextUtils.h>
103 #include <ImageCompression.h>
104 #include <QuickTimeComponents.h>
105 #endif /* not TARGET_API_MAC_CARBON */
107 /* MAC_TODO : Color tables on Mac. */
108 #undef COLOR_TABLE_SUPPORT
110 #define ZPixmap 0 /* arbitrary */
111 typedef struct mac_bitmap_record Bitmap_Record;
113 #define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
114 #define NO_PIXMAP 0
116 #define RGB_PIXEL_COLOR unsigned long
118 #if USE_MAC_IMAGE_IO
119 #define PIX_MASK_DRAW 255
120 #define PIX_MASK_RETAIN 0
121 #else
122 /* A black pixel in a mask bitmap/pixmap means ``draw a source
123 pixel''. A white pixel means ``retain the current pixel''. */
124 #define PIX_MASK_DRAW RGB_TO_ULONG(0,0,0)
125 #define PIX_MASK_RETAIN RGB_TO_ULONG(255,255,255)
126 #endif
128 #define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
129 #define x_defined_color mac_defined_color
130 #define DefaultDepthOfScreen(screen) (one_mac_display_info.n_planes)
132 #endif /* MAC_OS */
135 /* Search path for bitmap files. */
137 Lisp_Object Vx_bitmap_file_path;
140 static void x_disable_image P_ ((struct frame *, struct image *));
141 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
142 Lisp_Object));
144 static void init_color_table P_ ((void));
145 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
146 #ifdef COLOR_TABLE_SUPPORT
147 static void free_color_table P_ ((void));
148 static unsigned long *colors_in_color_table P_ ((int *n));
149 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
150 #endif
152 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
153 id, which is just an int that this section returns. Bitmaps are
154 reference counted so they can be shared among frames.
156 Bitmap indices are guaranteed to be > 0, so a negative number can
157 be used to indicate no bitmap.
159 If you use x_create_bitmap_from_data, then you must keep track of
160 the bitmaps yourself. That is, creating a bitmap from the same
161 data more than once will not be caught. */
163 #ifdef MAC_OS
165 static XImagePtr
166 XGetImage (display, pixmap, x, y, width, height, plane_mask, format)
167 Display *display; /* not used */
168 Pixmap pixmap;
169 int x, y; /* not used */
170 unsigned int width, height; /* not used */
171 unsigned long plane_mask; /* not used */
172 int format; /* not used */
174 #if !USE_MAC_IMAGE_IO
175 #if GLYPH_DEBUG
176 xassert (x == 0 && y == 0);
178 Rect ri, rp;
179 SetRect (&ri, 0, 0, width, height);
180 xassert (EqualRect (&ri, GetPixBounds (GetGWorldPixMap (pixmap), &rp)));
182 xassert (! (pixelsLocked & GetPixelsState (GetGWorldPixMap (pixmap))));
183 #endif
185 LockPixels (GetGWorldPixMap (pixmap));
186 #endif
188 return pixmap;
191 static void
192 XPutPixel (ximage, x, y, pixel)
193 XImagePtr ximage;
194 int x, y;
195 unsigned long pixel;
197 #if USE_MAC_IMAGE_IO
198 if (ximage->bits_per_pixel == 32)
199 ((unsigned int *)(ximage->data + y * ximage->bytes_per_line))[x] = pixel;
200 else
201 ((unsigned char *)(ximage->data + y * ximage->bytes_per_line))[x] = pixel;
202 #else
203 PixMapHandle pixmap = GetGWorldPixMap (ximage);
204 short depth = GetPixDepth (pixmap);
206 #if defined (WORDS_BIG_ENDIAN) || !USE_CG_DRAWING
207 if (depth == 32)
209 char *base_addr = GetPixBaseAddr (pixmap);
210 short row_bytes = GetPixRowBytes (pixmap);
212 ((unsigned long *) (base_addr + y * row_bytes))[x] = 0xff000000 | pixel;
214 else
215 #endif
216 if (depth == 1)
218 char *base_addr = GetPixBaseAddr (pixmap);
219 short row_bytes = GetPixRowBytes (pixmap);
221 if (pixel == PIX_MASK_DRAW)
222 base_addr[y * row_bytes + x / 8] |= (1 << 7) >> (x & 7);
223 else
224 base_addr[y * row_bytes + x / 8] &= ~((1 << 7) >> (x & 7));
226 else
228 CGrafPtr old_port;
229 GDHandle old_gdh;
230 RGBColor color;
232 GetGWorld (&old_port, &old_gdh);
233 SetGWorld (ximage, NULL);
235 color.red = RED16_FROM_ULONG (pixel);
236 color.green = GREEN16_FROM_ULONG (pixel);
237 color.blue = BLUE16_FROM_ULONG (pixel);
239 SetCPixel (x, y, &color);
241 SetGWorld (old_port, old_gdh);
243 #endif
246 static unsigned long
247 XGetPixel (ximage, x, y)
248 XImagePtr ximage;
249 int x, y;
251 #if USE_MAC_IMAGE_IO
252 if (ximage->bits_per_pixel == 32)
253 return ((unsigned int *)(ximage->data + y * ximage->bytes_per_line))[x];
254 else
255 return ((unsigned char *)(ximage->data + y * ximage->bytes_per_line))[x];
256 #else
257 PixMapHandle pixmap = GetGWorldPixMap (ximage);
258 short depth = GetPixDepth (pixmap);
260 #if defined (WORDS_BIG_ENDIAN) || !USE_CG_DRAWING
261 if (depth == 32)
263 char *base_addr = GetPixBaseAddr (pixmap);
264 short row_bytes = GetPixRowBytes (pixmap);
266 return ((unsigned long *) (base_addr + y * row_bytes))[x] & 0x00ffffff;
268 else
269 #endif
270 if (depth == 1)
272 char *base_addr = GetPixBaseAddr (pixmap);
273 short row_bytes = GetPixRowBytes (pixmap);
275 if (base_addr[y * row_bytes + x / 8] & (1 << (~x & 7)))
276 return PIX_MASK_DRAW;
277 else
278 return PIX_MASK_RETAIN;
280 else
282 CGrafPtr old_port;
283 GDHandle old_gdh;
284 RGBColor color;
286 GetGWorld (&old_port, &old_gdh);
287 SetGWorld (ximage, NULL);
289 GetCPixel (x, y, &color);
291 SetGWorld (old_port, old_gdh);
292 return RGB_TO_ULONG (color.red >> 8, color.green >> 8, color.blue >> 8);
294 #endif
297 static void
298 XDestroyImage (ximg)
299 XImagePtr ximg;
301 #if !USE_MAC_IMAGE_IO
302 UnlockPixels (GetGWorldPixMap (ximg));
303 #endif
306 #if USE_CG_DRAWING
307 #if USE_MAC_IMAGE_IO
308 void
309 mac_data_provider_release_data (info, data, size)
310 void *info;
311 const void *data;
312 size_t size;
314 xfree ((void *)data);
316 #endif
318 static CGImageRef
319 mac_create_cg_image_from_image (f, img)
320 struct frame *f;
321 struct image *img;
323 #if USE_MAC_IMAGE_IO
324 XImagePtr ximg = img->pixmap;
325 CGDataProviderRef provider;
326 CGImageRef result;
328 if (img->mask)
330 int x, y;
331 unsigned long color, alpha;
333 for (y = 0; y < ximg->height; y++)
334 for (x = 0; x < ximg->width; x++)
336 color = XGetPixel (ximg, x, y);
337 alpha = XGetPixel (img->mask, x, y);
338 XPutPixel (ximg, x, y,
339 ARGB_TO_ULONG (alpha,
340 RED_FROM_ULONG (color)
341 * alpha / PIX_MASK_DRAW,
342 GREEN_FROM_ULONG (color)
343 * alpha / PIX_MASK_DRAW,
344 BLUE_FROM_ULONG (color)
345 * alpha / PIX_MASK_DRAW));
347 xfree (img->mask->data);
348 img->mask->data = NULL;
350 BLOCK_INPUT;
351 provider = CGDataProviderCreateWithData (NULL, ximg->data,
352 ximg->bytes_per_line * ximg->height,
353 mac_data_provider_release_data);
354 ximg->data = NULL;
355 result = CGImageCreate (ximg->width, ximg->height, 8, 32,
356 ximg->bytes_per_line, mac_cg_color_space_rgb,
357 (img->mask ? kCGImageAlphaPremultipliedFirst
358 : kCGImageAlphaNoneSkipFirst)
359 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1040
360 | kCGBitmapByteOrder32Host
361 #endif
362 , provider, NULL, 0, kCGRenderingIntentDefault);
363 CGDataProviderRelease (provider);
364 UNBLOCK_INPUT;
366 return result;
367 #else
368 Pixmap mask;
369 CGImageRef result = NULL;
371 BLOCK_INPUT;
372 if (img->mask)
373 mask = img->mask;
374 else
376 mask = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
377 img->width, img->height, 1);
378 if (mask)
380 CGrafPtr old_port;
381 GDHandle old_gdh;
382 Rect r;
384 GetGWorld (&old_port, &old_gdh);
385 SetGWorld (mask, NULL);
386 BackColor (blackColor); /* Don't mask. */
387 SetRect (&r, 0, 0, img->width, img->height);
388 EraseRect (&r);
389 SetGWorld (old_port, old_gdh);
392 if (mask)
394 CreateCGImageFromPixMaps (GetGWorldPixMap (img->pixmap),
395 GetGWorldPixMap (mask), &result);
396 if (mask != img->mask)
397 XFreePixmap (FRAME_X_DISPLAY (f), mask);
399 UNBLOCK_INPUT;
401 return result;
402 #endif
404 #endif /* USE_CG_DRAWING */
405 #endif /* MAC_OS */
408 /* Functions to access the contents of a bitmap, given an id. */
411 x_bitmap_height (f, id)
412 FRAME_PTR f;
413 int id;
415 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
419 x_bitmap_width (f, id)
420 FRAME_PTR f;
421 int id;
423 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
426 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
428 x_bitmap_pixmap (f, id)
429 FRAME_PTR f;
430 int id;
432 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
434 #endif
436 #ifdef HAVE_X_WINDOWS
438 x_bitmap_mask (f, id)
439 FRAME_PTR f;
440 int id;
442 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
444 #endif
446 /* Allocate a new bitmap record. Returns index of new record. */
448 static int
449 x_allocate_bitmap_record (f)
450 FRAME_PTR f;
452 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
453 int i;
455 if (dpyinfo->bitmaps == NULL)
457 dpyinfo->bitmaps_size = 10;
458 dpyinfo->bitmaps
459 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
460 dpyinfo->bitmaps_last = 1;
461 return 1;
464 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
465 return ++dpyinfo->bitmaps_last;
467 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
468 if (dpyinfo->bitmaps[i].refcount == 0)
469 return i + 1;
471 dpyinfo->bitmaps_size *= 2;
472 dpyinfo->bitmaps
473 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
474 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
475 return ++dpyinfo->bitmaps_last;
478 /* Add one reference to the reference count of the bitmap with id ID. */
480 void
481 x_reference_bitmap (f, id)
482 FRAME_PTR f;
483 int id;
485 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
488 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
491 x_create_bitmap_from_data (f, bits, width, height)
492 struct frame *f;
493 char *bits;
494 unsigned int width, height;
496 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
497 int id;
499 #ifdef HAVE_X_WINDOWS
500 Pixmap bitmap;
501 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
502 bits, width, height);
503 if (! bitmap)
504 return -1;
505 #endif /* HAVE_X_WINDOWS */
507 #ifdef HAVE_NTGUI
508 Pixmap bitmap;
509 bitmap = CreateBitmap (width, height,
510 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
511 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
512 bits);
513 if (! bitmap)
514 return -1;
515 #endif /* HAVE_NTGUI */
517 #ifdef MAC_OS
518 /* MAC_TODO: for now fail if width is not mod 16 (toolbox requires it) */
519 if (width % 16 != 0)
520 return -1;
521 #endif
523 id = x_allocate_bitmap_record (f);
524 #ifdef MAC_OS
525 dpyinfo->bitmaps[id - 1].bitmap_data = (char *) xmalloc (height * width);
526 bcopy (bits, dpyinfo->bitmaps[id - 1].bitmap_data, height * width);
527 #endif /* MAC_OS */
529 dpyinfo->bitmaps[id - 1].file = NULL;
530 dpyinfo->bitmaps[id - 1].height = height;
531 dpyinfo->bitmaps[id - 1].width = width;
532 dpyinfo->bitmaps[id - 1].refcount = 1;
534 #ifdef HAVE_X_WINDOWS
535 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
536 dpyinfo->bitmaps[id - 1].have_mask = 0;
537 dpyinfo->bitmaps[id - 1].depth = 1;
538 #endif /* HAVE_X_WINDOWS */
540 #ifdef HAVE_NTGUI
541 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
542 dpyinfo->bitmaps[id - 1].hinst = NULL;
543 dpyinfo->bitmaps[id - 1].depth = 1;
544 #endif /* HAVE_NTGUI */
546 return id;
549 /* Create bitmap from file FILE for frame F. */
552 x_create_bitmap_from_file (f, file)
553 struct frame *f;
554 Lisp_Object file;
556 #ifdef MAC_OS
557 return -1; /* MAC_TODO : bitmap support */
558 #endif /* MAC_OS */
560 #ifdef HAVE_NTGUI
561 return -1; /* W32_TODO : bitmap support */
562 #endif /* HAVE_NTGUI */
564 #ifdef HAVE_X_WINDOWS
565 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
566 unsigned int width, height;
567 Pixmap bitmap;
568 int xhot, yhot, result, id;
569 Lisp_Object found;
570 int fd;
571 char *filename;
573 /* Look for an existing bitmap with the same name. */
574 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
576 if (dpyinfo->bitmaps[id].refcount
577 && dpyinfo->bitmaps[id].file
578 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
580 ++dpyinfo->bitmaps[id].refcount;
581 return id + 1;
585 /* Search bitmap-file-path for the file, if appropriate. */
586 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
587 if (fd < 0)
588 return -1;
589 emacs_close (fd);
591 filename = (char *) SDATA (found);
593 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
594 filename, &width, &height, &bitmap, &xhot, &yhot);
595 if (result != BitmapSuccess)
596 return -1;
598 id = x_allocate_bitmap_record (f);
599 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
600 dpyinfo->bitmaps[id - 1].have_mask = 0;
601 dpyinfo->bitmaps[id - 1].refcount = 1;
602 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
603 dpyinfo->bitmaps[id - 1].depth = 1;
604 dpyinfo->bitmaps[id - 1].height = height;
605 dpyinfo->bitmaps[id - 1].width = width;
606 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
608 return id;
609 #endif /* HAVE_X_WINDOWS */
612 /* Free bitmap B. */
614 static void
615 Free_Bitmap_Record (dpyinfo, bm)
616 Display_Info *dpyinfo;
617 Bitmap_Record *bm;
619 #ifdef HAVE_X_WINDOWS
620 XFreePixmap (dpyinfo->display, bm->pixmap);
621 if (bm->have_mask)
622 XFreePixmap (dpyinfo->display, bm->mask);
623 #endif /* HAVE_X_WINDOWS */
625 #ifdef HAVE_NTGUI
626 DeleteObject (bm->pixmap);
627 #endif /* HAVE_NTGUI */
629 #ifdef MAC_OS
630 xfree (bm->bitmap_data); /* Added ++kfs */
631 bm->bitmap_data = NULL;
632 #endif /* MAC_OS */
634 if (bm->file)
636 xfree (bm->file);
637 bm->file = NULL;
641 /* Remove reference to bitmap with id number ID. */
643 void
644 x_destroy_bitmap (f, id)
645 FRAME_PTR f;
646 int id;
648 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
650 if (id > 0)
652 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
654 if (--bm->refcount == 0)
656 BLOCK_INPUT;
657 Free_Bitmap_Record (dpyinfo, bm);
658 UNBLOCK_INPUT;
663 /* Free all the bitmaps for the display specified by DPYINFO. */
665 void
666 x_destroy_all_bitmaps (dpyinfo)
667 Display_Info *dpyinfo;
669 int i;
670 Bitmap_Record *bm = dpyinfo->bitmaps;
672 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
673 if (bm->refcount > 0)
674 Free_Bitmap_Record (dpyinfo, bm);
676 dpyinfo->bitmaps_last = 0;
680 #ifdef HAVE_X_WINDOWS
682 /* Useful functions defined in the section
683 `Image type independent image structures' below. */
685 static unsigned long four_corners_best P_ ((XImagePtr ximg,
686 int *corners,
687 unsigned long width,
688 unsigned long height));
690 static int x_create_x_image_and_pixmap P_ ((struct frame *f, int width, int height,
691 int depth, XImagePtr *ximg,
692 Pixmap *pixmap));
694 static void x_destroy_x_image P_ ((XImagePtr ximg));
697 /* Create a mask of a bitmap. Note is this not a perfect mask.
698 It's nicer with some borders in this context */
701 x_create_bitmap_mask (f, id)
702 struct frame *f;
703 int id;
705 Pixmap pixmap, mask;
706 XImagePtr ximg, mask_img;
707 unsigned long width, height;
708 int result;
709 unsigned long bg;
710 unsigned long x, y, xp, xm, yp, ym;
711 GC gc;
713 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
715 if (!(id > 0))
716 return -1;
718 pixmap = x_bitmap_pixmap (f, id);
719 width = x_bitmap_width (f, id);
720 height = x_bitmap_height (f, id);
722 BLOCK_INPUT;
723 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
724 ~0, ZPixmap);
726 if (!ximg)
728 UNBLOCK_INPUT;
729 return -1;
732 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
734 UNBLOCK_INPUT;
735 if (!result)
737 XDestroyImage (ximg);
738 return -1;
741 bg = four_corners_best (ximg, NULL, width, height);
743 for (y = 0; y < ximg->height; ++y)
745 for (x = 0; x < ximg->width; ++x)
747 xp = x != ximg->width - 1 ? x + 1 : 0;
748 xm = x != 0 ? x - 1 : ximg->width - 1;
749 yp = y != ximg->height - 1 ? y + 1 : 0;
750 ym = y != 0 ? y - 1 : ximg->height - 1;
751 if (XGetPixel (ximg, x, y) == bg
752 && XGetPixel (ximg, x, yp) == bg
753 && XGetPixel (ximg, x, ym) == bg
754 && XGetPixel (ximg, xp, y) == bg
755 && XGetPixel (ximg, xp, yp) == bg
756 && XGetPixel (ximg, xp, ym) == bg
757 && XGetPixel (ximg, xm, y) == bg
758 && XGetPixel (ximg, xm, yp) == bg
759 && XGetPixel (ximg, xm, ym) == bg)
760 XPutPixel (mask_img, x, y, 0);
761 else
762 XPutPixel (mask_img, x, y, 1);
766 xassert (interrupt_input_blocked);
767 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
768 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
769 width, height);
770 XFreeGC (FRAME_X_DISPLAY (f), gc);
772 dpyinfo->bitmaps[id - 1].have_mask = 1;
773 dpyinfo->bitmaps[id - 1].mask = mask;
775 XDestroyImage (ximg);
776 x_destroy_x_image (mask_img);
778 return 0;
781 #endif /* HAVE_X_WINDOWS */
784 /***********************************************************************
785 Image types
786 ***********************************************************************/
788 /* Value is the number of elements of vector VECTOR. */
790 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
792 /* List of supported image types. Use define_image_type to add new
793 types. Use lookup_image_type to find a type for a given symbol. */
795 static struct image_type *image_types;
797 /* A list of symbols, one for each supported image type. */
799 Lisp_Object Vimage_types;
801 /* An alist of image types and libraries that implement the type. */
803 Lisp_Object Vimage_library_alist;
805 /* Cache for delayed-loading image types. */
807 static Lisp_Object Vimage_type_cache;
809 /* The symbol `xbm' which is used as the type symbol for XBM images. */
811 Lisp_Object Qxbm;
813 /* Keywords. */
815 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
816 extern Lisp_Object QCdata, QCtype, Qcount;
817 extern Lisp_Object Qcenter;
818 Lisp_Object QCascent, QCmargin, QCrelief;
819 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
820 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
822 /* Other symbols. */
824 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
826 /* Time in seconds after which images should be removed from the cache
827 if not displayed. */
829 Lisp_Object Vimage_cache_eviction_delay;
831 /* Function prototypes. */
833 static Lisp_Object define_image_type P_ ((struct image_type *type, int loaded));
834 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
835 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
836 static void x_laplace P_ ((struct frame *, struct image *));
837 static void x_emboss P_ ((struct frame *, struct image *));
838 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
839 Lisp_Object));
841 #define CACHE_IMAGE_TYPE(type, status) \
842 do { Vimage_type_cache = Fcons (Fcons (type, status), Vimage_type_cache); } while (0)
844 #define ADD_IMAGE_TYPE(type) \
845 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
847 /* Define a new image type from TYPE. This adds a copy of TYPE to
848 image_types and caches the loading status of TYPE. */
850 static Lisp_Object
851 define_image_type (type, loaded)
852 struct image_type *type;
853 int loaded;
855 Lisp_Object success;
857 if (!loaded)
858 success = Qnil;
859 else
861 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
862 The initialized data segment is read-only. */
863 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
864 bcopy (type, p, sizeof *p);
865 p->next = image_types;
866 image_types = p;
867 success = Qt;
870 CACHE_IMAGE_TYPE (*type->type, success);
871 return success;
875 /* Look up image type SYMBOL, and return a pointer to its image_type
876 structure. Value is null if SYMBOL is not a known image type. */
878 static INLINE struct image_type *
879 lookup_image_type (symbol)
880 Lisp_Object symbol;
882 struct image_type *type;
884 /* We must initialize the image-type if it hasn't been already. */
885 if (NILP (Finit_image_library (symbol, Vimage_library_alist)))
886 return 0; /* unimplemented */
888 for (type = image_types; type; type = type->next)
889 if (EQ (symbol, *type->type))
890 break;
892 return type;
896 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
897 valid image specification is a list whose car is the symbol
898 `image', and whose rest is a property list. The property list must
899 contain a value for key `:type'. That value must be the name of a
900 supported image type. The rest of the property list depends on the
901 image type. */
904 valid_image_p (object)
905 Lisp_Object object;
907 int valid_p = 0;
909 if (IMAGEP (object))
911 Lisp_Object tem;
913 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
914 if (EQ (XCAR (tem), QCtype))
916 tem = XCDR (tem);
917 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
919 struct image_type *type;
920 type = lookup_image_type (XCAR (tem));
921 if (type)
922 valid_p = type->valid_p (object);
925 break;
929 return valid_p;
933 /* Log error message with format string FORMAT and argument ARG.
934 Signaling an error, e.g. when an image cannot be loaded, is not a
935 good idea because this would interrupt redisplay, and the error
936 message display would lead to another redisplay. This function
937 therefore simply displays a message. */
939 static void
940 image_error (format, arg1, arg2)
941 char *format;
942 Lisp_Object arg1, arg2;
944 add_to_log (format, arg1, arg2);
949 /***********************************************************************
950 Image specifications
951 ***********************************************************************/
953 enum image_value_type
955 IMAGE_DONT_CHECK_VALUE_TYPE,
956 IMAGE_STRING_VALUE,
957 IMAGE_STRING_OR_NIL_VALUE,
958 IMAGE_SYMBOL_VALUE,
959 IMAGE_POSITIVE_INTEGER_VALUE,
960 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
961 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
962 IMAGE_ASCENT_VALUE,
963 IMAGE_INTEGER_VALUE,
964 IMAGE_FUNCTION_VALUE,
965 IMAGE_NUMBER_VALUE,
966 IMAGE_BOOL_VALUE
969 /* Structure used when parsing image specifications. */
971 struct image_keyword
973 /* Name of keyword. */
974 char *name;
976 /* The type of value allowed. */
977 enum image_value_type type;
979 /* Non-zero means key must be present. */
980 int mandatory_p;
982 /* Used to recognize duplicate keywords in a property list. */
983 int count;
985 /* The value that was found. */
986 Lisp_Object value;
990 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
991 int, Lisp_Object));
992 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
995 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
996 has the format (image KEYWORD VALUE ...). One of the keyword/
997 value pairs must be `:type TYPE'. KEYWORDS is a vector of
998 image_keywords structures of size NKEYWORDS describing other
999 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
1001 static int
1002 parse_image_spec (spec, keywords, nkeywords, type)
1003 Lisp_Object spec;
1004 struct image_keyword *keywords;
1005 int nkeywords;
1006 Lisp_Object type;
1008 int i;
1009 Lisp_Object plist;
1011 if (!IMAGEP (spec))
1012 return 0;
1014 plist = XCDR (spec);
1015 while (CONSP (plist))
1017 Lisp_Object key, value;
1019 /* First element of a pair must be a symbol. */
1020 key = XCAR (plist);
1021 plist = XCDR (plist);
1022 if (!SYMBOLP (key))
1023 return 0;
1025 /* There must follow a value. */
1026 if (!CONSP (plist))
1027 return 0;
1028 value = XCAR (plist);
1029 plist = XCDR (plist);
1031 /* Find key in KEYWORDS. Error if not found. */
1032 for (i = 0; i < nkeywords; ++i)
1033 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
1034 break;
1036 if (i == nkeywords)
1037 continue;
1039 /* Record that we recognized the keyword. If a keywords
1040 was found more than once, it's an error. */
1041 keywords[i].value = value;
1042 ++keywords[i].count;
1044 if (keywords[i].count > 1)
1045 return 0;
1047 /* Check type of value against allowed type. */
1048 switch (keywords[i].type)
1050 case IMAGE_STRING_VALUE:
1051 if (!STRINGP (value))
1052 return 0;
1053 break;
1055 case IMAGE_STRING_OR_NIL_VALUE:
1056 if (!STRINGP (value) && !NILP (value))
1057 return 0;
1058 break;
1060 case IMAGE_SYMBOL_VALUE:
1061 if (!SYMBOLP (value))
1062 return 0;
1063 break;
1065 case IMAGE_POSITIVE_INTEGER_VALUE:
1066 if (!INTEGERP (value) || XINT (value) <= 0)
1067 return 0;
1068 break;
1070 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
1071 if (INTEGERP (value) && XINT (value) >= 0)
1072 break;
1073 if (CONSP (value)
1074 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
1075 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
1076 break;
1077 return 0;
1079 case IMAGE_ASCENT_VALUE:
1080 if (SYMBOLP (value) && EQ (value, Qcenter))
1081 break;
1082 else if (INTEGERP (value)
1083 && XINT (value) >= 0
1084 && XINT (value) <= 100)
1085 break;
1086 return 0;
1088 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
1089 if (!INTEGERP (value) || XINT (value) < 0)
1090 return 0;
1091 break;
1093 case IMAGE_DONT_CHECK_VALUE_TYPE:
1094 break;
1096 case IMAGE_FUNCTION_VALUE:
1097 value = indirect_function (value);
1098 if (SUBRP (value)
1099 || COMPILEDP (value)
1100 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
1101 break;
1102 return 0;
1104 case IMAGE_NUMBER_VALUE:
1105 if (!INTEGERP (value) && !FLOATP (value))
1106 return 0;
1107 break;
1109 case IMAGE_INTEGER_VALUE:
1110 if (!INTEGERP (value))
1111 return 0;
1112 break;
1114 case IMAGE_BOOL_VALUE:
1115 if (!NILP (value) && !EQ (value, Qt))
1116 return 0;
1117 break;
1119 default:
1120 abort ();
1121 break;
1124 if (EQ (key, QCtype) && !EQ (type, value))
1125 return 0;
1128 /* Check that all mandatory fields are present. */
1129 for (i = 0; i < nkeywords; ++i)
1130 if (keywords[i].mandatory_p && keywords[i].count == 0)
1131 return 0;
1133 return NILP (plist);
1137 /* Return the value of KEY in image specification SPEC. Value is nil
1138 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
1139 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
1141 static Lisp_Object
1142 image_spec_value (spec, key, found)
1143 Lisp_Object spec, key;
1144 int *found;
1146 Lisp_Object tail;
1148 xassert (valid_image_p (spec));
1150 for (tail = XCDR (spec);
1151 CONSP (tail) && CONSP (XCDR (tail));
1152 tail = XCDR (XCDR (tail)))
1154 if (EQ (XCAR (tail), key))
1156 if (found)
1157 *found = 1;
1158 return XCAR (XCDR (tail));
1162 if (found)
1163 *found = 0;
1164 return Qnil;
1168 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
1169 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
1170 PIXELS non-nil means return the size in pixels, otherwise return the
1171 size in canonical character units.
1172 FRAME is the frame on which the image will be displayed. FRAME nil
1173 or omitted means use the selected frame. */)
1174 (spec, pixels, frame)
1175 Lisp_Object spec, pixels, frame;
1177 Lisp_Object size;
1179 size = Qnil;
1180 if (valid_image_p (spec))
1182 struct frame *f = check_x_frame (frame);
1183 int id = lookup_image (f, spec);
1184 struct image *img = IMAGE_FROM_ID (f, id);
1185 int width = img->width + 2 * img->hmargin;
1186 int height = img->height + 2 * img->vmargin;
1188 if (NILP (pixels))
1189 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
1190 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
1191 else
1192 size = Fcons (make_number (width), make_number (height));
1194 else
1195 error ("Invalid image specification");
1197 return size;
1201 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
1202 doc: /* Return t if image SPEC has a mask bitmap.
1203 FRAME is the frame on which the image will be displayed. FRAME nil
1204 or omitted means use the selected frame. */)
1205 (spec, frame)
1206 Lisp_Object spec, frame;
1208 Lisp_Object mask;
1210 mask = Qnil;
1211 if (valid_image_p (spec))
1213 struct frame *f = check_x_frame (frame);
1214 int id = lookup_image (f, spec);
1215 struct image *img = IMAGE_FROM_ID (f, id);
1216 if (img->mask)
1217 mask = Qt;
1219 else
1220 error ("Invalid image specification");
1222 return mask;
1225 DEFUN ("image-extension-data", Fimage_extension_data, Simage_extension_data, 1, 2, 0,
1226 doc: /* Return extension data for image SPEC.
1227 FRAME is the frame on which the image will be displayed. FRAME nil
1228 or omitted means use the selected frame. */)
1229 (spec, frame)
1230 Lisp_Object spec, frame;
1232 Lisp_Object ext;
1234 ext = Qnil;
1235 if (valid_image_p (spec))
1237 struct frame *f = check_x_frame (frame);
1238 int id = lookup_image (f, spec);
1239 struct image *img = IMAGE_FROM_ID (f, id);
1240 ext = img->data.lisp_val;
1243 return ext;
1247 /***********************************************************************
1248 Image type independent image structures
1249 ***********************************************************************/
1251 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
1252 static void free_image P_ ((struct frame *f, struct image *img));
1253 static int check_image_size P_ ((struct frame *f, int width, int height));
1255 #define MAX_IMAGE_SIZE 6.0
1256 Lisp_Object Vmax_image_size;
1258 /* Allocate and return a new image structure for image specification
1259 SPEC. SPEC has a hash value of HASH. */
1261 static struct image *
1262 make_image (spec, hash)
1263 Lisp_Object spec;
1264 unsigned hash;
1266 struct image *img = (struct image *) xmalloc (sizeof *img);
1268 xassert (valid_image_p (spec));
1269 bzero (img, sizeof *img);
1270 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1271 xassert (img->type != NULL);
1272 img->spec = spec;
1273 img->data.lisp_val = Qnil;
1274 img->ascent = DEFAULT_IMAGE_ASCENT;
1275 img->hash = hash;
1276 img->corners[BOT_CORNER] = -1; /* Full image */
1277 return img;
1281 /* Free image IMG which was used on frame F, including its resources. */
1283 static void
1284 free_image (f, img)
1285 struct frame *f;
1286 struct image *img;
1288 if (img)
1290 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1292 /* Remove IMG from the hash table of its cache. */
1293 if (img->prev)
1294 img->prev->next = img->next;
1295 else
1296 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1298 if (img->next)
1299 img->next->prev = img->prev;
1301 c->images[img->id] = NULL;
1303 /* Free resources, then free IMG. */
1304 img->type->free (f, img);
1305 xfree (img);
1309 /* Return 1 if the given widths and heights are valid for display;
1310 otherwise, return 0. */
1313 check_image_size (f, width, height)
1314 struct frame *f;
1315 int width;
1316 int height;
1318 int w, h;
1320 if (width <= 0 || height <= 0)
1321 return 0;
1323 if (INTEGERP (Vmax_image_size))
1324 w = h = XINT (Vmax_image_size);
1325 else if (FLOATP (Vmax_image_size))
1327 if (f != NULL)
1329 w = FRAME_PIXEL_WIDTH (f);
1330 h = FRAME_PIXEL_HEIGHT (f);
1332 else
1333 w = h = 1024; /* Arbitrary size for unknown frame. */
1334 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1335 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1337 else
1338 return 1;
1340 return (width <= w && height <= h);
1343 /* Prepare image IMG for display on frame F. Must be called before
1344 drawing an image. */
1346 void
1347 prepare_image_for_display (f, img)
1348 struct frame *f;
1349 struct image *img;
1351 EMACS_TIME t;
1353 /* We're about to display IMG, so set its timestamp to `now'. */
1354 EMACS_GET_TIME (t);
1355 img->timestamp = EMACS_SECS (t);
1357 /* If IMG doesn't have a pixmap yet, load it now, using the image
1358 type dependent loader function. */
1359 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1360 img->load_failed_p = img->type->load (f, img) == 0;
1362 #if defined (MAC_OS) && USE_CG_DRAWING
1363 if (!img->load_failed_p && img->data.ptr_val == NULL)
1365 img->data.ptr_val = mac_create_cg_image_from_image (f, img);
1366 if (img->data.ptr_val == NULL)
1368 img->load_failed_p = 1;
1369 img->type->free (f, img);
1372 #endif
1376 /* Value is the number of pixels for the ascent of image IMG when
1377 drawn in face FACE. */
1380 image_ascent (img, face, slice)
1381 struct image *img;
1382 struct face *face;
1383 struct glyph_slice *slice;
1385 int height;
1386 int ascent;
1388 if (slice->height == img->height)
1389 height = img->height + img->vmargin;
1390 else if (slice->y == 0)
1391 height = slice->height + img->vmargin;
1392 else
1393 height = slice->height;
1395 if (img->ascent == CENTERED_IMAGE_ASCENT)
1397 if (face->font)
1399 #ifdef HAVE_NTGUI
1400 /* W32 specific version. Why?. ++kfs */
1401 ascent = height / 2 - (FONT_DESCENT(face->font)
1402 - FONT_BASE(face->font)) / 2;
1403 #else
1404 /* This expression is arranged so that if the image can't be
1405 exactly centered, it will be moved slightly up. This is
1406 because a typical font is `top-heavy' (due to the presence
1407 uppercase letters), so the image placement should err towards
1408 being top-heavy too. It also just generally looks better. */
1409 ascent = (height + face->font->ascent - face->font->descent + 1) / 2;
1410 #endif /* HAVE_NTGUI */
1412 else
1413 ascent = height / 2;
1415 else
1416 ascent = (int) (height * img->ascent / 100.0);
1418 return ascent;
1422 /* Image background colors. */
1424 /* Find the "best" corner color of a bitmap.
1425 On W32, XIMG is assumed to a device context with the bitmap selected. */
1427 static RGB_PIXEL_COLOR
1428 four_corners_best (ximg, corners, width, height)
1429 XImagePtr_or_DC ximg;
1430 int *corners;
1431 unsigned long width, height;
1433 RGB_PIXEL_COLOR corner_pixels[4], best;
1434 int i, best_count;
1436 if (corners && corners[BOT_CORNER] >= 0)
1438 /* Get the colors at the corner_pixels of ximg. */
1439 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1440 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1441 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1442 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1444 else
1446 /* Get the colors at the corner_pixels of ximg. */
1447 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1448 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1449 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1450 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1452 /* Choose the most frequently found color as background. */
1453 for (i = best_count = 0; i < 4; ++i)
1455 int j, n;
1457 for (j = n = 0; j < 4; ++j)
1458 if (corner_pixels[i] == corner_pixels[j])
1459 ++n;
1461 if (n > best_count)
1462 best = corner_pixels[i], best_count = n;
1465 return best;
1468 /* Portability macros */
1470 #ifdef HAVE_NTGUI
1472 #define Destroy_Image(img_dc, prev) \
1473 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1475 #define Free_Pixmap(display, pixmap) \
1476 DeleteObject (pixmap)
1478 #else
1480 #define Destroy_Image(ximg, dummy) \
1481 XDestroyImage (ximg)
1483 #define Free_Pixmap(display, pixmap) \
1484 XFreePixmap (display, pixmap)
1486 #endif /* HAVE_NTGUI */
1489 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1490 it is guessed heuristically. If non-zero, XIMG is an existing
1491 XImage object (or device context with the image selected on W32) to
1492 use for the heuristic. */
1494 RGB_PIXEL_COLOR
1495 image_background (img, f, ximg)
1496 struct image *img;
1497 struct frame *f;
1498 XImagePtr_or_DC ximg;
1500 if (! img->background_valid)
1501 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1503 int free_ximg = !ximg;
1504 #ifdef HAVE_NTGUI
1505 HGDIOBJ prev;
1506 #endif /* HAVE_NTGUI */
1508 if (free_ximg)
1510 #ifndef HAVE_NTGUI
1511 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1512 0, 0, img->width, img->height, ~0, ZPixmap);
1513 #else
1514 HDC frame_dc = get_frame_dc (f);
1515 ximg = CreateCompatibleDC (frame_dc);
1516 release_frame_dc (f, frame_dc);
1517 prev = SelectObject (ximg, img->pixmap);
1518 #endif /* !HAVE_NTGUI */
1521 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1523 if (free_ximg)
1524 Destroy_Image (ximg, prev);
1526 img->background_valid = 1;
1529 return img->background;
1532 /* Return the `background_transparent' field of IMG. If IMG doesn't
1533 have one yet, it is guessed heuristically. If non-zero, MASK is an
1534 existing XImage object to use for the heuristic. */
1537 image_background_transparent (img, f, mask)
1538 struct image *img;
1539 struct frame *f;
1540 XImagePtr_or_DC mask;
1542 if (! img->background_transparent_valid)
1543 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1545 if (img->mask)
1547 int free_mask = !mask;
1548 #ifdef HAVE_NTGUI
1549 HGDIOBJ prev;
1550 #endif /* HAVE_NTGUI */
1552 if (free_mask)
1554 #ifndef HAVE_NTGUI
1555 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1556 0, 0, img->width, img->height, ~0, ZPixmap);
1557 #else
1558 HDC frame_dc = get_frame_dc (f);
1559 mask = CreateCompatibleDC (frame_dc);
1560 release_frame_dc (f, frame_dc);
1561 prev = SelectObject (mask, img->mask);
1562 #endif /* HAVE_NTGUI */
1565 img->background_transparent
1566 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1568 if (free_mask)
1569 Destroy_Image (mask, prev);
1571 else
1572 img->background_transparent = 0;
1574 img->background_transparent_valid = 1;
1577 return img->background_transparent;
1581 /***********************************************************************
1582 Helper functions for X image types
1583 ***********************************************************************/
1585 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
1586 int, int));
1587 static void x_clear_image P_ ((struct frame *f, struct image *img));
1588 static unsigned long x_alloc_image_color P_ ((struct frame *f,
1589 struct image *img,
1590 Lisp_Object color_name,
1591 unsigned long dflt));
1594 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1595 free the pixmap if any. MASK_P non-zero means clear the mask
1596 pixmap if any. COLORS_P non-zero means free colors allocated for
1597 the image, if any. */
1599 static void
1600 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
1601 struct frame *f;
1602 struct image *img;
1603 int pixmap_p, mask_p, colors_p;
1605 if (pixmap_p && img->pixmap)
1607 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1608 img->pixmap = NO_PIXMAP;
1609 img->background_valid = 0;
1612 if (mask_p && img->mask)
1614 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1615 img->mask = NO_PIXMAP;
1616 img->background_transparent_valid = 0;
1619 if (colors_p && img->ncolors)
1621 /* MAC_TODO: color table support. */
1622 /* W32_TODO: color table support. */
1623 #ifdef HAVE_X_WINDOWS
1624 x_free_colors (f, img->colors, img->ncolors);
1625 #endif /* HAVE_X_WINDOWS */
1626 xfree (img->colors);
1627 img->colors = NULL;
1628 img->ncolors = 0;
1631 #if defined (MAC_OS) && USE_CG_DRAWING
1632 if (img->data.ptr_val)
1634 CGImageRelease (img->data.ptr_val);
1635 img->data.ptr_val = NULL;
1637 #endif
1640 /* Free X resources of image IMG which is used on frame F. */
1642 static void
1643 x_clear_image (f, img)
1644 struct frame *f;
1645 struct image *img;
1647 BLOCK_INPUT;
1648 x_clear_image_1 (f, img, 1, 1, 1);
1649 UNBLOCK_INPUT;
1653 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1654 cannot be allocated, use DFLT. Add a newly allocated color to
1655 IMG->colors, so that it can be freed again. Value is the pixel
1656 color. */
1658 static unsigned long
1659 x_alloc_image_color (f, img, color_name, dflt)
1660 struct frame *f;
1661 struct image *img;
1662 Lisp_Object color_name;
1663 unsigned long dflt;
1665 XColor color;
1666 unsigned long result;
1668 xassert (STRINGP (color_name));
1670 if (x_defined_color (f, SDATA (color_name), &color, 1))
1672 /* This isn't called frequently so we get away with simply
1673 reallocating the color vector to the needed size, here. */
1674 ++img->ncolors;
1675 img->colors =
1676 (unsigned long *) xrealloc (img->colors,
1677 img->ncolors * sizeof *img->colors);
1678 img->colors[img->ncolors - 1] = color.pixel;
1679 result = color.pixel;
1681 else
1682 result = dflt;
1684 return result;
1689 /***********************************************************************
1690 Image Cache
1691 ***********************************************************************/
1693 static struct image *search_image_cache P_ ((struct frame *, Lisp_Object, unsigned));
1694 static void cache_image P_ ((struct frame *f, struct image *img));
1695 static void postprocess_image P_ ((struct frame *, struct image *));
1697 /* Return a new, initialized image cache that is allocated from the
1698 heap. Call free_image_cache to free an image cache. */
1700 struct image_cache *
1701 make_image_cache ()
1703 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1704 int size;
1706 bzero (c, sizeof *c);
1707 c->size = 50;
1708 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1709 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1710 c->buckets = (struct image **) xmalloc (size);
1711 bzero (c->buckets, size);
1712 return c;
1716 /* Find an image matching SPEC in the cache, and return it. If no
1717 image is found, return NULL. */
1718 static struct image *
1719 search_image_cache (f, spec, hash)
1720 struct frame *f;
1721 Lisp_Object spec;
1722 unsigned hash;
1724 struct image *img;
1725 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1726 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1728 if (!c) return NULL;
1730 /* If the image spec does not specify a background color, the cached
1731 image must have the same background color as the current frame.
1732 The foreground color must also match, for the sake of monochrome
1733 images.
1735 In fact, we could ignore the foreground color matching condition
1736 for color images, or if the image spec specifies :foreground;
1737 similarly we could ignore the background color matching condition
1738 for formats that don't use transparency (such as jpeg), or if the
1739 image spec specifies :background. However, the extra memory
1740 usage is probably negligible in practice, so we don't bother. */
1742 for (img = c->buckets[i]; img; img = img->next)
1743 if (img->hash == hash
1744 && !NILP (Fequal (img->spec, spec))
1745 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1746 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1747 break;
1748 return img;
1752 /* Search frame F for an image with spec SPEC, and free it. */
1754 static void
1755 uncache_image (f, spec)
1756 struct frame *f;
1757 Lisp_Object spec;
1759 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1760 if (img)
1761 free_image (f, img);
1765 /* Free image cache of frame F. Be aware that X frames share images
1766 caches. */
1768 void
1769 free_image_cache (f)
1770 struct frame *f;
1772 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1773 if (c)
1775 int i;
1777 /* Cache should not be referenced by any frame when freed. */
1778 xassert (c->refcount == 0);
1780 for (i = 0; i < c->used; ++i)
1781 free_image (f, c->images[i]);
1782 xfree (c->images);
1783 xfree (c->buckets);
1784 xfree (c);
1785 FRAME_X_IMAGE_CACHE (f) = NULL;
1790 /* Clear image cache of frame F. FORCE_P non-zero means free all
1791 images. FORCE_P zero means clear only images that haven't been
1792 displayed for some time. Should be called from time to time to
1793 reduce the number of loaded images. If image-cache-eviction-delay
1794 is non-nil, this frees images in the cache which weren't displayed
1795 for at least that many seconds. */
1797 void
1798 clear_image_cache (f, force_p)
1799 struct frame *f;
1800 int force_p;
1802 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1804 if (c && INTEGERP (Vimage_cache_eviction_delay))
1806 EMACS_TIME t;
1807 unsigned long old;
1808 int i, nfreed;
1810 EMACS_GET_TIME (t);
1811 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
1813 /* Block input so that we won't be interrupted by a SIGIO
1814 while being in an inconsistent state. */
1815 BLOCK_INPUT;
1817 for (i = nfreed = 0; i < c->used; ++i)
1819 struct image *img = c->images[i];
1820 if (img != NULL
1821 && (force_p || img->timestamp < old))
1823 free_image (f, img);
1824 ++nfreed;
1828 /* We may be clearing the image cache because, for example,
1829 Emacs was iconified for a longer period of time. In that
1830 case, current matrices may still contain references to
1831 images freed above. So, clear these matrices. */
1832 if (nfreed)
1834 Lisp_Object tail, frame;
1836 FOR_EACH_FRAME (tail, frame)
1838 struct frame *f = XFRAME (frame);
1839 if (FRAME_WINDOW_P (f)
1840 && FRAME_X_IMAGE_CACHE (f) == c)
1841 clear_current_matrices (f);
1844 ++windows_or_buffers_changed;
1847 UNBLOCK_INPUT;
1852 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1853 0, 1, 0,
1854 doc: /* Clear the image cache of FRAME.
1855 FRAME nil or omitted means use the selected frame.
1856 FRAME t means clear the image caches of all frames. */)
1857 (frame)
1858 Lisp_Object frame;
1860 if (EQ (frame, Qt))
1862 Lisp_Object tail;
1864 FOR_EACH_FRAME (tail, frame)
1865 if (FRAME_WINDOW_P (XFRAME (frame)))
1866 clear_image_cache (XFRAME (frame), 1);
1868 else
1869 clear_image_cache (check_x_frame (frame), 1);
1871 return Qnil;
1875 DEFUN ("image-refresh", Fimage_refresh, Simage_refresh,
1876 1, 2, 0,
1877 doc: /* Refresh the image with specification SPEC on frame FRAME.
1878 If SPEC specifies an image file, the displayed image is updated with
1879 the current contents of that file.
1880 FRAME nil or omitted means use the selected frame.
1881 FRAME t means refresh the image on all frames. */)
1882 (spec, frame)
1883 Lisp_Object spec, frame;
1885 if (!valid_image_p (spec))
1886 error ("Invalid image specification");
1888 if (EQ (frame, Qt))
1890 Lisp_Object tail;
1891 FOR_EACH_FRAME (tail, frame)
1893 struct frame *f = XFRAME (frame);
1894 if (FRAME_WINDOW_P (f))
1895 uncache_image (f, spec);
1898 else
1899 uncache_image (check_x_frame (frame), spec);
1901 return Qnil;
1905 /* Compute masks and transform image IMG on frame F, as specified
1906 by the image's specification, */
1908 static void
1909 postprocess_image (f, img)
1910 struct frame *f;
1911 struct image *img;
1913 /* Manipulation of the image's mask. */
1914 if (img->pixmap)
1916 Lisp_Object conversion, spec;
1917 Lisp_Object mask;
1919 spec = img->spec;
1921 /* `:heuristic-mask t'
1922 `:mask heuristic'
1923 means build a mask heuristically.
1924 `:heuristic-mask (R G B)'
1925 `:mask (heuristic (R G B))'
1926 means build a mask from color (R G B) in the
1927 image.
1928 `:mask nil'
1929 means remove a mask, if any. */
1931 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1932 if (!NILP (mask))
1933 x_build_heuristic_mask (f, img, mask);
1934 else
1936 int found_p;
1938 mask = image_spec_value (spec, QCmask, &found_p);
1940 if (EQ (mask, Qheuristic))
1941 x_build_heuristic_mask (f, img, Qt);
1942 else if (CONSP (mask)
1943 && EQ (XCAR (mask), Qheuristic))
1945 if (CONSP (XCDR (mask)))
1946 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1947 else
1948 x_build_heuristic_mask (f, img, XCDR (mask));
1950 else if (NILP (mask) && found_p && img->mask)
1952 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1953 img->mask = NO_PIXMAP;
1958 /* Should we apply an image transformation algorithm? */
1959 conversion = image_spec_value (spec, QCconversion, NULL);
1960 if (EQ (conversion, Qdisabled))
1961 x_disable_image (f, img);
1962 else if (EQ (conversion, Qlaplace))
1963 x_laplace (f, img);
1964 else if (EQ (conversion, Qemboss))
1965 x_emboss (f, img);
1966 else if (CONSP (conversion)
1967 && EQ (XCAR (conversion), Qedge_detection))
1969 Lisp_Object tem;
1970 tem = XCDR (conversion);
1971 if (CONSP (tem))
1972 x_edge_detection (f, img,
1973 Fplist_get (tem, QCmatrix),
1974 Fplist_get (tem, QCcolor_adjustment));
1980 /* Return the id of image with Lisp specification SPEC on frame F.
1981 SPEC must be a valid Lisp image specification (see valid_image_p). */
1984 lookup_image (f, spec)
1985 struct frame *f;
1986 Lisp_Object spec;
1988 struct image *img;
1989 unsigned hash;
1990 struct gcpro gcpro1;
1991 EMACS_TIME now;
1993 /* F must be a window-system frame, and SPEC must be a valid image
1994 specification. */
1995 xassert (FRAME_WINDOW_P (f));
1996 xassert (valid_image_p (spec));
1998 GCPRO1 (spec);
2000 /* Look up SPEC in the hash table of the image cache. */
2001 hash = sxhash (spec, 0);
2002 img = search_image_cache (f, spec, hash);
2003 if (img && img->load_failed_p)
2005 free_image (f, img);
2006 img = NULL;
2009 /* If not found, create a new image and cache it. */
2010 if (img == NULL)
2012 extern Lisp_Object Qpostscript;
2014 BLOCK_INPUT;
2015 img = make_image (spec, hash);
2016 cache_image (f, img);
2017 img->load_failed_p = img->type->load (f, img) == 0;
2018 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
2019 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
2021 /* If we can't load the image, and we don't have a width and
2022 height, use some arbitrary width and height so that we can
2023 draw a rectangle for it. */
2024 if (img->load_failed_p)
2026 Lisp_Object value;
2028 value = image_spec_value (spec, QCwidth, NULL);
2029 img->width = (INTEGERP (value)
2030 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
2031 value = image_spec_value (spec, QCheight, NULL);
2032 img->height = (INTEGERP (value)
2033 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
2035 else
2037 /* Handle image type independent image attributes
2038 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
2039 `:background COLOR'. */
2040 Lisp_Object ascent, margin, relief, bg;
2042 ascent = image_spec_value (spec, QCascent, NULL);
2043 if (INTEGERP (ascent))
2044 img->ascent = XFASTINT (ascent);
2045 else if (EQ (ascent, Qcenter))
2046 img->ascent = CENTERED_IMAGE_ASCENT;
2048 margin = image_spec_value (spec, QCmargin, NULL);
2049 if (INTEGERP (margin) && XINT (margin) >= 0)
2050 img->vmargin = img->hmargin = XFASTINT (margin);
2051 else if (CONSP (margin) && INTEGERP (XCAR (margin))
2052 && INTEGERP (XCDR (margin)))
2054 if (XINT (XCAR (margin)) > 0)
2055 img->hmargin = XFASTINT (XCAR (margin));
2056 if (XINT (XCDR (margin)) > 0)
2057 img->vmargin = XFASTINT (XCDR (margin));
2060 relief = image_spec_value (spec, QCrelief, NULL);
2061 if (INTEGERP (relief))
2063 img->relief = XINT (relief);
2064 img->hmargin += abs (img->relief);
2065 img->vmargin += abs (img->relief);
2068 if (! img->background_valid)
2070 bg = image_spec_value (img->spec, QCbackground, NULL);
2071 if (!NILP (bg))
2073 img->background
2074 = x_alloc_image_color (f, img, bg,
2075 FRAME_BACKGROUND_PIXEL (f));
2076 img->background_valid = 1;
2080 /* Do image transformations and compute masks, unless we
2081 don't have the image yet. */
2082 if (!EQ (*img->type->type, Qpostscript))
2083 postprocess_image (f, img);
2086 UNBLOCK_INPUT;
2089 /* We're using IMG, so set its timestamp to `now'. */
2090 EMACS_GET_TIME (now);
2091 img->timestamp = EMACS_SECS (now);
2093 UNGCPRO;
2095 /* Value is the image id. */
2096 return img->id;
2100 /* Cache image IMG in the image cache of frame F. */
2102 static void
2103 cache_image (f, img)
2104 struct frame *f;
2105 struct image *img;
2107 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
2108 int i;
2110 /* Find a free slot in c->images. */
2111 for (i = 0; i < c->used; ++i)
2112 if (c->images[i] == NULL)
2113 break;
2115 /* If no free slot found, maybe enlarge c->images. */
2116 if (i == c->used && c->used == c->size)
2118 c->size *= 2;
2119 c->images = (struct image **) xrealloc (c->images,
2120 c->size * sizeof *c->images);
2123 /* Add IMG to c->images, and assign IMG an id. */
2124 c->images[i] = img;
2125 img->id = i;
2126 if (i == c->used)
2127 ++c->used;
2129 /* Add IMG to the cache's hash table. */
2130 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
2131 img->next = c->buckets[i];
2132 if (img->next)
2133 img->next->prev = img;
2134 img->prev = NULL;
2135 c->buckets[i] = img;
2139 /* Call FN on every image in the image cache of frame F. Used to mark
2140 Lisp Objects in the image cache. */
2142 void
2143 forall_images_in_image_cache (f, fn)
2144 struct frame *f;
2145 void (*fn) P_ ((struct image *img));
2147 if (FRAME_LIVE_P (f) && FRAME_WINDOW_P (f))
2149 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
2150 if (c)
2152 int i;
2153 for (i = 0; i < c->used; ++i)
2154 if (c->images[i])
2155 fn (c->images[i]);
2162 /***********************************************************************
2163 X / MAC / W32 support code
2164 ***********************************************************************/
2166 #ifdef HAVE_NTGUI
2168 /* Macro for defining functions that will be loaded from image DLLs. */
2169 #define DEF_IMGLIB_FN(func) int (FAR CDECL *fn_##func)()
2171 /* Macro for loading those image functions from the library. */
2172 #define LOAD_IMGLIB_FN(lib,func) { \
2173 fn_##func = (void *) GetProcAddress (lib, #func); \
2174 if (!fn_##func) return 0; \
2177 /* Load a DLL implementing an image type.
2178 The `image-library-alist' variable associates a symbol,
2179 identifying an image type, to a list of possible filenames.
2180 The function returns NULL if no library could be loaded for
2181 the given image type, or if the library was previously loaded;
2182 else the handle of the DLL. */
2183 static HMODULE
2184 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
2186 HMODULE library = NULL;
2188 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
2190 Lisp_Object dlls = Fassq (type, libraries);
2192 if (CONSP (dlls))
2193 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
2195 CHECK_STRING_CAR (dlls);
2196 if (library = LoadLibrary (SDATA (XCAR (dlls))))
2197 break;
2201 return library;
2204 #endif /* HAVE_NTGUI */
2206 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
2207 XImagePtr *, Pixmap *));
2208 static void x_destroy_x_image P_ ((XImagePtr));
2209 static void x_put_x_image P_ ((struct frame *, XImagePtr, Pixmap, int, int));
2212 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
2213 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
2214 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
2215 via xmalloc. Print error messages via image_error if an error
2216 occurs. Value is non-zero if successful.
2218 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
2219 should indicate the bit depth of the image. */
2221 static int
2222 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
2223 struct frame *f;
2224 int width, height, depth;
2225 XImagePtr *ximg;
2226 Pixmap *pixmap;
2228 #ifdef HAVE_X_WINDOWS
2229 Display *display = FRAME_X_DISPLAY (f);
2230 Window window = FRAME_X_WINDOW (f);
2231 Screen *screen = FRAME_X_SCREEN (f);
2233 xassert (interrupt_input_blocked);
2235 if (depth <= 0)
2236 depth = DefaultDepthOfScreen (screen);
2237 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
2238 depth, ZPixmap, 0, NULL, width, height,
2239 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
2240 if (*ximg == NULL)
2242 image_error ("Unable to allocate X image", Qnil, Qnil);
2243 return 0;
2246 /* Allocate image raster. */
2247 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
2249 /* Allocate a pixmap of the same size. */
2250 *pixmap = XCreatePixmap (display, window, width, height, depth);
2251 if (*pixmap == NO_PIXMAP)
2253 x_destroy_x_image (*ximg);
2254 *ximg = NULL;
2255 image_error ("Unable to create X pixmap", Qnil, Qnil);
2256 return 0;
2259 return 1;
2260 #endif /* HAVE_X_WINDOWS */
2262 #ifdef HAVE_NTGUI
2264 BITMAPINFOHEADER *header;
2265 HDC hdc;
2266 int scanline_width_bits;
2267 int remainder;
2268 int palette_colors = 0;
2270 if (depth == 0)
2271 depth = 24;
2273 if (depth != 1 && depth != 4 && depth != 8
2274 && depth != 16 && depth != 24 && depth != 32)
2276 image_error ("Invalid image bit depth specified", Qnil, Qnil);
2277 return 0;
2280 scanline_width_bits = width * depth;
2281 remainder = scanline_width_bits % 32;
2283 if (remainder)
2284 scanline_width_bits += 32 - remainder;
2286 /* Bitmaps with a depth less than 16 need a palette. */
2287 /* BITMAPINFO structure already contains the first RGBQUAD. */
2288 if (depth < 16)
2289 palette_colors = 1 << depth - 1;
2291 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2292 if (*ximg == NULL)
2294 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
2295 return 0;
2298 header = &((*ximg)->info.bmiHeader);
2299 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
2300 header->biSize = sizeof (*header);
2301 header->biWidth = width;
2302 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2303 header->biPlanes = 1;
2304 header->biBitCount = depth;
2305 header->biCompression = BI_RGB;
2306 header->biClrUsed = palette_colors;
2308 /* TODO: fill in palette. */
2309 if (depth == 1)
2311 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2312 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2313 (*ximg)->info.bmiColors[0].rgbRed = 0;
2314 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2315 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2316 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2317 (*ximg)->info.bmiColors[1].rgbRed = 255;
2318 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2321 hdc = get_frame_dc (f);
2323 /* Create a DIBSection and raster array for the bitmap,
2324 and store its handle in *pixmap. */
2325 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2326 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2327 /* casting avoids a GCC warning */
2328 (void **)&((*ximg)->data), NULL, 0);
2330 /* Realize display palette and garbage all frames. */
2331 release_frame_dc (f, hdc);
2333 if (*pixmap == NULL)
2335 DWORD err = GetLastError();
2336 Lisp_Object errcode;
2337 /* All system errors are < 10000, so the following is safe. */
2338 XSETINT (errcode, (int) err);
2339 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2340 x_destroy_x_image (*ximg);
2341 return 0;
2344 return 1;
2346 #endif /* HAVE_NTGUI */
2348 #ifdef MAC_OS
2349 Display *display = FRAME_X_DISPLAY (f);
2350 Window window = FRAME_X_WINDOW (f);
2352 xassert (interrupt_input_blocked);
2354 /* Allocate a pixmap of the same size. */
2355 *pixmap = XCreatePixmap (display, window, width, height, depth);
2356 if (*pixmap == NO_PIXMAP)
2358 *ximg = NULL;
2359 image_error ("Unable to create X pixmap", Qnil, Qnil);
2360 return 0;
2363 #if !USE_MAC_IMAGE_IO
2364 LockPixels (GetGWorldPixMap (*pixmap));
2365 #endif
2366 *ximg = *pixmap;
2367 return 1;
2369 #endif /* MAC_OS */
2373 /* Destroy XImage XIMG. Free XIMG->data. */
2375 static void
2376 x_destroy_x_image (ximg)
2377 XImagePtr ximg;
2379 xassert (interrupt_input_blocked);
2380 if (ximg)
2382 #ifdef HAVE_X_WINDOWS
2383 xfree (ximg->data);
2384 ximg->data = NULL;
2385 XDestroyImage (ximg);
2386 #endif /* HAVE_X_WINDOWS */
2387 #ifdef HAVE_NTGUI
2388 /* Data will be freed by DestroyObject. */
2389 ximg->data = NULL;
2390 xfree (ximg);
2391 #endif /* HAVE_NTGUI */
2392 #ifdef MAC_OS
2393 XDestroyImage (ximg);
2394 #endif /* MAC_OS */
2399 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2400 are width and height of both the image and pixmap. */
2402 static void
2403 x_put_x_image (f, ximg, pixmap, width, height)
2404 struct frame *f;
2405 XImagePtr ximg;
2406 Pixmap pixmap;
2407 int width, height;
2409 #ifdef HAVE_X_WINDOWS
2410 GC gc;
2412 xassert (interrupt_input_blocked);
2413 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2414 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2415 XFreeGC (FRAME_X_DISPLAY (f), gc);
2416 #endif /* HAVE_X_WINDOWS */
2418 #ifdef HAVE_NTGUI
2419 #if 0 /* I don't think this is necessary looking at where it is used. */
2420 HDC hdc = get_frame_dc (f);
2421 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2422 release_frame_dc (f, hdc);
2423 #endif
2424 #endif /* HAVE_NTGUI */
2426 #ifdef MAC_OS
2427 xassert (ximg == pixmap);
2428 #endif /* MAC_OS */
2432 /***********************************************************************
2433 File Handling
2434 ***********************************************************************/
2436 static unsigned char *slurp_file P_ ((char *, int *));
2439 /* Find image file FILE. Look in data-directory, then
2440 x-bitmap-file-path. Value is the encoded full name of the file
2441 found, or nil if not found. */
2443 Lisp_Object
2444 x_find_image_file (file)
2445 Lisp_Object file;
2447 Lisp_Object file_found, search_path;
2448 struct gcpro gcpro1, gcpro2;
2449 int fd;
2451 file_found = Qnil;
2452 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
2453 GCPRO2 (file_found, search_path);
2455 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
2456 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2458 if (fd == -1)
2459 file_found = Qnil;
2460 else
2462 file_found = ENCODE_FILE (file_found);
2463 close (fd);
2466 UNGCPRO;
2467 return file_found;
2471 /* Read FILE into memory. Value is a pointer to a buffer allocated
2472 with xmalloc holding FILE's contents. Value is null if an error
2473 occurred. *SIZE is set to the size of the file. */
2475 static unsigned char *
2476 slurp_file (file, size)
2477 char *file;
2478 int *size;
2480 FILE *fp = NULL;
2481 unsigned char *buf = NULL;
2482 struct stat st;
2484 if (stat (file, &st) == 0
2485 && (fp = fopen (file, "rb")) != NULL
2486 && (buf = (unsigned char *) xmalloc (st.st_size),
2487 fread (buf, 1, st.st_size, fp) == st.st_size))
2489 *size = st.st_size;
2490 fclose (fp);
2492 else
2494 if (fp)
2495 fclose (fp);
2496 if (buf)
2498 xfree (buf);
2499 buf = NULL;
2503 return buf;
2508 #ifdef MAC_OS
2510 /***********************************************************************
2511 MAC Image Load Functions
2512 ***********************************************************************/
2514 #if USE_MAC_IMAGE_IO
2515 static int
2516 image_load_image_io (f, img, type)
2517 struct frame *f;
2518 struct image *img;
2519 CFStringRef type;
2521 CFDictionaryRef options, src_props = NULL, props = NULL;
2522 CFStringRef keys[2];
2523 CFTypeRef values[2];
2524 Lisp_Object specified_file, specified_data;
2525 CGImageSourceRef source = NULL;
2526 size_t count;
2527 CGImageRef image = NULL;
2528 int loop_count = -1;
2529 double delay_time = -1.0;
2530 int width, height;
2531 XImagePtr ximg = NULL;
2532 CGContextRef context;
2533 CGRect rectangle;
2534 int has_alpha_p, gif_p;
2536 gif_p = UTTypeEqual (type, kUTTypeGIF);
2538 keys[0] = kCGImageSourceTypeIdentifierHint;
2539 values[0] = (CFTypeRef) type;
2540 keys[1] = kCGImageSourceShouldCache;
2541 values[1] = (CFTypeRef) kCFBooleanFalse;
2542 options = CFDictionaryCreate (NULL, (const void **) keys,
2543 (const void **) values,
2544 sizeof (keys) / sizeof (keys[0]),
2545 &kCFTypeDictionaryKeyCallBacks,
2546 &kCFTypeDictionaryValueCallBacks);
2547 if (options == NULL)
2549 image_error ("Error creating options for image `%s'", img->spec, Qnil);
2550 return 0;
2553 /* Open the file. */
2554 specified_file = image_spec_value (img->spec, QCfile, NULL);
2555 specified_data = image_spec_value (img->spec, QCdata, NULL);
2557 if (NILP (specified_data))
2559 Lisp_Object file;
2560 CFStringRef path;
2561 CFURLRef url;
2563 file = x_find_image_file (specified_file);
2564 if (!STRINGP (file))
2566 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2567 return 0;
2569 path = cfstring_create_with_utf8_cstring (SDATA (file));
2570 if (path)
2572 url = CFURLCreateWithFileSystemPath (NULL, path,
2573 kCFURLPOSIXPathStyle, 0);
2574 CFRelease (path);
2575 if (url)
2577 source = CGImageSourceCreateWithURL (url, NULL);
2578 CFRelease (url);
2582 else
2584 CFDataRef data = CFDataCreate (NULL, SDATA (specified_data),
2585 SBYTES (specified_data));
2587 if (data)
2589 source = CGImageSourceCreateWithData (data, options);
2590 CFRelease (data);
2593 CFRelease (options);
2595 if (source)
2597 CFStringRef real_type = CGImageSourceGetType (source);
2599 if (real_type && UTTypeEqual (type, real_type))
2600 src_props = CGImageSourceCopyProperties (source, NULL);
2601 if (src_props)
2603 EMACS_INT ino = 0;
2605 count = CGImageSourceGetCount (source);
2606 if (gif_p)
2608 Lisp_Object image = image_spec_value (img->spec, QCindex, NULL);
2610 if (INTEGERP (image))
2611 ino = XFASTINT (image);
2613 if (ino >= 0 && ino < count)
2615 props = CGImageSourceCopyPropertiesAtIndex (source, ino, NULL);
2616 if (props)
2617 image = CGImageSourceCreateImageAtIndex (source, ino, NULL);
2620 CFRelease (source);
2623 if (image == NULL)
2625 if (src_props)
2626 CFRelease (src_props);
2627 if (props)
2628 CFRelease (props);
2629 image_error ("Error reading image `%s'", img->spec, Qnil);
2630 return 0;
2632 else
2634 CFBooleanRef boolean;
2636 if (CFDictionaryGetValueIfPresent (props, kCGImagePropertyHasAlpha,
2637 (const void **) &boolean))
2638 has_alpha_p = CFBooleanGetValue (boolean);
2639 if (gif_p)
2641 CFDictionaryRef dict;
2642 CFNumberRef number;
2644 dict = CFDictionaryGetValue (src_props,
2645 kCGImagePropertyGIFDictionary);
2646 if (dict
2647 && CFDictionaryGetValueIfPresent (dict,
2648 kCGImagePropertyGIFLoopCount,
2649 (const void **) &number))
2650 CFNumberGetValue (number, kCFNumberIntType, &loop_count);
2652 dict = CFDictionaryGetValue (props, kCGImagePropertyGIFDictionary);
2653 if (dict
2654 && CFDictionaryGetValueIfPresent (dict,
2655 kCGImagePropertyGIFDelayTime,
2656 (const void **) &number))
2657 CFNumberGetValue (number, kCFNumberDoubleType, &delay_time);
2659 CFRelease (src_props);
2660 CFRelease (props);
2663 width = img->width = CGImageGetWidth (image);
2664 height = img->height = CGImageGetHeight (image);
2666 if (!check_image_size (f, width, height))
2668 CGImageRelease (image);
2669 image_error ("Invalid image size", Qnil, Qnil);
2670 return 0;
2673 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2675 CGImageRelease (image);
2676 image_error ("Out of memory (%s)", img->spec, Qnil);
2677 return 0;
2679 rectangle = CGRectMake (0, 0, width, height);
2681 context = CGBitmapContextCreate (ximg->data, ximg->width, ximg->height, 8,
2682 ximg->bytes_per_line,
2683 mac_cg_color_space_rgb,
2684 kCGImageAlphaNoneSkipFirst
2685 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1040
2686 | kCGBitmapByteOrder32Host
2687 #endif
2689 if (has_alpha_p)
2691 Lisp_Object specified_bg;
2692 XColor color;
2694 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2695 if (!STRINGP (specified_bg)
2696 || !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2698 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2699 color.red = RED16_FROM_ULONG (color.pixel);
2700 color.green = GREEN16_FROM_ULONG (color.pixel);
2701 color.blue = BLUE16_FROM_ULONG (color.pixel);
2703 CGContextSetRGBFillColor (context, color.red / 65535.0,
2704 color.green / 65535.0,
2705 color.blue / 65535.0, 1.0);
2706 CGContextFillRect (context, rectangle);
2708 CGContextDrawImage (context, rectangle, image);
2709 CGContextRelease (context);
2710 CGImageRelease (image);
2712 /* Save GIF image extension data for `image-extension-data'.
2713 Format is (count IMAGES
2714 0xff "NETSCAPE2.0" 0x00 DATA_SUB_BLOCK_FOR_LOOP_COUNT
2715 0xf9 GRAPHIC_CONTROL_EXTENSION_BLOCK). */
2716 if (gif_p)
2718 img->data.lisp_val = Qnil;
2719 if (delay_time >= 0)
2721 Lisp_Object gce = make_uninit_string (4);
2722 int centisec = delay_time * 100.0 + 0.5;
2724 /* Fill the delay time field. */
2725 SSET (gce, 1, centisec & 0xff);
2726 SSET (gce, 2, (centisec >> 8) & 0xff);
2727 /* We don't know about other fields. */
2728 SSET (gce, 0, 0);
2729 SSET (gce, 3, 0);
2730 img->data.lisp_val = Fcons (make_number (0xf9),
2731 Fcons (gce,
2732 img->data.lisp_val));
2734 if (loop_count >= 0)
2736 Lisp_Object data_sub_block = make_uninit_string (3);
2738 SSET (data_sub_block, 0, 0x01);
2739 SSET (data_sub_block, 1, loop_count & 0xff);
2740 SSET (data_sub_block, 2, (loop_count >> 8) & 0xff);
2741 img->data.lisp_val = Fcons (make_number (0),
2742 Fcons (data_sub_block,
2743 img->data.lisp_val));
2744 img->data.lisp_val = Fcons (make_number (0xff),
2745 Fcons (build_string ("NETSCAPE2.0"),
2746 img->data.lisp_val));
2748 if (count > 1)
2749 img->data.lisp_val = Fcons (Qcount,
2750 Fcons (make_number (count),
2751 img->data.lisp_val));
2754 /* Maybe fill in the background field while we have ximg handy. */
2755 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2756 IMAGE_BACKGROUND (img, f, ximg);
2758 /* Put the image into the pixmap. */
2759 x_put_x_image (f, ximg, img->pixmap, width, height);
2760 x_destroy_x_image (ximg);
2761 return 1;
2763 #else /* !USE_MAC_IMAGE_IO */
2764 static int image_load_quicktime P_ ((struct frame *, struct image *img,
2765 OSType));
2766 #ifdef MAC_OSX
2767 static int image_load_quartz2d P_ ((struct frame *, struct image *img, int));
2768 #endif
2770 static OSErr
2771 find_image_fsspec (specified_file, file, fss)
2772 Lisp_Object specified_file, *file;
2773 FSSpec *fss;
2775 OSErr err;
2776 AEDesc desc;
2778 *file = x_find_image_file (specified_file);
2779 if (!STRINGP (*file))
2780 return fnfErr; /* file or directory not found;
2781 incomplete pathname */
2782 /* Try to open the image file. */
2783 err = AECoercePtr (TYPE_FILE_NAME, SDATA (*file),
2784 SBYTES (*file), typeFSS, &desc);
2785 if (err == noErr)
2787 #if TARGET_API_MAC_CARBON
2788 err = AEGetDescData (&desc, fss, sizeof (FSSpec));
2789 #else
2790 *fss = *(FSSpec *)(*(desc.dataHandle));
2791 #endif
2792 AEDisposeDesc (&desc);
2794 return err;
2797 static int
2798 image_load_qt_1 (f, img, type, fss, dh)
2799 struct frame *f;
2800 struct image *img;
2801 OSType type;
2802 const FSSpec *fss;
2803 Handle dh;
2805 ComponentResult err;
2806 GraphicsImportComponent gi;
2807 Rect rect;
2808 int width, height;
2809 ImageDescriptionHandle desc_handle;
2810 short draw_all_pixels;
2811 Lisp_Object specified_bg;
2812 XColor color;
2813 XImagePtr ximg;
2814 RGBColor bg_color;
2816 err = OpenADefaultComponent (GraphicsImporterComponentType, type, &gi);
2817 if (err != noErr)
2819 image_error ("Cannot get importer component for `%s'", img->spec, Qnil);
2820 return 0;
2822 if (dh == NULL)
2824 /* read from file system spec */
2825 err = GraphicsImportSetDataFile (gi, fss);
2826 if (err != noErr)
2828 image_error ("Cannot set fsspec to graphics importer for '%s'",
2829 img->spec, Qnil);
2830 goto error;
2833 else
2835 /* read from data handle */
2836 err = GraphicsImportSetDataHandle (gi, dh);
2837 if (err != noErr)
2839 image_error ("Cannot set data handle to graphics importer for `%s'",
2840 img->spec, Qnil);
2841 goto error;
2844 err = GraphicsImportGetImageDescription (gi, &desc_handle);
2845 if (err != noErr || desc_handle == NULL)
2847 image_error ("Error reading `%s'", img->spec, Qnil);
2848 goto error;
2850 width = img->width = (*desc_handle)->width;
2851 height = img->height = (*desc_handle)->height;
2852 DisposeHandle ((Handle)desc_handle);
2854 if (!check_image_size (f, width, height))
2856 image_error ("Invalid image size", Qnil, Qnil);
2857 goto error;
2860 err = GraphicsImportDoesDrawAllPixels (gi, &draw_all_pixels);
2861 #if 0
2862 /* Don't check the error code here. It may have an undocumented
2863 value -32766. */
2864 if (err != noErr)
2866 image_error ("Error reading `%s'", img->spec, Qnil);
2867 goto error;
2869 #endif
2870 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2872 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2873 if (!STRINGP (specified_bg) ||
2874 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2876 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2877 color.red = RED16_FROM_ULONG (color.pixel);
2878 color.green = GREEN16_FROM_ULONG (color.pixel);
2879 color.blue = BLUE16_FROM_ULONG (color.pixel);
2883 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2884 goto error;
2885 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2887 CGrafPtr old_port;
2888 GDHandle old_gdh;
2890 GetGWorld (&old_port, &old_gdh);
2891 SetGWorld (ximg, NULL);
2892 bg_color.red = color.red;
2893 bg_color.green = color.green;
2894 bg_color.blue = color.blue;
2895 RGBBackColor (&bg_color);
2896 #if TARGET_API_MAC_CARBON
2897 GetPortBounds (ximg, &rect);
2898 EraseRect (&rect);
2899 #else
2900 EraseRect (&(ximg->portRect));
2901 #endif
2902 SetGWorld (old_port, old_gdh);
2904 GraphicsImportSetGWorld (gi, ximg, NULL);
2905 GraphicsImportDraw (gi);
2906 CloseComponent (gi);
2908 /* Maybe fill in the background field while we have ximg handy. */
2909 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2910 IMAGE_BACKGROUND (img, f, ximg);
2912 /* Put the image into the pixmap. */
2913 x_put_x_image (f, ximg, img->pixmap, width, height);
2914 x_destroy_x_image (ximg);
2915 return 1;
2917 error:
2918 CloseComponent (gi);
2919 return 0;
2923 /* Load an image using the QuickTime Graphics Importer.
2924 Note: The alpha channel does not work for PNG images. */
2925 static int
2926 image_load_quicktime (f, img, type)
2927 struct frame *f;
2928 struct image *img;
2929 OSType type;
2931 Lisp_Object specified_file;
2932 Lisp_Object specified_data;
2933 OSErr err;
2935 specified_file = image_spec_value (img->spec, QCfile, NULL);
2936 specified_data = image_spec_value (img->spec, QCdata, NULL);
2938 if (NILP (specified_data))
2940 /* Read from a file */
2941 Lisp_Object file;
2942 FSSpec fss;
2944 err = find_image_fsspec (specified_file, &file, &fss);
2945 if (err != noErr)
2947 if (err == fnfErr)
2948 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2949 else
2950 image_error ("Cannot open `%s'", file, Qnil);
2951 return 0;
2953 return image_load_qt_1 (f, img, type, &fss, NULL);
2955 else
2957 /* Memory source! */
2958 int success_p;
2959 Handle dh;
2961 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
2962 if (err != noErr)
2964 image_error ("Cannot allocate data handle for `%s'",
2965 img->spec, Qnil);
2966 return 0;
2968 success_p = image_load_qt_1 (f, img, type, NULL, dh);
2969 DisposeHandle (dh);
2970 return success_p;
2975 #ifdef MAC_OSX
2976 static int
2977 image_load_quartz2d (f, img, png_p)
2978 struct frame *f;
2979 struct image *img;
2980 int png_p;
2982 Lisp_Object file, specified_file;
2983 Lisp_Object specified_data, specified_bg;
2984 struct gcpro gcpro1;
2985 CGDataProviderRef source;
2986 CGImageRef image;
2987 int width, height;
2988 XColor color;
2989 XImagePtr ximg = NULL;
2990 CGContextRef context;
2991 CGRect rectangle;
2993 /* Open the file. */
2994 specified_file = image_spec_value (img->spec, QCfile, NULL);
2995 specified_data = image_spec_value (img->spec, QCdata, NULL);
2997 file = Qnil;
2998 GCPRO1 (file);
3000 if (NILP (specified_data))
3002 CFStringRef path;
3003 CFURLRef url;
3005 file = x_find_image_file (specified_file);
3006 if (!STRINGP (file))
3008 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3009 UNGCPRO;
3010 return 0;
3012 path = cfstring_create_with_utf8_cstring (SDATA (file));
3013 url = CFURLCreateWithFileSystemPath (NULL, path,
3014 kCFURLPOSIXPathStyle, 0);
3015 CFRelease (path);
3016 source = CGDataProviderCreateWithURL (url);
3017 CFRelease (url);
3019 else
3020 source = CGDataProviderCreateWithData (NULL, SDATA (specified_data),
3021 SBYTES (specified_data), NULL);
3023 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
3024 if (png_p)
3025 image = CGImageCreateWithPNGDataProvider (source, NULL, false,
3026 kCGRenderingIntentDefault);
3027 else
3028 #endif
3029 image = CGImageCreateWithJPEGDataProvider (source, NULL, false,
3030 kCGRenderingIntentDefault);
3032 CGDataProviderRelease (source);
3033 if (image == NULL)
3035 UNGCPRO;
3036 image_error ("Error reading image `%s'", img->spec, Qnil);
3037 return 0;
3039 width = img->width = CGImageGetWidth (image);
3040 height = img->height = CGImageGetHeight (image);
3042 if (!check_image_size (f, width, height))
3044 CGImageRelease (image);
3045 UNGCPRO;
3046 image_error ("Invalid image size", Qnil, Qnil);
3047 return 0;
3050 if (png_p)
3052 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
3053 if (!STRINGP (specified_bg) ||
3054 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
3056 color.pixel = FRAME_BACKGROUND_PIXEL (f);
3057 color.red = RED16_FROM_ULONG (color.pixel);
3058 color.green = GREEN16_FROM_ULONG (color.pixel);
3059 color.blue = BLUE16_FROM_ULONG (color.pixel);
3063 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
3065 CGImageRelease (image);
3066 UNGCPRO;
3067 return 0;
3069 rectangle = CGRectMake (0, 0, width, height);
3070 QDBeginCGContext (ximg, &context);
3071 if (png_p)
3073 CGContextSetRGBFillColor (context, color.red / 65535.0,
3074 color.green / 65535.0,
3075 color.blue / 65535.0, 1.0);
3076 CGContextFillRect (context, rectangle);
3078 CGContextDrawImage (context, rectangle, image);
3079 QDEndCGContext (ximg, &context);
3080 CGImageRelease (image);
3082 /* Maybe fill in the background field while we have ximg handy. */
3083 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
3084 IMAGE_BACKGROUND (img, f, ximg);
3086 /* Put the image into the pixmap. */
3087 x_put_x_image (f, ximg, img->pixmap, width, height);
3088 x_destroy_x_image (ximg);
3089 UNGCPRO;
3090 return 1;
3092 #endif
3093 #endif /* !USE_MAC_IMAGE_IO */
3095 #endif /* MAC_OS */
3098 /***********************************************************************
3099 XBM images
3100 ***********************************************************************/
3102 static int xbm_scan P_ ((unsigned char **, unsigned char *, char *, int *));
3103 static int xbm_load P_ ((struct frame *f, struct image *img));
3104 static int xbm_load_image P_ ((struct frame *f, struct image *img,
3105 unsigned char *, unsigned char *));
3106 static int xbm_image_p P_ ((Lisp_Object object));
3107 static int xbm_read_bitmap_data P_ ((struct frame *f,
3108 unsigned char *, unsigned char *,
3109 int *, int *, unsigned char **));
3110 static int xbm_file_p P_ ((Lisp_Object));
3113 /* Indices of image specification fields in xbm_format, below. */
3115 enum xbm_keyword_index
3117 XBM_TYPE,
3118 XBM_FILE,
3119 XBM_WIDTH,
3120 XBM_HEIGHT,
3121 XBM_DATA,
3122 XBM_FOREGROUND,
3123 XBM_BACKGROUND,
3124 XBM_ASCENT,
3125 XBM_MARGIN,
3126 XBM_RELIEF,
3127 XBM_ALGORITHM,
3128 XBM_HEURISTIC_MASK,
3129 XBM_MASK,
3130 XBM_LAST
3133 /* Vector of image_keyword structures describing the format
3134 of valid XBM image specifications. */
3136 static struct image_keyword xbm_format[XBM_LAST] =
3138 {":type", IMAGE_SYMBOL_VALUE, 1},
3139 {":file", IMAGE_STRING_VALUE, 0},
3140 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
3141 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
3142 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3143 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
3144 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
3145 {":ascent", IMAGE_ASCENT_VALUE, 0},
3146 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3147 {":relief", IMAGE_INTEGER_VALUE, 0},
3148 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3149 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3150 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
3153 /* Structure describing the image type XBM. */
3155 static struct image_type xbm_type =
3157 &Qxbm,
3158 xbm_image_p,
3159 xbm_load,
3160 x_clear_image,
3161 NULL
3164 /* Tokens returned from xbm_scan. */
3166 enum xbm_token
3168 XBM_TK_IDENT = 256,
3169 XBM_TK_NUMBER
3173 /* Return non-zero if OBJECT is a valid XBM-type image specification.
3174 A valid specification is a list starting with the symbol `image'
3175 The rest of the list is a property list which must contain an
3176 entry `:type xbm..
3178 If the specification specifies a file to load, it must contain
3179 an entry `:file FILENAME' where FILENAME is a string.
3181 If the specification is for a bitmap loaded from memory it must
3182 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
3183 WIDTH and HEIGHT are integers > 0. DATA may be:
3185 1. a string large enough to hold the bitmap data, i.e. it must
3186 have a size >= (WIDTH + 7) / 8 * HEIGHT
3188 2. a bool-vector of size >= WIDTH * HEIGHT
3190 3. a vector of strings or bool-vectors, one for each line of the
3191 bitmap.
3193 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
3194 may not be specified in this case because they are defined in the
3195 XBM file.
3197 Both the file and data forms may contain the additional entries
3198 `:background COLOR' and `:foreground COLOR'. If not present,
3199 foreground and background of the frame on which the image is
3200 displayed is used. */
3202 static int
3203 xbm_image_p (object)
3204 Lisp_Object object;
3206 struct image_keyword kw[XBM_LAST];
3208 bcopy (xbm_format, kw, sizeof kw);
3209 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
3210 return 0;
3212 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
3214 if (kw[XBM_FILE].count)
3216 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
3217 return 0;
3219 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
3221 /* In-memory XBM file. */
3222 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
3223 return 0;
3225 else
3227 Lisp_Object data;
3228 int width, height;
3230 /* Entries for `:width', `:height' and `:data' must be present. */
3231 if (!kw[XBM_WIDTH].count
3232 || !kw[XBM_HEIGHT].count
3233 || !kw[XBM_DATA].count)
3234 return 0;
3236 data = kw[XBM_DATA].value;
3237 width = XFASTINT (kw[XBM_WIDTH].value);
3238 height = XFASTINT (kw[XBM_HEIGHT].value);
3240 /* Check type of data, and width and height against contents of
3241 data. */
3242 if (VECTORP (data))
3244 int i;
3246 /* Number of elements of the vector must be >= height. */
3247 if (XVECTOR (data)->size < height)
3248 return 0;
3250 /* Each string or bool-vector in data must be large enough
3251 for one line of the image. */
3252 for (i = 0; i < height; ++i)
3254 Lisp_Object elt = XVECTOR (data)->contents[i];
3256 if (STRINGP (elt))
3258 if (SCHARS (elt)
3259 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
3260 return 0;
3262 else if (BOOL_VECTOR_P (elt))
3264 if (XBOOL_VECTOR (elt)->size < width)
3265 return 0;
3267 else
3268 return 0;
3271 else if (STRINGP (data))
3273 if (SCHARS (data)
3274 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
3275 return 0;
3277 else if (BOOL_VECTOR_P (data))
3279 if (XBOOL_VECTOR (data)->size < width * height)
3280 return 0;
3282 else
3283 return 0;
3286 return 1;
3290 /* Scan a bitmap file. FP is the stream to read from. Value is
3291 either an enumerator from enum xbm_token, or a character for a
3292 single-character token, or 0 at end of file. If scanning an
3293 identifier, store the lexeme of the identifier in SVAL. If
3294 scanning a number, store its value in *IVAL. */
3296 static int
3297 xbm_scan (s, end, sval, ival)
3298 unsigned char **s, *end;
3299 char *sval;
3300 int *ival;
3302 unsigned int c;
3304 loop:
3306 /* Skip white space. */
3307 while (*s < end && (c = *(*s)++, isspace (c)))
3310 if (*s >= end)
3311 c = 0;
3312 else if (isdigit (c))
3314 int value = 0, digit;
3316 if (c == '0' && *s < end)
3318 c = *(*s)++;
3319 if (c == 'x' || c == 'X')
3321 while (*s < end)
3323 c = *(*s)++;
3324 if (isdigit (c))
3325 digit = c - '0';
3326 else if (c >= 'a' && c <= 'f')
3327 digit = c - 'a' + 10;
3328 else if (c >= 'A' && c <= 'F')
3329 digit = c - 'A' + 10;
3330 else
3331 break;
3332 value = 16 * value + digit;
3335 else if (isdigit (c))
3337 value = c - '0';
3338 while (*s < end
3339 && (c = *(*s)++, isdigit (c)))
3340 value = 8 * value + c - '0';
3343 else
3345 value = c - '0';
3346 while (*s < end
3347 && (c = *(*s)++, isdigit (c)))
3348 value = 10 * value + c - '0';
3351 if (*s < end)
3352 *s = *s - 1;
3353 *ival = value;
3354 c = XBM_TK_NUMBER;
3356 else if (isalpha (c) || c == '_')
3358 *sval++ = c;
3359 while (*s < end
3360 && (c = *(*s)++, (isalnum (c) || c == '_')))
3361 *sval++ = c;
3362 *sval = 0;
3363 if (*s < end)
3364 *s = *s - 1;
3365 c = XBM_TK_IDENT;
3367 else if (c == '/' && **s == '*')
3369 /* C-style comment. */
3370 ++*s;
3371 while (**s && (**s != '*' || *(*s + 1) != '/'))
3372 ++*s;
3373 if (**s)
3375 *s += 2;
3376 goto loop;
3380 return c;
3383 #ifdef HAVE_NTGUI
3385 /* Create a Windows bitmap from X bitmap data. */
3386 static HBITMAP
3387 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
3389 static unsigned char swap_nibble[16]
3390 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
3391 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
3392 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
3393 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
3394 int i, j, w1, w2;
3395 unsigned char *bits, *p;
3396 HBITMAP bmp;
3398 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
3399 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
3400 bits = (unsigned char *) alloca (height * w2);
3401 bzero (bits, height * w2);
3402 for (i = 0; i < height; i++)
3404 p = bits + i*w2;
3405 for (j = 0; j < w1; j++)
3407 /* Bitswap XBM bytes to match how Windows does things. */
3408 unsigned char c = *data++;
3409 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
3410 | (swap_nibble[(c>>4) & 0xf]));
3413 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
3415 return bmp;
3418 static void
3419 convert_mono_to_color_image (f, img, foreground, background)
3420 struct frame *f;
3421 struct image *img;
3422 COLORREF foreground, background;
3424 HDC hdc, old_img_dc, new_img_dc;
3425 HGDIOBJ old_prev, new_prev;
3426 HBITMAP new_pixmap;
3428 hdc = get_frame_dc (f);
3429 old_img_dc = CreateCompatibleDC (hdc);
3430 new_img_dc = CreateCompatibleDC (hdc);
3431 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
3432 release_frame_dc (f, hdc);
3433 old_prev = SelectObject (old_img_dc, img->pixmap);
3434 new_prev = SelectObject (new_img_dc, new_pixmap);
3435 /* Windows convention for mono bitmaps is black = background,
3436 white = foreground. */
3437 SetTextColor (new_img_dc, background);
3438 SetBkColor (new_img_dc, foreground);
3440 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
3441 0, 0, SRCCOPY);
3443 SelectObject (old_img_dc, old_prev);
3444 SelectObject (new_img_dc, new_prev);
3445 DeleteDC (old_img_dc);
3446 DeleteDC (new_img_dc);
3447 DeleteObject (img->pixmap);
3448 if (new_pixmap == 0)
3449 fprintf (stderr, "Failed to convert image to color.\n");
3450 else
3451 img->pixmap = new_pixmap;
3454 #define XBM_BIT_SHUFFLE(b) (~(b))
3456 #else
3458 #define XBM_BIT_SHUFFLE(b) (b)
3460 #endif /* HAVE_NTGUI */
3463 static void
3464 Create_Pixmap_From_Bitmap_Data(f, img, data, fg, bg, non_default_colors)
3465 struct frame *f;
3466 struct image *img;
3467 char *data;
3468 RGB_PIXEL_COLOR fg, bg;
3469 int non_default_colors;
3471 #ifdef HAVE_NTGUI
3472 img->pixmap
3473 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
3475 /* If colors were specified, transfer the bitmap to a color one. */
3476 if (non_default_colors)
3477 convert_mono_to_color_image (f, img, fg, bg);
3478 #else
3479 img->pixmap
3480 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
3481 FRAME_X_WINDOW (f),
3482 data,
3483 img->width, img->height,
3484 fg, bg,
3485 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
3486 #endif /* HAVE_NTGUI */
3491 /* Replacement for XReadBitmapFileData which isn't available under old
3492 X versions. CONTENTS is a pointer to a buffer to parse; END is the
3493 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
3494 the image. Return in *DATA the bitmap data allocated with xmalloc.
3495 Value is non-zero if successful. DATA null means just test if
3496 CONTENTS looks like an in-memory XBM file. */
3498 static int
3499 xbm_read_bitmap_data (f, contents, end, width, height, data)
3500 struct frame *f;
3501 unsigned char *contents, *end;
3502 int *width, *height;
3503 unsigned char **data;
3505 unsigned char *s = contents;
3506 char buffer[BUFSIZ];
3507 int padding_p = 0;
3508 int v10 = 0;
3509 int bytes_per_line, i, nbytes;
3510 unsigned char *p;
3511 int value;
3512 int LA1;
3514 #define match() \
3515 LA1 = xbm_scan (&s, end, buffer, &value)
3517 #define expect(TOKEN) \
3518 if (LA1 != (TOKEN)) \
3519 goto failure; \
3520 else \
3521 match ()
3523 #define expect_ident(IDENT) \
3524 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
3525 match (); \
3526 else \
3527 goto failure
3529 *width = *height = -1;
3530 if (data)
3531 *data = NULL;
3532 LA1 = xbm_scan (&s, end, buffer, &value);
3534 /* Parse defines for width, height and hot-spots. */
3535 while (LA1 == '#')
3537 match ();
3538 expect_ident ("define");
3539 expect (XBM_TK_IDENT);
3541 if (LA1 == XBM_TK_NUMBER)
3543 char *p = strrchr (buffer, '_');
3544 p = p ? p + 1 : buffer;
3545 if (strcmp (p, "width") == 0)
3546 *width = value;
3547 else if (strcmp (p, "height") == 0)
3548 *height = value;
3550 expect (XBM_TK_NUMBER);
3553 if (!check_image_size (f, *width, *height))
3554 goto failure;
3555 else if (data == NULL)
3556 goto success;
3558 /* Parse bits. Must start with `static'. */
3559 expect_ident ("static");
3560 if (LA1 == XBM_TK_IDENT)
3562 if (strcmp (buffer, "unsigned") == 0)
3564 match ();
3565 expect_ident ("char");
3567 else if (strcmp (buffer, "short") == 0)
3569 match ();
3570 v10 = 1;
3571 if (*width % 16 && *width % 16 < 9)
3572 padding_p = 1;
3574 else if (strcmp (buffer, "char") == 0)
3575 match ();
3576 else
3577 goto failure;
3579 else
3580 goto failure;
3582 expect (XBM_TK_IDENT);
3583 expect ('[');
3584 expect (']');
3585 expect ('=');
3586 expect ('{');
3588 bytes_per_line = (*width + 7) / 8 + padding_p;
3589 nbytes = bytes_per_line * *height;
3590 p = *data = (unsigned char *) xmalloc (nbytes);
3592 if (v10)
3594 for (i = 0; i < nbytes; i += 2)
3596 int val = value;
3597 expect (XBM_TK_NUMBER);
3599 *p++ = XBM_BIT_SHUFFLE (val);
3600 if (!padding_p || ((i + 2) % bytes_per_line))
3601 *p++ = XBM_BIT_SHUFFLE (value >> 8);
3603 if (LA1 == ',' || LA1 == '}')
3604 match ();
3605 else
3606 goto failure;
3609 else
3611 for (i = 0; i < nbytes; ++i)
3613 int val = value;
3614 expect (XBM_TK_NUMBER);
3616 *p++ = XBM_BIT_SHUFFLE (val);
3618 if (LA1 == ',' || LA1 == '}')
3619 match ();
3620 else
3621 goto failure;
3625 success:
3626 return 1;
3628 failure:
3630 if (data && *data)
3632 xfree (*data);
3633 *data = NULL;
3635 return 0;
3637 #undef match
3638 #undef expect
3639 #undef expect_ident
3643 /* Load XBM image IMG which will be displayed on frame F from buffer
3644 CONTENTS. END is the end of the buffer. Value is non-zero if
3645 successful. */
3647 static int
3648 xbm_load_image (f, img, contents, end)
3649 struct frame *f;
3650 struct image *img;
3651 unsigned char *contents, *end;
3653 int rc;
3654 unsigned char *data;
3655 int success_p = 0;
3657 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height, &data);
3658 if (rc)
3660 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3661 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3662 int non_default_colors = 0;
3663 Lisp_Object value;
3665 xassert (img->width > 0 && img->height > 0);
3667 /* Get foreground and background colors, maybe allocate colors. */
3668 value = image_spec_value (img->spec, QCforeground, NULL);
3669 if (!NILP (value))
3671 foreground = x_alloc_image_color (f, img, value, foreground);
3672 non_default_colors = 1;
3674 value = image_spec_value (img->spec, QCbackground, NULL);
3675 if (!NILP (value))
3677 background = x_alloc_image_color (f, img, value, background);
3678 img->background = background;
3679 img->background_valid = 1;
3680 non_default_colors = 1;
3683 Create_Pixmap_From_Bitmap_Data (f, img, data,
3684 foreground, background,
3685 non_default_colors);
3686 xfree (data);
3688 if (img->pixmap == NO_PIXMAP)
3690 x_clear_image (f, img);
3691 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
3693 else
3694 success_p = 1;
3696 else
3697 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3699 return success_p;
3703 /* Value is non-zero if DATA looks like an in-memory XBM file. */
3705 static int
3706 xbm_file_p (data)
3707 Lisp_Object data;
3709 int w, h;
3710 return (STRINGP (data)
3711 && xbm_read_bitmap_data (NULL, SDATA (data),
3712 (SDATA (data)
3713 + SBYTES (data)),
3714 &w, &h, NULL));
3718 /* Fill image IMG which is used on frame F with pixmap data. Value is
3719 non-zero if successful. */
3721 static int
3722 xbm_load (f, img)
3723 struct frame *f;
3724 struct image *img;
3726 int success_p = 0;
3727 Lisp_Object file_name;
3729 xassert (xbm_image_p (img->spec));
3731 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3732 file_name = image_spec_value (img->spec, QCfile, NULL);
3733 if (STRINGP (file_name))
3735 Lisp_Object file;
3736 unsigned char *contents;
3737 int size;
3738 struct gcpro gcpro1;
3740 file = x_find_image_file (file_name);
3741 GCPRO1 (file);
3742 if (!STRINGP (file))
3744 image_error ("Cannot find image file `%s'", file_name, Qnil);
3745 UNGCPRO;
3746 return 0;
3749 contents = slurp_file (SDATA (file), &size);
3750 if (contents == NULL)
3752 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3753 UNGCPRO;
3754 return 0;
3757 success_p = xbm_load_image (f, img, contents, contents + size);
3758 UNGCPRO;
3760 else
3762 struct image_keyword fmt[XBM_LAST];
3763 Lisp_Object data;
3764 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3765 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3766 int non_default_colors = 0;
3767 char *bits;
3768 int parsed_p;
3769 int in_memory_file_p = 0;
3771 /* See if data looks like an in-memory XBM file. */
3772 data = image_spec_value (img->spec, QCdata, NULL);
3773 in_memory_file_p = xbm_file_p (data);
3775 /* Parse the image specification. */
3776 bcopy (xbm_format, fmt, sizeof fmt);
3777 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3778 xassert (parsed_p);
3780 /* Get specified width, and height. */
3781 if (!in_memory_file_p)
3783 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3784 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3785 xassert (img->width > 0 && img->height > 0);
3788 /* Get foreground and background colors, maybe allocate colors. */
3789 if (fmt[XBM_FOREGROUND].count
3790 && STRINGP (fmt[XBM_FOREGROUND].value))
3792 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3793 foreground);
3794 non_default_colors = 1;
3797 if (fmt[XBM_BACKGROUND].count
3798 && STRINGP (fmt[XBM_BACKGROUND].value))
3800 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3801 background);
3802 non_default_colors = 1;
3805 if (in_memory_file_p)
3806 success_p = xbm_load_image (f, img, SDATA (data),
3807 (SDATA (data)
3808 + SBYTES (data)));
3809 else
3811 if (VECTORP (data))
3813 int i;
3814 char *p;
3815 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3817 p = bits = (char *) alloca (nbytes * img->height);
3818 for (i = 0; i < img->height; ++i, p += nbytes)
3820 Lisp_Object line = XVECTOR (data)->contents[i];
3821 if (STRINGP (line))
3822 bcopy (SDATA (line), p, nbytes);
3823 else
3824 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
3827 else if (STRINGP (data))
3828 bits = SDATA (data);
3829 else
3830 bits = XBOOL_VECTOR (data)->data;
3832 #ifdef WINDOWSNT
3834 char *invertedBits;
3835 int nbytes, i;
3836 /* Windows mono bitmaps are reversed compared with X. */
3837 invertedBits = bits;
3838 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
3839 * img->height;
3840 bits = (char *) alloca(nbytes);
3841 for (i = 0; i < nbytes; i++)
3842 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3844 #endif
3845 /* Create the pixmap. */
3847 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3848 foreground, background,
3849 non_default_colors);
3850 if (img->pixmap)
3851 success_p = 1;
3852 else
3854 image_error ("Unable to create pixmap for XBM image `%s'",
3855 img->spec, Qnil);
3856 x_clear_image (f, img);
3861 return success_p;
3866 /***********************************************************************
3867 XPM images
3868 ***********************************************************************/
3870 #if defined (HAVE_XPM) || defined (MAC_OS)
3872 static int xpm_image_p P_ ((Lisp_Object object));
3873 static int xpm_load P_ ((struct frame *f, struct image *img));
3874 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
3876 #endif /* HAVE_XPM || MAC_OS */
3878 #ifdef HAVE_XPM
3879 #ifdef HAVE_NTGUI
3880 /* Indicate to xpm.h that we don't have Xlib. */
3881 #define FOR_MSW
3882 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3883 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3884 #define XColor xpm_XColor
3885 #define XImage xpm_XImage
3886 #define Display xpm_Display
3887 #define PIXEL_ALREADY_TYPEDEFED
3888 #include "X11/xpm.h"
3889 #undef FOR_MSW
3890 #undef XColor
3891 #undef XImage
3892 #undef Display
3893 #undef PIXEL_ALREADY_TYPEDEFED
3894 #else
3895 #include "X11/xpm.h"
3896 #endif /* HAVE_NTGUI */
3897 #endif /* HAVE_XPM */
3899 #if defined (HAVE_XPM) || defined (MAC_OS)
3900 /* The symbol `xpm' identifying XPM-format images. */
3902 Lisp_Object Qxpm;
3904 /* Indices of image specification fields in xpm_format, below. */
3906 enum xpm_keyword_index
3908 XPM_TYPE,
3909 XPM_FILE,
3910 XPM_DATA,
3911 XPM_ASCENT,
3912 XPM_MARGIN,
3913 XPM_RELIEF,
3914 XPM_ALGORITHM,
3915 XPM_HEURISTIC_MASK,
3916 XPM_MASK,
3917 XPM_COLOR_SYMBOLS,
3918 XPM_BACKGROUND,
3919 XPM_LAST
3922 /* Vector of image_keyword structures describing the format
3923 of valid XPM image specifications. */
3925 static struct image_keyword xpm_format[XPM_LAST] =
3927 {":type", IMAGE_SYMBOL_VALUE, 1},
3928 {":file", IMAGE_STRING_VALUE, 0},
3929 {":data", IMAGE_STRING_VALUE, 0},
3930 {":ascent", IMAGE_ASCENT_VALUE, 0},
3931 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3932 {":relief", IMAGE_INTEGER_VALUE, 0},
3933 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3934 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3935 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3936 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3937 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3940 /* Structure describing the image type XPM. */
3942 static struct image_type xpm_type =
3944 &Qxpm,
3945 xpm_image_p,
3946 xpm_load,
3947 x_clear_image,
3948 NULL
3951 #ifdef HAVE_X_WINDOWS
3953 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3954 functions for allocating image colors. Our own functions handle
3955 color allocation failures more gracefully than the ones on the XPM
3956 lib. */
3958 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3959 #define ALLOC_XPM_COLORS
3960 #endif
3961 #endif /* HAVE_X_WINDOWS */
3963 #ifdef ALLOC_XPM_COLORS
3965 static void xpm_init_color_cache P_ ((struct frame *, XpmAttributes *));
3966 static void xpm_free_color_cache P_ ((void));
3967 static int xpm_lookup_color P_ ((struct frame *, char *, XColor *));
3968 static int xpm_color_bucket P_ ((char *));
3969 static struct xpm_cached_color *xpm_cache_color P_ ((struct frame *, char *,
3970 XColor *, int));
3972 /* An entry in a hash table used to cache color definitions of named
3973 colors. This cache is necessary to speed up XPM image loading in
3974 case we do color allocations ourselves. Without it, we would need
3975 a call to XParseColor per pixel in the image. */
3977 struct xpm_cached_color
3979 /* Next in collision chain. */
3980 struct xpm_cached_color *next;
3982 /* Color definition (RGB and pixel color). */
3983 XColor color;
3985 /* Color name. */
3986 char name[1];
3989 /* The hash table used for the color cache, and its bucket vector
3990 size. */
3992 #define XPM_COLOR_CACHE_BUCKETS 1001
3993 struct xpm_cached_color **xpm_color_cache;
3995 /* Initialize the color cache. */
3997 static void
3998 xpm_init_color_cache (f, attrs)
3999 struct frame *f;
4000 XpmAttributes *attrs;
4002 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
4003 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
4004 memset (xpm_color_cache, 0, nbytes);
4005 init_color_table ();
4007 if (attrs->valuemask & XpmColorSymbols)
4009 int i;
4010 XColor color;
4012 for (i = 0; i < attrs->numsymbols; ++i)
4013 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
4014 attrs->colorsymbols[i].value, &color))
4016 color.pixel = lookup_rgb_color (f, color.red, color.green,
4017 color.blue);
4018 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
4023 /* Free the color cache. */
4025 static void
4026 xpm_free_color_cache ()
4028 struct xpm_cached_color *p, *next;
4029 int i;
4031 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
4032 for (p = xpm_color_cache[i]; p; p = next)
4034 next = p->next;
4035 xfree (p);
4038 xfree (xpm_color_cache);
4039 xpm_color_cache = NULL;
4040 free_color_table ();
4043 /* Return the bucket index for color named COLOR_NAME in the color
4044 cache. */
4046 static int
4047 xpm_color_bucket (color_name)
4048 char *color_name;
4050 unsigned h = 0;
4051 char *s;
4053 for (s = color_name; *s; ++s)
4054 h = (h << 2) ^ *s;
4055 return h %= XPM_COLOR_CACHE_BUCKETS;
4059 /* On frame F, cache values COLOR for color with name COLOR_NAME.
4060 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
4061 entry added. */
4063 static struct xpm_cached_color *
4064 xpm_cache_color (f, color_name, color, bucket)
4065 struct frame *f;
4066 char *color_name;
4067 XColor *color;
4068 int bucket;
4070 size_t nbytes;
4071 struct xpm_cached_color *p;
4073 if (bucket < 0)
4074 bucket = xpm_color_bucket (color_name);
4076 nbytes = sizeof *p + strlen (color_name);
4077 p = (struct xpm_cached_color *) xmalloc (nbytes);
4078 strcpy (p->name, color_name);
4079 p->color = *color;
4080 p->next = xpm_color_cache[bucket];
4081 xpm_color_cache[bucket] = p;
4082 return p;
4085 /* Look up color COLOR_NAME for frame F in the color cache. If found,
4086 return the cached definition in *COLOR. Otherwise, make a new
4087 entry in the cache and allocate the color. Value is zero if color
4088 allocation failed. */
4090 static int
4091 xpm_lookup_color (f, color_name, color)
4092 struct frame *f;
4093 char *color_name;
4094 XColor *color;
4096 struct xpm_cached_color *p;
4097 int h = xpm_color_bucket (color_name);
4099 for (p = xpm_color_cache[h]; p; p = p->next)
4100 if (strcmp (p->name, color_name) == 0)
4101 break;
4103 if (p != NULL)
4104 *color = p->color;
4105 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
4106 color_name, color))
4108 color->pixel = lookup_rgb_color (f, color->red, color->green,
4109 color->blue);
4110 p = xpm_cache_color (f, color_name, color, h);
4112 /* You get `opaque' at least from ImageMagick converting pbm to xpm
4113 with transparency, and it's useful. */
4114 else if (strcmp ("opaque", color_name) == 0)
4116 bzero (color, sizeof (XColor)); /* Is this necessary/correct? */
4117 color->pixel = FRAME_FOREGROUND_PIXEL (f);
4118 p = xpm_cache_color (f, color_name, color, h);
4121 return p != NULL;
4125 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
4126 CLOSURE is a pointer to the frame on which we allocate the
4127 color. Return in *COLOR the allocated color. Value is non-zero
4128 if successful. */
4130 static int
4131 xpm_alloc_color (dpy, cmap, color_name, color, closure)
4132 Display *dpy;
4133 Colormap cmap;
4134 char *color_name;
4135 XColor *color;
4136 void *closure;
4138 return xpm_lookup_color ((struct frame *) closure, color_name, color);
4142 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
4143 is a pointer to the frame on which we allocate the color. Value is
4144 non-zero if successful. */
4146 static int
4147 xpm_free_colors (dpy, cmap, pixels, npixels, closure)
4148 Display *dpy;
4149 Colormap cmap;
4150 Pixel *pixels;
4151 int npixels;
4152 void *closure;
4154 return 1;
4157 #endif /* ALLOC_XPM_COLORS */
4160 #ifdef HAVE_NTGUI
4162 /* XPM library details. */
4164 DEF_IMGLIB_FN (XpmFreeAttributes);
4165 DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
4166 DEF_IMGLIB_FN (XpmReadFileToImage);
4167 DEF_IMGLIB_FN (XImageFree);
4169 static int
4170 init_xpm_functions (Lisp_Object libraries)
4172 HMODULE library;
4174 if (!(library = w32_delayed_load (libraries, Qxpm)))
4175 return 0;
4177 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
4178 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
4179 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
4180 LOAD_IMGLIB_FN (library, XImageFree);
4181 return 1;
4184 #endif /* HAVE_NTGUI */
4187 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
4188 for XPM images. Such a list must consist of conses whose car and
4189 cdr are strings. */
4191 static int
4192 xpm_valid_color_symbols_p (color_symbols)
4193 Lisp_Object color_symbols;
4195 while (CONSP (color_symbols))
4197 Lisp_Object sym = XCAR (color_symbols);
4198 if (!CONSP (sym)
4199 || !STRINGP (XCAR (sym))
4200 || !STRINGP (XCDR (sym)))
4201 break;
4202 color_symbols = XCDR (color_symbols);
4205 return NILP (color_symbols);
4209 /* Value is non-zero if OBJECT is a valid XPM image specification. */
4211 static int
4212 xpm_image_p (object)
4213 Lisp_Object object;
4215 struct image_keyword fmt[XPM_LAST];
4216 bcopy (xpm_format, fmt, sizeof fmt);
4217 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
4218 /* Either `:file' or `:data' must be present. */
4219 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
4220 /* Either no `:color-symbols' or it's a list of conses
4221 whose car and cdr are strings. */
4222 && (fmt[XPM_COLOR_SYMBOLS].count == 0
4223 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
4226 #endif /* HAVE_XPM || MAC_OS */
4228 #if defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
4230 x_create_bitmap_from_xpm_data (f, bits)
4231 struct frame *f;
4232 char **bits;
4234 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4235 int id, rc;
4236 XpmAttributes attrs;
4237 Pixmap bitmap, mask;
4239 bzero (&attrs, sizeof attrs);
4241 attrs.visual = FRAME_X_VISUAL (f);
4242 attrs.colormap = FRAME_X_COLORMAP (f);
4243 attrs.valuemask |= XpmVisual;
4244 attrs.valuemask |= XpmColormap;
4246 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4247 bits, &bitmap, &mask, &attrs);
4248 if (rc != XpmSuccess)
4250 XpmFreeAttributes (&attrs);
4251 return -1;
4254 id = x_allocate_bitmap_record (f);
4255 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
4256 dpyinfo->bitmaps[id - 1].have_mask = 1;
4257 dpyinfo->bitmaps[id - 1].mask = mask;
4258 dpyinfo->bitmaps[id - 1].file = NULL;
4259 dpyinfo->bitmaps[id - 1].height = attrs.height;
4260 dpyinfo->bitmaps[id - 1].width = attrs.width;
4261 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
4262 dpyinfo->bitmaps[id - 1].refcount = 1;
4264 XpmFreeAttributes (&attrs);
4265 return id;
4267 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
4269 /* Load image IMG which will be displayed on frame F. Value is
4270 non-zero if successful. */
4272 #ifdef HAVE_XPM
4274 static int
4275 xpm_load (f, img)
4276 struct frame *f;
4277 struct image *img;
4279 int rc;
4280 XpmAttributes attrs;
4281 Lisp_Object specified_file, color_symbols;
4282 #ifdef HAVE_NTGUI
4283 HDC hdc;
4284 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
4285 #endif /* HAVE_NTGUI */
4287 /* Configure the XPM lib. Use the visual of frame F. Allocate
4288 close colors. Return colors allocated. */
4289 bzero (&attrs, sizeof attrs);
4291 #ifndef HAVE_NTGUI
4292 attrs.visual = FRAME_X_VISUAL (f);
4293 attrs.colormap = FRAME_X_COLORMAP (f);
4294 attrs.valuemask |= XpmVisual;
4295 attrs.valuemask |= XpmColormap;
4296 #endif /* HAVE_NTGUI */
4298 #ifdef ALLOC_XPM_COLORS
4299 /* Allocate colors with our own functions which handle
4300 failing color allocation more gracefully. */
4301 attrs.color_closure = f;
4302 attrs.alloc_color = xpm_alloc_color;
4303 attrs.free_colors = xpm_free_colors;
4304 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
4305 #else /* not ALLOC_XPM_COLORS */
4306 /* Let the XPM lib allocate colors. */
4307 attrs.valuemask |= XpmReturnAllocPixels;
4308 #ifdef XpmAllocCloseColors
4309 attrs.alloc_close_colors = 1;
4310 attrs.valuemask |= XpmAllocCloseColors;
4311 #else /* not XpmAllocCloseColors */
4312 attrs.closeness = 600;
4313 attrs.valuemask |= XpmCloseness;
4314 #endif /* not XpmAllocCloseColors */
4315 #endif /* ALLOC_XPM_COLORS */
4317 /* If image specification contains symbolic color definitions, add
4318 these to `attrs'. */
4319 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4320 if (CONSP (color_symbols))
4322 Lisp_Object tail;
4323 XpmColorSymbol *xpm_syms;
4324 int i, size;
4326 attrs.valuemask |= XpmColorSymbols;
4328 /* Count number of symbols. */
4329 attrs.numsymbols = 0;
4330 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
4331 ++attrs.numsymbols;
4333 /* Allocate an XpmColorSymbol array. */
4334 size = attrs.numsymbols * sizeof *xpm_syms;
4335 xpm_syms = (XpmColorSymbol *) alloca (size);
4336 bzero (xpm_syms, size);
4337 attrs.colorsymbols = xpm_syms;
4339 /* Fill the color symbol array. */
4340 for (tail = color_symbols, i = 0;
4341 CONSP (tail);
4342 ++i, tail = XCDR (tail))
4344 Lisp_Object name = XCAR (XCAR (tail));
4345 Lisp_Object color = XCDR (XCAR (tail));
4346 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
4347 strcpy (xpm_syms[i].name, SDATA (name));
4348 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
4349 strcpy (xpm_syms[i].value, SDATA (color));
4353 /* Create a pixmap for the image, either from a file, or from a
4354 string buffer containing data in the same format as an XPM file. */
4355 #ifdef ALLOC_XPM_COLORS
4356 xpm_init_color_cache (f, &attrs);
4357 #endif
4359 specified_file = image_spec_value (img->spec, QCfile, NULL);
4361 #ifdef HAVE_NTGUI
4363 HDC frame_dc = get_frame_dc (f);
4364 hdc = CreateCompatibleDC (frame_dc);
4365 release_frame_dc (f, frame_dc);
4367 #endif /* HAVE_NTGUI */
4369 if (STRINGP (specified_file))
4371 Lisp_Object file = x_find_image_file (specified_file);
4372 if (!STRINGP (file))
4374 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4375 return 0;
4378 #ifdef HAVE_NTGUI
4379 /* XpmReadFileToPixmap is not available in the Windows port of
4380 libxpm. But XpmReadFileToImage almost does what we want. */
4381 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
4382 &xpm_image, &xpm_mask,
4383 &attrs);
4384 #else
4385 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4386 SDATA (file), &img->pixmap, &img->mask,
4387 &attrs);
4388 #endif /* HAVE_NTGUI */
4390 else
4392 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
4393 #ifdef HAVE_NTGUI
4394 /* XpmCreatePixmapFromBuffer is not available in the Windows port
4395 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
4396 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
4397 &xpm_image, &xpm_mask,
4398 &attrs);
4399 #else
4400 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4401 SDATA (buffer),
4402 &img->pixmap, &img->mask,
4403 &attrs);
4404 #endif /* HAVE_NTGUI */
4407 if (rc == XpmSuccess)
4409 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
4410 img->colors = colors_in_color_table (&img->ncolors);
4411 #else /* not ALLOC_XPM_COLORS */
4412 int i;
4414 #ifdef HAVE_NTGUI
4415 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
4416 plus some duplicate attributes. */
4417 if (xpm_image && xpm_image->bitmap)
4419 img->pixmap = xpm_image->bitmap;
4420 /* XImageFree in libXpm frees XImage struct without destroying
4421 the bitmap, which is what we want. */
4422 fn_XImageFree (xpm_image);
4424 if (xpm_mask && xpm_mask->bitmap)
4426 /* The mask appears to be inverted compared with what we expect.
4427 TODO: invert our expectations. See other places where we
4428 have to invert bits because our idea of masks is backwards. */
4429 HGDIOBJ old_obj;
4430 old_obj = SelectObject (hdc, xpm_mask->bitmap);
4432 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
4433 SelectObject (hdc, old_obj);
4435 img->mask = xpm_mask->bitmap;
4436 fn_XImageFree (xpm_mask);
4437 DeleteDC (hdc);
4440 DeleteDC (hdc);
4441 #endif /* HAVE_NTGUI */
4443 /* Remember allocated colors. */
4444 img->ncolors = attrs.nalloc_pixels;
4445 img->colors = (unsigned long *) xmalloc (img->ncolors
4446 * sizeof *img->colors);
4447 for (i = 0; i < attrs.nalloc_pixels; ++i)
4449 img->colors[i] = attrs.alloc_pixels[i];
4450 #ifdef DEBUG_X_COLORS
4451 register_color (img->colors[i]);
4452 #endif
4454 #endif /* not ALLOC_XPM_COLORS */
4456 img->width = attrs.width;
4457 img->height = attrs.height;
4458 xassert (img->width > 0 && img->height > 0);
4460 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
4461 #ifdef HAVE_NTGUI
4462 fn_XpmFreeAttributes (&attrs);
4463 #else
4464 XpmFreeAttributes (&attrs);
4465 #endif /* HAVE_NTGUI */
4467 else
4469 #ifdef HAVE_NTGUI
4470 DeleteDC (hdc);
4471 #endif /* HAVE_NTGUI */
4473 switch (rc)
4475 case XpmOpenFailed:
4476 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
4477 break;
4479 case XpmFileInvalid:
4480 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4481 break;
4483 case XpmNoMemory:
4484 image_error ("Out of memory (%s)", img->spec, Qnil);
4485 break;
4487 case XpmColorFailed:
4488 image_error ("Color allocation error (%s)", img->spec, Qnil);
4489 break;
4491 default:
4492 image_error ("Unknown error (%s)", img->spec, Qnil);
4493 break;
4497 #ifdef ALLOC_XPM_COLORS
4498 xpm_free_color_cache ();
4499 #endif
4500 return rc == XpmSuccess;
4503 #endif /* HAVE_XPM */
4505 #ifdef MAC_OS
4507 /* XPM support functions for Mac OS where libxpm is not available.
4508 Only XPM version 3 (without any extensions) is supported. */
4510 static int xpm_scan P_ ((const unsigned char **, const unsigned char *,
4511 const unsigned char **, int *));
4512 static Lisp_Object xpm_make_color_table_v
4513 P_ ((void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
4514 Lisp_Object (**) (Lisp_Object, const unsigned char *, int)));
4515 static void xpm_put_color_table_v P_ ((Lisp_Object, const unsigned char *,
4516 int, Lisp_Object));
4517 static Lisp_Object xpm_get_color_table_v P_ ((Lisp_Object,
4518 const unsigned char *, int));
4519 static Lisp_Object xpm_make_color_table_h
4520 P_ ((void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
4521 Lisp_Object (**) (Lisp_Object, const unsigned char *, int)));
4522 static void xpm_put_color_table_h P_ ((Lisp_Object, const unsigned char *,
4523 int, Lisp_Object));
4524 static Lisp_Object xpm_get_color_table_h P_ ((Lisp_Object,
4525 const unsigned char *, int));
4526 static int xpm_str_to_color_key P_ ((const char *));
4527 static int xpm_load_image P_ ((struct frame *, struct image *,
4528 const unsigned char *, const unsigned char *));
4530 /* Tokens returned from xpm_scan. */
4532 enum xpm_token
4534 XPM_TK_IDENT = 256,
4535 XPM_TK_STRING,
4536 XPM_TK_EOF
4539 /* Scan an XPM data and return a character (< 256) or a token defined
4540 by enum xpm_token above. *S and END are the start (inclusive) and
4541 the end (exclusive) addresses of the data, respectively. Advance
4542 *S while scanning. If token is either XPM_TK_IDENT or
4543 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
4544 length of the corresponding token, respectively. */
4546 static int
4547 xpm_scan (s, end, beg, len)
4548 const unsigned char **s, *end, **beg;
4549 int *len;
4551 int c;
4553 while (*s < end)
4555 /* Skip white-space. */
4556 while (*s < end && (c = *(*s)++, isspace (c)))
4559 /* gnus-pointer.xpm uses '-' in its identifier.
4560 sb-dir-plus.xpm uses '+' in its identifier. */
4561 if (isalpha (c) || c == '_' || c == '-' || c == '+')
4563 *beg = *s - 1;
4564 while (*s < end
4565 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
4566 ++*s;
4567 *len = *s - *beg;
4568 return XPM_TK_IDENT;
4570 else if (c == '"')
4572 *beg = *s;
4573 while (*s < end && **s != '"')
4574 ++*s;
4575 *len = *s - *beg;
4576 if (*s < end)
4577 ++*s;
4578 return XPM_TK_STRING;
4580 else if (c == '/')
4582 if (*s < end && **s == '*')
4584 /* C-style comment. */
4585 ++*s;
4588 while (*s < end && *(*s)++ != '*')
4591 while (*s < end && **s != '/');
4592 if (*s < end)
4593 ++*s;
4595 else
4596 return c;
4598 else
4599 return c;
4602 return XPM_TK_EOF;
4605 /* Functions for color table lookup in XPM data. A key is a string
4606 specifying the color of each pixel in XPM data. A value is either
4607 an integer that specifies a pixel color, Qt that specifies
4608 transparency, or Qnil for the unspecified color. If the length of
4609 the key string is one, a vector is used as a table. Otherwise, a
4610 hash table is used. */
4612 static Lisp_Object
4613 xpm_make_color_table_v (put_func, get_func)
4614 void (**put_func) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4615 Lisp_Object (**get_func) (Lisp_Object, const unsigned char *, int);
4617 *put_func = xpm_put_color_table_v;
4618 *get_func = xpm_get_color_table_v;
4619 return Fmake_vector (make_number (256), Qnil);
4622 static void
4623 xpm_put_color_table_v (color_table, chars_start, chars_len, color)
4624 Lisp_Object color_table;
4625 const unsigned char *chars_start;
4626 int chars_len;
4627 Lisp_Object color;
4629 XVECTOR (color_table)->contents[*chars_start] = color;
4632 static Lisp_Object
4633 xpm_get_color_table_v (color_table, chars_start, chars_len)
4634 Lisp_Object color_table;
4635 const unsigned char *chars_start;
4636 int chars_len;
4638 return XVECTOR (color_table)->contents[*chars_start];
4641 static Lisp_Object
4642 xpm_make_color_table_h (put_func, get_func)
4643 void (**put_func) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4644 Lisp_Object (**get_func) (Lisp_Object, const unsigned char *, int);
4646 *put_func = xpm_put_color_table_h;
4647 *get_func = xpm_get_color_table_h;
4648 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
4649 make_float (DEFAULT_REHASH_SIZE),
4650 make_float (DEFAULT_REHASH_THRESHOLD),
4651 Qnil, Qnil, Qnil);
4654 static void
4655 xpm_put_color_table_h (color_table, chars_start, chars_len, color)
4656 Lisp_Object color_table;
4657 const unsigned char *chars_start;
4658 int chars_len;
4659 Lisp_Object color;
4661 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4662 unsigned hash_code;
4663 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4665 hash_lookup (table, chars, &hash_code);
4666 hash_put (table, chars, color, hash_code);
4669 static Lisp_Object
4670 xpm_get_color_table_h (color_table, chars_start, chars_len)
4671 Lisp_Object color_table;
4672 const unsigned char *chars_start;
4673 int chars_len;
4675 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4676 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
4677 NULL);
4679 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4682 enum xpm_color_key {
4683 XPM_COLOR_KEY_S,
4684 XPM_COLOR_KEY_M,
4685 XPM_COLOR_KEY_G4,
4686 XPM_COLOR_KEY_G,
4687 XPM_COLOR_KEY_C
4690 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4692 static int
4693 xpm_str_to_color_key (s)
4694 const char *s;
4696 int i;
4698 for (i = 0;
4699 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
4700 i++)
4701 if (strcmp (xpm_color_key_strings[i], s) == 0)
4702 return i;
4703 return -1;
4706 static int
4707 xpm_load_image (f, img, contents, end)
4708 struct frame *f;
4709 struct image *img;
4710 const unsigned char *contents, *end;
4712 const unsigned char *s = contents, *beg, *str;
4713 unsigned char buffer[BUFSIZ];
4714 int width, height, x, y;
4715 int num_colors, chars_per_pixel;
4716 int len, LA1;
4717 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4718 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
4719 Lisp_Object frame, color_symbols, color_table;
4720 int best_key, have_mask = 0;
4721 XImagePtr ximg = NULL, mask_img = NULL;
4723 #define match() \
4724 LA1 = xpm_scan (&s, end, &beg, &len)
4726 #define expect(TOKEN) \
4727 if (LA1 != (TOKEN)) \
4728 goto failure; \
4729 else \
4730 match ()
4732 #define expect_ident(IDENT) \
4733 if (LA1 == XPM_TK_IDENT \
4734 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4735 match (); \
4736 else \
4737 goto failure
4739 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4740 goto failure;
4741 s += 9;
4742 match();
4743 expect_ident ("static");
4744 expect_ident ("char");
4745 expect ('*');
4746 expect (XPM_TK_IDENT);
4747 expect ('[');
4748 expect (']');
4749 expect ('=');
4750 expect ('{');
4751 expect (XPM_TK_STRING);
4752 if (len >= BUFSIZ)
4753 goto failure;
4754 memcpy (buffer, beg, len);
4755 buffer[len] = '\0';
4756 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4757 &num_colors, &chars_per_pixel) != 4
4758 || width <= 0 || height <= 0
4759 || num_colors <= 0 || chars_per_pixel <= 0)
4760 goto failure;
4762 if (!check_image_size (f, width, height))
4764 image_error ("Invalid image size", Qnil, Qnil);
4765 goto failure;
4768 expect (',');
4770 XSETFRAME (frame, f);
4771 if (!NILP (Fxw_display_color_p (frame)))
4772 best_key = XPM_COLOR_KEY_C;
4773 else if (!NILP (Fx_display_grayscale_p (frame)))
4774 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4775 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4776 else
4777 best_key = XPM_COLOR_KEY_M;
4779 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4780 if (chars_per_pixel == 1)
4781 color_table = xpm_make_color_table_v (&put_color_table,
4782 &get_color_table);
4783 else
4784 color_table = xpm_make_color_table_h (&put_color_table,
4785 &get_color_table);
4787 while (num_colors-- > 0)
4789 unsigned char *color, *max_color;
4790 int key, next_key, max_key = 0;
4791 Lisp_Object symbol_color = Qnil, color_val;
4792 XColor cdef;
4794 expect (XPM_TK_STRING);
4795 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4796 goto failure;
4797 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4798 buffer[len - chars_per_pixel] = '\0';
4800 str = strtok (buffer, " \t");
4801 if (str == NULL)
4802 goto failure;
4803 key = xpm_str_to_color_key (str);
4804 if (key < 0)
4805 goto failure;
4808 color = strtok (NULL, " \t");
4809 if (color == NULL)
4810 goto failure;
4812 while ((str = strtok (NULL, " \t")) != NULL)
4814 next_key = xpm_str_to_color_key (str);
4815 if (next_key >= 0)
4816 break;
4817 color[strlen (color)] = ' ';
4820 if (key == XPM_COLOR_KEY_S)
4822 if (NILP (symbol_color))
4823 symbol_color = build_string (color);
4825 else if (max_key < key && key <= best_key)
4827 max_key = key;
4828 max_color = color;
4830 key = next_key;
4832 while (str);
4834 color_val = Qnil;
4835 if (!NILP (color_symbols) && !NILP (symbol_color))
4837 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4839 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4841 if (xstricmp (SDATA (XCDR (specified_color)), "None") == 0)
4842 color_val = Qt;
4843 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
4844 &cdef, 0))
4845 color_val = make_number (cdef.pixel);
4848 if (NILP (color_val) && max_key > 0)
4850 if (xstricmp (max_color, "None") == 0)
4851 color_val = Qt;
4852 else if (x_defined_color (f, max_color, &cdef, 0))
4853 color_val = make_number (cdef.pixel);
4855 if (!NILP (color_val))
4856 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4858 expect (',');
4861 if (!x_create_x_image_and_pixmap (f, width, height, 0,
4862 &ximg, &img->pixmap)
4863 || !x_create_x_image_and_pixmap (f, width, height, 1,
4864 &mask_img, &img->mask))
4866 image_error ("Out of memory (%s)", img->spec, Qnil);
4867 goto error;
4870 for (y = 0; y < height; y++)
4872 expect (XPM_TK_STRING);
4873 str = beg;
4874 if (len < width * chars_per_pixel)
4875 goto failure;
4876 for (x = 0; x < width; x++, str += chars_per_pixel)
4878 Lisp_Object color_val =
4879 (*get_color_table) (color_table, str, chars_per_pixel);
4881 XPutPixel (ximg, x, y,
4882 (INTEGERP (color_val) ? XINT (color_val)
4883 : FRAME_FOREGROUND_PIXEL (f)));
4884 XPutPixel (mask_img, x, y,
4885 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4886 : (have_mask = 1, PIX_MASK_RETAIN)));
4888 if (y + 1 < height)
4889 expect (',');
4892 img->width = width;
4893 img->height = height;
4895 /* Maybe fill in the background field while we have ximg handy. */
4896 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4897 IMAGE_BACKGROUND (img, f, ximg);
4899 x_put_x_image (f, ximg, img->pixmap, width, height);
4900 x_destroy_x_image (ximg);
4901 if (have_mask)
4903 /* Fill in the background_transparent field while we have the
4904 mask handy. */
4905 image_background_transparent (img, f, mask_img);
4907 x_put_x_image (f, mask_img, img->mask, width, height);
4908 x_destroy_x_image (mask_img);
4910 else
4912 x_destroy_x_image (mask_img);
4913 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4914 img->mask = NO_PIXMAP;
4917 return 1;
4919 failure:
4920 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4921 error:
4922 x_destroy_x_image (ximg);
4923 x_destroy_x_image (mask_img);
4924 x_clear_image (f, img);
4925 return 0;
4927 #undef match
4928 #undef expect
4929 #undef expect_ident
4932 static int
4933 xpm_load (f, img)
4934 struct frame *f;
4935 struct image *img;
4937 int success_p = 0;
4938 Lisp_Object file_name;
4940 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4941 file_name = image_spec_value (img->spec, QCfile, NULL);
4942 if (STRINGP (file_name))
4944 Lisp_Object file;
4945 unsigned char *contents;
4946 int size;
4947 struct gcpro gcpro1;
4949 file = x_find_image_file (file_name);
4950 GCPRO1 (file);
4951 if (!STRINGP (file))
4953 image_error ("Cannot find image file `%s'", file_name, Qnil);
4954 UNGCPRO;
4955 return 0;
4958 contents = slurp_file (SDATA (file), &size);
4959 if (contents == NULL)
4961 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4962 UNGCPRO;
4963 return 0;
4966 success_p = xpm_load_image (f, img, contents, contents + size);
4967 xfree (contents);
4968 UNGCPRO;
4970 else
4972 Lisp_Object data;
4974 data = image_spec_value (img->spec, QCdata, NULL);
4975 success_p = xpm_load_image (f, img, SDATA (data),
4976 SDATA (data) + SBYTES (data));
4979 return success_p;
4982 #endif /* MAC_OS */
4986 /***********************************************************************
4987 Color table
4988 ***********************************************************************/
4990 #ifdef COLOR_TABLE_SUPPORT
4992 /* An entry in the color table mapping an RGB color to a pixel color. */
4994 struct ct_color
4996 int r, g, b;
4997 unsigned long pixel;
4999 /* Next in color table collision list. */
5000 struct ct_color *next;
5003 /* The bucket vector size to use. Must be prime. */
5005 #define CT_SIZE 101
5007 /* Value is a hash of the RGB color given by R, G, and B. */
5009 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
5011 /* The color hash table. */
5013 struct ct_color **ct_table;
5015 /* Number of entries in the color table. */
5017 int ct_colors_allocated;
5019 /* Initialize the color table. */
5021 static void
5022 init_color_table ()
5024 int size = CT_SIZE * sizeof (*ct_table);
5025 ct_table = (struct ct_color **) xmalloc (size);
5026 bzero (ct_table, size);
5027 ct_colors_allocated = 0;
5031 /* Free memory associated with the color table. */
5033 static void
5034 free_color_table ()
5036 int i;
5037 struct ct_color *p, *next;
5039 for (i = 0; i < CT_SIZE; ++i)
5040 for (p = ct_table[i]; p; p = next)
5042 next = p->next;
5043 xfree (p);
5046 xfree (ct_table);
5047 ct_table = NULL;
5051 /* Value is a pixel color for RGB color R, G, B on frame F. If an
5052 entry for that color already is in the color table, return the
5053 pixel color of that entry. Otherwise, allocate a new color for R,
5054 G, B, and make an entry in the color table. */
5056 static unsigned long
5057 lookup_rgb_color (f, r, g, b)
5058 struct frame *f;
5059 int r, g, b;
5061 unsigned hash = CT_HASH_RGB (r, g, b);
5062 int i = hash % CT_SIZE;
5063 struct ct_color *p;
5064 Display_Info *dpyinfo;
5066 /* Handle TrueColor visuals specially, which improves performance by
5067 two orders of magnitude. Freeing colors on TrueColor visuals is
5068 a nop, and pixel colors specify RGB values directly. See also
5069 the Xlib spec, chapter 3.1. */
5070 dpyinfo = FRAME_X_DISPLAY_INFO (f);
5071 if (dpyinfo->red_bits > 0)
5073 unsigned long pr, pg, pb;
5075 /* Apply gamma-correction like normal color allocation does. */
5076 if (f->gamma)
5078 XColor color;
5079 color.red = r, color.green = g, color.blue = b;
5080 gamma_correct (f, &color);
5081 r = color.red, g = color.green, b = color.blue;
5084 /* Scale down RGB values to the visual's bits per RGB, and shift
5085 them to the right position in the pixel color. Note that the
5086 original RGB values are 16-bit values, as usual in X. */
5087 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
5088 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
5089 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
5091 /* Assemble the pixel color. */
5092 return pr | pg | pb;
5095 for (p = ct_table[i]; p; p = p->next)
5096 if (p->r == r && p->g == g && p->b == b)
5097 break;
5099 if (p == NULL)
5102 #ifdef HAVE_X_WINDOWS
5103 XColor color;
5104 Colormap cmap;
5105 int rc;
5107 color.red = r;
5108 color.green = g;
5109 color.blue = b;
5111 cmap = FRAME_X_COLORMAP (f);
5112 rc = x_alloc_nearest_color (f, cmap, &color);
5113 if (rc)
5115 ++ct_colors_allocated;
5116 p = (struct ct_color *) xmalloc (sizeof *p);
5117 p->r = r;
5118 p->g = g;
5119 p->b = b;
5120 p->pixel = color.pixel;
5121 p->next = ct_table[i];
5122 ct_table[i] = p;
5124 else
5125 return FRAME_FOREGROUND_PIXEL (f);
5127 #else
5128 COLORREF color;
5129 #ifdef HAVE_NTGUI
5130 color = PALETTERGB (r, g, b);
5131 #else
5132 color = RGB_TO_ULONG (r, g, b);
5133 #endif /* HAVE_NTGUI */
5134 ++ct_colors_allocated;
5135 p = (struct ct_color *) xmalloc (sizeof *p);
5136 p->r = r;
5137 p->g = g;
5138 p->b = b;
5139 p->pixel = color;
5140 p->next = ct_table[i];
5141 ct_table[i] = p;
5142 #endif /* HAVE_X_WINDOWS */
5146 return p->pixel;
5150 /* Look up pixel color PIXEL which is used on frame F in the color
5151 table. If not already present, allocate it. Value is PIXEL. */
5153 static unsigned long
5154 lookup_pixel_color (f, pixel)
5155 struct frame *f;
5156 unsigned long pixel;
5158 int i = pixel % CT_SIZE;
5159 struct ct_color *p;
5161 for (p = ct_table[i]; p; p = p->next)
5162 if (p->pixel == pixel)
5163 break;
5165 if (p == NULL)
5167 XColor color;
5168 Colormap cmap;
5169 int rc;
5171 #ifdef HAVE_X_WINDOWS
5172 cmap = FRAME_X_COLORMAP (f);
5173 color.pixel = pixel;
5174 x_query_color (f, &color);
5175 rc = x_alloc_nearest_color (f, cmap, &color);
5176 #else
5177 BLOCK_INPUT;
5178 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
5179 color.pixel = pixel;
5180 XQueryColor (NULL, cmap, &color);
5181 rc = x_alloc_nearest_color (f, cmap, &color);
5182 UNBLOCK_INPUT;
5183 #endif /* HAVE_X_WINDOWS */
5185 if (rc)
5187 ++ct_colors_allocated;
5189 p = (struct ct_color *) xmalloc (sizeof *p);
5190 p->r = color.red;
5191 p->g = color.green;
5192 p->b = color.blue;
5193 p->pixel = pixel;
5194 p->next = ct_table[i];
5195 ct_table[i] = p;
5197 else
5198 return FRAME_FOREGROUND_PIXEL (f);
5200 return p->pixel;
5204 /* Value is a vector of all pixel colors contained in the color table,
5205 allocated via xmalloc. Set *N to the number of colors. */
5207 static unsigned long *
5208 colors_in_color_table (n)
5209 int *n;
5211 int i, j;
5212 struct ct_color *p;
5213 unsigned long *colors;
5215 if (ct_colors_allocated == 0)
5217 *n = 0;
5218 colors = NULL;
5220 else
5222 colors = (unsigned long *) xmalloc (ct_colors_allocated
5223 * sizeof *colors);
5224 *n = ct_colors_allocated;
5226 for (i = j = 0; i < CT_SIZE; ++i)
5227 for (p = ct_table[i]; p; p = p->next)
5228 colors[j++] = p->pixel;
5231 return colors;
5234 #else /* COLOR_TABLE_SUPPORT */
5236 static unsigned long
5237 lookup_rgb_color (f, r, g, b)
5238 struct frame *f;
5239 int r, g, b;
5241 unsigned long pixel;
5243 #ifdef MAC_OS
5244 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
5245 gamma_correct (f, &pixel);
5246 #endif /* MAC_OS */
5248 #ifdef HAVE_NTGUI
5249 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
5250 #endif /* HAVE_NTGUI */
5252 return pixel;
5255 static void
5256 init_color_table ()
5259 #endif /* COLOR_TABLE_SUPPORT */
5262 /***********************************************************************
5263 Algorithms
5264 ***********************************************************************/
5266 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
5267 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
5268 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
5270 #ifdef HAVE_NTGUI
5271 static void XPutPixel (XImagePtr , int, int, COLORREF);
5272 #endif /* HAVE_NTGUI */
5274 /* Non-zero means draw a cross on images having `:conversion
5275 disabled'. */
5277 int cross_disabled_images;
5279 /* Edge detection matrices for different edge-detection
5280 strategies. */
5282 static int emboss_matrix[9] = {
5283 /* x - 1 x x + 1 */
5284 2, -1, 0, /* y - 1 */
5285 -1, 0, 1, /* y */
5286 0, 1, -2 /* y + 1 */
5289 static int laplace_matrix[9] = {
5290 /* x - 1 x x + 1 */
5291 1, 0, 0, /* y - 1 */
5292 0, 0, 0, /* y */
5293 0, 0, -1 /* y + 1 */
5296 /* Value is the intensity of the color whose red/green/blue values
5297 are R, G, and B. */
5299 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
5302 /* On frame F, return an array of XColor structures describing image
5303 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
5304 non-zero means also fill the red/green/blue members of the XColor
5305 structures. Value is a pointer to the array of XColors structures,
5306 allocated with xmalloc; it must be freed by the caller. */
5308 static XColor *
5309 x_to_xcolors (f, img, rgb_p)
5310 struct frame *f;
5311 struct image *img;
5312 int rgb_p;
5314 int x, y;
5315 XColor *colors, *p;
5316 XImagePtr_or_DC ximg;
5317 #ifdef HAVE_NTGUI
5318 HDC hdc;
5319 HGDIOBJ prev;
5320 #endif /* HAVE_NTGUI */
5322 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
5324 #ifndef HAVE_NTGUI
5325 /* Get the X image IMG->pixmap. */
5326 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
5327 0, 0, img->width, img->height, ~0, ZPixmap);
5328 #else
5329 /* Load the image into a memory device context. */
5330 hdc = get_frame_dc (f);
5331 ximg = CreateCompatibleDC (hdc);
5332 release_frame_dc (f, hdc);
5333 prev = SelectObject (ximg, img->pixmap);
5334 #endif /* HAVE_NTGUI */
5336 /* Fill the `pixel' members of the XColor array. I wished there
5337 were an easy and portable way to circumvent XGetPixel. */
5338 p = colors;
5339 for (y = 0; y < img->height; ++y)
5341 XColor *row = p;
5343 #ifdef HAVE_X_WINDOWS
5344 for (x = 0; x < img->width; ++x, ++p)
5345 p->pixel = XGetPixel (ximg, x, y);
5346 if (rgb_p)
5347 x_query_colors (f, row, img->width);
5349 #else
5351 for (x = 0; x < img->width; ++x, ++p)
5353 /* W32_TODO: palette support needed here? */
5354 p->pixel = GET_PIXEL (ximg, x, y);
5355 if (rgb_p)
5357 #ifdef MAC_OS
5358 p->red = RED16_FROM_ULONG (p->pixel);
5359 p->green = GREEN16_FROM_ULONG (p->pixel);
5360 p->blue = BLUE16_FROM_ULONG (p->pixel);
5361 #endif /* MAC_OS */
5362 #ifdef HAVE_NTGUI
5363 p->red = 256 * GetRValue (p->pixel);
5364 p->green = 256 * GetGValue (p->pixel);
5365 p->blue = 256 * GetBValue (p->pixel);
5366 #endif /* HAVE_NTGUI */
5369 #endif /* HAVE_X_WINDOWS */
5372 Destroy_Image (ximg, prev);
5374 return colors;
5377 #ifdef HAVE_NTGUI
5379 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
5380 created with CreateDIBSection, with the pointer to the bit values
5381 stored in ximg->data. */
5383 static void
5384 XPutPixel (ximg, x, y, color)
5385 XImagePtr ximg;
5386 int x, y;
5387 COLORREF color;
5389 int width = ximg->info.bmiHeader.biWidth;
5390 int height = ximg->info.bmiHeader.biHeight;
5391 unsigned char * pixel;
5393 /* True color images. */
5394 if (ximg->info.bmiHeader.biBitCount == 24)
5396 int rowbytes = width * 3;
5397 /* Ensure scanlines are aligned on 4 byte boundaries. */
5398 if (rowbytes % 4)
5399 rowbytes += 4 - (rowbytes % 4);
5401 pixel = ximg->data + y * rowbytes + x * 3;
5402 /* Windows bitmaps are in BGR order. */
5403 *pixel = GetBValue (color);
5404 *(pixel + 1) = GetGValue (color);
5405 *(pixel + 2) = GetRValue (color);
5407 /* Monochrome images. */
5408 else if (ximg->info.bmiHeader.biBitCount == 1)
5410 int rowbytes = width / 8;
5411 /* Ensure scanlines are aligned on 4 byte boundaries. */
5412 if (rowbytes % 4)
5413 rowbytes += 4 - (rowbytes % 4);
5414 pixel = ximg->data + y * rowbytes + x / 8;
5415 /* Filter out palette info. */
5416 if (color & 0x00ffffff)
5417 *pixel = *pixel | (1 << x % 8);
5418 else
5419 *pixel = *pixel & ~(1 << x % 8);
5421 else
5422 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
5425 #endif /* HAVE_NTGUI */
5427 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
5428 RGB members are set. F is the frame on which this all happens.
5429 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
5431 static void
5432 x_from_xcolors (f, img, colors)
5433 struct frame *f;
5434 struct image *img;
5435 XColor *colors;
5437 int x, y;
5438 XImagePtr oimg;
5439 Pixmap pixmap;
5440 XColor *p;
5442 init_color_table ();
5444 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
5445 &oimg, &pixmap);
5446 p = colors;
5447 for (y = 0; y < img->height; ++y)
5448 for (x = 0; x < img->width; ++x, ++p)
5450 unsigned long pixel;
5451 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
5452 XPutPixel (oimg, x, y, pixel);
5455 xfree (colors);
5456 x_clear_image_1 (f, img, 1, 0, 1);
5458 x_put_x_image (f, oimg, pixmap, img->width, img->height);
5459 x_destroy_x_image (oimg);
5460 img->pixmap = pixmap;
5461 #ifdef COLOR_TABLE_SUPPORT
5462 img->colors = colors_in_color_table (&img->ncolors);
5463 free_color_table ();
5464 #endif /* COLOR_TABLE_SUPPORT */
5468 /* On frame F, perform edge-detection on image IMG.
5470 MATRIX is a nine-element array specifying the transformation
5471 matrix. See emboss_matrix for an example.
5473 COLOR_ADJUST is a color adjustment added to each pixel of the
5474 outgoing image. */
5476 static void
5477 x_detect_edges (f, img, matrix, color_adjust)
5478 struct frame *f;
5479 struct image *img;
5480 int matrix[9], color_adjust;
5482 XColor *colors = x_to_xcolors (f, img, 1);
5483 XColor *new, *p;
5484 int x, y, i, sum;
5486 for (i = sum = 0; i < 9; ++i)
5487 sum += abs (matrix[i]);
5489 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
5491 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
5493 for (y = 0; y < img->height; ++y)
5495 p = COLOR (new, 0, y);
5496 p->red = p->green = p->blue = 0xffff/2;
5497 p = COLOR (new, img->width - 1, y);
5498 p->red = p->green = p->blue = 0xffff/2;
5501 for (x = 1; x < img->width - 1; ++x)
5503 p = COLOR (new, x, 0);
5504 p->red = p->green = p->blue = 0xffff/2;
5505 p = COLOR (new, x, img->height - 1);
5506 p->red = p->green = p->blue = 0xffff/2;
5509 for (y = 1; y < img->height - 1; ++y)
5511 p = COLOR (new, 1, y);
5513 for (x = 1; x < img->width - 1; ++x, ++p)
5515 int r, g, b, y1, x1;
5517 r = g = b = i = 0;
5518 for (y1 = y - 1; y1 < y + 2; ++y1)
5519 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
5520 if (matrix[i])
5522 XColor *t = COLOR (colors, x1, y1);
5523 r += matrix[i] * t->red;
5524 g += matrix[i] * t->green;
5525 b += matrix[i] * t->blue;
5528 r = (r / sum + color_adjust) & 0xffff;
5529 g = (g / sum + color_adjust) & 0xffff;
5530 b = (b / sum + color_adjust) & 0xffff;
5531 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
5535 xfree (colors);
5536 x_from_xcolors (f, img, new);
5538 #undef COLOR
5542 /* Perform the pre-defined `emboss' edge-detection on image IMG
5543 on frame F. */
5545 static void
5546 x_emboss (f, img)
5547 struct frame *f;
5548 struct image *img;
5550 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
5554 /* Transform image IMG which is used on frame F with a Laplace
5555 edge-detection algorithm. The result is an image that can be used
5556 to draw disabled buttons, for example. */
5558 static void
5559 x_laplace (f, img)
5560 struct frame *f;
5561 struct image *img;
5563 x_detect_edges (f, img, laplace_matrix, 45000);
5567 /* Perform edge-detection on image IMG on frame F, with specified
5568 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
5570 MATRIX must be either
5572 - a list of at least 9 numbers in row-major form
5573 - a vector of at least 9 numbers
5575 COLOR_ADJUST nil means use a default; otherwise it must be a
5576 number. */
5578 static void
5579 x_edge_detection (f, img, matrix, color_adjust)
5580 struct frame *f;
5581 struct image *img;
5582 Lisp_Object matrix, color_adjust;
5584 int i = 0;
5585 int trans[9];
5587 if (CONSP (matrix))
5589 for (i = 0;
5590 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
5591 ++i, matrix = XCDR (matrix))
5592 trans[i] = XFLOATINT (XCAR (matrix));
5594 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
5596 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
5597 trans[i] = XFLOATINT (AREF (matrix, i));
5600 if (NILP (color_adjust))
5601 color_adjust = make_number (0xffff / 2);
5603 if (i == 9 && NUMBERP (color_adjust))
5604 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
5608 /* Transform image IMG on frame F so that it looks disabled. */
5610 static void
5611 x_disable_image (f, img)
5612 struct frame *f;
5613 struct image *img;
5615 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
5616 #ifdef HAVE_NTGUI
5617 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
5618 #else
5619 int n_planes = dpyinfo->n_planes;
5620 #endif /* HAVE_NTGUI */
5622 if (n_planes >= 2)
5624 /* Color (or grayscale). Convert to gray, and equalize. Just
5625 drawing such images with a stipple can look very odd, so
5626 we're using this method instead. */
5627 XColor *colors = x_to_xcolors (f, img, 1);
5628 XColor *p, *end;
5629 const int h = 15000;
5630 const int l = 30000;
5632 for (p = colors, end = colors + img->width * img->height;
5633 p < end;
5634 ++p)
5636 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
5637 int i2 = (0xffff - h - l) * i / 0xffff + l;
5638 p->red = p->green = p->blue = i2;
5641 x_from_xcolors (f, img, colors);
5644 /* Draw a cross over the disabled image, if we must or if we
5645 should. */
5646 if (n_planes < 2 || cross_disabled_images)
5648 #ifndef HAVE_NTGUI
5649 Display *dpy = FRAME_X_DISPLAY (f);
5650 GC gc;
5652 #ifdef MAC_OS
5653 #define MaskForeground(f) PIX_MASK_DRAW
5654 #else
5655 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
5656 #endif
5658 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
5659 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
5660 XDrawLine (dpy, img->pixmap, gc, 0, 0,
5661 img->width - 1, img->height - 1);
5662 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
5663 img->width - 1, 0);
5664 XFreeGC (dpy, gc);
5666 if (img->mask)
5668 gc = XCreateGC (dpy, img->mask, 0, NULL);
5669 XSetForeground (dpy, gc, MaskForeground (f));
5670 XDrawLine (dpy, img->mask, gc, 0, 0,
5671 img->width - 1, img->height - 1);
5672 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
5673 img->width - 1, 0);
5674 XFreeGC (dpy, gc);
5676 #else
5677 HDC hdc, bmpdc;
5678 HGDIOBJ prev;
5680 hdc = get_frame_dc (f);
5681 bmpdc = CreateCompatibleDC (hdc);
5682 release_frame_dc (f, hdc);
5684 prev = SelectObject (bmpdc, img->pixmap);
5686 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5687 MoveToEx (bmpdc, 0, 0, NULL);
5688 LineTo (bmpdc, img->width - 1, img->height - 1);
5689 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5690 LineTo (bmpdc, img->width - 1, 0);
5692 if (img->mask)
5694 SelectObject (bmpdc, img->mask);
5695 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5696 MoveToEx (bmpdc, 0, 0, NULL);
5697 LineTo (bmpdc, img->width - 1, img->height - 1);
5698 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5699 LineTo (bmpdc, img->width - 1, 0);
5701 SelectObject (bmpdc, prev);
5702 DeleteDC (bmpdc);
5703 #endif /* HAVE_NTGUI */
5708 /* Build a mask for image IMG which is used on frame F. FILE is the
5709 name of an image file, for error messages. HOW determines how to
5710 determine the background color of IMG. If it is a list '(R G B)',
5711 with R, G, and B being integers >= 0, take that as the color of the
5712 background. Otherwise, determine the background color of IMG
5713 heuristically. Value is non-zero if successful. */
5715 static int
5716 x_build_heuristic_mask (f, img, how)
5717 struct frame *f;
5718 struct image *img;
5719 Lisp_Object how;
5721 XImagePtr_or_DC ximg;
5722 #ifndef HAVE_NTGUI
5723 XImagePtr mask_img;
5724 #else
5725 HDC frame_dc;
5726 HGDIOBJ prev;
5727 char *mask_img;
5728 int row_width;
5729 #endif /* HAVE_NTGUI */
5730 int x, y, rc, use_img_background;
5731 unsigned long bg = 0;
5733 if (img->mask)
5735 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
5736 img->mask = NO_PIXMAP;
5737 img->background_transparent_valid = 0;
5740 #ifndef HAVE_NTGUI
5741 /* Create an image and pixmap serving as mask. */
5742 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
5743 &mask_img, &img->mask);
5744 if (!rc)
5745 return 0;
5747 /* Get the X image of IMG->pixmap. */
5748 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
5749 img->width, img->height,
5750 ~0, ZPixmap);
5751 #else
5752 /* Create the bit array serving as mask. */
5753 row_width = (img->width + 7) / 8;
5754 mask_img = xmalloc (row_width * img->height);
5755 bzero (mask_img, row_width * img->height);
5757 /* Create a memory device context for IMG->pixmap. */
5758 frame_dc = get_frame_dc (f);
5759 ximg = CreateCompatibleDC (frame_dc);
5760 release_frame_dc (f, frame_dc);
5761 prev = SelectObject (ximg, img->pixmap);
5762 #endif /* HAVE_NTGUI */
5764 /* Determine the background color of ximg. If HOW is `(R G B)'
5765 take that as color. Otherwise, use the image's background color. */
5766 use_img_background = 1;
5768 if (CONSP (how))
5770 int rgb[3], i;
5772 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5774 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5775 how = XCDR (how);
5778 if (i == 3 && NILP (how))
5780 char color_name[30];
5781 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
5782 bg = (
5783 #ifdef HAVE_NTGUI
5784 0x00ffffff & /* Filter out palette info. */
5785 #endif /* HAVE_NTGUI */
5786 x_alloc_image_color (f, img, build_string (color_name), 0));
5787 use_img_background = 0;
5791 if (use_img_background)
5792 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5794 /* Set all bits in mask_img to 1 whose color in ximg is different
5795 from the background color bg. */
5796 #ifndef HAVE_NTGUI
5797 for (y = 0; y < img->height; ++y)
5798 for (x = 0; x < img->width; ++x)
5799 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5800 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5802 /* Fill in the background_transparent field while we have the mask handy. */
5803 image_background_transparent (img, f, mask_img);
5805 /* Put mask_img into img->mask. */
5806 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5807 x_destroy_x_image (mask_img);
5809 #else
5810 for (y = 0; y < img->height; ++y)
5811 for (x = 0; x < img->width; ++x)
5813 COLORREF p = GetPixel (ximg, x, y);
5814 if (p != bg)
5815 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5818 /* Create the mask image. */
5819 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5820 mask_img);
5821 /* Fill in the background_transparent field while we have the mask handy. */
5822 SelectObject (ximg, img->mask);
5823 image_background_transparent (img, f, ximg);
5825 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5826 xfree (mask_img);
5827 #endif /* HAVE_NTGUI */
5829 Destroy_Image (ximg, prev);
5831 return 1;
5835 /***********************************************************************
5836 PBM (mono, gray, color)
5837 ***********************************************************************/
5839 static int pbm_image_p P_ ((Lisp_Object object));
5840 static int pbm_load P_ ((struct frame *f, struct image *img));
5841 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
5843 /* The symbol `pbm' identifying images of this type. */
5845 Lisp_Object Qpbm;
5847 /* Indices of image specification fields in gs_format, below. */
5849 enum pbm_keyword_index
5851 PBM_TYPE,
5852 PBM_FILE,
5853 PBM_DATA,
5854 PBM_ASCENT,
5855 PBM_MARGIN,
5856 PBM_RELIEF,
5857 PBM_ALGORITHM,
5858 PBM_HEURISTIC_MASK,
5859 PBM_MASK,
5860 PBM_FOREGROUND,
5861 PBM_BACKGROUND,
5862 PBM_LAST
5865 /* Vector of image_keyword structures describing the format
5866 of valid user-defined image specifications. */
5868 static struct image_keyword pbm_format[PBM_LAST] =
5870 {":type", IMAGE_SYMBOL_VALUE, 1},
5871 {":file", IMAGE_STRING_VALUE, 0},
5872 {":data", IMAGE_STRING_VALUE, 0},
5873 {":ascent", IMAGE_ASCENT_VALUE, 0},
5874 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5875 {":relief", IMAGE_INTEGER_VALUE, 0},
5876 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5877 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5878 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5879 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5880 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5883 /* Structure describing the image type `pbm'. */
5885 static struct image_type pbm_type =
5887 &Qpbm,
5888 pbm_image_p,
5889 pbm_load,
5890 x_clear_image,
5891 NULL
5895 /* Return non-zero if OBJECT is a valid PBM image specification. */
5897 static int
5898 pbm_image_p (object)
5899 Lisp_Object object;
5901 struct image_keyword fmt[PBM_LAST];
5903 bcopy (pbm_format, fmt, sizeof fmt);
5905 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5906 return 0;
5908 /* Must specify either :data or :file. */
5909 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5913 /* Scan a decimal number from *S and return it. Advance *S while
5914 reading the number. END is the end of the string. Value is -1 at
5915 end of input. */
5917 static int
5918 pbm_scan_number (s, end)
5919 unsigned char **s, *end;
5921 int c = 0, val = -1;
5923 while (*s < end)
5925 /* Skip white-space. */
5926 while (*s < end && (c = *(*s)++, isspace (c)))
5929 if (c == '#')
5931 /* Skip comment to end of line. */
5932 while (*s < end && (c = *(*s)++, c != '\n'))
5935 else if (isdigit (c))
5937 /* Read decimal number. */
5938 val = c - '0';
5939 while (*s < end && (c = *(*s)++, isdigit (c)))
5940 val = 10 * val + c - '0';
5941 break;
5943 else
5944 break;
5947 return val;
5951 #ifdef HAVE_NTGUI
5952 #if 0 /* Unused. ++kfs */
5954 /* Read FILE into memory. Value is a pointer to a buffer allocated
5955 with xmalloc holding FILE's contents. Value is null if an error
5956 occurred. *SIZE is set to the size of the file. */
5958 static char *
5959 pbm_read_file (file, size)
5960 Lisp_Object file;
5961 int *size;
5963 FILE *fp = NULL;
5964 char *buf = NULL;
5965 struct stat st;
5967 if (stat (SDATA (file), &st) == 0
5968 && (fp = fopen (SDATA (file), "rb")) != NULL
5969 && (buf = (char *) xmalloc (st.st_size),
5970 fread (buf, 1, st.st_size, fp) == st.st_size))
5972 *size = st.st_size;
5973 fclose (fp);
5975 else
5977 if (fp)
5978 fclose (fp);
5979 if (buf)
5981 xfree (buf);
5982 buf = NULL;
5986 return buf;
5988 #endif
5989 #endif /* HAVE_NTGUI */
5991 /* Load PBM image IMG for use on frame F. */
5993 static int
5994 pbm_load (f, img)
5995 struct frame *f;
5996 struct image *img;
5998 int raw_p, x, y;
5999 int width, height, max_color_idx = 0;
6000 XImagePtr ximg;
6001 Lisp_Object file, specified_file;
6002 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
6003 struct gcpro gcpro1;
6004 unsigned char *contents = NULL;
6005 unsigned char *end, *p;
6006 int size;
6008 specified_file = image_spec_value (img->spec, QCfile, NULL);
6009 file = Qnil;
6010 GCPRO1 (file);
6012 if (STRINGP (specified_file))
6014 file = x_find_image_file (specified_file);
6015 if (!STRINGP (file))
6017 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6018 UNGCPRO;
6019 return 0;
6022 contents = slurp_file (SDATA (file), &size);
6023 if (contents == NULL)
6025 image_error ("Error reading `%s'", file, Qnil);
6026 UNGCPRO;
6027 return 0;
6030 p = contents;
6031 end = contents + size;
6033 else
6035 Lisp_Object data;
6036 data = image_spec_value (img->spec, QCdata, NULL);
6037 p = SDATA (data);
6038 end = p + SBYTES (data);
6041 /* Check magic number. */
6042 if (end - p < 2 || *p++ != 'P')
6044 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
6045 error:
6046 xfree (contents);
6047 UNGCPRO;
6048 return 0;
6051 switch (*p++)
6053 case '1':
6054 raw_p = 0, type = PBM_MONO;
6055 break;
6057 case '2':
6058 raw_p = 0, type = PBM_GRAY;
6059 break;
6061 case '3':
6062 raw_p = 0, type = PBM_COLOR;
6063 break;
6065 case '4':
6066 raw_p = 1, type = PBM_MONO;
6067 break;
6069 case '5':
6070 raw_p = 1, type = PBM_GRAY;
6071 break;
6073 case '6':
6074 raw_p = 1, type = PBM_COLOR;
6075 break;
6077 default:
6078 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
6079 goto error;
6082 /* Read width, height, maximum color-component. Characters
6083 starting with `#' up to the end of a line are ignored. */
6084 width = pbm_scan_number (&p, end);
6085 height = pbm_scan_number (&p, end);
6087 if (type != PBM_MONO)
6089 max_color_idx = pbm_scan_number (&p, end);
6090 if (max_color_idx > 65535 || max_color_idx < 0)
6092 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
6093 goto error;
6097 if (!check_image_size (f, width, height))
6099 image_error ("Invalid image size", Qnil, Qnil);
6100 goto error;
6103 if (!x_create_x_image_and_pixmap (f, width, height, 0,
6104 &ximg, &img->pixmap))
6105 goto error;
6107 /* Initialize the color hash table. */
6108 init_color_table ();
6110 if (type == PBM_MONO)
6112 int c = 0, g;
6113 struct image_keyword fmt[PBM_LAST];
6114 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
6115 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
6117 /* Parse the image specification. */
6118 bcopy (pbm_format, fmt, sizeof fmt);
6119 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
6121 /* Get foreground and background colors, maybe allocate colors. */
6122 if (fmt[PBM_FOREGROUND].count
6123 && STRINGP (fmt[PBM_FOREGROUND].value))
6124 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
6125 if (fmt[PBM_BACKGROUND].count
6126 && STRINGP (fmt[PBM_BACKGROUND].value))
6128 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
6129 img->background = bg;
6130 img->background_valid = 1;
6133 for (y = 0; y < height; ++y)
6134 for (x = 0; x < width; ++x)
6136 if (raw_p)
6138 if ((x & 7) == 0)
6140 if (p >= end)
6142 x_destroy_x_image (ximg);
6143 x_clear_image (f, img);
6144 image_error ("Invalid image size in image `%s'",
6145 img->spec, Qnil);
6146 goto error;
6148 c = *p++;
6150 g = c & 0x80;
6151 c <<= 1;
6153 else
6154 g = pbm_scan_number (&p, end);
6156 XPutPixel (ximg, x, y, g ? fg : bg);
6159 else
6161 int expected_size = height * width;
6162 if (max_color_idx > 255)
6163 expected_size *= 2;
6164 if (type == PBM_COLOR)
6165 expected_size *= 3;
6167 if (raw_p && p + expected_size > end)
6169 x_destroy_x_image (ximg);
6170 x_clear_image (f, img);
6171 image_error ("Invalid image size in image `%s'",
6172 img->spec, Qnil);
6173 goto error;
6176 for (y = 0; y < height; ++y)
6177 for (x = 0; x < width; ++x)
6179 int r, g, b;
6181 if (type == PBM_GRAY && raw_p)
6183 r = g = b = *p++;
6184 if (max_color_idx > 255)
6185 r = g = b = r * 256 + *p++;
6187 else if (type == PBM_GRAY)
6188 r = g = b = pbm_scan_number (&p, end);
6189 else if (raw_p)
6191 r = *p++;
6192 if (max_color_idx > 255)
6193 r = r * 256 + *p++;
6194 g = *p++;
6195 if (max_color_idx > 255)
6196 g = g * 256 + *p++;
6197 b = *p++;
6198 if (max_color_idx > 255)
6199 b = b * 256 + *p++;
6201 else
6203 r = pbm_scan_number (&p, end);
6204 g = pbm_scan_number (&p, end);
6205 b = pbm_scan_number (&p, end);
6208 if (r < 0 || g < 0 || b < 0)
6210 x_destroy_x_image (ximg);
6211 image_error ("Invalid pixel value in image `%s'",
6212 img->spec, Qnil);
6213 goto error;
6216 /* RGB values are now in the range 0..max_color_idx.
6217 Scale this to the range 0..0xffff supported by X. */
6218 r = (double) r * 65535 / max_color_idx;
6219 g = (double) g * 65535 / max_color_idx;
6220 b = (double) b * 65535 / max_color_idx;
6221 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6225 #ifdef COLOR_TABLE_SUPPORT
6226 /* Store in IMG->colors the colors allocated for the image, and
6227 free the color table. */
6228 img->colors = colors_in_color_table (&img->ncolors);
6229 free_color_table ();
6230 #endif /* COLOR_TABLE_SUPPORT */
6232 img->width = width;
6233 img->height = height;
6235 /* Maybe fill in the background field while we have ximg handy. */
6237 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6238 /* Casting avoids a GCC warning. */
6239 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6241 /* Put the image into a pixmap. */
6242 x_put_x_image (f, ximg, img->pixmap, width, height);
6243 x_destroy_x_image (ximg);
6245 /* X and W32 versions did it here, MAC version above. ++kfs
6246 img->width = width;
6247 img->height = height; */
6249 UNGCPRO;
6250 xfree (contents);
6251 return 1;
6255 /***********************************************************************
6257 ***********************************************************************/
6259 #if defined (HAVE_PNG) || defined (MAC_OS)
6261 /* Function prototypes. */
6263 static int png_image_p P_ ((Lisp_Object object));
6264 static int png_load P_ ((struct frame *f, struct image *img));
6266 /* The symbol `png' identifying images of this type. */
6268 Lisp_Object Qpng;
6270 /* Indices of image specification fields in png_format, below. */
6272 enum png_keyword_index
6274 PNG_TYPE,
6275 PNG_DATA,
6276 PNG_FILE,
6277 PNG_ASCENT,
6278 PNG_MARGIN,
6279 PNG_RELIEF,
6280 PNG_ALGORITHM,
6281 PNG_HEURISTIC_MASK,
6282 PNG_MASK,
6283 PNG_BACKGROUND,
6284 PNG_LAST
6287 /* Vector of image_keyword structures describing the format
6288 of valid user-defined image specifications. */
6290 static struct image_keyword png_format[PNG_LAST] =
6292 {":type", IMAGE_SYMBOL_VALUE, 1},
6293 {":data", IMAGE_STRING_VALUE, 0},
6294 {":file", IMAGE_STRING_VALUE, 0},
6295 {":ascent", IMAGE_ASCENT_VALUE, 0},
6296 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6297 {":relief", IMAGE_INTEGER_VALUE, 0},
6298 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6299 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6300 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6301 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6304 /* Structure describing the image type `png'. */
6306 static struct image_type png_type =
6308 &Qpng,
6309 png_image_p,
6310 png_load,
6311 x_clear_image,
6312 NULL
6315 /* Return non-zero if OBJECT is a valid PNG image specification. */
6317 static int
6318 png_image_p (object)
6319 Lisp_Object object;
6321 struct image_keyword fmt[PNG_LAST];
6322 bcopy (png_format, fmt, sizeof fmt);
6324 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
6325 return 0;
6327 /* Must specify either the :data or :file keyword. */
6328 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
6331 #endif /* HAVE_PNG || MAC_OS */
6334 #ifdef HAVE_PNG
6336 #if defined HAVE_LIBPNG_PNG_H
6337 # include <libpng/png.h>
6338 #else
6339 # include <png.h>
6340 #endif
6342 #ifdef HAVE_NTGUI
6343 /* PNG library details. */
6345 DEF_IMGLIB_FN (png_get_io_ptr);
6346 DEF_IMGLIB_FN (png_check_sig);
6347 DEF_IMGLIB_FN (png_create_read_struct);
6348 DEF_IMGLIB_FN (png_create_info_struct);
6349 DEF_IMGLIB_FN (png_destroy_read_struct);
6350 DEF_IMGLIB_FN (png_set_read_fn);
6351 DEF_IMGLIB_FN (png_set_sig_bytes);
6352 DEF_IMGLIB_FN (png_read_info);
6353 DEF_IMGLIB_FN (png_get_IHDR);
6354 DEF_IMGLIB_FN (png_get_valid);
6355 DEF_IMGLIB_FN (png_set_strip_16);
6356 DEF_IMGLIB_FN (png_set_expand);
6357 DEF_IMGLIB_FN (png_set_gray_to_rgb);
6358 DEF_IMGLIB_FN (png_set_background);
6359 DEF_IMGLIB_FN (png_get_bKGD);
6360 DEF_IMGLIB_FN (png_read_update_info);
6361 DEF_IMGLIB_FN (png_get_channels);
6362 DEF_IMGLIB_FN (png_get_rowbytes);
6363 DEF_IMGLIB_FN (png_read_image);
6364 DEF_IMGLIB_FN (png_read_end);
6365 DEF_IMGLIB_FN (png_error);
6367 static int
6368 init_png_functions (Lisp_Object libraries)
6370 HMODULE library;
6372 /* Try loading libpng under probable names. */
6373 if (!(library = w32_delayed_load (libraries, Qpng)))
6374 return 0;
6376 LOAD_IMGLIB_FN (library, png_get_io_ptr);
6377 LOAD_IMGLIB_FN (library, png_check_sig);
6378 LOAD_IMGLIB_FN (library, png_create_read_struct);
6379 LOAD_IMGLIB_FN (library, png_create_info_struct);
6380 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
6381 LOAD_IMGLIB_FN (library, png_set_read_fn);
6382 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
6383 LOAD_IMGLIB_FN (library, png_read_info);
6384 LOAD_IMGLIB_FN (library, png_get_IHDR);
6385 LOAD_IMGLIB_FN (library, png_get_valid);
6386 LOAD_IMGLIB_FN (library, png_set_strip_16);
6387 LOAD_IMGLIB_FN (library, png_set_expand);
6388 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
6389 LOAD_IMGLIB_FN (library, png_set_background);
6390 LOAD_IMGLIB_FN (library, png_get_bKGD);
6391 LOAD_IMGLIB_FN (library, png_read_update_info);
6392 LOAD_IMGLIB_FN (library, png_get_channels);
6393 LOAD_IMGLIB_FN (library, png_get_rowbytes);
6394 LOAD_IMGLIB_FN (library, png_read_image);
6395 LOAD_IMGLIB_FN (library, png_read_end);
6396 LOAD_IMGLIB_FN (library, png_error);
6397 return 1;
6399 #else
6401 #define fn_png_get_io_ptr png_get_io_ptr
6402 #define fn_png_check_sig png_check_sig
6403 #define fn_png_create_read_struct png_create_read_struct
6404 #define fn_png_create_info_struct png_create_info_struct
6405 #define fn_png_destroy_read_struct png_destroy_read_struct
6406 #define fn_png_set_read_fn png_set_read_fn
6407 #define fn_png_set_sig_bytes png_set_sig_bytes
6408 #define fn_png_read_info png_read_info
6409 #define fn_png_get_IHDR png_get_IHDR
6410 #define fn_png_get_valid png_get_valid
6411 #define fn_png_set_strip_16 png_set_strip_16
6412 #define fn_png_set_expand png_set_expand
6413 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
6414 #define fn_png_set_background png_set_background
6415 #define fn_png_get_bKGD png_get_bKGD
6416 #define fn_png_read_update_info png_read_update_info
6417 #define fn_png_get_channels png_get_channels
6418 #define fn_png_get_rowbytes png_get_rowbytes
6419 #define fn_png_read_image png_read_image
6420 #define fn_png_read_end png_read_end
6421 #define fn_png_error png_error
6423 #endif /* HAVE_NTGUI */
6425 /* Error and warning handlers installed when the PNG library
6426 is initialized. */
6428 static void
6429 my_png_error (png_ptr, msg)
6430 png_struct *png_ptr;
6431 char *msg;
6433 xassert (png_ptr != NULL);
6434 image_error ("PNG error: %s", build_string (msg), Qnil);
6435 longjmp (png_ptr->jmpbuf, 1);
6439 static void
6440 my_png_warning (png_ptr, msg)
6441 png_struct *png_ptr;
6442 char *msg;
6444 xassert (png_ptr != NULL);
6445 image_error ("PNG warning: %s", build_string (msg), Qnil);
6448 /* Memory source for PNG decoding. */
6450 struct png_memory_storage
6452 unsigned char *bytes; /* The data */
6453 size_t len; /* How big is it? */
6454 int index; /* Where are we? */
6458 /* Function set as reader function when reading PNG image from memory.
6459 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
6460 bytes from the input to DATA. */
6462 static void
6463 png_read_from_memory (png_ptr, data, length)
6464 png_structp png_ptr;
6465 png_bytep data;
6466 png_size_t length;
6468 struct png_memory_storage *tbr
6469 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
6471 if (length > tbr->len - tbr->index)
6472 fn_png_error (png_ptr, "Read error");
6474 bcopy (tbr->bytes + tbr->index, data, length);
6475 tbr->index = tbr->index + length;
6479 /* Function set as reader function when reading PNG image from a file.
6480 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
6481 bytes from the input to DATA. */
6483 static void
6484 png_read_from_file (png_ptr, data, length)
6485 png_structp png_ptr;
6486 png_bytep data;
6487 png_size_t length;
6489 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
6491 if (fread (data, 1, length, fp) < length)
6492 fn_png_error (png_ptr, "Read error");
6496 /* Load PNG image IMG for use on frame F. Value is non-zero if
6497 successful. */
6499 static int
6500 png_load (f, img)
6501 struct frame *f;
6502 struct image *img;
6504 Lisp_Object file, specified_file;
6505 Lisp_Object specified_data;
6506 int x, y, i;
6507 XImagePtr ximg, mask_img = NULL;
6508 struct gcpro gcpro1;
6509 png_struct *png_ptr = NULL;
6510 png_info *info_ptr = NULL, *end_info = NULL;
6511 FILE *volatile fp = NULL;
6512 png_byte sig[8];
6513 png_byte * volatile pixels = NULL;
6514 png_byte ** volatile rows = NULL;
6515 png_uint_32 width, height;
6516 int bit_depth, color_type, interlace_type;
6517 png_byte channels;
6518 png_uint_32 row_bytes;
6519 int transparent_p;
6520 double screen_gamma;
6521 struct png_memory_storage tbr; /* Data to be read */
6523 /* Find out what file to load. */
6524 specified_file = image_spec_value (img->spec, QCfile, NULL);
6525 specified_data = image_spec_value (img->spec, QCdata, NULL);
6526 file = Qnil;
6527 GCPRO1 (file);
6529 if (NILP (specified_data))
6531 file = x_find_image_file (specified_file);
6532 if (!STRINGP (file))
6534 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6535 UNGCPRO;
6536 return 0;
6539 /* Open the image file. */
6540 fp = fopen (SDATA (file), "rb");
6541 if (!fp)
6543 image_error ("Cannot open image file `%s'", file, Qnil);
6544 UNGCPRO;
6545 return 0;
6548 /* Check PNG signature. */
6549 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
6550 || !fn_png_check_sig (sig, sizeof sig))
6552 image_error ("Not a PNG file: `%s'", file, Qnil);
6553 UNGCPRO;
6554 fclose (fp);
6555 return 0;
6558 else
6560 /* Read from memory. */
6561 tbr.bytes = SDATA (specified_data);
6562 tbr.len = SBYTES (specified_data);
6563 tbr.index = 0;
6565 /* Check PNG signature. */
6566 if (tbr.len < sizeof sig
6567 || !fn_png_check_sig (tbr.bytes, sizeof sig))
6569 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
6570 UNGCPRO;
6571 return 0;
6574 /* Need to skip past the signature. */
6575 tbr.bytes += sizeof (sig);
6578 /* Initialize read and info structs for PNG lib. Casting return
6579 value avoids a GCC warning on W32. */
6580 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
6581 NULL, my_png_error,
6582 my_png_warning);
6583 if (!png_ptr)
6585 if (fp) fclose (fp);
6586 UNGCPRO;
6587 return 0;
6590 /* Casting return value avoids a GCC warning on W32. */
6591 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
6592 if (!info_ptr)
6594 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
6595 if (fp) fclose (fp);
6596 UNGCPRO;
6597 return 0;
6600 /* Casting return value avoids a GCC warning on W32. */
6601 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
6602 if (!end_info)
6604 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
6605 if (fp) fclose (fp);
6606 UNGCPRO;
6607 return 0;
6610 /* Set error jump-back. We come back here when the PNG library
6611 detects an error. */
6612 if (setjmp (png_ptr->jmpbuf))
6614 error:
6615 if (png_ptr)
6616 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6617 xfree (pixels);
6618 xfree (rows);
6619 if (fp) fclose (fp);
6620 UNGCPRO;
6621 return 0;
6624 /* Read image info. */
6625 if (!NILP (specified_data))
6626 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
6627 else
6628 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
6630 fn_png_set_sig_bytes (png_ptr, sizeof sig);
6631 fn_png_read_info (png_ptr, info_ptr);
6632 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6633 &interlace_type, NULL, NULL);
6635 if (!check_image_size (f, width, height))
6636 goto error;
6638 /* If image contains simply transparency data, we prefer to
6639 construct a clipping mask. */
6640 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6641 transparent_p = 1;
6642 else
6643 transparent_p = 0;
6645 /* This function is easier to write if we only have to handle
6646 one data format: RGB or RGBA with 8 bits per channel. Let's
6647 transform other formats into that format. */
6649 /* Strip more than 8 bits per channel. */
6650 if (bit_depth == 16)
6651 fn_png_set_strip_16 (png_ptr);
6653 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6654 if available. */
6655 fn_png_set_expand (png_ptr);
6657 /* Convert grayscale images to RGB. */
6658 if (color_type == PNG_COLOR_TYPE_GRAY
6659 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6660 fn_png_set_gray_to_rgb (png_ptr);
6662 screen_gamma = (f->gamma ? 1 / f->gamma / 0.45455 : 2.2);
6664 #if 0 /* Avoid double gamma correction for PNG images. */
6665 { /* Tell the PNG lib to handle gamma correction for us. */
6666 int intent;
6667 double image_gamma;
6668 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
6669 if (png_get_sRGB (png_ptr, info_ptr, &intent))
6670 /* The libpng documentation says this is right in this case. */
6671 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6672 else
6673 #endif
6674 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
6675 /* Image contains gamma information. */
6676 png_set_gamma (png_ptr, screen_gamma, image_gamma);
6677 else
6678 /* Use the standard default for the image gamma. */
6679 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6681 #endif /* if 0 */
6683 /* Handle alpha channel by combining the image with a background
6684 color. Do this only if a real alpha channel is supplied. For
6685 simple transparency, we prefer a clipping mask. */
6686 if (!transparent_p)
6688 png_color_16 *image_bg;
6689 Lisp_Object specified_bg
6690 = image_spec_value (img->spec, QCbackground, NULL);
6692 if (STRINGP (specified_bg))
6693 /* The user specified `:background', use that. */
6695 /* W32 version incorrectly used COLORREF here!! ++kfs */
6696 XColor color;
6697 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
6699 png_color_16 user_bg;
6701 bzero (&user_bg, sizeof user_bg);
6702 user_bg.red = color.red >> 8;
6703 user_bg.green = color.green >> 8;
6704 user_bg.blue = color.blue >> 8;
6706 fn_png_set_background (png_ptr, &user_bg,
6707 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6710 /* The commented-out code checked if the png specifies a default
6711 background color, and uses that. Since we use the current
6712 frame background, it is OK for us to ignore this.
6714 else if (fn_png_get_bKGD (png_ptr, info_ptr, &image_bg))
6715 fn_png_set_background (png_ptr, image_bg,
6716 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
6718 else
6720 /* Image does not contain a background color with which
6721 to combine the image data via an alpha channel. Use
6722 the frame's background instead. */
6723 #ifdef HAVE_X_WINDOWS
6724 XColor color;
6725 png_color_16 frame_background;
6727 color.pixel = FRAME_BACKGROUND_PIXEL (f);
6728 x_query_color (f, &color);
6730 bzero (&frame_background, sizeof frame_background);
6731 frame_background.red = color.red >> 8;
6732 frame_background.green = color.green >> 8;
6733 frame_background.blue = color.blue >> 8;
6734 #endif /* HAVE_X_WINDOWS */
6736 #ifdef HAVE_NTGUI
6737 COLORREF color;
6738 png_color_16 frame_background;
6739 color = FRAME_BACKGROUND_PIXEL (f);
6740 #if 0 /* W32 TODO : Colormap support. */
6741 x_query_color (f, &color);
6742 #endif
6743 bzero (&frame_background, sizeof frame_background);
6744 frame_background.red = GetRValue (color);
6745 frame_background.green = GetGValue (color);
6746 frame_background.blue = GetBValue (color);
6747 #endif /* HAVE_NTGUI */
6749 #ifdef MAC_OS
6750 unsigned long color;
6751 png_color_16 frame_background;
6752 color = FRAME_BACKGROUND_PIXEL (f);
6753 #if 0 /* MAC/W32 TODO : Colormap support. */
6754 x_query_color (f, &color);
6755 #endif
6756 bzero (&frame_background, sizeof frame_background);
6757 frame_background.red = RED_FROM_ULONG (color);
6758 frame_background.green = GREEN_FROM_ULONG (color);
6759 frame_background.blue = BLUE_FROM_ULONG (color);
6760 #endif /* MAC_OS */
6762 fn_png_set_background (png_ptr, &frame_background,
6763 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6767 /* Update info structure. */
6768 fn_png_read_update_info (png_ptr, info_ptr);
6770 /* Get number of channels. Valid values are 1 for grayscale images
6771 and images with a palette, 2 for grayscale images with transparency
6772 information (alpha channel), 3 for RGB images, and 4 for RGB
6773 images with alpha channel, i.e. RGBA. If conversions above were
6774 sufficient we should only have 3 or 4 channels here. */
6775 channels = fn_png_get_channels (png_ptr, info_ptr);
6776 xassert (channels == 3 || channels == 4);
6778 /* Number of bytes needed for one row of the image. */
6779 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
6781 /* Allocate memory for the image. */
6782 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
6783 rows = (png_byte **) xmalloc (height * sizeof *rows);
6784 for (i = 0; i < height; ++i)
6785 rows[i] = pixels + i * row_bytes;
6787 /* Read the entire image. */
6788 fn_png_read_image (png_ptr, rows);
6789 fn_png_read_end (png_ptr, info_ptr);
6790 if (fp)
6792 fclose (fp);
6793 fp = NULL;
6796 /* Create the X image and pixmap. */
6797 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
6798 &img->pixmap))
6799 goto error;
6801 /* Create an image and pixmap serving as mask if the PNG image
6802 contains an alpha channel. */
6803 if (channels == 4
6804 && !transparent_p
6805 && !x_create_x_image_and_pixmap (f, width, height, 1,
6806 &mask_img, &img->mask))
6808 x_destroy_x_image (ximg);
6809 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
6810 img->pixmap = NO_PIXMAP;
6811 goto error;
6814 /* Fill the X image and mask from PNG data. */
6815 init_color_table ();
6817 for (y = 0; y < height; ++y)
6819 png_byte *p = rows[y];
6821 for (x = 0; x < width; ++x)
6823 unsigned r, g, b;
6825 r = *p++ << 8;
6826 g = *p++ << 8;
6827 b = *p++ << 8;
6828 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6829 /* An alpha channel, aka mask channel, associates variable
6830 transparency with an image. Where other image formats
6831 support binary transparency---fully transparent or fully
6832 opaque---PNG allows up to 254 levels of partial transparency.
6833 The PNG library implements partial transparency by combining
6834 the image with a specified background color.
6836 I'm not sure how to handle this here nicely: because the
6837 background on which the image is displayed may change, for
6838 real alpha channel support, it would be necessary to create
6839 a new image for each possible background.
6841 What I'm doing now is that a mask is created if we have
6842 boolean transparency information. Otherwise I'm using
6843 the frame's background color to combine the image with. */
6845 if (channels == 4)
6847 if (mask_img)
6848 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6849 ++p;
6854 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6855 /* Set IMG's background color from the PNG image, unless the user
6856 overrode it. */
6858 png_color_16 *bg;
6859 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6861 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6862 img->background_valid = 1;
6866 #ifdef COLOR_TABLE_SUPPORT
6867 /* Remember colors allocated for this image. */
6868 img->colors = colors_in_color_table (&img->ncolors);
6869 free_color_table ();
6870 #endif /* COLOR_TABLE_SUPPORT */
6872 /* Clean up. */
6873 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6874 xfree (rows);
6875 xfree (pixels);
6877 img->width = width;
6878 img->height = height;
6880 /* Maybe fill in the background field while we have ximg handy.
6881 Casting avoids a GCC warning. */
6882 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6884 /* Put the image into the pixmap, then free the X image and its buffer. */
6885 x_put_x_image (f, ximg, img->pixmap, width, height);
6886 x_destroy_x_image (ximg);
6888 /* Same for the mask. */
6889 if (mask_img)
6891 /* Fill in the background_transparent field while we have the
6892 mask handy. Casting avoids a GCC warning. */
6893 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6895 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
6896 x_destroy_x_image (mask_img);
6899 UNGCPRO;
6900 return 1;
6903 #else /* HAVE_PNG */
6905 #ifdef MAC_OS
6906 static int
6907 png_load (f, img)
6908 struct frame *f;
6909 struct image *img;
6911 #if USE_MAC_IMAGE_IO
6912 return image_load_image_io (f, img, kUTTypePNG);
6913 #elif MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
6914 return image_load_quartz2d (f, img, 1);
6915 #else
6916 return image_load_quicktime (f, img, kQTFileTypePNG);
6917 #endif
6919 #endif /* MAC_OS */
6921 #endif /* !HAVE_PNG */
6925 /***********************************************************************
6926 JPEG
6927 ***********************************************************************/
6929 #if defined (HAVE_JPEG) || defined (MAC_OS)
6931 static int jpeg_image_p P_ ((Lisp_Object object));
6932 static int jpeg_load P_ ((struct frame *f, struct image *img));
6934 /* The symbol `jpeg' identifying images of this type. */
6936 Lisp_Object Qjpeg;
6938 /* Indices of image specification fields in gs_format, below. */
6940 enum jpeg_keyword_index
6942 JPEG_TYPE,
6943 JPEG_DATA,
6944 JPEG_FILE,
6945 JPEG_ASCENT,
6946 JPEG_MARGIN,
6947 JPEG_RELIEF,
6948 JPEG_ALGORITHM,
6949 JPEG_HEURISTIC_MASK,
6950 JPEG_MASK,
6951 JPEG_BACKGROUND,
6952 JPEG_LAST
6955 /* Vector of image_keyword structures describing the format
6956 of valid user-defined image specifications. */
6958 static struct image_keyword jpeg_format[JPEG_LAST] =
6960 {":type", IMAGE_SYMBOL_VALUE, 1},
6961 {":data", IMAGE_STRING_VALUE, 0},
6962 {":file", IMAGE_STRING_VALUE, 0},
6963 {":ascent", IMAGE_ASCENT_VALUE, 0},
6964 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6965 {":relief", IMAGE_INTEGER_VALUE, 0},
6966 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6967 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6968 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6969 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6972 /* Structure describing the image type `jpeg'. */
6974 static struct image_type jpeg_type =
6976 &Qjpeg,
6977 jpeg_image_p,
6978 jpeg_load,
6979 x_clear_image,
6980 NULL
6983 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6985 static int
6986 jpeg_image_p (object)
6987 Lisp_Object object;
6989 struct image_keyword fmt[JPEG_LAST];
6991 bcopy (jpeg_format, fmt, sizeof fmt);
6993 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6994 return 0;
6996 /* Must specify either the :data or :file keyword. */
6997 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
7000 #endif /* HAVE_JPEG || MAC_OS */
7002 #ifdef HAVE_JPEG
7004 /* Work around a warning about HAVE_STDLIB_H being redefined in
7005 jconfig.h. */
7006 #ifdef HAVE_STDLIB_H
7007 #define HAVE_STDLIB_H_1
7008 #undef HAVE_STDLIB_H
7009 #endif /* HAVE_STLIB_H */
7011 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
7012 /* In older releases of the jpeg library, jpeglib.h will define boolean
7013 differently depending on __WIN32__, so make sure it is defined. */
7014 #define __WIN32__ 1
7015 #endif
7017 #include <jpeglib.h>
7018 #include <jerror.h>
7019 #include <setjmp.h>
7021 #ifdef HAVE_STLIB_H_1
7022 #define HAVE_STDLIB_H 1
7023 #endif
7025 #ifdef HAVE_NTGUI
7027 /* JPEG library details. */
7028 DEF_IMGLIB_FN (jpeg_CreateDecompress);
7029 DEF_IMGLIB_FN (jpeg_start_decompress);
7030 DEF_IMGLIB_FN (jpeg_finish_decompress);
7031 DEF_IMGLIB_FN (jpeg_destroy_decompress);
7032 DEF_IMGLIB_FN (jpeg_read_header);
7033 DEF_IMGLIB_FN (jpeg_read_scanlines);
7034 DEF_IMGLIB_FN (jpeg_std_error);
7035 DEF_IMGLIB_FN (jpeg_resync_to_restart);
7037 static int
7038 init_jpeg_functions (Lisp_Object libraries)
7040 HMODULE library;
7042 if (!(library = w32_delayed_load (libraries, Qjpeg)))
7043 return 0;
7045 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
7046 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
7047 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
7048 LOAD_IMGLIB_FN (library, jpeg_read_header);
7049 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
7050 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
7051 LOAD_IMGLIB_FN (library, jpeg_std_error);
7052 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
7053 return 1;
7056 /* Wrapper since we can't directly assign the function pointer
7057 to another function pointer that was declared more completely easily. */
7058 static boolean
7059 jpeg_resync_to_restart_wrapper(cinfo, desired)
7060 j_decompress_ptr cinfo;
7061 int desired;
7063 return fn_jpeg_resync_to_restart (cinfo, desired);
7066 #else
7068 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
7069 #define fn_jpeg_start_decompress jpeg_start_decompress
7070 #define fn_jpeg_finish_decompress jpeg_finish_decompress
7071 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
7072 #define fn_jpeg_read_header jpeg_read_header
7073 #define fn_jpeg_read_scanlines jpeg_read_scanlines
7074 #define fn_jpeg_std_error jpeg_std_error
7075 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
7077 #endif /* HAVE_NTGUI */
7079 struct my_jpeg_error_mgr
7081 struct jpeg_error_mgr pub;
7082 jmp_buf setjmp_buffer;
7086 static void
7087 my_error_exit (cinfo)
7088 j_common_ptr cinfo;
7090 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
7091 longjmp (mgr->setjmp_buffer, 1);
7095 /* Init source method for JPEG data source manager. Called by
7096 jpeg_read_header() before any data is actually read. See
7097 libjpeg.doc from the JPEG lib distribution. */
7099 static void
7100 our_common_init_source (cinfo)
7101 j_decompress_ptr cinfo;
7106 /* Method to terminate data source. Called by
7107 jpeg_finish_decompress() after all data has been processed. */
7109 static void
7110 our_common_term_source (cinfo)
7111 j_decompress_ptr cinfo;
7116 /* Fill input buffer method for JPEG data source manager. Called
7117 whenever more data is needed. We read the whole image in one step,
7118 so this only adds a fake end of input marker at the end. */
7120 static JOCTET our_memory_buffer[2];
7122 static boolean
7123 our_memory_fill_input_buffer (cinfo)
7124 j_decompress_ptr cinfo;
7126 /* Insert a fake EOI marker. */
7127 struct jpeg_source_mgr *src = cinfo->src;
7129 our_memory_buffer[0] = (JOCTET) 0xFF;
7130 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
7132 src->next_input_byte = our_memory_buffer;
7133 src->bytes_in_buffer = 2;
7134 return 1;
7138 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
7139 is the JPEG data source manager. */
7141 static void
7142 our_memory_skip_input_data (cinfo, num_bytes)
7143 j_decompress_ptr cinfo;
7144 long num_bytes;
7146 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
7148 if (src)
7150 if (num_bytes > src->bytes_in_buffer)
7151 ERREXIT (cinfo, JERR_INPUT_EOF);
7153 src->bytes_in_buffer -= num_bytes;
7154 src->next_input_byte += num_bytes;
7159 /* Set up the JPEG lib for reading an image from DATA which contains
7160 LEN bytes. CINFO is the decompression info structure created for
7161 reading the image. */
7163 static void
7164 jpeg_memory_src (cinfo, data, len)
7165 j_decompress_ptr cinfo;
7166 JOCTET *data;
7167 unsigned int len;
7169 struct jpeg_source_mgr *src;
7171 if (cinfo->src == NULL)
7173 /* First time for this JPEG object? */
7174 cinfo->src = (struct jpeg_source_mgr *)
7175 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
7176 sizeof (struct jpeg_source_mgr));
7177 src = (struct jpeg_source_mgr *) cinfo->src;
7178 src->next_input_byte = data;
7181 src = (struct jpeg_source_mgr *) cinfo->src;
7182 src->init_source = our_common_init_source;
7183 src->fill_input_buffer = our_memory_fill_input_buffer;
7184 src->skip_input_data = our_memory_skip_input_data;
7185 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
7186 src->term_source = our_common_term_source;
7187 src->bytes_in_buffer = len;
7188 src->next_input_byte = data;
7192 struct jpeg_stdio_mgr
7194 struct jpeg_source_mgr mgr;
7195 boolean finished;
7196 FILE *file;
7197 JOCTET *buffer;
7201 /* Size of buffer to read JPEG from file.
7202 Not too big, as we want to use alloc_small. */
7203 #define JPEG_STDIO_BUFFER_SIZE 8192
7206 /* Fill input buffer method for JPEG data source manager. Called
7207 whenever more data is needed. The data is read from a FILE *. */
7209 static boolean
7210 our_stdio_fill_input_buffer (cinfo)
7211 j_decompress_ptr cinfo;
7213 struct jpeg_stdio_mgr *src;
7215 src = (struct jpeg_stdio_mgr *) cinfo->src;
7216 if (!src->finished)
7218 size_t bytes;
7220 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
7221 if (bytes > 0)
7222 src->mgr.bytes_in_buffer = bytes;
7223 else
7225 WARNMS (cinfo, JWRN_JPEG_EOF);
7226 src->finished = 1;
7227 src->buffer[0] = (JOCTET) 0xFF;
7228 src->buffer[1] = (JOCTET) JPEG_EOI;
7229 src->mgr.bytes_in_buffer = 2;
7231 src->mgr.next_input_byte = src->buffer;
7234 return 1;
7238 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
7239 is the JPEG data source manager. */
7241 static void
7242 our_stdio_skip_input_data (cinfo, num_bytes)
7243 j_decompress_ptr cinfo;
7244 long num_bytes;
7246 struct jpeg_stdio_mgr *src;
7247 src = (struct jpeg_stdio_mgr *) cinfo->src;
7249 while (num_bytes > 0 && !src->finished)
7251 if (num_bytes <= src->mgr.bytes_in_buffer)
7253 src->mgr.bytes_in_buffer -= num_bytes;
7254 src->mgr.next_input_byte += num_bytes;
7255 break;
7257 else
7259 num_bytes -= src->mgr.bytes_in_buffer;
7260 src->mgr.bytes_in_buffer = 0;
7261 src->mgr.next_input_byte = NULL;
7263 our_stdio_fill_input_buffer (cinfo);
7269 /* Set up the JPEG lib for reading an image from a FILE *.
7270 CINFO is the decompression info structure created for
7271 reading the image. */
7273 static void
7274 jpeg_file_src (cinfo, fp)
7275 j_decompress_ptr cinfo;
7276 FILE *fp;
7278 struct jpeg_stdio_mgr *src;
7280 if (cinfo->src != NULL)
7281 src = (struct jpeg_stdio_mgr *) cinfo->src;
7282 else
7284 /* First time for this JPEG object? */
7285 cinfo->src = (struct jpeg_source_mgr *)
7286 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
7287 sizeof (struct jpeg_stdio_mgr));
7288 src = (struct jpeg_stdio_mgr *) cinfo->src;
7289 src->buffer = (JOCTET *)
7290 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
7291 JPEG_STDIO_BUFFER_SIZE);
7294 src->file = fp;
7295 src->finished = 0;
7296 src->mgr.init_source = our_common_init_source;
7297 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
7298 src->mgr.skip_input_data = our_stdio_skip_input_data;
7299 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
7300 src->mgr.term_source = our_common_term_source;
7301 src->mgr.bytes_in_buffer = 0;
7302 src->mgr.next_input_byte = NULL;
7306 /* Load image IMG for use on frame F. Patterned after example.c
7307 from the JPEG lib. */
7309 static int
7310 jpeg_load (f, img)
7311 struct frame *f;
7312 struct image *img;
7314 struct jpeg_decompress_struct cinfo;
7315 struct my_jpeg_error_mgr mgr;
7316 Lisp_Object file, specified_file;
7317 Lisp_Object specified_data;
7318 FILE * volatile fp = NULL;
7319 JSAMPARRAY buffer;
7320 int row_stride, x, y;
7321 XImagePtr ximg = NULL;
7322 int rc;
7323 unsigned long *colors;
7324 int width, height;
7325 struct gcpro gcpro1;
7327 /* Open the JPEG file. */
7328 specified_file = image_spec_value (img->spec, QCfile, NULL);
7329 specified_data = image_spec_value (img->spec, QCdata, NULL);
7330 file = Qnil;
7331 GCPRO1 (file);
7333 if (NILP (specified_data))
7335 file = x_find_image_file (specified_file);
7336 if (!STRINGP (file))
7338 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7339 UNGCPRO;
7340 return 0;
7343 fp = fopen (SDATA (file), "rb");
7344 if (fp == NULL)
7346 image_error ("Cannot open `%s'", file, Qnil);
7347 UNGCPRO;
7348 return 0;
7352 /* Customize libjpeg's error handling to call my_error_exit when an
7353 error is detected. This function will perform a longjmp.
7354 Casting return value avoids a GCC warning on W32. */
7355 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
7356 mgr.pub.error_exit = my_error_exit;
7358 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
7360 if (rc == 1)
7362 /* Called from my_error_exit. Display a JPEG error. */
7363 char buffer[JMSG_LENGTH_MAX];
7364 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
7365 image_error ("Error reading JPEG image `%s': %s", img->spec,
7366 build_string (buffer));
7369 /* Close the input file and destroy the JPEG object. */
7370 if (fp)
7371 fclose ((FILE *) fp);
7372 fn_jpeg_destroy_decompress (&cinfo);
7374 /* If we already have an XImage, free that. */
7375 x_destroy_x_image (ximg);
7377 /* Free pixmap and colors. */
7378 x_clear_image (f, img);
7380 UNGCPRO;
7381 return 0;
7384 /* Create the JPEG decompression object. Let it read from fp.
7385 Read the JPEG image header. */
7386 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
7388 if (NILP (specified_data))
7389 jpeg_file_src (&cinfo, (FILE *) fp);
7390 else
7391 jpeg_memory_src (&cinfo, SDATA (specified_data),
7392 SBYTES (specified_data));
7394 fn_jpeg_read_header (&cinfo, 1);
7396 /* Customize decompression so that color quantization will be used.
7397 Start decompression. */
7398 cinfo.quantize_colors = 1;
7399 fn_jpeg_start_decompress (&cinfo);
7400 width = img->width = cinfo.output_width;
7401 height = img->height = cinfo.output_height;
7403 if (!check_image_size (f, width, height))
7405 image_error ("Invalid image size", Qnil, Qnil);
7406 longjmp (mgr.setjmp_buffer, 2);
7409 /* Create X image and pixmap. */
7410 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7411 longjmp (mgr.setjmp_buffer, 2);
7413 /* Allocate colors. When color quantization is used,
7414 cinfo.actual_number_of_colors has been set with the number of
7415 colors generated, and cinfo.colormap is a two-dimensional array
7416 of color indices in the range 0..cinfo.actual_number_of_colors.
7417 No more than 255 colors will be generated. */
7419 int i, ir, ig, ib;
7421 if (cinfo.out_color_components > 2)
7422 ir = 0, ig = 1, ib = 2;
7423 else if (cinfo.out_color_components > 1)
7424 ir = 0, ig = 1, ib = 0;
7425 else
7426 ir = 0, ig = 0, ib = 0;
7428 /* Use the color table mechanism because it handles colors that
7429 cannot be allocated nicely. Such colors will be replaced with
7430 a default color, and we don't have to care about which colors
7431 can be freed safely, and which can't. */
7432 init_color_table ();
7433 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
7434 * sizeof *colors);
7436 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
7438 /* Multiply RGB values with 255 because X expects RGB values
7439 in the range 0..0xffff. */
7440 int r = cinfo.colormap[ir][i] << 8;
7441 int g = cinfo.colormap[ig][i] << 8;
7442 int b = cinfo.colormap[ib][i] << 8;
7443 colors[i] = lookup_rgb_color (f, r, g, b);
7446 #ifdef COLOR_TABLE_SUPPORT
7447 /* Remember those colors actually allocated. */
7448 img->colors = colors_in_color_table (&img->ncolors);
7449 free_color_table ();
7450 #endif /* COLOR_TABLE_SUPPORT */
7453 /* Read pixels. */
7454 row_stride = width * cinfo.output_components;
7455 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
7456 row_stride, 1);
7457 for (y = 0; y < height; ++y)
7459 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
7460 for (x = 0; x < cinfo.output_width; ++x)
7461 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
7464 /* Clean up. */
7465 fn_jpeg_finish_decompress (&cinfo);
7466 fn_jpeg_destroy_decompress (&cinfo);
7467 if (fp)
7468 fclose ((FILE *) fp);
7470 /* Maybe fill in the background field while we have ximg handy. */
7471 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7472 /* Casting avoids a GCC warning. */
7473 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7475 /* Put the image into the pixmap. */
7476 x_put_x_image (f, ximg, img->pixmap, width, height);
7477 x_destroy_x_image (ximg);
7478 UNGCPRO;
7479 return 1;
7482 #else /* HAVE_JPEG */
7484 #ifdef MAC_OS
7485 static int
7486 jpeg_load (f, img)
7487 struct frame *f;
7488 struct image *img;
7490 #if USE_MAC_IMAGE_IO
7491 return image_load_image_io (f, img, kUTTypeJPEG);
7492 #elif defined (MAC_OSX)
7493 return image_load_quartz2d (f, img, 0);
7494 #else
7495 return image_load_quicktime (f, img, kQTFileTypeJPEG);
7496 #endif
7498 #endif /* MAC_OS */
7500 #endif /* !HAVE_JPEG */
7504 /***********************************************************************
7505 TIFF
7506 ***********************************************************************/
7508 #if defined (HAVE_TIFF) || defined (MAC_OS)
7510 static int tiff_image_p P_ ((Lisp_Object object));
7511 static int tiff_load P_ ((struct frame *f, struct image *img));
7513 /* The symbol `tiff' identifying images of this type. */
7515 Lisp_Object Qtiff;
7517 /* Indices of image specification fields in tiff_format, below. */
7519 enum tiff_keyword_index
7521 TIFF_TYPE,
7522 TIFF_DATA,
7523 TIFF_FILE,
7524 TIFF_ASCENT,
7525 TIFF_MARGIN,
7526 TIFF_RELIEF,
7527 TIFF_ALGORITHM,
7528 TIFF_HEURISTIC_MASK,
7529 TIFF_MASK,
7530 TIFF_BACKGROUND,
7531 TIFF_LAST
7534 /* Vector of image_keyword structures describing the format
7535 of valid user-defined image specifications. */
7537 static struct image_keyword tiff_format[TIFF_LAST] =
7539 {":type", IMAGE_SYMBOL_VALUE, 1},
7540 {":data", IMAGE_STRING_VALUE, 0},
7541 {":file", IMAGE_STRING_VALUE, 0},
7542 {":ascent", IMAGE_ASCENT_VALUE, 0},
7543 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7544 {":relief", IMAGE_INTEGER_VALUE, 0},
7545 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7546 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7547 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7548 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7551 /* Structure describing the image type `tiff'. */
7553 static struct image_type tiff_type =
7555 &Qtiff,
7556 tiff_image_p,
7557 tiff_load,
7558 x_clear_image,
7559 NULL
7562 /* Return non-zero if OBJECT is a valid TIFF image specification. */
7564 static int
7565 tiff_image_p (object)
7566 Lisp_Object object;
7568 struct image_keyword fmt[TIFF_LAST];
7569 bcopy (tiff_format, fmt, sizeof fmt);
7571 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
7572 return 0;
7574 /* Must specify either the :data or :file keyword. */
7575 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
7578 #endif /* HAVE_TIFF || MAC_OS */
7580 #ifdef HAVE_TIFF
7582 #include <tiffio.h>
7584 #ifdef HAVE_NTGUI
7586 /* TIFF library details. */
7587 DEF_IMGLIB_FN (TIFFSetErrorHandler);
7588 DEF_IMGLIB_FN (TIFFSetWarningHandler);
7589 DEF_IMGLIB_FN (TIFFOpen);
7590 DEF_IMGLIB_FN (TIFFClientOpen);
7591 DEF_IMGLIB_FN (TIFFGetField);
7592 DEF_IMGLIB_FN (TIFFReadRGBAImage);
7593 DEF_IMGLIB_FN (TIFFClose);
7595 static int
7596 init_tiff_functions (Lisp_Object libraries)
7598 HMODULE library;
7600 if (!(library = w32_delayed_load (libraries, Qtiff)))
7601 return 0;
7603 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
7604 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
7605 LOAD_IMGLIB_FN (library, TIFFOpen);
7606 LOAD_IMGLIB_FN (library, TIFFClientOpen);
7607 LOAD_IMGLIB_FN (library, TIFFGetField);
7608 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
7609 LOAD_IMGLIB_FN (library, TIFFClose);
7610 return 1;
7613 #else
7615 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
7616 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
7617 #define fn_TIFFOpen TIFFOpen
7618 #define fn_TIFFClientOpen TIFFClientOpen
7619 #define fn_TIFFGetField TIFFGetField
7620 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
7621 #define fn_TIFFClose TIFFClose
7623 #endif /* HAVE_NTGUI */
7626 /* Reading from a memory buffer for TIFF images Based on the PNG
7627 memory source, but we have to provide a lot of extra functions.
7628 Blah.
7630 We really only need to implement read and seek, but I am not
7631 convinced that the TIFF library is smart enough not to destroy
7632 itself if we only hand it the function pointers we need to
7633 override. */
7635 typedef struct
7637 unsigned char *bytes;
7638 size_t len;
7639 int index;
7641 tiff_memory_source;
7643 static size_t
7644 tiff_read_from_memory (data, buf, size)
7645 thandle_t data;
7646 tdata_t buf;
7647 tsize_t size;
7649 tiff_memory_source *src = (tiff_memory_source *) data;
7651 if (size > src->len - src->index)
7652 return (size_t) -1;
7653 bcopy (src->bytes + src->index, buf, size);
7654 src->index += size;
7655 return size;
7658 static size_t
7659 tiff_write_from_memory (data, buf, size)
7660 thandle_t data;
7661 tdata_t buf;
7662 tsize_t size;
7664 return (size_t) -1;
7667 static toff_t
7668 tiff_seek_in_memory (data, off, whence)
7669 thandle_t data;
7670 toff_t off;
7671 int whence;
7673 tiff_memory_source *src = (tiff_memory_source *) data;
7674 int idx;
7676 switch (whence)
7678 case SEEK_SET: /* Go from beginning of source. */
7679 idx = off;
7680 break;
7682 case SEEK_END: /* Go from end of source. */
7683 idx = src->len + off;
7684 break;
7686 case SEEK_CUR: /* Go from current position. */
7687 idx = src->index + off;
7688 break;
7690 default: /* Invalid `whence'. */
7691 return -1;
7694 if (idx > src->len || idx < 0)
7695 return -1;
7697 src->index = idx;
7698 return src->index;
7701 static int
7702 tiff_close_memory (data)
7703 thandle_t data;
7705 /* NOOP */
7706 return 0;
7709 static int
7710 tiff_mmap_memory (data, pbase, psize)
7711 thandle_t data;
7712 tdata_t *pbase;
7713 toff_t *psize;
7715 /* It is already _IN_ memory. */
7716 return 0;
7719 static void
7720 tiff_unmap_memory (data, base, size)
7721 thandle_t data;
7722 tdata_t base;
7723 toff_t size;
7725 /* We don't need to do this. */
7728 static toff_t
7729 tiff_size_of_memory (data)
7730 thandle_t data;
7732 return ((tiff_memory_source *) data)->len;
7736 static void
7737 tiff_error_handler (title, format, ap)
7738 const char *title, *format;
7739 va_list ap;
7741 char buf[512];
7742 int len;
7744 len = sprintf (buf, "TIFF error: %s ", title);
7745 vsprintf (buf + len, format, ap);
7746 add_to_log (buf, Qnil, Qnil);
7750 static void
7751 tiff_warning_handler (title, format, ap)
7752 const char *title, *format;
7753 va_list ap;
7755 char buf[512];
7756 int len;
7758 len = sprintf (buf, "TIFF warning: %s ", title);
7759 vsprintf (buf + len, format, ap);
7760 add_to_log (buf, Qnil, Qnil);
7764 /* Load TIFF image IMG for use on frame F. Value is non-zero if
7765 successful. */
7767 static int
7768 tiff_load (f, img)
7769 struct frame *f;
7770 struct image *img;
7772 Lisp_Object file, specified_file;
7773 Lisp_Object specified_data;
7774 TIFF *tiff;
7775 int width, height, x, y;
7776 uint32 *buf;
7777 int rc;
7778 XImagePtr ximg;
7779 struct gcpro gcpro1;
7780 tiff_memory_source memsrc;
7782 specified_file = image_spec_value (img->spec, QCfile, NULL);
7783 specified_data = image_spec_value (img->spec, QCdata, NULL);
7784 file = Qnil;
7785 GCPRO1 (file);
7787 fn_TIFFSetErrorHandler (tiff_error_handler);
7788 fn_TIFFSetWarningHandler (tiff_warning_handler);
7790 if (NILP (specified_data))
7792 /* Read from a file */
7793 file = x_find_image_file (specified_file);
7794 if (!STRINGP (file))
7796 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7797 UNGCPRO;
7798 return 0;
7801 /* Try to open the image file. Casting return value avoids a
7802 GCC warning on W32. */
7803 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
7804 if (tiff == NULL)
7806 image_error ("Cannot open `%s'", file, Qnil);
7807 UNGCPRO;
7808 return 0;
7811 else
7813 /* Memory source! */
7814 memsrc.bytes = SDATA (specified_data);
7815 memsrc.len = SBYTES (specified_data);
7816 memsrc.index = 0;
7818 /* Casting return value avoids a GCC warning on W32. */
7819 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r", &memsrc,
7820 (TIFFReadWriteProc) tiff_read_from_memory,
7821 (TIFFReadWriteProc) tiff_write_from_memory,
7822 tiff_seek_in_memory,
7823 tiff_close_memory,
7824 tiff_size_of_memory,
7825 tiff_mmap_memory,
7826 tiff_unmap_memory);
7828 if (!tiff)
7830 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7831 UNGCPRO;
7832 return 0;
7836 /* Get width and height of the image, and allocate a raster buffer
7837 of width x height 32-bit values. */
7838 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7839 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7841 if (!check_image_size (f, width, height))
7843 image_error ("Invalid image size", Qnil, Qnil);
7844 UNGCPRO;
7845 return 0;
7848 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
7850 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7851 fn_TIFFClose (tiff);
7852 if (!rc)
7854 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7855 xfree (buf);
7856 UNGCPRO;
7857 return 0;
7860 /* Create the X image and pixmap. */
7861 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7863 xfree (buf);
7864 UNGCPRO;
7865 return 0;
7868 /* Initialize the color table. */
7869 init_color_table ();
7871 /* Process the pixel raster. Origin is in the lower-left corner. */
7872 for (y = 0; y < height; ++y)
7874 uint32 *row = buf + y * width;
7876 for (x = 0; x < width; ++x)
7878 uint32 abgr = row[x];
7879 int r = TIFFGetR (abgr) << 8;
7880 int g = TIFFGetG (abgr) << 8;
7881 int b = TIFFGetB (abgr) << 8;
7882 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7886 #ifdef COLOR_TABLE_SUPPORT
7887 /* Remember the colors allocated for the image. Free the color table. */
7888 img->colors = colors_in_color_table (&img->ncolors);
7889 free_color_table ();
7890 #endif /* COLOR_TABLE_SUPPORT */
7892 img->width = width;
7893 img->height = height;
7895 /* Maybe fill in the background field while we have ximg handy. */
7896 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7897 /* Casting avoids a GCC warning on W32. */
7898 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7900 /* Put the image into the pixmap, then free the X image and its buffer. */
7901 x_put_x_image (f, ximg, img->pixmap, width, height);
7902 x_destroy_x_image (ximg);
7903 xfree (buf);
7905 UNGCPRO;
7906 return 1;
7909 #else /* HAVE_TIFF */
7911 #ifdef MAC_OS
7912 static int
7913 tiff_load (f, img)
7914 struct frame *f;
7915 struct image *img;
7917 #if USE_MAC_IMAGE_IO
7918 return image_load_image_io (f, img, kUTTypeTIFF);
7919 #else
7920 return image_load_quicktime (f, img, kQTFileTypeTIFF);
7921 #endif
7923 #endif /* MAC_OS */
7925 #endif /* !HAVE_TIFF */
7929 /***********************************************************************
7931 ***********************************************************************/
7933 #if defined (HAVE_GIF) || defined (MAC_OS)
7935 static int gif_image_p P_ ((Lisp_Object object));
7936 static int gif_load P_ ((struct frame *f, struct image *img));
7937 static void gif_clear_image P_ ((struct frame *f, struct image *img));
7939 /* The symbol `gif' identifying images of this type. */
7941 Lisp_Object Qgif;
7943 /* Indices of image specification fields in gif_format, below. */
7945 enum gif_keyword_index
7947 GIF_TYPE,
7948 GIF_DATA,
7949 GIF_FILE,
7950 GIF_ASCENT,
7951 GIF_MARGIN,
7952 GIF_RELIEF,
7953 GIF_ALGORITHM,
7954 GIF_HEURISTIC_MASK,
7955 GIF_MASK,
7956 GIF_IMAGE,
7957 GIF_BACKGROUND,
7958 GIF_LAST
7961 /* Vector of image_keyword structures describing the format
7962 of valid user-defined image specifications. */
7964 static struct image_keyword gif_format[GIF_LAST] =
7966 {":type", IMAGE_SYMBOL_VALUE, 1},
7967 {":data", IMAGE_STRING_VALUE, 0},
7968 {":file", IMAGE_STRING_VALUE, 0},
7969 {":ascent", IMAGE_ASCENT_VALUE, 0},
7970 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7971 {":relief", IMAGE_INTEGER_VALUE, 0},
7972 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7973 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7974 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7975 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7976 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7979 /* Structure describing the image type `gif'. */
7981 static struct image_type gif_type =
7983 &Qgif,
7984 gif_image_p,
7985 gif_load,
7986 gif_clear_image,
7987 NULL
7990 /* Free X resources of GIF image IMG which is used on frame F. */
7992 static void
7993 gif_clear_image (f, img)
7994 struct frame *f;
7995 struct image *img;
7997 /* IMG->data.ptr_val may contain extension data. */
7998 img->data.lisp_val = Qnil;
7999 x_clear_image (f, img);
8002 /* Return non-zero if OBJECT is a valid GIF image specification. */
8004 static int
8005 gif_image_p (object)
8006 Lisp_Object object;
8008 struct image_keyword fmt[GIF_LAST];
8009 bcopy (gif_format, fmt, sizeof fmt);
8011 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
8012 return 0;
8014 /* Must specify either the :data or :file keyword. */
8015 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
8018 #endif /* HAVE_GIF || MAC_OS */
8020 #ifdef HAVE_GIF
8022 #if defined (HAVE_NTGUI) || defined (MAC_OS)
8023 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
8024 Undefine before redefining to avoid a preprocessor warning. */
8025 #ifdef DrawText
8026 #undef DrawText
8027 #endif
8028 /* avoid conflict with QuickdrawText.h */
8029 #define DrawText gif_DrawText
8030 #include <gif_lib.h>
8031 #undef DrawText
8033 #else /* HAVE_NTGUI || MAC_OS */
8035 #include <gif_lib.h>
8037 #endif /* HAVE_NTGUI || MAC_OS */
8040 #ifdef HAVE_NTGUI
8042 /* GIF library details. */
8043 DEF_IMGLIB_FN (DGifCloseFile);
8044 DEF_IMGLIB_FN (DGifSlurp);
8045 DEF_IMGLIB_FN (DGifOpen);
8046 DEF_IMGLIB_FN (DGifOpenFileName);
8048 static int
8049 init_gif_functions (Lisp_Object libraries)
8051 HMODULE library;
8053 if (!(library = w32_delayed_load (libraries, Qgif)))
8054 return 0;
8056 LOAD_IMGLIB_FN (library, DGifCloseFile);
8057 LOAD_IMGLIB_FN (library, DGifSlurp);
8058 LOAD_IMGLIB_FN (library, DGifOpen);
8059 LOAD_IMGLIB_FN (library, DGifOpenFileName);
8060 return 1;
8063 #else
8065 #define fn_DGifCloseFile DGifCloseFile
8066 #define fn_DGifSlurp DGifSlurp
8067 #define fn_DGifOpen DGifOpen
8068 #define fn_DGifOpenFileName DGifOpenFileName
8070 #endif /* HAVE_NTGUI */
8072 /* Reading a GIF image from memory
8073 Based on the PNG memory stuff to a certain extent. */
8075 typedef struct
8077 unsigned char *bytes;
8078 size_t len;
8079 int index;
8081 gif_memory_source;
8083 /* Make the current memory source available to gif_read_from_memory.
8084 It's done this way because not all versions of libungif support
8085 a UserData field in the GifFileType structure. */
8086 static gif_memory_source *current_gif_memory_src;
8088 static int
8089 gif_read_from_memory (file, buf, len)
8090 GifFileType *file;
8091 GifByteType *buf;
8092 int len;
8094 gif_memory_source *src = current_gif_memory_src;
8096 if (len > src->len - src->index)
8097 return -1;
8099 bcopy (src->bytes + src->index, buf, len);
8100 src->index += len;
8101 return len;
8105 /* Load GIF image IMG for use on frame F. Value is non-zero if
8106 successful. */
8108 static int interlace_start[] = {0, 4, 2, 1};
8109 static int interlace_increment[] = {8, 8, 4, 2};
8111 static int
8112 gif_load (f, img)
8113 struct frame *f;
8114 struct image *img;
8116 Lisp_Object file, specified_file;
8117 Lisp_Object specified_data;
8118 int rc, width, height, x, y, i;
8119 XImagePtr ximg;
8120 ColorMapObject *gif_color_map;
8121 unsigned long pixel_colors[256];
8122 GifFileType *gif;
8123 struct gcpro gcpro1;
8124 Lisp_Object image;
8125 int ino, image_height, image_width;
8126 gif_memory_source memsrc;
8127 unsigned char *raster;
8129 specified_file = image_spec_value (img->spec, QCfile, NULL);
8130 specified_data = image_spec_value (img->spec, QCdata, NULL);
8131 file = Qnil;
8132 GCPRO1 (file);
8134 if (NILP (specified_data))
8136 file = x_find_image_file (specified_file);
8137 if (!STRINGP (file))
8139 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8140 UNGCPRO;
8141 return 0;
8144 /* Open the GIF file. Casting return value avoids a GCC warning
8145 on W32. */
8146 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
8147 if (gif == NULL)
8149 image_error ("Cannot open `%s'", file, Qnil);
8150 UNGCPRO;
8151 return 0;
8154 else
8156 /* Read from memory! */
8157 current_gif_memory_src = &memsrc;
8158 memsrc.bytes = SDATA (specified_data);
8159 memsrc.len = SBYTES (specified_data);
8160 memsrc.index = 0;
8162 /* Casting return value avoids a GCC warning on W32. */
8163 gif = (GifFileType *)fn_DGifOpen(&memsrc, gif_read_from_memory);
8164 if (!gif)
8166 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
8167 UNGCPRO;
8168 return 0;
8172 /* Before reading entire contents, check the declared image size. */
8173 if (!check_image_size (f, gif->SWidth, gif->SHeight))
8175 image_error ("Invalid image size", Qnil, Qnil);
8176 fn_DGifCloseFile (gif);
8177 UNGCPRO;
8178 return 0;
8181 /* Read entire contents. */
8182 rc = fn_DGifSlurp (gif);
8183 if (rc == GIF_ERROR)
8185 image_error ("Error reading `%s'", img->spec, Qnil);
8186 fn_DGifCloseFile (gif);
8187 UNGCPRO;
8188 return 0;
8191 image = image_spec_value (img->spec, QCindex, NULL);
8192 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8193 if (ino >= gif->ImageCount)
8195 image_error ("Invalid image number `%s' in image `%s'",
8196 image, img->spec);
8197 fn_DGifCloseFile (gif);
8198 UNGCPRO;
8199 return 0;
8202 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
8203 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
8204 image_height = gif->SavedImages[ino].ImageDesc.Height;
8205 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
8206 image_width = gif->SavedImages[ino].ImageDesc.Width;
8207 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
8209 width = img->width = max (gif->SWidth,
8210 max (gif->Image.Left + gif->Image.Width,
8211 img->corners[RIGHT_CORNER]));
8212 height = img->height = max (gif->SHeight,
8213 max (gif->Image.Top + gif->Image.Height,
8214 img->corners[BOT_CORNER]));
8216 if (!check_image_size (f, width, height))
8218 image_error ("Invalid image size", Qnil, Qnil);
8219 fn_DGifCloseFile (gif);
8220 UNGCPRO;
8221 return 0;
8224 /* Create the X image and pixmap. */
8225 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8227 fn_DGifCloseFile (gif);
8228 UNGCPRO;
8229 return 0;
8232 /* Allocate colors. */
8233 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
8234 if (!gif_color_map)
8235 gif_color_map = gif->SColorMap;
8236 init_color_table ();
8237 bzero (pixel_colors, sizeof pixel_colors);
8239 if (gif_color_map)
8240 for (i = 0; i < gif_color_map->ColorCount; ++i)
8242 int r = gif_color_map->Colors[i].Red << 8;
8243 int g = gif_color_map->Colors[i].Green << 8;
8244 int b = gif_color_map->Colors[i].Blue << 8;
8245 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
8248 #ifdef COLOR_TABLE_SUPPORT
8249 img->colors = colors_in_color_table (&img->ncolors);
8250 free_color_table ();
8251 #endif /* COLOR_TABLE_SUPPORT */
8253 /* Clear the part of the screen image that are not covered by
8254 the image from the GIF file. Full animated GIF support
8255 requires more than can be done here (see the gif89 spec,
8256 disposal methods). Let's simply assume that the part
8257 not covered by a sub-image is in the frame's background color. */
8258 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
8259 for (x = 0; x < width; ++x)
8260 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8262 for (y = img->corners[BOT_CORNER]; y < height; ++y)
8263 for (x = 0; x < width; ++x)
8264 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8266 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
8268 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
8269 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8270 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
8271 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8274 /* Read the GIF image into the X image. We use a local variable
8275 `raster' here because RasterBits below is a char *, and invites
8276 problems with bytes >= 0x80. */
8277 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
8279 if (gif->SavedImages[ino].ImageDesc.Interlace)
8281 int pass;
8282 int row = interlace_start[0];
8284 pass = 0;
8286 for (y = 0; y < image_height; y++)
8288 if (row >= image_height)
8290 row = interlace_start[++pass];
8291 while (row >= image_height)
8292 row = interlace_start[++pass];
8295 for (x = 0; x < image_width; x++)
8297 int i = raster[(y * image_width) + x];
8298 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
8299 row + img->corners[TOP_CORNER], pixel_colors[i]);
8302 row += interlace_increment[pass];
8305 else
8307 for (y = 0; y < image_height; ++y)
8308 for (x = 0; x < image_width; ++x)
8310 int i = raster[y * image_width + x];
8311 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
8312 y + img->corners[TOP_CORNER], pixel_colors[i]);
8316 /* Save GIF image extension data for `image-extension-data'.
8317 Format is (count IMAGES FUNCTION "BYTES" ...). */
8318 img->data.lisp_val = Qnil;
8319 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
8321 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
8322 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
8323 /* Append (... FUNCTION "BYTES") */
8324 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
8325 Fcons (make_number (ext->Function),
8326 img->data.lisp_val));
8327 img->data.lisp_val = Fnreverse (img->data.lisp_val);
8329 if (gif->ImageCount > 1)
8330 img->data.lisp_val = Fcons (Qcount,
8331 Fcons (make_number (gif->ImageCount),
8332 img->data.lisp_val));
8334 fn_DGifCloseFile (gif);
8336 /* Maybe fill in the background field while we have ximg handy. */
8337 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8338 /* Casting avoids a GCC warning. */
8339 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8341 /* Put the image into the pixmap, then free the X image and its buffer. */
8342 x_put_x_image (f, ximg, img->pixmap, width, height);
8343 x_destroy_x_image (ximg);
8345 UNGCPRO;
8346 return 1;
8349 #else /* !HAVE_GIF */
8351 #ifdef MAC_OS
8352 static int
8353 gif_load (f, img)
8354 struct frame *f;
8355 struct image *img;
8357 #if USE_MAC_IMAGE_IO
8358 return image_load_image_io (f, img, kUTTypeGIF);
8359 #else /* !USE_MAC_IMAGE_IO */
8360 Lisp_Object specified_file, file;
8361 Lisp_Object specified_data;
8362 OSErr err;
8363 Boolean graphic_p, movie_p, prefer_graphic_p;
8364 Handle dh = NULL;
8365 Movie movie = NULL;
8366 Lisp_Object image;
8367 Track track = NULL;
8368 Media media = NULL;
8369 long nsamples;
8370 Rect rect;
8371 Lisp_Object specified_bg;
8372 XColor color;
8373 RGBColor bg_color;
8374 int width, height;
8375 XImagePtr ximg;
8376 TimeScale time_scale;
8377 TimeValue time, duration;
8378 int ino;
8379 CGrafPtr old_port;
8380 GDHandle old_gdh;
8382 specified_file = image_spec_value (img->spec, QCfile, NULL);
8383 specified_data = image_spec_value (img->spec, QCdata, NULL);
8385 /* Animated gifs use QuickTime Movie Toolbox. So initialize it here. */
8386 EnterMovies ();
8388 if (NILP (specified_data))
8390 /* Read from a file */
8391 FSSpec fss;
8392 short refnum;
8394 err = find_image_fsspec (specified_file, &file, &fss);
8395 if (err != noErr)
8397 if (err == fnfErr)
8398 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8399 else
8400 goto open_error;
8403 err = CanQuickTimeOpenFile (&fss, kQTFileTypeGIF, 0,
8404 &graphic_p, &movie_p, &prefer_graphic_p, 0);
8405 if (err != noErr)
8406 goto open_error;
8408 if (!graphic_p && !movie_p)
8409 goto open_error;
8410 if (prefer_graphic_p)
8411 return image_load_qt_1 (f, img, kQTFileTypeGIF, &fss, NULL);
8412 err = OpenMovieFile (&fss, &refnum, fsRdPerm);
8413 if (err != noErr)
8414 goto open_error;
8415 err = NewMovieFromFile (&movie, refnum, NULL, NULL, 0, NULL);
8416 CloseMovieFile (refnum);
8417 if (err != noErr)
8419 image_error ("Error reading `%s'", file, Qnil);
8420 return 0;
8423 else
8425 /* Memory source! */
8426 Handle dref = NULL;
8427 long file_type_atom[3];
8429 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
8430 if (err != noErr)
8432 image_error ("Cannot allocate data handle for `%s'",
8433 img->spec, Qnil);
8434 goto error;
8437 file_type_atom[0] = EndianU32_NtoB (sizeof (long) * 3);
8438 file_type_atom[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
8439 file_type_atom[2] = EndianU32_NtoB (kQTFileTypeGIF);
8440 err = PtrToHand (&dh, &dref, sizeof (Handle));
8441 if (err == noErr)
8442 /* no file name */
8443 err = PtrAndHand ("\p", dref, 1);
8444 if (err == noErr)
8445 err = PtrAndHand (file_type_atom, dref, sizeof (long) * 3);
8446 if (err != noErr)
8448 image_error ("Cannot allocate handle data ref for `%s'", img->spec, Qnil);
8449 goto error;
8451 err = CanQuickTimeOpenDataRef (dref, HandleDataHandlerSubType, &graphic_p,
8452 &movie_p, &prefer_graphic_p, 0);
8453 if (err != noErr)
8454 goto open_error;
8456 if (!graphic_p && !movie_p)
8457 goto open_error;
8458 if (prefer_graphic_p)
8460 int success_p;
8462 DisposeHandle (dref);
8463 success_p = image_load_qt_1 (f, img, kQTFileTypeGIF, NULL, dh);
8464 DisposeHandle (dh);
8465 return success_p;
8467 err = NewMovieFromDataRef (&movie, 0, NULL, dref,
8468 HandleDataHandlerSubType);
8469 DisposeHandle (dref);
8470 if (err != noErr)
8471 goto open_error;
8474 image = image_spec_value (img->spec, QCindex, NULL);
8475 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8476 track = GetMovieIndTrack (movie, 1);
8477 media = GetTrackMedia (track);
8478 nsamples = GetMediaSampleCount (media);
8479 if (ino >= nsamples)
8481 image_error ("Invalid image number `%s' in image `%s'",
8482 image, img->spec);
8483 goto error;
8485 time_scale = GetMediaTimeScale (media);
8487 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8488 if (!STRINGP (specified_bg)
8489 || !mac_defined_color (f, SDATA (specified_bg), &color, 0))
8491 color.pixel = FRAME_BACKGROUND_PIXEL (f);
8492 color.red = RED16_FROM_ULONG (color.pixel);
8493 color.green = GREEN16_FROM_ULONG (color.pixel);
8494 color.blue = BLUE16_FROM_ULONG (color.pixel);
8496 GetMovieBox (movie, &rect);
8497 width = img->width = rect.right - rect.left;
8498 height = img->height = rect.bottom - rect.top;
8499 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8500 goto error;
8502 GetGWorld (&old_port, &old_gdh);
8503 SetGWorld (ximg, NULL);
8504 bg_color.red = color.red;
8505 bg_color.green = color.green;
8506 bg_color.blue = color.blue;
8507 RGBBackColor (&bg_color);
8508 SetGWorld (old_port, old_gdh);
8509 SetMovieActive (movie, 1);
8510 SetMovieGWorld (movie, ximg, NULL);
8511 SampleNumToMediaTime (media, ino + 1, &time, &duration);
8512 SetMovieTimeValue (movie, time);
8513 MoviesTask (movie, 0L);
8514 DisposeTrackMedia (media);
8515 DisposeMovieTrack (track);
8516 DisposeMovie (movie);
8517 if (dh)
8518 DisposeHandle (dh);
8520 /* Save GIF image extension data for `image-extension-data'.
8521 Format is (count IMAGES 0xf9 GRAPHIC_CONTROL_EXTENSION_BLOCK). */
8523 Lisp_Object gce = make_uninit_string (4);
8524 int centisec = ((float)duration / time_scale) * 100.0f + 0.5f;
8526 /* Fill the delay time field. */
8527 SSET (gce, 1, centisec & 0xff);
8528 SSET (gce, 2, (centisec >> 8) & 0xff);
8529 /* We don't know about other fields. */
8530 SSET (gce, 0, 0);
8531 SSET (gce, 3, 0);
8533 img->data.lisp_val = list4 (Qcount, make_number (nsamples),
8534 make_number (0xf9), gce);
8537 /* Maybe fill in the background field while we have ximg handy. */
8538 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8539 IMAGE_BACKGROUND (img, f, ximg);
8541 /* Put the image into the pixmap. */
8542 x_put_x_image (f, ximg, img->pixmap, width, height);
8543 x_destroy_x_image (ximg);
8544 return 1;
8546 open_error:
8547 image_error ("Cannot open `%s'", file, Qnil);
8548 error:
8549 if (media)
8550 DisposeTrackMedia (media);
8551 if (track)
8552 DisposeMovieTrack (track);
8553 if (movie)
8554 DisposeMovie (movie);
8555 if (dh)
8556 DisposeHandle (dh);
8557 return 0;
8558 #endif /* !USE_MAC_IMAGE_IO */
8560 #endif /* MAC_OS */
8562 #endif /* HAVE_GIF */
8566 /***********************************************************************
8567 Ghostscript
8568 ***********************************************************************/
8570 #ifdef HAVE_X_WINDOWS
8571 #define HAVE_GHOSTSCRIPT 1
8572 #endif /* HAVE_X_WINDOWS */
8574 /* The symbol `postscript' identifying images of this type. */
8576 Lisp_Object Qpostscript;
8578 #ifdef HAVE_GHOSTSCRIPT
8580 static int gs_image_p P_ ((Lisp_Object object));
8581 static int gs_load P_ ((struct frame *f, struct image *img));
8582 static void gs_clear_image P_ ((struct frame *f, struct image *img));
8584 /* Keyword symbols. */
8586 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8588 /* Indices of image specification fields in gs_format, below. */
8590 enum gs_keyword_index
8592 GS_TYPE,
8593 GS_PT_WIDTH,
8594 GS_PT_HEIGHT,
8595 GS_FILE,
8596 GS_LOADER,
8597 GS_BOUNDING_BOX,
8598 GS_ASCENT,
8599 GS_MARGIN,
8600 GS_RELIEF,
8601 GS_ALGORITHM,
8602 GS_HEURISTIC_MASK,
8603 GS_MASK,
8604 GS_BACKGROUND,
8605 GS_LAST
8608 /* Vector of image_keyword structures describing the format
8609 of valid user-defined image specifications. */
8611 static struct image_keyword gs_format[GS_LAST] =
8613 {":type", IMAGE_SYMBOL_VALUE, 1},
8614 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8615 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8616 {":file", IMAGE_STRING_VALUE, 1},
8617 {":loader", IMAGE_FUNCTION_VALUE, 0},
8618 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8619 {":ascent", IMAGE_ASCENT_VALUE, 0},
8620 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8621 {":relief", IMAGE_INTEGER_VALUE, 0},
8622 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8623 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8624 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8625 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8628 /* Structure describing the image type `ghostscript'. */
8630 static struct image_type gs_type =
8632 &Qpostscript,
8633 gs_image_p,
8634 gs_load,
8635 gs_clear_image,
8636 NULL
8640 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8642 static void
8643 gs_clear_image (f, img)
8644 struct frame *f;
8645 struct image *img;
8647 /* IMG->data.ptr_val may contain a recorded colormap. */
8648 xfree (img->data.ptr_val);
8649 x_clear_image (f, img);
8653 /* Return non-zero if OBJECT is a valid Ghostscript image
8654 specification. */
8656 static int
8657 gs_image_p (object)
8658 Lisp_Object object;
8660 struct image_keyword fmt[GS_LAST];
8661 Lisp_Object tem;
8662 int i;
8664 bcopy (gs_format, fmt, sizeof fmt);
8666 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8667 return 0;
8669 /* Bounding box must be a list or vector containing 4 integers. */
8670 tem = fmt[GS_BOUNDING_BOX].value;
8671 if (CONSP (tem))
8673 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8674 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8675 return 0;
8676 if (!NILP (tem))
8677 return 0;
8679 else if (VECTORP (tem))
8681 if (XVECTOR (tem)->size != 4)
8682 return 0;
8683 for (i = 0; i < 4; ++i)
8684 if (!INTEGERP (XVECTOR (tem)->contents[i]))
8685 return 0;
8687 else
8688 return 0;
8690 return 1;
8694 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8695 if successful. */
8697 static int
8698 gs_load (f, img)
8699 struct frame *f;
8700 struct image *img;
8702 char buffer[100];
8703 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8704 struct gcpro gcpro1, gcpro2;
8705 Lisp_Object frame;
8706 double in_width, in_height;
8707 Lisp_Object pixel_colors = Qnil;
8709 /* Compute pixel size of pixmap needed from the given size in the
8710 image specification. Sizes in the specification are in pt. 1 pt
8711 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8712 info. */
8713 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8714 in_width = XFASTINT (pt_width) / 72.0;
8715 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
8716 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8717 in_height = XFASTINT (pt_height) / 72.0;
8718 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
8720 if (!check_image_size (f, img->width, img->height))
8722 image_error ("Invalid image size", Qnil, Qnil);
8723 return 0;
8726 /* Create the pixmap. */
8727 xassert (img->pixmap == NO_PIXMAP);
8729 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8730 BLOCK_INPUT;
8731 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8732 img->width, img->height,
8733 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8734 UNBLOCK_INPUT;
8736 if (!img->pixmap)
8738 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8739 return 0;
8742 /* Call the loader to fill the pixmap. It returns a process object
8743 if successful. We do not record_unwind_protect here because
8744 other places in redisplay like calling window scroll functions
8745 don't either. Let the Lisp loader use `unwind-protect' instead. */
8746 GCPRO2 (window_and_pixmap_id, pixel_colors);
8748 sprintf (buffer, "%lu %lu",
8749 (unsigned long) FRAME_X_WINDOW (f),
8750 (unsigned long) img->pixmap);
8751 window_and_pixmap_id = build_string (buffer);
8753 sprintf (buffer, "%lu %lu",
8754 FRAME_FOREGROUND_PIXEL (f),
8755 FRAME_BACKGROUND_PIXEL (f));
8756 pixel_colors = build_string (buffer);
8758 XSETFRAME (frame, f);
8759 loader = image_spec_value (img->spec, QCloader, NULL);
8760 if (NILP (loader))
8761 loader = intern ("gs-load-image");
8763 img->data.lisp_val = call6 (loader, frame, img->spec,
8764 make_number (img->width),
8765 make_number (img->height),
8766 window_and_pixmap_id,
8767 pixel_colors);
8768 UNGCPRO;
8769 return PROCESSP (img->data.lisp_val);
8773 /* Kill the Ghostscript process that was started to fill PIXMAP on
8774 frame F. Called from XTread_socket when receiving an event
8775 telling Emacs that Ghostscript has finished drawing. */
8777 void
8778 x_kill_gs_process (pixmap, f)
8779 Pixmap pixmap;
8780 struct frame *f;
8782 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8783 int class, i;
8784 struct image *img;
8786 /* Find the image containing PIXMAP. */
8787 for (i = 0; i < c->used; ++i)
8788 if (c->images[i]->pixmap == pixmap)
8789 break;
8791 /* Should someone in between have cleared the image cache, for
8792 instance, give up. */
8793 if (i == c->used)
8794 return;
8796 /* Kill the GS process. We should have found PIXMAP in the image
8797 cache and its image should contain a process object. */
8798 img = c->images[i];
8799 xassert (PROCESSP (img->data.lisp_val));
8800 Fkill_process (img->data.lisp_val, Qnil);
8801 img->data.lisp_val = Qnil;
8803 #if defined (HAVE_X_WINDOWS)
8805 /* On displays with a mutable colormap, figure out the colors
8806 allocated for the image by looking at the pixels of an XImage for
8807 img->pixmap. */
8808 class = FRAME_X_VISUAL (f)->class;
8809 if (class != StaticColor && class != StaticGray && class != TrueColor)
8811 XImagePtr ximg;
8813 BLOCK_INPUT;
8815 /* Try to get an XImage for img->pixmep. */
8816 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8817 0, 0, img->width, img->height, ~0, ZPixmap);
8818 if (ximg)
8820 int x, y;
8822 /* Initialize the color table. */
8823 init_color_table ();
8825 /* For each pixel of the image, look its color up in the
8826 color table. After having done so, the color table will
8827 contain an entry for each color used by the image. */
8828 for (y = 0; y < img->height; ++y)
8829 for (x = 0; x < img->width; ++x)
8831 unsigned long pixel = XGetPixel (ximg, x, y);
8832 lookup_pixel_color (f, pixel);
8835 /* Record colors in the image. Free color table and XImage. */
8836 #ifdef COLOR_TABLE_SUPPORT
8837 img->colors = colors_in_color_table (&img->ncolors);
8838 free_color_table ();
8839 #endif
8840 XDestroyImage (ximg);
8842 #if 0 /* This doesn't seem to be the case. If we free the colors
8843 here, we get a BadAccess later in x_clear_image when
8844 freeing the colors. */
8845 /* We have allocated colors once, but Ghostscript has also
8846 allocated colors on behalf of us. So, to get the
8847 reference counts right, free them once. */
8848 if (img->ncolors)
8849 x_free_colors (f, img->colors, img->ncolors);
8850 #endif
8852 else
8853 image_error ("Cannot get X image of `%s'; colors will not be freed",
8854 img->spec, Qnil);
8856 UNBLOCK_INPUT;
8858 #endif /* HAVE_X_WINDOWS */
8860 /* Now that we have the pixmap, compute mask and transform the
8861 image if requested. */
8862 BLOCK_INPUT;
8863 postprocess_image (f, img);
8864 UNBLOCK_INPUT;
8867 #endif /* HAVE_GHOSTSCRIPT */
8870 /***********************************************************************
8871 Tests
8872 ***********************************************************************/
8874 #if GLYPH_DEBUG
8876 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8877 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8878 (spec)
8879 Lisp_Object spec;
8881 return valid_image_p (spec) ? Qt : Qnil;
8885 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8886 (spec)
8887 Lisp_Object spec;
8889 int id = -1;
8891 if (valid_image_p (spec))
8892 id = lookup_image (SELECTED_FRAME (), spec);
8894 debug_print (spec);
8895 return make_number (id);
8898 #endif /* GLYPH_DEBUG != 0 */
8901 /***********************************************************************
8902 Initialization
8903 ***********************************************************************/
8905 #ifdef HAVE_NTGUI
8906 /* Image types that rely on external libraries are loaded dynamically
8907 if the library is available. */
8908 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8909 define_image_type (image_type, init_lib_fn (libraries))
8910 #else
8911 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8912 define_image_type (image_type, 1)
8913 #endif /* HAVE_NTGUI */
8915 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8916 doc: /* Initialize image library implementing image type TYPE.
8917 Return non-nil if TYPE is a supported image type.
8919 Image types pbm and xbm are prebuilt; other types are loaded here.
8920 Libraries to load are specified in alist LIBRARIES (usually, the value
8921 of `image-library-alist', which see). */)
8922 (type, libraries)
8923 Lisp_Object type, libraries;
8925 Lisp_Object tested;
8927 /* Don't try to reload the library. */
8928 tested = Fassq (type, Vimage_type_cache);
8929 if (CONSP (tested))
8930 return XCDR (tested);
8932 #if defined (HAVE_XPM) || defined (MAC_OS)
8933 if (EQ (type, Qxpm))
8934 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8935 #endif
8937 #if defined (HAVE_JPEG) || defined (MAC_OS)
8938 if (EQ (type, Qjpeg))
8939 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8940 #endif
8942 #if defined (HAVE_TIFF) || defined (MAC_OS)
8943 if (EQ (type, Qtiff))
8944 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8945 #endif
8947 #if defined (HAVE_GIF) || defined (MAC_OS)
8948 if (EQ (type, Qgif))
8949 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8950 #endif
8952 #if defined (HAVE_PNG) || defined (MAC_OS)
8953 if (EQ (type, Qpng))
8954 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8955 #endif
8957 #ifdef HAVE_GHOSTSCRIPT
8958 if (EQ (type, Qpostscript))
8959 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8960 #endif
8962 /* If the type is not recognized, avoid testing it ever again. */
8963 CACHE_IMAGE_TYPE (type, Qnil);
8964 return Qnil;
8967 void
8968 syms_of_image ()
8970 extern Lisp_Object Qrisky_local_variable; /* Syms_of_xdisp has already run. */
8972 /* Initialize this only once, since that's what we do with Vimage_types
8973 and they are supposed to be in sync. Initializing here gives correct
8974 operation on GNU/Linux of calling dump-emacs after loading some images. */
8975 image_types = NULL;
8977 /* Must be defined now becase we're going to update it below, while
8978 defining the supported image types. */
8979 DEFVAR_LISP ("image-types", &Vimage_types,
8980 doc: /* List of potentially supported image types.
8981 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8982 To check whether it is really supported, use `image-type-available-p'. */);
8983 Vimage_types = Qnil;
8985 DEFVAR_LISP ("image-library-alist", &Vimage_library_alist,
8986 doc: /* Alist of image types vs external libraries needed to display them.
8988 Each element is a list (IMAGE-TYPE LIBRARY...), where the car is a symbol
8989 representing a supported image type, and the rest are strings giving
8990 alternate filenames for the corresponding external libraries.
8992 Emacs tries to load the libraries in the order they appear on the
8993 list; if none is loaded, the running session of Emacs won't
8994 support the image type. Types 'pbm and 'xbm don't need to be
8995 listed; they are always supported. */);
8996 Vimage_library_alist = Qnil;
8997 Fput (intern ("image-library-alist"), Qrisky_local_variable, Qt);
8999 DEFVAR_LISP ("max-image-size", &Vmax_image_size,
9000 doc: /* Maximum size of images.
9001 Emacs will not load an image into memory if its pixel width or
9002 pixel height exceeds this limit.
9004 If the value is an integer, it directly specifies the maximum
9005 image height and width, measured in pixels. If it is a floating
9006 point number, it specifies the maximum image height and width
9007 as a ratio to the frame height and width. If the value is
9008 non-numeric, there is no explicit limit on the size of images. */);
9009 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9011 Vimage_type_cache = Qnil;
9012 staticpro (&Vimage_type_cache);
9014 Qpbm = intern ("pbm");
9015 staticpro (&Qpbm);
9016 ADD_IMAGE_TYPE(Qpbm);
9018 Qxbm = intern ("xbm");
9019 staticpro (&Qxbm);
9020 ADD_IMAGE_TYPE(Qxbm);
9022 define_image_type (&xbm_type, 1);
9023 define_image_type (&pbm_type, 1);
9025 QCascent = intern (":ascent");
9026 staticpro (&QCascent);
9027 QCmargin = intern (":margin");
9028 staticpro (&QCmargin);
9029 QCrelief = intern (":relief");
9030 staticpro (&QCrelief);
9031 QCconversion = intern (":conversion");
9032 staticpro (&QCconversion);
9033 QCcolor_symbols = intern (":color-symbols");
9034 staticpro (&QCcolor_symbols);
9035 QCheuristic_mask = intern (":heuristic-mask");
9036 staticpro (&QCheuristic_mask);
9037 QCindex = intern (":index");
9038 staticpro (&QCindex);
9039 QCmatrix = intern (":matrix");
9040 staticpro (&QCmatrix);
9041 QCcolor_adjustment = intern (":color-adjustment");
9042 staticpro (&QCcolor_adjustment);
9043 QCmask = intern (":mask");
9044 staticpro (&QCmask);
9046 Qlaplace = intern ("laplace");
9047 staticpro (&Qlaplace);
9048 Qemboss = intern ("emboss");
9049 staticpro (&Qemboss);
9050 Qedge_detection = intern ("edge-detection");
9051 staticpro (&Qedge_detection);
9052 Qheuristic = intern ("heuristic");
9053 staticpro (&Qheuristic);
9055 Qpostscript = intern ("postscript");
9056 staticpro (&Qpostscript);
9057 #ifdef HAVE_GHOSTSCRIPT
9058 ADD_IMAGE_TYPE(Qpostscript);
9059 QCloader = intern (":loader");
9060 staticpro (&QCloader);
9061 QCbounding_box = intern (":bounding-box");
9062 staticpro (&QCbounding_box);
9063 QCpt_width = intern (":pt-width");
9064 staticpro (&QCpt_width);
9065 QCpt_height = intern (":pt-height");
9066 staticpro (&QCpt_height);
9067 #endif /* HAVE_GHOSTSCRIPT */
9069 #if defined (HAVE_XPM) || defined (MAC_OS)
9070 Qxpm = intern ("xpm");
9071 staticpro (&Qxpm);
9072 ADD_IMAGE_TYPE(Qxpm);
9073 #endif
9075 #if defined (HAVE_JPEG) || defined (MAC_OS)
9076 Qjpeg = intern ("jpeg");
9077 staticpro (&Qjpeg);
9078 ADD_IMAGE_TYPE(Qjpeg);
9079 #endif
9081 #if defined (HAVE_TIFF) || defined (MAC_OS)
9082 Qtiff = intern ("tiff");
9083 staticpro (&Qtiff);
9084 ADD_IMAGE_TYPE(Qtiff);
9085 #endif
9087 #if defined (HAVE_GIF) || defined (MAC_OS)
9088 Qgif = intern ("gif");
9089 staticpro (&Qgif);
9090 ADD_IMAGE_TYPE(Qgif);
9091 #endif
9093 #if defined (HAVE_PNG) || defined (MAC_OS)
9094 Qpng = intern ("png");
9095 staticpro (&Qpng);
9096 ADD_IMAGE_TYPE(Qpng);
9097 #endif
9099 defsubr (&Sinit_image_library);
9100 defsubr (&Sclear_image_cache);
9101 defsubr (&Simage_refresh);
9102 defsubr (&Simage_size);
9103 defsubr (&Simage_mask_p);
9104 defsubr (&Simage_extension_data);
9106 #if GLYPH_DEBUG
9107 defsubr (&Simagep);
9108 defsubr (&Slookup_image);
9109 #endif
9111 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
9112 doc: /* Non-nil means always draw a cross over disabled images.
9113 Disabled images are those having a `:conversion disabled' property.
9114 A cross is always drawn on black & white displays. */);
9115 cross_disabled_images = 0;
9117 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
9118 doc: /* List of directories to search for window system bitmap files. */);
9119 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
9121 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
9122 doc: /* Time after which cached images are removed from the cache.
9123 When an image has not been displayed this many seconds, remove it
9124 from the image cache. Value must be an integer or nil with nil
9125 meaning don't clear the cache. */);
9126 Vimage_cache_eviction_delay = make_number (30 * 60);
9129 void
9130 init_image ()
9134 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
9135 (do not change this comment) */