Merge from emacs--rel--22
[emacs.git] / src / image.c
blob48b223c6c7665450e40b5d38565d007dca45b1da
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"
45 #include "termhooks.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;
817 extern Lisp_Object Qcenter;
818 Lisp_Object QCascent, QCmargin, QCrelief, Qcount;
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);
1267 Lisp_Object file = image_spec_value (spec, QCfile, NULL);
1269 xassert (valid_image_p (spec));
1270 bzero (img, sizeof *img);
1271 img->dependencies = NILP (file) ? Qnil : list1 (file);
1272 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1273 xassert (img->type != NULL);
1274 img->spec = spec;
1275 img->data.lisp_val = Qnil;
1276 img->ascent = DEFAULT_IMAGE_ASCENT;
1277 img->hash = hash;
1278 img->corners[BOT_CORNER] = -1; /* Full image */
1279 return img;
1283 /* Free image IMG which was used on frame F, including its resources. */
1285 static void
1286 free_image (f, img)
1287 struct frame *f;
1288 struct image *img;
1290 if (img)
1292 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1294 /* Remove IMG from the hash table of its cache. */
1295 if (img->prev)
1296 img->prev->next = img->next;
1297 else
1298 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1300 if (img->next)
1301 img->next->prev = img->prev;
1303 c->images[img->id] = NULL;
1305 /* Free resources, then free IMG. */
1306 img->type->free (f, img);
1307 xfree (img);
1311 /* Return 1 if the given widths and heights are valid for display;
1312 otherwise, return 0. */
1315 check_image_size (f, width, height)
1316 struct frame *f;
1317 int width;
1318 int height;
1320 int w, h;
1322 if (width <= 0 || height <= 0)
1323 return 0;
1325 if (INTEGERP (Vmax_image_size))
1326 w = h = XINT (Vmax_image_size);
1327 else if (FLOATP (Vmax_image_size))
1329 if (f != NULL)
1331 w = FRAME_PIXEL_WIDTH (f);
1332 h = FRAME_PIXEL_HEIGHT (f);
1334 else
1335 w = h = 1024; /* Arbitrary size for unknown frame. */
1336 w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
1337 h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
1339 else
1340 return 1;
1342 return (width <= w && height <= h);
1345 /* Prepare image IMG for display on frame F. Must be called before
1346 drawing an image. */
1348 void
1349 prepare_image_for_display (f, img)
1350 struct frame *f;
1351 struct image *img;
1353 EMACS_TIME t;
1355 /* We're about to display IMG, so set its timestamp to `now'. */
1356 EMACS_GET_TIME (t);
1357 img->timestamp = EMACS_SECS (t);
1359 /* If IMG doesn't have a pixmap yet, load it now, using the image
1360 type dependent loader function. */
1361 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1362 img->load_failed_p = img->type->load (f, img) == 0;
1364 #if defined (MAC_OS) && USE_CG_DRAWING
1365 if (!img->load_failed_p && img->data.ptr_val == NULL)
1367 img->data.ptr_val = mac_create_cg_image_from_image (f, img);
1368 if (img->data.ptr_val == NULL)
1370 img->load_failed_p = 1;
1371 img->type->free (f, img);
1374 #endif
1378 /* Value is the number of pixels for the ascent of image IMG when
1379 drawn in face FACE. */
1382 image_ascent (img, face, slice)
1383 struct image *img;
1384 struct face *face;
1385 struct glyph_slice *slice;
1387 int height;
1388 int ascent;
1390 if (slice->height == img->height)
1391 height = img->height + img->vmargin;
1392 else if (slice->y == 0)
1393 height = slice->height + img->vmargin;
1394 else
1395 height = slice->height;
1397 if (img->ascent == CENTERED_IMAGE_ASCENT)
1399 if (face->font)
1401 #ifdef HAVE_NTGUI
1402 /* W32 specific version. Why?. ++kfs */
1403 ascent = height / 2 - (FONT_DESCENT (face->font)
1404 - FONT_BASE (face->font)) / 2;
1405 #else
1406 /* This expression is arranged so that if the image can't be
1407 exactly centered, it will be moved slightly up. This is
1408 because a typical font is `top-heavy' (due to the presence
1409 uppercase letters), so the image placement should err towards
1410 being top-heavy too. It also just generally looks better. */
1411 ascent = (height + face->font->ascent - face->font->descent + 1) / 2;
1412 #endif /* HAVE_NTGUI */
1414 else
1415 ascent = height / 2;
1417 else
1418 ascent = (int) (height * img->ascent / 100.0);
1420 return ascent;
1424 /* Image background colors. */
1426 /* Find the "best" corner color of a bitmap.
1427 On W32, XIMG is assumed to a device context with the bitmap selected. */
1429 static RGB_PIXEL_COLOR
1430 four_corners_best (ximg, corners, width, height)
1431 XImagePtr_or_DC ximg;
1432 int *corners;
1433 unsigned long width, height;
1435 RGB_PIXEL_COLOR corner_pixels[4], best;
1436 int i, best_count;
1438 if (corners && corners[BOT_CORNER] >= 0)
1440 /* Get the colors at the corner_pixels of ximg. */
1441 corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
1442 corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
1443 corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
1444 corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
1446 else
1448 /* Get the colors at the corner_pixels of ximg. */
1449 corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
1450 corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
1451 corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
1452 corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
1454 /* Choose the most frequently found color as background. */
1455 for (i = best_count = 0; i < 4; ++i)
1457 int j, n;
1459 for (j = n = 0; j < 4; ++j)
1460 if (corner_pixels[i] == corner_pixels[j])
1461 ++n;
1463 if (n > best_count)
1464 best = corner_pixels[i], best_count = n;
1467 return best;
1470 /* Portability macros */
1472 #ifdef HAVE_NTGUI
1474 #define Destroy_Image(img_dc, prev) \
1475 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1477 #define Free_Pixmap(display, pixmap) \
1478 DeleteObject (pixmap)
1480 #else
1482 #define Destroy_Image(ximg, dummy) \
1483 XDestroyImage (ximg)
1485 #define Free_Pixmap(display, pixmap) \
1486 XFreePixmap (display, pixmap)
1488 #endif /* HAVE_NTGUI */
1491 /* Return the `background' field of IMG. If IMG doesn't have one yet,
1492 it is guessed heuristically. If non-zero, XIMG is an existing
1493 XImage object (or device context with the image selected on W32) to
1494 use for the heuristic. */
1496 RGB_PIXEL_COLOR
1497 image_background (img, f, ximg)
1498 struct image *img;
1499 struct frame *f;
1500 XImagePtr_or_DC ximg;
1502 if (! img->background_valid)
1503 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1505 int free_ximg = !ximg;
1506 #ifdef HAVE_NTGUI
1507 HGDIOBJ prev;
1508 #endif /* HAVE_NTGUI */
1510 if (free_ximg)
1512 #ifndef HAVE_NTGUI
1513 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1514 0, 0, img->width, img->height, ~0, ZPixmap);
1515 #else
1516 HDC frame_dc = get_frame_dc (f);
1517 ximg = CreateCompatibleDC (frame_dc);
1518 release_frame_dc (f, frame_dc);
1519 prev = SelectObject (ximg, img->pixmap);
1520 #endif /* !HAVE_NTGUI */
1523 img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1525 if (free_ximg)
1526 Destroy_Image (ximg, prev);
1528 img->background_valid = 1;
1531 return img->background;
1534 /* Return the `background_transparent' field of IMG. If IMG doesn't
1535 have one yet, it is guessed heuristically. If non-zero, MASK is an
1536 existing XImage object to use for the heuristic. */
1539 image_background_transparent (img, f, mask)
1540 struct image *img;
1541 struct frame *f;
1542 XImagePtr_or_DC mask;
1544 if (! img->background_transparent_valid)
1545 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1547 if (img->mask)
1549 int free_mask = !mask;
1550 #ifdef HAVE_NTGUI
1551 HGDIOBJ prev;
1552 #endif /* HAVE_NTGUI */
1554 if (free_mask)
1556 #ifndef HAVE_NTGUI
1557 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1558 0, 0, img->width, img->height, ~0, ZPixmap);
1559 #else
1560 HDC frame_dc = get_frame_dc (f);
1561 mask = CreateCompatibleDC (frame_dc);
1562 release_frame_dc (f, frame_dc);
1563 prev = SelectObject (mask, img->mask);
1564 #endif /* HAVE_NTGUI */
1567 img->background_transparent
1568 = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1570 if (free_mask)
1571 Destroy_Image (mask, prev);
1573 else
1574 img->background_transparent = 0;
1576 img->background_transparent_valid = 1;
1579 return img->background_transparent;
1583 /***********************************************************************
1584 Helper functions for X image types
1585 ***********************************************************************/
1587 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
1588 int, int));
1589 static void x_clear_image P_ ((struct frame *f, struct image *img));
1590 static unsigned long x_alloc_image_color P_ ((struct frame *f,
1591 struct image *img,
1592 Lisp_Object color_name,
1593 unsigned long dflt));
1596 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1597 free the pixmap if any. MASK_P non-zero means clear the mask
1598 pixmap if any. COLORS_P non-zero means free colors allocated for
1599 the image, if any. */
1601 static void
1602 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
1603 struct frame *f;
1604 struct image *img;
1605 int pixmap_p, mask_p, colors_p;
1607 if (pixmap_p && img->pixmap)
1609 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1610 img->pixmap = NO_PIXMAP;
1611 img->background_valid = 0;
1614 if (mask_p && img->mask)
1616 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1617 img->mask = NO_PIXMAP;
1618 img->background_transparent_valid = 0;
1621 if (colors_p && img->ncolors)
1623 /* MAC_TODO: color table support. */
1624 /* W32_TODO: color table support. */
1625 #ifdef HAVE_X_WINDOWS
1626 x_free_colors (f, img->colors, img->ncolors);
1627 #endif /* HAVE_X_WINDOWS */
1628 xfree (img->colors);
1629 img->colors = NULL;
1630 img->ncolors = 0;
1633 #if defined (MAC_OS) && USE_CG_DRAWING
1634 if (img->data.ptr_val)
1636 CGImageRelease (img->data.ptr_val);
1637 img->data.ptr_val = NULL;
1639 #endif
1642 /* Free X resources of image IMG which is used on frame F. */
1644 static void
1645 x_clear_image (f, img)
1646 struct frame *f;
1647 struct image *img;
1649 BLOCK_INPUT;
1650 x_clear_image_1 (f, img, 1, 1, 1);
1651 UNBLOCK_INPUT;
1655 /* Allocate color COLOR_NAME for image IMG on frame F. If color
1656 cannot be allocated, use DFLT. Add a newly allocated color to
1657 IMG->colors, so that it can be freed again. Value is the pixel
1658 color. */
1660 static unsigned long
1661 x_alloc_image_color (f, img, color_name, dflt)
1662 struct frame *f;
1663 struct image *img;
1664 Lisp_Object color_name;
1665 unsigned long dflt;
1667 XColor color;
1668 unsigned long result;
1670 xassert (STRINGP (color_name));
1672 if (x_defined_color (f, SDATA (color_name), &color, 1))
1674 /* This isn't called frequently so we get away with simply
1675 reallocating the color vector to the needed size, here. */
1676 ++img->ncolors;
1677 img->colors =
1678 (unsigned long *) xrealloc (img->colors,
1679 img->ncolors * sizeof *img->colors);
1680 img->colors[img->ncolors - 1] = color.pixel;
1681 result = color.pixel;
1683 else
1684 result = dflt;
1686 return result;
1691 /***********************************************************************
1692 Image Cache
1693 ***********************************************************************/
1695 static struct image *search_image_cache P_ ((struct frame *, Lisp_Object, unsigned));
1696 static void cache_image P_ ((struct frame *f, struct image *img));
1697 static void postprocess_image P_ ((struct frame *, struct image *));
1699 /* Return a new, initialized image cache that is allocated from the
1700 heap. Call free_image_cache to free an image cache. */
1702 struct image_cache *
1703 make_image_cache ()
1705 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1706 int size;
1708 bzero (c, sizeof *c);
1709 c->size = 50;
1710 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1711 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1712 c->buckets = (struct image **) xmalloc (size);
1713 bzero (c->buckets, size);
1714 return c;
1718 /* Find an image matching SPEC in the cache, and return it. If no
1719 image is found, return NULL. */
1720 static struct image *
1721 search_image_cache (f, spec, hash)
1722 struct frame *f;
1723 Lisp_Object spec;
1724 unsigned hash;
1726 struct image *img;
1727 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1728 int i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1730 if (!c) return NULL;
1732 /* If the image spec does not specify a background color, the cached
1733 image must have the same background color as the current frame.
1734 The foreground color must also match, for the sake of monochrome
1735 images.
1737 In fact, we could ignore the foreground color matching condition
1738 for color images, or if the image spec specifies :foreground;
1739 similarly we could ignore the background color matching condition
1740 for formats that don't use transparency (such as jpeg), or if the
1741 image spec specifies :background. However, the extra memory
1742 usage is probably negligible in practice, so we don't bother. */
1744 for (img = c->buckets[i]; img; img = img->next)
1745 if (img->hash == hash
1746 && !NILP (Fequal (img->spec, spec))
1747 && img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
1748 && img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1749 break;
1750 return img;
1754 /* Search frame F for an image with spec SPEC, and free it. */
1756 static void
1757 uncache_image (f, spec)
1758 struct frame *f;
1759 Lisp_Object spec;
1761 struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
1762 if (img)
1763 free_image (f, img);
1767 /* Free image cache of frame F. Be aware that X frames share images
1768 caches. */
1770 void
1771 free_image_cache (f)
1772 struct frame *f;
1774 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1775 if (c)
1777 int i;
1779 /* Cache should not be referenced by any frame when freed. */
1780 xassert (c->refcount == 0);
1782 for (i = 0; i < c->used; ++i)
1783 free_image (f, c->images[i]);
1784 xfree (c->images);
1785 xfree (c->buckets);
1786 xfree (c);
1787 FRAME_IMAGE_CACHE (f) = NULL;
1792 /* Clear image cache of frame F. FILTER=t means free all images.
1793 FILTER=nil means clear only images that haven't been
1794 displayed for some time.
1795 Else, only free the images which have FILTER in their `dependencies'.
1796 Should be called from time to time to reduce the number of loaded images.
1797 If image-cache-eviction-delay is non-nil, this frees images in the cache
1798 which weren't displayed for at least that many seconds. */
1800 void
1801 clear_image_cache (struct frame *f, Lisp_Object filter)
1803 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1805 if (c && (!NILP (filter) || INTEGERP (Vimage_cache_eviction_delay)))
1807 EMACS_TIME t;
1808 unsigned long old;
1809 int i, nfreed;
1811 EMACS_GET_TIME (t);
1812 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
1814 /* Block input so that we won't be interrupted by a SIGIO
1815 while being in an inconsistent state. */
1816 BLOCK_INPUT;
1818 for (i = nfreed = 0; i < c->used; ++i)
1820 struct image *img = c->images[i];
1821 if (img != NULL
1822 && (NILP (filter) ? img->timestamp < old
1823 : (EQ (Qt, filter)
1824 || !NILP (Fmember (filter, img->dependencies)))))
1826 free_image (f, img);
1827 ++nfreed;
1831 /* We may be clearing the image cache because, for example,
1832 Emacs was iconified for a longer period of time. In that
1833 case, current matrices may still contain references to
1834 images freed above. So, clear these matrices. */
1835 if (nfreed)
1837 Lisp_Object tail, frame;
1839 FOR_EACH_FRAME (tail, frame)
1841 struct frame *f = XFRAME (frame);
1842 if (FRAME_IMAGE_CACHE (f) == c)
1843 clear_current_matrices (f);
1846 ++windows_or_buffers_changed;
1849 UNBLOCK_INPUT;
1853 void
1854 clear_image_caches (Lisp_Object filter)
1856 /* FIXME: We want to do
1857 * struct terminal *t;
1858 * for (t = terminal_list; t; t = t->next_terminal)
1859 * clear_image_cache (t, filter); */
1860 Lisp_Object tail, frame;
1861 FOR_EACH_FRAME (tail, frame)
1862 if (FRAME_WINDOW_P (XFRAME (frame)))
1863 clear_image_cache (XFRAME (frame), filter);
1866 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1867 0, 1, 0,
1868 doc: /* Clear the image cache.
1869 FILTER nil or a frame means clear all images in the selected frame.
1870 FILTER t means clear the image caches of all frames.
1871 Anything else, means only clear those images which refer to FILTER,
1872 which is then usually a filename. */)
1873 (filter)
1874 Lisp_Object filter;
1876 if (!(EQ (filter, Qnil) || FRAMEP (filter)))
1877 clear_image_caches (filter);
1878 else
1879 clear_image_cache (check_x_frame (filter), Qt);
1881 return Qnil;
1885 DEFUN ("image-refresh", Fimage_refresh, Simage_refresh,
1886 1, 2, 0,
1887 doc: /* Refresh the image with specification SPEC on frame FRAME.
1888 If SPEC specifies an image file, the displayed image is updated with
1889 the current contents of that file.
1890 FRAME nil or omitted means use the selected frame.
1891 FRAME t means refresh the image on all frames. */)
1892 (spec, frame)
1893 Lisp_Object spec, frame;
1895 if (!valid_image_p (spec))
1896 error ("Invalid image specification");
1898 if (EQ (frame, Qt))
1900 Lisp_Object tail;
1901 FOR_EACH_FRAME (tail, frame)
1903 struct frame *f = XFRAME (frame);
1904 if (FRAME_WINDOW_P (f))
1905 uncache_image (f, spec);
1908 else
1909 uncache_image (check_x_frame (frame), spec);
1911 return Qnil;
1915 /* Compute masks and transform image IMG on frame F, as specified
1916 by the image's specification, */
1918 static void
1919 postprocess_image (f, img)
1920 struct frame *f;
1921 struct image *img;
1923 /* Manipulation of the image's mask. */
1924 if (img->pixmap)
1926 Lisp_Object conversion, spec;
1927 Lisp_Object mask;
1929 spec = img->spec;
1931 /* `:heuristic-mask t'
1932 `:mask heuristic'
1933 means build a mask heuristically.
1934 `:heuristic-mask (R G B)'
1935 `:mask (heuristic (R G B))'
1936 means build a mask from color (R G B) in the
1937 image.
1938 `:mask nil'
1939 means remove a mask, if any. */
1941 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1942 if (!NILP (mask))
1943 x_build_heuristic_mask (f, img, mask);
1944 else
1946 int found_p;
1948 mask = image_spec_value (spec, QCmask, &found_p);
1950 if (EQ (mask, Qheuristic))
1951 x_build_heuristic_mask (f, img, Qt);
1952 else if (CONSP (mask)
1953 && EQ (XCAR (mask), Qheuristic))
1955 if (CONSP (XCDR (mask)))
1956 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1957 else
1958 x_build_heuristic_mask (f, img, XCDR (mask));
1960 else if (NILP (mask) && found_p && img->mask)
1962 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1963 img->mask = NO_PIXMAP;
1968 /* Should we apply an image transformation algorithm? */
1969 conversion = image_spec_value (spec, QCconversion, NULL);
1970 if (EQ (conversion, Qdisabled))
1971 x_disable_image (f, img);
1972 else if (EQ (conversion, Qlaplace))
1973 x_laplace (f, img);
1974 else if (EQ (conversion, Qemboss))
1975 x_emboss (f, img);
1976 else if (CONSP (conversion)
1977 && EQ (XCAR (conversion), Qedge_detection))
1979 Lisp_Object tem;
1980 tem = XCDR (conversion);
1981 if (CONSP (tem))
1982 x_edge_detection (f, img,
1983 Fplist_get (tem, QCmatrix),
1984 Fplist_get (tem, QCcolor_adjustment));
1990 /* Return the id of image with Lisp specification SPEC on frame F.
1991 SPEC must be a valid Lisp image specification (see valid_image_p). */
1994 lookup_image (f, spec)
1995 struct frame *f;
1996 Lisp_Object spec;
1998 struct image_cache *c;
1999 struct image *img;
2000 unsigned hash;
2001 struct gcpro gcpro1;
2002 EMACS_TIME now;
2004 /* F must be a window-system frame, and SPEC must be a valid image
2005 specification. */
2006 xassert (FRAME_WINDOW_P (f));
2007 xassert (valid_image_p (spec));
2009 c = FRAME_IMAGE_CACHE (f);
2011 GCPRO1 (spec);
2013 /* Look up SPEC in the hash table of the image cache. */
2014 hash = sxhash (spec, 0);
2015 img = search_image_cache (f, spec, hash);
2016 if (img && img->load_failed_p)
2018 free_image (f, img);
2019 img = NULL;
2022 /* If not found, create a new image and cache it. */
2023 if (img == NULL)
2025 extern Lisp_Object Qpostscript;
2027 BLOCK_INPUT;
2028 img = make_image (spec, hash);
2029 cache_image (f, img);
2030 img->load_failed_p = img->type->load (f, img) == 0;
2031 img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
2032 img->frame_background = FRAME_BACKGROUND_PIXEL (f);
2034 /* If we can't load the image, and we don't have a width and
2035 height, use some arbitrary width and height so that we can
2036 draw a rectangle for it. */
2037 if (img->load_failed_p)
2039 Lisp_Object value;
2041 value = image_spec_value (spec, QCwidth, NULL);
2042 img->width = (INTEGERP (value)
2043 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
2044 value = image_spec_value (spec, QCheight, NULL);
2045 img->height = (INTEGERP (value)
2046 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
2048 else
2050 /* Handle image type independent image attributes
2051 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
2052 `:background COLOR'. */
2053 Lisp_Object ascent, margin, relief, bg;
2055 ascent = image_spec_value (spec, QCascent, NULL);
2056 if (INTEGERP (ascent))
2057 img->ascent = XFASTINT (ascent);
2058 else if (EQ (ascent, Qcenter))
2059 img->ascent = CENTERED_IMAGE_ASCENT;
2061 margin = image_spec_value (spec, QCmargin, NULL);
2062 if (INTEGERP (margin) && XINT (margin) >= 0)
2063 img->vmargin = img->hmargin = XFASTINT (margin);
2064 else if (CONSP (margin) && INTEGERP (XCAR (margin))
2065 && INTEGERP (XCDR (margin)))
2067 if (XINT (XCAR (margin)) > 0)
2068 img->hmargin = XFASTINT (XCAR (margin));
2069 if (XINT (XCDR (margin)) > 0)
2070 img->vmargin = XFASTINT (XCDR (margin));
2073 relief = image_spec_value (spec, QCrelief, NULL);
2074 if (INTEGERP (relief))
2076 img->relief = XINT (relief);
2077 img->hmargin += eabs (img->relief);
2078 img->vmargin += eabs (img->relief);
2081 if (! img->background_valid)
2083 bg = image_spec_value (img->spec, QCbackground, NULL);
2084 if (!NILP (bg))
2086 img->background
2087 = x_alloc_image_color (f, img, bg,
2088 FRAME_BACKGROUND_PIXEL (f));
2089 img->background_valid = 1;
2093 /* Do image transformations and compute masks, unless we
2094 don't have the image yet. */
2095 if (!EQ (*img->type->type, Qpostscript))
2096 postprocess_image (f, img);
2099 UNBLOCK_INPUT;
2102 /* We're using IMG, so set its timestamp to `now'. */
2103 EMACS_GET_TIME (now);
2104 img->timestamp = EMACS_SECS (now);
2106 UNGCPRO;
2108 /* Value is the image id. */
2109 return img->id;
2113 /* Cache image IMG in the image cache of frame F. */
2115 static void
2116 cache_image (f, img)
2117 struct frame *f;
2118 struct image *img;
2120 struct image_cache *c = FRAME_IMAGE_CACHE (f);
2121 int i;
2123 /* Find a free slot in c->images. */
2124 for (i = 0; i < c->used; ++i)
2125 if (c->images[i] == NULL)
2126 break;
2128 /* If no free slot found, maybe enlarge c->images. */
2129 if (i == c->used && c->used == c->size)
2131 c->size *= 2;
2132 c->images = (struct image **) xrealloc (c->images,
2133 c->size * sizeof *c->images);
2136 /* Add IMG to c->images, and assign IMG an id. */
2137 c->images[i] = img;
2138 img->id = i;
2139 if (i == c->used)
2140 ++c->used;
2142 /* Add IMG to the cache's hash table. */
2143 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
2144 img->next = c->buckets[i];
2145 if (img->next)
2146 img->next->prev = img;
2147 img->prev = NULL;
2148 c->buckets[i] = img;
2152 /* Call FN on every image in the image cache of frame F. Used to mark
2153 Lisp Objects in the image cache. */
2155 /* Mark Lisp objects in image IMG. */
2157 static void
2158 mark_image (img)
2159 struct image *img;
2161 mark_object (img->spec);
2162 mark_object (img->dependencies);
2164 if (!NILP (img->data.lisp_val))
2165 mark_object (img->data.lisp_val);
2169 void
2170 mark_image_cache (struct image_cache *c)
2172 if (c)
2174 int i;
2175 for (i = 0; i < c->used; ++i)
2176 if (c->images[i])
2177 mark_image (c->images[i]);
2183 /***********************************************************************
2184 X / MAC / W32 support code
2185 ***********************************************************************/
2187 #ifdef HAVE_NTGUI
2189 /* Macro for defining functions that will be loaded from image DLLs. */
2190 #define DEF_IMGLIB_FN(func) int (FAR CDECL *fn_##func)()
2192 /* Macro for loading those image functions from the library. */
2193 #define LOAD_IMGLIB_FN(lib,func) { \
2194 fn_##func = (void *) GetProcAddress (lib, #func); \
2195 if (!fn_##func) return 0; \
2198 /* Load a DLL implementing an image type.
2199 The `image-library-alist' variable associates a symbol,
2200 identifying an image type, to a list of possible filenames.
2201 The function returns NULL if no library could be loaded for
2202 the given image type, or if the library was previously loaded;
2203 else the handle of the DLL. */
2204 static HMODULE
2205 w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
2207 HMODULE library = NULL;
2209 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
2211 Lisp_Object dlls = Fassq (type, libraries);
2213 if (CONSP (dlls))
2214 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
2216 CHECK_STRING_CAR (dlls);
2217 if (library = LoadLibrary (SDATA (XCAR (dlls))))
2218 break;
2222 return library;
2225 #endif /* HAVE_NTGUI */
2227 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
2228 XImagePtr *, Pixmap *));
2229 static void x_destroy_x_image P_ ((XImagePtr));
2230 static void x_put_x_image P_ ((struct frame *, XImagePtr, Pixmap, int, int));
2233 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
2234 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
2235 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
2236 via xmalloc. Print error messages via image_error if an error
2237 occurs. Value is non-zero if successful.
2239 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
2240 should indicate the bit depth of the image. */
2242 static int
2243 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
2244 struct frame *f;
2245 int width, height, depth;
2246 XImagePtr *ximg;
2247 Pixmap *pixmap;
2249 #ifdef HAVE_X_WINDOWS
2250 Display *display = FRAME_X_DISPLAY (f);
2251 Window window = FRAME_X_WINDOW (f);
2252 Screen *screen = FRAME_X_SCREEN (f);
2254 xassert (interrupt_input_blocked);
2256 if (depth <= 0)
2257 depth = DefaultDepthOfScreen (screen);
2258 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
2259 depth, ZPixmap, 0, NULL, width, height,
2260 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
2261 if (*ximg == NULL)
2263 image_error ("Unable to allocate X image", Qnil, Qnil);
2264 return 0;
2267 /* Allocate image raster. */
2268 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
2270 /* Allocate a pixmap of the same size. */
2271 *pixmap = XCreatePixmap (display, window, width, height, depth);
2272 if (*pixmap == NO_PIXMAP)
2274 x_destroy_x_image (*ximg);
2275 *ximg = NULL;
2276 image_error ("Unable to create X pixmap", Qnil, Qnil);
2277 return 0;
2280 return 1;
2281 #endif /* HAVE_X_WINDOWS */
2283 #ifdef HAVE_NTGUI
2285 BITMAPINFOHEADER *header;
2286 HDC hdc;
2287 int scanline_width_bits;
2288 int remainder;
2289 int palette_colors = 0;
2291 if (depth == 0)
2292 depth = 24;
2294 if (depth != 1 && depth != 4 && depth != 8
2295 && depth != 16 && depth != 24 && depth != 32)
2297 image_error ("Invalid image bit depth specified", Qnil, Qnil);
2298 return 0;
2301 scanline_width_bits = width * depth;
2302 remainder = scanline_width_bits % 32;
2304 if (remainder)
2305 scanline_width_bits += 32 - remainder;
2307 /* Bitmaps with a depth less than 16 need a palette. */
2308 /* BITMAPINFO structure already contains the first RGBQUAD. */
2309 if (depth < 16)
2310 palette_colors = 1 << depth - 1;
2312 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
2313 if (*ximg == NULL)
2315 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
2316 return 0;
2319 header = &((*ximg)->info.bmiHeader);
2320 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
2321 header->biSize = sizeof (*header);
2322 header->biWidth = width;
2323 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2324 header->biPlanes = 1;
2325 header->biBitCount = depth;
2326 header->biCompression = BI_RGB;
2327 header->biClrUsed = palette_colors;
2329 /* TODO: fill in palette. */
2330 if (depth == 1)
2332 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2333 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2334 (*ximg)->info.bmiColors[0].rgbRed = 0;
2335 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2336 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2337 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2338 (*ximg)->info.bmiColors[1].rgbRed = 255;
2339 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2342 hdc = get_frame_dc (f);
2344 /* Create a DIBSection and raster array for the bitmap,
2345 and store its handle in *pixmap. */
2346 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2347 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2348 /* casting avoids a GCC warning */
2349 (void **)&((*ximg)->data), NULL, 0);
2351 /* Realize display palette and garbage all frames. */
2352 release_frame_dc (f, hdc);
2354 if (*pixmap == NULL)
2356 DWORD err = GetLastError ();
2357 Lisp_Object errcode;
2358 /* All system errors are < 10000, so the following is safe. */
2359 XSETINT (errcode, (int) err);
2360 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2361 x_destroy_x_image (*ximg);
2362 return 0;
2365 return 1;
2367 #endif /* HAVE_NTGUI */
2369 #ifdef MAC_OS
2370 Display *display = FRAME_X_DISPLAY (f);
2371 Window window = FRAME_X_WINDOW (f);
2373 xassert (interrupt_input_blocked);
2375 /* Allocate a pixmap of the same size. */
2376 *pixmap = XCreatePixmap (display, window, width, height, depth);
2377 if (*pixmap == NO_PIXMAP)
2379 *ximg = NULL;
2380 image_error ("Unable to create X pixmap", Qnil, Qnil);
2381 return 0;
2384 #if !USE_MAC_IMAGE_IO
2385 LockPixels (GetGWorldPixMap (*pixmap));
2386 #endif
2387 *ximg = *pixmap;
2388 return 1;
2390 #endif /* MAC_OS */
2394 /* Destroy XImage XIMG. Free XIMG->data. */
2396 static void
2397 x_destroy_x_image (ximg)
2398 XImagePtr ximg;
2400 xassert (interrupt_input_blocked);
2401 if (ximg)
2403 #ifdef HAVE_X_WINDOWS
2404 xfree (ximg->data);
2405 ximg->data = NULL;
2406 XDestroyImage (ximg);
2407 #endif /* HAVE_X_WINDOWS */
2408 #ifdef HAVE_NTGUI
2409 /* Data will be freed by DestroyObject. */
2410 ximg->data = NULL;
2411 xfree (ximg);
2412 #endif /* HAVE_NTGUI */
2413 #ifdef MAC_OS
2414 XDestroyImage (ximg);
2415 #endif /* MAC_OS */
2420 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2421 are width and height of both the image and pixmap. */
2423 static void
2424 x_put_x_image (f, ximg, pixmap, width, height)
2425 struct frame *f;
2426 XImagePtr ximg;
2427 Pixmap pixmap;
2428 int width, height;
2430 #ifdef HAVE_X_WINDOWS
2431 GC gc;
2433 xassert (interrupt_input_blocked);
2434 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2435 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2436 XFreeGC (FRAME_X_DISPLAY (f), gc);
2437 #endif /* HAVE_X_WINDOWS */
2439 #ifdef HAVE_NTGUI
2440 #if 0 /* I don't think this is necessary looking at where it is used. */
2441 HDC hdc = get_frame_dc (f);
2442 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2443 release_frame_dc (f, hdc);
2444 #endif
2445 #endif /* HAVE_NTGUI */
2447 #ifdef MAC_OS
2448 xassert (ximg == pixmap);
2449 #endif /* MAC_OS */
2453 /***********************************************************************
2454 File Handling
2455 ***********************************************************************/
2457 static unsigned char *slurp_file P_ ((char *, int *));
2460 /* Find image file FILE. Look in data-directory/images, then
2461 x-bitmap-file-path. Value is the encoded full name of the file
2462 found, or nil if not found. */
2464 Lisp_Object
2465 x_find_image_file (file)
2466 Lisp_Object file;
2468 Lisp_Object file_found, search_path;
2469 struct gcpro gcpro1, gcpro2;
2470 int fd;
2472 file_found = Qnil;
2473 /* TODO I think this should use something like image-load-path
2474 instead. Unfortunately, that can contain non-string elements. */
2475 search_path = Fcons (Fexpand_file_name (build_string ("images"),
2476 Vdata_directory),
2477 Vx_bitmap_file_path);
2478 GCPRO2 (file_found, search_path);
2480 /* Try to find FILE in data-directory/images, then x-bitmap-file-path. */
2481 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2483 if (fd == -1)
2484 file_found = Qnil;
2485 else
2487 file_found = ENCODE_FILE (file_found);
2488 close (fd);
2491 UNGCPRO;
2492 return file_found;
2496 /* Read FILE into memory. Value is a pointer to a buffer allocated
2497 with xmalloc holding FILE's contents. Value is null if an error
2498 occurred. *SIZE is set to the size of the file. */
2500 static unsigned char *
2501 slurp_file (file, size)
2502 char *file;
2503 int *size;
2505 FILE *fp = NULL;
2506 unsigned char *buf = NULL;
2507 struct stat st;
2509 if (stat (file, &st) == 0
2510 && (fp = fopen (file, "rb")) != NULL
2511 && (buf = (unsigned char *) xmalloc (st.st_size),
2512 fread (buf, 1, st.st_size, fp) == st.st_size))
2514 *size = st.st_size;
2515 fclose (fp);
2517 else
2519 if (fp)
2520 fclose (fp);
2521 if (buf)
2523 xfree (buf);
2524 buf = NULL;
2528 return buf;
2533 #ifdef MAC_OS
2535 /***********************************************************************
2536 MAC Image Load Functions
2537 ***********************************************************************/
2539 #if USE_MAC_IMAGE_IO
2540 static int
2541 image_load_image_io (f, img, type)
2542 struct frame *f;
2543 struct image *img;
2544 CFStringRef type;
2546 CFDictionaryRef options, src_props = NULL, props = NULL;
2547 CFStringRef keys[2];
2548 CFTypeRef values[2];
2549 Lisp_Object specified_file, specified_data;
2550 CGImageSourceRef source = NULL;
2551 size_t count;
2552 CGImageRef image = NULL;
2553 int loop_count = -1;
2554 double delay_time = -1.0;
2555 int width, height;
2556 XImagePtr ximg = NULL;
2557 CGContextRef context;
2558 CGRect rectangle;
2559 int has_alpha_p, gif_p;
2561 gif_p = UTTypeEqual (type, kUTTypeGIF);
2563 keys[0] = kCGImageSourceTypeIdentifierHint;
2564 values[0] = (CFTypeRef) type;
2565 keys[1] = kCGImageSourceShouldCache;
2566 values[1] = (CFTypeRef) kCFBooleanFalse;
2567 options = CFDictionaryCreate (NULL, (const void **) keys,
2568 (const void **) values,
2569 sizeof (keys) / sizeof (keys[0]),
2570 &kCFTypeDictionaryKeyCallBacks,
2571 &kCFTypeDictionaryValueCallBacks);
2572 if (options == NULL)
2574 image_error ("Error creating options for image `%s'", img->spec, Qnil);
2575 return 0;
2578 /* Open the file. */
2579 specified_file = image_spec_value (img->spec, QCfile, NULL);
2580 specified_data = image_spec_value (img->spec, QCdata, NULL);
2582 if (NILP (specified_data))
2584 Lisp_Object file;
2585 CFStringRef path;
2586 CFURLRef url;
2588 file = x_find_image_file (specified_file);
2589 if (!STRINGP (file))
2591 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2592 return 0;
2594 path = cfstring_create_with_utf8_cstring (SDATA (file));
2595 if (path)
2597 url = CFURLCreateWithFileSystemPath (NULL, path,
2598 kCFURLPOSIXPathStyle, 0);
2599 CFRelease (path);
2600 if (url)
2602 source = CGImageSourceCreateWithURL (url, NULL);
2603 CFRelease (url);
2607 else
2609 CFDataRef data = CFDataCreate (NULL, SDATA (specified_data),
2610 SBYTES (specified_data));
2612 if (data)
2614 source = CGImageSourceCreateWithData (data, options);
2615 CFRelease (data);
2618 CFRelease (options);
2620 if (source)
2622 CFStringRef real_type = CGImageSourceGetType (source);
2624 if (real_type && UTTypeEqual (type, real_type))
2625 src_props = CGImageSourceCopyProperties (source, NULL);
2626 if (src_props)
2628 EMACS_INT ino = 0;
2630 count = CGImageSourceGetCount (source);
2631 if (gif_p)
2633 Lisp_Object image = image_spec_value (img->spec, QCindex, NULL);
2635 if (INTEGERP (image))
2636 ino = XFASTINT (image);
2638 if (ino >= 0 && ino < count)
2640 props = CGImageSourceCopyPropertiesAtIndex (source, ino, NULL);
2641 if (props)
2642 image = CGImageSourceCreateImageAtIndex (source, ino, NULL);
2645 CFRelease (source);
2648 if (image == NULL)
2650 if (src_props)
2651 CFRelease (src_props);
2652 if (props)
2653 CFRelease (props);
2654 image_error ("Error reading image `%s'", img->spec, Qnil);
2655 return 0;
2657 else
2659 CFBooleanRef boolean;
2661 if (CFDictionaryGetValueIfPresent (props, kCGImagePropertyHasAlpha,
2662 (const void **) &boolean))
2663 has_alpha_p = CFBooleanGetValue (boolean);
2664 if (gif_p)
2666 CFDictionaryRef dict;
2667 CFNumberRef number;
2669 dict = CFDictionaryGetValue (src_props,
2670 kCGImagePropertyGIFDictionary);
2671 if (dict
2672 && CFDictionaryGetValueIfPresent (dict,
2673 kCGImagePropertyGIFLoopCount,
2674 (const void **) &number))
2675 CFNumberGetValue (number, kCFNumberIntType, &loop_count);
2677 dict = CFDictionaryGetValue (props, kCGImagePropertyGIFDictionary);
2678 if (dict
2679 && CFDictionaryGetValueIfPresent (dict,
2680 kCGImagePropertyGIFDelayTime,
2681 (const void **) &number))
2682 CFNumberGetValue (number, kCFNumberDoubleType, &delay_time);
2684 CFRelease (src_props);
2685 CFRelease (props);
2688 width = img->width = CGImageGetWidth (image);
2689 height = img->height = CGImageGetHeight (image);
2691 if (!check_image_size (f, width, height))
2693 CGImageRelease (image);
2694 image_error ("Invalid image size", Qnil, Qnil);
2695 return 0;
2698 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2700 CGImageRelease (image);
2701 image_error ("Out of memory (%s)", img->spec, Qnil);
2702 return 0;
2704 rectangle = CGRectMake (0, 0, width, height);
2706 context = CGBitmapContextCreate (ximg->data, ximg->width, ximg->height, 8,
2707 ximg->bytes_per_line,
2708 mac_cg_color_space_rgb,
2709 kCGImageAlphaNoneSkipFirst
2710 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1040
2711 | kCGBitmapByteOrder32Host
2712 #endif
2714 if (has_alpha_p)
2716 Lisp_Object specified_bg;
2717 XColor color;
2719 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2720 if (!STRINGP (specified_bg)
2721 || !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2723 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2724 color.red = RED16_FROM_ULONG (color.pixel);
2725 color.green = GREEN16_FROM_ULONG (color.pixel);
2726 color.blue = BLUE16_FROM_ULONG (color.pixel);
2728 CGContextSetRGBFillColor (context, color.red / 65535.0,
2729 color.green / 65535.0,
2730 color.blue / 65535.0, 1.0);
2731 CGContextFillRect (context, rectangle);
2733 CGContextDrawImage (context, rectangle, image);
2734 CGContextRelease (context);
2735 CGImageRelease (image);
2737 /* Save GIF image extension data for `image-extension-data'.
2738 Format is (count IMAGES
2739 0xff "NETSCAPE2.0" 0x00 DATA_SUB_BLOCK_FOR_LOOP_COUNT
2740 0xf9 GRAPHIC_CONTROL_EXTENSION_BLOCK). */
2741 if (gif_p)
2743 img->data.lisp_val = Qnil;
2744 if (delay_time >= 0)
2746 Lisp_Object gce = make_uninit_string (4);
2747 int centisec = delay_time * 100.0 + 0.5;
2749 /* Fill the delay time field. */
2750 SSET (gce, 1, centisec & 0xff);
2751 SSET (gce, 2, (centisec >> 8) & 0xff);
2752 /* We don't know about other fields. */
2753 SSET (gce, 0, 0);
2754 SSET (gce, 3, 0);
2755 img->data.lisp_val = Fcons (make_number (0xf9),
2756 Fcons (gce,
2757 img->data.lisp_val));
2759 if (loop_count >= 0)
2761 Lisp_Object data_sub_block = make_uninit_string (3);
2763 SSET (data_sub_block, 0, 0x01);
2764 SSET (data_sub_block, 1, loop_count & 0xff);
2765 SSET (data_sub_block, 2, (loop_count >> 8) & 0xff);
2766 img->data.lisp_val = Fcons (make_number (0),
2767 Fcons (data_sub_block,
2768 img->data.lisp_val));
2769 img->data.lisp_val = Fcons (make_number (0xff),
2770 Fcons (build_string ("NETSCAPE2.0"),
2771 img->data.lisp_val));
2773 if (count > 1)
2774 img->data.lisp_val = Fcons (Qcount,
2775 Fcons (make_number (count),
2776 img->data.lisp_val));
2779 /* Maybe fill in the background field while we have ximg handy. */
2780 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2781 IMAGE_BACKGROUND (img, f, ximg);
2783 /* Put the image into the pixmap. */
2784 x_put_x_image (f, ximg, img->pixmap, width, height);
2785 x_destroy_x_image (ximg);
2786 return 1;
2788 #else /* !USE_MAC_IMAGE_IO */
2789 static int image_load_quicktime P_ ((struct frame *, struct image *img,
2790 OSType));
2791 #ifdef MAC_OSX
2792 static int image_load_quartz2d P_ ((struct frame *, struct image *img, int));
2793 #endif
2795 static OSErr
2796 find_image_fsspec (specified_file, file, fss)
2797 Lisp_Object specified_file, *file;
2798 FSSpec *fss;
2800 OSErr err;
2801 AEDesc desc;
2803 *file = x_find_image_file (specified_file);
2804 if (!STRINGP (*file))
2805 return fnfErr; /* file or directory not found;
2806 incomplete pathname */
2807 /* Try to open the image file. */
2808 err = AECoercePtr (TYPE_FILE_NAME, SDATA (*file),
2809 SBYTES (*file), typeFSS, &desc);
2810 if (err == noErr)
2812 #if TARGET_API_MAC_CARBON
2813 err = AEGetDescData (&desc, fss, sizeof (FSSpec));
2814 #else
2815 *fss = *(FSSpec *)(*(desc.dataHandle));
2816 #endif
2817 AEDisposeDesc (&desc);
2819 return err;
2822 static int
2823 image_load_qt_1 (f, img, type, fss, dh)
2824 struct frame *f;
2825 struct image *img;
2826 OSType type;
2827 const FSSpec *fss;
2828 Handle dh;
2830 ComponentResult err;
2831 GraphicsImportComponent gi;
2832 Rect rect;
2833 int width, height;
2834 ImageDescriptionHandle desc_handle;
2835 short draw_all_pixels;
2836 Lisp_Object specified_bg;
2837 XColor color;
2838 XImagePtr ximg;
2839 RGBColor bg_color;
2841 err = OpenADefaultComponent (GraphicsImporterComponentType, type, &gi);
2842 if (err != noErr)
2844 image_error ("Cannot get importer component for `%s'", img->spec, Qnil);
2845 return 0;
2847 if (dh == NULL)
2849 /* read from file system spec */
2850 err = GraphicsImportSetDataFile (gi, fss);
2851 if (err != noErr)
2853 image_error ("Cannot set fsspec to graphics importer for '%s'",
2854 img->spec, Qnil);
2855 goto error;
2858 else
2860 /* read from data handle */
2861 err = GraphicsImportSetDataHandle (gi, dh);
2862 if (err != noErr)
2864 image_error ("Cannot set data handle to graphics importer for `%s'",
2865 img->spec, Qnil);
2866 goto error;
2869 err = GraphicsImportGetImageDescription (gi, &desc_handle);
2870 if (err != noErr || desc_handle == NULL)
2872 image_error ("Error reading `%s'", img->spec, Qnil);
2873 goto error;
2875 width = img->width = (*desc_handle)->width;
2876 height = img->height = (*desc_handle)->height;
2877 DisposeHandle ((Handle)desc_handle);
2879 if (!check_image_size (f, width, height))
2881 image_error ("Invalid image size", Qnil, Qnil);
2882 goto error;
2885 err = GraphicsImportDoesDrawAllPixels (gi, &draw_all_pixels);
2886 #if 0
2887 /* Don't check the error code here. It may have an undocumented
2888 value -32766. */
2889 if (err != noErr)
2891 image_error ("Error reading `%s'", img->spec, Qnil);
2892 goto error;
2894 #endif
2895 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2897 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2898 if (!STRINGP (specified_bg) ||
2899 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2901 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2902 color.red = RED16_FROM_ULONG (color.pixel);
2903 color.green = GREEN16_FROM_ULONG (color.pixel);
2904 color.blue = BLUE16_FROM_ULONG (color.pixel);
2908 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2909 goto error;
2910 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2912 CGrafPtr old_port;
2913 GDHandle old_gdh;
2915 GetGWorld (&old_port, &old_gdh);
2916 SetGWorld (ximg, NULL);
2917 bg_color.red = color.red;
2918 bg_color.green = color.green;
2919 bg_color.blue = color.blue;
2920 RGBBackColor (&bg_color);
2921 #if TARGET_API_MAC_CARBON
2922 GetPortBounds (ximg, &rect);
2923 EraseRect (&rect);
2924 #else
2925 EraseRect (&(ximg->portRect));
2926 #endif
2927 SetGWorld (old_port, old_gdh);
2929 GraphicsImportSetGWorld (gi, ximg, NULL);
2930 GraphicsImportDraw (gi);
2931 CloseComponent (gi);
2933 /* Maybe fill in the background field while we have ximg handy. */
2934 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2935 IMAGE_BACKGROUND (img, f, ximg);
2937 /* Put the image into the pixmap. */
2938 x_put_x_image (f, ximg, img->pixmap, width, height);
2939 x_destroy_x_image (ximg);
2940 return 1;
2942 error:
2943 CloseComponent (gi);
2944 return 0;
2948 /* Load an image using the QuickTime Graphics Importer.
2949 Note: The alpha channel does not work for PNG images. */
2950 static int
2951 image_load_quicktime (f, img, type)
2952 struct frame *f;
2953 struct image *img;
2954 OSType type;
2956 Lisp_Object specified_file;
2957 Lisp_Object specified_data;
2958 OSErr err;
2960 specified_file = image_spec_value (img->spec, QCfile, NULL);
2961 specified_data = image_spec_value (img->spec, QCdata, NULL);
2963 if (NILP (specified_data))
2965 /* Read from a file */
2966 Lisp_Object file;
2967 FSSpec fss;
2969 err = find_image_fsspec (specified_file, &file, &fss);
2970 if (err != noErr)
2972 if (err == fnfErr)
2973 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2974 else
2975 image_error ("Cannot open `%s'", file, Qnil);
2976 return 0;
2978 return image_load_qt_1 (f, img, type, &fss, NULL);
2980 else
2982 /* Memory source! */
2983 int success_p;
2984 Handle dh;
2986 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
2987 if (err != noErr)
2989 image_error ("Cannot allocate data handle for `%s'",
2990 img->spec, Qnil);
2991 return 0;
2993 success_p = image_load_qt_1 (f, img, type, NULL, dh);
2994 DisposeHandle (dh);
2995 return success_p;
3000 #ifdef MAC_OSX
3001 static int
3002 image_load_quartz2d (f, img, png_p)
3003 struct frame *f;
3004 struct image *img;
3005 int png_p;
3007 Lisp_Object file, specified_file;
3008 Lisp_Object specified_data, specified_bg;
3009 struct gcpro gcpro1;
3010 CGDataProviderRef source;
3011 CGImageRef image;
3012 int width, height;
3013 XColor color;
3014 XImagePtr ximg = NULL;
3015 CGContextRef context;
3016 CGRect rectangle;
3018 /* Open the file. */
3019 specified_file = image_spec_value (img->spec, QCfile, NULL);
3020 specified_data = image_spec_value (img->spec, QCdata, NULL);
3022 file = Qnil;
3023 GCPRO1 (file);
3025 if (NILP (specified_data))
3027 CFStringRef path;
3028 CFURLRef url;
3030 file = x_find_image_file (specified_file);
3031 if (!STRINGP (file))
3033 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3034 UNGCPRO;
3035 return 0;
3037 path = cfstring_create_with_utf8_cstring (SDATA (file));
3038 url = CFURLCreateWithFileSystemPath (NULL, path,
3039 kCFURLPOSIXPathStyle, 0);
3040 CFRelease (path);
3041 source = CGDataProviderCreateWithURL (url);
3042 CFRelease (url);
3044 else
3045 source = CGDataProviderCreateWithData (NULL, SDATA (specified_data),
3046 SBYTES (specified_data), NULL);
3048 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
3049 if (png_p)
3050 image = CGImageCreateWithPNGDataProvider (source, NULL, false,
3051 kCGRenderingIntentDefault);
3052 else
3053 #endif
3054 image = CGImageCreateWithJPEGDataProvider (source, NULL, false,
3055 kCGRenderingIntentDefault);
3057 CGDataProviderRelease (source);
3058 if (image == NULL)
3060 UNGCPRO;
3061 image_error ("Error reading image `%s'", img->spec, Qnil);
3062 return 0;
3064 width = img->width = CGImageGetWidth (image);
3065 height = img->height = CGImageGetHeight (image);
3067 if (!check_image_size (f, width, height))
3069 CGImageRelease (image);
3070 UNGCPRO;
3071 image_error ("Invalid image size", Qnil, Qnil);
3072 return 0;
3075 if (png_p)
3077 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
3078 if (!STRINGP (specified_bg) ||
3079 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
3081 color.pixel = FRAME_BACKGROUND_PIXEL (f);
3082 color.red = RED16_FROM_ULONG (color.pixel);
3083 color.green = GREEN16_FROM_ULONG (color.pixel);
3084 color.blue = BLUE16_FROM_ULONG (color.pixel);
3088 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
3090 CGImageRelease (image);
3091 UNGCPRO;
3092 return 0;
3094 rectangle = CGRectMake (0, 0, width, height);
3095 QDBeginCGContext (ximg, &context);
3096 if (png_p)
3098 CGContextSetRGBFillColor (context, color.red / 65535.0,
3099 color.green / 65535.0,
3100 color.blue / 65535.0, 1.0);
3101 CGContextFillRect (context, rectangle);
3103 CGContextDrawImage (context, rectangle, image);
3104 QDEndCGContext (ximg, &context);
3105 CGImageRelease (image);
3107 /* Maybe fill in the background field while we have ximg handy. */
3108 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
3109 IMAGE_BACKGROUND (img, f, ximg);
3111 /* Put the image into the pixmap. */
3112 x_put_x_image (f, ximg, img->pixmap, width, height);
3113 x_destroy_x_image (ximg);
3114 UNGCPRO;
3115 return 1;
3117 #endif
3118 #endif /* !USE_MAC_IMAGE_IO */
3120 #endif /* MAC_OS */
3123 /***********************************************************************
3124 XBM images
3125 ***********************************************************************/
3127 static int xbm_scan P_ ((unsigned char **, unsigned char *, char *, int *));
3128 static int xbm_load P_ ((struct frame *f, struct image *img));
3129 static int xbm_load_image P_ ((struct frame *f, struct image *img,
3130 unsigned char *, unsigned char *));
3131 static int xbm_image_p P_ ((Lisp_Object object));
3132 static int xbm_read_bitmap_data P_ ((struct frame *f,
3133 unsigned char *, unsigned char *,
3134 int *, int *, unsigned char **));
3135 static int xbm_file_p P_ ((Lisp_Object));
3138 /* Indices of image specification fields in xbm_format, below. */
3140 enum xbm_keyword_index
3142 XBM_TYPE,
3143 XBM_FILE,
3144 XBM_WIDTH,
3145 XBM_HEIGHT,
3146 XBM_DATA,
3147 XBM_FOREGROUND,
3148 XBM_BACKGROUND,
3149 XBM_ASCENT,
3150 XBM_MARGIN,
3151 XBM_RELIEF,
3152 XBM_ALGORITHM,
3153 XBM_HEURISTIC_MASK,
3154 XBM_MASK,
3155 XBM_LAST
3158 /* Vector of image_keyword structures describing the format
3159 of valid XBM image specifications. */
3161 static struct image_keyword xbm_format[XBM_LAST] =
3163 {":type", IMAGE_SYMBOL_VALUE, 1},
3164 {":file", IMAGE_STRING_VALUE, 0},
3165 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
3166 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
3167 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3168 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
3169 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
3170 {":ascent", IMAGE_ASCENT_VALUE, 0},
3171 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3172 {":relief", IMAGE_INTEGER_VALUE, 0},
3173 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3174 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3175 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
3178 /* Structure describing the image type XBM. */
3180 static struct image_type xbm_type =
3182 &Qxbm,
3183 xbm_image_p,
3184 xbm_load,
3185 x_clear_image,
3186 NULL
3189 /* Tokens returned from xbm_scan. */
3191 enum xbm_token
3193 XBM_TK_IDENT = 256,
3194 XBM_TK_NUMBER
3198 /* Return non-zero if OBJECT is a valid XBM-type image specification.
3199 A valid specification is a list starting with the symbol `image'
3200 The rest of the list is a property list which must contain an
3201 entry `:type xbm..
3203 If the specification specifies a file to load, it must contain
3204 an entry `:file FILENAME' where FILENAME is a string.
3206 If the specification is for a bitmap loaded from memory it must
3207 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
3208 WIDTH and HEIGHT are integers > 0. DATA may be:
3210 1. a string large enough to hold the bitmap data, i.e. it must
3211 have a size >= (WIDTH + 7) / 8 * HEIGHT
3213 2. a bool-vector of size >= WIDTH * HEIGHT
3215 3. a vector of strings or bool-vectors, one for each line of the
3216 bitmap.
3218 4. a string containing an in-memory XBM file. WIDTH and HEIGHT
3219 may not be specified in this case because they are defined in the
3220 XBM file.
3222 Both the file and data forms may contain the additional entries
3223 `:background COLOR' and `:foreground COLOR'. If not present,
3224 foreground and background of the frame on which the image is
3225 displayed is used. */
3227 static int
3228 xbm_image_p (object)
3229 Lisp_Object object;
3231 struct image_keyword kw[XBM_LAST];
3233 bcopy (xbm_format, kw, sizeof kw);
3234 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
3235 return 0;
3237 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
3239 if (kw[XBM_FILE].count)
3241 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
3242 return 0;
3244 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
3246 /* In-memory XBM file. */
3247 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
3248 return 0;
3250 else
3252 Lisp_Object data;
3253 int width, height;
3255 /* Entries for `:width', `:height' and `:data' must be present. */
3256 if (!kw[XBM_WIDTH].count
3257 || !kw[XBM_HEIGHT].count
3258 || !kw[XBM_DATA].count)
3259 return 0;
3261 data = kw[XBM_DATA].value;
3262 width = XFASTINT (kw[XBM_WIDTH].value);
3263 height = XFASTINT (kw[XBM_HEIGHT].value);
3265 /* Check type of data, and width and height against contents of
3266 data. */
3267 if (VECTORP (data))
3269 int i;
3271 /* Number of elements of the vector must be >= height. */
3272 if (XVECTOR (data)->size < height)
3273 return 0;
3275 /* Each string or bool-vector in data must be large enough
3276 for one line of the image. */
3277 for (i = 0; i < height; ++i)
3279 Lisp_Object elt = XVECTOR (data)->contents[i];
3281 if (STRINGP (elt))
3283 if (SCHARS (elt)
3284 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
3285 return 0;
3287 else if (BOOL_VECTOR_P (elt))
3289 if (XBOOL_VECTOR (elt)->size < width)
3290 return 0;
3292 else
3293 return 0;
3296 else if (STRINGP (data))
3298 if (SCHARS (data)
3299 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
3300 return 0;
3302 else if (BOOL_VECTOR_P (data))
3304 if (XBOOL_VECTOR (data)->size < width * height)
3305 return 0;
3307 else
3308 return 0;
3311 return 1;
3315 /* Scan a bitmap file. FP is the stream to read from. Value is
3316 either an enumerator from enum xbm_token, or a character for a
3317 single-character token, or 0 at end of file. If scanning an
3318 identifier, store the lexeme of the identifier in SVAL. If
3319 scanning a number, store its value in *IVAL. */
3321 static int
3322 xbm_scan (s, end, sval, ival)
3323 unsigned char **s, *end;
3324 char *sval;
3325 int *ival;
3327 unsigned int c;
3329 loop:
3331 /* Skip white space. */
3332 while (*s < end && (c = *(*s)++, isspace (c)))
3335 if (*s >= end)
3336 c = 0;
3337 else if (isdigit (c))
3339 int value = 0, digit;
3341 if (c == '0' && *s < end)
3343 c = *(*s)++;
3344 if (c == 'x' || c == 'X')
3346 while (*s < end)
3348 c = *(*s)++;
3349 if (isdigit (c))
3350 digit = c - '0';
3351 else if (c >= 'a' && c <= 'f')
3352 digit = c - 'a' + 10;
3353 else if (c >= 'A' && c <= 'F')
3354 digit = c - 'A' + 10;
3355 else
3356 break;
3357 value = 16 * value + digit;
3360 else if (isdigit (c))
3362 value = c - '0';
3363 while (*s < end
3364 && (c = *(*s)++, isdigit (c)))
3365 value = 8 * value + c - '0';
3368 else
3370 value = c - '0';
3371 while (*s < end
3372 && (c = *(*s)++, isdigit (c)))
3373 value = 10 * value + c - '0';
3376 if (*s < end)
3377 *s = *s - 1;
3378 *ival = value;
3379 c = XBM_TK_NUMBER;
3381 else if (isalpha (c) || c == '_')
3383 *sval++ = c;
3384 while (*s < end
3385 && (c = *(*s)++, (isalnum (c) || c == '_')))
3386 *sval++ = c;
3387 *sval = 0;
3388 if (*s < end)
3389 *s = *s - 1;
3390 c = XBM_TK_IDENT;
3392 else if (c == '/' && **s == '*')
3394 /* C-style comment. */
3395 ++*s;
3396 while (**s && (**s != '*' || *(*s + 1) != '/'))
3397 ++*s;
3398 if (**s)
3400 *s += 2;
3401 goto loop;
3405 return c;
3408 #ifdef HAVE_NTGUI
3410 /* Create a Windows bitmap from X bitmap data. */
3411 static HBITMAP
3412 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
3414 static unsigned char swap_nibble[16]
3415 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
3416 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
3417 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
3418 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
3419 int i, j, w1, w2;
3420 unsigned char *bits, *p;
3421 HBITMAP bmp;
3423 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
3424 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
3425 bits = (unsigned char *) alloca (height * w2);
3426 bzero (bits, height * w2);
3427 for (i = 0; i < height; i++)
3429 p = bits + i*w2;
3430 for (j = 0; j < w1; j++)
3432 /* Bitswap XBM bytes to match how Windows does things. */
3433 unsigned char c = *data++;
3434 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
3435 | (swap_nibble[(c>>4) & 0xf]));
3438 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
3440 return bmp;
3443 static void
3444 convert_mono_to_color_image (f, img, foreground, background)
3445 struct frame *f;
3446 struct image *img;
3447 COLORREF foreground, background;
3449 HDC hdc, old_img_dc, new_img_dc;
3450 HGDIOBJ old_prev, new_prev;
3451 HBITMAP new_pixmap;
3453 hdc = get_frame_dc (f);
3454 old_img_dc = CreateCompatibleDC (hdc);
3455 new_img_dc = CreateCompatibleDC (hdc);
3456 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
3457 release_frame_dc (f, hdc);
3458 old_prev = SelectObject (old_img_dc, img->pixmap);
3459 new_prev = SelectObject (new_img_dc, new_pixmap);
3460 /* Windows convention for mono bitmaps is black = background,
3461 white = foreground. */
3462 SetTextColor (new_img_dc, background);
3463 SetBkColor (new_img_dc, foreground);
3465 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
3466 0, 0, SRCCOPY);
3468 SelectObject (old_img_dc, old_prev);
3469 SelectObject (new_img_dc, new_prev);
3470 DeleteDC (old_img_dc);
3471 DeleteDC (new_img_dc);
3472 DeleteObject (img->pixmap);
3473 if (new_pixmap == 0)
3474 fprintf (stderr, "Failed to convert image to color.\n");
3475 else
3476 img->pixmap = new_pixmap;
3479 #define XBM_BIT_SHUFFLE(b) (~(b))
3481 #else
3483 #define XBM_BIT_SHUFFLE(b) (b)
3485 #endif /* HAVE_NTGUI */
3488 static void
3489 Create_Pixmap_From_Bitmap_Data (f, img, data, fg, bg, non_default_colors)
3490 struct frame *f;
3491 struct image *img;
3492 char *data;
3493 RGB_PIXEL_COLOR fg, bg;
3494 int non_default_colors;
3496 #ifdef HAVE_NTGUI
3497 img->pixmap
3498 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
3500 /* If colors were specified, transfer the bitmap to a color one. */
3501 if (non_default_colors)
3502 convert_mono_to_color_image (f, img, fg, bg);
3503 #else
3504 img->pixmap
3505 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
3506 FRAME_X_WINDOW (f),
3507 data,
3508 img->width, img->height,
3509 fg, bg,
3510 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
3511 #endif /* HAVE_NTGUI */
3516 /* Replacement for XReadBitmapFileData which isn't available under old
3517 X versions. CONTENTS is a pointer to a buffer to parse; END is the
3518 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
3519 the image. Return in *DATA the bitmap data allocated with xmalloc.
3520 Value is non-zero if successful. DATA null means just test if
3521 CONTENTS looks like an in-memory XBM file. */
3523 static int
3524 xbm_read_bitmap_data (f, contents, end, width, height, data)
3525 struct frame *f;
3526 unsigned char *contents, *end;
3527 int *width, *height;
3528 unsigned char **data;
3530 unsigned char *s = contents;
3531 char buffer[BUFSIZ];
3532 int padding_p = 0;
3533 int v10 = 0;
3534 int bytes_per_line, i, nbytes;
3535 unsigned char *p;
3536 int value;
3537 int LA1;
3539 #define match() \
3540 LA1 = xbm_scan (&s, end, buffer, &value)
3542 #define expect(TOKEN) \
3543 if (LA1 != (TOKEN)) \
3544 goto failure; \
3545 else \
3546 match ()
3548 #define expect_ident(IDENT) \
3549 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
3550 match (); \
3551 else \
3552 goto failure
3554 *width = *height = -1;
3555 if (data)
3556 *data = NULL;
3557 LA1 = xbm_scan (&s, end, buffer, &value);
3559 /* Parse defines for width, height and hot-spots. */
3560 while (LA1 == '#')
3562 match ();
3563 expect_ident ("define");
3564 expect (XBM_TK_IDENT);
3566 if (LA1 == XBM_TK_NUMBER)
3568 char *p = strrchr (buffer, '_');
3569 p = p ? p + 1 : buffer;
3570 if (strcmp (p, "width") == 0)
3571 *width = value;
3572 else if (strcmp (p, "height") == 0)
3573 *height = value;
3575 expect (XBM_TK_NUMBER);
3578 if (!check_image_size (f, *width, *height))
3579 goto failure;
3580 else if (data == NULL)
3581 goto success;
3583 /* Parse bits. Must start with `static'. */
3584 expect_ident ("static");
3585 if (LA1 == XBM_TK_IDENT)
3587 if (strcmp (buffer, "unsigned") == 0)
3589 match ();
3590 expect_ident ("char");
3592 else if (strcmp (buffer, "short") == 0)
3594 match ();
3595 v10 = 1;
3596 if (*width % 16 && *width % 16 < 9)
3597 padding_p = 1;
3599 else if (strcmp (buffer, "char") == 0)
3600 match ();
3601 else
3602 goto failure;
3604 else
3605 goto failure;
3607 expect (XBM_TK_IDENT);
3608 expect ('[');
3609 expect (']');
3610 expect ('=');
3611 expect ('{');
3613 bytes_per_line = (*width + 7) / 8 + padding_p;
3614 nbytes = bytes_per_line * *height;
3615 p = *data = (unsigned char *) xmalloc (nbytes);
3617 if (v10)
3619 for (i = 0; i < nbytes; i += 2)
3621 int val = value;
3622 expect (XBM_TK_NUMBER);
3624 *p++ = XBM_BIT_SHUFFLE (val);
3625 if (!padding_p || ((i + 2) % bytes_per_line))
3626 *p++ = XBM_BIT_SHUFFLE (value >> 8);
3628 if (LA1 == ',' || LA1 == '}')
3629 match ();
3630 else
3631 goto failure;
3634 else
3636 for (i = 0; i < nbytes; ++i)
3638 int val = value;
3639 expect (XBM_TK_NUMBER);
3641 *p++ = XBM_BIT_SHUFFLE (val);
3643 if (LA1 == ',' || LA1 == '}')
3644 match ();
3645 else
3646 goto failure;
3650 success:
3651 return 1;
3653 failure:
3655 if (data && *data)
3657 xfree (*data);
3658 *data = NULL;
3660 return 0;
3662 #undef match
3663 #undef expect
3664 #undef expect_ident
3668 /* Load XBM image IMG which will be displayed on frame F from buffer
3669 CONTENTS. END is the end of the buffer. Value is non-zero if
3670 successful. */
3672 static int
3673 xbm_load_image (f, img, contents, end)
3674 struct frame *f;
3675 struct image *img;
3676 unsigned char *contents, *end;
3678 int rc;
3679 unsigned char *data;
3680 int success_p = 0;
3682 rc = xbm_read_bitmap_data (f, contents, end, &img->width, &img->height, &data);
3683 if (rc)
3685 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3686 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3687 int non_default_colors = 0;
3688 Lisp_Object value;
3690 xassert (img->width > 0 && img->height > 0);
3692 /* Get foreground and background colors, maybe allocate colors. */
3693 value = image_spec_value (img->spec, QCforeground, NULL);
3694 if (!NILP (value))
3696 foreground = x_alloc_image_color (f, img, value, foreground);
3697 non_default_colors = 1;
3699 value = image_spec_value (img->spec, QCbackground, NULL);
3700 if (!NILP (value))
3702 background = x_alloc_image_color (f, img, value, background);
3703 img->background = background;
3704 img->background_valid = 1;
3705 non_default_colors = 1;
3708 Create_Pixmap_From_Bitmap_Data (f, img, data,
3709 foreground, background,
3710 non_default_colors);
3711 xfree (data);
3713 if (img->pixmap == NO_PIXMAP)
3715 x_clear_image (f, img);
3716 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
3718 else
3719 success_p = 1;
3721 else
3722 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3724 return success_p;
3728 /* Value is non-zero if DATA looks like an in-memory XBM file. */
3730 static int
3731 xbm_file_p (data)
3732 Lisp_Object data;
3734 int w, h;
3735 return (STRINGP (data)
3736 && xbm_read_bitmap_data (NULL, SDATA (data),
3737 (SDATA (data)
3738 + SBYTES (data)),
3739 &w, &h, NULL));
3743 /* Fill image IMG which is used on frame F with pixmap data. Value is
3744 non-zero if successful. */
3746 static int
3747 xbm_load (f, img)
3748 struct frame *f;
3749 struct image *img;
3751 int success_p = 0;
3752 Lisp_Object file_name;
3754 xassert (xbm_image_p (img->spec));
3756 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3757 file_name = image_spec_value (img->spec, QCfile, NULL);
3758 if (STRINGP (file_name))
3760 Lisp_Object file;
3761 unsigned char *contents;
3762 int size;
3763 struct gcpro gcpro1;
3765 file = x_find_image_file (file_name);
3766 GCPRO1 (file);
3767 if (!STRINGP (file))
3769 image_error ("Cannot find image file `%s'", file_name, Qnil);
3770 UNGCPRO;
3771 return 0;
3774 contents = slurp_file (SDATA (file), &size);
3775 if (contents == NULL)
3777 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3778 UNGCPRO;
3779 return 0;
3782 success_p = xbm_load_image (f, img, contents, contents + size);
3783 UNGCPRO;
3785 else
3787 struct image_keyword fmt[XBM_LAST];
3788 Lisp_Object data;
3789 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3790 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3791 int non_default_colors = 0;
3792 char *bits;
3793 int parsed_p;
3794 int in_memory_file_p = 0;
3796 /* See if data looks like an in-memory XBM file. */
3797 data = image_spec_value (img->spec, QCdata, NULL);
3798 in_memory_file_p = xbm_file_p (data);
3800 /* Parse the image specification. */
3801 bcopy (xbm_format, fmt, sizeof fmt);
3802 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3803 xassert (parsed_p);
3805 /* Get specified width, and height. */
3806 if (!in_memory_file_p)
3808 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3809 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3810 xassert (img->width > 0 && img->height > 0);
3813 /* Get foreground and background colors, maybe allocate colors. */
3814 if (fmt[XBM_FOREGROUND].count
3815 && STRINGP (fmt[XBM_FOREGROUND].value))
3817 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3818 foreground);
3819 non_default_colors = 1;
3822 if (fmt[XBM_BACKGROUND].count
3823 && STRINGP (fmt[XBM_BACKGROUND].value))
3825 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3826 background);
3827 non_default_colors = 1;
3830 if (in_memory_file_p)
3831 success_p = xbm_load_image (f, img, SDATA (data),
3832 (SDATA (data)
3833 + SBYTES (data)));
3834 else
3836 if (VECTORP (data))
3838 int i;
3839 char *p;
3840 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3842 p = bits = (char *) alloca (nbytes * img->height);
3843 for (i = 0; i < img->height; ++i, p += nbytes)
3845 Lisp_Object line = XVECTOR (data)->contents[i];
3846 if (STRINGP (line))
3847 bcopy (SDATA (line), p, nbytes);
3848 else
3849 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
3852 else if (STRINGP (data))
3853 bits = SDATA (data);
3854 else
3855 bits = XBOOL_VECTOR (data)->data;
3857 #ifdef WINDOWSNT
3859 char *invertedBits;
3860 int nbytes, i;
3861 /* Windows mono bitmaps are reversed compared with X. */
3862 invertedBits = bits;
3863 nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR
3864 * img->height;
3865 bits = (char *) alloca(nbytes);
3866 for (i = 0; i < nbytes; i++)
3867 bits[i] = XBM_BIT_SHUFFLE (invertedBits[i]);
3869 #endif
3870 /* Create the pixmap. */
3872 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3873 foreground, background,
3874 non_default_colors);
3875 if (img->pixmap)
3876 success_p = 1;
3877 else
3879 image_error ("Unable to create pixmap for XBM image `%s'",
3880 img->spec, Qnil);
3881 x_clear_image (f, img);
3886 return success_p;
3891 /***********************************************************************
3892 XPM images
3893 ***********************************************************************/
3895 #if defined (HAVE_XPM) || defined (MAC_OS)
3897 static int xpm_image_p P_ ((Lisp_Object object));
3898 static int xpm_load P_ ((struct frame *f, struct image *img));
3899 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
3901 #endif /* HAVE_XPM || MAC_OS */
3903 #ifdef HAVE_XPM
3904 #ifdef HAVE_NTGUI
3905 /* Indicate to xpm.h that we don't have Xlib. */
3906 #define FOR_MSW
3907 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
3908 /* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
3909 #define XColor xpm_XColor
3910 #define XImage xpm_XImage
3911 #define Display xpm_Display
3912 #define PIXEL_ALREADY_TYPEDEFED
3913 #include "X11/xpm.h"
3914 #undef FOR_MSW
3915 #undef XColor
3916 #undef XImage
3917 #undef Display
3918 #undef PIXEL_ALREADY_TYPEDEFED
3919 #else
3920 #include "X11/xpm.h"
3921 #endif /* HAVE_NTGUI */
3922 #endif /* HAVE_XPM */
3924 #if defined (HAVE_XPM) || defined (MAC_OS)
3925 /* The symbol `xpm' identifying XPM-format images. */
3927 Lisp_Object Qxpm;
3929 /* Indices of image specification fields in xpm_format, below. */
3931 enum xpm_keyword_index
3933 XPM_TYPE,
3934 XPM_FILE,
3935 XPM_DATA,
3936 XPM_ASCENT,
3937 XPM_MARGIN,
3938 XPM_RELIEF,
3939 XPM_ALGORITHM,
3940 XPM_HEURISTIC_MASK,
3941 XPM_MASK,
3942 XPM_COLOR_SYMBOLS,
3943 XPM_BACKGROUND,
3944 XPM_LAST
3947 /* Vector of image_keyword structures describing the format
3948 of valid XPM image specifications. */
3950 static struct image_keyword xpm_format[XPM_LAST] =
3952 {":type", IMAGE_SYMBOL_VALUE, 1},
3953 {":file", IMAGE_STRING_VALUE, 0},
3954 {":data", IMAGE_STRING_VALUE, 0},
3955 {":ascent", IMAGE_ASCENT_VALUE, 0},
3956 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3957 {":relief", IMAGE_INTEGER_VALUE, 0},
3958 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3959 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3960 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3961 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3962 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3965 /* Structure describing the image type XPM. */
3967 static struct image_type xpm_type =
3969 &Qxpm,
3970 xpm_image_p,
3971 xpm_load,
3972 x_clear_image,
3973 NULL
3976 #ifdef HAVE_X_WINDOWS
3978 /* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3979 functions for allocating image colors. Our own functions handle
3980 color allocation failures more gracefully than the ones on the XPM
3981 lib. */
3983 #if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3984 #define ALLOC_XPM_COLORS
3985 #endif
3986 #endif /* HAVE_X_WINDOWS */
3988 #ifdef ALLOC_XPM_COLORS
3990 static void xpm_init_color_cache P_ ((struct frame *, XpmAttributes *));
3991 static void xpm_free_color_cache P_ ((void));
3992 static int xpm_lookup_color P_ ((struct frame *, char *, XColor *));
3993 static int xpm_color_bucket P_ ((char *));
3994 static struct xpm_cached_color *xpm_cache_color P_ ((struct frame *, char *,
3995 XColor *, int));
3997 /* An entry in a hash table used to cache color definitions of named
3998 colors. This cache is necessary to speed up XPM image loading in
3999 case we do color allocations ourselves. Without it, we would need
4000 a call to XParseColor per pixel in the image. */
4002 struct xpm_cached_color
4004 /* Next in collision chain. */
4005 struct xpm_cached_color *next;
4007 /* Color definition (RGB and pixel color). */
4008 XColor color;
4010 /* Color name. */
4011 char name[1];
4014 /* The hash table used for the color cache, and its bucket vector
4015 size. */
4017 #define XPM_COLOR_CACHE_BUCKETS 1001
4018 struct xpm_cached_color **xpm_color_cache;
4020 /* Initialize the color cache. */
4022 static void
4023 xpm_init_color_cache (f, attrs)
4024 struct frame *f;
4025 XpmAttributes *attrs;
4027 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
4028 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
4029 memset (xpm_color_cache, 0, nbytes);
4030 init_color_table ();
4032 if (attrs->valuemask & XpmColorSymbols)
4034 int i;
4035 XColor color;
4037 for (i = 0; i < attrs->numsymbols; ++i)
4038 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
4039 attrs->colorsymbols[i].value, &color))
4041 color.pixel = lookup_rgb_color (f, color.red, color.green,
4042 color.blue);
4043 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
4048 /* Free the color cache. */
4050 static void
4051 xpm_free_color_cache ()
4053 struct xpm_cached_color *p, *next;
4054 int i;
4056 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
4057 for (p = xpm_color_cache[i]; p; p = next)
4059 next = p->next;
4060 xfree (p);
4063 xfree (xpm_color_cache);
4064 xpm_color_cache = NULL;
4065 free_color_table ();
4068 /* Return the bucket index for color named COLOR_NAME in the color
4069 cache. */
4071 static int
4072 xpm_color_bucket (color_name)
4073 char *color_name;
4075 unsigned h = 0;
4076 char *s;
4078 for (s = color_name; *s; ++s)
4079 h = (h << 2) ^ *s;
4080 return h %= XPM_COLOR_CACHE_BUCKETS;
4084 /* On frame F, cache values COLOR for color with name COLOR_NAME.
4085 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
4086 entry added. */
4088 static struct xpm_cached_color *
4089 xpm_cache_color (f, color_name, color, bucket)
4090 struct frame *f;
4091 char *color_name;
4092 XColor *color;
4093 int bucket;
4095 size_t nbytes;
4096 struct xpm_cached_color *p;
4098 if (bucket < 0)
4099 bucket = xpm_color_bucket (color_name);
4101 nbytes = sizeof *p + strlen (color_name);
4102 p = (struct xpm_cached_color *) xmalloc (nbytes);
4103 strcpy (p->name, color_name);
4104 p->color = *color;
4105 p->next = xpm_color_cache[bucket];
4106 xpm_color_cache[bucket] = p;
4107 return p;
4110 /* Look up color COLOR_NAME for frame F in the color cache. If found,
4111 return the cached definition in *COLOR. Otherwise, make a new
4112 entry in the cache and allocate the color. Value is zero if color
4113 allocation failed. */
4115 static int
4116 xpm_lookup_color (f, color_name, color)
4117 struct frame *f;
4118 char *color_name;
4119 XColor *color;
4121 struct xpm_cached_color *p;
4122 int h = xpm_color_bucket (color_name);
4124 for (p = xpm_color_cache[h]; p; p = p->next)
4125 if (strcmp (p->name, color_name) == 0)
4126 break;
4128 if (p != NULL)
4129 *color = p->color;
4130 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
4131 color_name, color))
4133 color->pixel = lookup_rgb_color (f, color->red, color->green,
4134 color->blue);
4135 p = xpm_cache_color (f, color_name, color, h);
4137 /* You get `opaque' at least from ImageMagick converting pbm to xpm
4138 with transparency, and it's useful. */
4139 else if (strcmp ("opaque", color_name) == 0)
4141 bzero (color, sizeof (XColor)); /* Is this necessary/correct? */
4142 color->pixel = FRAME_FOREGROUND_PIXEL (f);
4143 p = xpm_cache_color (f, color_name, color, h);
4146 return p != NULL;
4150 /* Callback for allocating color COLOR_NAME. Called from the XPM lib.
4151 CLOSURE is a pointer to the frame on which we allocate the
4152 color. Return in *COLOR the allocated color. Value is non-zero
4153 if successful. */
4155 static int
4156 xpm_alloc_color (dpy, cmap, color_name, color, closure)
4157 Display *dpy;
4158 Colormap cmap;
4159 char *color_name;
4160 XColor *color;
4161 void *closure;
4163 return xpm_lookup_color ((struct frame *) closure, color_name, color);
4167 /* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
4168 is a pointer to the frame on which we allocate the color. Value is
4169 non-zero if successful. */
4171 static int
4172 xpm_free_colors (dpy, cmap, pixels, npixels, closure)
4173 Display *dpy;
4174 Colormap cmap;
4175 Pixel *pixels;
4176 int npixels;
4177 void *closure;
4179 return 1;
4182 #endif /* ALLOC_XPM_COLORS */
4185 #ifdef HAVE_NTGUI
4187 /* XPM library details. */
4189 DEF_IMGLIB_FN (XpmFreeAttributes);
4190 DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
4191 DEF_IMGLIB_FN (XpmReadFileToImage);
4192 DEF_IMGLIB_FN (XImageFree);
4194 static int
4195 init_xpm_functions (Lisp_Object libraries)
4197 HMODULE library;
4199 if (!(library = w32_delayed_load (libraries, Qxpm)))
4200 return 0;
4202 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
4203 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
4204 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
4205 LOAD_IMGLIB_FN (library, XImageFree);
4206 return 1;
4209 #endif /* HAVE_NTGUI */
4212 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
4213 for XPM images. Such a list must consist of conses whose car and
4214 cdr are strings. */
4216 static int
4217 xpm_valid_color_symbols_p (color_symbols)
4218 Lisp_Object color_symbols;
4220 while (CONSP (color_symbols))
4222 Lisp_Object sym = XCAR (color_symbols);
4223 if (!CONSP (sym)
4224 || !STRINGP (XCAR (sym))
4225 || !STRINGP (XCDR (sym)))
4226 break;
4227 color_symbols = XCDR (color_symbols);
4230 return NILP (color_symbols);
4234 /* Value is non-zero if OBJECT is a valid XPM image specification. */
4236 static int
4237 xpm_image_p (object)
4238 Lisp_Object object;
4240 struct image_keyword fmt[XPM_LAST];
4241 bcopy (xpm_format, fmt, sizeof fmt);
4242 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
4243 /* Either `:file' or `:data' must be present. */
4244 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
4245 /* Either no `:color-symbols' or it's a list of conses
4246 whose car and cdr are strings. */
4247 && (fmt[XPM_COLOR_SYMBOLS].count == 0
4248 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
4251 #endif /* HAVE_XPM || MAC_OS */
4253 #if defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
4255 x_create_bitmap_from_xpm_data (f, bits)
4256 struct frame *f;
4257 char **bits;
4259 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4260 int id, rc;
4261 XpmAttributes attrs;
4262 Pixmap bitmap, mask;
4264 bzero (&attrs, sizeof attrs);
4266 attrs.visual = FRAME_X_VISUAL (f);
4267 attrs.colormap = FRAME_X_COLORMAP (f);
4268 attrs.valuemask |= XpmVisual;
4269 attrs.valuemask |= XpmColormap;
4271 rc = XpmCreatePixmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4272 bits, &bitmap, &mask, &attrs);
4273 if (rc != XpmSuccess)
4275 XpmFreeAttributes (&attrs);
4276 return -1;
4279 id = x_allocate_bitmap_record (f);
4280 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
4281 dpyinfo->bitmaps[id - 1].have_mask = 1;
4282 dpyinfo->bitmaps[id - 1].mask = mask;
4283 dpyinfo->bitmaps[id - 1].file = NULL;
4284 dpyinfo->bitmaps[id - 1].height = attrs.height;
4285 dpyinfo->bitmaps[id - 1].width = attrs.width;
4286 dpyinfo->bitmaps[id - 1].depth = attrs.depth;
4287 dpyinfo->bitmaps[id - 1].refcount = 1;
4289 XpmFreeAttributes (&attrs);
4290 return id;
4292 #endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
4294 /* Load image IMG which will be displayed on frame F. Value is
4295 non-zero if successful. */
4297 #ifdef HAVE_XPM
4299 static int
4300 xpm_load (f, img)
4301 struct frame *f;
4302 struct image *img;
4304 int rc;
4305 XpmAttributes attrs;
4306 Lisp_Object specified_file, color_symbols;
4307 #ifdef HAVE_NTGUI
4308 HDC hdc;
4309 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
4310 #endif /* HAVE_NTGUI */
4312 /* Configure the XPM lib. Use the visual of frame F. Allocate
4313 close colors. Return colors allocated. */
4314 bzero (&attrs, sizeof attrs);
4316 #ifndef HAVE_NTGUI
4317 attrs.visual = FRAME_X_VISUAL (f);
4318 attrs.colormap = FRAME_X_COLORMAP (f);
4319 attrs.valuemask |= XpmVisual;
4320 attrs.valuemask |= XpmColormap;
4321 #endif /* HAVE_NTGUI */
4323 #ifdef ALLOC_XPM_COLORS
4324 /* Allocate colors with our own functions which handle
4325 failing color allocation more gracefully. */
4326 attrs.color_closure = f;
4327 attrs.alloc_color = xpm_alloc_color;
4328 attrs.free_colors = xpm_free_colors;
4329 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
4330 #else /* not ALLOC_XPM_COLORS */
4331 /* Let the XPM lib allocate colors. */
4332 attrs.valuemask |= XpmReturnAllocPixels;
4333 #ifdef XpmAllocCloseColors
4334 attrs.alloc_close_colors = 1;
4335 attrs.valuemask |= XpmAllocCloseColors;
4336 #else /* not XpmAllocCloseColors */
4337 attrs.closeness = 600;
4338 attrs.valuemask |= XpmCloseness;
4339 #endif /* not XpmAllocCloseColors */
4340 #endif /* ALLOC_XPM_COLORS */
4342 /* If image specification contains symbolic color definitions, add
4343 these to `attrs'. */
4344 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4345 if (CONSP (color_symbols))
4347 Lisp_Object tail;
4348 XpmColorSymbol *xpm_syms;
4349 int i, size;
4351 attrs.valuemask |= XpmColorSymbols;
4353 /* Count number of symbols. */
4354 attrs.numsymbols = 0;
4355 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
4356 ++attrs.numsymbols;
4358 /* Allocate an XpmColorSymbol array. */
4359 size = attrs.numsymbols * sizeof *xpm_syms;
4360 xpm_syms = (XpmColorSymbol *) alloca (size);
4361 bzero (xpm_syms, size);
4362 attrs.colorsymbols = xpm_syms;
4364 /* Fill the color symbol array. */
4365 for (tail = color_symbols, i = 0;
4366 CONSP (tail);
4367 ++i, tail = XCDR (tail))
4369 Lisp_Object name = XCAR (XCAR (tail));
4370 Lisp_Object color = XCDR (XCAR (tail));
4371 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
4372 strcpy (xpm_syms[i].name, SDATA (name));
4373 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
4374 strcpy (xpm_syms[i].value, SDATA (color));
4378 /* Create a pixmap for the image, either from a file, or from a
4379 string buffer containing data in the same format as an XPM file. */
4380 #ifdef ALLOC_XPM_COLORS
4381 xpm_init_color_cache (f, &attrs);
4382 #endif
4384 specified_file = image_spec_value (img->spec, QCfile, NULL);
4386 #ifdef HAVE_NTGUI
4388 HDC frame_dc = get_frame_dc (f);
4389 hdc = CreateCompatibleDC (frame_dc);
4390 release_frame_dc (f, frame_dc);
4392 #endif /* HAVE_NTGUI */
4394 if (STRINGP (specified_file))
4396 Lisp_Object file = x_find_image_file (specified_file);
4397 if (!STRINGP (file))
4399 image_error ("Cannot find image file `%s'", specified_file, Qnil);
4400 return 0;
4403 #ifdef HAVE_NTGUI
4404 /* XpmReadFileToPixmap is not available in the Windows port of
4405 libxpm. But XpmReadFileToImage almost does what we want. */
4406 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
4407 &xpm_image, &xpm_mask,
4408 &attrs);
4409 #else
4410 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4411 SDATA (file), &img->pixmap, &img->mask,
4412 &attrs);
4413 #endif /* HAVE_NTGUI */
4415 else
4417 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
4418 #ifdef HAVE_NTGUI
4419 /* XpmCreatePixmapFromBuffer is not available in the Windows port
4420 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
4421 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
4422 &xpm_image, &xpm_mask,
4423 &attrs);
4424 #else
4425 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4426 SDATA (buffer),
4427 &img->pixmap, &img->mask,
4428 &attrs);
4429 #endif /* HAVE_NTGUI */
4432 if (rc == XpmSuccess)
4434 #if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
4435 img->colors = colors_in_color_table (&img->ncolors);
4436 #else /* not ALLOC_XPM_COLORS */
4437 int i;
4439 #ifdef HAVE_NTGUI
4440 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
4441 plus some duplicate attributes. */
4442 if (xpm_image && xpm_image->bitmap)
4444 img->pixmap = xpm_image->bitmap;
4445 /* XImageFree in libXpm frees XImage struct without destroying
4446 the bitmap, which is what we want. */
4447 fn_XImageFree (xpm_image);
4449 if (xpm_mask && xpm_mask->bitmap)
4451 /* The mask appears to be inverted compared with what we expect.
4452 TODO: invert our expectations. See other places where we
4453 have to invert bits because our idea of masks is backwards. */
4454 HGDIOBJ old_obj;
4455 old_obj = SelectObject (hdc, xpm_mask->bitmap);
4457 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
4458 SelectObject (hdc, old_obj);
4460 img->mask = xpm_mask->bitmap;
4461 fn_XImageFree (xpm_mask);
4462 DeleteDC (hdc);
4465 DeleteDC (hdc);
4466 #endif /* HAVE_NTGUI */
4468 /* Remember allocated colors. */
4469 img->ncolors = attrs.nalloc_pixels;
4470 img->colors = (unsigned long *) xmalloc (img->ncolors
4471 * sizeof *img->colors);
4472 for (i = 0; i < attrs.nalloc_pixels; ++i)
4474 img->colors[i] = attrs.alloc_pixels[i];
4475 #ifdef DEBUG_X_COLORS
4476 register_color (img->colors[i]);
4477 #endif
4479 #endif /* not ALLOC_XPM_COLORS */
4481 img->width = attrs.width;
4482 img->height = attrs.height;
4483 xassert (img->width > 0 && img->height > 0);
4485 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
4486 #ifdef HAVE_NTGUI
4487 fn_XpmFreeAttributes (&attrs);
4488 #else
4489 XpmFreeAttributes (&attrs);
4490 #endif /* HAVE_NTGUI */
4492 else
4494 #ifdef HAVE_NTGUI
4495 DeleteDC (hdc);
4496 #endif /* HAVE_NTGUI */
4498 switch (rc)
4500 case XpmOpenFailed:
4501 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
4502 break;
4504 case XpmFileInvalid:
4505 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4506 break;
4508 case XpmNoMemory:
4509 image_error ("Out of memory (%s)", img->spec, Qnil);
4510 break;
4512 case XpmColorFailed:
4513 image_error ("Color allocation error (%s)", img->spec, Qnil);
4514 break;
4516 default:
4517 image_error ("Unknown error (%s)", img->spec, Qnil);
4518 break;
4522 #ifdef ALLOC_XPM_COLORS
4523 xpm_free_color_cache ();
4524 #endif
4525 return rc == XpmSuccess;
4528 #endif /* HAVE_XPM */
4530 #ifdef MAC_OS
4532 /* XPM support functions for Mac OS where libxpm is not available.
4533 Only XPM version 3 (without any extensions) is supported. */
4535 static int xpm_scan P_ ((const unsigned char **, const unsigned char *,
4536 const unsigned char **, int *));
4537 static Lisp_Object xpm_make_color_table_v
4538 P_ ((void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
4539 Lisp_Object (**) (Lisp_Object, const unsigned char *, int)));
4540 static void xpm_put_color_table_v P_ ((Lisp_Object, const unsigned char *,
4541 int, Lisp_Object));
4542 static Lisp_Object xpm_get_color_table_v P_ ((Lisp_Object,
4543 const unsigned char *, int));
4544 static Lisp_Object xpm_make_color_table_h
4545 P_ ((void (**) (Lisp_Object, const unsigned char *, int, Lisp_Object),
4546 Lisp_Object (**) (Lisp_Object, const unsigned char *, int)));
4547 static void xpm_put_color_table_h P_ ((Lisp_Object, const unsigned char *,
4548 int, Lisp_Object));
4549 static Lisp_Object xpm_get_color_table_h P_ ((Lisp_Object,
4550 const unsigned char *, int));
4551 static int xpm_str_to_color_key P_ ((const char *));
4552 static int xpm_load_image P_ ((struct frame *, struct image *,
4553 const unsigned char *, const unsigned char *));
4555 /* Tokens returned from xpm_scan. */
4557 enum xpm_token
4559 XPM_TK_IDENT = 256,
4560 XPM_TK_STRING,
4561 XPM_TK_EOF
4564 /* Scan an XPM data and return a character (< 256) or a token defined
4565 by enum xpm_token above. *S and END are the start (inclusive) and
4566 the end (exclusive) addresses of the data, respectively. Advance
4567 *S while scanning. If token is either XPM_TK_IDENT or
4568 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
4569 length of the corresponding token, respectively. */
4571 static int
4572 xpm_scan (s, end, beg, len)
4573 const unsigned char **s, *end, **beg;
4574 int *len;
4576 int c;
4578 while (*s < end)
4580 /* Skip white-space. */
4581 while (*s < end && (c = *(*s)++, isspace (c)))
4584 /* gnus-pointer.xpm uses '-' in its identifier.
4585 sb-dir-plus.xpm uses '+' in its identifier. */
4586 if (isalpha (c) || c == '_' || c == '-' || c == '+')
4588 *beg = *s - 1;
4589 while (*s < end
4590 && (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
4591 ++*s;
4592 *len = *s - *beg;
4593 return XPM_TK_IDENT;
4595 else if (c == '"')
4597 *beg = *s;
4598 while (*s < end && **s != '"')
4599 ++*s;
4600 *len = *s - *beg;
4601 if (*s < end)
4602 ++*s;
4603 return XPM_TK_STRING;
4605 else if (c == '/')
4607 if (*s < end && **s == '*')
4609 /* C-style comment. */
4610 ++*s;
4613 while (*s < end && *(*s)++ != '*')
4616 while (*s < end && **s != '/');
4617 if (*s < end)
4618 ++*s;
4620 else
4621 return c;
4623 else
4624 return c;
4627 return XPM_TK_EOF;
4630 /* Functions for color table lookup in XPM data. A key is a string
4631 specifying the color of each pixel in XPM data. A value is either
4632 an integer that specifies a pixel color, Qt that specifies
4633 transparency, or Qnil for the unspecified color. If the length of
4634 the key string is one, a vector is used as a table. Otherwise, a
4635 hash table is used. */
4637 static Lisp_Object
4638 xpm_make_color_table_v (put_func, get_func)
4639 void (**put_func) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4640 Lisp_Object (**get_func) (Lisp_Object, const unsigned char *, int);
4642 *put_func = xpm_put_color_table_v;
4643 *get_func = xpm_get_color_table_v;
4644 return Fmake_vector (make_number (256), Qnil);
4647 static void
4648 xpm_put_color_table_v (color_table, chars_start, chars_len, color)
4649 Lisp_Object color_table;
4650 const unsigned char *chars_start;
4651 int chars_len;
4652 Lisp_Object color;
4654 XVECTOR (color_table)->contents[*chars_start] = color;
4657 static Lisp_Object
4658 xpm_get_color_table_v (color_table, chars_start, chars_len)
4659 Lisp_Object color_table;
4660 const unsigned char *chars_start;
4661 int chars_len;
4663 return XVECTOR (color_table)->contents[*chars_start];
4666 static Lisp_Object
4667 xpm_make_color_table_h (put_func, get_func)
4668 void (**put_func) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4669 Lisp_Object (**get_func) (Lisp_Object, const unsigned char *, int);
4671 *put_func = xpm_put_color_table_h;
4672 *get_func = xpm_get_color_table_h;
4673 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
4674 make_float (DEFAULT_REHASH_SIZE),
4675 make_float (DEFAULT_REHASH_THRESHOLD),
4676 Qnil, Qnil, Qnil);
4679 static void
4680 xpm_put_color_table_h (color_table, chars_start, chars_len, color)
4681 Lisp_Object color_table;
4682 const unsigned char *chars_start;
4683 int chars_len;
4684 Lisp_Object color;
4686 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4687 unsigned hash_code;
4688 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4690 hash_lookup (table, chars, &hash_code);
4691 hash_put (table, chars, color, hash_code);
4694 static Lisp_Object
4695 xpm_get_color_table_h (color_table, chars_start, chars_len)
4696 Lisp_Object color_table;
4697 const unsigned char *chars_start;
4698 int chars_len;
4700 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4701 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
4702 NULL);
4704 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4707 enum xpm_color_key {
4708 XPM_COLOR_KEY_S,
4709 XPM_COLOR_KEY_M,
4710 XPM_COLOR_KEY_G4,
4711 XPM_COLOR_KEY_G,
4712 XPM_COLOR_KEY_C
4715 static const char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4717 static int
4718 xpm_str_to_color_key (s)
4719 const char *s;
4721 int i;
4723 for (i = 0;
4724 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
4725 i++)
4726 if (strcmp (xpm_color_key_strings[i], s) == 0)
4727 return i;
4728 return -1;
4731 static int
4732 xpm_load_image (f, img, contents, end)
4733 struct frame *f;
4734 struct image *img;
4735 const unsigned char *contents, *end;
4737 const unsigned char *s = contents, *beg, *str;
4738 unsigned char buffer[BUFSIZ];
4739 int width, height, x, y;
4740 int num_colors, chars_per_pixel;
4741 int len, LA1;
4742 void (*put_color_table) (Lisp_Object, const unsigned char *, int, Lisp_Object);
4743 Lisp_Object (*get_color_table) (Lisp_Object, const unsigned char *, int);
4744 Lisp_Object frame, color_symbols, color_table;
4745 int best_key, have_mask = 0;
4746 XImagePtr ximg = NULL, mask_img = NULL;
4748 #define match() \
4749 LA1 = xpm_scan (&s, end, &beg, &len)
4751 #define expect(TOKEN) \
4752 if (LA1 != (TOKEN)) \
4753 goto failure; \
4754 else \
4755 match ()
4757 #define expect_ident(IDENT) \
4758 if (LA1 == XPM_TK_IDENT \
4759 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4760 match (); \
4761 else \
4762 goto failure
4764 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4765 goto failure;
4766 s += 9;
4767 match();
4768 expect_ident ("static");
4769 expect_ident ("char");
4770 expect ('*');
4771 expect (XPM_TK_IDENT);
4772 expect ('[');
4773 expect (']');
4774 expect ('=');
4775 expect ('{');
4776 expect (XPM_TK_STRING);
4777 if (len >= BUFSIZ)
4778 goto failure;
4779 memcpy (buffer, beg, len);
4780 buffer[len] = '\0';
4781 if (sscanf (buffer, "%d %d %d %d", &width, &height,
4782 &num_colors, &chars_per_pixel) != 4
4783 || width <= 0 || height <= 0
4784 || num_colors <= 0 || chars_per_pixel <= 0)
4785 goto failure;
4787 if (!check_image_size (f, width, height))
4789 image_error ("Invalid image size", Qnil, Qnil);
4790 goto failure;
4793 expect (',');
4795 XSETFRAME (frame, f);
4796 if (!NILP (Fxw_display_color_p (frame)))
4797 best_key = XPM_COLOR_KEY_C;
4798 else if (!NILP (Fx_display_grayscale_p (frame)))
4799 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
4800 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
4801 else
4802 best_key = XPM_COLOR_KEY_M;
4804 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4805 if (chars_per_pixel == 1)
4806 color_table = xpm_make_color_table_v (&put_color_table,
4807 &get_color_table);
4808 else
4809 color_table = xpm_make_color_table_h (&put_color_table,
4810 &get_color_table);
4812 while (num_colors-- > 0)
4814 unsigned char *color, *max_color;
4815 int key, next_key, max_key = 0;
4816 Lisp_Object symbol_color = Qnil, color_val;
4817 XColor cdef;
4819 expect (XPM_TK_STRING);
4820 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
4821 goto failure;
4822 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4823 buffer[len - chars_per_pixel] = '\0';
4825 str = strtok (buffer, " \t");
4826 if (str == NULL)
4827 goto failure;
4828 key = xpm_str_to_color_key (str);
4829 if (key < 0)
4830 goto failure;
4833 color = strtok (NULL, " \t");
4834 if (color == NULL)
4835 goto failure;
4837 while ((str = strtok (NULL, " \t")) != NULL)
4839 next_key = xpm_str_to_color_key (str);
4840 if (next_key >= 0)
4841 break;
4842 color[strlen (color)] = ' ';
4845 if (key == XPM_COLOR_KEY_S)
4847 if (NILP (symbol_color))
4848 symbol_color = build_string (color);
4850 else if (max_key < key && key <= best_key)
4852 max_key = key;
4853 max_color = color;
4855 key = next_key;
4857 while (str);
4859 color_val = Qnil;
4860 if (!NILP (color_symbols) && !NILP (symbol_color))
4862 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4864 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4866 if (xstricmp (SDATA (XCDR (specified_color)), "None") == 0)
4867 color_val = Qt;
4868 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
4869 &cdef, 0))
4870 color_val = make_number (cdef.pixel);
4873 if (NILP (color_val) && max_key > 0)
4875 if (xstricmp (max_color, "None") == 0)
4876 color_val = Qt;
4877 else if (x_defined_color (f, max_color, &cdef, 0))
4878 color_val = make_number (cdef.pixel);
4880 if (!NILP (color_val))
4881 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
4883 expect (',');
4886 if (!x_create_x_image_and_pixmap (f, width, height, 0,
4887 &ximg, &img->pixmap)
4888 || !x_create_x_image_and_pixmap (f, width, height, 1,
4889 &mask_img, &img->mask))
4891 image_error ("Out of memory (%s)", img->spec, Qnil);
4892 goto error;
4895 for (y = 0; y < height; y++)
4897 expect (XPM_TK_STRING);
4898 str = beg;
4899 if (len < width * chars_per_pixel)
4900 goto failure;
4901 for (x = 0; x < width; x++, str += chars_per_pixel)
4903 Lisp_Object color_val =
4904 (*get_color_table) (color_table, str, chars_per_pixel);
4906 XPutPixel (ximg, x, y,
4907 (INTEGERP (color_val) ? XINT (color_val)
4908 : FRAME_FOREGROUND_PIXEL (f)));
4909 XPutPixel (mask_img, x, y,
4910 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4911 : (have_mask = 1, PIX_MASK_RETAIN)));
4913 if (y + 1 < height)
4914 expect (',');
4917 img->width = width;
4918 img->height = height;
4920 /* Maybe fill in the background field while we have ximg handy. */
4921 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
4922 IMAGE_BACKGROUND (img, f, ximg);
4924 x_put_x_image (f, ximg, img->pixmap, width, height);
4925 x_destroy_x_image (ximg);
4926 if (have_mask)
4928 /* Fill in the background_transparent field while we have the
4929 mask handy. */
4930 image_background_transparent (img, f, mask_img);
4932 x_put_x_image (f, mask_img, img->mask, width, height);
4933 x_destroy_x_image (mask_img);
4935 else
4937 x_destroy_x_image (mask_img);
4938 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4939 img->mask = NO_PIXMAP;
4942 return 1;
4944 failure:
4945 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4946 error:
4947 x_destroy_x_image (ximg);
4948 x_destroy_x_image (mask_img);
4949 x_clear_image (f, img);
4950 return 0;
4952 #undef match
4953 #undef expect
4954 #undef expect_ident
4957 static int
4958 xpm_load (f, img)
4959 struct frame *f;
4960 struct image *img;
4962 int success_p = 0;
4963 Lisp_Object file_name;
4965 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4966 file_name = image_spec_value (img->spec, QCfile, NULL);
4967 if (STRINGP (file_name))
4969 Lisp_Object file;
4970 unsigned char *contents;
4971 int size;
4972 struct gcpro gcpro1;
4974 file = x_find_image_file (file_name);
4975 GCPRO1 (file);
4976 if (!STRINGP (file))
4978 image_error ("Cannot find image file `%s'", file_name, Qnil);
4979 UNGCPRO;
4980 return 0;
4983 contents = slurp_file (SDATA (file), &size);
4984 if (contents == NULL)
4986 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4987 UNGCPRO;
4988 return 0;
4991 success_p = xpm_load_image (f, img, contents, contents + size);
4992 xfree (contents);
4993 UNGCPRO;
4995 else
4997 Lisp_Object data;
4999 data = image_spec_value (img->spec, QCdata, NULL);
5000 success_p = xpm_load_image (f, img, SDATA (data),
5001 SDATA (data) + SBYTES (data));
5004 return success_p;
5007 #endif /* MAC_OS */
5011 /***********************************************************************
5012 Color table
5013 ***********************************************************************/
5015 #ifdef COLOR_TABLE_SUPPORT
5017 /* An entry in the color table mapping an RGB color to a pixel color. */
5019 struct ct_color
5021 int r, g, b;
5022 unsigned long pixel;
5024 /* Next in color table collision list. */
5025 struct ct_color *next;
5028 /* The bucket vector size to use. Must be prime. */
5030 #define CT_SIZE 101
5032 /* Value is a hash of the RGB color given by R, G, and B. */
5034 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
5036 /* The color hash table. */
5038 struct ct_color **ct_table;
5040 /* Number of entries in the color table. */
5042 int ct_colors_allocated;
5044 /* Initialize the color table. */
5046 static void
5047 init_color_table ()
5049 int size = CT_SIZE * sizeof (*ct_table);
5050 ct_table = (struct ct_color **) xmalloc (size);
5051 bzero (ct_table, size);
5052 ct_colors_allocated = 0;
5056 /* Free memory associated with the color table. */
5058 static void
5059 free_color_table ()
5061 int i;
5062 struct ct_color *p, *next;
5064 for (i = 0; i < CT_SIZE; ++i)
5065 for (p = ct_table[i]; p; p = next)
5067 next = p->next;
5068 xfree (p);
5071 xfree (ct_table);
5072 ct_table = NULL;
5076 /* Value is a pixel color for RGB color R, G, B on frame F. If an
5077 entry for that color already is in the color table, return the
5078 pixel color of that entry. Otherwise, allocate a new color for R,
5079 G, B, and make an entry in the color table. */
5081 static unsigned long
5082 lookup_rgb_color (f, r, g, b)
5083 struct frame *f;
5084 int r, g, b;
5086 unsigned hash = CT_HASH_RGB (r, g, b);
5087 int i = hash % CT_SIZE;
5088 struct ct_color *p;
5089 Display_Info *dpyinfo;
5091 /* Handle TrueColor visuals specially, which improves performance by
5092 two orders of magnitude. Freeing colors on TrueColor visuals is
5093 a nop, and pixel colors specify RGB values directly. See also
5094 the Xlib spec, chapter 3.1. */
5095 dpyinfo = FRAME_X_DISPLAY_INFO (f);
5096 if (dpyinfo->red_bits > 0)
5098 unsigned long pr, pg, pb;
5100 /* Apply gamma-correction like normal color allocation does. */
5101 if (f->gamma)
5103 XColor color;
5104 color.red = r, color.green = g, color.blue = b;
5105 gamma_correct (f, &color);
5106 r = color.red, g = color.green, b = color.blue;
5109 /* Scale down RGB values to the visual's bits per RGB, and shift
5110 them to the right position in the pixel color. Note that the
5111 original RGB values are 16-bit values, as usual in X. */
5112 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
5113 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
5114 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
5116 /* Assemble the pixel color. */
5117 return pr | pg | pb;
5120 for (p = ct_table[i]; p; p = p->next)
5121 if (p->r == r && p->g == g && p->b == b)
5122 break;
5124 if (p == NULL)
5127 #ifdef HAVE_X_WINDOWS
5128 XColor color;
5129 Colormap cmap;
5130 int rc;
5132 color.red = r;
5133 color.green = g;
5134 color.blue = b;
5136 cmap = FRAME_X_COLORMAP (f);
5137 rc = x_alloc_nearest_color (f, cmap, &color);
5138 if (rc)
5140 ++ct_colors_allocated;
5141 p = (struct ct_color *) xmalloc (sizeof *p);
5142 p->r = r;
5143 p->g = g;
5144 p->b = b;
5145 p->pixel = color.pixel;
5146 p->next = ct_table[i];
5147 ct_table[i] = p;
5149 else
5150 return FRAME_FOREGROUND_PIXEL (f);
5152 #else
5153 COLORREF color;
5154 #ifdef HAVE_NTGUI
5155 color = PALETTERGB (r, g, b);
5156 #else
5157 color = RGB_TO_ULONG (r, g, b);
5158 #endif /* HAVE_NTGUI */
5159 ++ct_colors_allocated;
5160 p = (struct ct_color *) xmalloc (sizeof *p);
5161 p->r = r;
5162 p->g = g;
5163 p->b = b;
5164 p->pixel = color;
5165 p->next = ct_table[i];
5166 ct_table[i] = p;
5167 #endif /* HAVE_X_WINDOWS */
5171 return p->pixel;
5175 /* Look up pixel color PIXEL which is used on frame F in the color
5176 table. If not already present, allocate it. Value is PIXEL. */
5178 static unsigned long
5179 lookup_pixel_color (f, pixel)
5180 struct frame *f;
5181 unsigned long pixel;
5183 int i = pixel % CT_SIZE;
5184 struct ct_color *p;
5186 for (p = ct_table[i]; p; p = p->next)
5187 if (p->pixel == pixel)
5188 break;
5190 if (p == NULL)
5192 XColor color;
5193 Colormap cmap;
5194 int rc;
5196 #ifdef HAVE_X_WINDOWS
5197 cmap = FRAME_X_COLORMAP (f);
5198 color.pixel = pixel;
5199 x_query_color (f, &color);
5200 rc = x_alloc_nearest_color (f, cmap, &color);
5201 #else
5202 BLOCK_INPUT;
5203 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
5204 color.pixel = pixel;
5205 XQueryColor (NULL, cmap, &color);
5206 rc = x_alloc_nearest_color (f, cmap, &color);
5207 UNBLOCK_INPUT;
5208 #endif /* HAVE_X_WINDOWS */
5210 if (rc)
5212 ++ct_colors_allocated;
5214 p = (struct ct_color *) xmalloc (sizeof *p);
5215 p->r = color.red;
5216 p->g = color.green;
5217 p->b = color.blue;
5218 p->pixel = pixel;
5219 p->next = ct_table[i];
5220 ct_table[i] = p;
5222 else
5223 return FRAME_FOREGROUND_PIXEL (f);
5225 return p->pixel;
5229 /* Value is a vector of all pixel colors contained in the color table,
5230 allocated via xmalloc. Set *N to the number of colors. */
5232 static unsigned long *
5233 colors_in_color_table (n)
5234 int *n;
5236 int i, j;
5237 struct ct_color *p;
5238 unsigned long *colors;
5240 if (ct_colors_allocated == 0)
5242 *n = 0;
5243 colors = NULL;
5245 else
5247 colors = (unsigned long *) xmalloc (ct_colors_allocated
5248 * sizeof *colors);
5249 *n = ct_colors_allocated;
5251 for (i = j = 0; i < CT_SIZE; ++i)
5252 for (p = ct_table[i]; p; p = p->next)
5253 colors[j++] = p->pixel;
5256 return colors;
5259 #else /* COLOR_TABLE_SUPPORT */
5261 static unsigned long
5262 lookup_rgb_color (f, r, g, b)
5263 struct frame *f;
5264 int r, g, b;
5266 unsigned long pixel;
5268 #ifdef MAC_OS
5269 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
5270 gamma_correct (f, &pixel);
5271 #endif /* MAC_OS */
5273 #ifdef HAVE_NTGUI
5274 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
5275 #endif /* HAVE_NTGUI */
5277 return pixel;
5280 static void
5281 init_color_table ()
5284 #endif /* COLOR_TABLE_SUPPORT */
5287 /***********************************************************************
5288 Algorithms
5289 ***********************************************************************/
5291 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
5292 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
5293 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
5295 #ifdef HAVE_NTGUI
5296 static void XPutPixel (XImagePtr , int, int, COLORREF);
5297 #endif /* HAVE_NTGUI */
5299 /* Non-zero means draw a cross on images having `:conversion
5300 disabled'. */
5302 int cross_disabled_images;
5304 /* Edge detection matrices for different edge-detection
5305 strategies. */
5307 static int emboss_matrix[9] = {
5308 /* x - 1 x x + 1 */
5309 2, -1, 0, /* y - 1 */
5310 -1, 0, 1, /* y */
5311 0, 1, -2 /* y + 1 */
5314 static int laplace_matrix[9] = {
5315 /* x - 1 x x + 1 */
5316 1, 0, 0, /* y - 1 */
5317 0, 0, 0, /* y */
5318 0, 0, -1 /* y + 1 */
5321 /* Value is the intensity of the color whose red/green/blue values
5322 are R, G, and B. */
5324 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
5327 /* On frame F, return an array of XColor structures describing image
5328 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
5329 non-zero means also fill the red/green/blue members of the XColor
5330 structures. Value is a pointer to the array of XColors structures,
5331 allocated with xmalloc; it must be freed by the caller. */
5333 static XColor *
5334 x_to_xcolors (f, img, rgb_p)
5335 struct frame *f;
5336 struct image *img;
5337 int rgb_p;
5339 int x, y;
5340 XColor *colors, *p;
5341 XImagePtr_or_DC ximg;
5342 #ifdef HAVE_NTGUI
5343 HDC hdc;
5344 HGDIOBJ prev;
5345 #endif /* HAVE_NTGUI */
5347 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
5349 #ifndef HAVE_NTGUI
5350 /* Get the X image IMG->pixmap. */
5351 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
5352 0, 0, img->width, img->height, ~0, ZPixmap);
5353 #else
5354 /* Load the image into a memory device context. */
5355 hdc = get_frame_dc (f);
5356 ximg = CreateCompatibleDC (hdc);
5357 release_frame_dc (f, hdc);
5358 prev = SelectObject (ximg, img->pixmap);
5359 #endif /* HAVE_NTGUI */
5361 /* Fill the `pixel' members of the XColor array. I wished there
5362 were an easy and portable way to circumvent XGetPixel. */
5363 p = colors;
5364 for (y = 0; y < img->height; ++y)
5366 XColor *row = p;
5368 #ifdef HAVE_X_WINDOWS
5369 for (x = 0; x < img->width; ++x, ++p)
5370 p->pixel = XGetPixel (ximg, x, y);
5371 if (rgb_p)
5372 x_query_colors (f, row, img->width);
5374 #else
5376 for (x = 0; x < img->width; ++x, ++p)
5378 /* W32_TODO: palette support needed here? */
5379 p->pixel = GET_PIXEL (ximg, x, y);
5380 if (rgb_p)
5382 #ifdef MAC_OS
5383 p->red = RED16_FROM_ULONG (p->pixel);
5384 p->green = GREEN16_FROM_ULONG (p->pixel);
5385 p->blue = BLUE16_FROM_ULONG (p->pixel);
5386 #endif /* MAC_OS */
5387 #ifdef HAVE_NTGUI
5388 p->red = 256 * GetRValue (p->pixel);
5389 p->green = 256 * GetGValue (p->pixel);
5390 p->blue = 256 * GetBValue (p->pixel);
5391 #endif /* HAVE_NTGUI */
5394 #endif /* HAVE_X_WINDOWS */
5397 Destroy_Image (ximg, prev);
5399 return colors;
5402 #ifdef HAVE_NTGUI
5404 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
5405 created with CreateDIBSection, with the pointer to the bit values
5406 stored in ximg->data. */
5408 static void
5409 XPutPixel (ximg, x, y, color)
5410 XImagePtr ximg;
5411 int x, y;
5412 COLORREF color;
5414 int width = ximg->info.bmiHeader.biWidth;
5415 int height = ximg->info.bmiHeader.biHeight;
5416 unsigned char * pixel;
5418 /* True color images. */
5419 if (ximg->info.bmiHeader.biBitCount == 24)
5421 int rowbytes = width * 3;
5422 /* Ensure scanlines are aligned on 4 byte boundaries. */
5423 if (rowbytes % 4)
5424 rowbytes += 4 - (rowbytes % 4);
5426 pixel = ximg->data + y * rowbytes + x * 3;
5427 /* Windows bitmaps are in BGR order. */
5428 *pixel = GetBValue (color);
5429 *(pixel + 1) = GetGValue (color);
5430 *(pixel + 2) = GetRValue (color);
5432 /* Monochrome images. */
5433 else if (ximg->info.bmiHeader.biBitCount == 1)
5435 int rowbytes = width / 8;
5436 /* Ensure scanlines are aligned on 4 byte boundaries. */
5437 if (rowbytes % 4)
5438 rowbytes += 4 - (rowbytes % 4);
5439 pixel = ximg->data + y * rowbytes + x / 8;
5440 /* Filter out palette info. */
5441 if (color & 0x00ffffff)
5442 *pixel = *pixel | (1 << x % 8);
5443 else
5444 *pixel = *pixel & ~(1 << x % 8);
5446 else
5447 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
5450 #endif /* HAVE_NTGUI */
5452 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
5453 RGB members are set. F is the frame on which this all happens.
5454 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
5456 static void
5457 x_from_xcolors (f, img, colors)
5458 struct frame *f;
5459 struct image *img;
5460 XColor *colors;
5462 int x, y;
5463 XImagePtr oimg;
5464 Pixmap pixmap;
5465 XColor *p;
5467 init_color_table ();
5469 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
5470 &oimg, &pixmap);
5471 p = colors;
5472 for (y = 0; y < img->height; ++y)
5473 for (x = 0; x < img->width; ++x, ++p)
5475 unsigned long pixel;
5476 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
5477 XPutPixel (oimg, x, y, pixel);
5480 xfree (colors);
5481 x_clear_image_1 (f, img, 1, 0, 1);
5483 x_put_x_image (f, oimg, pixmap, img->width, img->height);
5484 x_destroy_x_image (oimg);
5485 img->pixmap = pixmap;
5486 #ifdef COLOR_TABLE_SUPPORT
5487 img->colors = colors_in_color_table (&img->ncolors);
5488 free_color_table ();
5489 #endif /* COLOR_TABLE_SUPPORT */
5493 /* On frame F, perform edge-detection on image IMG.
5495 MATRIX is a nine-element array specifying the transformation
5496 matrix. See emboss_matrix for an example.
5498 COLOR_ADJUST is a color adjustment added to each pixel of the
5499 outgoing image. */
5501 static void
5502 x_detect_edges (f, img, matrix, color_adjust)
5503 struct frame *f;
5504 struct image *img;
5505 int matrix[9], color_adjust;
5507 XColor *colors = x_to_xcolors (f, img, 1);
5508 XColor *new, *p;
5509 int x, y, i, sum;
5511 for (i = sum = 0; i < 9; ++i)
5512 sum += eabs (matrix[i]);
5514 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
5516 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
5518 for (y = 0; y < img->height; ++y)
5520 p = COLOR (new, 0, y);
5521 p->red = p->green = p->blue = 0xffff/2;
5522 p = COLOR (new, img->width - 1, y);
5523 p->red = p->green = p->blue = 0xffff/2;
5526 for (x = 1; x < img->width - 1; ++x)
5528 p = COLOR (new, x, 0);
5529 p->red = p->green = p->blue = 0xffff/2;
5530 p = COLOR (new, x, img->height - 1);
5531 p->red = p->green = p->blue = 0xffff/2;
5534 for (y = 1; y < img->height - 1; ++y)
5536 p = COLOR (new, 1, y);
5538 for (x = 1; x < img->width - 1; ++x, ++p)
5540 int r, g, b, y1, x1;
5542 r = g = b = i = 0;
5543 for (y1 = y - 1; y1 < y + 2; ++y1)
5544 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
5545 if (matrix[i])
5547 XColor *t = COLOR (colors, x1, y1);
5548 r += matrix[i] * t->red;
5549 g += matrix[i] * t->green;
5550 b += matrix[i] * t->blue;
5553 r = (r / sum + color_adjust) & 0xffff;
5554 g = (g / sum + color_adjust) & 0xffff;
5555 b = (b / sum + color_adjust) & 0xffff;
5556 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
5560 xfree (colors);
5561 x_from_xcolors (f, img, new);
5563 #undef COLOR
5567 /* Perform the pre-defined `emboss' edge-detection on image IMG
5568 on frame F. */
5570 static void
5571 x_emboss (f, img)
5572 struct frame *f;
5573 struct image *img;
5575 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
5579 /* Transform image IMG which is used on frame F with a Laplace
5580 edge-detection algorithm. The result is an image that can be used
5581 to draw disabled buttons, for example. */
5583 static void
5584 x_laplace (f, img)
5585 struct frame *f;
5586 struct image *img;
5588 x_detect_edges (f, img, laplace_matrix, 45000);
5592 /* Perform edge-detection on image IMG on frame F, with specified
5593 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
5595 MATRIX must be either
5597 - a list of at least 9 numbers in row-major form
5598 - a vector of at least 9 numbers
5600 COLOR_ADJUST nil means use a default; otherwise it must be a
5601 number. */
5603 static void
5604 x_edge_detection (f, img, matrix, color_adjust)
5605 struct frame *f;
5606 struct image *img;
5607 Lisp_Object matrix, color_adjust;
5609 int i = 0;
5610 int trans[9];
5612 if (CONSP (matrix))
5614 for (i = 0;
5615 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
5616 ++i, matrix = XCDR (matrix))
5617 trans[i] = XFLOATINT (XCAR (matrix));
5619 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
5621 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
5622 trans[i] = XFLOATINT (AREF (matrix, i));
5625 if (NILP (color_adjust))
5626 color_adjust = make_number (0xffff / 2);
5628 if (i == 9 && NUMBERP (color_adjust))
5629 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
5633 /* Transform image IMG on frame F so that it looks disabled. */
5635 static void
5636 x_disable_image (f, img)
5637 struct frame *f;
5638 struct image *img;
5640 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
5641 #ifdef HAVE_NTGUI
5642 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
5643 #else
5644 int n_planes = dpyinfo->n_planes;
5645 #endif /* HAVE_NTGUI */
5647 if (n_planes >= 2)
5649 /* Color (or grayscale). Convert to gray, and equalize. Just
5650 drawing such images with a stipple can look very odd, so
5651 we're using this method instead. */
5652 XColor *colors = x_to_xcolors (f, img, 1);
5653 XColor *p, *end;
5654 const int h = 15000;
5655 const int l = 30000;
5657 for (p = colors, end = colors + img->width * img->height;
5658 p < end;
5659 ++p)
5661 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
5662 int i2 = (0xffff - h - l) * i / 0xffff + l;
5663 p->red = p->green = p->blue = i2;
5666 x_from_xcolors (f, img, colors);
5669 /* Draw a cross over the disabled image, if we must or if we
5670 should. */
5671 if (n_planes < 2 || cross_disabled_images)
5673 #ifndef HAVE_NTGUI
5674 Display *dpy = FRAME_X_DISPLAY (f);
5675 GC gc;
5677 #ifdef MAC_OS
5678 #define MaskForeground(f) PIX_MASK_DRAW
5679 #else
5680 #define MaskForeground(f) WHITE_PIX_DEFAULT (f)
5681 #endif
5683 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
5684 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
5685 XDrawLine (dpy, img->pixmap, gc, 0, 0,
5686 img->width - 1, img->height - 1);
5687 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
5688 img->width - 1, 0);
5689 XFreeGC (dpy, gc);
5691 if (img->mask)
5693 gc = XCreateGC (dpy, img->mask, 0, NULL);
5694 XSetForeground (dpy, gc, MaskForeground (f));
5695 XDrawLine (dpy, img->mask, gc, 0, 0,
5696 img->width - 1, img->height - 1);
5697 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
5698 img->width - 1, 0);
5699 XFreeGC (dpy, gc);
5701 #else
5702 HDC hdc, bmpdc;
5703 HGDIOBJ prev;
5705 hdc = get_frame_dc (f);
5706 bmpdc = CreateCompatibleDC (hdc);
5707 release_frame_dc (f, hdc);
5709 prev = SelectObject (bmpdc, img->pixmap);
5711 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5712 MoveToEx (bmpdc, 0, 0, NULL);
5713 LineTo (bmpdc, img->width - 1, img->height - 1);
5714 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5715 LineTo (bmpdc, img->width - 1, 0);
5717 if (img->mask)
5719 SelectObject (bmpdc, img->mask);
5720 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5721 MoveToEx (bmpdc, 0, 0, NULL);
5722 LineTo (bmpdc, img->width - 1, img->height - 1);
5723 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5724 LineTo (bmpdc, img->width - 1, 0);
5726 SelectObject (bmpdc, prev);
5727 DeleteDC (bmpdc);
5728 #endif /* HAVE_NTGUI */
5733 /* Build a mask for image IMG which is used on frame F. FILE is the
5734 name of an image file, for error messages. HOW determines how to
5735 determine the background color of IMG. If it is a list '(R G B)',
5736 with R, G, and B being integers >= 0, take that as the color of the
5737 background. Otherwise, determine the background color of IMG
5738 heuristically. Value is non-zero if successful. */
5740 static int
5741 x_build_heuristic_mask (f, img, how)
5742 struct frame *f;
5743 struct image *img;
5744 Lisp_Object how;
5746 XImagePtr_or_DC ximg;
5747 #ifndef HAVE_NTGUI
5748 XImagePtr mask_img;
5749 #else
5750 HDC frame_dc;
5751 HGDIOBJ prev;
5752 char *mask_img;
5753 int row_width;
5754 #endif /* HAVE_NTGUI */
5755 int x, y, rc, use_img_background;
5756 unsigned long bg = 0;
5758 if (img->mask)
5760 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
5761 img->mask = NO_PIXMAP;
5762 img->background_transparent_valid = 0;
5765 #ifndef HAVE_NTGUI
5766 /* Create an image and pixmap serving as mask. */
5767 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
5768 &mask_img, &img->mask);
5769 if (!rc)
5770 return 0;
5772 /* Get the X image of IMG->pixmap. */
5773 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
5774 img->width, img->height,
5775 ~0, ZPixmap);
5776 #else
5777 /* Create the bit array serving as mask. */
5778 row_width = (img->width + 7) / 8;
5779 mask_img = xmalloc (row_width * img->height);
5780 bzero (mask_img, row_width * img->height);
5782 /* Create a memory device context for IMG->pixmap. */
5783 frame_dc = get_frame_dc (f);
5784 ximg = CreateCompatibleDC (frame_dc);
5785 release_frame_dc (f, frame_dc);
5786 prev = SelectObject (ximg, img->pixmap);
5787 #endif /* HAVE_NTGUI */
5789 /* Determine the background color of ximg. If HOW is `(R G B)'
5790 take that as color. Otherwise, use the image's background color. */
5791 use_img_background = 1;
5793 if (CONSP (how))
5795 int rgb[3], i;
5797 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5799 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5800 how = XCDR (how);
5803 if (i == 3 && NILP (how))
5805 char color_name[30];
5806 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
5807 bg = (
5808 #ifdef HAVE_NTGUI
5809 0x00ffffff & /* Filter out palette info. */
5810 #endif /* HAVE_NTGUI */
5811 x_alloc_image_color (f, img, build_string (color_name), 0));
5812 use_img_background = 0;
5816 if (use_img_background)
5817 bg = four_corners_best (ximg, img->corners, img->width, img->height);
5819 /* Set all bits in mask_img to 1 whose color in ximg is different
5820 from the background color bg. */
5821 #ifndef HAVE_NTGUI
5822 for (y = 0; y < img->height; ++y)
5823 for (x = 0; x < img->width; ++x)
5824 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
5825 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
5827 /* Fill in the background_transparent field while we have the mask handy. */
5828 image_background_transparent (img, f, mask_img);
5830 /* Put mask_img into img->mask. */
5831 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5832 x_destroy_x_image (mask_img);
5834 #else
5835 for (y = 0; y < img->height; ++y)
5836 for (x = 0; x < img->width; ++x)
5838 COLORREF p = GetPixel (ximg, x, y);
5839 if (p != bg)
5840 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5843 /* Create the mask image. */
5844 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5845 mask_img);
5846 /* Fill in the background_transparent field while we have the mask handy. */
5847 SelectObject (ximg, img->mask);
5848 image_background_transparent (img, f, ximg);
5850 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5851 xfree (mask_img);
5852 #endif /* HAVE_NTGUI */
5854 Destroy_Image (ximg, prev);
5856 return 1;
5860 /***********************************************************************
5861 PBM (mono, gray, color)
5862 ***********************************************************************/
5864 static int pbm_image_p P_ ((Lisp_Object object));
5865 static int pbm_load P_ ((struct frame *f, struct image *img));
5866 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
5868 /* The symbol `pbm' identifying images of this type. */
5870 Lisp_Object Qpbm;
5872 /* Indices of image specification fields in gs_format, below. */
5874 enum pbm_keyword_index
5876 PBM_TYPE,
5877 PBM_FILE,
5878 PBM_DATA,
5879 PBM_ASCENT,
5880 PBM_MARGIN,
5881 PBM_RELIEF,
5882 PBM_ALGORITHM,
5883 PBM_HEURISTIC_MASK,
5884 PBM_MASK,
5885 PBM_FOREGROUND,
5886 PBM_BACKGROUND,
5887 PBM_LAST
5890 /* Vector of image_keyword structures describing the format
5891 of valid user-defined image specifications. */
5893 static struct image_keyword pbm_format[PBM_LAST] =
5895 {":type", IMAGE_SYMBOL_VALUE, 1},
5896 {":file", IMAGE_STRING_VALUE, 0},
5897 {":data", IMAGE_STRING_VALUE, 0},
5898 {":ascent", IMAGE_ASCENT_VALUE, 0},
5899 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5900 {":relief", IMAGE_INTEGER_VALUE, 0},
5901 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5902 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5903 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5904 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5905 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5908 /* Structure describing the image type `pbm'. */
5910 static struct image_type pbm_type =
5912 &Qpbm,
5913 pbm_image_p,
5914 pbm_load,
5915 x_clear_image,
5916 NULL
5920 /* Return non-zero if OBJECT is a valid PBM image specification. */
5922 static int
5923 pbm_image_p (object)
5924 Lisp_Object object;
5926 struct image_keyword fmt[PBM_LAST];
5928 bcopy (pbm_format, fmt, sizeof fmt);
5930 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5931 return 0;
5933 /* Must specify either :data or :file. */
5934 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5938 /* Scan a decimal number from *S and return it. Advance *S while
5939 reading the number. END is the end of the string. Value is -1 at
5940 end of input. */
5942 static int
5943 pbm_scan_number (s, end)
5944 unsigned char **s, *end;
5946 int c = 0, val = -1;
5948 while (*s < end)
5950 /* Skip white-space. */
5951 while (*s < end && (c = *(*s)++, isspace (c)))
5954 if (c == '#')
5956 /* Skip comment to end of line. */
5957 while (*s < end && (c = *(*s)++, c != '\n'))
5960 else if (isdigit (c))
5962 /* Read decimal number. */
5963 val = c - '0';
5964 while (*s < end && (c = *(*s)++, isdigit (c)))
5965 val = 10 * val + c - '0';
5966 break;
5968 else
5969 break;
5972 return val;
5976 #ifdef HAVE_NTGUI
5977 #if 0 /* Unused. ++kfs */
5979 /* Read FILE into memory. Value is a pointer to a buffer allocated
5980 with xmalloc holding FILE's contents. Value is null if an error
5981 occurred. *SIZE is set to the size of the file. */
5983 static char *
5984 pbm_read_file (file, size)
5985 Lisp_Object file;
5986 int *size;
5988 FILE *fp = NULL;
5989 char *buf = NULL;
5990 struct stat st;
5992 if (stat (SDATA (file), &st) == 0
5993 && (fp = fopen (SDATA (file), "rb")) != NULL
5994 && (buf = (char *) xmalloc (st.st_size),
5995 fread (buf, 1, st.st_size, fp) == st.st_size))
5997 *size = st.st_size;
5998 fclose (fp);
6000 else
6002 if (fp)
6003 fclose (fp);
6004 if (buf)
6006 xfree (buf);
6007 buf = NULL;
6011 return buf;
6013 #endif
6014 #endif /* HAVE_NTGUI */
6016 /* Load PBM image IMG for use on frame F. */
6018 static int
6019 pbm_load (f, img)
6020 struct frame *f;
6021 struct image *img;
6023 int raw_p, x, y;
6024 int width, height, max_color_idx = 0;
6025 XImagePtr ximg;
6026 Lisp_Object file, specified_file;
6027 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
6028 struct gcpro gcpro1;
6029 unsigned char *contents = NULL;
6030 unsigned char *end, *p;
6031 int size;
6033 specified_file = image_spec_value (img->spec, QCfile, NULL);
6034 file = Qnil;
6035 GCPRO1 (file);
6037 if (STRINGP (specified_file))
6039 file = x_find_image_file (specified_file);
6040 if (!STRINGP (file))
6042 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6043 UNGCPRO;
6044 return 0;
6047 contents = slurp_file (SDATA (file), &size);
6048 if (contents == NULL)
6050 image_error ("Error reading `%s'", file, Qnil);
6051 UNGCPRO;
6052 return 0;
6055 p = contents;
6056 end = contents + size;
6058 else
6060 Lisp_Object data;
6061 data = image_spec_value (img->spec, QCdata, NULL);
6062 p = SDATA (data);
6063 end = p + SBYTES (data);
6066 /* Check magic number. */
6067 if (end - p < 2 || *p++ != 'P')
6069 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
6070 error:
6071 xfree (contents);
6072 UNGCPRO;
6073 return 0;
6076 switch (*p++)
6078 case '1':
6079 raw_p = 0, type = PBM_MONO;
6080 break;
6082 case '2':
6083 raw_p = 0, type = PBM_GRAY;
6084 break;
6086 case '3':
6087 raw_p = 0, type = PBM_COLOR;
6088 break;
6090 case '4':
6091 raw_p = 1, type = PBM_MONO;
6092 break;
6094 case '5':
6095 raw_p = 1, type = PBM_GRAY;
6096 break;
6098 case '6':
6099 raw_p = 1, type = PBM_COLOR;
6100 break;
6102 default:
6103 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
6104 goto error;
6107 /* Read width, height, maximum color-component. Characters
6108 starting with `#' up to the end of a line are ignored. */
6109 width = pbm_scan_number (&p, end);
6110 height = pbm_scan_number (&p, end);
6112 if (type != PBM_MONO)
6114 max_color_idx = pbm_scan_number (&p, end);
6115 if (max_color_idx > 65535 || max_color_idx < 0)
6117 image_error ("Unsupported maximum PBM color value", Qnil, Qnil);
6118 goto error;
6122 if (!check_image_size (f, width, height))
6124 image_error ("Invalid image size", Qnil, Qnil);
6125 goto error;
6128 if (!x_create_x_image_and_pixmap (f, width, height, 0,
6129 &ximg, &img->pixmap))
6130 goto error;
6132 /* Initialize the color hash table. */
6133 init_color_table ();
6135 if (type == PBM_MONO)
6137 int c = 0, g;
6138 struct image_keyword fmt[PBM_LAST];
6139 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
6140 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
6142 /* Parse the image specification. */
6143 bcopy (pbm_format, fmt, sizeof fmt);
6144 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
6146 /* Get foreground and background colors, maybe allocate colors. */
6147 if (fmt[PBM_FOREGROUND].count
6148 && STRINGP (fmt[PBM_FOREGROUND].value))
6149 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
6150 if (fmt[PBM_BACKGROUND].count
6151 && STRINGP (fmt[PBM_BACKGROUND].value))
6153 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
6154 img->background = bg;
6155 img->background_valid = 1;
6158 for (y = 0; y < height; ++y)
6159 for (x = 0; x < width; ++x)
6161 if (raw_p)
6163 if ((x & 7) == 0)
6165 if (p >= end)
6167 x_destroy_x_image (ximg);
6168 x_clear_image (f, img);
6169 image_error ("Invalid image size in image `%s'",
6170 img->spec, Qnil);
6171 goto error;
6173 c = *p++;
6175 g = c & 0x80;
6176 c <<= 1;
6178 else
6179 g = pbm_scan_number (&p, end);
6181 XPutPixel (ximg, x, y, g ? fg : bg);
6184 else
6186 int expected_size = height * width;
6187 if (max_color_idx > 255)
6188 expected_size *= 2;
6189 if (type == PBM_COLOR)
6190 expected_size *= 3;
6192 if (raw_p && p + expected_size > end)
6194 x_destroy_x_image (ximg);
6195 x_clear_image (f, img);
6196 image_error ("Invalid image size in image `%s'",
6197 img->spec, Qnil);
6198 goto error;
6201 for (y = 0; y < height; ++y)
6202 for (x = 0; x < width; ++x)
6204 int r, g, b;
6206 if (type == PBM_GRAY && raw_p)
6208 r = g = b = *p++;
6209 if (max_color_idx > 255)
6210 r = g = b = r * 256 + *p++;
6212 else if (type == PBM_GRAY)
6213 r = g = b = pbm_scan_number (&p, end);
6214 else if (raw_p)
6216 r = *p++;
6217 if (max_color_idx > 255)
6218 r = r * 256 + *p++;
6219 g = *p++;
6220 if (max_color_idx > 255)
6221 g = g * 256 + *p++;
6222 b = *p++;
6223 if (max_color_idx > 255)
6224 b = b * 256 + *p++;
6226 else
6228 r = pbm_scan_number (&p, end);
6229 g = pbm_scan_number (&p, end);
6230 b = pbm_scan_number (&p, end);
6233 if (r < 0 || g < 0 || b < 0)
6235 x_destroy_x_image (ximg);
6236 image_error ("Invalid pixel value in image `%s'",
6237 img->spec, Qnil);
6238 goto error;
6241 /* RGB values are now in the range 0..max_color_idx.
6242 Scale this to the range 0..0xffff supported by X. */
6243 r = (double) r * 65535 / max_color_idx;
6244 g = (double) g * 65535 / max_color_idx;
6245 b = (double) b * 65535 / max_color_idx;
6246 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6250 #ifdef COLOR_TABLE_SUPPORT
6251 /* Store in IMG->colors the colors allocated for the image, and
6252 free the color table. */
6253 img->colors = colors_in_color_table (&img->ncolors);
6254 free_color_table ();
6255 #endif /* COLOR_TABLE_SUPPORT */
6257 img->width = width;
6258 img->height = height;
6260 /* Maybe fill in the background field while we have ximg handy. */
6262 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6263 /* Casting avoids a GCC warning. */
6264 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6266 /* Put the image into a pixmap. */
6267 x_put_x_image (f, ximg, img->pixmap, width, height);
6268 x_destroy_x_image (ximg);
6270 /* X and W32 versions did it here, MAC version above. ++kfs
6271 img->width = width;
6272 img->height = height; */
6274 UNGCPRO;
6275 xfree (contents);
6276 return 1;
6280 /***********************************************************************
6282 ***********************************************************************/
6284 #if defined (HAVE_PNG) || defined (MAC_OS)
6286 /* Function prototypes. */
6288 static int png_image_p P_ ((Lisp_Object object));
6289 static int png_load P_ ((struct frame *f, struct image *img));
6291 /* The symbol `png' identifying images of this type. */
6293 Lisp_Object Qpng;
6295 /* Indices of image specification fields in png_format, below. */
6297 enum png_keyword_index
6299 PNG_TYPE,
6300 PNG_DATA,
6301 PNG_FILE,
6302 PNG_ASCENT,
6303 PNG_MARGIN,
6304 PNG_RELIEF,
6305 PNG_ALGORITHM,
6306 PNG_HEURISTIC_MASK,
6307 PNG_MASK,
6308 PNG_BACKGROUND,
6309 PNG_LAST
6312 /* Vector of image_keyword structures describing the format
6313 of valid user-defined image specifications. */
6315 static struct image_keyword png_format[PNG_LAST] =
6317 {":type", IMAGE_SYMBOL_VALUE, 1},
6318 {":data", IMAGE_STRING_VALUE, 0},
6319 {":file", IMAGE_STRING_VALUE, 0},
6320 {":ascent", IMAGE_ASCENT_VALUE, 0},
6321 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6322 {":relief", IMAGE_INTEGER_VALUE, 0},
6323 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6324 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6325 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6326 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6329 /* Structure describing the image type `png'. */
6331 static struct image_type png_type =
6333 &Qpng,
6334 png_image_p,
6335 png_load,
6336 x_clear_image,
6337 NULL
6340 /* Return non-zero if OBJECT is a valid PNG image specification. */
6342 static int
6343 png_image_p (object)
6344 Lisp_Object object;
6346 struct image_keyword fmt[PNG_LAST];
6347 bcopy (png_format, fmt, sizeof fmt);
6349 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
6350 return 0;
6352 /* Must specify either the :data or :file keyword. */
6353 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
6356 #endif /* HAVE_PNG || MAC_OS */
6359 #ifdef HAVE_PNG
6361 #if defined HAVE_LIBPNG_PNG_H
6362 # include <libpng/png.h>
6363 #else
6364 # include <png.h>
6365 #endif
6367 #ifdef HAVE_NTGUI
6368 /* PNG library details. */
6370 DEF_IMGLIB_FN (png_get_io_ptr);
6371 DEF_IMGLIB_FN (png_check_sig);
6372 DEF_IMGLIB_FN (png_create_read_struct);
6373 DEF_IMGLIB_FN (png_create_info_struct);
6374 DEF_IMGLIB_FN (png_destroy_read_struct);
6375 DEF_IMGLIB_FN (png_set_read_fn);
6376 DEF_IMGLIB_FN (png_set_sig_bytes);
6377 DEF_IMGLIB_FN (png_read_info);
6378 DEF_IMGLIB_FN (png_get_IHDR);
6379 DEF_IMGLIB_FN (png_get_valid);
6380 DEF_IMGLIB_FN (png_set_strip_16);
6381 DEF_IMGLIB_FN (png_set_expand);
6382 DEF_IMGLIB_FN (png_set_gray_to_rgb);
6383 DEF_IMGLIB_FN (png_set_background);
6384 DEF_IMGLIB_FN (png_get_bKGD);
6385 DEF_IMGLIB_FN (png_read_update_info);
6386 DEF_IMGLIB_FN (png_get_channels);
6387 DEF_IMGLIB_FN (png_get_rowbytes);
6388 DEF_IMGLIB_FN (png_read_image);
6389 DEF_IMGLIB_FN (png_read_end);
6390 DEF_IMGLIB_FN (png_error);
6392 static int
6393 init_png_functions (Lisp_Object libraries)
6395 HMODULE library;
6397 /* Try loading libpng under probable names. */
6398 if (!(library = w32_delayed_load (libraries, Qpng)))
6399 return 0;
6401 LOAD_IMGLIB_FN (library, png_get_io_ptr);
6402 LOAD_IMGLIB_FN (library, png_check_sig);
6403 LOAD_IMGLIB_FN (library, png_create_read_struct);
6404 LOAD_IMGLIB_FN (library, png_create_info_struct);
6405 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
6406 LOAD_IMGLIB_FN (library, png_set_read_fn);
6407 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
6408 LOAD_IMGLIB_FN (library, png_read_info);
6409 LOAD_IMGLIB_FN (library, png_get_IHDR);
6410 LOAD_IMGLIB_FN (library, png_get_valid);
6411 LOAD_IMGLIB_FN (library, png_set_strip_16);
6412 LOAD_IMGLIB_FN (library, png_set_expand);
6413 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
6414 LOAD_IMGLIB_FN (library, png_set_background);
6415 LOAD_IMGLIB_FN (library, png_get_bKGD);
6416 LOAD_IMGLIB_FN (library, png_read_update_info);
6417 LOAD_IMGLIB_FN (library, png_get_channels);
6418 LOAD_IMGLIB_FN (library, png_get_rowbytes);
6419 LOAD_IMGLIB_FN (library, png_read_image);
6420 LOAD_IMGLIB_FN (library, png_read_end);
6421 LOAD_IMGLIB_FN (library, png_error);
6422 return 1;
6424 #else
6426 #define fn_png_get_io_ptr png_get_io_ptr
6427 #define fn_png_check_sig png_check_sig
6428 #define fn_png_create_read_struct png_create_read_struct
6429 #define fn_png_create_info_struct png_create_info_struct
6430 #define fn_png_destroy_read_struct png_destroy_read_struct
6431 #define fn_png_set_read_fn png_set_read_fn
6432 #define fn_png_set_sig_bytes png_set_sig_bytes
6433 #define fn_png_read_info png_read_info
6434 #define fn_png_get_IHDR png_get_IHDR
6435 #define fn_png_get_valid png_get_valid
6436 #define fn_png_set_strip_16 png_set_strip_16
6437 #define fn_png_set_expand png_set_expand
6438 #define fn_png_set_gray_to_rgb png_set_gray_to_rgb
6439 #define fn_png_set_background png_set_background
6440 #define fn_png_get_bKGD png_get_bKGD
6441 #define fn_png_read_update_info png_read_update_info
6442 #define fn_png_get_channels png_get_channels
6443 #define fn_png_get_rowbytes png_get_rowbytes
6444 #define fn_png_read_image png_read_image
6445 #define fn_png_read_end png_read_end
6446 #define fn_png_error png_error
6448 #endif /* HAVE_NTGUI */
6450 /* Error and warning handlers installed when the PNG library
6451 is initialized. */
6453 static void
6454 my_png_error (png_ptr, msg)
6455 png_struct *png_ptr;
6456 char *msg;
6458 xassert (png_ptr != NULL);
6459 image_error ("PNG error: %s", build_string (msg), Qnil);
6460 longjmp (png_ptr->jmpbuf, 1);
6464 static void
6465 my_png_warning (png_ptr, msg)
6466 png_struct *png_ptr;
6467 char *msg;
6469 xassert (png_ptr != NULL);
6470 image_error ("PNG warning: %s", build_string (msg), Qnil);
6473 /* Memory source for PNG decoding. */
6475 struct png_memory_storage
6477 unsigned char *bytes; /* The data */
6478 size_t len; /* How big is it? */
6479 int index; /* Where are we? */
6483 /* Function set as reader function when reading PNG image from memory.
6484 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
6485 bytes from the input to DATA. */
6487 static void
6488 png_read_from_memory (png_ptr, data, length)
6489 png_structp png_ptr;
6490 png_bytep data;
6491 png_size_t length;
6493 struct png_memory_storage *tbr
6494 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
6496 if (length > tbr->len - tbr->index)
6497 fn_png_error (png_ptr, "Read error");
6499 bcopy (tbr->bytes + tbr->index, data, length);
6500 tbr->index = tbr->index + length;
6504 /* Function set as reader function when reading PNG image from a file.
6505 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
6506 bytes from the input to DATA. */
6508 static void
6509 png_read_from_file (png_ptr, data, length)
6510 png_structp png_ptr;
6511 png_bytep data;
6512 png_size_t length;
6514 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
6516 if (fread (data, 1, length, fp) < length)
6517 fn_png_error (png_ptr, "Read error");
6521 /* Load PNG image IMG for use on frame F. Value is non-zero if
6522 successful. */
6524 static int
6525 png_load (f, img)
6526 struct frame *f;
6527 struct image *img;
6529 Lisp_Object file, specified_file;
6530 Lisp_Object specified_data;
6531 int x, y, i;
6532 XImagePtr ximg, mask_img = NULL;
6533 struct gcpro gcpro1;
6534 png_struct *png_ptr = NULL;
6535 png_info *info_ptr = NULL, *end_info = NULL;
6536 FILE *volatile fp = NULL;
6537 png_byte sig[8];
6538 png_byte * volatile pixels = NULL;
6539 png_byte ** volatile rows = NULL;
6540 png_uint_32 width, height;
6541 int bit_depth, color_type, interlace_type;
6542 png_byte channels;
6543 png_uint_32 row_bytes;
6544 int transparent_p;
6545 double screen_gamma;
6546 struct png_memory_storage tbr; /* Data to be read */
6548 /* Find out what file to load. */
6549 specified_file = image_spec_value (img->spec, QCfile, NULL);
6550 specified_data = image_spec_value (img->spec, QCdata, NULL);
6551 file = Qnil;
6552 GCPRO1 (file);
6554 if (NILP (specified_data))
6556 file = x_find_image_file (specified_file);
6557 if (!STRINGP (file))
6559 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6560 UNGCPRO;
6561 return 0;
6564 /* Open the image file. */
6565 fp = fopen (SDATA (file), "rb");
6566 if (!fp)
6568 image_error ("Cannot open image file `%s'", file, Qnil);
6569 UNGCPRO;
6570 return 0;
6573 /* Check PNG signature. */
6574 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
6575 || !fn_png_check_sig (sig, sizeof sig))
6577 image_error ("Not a PNG file: `%s'", file, Qnil);
6578 UNGCPRO;
6579 fclose (fp);
6580 return 0;
6583 else
6585 /* Read from memory. */
6586 tbr.bytes = SDATA (specified_data);
6587 tbr.len = SBYTES (specified_data);
6588 tbr.index = 0;
6590 /* Check PNG signature. */
6591 if (tbr.len < sizeof sig
6592 || !fn_png_check_sig (tbr.bytes, sizeof sig))
6594 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
6595 UNGCPRO;
6596 return 0;
6599 /* Need to skip past the signature. */
6600 tbr.bytes += sizeof (sig);
6603 /* Initialize read and info structs for PNG lib. Casting return
6604 value avoids a GCC warning on W32. */
6605 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
6606 NULL, my_png_error,
6607 my_png_warning);
6608 if (!png_ptr)
6610 if (fp) fclose (fp);
6611 UNGCPRO;
6612 return 0;
6615 /* Casting return value avoids a GCC warning on W32. */
6616 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
6617 if (!info_ptr)
6619 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
6620 if (fp) fclose (fp);
6621 UNGCPRO;
6622 return 0;
6625 /* Casting return value avoids a GCC warning on W32. */
6626 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
6627 if (!end_info)
6629 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
6630 if (fp) fclose (fp);
6631 UNGCPRO;
6632 return 0;
6635 /* Set error jump-back. We come back here when the PNG library
6636 detects an error. */
6637 if (setjmp (png_ptr->jmpbuf))
6639 error:
6640 if (png_ptr)
6641 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6642 xfree (pixels);
6643 xfree (rows);
6644 if (fp) fclose (fp);
6645 UNGCPRO;
6646 return 0;
6649 /* Read image info. */
6650 if (!NILP (specified_data))
6651 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
6652 else
6653 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
6655 fn_png_set_sig_bytes (png_ptr, sizeof sig);
6656 fn_png_read_info (png_ptr, info_ptr);
6657 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
6658 &interlace_type, NULL, NULL);
6660 if (!check_image_size (f, width, height))
6661 goto error;
6663 /* If image contains simply transparency data, we prefer to
6664 construct a clipping mask. */
6665 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6666 transparent_p = 1;
6667 else
6668 transparent_p = 0;
6670 /* This function is easier to write if we only have to handle
6671 one data format: RGB or RGBA with 8 bits per channel. Let's
6672 transform other formats into that format. */
6674 /* Strip more than 8 bits per channel. */
6675 if (bit_depth == 16)
6676 fn_png_set_strip_16 (png_ptr);
6678 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
6679 if available. */
6680 fn_png_set_expand (png_ptr);
6682 /* Convert grayscale images to RGB. */
6683 if (color_type == PNG_COLOR_TYPE_GRAY
6684 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6685 fn_png_set_gray_to_rgb (png_ptr);
6687 screen_gamma = (f->gamma ? 1 / f->gamma / 0.45455 : 2.2);
6689 #if 0 /* Avoid double gamma correction for PNG images. */
6690 { /* Tell the PNG lib to handle gamma correction for us. */
6691 int intent;
6692 double image_gamma;
6693 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
6694 if (png_get_sRGB (png_ptr, info_ptr, &intent))
6695 /* The libpng documentation says this is right in this case. */
6696 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6697 else
6698 #endif
6699 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
6700 /* Image contains gamma information. */
6701 png_set_gamma (png_ptr, screen_gamma, image_gamma);
6702 else
6703 /* Use the standard default for the image gamma. */
6704 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6706 #endif /* if 0 */
6708 /* Handle alpha channel by combining the image with a background
6709 color. Do this only if a real alpha channel is supplied. For
6710 simple transparency, we prefer a clipping mask. */
6711 if (!transparent_p)
6713 /* png_color_16 *image_bg; */
6714 Lisp_Object specified_bg
6715 = image_spec_value (img->spec, QCbackground, NULL);
6717 if (STRINGP (specified_bg))
6718 /* The user specified `:background', use that. */
6720 /* W32 version incorrectly used COLORREF here!! ++kfs */
6721 XColor color;
6722 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
6724 png_color_16 user_bg;
6726 bzero (&user_bg, sizeof user_bg);
6727 user_bg.red = color.red >> 8;
6728 user_bg.green = color.green >> 8;
6729 user_bg.blue = color.blue >> 8;
6731 fn_png_set_background (png_ptr, &user_bg,
6732 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6735 /* The commented-out code checked if the png specifies a default
6736 background color, and uses that. Since we use the current
6737 frame background, it is OK for us to ignore this.
6739 else if (fn_png_get_bKGD (png_ptr, info_ptr, &image_bg))
6740 fn_png_set_background (png_ptr, image_bg,
6741 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
6743 else
6745 /* Image does not contain a background color with which
6746 to combine the image data via an alpha channel. Use
6747 the frame's background instead. */
6748 #ifdef HAVE_X_WINDOWS
6749 XColor color;
6750 png_color_16 frame_background;
6752 color.pixel = FRAME_BACKGROUND_PIXEL (f);
6753 x_query_color (f, &color);
6755 bzero (&frame_background, sizeof frame_background);
6756 frame_background.red = color.red >> 8;
6757 frame_background.green = color.green >> 8;
6758 frame_background.blue = color.blue >> 8;
6759 #endif /* HAVE_X_WINDOWS */
6761 #ifdef HAVE_NTGUI
6762 COLORREF color;
6763 png_color_16 frame_background;
6764 color = FRAME_BACKGROUND_PIXEL (f);
6765 #if 0 /* W32 TODO : Colormap support. */
6766 x_query_color (f, &color);
6767 #endif
6768 bzero (&frame_background, sizeof frame_background);
6769 frame_background.red = GetRValue (color);
6770 frame_background.green = GetGValue (color);
6771 frame_background.blue = GetBValue (color);
6772 #endif /* HAVE_NTGUI */
6774 #ifdef MAC_OS
6775 unsigned long color;
6776 png_color_16 frame_background;
6777 color = FRAME_BACKGROUND_PIXEL (f);
6778 #if 0 /* MAC/W32 TODO : Colormap support. */
6779 x_query_color (f, &color);
6780 #endif
6781 bzero (&frame_background, sizeof frame_background);
6782 frame_background.red = RED_FROM_ULONG (color);
6783 frame_background.green = GREEN_FROM_ULONG (color);
6784 frame_background.blue = BLUE_FROM_ULONG (color);
6785 #endif /* MAC_OS */
6787 fn_png_set_background (png_ptr, &frame_background,
6788 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6792 /* Update info structure. */
6793 fn_png_read_update_info (png_ptr, info_ptr);
6795 /* Get number of channels. Valid values are 1 for grayscale images
6796 and images with a palette, 2 for grayscale images with transparency
6797 information (alpha channel), 3 for RGB images, and 4 for RGB
6798 images with alpha channel, i.e. RGBA. If conversions above were
6799 sufficient we should only have 3 or 4 channels here. */
6800 channels = fn_png_get_channels (png_ptr, info_ptr);
6801 xassert (channels == 3 || channels == 4);
6803 /* Number of bytes needed for one row of the image. */
6804 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
6806 /* Allocate memory for the image. */
6807 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
6808 rows = (png_byte **) xmalloc (height * sizeof *rows);
6809 for (i = 0; i < height; ++i)
6810 rows[i] = pixels + i * row_bytes;
6812 /* Read the entire image. */
6813 fn_png_read_image (png_ptr, rows);
6814 fn_png_read_end (png_ptr, info_ptr);
6815 if (fp)
6817 fclose (fp);
6818 fp = NULL;
6821 /* Create the X image and pixmap. */
6822 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
6823 &img->pixmap))
6824 goto error;
6826 /* Create an image and pixmap serving as mask if the PNG image
6827 contains an alpha channel. */
6828 if (channels == 4
6829 && !transparent_p
6830 && !x_create_x_image_and_pixmap (f, width, height, 1,
6831 &mask_img, &img->mask))
6833 x_destroy_x_image (ximg);
6834 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
6835 img->pixmap = NO_PIXMAP;
6836 goto error;
6839 /* Fill the X image and mask from PNG data. */
6840 init_color_table ();
6842 for (y = 0; y < height; ++y)
6844 png_byte *p = rows[y];
6846 for (x = 0; x < width; ++x)
6848 unsigned r, g, b;
6850 r = *p++ << 8;
6851 g = *p++ << 8;
6852 b = *p++ << 8;
6853 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6854 /* An alpha channel, aka mask channel, associates variable
6855 transparency with an image. Where other image formats
6856 support binary transparency---fully transparent or fully
6857 opaque---PNG allows up to 254 levels of partial transparency.
6858 The PNG library implements partial transparency by combining
6859 the image with a specified background color.
6861 I'm not sure how to handle this here nicely: because the
6862 background on which the image is displayed may change, for
6863 real alpha channel support, it would be necessary to create
6864 a new image for each possible background.
6866 What I'm doing now is that a mask is created if we have
6867 boolean transparency information. Otherwise I'm using
6868 the frame's background color to combine the image with. */
6870 if (channels == 4)
6872 if (mask_img)
6873 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
6874 ++p;
6879 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6880 /* Set IMG's background color from the PNG image, unless the user
6881 overrode it. */
6883 png_color_16 *bg;
6884 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6886 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6887 img->background_valid = 1;
6891 #ifdef COLOR_TABLE_SUPPORT
6892 /* Remember colors allocated for this image. */
6893 img->colors = colors_in_color_table (&img->ncolors);
6894 free_color_table ();
6895 #endif /* COLOR_TABLE_SUPPORT */
6897 /* Clean up. */
6898 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6899 xfree (rows);
6900 xfree (pixels);
6902 img->width = width;
6903 img->height = height;
6905 /* Maybe fill in the background field while we have ximg handy.
6906 Casting avoids a GCC warning. */
6907 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
6909 /* Put the image into the pixmap, then free the X image and its buffer. */
6910 x_put_x_image (f, ximg, img->pixmap, width, height);
6911 x_destroy_x_image (ximg);
6913 /* Same for the mask. */
6914 if (mask_img)
6916 /* Fill in the background_transparent field while we have the
6917 mask handy. Casting avoids a GCC warning. */
6918 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
6920 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
6921 x_destroy_x_image (mask_img);
6924 UNGCPRO;
6925 return 1;
6928 #else /* HAVE_PNG */
6930 #ifdef MAC_OS
6931 static int
6932 png_load (f, img)
6933 struct frame *f;
6934 struct image *img;
6936 #if USE_MAC_IMAGE_IO
6937 return image_load_image_io (f, img, kUTTypePNG);
6938 #elif MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
6939 return image_load_quartz2d (f, img, 1);
6940 #else
6941 return image_load_quicktime (f, img, kQTFileTypePNG);
6942 #endif
6944 #endif /* MAC_OS */
6946 #endif /* !HAVE_PNG */
6950 /***********************************************************************
6951 JPEG
6952 ***********************************************************************/
6954 #if defined (HAVE_JPEG) || defined (MAC_OS)
6956 static int jpeg_image_p P_ ((Lisp_Object object));
6957 static int jpeg_load P_ ((struct frame *f, struct image *img));
6959 /* The symbol `jpeg' identifying images of this type. */
6961 Lisp_Object Qjpeg;
6963 /* Indices of image specification fields in gs_format, below. */
6965 enum jpeg_keyword_index
6967 JPEG_TYPE,
6968 JPEG_DATA,
6969 JPEG_FILE,
6970 JPEG_ASCENT,
6971 JPEG_MARGIN,
6972 JPEG_RELIEF,
6973 JPEG_ALGORITHM,
6974 JPEG_HEURISTIC_MASK,
6975 JPEG_MASK,
6976 JPEG_BACKGROUND,
6977 JPEG_LAST
6980 /* Vector of image_keyword structures describing the format
6981 of valid user-defined image specifications. */
6983 static struct image_keyword jpeg_format[JPEG_LAST] =
6985 {":type", IMAGE_SYMBOL_VALUE, 1},
6986 {":data", IMAGE_STRING_VALUE, 0},
6987 {":file", IMAGE_STRING_VALUE, 0},
6988 {":ascent", IMAGE_ASCENT_VALUE, 0},
6989 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6990 {":relief", IMAGE_INTEGER_VALUE, 0},
6991 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6992 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6993 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6994 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6997 /* Structure describing the image type `jpeg'. */
6999 static struct image_type jpeg_type =
7001 &Qjpeg,
7002 jpeg_image_p,
7003 jpeg_load,
7004 x_clear_image,
7005 NULL
7008 /* Return non-zero if OBJECT is a valid JPEG image specification. */
7010 static int
7011 jpeg_image_p (object)
7012 Lisp_Object object;
7014 struct image_keyword fmt[JPEG_LAST];
7016 bcopy (jpeg_format, fmt, sizeof fmt);
7018 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
7019 return 0;
7021 /* Must specify either the :data or :file keyword. */
7022 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
7025 #endif /* HAVE_JPEG || MAC_OS */
7027 #ifdef HAVE_JPEG
7029 /* Work around a warning about HAVE_STDLIB_H being redefined in
7030 jconfig.h. */
7031 #ifdef HAVE_STDLIB_H
7032 #define HAVE_STDLIB_H_1
7033 #undef HAVE_STDLIB_H
7034 #endif /* HAVE_STLIB_H */
7036 #if defined (HAVE_NTGUI) && !defined (__WIN32__)
7037 /* In older releases of the jpeg library, jpeglib.h will define boolean
7038 differently depending on __WIN32__, so make sure it is defined. */
7039 #define __WIN32__ 1
7040 #endif
7042 #include <jpeglib.h>
7043 #include <jerror.h>
7044 #include <setjmp.h>
7046 #ifdef HAVE_STLIB_H_1
7047 #define HAVE_STDLIB_H 1
7048 #endif
7050 #ifdef HAVE_NTGUI
7052 /* JPEG library details. */
7053 DEF_IMGLIB_FN (jpeg_CreateDecompress);
7054 DEF_IMGLIB_FN (jpeg_start_decompress);
7055 DEF_IMGLIB_FN (jpeg_finish_decompress);
7056 DEF_IMGLIB_FN (jpeg_destroy_decompress);
7057 DEF_IMGLIB_FN (jpeg_read_header);
7058 DEF_IMGLIB_FN (jpeg_read_scanlines);
7059 DEF_IMGLIB_FN (jpeg_std_error);
7060 DEF_IMGLIB_FN (jpeg_resync_to_restart);
7062 static int
7063 init_jpeg_functions (Lisp_Object libraries)
7065 HMODULE library;
7067 if (!(library = w32_delayed_load (libraries, Qjpeg)))
7068 return 0;
7070 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
7071 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
7072 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
7073 LOAD_IMGLIB_FN (library, jpeg_read_header);
7074 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
7075 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
7076 LOAD_IMGLIB_FN (library, jpeg_std_error);
7077 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
7078 return 1;
7081 /* Wrapper since we can't directly assign the function pointer
7082 to another function pointer that was declared more completely easily. */
7083 static boolean
7084 jpeg_resync_to_restart_wrapper (cinfo, desired)
7085 j_decompress_ptr cinfo;
7086 int desired;
7088 return fn_jpeg_resync_to_restart (cinfo, desired);
7091 #else
7093 #define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
7094 #define fn_jpeg_start_decompress jpeg_start_decompress
7095 #define fn_jpeg_finish_decompress jpeg_finish_decompress
7096 #define fn_jpeg_destroy_decompress jpeg_destroy_decompress
7097 #define fn_jpeg_read_header jpeg_read_header
7098 #define fn_jpeg_read_scanlines jpeg_read_scanlines
7099 #define fn_jpeg_std_error jpeg_std_error
7100 #define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
7102 #endif /* HAVE_NTGUI */
7104 struct my_jpeg_error_mgr
7106 struct jpeg_error_mgr pub;
7107 jmp_buf setjmp_buffer;
7111 static void
7112 my_error_exit (cinfo)
7113 j_common_ptr cinfo;
7115 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
7116 longjmp (mgr->setjmp_buffer, 1);
7120 /* Init source method for JPEG data source manager. Called by
7121 jpeg_read_header() before any data is actually read. See
7122 libjpeg.doc from the JPEG lib distribution. */
7124 static void
7125 our_common_init_source (cinfo)
7126 j_decompress_ptr cinfo;
7131 /* Method to terminate data source. Called by
7132 jpeg_finish_decompress() after all data has been processed. */
7134 static void
7135 our_common_term_source (cinfo)
7136 j_decompress_ptr cinfo;
7141 /* Fill input buffer method for JPEG data source manager. Called
7142 whenever more data is needed. We read the whole image in one step,
7143 so this only adds a fake end of input marker at the end. */
7145 static JOCTET our_memory_buffer[2];
7147 static boolean
7148 our_memory_fill_input_buffer (cinfo)
7149 j_decompress_ptr cinfo;
7151 /* Insert a fake EOI marker. */
7152 struct jpeg_source_mgr *src = cinfo->src;
7154 our_memory_buffer[0] = (JOCTET) 0xFF;
7155 our_memory_buffer[1] = (JOCTET) JPEG_EOI;
7157 src->next_input_byte = our_memory_buffer;
7158 src->bytes_in_buffer = 2;
7159 return 1;
7163 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
7164 is the JPEG data source manager. */
7166 static void
7167 our_memory_skip_input_data (cinfo, num_bytes)
7168 j_decompress_ptr cinfo;
7169 long num_bytes;
7171 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
7173 if (src)
7175 if (num_bytes > src->bytes_in_buffer)
7176 ERREXIT (cinfo, JERR_INPUT_EOF);
7178 src->bytes_in_buffer -= num_bytes;
7179 src->next_input_byte += num_bytes;
7184 /* Set up the JPEG lib for reading an image from DATA which contains
7185 LEN bytes. CINFO is the decompression info structure created for
7186 reading the image. */
7188 static void
7189 jpeg_memory_src (cinfo, data, len)
7190 j_decompress_ptr cinfo;
7191 JOCTET *data;
7192 unsigned int len;
7194 struct jpeg_source_mgr *src;
7196 if (cinfo->src == NULL)
7198 /* First time for this JPEG object? */
7199 cinfo->src = (struct jpeg_source_mgr *)
7200 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
7201 sizeof (struct jpeg_source_mgr));
7202 src = (struct jpeg_source_mgr *) cinfo->src;
7203 src->next_input_byte = data;
7206 src = (struct jpeg_source_mgr *) cinfo->src;
7207 src->init_source = our_common_init_source;
7208 src->fill_input_buffer = our_memory_fill_input_buffer;
7209 src->skip_input_data = our_memory_skip_input_data;
7210 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
7211 src->term_source = our_common_term_source;
7212 src->bytes_in_buffer = len;
7213 src->next_input_byte = data;
7217 struct jpeg_stdio_mgr
7219 struct jpeg_source_mgr mgr;
7220 boolean finished;
7221 FILE *file;
7222 JOCTET *buffer;
7226 /* Size of buffer to read JPEG from file.
7227 Not too big, as we want to use alloc_small. */
7228 #define JPEG_STDIO_BUFFER_SIZE 8192
7231 /* Fill input buffer method for JPEG data source manager. Called
7232 whenever more data is needed. The data is read from a FILE *. */
7234 static boolean
7235 our_stdio_fill_input_buffer (cinfo)
7236 j_decompress_ptr cinfo;
7238 struct jpeg_stdio_mgr *src;
7240 src = (struct jpeg_stdio_mgr *) cinfo->src;
7241 if (!src->finished)
7243 size_t bytes;
7245 bytes = fread (src->buffer, 1, JPEG_STDIO_BUFFER_SIZE, src->file);
7246 if (bytes > 0)
7247 src->mgr.bytes_in_buffer = bytes;
7248 else
7250 WARNMS (cinfo, JWRN_JPEG_EOF);
7251 src->finished = 1;
7252 src->buffer[0] = (JOCTET) 0xFF;
7253 src->buffer[1] = (JOCTET) JPEG_EOI;
7254 src->mgr.bytes_in_buffer = 2;
7256 src->mgr.next_input_byte = src->buffer;
7259 return 1;
7263 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
7264 is the JPEG data source manager. */
7266 static void
7267 our_stdio_skip_input_data (cinfo, num_bytes)
7268 j_decompress_ptr cinfo;
7269 long num_bytes;
7271 struct jpeg_stdio_mgr *src;
7272 src = (struct jpeg_stdio_mgr *) cinfo->src;
7274 while (num_bytes > 0 && !src->finished)
7276 if (num_bytes <= src->mgr.bytes_in_buffer)
7278 src->mgr.bytes_in_buffer -= num_bytes;
7279 src->mgr.next_input_byte += num_bytes;
7280 break;
7282 else
7284 num_bytes -= src->mgr.bytes_in_buffer;
7285 src->mgr.bytes_in_buffer = 0;
7286 src->mgr.next_input_byte = NULL;
7288 our_stdio_fill_input_buffer (cinfo);
7294 /* Set up the JPEG lib for reading an image from a FILE *.
7295 CINFO is the decompression info structure created for
7296 reading the image. */
7298 static void
7299 jpeg_file_src (cinfo, fp)
7300 j_decompress_ptr cinfo;
7301 FILE *fp;
7303 struct jpeg_stdio_mgr *src;
7305 if (cinfo->src != NULL)
7306 src = (struct jpeg_stdio_mgr *) cinfo->src;
7307 else
7309 /* First time for this JPEG object? */
7310 cinfo->src = (struct jpeg_source_mgr *)
7311 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
7312 sizeof (struct jpeg_stdio_mgr));
7313 src = (struct jpeg_stdio_mgr *) cinfo->src;
7314 src->buffer = (JOCTET *)
7315 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
7316 JPEG_STDIO_BUFFER_SIZE);
7319 src->file = fp;
7320 src->finished = 0;
7321 src->mgr.init_source = our_common_init_source;
7322 src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
7323 src->mgr.skip_input_data = our_stdio_skip_input_data;
7324 src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
7325 src->mgr.term_source = our_common_term_source;
7326 src->mgr.bytes_in_buffer = 0;
7327 src->mgr.next_input_byte = NULL;
7331 /* Load image IMG for use on frame F. Patterned after example.c
7332 from the JPEG lib. */
7334 static int
7335 jpeg_load (f, img)
7336 struct frame *f;
7337 struct image *img;
7339 struct jpeg_decompress_struct cinfo;
7340 struct my_jpeg_error_mgr mgr;
7341 Lisp_Object file, specified_file;
7342 Lisp_Object specified_data;
7343 FILE * volatile fp = NULL;
7344 JSAMPARRAY buffer;
7345 int row_stride, x, y;
7346 XImagePtr ximg = NULL;
7347 int rc;
7348 unsigned long *colors;
7349 int width, height;
7350 struct gcpro gcpro1;
7352 /* Open the JPEG file. */
7353 specified_file = image_spec_value (img->spec, QCfile, NULL);
7354 specified_data = image_spec_value (img->spec, QCdata, NULL);
7355 file = Qnil;
7356 GCPRO1 (file);
7358 if (NILP (specified_data))
7360 file = x_find_image_file (specified_file);
7361 if (!STRINGP (file))
7363 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7364 UNGCPRO;
7365 return 0;
7368 fp = fopen (SDATA (file), "rb");
7369 if (fp == NULL)
7371 image_error ("Cannot open `%s'", file, Qnil);
7372 UNGCPRO;
7373 return 0;
7377 /* Customize libjpeg's error handling to call my_error_exit when an
7378 error is detected. This function will perform a longjmp.
7379 Casting return value avoids a GCC warning on W32. */
7380 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
7381 mgr.pub.error_exit = my_error_exit;
7383 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
7385 if (rc == 1)
7387 /* Called from my_error_exit. Display a JPEG error. */
7388 char buffer[JMSG_LENGTH_MAX];
7389 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
7390 image_error ("Error reading JPEG image `%s': %s", img->spec,
7391 build_string (buffer));
7394 /* Close the input file and destroy the JPEG object. */
7395 if (fp)
7396 fclose ((FILE *) fp);
7397 fn_jpeg_destroy_decompress (&cinfo);
7399 /* If we already have an XImage, free that. */
7400 x_destroy_x_image (ximg);
7402 /* Free pixmap and colors. */
7403 x_clear_image (f, img);
7405 UNGCPRO;
7406 return 0;
7409 /* Create the JPEG decompression object. Let it read from fp.
7410 Read the JPEG image header. */
7411 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
7413 if (NILP (specified_data))
7414 jpeg_file_src (&cinfo, (FILE *) fp);
7415 else
7416 jpeg_memory_src (&cinfo, SDATA (specified_data),
7417 SBYTES (specified_data));
7419 fn_jpeg_read_header (&cinfo, 1);
7421 /* Customize decompression so that color quantization will be used.
7422 Start decompression. */
7423 cinfo.quantize_colors = 1;
7424 fn_jpeg_start_decompress (&cinfo);
7425 width = img->width = cinfo.output_width;
7426 height = img->height = cinfo.output_height;
7428 if (!check_image_size (f, width, height))
7430 image_error ("Invalid image size", Qnil, Qnil);
7431 longjmp (mgr.setjmp_buffer, 2);
7434 /* Create X image and pixmap. */
7435 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7436 longjmp (mgr.setjmp_buffer, 2);
7438 /* Allocate colors. When color quantization is used,
7439 cinfo.actual_number_of_colors has been set with the number of
7440 colors generated, and cinfo.colormap is a two-dimensional array
7441 of color indices in the range 0..cinfo.actual_number_of_colors.
7442 No more than 255 colors will be generated. */
7444 int i, ir, ig, ib;
7446 if (cinfo.out_color_components > 2)
7447 ir = 0, ig = 1, ib = 2;
7448 else if (cinfo.out_color_components > 1)
7449 ir = 0, ig = 1, ib = 0;
7450 else
7451 ir = 0, ig = 0, ib = 0;
7453 /* Use the color table mechanism because it handles colors that
7454 cannot be allocated nicely. Such colors will be replaced with
7455 a default color, and we don't have to care about which colors
7456 can be freed safely, and which can't. */
7457 init_color_table ();
7458 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
7459 * sizeof *colors);
7461 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
7463 /* Multiply RGB values with 255 because X expects RGB values
7464 in the range 0..0xffff. */
7465 int r = cinfo.colormap[ir][i] << 8;
7466 int g = cinfo.colormap[ig][i] << 8;
7467 int b = cinfo.colormap[ib][i] << 8;
7468 colors[i] = lookup_rgb_color (f, r, g, b);
7471 #ifdef COLOR_TABLE_SUPPORT
7472 /* Remember those colors actually allocated. */
7473 img->colors = colors_in_color_table (&img->ncolors);
7474 free_color_table ();
7475 #endif /* COLOR_TABLE_SUPPORT */
7478 /* Read pixels. */
7479 row_stride = width * cinfo.output_components;
7480 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
7481 row_stride, 1);
7482 for (y = 0; y < height; ++y)
7484 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
7485 for (x = 0; x < cinfo.output_width; ++x)
7486 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
7489 /* Clean up. */
7490 fn_jpeg_finish_decompress (&cinfo);
7491 fn_jpeg_destroy_decompress (&cinfo);
7492 if (fp)
7493 fclose ((FILE *) fp);
7495 /* Maybe fill in the background field while we have ximg handy. */
7496 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7497 /* Casting avoids a GCC warning. */
7498 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7500 /* Put the image into the pixmap. */
7501 x_put_x_image (f, ximg, img->pixmap, width, height);
7502 x_destroy_x_image (ximg);
7503 UNGCPRO;
7504 return 1;
7507 #else /* HAVE_JPEG */
7509 #ifdef MAC_OS
7510 static int
7511 jpeg_load (f, img)
7512 struct frame *f;
7513 struct image *img;
7515 #if USE_MAC_IMAGE_IO
7516 return image_load_image_io (f, img, kUTTypeJPEG);
7517 #elif defined (MAC_OSX)
7518 return image_load_quartz2d (f, img, 0);
7519 #else
7520 return image_load_quicktime (f, img, kQTFileTypeJPEG);
7521 #endif
7523 #endif /* MAC_OS */
7525 #endif /* !HAVE_JPEG */
7529 /***********************************************************************
7530 TIFF
7531 ***********************************************************************/
7533 #if defined (HAVE_TIFF) || defined (MAC_OS)
7535 static int tiff_image_p P_ ((Lisp_Object object));
7536 static int tiff_load P_ ((struct frame *f, struct image *img));
7538 /* The symbol `tiff' identifying images of this type. */
7540 Lisp_Object Qtiff;
7542 /* Indices of image specification fields in tiff_format, below. */
7544 enum tiff_keyword_index
7546 TIFF_TYPE,
7547 TIFF_DATA,
7548 TIFF_FILE,
7549 TIFF_ASCENT,
7550 TIFF_MARGIN,
7551 TIFF_RELIEF,
7552 TIFF_ALGORITHM,
7553 TIFF_HEURISTIC_MASK,
7554 TIFF_MASK,
7555 TIFF_BACKGROUND,
7556 TIFF_LAST
7559 /* Vector of image_keyword structures describing the format
7560 of valid user-defined image specifications. */
7562 static struct image_keyword tiff_format[TIFF_LAST] =
7564 {":type", IMAGE_SYMBOL_VALUE, 1},
7565 {":data", IMAGE_STRING_VALUE, 0},
7566 {":file", IMAGE_STRING_VALUE, 0},
7567 {":ascent", IMAGE_ASCENT_VALUE, 0},
7568 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7569 {":relief", IMAGE_INTEGER_VALUE, 0},
7570 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7571 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7572 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7573 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7576 /* Structure describing the image type `tiff'. */
7578 static struct image_type tiff_type =
7580 &Qtiff,
7581 tiff_image_p,
7582 tiff_load,
7583 x_clear_image,
7584 NULL
7587 /* Return non-zero if OBJECT is a valid TIFF image specification. */
7589 static int
7590 tiff_image_p (object)
7591 Lisp_Object object;
7593 struct image_keyword fmt[TIFF_LAST];
7594 bcopy (tiff_format, fmt, sizeof fmt);
7596 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
7597 return 0;
7599 /* Must specify either the :data or :file keyword. */
7600 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
7603 #endif /* HAVE_TIFF || MAC_OS */
7605 #ifdef HAVE_TIFF
7607 #include <tiffio.h>
7609 #ifdef HAVE_NTGUI
7611 /* TIFF library details. */
7612 DEF_IMGLIB_FN (TIFFSetErrorHandler);
7613 DEF_IMGLIB_FN (TIFFSetWarningHandler);
7614 DEF_IMGLIB_FN (TIFFOpen);
7615 DEF_IMGLIB_FN (TIFFClientOpen);
7616 DEF_IMGLIB_FN (TIFFGetField);
7617 DEF_IMGLIB_FN (TIFFReadRGBAImage);
7618 DEF_IMGLIB_FN (TIFFClose);
7620 static int
7621 init_tiff_functions (Lisp_Object libraries)
7623 HMODULE library;
7625 if (!(library = w32_delayed_load (libraries, Qtiff)))
7626 return 0;
7628 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
7629 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
7630 LOAD_IMGLIB_FN (library, TIFFOpen);
7631 LOAD_IMGLIB_FN (library, TIFFClientOpen);
7632 LOAD_IMGLIB_FN (library, TIFFGetField);
7633 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
7634 LOAD_IMGLIB_FN (library, TIFFClose);
7635 return 1;
7638 #else
7640 #define fn_TIFFSetErrorHandler TIFFSetErrorHandler
7641 #define fn_TIFFSetWarningHandler TIFFSetWarningHandler
7642 #define fn_TIFFOpen TIFFOpen
7643 #define fn_TIFFClientOpen TIFFClientOpen
7644 #define fn_TIFFGetField TIFFGetField
7645 #define fn_TIFFReadRGBAImage TIFFReadRGBAImage
7646 #define fn_TIFFClose TIFFClose
7648 #endif /* HAVE_NTGUI */
7651 /* Reading from a memory buffer for TIFF images Based on the PNG
7652 memory source, but we have to provide a lot of extra functions.
7653 Blah.
7655 We really only need to implement read and seek, but I am not
7656 convinced that the TIFF library is smart enough not to destroy
7657 itself if we only hand it the function pointers we need to
7658 override. */
7660 typedef struct
7662 unsigned char *bytes;
7663 size_t len;
7664 int index;
7666 tiff_memory_source;
7668 static size_t
7669 tiff_read_from_memory (data, buf, size)
7670 thandle_t data;
7671 tdata_t buf;
7672 tsize_t size;
7674 tiff_memory_source *src = (tiff_memory_source *) data;
7676 if (size > src->len - src->index)
7677 return (size_t) -1;
7678 bcopy (src->bytes + src->index, buf, size);
7679 src->index += size;
7680 return size;
7683 static size_t
7684 tiff_write_from_memory (data, buf, size)
7685 thandle_t data;
7686 tdata_t buf;
7687 tsize_t size;
7689 return (size_t) -1;
7692 static toff_t
7693 tiff_seek_in_memory (data, off, whence)
7694 thandle_t data;
7695 toff_t off;
7696 int whence;
7698 tiff_memory_source *src = (tiff_memory_source *) data;
7699 int idx;
7701 switch (whence)
7703 case SEEK_SET: /* Go from beginning of source. */
7704 idx = off;
7705 break;
7707 case SEEK_END: /* Go from end of source. */
7708 idx = src->len + off;
7709 break;
7711 case SEEK_CUR: /* Go from current position. */
7712 idx = src->index + off;
7713 break;
7715 default: /* Invalid `whence'. */
7716 return -1;
7719 if (idx > src->len || idx < 0)
7720 return -1;
7722 src->index = idx;
7723 return src->index;
7726 static int
7727 tiff_close_memory (data)
7728 thandle_t data;
7730 /* NOOP */
7731 return 0;
7734 static int
7735 tiff_mmap_memory (data, pbase, psize)
7736 thandle_t data;
7737 tdata_t *pbase;
7738 toff_t *psize;
7740 /* It is already _IN_ memory. */
7741 return 0;
7744 static void
7745 tiff_unmap_memory (data, base, size)
7746 thandle_t data;
7747 tdata_t base;
7748 toff_t size;
7750 /* We don't need to do this. */
7753 static toff_t
7754 tiff_size_of_memory (data)
7755 thandle_t data;
7757 return ((tiff_memory_source *) data)->len;
7761 static void
7762 tiff_error_handler (title, format, ap)
7763 const char *title, *format;
7764 va_list ap;
7766 char buf[512];
7767 int len;
7769 len = sprintf (buf, "TIFF error: %s ", title);
7770 vsprintf (buf + len, format, ap);
7771 add_to_log (buf, Qnil, Qnil);
7775 static void
7776 tiff_warning_handler (title, format, ap)
7777 const char *title, *format;
7778 va_list ap;
7780 char buf[512];
7781 int len;
7783 len = sprintf (buf, "TIFF warning: %s ", title);
7784 vsprintf (buf + len, format, ap);
7785 add_to_log (buf, Qnil, Qnil);
7789 /* Load TIFF image IMG for use on frame F. Value is non-zero if
7790 successful. */
7792 static int
7793 tiff_load (f, img)
7794 struct frame *f;
7795 struct image *img;
7797 Lisp_Object file, specified_file;
7798 Lisp_Object specified_data;
7799 TIFF *tiff;
7800 int width, height, x, y;
7801 uint32 *buf;
7802 int rc;
7803 XImagePtr ximg;
7804 struct gcpro gcpro1;
7805 tiff_memory_source memsrc;
7807 specified_file = image_spec_value (img->spec, QCfile, NULL);
7808 specified_data = image_spec_value (img->spec, QCdata, NULL);
7809 file = Qnil;
7810 GCPRO1 (file);
7812 fn_TIFFSetErrorHandler (tiff_error_handler);
7813 fn_TIFFSetWarningHandler (tiff_warning_handler);
7815 if (NILP (specified_data))
7817 /* Read from a file */
7818 file = x_find_image_file (specified_file);
7819 if (!STRINGP (file))
7821 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7822 UNGCPRO;
7823 return 0;
7826 /* Try to open the image file. Casting return value avoids a
7827 GCC warning on W32. */
7828 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
7829 if (tiff == NULL)
7831 image_error ("Cannot open `%s'", file, Qnil);
7832 UNGCPRO;
7833 return 0;
7836 else
7838 /* Memory source! */
7839 memsrc.bytes = SDATA (specified_data);
7840 memsrc.len = SBYTES (specified_data);
7841 memsrc.index = 0;
7843 /* Casting return value avoids a GCC warning on W32. */
7844 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r", &memsrc,
7845 (TIFFReadWriteProc) tiff_read_from_memory,
7846 (TIFFReadWriteProc) tiff_write_from_memory,
7847 tiff_seek_in_memory,
7848 tiff_close_memory,
7849 tiff_size_of_memory,
7850 tiff_mmap_memory,
7851 tiff_unmap_memory);
7853 if (!tiff)
7855 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7856 UNGCPRO;
7857 return 0;
7861 /* Get width and height of the image, and allocate a raster buffer
7862 of width x height 32-bit values. */
7863 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7864 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7866 if (!check_image_size (f, width, height))
7868 image_error ("Invalid image size", Qnil, Qnil);
7869 UNGCPRO;
7870 return 0;
7873 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
7875 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7876 fn_TIFFClose (tiff);
7877 if (!rc)
7879 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7880 xfree (buf);
7881 UNGCPRO;
7882 return 0;
7885 /* Create the X image and pixmap. */
7886 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7888 xfree (buf);
7889 UNGCPRO;
7890 return 0;
7893 /* Initialize the color table. */
7894 init_color_table ();
7896 /* Process the pixel raster. Origin is in the lower-left corner. */
7897 for (y = 0; y < height; ++y)
7899 uint32 *row = buf + y * width;
7901 for (x = 0; x < width; ++x)
7903 uint32 abgr = row[x];
7904 int r = TIFFGetR (abgr) << 8;
7905 int g = TIFFGetG (abgr) << 8;
7906 int b = TIFFGetB (abgr) << 8;
7907 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7911 #ifdef COLOR_TABLE_SUPPORT
7912 /* Remember the colors allocated for the image. Free the color table. */
7913 img->colors = colors_in_color_table (&img->ncolors);
7914 free_color_table ();
7915 #endif /* COLOR_TABLE_SUPPORT */
7917 img->width = width;
7918 img->height = height;
7920 /* Maybe fill in the background field while we have ximg handy. */
7921 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7922 /* Casting avoids a GCC warning on W32. */
7923 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
7925 /* Put the image into the pixmap, then free the X image and its buffer. */
7926 x_put_x_image (f, ximg, img->pixmap, width, height);
7927 x_destroy_x_image (ximg);
7928 xfree (buf);
7930 UNGCPRO;
7931 return 1;
7934 #else /* HAVE_TIFF */
7936 #ifdef MAC_OS
7937 static int
7938 tiff_load (f, img)
7939 struct frame *f;
7940 struct image *img;
7942 #if USE_MAC_IMAGE_IO
7943 return image_load_image_io (f, img, kUTTypeTIFF);
7944 #else
7945 return image_load_quicktime (f, img, kQTFileTypeTIFF);
7946 #endif
7948 #endif /* MAC_OS */
7950 #endif /* !HAVE_TIFF */
7954 /***********************************************************************
7956 ***********************************************************************/
7958 #if defined (HAVE_GIF) || defined (MAC_OS)
7960 static int gif_image_p P_ ((Lisp_Object object));
7961 static int gif_load P_ ((struct frame *f, struct image *img));
7962 static void gif_clear_image P_ ((struct frame *f, struct image *img));
7964 /* The symbol `gif' identifying images of this type. */
7966 Lisp_Object Qgif;
7968 /* Indices of image specification fields in gif_format, below. */
7970 enum gif_keyword_index
7972 GIF_TYPE,
7973 GIF_DATA,
7974 GIF_FILE,
7975 GIF_ASCENT,
7976 GIF_MARGIN,
7977 GIF_RELIEF,
7978 GIF_ALGORITHM,
7979 GIF_HEURISTIC_MASK,
7980 GIF_MASK,
7981 GIF_IMAGE,
7982 GIF_BACKGROUND,
7983 GIF_LAST
7986 /* Vector of image_keyword structures describing the format
7987 of valid user-defined image specifications. */
7989 static struct image_keyword gif_format[GIF_LAST] =
7991 {":type", IMAGE_SYMBOL_VALUE, 1},
7992 {":data", IMAGE_STRING_VALUE, 0},
7993 {":file", IMAGE_STRING_VALUE, 0},
7994 {":ascent", IMAGE_ASCENT_VALUE, 0},
7995 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7996 {":relief", IMAGE_INTEGER_VALUE, 0},
7997 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7998 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7999 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8000 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
8001 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8004 /* Structure describing the image type `gif'. */
8006 static struct image_type gif_type =
8008 &Qgif,
8009 gif_image_p,
8010 gif_load,
8011 gif_clear_image,
8012 NULL
8015 /* Free X resources of GIF image IMG which is used on frame F. */
8017 static void
8018 gif_clear_image (f, img)
8019 struct frame *f;
8020 struct image *img;
8022 /* IMG->data.ptr_val may contain extension data. */
8023 img->data.lisp_val = Qnil;
8024 x_clear_image (f, img);
8027 /* Return non-zero if OBJECT is a valid GIF image specification. */
8029 static int
8030 gif_image_p (object)
8031 Lisp_Object object;
8033 struct image_keyword fmt[GIF_LAST];
8034 bcopy (gif_format, fmt, sizeof fmt);
8036 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
8037 return 0;
8039 /* Must specify either the :data or :file keyword. */
8040 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
8043 #endif /* HAVE_GIF || MAC_OS */
8045 #ifdef HAVE_GIF
8047 #if defined (HAVE_NTGUI) || defined (MAC_OS)
8048 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
8049 Undefine before redefining to avoid a preprocessor warning. */
8050 #ifdef DrawText
8051 #undef DrawText
8052 #endif
8053 /* avoid conflict with QuickdrawText.h */
8054 #define DrawText gif_DrawText
8055 #include <gif_lib.h>
8056 #undef DrawText
8058 #else /* HAVE_NTGUI || MAC_OS */
8060 #include <gif_lib.h>
8062 #endif /* HAVE_NTGUI || MAC_OS */
8065 #ifdef HAVE_NTGUI
8067 /* GIF library details. */
8068 DEF_IMGLIB_FN (DGifCloseFile);
8069 DEF_IMGLIB_FN (DGifSlurp);
8070 DEF_IMGLIB_FN (DGifOpen);
8071 DEF_IMGLIB_FN (DGifOpenFileName);
8073 static int
8074 init_gif_functions (Lisp_Object libraries)
8076 HMODULE library;
8078 if (!(library = w32_delayed_load (libraries, Qgif)))
8079 return 0;
8081 LOAD_IMGLIB_FN (library, DGifCloseFile);
8082 LOAD_IMGLIB_FN (library, DGifSlurp);
8083 LOAD_IMGLIB_FN (library, DGifOpen);
8084 LOAD_IMGLIB_FN (library, DGifOpenFileName);
8085 return 1;
8088 #else
8090 #define fn_DGifCloseFile DGifCloseFile
8091 #define fn_DGifSlurp DGifSlurp
8092 #define fn_DGifOpen DGifOpen
8093 #define fn_DGifOpenFileName DGifOpenFileName
8095 #endif /* HAVE_NTGUI */
8097 /* Reading a GIF image from memory
8098 Based on the PNG memory stuff to a certain extent. */
8100 typedef struct
8102 unsigned char *bytes;
8103 size_t len;
8104 int index;
8106 gif_memory_source;
8108 /* Make the current memory source available to gif_read_from_memory.
8109 It's done this way because not all versions of libungif support
8110 a UserData field in the GifFileType structure. */
8111 static gif_memory_source *current_gif_memory_src;
8113 static int
8114 gif_read_from_memory (file, buf, len)
8115 GifFileType *file;
8116 GifByteType *buf;
8117 int len;
8119 gif_memory_source *src = current_gif_memory_src;
8121 if (len > src->len - src->index)
8122 return -1;
8124 bcopy (src->bytes + src->index, buf, len);
8125 src->index += len;
8126 return len;
8130 /* Load GIF image IMG for use on frame F. Value is non-zero if
8131 successful. */
8133 static int interlace_start[] = {0, 4, 2, 1};
8134 static int interlace_increment[] = {8, 8, 4, 2};
8136 static int
8137 gif_load (f, img)
8138 struct frame *f;
8139 struct image *img;
8141 Lisp_Object file, specified_file;
8142 Lisp_Object specified_data;
8143 int rc, width, height, x, y, i;
8144 XImagePtr ximg;
8145 ColorMapObject *gif_color_map;
8146 unsigned long pixel_colors[256];
8147 GifFileType *gif;
8148 struct gcpro gcpro1;
8149 Lisp_Object image;
8150 int ino, image_height, image_width;
8151 gif_memory_source memsrc;
8152 unsigned char *raster;
8154 specified_file = image_spec_value (img->spec, QCfile, NULL);
8155 specified_data = image_spec_value (img->spec, QCdata, NULL);
8156 file = Qnil;
8157 GCPRO1 (file);
8159 if (NILP (specified_data))
8161 file = x_find_image_file (specified_file);
8162 if (!STRINGP (file))
8164 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8165 UNGCPRO;
8166 return 0;
8169 /* Open the GIF file. Casting return value avoids a GCC warning
8170 on W32. */
8171 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
8172 if (gif == NULL)
8174 image_error ("Cannot open `%s'", file, Qnil);
8175 UNGCPRO;
8176 return 0;
8179 else
8181 /* Read from memory! */
8182 current_gif_memory_src = &memsrc;
8183 memsrc.bytes = SDATA (specified_data);
8184 memsrc.len = SBYTES (specified_data);
8185 memsrc.index = 0;
8187 /* Casting return value avoids a GCC warning on W32. */
8188 gif = (GifFileType *) fn_DGifOpen (&memsrc, gif_read_from_memory);
8189 if (!gif)
8191 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
8192 UNGCPRO;
8193 return 0;
8197 /* Before reading entire contents, check the declared image size. */
8198 if (!check_image_size (f, gif->SWidth, gif->SHeight))
8200 image_error ("Invalid image size", Qnil, Qnil);
8201 fn_DGifCloseFile (gif);
8202 UNGCPRO;
8203 return 0;
8206 /* Read entire contents. */
8207 rc = fn_DGifSlurp (gif);
8208 if (rc == GIF_ERROR)
8210 image_error ("Error reading `%s'", img->spec, Qnil);
8211 fn_DGifCloseFile (gif);
8212 UNGCPRO;
8213 return 0;
8216 image = image_spec_value (img->spec, QCindex, NULL);
8217 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8218 if (ino >= gif->ImageCount)
8220 image_error ("Invalid image number `%s' in image `%s'",
8221 image, img->spec);
8222 fn_DGifCloseFile (gif);
8223 UNGCPRO;
8224 return 0;
8227 img->corners[TOP_CORNER] = gif->SavedImages[ino].ImageDesc.Top;
8228 img->corners[LEFT_CORNER] = gif->SavedImages[ino].ImageDesc.Left;
8229 image_height = gif->SavedImages[ino].ImageDesc.Height;
8230 img->corners[BOT_CORNER] = img->corners[TOP_CORNER] + image_height;
8231 image_width = gif->SavedImages[ino].ImageDesc.Width;
8232 img->corners[RIGHT_CORNER] = img->corners[LEFT_CORNER] + image_width;
8234 width = img->width = max (gif->SWidth,
8235 max (gif->Image.Left + gif->Image.Width,
8236 img->corners[RIGHT_CORNER]));
8237 height = img->height = max (gif->SHeight,
8238 max (gif->Image.Top + gif->Image.Height,
8239 img->corners[BOT_CORNER]));
8241 if (!check_image_size (f, width, height))
8243 image_error ("Invalid image size", Qnil, Qnil);
8244 fn_DGifCloseFile (gif);
8245 UNGCPRO;
8246 return 0;
8249 /* Create the X image and pixmap. */
8250 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8252 fn_DGifCloseFile (gif);
8253 UNGCPRO;
8254 return 0;
8257 /* Allocate colors. */
8258 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
8259 if (!gif_color_map)
8260 gif_color_map = gif->SColorMap;
8261 init_color_table ();
8262 bzero (pixel_colors, sizeof pixel_colors);
8264 if (gif_color_map)
8265 for (i = 0; i < gif_color_map->ColorCount; ++i)
8267 int r = gif_color_map->Colors[i].Red << 8;
8268 int g = gif_color_map->Colors[i].Green << 8;
8269 int b = gif_color_map->Colors[i].Blue << 8;
8270 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
8273 #ifdef COLOR_TABLE_SUPPORT
8274 img->colors = colors_in_color_table (&img->ncolors);
8275 free_color_table ();
8276 #endif /* COLOR_TABLE_SUPPORT */
8278 /* Clear the part of the screen image that are not covered by
8279 the image from the GIF file. Full animated GIF support
8280 requires more than can be done here (see the gif89 spec,
8281 disposal methods). Let's simply assume that the part
8282 not covered by a sub-image is in the frame's background color. */
8283 for (y = 0; y < img->corners[TOP_CORNER]; ++y)
8284 for (x = 0; x < width; ++x)
8285 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8287 for (y = img->corners[BOT_CORNER]; y < height; ++y)
8288 for (x = 0; x < width; ++x)
8289 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8291 for (y = img->corners[TOP_CORNER]; y < img->corners[BOT_CORNER]; ++y)
8293 for (x = 0; x < img->corners[LEFT_CORNER]; ++x)
8294 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8295 for (x = img->corners[RIGHT_CORNER]; x < width; ++x)
8296 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
8299 /* Read the GIF image into the X image. We use a local variable
8300 `raster' here because RasterBits below is a char *, and invites
8301 problems with bytes >= 0x80. */
8302 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
8304 if (gif->SavedImages[ino].ImageDesc.Interlace)
8306 int pass;
8307 int row = interlace_start[0];
8309 pass = 0;
8311 for (y = 0; y < image_height; y++)
8313 if (row >= image_height)
8315 row = interlace_start[++pass];
8316 while (row >= image_height)
8317 row = interlace_start[++pass];
8320 for (x = 0; x < image_width; x++)
8322 int i = raster[(y * image_width) + x];
8323 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
8324 row + img->corners[TOP_CORNER], pixel_colors[i]);
8327 row += interlace_increment[pass];
8330 else
8332 for (y = 0; y < image_height; ++y)
8333 for (x = 0; x < image_width; ++x)
8335 int i = raster[y * image_width + x];
8336 XPutPixel (ximg, x + img->corners[LEFT_CORNER],
8337 y + img->corners[TOP_CORNER], pixel_colors[i]);
8341 /* Save GIF image extension data for `image-extension-data'.
8342 Format is (count IMAGES FUNCTION "BYTES" ...). */
8343 img->data.lisp_val = Qnil;
8344 if (gif->SavedImages[ino].ExtensionBlockCount > 0)
8346 ExtensionBlock *ext = gif->SavedImages[ino].ExtensionBlocks;
8347 for (i = 0; i < gif->SavedImages[ino].ExtensionBlockCount; i++, ext++)
8348 /* Append (... FUNCTION "BYTES") */
8349 img->data.lisp_val = Fcons (make_unibyte_string (ext->Bytes, ext->ByteCount),
8350 Fcons (make_number (ext->Function),
8351 img->data.lisp_val));
8352 img->data.lisp_val = Fnreverse (img->data.lisp_val);
8354 if (gif->ImageCount > 1)
8355 img->data.lisp_val = Fcons (Qcount,
8356 Fcons (make_number (gif->ImageCount),
8357 img->data.lisp_val));
8359 fn_DGifCloseFile (gif);
8361 /* Maybe fill in the background field while we have ximg handy. */
8362 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8363 /* Casting avoids a GCC warning. */
8364 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8366 /* Put the image into the pixmap, then free the X image and its buffer. */
8367 x_put_x_image (f, ximg, img->pixmap, width, height);
8368 x_destroy_x_image (ximg);
8370 UNGCPRO;
8371 return 1;
8374 #else /* !HAVE_GIF */
8376 #ifdef MAC_OS
8377 static int
8378 gif_load (f, img)
8379 struct frame *f;
8380 struct image *img;
8382 #if USE_MAC_IMAGE_IO
8383 return image_load_image_io (f, img, kUTTypeGIF);
8384 #else /* !USE_MAC_IMAGE_IO */
8385 Lisp_Object specified_file, file;
8386 Lisp_Object specified_data;
8387 OSErr err;
8388 Boolean graphic_p, movie_p, prefer_graphic_p;
8389 Handle dh = NULL;
8390 Movie movie = NULL;
8391 Lisp_Object image;
8392 Track track = NULL;
8393 Media media = NULL;
8394 long nsamples;
8395 Rect rect;
8396 Lisp_Object specified_bg;
8397 XColor color;
8398 RGBColor bg_color;
8399 int width, height;
8400 XImagePtr ximg;
8401 TimeScale time_scale;
8402 TimeValue time, duration;
8403 int ino;
8404 CGrafPtr old_port;
8405 GDHandle old_gdh;
8407 specified_file = image_spec_value (img->spec, QCfile, NULL);
8408 specified_data = image_spec_value (img->spec, QCdata, NULL);
8410 /* Animated gifs use QuickTime Movie Toolbox. So initialize it here. */
8411 EnterMovies ();
8413 if (NILP (specified_data))
8415 /* Read from a file */
8416 FSSpec fss;
8417 short refnum;
8419 err = find_image_fsspec (specified_file, &file, &fss);
8420 if (err != noErr)
8422 if (err == fnfErr)
8423 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8424 else
8425 goto open_error;
8428 err = CanQuickTimeOpenFile (&fss, kQTFileTypeGIF, 0,
8429 &graphic_p, &movie_p, &prefer_graphic_p, 0);
8430 if (err != noErr)
8431 goto open_error;
8433 if (!graphic_p && !movie_p)
8434 goto open_error;
8435 if (prefer_graphic_p)
8436 return image_load_qt_1 (f, img, kQTFileTypeGIF, &fss, NULL);
8437 err = OpenMovieFile (&fss, &refnum, fsRdPerm);
8438 if (err != noErr)
8439 goto open_error;
8440 err = NewMovieFromFile (&movie, refnum, NULL, NULL, 0, NULL);
8441 CloseMovieFile (refnum);
8442 if (err != noErr)
8444 image_error ("Error reading `%s'", file, Qnil);
8445 return 0;
8448 else
8450 /* Memory source! */
8451 Handle dref = NULL;
8452 long file_type_atom[3];
8454 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
8455 if (err != noErr)
8457 image_error ("Cannot allocate data handle for `%s'",
8458 img->spec, Qnil);
8459 goto error;
8462 file_type_atom[0] = EndianU32_NtoB (sizeof (long) * 3);
8463 file_type_atom[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
8464 file_type_atom[2] = EndianU32_NtoB (kQTFileTypeGIF);
8465 err = PtrToHand (&dh, &dref, sizeof (Handle));
8466 if (err == noErr)
8467 /* no file name */
8468 err = PtrAndHand ("\p", dref, 1);
8469 if (err == noErr)
8470 err = PtrAndHand (file_type_atom, dref, sizeof (long) * 3);
8471 if (err != noErr)
8473 image_error ("Cannot allocate handle data ref for `%s'", img->spec, Qnil);
8474 goto error;
8476 err = CanQuickTimeOpenDataRef (dref, HandleDataHandlerSubType, &graphic_p,
8477 &movie_p, &prefer_graphic_p, 0);
8478 if (err != noErr)
8479 goto open_error;
8481 if (!graphic_p && !movie_p)
8482 goto open_error;
8483 if (prefer_graphic_p)
8485 int success_p;
8487 DisposeHandle (dref);
8488 success_p = image_load_qt_1 (f, img, kQTFileTypeGIF, NULL, dh);
8489 DisposeHandle (dh);
8490 return success_p;
8492 err = NewMovieFromDataRef (&movie, 0, NULL, dref,
8493 HandleDataHandlerSubType);
8494 DisposeHandle (dref);
8495 if (err != noErr)
8496 goto open_error;
8499 image = image_spec_value (img->spec, QCindex, NULL);
8500 ino = INTEGERP (image) ? XFASTINT (image) : 0;
8501 track = GetMovieIndTrack (movie, 1);
8502 media = GetTrackMedia (track);
8503 nsamples = GetMediaSampleCount (media);
8504 if (ino >= nsamples)
8506 image_error ("Invalid image number `%s' in image `%s'",
8507 image, img->spec);
8508 goto error;
8510 time_scale = GetMediaTimeScale (media);
8512 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8513 if (!STRINGP (specified_bg)
8514 || !mac_defined_color (f, SDATA (specified_bg), &color, 0))
8516 color.pixel = FRAME_BACKGROUND_PIXEL (f);
8517 color.red = RED16_FROM_ULONG (color.pixel);
8518 color.green = GREEN16_FROM_ULONG (color.pixel);
8519 color.blue = BLUE16_FROM_ULONG (color.pixel);
8521 GetMovieBox (movie, &rect);
8522 width = img->width = rect.right - rect.left;
8523 height = img->height = rect.bottom - rect.top;
8524 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8525 goto error;
8527 GetGWorld (&old_port, &old_gdh);
8528 SetGWorld (ximg, NULL);
8529 bg_color.red = color.red;
8530 bg_color.green = color.green;
8531 bg_color.blue = color.blue;
8532 RGBBackColor (&bg_color);
8533 SetGWorld (old_port, old_gdh);
8534 SetMovieActive (movie, 1);
8535 SetMovieGWorld (movie, ximg, NULL);
8536 SampleNumToMediaTime (media, ino + 1, &time, &duration);
8537 SetMovieTimeValue (movie, time);
8538 MoviesTask (movie, 0L);
8539 DisposeTrackMedia (media);
8540 DisposeMovieTrack (track);
8541 DisposeMovie (movie);
8542 if (dh)
8543 DisposeHandle (dh);
8545 /* Save GIF image extension data for `image-extension-data'.
8546 Format is (count IMAGES 0xf9 GRAPHIC_CONTROL_EXTENSION_BLOCK). */
8548 Lisp_Object gce = make_uninit_string (4);
8549 int centisec = ((float)duration / time_scale) * 100.0f + 0.5f;
8551 /* Fill the delay time field. */
8552 SSET (gce, 1, centisec & 0xff);
8553 SSET (gce, 2, (centisec >> 8) & 0xff);
8554 /* We don't know about other fields. */
8555 SSET (gce, 0, 0);
8556 SSET (gce, 3, 0);
8558 img->data.lisp_val = list4 (Qcount, make_number (nsamples),
8559 make_number (0xf9), gce);
8562 /* Maybe fill in the background field while we have ximg handy. */
8563 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
8564 IMAGE_BACKGROUND (img, f, ximg);
8566 /* Put the image into the pixmap. */
8567 x_put_x_image (f, ximg, img->pixmap, width, height);
8568 x_destroy_x_image (ximg);
8569 return 1;
8571 open_error:
8572 image_error ("Cannot open `%s'", file, Qnil);
8573 error:
8574 if (media)
8575 DisposeTrackMedia (media);
8576 if (track)
8577 DisposeMovieTrack (track);
8578 if (movie)
8579 DisposeMovie (movie);
8580 if (dh)
8581 DisposeHandle (dh);
8582 return 0;
8583 #endif /* !USE_MAC_IMAGE_IO */
8585 #endif /* MAC_OS */
8587 #endif /* HAVE_GIF */
8591 /***********************************************************************
8593 ***********************************************************************/
8595 #if defined (HAVE_RSVG)
8597 /* Function prototypes. */
8599 static int svg_image_p P_ ((Lisp_Object object));
8600 static int svg_load P_ ((struct frame *f, struct image *img));
8602 static int svg_load_image P_ ((struct frame *, struct image *,
8603 unsigned char *, unsigned int));
8605 /* The symbol `svg' identifying images of this type. */
8607 Lisp_Object Qsvg;
8609 /* Indices of image specification fields in svg_format, below. */
8611 enum svg_keyword_index
8613 SVG_TYPE,
8614 SVG_DATA,
8615 SVG_FILE,
8616 SVG_ASCENT,
8617 SVG_MARGIN,
8618 SVG_RELIEF,
8619 SVG_ALGORITHM,
8620 SVG_HEURISTIC_MASK,
8621 SVG_MASK,
8622 SVG_BACKGROUND,
8623 SVG_LAST
8626 /* Vector of image_keyword structures describing the format
8627 of valid user-defined image specifications. */
8629 static struct image_keyword svg_format[SVG_LAST] =
8631 {":type", IMAGE_SYMBOL_VALUE, 1},
8632 {":data", IMAGE_STRING_VALUE, 0},
8633 {":file", IMAGE_STRING_VALUE, 0},
8634 {":ascent", IMAGE_ASCENT_VALUE, 0},
8635 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8636 {":relief", IMAGE_INTEGER_VALUE, 0},
8637 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8638 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8639 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8640 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
8643 /* Structure describing the image type `svg'. Its the same type of
8644 structure defined for all image formats, handled by emacs image
8645 functions. See struct image_type in dispextern.h. */
8647 static struct image_type svg_type =
8649 /* An identifier showing that this is an image structure for the SVG format. */
8650 &Qsvg,
8651 /* Handle to a function that can be used to identify a SVG file. */
8652 svg_image_p,
8653 /* Handle to function used to load a SVG file. */
8654 svg_load,
8655 /* Handle to function to free sresources for SVG. */
8656 x_clear_image,
8657 /* An internal field to link to the next image type in a list of
8658 image types, will be filled in when registering the format. */
8659 NULL
8663 /* Return non-zero if OBJECT is a valid SVG image specification. Do
8664 this by calling parse_image_spec and supplying the keywords that
8665 identify the SVG format. */
8667 static int
8668 svg_image_p (object)
8669 Lisp_Object object;
8671 struct image_keyword fmt[SVG_LAST];
8672 bcopy (svg_format, fmt, sizeof fmt);
8674 if (!parse_image_spec (object, fmt, SVG_LAST, Qsvg))
8675 return 0;
8677 /* Must specify either the :data or :file keyword. */
8678 return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
8681 #include <librsvg/rsvg.h>
8683 #ifdef HAVE_NTGUI
8685 /* SVG library functions. */
8686 DEF_IMGLIB_FN (rsvg_handle_new);
8687 DEF_IMGLIB_FN (rsvg_handle_set_size_callback);
8688 DEF_IMGLIB_FN (rsvg_handle_write);
8689 DEF_IMGLIB_FN (rsvg_handle_close);
8690 DEF_IMGLIB_FN (rsvg_handle_get_pixbuf);
8691 DEF_IMGLIB_FN (rsvg_handle_free);
8693 DEF_IMGLIB_FN (gdk_pixbuf_get_width);
8694 DEF_IMGLIB_FN (gdk_pixbuf_get_height);
8695 DEF_IMGLIB_FN (gdk_pixbuf_get_pixels);
8696 DEF_IMGLIB_FN (gdk_pixbuf_get_rowstride);
8697 DEF_IMGLIB_FN (gdk_pixbuf_get_colorspace);
8698 DEF_IMGLIB_FN (gdk_pixbuf_get_n_channels);
8699 DEF_IMGLIB_FN (gdk_pixbuf_get_has_alpha);
8700 DEF_IMGLIB_FN (gdk_pixbuf_get_bits_per_sample);
8702 DEF_IMGLIB_FN (g_type_init);
8703 DEF_IMGLIB_FN (g_object_unref);
8704 DEF_IMGLIB_FN (g_error_free);
8706 Lisp_Object Qgdk_pixbuf, Qglib;
8708 static int
8709 init_svg_functions (Lisp_Object libraries)
8711 HMODULE library, gdklib, glib;
8713 if (!(glib = w32_delayed_load (libraries, Qglib))
8714 || !(gdklib = w32_delayed_load (libraries, Qgdk_pixbuf))
8715 || !(library = w32_delayed_load (libraries, Qsvg)))
8716 return 0;
8718 LOAD_IMGLIB_FN (library, rsvg_handle_new);
8719 LOAD_IMGLIB_FN (library, rsvg_handle_set_size_callback);
8720 LOAD_IMGLIB_FN (library, rsvg_handle_write);
8721 LOAD_IMGLIB_FN (library, rsvg_handle_close);
8722 LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
8723 LOAD_IMGLIB_FN (library, rsvg_handle_free);
8725 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
8726 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
8727 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
8728 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
8729 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
8730 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
8731 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
8732 LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
8734 LOAD_IMGLIB_FN (glib, g_type_init);
8735 LOAD_IMGLIB_FN (glib, g_object_unref);
8736 LOAD_IMGLIB_FN (glib, g_error_free);
8737 return 1;
8740 #else
8741 /* The following aliases for library functions allow dynamic loading
8742 to be used on some platforms. */
8743 #define fn_rsvg_handle_new rsvg_handle_new
8744 #define fn_rsvg_handle_set_size_callback rsvg_handle_set_size_callback
8745 #define fn_rsvg_handle_write rsvg_handle_write
8746 #define fn_rsvg_handle_close rsvg_handle_close
8747 #define fn_rsvg_handle_get_pixbuf rsvg_handle_get_pixbuf
8748 #define fn_rsvg_handle_free rsvg_handle_free
8750 #define fn_gdk_pixbuf_get_width gdk_pixbuf_get_width
8751 #define fn_gdk_pixbuf_get_height gdk_pixbuf_get_height
8752 #define fn_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels
8753 #define fn_gdk_pixbuf_get_rowstride gdk_pixbuf_get_rowstride
8754 #define fn_gdk_pixbuf_get_colorspace gdk_pixbuf_get_colorspace
8755 #define fn_gdk_pixbuf_get_n_channels gdk_pixbuf_get_n_channels
8756 #define fn_gdk_pixbuf_get_has_alpha gdk_pixbuf_get_has_alpha
8757 #define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
8759 #define fn_g_type_init g_type_init
8760 #define fn_g_object_unref g_object_unref
8761 #define fn_g_error_free g_error_free
8762 #endif /* !HAVE_NTGUI */
8764 /* Load SVG image IMG for use on frame F. Value is non-zero if
8765 successful. this function will go into the svg_type structure, and
8766 the prototype thus needs to be compatible with that structure. */
8768 static int
8769 svg_load (f, img)
8770 struct frame *f;
8771 struct image *img;
8773 int success_p = 0;
8774 Lisp_Object file_name;
8776 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8777 file_name = image_spec_value (img->spec, QCfile, NULL);
8778 if (STRINGP (file_name))
8780 Lisp_Object file;
8781 unsigned char *contents;
8782 int size;
8783 struct gcpro gcpro1;
8785 file = x_find_image_file (file_name);
8786 GCPRO1 (file);
8787 if (!STRINGP (file))
8789 image_error ("Cannot find image file `%s'", file_name, Qnil);
8790 UNGCPRO;
8791 return 0;
8794 /* Read the entire file into memory. */
8795 contents = slurp_file (SDATA (file), &size);
8796 if (contents == NULL)
8798 image_error ("Error loading SVG image `%s'", img->spec, Qnil);
8799 UNGCPRO;
8800 return 0;
8802 /* If the file was slurped into memory properly, parse it. */
8803 success_p = svg_load_image (f, img, contents, size);
8804 xfree (contents);
8805 UNGCPRO;
8807 /* Else its not a file, its a lisp object. Load the image from a
8808 lisp object rather than a file. */
8809 else
8811 Lisp_Object data;
8813 data = image_spec_value (img->spec, QCdata, NULL);
8814 success_p = svg_load_image (f, img, SDATA (data), SBYTES (data));
8817 return success_p;
8820 /* svg_load_image is a helper function for svg_load, which does the
8821 actual loading given contents and size, apart from frame and image
8822 structures, passed from svg_load.
8824 Uses librsvg to do most of the image processing.
8826 Returns non-zero when successful. */
8827 static int
8828 svg_load_image (f, img, contents, size)
8829 /* Pointer to emacs frame structure. */
8830 struct frame *f;
8831 /* Pointer to emacs image structure. */
8832 struct image *img;
8833 /* String containing the SVG XML data to be parsed. */
8834 unsigned char *contents;
8835 /* Size of data in bytes. */
8836 unsigned int size;
8838 RsvgHandle *rsvg_handle;
8839 GError *error = NULL;
8840 GdkPixbuf *pixbuf;
8841 int width;
8842 int height;
8843 const guint8 *pixels;
8844 int rowstride;
8845 XImagePtr ximg;
8846 Lisp_Object specified_bg;
8847 XColor background;
8848 int x;
8849 int y;
8851 /* g_type_init is a glib function that must be called prior to using
8852 gnome type library functions. */
8853 fn_g_type_init ();
8854 /* Make a handle to a new rsvg object. */
8855 rsvg_handle = fn_rsvg_handle_new ();
8857 /* Parse the contents argument and fill in the rsvg_handle. */
8858 fn_rsvg_handle_write (rsvg_handle, contents, size, &error);
8859 if (error)
8860 goto rsvg_error;
8862 /* The parsing is complete, rsvg_handle is ready to used, close it
8863 for further writes. */
8864 fn_rsvg_handle_close (rsvg_handle, &error);
8865 if (error)
8866 goto rsvg_error;
8867 /* We can now get a valid pixel buffer from the svg file, if all
8868 went ok. */
8869 pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
8870 eassert (pixbuf);
8872 /* Extract some meta data from the svg handle. */
8873 width = fn_gdk_pixbuf_get_width (pixbuf);
8874 height = fn_gdk_pixbuf_get_height (pixbuf);
8875 pixels = fn_gdk_pixbuf_get_pixels (pixbuf);
8876 rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
8878 /* Validate the svg meta data. */
8879 eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
8880 eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
8881 eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
8882 eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
8884 /* Try to create a x pixmap to hold the svg pixmap. */
8885 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
8887 fn_g_object_unref (pixbuf);
8888 return 0;
8891 init_color_table ();
8893 /* Handle alpha channel by combining the image with a background
8894 color. */
8895 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
8896 if (STRINGP (specified_bg)
8897 && x_defined_color (f, SDATA (specified_bg), &background, 0))
8899 background.red >>= 8;
8900 background.green >>= 8;
8901 background.blue >>= 8;
8903 else
8905 #ifdef HAVE_X_WINDOWS
8906 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8907 x_query_color (f, &background);
8909 /* SVG pixmaps specify transparency in the last byte, so right
8910 shift 8 bits to get rid of it, since emacs doesn't support
8911 transparency. */
8912 background.red >>= 8;
8913 background.green >>= 8;
8914 background.blue >>= 8;
8915 #elif defined (MAC_OS)
8916 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8917 background.red = RED_FROM_ULONG (background.pixel);
8918 background.green = GREEN_FROM_ULONG (background.pixel);
8919 background.blue = BLUE_FROM_ULONG (background.pixel);
8920 #elif defined (HAVE_NTGUI)
8921 background.pixel = FRAME_BACKGROUND_PIXEL (f);
8922 #if 0 /* W32 TODO : Colormap support. */
8923 x_query_color (f, &background);
8924 #endif
8926 /* SVG pixmaps specify transparency in the last byte, so right
8927 shift 8 bits to get rid of it, since emacs doesn't support
8928 transparency. */
8929 background.red >>= 8;
8930 background.green >>= 8;
8931 background.blue >>= 8;
8932 #else /* not HAVE_X_WINDOWS && not MAC_OS*/
8933 #error FIXME
8934 #endif
8937 /* This loop handles opacity values, since Emacs assumes
8938 non-transparent images. Each pixel must be "flattened" by
8939 calculating the resulting color, given the transparency of the
8940 pixel, and the image background color. */
8941 for (y = 0; y < height; ++y)
8943 for (x = 0; x < width; ++x)
8945 unsigned red;
8946 unsigned green;
8947 unsigned blue;
8948 unsigned opacity;
8950 red = *pixels++;
8951 green = *pixels++;
8952 blue = *pixels++;
8953 opacity = *pixels++;
8955 red = ((red * opacity)
8956 + (background.red * ((1 << 8) - opacity)));
8957 green = ((green * opacity)
8958 + (background.green * ((1 << 8) - opacity)));
8959 blue = ((blue * opacity)
8960 + (background.blue * ((1 << 8) - opacity)));
8962 XPutPixel (ximg, x, y, lookup_rgb_color (f, red, green, blue));
8965 pixels += rowstride - 4 * width;
8968 #ifdef COLOR_TABLE_SUPPORT
8969 /* Remember colors allocated for this image. */
8970 img->colors = colors_in_color_table (&img->ncolors);
8971 free_color_table ();
8972 #endif /* COLOR_TABLE_SUPPORT */
8974 fn_g_object_unref (pixbuf);
8976 img->width = width;
8977 img->height = height;
8979 /* Maybe fill in the background field while we have ximg handy.
8980 Casting avoids a GCC warning. */
8981 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
8983 /* Put the image into the pixmap, then free the X image and its
8984 buffer. */
8985 x_put_x_image (f, ximg, img->pixmap, width, height);
8986 x_destroy_x_image (ximg);
8988 return 1;
8990 rsvg_error:
8991 /* FIXME: Use error->message so the user knows what is the actual
8992 problem with the image. */
8993 image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
8994 fn_g_error_free (error);
8995 return 0;
8998 #endif /* defined (HAVE_RSVG) */
9003 /***********************************************************************
9004 Ghostscript
9005 ***********************************************************************/
9007 #ifdef HAVE_X_WINDOWS
9008 #define HAVE_GHOSTSCRIPT 1
9009 #endif /* HAVE_X_WINDOWS */
9011 /* The symbol `postscript' identifying images of this type. */
9013 Lisp_Object Qpostscript;
9015 #ifdef HAVE_GHOSTSCRIPT
9017 static int gs_image_p P_ ((Lisp_Object object));
9018 static int gs_load P_ ((struct frame *f, struct image *img));
9019 static void gs_clear_image P_ ((struct frame *f, struct image *img));
9021 /* Keyword symbols. */
9023 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
9025 /* Indices of image specification fields in gs_format, below. */
9027 enum gs_keyword_index
9029 GS_TYPE,
9030 GS_PT_WIDTH,
9031 GS_PT_HEIGHT,
9032 GS_FILE,
9033 GS_LOADER,
9034 GS_BOUNDING_BOX,
9035 GS_ASCENT,
9036 GS_MARGIN,
9037 GS_RELIEF,
9038 GS_ALGORITHM,
9039 GS_HEURISTIC_MASK,
9040 GS_MASK,
9041 GS_BACKGROUND,
9042 GS_LAST
9045 /* Vector of image_keyword structures describing the format
9046 of valid user-defined image specifications. */
9048 static struct image_keyword gs_format[GS_LAST] =
9050 {":type", IMAGE_SYMBOL_VALUE, 1},
9051 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9052 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
9053 {":file", IMAGE_STRING_VALUE, 1},
9054 {":loader", IMAGE_FUNCTION_VALUE, 0},
9055 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
9056 {":ascent", IMAGE_ASCENT_VALUE, 0},
9057 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9058 {":relief", IMAGE_INTEGER_VALUE, 0},
9059 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9060 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9061 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9062 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9065 /* Structure describing the image type `ghostscript'. */
9067 static struct image_type gs_type =
9069 &Qpostscript,
9070 gs_image_p,
9071 gs_load,
9072 gs_clear_image,
9073 NULL
9077 /* Free X resources of Ghostscript image IMG which is used on frame F. */
9079 static void
9080 gs_clear_image (f, img)
9081 struct frame *f;
9082 struct image *img;
9084 /* IMG->data.ptr_val may contain a recorded colormap. */
9085 xfree (img->data.ptr_val);
9086 x_clear_image (f, img);
9090 /* Return non-zero if OBJECT is a valid Ghostscript image
9091 specification. */
9093 static int
9094 gs_image_p (object)
9095 Lisp_Object object;
9097 struct image_keyword fmt[GS_LAST];
9098 Lisp_Object tem;
9099 int i;
9101 bcopy (gs_format, fmt, sizeof fmt);
9103 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
9104 return 0;
9106 /* Bounding box must be a list or vector containing 4 integers. */
9107 tem = fmt[GS_BOUNDING_BOX].value;
9108 if (CONSP (tem))
9110 for (i = 0; i < 4; ++i, tem = XCDR (tem))
9111 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
9112 return 0;
9113 if (!NILP (tem))
9114 return 0;
9116 else if (VECTORP (tem))
9118 if (XVECTOR (tem)->size != 4)
9119 return 0;
9120 for (i = 0; i < 4; ++i)
9121 if (!INTEGERP (XVECTOR (tem)->contents[i]))
9122 return 0;
9124 else
9125 return 0;
9127 return 1;
9131 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
9132 if successful. */
9134 static int
9135 gs_load (f, img)
9136 struct frame *f;
9137 struct image *img;
9139 char buffer[100];
9140 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
9141 struct gcpro gcpro1, gcpro2;
9142 Lisp_Object frame;
9143 double in_width, in_height;
9144 Lisp_Object pixel_colors = Qnil;
9146 /* Compute pixel size of pixmap needed from the given size in the
9147 image specification. Sizes in the specification are in pt. 1 pt
9148 = 1/72 in, xdpi and ydpi are stored in the frame's X display
9149 info. */
9150 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
9151 in_width = XFASTINT (pt_width) / 72.0;
9152 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
9153 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
9154 in_height = XFASTINT (pt_height) / 72.0;
9155 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
9157 if (!check_image_size (f, img->width, img->height))
9159 image_error ("Invalid image size", Qnil, Qnil);
9160 return 0;
9163 /* Create the pixmap. */
9164 xassert (img->pixmap == NO_PIXMAP);
9166 /* Only W32 version did BLOCK_INPUT here. ++kfs */
9167 BLOCK_INPUT;
9168 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
9169 img->width, img->height,
9170 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
9171 UNBLOCK_INPUT;
9173 if (!img->pixmap)
9175 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
9176 return 0;
9179 /* Call the loader to fill the pixmap. It returns a process object
9180 if successful. We do not record_unwind_protect here because
9181 other places in redisplay like calling window scroll functions
9182 don't either. Let the Lisp loader use `unwind-protect' instead. */
9183 GCPRO2 (window_and_pixmap_id, pixel_colors);
9185 sprintf (buffer, "%lu %lu",
9186 (unsigned long) FRAME_X_WINDOW (f),
9187 (unsigned long) img->pixmap);
9188 window_and_pixmap_id = build_string (buffer);
9190 sprintf (buffer, "%lu %lu",
9191 FRAME_FOREGROUND_PIXEL (f),
9192 FRAME_BACKGROUND_PIXEL (f));
9193 pixel_colors = build_string (buffer);
9195 XSETFRAME (frame, f);
9196 loader = image_spec_value (img->spec, QCloader, NULL);
9197 if (NILP (loader))
9198 loader = intern ("gs-load-image");
9200 img->data.lisp_val = call6 (loader, frame, img->spec,
9201 make_number (img->width),
9202 make_number (img->height),
9203 window_and_pixmap_id,
9204 pixel_colors);
9205 UNGCPRO;
9206 return PROCESSP (img->data.lisp_val);
9210 /* Kill the Ghostscript process that was started to fill PIXMAP on
9211 frame F. Called from XTread_socket when receiving an event
9212 telling Emacs that Ghostscript has finished drawing. */
9214 void
9215 x_kill_gs_process (pixmap, f)
9216 Pixmap pixmap;
9217 struct frame *f;
9219 struct image_cache *c = FRAME_IMAGE_CACHE (f);
9220 int class, i;
9221 struct image *img;
9223 /* Find the image containing PIXMAP. */
9224 for (i = 0; i < c->used; ++i)
9225 if (c->images[i]->pixmap == pixmap)
9226 break;
9228 /* Should someone in between have cleared the image cache, for
9229 instance, give up. */
9230 if (i == c->used)
9231 return;
9233 /* Kill the GS process. We should have found PIXMAP in the image
9234 cache and its image should contain a process object. */
9235 img = c->images[i];
9236 xassert (PROCESSP (img->data.lisp_val));
9237 Fkill_process (img->data.lisp_val, Qnil);
9238 img->data.lisp_val = Qnil;
9240 #if defined (HAVE_X_WINDOWS)
9242 /* On displays with a mutable colormap, figure out the colors
9243 allocated for the image by looking at the pixels of an XImage for
9244 img->pixmap. */
9245 class = FRAME_X_VISUAL (f)->class;
9246 if (class != StaticColor && class != StaticGray && class != TrueColor)
9248 XImagePtr ximg;
9250 BLOCK_INPUT;
9252 /* Try to get an XImage for img->pixmep. */
9253 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
9254 0, 0, img->width, img->height, ~0, ZPixmap);
9255 if (ximg)
9257 int x, y;
9259 /* Initialize the color table. */
9260 init_color_table ();
9262 /* For each pixel of the image, look its color up in the
9263 color table. After having done so, the color table will
9264 contain an entry for each color used by the image. */
9265 for (y = 0; y < img->height; ++y)
9266 for (x = 0; x < img->width; ++x)
9268 unsigned long pixel = XGetPixel (ximg, x, y);
9269 lookup_pixel_color (f, pixel);
9272 /* Record colors in the image. Free color table and XImage. */
9273 #ifdef COLOR_TABLE_SUPPORT
9274 img->colors = colors_in_color_table (&img->ncolors);
9275 free_color_table ();
9276 #endif
9277 XDestroyImage (ximg);
9279 #if 0 /* This doesn't seem to be the case. If we free the colors
9280 here, we get a BadAccess later in x_clear_image when
9281 freeing the colors. */
9282 /* We have allocated colors once, but Ghostscript has also
9283 allocated colors on behalf of us. So, to get the
9284 reference counts right, free them once. */
9285 if (img->ncolors)
9286 x_free_colors (f, img->colors, img->ncolors);
9287 #endif
9289 else
9290 image_error ("Cannot get X image of `%s'; colors will not be freed",
9291 img->spec, Qnil);
9293 UNBLOCK_INPUT;
9295 #endif /* HAVE_X_WINDOWS */
9297 /* Now that we have the pixmap, compute mask and transform the
9298 image if requested. */
9299 BLOCK_INPUT;
9300 postprocess_image (f, img);
9301 UNBLOCK_INPUT;
9304 #endif /* HAVE_GHOSTSCRIPT */
9307 /***********************************************************************
9308 Tests
9309 ***********************************************************************/
9311 #if GLYPH_DEBUG
9313 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
9314 doc: /* Value is non-nil if SPEC is a valid image specification. */)
9315 (spec)
9316 Lisp_Object spec;
9318 return valid_image_p (spec) ? Qt : Qnil;
9322 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
9323 (spec)
9324 Lisp_Object spec;
9326 int id = -1;
9328 if (valid_image_p (spec))
9329 id = lookup_image (SELECTED_FRAME (), spec);
9331 debug_print (spec);
9332 return make_number (id);
9335 #endif /* GLYPH_DEBUG != 0 */
9338 /***********************************************************************
9339 Initialization
9340 ***********************************************************************/
9342 #ifdef HAVE_NTGUI
9343 /* Image types that rely on external libraries are loaded dynamically
9344 if the library is available. */
9345 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
9346 define_image_type (image_type, init_lib_fn (libraries))
9347 #else
9348 #define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
9349 define_image_type (image_type, 1)
9350 #endif /* HAVE_NTGUI */
9352 DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
9353 doc: /* Initialize image library implementing image type TYPE.
9354 Return non-nil if TYPE is a supported image type.
9356 Image types pbm and xbm are prebuilt; other types are loaded here.
9357 Libraries to load are specified in alist LIBRARIES (usually, the value
9358 of `image-library-alist', which see). */)
9359 (type, libraries)
9360 Lisp_Object type, libraries;
9362 Lisp_Object tested;
9364 /* Don't try to reload the library. */
9365 tested = Fassq (type, Vimage_type_cache);
9366 if (CONSP (tested))
9367 return XCDR (tested);
9369 #if defined (HAVE_XPM) || defined (MAC_OS)
9370 if (EQ (type, Qxpm))
9371 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
9372 #endif
9374 #if defined (HAVE_JPEG) || defined (MAC_OS)
9375 if (EQ (type, Qjpeg))
9376 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
9377 #endif
9379 #if defined (HAVE_TIFF) || defined (MAC_OS)
9380 if (EQ (type, Qtiff))
9381 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
9382 #endif
9384 #if defined (HAVE_GIF) || defined (MAC_OS)
9385 if (EQ (type, Qgif))
9386 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
9387 #endif
9389 #if defined (HAVE_PNG) || defined (MAC_OS)
9390 if (EQ (type, Qpng))
9391 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
9392 #endif
9394 #if defined (HAVE_RSVG)
9395 if (EQ (type, Qsvg))
9396 return CHECK_LIB_AVAILABLE (&svg_type, init_svg_functions, libraries);
9397 #endif
9399 #ifdef HAVE_GHOSTSCRIPT
9400 if (EQ (type, Qpostscript))
9401 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
9402 #endif
9404 /* If the type is not recognized, avoid testing it ever again. */
9405 CACHE_IMAGE_TYPE (type, Qnil);
9406 return Qnil;
9409 void
9410 syms_of_image ()
9412 extern Lisp_Object Qrisky_local_variable; /* Syms_of_xdisp has already run. */
9414 /* Initialize this only once, since that's what we do with Vimage_types
9415 and they are supposed to be in sync. Initializing here gives correct
9416 operation on GNU/Linux of calling dump-emacs after loading some images. */
9417 image_types = NULL;
9419 /* Must be defined now becase we're going to update it below, while
9420 defining the supported image types. */
9421 DEFVAR_LISP ("image-types", &Vimage_types,
9422 doc: /* List of potentially supported image types.
9423 Each element of the list is a symbol for an image type, like 'jpeg or 'png.
9424 To check whether it is really supported, use `image-type-available-p'. */);
9425 Vimage_types = Qnil;
9427 DEFVAR_LISP ("image-library-alist", &Vimage_library_alist,
9428 doc: /* Alist of image types vs external libraries needed to display them.
9430 Each element is a list (IMAGE-TYPE LIBRARY...), where the car is a symbol
9431 representing a supported image type, and the rest are strings giving
9432 alternate filenames for the corresponding external libraries.
9434 Emacs tries to load the libraries in the order they appear on the
9435 list; if none is loaded, the running session of Emacs won't
9436 support the image type. Types 'pbm and 'xbm don't need to be
9437 listed; they are always supported. */);
9438 Vimage_library_alist = Qnil;
9439 Fput (intern ("image-library-alist"), Qrisky_local_variable, Qt);
9441 DEFVAR_LISP ("max-image-size", &Vmax_image_size,
9442 doc: /* Maximum size of images.
9443 Emacs will not load an image into memory if its pixel width or
9444 pixel height exceeds this limit.
9446 If the value is an integer, it directly specifies the maximum
9447 image height and width, measured in pixels. If it is a floating
9448 point number, it specifies the maximum image height and width
9449 as a ratio to the frame height and width. If the value is
9450 non-numeric, there is no explicit limit on the size of images. */);
9451 Vmax_image_size = make_float (MAX_IMAGE_SIZE);
9453 Vimage_type_cache = Qnil;
9454 staticpro (&Vimage_type_cache);
9456 Qpbm = intern ("pbm");
9457 staticpro (&Qpbm);
9458 ADD_IMAGE_TYPE (Qpbm);
9460 Qxbm = intern ("xbm");
9461 staticpro (&Qxbm);
9462 ADD_IMAGE_TYPE (Qxbm);
9464 define_image_type (&xbm_type, 1);
9465 define_image_type (&pbm_type, 1);
9467 Qcount = intern ("count");
9468 staticpro (&Qcount);
9470 QCascent = intern (":ascent");
9471 staticpro (&QCascent);
9472 QCmargin = intern (":margin");
9473 staticpro (&QCmargin);
9474 QCrelief = intern (":relief");
9475 staticpro (&QCrelief);
9476 QCconversion = intern (":conversion");
9477 staticpro (&QCconversion);
9478 QCcolor_symbols = intern (":color-symbols");
9479 staticpro (&QCcolor_symbols);
9480 QCheuristic_mask = intern (":heuristic-mask");
9481 staticpro (&QCheuristic_mask);
9482 QCindex = intern (":index");
9483 staticpro (&QCindex);
9484 QCmatrix = intern (":matrix");
9485 staticpro (&QCmatrix);
9486 QCcolor_adjustment = intern (":color-adjustment");
9487 staticpro (&QCcolor_adjustment);
9488 QCmask = intern (":mask");
9489 staticpro (&QCmask);
9491 Qlaplace = intern ("laplace");
9492 staticpro (&Qlaplace);
9493 Qemboss = intern ("emboss");
9494 staticpro (&Qemboss);
9495 Qedge_detection = intern ("edge-detection");
9496 staticpro (&Qedge_detection);
9497 Qheuristic = intern ("heuristic");
9498 staticpro (&Qheuristic);
9500 Qpostscript = intern ("postscript");
9501 staticpro (&Qpostscript);
9502 #ifdef HAVE_GHOSTSCRIPT
9503 ADD_IMAGE_TYPE (Qpostscript);
9504 QCloader = intern (":loader");
9505 staticpro (&QCloader);
9506 QCbounding_box = intern (":bounding-box");
9507 staticpro (&QCbounding_box);
9508 QCpt_width = intern (":pt-width");
9509 staticpro (&QCpt_width);
9510 QCpt_height = intern (":pt-height");
9511 staticpro (&QCpt_height);
9512 #endif /* HAVE_GHOSTSCRIPT */
9514 #if defined (HAVE_XPM) || defined (MAC_OS)
9515 Qxpm = intern ("xpm");
9516 staticpro (&Qxpm);
9517 ADD_IMAGE_TYPE (Qxpm);
9518 #endif
9520 #if defined (HAVE_JPEG) || defined (MAC_OS)
9521 Qjpeg = intern ("jpeg");
9522 staticpro (&Qjpeg);
9523 ADD_IMAGE_TYPE (Qjpeg);
9524 #endif
9526 #if defined (HAVE_TIFF) || defined (MAC_OS)
9527 Qtiff = intern ("tiff");
9528 staticpro (&Qtiff);
9529 ADD_IMAGE_TYPE (Qtiff);
9530 #endif
9532 #if defined (HAVE_GIF) || defined (MAC_OS)
9533 Qgif = intern ("gif");
9534 staticpro (&Qgif);
9535 ADD_IMAGE_TYPE (Qgif);
9536 #endif
9538 #if defined (HAVE_PNG) || defined (MAC_OS)
9539 Qpng = intern ("png");
9540 staticpro (&Qpng);
9541 ADD_IMAGE_TYPE (Qpng);
9542 #endif
9544 #if defined (HAVE_RSVG)
9545 Qsvg = intern ("svg");
9546 staticpro (&Qsvg);
9547 ADD_IMAGE_TYPE (Qsvg);
9548 #ifdef HAVE_NTGUI
9549 Qgdk_pixbuf = intern ("gdk-pixbuf");
9550 staticpro (&Qgdk_pixbuf);
9551 Qglib = intern ("glib");
9552 staticpro (&Qglib);
9553 #endif /* HAVE_NTGUI */
9554 #endif /* HAVE_RSVG */
9556 defsubr (&Sinit_image_library);
9557 defsubr (&Sclear_image_cache);
9558 defsubr (&Simage_refresh);
9559 defsubr (&Simage_size);
9560 defsubr (&Simage_mask_p);
9561 defsubr (&Simage_extension_data);
9563 #if GLYPH_DEBUG
9564 defsubr (&Simagep);
9565 defsubr (&Slookup_image);
9566 #endif
9568 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
9569 doc: /* Non-nil means always draw a cross over disabled images.
9570 Disabled images are those having a `:conversion disabled' property.
9571 A cross is always drawn on black & white displays. */);
9572 cross_disabled_images = 0;
9574 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
9575 doc: /* List of directories to search for window system bitmap files. */);
9576 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
9578 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
9579 doc: /* Time after which cached images are removed from the cache.
9580 When an image has not been displayed this many seconds, remove it
9581 from the image cache. Value must be an integer or nil with nil
9582 meaning don't clear the cache. */);
9583 Vimage_cache_eviction_delay = make_number (30 * 60);
9586 void
9587 init_image ()
9591 /* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
9592 (do not change this comment) */