(Foverlay_buffer): Add EXFUN.
[emacs.git] / src / image.c
blobf2dc1ae30ca47b2c7c80238fae057417ac6c1744
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 struct png_memory_storage tbr; /* Data to be read */
6522 /* Find out what file to load. */
6523 specified_file = image_spec_value (img->spec, QCfile, NULL);
6524 specified_data = image_spec_value (img->spec, QCdata, NULL);
6525 file = Qnil;
6526 GCPRO1 (file);
6528 if (NILP (specified_data))
6530 file = x_find_image_file (specified_file);
6531 if (!STRINGP (file))
6533 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6534 UNGCPRO;
6535 return 0;
6538 /* Open the image file. */
6539 fp = fopen (SDATA (file), "rb");
6540 if (!fp)
6542 image_error ("Cannot open image file `%s'", file, Qnil);
6543 UNGCPRO;
6544 return 0;
6547 /* Check PNG signature. */
6548 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
6549 || !fn_png_check_sig (sig, sizeof sig))
6551 image_error ("Not a PNG file: `%s'", file, Qnil);
6552 UNGCPRO;
6553 fclose (fp);
6554 return 0;
6557 else
6559 /* Read from memory. */
6560 tbr.bytes = SDATA (specified_data);
6561 tbr.len = SBYTES (specified_data);
6562 tbr.index = 0;
6564 /* Check PNG signature. */
6565 if (tbr.len < sizeof sig
6566 || !fn_png_check_sig (tbr.bytes, sizeof sig))
6568 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
6569 UNGCPRO;
6570 return 0;
6573 /* Need to skip past the signature. */
6574 tbr.bytes += sizeof (sig);
6577 /* Initialize read and info structs for PNG lib. Casting return
6578 value avoids a GCC warning on W32. */
6579 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
6580 NULL, my_png_error,
6581 my_png_warning);
6582 if (!png_ptr)
6584 if (fp) fclose (fp);
6585 UNGCPRO;
6586 return 0;
6589 /* Casting return value avoids a GCC warning on W32. */
6590 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
6591 if (!info_ptr)
6593 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
6594 if (fp) fclose (fp);
6595 UNGCPRO;
6596 return 0;
6599 /* Casting return value avoids a GCC warning on W32. */
6600 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
6601 if (!end_info)
6603 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
6604 if (fp) fclose (fp);
6605 UNGCPRO;
6606 return 0;
6609 /* Set error jump-back. We come back here when the PNG library
6610 detects an error. */
6611 if (setjmp (png_ptr->jmpbuf))
6613 error:
6614 if (png_ptr)
6615 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6616 xfree (pixels);
6617 xfree (rows);
6618 if (fp) fclose (fp);
6619 UNGCPRO;
6620 return 0;
6623 /* Read image info. */
6624 if (!NILP (specified_data))
6625 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
6626 else
6627 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
6629 fn_png_set_sig_bytes (png_ptr, sizeof sig);
6630 fn_png_read_info (png_ptr, info_ptr);
6631 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6632 &interlace_type, NULL, NULL);
6634 if (!check_image_size (f, width, height))
6635 goto error;
6637 /* If image contains simply transparency data, we prefer to
6638 construct a clipping mask. */
6639 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6640 transparent_p = 1;
6641 else
6642 transparent_p = 0;
6644 /* This function is easier to write if we only have to handle
6645 one data format: RGB or RGBA with 8 bits per channel. Let's
6646 transform other formats into that format. */
6648 /* Strip more than 8 bits per channel. */
6649 if (bit_depth == 16)
6650 fn_png_set_strip_16 (png_ptr);
6652 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6653 if available. */
6654 fn_png_set_expand (png_ptr);
6656 /* Convert grayscale images to RGB. */
6657 if (color_type == PNG_COLOR_TYPE_GRAY
6658 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6659 fn_png_set_gray_to_rgb (png_ptr);
6661 /* Handle alpha channel by combining the image with a background
6662 color. Do this only if a real alpha channel is supplied. For
6663 simple transparency, we prefer a clipping mask. */
6664 if (!transparent_p)
6666 png_color_16 *image_bg;
6667 Lisp_Object specified_bg
6668 = image_spec_value (img->spec, QCbackground, NULL);
6669 int shift = (bit_depth == 16) ? 0 : 8;
6671 if (STRINGP (specified_bg))
6672 /* The user specified `:background', use that. */
6674 /* W32 version incorrectly used COLORREF here!! ++kfs */
6675 XColor color;
6676 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
6678 png_color_16 user_bg;
6680 bzero (&user_bg, sizeof user_bg);
6681 user_bg.red = color.red >> shift;
6682 user_bg.green = color.green >> shift;
6683 user_bg.blue = color.blue >> shift;
6685 fn_png_set_background (png_ptr, &user_bg,
6686 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6689 else
6691 /* We use the current frame background, ignoring any default
6692 background color set by the image. */
6693 #ifdef HAVE_X_WINDOWS
6694 XColor color;
6695 png_color_16 frame_background;
6697 color.pixel = FRAME_BACKGROUND_PIXEL (f);
6698 x_query_color (f, &color);
6700 bzero (&frame_background, sizeof frame_background);
6701 frame_background.red = color.red >> shift;
6702 frame_background.green = color.green >> shift;
6703 frame_background.blue = color.blue >> shift;
6704 #endif /* HAVE_X_WINDOWS */
6706 #ifdef HAVE_NTGUI
6707 COLORREF color;
6708 png_color_16 frame_background;
6709 color = FRAME_BACKGROUND_PIXEL (f);
6710 #if 0 /* W32 TODO : Colormap support. */
6711 x_query_color (f, &color);
6712 #endif
6713 bzero (&frame_background, sizeof frame_background);
6714 frame_background.red = GetRValue (color);
6715 frame_background.green = GetGValue (color);
6716 frame_background.blue = GetBValue (color);
6717 #endif /* HAVE_NTGUI */
6719 #ifdef MAC_OS
6720 unsigned long color;
6721 png_color_16 frame_background;
6722 color = FRAME_BACKGROUND_PIXEL (f);
6723 #if 0 /* MAC/W32 TODO : Colormap support. */
6724 x_query_color (f, &color);
6725 #endif
6726 bzero (&frame_background, sizeof frame_background);
6727 frame_background.red = RED_FROM_ULONG (color);
6728 frame_background.green = GREEN_FROM_ULONG (color);
6729 frame_background.blue = BLUE_FROM_ULONG (color);
6730 #endif /* MAC_OS */
6732 fn_png_set_background (png_ptr, &frame_background,
6733 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6737 /* Update info structure. */
6738 fn_png_read_update_info (png_ptr, info_ptr);
6740 /* Get number of channels. Valid values are 1 for grayscale images
6741 and images with a palette, 2 for grayscale images with transparency
6742 information (alpha channel), 3 for RGB images, and 4 for RGB
6743 images with alpha channel, i.e. RGBA. If conversions above were
6744 sufficient we should only have 3 or 4 channels here. */
6745 channels = fn_png_get_channels (png_ptr, info_ptr);
6746 xassert (channels == 3 || channels == 4);
6748 /* Number of bytes needed for one row of the image. */
6749 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
6751 /* Allocate memory for the image. */
6752 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
6753 rows = (png_byte **) xmalloc (height * sizeof *rows);
6754 for (i = 0; i < height; ++i)
6755 rows[i] = pixels + i * row_bytes;
6757 /* Read the entire image. */
6758 fn_png_read_image (png_ptr, rows);
6759 fn_png_read_end (png_ptr, info_ptr);
6760 if (fp)
6762 fclose (fp);
6763 fp = NULL;
6766 /* Create the X image and pixmap. */
6767 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
6768 &img->pixmap))
6769 goto error;
6771 /* Create an image and pixmap serving as mask if the PNG image
6772 contains an alpha channel. */
6773 if (channels == 4
6774 && !transparent_p
6775 && !x_create_x_image_and_pixmap (f, width, height, 1,
6776 &mask_img, &img->mask))
6778 x_destroy_x_image (ximg);
6779 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
6780 img->pixmap = NO_PIXMAP;
6781 goto error;
6784 /* Fill the X image and mask from PNG data. */
6785 init_color_table ();
6787 for (y = 0; y < height; ++y)
6789 png_byte *p = rows[y];
6791 for (x = 0; x < width; ++x)
6793 unsigned r, g, b;
6795 r = *p++ << 8;
6796 g = *p++ << 8;
6797 b = *p++ << 8;
6798 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6799 /* An alpha channel, aka mask channel, associates variable
6800 transparency with an image. Where other image formats
6801 support binary transparency---fully transparent or fully
6802 opaque---PNG allows up to 254 levels of partial transparency.
6803 The PNG library implements partial transparency by combining
6804 the image with a specified background color.
6806 I'm not sure how to handle this here nicely: because the
6807 background on which the image is displayed may change, for
6808 real alpha channel support, it would be necessary to create
6809 a new image for each possible background.
6811 What I'm doing now is that a mask is created if we have
6812 boolean transparency information. Otherwise I'm using
6813 the frame's background color to combine the image with. */
6815 if (channels == 4)
6817 if (mask_img)
6818 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6819 ++p;
6824 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6825 /* Set IMG's background color from the PNG image, unless the user
6826 overrode it. */
6828 png_color_16 *bg;
6829 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6831 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6832 img->background_valid = 1;
6836 #ifdef COLOR_TABLE_SUPPORT
6837 /* Remember colors allocated for this image. */
6838 img->colors = colors_in_color_table (&img->ncolors);
6839 free_color_table ();
6840 #endif /* COLOR_TABLE_SUPPORT */
6842 /* Clean up. */
6843 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6844 xfree (rows);
6845 xfree (pixels);
6847 img->width = width;
6848 img->height = height;
6850 /* Maybe fill in the background field while we have ximg handy.
6851 Casting avoids a GCC warning. */
6852 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6854 /* Put the image into the pixmap, then free the X image and its buffer. */
6855 x_put_x_image (f, ximg, img->pixmap, width, height);
6856 x_destroy_x_image (ximg);
6858 /* Same for the mask. */
6859 if (mask_img)
6861 /* Fill in the background_transparent field while we have the
6862 mask handy. Casting avoids a GCC warning. */
6863 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6865 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
6866 x_destroy_x_image (mask_img);
6869 UNGCPRO;
6870 return 1;
6873 #else /* HAVE_PNG */
6875 #ifdef MAC_OS
6876 static int
6877 png_load (f, img)
6878 struct frame *f;
6879 struct image *img;
6881 #if USE_MAC_IMAGE_IO
6882 return image_load_image_io (f, img, kUTTypePNG);
6883 #elif MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
6884 return image_load_quartz2d (f, img, 1);
6885 #else
6886 return image_load_quicktime (f, img, kQTFileTypePNG);
6887 #endif
6889 #endif /* MAC_OS */
6891 #endif /* !HAVE_PNG */
6895 /***********************************************************************
6896 JPEG
6897 ***********************************************************************/
6899 #if defined (HAVE_JPEG) || defined (MAC_OS)
6901 static int jpeg_image_p P_ ((Lisp_Object object));
6902 static int jpeg_load P_ ((struct frame *f, struct image *img));
6904 /* The symbol `jpeg' identifying images of this type. */
6906 Lisp_Object Qjpeg;
6908 /* Indices of image specification fields in gs_format, below. */
6910 enum jpeg_keyword_index
6912 JPEG_TYPE,
6913 JPEG_DATA,
6914 JPEG_FILE,
6915 JPEG_ASCENT,
6916 JPEG_MARGIN,
6917 JPEG_RELIEF,
6918 JPEG_ALGORITHM,
6919 JPEG_HEURISTIC_MASK,
6920 JPEG_MASK,
6921 JPEG_BACKGROUND,
6922 JPEG_LAST
6925 /* Vector of image_keyword structures describing the format
6926 of valid user-defined image specifications. */
6928 static struct image_keyword jpeg_format[JPEG_LAST] =
6930 {":type", IMAGE_SYMBOL_VALUE, 1},
6931 {":data", IMAGE_STRING_VALUE, 0},
6932 {":file", IMAGE_STRING_VALUE, 0},
6933 {":ascent", IMAGE_ASCENT_VALUE, 0},
6934 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6935 {":relief", IMAGE_INTEGER_VALUE, 0},
6936 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6937 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6938 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6939 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6942 /* Structure describing the image type `jpeg'. */
6944 static struct image_type jpeg_type =
6946 &Qjpeg,
6947 jpeg_image_p,
6948 jpeg_load,
6949 x_clear_image,
6950 NULL
6953 /* Return non-zero if OBJECT is a valid JPEG image specification. */
6955 static int
6956 jpeg_image_p (object)
6957 Lisp_Object object;
6959 struct image_keyword fmt[JPEG_LAST];
6961 bcopy (jpeg_format, fmt, sizeof fmt);
6963 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6964 return 0;
6966 /* Must specify either the :data or :file keyword. */
6967 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6970 #endif /* HAVE_JPEG || MAC_OS */
6972 #ifdef HAVE_JPEG
6974 /* Work around a warning about HAVE_STDLIB_H being redefined in
6975 jconfig.h. */
6976 #ifdef HAVE_STDLIB_H
6977 #define HAVE_STDLIB_H_1
6978 #undef HAVE_STDLIB_H
6979 #endif /* HAVE_STLIB_H */
6981 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
6982 /* In older releases of the jpeg library, jpeglib.h will define boolean
6983 differently depending on __WIN32__, so make sure it is defined. */
6984 #define __WIN32__ 1
6985 #endif
6987 #include <jpeglib.h>
6988 #include <jerror.h>
6989 #include <setjmp.h>
6991 #ifdef HAVE_STLIB_H_1
6992 #define HAVE_STDLIB_H 1
6993 #endif
6995 #ifdef HAVE_NTGUI
6997 /* JPEG library details. */
6998 DEF_IMGLIB_FN (jpeg_CreateDecompress);
6999 DEF_IMGLIB_FN (jpeg_start_decompress);
7000 DEF_IMGLIB_FN (jpeg_finish_decompress);
7001 DEF_IMGLIB_FN (jpeg_destroy_decompress);
7002 DEF_IMGLIB_FN (jpeg_read_header);
7003 DEF_IMGLIB_FN (jpeg_read_scanlines);
7004 DEF_IMGLIB_FN (jpeg_std_error);
7005 DEF_IMGLIB_FN (jpeg_resync_to_restart);
7007 static int
7008 init_jpeg_functions (Lisp_Object libraries)
7010 HMODULE library;
7012 if (!(library = w32_delayed_load (libraries, Qjpeg)))
7013 return 0;
7015 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
7016 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
7017 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
7018 LOAD_IMGLIB_FN (library, jpeg_read_header);
7019 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
7020 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
7021 LOAD_IMGLIB_FN (library, jpeg_std_error);
7022 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
7023 return 1;
7026 /* Wrapper since we can't directly assign the function pointer
7027 to another function pointer that was declared more completely easily. */
7028 static boolean
7029 jpeg_resync_to_restart_wrapper(cinfo, desired)
7030 j_decompress_ptr cinfo;
7031 int desired;
7033 return fn_jpeg_resync_to_restart (cinfo, desired);
7036 #else
7038 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
7039 #define fn_jpeg_start_decompress jpeg_start_decompress
7040 #define fn_jpeg_finish_decompress jpeg_finish_decompress
7041 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
7042 #define fn_jpeg_read_header jpeg_read_header
7043 #define fn_jpeg_read_scanlines jpeg_read_scanlines
7044 #define fn_jpeg_std_error jpeg_std_error
7045 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
7047 #endif /* HAVE_NTGUI */
7049 struct my_jpeg_error_mgr
7051 struct jpeg_error_mgr pub;
7052 jmp_buf setjmp_buffer;
7056 static void
7057 my_error_exit (cinfo)
7058 j_common_ptr cinfo;
7060 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
7061 longjmp (mgr->setjmp_buffer, 1);
7065 /* Init source method for JPEG data source manager. Called by
7066 jpeg_read_header() before any data is actually read. See
7067 libjpeg.doc from the JPEG lib distribution. */
7069 static void
7070 our_common_init_source (cinfo)
7071 j_decompress_ptr cinfo;
7076 /* Method to terminate data source. Called by
7077 jpeg_finish_decompress() after all data has been processed. */
7079 static void
7080 our_common_term_source (cinfo)
7081 j_decompress_ptr cinfo;
7086 /* Fill input buffer method for JPEG data source manager. Called
7087 whenever more data is needed. We read the whole image in one step,
7088 so this only adds a fake end of input marker at the end. */
7090 static JOCTET our_memory_buffer[2];
7092 static boolean
7093 our_memory_fill_input_buffer (cinfo)
7094 j_decompress_ptr cinfo;
7096 /* Insert a fake EOI marker. */
7097 struct jpeg_source_mgr *src = cinfo->src;
7099 our_memory_buffer[0] = (JOCTET) 0xFF;
7100 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
7102 src->next_input_byte = our_memory_buffer;
7103 src->bytes_in_buffer = 2;
7104 return 1;
7108 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
7109 is the JPEG data source manager. */
7111 static void
7112 our_memory_skip_input_data (cinfo, num_bytes)
7113 j_decompress_ptr cinfo;
7114 long num_bytes;
7116 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
7118 if (src)
7120 if (num_bytes > src->bytes_in_buffer)
7121 ERREXIT (cinfo, JERR_INPUT_EOF);
7123 src->bytes_in_buffer -= num_bytes;
7124 src->next_input_byte += num_bytes;
7129 /* Set up the JPEG lib for reading an image from DATA which contains
7130 LEN bytes. CINFO is the decompression info structure created for
7131 reading the image. */
7133 static void
7134 jpeg_memory_src (cinfo, data, len)
7135 j_decompress_ptr cinfo;
7136 JOCTET *data;
7137 unsigned int len;
7139 struct jpeg_source_mgr *src;
7141 if (cinfo->src == NULL)
7143 /* First time for this JPEG object? */
7144 cinfo->src = (struct jpeg_source_mgr *)
7145 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
7146 sizeof (struct jpeg_source_mgr));
7147 src = (struct jpeg_source_mgr *) cinfo->src;
7148 src->next_input_byte = data;
7151 src = (struct jpeg_source_mgr *) cinfo->src;
7152 src->init_source = our_common_init_source;
7153 src->fill_input_buffer = our_memory_fill_input_buffer;
7154 src->skip_input_data = our_memory_skip_input_data;
7155 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
7156 src->term_source = our_common_term_source;
7157 src->bytes_in_buffer = len;
7158 src->next_input_byte = data;
7162 struct jpeg_stdio_mgr
7164 struct jpeg_source_mgr mgr;
7165 boolean finished;
7166 FILE *file;
7167 JOCTET *buffer;
7171 /* Size of buffer to read JPEG from file.
7172 Not too big, as we want to use alloc_small. */
7173 #define JPEG_STDIO_BUFFER_SIZE 8192
7176 /* Fill input buffer method for JPEG data source manager. Called
7177 whenever more data is needed. The data is read from a FILE *. */
7179 static boolean
7180 our_stdio_fill_input_buffer (cinfo)
7181 j_decompress_ptr cinfo;
7183 struct jpeg_stdio_mgr *src;
7185 src = (struct jpeg_stdio_mgr *) cinfo->src;
7186 if (!src->finished)
7188 size_t bytes;
7190 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
7191 if (bytes > 0)
7192 src->mgr.bytes_in_buffer = bytes;
7193 else
7195 WARNMS (cinfo, JWRN_JPEG_EOF);
7196 src->finished = 1;
7197 src->buffer[0] = (JOCTET) 0xFF;
7198 src->buffer[1] = (JOCTET) JPEG_EOI;
7199 src->mgr.bytes_in_buffer = 2;
7201 src->mgr.next_input_byte = src->buffer;
7204 return 1;
7208 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
7209 is the JPEG data source manager. */
7211 static void
7212 our_stdio_skip_input_data (cinfo, num_bytes)
7213 j_decompress_ptr cinfo;
7214 long num_bytes;
7216 struct jpeg_stdio_mgr *src;
7217 src = (struct jpeg_stdio_mgr *) cinfo->src;
7219 while (num_bytes > 0 && !src->finished)
7221 if (num_bytes <= src->mgr.bytes_in_buffer)
7223 src->mgr.bytes_in_buffer -= num_bytes;
7224 src->mgr.next_input_byte += num_bytes;
7225 break;
7227 else
7229 num_bytes -= src->mgr.bytes_in_buffer;
7230 src->mgr.bytes_in_buffer = 0;
7231 src->mgr.next_input_byte = NULL;
7233 our_stdio_fill_input_buffer (cinfo);
7239 /* Set up the JPEG lib for reading an image from a FILE *.
7240 CINFO is the decompression info structure created for
7241 reading the image. */
7243 static void
7244 jpeg_file_src (cinfo, fp)
7245 j_decompress_ptr cinfo;
7246 FILE *fp;
7248 struct jpeg_stdio_mgr *src;
7250 if (cinfo->src != NULL)
7251 src = (struct jpeg_stdio_mgr *) cinfo->src;
7252 else
7254 /* First time for this JPEG object? */
7255 cinfo->src = (struct jpeg_source_mgr *)
7256 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
7257 sizeof (struct jpeg_stdio_mgr));
7258 src = (struct jpeg_stdio_mgr *) cinfo->src;
7259 src->buffer = (JOCTET *)
7260 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
7261 JPEG_STDIO_BUFFER_SIZE);
7264 src->file = fp;
7265 src->finished = 0;
7266 src->mgr.init_source = our_common_init_source;
7267 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
7268 src->mgr.skip_input_data = our_stdio_skip_input_data;
7269 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
7270 src->mgr.term_source = our_common_term_source;
7271 src->mgr.bytes_in_buffer = 0;
7272 src->mgr.next_input_byte = NULL;
7276 /* Load image IMG for use on frame F. Patterned after example.c
7277 from the JPEG lib. */
7279 static int
7280 jpeg_load (f, img)
7281 struct frame *f;
7282 struct image *img;
7284 struct jpeg_decompress_struct cinfo;
7285 struct my_jpeg_error_mgr mgr;
7286 Lisp_Object file, specified_file;
7287 Lisp_Object specified_data;
7288 FILE * volatile fp = NULL;
7289 JSAMPARRAY buffer;
7290 int row_stride, x, y;
7291 XImagePtr ximg = NULL;
7292 int rc;
7293 unsigned long *colors;
7294 int width, height;
7295 struct gcpro gcpro1;
7297 /* Open the JPEG file. */
7298 specified_file = image_spec_value (img->spec, QCfile, NULL);
7299 specified_data = image_spec_value (img->spec, QCdata, NULL);
7300 file = Qnil;
7301 GCPRO1 (file);
7303 if (NILP (specified_data))
7305 file = x_find_image_file (specified_file);
7306 if (!STRINGP (file))
7308 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7309 UNGCPRO;
7310 return 0;
7313 fp = fopen (SDATA (file), "rb");
7314 if (fp == NULL)
7316 image_error ("Cannot open `%s'", file, Qnil);
7317 UNGCPRO;
7318 return 0;
7322 /* Customize libjpeg's error handling to call my_error_exit when an
7323 error is detected. This function will perform a longjmp.
7324 Casting return value avoids a GCC warning on W32. */
7325 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
7326 mgr.pub.error_exit = my_error_exit;
7328 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
7330 if (rc == 1)
7332 /* Called from my_error_exit. Display a JPEG error. */
7333 char buffer[JMSG_LENGTH_MAX];
7334 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
7335 image_error ("Error reading JPEG image `%s': %s", img->spec,
7336 build_string (buffer));
7339 /* Close the input file and destroy the JPEG object. */
7340 if (fp)
7341 fclose ((FILE *) fp);
7342 fn_jpeg_destroy_decompress (&cinfo);
7344 /* If we already have an XImage, free that. */
7345 x_destroy_x_image (ximg);
7347 /* Free pixmap and colors. */
7348 x_clear_image (f, img);
7350 UNGCPRO;
7351 return 0;
7354 /* Create the JPEG decompression object. Let it read from fp.
7355 Read the JPEG image header. */
7356 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
7358 if (NILP (specified_data))
7359 jpeg_file_src (&cinfo, (FILE *) fp);
7360 else
7361 jpeg_memory_src (&cinfo, SDATA (specified_data),
7362 SBYTES (specified_data));
7364 fn_jpeg_read_header (&cinfo, 1);
7366 /* Customize decompression so that color quantization will be used.
7367 Start decompression. */
7368 cinfo.quantize_colors = 1;
7369 fn_jpeg_start_decompress (&cinfo);
7370 width = img->width = cinfo.output_width;
7371 height = img->height = cinfo.output_height;
7373 if (!check_image_size (f, width, height))
7375 image_error ("Invalid image size", Qnil, Qnil);
7376 longjmp (mgr.setjmp_buffer, 2);
7379 /* Create X image and pixmap. */
7380 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7381 longjmp (mgr.setjmp_buffer, 2);
7383 /* Allocate colors. When color quantization is used,
7384 cinfo.actual_number_of_colors has been set with the number of
7385 colors generated, and cinfo.colormap is a two-dimensional array
7386 of color indices in the range 0..cinfo.actual_number_of_colors.
7387 No more than 255 colors will be generated. */
7389 int i, ir, ig, ib;
7391 if (cinfo.out_color_components > 2)
7392 ir = 0, ig = 1, ib = 2;
7393 else if (cinfo.out_color_components > 1)
7394 ir = 0, ig = 1, ib = 0;
7395 else
7396 ir = 0, ig = 0, ib = 0;
7398 /* Use the color table mechanism because it handles colors that
7399 cannot be allocated nicely. Such colors will be replaced with
7400 a default color, and we don't have to care about which colors
7401 can be freed safely, and which can't. */
7402 init_color_table ();
7403 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
7404 * sizeof *colors);
7406 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
7408 /* Multiply RGB values with 255 because X expects RGB values
7409 in the range 0..0xffff. */
7410 int r = cinfo.colormap[ir][i] << 8;
7411 int g = cinfo.colormap[ig][i] << 8;
7412 int b = cinfo.colormap[ib][i] << 8;
7413 colors[i] = lookup_rgb_color (f, r, g, b);
7416 #ifdef COLOR_TABLE_SUPPORT
7417 /* Remember those colors actually allocated. */
7418 img->colors = colors_in_color_table (&img->ncolors);
7419 free_color_table ();
7420 #endif /* COLOR_TABLE_SUPPORT */
7423 /* Read pixels. */
7424 row_stride = width * cinfo.output_components;
7425 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
7426 row_stride, 1);
7427 for (y = 0; y < height; ++y)
7429 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
7430 for (x = 0; x < cinfo.output_width; ++x)
7431 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
7434 /* Clean up. */
7435 fn_jpeg_finish_decompress (&cinfo);
7436 fn_jpeg_destroy_decompress (&cinfo);
7437 if (fp)
7438 fclose ((FILE *) fp);
7440 /* Maybe fill in the background field while we have ximg handy. */
7441 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7442 /* Casting avoids a GCC warning. */
7443 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7445 /* Put the image into the pixmap. */
7446 x_put_x_image (f, ximg, img->pixmap, width, height);
7447 x_destroy_x_image (ximg);
7448 UNGCPRO;
7449 return 1;
7452 #else /* HAVE_JPEG */
7454 #ifdef MAC_OS
7455 static int
7456 jpeg_load (f, img)
7457 struct frame *f;
7458 struct image *img;
7460 #if USE_MAC_IMAGE_IO
7461 return image_load_image_io (f, img, kUTTypeJPEG);
7462 #elif defined (MAC_OSX)
7463 return image_load_quartz2d (f, img, 0);
7464 #else
7465 return image_load_quicktime (f, img, kQTFileTypeJPEG);
7466 #endif
7468 #endif /* MAC_OS */
7470 #endif /* !HAVE_JPEG */
7474 /***********************************************************************
7475 TIFF
7476 ***********************************************************************/
7478 #if defined (HAVE_TIFF) || defined (MAC_OS)
7480 static int tiff_image_p P_ ((Lisp_Object object));
7481 static int tiff_load P_ ((struct frame *f, struct image *img));
7483 /* The symbol `tiff' identifying images of this type. */
7485 Lisp_Object Qtiff;
7487 /* Indices of image specification fields in tiff_format, below. */
7489 enum tiff_keyword_index
7491 TIFF_TYPE,
7492 TIFF_DATA,
7493 TIFF_FILE,
7494 TIFF_ASCENT,
7495 TIFF_MARGIN,
7496 TIFF_RELIEF,
7497 TIFF_ALGORITHM,
7498 TIFF_HEURISTIC_MASK,
7499 TIFF_MASK,
7500 TIFF_BACKGROUND,
7501 TIFF_LAST
7504 /* Vector of image_keyword structures describing the format
7505 of valid user-defined image specifications. */
7507 static struct image_keyword tiff_format[TIFF_LAST] =
7509 {":type", IMAGE_SYMBOL_VALUE, 1},
7510 {":data", IMAGE_STRING_VALUE, 0},
7511 {":file", IMAGE_STRING_VALUE, 0},
7512 {":ascent", IMAGE_ASCENT_VALUE, 0},
7513 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7514 {":relief", IMAGE_INTEGER_VALUE, 0},
7515 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7516 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7517 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7518 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7521 /* Structure describing the image type `tiff'. */
7523 static struct image_type tiff_type =
7525 &Qtiff,
7526 tiff_image_p,
7527 tiff_load,
7528 x_clear_image,
7529 NULL
7532 /* Return non-zero if OBJECT is a valid TIFF image specification. */
7534 static int
7535 tiff_image_p (object)
7536 Lisp_Object object;
7538 struct image_keyword fmt[TIFF_LAST];
7539 bcopy (tiff_format, fmt, sizeof fmt);
7541 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
7542 return 0;
7544 /* Must specify either the :data or :file keyword. */
7545 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
7548 #endif /* HAVE_TIFF || MAC_OS */
7550 #ifdef HAVE_TIFF
7552 #include <tiffio.h>
7554 #ifdef HAVE_NTGUI
7556 /* TIFF library details. */
7557 DEF_IMGLIB_FN (TIFFSetErrorHandler);
7558 DEF_IMGLIB_FN (TIFFSetWarningHandler);
7559 DEF_IMGLIB_FN (TIFFOpen);
7560 DEF_IMGLIB_FN (TIFFClientOpen);
7561 DEF_IMGLIB_FN (TIFFGetField);
7562 DEF_IMGLIB_FN (TIFFReadRGBAImage);
7563 DEF_IMGLIB_FN (TIFFClose);
7565 static int
7566 init_tiff_functions (Lisp_Object libraries)
7568 HMODULE library;
7570 if (!(library = w32_delayed_load (libraries, Qtiff)))
7571 return 0;
7573 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
7574 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
7575 LOAD_IMGLIB_FN (library, TIFFOpen);
7576 LOAD_IMGLIB_FN (library, TIFFClientOpen);
7577 LOAD_IMGLIB_FN (library, TIFFGetField);
7578 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
7579 LOAD_IMGLIB_FN (library, TIFFClose);
7580 return 1;
7583 #else
7585 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
7586 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
7587 #define fn_TIFFOpen TIFFOpen
7588 #define fn_TIFFClientOpen TIFFClientOpen
7589 #define fn_TIFFGetField TIFFGetField
7590 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
7591 #define fn_TIFFClose TIFFClose
7593 #endif /* HAVE_NTGUI */
7596 /* Reading from a memory buffer for TIFF images Based on the PNG
7597 memory source, but we have to provide a lot of extra functions.
7598 Blah.
7600 We really only need to implement read and seek, but I am not
7601 convinced that the TIFF library is smart enough not to destroy
7602 itself if we only hand it the function pointers we need to
7603 override. */
7605 typedef struct
7607 unsigned char *bytes;
7608 size_t len;
7609 int index;
7611 tiff_memory_source;
7613 static size_t
7614 tiff_read_from_memory (data, buf, size)
7615 thandle_t data;
7616 tdata_t buf;
7617 tsize_t size;
7619 tiff_memory_source *src = (tiff_memory_source *) data;
7621 if (size > src->len - src->index)
7622 return (size_t) -1;
7623 bcopy (src->bytes + src->index, buf, size);
7624 src->index += size;
7625 return size;
7628 static size_t
7629 tiff_write_from_memory (data, buf, size)
7630 thandle_t data;
7631 tdata_t buf;
7632 tsize_t size;
7634 return (size_t) -1;
7637 static toff_t
7638 tiff_seek_in_memory (data, off, whence)
7639 thandle_t data;
7640 toff_t off;
7641 int whence;
7643 tiff_memory_source *src = (tiff_memory_source *) data;
7644 int idx;
7646 switch (whence)
7648 case SEEK_SET: /* Go from beginning of source. */
7649 idx = off;
7650 break;
7652 case SEEK_END: /* Go from end of source. */
7653 idx = src->len + off;
7654 break;
7656 case SEEK_CUR: /* Go from current position. */
7657 idx = src->index + off;
7658 break;
7660 default: /* Invalid `whence'. */
7661 return -1;
7664 if (idx > src->len || idx < 0)
7665 return -1;
7667 src->index = idx;
7668 return src->index;
7671 static int
7672 tiff_close_memory (data)
7673 thandle_t data;
7675 /* NOOP */
7676 return 0;
7679 static int
7680 tiff_mmap_memory (data, pbase, psize)
7681 thandle_t data;
7682 tdata_t *pbase;
7683 toff_t *psize;
7685 /* It is already _IN_ memory. */
7686 return 0;
7689 static void
7690 tiff_unmap_memory (data, base, size)
7691 thandle_t data;
7692 tdata_t base;
7693 toff_t size;
7695 /* We don't need to do this. */
7698 static toff_t
7699 tiff_size_of_memory (data)
7700 thandle_t data;
7702 return ((tiff_memory_source *) data)->len;
7706 static void
7707 tiff_error_handler (title, format, ap)
7708 const char *title, *format;
7709 va_list ap;
7711 char buf[512];
7712 int len;
7714 len = sprintf (buf, "TIFF error: %s ", title);
7715 vsprintf (buf + len, format, ap);
7716 add_to_log (buf, Qnil, Qnil);
7720 static void
7721 tiff_warning_handler (title, format, ap)
7722 const char *title, *format;
7723 va_list ap;
7725 char buf[512];
7726 int len;
7728 len = sprintf (buf, "TIFF warning: %s ", title);
7729 vsprintf (buf + len, format, ap);
7730 add_to_log (buf, Qnil, Qnil);
7734 /* Load TIFF image IMG for use on frame F. Value is non-zero if
7735 successful. */
7737 static int
7738 tiff_load (f, img)
7739 struct frame *f;
7740 struct image *img;
7742 Lisp_Object file, specified_file;
7743 Lisp_Object specified_data;
7744 TIFF *tiff;
7745 int width, height, x, y;
7746 uint32 *buf;
7747 int rc;
7748 XImagePtr ximg;
7749 struct gcpro gcpro1;
7750 tiff_memory_source memsrc;
7752 specified_file = image_spec_value (img->spec, QCfile, NULL);
7753 specified_data = image_spec_value (img->spec, QCdata, NULL);
7754 file = Qnil;
7755 GCPRO1 (file);
7757 fn_TIFFSetErrorHandler (tiff_error_handler);
7758 fn_TIFFSetWarningHandler (tiff_warning_handler);
7760 if (NILP (specified_data))
7762 /* Read from a file */
7763 file = x_find_image_file (specified_file);
7764 if (!STRINGP (file))
7766 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7767 UNGCPRO;
7768 return 0;
7771 /* Try to open the image file. Casting return value avoids a
7772 GCC warning on W32. */
7773 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
7774 if (tiff == NULL)
7776 image_error ("Cannot open `%s'", file, Qnil);
7777 UNGCPRO;
7778 return 0;
7781 else
7783 /* Memory source! */
7784 memsrc.bytes = SDATA (specified_data);
7785 memsrc.len = SBYTES (specified_data);
7786 memsrc.index = 0;
7788 /* Casting return value avoids a GCC warning on W32. */
7789 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r", &memsrc,
7790 (TIFFReadWriteProc) tiff_read_from_memory,
7791 (TIFFReadWriteProc) tiff_write_from_memory,
7792 tiff_seek_in_memory,
7793 tiff_close_memory,
7794 tiff_size_of_memory,
7795 tiff_mmap_memory,
7796 tiff_unmap_memory);
7798 if (!tiff)
7800 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7801 UNGCPRO;
7802 return 0;
7806 /* Get width and height of the image, and allocate a raster buffer
7807 of width x height 32-bit values. */
7808 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7809 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7811 if (!check_image_size (f, width, height))
7813 image_error ("Invalid image size", Qnil, Qnil);
7814 UNGCPRO;
7815 return 0;
7818 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
7820 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7821 fn_TIFFClose (tiff);
7822 if (!rc)
7824 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7825 xfree (buf);
7826 UNGCPRO;
7827 return 0;
7830 /* Create the X image and pixmap. */
7831 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7833 xfree (buf);
7834 UNGCPRO;
7835 return 0;
7838 /* Initialize the color table. */
7839 init_color_table ();
7841 /* Process the pixel raster. Origin is in the lower-left corner. */
7842 for (y = 0; y < height; ++y)
7844 uint32 *row = buf + y * width;
7846 for (x = 0; x < width; ++x)
7848 uint32 abgr = row[x];
7849 int r = TIFFGetR (abgr) << 8;
7850 int g = TIFFGetG (abgr) << 8;
7851 int b = TIFFGetB (abgr) << 8;
7852 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7856 #ifdef COLOR_TABLE_SUPPORT
7857 /* Remember the colors allocated for the image. Free the color table. */
7858 img->colors = colors_in_color_table (&img->ncolors);
7859 free_color_table ();
7860 #endif /* COLOR_TABLE_SUPPORT */
7862 img->width = width;
7863 img->height = height;
7865 /* Maybe fill in the background field while we have ximg handy. */
7866 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7867 /* Casting avoids a GCC warning on W32. */
7868 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7870 /* Put the image into the pixmap, then free the X image and its buffer. */
7871 x_put_x_image (f, ximg, img->pixmap, width, height);
7872 x_destroy_x_image (ximg);
7873 xfree (buf);
7875 UNGCPRO;
7876 return 1;
7879 #else /* HAVE_TIFF */
7881 #ifdef MAC_OS
7882 static int
7883 tiff_load (f, img)
7884 struct frame *f;
7885 struct image *img;
7887 #if USE_MAC_IMAGE_IO
7888 return image_load_image_io (f, img, kUTTypeTIFF);
7889 #else
7890 return image_load_quicktime (f, img, kQTFileTypeTIFF);
7891 #endif
7893 #endif /* MAC_OS */
7895 #endif /* !HAVE_TIFF */
7899 /***********************************************************************
7901 ***********************************************************************/
7903 #if defined (HAVE_GIF) || defined (MAC_OS)
7905 static int gif_image_p P_ ((Lisp_Object object));
7906 static int gif_load P_ ((struct frame *f, struct image *img));
7907 static void gif_clear_image P_ ((struct frame *f, struct image *img));
7909 /* The symbol `gif' identifying images of this type. */
7911 Lisp_Object Qgif;
7913 /* Indices of image specification fields in gif_format, below. */
7915 enum gif_keyword_index
7917 GIF_TYPE,
7918 GIF_DATA,
7919 GIF_FILE,
7920 GIF_ASCENT,
7921 GIF_MARGIN,
7922 GIF_RELIEF,
7923 GIF_ALGORITHM,
7924 GIF_HEURISTIC_MASK,
7925 GIF_MASK,
7926 GIF_IMAGE,
7927 GIF_BACKGROUND,
7928 GIF_LAST
7931 /* Vector of image_keyword structures describing the format
7932 of valid user-defined image specifications. */
7934 static struct image_keyword gif_format[GIF_LAST] =
7936 {":type", IMAGE_SYMBOL_VALUE, 1},
7937 {":data", IMAGE_STRING_VALUE, 0},
7938 {":file", IMAGE_STRING_VALUE, 0},
7939 {":ascent", IMAGE_ASCENT_VALUE, 0},
7940 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7941 {":relief", IMAGE_INTEGER_VALUE, 0},
7942 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7943 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7944 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7945 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7946 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7949 /* Structure describing the image type `gif'. */
7951 static struct image_type gif_type =
7953 &Qgif,
7954 gif_image_p,
7955 gif_load,
7956 gif_clear_image,
7957 NULL
7960 /* Free X resources of GIF image IMG which is used on frame F. */
7962 static void
7963 gif_clear_image (f, img)
7964 struct frame *f;
7965 struct image *img;
7967 /* IMG->data.ptr_val may contain extension data. */
7968 img->data.lisp_val = Qnil;
7969 x_clear_image (f, img);
7972 /* Return non-zero if OBJECT is a valid GIF image specification. */
7974 static int
7975 gif_image_p (object)
7976 Lisp_Object object;
7978 struct image_keyword fmt[GIF_LAST];
7979 bcopy (gif_format, fmt, sizeof fmt);
7981 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7982 return 0;
7984 /* Must specify either the :data or :file keyword. */
7985 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7988 #endif /* HAVE_GIF || MAC_OS */
7990 #ifdef HAVE_GIF
7992 #if defined (HAVE_NTGUI) || defined (MAC_OS)
7993 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
7994 Undefine before redefining to avoid a preprocessor warning. */
7995 #ifdef DrawText
7996 #undef DrawText
7997 #endif
7998 /* avoid conflict with QuickdrawText.h */
7999 #define DrawText gif_DrawText
8000 #include <gif_lib.h>
8001 #undef DrawText
8003 #else /* HAVE_NTGUI || MAC_OS */
8005 #include <gif_lib.h>
8007 #endif /* HAVE_NTGUI || MAC_OS */
8010 #ifdef HAVE_NTGUI
8012 /* GIF library details. */
8013 DEF_IMGLIB_FN (DGifCloseFile);
8014 DEF_IMGLIB_FN (DGifSlurp);
8015 DEF_IMGLIB_FN (DGifOpen);
8016 DEF_IMGLIB_FN (DGifOpenFileName);
8018 static int
8019 init_gif_functions (Lisp_Object libraries)
8021 HMODULE library;
8023 if (!(library = w32_delayed_load (libraries, Qgif)))
8024 return 0;
8026 LOAD_IMGLIB_FN (library, DGifCloseFile);
8027 LOAD_IMGLIB_FN (library, DGifSlurp);
8028 LOAD_IMGLIB_FN (library, DGifOpen);
8029 LOAD_IMGLIB_FN (library, DGifOpenFileName);
8030 return 1;
8033 #else
8035 #define fn_DGifCloseFile DGifCloseFile
8036 #define fn_DGifSlurp DGifSlurp
8037 #define fn_DGifOpen DGifOpen
8038 #define fn_DGifOpenFileName DGifOpenFileName
8040 #endif /* HAVE_NTGUI */
8042 /* Reading a GIF image from memory
8043 Based on the PNG memory stuff to a certain extent. */
8045 typedef struct
8047 unsigned char *bytes;
8048 size_t len;
8049 int index;
8051 gif_memory_source;
8053 /* Make the current memory source available to gif_read_from_memory.
8054 It's done this way because not all versions of libungif support
8055 a UserData field in the GifFileType structure. */
8056 static gif_memory_source *current_gif_memory_src;
8058 static int
8059 gif_read_from_memory (file, buf, len)
8060 GifFileType *file;
8061 GifByteType *buf;
8062 int len;
8064 gif_memory_source *src = current_gif_memory_src;
8066 if (len > src->len - src->index)
8067 return -1;
8069 bcopy (src->bytes + src->index, buf, len);
8070 src->index += len;
8071 return len;
8075 /* Load GIF image IMG for use on frame F. Value is non-zero if
8076 successful. */
8078 static int interlace_start[] = {0, 4, 2, 1};
8079 static int interlace_increment[] = {8, 8, 4, 2};
8081 static int
8082 gif_load (f, img)
8083 struct frame *f;
8084 struct image *img;
8086 Lisp_Object file, specified_file;
8087 Lisp_Object specified_data;
8088 int rc, width, height, x, y, i;
8089 XImagePtr ximg;
8090 ColorMapObject *gif_color_map;
8091 unsigned long pixel_colors[256];
8092 GifFileType *gif;
8093 struct gcpro gcpro1;
8094 Lisp_Object image;
8095 int ino, image_height, image_width;
8096 gif_memory_source memsrc;
8097 unsigned char *raster;
8099 specified_file = image_spec_value (img->spec, QCfile, NULL);
8100 specified_data = image_spec_value (img->spec, QCdata, NULL);
8101 file = Qnil;
8102 GCPRO1 (file);
8104 if (NILP (specified_data))
8106 file = x_find_image_file (specified_file);
8107 if (!STRINGP (file))
8109 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8110 UNGCPRO;
8111 return 0;
8114 /* Open the GIF file. Casting return value avoids a GCC warning
8115 on W32. */
8116 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
8117 if (gif == NULL)
8119 image_error ("Cannot open `%s'", file, Qnil);
8120 UNGCPRO;
8121 return 0;
8124 else
8126 /* Read from memory! */
8127 current_gif_memory_src = &memsrc;
8128 memsrc.bytes = SDATA (specified_data);
8129 memsrc.len = SBYTES (specified_data);
8130 memsrc.index = 0;
8132 /* Casting return value avoids a GCC warning on W32. */
8133 gif = (GifFileType *)fn_DGifOpen(&memsrc, gif_read_from_memory);
8134 if (!gif)
8136 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
8137 UNGCPRO;
8138 return 0;
8142 /* Before reading entire contents, check the declared image size. */
8143 if (!check_image_size (f, gif->SWidth, gif->SHeight))
8145 image_error ("Invalid image size", Qnil, Qnil);
8146 fn_DGifCloseFile (gif);
8147 UNGCPRO;
8148 return 0;
8151 /* Read entire contents. */
8152 rc = fn_DGifSlurp (gif);
8153 if (rc == GIF_ERROR)
8155 image_error ("Error reading `%s'", img->spec, Qnil);
8156 fn_DGifCloseFile (gif);
8157 UNGCPRO;
8158 return 0;
8161 image = image_spec_value (img->spec, QCindex, NULL);
8162 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8163 if (ino >= gif->ImageCount)
8165 image_error ("Invalid image number `%s' in image `%s'",
8166 image, img->spec);
8167 fn_DGifCloseFile (gif);
8168 UNGCPRO;
8169 return 0;
8172 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
8173 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
8174 image_height = gif->SavedImages[ino].ImageDesc.Height;
8175 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
8176 image_width = gif->SavedImages[ino].ImageDesc.Width;
8177 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
8179 width = img->width = max (gif->SWidth,
8180 max (gif->Image.Left + gif->Image.Width,
8181 img->corners[RIGHT_CORNER]));
8182 height = img->height = max (gif->SHeight,
8183 max (gif->Image.Top + gif->Image.Height,
8184 img->corners[BOT_CORNER]));
8186 if (!check_image_size (f, width, height))
8188 image_error ("Invalid image size", Qnil, Qnil);
8189 fn_DGifCloseFile (gif);
8190 UNGCPRO;
8191 return 0;
8194 /* Create the X image and pixmap. */
8195 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8197 fn_DGifCloseFile (gif);
8198 UNGCPRO;
8199 return 0;
8202 /* Allocate colors. */
8203 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
8204 if (!gif_color_map)
8205 gif_color_map = gif->SColorMap;
8206 init_color_table ();
8207 bzero (pixel_colors, sizeof pixel_colors);
8209 if (gif_color_map)
8210 for (i = 0; i < gif_color_map->ColorCount; ++i)
8212 int r = gif_color_map->Colors[i].Red << 8;
8213 int g = gif_color_map->Colors[i].Green << 8;
8214 int b = gif_color_map->Colors[i].Blue << 8;
8215 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
8218 #ifdef COLOR_TABLE_SUPPORT
8219 img->colors = colors_in_color_table (&img->ncolors);
8220 free_color_table ();
8221 #endif /* COLOR_TABLE_SUPPORT */
8223 /* Clear the part of the screen image that are not covered by
8224 the image from the GIF file. Full animated GIF support
8225 requires more than can be done here (see the gif89 spec,
8226 disposal methods). Let's simply assume that the part
8227 not covered by a sub-image is in the frame's background color. */
8228 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
8229 for (x = 0; x < width; ++x)
8230 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8232 for (y = img->corners[BOT_CORNER]; y < height; ++y)
8233 for (x = 0; x < width; ++x)
8234 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8236 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
8238 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
8239 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8240 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
8241 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8244 /* Read the GIF image into the X image. We use a local variable
8245 `raster' here because RasterBits below is a char *, and invites
8246 problems with bytes >= 0x80. */
8247 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
8249 if (gif->SavedImages[ino].ImageDesc.Interlace)
8251 int pass;
8252 int row = interlace_start[0];
8254 pass = 0;
8256 for (y = 0; y < image_height; y++)
8258 if (row >= image_height)
8260 row = interlace_start[++pass];
8261 while (row >= image_height)
8262 row = interlace_start[++pass];
8265 for (x = 0; x < image_width; x++)
8267 int i = raster[(y * image_width) + x];
8268 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
8269 row + img->corners[TOP_CORNER], pixel_colors[i]);
8272 row += interlace_increment[pass];
8275 else
8277 for (y = 0; y < image_height; ++y)
8278 for (x = 0; x < image_width; ++x)
8280 int i = raster[y * image_width + x];
8281 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
8282 y + img->corners[TOP_CORNER], pixel_colors[i]);
8286 /* Save GIF image extension data for `image-extension-data'.
8287 Format is (count IMAGES FUNCTION "BYTES" ...). */
8288 img->data.lisp_val = Qnil;
8289 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
8291 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
8292 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
8293 /* Append (... FUNCTION "BYTES") */
8294 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
8295 Fcons (make_number (ext->Function),
8296 img->data.lisp_val));
8297 img->data.lisp_val = Fnreverse (img->data.lisp_val);
8299 if (gif->ImageCount > 1)
8300 img->data.lisp_val = Fcons (Qcount,
8301 Fcons (make_number (gif->ImageCount),
8302 img->data.lisp_val));
8304 fn_DGifCloseFile (gif);
8306 /* Maybe fill in the background field while we have ximg handy. */
8307 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8308 /* Casting avoids a GCC warning. */
8309 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8311 /* Put the image into the pixmap, then free the X image and its buffer. */
8312 x_put_x_image (f, ximg, img->pixmap, width, height);
8313 x_destroy_x_image (ximg);
8315 UNGCPRO;
8316 return 1;
8319 #else /* !HAVE_GIF */
8321 #ifdef MAC_OS
8322 static int
8323 gif_load (f, img)
8324 struct frame *f;
8325 struct image *img;
8327 #if USE_MAC_IMAGE_IO
8328 return image_load_image_io (f, img, kUTTypeGIF);
8329 #else /* !USE_MAC_IMAGE_IO */
8330 Lisp_Object specified_file, file;
8331 Lisp_Object specified_data;
8332 OSErr err;
8333 Boolean graphic_p, movie_p, prefer_graphic_p;
8334 Handle dh = NULL;
8335 Movie movie = NULL;
8336 Lisp_Object image;
8337 Track track = NULL;
8338 Media media = NULL;
8339 long nsamples;
8340 Rect rect;
8341 Lisp_Object specified_bg;
8342 XColor color;
8343 RGBColor bg_color;
8344 int width, height;
8345 XImagePtr ximg;
8346 TimeScale time_scale;
8347 TimeValue time, duration;
8348 int ino;
8349 CGrafPtr old_port;
8350 GDHandle old_gdh;
8352 specified_file = image_spec_value (img->spec, QCfile, NULL);
8353 specified_data = image_spec_value (img->spec, QCdata, NULL);
8355 /* Animated gifs use QuickTime Movie Toolbox. So initialize it here. */
8356 EnterMovies ();
8358 if (NILP (specified_data))
8360 /* Read from a file */
8361 FSSpec fss;
8362 short refnum;
8364 err = find_image_fsspec (specified_file, &file, &fss);
8365 if (err != noErr)
8367 if (err == fnfErr)
8368 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8369 else
8370 goto open_error;
8373 err = CanQuickTimeOpenFile (&fss, kQTFileTypeGIF, 0,
8374 &graphic_p, &movie_p, &prefer_graphic_p, 0);
8375 if (err != noErr)
8376 goto open_error;
8378 if (!graphic_p && !movie_p)
8379 goto open_error;
8380 if (prefer_graphic_p)
8381 return image_load_qt_1 (f, img, kQTFileTypeGIF, &fss, NULL);
8382 err = OpenMovieFile (&fss, &refnum, fsRdPerm);
8383 if (err != noErr)
8384 goto open_error;
8385 err = NewMovieFromFile (&movie, refnum, NULL, NULL, 0, NULL);
8386 CloseMovieFile (refnum);
8387 if (err != noErr)
8389 image_error ("Error reading `%s'", file, Qnil);
8390 return 0;
8393 else
8395 /* Memory source! */
8396 Handle dref = NULL;
8397 long file_type_atom[3];
8399 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
8400 if (err != noErr)
8402 image_error ("Cannot allocate data handle for `%s'",
8403 img->spec, Qnil);
8404 goto error;
8407 file_type_atom[0] = EndianU32_NtoB (sizeof (long) * 3);
8408 file_type_atom[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
8409 file_type_atom[2] = EndianU32_NtoB (kQTFileTypeGIF);
8410 err = PtrToHand (&dh, &dref, sizeof (Handle));
8411 if (err == noErr)
8412 /* no file name */
8413 err = PtrAndHand ("\p", dref, 1);
8414 if (err == noErr)
8415 err = PtrAndHand (file_type_atom, dref, sizeof (long) * 3);
8416 if (err != noErr)
8418 image_error ("Cannot allocate handle data ref for `%s'", img->spec, Qnil);
8419 goto error;
8421 err = CanQuickTimeOpenDataRef (dref, HandleDataHandlerSubType, &graphic_p,
8422 &movie_p, &prefer_graphic_p, 0);
8423 if (err != noErr)
8424 goto open_error;
8426 if (!graphic_p && !movie_p)
8427 goto open_error;
8428 if (prefer_graphic_p)
8430 int success_p;
8432 DisposeHandle (dref);
8433 success_p = image_load_qt_1 (f, img, kQTFileTypeGIF, NULL, dh);
8434 DisposeHandle (dh);
8435 return success_p;
8437 err = NewMovieFromDataRef (&movie, 0, NULL, dref,
8438 HandleDataHandlerSubType);
8439 DisposeHandle (dref);
8440 if (err != noErr)
8441 goto open_error;
8444 image = image_spec_value (img->spec, QCindex, NULL);
8445 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8446 track = GetMovieIndTrack (movie, 1);
8447 media = GetTrackMedia (track);
8448 nsamples = GetMediaSampleCount (media);
8449 if (ino >= nsamples)
8451 image_error ("Invalid image number `%s' in image `%s'",
8452 image, img->spec);
8453 goto error;
8455 time_scale = GetMediaTimeScale (media);
8457 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8458 if (!STRINGP (specified_bg)
8459 || !mac_defined_color (f, SDATA (specified_bg), &color, 0))
8461 color.pixel = FRAME_BACKGROUND_PIXEL (f);
8462 color.red = RED16_FROM_ULONG (color.pixel);
8463 color.green = GREEN16_FROM_ULONG (color.pixel);
8464 color.blue = BLUE16_FROM_ULONG (color.pixel);
8466 GetMovieBox (movie, &rect);
8467 width = img->width = rect.right - rect.left;
8468 height = img->height = rect.bottom - rect.top;
8469 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8470 goto error;
8472 GetGWorld (&old_port, &old_gdh);
8473 SetGWorld (ximg, NULL);
8474 bg_color.red = color.red;
8475 bg_color.green = color.green;
8476 bg_color.blue = color.blue;
8477 RGBBackColor (&bg_color);
8478 SetGWorld (old_port, old_gdh);
8479 SetMovieActive (movie, 1);
8480 SetMovieGWorld (movie, ximg, NULL);
8481 SampleNumToMediaTime (media, ino + 1, &time, &duration);
8482 SetMovieTimeValue (movie, time);
8483 MoviesTask (movie, 0L);
8484 DisposeTrackMedia (media);
8485 DisposeMovieTrack (track);
8486 DisposeMovie (movie);
8487 if (dh)
8488 DisposeHandle (dh);
8490 /* Save GIF image extension data for `image-extension-data'.
8491 Format is (count IMAGES 0xf9 GRAPHIC_CONTROL_EXTENSION_BLOCK). */
8493 Lisp_Object gce = make_uninit_string (4);
8494 int centisec = ((float)duration / time_scale) * 100.0f + 0.5f;
8496 /* Fill the delay time field. */
8497 SSET (gce, 1, centisec & 0xff);
8498 SSET (gce, 2, (centisec >> 8) & 0xff);
8499 /* We don't know about other fields. */
8500 SSET (gce, 0, 0);
8501 SSET (gce, 3, 0);
8503 img->data.lisp_val = list4 (Qcount, make_number (nsamples),
8504 make_number (0xf9), gce);
8507 /* Maybe fill in the background field while we have ximg handy. */
8508 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8509 IMAGE_BACKGROUND (img, f, ximg);
8511 /* Put the image into the pixmap. */
8512 x_put_x_image (f, ximg, img->pixmap, width, height);
8513 x_destroy_x_image (ximg);
8514 return 1;
8516 open_error:
8517 image_error ("Cannot open `%s'", file, Qnil);
8518 error:
8519 if (media)
8520 DisposeTrackMedia (media);
8521 if (track)
8522 DisposeMovieTrack (track);
8523 if (movie)
8524 DisposeMovie (movie);
8525 if (dh)
8526 DisposeHandle (dh);
8527 return 0;
8528 #endif /* !USE_MAC_IMAGE_IO */
8530 #endif /* MAC_OS */
8532 #endif /* HAVE_GIF */
8536 /***********************************************************************
8537 Ghostscript
8538 ***********************************************************************/
8540 #ifdef HAVE_X_WINDOWS
8541 #define HAVE_GHOSTSCRIPT 1
8542 #endif /* HAVE_X_WINDOWS */
8544 /* The symbol `postscript' identifying images of this type. */
8546 Lisp_Object Qpostscript;
8548 #ifdef HAVE_GHOSTSCRIPT
8550 static int gs_image_p P_ ((Lisp_Object object));
8551 static int gs_load P_ ((struct frame *f, struct image *img));
8552 static void gs_clear_image P_ ((struct frame *f, struct image *img));
8554 /* Keyword symbols. */
8556 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
8558 /* Indices of image specification fields in gs_format, below. */
8560 enum gs_keyword_index
8562 GS_TYPE,
8563 GS_PT_WIDTH,
8564 GS_PT_HEIGHT,
8565 GS_FILE,
8566 GS_LOADER,
8567 GS_BOUNDING_BOX,
8568 GS_ASCENT,
8569 GS_MARGIN,
8570 GS_RELIEF,
8571 GS_ALGORITHM,
8572 GS_HEURISTIC_MASK,
8573 GS_MASK,
8574 GS_BACKGROUND,
8575 GS_LAST
8578 /* Vector of image_keyword structures describing the format
8579 of valid user-defined image specifications. */
8581 static struct image_keyword gs_format[GS_LAST] =
8583 {":type", IMAGE_SYMBOL_VALUE, 1},
8584 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8585 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
8586 {":file", IMAGE_STRING_VALUE, 1},
8587 {":loader", IMAGE_FUNCTION_VALUE, 0},
8588 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8589 {":ascent", IMAGE_ASCENT_VALUE, 0},
8590 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8591 {":relief", IMAGE_INTEGER_VALUE, 0},
8592 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8593 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8594 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8595 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8598 /* Structure describing the image type `ghostscript'. */
8600 static struct image_type gs_type =
8602 &Qpostscript,
8603 gs_image_p,
8604 gs_load,
8605 gs_clear_image,
8606 NULL
8610 /* Free X resources of Ghostscript image IMG which is used on frame F. */
8612 static void
8613 gs_clear_image (f, img)
8614 struct frame *f;
8615 struct image *img;
8617 /* IMG->data.ptr_val may contain a recorded colormap. */
8618 xfree (img->data.ptr_val);
8619 x_clear_image (f, img);
8623 /* Return non-zero if OBJECT is a valid Ghostscript image
8624 specification. */
8626 static int
8627 gs_image_p (object)
8628 Lisp_Object object;
8630 struct image_keyword fmt[GS_LAST];
8631 Lisp_Object tem;
8632 int i;
8634 bcopy (gs_format, fmt, sizeof fmt);
8636 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
8637 return 0;
8639 /* Bounding box must be a list or vector containing 4 integers. */
8640 tem = fmt[GS_BOUNDING_BOX].value;
8641 if (CONSP (tem))
8643 for (i = 0; i < 4; ++i, tem = XCDR (tem))
8644 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
8645 return 0;
8646 if (!NILP (tem))
8647 return 0;
8649 else if (VECTORP (tem))
8651 if (XVECTOR (tem)->size != 4)
8652 return 0;
8653 for (i = 0; i < 4; ++i)
8654 if (!INTEGERP (XVECTOR (tem)->contents[i]))
8655 return 0;
8657 else
8658 return 0;
8660 return 1;
8664 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
8665 if successful. */
8667 static int
8668 gs_load (f, img)
8669 struct frame *f;
8670 struct image *img;
8672 char buffer[100];
8673 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8674 struct gcpro gcpro1, gcpro2;
8675 Lisp_Object frame;
8676 double in_width, in_height;
8677 Lisp_Object pixel_colors = Qnil;
8679 /* Compute pixel size of pixmap needed from the given size in the
8680 image specification. Sizes in the specification are in pt. 1 pt
8681 = 1/72 in, xdpi and ydpi are stored in the frame's X display
8682 info. */
8683 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8684 in_width = XFASTINT (pt_width) / 72.0;
8685 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
8686 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8687 in_height = XFASTINT (pt_height) / 72.0;
8688 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
8690 if (!check_image_size (f, img->width, img->height))
8692 image_error ("Invalid image size", Qnil, Qnil);
8693 return 0;
8696 /* Create the pixmap. */
8697 xassert (img->pixmap == NO_PIXMAP);
8699 /* Only W32 version did BLOCK_INPUT here. ++kfs */
8700 BLOCK_INPUT;
8701 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8702 img->width, img->height,
8703 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
8704 UNBLOCK_INPUT;
8706 if (!img->pixmap)
8708 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
8709 return 0;
8712 /* Call the loader to fill the pixmap. It returns a process object
8713 if successful. We do not record_unwind_protect here because
8714 other places in redisplay like calling window scroll functions
8715 don't either. Let the Lisp loader use `unwind-protect' instead. */
8716 GCPRO2 (window_and_pixmap_id, pixel_colors);
8718 sprintf (buffer, "%lu %lu",
8719 (unsigned long) FRAME_X_WINDOW (f),
8720 (unsigned long) img->pixmap);
8721 window_and_pixmap_id = build_string (buffer);
8723 sprintf (buffer, "%lu %lu",
8724 FRAME_FOREGROUND_PIXEL (f),
8725 FRAME_BACKGROUND_PIXEL (f));
8726 pixel_colors = build_string (buffer);
8728 XSETFRAME (frame, f);
8729 loader = image_spec_value (img->spec, QCloader, NULL);
8730 if (NILP (loader))
8731 loader = intern ("gs-load-image");
8733 img->data.lisp_val = call6 (loader, frame, img->spec,
8734 make_number (img->width),
8735 make_number (img->height),
8736 window_and_pixmap_id,
8737 pixel_colors);
8738 UNGCPRO;
8739 return PROCESSP (img->data.lisp_val);
8743 /* Kill the Ghostscript process that was started to fill PIXMAP on
8744 frame F. Called from XTread_socket when receiving an event
8745 telling Emacs that Ghostscript has finished drawing. */
8747 void
8748 x_kill_gs_process (pixmap, f)
8749 Pixmap pixmap;
8750 struct frame *f;
8752 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8753 int class, i;
8754 struct image *img;
8756 /* Find the image containing PIXMAP. */
8757 for (i = 0; i < c->used; ++i)
8758 if (c->images[i]->pixmap == pixmap)
8759 break;
8761 /* Should someone in between have cleared the image cache, for
8762 instance, give up. */
8763 if (i == c->used)
8764 return;
8766 /* Kill the GS process. We should have found PIXMAP in the image
8767 cache and its image should contain a process object. */
8768 img = c->images[i];
8769 xassert (PROCESSP (img->data.lisp_val));
8770 Fkill_process (img->data.lisp_val, Qnil);
8771 img->data.lisp_val = Qnil;
8773 #if defined (HAVE_X_WINDOWS)
8775 /* On displays with a mutable colormap, figure out the colors
8776 allocated for the image by looking at the pixels of an XImage for
8777 img->pixmap. */
8778 class = FRAME_X_VISUAL (f)->class;
8779 if (class != StaticColor && class != StaticGray && class != TrueColor)
8781 XImagePtr ximg;
8783 BLOCK_INPUT;
8785 /* Try to get an XImage for img->pixmep. */
8786 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8787 0, 0, img->width, img->height, ~0, ZPixmap);
8788 if (ximg)
8790 int x, y;
8792 /* Initialize the color table. */
8793 init_color_table ();
8795 /* For each pixel of the image, look its color up in the
8796 color table. After having done so, the color table will
8797 contain an entry for each color used by the image. */
8798 for (y = 0; y < img->height; ++y)
8799 for (x = 0; x < img->width; ++x)
8801 unsigned long pixel = XGetPixel (ximg, x, y);
8802 lookup_pixel_color (f, pixel);
8805 /* Record colors in the image. Free color table and XImage. */
8806 #ifdef COLOR_TABLE_SUPPORT
8807 img->colors = colors_in_color_table (&img->ncolors);
8808 free_color_table ();
8809 #endif
8810 XDestroyImage (ximg);
8812 #if 0 /* This doesn't seem to be the case. If we free the colors
8813 here, we get a BadAccess later in x_clear_image when
8814 freeing the colors. */
8815 /* We have allocated colors once, but Ghostscript has also
8816 allocated colors on behalf of us. So, to get the
8817 reference counts right, free them once. */
8818 if (img->ncolors)
8819 x_free_colors (f, img->colors, img->ncolors);
8820 #endif
8822 else
8823 image_error ("Cannot get X image of `%s'; colors will not be freed",
8824 img->spec, Qnil);
8826 UNBLOCK_INPUT;
8828 #endif /* HAVE_X_WINDOWS */
8830 /* Now that we have the pixmap, compute mask and transform the
8831 image if requested. */
8832 BLOCK_INPUT;
8833 postprocess_image (f, img);
8834 UNBLOCK_INPUT;
8837 #endif /* HAVE_GHOSTSCRIPT */
8840 /***********************************************************************
8841 Tests
8842 ***********************************************************************/
8844 #if GLYPH_DEBUG
8846 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8847 doc: /* Value is non-nil if SPEC is a valid image specification. */)
8848 (spec)
8849 Lisp_Object spec;
8851 return valid_image_p (spec) ? Qt : Qnil;
8855 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8856 (spec)
8857 Lisp_Object spec;
8859 int id = -1;
8861 if (valid_image_p (spec))
8862 id = lookup_image (SELECTED_FRAME (), spec);
8864 debug_print (spec);
8865 return make_number (id);
8868 #endif /* GLYPH_DEBUG != 0 */
8871 /***********************************************************************
8872 Initialization
8873 ***********************************************************************/
8875 #ifdef HAVE_NTGUI
8876 /* Image types that rely on external libraries are loaded dynamically
8877 if the library is available. */
8878 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8879 define_image_type (image_type, init_lib_fn (libraries))
8880 #else
8881 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
8882 define_image_type (image_type, 1)
8883 #endif /* HAVE_NTGUI */
8885 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8886 doc: /* Initialize image library implementing image type TYPE.
8887 Return non-nil if TYPE is a supported image type.
8889 Image types pbm and xbm are prebuilt; other types are loaded here.
8890 Libraries to load are specified in alist LIBRARIES (usually, the value
8891 of `image-library-alist', which see). */)
8892 (type, libraries)
8893 Lisp_Object type, libraries;
8895 Lisp_Object tested;
8897 /* Don't try to reload the library. */
8898 tested = Fassq (type, Vimage_type_cache);
8899 if (CONSP (tested))
8900 return XCDR (tested);
8902 #if defined (HAVE_XPM) || defined (MAC_OS)
8903 if (EQ (type, Qxpm))
8904 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
8905 #endif
8907 #if defined (HAVE_JPEG) || defined (MAC_OS)
8908 if (EQ (type, Qjpeg))
8909 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
8910 #endif
8912 #if defined (HAVE_TIFF) || defined (MAC_OS)
8913 if (EQ (type, Qtiff))
8914 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
8915 #endif
8917 #if defined (HAVE_GIF) || defined (MAC_OS)
8918 if (EQ (type, Qgif))
8919 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
8920 #endif
8922 #if defined (HAVE_PNG) || defined (MAC_OS)
8923 if (EQ (type, Qpng))
8924 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
8925 #endif
8927 #ifdef HAVE_GHOSTSCRIPT
8928 if (EQ (type, Qpostscript))
8929 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
8930 #endif
8932 /* If the type is not recognized, avoid testing it ever again. */
8933 CACHE_IMAGE_TYPE (type, Qnil);
8934 return Qnil;
8937 void
8938 syms_of_image ()
8940 extern Lisp_Object Qrisky_local_variable; /* Syms_of_xdisp has already run. */
8942 /* Initialize this only once, since that's what we do with Vimage_types
8943 and they are supposed to be in sync. Initializing here gives correct
8944 operation on GNU/Linux of calling dump-emacs after loading some images. */
8945 image_types = NULL;
8947 /* Must be defined now becase we're going to update it below, while
8948 defining the supported image types. */
8949 DEFVAR_LISP ("image-types", &Vimage_types,
8950 doc: /* List of potentially supported image types.
8951 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
8952 To check whether it is really supported, use `image-type-available-p'. */);
8953 Vimage_types = Qnil;
8955 DEFVAR_LISP ("image-library-alist", &Vimage_library_alist,
8956 doc: /* Alist of image types vs external libraries needed to display them.
8958 Each element is a list (IMAGE-TYPE LIBRARY...), where the car is a symbol
8959 representing a supported image type, and the rest are strings giving
8960 alternate filenames for the corresponding external libraries.
8962 Emacs tries to load the libraries in the order they appear on the
8963 list; if none is loaded, the running session of Emacs won't
8964 support the image type. Types 'pbm and 'xbm don't need to be
8965 listed; they are always supported. */);
8966 Vimage_library_alist = Qnil;
8967 Fput (intern ("image-library-alist"), Qrisky_local_variable, Qt);
8969 DEFVAR_LISP ("max-image-size", &Vmax_image_size,
8970 doc: /* Maximum size of images.
8971 Emacs will not load an image into memory if its pixel width or
8972 pixel height exceeds this limit.
8974 If the value is an integer, it directly specifies the maximum
8975 image height and width, measured in pixels. If it is a floating
8976 point number, it specifies the maximum image height and width
8977 as a ratio to the frame height and width. If the value is
8978 non-numeric, there is no explicit limit on the size of images. */);
8979 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
8981 Vimage_type_cache = Qnil;
8982 staticpro (&Vimage_type_cache);
8984 Qpbm = intern ("pbm");
8985 staticpro (&Qpbm);
8986 ADD_IMAGE_TYPE(Qpbm);
8988 Qxbm = intern ("xbm");
8989 staticpro (&Qxbm);
8990 ADD_IMAGE_TYPE(Qxbm);
8992 define_image_type (&xbm_type, 1);
8993 define_image_type (&pbm_type, 1);
8995 QCascent = intern (":ascent");
8996 staticpro (&QCascent);
8997 QCmargin = intern (":margin");
8998 staticpro (&QCmargin);
8999 QCrelief = intern (":relief");
9000 staticpro (&QCrelief);
9001 QCconversion = intern (":conversion");
9002 staticpro (&QCconversion);
9003 QCcolor_symbols = intern (":color-symbols");
9004 staticpro (&QCcolor_symbols);
9005 QCheuristic_mask = intern (":heuristic-mask");
9006 staticpro (&QCheuristic_mask);
9007 QCindex = intern (":index");
9008 staticpro (&QCindex);
9009 QCmatrix = intern (":matrix");
9010 staticpro (&QCmatrix);
9011 QCcolor_adjustment = intern (":color-adjustment");
9012 staticpro (&QCcolor_adjustment);
9013 QCmask = intern (":mask");
9014 staticpro (&QCmask);
9016 Qlaplace = intern ("laplace");
9017 staticpro (&Qlaplace);
9018 Qemboss = intern ("emboss");
9019 staticpro (&Qemboss);
9020 Qedge_detection = intern ("edge-detection");
9021 staticpro (&Qedge_detection);
9022 Qheuristic = intern ("heuristic");
9023 staticpro (&Qheuristic);
9025 Qpostscript = intern ("postscript");
9026 staticpro (&Qpostscript);
9027 #ifdef HAVE_GHOSTSCRIPT
9028 ADD_IMAGE_TYPE(Qpostscript);
9029 QCloader = intern (":loader");
9030 staticpro (&QCloader);
9031 QCbounding_box = intern (":bounding-box");
9032 staticpro (&QCbounding_box);
9033 QCpt_width = intern (":pt-width");
9034 staticpro (&QCpt_width);
9035 QCpt_height = intern (":pt-height");
9036 staticpro (&QCpt_height);
9037 #endif /* HAVE_GHOSTSCRIPT */
9039 #if defined (HAVE_XPM) || defined (MAC_OS)
9040 Qxpm = intern ("xpm");
9041 staticpro (&Qxpm);
9042 ADD_IMAGE_TYPE(Qxpm);
9043 #endif
9045 #if defined (HAVE_JPEG) || defined (MAC_OS)
9046 Qjpeg = intern ("jpeg");
9047 staticpro (&Qjpeg);
9048 ADD_IMAGE_TYPE(Qjpeg);
9049 #endif
9051 #if defined (HAVE_TIFF) || defined (MAC_OS)
9052 Qtiff = intern ("tiff");
9053 staticpro (&Qtiff);
9054 ADD_IMAGE_TYPE(Qtiff);
9055 #endif
9057 #if defined (HAVE_GIF) || defined (MAC_OS)
9058 Qgif = intern ("gif");
9059 staticpro (&Qgif);
9060 ADD_IMAGE_TYPE(Qgif);
9061 #endif
9063 #if defined (HAVE_PNG) || defined (MAC_OS)
9064 Qpng = intern ("png");
9065 staticpro (&Qpng);
9066 ADD_IMAGE_TYPE(Qpng);
9067 #endif
9069 defsubr (&Sinit_image_library);
9070 defsubr (&Sclear_image_cache);
9071 defsubr (&Simage_refresh);
9072 defsubr (&Simage_size);
9073 defsubr (&Simage_mask_p);
9074 defsubr (&Simage_extension_data);
9076 #if GLYPH_DEBUG
9077 defsubr (&Simagep);
9078 defsubr (&Slookup_image);
9079 #endif
9081 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
9082 doc: /* Non-nil means always draw a cross over disabled images.
9083 Disabled images are those having a `:conversion disabled' property.
9084 A cross is always drawn on black & white displays. */);
9085 cross_disabled_images = 0;
9087 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
9088 doc: /* List of directories to search for window system bitmap files. */);
9089 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
9091 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
9092 doc: /* Time after which cached images are removed from the cache.
9093 When an image has not been displayed this many seconds, remove it
9094 from the image cache. Value must be an integer or nil with nil
9095 meaning don't clear the cache. */);
9096 Vimage_cache_eviction_delay = make_number (30 * 60);
9099 void
9100 init_image ()
9104 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
9105 (do not change this comment) */